From d4d8e582f939aa40fe416bd2f91949660f15e479 Mon Sep 17 00:00:00 2001 From: Pradeep AgrawaL Date: Tue, 31 Dec 2024 21:06:49 +0530 Subject: [PATCH 01/15] RANGER-5061: checkstyle compliance : security-admin module --- security-admin/pom.xml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/security-admin/pom.xml b/security-admin/pom.xml index 4245f9c1ef..db17552c45 100644 --- a/security-admin/pom.xml +++ b/security-admin/pom.xml @@ -27,6 +27,9 @@ Security Admin Web Application security-admin-tool java web application + true + false + UTF-8 false From d149d1a9d8f0ccb37a98b98576e6ba7a68b587ec Mon Sep 17 00:00:00 2001 From: Abhishek Kumar Date: Thu, 2 Jan 2025 01:56:22 -0800 Subject: [PATCH 02/15] RANGER-5061: checkstyle compliance updates - security-admin module - all unit tests (#484) --- .../apache/ranger/audit/TestAuditQueue.java | 1665 ++- .../org/apache/ranger/audit/TestConsumer.java | 358 +- .../AmazonCloudWatchAuditDestinationTest.java | 10 +- .../apache/ranger/biz/TestPolicyAdmin.java | 223 +- .../org/apache/ranger/biz/TestPolicyDb.java | 202 +- .../apache/ranger/biz/TestRangerBizUtil.java | 1083 +- .../apache/ranger/biz/TestRoleDBStore.java | 132 +- .../ranger/biz/TestSecurityZoneDBStore.java | 575 +- .../apache/ranger/biz/TestServiceDBStore.java | 5015 +++++---- .../org/apache/ranger/biz/TestTagDBStore.java | 392 +- .../org/apache/ranger/biz/TestUserMgr.java | 4341 ++++---- .../org/apache/ranger/biz/TestXUserMgr.java | 9172 ++++++++--------- .../apache/ranger/common/TestContextUtil.java | 137 +- .../apache/ranger/common/TestDateUtil.java | 245 +- .../apache/ranger/common/TestJSONUtil.java | 164 +- .../ranger/common/TestPropertiesUtil.java | 208 +- .../ranger/common/TestRangerConfigUtil.java | 49 +- .../ranger/common/TestRangerSearchUtil.java | 214 +- .../apache/ranger/common/TestServiceUtil.java | 3607 ++++--- .../apache/ranger/common/TestStringUtil.java | 326 +- .../ranger/common/TestTimedExecutor.java | 297 +- ...ngerTransactionSynchronizationAdapter.java | 2 - .../ElasticSearchAccessAuditsServiceTest.java | 54 +- .../cliutil/TestRoleBasedUserSearchUtil.java | 91 +- .../org/apache/ranger/rest/TestAssetREST.java | 1684 ++- .../org/apache/ranger/rest/TestGdsREST.java | 307 +- .../apache/ranger/rest/TestMetricsREST.java | 17 +- .../apache/ranger/rest/TestPublicAPIs.java | 822 +- .../apache/ranger/rest/TestPublicAPIsv2.java | 1174 +-- .../ranger/rest/TestRangerHealthREST.java | 35 +- .../org/apache/ranger/rest/TestRoleREST.java | 1434 ++- .../ranger/rest/TestSecurityZoneREST.java | 465 +- .../apache/ranger/rest/TestServiceREST.java | 5151 +++++---- .../ranger/rest/TestServiceTagProcessor.java | 487 +- .../org/apache/ranger/rest/TestTagREST.java | 3897 ++++--- .../org/apache/ranger/rest/TestUserREST.java | 816 +- .../apache/ranger/rest/TestXAuditREST.java | 327 +- .../org/apache/ranger/rest/TestXKeyREST.java | 274 +- .../org/apache/ranger/rest/TestXUserREST.java | 4292 ++++---- .../TestRangerCSRFPreventionFilter.java | 306 +- .../web/filter/TestRangerMDCFilter.java | 9 +- .../PasswordComparisonAuthenticator.java | 193 +- .../service/TestAuthSessionService.java | 116 +- .../ranger/service/TestRangerAuditFields.java | 53 +- .../service/TestRangerDataHistService.java | 64 +- .../service/TestRangerPolicyService.java | 231 +- .../service/TestRangerPolicyServiceBase.java | 361 +- .../service/TestRangerServiceDefService.java | 1461 ++- .../TestRangerServiceDefServiceBase.java | 1279 +-- .../service/TestRangerServiceService.java | 711 +- .../service/TestRangerServiceServiceBase.java | 312 +- ...estRangerServiceWithAssignedIdService.java | 132 +- .../service/TestRangerTagDefService.java | 384 +- .../service/TestRangerTagDefServiceBase.java | 69 +- .../TestRangerTagResourceMapService.java | 179 +- .../ranger/service/TestRangerTagService.java | 194 +- .../service/TestRangerTransactionService.java | 44 +- .../ranger/service/TestUserService.java | 39 +- .../service/TestXAccessAuditService.java | 105 +- .../ranger/service/TestXAssetService.java | 133 +- .../ranger/service/TestXAuditMapService.java | 30 +- .../service/TestXGroupPermissionService.java | 44 +- .../ranger/service/TestXGroupService.java | 249 +- .../ranger/service/TestXGroupUserService.java | 294 +- .../ranger/service/TestXPermMapService.java | 319 +- .../filter/TestRangerRESTAPIFilter.java | 22 +- .../java/org/apache/ranger/util/BaseTest.java | 117 +- .../ranger/util/TestRangerEnumUtil.java | 191 +- .../ranger/util/TestRangerMetricsUtil.java | 9 +- .../util/TestRangerServerHealthUtil.java | 9 +- 70 files changed, 27935 insertions(+), 29468 deletions(-) diff --git a/security-admin/src/test/java/org/apache/ranger/audit/TestAuditQueue.java b/security-admin/src/test/java/org/apache/ranger/audit/TestAuditQueue.java index aef14a987d..c627be87c8 100644 --- a/security-admin/src/test/java/org/apache/ranger/audit/TestAuditQueue.java +++ b/security-admin/src/test/java/org/apache/ranger/audit/TestAuditQueue.java @@ -17,20 +17,8 @@ * under the License. */ - package org.apache.ranger.audit; -import static org.junit.Assert.*; - -import java.io.*; -import java.nio.file.Files; -import java.nio.file.Paths; -import java.time.LocalDate; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Properties; - import org.apache.commons.io.FileUtils; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; @@ -39,7 +27,11 @@ import org.apache.ranger.audit.destination.FileAuditDestination; import org.apache.ranger.audit.model.AuditIndexRecord; import org.apache.ranger.audit.model.AuthzAuditEvent; -import org.apache.ranger.audit.provider.*; +import org.apache.ranger.audit.provider.AuditHandler; +import org.apache.ranger.audit.provider.AuditProviderFactory; +import org.apache.ranger.audit.provider.BaseAuditHandler; +import org.apache.ranger.audit.provider.MiscUtil; +import org.apache.ranger.audit.provider.MultiDestAuditProvider; import org.apache.ranger.audit.queue.AuditAsyncQueue; import org.apache.ranger.audit.queue.AuditBatchQueue; import org.apache.ranger.audit.queue.AuditFileSpool; @@ -51,887 +43,770 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -public class TestAuditQueue { +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.time.LocalDate; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Properties; - private static final Logger logger = LoggerFactory.getLogger(TestAuditQueue.class); - - @BeforeClass - public static void setUpBeforeClass() throws Exception { - } - - @AfterClass - public static void tearDownAfterClass() throws Exception { - } - - static private int seqNum = 0; - - @Test - public void testAuditAsyncQueue() { - logger.debug("testAuditAsyncQueue()..."); - TestConsumer testConsumer = new TestConsumer(); - AuditAsyncQueue queue = new AuditAsyncQueue(testConsumer); - Properties props = new Properties(); - queue.init(props); - - queue.start(); - - int messageToSend = 10; - for (int i = 0; i < messageToSend; i++) { - queue.log(createEvent()); - } - queue.stop(); - queue.waitToComplete(); - // Let's wait for second - try { - Thread.sleep(1000); - } catch (InterruptedException e) { - // ignore - } - assertEquals(messageToSend, testConsumer.getCountTotal()); - assertEquals(messageToSend, testConsumer.getSumTotal()); - assertNull("Event not in sequnce", testConsumer.isInSequence()); - } - - @Test - public void testAuditSummaryQueue() { - logger.debug("testAuditSummaryQueue()..."); - TestConsumer testConsumer = new TestConsumer(); - AuditSummaryQueue queue = new AuditSummaryQueue(testConsumer); - - Properties props = new Properties(); - props.put(BaseAuditHandler.PROP_DEFAULT_PREFIX + "." - + AuditSummaryQueue.PROP_SUMMARY_INTERVAL, "" + 300); - queue.init(props, BaseAuditHandler.PROP_DEFAULT_PREFIX); - - queue.start(); - - commonTestSummary(testConsumer, queue); - } - - private void commonTestSummary(TestConsumer testConsumer, - BaseAuditHandler queue) { - int messageToSend = 0; - int pauseMS = 330; - - int countToCheck = 0; - try { - - queue.log(createEvent("john", "select", - "xademo/customer_details/imei", true)); - messageToSend++; - queue.log(createEvent("john", "select", - "xademo/customer_details/imei", true)); - messageToSend++; - countToCheck++; - queue.log(createEvent("jane", "select", - "xademo/customer_details/imei", true)); - messageToSend++; - countToCheck++; - Thread.sleep(pauseMS); - - queue.log(createEvent("john", "select", - "xademo/customer_details/imei", true)); - messageToSend++; - queue.log(createEvent("john", "select", - "xademo/customer_details/imei", true)); - messageToSend++; - countToCheck++; - queue.log(createEvent("jane", "select", - "xademo/customer_details/imei", true)); - messageToSend++; - countToCheck++; - Thread.sleep(pauseMS); - - queue.log(createEvent("john", "select", - "xademo/customer_details/imei", true)); - messageToSend++; - countToCheck++; - queue.log(createEvent("john", "select", - "xademo/customer_details/imei", false)); - messageToSend++; - countToCheck++; - queue.log(createEvent("jane", "select", - "xademo/customer_details/imei", true)); - messageToSend++; - countToCheck++; - Thread.sleep(pauseMS); - - } catch (InterruptedException e1) { - logger.error("Sleep interupted", e1); - } - // Let's wait for second - try { - Thread.sleep(1000); - } catch (InterruptedException e) { - // ignore - } - - queue.waitToComplete(); - queue.stop(); - queue.waitToComplete(); - // Let's wait for second - try { - Thread.sleep(1000); - } catch (InterruptedException e) { - // ignore - } - assertEquals(messageToSend, testConsumer.getSumTotal()); - assertEquals(countToCheck, testConsumer.getCountTotal()); - } - - @Test - public void testAuditSummaryByInfra() { - logger.debug("testAuditSummaryByInfra()..."); - - Properties props = new Properties(); - // Destination - String propPrefix = AuditProviderFactory.AUDIT_DEST_BASE + ".test"; - props.put(propPrefix, "enable"); - props.put(BaseAuditHandler.PROP_DEFAULT_PREFIX + "." + "summary" + "." - + "enabled", "true"); - props.put(propPrefix + "." + BaseAuditHandler.PROP_NAME, "test"); - props.put(propPrefix + "." + AuditQueue.PROP_QUEUE, "none"); - - props.put(BaseAuditHandler.PROP_DEFAULT_PREFIX + "." - + AuditSummaryQueue.PROP_SUMMARY_INTERVAL, "" + 300); - props.put(propPrefix + "." + BaseAuditHandler.PROP_CLASS_NAME, - TestConsumer.class.getName()); - - AuditProviderFactory factory = AuditProviderFactory.getInstance(); - factory.init(props, "test"); - AuditQueue queue = (AuditQueue) factory.getAuditProvider(); - BaseAuditHandler consumer = (BaseAuditHandler) queue.getConsumer(); - while (consumer != null && consumer instanceof AuditQueue) { - AuditQueue cQueue = (AuditQueue) consumer; - consumer = (BaseAuditHandler) cQueue.getConsumer(); - } - assertTrue("Consumer should be TestConsumer. class=" - + consumer.getClass().getName(), - consumer instanceof TestConsumer); - TestConsumer testConsumer = (TestConsumer) consumer; - commonTestSummary(testConsumer, queue); - } - - @Test - public void testMultipleQueue() { - logger.debug("testAuditAsyncQueue()..."); - int destCount = 3; - TestConsumer[] testConsumer = new TestConsumer[destCount]; - - MultiDestAuditProvider multiQueue = new MultiDestAuditProvider(); - for (int i = 0; i < destCount; i++) { - testConsumer[i] = new TestConsumer(); - multiQueue.addAuditProvider(testConsumer[i]); - } - - AuditAsyncQueue queue = new AuditAsyncQueue(multiQueue); - Properties props = new Properties(); - queue.init(props); - queue.start(); - - int messageToSend = 10; - for (int i = 0; i < messageToSend; i++) { - queue.log(createEvent()); - } - queue.stop(); - queue.waitToComplete(); - // Let's wait for second - try { - Thread.sleep(1000); - } catch (InterruptedException e) { - // ignore - } - for (int i = 0; i < destCount; i++) { - assertEquals("consumer" + i, messageToSend, - testConsumer[i].getCountTotal()); - assertEquals("consumer" + i, messageToSend, - testConsumer[i].getSumTotal()); - - } - } - - @Test - public void testAuditBatchQueueBySize() { - logger.debug("testAuditBatchQueue()..."); - int messageToSend = 10; - - String basePropName = "testAuditBatchQueueBySize_" - + MiscUtil.generateUniqueId(); - int batchSize = messageToSend / 3; - int expectedBatchSize = batchSize - + (batchSize * 3 < messageToSend ? 1 : 0); - int queueSize = batchSize * 2; - int intervalMS = messageToSend * 100; // Deliberately big interval - Properties props = new Properties(); - props.put(basePropName + "." + AuditQueue.PROP_BATCH_SIZE, "" - + batchSize); - props.put(basePropName + "." + AuditQueue.PROP_QUEUE_SIZE, "" - + queueSize); - props.put(basePropName + "." + AuditQueue.PROP_BATCH_INTERVAL, "" - + intervalMS); - - TestConsumer testConsumer = new TestConsumer(); - AuditBatchQueue queue = new AuditBatchQueue(testConsumer); - queue.init(props, basePropName); - queue.start(); - - for (int i = 0; i < messageToSend; i++) { - queue.log(createEvent()); - - } - // Let's wait for second - try { - Thread.sleep(2000); - } catch (InterruptedException e) { - // ignore - } - - queue.waitToComplete(); - queue.stop(); - queue.waitToComplete(); - - assertEquals("Total count", messageToSend, testConsumer.getCountTotal()); - assertEquals("Total sum", messageToSend, testConsumer.getSumTotal()); - assertEquals("Total batch", expectedBatchSize, - testConsumer.getBatchCount()); - assertNull("Event not in sequnce", testConsumer.isInSequence()); - - } - - @Test - public void testAuditBatchQueueByTime() { - logger.debug("testAuditBatchQueue()..."); - - int messageToSend = 10; - - String basePropName = "testAuditBatchQueueByTime_" - + MiscUtil.generateUniqueId(); - int batchSize = messageToSend * 2; // Deliberately big size - int queueSize = messageToSend * 2; - int intervalMS = (1000 / messageToSend) * 3; // e.g (1000/10 * 3) = 300 - // ms - int pauseMS = 1000 / messageToSend + 3; // e.g. 1000/10 + 3 = 103ms - int expectedBatchSize = (messageToSend * pauseMS) / intervalMS + 1; - - Properties props = new Properties(); - props.put(basePropName + "." + AuditQueue.PROP_BATCH_SIZE, "" - + batchSize); - props.put(basePropName + "." + AuditQueue.PROP_QUEUE_SIZE, "" - + queueSize); - props.put(basePropName + "." + AuditQueue.PROP_BATCH_INTERVAL, "" - + intervalMS); - - TestConsumer testConsumer = new TestConsumer(); - AuditBatchQueue queue = new AuditBatchQueue(testConsumer); - queue.init(props, basePropName); - queue.start(); - - for (int i = 0; i < messageToSend; i++) { - queue.log(createEvent()); - try { - Thread.sleep(pauseMS); - } catch (InterruptedException e) { - // ignore - } - } - // Let's wait for second - try { - Thread.sleep(2000); - } catch (InterruptedException e) { - // ignore - } - queue.waitToComplete(); - queue.stop(); - queue.waitToComplete(); - - assertEquals("Total count", messageToSend, testConsumer.getCountTotal()); - assertEquals("Total sum", messageToSend, testConsumer.getSumTotal()); - assertEquals("Total batch", expectedBatchSize, - testConsumer.getBatchCount()); - assertNull("Event not in sequnce", testConsumer.isInSequence()); - } - - @Test - public void testAuditBatchQueueDestDown() { - logger.debug("testAuditBatchQueueDestDown()..."); - int messageToSend = 10; - - String basePropName = "testAuditBatchQueueDestDown_" - + MiscUtil.generateUniqueId(); - int batchSize = messageToSend / 3; - int queueSize = messageToSend * 2; - int intervalMS = Integer.MAX_VALUE; // Deliberately big interval - Properties props = new Properties(); - props.put(basePropName + "." + BaseAuditHandler.PROP_NAME, - "testAuditBatchQueueDestDown"); - - props.put(basePropName + "." + AuditQueue.PROP_BATCH_SIZE, "" - + batchSize); - props.put(basePropName + "." + AuditQueue.PROP_QUEUE_SIZE, "" - + queueSize); - props.put(basePropName + "." + AuditQueue.PROP_BATCH_INTERVAL, "" - + intervalMS); - - // Enable File Spooling - props.put(basePropName + "." + "filespool.enable", "" + true); - props.put(basePropName + "." + "filespool.dir", "target"); - - TestConsumer testConsumer = new TestConsumer(); - testConsumer.isDown = true; - - AuditBatchQueue queue = new AuditBatchQueue(testConsumer); - queue.init(props, basePropName); - queue.start(); - - for (int i = 0; i < messageToSend; i++) { - queue.log(createEvent()); - - } - // Let's wait for second - try { - Thread.sleep(2000); - } catch (InterruptedException e) { - // ignore - } - - queue.waitToComplete(5000); - queue.stop(); - queue.waitToComplete(); - - assertEquals("Total count", 0, testConsumer.getCountTotal()); - assertEquals("Total sum", 0, testConsumer.getSumTotal()); - assertEquals("Total batch", 0, testConsumer.getBatchCount()); - assertNull("Event not in sequnce", testConsumer.isInSequence()); - } - - @Test - public void testAuditBatchQueueDestDownFlipFlop() { - logger.debug("testAuditBatchQueueDestDownFlipFlop()..."); - int messageToSend = 10; - - String basePropName = "testAuditBatchQueueDestDownFlipFlop_" - + MiscUtil.generateUniqueId(); - int batchSize = messageToSend / 3; - int queueSize = messageToSend * 2; - int intervalMS = 5000; // Deliberately big interval - Properties props = new Properties(); - props.put( - basePropName + "." + BaseAuditHandler.PROP_NAME, - "testAuditBatchQueueDestDownFlipFlop_" - + MiscUtil.generateUniqueId()); - - props.put(basePropName + "." + AuditQueue.PROP_BATCH_SIZE, "" - + batchSize); - props.put(basePropName + "." + AuditQueue.PROP_QUEUE_SIZE, "" - + queueSize); - props.put(basePropName + "." + AuditQueue.PROP_BATCH_INTERVAL, "" - + intervalMS); - - // Enable File Spooling - int destRetryMS = 10; - props.put(basePropName + "." + AuditQueue.PROP_FILE_SPOOL_ENABLE, - "" + true); - props.put( - basePropName + "." + AuditFileSpool.PROP_FILE_SPOOL_LOCAL_DIR, - "target"); - props.put(basePropName + "." - + AuditFileSpool.PROP_FILE_SPOOL_DEST_RETRY_MS, "" - + destRetryMS); - - TestConsumer testConsumer = new TestConsumer(); - testConsumer.isDown = false; - - AuditBatchQueue queue = new AuditBatchQueue(testConsumer); - queue.init(props, basePropName); - queue.start(); - - try { - queue.log(createEvent()); - queue.log(createEvent()); - queue.log(createEvent()); - Thread.sleep(1000); - testConsumer.isDown = true; - Thread.sleep(1000); - queue.log(createEvent()); - queue.log(createEvent()); - queue.log(createEvent()); - Thread.sleep(1000); - testConsumer.isDown = false; - Thread.sleep(1000); - queue.log(createEvent()); - queue.log(createEvent()); - queue.log(createEvent()); - Thread.sleep(1000); - testConsumer.isDown = true; - Thread.sleep(1000); - queue.log(createEvent()); - Thread.sleep(1000); - testConsumer.isDown = false; - Thread.sleep(1000); - } catch (InterruptedException e) { - // ignore - } - // Let's wait for second - try { - Thread.sleep(2000); - } catch (InterruptedException e) { - // ignore - } - - queue.waitToComplete(5000); - queue.stop(); - queue.waitToComplete(); - - assertEquals("Total count", messageToSend, testConsumer.getCountTotal()); - assertEquals("Total sum", messageToSend, testConsumer.getSumTotal()); - assertNull("Event not in sequnce", testConsumer.isInSequence()); - - } - - /** - * See if we recover after restart - */ - @Test - public void testAuditBatchQueueDestDownRestart() { - logger.debug("testAuditBatchQueueDestDownRestart()..."); - int messageToSend = 10; - - String basePropName = "testAuditBatchQueueDestDownRestart_" - + MiscUtil.generateUniqueId(); - int batchSize = messageToSend / 3; - int queueSize = messageToSend * 2; - int intervalMS = 3000; // Deliberately big interval - int maxArchivedFiles = 1; - Properties props = new Properties(); - props.put( - basePropName + "." + BaseAuditHandler.PROP_NAME, - "testAuditBatchQueueDestDownRestart_" - + MiscUtil.generateUniqueId()); - - props.put(basePropName + "." + AuditQueue.PROP_BATCH_SIZE, "" - + batchSize); - props.put(basePropName + "." + AuditQueue.PROP_QUEUE_SIZE, "" - + queueSize); - props.put(basePropName + "." + AuditQueue.PROP_BATCH_INTERVAL, "" - + intervalMS); - - // Enable File Spooling - int destRetryMS = 10; - props.put(basePropName + "." + AuditQueue.PROP_FILE_SPOOL_ENABLE, - "" + true); - props.put( - basePropName + "." + AuditFileSpool.PROP_FILE_SPOOL_LOCAL_DIR, - "target"); - props.put(basePropName + "." - + AuditFileSpool.PROP_FILE_SPOOL_DEST_RETRY_MS, "" - + destRetryMS); - props.put(basePropName + "." - + AuditFileSpool.PROP_FILE_SPOOL_ARCHIVE_MAX_FILES_COUNT, "" - + maxArchivedFiles); - - TestConsumer testConsumer = new TestConsumer(); - testConsumer.isDown = true; - - AuditBatchQueue queue = new AuditBatchQueue(testConsumer); - queue.init(props, basePropName); - queue.start(); - - for (int i = 0; i < messageToSend; i++) { - queue.log(createEvent()); - - } - // Let's wait for second or two - try { - Thread.sleep(2000); - } catch (InterruptedException e) { - // ignore - } - - queue.waitToComplete(5000); - queue.stop(); - queue.waitToComplete(); - - testConsumer.isDown = true; - - // Let's wait for second or two - try { - Thread.sleep(5000); - } catch (InterruptedException e) { - // ignore - } - - // Let's now recreate the objects - testConsumer = new TestConsumer(); - - queue = new AuditBatchQueue(testConsumer); - queue.init(props, basePropName); - queue.start(); - - // Let's wait for second - try { - Thread.sleep(2000); - } catch (InterruptedException e) { - // ignore - } - - queue.waitToComplete(5000); - queue.stop(); - queue.waitToComplete(); - - assertEquals("Total count", messageToSend, testConsumer.getCountTotal()); - assertEquals("Total sum", messageToSend, testConsumer.getSumTotal()); - assertNull("Event not in sequnce", testConsumer.isInSequence()); - - } - - @Test - public void testFileDestination() { - logger.debug("testFileDestination()..."); - - int messageToSend = 10; - int batchSize = messageToSend / 3; - int queueSize = messageToSend * 2; - int intervalMS = 500; // Should be less than final sleep time - - String logFolderName = "target/testFileDestination"; - File logFolder = new File(logFolderName); - String logFileName = "test_ranger_audit.log"; - File logFile = new File(logFolder, logFileName); - - Properties props = new Properties(); - // Destination - String filePropPrefix = AuditProviderFactory.AUDIT_DEST_BASE + ".file"; - props.put(filePropPrefix, "enable"); - props.put(filePropPrefix + "." + AuditQueue.PROP_NAME, "file"); - props.put(filePropPrefix + "." - + FileAuditDestination.PROP_FILE_LOCAL_DIR, logFolderName); - props.put(filePropPrefix + "." - + FileAuditDestination.PROP_FILE_LOCAL_FILE_NAME_FORMAT, - "%app-type%_ranger_audit.log"); - props.put(filePropPrefix + "." - + FileAuditDestination.PROP_FILE_FILE_ROLLOVER, "" + 10); - - props.put(filePropPrefix + "." + AuditQueue.PROP_QUEUE, "batch"); - String batchPropPrefix = filePropPrefix + "." + "batch"; - - props.put(batchPropPrefix + "." + AuditQueue.PROP_BATCH_SIZE, "" - + batchSize); - props.put(batchPropPrefix + "." + AuditQueue.PROP_QUEUE_SIZE, "" - + queueSize); - props.put(batchPropPrefix + "." + AuditQueue.PROP_BATCH_INTERVAL, - "" + intervalMS); - - // Enable File Spooling - int destRetryMS = 10; - props.put(batchPropPrefix + "." - + AuditQueue.PROP_FILE_SPOOL_ENABLE, "" + true); - props.put(batchPropPrefix + "." - + AuditFileSpool.PROP_FILE_SPOOL_LOCAL_DIR, "target"); - props.put(batchPropPrefix + "." - + AuditFileSpool.PROP_FILE_SPOOL_DEST_RETRY_MS, "" - + destRetryMS); - - AuditProviderFactory factory = new AuditProviderFactory(); - factory.init(props, "test"); - - // FileAuditDestination fileDest = new FileAuditDestination(); - // fileDest.init(props, filePropPrefix); - // - // AuditBatchQueue queue = new AuditBatchQueue(fileDest); - // queue.init(props, batchPropPrefix); - // queue.start(); - - AuditHandler queue = factory.getAuditProvider(); - - for (int i = 0; i < messageToSend; i++) { - queue.log(createEvent()); - } - // Let's wait for second - try { - Thread.sleep(1000); - } catch (InterruptedException e) { - // ignore - } - - queue.waitToComplete(); - queue.stop(); - queue.waitToComplete(); - - assertTrue("File created", logFile.exists()); - try { - List eventList = new ArrayList(); - int totalSum = 0; - BufferedReader br = new BufferedReader(new FileReader(logFile)); - String line; - int lastSeq = -1; - boolean outOfSeq = false; - while ((line = br.readLine()) != null) { - AuthzAuditEvent event = MiscUtil.fromJson(line, - AuthzAuditEvent.class); - eventList.add(event); - totalSum += event.getEventCount(); - if (event.getSeqNum() <= lastSeq) { - outOfSeq = true; - } - } - br.close(); - assertEquals("Total count", messageToSend, eventList.size()); - assertEquals("Total sum", messageToSend, totalSum); - assertFalse("Event not in sequnce", outOfSeq); - - } catch (Throwable e) { - logger.error("Error opening file for reading.", e); - assertTrue("Error reading file. fileName=" + logFile + ", error=" - + e.toString(), true); - } - - } - @Test - public void testAuditFileQueueSpoolORC(){ - String appType = "test"; - int messageToSend = 10; - String spoolFolderName = "target/spool"; - String logFolderName = "target/testAuditFileQueueSpoolORC"; - try { - FileUtils.deleteDirectory(new File(spoolFolderName)); - } catch (IOException e) { - throw new RuntimeException(e); - } - try { - FileUtils.deleteDirectory(new File(logFolderName)); - } catch (IOException e) { - throw new RuntimeException(e); - } - assertTrue(Files.notExists(Paths.get(spoolFolderName))); - assertTrue(Files.notExists(Paths.get(logFolderName))); - String subdir = appType + "/" + LocalDate.now().toString().replace("-",""); - File logFolder = new File(logFolderName); - File logSubfolder = new File(logFolder, subdir); - String logFileName = "test_ranger_audit.orc"; - File logFile = new File(logSubfolder, logFileName); - Properties props = new Properties(); - props.put(AuditProviderFactory.AUDIT_IS_ENABLED_PROP, "true"); - String hdfsPropPrefix = AuditProviderFactory.AUDIT_DEST_BASE + ".hdfs"; - props.put(hdfsPropPrefix,"enable"); - props.put(hdfsPropPrefix+".dir",logFolderName); - props.put(hdfsPropPrefix + "." + FileAuditDestination.PROP_FILE_LOCAL_FILE_NAME_FORMAT, - "%app-type%_ranger_audit.orc"); - String orcPrefix = hdfsPropPrefix + ".orc"; - props.put(orcPrefix+".compression","none"); - props.put(orcPrefix+".buffersize",""+10); - props.put(orcPrefix+".stripesize",""+10); - props.put(hdfsPropPrefix + ".batch.queuetype","filequeue"); - String filequeuePrefix = hdfsPropPrefix + ".batch.filequeue"; - props.put(filequeuePrefix+".filetype","orc"); - String fileSpoolPrefix = filequeuePrefix + ".filespool"; - props.put(fileSpoolPrefix+".dir",spoolFolderName); - props.put(fileSpoolPrefix+".buffer.size",""+10); - props.put(fileSpoolPrefix+".file.rollover.sec",""+5); - AuditProviderFactory factory = new AuditProviderFactory(); - factory.init(props, appType); - AuditHandler queue = factory.getAuditProvider(); - for (int i = 0; i < messageToSend; i++) { - queue.log(createEvent()); - } - try { - Thread.sleep(40000); - } catch (InterruptedException e) { - logger.error(e.getMessage()); - } - queue.waitToComplete(); - assertTrue("File created", logFile.exists()); - long rowCount = getOrcFileRowCount(logFile.getPath()); - assertEquals(messageToSend, rowCount); - } - @Test - public void testAuditFileQueueSpoolORCRollover(){ - String appType = "test"; - int messageToSend = 1000; - int preRolloverMessagesCount = (int)(0.8*messageToSend); - int postRolloverMessagesCount = messageToSend - preRolloverMessagesCount; - String spoolFolderName = "target/spool"; - String logFolderName = "target/testAuditFileQueueSpoolORC"; - try { - FileUtils.deleteDirectory(new File(spoolFolderName)); - } catch (IOException e) { - throw new RuntimeException(e); - } - try { - FileUtils.deleteDirectory(new File(logFolderName)); - } catch (IOException e) { - throw new RuntimeException(e); - } - assertTrue(Files.notExists(Paths.get(spoolFolderName))); - assertTrue(Files.notExists(Paths.get(logFolderName))); - File logFolder = new File(logFolderName); - Properties props = new Properties(); - props.put(AuditProviderFactory.AUDIT_IS_ENABLED_PROP, "true"); - String hdfsPropPrefix = AuditProviderFactory.AUDIT_DEST_BASE + ".hdfs"; - props.put(hdfsPropPrefix,"enable"); - props.put(hdfsPropPrefix+".dir",logFolderName); - props.put(hdfsPropPrefix + "." + FileAuditDestination.PROP_FILE_LOCAL_FILE_NAME_FORMAT, - "%app-type%_ranger_audit.orc"); - String orcPrefix = hdfsPropPrefix + ".orc"; - props.put(orcPrefix+".compression","snappy"); - //large numbers used here to ensure that file rollover happens because of file rollover seconds and not orc file /related props - props.put(orcPrefix+".buffersize",""+100000000000000L); - props.put(orcPrefix+".stripesize",""+100000000000000L); - props.put(hdfsPropPrefix + ".batch.queuetype","filequeue"); - String filequeuePrefix = hdfsPropPrefix + ".batch.filequeue"; - props.put(filequeuePrefix+".filetype","orc"); - String fileSpoolPrefix = filequeuePrefix + ".filespool"; - props.put(fileSpoolPrefix+".dir",spoolFolderName); - props.put(fileSpoolPrefix+".buffer.size",""+100000000000000L); - props.put(fileSpoolPrefix+".file.rollover.sec",""+5); - AuditProviderFactory factory = new AuditProviderFactory(); - factory.init(props, appType); - AuditHandler queue = factory.getAuditProvider(); - for (int i = 0; i < preRolloverMessagesCount; i++) { - queue.log(createEvent()); - try { - Thread.sleep(10); - } catch (InterruptedException e) { - logger.error(e.getMessage()); - } - } - //wait for rollover to happen - try { - Thread.sleep(10000); - } catch (InterruptedException e) { - logger.error(e.getMessage()); - } - //send some more logs - for (int i = 0; i < postRolloverMessagesCount; i++) { - queue.log(createEvent()); - try { - Thread.sleep(10); - } catch (InterruptedException e) { - logger.error(e.getMessage()); - } - } - queue.waitToComplete(); - int totalLogsOrc = 0; - File appSubFolder = new File(logFolder,appType); - String[] datewiseSubfolders = appSubFolder.list(); - logger.info("subfolder list="+ Arrays.toString(datewiseSubfolders)); - if (datewiseSubfolders != null) { - for (String dateSubfolder : datewiseSubfolders){ - File logSubfolder = new File(appSubFolder, dateSubfolder); - File[] listOfFiles = logSubfolder.listFiles(); - if (listOfFiles != null){ - for(File f : listOfFiles){ - if (f.getName().endsWith(".orc")){ - logger.info("Reading orc file:"+f.getName()); - totalLogsOrc += getOrcFileRowCount(f.getPath()); - } - } - } - } - } - logger.info("Number of logs in orc="+totalLogsOrc); - long totalLogsArchive = 0; - - try { - List convertedLogFiles = getFileNames(spoolFolderName+"/index_AuditFileQueueSpool_hdfs_test_closed.json"); - String[] convertedLogFileNames = new String[convertedLogFiles.size()]; - for(int i=0;i spoolFiles = getFileNames(spoolFolderName+"/index_AuditFileQueueSpool_hdfs_test.json"); - if (spoolFiles!=null){ - for(String f : spoolFiles){ - if (f.endsWith(".log")){ - try { - notYetConvertedToORCLogsCount += getLogCountInFile(f); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - } - } - } - catch (IOException e){ - throw new RuntimeException(e); - } - logger.info("Number of logs not converted to ORC:"+notYetConvertedToORCLogsCount); - assertEquals(messageToSend, notYetConvertedToORCLogsCount+totalLogsArchive); - } - - private AuthzAuditEvent createEvent() { - AuthzAuditEvent event = new AuthzAuditEvent(); - event.setSeqNum(++seqNum); - return event; - } - - private AuthzAuditEvent createEvent(String user, String accessType, - String resource, boolean isAllowed) { - AuthzAuditEvent event = new AuthzAuditEvent(); - event.setUser(user); - event.setAccessType(accessType); - event.setResourcePath(resource); - event.setAccessResult(isAllowed ? (short) 1 : (short) 0); - - event.setSeqNum(++seqNum); - return event; - } - - private static long getOrcFileRowCount(String filePath) { - try { - Configuration conf = new Configuration(); - Path orcFilePath = new Path(filePath); - Reader reader = OrcFile.createReader(orcFilePath, OrcFile.readerOptions(conf)); - long numRows = reader.getNumberOfRows(); - return numRows; - } catch (Exception e) { - e.printStackTrace(); - } - return -1; - } - private static long getLogCountInFile(String filePath) throws IOException { - BufferedReader reader = new BufferedReader(new FileReader(filePath)); - long lines = 0; - while (reader.readLine() != null) { - lines++; - } - reader.close(); - return lines; - } - - private static List getFileNames(String jsonIndexFile) throws IOException { - List fileNames = new ArrayList<>(); - BufferedReader reader = new BufferedReader(new FileReader(jsonIndexFile)); - while (true) { - String line = reader.readLine(); - if (line!=null){ - try { - AuditIndexRecord indexRecord = MiscUtil.getMapper().readValue(line, AuditIndexRecord.class); - String filePath = indexRecord != null ? indexRecord.getFilePath() : null; - - if (filePath != null) { - fileNames.add(filePath); - } - } catch (Exception excp) { - excp.printStackTrace(System.out); - } - } - else{ - break; - } - } - reader.close(); - return fileNames; - } +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +public class TestAuditQueue { + private static final Logger logger = LoggerFactory.getLogger(TestAuditQueue.class); + private static int seqNum; + + @BeforeClass + public static void setUpBeforeClass() { + } + + @AfterClass + public static void tearDownAfterClass() { + } + + @Test + public void testAuditAsyncQueue() { + logger.debug("testAuditAsyncQueue() ..."); + TestConsumer testConsumer = new TestConsumer(); + AuditAsyncQueue queue = new AuditAsyncQueue(testConsumer); + Properties props = new Properties(); + queue.init(props); + + queue.start(); + + int messageToSend = 10; + for (int i = 0; i < messageToSend; i++) { + queue.log(createEvent()); + } + queue.stop(); + queue.waitToComplete(); + + sleep(1000); + assertEquals(messageToSend, testConsumer.getCountTotal()); + assertEquals(messageToSend, testConsumer.getSumTotal()); + assertNull("Event not in sequence", testConsumer.isInSequence()); + } + + @Test + public void testAuditSummaryQueue() { + logger.debug("testAuditSummaryQueue()..."); + + TestConsumer testConsumer = new TestConsumer(); + AuditSummaryQueue queue = new AuditSummaryQueue(testConsumer); + + Properties props = new Properties(); + props.put(BaseAuditHandler.PROP_DEFAULT_PREFIX + "." + AuditSummaryQueue.PROP_SUMMARY_INTERVAL, "" + 300); + queue.init(props, BaseAuditHandler.PROP_DEFAULT_PREFIX); + + queue.start(); + + commonTestSummary(testConsumer, queue); + } + + @Test + public void testAuditSummaryByInfra() { + logger.debug("testAuditSummaryByInfra()..."); + + Properties props = new Properties(); + // Destination + String propPrefix = AuditProviderFactory.AUDIT_DEST_BASE + ".test"; + props.put(propPrefix, "enable"); + props.put(BaseAuditHandler.PROP_DEFAULT_PREFIX + "." + "summary" + "." + "enabled", "true"); + props.put(propPrefix + "." + BaseAuditHandler.PROP_NAME, "test"); + props.put(propPrefix + "." + AuditQueue.PROP_QUEUE, "none"); + + props.put(BaseAuditHandler.PROP_DEFAULT_PREFIX + "." + AuditSummaryQueue.PROP_SUMMARY_INTERVAL, "" + 300); + props.put(propPrefix + "." + BaseAuditHandler.PROP_CLASS_NAME, TestConsumer.class.getName()); + + AuditProviderFactory factory = AuditProviderFactory.getInstance(); + factory.init(props, "test"); + AuditQueue queue = (AuditQueue) factory.getAuditProvider(); + BaseAuditHandler consumer = (BaseAuditHandler) queue.getConsumer(); + while (consumer != null && consumer instanceof AuditQueue) { + AuditQueue cQueue = (AuditQueue) consumer; + consumer = (BaseAuditHandler) cQueue.getConsumer(); + } + assertTrue("Consumer should be TestConsumer. class = " + consumer.getClass().getName(), consumer instanceof TestConsumer); + TestConsumer testConsumer = (TestConsumer) consumer; + commonTestSummary(testConsumer, queue); + } + + @Test + public void testMultipleQueue() { + logger.debug("testAuditAsyncQueue()..."); + int destCount = 3; + TestConsumer[] testConsumer = new TestConsumer[destCount]; + + MultiDestAuditProvider multiQueue = new MultiDestAuditProvider(); + for (int i = 0; i < destCount; i++) { + testConsumer[i] = new TestConsumer(); + multiQueue.addAuditProvider(testConsumer[i]); + } + + AuditAsyncQueue queue = new AuditAsyncQueue(multiQueue); + Properties props = new Properties(); + queue.init(props); + queue.start(); + + int messageToSend = 10; + for (int i = 0; i < messageToSend; i++) { + queue.log(createEvent()); + } + queue.stop(); + queue.waitToComplete(); + + sleep(1000); + for (int i = 0; i < destCount; i++) { + assertEquals("consumer" + i, messageToSend, testConsumer[i].getCountTotal()); + assertEquals("consumer" + i, messageToSend, testConsumer[i].getSumTotal()); + } + } + + @Test + public void testAuditBatchQueueBySize() { + logger.debug("testAuditBatchQueue()..."); + int messageToSend = 10; + + String basePropName = "testAuditBatchQueueBySize_" + MiscUtil.generateUniqueId(); + int batchSize = messageToSend / 3; + int expectedBatchSize = batchSize + (batchSize * 3 < messageToSend ? 1 : 0); + int queueSize = batchSize * 2; + int intervalMS = messageToSend * 100; // Deliberately big interval + Properties props = new Properties(); + props.put(basePropName + "." + AuditQueue.PROP_BATCH_SIZE, "" + batchSize); + props.put(basePropName + "." + AuditQueue.PROP_QUEUE_SIZE, "" + queueSize); + props.put(basePropName + "." + AuditQueue.PROP_BATCH_INTERVAL, "" + intervalMS); + + TestConsumer testConsumer = new TestConsumer(); + AuditBatchQueue queue = new AuditBatchQueue(testConsumer); + queue.init(props, basePropName); + queue.start(); + + for (int i = 0; i < messageToSend; i++) { + queue.log(createEvent()); + } + + sleep(2000); + + queue.waitToComplete(); + queue.stop(); + queue.waitToComplete(); + + assertEquals("Total count", messageToSend, testConsumer.getCountTotal()); + assertEquals("Total sum", messageToSend, testConsumer.getSumTotal()); + assertEquals("Total batch", expectedBatchSize, testConsumer.getBatchCount()); + assertNull("Event not in sequnce", testConsumer.isInSequence()); + } + + @Test + public void testAuditBatchQueueByTime() { + logger.debug("testAuditBatchQueue() ..."); + + int messageToSend = 10; + + String basePropName = "testAuditBatchQueueByTime_" + MiscUtil.generateUniqueId(); + int batchSize = messageToSend * 2; // Deliberately big size + int queueSize = messageToSend * 2; + int intervalMS = (1000 / messageToSend) * 3; // e.g (1000/10 * 3) = 300 + // ms + int pauseMS = 1000 / messageToSend + 3; // e.g. 1000/10 + 3 = 103ms + int expectedBatchSize = (messageToSend * pauseMS) / intervalMS + 1; + + Properties props = new Properties(); + props.put(basePropName + "." + AuditQueue.PROP_BATCH_SIZE, "" + batchSize); + props.put(basePropName + "." + AuditQueue.PROP_QUEUE_SIZE, "" + queueSize); + props.put(basePropName + "." + AuditQueue.PROP_BATCH_INTERVAL, "" + intervalMS); + + TestConsumer testConsumer = new TestConsumer(); + AuditBatchQueue queue = new AuditBatchQueue(testConsumer); + queue.init(props, basePropName); + queue.start(); + + for (int i = 0; i < messageToSend; i++) { + queue.log(createEvent()); + try { + Thread.sleep(pauseMS); + } catch (InterruptedException ignored) { + } + } + + sleep(2000); + queue.waitToComplete(); + queue.stop(); + queue.waitToComplete(); + + assertEquals("Total count", messageToSend, testConsumer.getCountTotal()); + assertEquals("Total sum", messageToSend, testConsumer.getSumTotal()); + assertEquals("Total batch", expectedBatchSize, testConsumer.getBatchCount()); + assertNull("Event not in sequnce", testConsumer.isInSequence()); + } + + @Test + public void testAuditBatchQueueDestDown() { + logger.debug("testAuditBatchQueueDestDown()..."); + int messageToSend = 10; + + String basePropName = "testAuditBatchQueueDestDown_" + MiscUtil.generateUniqueId(); + int batchSize = messageToSend / 3; + int queueSize = messageToSend * 2; + int intervalMS = Integer.MAX_VALUE; // Deliberately big interval + Properties props = new Properties(); + props.put(basePropName + "." + BaseAuditHandler.PROP_NAME, "testAuditBatchQueueDestDown"); + + props.put(basePropName + "." + AuditQueue.PROP_BATCH_SIZE, "" + batchSize); + props.put(basePropName + "." + AuditQueue.PROP_QUEUE_SIZE, "" + queueSize); + props.put(basePropName + "." + AuditQueue.PROP_BATCH_INTERVAL, "" + intervalMS); + + // Enable File Spooling + props.put(basePropName + "." + "filespool.enable", "" + true); + props.put(basePropName + "." + "filespool.dir", "target"); + + TestConsumer testConsumer = new TestConsumer(); + testConsumer.isDown = true; + + AuditBatchQueue queue = new AuditBatchQueue(testConsumer); + queue.init(props, basePropName); + queue.start(); + + for (int i = 0; i < messageToSend; i++) { + queue.log(createEvent()); + } + + try { + Thread.sleep(2000); + } catch (InterruptedException ignored) { + } + + queue.waitToComplete(5000); + queue.stop(); + queue.waitToComplete(); + + assertEquals("Total count", 0, testConsumer.getCountTotal()); + assertEquals("Total sum", 0, testConsumer.getSumTotal()); + assertEquals("Total batch", 0, testConsumer.getBatchCount()); + assertNull("Event not in sequnce", testConsumer.isInSequence()); + } + + @Test + public void testAuditBatchQueueDestDownFlipFlop() { + logger.debug("testAuditBatchQueueDestDownFlipFlop()..."); + int messageToSend = 10; + + String basePropName = "testAuditBatchQueueDestDownFlipFlop_" + MiscUtil.generateUniqueId(); + int batchSize = messageToSend / 3; + int queueSize = messageToSend * 2; + int intervalMS = 5000; // Deliberately big interval + Properties props = new Properties(); + props.put(basePropName + "." + BaseAuditHandler.PROP_NAME, "testAuditBatchQueueDestDownFlipFlop_" + MiscUtil.generateUniqueId()); + + props.put(basePropName + "." + AuditQueue.PROP_BATCH_SIZE, "" + batchSize); + props.put(basePropName + "." + AuditQueue.PROP_QUEUE_SIZE, "" + queueSize); + props.put(basePropName + "." + AuditQueue.PROP_BATCH_INTERVAL, "" + intervalMS); + + // Enable File Spooling + int destRetryMS = 10; + props.put(basePropName + "." + AuditQueue.PROP_FILE_SPOOL_ENABLE, "" + true); + props.put(basePropName + "." + AuditFileSpool.PROP_FILE_SPOOL_LOCAL_DIR, "target"); + props.put(basePropName + "." + AuditFileSpool.PROP_FILE_SPOOL_DEST_RETRY_MS, "" + destRetryMS); + + TestConsumer testConsumer = new TestConsumer(); + testConsumer.isDown = false; + + AuditBatchQueue queue = new AuditBatchQueue(testConsumer); + queue.init(props, basePropName); + queue.start(); + + try { + queue.log(createEvent()); + queue.log(createEvent()); + queue.log(createEvent()); + Thread.sleep(1000); + testConsumer.isDown = true; + Thread.sleep(1000); + queue.log(createEvent()); + queue.log(createEvent()); + queue.log(createEvent()); + Thread.sleep(1000); + testConsumer.isDown = false; + Thread.sleep(1000); + queue.log(createEvent()); + queue.log(createEvent()); + queue.log(createEvent()); + Thread.sleep(1000); + testConsumer.isDown = true; + Thread.sleep(1000); + queue.log(createEvent()); + Thread.sleep(1000); + testConsumer.isDown = false; + Thread.sleep(1000); + } catch (InterruptedException ignored) { + } + + sleep(2000); + + queue.waitToComplete(5000); + queue.stop(); + queue.waitToComplete(); + + assertEquals("Total count", messageToSend, testConsumer.getCountTotal()); + assertEquals("Total sum", messageToSend, testConsumer.getSumTotal()); + assertNull("Event not in sequence", testConsumer.isInSequence()); + } + + /** + * See if we recover after restart + */ + @Test + public void testAuditBatchQueueDestDownRestart() { + logger.debug("testAuditBatchQueueDestDownRestart()..."); + + String basePropName = "testAuditBatchQueueDestDownRestart_" + MiscUtil.generateUniqueId(); + int messageToSend = 10; + int batchSize = messageToSend / 3; + int queueSize = messageToSend * 2; + int intervalMS = 3000; // Deliberately big interval + int maxArchivedFiles = 1; + Properties props = new Properties(); + props.put(basePropName + "." + BaseAuditHandler.PROP_NAME, "testAuditBatchQueueDestDownRestart_" + MiscUtil.generateUniqueId()); + + props.put(basePropName + "." + AuditQueue.PROP_BATCH_SIZE, "" + batchSize); + props.put(basePropName + "." + AuditQueue.PROP_QUEUE_SIZE, "" + queueSize); + props.put(basePropName + "." + AuditQueue.PROP_BATCH_INTERVAL, "" + intervalMS); + + // Enable File Spooling + int destRetryMS = 10; + props.put(basePropName + "." + AuditQueue.PROP_FILE_SPOOL_ENABLE, "" + true); + props.put(basePropName + "." + AuditFileSpool.PROP_FILE_SPOOL_LOCAL_DIR, "target"); + props.put(basePropName + "." + AuditFileSpool.PROP_FILE_SPOOL_DEST_RETRY_MS, "" + destRetryMS); + props.put(basePropName + "." + AuditFileSpool.PROP_FILE_SPOOL_ARCHIVE_MAX_FILES_COUNT, "" + maxArchivedFiles); + + TestConsumer testConsumer = new TestConsumer(); + testConsumer.isDown = true; + + AuditBatchQueue queue = new AuditBatchQueue(testConsumer); + queue.init(props, basePropName); + queue.start(); + + for (int i = 0; i < messageToSend; i++) { + queue.log(createEvent()); + } + + sleep(2000); + + queue.waitToComplete(5000); + queue.stop(); + queue.waitToComplete(); + + testConsumer.isDown = true; + + sleep(5000); + + // Let's now recreate the objects + testConsumer = new TestConsumer(); + + queue = new AuditBatchQueue(testConsumer); + queue.init(props, basePropName); + queue.start(); + + sleep(2000); + + queue.waitToComplete(5000); + queue.stop(); + queue.waitToComplete(); + + assertEquals("Total count", messageToSend, testConsumer.getCountTotal()); + assertEquals("Total sum", messageToSend, testConsumer.getSumTotal()); + assertNull("Event not in sequence", testConsumer.isInSequence()); + } + + @Test + public void testFileDestination() { + logger.debug("testFileDestination()..."); + + int messageToSend = 10; + int batchSize = messageToSend / 3; + int queueSize = messageToSend * 2; + int intervalMS = 500; // Should be less than final sleep time + + String logFolderName = "target/testFileDestination"; + File logFolder = new File(logFolderName); + String logFileName = "test_ranger_audit.log"; + File logFile = new File(logFolder, logFileName); + + Properties props = new Properties(); + // Destination + String filePropPrefix = AuditProviderFactory.AUDIT_DEST_BASE + ".file"; + props.put(filePropPrefix, "enable"); + props.put(filePropPrefix + "." + AuditQueue.PROP_NAME, "file"); + props.put(filePropPrefix + "." + FileAuditDestination.PROP_FILE_LOCAL_DIR, logFolderName); + props.put(filePropPrefix + "." + FileAuditDestination.PROP_FILE_LOCAL_FILE_NAME_FORMAT, "%app-type%_ranger_audit.log"); + props.put(filePropPrefix + "." + FileAuditDestination.PROP_FILE_FILE_ROLLOVER, "" + 10); + + props.put(filePropPrefix + "." + AuditQueue.PROP_QUEUE, "batch"); + String batchPropPrefix = filePropPrefix + "." + "batch"; + + props.put(batchPropPrefix + "." + AuditQueue.PROP_BATCH_SIZE, "" + batchSize); + props.put(batchPropPrefix + "." + AuditQueue.PROP_QUEUE_SIZE, "" + queueSize); + props.put(batchPropPrefix + "." + AuditQueue.PROP_BATCH_INTERVAL, "" + intervalMS); + + // Enable File Spooling + int destRetryMS = 10; + props.put(batchPropPrefix + "." + AuditQueue.PROP_FILE_SPOOL_ENABLE, "" + true); + props.put(batchPropPrefix + "." + AuditFileSpool.PROP_FILE_SPOOL_LOCAL_DIR, "target"); + props.put(batchPropPrefix + "." + AuditFileSpool.PROP_FILE_SPOOL_DEST_RETRY_MS, "" + destRetryMS); + + AuditProviderFactory factory = new AuditProviderFactory(); + factory.init(props, "test"); + + AuditHandler queue = factory.getAuditProvider(); + + for (int i = 0; i < messageToSend; i++) { + queue.log(createEvent()); + } + + sleep(1000); + + queue.waitToComplete(); + queue.stop(); + queue.waitToComplete(); + + assertTrue("File created", logFile.exists()); + try { + List eventList = new ArrayList<>(); + int totalSum = 0; + BufferedReader br = new BufferedReader(new FileReader(logFile)); + String line; + int lastSeq = -1; + boolean outOfSeq = false; + while ((line = br.readLine()) != null) { + AuthzAuditEvent event = MiscUtil.fromJson(line, AuthzAuditEvent.class); + eventList.add(event); + totalSum += event.getEventCount(); + if (event.getSeqNum() <= lastSeq) { + outOfSeq = true; + } + } + br.close(); + assertEquals("Total count", messageToSend, eventList.size()); + assertEquals("Total sum", messageToSend, totalSum); + assertFalse("Event not in sequnce", outOfSeq); + } catch (Throwable e) { + logger.error("Error opening file for reading.", e); + assertTrue("Error reading file. fileName=" + logFile + ", error=" + e, true); + } + } + + @Test + public void testAuditFileQueueSpoolORC() { + String appType = "test"; + int messageToSend = 10; + String spoolFolderName = "target/spool"; + String logFolderName = "target/testAuditFileQueueSpoolORC"; + try { + FileUtils.deleteDirectory(new File(spoolFolderName)); + } catch (IOException e) { + throw new RuntimeException(e); + } + try { + FileUtils.deleteDirectory(new File(logFolderName)); + } catch (IOException e) { + throw new RuntimeException(e); + } + assertTrue(Files.notExists(Paths.get(spoolFolderName))); + assertTrue(Files.notExists(Paths.get(logFolderName))); + String subdir = appType + "/" + LocalDate.now().toString().replace("-", ""); + File logFolder = new File(logFolderName); + File logSubfolder = new File(logFolder, subdir); + String logFileName = "test_ranger_audit.orc"; + File logFile = new File(logSubfolder, logFileName); + Properties props = new Properties(); + props.put(AuditProviderFactory.AUDIT_IS_ENABLED_PROP, "true"); + String hdfsPropPrefix = AuditProviderFactory.AUDIT_DEST_BASE + ".hdfs"; + props.put(hdfsPropPrefix, "enable"); + props.put(hdfsPropPrefix + ".dir", logFolderName); + props.put(hdfsPropPrefix + "." + FileAuditDestination.PROP_FILE_LOCAL_FILE_NAME_FORMAT, "%app-type%_ranger_audit.orc"); + String orcPrefix = hdfsPropPrefix + ".orc"; + props.put(orcPrefix + ".compression", "none"); + props.put(orcPrefix + ".buffersize", "" + 10); + props.put(orcPrefix + ".stripesize", "" + 10); + props.put(hdfsPropPrefix + ".batch.queuetype", "filequeue"); + String filequeuePrefix = hdfsPropPrefix + ".batch.filequeue"; + props.put(filequeuePrefix + ".filetype", "orc"); + String fileSpoolPrefix = filequeuePrefix + ".filespool"; + props.put(fileSpoolPrefix + ".dir", spoolFolderName); + props.put(fileSpoolPrefix + ".buffer.size", "" + 10); + props.put(fileSpoolPrefix + ".file.rollover.sec", "" + 5); + AuditProviderFactory factory = new AuditProviderFactory(); + factory.init(props, appType); + AuditHandler queue = factory.getAuditProvider(); + for (int i = 0; i < messageToSend; i++) { + queue.log(createEvent()); + } + try { + Thread.sleep(40000); + } catch (InterruptedException e) { + logger.error(e.getMessage()); + } + queue.waitToComplete(); + assertTrue("File created", logFile.exists()); + long rowCount = getOrcFileRowCount(logFile.getPath()); + assertEquals(messageToSend, rowCount); + } + + @Test + public void testAuditFileQueueSpoolORCRollover() { + String appType = "test"; + int messageToSend = 1000; + int preRolloverMessagesCount = (int) (0.8 * messageToSend); + int postRolloverMessagesCount = messageToSend - preRolloverMessagesCount; + String spoolFolderName = "target/spool"; + String logFolderName = "target/testAuditFileQueueSpoolORC"; + try { + FileUtils.deleteDirectory(new File(spoolFolderName)); + } catch (IOException e) { + throw new RuntimeException(e); + } + try { + FileUtils.deleteDirectory(new File(logFolderName)); + } catch (IOException e) { + throw new RuntimeException(e); + } + assertTrue(Files.notExists(Paths.get(spoolFolderName))); + assertTrue(Files.notExists(Paths.get(logFolderName))); + File logFolder = new File(logFolderName); + Properties props = new Properties(); + props.put(AuditProviderFactory.AUDIT_IS_ENABLED_PROP, "true"); + String hdfsPropPrefix = AuditProviderFactory.AUDIT_DEST_BASE + ".hdfs"; + props.put(hdfsPropPrefix, "enable"); + props.put(hdfsPropPrefix + ".dir", logFolderName); + props.put(hdfsPropPrefix + "." + FileAuditDestination.PROP_FILE_LOCAL_FILE_NAME_FORMAT, "%app-type%_ranger_audit.orc"); + String orcPrefix = hdfsPropPrefix + ".orc"; + props.put(orcPrefix + ".compression", "snappy"); + //large numbers used here to ensure that file rollover happens because of file rollover seconds and not orc file /related props + props.put(orcPrefix + ".buffersize", "" + 100000000000000L); + props.put(orcPrefix + ".stripesize", "" + 100000000000000L); + props.put(hdfsPropPrefix + ".batch.queuetype", "filequeue"); + String filequeuePrefix = hdfsPropPrefix + ".batch.filequeue"; + props.put(filequeuePrefix + ".filetype", "orc"); + String fileSpoolPrefix = filequeuePrefix + ".filespool"; + props.put(fileSpoolPrefix + ".dir", spoolFolderName); + props.put(fileSpoolPrefix + ".buffer.size", "" + 100000000000000L); + props.put(fileSpoolPrefix + ".file.rollover.sec", "" + 5); + AuditProviderFactory factory = new AuditProviderFactory(); + factory.init(props, appType); + AuditHandler queue = factory.getAuditProvider(); + for (int i = 0; i < preRolloverMessagesCount; i++) { + queue.log(createEvent()); + try { + Thread.sleep(10); + } catch (InterruptedException e) { + logger.error(e.getMessage()); + } + } + //wait for rollover to happen + try { + Thread.sleep(10000); + } catch (InterruptedException e) { + logger.error(e.getMessage()); + } + //send some more logs + for (int i = 0; i < postRolloverMessagesCount; i++) { + queue.log(createEvent()); + try { + Thread.sleep(10); + } catch (InterruptedException e) { + logger.error(e.getMessage()); + } + } + queue.waitToComplete(); + int totalLogsOrc = 0; + File appSubFolder = new File(logFolder, appType); + String[] datewiseSubfolders = appSubFolder.list(); + + logger.info("subfolder list={}", Arrays.toString(datewiseSubfolders)); + + if (datewiseSubfolders != null) { + for (String dateSubfolder : datewiseSubfolders) { + File logSubfolder = new File(appSubFolder, dateSubfolder); + File[] listOfFiles = logSubfolder.listFiles(); + if (listOfFiles != null) { + for (File f : listOfFiles) { + if (f.getName().endsWith(".orc")) { + logger.info("Reading orc file: {}", f.getName()); + totalLogsOrc += getOrcFileRowCount(f.getPath()); + } + } + } + } + } + logger.info("Number of logs in orc = {}", totalLogsOrc); + long totalLogsArchive = 0; + + try { + List convertedLogFiles = getFileNames(spoolFolderName + "/index_AuditFileQueueSpool_hdfs_test_closed.json"); + String[] convertedLogFileNames = new String[convertedLogFiles.size()]; + for (int i = 0; i < convertedLogFiles.size(); i++) { + String[] pathElements = convertedLogFiles.get(i).split("/"); + convertedLogFileNames[i] = spoolFolderName + "/archive/" + pathElements[pathElements.length - 1]; + } + for (String f : convertedLogFileNames) { + totalLogsArchive += getLogCountInFile(f); + } + } catch (IOException e) { + throw new RuntimeException(e); + } + logger.info("Number of logs in archive: {}", totalLogsArchive); + assertEquals(totalLogsOrc, totalLogsArchive); + + long notYetConvertedToORCLogsCount = 0; + //count logs which have not yet been converted to orc + try { + List spoolFiles = getFileNames(spoolFolderName + "/index_AuditFileQueueSpool_hdfs_test.json"); + if (spoolFiles != null) { + for (String f : spoolFiles) { + if (f.endsWith(".log")) { + try { + notYetConvertedToORCLogsCount += getLogCountInFile(f); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + } + } + } catch (IOException e) { + throw new RuntimeException(e); + } + logger.info("Number of logs not converted to ORC: {}", notYetConvertedToORCLogsCount); + assertEquals(messageToSend, notYetConvertedToORCLogsCount + totalLogsArchive); + } + + private void commonTestSummary(TestConsumer testConsumer, BaseAuditHandler queue) { + int messageToSend = 0; + int pauseMS = 330; + int countToCheck = 0; + + try { + queue.log(createEvent("john", "select", "xademo/customer_details/imei", true)); + messageToSend++; + queue.log(createEvent("john", "select", "xademo/customer_details/imei", true)); + messageToSend++; + countToCheck++; + queue.log(createEvent("jane", "select", "xademo/customer_details/imei", true)); + messageToSend++; + countToCheck++; + Thread.sleep(pauseMS); + + queue.log(createEvent("john", "select", "xademo/customer_details/imei", true)); + messageToSend++; + queue.log(createEvent("john", "select", "xademo/customer_details/imei", true)); + messageToSend++; + countToCheck++; + queue.log(createEvent("jane", "select", "xademo/customer_details/imei", true)); + messageToSend++; + countToCheck++; + Thread.sleep(pauseMS); + + queue.log(createEvent("john", "select", "xademo/customer_details/imei", true)); + messageToSend++; + countToCheck++; + queue.log(createEvent("john", "select", "xademo/customer_details/imei", false)); + messageToSend++; + countToCheck++; + queue.log(createEvent("jane", "select", "xademo/customer_details/imei", true)); + messageToSend++; + countToCheck++; + Thread.sleep(pauseMS); + } catch (InterruptedException e1) { + logger.error("Sleep interrupted", e1); + } + + sleep(1000); + + queue.waitToComplete(); + queue.stop(); + queue.waitToComplete(); + + sleep(1000); + assertEquals(messageToSend, testConsumer.getSumTotal()); + assertEquals(countToCheck, testConsumer.getCountTotal()); + } + + private AuthzAuditEvent createEvent() { + AuthzAuditEvent event = new AuthzAuditEvent(); + event.setSeqNum(++seqNum); + return event; + } + + private AuthzAuditEvent createEvent(String user, String accessType, String resource, boolean isAllowed) { + AuthzAuditEvent event = new AuthzAuditEvent(); + event.setUser(user); + event.setAccessType(accessType); + event.setResourcePath(resource); + event.setAccessResult(isAllowed ? (short) 1 : (short) 0); + + event.setSeqNum(++seqNum); + return event; + } + + private static long getOrcFileRowCount(String filePath) { + try { + Configuration conf = new Configuration(); + Path orcFilePath = new Path(filePath); + Reader reader = OrcFile.createReader(orcFilePath, OrcFile.readerOptions(conf)); + long numRows = reader.getNumberOfRows(); + return numRows; + } catch (Exception e) { + e.printStackTrace(); + } + return -1; + } + + private static long getLogCountInFile(String filePath) throws IOException { + BufferedReader reader = new BufferedReader(new FileReader(filePath)); + long lines = 0; + while (reader.readLine() != null) { + lines++; + } + reader.close(); + return lines; + } + + private static List getFileNames(String jsonIndexFile) throws IOException { + List fileNames = new ArrayList<>(); + BufferedReader reader = new BufferedReader(new FileReader(jsonIndexFile)); + while (true) { + String line = reader.readLine(); + if (line != null) { + try { + AuditIndexRecord indexRecord = MiscUtil.getMapper().readValue(line, AuditIndexRecord.class); + String filePath = indexRecord != null ? indexRecord.getFilePath() : null; + + if (filePath != null) { + fileNames.add(filePath); + } + } catch (Exception excp) { + excp.printStackTrace(System.out); + } + } else { + break; + } + } + reader.close(); + return fileNames; + } + + private void sleep(long ms) { + try { + Thread.sleep(ms); + } catch (InterruptedException ignored) { + } + } } diff --git a/security-admin/src/test/java/org/apache/ranger/audit/TestConsumer.java b/security-admin/src/test/java/org/apache/ranger/audit/TestConsumer.java index 09386d2318..01548cfca7 100644 --- a/security-admin/src/test/java/org/apache/ranger/audit/TestConsumer.java +++ b/security-admin/src/test/java/org/apache/ranger/audit/TestConsumer.java @@ -19,9 +19,6 @@ package org.apache.ranger.audit; -import java.util.Collection; -import java.util.Properties; - import org.apache.ranger.audit.destination.AuditDestination; import org.apache.ranger.audit.model.AuditEventBase; import org.apache.ranger.audit.model.AuthzAuditEvent; @@ -29,184 +26,181 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.util.Collection; +import java.util.Properties; + public class TestConsumer extends AuditDestination { - private static final Logger logger = LoggerFactory.getLogger(TestConsumer.class); - - int countTotal = 0; - int sumTotal = 0; - int batchCount = 0; - AuthzAuditEvent lastEvent = null; - AuthzAuditEvent lastOutOfSeqEvent = null; - String providerName = getClass().getName(); - boolean isDown = false; - - /* - * (non-Javadoc) - * - * @see org.apache.ranger.audit.provider.AuditProvider#log(org.apache.ranger - * .audit.model.AuditEventBase) - */ - @Override - public boolean log(AuditEventBase event) { - if (isDown) { - return false; - } - countTotal++; - if (event instanceof AuthzAuditEvent) { - AuthzAuditEvent azEvent = (AuthzAuditEvent) event; - sumTotal += azEvent.getEventCount(); - logger.info("EVENT:" + event); - - processEvent(azEvent); - } - return true; - } - - @Override - public boolean log(Collection events) { - if (isDown) { - return false; - } - batchCount++; - for (AuditEventBase event : events) { - log(event); - } - return true; - } - - @Override - public boolean logJSON(String jsonStr) { - if (isDown) { - return false; - } - countTotal++; - AuthzAuditEvent event = MiscUtil.fromJson(jsonStr, - AuthzAuditEvent.class); - sumTotal += event.getEventCount(); - logger.info("JSON:" + jsonStr); - processEvent(event); - return true; - } - - @Override - public boolean logJSON(Collection events) { - if (isDown) { - return false; - } - batchCount++; - for (String event : events) { - logJSON(event); - } - return true; - } - - /* - * (non-Javadoc) - * - * @see - * org.apache.ranger.audit.provider.AuditProvider#init(java.util.Properties - * ) - */ - @Override - public void init(Properties prop) { - // Nothing to do here - } - - /* - * (non-Javadoc) - * - * @see org.apache.ranger.audit.provider.AuditProvider#start() - */ - @Override - public void start() { - // Nothing to do here - } - - /* - * (non-Javadoc) - * - * @see org.apache.ranger.audit.provider.AuditProvider#stop() - */ - @Override - public void stop() { - // Nothing to do here - } - - /* - * (non-Javadoc) - * - * @see org.apache.ranger.audit.provider.AuditProvider#waitToComplete() - */ - @Override - public void waitToComplete() { - } - - /* - * (non-Javadoc) - * - * @see org.apache.ranger.audit.provider.AuditProvider#flush() - */ - @Override - public void flush() { - // Nothing to do here - } - - public int getCountTotal() { - return countTotal; - } - - public int getSumTotal() { - return sumTotal; - } - - public int getBatchCount() { - return batchCount; - } - - /* - * (non-Javadoc) - * - * @see - * org.apache.ranger.audit.provider.AuditProvider#init(java.util.Properties - * , java.lang.String) - */ - @Override - public void init(Properties prop, String basePropertyName) { - - } - - /* - * (non-Javadoc) - * - * @see org.apache.ranger.audit.provider.AuditProvider#waitToComplete(long) - */ - @Override - public void waitToComplete(long timeout) { - - } - - /* - * (non-Javadoc) - * - * @see org.apache.ranger.audit.provider.AuditProvider#getName() - */ - @Override - public String getName() { - return providerName; - } - - // Local methods - public AuthzAuditEvent isInSequence() { - return lastOutOfSeqEvent; - } - - private void processEvent(AuthzAuditEvent azEvent) { - if (lastEvent == null) { - lastEvent = azEvent; - } else if (lastOutOfSeqEvent == null) { - if (azEvent.getSeqNum() <= lastEvent.getSeqNum()) { - lastOutOfSeqEvent = azEvent; - } - } - } + private static final Logger logger = LoggerFactory.getLogger(TestConsumer.class); + + String providerName = getClass().getName(); + int countTotal; + int sumTotal; + int batchCount; + AuthzAuditEvent lastEvent; + AuthzAuditEvent lastOutOfSeqEvent; + boolean isDown; + + /* + * (non-Javadoc) + * + * @see org.apache.ranger.audit.provider.AuditProvider#log(org.apache.ranger + * .audit.model.AuditEventBase) + */ + @Override + public boolean log(AuditEventBase event) { + if (isDown) { + return false; + } + countTotal++; + if (event instanceof AuthzAuditEvent) { + AuthzAuditEvent azEvent = (AuthzAuditEvent) event; + sumTotal += azEvent.getEventCount(); + logger.info("EVENT: {}", event); + + processEvent(azEvent); + } + return true; + } + + @Override + public boolean logJSON(String jsonStr) { + if (isDown) { + return false; + } + countTotal++; + AuthzAuditEvent event = MiscUtil.fromJson(jsonStr, AuthzAuditEvent.class); + sumTotal += event.getEventCount(); + logger.info("JSON: {}", jsonStr); + processEvent(event); + return true; + } + + @Override + public boolean logJSON(Collection events) { + if (isDown) { + return false; + } + batchCount++; + for (String event : events) { + logJSON(event); + } + return true; + } + + /* + * (non-Javadoc) + * + * @see + * org.apache.ranger.audit.provider.AuditProvider#init(java.util.Properties) + */ + @Override + public void init(Properties prop) { + } + + /* + * (non-Javadoc) + * + * @see org.apache.ranger.audit.provider.AuditProvider#getName() + */ + @Override + public String getName() { + return providerName; + } + + @Override + public boolean log(Collection events) { + if (isDown) { + return false; + } + batchCount++; + for (AuditEventBase event : events) { + log(event); + } + return true; + } + + public int getCountTotal() { + return countTotal; + } + + public int getSumTotal() { + return sumTotal; + } + + public int getBatchCount() { + return batchCount; + } + + /* + * (non-Javadoc) + * + * @see + * org.apache.ranger.audit.provider.AuditProvider#init(java.util.Properties + * , java.lang.String) + */ + @Override + public void init(Properties prop, String basePropertyName) { + } + + /* + * (non-Javadoc) + * + * @see org.apache.ranger.audit.provider.AuditProvider#start() + */ + @Override + public void start() { + // Nothing to do here + } + + /* + * (non-Javadoc) + * + * @see org.apache.ranger.audit.provider.AuditProvider#stop() + */ + @Override + public void stop() { + // Nothing to do here + } + + /* + * (non-Javadoc) + * + * @see org.apache.ranger.audit.provider.AuditProvider#waitToComplete() + */ + @Override + public void waitToComplete() { + } + + /* + * (non-Javadoc) + * + * @see org.apache.ranger.audit.provider.AuditProvider#waitToComplete(long) + */ + @Override + public void waitToComplete(long timeout) { + } + + /* + * (non-Javadoc) + * + * @see org.apache.ranger.audit.provider.AuditProvider#flush() + */ + @Override + public void flush() { + } + + // Local methods + public AuthzAuditEvent isInSequence() { + return lastOutOfSeqEvent; + } + + private void processEvent(AuthzAuditEvent azEvent) { + if (lastEvent == null) { + lastEvent = azEvent; + } else if (lastOutOfSeqEvent == null) { + if (azEvent.getSeqNum() <= lastEvent.getSeqNum()) { + lastOutOfSeqEvent = azEvent; + } + } + } } diff --git a/security-admin/src/test/java/org/apache/ranger/audit/destination/AmazonCloudWatchAuditDestinationTest.java b/security-admin/src/test/java/org/apache/ranger/audit/destination/AmazonCloudWatchAuditDestinationTest.java index dde8bb568d..7b95a86131 100644 --- a/security-admin/src/test/java/org/apache/ranger/audit/destination/AmazonCloudWatchAuditDestinationTest.java +++ b/security-admin/src/test/java/org/apache/ranger/audit/destination/AmazonCloudWatchAuditDestinationTest.java @@ -20,10 +20,11 @@ package org.apache.ranger.audit.destination; import org.apache.ranger.audit.model.AuthzAuditEvent; +import org.junit.Assert; import org.junit.Ignore; import org.junit.Test; -import java.util.Arrays; +import java.util.Collections; import java.util.Date; import java.util.HashSet; import java.util.Properties; @@ -31,18 +32,17 @@ import static org.apache.ranger.audit.destination.AmazonCloudWatchAuditDestination.CONFIG_PREFIX; public class AmazonCloudWatchAuditDestinationTest { - @Test @Ignore // For manual execution only public void testWrite() { AmazonCloudWatchAuditDestination amazonCloudWatchAuditDestination = new AmazonCloudWatchAuditDestination(); - Properties properties = new Properties(); + Properties properties = new Properties(); properties.put(CONFIG_PREFIX + "." + AmazonCloudWatchAuditDestination.PROP_LOG_GROUP_NAME, "test-log-group"); properties.put(CONFIG_PREFIX + "." + AmazonCloudWatchAuditDestination.PROP_LOG_STREAM_PREFIX, "test-log-stream"); amazonCloudWatchAuditDestination.init(properties, CONFIG_PREFIX); - assert amazonCloudWatchAuditDestination.log(Arrays.asList(getAuthzAuditEvent())); + Assert.assertTrue(amazonCloudWatchAuditDestination.log(Collections.singletonList(getAuthzAuditEvent()))); } private AuthzAuditEvent getAuthzAuditEvent() { @@ -63,7 +63,7 @@ private AuthzAuditEvent getAuthzAuditEvent() { event.setEventTime(new Date()); event.setLogType(""); event.setPolicyId(1); - event.setPolicyVersion(1l); + event.setPolicyVersion(1L); event.setRepositoryName(""); event.setRequestData(""); event.setRepositoryType(1); diff --git a/security-admin/src/test/java/org/apache/ranger/biz/TestPolicyAdmin.java b/security-admin/src/test/java/org/apache/ranger/biz/TestPolicyAdmin.java index 0989277dde..24af7df22d 100644 --- a/security-admin/src/test/java/org/apache/ranger/biz/TestPolicyAdmin.java +++ b/security-admin/src/test/java/org/apache/ranger/biz/TestPolicyAdmin.java @@ -36,120 +36,121 @@ import java.io.InputStream; import java.io.InputStreamReader; -import java.util.*; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; public class TestPolicyAdmin { - static Gson gsonBuilder; - - @BeforeClass - public static void setUpBeforeClass() throws Exception { - gsonBuilder = new GsonBuilder().setDateFormat("yyyyMMdd-HH:mm:ss.SSS-Z") - .setPrettyPrinting() - .create(); - } - - @AfterClass - public static void tearDownAfterClass() throws Exception { - } - - @Test - public void testPolicyAdmin_additionalResources() { - String[] testFile = { "/biz/test_policyadmin_additional_resources.json" }; - - runTestsFromResourceFiles(testFile); - } - - private void runTestsFromResourceFiles(String[] resourceNames) { - for(String resourceName : resourceNames) { - InputStream inStream = this.getClass().getResourceAsStream(resourceName); - InputStreamReader reader = new InputStreamReader(inStream); - - runTests(reader, resourceName); - } - } - - private void runTests(InputStreamReader reader, String testName) { - PolicyAdminTestCase testCase = gsonBuilder.fromJson(reader, PolicyAdminTestCase.class); - - assertTrue("invalid input: " + testName, testCase != null && testCase.servicePolicies != null && testCase.tests != null && testCase.servicePolicies.getPolicies() != null); - - RangerPolicyEngineOptions policyEngineOptions = new RangerPolicyEngineOptions(); - - policyEngineOptions.evaluatorType = RangerPolicyEvaluator.EVALUATOR_TYPE_OPTIMIZED; - policyEngineOptions.cacheAuditResults = false; - policyEngineOptions.disableContextEnrichers = true; - policyEngineOptions.disableCustomConditions = true; - policyEngineOptions.evaluateDelegateAdminOnly = true; - - RangerPluginContext pluginContext = new RangerPluginContext(new RangerPluginConfig("hive", null, "test-policydb", "cl1", "on-prem", policyEngineOptions)); - RangerPolicyAdmin policyAdmin = new RangerPolicyAdminImpl(testCase.servicePolicies, pluginContext, null); - - for(TestData test : testCase.tests) { - if (test.userGroups == null) { - test.userGroups = Collections.emptySet(); - } - - if (test.allowedPolicies != null) { - Set allowedPolicies = new HashSet<>(); - - for (RangerPolicy policy : testCase.servicePolicies.getPolicies()) { - boolean isAllowed = test.isModifyAccess ? policyAdmin.isDelegatedAdminAccessAllowedForModify(policy, test.user, test.userGroups, null, null) - : policyAdmin.isDelegatedAdminAccessAllowedForRead(policy, test.user, test.userGroups, null, null); - - if (isAllowed) { - allowedPolicies.add(policy.getId()); - } - } - - assertEquals("allowed-policy count mismatch! - " + test.name, test.allowedPolicies.size(), allowedPolicies.size()); - - assertEquals("allowed-policy list mismatch! - " + test.name, test.allowedPolicies, allowedPolicies); - } else { - RangerPolicy policy = new RangerPolicy(); - RangerPolicyItem policyItem = new RangerPolicyItem(); - - policyItem.addUser(test.user); - policyItem.addGroups(test.userGroups); - - for (String accessType : test.accessTypes) { - policyItem.addAccess(new RangerPolicy.RangerPolicyItemAccess(accessType)); - } - - policy.setResources(test.resources); - policy.setAdditionalResources(test.additionalResources); - policy.addPolicyItem(policyItem); - - final boolean expected = test.result; - final boolean result; - - if (test.isModifyAccess) { - result = policyAdmin.isDelegatedAdminAccessAllowedForModify(policy, test.user, test.userGroups, null, null); - } else { - result = policyAdmin.isDelegatedAdminAccessAllowedForRead(policy, test.user, test.userGroups, null, null); - } - - assertEquals("isAccessAllowed mismatched! - " + test.name, expected, result); - } - } - } - - static class PolicyAdminTestCase { - public ServicePolicies servicePolicies; - public List tests; - - class TestData { - public String name; - public Map resources; - public List> additionalResources; - public String user; - public Set userGroups; - public Set accessTypes; - public boolean isModifyAccess; - public boolean result; - public Set allowedPolicies; - } - } + static Gson gsonBuilder; + + @BeforeClass + public static void setUpBeforeClass() { + gsonBuilder = new GsonBuilder().setDateFormat("yyyyMMdd-HH:mm:ss.SSS-Z").setPrettyPrinting().create(); + } + + @AfterClass + public static void tearDownAfterClass() { + } + + @Test + public void testPolicyAdmin_additionalResources() { + String[] testFile = {"/biz/test_policyadmin_additional_resources.json"}; + + runTestsFromResourceFiles(testFile); + } + + private void runTestsFromResourceFiles(String[] resourceNames) { + for (String resourceName : resourceNames) { + InputStream inStream = this.getClass().getResourceAsStream(resourceName); + InputStreamReader reader = new InputStreamReader(inStream); + + runTests(reader, resourceName); + } + } + + private void runTests(InputStreamReader reader, String testName) { + PolicyAdminTestCase testCase = gsonBuilder.fromJson(reader, PolicyAdminTestCase.class); + + assertTrue("invalid input: " + testName, testCase != null && testCase.servicePolicies != null && testCase.tests != null && testCase.servicePolicies.getPolicies() != null); + + RangerPolicyEngineOptions policyEngineOptions = new RangerPolicyEngineOptions(); + + policyEngineOptions.evaluatorType = RangerPolicyEvaluator.EVALUATOR_TYPE_OPTIMIZED; + policyEngineOptions.cacheAuditResults = false; + policyEngineOptions.disableContextEnrichers = true; + policyEngineOptions.disableCustomConditions = true; + policyEngineOptions.evaluateDelegateAdminOnly = true; + + RangerPluginContext pluginContext = new RangerPluginContext(new RangerPluginConfig("hive", null, "test-policydb", "cl1", "on-prem", policyEngineOptions)); + RangerPolicyAdmin policyAdmin = new RangerPolicyAdminImpl(testCase.servicePolicies, pluginContext, null); + + for (TestData test : testCase.tests) { + if (test.userGroups == null) { + test.userGroups = Collections.emptySet(); + } + + if (test.allowedPolicies != null) { + Set allowedPolicies = new HashSet<>(); + + for (RangerPolicy policy : testCase.servicePolicies.getPolicies()) { + boolean isAllowed = test.isModifyAccess ? policyAdmin.isDelegatedAdminAccessAllowedForModify(policy, test.user, test.userGroups, null, null) + : policyAdmin.isDelegatedAdminAccessAllowedForRead(policy, test.user, test.userGroups, null, null); + + if (isAllowed) { + allowedPolicies.add(policy.getId()); + } + } + + assertEquals("allowed-policy count mismatch! - " + test.name, test.allowedPolicies.size(), allowedPolicies.size()); + assertEquals("allowed-policy list mismatch! - " + test.name, test.allowedPolicies, allowedPolicies); + } else { + RangerPolicy policy = new RangerPolicy(); + RangerPolicyItem policyItem = new RangerPolicyItem(); + + policyItem.addUser(test.user); + policyItem.addGroups(test.userGroups); + + for (String accessType : test.accessTypes) { + policyItem.addAccess(new RangerPolicy.RangerPolicyItemAccess(accessType)); + } + + policy.setResources(test.resources); + policy.setAdditionalResources(test.additionalResources); + policy.addPolicyItem(policyItem); + + final boolean expected = test.result; + final boolean result; + + if (test.isModifyAccess) { + result = policyAdmin.isDelegatedAdminAccessAllowedForModify(policy, test.user, test.userGroups, null, null); + } else { + result = policyAdmin.isDelegatedAdminAccessAllowedForRead(policy, test.user, test.userGroups, null, null); + } + + assertEquals("isAccessAllowed mismatched! - " + test.name, expected, result); + } + } + } + + static class PolicyAdminTestCase { + public ServicePolicies servicePolicies; + public List tests; + + class TestData { + public String name; + public Map resources; + public List> additionalResources; + public String user; + public Set userGroups; + public Set accessTypes; + public boolean isModifyAccess; + public boolean result; + public Set allowedPolicies; + } + } } diff --git a/security-admin/src/test/java/org/apache/ranger/biz/TestPolicyDb.java b/security-admin/src/test/java/org/apache/ranger/biz/TestPolicyDb.java index 5b7e6b6afd..a86206b125 100644 --- a/security-admin/src/test/java/org/apache/ranger/biz/TestPolicyDb.java +++ b/security-admin/src/test/java/org/apache/ranger/biz/TestPolicyDb.java @@ -19,142 +19,136 @@ package org.apache.ranger.biz; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import java.io.InputStream; -import java.io.InputStreamReader; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; import org.apache.ranger.authorization.hadoop.config.RangerPluginConfig; +import org.apache.ranger.biz.TestPolicyDb.PolicyDbTestCase.TestData; import org.apache.ranger.plugin.model.RangerPolicy; import org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyResource; import org.apache.ranger.plugin.model.RangerServiceDef; import org.apache.ranger.plugin.policyengine.RangerPluginContext; import org.apache.ranger.plugin.policyengine.RangerPolicyEngineOptions; -import org.apache.ranger.biz.TestPolicyDb.PolicyDbTestCase.TestData; import org.apache.ranger.plugin.policyevaluator.RangerPolicyEvaluator; import org.apache.ranger.plugin.util.ServicePolicies; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; public class TestPolicyDb { - static Gson gsonBuilder; + static Gson gsonBuilder; static RangerServiceDef hdfsServiceDef; static RangerServiceDef hiveServiceDef; static RangerServiceDef hbaseServiceDef; static RangerServiceDef tagServiceDef; - @BeforeClass - public static void setUpBeforeClass() throws Exception { - gsonBuilder = new GsonBuilder().setDateFormat("yyyyMMdd-HH:mm:ss.SSS-Z") - .setPrettyPrinting() - .create(); - initializeServiceDefs(); - } - - private static void initializeServiceDefs() { - hdfsServiceDef = readServiceDef("hdfs"); - hiveServiceDef = readServiceDef("hive"); + @BeforeClass + public static void setUpBeforeClass() { + gsonBuilder = new GsonBuilder().setDateFormat("yyyyMMdd-HH:mm:ss.SSS-Z").setPrettyPrinting().create(); + initializeServiceDefs(); + } + + @AfterClass + public static void tearDownAfterClass() { + } + + @Test + public void testPolicyDb_hdfs() { + String[] hdfsTestResourceFiles = {"/biz/test_policydb_hdfs.json"}; + + runTestsFromResourceFiles(hdfsTestResourceFiles, hdfsServiceDef); + } + + @Test + public void testPolicyDb_hive() { + String[] hiveTestResourceFiles = {"/biz/test_policydb_hive.json"}; + + runTestsFromResourceFiles(hiveTestResourceFiles, hiveServiceDef); + } + + private static void initializeServiceDefs() { + hdfsServiceDef = readServiceDef("hdfs"); + hiveServiceDef = readServiceDef("hive"); hbaseServiceDef = readServiceDef("hbase"); - tagServiceDef = readServiceDef("tag"); + tagServiceDef = readServiceDef("tag"); } private static RangerServiceDef readServiceDef(String name) { - InputStream inStream = TestPolicyDb.class.getResourceAsStream("/admin/service-defs/test-" + name + "-servicedef.json"); - InputStreamReader reader = new InputStreamReader(inStream); + InputStream inStream = TestPolicyDb.class.getResourceAsStream("/admin/service-defs/test-" + name + "-servicedef.json"); + InputStreamReader reader = new InputStreamReader(inStream); return gsonBuilder.fromJson(reader, RangerServiceDef.class); + } + private void runTestsFromResourceFiles(String[] resourceNames, RangerServiceDef serviceDef) { + for (String resourceName : resourceNames) { + InputStream inStream = this.getClass().getResourceAsStream(resourceName); + InputStreamReader reader = new InputStreamReader(inStream); + + runTests(reader, resourceName, serviceDef); + } } - @AfterClass - public static void tearDownAfterClass() throws Exception { - } + private void runTests(InputStreamReader reader, String testName, RangerServiceDef serviceDef) { + PolicyDbTestCase testCase = gsonBuilder.fromJson(reader, PolicyDbTestCase.class); + if (serviceDef != null) { + // Override serviceDef in the json test-file with a global service-def + testCase.servicePolicies.setServiceDef(serviceDef); + } - @Test - public void testPolicyDb_hdfs() { + assertTrue("invalid input: " + testName, testCase != null && testCase.servicePolicies != null && testCase.tests != null && testCase.servicePolicies.getPolicies() != null); - String[] hdfsTestResourceFiles = { "/biz/test_policydb_hdfs.json" }; + RangerPolicyEngineOptions policyEngineOptions = new RangerPolicyEngineOptions(); - runTestsFromResourceFiles(hdfsTestResourceFiles, hdfsServiceDef); - } + policyEngineOptions.evaluatorType = RangerPolicyEvaluator.EVALUATOR_TYPE_OPTIMIZED; + policyEngineOptions.cacheAuditResults = false; + policyEngineOptions.disableContextEnrichers = true; + policyEngineOptions.disableCustomConditions = true; - @Test - public void testPolicyDb_hive() { - String[] hiveTestResourceFiles = { "/biz/test_policydb_hive.json" }; + RangerPluginContext pluginContext = new RangerPluginContext(new RangerPluginConfig("hive", null, "test-policydb", "cl1", "on-prem", policyEngineOptions)); + RangerPolicyAdmin policyAdmin = new RangerPolicyAdminImpl(testCase.servicePolicies, pluginContext, null); - runTestsFromResourceFiles(hiveTestResourceFiles, hiveServiceDef); + for (TestData test : testCase.tests) { + boolean expected = test.result; + + if (test.allowedPolicies != null) { + List allowedPolicies = policyAdmin.getAllowedUnzonedPolicies(test.user, test.userGroups, test.accessType); + + assertEquals("allowed-policy count mismatch!", test.allowedPolicies.size(), allowedPolicies.size()); + + Set allowedPolicyIds = new HashSet<>(); + for (RangerPolicy allowedPolicy : allowedPolicies) { + allowedPolicyIds.add(allowedPolicy.getId()); + } + assertEquals("allowed-policy list mismatch!", test.allowedPolicies, allowedPolicyIds); + } else { + boolean result = policyAdmin.isAccessAllowedByUnzonedPolicies(test.resources, null, test.user, test.userGroups, test.accessType); + + assertEquals("isAccessAllowed mismatched! - " + test.name, expected, result); + } + } } - private void runTestsFromResourceFiles(String[] resourceNames, RangerServiceDef serviceDef) { - for(String resourceName : resourceNames) { - InputStream inStream = this.getClass().getResourceAsStream(resourceName); - InputStreamReader reader = new InputStreamReader(inStream); - - runTests(reader, resourceName, serviceDef); - } - } - - private void runTests(InputStreamReader reader, String testName, RangerServiceDef serviceDef) { - PolicyDbTestCase testCase = gsonBuilder.fromJson(reader, PolicyDbTestCase.class); - if (serviceDef != null) { - // Override serviceDef in the json test-file with a global service-def - testCase.servicePolicies.setServiceDef(serviceDef); - } - - assertTrue("invalid input: " + testName, testCase != null && testCase.servicePolicies != null && testCase.tests != null && testCase.servicePolicies.getPolicies() != null); - - - RangerPolicyEngineOptions policyEngineOptions = new RangerPolicyEngineOptions(); - - policyEngineOptions.evaluatorType = RangerPolicyEvaluator.EVALUATOR_TYPE_OPTIMIZED; - policyEngineOptions.cacheAuditResults = false; - policyEngineOptions.disableContextEnrichers = true; - policyEngineOptions.disableCustomConditions = true; - - RangerPluginContext pluginContext = new RangerPluginContext(new RangerPluginConfig("hive", null, "test-policydb", "cl1", "on-prem", policyEngineOptions)); - RangerPolicyAdmin policyAdmin = new RangerPolicyAdminImpl(testCase.servicePolicies, pluginContext, null); - - for(TestData test : testCase.tests) { - boolean expected = test.result; - - if(test.allowedPolicies != null) { - List allowedPolicies = policyAdmin.getAllowedUnzonedPolicies(test.user, test.userGroups, test.accessType); - - assertEquals("allowed-policy count mismatch!", test.allowedPolicies.size(), allowedPolicies.size()); - - Set allowedPolicyIds = new HashSet<>(); - for(RangerPolicy allowedPolicy : allowedPolicies) { - allowedPolicyIds.add(allowedPolicy.getId()); - } - assertEquals("allowed-policy list mismatch!", test.allowedPolicies, allowedPolicyIds); - } else { - boolean result = policyAdmin.isAccessAllowedByUnzonedPolicies(test.resources, null, test.user, test.userGroups, test.accessType); - - assertEquals("isAccessAllowed mismatched! - " + test.name, expected, result); - } - } - } - - static class PolicyDbTestCase { - public ServicePolicies servicePolicies; - public List tests; - - class TestData { - public String name; - public Map resources; - public String user; - public Set userGroups; - public String accessType; - public boolean result; - public Set allowedPolicies; - } - } + static class PolicyDbTestCase { + public ServicePolicies servicePolicies; + public List tests; + + class TestData { + public String name; + public Map resources; + public String user; + public Set userGroups; + public String accessType; + public boolean result; + public Set allowedPolicies; + } + } } diff --git a/security-admin/src/test/java/org/apache/ranger/biz/TestRangerBizUtil.java b/security-admin/src/test/java/org/apache/ranger/biz/TestRangerBizUtil.java index 5fca22d939..66cce52384 100644 --- a/security-admin/src/test/java/org/apache/ranger/biz/TestRangerBizUtil.java +++ b/security-admin/src/test/java/org/apache/ranger/biz/TestRangerBizUtil.java @@ -16,13 +16,6 @@ */ package org.apache.ranger.biz; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - -import javax.servlet.http.HttpServletResponse; -import javax.ws.rs.WebApplicationException; - import org.apache.ranger.common.AppConstants; import org.apache.ranger.common.ContextUtil; import org.apache.ranger.common.MessageEnums; @@ -56,592 +49,541 @@ import org.mockito.Mockito; import org.mockito.junit.MockitoJUnitRunner; -@RunWith(MockitoJUnitRunner.class) -public class TestRangerBizUtil { - - private Long id = 1L; - private String resourceName = "hadoopdev"; - - @InjectMocks - RangerBizUtil rangerBizUtil = new RangerBizUtil(); - - @Mock - RangerDaoManager daoManager; - - @Mock - StringUtil stringUtil; - - @Mock - VXUser vXUser; - - @Mock - UserMgr userMgr; - - @Mock - ContextUtil contextUtil; - - @Mock - RangerSecurityContext context; - - @Mock - UserSessionBase currentUserSession; - - @Mock - RESTErrorUtil restErrorUtil; - - @Mock - VXResponse vXResponse; - - @Rule - public ExpectedException thrown = ExpectedException.none(); - - @Before - public void setup(){ - RangerSecurityContext context = new RangerSecurityContext(); - context.setUserSession(new UserSessionBase()); - RangerContextHolder.setSecurityContext(context); - -// RESTErrorUtil restErrorUtil; - } - - @Test - public void testGetDBFlavor(){ - int dbFlavor = RangerBizUtil.getDBFlavor(); - Assert.assertEquals(AppConstants.DB_FLAVOR_UNKNOWN, dbFlavor); - } - - @Test - public void testGetDBFlavorType(){ - int dbFlavor = 1; - String dbFlavourType = RangerBizUtil.getDBFlavorType(dbFlavor); - Assert.assertEquals("MYSQL", dbFlavourType); - dbFlavor = 2; - dbFlavourType = RangerBizUtil.getDBFlavorType(dbFlavor); - Assert.assertEquals("ORACLE", dbFlavourType); - } - - @Test - public void testGetDBQuery(){ - int dbFlavor = 1; - String dbQuery = RangerBizUtil.getDBVersionQuery(dbFlavor); - Assert.assertEquals("SELECT version()", dbQuery); - dbFlavor = 2; - dbQuery =RangerBizUtil.getDBVersionQuery(dbFlavor); - Assert.assertEquals("SELECT banner from v$version where rownum<2", dbQuery); - dbFlavor = 3; - dbQuery =RangerBizUtil.getDBVersionQuery(dbFlavor); - Assert.assertEquals("SELECT version()", dbQuery); - dbFlavor = 5; - dbQuery =RangerBizUtil.getDBVersionQuery(dbFlavor); - Assert.assertEquals("SELECT @@version", dbQuery); - } - - @Test - public void testHasPermission_When_disableAccessControl(){ - VXResource vXResource = null; - rangerBizUtil.enableResourceAccessControl = false; - VXResponse resp = rangerBizUtil.hasPermission(vXResource, AppConstants.XA_PERM_TYPE_UNKNOWN); - Assert.assertNotNull(resp); - } - - @Test - public void testHasPermission_When_NoResource(){ - VXResource vXResource = null; - VXResponse resp = rangerBizUtil.hasPermission(vXResource, AppConstants.XA_PERM_TYPE_UNKNOWN); - Assert.assertNotNull(resp); - Assert.assertEquals(VXResponse.STATUS_ERROR, resp.getStatusCode()); - Assert.assertEquals("Please provide valid policy.", resp.getMsgDesc()); - } - - @Test - public void testHasPermission_emptyResourceName(){ - VXResource vXResource = new VXResource(); - vXResource.setAssetId(12345L); - XXPortalUser portalUser = new XXPortalUser(); - portalUser.setId(id); - portalUser.setLoginId("12121"); - RangerContextHolder.getSecurityContext().getUserSession().setXXPortalUser(portalUser); - - XXUserDao xxUserDao = Mockito.mock(XXUserDao.class); - XXPortalUserDao userDao = Mockito.mock(XXPortalUserDao.class); - XXUser xxUser = new XXUser(); - XXAsset xxAsset = new XXAsset(); - List lst = new ArrayList(); - XXResourceDao xxResourceDao = Mockito.mock(XXResourceDao.class); - XXAssetDao xxAssetDao = Mockito.mock(XXAssetDao.class); - Mockito.when(daoManager.getXXPortalUser()).thenReturn(userDao); - Mockito.when(userDao.getById(Mockito.anyLong())).thenReturn(portalUser); - Mockito.when(daoManager.getXXUser()).thenReturn(xxUserDao); - Mockito.when(xxUserDao.findByUserName(Mockito.anyString())).thenReturn(xxUser); - Mockito.when(daoManager.getXXResource()).thenReturn(xxResourceDao); - Mockito.when(xxResourceDao.findByAssetIdAndResourceStatus(Mockito.anyLong(),Mockito.anyInt())).thenReturn(lst); - Mockito.when(daoManager.getXXAsset()).thenReturn(xxAssetDao); - Mockito.when(xxAssetDao.getById(Mockito.anyLong())).thenReturn(xxAsset); - VXResponse resp = rangerBizUtil.hasPermission(vXResource, AppConstants.XA_PERM_TYPE_UNKNOWN); - Mockito.verify(daoManager).getXXPortalUser(); - Mockito.verify(userDao).getById(Mockito.anyLong()); - Mockito.verify(daoManager).getXXUser(); - Mockito.verify(xxUserDao).findByUserName(Mockito.anyString()); - Assert.assertNotNull(resp); - Assert.assertEquals(VXResponse.STATUS_ERROR, resp.getStatusCode()); - Assert.assertEquals("Permission Denied !", resp.getMsgDesc()); - } - - @Test - public void testHasPermission_isAdmin(){ - VXResource vXResource = new VXResource(); - vXResource.setName(resourceName); - vXResource.setAssetId(id); - UserSessionBase currentUserSession = ContextUtil.getCurrentUserSession(); - currentUserSession.setUserAdmin(true); - VXResponse resp = rangerBizUtil.hasPermission(vXResource, AppConstants.XA_PERM_TYPE_UNKNOWN); - Assert.assertNotNull(resp); - Assert.assertEquals(VXResponse.STATUS_SUCCESS, resp.getStatusCode()); - } - - @Test - public void testIsNotAdmin(){ - boolean isAdminChk = rangerBizUtil.isAdmin(); - Assert.assertFalse(isAdminChk); - } - - @Test - public void testIsAdmin(){ - UserSessionBase currentUserSession = ContextUtil.getCurrentUserSession(); - currentUserSession.setUserAdmin(true); - boolean isAdminChk = rangerBizUtil.isAdmin(); - Assert.assertTrue(isAdminChk); - } - - @Test - public void testUserSessionNull_forIsAdmin(){ - RangerContextHolder.setSecurityContext(null); - boolean isAdminChk = rangerBizUtil.isAdmin(); - Assert.assertFalse(isAdminChk); - } - - @Test - public void testGetXUserId_NoUserSession(){ - RangerContextHolder.setSecurityContext(null); - Long chk = rangerBizUtil.getXUserId(); - Assert.assertNull(chk); - } - - @Test - public void testGetXUserId_NoUser(){ - RangerSecurityContext context = new RangerSecurityContext(); - context.setUserSession(new UserSessionBase()); - RangerContextHolder.setSecurityContext(context); - XXPortalUser xxPortalUser = new XXPortalUser(); - xxPortalUser.setId(id); - xxPortalUser.setLoginId("12121"); - context.getUserSession().setXXPortalUser(xxPortalUser); - - XXUser xxUser = new XXUser(); - XXUserDao xxUserDao = Mockito.mock(XXUserDao.class); - XXPortalUserDao xxPortalUserDao = Mockito.mock(XXPortalUserDao.class); - Mockito.when(daoManager.getXXPortalUser()).thenReturn(xxPortalUserDao); - Mockito.when(xxPortalUserDao.getById(Mockito.anyLong())).thenReturn(xxPortalUser); - Mockito.when(daoManager.getXXUser()).thenReturn(xxUserDao); - Mockito.when(xxUserDao.findByUserName(Mockito.anyString())).thenReturn(xxUser); - Long chk = rangerBizUtil.getXUserId(); - Mockito.verify(daoManager).getXXPortalUser(); - Mockito.verify(xxPortalUserDao).getById(Mockito.anyLong()); - Mockito.verify(daoManager).getXXUser(); - Mockito.verify(xxUserDao).findByUserName(Mockito.anyString()); - Assert.assertNull(chk); - } - - @Test - public void testGetXUserId(){ - XXPortalUser xxPortalUser = new XXPortalUser(); - xxPortalUser.setId(id); - xxPortalUser.setLoginId("12121"); - XXUser xxUser = new XXUser(); - xxUser.setId(id); - XXPortalUserDao xxPortalUserDao = Mockito.mock(XXPortalUserDao.class); - XXUserDao xxUserDao = Mockito.mock(XXUserDao.class); - RangerSecurityContext context = new RangerSecurityContext(); - UserSessionBase userSessionBase = new UserSessionBase(); - userSessionBase.setUserAdmin(true); - context.setUserSession(userSessionBase); - userSessionBase.setXXPortalUser(xxPortalUser); - RangerContextHolder.setSecurityContext(context); - Mockito.when(daoManager.getXXPortalUser()).thenReturn(xxPortalUserDao); - Mockito.when(xxPortalUserDao.getById(Mockito.anyLong())).thenReturn(xxPortalUser); - Mockito.when(daoManager.getXXUser()).thenReturn(xxUserDao); - Mockito.when(xxUserDao.findByUserName(Mockito.anyString())).thenReturn(xxUser); - Long chk = rangerBizUtil.getXUserId(); - Mockito.verify(daoManager).getXXPortalUser(); - Mockito.verify(xxPortalUserDao).getById(Mockito.anyLong()); - Mockito.verify(daoManager).getXXUser(); - Mockito.verify(xxUserDao).findByUserName(Mockito.anyString()); - Assert.assertEquals(chk, id); - } - - @Test - public void testReplaceMetaChars_PathEmpty(){ - String path = ""; - String pathChk = rangerBizUtil.replaceMetaChars(path); - Assert.assertFalse(pathChk.contains("\\*")); - Assert.assertFalse(pathChk.contains("\\?")); - } - - @Test - public void testReplaceMetaChars_NoMetaChars(){ - String path = "\\Demo\\Test"; - String pathChk = rangerBizUtil.replaceMetaChars(path); - Assert.assertFalse(pathChk.contains("\\*")); - Assert.assertFalse(pathChk.contains("\\?")); - } - - @Test - public void testReplaceMetaChars_PathNull(){ - String path = null; - String pathChk = rangerBizUtil.replaceMetaChars(path); - Assert.assertNull(pathChk); - } - - @Test - public void testReplaceMetaChars(){ - String path = "\\Demo\\Test\\*\\?"; - String pathChk = rangerBizUtil.replaceMetaChars(path); - Assert.assertFalse(pathChk.contains("\\*")); - Assert.assertFalse(pathChk.contains("\\?")); - } - - @Test - public void testGeneratePublicName(){ - String firstName = "Test123456789123456789"; - String lastName = "Unit"; - String publicNameChk = rangerBizUtil.generatePublicName(firstName, lastName); - Assert.assertEquals("Test12345678... U.", publicNameChk); - } - - @Test - public void testGeneratePublicName_fNameLessThanMax(){ - String firstName = "Test"; - String lastName = ""; - String publicNameChk = rangerBizUtil.generatePublicName(firstName, lastName); - Assert.assertNull(publicNameChk); - } - - @Test - public void testGeneratePublicName_withPortalUser(){ - VXPortalUser vXPortalUser = new VXPortalUser(); - vXPortalUser.setFirstName("Test"); - vXPortalUser.setLastName(null); - String publicNameChk = rangerBizUtil.generatePublicName(vXPortalUser, null); - Assert.assertNull(publicNameChk); - } - - - @Test - public void testMatchHdfsPolicy_NoResourceName(){ - boolean bnlChk = rangerBizUtil.matchHbasePolicy(null, null, null, id, AppConstants.XA_PERM_TYPE_UNKNOWN); - Assert.assertFalse(bnlChk); - } - - @Test - public void testMatchHdfsPolicy_NoResourceList(){ - boolean bnlChk = rangerBizUtil.matchHbasePolicy(resourceName, null, null, id, AppConstants.XA_PERM_TYPE_UNKNOWN); - Assert.assertFalse(bnlChk); - } - - @Test - public void testMatchHdfsPolicy_NoUserId(){ - VXResponse vXResponse = new VXResponse(); - List xResourceList = new ArrayList(); - XXResource xXResource = new XXResource(); - xXResource.setId(id); - xXResource.setName(resourceName); - xXResource.setIsRecursive(AppConstants.BOOL_TRUE); - xXResource.setResourceStatus(AppConstants.STATUS_ENABLED); - xResourceList.add(xXResource); - boolean bnlChk = rangerBizUtil.matchHbasePolicy(resourceName, xResourceList, vXResponse, null, AppConstants.XA_PERM_TYPE_UNKNOWN); - Assert.assertFalse(bnlChk); - } - - @Test - public void testMatchHdfsPolicy_NoPremission(){ - VXResponse vXResponse = new VXResponse(); - List xResourceList = new ArrayList(); - XXResource xXResource = new XXResource(); - xXResource.setId(id); - xXResource.setName(resourceName); - xXResource.setIsRecursive(AppConstants.BOOL_TRUE); - xXResource.setResourceStatus(AppConstants.STATUS_ENABLED); - xResourceList.add(xXResource); - Mockito.when(stringUtil.split(Mockito.anyString(), Mockito.anyString())).thenReturn(new String[0]); - boolean bnlChk = rangerBizUtil.matchHbasePolicy("/*/*/*", xResourceList, vXResponse, id, AppConstants.XA_PERM_TYPE_UNKNOWN); - Mockito.verify(stringUtil).split(Mockito.anyString(), Mockito.anyString()); - Assert.assertFalse(bnlChk); - } - - @Test - public void testMatchHivePolicy_NoResourceName(){ - boolean bnlChk = rangerBizUtil.matchHivePolicy(null, null, null, 0); - Assert.assertFalse(bnlChk); - - } - - @Test - public void testMatchHivePolicy_NoResourceList(){ - boolean bnlChk = rangerBizUtil.matchHivePolicy(resourceName, null, null, 0); - Assert.assertFalse(bnlChk); - - } - - @Test - public void testMatchHivePolicy_NoUserId(){ - List xResourceList = new ArrayList(); - XXResource xXResource = new XXResource(); - xXResource.setId(id); - xXResource.setName(resourceName); - xXResource.setIsRecursive(AppConstants.BOOL_TRUE); - xXResource.setResourceStatus(AppConstants.STATUS_ENABLED); - xResourceList.add(xXResource); - boolean bnlChk = rangerBizUtil.matchHivePolicy(resourceName, xResourceList, null, 0); - Assert.assertFalse(bnlChk); - - } - - @Test - public void testMatchHivePolicy_NoPremission(){ - List xResourceList = new ArrayList(); - XXResource xXResource = new XXResource(); - xXResource.setId(id); - xXResource.setName(resourceName); - xXResource.setIsRecursive(AppConstants.BOOL_TRUE); - xXResource.setResourceStatus(AppConstants.STATUS_ENABLED); - xResourceList.add(xXResource); - Mockito.when(stringUtil.split(Mockito.anyString(), Mockito.anyString())).thenReturn(new String[0]); - boolean bnlChk = rangerBizUtil.matchHivePolicy("/*/*/*", xResourceList, id, 0); - Assert.assertFalse(bnlChk); - } - - @Test - public void testMatchHivePolicy(){ - List xResourceList = new ArrayList(); - XXResource xXResource = new XXResource(); - xXResource.setId(5L); - xXResource.setName(resourceName); - xXResource.setIsRecursive(AppConstants.BOOL_TRUE); - xXResource.setResourceStatus(AppConstants.STATUS_ENABLED); - xResourceList.add(xXResource); - Mockito.when(stringUtil.split(Mockito.anyString(), Mockito.anyString())).thenReturn(new String[0]); - boolean bnlChk = rangerBizUtil.matchHivePolicy("/*/*/*", xResourceList, id, 17); - Mockito.verify(stringUtil).split(Mockito.anyString(), Mockito.anyString()); - Assert.assertFalse(bnlChk); - } - - @Test - public void testCheckUserAccessibleThrowErrorForKeyAdminAndUserRoleSysAdmin() - throws Exception { - - Collection roleList = new ArrayList(); - roleList.add(RangerConstants.ROLE_SYS_ADMIN); - Mockito.when(userMgr.getRolesByLoginId(vXUser.getName())).thenReturn( - roleList); - Mockito.when(vXUser.getUserRoleList()).thenReturn(roleList); - - currentUserSession.setKeyAdmin(true); - RangerSecurityContext context = new RangerSecurityContext(); - context.setUserSession(currentUserSession); - RangerContextHolder.setSecurityContext(context); - - Mockito.when(currentUserSession.isKeyAdmin()).thenReturn(true); - - WebApplicationException webExp = new WebApplicationException(); - - Mockito.when( - restErrorUtil.createRESTException( - "Logged in user is not allowed to create/update user", - MessageEnums.OPER_NO_PERMISSION)).thenReturn(webExp); - - thrown.expect(WebApplicationException.class); - - rangerBizUtil.checkUserAccessible(vXUser); - - Mockito.verify(restErrorUtil).createRESTException( - "Logged in user is not allowed to create/update user", - MessageEnums.OPER_NO_PERMISSION); - - } - - @Test - public void testCheckUserAccessibleThrowErrorForKeyAdminAndUserRoleAdminAuditor() - throws Exception { - - Collection roleList = new ArrayList(); - roleList.add(RangerConstants.ROLE_ADMIN_AUDITOR); - Mockito.when(userMgr.getRolesByLoginId(vXUser.getName())).thenReturn( - roleList); - Mockito.when(vXUser.getUserRoleList()).thenReturn(roleList); - - currentUserSession.setKeyAdmin(true); - RangerSecurityContext context = new RangerSecurityContext(); - context.setUserSession(currentUserSession); - RangerContextHolder.setSecurityContext(context); - - Mockito.when(currentUserSession.isKeyAdmin()).thenReturn(true); - - WebApplicationException webExp = new WebApplicationException(); - - Mockito.when( - restErrorUtil.createRESTException( - "Logged in user is not allowed to create/update user", - MessageEnums.OPER_NO_PERMISSION)).thenReturn(webExp); - - thrown.expect(WebApplicationException.class); - - rangerBizUtil.checkUserAccessible(vXUser); - - Mockito.verify(restErrorUtil).createRESTException( - "Logged in user is not allowed to create/update user", - MessageEnums.OPER_NO_PERMISSION); - - } - - @Test - public void testCheckUserAccessibleSuccessForKeyAdmin(){ - Collection roleList = new ArrayList(); - roleList.add(RangerConstants.ROLE_KEY_ADMIN); - roleList.add(RangerConstants.ROLE_KEY_ADMIN_AUDITOR); - Mockito.when(userMgr.getRolesByLoginId(vXUser.getName())).thenReturn( - roleList); - Mockito.when(vXUser.getUserRoleList()).thenReturn(roleList); +import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.WebApplicationException; - currentUserSession.setKeyAdmin(true); +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; - RangerSecurityContext context = new RangerSecurityContext(); - context.setUserSession(currentUserSession); - RangerContextHolder.setSecurityContext(context); +@RunWith(MockitoJUnitRunner.class) +public class TestRangerBizUtil { + @Rule + public ExpectedException thrown = ExpectedException.none(); + @InjectMocks + RangerBizUtil rangerBizUtil = new RangerBizUtil(); + @Mock + RangerDaoManager daoManager; + @Mock + StringUtil stringUtil; + @Mock + VXUser vXUser; + @Mock + UserMgr userMgr; + @Mock + ContextUtil contextUtil; + @Mock + RangerSecurityContext context; + @Mock + UserSessionBase currentUserSession; + @Mock + RESTErrorUtil restErrorUtil; + @Mock + VXResponse vXResponse; + private final Long id = 1L; + private final String resourceName = "hadoopdev"; + + @Before + public void setup() { + RangerSecurityContext context = new RangerSecurityContext(); + context.setUserSession(new UserSessionBase()); + RangerContextHolder.setSecurityContext(context); + } + + @Test + public void testGetDBFlavor() { + int dbFlavor = RangerBizUtil.getDBFlavor(); + Assert.assertEquals(AppConstants.DB_FLAVOR_UNKNOWN, dbFlavor); + } + + @Test + public void testGetDBFlavorType() { + int dbFlavor = 1; + String dbFlavourType = RangerBizUtil.getDBFlavorType(dbFlavor); + Assert.assertEquals("MYSQL", dbFlavourType); + dbFlavor = 2; + dbFlavourType = RangerBizUtil.getDBFlavorType(dbFlavor); + Assert.assertEquals("ORACLE", dbFlavourType); + } + + @Test + public void testGetDBQuery() { + int dbFlavor = 1; + String dbQuery = RangerBizUtil.getDBVersionQuery(dbFlavor); + Assert.assertEquals("SELECT version()", dbQuery); + dbFlavor = 2; + dbQuery = RangerBizUtil.getDBVersionQuery(dbFlavor); + Assert.assertEquals("SELECT banner from v$version where rownum<2", dbQuery); + dbFlavor = 3; + dbQuery = RangerBizUtil.getDBVersionQuery(dbFlavor); + Assert.assertEquals("SELECT version()", dbQuery); + dbFlavor = 5; + dbQuery = RangerBizUtil.getDBVersionQuery(dbFlavor); + Assert.assertEquals("SELECT @@version", dbQuery); + } + + @Test + public void testHasPermission_When_disableAccessControl() { + VXResource vXResource = null; + rangerBizUtil.enableResourceAccessControl = false; + VXResponse resp = rangerBizUtil.hasPermission(vXResource, AppConstants.XA_PERM_TYPE_UNKNOWN); + Assert.assertNotNull(resp); + } + + @Test + public void testHasPermission_When_NoResource() { + VXResource vXResource = null; + VXResponse resp = rangerBizUtil.hasPermission(vXResource, AppConstants.XA_PERM_TYPE_UNKNOWN); + Assert.assertNotNull(resp); + Assert.assertEquals(VXResponse.STATUS_ERROR, resp.getStatusCode()); + Assert.assertEquals("Please provide valid policy.", resp.getMsgDesc()); + } + + @Test + public void testHasPermission_emptyResourceName() { + VXResource vXResource = new VXResource(); + vXResource.setAssetId(12345L); + XXPortalUser portalUser = new XXPortalUser(); + portalUser.setId(id); + portalUser.setLoginId("12121"); + RangerContextHolder.getSecurityContext().getUserSession().setXXPortalUser(portalUser); + + XXUserDao xxUserDao = Mockito.mock(XXUserDao.class); + XXPortalUserDao userDao = Mockito.mock(XXPortalUserDao.class); + XXUser xxUser = new XXUser(); + XXAsset xxAsset = new XXAsset(); + List lst = new ArrayList<>(); + XXResourceDao xxResourceDao = Mockito.mock(XXResourceDao.class); + XXAssetDao xxAssetDao = Mockito.mock(XXAssetDao.class); + Mockito.when(daoManager.getXXPortalUser()).thenReturn(userDao); + Mockito.when(userDao.getById(Mockito.anyLong())).thenReturn(portalUser); + Mockito.when(daoManager.getXXUser()).thenReturn(xxUserDao); + Mockito.when(xxUserDao.findByUserName(Mockito.anyString())).thenReturn(xxUser); + Mockito.when(daoManager.getXXResource()).thenReturn(xxResourceDao); + Mockito.when(xxResourceDao.findByAssetIdAndResourceStatus(Mockito.anyLong(), Mockito.anyInt())).thenReturn(lst); + Mockito.when(daoManager.getXXAsset()).thenReturn(xxAssetDao); + Mockito.when(xxAssetDao.getById(Mockito.anyLong())).thenReturn(xxAsset); + VXResponse resp = rangerBizUtil.hasPermission(vXResource, AppConstants.XA_PERM_TYPE_UNKNOWN); + Mockito.verify(daoManager).getXXPortalUser(); + Mockito.verify(userDao).getById(Mockito.anyLong()); + Mockito.verify(daoManager).getXXUser(); + Mockito.verify(xxUserDao).findByUserName(Mockito.anyString()); + Assert.assertNotNull(resp); + Assert.assertEquals(VXResponse.STATUS_ERROR, resp.getStatusCode()); + Assert.assertEquals("Permission Denied !", resp.getMsgDesc()); + } + + @Test + public void testHasPermission_isAdmin() { + VXResource vXResource = new VXResource(); + vXResource.setName(resourceName); + vXResource.setAssetId(id); + UserSessionBase currentUserSession = ContextUtil.getCurrentUserSession(); + currentUserSession.setUserAdmin(true); + VXResponse resp = rangerBizUtil.hasPermission(vXResource, AppConstants.XA_PERM_TYPE_UNKNOWN); + Assert.assertNotNull(resp); + Assert.assertEquals(VXResponse.STATUS_SUCCESS, resp.getStatusCode()); + } + + @Test + public void testIsNotAdmin() { + boolean isAdminChk = rangerBizUtil.isAdmin(); + Assert.assertFalse(isAdminChk); + } + + @Test + public void testIsAdmin() { + UserSessionBase currentUserSession = ContextUtil.getCurrentUserSession(); + currentUserSession.setUserAdmin(true); + boolean isAdminChk = rangerBizUtil.isAdmin(); + Assert.assertTrue(isAdminChk); + } + + @Test + public void testUserSessionNull_forIsAdmin() { + RangerContextHolder.setSecurityContext(null); + boolean isAdminChk = rangerBizUtil.isAdmin(); + Assert.assertFalse(isAdminChk); + } + + @Test + public void testGetXUserId_NoUserSession() { + RangerContextHolder.setSecurityContext(null); + Long chk = rangerBizUtil.getXUserId(); + Assert.assertNull(chk); + } + + @Test + public void testGetXUserId_NoUser() { + RangerSecurityContext context = new RangerSecurityContext(); + context.setUserSession(new UserSessionBase()); + RangerContextHolder.setSecurityContext(context); + XXPortalUser xxPortalUser = new XXPortalUser(); + xxPortalUser.setId(id); + xxPortalUser.setLoginId("12121"); + context.getUserSession().setXXPortalUser(xxPortalUser); + + XXUser xxUser = new XXUser(); + XXUserDao xxUserDao = Mockito.mock(XXUserDao.class); + XXPortalUserDao xxPortalUserDao = Mockito.mock(XXPortalUserDao.class); + Mockito.when(daoManager.getXXPortalUser()).thenReturn(xxPortalUserDao); + Mockito.when(xxPortalUserDao.getById(Mockito.anyLong())).thenReturn(xxPortalUser); + Mockito.when(daoManager.getXXUser()).thenReturn(xxUserDao); + Mockito.when(xxUserDao.findByUserName(Mockito.anyString())).thenReturn(xxUser); + Long chk = rangerBizUtil.getXUserId(); + Mockito.verify(daoManager).getXXPortalUser(); + Mockito.verify(xxPortalUserDao).getById(Mockito.anyLong()); + Mockito.verify(daoManager).getXXUser(); + Mockito.verify(xxUserDao).findByUserName(Mockito.anyString()); + Assert.assertNull(chk); + } + + @Test + public void testGetXUserId() { + XXPortalUser xxPortalUser = new XXPortalUser(); + xxPortalUser.setId(id); + xxPortalUser.setLoginId("12121"); + XXUser xxUser = new XXUser(); + xxUser.setId(id); + XXPortalUserDao xxPortalUserDao = Mockito.mock(XXPortalUserDao.class); + XXUserDao xxUserDao = Mockito.mock(XXUserDao.class); + RangerSecurityContext context = new RangerSecurityContext(); + UserSessionBase userSessionBase = new UserSessionBase(); + userSessionBase.setUserAdmin(true); + context.setUserSession(userSessionBase); + userSessionBase.setXXPortalUser(xxPortalUser); + RangerContextHolder.setSecurityContext(context); + Mockito.when(daoManager.getXXPortalUser()).thenReturn(xxPortalUserDao); + Mockito.when(xxPortalUserDao.getById(Mockito.anyLong())).thenReturn(xxPortalUser); + Mockito.when(daoManager.getXXUser()).thenReturn(xxUserDao); + Mockito.when(xxUserDao.findByUserName(Mockito.anyString())).thenReturn(xxUser); + Long chk = rangerBizUtil.getXUserId(); + Mockito.verify(daoManager).getXXPortalUser(); + Mockito.verify(xxPortalUserDao).getById(Mockito.anyLong()); + Mockito.verify(daoManager).getXXUser(); + Mockito.verify(xxUserDao).findByUserName(Mockito.anyString()); + Assert.assertEquals(chk, id); + } + + @Test + public void testReplaceMetaChars_PathEmpty() { + String path = ""; + String pathChk = rangerBizUtil.replaceMetaChars(path); + Assert.assertFalse(pathChk.contains("\\*")); + Assert.assertFalse(pathChk.contains("\\?")); + } + + @Test + public void testReplaceMetaChars_NoMetaChars() { + String path = "\\Demo\\Test"; + String pathChk = rangerBizUtil.replaceMetaChars(path); + Assert.assertFalse(pathChk.contains("\\*")); + Assert.assertFalse(pathChk.contains("\\?")); + } + + @Test + public void testReplaceMetaChars_PathNull() { + String path = null; + String pathChk = rangerBizUtil.replaceMetaChars(path); + Assert.assertNull(pathChk); + } + + @Test + public void testReplaceMetaChars() { + String path = "\\Demo\\Test\\*\\?"; + String pathChk = rangerBizUtil.replaceMetaChars(path); + Assert.assertFalse(pathChk.contains("\\*")); + Assert.assertFalse(pathChk.contains("\\?")); + } + + @Test + public void testGeneratePublicName() { + String firstName = "Test123456789123456789"; + String lastName = "Unit"; + String publicNameChk = rangerBizUtil.generatePublicName(firstName, lastName); + Assert.assertEquals("Test12345678... U.", publicNameChk); + } + + @Test + public void testGeneratePublicName_fNameLessThanMax() { + String firstName = "Test"; + String lastName = ""; + String publicNameChk = rangerBizUtil.generatePublicName(firstName, lastName); + Assert.assertNull(publicNameChk); + } + + @Test + public void testGeneratePublicName_withPortalUser() { + VXPortalUser vXPortalUser = new VXPortalUser(); + vXPortalUser.setFirstName("Test"); + vXPortalUser.setLastName(null); + String publicNameChk = rangerBizUtil.generatePublicName(vXPortalUser, null); + Assert.assertNull(publicNameChk); + } + + @Test + public void testMatchHdfsPolicy_NoResourceName() { + boolean bnlChk = rangerBizUtil.matchHbasePolicy(null, null, null, id, AppConstants.XA_PERM_TYPE_UNKNOWN); + Assert.assertFalse(bnlChk); + } + + @Test + public void testMatchHdfsPolicy_NoResourceList() { + boolean bnlChk = rangerBizUtil.matchHbasePolicy(resourceName, null, null, id, AppConstants.XA_PERM_TYPE_UNKNOWN); + Assert.assertFalse(bnlChk); + } + + @Test + public void testMatchHdfsPolicy_NoUserId() { + VXResponse vXResponse = new VXResponse(); + List xResourceList = new ArrayList<>(); + XXResource xXResource = new XXResource(); + xXResource.setId(id); + xXResource.setName(resourceName); + xXResource.setIsRecursive(AppConstants.BOOL_TRUE); + xXResource.setResourceStatus(AppConstants.STATUS_ENABLED); + xResourceList.add(xXResource); + boolean bnlChk = rangerBizUtil.matchHbasePolicy(resourceName, xResourceList, vXResponse, null, AppConstants.XA_PERM_TYPE_UNKNOWN); + Assert.assertFalse(bnlChk); + } + + @Test + public void testMatchHdfsPolicy_NoPremission() { + VXResponse vXResponse = new VXResponse(); + List xResourceList = new ArrayList<>(); + XXResource xXResource = new XXResource(); + xXResource.setId(id); + xXResource.setName(resourceName); + xXResource.setIsRecursive(AppConstants.BOOL_TRUE); + xXResource.setResourceStatus(AppConstants.STATUS_ENABLED); + xResourceList.add(xXResource); + Mockito.when(stringUtil.split(Mockito.anyString(), Mockito.anyString())).thenReturn(new String[0]); + boolean bnlChk = rangerBizUtil.matchHbasePolicy("/*/*/*", xResourceList, vXResponse, id, AppConstants.XA_PERM_TYPE_UNKNOWN); + Mockito.verify(stringUtil).split(Mockito.anyString(), Mockito.anyString()); + Assert.assertFalse(bnlChk); + } + + @Test + public void testMatchHivePolicy_NoResourceName() { + boolean bnlChk = rangerBizUtil.matchHivePolicy(null, null, null, 0); + Assert.assertFalse(bnlChk); + } + + @Test + public void testMatchHivePolicy_NoResourceList() { + boolean bnlChk = rangerBizUtil.matchHivePolicy(resourceName, null, null, 0); + Assert.assertFalse(bnlChk); + } + + @Test + public void testMatchHivePolicy_NoUserId() { + List xResourceList = new ArrayList<>(); + XXResource xXResource = new XXResource(); + xXResource.setId(id); + xXResource.setName(resourceName); + xXResource.setIsRecursive(AppConstants.BOOL_TRUE); + xXResource.setResourceStatus(AppConstants.STATUS_ENABLED); + xResourceList.add(xXResource); + boolean bnlChk = rangerBizUtil.matchHivePolicy(resourceName, xResourceList, null, 0); + Assert.assertFalse(bnlChk); + } + + @Test + public void testMatchHivePolicy_NoPremission() { + List xResourceList = new ArrayList<>(); + XXResource xXResource = new XXResource(); + xXResource.setId(id); + xXResource.setName(resourceName); + xXResource.setIsRecursive(AppConstants.BOOL_TRUE); + xXResource.setResourceStatus(AppConstants.STATUS_ENABLED); + xResourceList.add(xXResource); + Mockito.when(stringUtil.split(Mockito.anyString(), Mockito.anyString())).thenReturn(new String[0]); + boolean bnlChk = rangerBizUtil.matchHivePolicy("/*/*/*", xResourceList, id, 0); + Assert.assertFalse(bnlChk); + } + + @Test + public void testMatchHivePolicy() { + List xResourceList = new ArrayList<>(); + XXResource xXResource = new XXResource(); + xXResource.setId(5L); + xXResource.setName(resourceName); + xXResource.setIsRecursive(AppConstants.BOOL_TRUE); + xXResource.setResourceStatus(AppConstants.STATUS_ENABLED); + xResourceList.add(xXResource); + Mockito.when(stringUtil.split(Mockito.anyString(), Mockito.anyString())).thenReturn(new String[0]); + boolean bnlChk = rangerBizUtil.matchHivePolicy("/*/*/*", xResourceList, id, 17); + Mockito.verify(stringUtil).split(Mockito.anyString(), Mockito.anyString()); + Assert.assertFalse(bnlChk); + } + + @Test + public void testCheckUserAccessibleThrowErrorForKeyAdminAndUserRoleSysAdmin() { + Collection roleList = new ArrayList<>(); + roleList.add(RangerConstants.ROLE_SYS_ADMIN); + Mockito.when(userMgr.getRolesByLoginId(vXUser.getName())).thenReturn( + roleList); + Mockito.when(vXUser.getUserRoleList()).thenReturn(roleList); + + currentUserSession.setKeyAdmin(true); + RangerSecurityContext context = new RangerSecurityContext(); + context.setUserSession(currentUserSession); + RangerContextHolder.setSecurityContext(context); + + Mockito.when(currentUserSession.isKeyAdmin()).thenReturn(true); + + WebApplicationException webExp = new WebApplicationException(); + + Mockito.when(restErrorUtil.createRESTException("Logged in user is not allowed to create/update user", MessageEnums.OPER_NO_PERMISSION)).thenReturn(webExp); + + thrown.expect(WebApplicationException.class); + + rangerBizUtil.checkUserAccessible(vXUser); + + Mockito.verify(restErrorUtil).createRESTException("Logged in user is not allowed to create/update user", MessageEnums.OPER_NO_PERMISSION); + } + + @Test + public void testCheckUserAccessibleThrowErrorForKeyAdminAndUserRoleAdminAuditor() { + Collection roleList = new ArrayList<>(); + roleList.add(RangerConstants.ROLE_ADMIN_AUDITOR); + Mockito.when(userMgr.getRolesByLoginId(vXUser.getName())).thenReturn(roleList); + Mockito.when(vXUser.getUserRoleList()).thenReturn(roleList); + + currentUserSession.setKeyAdmin(true); + RangerSecurityContext context = new RangerSecurityContext(); + context.setUserSession(currentUserSession); + RangerContextHolder.setSecurityContext(context); + + Mockito.when(currentUserSession.isKeyAdmin()).thenReturn(true); + + WebApplicationException webExp = new WebApplicationException(); + + Mockito.when(restErrorUtil.createRESTException("Logged in user is not allowed to create/update user", MessageEnums.OPER_NO_PERMISSION)).thenReturn(webExp); - Mockito.when(currentUserSession.isKeyAdmin()).thenReturn(true); + thrown.expect(WebApplicationException.class); - boolean result = rangerBizUtil.checkUserAccessible(vXUser); - Assert.assertTrue(result); + rangerBizUtil.checkUserAccessible(vXUser); - } + Mockito.verify(restErrorUtil).createRESTException("Logged in user is not allowed to create/update user", MessageEnums.OPER_NO_PERMISSION); + } - @Test - public void testCheckUserAccessibleThrowErrorForAdminAndUserRoleKeyAdmin() - throws Exception { + @Test + public void testCheckUserAccessibleSuccessForKeyAdmin() { + Collection roleList = new ArrayList<>(); + roleList.add(RangerConstants.ROLE_KEY_ADMIN); + roleList.add(RangerConstants.ROLE_KEY_ADMIN_AUDITOR); + Mockito.when(userMgr.getRolesByLoginId(vXUser.getName())).thenReturn(roleList); + Mockito.when(vXUser.getUserRoleList()).thenReturn(roleList); - Collection roleList = new ArrayList(); - roleList.add(RangerConstants.ROLE_KEY_ADMIN); - Mockito.when(userMgr.getRolesByLoginId(vXUser.getName())).thenReturn( - roleList); - Mockito.when(vXUser.getUserRoleList()).thenReturn(roleList); + currentUserSession.setKeyAdmin(true); - currentUserSession.setUserAdmin(true); + RangerSecurityContext context = new RangerSecurityContext(); + context.setUserSession(currentUserSession); + RangerContextHolder.setSecurityContext(context); - RangerSecurityContext context = new RangerSecurityContext(); - context.setUserSession(currentUserSession); - RangerContextHolder.setSecurityContext(context); + Mockito.when(currentUserSession.isKeyAdmin()).thenReturn(true); - Mockito.when(currentUserSession.isUserAdmin()).thenReturn(true); + boolean result = rangerBizUtil.checkUserAccessible(vXUser); + Assert.assertTrue(result); + } - WebApplicationException webExp = new WebApplicationException(); + @Test + public void testCheckUserAccessibleThrowErrorForAdminAndUserRoleKeyAdmin() { + Collection roleList = new ArrayList<>(); + roleList.add(RangerConstants.ROLE_KEY_ADMIN); + Mockito.when(userMgr.getRolesByLoginId(vXUser.getName())).thenReturn( + roleList); + Mockito.when(vXUser.getUserRoleList()).thenReturn(roleList); - Mockito.when( - restErrorUtil.createRESTException( - "Logged in user is not allowed to create/update user", - MessageEnums.OPER_NO_PERMISSION)).thenReturn(webExp); + currentUserSession.setUserAdmin(true); - thrown.expect(WebApplicationException.class); + RangerSecurityContext context = new RangerSecurityContext(); + context.setUserSession(currentUserSession); + RangerContextHolder.setSecurityContext(context); - rangerBizUtil.checkUserAccessible(vXUser); + Mockito.when(currentUserSession.isUserAdmin()).thenReturn(true); - Mockito.verify(restErrorUtil).createRESTException( - "Logged in user is not allowed to create/update user", - MessageEnums.OPER_NO_PERMISSION); + WebApplicationException webExp = new WebApplicationException(); - } + Mockito.when(restErrorUtil.createRESTException("Logged in user is not allowed to create/update user", MessageEnums.OPER_NO_PERMISSION)).thenReturn(webExp); - @Test - public void testCheckUserAccessibleThrowErrorForAdminAndUserRoleKeyAdminAuditor() - throws Exception { + thrown.expect(WebApplicationException.class); - Collection roleList = new ArrayList(); - roleList.add(RangerConstants.ROLE_KEY_ADMIN_AUDITOR); - Mockito.when(userMgr.getRolesByLoginId(vXUser.getName())).thenReturn( - roleList); - Mockito.when(vXUser.getUserRoleList()).thenReturn(roleList); + rangerBizUtil.checkUserAccessible(vXUser); - currentUserSession.setUserAdmin(true); + Mockito.verify(restErrorUtil).createRESTException("Logged in user is not allowed to create/update user", MessageEnums.OPER_NO_PERMISSION); + } - RangerSecurityContext context = new RangerSecurityContext(); - context.setUserSession(currentUserSession); - RangerContextHolder.setSecurityContext(context); + @Test + public void testCheckUserAccessibleThrowErrorForAdminAndUserRoleKeyAdminAuditor() { + Collection roleList = new ArrayList<>(); + roleList.add(RangerConstants.ROLE_KEY_ADMIN_AUDITOR); + Mockito.when(userMgr.getRolesByLoginId(vXUser.getName())).thenReturn(roleList); + Mockito.when(vXUser.getUserRoleList()).thenReturn(roleList); - Mockito.when(currentUserSession.isUserAdmin()).thenReturn(true); + currentUserSession.setUserAdmin(true); - WebApplicationException webExp = new WebApplicationException(); + RangerSecurityContext context = new RangerSecurityContext(); + context.setUserSession(currentUserSession); + RangerContextHolder.setSecurityContext(context); - Mockito.when( - restErrorUtil.createRESTException( - "Logged in user is not allowed to create/update user", - MessageEnums.OPER_NO_PERMISSION)).thenReturn(webExp); + Mockito.when(currentUserSession.isUserAdmin()).thenReturn(true); - thrown.expect(WebApplicationException.class); + WebApplicationException webExp = new WebApplicationException(); - rangerBizUtil.checkUserAccessible(vXUser); + Mockito.when(restErrorUtil.createRESTException("Logged in user is not allowed to create/update user", MessageEnums.OPER_NO_PERMISSION)).thenReturn(webExp); - Mockito.verify(restErrorUtil).createRESTException( - "Logged in user is not allowed to create/update user", - MessageEnums.OPER_NO_PERMISSION); + thrown.expect(WebApplicationException.class); - } + rangerBizUtil.checkUserAccessible(vXUser); - @Test - public void testCheckUserAccessibleSuccessForAdmin(){ - Collection roleList = new ArrayList(); - roleList.add(RangerConstants.ROLE_SYS_ADMIN); - Mockito.when(userMgr.getRolesByLoginId(vXUser.getName())).thenReturn( - roleList); - Mockito.when(vXUser.getUserRoleList()).thenReturn(roleList); + Mockito.verify(restErrorUtil).createRESTException("Logged in user is not allowed to create/update user", MessageEnums.OPER_NO_PERMISSION); + } - currentUserSession.setUserAdmin(true); + @Test + public void testCheckUserAccessibleSuccessForAdmin() { + Collection roleList = new ArrayList<>(); + roleList.add(RangerConstants.ROLE_SYS_ADMIN); + Mockito.when(userMgr.getRolesByLoginId(vXUser.getName())).thenReturn(roleList); + Mockito.when(vXUser.getUserRoleList()).thenReturn(roleList); - RangerSecurityContext context = new RangerSecurityContext(); - context.setUserSession(currentUserSession); - RangerContextHolder.setSecurityContext(context); + currentUserSession.setUserAdmin(true); - Mockito.when(currentUserSession.isUserAdmin()).thenReturn(true); + RangerSecurityContext context = new RangerSecurityContext(); + context.setUserSession(currentUserSession); + RangerContextHolder.setSecurityContext(context); - boolean result = rangerBizUtil.checkUserAccessible(vXUser); - Assert.assertTrue(result); + Mockito.when(currentUserSession.isUserAdmin()).thenReturn(true); - } + boolean result = rangerBizUtil.checkUserAccessible(vXUser); + Assert.assertTrue(result); + } - @Test - public void testBlockAuditorRoleUserThrowsErrorForAuditKeyAdmin(){ - RangerBizUtil rangerBizUtilMock = Mockito.mock(RangerBizUtil.class); + @Test + public void testBlockAuditorRoleUserThrowsErrorForAuditKeyAdmin() { + RangerBizUtil rangerBizUtilMock = Mockito.mock(RangerBizUtil.class); vXResponse.setStatusCode(HttpServletResponse.SC_UNAUTHORIZED); vXResponse.setMsgDesc("Operation denied. LoggedInUser=1 ,isn't permitted to perform the action."); XXPortalUser xxPortalUser = new XXPortalUser(); xxPortalUser.setId(1L); - currentUserSession.setAuditKeyAdmin(true); - - RangerSecurityContext context = new RangerSecurityContext(); - context.setUserSession(currentUserSession); - RangerContextHolder.setSecurityContext(context); - - Mockito.doThrow(new WebApplicationException()).when(rangerBizUtilMock).blockAuditorRoleUser(); - thrown.expect(WebApplicationException.class); + currentUserSession.setAuditKeyAdmin(true); - rangerBizUtilMock.blockAuditorRoleUser(); + RangerSecurityContext context = new RangerSecurityContext(); + context.setUserSession(currentUserSession); + RangerContextHolder.setSecurityContext(context); - } + Mockito.doThrow(new WebApplicationException()).when(rangerBizUtilMock).blockAuditorRoleUser(); + thrown.expect(WebApplicationException.class); - @Test - public void testBlockAuditorRoleUserThrowsErrorForAuditUserAdmin(){ + rangerBizUtilMock.blockAuditorRoleUser(); + } - RangerBizUtil rangerBizUtilMock = Mockito.mock(RangerBizUtil.class); + @Test + public void testBlockAuditorRoleUserThrowsErrorForAuditUserAdmin() { + RangerBizUtil rangerBizUtilMock = Mockito.mock(RangerBizUtil.class); vXResponse.setStatusCode(HttpServletResponse.SC_UNAUTHORIZED); vXResponse.setMsgDesc("Operation denied. LoggedInUser=1 ,isn't permitted to perform the action."); @@ -649,38 +591,35 @@ public void testBlockAuditorRoleUserThrowsErrorForAuditUserAdmin(){ XXPortalUser xxPortalUser = new XXPortalUser(); xxPortalUser.setId(1L); - currentUserSession.setAuditKeyAdmin(true); + currentUserSession.setAuditKeyAdmin(true); - RangerSecurityContext context = new RangerSecurityContext(); - context.setUserSession(currentUserSession); - RangerContextHolder.setSecurityContext(context); + RangerSecurityContext context = new RangerSecurityContext(); + context.setUserSession(currentUserSession); + RangerContextHolder.setSecurityContext(context); + Mockito.doThrow(new WebApplicationException()).when(rangerBizUtilMock).blockAuditorRoleUser(); - Mockito.doThrow(new WebApplicationException()).when(rangerBizUtilMock).blockAuditorRoleUser(); + thrown.expect(WebApplicationException.class); - thrown.expect(WebApplicationException.class); + rangerBizUtilMock.blockAuditorRoleUser(); + } - rangerBizUtilMock.blockAuditorRoleUser(); - } - - @Test - public void testBlockAuditorRoleUserSuccess(){ - RangerBizUtil rangerBizUtilMock = Mockito.mock(RangerBizUtil.class); + @Test + public void testBlockAuditorRoleUserSuccess() { + RangerBizUtil rangerBizUtilMock = Mockito.mock(RangerBizUtil.class); XXPortalUser xxPortalUser = new XXPortalUser(); xxPortalUser.setId(1L); - currentUserSession.setUserAdmin(true); - - RangerSecurityContext context = new RangerSecurityContext(); - context.setUserSession(currentUserSession); - RangerContextHolder.setSecurityContext(context); - + currentUserSession.setUserAdmin(true); - Mockito.doNothing().when(rangerBizUtilMock).blockAuditorRoleUser(); + RangerSecurityContext context = new RangerSecurityContext(); + context.setUserSession(currentUserSession); + RangerContextHolder.setSecurityContext(context); - rangerBizUtilMock.blockAuditorRoleUser(); - Mockito.verify(rangerBizUtilMock).blockAuditorRoleUser(); + Mockito.doNothing().when(rangerBizUtilMock).blockAuditorRoleUser(); - } -} \ No newline at end of file + rangerBizUtilMock.blockAuditorRoleUser(); + Mockito.verify(rangerBizUtilMock).blockAuditorRoleUser(); + } +} diff --git a/security-admin/src/test/java/org/apache/ranger/biz/TestRoleDBStore.java b/security-admin/src/test/java/org/apache/ranger/biz/TestRoleDBStore.java index ac401c3949..73fe2a56e6 100644 --- a/security-admin/src/test/java/org/apache/ranger/biz/TestRoleDBStore.java +++ b/security-admin/src/test/java/org/apache/ranger/biz/TestRoleDBStore.java @@ -17,13 +17,6 @@ package org.apache.ranger.biz; -import java.util.Arrays; -import java.util.Collections; -import java.util.Date; -import java.util.List; - -import javax.ws.rs.WebApplicationException; - import org.apache.ranger.authorization.hadoop.config.RangerAdminConfig; import org.apache.ranger.common.ContextUtil; import org.apache.ranger.common.RESTErrorUtil; @@ -63,6 +56,13 @@ import org.mockito.Mockito; import org.mockito.runners.MockitoJUnitRunner; +import javax.ws.rs.WebApplicationException; + +import java.util.Arrays; +import java.util.Collections; +import java.util.Date; +import java.util.List; + @RunWith(MockitoJUnitRunner.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class TestRoleDBStore { @@ -72,43 +72,31 @@ public class TestRoleDBStore { private static final String keyAdminLoginID = "keyadmin"; private static final String userLoginID = "testuser"; private static final String roleName = "test-role"; - + @Rule + public ExpectedException thrown = ExpectedException.none(); @InjectMocks RoleDBStore roleDBStore = new RoleDBStore(); - @Mock GdsDBStore gdsStore; - @Mock RangerBizUtil bizUtil; - @Mock RangerDaoManager daoMgr; - @Mock RESTErrorUtil restErrorUtil; - @Mock RangerTransactionSynchronizationAdapter transactionSynchronizationAdapter; - @Mock ServiceDBStore svcStore; - @Mock RangerAdminConfig config; - @Mock RangerRoleService roleService; - @Mock XUserService xUserService; - @Mock RoleRefUpdater roleRefUpdater; - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Test public void testRoleExistsByRoleName() throws Exception { XXRoleDao xxRoleDao = Mockito.mock(XXRoleDao.class); @@ -145,7 +133,6 @@ public void testGetRoleByRoleId() throws Exception { Assert.assertEquals(rangerRole.getId(), rangerRoleInDB.getId()); } - @Test public void testGetRolesBySearchFilter() throws Exception { RangerRole rangerRole = getRangerRole(); @@ -154,7 +141,7 @@ public void testGetRolesBySearchFilter() throws Exception { List xxRoles = Collections.singletonList(xxRole); SearchFilter searchFilter = new SearchFilter(); - Mockito.when(roleService.searchResources(searchFilter, roleService.searchFields, roleService.sortFields , rangerRoleList)).thenReturn(xxRoles); + Mockito.when(roleService.searchResources(searchFilter, roleService.searchFields, roleService.sortFields, rangerRoleList)).thenReturn(xxRoles); Mockito.when(roleService.read(xxRole.getId())).thenReturn(rangerRole); RangerRoleList rangerRoleListInDB = roleDBStore.getRoles(searchFilter, rangerRoleList); @@ -171,7 +158,7 @@ public void testGetRolesForUser_WithoutUserSession() throws Exception { List xxRoles = Collections.singletonList(xxRole); SearchFilter searchFilter = new SearchFilter(); - Mockito.when(roleService.searchResources(searchFilter, roleService.searchFields, roleService.sortFields , rangerRoleList)).thenReturn(xxRoles); + Mockito.when(roleService.searchResources(searchFilter, roleService.searchFields, roleService.sortFields, rangerRoleList)).thenReturn(xxRoles); Mockito.when(roleService.read(xxRole.getId())).thenReturn(rangerRole); RangerContextHolder.setSecurityContext(null); @@ -188,8 +175,13 @@ public void testGetRolesForUser_WithUserSession() throws Exception { RangerRoleList rangerRoleList = new RangerRoleList(Collections.singletonList(rangerRole)); XXRole xxRole = getTestRole(); List xxRoles = Collections.singletonList(xxRole); - XXPortalUser userKeyAdmin = new XXPortalUser() {{ setId(getUserProfile().getId()); setLoginId(keyAdminLoginID); }}; - VXUser vxUserKeyAdmin = new VXUser() {{ setId(userKeyAdmin.getId()); }}; + XXPortalUser userKeyAdmin = new XXPortalUser() {{ + setId(getUserProfile().getId()); + setLoginId(keyAdminLoginID); + }}; + VXUser vxUserKeyAdmin = new VXUser() {{ + setId(userKeyAdmin.getId()); + }}; SearchFilter searchFilter = new SearchFilter(); XXRoleDao xxRoleDao = Mockito.mock(XXRoleDao.class); @@ -198,7 +190,9 @@ public void testGetRolesForUser_WithUserSession() throws Exception { Mockito.when(daoMgr.getXXRole()).thenReturn(xxRoleDao); Mockito.when(xxRoleDao.findByUserId(userKeyAdmin.getId())).thenReturn(xxRoles); - RangerSecurityContext context = new RangerSecurityContext() {{ setUserSession(new UserSessionBase());}}; + RangerSecurityContext context = new RangerSecurityContext() {{ + setUserSession(new UserSessionBase()); + }}; RangerContextHolder.setSecurityContext(context); @@ -307,7 +301,7 @@ public void testGetRoles() throws Exception { Mockito.when(xxRoleDao.getAll()).thenReturn(xxRoles); Mockito.when(roleService.read(xxRole.getId())).thenReturn(rangerRole); - List rangerRolesInDB = roleDBStore.getRoles(searchFilter); + List rangerRolesInDB = roleDBStore.getRoles(searchFilter); Assert.assertNotNull(rangerRolesInDB); } @@ -320,7 +314,7 @@ public void testGetRoleVersion() { Mockito.when(daoMgr.getXXGlobalState()).thenReturn(xxGlobalStateDao); Mockito.when(xxGlobalStateDao.getAppDataVersion("RangerRole")).thenReturn(1L); - Long roleVersion = roleDBStore.getRoleVersion(xxService.getName()); + Long roleVersion = roleDBStore.getRoleVersion(xxService.getName()); Assert.assertNotNull(roleVersion); } @@ -379,7 +373,7 @@ public void testDeleteRoleByValidRoleName() throws Exception { Mockito.when(roleRefUpdater.cleanupRefTables(Mockito.any())).thenReturn(true); Mockito.doNothing().when(svcStore).updateServiceAuditConfig(Mockito.anyString(), Mockito.any()); Mockito.when(roleService.delete(Mockito.any())).thenReturn(true); - Mockito.doNothing().when(roleService).createTransactionLog( Mockito.any(), Mockito.any(), Mockito.anyInt()); + Mockito.doNothing().when(roleService).createTransactionLog(Mockito.any(), Mockito.any(), Mockito.anyInt()); roleDBStore.deleteRole(roleName); } @@ -410,7 +404,7 @@ public void testCreateRole() throws Exception { Mockito.when(roleService.read(xxRole.getId())).thenReturn(rangerRole); Mockito.doNothing().when(transactionSynchronizationAdapter).executeOnTransactionCommit(Mockito.any()); Mockito.doNothing().when(roleRefUpdater).createNewRoleMappingForRefTable(Mockito.any(), Mockito.anyBoolean()); - Mockito.doNothing().when(roleService).createTransactionLog( Mockito.any(), Mockito.any(), Mockito.anyInt()); + Mockito.doNothing().when(roleService).createTransactionLog(Mockito.any(), Mockito.any(), Mockito.anyInt()); roleDBStore.createRole(rangerRole, true); } @@ -440,7 +434,7 @@ public void testUpdateRole() throws Exception { Mockito.when(roleService.update(rangerRole)).thenReturn(rangerRole); Mockito.doNothing().when(roleRefUpdater).createNewRoleMappingForRefTable(Mockito.any(), Mockito.anyBoolean()); Mockito.doNothing().when(roleService).updatePolicyVersions(rangerRole.getId()); - Mockito.doNothing().when(roleService).createTransactionLog( Mockito.any(), Mockito.any(), Mockito.anyInt()); + Mockito.doNothing().when(roleService).createTransactionLog(Mockito.any(), Mockito.any(), Mockito.anyInt()); roleDBStore.updateRole(rangerRole, true); } @@ -465,7 +459,7 @@ public void testDeleteRoleByRoleId() throws Exception { Mockito.when(roleRefUpdater.cleanupRefTables(Mockito.any())).thenReturn(true); Mockito.doNothing().when(svcStore).updateServiceAuditConfig(Mockito.anyString(), Mockito.any()); Mockito.when(roleService.delete(Mockito.any())).thenReturn(true); - Mockito.doNothing().when(roleService).createTransactionLog( Mockito.any(), Mockito.any(), Mockito.anyInt()); + Mockito.doNothing().when(roleService).createTransactionLog(Mockito.any(), Mockito.any(), Mockito.anyInt()); roleDBStore.deleteRole(rangerRole.getId()); } @@ -508,53 +502,53 @@ public void testDeleteRoleByValidRoleNameWhenRoleIsAssociatedWithOneOrMoreSecuri private XXRole getTestRole() { return new XXRole() {{ - setId(TestRoleDBStore.roleId); - setCreateTime(new Date()); - setName(TestRoleDBStore.roleName); - setDescription(TestRoleDBStore.roleName); - }}; + setId(TestRoleDBStore.roleId); + setCreateTime(new Date()); + setName(TestRoleDBStore.roleName); + setDescription(TestRoleDBStore.roleName); + }}; } private VXPortalUser getUserProfile() { return new VXPortalUser() {{ - setEmailAddress("test@test.com"); - setFirstName("user12"); - setLastName("test12"); - setLoginId(TestRoleDBStore.userLoginID); - setPassword("Usertest123"); - setUserSource(1); - setPublicScreenName("testuser"); - setId(TestRoleDBStore.userId); - }}; + setEmailAddress("test@test.com"); + setFirstName("user12"); + setLastName("test12"); + setLoginId(TestRoleDBStore.userLoginID); + setPassword("Usertest123"); + setUserSource(1); + setPublicScreenName("testuser"); + setId(TestRoleDBStore.userId); + }}; } - private RangerRole getRangerRole(){ - String name = "test-role"; - String name2 = "admin"; - RoleMember rm1 = new RoleMember(name, true); - RoleMember rm2 = new RoleMember(name2, true); - List usersList = Arrays.asList(rm1,rm2); + private RangerRole getRangerRole() { + String name = "test-role"; + String name2 = "admin"; + RoleMember rm1 = new RoleMember(name, true); + RoleMember rm2 = new RoleMember(name2, true); + List usersList = Arrays.asList(rm1, rm2); return new RangerRole(name, name, null, usersList, null) {{ - setCreatedByUser(name); - setId(TestRoleDBStore.roleId); - }}; + setCreatedByUser(name); + setId(TestRoleDBStore.roleId); + }}; } private XXService getXXService() { return new XXService() {{ - setAddedByUserId(TestRoleDBStore.id); - setCreateTime(new Date()); - setDescription("Hdfs service"); - setGuid("serviceguid"); - setId(TestRoleDBStore.id); - setIsEnabled(true); - setName("Hdfs"); - setPolicyUpdateTime(new Date()); - setPolicyVersion(1L); - setType(1L); - setUpdatedByUserId(TestRoleDBStore.id); - setUpdateTime(new Date()); - }}; + setAddedByUserId(TestRoleDBStore.id); + setCreateTime(new Date()); + setDescription("Hdfs service"); + setGuid("serviceguid"); + setId(TestRoleDBStore.id); + setIsEnabled(true); + setName("Hdfs"); + setPolicyUpdateTime(new Date()); + setPolicyVersion(1L); + setType(1L); + setUpdatedByUserId(TestRoleDBStore.id); + setUpdateTime(new Date()); + }}; } } diff --git a/security-admin/src/test/java/org/apache/ranger/biz/TestSecurityZoneDBStore.java b/security-admin/src/test/java/org/apache/ranger/biz/TestSecurityZoneDBStore.java index 66ef172f66..ae0c56dfe2 100644 --- a/security-admin/src/test/java/org/apache/ranger/biz/TestSecurityZoneDBStore.java +++ b/security-admin/src/test/java/org/apache/ranger/biz/TestSecurityZoneDBStore.java @@ -16,14 +16,6 @@ */ package org.apache.ranger.biz; -import static org.mockito.Mockito.times; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.ws.rs.WebApplicationException; import org.apache.ranger.common.MessageEnums; import org.apache.ranger.common.RESTErrorUtil; @@ -47,291 +39,290 @@ import org.mockito.Mockito; import org.mockito.runners.MockitoJUnitRunner; +import javax.ws.rs.WebApplicationException; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.mockito.Mockito.times; + @RunWith(MockitoJUnitRunner.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class TestSecurityZoneDBStore { - private static final String RANGER_GLOBAL_STATE_NAME = "RangerSecurityZone"; - - @InjectMocks - SecurityZoneDBStore securityZoneDBStore = new SecurityZoneDBStore(); - - @Mock - RangerSecurityZoneServiceService securityZoneService; - - @Mock - SecurityZoneRefUpdater securityZoneRefUpdater; - - @Mock - RangerDaoManager daoManager; - - @Mock - ServicePredicateUtil predicateUtil; - @Mock - RESTErrorUtil restErrorUtil; - - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Test - public void test1createSecurityZone() throws Exception { - XXSecurityZone xxSecurityZone = null; - RangerSecurityZone securityZone = new RangerSecurityZone(); - RangerSecurityZone createdSecurityZone = new RangerSecurityZone(); - createdSecurityZone.setId(2L); - - XXSecurityZoneDao xXSecurityZoneDao = Mockito.mock(XXSecurityZoneDao.class); - XXGlobalStateDao xXGlobalStateDao = Mockito.mock(XXGlobalStateDao.class); - - Mockito.when(daoManager.getXXSecurityZoneDao()).thenReturn(xXSecurityZoneDao); - Mockito.when(xXSecurityZoneDao.findByZoneName(securityZone.getName())).thenReturn(xxSecurityZone); - - Mockito.when(daoManager.getXXGlobalState()).thenReturn(xXGlobalStateDao); - Mockito.doNothing().when(xXGlobalStateDao).onGlobalStateChange(RANGER_GLOBAL_STATE_NAME); - - Mockito.when(securityZoneService.create(securityZone)).thenReturn(createdSecurityZone); - Mockito.doNothing().when(securityZoneRefUpdater).createNewZoneMappingForRefTable(createdSecurityZone); - - RangerSecurityZone expectedSecurityZone = securityZoneDBStore.createSecurityZone(securityZone); - - Assert.assertNull(xxSecurityZone); - Assert.assertEquals(createdSecurityZone.getId(), expectedSecurityZone.getId()); - Mockito.verify(daoManager).getXXSecurityZoneDao(); - Mockito.verify(daoManager).getXXGlobalState(); - Mockito.verify(securityZoneService).create(securityZone); - } - - @Test - public void test2updateSecurityZoneById() throws Exception { - XXSecurityZone xxSecurityZone = new XXSecurityZone(); - xxSecurityZone.setId(2L); - RangerSecurityZone securityZone = new RangerSecurityZone(); - securityZone.setId(2L); - RangerSecurityZone updateSecurityZone = new RangerSecurityZone(); - updateSecurityZone.setId(2L); - - XXGlobalStateDao xXGlobalStateDao = Mockito.mock(XXGlobalStateDao.class); - - Mockito.when(daoManager.getXXGlobalState()).thenReturn(xXGlobalStateDao); - Mockito.doNothing().when(xXGlobalStateDao).onGlobalStateChange(RANGER_GLOBAL_STATE_NAME); - - Mockito.when(securityZoneService.update(securityZone)).thenReturn(updateSecurityZone); - Mockito.doNothing().when(securityZoneRefUpdater).createNewZoneMappingForRefTable(updateSecurityZone); - - RangerSecurityZone expectedSecurityZone = securityZoneDBStore.updateSecurityZoneById(securityZone); - - Assert.assertNotNull(xxSecurityZone); - Assert.assertEquals(updateSecurityZone.getId(), expectedSecurityZone.getId()); - Mockito.verify(daoManager).getXXGlobalState(); - Mockito.verify(securityZoneService).update(securityZone); - } - - @Test - public void test3deleteSecurityZoneByName() throws Exception { - XXSecurityZone xxSecurityZone = new XXSecurityZone(); - xxSecurityZone.setId(2L); - RangerSecurityZone securityZone = new RangerSecurityZone(); - securityZone.setId(2L); - securityZone.setName("sz1"); - - XXSecurityZoneDao xXSecurityZoneDao = Mockito.mock(XXSecurityZoneDao.class); - XXGlobalStateDao xXGlobalStateDao = Mockito.mock(XXGlobalStateDao.class); - - Mockito.when(daoManager.getXXSecurityZoneDao()).thenReturn(xXSecurityZoneDao); - Mockito.when(xXSecurityZoneDao.findByZoneName(securityZone.getName())).thenReturn(xxSecurityZone); - Mockito.when(securityZoneService.read(securityZone.getId())).thenReturn(securityZone); - Mockito.when(daoManager.getXXGlobalState()).thenReturn(xXGlobalStateDao); - Mockito.doNothing().when(xXGlobalStateDao).onGlobalStateChange(RANGER_GLOBAL_STATE_NAME); - Mockito.when(securityZoneRefUpdater.cleanupRefTables(securityZone)).thenReturn(true); - Mockito.when(securityZoneService.delete(securityZone)).thenReturn(true); - - securityZoneDBStore.deleteSecurityZoneByName(securityZone.getName()); - - Assert.assertNotNull(xxSecurityZone); - } - - @Test - public void test4deleteSecurityZoneById() throws Exception { - XXSecurityZone xxSecurityZone = new XXSecurityZone(); - xxSecurityZone.setId(2L); - RangerSecurityZone securityZone = new RangerSecurityZone(); - securityZone.setId(2L); - securityZone.setName("sz1"); - - XXGlobalStateDao xXGlobalStateDao = Mockito.mock(XXGlobalStateDao.class); - Mockito.when(securityZoneService.read(securityZone.getId())).thenReturn(securityZone); - Mockito.when(daoManager.getXXGlobalState()).thenReturn(xXGlobalStateDao); - Mockito.doNothing().when(xXGlobalStateDao).onGlobalStateChange(RANGER_GLOBAL_STATE_NAME); - Mockito.when(securityZoneRefUpdater.cleanupRefTables(securityZone)).thenReturn(true); - Mockito.when(securityZoneService.delete(securityZone)).thenReturn(true); - - securityZoneDBStore.deleteSecurityZoneById(securityZone.getId()); - } - - @Test - public void test5getSecurityZoneByName() throws Exception { - XXSecurityZone xxSecurityZone = new XXSecurityZone(); - xxSecurityZone.setId(2L); - xxSecurityZone.setName("sz1"); - RangerSecurityZone securityZone = new RangerSecurityZone(); - securityZone.setId(2L); - securityZone.setName("sz1"); - RangerSecurityZone createdSecurityZone = new RangerSecurityZone(); - createdSecurityZone.setId(2L); - createdSecurityZone.setName("sz1"); - XXSecurityZoneDao xXSecurityZoneDao = Mockito.mock(XXSecurityZoneDao.class); - - Mockito.when(daoManager.getXXSecurityZoneDao()).thenReturn(xXSecurityZoneDao); - Mockito.when(xXSecurityZoneDao.findByZoneName(securityZone.getName())).thenReturn(xxSecurityZone); - Mockito.when(securityZoneService.read(securityZone.getId())).thenReturn(createdSecurityZone); - - RangerSecurityZone expectedSecurityZone = securityZoneDBStore.getSecurityZoneByName(securityZone.getName()); - - Assert.assertNotNull(xxSecurityZone); - Assert.assertEquals(createdSecurityZone.getName(), expectedSecurityZone.getName()); - Mockito.verify(securityZoneService).read(securityZone.getId()); - } - - @Test - public void test6getSecurityZones() throws Exception { - SearchFilter filter = new SearchFilter(); - filter.setParam(SearchFilter.ZONE_NAME, "sz1"); - - List ret = new ArrayList<>(); - List xxSecurityZones = new ArrayList(); - XXSecurityZone xxSecurityZone = new XXSecurityZone(); - xxSecurityZone.setId(2L); - xxSecurityZone.setName("sz1"); - xxSecurityZones.add(xxSecurityZone); - - RangerSecurityZone rangerSecurityZone = new RangerSecurityZone(); - rangerSecurityZone.setId(3L); - ret.add(rangerSecurityZone); - List copy = new ArrayList<>(ret); - - XXSecurityZoneDao xXSecurityZoneDao = Mockito.mock(XXSecurityZoneDao.class); - Mockito.when(daoManager.getXXSecurityZoneDao()).thenReturn(xXSecurityZoneDao); - Mockito.when(xXSecurityZoneDao.getAll()).thenReturn(xxSecurityZones); - Mockito.when(securityZoneService.read(xxSecurityZone.getId())).thenReturn(rangerSecurityZone); - Mockito.doNothing().when(predicateUtil).applyFilter(copy, filter); - - securityZoneDBStore.getSecurityZones(filter); - - Assert.assertNotNull(xxSecurityZone); - Assert.assertNotNull(xxSecurityZones); - Mockito.verify(daoManager).getXXSecurityZoneDao(); - Mockito.verify(securityZoneService).read(xxSecurityZone.getId()); - Mockito.verify(predicateUtil).applyFilter(copy, filter); - } - - @Test - public void test7getSecurityZonesForService() throws Exception { - String serviceName = "hdfs_service"; - Map retMap = null; - - SearchFilter filter = new SearchFilter(); - filter.setParam(SearchFilter.ZONE_NAME, "sz1"); - filter.setParam(SearchFilter.SERVICE_NAME, serviceName); - List ret = new ArrayList<>(); - List xxSecurityZones = new ArrayList(); - - XXSecurityZone xxSecurityZone = new XXSecurityZone(); - xxSecurityZone.setId(2L); - xxSecurityZone.setName("sz1"); - xxSecurityZones.add(xxSecurityZone); - - RangerSecurityZone rangerSecurityZone = new RangerSecurityZone(); - rangerSecurityZone.setId(3L); - ret.add(rangerSecurityZone); -// List copy = new ArrayList<>(ret); - - XXSecurityZoneDao xXSecurityZoneDao = Mockito.mock(XXSecurityZoneDao.class); - Mockito.when(daoManager.getXXSecurityZoneDao()).thenReturn(xXSecurityZoneDao); - Mockito.when(xXSecurityZoneDao.getAll()).thenReturn(xxSecurityZones); - Mockito.when(securityZoneService.read(xxSecurityZone.getId())).thenReturn(rangerSecurityZone); -// Mockito.doNothing().when(predicateUtil).applyFilter(copy, filter); - retMap = new HashMap<>(); - retMap.put(rangerSecurityZone.getName(), rangerSecurityZone.getServices().get(serviceName)); - - securityZoneDBStore.getSecurityZonesForService(serviceName); - - Assert.assertNotNull(xxSecurityZone); - Assert.assertNotNull(xxSecurityZones); - Mockito.verify(daoManager).getXXSecurityZoneDao(); - Mockito.verify(securityZoneService).read(xxSecurityZone.getId()); - } - - @Test - public void test8createSecurityZoneWithExistingName() throws Exception { - XXSecurityZone xxSecurityZone = new XXSecurityZone(); - xxSecurityZone.setId(2L); - RangerSecurityZone securityZone = new RangerSecurityZone(); - RangerSecurityZone createdSecurityZone = new RangerSecurityZone(); - createdSecurityZone.setId(2L); - - XXSecurityZoneDao xXSecurityZoneDao = Mockito.mock(XXSecurityZoneDao.class); - - Mockito.when(daoManager.getXXSecurityZoneDao()).thenReturn(xXSecurityZoneDao); - Mockito.when(xXSecurityZoneDao.findByZoneName(securityZone.getName())).thenReturn(xxSecurityZone); - Mockito.when(restErrorUtil.createRESTException(Mockito.anyString(), Mockito.any(MessageEnums.class))) - .thenThrow(new WebApplicationException()); - thrown.expect(WebApplicationException.class); - - securityZoneDBStore.createSecurityZone(securityZone); - - Mockito.verify(daoManager, times(1)).getXXSecurityZoneDao(); - Mockito.verify(xXSecurityZoneDao, times(1)).findByZoneName(securityZone.getName()); - } - - @Test - public void test9updateSecurityZoneByUnknownId() throws Exception { - RangerSecurityZone securityZoneToUpdate = new RangerSecurityZone(); - securityZoneToUpdate.setId(2L); - - XXSecurityZoneDao xXSecurityZoneDao = Mockito.mock(XXSecurityZoneDao.class); - Mockito.when(restErrorUtil.createRESTException(Mockito.anyString())).thenThrow(new WebApplicationException()); - thrown.expect(WebApplicationException.class); - - XXGlobalStateDao xXGlobalStateDao = Mockito.mock(XXGlobalStateDao.class); - Mockito.when(daoManager.getXXGlobalState()).thenReturn(xXGlobalStateDao); - Mockito.doNothing().when(xXGlobalStateDao).onGlobalStateChange(RANGER_GLOBAL_STATE_NAME); - - securityZoneDBStore.updateSecurityZoneById(securityZoneToUpdate); - Mockito.verify(daoManager, times(1)).getXXSecurityZoneDao(); - Mockito.verify(xXSecurityZoneDao, times(1)).findByZoneId(securityZoneToUpdate.getId()); - } - - @Test - public void test10deleteSecurityZoneByWrongName() throws Exception { - XXSecurityZone xxSecurityZone = new XXSecurityZone(); - xxSecurityZone.setId(2L); - RangerSecurityZone securityZone = new RangerSecurityZone(); - securityZone.setId(2L); - securityZone.setName("sz1"); - - XXSecurityZoneDao xXSecurityZoneDao = Mockito.mock(XXSecurityZoneDao.class); - Mockito.when(daoManager.getXXSecurityZoneDao()).thenReturn(xXSecurityZoneDao); - Mockito.when(xXSecurityZoneDao.findByZoneName(securityZone.getName())).thenReturn(null); - Mockito.when(restErrorUtil.createRESTException(Mockito.anyString())).thenThrow(new WebApplicationException()); - thrown.expect(WebApplicationException.class); - - securityZoneDBStore.deleteSecurityZoneByName(securityZone.getName()); - Mockito.verify(xXSecurityZoneDao, times(1)).findByZoneName(xxSecurityZone.getName()); - - } - - @Test - public void test11getSecurityZoneByWrongName() throws Exception { - RangerSecurityZone securityZone = new RangerSecurityZone(); - securityZone.setId(2L); - securityZone.setName("sz1"); - - XXSecurityZoneDao xXSecurityZoneDao = Mockito.mock(XXSecurityZoneDao.class); - Mockito.when(daoManager.getXXSecurityZoneDao()).thenReturn(xXSecurityZoneDao); - Mockito.when(xXSecurityZoneDao.findByZoneName(securityZone.getName())).thenReturn(null); - Mockito.when(restErrorUtil.createRESTException(Mockito.anyString())).thenThrow(new WebApplicationException()); - thrown.expect(WebApplicationException.class); - - securityZoneDBStore.getSecurityZoneByName(securityZone.getName()); - Mockito.verify(xXSecurityZoneDao, times(1)).findByZoneName(securityZone.getName()); - - } + private static final String RANGER_GLOBAL_STATE_NAME = "RangerSecurityZone"; + @Rule + public ExpectedException thrown = ExpectedException.none(); + @InjectMocks + SecurityZoneDBStore securityZoneDBStore = new SecurityZoneDBStore(); + @Mock + RangerSecurityZoneServiceService securityZoneService; + @Mock + SecurityZoneRefUpdater securityZoneRefUpdater; + @Mock + RangerDaoManager daoManager; + @Mock + ServicePredicateUtil predicateUtil; + @Mock + RESTErrorUtil restErrorUtil; + + @Test + public void test1createSecurityZone() throws Exception { + XXSecurityZone xxSecurityZone = null; + RangerSecurityZone securityZone = new RangerSecurityZone(); + RangerSecurityZone createdSecurityZone = new RangerSecurityZone(); + createdSecurityZone.setId(2L); + + XXSecurityZoneDao xXSecurityZoneDao = Mockito.mock(XXSecurityZoneDao.class); + XXGlobalStateDao xXGlobalStateDao = Mockito.mock(XXGlobalStateDao.class); + + Mockito.when(daoManager.getXXSecurityZoneDao()).thenReturn(xXSecurityZoneDao); + Mockito.when(xXSecurityZoneDao.findByZoneName(securityZone.getName())).thenReturn(xxSecurityZone); + + Mockito.when(daoManager.getXXGlobalState()).thenReturn(xXGlobalStateDao); + Mockito.doNothing().when(xXGlobalStateDao).onGlobalStateChange(RANGER_GLOBAL_STATE_NAME); + + Mockito.when(securityZoneService.create(securityZone)).thenReturn(createdSecurityZone); + Mockito.doNothing().when(securityZoneRefUpdater).createNewZoneMappingForRefTable(createdSecurityZone); + + RangerSecurityZone expectedSecurityZone = securityZoneDBStore.createSecurityZone(securityZone); + + Assert.assertNull(xxSecurityZone); + Assert.assertEquals(createdSecurityZone.getId(), expectedSecurityZone.getId()); + Mockito.verify(daoManager).getXXSecurityZoneDao(); + Mockito.verify(daoManager).getXXGlobalState(); + Mockito.verify(securityZoneService).create(securityZone); + } + + @Test + public void test2updateSecurityZoneById() throws Exception { + XXSecurityZone xxSecurityZone = new XXSecurityZone(); + xxSecurityZone.setId(2L); + RangerSecurityZone securityZone = new RangerSecurityZone(); + securityZone.setId(2L); + RangerSecurityZone updateSecurityZone = new RangerSecurityZone(); + updateSecurityZone.setId(2L); + + XXGlobalStateDao xXGlobalStateDao = Mockito.mock(XXGlobalStateDao.class); + + Mockito.when(daoManager.getXXGlobalState()).thenReturn(xXGlobalStateDao); + Mockito.doNothing().when(xXGlobalStateDao).onGlobalStateChange(RANGER_GLOBAL_STATE_NAME); + + Mockito.when(securityZoneService.update(securityZone)).thenReturn(updateSecurityZone); + Mockito.doNothing().when(securityZoneRefUpdater).createNewZoneMappingForRefTable(updateSecurityZone); + + RangerSecurityZone expectedSecurityZone = securityZoneDBStore.updateSecurityZoneById(securityZone); + + Assert.assertNotNull(xxSecurityZone); + Assert.assertEquals(updateSecurityZone.getId(), expectedSecurityZone.getId()); + Mockito.verify(daoManager).getXXGlobalState(); + Mockito.verify(securityZoneService).update(securityZone); + } + + @Test + public void test3deleteSecurityZoneByName() throws Exception { + XXSecurityZone xxSecurityZone = new XXSecurityZone(); + xxSecurityZone.setId(2L); + RangerSecurityZone securityZone = new RangerSecurityZone(); + securityZone.setId(2L); + securityZone.setName("sz1"); + + XXSecurityZoneDao xXSecurityZoneDao = Mockito.mock(XXSecurityZoneDao.class); + XXGlobalStateDao xXGlobalStateDao = Mockito.mock(XXGlobalStateDao.class); + + Mockito.when(daoManager.getXXSecurityZoneDao()).thenReturn(xXSecurityZoneDao); + Mockito.when(xXSecurityZoneDao.findByZoneName(securityZone.getName())).thenReturn(xxSecurityZone); + Mockito.when(securityZoneService.read(securityZone.getId())).thenReturn(securityZone); + Mockito.when(daoManager.getXXGlobalState()).thenReturn(xXGlobalStateDao); + Mockito.doNothing().when(xXGlobalStateDao).onGlobalStateChange(RANGER_GLOBAL_STATE_NAME); + Mockito.when(securityZoneRefUpdater.cleanupRefTables(securityZone)).thenReturn(true); + Mockito.when(securityZoneService.delete(securityZone)).thenReturn(true); + + securityZoneDBStore.deleteSecurityZoneByName(securityZone.getName()); + + Assert.assertNotNull(xxSecurityZone); + } + + @Test + public void test4deleteSecurityZoneById() throws Exception { + XXSecurityZone xxSecurityZone = new XXSecurityZone(); + xxSecurityZone.setId(2L); + RangerSecurityZone securityZone = new RangerSecurityZone(); + securityZone.setId(2L); + securityZone.setName("sz1"); + + XXGlobalStateDao xXGlobalStateDao = Mockito.mock(XXGlobalStateDao.class); + Mockito.when(securityZoneService.read(securityZone.getId())).thenReturn(securityZone); + Mockito.when(daoManager.getXXGlobalState()).thenReturn(xXGlobalStateDao); + Mockito.doNothing().when(xXGlobalStateDao).onGlobalStateChange(RANGER_GLOBAL_STATE_NAME); + Mockito.when(securityZoneRefUpdater.cleanupRefTables(securityZone)).thenReturn(true); + Mockito.when(securityZoneService.delete(securityZone)).thenReturn(true); + + securityZoneDBStore.deleteSecurityZoneById(securityZone.getId()); + } + + @Test + public void test5getSecurityZoneByName() throws Exception { + XXSecurityZone xxSecurityZone = new XXSecurityZone(); + xxSecurityZone.setId(2L); + xxSecurityZone.setName("sz1"); + RangerSecurityZone securityZone = new RangerSecurityZone(); + securityZone.setId(2L); + securityZone.setName("sz1"); + RangerSecurityZone createdSecurityZone = new RangerSecurityZone(); + createdSecurityZone.setId(2L); + createdSecurityZone.setName("sz1"); + XXSecurityZoneDao xXSecurityZoneDao = Mockito.mock(XXSecurityZoneDao.class); + + Mockito.when(daoManager.getXXSecurityZoneDao()).thenReturn(xXSecurityZoneDao); + Mockito.when(xXSecurityZoneDao.findByZoneName(securityZone.getName())).thenReturn(xxSecurityZone); + Mockito.when(securityZoneService.read(securityZone.getId())).thenReturn(createdSecurityZone); + + RangerSecurityZone expectedSecurityZone = securityZoneDBStore.getSecurityZoneByName(securityZone.getName()); + + Assert.assertNotNull(xxSecurityZone); + Assert.assertEquals(createdSecurityZone.getName(), expectedSecurityZone.getName()); + Mockito.verify(securityZoneService).read(securityZone.getId()); + } + + @Test + public void test6getSecurityZones() throws Exception { + SearchFilter filter = new SearchFilter(); + filter.setParam(SearchFilter.ZONE_NAME, "sz1"); + + List ret = new ArrayList<>(); + List xxSecurityZones = new ArrayList<>(); + XXSecurityZone xxSecurityZone = new XXSecurityZone(); + xxSecurityZone.setId(2L); + xxSecurityZone.setName("sz1"); + xxSecurityZones.add(xxSecurityZone); + + RangerSecurityZone rangerSecurityZone = new RangerSecurityZone(); + rangerSecurityZone.setId(3L); + ret.add(rangerSecurityZone); + List copy = new ArrayList<>(ret); + + XXSecurityZoneDao xXSecurityZoneDao = Mockito.mock(XXSecurityZoneDao.class); + Mockito.when(daoManager.getXXSecurityZoneDao()).thenReturn(xXSecurityZoneDao); + Mockito.when(xXSecurityZoneDao.getAll()).thenReturn(xxSecurityZones); + Mockito.when(securityZoneService.read(xxSecurityZone.getId())).thenReturn(rangerSecurityZone); + Mockito.doNothing().when(predicateUtil).applyFilter(copy, filter); + + securityZoneDBStore.getSecurityZones(filter); + + Assert.assertNotNull(xxSecurityZone); + Assert.assertNotNull(xxSecurityZones); + Mockito.verify(daoManager).getXXSecurityZoneDao(); + Mockito.verify(securityZoneService).read(xxSecurityZone.getId()); + Mockito.verify(predicateUtil).applyFilter(copy, filter); + } + + @Test + public void test7getSecurityZonesForService() { + String serviceName = "hdfs_service"; + Map retMap; + + SearchFilter filter = new SearchFilter(); + filter.setParam(SearchFilter.ZONE_NAME, "sz1"); + filter.setParam(SearchFilter.SERVICE_NAME, serviceName); + List ret = new ArrayList<>(); + List xxSecurityZones = new ArrayList<>(); + + XXSecurityZone xxSecurityZone = new XXSecurityZone(); + xxSecurityZone.setId(2L); + xxSecurityZone.setName("sz1"); + xxSecurityZones.add(xxSecurityZone); + + RangerSecurityZone rangerSecurityZone = new RangerSecurityZone(); + rangerSecurityZone.setId(3L); + ret.add(rangerSecurityZone); + + XXSecurityZoneDao xXSecurityZoneDao = Mockito.mock(XXSecurityZoneDao.class); + Mockito.when(daoManager.getXXSecurityZoneDao()).thenReturn(xXSecurityZoneDao); + Mockito.when(xXSecurityZoneDao.getAll()).thenReturn(xxSecurityZones); + Mockito.when(securityZoneService.read(xxSecurityZone.getId())).thenReturn(rangerSecurityZone); + retMap = new HashMap<>(); + retMap.put(rangerSecurityZone.getName(), rangerSecurityZone.getServices().get(serviceName)); + + securityZoneDBStore.getSecurityZonesForService(serviceName); + + Assert.assertNotNull(xxSecurityZone); + Assert.assertNotNull(xxSecurityZones); + Mockito.verify(daoManager).getXXSecurityZoneDao(); + Mockito.verify(securityZoneService).read(xxSecurityZone.getId()); + } + + @Test + public void test8createSecurityZoneWithExistingName() throws Exception { + XXSecurityZone xxSecurityZone = new XXSecurityZone(); + xxSecurityZone.setId(2L); + RangerSecurityZone securityZone = new RangerSecurityZone(); + RangerSecurityZone createdSecurityZone = new RangerSecurityZone(); + createdSecurityZone.setId(2L); + + XXSecurityZoneDao xXSecurityZoneDao = Mockito.mock(XXSecurityZoneDao.class); + + Mockito.when(daoManager.getXXSecurityZoneDao()).thenReturn(xXSecurityZoneDao); + Mockito.when(xXSecurityZoneDao.findByZoneName(securityZone.getName())).thenReturn(xxSecurityZone); + Mockito.when(restErrorUtil.createRESTException(Mockito.anyString(), Mockito.any(MessageEnums.class))).thenThrow(new WebApplicationException()); + thrown.expect(WebApplicationException.class); + + securityZoneDBStore.createSecurityZone(securityZone); + + Mockito.verify(daoManager, times(1)).getXXSecurityZoneDao(); + Mockito.verify(xXSecurityZoneDao, times(1)).findByZoneName(securityZone.getName()); + } + + @Test + public void test9updateSecurityZoneByUnknownId() throws Exception { + RangerSecurityZone securityZoneToUpdate = new RangerSecurityZone(); + securityZoneToUpdate.setId(2L); + + XXSecurityZoneDao xXSecurityZoneDao = Mockito.mock(XXSecurityZoneDao.class); + Mockito.when(restErrorUtil.createRESTException(Mockito.anyString())).thenThrow(new WebApplicationException()); + thrown.expect(WebApplicationException.class); + + XXGlobalStateDao xXGlobalStateDao = Mockito.mock(XXGlobalStateDao.class); + Mockito.when(daoManager.getXXGlobalState()).thenReturn(xXGlobalStateDao); + Mockito.doNothing().when(xXGlobalStateDao).onGlobalStateChange(RANGER_GLOBAL_STATE_NAME); + + securityZoneDBStore.updateSecurityZoneById(securityZoneToUpdate); + Mockito.verify(daoManager, times(1)).getXXSecurityZoneDao(); + Mockito.verify(xXSecurityZoneDao, times(1)).findByZoneId(securityZoneToUpdate.getId()); + } + + @Test + public void test10deleteSecurityZoneByWrongName() throws Exception { + XXSecurityZone xxSecurityZone = new XXSecurityZone(); + xxSecurityZone.setId(2L); + RangerSecurityZone securityZone = new RangerSecurityZone(); + securityZone.setId(2L); + securityZone.setName("sz1"); + + XXSecurityZoneDao xXSecurityZoneDao = Mockito.mock(XXSecurityZoneDao.class); + Mockito.when(daoManager.getXXSecurityZoneDao()).thenReturn(xXSecurityZoneDao); + Mockito.when(xXSecurityZoneDao.findByZoneName(securityZone.getName())).thenReturn(null); + Mockito.when(restErrorUtil.createRESTException(Mockito.anyString())).thenThrow(new WebApplicationException()); + thrown.expect(WebApplicationException.class); + + securityZoneDBStore.deleteSecurityZoneByName(securityZone.getName()); + Mockito.verify(xXSecurityZoneDao, times(1)).findByZoneName(xxSecurityZone.getName()); + } + + @Test + public void test11getSecurityZoneByWrongName() throws Exception { + RangerSecurityZone securityZone = new RangerSecurityZone(); + securityZone.setId(2L); + securityZone.setName("sz1"); + + XXSecurityZoneDao xXSecurityZoneDao = Mockito.mock(XXSecurityZoneDao.class); + Mockito.when(daoManager.getXXSecurityZoneDao()).thenReturn(xXSecurityZoneDao); + Mockito.when(xXSecurityZoneDao.findByZoneName(securityZone.getName())).thenReturn(null); + Mockito.when(restErrorUtil.createRESTException(Mockito.anyString())).thenThrow(new WebApplicationException()); + thrown.expect(WebApplicationException.class); + + securityZoneDBStore.getSecurityZoneByName(securityZone.getName()); + Mockito.verify(xXSecurityZoneDao, times(1)).findByZoneName(securityZone.getName()); + } } diff --git a/security-admin/src/test/java/org/apache/ranger/biz/TestServiceDBStore.java b/security-admin/src/test/java/org/apache/ranger/biz/TestServiceDBStore.java index 671b80de54..7747e327ac 100644 --- a/security-admin/src/test/java/org/apache/ranger/biz/TestServiceDBStore.java +++ b/security-admin/src/test/java/org/apache/ranger/biz/TestServiceDBStore.java @@ -17,16 +17,6 @@ package org.apache.ranger.biz; -import static org.mockito.ArgumentMatchers.anyString; - -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.Set; - import org.apache.commons.collections.ListUtils; import org.apache.ranger.common.ContextUtil; import org.apache.ranger.common.GUIDUtil; @@ -38,8 +28,59 @@ import org.apache.ranger.common.StringUtil; import org.apache.ranger.common.UserSessionBase; import org.apache.ranger.common.db.RangerTransactionSynchronizationAdapter; -import org.apache.ranger.db.*; -import org.apache.ranger.entity.*; +import org.apache.ranger.db.RangerDaoManager; +import org.apache.ranger.db.XXAccessTypeDefDao; +import org.apache.ranger.db.XXAccessTypeDefGrantsDao; +import org.apache.ranger.db.XXContextEnricherDefDao; +import org.apache.ranger.db.XXDataHistDao; +import org.apache.ranger.db.XXDataMaskTypeDefDao; +import org.apache.ranger.db.XXEnumDefDao; +import org.apache.ranger.db.XXEnumElementDefDao; +import org.apache.ranger.db.XXGroupDao; +import org.apache.ranger.db.XXGroupGroupDao; +import org.apache.ranger.db.XXPolicyConditionDefDao; +import org.apache.ranger.db.XXPolicyDao; +import org.apache.ranger.db.XXPolicyLabelMapDao; +import org.apache.ranger.db.XXPolicyRefAccessTypeDao; +import org.apache.ranger.db.XXPolicyRefConditionDao; +import org.apache.ranger.db.XXPolicyRefResourceDao; +import org.apache.ranger.db.XXRMSServiceResourceDao; +import org.apache.ranger.db.XXResourceDefDao; +import org.apache.ranger.db.XXRoleDao; +import org.apache.ranger.db.XXSecurityZoneDao; +import org.apache.ranger.db.XXServiceConfigDefDao; +import org.apache.ranger.db.XXServiceConfigMapDao; +import org.apache.ranger.db.XXServiceDao; +import org.apache.ranger.db.XXServiceDefDao; +import org.apache.ranger.db.XXServiceVersionInfoDao; +import org.apache.ranger.db.XXUserDao; +import org.apache.ranger.entity.XXAccessTypeDef; +import org.apache.ranger.entity.XXAccessTypeDefGrants; +import org.apache.ranger.entity.XXContextEnricherDef; +import org.apache.ranger.entity.XXDataHist; +import org.apache.ranger.entity.XXEnumDef; +import org.apache.ranger.entity.XXEnumElementDef; +import org.apache.ranger.entity.XXGroup; +import org.apache.ranger.entity.XXPolicy; +import org.apache.ranger.entity.XXPolicyConditionDef; +import org.apache.ranger.entity.XXPolicyItem; +import org.apache.ranger.entity.XXPolicyItemAccess; +import org.apache.ranger.entity.XXPolicyItemCondition; +import org.apache.ranger.entity.XXPolicyItemGroupPerm; +import org.apache.ranger.entity.XXPolicyItemUserPerm; +import org.apache.ranger.entity.XXPolicyRefAccessType; +import org.apache.ranger.entity.XXPolicyRefCondition; +import org.apache.ranger.entity.XXPolicyRefResource; +import org.apache.ranger.entity.XXPolicyResource; +import org.apache.ranger.entity.XXPolicyResourceMap; +import org.apache.ranger.entity.XXResourceDef; +import org.apache.ranger.entity.XXRole; +import org.apache.ranger.entity.XXService; +import org.apache.ranger.entity.XXServiceConfigDef; +import org.apache.ranger.entity.XXServiceConfigMap; +import org.apache.ranger.entity.XXServiceDef; +import org.apache.ranger.entity.XXServiceVersionInfo; +import org.apache.ranger.entity.XXUser; import org.apache.ranger.plugin.model.RangerPolicy; import org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyItem; import org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyItemAccess; @@ -88,2647 +129,2423 @@ import org.mockito.Mockito; import org.mockito.junit.MockitoJUnitRunner; +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.Set; + +import static org.mockito.ArgumentMatchers.anyString; + @RunWith(MockitoJUnitRunner.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class TestServiceDBStore { - private static Long Id = 8L; + private static final String CFG_SERVICE_ADMIN_USERS = "service.admin.users"; + private static final String CFG_SERVICE_ADMIN_GROUPS = "service.admin.groups"; + private static final Long Id = 8L; + @Rule + public ExpectedException thrown = ExpectedException.none(); + @InjectMocks + ServiceDBStore serviceDBStore = new ServiceDBStore(); + @Mock + RangerDaoManager daoManager; + @Mock + RangerServiceService svcService; + @Mock + RangerDataHistService dataHistService; + @Mock + RangerServiceDefService serviceDefService; + @Mock + RangerPolicyService policyService; + @Mock + StringUtil stringUtil; + @Mock + XUserService xUserService; + @Mock + XUserMgr xUserMgr; + @Mock + RangerAuditFields rangerAuditFields; + @Mock + ContextUtil contextUtil; + @Mock + RangerBizUtil bizUtil; + @Mock + RangerServiceWithAssignedIdService svcServiceWithAssignedId; + @Mock + RangerFactory factory; + @Mock + ServicePredicateUtil predicateUtil; + @Mock + PolicyRefUpdater policyRefUpdater; + @Mock + XGroupService xGroupService; + @Mock + RESTErrorUtil restErrorUtil; + @Mock + AssetMgr assetMgr; + @Mock + RangerTransactionSynchronizationAdapter transactionSynchronizationAdapter; + @Mock + JSONUtil jsonUtil; + @Mock + GUIDUtil guidUtil; + @Mock + TagDBStore tagStore; + + public void setup() { + RangerSecurityContext context = new RangerSecurityContext(); + context.setUserSession(new UserSessionBase()); + RangerContextHolder.setSecurityContext(context); + UserSessionBase currentUserSession = ContextUtil.getCurrentUserSession(); + currentUserSession.setUserAdmin(true); + } + + @Test + public void test11createServiceDef() throws Exception { + XXServiceDefDao xServiceDefDao = Mockito.mock(XXServiceDefDao.class); + XXResourceDefDao xResourceDefDao = Mockito.mock(XXResourceDefDao.class); + XXServiceConfigDefDao xServiceConfigDefDao = Mockito.mock(XXServiceConfigDefDao.class); + XXAccessTypeDefDao xAccessTypeDefDao = Mockito.mock(XXAccessTypeDefDao.class); + XXPolicyConditionDefDao xPolicyConditionDefDao = Mockito.mock(XXPolicyConditionDefDao.class); + XXContextEnricherDefDao xContextEnricherDefDao = Mockito.mock(XXContextEnricherDefDao.class); + XXEnumDefDao xEnumDefDao = Mockito.mock(XXEnumDefDao.class); + + XXServiceDef xServiceDef = Mockito.mock(XXServiceDef.class); + XXResourceDef xResourceDef = Mockito.mock(XXResourceDef.class); + XXAccessTypeDef xAccessTypeDef = Mockito.mock(XXAccessTypeDef.class); + + List xAccessTypeDefs = new ArrayList<>(); + xAccessTypeDefs.add(xAccessTypeDef); + + List xResourceDefs = new ArrayList<>(); + xResourceDefs.add(xResourceDef); + + RangerServiceDef serviceDef = new RangerServiceDef(); + Mockito.when(serviceDefService.create(serviceDef)).thenReturn(serviceDef); + + Mockito.when(daoManager.getXXServiceDef()).thenReturn(xServiceDefDao); + Mockito.when(daoManager.getXXServiceDef()).thenReturn(xServiceDefDao); + Mockito.when(xServiceDefDao.getById(null)).thenReturn(xServiceDef); + + Mockito.when(daoManager.getXXServiceConfigDef()).thenReturn(xServiceConfigDefDao); + + Mockito.when(daoManager.getXXResourceDef()).thenReturn(xResourceDefDao); + Mockito.when(xResourceDefDao.findByServiceDefId(xServiceDef.getId())).thenReturn(xResourceDefs); + + Mockito.when(daoManager.getXXAccessTypeDef()).thenReturn(xAccessTypeDefDao); + Mockito.when(xAccessTypeDefDao.findByServiceDefId(xServiceDef.getId())).thenReturn(xAccessTypeDefs); + + Mockito.when(daoManager.getXXPolicyConditionDef()).thenReturn(xPolicyConditionDefDao); + Mockito.when(daoManager.getXXContextEnricherDef()).thenReturn(xContextEnricherDefDao); + + Mockito.when(daoManager.getXXEnumDef()).thenReturn(xEnumDefDao); + + Mockito.when(serviceDefService.getPopulatedViewObject(xServiceDef)).thenReturn(serviceDef); + + RangerServiceDef dbServiceDef = serviceDBStore.createServiceDef(serviceDef); + Assert.assertNotNull(dbServiceDef); + Assert.assertEquals(dbServiceDef, serviceDef); + Assert.assertEquals(dbServiceDef.getId(), serviceDef.getId()); + Assert.assertEquals(dbServiceDef.getCreatedBy(), serviceDef.getCreatedBy()); + Assert.assertEquals(dbServiceDef.getDescription(), serviceDef.getDescription()); + Assert.assertEquals(dbServiceDef.getGuid(), serviceDef.getGuid()); + Assert.assertEquals(dbServiceDef.getImplClass(), serviceDef.getImplClass()); + Assert.assertEquals(dbServiceDef.getLabel(), serviceDef.getLabel()); + Assert.assertEquals(dbServiceDef.getName(), serviceDef.getName()); + Assert.assertEquals(dbServiceDef.getRbKeyDescription(), serviceDef.getRbKeyDescription()); + Assert.assertEquals(dbServiceDef.getRbKeyLabel(), serviceDef.getLabel()); + Assert.assertEquals(dbServiceDef.getConfigs(), serviceDef.getConfigs()); + Assert.assertEquals(dbServiceDef.getVersion(), serviceDef.getVersion()); + Assert.assertEquals(dbServiceDef.getResources(), serviceDef.getResources()); + Mockito.verify(serviceDefService).getPopulatedViewObject(xServiceDef); + Mockito.verify(serviceDefService).create(serviceDef); + Mockito.verify(daoManager).getXXServiceConfigDef(); + Mockito.verify(daoManager).getXXEnumDef(); + Mockito.verify(daoManager).getXXAccessTypeDef(); + } + + @Test + public void test12updateServiceDef() throws Exception { + setup(); + XXServiceDefDao xServiceDefDao = Mockito.mock(XXServiceDefDao.class); + XXServiceDef xServiceDef = Mockito.mock(XXServiceDef.class); + XXServiceConfigDefDao xServiceConfigDefDao = Mockito.mock(XXServiceConfigDefDao.class); + XXResourceDefDao xResourceDefDao = Mockito.mock(XXResourceDefDao.class); + XXAccessTypeDefDao xAccessTypeDefDao = Mockito.mock(XXAccessTypeDefDao.class); + XXPolicyConditionDefDao xPolicyConditionDefDao = Mockito.mock(XXPolicyConditionDefDao.class); + XXContextEnricherDefDao xContextEnricherDefDao = Mockito.mock(XXContextEnricherDefDao.class); + XXEnumDefDao xEnumDefDao = Mockito.mock(XXEnumDefDao.class); + XXDataMaskTypeDefDao xDataMaskDefDao = Mockito.mock(XXDataMaskTypeDefDao.class); + XXServiceDao xServiceDao = Mockito.mock(XXServiceDao.class); + + RangerServiceDef rangerServiceDef = rangerServiceDef(); + Long serviceDefId = rangerServiceDef.getId(); + + List svcConfDefList = new ArrayList<>(); + XXServiceConfigDef serviceConfigDefObj = new XXServiceConfigDef(); + serviceConfigDefObj.setId(Id); + serviceConfigDefObj.setType("1"); + svcConfDefList.add(serviceConfigDefObj); + + Mockito.when(serviceDefService.populateRangerServiceConfigDefToXX(Mockito.any(RangerServiceConfigDef.class), Mockito.any(XXServiceConfigDef.class), Mockito.any(XXServiceDef.class), Mockito.eq(RangerServiceDefService.OPERATION_CREATE_CONTEXT))).thenReturn(serviceConfigDefObj); + Mockito.when(xServiceConfigDefDao.create(serviceConfigDefObj)).thenReturn(serviceConfigDefObj); + + List resDefList = new ArrayList<>(); + XXResourceDef resourceDef = new XXResourceDef(); + resourceDef.setAddedByUserId(Id); + resourceDef.setCreateTime(new Date()); + resourceDef.setDefid(Id); + resourceDef.setDescription("test"); + resourceDef.setId(Id); + resDefList.add(resourceDef); + + List accessTypeDefList = new ArrayList<>(); + XXAccessTypeDef accessTypeDefObj = new XXAccessTypeDef(); + accessTypeDefObj.setAddedByUserId(Id); + accessTypeDefObj.setCreateTime(new Date()); + accessTypeDefObj.setDefid(Id); + accessTypeDefObj.setId(Id); + accessTypeDefObj.setLabel("Read"); + accessTypeDefObj.setName("read"); + accessTypeDefObj.setOrder(null); + accessTypeDefObj.setRbkeylabel(null); + accessTypeDefObj.setUpdatedByUserId(Id); + accessTypeDefObj.setUpdateTime(new Date()); + accessTypeDefList.add(accessTypeDefObj); + + List policyConditionDefList = new ArrayList<>(); + XXPolicyConditionDef policyConditionDefObj = new XXPolicyConditionDef(); + policyConditionDefObj.setAddedByUserId(Id); + policyConditionDefObj.setCreateTime(new Date()); + policyConditionDefObj.setDefid(Id); + policyConditionDefObj.setDescription("policy"); + policyConditionDefObj.setId(Id); + policyConditionDefObj.setName("country"); + policyConditionDefObj.setOrder(0); + policyConditionDefObj.setUpdatedByUserId(Id); + policyConditionDefObj.setUpdateTime(new Date()); + policyConditionDefList.add(policyConditionDefObj); + + List contextEnricherDefList = new ArrayList<>(); + XXContextEnricherDef contextEnricherDefObj = new XXContextEnricherDef(); + contextEnricherDefObj.setAddedByUserId(Id); + contextEnricherDefObj.setCreateTime(new Date()); + contextEnricherDefObj.setDefid(Id); + contextEnricherDefObj.setId(Id); + contextEnricherDefObj.setName("country-provider"); + contextEnricherDefObj.setEnricherOptions("contextName=COUNTRY;dataFile=/etc/ranger/data/userCountry.properties"); + contextEnricherDefObj.setEnricher("RangerCountryProvider"); + contextEnricherDefObj.setOrder(null); + contextEnricherDefObj.setUpdatedByUserId(Id); + contextEnricherDefObj.setUpdateTime(new Date()); + contextEnricherDefList.add(contextEnricherDefObj); + + List enumDefList = new ArrayList<>(); + XXEnumDef enumDefObj = new XXEnumDef(); + enumDefObj.setAddedByUserId(Id); + enumDefObj.setCreateTime(new Date()); + enumDefObj.setDefaultindex(0); + enumDefObj.setDefid(Id); + enumDefObj.setId(Id); + enumDefObj.setName("authnType"); + enumDefObj.setUpdatedByUserId(Id); + enumDefObj.setUpdateTime(new Date()); + enumDefList.add(enumDefObj); + + Mockito.when(daoManager.getXXServiceDef()).thenReturn(xServiceDefDao); + Mockito.when(xServiceDefDao.getById(serviceDefId)).thenReturn(xServiceDef); + + Mockito.when(daoManager.getXXServiceConfigDef()).thenReturn(xServiceConfigDefDao); + Mockito.when(daoManager.getXXResourceDef()).thenReturn(xResourceDefDao); + Mockito.when(daoManager.getXXAccessTypeDef()).thenReturn(xAccessTypeDefDao); + Mockito.when(daoManager.getXXPolicyConditionDef()).thenReturn(xPolicyConditionDefDao); + Mockito.when(daoManager.getXXContextEnricherDef()).thenReturn(xContextEnricherDefDao); + Mockito.when(daoManager.getXXEnumDef()).thenReturn(xEnumDefDao); + Mockito.when(daoManager.getXXDataMaskTypeDef()).thenReturn(xDataMaskDefDao); + Mockito.when(daoManager.getXXService()).thenReturn(xServiceDao); + Mockito.when(xServiceDao.findByServiceDefId(serviceDefId)).thenReturn(null); + Mockito.when(serviceDefService.read(Id)).thenReturn(rangerServiceDef); + + RangerServiceDef dbServiceDef = serviceDBStore.updateServiceDef(rangerServiceDef); + Assert.assertNotNull(dbServiceDef); + Assert.assertEquals(dbServiceDef, rangerServiceDef); + Assert.assertEquals(dbServiceDef.getId(), rangerServiceDef.getId()); + Assert.assertEquals(dbServiceDef.getCreatedBy(), rangerServiceDef.getCreatedBy()); + Assert.assertEquals(dbServiceDef.getDescription(), rangerServiceDef.getDescription()); + Assert.assertEquals(dbServiceDef.getGuid(), rangerServiceDef.getGuid()); + Assert.assertEquals(dbServiceDef.getImplClass(), rangerServiceDef.getImplClass()); + Assert.assertEquals(dbServiceDef.getLabel(), rangerServiceDef.getLabel()); + Assert.assertEquals(dbServiceDef.getName(), rangerServiceDef.getName()); + Assert.assertEquals(dbServiceDef.getRbKeyDescription(), rangerServiceDef.getRbKeyDescription()); + Assert.assertEquals(dbServiceDef.getConfigs(), rangerServiceDef.getConfigs()); + Assert.assertEquals(dbServiceDef.getVersion(), rangerServiceDef.getVersion()); + Assert.assertEquals(dbServiceDef.getResources(), rangerServiceDef.getResources()); + } + + @Test + public void test13deleteServiceDef() throws Exception { + setup(); + XXServiceDao xServiceDao = Mockito.mock(XXServiceDao.class); + XXDataMaskTypeDefDao xDataMaskDefDao = Mockito.mock(XXDataMaskTypeDefDao.class); + XXAccessTypeDefDao xAccessTypeDefDao = Mockito.mock(XXAccessTypeDefDao.class); + XXAccessTypeDefGrantsDao xAccessTypeDefGrantsDao = Mockito.mock(XXAccessTypeDefGrantsDao.class); + XXPolicyRefAccessTypeDao xPolicyRefAccessTypeDao = Mockito.mock(XXPolicyRefAccessTypeDao.class); + XXPolicyRefConditionDao xPolicyRefConditionDao = Mockito.mock(XXPolicyRefConditionDao.class); + XXPolicyRefResourceDao xPolicyRefResourceDao = Mockito.mock(XXPolicyRefResourceDao.class); + XXContextEnricherDefDao xContextEnricherDefDao = Mockito.mock(XXContextEnricherDefDao.class); + XXEnumDefDao xEnumDefDao = Mockito.mock(XXEnumDefDao.class); + XXEnumElementDefDao xEnumElementDefDao = Mockito.mock(XXEnumElementDefDao.class); + XXPolicyConditionDefDao xPolicyConditionDefDao = Mockito.mock(XXPolicyConditionDefDao.class); + XXResourceDefDao xResourceDefDao = Mockito.mock(XXResourceDefDao.class); + XXServiceConfigDefDao xServiceConfigDefDao = Mockito.mock(XXServiceConfigDefDao.class); + + RangerServiceDef rangerServiceDef = rangerServiceDef(); + RangerService rangerService = rangerService(); + String name = "fdfdfds"; + Long serviceDefId = rangerServiceDef.getId(); + + List xServiceList = new ArrayList<>(); + XXService xService = new XXService(); + xService.setAddedByUserId(Id); + xService.setCreateTime(new Date()); + xService.setDescription("Hdfs service"); + xService.setGuid("serviceguid"); + xService.setId(Id); + xService.setIsEnabled(true); + xService.setName("Hdfs"); + xService.setPolicyUpdateTime(new Date()); + xService.setPolicyVersion(1L); + xService.setType(1L); + xService.setUpdatedByUserId(Id); + xService.setUpdateTime(new Date()); + xServiceList.add(xService); + + List accessTypeDefList = new ArrayList<>(); + XXAccessTypeDef accessTypeDefObj = new XXAccessTypeDef(); + accessTypeDefObj.setAddedByUserId(Id); + accessTypeDefObj.setCreateTime(new Date()); + accessTypeDefObj.setDefid(Id); + accessTypeDefObj.setId(Id); + accessTypeDefObj.setLabel("Read"); + accessTypeDefObj.setName("read"); + accessTypeDefObj.setOrder(null); + accessTypeDefObj.setRbkeylabel(null); + accessTypeDefObj.setUpdatedByUserId(Id); + accessTypeDefObj.setUpdateTime(new Date()); + accessTypeDefList.add(accessTypeDefObj); + + List accessTypeDefGrantslist = new ArrayList<>(); + XXAccessTypeDefGrants accessTypeDefGrantsObj = new XXAccessTypeDefGrants(); + accessTypeDefGrantsObj.setAddedByUserId(Id); + accessTypeDefGrantsObj.setAtdId(Id); + accessTypeDefGrantsObj.setCreateTime(new Date()); + accessTypeDefGrantsObj.setId(Id); + accessTypeDefGrantsObj.setUpdatedByUserId(Id); + accessTypeDefGrantsObj.setUpdateTime(new Date()); + accessTypeDefGrantsObj.setImpliedGrant("read"); + accessTypeDefGrantslist.add(accessTypeDefGrantsObj); + + List policyItemAccessList = new ArrayList<>(); + XXPolicyItemAccess policyItemAccess = new XXPolicyItemAccess(); + policyItemAccess.setAddedByUserId(Id); + policyItemAccess.setCreateTime(new Date()); + policyItemAccess.setPolicyitemid(Id); + policyItemAccess.setId(Id); + policyItemAccess.setOrder(1); + policyItemAccess.setUpdatedByUserId(Id); + policyItemAccess.setUpdateTime(new Date()); + policyItemAccessList.add(policyItemAccess); + + List contextEnricherDefList = new ArrayList<>(); + XXContextEnricherDef contextEnricherDefObj = new XXContextEnricherDef(); + contextEnricherDefObj.setAddedByUserId(Id); + contextEnricherDefObj.setCreateTime(new Date()); + contextEnricherDefObj.setDefid(Id); + contextEnricherDefObj.setId(Id); + contextEnricherDefObj.setName("country-provider"); + contextEnricherDefObj.setEnricherOptions("contextName=COUNTRY;dataFile=/etc/ranger/data/userCountry.properties"); + contextEnricherDefObj.setEnricher("RangerCountryProvider"); + contextEnricherDefObj.setOrder(null); + contextEnricherDefObj.setUpdatedByUserId(Id); + contextEnricherDefObj.setUpdateTime(new Date()); + contextEnricherDefList.add(contextEnricherDefObj); + + List enumDefList = new ArrayList<>(); + XXEnumDef enumDefObj = new XXEnumDef(); + enumDefObj.setAddedByUserId(Id); + enumDefObj.setCreateTime(new Date()); + enumDefObj.setDefaultindex(0); + enumDefObj.setDefid(Id); + enumDefObj.setId(Id); + enumDefObj.setName("authnType"); + enumDefObj.setUpdatedByUserId(Id); + enumDefObj.setUpdateTime(new Date()); + enumDefList.add(enumDefObj); + + List xElementsList = new ArrayList<>(); + XXEnumElementDef enumElementDefObj = new XXEnumElementDef(); + enumElementDefObj.setAddedByUserId(Id); + enumElementDefObj.setCreateTime(new Date()); + enumElementDefObj.setEnumdefid(Id); + enumElementDefObj.setId(Id); + enumElementDefObj.setLabel("Authentication"); + enumElementDefObj.setName("authentication"); + enumElementDefObj.setUpdateTime(new Date()); + enumElementDefObj.setUpdatedByUserId(Id); + enumElementDefObj.setRbkeylabel(null); + enumElementDefObj.setOrder(0); + xElementsList.add(enumElementDefObj); + + List xConditionDefList = new ArrayList<>(); + XXPolicyConditionDef policyConditionDefObj = new XXPolicyConditionDef(); + policyConditionDefObj.setAddedByUserId(Id); + policyConditionDefObj.setCreateTime(new Date()); + policyConditionDefObj.setDefid(Id); + policyConditionDefObj.setDescription("policy condition"); + policyConditionDefObj.setId(Id); + policyConditionDefObj.setName(name); + policyConditionDefObj.setOrder(1); + policyConditionDefObj.setLabel("label"); + xConditionDefList.add(policyConditionDefObj); + + List policyItemConditionList = new ArrayList<>(); + XXPolicyItemCondition policyItemCondition = new XXPolicyItemCondition(); + policyItemCondition.setAddedByUserId(Id); + policyItemCondition.setCreateTime(new Date()); + policyItemCondition.setType(1L); + policyItemCondition.setId(Id); + policyItemCondition.setOrder(1); + policyItemCondition.setPolicyItemId(Id); + policyItemCondition.setUpdatedByUserId(Id); + policyItemCondition.setUpdateTime(new Date()); + policyItemConditionList.add(policyItemCondition); + + List resDefList = new ArrayList<>(); + XXResourceDef resourceDef = new XXResourceDef(); + resourceDef.setAddedByUserId(Id); + resourceDef.setCreateTime(new Date()); + resourceDef.setDefid(Id); + resourceDef.setDescription("test"); + resourceDef.setId(Id); + resDefList.add(resourceDef); + + List policyResourceList = new ArrayList<>(); + XXPolicyResource policyResource = new XXPolicyResource(); + policyResource.setId(Id); + policyResource.setCreateTime(new Date()); + policyResource.setAddedByUserId(Id); + policyResource.setIsExcludes(false); + policyResource.setIsRecursive(false); + policyResource.setPolicyId(Id); + policyResource.setResDefId(Id); + policyResource.setUpdatedByUserId(Id); + policyResource.setUpdateTime(new Date()); + policyResourceList.add(policyResource); + + List policyResourceMapList = new ArrayList<>(); + XXPolicyResourceMap policyResourceMap = new XXPolicyResourceMap(); + policyResourceMap.setAddedByUserId(Id); + policyResourceMap.setCreateTime(new Date()); + policyResourceMap.setId(Id); + policyResourceMap.setOrder(1); + policyResourceMap.setResourceId(Id); + policyResourceMap.setUpdatedByUserId(Id); + policyResourceMap.setUpdateTime(new Date()); + policyResourceMap.setValue("1L"); + policyResourceMapList.add(policyResourceMap); + + List serviceConfigDefList = new ArrayList<>(); + XXServiceConfigDef serviceConfigDefObj = new XXServiceConfigDef(); + serviceConfigDefObj.setAddedByUserId(Id); + serviceConfigDefObj.setCreateTime(new Date()); + serviceConfigDefObj.setDefaultvalue("simple"); + serviceConfigDefObj.setDescription("service config"); + serviceConfigDefObj.setId(Id); + serviceConfigDefObj.setIsMandatory(true); + serviceConfigDefObj.setName(name); + serviceConfigDefObj.setLabel("username"); + serviceConfigDefObj.setRbkeydescription(null); + serviceConfigDefObj.setRbkeylabel(null); + serviceConfigDefObj.setRbKeyValidationMessage(null); + serviceConfigDefObj.setType("password"); + serviceConfigDefList.add(serviceConfigDefObj); + + List policiesList = new ArrayList<>(); + XXPolicy policy = new XXPolicy(); + policy.setAddedByUserId(Id); + policy.setCreateTime(new Date()); + policy.setDescription("polcy test"); + policy.setGuid(""); + policy.setId(rangerService.getId()); + policy.setIsAuditEnabled(true); + policy.setName("HDFS_1-1-20150316062453"); + policy.setService(rangerService.getId()); + policiesList.add(policy); + + List policyItemList = new ArrayList<>(); + XXPolicyItem policyItem = new XXPolicyItem(); + policyItem.setAddedByUserId(Id); + policyItem.setCreateTime(new Date()); + policyItem.setDelegateAdmin(false); + policyItem.setId(Id); + policyItem.setOrder(1); + policyItem.setPolicyId(Id); + policyItem.setUpdatedByUserId(Id); + policyItem.setUpdateTime(new Date()); + policyItemList.add(policyItem); + + XXServiceConfigMap xConfMap = new XXServiceConfigMap(); + xConfMap.setAddedByUserId(null); + xConfMap.setConfigkey(name); + xConfMap.setConfigvalue(name); + xConfMap.setCreateTime(new Date()); + xConfMap.setServiceId(Id); + + List policyItemGroupPermlist = new ArrayList<>(); + XXPolicyItemGroupPerm policyItemGroupPermObj = new XXPolicyItemGroupPerm(); + policyItemGroupPermObj.setAddedByUserId(Id); + policyItemGroupPermObj.setCreateTime(new Date()); + policyItemGroupPermObj.setGroupId(Id); + policyItemGroupPermObj.setId(Id); + policyItemGroupPermObj.setOrder(1); + policyItemGroupPermObj.setPolicyItemId(Id); + policyItemGroupPermObj.setUpdatedByUserId(Id); + policyItemGroupPermObj.setUpdateTime(new Date()); + policyItemGroupPermlist.add(policyItemGroupPermObj); + + List policyItemUserPermList = new ArrayList<>(); + XXPolicyItemUserPerm policyItemUserPermObj = new XXPolicyItemUserPerm(); + policyItemUserPermObj.setAddedByUserId(Id); + policyItemUserPermObj.setCreateTime(new Date()); + policyItemUserPermObj.setId(Id); + policyItemUserPermObj.setOrder(1); + policyItemUserPermObj.setPolicyItemId(Id); + policyItemUserPermObj.setUpdatedByUserId(serviceDefId); + policyItemUserPermObj.setUpdateTime(new Date()); + policyItemUserPermObj.setUserId(Id); + policyItemUserPermList.add(policyItemUserPermObj); + + List policyRefAccessTypeList = new ArrayList<>(); + XXPolicyRefAccessType policyRefAccessType = new XXPolicyRefAccessType(); + policyRefAccessType.setId(Id); + policyRefAccessType.setAccessTypeName("myAccessType"); + policyRefAccessType.setPolicyId(Id); + policyRefAccessType.setCreateTime(new Date()); + policyRefAccessType.setUpdateTime(new Date()); + policyRefAccessType.setAddedByUserId(Id); + policyRefAccessType.setUpdatedByUserId(Id); + policyRefAccessTypeList.add(policyRefAccessType); + + List policyRefConditionsList = new ArrayList<>(); + XXPolicyRefCondition policyRefCondition = new XXPolicyRefCondition(); + policyRefCondition.setId(Id); + policyRefCondition.setAddedByUserId(Id); + policyRefCondition.setConditionDefId(Id); + policyRefCondition.setConditionName("myConditionName"); + policyRefCondition.setPolicyId(Id); + policyRefCondition.setUpdatedByUserId(Id); + policyRefCondition.setCreateTime(new Date()); + policyRefCondition.setUpdateTime(new Date()); + policyRefConditionsList.add(policyRefCondition); + + List policyRefResourcesList = new ArrayList<>(); + XXPolicyRefResource policyRefResource = new XXPolicyRefResource(); + policyRefResource.setAddedByUserId(Id); + policyRefResource.setCreateTime(new Date()); + policyRefResource.setId(Id); + policyRefResource.setPolicyId(Id); + policyRefResource.setResourceDefId(Id); + policyRefResource.setUpdateTime(new Date()); + policyRefResource.setResourceName("myresourceName"); + policyRefResourcesList.add(policyRefResource); + + XXUser xUser = new XXUser(); + xUser.setAddedByUserId(Id); + xUser.setCreateTime(new Date()); + xUser.setCredStoreId(Id); + xUser.setDescription("user test"); + xUser.setId(Id); + xUser.setIsVisible(null); + xUser.setName(name); + xUser.setStatus(0); + xUser.setUpdatedByUserId(Id); + xUser.setUpdateTime(new Date()); + + Mockito.when(daoManager.getXXPolicyRefAccessType()).thenReturn(xPolicyRefAccessTypeDao); + Mockito.when(xPolicyRefAccessTypeDao.findByAccessTypeDefId(Id)).thenReturn(policyRefAccessTypeList); + Mockito.when(xPolicyRefAccessTypeDao.remove(policyRefAccessType)).thenReturn(true); + + Mockito.when(daoManager.getXXPolicyRefCondition()).thenReturn(xPolicyRefConditionDao); + Mockito.when(xPolicyRefConditionDao.findByConditionDefId(Id)).thenReturn(policyRefConditionsList); + Mockito.when(xPolicyRefConditionDao.remove(policyRefCondition)).thenReturn(true); + + Mockito.when(daoManager.getXXPolicyRefResource()).thenReturn(xPolicyRefResourceDao); + Mockito.when(xPolicyRefResourceDao.findByResourceDefID(Id)).thenReturn(policyRefResourcesList); + Mockito.when(xPolicyRefResourceDao.remove(policyRefResource)).thenReturn(true); + + Mockito.when(serviceDefService.read(Id)).thenReturn(rangerServiceDef); + Mockito.when(daoManager.getXXService()).thenReturn(xServiceDao); + Mockito.when(xServiceDao.findByServiceDefId(serviceDefId)).thenReturn(null); + Mockito.when(daoManager.getXXAccessTypeDef()).thenReturn(xAccessTypeDefDao); + Mockito.when(xAccessTypeDefDao.findByServiceDefId(serviceDefId)).thenReturn(accessTypeDefList); + Mockito.when(daoManager.getXXAccessTypeDefGrants()).thenReturn(xAccessTypeDefGrantsDao); + Mockito.when(xAccessTypeDefGrantsDao.findByATDId(accessTypeDefObj.getId())).thenReturn(accessTypeDefGrantslist); + Mockito.when(daoManager.getXXContextEnricherDef()).thenReturn(xContextEnricherDefDao); + Mockito.when(xContextEnricherDefDao.findByServiceDefId(serviceDefId)).thenReturn(contextEnricherDefList); + Mockito.when(daoManager.getXXEnumDef()).thenReturn(xEnumDefDao); + Mockito.when(xEnumDefDao.findByServiceDefId(serviceDefId)).thenReturn(enumDefList); + Mockito.when(daoManager.getXXEnumElementDef()).thenReturn(xEnumElementDefDao); + Mockito.when(xEnumElementDefDao.findByEnumDefId(enumDefObj.getId())).thenReturn(xElementsList); + + Mockito.when(daoManager.getXXPolicyConditionDef()).thenReturn(xPolicyConditionDefDao); + Mockito.when(xPolicyConditionDefDao.findByServiceDefId(serviceDefId)).thenReturn(xConditionDefList); + + Mockito.when(daoManager.getXXResourceDef()).thenReturn(xResourceDefDao); + Mockito.when(xResourceDefDao.findByServiceDefId(serviceDefId)).thenReturn(resDefList); + + Mockito.when(daoManager.getXXServiceConfigDef()).thenReturn(xServiceConfigDefDao); + Mockito.when(xServiceConfigDefDao.findByServiceDefId(serviceDefId)).thenReturn(serviceConfigDefList); + + Mockito.when(daoManager.getXXService()).thenReturn(xServiceDao); + + svcServiceWithAssignedId.setPopulateExistingBaseFields(true); + + Mockito.when(daoManager.getXXService()).thenReturn(xServiceDao); + Mockito.when(xServiceDao.findByServiceDefId(serviceDefId)).thenReturn(null); + + Mockito.when(daoManager.getXXService()).thenReturn(xServiceDao); + + Mockito.when(daoManager.getXXDataMaskTypeDef()).thenReturn(xDataMaskDefDao); + Mockito.when(xDataMaskDefDao.findByServiceDefId(serviceDefId)).thenReturn(new ArrayList<>()); + + serviceDBStore.deleteServiceDef(Id, true); + Mockito.verify(daoManager).getXXContextEnricherDef(); + Mockito.verify(daoManager).getXXEnumDef(); + } + + @Test + public void test14getServiceDef() throws Exception { + RangerServiceDef rangerServiceDef = rangerServiceDef(); + Mockito.when(serviceDefService.read(Id)).thenReturn(rangerServiceDef); + RangerServiceDef dbRangerServiceDef = serviceDBStore.getServiceDef(Id); + Assert.assertNotNull(dbRangerServiceDef); + Assert.assertEquals(dbRangerServiceDef, rangerServiceDef); + Assert.assertEquals(dbRangerServiceDef.getId(), rangerServiceDef.getId()); + Assert.assertEquals(dbRangerServiceDef.getCreatedBy(), rangerServiceDef.getCreatedBy()); + Assert.assertEquals(dbRangerServiceDef.getDescription(), rangerServiceDef.getDescription()); + Assert.assertEquals(dbRangerServiceDef.getGuid(), rangerServiceDef.getGuid()); + Assert.assertEquals(dbRangerServiceDef.getImplClass(), rangerServiceDef.getImplClass()); + Assert.assertEquals(dbRangerServiceDef.getLabel(), rangerServiceDef.getLabel()); + Assert.assertEquals(dbRangerServiceDef.getName(), rangerServiceDef.getName()); + Assert.assertEquals(dbRangerServiceDef.getRbKeyDescription(), rangerServiceDef.getRbKeyDescription()); + Assert.assertEquals(dbRangerServiceDef.getConfigs(), rangerServiceDef.getConfigs()); + Assert.assertEquals(dbRangerServiceDef.getVersion(), rangerServiceDef.getVersion()); + Assert.assertEquals(dbRangerServiceDef.getResources(), rangerServiceDef.getResources()); + Mockito.verify(serviceDefService).read(Id); + } + + @Test + public void test15getServiceDefByName() throws Exception { + String name = "fdfdfds"; + + XXServiceDefDao xServiceDefDao = Mockito.mock(XXServiceDefDao.class); + XXServiceDef xServiceDef = Mockito.mock(XXServiceDef.class); + + Mockito.when(daoManager.getXXServiceDef()).thenReturn(xServiceDefDao); + Mockito.when(xServiceDefDao.findByName(name)).thenReturn(xServiceDef); + + RangerServiceDef dbServiceDef = serviceDBStore.getServiceDefByName(name); + Assert.assertNull(dbServiceDef); + Mockito.verify(daoManager).getXXServiceDef(); + } + + @Test + public void test16getServiceDefByNameNotNull() throws Exception { + String name = "fdfdfds"; - private static final String CFG_SERVICE_ADMIN_USERS = "service.admin.users"; - private static final String CFG_SERVICE_ADMIN_GROUPS = "service.admin.groups"; + XXServiceDefDao xServiceDefDao = Mockito.mock(XXServiceDefDao.class); + XXServiceDef xServiceDef = Mockito.mock(XXServiceDef.class); - @InjectMocks - ServiceDBStore serviceDBStore = new ServiceDBStore(); + RangerServiceDef serviceDef = new RangerServiceDef(); + Mockito.when(daoManager.getXXServiceDef()).thenReturn(xServiceDefDao); + Mockito.when(xServiceDefDao.findByName(name)).thenReturn(xServiceDef); + Mockito.when(serviceDefService.getPopulatedViewObject(xServiceDef)).thenReturn(serviceDef); - @Mock - RangerDaoManager daoManager; + RangerServiceDef dbServiceDef = serviceDBStore.getServiceDefByName(name); + Assert.assertNotNull(dbServiceDef); + Mockito.verify(daoManager).getXXServiceDef(); + } - @Mock - RangerServiceService svcService; + @Test + public void test17getServiceDefs() throws Exception { + SearchFilter filter = new SearchFilter(); + filter.setParam(SearchFilter.POLICY_NAME, "policyName"); + filter.setParam(SearchFilter.SERVICE_NAME, "serviceName"); + List serviceDefsList = new ArrayList<>(); + RangerServiceDef serviceDef = rangerServiceDef(); + serviceDefsList.add(serviceDef); + RangerServiceDefList serviceDefList = new RangerServiceDefList(); + serviceDefList.setPageSize(0); + serviceDefList.setResultSize(1); + serviceDefList.setSortBy("asc"); + serviceDefList.setSortType("1"); + serviceDefList.setStartIndex(0); + serviceDefList.setTotalCount(10); + serviceDefList.setServiceDefs(serviceDefsList); + Mockito.when(serviceDefService.searchRangerServiceDefs(filter)).thenReturn(serviceDefList); + + List dbServiceDef = serviceDBStore.getServiceDefs(filter); + Assert.assertNotNull(dbServiceDef); + Assert.assertEquals(dbServiceDef, serviceDefsList); + Assert.assertEquals(dbServiceDef.get(0), serviceDefsList.get(0)); + Mockito.verify(serviceDefService).searchRangerServiceDefs(filter); + } - @Mock - RangerDataHistService dataHistService; + @Test + public void test18getPaginatedServiceDefs() throws Exception { + SearchFilter filter = new SearchFilter(); + filter.setParam(SearchFilter.POLICY_NAME, "policyName"); + filter.setParam(SearchFilter.SERVICE_NAME, "serviceName"); + + List serviceDefsList = new ArrayList<>(); + RangerServiceDef serviceDef = rangerServiceDef(); + serviceDefsList.add(serviceDef); + RangerServiceDefList serviceDefList = new RangerServiceDefList(); + serviceDefList.setPageSize(0); + serviceDefList.setResultSize(1); + serviceDefList.setSortBy("asc"); + serviceDefList.setSortType("1"); + serviceDefList.setStartIndex(0); + serviceDefList.setTotalCount(10); + serviceDefList.setServiceDefs(serviceDefsList); + Mockito.when(serviceDefService.searchRangerServiceDefs(filter)).thenReturn(serviceDefList); + + PList dbServiceDefList = serviceDBStore.getPaginatedServiceDefs(filter); + Assert.assertNotNull(dbServiceDefList); + Assert.assertEquals(dbServiceDefList.getList(), serviceDefList.getServiceDefs()); + Mockito.verify(serviceDefService).searchRangerServiceDefs(filter); + } - @Mock - RangerServiceDefService serviceDefService; + @Test + public void test19createService() throws Exception { + XXServiceDao xServiceDao = Mockito.mock(XXServiceDao.class); + XXServiceConfigMapDao xServiceConfigMapDao = Mockito + .mock(XXServiceConfigMapDao.class); + XXUserDao xUserDao = Mockito.mock(XXUserDao.class); + XXServiceConfigDefDao xServiceConfigDefDao = Mockito.mock(XXServiceConfigDefDao.class); + XXService xService = Mockito.mock(XXService.class); - @Mock - RangerPolicyService policyService; + RangerService rangerService = rangerService(); - @Mock - StringUtil stringUtil; + List svcConfDefList = new ArrayList<>(); + XXServiceConfigDef serviceConfigDefObj = new XXServiceConfigDef(); + serviceConfigDefObj.setId(Id); + serviceConfigDefObj.setType("1"); + svcConfDefList.add(serviceConfigDefObj); + Mockito.when(daoManager.getXXServiceConfigDef()).thenReturn(xServiceConfigDefDao); + Mockito.when(svcService.create(rangerService)).thenReturn(rangerService); - @Mock - XUserService xUserService; + Mockito.when(daoManager.getXXService()).thenReturn(xServiceDao); + Mockito.when(xServiceDao.getById(rangerService.getId())).thenReturn(xService); + Mockito.when(daoManager.getXXServiceConfigMap()).thenReturn(xServiceConfigMapDao); + Mockito.when(daoManager.getXXUser()).thenReturn(xUserDao); - @Mock - XUserMgr xUserMgr; + XXServiceConfigMap xConfMap = new XXServiceConfigMap(); - @Mock - RangerAuditFields rangerAuditFields; + Mockito.when(svcService.getPopulatedViewObject(xService)).thenReturn(rangerService); - @Mock - ContextUtil contextUtil; + Mockito.when(rangerAuditFields.populateAuditFields(Mockito.isA(XXServiceConfigMap.class), Mockito.isA(XXService.class))).thenReturn(xConfMap); - @Mock - RangerBizUtil bizUtil; + RangerServiceDef ran = new RangerServiceDef(); + ran.setName("Test"); - @Mock - RangerServiceWithAssignedIdService svcServiceWithAssignedId; + ServiceDBStore spy = Mockito.spy(serviceDBStore); - @Mock - RangerFactory factory; + Mockito.doNothing().when(spy).createDefaultPolicies(rangerService); - @Mock - ServicePredicateUtil predicateUtil; + spy.createService(rangerService); - @Mock - PolicyRefUpdater policyRefUpdater; + Mockito.verify(daoManager, Mockito.atLeast(1)).getXXService(); + Mockito.verify(daoManager).getXXServiceConfigMap(); + } - @Mock - XGroupService xGroupService; - - - @Mock - RESTErrorUtil restErrorUtil; - - @Mock - AssetMgr assetMgr; - - @Mock - RangerTransactionSynchronizationAdapter transactionSynchronizationAdapter; - - @Mock - JSONUtil jsonUtil; - - @Mock - GUIDUtil guidUtil; - - @Mock - TagDBStore tagStore; - - - @Rule - public ExpectedException thrown = ExpectedException.none(); - - private VXGroup vxGroup() { - VXGroup vXGroup = new VXGroup(); - vXGroup.setId(Id); - vXGroup.setDescription("group test working"); - vXGroup.setName(RangerConstants.GROUP_PUBLIC); - vXGroup.setIsVisible(1); - return vXGroup; - } - - public void setup() { - RangerSecurityContext context = new RangerSecurityContext(); - context.setUserSession(new UserSessionBase()); - RangerContextHolder.setSecurityContext(context); - UserSessionBase currentUserSession = ContextUtil - .getCurrentUserSession(); - currentUserSession.setUserAdmin(true); - } - - private XXAccessTypeDef rangerKmsAccessTypes(String accessTypeName, int itemId) { - XXAccessTypeDef accessTypeDefObj = new XXAccessTypeDef(); - accessTypeDefObj.setAddedByUserId(Id); - accessTypeDefObj.setCreateTime(new Date()); - accessTypeDefObj.setDefid(Long.valueOf(itemId)); - accessTypeDefObj.setId(Long.valueOf(itemId)); - accessTypeDefObj.setItemId(Long.valueOf(itemId)); - accessTypeDefObj.setLabel(accessTypeName); - accessTypeDefObj.setName(accessTypeName); - accessTypeDefObj.setOrder(null); - accessTypeDefObj.setRbkeylabel(null); - accessTypeDefObj.setUpdatedByUserId(Id); - accessTypeDefObj.setUpdateTime(new Date()); - return accessTypeDefObj; - } - - private RangerServiceDef rangerServiceDef() { - List configs = new ArrayList(); - RangerServiceConfigDef serviceConfigDefObj = new RangerServiceConfigDef(); - serviceConfigDefObj.setDefaultValue("xyz"); - serviceConfigDefObj.setDescription("ServiceDef"); - serviceConfigDefObj.setItemId(Id); - serviceConfigDefObj.setLabel("Username"); - serviceConfigDefObj.setMandatory(true); - serviceConfigDefObj.setName("username"); - serviceConfigDefObj.setRbKeyDescription(null); - serviceConfigDefObj.setRbKeyLabel(null); - serviceConfigDefObj.setRbKeyValidationMessage(null); - serviceConfigDefObj.setSubType(null); - configs.add(serviceConfigDefObj); - List resources = new ArrayList(); - List accessTypes = new ArrayList(); - List policyConditions = new ArrayList(); - List contextEnrichers = new ArrayList(); - List enums = new ArrayList(); - - RangerServiceDef rangerServiceDef = new RangerServiceDef(); - rangerServiceDef.setId(Id); - rangerServiceDef.setName("RangerServiceHdfs"); - rangerServiceDef.setImplClass("RangerServiceHdfs"); - rangerServiceDef.setLabel("HDFS Repository"); - rangerServiceDef.setDescription("HDFS Repository"); - rangerServiceDef.setRbKeyDescription(null); - rangerServiceDef.setUpdatedBy("Admin"); - rangerServiceDef.setUpdateTime(new Date()); - rangerServiceDef.setConfigs(configs); - rangerServiceDef.setResources(resources); - rangerServiceDef.setAccessTypes(accessTypes); - rangerServiceDef.setPolicyConditions(policyConditions); - rangerServiceDef.setContextEnrichers(contextEnrichers); - rangerServiceDef.setEnums(enums); - - return rangerServiceDef; - } - - private RangerService rangerService() { - Map configs = new HashMap(); - configs.put("username", "servicemgr"); - configs.put("password", "servicemgr"); - configs.put("namenode", "servicemgr"); - configs.put("hadoop.security.authorization", "No"); - configs.put("hadoop.security.authentication", "Simple"); - configs.put("hadoop.security.auth_to_local", ""); - configs.put("dfs.datanode.kerberos.principal", ""); - configs.put("dfs.namenode.kerberos.principal", ""); - configs.put("dfs.secondary.namenode.kerberos.principal", ""); - configs.put("hadoop.rpc.protection", "Privacy"); - configs.put("commonNameForCertificate", ""); - configs.put("service.admin.users", "testServiceAdminUser1,testServiceAdminUser2"); - configs.put("service.admin.groups", "testServiceAdminGroup1,testServiceAdminGroup2"); - - RangerService rangerService = new RangerService(); - rangerService.setId(Id); - rangerService.setConfigs(configs); - rangerService.setCreateTime(new Date()); - rangerService.setDescription("service policy"); - rangerService.setGuid("1427365526516_835_0"); - rangerService.setIsEnabled(true); - rangerService.setName("HDFS_1"); - rangerService.setPolicyUpdateTime(new Date()); - rangerService.setType("1"); - rangerService.setUpdatedBy("Admin"); - rangerService.setUpdateTime(new Date()); - - return rangerService; - } - - private RangerService rangerKMSService() { - Map configs = new HashMap(); - configs.put("username", "servicemgr"); - configs.put("password", "servicemgr"); - configs.put("provider", "kmsurl"); - - RangerService rangerService = new RangerService(); - rangerService.setId(Id); - rangerService.setConfigs(configs); - rangerService.setCreateTime(new Date()); - rangerService.setDescription("service kms policy"); - rangerService.setGuid("1427365526516_835_1"); - rangerService.setIsEnabled(true); - rangerService.setName("KMS_1"); - rangerService.setPolicyUpdateTime(new Date()); - rangerService.setType("7"); - rangerService.setUpdatedBy("Admin"); - rangerService.setUpdateTime(new Date()); - - return rangerService; - } - - private RangerPolicy rangerPolicy() { - List accesses = new ArrayList(); - List users = new ArrayList(); - List groups = new ArrayList(); - List policyLabels = new ArrayList(); - List conditions = new ArrayList(); - List policyItems = new ArrayList(); - RangerPolicyItem rangerPolicyItem = new RangerPolicyItem(); - rangerPolicyItem.setAccesses(accesses); - rangerPolicyItem.setConditions(conditions); - rangerPolicyItem.setGroups(groups); - rangerPolicyItem.setUsers(users); - rangerPolicyItem.setDelegateAdmin(false); - - policyItems.add(rangerPolicyItem); - - Map policyResource = new HashMap(); - RangerPolicyResource rangerPolicyResource = new RangerPolicyResource(); - rangerPolicyResource.setIsExcludes(true); - rangerPolicyResource.setIsRecursive(true); - rangerPolicyResource.setValue("1"); - rangerPolicyResource.setValues(users); - RangerPolicy policy = new RangerPolicy(); - policy.setId(Id); - policy.setCreateTime(new Date()); - policy.setDescription("policy"); - policy.setGuid("policyguid"); - policy.setIsEnabled(true); - policy.setName("HDFS_1-1-20150316062453"); - policy.setUpdatedBy("Admin"); - policy.setUpdateTime(new Date()); - policy.setService("HDFS_1-1-20150316062453"); - policy.setIsAuditEnabled(true); - policy.setPolicyItems(policyItems); - policy.setResources(policyResource); - policy.setPolicyLabels(policyLabels); - - return policy; - } - - private XXServiceDef serviceDef() { - XXServiceDef xServiceDef = new XXServiceDef(); - xServiceDef.setAddedByUserId(Id); - xServiceDef.setCreateTime(new Date()); - xServiceDef.setDescription("HDFS Repository"); - xServiceDef.setGuid("1427365526516_835_0"); - xServiceDef.setId(Id); - xServiceDef.setUpdateTime(new Date()); - xServiceDef.setUpdatedByUserId(Id); - xServiceDef.setImplclassname("RangerServiceHdfs"); - xServiceDef.setLabel("HDFS Repository"); - xServiceDef.setRbkeylabel(null); - xServiceDef.setRbkeydescription(null); - xServiceDef.setIsEnabled(true); - - return xServiceDef; - } - - private XXService xService() { - XXService xService = new XXService(); - xService.setAddedByUserId(Id); - xService.setCreateTime(new Date()); - xService.setDescription("Hdfs service"); - xService.setGuid("serviceguid"); - xService.setId(Id); - xService.setIsEnabled(true); - xService.setName("Hdfs"); - xService.setPolicyUpdateTime(new Date()); - xService.setPolicyVersion(1L); - xService.setType(1L); - xService.setUpdatedByUserId(Id); - xService.setUpdateTime(new Date()); - - return xService; - } - - @Test - public void test11createServiceDef() throws Exception { - - XXServiceDefDao xServiceDefDao = Mockito.mock(XXServiceDefDao.class); - XXResourceDefDao xResourceDefDao = Mockito.mock(XXResourceDefDao.class); - XXServiceConfigDefDao xServiceConfigDefDao = Mockito - .mock(XXServiceConfigDefDao.class); - XXAccessTypeDefDao xAccessTypeDefDao = Mockito - .mock(XXAccessTypeDefDao.class); - XXPolicyConditionDefDao xPolicyConditionDefDao = Mockito - .mock(XXPolicyConditionDefDao.class); - XXContextEnricherDefDao xContextEnricherDefDao = Mockito - .mock(XXContextEnricherDefDao.class); - XXEnumDefDao xEnumDefDao = Mockito.mock(XXEnumDefDao.class); - - XXServiceDef xServiceDef = Mockito.mock(XXServiceDef.class); - XXResourceDef xResourceDef = Mockito.mock(XXResourceDef.class); - XXAccessTypeDef xAccessTypeDef = Mockito.mock(XXAccessTypeDef.class); - List xAccessTypeDefs = new ArrayList(); - xAccessTypeDefs.add(xAccessTypeDef); - List xResourceDefs = new ArrayList(); - xResourceDefs.add(xResourceDef); - - RangerServiceDef serviceDef = new RangerServiceDef(); - Mockito.when(serviceDefService.create(serviceDef)).thenReturn( - serviceDef); - - Mockito.when(daoManager.getXXServiceDef()).thenReturn(xServiceDefDao); - Mockito.when(daoManager.getXXServiceDef()).thenReturn(xServiceDefDao); - Mockito.when(xServiceDefDao.getById(null)).thenReturn(xServiceDef); - - Mockito.when(daoManager.getXXServiceConfigDef()).thenReturn( - xServiceConfigDefDao); - - Mockito.when(daoManager.getXXResourceDef()).thenReturn(xResourceDefDao); - Mockito.when(xResourceDefDao.findByServiceDefId(xServiceDef.getId())).thenReturn(xResourceDefs); - - Mockito.when(daoManager.getXXAccessTypeDef()).thenReturn( - xAccessTypeDefDao); - Mockito.when(xAccessTypeDefDao.findByServiceDefId(xServiceDef.getId())).thenReturn(xAccessTypeDefs); - - Mockito.when(daoManager.getXXPolicyConditionDef()).thenReturn( - xPolicyConditionDefDao); - Mockito.when(daoManager.getXXContextEnricherDef()).thenReturn( - xContextEnricherDefDao); - - Mockito.when(daoManager.getXXEnumDef()).thenReturn(xEnumDefDao); - - Mockito.when(serviceDefService.getPopulatedViewObject(xServiceDef)) - .thenReturn(serviceDef); - - RangerServiceDef dbServiceDef = serviceDBStore - .createServiceDef(serviceDef); - Assert.assertNotNull(dbServiceDef); - Assert.assertEquals(dbServiceDef, serviceDef); - Assert.assertEquals(dbServiceDef.getId(), serviceDef.getId()); - Assert.assertEquals(dbServiceDef.getCreatedBy(), - serviceDef.getCreatedBy()); - Assert.assertEquals(dbServiceDef.getDescription(), - serviceDef.getDescription()); - Assert.assertEquals(dbServiceDef.getGuid(), serviceDef.getGuid()); - Assert.assertEquals(dbServiceDef.getImplClass(), - serviceDef.getImplClass()); - Assert.assertEquals(dbServiceDef.getLabel(), serviceDef.getLabel()); - Assert.assertEquals(dbServiceDef.getName(), serviceDef.getName()); - Assert.assertEquals(dbServiceDef.getRbKeyDescription(), - serviceDef.getRbKeyDescription()); - Assert.assertEquals(dbServiceDef.getRbKeyLabel(), serviceDef.getLabel()); - Assert.assertEquals(dbServiceDef.getConfigs(), serviceDef.getConfigs()); - Assert.assertEquals(dbServiceDef.getVersion(), serviceDef.getVersion()); - Assert.assertEquals(dbServiceDef.getResources(), - serviceDef.getResources()); - Mockito.verify(serviceDefService).getPopulatedViewObject(xServiceDef); - Mockito.verify(serviceDefService).create(serviceDef); - Mockito.verify(daoManager).getXXServiceConfigDef(); - Mockito.verify(daoManager).getXXEnumDef(); - Mockito.verify(daoManager).getXXAccessTypeDef(); - } - - @Test - public void test12updateServiceDef() throws Exception { - setup(); - XXServiceDefDao xServiceDefDao = Mockito.mock(XXServiceDefDao.class); - XXServiceDef xServiceDef = Mockito.mock(XXServiceDef.class); - XXServiceConfigDefDao xServiceConfigDefDao = Mockito - .mock(XXServiceConfigDefDao.class); - XXResourceDefDao xResourceDefDao = Mockito.mock(XXResourceDefDao.class); - XXAccessTypeDefDao xAccessTypeDefDao = Mockito - .mock(XXAccessTypeDefDao.class); - XXPolicyConditionDefDao xPolicyConditionDefDao = Mockito - .mock(XXPolicyConditionDefDao.class); - XXContextEnricherDefDao xContextEnricherDefDao = Mockito - .mock(XXContextEnricherDefDao.class); - XXEnumDefDao xEnumDefDao = Mockito.mock(XXEnumDefDao.class); - XXDataMaskTypeDefDao xDataMaskDefDao = Mockito.mock(XXDataMaskTypeDefDao.class); - XXServiceDao xServiceDao = Mockito.mock(XXServiceDao.class); - - RangerServiceDef rangerServiceDef = rangerServiceDef(); - Long serviceDefId = rangerServiceDef.getId(); - - List svcConfDefList = new ArrayList(); - XXServiceConfigDef serviceConfigDefObj = new XXServiceConfigDef(); - serviceConfigDefObj.setId(Id); - serviceConfigDefObj.setType("1"); - svcConfDefList.add(serviceConfigDefObj); - - Mockito.when( - serviceDefService.populateRangerServiceConfigDefToXX( - Mockito.any(RangerServiceConfigDef.class), Mockito.any(XXServiceConfigDef.class), Mockito.any(XXServiceDef.class), - Mockito.eq(RangerServiceDefService.OPERATION_CREATE_CONTEXT))).thenReturn(serviceConfigDefObj); - Mockito.when(xServiceConfigDefDao.create(serviceConfigDefObj)) - .thenReturn(serviceConfigDefObj); - - List resDefList = new ArrayList(); - XXResourceDef resourceDef = new XXResourceDef(); - resourceDef.setAddedByUserId(Id); - resourceDef.setCreateTime(new Date()); - resourceDef.setDefid(Id); - resourceDef.setDescription("test"); - resourceDef.setId(Id); - resDefList.add(resourceDef); - - List accessTypeDefList = new ArrayList(); - XXAccessTypeDef accessTypeDefObj = new XXAccessTypeDef(); - accessTypeDefObj.setAddedByUserId(Id); - accessTypeDefObj.setCreateTime(new Date()); - accessTypeDefObj.setDefid(Id); - accessTypeDefObj.setId(Id); - accessTypeDefObj.setLabel("Read"); - accessTypeDefObj.setName("read"); - accessTypeDefObj.setOrder(null); - accessTypeDefObj.setRbkeylabel(null); - accessTypeDefObj.setUpdatedByUserId(Id); - accessTypeDefObj.setUpdateTime(new Date()); - accessTypeDefList.add(accessTypeDefObj); - - List policyConditionDefList = new ArrayList(); - XXPolicyConditionDef policyConditionDefObj = new XXPolicyConditionDef(); - policyConditionDefObj.setAddedByUserId(Id); - policyConditionDefObj.setCreateTime(new Date()); - policyConditionDefObj.setDefid(Id); - policyConditionDefObj.setDescription("policy"); - policyConditionDefObj.setId(Id); - policyConditionDefObj.setName("country"); - policyConditionDefObj.setOrder(0); - policyConditionDefObj.setUpdatedByUserId(Id); - policyConditionDefObj.setUpdateTime(new Date()); - policyConditionDefList.add(policyConditionDefObj); - - List contextEnricherDefList = new ArrayList(); - XXContextEnricherDef contextEnricherDefObj = new XXContextEnricherDef(); - contextEnricherDefObj.setAddedByUserId(Id); - contextEnricherDefObj.setCreateTime(new Date()); - contextEnricherDefObj.setDefid(Id); - contextEnricherDefObj.setId(Id); - contextEnricherDefObj.setName("country-provider"); - contextEnricherDefObj - .setEnricherOptions("contextName=COUNTRY;dataFile=/etc/ranger/data/userCountry.properties"); - contextEnricherDefObj.setEnricher("RangerCountryProvider"); - contextEnricherDefObj.setOrder(null); - contextEnricherDefObj.setUpdatedByUserId(Id); - contextEnricherDefObj.setUpdateTime(new Date()); - contextEnricherDefList.add(contextEnricherDefObj); - - List enumDefList = new ArrayList(); - XXEnumDef enumDefObj = new XXEnumDef(); - enumDefObj.setAddedByUserId(Id); - enumDefObj.setCreateTime(new Date()); - enumDefObj.setDefaultindex(0); - enumDefObj.setDefid(Id); - enumDefObj.setId(Id); - enumDefObj.setName("authnType"); - enumDefObj.setUpdatedByUserId(Id); - enumDefObj.setUpdateTime(new Date()); - enumDefList.add(enumDefObj); - - Mockito.when(daoManager.getXXServiceDef()).thenReturn(xServiceDefDao); - Mockito.when(xServiceDefDao.getById(serviceDefId)).thenReturn( - xServiceDef); - - Mockito.when(daoManager.getXXServiceConfigDef()).thenReturn( - xServiceConfigDefDao); - - Mockito.when(daoManager.getXXResourceDef()).thenReturn(xResourceDefDao); - - Mockito.when(daoManager.getXXAccessTypeDef()).thenReturn( - xAccessTypeDefDao); - - Mockito.when(daoManager.getXXPolicyConditionDef()).thenReturn( - xPolicyConditionDefDao); - - Mockito.when(daoManager.getXXContextEnricherDef()).thenReturn( - xContextEnricherDefDao); - - Mockito.when(daoManager.getXXEnumDef()).thenReturn(xEnumDefDao); - - Mockito.when(daoManager.getXXDataMaskTypeDef()).thenReturn(xDataMaskDefDao); - - Mockito.when(daoManager.getXXService()).thenReturn(xServiceDao); - Mockito.when(xServiceDao.findByServiceDefId(serviceDefId)).thenReturn(null); - - Mockito.when(serviceDefService.read(Id)).thenReturn(rangerServiceDef); - RangerServiceDef dbServiceDef = serviceDBStore - .updateServiceDef(rangerServiceDef); - Assert.assertNotNull(dbServiceDef); - Assert.assertEquals(dbServiceDef, rangerServiceDef); - Assert.assertEquals(dbServiceDef.getId(), rangerServiceDef.getId()); - Assert.assertEquals(dbServiceDef.getCreatedBy(), - rangerServiceDef.getCreatedBy()); - Assert.assertEquals(dbServiceDef.getDescription(), - rangerServiceDef.getDescription()); - Assert.assertEquals(dbServiceDef.getGuid(), rangerServiceDef.getGuid()); - Assert.assertEquals(dbServiceDef.getImplClass(), - rangerServiceDef.getImplClass()); - Assert.assertEquals(dbServiceDef.getLabel(), - rangerServiceDef.getLabel()); - Assert.assertEquals(dbServiceDef.getName(), rangerServiceDef.getName()); - Assert.assertEquals(dbServiceDef.getRbKeyDescription(), - rangerServiceDef.getRbKeyDescription()); - Assert.assertEquals(dbServiceDef.getConfigs(), - rangerServiceDef.getConfigs()); - Assert.assertEquals(dbServiceDef.getVersion(), - rangerServiceDef.getVersion()); - Assert.assertEquals(dbServiceDef.getResources(), - rangerServiceDef.getResources()); - - } - - @Test - public void test13deleteServiceDef() throws Exception { - setup(); - XXServiceDao xServiceDao = Mockito.mock(XXServiceDao.class); - XXDataMaskTypeDefDao xDataMaskDefDao = Mockito.mock(XXDataMaskTypeDefDao.class); - XXAccessTypeDefDao xAccessTypeDefDao = Mockito - .mock(XXAccessTypeDefDao.class); - XXAccessTypeDefGrantsDao xAccessTypeDefGrantsDao = Mockito - .mock(XXAccessTypeDefGrantsDao.class); - XXPolicyRefAccessTypeDao xPolicyRefAccessTypeDao = Mockito - .mock(XXPolicyRefAccessTypeDao.class); - XXPolicyRefConditionDao xPolicyRefConditionDao = Mockito - .mock(XXPolicyRefConditionDao.class); - XXPolicyRefResourceDao xPolicyRefResourceDao = Mockito - .mock(XXPolicyRefResourceDao.class); - XXContextEnricherDefDao xContextEnricherDefDao = Mockito - .mock(XXContextEnricherDefDao.class); - XXEnumDefDao xEnumDefDao = Mockito.mock(XXEnumDefDao.class); - XXEnumElementDefDao xEnumElementDefDao = Mockito - .mock(XXEnumElementDefDao.class); - XXPolicyConditionDefDao xPolicyConditionDefDao = Mockito - .mock(XXPolicyConditionDefDao.class); - XXResourceDefDao xResourceDefDao = Mockito.mock(XXResourceDefDao.class); - XXServiceConfigDefDao xServiceConfigDefDao = Mockito - .mock(XXServiceConfigDefDao.class); - - RangerServiceDef rangerServiceDef = rangerServiceDef(); - RangerService rangerService = rangerService(); - String name = "fdfdfds"; - Long serviceDefId = rangerServiceDef.getId(); - - List xServiceList = new ArrayList(); - XXService xService = new XXService(); - xService.setAddedByUserId(Id); - xService.setCreateTime(new Date()); - xService.setDescription("Hdfs service"); - xService.setGuid("serviceguid"); - xService.setId(Id); - xService.setIsEnabled(true); - xService.setName("Hdfs"); - xService.setPolicyUpdateTime(new Date()); - xService.setPolicyVersion(1L); - xService.setType(1L); - xService.setUpdatedByUserId(Id); - xService.setUpdateTime(new Date()); - xServiceList.add(xService); - - List accessTypeDefList = new ArrayList(); - XXAccessTypeDef accessTypeDefObj = new XXAccessTypeDef(); - accessTypeDefObj.setAddedByUserId(Id); - accessTypeDefObj.setCreateTime(new Date()); - accessTypeDefObj.setDefid(Id); - accessTypeDefObj.setId(Id); - accessTypeDefObj.setLabel("Read"); - accessTypeDefObj.setName("read"); - accessTypeDefObj.setOrder(null); - accessTypeDefObj.setRbkeylabel(null); - accessTypeDefObj.setUpdatedByUserId(Id); - accessTypeDefObj.setUpdateTime(new Date()); - accessTypeDefList.add(accessTypeDefObj); - - List accessTypeDefGrantslist = new ArrayList(); - XXAccessTypeDefGrants accessTypeDefGrantsObj = new XXAccessTypeDefGrants(); - accessTypeDefGrantsObj.setAddedByUserId(Id); - accessTypeDefGrantsObj.setAtdId(Id); - accessTypeDefGrantsObj.setCreateTime(new Date()); - accessTypeDefGrantsObj.setId(Id); - accessTypeDefGrantsObj.setUpdatedByUserId(Id); - accessTypeDefGrantsObj.setUpdateTime(new Date()); - accessTypeDefGrantsObj.setImpliedGrant("read"); - accessTypeDefGrantslist.add(accessTypeDefGrantsObj); - - List policyItemAccessList = new ArrayList(); - XXPolicyItemAccess policyItemAccess = new XXPolicyItemAccess(); - policyItemAccess.setAddedByUserId(Id); - policyItemAccess.setCreateTime(new Date()); - policyItemAccess.setPolicyitemid(Id); - policyItemAccess.setId(Id); - policyItemAccess.setOrder(1); - policyItemAccess.setUpdatedByUserId(Id); - policyItemAccess.setUpdateTime(new Date()); - policyItemAccessList.add(policyItemAccess); - - List contextEnricherDefList = new ArrayList(); - XXContextEnricherDef contextEnricherDefObj = new XXContextEnricherDef(); - contextEnricherDefObj.setAddedByUserId(Id); - contextEnricherDefObj.setCreateTime(new Date()); - contextEnricherDefObj.setDefid(Id); - contextEnricherDefObj.setId(Id); - contextEnricherDefObj.setName("country-provider"); - contextEnricherDefObj - .setEnricherOptions("contextName=COUNTRY;dataFile=/etc/ranger/data/userCountry.properties"); - contextEnricherDefObj.setEnricher("RangerCountryProvider"); - contextEnricherDefObj.setOrder(null); - contextEnricherDefObj.setUpdatedByUserId(Id); - contextEnricherDefObj.setUpdateTime(new Date()); - contextEnricherDefList.add(contextEnricherDefObj); - - List enumDefList = new ArrayList(); - XXEnumDef enumDefObj = new XXEnumDef(); - enumDefObj.setAddedByUserId(Id); - enumDefObj.setCreateTime(new Date()); - enumDefObj.setDefaultindex(0); - enumDefObj.setDefid(Id); - enumDefObj.setId(Id); - enumDefObj.setName("authnType"); - enumDefObj.setUpdatedByUserId(Id); - enumDefObj.setUpdateTime(new Date()); - enumDefList.add(enumDefObj); - - List xElementsList = new ArrayList(); - XXEnumElementDef enumElementDefObj = new XXEnumElementDef(); - enumElementDefObj.setAddedByUserId(Id); - enumElementDefObj.setCreateTime(new Date()); - enumElementDefObj.setEnumdefid(Id); - enumElementDefObj.setId(Id); - enumElementDefObj.setLabel("Authentication"); - enumElementDefObj.setName("authentication"); - enumElementDefObj.setUpdateTime(new Date()); - enumElementDefObj.setUpdatedByUserId(Id); - enumElementDefObj.setRbkeylabel(null); - enumElementDefObj.setOrder(0); - xElementsList.add(enumElementDefObj); - - List xConditionDefList = new ArrayList(); - XXPolicyConditionDef policyConditionDefObj = new XXPolicyConditionDef(); - policyConditionDefObj.setAddedByUserId(Id); - policyConditionDefObj.setCreateTime(new Date()); - policyConditionDefObj.setDefid(Id); - policyConditionDefObj.setDescription("policy conditio"); - policyConditionDefObj.setId(Id); - policyConditionDefObj.setName(name); - policyConditionDefObj.setOrder(1); - policyConditionDefObj.setLabel("label"); - xConditionDefList.add(policyConditionDefObj); - - List policyItemConditionList = new ArrayList(); - XXPolicyItemCondition policyItemCondition = new XXPolicyItemCondition(); - policyItemCondition.setAddedByUserId(Id); - policyItemCondition.setCreateTime(new Date()); - policyItemCondition.setType(1L); - policyItemCondition.setId(Id); - policyItemCondition.setOrder(1); - policyItemCondition.setPolicyItemId(Id); - policyItemCondition.setUpdatedByUserId(Id); - policyItemCondition.setUpdateTime(new Date()); - policyItemConditionList.add(policyItemCondition); - - List resDefList = new ArrayList(); - XXResourceDef resourceDef = new XXResourceDef(); - resourceDef.setAddedByUserId(Id); - resourceDef.setCreateTime(new Date()); - resourceDef.setDefid(Id); - resourceDef.setDescription("test"); - resourceDef.setId(Id); - resDefList.add(resourceDef); - - List policyResourceList = new ArrayList(); - XXPolicyResource policyResource = new XXPolicyResource(); - policyResource.setId(Id); - policyResource.setCreateTime(new Date()); - policyResource.setAddedByUserId(Id); - policyResource.setIsExcludes(false); - policyResource.setIsRecursive(false); - policyResource.setPolicyId(Id); - policyResource.setResDefId(Id); - policyResource.setUpdatedByUserId(Id); - policyResource.setUpdateTime(new Date()); - policyResourceList.add(policyResource); - - List policyResourceMapList = new ArrayList(); - XXPolicyResourceMap policyResourceMap = new XXPolicyResourceMap(); - policyResourceMap.setAddedByUserId(Id); - policyResourceMap.setCreateTime(new Date()); - policyResourceMap.setId(Id); - policyResourceMap.setOrder(1); - policyResourceMap.setResourceId(Id); - policyResourceMap.setUpdatedByUserId(Id); - policyResourceMap.setUpdateTime(new Date()); - policyResourceMap.setValue("1L"); - policyResourceMapList.add(policyResourceMap); - - List serviceConfigDefList = new ArrayList(); - XXServiceConfigDef serviceConfigDefObj = new XXServiceConfigDef(); - serviceConfigDefObj.setAddedByUserId(Id); - serviceConfigDefObj.setCreateTime(new Date()); - serviceConfigDefObj.setDefaultvalue("simple"); - serviceConfigDefObj.setDescription("service config"); - serviceConfigDefObj.setId(Id); - serviceConfigDefObj.setIsMandatory(true); - serviceConfigDefObj.setName(name); - serviceConfigDefObj.setLabel("username"); - serviceConfigDefObj.setRbkeydescription(null); - serviceConfigDefObj.setRbkeylabel(null); - serviceConfigDefObj.setRbKeyValidationMessage(null); - serviceConfigDefObj.setType("password"); - serviceConfigDefList.add(serviceConfigDefObj); - - List policiesList = new ArrayList(); - XXPolicy policy = new XXPolicy(); - policy.setAddedByUserId(Id); - policy.setCreateTime(new Date()); - policy.setDescription("polcy test"); - policy.setGuid(""); - policy.setId(rangerService.getId()); - policy.setIsAuditEnabled(true); - policy.setName("HDFS_1-1-20150316062453"); - policy.setService(rangerService.getId()); - policiesList.add(policy); - - List policyItemList = new ArrayList(); - XXPolicyItem policyItem = new XXPolicyItem(); - policyItem.setAddedByUserId(Id); - policyItem.setCreateTime(new Date()); - policyItem.setDelegateAdmin(false); - policyItem.setId(Id); - policyItem.setOrder(1); - policyItem.setPolicyId(Id); - policyItem.setUpdatedByUserId(Id); - policyItem.setUpdateTime(new Date()); - policyItemList.add(policyItem); - - XXServiceConfigMap xConfMap = new XXServiceConfigMap(); - xConfMap.setAddedByUserId(null); - xConfMap.setConfigkey(name); - xConfMap.setConfigvalue(name); - xConfMap.setCreateTime(new Date()); - xConfMap.setServiceId(Id); - - List policyItemGroupPermlist = new ArrayList(); - XXPolicyItemGroupPerm policyItemGroupPermObj = new XXPolicyItemGroupPerm(); - policyItemGroupPermObj.setAddedByUserId(Id); - policyItemGroupPermObj.setCreateTime(new Date()); - policyItemGroupPermObj.setGroupId(Id); - policyItemGroupPermObj.setId(Id); - policyItemGroupPermObj.setOrder(1); - policyItemGroupPermObj.setPolicyItemId(Id); - policyItemGroupPermObj.setUpdatedByUserId(Id); - policyItemGroupPermObj.setUpdateTime(new Date()); - policyItemGroupPermlist.add(policyItemGroupPermObj); - - List policyItemUserPermList = new ArrayList(); - XXPolicyItemUserPerm policyItemUserPermObj = new XXPolicyItemUserPerm(); - policyItemUserPermObj.setAddedByUserId(Id); - policyItemUserPermObj.setCreateTime(new Date()); - policyItemUserPermObj.setId(Id); - policyItemUserPermObj.setOrder(1); - policyItemUserPermObj.setPolicyItemId(Id); - policyItemUserPermObj.setUpdatedByUserId(serviceDefId); - policyItemUserPermObj.setUpdateTime(new Date()); - policyItemUserPermObj.setUserId(Id); - policyItemUserPermList.add(policyItemUserPermObj); - - List policyRefAccessTypeList = new ArrayList(); - XXPolicyRefAccessType policyRefAccessType = new XXPolicyRefAccessType(); - policyRefAccessType.setId(Id); - policyRefAccessType.setAccessTypeName("myAccessType"); - policyRefAccessType.setPolicyId(Id); - policyRefAccessType.setCreateTime(new Date()); - policyRefAccessType.setUpdateTime(new Date()); - policyRefAccessType.setAddedByUserId(Id); - policyRefAccessType.setUpdatedByUserId(Id); - policyRefAccessTypeList.add(policyRefAccessType); - - List policyRefConditionsList = new ArrayList(); - XXPolicyRefCondition policyRefCondition = new XXPolicyRefCondition(); - policyRefCondition.setId(Id); - policyRefCondition.setAddedByUserId(Id); - policyRefCondition.setConditionDefId(Id); - policyRefCondition.setConditionName("myConditionName"); - policyRefCondition.setPolicyId(Id); - policyRefCondition.setUpdatedByUserId(Id); - policyRefCondition.setCreateTime(new Date()); - policyRefCondition.setUpdateTime(new Date()); - policyRefConditionsList.add(policyRefCondition); - - List policyRefResourcesList = new ArrayList(); - XXPolicyRefResource policyRefResource = new XXPolicyRefResource(); - policyRefResource.setAddedByUserId(Id); - policyRefResource.setCreateTime(new Date()); - policyRefResource.setId(Id); - policyRefResource.setPolicyId(Id); - policyRefResource.setResourceDefId(Id); - policyRefResource.setUpdateTime(new Date()); - policyRefResource.setResourceName("myresourceName"); - policyRefResourcesList.add(policyRefResource); - - XXUser xUser = new XXUser(); - xUser.setAddedByUserId(Id); - xUser.setCreateTime(new Date()); - xUser.setCredStoreId(Id); - xUser.setDescription("user test"); - xUser.setId(Id); - xUser.setIsVisible(null); - xUser.setName(name); - xUser.setStatus(0); - xUser.setUpdatedByUserId(Id); - xUser.setUpdateTime(new Date()); - - Mockito.when(daoManager.getXXPolicyRefAccessType()).thenReturn(xPolicyRefAccessTypeDao); - Mockito.when(xPolicyRefAccessTypeDao.findByAccessTypeDefId(Id)).thenReturn(policyRefAccessTypeList); - Mockito.when(xPolicyRefAccessTypeDao.remove(policyRefAccessType)).thenReturn(true); - - Mockito.when(daoManager.getXXPolicyRefCondition()).thenReturn(xPolicyRefConditionDao); - Mockito.when(xPolicyRefConditionDao.findByConditionDefId(Id)).thenReturn(policyRefConditionsList); - Mockito.when(xPolicyRefConditionDao.remove(policyRefCondition)).thenReturn(true); - - Mockito.when(daoManager.getXXPolicyRefResource()).thenReturn(xPolicyRefResourceDao); - Mockito.when(xPolicyRefResourceDao.findByResourceDefID(Id)).thenReturn(policyRefResourcesList); - Mockito.when(xPolicyRefResourceDao.remove(policyRefResource)).thenReturn(true); - - Mockito.when(serviceDefService.read(Id)).thenReturn(rangerServiceDef); - Mockito.when(daoManager.getXXService()).thenReturn(xServiceDao); - Mockito.when(xServiceDao.findByServiceDefId(serviceDefId)).thenReturn(null); -// xServiceList); - - Mockito.when(daoManager.getXXAccessTypeDef()).thenReturn( - xAccessTypeDefDao); - Mockito.when(xAccessTypeDefDao.findByServiceDefId(serviceDefId)) - .thenReturn(accessTypeDefList); - - Mockito.when(daoManager.getXXAccessTypeDefGrants()).thenReturn( - xAccessTypeDefGrantsDao); - Mockito.when( - xAccessTypeDefGrantsDao.findByATDId(accessTypeDefObj.getId())) - .thenReturn(accessTypeDefGrantslist); - - Mockito.when(daoManager.getXXContextEnricherDef()).thenReturn( - xContextEnricherDefDao); - Mockito.when(xContextEnricherDefDao.findByServiceDefId(serviceDefId)) - .thenReturn(contextEnricherDefList); - - Mockito.when(daoManager.getXXEnumDef()).thenReturn(xEnumDefDao); - Mockito.when(xEnumDefDao.findByServiceDefId(serviceDefId)).thenReturn( - enumDefList); - - Mockito.when(daoManager.getXXEnumElementDef()).thenReturn( - xEnumElementDefDao); - Mockito.when(xEnumElementDefDao.findByEnumDefId(enumDefObj.getId())) - .thenReturn(xElementsList); - - Mockito.when(daoManager.getXXPolicyConditionDef()).thenReturn( - xPolicyConditionDefDao); - Mockito.when(xPolicyConditionDefDao.findByServiceDefId(serviceDefId)) - .thenReturn(xConditionDefList); - - Mockito.when(daoManager.getXXResourceDef()).thenReturn(xResourceDefDao); - Mockito.when(xResourceDefDao.findByServiceDefId(serviceDefId)) - .thenReturn(resDefList); - - Mockito.when(daoManager.getXXServiceConfigDef()).thenReturn( - xServiceConfigDefDao); - Mockito.when(xServiceConfigDefDao.findByServiceDefId(serviceDefId)) - .thenReturn(serviceConfigDefList); - - Mockito.when(daoManager.getXXService()).thenReturn(xServiceDao); - - svcServiceWithAssignedId.setPopulateExistingBaseFields(true); - - Mockito.when(daoManager.getXXService()).thenReturn(xServiceDao); - Mockito.when(xServiceDao.findByServiceDefId(serviceDefId)).thenReturn(null); - - Mockito.when(daoManager.getXXService()).thenReturn(xServiceDao); - - Mockito.when(daoManager.getXXDataMaskTypeDef()).thenReturn(xDataMaskDefDao); - Mockito.when(xDataMaskDefDao.findByServiceDefId(serviceDefId)).thenReturn(new ArrayList()); - - serviceDBStore.deleteServiceDef(Id, true); - Mockito.verify(daoManager).getXXContextEnricherDef(); - Mockito.verify(daoManager).getXXEnumDef(); - } - - @Test - public void test14getServiceDef() throws Exception { - RangerServiceDef rangerServiceDef = rangerServiceDef(); - Mockito.when(serviceDefService.read(Id)).thenReturn(rangerServiceDef); - RangerServiceDef dbRangerServiceDef = serviceDBStore.getServiceDef(Id); - Assert.assertNotNull(dbRangerServiceDef); - Assert.assertEquals(dbRangerServiceDef, rangerServiceDef); - Assert.assertEquals(dbRangerServiceDef.getId(), - rangerServiceDef.getId()); - Assert.assertEquals(dbRangerServiceDef.getCreatedBy(), - rangerServiceDef.getCreatedBy()); - Assert.assertEquals(dbRangerServiceDef.getDescription(), - rangerServiceDef.getDescription()); - Assert.assertEquals(dbRangerServiceDef.getGuid(), - rangerServiceDef.getGuid()); - Assert.assertEquals(dbRangerServiceDef.getImplClass(), - rangerServiceDef.getImplClass()); - Assert.assertEquals(dbRangerServiceDef.getLabel(), - rangerServiceDef.getLabel()); - Assert.assertEquals(dbRangerServiceDef.getName(), - rangerServiceDef.getName()); - Assert.assertEquals(dbRangerServiceDef.getRbKeyDescription(), - rangerServiceDef.getRbKeyDescription()); - Assert.assertEquals(dbRangerServiceDef.getConfigs(), - rangerServiceDef.getConfigs()); - Assert.assertEquals(dbRangerServiceDef.getVersion(), - rangerServiceDef.getVersion()); - Assert.assertEquals(dbRangerServiceDef.getResources(), - rangerServiceDef.getResources()); - Mockito.verify(serviceDefService).read(Id); - } - - @Test - public void test15getServiceDefByName() throws Exception { - String name = "fdfdfds"; - - XXServiceDefDao xServiceDefDao = Mockito.mock(XXServiceDefDao.class); - XXServiceDef xServiceDef = Mockito.mock(XXServiceDef.class); - - Mockito.when(daoManager.getXXServiceDef()).thenReturn(xServiceDefDao); - Mockito.when(xServiceDefDao.findByName(name)).thenReturn(xServiceDef); - - RangerServiceDef dbServiceDef = serviceDBStore - .getServiceDefByName(name); - Assert.assertNull(dbServiceDef); - Mockito.verify(daoManager).getXXServiceDef(); - } - - @Test - public void test16getServiceDefByNameNotNull() throws Exception { - String name = "fdfdfds"; - - XXServiceDefDao xServiceDefDao = Mockito.mock(XXServiceDefDao.class); - XXServiceDef xServiceDef = Mockito.mock(XXServiceDef.class); - - RangerServiceDef serviceDef = new RangerServiceDef(); - Mockito.when(daoManager.getXXServiceDef()).thenReturn(xServiceDefDao); - Mockito.when(xServiceDefDao.findByName(name)).thenReturn(xServiceDef); - Mockito.when(serviceDefService.getPopulatedViewObject(xServiceDef)) - .thenReturn(serviceDef); - - RangerServiceDef dbServiceDef = serviceDBStore - .getServiceDefByName(name); - Assert.assertNotNull(dbServiceDef); - Mockito.verify(daoManager).getXXServiceDef(); - } - - @Test - public void test17getServiceDefs() throws Exception { - SearchFilter filter = new SearchFilter(); - filter.setParam(SearchFilter.POLICY_NAME, "policyName"); - filter.setParam(SearchFilter.SERVICE_NAME, "serviceName"); - List serviceDefsList = new ArrayList(); - RangerServiceDef serviceDef = rangerServiceDef(); - serviceDefsList.add(serviceDef); - RangerServiceDefList serviceDefList = new RangerServiceDefList(); - serviceDefList.setPageSize(0); - serviceDefList.setResultSize(1); - serviceDefList.setSortBy("asc"); - serviceDefList.setSortType("1"); - serviceDefList.setStartIndex(0); - serviceDefList.setTotalCount(10); - serviceDefList.setServiceDefs(serviceDefsList); - Mockito.when(serviceDefService.searchRangerServiceDefs(filter)) - .thenReturn(serviceDefList); - - List dbServiceDef = serviceDBStore - .getServiceDefs(filter); - Assert.assertNotNull(dbServiceDef); - Assert.assertEquals(dbServiceDef, serviceDefsList); - Assert.assertEquals(dbServiceDef.get(0), serviceDefsList.get(0)); - Mockito.verify(serviceDefService).searchRangerServiceDefs(filter); - } - - @Test - public void test18getPaginatedServiceDefs() throws Exception { - SearchFilter filter = new SearchFilter(); - filter.setParam(SearchFilter.POLICY_NAME, "policyName"); - filter.setParam(SearchFilter.SERVICE_NAME, "serviceName"); - - List serviceDefsList = new ArrayList(); - RangerServiceDef serviceDef = rangerServiceDef(); - serviceDefsList.add(serviceDef); - RangerServiceDefList serviceDefList = new RangerServiceDefList(); - serviceDefList.setPageSize(0); - serviceDefList.setResultSize(1); - serviceDefList.setSortBy("asc"); - serviceDefList.setSortType("1"); - serviceDefList.setStartIndex(0); - serviceDefList.setTotalCount(10); - serviceDefList.setServiceDefs(serviceDefsList); - Mockito.when(serviceDefService.searchRangerServiceDefs(filter)) - .thenReturn(serviceDefList); - - PList dbServiceDefList = serviceDBStore - .getPaginatedServiceDefs(filter); - Assert.assertNotNull(dbServiceDefList); - Assert.assertEquals(dbServiceDefList.getList(), - serviceDefList.getServiceDefs()); - Mockito.verify(serviceDefService).searchRangerServiceDefs(filter); - } - - @Test - public void test19createService() throws Exception { - XXServiceDao xServiceDao = Mockito.mock(XXServiceDao.class); - XXServiceConfigMapDao xServiceConfigMapDao = Mockito - .mock(XXServiceConfigMapDao.class); - XXUserDao xUserDao = Mockito.mock(XXUserDao.class); - XXServiceConfigDefDao xServiceConfigDefDao = Mockito - .mock(XXServiceConfigDefDao.class); - XXService xService = Mockito.mock(XXService.class); - - RangerService rangerService = rangerService(); - - List svcConfDefList = new ArrayList(); - XXServiceConfigDef serviceConfigDefObj = new XXServiceConfigDef(); - serviceConfigDefObj.setId(Id); - serviceConfigDefObj.setType("1"); - svcConfDefList.add(serviceConfigDefObj); - Mockito.when(daoManager.getXXServiceConfigDef()).thenReturn( - xServiceConfigDefDao); - - Mockito.when(svcService.create(rangerService)).thenReturn(rangerService); - - Mockito.when(daoManager.getXXService()).thenReturn(xServiceDao); - Mockito.when(xServiceDao.getById(rangerService.getId())).thenReturn( - xService); - Mockito.when(daoManager.getXXServiceConfigMap()).thenReturn( - xServiceConfigMapDao); - - Mockito.when(daoManager.getXXUser()).thenReturn(xUserDao); - - XXServiceConfigMap xConfMap = new XXServiceConfigMap(); - - Mockito.when(svcService.getPopulatedViewObject(xService)).thenReturn( - rangerService); - - Mockito.when( - rangerAuditFields.populateAuditFields( - Mockito.isA(XXServiceConfigMap.class), - Mockito.isA(XXService.class))).thenReturn(xConfMap); - - RangerServiceDef ran = new RangerServiceDef(); - ran.setName("Test"); - - ServiceDBStore spy = Mockito.spy(serviceDBStore); - - Mockito.doNothing().when(spy).createDefaultPolicies(rangerService); - - spy.createService(rangerService); - - Mockito.verify(daoManager, Mockito.atLeast(1)).getXXService(); - Mockito.verify(daoManager).getXXServiceConfigMap(); - } - - @Test - public void test20updateService() throws Exception { - XXServiceDao xServiceDao = Mockito.mock(XXServiceDao.class); - XXService xService = Mockito.mock(XXService.class); - XXServiceConfigMapDao xServiceConfigMapDao = Mockito - .mock(XXServiceConfigMapDao.class); - XXServiceConfigDefDao xServiceConfigDefDao = Mockito - .mock(XXServiceConfigDefDao.class); - XXUserDao xUserDao = Mockito.mock(XXUserDao.class); - - RangerService rangerService = rangerService(); - Map options = null; - String name = "fdfdfds"; - - Mockito.when(daoManager.getXXService()).thenReturn(xServiceDao); - Mockito.when(xServiceDao.getById(Id)).thenReturn(xService); - - Mockito.when(daoManager.getXXService()).thenReturn(xServiceDao); - - List xServiceConfigDefList = new ArrayList(); - XXServiceConfigDef serviceConfigDefObj = new XXServiceConfigDef(); - serviceConfigDefObj.setId(Id); - xServiceConfigDefList.add(serviceConfigDefObj); - Mockito.when(daoManager.getXXServiceConfigDef()).thenReturn( - xServiceConfigDefDao); - - Mockito.when(svcService.update(rangerService)) - .thenReturn(rangerService); - Mockito.when(daoManager.getXXService()).thenReturn(xServiceDao); - Mockito.when(xServiceDao.getById(Id)).thenReturn(xService); - - List xConfMapList = new ArrayList(); - XXServiceConfigMap xConfMap = new XXServiceConfigMap(); - xConfMap.setAddedByUserId(null); - xConfMap.setConfigkey(name); - xConfMap.setConfigvalue(name); - xConfMap.setCreateTime(new Date()); - xConfMap.setServiceId(null); - - xConfMap.setUpdatedByUserId(null); - xConfMap.setUpdateTime(new Date()); - xConfMapList.add(xConfMap); - - Mockito.when(daoManager.getXXServiceConfigMap()).thenReturn( - xServiceConfigMapDao); - Mockito.when(xServiceConfigMapDao.findByServiceId(Id)).thenReturn( - xConfMapList); - Mockito.when(daoManager.getXXServiceConfigMap()).thenReturn( - xServiceConfigMapDao); - Mockito.when(xServiceConfigMapDao.remove(xConfMap)).thenReturn(true); - - Mockito.when(daoManager.getXXServiceConfigMap()).thenReturn( - xServiceConfigMapDao); - Mockito.when(daoManager.getXXUser()).thenReturn(xUserDao); - - Mockito.when( - rangerAuditFields.populateAuditFields( - Mockito.isA(XXServiceConfigMap.class), - Mockito.isA(XXService.class))).thenReturn(xConfMap); - - Mockito.when(svcService.getPopulatedViewObject(xService)).thenReturn( - rangerService); - - RangerService dbRangerService = serviceDBStore - .updateService(rangerService, options); - Assert.assertNotNull(dbRangerService); - Assert.assertEquals(dbRangerService, rangerService); - Assert.assertEquals(dbRangerService.getId(), rangerService.getId()); - Assert.assertEquals(dbRangerService.getName(), rangerService.getName()); - Assert.assertEquals(dbRangerService.getCreatedBy(), - rangerService.getCreatedBy()); - Assert.assertEquals(dbRangerService.getDescription(), - rangerService.getDescription()); - Assert.assertEquals(dbRangerService.getType(), rangerService.getType()); - Assert.assertEquals(dbRangerService.getVersion(), - rangerService.getVersion()); - Mockito.verify(daoManager).getXXUser(); - } - - @Test - public void test21deleteService() throws Exception { - setup(); - XXPolicyDao xPolicyDao = Mockito.mock(XXPolicyDao.class); - XXServiceDao xServiceDao = Mockito.mock(XXServiceDao.class); - XXService xService = Mockito.mock(XXService.class); - XXServiceConfigMapDao xServiceConfigMapDao = Mockito - .mock(XXServiceConfigMapDao.class); - XXPolicyLabelMapDao xPolicyLabelMapDao = Mockito.mock(XXPolicyLabelMapDao.class); - XXSecurityZoneDao xSecurityZoneDao = Mockito.mock(XXSecurityZoneDao.class); - XXRMSServiceResourceDao xRMSServiceResourceDao = Mockito.mock(XXRMSServiceResourceDao.class); + @Test + public void test20updateService() throws Exception { + XXServiceDao xServiceDao = Mockito.mock(XXServiceDao.class); + XXService xService = Mockito.mock(XXService.class); + XXServiceConfigMapDao xServiceConfigMapDao = Mockito.mock(XXServiceConfigMapDao.class); + XXServiceConfigDefDao xServiceConfigDefDao = Mockito.mock(XXServiceConfigDefDao.class); + XXUserDao xUserDao = Mockito.mock(XXUserDao.class); + + RangerService rangerService = rangerService(); + Map options = null; + String name = "fdfdfds"; + + Mockito.when(daoManager.getXXService()).thenReturn(xServiceDao); + Mockito.when(xServiceDao.getById(Id)).thenReturn(xService); + + Mockito.when(daoManager.getXXService()).thenReturn(xServiceDao); + + List xServiceConfigDefList = new ArrayList<>(); + XXServiceConfigDef serviceConfigDefObj = new XXServiceConfigDef(); + serviceConfigDefObj.setId(Id); + xServiceConfigDefList.add(serviceConfigDefObj); + Mockito.when(daoManager.getXXServiceConfigDef()).thenReturn(xServiceConfigDefDao); + + Mockito.when(svcService.update(rangerService)).thenReturn(rangerService); + Mockito.when(daoManager.getXXService()).thenReturn(xServiceDao); + Mockito.when(xServiceDao.getById(Id)).thenReturn(xService); + + List xConfMapList = new ArrayList<>(); + XXServiceConfigMap xConfMap = new XXServiceConfigMap(); + xConfMap.setAddedByUserId(null); + xConfMap.setConfigkey(name); + xConfMap.setConfigvalue(name); + xConfMap.setCreateTime(new Date()); + xConfMap.setServiceId(null); + + xConfMap.setUpdatedByUserId(null); + xConfMap.setUpdateTime(new Date()); + xConfMapList.add(xConfMap); + + Mockito.when(daoManager.getXXServiceConfigMap()).thenReturn(xServiceConfigMapDao); + Mockito.when(xServiceConfigMapDao.findByServiceId(Id)).thenReturn(xConfMapList); + Mockito.when(daoManager.getXXServiceConfigMap()).thenReturn(xServiceConfigMapDao); + Mockito.when(xServiceConfigMapDao.remove(xConfMap)).thenReturn(true); + + Mockito.when(daoManager.getXXServiceConfigMap()).thenReturn(xServiceConfigMapDao); + Mockito.when(daoManager.getXXUser()).thenReturn(xUserDao); + + Mockito.when(rangerAuditFields.populateAuditFields(Mockito.isA(XXServiceConfigMap.class), Mockito.isA(XXService.class))).thenReturn(xConfMap); + + Mockito.when(svcService.getPopulatedViewObject(xService)).thenReturn(rangerService); + + RangerService dbRangerService = serviceDBStore.updateService(rangerService, options); + Assert.assertNotNull(dbRangerService); + Assert.assertEquals(dbRangerService, rangerService); + Assert.assertEquals(dbRangerService.getId(), rangerService.getId()); + Assert.assertEquals(dbRangerService.getName(), rangerService.getName()); + Assert.assertEquals(dbRangerService.getCreatedBy(), rangerService.getCreatedBy()); + Assert.assertEquals(dbRangerService.getDescription(), rangerService.getDescription()); + Assert.assertEquals(dbRangerService.getType(), rangerService.getType()); + Assert.assertEquals(dbRangerService.getVersion(), rangerService.getVersion()); + Mockito.verify(daoManager).getXXUser(); + } + + @Test + public void test21deleteService() throws Exception { + setup(); + XXPolicyDao xPolicyDao = Mockito.mock(XXPolicyDao.class); + XXServiceDao xServiceDao = Mockito.mock(XXServiceDao.class); + XXService xService = Mockito.mock(XXService.class); + XXServiceConfigMapDao xServiceConfigMapDao = Mockito.mock(XXServiceConfigMapDao.class); + XXPolicyLabelMapDao xPolicyLabelMapDao = Mockito.mock(XXPolicyLabelMapDao.class); + XXSecurityZoneDao xSecurityZoneDao = Mockito.mock(XXSecurityZoneDao.class); + XXRMSServiceResourceDao xRMSServiceResourceDao = Mockito.mock(XXRMSServiceResourceDao.class); RangerService rangerService = rangerService(); - RangerPolicy rangerPolicy = rangerPolicy(); - String name = "HDFS_1-1-20150316062453"; - - List policiesList = new ArrayList(); - XXPolicy policy = new XXPolicy(); - policy.setAddedByUserId(Id); - policy.setCreateTime(new Date()); - policy.setDescription("polcy test"); - policy.setGuid(""); - policy.setId(rangerService.getId()); - policy.setIsAuditEnabled(true); - policy.setName("HDFS_1-1-20150316062453"); - policy.setService(rangerService.getId()); - policiesList.add(policy); - - List policiesIds = new ArrayList(); - policiesIds.add(Id); - - List zonesNameList =new ArrayList(); - - List policyItemList = new ArrayList(); - XXPolicyItem policyItem = new XXPolicyItem(); - policyItem.setAddedByUserId(Id); - policyItem.setCreateTime(new Date()); - policyItem.setDelegateAdmin(false); - policyItem.setId(Id); - policyItem.setOrder(1); - policyItem.setPolicyId(Id); - policyItem.setUpdatedByUserId(Id); - policyItem.setUpdateTime(new Date()); - policyItemList.add(policyItem); - - List policyItemConditionList = new ArrayList(); - XXPolicyItemCondition policyItemCondition = new XXPolicyItemCondition(); - policyItemCondition.setAddedByUserId(Id); - policyItemCondition.setCreateTime(new Date()); - policyItemCondition.setType(1L); - policyItemCondition.setId(Id); - policyItemCondition.setOrder(1); - policyItemCondition.setPolicyItemId(Id); - policyItemCondition.setUpdatedByUserId(Id); - policyItemCondition.setUpdateTime(new Date()); - policyItemConditionList.add(policyItemCondition); - - List policyItemGroupPermList = new ArrayList(); - XXPolicyItemGroupPerm policyItemGroupPerm = new XXPolicyItemGroupPerm(); - policyItemGroupPerm.setAddedByUserId(Id); - policyItemGroupPerm.setCreateTime(new Date()); - policyItemGroupPerm.setGroupId(Id); - - List xConfMapList = new ArrayList(); - XXServiceConfigMap xConfMap = new XXServiceConfigMap(); - xConfMap.setAddedByUserId(null); - xConfMap.setConfigkey(name); - xConfMap.setConfigvalue(name); - xConfMap.setCreateTime(new Date()); - xConfMap.setServiceId(null); - xConfMap.setId(Id); - xConfMap.setUpdatedByUserId(null); - xConfMap.setUpdateTime(new Date()); - xConfMapList.add(xConfMap); - policyItemGroupPerm.setId(Id); - policyItemGroupPerm.setOrder(1); - policyItemGroupPerm.setPolicyItemId(Id); - policyItemGroupPerm.setUpdatedByUserId(Id); - policyItemGroupPerm.setUpdateTime(new Date()); - policyItemGroupPermList.add(policyItemGroupPerm); - - List policyItemUserPermList = new ArrayList(); - XXPolicyItemUserPerm policyItemUserPerm = new XXPolicyItemUserPerm(); - policyItemUserPerm.setAddedByUserId(Id); - policyItemUserPerm.setCreateTime(new Date()); - policyItemUserPerm.setPolicyItemId(Id); - policyItemUserPerm.setId(Id); - policyItemUserPerm.setOrder(1); - policyItemUserPerm.setUpdatedByUserId(Id); - policyItemUserPerm.setUpdateTime(new Date()); - policyItemUserPermList.add(policyItemUserPerm); - - List policyItemAccessList = new ArrayList(); - XXPolicyItemAccess policyItemAccess = new XXPolicyItemAccess(); - policyItemAccess.setAddedByUserId(Id); - policyItemAccess.setCreateTime(new Date()); - policyItemAccess.setPolicyitemid(Id); - policyItemAccess.setId(Id); - policyItemAccess.setOrder(1); - policyItemAccess.setUpdatedByUserId(Id); - policyItemAccess.setUpdateTime(new Date()); - policyItemAccessList.add(policyItemAccess); - - List policyResourceList = new ArrayList(); - XXPolicyResource policyResource = new XXPolicyResource(); - policyResource.setId(Id); - policyResource.setCreateTime(new Date()); - policyResource.setAddedByUserId(Id); - policyResource.setIsExcludes(false); - policyResource.setIsRecursive(false); - policyResource.setPolicyId(Id); - policyResource.setResDefId(Id); - policyResource.setUpdatedByUserId(Id); - policyResource.setUpdateTime(new Date()); - policyResourceList.add(policyResource); - - List policyResourceMapList = new ArrayList(); - XXPolicyResourceMap policyResourceMap = new XXPolicyResourceMap(); - policyResourceMap.setAddedByUserId(Id); - policyResourceMap.setCreateTime(new Date()); - policyResourceMap.setId(Id); - policyResourceMap.setOrder(1); - policyResourceMap.setResourceId(Id); - policyResourceMap.setUpdatedByUserId(Id); - policyResourceMap.setUpdateTime(new Date()); - policyResourceMap.setValue("1L"); - policyResourceMapList.add(policyResourceMap); - - List xServiceConfigDefList = new ArrayList(); - XXServiceConfigDef serviceConfigDefObj = new XXServiceConfigDef(); - serviceConfigDefObj.setId(Id); - xServiceConfigDefList.add(serviceConfigDefObj); - - Mockito.when(daoManager.getXXSecurityZoneDao()).thenReturn(xSecurityZoneDao); - Mockito.when(xSecurityZoneDao.findZonesByServiceName(rangerService.getName())).thenReturn(zonesNameList); - - Mockito.when(daoManager.getXXPolicy()).thenReturn(xPolicyDao); - Mockito.when(xPolicyDao.findPolicyIdsByServiceId(rangerService.getId())) - .thenReturn(policiesIds); - Mockito.when(svcService.delete(rangerService)).thenReturn(true); - - Mockito.when(policyService.read(Id)).thenReturn(rangerPolicy); - Mockito.when(daoManager.getXXService()).thenReturn(xServiceDao); - Mockito.when(svcService.getPopulatedViewObject(xService)).thenReturn( - rangerService); - - Mockito.when(daoManager.getXXService()).thenReturn(xServiceDao); - Mockito.when(xServiceDao.getById(Id)).thenReturn(xService); - - Mockito.when(daoManager.getXXService()).thenReturn(xServiceDao); - Mockito.when(xServiceDao.getById(rangerService.getId())).thenReturn( - xService); - - Mockito.when(daoManager.getXXServiceConfigMap()).thenReturn( - xServiceConfigMapDao); - Mockito.when( - xServiceConfigMapDao.findByServiceId(rangerService.getId())) - .thenReturn(xConfMapList); - Mockito.when(daoManager.getXXPolicyLabelMap()).thenReturn(xPolicyLabelMapDao); - Mockito.when(xPolicyLabelMapDao.findByPolicyId(rangerPolicy.getId())).thenReturn(ListUtils.EMPTY_LIST); - - Mockito.when(daoManager.getXXRMSServiceResource()).thenReturn(xRMSServiceResourceDao); - - Mockito.when(!bizUtil.hasAccess(xService, null)).thenReturn(true); - Mockito.when(tagStore.resetTagCache(rangerService.getName())).thenReturn(true); - - serviceDBStore.deleteService(Id); - Mockito.verify(svcService).delete(rangerService); - Mockito.verify(tagStore).resetTagCache(rangerService.getName()); - } - - @Test - public void test22getService() throws Exception { - RangerService rangerService = rangerService(); - XXService xService = xService(); - XXServiceDao xServiceDao = Mockito.mock(XXServiceDao.class); - - Mockito.when(daoManager.getXXService()).thenReturn(xServiceDao); - Mockito.when(xServiceDao.getById(Id)).thenReturn(xService); - Mockito.when(!bizUtil.hasAccess(xService, null)).thenReturn(true); - - Mockito.when(svcService.getPopulatedViewObject(xService)).thenReturn( - rangerService); - RangerService dbRangerService = serviceDBStore.getService(Id); - Assert.assertNotNull(dbRangerService); - Assert.assertEquals(dbRangerService, rangerService); - Assert.assertEquals(dbRangerService.getCreatedBy(), - rangerService.getCreatedBy()); - Assert.assertEquals(dbRangerService.getDescription(), - rangerService.getDescription()); - Assert.assertEquals(dbRangerService.getGuid(), rangerService.getGuid()); - Assert.assertEquals(dbRangerService.getName(), rangerService.getName()); - Assert.assertEquals(dbRangerService.getType(), rangerService.getType()); - Assert.assertEquals(dbRangerService.getUpdatedBy(), - rangerService.getUpdatedBy()); - Assert.assertEquals(dbRangerService.getConfigs(), - rangerService.getConfigs()); - Assert.assertEquals(dbRangerService.getCreateTime(), - rangerService.getCreateTime()); - Assert.assertEquals(dbRangerService.getId(), rangerService.getId()); - Assert.assertEquals(dbRangerService.getPolicyVersion(), - rangerService.getPolicyVersion()); - Assert.assertEquals(dbRangerService.getVersion(), - rangerService.getVersion()); - Assert.assertEquals(dbRangerService.getPolicyUpdateTime(), - rangerService.getPolicyUpdateTime()); - Mockito.verify(daoManager).getXXService(); - Mockito.verify(bizUtil).hasAccess(xService, null); - Mockito.verify(svcService).getPopulatedViewObject(xService); - } - - @Test - public void test23getServiceByName() throws Exception { - - XXServiceDao xServiceDao = Mockito.mock(XXServiceDao.class); - RangerService rangerService = rangerService(); - XXService xService = xService(); - String name = rangerService.getName(); - - Mockito.when(daoManager.getXXService()).thenReturn(xServiceDao); - Mockito.when(xServiceDao.findByName(name)).thenReturn(xService); - Mockito.when(!bizUtil.hasAccess(xService, null)).thenReturn(true); - Mockito.when(svcService.getPopulatedViewObject(xService)).thenReturn( - rangerService); - - RangerService dbRangerService = serviceDBStore.getServiceByName(name); - Assert.assertNotNull(dbRangerService); - Assert.assertEquals(dbRangerService, rangerService); - Assert.assertEquals(dbRangerService.getName(), rangerService.getName()); - Mockito.verify(daoManager).getXXService(); - Mockito.verify(bizUtil).hasAccess(xService, null); - Mockito.verify(svcService).getPopulatedViewObject(xService); - } - - @Test - public void test24getServices() throws Exception { - SearchFilter filter = new SearchFilter(); - filter.setParam(SearchFilter.POLICY_NAME, "policyName"); - filter.setParam(SearchFilter.SERVICE_NAME, "serviceName"); - - List serviceList = new ArrayList(); - RangerService rangerService = rangerService(); - serviceList.add(rangerService); - - RangerServiceList serviceListObj = new RangerServiceList(); - serviceListObj.setPageSize(0); - serviceListObj.setResultSize(1); - serviceListObj.setSortBy("asc"); - serviceListObj.setSortType("1"); - serviceListObj.setStartIndex(0); - serviceListObj.setTotalCount(10); - serviceListObj.setServices(serviceList); - - Mockito.when(svcService.searchRangerServices(filter)).thenReturn( - serviceListObj); - List dbRangerService = serviceDBStore - .getServices(filter); - Assert.assertNotNull(dbRangerService); - Assert.assertEquals(dbRangerService, serviceList); - Mockito.verify(svcService).searchRangerServices(filter); - } - - @Test - public void test25getPaginatedServiceDefs() throws Exception { - SearchFilter filter = new SearchFilter(); - filter.setParam(SearchFilter.POLICY_NAME, "policyName"); - filter.setParam(SearchFilter.SERVICE_NAME, "serviceName"); - - List serviceList = new ArrayList(); - RangerService rangerService = rangerService(); - serviceList.add(rangerService); - - RangerServiceList serviceListObj = new RangerServiceList(); - serviceListObj.setPageSize(0); - serviceListObj.setResultSize(1); - serviceListObj.setSortBy("asc"); - serviceListObj.setSortType("1"); - serviceListObj.setStartIndex(0); - serviceListObj.setTotalCount(10); - serviceListObj.setServices(serviceList); - - Mockito.when(svcService.searchRangerServices(filter)).thenReturn( - serviceListObj); - - PList dbServiceList = serviceDBStore - .getPaginatedServices(filter); - Assert.assertNotNull(dbServiceList); - Assert.assertEquals(dbServiceList.getList(), - serviceListObj.getServices()); - - Mockito.verify(svcService).searchRangerServices(filter); - } - - @Test - public void test26createPolicy() throws Exception { - setup(); - XXServiceDefDao xServiceDefDao = Mockito.mock(XXServiceDefDao.class); - XXPolicy xPolicy = Mockito.mock(XXPolicy.class); - XXPolicyDao xPolicyDao = Mockito.mock(XXPolicyDao.class); - XXServiceDao xServiceDao = Mockito.mock(XXServiceDao.class); - XXService xService = Mockito.mock(XXService.class); - - XXServiceDef xServiceDef = serviceDef(); - Map configs = new HashMap(); - configs.put("username", "servicemgr"); - configs.put("password", "servicemgr"); - configs.put("namenode", "servicemgr"); - configs.put("hadoop.security.authorization", "No"); - configs.put("hadoop.security.authentication", "Simple"); - configs.put("hadoop.security.auth_to_local", ""); - configs.put("dfs.datanode.kerberos.principal", ""); - configs.put("dfs.namenode.kerberos.principal", ""); - configs.put("dfs.secondary.namenode.kerberos.principal", ""); - configs.put("hadoop.rpc.protection", "Privacy"); - configs.put("commonNameForCertificate", ""); - - RangerService rangerService = new RangerService(); - rangerService.setId(Id); - rangerService.setConfigs(configs); - rangerService.setCreateTime(new Date()); - rangerService.setDescription("service policy"); - rangerService.setGuid("1427365526516_835_0"); - rangerService.setIsEnabled(true); - rangerService.setName("HDFS_1"); - rangerService.setPolicyUpdateTime(new Date()); - rangerService.setType("1"); - rangerService.setUpdatedBy("Admin"); - - String policyName = "HDFS_1-1-20150316062345"; - String name = "HDFS_1-1-20150316062453"; - - List accessesList = new ArrayList(); - RangerPolicyItemAccess policyItemAccess = new RangerPolicyItemAccess(); - policyItemAccess.setIsAllowed(true); - policyItemAccess.setType("1"); - List usersList = new ArrayList(); - List groupsList = new ArrayList(); - List rolesList = new ArrayList(); - List policyLabels = new ArrayList(); - List conditionsList = new ArrayList(); - RangerPolicyItemCondition policyItemCondition = new RangerPolicyItemCondition(); - policyItemCondition.setType("1"); - policyItemCondition.setValues(usersList); - conditionsList.add(policyItemCondition); - - List policyItems = new ArrayList(); - RangerPolicyItem rangerPolicyItem = new RangerPolicyItem(); - rangerPolicyItem.setDelegateAdmin(false); - rangerPolicyItem.setAccesses(accessesList); - rangerPolicyItem.setConditions(conditionsList); - rangerPolicyItem.setGroups(groupsList); - rangerPolicyItem.setUsers(usersList); - policyItems.add(rangerPolicyItem); - - List policyItemsSet = new ArrayList(); - RangerPolicyItem paramPolicyItem = new RangerPolicyItem(accessesList, - usersList, groupsList, rolesList, conditionsList, false); - paramPolicyItem.setDelegateAdmin(false); - paramPolicyItem.setAccesses(accessesList); - paramPolicyItem.setConditions(conditionsList); - paramPolicyItem.setGroups(groupsList); - rangerPolicyItem.setUsers(usersList); - policyItemsSet.add(paramPolicyItem); - - XXPolicyItem xPolicyItem = new XXPolicyItem(); - xPolicyItem.setDelegateAdmin(false); - xPolicyItem.setAddedByUserId(null); - xPolicyItem.setCreateTime(new Date()); - xPolicyItem.setGUID(null); - xPolicyItem.setId(Id); - xPolicyItem.setOrder(null); - xPolicyItem.setPolicyId(Id); - xPolicyItem.setUpdatedByUserId(null); - xPolicyItem.setUpdateTime(new Date()); - - XXPolicy xxPolicy = new XXPolicy(); - xxPolicy.setId(Id); - xxPolicy.setName(name); - xxPolicy.setAddedByUserId(Id); - xxPolicy.setCreateTime(new Date()); - xxPolicy.setDescription("test"); - xxPolicy.setIsAuditEnabled(true); - xxPolicy.setIsEnabled(true); - xxPolicy.setService(1L); - xxPolicy.setUpdatedByUserId(Id); - xxPolicy.setUpdateTime(new Date()); - - List xServiceConfigDefList = new ArrayList(); - XXServiceConfigDef serviceConfigDefObj = new XXServiceConfigDef(); - serviceConfigDefObj.setId(Id); - xServiceConfigDefList.add(serviceConfigDefObj); - - List xConfMapList = new ArrayList(); - XXServiceConfigMap xConfMap = new XXServiceConfigMap(); - xConfMap.setAddedByUserId(null); - xConfMap.setConfigkey(name); - xConfMap.setConfigvalue(name); - xConfMap.setCreateTime(new Date()); - xConfMap.setServiceId(null); - xConfMap.setId(Id); - xConfMap.setUpdatedByUserId(null); - xConfMap.setUpdateTime(new Date()); - xConfMapList.add(xConfMap); - - List users = new ArrayList(); - - RangerPolicyResource rangerPolicyResource = new RangerPolicyResource(); - rangerPolicyResource.setIsExcludes(true); - rangerPolicyResource.setIsRecursive(true); - rangerPolicyResource.setValue("1"); - rangerPolicyResource.setValues(users); - - Map policyResource = new HashMap(); - policyResource.put(name, rangerPolicyResource); - policyResource.put(policyName, rangerPolicyResource); - RangerPolicy rangerPolicy = new RangerPolicy(); - rangerPolicy.setId(Id); - rangerPolicy.setCreateTime(new Date()); - rangerPolicy.setDescription("policy"); - rangerPolicy.setGuid("policyguid"); - rangerPolicy.setIsEnabled(true); - rangerPolicy.setName("HDFS_1-1-20150316062453"); - rangerPolicy.setUpdatedBy("Admin"); - rangerPolicy.setUpdateTime(new Date()); - rangerPolicy.setService("HDFS_1-1-20150316062453"); - rangerPolicy.setIsAuditEnabled(true); - rangerPolicy.setPolicyItems(policyItems); - rangerPolicy.setResources(policyResource); - rangerPolicy.setPolicyLabels(policyLabels); - - XXPolicyResource xPolicyResource = new XXPolicyResource(); - xPolicyResource.setAddedByUserId(Id); - xPolicyResource.setCreateTime(new Date()); - xPolicyResource.setId(Id); - xPolicyResource.setIsExcludes(true); - xPolicyResource.setIsRecursive(true); - xPolicyResource.setPolicyId(Id); - xPolicyResource.setResDefId(Id); - xPolicyResource.setUpdatedByUserId(Id); - xPolicyResource.setUpdateTime(new Date()); - - List policyConditionDefList = new ArrayList(); - XXPolicyConditionDef policyConditionDefObj = new XXPolicyConditionDef(); - policyConditionDefObj.setAddedByUserId(Id); - policyConditionDefObj.setCreateTime(new Date()); - policyConditionDefObj.setDefid(Id); - policyConditionDefObj.setDescription("policy"); - policyConditionDefObj.setId(Id); - policyConditionDefObj.setName("country"); - policyConditionDefObj.setOrder(0); - policyConditionDefObj.setUpdatedByUserId(Id); - policyConditionDefObj.setUpdateTime(new Date()); - policyConditionDefList.add(policyConditionDefObj); - - Mockito.when(daoManager.getXXService()).thenReturn(xServiceDao); - Mockito.when(xServiceDao.findByName(name)).thenReturn(xService); - - Mockito.when(svcService.getPopulatedViewObject(xService)).thenReturn( - rangerService); - - Mockito.when(daoManager.getXXServiceDef()).thenReturn(xServiceDefDao); - Mockito.when(xServiceDefDao.findByName(rangerService.getType())) - .thenReturn(xServiceDef); - - Mockito.when(daoManager.getXXPolicy()).thenReturn(xPolicyDao); - - Mockito.when(policyService.create(rangerPolicy, true)).thenReturn( - rangerPolicy); - - Mockito.when(daoManager.getXXPolicy()).thenReturn(xPolicyDao); - Mockito.when(xPolicyDao.getById(Id)).thenReturn(xPolicy); - Mockito.doNothing().when(policyRefUpdater).createNewPolMappingForRefTable(rangerPolicy, xPolicy, xServiceDef, false); - Mockito.when(policyService.getPopulatedViewObject(xPolicy)).thenReturn(rangerPolicy); - - Mockito.when(daoManager.getXXService()).thenReturn(xServiceDao); - Mockito.when(xServiceDao.getById(Id)).thenReturn(xService); - - Mockito.when(daoManager.getXXService()).thenReturn(xServiceDao); - Mockito.when(xServiceDao.getById(Id)).thenReturn(xService); - - RangerPolicyResourceSignature signature = Mockito - .mock(RangerPolicyResourceSignature.class); - Mockito.when(factory.createPolicyResourceSignature(rangerPolicy)) - .thenReturn(signature); - Mockito.when(!bizUtil.hasAccess(xService, null)).thenReturn(true); - - RangerPolicy dbRangerPolicy = serviceDBStore.createPolicy(rangerPolicy); - - Assert.assertNotNull(dbRangerPolicy); - Assert.assertEquals(Id, dbRangerPolicy.getId()); - } - - @Test - public void tess27getPolicy() throws Exception { - RangerPolicy rangerPolicy = rangerPolicy(); - Mockito.when(policyService.read(Id)).thenReturn(rangerPolicy); - RangerPolicy dbRangerPolicy = serviceDBStore.getPolicy(Id); - Assert.assertNotNull(dbRangerPolicy); - Assert.assertEquals(dbRangerPolicy, rangerPolicy); - Assert.assertEquals(dbRangerPolicy.getId(), rangerPolicy.getId()); - Assert.assertEquals(dbRangerPolicy.getName(), rangerPolicy.getName()); - Assert.assertEquals(dbRangerPolicy.getCreatedBy(), - rangerPolicy.getCreatedBy()); - Assert.assertEquals(dbRangerPolicy.getDescription(), - rangerPolicy.getDescription()); - Assert.assertEquals(dbRangerPolicy.getGuid(), rangerPolicy.getGuid()); - Assert.assertEquals(dbRangerPolicy.getService(), - rangerPolicy.getService()); - Assert.assertEquals(dbRangerPolicy.getUpdatedBy(), - rangerPolicy.getUpdatedBy()); - Assert.assertEquals(dbRangerPolicy.getCreateTime(), - rangerPolicy.getCreateTime()); - Assert.assertEquals(dbRangerPolicy.getIsAuditEnabled(), - rangerPolicy.getIsAuditEnabled()); - Assert.assertEquals(dbRangerPolicy.getIsEnabled(), - rangerPolicy.getIsEnabled()); - Assert.assertEquals(dbRangerPolicy.getPolicyItems(), - rangerPolicy.getPolicyItems()); - Assert.assertEquals(dbRangerPolicy.getVersion(), - rangerPolicy.getVersion()); - Mockito.verify(policyService).read(Id); - - } - - @Test - public void tess28updatePolicy() throws Exception { - setup(); - XXPolicyDao xPolicyDao = Mockito.mock(XXPolicyDao.class); - XXPolicy xPolicy = Mockito.mock(XXPolicy.class); - XXServiceDao xServiceDao = Mockito.mock(XXServiceDao.class); - XXService xService = Mockito.mock(XXService.class); - XXServiceDefDao xServiceDefDao = Mockito.mock(XXServiceDefDao.class); - XXServiceDef xServiceDef = Mockito.mock(XXServiceDef.class); - XXPolicyLabelMapDao xPolicyLabelMapDao = Mockito.mock(XXPolicyLabelMapDao.class); - - RangerService rangerService = rangerService(); - - RangerPolicy rangerPolicy = rangerPolicy(); - String name = "HDFS_1-1-20150316062453"; - - List policyResourceList = new ArrayList(); - XXPolicyResource policyResource = new XXPolicyResource(); - policyResource.setId(Id); - policyResource.setCreateTime(new Date()); - policyResource.setAddedByUserId(Id); - policyResource.setIsExcludes(false); - policyResource.setIsRecursive(false); - policyResource.setPolicyId(Id); - policyResource.setResDefId(Id); - policyResource.setUpdatedByUserId(Id); - policyResource.setUpdateTime(new Date()); - policyResourceList.add(policyResource); - - List policyResourceMapList = new ArrayList(); - XXPolicyResourceMap policyResourceMap = new XXPolicyResourceMap(); - policyResourceMap.setAddedByUserId(Id); - policyResourceMap.setCreateTime(new Date()); - policyResourceMap.setId(Id); - policyResourceMap.setOrder(1); - policyResourceMap.setResourceId(Id); - policyResourceMap.setUpdatedByUserId(Id); - policyResourceMap.setUpdateTime(new Date()); - policyResourceMap.setValue("1L"); - policyResourceMapList.add(policyResourceMap); - - List xServiceConfigDefList = new ArrayList(); - XXServiceConfigDef serviceConfigDefObj = new XXServiceConfigDef(); - serviceConfigDefObj.setId(Id); - xServiceConfigDefList.add(serviceConfigDefObj); - - List xConfMapList = new ArrayList(); - XXServiceConfigMap xConfMap = new XXServiceConfigMap(); - xConfMap.setAddedByUserId(null); - xConfMap.setConfigkey(name); - xConfMap.setConfigvalue(name); - xConfMap.setCreateTime(new Date()); - xConfMap.setServiceId(null); - xConfMap.setId(Id); - xConfMap.setUpdatedByUserId(null); - xConfMap.setUpdateTime(new Date()); - xConfMapList.add(xConfMap); - - Mockito.when(daoManager.getXXPolicy()).thenReturn(xPolicyDao); - Mockito.when(xPolicyDao.getById(Id)).thenReturn(xPolicy); - Mockito.when(policyService.getPopulatedViewObject(xPolicy)).thenReturn( - rangerPolicy); - - Mockito.when(daoManager.getXXService()).thenReturn(xServiceDao); - Mockito.when(xServiceDao.findByName(name)).thenReturn(xService); - Mockito.when(svcService.getPopulatedViewObject(xService)).thenReturn( - rangerService); - - Mockito.when(daoManager.getXXServiceDef()).thenReturn(xServiceDefDao); - Mockito.when(xServiceDefDao.findByName(rangerService.getType())) - .thenReturn(xServiceDef); - - Mockito.when(policyService.update(rangerPolicy)).thenReturn( - rangerPolicy); - Mockito.when(daoManager.getXXPolicy()).thenReturn(xPolicyDao); - Mockito.when(xPolicyDao.getById(rangerPolicy.getId())).thenReturn( - xPolicy); - - Mockito.when(daoManager.getXXService()).thenReturn(xServiceDao); - Mockito.when(xServiceDao.getById(rangerService.getId())).thenReturn( - xService); - - Mockito.when(daoManager.getXXService()).thenReturn(xServiceDao); - Mockito.when(xServiceDao.getById(rangerService.getId())).thenReturn( - xService); - Mockito.when(daoManager.getXXPolicyLabelMap()).thenReturn(xPolicyLabelMapDao); - Mockito.when(xPolicyLabelMapDao.findByPolicyId(rangerPolicy.getId())).thenReturn(ListUtils.EMPTY_LIST); - - - RangerPolicyResourceSignature signature = Mockito - .mock(RangerPolicyResourceSignature.class); - Mockito.when(factory.createPolicyResourceSignature(rangerPolicy)) - .thenReturn(signature); - Mockito.when(!bizUtil.hasAccess(xService, null)).thenReturn(true); - Mockito.when(policyRefUpdater.cleanupRefTables(rangerPolicy)).thenReturn(true); + RangerPolicy rangerPolicy = rangerPolicy(); + String name = "HDFS_1-1-20150316062453"; + + List policiesList = new ArrayList<>(); + XXPolicy policy = new XXPolicy(); + policy.setAddedByUserId(Id); + policy.setCreateTime(new Date()); + policy.setDescription("polcy test"); + policy.setGuid(""); + policy.setId(rangerService.getId()); + policy.setIsAuditEnabled(true); + policy.setName("HDFS_1-1-20150316062453"); + policy.setService(rangerService.getId()); + policiesList.add(policy); + + List policiesIds = new ArrayList<>(); + policiesIds.add(Id); + + List zonesNameList = new ArrayList<>(); + + List policyItemList = new ArrayList<>(); + XXPolicyItem policyItem = new XXPolicyItem(); + policyItem.setAddedByUserId(Id); + policyItem.setCreateTime(new Date()); + policyItem.setDelegateAdmin(false); + policyItem.setId(Id); + policyItem.setOrder(1); + policyItem.setPolicyId(Id); + policyItem.setUpdatedByUserId(Id); + policyItem.setUpdateTime(new Date()); + policyItemList.add(policyItem); + + List policyItemConditionList = new ArrayList<>(); + XXPolicyItemCondition policyItemCondition = new XXPolicyItemCondition(); + policyItemCondition.setAddedByUserId(Id); + policyItemCondition.setCreateTime(new Date()); + policyItemCondition.setType(1L); + policyItemCondition.setId(Id); + policyItemCondition.setOrder(1); + policyItemCondition.setPolicyItemId(Id); + policyItemCondition.setUpdatedByUserId(Id); + policyItemCondition.setUpdateTime(new Date()); + policyItemConditionList.add(policyItemCondition); + + List policyItemGroupPermList = new ArrayList<>(); + XXPolicyItemGroupPerm policyItemGroupPerm = new XXPolicyItemGroupPerm(); + policyItemGroupPerm.setAddedByUserId(Id); + policyItemGroupPerm.setCreateTime(new Date()); + policyItemGroupPerm.setGroupId(Id); + + List xConfMapList = new ArrayList<>(); + XXServiceConfigMap xConfMap = new XXServiceConfigMap(); + xConfMap.setAddedByUserId(null); + xConfMap.setConfigkey(name); + xConfMap.setConfigvalue(name); + xConfMap.setCreateTime(new Date()); + xConfMap.setServiceId(null); + xConfMap.setId(Id); + xConfMap.setUpdatedByUserId(null); + xConfMap.setUpdateTime(new Date()); + xConfMapList.add(xConfMap); + policyItemGroupPerm.setId(Id); + policyItemGroupPerm.setOrder(1); + policyItemGroupPerm.setPolicyItemId(Id); + policyItemGroupPerm.setUpdatedByUserId(Id); + policyItemGroupPerm.setUpdateTime(new Date()); + policyItemGroupPermList.add(policyItemGroupPerm); + + List policyItemUserPermList = new ArrayList<>(); + XXPolicyItemUserPerm policyItemUserPerm = new XXPolicyItemUserPerm(); + policyItemUserPerm.setAddedByUserId(Id); + policyItemUserPerm.setCreateTime(new Date()); + policyItemUserPerm.setPolicyItemId(Id); + policyItemUserPerm.setId(Id); + policyItemUserPerm.setOrder(1); + policyItemUserPerm.setUpdatedByUserId(Id); + policyItemUserPerm.setUpdateTime(new Date()); + policyItemUserPermList.add(policyItemUserPerm); + + List policyItemAccessList = new ArrayList<>(); + XXPolicyItemAccess policyItemAccess = new XXPolicyItemAccess(); + policyItemAccess.setAddedByUserId(Id); + policyItemAccess.setCreateTime(new Date()); + policyItemAccess.setPolicyitemid(Id); + policyItemAccess.setId(Id); + policyItemAccess.setOrder(1); + policyItemAccess.setUpdatedByUserId(Id); + policyItemAccess.setUpdateTime(new Date()); + policyItemAccessList.add(policyItemAccess); + + List policyResourceList = new ArrayList<>(); + XXPolicyResource policyResource = new XXPolicyResource(); + policyResource.setId(Id); + policyResource.setCreateTime(new Date()); + policyResource.setAddedByUserId(Id); + policyResource.setIsExcludes(false); + policyResource.setIsRecursive(false); + policyResource.setPolicyId(Id); + policyResource.setResDefId(Id); + policyResource.setUpdatedByUserId(Id); + policyResource.setUpdateTime(new Date()); + policyResourceList.add(policyResource); + + List policyResourceMapList = new ArrayList<>(); + XXPolicyResourceMap policyResourceMap = new XXPolicyResourceMap(); + policyResourceMap.setAddedByUserId(Id); + policyResourceMap.setCreateTime(new Date()); + policyResourceMap.setId(Id); + policyResourceMap.setOrder(1); + policyResourceMap.setResourceId(Id); + policyResourceMap.setUpdatedByUserId(Id); + policyResourceMap.setUpdateTime(new Date()); + policyResourceMap.setValue("1L"); + policyResourceMapList.add(policyResourceMap); + + List xServiceConfigDefList = new ArrayList<>(); + XXServiceConfigDef serviceConfigDefObj = new XXServiceConfigDef(); + serviceConfigDefObj.setId(Id); + xServiceConfigDefList.add(serviceConfigDefObj); + + Mockito.when(daoManager.getXXSecurityZoneDao()).thenReturn(xSecurityZoneDao); + Mockito.when(xSecurityZoneDao.findZonesByServiceName(rangerService.getName())).thenReturn(zonesNameList); + + Mockito.when(daoManager.getXXPolicy()).thenReturn(xPolicyDao); + Mockito.when(xPolicyDao.findPolicyIdsByServiceId(rangerService.getId())).thenReturn(policiesIds); + Mockito.when(svcService.delete(rangerService)).thenReturn(true); + + Mockito.when(policyService.read(Id)).thenReturn(rangerPolicy); + Mockito.when(daoManager.getXXService()).thenReturn(xServiceDao); + Mockito.when(svcService.getPopulatedViewObject(xService)).thenReturn(rangerService); + + Mockito.when(daoManager.getXXService()).thenReturn(xServiceDao); + Mockito.when(xServiceDao.getById(Id)).thenReturn(xService); + + Mockito.when(daoManager.getXXService()).thenReturn(xServiceDao); + Mockito.when(xServiceDao.getById(rangerService.getId())).thenReturn(xService); + + Mockito.when(daoManager.getXXServiceConfigMap()).thenReturn(xServiceConfigMapDao); + Mockito.when(xServiceConfigMapDao.findByServiceId(rangerService.getId())).thenReturn(xConfMapList); + Mockito.when(daoManager.getXXPolicyLabelMap()).thenReturn(xPolicyLabelMapDao); + Mockito.when(xPolicyLabelMapDao.findByPolicyId(rangerPolicy.getId())).thenReturn(ListUtils.EMPTY_LIST); + + Mockito.when(daoManager.getXXRMSServiceResource()).thenReturn(xRMSServiceResourceDao); + + Mockito.when(!bizUtil.hasAccess(xService, null)).thenReturn(true); + Mockito.when(tagStore.resetTagCache(rangerService.getName())).thenReturn(true); + + serviceDBStore.deleteService(Id); + Mockito.verify(svcService).delete(rangerService); + Mockito.verify(tagStore).resetTagCache(rangerService.getName()); + } + + @Test + public void test22getService() throws Exception { + RangerService rangerService = rangerService(); + XXService xService = xService(); + XXServiceDao xServiceDao = Mockito.mock(XXServiceDao.class); + + Mockito.when(daoManager.getXXService()).thenReturn(xServiceDao); + Mockito.when(xServiceDao.getById(Id)).thenReturn(xService); + Mockito.when(!bizUtil.hasAccess(xService, null)).thenReturn(true); + + Mockito.when(svcService.getPopulatedViewObject(xService)).thenReturn(rangerService); + RangerService dbRangerService = serviceDBStore.getService(Id); + Assert.assertNotNull(dbRangerService); + Assert.assertEquals(dbRangerService, rangerService); + Assert.assertEquals(dbRangerService.getCreatedBy(), rangerService.getCreatedBy()); + Assert.assertEquals(dbRangerService.getDescription(), rangerService.getDescription()); + Assert.assertEquals(dbRangerService.getGuid(), rangerService.getGuid()); + Assert.assertEquals(dbRangerService.getName(), rangerService.getName()); + Assert.assertEquals(dbRangerService.getType(), rangerService.getType()); + Assert.assertEquals(dbRangerService.getUpdatedBy(), rangerService.getUpdatedBy()); + Assert.assertEquals(dbRangerService.getConfigs(), rangerService.getConfigs()); + Assert.assertEquals(dbRangerService.getCreateTime(), rangerService.getCreateTime()); + Assert.assertEquals(dbRangerService.getId(), rangerService.getId()); + Assert.assertEquals(dbRangerService.getPolicyVersion(), rangerService.getPolicyVersion()); + Assert.assertEquals(dbRangerService.getVersion(), rangerService.getVersion()); + Assert.assertEquals(dbRangerService.getPolicyUpdateTime(), rangerService.getPolicyUpdateTime()); + Mockito.verify(daoManager).getXXService(); + Mockito.verify(bizUtil).hasAccess(xService, null); + Mockito.verify(svcService).getPopulatedViewObject(xService); + } + @Test + public void test23getServiceByName() throws Exception { + XXServiceDao xServiceDao = Mockito.mock(XXServiceDao.class); + RangerService rangerService = rangerService(); + XXService xService = xService(); + String name = rangerService.getName(); + + Mockito.when(daoManager.getXXService()).thenReturn(xServiceDao); + Mockito.when(xServiceDao.findByName(name)).thenReturn(xService); + Mockito.when(!bizUtil.hasAccess(xService, null)).thenReturn(true); + Mockito.when(svcService.getPopulatedViewObject(xService)).thenReturn(rangerService); + + RangerService dbRangerService = serviceDBStore.getServiceByName(name); + Assert.assertNotNull(dbRangerService); + Assert.assertEquals(dbRangerService, rangerService); + Assert.assertEquals(dbRangerService.getName(), rangerService.getName()); + Mockito.verify(daoManager).getXXService(); + Mockito.verify(bizUtil).hasAccess(xService, null); + Mockito.verify(svcService).getPopulatedViewObject(xService); + } + + @Test + public void test24getServices() throws Exception { + SearchFilter filter = new SearchFilter(); + filter.setParam(SearchFilter.POLICY_NAME, "policyName"); + filter.setParam(SearchFilter.SERVICE_NAME, "serviceName"); + + List serviceList = new ArrayList<>(); + RangerService rangerService = rangerService(); + serviceList.add(rangerService); + + RangerServiceList serviceListObj = new RangerServiceList(); + serviceListObj.setPageSize(0); + serviceListObj.setResultSize(1); + serviceListObj.setSortBy("asc"); + serviceListObj.setSortType("1"); + serviceListObj.setStartIndex(0); + serviceListObj.setTotalCount(10); + serviceListObj.setServices(serviceList); + + Mockito.when(svcService.searchRangerServices(filter)).thenReturn(serviceListObj); + List dbRangerService = serviceDBStore.getServices(filter); + Assert.assertNotNull(dbRangerService); + Assert.assertEquals(dbRangerService, serviceList); + Mockito.verify(svcService).searchRangerServices(filter); + } + + @Test + public void test25getPaginatedServiceDefs() throws Exception { + SearchFilter filter = new SearchFilter(); + filter.setParam(SearchFilter.POLICY_NAME, "policyName"); + filter.setParam(SearchFilter.SERVICE_NAME, "serviceName"); + + List serviceList = new ArrayList<>(); + RangerService rangerService = rangerService(); + serviceList.add(rangerService); + + RangerServiceList serviceListObj = new RangerServiceList(); + serviceListObj.setPageSize(0); + serviceListObj.setResultSize(1); + serviceListObj.setSortBy("asc"); + serviceListObj.setSortType("1"); + serviceListObj.setStartIndex(0); + serviceListObj.setTotalCount(10); + serviceListObj.setServices(serviceList); + + Mockito.when(svcService.searchRangerServices(filter)).thenReturn(serviceListObj); + + PList dbServiceList = serviceDBStore.getPaginatedServices(filter); + Assert.assertNotNull(dbServiceList); + Assert.assertEquals(dbServiceList.getList(), serviceListObj.getServices()); + + Mockito.verify(svcService).searchRangerServices(filter); + } + + @Test + public void test26createPolicy() throws Exception { + setup(); + XXServiceDefDao xServiceDefDao = Mockito.mock(XXServiceDefDao.class); + XXPolicy xPolicy = Mockito.mock(XXPolicy.class); + XXPolicyDao xPolicyDao = Mockito.mock(XXPolicyDao.class); + XXServiceDao xServiceDao = Mockito.mock(XXServiceDao.class); + XXService xService = Mockito.mock(XXService.class); + + XXServiceDef xServiceDef = serviceDef(); + Map configs = new HashMap<>(); + configs.put("username", "servicemgr"); + configs.put("password", "servicemgr"); + configs.put("namenode", "servicemgr"); + configs.put("hadoop.security.authorization", "No"); + configs.put("hadoop.security.authentication", "Simple"); + configs.put("hadoop.security.auth_to_local", ""); + configs.put("dfs.datanode.kerberos.principal", ""); + configs.put("dfs.namenode.kerberos.principal", ""); + configs.put("dfs.secondary.namenode.kerberos.principal", ""); + configs.put("hadoop.rpc.protection", "Privacy"); + configs.put("commonNameForCertificate", ""); + + RangerService rangerService = new RangerService(); + rangerService.setId(Id); + rangerService.setConfigs(configs); + rangerService.setCreateTime(new Date()); + rangerService.setDescription("service policy"); + rangerService.setGuid("1427365526516_835_0"); + rangerService.setIsEnabled(true); + rangerService.setName("HDFS_1"); + rangerService.setPolicyUpdateTime(new Date()); + rangerService.setType("1"); + rangerService.setUpdatedBy("Admin"); + + String policyName = "HDFS_1-1-20150316062345"; + String name = "HDFS_1-1-20150316062453"; + + List accessesList = new ArrayList<>(); + RangerPolicyItemAccess policyItemAccess = new RangerPolicyItemAccess(); + policyItemAccess.setIsAllowed(true); + policyItemAccess.setType("1"); + List usersList = new ArrayList<>(); + List groupsList = new ArrayList<>(); + List rolesList = new ArrayList<>(); + List policyLabels = new ArrayList<>(); + List conditionsList = new ArrayList<>(); + RangerPolicyItemCondition policyItemCondition = new RangerPolicyItemCondition(); + policyItemCondition.setType("1"); + policyItemCondition.setValues(usersList); + conditionsList.add(policyItemCondition); + + List policyItems = new ArrayList<>(); + RangerPolicyItem rangerPolicyItem = new RangerPolicyItem(); + rangerPolicyItem.setDelegateAdmin(false); + rangerPolicyItem.setAccesses(accessesList); + rangerPolicyItem.setConditions(conditionsList); + rangerPolicyItem.setGroups(groupsList); + rangerPolicyItem.setUsers(usersList); + policyItems.add(rangerPolicyItem); + + List policyItemsSet = new ArrayList<>(); + RangerPolicyItem paramPolicyItem = new RangerPolicyItem(accessesList, usersList, groupsList, rolesList, conditionsList, false); + paramPolicyItem.setDelegateAdmin(false); + paramPolicyItem.setAccesses(accessesList); + paramPolicyItem.setConditions(conditionsList); + paramPolicyItem.setGroups(groupsList); + rangerPolicyItem.setUsers(usersList); + policyItemsSet.add(paramPolicyItem); + + XXPolicyItem xPolicyItem = new XXPolicyItem(); + xPolicyItem.setDelegateAdmin(false); + xPolicyItem.setAddedByUserId(null); + xPolicyItem.setCreateTime(new Date()); + xPolicyItem.setGUID(null); + xPolicyItem.setId(Id); + xPolicyItem.setOrder(null); + xPolicyItem.setPolicyId(Id); + xPolicyItem.setUpdatedByUserId(null); + xPolicyItem.setUpdateTime(new Date()); + + XXPolicy xxPolicy = new XXPolicy(); + xxPolicy.setId(Id); + xxPolicy.setName(name); + xxPolicy.setAddedByUserId(Id); + xxPolicy.setCreateTime(new Date()); + xxPolicy.setDescription("test"); + xxPolicy.setIsAuditEnabled(true); + xxPolicy.setIsEnabled(true); + xxPolicy.setService(1L); + xxPolicy.setUpdatedByUserId(Id); + xxPolicy.setUpdateTime(new Date()); + + List xServiceConfigDefList = new ArrayList<>(); + XXServiceConfigDef serviceConfigDefObj = new XXServiceConfigDef(); + serviceConfigDefObj.setId(Id); + xServiceConfigDefList.add(serviceConfigDefObj); + + List xConfMapList = new ArrayList<>(); + XXServiceConfigMap xConfMap = new XXServiceConfigMap(); + xConfMap.setAddedByUserId(null); + xConfMap.setConfigkey(name); + xConfMap.setConfigvalue(name); + xConfMap.setCreateTime(new Date()); + xConfMap.setServiceId(null); + xConfMap.setId(Id); + xConfMap.setUpdatedByUserId(null); + xConfMap.setUpdateTime(new Date()); + xConfMapList.add(xConfMap); + + List users = new ArrayList<>(); + + RangerPolicyResource rangerPolicyResource = new RangerPolicyResource(); + rangerPolicyResource.setIsExcludes(true); + rangerPolicyResource.setIsRecursive(true); + rangerPolicyResource.setValue("1"); + rangerPolicyResource.setValues(users); + + Map policyResource = new HashMap<>(); + policyResource.put(name, rangerPolicyResource); + policyResource.put(policyName, rangerPolicyResource); + RangerPolicy rangerPolicy = new RangerPolicy(); + rangerPolicy.setId(Id); + rangerPolicy.setCreateTime(new Date()); + rangerPolicy.setDescription("policy"); + rangerPolicy.setGuid("policyguid"); + rangerPolicy.setIsEnabled(true); + rangerPolicy.setName("HDFS_1-1-20150316062453"); + rangerPolicy.setUpdatedBy("Admin"); + rangerPolicy.setUpdateTime(new Date()); + rangerPolicy.setService("HDFS_1-1-20150316062453"); + rangerPolicy.setIsAuditEnabled(true); + rangerPolicy.setPolicyItems(policyItems); + rangerPolicy.setResources(policyResource); + rangerPolicy.setPolicyLabels(policyLabels); + + XXPolicyResource xPolicyResource = new XXPolicyResource(); + xPolicyResource.setAddedByUserId(Id); + xPolicyResource.setCreateTime(new Date()); + xPolicyResource.setId(Id); + xPolicyResource.setIsExcludes(true); + xPolicyResource.setIsRecursive(true); + xPolicyResource.setPolicyId(Id); + xPolicyResource.setResDefId(Id); + xPolicyResource.setUpdatedByUserId(Id); + xPolicyResource.setUpdateTime(new Date()); + + List policyConditionDefList = new ArrayList<>(); + XXPolicyConditionDef policyConditionDefObj = new XXPolicyConditionDef(); + policyConditionDefObj.setAddedByUserId(Id); + policyConditionDefObj.setCreateTime(new Date()); + policyConditionDefObj.setDefid(Id); + policyConditionDefObj.setDescription("policy"); + policyConditionDefObj.setId(Id); + policyConditionDefObj.setName("country"); + policyConditionDefObj.setOrder(0); + policyConditionDefObj.setUpdatedByUserId(Id); + policyConditionDefObj.setUpdateTime(new Date()); + policyConditionDefList.add(policyConditionDefObj); + + Mockito.when(daoManager.getXXService()).thenReturn(xServiceDao); + Mockito.when(xServiceDao.findByName(name)).thenReturn(xService); + + Mockito.when(svcService.getPopulatedViewObject(xService)).thenReturn(rangerService); + + Mockito.when(daoManager.getXXServiceDef()).thenReturn(xServiceDefDao); + Mockito.when(xServiceDefDao.findByName(rangerService.getType())).thenReturn(xServiceDef); + + Mockito.when(daoManager.getXXPolicy()).thenReturn(xPolicyDao); + Mockito.when(policyService.create(rangerPolicy, true)).thenReturn(rangerPolicy); + + Mockito.when(daoManager.getXXPolicy()).thenReturn(xPolicyDao); + Mockito.when(xPolicyDao.getById(Id)).thenReturn(xPolicy); + Mockito.doNothing().when(policyRefUpdater).createNewPolMappingForRefTable(rangerPolicy, xPolicy, xServiceDef, false); + Mockito.when(policyService.getPopulatedViewObject(xPolicy)).thenReturn(rangerPolicy); + + Mockito.when(daoManager.getXXService()).thenReturn(xServiceDao); + Mockito.when(xServiceDao.getById(Id)).thenReturn(xService); + + Mockito.when(daoManager.getXXService()).thenReturn(xServiceDao); + Mockito.when(xServiceDao.getById(Id)).thenReturn(xService); + + RangerPolicyResourceSignature signature = Mockito.mock(RangerPolicyResourceSignature.class); + Mockito.when(factory.createPolicyResourceSignature(rangerPolicy)).thenReturn(signature); + Mockito.when(!bizUtil.hasAccess(xService, null)).thenReturn(true); + + RangerPolicy dbRangerPolicy = serviceDBStore.createPolicy(rangerPolicy); + + Assert.assertNotNull(dbRangerPolicy); + Assert.assertEquals(Id, dbRangerPolicy.getId()); + } + + @Test + public void tess27getPolicy() throws Exception { + RangerPolicy rangerPolicy = rangerPolicy(); + Mockito.when(policyService.read(Id)).thenReturn(rangerPolicy); + RangerPolicy dbRangerPolicy = serviceDBStore.getPolicy(Id); + Assert.assertNotNull(dbRangerPolicy); + Assert.assertEquals(dbRangerPolicy, rangerPolicy); + Assert.assertEquals(dbRangerPolicy.getId(), rangerPolicy.getId()); + Assert.assertEquals(dbRangerPolicy.getName(), rangerPolicy.getName()); + Assert.assertEquals(dbRangerPolicy.getCreatedBy(), rangerPolicy.getCreatedBy()); + Assert.assertEquals(dbRangerPolicy.getDescription(), rangerPolicy.getDescription()); + Assert.assertEquals(dbRangerPolicy.getGuid(), rangerPolicy.getGuid()); + Assert.assertEquals(dbRangerPolicy.getService(), rangerPolicy.getService()); + Assert.assertEquals(dbRangerPolicy.getUpdatedBy(), rangerPolicy.getUpdatedBy()); + Assert.assertEquals(dbRangerPolicy.getCreateTime(), rangerPolicy.getCreateTime()); + Assert.assertEquals(dbRangerPolicy.getIsAuditEnabled(), rangerPolicy.getIsAuditEnabled()); + Assert.assertEquals(dbRangerPolicy.getIsEnabled(), rangerPolicy.getIsEnabled()); + Assert.assertEquals(dbRangerPolicy.getPolicyItems(), rangerPolicy.getPolicyItems()); + Assert.assertEquals(dbRangerPolicy.getVersion(), rangerPolicy.getVersion()); + Mockito.verify(policyService).read(Id); + } + + @Test + public void tess28updatePolicy() throws Exception { + setup(); + XXPolicyDao xPolicyDao = Mockito.mock(XXPolicyDao.class); + XXPolicy xPolicy = Mockito.mock(XXPolicy.class); + XXServiceDao xServiceDao = Mockito.mock(XXServiceDao.class); + XXService xService = Mockito.mock(XXService.class); + XXServiceDefDao xServiceDefDao = Mockito.mock(XXServiceDefDao.class); + XXServiceDef xServiceDef = Mockito.mock(XXServiceDef.class); + XXPolicyLabelMapDao xPolicyLabelMapDao = Mockito.mock(XXPolicyLabelMapDao.class); + + RangerService rangerService = rangerService(); + + RangerPolicy rangerPolicy = rangerPolicy(); + String name = "HDFS_1-1-20150316062453"; + + List policyResourceList = new ArrayList<>(); + XXPolicyResource policyResource = new XXPolicyResource(); + policyResource.setId(Id); + policyResource.setCreateTime(new Date()); + policyResource.setAddedByUserId(Id); + policyResource.setIsExcludes(false); + policyResource.setIsRecursive(false); + policyResource.setPolicyId(Id); + policyResource.setResDefId(Id); + policyResource.setUpdatedByUserId(Id); + policyResource.setUpdateTime(new Date()); + policyResourceList.add(policyResource); + + List policyResourceMapList = new ArrayList<>(); + XXPolicyResourceMap policyResourceMap = new XXPolicyResourceMap(); + policyResourceMap.setAddedByUserId(Id); + policyResourceMap.setCreateTime(new Date()); + policyResourceMap.setId(Id); + policyResourceMap.setOrder(1); + policyResourceMap.setResourceId(Id); + policyResourceMap.setUpdatedByUserId(Id); + policyResourceMap.setUpdateTime(new Date()); + policyResourceMap.setValue("1L"); + policyResourceMapList.add(policyResourceMap); + + List xServiceConfigDefList = new ArrayList<>(); + XXServiceConfigDef serviceConfigDefObj = new XXServiceConfigDef(); + serviceConfigDefObj.setId(Id); + xServiceConfigDefList.add(serviceConfigDefObj); + + List xConfMapList = new ArrayList<>(); + XXServiceConfigMap xConfMap = new XXServiceConfigMap(); + xConfMap.setAddedByUserId(null); + xConfMap.setConfigkey(name); + xConfMap.setConfigvalue(name); + xConfMap.setCreateTime(new Date()); + xConfMap.setServiceId(null); + xConfMap.setId(Id); + xConfMap.setUpdatedByUserId(null); + xConfMap.setUpdateTime(new Date()); + xConfMapList.add(xConfMap); + + Mockito.when(daoManager.getXXPolicy()).thenReturn(xPolicyDao); + Mockito.when(xPolicyDao.getById(Id)).thenReturn(xPolicy); + Mockito.when(policyService.getPopulatedViewObject(xPolicy)).thenReturn(rangerPolicy); + + Mockito.when(daoManager.getXXService()).thenReturn(xServiceDao); + Mockito.when(xServiceDao.findByName(name)).thenReturn(xService); + Mockito.when(svcService.getPopulatedViewObject(xService)).thenReturn(rangerService); + + Mockito.when(daoManager.getXXServiceDef()).thenReturn(xServiceDefDao); + Mockito.when(xServiceDefDao.findByName(rangerService.getType())).thenReturn(xServiceDef); + + Mockito.when(policyService.update(rangerPolicy)).thenReturn(rangerPolicy); + Mockito.when(daoManager.getXXPolicy()).thenReturn(xPolicyDao); + Mockito.when(xPolicyDao.getById(rangerPolicy.getId())).thenReturn(xPolicy); + + Mockito.when(daoManager.getXXService()).thenReturn(xServiceDao); + Mockito.when(xServiceDao.getById(rangerService.getId())).thenReturn(xService); + + Mockito.when(daoManager.getXXService()).thenReturn(xServiceDao); + Mockito.when(xServiceDao.getById(rangerService.getId())).thenReturn(xService); + Mockito.when(daoManager.getXXPolicyLabelMap()).thenReturn(xPolicyLabelMapDao); + Mockito.when(xPolicyLabelMapDao.findByPolicyId(rangerPolicy.getId())).thenReturn(ListUtils.EMPTY_LIST); + + RangerPolicyResourceSignature signature = Mockito.mock(RangerPolicyResourceSignature.class); + Mockito.when(factory.createPolicyResourceSignature(rangerPolicy)).thenReturn(signature); + Mockito.when(!bizUtil.hasAccess(xService, null)).thenReturn(true); + Mockito.when(policyRefUpdater.cleanupRefTables(rangerPolicy)).thenReturn(true); RangerPolicy dbRangerPolicy = serviceDBStore.updatePolicy(rangerPolicy); - Assert.assertNotNull(dbRangerPolicy); - Assert.assertEquals(dbRangerPolicy, rangerPolicy); - Assert.assertEquals(dbRangerPolicy.getId(), rangerPolicy.getId()); - Assert.assertEquals(dbRangerPolicy.getCreatedBy(), - rangerPolicy.getCreatedBy()); - Assert.assertEquals(dbRangerPolicy.getDescription(), - rangerPolicy.getDescription()); - Assert.assertEquals(dbRangerPolicy.getName(), rangerPolicy.getName()); - Assert.assertEquals(dbRangerPolicy.getGuid(), rangerPolicy.getGuid()); - Assert.assertEquals(dbRangerPolicy.getService(), - rangerPolicy.getService()); - Assert.assertEquals(dbRangerPolicy.getIsEnabled(), - rangerPolicy.getIsEnabled()); - Assert.assertEquals(dbRangerPolicy.getVersion(), - rangerPolicy.getVersion()); - } - - @Test - public void tess29deletePolicy() throws Exception { - setup(); - XXServiceDao xServiceDao = Mockito.mock(XXServiceDao.class); - XXService xService = Mockito.mock(XXService.class); - XXPolicyLabelMapDao xPolicyLabelMapDao = Mockito.mock(XXPolicyLabelMapDao.class); - - RangerService rangerService = rangerService(); - RangerPolicy rangerPolicy = rangerPolicy(); - String name = "HDFS_1-1-20150316062453"; - - List policyItemList = new ArrayList(); - XXPolicyItem policyItem = new XXPolicyItem(); - policyItem.setAddedByUserId(Id); - policyItem.setCreateTime(new Date()); - policyItem.setDelegateAdmin(false); - policyItem.setId(Id); - policyItem.setOrder(1); - policyItem.setPolicyId(Id); - policyItem.setUpdatedByUserId(Id); - policyItem.setUpdateTime(new Date()); - policyItemList.add(policyItem); - - List policyItemConditionList = new ArrayList(); - XXPolicyItemCondition policyItemCondition = new XXPolicyItemCondition(); - policyItemCondition.setAddedByUserId(Id); - policyItemCondition.setCreateTime(new Date()); - policyItemCondition.setType(1L); - policyItemCondition.setId(Id); - policyItemCondition.setOrder(1); - policyItemCondition.setPolicyItemId(Id); - policyItemCondition.setUpdatedByUserId(Id); - policyItemCondition.setUpdateTime(new Date()); - policyItemConditionList.add(policyItemCondition); - - List policyItemGroupPermList = new ArrayList(); - XXPolicyItemGroupPerm policyItemGroupPerm = new XXPolicyItemGroupPerm(); - policyItemGroupPerm.setAddedByUserId(Id); - policyItemGroupPerm.setCreateTime(new Date()); - policyItemGroupPerm.setGroupId(Id); - - List xConfMapList = new ArrayList(); - XXServiceConfigMap xConfMap = new XXServiceConfigMap(); - xConfMap.setAddedByUserId(null); - xConfMap.setConfigkey(name); - xConfMap.setConfigvalue(name); - xConfMap.setCreateTime(new Date()); - xConfMap.setServiceId(null); - xConfMap.setId(Id); - xConfMap.setUpdatedByUserId(null); - xConfMap.setUpdateTime(new Date()); - xConfMapList.add(xConfMap); - policyItemGroupPerm.setId(Id); - policyItemGroupPerm.setOrder(1); - policyItemGroupPerm.setPolicyItemId(Id); - policyItemGroupPerm.setUpdatedByUserId(Id); - policyItemGroupPerm.setUpdateTime(new Date()); - policyItemGroupPermList.add(policyItemGroupPerm); - - List policyItemUserPermList = new ArrayList(); - XXPolicyItemUserPerm policyItemUserPerm = new XXPolicyItemUserPerm(); - policyItemUserPerm.setAddedByUserId(Id); - policyItemUserPerm.setCreateTime(new Date()); - policyItemUserPerm.setPolicyItemId(Id); - policyItemUserPerm.setId(Id); - policyItemUserPerm.setOrder(1); - policyItemUserPerm.setUpdatedByUserId(Id); - policyItemUserPerm.setUpdateTime(new Date()); - policyItemUserPermList.add(policyItemUserPerm); - - List policyItemAccessList = new ArrayList(); - XXPolicyItemAccess policyItemAccess = new XXPolicyItemAccess(); - policyItemAccess.setAddedByUserId(Id); - policyItemAccess.setCreateTime(new Date()); - policyItemAccess.setPolicyitemid(Id); - policyItemAccess.setId(Id); - policyItemAccess.setOrder(1); - policyItemAccess.setUpdatedByUserId(Id); - policyItemAccess.setUpdateTime(new Date()); - policyItemAccessList.add(policyItemAccess); - - List policyResourceList = new ArrayList(); - XXPolicyResource policyResource = new XXPolicyResource(); - policyResource.setId(Id); - policyResource.setCreateTime(new Date()); - policyResource.setAddedByUserId(Id); - policyResource.setIsExcludes(false); - policyResource.setIsRecursive(false); - policyResource.setPolicyId(Id); - policyResource.setResDefId(Id); - policyResource.setUpdatedByUserId(Id); - policyResource.setUpdateTime(new Date()); - policyResourceList.add(policyResource); - - XXPolicyResourceMap policyResourceMap = new XXPolicyResourceMap(); - policyResourceMap.setAddedByUserId(Id); - policyResourceMap.setCreateTime(new Date()); - policyResourceMap.setId(Id); - policyResourceMap.setOrder(1); - policyResourceMap.setResourceId(Id); - policyResourceMap.setUpdatedByUserId(Id); - policyResourceMap.setUpdateTime(new Date()); - policyResourceMap.setValue("1L"); - List xServiceConfigDefList = new ArrayList(); - XXServiceConfigDef serviceConfigDefObj = new XXServiceConfigDef(); - serviceConfigDefObj.setId(Id); - xServiceConfigDefList.add(serviceConfigDefObj); - - Mockito.when(daoManager.getXXService()).thenReturn(xServiceDao); - Mockito.when(xServiceDao.findByName(name)).thenReturn(xService); - Mockito.when(svcService.getPopulatedViewObject(xService)).thenReturn( - rangerService); - - Mockito.when(daoManager.getXXService()).thenReturn(xServiceDao); - Mockito.when(xServiceDao.getById(Id)).thenReturn(xService); - - Mockito.when(daoManager.getXXService()).thenReturn(xServiceDao); - Mockito.when(xServiceDao.getById(rangerService.getId())).thenReturn( - xService); - Mockito.when(daoManager.getXXPolicyLabelMap()).thenReturn(xPolicyLabelMapDao); - Mockito.when(xPolicyLabelMapDao.findByPolicyId(rangerPolicy.getId())).thenReturn(ListUtils.EMPTY_LIST); - - Mockito.when(!bizUtil.hasAccess(xService, null)).thenReturn(true); + Assert.assertNotNull(dbRangerPolicy); + Assert.assertEquals(dbRangerPolicy, rangerPolicy); + Assert.assertEquals(dbRangerPolicy.getId(), rangerPolicy.getId()); + Assert.assertEquals(dbRangerPolicy.getCreatedBy(), rangerPolicy.getCreatedBy()); + Assert.assertEquals(dbRangerPolicy.getDescription(), rangerPolicy.getDescription()); + Assert.assertEquals(dbRangerPolicy.getName(), rangerPolicy.getName()); + Assert.assertEquals(dbRangerPolicy.getGuid(), rangerPolicy.getGuid()); + Assert.assertEquals(dbRangerPolicy.getService(), rangerPolicy.getService()); + Assert.assertEquals(dbRangerPolicy.getIsEnabled(), rangerPolicy.getIsEnabled()); + Assert.assertEquals(dbRangerPolicy.getVersion(), rangerPolicy.getVersion()); + } + + @Test + public void tess29deletePolicy() throws Exception { + setup(); + XXServiceDao xServiceDao = Mockito.mock(XXServiceDao.class); + XXService xService = Mockito.mock(XXService.class); + XXPolicyLabelMapDao xPolicyLabelMapDao = Mockito.mock(XXPolicyLabelMapDao.class); + + RangerService rangerService = rangerService(); + RangerPolicy rangerPolicy = rangerPolicy(); + String name = "HDFS_1-1-20150316062453"; + + List policyItemList = new ArrayList<>(); + XXPolicyItem policyItem = new XXPolicyItem(); + policyItem.setAddedByUserId(Id); + policyItem.setCreateTime(new Date()); + policyItem.setDelegateAdmin(false); + policyItem.setId(Id); + policyItem.setOrder(1); + policyItem.setPolicyId(Id); + policyItem.setUpdatedByUserId(Id); + policyItem.setUpdateTime(new Date()); + policyItemList.add(policyItem); + + List policyItemConditionList = new ArrayList<>(); + XXPolicyItemCondition policyItemCondition = new XXPolicyItemCondition(); + policyItemCondition.setAddedByUserId(Id); + policyItemCondition.setCreateTime(new Date()); + policyItemCondition.setType(1L); + policyItemCondition.setId(Id); + policyItemCondition.setOrder(1); + policyItemCondition.setPolicyItemId(Id); + policyItemCondition.setUpdatedByUserId(Id); + policyItemCondition.setUpdateTime(new Date()); + policyItemConditionList.add(policyItemCondition); + + List policyItemGroupPermList = new ArrayList<>(); + XXPolicyItemGroupPerm policyItemGroupPerm = new XXPolicyItemGroupPerm(); + policyItemGroupPerm.setAddedByUserId(Id); + policyItemGroupPerm.setCreateTime(new Date()); + policyItemGroupPerm.setGroupId(Id); + + List xConfMapList = new ArrayList<>(); + XXServiceConfigMap xConfMap = new XXServiceConfigMap(); + xConfMap.setAddedByUserId(null); + xConfMap.setConfigkey(name); + xConfMap.setConfigvalue(name); + xConfMap.setCreateTime(new Date()); + xConfMap.setServiceId(null); + xConfMap.setId(Id); + xConfMap.setUpdatedByUserId(null); + xConfMap.setUpdateTime(new Date()); + xConfMapList.add(xConfMap); + policyItemGroupPerm.setId(Id); + policyItemGroupPerm.setOrder(1); + policyItemGroupPerm.setPolicyItemId(Id); + policyItemGroupPerm.setUpdatedByUserId(Id); + policyItemGroupPerm.setUpdateTime(new Date()); + policyItemGroupPermList.add(policyItemGroupPerm); + + List policyItemUserPermList = new ArrayList<>(); + XXPolicyItemUserPerm policyItemUserPerm = new XXPolicyItemUserPerm(); + policyItemUserPerm.setAddedByUserId(Id); + policyItemUserPerm.setCreateTime(new Date()); + policyItemUserPerm.setPolicyItemId(Id); + policyItemUserPerm.setId(Id); + policyItemUserPerm.setOrder(1); + policyItemUserPerm.setUpdatedByUserId(Id); + policyItemUserPerm.setUpdateTime(new Date()); + policyItemUserPermList.add(policyItemUserPerm); + + List policyItemAccessList = new ArrayList<>(); + XXPolicyItemAccess policyItemAccess = new XXPolicyItemAccess(); + policyItemAccess.setAddedByUserId(Id); + policyItemAccess.setCreateTime(new Date()); + policyItemAccess.setPolicyitemid(Id); + policyItemAccess.setId(Id); + policyItemAccess.setOrder(1); + policyItemAccess.setUpdatedByUserId(Id); + policyItemAccess.setUpdateTime(new Date()); + policyItemAccessList.add(policyItemAccess); + + List policyResourceList = new ArrayList<>(); + XXPolicyResource policyResource = new XXPolicyResource(); + policyResource.setId(Id); + policyResource.setCreateTime(new Date()); + policyResource.setAddedByUserId(Id); + policyResource.setIsExcludes(false); + policyResource.setIsRecursive(false); + policyResource.setPolicyId(Id); + policyResource.setResDefId(Id); + policyResource.setUpdatedByUserId(Id); + policyResource.setUpdateTime(new Date()); + policyResourceList.add(policyResource); + + XXPolicyResourceMap policyResourceMap = new XXPolicyResourceMap(); + policyResourceMap.setAddedByUserId(Id); + policyResourceMap.setCreateTime(new Date()); + policyResourceMap.setId(Id); + policyResourceMap.setOrder(1); + policyResourceMap.setResourceId(Id); + policyResourceMap.setUpdatedByUserId(Id); + policyResourceMap.setUpdateTime(new Date()); + policyResourceMap.setValue("1L"); + List xServiceConfigDefList = new ArrayList<>(); + XXServiceConfigDef serviceConfigDefObj = new XXServiceConfigDef(); + serviceConfigDefObj.setId(Id); + xServiceConfigDefList.add(serviceConfigDefObj); + + Mockito.when(daoManager.getXXService()).thenReturn(xServiceDao); + Mockito.when(xServiceDao.findByName(name)).thenReturn(xService); + Mockito.when(svcService.getPopulatedViewObject(xService)).thenReturn( + rangerService); + + Mockito.when(daoManager.getXXService()).thenReturn(xServiceDao); + Mockito.when(xServiceDao.getById(Id)).thenReturn(xService); + + Mockito.when(daoManager.getXXService()).thenReturn(xServiceDao); + Mockito.when(xServiceDao.getById(rangerService.getId())).thenReturn(xService); + Mockito.when(daoManager.getXXPolicyLabelMap()).thenReturn(xPolicyLabelMapDao); + Mockito.when(xPolicyLabelMapDao.findByPolicyId(rangerPolicy.getId())).thenReturn(ListUtils.EMPTY_LIST); + + Mockito.when(!bizUtil.hasAccess(xService, null)).thenReturn(true); Mockito.when(policyRefUpdater.cleanupRefTables(rangerPolicy)).thenReturn(true); - serviceDBStore.deletePolicy(rangerPolicy); - } - - @Test - public void test30getPolicies() throws Exception { - SearchFilter filter = new SearchFilter(); - filter.setParam(SearchFilter.POLICY_NAME, "policyName"); - filter.setParam(SearchFilter.SERVICE_NAME, "serviceName"); - - List rangerPolicyLists = new ArrayList(); - RangerPolicy rangerPolicy = rangerPolicy(); - rangerPolicyLists.add(rangerPolicy); - - RangerPolicyList policyListObj = new RangerPolicyList(); - policyListObj.setPageSize(0); - policyListObj.setResultSize(1); - policyListObj.setSortBy("asc"); - policyListObj.setSortType("1"); - policyListObj.setStartIndex(0); - policyListObj.setTotalCount(10); - - Set groupNames = new HashSet(){{add(RangerConstants.GROUP_PUBLIC);}}; - XXGroupGroupDao xXGroupGroupDao = Mockito.mock(XXGroupGroupDao.class); - Mockito.when(daoManager.getXXGroupGroup()).thenReturn(xXGroupGroupDao); - XXGroupDao xxGroupDao = Mockito.mock(XXGroupDao.class); - XXRoleDao xxRoleDao = Mockito.mock(XXRoleDao.class); - VXGroup vxGroup = vxGroup(); - XXGroup xxGroup = new XXGroup(); - xxGroup.setId(vxGroup.getId()); - xxGroup.setName(vxGroup.getName()); - xxGroup.setDescription(vxGroup.getDescription()); - xxGroup.setIsVisible(vxGroup.getIsVisible()); - Mockito.when(daoManager.getXXGroup()).thenReturn(xxGroupDao); - Mockito.when(xxGroupDao.findByGroupName(vxGroup.getName())).thenReturn(xxGroup); - Mockito.when(xXGroupGroupDao.findGroupNamesByGroupName(Mockito.anyString())).thenReturn(groupNames); - List xxRoles = new ArrayList(); - Mockito.when(daoManager.getXXGroup()).thenReturn(xxGroupDao); - Mockito.when(daoManager.getXXRole()).thenReturn(xxRoleDao); - Mockito.when(xxRoleDao.findByGroupId(xxGroup.getId())).thenReturn(xxRoles); - - List dbRangerPolicy = serviceDBStore.getPolicies(filter); - Assert.assertNotNull(dbRangerPolicy); - } - - @Test - public void test31getPaginatedPolicies() throws Exception { - SearchFilter filter = new SearchFilter(); - filter.setParam(SearchFilter.POLICY_NAME, "policyName"); - filter.setParam(SearchFilter.SERVICE_NAME, "serviceName"); - - RangerPolicyList policyListObj = new RangerPolicyList(); - policyListObj.setPageSize(0); - policyListObj.setResultSize(1); - policyListObj.setSortBy("asc"); - policyListObj.setSortType("1"); - policyListObj.setStartIndex(0); - policyListObj.setTotalCount(10); - - Set groupNames = new HashSet(){{add(RangerConstants.GROUP_PUBLIC);}}; - XXGroupGroupDao xXGroupGroupDao = Mockito.mock(XXGroupGroupDao.class); - Mockito.when(daoManager.getXXGroupGroup()).thenReturn(xXGroupGroupDao); - XXGroupDao xxGroupDao = Mockito.mock(XXGroupDao.class); - XXRoleDao xxRoleDao = Mockito.mock(XXRoleDao.class); - VXGroup vxGroup = vxGroup(); - XXGroup xxGroup = new XXGroup(); - xxGroup.setId(vxGroup.getId()); - xxGroup.setName(vxGroup.getName()); - xxGroup.setDescription(vxGroup.getDescription()); - xxGroup.setIsVisible(vxGroup.getIsVisible()); - Mockito.when(daoManager.getXXGroup()).thenReturn(xxGroupDao); - Mockito.when(xxGroupDao.findByGroupName(vxGroup.getName())).thenReturn(xxGroup); - Mockito.when(xXGroupGroupDao.findGroupNamesByGroupName(Mockito.anyString())).thenReturn(groupNames); - List xxRoles = new ArrayList(); - Mockito.when(daoManager.getXXGroup()).thenReturn(xxGroupDao); - Mockito.when(daoManager.getXXRole()).thenReturn(xxRoleDao); - Mockito.when(xxRoleDao.findByGroupId(xxGroup.getId())).thenReturn(xxRoles); - - PList dbRangerPolicyList = serviceDBStore - .getPaginatedPolicies(filter); - Assert.assertNotNull(dbRangerPolicyList); - } - - @Test - public void test32getServicePolicies() throws Exception { - SearchFilter filter = new SearchFilter(); - filter.setParam(SearchFilter.POLICY_NAME, "policyName"); - filter.setParam(SearchFilter.SERVICE_NAME, "serviceName"); - - XXService xService = xService(); - XXServiceDao xServiceDao = Mockito.mock(XXServiceDao.class); - Mockito.when(daoManager.getXXService()).thenReturn(xServiceDao); - Mockito.when(xServiceDao.getById(Id)).thenReturn(xService); - - thrown.expect(Exception.class); - List dbRangerPolicy = serviceDBStore.getServicePolicies( - Id, filter); + serviceDBStore.deletePolicy(rangerPolicy); + } + + @Test + public void test30getPolicies() throws Exception { + SearchFilter filter = new SearchFilter(); + filter.setParam(SearchFilter.POLICY_NAME, "policyName"); + filter.setParam(SearchFilter.SERVICE_NAME, "serviceName"); + + List rangerPolicyLists = new ArrayList<>(); + RangerPolicy rangerPolicy = rangerPolicy(); + rangerPolicyLists.add(rangerPolicy); + + RangerPolicyList policyListObj = new RangerPolicyList(); + policyListObj.setPageSize(0); + policyListObj.setResultSize(1); + policyListObj.setSortBy("asc"); + policyListObj.setSortType("1"); + policyListObj.setStartIndex(0); + policyListObj.setTotalCount(10); + + Set groupNames = new HashSet() {{ + add(RangerConstants.GROUP_PUBLIC); + }}; + XXGroupGroupDao xXGroupGroupDao = Mockito.mock(XXGroupGroupDao.class); + Mockito.when(daoManager.getXXGroupGroup()).thenReturn(xXGroupGroupDao); + XXGroupDao xxGroupDao = Mockito.mock(XXGroupDao.class); + XXRoleDao xxRoleDao = Mockito.mock(XXRoleDao.class); + VXGroup vxGroup = vxGroup(); + XXGroup xxGroup = new XXGroup(); + xxGroup.setId(vxGroup.getId()); + xxGroup.setName(vxGroup.getName()); + xxGroup.setDescription(vxGroup.getDescription()); + xxGroup.setIsVisible(vxGroup.getIsVisible()); + Mockito.when(daoManager.getXXGroup()).thenReturn(xxGroupDao); + Mockito.when(xxGroupDao.findByGroupName(vxGroup.getName())).thenReturn(xxGroup); + Mockito.when(xXGroupGroupDao.findGroupNamesByGroupName(Mockito.anyString())).thenReturn(groupNames); + List xxRoles = new ArrayList<>(); + Mockito.when(daoManager.getXXGroup()).thenReturn(xxGroupDao); + Mockito.when(daoManager.getXXRole()).thenReturn(xxRoleDao); + Mockito.when(xxRoleDao.findByGroupId(xxGroup.getId())).thenReturn(xxRoles); + + List dbRangerPolicy = serviceDBStore.getPolicies(filter); + Assert.assertNotNull(dbRangerPolicy); + } + + @Test + public void test31getPaginatedPolicies() throws Exception { + SearchFilter filter = new SearchFilter(); + filter.setParam(SearchFilter.POLICY_NAME, "policyName"); + filter.setParam(SearchFilter.SERVICE_NAME, "serviceName"); + + RangerPolicyList policyListObj = new RangerPolicyList(); + policyListObj.setPageSize(0); + policyListObj.setResultSize(1); + policyListObj.setSortBy("asc"); + policyListObj.setSortType("1"); + policyListObj.setStartIndex(0); + policyListObj.setTotalCount(10); + + Set groupNames = new HashSet() {{ + add(RangerConstants.GROUP_PUBLIC); + }}; + XXGroupGroupDao xXGroupGroupDao = Mockito.mock(XXGroupGroupDao.class); + Mockito.when(daoManager.getXXGroupGroup()).thenReturn(xXGroupGroupDao); + XXGroupDao xxGroupDao = Mockito.mock(XXGroupDao.class); + XXRoleDao xxRoleDao = Mockito.mock(XXRoleDao.class); + VXGroup vxGroup = vxGroup(); + XXGroup xxGroup = new XXGroup(); + xxGroup.setId(vxGroup.getId()); + xxGroup.setName(vxGroup.getName()); + xxGroup.setDescription(vxGroup.getDescription()); + xxGroup.setIsVisible(vxGroup.getIsVisible()); + Mockito.when(daoManager.getXXGroup()).thenReturn(xxGroupDao); + Mockito.when(xxGroupDao.findByGroupName(vxGroup.getName())).thenReturn(xxGroup); + Mockito.when(xXGroupGroupDao.findGroupNamesByGroupName(Mockito.anyString())).thenReturn(groupNames); + List xxRoles = new ArrayList<>(); + Mockito.when(daoManager.getXXGroup()).thenReturn(xxGroupDao); + Mockito.when(daoManager.getXXRole()).thenReturn(xxRoleDao); + Mockito.when(xxRoleDao.findByGroupId(xxGroup.getId())).thenReturn(xxRoles); + + PList dbRangerPolicyList = serviceDBStore + .getPaginatedPolicies(filter); + Assert.assertNotNull(dbRangerPolicyList); + } + + @Test + public void test32getServicePolicies() throws Exception { + SearchFilter filter = new SearchFilter(); + filter.setParam(SearchFilter.POLICY_NAME, "policyName"); + filter.setParam(SearchFilter.SERVICE_NAME, "serviceName"); + + XXService xService = xService(); + XXServiceDao xServiceDao = Mockito.mock(XXServiceDao.class); + Mockito.when(daoManager.getXXService()).thenReturn(xServiceDao); + Mockito.when(xServiceDao.getById(Id)).thenReturn(xService); + + thrown.expect(Exception.class); + List dbRangerPolicy = serviceDBStore.getServicePolicies(Id, filter); Assert.assertFalse(dbRangerPolicy.isEmpty()); - Mockito.verify(daoManager).getXXService(); - } - - @Test - public void test33getServicePoliciesIfUpdated() throws Exception { - XXServiceDao xServiceDao = Mockito.mock(XXServiceDao.class); - XXServiceVersionInfoDao xServiceVersionInfoDao = Mockito.mock(XXServiceVersionInfoDao.class); - - XXService xService = new XXService(); - xService.setAddedByUserId(Id); - xService.setCreateTime(new Date()); - xService.setDescription("Hdfs service"); - xService.setGuid("serviceguid"); - xService.setId(Id); - xService.setIsEnabled(true); - xService.setName("Hdfs"); - xService.setPolicyUpdateTime(new Date()); - xService.setPolicyVersion(1L); - xService.setType(1L); - xService.setUpdatedByUserId(Id); - xService.setUpdateTime(new Date()); - - XXServiceVersionInfo xServiceVersionInfo = new XXServiceVersionInfo(); - - xServiceVersionInfo.setServiceId(Id); - xServiceVersionInfo.setPolicyVersion(1L); - xServiceVersionInfo.setPolicyUpdateTime(new Date()); - xServiceVersionInfo.setTagVersion(1L); - xServiceVersionInfo.setTagUpdateTime(new Date()); - xServiceVersionInfo.setGdsVersion(1L); - xServiceVersionInfo.setGdsUpdateTime(new Date()); - - String serviceName = "HDFS_1"; - Long lastKnownVersion = 1l; - Mockito.when(daoManager.getXXService()).thenReturn(xServiceDao); - Mockito.when(daoManager.getXXServiceVersionInfo()).thenReturn(xServiceVersionInfoDao); - Mockito.when(xServiceDao.findByName(serviceName)).thenReturn(xService); - Mockito.when(xServiceVersionInfoDao.findByServiceName(serviceName)).thenReturn(xServiceVersionInfo); - - ServicePolicies dbServicePolicies = serviceDBStore - .getServicePoliciesIfUpdated(serviceName, lastKnownVersion, true); - Assert.assertNull(dbServicePolicies); - } - - @Test - public void test34getPolicyFromEventTime() { - XXDataHistDao xDataHistDao = Mockito.mock(XXDataHistDao.class); - XXDataHist xDataHist = Mockito.mock(XXDataHist.class); - - String eventTime = "2015-03-16 06:24:54"; - Mockito.when(daoManager.getXXDataHist()).thenReturn(xDataHistDao); - Mockito.when( - xDataHistDao.findObjByEventTimeClassTypeAndId(eventTime, 1020, - Id)).thenReturn(xDataHist); - - RangerPolicy dbRangerPolicy = serviceDBStore.getPolicyFromEventTime( - eventTime, Id); - Assert.assertNull(dbRangerPolicy); - Mockito.verify(daoManager).getXXDataHist(); - } - - @Test - public void test35getPopulateExistingBaseFields() { - Boolean isFound = serviceDBStore.getPopulateExistingBaseFields(); - Assert.assertFalse(isFound); - } - - @Test - public void test36getPaginatedServicePolicies() throws Exception { - String serviceName = "HDFS_1"; - RangerPolicyList policyList = new RangerPolicyList(); - policyList.setPageSize(0); - SearchFilter filter = new SearchFilter(); - filter.setParam(SearchFilter.POLICY_NAME, "policyName"); - filter.setParam(SearchFilter.SERVICE_NAME, "serviceName"); - - Set groupNames = new HashSet(){{add(RangerConstants.GROUP_PUBLIC);}}; - XXGroupGroupDao xXGroupGroupDao = Mockito.mock(XXGroupGroupDao.class); - Mockito.when(daoManager.getXXGroupGroup()).thenReturn(xXGroupGroupDao); - XXGroupDao xxGroupDao = Mockito.mock(XXGroupDao.class); - XXRoleDao xxRoleDao = Mockito.mock(XXRoleDao.class); - VXGroup vxGroup = vxGroup(); - XXGroup xxGroup = new XXGroup(); - xxGroup.setId(vxGroup.getId()); - xxGroup.setName(vxGroup.getName()); - xxGroup.setDescription(vxGroup.getDescription()); - xxGroup.setIsVisible(vxGroup.getIsVisible()); - Mockito.when(daoManager.getXXGroup()).thenReturn(xxGroupDao); - Mockito.when(xxGroupDao.findByGroupName(vxGroup.getName())).thenReturn(xxGroup); - Mockito.when(xXGroupGroupDao.findGroupNamesByGroupName(Mockito.anyString())).thenReturn(groupNames); - List xxRoles = new ArrayList(); - Mockito.when(daoManager.getXXGroup()).thenReturn(xxGroupDao); - Mockito.when(daoManager.getXXRole()).thenReturn(xxRoleDao); - Mockito.when(xxRoleDao.findByGroupId(xxGroup.getId())).thenReturn(xxRoles); - - PList dbRangerPolicyList = serviceDBStore - .getPaginatedServicePolicies(serviceName, filter); - Assert.assertNotNull(dbRangerPolicyList); - } - - @Test - public void test37getPaginatedServicePolicies() throws Exception { - - SearchFilter filter = new SearchFilter(); - filter.setParam(SearchFilter.POLICY_NAME, "policyName"); - filter.setParam(SearchFilter.SERVICE_NAME, "serviceName"); - RangerService rangerService = rangerService(); - - XXService xService = xService(); - XXServiceDao xServiceDao = Mockito.mock(XXServiceDao.class); - Mockito.when(daoManager.getXXService()).thenReturn(xServiceDao); - Mockito.when(xServiceDao.getById(Id)).thenReturn(xService); - - Set groupNames = new HashSet(){{add(RangerConstants.GROUP_PUBLIC);}}; - XXGroupGroupDao xXGroupGroupDao = Mockito.mock(XXGroupGroupDao.class); - Mockito.when(daoManager.getXXGroupGroup()).thenReturn(xXGroupGroupDao); - XXGroupDao xxGroupDao = Mockito.mock(XXGroupDao.class); - XXRoleDao xxRoleDao = Mockito.mock(XXRoleDao.class); - VXGroup vxGroup = vxGroup(); - XXGroup xxGroup = new XXGroup(); - xxGroup.setId(vxGroup.getId()); - xxGroup.setName(vxGroup.getName()); - xxGroup.setDescription(vxGroup.getDescription()); - xxGroup.setIsVisible(vxGroup.getIsVisible()); - Mockito.when(daoManager.getXXGroup()).thenReturn(xxGroupDao); - Mockito.when(xxGroupDao.findByGroupName(vxGroup.getName())).thenReturn(xxGroup); - Mockito.when(xXGroupGroupDao.findGroupNamesByGroupName(Mockito.anyString())).thenReturn(groupNames); - List xxRoles = new ArrayList(); - Mockito.when(daoManager.getXXGroup()).thenReturn(xxGroupDao); - Mockito.when(daoManager.getXXRole()).thenReturn(xxRoleDao); - Mockito.when(xxRoleDao.findByGroupId(xxGroup.getId())).thenReturn(xxRoles); - - //PList dbRangerPolicyList = - serviceDBStore.getPaginatedServicePolicies(rangerService.getId(), filter); - } - - @Test - public void test38getPolicyVersionList() throws Exception { - XXDataHistDao xDataHistDao = Mockito.mock(XXDataHistDao.class); - List versionList = new ArrayList(); - versionList.add(1); - versionList.add(2); - Mockito.when(daoManager.getXXDataHist()).thenReturn(xDataHistDao); - Mockito.when(xDataHistDao.getVersionListOfObject(Id, 1020)).thenReturn( - versionList); - - VXString dbVXString = serviceDBStore.getPolicyVersionList(Id); - Assert.assertNotNull(dbVXString); - Mockito.verify(daoManager).getXXDataHist(); - } - - @Test - public void test39getPolicyForVersionNumber() throws Exception { - XXDataHistDao xDataHistDao = Mockito.mock(XXDataHistDao.class); - XXDataHist xDataHist = Mockito.mock(XXDataHist.class); - Mockito.when(daoManager.getXXDataHist()).thenReturn(xDataHistDao); - Mockito.when(xDataHistDao.findObjectByVersionNumber(Id, 1020, 1)) - .thenReturn(xDataHist); - RangerPolicy dbRangerPolicy = serviceDBStore.getPolicyForVersionNumber( - Id, 1); - Assert.assertNull(dbRangerPolicy); - Mockito.verify(daoManager).getXXDataHist(); - } - - @Test - public void test40getPoliciesByResourceSignature() throws Exception { - List rangerPolicyLists = new ArrayList(); - RangerPolicy rangerPolicy = rangerPolicy(); - rangerPolicyLists.add(rangerPolicy); - - String serviceName = "HDFS_1"; - String policySignature = "Repo"; - Boolean isPolicyEnabled = true; - - RangerService rangerService = rangerService(); - List policiesList = new ArrayList(); - XXPolicy policy = new XXPolicy(); - policy.setAddedByUserId(Id); - policy.setCreateTime(new Date()); - policy.setDescription("polcy test"); - policy.setGuid(""); - policy.setId(rangerService.getId()); - policy.setIsAuditEnabled(true); - policy.setName("HDFS_1-1-20150316062453"); - policy.setService(rangerService.getId()); - policiesList.add(policy); - - XXPolicyDao xPolicyDao = Mockito.mock(XXPolicyDao.class); - Mockito.when(daoManager.getXXPolicy()).thenReturn(xPolicyDao); - Mockito.when( - xPolicyDao.findByResourceSignatureByPolicyStatus(serviceName, - policySignature, isPolicyEnabled)).thenReturn( - policiesList); - List policyList = serviceDBStore - .getPoliciesByResourceSignature(serviceName, policySignature, - isPolicyEnabled); - Assert.assertNotNull(policyList); - Mockito.verify(daoManager).getXXPolicy(); - } - - @Test - public void test41updateServiceCryptAlgo() throws Exception { - XXServiceDao xServiceDao = Mockito.mock(XXServiceDao.class); - XXService xService = Mockito.mock(XXService.class); - XXServiceConfigMapDao xServiceConfigMapDao = Mockito - .mock(XXServiceConfigMapDao.class); - XXServiceConfigDefDao xServiceConfigDefDao = Mockito - .mock(XXServiceConfigDefDao.class); - XXUserDao xUserDao = Mockito.mock(XXUserDao.class); - - RangerService rangerService = rangerService(); - rangerService.getConfigs().put(ServiceDBStore.CONFIG_KEY_PASSWORD, "*****"); - - Mockito.when(daoManager.getXXService()).thenReturn(xServiceDao); - Mockito.when(xServiceDao.getById(Id)).thenReturn(xService); - - Mockito.when(daoManager.getXXService()).thenReturn(xServiceDao); - - List xServiceConfigDefList = new ArrayList(); - XXServiceConfigDef serviceConfigDefObj = new XXServiceConfigDef(); - serviceConfigDefObj.setId(Id); - xServiceConfigDefList.add(serviceConfigDefObj); - Mockito.when(daoManager.getXXServiceConfigDef()).thenReturn( - xServiceConfigDefDao); - - Mockito.when(svcService.update(rangerService)) - .thenReturn(rangerService); - Mockito.when(daoManager.getXXService()).thenReturn(xServiceDao); - Mockito.when(xServiceDao.getById(Id)).thenReturn(xService); - - // the old pass - List xConfMapList = new ArrayList(); - XXServiceConfigMap xConfMap = new XXServiceConfigMap(); - xConfMap.setAddedByUserId(null); - xConfMap.setConfigkey(ServiceDBStore.CONFIG_KEY_PASSWORD); - //old outdated - xConfMap.setConfigvalue("PBEWithSHA1AndDESede,ENCRYPT_KEY,SALTSALT,4,lXintlvY73rdk3jXvD7CqB5mcSKl0AMhouBbI5m3whrhLdbKddnzxA=="); - xConfMap.setCreateTime(new Date()); - xConfMap.setServiceId(null); - xConfMap.setUpdatedByUserId(null); - xConfMap.setUpdateTime(new Date()); - xConfMapList.add(xConfMap); - - Mockito.when(daoManager.getXXServiceConfigMap()).thenReturn( - xServiceConfigMapDao); - Mockito.when(xServiceConfigMapDao.findByServiceId(Id)).thenReturn( - xConfMapList); - Mockito.when(daoManager.getXXServiceConfigMap()).thenReturn( - xServiceConfigMapDao); - Mockito.when(xServiceConfigMapDao.remove(xConfMap)).thenReturn(true); - - Mockito.when(daoManager.getXXServiceConfigMap()).thenReturn( - xServiceConfigMapDao); - Mockito.when(daoManager.getXXUser()).thenReturn(xUserDao); - - Mockito.when( - rangerAuditFields.populateAuditFields( - Mockito.isA(XXServiceConfigMap.class), - Mockito.isA(XXService.class))).thenReturn(xConfMap); - - Mockito.when(svcService.getPopulatedViewObject(xService)).thenReturn( - rangerService); - - Map options = null; - RangerService dbRangerService = serviceDBStore - .updateService(rangerService, options); - - Assert.assertNotNull(dbRangerService); - Assert.assertEquals(dbRangerService, rangerService); - Assert.assertEquals(dbRangerService.getId(), rangerService.getId()); - Assert.assertEquals(dbRangerService.getName(), rangerService.getName()); - Assert.assertEquals(dbRangerService.getCreatedBy(), - rangerService.getCreatedBy()); - Assert.assertEquals(dbRangerService.getDescription(), - rangerService.getDescription()); - Assert.assertEquals(dbRangerService.getType(), rangerService.getType()); - Assert.assertEquals(dbRangerService.getVersion(), - rangerService.getVersion()); - Mockito.verify(daoManager).getXXUser(); -} + Mockito.verify(daoManager).getXXService(); + } -@Test -public void test41getMetricByTypeusergroup() throws Exception { - VXGroupList vxGroupList = new VXGroupList(); - vxGroupList.setTotalCount(4l); - vxGroupList.setPageSize(1); - String type = "usergroup"; - VXUserList vXUserList = new VXUserList(); - vXUserList.setTotalCount(4l); - Mockito.when(xUserMgr.searchXGroups(Mockito.any(SearchCriteria.class))).thenReturn(vxGroupList); - Mockito.when(xUserMgr.searchXUsers(Mockito.any(SearchCriteria.class))).thenReturn(vXUserList); - serviceDBStore.getMetricByType(ServiceDBStore.METRIC_TYPE.getMetricTypeByName(type)); + @Test + public void test33getServicePoliciesIfUpdated() throws Exception { + XXServiceDao xServiceDao = Mockito.mock(XXServiceDao.class); + XXServiceVersionInfoDao xServiceVersionInfoDao = Mockito.mock(XXServiceVersionInfoDao.class); + + XXService xService = new XXService(); + xService.setAddedByUserId(Id); + xService.setCreateTime(new Date()); + xService.setDescription("Hdfs service"); + xService.setGuid("serviceguid"); + xService.setId(Id); + xService.setIsEnabled(true); + xService.setName("Hdfs"); + xService.setPolicyUpdateTime(new Date()); + xService.setPolicyVersion(1L); + xService.setType(1L); + xService.setUpdatedByUserId(Id); + xService.setUpdateTime(new Date()); + + XXServiceVersionInfo xServiceVersionInfo = new XXServiceVersionInfo(); + + xServiceVersionInfo.setServiceId(Id); + xServiceVersionInfo.setPolicyVersion(1L); + xServiceVersionInfo.setPolicyUpdateTime(new Date()); + xServiceVersionInfo.setTagVersion(1L); + xServiceVersionInfo.setTagUpdateTime(new Date()); + xServiceVersionInfo.setGdsVersion(1L); + xServiceVersionInfo.setGdsUpdateTime(new Date()); + + String serviceName = "HDFS_1"; + Long lastKnownVersion = 1L; + Mockito.when(daoManager.getXXService()).thenReturn(xServiceDao); + Mockito.when(daoManager.getXXServiceVersionInfo()).thenReturn(xServiceVersionInfoDao); + Mockito.when(xServiceDao.findByName(serviceName)).thenReturn(xService); + Mockito.when(xServiceVersionInfoDao.findByServiceName(serviceName)).thenReturn(xServiceVersionInfo); + + ServicePolicies dbServicePolicies = serviceDBStore + .getServicePoliciesIfUpdated(serviceName, lastKnownVersion, true); + Assert.assertNull(dbServicePolicies); + } -} + @Test + public void test34getPolicyFromEventTime() { + XXDataHistDao xDataHistDao = Mockito.mock(XXDataHistDao.class); + XXDataHist xDataHist = Mockito.mock(XXDataHist.class); -@Test -public void test42getMetricByTypeaudits() throws Exception { - String type = "audits"; + String eventTime = "2015-03-16 06:24:54"; + Mockito.when(daoManager.getXXDataHist()).thenReturn(xDataHistDao); + Mockito.when(xDataHistDao.findObjByEventTimeClassTypeAndId(eventTime, 1020, Id)).thenReturn(xDataHist); - Date date = new Date(); - date.setYear(2018); + RangerPolicy dbRangerPolicy = serviceDBStore.getPolicyFromEventTime(eventTime, Id); + Assert.assertNull(dbRangerPolicy); + Mockito.verify(daoManager).getXXDataHist(); + } - Mockito.when(restErrorUtil.parseDate(anyString(), anyString(), Mockito.any(), Mockito.any(), anyString(), anyString())).thenReturn(date); - RangerServiceDefList svcDefList = new RangerServiceDefList(); - svcDefList.setTotalCount(10l); - Mockito.when(serviceDefService.searchRangerServiceDefs(Mockito.any(SearchFilter.class))).thenReturn(svcDefList); + @Test + public void test35getPopulateExistingBaseFields() { + Boolean isFound = serviceDBStore.getPopulateExistingBaseFields(); + Assert.assertFalse(isFound); + } - serviceDBStore.getMetricByType(ServiceDBStore.METRIC_TYPE.getMetricTypeByName(type)); + @Test + public void test36getPaginatedServicePolicies() throws Exception { + String serviceName = "HDFS_1"; + RangerPolicyList policyList = new RangerPolicyList(); + policyList.setPageSize(0); + SearchFilter filter = new SearchFilter(); + filter.setParam(SearchFilter.POLICY_NAME, "policyName"); + filter.setParam(SearchFilter.SERVICE_NAME, "serviceName"); + + Set groupNames = new HashSet() {{ + add(RangerConstants.GROUP_PUBLIC); + }}; + XXGroupGroupDao xXGroupGroupDao = Mockito.mock(XXGroupGroupDao.class); + Mockito.when(daoManager.getXXGroupGroup()).thenReturn(xXGroupGroupDao); + XXGroupDao xxGroupDao = Mockito.mock(XXGroupDao.class); + XXRoleDao xxRoleDao = Mockito.mock(XXRoleDao.class); + VXGroup vxGroup = vxGroup(); + XXGroup xxGroup = new XXGroup(); + xxGroup.setId(vxGroup.getId()); + xxGroup.setName(vxGroup.getName()); + xxGroup.setDescription(vxGroup.getDescription()); + xxGroup.setIsVisible(vxGroup.getIsVisible()); + Mockito.when(daoManager.getXXGroup()).thenReturn(xxGroupDao); + Mockito.when(xxGroupDao.findByGroupName(vxGroup.getName())).thenReturn(xxGroup); + Mockito.when(xXGroupGroupDao.findGroupNamesByGroupName(Mockito.anyString())).thenReturn(groupNames); + List xxRoles = new ArrayList<>(); + Mockito.when(daoManager.getXXGroup()).thenReturn(xxGroupDao); + Mockito.when(daoManager.getXXRole()).thenReturn(xxRoleDao); + Mockito.when(xxRoleDao.findByGroupId(xxGroup.getId())).thenReturn(xxRoles); + + PList dbRangerPolicyList = serviceDBStore.getPaginatedServicePolicies(serviceName, filter); + Assert.assertNotNull(dbRangerPolicyList); + } -} + @Test + public void test37getPaginatedServicePolicies() throws Exception { + SearchFilter filter = new SearchFilter(); + filter.setParam(SearchFilter.POLICY_NAME, "policyName"); + filter.setParam(SearchFilter.SERVICE_NAME, "serviceName"); + RangerService rangerService = rangerService(); -@Test -public void test43getMetricByTypeServices() throws Exception { - String type = "services"; - RangerServiceList svcList = new RangerServiceList(); - svcList.setTotalCount(10l); - Mockito.when(svcService.searchRangerServices(Mockito.any(SearchFilter.class))).thenReturn(svcList); - serviceDBStore.getMetricByType(ServiceDBStore.METRIC_TYPE.getMetricTypeByName(type)); -} + XXService xService = xService(); + XXServiceDao xServiceDao = Mockito.mock(XXServiceDao.class); + Mockito.when(daoManager.getXXService()).thenReturn(xServiceDao); + Mockito.when(xServiceDao.getById(Id)).thenReturn(xService); + + Set groupNames = new HashSet() {{ + add(RangerConstants.GROUP_PUBLIC); + }}; + XXGroupGroupDao xXGroupGroupDao = Mockito.mock(XXGroupGroupDao.class); + Mockito.when(daoManager.getXXGroupGroup()).thenReturn(xXGroupGroupDao); + XXGroupDao xxGroupDao = Mockito.mock(XXGroupDao.class); + XXRoleDao xxRoleDao = Mockito.mock(XXRoleDao.class); + VXGroup vxGroup = vxGroup(); + XXGroup xxGroup = new XXGroup(); + xxGroup.setId(vxGroup.getId()); + xxGroup.setName(vxGroup.getName()); + xxGroup.setDescription(vxGroup.getDescription()); + xxGroup.setIsVisible(vxGroup.getIsVisible()); + Mockito.when(daoManager.getXXGroup()).thenReturn(xxGroupDao); + Mockito.when(xxGroupDao.findByGroupName(vxGroup.getName())).thenReturn(xxGroup); + Mockito.when(xXGroupGroupDao.findGroupNamesByGroupName(Mockito.anyString())).thenReturn(groupNames); + List xxRoles = new ArrayList<>(); + Mockito.when(daoManager.getXXGroup()).thenReturn(xxGroupDao); + Mockito.when(daoManager.getXXRole()).thenReturn(xxRoleDao); + Mockito.when(xxRoleDao.findByGroupId(xxGroup.getId())).thenReturn(xxRoles); -@Test -public void test44getMetricByTypePolicies() throws Exception { - String type = "policies"; - RangerServiceList svcList = new RangerServiceList(); - svcList.setTotalCount(10l); - serviceDBStore.getMetricByType(ServiceDBStore.METRIC_TYPE.getMetricTypeByName(type)); -} + serviceDBStore.getPaginatedServicePolicies(rangerService.getId(), filter); + } -@Test -public void test45getMetricByTypeDatabase() throws Exception { - String type = "database"; - Mockito.when(bizUtil.getDBVersion()).thenReturn("MYSQL"); - serviceDBStore.getMetricByType(ServiceDBStore.METRIC_TYPE.getMetricTypeByName(type)); -} + @Test + public void test38getPolicyVersionList() { + XXDataHistDao xDataHistDao = Mockito.mock(XXDataHistDao.class); + List versionList = new ArrayList<>(); + versionList.add(1); + versionList.add(2); + Mockito.when(daoManager.getXXDataHist()).thenReturn(xDataHistDao); + Mockito.when(xDataHistDao.getVersionListOfObject(Id, 1020)).thenReturn(versionList); + + VXString dbVXString = serviceDBStore.getPolicyVersionList(Id); + Assert.assertNotNull(dbVXString); + Mockito.verify(daoManager).getXXDataHist(); + } -@Test -public void test46getMetricByTypeContextenrichers() throws Exception { - String type = "contextenrichers"; - RangerServiceDefList svcDefList = new RangerServiceDefList(); - svcDefList.setTotalCount(10l); - Mockito.when(serviceDefService.searchRangerServiceDefs(Mockito.any(SearchFilter.class))).thenReturn(svcDefList); - serviceDBStore.getMetricByType(ServiceDBStore.METRIC_TYPE.getMetricTypeByName(type)); -} + @Test + public void test39getPolicyForVersionNumber() { + XXDataHistDao xDataHistDao = Mockito.mock(XXDataHistDao.class); + XXDataHist xDataHist = Mockito.mock(XXDataHist.class); + Mockito.when(daoManager.getXXDataHist()).thenReturn(xDataHistDao); + Mockito.when(xDataHistDao.findObjectByVersionNumber(Id, 1020, 1)) + .thenReturn(xDataHist); + RangerPolicy dbRangerPolicy = serviceDBStore.getPolicyForVersionNumber( + Id, 1); + Assert.assertNull(dbRangerPolicy); + Mockito.verify(daoManager).getXXDataHist(); + } -@Test -public void test47getMetricByTypeDenyconditions() throws Exception { - String type = "denyconditions"; - RangerServiceDefList svcDefList = new RangerServiceDefList(); - svcDefList.setTotalCount(10l); - Mockito.when(serviceDefService.searchRangerServiceDefs(Mockito.any(SearchFilter.class))).thenReturn(svcDefList); - serviceDBStore.getMetricByType(ServiceDBStore.METRIC_TYPE.getMetricTypeByName(type)); -} + @Test + public void test40getPoliciesByResourceSignature() throws Exception { + List rangerPolicyLists = new ArrayList<>(); + RangerPolicy rangerPolicy = rangerPolicy(); + rangerPolicyLists.add(rangerPolicy); + + String serviceName = "HDFS_1"; + String policySignature = "Repo"; + Boolean isPolicyEnabled = true; + + RangerService rangerService = rangerService(); + List policiesList = new ArrayList<>(); + XXPolicy policy = new XXPolicy(); + policy.setAddedByUserId(Id); + policy.setCreateTime(new Date()); + policy.setDescription("polcy test"); + policy.setGuid(""); + policy.setId(rangerService.getId()); + policy.setIsAuditEnabled(true); + policy.setName("HDFS_1-1-20150316062453"); + policy.setService(rangerService.getId()); + policiesList.add(policy); + + XXPolicyDao xPolicyDao = Mockito.mock(XXPolicyDao.class); + Mockito.when(daoManager.getXXPolicy()).thenReturn(xPolicyDao); + Mockito.when(xPolicyDao.findByResourceSignatureByPolicyStatus(serviceName, policySignature, isPolicyEnabled)).thenReturn(policiesList); + List policyList = serviceDBStore.getPoliciesByResourceSignature(serviceName, policySignature, isPolicyEnabled); + Assert.assertNotNull(policyList); + Mockito.verify(daoManager).getXXPolicy(); + } - @Test - public void test48IsServiceAdminUserTrue() { - RangerService rService = rangerService(); - XXServiceConfigMapDao xxServiceConfigMapDao = Mockito.mock(XXServiceConfigMapDao.class); - XXServiceConfigMap svcAdminUserCfg = new XXServiceConfigMap() {{ setConfigkey(CFG_SERVICE_ADMIN_USERS); setConfigvalue(rService.getConfigs().get(CFG_SERVICE_ADMIN_USERS)); }}; - XXServiceConfigMap svcAdminGroupCfg = new XXServiceConfigMap() {{ setConfigkey(CFG_SERVICE_ADMIN_GROUPS); setConfigvalue(rService.getConfigs().get(CFG_SERVICE_ADMIN_GROUPS)); }}; + @Test + public void test41updateServiceCryptAlgo() throws Exception { + XXServiceDao xServiceDao = Mockito.mock(XXServiceDao.class); + XXService xService = Mockito.mock(XXService.class); + XXServiceConfigMapDao xServiceConfigMapDao = Mockito.mock(XXServiceConfigMapDao.class); + XXServiceConfigDefDao xServiceConfigDefDao = Mockito.mock(XXServiceConfigDefDao.class); + XXUserDao xUserDao = Mockito.mock(XXUserDao.class); - Mockito.when(daoManager.getXXServiceConfigMap()).thenReturn(xxServiceConfigMapDao); - Mockito.when(xxServiceConfigMapDao.findByServiceNameAndConfigKey(rService.getName(), CFG_SERVICE_ADMIN_USERS)).thenReturn(svcAdminUserCfg); - Mockito.when(xxServiceConfigMapDao.findByServiceNameAndConfigKey(rService.getName(), CFG_SERVICE_ADMIN_GROUPS)).thenReturn(svcAdminGroupCfg); + RangerService rangerService = rangerService(); + rangerService.getConfigs().put(ServiceDBStore.CONFIG_KEY_PASSWORD, "*****"); + + Mockito.when(daoManager.getXXService()).thenReturn(xServiceDao); + Mockito.when(xServiceDao.getById(Id)).thenReturn(xService); + + Mockito.when(daoManager.getXXService()).thenReturn(xServiceDao); + + List xServiceConfigDefList = new ArrayList<>(); + XXServiceConfigDef serviceConfigDefObj = new XXServiceConfigDef(); + serviceConfigDefObj.setId(Id); + xServiceConfigDefList.add(serviceConfigDefObj); + Mockito.when(daoManager.getXXServiceConfigDef()).thenReturn(xServiceConfigDefDao); + + Mockito.when(svcService.update(rangerService)).thenReturn(rangerService); + Mockito.when(daoManager.getXXService()).thenReturn(xServiceDao); + Mockito.when(xServiceDao.getById(Id)).thenReturn(xService); + + // the old pass + List xConfMapList = new ArrayList<>(); + XXServiceConfigMap xConfMap = new XXServiceConfigMap(); + xConfMap.setAddedByUserId(null); + xConfMap.setConfigkey(ServiceDBStore.CONFIG_KEY_PASSWORD); + //old outdated + xConfMap.setConfigvalue("PBEWithSHA1AndDESede,ENCRYPT_KEY,SALTSALT,4,lXintlvY73rdk3jXvD7CqB5mcSKl0AMhouBbI5m3whrhLdbKddnzxA=="); + xConfMap.setCreateTime(new Date()); + xConfMap.setServiceId(null); + xConfMap.setUpdatedByUserId(null); + xConfMap.setUpdateTime(new Date()); + xConfMapList.add(xConfMap); + + Mockito.when(daoManager.getXXServiceConfigMap()).thenReturn(xServiceConfigMapDao); + Mockito.when(xServiceConfigMapDao.findByServiceId(Id)).thenReturn(xConfMapList); + Mockito.when(daoManager.getXXServiceConfigMap()).thenReturn(xServiceConfigMapDao); + Mockito.when(xServiceConfigMapDao.remove(xConfMap)).thenReturn(true); + + Mockito.when(daoManager.getXXServiceConfigMap()).thenReturn(xServiceConfigMapDao); + Mockito.when(daoManager.getXXUser()).thenReturn(xUserDao); + + Mockito.when(rangerAuditFields.populateAuditFields(Mockito.isA(XXServiceConfigMap.class), Mockito.isA(XXService.class))).thenReturn(xConfMap); + + Mockito.when(svcService.getPopulatedViewObject(xService)).thenReturn(rangerService); + + Map options = null; + RangerService dbRangerService = serviceDBStore.updateService(rangerService, options); + + Assert.assertNotNull(dbRangerService); + Assert.assertEquals(dbRangerService, rangerService); + Assert.assertEquals(dbRangerService.getId(), rangerService.getId()); + Assert.assertEquals(dbRangerService.getName(), rangerService.getName()); + Assert.assertEquals(dbRangerService.getCreatedBy(), rangerService.getCreatedBy()); + Assert.assertEquals(dbRangerService.getDescription(), rangerService.getDescription()); + Assert.assertEquals(dbRangerService.getType(), rangerService.getType()); + Assert.assertEquals(dbRangerService.getVersion(), rangerService.getVersion()); + Mockito.verify(daoManager).getXXUser(); + } - boolean result = serviceDBStore.isServiceAdminUser(rService.getName(), "testServiceAdminUser1"); + @Test + public void test41getMetricByTypeusergroup() throws Exception { + VXGroupList vxGroupList = new VXGroupList(); + vxGroupList.setTotalCount(4L); + vxGroupList.setPageSize(1); + String type = "usergroup"; + VXUserList vXUserList = new VXUserList(); + vXUserList.setTotalCount(4L); + Mockito.when(xUserMgr.searchXGroups(Mockito.any(SearchCriteria.class))).thenReturn(vxGroupList); + Mockito.when(xUserMgr.searchXUsers(Mockito.any(SearchCriteria.class))).thenReturn(vXUserList); + serviceDBStore.getMetricByType(ServiceDBStore.METRIC_TYPE.getMetricTypeByName(type)); + } - Assert.assertTrue(result); - Mockito.verify(daoManager).getXXServiceConfigMap(); - Mockito.verify(xxServiceConfigMapDao).findByServiceNameAndConfigKey(rService.getName(), CFG_SERVICE_ADMIN_USERS); - Mockito.verify(xxServiceConfigMapDao, Mockito.never()).findByServiceNameAndConfigKey(rService.getName(), CFG_SERVICE_ADMIN_GROUPS); - Mockito.clearInvocations(daoManager); - Mockito.clearInvocations(xxServiceConfigMapDao); + @Test + public void test42getMetricByTypeAudits() throws Exception { + String type = "audits"; - result = serviceDBStore.isServiceAdminUser(rService.getName(), "testServiceAdminUser2"); + Date date = new Date(); + date.setYear(2018); - Assert.assertTrue(result); - Mockito.verify(daoManager).getXXServiceConfigMap(); - Mockito.verify(xxServiceConfigMapDao).findByServiceNameAndConfigKey(rService.getName(), CFG_SERVICE_ADMIN_USERS); - Mockito.verify(xxServiceConfigMapDao, Mockito.never()).findByServiceNameAndConfigKey(rService.getName(), CFG_SERVICE_ADMIN_GROUPS); - Mockito.clearInvocations(daoManager); - Mockito.clearInvocations(xxServiceConfigMapDao); + Mockito.when(restErrorUtil.parseDate(anyString(), anyString(), Mockito.any(), Mockito.any(), anyString(), anyString())).thenReturn(date); + RangerServiceDefList svcDefList = new RangerServiceDefList(); + svcDefList.setTotalCount(10L); + Mockito.when(serviceDefService.searchRangerServiceDefs(Mockito.any(SearchFilter.class))).thenReturn(svcDefList); - Mockito.when(serviceDBStore.xUserMgr.getGroupsForUser("testUser1")).thenReturn(new HashSet() {{ add("testServiceAdminGroup1"); }}); + serviceDBStore.getMetricByType(ServiceDBStore.METRIC_TYPE.getMetricTypeByName(type)); + } - result = serviceDBStore.isServiceAdminUser(rService.getName(), "testUser1"); + @Test + public void test43getMetricByTypeServices() throws Exception { + String type = "services"; + RangerServiceList svcList = new RangerServiceList(); + svcList.setTotalCount(10L); + Mockito.when(svcService.searchRangerServices(Mockito.any(SearchFilter.class))).thenReturn(svcList); + serviceDBStore.getMetricByType(ServiceDBStore.METRIC_TYPE.getMetricTypeByName(type)); + } - Assert.assertTrue(result); - Mockito.verify(daoManager).getXXServiceConfigMap(); - Mockito.verify(xxServiceConfigMapDao).findByServiceNameAndConfigKey(rService.getName(), CFG_SERVICE_ADMIN_USERS); - Mockito.verify(xxServiceConfigMapDao).findByServiceNameAndConfigKey(rService.getName(), CFG_SERVICE_ADMIN_GROUPS); - Mockito.clearInvocations(daoManager); - Mockito.clearInvocations(xxServiceConfigMapDao); + @Test + public void test44getMetricByTypePolicies() throws Exception { + String type = "policies"; + RangerServiceList svcList = new RangerServiceList(); + svcList.setTotalCount(10L); + serviceDBStore.getMetricByType(ServiceDBStore.METRIC_TYPE.getMetricTypeByName(type)); + } + + @Test + public void test45getMetricByTypeDatabase() throws Exception { + String type = "database"; + Mockito.when(bizUtil.getDBVersion()).thenReturn("MYSQL"); + serviceDBStore.getMetricByType(ServiceDBStore.METRIC_TYPE.getMetricTypeByName(type)); + } + + @Test + public void test46getMetricByTypeContextEnrichers() throws Exception { + String type = "contextenrichers"; + RangerServiceDefList svcDefList = new RangerServiceDefList(); + svcDefList.setTotalCount(10L); + Mockito.when(serviceDefService.searchRangerServiceDefs(Mockito.any(SearchFilter.class))).thenReturn(svcDefList); + serviceDBStore.getMetricByType(ServiceDBStore.METRIC_TYPE.getMetricTypeByName(type)); + } + + @Test + public void test47getMetricByTypeDenyConditions() throws Exception { + String type = "denyconditions"; + RangerServiceDefList svcDefList = new RangerServiceDefList(); + svcDefList.setTotalCount(10L); + Mockito.when(serviceDefService.searchRangerServiceDefs(Mockito.any(SearchFilter.class))).thenReturn(svcDefList); + serviceDBStore.getMetricByType(ServiceDBStore.METRIC_TYPE.getMetricTypeByName(type)); + } + + @Test + public void test48IsServiceAdminUserTrue() { + RangerService rService = rangerService(); + XXServiceConfigMapDao xxServiceConfigMapDao = Mockito.mock(XXServiceConfigMapDao.class); + XXServiceConfigMap svcAdminUserCfg = new XXServiceConfigMap() {{ + setConfigkey(CFG_SERVICE_ADMIN_USERS); + setConfigvalue(rService.getConfigs().get(CFG_SERVICE_ADMIN_USERS)); + }}; + XXServiceConfigMap svcAdminGroupCfg = new XXServiceConfigMap() {{ + setConfigkey(CFG_SERVICE_ADMIN_GROUPS); + setConfigvalue(rService.getConfigs().get(CFG_SERVICE_ADMIN_GROUPS)); + }}; + + Mockito.when(daoManager.getXXServiceConfigMap()).thenReturn(xxServiceConfigMapDao); + Mockito.when(xxServiceConfigMapDao.findByServiceNameAndConfigKey(rService.getName(), CFG_SERVICE_ADMIN_USERS)).thenReturn(svcAdminUserCfg); + Mockito.when(xxServiceConfigMapDao.findByServiceNameAndConfigKey(rService.getName(), CFG_SERVICE_ADMIN_GROUPS)).thenReturn(svcAdminGroupCfg); + + boolean result = serviceDBStore.isServiceAdminUser(rService.getName(), "testServiceAdminUser1"); + + Assert.assertTrue(result); + Mockito.verify(daoManager).getXXServiceConfigMap(); + Mockito.verify(xxServiceConfigMapDao).findByServiceNameAndConfigKey(rService.getName(), CFG_SERVICE_ADMIN_USERS); + Mockito.verify(xxServiceConfigMapDao, Mockito.never()).findByServiceNameAndConfigKey(rService.getName(), CFG_SERVICE_ADMIN_GROUPS); + Mockito.clearInvocations(daoManager); + Mockito.clearInvocations(xxServiceConfigMapDao); + + result = serviceDBStore.isServiceAdminUser(rService.getName(), "testServiceAdminUser2"); + + Assert.assertTrue(result); + Mockito.verify(daoManager).getXXServiceConfigMap(); + Mockito.verify(xxServiceConfigMapDao).findByServiceNameAndConfigKey(rService.getName(), CFG_SERVICE_ADMIN_USERS); + Mockito.verify(xxServiceConfigMapDao, Mockito.never()).findByServiceNameAndConfigKey(rService.getName(), CFG_SERVICE_ADMIN_GROUPS); + Mockito.clearInvocations(daoManager); + Mockito.clearInvocations(xxServiceConfigMapDao); + + Mockito.when(serviceDBStore.xUserMgr.getGroupsForUser("testUser1")).thenReturn(new HashSet() {{ + add("testServiceAdminGroup1"); + }}); + + result = serviceDBStore.isServiceAdminUser(rService.getName(), "testUser1"); + + Assert.assertTrue(result); + Mockito.verify(daoManager).getXXServiceConfigMap(); + Mockito.verify(xxServiceConfigMapDao).findByServiceNameAndConfigKey(rService.getName(), CFG_SERVICE_ADMIN_USERS); + Mockito.verify(xxServiceConfigMapDao).findByServiceNameAndConfigKey(rService.getName(), CFG_SERVICE_ADMIN_GROUPS); + Mockito.clearInvocations(daoManager); + Mockito.clearInvocations(xxServiceConfigMapDao); + + Mockito.when(serviceDBStore.xUserMgr.getGroupsForUser("testUser2")).thenReturn(new HashSet() {{ + add("testServiceAdminGroup2"); + }}); + + result = serviceDBStore.isServiceAdminUser(rService.getName(), "testUser2"); + + Assert.assertTrue(result); + Mockito.verify(daoManager).getXXServiceConfigMap(); + Mockito.verify(xxServiceConfigMapDao).findByServiceNameAndConfigKey(rService.getName(), CFG_SERVICE_ADMIN_USERS); + Mockito.verify(xxServiceConfigMapDao).findByServiceNameAndConfigKey(rService.getName(), CFG_SERVICE_ADMIN_GROUPS); + Mockito.clearInvocations(daoManager); + Mockito.clearInvocations(xxServiceConfigMapDao); + } + + @Test + public void test49IsServiceAdminUserFalse() throws Exception { + String configName = CFG_SERVICE_ADMIN_USERS; + boolean result = false; + RangerService rService = rangerService(); + XXServiceConfigMapDao xxServiceConfigMapDao = Mockito.mock(XXServiceConfigMapDao.class); + XXServiceConfigMap xxServiceConfigMap = new XXServiceConfigMap(); + xxServiceConfigMap.setConfigkey(configName); + xxServiceConfigMap.setConfigvalue(rService.getConfigs().get(configName)); + + Mockito.when(daoManager.getXXServiceConfigMap()).thenReturn(xxServiceConfigMapDao); + Mockito.when(xxServiceConfigMapDao.findByServiceNameAndConfigKey(rService.getName(), configName)).thenReturn(xxServiceConfigMap); + + result = serviceDBStore.isServiceAdminUser(rService.getName(), "testServiceAdminUser3"); + + Assert.assertFalse(result); + Mockito.verify(daoManager).getXXServiceConfigMap(); + Mockito.verify(xxServiceConfigMapDao).findByServiceNameAndConfigKey(rService.getName(), configName); + } + + @Test + public void test41createKMSService() throws Exception { + XXServiceDao xServiceDao = Mockito.mock(XXServiceDao.class); + XXServiceConfigMapDao xServiceConfigMapDao = Mockito.mock(XXServiceConfigMapDao.class); + XXUserDao xUserDao = Mockito.mock(XXUserDao.class); + XXServiceConfigDefDao xServiceConfigDefDao = Mockito.mock(XXServiceConfigDefDao.class); + XXService xService = Mockito.mock(XXService.class); + XXUser xUser = Mockito.mock(XXUser.class); + + Mockito.when(xServiceDao.findByName("KMS_1")).thenReturn(xService); + Mockito.when(!bizUtil.hasAccess(xService, null)).thenReturn(true); + + RangerService rangerService = rangerKMSService(); + VXUser vXUser = null; + String userName = "servicemgr"; + + List svcConfDefList = new ArrayList<>(); + XXServiceConfigDef serviceConfigDefObj = new XXServiceConfigDef(); + serviceConfigDefObj.setId(Id); + serviceConfigDefObj.setType("7"); + svcConfDefList.add(serviceConfigDefObj); + + Mockito.when(daoManager.getXXServiceConfigDef()).thenReturn(xServiceConfigDefDao); + Mockito.when(svcService.create(rangerService)).thenReturn(rangerService); + Mockito.when(daoManager.getXXService()).thenReturn(xServiceDao); + Mockito.when(xServiceDao.getById(rangerService.getId())).thenReturn(xService); + Mockito.when(daoManager.getXXServiceConfigMap()).thenReturn(xServiceConfigMapDao); + Mockito.when(stringUtil.getValidUserName(userName)).thenReturn(userName); + Mockito.when(daoManager.getXXUser()).thenReturn(xUserDao); + Mockito.when(xUserDao.findByUserName(userName)).thenReturn(xUser); + + Mockito.when(xUserService.populateViewBean(xUser)).thenReturn(vXUser); + VXUser vXUserHdfs = new VXUser(); + vXUserHdfs.setName("hdfs"); + vXUserHdfs.setPassword("hdfs"); + VXUser vXUserHive = new VXUser(); + vXUserHive.setName("hive"); + vXUserHive.setPassword("hive"); + + XXServiceConfigMap xConfMap = new XXServiceConfigMap(); + + Mockito.when(svcService.getPopulatedViewObject(xService)).thenReturn(rangerService); + + Mockito.when(rangerAuditFields.populateAuditFields(Mockito.isA(XXServiceConfigMap.class), Mockito.isA(XXService.class))).thenReturn(xConfMap); + + List accessTypeDefList = new ArrayList<>(); + accessTypeDefList.add(rangerKmsAccessTypes("getmetadata", 7)); + accessTypeDefList.add(rangerKmsAccessTypes("generateeek", 8)); + accessTypeDefList.add(rangerKmsAccessTypes("decrypteek", 9)); + + RangerServiceDef ran = new RangerServiceDef(); + ran.setName("KMS Test"); + + ServiceDBStore spy = Mockito.spy(serviceDBStore); + + Mockito.when(spy.getServiceByName("KMS_1")).thenReturn(rangerService); + Mockito.doNothing().when(spy).createDefaultPolicies(rangerService); + + RangerResourceDef resourceDef = new RangerResourceDef(); + resourceDef.setItemId(Id); + resourceDef.setName("keyname"); + resourceDef.setType("string"); + resourceDef.setType("string"); + resourceDef.setLabel("Key Name"); + resourceDef.setDescription("Key Name"); + + List resourceHierarchy = new ArrayList<>(); + resourceHierarchy.addAll(resourceHierarchy); + + spy.createService(rangerService); + vXUser = new VXUser(); + vXUser.setName(userName); + vXUser.setPassword(userName); + + spy.createDefaultPolicies(rangerService); + + Mockito.verify(daoManager, Mockito.atLeast(1)).getXXService(); + Mockito.verify(daoManager).getXXServiceConfigMap(); + } + + @Test + public void test50hasServiceConfigForPluginChanged() throws Exception { + String pluginConfigKey = "ranger.plugin.testconfig"; + String otherConfigKey = "ranger.other.testconfig"; + Map serviceConfigs = rangerService().getConfigs(); + List xConfMapList = new ArrayList<>(); + for (String key : serviceConfigs.keySet()) { + XXServiceConfigMap xConfMap = new XXServiceConfigMap(); + xConfMap.setConfigkey(key); + xConfMap.setConfigvalue(serviceConfigs.get(key)); + xConfMap.setServiceId(Id); + xConfMapList.add(xConfMap); + } + + Map validConfig = new HashMap<>(); + validConfig.putAll(serviceConfigs); + Assert.assertFalse(serviceDBStore.hasServiceConfigForPluginChanged(null, null)); + Assert.assertFalse(serviceDBStore.hasServiceConfigForPluginChanged(xConfMapList, validConfig)); + + validConfig.put(pluginConfigKey, "test value added"); + Assert.assertTrue(serviceDBStore.hasServiceConfigForPluginChanged(xConfMapList, validConfig)); + + XXServiceConfigMap xConfMap = new XXServiceConfigMap(); + xConfMap.setConfigkey(pluginConfigKey); + xConfMap.setConfigvalue("test value added"); + xConfMap.setServiceId(Id); + xConfMapList.add(xConfMap); + Assert.assertFalse(serviceDBStore.hasServiceConfigForPluginChanged(xConfMapList, validConfig)); + + validConfig.put(pluginConfigKey, "test value changed"); + Assert.assertTrue(serviceDBStore.hasServiceConfigForPluginChanged(xConfMapList, validConfig)); + + validConfig.remove(pluginConfigKey); + Assert.assertTrue(serviceDBStore.hasServiceConfigForPluginChanged(xConfMapList, validConfig)); + int index = xConfMapList.size(); + xConfMap = xConfMapList.remove(index - 1); + Assert.assertFalse(serviceDBStore.hasServiceConfigForPluginChanged(xConfMapList, validConfig)); + + validConfig.put(otherConfigKey, "other test value added"); + Assert.assertFalse(serviceDBStore.hasServiceConfigForPluginChanged(xConfMapList, validConfig)); + + xConfMap = new XXServiceConfigMap(); + xConfMap.setConfigkey(otherConfigKey); + xConfMap.setConfigvalue("other test value added"); + xConfMap.setServiceId(Id); + xConfMapList.add(xConfMap); + Assert.assertFalse(serviceDBStore.hasServiceConfigForPluginChanged(xConfMapList, validConfig)); + + validConfig.put(otherConfigKey, "other test value changed"); + Assert.assertFalse(serviceDBStore.hasServiceConfigForPluginChanged(xConfMapList, validConfig)); + + validConfig.remove(otherConfigKey); + Assert.assertFalse(serviceDBStore.hasServiceConfigForPluginChanged(xConfMapList, validConfig)); + + index = xConfMapList.size(); + xConfMap = xConfMapList.remove(index - 1); + Assert.assertFalse(serviceDBStore.hasServiceConfigForPluginChanged(xConfMapList, validConfig)); + } - Mockito.when(serviceDBStore.xUserMgr.getGroupsForUser("testUser2")).thenReturn(new HashSet() {{ add("testServiceAdminGroup2"); }}); + @Test + public void test51GetPolicyByGUID() throws Exception { + XXPolicyDao xPolicyDao = Mockito.mock(XXPolicyDao.class); + XXPolicy xPolicy = Mockito.mock(XXPolicy.class); + RangerPolicy rangerPolicy = rangerPolicy(); + Mockito.when(daoManager.getXXPolicy()).thenReturn(xPolicyDao); + Mockito.when(xPolicyDao.findPolicyByGUIDAndServiceNameAndZoneName(rangerPolicy.getGuid(), null, null)).thenReturn(xPolicy); + Mockito.when(policyService.getPopulatedViewObject(xPolicy)).thenReturn(rangerPolicy); + RangerPolicy dbRangerPolicy = serviceDBStore.getPolicy(rangerPolicy.getGuid(), null, null); + Assert.assertNotNull(dbRangerPolicy); + Assert.assertEquals(Id, dbRangerPolicy.getId()); + Mockito.verify(xPolicyDao).findPolicyByGUIDAndServiceNameAndZoneName(rangerPolicy.getGuid(), null, null); + Mockito.verify(policyService).getPopulatedViewObject(xPolicy); + } - result = serviceDBStore.isServiceAdminUser(rService.getName(), "testUser2"); + @Test + public void test52GetPolicyByGUIDAndServiceName() throws Exception { + XXPolicyDao xPolicyDao = Mockito.mock(XXPolicyDao.class); + XXPolicy xPolicy = Mockito.mock(XXPolicy.class); + RangerPolicy rangerPolicy = rangerPolicy(); + RangerService rangerService = rangerService(); + String serviceName = rangerService.getName(); + Mockito.when(daoManager.getXXPolicy()).thenReturn(xPolicyDao); + Mockito.when(xPolicyDao.findPolicyByGUIDAndServiceNameAndZoneName(rangerPolicy.getGuid(), serviceName, null)).thenReturn(xPolicy); + Mockito.when(policyService.getPopulatedViewObject(xPolicy)).thenReturn(rangerPolicy); + RangerPolicy dbRangerPolicy = serviceDBStore.getPolicy(rangerPolicy.getGuid(), serviceName, null); + Assert.assertNotNull(dbRangerPolicy); + Assert.assertEquals(Id, dbRangerPolicy.getId()); + Mockito.verify(xPolicyDao).findPolicyByGUIDAndServiceNameAndZoneName(rangerPolicy.getGuid(), serviceName, null); + Mockito.verify(policyService).getPopulatedViewObject(xPolicy); + } - Assert.assertTrue(result); - Mockito.verify(daoManager).getXXServiceConfigMap(); - Mockito.verify(xxServiceConfigMapDao).findByServiceNameAndConfigKey(rService.getName(), CFG_SERVICE_ADMIN_USERS); - Mockito.verify(xxServiceConfigMapDao).findByServiceNameAndConfigKey(rService.getName(), CFG_SERVICE_ADMIN_GROUPS); - Mockito.clearInvocations(daoManager); - Mockito.clearInvocations(xxServiceConfigMapDao); - } + @Test + public void test53GetPolicyByGUIDAndServiceNameAndZoneName() throws Exception { + XXPolicyDao xPolicyDao = Mockito.mock(XXPolicyDao.class); + XXPolicy xPolicy = Mockito.mock(XXPolicy.class); + RangerPolicy rangerPolicy = rangerPolicy(); + RangerService rangerService = rangerService(); + String serviceName = rangerService.getName(); + String zoneName = "zone-1"; + Mockito.when(daoManager.getXXPolicy()).thenReturn(xPolicyDao); + Mockito.when(xPolicyDao.findPolicyByGUIDAndServiceNameAndZoneName(rangerPolicy.getGuid(), serviceName, zoneName)).thenReturn(xPolicy); + Mockito.when(policyService.getPopulatedViewObject(xPolicy)).thenReturn(rangerPolicy); + RangerPolicy dbRangerPolicy = serviceDBStore.getPolicy(rangerPolicy.getGuid(), serviceName, zoneName); + Assert.assertNotNull(dbRangerPolicy); + Assert.assertEquals(Id, dbRangerPolicy.getId()); + Mockito.verify(xPolicyDao).findPolicyByGUIDAndServiceNameAndZoneName(rangerPolicy.getGuid(), serviceName, zoneName); + Mockito.verify(policyService).getPopulatedViewObject(xPolicy); + } @Test - public void test49IsServiceAdminUserFalse() throws Exception{ - String configName = CFG_SERVICE_ADMIN_USERS; - boolean result=false; - RangerService rService= rangerService(); - XXServiceConfigMapDao xxServiceConfigMapDao = Mockito.mock(XXServiceConfigMapDao.class); - XXServiceConfigMap xxServiceConfigMap = new XXServiceConfigMap(); - xxServiceConfigMap.setConfigkey(configName); - xxServiceConfigMap.setConfigvalue(rService.getConfigs().get(configName)); - - Mockito.when(daoManager.getXXServiceConfigMap()).thenReturn(xxServiceConfigMapDao); - Mockito.when(xxServiceConfigMapDao.findByServiceNameAndConfigKey(rService.getName(), configName)).thenReturn(xxServiceConfigMap); - - result = serviceDBStore.isServiceAdminUser(rService.getName(),"testServiceAdminUser3"); - - Assert.assertFalse(result); - Mockito.verify(daoManager).getXXServiceConfigMap(); - Mockito.verify(xxServiceConfigMapDao).findByServiceNameAndConfigKey(rService.getName(), configName); + public void test53GetPolicyByGUIDAndZoneName() throws Exception { + XXPolicyDao xPolicyDao = Mockito.mock(XXPolicyDao.class); + XXPolicy xPolicy = Mockito.mock(XXPolicy.class); + RangerPolicy rangerPolicy = rangerPolicy(); + String zoneName = "zone-1"; + Mockito.when(daoManager.getXXPolicy()).thenReturn(xPolicyDao); + Mockito.when(xPolicyDao.findPolicyByGUIDAndServiceNameAndZoneName(rangerPolicy.getGuid(), null, zoneName)).thenReturn(xPolicy); + Mockito.when(policyService.getPopulatedViewObject(xPolicy)).thenReturn(rangerPolicy); + RangerPolicy dbRangerPolicy = serviceDBStore.getPolicy(rangerPolicy.getGuid(), null, zoneName); + Assert.assertNotNull(dbRangerPolicy); + Assert.assertEquals(Id, dbRangerPolicy.getId()); + Mockito.verify(xPolicyDao).findPolicyByGUIDAndServiceNameAndZoneName(rangerPolicy.getGuid(), null, zoneName); + Mockito.verify(policyService).getPopulatedViewObject(xPolicy); + } + + private VXGroup vxGroup() { + VXGroup vXGroup = new VXGroup(); + vXGroup.setId(Id); + vXGroup.setDescription("group test working"); + vXGroup.setName(RangerConstants.GROUP_PUBLIC); + vXGroup.setIsVisible(1); + return vXGroup; + } + + private XXAccessTypeDef rangerKmsAccessTypes(String accessTypeName, int itemId) { + XXAccessTypeDef accessTypeDefObj = new XXAccessTypeDef(); + accessTypeDefObj.setAddedByUserId(Id); + accessTypeDefObj.setCreateTime(new Date()); + accessTypeDefObj.setDefid(Long.valueOf(itemId)); + accessTypeDefObj.setId(Long.valueOf(itemId)); + accessTypeDefObj.setItemId(Long.valueOf(itemId)); + accessTypeDefObj.setLabel(accessTypeName); + accessTypeDefObj.setName(accessTypeName); + accessTypeDefObj.setOrder(null); + accessTypeDefObj.setRbkeylabel(null); + accessTypeDefObj.setUpdatedByUserId(Id); + accessTypeDefObj.setUpdateTime(new Date()); + return accessTypeDefObj; + } + + private RangerServiceDef rangerServiceDef() { + List configs = new ArrayList<>(); + RangerServiceConfigDef serviceConfigDefObj = new RangerServiceConfigDef(); + serviceConfigDefObj.setDefaultValue("xyz"); + serviceConfigDefObj.setDescription("ServiceDef"); + serviceConfigDefObj.setItemId(Id); + serviceConfigDefObj.setLabel("Username"); + serviceConfigDefObj.setMandatory(true); + serviceConfigDefObj.setName("username"); + serviceConfigDefObj.setRbKeyDescription(null); + serviceConfigDefObj.setRbKeyLabel(null); + serviceConfigDefObj.setRbKeyValidationMessage(null); + serviceConfigDefObj.setSubType(null); + configs.add(serviceConfigDefObj); + List resources = new ArrayList<>(); + List accessTypes = new ArrayList<>(); + List policyConditions = new ArrayList<>(); + List contextEnrichers = new ArrayList<>(); + List enums = new ArrayList<>(); + + RangerServiceDef rangerServiceDef = new RangerServiceDef(); + rangerServiceDef.setId(Id); + rangerServiceDef.setName("RangerServiceHdfs"); + rangerServiceDef.setImplClass("RangerServiceHdfs"); + rangerServiceDef.setLabel("HDFS Repository"); + rangerServiceDef.setDescription("HDFS Repository"); + rangerServiceDef.setRbKeyDescription(null); + rangerServiceDef.setUpdatedBy("Admin"); + rangerServiceDef.setUpdateTime(new Date()); + rangerServiceDef.setConfigs(configs); + rangerServiceDef.setResources(resources); + rangerServiceDef.setAccessTypes(accessTypes); + rangerServiceDef.setPolicyConditions(policyConditions); + rangerServiceDef.setContextEnrichers(contextEnrichers); + rangerServiceDef.setEnums(enums); + + return rangerServiceDef; + } + + private RangerService rangerService() { + Map configs = new HashMap<>(); + configs.put("username", "servicemgr"); + configs.put("password", "servicemgr"); + configs.put("namenode", "servicemgr"); + configs.put("hadoop.security.authorization", "No"); + configs.put("hadoop.security.authentication", "Simple"); + configs.put("hadoop.security.auth_to_local", ""); + configs.put("dfs.datanode.kerberos.principal", ""); + configs.put("dfs.namenode.kerberos.principal", ""); + configs.put("dfs.secondary.namenode.kerberos.principal", ""); + configs.put("hadoop.rpc.protection", "Privacy"); + configs.put("commonNameForCertificate", ""); + configs.put("service.admin.users", "testServiceAdminUser1,testServiceAdminUser2"); + configs.put("service.admin.groups", "testServiceAdminGroup1,testServiceAdminGroup2"); + + RangerService rangerService = new RangerService(); + rangerService.setId(Id); + rangerService.setConfigs(configs); + rangerService.setCreateTime(new Date()); + rangerService.setDescription("service policy"); + rangerService.setGuid("1427365526516_835_0"); + rangerService.setIsEnabled(true); + rangerService.setName("HDFS_1"); + rangerService.setPolicyUpdateTime(new Date()); + rangerService.setType("1"); + rangerService.setUpdatedBy("Admin"); + rangerService.setUpdateTime(new Date()); + + return rangerService; + } + + private RangerService rangerKMSService() { + Map configs = new HashMap(); + configs.put("username", "servicemgr"); + configs.put("password", "servicemgr"); + configs.put("provider", "kmsurl"); + + RangerService rangerService = new RangerService(); + rangerService.setId(Id); + rangerService.setConfigs(configs); + rangerService.setCreateTime(new Date()); + rangerService.setDescription("service kms policy"); + rangerService.setGuid("1427365526516_835_1"); + rangerService.setIsEnabled(true); + rangerService.setName("KMS_1"); + rangerService.setPolicyUpdateTime(new Date()); + rangerService.setType("7"); + rangerService.setUpdatedBy("Admin"); + rangerService.setUpdateTime(new Date()); + + return rangerService; + } + + private RangerPolicy rangerPolicy() { + List accesses = new ArrayList<>(); + List users = new ArrayList<>(); + List groups = new ArrayList<>(); + List policyLabels = new ArrayList<>(); + List conditions = new ArrayList<>(); + List policyItems = new ArrayList<>(); + RangerPolicyItem rangerPolicyItem = new RangerPolicyItem(); + rangerPolicyItem.setAccesses(accesses); + rangerPolicyItem.setConditions(conditions); + rangerPolicyItem.setGroups(groups); + rangerPolicyItem.setUsers(users); + rangerPolicyItem.setDelegateAdmin(false); + + policyItems.add(rangerPolicyItem); + + Map policyResource = new HashMap<>(); + RangerPolicyResource rangerPolicyResource = new RangerPolicyResource(); + rangerPolicyResource.setIsExcludes(true); + rangerPolicyResource.setIsRecursive(true); + rangerPolicyResource.setValue("1"); + rangerPolicyResource.setValues(users); + RangerPolicy policy = new RangerPolicy(); + policy.setId(Id); + policy.setCreateTime(new Date()); + policy.setDescription("policy"); + policy.setGuid("policyguid"); + policy.setIsEnabled(true); + policy.setName("HDFS_1-1-20150316062453"); + policy.setUpdatedBy("Admin"); + policy.setUpdateTime(new Date()); + policy.setService("HDFS_1-1-20150316062453"); + policy.setIsAuditEnabled(true); + policy.setPolicyItems(policyItems); + policy.setResources(policyResource); + policy.setPolicyLabels(policyLabels); + + return policy; + } + + private XXServiceDef serviceDef() { + XXServiceDef xServiceDef = new XXServiceDef(); + xServiceDef.setAddedByUserId(Id); + xServiceDef.setCreateTime(new Date()); + xServiceDef.setDescription("HDFS Repository"); + xServiceDef.setGuid("1427365526516_835_0"); + xServiceDef.setId(Id); + xServiceDef.setUpdateTime(new Date()); + xServiceDef.setUpdatedByUserId(Id); + xServiceDef.setImplclassname("RangerServiceHdfs"); + xServiceDef.setLabel("HDFS Repository"); + xServiceDef.setRbkeylabel(null); + xServiceDef.setRbkeydescription(null); + xServiceDef.setIsEnabled(true); + + return xServiceDef; + } + + private XXService xService() { + XXService xService = new XXService(); + xService.setAddedByUserId(Id); + xService.setCreateTime(new Date()); + xService.setDescription("Hdfs service"); + xService.setGuid("serviceguid"); + xService.setId(Id); + xService.setIsEnabled(true); + xService.setName("Hdfs"); + xService.setPolicyUpdateTime(new Date()); + xService.setPolicyVersion(1L); + xService.setType(1L); + xService.setUpdatedByUserId(Id); + xService.setUpdateTime(new Date()); + + return xService; } - - @Test - public void test41createKMSService() throws Exception { - XXServiceDao xServiceDao = Mockito.mock(XXServiceDao.class); - XXServiceConfigMapDao xServiceConfigMapDao = Mockito - .mock(XXServiceConfigMapDao.class); - XXUserDao xUserDao = Mockito.mock(XXUserDao.class); - XXServiceConfigDefDao xServiceConfigDefDao = Mockito - .mock(XXServiceConfigDefDao.class); - XXService xService = Mockito.mock(XXService.class); - XXUser xUser = Mockito.mock(XXUser.class); - - Mockito.when(xServiceDao.findByName("KMS_1")).thenReturn( - xService); - Mockito.when(!bizUtil.hasAccess(xService, null)).thenReturn(true); - - RangerService rangerService = rangerKMSService(); - VXUser vXUser = null; - String userName = "servicemgr"; - - List svcConfDefList = new ArrayList(); - XXServiceConfigDef serviceConfigDefObj = new XXServiceConfigDef(); - serviceConfigDefObj.setId(Id); - serviceConfigDefObj.setType("7"); - svcConfDefList.add(serviceConfigDefObj); - Mockito.when(daoManager.getXXServiceConfigDef()).thenReturn( - xServiceConfigDefDao); - - Mockito.when(svcService.create(rangerService)).thenReturn(rangerService); - - Mockito.when(daoManager.getXXService()).thenReturn(xServiceDao); - Mockito.when(xServiceDao.getById(rangerService.getId())).thenReturn( - xService); - Mockito.when(daoManager.getXXServiceConfigMap()).thenReturn( - xServiceConfigMapDao); - - Mockito.when(stringUtil.getValidUserName(userName)) - .thenReturn(userName); - Mockito.when(daoManager.getXXUser()).thenReturn(xUserDao); - Mockito.when(xUserDao.findByUserName(userName)).thenReturn(xUser); - - Mockito.when(xUserService.populateViewBean(xUser)).thenReturn(vXUser); - VXUser vXUserHdfs = new VXUser(); - vXUserHdfs.setName("hdfs"); - vXUserHdfs.setPassword("hdfs"); - VXUser vXUserHive = new VXUser(); - vXUserHive.setName("hive"); - vXUserHive.setPassword("hive"); - - XXServiceConfigMap xConfMap = new XXServiceConfigMap(); - - Mockito.when(svcService.getPopulatedViewObject(xService)).thenReturn( - rangerService); - - Mockito.when( - rangerAuditFields.populateAuditFields( - Mockito.isA(XXServiceConfigMap.class), - Mockito.isA(XXService.class))).thenReturn(xConfMap); - - List accessTypeDefList = new ArrayList(); - accessTypeDefList.add(rangerKmsAccessTypes("getmetadata", 7)); - accessTypeDefList.add(rangerKmsAccessTypes("generateeek", 8)); - accessTypeDefList.add(rangerKmsAccessTypes("decrypteek", 9)); - - RangerServiceDef ran = new RangerServiceDef(); - ran.setName("KMS Test"); - - ServiceDBStore spy = Mockito.spy(serviceDBStore); - - Mockito.when(spy.getServiceByName("KMS_1")).thenReturn( - rangerService); - Mockito.doNothing().when(spy).createDefaultPolicies(rangerService); - - RangerResourceDef resourceDef = new RangerResourceDef(); - resourceDef.setItemId(Id); - resourceDef.setName("keyname"); - resourceDef.setType("string"); - resourceDef.setType("string"); - resourceDef.setLabel("Key Name"); - resourceDef.setDescription("Key Name"); - - List resourceHierarchy = new ArrayList(); - resourceHierarchy.addAll(resourceHierarchy); - - spy.createService(rangerService); - vXUser = new VXUser(); - vXUser.setName(userName); - vXUser.setPassword(userName); - - spy.createDefaultPolicies(rangerService); - - Mockito.verify(daoManager, Mockito.atLeast(1)).getXXService(); - Mockito.verify(daoManager).getXXServiceConfigMap(); - } - - @Test - public void test50hasServiceConfigForPluginChanged() throws Exception { - String pluginConfigKey = "ranger.plugin.testconfig"; - String otherConfigKey = "ranger.other.testconfig"; - Map serviceConfigs = rangerService().getConfigs(); - List xConfMapList = new ArrayList(); - for (String key : serviceConfigs.keySet()) { - XXServiceConfigMap xConfMap = new XXServiceConfigMap(); - xConfMap.setConfigkey(key); - xConfMap.setConfigvalue(serviceConfigs.get(key)); - xConfMap.setServiceId(Id); - xConfMapList.add(xConfMap); - } - - Map validConfig = new HashMap(); - validConfig.putAll(serviceConfigs); - Assert.assertFalse(serviceDBStore.hasServiceConfigForPluginChanged(null, null)); - Assert.assertFalse(serviceDBStore.hasServiceConfigForPluginChanged(xConfMapList, validConfig)); - - validConfig.put(pluginConfigKey, "test value added"); - Assert.assertTrue(serviceDBStore.hasServiceConfigForPluginChanged(xConfMapList, validConfig)); - - XXServiceConfigMap xConfMap = new XXServiceConfigMap(); - xConfMap.setConfigkey(pluginConfigKey); - xConfMap.setConfigvalue("test value added"); - xConfMap.setServiceId(Id); - xConfMapList.add(xConfMap); - Assert.assertFalse(serviceDBStore.hasServiceConfigForPluginChanged(xConfMapList, validConfig)); - - validConfig.put(pluginConfigKey, "test value changed"); - Assert.assertTrue(serviceDBStore.hasServiceConfigForPluginChanged(xConfMapList, validConfig)); - - validConfig.remove(pluginConfigKey); - Assert.assertTrue(serviceDBStore.hasServiceConfigForPluginChanged(xConfMapList, validConfig)); - int index = xConfMapList.size(); - xConfMap = xConfMapList.remove(index - 1); - Assert.assertFalse(serviceDBStore.hasServiceConfigForPluginChanged(xConfMapList, validConfig)); - - validConfig.put(otherConfigKey, "other test value added"); - Assert.assertFalse(serviceDBStore.hasServiceConfigForPluginChanged(xConfMapList, validConfig)); - - xConfMap = new XXServiceConfigMap(); - xConfMap.setConfigkey(otherConfigKey); - xConfMap.setConfigvalue("other test value added"); - xConfMap.setServiceId(Id); - xConfMapList.add(xConfMap); - Assert.assertFalse(serviceDBStore.hasServiceConfigForPluginChanged(xConfMapList, validConfig)); - - validConfig.put(otherConfigKey, "other test value changed"); - Assert.assertFalse(serviceDBStore.hasServiceConfigForPluginChanged(xConfMapList, validConfig)); - - validConfig.remove(otherConfigKey); - Assert.assertFalse(serviceDBStore.hasServiceConfigForPluginChanged(xConfMapList, validConfig)); - - index = xConfMapList.size(); - xConfMap = xConfMapList.remove(index - 1); - Assert.assertFalse(serviceDBStore.hasServiceConfigForPluginChanged(xConfMapList, validConfig)); - } - - @Test - public void test51GetPolicyByGUID() throws Exception { - XXPolicyDao xPolicyDao = Mockito.mock(XXPolicyDao.class); - XXPolicy xPolicy = Mockito.mock(XXPolicy.class); - RangerPolicy rangerPolicy = rangerPolicy(); - Mockito.when(daoManager.getXXPolicy()).thenReturn(xPolicyDao); - Mockito.when(xPolicyDao.findPolicyByGUIDAndServiceNameAndZoneName(rangerPolicy.getGuid(), null, null)).thenReturn(xPolicy); - Mockito.when(policyService.getPopulatedViewObject(xPolicy)).thenReturn(rangerPolicy); - RangerPolicy dbRangerPolicy = serviceDBStore.getPolicy(rangerPolicy.getGuid(), null, null); - Assert.assertNotNull(dbRangerPolicy); - Assert.assertEquals(Id, dbRangerPolicy.getId()); - Mockito.verify(xPolicyDao).findPolicyByGUIDAndServiceNameAndZoneName(rangerPolicy.getGuid(), null, null); - Mockito.verify(policyService).getPopulatedViewObject(xPolicy); - } - - @Test - public void test52GetPolicyByGUIDAndServiceName() throws Exception { - XXPolicyDao xPolicyDao = Mockito.mock(XXPolicyDao.class); - XXPolicy xPolicy = Mockito.mock(XXPolicy.class); - RangerPolicy rangerPolicy = rangerPolicy(); - RangerService rangerService = rangerService(); - String serviceName = rangerService.getName(); - Mockito.when(daoManager.getXXPolicy()).thenReturn(xPolicyDao); - Mockito.when(xPolicyDao.findPolicyByGUIDAndServiceNameAndZoneName(rangerPolicy.getGuid(), serviceName, null)).thenReturn(xPolicy); - Mockito.when(policyService.getPopulatedViewObject(xPolicy)).thenReturn(rangerPolicy); - RangerPolicy dbRangerPolicy = serviceDBStore.getPolicy(rangerPolicy.getGuid(), serviceName, null); - Assert.assertNotNull(dbRangerPolicy); - Assert.assertEquals(Id, dbRangerPolicy.getId()); - Mockito.verify(xPolicyDao).findPolicyByGUIDAndServiceNameAndZoneName(rangerPolicy.getGuid(), serviceName, null); - Mockito.verify(policyService).getPopulatedViewObject(xPolicy); - } - - @Test - public void test53GetPolicyByGUIDAndServiceNameAndZoneName() throws Exception { - XXPolicyDao xPolicyDao = Mockito.mock(XXPolicyDao.class); - XXPolicy xPolicy = Mockito.mock(XXPolicy.class); - RangerPolicy rangerPolicy = rangerPolicy(); - RangerService rangerService = rangerService(); - String serviceName = rangerService.getName(); - String zoneName = "zone-1"; - Mockito.when(daoManager.getXXPolicy()).thenReturn(xPolicyDao); - Mockito.when(xPolicyDao.findPolicyByGUIDAndServiceNameAndZoneName(rangerPolicy.getGuid(), serviceName, zoneName)).thenReturn(xPolicy); - Mockito.when(policyService.getPopulatedViewObject(xPolicy)).thenReturn(rangerPolicy); - RangerPolicy dbRangerPolicy = serviceDBStore.getPolicy(rangerPolicy.getGuid(), serviceName, zoneName); - Assert.assertNotNull(dbRangerPolicy); - Assert.assertEquals(Id, dbRangerPolicy.getId()); - Mockito.verify(xPolicyDao).findPolicyByGUIDAndServiceNameAndZoneName(rangerPolicy.getGuid(), serviceName, zoneName); - Mockito.verify(policyService).getPopulatedViewObject(xPolicy); - } - - @Test - public void test53GetPolicyByGUIDAndZoneName() throws Exception { - XXPolicyDao xPolicyDao = Mockito.mock(XXPolicyDao.class); - XXPolicy xPolicy = Mockito.mock(XXPolicy.class); - RangerPolicy rangerPolicy = rangerPolicy(); - String zoneName = "zone-1"; - Mockito.when(daoManager.getXXPolicy()).thenReturn(xPolicyDao); - Mockito.when(xPolicyDao.findPolicyByGUIDAndServiceNameAndZoneName(rangerPolicy.getGuid(), null, zoneName)).thenReturn(xPolicy); - Mockito.when(policyService.getPopulatedViewObject(xPolicy)).thenReturn(rangerPolicy); - RangerPolicy dbRangerPolicy = serviceDBStore.getPolicy(rangerPolicy.getGuid(), null, zoneName); - Assert.assertNotNull(dbRangerPolicy); - Assert.assertEquals(Id, dbRangerPolicy.getId()); - Mockito.verify(xPolicyDao).findPolicyByGUIDAndServiceNameAndZoneName(rangerPolicy.getGuid(), null, zoneName); - Mockito.verify(policyService).getPopulatedViewObject(xPolicy); - } } diff --git a/security-admin/src/test/java/org/apache/ranger/biz/TestTagDBStore.java b/security-admin/src/test/java/org/apache/ranger/biz/TestTagDBStore.java index beba9af617..5600674b28 100755 --- a/security-admin/src/test/java/org/apache/ranger/biz/TestTagDBStore.java +++ b/security-admin/src/test/java/org/apache/ranger/biz/TestTagDBStore.java @@ -17,15 +17,6 @@ package org.apache.ranger.biz; -import static org.mockito.ArgumentMatchers.any; - -import java.util.ArrayList; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.ws.rs.WebApplicationException; import org.apache.ranger.common.MessageEnums; import org.apache.ranger.common.RESTErrorUtil; import org.apache.ranger.common.RangerServiceTagsCache; @@ -41,6 +32,7 @@ import org.apache.ranger.entity.XXServiceVersionInfo; import org.apache.ranger.entity.XXTag; import org.apache.ranger.entity.XXTagResourceMap; +import org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyResource; import org.apache.ranger.plugin.model.RangerServiceDef; import org.apache.ranger.plugin.model.RangerServiceDef.RangerAccessTypeDef; import org.apache.ranger.plugin.model.RangerServiceDef.RangerContextEnricherDef; @@ -53,7 +45,6 @@ import org.apache.ranger.plugin.model.RangerTag; import org.apache.ranger.plugin.model.RangerTagDef; import org.apache.ranger.plugin.model.RangerTagResourceMap; -import org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyResource; import org.apache.ranger.plugin.store.PList; import org.apache.ranger.plugin.util.SearchFilter; import org.apache.ranger.plugin.util.ServiceTags; @@ -75,46 +66,46 @@ import org.mockito.Mockito; import org.mockito.runners.MockitoJUnitRunner; +import javax.ws.rs.WebApplicationException; + +import java.util.ArrayList; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.mockito.ArgumentMatchers.any; + @RunWith(MockitoJUnitRunner.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class TestTagDBStore { - private final static Long id = 1L; - private final static String name = "test"; - private final static String gId = "1427365526516_835_0"; - private final static Long lastKnownVersion = 10L; - private final static String resourceSignature = "testResourceSign"; - private final static String serviceName = "HDFS"; - + private static final Long id = 1L; + private static final String name = "test"; + private static final String gId = "1427365526516_835_0"; + private static final Long lastKnownVersion = 10L; + private static final String resourceSignature = "testResourceSign"; + private static final String serviceName = "HDFS"; + @Rule + public ExpectedException thrown = ExpectedException.none(); @InjectMocks TagDBStore tagDBStore = new TagDBStore(); - @Mock RangerTagDefService rangerTagDefService; - @Mock RangerServiceResourceService rangerServiceResourceService; - @Mock RangerServiceResourceWithTagsService rangerServiceResourceWithTagsService; - @Mock RangerTagResourceMapService rangerTagResourceMapService; - @Mock RESTErrorUtil errorUtil; - @Mock RangerTagService rangerTagService; - @Mock RangerDaoManager daoManager; - @Mock ServiceDBStore svcStore; - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Test public void testCreateTagDef() throws Exception { RangerTagDef rangerTagDef = createRangerTagDef(); @@ -125,8 +116,8 @@ public void testCreateTagDef() throws Exception { RangerTagDef returnedRangerTagDef = tagDBStore.createTagDef(rangerTagDef); Assert.assertNotNull(returnedRangerTagDef); - Assert.assertEquals(returnedRangerTagDef.getId(), id); - Assert.assertEquals(rangerTagDef.getName(), name); + Assert.assertEquals(id, returnedRangerTagDef.getId()); + Assert.assertEquals(name, rangerTagDef.getName()); } @Test @@ -139,8 +130,8 @@ public void testUpdateTagDef() throws Exception { RangerTagDef returnedRangerTagDef = tagDBStore.updateTagDef(rangerTagDef); Assert.assertNotNull(returnedRangerTagDef); - Assert.assertEquals(returnedRangerTagDef.getId(), id); - Assert.assertEquals(rangerTagDef.getName(), name); + Assert.assertEquals(id, returnedRangerTagDef.getId()); + Assert.assertEquals(name, rangerTagDef.getName()); } @Test @@ -177,8 +168,8 @@ public void testGetTagDefByName() throws Exception { RangerTagDef returnedRangerTagDef = tagDBStore.getTagDefByName(rangerTagDef.getName()); Assert.assertNotNull(returnedRangerTagDef); - Assert.assertEquals(returnedRangerTagDef.getId(), id); - Assert.assertEquals(rangerTagDef.getName(), name); + Assert.assertEquals(id, returnedRangerTagDef.getId()); + Assert.assertEquals(name, rangerTagDef.getName()); } @Test @@ -190,9 +181,9 @@ public void testGetTagDefByGuid() throws Exception { RangerTagDef returnedRangerTagDef = tagDBStore.getTagDefByGuid(rangerTagDef.getGuid()); Assert.assertNotNull(returnedRangerTagDef); - Assert.assertEquals(returnedRangerTagDef.getId(), id); - Assert.assertEquals(returnedRangerTagDef.getGuid(), gId); - Assert.assertEquals(rangerTagDef.getName(), name); + Assert.assertEquals(id, returnedRangerTagDef.getId()); + Assert.assertEquals(gId, returnedRangerTagDef.getGuid()); + Assert.assertEquals(name, rangerTagDef.getName()); } @Test @@ -204,9 +195,9 @@ public void testGetTagDefById() throws Exception { RangerTagDef returnedRangerTagDef = tagDBStore.getTagDef(rangerTagDef.getId()); Assert.assertNotNull(returnedRangerTagDef); - Assert.assertEquals(returnedRangerTagDef.getId(), id); - Assert.assertEquals(returnedRangerTagDef.getGuid(), gId); - Assert.assertEquals(rangerTagDef.getName(), name); + Assert.assertEquals(id, returnedRangerTagDef.getId()); + Assert.assertEquals(gId, returnedRangerTagDef.getGuid()); + Assert.assertEquals(name, rangerTagDef.getName()); } @Test @@ -242,9 +233,9 @@ public void testGetTagDefs() throws Exception { RangerTagDef rangerTagDef = rangerTagDefList.get(0); - Assert.assertEquals(rangerTagDef.getId(), id); - Assert.assertEquals(rangerTagDef.getGuid(), gId); - Assert.assertEquals(rangerTagDef.getName(), name); + Assert.assertEquals(id, rangerTagDef.getId()); + Assert.assertEquals(gId, rangerTagDef.getGuid()); + Assert.assertEquals(name, rangerTagDef.getName()); } @Test @@ -260,10 +251,10 @@ public void testGetPaginatedTagDefs() throws Exception { RangerTagDef rangerTagDef = returnedRangerTagDefList.getList().get(0); - Assert.assertEquals(returnedRangerTagDefList.getList().size(), 1); - Assert.assertEquals(rangerTagDef.getId(), id); - Assert.assertEquals(rangerTagDef.getGuid(), gId); - Assert.assertEquals(rangerTagDef.getName(), name); + Assert.assertEquals(1, returnedRangerTagDefList.getList().size()); + Assert.assertEquals(id, rangerTagDef.getId()); + Assert.assertEquals(gId, rangerTagDef.getGuid()); + Assert.assertEquals(name, rangerTagDef.getName()); } @Test @@ -276,8 +267,8 @@ public void testCreateTag() throws Exception { RangerTag returnedRangerTag = tagDBStore.createTag(rangerTag); Assert.assertNotNull(returnedRangerTag); - Assert.assertEquals(returnedRangerTag.getId(), id); - Assert.assertEquals(returnedRangerTag.getGuid(), gId); + Assert.assertEquals(id, returnedRangerTag.getId()); + Assert.assertEquals(gId, returnedRangerTag.getGuid()); } @Test @@ -290,8 +281,8 @@ public void testUpdateTag() throws Exception { RangerTag returnedRangerTag = tagDBStore.updateTag(rangerTag); Assert.assertNotNull(returnedRangerTag); - Assert.assertEquals(returnedRangerTag.getId(), id); - Assert.assertEquals(returnedRangerTag.getGuid(), gId); + Assert.assertEquals(id, returnedRangerTag.getId()); + Assert.assertEquals(gId, returnedRangerTag.getGuid()); } @Test @@ -324,8 +315,8 @@ public void testGetTagById() throws Exception { RangerTag returnedRangerTag = tagDBStore.getTag(id); Assert.assertNotNull(returnedRangerTag); - Assert.assertEquals(returnedRangerTag.getId(), id); - Assert.assertEquals(returnedRangerTag.getGuid(), gId); + Assert.assertEquals(id, returnedRangerTag.getId()); + Assert.assertEquals(gId, returnedRangerTag.getGuid()); } @Test @@ -337,11 +328,10 @@ public void testGetTagByGuid() throws Exception { RangerTag returnedRangerTag = tagDBStore.getTagByGuid(gId); Assert.assertNotNull(returnedRangerTag); - Assert.assertEquals(returnedRangerTag.getId(), id); - Assert.assertEquals(returnedRangerTag.getGuid(), gId); + Assert.assertEquals(id, returnedRangerTag.getId()); + Assert.assertEquals(gId, returnedRangerTag.getGuid()); } - @Test public void testGetTagsByType() throws Exception { String type = "file"; @@ -358,8 +348,8 @@ public void testGetTagsByType() throws Exception { RangerTag returnedRangerTag = returnedRangerTags.get(0); - Assert.assertEquals(returnedRangerTag.getId(), id); - Assert.assertEquals(returnedRangerTag.getGuid(), gId); + Assert.assertEquals(id, returnedRangerTag.getId()); + Assert.assertEquals(gId, returnedRangerTag.getGuid()); } @Test @@ -377,8 +367,8 @@ public void testGetTagsForResourceId() throws Exception { RangerTag returnedRangerTag = returnedRangerTags.get(0); - Assert.assertEquals(returnedRangerTag.getId(), id); - Assert.assertEquals(returnedRangerTag.getGuid(), gId); + Assert.assertEquals(id, returnedRangerTag.getId()); + Assert.assertEquals(gId, returnedRangerTag.getGuid()); } @Test @@ -395,8 +385,8 @@ public void testGetTagsForResourceGuid() throws Exception { RangerTag returnedRangerTag = returnedRangerTags.get(0); - Assert.assertEquals(returnedRangerTag.getId(), id); - Assert.assertEquals(returnedRangerTag.getGuid(), gId); + Assert.assertEquals(id, returnedRangerTag.getId()); + Assert.assertEquals(gId, returnedRangerTag.getGuid()); } @Test @@ -412,8 +402,8 @@ public void testGetTags() throws Exception { RangerTag returnedRangerTag = returnedRangerTags.get(0); - Assert.assertEquals(returnedRangerTag.getId(), id); - Assert.assertEquals(returnedRangerTag.getGuid(), gId); + Assert.assertEquals(id, returnedRangerTag.getId()); + Assert.assertEquals(gId, returnedRangerTag.getGuid()); } @Test @@ -426,16 +416,16 @@ public void testGetPaginatedTags() throws Exception { PList returnedRangerTagPList = tagDBStore.getPaginatedTags(filter); Assert.assertNotNull(returnedRangerTagPList); - Assert.assertEquals(returnedRangerTagPList.getListSize(), 1); + Assert.assertEquals(1, returnedRangerTagPList.getListSize()); RangerTag returnedRangerTag = returnedRangerTagPList.getList().get(0); - Assert.assertEquals(returnedRangerTag.getId(), id); - Assert.assertEquals(returnedRangerTag.getGuid(), gId); + Assert.assertEquals(id, returnedRangerTag.getId()); + Assert.assertEquals(gId, returnedRangerTag.getGuid()); } @Test - public void testResetTagCache() throws Exception { + public void testResetTagCache() { RangerServiceTagsCache rangerServiceTagsCache = Mockito.mock(RangerServiceTagsCache.class); tagDBStore.resetTagCache(name); @@ -451,10 +441,10 @@ public void testCreateServiceResource() throws Exception { RangerServiceResource returnedRangerServiceResource = tagDBStore.createServiceResource(rangerServiceResource); Assert.assertNotNull(returnedRangerServiceResource); - Assert.assertEquals(returnedRangerServiceResource.getId(), id); - Assert.assertEquals(returnedRangerServiceResource.getGuid(), gId); - Assert.assertEquals(returnedRangerServiceResource.getResourceSignature(), resourceSignature); - Assert.assertEquals(returnedRangerServiceResource.getServiceName(), serviceName); + Assert.assertEquals(id, returnedRangerServiceResource.getId()); + Assert.assertEquals(gId, returnedRangerServiceResource.getGuid()); + Assert.assertEquals(resourceSignature, returnedRangerServiceResource.getResourceSignature()); + Assert.assertEquals(serviceName, returnedRangerServiceResource.getServiceName()); } @Test @@ -467,10 +457,10 @@ public void testUpdateServiceResource() throws Exception { RangerServiceResource returnedRangerServiceResource = tagDBStore.updateServiceResource(rangerServiceResource); Assert.assertNotNull(returnedRangerServiceResource); - Assert.assertEquals(returnedRangerServiceResource.getId(), id); - Assert.assertEquals(returnedRangerServiceResource.getGuid(), gId); - Assert.assertEquals(returnedRangerServiceResource.getResourceSignature(), resourceSignature); - Assert.assertEquals(returnedRangerServiceResource.getServiceName(), serviceName); + Assert.assertEquals(id, returnedRangerServiceResource.getId()); + Assert.assertEquals(gId, returnedRangerServiceResource.getGuid()); + Assert.assertEquals(resourceSignature, returnedRangerServiceResource.getResourceSignature()); + Assert.assertEquals(serviceName, returnedRangerServiceResource.getServiceName()); } @Test @@ -521,10 +511,10 @@ public void tesGetServiceResourceByGuid() throws Exception { RangerServiceResource returnedRangerServiceResource = tagDBStore.getServiceResourceByGuid(gId); Assert.assertNotNull(returnedRangerServiceResource); - Assert.assertEquals(returnedRangerServiceResource.getId(), id); - Assert.assertEquals(returnedRangerServiceResource.getGuid(), gId); - Assert.assertEquals(returnedRangerServiceResource.getResourceSignature(), resourceSignature); - Assert.assertEquals(returnedRangerServiceResource.getServiceName(), serviceName); + Assert.assertEquals(id, returnedRangerServiceResource.getId()); + Assert.assertEquals(gId, returnedRangerServiceResource.getGuid()); + Assert.assertEquals(resourceSignature, returnedRangerServiceResource.getResourceSignature()); + Assert.assertEquals(serviceName, returnedRangerServiceResource.getServiceName()); } @Test @@ -536,10 +526,10 @@ public void tesGetServiceResourceById() throws Exception { RangerServiceResource returnedRangerServiceResource = tagDBStore.getServiceResource(id); Assert.assertNotNull(returnedRangerServiceResource); - Assert.assertEquals(returnedRangerServiceResource.getId(), id); - Assert.assertEquals(returnedRangerServiceResource.getGuid(), gId); - Assert.assertEquals(returnedRangerServiceResource.getResourceSignature(), resourceSignature); - Assert.assertEquals(returnedRangerServiceResource.getServiceName(), serviceName); + Assert.assertEquals(id, returnedRangerServiceResource.getId()); + Assert.assertEquals(gId, returnedRangerServiceResource.getGuid()); + Assert.assertEquals(resourceSignature, returnedRangerServiceResource.getResourceSignature()); + Assert.assertEquals(serviceName, returnedRangerServiceResource.getServiceName()); } @Test @@ -561,16 +551,16 @@ public void tesGetServiceResourcesByService() throws Exception { RangerServiceResource returnedRangerServiceResource = returnedRangerServiceResourceList.get(0); - Assert.assertEquals(returnedRangerServiceResource.getId(), id); - Assert.assertEquals(returnedRangerServiceResource.getGuid(), gId); - Assert.assertEquals(returnedRangerServiceResource.getResourceSignature(), resourceSignature); - Assert.assertEquals(returnedRangerServiceResource.getServiceName(), serviceName); + Assert.assertEquals(id, returnedRangerServiceResource.getId()); + Assert.assertEquals(gId, returnedRangerServiceResource.getGuid()); + Assert.assertEquals(resourceSignature, returnedRangerServiceResource.getResourceSignature()); + Assert.assertEquals(serviceName, returnedRangerServiceResource.getServiceName()); } @Test - public void tesGetServiceResourceGuidsByService() throws Exception { + public void tesGetServiceResourceGuidsByService() { RangerServiceResource rangerServiceResource = createRangerServiceResource(); - List result = new ArrayList<>(); + List result = new ArrayList<>(); XXServiceResourceDao xxServiceResourceDao = Mockito.mock(XXServiceResourceDao.class); XXServiceDao xxServiceDao = Mockito.mock(XXServiceDao.class); @@ -584,7 +574,7 @@ public void tesGetServiceResourceGuidsByService() throws Exception { List returnedServiceResourceGuidsInServiceId = tagDBStore.getServiceResourceGuidsByService(serviceName); Assert.assertNotNull(returnedServiceResourceGuidsInServiceId); - Assert.assertEquals(returnedServiceResourceGuidsInServiceId.get(0), gId); + Assert.assertEquals(gId, returnedServiceResourceGuidsInServiceId.get(0)); } @Test @@ -599,9 +589,9 @@ public void tesGetServiceResourceByServiceAndResourceSignature() throws Exceptio RangerServiceResource returnedRangerServiceResource = tagDBStore.getServiceResourceByServiceAndResourceSignature(serviceName, resourceSignature); Assert.assertNotNull(returnedRangerServiceResource); - Assert.assertEquals(returnedRangerServiceResource.getId(), id); - Assert.assertEquals(returnedRangerServiceResource.getGuid(), gId); - Assert.assertEquals(returnedRangerServiceResource.getResourceSignature(), resourceSignature); + Assert.assertEquals(id, returnedRangerServiceResource.getId()); + Assert.assertEquals(gId, returnedRangerServiceResource.getGuid()); + Assert.assertEquals(resourceSignature, returnedRangerServiceResource.getResourceSignature()); } @Test @@ -614,13 +604,13 @@ public void tesGetServiceResources() throws Exception { List returnedRangerServiceResourceList = tagDBStore.getServiceResources(searchFilter); Assert.assertNotNull(returnedRangerServiceResourceList); - Assert.assertEquals(returnedRangerServiceResourceList.size(), 1); + Assert.assertEquals(1, returnedRangerServiceResourceList.size()); RangerServiceResource returnedRangerServiceResource = returnedRangerServiceResourceList.get(0); - Assert.assertEquals(returnedRangerServiceResource.getId(), id); - Assert.assertEquals(returnedRangerServiceResource.getGuid(), gId); - Assert.assertEquals(returnedRangerServiceResource.getResourceSignature(), resourceSignature); + Assert.assertEquals(id, returnedRangerServiceResource.getId()); + Assert.assertEquals(gId, returnedRangerServiceResource.getGuid()); + Assert.assertEquals(resourceSignature, returnedRangerServiceResource.getResourceSignature()); } @Test @@ -633,13 +623,13 @@ public void tesGetPaginatedServiceResources() throws Exception { PList returnedRangerServiceResourcePList = tagDBStore.getPaginatedServiceResources(searchFilter); Assert.assertNotNull(returnedRangerServiceResourcePList); - Assert.assertEquals(returnedRangerServiceResourcePList.getList().size(), 1); + Assert.assertEquals(1, returnedRangerServiceResourcePList.getList().size()); RangerServiceResource returnedRangerServiceResource = returnedRangerServiceResourcePList.getList().get(0); - Assert.assertEquals(returnedRangerServiceResource.getId(), id); - Assert.assertEquals(returnedRangerServiceResource.getGuid(), gId); - Assert.assertEquals(returnedRangerServiceResource.getResourceSignature(), resourceSignature); + Assert.assertEquals(id, returnedRangerServiceResource.getId()); + Assert.assertEquals(gId, returnedRangerServiceResource.getGuid()); + Assert.assertEquals(resourceSignature, returnedRangerServiceResource.getResourceSignature()); } @Test @@ -660,8 +650,8 @@ public void tesCreateTagResourceMap() throws Exception { RangerTagResourceMap returnedRangerTagResourceMap = tagDBStore.createTagResourceMap(rangerTagResourceMap); Assert.assertNotNull(returnedRangerTagResourceMap); - Assert.assertEquals(returnedRangerTagResourceMap.getId(), id); - Assert.assertEquals(returnedRangerTagResourceMap.getGuid(), gId); + Assert.assertEquals(id, returnedRangerTagResourceMap.getId()); + Assert.assertEquals(gId, returnedRangerTagResourceMap.getGuid()); } @Test @@ -696,8 +686,8 @@ public void tesGetTagResourceMap() throws Exception { RangerTagResourceMap returnedRangerTagResourceMap = tagDBStore.getTagResourceMap(id); Assert.assertNotNull(returnedRangerTagResourceMap); - Assert.assertEquals(returnedRangerTagResourceMap.getId(), id); - Assert.assertEquals(returnedRangerTagResourceMap.getGuid(), gId); + Assert.assertEquals(id, returnedRangerTagResourceMap.getId()); + Assert.assertEquals(gId, returnedRangerTagResourceMap.getGuid()); } @Test @@ -709,8 +699,8 @@ public void tesGetTagResourceMapByGuid() throws Exception { RangerTagResourceMap returnedRangerTagResourceMap = tagDBStore.getTagResourceMapByGuid(gId); Assert.assertNotNull(returnedRangerTagResourceMap); - Assert.assertEquals(returnedRangerTagResourceMap.getId(), id); - Assert.assertEquals(returnedRangerTagResourceMap.getGuid(), gId); + Assert.assertEquals(id, returnedRangerTagResourceMap.getId()); + Assert.assertEquals(gId, returnedRangerTagResourceMap.getGuid()); } @Test @@ -726,8 +716,8 @@ public void tesGetTagResourceMapsForTagId() throws Exception { RangerTagResourceMap returnedRangerTagResourceMap = returnedRangerTagResourceMapList.get(0); Assert.assertNotNull(returnedRangerTagResourceMap); - Assert.assertEquals(returnedRangerTagResourceMap.getId(), id); - Assert.assertEquals(returnedRangerTagResourceMap.getGuid(), gId); + Assert.assertEquals(id, returnedRangerTagResourceMap.getId()); + Assert.assertEquals(gId, returnedRangerTagResourceMap.getGuid()); } @Test @@ -743,8 +733,8 @@ public void tesGetTagResourceMapsForTagGuid() throws Exception { RangerTagResourceMap returnedRangerTagResourceMap = returnedRangerTagResourceMapList.get(0); Assert.assertNotNull(returnedRangerTagResourceMap); - Assert.assertEquals(returnedRangerTagResourceMap.getId(), id); - Assert.assertEquals(returnedRangerTagResourceMap.getGuid(), gId); + Assert.assertEquals(id, returnedRangerTagResourceMap.getId()); + Assert.assertEquals(gId, returnedRangerTagResourceMap.getGuid()); } @Test @@ -758,11 +748,10 @@ public void tesGetTagIdsForResourceId() throws Exception { List returnedTagIdsList = tagDBStore.getTagIdsForResourceId(id); Assert.assertNotNull(returnedTagIdsList); - Assert.assertEquals(returnedTagIdsList.size(), 1); - Assert.assertEquals(returnedTagIdsList.get(0), id); + Assert.assertEquals(1, returnedTagIdsList.size()); + Assert.assertEquals(id, returnedTagIdsList.get(0)); } - @Test public void testGetTagResourceMapsForResourceId() throws Exception { RangerTagResourceMap rangerTagResourceMap = createRangerTagResourceMap(); @@ -776,8 +765,8 @@ public void testGetTagResourceMapsForResourceId() throws Exception { RangerTagResourceMap returnedRangerTagResourceMap = returnedRangerTagResourceMapList.get(0); Assert.assertNotNull(returnedRangerTagResourceMap); - Assert.assertEquals(returnedRangerTagResourceMap.getId(), id); - Assert.assertEquals(returnedRangerTagResourceMap.getGuid(), gId); + Assert.assertEquals(id, returnedRangerTagResourceMap.getId()); + Assert.assertEquals(gId, returnedRangerTagResourceMap.getGuid()); } @Test @@ -793,35 +782,34 @@ public void testGetTagResourceMapsForResourceGuid() throws Exception { RangerTagResourceMap returnedRangerTagResourceMap = returnedRangerTagResourceMapList.get(0); Assert.assertNotNull(returnedRangerTagResourceMap); - Assert.assertEquals(returnedRangerTagResourceMap.getId(), id); - Assert.assertEquals(returnedRangerTagResourceMap.getGuid(), gId); + Assert.assertEquals(id, returnedRangerTagResourceMap.getId()); + Assert.assertEquals(gId, returnedRangerTagResourceMap.getGuid()); } - @Test public void testGetTagResourceMapForTagAndResourceId() throws Exception { RangerTagResourceMap rangerTagResourceMap = createRangerTagResourceMap(); - Mockito.when(rangerTagResourceMapService.getByTagAndResourceId(id,id)).thenReturn(rangerTagResourceMap); + Mockito.when(rangerTagResourceMapService.getByTagAndResourceId(id, id)).thenReturn(rangerTagResourceMap); - RangerTagResourceMap returnedRangerTagResourceMap = tagDBStore.getTagResourceMapForTagAndResourceId(id,id); + RangerTagResourceMap returnedRangerTagResourceMap = tagDBStore.getTagResourceMapForTagAndResourceId(id, id); Assert.assertNotNull(returnedRangerTagResourceMap); - Assert.assertEquals(returnedRangerTagResourceMap.getId(), id); - Assert.assertEquals(returnedRangerTagResourceMap.getGuid(), gId); + Assert.assertEquals(id, returnedRangerTagResourceMap.getId()); + Assert.assertEquals(gId, returnedRangerTagResourceMap.getGuid()); } @Test public void testGetTagResourceMapForTagAndResourceGuid() throws Exception { RangerTagResourceMap rangerTagResourceMap = createRangerTagResourceMap(); - Mockito.when(rangerTagResourceMapService.getByTagAndResourceGuid(gId,gId)).thenReturn(rangerTagResourceMap); + Mockito.when(rangerTagResourceMapService.getByTagAndResourceGuid(gId, gId)).thenReturn(rangerTagResourceMap); - RangerTagResourceMap returnedRangerTagResourceMap = tagDBStore.getTagResourceMapForTagAndResourceGuid(gId,gId); + RangerTagResourceMap returnedRangerTagResourceMap = tagDBStore.getTagResourceMapForTagAndResourceGuid(gId, gId); Assert.assertNotNull(returnedRangerTagResourceMap); - Assert.assertEquals(returnedRangerTagResourceMap.getId(), id); - Assert.assertEquals(returnedRangerTagResourceMap.getGuid(), gId); + Assert.assertEquals(id, returnedRangerTagResourceMap.getId()); + Assert.assertEquals(gId, returnedRangerTagResourceMap.getGuid()); } @Test @@ -834,12 +822,12 @@ public void testGetPaginatedTagResourceMaps() throws Exception { PList returnedRangerTagResourceMapPList = tagDBStore.getPaginatedTagResourceMaps(searchFilter); Assert.assertNotNull(returnedRangerTagResourceMapPList); - Assert.assertEquals(returnedRangerTagResourceMapPList.getList().size(), 1); + Assert.assertEquals(1, returnedRangerTagResourceMapPList.getList().size()); RangerTagResourceMap returnedRangerTagResourceMap = returnedRangerTagResourceMapPList.getList().get(0); - Assert.assertEquals(returnedRangerTagResourceMap.getId(), id); - Assert.assertEquals(returnedRangerTagResourceMap.getGuid(), gId); + Assert.assertEquals(id, returnedRangerTagResourceMap.getId()); + Assert.assertEquals(gId, returnedRangerTagResourceMap.getGuid()); } @Test @@ -852,18 +840,18 @@ public void testGetTagResourceMaps() throws Exception { List returnedRangerTagResourceMapList = tagDBStore.getTagResourceMaps(searchFilter); Assert.assertNotNull(returnedRangerTagResourceMapList); - Assert.assertEquals(returnedRangerTagResourceMapList.size(), 1); + Assert.assertEquals(1, returnedRangerTagResourceMapList.size()); RangerTagResourceMap returnedRangerTagResourceMap = returnedRangerTagResourceMapList.get(0); - Assert.assertEquals(returnedRangerTagResourceMap.getId(), id); - Assert.assertEquals(returnedRangerTagResourceMap.getGuid(), gId); + Assert.assertEquals(id, returnedRangerTagResourceMap.getId()); + Assert.assertEquals(gId, returnedRangerTagResourceMap.getGuid()); } @Test public void testGetServiceTagsIfUpdated() throws Exception { XXServiceVersionInfo serviceVersionInfoDbObj = createXXServiceVersionInfo(); - XXTagDefDao xxTagDefDao = Mockito.mock(XXTagDefDao.class); + XXTagDefDao xxTagDefDao = Mockito.mock(XXTagDefDao.class); XXServiceVersionInfoDao xxServiceVersionInfoDao = Mockito.mock(XXServiceVersionInfoDao.class); XXServiceDao xxServiceDao = Mockito.mock(XXServiceDao.class); XXServiceResourceDao xxServiceResourceDao = Mockito.mock(XXServiceResourceDao.class); @@ -882,14 +870,14 @@ public void testGetServiceTagsIfUpdated() throws Exception { ServiceTags serviceTags = tagDBStore.getServiceTagsIfUpdated(serviceName, -1L, true); Assert.assertNotNull(serviceTags); - Assert.assertEquals(serviceTags.getTagVersion(), lastKnownVersion); - Assert.assertEquals(serviceTags.getServiceName(), serviceName); + Assert.assertEquals(lastKnownVersion, serviceTags.getTagVersion()); + Assert.assertEquals(serviceName, serviceTags.getServiceName()); } @Test public void testGetServiceTags() throws Exception { XXServiceVersionInfo serviceVersionInfoDbObj = createXXServiceVersionInfo(); - XXTagDefDao xxTagDefDao = Mockito.mock(XXTagDefDao.class); + XXTagDefDao xxTagDefDao = Mockito.mock(XXTagDefDao.class); XXServiceVersionInfoDao xxServiceVersionInfoDao = Mockito.mock(XXServiceVersionInfoDao.class); XXServiceDao xxServiceDao = Mockito.mock(XXServiceDao.class); XXServiceResourceDao xxServiceResourceDao = Mockito.mock(XXServiceResourceDao.class); @@ -907,23 +895,23 @@ public void testGetServiceTags() throws Exception { ServiceTags serviceTags = tagDBStore.getServiceTags(serviceName, -1L); Assert.assertNotNull(serviceTags); - Assert.assertEquals(serviceTags.getTagVersion(), lastKnownVersion); - Assert.assertEquals(serviceTags.getServiceName(), serviceName); + Assert.assertEquals(lastKnownVersion, serviceTags.getTagVersion()); + Assert.assertEquals(serviceName, serviceTags.getServiceName()); } @Test public void testDeleteAllTagObjectsForService() throws Exception { - XXServiceDao xxServiceDao = Mockito.mock(XXServiceDao.class); - XXTagDao xxTagDao = Mockito.mock(XXTagDao.class); - XXTagResourceMapDao xxTagResourceMapDao = Mockito.mock(XXTagResourceMapDao.class); - XXServiceResourceDao xxServiceResourceDao = Mockito.mock(XXServiceResourceDao.class); - XXService xxService = createXXService(); - XXTag xxTag = createXXTag(); - XXTagResourceMap xxTagResourceMap = createXXTagResourceMap(); - XXServiceResource xxServiceResource = createXXServiceResource(); - List xxTagList = new ArrayList<>(); - List xxTagResourceMapList = new ArrayList<>(); - List xxServiceResources = new ArrayList<>(); + XXServiceDao xxServiceDao = Mockito.mock(XXServiceDao.class); + XXTagDao xxTagDao = Mockito.mock(XXTagDao.class); + XXTagResourceMapDao xxTagResourceMapDao = Mockito.mock(XXTagResourceMapDao.class); + XXServiceResourceDao xxServiceResourceDao = Mockito.mock(XXServiceResourceDao.class); + XXService xxService = createXXService(); + XXTag xxTag = createXXTag(); + XXTagResourceMap xxTagResourceMap = createXXTagResourceMap(); + XXServiceResource xxServiceResource = createXXServiceResource(); + List xxTagList = new ArrayList<>(); + List xxTagResourceMapList = new ArrayList<>(); + List xxServiceResources = new ArrayList<>(); Mockito.when(daoManager.getXXService()).thenReturn(xxServiceDao); Mockito.when(daoManager.getXXTag()).thenReturn(xxTagDao); @@ -954,30 +942,67 @@ public void testGetServiceTagsDeltaWhenTagDeltaSupportsDisabled() throws Excepti } @Test - public void testIsSupportsTagDeltas() throws Exception { - boolean isSupportsTagDeltas = tagDBStore.isSupportsTagDeltas(); + public void testIsSupportsTagDeltas() { + boolean isSupportsTagDeltas = TagDBStore.isSupportsTagDeltas(); Assert.assertFalse(isSupportsTagDeltas); } @Test - public void testIsInPlaceTagUpdateSupported() throws Exception { + public void testIsInPlaceTagUpdateSupported() { boolean isInPlaceTagUpdateSupported = tagDBStore.isInPlaceTagUpdateSupported(); Assert.assertFalse(isInPlaceTagUpdateSupported); } @Test - public void testGetTagVersion() throws Exception { - XXServiceVersionInfo serviceVersionInfoDbObj = createXXServiceVersionInfo(); + public void testGetTagVersion() { + XXServiceVersionInfo serviceVersionInfoDbObj = createXXServiceVersionInfo(); XXServiceVersionInfoDao xxServiceVersionInfoDao = Mockito.mock(XXServiceVersionInfoDao.class); Mockito.when(daoManager.getXXServiceVersionInfo()).thenReturn(xxServiceVersionInfoDao); Mockito.when(xxServiceVersionInfoDao.findByServiceName(serviceName)).thenReturn(serviceVersionInfoDbObj); - Long tagVersion = tagDBStore.getTagVersion(serviceName); + Long tagVersion = tagDBStore.getTagVersion(serviceName); - Assert.assertEquals(tagVersion, lastKnownVersion); + Assert.assertEquals(lastKnownVersion, tagVersion); + } + + @Test + public void tesGetPaginatedServiceResourcesWithTags() throws Exception { + RangerServiceResourceWithTagsList rangerServiceResourceViewList = createRangerServiceResourceWithTagsViewList(); + SearchFilter searchFilter = new SearchFilter(); + + Mockito.when(rangerServiceResourceWithTagsService.searchServiceResourcesWithTags(searchFilter)).thenReturn(rangerServiceResourceViewList); + + RangerServiceResourceWithTagsList returnedRangerServiceResourcePList = tagDBStore.getPaginatedServiceResourcesWithTags(searchFilter); + + Assert.assertNotNull(returnedRangerServiceResourcePList); + Assert.assertEquals(1, returnedRangerServiceResourcePList.getList().size()); + + RangerServiceResourceWithTags returnedRangerServiceResource = returnedRangerServiceResourcePList.getResourceList().get(0); + + Assert.assertEquals(id, returnedRangerServiceResource.getId()); + Assert.assertEquals(gId, returnedRangerServiceResource.getGuid()); + Assert.assertNotNull(returnedRangerServiceResource.getAssociatedTags()); + Assert.assertEquals(rangerServiceResourceViewList.getResourceList().get(0).getAssociatedTags().size(), returnedRangerServiceResource.getAssociatedTags().size()); + } + + @Test + public void testToRangerServiceResource() { + Map resourceMap = new HashMap<>(); + Map resourceElements = new HashMap<>(); + + resourceMap.put("database", new String[] {"db1"}); + resourceMap.put("database.isExcludes", new String[] {"false"}); + resourceMap.put("database.isRecursive", new String[] {"false"}); + + resourceElements.put("database", new RangerPolicyResource("db1", false, false)); + + RangerServiceResource expectedResource = new RangerServiceResource(serviceName, resourceElements); + RangerServiceResource actualResource = TagDBStore.toRangerServiceResource(serviceName, resourceMap); + + Assert.assertEquals(expectedResource.getResourceElements(), actualResource.getResourceElements()); } private RangerTagDef createRangerTagDef() { @@ -992,7 +1017,7 @@ private RangerTagDef createRangerTagDef() { return rangerTagDef; } - private PList createRangerTagDefPList() { + private PList createRangerTagDefPList() { PList rangerTagDefPList = new PList<>(); List rangerTagDefList = new ArrayList<>(); RangerTagDef rangerTagDef = createRangerTagDef(); @@ -1015,7 +1040,7 @@ private RangerTag createRangerTag() { rangerTag.setId(id); rangerTag.setCreatedBy(name); - rangerTag.setOwner((short)0); + rangerTag.setOwner((short) 0); rangerTag.setCreateTime(new Date()); rangerTag.setGuid(gId); rangerTag.setVersion(lastKnownVersion); @@ -1023,7 +1048,7 @@ private RangerTag createRangerTag() { return rangerTag; } - private PList createRangerTagPList() { + private PList createRangerTagPList() { PList rangerTagPList = new PList<>(); List rangerTagList = new ArrayList<>(); RangerTag rangerTag = createRangerTag(); @@ -1053,7 +1078,7 @@ private RangerServiceResource createRangerServiceResource() { return rangerServiceResource; } - private PList createRangerServiceResourcePList() { + private PList createRangerServiceResourcePList() { PList rangerServiceResourcePList = new PList<>(); List rangerServiceResourceList = new ArrayList<>(); RangerServiceResource rangerServiceResource = new RangerServiceResource(); @@ -1103,7 +1128,7 @@ private XXServiceResource createXXServiceResource() { return xxServiceResource; } - private PList createRangerTagResourceMapPList() { + private PList createRangerTagResourceMapPList() { PList rangerTagResourceMapPList = new PList<>(); List rangerTagResourceMapList = new ArrayList<>(); RangerTagResourceMap rangerTagResourceMap = new RangerTagResourceMap(); @@ -1196,27 +1221,7 @@ private XXTagResourceMap createXXTagResourceMap() { return xxTagResourceMap; } - @Test - public void tesGetPaginatedServiceResourcesWithTags() throws Exception { - RangerServiceResourceWithTagsList rangerServiceResourceViewList = createRangerServiceResourceWithTagsViewList(); - SearchFilter searchFilter = new SearchFilter(); - - Mockito.when(rangerServiceResourceWithTagsService.searchServiceResourcesWithTags(searchFilter)).thenReturn(rangerServiceResourceViewList); - - RangerServiceResourceWithTagsList returnedRangerServiceResourcePList = tagDBStore.getPaginatedServiceResourcesWithTags(searchFilter); - - Assert.assertNotNull(returnedRangerServiceResourcePList); - Assert.assertEquals(returnedRangerServiceResourcePList.getList().size(), 1); - - RangerServiceResourceWithTags returnedRangerServiceResource = returnedRangerServiceResourcePList.getResourceList().get(0); - - Assert.assertEquals(returnedRangerServiceResource.getId(), id); - Assert.assertEquals(returnedRangerServiceResource.getGuid(), gId); - Assert.assertNotNull(returnedRangerServiceResource.getAssociatedTags()); - Assert.assertEquals(rangerServiceResourceViewList.getResourceList().get(0).getAssociatedTags().size(), returnedRangerServiceResource.getAssociatedTags().size()); - } - - private RangerServiceResourceWithTagsList createRangerServiceResourceWithTagsViewList() { + private RangerServiceResourceWithTagsList createRangerServiceResourceWithTagsViewList() { RangerServiceResourceWithTagsList rangerServiceResourceViewList = new RangerServiceResourceWithTagsList(); List rangerServiceResourceList = new ArrayList<>(); RangerServiceResourceWithTags rangerServiceResource = new RangerServiceResourceWithTags(); @@ -1243,21 +1248,4 @@ private RangerServiceResourceWithTagsList createRangerServiceResourceWithTagsVi return rangerServiceResourceViewList; } - - @Test - public void testToRangerServiceResource() { - Map resourceMap = new HashMap<>(); - Map resourceElements = new HashMap<>(); - - resourceMap.put("database", new String[] { "db1" }); - resourceMap.put("database.isExcludes", new String[] { "false" }); - resourceMap.put("database.isRecursive", new String[] { "false" }); - - resourceElements.put("database", new RangerPolicyResource("db1", false, false)); - - RangerServiceResource expectedResource = new RangerServiceResource(serviceName, resourceElements); - RangerServiceResource actualResource = tagDBStore.toRangerServiceResource(serviceName, resourceMap); - - Assert.assertEquals(expectedResource.getResourceElements(), actualResource.getResourceElements()); - } -} \ No newline at end of file +} diff --git a/security-admin/src/test/java/org/apache/ranger/biz/TestUserMgr.java b/security-admin/src/test/java/org/apache/ranger/biz/TestUserMgr.java index cdf265b2d9..cb8dcd3bb8 100644 --- a/security-admin/src/test/java/org/apache/ranger/biz/TestUserMgr.java +++ b/security-admin/src/test/java/org/apache/ranger/biz/TestUserMgr.java @@ -16,16 +16,6 @@ */ package org.apache.ranger.biz; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Date; -import java.util.List; - -import javax.persistence.EntityManager; -import javax.persistence.Query; -import javax.servlet.http.HttpServletResponse; -import javax.ws.rs.WebApplicationException; - import org.apache.ranger.common.ContextUtil; import org.apache.ranger.common.MessageEnums; import org.apache.ranger.common.RESTErrorUtil; @@ -73,2175 +63,2170 @@ import org.mockito.Mockito; import org.mockito.junit.MockitoJUnitRunner; +import javax.persistence.EntityManager; +import javax.persistence.Query; +import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.WebApplicationException; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Date; +import java.util.List; + @RunWith(MockitoJUnitRunner.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class TestUserMgr { - - private static Long userId = 1L; - private static String userLoginID = "testuser"; - - @InjectMocks - UserMgr userMgr = new UserMgr(); - - @Mock - VXPortalUser VXPortalUser; - - @Mock - RangerDaoManager daoManager; - - @Mock - RESTErrorUtil restErrorUtil; - - @Mock - ContextUtil contextUtil; - - @Mock - StringUtil stringUtil; - - @Mock - SearchUtil searchUtil; - - @Mock - RangerBizUtil rangerBizUtil; - - @Mock - XUserPermissionService xUserPermissionService; - - @Mock - XGroupPermissionService xGroupPermissionService; - - @Mock - SessionMgr sessionMgr; - - @Mock - XUserMgr xUserMgr; - - @Mock - XPortalUserService xPortalUserService; - - @Rule - public ExpectedException thrown = ExpectedException.none(); - - public void setup() { - RangerSecurityContext context = new RangerSecurityContext(); - context.setUserSession(new UserSessionBase()); - RangerContextHolder.setSecurityContext(context); - UserSessionBase currentUserSession = ContextUtil.getCurrentUserSession(); - currentUserSession.setUserAdmin(true); - } - - public void setupKeyAdmin() { - RangerSecurityContext context = new RangerSecurityContext(); - context.setUserSession(new UserSessionBase()); - RangerContextHolder.setSecurityContext(context); - UserSessionBase currentUserSession = ContextUtil.getCurrentUserSession(); - XXPortalUser userKeyAdmin = new XXPortalUser(); - userKeyAdmin.setId(userProfile().getId()); - userKeyAdmin.setLoginId(userProfile().getLoginId()); - currentUserSession.setXXPortalUser(userKeyAdmin); - currentUserSession.setKeyAdmin(true); - } - - public void setupUser() { - RangerSecurityContext context = new RangerSecurityContext(); - context.setUserSession(new UserSessionBase()); - RangerContextHolder.setSecurityContext(context); - UserSessionBase currentUserSession = ContextUtil.getCurrentUserSession(); - XXPortalUser user = new XXPortalUser(); - user.setId(userProfile().getId()); - user.setLoginId(userProfile().getLoginId()); - currentUserSession.setXXPortalUser(user); - } - - private VXPortalUser userProfile() { - VXPortalUser userProfile = new VXPortalUser(); - userProfile.setEmailAddress("test@test.com"); - userProfile.setFirstName("user12"); - userProfile.setLastName("test12"); - userProfile.setLoginId(userLoginID); - userProfile.setPassword("usertest12323"); - userProfile.setUserSource(1); - userProfile.setPublicScreenName("testuser"); - userProfile.setId(userId); - return userProfile; - } - - private XXPortalUser xxPortalUser(VXPortalUser userProfile) { - XXPortalUser xxPortalUser = new XXPortalUser(); - xxPortalUser.setEmailAddress(userProfile.getEmailAddress()); - xxPortalUser.setFirstName(userProfile.getFirstName()); - xxPortalUser.setLastName(userProfile.getLastName()); - xxPortalUser.setLoginId(userProfile.getLoginId()); - xxPortalUser.setPassword(userProfile.getPassword()); - xxPortalUser.setUserSource(userProfile.getUserSource()); - xxPortalUser.setPublicScreenName(userProfile.getPublicScreenName()); - return xxPortalUser; - } - - public void setupRangerUserSyncUser() { - RangerSecurityContext context = new RangerSecurityContext(); - context.setUserSession(new UserSessionBase()); - RangerContextHolder.setSecurityContext(context); - UserSessionBase currentUserSession = ContextUtil.getCurrentUserSession(); - XXPortalUser user = new XXPortalUser(); - user.setId(1L); - user.setLoginId("rangerusersync"); - user.setEmailAddress("test@test.com"); - currentUserSession.setXXPortalUser(user); - currentUserSession.setUserAdmin(true); - } - - @After - public void destroySession() { - RangerSecurityContext context = new RangerSecurityContext(); - context.setUserSession(null); - RangerContextHolder.setSecurityContext(context); - } - - @Test - public void test01CreateUser() { - setup(); - XXPortalUserDao userDao = Mockito.mock(XXPortalUserDao.class); - XXPortalUserRoleDao roleDao = Mockito.mock(XXPortalUserRoleDao.class); - - VXPortalUser userProfile = userProfile(); - - Collection userRoleList = new ArrayList(); - userRoleList.add("ROLE_USER"); - - XXPortalUser user = new XXPortalUser(); - user.setEmailAddress(userProfile.getEmailAddress()); - user.setFirstName(userProfile.getFirstName()); - user.setLastName(userProfile.getLastName()); - user.setLoginId(userProfile.getLoginId()); - user.setPassword(userProfile.getPassword()); - user.setUserSource(userProfile.getUserSource()); - user.setPublicScreenName(userProfile.getPublicScreenName()); - user.setId(userProfile.getId()); - - XXPortalUserRole XXPortalUserRole = new XXPortalUserRole(); - XXPortalUserRole.setId(user.getId()); - XXPortalUserRole.setUserRole("ROLE_USER"); - List list = new ArrayList(); - list.add(XXPortalUserRole); - - Mockito.when(daoManager.getXXPortalUser()).thenReturn(userDao); - Mockito.when(userDao.create((XXPortalUser) Mockito.any())).thenReturn(user); - Mockito.when(daoManager.getXXPortalUserRole()).thenReturn(roleDao); - Mockito.when(roleDao.findByUserId(userId)).thenReturn(list); - Mockito.doNothing().when(rangerBizUtil).blockAuditorRoleUser(); - Mockito.when(userDao.findByLoginId(Mockito.anyString())).thenReturn(user); - XXPortalUser dbxxPortalUser = userMgr.createUser(userProfile, 1, userRoleList); - Assert.assertNotNull(dbxxPortalUser); - userId = dbxxPortalUser.getId(); - - Assert.assertEquals(userId, dbxxPortalUser.getId()); - Assert.assertEquals(userProfile.getFirstName(),dbxxPortalUser.getFirstName()); - Assert.assertEquals(userProfile.getFirstName(),dbxxPortalUser.getFirstName()); - Assert.assertEquals(userProfile.getLastName(),dbxxPortalUser.getLastName()); - Assert.assertEquals(userProfile.getLoginId(),dbxxPortalUser.getLoginId()); - Assert.assertEquals(userProfile.getEmailAddress(),dbxxPortalUser.getEmailAddress()); - Assert.assertEquals(userProfile.getPassword(),dbxxPortalUser.getPassword()); - - Mockito.verify(daoManager, Mockito.atLeast(1)).getXXPortalUser(); - Mockito.verify(daoManager).getXXPortalUserRole(); - } - - @Test - public void test02CreateUser() { - setup(); - XXPortalUserDao userDao = Mockito.mock(XXPortalUserDao.class); - XXPortalUserRoleDao roleDao = Mockito.mock(XXPortalUserRoleDao.class); - - VXPortalUser userProfile = userProfile(); - Collection userRoleList = new ArrayList(); - userRoleList.add("ROLE_USER"); - userProfile.setUserRoleList(userRoleList); - - XXPortalUser user = new XXPortalUser(); - user.setEmailAddress(userProfile.getEmailAddress()); - user.setFirstName(userProfile.getFirstName()); - user.setLastName(userProfile.getLastName()); - user.setLoginId(userProfile.getLoginId()); - user.setPassword(userProfile.getPassword()); - user.setUserSource(userProfile.getUserSource()); - user.setPublicScreenName(userProfile.getPublicScreenName()); - user.setId(userProfile.getId()); - - XXPortalUserRole XXPortalUserRole = new XXPortalUserRole(); - XXPortalUserRole.setId(user.getId()); - XXPortalUserRole.setUserRole("ROLE_USER"); - List list = new ArrayList(); - list.add(XXPortalUserRole); - - Mockito.when(daoManager.getXXPortalUser()).thenReturn(userDao); - Mockito.when(userDao.create((XXPortalUser) Mockito.any())).thenReturn(user); - Mockito.when(daoManager.getXXPortalUserRole()).thenReturn(roleDao); - Mockito.when(roleDao.findByUserId(userId)).thenReturn(list); - Mockito.doNothing().when(rangerBizUtil).blockAuditorRoleUser(); - Mockito.when(userDao.findByLoginId(Mockito.anyString())).thenReturn(user); - XXPortalUser dbxxPortalUser = userMgr.createUser(userProfile, 1); - userId = dbxxPortalUser.getId(); - - Assert.assertNotNull(dbxxPortalUser); - Assert.assertEquals(userId, dbxxPortalUser.getId()); - Assert.assertEquals(userProfile.getFirstName(),dbxxPortalUser.getFirstName()); - Assert.assertEquals(userProfile.getFirstName(),dbxxPortalUser.getFirstName()); - Assert.assertEquals(userProfile.getLastName(),dbxxPortalUser.getLastName()); - Assert.assertEquals(userProfile.getLoginId(),dbxxPortalUser.getLoginId()); - Assert.assertEquals(userProfile.getEmailAddress(),dbxxPortalUser.getEmailAddress()); - Assert.assertEquals(userProfile.getPassword(),dbxxPortalUser.getPassword()); - - Mockito.verify(daoManager, Mockito.atLeast(1)).getXXPortalUser(); - Mockito.verify(daoManager).getXXPortalUserRole(); - } - - @Test - public void test03ChangePasswordAsAdmin() { - setup(); - XXPortalUserDao userDao = Mockito.mock(XXPortalUserDao.class); - VXPortalUser userProfile = userProfile(); - - VXPasswordChange pwdChange = new VXPasswordChange(); - pwdChange.setId(userProfile.getId()); - pwdChange.setLoginId(userProfile.getLoginId()); - pwdChange.setOldPassword(userProfile.getPassword()); - pwdChange.setEmailAddress(userProfile.getEmailAddress()); - pwdChange.setUpdPassword(userProfile.getPassword()); - - XXPortalUser user = new XXPortalUser(); - - Mockito.when(daoManager.getXXPortalUser()).thenReturn(userDao); - Mockito.when(userDao.findByLoginId(Mockito.nullable(String.class))).thenReturn(user); - - XXPortalUserRoleDao xPortalUserRoleDao = Mockito.mock(XXPortalUserRoleDao.class); - Mockito.when(daoManager.getXXPortalUserRole()).thenReturn(xPortalUserRoleDao); - List xPortalUserRoleList = new ArrayList(); - XXPortalUserRole XXPortalUserRole = new XXPortalUserRole(); - XXPortalUserRole.setId(userId); - XXPortalUserRole.setUserId(userId); - XXPortalUserRole.setUserRole("ROLE_USER"); - xPortalUserRoleList.add(XXPortalUserRole); - XXUserPermissionDao xUserPermissionDao = Mockito.mock(XXUserPermissionDao.class); - XXGroupPermissionDao xGroupPermissionDao = Mockito.mock(XXGroupPermissionDao.class); - Mockito.when(daoManager.getXXUserPermission()).thenReturn(xUserPermissionDao); - Mockito.when(daoManager.getXXGroupPermission()).thenReturn(xGroupPermissionDao); - XXPortalUserRoleDao roleDao = Mockito.mock(XXPortalUserRoleDao.class); - Mockito.when(daoManager.getXXPortalUserRole()).thenReturn(roleDao); - Mockito.when(restErrorUtil.createRESTException(HttpServletResponse.SC_FORBIDDEN, "Logged-In user is not allowed to access requested user data", true)).thenThrow(new WebApplicationException()); - thrown.expect(WebApplicationException.class); - - VXResponse dbVXResponse = userMgr.changePassword(pwdChange); - Assert.assertNotNull(dbVXResponse); - Assert.assertEquals(userProfile.getStatus(),dbVXResponse.getStatusCode()); - - Mockito.verify(stringUtil).equals(Mockito.anyString(),Mockito.nullable(String.class)); - Mockito.verify(stringUtil).validatePassword(Mockito.anyString(),Mockito.any(String[].class)); - - XXPortalUser user2 = new XXPortalUser(); - user2.setId(userId); - Mockito.when(userDao.findByLoginId(Mockito.anyString())).thenReturn(user2); - VXPasswordChange invalidpwdChange = new VXPasswordChange(); - invalidpwdChange.setId(userProfile.getId()); - invalidpwdChange.setLoginId(userProfile.getLoginId()); - invalidpwdChange.setOldPassword("invalidOldPassword"); - invalidpwdChange.setEmailAddress(userProfile.getEmailAddress()); - invalidpwdChange.setUpdPassword(userProfile.getPassword()); - thrown.expect(WebApplicationException.class); - userMgr.changePassword(invalidpwdChange); - - XXPortalUser externalUser = new XXPortalUser(); - externalUser.setUserSource(RangerCommonEnums.USER_EXTERNAL); - Mockito.when(userDao.findByLoginId(Mockito.anyString())).thenReturn(externalUser); - VXResponse vXResponse = new VXResponse(); - vXResponse.setStatusCode(HttpServletResponse.SC_FORBIDDEN); - vXResponse.setMsgDesc("SECURITY:changePassword().Ranger External Users cannot change password. LoginId=" + pwdChange.getLoginId()); - Mockito.when(restErrorUtil.generateRESTException((VXResponse) Mockito.any())).thenReturn(new WebApplicationException()); - thrown.expect(WebApplicationException.class); - userMgr.changePassword(pwdChange); - } - - @Test - public void test04ChangePasswordAsKeyAdmin() { - setupKeyAdmin(); - XXPortalUserDao userDao = Mockito.mock(XXPortalUserDao.class); - VXPortalUser userProfile = userProfile(); - - VXPasswordChange pwdChange = new VXPasswordChange(); - pwdChange.setId(userProfile.getId()); - pwdChange.setLoginId(userProfile.getLoginId()); - pwdChange.setOldPassword(userProfile.getPassword()); - pwdChange.setEmailAddress(userProfile.getEmailAddress()); - pwdChange.setUpdPassword(userProfile.getPassword()); - - XXPortalUser userKeyAdmin = new XXPortalUser(); - userKeyAdmin.setId(userProfile.getId()); - userKeyAdmin.setLoginId(userProfile.getLoginId()); - Mockito.when(daoManager.getXXPortalUser()).thenReturn(userDao); - Mockito.when(userDao.findByLoginId(Mockito.anyString())).thenReturn(userKeyAdmin); - Mockito.when(stringUtil.equals(Mockito.anyString(), Mockito.nullable(String.class))).thenReturn(true); - Mockito.when(daoManager.getXXPortalUser()).thenReturn(userDao); - Mockito.when(stringUtil.validatePassword(Mockito.anyString(), Mockito.any(String[].class))).thenReturn(true); - - XXPortalUserRoleDao xPortalUserRoleDao = Mockito.mock(XXPortalUserRoleDao.class); - Mockito.when(daoManager.getXXPortalUserRole()).thenReturn(xPortalUserRoleDao); - List xPortalUserRoleList = new ArrayList(); - XXPortalUserRole XXPortalUserRole = new XXPortalUserRole(); - XXPortalUserRole.setId(userId); - XXPortalUserRole.setUserId(userId); - XXPortalUserRole.setUserRole("ROLE_USER"); - xPortalUserRoleList.add(XXPortalUserRole); - XXPortalUserRoleDao roleDao = Mockito.mock(XXPortalUserRoleDao.class); - Mockito.when(daoManager.getXXPortalUserRole()).thenReturn(roleDao); - Mockito.when(roleDao.findByParentId(Mockito.anyLong())).thenReturn(xPortalUserRoleList); - XXUserPermissionDao xUserPermissionDao = Mockito.mock(XXUserPermissionDao.class); - XXGroupPermissionDao xGroupPermissionDao = Mockito.mock(XXGroupPermissionDao.class); - Mockito.when(daoManager.getXXUserPermission()).thenReturn(xUserPermissionDao); - List xUserPermissionsList = new ArrayList(); - List xGroupPermissionList = new ArrayList(); - Mockito.when(xUserPermissionDao.findByUserPermissionIdAndIsAllowed(userProfile.getId())).thenReturn(xUserPermissionsList); - Mockito.when(daoManager.getXXGroupPermission()).thenReturn(xGroupPermissionDao); - Mockito.when(xGroupPermissionDao.findbyVXPortalUserId(userProfile.getId())).thenReturn(xGroupPermissionList); - VXResponse dbVXResponse = userMgr.changePassword(pwdChange); - Assert.assertNotNull(dbVXResponse); - Assert.assertEquals(userProfile.getStatus(),dbVXResponse.getStatusCode()); - - Mockito.verify(stringUtil).equals(Mockito.anyString(), Mockito.nullable(String.class)); - Mockito.verify(stringUtil).validatePassword(Mockito.anyString(), Mockito.any(String[].class)); - } - - @Test - public void test05ChangePasswordAsUser() { - setupUser(); - XXPortalUserDao userDao = Mockito.mock(XXPortalUserDao.class); - VXPortalUser userProfile = userProfile(); - - VXPasswordChange pwdChange = new VXPasswordChange(); - pwdChange.setId(userProfile.getId()); - pwdChange.setLoginId(userProfile.getLoginId()); - pwdChange.setOldPassword(userProfile.getPassword()); - pwdChange.setEmailAddress(userProfile.getEmailAddress()); - pwdChange.setUpdPassword(userProfile.getPassword()); - - XXPortalUser user = new XXPortalUser(); - user.setId(userProfile.getId()); - user.setLoginId(userProfile.getLoginId()); - Mockito.when(daoManager.getXXPortalUser()).thenReturn(userDao); - Mockito.when(userDao.findByLoginId(Mockito.anyString())).thenReturn(user); - Mockito.when(stringUtil.equals(Mockito.anyString(), Mockito.nullable(String.class))).thenReturn(true); - Mockito.when(daoManager.getXXPortalUser()).thenReturn(userDao); - Mockito.when(stringUtil.validatePassword(Mockito.anyString(), Mockito.any(String[].class))).thenReturn(true); - Mockito.when(userDao.findByLoginId(Mockito.anyString())).thenReturn(user); - XXPortalUserRoleDao xPortalUserRoleDao = Mockito.mock(XXPortalUserRoleDao.class); - Mockito.when(daoManager.getXXPortalUserRole()).thenReturn(xPortalUserRoleDao); - List xPortalUserRoleList = new ArrayList(); - XXPortalUserRole XXPortalUserRole = new XXPortalUserRole(); - XXPortalUserRole.setId(userId); - XXPortalUserRole.setUserId(userId); - XXPortalUserRole.setUserRole("ROLE_USER"); - xPortalUserRoleList.add(XXPortalUserRole); - XXUserPermissionDao xUserPermissionDao = Mockito.mock(XXUserPermissionDao.class); - XXGroupPermissionDao xGroupPermissionDao = Mockito.mock(XXGroupPermissionDao.class); - Mockito.when(daoManager.getXXUserPermission()).thenReturn(xUserPermissionDao); - List xUserPermissionsList = new ArrayList(); - List xGroupPermissionList = new ArrayList(); - Mockito.when(xUserPermissionDao.findByUserPermissionIdAndIsAllowed(userProfile.getId())).thenReturn(xUserPermissionsList); - Mockito.when(daoManager.getXXGroupPermission()).thenReturn(xGroupPermissionDao); - Mockito.when(xGroupPermissionDao.findbyVXPortalUserId(userProfile.getId())).thenReturn(xGroupPermissionList); - XXPortalUserRoleDao roleDao = Mockito.mock(XXPortalUserRoleDao.class); - Mockito.when(daoManager.getXXPortalUserRole()).thenReturn(roleDao); - Mockito.when(roleDao.findByParentId(Mockito.anyLong())).thenReturn(xPortalUserRoleList); - - VXResponse dbVXResponse = userMgr.changePassword(pwdChange); - Assert.assertNotNull(dbVXResponse); - Assert.assertEquals(userProfile.getStatus(),dbVXResponse.getStatusCode()); - - Mockito.verify(stringUtil).equals(Mockito.anyString(), Mockito.nullable(String.class)); - Mockito.verify(stringUtil).validatePassword(Mockito.anyString(),Mockito.any(String[].class)); - } - - @Test - public void test06ChangeEmailAddressAsAdmin() { - setup(); - XXPortalUserDao userDao = Mockito.mock(XXPortalUserDao.class); - XXPortalUserRoleDao roleDao = Mockito.mock(XXPortalUserRoleDao.class); - XXUserPermissionDao xUserPermissionDao = Mockito.mock(XXUserPermissionDao.class); - XXGroupPermissionDao xGroupPermissionDao = Mockito.mock(XXGroupPermissionDao.class); - XXModuleDefDao xModuleDefDao = Mockito.mock(XXModuleDefDao.class); - - XXModuleDef xModuleDef = new XXModuleDef(); - xModuleDef.setUpdatedByUserId(userId); - xModuleDef.setAddedByUserId(userId); - xModuleDef.setCreateTime(new Date()); - xModuleDef.setId(userId); - xModuleDef.setModule("Policy manager"); - xModuleDef.setUpdateTime(new Date()); - xModuleDef.setUrl("/policy manager"); - - VXPortalUser userProfile = userProfile(); - - XXPortalUser user = new XXPortalUser(); - user.setEmailAddress(userProfile.getEmailAddress()); - user.setFirstName(userProfile.getFirstName()); - user.setLastName(userProfile.getLastName()); - user.setLoginId(userProfile.getLoginId()); - String encryptedPwd = userMgr.encrypt(userProfile.getLoginId(),userProfile.getPassword()); - user.setPassword(encryptedPwd); - user.setUserSource(userProfile.getUserSource()); - user.setPublicScreenName(userProfile.getPublicScreenName()); - user.setId(userProfile.getId()); - - VXPasswordChange changeEmail = new VXPasswordChange(); - changeEmail.setEmailAddress("testuser@test.com"); - changeEmail.setId(user.getId()); - changeEmail.setLoginId(user.getLoginId()); - changeEmail.setOldPassword(userProfile.getPassword()); - - XXPortalUserRole XXPortalUserRole = new XXPortalUserRole(); - XXPortalUserRole.setId(userId); - XXPortalUserRole.setUserRole("ROLE_USER"); - List list = new ArrayList(); - list.add(XXPortalUserRole); - - List xUserPermissionsList = new ArrayList(); - XXUserPermission xUserPermissionObj = new XXUserPermission(); - xUserPermissionObj.setAddedByUserId(userId); - xUserPermissionObj.setCreateTime(new Date()); - xUserPermissionObj.setId(userId); - xUserPermissionObj.setIsAllowed(1); - xUserPermissionObj.setModuleId(1L); - xUserPermissionObj.setUpdatedByUserId(userId); - xUserPermissionObj.setUpdateTime(new Date()); - xUserPermissionObj.setUserId(userId); - xUserPermissionsList.add(xUserPermissionObj); - - List xGroupPermissionList = new ArrayList(); - XXGroupPermission xGroupPermissionObj = new XXGroupPermission(); - xGroupPermissionObj.setAddedByUserId(userId); - xGroupPermissionObj.setCreateTime(new Date()); - xGroupPermissionObj.setId(userId); - xGroupPermissionObj.setIsAllowed(1); - xGroupPermissionObj.setModuleId(1L); - xGroupPermissionObj.setUpdatedByUserId(userId); - xGroupPermissionObj.setUpdateTime(new Date()); - xGroupPermissionObj.setGroupId(userId); - xGroupPermissionList.add(xGroupPermissionObj); - - VXUserPermission userPermission = new VXUserPermission(); - userPermission.setId(1L); - userPermission.setIsAllowed(1); - userPermission.setModuleId(1L); - userPermission.setUserId(userId); - userPermission.setUserName("xyz"); - userPermission.setOwner("admin"); - - VXGroupPermission groupPermission = new VXGroupPermission(); - groupPermission.setId(1L); - groupPermission.setIsAllowed(1); - groupPermission.setModuleId(1L); - groupPermission.setGroupId(userId); - groupPermission.setGroupName("xyz"); - groupPermission.setOwner("admin"); - - Mockito.when(stringUtil.validateEmail(Mockito.anyString())).thenReturn(true); - Mockito.when(daoManager.getXXPortalUser()).thenReturn(userDao); - Mockito.when(daoManager.getXXPortalUserRole()).thenReturn(roleDao); - Mockito.when(roleDao.findByParentId(Mockito.anyLong())).thenReturn(list); - Mockito.when(daoManager.getXXUserPermission()).thenReturn(xUserPermissionDao); - Mockito.when(daoManager.getXXGroupPermission()).thenReturn(xGroupPermissionDao); - Mockito.when(xUserPermissionDao.findByUserPermissionIdAndIsAllowed(userProfile.getId())).thenReturn(xUserPermissionsList); - Mockito.when(xGroupPermissionDao.findbyVXPortalUserId(userProfile.getId())).thenReturn(xGroupPermissionList); - Mockito.when(xGroupPermissionService.populateViewBean(xGroupPermissionObj)).thenReturn(groupPermission); - Mockito.when(xUserPermissionService.populateViewBean(xUserPermissionObj)).thenReturn(userPermission); - Mockito.when(daoManager.getXXModuleDef()).thenReturn(xModuleDefDao); - Mockito.when(xModuleDefDao.findByModuleId(Mockito.anyLong())).thenReturn(xModuleDef); - - Mockito.when(daoManager.getXXPortalUser()).thenReturn(userDao); - Mockito.when(userDao.findByLoginId(Mockito.anyString())).thenReturn(user); - Mockito.when(daoManager.getXXPortalUser()).thenReturn(userDao); - Mockito.when(userDao.findByLoginId(Mockito.anyString())).thenReturn(user); - XXPortalUserRoleDao xPortalUserRoleDao = Mockito.mock(XXPortalUserRoleDao.class); - Mockito.when(daoManager.getXXPortalUserRole()).thenReturn(xPortalUserRoleDao); - List xPortalUserRoleList = new ArrayList(); - XXPortalUserRole.setId(userId); - XXPortalUserRole.setUserId(userId); - XXPortalUserRole.setUserRole("ROLE_USER"); - xPortalUserRoleList.add(XXPortalUserRole); - Mockito.when(daoManager.getXXUserPermission()).thenReturn(xUserPermissionDao); - Mockito.when(xUserPermissionDao.findByUserPermissionIdAndIsAllowed(userProfile.getId())).thenReturn(xUserPermissionsList); - Mockito.when(daoManager.getXXGroupPermission()).thenReturn(xGroupPermissionDao); - Mockito.when(xGroupPermissionDao.findbyVXPortalUserId(userProfile.getId())).thenReturn(xGroupPermissionList); - Mockito.when(daoManager.getXXPortalUserRole()).thenReturn(roleDao); - Mockito.when(roleDao.findByParentId(Mockito.anyLong())).thenReturn(xPortalUserRoleList); - Mockito.when(daoManager.getXXModuleDef()).thenReturn(xModuleDefDao); - Mockito.when(xModuleDefDao.findByModuleId(Mockito.anyLong())).thenReturn(xModuleDef); - Mockito.when(restErrorUtil.createRESTException(HttpServletResponse.SC_FORBIDDEN, "Logged-In user is not allowed to access requested user data", true)).thenThrow(new WebApplicationException()); - thrown.expect(WebApplicationException.class); - VXPortalUser dbVXPortalUser = userMgr.changeEmailAddress(user,changeEmail); - Assert.assertNotNull(dbVXPortalUser); - Assert.assertEquals(userId, dbVXPortalUser.getId()); - Assert.assertEquals(userProfile.getLastName(),dbVXPortalUser.getLastName()); - Assert.assertEquals(changeEmail.getLoginId(),dbVXPortalUser.getLoginId()); - Assert.assertEquals(changeEmail.getEmailAddress(),dbVXPortalUser.getEmailAddress()); - user.setUserSource(RangerCommonEnums.USER_APP); - dbVXPortalUser = userMgr.changeEmailAddress(user,changeEmail); - user.setUserSource(RangerCommonEnums.USER_EXTERNAL); - changeEmail.setEmailAddress(""); - dbVXPortalUser = userMgr.changeEmailAddress(user,changeEmail); - - Mockito.when(stringUtil.validateEmail(Mockito.anyString())).thenReturn(false); - changeEmail.setEmailAddress("test@123.com"); - Mockito.when(restErrorUtil.createRESTException("serverMsg.userMgrInvalidEmail",MessageEnums.INVALID_INPUT_DATA, changeEmail.getId(), "emailAddress", changeEmail.toString())).thenThrow(new WebApplicationException()); - thrown.expect(WebApplicationException.class); - userMgr.changeEmailAddress(user,changeEmail); - } - - @Test - public void test07ChangeEmailAddressAsKeyAdmin() { - setupKeyAdmin(); - XXPortalUserDao userDao = Mockito.mock(XXPortalUserDao.class); - XXPortalUserRoleDao roleDao = Mockito.mock(XXPortalUserRoleDao.class); - VXPortalUser userProfile = userProfile(); - - XXPortalUser userKeyAdmin = new XXPortalUser(); - userKeyAdmin.setEmailAddress(userProfile.getEmailAddress()); - userKeyAdmin.setFirstName(userProfile.getFirstName()); - userKeyAdmin.setLastName(userProfile.getLastName()); - userKeyAdmin.setLoginId(userProfile.getLoginId()); - String encryptedPwd = userMgr.encrypt(userProfile.getLoginId(),userProfile.getPassword()); - userKeyAdmin.setPassword(encryptedPwd); - userKeyAdmin.setUserSource(userProfile.getUserSource()); - userKeyAdmin.setPublicScreenName(userProfile.getPublicScreenName()); - userKeyAdmin.setId(userProfile.getId()); - - VXPasswordChange changeEmail = new VXPasswordChange(); - changeEmail.setEmailAddress("testuser@test.com"); - changeEmail.setId(userKeyAdmin.getId()); - changeEmail.setLoginId(userKeyAdmin.getLoginId()); - changeEmail.setOldPassword(userProfile.getPassword()); - - XXPortalUserRole XXPortalUserRole = new XXPortalUserRole(); - XXPortalUserRole.setId(userId); - XXPortalUserRole.setUserRole("ROLE_USER"); - List list = new ArrayList(); - list.add(XXPortalUserRole); - - List xUserPermissionsList = new ArrayList(); - XXUserPermission xUserPermissionObj = new XXUserPermission(); - xUserPermissionObj.setAddedByUserId(userId); - xUserPermissionObj.setCreateTime(new Date()); - xUserPermissionObj.setId(userId); - xUserPermissionObj.setIsAllowed(1); - xUserPermissionObj.setModuleId(1L); - xUserPermissionObj.setUpdatedByUserId(userId); - xUserPermissionObj.setUpdateTime(new Date()); - xUserPermissionObj.setUserId(userId); - xUserPermissionsList.add(xUserPermissionObj); - - List xGroupPermissionList = new ArrayList(); - XXGroupPermission xGroupPermissionObj = new XXGroupPermission(); - xGroupPermissionObj.setAddedByUserId(userId); - xGroupPermissionObj.setCreateTime(new Date()); - xGroupPermissionObj.setId(userId); - xGroupPermissionObj.setIsAllowed(1); - xGroupPermissionObj.setModuleId(1L); - xGroupPermissionObj.setUpdatedByUserId(userId); - xGroupPermissionObj.setUpdateTime(new Date()); - xGroupPermissionObj.setGroupId(userId); - xGroupPermissionList.add(xGroupPermissionObj); - - VXUserPermission userPermission = new VXUserPermission(); - userPermission.setId(1L); - userPermission.setIsAllowed(1); - userPermission.setModuleId(1L); - userPermission.setUserId(userId); - userPermission.setUserName("xyz"); - userPermission.setOwner("admin"); - - VXGroupPermission groupPermission = new VXGroupPermission(); - groupPermission.setId(1L); - groupPermission.setIsAllowed(1); - groupPermission.setModuleId(1L); - groupPermission.setGroupId(userId); - groupPermission.setGroupName("xyz"); - groupPermission.setOwner("admin"); - - Mockito.when(stringUtil.validateEmail(Mockito.anyString())).thenReturn(true); - Mockito.when(stringUtil.equals(Mockito.anyString(), Mockito.anyString())).thenReturn(true); - Mockito.when(stringUtil.normalizeEmail(Mockito.anyString())).thenReturn(changeEmail.getEmailAddress()); - Mockito.when(daoManager.getXXPortalUser()).thenReturn(userDao); - Mockito.when(daoManager.getXXPortalUserRole()).thenReturn(roleDao); - Mockito.when(roleDao.findByParentId(Mockito.anyLong())).thenReturn(list); - Mockito.when(daoManager.getXXPortalUser()).thenReturn(userDao); - Mockito.when(userDao.findByLoginId(Mockito.anyString())).thenReturn(userKeyAdmin); - XXPortalUserRoleDao xPortalUserRoleDao = Mockito.mock(XXPortalUserRoleDao.class); - Mockito.when(daoManager.getXXPortalUserRole()).thenReturn(xPortalUserRoleDao); - List xPortalUserRoleList = new ArrayList(); - XXPortalUserRole.setId(userId); - XXPortalUserRole.setUserId(userId); - XXPortalUserRole.setUserRole("ROLE_USER"); - xPortalUserRoleList.add(XXPortalUserRole); - Mockito.when(daoManager.getXXPortalUserRole()).thenReturn(roleDao); - Mockito.when(roleDao.findByParentId(Mockito.anyLong())).thenReturn(xPortalUserRoleList); - XXUserPermissionDao xUserPermissionDao = Mockito.mock(XXUserPermissionDao.class); - XXGroupPermissionDao xGroupPermissionDao = Mockito.mock(XXGroupPermissionDao.class); - Mockito.when(daoManager.getXXUserPermission()).thenReturn(xUserPermissionDao); - Mockito.when(xUserPermissionDao.findByUserPermissionIdAndIsAllowed(userProfile.getId())).thenReturn(xUserPermissionsList); - Mockito.when(daoManager.getXXGroupPermission()).thenReturn(xGroupPermissionDao); - Mockito.when(xGroupPermissionDao.findbyVXPortalUserId(userProfile.getId())).thenReturn(xGroupPermissionList); - Mockito.when(xGroupPermissionService.populateViewBean(xGroupPermissionObj)).thenReturn(groupPermission); - Mockito.when(xUserPermissionService.populateViewBean(xUserPermissionObj)).thenReturn(userPermission); - XXModuleDefDao xModuleDefDao = Mockito.mock(XXModuleDefDao.class); - XXModuleDef xModuleDef = new XXModuleDef(); - xModuleDef.setModule("Users/Groups"); - Mockito.when(daoManager.getXXModuleDef()).thenReturn(xModuleDefDao); - Mockito.when(xModuleDefDao.findByModuleId(groupPermission.getModuleId())).thenReturn(xModuleDef); - VXPortalUser dbVXPortalUser = userMgr.changeEmailAddress(userKeyAdmin,changeEmail); - Assert.assertNotNull(dbVXPortalUser); - Assert.assertEquals(userId, dbVXPortalUser.getId()); - Assert.assertEquals(userProfile.getLastName(),dbVXPortalUser.getLastName()); - Assert.assertEquals(changeEmail.getLoginId(),dbVXPortalUser.getLoginId()); - Assert.assertEquals(changeEmail.getEmailAddress(),dbVXPortalUser.getEmailAddress()); - } - - @Test - public void test08ChangeEmailAddressAsUser() { - setupUser(); - XXPortalUserDao userDao = Mockito.mock(XXPortalUserDao.class); - XXPortalUserRoleDao roleDao = Mockito.mock(XXPortalUserRoleDao.class); - XXUserPermissionDao xUserPermissionDao = Mockito.mock(XXUserPermissionDao.class); - XXGroupPermissionDao xGroupPermissionDao = Mockito.mock(XXGroupPermissionDao.class); - XXModuleDefDao xModuleDefDao = Mockito.mock(XXModuleDefDao.class); - XXModuleDef xModuleDef = Mockito.mock(XXModuleDef.class); - VXPortalUser userProfile = userProfile(); - - XXPortalUser user = new XXPortalUser(); - user.setEmailAddress(userProfile.getEmailAddress()); - user.setFirstName(userProfile.getFirstName()); - user.setLastName(userProfile.getLastName()); - user.setLoginId(userProfile.getLoginId()); - String encryptedPwd = userMgr.encrypt(userProfile.getLoginId(),userProfile.getPassword()); - user.setPassword(encryptedPwd); - user.setUserSource(userProfile.getUserSource()); - user.setPublicScreenName(userProfile.getPublicScreenName()); - user.setId(userProfile.getId()); - - VXPasswordChange changeEmail = new VXPasswordChange(); - changeEmail.setEmailAddress("testuser@test.com"); - changeEmail.setId(user.getId()); - changeEmail.setLoginId(user.getLoginId()); - changeEmail.setOldPassword(userProfile.getPassword()); - - XXPortalUserRole XXPortalUserRole = new XXPortalUserRole(); - XXPortalUserRole.setId(userId); - XXPortalUserRole.setUserRole("ROLE_USER"); - List list = new ArrayList(); - list.add(XXPortalUserRole); - - List xUserPermissionsList = new ArrayList(); - XXUserPermission xUserPermissionObj = new XXUserPermission(); - xUserPermissionObj.setAddedByUserId(userId); - xUserPermissionObj.setCreateTime(new Date()); - xUserPermissionObj.setId(userId); - xUserPermissionObj.setIsAllowed(1); - xUserPermissionObj.setModuleId(1L); - xUserPermissionObj.setUpdatedByUserId(userId); - xUserPermissionObj.setUpdateTime(new Date()); - xUserPermissionObj.setUserId(userId); - xUserPermissionsList.add(xUserPermissionObj); - - List xGroupPermissionList = new ArrayList(); - XXGroupPermission xGroupPermissionObj = new XXGroupPermission(); - xGroupPermissionObj.setAddedByUserId(userId); - xGroupPermissionObj.setCreateTime(new Date()); - xGroupPermissionObj.setId(userId); - xGroupPermissionObj.setIsAllowed(1); - xGroupPermissionObj.setModuleId(1L); - xGroupPermissionObj.setUpdatedByUserId(userId); - xGroupPermissionObj.setUpdateTime(new Date()); - xGroupPermissionObj.setGroupId(userId); - xGroupPermissionList.add(xGroupPermissionObj); - - VXUserPermission userPermission = new VXUserPermission(); - userPermission.setId(1L); - userPermission.setIsAllowed(1); - userPermission.setModuleId(1L); - userPermission.setUserId(userId); - userPermission.setUserName("xyz"); - userPermission.setOwner("admin"); - - VXGroupPermission groupPermission = new VXGroupPermission(); - groupPermission.setId(1L); - groupPermission.setIsAllowed(1); - groupPermission.setModuleId(1L); - groupPermission.setGroupId(userId); - groupPermission.setGroupName("xyz"); - groupPermission.setOwner("admin"); - - Mockito.when(stringUtil.validateEmail(Mockito.anyString())).thenReturn(true); - Mockito.when(stringUtil.equals(Mockito.anyString(), Mockito.anyString())).thenReturn(true); - Mockito.when(stringUtil.normalizeEmail(Mockito.anyString())).thenReturn(changeEmail.getEmailAddress()); - Mockito.when(daoManager.getXXPortalUser()).thenReturn(userDao); - Mockito.when(daoManager.getXXPortalUserRole()).thenReturn(roleDao); - Mockito.when(roleDao.findByParentId(Mockito.anyLong())).thenReturn(list); - Mockito.when(daoManager.getXXUserPermission()).thenReturn(xUserPermissionDao); - Mockito.when(daoManager.getXXGroupPermission()).thenReturn(xGroupPermissionDao); - Mockito.when(xUserPermissionDao.findByUserPermissionIdAndIsAllowed(userProfile.getId())).thenReturn(xUserPermissionsList); - Mockito.when(xGroupPermissionDao.findbyVXPortalUserId(userProfile.getId())).thenReturn(xGroupPermissionList); - Mockito.when(xGroupPermissionService.populateViewBean(xGroupPermissionObj)).thenReturn(groupPermission); - Mockito.when(xUserPermissionService.populateViewBean(xUserPermissionObj)).thenReturn(userPermission); - Mockito.when(daoManager.getXXModuleDef()).thenReturn(xModuleDefDao); - Mockito.when(xModuleDefDao.findByModuleId(Mockito.anyLong())).thenReturn(xModuleDef); - Mockito.when(daoManager.getXXPortalUser()).thenReturn(userDao); - Mockito.when(userDao.findByLoginId(Mockito.anyString())).thenReturn(user); - XXPortalUserRoleDao xPortalUserRoleDao = Mockito.mock(XXPortalUserRoleDao.class); - Mockito.when(daoManager.getXXPortalUserRole()).thenReturn(xPortalUserRoleDao); - List xPortalUserRoleList = new ArrayList(); - XXPortalUserRole.setId(userId); - XXPortalUserRole.setUserId(userId); - XXPortalUserRole.setUserRole("ROLE_USER"); - xPortalUserRoleList.add(XXPortalUserRole); - Mockito.when(daoManager.getXXUserPermission()).thenReturn(xUserPermissionDao); - Mockito.when(xUserPermissionDao.findByUserPermissionIdAndIsAllowed(userProfile.getId())).thenReturn(xUserPermissionsList); - Mockito.when(daoManager.getXXGroupPermission()).thenReturn(xGroupPermissionDao); - Mockito.when(xGroupPermissionDao.findbyVXPortalUserId(userProfile.getId())).thenReturn(xGroupPermissionList); - Mockito.when(daoManager.getXXPortalUserRole()).thenReturn(roleDao); - Mockito.when(roleDao.findByParentId(Mockito.anyLong())).thenReturn(xPortalUserRoleList); - Mockito.when(daoManager.getXXModuleDef()).thenReturn(xModuleDefDao); - Mockito.when(xModuleDefDao.findByModuleId(Mockito.anyLong())).thenReturn(xModuleDef); - VXPortalUser dbVXPortalUser = userMgr.changeEmailAddress(user,changeEmail); - Assert.assertNotNull(dbVXPortalUser); - Assert.assertEquals(userId, dbVXPortalUser.getId()); - Assert.assertEquals(userProfile.getLastName(),dbVXPortalUser.getLastName()); - Assert.assertEquals(changeEmail.getLoginId(),dbVXPortalUser.getLoginId()); - Assert.assertEquals(changeEmail.getEmailAddress(),dbVXPortalUser.getEmailAddress()); - - user.setId(userProfile.getId()); - user.setLoginId("usertest123"); - String encryptCred = userMgr.encrypt(user.getLoginId(), userProfile.getPassword()); - user.setPassword(encryptCred); - Mockito.when(stringUtil.equals(Mockito.anyString(), Mockito.nullable(String.class))).thenReturn(true); - Mockito.when(stringUtil.equals(Mockito.anyString(), Mockito.anyString())).thenReturn(false); - Mockito.when(restErrorUtil.createRESTException("serverMsg.userMgrWrongPassword",MessageEnums.OPER_NO_PERMISSION, null, null, changeEmail.toString())).thenThrow(new WebApplicationException()); - thrown.expect(WebApplicationException.class); - userMgr.changeEmailAddress(user, changeEmail); - } - - @Test - public void test09CreateUser() { - setup(); - XXPortalUserDao userDao = Mockito.mock(XXPortalUserDao.class); - XXPortalUserRoleDao roleDao = Mockito.mock(XXPortalUserRoleDao.class); - XXUserPermissionDao xUserPermissionDao = Mockito.mock(XXUserPermissionDao.class); - XXGroupPermissionDao xGroupPermissionDao = Mockito.mock(XXGroupPermissionDao.class); - - XXPortalUser user = new XXPortalUser(); - VXPortalUser userProfile = userProfile(); - - XXPortalUserRole XXPortalUserRole = new XXPortalUserRole(); - XXPortalUserRole.setId(userId); - XXPortalUserRole.setUserRole("ROLE_USER"); - List list = new ArrayList(); - list.add(XXPortalUserRole); - - List xUserPermissionsList = new ArrayList(); - XXUserPermission xUserPermissionObj = new XXUserPermission(); - xUserPermissionObj.setAddedByUserId(userId); - xUserPermissionObj.setCreateTime(new Date()); - xUserPermissionObj.setId(userId); - xUserPermissionObj.setIsAllowed(1); - xUserPermissionObj.setModuleId(1L); - xUserPermissionObj.setUpdatedByUserId(userId); - xUserPermissionObj.setUpdateTime(new Date()); - xUserPermissionObj.setUserId(userId); - xUserPermissionsList.add(xUserPermissionObj); - - List xGroupPermissionList = new ArrayList(); - XXGroupPermission xGroupPermissionObj = new XXGroupPermission(); - xGroupPermissionObj.setAddedByUserId(userId); - xGroupPermissionObj.setCreateTime(new Date()); - xGroupPermissionObj.setId(userId); - xGroupPermissionObj.setIsAllowed(1); - xGroupPermissionObj.setModuleId(1L); - xGroupPermissionObj.setUpdatedByUserId(userId); - xGroupPermissionObj.setUpdateTime(new Date()); - xGroupPermissionObj.setGroupId(userId); - xGroupPermissionList.add(xGroupPermissionObj); - - Mockito.when(daoManager.getXXPortalUser()).thenReturn(userDao); - Mockito.when(userDao.create((XXPortalUser) Mockito.any())).thenReturn(user); - Mockito.when(daoManager.getXXPortalUserRole()).thenReturn(roleDao); - - Mockito.when(daoManager.getXXUserPermission()).thenReturn(xUserPermissionDao); - - Mockito.when(daoManager.getXXGroupPermission()).thenReturn(xGroupPermissionDao); - Mockito.doNothing().when(rangerBizUtil).blockAuditorRoleUser(); - Mockito.when(userDao.findByLoginId(Mockito.anyString())).thenReturn(user); - VXPortalUser dbVXPortalUser = userMgr.createUser(userProfile); - Assert.assertNotNull(dbVXPortalUser); - Assert.assertEquals(user.getId(), dbVXPortalUser.getId()); - Assert.assertEquals(user.getFirstName(), dbVXPortalUser.getFirstName()); - Assert.assertEquals(user.getLastName(), dbVXPortalUser.getLastName()); - Assert.assertEquals(user.getLoginId(), dbVXPortalUser.getLoginId()); - Assert.assertEquals(user.getEmailAddress(),dbVXPortalUser.getEmailAddress()); - Assert.assertEquals(user.getPassword(), dbVXPortalUser.getPassword()); - - Mockito.verify(daoManager, Mockito.atLeast(1)).getXXPortalUser(); - Mockito.verify(daoManager).getXXUserPermission(); - Mockito.verify(daoManager).getXXGroupPermission(); - - Collection reqRoleList = new ArrayList(); - reqRoleList.add(null); - userProfile.setUserRoleList(reqRoleList); - dbVXPortalUser = userMgr.createUser(userProfile); - } - - @Test - public void test10CreateDefaultAccountUser() { - setup(); - XXPortalUserDao userDao = Mockito.mock(XXPortalUserDao.class); - XXPortalUserRoleDao roleDao = Mockito.mock(XXPortalUserRoleDao.class); - VXPortalUser userProfile = userProfile(); - Collection userRoleList = new ArrayList(); - userRoleList.add("ROLE_USER"); - userProfile.setUserRoleList(userRoleList); - XXPortalUser user = new XXPortalUser(); - user.setEmailAddress(userProfile.getEmailAddress()); - XXPortalUserRole XXPortalUserRole = new XXPortalUserRole(); - XXPortalUserRole.setId(userId); - XXPortalUserRole.setUserRole("ROLE_USER"); - - List list = new ArrayList(); - list.add(XXPortalUserRole); - - Mockito.when(daoManager.getXXPortalUser()).thenReturn(userDao); - Mockito.when(userDao.findByLoginId(Mockito.anyString())).thenReturn(user); - Mockito.when(daoManager.getXXPortalUserRole()).thenReturn(roleDao); - Mockito.doNothing().when(rangerBizUtil).blockAuditorRoleUser(); - userProfile.setOtherAttributes("other1"); - VXPortalUser dbVXPortalUser = userMgr.createDefaultAccountUser(userProfile); - Assert.assertNotNull(dbVXPortalUser); - Assert.assertEquals(user.getId(), dbVXPortalUser.getId()); - Assert.assertEquals(user.getFirstName(), dbVXPortalUser.getFirstName()); - Assert.assertEquals(user.getLastName(), dbVXPortalUser.getLastName()); - Assert.assertEquals(user.getLoginId(), dbVXPortalUser.getLoginId()); - Assert.assertEquals(user.getEmailAddress(),dbVXPortalUser.getEmailAddress()); - Assert.assertEquals(user.getPassword(), dbVXPortalUser.getPassword()); - Mockito.verify(daoManager, Mockito.atLeast(1)).getXXPortalUser(); - Mockito.verify(daoManager, Mockito.atLeast(1)).getXXPortalUserRole(); - } - - @Test - public void test11CreateDefaultAccountUser() { - destroySession(); - setup(); - XXPortalUserDao userDao = Mockito.mock(XXPortalUserDao.class); - XXPortalUserRoleDao roleDao = Mockito.mock(XXPortalUserRoleDao.class); - VXPortalUser userProfile = userProfile(); - userProfile.setStatus(RangerCommonEnums.USER_EXTERNAL); - Collection userRoleList = new ArrayList(); - userRoleList.add("ROLE_USER"); - userProfile.setUserRoleList(userRoleList); - XXPortalUser user = new XXPortalUser(); - user.setEmailAddress(userProfile.getEmailAddress()); - user.setUserSource(RangerCommonEnums.USER_EXTERNAL); - XXPortalUserRole XXPortalUserRole = new XXPortalUserRole(); - XXPortalUserRole.setId(userId); - XXPortalUserRole.setUserRole("ROLE_USER"); - - List list = new ArrayList(); - list.add(XXPortalUserRole); - - Mockito.when(daoManager.getXXPortalUser()).thenReturn(userDao); - Mockito.when(userDao.findByLoginId(Mockito.anyString())).thenReturn(null, user); - Mockito.when(userDao.findByEmailAddress(Mockito.anyString())).thenReturn(null); - Mockito.when(daoManager.getXXPortalUserRole()).thenReturn(roleDao); - Mockito.when(userDao.create((XXPortalUser) Mockito.any())).thenReturn(user); - Mockito.doNothing().when(rangerBizUtil).blockAuditorRoleUser(); - VXPortalUser dbVXPortalUser = userMgr.createDefaultAccountUser(userProfile); - Assert.assertNotNull(dbVXPortalUser); - Assert.assertEquals(user.getId(), dbVXPortalUser.getId()); - Assert.assertEquals(user.getFirstName(), dbVXPortalUser.getFirstName()); - Assert.assertEquals(user.getLastName(), dbVXPortalUser.getLastName()); - Assert.assertEquals(user.getLoginId(), dbVXPortalUser.getLoginId()); - Assert.assertEquals(user.getEmailAddress(),dbVXPortalUser.getEmailAddress()); - Assert.assertEquals(user.getPassword(), dbVXPortalUser.getPassword()); - Mockito.verify(daoManager, Mockito.atLeast(1)).getXXPortalUser(); - Mockito.verify(daoManager, Mockito.atLeast(1)).getXXPortalUserRole(); - } - - @Test - public void test12CreateDefaultAccountUser() { - setup(); - XXPortalUserDao userDao = Mockito.mock(XXPortalUserDao.class); - XXPortalUserRoleDao roleDao = Mockito.mock(XXPortalUserRoleDao.class); - VXPortalUser userProfile = userProfile(); - userProfile.setStatus(RangerCommonEnums.USER_EXTERNAL); - Collection userRoleList = new ArrayList(); - userRoleList.add("ROLE_USER"); - userProfile.setUserRoleList(userRoleList); - XXPortalUser xxPortalUser = new XXPortalUser(); - xxPortalUser.setEmailAddress(userProfile.getEmailAddress()); - xxPortalUser.setUserSource(RangerCommonEnums.USER_EXTERNAL); - XXPortalUserRole XXPortalUserRole = new XXPortalUserRole(); - XXPortalUserRole.setId(userId); - XXPortalUserRole.setUserRole("ROLE_USER"); - - List list = new ArrayList(); - list.add(XXPortalUserRole); - - Mockito.when(daoManager.getXXPortalUser()).thenReturn(userDao); - Mockito.when(userDao.findByLoginId(Mockito.anyString())).thenReturn(xxPortalUser); - Mockito.when(daoManager.getXXPortalUserRole()).thenReturn(roleDao); - Mockito.doNothing().when(rangerBizUtil).blockAuditorRoleUser(); - userProfile.setPassword(""); - userProfile.setEmailAddress(null); - VXPortalUser dbVXPortalUser = userMgr.createDefaultAccountUser(userProfile); - Assert.assertNotNull(dbVXPortalUser); - Assert.assertEquals(xxPortalUser.getId(), dbVXPortalUser.getId()); - Assert.assertEquals(xxPortalUser.getFirstName(), dbVXPortalUser.getFirstName()); - Assert.assertEquals(xxPortalUser.getLastName(), dbVXPortalUser.getLastName()); - Assert.assertEquals(xxPortalUser.getLoginId(), dbVXPortalUser.getLoginId()); - Assert.assertEquals(xxPortalUser.getEmailAddress(),dbVXPortalUser.getEmailAddress()); - Assert.assertEquals(xxPortalUser.getPassword(), dbVXPortalUser.getPassword()); - Mockito.verify(daoManager, Mockito.atLeast(1)).getXXPortalUser(); - Mockito.verify(daoManager, Mockito.atLeast(1)).getXXPortalUserRole(); - } - - @Test - public void test13IsUserInRole() { - XXPortalUserRoleDao roleDao = Mockito.mock(XXPortalUserRoleDao.class); - XXPortalUserRole XXPortalUserRole = new XXPortalUserRole(); - XXPortalUserRole.setId(userId); - XXPortalUserRole.setUserRole("ROLE_USER"); - List list = new ArrayList(); - list.add(XXPortalUserRole); - Mockito.when(daoManager.getXXPortalUserRole()).thenReturn(roleDao); - Mockito.when(roleDao.findByRoleUserId(userId, "ROLE_USER")).thenReturn(XXPortalUserRole); - boolean isValue = userMgr.isUserInRole(userId, "ROLE_USER"); - Assert.assertTrue(isValue); - Mockito.when(roleDao.findByRoleUserId(userId, "ROLE_USER")).thenReturn(null); - isValue = userMgr.isUserInRole(userId, "ROLE_USER"); - Assert.assertFalse(isValue); - } - - @Test - public void test14UpdateUserWithPass() { - setup(); - XXPortalUserDao userDao = Mockito.mock(XXPortalUserDao.class); - VXPortalUser userProfile = userProfile(); - userProfile.setPassword("password1234"); - XXPortalUser user = new XXPortalUser(); - user.setId(userProfile.getId()); - user.setLoginId(userProfile.getLoginId()); - user.setEmailAddress(userProfile.getEmailAddress()); - user.setLoginId(userProfile.getLoginId()); - String encryptedPwd = userMgr.encrypt(userProfile.getLoginId(),userProfile.getPassword()); - user.setPassword(encryptedPwd); - Mockito.when(daoManager.getXXPortalUser()).thenReturn(userDao); - Mockito.when(userDao.getById(userProfile.getId())).thenReturn(user); - Mockito.when(restErrorUtil.createRESTException(HttpServletResponse.SC_FORBIDDEN, "Logged-In user is not allowed to access requested user data", true)).thenThrow(new WebApplicationException()); - thrown.expect(WebApplicationException.class); - XXPortalUser dbXXPortalUser = userMgr.updateUserWithPass(userProfile); - Assert.assertNotNull(dbXXPortalUser); - Assert.assertEquals(userId, dbXXPortalUser.getId()); - Assert.assertEquals(userProfile.getFirstName(),dbXXPortalUser.getFirstName()); - Assert.assertEquals(userProfile.getFirstName(),dbXXPortalUser.getFirstName()); - Assert.assertEquals(userProfile.getLastName(),dbXXPortalUser.getLastName()); - Assert.assertEquals(userProfile.getLoginId(),dbXXPortalUser.getLoginId()); - Assert.assertEquals(userProfile.getEmailAddress(),dbXXPortalUser.getEmailAddress()); - Assert.assertEquals(encryptedPwd, dbXXPortalUser.getPassword()); - Mockito.when(userDao.getById(userProfile.getId())).thenReturn(null); - dbXXPortalUser = userMgr.updateUserWithPass(userProfile); - Assert.assertNull(dbXXPortalUser); - } - - @Test - public void test15searchUsers() { - Query query = Mockito.mock(Query.class); - EntityManager entityManager = Mockito.mock(EntityManager.class); - SearchCriteria searchCriteria = new SearchCriteria(); - searchCriteria.setDistinct(true); - searchCriteria.setGetChildren(true); - searchCriteria.setGetCount(true); - searchCriteria.setMaxRows(12); - searchCriteria.setOwnerId(userId); - searchCriteria.setStartIndex(1); - searchCriteria.setSortBy("userId"); - searchCriteria.setSortType("asc"); - Long count = 1l; - Mockito.when(daoManager.getEntityManager()).thenReturn(entityManager); - Mockito.when(entityManager.createQuery(Mockito.anyString())).thenReturn(query); - Mockito.when(query.getSingleResult()).thenReturn(count); - - VXPortalUserList dbVXPortalUserList = userMgr.searchUsers(searchCriteria); - Assert.assertNotNull(dbVXPortalUserList); - searchCriteria.setSortBy("loginId"); - dbVXPortalUserList = userMgr.searchUsers(searchCriteria); - Assert.assertNotNull(dbVXPortalUserList); - searchCriteria.setSortBy("emailAddress"); - dbVXPortalUserList = userMgr.searchUsers(searchCriteria); - Assert.assertNotNull(dbVXPortalUserList); - searchCriteria.setSortBy("firstName"); - dbVXPortalUserList = userMgr.searchUsers(searchCriteria); - Assert.assertNotNull(dbVXPortalUserList); - searchCriteria.setSortBy("lastName"); - dbVXPortalUserList = userMgr.searchUsers(searchCriteria); - Assert.assertNotNull(dbVXPortalUserList); - searchCriteria.setSortBy("source"); - searchCriteria.setSortType(""); - dbVXPortalUserList = userMgr.searchUsers(searchCriteria); - Assert.assertNotNull(dbVXPortalUserList); - searchCriteria.setSortBy(""); - searchCriteria.setSortType("desc"); - dbVXPortalUserList = userMgr.searchUsers(searchCriteria); - Assert.assertNotNull(dbVXPortalUserList); - - VXPortalUser userProfile = userProfile(); - XXPortalUser user = new XXPortalUser(); - user.setId(userProfile.getId()); - user.setLoginId(userProfile.getLoginId()); - user.setEmailAddress(userProfile.getEmailAddress()); - user.setLoginId(userProfile.getLoginId()); - List resultList = new ArrayList(); - resultList.add(user); - Mockito.when(query.getResultList()).thenReturn(resultList); - dbVXPortalUserList = userMgr.searchUsers(searchCriteria); - Assert.assertNotNull(dbVXPortalUserList); - - count = 0l; - Mockito.when(query.getSingleResult()).thenReturn(count); - dbVXPortalUserList = userMgr.searchUsers(searchCriteria); - Assert.assertNotNull(dbVXPortalUserList); - } - - @Test - public void test16FindByEmailAddress() { - XXPortalUserDao userDao = Mockito.mock(XXPortalUserDao.class); - - XXPortalUser user = new XXPortalUser(); - - String emailId = "test001user@apache.org"; - Mockito.when(daoManager.getXXPortalUser()).thenReturn(userDao); - Mockito.when(userDao.findByEmailAddress(emailId)).thenReturn(user); - - XXPortalUser dbXXPortalUser = userMgr.findByEmailAddress(emailId); - Assert.assertNotNull(dbXXPortalUser); - Assert.assertNotEquals(emailId, dbXXPortalUser.getEmailAddress()); - - Mockito.verify(daoManager).getXXPortalUser(); - } - - @Test - public void test17GetRolesForUser() { - XXPortalUserRoleDao roleDao = Mockito.mock(XXPortalUserRoleDao.class); - VXPortalUser userProfile = userProfile(); - - XXPortalUser user = new XXPortalUser(); - user.setEmailAddress(userProfile.getEmailAddress()); - user.setFirstName(userProfile.getFirstName()); - user.setLastName(userProfile.getLastName()); - user.setLoginId(userProfile.getLoginId()); - user.setPassword(userProfile.getPassword()); - user.setUserSource(userProfile.getUserSource()); - user.setPublicScreenName(userProfile.getPublicScreenName()); - user.setId(userProfile.getId()); - - XXPortalUserRole XXPortalUserRole = new XXPortalUserRole(); - XXPortalUserRole.setId(user.getId()); - XXPortalUserRole.setUserRole("ROLE_USER"); - List list = new ArrayList(); - list.add(XXPortalUserRole); - - Mockito.when(daoManager.getXXPortalUserRole()).thenReturn(roleDao); - Mockito.when(roleDao.findByUserId(userId)).thenReturn(list); - - Collection stringReturn = userMgr.getRolesForUser(user); - Assert.assertNotNull(stringReturn); - - Mockito.verify(daoManager).getXXPortalUserRole(); - } - - @Test - public void test18DeleteUserRole() { - setup(); - XXPortalUserRoleDao roleDao = Mockito.mock(XXPortalUserRoleDao.class); - - XXPortalUserRole XXPortalUserRole = new XXPortalUserRole(); - String userRole = "ROLE_USER"; - XXPortalUser user = new XXPortalUser(); - XXPortalUserRole.setId(user.getId()); - XXPortalUserRole.setUserRole("ROLE_USER"); - List list = new ArrayList(); - list.add(XXPortalUserRole); - - Mockito.when(daoManager.getXXPortalUserRole()).thenReturn(roleDao); - Mockito.when(roleDao.findByUserId(userId)).thenReturn(list); - - boolean deleteValue = userMgr.deleteUserRole(userId, userRole); - Assert.assertTrue(deleteValue); - } - - @Test - public void test19DeactivateUser() { - setup(); - XXPortalUserDao userDao = Mockito.mock(XXPortalUserDao.class); - XXPortalUserRoleDao roleDao = Mockito.mock(XXPortalUserRoleDao.class); - XXUserPermissionDao xUserPermissionDao = Mockito.mock(XXUserPermissionDao.class); - XXGroupPermissionDao xGroupPermissionDao = Mockito.mock(XXGroupPermissionDao.class); - VXGroupPermission vXGroupPermission = Mockito.mock(VXGroupPermission.class); - XXModuleDefDao xModuleDefDao = Mockito.mock(XXModuleDefDao.class); - XXModuleDef xModuleDef = Mockito.mock(XXModuleDef.class); - VXUserPermission vXUserPermission = Mockito.mock(VXUserPermission.class); - - VXPortalUser userProfile = userProfile(); - - XXPortalUser user = new XXPortalUser(); - user.setEmailAddress(userProfile.getEmailAddress()); - user.setFirstName(userProfile.getFirstName()); - user.setLastName(userProfile.getLastName()); - user.setLoginId(userProfile.getLoginId()); - user.setPassword(userProfile.getPassword()); - user.setUserSource(userProfile.getUserSource()); - user.setPublicScreenName(userProfile.getPublicScreenName()); - user.setId(userProfile.getId()); - - List xUserPermissionsList = new ArrayList(); - XXUserPermission xUserPermissionObj = new XXUserPermission(); - xUserPermissionObj.setAddedByUserId(userId); - xUserPermissionObj.setCreateTime(new Date()); - xUserPermissionObj.setId(userId); - xUserPermissionObj.setIsAllowed(1); - xUserPermissionObj.setModuleId(1L); - xUserPermissionObj.setUpdatedByUserId(userId); - xUserPermissionObj.setUpdateTime(new Date()); - xUserPermissionObj.setUserId(userId); - xUserPermissionsList.add(xUserPermissionObj); - - List xGroupPermissionList = new ArrayList(); - XXGroupPermission xGroupPermissionObj = new XXGroupPermission(); - xGroupPermissionObj.setAddedByUserId(userId); - xGroupPermissionObj.setCreateTime(new Date()); - xGroupPermissionObj.setId(userId); - xGroupPermissionObj.setIsAllowed(1); - xGroupPermissionObj.setModuleId(1L); - xGroupPermissionObj.setUpdatedByUserId(userId); - xGroupPermissionObj.setUpdateTime(new Date()); - xGroupPermissionObj.setGroupId(userId); - xGroupPermissionList.add(xGroupPermissionObj); - - XXPortalUserRole XXPortalUserRole = new XXPortalUserRole(); - XXPortalUserRole.setId(userId); - XXPortalUserRole.setUserRole("ROLE_USER"); - - List list = new ArrayList(); - list.add(XXPortalUserRole); - Mockito.when(daoManager.getXXPortalUser()).thenReturn(userDao); - Mockito.when(userDao.update(user)).thenReturn(user); - - Mockito.when(daoManager.getXXPortalUserRole()).thenReturn(roleDao); - Mockito.when(roleDao.findByParentId(Mockito.anyLong())).thenReturn(list); - - Mockito.when(daoManager.getXXUserPermission()).thenReturn(xUserPermissionDao); - Mockito.when(xUserPermissionDao.findByUserPermissionIdAndIsAllowed(userProfile.getId())).thenReturn(xUserPermissionsList); - - Mockito.when(daoManager.getXXGroupPermission()).thenReturn(xGroupPermissionDao); - Mockito.when(xGroupPermissionDao.findbyVXPortalUserId(userProfile.getId())).thenReturn(xGroupPermissionList); - - Mockito.when(xGroupPermissionService.populateViewBean(xGroupPermissionObj)).thenReturn(vXGroupPermission); - - Mockito.when(daoManager.getXXModuleDef()).thenReturn(xModuleDefDao); - Mockito.when(xModuleDefDao.findByModuleId(Mockito.anyLong())).thenReturn(xModuleDef); - - Mockito.when(xUserPermissionService.populateViewBean(xUserPermissionObj)).thenReturn(vXUserPermission); - Mockito.doNothing().when(rangerBizUtil).blockAuditorRoleUser(); - VXPortalUser dbVXPortalUser = userMgr.deactivateUser(null); - Assert.assertNull(dbVXPortalUser); - dbVXPortalUser = userMgr.deactivateUser(user); - Assert.assertNotNull(dbVXPortalUser); - Assert.assertEquals(user.getId(), dbVXPortalUser.getId()); - Assert.assertEquals(user.getFirstName(), dbVXPortalUser.getFirstName()); - Assert.assertEquals(user.getLastName(), dbVXPortalUser.getLastName()); - Assert.assertEquals(user.getLoginId(), dbVXPortalUser.getLoginId()); - - Mockito.verify(daoManager).getXXPortalUser(); - Mockito.verify(daoManager).getXXUserPermission(); - Mockito.verify(daoManager).getXXGroupPermission(); - Mockito.verify(xUserPermissionService).populateViewBean(xUserPermissionObj); - Mockito.verify(xGroupPermissionService).populateViewBean(xGroupPermissionObj); - } - - @Test - public void test20checkAccess() { - setup(); - XXPortalUserDao xPortalUserDao = Mockito.mock(XXPortalUserDao.class); - XXPortalUser xPortalUser = Mockito.mock(XXPortalUser.class); - Mockito.when(daoManager.getXXPortalUser()).thenReturn(xPortalUserDao); - Mockito.when(xPortalUserDao.getById(userId)).thenReturn(xPortalUser); - Mockito.when(restErrorUtil.createRESTException(HttpServletResponse.SC_FORBIDDEN, "Logged-In user is not allowed to access requested user data", true)).thenThrow(new WebApplicationException()); - thrown.expect(WebApplicationException.class); - userMgr.checkAccess(userId); - - Mockito.when(xPortalUserDao.getById(userId)).thenReturn(null); - Mockito.when(restErrorUtil.create403RESTException("serverMsg.userMgrWrongUser: "+userId)).thenThrow(new WebApplicationException()); - thrown.expect(WebApplicationException.class); - userMgr.checkAccess(userId); - } - - @Test - public void test21getUserProfile() { - setup(); - XXPortalUserDao xPortalUserDao = Mockito.mock(XXPortalUserDao.class); - XXPortalUser xPortalUser = Mockito.mock(XXPortalUser.class); - - List xPortalUserRoleList = new ArrayList(); - XXPortalUserRole XXPortalUserRole = new XXPortalUserRole(); - XXPortalUserRole.setId(userId); - XXPortalUserRole.setUserRole("ROLE_USER"); - xPortalUserRoleList.add(XXPortalUserRole); - - List xUserPermissionsList = new ArrayList(); - XXUserPermission xUserPermissionObj = new XXUserPermission(); - xUserPermissionObj.setAddedByUserId(userId); - xUserPermissionObj.setCreateTime(new Date()); - xUserPermissionObj.setId(userId); - xUserPermissionObj.setIsAllowed(1); - xUserPermissionObj.setModuleId(1L); - xUserPermissionObj.setUpdatedByUserId(userId); - xUserPermissionObj.setUpdateTime(new Date()); - xUserPermissionObj.setUserId(userId); - xUserPermissionsList.add(xUserPermissionObj); - - List xGroupPermissionList = new ArrayList(); - XXGroupPermission xGroupPermissionObj = new XXGroupPermission(); - xGroupPermissionObj.setAddedByUserId(userId); - xGroupPermissionObj.setCreateTime(new Date()); - xGroupPermissionObj.setId(userId); - xGroupPermissionObj.setIsAllowed(1); - xGroupPermissionObj.setModuleId(1L); - xGroupPermissionObj.setUpdatedByUserId(userId); - xGroupPermissionObj.setUpdateTime(new Date()); - xGroupPermissionObj.setGroupId(userId); - xGroupPermissionList.add(xGroupPermissionObj); - - Mockito.when(daoManager.getXXPortalUser()).thenReturn(xPortalUserDao); - Mockito.when(xPortalUserDao.getById(userId)).thenReturn(null); - Mockito.when(restErrorUtil.createRESTException(HttpServletResponse.SC_FORBIDDEN, "Logged-In user is not allowed to access requested user data", true)).thenThrow(new WebApplicationException()); - thrown.expect(WebApplicationException.class); - VXPortalUser dbVXPortalUser = userMgr.getUserProfile(userId); - Mockito.when(xPortalUserDao.getById(userId)).thenReturn(xPortalUser); - dbVXPortalUser = userMgr.getUserProfile(userId); - Assert.assertNotNull(dbVXPortalUser); - } - - @Test - public void test22getUserProfileByLoginId() { - setup(); - XXPortalUserDao xPortalUserDao = Mockito.mock(XXPortalUserDao.class); - Mockito.when(daoManager.getXXPortalUser()).thenReturn(xPortalUserDao); - VXPortalUser userProfile = userProfile(); - XXPortalUser user = new XXPortalUser(); - user.setEmailAddress(userProfile.getEmailAddress()); - user.setFirstName(userProfile.getFirstName()); - user.setLastName(userProfile.getLastName()); - user.setLoginId(userProfile.getLoginId()); - user.setPassword(userProfile.getPassword()); - user.setUserSource(userProfile.getUserSource()); - user.setPublicScreenName(userProfile.getPublicScreenName()); - user.setId(userProfile.getId()); - VXPortalUser dbVXPortalUser = userMgr.getUserProfileByLoginId(); - Mockito.when(xPortalUserDao.findByLoginId(Mockito.anyString())).thenReturn(user); - XXPortalUserRoleDao xPortalUserRoleDao = Mockito.mock(XXPortalUserRoleDao.class); - Mockito.when(daoManager.getXXPortalUserRole()).thenReturn(xPortalUserRoleDao); - List xPortalUserRoleList = new ArrayList(); - XXPortalUserRole XXPortalUserRole = new XXPortalUserRole(); - XXPortalUserRole.setId(userId); - XXPortalUserRole.setUserId(userId); - XXPortalUserRole.setUserRole("ROLE_USER"); - xPortalUserRoleList.add(XXPortalUserRole); - Mockito.when(xPortalUserRoleDao.findByParentId(Mockito.anyLong())).thenReturn(xPortalUserRoleList); - XXUserPermissionDao xUserPermissionDao = Mockito.mock(XXUserPermissionDao.class); - XXGroupPermissionDao xGroupPermissionDao = Mockito.mock(XXGroupPermissionDao.class); - Mockito.when(daoManager.getXXUserPermission()).thenReturn(xUserPermissionDao); - List xUserPermissionsList = new ArrayList(); - List xGroupPermissionList = new ArrayList(); - Mockito.when(xUserPermissionDao.findByUserPermissionIdAndIsAllowed(userProfile.getId())).thenReturn(xUserPermissionsList); - Mockito.when(daoManager.getXXGroupPermission()).thenReturn(xGroupPermissionDao); - Mockito.when(xGroupPermissionDao.findbyVXPortalUserId(userProfile.getId())).thenReturn(xGroupPermissionList); - dbVXPortalUser = userMgr.getUserProfileByLoginId(user.getLoginId()); - Assert.assertNotNull(dbVXPortalUser); - } - - @Test - public void test23setUserRoles() { - setup(); - XXPortalUserDao userDao = Mockito.mock(XXPortalUserDao.class); - VXPortalUser userProfile = userProfile(); - XXPortalUser user = new XXPortalUser(); - user.setEmailAddress(userProfile.getEmailAddress()); - user.setFirstName(userProfile.getFirstName()); - user.setLastName(userProfile.getLastName()); - user.setLoginId(userProfile.getLoginId()); - user.setPassword(userProfile.getPassword()); - user.setUserSource(userProfile.getUserSource()); - user.setPublicScreenName(userProfile.getPublicScreenName()); - user.setId(userProfile.getId()); - - List vStringRolesList = new ArrayList(); - VXString vXStringObj = new VXString(); - vXStringObj.setValue("ROLE_USER"); - vStringRolesList.add(vXStringObj); - - List xPortalUserRoleList = new ArrayList(); - XXPortalUserRole XXPortalUserRole = new XXPortalUserRole(); - XXPortalUserRole.setId(userId); - XXPortalUserRole.setUserId(userId); - XXPortalUserRole.setUserRole("ROLE_USER"); - xPortalUserRoleList.add(XXPortalUserRole); - - List xUserPermissionsList = new ArrayList(); - XXUserPermission xUserPermissionObj = new XXUserPermission(); - xUserPermissionObj.setAddedByUserId(userId); - xUserPermissionObj.setCreateTime(new Date()); - xUserPermissionObj.setId(userId); - xUserPermissionObj.setIsAllowed(1); - xUserPermissionObj.setModuleId(1L); - xUserPermissionObj.setUpdatedByUserId(userId); - xUserPermissionObj.setUpdateTime(new Date()); - xUserPermissionObj.setUserId(userId); - xUserPermissionsList.add(xUserPermissionObj); - - List xGroupPermissionList = new ArrayList(); - XXGroupPermission xGroupPermissionObj = new XXGroupPermission(); - xGroupPermissionObj.setAddedByUserId(userId); - xGroupPermissionObj.setCreateTime(new Date()); - xGroupPermissionObj.setId(userId); - xGroupPermissionObj.setIsAllowed(1); - xGroupPermissionObj.setModuleId(1L); - xGroupPermissionObj.setUpdatedByUserId(userId); - xGroupPermissionObj.setUpdateTime(new Date()); - xGroupPermissionObj.setGroupId(userId); - xGroupPermissionList.add(xGroupPermissionObj); - - List groupPermList = new ArrayList(); - VXGroupPermission groupPermission = new VXGroupPermission(); - groupPermission.setId(1L); - groupPermission.setIsAllowed(1); - groupPermission.setModuleId(1L); - groupPermission.setGroupId(userId); - groupPermission.setGroupName("xyz"); - groupPermission.setOwner("admin"); - groupPermList.add(groupPermission); - - XXModuleDef xModuleDef = new XXModuleDef(); - xModuleDef.setUpdatedByUserId(userId); - xModuleDef.setAddedByUserId(userId); - xModuleDef.setCreateTime(new Date()); - xModuleDef.setId(userId); - xModuleDef.setModule("Policy manager"); - xModuleDef.setUpdateTime(new Date()); - xModuleDef.setUrl("/policy manager"); - - VXUserPermission userPermission = new VXUserPermission(); - userPermission.setId(1L); - userPermission.setIsAllowed(1); - userPermission.setModuleId(1L); - userPermission.setUserId(userId); - userPermission.setUserName("xyz"); - userPermission.setOwner("admin"); - Mockito.when(daoManager.getXXPortalUser()).thenReturn(userDao); - Mockito.when(userDao.getById(userId)).thenReturn(user); - Mockito.when(restErrorUtil.createRESTException(HttpServletResponse.SC_FORBIDDEN, "Logged-In user is not allowed to access requested user data", true)).thenThrow(new WebApplicationException()); - thrown.expect(WebApplicationException.class); - userMgr.checkAccess(userId); - userMgr.setUserRoles(userId, vStringRolesList); - - Mockito.verify(daoManager).getXXUserPermission(); - Mockito.verify(daoManager).getXXGroupPermission(); - Mockito.verify(xGroupPermissionService).populateViewBean(xGroupPermissionObj); - Mockito.verify(xUserPermissionService).populateViewBean(xUserPermissionObj); - } - - @Test - public void test24updateRoles() { - setup(); - Collection rolesList = new ArrayList(); - rolesList.add("ROLE_USER"); - rolesList.add("ROLE_SYS_ADMIN"); - XXPortalUserRole XXPortalUserRole = new XXPortalUserRole(); - XXPortalUserRole.setId(userId); - XXPortalUserRole.setUserRole("ROLE_USER"); - List list = new ArrayList(); - list.add(XXPortalUserRole); - XXPortalUserRoleDao userDao = Mockito.mock(XXPortalUserRoleDao.class); - Mockito.when(daoManager.getXXPortalUserRole()).thenReturn(userDao); - Mockito.when(userDao.findByUserId(userId)).thenReturn(list); - boolean isFound = userMgr.updateRoles(userId, rolesList); - Assert.assertFalse(isFound); - - Mockito.when(restErrorUtil.createRESTException("Invalid user role, please provide valid user role.", MessageEnums.INVALID_INPUT_DATA)).thenThrow(new WebApplicationException()); - thrown.expect(WebApplicationException.class); - rolesList.clear(); - rolesList.add("INVALID_ROLE"); - isFound = userMgr.updateRoles(userId, rolesList); - } - - @Test - public void test25updatePasswordInSHA256() { - XXPortalUserDao userDao = Mockito.mock(XXPortalUserDao.class); - VXPortalUser userProfile = userProfile(); - String userName = userProfile.getFirstName(); - String userPassword = userProfile.getPassword(); - XXPortalUser user = new XXPortalUser(); - user.setEmailAddress(userProfile.getEmailAddress()); - user.setFirstName(userProfile.getFirstName()); - user.setLastName(userProfile.getLastName()); - user.setLoginId(userProfile.getLoginId()); - user.setPassword(userProfile.getPassword()); - user.setUserSource(RangerCommonEnums.USER_APP); - user.setPublicScreenName(userProfile.getPublicScreenName()); - user.setId(userProfile.getId()); - Mockito.when(daoManager.getXXPortalUser()).thenReturn(userDao); - Mockito.when(daoManager.getXXPortalUser()).thenReturn(userDao); - Mockito.when(userDao.update(user)).thenReturn(user); - XXPortalUser dbXXPortalUser = userMgr.updatePasswordInSHA256(null,userPassword,false); - Assert.assertNull(dbXXPortalUser); - Mockito.when(userDao.findByLoginId(Mockito.anyString())).thenReturn(null); - dbXXPortalUser = userMgr.updatePasswordInSHA256(userName,userPassword,false); - Assert.assertNull(dbXXPortalUser); - Mockito.when(userDao.findByLoginId(Mockito.anyString())).thenReturn(user); - dbXXPortalUser = userMgr.updatePasswordInSHA256(userName,userPassword,true); - Assert.assertNotNull(dbXXPortalUser); - dbXXPortalUser = userMgr.updatePasswordInSHA256(userName,"Secret",true); - Assert.assertNotNull(dbXXPortalUser); - - } - - @Test - public void test26CreateUser() { - setup(); - XXPortalUserDao userDao = Mockito.mock(XXPortalUserDao.class); - XXPortalUserRoleDao roleDao = Mockito.mock(XXPortalUserRoleDao.class); - - VXPortalUser userProfile = userProfile(); - - Collection userRoleList = new ArrayList(); - userRoleList.add("ROLE_USER"); - - XXPortalUser user = new XXPortalUser(); - user.setEmailAddress(userProfile.getEmailAddress()); - user.setFirstName(userProfile.getFirstName()); - user.setLastName(userProfile.getLastName()); - user.setLoginId(userProfile.getLoginId()); - String encryptedPwd = userMgr.encrypt(userProfile.getLoginId(),userProfile.getPassword()); - user.setPassword(encryptedPwd); - user.setUserSource(userProfile.getUserSource()); - user.setPublicScreenName(userProfile.getPublicScreenName()); - user.setId(userProfile.getId()); - - XXPortalUserRole XXPortalUserRole = new XXPortalUserRole(); - XXPortalUserRole.setId(user.getId()); - XXPortalUserRole.setUserRole("ROLE_USER"); - List list = new ArrayList(); - list.add(XXPortalUserRole); - - Mockito.when(daoManager.getXXPortalUser()).thenReturn(userDao); - Mockito.when(userDao.create((XXPortalUser) Mockito.any())).thenReturn(user); - Mockito.when(daoManager.getXXPortalUserRole()).thenReturn(roleDao); - Mockito.when(roleDao.findByUserId(userId)).thenReturn(list); - Mockito.when(userDao.findByLoginId(Mockito.anyString())).thenReturn(user); - XXPortalUser dbxxPortalUser = userMgr.createUser(userProfile, 1,userRoleList); - Assert.assertNotNull(dbxxPortalUser); - userId = dbxxPortalUser.getId(); - Assert.assertEquals(userId, dbxxPortalUser.getId()); - Assert.assertEquals(userProfile.getFirstName(),dbxxPortalUser.getFirstName()); - Assert.assertEquals(userProfile.getFirstName(),dbxxPortalUser.getFirstName()); - Assert.assertEquals(userProfile.getLastName(),dbxxPortalUser.getLastName()); - Assert.assertEquals(userProfile.getLoginId(),dbxxPortalUser.getLoginId()); - Assert.assertEquals(userProfile.getEmailAddress(),dbxxPortalUser.getEmailAddress()); - Assert.assertEquals(encryptedPwd,dbxxPortalUser.getPassword()); - - Mockito.verify(daoManager, Mockito.atLeast(1)).getXXPortalUser(); - Mockito.verify(daoManager).getXXPortalUserRole(); - } - - @Test - public void test27UpdateUser() { - setup(); - XXPortalUserDao userDao = Mockito.mock(XXPortalUserDao.class); - - VXPortalUser userProfile = userProfile(); - XXPortalUser user = new XXPortalUser(); - user.setId(userProfile.getId()); - user.setLoginId(userProfile.getLoginId()); - user.setEmailAddress(userProfile.getEmailAddress()); - user.setLoginId(userProfile.getLoginId()); - String encryptedPwd = userMgr.encrypt(userProfile.getLoginId(),userProfile.getPassword()); - user.setPassword(encryptedPwd); - Mockito.when(daoManager.getXXPortalUser()).thenReturn(userDao); - Mockito.when(userDao.getById(userProfile.getId())).thenReturn(user); - Mockito.when(restErrorUtil.createRESTException(HttpServletResponse.SC_FORBIDDEN, "Logged-In user is not allowed to access requested user data", true)).thenThrow(new WebApplicationException()); - thrown.expect(WebApplicationException.class); - XXPortalUser dbXXPortalUser = userMgr.updateUser(userProfile); - Assert.assertNotNull(dbXXPortalUser); - Assert.assertEquals(userId, dbXXPortalUser.getId()); - Assert.assertEquals(userProfile.getFirstName(),dbXXPortalUser.getFirstName()); - Assert.assertEquals(userProfile.getFirstName(),dbXXPortalUser.getFirstName()); - Assert.assertEquals(userProfile.getLastName(),dbXXPortalUser.getLastName()); - Assert.assertEquals(userProfile.getLoginId(),dbXXPortalUser.getLoginId()); - Assert.assertEquals(userProfile.getEmailAddress(),dbXXPortalUser.getEmailAddress()); - Assert.assertEquals(encryptedPwd,dbXXPortalUser.getPassword()); - - Mockito.when(restErrorUtil.createRESTException("Please provide valid email address.", MessageEnums.INVALID_INPUT_DATA)).thenThrow(new WebApplicationException()); - thrown.expect(WebApplicationException.class); - Mockito.when(stringUtil.validateEmail(Mockito.anyString())).thenReturn(false); - userMgr.updateUser(userProfile); - } - - @Test - public void test28UpdateUser() { - setup(); - XXPortalUserDao userDao = Mockito.mock(XXPortalUserDao.class); - - VXPortalUser userProfile = userProfile(); - XXPortalUser user = new XXPortalUser(); - user.setId(userProfile.getId()); - user.setLoginId(userProfile.getLoginId()); - user.setEmailAddress(userProfile.getEmailAddress()); - user.setLoginId(userProfile.getLoginId()); - String encryptedPwd = userMgr.encrypt(userProfile.getLoginId(),userProfile.getPassword()); - user.setPassword(encryptedPwd); - Mockito.when(daoManager.getXXPortalUser()).thenReturn(userDao); - Mockito.when(userDao.getById(userProfile.getId())).thenReturn(null); - XXPortalUser dbXXPortalUser = userMgr.updateUser(userProfile); - Assert.assertNull(dbXXPortalUser); - user.setStatus(RangerCommonEnums.USER_EXTERNAL); - user.setFirstName("null"); - user.setLastName("null"); - Mockito.when(userDao.getById(userProfile.getId())).thenReturn(user); - Mockito.when(restErrorUtil.createRESTException(HttpServletResponse.SC_FORBIDDEN, "Logged-In user is not allowed to access requested user data", true)).thenThrow(new WebApplicationException()); - thrown.expect(WebApplicationException.class); - dbXXPortalUser = userMgr.updateUser(userProfile); - Assert.assertNotNull(dbXXPortalUser); - Assert.assertEquals(userId, dbXXPortalUser.getId()); - Assert.assertEquals(userProfile.getLoginId(),dbXXPortalUser.getLoginId()); - Assert.assertEquals(userProfile.getEmailAddress(),dbXXPortalUser.getEmailAddress()); - Assert.assertEquals(encryptedPwd,dbXXPortalUser.getPassword()); - - Mockito.when(restErrorUtil.createRESTException("Invalid user, please provide valid username.", MessageEnums.INVALID_INPUT_DATA)).thenThrow(new WebApplicationException()); - thrown.expect(WebApplicationException.class); - userProfile.setLoginId(null); - dbXXPortalUser = userMgr.updateUser(userProfile); - - Mockito.when(restErrorUtil.createRESTException("The email address you've provided already exists in system.", MessageEnums.INVALID_INPUT_DATA)).thenThrow(new WebApplicationException()); - thrown.expect(WebApplicationException.class); - userProfile.setLoginId("test1234"); - user.setLoginId(null); - Mockito.when(userDao.findByEmailAddress(Mockito.anyString())).thenReturn(user); - dbXXPortalUser = userMgr.updateUser(userProfile); - } - - @Test - public void test29UpdateOldUserName() { - setup(); - XXPortalUserDao userDao = Mockito.mock(XXPortalUserDao.class); - XXUserDao xXUserDao = Mockito.mock(XXUserDao.class); - VXPortalUser userProfile = userProfile(); - String userLoginId = userProfile.getLoginId(); - String newUserName= "newUserName"; - String currentPassword = userProfile.getPassword(); - - XXPortalUser xXPortalUser = new XXPortalUser(); - xXPortalUser.setEmailAddress(userProfile.getEmailAddress()); - xXPortalUser.setFirstName(userProfile.getFirstName()); - xXPortalUser.setLastName(userProfile.getLastName()); - xXPortalUser.setLoginId(userProfile.getLoginId()); - String encryptedPwd = userMgr.encrypt(userProfile.getLoginId(),userProfile.getPassword()); - xXPortalUser.setPassword(encryptedPwd); - xXPortalUser.setUserSource(userProfile.getUserSource()); - xXPortalUser.setPublicScreenName(userProfile.getPublicScreenName()); - xXPortalUser.setId(userProfile.getId()); - xXPortalUser.setUserSource(RangerCommonEnums.USER_APP); - - XXUser xXUser = new XXUser(); - Collection userRoleList = new ArrayList(); - userRoleList.add("ROLE_USER"); - Collection groupNameList = new ArrayList(); - groupNameList.add("Grp2"); - xXUser.setId(userId); - xXUser.setDescription(userProfile.getPublicScreenName()); - xXUser.setName(userProfile.getLoginId()); - - Mockito.when(daoManager.getXXPortalUser()).thenReturn(userDao); - Mockito.when(userDao.findByLoginId(userProfile.getLoginId())).thenReturn(xXPortalUser); - Mockito.when(daoManager.getXXUser()).thenReturn(xXUserDao); - Mockito.when(xXUserDao.findByUserName(xXUser.getName())).thenReturn(xXUser); - - xXUser.setName(newUserName); - Mockito.when(xXUserDao.update(xXUser)).thenReturn(xXUser); - - xXPortalUser.setLoginId(newUserName); - Mockito.when(userDao.update(xXPortalUser)).thenReturn(xXPortalUser); - - xXPortalUser=userMgr.updateOldUserName(userLoginId, newUserName, currentPassword); - - Assert.assertNotNull(xXPortalUser); - Assert.assertEquals(newUserName,xXPortalUser.getLoginId()); - xXPortalUser.setUserSource(RangerCommonEnums.USER_EXTERNAL); - Mockito.when(userDao.findByLoginId(userProfile.getLoginId())).thenReturn(xXPortalUser); - xXPortalUser=userMgr.updateOldUserName(userLoginId, newUserName, currentPassword); - xXPortalUser=userMgr.updateOldUserName(null, newUserName, currentPassword); - Mockito.when(userDao.findByLoginId(userProfile.getLoginId())).thenReturn(null); - xXPortalUser=userMgr.updateOldUserName(userLoginId, newUserName, currentPassword); - } - - @Test - public void test30getRolesByLoginId() { - setup(); - XXPortalUserDao userDao = Mockito.mock(XXPortalUserDao.class); - XXPortalUserRoleDao roleDao = Mockito.mock(XXPortalUserRoleDao.class); - - VXPortalUser userProfile = userProfile(); - String userLoginId = userProfile.getLoginId(); - - Collection userRoleList = new ArrayList(); - userRoleList.add("ROLE_USER"); - - XXPortalUser user = new XXPortalUser(); - user.setEmailAddress(userProfile.getEmailAddress()); - user.setFirstName(userProfile.getFirstName()); - user.setLastName(userProfile.getLastName()); - user.setLoginId(userProfile.getLoginId()); - String encryptedPwd = userMgr.encrypt(userProfile.getLoginId(),userProfile.getPassword()); - user.setPassword(encryptedPwd); - user.setUserSource(userProfile.getUserSource()); - user.setPublicScreenName(userProfile.getPublicScreenName()); - user.setId(userProfile.getId()); - - XXPortalUserRole XXPortalUserRole = new XXPortalUserRole(); - XXPortalUserRole.setId(user.getId()); - XXPortalUserRole.setUserRole("ROLE_USER"); - List list = new ArrayList(); - list.add(XXPortalUserRole); - - Mockito.when(daoManager.getXXPortalUser()).thenReturn(userDao); - Mockito.when(userDao.findByLoginId(userProfile.getLoginId())).thenReturn(user); - Mockito.when(daoManager.getXXPortalUserRole()).thenReturn(roleDao); - Mockito.when(roleDao.findByUserId(userId)).thenReturn(list); - Collection roleList = userMgr.getRolesByLoginId(userLoginId); - Assert.assertNotNull(roleList); - Assert.assertEquals(userLoginId, user.getLoginId()); - Assert.assertEquals(userRoleList, roleList); - roleList = userMgr.getRolesByLoginId(null); - Mockito.when(roleDao.findByUserId(userId)).thenReturn(null); - roleList = userMgr.getRolesByLoginId(userLoginId); - Mockito.when(userDao.findByLoginId(userProfile.getLoginId())).thenReturn(null); - roleList = userMgr.getRolesByLoginId(userLoginId); - Assert.assertNotNull(roleList); - } - - @Test - public void test31checkAccess() { - setup(); - XXPortalUserDao userDao = Mockito.mock(XXPortalUserDao.class); - Mockito.when(daoManager.getXXPortalUser()).thenReturn(userDao); - XXPortalUser xPortalUser = Mockito.mock(XXPortalUser.class); - Mockito.when(restErrorUtil.createRESTException(HttpServletResponse.SC_FORBIDDEN, "Logged-In user is not allowed to access requested user data", true)).thenThrow(new WebApplicationException()); - thrown.expect(WebApplicationException.class); - userMgr.checkAccess(xPortalUser); - destroySession(); - VXPortalUser userProfile = userProfile(); - xPortalUser = xxPortalUser(userProfile); - xPortalUser.setId(userProfile.getId()); - setupUser(); - userMgr.checkAccess(xPortalUser); - - destroySession(); - Mockito.when(restErrorUtil.create403RESTException("User access denied. loggedInUser=Not Logged In, accessing user=" + userProfile.getId())).thenThrow(new WebApplicationException()); - thrown.expect(WebApplicationException.class); - userMgr.checkAccess(xPortalUser); - - Mockito.when(restErrorUtil.create403RESTException("serverMsg.userMgrWrongUser")).thenThrow(new WebApplicationException()); - thrown.expect(WebApplicationException.class); - xPortalUser = null; - userMgr.checkAccess(xPortalUser); - } - - @Test - public void test32checkAdminAccess() { - setup(); - userMgr.checkAdminAccess(); - destroySession(); - Mockito.when(restErrorUtil.create403RESTException("Operation not allowed. loggedInUser=. Not Logged In.")).thenThrow(new WebApplicationException()); - thrown.expect(WebApplicationException.class); - userMgr.checkAdminAccess(); - } - - @Test - public void test34updateRoleForExternalUsers() { - setupRangerUserSyncUser(); - XXPortalUserDao userDao = Mockito.mock(XXPortalUserDao.class); - XXUserPermissionDao xUserPermissionDao = Mockito.mock(XXUserPermissionDao.class); - Collection existingRoleList = new ArrayList(); - existingRoleList.add(RangerConstants.ROLE_USER); - Collection reqRoleList = new ArrayList(); - reqRoleList.add(RangerConstants.ROLE_SYS_ADMIN); - - VXPortalUser userProfile = userProfile(); - XXPortalUser user = new XXPortalUser(); - user.setId(userProfile.getId()); - user.setLoginId(userProfile.getLoginId()); - user.setEmailAddress(userProfile.getEmailAddress()); - user.setLoginId(userProfile.getLoginId()); - String encryptedPwd = userMgr.encrypt(userProfile.getLoginId(),userProfile.getPassword()); - user.setPassword(encryptedPwd); - - XXPortalUserRole XXPortalUserRole = new XXPortalUserRole(); - XXPortalUserRole.setId(userProfile.getId()); - XXPortalUserRole.setUserRole(RangerConstants.ROLE_USER); - List list = new ArrayList(); - list.add(XXPortalUserRole); - - List xUserPermissionsList = new ArrayList(); - XXUserPermission xUserPermissionObj = new XXUserPermission(); - xUserPermissionObj.setAddedByUserId(userId); - xUserPermissionObj.setCreateTime(new Date()); - xUserPermissionObj.setId(userId); - xUserPermissionObj.setIsAllowed(1); - xUserPermissionObj.setModuleId(1L); - xUserPermissionObj.setUpdatedByUserId(userId); - xUserPermissionObj.setUpdateTime(new Date()); - xUserPermissionObj.setUserId(userId); - xUserPermissionsList.add(xUserPermissionObj); - Mockito.when(daoManager.getXXPortalUser()).thenReturn(userDao); - Mockito.when(userDao.getById(userProfile.getId())).thenReturn(user); - Mockito.when(daoManager.getXXUserPermission()).thenReturn(xUserPermissionDao); - Mockito.when(xUserPermissionDao.findByUserPermissionId(userProfile.getId())).thenReturn(xUserPermissionsList); - Mockito.when(restErrorUtil.createRESTException(HttpServletResponse.SC_FORBIDDEN, "Logged-In user is not allowed to access requested user data", true)).thenThrow(new WebApplicationException()); - thrown.expect(WebApplicationException.class); - VXPortalUser dbVXPortalUser = userMgr.updateRoleForExternalUsers(reqRoleList,existingRoleList,userProfile); - Assert.assertNotNull(dbVXPortalUser); - Assert.assertEquals(userId, dbVXPortalUser.getId()); - Assert.assertEquals(userProfile.getFirstName(),dbVXPortalUser.getFirstName()); - Assert.assertEquals(userProfile.getLastName(),dbVXPortalUser.getLastName()); - Assert.assertEquals(userProfile.getLoginId(),dbVXPortalUser.getLoginId()); - Assert.assertEquals(userProfile.getEmailAddress(),dbVXPortalUser.getEmailAddress()); - } - - @Test - public void test35mapVXPortalUserToXXPortalUser() { - setup(); - Collection existingRoleList = new ArrayList(); - existingRoleList.add(RangerConstants.ROLE_USER); - Collection reqRoleList = new ArrayList(); - reqRoleList.add(RangerConstants.ROLE_SYS_ADMIN); - - VXPortalUser userProfile = userProfile(); - userProfile.setFirstName("null"); - userProfile.setLastName("null"); - XXPortalUser user = new XXPortalUser(); - user.setId(userProfile.getId()); - user.setLoginId(userProfile.getLoginId()); - user.setEmailAddress(userProfile.getEmailAddress()); - user.setLoginId(userProfile.getLoginId()); - String encryptedPwd = userMgr.encrypt(userProfile.getLoginId(),userProfile.getPassword()); - user.setPassword(encryptedPwd); - - XXPortalUserRole XXPortalUserRole = new XXPortalUserRole(); - XXPortalUserRole.setId(userProfile.getId()); - XXPortalUserRole.setUserRole(RangerConstants.ROLE_USER); - List list = new ArrayList(); - list.add(XXPortalUserRole); - - List xUserPermissionsList = new ArrayList(); - XXUserPermission xUserPermissionObj = new XXUserPermission(); - xUserPermissionObj.setAddedByUserId(userId); - xUserPermissionObj.setCreateTime(new Date()); - xUserPermissionObj.setId(userId); - xUserPermissionObj.setIsAllowed(1); - xUserPermissionObj.setModuleId(1L); - xUserPermissionObj.setUpdatedByUserId(userId); - xUserPermissionObj.setUpdateTime(new Date()); - xUserPermissionObj.setUserId(userId); - xUserPermissionsList.add(xUserPermissionObj); - XXPortalUser dbVXPortalUser = userMgr.mapVXPortalUserToXXPortalUser(userProfile); - Assert.assertNotNull(dbVXPortalUser); - Assert.assertEquals(userProfile.getLoginId(),dbVXPortalUser.getLoginId()); - Assert.assertEquals(userProfile.getEmailAddress(),dbVXPortalUser.getEmailAddress()); - - userProfile.setLoginId(null); - Mockito.when(restErrorUtil.createRESTException("LoginId should not be null or blank, It is", MessageEnums.INVALID_INPUT_DATA)).thenThrow(new WebApplicationException()); - thrown.expect(WebApplicationException.class); - userMgr.mapVXPortalUserToXXPortalUser(userProfile); - } - - @Test - public void test36UpdateUser() { - setup(); - XXPortalUserDao userDao = Mockito.mock(XXPortalUserDao.class); - VXPortalUser userProfile = userProfile(); - XXPortalUser user = new XXPortalUser(); - user.setId(userProfile.getId()); - user.setLoginId(userProfile.getLoginId()); - userProfile.setFirstName("User"); - userProfile.setLastName("User"); - String encryptedPwd = userMgr.encrypt(userProfile.getLoginId(),userProfile.getPassword()); - user.setPassword(encryptedPwd); - Mockito.when(daoManager.getXXPortalUser()).thenReturn(userDao); - Mockito.when(userDao.getById(userProfile.getId())).thenReturn(user); - Mockito.when(restErrorUtil.createRESTException(HttpServletResponse.SC_FORBIDDEN, "Logged-In user is not allowed to access requested user data", true)).thenThrow(new WebApplicationException()); - thrown.expect(WebApplicationException.class); - XXPortalUser dbXXPortalUser = userMgr.updateUser(userProfile); - Assert.assertNotNull(dbXXPortalUser); - Mockito.when(stringUtil.isEmpty(Mockito.anyString())).thenReturn(true); - userProfile.setFirstName("null"); - userProfile.setLastName("null"); - userProfile.setEmailAddress(""); - dbXXPortalUser = userMgr.updateUser(userProfile); - } - - @Test - public void test37createUserSearchQuery() { - EntityManager entityManager = Mockito.mock(EntityManager.class); - String queryString="Select id,loginId,emailAddress,firstName,lastName,statusList,publicScreenName,status from XXPortalUser"; - Query query = Mockito.mock(Query.class); - SearchCriteria searchCriteria = new SearchCriteria(); - searchCriteria.setDistinct(true); - searchCriteria.setGetChildren(true); - searchCriteria.setGetCount(true); - searchCriteria.setMaxRows(12); - searchCriteria.setOwnerId(userId); - searchCriteria.setStartIndex(1); - searchCriteria.setSortBy("asc"); - VXPortalUser vXPortalUser=userProfile(); - List userRoleList = new ArrayList(); - userRoleList.add("ROLE_USER"); - List statusList = new ArrayList(); - statusList.add(1); - searchCriteria.addParam("roleList", userRoleList); - searchCriteria.addParam("userId", vXPortalUser.getId()); - searchCriteria.addParam("loginId", vXPortalUser.getLoginId()); - searchCriteria.addParam("emailAddress", vXPortalUser.getEmailAddress()); - searchCriteria.addParam("firstName", vXPortalUser.getFirstName()); - searchCriteria.addParam("lastName", vXPortalUser.getLastName()); - searchCriteria.addParam("statusList", statusList); - searchCriteria.addParam("publicScreenName", vXPortalUser.getPublicScreenName()); - searchCriteria.addParam("status", vXPortalUser.getStatus()); - searchCriteria.addParam("familyScreenName", vXPortalUser.getPublicScreenName()); - Mockito.when(daoManager.getEntityManager()).thenReturn(entityManager); - Mockito.when(entityManager.createQuery(Mockito.anyString())).thenReturn(query); - Query newQuery = userMgr.createUserSearchQuery(query.toString(),queryString,searchCriteria); - Assert.assertNotNull(newQuery); - userRoleList.add("ROLE_SYS_ADMIN"); - statusList.add(0); - searchCriteria.addParam("statusList", statusList); - searchCriteria.addParam("roleList", userRoleList); - newQuery = userMgr.createUserSearchQuery(query.toString(),queryString,searchCriteria); - } - - @Test - public void test38mapVXPortalUserToXXPortalUser() { - Collection existingRoleList = new ArrayList(); - existingRoleList.add(RangerConstants.ROLE_USER); - VXPortalUser dbVXPortalUser = userMgr.mapXXPortalUserToVXPortalUser(null,existingRoleList); - XXPortalUser user = new XXPortalUser(); - Assert.assertNull(dbVXPortalUser); - dbVXPortalUser = userMgr.mapXXPortalUserToVXPortalUser(user,existingRoleList); - Assert.assertNull(dbVXPortalUser); - } - - @Test - public void test39gjUserToUserProfile() { - VXPortalUser vXPortalUser = new VXPortalUser(); - XXPortalUser xXPortalUser = new XXPortalUser(); - userMgr.gjUserToUserProfile(xXPortalUser,vXPortalUser); - } - - @Test - public void test40deleteUserRole() { - XXPortalUserRole xXPortalUserRole = new XXPortalUserRole(); - userMgr.deleteUserRole(1L,xXPortalUserRole); - } - - @Test - public void test41mapXXPortalUserToVXPortalUserForDefaultAccount() { - VXPortalUser vXPortalUser=userProfile(); - XXPortalUser xXPortalUser = xxPortalUser(vXPortalUser); - XXPortalUserRoleDao roleDao = Mockito.mock(XXPortalUserRoleDao.class); - Mockito.when(daoManager.getXXPortalUserRole()).thenReturn(roleDao); - XXPortalUserRole XXPortalUserRole = new XXPortalUserRole(); - XXPortalUserRole.setId(userId); - XXPortalUserRole.setUserRole("ROLE_USER"); - List list = new ArrayList(); - list.add(XXPortalUserRole); - Mockito.when(roleDao.findByParentId(xXPortalUser.getId())).thenReturn(list); - VXPortalUser dbVXPortalUser = userMgr.mapXXPortalUserToVXPortalUserForDefaultAccount(xXPortalUser); - Assert.assertNotNull(dbVXPortalUser); - } - - @Test - public void test42EncryptWithOlderAlgo() { - VXPortalUser vXPortalUser = userProfile(); - String encodedpasswd = userMgr.encryptWithOlderAlgo(vXPortalUser.getLoginId(), vXPortalUser.getPassword()); - Assert.assertNotNull(encodedpasswd); - encodedpasswd = userMgr.encryptWithOlderAlgo(null, vXPortalUser.getPassword()); - Assert.assertNotNull(encodedpasswd); - encodedpasswd = userMgr.encryptWithOlderAlgo(vXPortalUser.getLoginId(), null); - Assert.assertNotNull(encodedpasswd); - encodedpasswd = userMgr.encryptWithOlderAlgo(null, null); - Assert.assertNotNull(encodedpasswd); - } - - @Test - public void test43IsNewPasswordDifferent() { - VXPortalUser vXPortalUser = userProfile(); - String newCred = "New5ecret4User21"; - boolean isDifferent = userMgr.isNewPasswordDifferent(vXPortalUser.getLoginId(), vXPortalUser.getPassword(), newCred); - Assert.assertTrue(isDifferent); - isDifferent = userMgr.isNewPasswordDifferent(vXPortalUser.getLoginId(), vXPortalUser.getPassword(), vXPortalUser.getPassword()); - Assert.assertFalse(isDifferent); - isDifferent = userMgr.isNewPasswordDifferent(vXPortalUser.getLoginId(), null, newCred); - Assert.assertTrue(isDifferent); - isDifferent = userMgr.isNewPasswordDifferent(null, vXPortalUser.getPassword(), newCred); - Assert.assertTrue(isDifferent); - isDifferent = userMgr.isNewPasswordDifferent(null, null , newCred); - Assert.assertTrue(isDifferent); - } - - @Test - public void test44IsPasswordValid() { - VXPortalUser vXPortalUser = userProfile(); - boolean isValid = userMgr.isPasswordValid(vXPortalUser.getLoginId(), "ceb4f32325eda6142bd65215f4c0f371" , vXPortalUser.getPassword()); - Assert.assertFalse(isValid); - } - - @Test - public void test45ChangePassword() { - destroySession(); - setupUser(); - VXPortalUser userProfile = userProfile(); - XXPortalUser user2 = new XXPortalUser(); - user2.setId(userId); - - XXPortalUserDao userDao = Mockito.mock(XXPortalUserDao.class); - Mockito.when(daoManager.getXXPortalUser()).thenReturn(userDao); - Mockito.when(daoManager.getXXPortalUser().findByLoginId(Mockito.anyString())).thenReturn(user2); - VXPasswordChange invalidpwdChange = new VXPasswordChange(); - invalidpwdChange.setId(userProfile.getId()); - invalidpwdChange.setLoginId(userProfile.getLoginId()); - invalidpwdChange.setOldPassword("invalidOldPassword"); - invalidpwdChange.setEmailAddress(userProfile.getEmailAddress()); - invalidpwdChange.setUpdPassword(userProfile.getPassword()); - Mockito.when(restErrorUtil.createRESTException(HttpServletResponse.SC_FORBIDDEN, "Logged-In user is not allowed to access requested user data", true)).thenThrow(new WebApplicationException()); - thrown.expect(WebApplicationException.class); - userMgr.changePassword(invalidpwdChange); - } - - @Test - public void test46ChangePassword() { - destroySession(); - setupUser(); - VXPortalUser userProfile = userProfile(); - XXPortalUser gjUser = new XXPortalUser(); - gjUser.setId(userId); - VXPasswordChange invalidpwdChange = new VXPasswordChange(); - invalidpwdChange.setId(userProfile.getId()); - invalidpwdChange.setLoginId(userProfile.getLoginId()+1); - invalidpwdChange.setOldPassword("invalidOldPassword"); - invalidpwdChange.setEmailAddress(userProfile.getEmailAddress()); - invalidpwdChange.setUpdPassword(userProfile.getPassword()); - - XXPortalUserDao userDao = Mockito.mock(XXPortalUserDao.class); - Mockito.when(daoManager.getXXPortalUser()).thenReturn(userDao); - Mockito.when(userDao.findByLoginId(invalidpwdChange.getLoginId())).thenReturn(gjUser); - - Mockito.when(restErrorUtil.createRESTException(HttpServletResponse.SC_FORBIDDEN, "Logged-In user is not allowed to access requested user data", true)).thenThrow(new WebApplicationException()); - thrown.expect(WebApplicationException.class); - userMgr.changePassword(invalidpwdChange); - } - - @Test - public void test47ChangePasswordAsUser() { - destroySession(); - setupUser(); - XXPortalUserDao userDao = Mockito.mock(XXPortalUserDao.class); - VXPortalUser userProfile = userProfile(); - - VXPasswordChange pwdChange = new VXPasswordChange(); - pwdChange.setId(userProfile.getId()); - pwdChange.setLoginId(userProfile.getLoginId()); - pwdChange.setOldPassword(userProfile.getPassword()); - pwdChange.setEmailAddress(userProfile.getEmailAddress()); - pwdChange.setUpdPassword(userProfile.getPassword()); - - XXPortalUser user = new XXPortalUser(); - user.setId(userProfile.getId()); - user.setLoginId(userProfile.getLoginId()); - String encryptCred = userMgr.encrypt(userProfile.getLoginId(), userProfile.getPassword()); - user.setPassword(encryptCred); - user.setOldPasswords(encryptCred); - Mockito.when(daoManager.getXXPortalUser()).thenReturn(userDao); - Mockito.when(userDao.findByLoginId(Mockito.anyString())).thenReturn(user); - Mockito.when(stringUtil.equals(Mockito.anyString(), Mockito.nullable(String.class))).thenReturn(true); - Mockito.when(daoManager.getXXPortalUser()).thenReturn(userDao); - Mockito.when(stringUtil.validatePassword(Mockito.anyString(), Mockito.any(String[].class))).thenReturn(true); - Mockito.when(userDao.findByLoginId(Mockito.anyString())).thenReturn(user); - XXPortalUserRoleDao xPortalUserRoleDao = Mockito.mock(XXPortalUserRoleDao.class); - Mockito.when(daoManager.getXXPortalUserRole()).thenReturn(xPortalUserRoleDao); - List xPortalUserRoleList = new ArrayList(); - XXPortalUserRole XXPortalUserRole = new XXPortalUserRole(); - XXPortalUserRole.setId(userId); - XXPortalUserRole.setUserId(userId); - XXPortalUserRole.setUserRole("ROLE_USER"); - xPortalUserRoleList.add(XXPortalUserRole); - XXUserPermissionDao xUserPermissionDao = Mockito.mock(XXUserPermissionDao.class); - XXGroupPermissionDao xGroupPermissionDao = Mockito.mock(XXGroupPermissionDao.class); - Mockito.when(daoManager.getXXUserPermission()).thenReturn(xUserPermissionDao); - List xUserPermissionsList = new ArrayList(); - List xGroupPermissionList = new ArrayList(); - Mockito.when(xUserPermissionDao.findByUserPermissionIdAndIsAllowed(userProfile.getId())).thenReturn(xUserPermissionsList); - Mockito.when(daoManager.getXXGroupPermission()).thenReturn(xGroupPermissionDao); - Mockito.when(xGroupPermissionDao.findbyVXPortalUserId(userProfile.getId())).thenReturn(xGroupPermissionList); - XXPortalUserRoleDao roleDao = Mockito.mock(XXPortalUserRoleDao.class); - Mockito.when(daoManager.getXXPortalUserRole()).thenReturn(roleDao); - Mockito.when(roleDao.findByParentId(Mockito.anyLong())).thenReturn(xPortalUserRoleList); - Mockito.when(restErrorUtil.createRESTException("serverMsg.userMgrOldPassword",MessageEnums.INVALID_INPUT_DATA, user.getId(), "password", user.toString())).thenThrow(new WebApplicationException()); - thrown.expect(WebApplicationException.class); - userMgr.changePassword(pwdChange); - } - - @Test - public void test48ChangePasswordAsUser() { - destroySession(); - setupUser(); - XXPortalUserDao userDao = Mockito.mock(XXPortalUserDao.class); - VXPortalUser userProfile = userProfile(); - - VXPasswordChange pwdChange = new VXPasswordChange(); - pwdChange.setId(userProfile.getId()); - pwdChange.setLoginId(userProfile.getLoginId()); - pwdChange.setOldPassword(userProfile.getPassword()); - pwdChange.setEmailAddress(userProfile.getEmailAddress()); - pwdChange.setUpdPassword(userProfile.getPassword()); - - XXPortalUser user = new XXPortalUser(); - user.setId(userProfile.getId()); - user.setLoginId(userProfile.getLoginId()); - String encryptCred = userMgr.encrypt(userProfile.getLoginId(), userProfile.getPassword()); - user.setPassword(encryptCred); - Mockito.when(daoManager.getXXPortalUser()).thenReturn(userDao); - Mockito.when(userDao.findByLoginId(Mockito.anyString())).thenReturn(user); - Mockito.when(stringUtil.equals(Mockito.anyString(), Mockito.nullable(String.class))).thenReturn(true); - Mockito.when(daoManager.getXXPortalUser()).thenReturn(userDao); - Mockito.when(stringUtil.validatePassword(Mockito.anyString(), Mockito.any(String[].class))).thenReturn(false); - Mockito.when(userDao.findByLoginId(Mockito.anyString())).thenReturn(user); - XXPortalUserRoleDao xPortalUserRoleDao = Mockito.mock(XXPortalUserRoleDao.class); - Mockito.when(daoManager.getXXPortalUserRole()).thenReturn(xPortalUserRoleDao); - List xPortalUserRoleList = new ArrayList(); - XXPortalUserRole XXPortalUserRole = new XXPortalUserRole(); - XXPortalUserRole.setId(userId); - XXPortalUserRole.setUserId(userId); - XXPortalUserRole.setUserRole("ROLE_USER"); - xPortalUserRoleList.add(XXPortalUserRole); - XXUserPermissionDao xUserPermissionDao = Mockito.mock(XXUserPermissionDao.class); - XXGroupPermissionDao xGroupPermissionDao = Mockito.mock(XXGroupPermissionDao.class); - Mockito.when(daoManager.getXXUserPermission()).thenReturn(xUserPermissionDao); - List xUserPermissionsList = new ArrayList(); - List xGroupPermissionList = new ArrayList(); - Mockito.when(xUserPermissionDao.findByUserPermissionIdAndIsAllowed(userProfile.getId())).thenReturn(xUserPermissionsList); - Mockito.when(daoManager.getXXGroupPermission()).thenReturn(xGroupPermissionDao); - Mockito.when(xGroupPermissionDao.findbyVXPortalUserId(userProfile.getId())).thenReturn(xGroupPermissionList); - XXPortalUserRoleDao roleDao = Mockito.mock(XXPortalUserRoleDao.class); - Mockito.when(daoManager.getXXPortalUserRole()).thenReturn(roleDao); - Mockito.when(roleDao.findByParentId(Mockito.anyLong())).thenReturn(xPortalUserRoleList); - Mockito.when(restErrorUtil.createRESTException("serverMsg.userMgrNewPassword",MessageEnums.INVALID_PASSWORD, null, null, pwdChange.getLoginId())).thenThrow(new WebApplicationException()); - thrown.expect(WebApplicationException.class); - userMgr.changePassword(pwdChange); - } - - @Test - public void test49CreateDefaultAccountUser() { - destroySession(); - setup(); - XXPortalUserDao userDao = Mockito.mock(XXPortalUserDao.class); - XXPortalUserRoleDao roleDao = Mockito.mock(XXPortalUserRoleDao.class); - VXPortalUser userProfile = userProfile(); - userProfile.setStatus(RangerCommonEnums.USER_EXTERNAL); - Collection userRoleList = new ArrayList(); - userRoleList.add("ROLE_USER"); - userProfile.setUserRoleList(userRoleList); - XXPortalUser user = new XXPortalUser(); - user.setEmailAddress(userProfile.getEmailAddress()); - user.setUserSource(RangerCommonEnums.USER_EXTERNAL); - XXPortalUserRole XXPortalUserRole = new XXPortalUserRole(); - XXPortalUserRole.setId(userId); - XXPortalUserRole.setUserRole("ROLE_USER"); - - List list = new ArrayList(); - list.add(XXPortalUserRole); - - Mockito.when(daoManager.getXXPortalUser()).thenReturn(userDao); - Mockito.when(userDao.findByLoginId(Mockito.anyString())).thenReturn(null, user); - Mockito.when(userDao.findByEmailAddress(Mockito.anyString())).thenReturn(null); - Mockito.when(daoManager.getXXPortalUserRole()).thenReturn(roleDao); - Mockito.when(userDao.create((XXPortalUser) Mockito.any())).thenReturn(user); - Mockito.doNothing().when(rangerBizUtil).blockAuditorRoleUser(); - userProfile.setEmailAddress(null); - VXPortalUser dbVXPortalUser = userMgr.createDefaultAccountUser(userProfile); - Assert.assertNotNull(dbVXPortalUser); - Assert.assertEquals(user.getId(), dbVXPortalUser.getId()); - Assert.assertEquals(user.getFirstName(), dbVXPortalUser.getFirstName()); - Assert.assertEquals(user.getLastName(), dbVXPortalUser.getLastName()); - Assert.assertEquals(user.getLoginId(), dbVXPortalUser.getLoginId()); - Assert.assertEquals(user.getEmailAddress(),dbVXPortalUser.getEmailAddress()); - Assert.assertEquals(user.getPassword(), dbVXPortalUser.getPassword()); - Mockito.verify(daoManager, Mockito.atLeast(1)).getXXPortalUser(); - Mockito.verify(daoManager, Mockito.atLeast(1)).getXXPortalUserRole(); - - Mockito.when(userDao.findByLoginId(Mockito.anyString())).thenReturn(null); - Mockito.when(userDao.findByEmailAddress(Mockito.anyString())).thenReturn(user); - Mockito.when(restErrorUtil.createRESTException("The email address " + user.getEmailAddress() + " you've provided already exists. Please try again with different email address.", MessageEnums.OPER_NOT_ALLOWED_FOR_STATE)).thenThrow(new WebApplicationException()); - thrown.expect(WebApplicationException.class); - userProfile.setEmailAddress(user.getEmailAddress()); - userMgr.createDefaultAccountUser(userProfile); - } - - @Test - public void test50AddUserRole() { - setupUser(); - XXPortalUserRole XXPortalUserRole = new XXPortalUserRole(); - XXPortalUserRole.setId(userId); - XXPortalUserRole.setUserRole("ROLE_USER"); - List list = new ArrayList(); - list.add(XXPortalUserRole); - XXPortalUserRoleDao userDao = Mockito.mock(XXPortalUserRoleDao.class); - Mockito.when(daoManager.getXXPortalUserRole()).thenReturn(userDao); - Mockito.when(userDao.findByUserId(userId)).thenReturn(list); - try { - userMgr.addUserRole(userId, "ROLE_SYS_ADMIN"); - } catch (Exception e) { - } - destroySession(); - userMgr.addUserRole(userId, "ROLE_SYS_ADMIN"); - } - - @Test - public void test51UpdateUserWithPass() { - setup(); - XXPortalUserDao userDao = Mockito.mock(XXPortalUserDao.class); - VXPortalUser userProfile = userProfile(); - userProfile.setPassword("password1234"); - XXPortalUser user = new XXPortalUser(); - user.setId(userProfile.getId()); - user.setLoginId(userProfile.getLoginId()); - user.setEmailAddress(userProfile.getEmailAddress()); - user.setLoginId(userProfile.getLoginId()); - String encryptedPwd = userMgr.encrypt(userProfile.getLoginId(),userProfile.getPassword()); - user.setPassword(encryptedPwd); - Mockito.when(daoManager.getXXPortalUser()).thenReturn(userDao); - Mockito.when(userDao.getById(userProfile.getId())).thenReturn(user); - Mockito.when(restErrorUtil.createRESTException(HttpServletResponse.SC_FORBIDDEN, "Logged-In user is not allowed to access requested user data", true)).thenThrow(new WebApplicationException()); - thrown.expect(WebApplicationException.class); - userMgr.updateUserWithPass(userProfile); - } + private static Long userId = 1L; + private static final String userLoginID = "testuser"; + @Rule + public ExpectedException thrown = ExpectedException.none(); + @InjectMocks + UserMgr userMgr = new UserMgr(); + @Mock + VXPortalUser vxPortalUser; + @Mock + RangerDaoManager daoManager; + @Mock + RESTErrorUtil restErrorUtil; + @Mock + ContextUtil contextUtil; + @Mock + StringUtil stringUtil; + @Mock + SearchUtil searchUtil; + @Mock + RangerBizUtil rangerBizUtil; + @Mock + XUserPermissionService xUserPermissionService; + @Mock + XGroupPermissionService xGroupPermissionService; + @Mock + SessionMgr sessionMgr; + @Mock + XUserMgr xUserMgr; + @Mock + XPortalUserService xPortalUserService; + + public void setup() { + RangerSecurityContext context = new RangerSecurityContext(); + context.setUserSession(new UserSessionBase()); + RangerContextHolder.setSecurityContext(context); + UserSessionBase currentUserSession = ContextUtil.getCurrentUserSession(); + currentUserSession.setUserAdmin(true); + } + + public void setupKeyAdmin() { + RangerSecurityContext context = new RangerSecurityContext(); + context.setUserSession(new UserSessionBase()); + RangerContextHolder.setSecurityContext(context); + UserSessionBase currentUserSession = ContextUtil.getCurrentUserSession(); + XXPortalUser userKeyAdmin = new XXPortalUser(); + userKeyAdmin.setId(userProfile().getId()); + userKeyAdmin.setLoginId(userProfile().getLoginId()); + currentUserSession.setXXPortalUser(userKeyAdmin); + currentUserSession.setKeyAdmin(true); + } + + public void setupUser() { + RangerSecurityContext context = new RangerSecurityContext(); + context.setUserSession(new UserSessionBase()); + RangerContextHolder.setSecurityContext(context); + UserSessionBase currentUserSession = ContextUtil.getCurrentUserSession(); + XXPortalUser user = new XXPortalUser(); + user.setId(userProfile().getId()); + user.setLoginId(userProfile().getLoginId()); + currentUserSession.setXXPortalUser(user); + } + + public void setupRangerUserSyncUser() { + RangerSecurityContext context = new RangerSecurityContext(); + context.setUserSession(new UserSessionBase()); + RangerContextHolder.setSecurityContext(context); + UserSessionBase currentUserSession = ContextUtil.getCurrentUserSession(); + XXPortalUser user = new XXPortalUser(); + user.setId(1L); + user.setLoginId("rangerusersync"); + user.setEmailAddress("test@test.com"); + currentUserSession.setXXPortalUser(user); + currentUserSession.setUserAdmin(true); + } + + @After + public void destroySession() { + RangerSecurityContext context = new RangerSecurityContext(); + context.setUserSession(null); + RangerContextHolder.setSecurityContext(context); + } + + @Test + public void test01CreateUser() { + setup(); + XXPortalUserDao userDao = Mockito.mock(XXPortalUserDao.class); + XXPortalUserRoleDao roleDao = Mockito.mock(XXPortalUserRoleDao.class); + + VXPortalUser userProfile = userProfile(); + + Collection userRoleList = new ArrayList<>(); + userRoleList.add("ROLE_USER"); + + XXPortalUser user = new XXPortalUser(); + user.setEmailAddress(userProfile.getEmailAddress()); + user.setFirstName(userProfile.getFirstName()); + user.setLastName(userProfile.getLastName()); + user.setLoginId(userProfile.getLoginId()); + user.setPassword(userProfile.getPassword()); + user.setUserSource(userProfile.getUserSource()); + user.setPublicScreenName(userProfile.getPublicScreenName()); + user.setId(userProfile.getId()); + + XXPortalUserRole xxPortalUserRole = new XXPortalUserRole(); + xxPortalUserRole.setId(user.getId()); + xxPortalUserRole.setUserRole("ROLE_USER"); + List list = new ArrayList<>(); + list.add(xxPortalUserRole); + + Mockito.when(daoManager.getXXPortalUser()).thenReturn(userDao); + Mockito.when(userDao.create(Mockito.any())).thenReturn(user); + Mockito.when(daoManager.getXXPortalUserRole()).thenReturn(roleDao); + Mockito.when(roleDao.findByUserId(userId)).thenReturn(list); + Mockito.doNothing().when(rangerBizUtil).blockAuditorRoleUser(); + Mockito.when(userDao.findByLoginId(Mockito.anyString())).thenReturn(user); + XXPortalUser dbxxPortalUser = userMgr.createUser(userProfile, 1, userRoleList); + Assert.assertNotNull(dbxxPortalUser); + userId = dbxxPortalUser.getId(); + + Assert.assertEquals(userId, dbxxPortalUser.getId()); + Assert.assertEquals(userProfile.getFirstName(), dbxxPortalUser.getFirstName()); + Assert.assertEquals(userProfile.getFirstName(), dbxxPortalUser.getFirstName()); + Assert.assertEquals(userProfile.getLastName(), dbxxPortalUser.getLastName()); + Assert.assertEquals(userProfile.getLoginId(), dbxxPortalUser.getLoginId()); + Assert.assertEquals(userProfile.getEmailAddress(), dbxxPortalUser.getEmailAddress()); + Assert.assertEquals(userProfile.getPassword(), dbxxPortalUser.getPassword()); + + Mockito.verify(daoManager, Mockito.atLeast(1)).getXXPortalUser(); + Mockito.verify(daoManager).getXXPortalUserRole(); + } + + @Test + public void test02CreateUser() { + setup(); + XXPortalUserDao userDao = Mockito.mock(XXPortalUserDao.class); + XXPortalUserRoleDao roleDao = Mockito.mock(XXPortalUserRoleDao.class); + + VXPortalUser userProfile = userProfile(); + Collection userRoleList = new ArrayList<>(); + userRoleList.add("ROLE_USER"); + userProfile.setUserRoleList(userRoleList); + + XXPortalUser user = new XXPortalUser(); + user.setEmailAddress(userProfile.getEmailAddress()); + user.setFirstName(userProfile.getFirstName()); + user.setLastName(userProfile.getLastName()); + user.setLoginId(userProfile.getLoginId()); + user.setPassword(userProfile.getPassword()); + user.setUserSource(userProfile.getUserSource()); + user.setPublicScreenName(userProfile.getPublicScreenName()); + user.setId(userProfile.getId()); + + XXPortalUserRole xxPortalUserRole = new XXPortalUserRole(); + xxPortalUserRole.setId(user.getId()); + xxPortalUserRole.setUserRole("ROLE_USER"); + List list = new ArrayList<>(); + list.add(xxPortalUserRole); + + Mockito.when(daoManager.getXXPortalUser()).thenReturn(userDao); + Mockito.when(userDao.create(Mockito.any())).thenReturn(user); + Mockito.when(daoManager.getXXPortalUserRole()).thenReturn(roleDao); + Mockito.when(roleDao.findByUserId(userId)).thenReturn(list); + Mockito.doNothing().when(rangerBizUtil).blockAuditorRoleUser(); + Mockito.when(userDao.findByLoginId(Mockito.anyString())).thenReturn(user); + XXPortalUser dbxxPortalUser = userMgr.createUser(userProfile, 1); + userId = dbxxPortalUser.getId(); + + Assert.assertNotNull(dbxxPortalUser); + Assert.assertEquals(userId, dbxxPortalUser.getId()); + Assert.assertEquals(userProfile.getFirstName(), dbxxPortalUser.getFirstName()); + Assert.assertEquals(userProfile.getFirstName(), dbxxPortalUser.getFirstName()); + Assert.assertEquals(userProfile.getLastName(), dbxxPortalUser.getLastName()); + Assert.assertEquals(userProfile.getLoginId(), dbxxPortalUser.getLoginId()); + Assert.assertEquals(userProfile.getEmailAddress(), dbxxPortalUser.getEmailAddress()); + Assert.assertEquals(userProfile.getPassword(), dbxxPortalUser.getPassword()); + + Mockito.verify(daoManager, Mockito.atLeast(1)).getXXPortalUser(); + Mockito.verify(daoManager).getXXPortalUserRole(); + } + + @Test + public void test03ChangePasswordAsAdmin() { + setup(); + XXPortalUserDao userDao = Mockito.mock(XXPortalUserDao.class); + VXPortalUser userProfile = userProfile(); + + VXPasswordChange pwdChange = new VXPasswordChange(); + pwdChange.setId(userProfile.getId()); + pwdChange.setLoginId(userProfile.getLoginId()); + pwdChange.setOldPassword(userProfile.getPassword()); + pwdChange.setEmailAddress(userProfile.getEmailAddress()); + pwdChange.setUpdPassword(userProfile.getPassword()); + + XXPortalUser user = new XXPortalUser(); + + Mockito.when(daoManager.getXXPortalUser()).thenReturn(userDao); + Mockito.when(userDao.findByLoginId(Mockito.nullable(String.class))).thenReturn(user); + + XXPortalUserRoleDao xPortalUserRoleDao = Mockito.mock(XXPortalUserRoleDao.class); + Mockito.when(daoManager.getXXPortalUserRole()).thenReturn(xPortalUserRoleDao); + List xPortalUserRoleList = new ArrayList<>(); + XXPortalUserRole xxPortalUserRole = new XXPortalUserRole(); + xxPortalUserRole.setId(userId); + xxPortalUserRole.setUserId(userId); + xxPortalUserRole.setUserRole("ROLE_USER"); + xPortalUserRoleList.add(xxPortalUserRole); + XXUserPermissionDao xUserPermissionDao = Mockito.mock(XXUserPermissionDao.class); + XXGroupPermissionDao xGroupPermissionDao = Mockito.mock(XXGroupPermissionDao.class); + Mockito.when(daoManager.getXXUserPermission()).thenReturn(xUserPermissionDao); + Mockito.when(daoManager.getXXGroupPermission()).thenReturn(xGroupPermissionDao); + XXPortalUserRoleDao roleDao = Mockito.mock(XXPortalUserRoleDao.class); + Mockito.when(daoManager.getXXPortalUserRole()).thenReturn(roleDao); + Mockito.when(restErrorUtil.createRESTException(HttpServletResponse.SC_FORBIDDEN, "Logged-In user is not allowed to access requested user data", true)).thenThrow(new WebApplicationException()); + thrown.expect(WebApplicationException.class); + + VXResponse dbVXResponse = userMgr.changePassword(pwdChange); + Assert.assertNotNull(dbVXResponse); + Assert.assertEquals(userProfile.getStatus(), dbVXResponse.getStatusCode()); + + Mockito.verify(stringUtil).equals(Mockito.anyString(), Mockito.nullable(String.class)); + Mockito.verify(stringUtil).validatePassword(Mockito.anyString(), Mockito.any(String[].class)); + + XXPortalUser user2 = new XXPortalUser(); + user2.setId(userId); + Mockito.when(userDao.findByLoginId(Mockito.anyString())).thenReturn(user2); + VXPasswordChange invalidpwdChange = new VXPasswordChange(); + invalidpwdChange.setId(userProfile.getId()); + invalidpwdChange.setLoginId(userProfile.getLoginId()); + invalidpwdChange.setOldPassword("invalidOldPassword"); + invalidpwdChange.setEmailAddress(userProfile.getEmailAddress()); + invalidpwdChange.setUpdPassword(userProfile.getPassword()); + thrown.expect(WebApplicationException.class); + userMgr.changePassword(invalidpwdChange); + + XXPortalUser externalUser = new XXPortalUser(); + externalUser.setUserSource(RangerCommonEnums.USER_EXTERNAL); + Mockito.when(userDao.findByLoginId(Mockito.anyString())).thenReturn(externalUser); + VXResponse vXResponse = new VXResponse(); + vXResponse.setStatusCode(HttpServletResponse.SC_FORBIDDEN); + vXResponse.setMsgDesc("SECURITY:changePassword().Ranger External Users cannot change password. LoginId=" + pwdChange.getLoginId()); + Mockito.when(restErrorUtil.generateRESTException(Mockito.any())).thenReturn(new WebApplicationException()); + thrown.expect(WebApplicationException.class); + userMgr.changePassword(pwdChange); + } + + @Test + public void test04ChangePasswordAsKeyAdmin() { + setupKeyAdmin(); + XXPortalUserDao userDao = Mockito.mock(XXPortalUserDao.class); + VXPortalUser userProfile = userProfile(); + + VXPasswordChange pwdChange = new VXPasswordChange(); + pwdChange.setId(userProfile.getId()); + pwdChange.setLoginId(userProfile.getLoginId()); + pwdChange.setOldPassword(userProfile.getPassword()); + pwdChange.setEmailAddress(userProfile.getEmailAddress()); + pwdChange.setUpdPassword(userProfile.getPassword()); + + XXPortalUser userKeyAdmin = new XXPortalUser(); + userKeyAdmin.setId(userProfile.getId()); + userKeyAdmin.setLoginId(userProfile.getLoginId()); + Mockito.when(daoManager.getXXPortalUser()).thenReturn(userDao); + Mockito.when(userDao.findByLoginId(Mockito.anyString())).thenReturn(userKeyAdmin); + Mockito.when(stringUtil.equals(Mockito.anyString(), Mockito.nullable(String.class))).thenReturn(true); + Mockito.when(daoManager.getXXPortalUser()).thenReturn(userDao); + Mockito.when(stringUtil.validatePassword(Mockito.anyString(), Mockito.any(String[].class))).thenReturn(true); + + XXPortalUserRoleDao xPortalUserRoleDao = Mockito.mock(XXPortalUserRoleDao.class); + Mockito.when(daoManager.getXXPortalUserRole()).thenReturn(xPortalUserRoleDao); + List xPortalUserRoleList = new ArrayList<>(); + XXPortalUserRole xxPortalUserRole = new XXPortalUserRole(); + xxPortalUserRole.setId(userId); + xxPortalUserRole.setUserId(userId); + xxPortalUserRole.setUserRole("ROLE_USER"); + xPortalUserRoleList.add(xxPortalUserRole); + XXPortalUserRoleDao roleDao = Mockito.mock(XXPortalUserRoleDao.class); + Mockito.when(daoManager.getXXPortalUserRole()).thenReturn(roleDao); + Mockito.when(roleDao.findByParentId(Mockito.anyLong())).thenReturn(xPortalUserRoleList); + XXUserPermissionDao xUserPermissionDao = Mockito.mock(XXUserPermissionDao.class); + XXGroupPermissionDao xGroupPermissionDao = Mockito.mock(XXGroupPermissionDao.class); + Mockito.when(daoManager.getXXUserPermission()).thenReturn(xUserPermissionDao); + List xUserPermissionsList = new ArrayList<>(); + List xGroupPermissionList = new ArrayList<>(); + Mockito.when(xUserPermissionDao.findByUserPermissionIdAndIsAllowed(userProfile.getId())).thenReturn(xUserPermissionsList); + Mockito.when(daoManager.getXXGroupPermission()).thenReturn(xGroupPermissionDao); + Mockito.when(xGroupPermissionDao.findbyVXPortalUserId(userProfile.getId())).thenReturn(xGroupPermissionList); + VXResponse dbVXResponse = userMgr.changePassword(pwdChange); + Assert.assertNotNull(dbVXResponse); + Assert.assertEquals(userProfile.getStatus(), dbVXResponse.getStatusCode()); + + Mockito.verify(stringUtil).equals(Mockito.anyString(), Mockito.nullable(String.class)); + Mockito.verify(stringUtil).validatePassword(Mockito.anyString(), Mockito.any(String[].class)); + } + + @Test + public void test05ChangePasswordAsUser() { + setupUser(); + XXPortalUserDao userDao = Mockito.mock(XXPortalUserDao.class); + VXPortalUser userProfile = userProfile(); + + VXPasswordChange pwdChange = new VXPasswordChange(); + pwdChange.setId(userProfile.getId()); + pwdChange.setLoginId(userProfile.getLoginId()); + pwdChange.setOldPassword(userProfile.getPassword()); + pwdChange.setEmailAddress(userProfile.getEmailAddress()); + pwdChange.setUpdPassword(userProfile.getPassword()); + + XXPortalUser user = new XXPortalUser(); + user.setId(userProfile.getId()); + user.setLoginId(userProfile.getLoginId()); + Mockito.when(daoManager.getXXPortalUser()).thenReturn(userDao); + Mockito.when(userDao.findByLoginId(Mockito.anyString())).thenReturn(user); + Mockito.when(stringUtil.equals(Mockito.anyString(), Mockito.nullable(String.class))).thenReturn(true); + Mockito.when(daoManager.getXXPortalUser()).thenReturn(userDao); + Mockito.when(stringUtil.validatePassword(Mockito.anyString(), Mockito.any(String[].class))).thenReturn(true); + Mockito.when(userDao.findByLoginId(Mockito.anyString())).thenReturn(user); + XXPortalUserRoleDao xPortalUserRoleDao = Mockito.mock(XXPortalUserRoleDao.class); + Mockito.when(daoManager.getXXPortalUserRole()).thenReturn(xPortalUserRoleDao); + List xPortalUserRoleList = new ArrayList<>(); + XXPortalUserRole xxPortalUserRole = new XXPortalUserRole(); + xxPortalUserRole.setId(userId); + xxPortalUserRole.setUserId(userId); + xxPortalUserRole.setUserRole("ROLE_USER"); + xPortalUserRoleList.add(xxPortalUserRole); + XXUserPermissionDao xUserPermissionDao = Mockito.mock(XXUserPermissionDao.class); + XXGroupPermissionDao xGroupPermissionDao = Mockito.mock(XXGroupPermissionDao.class); + Mockito.when(daoManager.getXXUserPermission()).thenReturn(xUserPermissionDao); + List xUserPermissionsList = new ArrayList<>(); + List xGroupPermissionList = new ArrayList<>(); + Mockito.when(xUserPermissionDao.findByUserPermissionIdAndIsAllowed(userProfile.getId())).thenReturn(xUserPermissionsList); + Mockito.when(daoManager.getXXGroupPermission()).thenReturn(xGroupPermissionDao); + Mockito.when(xGroupPermissionDao.findbyVXPortalUserId(userProfile.getId())).thenReturn(xGroupPermissionList); + XXPortalUserRoleDao roleDao = Mockito.mock(XXPortalUserRoleDao.class); + Mockito.when(daoManager.getXXPortalUserRole()).thenReturn(roleDao); + Mockito.when(roleDao.findByParentId(Mockito.anyLong())).thenReturn(xPortalUserRoleList); + + VXResponse dbVXResponse = userMgr.changePassword(pwdChange); + Assert.assertNotNull(dbVXResponse); + Assert.assertEquals(userProfile.getStatus(), dbVXResponse.getStatusCode()); + + Mockito.verify(stringUtil).equals(Mockito.anyString(), Mockito.nullable(String.class)); + Mockito.verify(stringUtil).validatePassword(Mockito.anyString(), Mockito.any(String[].class)); + } + + @Test + public void test06ChangeEmailAddressAsAdmin() { + setup(); + XXPortalUserDao userDao = Mockito.mock(XXPortalUserDao.class); + XXPortalUserRoleDao roleDao = Mockito.mock(XXPortalUserRoleDao.class); + XXUserPermissionDao xUserPermissionDao = Mockito.mock(XXUserPermissionDao.class); + XXGroupPermissionDao xGroupPermissionDao = Mockito.mock(XXGroupPermissionDao.class); + XXModuleDefDao xModuleDefDao = Mockito.mock(XXModuleDefDao.class); + + XXModuleDef xModuleDef = new XXModuleDef(); + xModuleDef.setUpdatedByUserId(userId); + xModuleDef.setAddedByUserId(userId); + xModuleDef.setCreateTime(new Date()); + xModuleDef.setId(userId); + xModuleDef.setModule("Policy manager"); + xModuleDef.setUpdateTime(new Date()); + xModuleDef.setUrl("/policy manager"); + + VXPortalUser userProfile = userProfile(); + + XXPortalUser user = new XXPortalUser(); + user.setEmailAddress(userProfile.getEmailAddress()); + user.setFirstName(userProfile.getFirstName()); + user.setLastName(userProfile.getLastName()); + user.setLoginId(userProfile.getLoginId()); + String encryptedPwd = userMgr.encrypt(userProfile.getLoginId(), userProfile.getPassword()); + user.setPassword(encryptedPwd); + user.setUserSource(userProfile.getUserSource()); + user.setPublicScreenName(userProfile.getPublicScreenName()); + user.setId(userProfile.getId()); + + VXPasswordChange changeEmail = new VXPasswordChange(); + changeEmail.setEmailAddress("testuser@test.com"); + changeEmail.setId(user.getId()); + changeEmail.setLoginId(user.getLoginId()); + changeEmail.setOldPassword(userProfile.getPassword()); + + XXPortalUserRole xxPortalUserRole = new XXPortalUserRole(); + xxPortalUserRole.setId(userId); + xxPortalUserRole.setUserRole("ROLE_USER"); + List list = new ArrayList<>(); + list.add(xxPortalUserRole); + + List xUserPermissionsList = new ArrayList<>(); + XXUserPermission xUserPermissionObj = new XXUserPermission(); + xUserPermissionObj.setAddedByUserId(userId); + xUserPermissionObj.setCreateTime(new Date()); + xUserPermissionObj.setId(userId); + xUserPermissionObj.setIsAllowed(1); + xUserPermissionObj.setModuleId(1L); + xUserPermissionObj.setUpdatedByUserId(userId); + xUserPermissionObj.setUpdateTime(new Date()); + xUserPermissionObj.setUserId(userId); + xUserPermissionsList.add(xUserPermissionObj); + + List xGroupPermissionList = new ArrayList<>(); + XXGroupPermission xGroupPermissionObj = new XXGroupPermission(); + xGroupPermissionObj.setAddedByUserId(userId); + xGroupPermissionObj.setCreateTime(new Date()); + xGroupPermissionObj.setId(userId); + xGroupPermissionObj.setIsAllowed(1); + xGroupPermissionObj.setModuleId(1L); + xGroupPermissionObj.setUpdatedByUserId(userId); + xGroupPermissionObj.setUpdateTime(new Date()); + xGroupPermissionObj.setGroupId(userId); + xGroupPermissionList.add(xGroupPermissionObj); + + VXUserPermission userPermission = new VXUserPermission(); + userPermission.setId(1L); + userPermission.setIsAllowed(1); + userPermission.setModuleId(1L); + userPermission.setUserId(userId); + userPermission.setUserName("xyz"); + userPermission.setOwner("admin"); + + VXGroupPermission groupPermission = new VXGroupPermission(); + groupPermission.setId(1L); + groupPermission.setIsAllowed(1); + groupPermission.setModuleId(1L); + groupPermission.setGroupId(userId); + groupPermission.setGroupName("xyz"); + groupPermission.setOwner("admin"); + + Mockito.when(stringUtil.validateEmail(Mockito.anyString())).thenReturn(true); + Mockito.when(daoManager.getXXPortalUser()).thenReturn(userDao); + Mockito.when(daoManager.getXXPortalUserRole()).thenReturn(roleDao); + Mockito.when(roleDao.findByParentId(Mockito.anyLong())).thenReturn(list); + Mockito.when(daoManager.getXXUserPermission()).thenReturn(xUserPermissionDao); + Mockito.when(daoManager.getXXGroupPermission()).thenReturn(xGroupPermissionDao); + Mockito.when(xUserPermissionDao.findByUserPermissionIdAndIsAllowed(userProfile.getId())).thenReturn(xUserPermissionsList); + Mockito.when(xGroupPermissionDao.findbyVXPortalUserId(userProfile.getId())).thenReturn(xGroupPermissionList); + Mockito.when(xGroupPermissionService.populateViewBean(xGroupPermissionObj)).thenReturn(groupPermission); + Mockito.when(xUserPermissionService.populateViewBean(xUserPermissionObj)).thenReturn(userPermission); + Mockito.when(daoManager.getXXModuleDef()).thenReturn(xModuleDefDao); + Mockito.when(xModuleDefDao.findByModuleId(Mockito.anyLong())).thenReturn(xModuleDef); + + Mockito.when(daoManager.getXXPortalUser()).thenReturn(userDao); + Mockito.when(userDao.findByLoginId(Mockito.anyString())).thenReturn(user); + Mockito.when(daoManager.getXXPortalUser()).thenReturn(userDao); + Mockito.when(userDao.findByLoginId(Mockito.anyString())).thenReturn(user); + XXPortalUserRoleDao xPortalUserRoleDao = Mockito.mock(XXPortalUserRoleDao.class); + Mockito.when(daoManager.getXXPortalUserRole()).thenReturn(xPortalUserRoleDao); + List xPortalUserRoleList = new ArrayList<>(); + xxPortalUserRole.setId(userId); + xxPortalUserRole.setUserId(userId); + xxPortalUserRole.setUserRole("ROLE_USER"); + xPortalUserRoleList.add(xxPortalUserRole); + Mockito.when(daoManager.getXXUserPermission()).thenReturn(xUserPermissionDao); + Mockito.when(xUserPermissionDao.findByUserPermissionIdAndIsAllowed(userProfile.getId())).thenReturn(xUserPermissionsList); + Mockito.when(daoManager.getXXGroupPermission()).thenReturn(xGroupPermissionDao); + Mockito.when(xGroupPermissionDao.findbyVXPortalUserId(userProfile.getId())).thenReturn(xGroupPermissionList); + Mockito.when(daoManager.getXXPortalUserRole()).thenReturn(roleDao); + Mockito.when(roleDao.findByParentId(Mockito.anyLong())).thenReturn(xPortalUserRoleList); + Mockito.when(daoManager.getXXModuleDef()).thenReturn(xModuleDefDao); + Mockito.when(xModuleDefDao.findByModuleId(Mockito.anyLong())).thenReturn(xModuleDef); + Mockito.when(restErrorUtil.createRESTException(HttpServletResponse.SC_FORBIDDEN, "Logged-In user is not allowed to access requested user data", true)).thenThrow(new WebApplicationException()); + thrown.expect(WebApplicationException.class); + VXPortalUser dbVXPortalUser = userMgr.changeEmailAddress(user, changeEmail); + Assert.assertNotNull(dbVXPortalUser); + Assert.assertEquals(userId, dbVXPortalUser.getId()); + Assert.assertEquals(userProfile.getLastName(), dbVXPortalUser.getLastName()); + Assert.assertEquals(changeEmail.getLoginId(), dbVXPortalUser.getLoginId()); + Assert.assertEquals(changeEmail.getEmailAddress(), dbVXPortalUser.getEmailAddress()); + user.setUserSource(RangerCommonEnums.USER_APP); + user.setUserSource(RangerCommonEnums.USER_EXTERNAL); + changeEmail.setEmailAddress(""); + dbVXPortalUser = userMgr.changeEmailAddress(user, changeEmail); + + Mockito.when(stringUtil.validateEmail(Mockito.anyString())).thenReturn(false); + changeEmail.setEmailAddress("test@123.com"); + Mockito.when(restErrorUtil.createRESTException("serverMsg.userMgrInvalidEmail", MessageEnums.INVALID_INPUT_DATA, changeEmail.getId(), "emailAddress", changeEmail.toString())).thenThrow(new WebApplicationException()); + thrown.expect(WebApplicationException.class); + userMgr.changeEmailAddress(user, changeEmail); + } + + @Test + public void test07ChangeEmailAddressAsKeyAdmin() { + setupKeyAdmin(); + XXPortalUserDao userDao = Mockito.mock(XXPortalUserDao.class); + XXPortalUserRoleDao roleDao = Mockito.mock(XXPortalUserRoleDao.class); + VXPortalUser userProfile = userProfile(); + + XXPortalUser userKeyAdmin = new XXPortalUser(); + userKeyAdmin.setEmailAddress(userProfile.getEmailAddress()); + userKeyAdmin.setFirstName(userProfile.getFirstName()); + userKeyAdmin.setLastName(userProfile.getLastName()); + userKeyAdmin.setLoginId(userProfile.getLoginId()); + String encryptedPwd = userMgr.encrypt(userProfile.getLoginId(), userProfile.getPassword()); + userKeyAdmin.setPassword(encryptedPwd); + userKeyAdmin.setUserSource(userProfile.getUserSource()); + userKeyAdmin.setPublicScreenName(userProfile.getPublicScreenName()); + userKeyAdmin.setId(userProfile.getId()); + + VXPasswordChange changeEmail = new VXPasswordChange(); + changeEmail.setEmailAddress("testuser@test.com"); + changeEmail.setId(userKeyAdmin.getId()); + changeEmail.setLoginId(userKeyAdmin.getLoginId()); + changeEmail.setOldPassword(userProfile.getPassword()); + + XXPortalUserRole xxPortalUserRole = new XXPortalUserRole(); + xxPortalUserRole.setId(userId); + xxPortalUserRole.setUserRole("ROLE_USER"); + List list = new ArrayList<>(); + list.add(xxPortalUserRole); + + List xUserPermissionsList = new ArrayList<>(); + XXUserPermission xUserPermissionObj = new XXUserPermission(); + xUserPermissionObj.setAddedByUserId(userId); + xUserPermissionObj.setCreateTime(new Date()); + xUserPermissionObj.setId(userId); + xUserPermissionObj.setIsAllowed(1); + xUserPermissionObj.setModuleId(1L); + xUserPermissionObj.setUpdatedByUserId(userId); + xUserPermissionObj.setUpdateTime(new Date()); + xUserPermissionObj.setUserId(userId); + xUserPermissionsList.add(xUserPermissionObj); + + List xGroupPermissionList = new ArrayList<>(); + XXGroupPermission xGroupPermissionObj = new XXGroupPermission(); + xGroupPermissionObj.setAddedByUserId(userId); + xGroupPermissionObj.setCreateTime(new Date()); + xGroupPermissionObj.setId(userId); + xGroupPermissionObj.setIsAllowed(1); + xGroupPermissionObj.setModuleId(1L); + xGroupPermissionObj.setUpdatedByUserId(userId); + xGroupPermissionObj.setUpdateTime(new Date()); + xGroupPermissionObj.setGroupId(userId); + xGroupPermissionList.add(xGroupPermissionObj); + + VXUserPermission userPermission = new VXUserPermission(); + userPermission.setId(1L); + userPermission.setIsAllowed(1); + userPermission.setModuleId(1L); + userPermission.setUserId(userId); + userPermission.setUserName("xyz"); + userPermission.setOwner("admin"); + + VXGroupPermission groupPermission = new VXGroupPermission(); + groupPermission.setId(1L); + groupPermission.setIsAllowed(1); + groupPermission.setModuleId(1L); + groupPermission.setGroupId(userId); + groupPermission.setGroupName("xyz"); + groupPermission.setOwner("admin"); + + Mockito.when(stringUtil.validateEmail(Mockito.anyString())).thenReturn(true); + Mockito.when(stringUtil.equals(Mockito.anyString(), Mockito.anyString())).thenReturn(true); + Mockito.when(stringUtil.normalizeEmail(Mockito.anyString())).thenReturn(changeEmail.getEmailAddress()); + Mockito.when(daoManager.getXXPortalUser()).thenReturn(userDao); + Mockito.when(daoManager.getXXPortalUserRole()).thenReturn(roleDao); + Mockito.when(roleDao.findByParentId(Mockito.anyLong())).thenReturn(list); + Mockito.when(daoManager.getXXPortalUser()).thenReturn(userDao); + Mockito.when(userDao.findByLoginId(Mockito.anyString())).thenReturn(userKeyAdmin); + XXPortalUserRoleDao xPortalUserRoleDao = Mockito.mock(XXPortalUserRoleDao.class); + Mockito.when(daoManager.getXXPortalUserRole()).thenReturn(xPortalUserRoleDao); + List xPortalUserRoleList = new ArrayList<>(); + xxPortalUserRole.setId(userId); + xxPortalUserRole.setUserId(userId); + xxPortalUserRole.setUserRole("ROLE_USER"); + xPortalUserRoleList.add(xxPortalUserRole); + Mockito.when(daoManager.getXXPortalUserRole()).thenReturn(roleDao); + Mockito.when(roleDao.findByParentId(Mockito.anyLong())).thenReturn(xPortalUserRoleList); + XXUserPermissionDao xUserPermissionDao = Mockito.mock(XXUserPermissionDao.class); + XXGroupPermissionDao xGroupPermissionDao = Mockito.mock(XXGroupPermissionDao.class); + Mockito.when(daoManager.getXXUserPermission()).thenReturn(xUserPermissionDao); + Mockito.when(xUserPermissionDao.findByUserPermissionIdAndIsAllowed(userProfile.getId())).thenReturn(xUserPermissionsList); + Mockito.when(daoManager.getXXGroupPermission()).thenReturn(xGroupPermissionDao); + Mockito.when(xGroupPermissionDao.findbyVXPortalUserId(userProfile.getId())).thenReturn(xGroupPermissionList); + Mockito.when(xGroupPermissionService.populateViewBean(xGroupPermissionObj)).thenReturn(groupPermission); + Mockito.when(xUserPermissionService.populateViewBean(xUserPermissionObj)).thenReturn(userPermission); + XXModuleDefDao xModuleDefDao = Mockito.mock(XXModuleDefDao.class); + XXModuleDef xModuleDef = new XXModuleDef(); + xModuleDef.setModule("Users/Groups"); + Mockito.when(daoManager.getXXModuleDef()).thenReturn(xModuleDefDao); + Mockito.when(xModuleDefDao.findByModuleId(groupPermission.getModuleId())).thenReturn(xModuleDef); + VXPortalUser dbVXPortalUser = userMgr.changeEmailAddress(userKeyAdmin, changeEmail); + Assert.assertNotNull(dbVXPortalUser); + Assert.assertEquals(userId, dbVXPortalUser.getId()); + Assert.assertEquals(userProfile.getLastName(), dbVXPortalUser.getLastName()); + Assert.assertEquals(changeEmail.getLoginId(), dbVXPortalUser.getLoginId()); + Assert.assertEquals(changeEmail.getEmailAddress(), dbVXPortalUser.getEmailAddress()); + } + + @Test + public void test08ChangeEmailAddressAsUser() { + setupUser(); + XXPortalUserDao userDao = Mockito.mock(XXPortalUserDao.class); + XXPortalUserRoleDao roleDao = Mockito.mock(XXPortalUserRoleDao.class); + XXUserPermissionDao xUserPermissionDao = Mockito.mock(XXUserPermissionDao.class); + XXGroupPermissionDao xGroupPermissionDao = Mockito.mock(XXGroupPermissionDao.class); + XXModuleDefDao xModuleDefDao = Mockito.mock(XXModuleDefDao.class); + XXModuleDef xModuleDef = Mockito.mock(XXModuleDef.class); + VXPortalUser userProfile = userProfile(); + + XXPortalUser user = new XXPortalUser(); + user.setEmailAddress(userProfile.getEmailAddress()); + user.setFirstName(userProfile.getFirstName()); + user.setLastName(userProfile.getLastName()); + user.setLoginId(userProfile.getLoginId()); + String encryptedPwd = userMgr.encrypt(userProfile.getLoginId(), userProfile.getPassword()); + user.setPassword(encryptedPwd); + user.setUserSource(userProfile.getUserSource()); + user.setPublicScreenName(userProfile.getPublicScreenName()); + user.setId(userProfile.getId()); + + VXPasswordChange changeEmail = new VXPasswordChange(); + changeEmail.setEmailAddress("testuser@test.com"); + changeEmail.setId(user.getId()); + changeEmail.setLoginId(user.getLoginId()); + changeEmail.setOldPassword(userProfile.getPassword()); + + XXPortalUserRole xxPortalUserRole = new XXPortalUserRole(); + xxPortalUserRole.setId(userId); + xxPortalUserRole.setUserRole("ROLE_USER"); + List list = new ArrayList<>(); + list.add(xxPortalUserRole); + + List xUserPermissionsList = new ArrayList<>(); + XXUserPermission xUserPermissionObj = new XXUserPermission(); + xUserPermissionObj.setAddedByUserId(userId); + xUserPermissionObj.setCreateTime(new Date()); + xUserPermissionObj.setId(userId); + xUserPermissionObj.setIsAllowed(1); + xUserPermissionObj.setModuleId(1L); + xUserPermissionObj.setUpdatedByUserId(userId); + xUserPermissionObj.setUpdateTime(new Date()); + xUserPermissionObj.setUserId(userId); + xUserPermissionsList.add(xUserPermissionObj); + + List xGroupPermissionList = new ArrayList<>(); + XXGroupPermission xGroupPermissionObj = new XXGroupPermission(); + xGroupPermissionObj.setAddedByUserId(userId); + xGroupPermissionObj.setCreateTime(new Date()); + xGroupPermissionObj.setId(userId); + xGroupPermissionObj.setIsAllowed(1); + xGroupPermissionObj.setModuleId(1L); + xGroupPermissionObj.setUpdatedByUserId(userId); + xGroupPermissionObj.setUpdateTime(new Date()); + xGroupPermissionObj.setGroupId(userId); + xGroupPermissionList.add(xGroupPermissionObj); + + VXUserPermission userPermission = new VXUserPermission(); + userPermission.setId(1L); + userPermission.setIsAllowed(1); + userPermission.setModuleId(1L); + userPermission.setUserId(userId); + userPermission.setUserName("xyz"); + userPermission.setOwner("admin"); + + VXGroupPermission groupPermission = new VXGroupPermission(); + groupPermission.setId(1L); + groupPermission.setIsAllowed(1); + groupPermission.setModuleId(1L); + groupPermission.setGroupId(userId); + groupPermission.setGroupName("xyz"); + groupPermission.setOwner("admin"); + + Mockito.when(stringUtil.validateEmail(Mockito.anyString())).thenReturn(true); + Mockito.when(stringUtil.equals(Mockito.anyString(), Mockito.anyString())).thenReturn(true); + Mockito.when(stringUtil.normalizeEmail(Mockito.anyString())).thenReturn(changeEmail.getEmailAddress()); + Mockito.when(daoManager.getXXPortalUser()).thenReturn(userDao); + Mockito.when(daoManager.getXXPortalUserRole()).thenReturn(roleDao); + Mockito.when(roleDao.findByParentId(Mockito.anyLong())).thenReturn(list); + Mockito.when(daoManager.getXXUserPermission()).thenReturn(xUserPermissionDao); + Mockito.when(daoManager.getXXGroupPermission()).thenReturn(xGroupPermissionDao); + Mockito.when(xUserPermissionDao.findByUserPermissionIdAndIsAllowed(userProfile.getId())).thenReturn(xUserPermissionsList); + Mockito.when(xGroupPermissionDao.findbyVXPortalUserId(userProfile.getId())).thenReturn(xGroupPermissionList); + Mockito.when(xGroupPermissionService.populateViewBean(xGroupPermissionObj)).thenReturn(groupPermission); + Mockito.when(xUserPermissionService.populateViewBean(xUserPermissionObj)).thenReturn(userPermission); + Mockito.when(daoManager.getXXModuleDef()).thenReturn(xModuleDefDao); + Mockito.when(xModuleDefDao.findByModuleId(Mockito.anyLong())).thenReturn(xModuleDef); + Mockito.when(daoManager.getXXPortalUser()).thenReturn(userDao); + Mockito.when(userDao.findByLoginId(Mockito.anyString())).thenReturn(user); + XXPortalUserRoleDao xPortalUserRoleDao = Mockito.mock(XXPortalUserRoleDao.class); + Mockito.when(daoManager.getXXPortalUserRole()).thenReturn(xPortalUserRoleDao); + List xPortalUserRoleList = new ArrayList<>(); + xxPortalUserRole.setId(userId); + xxPortalUserRole.setUserId(userId); + xxPortalUserRole.setUserRole("ROLE_USER"); + xPortalUserRoleList.add(xxPortalUserRole); + Mockito.when(daoManager.getXXUserPermission()).thenReturn(xUserPermissionDao); + Mockito.when(xUserPermissionDao.findByUserPermissionIdAndIsAllowed(userProfile.getId())).thenReturn(xUserPermissionsList); + Mockito.when(daoManager.getXXGroupPermission()).thenReturn(xGroupPermissionDao); + Mockito.when(xGroupPermissionDao.findbyVXPortalUserId(userProfile.getId())).thenReturn(xGroupPermissionList); + Mockito.when(daoManager.getXXPortalUserRole()).thenReturn(roleDao); + Mockito.when(roleDao.findByParentId(Mockito.anyLong())).thenReturn(xPortalUserRoleList); + Mockito.when(daoManager.getXXModuleDef()).thenReturn(xModuleDefDao); + Mockito.when(xModuleDefDao.findByModuleId(Mockito.anyLong())).thenReturn(xModuleDef); + VXPortalUser dbVXPortalUser = userMgr.changeEmailAddress(user, changeEmail); + Assert.assertNotNull(dbVXPortalUser); + Assert.assertEquals(userId, dbVXPortalUser.getId()); + Assert.assertEquals(userProfile.getLastName(), dbVXPortalUser.getLastName()); + Assert.assertEquals(changeEmail.getLoginId(), dbVXPortalUser.getLoginId()); + Assert.assertEquals(changeEmail.getEmailAddress(), dbVXPortalUser.getEmailAddress()); + + user.setId(userProfile.getId()); + user.setLoginId("usertest123"); + String encryptCred = userMgr.encrypt(user.getLoginId(), userProfile.getPassword()); + user.setPassword(encryptCred); + Mockito.when(stringUtil.equals(Mockito.anyString(), Mockito.nullable(String.class))).thenReturn(true); + Mockito.when(stringUtil.equals(Mockito.anyString(), Mockito.anyString())).thenReturn(false); + Mockito.when(restErrorUtil.createRESTException("serverMsg.userMgrWrongPassword", MessageEnums.OPER_NO_PERMISSION, null, null, changeEmail.toString())).thenThrow(new WebApplicationException()); + thrown.expect(WebApplicationException.class); + userMgr.changeEmailAddress(user, changeEmail); + } + + @Test + public void test09CreateUser() { + setup(); + XXPortalUserDao userDao = Mockito.mock(XXPortalUserDao.class); + XXPortalUserRoleDao roleDao = Mockito.mock(XXPortalUserRoleDao.class); + XXUserPermissionDao xUserPermissionDao = Mockito.mock(XXUserPermissionDao.class); + XXGroupPermissionDao xGroupPermissionDao = Mockito.mock(XXGroupPermissionDao.class); + + XXPortalUser user = new XXPortalUser(); + VXPortalUser userProfile = userProfile(); + + XXPortalUserRole xxPortalUserRole = new XXPortalUserRole(); + xxPortalUserRole.setId(userId); + xxPortalUserRole.setUserRole("ROLE_USER"); + List list = new ArrayList<>(); + list.add(xxPortalUserRole); + + List xUserPermissionsList = new ArrayList<>(); + XXUserPermission xUserPermissionObj = new XXUserPermission(); + xUserPermissionObj.setAddedByUserId(userId); + xUserPermissionObj.setCreateTime(new Date()); + xUserPermissionObj.setId(userId); + xUserPermissionObj.setIsAllowed(1); + xUserPermissionObj.setModuleId(1L); + xUserPermissionObj.setUpdatedByUserId(userId); + xUserPermissionObj.setUpdateTime(new Date()); + xUserPermissionObj.setUserId(userId); + xUserPermissionsList.add(xUserPermissionObj); + + List xGroupPermissionList = new ArrayList<>(); + XXGroupPermission xGroupPermissionObj = new XXGroupPermission(); + xGroupPermissionObj.setAddedByUserId(userId); + xGroupPermissionObj.setCreateTime(new Date()); + xGroupPermissionObj.setId(userId); + xGroupPermissionObj.setIsAllowed(1); + xGroupPermissionObj.setModuleId(1L); + xGroupPermissionObj.setUpdatedByUserId(userId); + xGroupPermissionObj.setUpdateTime(new Date()); + xGroupPermissionObj.setGroupId(userId); + xGroupPermissionList.add(xGroupPermissionObj); + + Mockito.when(daoManager.getXXPortalUser()).thenReturn(userDao); + Mockito.when(userDao.create(Mockito.any())).thenReturn(user); + Mockito.when(daoManager.getXXPortalUserRole()).thenReturn(roleDao); + + Mockito.when(daoManager.getXXUserPermission()).thenReturn(xUserPermissionDao); + + Mockito.when(daoManager.getXXGroupPermission()).thenReturn(xGroupPermissionDao); + Mockito.doNothing().when(rangerBizUtil).blockAuditorRoleUser(); + Mockito.when(userDao.findByLoginId(Mockito.anyString())).thenReturn(user); + VXPortalUser dbVXPortalUser = userMgr.createUser(userProfile); + Assert.assertNotNull(dbVXPortalUser); + Assert.assertEquals(user.getId(), dbVXPortalUser.getId()); + Assert.assertEquals(user.getFirstName(), dbVXPortalUser.getFirstName()); + Assert.assertEquals(user.getLastName(), dbVXPortalUser.getLastName()); + Assert.assertEquals(user.getLoginId(), dbVXPortalUser.getLoginId()); + Assert.assertEquals(user.getEmailAddress(), dbVXPortalUser.getEmailAddress()); + Assert.assertEquals(user.getPassword(), dbVXPortalUser.getPassword()); + + Mockito.verify(daoManager, Mockito.atLeast(1)).getXXPortalUser(); + Mockito.verify(daoManager).getXXUserPermission(); + Mockito.verify(daoManager).getXXGroupPermission(); + + Collection reqRoleList = new ArrayList<>(); + reqRoleList.add(null); + userProfile.setUserRoleList(reqRoleList); + dbVXPortalUser = userMgr.createUser(userProfile); + } + + @Test + public void test10CreateDefaultAccountUser() { + setup(); + XXPortalUserDao userDao = Mockito.mock(XXPortalUserDao.class); + XXPortalUserRoleDao roleDao = Mockito.mock(XXPortalUserRoleDao.class); + VXPortalUser userProfile = userProfile(); + Collection userRoleList = new ArrayList<>(); + userRoleList.add("ROLE_USER"); + userProfile.setUserRoleList(userRoleList); + XXPortalUser user = new XXPortalUser(); + user.setEmailAddress(userProfile.getEmailAddress()); + XXPortalUserRole xxPortalUserRole = new XXPortalUserRole(); + xxPortalUserRole.setId(userId); + xxPortalUserRole.setUserRole("ROLE_USER"); + + List list = new ArrayList<>(); + list.add(xxPortalUserRole); + + Mockito.when(daoManager.getXXPortalUser()).thenReturn(userDao); + Mockito.when(userDao.findByLoginId(Mockito.anyString())).thenReturn(user); + Mockito.when(daoManager.getXXPortalUserRole()).thenReturn(roleDao); + Mockito.doNothing().when(rangerBizUtil).blockAuditorRoleUser(); + userProfile.setOtherAttributes("other1"); + VXPortalUser dbVXPortalUser = userMgr.createDefaultAccountUser(userProfile); + Assert.assertNotNull(dbVXPortalUser); + Assert.assertEquals(user.getId(), dbVXPortalUser.getId()); + Assert.assertEquals(user.getFirstName(), dbVXPortalUser.getFirstName()); + Assert.assertEquals(user.getLastName(), dbVXPortalUser.getLastName()); + Assert.assertEquals(user.getLoginId(), dbVXPortalUser.getLoginId()); + Assert.assertEquals(user.getEmailAddress(), dbVXPortalUser.getEmailAddress()); + Assert.assertEquals(user.getPassword(), dbVXPortalUser.getPassword()); + Mockito.verify(daoManager, Mockito.atLeast(1)).getXXPortalUser(); + Mockito.verify(daoManager, Mockito.atLeast(1)).getXXPortalUserRole(); + } + + @Test + public void test11CreateDefaultAccountUser() { + destroySession(); + setup(); + XXPortalUserDao userDao = Mockito.mock(XXPortalUserDao.class); + XXPortalUserRoleDao roleDao = Mockito.mock(XXPortalUserRoleDao.class); + VXPortalUser userProfile = userProfile(); + userProfile.setStatus(RangerCommonEnums.USER_EXTERNAL); + Collection userRoleList = new ArrayList<>(); + userRoleList.add("ROLE_USER"); + userProfile.setUserRoleList(userRoleList); + XXPortalUser user = new XXPortalUser(); + user.setEmailAddress(userProfile.getEmailAddress()); + user.setUserSource(RangerCommonEnums.USER_EXTERNAL); + XXPortalUserRole xxPortalUserRole = new XXPortalUserRole(); + xxPortalUserRole.setId(userId); + xxPortalUserRole.setUserRole("ROLE_USER"); + + List list = new ArrayList<>(); + list.add(xxPortalUserRole); + + Mockito.when(daoManager.getXXPortalUser()).thenReturn(userDao); + Mockito.when(userDao.findByLoginId(Mockito.anyString())).thenReturn(null, user); + Mockito.when(userDao.findByEmailAddress(Mockito.anyString())).thenReturn(null); + Mockito.when(daoManager.getXXPortalUserRole()).thenReturn(roleDao); + Mockito.when(userDao.create(Mockito.any())).thenReturn(user); + Mockito.doNothing().when(rangerBizUtil).blockAuditorRoleUser(); + VXPortalUser dbVXPortalUser = userMgr.createDefaultAccountUser(userProfile); + Assert.assertNotNull(dbVXPortalUser); + Assert.assertEquals(user.getId(), dbVXPortalUser.getId()); + Assert.assertEquals(user.getFirstName(), dbVXPortalUser.getFirstName()); + Assert.assertEquals(user.getLastName(), dbVXPortalUser.getLastName()); + Assert.assertEquals(user.getLoginId(), dbVXPortalUser.getLoginId()); + Assert.assertEquals(user.getEmailAddress(), dbVXPortalUser.getEmailAddress()); + Assert.assertEquals(user.getPassword(), dbVXPortalUser.getPassword()); + Mockito.verify(daoManager, Mockito.atLeast(1)).getXXPortalUser(); + Mockito.verify(daoManager, Mockito.atLeast(1)).getXXPortalUserRole(); + } + + @Test + public void test12CreateDefaultAccountUser() { + setup(); + XXPortalUserDao userDao = Mockito.mock(XXPortalUserDao.class); + XXPortalUserRoleDao roleDao = Mockito.mock(XXPortalUserRoleDao.class); + VXPortalUser userProfile = userProfile(); + userProfile.setStatus(RangerCommonEnums.USER_EXTERNAL); + Collection userRoleList = new ArrayList<>(); + userRoleList.add("ROLE_USER"); + userProfile.setUserRoleList(userRoleList); + XXPortalUser xxPortalUser = new XXPortalUser(); + xxPortalUser.setEmailAddress(userProfile.getEmailAddress()); + xxPortalUser.setUserSource(RangerCommonEnums.USER_EXTERNAL); + XXPortalUserRole xxPortalUserRole = new XXPortalUserRole(); + xxPortalUserRole.setId(userId); + xxPortalUserRole.setUserRole("ROLE_USER"); + + List list = new ArrayList<>(); + list.add(xxPortalUserRole); + + Mockito.when(daoManager.getXXPortalUser()).thenReturn(userDao); + Mockito.when(userDao.findByLoginId(Mockito.anyString())).thenReturn(xxPortalUser); + Mockito.when(daoManager.getXXPortalUserRole()).thenReturn(roleDao); + Mockito.doNothing().when(rangerBizUtil).blockAuditorRoleUser(); + userProfile.setPassword(""); + userProfile.setEmailAddress(null); + VXPortalUser dbVXPortalUser = userMgr.createDefaultAccountUser(userProfile); + Assert.assertNotNull(dbVXPortalUser); + Assert.assertEquals(xxPortalUser.getId(), dbVXPortalUser.getId()); + Assert.assertEquals(xxPortalUser.getFirstName(), dbVXPortalUser.getFirstName()); + Assert.assertEquals(xxPortalUser.getLastName(), dbVXPortalUser.getLastName()); + Assert.assertEquals(xxPortalUser.getLoginId(), dbVXPortalUser.getLoginId()); + Assert.assertEquals(xxPortalUser.getEmailAddress(), dbVXPortalUser.getEmailAddress()); + Assert.assertEquals(xxPortalUser.getPassword(), dbVXPortalUser.getPassword()); + Mockito.verify(daoManager, Mockito.atLeast(1)).getXXPortalUser(); + Mockito.verify(daoManager, Mockito.atLeast(1)).getXXPortalUserRole(); + } + + @Test + public void test13IsUserInRole() { + XXPortalUserRoleDao roleDao = Mockito.mock(XXPortalUserRoleDao.class); + XXPortalUserRole xxPortalUserRole = new XXPortalUserRole(); + xxPortalUserRole.setId(userId); + xxPortalUserRole.setUserRole("ROLE_USER"); + List list = new ArrayList<>(); + list.add(xxPortalUserRole); + Mockito.when(daoManager.getXXPortalUserRole()).thenReturn(roleDao); + Mockito.when(roleDao.findByRoleUserId(userId, "ROLE_USER")).thenReturn(xxPortalUserRole); + boolean isValue = userMgr.isUserInRole(userId, "ROLE_USER"); + Assert.assertTrue(isValue); + Mockito.when(roleDao.findByRoleUserId(userId, "ROLE_USER")).thenReturn(null); + isValue = userMgr.isUserInRole(userId, "ROLE_USER"); + Assert.assertFalse(isValue); + } + + @Test + public void test14UpdateUserWithPass() { + setup(); + XXPortalUserDao userDao = Mockito.mock(XXPortalUserDao.class); + VXPortalUser userProfile = userProfile(); + userProfile.setPassword("password1234"); + XXPortalUser user = new XXPortalUser(); + user.setId(userProfile.getId()); + user.setLoginId(userProfile.getLoginId()); + user.setEmailAddress(userProfile.getEmailAddress()); + user.setLoginId(userProfile.getLoginId()); + String encryptedPwd = userMgr.encrypt(userProfile.getLoginId(), userProfile.getPassword()); + user.setPassword(encryptedPwd); + Mockito.when(daoManager.getXXPortalUser()).thenReturn(userDao); + Mockito.when(userDao.getById(userProfile.getId())).thenReturn(user); + Mockito.when(restErrorUtil.createRESTException(HttpServletResponse.SC_FORBIDDEN, "Logged-In user is not allowed to access requested user data", true)).thenThrow(new WebApplicationException()); + thrown.expect(WebApplicationException.class); + XXPortalUser dbXXPortalUser = userMgr.updateUserWithPass(userProfile); + Assert.assertNotNull(dbXXPortalUser); + Assert.assertEquals(userId, dbXXPortalUser.getId()); + Assert.assertEquals(userProfile.getFirstName(), dbXXPortalUser.getFirstName()); + Assert.assertEquals(userProfile.getFirstName(), dbXXPortalUser.getFirstName()); + Assert.assertEquals(userProfile.getLastName(), dbXXPortalUser.getLastName()); + Assert.assertEquals(userProfile.getLoginId(), dbXXPortalUser.getLoginId()); + Assert.assertEquals(userProfile.getEmailAddress(), dbXXPortalUser.getEmailAddress()); + Assert.assertEquals(encryptedPwd, dbXXPortalUser.getPassword()); + Mockito.when(userDao.getById(userProfile.getId())).thenReturn(null); + dbXXPortalUser = userMgr.updateUserWithPass(userProfile); + Assert.assertNull(dbXXPortalUser); + } + + @Test + public void test15searchUsers() { + Query query = Mockito.mock(Query.class); + EntityManager entityManager = Mockito.mock(EntityManager.class); + SearchCriteria searchCriteria = new SearchCriteria(); + searchCriteria.setDistinct(true); + searchCriteria.setGetChildren(true); + searchCriteria.setGetCount(true); + searchCriteria.setMaxRows(12); + searchCriteria.setOwnerId(userId); + searchCriteria.setStartIndex(1); + searchCriteria.setSortBy("userId"); + searchCriteria.setSortType("asc"); + Long count = 1L; + Mockito.when(daoManager.getEntityManager()).thenReturn(entityManager); + Mockito.when(entityManager.createQuery(Mockito.anyString())).thenReturn(query); + Mockito.when(query.getSingleResult()).thenReturn(count); + + VXPortalUserList dbVXPortalUserList = userMgr.searchUsers(searchCriteria); + Assert.assertNotNull(dbVXPortalUserList); + searchCriteria.setSortBy("loginId"); + dbVXPortalUserList = userMgr.searchUsers(searchCriteria); + Assert.assertNotNull(dbVXPortalUserList); + searchCriteria.setSortBy("emailAddress"); + dbVXPortalUserList = userMgr.searchUsers(searchCriteria); + Assert.assertNotNull(dbVXPortalUserList); + searchCriteria.setSortBy("firstName"); + dbVXPortalUserList = userMgr.searchUsers(searchCriteria); + Assert.assertNotNull(dbVXPortalUserList); + searchCriteria.setSortBy("lastName"); + dbVXPortalUserList = userMgr.searchUsers(searchCriteria); + Assert.assertNotNull(dbVXPortalUserList); + searchCriteria.setSortBy("source"); + searchCriteria.setSortType(""); + dbVXPortalUserList = userMgr.searchUsers(searchCriteria); + Assert.assertNotNull(dbVXPortalUserList); + searchCriteria.setSortBy(""); + searchCriteria.setSortType("desc"); + dbVXPortalUserList = userMgr.searchUsers(searchCriteria); + Assert.assertNotNull(dbVXPortalUserList); + + VXPortalUser userProfile = userProfile(); + XXPortalUser user = new XXPortalUser(); + user.setId(userProfile.getId()); + user.setLoginId(userProfile.getLoginId()); + user.setEmailAddress(userProfile.getEmailAddress()); + user.setLoginId(userProfile.getLoginId()); + List resultList = new ArrayList<>(); + resultList.add(user); + Mockito.when(query.getResultList()).thenReturn(resultList); + dbVXPortalUserList = userMgr.searchUsers(searchCriteria); + Assert.assertNotNull(dbVXPortalUserList); + + count = 0L; + Mockito.when(query.getSingleResult()).thenReturn(count); + dbVXPortalUserList = userMgr.searchUsers(searchCriteria); + Assert.assertNotNull(dbVXPortalUserList); + } + + @Test + public void test16FindByEmailAddress() { + XXPortalUserDao userDao = Mockito.mock(XXPortalUserDao.class); + + XXPortalUser user = new XXPortalUser(); + + String emailId = "test001user@apache.org"; + Mockito.when(daoManager.getXXPortalUser()).thenReturn(userDao); + Mockito.when(userDao.findByEmailAddress(emailId)).thenReturn(user); + + XXPortalUser dbXXPortalUser = userMgr.findByEmailAddress(emailId); + Assert.assertNotNull(dbXXPortalUser); + Assert.assertNotEquals(emailId, dbXXPortalUser.getEmailAddress()); + + Mockito.verify(daoManager).getXXPortalUser(); + } + + @Test + public void test17GetRolesForUser() { + XXPortalUserRoleDao roleDao = Mockito.mock(XXPortalUserRoleDao.class); + VXPortalUser userProfile = userProfile(); + + XXPortalUser user = new XXPortalUser(); + user.setEmailAddress(userProfile.getEmailAddress()); + user.setFirstName(userProfile.getFirstName()); + user.setLastName(userProfile.getLastName()); + user.setLoginId(userProfile.getLoginId()); + user.setPassword(userProfile.getPassword()); + user.setUserSource(userProfile.getUserSource()); + user.setPublicScreenName(userProfile.getPublicScreenName()); + user.setId(userProfile.getId()); + + XXPortalUserRole xxPortalUserRole = new XXPortalUserRole(); + xxPortalUserRole.setId(user.getId()); + xxPortalUserRole.setUserRole("ROLE_USER"); + List list = new ArrayList<>(); + list.add(xxPortalUserRole); + + Mockito.when(daoManager.getXXPortalUserRole()).thenReturn(roleDao); + Mockito.when(roleDao.findByUserId(userId)).thenReturn(list); + + Collection stringReturn = userMgr.getRolesForUser(user); + Assert.assertNotNull(stringReturn); + + Mockito.verify(daoManager).getXXPortalUserRole(); + } + + @Test + public void test18DeleteUserRole() { + setup(); + XXPortalUserRoleDao roleDao = Mockito.mock(XXPortalUserRoleDao.class); + + XXPortalUserRole xxPortalUserRole = new XXPortalUserRole(); + String userRole = "ROLE_USER"; + XXPortalUser user = new XXPortalUser(); + xxPortalUserRole.setId(user.getId()); + xxPortalUserRole.setUserRole("ROLE_USER"); + List list = new ArrayList<>(); + list.add(xxPortalUserRole); + + Mockito.when(daoManager.getXXPortalUserRole()).thenReturn(roleDao); + Mockito.when(roleDao.findByUserId(userId)).thenReturn(list); + + boolean deleteValue = userMgr.deleteUserRole(userId, userRole); + Assert.assertTrue(deleteValue); + } + + @Test + public void test19DeactivateUser() { + setup(); + XXPortalUserDao userDao = Mockito.mock(XXPortalUserDao.class); + XXPortalUserRoleDao roleDao = Mockito.mock(XXPortalUserRoleDao.class); + XXUserPermissionDao xUserPermissionDao = Mockito.mock(XXUserPermissionDao.class); + XXGroupPermissionDao xGroupPermissionDao = Mockito.mock(XXGroupPermissionDao.class); + VXGroupPermission vXGroupPermission = Mockito.mock(VXGroupPermission.class); + XXModuleDefDao xModuleDefDao = Mockito.mock(XXModuleDefDao.class); + XXModuleDef xModuleDef = Mockito.mock(XXModuleDef.class); + VXUserPermission vXUserPermission = Mockito.mock(VXUserPermission.class); + + VXPortalUser userProfile = userProfile(); + + XXPortalUser user = new XXPortalUser(); + user.setEmailAddress(userProfile.getEmailAddress()); + user.setFirstName(userProfile.getFirstName()); + user.setLastName(userProfile.getLastName()); + user.setLoginId(userProfile.getLoginId()); + user.setPassword(userProfile.getPassword()); + user.setUserSource(userProfile.getUserSource()); + user.setPublicScreenName(userProfile.getPublicScreenName()); + user.setId(userProfile.getId()); + + List xUserPermissionsList = new ArrayList<>(); + XXUserPermission xUserPermissionObj = new XXUserPermission(); + xUserPermissionObj.setAddedByUserId(userId); + xUserPermissionObj.setCreateTime(new Date()); + xUserPermissionObj.setId(userId); + xUserPermissionObj.setIsAllowed(1); + xUserPermissionObj.setModuleId(1L); + xUserPermissionObj.setUpdatedByUserId(userId); + xUserPermissionObj.setUpdateTime(new Date()); + xUserPermissionObj.setUserId(userId); + xUserPermissionsList.add(xUserPermissionObj); + + List xGroupPermissionList = new ArrayList<>(); + XXGroupPermission xGroupPermissionObj = new XXGroupPermission(); + xGroupPermissionObj.setAddedByUserId(userId); + xGroupPermissionObj.setCreateTime(new Date()); + xGroupPermissionObj.setId(userId); + xGroupPermissionObj.setIsAllowed(1); + xGroupPermissionObj.setModuleId(1L); + xGroupPermissionObj.setUpdatedByUserId(userId); + xGroupPermissionObj.setUpdateTime(new Date()); + xGroupPermissionObj.setGroupId(userId); + xGroupPermissionList.add(xGroupPermissionObj); + + XXPortalUserRole xxPortalUserRole = new XXPortalUserRole(); + xxPortalUserRole.setId(userId); + xxPortalUserRole.setUserRole("ROLE_USER"); + + List list = new ArrayList<>(); + list.add(xxPortalUserRole); + Mockito.when(daoManager.getXXPortalUser()).thenReturn(userDao); + Mockito.when(userDao.update(user)).thenReturn(user); + + Mockito.when(daoManager.getXXPortalUserRole()).thenReturn(roleDao); + Mockito.when(roleDao.findByParentId(Mockito.anyLong())).thenReturn(list); + + Mockito.when(daoManager.getXXUserPermission()).thenReturn(xUserPermissionDao); + Mockito.when(xUserPermissionDao.findByUserPermissionIdAndIsAllowed(userProfile.getId())).thenReturn(xUserPermissionsList); + + Mockito.when(daoManager.getXXGroupPermission()).thenReturn(xGroupPermissionDao); + Mockito.when(xGroupPermissionDao.findbyVXPortalUserId(userProfile.getId())).thenReturn(xGroupPermissionList); + + Mockito.when(xGroupPermissionService.populateViewBean(xGroupPermissionObj)).thenReturn(vXGroupPermission); + + Mockito.when(daoManager.getXXModuleDef()).thenReturn(xModuleDefDao); + Mockito.when(xModuleDefDao.findByModuleId(Mockito.anyLong())).thenReturn(xModuleDef); + + Mockito.when(xUserPermissionService.populateViewBean(xUserPermissionObj)).thenReturn(vXUserPermission); + Mockito.doNothing().when(rangerBizUtil).blockAuditorRoleUser(); + VXPortalUser dbVXPortalUser = userMgr.deactivateUser(null); + Assert.assertNull(dbVXPortalUser); + dbVXPortalUser = userMgr.deactivateUser(user); + Assert.assertNotNull(dbVXPortalUser); + Assert.assertEquals(user.getId(), dbVXPortalUser.getId()); + Assert.assertEquals(user.getFirstName(), dbVXPortalUser.getFirstName()); + Assert.assertEquals(user.getLastName(), dbVXPortalUser.getLastName()); + Assert.assertEquals(user.getLoginId(), dbVXPortalUser.getLoginId()); + + Mockito.verify(daoManager).getXXPortalUser(); + Mockito.verify(daoManager).getXXUserPermission(); + Mockito.verify(daoManager).getXXGroupPermission(); + Mockito.verify(xUserPermissionService).populateViewBean(xUserPermissionObj); + Mockito.verify(xGroupPermissionService).populateViewBean(xGroupPermissionObj); + } + + @Test + public void test20checkAccess() { + setup(); + XXPortalUserDao xPortalUserDao = Mockito.mock(XXPortalUserDao.class); + XXPortalUser xPortalUser = Mockito.mock(XXPortalUser.class); + Mockito.when(daoManager.getXXPortalUser()).thenReturn(xPortalUserDao); + Mockito.when(xPortalUserDao.getById(userId)).thenReturn(xPortalUser); + Mockito.when(restErrorUtil.createRESTException(HttpServletResponse.SC_FORBIDDEN, "Logged-In user is not allowed to access requested user data", true)).thenThrow(new WebApplicationException()); + thrown.expect(WebApplicationException.class); + userMgr.checkAccess(userId); + + Mockito.when(xPortalUserDao.getById(userId)).thenReturn(null); + Mockito.when(restErrorUtil.create403RESTException("serverMsg.userMgrWrongUser: " + userId)).thenThrow(new WebApplicationException()); + thrown.expect(WebApplicationException.class); + userMgr.checkAccess(userId); + } + + @Test + public void test21getUserProfile() { + setup(); + XXPortalUserDao xPortalUserDao = Mockito.mock(XXPortalUserDao.class); + XXPortalUser xPortalUser = Mockito.mock(XXPortalUser.class); + + List xPortalUserRoleList = new ArrayList<>(); + XXPortalUserRole xxPortalUserRole = new XXPortalUserRole(); + xxPortalUserRole.setId(userId); + xxPortalUserRole.setUserRole("ROLE_USER"); + xPortalUserRoleList.add(xxPortalUserRole); + + List xUserPermissionsList = new ArrayList<>(); + XXUserPermission xUserPermissionObj = new XXUserPermission(); + xUserPermissionObj.setAddedByUserId(userId); + xUserPermissionObj.setCreateTime(new Date()); + xUserPermissionObj.setId(userId); + xUserPermissionObj.setIsAllowed(1); + xUserPermissionObj.setModuleId(1L); + xUserPermissionObj.setUpdatedByUserId(userId); + xUserPermissionObj.setUpdateTime(new Date()); + xUserPermissionObj.setUserId(userId); + xUserPermissionsList.add(xUserPermissionObj); + + List xGroupPermissionList = new ArrayList<>(); + XXGroupPermission xGroupPermissionObj = new XXGroupPermission(); + xGroupPermissionObj.setAddedByUserId(userId); + xGroupPermissionObj.setCreateTime(new Date()); + xGroupPermissionObj.setId(userId); + xGroupPermissionObj.setIsAllowed(1); + xGroupPermissionObj.setModuleId(1L); + xGroupPermissionObj.setUpdatedByUserId(userId); + xGroupPermissionObj.setUpdateTime(new Date()); + xGroupPermissionObj.setGroupId(userId); + xGroupPermissionList.add(xGroupPermissionObj); + + Mockito.when(daoManager.getXXPortalUser()).thenReturn(xPortalUserDao); + Mockito.when(xPortalUserDao.getById(userId)).thenReturn(null); + Mockito.when(restErrorUtil.createRESTException(HttpServletResponse.SC_FORBIDDEN, "Logged-In user is not allowed to access requested user data", true)).thenThrow(new WebApplicationException()); + thrown.expect(WebApplicationException.class); + userMgr.getUserProfile(userId); + VXPortalUser dbVXPortalUser; + Mockito.when(xPortalUserDao.getById(userId)).thenReturn(xPortalUser); + dbVXPortalUser = userMgr.getUserProfile(userId); + Assert.assertNotNull(dbVXPortalUser); + } + + @Test + public void test22getUserProfileByLoginId() { + setup(); + XXPortalUserDao xPortalUserDao = Mockito.mock(XXPortalUserDao.class); + Mockito.when(daoManager.getXXPortalUser()).thenReturn(xPortalUserDao); + VXPortalUser userProfile = userProfile(); + XXPortalUser user = new XXPortalUser(); + user.setEmailAddress(userProfile.getEmailAddress()); + user.setFirstName(userProfile.getFirstName()); + user.setLastName(userProfile.getLastName()); + user.setLoginId(userProfile.getLoginId()); + user.setPassword(userProfile.getPassword()); + user.setUserSource(userProfile.getUserSource()); + user.setPublicScreenName(userProfile.getPublicScreenName()); + user.setId(userProfile.getId()); + userMgr.getUserProfileByLoginId(); + VXPortalUser dbVXPortalUser; + Mockito.when(xPortalUserDao.findByLoginId(Mockito.anyString())).thenReturn(user); + XXPortalUserRoleDao xPortalUserRoleDao = Mockito.mock(XXPortalUserRoleDao.class); + Mockito.when(daoManager.getXXPortalUserRole()).thenReturn(xPortalUserRoleDao); + List xPortalUserRoleList = new ArrayList<>(); + XXPortalUserRole xxPortalUserRole = new XXPortalUserRole(); + xxPortalUserRole.setId(userId); + xxPortalUserRole.setUserId(userId); + xxPortalUserRole.setUserRole("ROLE_USER"); + xPortalUserRoleList.add(xxPortalUserRole); + Mockito.when(xPortalUserRoleDao.findByParentId(Mockito.anyLong())).thenReturn(xPortalUserRoleList); + XXUserPermissionDao xUserPermissionDao = Mockito.mock(XXUserPermissionDao.class); + XXGroupPermissionDao xGroupPermissionDao = Mockito.mock(XXGroupPermissionDao.class); + Mockito.when(daoManager.getXXUserPermission()).thenReturn(xUserPermissionDao); + List xUserPermissionsList = new ArrayList<>(); + List xGroupPermissionList = new ArrayList<>(); + Mockito.when(xUserPermissionDao.findByUserPermissionIdAndIsAllowed(userProfile.getId())).thenReturn(xUserPermissionsList); + Mockito.when(daoManager.getXXGroupPermission()).thenReturn(xGroupPermissionDao); + Mockito.when(xGroupPermissionDao.findbyVXPortalUserId(userProfile.getId())).thenReturn(xGroupPermissionList); + dbVXPortalUser = userMgr.getUserProfileByLoginId(user.getLoginId()); + Assert.assertNotNull(dbVXPortalUser); + } + + @Test + public void test23setUserRoles() { + setup(); + XXPortalUserDao userDao = Mockito.mock(XXPortalUserDao.class); + VXPortalUser userProfile = userProfile(); + XXPortalUser user = new XXPortalUser(); + user.setEmailAddress(userProfile.getEmailAddress()); + user.setFirstName(userProfile.getFirstName()); + user.setLastName(userProfile.getLastName()); + user.setLoginId(userProfile.getLoginId()); + user.setPassword(userProfile.getPassword()); + user.setUserSource(userProfile.getUserSource()); + user.setPublicScreenName(userProfile.getPublicScreenName()); + user.setId(userProfile.getId()); + + List vStringRolesList = new ArrayList<>(); + VXString vXStringObj = new VXString(); + vXStringObj.setValue("ROLE_USER"); + vStringRolesList.add(vXStringObj); + + List xPortalUserRoleList = new ArrayList<>(); + XXPortalUserRole xxPortalUserRole = new XXPortalUserRole(); + xxPortalUserRole.setId(userId); + xxPortalUserRole.setUserId(userId); + xxPortalUserRole.setUserRole("ROLE_USER"); + xPortalUserRoleList.add(xxPortalUserRole); + + List xUserPermissionsList = new ArrayList<>(); + XXUserPermission xUserPermissionObj = new XXUserPermission(); + xUserPermissionObj.setAddedByUserId(userId); + xUserPermissionObj.setCreateTime(new Date()); + xUserPermissionObj.setId(userId); + xUserPermissionObj.setIsAllowed(1); + xUserPermissionObj.setModuleId(1L); + xUserPermissionObj.setUpdatedByUserId(userId); + xUserPermissionObj.setUpdateTime(new Date()); + xUserPermissionObj.setUserId(userId); + xUserPermissionsList.add(xUserPermissionObj); + + List xGroupPermissionList = new ArrayList<>(); + XXGroupPermission xGroupPermissionObj = new XXGroupPermission(); + xGroupPermissionObj.setAddedByUserId(userId); + xGroupPermissionObj.setCreateTime(new Date()); + xGroupPermissionObj.setId(userId); + xGroupPermissionObj.setIsAllowed(1); + xGroupPermissionObj.setModuleId(1L); + xGroupPermissionObj.setUpdatedByUserId(userId); + xGroupPermissionObj.setUpdateTime(new Date()); + xGroupPermissionObj.setGroupId(userId); + xGroupPermissionList.add(xGroupPermissionObj); + + List groupPermList = new ArrayList<>(); + VXGroupPermission groupPermission = new VXGroupPermission(); + groupPermission.setId(1L); + groupPermission.setIsAllowed(1); + groupPermission.setModuleId(1L); + groupPermission.setGroupId(userId); + groupPermission.setGroupName("xyz"); + groupPermission.setOwner("admin"); + groupPermList.add(groupPermission); + + XXModuleDef xModuleDef = new XXModuleDef(); + xModuleDef.setUpdatedByUserId(userId); + xModuleDef.setAddedByUserId(userId); + xModuleDef.setCreateTime(new Date()); + xModuleDef.setId(userId); + xModuleDef.setModule("Policy manager"); + xModuleDef.setUpdateTime(new Date()); + xModuleDef.setUrl("/policy manager"); + + VXUserPermission userPermission = new VXUserPermission(); + userPermission.setId(1L); + userPermission.setIsAllowed(1); + userPermission.setModuleId(1L); + userPermission.setUserId(userId); + userPermission.setUserName("xyz"); + userPermission.setOwner("admin"); + Mockito.when(daoManager.getXXPortalUser()).thenReturn(userDao); + Mockito.when(userDao.getById(userId)).thenReturn(user); + Mockito.when(restErrorUtil.createRESTException(HttpServletResponse.SC_FORBIDDEN, "Logged-In user is not allowed to access requested user data", true)).thenThrow(new WebApplicationException()); + thrown.expect(WebApplicationException.class); + userMgr.checkAccess(userId); + userMgr.setUserRoles(userId, vStringRolesList); + + Mockito.verify(daoManager).getXXUserPermission(); + Mockito.verify(daoManager).getXXGroupPermission(); + Mockito.verify(xGroupPermissionService).populateViewBean(xGroupPermissionObj); + Mockito.verify(xUserPermissionService).populateViewBean(xUserPermissionObj); + } + + @Test + public void test24updateRoles() { + setup(); + Collection rolesList = new ArrayList<>(); + rolesList.add("ROLE_USER"); + rolesList.add("ROLE_SYS_ADMIN"); + XXPortalUserRole xxPortalUserRole = new XXPortalUserRole(); + xxPortalUserRole.setId(userId); + xxPortalUserRole.setUserRole("ROLE_USER"); + List list = new ArrayList<>(); + list.add(xxPortalUserRole); + XXPortalUserRoleDao userDao = Mockito.mock(XXPortalUserRoleDao.class); + Mockito.when(daoManager.getXXPortalUserRole()).thenReturn(userDao); + Mockito.when(userDao.findByUserId(userId)).thenReturn(list); + boolean isFound = userMgr.updateRoles(userId, rolesList); + Assert.assertFalse(isFound); + + Mockito.when(restErrorUtil.createRESTException("Invalid user role, please provide valid user role.", MessageEnums.INVALID_INPUT_DATA)).thenThrow(new WebApplicationException()); + thrown.expect(WebApplicationException.class); + rolesList.clear(); + rolesList.add("INVALID_ROLE"); + isFound = userMgr.updateRoles(userId, rolesList); + } + + @Test + public void test25updatePasswordInSHA256() { + XXPortalUserDao userDao = Mockito.mock(XXPortalUserDao.class); + VXPortalUser userProfile = userProfile(); + String userName = userProfile.getFirstName(); + String userPassword = userProfile.getPassword(); + XXPortalUser user = new XXPortalUser(); + user.setEmailAddress(userProfile.getEmailAddress()); + user.setFirstName(userProfile.getFirstName()); + user.setLastName(userProfile.getLastName()); + user.setLoginId(userProfile.getLoginId()); + user.setPassword(userProfile.getPassword()); + user.setUserSource(RangerCommonEnums.USER_APP); + user.setPublicScreenName(userProfile.getPublicScreenName()); + user.setId(userProfile.getId()); + Mockito.when(daoManager.getXXPortalUser()).thenReturn(userDao); + Mockito.when(daoManager.getXXPortalUser()).thenReturn(userDao); + Mockito.when(userDao.update(user)).thenReturn(user); + XXPortalUser dbXXPortalUser = userMgr.updatePasswordInSHA256(null, userPassword, false); + Assert.assertNull(dbXXPortalUser); + Mockito.when(userDao.findByLoginId(Mockito.anyString())).thenReturn(null); + dbXXPortalUser = userMgr.updatePasswordInSHA256(userName, userPassword, false); + Assert.assertNull(dbXXPortalUser); + Mockito.when(userDao.findByLoginId(Mockito.anyString())).thenReturn(user); + dbXXPortalUser = userMgr.updatePasswordInSHA256(userName, userPassword, true); + Assert.assertNotNull(dbXXPortalUser); + dbXXPortalUser = userMgr.updatePasswordInSHA256(userName, "Secret", true); + Assert.assertNotNull(dbXXPortalUser); + } + + @Test + public void test26CreateUser() { + setup(); + XXPortalUserDao userDao = Mockito.mock(XXPortalUserDao.class); + XXPortalUserRoleDao roleDao = Mockito.mock(XXPortalUserRoleDao.class); + + VXPortalUser userProfile = userProfile(); + + Collection userRoleList = new ArrayList<>(); + userRoleList.add("ROLE_USER"); + + XXPortalUser user = new XXPortalUser(); + user.setEmailAddress(userProfile.getEmailAddress()); + user.setFirstName(userProfile.getFirstName()); + user.setLastName(userProfile.getLastName()); + user.setLoginId(userProfile.getLoginId()); + String encryptedPwd = userMgr.encrypt(userProfile.getLoginId(), userProfile.getPassword()); + user.setPassword(encryptedPwd); + user.setUserSource(userProfile.getUserSource()); + user.setPublicScreenName(userProfile.getPublicScreenName()); + user.setId(userProfile.getId()); + + XXPortalUserRole xxPortalUserRole = new XXPortalUserRole(); + xxPortalUserRole.setId(user.getId()); + xxPortalUserRole.setUserRole("ROLE_USER"); + List list = new ArrayList<>(); + list.add(xxPortalUserRole); + + Mockito.when(daoManager.getXXPortalUser()).thenReturn(userDao); + Mockito.when(userDao.create(Mockito.any())).thenReturn(user); + Mockito.when(daoManager.getXXPortalUserRole()).thenReturn(roleDao); + Mockito.when(roleDao.findByUserId(userId)).thenReturn(list); + Mockito.when(userDao.findByLoginId(Mockito.anyString())).thenReturn(user); + XXPortalUser dbxxPortalUser = userMgr.createUser(userProfile, 1, userRoleList); + Assert.assertNotNull(dbxxPortalUser); + userId = dbxxPortalUser.getId(); + Assert.assertEquals(userId, dbxxPortalUser.getId()); + Assert.assertEquals(userProfile.getFirstName(), dbxxPortalUser.getFirstName()); + Assert.assertEquals(userProfile.getFirstName(), dbxxPortalUser.getFirstName()); + Assert.assertEquals(userProfile.getLastName(), dbxxPortalUser.getLastName()); + Assert.assertEquals(userProfile.getLoginId(), dbxxPortalUser.getLoginId()); + Assert.assertEquals(userProfile.getEmailAddress(), dbxxPortalUser.getEmailAddress()); + Assert.assertEquals(encryptedPwd, dbxxPortalUser.getPassword()); + + Mockito.verify(daoManager, Mockito.atLeast(1)).getXXPortalUser(); + Mockito.verify(daoManager).getXXPortalUserRole(); + } + + @Test + public void test27UpdateUser() { + setup(); + XXPortalUserDao userDao = Mockito.mock(XXPortalUserDao.class); + + VXPortalUser userProfile = userProfile(); + XXPortalUser user = new XXPortalUser(); + user.setId(userProfile.getId()); + user.setLoginId(userProfile.getLoginId()); + user.setEmailAddress(userProfile.getEmailAddress()); + user.setLoginId(userProfile.getLoginId()); + String encryptedPwd = userMgr.encrypt(userProfile.getLoginId(), userProfile.getPassword()); + user.setPassword(encryptedPwd); + Mockito.when(daoManager.getXXPortalUser()).thenReturn(userDao); + Mockito.when(userDao.getById(userProfile.getId())).thenReturn(user); + Mockito.when(restErrorUtil.createRESTException(HttpServletResponse.SC_FORBIDDEN, "Logged-In user is not allowed to access requested user data", true)).thenThrow(new WebApplicationException()); + thrown.expect(WebApplicationException.class); + XXPortalUser dbXXPortalUser = userMgr.updateUser(userProfile); + Assert.assertNotNull(dbXXPortalUser); + Assert.assertEquals(userId, dbXXPortalUser.getId()); + Assert.assertEquals(userProfile.getFirstName(), dbXXPortalUser.getFirstName()); + Assert.assertEquals(userProfile.getFirstName(), dbXXPortalUser.getFirstName()); + Assert.assertEquals(userProfile.getLastName(), dbXXPortalUser.getLastName()); + Assert.assertEquals(userProfile.getLoginId(), dbXXPortalUser.getLoginId()); + Assert.assertEquals(userProfile.getEmailAddress(), dbXXPortalUser.getEmailAddress()); + Assert.assertEquals(encryptedPwd, dbXXPortalUser.getPassword()); + + Mockito.when(restErrorUtil.createRESTException("Please provide valid email address.", MessageEnums.INVALID_INPUT_DATA)).thenThrow(new WebApplicationException()); + thrown.expect(WebApplicationException.class); + Mockito.when(stringUtil.validateEmail(Mockito.anyString())).thenReturn(false); + userMgr.updateUser(userProfile); + } + + @Test + public void test28UpdateUser() { + setup(); + XXPortalUserDao userDao = Mockito.mock(XXPortalUserDao.class); + + VXPortalUser userProfile = userProfile(); + XXPortalUser user = new XXPortalUser(); + user.setId(userProfile.getId()); + user.setLoginId(userProfile.getLoginId()); + user.setEmailAddress(userProfile.getEmailAddress()); + user.setLoginId(userProfile.getLoginId()); + String encryptedPwd = userMgr.encrypt(userProfile.getLoginId(), userProfile.getPassword()); + user.setPassword(encryptedPwd); + Mockito.when(daoManager.getXXPortalUser()).thenReturn(userDao); + Mockito.when(userDao.getById(userProfile.getId())).thenReturn(null); + XXPortalUser dbXXPortalUser = userMgr.updateUser(userProfile); + Assert.assertNull(dbXXPortalUser); + user.setStatus(RangerCommonEnums.USER_EXTERNAL); + user.setFirstName("null"); + user.setLastName("null"); + Mockito.when(userDao.getById(userProfile.getId())).thenReturn(user); + Mockito.when(restErrorUtil.createRESTException(HttpServletResponse.SC_FORBIDDEN, "Logged-In user is not allowed to access requested user data", true)).thenThrow(new WebApplicationException()); + thrown.expect(WebApplicationException.class); + dbXXPortalUser = userMgr.updateUser(userProfile); + Assert.assertNotNull(dbXXPortalUser); + Assert.assertEquals(userId, dbXXPortalUser.getId()); + Assert.assertEquals(userProfile.getLoginId(), dbXXPortalUser.getLoginId()); + Assert.assertEquals(userProfile.getEmailAddress(), dbXXPortalUser.getEmailAddress()); + Assert.assertEquals(encryptedPwd, dbXXPortalUser.getPassword()); + + Mockito.when(restErrorUtil.createRESTException("Invalid user, please provide valid username.", MessageEnums.INVALID_INPUT_DATA)).thenThrow(new WebApplicationException()); + thrown.expect(WebApplicationException.class); + userProfile.setLoginId(null); + dbXXPortalUser = userMgr.updateUser(userProfile); + + Mockito.when(restErrorUtil.createRESTException("The email address you've provided already exists in system.", MessageEnums.INVALID_INPUT_DATA)).thenThrow(new WebApplicationException()); + thrown.expect(WebApplicationException.class); + userProfile.setLoginId("test1234"); + user.setLoginId(null); + Mockito.when(userDao.findByEmailAddress(Mockito.anyString())).thenReturn(user); + dbXXPortalUser = userMgr.updateUser(userProfile); + } + + @Test + public void test29UpdateOldUserName() { + setup(); + XXPortalUserDao userDao = Mockito.mock(XXPortalUserDao.class); + XXUserDao xXUserDao = Mockito.mock(XXUserDao.class); + VXPortalUser userProfile = userProfile(); + String userLoginId = userProfile.getLoginId(); + String newUserName = "newUserName"; + String currentPassword = userProfile.getPassword(); + + XXPortalUser xXPortalUser = new XXPortalUser(); + xXPortalUser.setEmailAddress(userProfile.getEmailAddress()); + xXPortalUser.setFirstName(userProfile.getFirstName()); + xXPortalUser.setLastName(userProfile.getLastName()); + xXPortalUser.setLoginId(userProfile.getLoginId()); + String encryptedPwd = userMgr.encrypt(userProfile.getLoginId(), userProfile.getPassword()); + xXPortalUser.setPassword(encryptedPwd); + xXPortalUser.setUserSource(userProfile.getUserSource()); + xXPortalUser.setPublicScreenName(userProfile.getPublicScreenName()); + xXPortalUser.setId(userProfile.getId()); + xXPortalUser.setUserSource(RangerCommonEnums.USER_APP); + + XXUser xXUser = new XXUser(); + Collection userRoleList = new ArrayList<>(); + userRoleList.add("ROLE_USER"); + Collection groupNameList = new ArrayList<>(); + groupNameList.add("Grp2"); + xXUser.setId(userId); + xXUser.setDescription(userProfile.getPublicScreenName()); + xXUser.setName(userProfile.getLoginId()); + + Mockito.when(daoManager.getXXPortalUser()).thenReturn(userDao); + Mockito.when(userDao.findByLoginId(userProfile.getLoginId())).thenReturn(xXPortalUser); + Mockito.when(daoManager.getXXUser()).thenReturn(xXUserDao); + Mockito.when(xXUserDao.findByUserName(xXUser.getName())).thenReturn(xXUser); + + xXUser.setName(newUserName); + Mockito.when(xXUserDao.update(xXUser)).thenReturn(xXUser); + + xXPortalUser.setLoginId(newUserName); + Mockito.when(userDao.update(xXPortalUser)).thenReturn(xXPortalUser); + + xXPortalUser = userMgr.updateOldUserName(userLoginId, newUserName, currentPassword); + + Assert.assertNotNull(xXPortalUser); + Assert.assertEquals(newUserName, xXPortalUser.getLoginId()); + xXPortalUser.setUserSource(RangerCommonEnums.USER_EXTERNAL); + Mockito.when(userDao.findByLoginId(userProfile.getLoginId())).thenReturn(xXPortalUser); + xXPortalUser = userMgr.updateOldUserName(userLoginId, newUserName, currentPassword); + xXPortalUser = userMgr.updateOldUserName(null, newUserName, currentPassword); + Mockito.when(userDao.findByLoginId(userProfile.getLoginId())).thenReturn(null); + xXPortalUser = userMgr.updateOldUserName(userLoginId, newUserName, currentPassword); + } + + @Test + public void test30getRolesByLoginId() { + setup(); + XXPortalUserDao userDao = Mockito.mock(XXPortalUserDao.class); + XXPortalUserRoleDao roleDao = Mockito.mock(XXPortalUserRoleDao.class); + + VXPortalUser userProfile = userProfile(); + String userLoginId = userProfile.getLoginId(); + + Collection userRoleList = new ArrayList<>(); + userRoleList.add("ROLE_USER"); + + XXPortalUser user = new XXPortalUser(); + user.setEmailAddress(userProfile.getEmailAddress()); + user.setFirstName(userProfile.getFirstName()); + user.setLastName(userProfile.getLastName()); + user.setLoginId(userProfile.getLoginId()); + String encryptedPwd = userMgr.encrypt(userProfile.getLoginId(), userProfile.getPassword()); + user.setPassword(encryptedPwd); + user.setUserSource(userProfile.getUserSource()); + user.setPublicScreenName(userProfile.getPublicScreenName()); + user.setId(userProfile.getId()); + + XXPortalUserRole xxPortalUserRole = new XXPortalUserRole(); + xxPortalUserRole.setId(user.getId()); + xxPortalUserRole.setUserRole("ROLE_USER"); + List list = new ArrayList<>(); + list.add(xxPortalUserRole); + + Mockito.when(daoManager.getXXPortalUser()).thenReturn(userDao); + Mockito.when(userDao.findByLoginId(userProfile.getLoginId())).thenReturn(user); + Mockito.when(daoManager.getXXPortalUserRole()).thenReturn(roleDao); + Mockito.when(roleDao.findByUserId(userId)).thenReturn(list); + Collection roleList = userMgr.getRolesByLoginId(userLoginId); + Assert.assertNotNull(roleList); + Assert.assertEquals(userLoginId, user.getLoginId()); + Assert.assertEquals(userRoleList, roleList); + roleList = userMgr.getRolesByLoginId(null); + Mockito.when(roleDao.findByUserId(userId)).thenReturn(null); + roleList = userMgr.getRolesByLoginId(userLoginId); + Mockito.when(userDao.findByLoginId(userProfile.getLoginId())).thenReturn(null); + roleList = userMgr.getRolesByLoginId(userLoginId); + Assert.assertNotNull(roleList); + } + + @Test + public void test31checkAccess() { + setup(); + XXPortalUserDao userDao = Mockito.mock(XXPortalUserDao.class); + Mockito.when(daoManager.getXXPortalUser()).thenReturn(userDao); + XXPortalUser xPortalUser = Mockito.mock(XXPortalUser.class); + Mockito.when(restErrorUtil.createRESTException(HttpServletResponse.SC_FORBIDDEN, "Logged-In user is not allowed to access requested user data", true)).thenThrow(new WebApplicationException()); + thrown.expect(WebApplicationException.class); + userMgr.checkAccess(xPortalUser); + destroySession(); + VXPortalUser userProfile = userProfile(); + xPortalUser = xxPortalUser(userProfile); + xPortalUser.setId(userProfile.getId()); + setupUser(); + userMgr.checkAccess(xPortalUser); + + destroySession(); + Mockito.when(restErrorUtil.create403RESTException("User access denied. loggedInUser=Not Logged In, accessing user=" + userProfile.getId())).thenThrow(new WebApplicationException()); + thrown.expect(WebApplicationException.class); + userMgr.checkAccess(xPortalUser); + + Mockito.when(restErrorUtil.create403RESTException("serverMsg.userMgrWrongUser")).thenThrow(new WebApplicationException()); + thrown.expect(WebApplicationException.class); + xPortalUser = null; + userMgr.checkAccess(xPortalUser); + } + + @Test + public void test32checkAdminAccess() { + setup(); + userMgr.checkAdminAccess(); + destroySession(); + Mockito.when(restErrorUtil.create403RESTException("Operation not allowed. loggedInUser=. Not Logged In.")).thenThrow(new WebApplicationException()); + thrown.expect(WebApplicationException.class); + userMgr.checkAdminAccess(); + } + + @Test + public void test34updateRoleForExternalUsers() { + setupRangerUserSyncUser(); + XXPortalUserDao userDao = Mockito.mock(XXPortalUserDao.class); + XXUserPermissionDao xUserPermissionDao = Mockito.mock(XXUserPermissionDao.class); + Collection existingRoleList = new ArrayList<>(); + existingRoleList.add(RangerConstants.ROLE_USER); + Collection reqRoleList = new ArrayList<>(); + reqRoleList.add(RangerConstants.ROLE_SYS_ADMIN); + + VXPortalUser userProfile = userProfile(); + XXPortalUser user = new XXPortalUser(); + user.setId(userProfile.getId()); + user.setLoginId(userProfile.getLoginId()); + user.setEmailAddress(userProfile.getEmailAddress()); + user.setLoginId(userProfile.getLoginId()); + String encryptedPwd = userMgr.encrypt(userProfile.getLoginId(), userProfile.getPassword()); + user.setPassword(encryptedPwd); + + XXPortalUserRole xxPortalUserRole = new XXPortalUserRole(); + xxPortalUserRole.setId(userProfile.getId()); + xxPortalUserRole.setUserRole(RangerConstants.ROLE_USER); + List list = new ArrayList<>(); + list.add(xxPortalUserRole); + + List xUserPermissionsList = new ArrayList<>(); + XXUserPermission xUserPermissionObj = new XXUserPermission(); + xUserPermissionObj.setAddedByUserId(userId); + xUserPermissionObj.setCreateTime(new Date()); + xUserPermissionObj.setId(userId); + xUserPermissionObj.setIsAllowed(1); + xUserPermissionObj.setModuleId(1L); + xUserPermissionObj.setUpdatedByUserId(userId); + xUserPermissionObj.setUpdateTime(new Date()); + xUserPermissionObj.setUserId(userId); + xUserPermissionsList.add(xUserPermissionObj); + Mockito.when(daoManager.getXXPortalUser()).thenReturn(userDao); + Mockito.when(userDao.getById(userProfile.getId())).thenReturn(user); + Mockito.when(daoManager.getXXUserPermission()).thenReturn(xUserPermissionDao); + Mockito.when(xUserPermissionDao.findByUserPermissionId(userProfile.getId())).thenReturn(xUserPermissionsList); + Mockito.when(restErrorUtil.createRESTException(HttpServletResponse.SC_FORBIDDEN, "Logged-In user is not allowed to access requested user data", true)).thenThrow(new WebApplicationException()); + thrown.expect(WebApplicationException.class); + VXPortalUser dbVXPortalUser = userMgr.updateRoleForExternalUsers(reqRoleList, existingRoleList, userProfile); + Assert.assertNotNull(dbVXPortalUser); + Assert.assertEquals(userId, dbVXPortalUser.getId()); + Assert.assertEquals(userProfile.getFirstName(), dbVXPortalUser.getFirstName()); + Assert.assertEquals(userProfile.getLastName(), dbVXPortalUser.getLastName()); + Assert.assertEquals(userProfile.getLoginId(), dbVXPortalUser.getLoginId()); + Assert.assertEquals(userProfile.getEmailAddress(), dbVXPortalUser.getEmailAddress()); + } + + @Test + public void test35mapVXPortalUserToXXPortalUser() { + setup(); + Collection existingRoleList = new ArrayList<>(); + existingRoleList.add(RangerConstants.ROLE_USER); + Collection reqRoleList = new ArrayList<>(); + reqRoleList.add(RangerConstants.ROLE_SYS_ADMIN); + + VXPortalUser userProfile = userProfile(); + userProfile.setFirstName("null"); + userProfile.setLastName("null"); + XXPortalUser user = new XXPortalUser(); + user.setId(userProfile.getId()); + user.setLoginId(userProfile.getLoginId()); + user.setEmailAddress(userProfile.getEmailAddress()); + user.setLoginId(userProfile.getLoginId()); + String encryptedPwd = userMgr.encrypt(userProfile.getLoginId(), userProfile.getPassword()); + user.setPassword(encryptedPwd); + + XXPortalUserRole xxPortalUserRole = new XXPortalUserRole(); + xxPortalUserRole.setId(userProfile.getId()); + xxPortalUserRole.setUserRole(RangerConstants.ROLE_USER); + List list = new ArrayList<>(); + list.add(xxPortalUserRole); + + List xUserPermissionsList = new ArrayList<>(); + XXUserPermission xUserPermissionObj = new XXUserPermission(); + xUserPermissionObj.setAddedByUserId(userId); + xUserPermissionObj.setCreateTime(new Date()); + xUserPermissionObj.setId(userId); + xUserPermissionObj.setIsAllowed(1); + xUserPermissionObj.setModuleId(1L); + xUserPermissionObj.setUpdatedByUserId(userId); + xUserPermissionObj.setUpdateTime(new Date()); + xUserPermissionObj.setUserId(userId); + xUserPermissionsList.add(xUserPermissionObj); + XXPortalUser dbVXPortalUser = userMgr.mapVXPortalUserToXXPortalUser(userProfile); + Assert.assertNotNull(dbVXPortalUser); + Assert.assertEquals(userProfile.getLoginId(), dbVXPortalUser.getLoginId()); + Assert.assertEquals(userProfile.getEmailAddress(), dbVXPortalUser.getEmailAddress()); + + userProfile.setLoginId(null); + Mockito.when(restErrorUtil.createRESTException("LoginId should not be null or blank, It is", MessageEnums.INVALID_INPUT_DATA)).thenThrow(new WebApplicationException()); + thrown.expect(WebApplicationException.class); + userMgr.mapVXPortalUserToXXPortalUser(userProfile); + } + + @Test + public void test36UpdateUser() { + setup(); + XXPortalUserDao userDao = Mockito.mock(XXPortalUserDao.class); + VXPortalUser userProfile = userProfile(); + XXPortalUser user = new XXPortalUser(); + user.setId(userProfile.getId()); + user.setLoginId(userProfile.getLoginId()); + userProfile.setFirstName("User"); + userProfile.setLastName("User"); + String encryptedPwd = userMgr.encrypt(userProfile.getLoginId(), userProfile.getPassword()); + user.setPassword(encryptedPwd); + Mockito.when(daoManager.getXXPortalUser()).thenReturn(userDao); + Mockito.when(userDao.getById(userProfile.getId())).thenReturn(user); + Mockito.when(restErrorUtil.createRESTException(HttpServletResponse.SC_FORBIDDEN, "Logged-In user is not allowed to access requested user data", true)).thenThrow(new WebApplicationException()); + thrown.expect(WebApplicationException.class); + XXPortalUser dbXXPortalUser = userMgr.updateUser(userProfile); + Assert.assertNotNull(dbXXPortalUser); + Mockito.when(stringUtil.isEmpty(Mockito.anyString())).thenReturn(true); + userProfile.setFirstName("null"); + userProfile.setLastName("null"); + userProfile.setEmailAddress(""); + dbXXPortalUser = userMgr.updateUser(userProfile); + } + + @Test + public void test37createUserSearchQuery() { + EntityManager entityManager = Mockito.mock(EntityManager.class); + String queryString = "Select id,loginId,emailAddress,firstName,lastName,statusList,publicScreenName,status from XXPortalUser"; + Query query = Mockito.mock(Query.class); + SearchCriteria searchCriteria = new SearchCriteria(); + searchCriteria.setDistinct(true); + searchCriteria.setGetChildren(true); + searchCriteria.setGetCount(true); + searchCriteria.setMaxRows(12); + searchCriteria.setOwnerId(userId); + searchCriteria.setStartIndex(1); + searchCriteria.setSortBy("asc"); + VXPortalUser vXPortalUser = userProfile(); + List userRoleList = new ArrayList<>(); + userRoleList.add("ROLE_USER"); + List statusList = new ArrayList<>(); + statusList.add(1); + searchCriteria.addParam("roleList", userRoleList); + searchCriteria.addParam("userId", vXPortalUser.getId()); + searchCriteria.addParam("loginId", vXPortalUser.getLoginId()); + searchCriteria.addParam("emailAddress", vXPortalUser.getEmailAddress()); + searchCriteria.addParam("firstName", vXPortalUser.getFirstName()); + searchCriteria.addParam("lastName", vXPortalUser.getLastName()); + searchCriteria.addParam("statusList", statusList); + searchCriteria.addParam("publicScreenName", vXPortalUser.getPublicScreenName()); + searchCriteria.addParam("status", vXPortalUser.getStatus()); + searchCriteria.addParam("familyScreenName", vXPortalUser.getPublicScreenName()); + Mockito.when(daoManager.getEntityManager()).thenReturn(entityManager); + Mockito.when(entityManager.createQuery(Mockito.anyString())).thenReturn(query); + Query newQuery = userMgr.createUserSearchQuery(query.toString(), queryString, searchCriteria); + Assert.assertNotNull(newQuery); + userRoleList.add("ROLE_SYS_ADMIN"); + statusList.add(0); + searchCriteria.addParam("statusList", statusList); + searchCriteria.addParam("roleList", userRoleList); + newQuery = userMgr.createUserSearchQuery(query.toString(), queryString, searchCriteria); + } + + @Test + public void test38mapVXPortalUserToXXPortalUser() { + Collection existingRoleList = new ArrayList<>(); + existingRoleList.add(RangerConstants.ROLE_USER); + VXPortalUser dbVXPortalUser = userMgr.mapXXPortalUserToVXPortalUser(null, existingRoleList); + XXPortalUser user = new XXPortalUser(); + Assert.assertNull(dbVXPortalUser); + dbVXPortalUser = userMgr.mapXXPortalUserToVXPortalUser(user, existingRoleList); + Assert.assertNull(dbVXPortalUser); + } + + @Test + public void test39gjUserToUserProfile() { + VXPortalUser vXPortalUser = new VXPortalUser(); + XXPortalUser xXPortalUser = new XXPortalUser(); + userMgr.gjUserToUserProfile(xXPortalUser, vXPortalUser); + } + + @Test + public void test40deleteUserRole() { + XXPortalUserRole xxPortalUserRole = new XXPortalUserRole(); + userMgr.deleteUserRole(1L, xxPortalUserRole); + } + + @Test + public void test41mapXXPortalUserToVXPortalUserForDefaultAccount() { + VXPortalUser vXPortalUser = userProfile(); + XXPortalUser xXPortalUser = xxPortalUser(vXPortalUser); + XXPortalUserRoleDao roleDao = Mockito.mock(XXPortalUserRoleDao.class); + Mockito.when(daoManager.getXXPortalUserRole()).thenReturn(roleDao); + XXPortalUserRole xxPortalUserRole = new XXPortalUserRole(); + xxPortalUserRole.setId(userId); + xxPortalUserRole.setUserRole("ROLE_USER"); + List list = new ArrayList<>(); + list.add(xxPortalUserRole); + Mockito.when(roleDao.findByParentId(xXPortalUser.getId())).thenReturn(list); + VXPortalUser dbVXPortalUser = userMgr.mapXXPortalUserToVXPortalUserForDefaultAccount(xXPortalUser); + Assert.assertNotNull(dbVXPortalUser); + } + + @Test + public void test42EncryptWithOlderAlgo() { + VXPortalUser vXPortalUser = userProfile(); + String encodedpasswd = userMgr.encryptWithOlderAlgo(vXPortalUser.getLoginId(), vXPortalUser.getPassword()); + Assert.assertNotNull(encodedpasswd); + encodedpasswd = userMgr.encryptWithOlderAlgo(null, vXPortalUser.getPassword()); + Assert.assertNotNull(encodedpasswd); + encodedpasswd = userMgr.encryptWithOlderAlgo(vXPortalUser.getLoginId(), null); + Assert.assertNotNull(encodedpasswd); + encodedpasswd = userMgr.encryptWithOlderAlgo(null, null); + Assert.assertNotNull(encodedpasswd); + } + + @Test + public void test43IsNewPasswordDifferent() { + VXPortalUser vXPortalUser = userProfile(); + String newCred = "New5ecret4User21"; + boolean isDifferent = userMgr.isNewPasswordDifferent(vXPortalUser.getLoginId(), vXPortalUser.getPassword(), newCred); + Assert.assertTrue(isDifferent); + isDifferent = userMgr.isNewPasswordDifferent(vXPortalUser.getLoginId(), vXPortalUser.getPassword(), vXPortalUser.getPassword()); + Assert.assertFalse(isDifferent); + isDifferent = userMgr.isNewPasswordDifferent(vXPortalUser.getLoginId(), null, newCred); + Assert.assertTrue(isDifferent); + isDifferent = userMgr.isNewPasswordDifferent(null, vXPortalUser.getPassword(), newCred); + Assert.assertTrue(isDifferent); + isDifferent = userMgr.isNewPasswordDifferent(null, null, newCred); + Assert.assertTrue(isDifferent); + } + + @Test + public void test44IsPasswordValid() { + VXPortalUser vXPortalUser = userProfile(); + boolean isValid = userMgr.isPasswordValid(vXPortalUser.getLoginId(), "ceb4f32325eda6142bd65215f4c0f371", vXPortalUser.getPassword()); + Assert.assertFalse(isValid); + } + + @Test + public void test45ChangePassword() { + destroySession(); + setupUser(); + VXPortalUser userProfile = userProfile(); + XXPortalUser user2 = new XXPortalUser(); + user2.setId(userId); + + XXPortalUserDao userDao = Mockito.mock(XXPortalUserDao.class); + Mockito.when(daoManager.getXXPortalUser()).thenReturn(userDao); + Mockito.when(daoManager.getXXPortalUser().findByLoginId(Mockito.anyString())).thenReturn(user2); + VXPasswordChange invalidpwdChange = new VXPasswordChange(); + invalidpwdChange.setId(userProfile.getId()); + invalidpwdChange.setLoginId(userProfile.getLoginId()); + invalidpwdChange.setOldPassword("invalidOldPassword"); + invalidpwdChange.setEmailAddress(userProfile.getEmailAddress()); + invalidpwdChange.setUpdPassword(userProfile.getPassword()); + Mockito.when(restErrorUtil.createRESTException(HttpServletResponse.SC_FORBIDDEN, "Logged-In user is not allowed to access requested user data", true)).thenThrow(new WebApplicationException()); + thrown.expect(WebApplicationException.class); + userMgr.changePassword(invalidpwdChange); + } + + @Test + public void test46ChangePassword() { + destroySession(); + setupUser(); + VXPortalUser userProfile = userProfile(); + XXPortalUser gjUser = new XXPortalUser(); + gjUser.setId(userId); + VXPasswordChange invalidpwdChange = new VXPasswordChange(); + invalidpwdChange.setId(userProfile.getId()); + invalidpwdChange.setLoginId(userProfile.getLoginId() + 1); + invalidpwdChange.setOldPassword("invalidOldPassword"); + invalidpwdChange.setEmailAddress(userProfile.getEmailAddress()); + invalidpwdChange.setUpdPassword(userProfile.getPassword()); + + XXPortalUserDao userDao = Mockito.mock(XXPortalUserDao.class); + Mockito.when(daoManager.getXXPortalUser()).thenReturn(userDao); + Mockito.when(userDao.findByLoginId(invalidpwdChange.getLoginId())).thenReturn(gjUser); + + Mockito.when(restErrorUtil.createRESTException(HttpServletResponse.SC_FORBIDDEN, "Logged-In user is not allowed to access requested user data", true)).thenThrow(new WebApplicationException()); + thrown.expect(WebApplicationException.class); + userMgr.changePassword(invalidpwdChange); + } + + @Test + public void test47ChangePasswordAsUser() { + destroySession(); + setupUser(); + XXPortalUserDao userDao = Mockito.mock(XXPortalUserDao.class); + VXPortalUser userProfile = userProfile(); + + VXPasswordChange pwdChange = new VXPasswordChange(); + pwdChange.setId(userProfile.getId()); + pwdChange.setLoginId(userProfile.getLoginId()); + pwdChange.setOldPassword(userProfile.getPassword()); + pwdChange.setEmailAddress(userProfile.getEmailAddress()); + pwdChange.setUpdPassword(userProfile.getPassword()); + + XXPortalUser user = new XXPortalUser(); + user.setId(userProfile.getId()); + user.setLoginId(userProfile.getLoginId()); + String encryptCred = userMgr.encrypt(userProfile.getLoginId(), userProfile.getPassword()); + user.setPassword(encryptCred); + user.setOldPasswords(encryptCred); + Mockito.when(daoManager.getXXPortalUser()).thenReturn(userDao); + Mockito.when(userDao.findByLoginId(Mockito.anyString())).thenReturn(user); + Mockito.when(stringUtil.equals(Mockito.anyString(), Mockito.nullable(String.class))).thenReturn(true); + Mockito.when(daoManager.getXXPortalUser()).thenReturn(userDao); + Mockito.when(stringUtil.validatePassword(Mockito.anyString(), Mockito.any(String[].class))).thenReturn(true); + Mockito.when(userDao.findByLoginId(Mockito.anyString())).thenReturn(user); + XXPortalUserRoleDao xPortalUserRoleDao = Mockito.mock(XXPortalUserRoleDao.class); + Mockito.when(daoManager.getXXPortalUserRole()).thenReturn(xPortalUserRoleDao); + List xPortalUserRoleList = new ArrayList<>(); + XXPortalUserRole xxPortalUserRole = new XXPortalUserRole(); + xxPortalUserRole.setId(userId); + xxPortalUserRole.setUserId(userId); + xxPortalUserRole.setUserRole("ROLE_USER"); + xPortalUserRoleList.add(xxPortalUserRole); + XXUserPermissionDao xUserPermissionDao = Mockito.mock(XXUserPermissionDao.class); + XXGroupPermissionDao xGroupPermissionDao = Mockito.mock(XXGroupPermissionDao.class); + Mockito.when(daoManager.getXXUserPermission()).thenReturn(xUserPermissionDao); + List xUserPermissionsList = new ArrayList<>(); + List xGroupPermissionList = new ArrayList<>(); + Mockito.when(xUserPermissionDao.findByUserPermissionIdAndIsAllowed(userProfile.getId())).thenReturn(xUserPermissionsList); + Mockito.when(daoManager.getXXGroupPermission()).thenReturn(xGroupPermissionDao); + Mockito.when(xGroupPermissionDao.findbyVXPortalUserId(userProfile.getId())).thenReturn(xGroupPermissionList); + XXPortalUserRoleDao roleDao = Mockito.mock(XXPortalUserRoleDao.class); + Mockito.when(daoManager.getXXPortalUserRole()).thenReturn(roleDao); + Mockito.when(roleDao.findByParentId(Mockito.anyLong())).thenReturn(xPortalUserRoleList); + Mockito.when(restErrorUtil.createRESTException("serverMsg.userMgrOldPassword", MessageEnums.INVALID_INPUT_DATA, user.getId(), "password", user.toString())).thenThrow(new WebApplicationException()); + thrown.expect(WebApplicationException.class); + userMgr.changePassword(pwdChange); + } + + @Test + public void test48ChangePasswordAsUser() { + destroySession(); + setupUser(); + XXPortalUserDao userDao = Mockito.mock(XXPortalUserDao.class); + VXPortalUser userProfile = userProfile(); + + VXPasswordChange pwdChange = new VXPasswordChange(); + pwdChange.setId(userProfile.getId()); + pwdChange.setLoginId(userProfile.getLoginId()); + pwdChange.setOldPassword(userProfile.getPassword()); + pwdChange.setEmailAddress(userProfile.getEmailAddress()); + pwdChange.setUpdPassword(userProfile.getPassword()); + + XXPortalUser user = new XXPortalUser(); + user.setId(userProfile.getId()); + user.setLoginId(userProfile.getLoginId()); + String encryptCred = userMgr.encrypt(userProfile.getLoginId(), userProfile.getPassword()); + user.setPassword(encryptCred); + Mockito.when(daoManager.getXXPortalUser()).thenReturn(userDao); + Mockito.when(userDao.findByLoginId(Mockito.anyString())).thenReturn(user); + Mockito.when(stringUtil.equals(Mockito.anyString(), Mockito.nullable(String.class))).thenReturn(true); + Mockito.when(daoManager.getXXPortalUser()).thenReturn(userDao); + Mockito.when(stringUtil.validatePassword(Mockito.anyString(), Mockito.any(String[].class))).thenReturn(false); + Mockito.when(userDao.findByLoginId(Mockito.anyString())).thenReturn(user); + XXPortalUserRoleDao xPortalUserRoleDao = Mockito.mock(XXPortalUserRoleDao.class); + Mockito.when(daoManager.getXXPortalUserRole()).thenReturn(xPortalUserRoleDao); + List xPortalUserRoleList = new ArrayList<>(); + XXPortalUserRole xxPortalUserRole = new XXPortalUserRole(); + xxPortalUserRole.setId(userId); + xxPortalUserRole.setUserId(userId); + xxPortalUserRole.setUserRole("ROLE_USER"); + xPortalUserRoleList.add(xxPortalUserRole); + XXUserPermissionDao xUserPermissionDao = Mockito.mock(XXUserPermissionDao.class); + XXGroupPermissionDao xGroupPermissionDao = Mockito.mock(XXGroupPermissionDao.class); + Mockito.when(daoManager.getXXUserPermission()).thenReturn(xUserPermissionDao); + List xUserPermissionsList = new ArrayList<>(); + List xGroupPermissionList = new ArrayList<>(); + Mockito.when(xUserPermissionDao.findByUserPermissionIdAndIsAllowed(userProfile.getId())).thenReturn(xUserPermissionsList); + Mockito.when(daoManager.getXXGroupPermission()).thenReturn(xGroupPermissionDao); + Mockito.when(xGroupPermissionDao.findbyVXPortalUserId(userProfile.getId())).thenReturn(xGroupPermissionList); + XXPortalUserRoleDao roleDao = Mockito.mock(XXPortalUserRoleDao.class); + Mockito.when(daoManager.getXXPortalUserRole()).thenReturn(roleDao); + Mockito.when(roleDao.findByParentId(Mockito.anyLong())).thenReturn(xPortalUserRoleList); + Mockito.when(restErrorUtil.createRESTException("serverMsg.userMgrNewPassword", MessageEnums.INVALID_PASSWORD, null, null, pwdChange.getLoginId())).thenThrow(new WebApplicationException()); + thrown.expect(WebApplicationException.class); + userMgr.changePassword(pwdChange); + } + + @Test + public void test49CreateDefaultAccountUser() { + destroySession(); + setup(); + XXPortalUserDao userDao = Mockito.mock(XXPortalUserDao.class); + XXPortalUserRoleDao roleDao = Mockito.mock(XXPortalUserRoleDao.class); + VXPortalUser userProfile = userProfile(); + userProfile.setStatus(RangerCommonEnums.USER_EXTERNAL); + Collection userRoleList = new ArrayList<>(); + userRoleList.add("ROLE_USER"); + userProfile.setUserRoleList(userRoleList); + XXPortalUser user = new XXPortalUser(); + user.setEmailAddress(userProfile.getEmailAddress()); + user.setUserSource(RangerCommonEnums.USER_EXTERNAL); + XXPortalUserRole xxPortalUserRole = new XXPortalUserRole(); + xxPortalUserRole.setId(userId); + xxPortalUserRole.setUserRole("ROLE_USER"); + + List list = new ArrayList<>(); + list.add(xxPortalUserRole); + + Mockito.when(daoManager.getXXPortalUser()).thenReturn(userDao); + Mockito.when(userDao.findByLoginId(Mockito.anyString())).thenReturn(null, user); + Mockito.when(userDao.findByEmailAddress(Mockito.anyString())).thenReturn(null); + Mockito.when(daoManager.getXXPortalUserRole()).thenReturn(roleDao); + Mockito.when(userDao.create(Mockito.any())).thenReturn(user); + Mockito.doNothing().when(rangerBizUtil).blockAuditorRoleUser(); + userProfile.setEmailAddress(null); + VXPortalUser dbVXPortalUser = userMgr.createDefaultAccountUser(userProfile); + Assert.assertNotNull(dbVXPortalUser); + Assert.assertEquals(user.getId(), dbVXPortalUser.getId()); + Assert.assertEquals(user.getFirstName(), dbVXPortalUser.getFirstName()); + Assert.assertEquals(user.getLastName(), dbVXPortalUser.getLastName()); + Assert.assertEquals(user.getLoginId(), dbVXPortalUser.getLoginId()); + Assert.assertEquals(user.getEmailAddress(), dbVXPortalUser.getEmailAddress()); + Assert.assertEquals(user.getPassword(), dbVXPortalUser.getPassword()); + Mockito.verify(daoManager, Mockito.atLeast(1)).getXXPortalUser(); + Mockito.verify(daoManager, Mockito.atLeast(1)).getXXPortalUserRole(); + + Mockito.when(userDao.findByLoginId(Mockito.anyString())).thenReturn(null); + Mockito.when(userDao.findByEmailAddress(Mockito.anyString())).thenReturn(user); + Mockito.when(restErrorUtil.createRESTException("The email address " + user.getEmailAddress() + " you've provided already exists. Please try again with different email address.", MessageEnums.OPER_NOT_ALLOWED_FOR_STATE)).thenThrow(new WebApplicationException()); + thrown.expect(WebApplicationException.class); + userProfile.setEmailAddress(user.getEmailAddress()); + userMgr.createDefaultAccountUser(userProfile); + } + + @Test + public void test50AddUserRole() { + setupUser(); + XXPortalUserRole xxPortalUserRole = new XXPortalUserRole(); + xxPortalUserRole.setId(userId); + xxPortalUserRole.setUserRole("ROLE_USER"); + List list = new ArrayList<>(); + list.add(xxPortalUserRole); + XXPortalUserRoleDao userDao = Mockito.mock(XXPortalUserRoleDao.class); + Mockito.when(daoManager.getXXPortalUserRole()).thenReturn(userDao); + Mockito.when(userDao.findByUserId(userId)).thenReturn(list); + try { + userMgr.addUserRole(userId, "ROLE_SYS_ADMIN"); + } catch (Exception ignored) { + } + destroySession(); + userMgr.addUserRole(userId, "ROLE_SYS_ADMIN"); + } + + @Test + public void test51UpdateUserWithPass() { + setup(); + XXPortalUserDao userDao = Mockito.mock(XXPortalUserDao.class); + VXPortalUser userProfile = userProfile(); + userProfile.setPassword("password1234"); + XXPortalUser user = new XXPortalUser(); + user.setId(userProfile.getId()); + user.setLoginId(userProfile.getLoginId()); + user.setEmailAddress(userProfile.getEmailAddress()); + user.setLoginId(userProfile.getLoginId()); + String encryptedPwd = userMgr.encrypt(userProfile.getLoginId(), userProfile.getPassword()); + user.setPassword(encryptedPwd); + Mockito.when(daoManager.getXXPortalUser()).thenReturn(userDao); + Mockito.when(userDao.getById(userProfile.getId())).thenReturn(user); + Mockito.when(restErrorUtil.createRESTException(HttpServletResponse.SC_FORBIDDEN, "Logged-In user is not allowed to access requested user data", true)).thenThrow(new WebApplicationException()); + thrown.expect(WebApplicationException.class); + userMgr.updateUserWithPass(userProfile); + } + + private VXPortalUser userProfile() { + VXPortalUser userProfile = new VXPortalUser(); + userProfile.setEmailAddress("test@test.com"); + userProfile.setFirstName("user12"); + userProfile.setLastName("test12"); + userProfile.setLoginId(userLoginID); + userProfile.setPassword("usertest12323"); + userProfile.setUserSource(1); + userProfile.setPublicScreenName("testuser"); + userProfile.setId(userId); + return userProfile; + } + + private XXPortalUser xxPortalUser(VXPortalUser userProfile) { + XXPortalUser xxPortalUser = new XXPortalUser(); + xxPortalUser.setEmailAddress(userProfile.getEmailAddress()); + xxPortalUser.setFirstName(userProfile.getFirstName()); + xxPortalUser.setLastName(userProfile.getLastName()); + xxPortalUser.setLoginId(userProfile.getLoginId()); + xxPortalUser.setPassword(userProfile.getPassword()); + xxPortalUser.setUserSource(userProfile.getUserSource()); + xxPortalUser.setPublicScreenName(userProfile.getPublicScreenName()); + return xxPortalUser; + } } diff --git a/security-admin/src/test/java/org/apache/ranger/biz/TestXUserMgr.java b/security-admin/src/test/java/org/apache/ranger/biz/TestXUserMgr.java index 2da5d3cd8d..699e4ce1f4 100644 --- a/security-admin/src/test/java/org/apache/ranger/biz/TestXUserMgr.java +++ b/security-admin/src/test/java/org/apache/ranger/biz/TestXUserMgr.java @@ -6,7 +6,7 @@ * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -16,18 +16,6 @@ */ package org.apache.ranger.biz; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Date; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import javax.servlet.http.HttpServletResponse; -import javax.ws.rs.WebApplicationException; - import org.apache.ranger.common.AppConstants; import org.apache.ranger.common.ContextUtil; import org.apache.ranger.common.MessageEnums; @@ -81,11 +69,11 @@ import org.apache.ranger.entity.XXUser; import org.apache.ranger.entity.XXUserPermission; import org.apache.ranger.plugin.model.RangerPolicy; -import org.apache.ranger.plugin.model.RangerSecurityZone; import org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyItem; import org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyItemAccess; import org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyItemCondition; import org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyResource; +import org.apache.ranger.plugin.model.RangerSecurityZone; import org.apache.ranger.plugin.model.UserInfo; import org.apache.ranger.security.context.RangerContextHolder; import org.apache.ranger.security.context.RangerSecurityContext; @@ -141,4598 +129,4572 @@ import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.transaction.PlatformTransactionManager; +import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.WebApplicationException; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Date; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + @RunWith(MockitoJUnitRunner.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class TestXUserMgr { - - private static Long userId = 8L; - private static String adminLoginID = "admin"; - private static String keyadminLoginID = "keyadmin"; - private static String userLoginID = "testuser"; - private static String groupName = "public"; - private static final String RANGER_USER_GROUP_GLOBAL_STATE_NAME = "RangerUserStore"; - - private static Integer emptyValue; - - @InjectMocks - XUserMgr xUserMgr = new XUserMgr(); - - @Mock - XGroupService xGroupService; - - @Mock - RangerDaoManager daoManager; - - @Mock - RESTErrorUtil restErrorUtil; - - @Mock - XGroupUserService xGroupUserService; - - @Mock - StringUtil stringUtil; - - @Mock - RangerBizUtil msBizUtil; - - @Mock - UserMgr userMgr; - - @Mock - RangerBizUtil xaBizUtil; - - @Mock - XUserService xUserService; - - @Mock - XModuleDefService xModuleDefService; - - @Mock - XUserPermissionService xUserPermissionService; - - @Mock - XGroupPermissionService xGroupPermissionService; - - @Mock - ContextUtil contextUtil; - - @Mock - RangerSecurityContext rangerSecurityContext; - - @Mock - XPortalUserService xPortalUserService; - - @Mock - SessionMgr sessionMgr; - - @Mock - XPermMapService xPermMapService; - - @Mock - XAuditMapService xAuditMapService; - - @Mock - RangerPolicyService policyService; - - @Mock - ServiceDBStore svcStore; - - @Mock - GdsDBStore gdsStore; - - @Mock - XGroupGroupService xGroupGroupService; - - @Mock - XResourceService xResourceService; - - @Mock - XUgsyncAuditInfoService xUgsyncAuditInfoService; - - @Mock - RangerTransactionSynchronizationAdapter transactionSynchronizationAdapter; - - @Mock - XXGlobalStateDao xxGlobalStateDao; - - @Rule - public ExpectedException thrown = ExpectedException.none(); - - @Mock - @Qualifier(value = "transactionManager") - PlatformTransactionManager txManager; - - public void setup() { - RangerSecurityContext context = new RangerSecurityContext(); - context.setUserSession(new UserSessionBase()); - RangerContextHolder.setSecurityContext(context); - UserSessionBase currentUserSession = ContextUtil.getCurrentUserSession(); - currentUserSession.setUserAdmin(true); - XXPortalUser xXPortalUser = new XXPortalUser(); - xXPortalUser.setLoginId(adminLoginID); - xXPortalUser.setId(userId); - currentUserSession.setXXPortalUser(xXPortalUser); - Mockito.when(daoManager.getXXGlobalState()).thenReturn(xxGlobalStateDao); - } - - @After - public void destroySession() { - RangerSecurityContext context = new RangerSecurityContext(); - context.setUserSession(null); - RangerContextHolder.setSecurityContext(context); - } - - private VXUser vxUser() { - Collection userRoleList = new ArrayList(); - userRoleList.add("ROLE_USER"); - Collection groupNameList = new ArrayList(); - groupNameList.add(groupName); - VXUser vxUser = new VXUser(); - vxUser.setId(userId); - vxUser.setDescription("group test working"); - vxUser.setName(userLoginID); - vxUser.setUserRoleList(userRoleList); - vxUser.setGroupNameList(groupNameList); - vxUser.setPassword("Usertest123"); - vxUser.setEmailAddress("test@test.com"); - return vxUser; - } - - private VXUser vxUserFederated() { - Collection userRoleList = new ArrayList(); - userRoleList.add("ROLE_USER"); - Collection groupNameList = new ArrayList(); - groupNameList.add(groupName); - VXUser vxUser = new VXUser(); - vxUser.setId(userId); - vxUser.setDescription("group test working"); - vxUser.setName(userLoginID); - vxUser.setUserRoleList(userRoleList); - vxUser.setGroupNameList(groupNameList); - vxUser.setPassword(null); - vxUser.setEmailAddress("test@test.com"); - vxUser.setUserSource(RangerCommonEnums.USER_FEDERATED); - return vxUser; - } - - private XXUser xxUser(VXUser vxUser) { - XXUser xXUser = new XXUser(); - xXUser.setId(userId); - xXUser.setName(vxUser.getName()); - xXUser.setStatus(vxUser.getStatus()); - xXUser.setIsVisible(vxUser.getIsVisible()); - xXUser.setDescription(vxUser.getDescription()); - return xXUser; - } - - private VXGroup vxGroup() { - VXGroup vXGroup = new VXGroup(); - vXGroup.setId(userId); - vXGroup.setDescription("group test working"); - vXGroup.setName(groupName); - vXGroup.setIsVisible(1); - return vXGroup; - } - - private VXModuleDef vxModuleDef() { - VXUserPermission userPermission = vxUserPermission(); - List userPermList = new ArrayList(); - userPermList.add(userPermission); - VXGroupPermission groupPermission = vxGroupPermission(); - List groupPermList = new ArrayList(); - groupPermList.add(groupPermission); - VXModuleDef vxModuleDef = new VXModuleDef(); - vxModuleDef.setAddedById(userId); - vxModuleDef.setCreateDate(new Date()); - vxModuleDef.setCreateTime(new Date()); - vxModuleDef.setId(userId); - vxModuleDef.setModule("Policy manager"); - vxModuleDef.setOwner("admin"); - vxModuleDef.setUpdateDate(new Date()); - vxModuleDef.setUpdatedBy("admin"); - vxModuleDef.setUpdatedById(userId); - vxModuleDef.setUpdateTime(new Date()); - vxModuleDef.setUrl("/policy manager"); - vxModuleDef.setUserPermList(userPermList); - vxModuleDef.setGroupPermList(groupPermList); - return vxModuleDef; - } - - private VXUserPermission vxUserPermission() { - VXUserPermission userPermission = new VXUserPermission(); - userPermission.setId(1L); - userPermission.setIsAllowed(1); - userPermission.setModuleId(1L); - userPermission.setUserId(userId); - userPermission.setUserName(userLoginID); - userPermission.setOwner("admin"); - return userPermission; - } - - private VXGroupPermission vxGroupPermission() { - VXGroupPermission groupPermission = new VXGroupPermission(); - groupPermission.setId(1L); - groupPermission.setIsAllowed(1); - groupPermission.setModuleId(1L); - groupPermission.setGroupId(userId); - groupPermission.setGroupName(groupName); - groupPermission.setOwner("admin"); - return groupPermission; - } - - private VXPortalUser userProfile() { - VXPortalUser userProfile = new VXPortalUser(); - userProfile.setEmailAddress("test@test.com"); - userProfile.setFirstName("user12"); - userProfile.setLastName("test12"); - userProfile.setLoginId(userLoginID); - userProfile.setPassword("Usertest123"); - userProfile.setUserSource(1); - userProfile.setPublicScreenName("testuser"); - userProfile.setId(userId); - return userProfile; - } - - private XXPortalUser xxPortalUser(VXPortalUser userProfile) { - XXPortalUser xxPortalUser = new XXPortalUser(); - xxPortalUser.setEmailAddress(userProfile.getEmailAddress()); - xxPortalUser.setFirstName(userProfile.getFirstName()); - xxPortalUser.setLastName(userProfile.getLastName()); - xxPortalUser.setLoginId(userProfile.getLoginId()); - xxPortalUser.setPassword(userProfile.getPassword()); - xxPortalUser.setUserSource(userProfile.getUserSource()); - xxPortalUser.setPublicScreenName(userProfile.getPublicScreenName()); - return xxPortalUser; - } - - public void setupKeyAdmin() { - RangerSecurityContext context = new RangerSecurityContext(); - context.setUserSession(new UserSessionBase()); - RangerContextHolder.setSecurityContext(context); - UserSessionBase currentUserSession = ContextUtil.getCurrentUserSession(); - XXPortalUser userKeyAdmin = new XXPortalUser(); - userKeyAdmin.setId(userProfile().getId()); - userKeyAdmin.setLoginId(keyadminLoginID); - currentUserSession.setXXPortalUser(userKeyAdmin); - currentUserSession.setKeyAdmin(true); - } - - private List xxModuleDefs(){ - List xXModuleDefs=new ArrayList(); - XXModuleDef xXModuleDef1=xxModuleDef(); - XXModuleDef xXModuleDef2=xxModuleDef(); - XXModuleDef xXModuleDef3=xxModuleDef(); - XXModuleDef xXModuleDef4=xxModuleDef(); - XXModuleDef xXModuleDef5=xxModuleDef(); - xXModuleDef1.setId(1L); - xXModuleDef1.setModule("Resource Based Policies"); - xXModuleDef1.setId(2L); - xXModuleDef1.setModule("Users/Groups"); - xXModuleDef1.setId(3L); - xXModuleDef1.setModule("Reports"); - xXModuleDef1.setId(4L); - xXModuleDef1.setModule("Audit"); - xXModuleDef1.setId(5L); - xXModuleDef1.setModule("Key Manager"); - xXModuleDefs.add(xXModuleDef1); - xXModuleDefs.add(xXModuleDef2); - xXModuleDefs.add(xXModuleDef3); - xXModuleDefs.add(xXModuleDef4); - xXModuleDefs.add(xXModuleDef5); - return xXModuleDefs; - } - - private VXGroupUser vxGroupUser(){ - VXUser vXUser = vxUser(); - VXGroupUser vxGroupUser = new VXGroupUser(); - vxGroupUser.setId(userId); - vxGroupUser.setName(vXUser.getName()); - vxGroupUser.setOwner("Admin"); - vxGroupUser.setUserId(vXUser.getId()); - vxGroupUser.setUpdatedBy("User"); - vxGroupUser.setParentGroupId(userId); - return vxGroupUser; - } - - private XXGroupGroup xxGroupGroup(){ - XXGroupGroup xXGroupGroup = new XXGroupGroup(); - xXGroupGroup.setId(userId); - xXGroupGroup.setName("group user test"); - return xXGroupGroup; - } - - private XXPolicy getXXPolicy() { - XXPolicy xxPolicy = new XXPolicy(); - xxPolicy.setId(userId); - xxPolicy.setName("HDFS_1-1-20150316062453"); - xxPolicy.setAddedByUserId(userId); - xxPolicy.setCreateTime(new Date()); - xxPolicy.setDescription("test"); - xxPolicy.setIsAuditEnabled(false); - xxPolicy.setIsEnabled(false); - xxPolicy.setService(1L); - xxPolicy.setUpdatedByUserId(userId); - xxPolicy.setUpdateTime(new Date()); - return xxPolicy; - } - - private VXGroupUserList vxGroupUserList(){ - VXGroupUserList vxGroupUserList = new VXGroupUserList(); - List vXGroupUsers =new ArrayList(); - VXGroupUser vxGroupUser = vxGroupUser(); - vXGroupUsers.add(vxGroupUser); - vxGroupUserList.setVXGroupUsers(vXGroupUsers); - return vxGroupUserList; - } - - private ArrayList getRoleList() { - ArrayList userRoleList = new ArrayList(); - userRoleList.add("ROLE_USER"); - return userRoleList; - } - - private SearchCriteria createsearchCriteria(){ - SearchCriteria testsearchCriteria = new SearchCriteria(); - testsearchCriteria.setStartIndex(0); - testsearchCriteria.setMaxRows(Integer.MAX_VALUE); - testsearchCriteria.setSortBy("id"); - testsearchCriteria.setSortType("asc"); - testsearchCriteria.setGetCount(true); - testsearchCriteria.setOwnerId(null); - testsearchCriteria.setGetChildren(false); - testsearchCriteria.setDistinct(false); - return testsearchCriteria; - } - - private XXUserPermission xxUserPermission(){ - XXUserPermission xUserPermissionObj = new XXUserPermission(); - xUserPermissionObj.setAddedByUserId(userId); - xUserPermissionObj.setCreateTime(new Date()); - xUserPermissionObj.setId(userId); - xUserPermissionObj.setIsAllowed(1); - xUserPermissionObj.setModuleId(1L); - xUserPermissionObj.setUpdatedByUserId(userId); - xUserPermissionObj.setUpdateTime(new Date()); - xUserPermissionObj.setUserId(userId); - return xUserPermissionObj; - } - - private XXGroupPermission xxGroupPermission(){ - XXGroupPermission xGroupPermissionObj = new XXGroupPermission(); - xGroupPermissionObj.setAddedByUserId(userId); - xGroupPermissionObj.setCreateTime(new Date()); - xGroupPermissionObj.setId(userId); - xGroupPermissionObj.setIsAllowed(1); - xGroupPermissionObj.setModuleId(1L); - xGroupPermissionObj.setUpdatedByUserId(userId); - xGroupPermissionObj.setUpdateTime(new Date()); - xGroupPermissionObj.setGroupId(userId); - return xGroupPermissionObj; - } - - private XXModuleDef xxModuleDef(){ - XXModuleDef xModuleDef = new XXModuleDef(); - xModuleDef.setUpdatedByUserId(userId); - xModuleDef.setAddedByUserId(userId); - xModuleDef.setCreateTime(new Date()); - xModuleDef.setId(userId); - xModuleDef.setModule("Policy manager"); - xModuleDef.setUpdateTime(new Date()); - xModuleDef.setUrl("/policy manager"); - return xModuleDef; - } - - private VXPermMap getVXPermMap(){ - VXPermMap testVXPermMap= new VXPermMap(); - testVXPermMap.setCreateDate(new Date()); - testVXPermMap.setGroupId(userId); - testVXPermMap.setGroupName("testGroup"); - testVXPermMap.setId(userId); - testVXPermMap.setOwner("Admin"); - testVXPermMap.setPermGroup("testPermGroup"); - testVXPermMap.setPermType(1); - testVXPermMap.setResourceId(userId); - testVXPermMap.setUpdateDate(new Date()); - testVXPermMap.setUpdatedBy("Admin"); - testVXPermMap.setUserId(userId); - testVXPermMap.setUserName("testUser"); - testVXPermMap.setPermFor(1); - return testVXPermMap; - } - - private VXAuditMap getVXAuditMap() { - VXAuditMap testVXAuditMap=new VXAuditMap(); - testVXAuditMap.setAuditType(1); - testVXAuditMap.setCreateDate(new Date()); - testVXAuditMap.setGroupId(userId); - testVXAuditMap.setId(userId); - testVXAuditMap.setResourceId(userId); - testVXAuditMap.setUpdateDate(new Date()); - testVXAuditMap.setOwner("Admin"); - testVXAuditMap.setUpdatedBy("Admin"); - testVXAuditMap.setUserId(userId); - return testVXAuditMap; - } - - private RangerPolicy rangerPolicy() { - List accesses = new ArrayList(); - List users = new ArrayList(); - List groups = new ArrayList(); - List policyLabels = new ArrayList(); - List conditions = new ArrayList(); - List policyItems = new ArrayList(); - RangerPolicyItem rangerPolicyItem = new RangerPolicyItem(); - rangerPolicyItem.setAccesses(accesses); - rangerPolicyItem.setConditions(conditions); - rangerPolicyItem.setGroups(groups); - rangerPolicyItem.setUsers(users); - rangerPolicyItem.setDelegateAdmin(false); - - policyItems.add(rangerPolicyItem); - - Map policyResource = new HashMap(); - RangerPolicyResource rangerPolicyResource = new RangerPolicyResource(); - rangerPolicyResource.setIsExcludes(true); - rangerPolicyResource.setIsRecursive(true); - rangerPolicyResource.setValue("1"); - rangerPolicyResource.setValues(users); - RangerPolicy policy = new RangerPolicy(); - policy.setId(userId); - policy.setCreateTime(new Date()); - policy.setDescription("policy"); - policy.setGuid("policyguid"); - policy.setIsEnabled(true); - policy.setName("HDFS_1-1-20150316062453"); - policy.setUpdatedBy("Admin"); - policy.setUpdateTime(new Date()); - policy.setService("HDFS_1-1-20150316062453"); - policy.setIsAuditEnabled(true); - policy.setPolicyItems(policyItems); - policy.setResources(policyResource); - policy.setPolicyLabels(policyLabels); - policy.setServiceType("hdfs"); - return policy; - } - - public void setupUser() { - RangerSecurityContext context = new RangerSecurityContext(); - context.setUserSession(new UserSessionBase()); - RangerContextHolder.setSecurityContext(context); - UserSessionBase currentUserSession = ContextUtil.getCurrentUserSession(); - XXPortalUser user = new XXPortalUser(); - user.setId(userProfile().getId()); - user.setLoginId(userProfile().getLoginId()); - currentUserSession.setXXPortalUser(user); - currentUserSession.setUserRoleList(getRoleList()); - } - - @Test - public void test01CreateXUser() { - setup(); - VXUser vxUser = vxUser(); - vxUser.setFirstName("user12"); - vxUser.setLastName("test12"); - Collection groupIdList = new ArrayList(); - groupIdList.add(userId); - vxUser.setGroupIdList(groupIdList); - VXGroup vxGroup = vxGroup(); - vxGroup.setName("user12Grp"); - VXGroupUser vXGroupUser = new VXGroupUser(); - vXGroupUser.setParentGroupId(userId); - vXGroupUser.setUserId(userId); - vXGroupUser.setName(vxGroup.getName()); - Mockito.when(xGroupService.readResource(userId)).thenReturn(vxGroup); - Mockito.when(xGroupUserService.createResource((VXGroupUser) Mockito.any())).thenReturn(vXGroupUser); - ArrayList userRoleListVXPortaUser = getRoleList(); - VXPortalUser vXPortalUser = new VXPortalUser(); - vXPortalUser.setUserRoleList(userRoleListVXPortaUser); - Mockito.when(xUserService.createResource(vxUser)).thenReturn(vxUser); - XXModuleDefDao value = Mockito.mock(XXModuleDefDao.class); - Mockito.when(daoManager.getXXModuleDef()).thenReturn(value); - Mockito.when(userMgr.createDefaultAccountUser((VXPortalUser) Mockito.any())).thenReturn(vXPortalUser); - Mockito.when(stringUtil.validateEmail("test@test.com")).thenReturn(true); - VXUser dbUser = xUserMgr.createXUser(vxUser); - Assert.assertNotNull(dbUser); - userId = dbUser.getId(); - Assert.assertEquals(userId, dbUser.getId()); - Assert.assertEquals(dbUser.getDescription(), vxUser.getDescription()); - Assert.assertEquals(dbUser.getName(), vxUser.getName()); - Assert.assertEquals(dbUser.getUserRoleList(), vxUser.getUserRoleList()); - Assert.assertEquals(dbUser.getGroupNameList(), - vxUser.getGroupNameList()); - Mockito.verify(xUserService).createResource(vxUser); - Mockito.when(xUserService.readResourceWithOutLogin(userId)).thenReturn(vxUser); - - VXUser loggedInUser = vxUser(); - List loggedInUserRole = new ArrayList(); - loggedInUserRole.add(RangerConstants.ROLE_ADMIN); - loggedInUser.setId(8L); - loggedInUser.setName("testuser"); - loggedInUser.setUserRoleList(loggedInUserRole); - Mockito.when(xUserService.getXUserByUserName("admin")).thenReturn(loggedInUser); - Mockito.when(restErrorUtil.createRESTException(HttpServletResponse.SC_FORBIDDEN, "Logged-In user is not allowed to access requested user data", true)).thenThrow(new WebApplicationException()); - thrown.expect(WebApplicationException.class); - VXUser dbvxUser = xUserMgr.getXUser(userId); - Mockito.verify(userMgr).createDefaultAccountUser((VXPortalUser) Mockito.any()); - Assert.assertNotNull(dbvxUser); - Assert.assertEquals(userId, dbvxUser.getId()); - Assert.assertEquals(dbvxUser.getDescription(), vxUser.getDescription()); - Assert.assertEquals(dbvxUser.getName(), vxUser.getName()); - Assert.assertEquals(dbvxUser.getUserRoleList(),vxUser.getUserRoleList()); - Assert.assertEquals(dbvxUser.getGroupIdList(),vxUser.getGroupIdList()); - Assert.assertEquals(dbvxUser.getGroupNameList(),vxUser.getGroupNameList()); - Mockito.verify(xUserService).readResourceWithOutLogin(userId); - } - - @Test - public void test02CreateXUser_WithBlankName() { - setup(); - VXUser vxUser = vxUser(); - ArrayList userRoleListVXPortaUser = getRoleList(); - VXPortalUser vXPortalUser = new VXPortalUser(); - vXPortalUser.setUserRoleList(userRoleListVXPortaUser); - vxUser.setName(null); - Mockito.when(restErrorUtil.createRESTException("Please provide a valid username.",MessageEnums.INVALID_INPUT_DATA)).thenThrow(new WebApplicationException()); - thrown.expect(WebApplicationException.class); - xUserMgr.createXUser(vxUser); - } - - @Test - public void test03CreateXUser_WithBlankName() { - destroySession(); - setup(); - VXUser vxUser = vxUser(); - ArrayList userRoleListVXPortaUser = getRoleList(); - VXPortalUser vXPortalUser = new VXPortalUser(); - vXPortalUser.setUserRoleList(userRoleListVXPortaUser); - vxUser.setName(""); - Mockito.when(restErrorUtil.createRESTException("Please provide a valid username.",MessageEnums.INVALID_INPUT_DATA)).thenThrow(new WebApplicationException()); - thrown.expect(WebApplicationException.class); - xUserMgr.createXUser(vxUser); - } - - @Test - public void testCreateXUser_WithBlankFirstName() { - destroySession(); - setup(); - VXUser vxUser = vxUser(); - vxUser.setName("test"); - vxUser.setFirstName(null); - Mockito.when(restErrorUtil.createRESTException("Please provide a valid first name.",MessageEnums.INVALID_INPUT_DATA)).thenThrow(new WebApplicationException()); - thrown.expect(WebApplicationException.class); - xUserMgr.createXUser(vxUser); - } - - @Test - public void test04CreateXUser_WithBlankValues() { - destroySession(); - setup(); - VXUser vxUser = vxUser(); - vxUser.setDescription(null); - vxUser.setFirstName("test"); - vxUser.setLastName("null"); - Mockito.when(restErrorUtil.createRESTException("Please provide valid email address.",MessageEnums.INVALID_INPUT_DATA)).thenThrow(new WebApplicationException()); - thrown.expect(WebApplicationException.class); - xUserMgr.createXUser(vxUser); - } - - @Test - public void testUpdateXUser_WithBlankFirstName() { - setup(); - VXUser vxUser = vxUser(); - ArrayList userRoleListVXPortaUser = getRoleList(); - VXPortalUser vXPortalUser = new VXPortalUser(); - vXPortalUser.setUserRoleList(userRoleListVXPortaUser); - vxUser.setDescription(null); - vxUser.setFirstName("null"); - Mockito.when(restErrorUtil.createRESTException("Please provide a valid first name.",MessageEnums.INVALID_INPUT_DATA)).thenThrow(new WebApplicationException()); - thrown.expect(WebApplicationException.class); - xUserMgr.updateXUser(vxUser); - } - - @Test - public void testUpdateXUser_WithBlankUserName() { - setup(); - VXUser vxUser = vxUser(); - ArrayList userRoleListVXPortaUser = getRoleList(); - VXPortalUser vXPortalUser = new VXPortalUser(); - vXPortalUser.setUserRoleList(userRoleListVXPortaUser); - vxUser.setDescription(null); - vxUser.setName("null"); - Mockito.when(restErrorUtil.createRESTException("Please provide a valid username.",MessageEnums.INVALID_INPUT_DATA)).thenThrow(new WebApplicationException()); - thrown.expect(WebApplicationException.class); - xUserMgr.updateXUser(vxUser); - } - - @Test - public void test05UpdateXUser() { - setup(); - XXUserPermissionDao xUserPermissionDao = Mockito.mock(XXUserPermissionDao.class); - Collection existingRoleList = new ArrayList(); - existingRoleList.add(RangerConstants.ROLE_USER); - Collection reqRoleList = new ArrayList(); - reqRoleList.add(RangerConstants.ROLE_SYS_ADMIN); - Collection groupIdList = new ArrayList(); - groupIdList.add(userId); - VXUser vxUser = vxUser(); - vxUser.setUserRoleList(reqRoleList); - vxUser.setUserSource(RangerCommonEnums.USER_EXTERNAL); - vxUser.setGroupIdList(groupIdList); - vxUser.setFirstName("user12"); - vxUser.setLastName("test12"); - Mockito.when(xUserService.updateResource(vxUser)).thenReturn(vxUser); - XXModuleDefDao xModuleDefDao = Mockito.mock(XXModuleDefDao.class); - VXPortalUser vXPortalUser = userProfile(); - vXPortalUser.setUserRoleList(existingRoleList); - Mockito.when(userMgr.getUserProfileByLoginId(vxUser.getName())).thenReturn(vXPortalUser); - Mockito.when(daoManager.getXXUserPermission()).thenReturn(xUserPermissionDao); - List xUserPermissionsList = new ArrayList(); - XXUserPermission xUserPermissionObj = new XXUserPermission(); - xUserPermissionObj.setAddedByUserId(userId); - xUserPermissionObj.setCreateTime(new Date()); - xUserPermissionObj.setId(userId); - xUserPermissionObj.setIsAllowed(1); - xUserPermissionObj.setModuleId(1L); - xUserPermissionObj.setUpdatedByUserId(userId); - xUserPermissionObj.setUpdateTime(new Date()); - xUserPermissionObj.setUserId(userId); - xUserPermissionsList.add(xUserPermissionObj); - List xXModuleDefs = xxModuleDefs(); - Mockito.when(xUserPermissionDao.findByUserPermissionId(vXPortalUser.getId())).thenReturn(xUserPermissionsList); - Mockito.when(daoManager.getXXModuleDef()).thenReturn(xModuleDefDao); - Mockito.when(xModuleDefDao.getAll()).thenReturn(xXModuleDefs); - XXUser xXUser = xxUser(vxUser); - XXUserDao xxUserDao = Mockito.mock(XXUserDao.class); - Mockito.when(daoManager.getXXUser()).thenReturn(xxUserDao); - Mockito.when(xxUserDao.findByPortalUserId(vXPortalUser.getId())).thenReturn(xXUser); - VXGroupUserList vxGroupUserList = vxGroupUserList(); - Mockito.when(xGroupUserService.searchXGroupUsers((SearchCriteria) Mockito.any())).thenReturn(vxGroupUserList); - UserSessionBase userSession = Mockito.mock(UserSessionBase.class); - Set userSessions = new HashSet(); - userSessions.add(userSession); - VXUserPermission vXUserPermission = vxUserPermission(); - Mockito.when(xUserPermissionService.createResource((VXUserPermission) Mockito.any())).thenReturn(vXUserPermission); - Mockito.when(sessionMgr.getActiveUserSessionsForPortalUserId(userId)).thenReturn(userSessions); - VXUser loggedInUser = vxUser(); - List loggedInUserRole = new ArrayList(); - loggedInUserRole.add(RangerConstants.ROLE_SYS_ADMIN); - loggedInUser.setId(8L); - loggedInUser.setName("testuser"); - loggedInUser.setUserRoleList(loggedInUserRole); - Mockito.when(xUserService.getXUserByUserName("admin")).thenReturn(loggedInUser); - VXUser dbvxUser = xUserMgr.updateXUser(vxUser); - Assert.assertNotNull(dbvxUser); - Assert.assertEquals(dbvxUser.getId(), vxUser.getId()); - Assert.assertEquals(dbvxUser.getDescription(), vxUser.getDescription()); - Assert.assertEquals(dbvxUser.getName(), vxUser.getName()); - Mockito.verify(xUserService).updateResource(vxUser); - groupIdList.clear(); - groupIdList.add(9L); - vxUser.setGroupIdList(groupIdList); - VXGroup vXGroup = vxGroup(); - Mockito.when(xGroupService.readResource(Mockito.anyLong())).thenReturn(vXGroup); - VXGroupUser vXGroupUser = vxGroupUser(); - Mockito.when(xGroupUserService.createResource((VXGroupUser) Mockito.any())).thenReturn(vXGroupUser); - dbvxUser = xUserMgr.updateXUser(vxUser); - Assert.assertNotNull(dbvxUser); - } - - @Test - public void test06ModifyUserVisibilitySetOne() { - setup(); - XXUserDao xxUserDao = Mockito.mock(XXUserDao.class); - XXUser xxUser = Mockito.mock(XXUser.class); - VXUser vxUser = vxUser(); - Mockito.when(xUserService.updateResource(vxUser)).thenReturn(vxUser); - HashMap visibilityMap = new HashMap(); - Integer value = 1; - visibilityMap.put(userId, value); - Mockito.when(daoManager.getXXUser()).thenReturn(xxUserDao); - Mockito.when(xxUserDao.getById(userId)).thenReturn(xxUser); - Mockito.when(xUserService.populateViewBean(xxUser)).thenReturn(vxUser); - xUserMgr.modifyUserVisibility(visibilityMap); - Assert.assertEquals(value, vxUser.getIsVisible()); - Assert.assertEquals(userId, vxUser.getId()); - Mockito.verify(xUserService).updateResource(vxUser); - Mockito.verify(daoManager).getXXUser(); - Mockito.verify(xUserService).populateViewBean(xxUser); - } - - @Test - public void test07ModifyUserVisibilitySetZero() { - setup(); - XXUserDao xxUserDao = Mockito.mock(XXUserDao.class); - XXUser xxUser = Mockito.mock(XXUser.class); - VXUser vxUser = vxUser(); - Mockito.when(xUserService.updateResource(vxUser)).thenReturn(vxUser); - HashMap visibilityMap = new HashMap(); - Integer value = 0; - visibilityMap.put(userId, value); - Mockito.when(daoManager.getXXUser()).thenReturn(xxUserDao); - Mockito.when(xxUserDao.getById(userId)).thenReturn(xxUser); - Mockito.when(xUserService.populateViewBean(xxUser)).thenReturn(vxUser); - xUserMgr.modifyUserVisibility(visibilityMap); - Assert.assertEquals(value, vxUser.getIsVisible()); - Assert.assertEquals(userId, vxUser.getId()); - Mockito.verify(xUserService).updateResource(vxUser); - Mockito.verify(daoManager).getXXUser(); - Mockito.verify(xUserService).populateViewBean(xxUser); - } - - @Test - public void test08ModifyUserVisibilitySetEmpty() { - setup(); - XXUserDao xxUserDao = Mockito.mock(XXUserDao.class); - XXUser xxUser = Mockito.mock(XXUser.class); - VXUser vxUser = vxUser(); - Mockito.when(xUserService.updateResource(vxUser)).thenReturn(vxUser); - HashMap visibilityMap = new HashMap(); - visibilityMap.put(userId, emptyValue); - Mockito.when(daoManager.getXXUser()).thenReturn(xxUserDao); - Mockito.when(xxUserDao.getById(userId)).thenReturn(xxUser); - Mockito.when(xUserService.populateViewBean(xxUser)).thenReturn(vxUser); - xUserMgr.modifyUserVisibility(visibilityMap); - Assert.assertEquals(emptyValue, vxUser.getIsVisible()); - Assert.assertEquals(userId, vxUser.getId()); - Mockito.verify(xUserService).updateResource(vxUser); - Mockito.verify(daoManager).getXXUser(); - Mockito.verify(xUserService).populateViewBean(xxUser); - } - - @Test - public void test09CreateXGroup() { - setup(); - VXGroup vXGroup = vxGroup(); - vXGroup.setDescription(null); - Mockito.when(xGroupService.createResource(vXGroup)).thenReturn(vXGroup); - VXGroup dbXGroup = xUserMgr.createXGroup(vXGroup); - Assert.assertNotNull(dbXGroup); - userId = dbXGroup.getId(); - Assert.assertEquals(userId, dbXGroup.getId()); - Assert.assertEquals(vXGroup.getName(), dbXGroup.getName()); - Mockito.verify(xGroupService).createResource(vXGroup); - Mockito.when(xGroupService.readResourceWithOutLogin(userId)).thenReturn(vXGroup); - VXGroup dbxGroup = xUserMgr.getXGroup(userId); - Assert.assertNotNull(dbXGroup); - Assert.assertEquals(userId, dbxGroup.getId()); - Assert.assertEquals(dbXGroup.getName(), dbxGroup.getName()); - Mockito.verify(xGroupService).readResourceWithOutLogin(userId); - } - - @Test - public void test10UpdateXGroup() { - XXGroupDao xxGroupDao = Mockito.mock(XXGroupDao.class); - XXGroupUserDao xxGroupUserDao = Mockito.mock(XXGroupUserDao.class); - List grpUsers =new ArrayList(); - setup(); - VXGroup vXGroup = vxGroup(); - XXGroup xxGroup = new XXGroup(); - xxGroup.setName(groupName); - Mockito.when(daoManager.getXXGroup()).thenReturn(xxGroupDao); - Mockito.when(xxGroupDao.getById(vXGroup.getId())).thenReturn(xxGroup); - Mockito.when(xGroupService.updateResource(vXGroup)).thenReturn(vXGroup); - Mockito.when(daoManager.getXXGroupUser()).thenReturn(xxGroupUserDao); - Mockito.when(xxGroupUserDao.findByGroupId(vXGroup.getId())).thenReturn(grpUsers); - VXGroup dbvxGroup = xUserMgr.updateXGroup(vXGroup); - Assert.assertNotNull(dbvxGroup); - userId = dbvxGroup.getId(); - Assert.assertEquals(userId, dbvxGroup.getId()); - Assert.assertEquals(vXGroup.getDescription(),dbvxGroup.getDescription()); - Assert.assertEquals(vXGroup.getName(), dbvxGroup.getName()); - Mockito.verify(daoManager).getXXGroup(); - Mockito.verify(daoManager).getXXGroupUser(); - Mockito.verify(xGroupService).updateResource(vXGroup); - Mockito.verify(xxGroupUserDao).findByGroupId(vXGroup.getId()); - Mockito.when(restErrorUtil.createRESTException("group name updates are not allowed.",MessageEnums.INVALID_INPUT_DATA)).thenThrow(new WebApplicationException()); - thrown.expect(WebApplicationException.class); - vXGroup.setName("UnknownGroup"); - xUserMgr.updateXGroup(vXGroup); - } - - @Test - public void test11ModifyGroupsVisibilitySetOne() { - setup(); - XXGroupDao xxGroupDao = Mockito.mock(XXGroupDao.class); - VXGroup vXGroup = vxGroup(); - XXGroup xxGroup = new XXGroup(); - HashMap groupVisibilityMap = new HashMap(); - Integer value = 1; - groupVisibilityMap.put(userId, value); - Mockito.when(daoManager.getXXGroup()).thenReturn(xxGroupDao); - Mockito.when(xxGroupDao.getById(vXGroup.getId())).thenReturn(xxGroup); - Mockito.when(xGroupService.populateViewBean(xxGroup)).thenReturn(vXGroup); - Mockito.when(xGroupService.updateResource(vXGroup)).thenReturn(vXGroup); - xUserMgr.modifyGroupsVisibility(groupVisibilityMap); - Assert.assertEquals(value, vXGroup.getIsVisible()); - Assert.assertEquals(userId, vXGroup.getId()); - Mockito.verify(daoManager).getXXGroup(); - Mockito.verify(xGroupService).populateViewBean(xxGroup); - Mockito.verify(xGroupService).updateResource(vXGroup); - } - - @Test - public void test12ModifyGroupsVisibilitySetZero() { - setup(); - XXGroupDao xxGroupDao = Mockito.mock(XXGroupDao.class); - VXGroup vXGroup = vxGroup(); - XXGroup xxGroup = new XXGroup(); - HashMap groupVisibilityMap = new HashMap(); - Integer value = 0; - groupVisibilityMap.put(userId, value); - Mockito.when(daoManager.getXXGroup()).thenReturn(xxGroupDao); - Mockito.when(xxGroupDao.getById(vXGroup.getId())).thenReturn(xxGroup); - Mockito.when(xGroupService.populateViewBean(xxGroup)).thenReturn(vXGroup); - Mockito.when(xGroupService.updateResource(vXGroup)).thenReturn(vXGroup); - xUserMgr.modifyGroupsVisibility(groupVisibilityMap); - Assert.assertEquals(value, vXGroup.getIsVisible()); - Assert.assertEquals(userId, vXGroup.getId()); - Mockito.verify(daoManager).getXXGroup(); - Mockito.verify(xGroupService).populateViewBean(xxGroup); - Mockito.verify(xGroupService).updateResource(vXGroup); - } - - @Test - public void test13ModifyGroupsVisibilitySetEmpty() { - setup(); - XXGroupDao xxGroupDao = Mockito.mock(XXGroupDao.class); - VXGroup vXGroup = vxGroup(); - XXGroup xxGroup = new XXGroup(); - HashMap groupVisibilityMap = new HashMap(); - groupVisibilityMap.put(userId, emptyValue); - Mockito.when(daoManager.getXXGroup()).thenReturn(xxGroupDao); - Mockito.when(xxGroupDao.getById(vXGroup.getId())).thenReturn(xxGroup); - Mockito.when(xGroupService.populateViewBean(xxGroup)).thenReturn(vXGroup); - Mockito.when(xGroupService.updateResource(vXGroup)).thenReturn(vXGroup); - xUserMgr.modifyGroupsVisibility(groupVisibilityMap); - Assert.assertEquals(emptyValue, vXGroup.getIsVisible()); - Assert.assertEquals(userId, vXGroup.getId()); - Mockito.verify(daoManager).getXXGroup(); - Mockito.verify(xGroupService).populateViewBean(xxGroup); - Mockito.verify(xGroupService).updateResource(vXGroup); - } - - @Test - public void test14createXGroupUser() { - setup(); - VXGroupUser vxGroupUser = vxGroupUser(); - Mockito.when(xGroupUserService.createXGroupUserWithOutLogin(vxGroupUser)).thenReturn(vxGroupUser); - VXGroupUser dbVXGroupUser = xUserMgr.createXGroupUser(vxGroupUser); - Assert.assertNotNull(dbVXGroupUser); - userId = dbVXGroupUser.getId(); - Assert.assertEquals(userId, dbVXGroupUser.getId()); - Assert.assertEquals(dbVXGroupUser.getOwner(), vxGroupUser.getOwner()); - Assert.assertEquals(dbVXGroupUser.getName(), vxGroupUser.getName()); - Assert.assertEquals(dbVXGroupUser.getUserId(), vxGroupUser.getUserId()); - Assert.assertEquals(dbVXGroupUser.getUpdatedBy(),vxGroupUser.getUpdatedBy()); - Mockito.verify(xGroupUserService).createXGroupUserWithOutLogin(vxGroupUser); - Mockito.when(xGroupUserService.readResourceWithOutLogin(userId)).thenReturn(vxGroupUser); - VXGroupUser dbvxGroupUser = xUserMgr.getXGroupUser(userId); - Assert.assertNotNull(dbvxGroupUser); - userId = dbvxGroupUser.getId(); - Assert.assertEquals(userId, dbvxGroupUser.getId()); - Assert.assertEquals(dbvxGroupUser.getOwner(), vxGroupUser.getOwner()); - Assert.assertEquals(dbvxGroupUser.getName(), vxGroupUser.getName()); - Assert.assertEquals(dbvxGroupUser.getUserId(), vxGroupUser.getUserId()); - Assert.assertEquals(dbvxGroupUser.getUpdatedBy(),vxGroupUser.getUpdatedBy()); - Mockito.verify(xGroupUserService).readResourceWithOutLogin(userId); - } - - @Test - public void test15GetXUserGroups() { - List vXGroupList = new ArrayList(); - final VXGroup vXGroup1 = vxGroup(); - vXGroup1.setName("users"); - vXGroup1.setDescription("users -added for unit testing"); - vXGroupList.add(vXGroup1); - SearchCriteria testSearchCriteria = createsearchCriteria(); - testSearchCriteria.addParam("xUserId", userId); - VXGroupUserList vxGroupUserList = vxGroupUserList(); - Mockito.when(xGroupUserService.searchXGroupUsers((SearchCriteria) Mockito.any())).thenReturn(vxGroupUserList); - VXGroupList dbVXGroupList = xUserMgr.getXUserGroups(userId); - Assert.assertNotNull(dbVXGroupList); - } - - @Test - public void test16GetXGroupUsers() { - SearchCriteria testSearchCriteria = createsearchCriteria(); - testSearchCriteria.addParam("xGroupId", userId); - VXGroupUserList vxGroupUserList = vxGroupUserList(); - Mockito.when(xGroupUserService.searchXGroupUsers((SearchCriteria) Mockito.any())).thenReturn(vxGroupUserList); - Mockito.when(msBizUtil.hasModuleAccess(RangerConstants.MODULE_USER_GROUPS)).thenReturn(true); - VXUserList dbVXUserList = xUserMgr.getXGroupUsers(testSearchCriteria); - Assert.assertNotNull(dbVXUserList); - Mockito.when(msBizUtil.hasModuleAccess(Mockito.anyString())).thenReturn(false); - Mockito.when(restErrorUtil.createRESTException(HttpServletResponse.SC_FORBIDDEN, "User is not having permissions on the "+RangerConstants.MODULE_USER_GROUPS+" module.", true)).thenThrow(new WebApplicationException()); - thrown.expect(WebApplicationException.class); - xUserMgr.getXGroupUsers(testSearchCriteria); - } - - @Test - public void test17GetXUserByUserName() { - setupUser(); - VXUser vxUser = vxUser(); - Mockito.when(xUserService.getXUserByUserName(vxUser.getName())).thenReturn(vxUser); - XXModuleDefDao xxModuleDefDao = Mockito.mock(XXModuleDefDao.class); - Mockito.when(daoManager.getXXModuleDef()).thenReturn(xxModuleDefDao); - VXUser dbVXUser = xUserMgr.getXUserByUserName(vxUser.getName()); - Assert.assertNotNull(dbVXUser); - userId = dbVXUser.getId(); - Assert.assertEquals(userId, dbVXUser.getId()); - Assert.assertEquals(dbVXUser.getName(), vxUser.getName()); - Assert.assertEquals(dbVXUser.getOwner(), vxUser.getOwner()); - Mockito.verify(xUserService, Mockito.atLeast(2)).getXUserByUserName(vxUser.getName()); - } - - @Test - public void test18CreateXUserWithOutLogin() { - setup(); - VXUser vxUser = vxUser(); - Mockito.when(xUserService.createXUserWithOutLogin(vxUser)).thenReturn(vxUser); - VXUser dbUser = xUserMgr.createXUserWithOutLogin(vxUser); - Assert.assertNotNull(dbUser); - userId = dbUser.getId(); - Assert.assertEquals(userId, dbUser.getId()); - Assert.assertEquals(dbUser.getDescription(), vxUser.getDescription()); - Assert.assertEquals(dbUser.getName(), vxUser.getName()); - Assert.assertEquals(dbUser.getUserRoleList(), vxUser.getUserRoleList()); - Assert.assertEquals(dbUser.getGroupNameList(),vxUser.getGroupNameList()); - Mockito.verify(xUserService).createXUserWithOutLogin(vxUser); - } - - @Test - public void test19CreateXGroupWithoutLogin() { - setup(); - VXGroup vXGroup = vxGroup(); - Mockito.when(xGroupService.createXGroupWithOutLogin(vXGroup)).thenReturn(vXGroup); - VXGroup dbVXGroup = xUserMgr.createXGroupWithoutLogin(vXGroup); - Assert.assertNotNull(dbVXGroup); - userId = dbVXGroup.getId(); - Assert.assertEquals(userId, dbVXGroup.getId()); - Assert.assertEquals(vXGroup.getDescription(),dbVXGroup.getDescription()); - Assert.assertEquals(vXGroup.getName(), dbVXGroup.getName()); - Mockito.verify(xGroupService).createXGroupWithOutLogin(vXGroup); - } - - @Test - public void test20DeleteXGroup() { - setup(); - boolean force = true; - VXGroup vXGroup = vxGroup(); - XXGroupDao xXGroupDao = Mockito.mock(XXGroupDao.class); - XXUserDao xXUserDao = Mockito.mock(XXUserDao.class); - VXUser vxUser=vxUser(); - XXUser xXUser = xxUser(vxUser); - Mockito.when(daoManager.getXXUser()).thenReturn(xXUserDao); - Mockito.when(xXUserDao.getById(xXUser.getId())).thenReturn(xXUser); - XXGroup xXGroup = new XXGroup(); - Mockito.when(daoManager.getXXGroup()).thenReturn(xXGroupDao); - Mockito.when(xXGroupDao.getById(vXGroup.getId())).thenReturn(xXGroup); - Mockito.when(xGroupService.populateViewBean(xXGroup)).thenReturn(vXGroup); - VXGroupUserList vxGroupUserList = vxGroupUserList(); - XXGroupUserDao xGroupUserDao = Mockito.mock(XXGroupUserDao.class); - Mockito.when(xGroupUserService.searchXGroupUsers((SearchCriteria) Mockito.any())).thenReturn(vxGroupUserList); - Mockito.when(daoManager.getXXGroupUser()).thenReturn(xGroupUserDao); - VXPermMapList vXPermMapList = new VXPermMapList(); - VXPermMap vXPermMap1=getVXPermMap(); - List vXPermMaps=new ArrayList(); - vXPermMaps.add(vXPermMap1); - vXPermMapList.setVXPermMaps(vXPermMaps); - XXPermMapDao xXPermMapDao = Mockito.mock(XXPermMapDao.class); - Mockito.when(xPermMapService.searchXPermMaps((SearchCriteria) Mockito.any())).thenReturn(vXPermMapList); - Mockito.when(daoManager.getXXPermMap()).thenReturn(xXPermMapDao); - VXAuditMapList vXAuditMapList = new VXAuditMapList(); - List vXAuditMaps=new ArrayList(); - VXAuditMap vXAuditMap=getVXAuditMap(); - vXAuditMaps.add(vXAuditMap); - vXAuditMapList.setVXAuditMaps(vXAuditMaps); - XXAuditMapDao xXAuditMapDao = Mockito.mock(XXAuditMapDao.class); - Mockito.when(xAuditMapService.searchXAuditMaps((SearchCriteria) Mockito.any())).thenReturn(vXAuditMapList); - Mockito.when(daoManager.getXXAuditMap()).thenReturn(xXAuditMapDao); - XXGroupGroupDao xXGroupGroupDao = Mockito.mock(XXGroupGroupDao.class); - List xXGroupGroups = new ArrayList(); - XXGroupGroup xXGroupGroup = xxGroupGroup(); - xXGroupGroups.add(xXGroupGroup); - XXGroupPermissionDao xXGroupPermissionDao= Mockito.mock(XXGroupPermissionDao.class); - Mockito.when(daoManager.getXXGroupPermission()).thenReturn(xXGroupPermissionDao); - List xXGroupPermissions=new ArrayList(); - XXGroupPermission xGroupPermissionObj = xxGroupPermission(); - xXGroupPermissions.add(xGroupPermissionObj); - Mockito.when(xXGroupPermissionDao.findByGroupId(vXGroup.getId())).thenReturn(xXGroupPermissions); - XXPolicyDao xXPolicyDao = Mockito.mock(XXPolicyDao.class); - List xXPolicyList = new ArrayList(); - XXPolicy xXPolicy=getXXPolicy(); - xXPolicyList.add(xXPolicy); - Mockito.when(daoManager.getXXPolicy()).thenReturn(xXPolicyDao); - Mockito.when(xXPolicyDao.findByGroupId(userId)).thenReturn(xXPolicyList); - List xResourceList = new ArrayList(); - XXResource xXResource = new XXResource(); - xXResource.setId(userId); - xXResource.setName("hadoopdev"); - xXResource.setIsRecursive(AppConstants.BOOL_TRUE); - xXResource.setResourceStatus(AppConstants.STATUS_ENABLED); - xResourceList.add(xXResource); - XXResourceDao xxResourceDao = Mockito.mock(XXResourceDao.class); - Mockito.when(daoManager.getXXResource()).thenReturn(xxResourceDao); - Mockito.when(xxResourceDao.getById(Mockito.anyLong())).thenReturn(xXResource); - RangerPolicy rangerPolicy=rangerPolicy(); - Mockito.when(policyService.getPopulatedViewObject(xXPolicy)).thenReturn(rangerPolicy); - XXModuleDefDao xModuleDefDao = Mockito.mock(XXModuleDefDao.class); - Mockito.when(daoManager.getXXModuleDef()).thenReturn(xModuleDefDao); - XXModuleDef xModuleDef=xxModuleDef(); - Mockito.when(xModuleDefDao.findByModuleId(Mockito.anyLong())).thenReturn(xModuleDef); - List zoneSecRefGroup=new ArrayList(); - XXSecurityZoneRefGroupDao zoneSecRefGroupDao=Mockito.mock(XXSecurityZoneRefGroupDao.class); - Mockito.when(daoManager.getXXSecurityZoneRefGroup()).thenReturn(zoneSecRefGroupDao); - Mockito.when(zoneSecRefGroupDao.findByGroupId(userId)).thenReturn(zoneSecRefGroup); - List roleRefGroup = new ArrayList(); - XXRoleRefGroupDao roleRefGroupDao = Mockito.mock(XXRoleRefGroupDao.class); - Mockito.when(daoManager.getXXRoleRefGroup()).thenReturn(roleRefGroupDao); - Mockito.when(roleRefGroupDao.findByGroupId(userId)).thenReturn(roleRefGroup); - xUserMgr.deleteXGroup(vXGroup.getId(), force); - } - - @Test - public void test21DeleteXUser() { - setup(); - boolean force = true; - VXUser vXUser = vxUser(); - XXUser xXUser = new XXUser(); - XXUserDao xXUserDao = Mockito.mock(XXUserDao.class); - Mockito.when(daoManager.getXXUser()).thenReturn(xXUserDao); - Mockito.when(xXUserDao.getById(vXUser.getId())).thenReturn(xXUser); - Mockito.when(xUserService.populateViewBean(xXUser)).thenReturn(vXUser); - VXGroupUserList vxGroupUserList=vxGroupUserList(); - XXGroupUserDao xGroupUserDao = Mockito.mock(XXGroupUserDao.class); - Mockito.when(xGroupUserService.searchXGroupUsers((SearchCriteria) Mockito.any())).thenReturn(vxGroupUserList); - Mockito.when(daoManager.getXXGroupUser()).thenReturn(xGroupUserDao); - VXPermMapList vXPermMapList = new VXPermMapList(); - VXPermMap vXPermMap1=getVXPermMap(); - List vXPermMaps=new ArrayList(); - vXPermMaps.add(vXPermMap1); - vXPermMapList.setVXPermMaps(vXPermMaps); - XXPermMapDao xXPermMapDao = Mockito.mock(XXPermMapDao.class); - Mockito.when(xPermMapService.searchXPermMaps((SearchCriteria) Mockito.any())).thenReturn(vXPermMapList); - Mockito.when(daoManager.getXXPermMap()).thenReturn(xXPermMapDao); - VXAuditMapList vXAuditMapList = new VXAuditMapList(); - List vXAuditMaps=new ArrayList(); - VXAuditMap vXAuditMap=getVXAuditMap(); - vXAuditMaps.add(vXAuditMap); - vXAuditMapList.setVXAuditMaps(vXAuditMaps); - XXAuditMapDao xXAuditMapDao = Mockito.mock(XXAuditMapDao.class); - Mockito.when(xAuditMapService.searchXAuditMaps((SearchCriteria) Mockito.any())).thenReturn(vXAuditMapList); - Mockito.when(daoManager.getXXAuditMap()).thenReturn(xXAuditMapDao); - VXPortalUser vXPortalUser = userProfile(); - XXPortalUser xXPortalUser = xxPortalUser(vXPortalUser); - XXPortalUserDao xXPortalUserDao = Mockito.mock(XXPortalUserDao.class); - Mockito.when(daoManager.getXXPortalUser()).thenReturn(xXPortalUserDao); - Mockito.when(xXPortalUserDao.findByLoginId(vXUser.getName().trim())).thenReturn(xXPortalUser); - Mockito.when(xPortalUserService.populateViewBean(xXPortalUser)).thenReturn(vXPortalUser); - XXPortalUserRole XXPortalUserRole = new XXPortalUserRole(); - XXPortalUserRole.setId(userId); - XXPortalUserRole.setUserId(userId); - XXPortalUserRole.setUserRole("ROLE_USER"); - XXModuleDefDao xModuleDefDao = Mockito.mock(XXModuleDefDao.class); - Mockito.when(daoManager.getXXModuleDef()).thenReturn(xModuleDefDao); - XXModuleDef xModuleDef=xxModuleDef(); - Mockito.when(xModuleDefDao.findByModuleId(Mockito.anyLong())).thenReturn(xModuleDef); - XXAuthSessionDao xXAuthSessionDao= Mockito.mock(XXAuthSessionDao.class); - XXUserPermissionDao xXUserPermissionDao= Mockito.mock(XXUserPermissionDao.class); - XXPortalUserRoleDao xXPortalUserRoleDao= Mockito.mock(XXPortalUserRoleDao.class); - Mockito.when(daoManager.getXXAuthSession()).thenReturn(xXAuthSessionDao); - Mockito.when(daoManager.getXXUserPermission()).thenReturn(xXUserPermissionDao); - Mockito.when(daoManager.getXXPortalUserRole()).thenReturn(xXPortalUserRoleDao); - List xXAuthSessions=new ArrayList(); - XXAuthSession xXAuthSession = new XXAuthSession(); - xXAuthSession.setId(userId); - xXAuthSession.setLoginId(vXPortalUser.getLoginId()); - xXAuthSessions.add(xXAuthSession); - List xXUserPermissions=new ArrayList(); - xXUserPermissions.add(xxUserPermission()); - List xXPortalUserRoles=new ArrayList(); - xXPortalUserRoles.add(XXPortalUserRole); - Mockito.when(xXUserPermissionDao.findByUserPermissionId(vXPortalUser.getId())).thenReturn(xXUserPermissions); - Mockito.when(xXPortalUserRoleDao.findByUserId(vXPortalUser.getId())).thenReturn(xXPortalUserRoles); - XXPolicyDao xXPolicyDao = Mockito.mock(XXPolicyDao.class); - List xXPolicyList = new ArrayList(); - XXPolicy xXPolicy=getXXPolicy(); - xXPolicyList.add(xXPolicy); - Mockito.when(daoManager.getXXPolicy()).thenReturn(xXPolicyDao); - Mockito.when(xXPolicyDao.findByUserId(vXUser.getId())).thenReturn(xXPolicyList); - RangerPolicy rangerPolicy=rangerPolicy(); - Mockito.when(policyService.getPopulatedViewObject(xXPolicy)).thenReturn(rangerPolicy); - List zoneSecRefUser=new ArrayList(); - XXSecurityZoneRefUserDao zoneSecRefUserDao=Mockito.mock(XXSecurityZoneRefUserDao.class); - Mockito.when(daoManager.getXXSecurityZoneRefUser()).thenReturn(zoneSecRefUserDao); - Mockito.when(zoneSecRefUserDao.findByUserId(userId)).thenReturn(zoneSecRefUser); - List roleRefUser=new ArrayList(); - XXRoleRefUserDao roleRefUserDao=Mockito.mock(XXRoleRefUserDao.class); - Mockito.when(daoManager.getXXRoleRefUser()).thenReturn(roleRefUserDao); - Mockito.when(roleRefUserDao.findByUserId(userId)).thenReturn(roleRefUser); - xUserMgr.deleteXUser(vXUser.getId(), force); - force=false; - xUserMgr.deleteXUser(vXUser.getId(), force); - } - - @Test - public void test22DeleteXGroupAndXUser() { - setup(); - VXUser vxUser = vxUser(); - VXGroup vxGroup = vxGroup(); - VXGroupUserList vxGroupUserList = new VXGroupUserList(); - List vXGroupUsers = new ArrayList(); - VXGroupUser vxGroupUser = vxGroupUser(); - vXGroupUsers.add(vxGroupUser); - vxGroupUserList.setVXGroupUsers(vXGroupUsers); - Mockito.when(xGroupService.getGroupByGroupName(Mockito.anyString())).thenReturn(vxGroup); - Mockito.when(xUserService.getXUserByUserName(Mockito.anyString())).thenReturn(vxUser); - Mockito.when(xGroupUserService.searchXGroupUsers((SearchCriteria) Mockito.any())).thenReturn(vxGroupUserList); - XXGroupUserDao xGrpUserDao = Mockito.mock(XXGroupUserDao.class); - Mockito.when(daoManager.getXXGroupUser()).thenReturn(xGrpUserDao); - Mockito.when(xGrpUserDao.remove(vxGroupUser.getId())).thenReturn(true); - xUserMgr.deleteXGroupAndXUser(groupName, userLoginID); - Mockito.verify(xGroupService).getGroupByGroupName(Mockito.anyString()); - Mockito.verify(xUserService).getXUserByUserName(Mockito.anyString()); - Mockito.verify(xGroupUserService).searchXGroupUsers((SearchCriteria) Mockito.any()); - } - - @Test - public void test23CreateVXUserGroupInfo() { - setup(); - VXUserGroupInfo vXUserGroupInfo = new VXUserGroupInfo(); - VXUser vXUser = vxUser(); - List vXGroupUserList = new ArrayList(); - List vXGroupList = new ArrayList(); - final VXGroup vXGroup1 = vxGroup(); - vXGroup1.setName("users"); - vXGroup1.setDescription("users -added for unit testing"); - vXGroupList.add(vXGroup1); - VXGroupUser vXGroupUser1 = vxGroupUser(); - vXGroupUser1.setName("users"); - vXGroupUserList.add(vXGroupUser1); - final VXGroup vXGroup2 = vxGroup(); - vXGroup2.setName("user1"); - vXGroup2.setDescription("user1 -added for unit testing"); - vXGroupList.add(vXGroup2); - VXGroupUser vXGroupUser2 = vxGroupUser(); - vXGroupUser2.setName("user1"); - vXGroupUserList.add(vXGroupUser2); - vXUserGroupInfo.setXuserInfo(vXUser); - vXUserGroupInfo.setXgroupInfo(vXGroupList); - Mockito.when(xUserService.createXUserWithOutLogin(vXUser)).thenReturn(vXUser); - Mockito.when(xGroupService.createXGroupWithOutLogin(vXGroup1)).thenReturn(vXGroup1); - Mockito.when(xGroupService.createXGroupWithOutLogin(vXGroup2)).thenReturn(vXGroup2); - XXPortalUserDao portalUser = Mockito.mock(XXPortalUserDao.class); - Mockito.when(daoManager.getXXPortalUser()).thenReturn(portalUser); - XXPortalUser user = new XXPortalUser(); - user.setId(1L); - user.setUserSource(RangerCommonEnums.USER_EXTERNAL); - Mockito.when(portalUser.findByLoginId(vXUser.getName())).thenReturn(user); - XXPortalUserRoleDao userDao = Mockito.mock(XXPortalUserRoleDao.class); - Mockito.when(daoManager.getXXPortalUserRole()).thenReturn(userDao); - List existingRole = new ArrayList(); - existingRole.add(RangerConstants.ROLE_USER); - List reqRoleList = new ArrayList(); - reqRoleList.add(RangerConstants.ROLE_SYS_ADMIN); - Mockito.when(userDao.findXPortalUserRolebyXPortalUserId(Mockito.anyLong())).thenReturn(reqRoleList); - VXPortalUser vXPortalUser = userProfile(); - Mockito.when(userMgr.getUserProfileByLoginId(Mockito.anyString())).thenReturn(vXPortalUser); - Mockito.when(userMgr.updateRoleForExternalUsers(Mockito.any(), Mockito.any(), (VXPortalUser)Mockito.any())).thenReturn(vXPortalUser); - XXModuleDefDao xXModuleDefDao = Mockito.mock(XXModuleDefDao.class); - XXUserPermissionDao xXUserPermissionDao= Mockito.mock(XXUserPermissionDao.class); - XXUserDao xxUserDao = Mockito.mock(XXUserDao.class); - Collection userRoleList = new ArrayList(); - userRoleList.add("ROLE_USER"); - vXPortalUser.setUserRoleList(userRoleList); - VXUser vxUser = vxUser(); - XXUser xXUser = xxUser(vxUser); - List xXModuleDefs = xxModuleDefs(); - VXUserPermission userPermission = vxUserPermission(); - List userPermList = new ArrayList(); - userPermList.add(userPermission); - List xUserPermissionsList = new ArrayList(); - XXUserPermission xUserPermissionObj = xxUserPermission(); - xUserPermissionObj.setModuleId(userPermission.getModuleId()); - xUserPermissionObj.setUserId(userPermission.getUserId()); - xUserPermissionsList.add(xUserPermissionObj); - Mockito.when(daoManager.getXXModuleDef()).thenReturn(xXModuleDefDao); - Mockito.when(xXModuleDefDao.getAll()).thenReturn(xXModuleDefs); - Mockito.when(daoManager.getXXUserPermission()).thenReturn(xXUserPermissionDao); - Mockito.when(daoManager.getXXUser()).thenReturn(xxUserDao); - Mockito.when(xxUserDao.findByPortalUserId(vXPortalUser.getId())).thenReturn(xXUser); - UserSessionBase userSession = Mockito.mock(UserSessionBase.class); - Set userSessions = new HashSet(); - userSessions.add(userSession); - Mockito.when(xUserPermissionService.createResource((VXUserPermission) Mockito.any())).thenReturn(userPermission); - Mockito.when(sessionMgr.getActiveUserSessionsForPortalUserId(userId)).thenReturn(userSessions); - VXUserGroupInfo vxUserGroupTest = xUserMgr.createXUserGroupFromMap(vXUserGroupInfo); - Assert.assertEquals(userLoginID, vxUserGroupTest.getXuserInfo().getName()); - List result = vxUserGroupTest.getXgroupInfo(); - List expected = new ArrayList(); - expected.add(vXGroup1); - expected.add(vXGroup2); - Assert.assertTrue(result.containsAll(expected)); - Mockito.verify(portalUser).findByLoginId(vXUser.getName()); - Mockito.verify(userDao).findXPortalUserRolebyXPortalUserId( - Mockito.anyLong()); - } - - @Test - public void test24createXModuleDefPermission() { - VXModuleDef vXModuleDef = vxModuleDef(); - Mockito.when(xModuleDefService.createResource(vXModuleDef)).thenReturn(vXModuleDef); - XXModuleDefDao obj = Mockito.mock(XXModuleDefDao.class); - Mockito.when(daoManager.getXXModuleDef()).thenReturn(obj); - VXModuleDef dbMuduleDef = xUserMgr.createXModuleDefPermission(vXModuleDef); - Assert.assertNotNull(dbMuduleDef); - Assert.assertEquals(dbMuduleDef, vXModuleDef); - Assert.assertEquals(dbMuduleDef.getId(), vXModuleDef.getId()); - Assert.assertEquals(dbMuduleDef.getOwner(), vXModuleDef.getOwner()); - Assert.assertEquals(dbMuduleDef.getUpdatedBy(),vXModuleDef.getUpdatedBy()); - Assert.assertEquals(dbMuduleDef.getUrl(), vXModuleDef.getUrl()); - Assert.assertEquals(dbMuduleDef.getAddedById(),vXModuleDef.getAddedById()); - Assert.assertEquals(dbMuduleDef.getCreateDate(),vXModuleDef.getCreateDate()); - Assert.assertEquals(dbMuduleDef.getCreateTime(),vXModuleDef.getCreateTime()); - Assert.assertEquals(dbMuduleDef.getUserPermList(),vXModuleDef.getUserPermList()); - Assert.assertEquals(dbMuduleDef.getGroupPermList(),vXModuleDef.getGroupPermList()); - Mockito.verify(xModuleDefService).createResource(vXModuleDef); - } - - @Test - public void test25getXModuleDefPermission() { - VXModuleDef vXModuleDef = vxModuleDef(); - Mockito.when(xModuleDefService.readResource(1L)).thenReturn(vXModuleDef); - VXModuleDef dbMuduleDef = xUserMgr.getXModuleDefPermission(1L); - Assert.assertNotNull(dbMuduleDef); - Assert.assertEquals(dbMuduleDef, vXModuleDef); - Assert.assertEquals(dbMuduleDef.getId(), vXModuleDef.getId()); - Assert.assertEquals(dbMuduleDef.getOwner(), vXModuleDef.getOwner()); - Assert.assertEquals(dbMuduleDef.getUpdatedBy(),vXModuleDef.getUpdatedBy()); - Assert.assertEquals(dbMuduleDef.getUrl(), vXModuleDef.getUrl()); - Assert.assertEquals(dbMuduleDef.getAddedById(),vXModuleDef.getAddedById()); - Assert.assertEquals(dbMuduleDef.getCreateDate(),vXModuleDef.getCreateDate()); - Assert.assertEquals(dbMuduleDef.getCreateTime(),vXModuleDef.getCreateTime()); - Assert.assertEquals(dbMuduleDef.getUserPermList(),vXModuleDef.getUserPermList()); - Assert.assertEquals(dbMuduleDef.getGroupPermList(),vXModuleDef.getGroupPermList()); - Mockito.verify(xModuleDefService).readResource(1L); - } - - @Test - public void test26updateXModuleDefPermission() { - XXModuleDefDao xModuleDefDao = Mockito.mock(XXModuleDefDao.class); - XXModuleDef xModuleDef = xxModuleDef(); - VXModuleDef vXModuleDef = vxModuleDef(); - Mockito.when(xModuleDefService.updateResource(vXModuleDef)).thenReturn(vXModuleDef); - Mockito.when(daoManager.getXXModuleDef()).thenReturn(xModuleDefDao); - Mockito.when(xModuleDefDao.getById(userId)).thenReturn(xModuleDef); - Map xXGroupNameMap = new HashMap(); - xXGroupNameMap.put(userId, groupName); - Mockito.when(xGroupService.getXXGroupIdNameMap()).thenReturn(xXGroupNameMap); - Object[] objArr = new Object[] {userId ,userId,userLoginID}; - Map xXUserMap =new HashMap(); - xXUserMap.put(userId, objArr); - Mockito.when(xUserService.getXXPortalUserIdXXUserNameMap()).thenReturn(xXUserMap); - Mockito.when(xModuleDefService.populateViewBean(xModuleDef,xXUserMap,xXGroupNameMap,true)).thenReturn(vXModuleDef); - List xXGroupPermissions=new ArrayList(); - XXGroupPermission xGroupPermissionObj = xxGroupPermission(); - xXGroupPermissions.add(xGroupPermissionObj); - VXGroupPermission groupPermission=vxGroupPermission(); - List xXUserPermissions=new ArrayList(); - XXUserPermission xUserPermissionObj=xxUserPermission(); - xXUserPermissions.add(xUserPermissionObj); - VXUserPermission vxUserPermission=vxUserPermission(); - - Map groupPermMapOld = new HashMap(); - groupPermMapOld.put(groupPermission.getGroupId(), groupPermission); - Mockito.when(xGroupPermissionService.convertVListToVMap((List) Mockito.any())).thenReturn(groupPermMapOld); - - Map userPermMapOld = new HashMap(); - userPermMapOld.put(vxUserPermission.getUserId(), vxUserPermission); - Mockito.when(xUserPermissionService.convertVListToVMap((List) Mockito.any())).thenReturn(userPermMapOld); - - UserSessionBase userSession = Mockito.mock(UserSessionBase.class); - Set userSessions = new HashSet(); - userSessions.add(userSession); - VXModuleDef dbMuduleDef = xUserMgr.updateXModuleDefPermission(vXModuleDef); - Assert.assertEquals(dbMuduleDef, vXModuleDef); - Assert.assertNotNull(dbMuduleDef); - Assert.assertEquals(dbMuduleDef, vXModuleDef); - Assert.assertEquals(dbMuduleDef.getId(), vXModuleDef.getId()); - Assert.assertEquals(dbMuduleDef.getOwner(), vXModuleDef.getOwner()); - Assert.assertEquals(dbMuduleDef.getUpdatedBy(),vXModuleDef.getUpdatedBy()); - Assert.assertEquals(dbMuduleDef.getUrl(), vXModuleDef.getUrl()); - Assert.assertEquals(dbMuduleDef.getAddedById(),vXModuleDef.getAddedById()); - Assert.assertEquals(dbMuduleDef.getCreateDate(),vXModuleDef.getCreateDate()); - Assert.assertEquals(dbMuduleDef.getCreateTime(),vXModuleDef.getCreateTime()); - Assert.assertEquals(dbMuduleDef.getUserPermList(),vXModuleDef.getUserPermList()); - Assert.assertEquals(dbMuduleDef.getGroupPermList(),vXModuleDef.getGroupPermList()); - Mockito.verify(xModuleDefService).updateResource(vXModuleDef); - Mockito.verify(daoManager).getXXModuleDef(); - Mockito.verify(xModuleDefService).populateViewBean(xModuleDef,xXUserMap,xXGroupNameMap,true); - vXModuleDef.setModule("UnknownModule"); - Mockito.when(xModuleDefDao.getById(userId)).thenReturn(xModuleDef); - Mockito.when(restErrorUtil.createRESTException("Module name change is not allowed!",MessageEnums.DATA_NOT_UPDATABLE)).thenThrow(new WebApplicationException()); - thrown.expect(WebApplicationException.class); - dbMuduleDef = xUserMgr.updateXModuleDefPermission(vXModuleDef); - } - - @Test - public void test27deleteXModuleDefPermission() { - Long moduleId=Long.valueOf(1); - XXUserPermissionDao xUserPermissionDao = Mockito.mock(XXUserPermissionDao.class); - XXGroupPermissionDao xGroupPermissionDao = Mockito.mock(XXGroupPermissionDao.class); - Mockito.when(daoManager.getXXUserPermission()).thenReturn(xUserPermissionDao); - Mockito.when(daoManager.getXXGroupPermission()).thenReturn(xGroupPermissionDao); - Mockito.doNothing().when(xUserPermissionDao).deleteByModuleId(moduleId); - Mockito.doNothing().when(xGroupPermissionDao).deleteByModuleId(moduleId); - Mockito.when(xModuleDefService.deleteResource(1L)).thenReturn(true); - xUserMgr.deleteXModuleDefPermission(1L, true); - Mockito.verify(xModuleDefService).deleteResource(1L); - } - - @Test - public void test28createXUserPermission() { - VXUserPermission vXUserPermission = vxUserPermission(); - Mockito.when(xUserPermissionService.createResource(vXUserPermission)).thenReturn(vXUserPermission); - VXUserPermission dbUserPermission = xUserMgr.createXUserPermission(vXUserPermission); - Assert.assertNotNull(dbUserPermission); - Assert.assertEquals(dbUserPermission, vXUserPermission); - Assert.assertEquals(dbUserPermission.getId(), vXUserPermission.getId()); - Assert.assertEquals(dbUserPermission.getOwner(),vXUserPermission.getOwner()); - Assert.assertEquals(dbUserPermission.getUpdatedBy(),vXUserPermission.getUpdatedBy()); - Assert.assertEquals(dbUserPermission.getUserName(),vXUserPermission.getUserName()); - Assert.assertEquals(dbUserPermission.getCreateDate(),vXUserPermission.getCreateDate()); - Assert.assertEquals(dbUserPermission.getIsAllowed(),vXUserPermission.getIsAllowed()); - Assert.assertEquals(dbUserPermission.getModuleId(),vXUserPermission.getModuleId()); - Assert.assertEquals(dbUserPermission.getUpdateDate(),vXUserPermission.getUpdateDate()); - Assert.assertEquals(dbUserPermission.getUserId(),vXUserPermission.getUserId()); - Mockito.verify(xUserPermissionService).createResource(vXUserPermission); - } - - @Test - public void test29getXUserPermission() { - VXUserPermission vXUserPermission = vxUserPermission(); - Mockito.when(xUserPermissionService.readResource(1L)).thenReturn(vXUserPermission); - VXUserPermission dbUserPermission = xUserMgr.getXUserPermission(1L); - Assert.assertNotNull(dbUserPermission); - Assert.assertEquals(dbUserPermission, vXUserPermission); - Assert.assertEquals(dbUserPermission.getId(), vXUserPermission.getId()); - Assert.assertEquals(dbUserPermission.getOwner(),vXUserPermission.getOwner()); - Assert.assertEquals(dbUserPermission.getUpdatedBy(),vXUserPermission.getUpdatedBy()); - Assert.assertEquals(dbUserPermission.getUserName(),vXUserPermission.getUserName()); - Assert.assertEquals(dbUserPermission.getCreateDate(),vXUserPermission.getCreateDate()); - Assert.assertEquals(dbUserPermission.getIsAllowed(),vXUserPermission.getIsAllowed()); - Assert.assertEquals(dbUserPermission.getModuleId(),vXUserPermission.getModuleId()); - Assert.assertEquals(dbUserPermission.getUpdateDate(),vXUserPermission.getUpdateDate()); - Assert.assertEquals(dbUserPermission.getUserId(),vXUserPermission.getUserId()); - Mockito.verify(xUserPermissionService).readResource(1L); - } - - @Test - public void test30updateXUserPermission() { - VXUserPermission vXUserPermission = vxUserPermission(); - Mockito.when(xUserPermissionService.updateResource(vXUserPermission)).thenReturn(vXUserPermission); - VXUserPermission dbUserPermission = xUserMgr.updateXUserPermission(vXUserPermission); - Assert.assertNotNull(dbUserPermission); - Assert.assertEquals(dbUserPermission, vXUserPermission); - Assert.assertEquals(dbUserPermission.getId(), vXUserPermission.getId()); - Assert.assertEquals(dbUserPermission.getOwner(),vXUserPermission.getOwner()); - Assert.assertEquals(dbUserPermission.getUpdatedBy(),vXUserPermission.getUpdatedBy()); - Assert.assertEquals(dbUserPermission.getUserName(),vXUserPermission.getUserName()); - Assert.assertEquals(dbUserPermission.getCreateDate(),vXUserPermission.getCreateDate()); - Assert.assertEquals(dbUserPermission.getIsAllowed(),vXUserPermission.getIsAllowed()); - Assert.assertEquals(dbUserPermission.getModuleId(),vXUserPermission.getModuleId()); - Assert.assertEquals(dbUserPermission.getUpdateDate(),vXUserPermission.getUpdateDate()); - Assert.assertEquals(dbUserPermission.getUserId(),vXUserPermission.getUserId()); - Mockito.verify(xUserPermissionService).updateResource(vXUserPermission); - } - - @Test - public void test31deleteXUserPermission() { - UserSessionBase userSession = Mockito.mock(UserSessionBase.class); - Set userSessions = new HashSet(); - userSessions.add(userSession); - XXUserPermission xUserPermissionObj = xxUserPermission(); - XXUserPermissionDao xUserPermDao = Mockito.mock(XXUserPermissionDao.class); - Mockito.when(daoManager.getXXUserPermission()).thenReturn(xUserPermDao); - Mockito.when(xUserPermDao.getById(1L)).thenReturn(xUserPermissionObj); - Mockito.when(xUserPermissionService.deleteResource(1L)).thenReturn(true); - Mockito.when(sessionMgr.getActiveUserSessionsForPortalUserId(xUserPermissionObj.getUserId())).thenReturn(userSessions); - xUserMgr.deleteXUserPermission(1L, true); - Mockito.verify(xUserPermissionService).deleteResource(1L); - } - - @Test - public void test32createXGroupPermission() { - VXGroupPermission vXGroupPermission = vxGroupPermission(); - XXGroupUserDao xGrpUserDao = Mockito.mock(XXGroupUserDao.class); - Mockito.when(daoManager.getXXGroupUser()).thenReturn(xGrpUserDao); - Mockito.when(xGroupPermissionService.createResource(vXGroupPermission)).thenReturn(vXGroupPermission); - List xXGroupUserList = new ArrayList(); - VXGroupUser vxGroupUser = vxGroupUser(); - XXGroupUser xXGroupUser =new XXGroupUser(); - xXGroupUser.setId(vxGroupUser.getId()); - xXGroupUser.setName(vxGroupUser.getName()); - xXGroupUser.setParentGroupId(vxGroupUser.getParentGroupId()); - xXGroupUser.setUserId(vxGroupUser.getUserId()); - xXGroupUserList.add(xXGroupUser); - Mockito.when(xGrpUserDao.findByGroupId(vXGroupPermission.getGroupId())).thenReturn(xXGroupUserList); - UserSessionBase userSession = Mockito.mock(UserSessionBase.class); - Set userSessions = new HashSet(); - userSessions.add(userSession); - Mockito.when(sessionMgr.getActiveUserSessionsForXUserId(xXGroupUser.getUserId())).thenReturn(userSessions); - VXGroupPermission dbGroupPermission = xUserMgr.createXGroupPermission(vXGroupPermission); - Assert.assertNotNull(dbGroupPermission); - Assert.assertEquals(dbGroupPermission, vXGroupPermission); - Assert.assertEquals(dbGroupPermission.getId(),vXGroupPermission.getId()); - Assert.assertEquals(dbGroupPermission.getGroupName(),vXGroupPermission.getGroupName()); - Assert.assertEquals(dbGroupPermission.getOwner(),vXGroupPermission.getOwner()); - Assert.assertEquals(dbGroupPermission.getUpdatedBy(),vXGroupPermission.getUpdatedBy()); - Assert.assertEquals(dbGroupPermission.getCreateDate(),vXGroupPermission.getCreateDate()); - Assert.assertEquals(dbGroupPermission.getGroupId(),vXGroupPermission.getGroupId()); - Assert.assertEquals(dbGroupPermission.getIsAllowed(),vXGroupPermission.getIsAllowed()); - Assert.assertEquals(dbGroupPermission.getModuleId(),vXGroupPermission.getModuleId()); - Assert.assertEquals(dbGroupPermission.getUpdateDate(),vXGroupPermission.getUpdateDate()); - Mockito.verify(xGroupPermissionService).createResource(vXGroupPermission); - } - - @Test - public void test33getXGroupPermission() { - VXGroupPermission vXGroupPermission = vxGroupPermission(); - Mockito.when(xGroupPermissionService.readResource(1L)).thenReturn(vXGroupPermission); - VXGroupPermission dbGroupPermission = xUserMgr.getXGroupPermission(1L); - Assert.assertNotNull(dbGroupPermission); - Assert.assertEquals(dbGroupPermission, vXGroupPermission); - Assert.assertEquals(dbGroupPermission.getId(),vXGroupPermission.getId()); - Assert.assertEquals(dbGroupPermission.getGroupName(),vXGroupPermission.getGroupName()); - Assert.assertEquals(dbGroupPermission.getOwner(),vXGroupPermission.getOwner()); - Assert.assertEquals(dbGroupPermission.getUpdatedBy(),vXGroupPermission.getUpdatedBy()); - Assert.assertEquals(dbGroupPermission.getCreateDate(),vXGroupPermission.getCreateDate()); - Assert.assertEquals(dbGroupPermission.getGroupId(),vXGroupPermission.getGroupId()); - Assert.assertEquals(dbGroupPermission.getIsAllowed(),vXGroupPermission.getIsAllowed()); - Assert.assertEquals(dbGroupPermission.getModuleId(),vXGroupPermission.getModuleId()); - Assert.assertEquals(dbGroupPermission.getUpdateDate(),vXGroupPermission.getUpdateDate()); - Mockito.verify(xGroupPermissionService).readResource(1L); - } - - @Test - public void test34updateXGroupPermission() { - setup(); - VXGroupPermission vXGroupPermission = vxGroupPermission(); - XXGroupUserDao xGrpUserDao = Mockito.mock(XXGroupUserDao.class); - Mockito.when(daoManager.getXXGroupUser()).thenReturn(xGrpUserDao); - Mockito.when(xGroupPermissionService.updateResource(vXGroupPermission)).thenReturn(vXGroupPermission); - UserSessionBase userSession = Mockito.mock(UserSessionBase.class); - Set userSessions = new HashSet(); - userSessions.add(userSession); - Mockito.when(sessionMgr.getActiveUserSessionsForXUserId(userId)).thenReturn(userSessions); - List xXGroupUserList = new ArrayList(); - VXGroupUser vxGroupUser = vxGroupUser(); - XXGroupUser xXGroupUser =new XXGroupUser(); - xXGroupUser.setId(vxGroupUser.getId()); - xXGroupUser.setName(vxGroupUser.getName()); - xXGroupUser.setParentGroupId(vxGroupUser.getParentGroupId()); - xXGroupUser.setUserId(vxGroupUser.getUserId()); - xXGroupUserList.add(xXGroupUser); - Mockito.when(xGrpUserDao.findByGroupId(vXGroupPermission.getGroupId())).thenReturn(xXGroupUserList); - VXGroupPermission dbGroupPermission = xUserMgr.updateXGroupPermission(vXGroupPermission); - Assert.assertNotNull(dbGroupPermission); - Assert.assertEquals(dbGroupPermission, vXGroupPermission); - Assert.assertEquals(dbGroupPermission.getId(),vXGroupPermission.getId()); - Assert.assertEquals(dbGroupPermission.getGroupName(),vXGroupPermission.getGroupName()); - Assert.assertEquals(dbGroupPermission.getOwner(),vXGroupPermission.getOwner()); - Assert.assertEquals(dbGroupPermission.getUpdatedBy(),vXGroupPermission.getUpdatedBy()); - Assert.assertEquals(dbGroupPermission.getCreateDate(),vXGroupPermission.getCreateDate()); - Assert.assertEquals(dbGroupPermission.getGroupId(),vXGroupPermission.getGroupId()); - Assert.assertEquals(dbGroupPermission.getIsAllowed(),vXGroupPermission.getIsAllowed()); - Assert.assertEquals(dbGroupPermission.getModuleId(),vXGroupPermission.getModuleId()); - Assert.assertEquals(dbGroupPermission.getUpdateDate(),vXGroupPermission.getUpdateDate()); - Mockito.verify(xGroupPermissionService).updateResource(vXGroupPermission); - } - - @Test - public void test35deleteXGroupPermission() { - XXGroupPermissionDao xGrpPermDao = Mockito.mock(XXGroupPermissionDao.class); - XXGroupPermission xGroupPermissionObj = xxGroupPermission(); - Mockito.when(daoManager.getXXGroupPermission()).thenReturn(xGrpPermDao); - Mockito.when(xGrpPermDao.getById(1L)).thenReturn(xGroupPermissionObj); - XXGroupUserDao xGrpUserDao = Mockito.mock(XXGroupUserDao.class); - Mockito.when(daoManager.getXXGroupUser()).thenReturn(xGrpUserDao); - List xXGroupUserList = new ArrayList(); - VXGroupUser vxGroupUser = vxGroupUser(); - XXGroupUser xXGroupUser =new XXGroupUser(); - xXGroupUser.setId(vxGroupUser.getId()); - xXGroupUser.setName(vxGroupUser.getName()); - xXGroupUser.setParentGroupId(vxGroupUser.getParentGroupId()); - xXGroupUser.setUserId(vxGroupUser.getUserId()); - xXGroupUserList.add(xXGroupUser); - Mockito.when(xGrpUserDao.findByGroupId(xGroupPermissionObj.getGroupId())).thenReturn(xXGroupUserList); - UserSessionBase userSession = Mockito.mock(UserSessionBase.class); - Set userSessions = new HashSet(); - userSessions.add(userSession); - Mockito.when(sessionMgr.getActiveUserSessionsForXUserId(userId)).thenReturn(userSessions); - Mockito.when(xGroupPermissionService.deleteResource(1L)).thenReturn(true); - xUserMgr.deleteXGroupPermission(1L, true); - Mockito.verify(xGroupPermissionService).deleteResource(1L); - } - - @Test - public void test36getGroupsForUser() { - setupUser(); - VXUser vxUser = vxUser(); - VXGroup vxGroup=vxGroup(); - String userName = userLoginID; - Mockito.when(xUserService.getXUserByUserName(userName)).thenReturn(vxUser); - VXGroupUserList vxGroupUserList = vxGroupUserList(); - Mockito.when(xGroupUserService.searchXGroupUsers((SearchCriteria) Mockito.any())).thenReturn(vxGroupUserList); - Mockito.when(xGroupService.readResource(userId)).thenReturn(vxGroup); - XXModuleDefDao modDef = Mockito.mock(XXModuleDefDao.class); - Mockito.when(daoManager.getXXModuleDef()).thenReturn(modDef); - List lstModule = new ArrayList(); - lstModule.add(RangerConstants.MODULE_USER_GROUPS); - lstModule.add(RangerConstants.MODULE_RESOURCE_BASED_POLICIES); - Mockito.when(modDef.findAccessibleModulesByUserId(Mockito.anyLong(), - Mockito.anyLong())).thenReturn(lstModule); - Set list = xUserMgr.getGroupsForUser(userName); - Assert.assertNotNull(list); - Mockito.verify(xUserService, Mockito.atLeast(2)).getXUserByUserName(userName); - Mockito.verify(modDef).findAccessibleModulesByUserId(Mockito.anyLong(),Mockito.anyLong()); - Mockito.when(xUserService.getXUserByUserName(userName)).thenReturn(null); - list = xUserMgr.getGroupsForUser(userName); - Assert.assertTrue(list.isEmpty()); - Mockito.verify(xUserService, Mockito.atLeast(2)).getXUserByUserName(userName); - Mockito.verify(modDef).findAccessibleModulesByUserId(Mockito.anyLong(),Mockito.anyLong()); - Mockito.when(xUserService.getXUserByUserName(userName)).thenReturn(null); - list = xUserMgr.getGroupsForUser(userName); - Assert.assertTrue(list.isEmpty()); - Mockito.verify(xUserService, Mockito.atLeast(2)).getXUserByUserName(userName); - Mockito.verify(modDef).findAccessibleModulesByUserId(Mockito.anyLong(),Mockito.anyLong()); - } - - @Test - public void test37setUserRolesByExternalID() { - setup(); - VXUser vXUser = vxUser(); - List vStringRolesList = new ArrayList(); - VXString vXStringObj = new VXString(); - vXStringObj.setValue("ROLE_USER"); - vStringRolesList.add(vXStringObj); - List xPortalUserRoleList = new ArrayList(); - XXPortalUserRole XXPortalUserRole = new XXPortalUserRole(); - XXPortalUserRole.setId(userId); - XXPortalUserRole.setUserId(userId); - XXPortalUserRole.setUserRole("ROLE_USER"); - xPortalUserRoleList.add(XXPortalUserRole); - List xUserPermissionsList = new ArrayList(); - XXUserPermission xUserPermissionObj = xxUserPermission(); - xUserPermissionsList.add(xUserPermissionObj); - List xGroupPermissionList = new ArrayList(); - XXGroupPermission xGroupPermissionObj = xxGroupPermission(); - xGroupPermissionList.add(xGroupPermissionObj); - List groupPermList = new ArrayList(); - VXGroupPermission groupPermission = vxGroupPermission(); - groupPermList.add(groupPermission); - Mockito.when(xUserMgr.getXUser(userId)).thenReturn(vXUser); - - List permissionList = new ArrayList(); - permissionList.add(RangerConstants.MODULE_USER_GROUPS); - - VXUser loggedInUser = vxUser(); - List loggedInUserRole = new ArrayList(); - loggedInUserRole.add(RangerConstants.ROLE_ADMIN); - loggedInUser.setId(8L); - loggedInUser.setName("testuser"); - loggedInUser.setUserRoleList(loggedInUserRole); - Mockito.when(xUserService.getXUserByUserName("admin")).thenReturn(loggedInUser); - - Mockito.when(restErrorUtil.createRESTException(HttpServletResponse.SC_FORBIDDEN, "Logged-In user is not allowed to access requested user data", true)).thenThrow(new WebApplicationException()); - thrown.expect(WebApplicationException.class); - VXStringList vXStringList = xUserMgr.setUserRolesByExternalID(userId,vStringRolesList); - Assert.assertNotNull(vXStringList); - } - - @Test - public void test38setUserRolesByExternalID() { - destroySession(); - setup(); - VXUser vXUser = vxUser(); - List vStringRolesList = new ArrayList(); - VXString vXStringObj = new VXString(); - vXStringObj.setValue("ROLE_USER"); - vStringRolesList.add(vXStringObj); - List xPortalUserRoleList = new ArrayList(); - XXPortalUserRole XXPortalUserRole = new XXPortalUserRole(); - XXPortalUserRole.setId(userId); - XXPortalUserRole.setUserId(userId); - XXPortalUserRole.setUserRole("ROLE_USER"); - xPortalUserRoleList.add(XXPortalUserRole); - List xUserPermissionsList = new ArrayList(); - XXUserPermission xUserPermissionObj = xxUserPermission(); - xUserPermissionsList.add(xUserPermissionObj); - List xGroupPermissionList = new ArrayList(); - XXGroupPermission xGroupPermissionObj = xxGroupPermission(); - xGroupPermissionList.add(xGroupPermissionObj); - List groupPermList = new ArrayList(); - VXGroupPermission groupPermission = vxGroupPermission(); - groupPermList.add(groupPermission); - Mockito.when(xUserMgr.getXUser(userId)).thenReturn(vXUser); - - List permissionList = new ArrayList(); - permissionList.add(RangerConstants.MODULE_USER_GROUPS); - - VXUser loggedInUser = vxUser(); - List loggedInUserRole = new ArrayList(); - loggedInUserRole.add(RangerConstants.ROLE_ADMIN); - loggedInUser.setId(8L); - loggedInUser.setName("testuser"); - loggedInUser.setUserRoleList(loggedInUserRole); - Mockito.when(xUserService.getXUserByUserName("admin")).thenReturn(loggedInUser); - - Mockito.when(restErrorUtil.createRESTException(HttpServletResponse.SC_FORBIDDEN, "Logged-In user is not allowed to access requested user data", true)).thenThrow(new WebApplicationException()); - thrown.expect(WebApplicationException.class); - xUserMgr.setUserRolesByExternalID(userId, vStringRolesList); - } - - @Test - public void test39setUserRolesByExternalID() { - destroySession(); - setup(); - VXUser vXUser = vxUser(); - List vStringRolesList = new ArrayList(); - VXString vXStringObj = new VXString(); - vXStringObj.setValue("ROLE_USER"); - vStringRolesList.add(vXStringObj); - List xPortalUserRoleList = new ArrayList(); - XXPortalUserRole XXPortalUserRole = new XXPortalUserRole(); - XXPortalUserRole.setId(userId); - XXPortalUserRole.setUserId(userId); - XXPortalUserRole.setUserRole("ROLE_USER"); - xPortalUserRoleList.add(XXPortalUserRole); - List xUserPermissionsList = new ArrayList(); - XXUserPermission xUserPermissionObj = xxUserPermission(); - xUserPermissionsList.add(xUserPermissionObj); - List xGroupPermissionList = new ArrayList(); - XXGroupPermission xGroupPermissionObj = xxGroupPermission(); - xGroupPermissionList.add(xGroupPermissionObj); - List groupPermList = new ArrayList(); - VXGroupPermission groupPermission = vxGroupPermission(); - groupPermList.add(groupPermission); - Mockito.when(xUserMgr.getXUser(userId)).thenReturn(vXUser); - Mockito.when(xUserMgr.getXUser(0L)).thenReturn(null); - Mockito.when(restErrorUtil.createRESTException("User ID doesn't exist.",MessageEnums.INVALID_INPUT_DATA)).thenThrow(new WebApplicationException()); - thrown.expect(WebApplicationException.class); - xUserMgr.setUserRolesByExternalID(0L, vStringRolesList); - } - - @Test - public void test40setUserRolesByName() { - destroySession(); - setup(); - VXPortalUser userProfile = userProfile(); - List vStringRolesList = new ArrayList(); - VXString vXStringObj = new VXString(); - vXStringObj.setValue("ROLE_USER"); - vStringRolesList.add(vXStringObj); - List xPortalUserRoleList = new ArrayList(); - XXPortalUserRole XXPortalUserRole = new XXPortalUserRole(); - XXPortalUserRole.setId(userId); - XXPortalUserRole.setUserId(userId); - XXPortalUserRole.setUserRole("ROLE_USER"); - xPortalUserRoleList.add(XXPortalUserRole); - List xUserPermissionsList = new ArrayList(); - XXUserPermission xUserPermissionObj = xxUserPermission(); - xUserPermissionsList.add(xUserPermissionObj); - List xGroupPermissionList = new ArrayList(); - XXGroupPermission xGroupPermissionObj = xxGroupPermission(); - xGroupPermissionList.add(xGroupPermissionObj); - List groupPermList = new ArrayList(); - VXGroupPermission groupPermission = vxGroupPermission(); - groupPermList.add(groupPermission); - Mockito.when(restErrorUtil.createRESTException("Login ID doesn't exist.",MessageEnums.INVALID_INPUT_DATA)).thenThrow(new WebApplicationException()); - thrown.expect(WebApplicationException.class); - VXStringList vXStringList = xUserMgr.setUserRolesByName(userProfile.getLoginId(), vStringRolesList); - Assert.assertNotNull(vXStringList); - xUserMgr.setUserRolesByName(null, vStringRolesList); - } - - @Test - public void test41setUserRolesByName() { - destroySession(); - setup(); - VXPortalUser userProfile = userProfile(); - List vStringRolesList = new ArrayList(); - VXString vXStringObj = new VXString(); - vXStringObj.setValue("ROLE_USER"); - vStringRolesList.add(vXStringObj); - List xPortalUserRoleList = new ArrayList(); - XXPortalUserRole XXPortalUserRole = new XXPortalUserRole(); - XXPortalUserRole.setId(userId); - XXPortalUserRole.setUserId(userId); - XXPortalUserRole.setUserRole("ROLE_USER"); - xPortalUserRoleList.add(XXPortalUserRole); - List xUserPermissionsList = new ArrayList(); - XXUserPermission xUserPermissionObj = xxUserPermission(); - xUserPermissionsList.add(xUserPermissionObj); - List xGroupPermissionList = new ArrayList(); - XXGroupPermission xGroupPermissionObj = xxGroupPermission(); - xGroupPermissionList.add(xGroupPermissionObj); - List groupPermList = new ArrayList(); - VXGroupPermission groupPermission = vxGroupPermission(); - groupPermList.add(groupPermission); - Mockito.when(restErrorUtil.createRESTException("Login ID doesn't exist.",MessageEnums.INVALID_INPUT_DATA)).thenThrow(new WebApplicationException()); - thrown.expect(WebApplicationException.class); - VXStringList vXStringList = xUserMgr.setUserRolesByName(userProfile.getLoginId(), vStringRolesList); - Assert.assertNotNull(vXStringList); - xUserMgr.setUserRolesByName(null, vStringRolesList); - } - - @Test - public void test42getUserRolesByExternalID() { - destroySession(); - setup(); - VXUser vXUser = vxUser(); - List vStringRolesList = new ArrayList(); - VXString vXStringObj = new VXString(); - vXStringObj.setValue("ROLE_USER"); - vStringRolesList.add(vXStringObj); - List xPortalUserRoleList = new ArrayList(); - XXPortalUserRole XXPortalUserRole = new XXPortalUserRole(); - XXPortalUserRole.setId(userId); - XXPortalUserRole.setUserId(userId); - XXPortalUserRole.setUserRole("ROLE_USER"); - xPortalUserRoleList.add(XXPortalUserRole); - List xUserPermissionsList = new ArrayList(); - XXUserPermission xUserPermissionObj = xxUserPermission(); - xUserPermissionsList.add(xUserPermissionObj); - List xGroupPermissionList = new ArrayList(); - XXGroupPermission xGroupPermissionObj = xxGroupPermission(); - xGroupPermissionList.add(xGroupPermissionObj); - List groupPermList = new ArrayList(); - VXGroupPermission groupPermission = vxGroupPermission(); - groupPermList.add(groupPermission); - Mockito.when(xUserMgr.getXUser(userId)).thenReturn(vXUser); - - List permissionList = new ArrayList(); - permissionList.add(RangerConstants.MODULE_USER_GROUPS); - - VXUser loggedInUser = vxUser(); - List loggedInUserRole = new ArrayList(); - loggedInUserRole.add(RangerConstants.ROLE_ADMIN); - loggedInUser.setId(8L); - loggedInUser.setName("testuser"); - loggedInUser.setUserRoleList(loggedInUserRole); - Mockito.when(xUserService.getXUserByUserName("admin")).thenReturn(loggedInUser); - Mockito.when(restErrorUtil.createRESTException(HttpServletResponse.SC_FORBIDDEN, "Logged-In user is not allowed to access requested user data", true)).thenThrow(new WebApplicationException()); - thrown.expect(WebApplicationException.class); - VXStringList vXStringList = xUserMgr.getUserRolesByExternalID(userId); - Assert.assertNotNull(vXStringList); - Mockito.when(restErrorUtil.createRESTException("Please provide a valid ID",MessageEnums.INVALID_INPUT_DATA)).thenThrow(new WebApplicationException()); - thrown.expect(WebApplicationException.class); - Mockito.when(xUserService.readResourceWithOutLogin((Long)Mockito.any())).thenReturn(null); - xUserMgr.getUserRolesByExternalID(userId); - } - - @Test - public void test43getUserRolesByExternalID() { - destroySession(); - setup(); - VXUser vXUser = vxUser(); - List vStringRolesList = new ArrayList(); - VXString vXStringObj = new VXString(); - vXStringObj.setValue("ROLE_USER"); - vStringRolesList.add(vXStringObj); - List xPortalUserRoleList = new ArrayList(); - XXPortalUserRole XXPortalUserRole = new XXPortalUserRole(); - XXPortalUserRole.setId(userId); - XXPortalUserRole.setUserId(userId); - XXPortalUserRole.setUserRole("ROLE_USER"); - xPortalUserRoleList.add(XXPortalUserRole); - List xUserPermissionsList = new ArrayList(); - XXUserPermission xUserPermissionObj = xxUserPermission(); - xUserPermissionsList.add(xUserPermissionObj); - List xGroupPermissionList = new ArrayList(); - XXGroupPermission xGroupPermissionObj = xxGroupPermission(); - xGroupPermissionList.add(xGroupPermissionObj); - List groupPermList = new ArrayList(); - VXGroupPermission groupPermission = vxGroupPermission(); - groupPermList.add(groupPermission); - Mockito.when(xUserMgr.getXUser(userId)).thenReturn(vXUser); - - List permissionList = new ArrayList(); - permissionList.add(RangerConstants.MODULE_USER_GROUPS); - - VXUser loggedInUser = vxUser(); - List loggedInUserRole = new ArrayList(); - loggedInUserRole.add(RangerConstants.ROLE_ADMIN); - loggedInUser.setId(8L); - loggedInUser.setName("testuser"); - loggedInUser.setUserRoleList(loggedInUserRole); - Mockito.when(xUserService.getXUserByUserName("admin")).thenReturn(loggedInUser); - Mockito.when(restErrorUtil.createRESTException(HttpServletResponse.SC_FORBIDDEN, "Logged-In user is not allowed to access requested user data", true)).thenThrow(new WebApplicationException()); - thrown.expect(WebApplicationException.class); - VXStringList vXStringList = xUserMgr.getUserRolesByExternalID(userId); - Assert.assertNotNull(vXStringList); - Mockito.when(restErrorUtil.createRESTException("User ID doesn't exist.",MessageEnums.INVALID_INPUT_DATA)).thenThrow(new WebApplicationException()); - thrown.expect(WebApplicationException.class); - Mockito.when(userMgr.getUserProfileByLoginId((String)Mockito.anyString())).thenReturn(null); - xUserMgr.getUserRolesByExternalID(userId); - } - - @Test - public void test44getUserRolesByName() { - destroySession(); - setup(); - XXPortalUserRoleDao xPortalUserRoleDao = Mockito.mock(XXPortalUserRoleDao.class); - VXPortalUser userProfile = userProfile(); - Collection userRoleList = new ArrayList(); - userRoleList.add("ROLE_USER"); - userProfile.setUserRoleList(userRoleList); - List vStringRolesList = new ArrayList(); - VXString vXStringObj = new VXString(); - vXStringObj.setValue("ROLE_USER"); - vStringRolesList.add(vXStringObj); - List xPortalUserRoleList = new ArrayList(); - XXPortalUserRole XXPortalUserRole = new XXPortalUserRole(); - XXPortalUserRole.setId(userId); - XXPortalUserRole.setUserId(userId); - XXPortalUserRole.setUserRole("ROLE_USER"); - xPortalUserRoleList.add(XXPortalUserRole); - List xUserPermissionsList = new ArrayList(); - XXUserPermission xUserPermissionObj = xxUserPermission(); - xUserPermissionsList.add(xUserPermissionObj); - List xGroupPermissionList = new ArrayList(); - XXGroupPermission xGroupPermissionObj = xxGroupPermission(); - xGroupPermissionList.add(xGroupPermissionObj); - List groupPermList = new ArrayList(); - VXGroupPermission groupPermission = vxGroupPermission(); - groupPermList.add(groupPermission); - Mockito.when(daoManager.getXXPortalUserRole()).thenReturn(xPortalUserRoleDao); - Mockito.when(xPortalUserRoleDao.findByUserId(userId)).thenReturn(xPortalUserRoleList); - Mockito.when(userMgr.getUserProfileByLoginId(userProfile.getLoginId())).thenReturn(userProfile); - VXUser loggedInUser = vxUser(); - List loggedInUserRole = new ArrayList(); - loggedInUserRole.add(RangerConstants.ROLE_SYS_ADMIN); - loggedInUser.setId(8L); - loggedInUser.setName("admin"); - loggedInUser.setUserRoleList(loggedInUserRole); - Mockito.when(xUserService.getXUserByUserName("admin")).thenReturn(loggedInUser); - VXUser testuser = vxUser(); - Mockito.when(xUserService.getXUserByUserName("testuser")).thenReturn(testuser); - VXStringList vXStringList = xUserMgr.getUserRolesByName(userProfile.getLoginId()); - Assert.assertNotNull(vXStringList); - Mockito.when(restErrorUtil.createRESTException("Please provide a valid userName",MessageEnums.INVALID_INPUT_DATA)).thenThrow(new WebApplicationException()); - thrown.expect(WebApplicationException.class); - Mockito.when(userMgr.getUserProfileByLoginId((String) Mockito.anyString())).thenReturn(null); - xUserMgr.getUserRolesByName(userProfile.getLoginId()); - } - - @Test - public void test45getUserRolesByName() { - destroySession(); - setup(); - XXPortalUserRoleDao xPortalUserRoleDao = Mockito.mock(XXPortalUserRoleDao.class); - VXPortalUser userProfile = userProfile(); - Collection userRoleList = new ArrayList(); - userRoleList.add("ROLE_USER"); - userProfile.setUserRoleList(userRoleList); - List vStringRolesList = new ArrayList(); - VXString vXStringObj = new VXString(); - vXStringObj.setValue("ROLE_USER"); - vStringRolesList.add(vXStringObj); - List xPortalUserRoleList = new ArrayList(); - XXPortalUserRole XXPortalUserRole = new XXPortalUserRole(); - XXPortalUserRole.setId(userId); - XXPortalUserRole.setUserId(userId); - XXPortalUserRole.setUserRole("ROLE_USER"); - xPortalUserRoleList.add(XXPortalUserRole); - List xUserPermissionsList = new ArrayList(); - XXUserPermission xUserPermissionObj = xxUserPermission(); - xUserPermissionsList.add(xUserPermissionObj); - List xGroupPermissionList = new ArrayList(); - XXGroupPermission xGroupPermissionObj = xxGroupPermission(); - xGroupPermissionList.add(xGroupPermissionObj); - List groupPermList = new ArrayList(); - VXGroupPermission groupPermission = vxGroupPermission(); - groupPermList.add(groupPermission); - Mockito.when(daoManager.getXXPortalUserRole()).thenReturn(xPortalUserRoleDao); - Mockito.when(xPortalUserRoleDao.findByUserId(userId)).thenReturn(xPortalUserRoleList); - Mockito.when(userMgr.getUserProfileByLoginId(userProfile.getLoginId())).thenReturn(userProfile); - VXUser loggedInUser = vxUser(); - List loggedInUserRole = new ArrayList(); - loggedInUserRole.add(RangerConstants.ROLE_SYS_ADMIN); - loggedInUser.setId(8L); - loggedInUser.setName("admin"); - loggedInUser.setUserRoleList(loggedInUserRole); - Mockito.when(xUserService.getXUserByUserName("admin")).thenReturn(loggedInUser); - VXUser testuser = vxUser(); - Mockito.when(xUserService.getXUserByUserName("testuser")).thenReturn(testuser); - VXStringList vXStringList = xUserMgr.getUserRolesByName(userProfile.getLoginId()); - Assert.assertNotNull(vXStringList); - Mockito.when(restErrorUtil.createRESTException("Please provide a valid userName",MessageEnums.INVALID_INPUT_DATA)).thenThrow(new WebApplicationException()); - thrown.expect(WebApplicationException.class); - xUserMgr.getUserRolesByName(""); - } - - @Test - public void test46hasAccess() { - setup(); - xUserMgr.hasAccess("test"); - } - - @Test - public void test47searchXUsers() { - VXUser vxUser = vxUser(); - vxUser.setStatus(1); - vxUser.setUserSource(1); - VXUserList vXUserListSort = new VXUserList(); - List vXUsers = new ArrayList(); - vXUsers.add(vxUser); - vXUserListSort.setVXUsers(vXUsers); - String userName = vxUser.getName(); - SearchCriteria testSearchCriteria = createsearchCriteria(); - testSearchCriteria.addParam("name", userName); - Mockito.when(xUserService.getXUserByUserName(userName)).thenReturn(vxUser); - Mockito.when(xUserService.searchXUsers(testSearchCriteria)).thenReturn(vXUserListSort); - VXUserList dbVXUserList = xUserMgr.searchXUsers(testSearchCriteria); - Assert.assertNotNull(dbVXUserList); - testSearchCriteria.addParam("isvisible", "true"); - dbVXUserList = xUserMgr.searchXUsers(testSearchCriteria); - Assert.assertNotNull(dbVXUserList); - testSearchCriteria = createsearchCriteria(); - testSearchCriteria.addParam("name", userName); - testSearchCriteria.addParam("usersource", vxUser.getUserSource()); - Mockito.when(xUserService.getXUserByUserName(userName)).thenReturn(vxUser); - Mockito.when(xUserService.searchXUsers(testSearchCriteria)).thenReturn(vXUserListSort); - List vXGroupList = new ArrayList(); - final VXGroup vXGroup1 = vxGroup(); - vXGroup1.setName("users"); - vXGroup1.setDescription("users -added for unit testing"); - vXGroupList.add(vXGroup1); - testSearchCriteria.addParam("xUserId", userId); - dbVXUserList = xUserMgr.searchXUsers(testSearchCriteria); - Assert.assertNotNull(dbVXUserList); - testSearchCriteria = createsearchCriteria(); - testSearchCriteria.addParam("name", userName); - testSearchCriteria.addParam("emailaddress", vxUser.getEmailAddress()); - Mockito.when(xUserService.getXUserByUserName(userName)).thenReturn(vxUser); - Mockito.when(xUserService.searchXUsers(testSearchCriteria)).thenReturn(vXUserListSort); - dbVXUserList = xUserMgr.searchXUsers(testSearchCriteria); - } - - @Test - public void test48searchXGroups() { - setupUser(); - VXGroup vXGroup = vxGroup(); - VXGroupList vXGroupListSort = new VXGroupList(); - List vXGroups = new ArrayList(); - vXGroups.add(vXGroup); - vXGroupListSort.setVXGroups(vXGroups); - String groupName = vXGroup.getName(); - SearchCriteria testSearchCriteria = createsearchCriteria(); - testSearchCriteria.addParam("name", groupName); - Mockito.when(xGroupService.getGroupByGroupName(groupName)).thenReturn(vXGroup); - Mockito.when(xGroupService.searchXGroups(testSearchCriteria)).thenReturn(vXGroupListSort); - VXGroupList vXGroupList = xUserMgr.searchXGroups(testSearchCriteria); - testSearchCriteria.addParam("isvisible", "true"); - vXGroupList = xUserMgr.searchXGroups(testSearchCriteria); - Assert.assertNotNull(vXGroupList); - testSearchCriteria = createsearchCriteria(); - testSearchCriteria.addParam("name", groupName); - testSearchCriteria.addParam("groupsource", 1L); - Mockito.when(xGroupService.searchXGroups(testSearchCriteria)).thenReturn(vXGroupListSort); - vXGroupList = xUserMgr.searchXGroups(testSearchCriteria); - Assert.assertNotNull(vXGroupList); - testSearchCriteria = createsearchCriteria(); - testSearchCriteria.addParam("name", groupName); - testSearchCriteria.addParam("userid", userId); - VXUser loggedInUser = vxUser(); - List loggedInUserRole = new ArrayList(); - loggedInUserRole.add(RangerConstants.ROLE_USER); - loggedInUser.setId(8L); - loggedInUser.setName("testuser"); - loggedInUser.setUserRoleList(loggedInUserRole); - Mockito.when(xUserService.getXUserByUserName(userLoginID)).thenReturn(loggedInUser); - Mockito.when(xGroupService.searchXGroups(testSearchCriteria)).thenReturn(vXGroupListSort); - - List groupIdList = new ArrayList(); - groupIdList.add(2L); - XXGroupUserDao mockxxGroupUserDao = Mockito.mock(XXGroupUserDao.class); - Mockito.when(daoManager.getXXGroupUser()).thenReturn(mockxxGroupUserDao); - Mockito.when(mockxxGroupUserDao.findGroupIdListByUserId(loggedInUser.getId())).thenReturn(groupIdList); - XXModuleDefDao modDef = Mockito.mock(XXModuleDefDao.class); - Mockito.when(daoManager.getXXModuleDef()).thenReturn(modDef); - List lstModule = new ArrayList(); - lstModule.add(RangerConstants.MODULE_USER_GROUPS); - Mockito.when(modDef.findAccessibleModulesByUserId(Mockito.anyLong(), - Mockito.anyLong())).thenReturn(lstModule); - xUserMgr.searchXGroups(testSearchCriteria); - } - - @Test - public void test49createServiceConfigUser() { - XXUserDao xxUserDao = Mockito.mock(XXUserDao.class); - VXUser vxUser = vxUser(); - XXUser xXUser = xxUser(vxUser); - VXPortalUser userProfile = userProfile(); - Collection userRoleList =getRoleList(); - VXUserPermission vXUserPermission=vxUserPermission(); - XXUserPermission xUserPermissionObj = xxUserPermission(); - xUserPermissionObj.setModuleId(vXUserPermission.getModuleId()); - xUserPermissionObj.setUserId(vXUserPermission.getUserId()); - Mockito.when(daoManager.getXXUser()).thenReturn(xxUserDao); - Mockito.when(xxUserDao.findByUserName(vxUser.getName())).thenReturn(xXUser); - Mockito.when(xUserService.populateViewBean(xXUser)).thenReturn(vxUser); - VXUser serviceConfigUser=xUserMgr.createServiceConfigUser(vxUser.getName()); - Assert.assertNotNull(serviceConfigUser); - Assert.assertEquals(xXUser.getName(), serviceConfigUser.getName()); - Mockito.when(daoManager.getXXUser()).thenReturn(xxUserDao); - Mockito.when(xxUserDao.findByUserName(vxUser.getName())).thenReturn(null, xXUser); - Mockito.when(daoManager.getXXUser()).thenReturn(xxUserDao); - UserSessionBase userSession = Mockito.mock(UserSessionBase.class); - Set userSessions = new HashSet(); - userSessions.add(userSession); - - userProfile.setUserRoleList(userRoleList); - List xUserPermissionsList = new ArrayList(); - XXUserPermission xUserPermissionObj2 = new XXUserPermission(); - xUserPermissionObj2.setAddedByUserId(userId); - xUserPermissionObj2.setCreateTime(new Date()); - xUserPermissionObj2.setId(userId); - xUserPermissionObj2.setIsAllowed(1); - xUserPermissionObj2.setModuleId(1L); - xUserPermissionObj2.setUpdatedByUserId(userId); - xUserPermissionObj2.setUpdateTime(new Date()); - xUserPermissionObj2.setUserId(userId); - xUserPermissionsList.add(xUserPermissionObj2); - - serviceConfigUser=xUserMgr.createServiceConfigUser(vxUser.getName()); - Assert.assertNotNull(serviceConfigUser); - Assert.assertEquals(xXUser.getName(), serviceConfigUser.getName()); - } - - @Test - public void test50createServiceConfigUser_WithBlankName() { - destroySession(); - setup(); - Mockito.when(restErrorUtil.createRESTException("Please provide a valid username.",MessageEnums.INVALID_INPUT_DATA)).thenThrow(new WebApplicationException()); - thrown.expect(WebApplicationException.class); - xUserMgr.createServiceConfigUser(null); - } - - @Test - public void test51assignPermissionToUser() { - XXModuleDefDao xXModuleDefDao = Mockito.mock(XXModuleDefDao.class); - XXUserPermissionDao xXUserPermissionDao= Mockito.mock(XXUserPermissionDao.class); - XXUserDao xxUserDao = Mockito.mock(XXUserDao.class); - VXPortalUser vXPortalUser = userProfile(); - Collection userRoleList = new ArrayList(); - userRoleList.add("ROLE_USER"); - vXPortalUser.setUserRoleList(userRoleList); - VXUser vxUser = vxUser(); - XXUser xXUser = xxUser(vxUser); - List xXModuleDefs = xxModuleDefs(); - VXUserPermission userPermission = vxUserPermission(); - List userPermList = new ArrayList(); - userPermList.add(userPermission); - List xUserPermissionsList = new ArrayList(); - XXUserPermission xUserPermissionObj = xxUserPermission(); - xUserPermissionObj.setModuleId(userPermission.getModuleId()); - xUserPermissionObj.setUserId(userPermission.getUserId()); - xUserPermissionsList.add(xUserPermissionObj); - Mockito.when(daoManager.getXXModuleDef()).thenReturn(xXModuleDefDao); - Mockito.when(xXModuleDefDao.getAll()).thenReturn(xXModuleDefs); - Mockito.when(daoManager.getXXUserPermission()).thenReturn(xXUserPermissionDao); - Mockito.when(xXUserPermissionDao.findByModuleIdAndPortalUserId(vXPortalUser.getId(),xXModuleDefs.get(0).getId())).thenReturn(xUserPermissionObj); - Mockito.when(daoManager.getXXUser()).thenReturn(xxUserDao); - Mockito.when(xxUserDao.findByPortalUserId(vXPortalUser.getId())).thenReturn(xXUser); - UserSessionBase userSession = Mockito.mock(UserSessionBase.class); - Set userSessions = new HashSet(); - userSessions.add(userSession); - Mockito.when(xUserPermissionService.createResource((VXUserPermission) Mockito.any())).thenReturn(userPermission); - Mockito.when(xUserPermissionService.populateViewBean(xUserPermissionObj)).thenReturn(userPermission); - Mockito.when(xUserPermissionService.updateResource((VXUserPermission) Mockito.any())).thenReturn(userPermission); - Mockito.when(sessionMgr.getActiveUserSessionsForPortalUserId(userId)).thenReturn(userSessions); - xUserMgr.assignPermissionToUser(vXPortalUser,true); - userRoleList.clear(); - userRoleList.add("ROLE_SYS_ADMIN"); - vXPortalUser.setUserRoleList(userRoleList); - xUserMgr.assignPermissionToUser(vXPortalUser,true); - userRoleList.clear(); - userRoleList.add("ROLE_KEY_ADMIN"); - vXPortalUser.setUserRoleList(userRoleList); - xUserMgr.assignPermissionToUser(vXPortalUser,true); - userRoleList.clear(); - userRoleList.add("ROLE_KEY_ADMIN_AUDITOR"); - vXPortalUser.setUserRoleList(userRoleList); - xUserMgr.assignPermissionToUser(vXPortalUser,true); - userRoleList.clear(); - userRoleList.add("ROLE_ADMIN_AUDITOR"); - vXPortalUser.setUserRoleList(userRoleList); - xUserMgr.assignPermissionToUser(vXPortalUser,true); - Assert.assertNotNull(xXModuleDefs); - } - - @Test - public void test52createXGroupUserFromMap() { - setup(); - VXGroup vxGroup=vxGroup(); - VXUser vxUser = vxUser(); - List vXUserList=new ArrayList(); - vXUserList.add(vxUser); - VXGroupUserInfo vxGUInfo = new VXGroupUserInfo(); - vxGUInfo.setXgroupInfo(vxGroup); - vxGUInfo.setXuserInfo(vXUserList); - XXUserDao xxUserDao = Mockito.mock(XXUserDao.class); - XXPortalUserDao userDao = Mockito.mock(XXPortalUserDao.class); - XXPortalUserRoleDao userRoleDao = Mockito.mock(XXPortalUserRoleDao.class); - XXModuleDefDao xXModuleDefDao = Mockito.mock(XXModuleDefDao.class); - XXUser xXUser = xxUser(vxUser); - VXPortalUser userProfile = userProfile(); - XXPortalUser xXPortalUser = xxPortalUser(userProfile); - xXPortalUser.setUserSource(RangerCommonEnums.USER_EXTERNAL); - List lstRole = new ArrayList(); - lstRole.add(RangerConstants.ROLE_SYS_ADMIN); - List xXModuleDefs=new ArrayList(); - Mockito.when(daoManager.getXXUser()).thenReturn(xxUserDao); - Mockito.when(xxUserDao.findByUserName(vxUser.getName())).thenReturn(xXUser); - Mockito.when(daoManager.getXXPortalUser()).thenReturn(userDao); - Mockito.when(userDao.findByLoginId(vxUser.getName())).thenReturn(xXPortalUser); - Mockito.when(xGroupService.createXGroupWithOutLogin(vxGroup)).thenReturn(vxGroup); - Mockito.when(daoManager.getXXPortalUserRole()).thenReturn(userRoleDao); - Mockito.when(userMgr.mapXXPortalUserToVXPortalUserForDefaultAccount(xXPortalUser)).thenReturn(userProfile); - Mockito.when(daoManager.getXXModuleDef()).thenReturn(xXModuleDefDao); - Mockito.when(xXModuleDefDao.getAll()).thenReturn(xXModuleDefs); - VXGroupUserInfo vxGUInfoObj=xUserMgr.createXGroupUserFromMap(vxGUInfo); - Assert.assertNotNull(vxGUInfoObj); - } - - @Test - public void test53getXGroupUserFromMap() { - setup(); - VXGroup vxGroup=vxGroup(); - VXUser vxUser = vxUser(); - List vXUserList=new ArrayList(); - vXUserList.add(vxUser); - VXGroupUserInfo vxGUInfo = new VXGroupUserInfo(); - vxGUInfo.setXgroupInfo(vxGroup); - vxGUInfo.setXuserInfo(vXUserList); - XXGroupDao xxGroupDao = Mockito.mock(XXGroupDao.class); - XXGroup xxGroup = new XXGroup(); - xxGroup.setId(vxGroup.getId()); - xxGroup.setName(vxGroup.getName()); - xxGroup.setDescription(vxGroup.getDescription()); - xxGroup.setIsVisible(vxGroup.getIsVisible()); - VXPortalUser userProfile = userProfile(); - XXPortalUser xXPortalUser = xxPortalUser(userProfile); - xXPortalUser.setUserSource(RangerCommonEnums.USER_EXTERNAL); - VXGroupUserList vxGroupUserList = new VXGroupUserList(); - List vXGroupUsers = new ArrayList(); - VXGroupUser vxGroupUser = vxGroupUser(); - vXGroupUsers.add(vxGroupUser); - vxGroupUserList.setVXGroupUsers(vXGroupUsers); - List lstRole = new ArrayList(); - lstRole.add(RangerConstants.ROLE_USER); - Mockito.when(daoManager.getXXGroup()).thenReturn(xxGroupDao); - SearchCriteria searchCriteria = createsearchCriteria(); - searchCriteria.addParam("xGroupId", xxGroup.getId()); - Mockito.when(xxGroupDao.findByGroupName("")).thenReturn(null); - VXGroupUserInfo vxGUInfoObjNull=xUserMgr.getXGroupUserFromMap(""); - Assert.assertNull(vxGUInfoObjNull.getXgroupInfo()); - Mockito.when(xxGroupDao.findByGroupName(Mockito.anyString())).thenReturn(xxGroup); - Mockito.when(xGroupService.populateViewBean(xxGroup)).thenReturn(vxGroup); - Mockito.when(xGroupUserService.searchXGroupUsers((SearchCriteria) Mockito.any())).thenReturn(vxGroupUserList); - XXUser xXUser = xxUser(vxUser); - XXUserDao xxUserDao = Mockito.mock(XXUserDao.class); - Mockito.when(daoManager.getXXUser()).thenReturn(xxUserDao); - Mockito.when(xxUserDao.getById(userId)).thenReturn(xXUser); - XXPortalUserDao xXPortalUserDao = Mockito.mock(XXPortalUserDao.class); - Mockito.when(daoManager.getXXPortalUser()).thenReturn(xXPortalUserDao); - Mockito.when(xXPortalUserDao.findByLoginId(xXUser.getName().trim())).thenReturn(xXPortalUser); - XXPortalUserRoleDao xXPortalUserRoleDao = Mockito.mock(XXPortalUserRoleDao.class); - Mockito.when(daoManager.getXXPortalUserRole()).thenReturn(xXPortalUserRoleDao); - vxGUInfoObjNull=xUserMgr.getXGroupUserFromMap(xxGroup.getName()); - } - - @Test - public void test54modifyUserActiveStatus() { - setup(); - XXUserDao xxUserDao = Mockito.mock(XXUserDao.class); - VXPortalUser userProfile = userProfile(); - VXUser vxUser = vxUser(); - XXUser xXUser = xxUser(vxUser); - XXPortalUser xXPortalUser = xxPortalUser(userProfile); - xXPortalUser.setUserSource(RangerCommonEnums.USER_EXTERNAL); - Mockito.when(daoManager.getXXUser()).thenReturn(xxUserDao); - Mockito.when(xxUserDao.getById(xXUser.getId())).thenReturn(xXUser); - Mockito.when(userMgr.updateUser(userProfile)).thenReturn(xXPortalUser); - HashMap statusMap= new HashMap(); - statusMap.put(xXUser.getId(), 1); - Mockito.when(userMgr.getUserProfileByLoginId(vxUser.getName())).thenReturn(userProfile); - xUserMgr.modifyUserActiveStatus(statusMap); - } - - @Test - public void test55updateXGroupUser() { - setup(); - VXUser vxUser = vxUser(); - vxUser.setUserSource(RangerCommonEnums.USER_EXTERNAL); - VXGroupUser vxGroupUser = vxGroupUser(); - Mockito.when(xGroupUserService.updateResource((VXGroupUser) Mockito.any())).thenReturn(vxGroupUser); - VXGroupUser dbvxUser = xUserMgr.updateXGroupUser(vxGroupUser); - Assert.assertNotNull(dbvxUser); - Assert.assertEquals(dbvxUser.getId(), vxGroupUser.getId()); - Assert.assertEquals(dbvxUser.getName(), vxGroupUser.getName()); - Mockito.verify(xGroupUserService).updateResource((VXGroupUser) Mockito.any()); - } - - @Test - public void test59deleteXGroupUser() { - setup(); - VXUser vxUser = vxUser(); - vxUser.setUserSource(RangerCommonEnums.USER_EXTERNAL); - VXGroupUser vXGroupUser = vxGroupUser(); - Mockito.when(xGroupUserService.deleteResource((Long) Mockito.any())).thenReturn(true); - xUserMgr.deleteXGroupUser(vXGroupUser.getId(),true); - Mockito.verify(xGroupUserService).deleteResource((Long) Mockito.any()); - } - - @Test - public void test60postUserGroupAuditInfo() { - setup(); - VXUgsyncAuditInfo vxUgsyncAuditInfo=new VXUgsyncAuditInfo(); - vxUgsyncAuditInfo.setId(userId); - Mockito.when(xUgsyncAuditInfoService.createUgsyncAuditInfo((VXUgsyncAuditInfo) Mockito.any())).thenReturn(vxUgsyncAuditInfo); - VXUgsyncAuditInfo dbVXUgsyncAuditInfo = xUserMgr.postUserGroupAuditInfo(vxUgsyncAuditInfo); - Assert.assertNotNull(dbVXUgsyncAuditInfo); - Assert.assertEquals(dbVXUgsyncAuditInfo.getId(), vxUgsyncAuditInfo.getId()); - Mockito.verify(xUgsyncAuditInfoService).createUgsyncAuditInfo((VXUgsyncAuditInfo) Mockito.any()); - } - - @Test - public void test61createXGroupUser() { - setup(); - VXUser vxUser = vxUser(); - vxUser.setUserSource(RangerCommonEnums.USER_EXTERNAL); - VXGroupUser vxGroupUser = vxGroupUser(); - Mockito.when(xGroupUserService.createXGroupUserWithOutLogin((VXGroupUser) Mockito.any())).thenReturn(vxGroupUser); - VXGroupUser dbvxUser = xUserMgr.createXGroupUser(vxGroupUser); - Assert.assertNotNull(dbvxUser); - Assert.assertEquals(dbvxUser.getId(), vxGroupUser.getId()); - Assert.assertEquals(dbvxUser.getName(), vxGroupUser.getName()); - Mockito.verify(xGroupUserService).createXGroupUserWithOutLogin((VXGroupUser) Mockito.any()); - } - - @Test - public void test62createXGroupUser() { - setup(); - VXGroupUser vXGroupUser = vxGroupUser(); - VXGroup vxGroup=vxGroup(); - Mockito.when(xGroupService.readResource(userId)).thenReturn(vxGroup); - Mockito.when(xGroupUserService.createResource((VXGroupUser) Mockito.any())).thenReturn(vXGroupUser); - VXGroupUser dbVXGroupUser = xUserMgr.createXGroupUser(userId,vxGroup.getId()); - Assert.assertNotNull(dbVXGroupUser); - Assert.assertEquals(userId, dbVXGroupUser.getId()); - Assert.assertEquals(dbVXGroupUser.getOwner(), vXGroupUser.getOwner()); - Assert.assertEquals(dbVXGroupUser.getName(), vXGroupUser.getName()); - Assert.assertEquals(dbVXGroupUser.getUserId(), vXGroupUser.getUserId()); - Assert.assertEquals(dbVXGroupUser.getUpdatedBy(),vXGroupUser.getUpdatedBy()); - } - - @Test - public void test63searchXUsers_Cases() { - VXUser vxUser = vxUser(); - VXUserList vXUserListSort = new VXUserList(); - List vXUsers = new ArrayList(); - vXUsers.add(vxUser); - vXUserListSort.setVXUsers(vXUsers); - String userName = vxUser.getName(); - SearchCriteria testSearchCriteria = createsearchCriteria(); - testSearchCriteria.addParam("name", userName); - Mockito.when(xUserService.getXUserByUserName(userName)).thenReturn(vxUser); - Mockito.when(xUserService.searchXUsers(testSearchCriteria)).thenReturn(vXUserListSort); - VXUserList dbVXUserList = xUserMgr.searchXUsers(testSearchCriteria); - Assert.assertNotNull(dbVXUserList); - testSearchCriteria.addParam("isvisible", "true"); - dbVXUserList = xUserMgr.searchXUsers(testSearchCriteria); - Assert.assertNotNull(dbVXUserList); - testSearchCriteria = createsearchCriteria(); - testSearchCriteria.addParam("name", userName); - testSearchCriteria.addParam("status", RangerCommonEnums.USER_EXTERNAL); - Mockito.when(xUserService.searchXUsers(testSearchCriteria)).thenReturn(vXUserListSort); - dbVXUserList = xUserMgr.searchXUsers(testSearchCriteria); - Assert.assertNotNull(dbVXUserList); - testSearchCriteria = createsearchCriteria(); - testSearchCriteria.addParam("name", userName); - testSearchCriteria.addParam("usersource", 1L); - Mockito.when(xUserService.searchXUsers(testSearchCriteria)).thenReturn(vXUserListSort); - dbVXUserList = xUserMgr.searchXUsers(testSearchCriteria); - Assert.assertNotNull(dbVXUserList); - testSearchCriteria = createsearchCriteria(); - testSearchCriteria.addParam("name", userName); - testSearchCriteria.addParam("emailaddress", "new"+vxUser.getEmailAddress()); - Mockito.when(xUserService.searchXUsers(testSearchCriteria)).thenReturn(vXUserListSort); - dbVXUserList = xUserMgr.searchXUsers(testSearchCriteria); - Assert.assertNotNull(dbVXUserList); - testSearchCriteria = createsearchCriteria(); - testSearchCriteria.addParam("name", userName); - testSearchCriteria.addParam("userrole", RangerConstants.ROLE_USER); - Mockito.when(xUserService.searchXUsers(testSearchCriteria)).thenReturn(vXUserListSort); - dbVXUserList = xUserMgr.searchXUsers(testSearchCriteria); - Assert.assertNotNull(dbVXUserList); - testSearchCriteria = createsearchCriteria(); - testSearchCriteria.addParam("name", userName); - testSearchCriteria.addParam("userrolelist", vxUser.getUserRoleList()); - Mockito.when(xUserService.searchXUsers(testSearchCriteria)).thenReturn(vXUserListSort); - dbVXUserList = xUserMgr.searchXUsers(testSearchCriteria); - Assert.assertNotNull(dbVXUserList); - } - - @Test - public void test64checkAccessRolesAdmin() { - destroySession(); - setup(); - List userRoleList = new ArrayList(); - userRoleList.add("ROLE_KEY_ADMIN"); - Mockito.when(restErrorUtil.create403RESTException(Mockito.anyString())).thenThrow(new WebApplicationException()); - thrown.expect(WebApplicationException.class); - xUserMgr.checkAccessRoles(userRoleList); - } - - @Test - public void test65checkAccessRolesKeyAdmin() { - destroySession(); - List userRoleList = new ArrayList(); - setupKeyAdmin(); - userRoleList.add("ROLE_SYS_ADMIN"); - Mockito.when(restErrorUtil.create403RESTException(Mockito.anyString())).thenThrow(new WebApplicationException()); - thrown.expect(WebApplicationException.class); - xUserMgr.checkAccessRoles(userRoleList); - } - - @Test - public void test66checkAccessRolesUser() { - destroySession(); - setupUser(); - List userRoleList = new ArrayList(); - userRoleList.add("ROLE_USER"); - Mockito.when(restErrorUtil.create403RESTException(Mockito.anyString())).thenThrow(new WebApplicationException()); - thrown.expect(WebApplicationException.class); - xUserMgr.checkAccessRoles(userRoleList); - } - - @Test - public void test67checkAccessRolesUser() { - destroySession(); - List userRoleList = new ArrayList(); - userRoleList.add("ROLE_USER"); - VXResponse vXResponse = new VXResponse(); - vXResponse.setStatusCode(HttpServletResponse.SC_UNAUTHORIZED); - vXResponse.setMsgDesc("Bad Credentials"); - Mockito.when(restErrorUtil.generateRESTException((VXResponse) Mockito.any())).thenThrow(new WebApplicationException()); - thrown.expect(WebApplicationException.class); - xUserMgr.checkAccessRoles(userRoleList); - } - - @Test - public void test68getGroupByGroupName() { - destroySession(); - VXGroup vxGroup=vxGroup(); - Mockito.when(xGroupService.getGroupByGroupName(vxGroup.getName())).thenReturn(vxGroup); - VXGroup vxGroup1=xUserMgr.getGroupByGroupName(vxGroup.getName()); - Assert.assertNotNull(vxGroup1); - Mockito.when(xGroupService.getGroupByGroupName(Mockito.anyString())).thenReturn(null); - Mockito.when(restErrorUtil.createRESTException(vxGroup.getName() + " is Not Found", MessageEnums.DATA_NOT_FOUND)).thenThrow(new WebApplicationException()); - thrown.expect(WebApplicationException.class); - VXGroup vxGroup2=xUserMgr.getGroupByGroupName(vxGroup.getName()); - Assert.assertNull(vxGroup2); - } - - @Test - public void test69denySelfRoleChange() { - destroySession(); - setupUser(); - Mockito.when(restErrorUtil.create403RESTException(Mockito.anyString())).thenThrow(new WebApplicationException()); - thrown.expect(WebApplicationException.class); - xUserMgr.denySelfRoleChange(userProfile().getLoginId()); - } - - @Test - public void test70denySelfRoleChange() { - destroySession(); - setup(); - Mockito.when(restErrorUtil.create403RESTException(Mockito.anyString())).thenThrow(new WebApplicationException()); - thrown.expect(WebApplicationException.class); - xUserMgr.denySelfRoleChange(adminLoginID); - } - - @Test - public void test71denySelfRoleChange() { - destroySession(); - setupKeyAdmin(); - Mockito.when(restErrorUtil.create403RESTException(Mockito.anyString())).thenThrow(new WebApplicationException()); - thrown.expect(WebApplicationException.class); - xUserMgr.denySelfRoleChange(keyadminLoginID); - } - - @Test - public void test72UpdateXUser() { - destroySession(); - setup(); - Collection existingRoleList = new ArrayList(); - existingRoleList.add(RangerConstants.ROLE_USER); - Collection reqRoleList = new ArrayList(); - reqRoleList.add(RangerConstants.ROLE_SYS_ADMIN); - Collection groupIdList = new ArrayList(); - groupIdList.add(userId); - VXUser vxUser = vxUser(); - vxUser.setUserRoleList(reqRoleList); - vxUser.setUserSource(RangerCommonEnums.USER_EXTERNAL); - vxUser.setGroupIdList(groupIdList); - vxUser.setFirstName("user1"); - vxUser.setLastName("null"); - vxUser.setPassword("*****"); - Mockito.when(xUserService.updateResource(vxUser)).thenReturn(vxUser); - VXPortalUser oldUserProfile = userProfile(); - oldUserProfile.setUserSource(RangerCommonEnums.USER_APP); - oldUserProfile.setPassword(vxUser.getPassword()); - VXPortalUser vXPortalUser = userProfile(); - vXPortalUser.setUserRoleList(existingRoleList); - Mockito.when(userMgr.getUserProfileByLoginId(vxUser.getName())).thenReturn(oldUserProfile); - XXPortalUser xXPortalUser = xxPortalUser(vXPortalUser); - Mockito.when(userMgr.updateUserWithPass((VXPortalUser) Mockito.any())).thenReturn(xXPortalUser); - List xUserPermissionsList = new ArrayList(); - XXUserPermission xUserPermissionObj = new XXUserPermission(); - xUserPermissionObj.setAddedByUserId(userId); - xUserPermissionObj.setCreateTime(new Date()); - xUserPermissionObj.setId(userId); - xUserPermissionObj.setIsAllowed(1); - xUserPermissionObj.setModuleId(1L); - xUserPermissionObj.setUpdatedByUserId(userId); - xUserPermissionObj.setUpdateTime(new Date()); - xUserPermissionObj.setUserId(userId); - xUserPermissionsList.add(xUserPermissionObj); - VXGroupUserList vxGroupUserList = vxGroupUserList(); - Mockito.when(xGroupUserService.searchXGroupUsers((SearchCriteria) Mockito.any())).thenReturn(vxGroupUserList); - UserSessionBase userSession = Mockito.mock(UserSessionBase.class); - Set userSessions = new HashSet(); - userSessions.add(userSession); - VXUser loggedInUser = vxUser(); - List loggedInUserRole = new ArrayList(); - loggedInUserRole.add(RangerConstants.ROLE_SYS_ADMIN); - loggedInUser.setId(8L); - loggedInUser.setName("testuser"); - loggedInUser.setUserRoleList(loggedInUserRole); - Mockito.when(xUserService.getXUserByUserName("admin")).thenReturn(loggedInUser); - VXUser dbvxUser = xUserMgr.updateXUser(vxUser); - Assert.assertNotNull(dbvxUser); - Assert.assertEquals(dbvxUser.getId(), vxUser.getId()); - Assert.assertEquals(dbvxUser.getDescription(), vxUser.getDescription()); - Assert.assertEquals(dbvxUser.getName(), vxUser.getName()); - Mockito.verify(xUserService).updateResource(vxUser); - - groupIdList.clear(); - groupIdList.add(9L); - vxUser.setGroupIdList(groupIdList); - vxUser.setPassword("TestUser@1234"); - oldUserProfile.setPassword(vxUser.getPassword()); - vxGroupUserList.setVXGroupUsers(null); - Mockito.when(xGroupUserService.searchXGroupUsers((SearchCriteria) Mockito.any())).thenReturn(vxGroupUserList); - VXGroup vXGroup = vxGroup(); - Mockito.when(xGroupService.readResource(Mockito.anyLong())).thenReturn(vXGroup); - VXGroupUser vXGroupUser = vxGroupUser(); - Mockito.when(xGroupUserService.createResource((VXGroupUser) Mockito.any())).thenReturn(vXGroupUser); - dbvxUser = xUserMgr.updateXUser(vxUser); - Assert.assertNotNull(dbvxUser); - - Mockito.when(userMgr.getUserProfileByLoginId(Mockito.anyString())).thenReturn(null); - Mockito.when(restErrorUtil.createRESTException("user " + vxUser.getName() + " does not exist.",MessageEnums.INVALID_INPUT_DATA)).thenThrow(new WebApplicationException()); - thrown.expect(WebApplicationException.class); - vxUser=xUserMgr.updateXUser(vxUser); - Assert.assertNull(vxUser); - } - - @Test - public void test73restrictSelfAccountDeletion() { - destroySession(); - setupUser(); - Mockito.when(restErrorUtil.generateRESTException((VXResponse)Mockito.any())).thenThrow(new WebApplicationException()); - thrown.expect(WebApplicationException.class); - xUserMgr.restrictSelfAccountDeletion(userProfile().getLoginId()); - } - - @Test - public void test74restrictSelfAccountDeletion() { - destroySession(); - setup(); - Mockito.when(restErrorUtil.generateRESTException((VXResponse)Mockito.any())).thenThrow(new WebApplicationException()); - thrown.expect(WebApplicationException.class); - xUserMgr.restrictSelfAccountDeletion(adminLoginID); - } - - @Test - public void test75restrictSelfAccountDeletion() { - destroySession(); - setupKeyAdmin(); - Mockito.when(restErrorUtil.generateRESTException((VXResponse)Mockito.any())).thenThrow(new WebApplicationException()); - thrown.expect(WebApplicationException.class); - xUserMgr.restrictSelfAccountDeletion(keyadminLoginID); - } - - @Test - public void test76restrictSelfAccountDeletion() { - destroySession(); - Mockito.when(restErrorUtil.generateRESTException((VXResponse)Mockito.any())).thenThrow(new WebApplicationException()); - thrown.expect(WebApplicationException.class); - xUserMgr.restrictSelfAccountDeletion(userProfile().getLoginId()); - } - - @Test - public void test77updateUserRolesPermissions() { - setup(); - List existingRoleList = new ArrayList(); - existingRoleList.add(RangerConstants.ROLE_USER); - List reqRoleList = new ArrayList(); - reqRoleList.add(RangerConstants.ROLE_SYS_ADMIN); - Collection groupIdList = new ArrayList(); - groupIdList.add(userId); - VXUser vxUser = vxUser(); - vxUser.setUserRoleList(reqRoleList); - vxUser.setUserSource(RangerCommonEnums.USER_EXTERNAL); - vxUser.setGroupIdList(groupIdList); - vxUser.setFirstName("null"); - vxUser.setLastName("null"); - vxUser.setPassword("*****"); - VXPortalUser oldUserProfile = userProfile(); - oldUserProfile.setUserSource(RangerCommonEnums.USER_APP); - oldUserProfile.setPassword(vxUser.getPassword()); - oldUserProfile.setUserRoleList(existingRoleList); - VXPortalUser vXPortalUser = userProfile(); - vXPortalUser.setUserRoleList(reqRoleList); - List xUserPermissionsList = new ArrayList(); - XXUserPermission xUserPermissionObj = new XXUserPermission(); - xUserPermissionObj.setAddedByUserId(userId); - xUserPermissionObj.setCreateTime(new Date()); - xUserPermissionObj.setId(userId); - xUserPermissionObj.setIsAllowed(1); - xUserPermissionObj.setModuleId(1L); - xUserPermissionObj.setUpdatedByUserId(userId); - xUserPermissionObj.setUpdateTime(new Date()); - xUserPermissionObj.setUserId(userId); - xUserPermissionsList.add(xUserPermissionObj); - UserSessionBase userSession = Mockito.mock(UserSessionBase.class); - Set userSessions = new HashSet(); - userSessions.add(userSession); - XXUserPermissionDao xUserPermissionDao = Mockito.mock(XXUserPermissionDao.class); - Mockito.when(daoManager.getXXUserPermission()).thenReturn(xUserPermissionDao); - XXModuleDefDao xXModuleDefDao = Mockito.mock(XXModuleDefDao.class); - XXUserPermissionDao xXUserPermissionDao= Mockito.mock(XXUserPermissionDao.class); - XXUserDao xxUserDao = Mockito.mock(XXUserDao.class); - Collection userRoleList = new ArrayList(); - userRoleList.add("ROLE_USER"); - vXPortalUser.setUserRoleList(userRoleList); - XXUser xXUser = xxUser(vxUser); - List xXModuleDefs = xxModuleDefs(); - VXUserPermission userPermission = vxUserPermission(); - List userPermList = new ArrayList(); - userPermList.add(userPermission); - xUserPermissionObj.setModuleId(userPermission.getModuleId()); - xUserPermissionObj.setUserId(userPermission.getUserId()); - xUserPermissionsList.add(xUserPermissionObj); - Mockito.when(daoManager.getXXModuleDef()).thenReturn(xXModuleDefDao); - Mockito.when(xXModuleDefDao.getAll()).thenReturn(xXModuleDefs); - Mockito.when(daoManager.getXXUserPermission()).thenReturn(xXUserPermissionDao); - Mockito.when(daoManager.getXXUser()).thenReturn(xxUserDao); - Mockito.when(xxUserDao.findByPortalUserId(vXPortalUser.getId())).thenReturn(xXUser); - Mockito.when(xXUserPermissionDao.findByUserPermissionId(vXPortalUser.getId())).thenReturn(xUserPermissionsList); - Mockito.when(xUserPermissionService.createResource((VXUserPermission) Mockito.any())).thenReturn(userPermission); - Mockito.when(sessionMgr.getActiveUserSessionsForPortalUserId(userId)).thenReturn(userSessions); - xUserMgr.updateUserRolesPermissions(oldUserProfile,reqRoleList); - } - - @Test - public void test78checkAccess() { - destroySession(); - setupUser(); - VXUser vxUser = vxUser(); - Mockito.when(restErrorUtil.create403RESTException(Mockito.anyString())).thenThrow(new WebApplicationException()); - thrown.expect(WebApplicationException.class); - xUserMgr.checkAccess(vxUser); - } - - @Test - public void test79checkAccess() { - destroySession(); - VXUser vxUser = vxUser(); - VXUser loggedInUser = vxUser(); - List loggedInUserRole = new ArrayList(); - loggedInUserRole.add(RangerConstants.ROLE_SYS_ADMIN); - loggedInUser.setId(8L); - loggedInUser.setName("admin"); - loggedInUser.setUserRoleList(loggedInUserRole); - Mockito.when(restErrorUtil.generateRESTException((VXResponse)Mockito.any())).thenThrow(new WebApplicationException()); - thrown.expect(WebApplicationException.class); - xUserMgr.checkAccess(vxUser); - } - - @Test - public void test80checkAdminAccess() { - destroySession(); - setupUser(); - Mockito.when(restErrorUtil.generateRESTException((VXResponse)Mockito.any())).thenThrow(new WebApplicationException()); - thrown.expect(WebApplicationException.class); - xUserMgr.checkAdminAccess(); - } - - @Test - public void test81checkAdminAccess() { - destroySession(); - Mockito.when(restErrorUtil.generateRESTException((VXResponse)Mockito.any())).thenThrow(new WebApplicationException()); - thrown.expect(WebApplicationException.class); - xUserMgr.checkAdminAccess(); - } - - @Test - public void test82updateXgroupUserForGroupUpdate() { - setup(); - XXGroupUserDao xxGroupUserDao = Mockito.mock(XXGroupUserDao.class); - VXGroup vXGroup = vxGroup(); - List xXGroupUserList = new ArrayList(); - VXGroupUser vxGroupUser = vxGroupUser(); - XXGroupUser xXGroupUser =new XXGroupUser(); - xXGroupUser.setId(vxGroupUser.getId()); - xXGroupUser.setName(vxGroupUser.getName()); - xXGroupUser.setParentGroupId(vxGroupUser.getParentGroupId()); - xXGroupUser.setUserId(vxGroupUser.getUserId()); - xXGroupUserList.add(xXGroupUser); - Mockito.when(daoManager.getXXGroupUser()).thenReturn(xxGroupUserDao); - Mockito.when(xxGroupUserDao.findByGroupId(vXGroup.getId())).thenReturn(xXGroupUserList); - Mockito.when(xGroupUserService.populateViewBean(xXGroupUser)).thenReturn(vxGroupUser); - xUserMgr.updateXgroupUserForGroupUpdate(vXGroup); - Mockito.verify(daoManager).getXXGroupUser(); - Mockito.verify(xxGroupUserDao).findByGroupId(vXGroup.getId()); - } - - @Test - public void test83validatePassword() { - destroySession(); - setup(); - VXUser vxUser = vxUser(); - vxUser.setPassword(null); - Mockito.when(restErrorUtil.createRESTException("serverMsg.xuserMgrValidatePassword", MessageEnums.INVALID_PASSWORD, null, "Password cannot be blank/null", null)).thenThrow(new WebApplicationException()); - thrown.expect(WebApplicationException.class); - xUserMgr.validatePassword(vxUser); - } - - @Test - public void test84validatePassword() { - setup(); - VXUser vxUser = vxUser(); - xUserMgr.validatePassword(vxUser); - } - - @Test - public void test85validatePassword() { - destroySession(); - setup(); - VXUser vxUser = vxUser(); - vxUser.setPassword("password"); - Mockito.when(restErrorUtil.createRESTException("serverMsg.xuserMgrValidatePassword", MessageEnums.INVALID_PASSWORD, null, "Password should be minimum 8 characters, at least one uppercase letter, one lowercase letter and one numeric.", null)).thenThrow(new WebApplicationException()); - thrown.expect(WebApplicationException.class); - xUserMgr.validatePassword(vxUser); - } - - @Test - public void test86deleteXPermMap() { - setup(); - VXResource vxresource=new VXResource(); - XXPermMapDao xXPermMapDao = Mockito.mock(XXPermMapDao.class); - Mockito.when(daoManager.getXXPermMap()).thenReturn(xXPermMapDao); - VXPermMap vXPermMap1=getVXPermMap(); - XXPermMap xXPermMap1=new XXPermMap(); - xXPermMap1.setId(vXPermMap1.getId()); - xXPermMap1.setResourceId(vXPermMap1.getResourceId()); - Mockito.when(xXPermMapDao.getById(xXPermMap1.getId())).thenReturn(xXPermMap1); - Mockito.when(xResourceService.readResource(xXPermMap1.getResourceId())).thenReturn(vxresource); - Mockito.when(xPermMapService.deleteResource(Mockito.anyLong())).thenReturn(true); - xUserMgr.deleteXPermMap(vXPermMap1.getId(),true); - } - - @Test - public void test87deleteXPermMap() { - destroySession(); - setup(); - VXResource vxresource=new VXResource(); - XXPermMapDao xXPermMapDao = Mockito.mock(XXPermMapDao.class); - Mockito.when(daoManager.getXXPermMap()).thenReturn(xXPermMapDao); - VXPermMap vXPermMap1=getVXPermMap(); - XXPermMap xXPermMap1=new XXPermMap(); - xXPermMap1.setId(vXPermMap1.getId()); - xXPermMap1.setResourceId(vXPermMap1.getResourceId()); - Mockito.when(xXPermMapDao.getById(xXPermMap1.getId())).thenReturn(xXPermMap1); - Mockito.when(xResourceService.readResource(xXPermMap1.getResourceId())).thenReturn(vxresource); - Mockito.when(xResourceService.readResource(xXPermMap1.getResourceId())).thenReturn(null); - Mockito.when(restErrorUtil.createRESTException("Invalid Input Data - No resource found with Id: " + xXPermMap1.getResourceId(), MessageEnums.INVALID_INPUT_DATA)).thenThrow(new WebApplicationException()); - thrown.expect(WebApplicationException.class); - xUserMgr.deleteXPermMap(vXPermMap1.getId(),true); - } - - @Test - public void test88deleteXPermMap() { - destroySession(); - setup(); - VXPermMap vXPermMap1=getVXPermMap(); - XXPermMap xXPermMap1=new XXPermMap(); - xXPermMap1.setId(vXPermMap1.getId()); - xXPermMap1.setResourceId(vXPermMap1.getResourceId()); - Mockito.when(restErrorUtil.createRESTException("serverMsg.modelMgrBaseDeleteModel", MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY)).thenThrow(new WebApplicationException()); - thrown.expect(WebApplicationException.class); - xUserMgr.deleteXPermMap(vXPermMap1.getId(),false); - } - - @Test - public void test89deleteXAuditMap() { - destroySession(); - setup(); - VXResource vxresource=new VXResource(); - XXAuditMapDao xXAuditMapDao = Mockito.mock(XXAuditMapDao.class); - Mockito.when(daoManager.getXXAuditMap()).thenReturn(xXAuditMapDao); - VXAuditMap vXAuditMap=getVXAuditMap(); - XXAuditMap xXAuditMap=new XXAuditMap(); - xXAuditMap.setId(vXAuditMap.getId()); - xXAuditMap.setResourceId(vXAuditMap.getResourceId()); - Mockito.when(xXAuditMapDao.getById(vXAuditMap.getId())).thenReturn(xXAuditMap); - Mockito.when(xResourceService.readResource(xXAuditMap.getResourceId())).thenReturn(vxresource); - Mockito.when(xAuditMapService.deleteResource(Mockito.anyLong())).thenReturn(true); - xUserMgr.deleteXAuditMap(vXAuditMap.getId(),true); - Mockito.when(xResourceService.readResource(xXAuditMap.getResourceId())).thenReturn(null); - Mockito.when(restErrorUtil.createRESTException("Invalid Input Data - No resource found with Id: " + xXAuditMap.getResourceId(), MessageEnums.INVALID_INPUT_DATA)).thenThrow(new WebApplicationException()); - thrown.expect(WebApplicationException.class); - xUserMgr.deleteXAuditMap(vXAuditMap.getId(),true); - } - - @Test - public void test90getXPermMapSearchCount() { - SearchCriteria testSearchCriteria = createsearchCriteria(); - testSearchCriteria.addParam("xUserId", userId); - VXPermMap vXPermMap=getVXPermMap(); - List vXPermMapList=new ArrayList(); - vXPermMapList.add(vXPermMap); - VXPermMapList permMapList=new VXPermMapList(); - permMapList.setVXPermMaps(vXPermMapList); - Mockito.when(xPermMapService.searchXPermMaps((SearchCriteria) Mockito.any())).thenReturn(permMapList); - VXLong vXLong = new VXLong(); - vXLong.setValue(permMapList.getListSize()); - VXLong vXLong1=xUserMgr.getXPermMapSearchCount(testSearchCriteria); - Assert.assertEquals(vXLong.getValue(), vXLong1.getValue()); - } - - @Test - public void test91getXAuditMapSearchCount() { - SearchCriteria testSearchCriteria = createsearchCriteria(); - testSearchCriteria.addParam("xUserId", userId); - VXAuditMap vXAuditMap=getVXAuditMap(); - List vXAuditMapList=new ArrayList(); - vXAuditMapList.add(vXAuditMap); - VXAuditMapList auditMapList=new VXAuditMapList(); - auditMapList.setVXAuditMaps(vXAuditMapList); - Mockito.when(xAuditMapService.searchXAuditMaps((SearchCriteria) Mockito.any())).thenReturn(auditMapList); - VXLong vXLong = new VXLong(); - vXLong.setValue(auditMapList.getListSize()); - VXLong vXLong1=xUserMgr.getXAuditMapSearchCount(testSearchCriteria); - Assert.assertEquals(vXLong.getValue(), vXLong1.getValue()); - } - - @Test - public void test92searchXPermMap() { - SearchCriteria testSearchCriteria = createsearchCriteria(); - testSearchCriteria.addParam("xUserId", userId); - VXResource vxresource=new VXResource(); - VXPermMap vXPermMap=getVXPermMap(); - List vXPermMapList=new ArrayList(); - vXPermMapList.add(vXPermMap); - VXPermMapList permMapList=new VXPermMapList(); - permMapList.setVXPermMaps(vXPermMapList); - Mockito.when(xPermMapService.searchXPermMaps((SearchCriteria) Mockito.any())).thenReturn(permMapList); - List xResourceList = new ArrayList(); - XXResource xRes = new XXResource(); - xRes.setId(userId); - xRes.setName("hadoopdev"); - xRes.setIsRecursive(AppConstants.BOOL_TRUE); - xRes.setResourceStatus(AppConstants.STATUS_ENABLED); - xResourceList.add(xRes); - XXResourceDao xxResourceDao = Mockito.mock(XXResourceDao.class); - Mockito.when(daoManager.getXXResource()).thenReturn(xxResourceDao); - Mockito.when(xxResourceDao.getById(Mockito.anyLong())).thenReturn(xRes); - Mockito.when(xResourceService.populateViewBean(xRes)).thenReturn(vxresource); - VXResponse vXResponse = new VXResponse(); - vXResponse.setStatusCode(VXResponse.STATUS_SUCCESS); - Mockito.when(msBizUtil.hasPermission(vxresource, AppConstants.XA_PERM_TYPE_ADMIN)).thenReturn(vXResponse); - VXPermMapList returnList=xUserMgr.searchXPermMaps(testSearchCriteria); - Assert.assertNotNull(returnList); - Assert.assertEquals(permMapList.getListSize(), returnList.getListSize()); - } - - @Test - public void test93searchXAuditMap() { - SearchCriteria testSearchCriteria = createsearchCriteria(); - testSearchCriteria.addParam("xUserId", userId); - VXResource vxresource=new VXResource(); - VXAuditMap vXAuditMap=getVXAuditMap(); - List vXAuditMapList=new ArrayList(); - vXAuditMapList.add(vXAuditMap); - VXAuditMapList auditMapList=new VXAuditMapList(); - auditMapList.setVXAuditMaps(vXAuditMapList); - Mockito.when(xAuditMapService.searchXAuditMaps((SearchCriteria) Mockito.any())).thenReturn(auditMapList); - List xResourceList = new ArrayList(); - XXResource xRes = new XXResource(); - xRes.setId(userId); - xRes.setName("hadoopdev"); - xRes.setIsRecursive(AppConstants.BOOL_TRUE); - xRes.setResourceStatus(AppConstants.STATUS_ENABLED); - xResourceList.add(xRes); - XXResourceDao xxResourceDao = Mockito.mock(XXResourceDao.class); - Mockito.when(daoManager.getXXResource()).thenReturn(xxResourceDao); - Mockito.when(xxResourceDao.getById(Mockito.anyLong())).thenReturn(xRes); - Mockito.when(xResourceService.populateViewBean(xRes)).thenReturn(vxresource); - VXResponse vXResponse = new VXResponse(); - vXResponse.setStatusCode(VXResponse.STATUS_SUCCESS); - Mockito.when(msBizUtil.hasPermission(vxresource, AppConstants.XA_PERM_TYPE_ADMIN)).thenReturn(vXResponse); - VXAuditMapList returnList=xUserMgr.searchXAuditMaps(testSearchCriteria); - Assert.assertNotNull(returnList); - Assert.assertEquals(auditMapList.getListSize(), returnList.getListSize()); - } - - @Test - public void test94DeleteXUser() { - setup(); - boolean force = false; - VXUser vXUser = vxUser(); - XXUser xXUser = new XXUser(); - XXUserDao xXUserDao = Mockito.mock(XXUserDao.class); - Mockito.when(daoManager.getXXUser()).thenReturn(xXUserDao); - Mockito.when(xXUserDao.getById(vXUser.getId())).thenReturn(xXUser); - Mockito.when(xUserService.populateViewBean(xXUser)).thenReturn(vXUser); - VXGroupUserList vxGroupUserList=new VXGroupUserList(); - Mockito.when(xGroupUserService.searchXGroupUsers((SearchCriteria) Mockito.any())).thenReturn(vxGroupUserList); - VXAuditMapList vXAuditMapList = new VXAuditMapList(); - Mockito.when(xAuditMapService.searchXAuditMaps((SearchCriteria) Mockito.any())).thenReturn(vXAuditMapList); - VXPortalUser vXPortalUser = userProfile(); - XXPortalUser xXPortalUser = xxPortalUser(vXPortalUser); - XXPortalUserDao xXPortalUserDao = Mockito.mock(XXPortalUserDao.class); - Mockito.when(daoManager.getXXPortalUser()).thenReturn(xXPortalUserDao); - Mockito.when(xXPortalUserDao.findByLoginId(vXUser.getName().trim())).thenReturn(xXPortalUser); - Mockito.when(xPortalUserService.populateViewBean(xXPortalUser)).thenReturn(vXPortalUser); - XXPortalUserRole XXPortalUserRole = new XXPortalUserRole(); - XXPortalUserRole.setId(userId); - XXPortalUserRole.setUserId(userId); - XXPortalUserRole.setUserRole("ROLE_USER"); - XXAuthSessionDao xXAuthSessionDao= Mockito.mock(XXAuthSessionDao.class); - XXUserPermissionDao xXUserPermissionDao= Mockito.mock(XXUserPermissionDao.class); - XXPortalUserRoleDao xXPortalUserRoleDao= Mockito.mock(XXPortalUserRoleDao.class); - Mockito.when(daoManager.getXXAuthSession()).thenReturn(xXAuthSessionDao); - Mockito.when(daoManager.getXXUserPermission()).thenReturn(xXUserPermissionDao); - Mockito.when(daoManager.getXXPortalUserRole()).thenReturn(xXPortalUserRoleDao); - List xXAuthSessions=new ArrayList(); - XXAuthSession xXAuthSession = new XXAuthSession(); - xXAuthSession.setId(userId); - xXAuthSession.setLoginId(vXPortalUser.getLoginId()); - List xXUserPermissions=new ArrayList(); - List xXPortalUserRoles=new ArrayList(); - Mockito.when(xXUserPermissionDao.findByUserPermissionId(vXPortalUser.getId())).thenReturn(xXUserPermissions); - Mockito.when(xXPortalUserRoleDao.findByUserId(vXPortalUser.getId())).thenReturn(xXPortalUserRoles); - XXPolicyDao xXPolicyDao = Mockito.mock(XXPolicyDao.class); - List xXPolicyList = new ArrayList(); - Mockito.when(daoManager.getXXPolicy()).thenReturn(xXPolicyDao); - Mockito.when(xXPolicyDao.findByUserId(vXUser.getId())).thenReturn(xXPolicyList); - List zoneSecRefUser=new ArrayList(); - XXSecurityZoneRefUserDao zoneSecRefUserDao=Mockito.mock(XXSecurityZoneRefUserDao.class); - Mockito.when(daoManager.getXXSecurityZoneRefUser()).thenReturn(zoneSecRefUserDao); - Mockito.when(zoneSecRefUserDao.findByUserId(userId)).thenReturn(zoneSecRefUser); - List roleRefUser=new ArrayList(); - XXRoleRefUserDao roleRefUserDao=Mockito.mock(XXRoleRefUserDao.class); - Mockito.when(daoManager.getXXRoleRefUser()).thenReturn(roleRefUserDao); - Mockito.when(roleRefUserDao.findByUserId(userId)).thenReturn(roleRefUser); - xUserMgr.deleteXUser(vXUser.getId(), force); - Mockito.when(xGroupUserService.searchXGroupUsers((SearchCriteria) Mockito.any())).thenReturn(new VXGroupUserList()); - XXPolicy xXPolicy=getXXPolicy(); - xXPolicyList.add(xXPolicy); - Mockito.when(xXPolicyDao.findByUserId(userId)).thenReturn(xXPolicyList); - xUserMgr.deleteXUser(vXUser.getId(), force); - Mockito.when(xXPolicyDao.findByUserId(userId)).thenReturn(new ArrayList()); - VXPermMapList vXPermMapList = new VXPermMapList(); - VXPermMap vXPermMap1=getVXPermMap(); - List vXPermMaps=new ArrayList(); - vXPermMaps.add(vXPermMap1); - vXPermMapList.setVXPermMaps(vXPermMaps); - Mockito.when(xPermMapService.searchXPermMaps((SearchCriteria) Mockito.any())).thenReturn(vXPermMapList); - xUserMgr.deleteXUser(vXUser.getId(), force); - Mockito.when(xPermMapService.searchXPermMaps((SearchCriteria) Mockito.any())).thenReturn(new VXPermMapList()); - List vXAuditMaps=new ArrayList(); - VXAuditMap vXAuditMap=getVXAuditMap(); - vXAuditMaps.add(vXAuditMap); - vXAuditMapList.setVXAuditMaps(vXAuditMaps); - Mockito.when(xAuditMapService.searchXAuditMaps((SearchCriteria) Mockito.any())).thenReturn(vXAuditMapList); - xUserMgr.deleteXUser(vXUser.getId(), force); - Mockito.when(xAuditMapService.searchXAuditMaps((SearchCriteria) Mockito.any())).thenReturn(new VXAuditMapList()); - xXAuthSessions.add(xXAuthSession); - xUserMgr.deleteXUser(vXUser.getId(), force); - XXUserPermission xUserPermissionObj=xxUserPermission(); - xXUserPermissions.add(xUserPermissionObj); - Mockito.when(xXUserPermissionDao.findByUserPermissionId(vXPortalUser.getId())).thenReturn(xXUserPermissions); - xUserMgr.deleteXUser(vXUser.getId(), force); - Mockito.when(xXUserPermissionDao.findByUserPermissionId(vXPortalUser.getId())).thenReturn(new ArrayList()); - xXPortalUserRoles.add(XXPortalUserRole); - Mockito.when(xXPortalUserRoleDao.findByUserId(vXPortalUser.getId())).thenReturn(xXPortalUserRoles); - xUserMgr.deleteXUser(vXUser.getId(), force); - Mockito.when(xXPortalUserRoleDao.findByUserId(vXPortalUser.getId())).thenReturn(new ArrayList()); - xUserMgr.deleteXUser(vXUser.getId(), force); - - vXUser.setName(""); - Mockito.when(xXUserDao.getById(vXUser.getId())).thenReturn(xXUser); - Mockito.when(xUserService.populateViewBean(xXUser)).thenReturn(vXUser); - thrown.expect(NullPointerException.class); - xUserMgr.deleteXUser(vXUser.getId(), force); - } - - @Test - public void test95DeleteXGroup() { - setup(); - boolean force = false; - VXGroup vXGroup = vxGroup(); - XXGroupDao xXGroupDao = Mockito.mock(XXGroupDao.class); - XXGroup xXGroup = new XXGroup(); - Mockito.when(daoManager.getXXGroup()).thenReturn(xXGroupDao); - Mockito.when(xXGroupDao.getById(vXGroup.getId())).thenReturn(xXGroup); - Mockito.when(xGroupService.populateViewBean(xXGroup)).thenReturn(vXGroup); - VXGroupUserList vxGroupUserList =vxGroupUserList(); - Mockito.when(xGroupUserService.searchXGroupUsers((SearchCriteria) Mockito.any())).thenReturn(vxGroupUserList); - VXPermMapList vXPermMapList = new VXPermMapList(); - VXPermMap vXPermMap1=getVXPermMap(); - List vXPermMaps=new ArrayList(); - vXPermMaps.add(vXPermMap1); - VXAuditMapList vXAuditMapList = new VXAuditMapList(); - List vXAuditMaps=new ArrayList(); - VXAuditMap vXAuditMap=getVXAuditMap(); - vXAuditMaps.add(vXAuditMap); - XXGroupGroupDao xXGroupGroupDao = Mockito.mock(XXGroupGroupDao.class); - List xXGroupGroups = new ArrayList(); - XXGroupPermissionDao xXGroupPermissionDao= Mockito.mock(XXGroupPermissionDao.class); - Mockito.when(daoManager.getXXGroupPermission()).thenReturn(xXGroupPermissionDao); - List xXGroupPermissions=new ArrayList(); - Mockito.when(xXGroupPermissionDao.findByGroupId(vXGroup.getId())).thenReturn(xXGroupPermissions); - XXPolicyDao xXPolicyDao = Mockito.mock(XXPolicyDao.class); - List xXPolicyList = new ArrayList(); - Mockito.when(daoManager.getXXPolicy()).thenReturn(xXPolicyDao); - List xResourceList = new ArrayList(); - List zoneSecRefGroup=new ArrayList(); - XXSecurityZoneRefGroupDao zoneSecRefGroupDao=Mockito.mock(XXSecurityZoneRefGroupDao.class); - Mockito.when(daoManager.getXXSecurityZoneRefGroup()).thenReturn(zoneSecRefGroupDao); - List roleRefGroup=new ArrayList(); - XXRoleRefGroupDao roleRefGroupDao = Mockito.mock(XXRoleRefGroupDao.class); - Mockito.when(daoManager.getXXRoleRefGroup()).thenReturn(roleRefGroupDao); - Mockito.when(zoneSecRefGroupDao.findByGroupId(userId)).thenReturn(zoneSecRefGroup); - Mockito.when(roleRefGroupDao.findByGroupId(userId)).thenReturn(roleRefGroup); - XXResource xXResource = new XXResource(); - xXResource.setId(userId); - xXResource.setName("hadoopdev"); - xXResource.setIsRecursive(AppConstants.BOOL_TRUE); - xXResource.setResourceStatus(AppConstants.STATUS_ENABLED); - xResourceList.add(xXResource); - xUserMgr.deleteXGroup(vXGroup.getId(), force); - Mockito.when(xGroupUserService.searchXGroupUsers((SearchCriteria) Mockito.any())).thenReturn(new VXGroupUserList()); - XXPolicy xXPolicy=getXXPolicy(); - xXPolicyList.add(xXPolicy); - Mockito.when(xXPolicyDao.findByGroupId(userId)).thenReturn(xXPolicyList); - xUserMgr.deleteXGroup(vXGroup.getId(), force); - Mockito.when(xXPolicyDao.findByGroupId(userId)).thenReturn(new ArrayList()); - vXPermMapList.setVXPermMaps(vXPermMaps); - Mockito.when(xPermMapService.searchXPermMaps((SearchCriteria) Mockito.any())).thenReturn(vXPermMapList); - xUserMgr.deleteXGroup(vXGroup.getId(), force); - Mockito.when(xPermMapService.searchXPermMaps((SearchCriteria) Mockito.any())).thenReturn(new VXPermMapList()); - vXAuditMapList.setVXAuditMaps(vXAuditMaps); - Mockito.when(xAuditMapService.searchXAuditMaps((SearchCriteria) Mockito.any())).thenReturn(vXAuditMapList); - xUserMgr.deleteXGroup(vXGroup.getId(), force); - Mockito.when(xAuditMapService.searchXAuditMaps((SearchCriteria) Mockito.any())).thenReturn(new VXAuditMapList()); - XXGroupGroup xXGroupGroup = xxGroupGroup(); - xXGroupGroups.add(xXGroupGroup); - xUserMgr.deleteXGroup(vXGroup.getId(), force); - XXGroupPermission xGroupPermissionObj = xxGroupPermission(); - xXGroupPermissions.add(xGroupPermissionObj); - Mockito.when(xXGroupPermissionDao.findByGroupId(vXGroup.getId())).thenReturn(xXGroupPermissions); - xUserMgr.deleteXGroup(vXGroup.getId(), force); - Mockito.when(xXGroupPermissionDao.findByGroupId(vXGroup.getId())).thenReturn(new ArrayList()); - xUserMgr.deleteXGroup(vXGroup.getId(), force); - Mockito.when(xGroupService.populateViewBean(xXGroup)).thenReturn(null); - Mockito.when(restErrorUtil.createRESTException("Group ID doesn't exist.",MessageEnums.INVALID_INPUT_DATA)).thenThrow(new WebApplicationException()); - thrown.expect(WebApplicationException.class); - xUserMgr.deleteXGroup(vXGroup.getId(), force); - } - - @Test - public void test96updateXModuleDefPermission() { - XXModuleDefDao xModuleDefDao = Mockito.mock(XXModuleDefDao.class); - XXModuleDef xModuleDef = xxModuleDef(); - VXModuleDef vXModuleDef = vxModuleDef(); - Mockito.when(xModuleDefService.updateResource(vXModuleDef)).thenReturn(vXModuleDef); - Mockito.when(daoManager.getXXModuleDef()).thenReturn(xModuleDefDao); - Mockito.when(xModuleDefDao.getById(userId)).thenReturn(xModuleDef); - - Map xXGroupNameMap = new HashMap(); - xXGroupNameMap.put(userId, groupName); - Mockito.when(xGroupService.getXXGroupIdNameMap()).thenReturn(xXGroupNameMap); - - Object[] objArr = new Object[] {userId ,userId,userLoginID}; - Map xXUserMap =new HashMap(); - xXUserMap.put(userId, objArr); - Mockito.when(xUserService.getXXPortalUserIdXXUserNameMap()).thenReturn(xXUserMap); - - Mockito.when(xModuleDefService.populateViewBean(xModuleDef,xXUserMap,xXGroupNameMap,true)).thenReturn(vXModuleDef); - List xXGroupPermissions=new ArrayList(); - XXGroupPermission xGroupPermissionObj = xxGroupPermission(); - xXGroupPermissions.add(xGroupPermissionObj); - List vXGroupPermissions=new ArrayList(); - VXGroupPermission vXGroupPermission=vxGroupPermission(); - vXGroupPermission.setIsAllowed(0); - vXGroupPermissions.add(vXGroupPermission); - List xXUserPermissions=new ArrayList(); - XXUserPermission xUserPermissionObj=xxUserPermission(); - xXUserPermissions.add(xUserPermissionObj); - VXUserPermission vxUserPermission=vxUserPermission(); - vxUserPermission.setIsAllowed(0); - UserSessionBase userSession = Mockito.mock(UserSessionBase.class); - Set userSessions = new HashSet(); - userSessions.add(userSession); - Map groupPermMapOld = new HashMap(); - groupPermMapOld.put(vXGroupPermission.getGroupId(), vXGroupPermission); - Mockito.when(xGroupPermissionService.convertVListToVMap((List) Mockito.any())).thenReturn(groupPermMapOld); - Mockito.when(xGroupPermissionService.updateResource(vXGroupPermission)).thenReturn(vXGroupPermission); - XXGroupUserDao xxGroupUserDao = Mockito.mock(XXGroupUserDao.class); - Mockito.when(daoManager.getXXGroupUser()).thenReturn(xxGroupUserDao); - List grpUsers =new ArrayList(); - Mockito.when(xxGroupUserDao.findByGroupId(vXGroupPermission.getGroupId())).thenReturn(grpUsers); - List userPermListOld = new ArrayList(); - userPermListOld.add(vxUserPermission); - Map userPermMapOld = new HashMap(); - userPermMapOld.put(vxUserPermission.getUserId(), vxUserPermission); - Mockito.when(xUserPermissionService.convertVListToVMap((List) Mockito.any())).thenReturn(userPermMapOld); - Mockito.when(xUserPermissionService.updateResource(vxUserPermission)).thenReturn(vxUserPermission); - Mockito.when(sessionMgr.getActiveUserSessionsForPortalUserId(vxUserPermission.getUserId())).thenReturn(userSessions); - VXModuleDef dbMuduleDef = xUserMgr.updateXModuleDefPermission(vXModuleDef); - Assert.assertEquals(dbMuduleDef, vXModuleDef); - Assert.assertNotNull(dbMuduleDef); - Assert.assertEquals(dbMuduleDef, vXModuleDef); - Assert.assertEquals(dbMuduleDef.getId(), vXModuleDef.getId()); - Assert.assertEquals(dbMuduleDef.getOwner(), vXModuleDef.getOwner()); - Assert.assertEquals(dbMuduleDef.getUpdatedBy(),vXModuleDef.getUpdatedBy()); - Assert.assertEquals(dbMuduleDef.getUrl(), vXModuleDef.getUrl()); - Assert.assertEquals(dbMuduleDef.getAddedById(),vXModuleDef.getAddedById()); - Assert.assertEquals(dbMuduleDef.getCreateDate(),vXModuleDef.getCreateDate()); - Assert.assertEquals(dbMuduleDef.getCreateTime(),vXModuleDef.getCreateTime()); - Assert.assertEquals(dbMuduleDef.getUserPermList(),vXModuleDef.getUserPermList()); - Assert.assertEquals(dbMuduleDef.getGroupPermList(),vXModuleDef.getGroupPermList()); - Mockito.verify(xModuleDefService).populateViewBean(xModuleDef,xXUserMap,xXGroupNameMap,true); - Mockito.verify(xModuleDefService).updateResource(vXModuleDef); - Mockito.verify(daoManager).getXXModuleDef(); - } - - @Test - public void test97updateXModuleDefPermission() { - XXModuleDefDao xModuleDefDao = Mockito.mock(XXModuleDefDao.class); - XXModuleDef xModuleDef = xxModuleDef(); - VXModuleDef vXModuleDef = vxModuleDef(); - Mockito.when(xModuleDefService.updateResource(vXModuleDef)).thenReturn(vXModuleDef); - Mockito.when(daoManager.getXXModuleDef()).thenReturn(xModuleDefDao); - Mockito.when(xModuleDefDao.getById(userId)).thenReturn(xModuleDef); - - Map xXGroupNameMap = new HashMap(); - xXGroupNameMap.put(userId, groupName); - Mockito.when(xGroupService.getXXGroupIdNameMap()).thenReturn(xXGroupNameMap); - - Object[] objArr = new Object[] {userId ,userId,userLoginID}; - Map xXUserMap =new HashMap(); - xXUserMap.put(userId, objArr); - Mockito.when(xUserService.getXXPortalUserIdXXUserNameMap()).thenReturn(xXUserMap); - - Mockito.when(xModuleDefService.populateViewBean(xModuleDef,xXUserMap,xXGroupNameMap,true)).thenReturn(vXModuleDef); - List xXGroupPermissions=new ArrayList(); - XXGroupPermission xGroupPermissionObj = xxGroupPermission(); - xXGroupPermissions.add(xGroupPermissionObj); - VXGroupPermission vXGroupPermission=vxGroupPermission(); - vXGroupPermission.setIsAllowed(0); - List xXUserPermissions=new ArrayList(); - XXUserPermission xUserPermissionObj=xxUserPermission(); - xXUserPermissions.add(xUserPermissionObj); - VXUserPermission vxUserPermission=vxUserPermission(); - vxUserPermission.setIsAllowed(0); - UserSessionBase userSession = Mockito.mock(UserSessionBase.class); - Set userSessions = new HashSet(); - userSessions.add(userSession); - XXGroupUserDao xxGroupUserDao = Mockito.mock(XXGroupUserDao.class); - Mockito.when(daoManager.getXXGroupUser()).thenReturn(xxGroupUserDao); - List grpUsers =new ArrayList(); - Mockito.when(xxGroupUserDao.findByGroupId(vXGroupPermission.getGroupId())).thenReturn(grpUsers); - Mockito.when(sessionMgr.getActiveUserSessionsForPortalUserId(vxUserPermission.getUserId())).thenReturn(userSessions); - Mockito.when(xGroupPermissionService.createResource((VXGroupPermission) Mockito.any())).thenReturn(vXGroupPermission); - Mockito.when(xUserPermissionService.createResource((VXUserPermission) Mockito.any())).thenReturn(vxUserPermission); - VXModuleDef dbMuduleDef = xUserMgr.updateXModuleDefPermission(vXModuleDef); - Assert.assertEquals(dbMuduleDef, vXModuleDef); - Assert.assertNotNull(dbMuduleDef); - Assert.assertEquals(dbMuduleDef, vXModuleDef); - Assert.assertEquals(dbMuduleDef.getId(), vXModuleDef.getId()); - Assert.assertEquals(dbMuduleDef.getOwner(), vXModuleDef.getOwner()); - Assert.assertEquals(dbMuduleDef.getUpdatedBy(),vXModuleDef.getUpdatedBy()); - Assert.assertEquals(dbMuduleDef.getUrl(), vXModuleDef.getUrl()); - Assert.assertEquals(dbMuduleDef.getAddedById(),vXModuleDef.getAddedById()); - Assert.assertEquals(dbMuduleDef.getCreateDate(),vXModuleDef.getCreateDate()); - Assert.assertEquals(dbMuduleDef.getCreateTime(),vXModuleDef.getCreateTime()); - Assert.assertEquals(dbMuduleDef.getUserPermList(),vXModuleDef.getUserPermList()); - Assert.assertEquals(dbMuduleDef.getGroupPermList(),vXModuleDef.getGroupPermList()); - Mockito.verify(xModuleDefService).updateResource(vXModuleDef); - Mockito.verify(daoManager).getXXModuleDef(); - Mockito.verify(xModuleDefService).populateViewBean(xModuleDef,xXUserMap,xXGroupNameMap,true); - Mockito.verify(xGroupService).getXXGroupIdNameMap(); - Mockito.verify(xUserService).getXXPortalUserIdXXUserNameMap(); - } - - @Test - public void test98modifyUserActiveStatus() { - VXUser vxUser = vxUser(); - XXUser xXUser = xxUser(vxUser); - HashMap statusMap= new HashMap(); - statusMap.put(xXUser.getId(), 1); - RangerSecurityContext context = new RangerSecurityContext(); - context.setUserSession(new UserSessionBase()); - RangerContextHolder.setSecurityContext(context); - UserSessionBase currentUserSession = ContextUtil.getCurrentUserSession(); - currentUserSession.setUserAdmin(true); - XXPortalUser xXPortalUser = new XXPortalUser(); - xXPortalUser.setLoginId(null); - xXPortalUser.setId(userId); - currentUserSession.setXXPortalUser(xXPortalUser); - xUserMgr.modifyUserActiveStatus(statusMap); - } - - @Test - public void test99createServiceConfigUser() { - XXUserDao xxUserDao = Mockito.mock(XXUserDao.class); - VXUser vxUser = vxUser(); - XXUser xXUser = xxUser(vxUser); - VXUserPermission vXUserPermission=vxUserPermission(); - XXUserPermission xUserPermissionObj = xxUserPermission(); - xUserPermissionObj.setModuleId(vXUserPermission.getModuleId()); - xUserPermissionObj.setUserId(vXUserPermission.getUserId()); - Mockito.when(daoManager.getXXUser()).thenReturn(xxUserDao); - Mockito.when(xxUserDao.findByUserName(vxUser.getName())).thenReturn(xXUser); - Mockito.when(xUserService.populateViewBean(xXUser)).thenReturn(vxUser); - VXUser serviceConfigUser=xUserMgr.createServiceConfigUser(vxUser.getName()); - Assert.assertNotNull(serviceConfigUser); - Assert.assertEquals(xXUser.getName(), serviceConfigUser.getName()); - Mockito.when(daoManager.getXXUser()).thenReturn(xxUserDao); - Mockito.when(xxUserDao.findByUserName(vxUser.getName())).thenReturn(null); - Mockito.when(daoManager.getXXUser()).thenReturn(xxUserDao); - UserSessionBase userSession = Mockito.mock(UserSessionBase.class); - Set userSessions = new HashSet(); - userSessions.add(userSession); - serviceConfigUser=xUserMgr.createServiceConfigUser(vxUser.getName()); - Assert.assertNull(serviceConfigUser); - } - - @Test - public void test100getStringListFromUserRoleList() { - destroySession(); - VXStringList vXStringList=xUserMgr.getStringListFromUserRoleList(null); - Assert.assertNull(vXStringList); - } - - - @Test - public void test101getAdminUserDetailsWithUserHavingUSER_ROLE() { - destroySession(); - - RangerSecurityContext context = new RangerSecurityContext(); - context.setUserSession(new UserSessionBase()); - RangerContextHolder.setSecurityContext(context); - UserSessionBase currentUserSession = ContextUtil.getCurrentUserSession(); - currentUserSession.setUserAdmin(false); - XXPortalUser xXPortalUser = new XXPortalUser(); - xXPortalUser.setLoginId(userLoginID); - xXPortalUser.setId(userId); - currentUserSession.setXXPortalUser(xXPortalUser); - - VXUser loggedInUser = vxUser(); - List loggedInUserRole = new ArrayList(); - loggedInUserRole.add(RangerConstants.ROLE_USER); - loggedInUser.setId(8L); - loggedInUser.setName("testuser"); - loggedInUser.setUserRoleList(loggedInUserRole); - - VXUser vxUser = vxUser(); - List userRole = new ArrayList(); - userRole.add(RangerConstants.ROLE_ADMIN); - vxUser.setId(5L); - vxUser.setName("test3"); - vxUser.setUserRoleList(userRole); - vxUser.setUserSource(RangerCommonEnums.USER_UNIX); - Mockito.when(xUserService.readResourceWithOutLogin(5L)).thenReturn(vxUser); - Mockito.when(xUserService.getXUserByUserName("testuser")).thenReturn(loggedInUser); - Mockito.when(restErrorUtil.createRESTException(HttpServletResponse.SC_FORBIDDEN, "Logged-In user is not allowed to access requested user data", true)).thenThrow(new WebApplicationException()); - thrown.expect(WebApplicationException.class); - xUserMgr.getXUser(5L); - } - - @Test - public void test102getKeyAdminUserDetailsWithUserHavingUSER_ROLE() { - destroySession(); - - RangerSecurityContext context = new RangerSecurityContext(); - context.setUserSession(new UserSessionBase()); - RangerContextHolder.setSecurityContext(context); - UserSessionBase currentUserSession = ContextUtil.getCurrentUserSession(); - currentUserSession.setUserAdmin(false); - XXPortalUser xXPortalUser = new XXPortalUser(); - xXPortalUser.setLoginId(userLoginID); - xXPortalUser.setId(userId); - currentUserSession.setXXPortalUser(xXPortalUser); - - VXUser loggedInUser = vxUser(); - List loggedInUserRole = new ArrayList(); - loggedInUserRole.add(RangerConstants.ROLE_USER); - loggedInUser.setId(8L); - loggedInUser.setName("testuser"); - loggedInUser.setUserRoleList(loggedInUserRole); - - VXUser vxUser = vxUser(); - List userRole = new ArrayList(); - userRole.add(RangerConstants.ROLE_KEY_ADMIN); - vxUser.setId(5L); - vxUser.setName("test3"); - vxUser.setUserRoleList(userRole); - vxUser.setUserSource(RangerCommonEnums.USER_UNIX); - Mockito.when(xUserService.readResourceWithOutLogin(5L)).thenReturn(vxUser); - Mockito.when(xUserService.getXUserByUserName("testuser")).thenReturn(loggedInUser); - Mockito.when(restErrorUtil.createRESTException(HttpServletResponse.SC_FORBIDDEN, "Logged-In user is not allowed to access requested user data", true)).thenThrow(new WebApplicationException()); - thrown.expect(WebApplicationException.class); - xUserMgr.getXUser(5L); - } - - @Test - public void test103getAdminAuditorUserDetailsWithUserHavingUSER_ROLE() { - destroySession(); - - RangerSecurityContext context = new RangerSecurityContext(); - context.setUserSession(new UserSessionBase()); - RangerContextHolder.setSecurityContext(context); - UserSessionBase currentUserSession = ContextUtil.getCurrentUserSession(); - currentUserSession.setUserAdmin(false); - XXPortalUser xXPortalUser = new XXPortalUser(); - xXPortalUser.setLoginId(userLoginID); - xXPortalUser.setId(userId); - currentUserSession.setXXPortalUser(xXPortalUser); - - VXUser loggedInUser = vxUser(); - List loggedInUserRole = new ArrayList(); - loggedInUserRole.add(RangerConstants.ROLE_USER); - loggedInUser.setId(8L); - loggedInUser.setName("testuser"); - loggedInUser.setUserRoleList(loggedInUserRole); - - VXUser vxUser = vxUser(); - List userRole = new ArrayList(); - userRole.add(RangerConstants.ROLE_ADMIN_AUDITOR); - vxUser.setId(5L); - vxUser.setName("test3"); - vxUser.setUserRoleList(userRole); - vxUser.setUserSource(RangerCommonEnums.USER_UNIX); - Mockito.when(xUserService.readResourceWithOutLogin(5L)).thenReturn(vxUser); - Mockito.when(xUserService.getXUserByUserName("testuser")).thenReturn(loggedInUser); - Mockito.when(restErrorUtil.createRESTException(HttpServletResponse.SC_FORBIDDEN, "Logged-In user is not allowed to access requested user data", true)).thenThrow(new WebApplicationException()); - thrown.expect(WebApplicationException.class); - xUserMgr.getXUser(5L); - } - - @Test - public void test104getKeyAdminAuditorUserDetailsWithUserHavingUSER_ROLE() { - destroySession(); - - RangerSecurityContext context = new RangerSecurityContext(); - context.setUserSession(new UserSessionBase()); - RangerContextHolder.setSecurityContext(context); - UserSessionBase currentUserSession = ContextUtil.getCurrentUserSession(); - currentUserSession.setUserAdmin(false); - XXPortalUser xXPortalUser = new XXPortalUser(); - xXPortalUser.setLoginId(userLoginID); - xXPortalUser.setId(userId); - currentUserSession.setXXPortalUser(xXPortalUser); - - VXUser loggedInUser = vxUser(); - List loggedInUserRole = new ArrayList(); - loggedInUserRole.add(RangerConstants.ROLE_USER); - loggedInUser.setId(8L); - loggedInUser.setName("testuser"); - loggedInUser.setUserRoleList(loggedInUserRole); - - VXUser vxUser = vxUser(); - List userRole = new ArrayList(); - userRole.add(RangerConstants.ROLE_KEY_ADMIN_AUDITOR); - vxUser.setId(5L); - vxUser.setName("test3"); - vxUser.setUserRoleList(userRole); - vxUser.setUserSource(RangerCommonEnums.USER_UNIX); - Mockito.when(xUserService.readResourceWithOutLogin(5L)).thenReturn(vxUser); - Mockito.when(xUserService.getXUserByUserName("testuser")).thenReturn(loggedInUser); - Mockito.when(restErrorUtil.createRESTException(HttpServletResponse.SC_FORBIDDEN, "Logged-In user is not allowed to access requested user data", true)).thenThrow(new WebApplicationException()); - thrown.expect(WebApplicationException.class); - xUserMgr.getXUser(5L); - } - - @Test - public void test105getUserDetailsOfItsOwn() { - destroySession(); - - RangerSecurityContext context = new RangerSecurityContext(); - context.setUserSession(new UserSessionBase()); - RangerContextHolder.setSecurityContext(context); - UserSessionBase currentUserSession = ContextUtil.getCurrentUserSession(); - currentUserSession.setUserAdmin(false); - XXPortalUser xXPortalUser = new XXPortalUser(); - xXPortalUser.setLoginId(userLoginID); - xXPortalUser.setId(userId); - currentUserSession.setXXPortalUser(xXPortalUser); - List permissionList = new ArrayList(); - permissionList.add(RangerConstants.MODULE_USER_GROUPS); - - - VXUser loggedInUser = vxUser(); - List loggedInUserRole = new ArrayList(); - loggedInUserRole.add(RangerConstants.ROLE_USER); - loggedInUser.setId(8L); - loggedInUser.setName("testuser"); - loggedInUser.setUserRoleList(loggedInUserRole); - - VXUser vxUser = vxUser(); - List userRole = new ArrayList(); - userRole.add(RangerConstants.ROLE_USER); - vxUser.setId(8L); - vxUser.setName("test3"); - vxUser.setUserRoleList(userRole); - vxUser.setUserSource(RangerCommonEnums.USER_UNIX); - Mockito.when(xUserService.readResourceWithOutLogin(8L)).thenReturn(vxUser); - Mockito.when(xUserService.getXUserByUserName("testuser")).thenReturn(loggedInUser); - XXModuleDefDao mockxxModuleDefDao = Mockito.mock(XXModuleDefDao.class); - Mockito.when(daoManager.getXXModuleDef()).thenReturn(mockxxModuleDefDao); - Mockito.when(mockxxModuleDefDao.findAccessibleModulesByUserId(8L, 8L)).thenReturn(permissionList); - VXUser expectedVXUser = xUserMgr.getXUser(8L); - Assert.assertNotNull(expectedVXUser); - Assert.assertEquals(expectedVXUser.getName(), vxUser.getName()); - destroySession(); - Mockito.when(restErrorUtil.createRESTException(HttpServletResponse.SC_FORBIDDEN, "Logged-In user is not allowed to access requested user data", true)).thenThrow(new WebApplicationException()); - thrown.expect(WebApplicationException.class); - xUserMgr.getXUser(8L); - } - - @Test - public void test106getErrorWhenRoleUserFetchAnotherUserGroupInfo() { - destroySession(); - - RangerSecurityContext context = new RangerSecurityContext(); - context.setUserSession(new UserSessionBase()); - RangerContextHolder.setSecurityContext(context); - UserSessionBase currentUserSession = ContextUtil.getCurrentUserSession(); - currentUserSession.setUserAdmin(false); - XXPortalUser xXPortalUser = new XXPortalUser(); - xXPortalUser.setLoginId(userLoginID); - xXPortalUser.setId(userId); - currentUserSession.setXXPortalUser(xXPortalUser); - List permissionList = new ArrayList(); - permissionList.add(RangerConstants.MODULE_USER_GROUPS); - - List groupIdList = new ArrayList(); - groupIdList.add(2L); - - VXUser loggedInUser = vxUser(); - List loggedInUserRole = new ArrayList(); - loggedInUserRole.add(RangerConstants.ROLE_USER); - loggedInUser.setId(8L); - loggedInUser.setName("testuser"); - loggedInUser.setUserRoleList(loggedInUserRole); - loggedInUser.setGroupIdList(groupIdList); - - VXUser vxUser = vxUser(); - List userRole = new ArrayList(); - userRole.add(RangerConstants.ROLE_USER); - vxUser.setId(8L); - vxUser.setName("test3"); - vxUser.setUserRoleList(userRole); - vxUser.setUserSource(RangerCommonEnums.USER_UNIX); - - Mockito.when(xUserService.getXUserByUserName("testuser")).thenReturn(loggedInUser); - - XXGroupUserDao mockxxGroupUserDao = Mockito.mock(XXGroupUserDao.class); - - Mockito.when(daoManager.getXXGroupUser()).thenReturn(mockxxGroupUserDao); - Mockito.when(mockxxGroupUserDao.findGroupIdListByUserId(loggedInUser.getId())).thenReturn(groupIdList); - - Mockito.when(restErrorUtil.create403RESTException("Logged-In user is not allowed to access requested group data.")).thenThrow(new WebApplicationException()); - thrown.expect(WebApplicationException.class); - xUserMgr.getXGroup(5L); - } - - @Test - public void test107RoleUserWillFetchOnlyHisOwnGroupDetails() { - destroySession(); - - RangerSecurityContext context = new RangerSecurityContext(); - context.setUserSession(new UserSessionBase()); - RangerContextHolder.setSecurityContext(context); - UserSessionBase currentUserSession = ContextUtil.getCurrentUserSession(); - currentUserSession.setUserAdmin(false); - XXPortalUser xXPortalUser = new XXPortalUser(); - xXPortalUser.setLoginId(userLoginID); - xXPortalUser.setId(userId); - currentUserSession.setXXPortalUser(xXPortalUser); - List permissionList = new ArrayList(); - permissionList.add(RangerConstants.MODULE_USER_GROUPS); - - List groupIdList = new ArrayList(); - groupIdList.add(5L); - - VXGroup expectedVXGroup = new VXGroup(); - expectedVXGroup.setId(5L); - expectedVXGroup.setName("testGroup"); - - VXUser loggedInUser = vxUser(); - List loggedInUserRole = new ArrayList(); - loggedInUserRole.add(RangerConstants.ROLE_USER); - loggedInUser.setId(8L); - loggedInUser.setName("testuser"); - loggedInUser.setUserRoleList(loggedInUserRole); - loggedInUser.setGroupIdList(groupIdList); - - VXUser vxUser = vxUser(); - List userRole = new ArrayList(); - userRole.add(RangerConstants.ROLE_USER); - vxUser.setId(8L); - vxUser.setName("test3"); - vxUser.setUserRoleList(userRole); - vxUser.setUserSource(RangerCommonEnums.USER_UNIX); - Mockito.when(xGroupService.readResourceWithOutLogin(5L)).thenReturn(expectedVXGroup); - - VXGroup rcvVXGroup = xUserMgr.getXGroup(5L); - Assert.assertNotNull(rcvVXGroup); - Assert.assertEquals(expectedVXGroup.getId(), rcvVXGroup.getId()); - Assert.assertEquals(expectedVXGroup.getName(), rcvVXGroup.getName()); - } - - @Test - public void test108RoleUserWillSearchOnlyHisOwnGroupDetails() { - destroySession(); - - RangerSecurityContext context = new RangerSecurityContext(); - context.setUserSession(new UserSessionBase()); - RangerContextHolder.setSecurityContext(context); - UserSessionBase currentUserSession = ContextUtil.getCurrentUserSession(); - currentUserSession.setUserAdmin(false); - XXPortalUser xXPortalUser = new XXPortalUser(); - xXPortalUser.setLoginId(userLoginID); - xXPortalUser.setId(userId); - currentUserSession.setXXPortalUser(xXPortalUser); - List permissionList = new ArrayList(); - permissionList.add(RangerConstants.MODULE_USER_GROUPS); - - SearchCriteria testSearchCriteria = createsearchCriteria(); - - List groupIdList = new ArrayList(); - groupIdList.add(5L); - - VXGroup expectedVXGroup = new VXGroup(); - expectedVXGroup.setId(5L); - expectedVXGroup.setName("testGroup"); - - List grpList = new ArrayList(); - grpList.add(expectedVXGroup); - - - VXGroupList expectedVXGroupList = new VXGroupList(); - expectedVXGroupList.setVXGroups(grpList); - - VXUser loggedInUser = vxUser(); - List loggedInUserRole = new ArrayList(); - loggedInUserRole.add(RangerConstants.ROLE_USER); - loggedInUser.setId(8L); - loggedInUser.setName("testuser"); - loggedInUser.setUserRoleList(loggedInUserRole); - loggedInUser.setGroupIdList(groupIdList); - - VXUser vxUser = vxUser(); - List userRole = new ArrayList(); - userRole.add(RangerConstants.ROLE_USER); - vxUser.setId(8L); - vxUser.setName("test3"); - vxUser.setUserRoleList(userRole); - vxUser.setUserSource(RangerCommonEnums.USER_UNIX); - Mockito.when(xUserService.getXUserByUserName("testuser")).thenReturn(loggedInUser); - Mockito.when(xGroupService.searchXGroups(testSearchCriteria)).thenReturn(expectedVXGroupList); - XXModuleDefDao mockxxModuleDefDao = Mockito.mock(XXModuleDefDao.class); - Mockito.when(daoManager.getXXModuleDef()).thenReturn(mockxxModuleDefDao); - Mockito.when(mockxxModuleDefDao.findAccessibleModulesByUserId(8L, 8L)).thenReturn(permissionList); - - VXGroupList rcvVXGroupList = xUserMgr.searchXGroups(testSearchCriteria); - Assert.assertNotNull(rcvVXGroupList); - - Assert.assertEquals(rcvVXGroupList.getList().get(0).getId(),expectedVXGroup.getId()); - Assert.assertEquals(rcvVXGroupList.getList().get(0).getName(),expectedVXGroup.getName()); - } - - @Test - public void test109AssignPermissionToUser() { - destroySession(); - setup(); - VXPortalUser vXPortalUser = userProfile(); - List xXModuleDefs = xxModuleDefs(); - XXModuleDefDao xXModuleDefDao = Mockito.mock(XXModuleDefDao.class); - Mockito.when(daoManager.getXXModuleDef()).thenReturn(xXModuleDefDao); - Mockito.when(daoManager.getXXModuleDef().getAll()).thenReturn(xXModuleDefs); - - VXUserPermission userPermission = vxUserPermission(); - List userPermList = new ArrayList(); - userPermList.add(userPermission); - List xUserPermissionsList = new ArrayList(); - XXUserPermission xUserPermission = xxUserPermission(); - xUserPermission.setModuleId(userPermission.getModuleId()); - xUserPermission.setUserId(userPermission.getUserId()); - xUserPermissionsList.add(xUserPermission); - - XXUserPermissionDao xXUserPermissionDao= Mockito.mock(XXUserPermissionDao.class); - Mockito.when(daoManager.getXXUserPermission()).thenReturn(xXUserPermissionDao); - Mockito.when(xXUserPermissionDao.findByModuleIdAndPortalUserId(vXPortalUser.getId(),xXModuleDefs.get(0).getId())).thenReturn(xUserPermission); - - VXUser vxUser = vxUser(); - XXUser xXUser = xxUser(vxUser); - XXUserDao xxUserDao = Mockito.mock(XXUserDao.class); - Mockito.when(daoManager.getXXUser()).thenReturn(xxUserDao); - Mockito.when(xxUserDao.findByPortalUserId(vXPortalUser.getId())).thenReturn(xXUser); - - Mockito.when(xUserPermissionService.populateViewBean(xUserPermission)).thenReturn(userPermission); - - Mockito.when(xUserPermissionService.createResource((VXUserPermission) Mockito.any())).thenReturn(userPermission); - Mockito.when(xUserPermissionService.updateResource((VXUserPermission) Mockito.any())).thenReturn(userPermission); - UserSessionBase userSession = Mockito.mock(UserSessionBase.class); - Set userSessions = new HashSet(); - userSessions.add(userSession); - Mockito.when(sessionMgr.getActiveUserSessionsForPortalUserId(userId)).thenReturn(userSessions); - - Collection existingRoleList = new ArrayList(); - existingRoleList.add(RangerConstants.ROLE_SYS_ADMIN); - vXPortalUser.setUserRoleList(existingRoleList); - xUserMgr.assignPermissionToUser(vXPortalUser, true); - existingRoleList.clear(); - existingRoleList.add(RangerConstants.ROLE_KEY_ADMIN); - vXPortalUser.setUserRoleList(existingRoleList); - xUserMgr.assignPermissionToUser(vXPortalUser, true); - existingRoleList.clear(); - existingRoleList.add(RangerConstants.ROLE_KEY_ADMIN_AUDITOR); - vXPortalUser.setUserRoleList(existingRoleList); - xUserMgr.assignPermissionToUser(vXPortalUser, true); - existingRoleList.clear(); - existingRoleList.add(RangerConstants.ROLE_ADMIN_AUDITOR); - vXPortalUser.setUserRoleList(existingRoleList); - xUserMgr.assignPermissionToUser(vXPortalUser, true); - } - - @Test - public void test110CreateOrDeleteXGroupUserList() { - destroySession(); - setup(); - GroupUserInfo groupUserInfo = new GroupUserInfo(); - groupUserInfo.setGroupName("public"); - Set addUsers = new HashSet(); - Set delUsers = new HashSet(); - addUsers.add("testuser1"); - addUsers.add("testuser2"); - delUsers.add("testuser3"); - groupUserInfo.setAddUsers(addUsers); - groupUserInfo.setDelUsers(delUsers); - List groupUserInfoList = new ArrayList(); - groupUserInfoList.add(groupUserInfo); - Map usersFromDB = new HashMap(); - usersFromDB.put("testuser1", 1L); - usersFromDB.put("testuser2", 2L); - XXUserDao xxUserDao = Mockito.mock(XXUserDao.class); - Mockito.when(daoManager.getXXUser()).thenReturn(xxUserDao); - Mockito.when(xxUserDao.getAllUserIds()).thenReturn(usersFromDB); - xUserMgr.createOrDeleteXGroupUserList(groupUserInfoList); - } - - @Test - public void test111CreateOrUpdateXUsers() { - destroySession(); - setup(); - List vXUserList=new ArrayList(); - VXUser vXUser = vxUser(); - VXUser vXUser1 = vxUser(); - VXUser vXUser2 = vxUser(); - vXUser2.setFirstName("user12"); - vXUser2.setEmailAddress(null); - vXUser.setFirstName("null"); - vXUser.setLastName("null"); - vXUser.setEmailAddress(""); - vXUser1.setName("null"); - Collection userRoleList = new ArrayList(); - userRoleList.add(RangerConstants.ROLE_USER); - userRoleList.add(RangerConstants.ROLE_SYS_ADMIN); - userRoleList.add(RangerConstants.ROLE_KEY_ADMIN); - userRoleList.add(RangerConstants.ROLE_KEY_ADMIN_AUDITOR); - userRoleList.add(RangerConstants.ROLE_ADMIN_AUDITOR); - vXUser.setUserRoleList(userRoleList); - vXUser1.setUserRoleList(userRoleList); - vXUser2.setUserRoleList(userRoleList); - vXUserList.add(vXUser); - vXUserList.add(vXUser1); - vXUserList.add(vXUser2); - VXUserList users = new VXUserList(vXUserList); - XXUserDao xxUserDao = Mockito.mock(XXUserDao.class); - XXPortalUserDao userDao = Mockito.mock(XXPortalUserDao.class); - XXModuleDefDao xXModuleDefDao = Mockito.mock(XXModuleDefDao.class); - XXUser xXUser = xxUser(vXUser); - VXPortalUser vXPortalUser = userProfile(); - vXPortalUser.setFirstName("null"); - vXPortalUser.setLastName("null"); - XXPortalUser xXPortalUser = xxPortalUser(vXPortalUser); - xXPortalUser.setUserSource(RangerCommonEnums.USER_EXTERNAL); - List lstRole = new ArrayList(); - lstRole.add(RangerConstants.ROLE_SYS_ADMIN); - List xXModuleDefs=xxModuleDefs(); - - vXPortalUser.setUserRoleList(lstRole); - Mockito.when(userMgr.getUserProfileByLoginId(vXUser.getName())).thenReturn(null); - - Mockito.when(daoManager.getXXUser()).thenReturn(xxUserDao); - Mockito.when(xxUserDao.findByUserName(vXUser.getName())).thenReturn(xXUser); - Mockito.when(daoManager.getXXPortalUser()).thenReturn(userDao); - Mockito.when(daoManager.getXXModuleDef()).thenReturn(xXModuleDefDao); - Mockito.when(xXModuleDefDao.getAll()).thenReturn(xXModuleDefs); - - Mockito.when(userMgr.mapVXPortalUserToXXPortalUser((VXPortalUser) Mockito.any())).thenReturn(xXPortalUser); - XXPortalUserDao xXPortalUserDao = Mockito.mock(XXPortalUserDao.class); - Mockito.when(daoManager.getXXPortalUser()).thenReturn(xXPortalUserDao); - Mockito.when(daoManager.getXXPortalUser().create((XXPortalUser) Mockito.any())).thenReturn(xXPortalUser); - XXUser xUser = xxUser(vXUser); - Mockito.when(daoManager.getXXUser()).thenReturn(xxUserDao); - Mockito.when(daoManager.getXXUser().findByUserName(vXUser.getName())).thenReturn(xUser); - Mockito.when(xUserService.populateViewBean(xUser)).thenReturn(vXUser); - - VXUserPermission userPermission = vxUserPermission(); - List userPermList = new ArrayList(); - userPermList.add(userPermission); - - List xUserPermissionsList = new ArrayList(); - XXUserPermission xUserPermissionObj = xxUserPermission(); - xUserPermissionObj.setModuleId(userPermission.getModuleId()); - xUserPermissionObj.setUserId(userPermission.getUserId()); - xUserPermissionsList.add(xUserPermissionObj); - - XXUserPermissionDao xUserPermissionDao = Mockito.mock(XXUserPermissionDao.class); - Mockito.when(daoManager.getXXUserPermission()).thenReturn(xUserPermissionDao); - UserSessionBase userSession = Mockito.mock(UserSessionBase.class); - Set userSessions = new HashSet(); - userSessions.add(userSession); - - Mockito.when(xUserPermissionService.createResource((VXUserPermission) Mockito.any())).thenReturn(userPermission); - Mockito.when(sessionMgr.getActiveUserSessionsForPortalUserId(userId)).thenReturn(userSessions); - Mockito.when(xUserPermissionDao.findByModuleIdAndPortalUserId(null, null)).thenReturn(xUserPermissionObj); - Mockito.when(xUserPermissionService.populateViewBean(xUserPermissionObj)).thenReturn(userPermission); - Mockito.when(xUserPermissionService.updateResource((VXUserPermission) Mockito.any())).thenReturn(userPermission); - Mockito.when(daoManager.getXXPortalUser()).thenReturn(xXPortalUserDao); - VXUser loggedInUser = vxUser(); - List loggedInUserRole = new ArrayList(); - loggedInUserRole.add(RangerConstants.ROLE_SYS_ADMIN); - loggedInUser.setId(8L); - loggedInUser.setName("testuser"); - loggedInUser.setUserRoleList(loggedInUserRole); - Mockito.when(xUserService.getXUserByUserName("admin")).thenReturn(loggedInUser); - int createdOrUpdatedUserCount = xUserMgr.createOrUpdateXUsers(users); - Assert.assertEquals(createdOrUpdatedUserCount, 1); - } - - @Test - public void test112CreateOrUpdateXUsers() { - destroySession(); - setup(); - List vXUserList=new ArrayList(); - VXUser vXUser = vxUser(); - vXUser.setFirstName("testuser"); - vXUser.setLastName("testuser"); - vXUser.setPassword("TestPassword@123"); - vXUser.setEmailAddress(""); - vXUser.setUserSource(RangerCommonEnums.USER_APP); - Collection userRoleList = new ArrayList(); - userRoleList.add(RangerConstants.ROLE_USER); - userRoleList.add(RangerConstants.ROLE_SYS_ADMIN); - userRoleList.add(RangerConstants.ROLE_KEY_ADMIN); - userRoleList.add(RangerConstants.ROLE_KEY_ADMIN_AUDITOR); - userRoleList.add(RangerConstants.ROLE_ADMIN_AUDITOR); - vXUser.setUserRoleList(userRoleList); - vXUserList.add(vXUser); - VXUserList users = new VXUserList(vXUserList); - - VXPortalUser vXPortalUser = userProfile(); - vXPortalUser.setFirstName("testuser"); - vXPortalUser.setLastName("testuser"); - vXPortalUser.setPassword("TestPassword@123"); - XXPortalUser xXPortalUser = xxPortalUser(vXPortalUser); - List xXModuleDefs=xxModuleDefs(); - List xUserPermissionsList = new ArrayList(); - XXUserPermission xUserPermissionObj = xxUserPermission(); - VXUserPermission userPermission = vxUserPermission(); - List userPermList = new ArrayList(); - userPermList.add(userPermission); - xUserPermissionObj.setModuleId(userPermission.getModuleId()); - xUserPermissionObj.setUserId(userPermission.getUserId()); - xUserPermissionsList.add(xUserPermissionObj); - UserSessionBase userSession = Mockito.mock(UserSessionBase.class); - Set userSessions = new HashSet(); - userSessions.add(userSession); - - XXUserDao xxUserDao = Mockito.mock(XXUserDao.class); - XXPortalUserDao userDao = Mockito.mock(XXPortalUserDao.class); - XXModuleDefDao xXModuleDefDao = Mockito.mock(XXModuleDefDao.class); - XXUserPermissionDao xUserPermissionDao = Mockito.mock(XXUserPermissionDao.class); - - Mockito.when(daoManager.getXXUser()).thenReturn(xxUserDao); - Mockito.when(daoManager.getXXPortalUser()).thenReturn(userDao); - Mockito.when(daoManager.getXXPortalUser().create((XXPortalUser) Mockito.any())).thenReturn(xXPortalUser); - Mockito.when(daoManager.getXXModuleDef()).thenReturn(xXModuleDefDao); - Mockito.when(xXModuleDefDao.getAll()).thenReturn(xXModuleDefs); - Mockito.when(daoManager.getXXUserPermission()).thenReturn(xUserPermissionDao); - Mockito.when(xUserPermissionDao.findByModuleIdAndPortalUserId(null, null)).thenReturn(xUserPermissionObj); - Mockito.when(xUserPermissionService.createResource((VXUserPermission) Mockito.any())).thenReturn(userPermission); - Mockito.when(sessionMgr.getActiveUserSessionsForPortalUserId(userId)).thenReturn(userSessions); - Mockito.when(xUserService.createResource((VXUser) Mockito.any())).thenReturn(vXUser); - Mockito.when(xUserPermissionService.populateViewBean(xUserPermissionObj)).thenReturn(userPermission); - Mockito.when(xUserPermissionService.updateResource((VXUserPermission) Mockito.any())).thenReturn(userPermission); - Mockito.when(daoManager.getXXPortalUser()).thenReturn(userDao); - VXUser loggedInUser = vxUser(); - List loggedInUserRole = new ArrayList(); - loggedInUserRole.add(RangerConstants.ROLE_SYS_ADMIN); - loggedInUser.setId(8L); - loggedInUser.setName("testuser"); - loggedInUser.setUserRoleList(loggedInUserRole); - Mockito.when(xUserService.getXUserByUserName("admin")).thenReturn(loggedInUser); - xUserMgr.createOrUpdateXUsers(users); - - vXUser.setPassword("*****"); - xUserMgr.createOrUpdateXUsers(users); - } - - @Test - public void test113CreateOrUpdateXUsers() { - destroySession(); - setup(); - VXUser vXUser = vxUser(); - vXUser.setFirstName("null"); - vXUser.setLastName("null"); - List vXUserList=new ArrayList(); - vXUserList.add(vXUser); - VXUserList users = new VXUserList(vXUserList); - XXUserDao xxUserDao = Mockito.mock(XXUserDao.class); - XXModuleDefDao xXModuleDefDao = Mockito.mock(XXModuleDefDao.class); - XXUser xXUser = xxUser(vXUser); - VXPortalUser vXPortalUser = userProfile(); - vXPortalUser.setFirstName("null"); - vXPortalUser.setLastName("null"); - XXPortalUser xXPortalUser = xxPortalUser(vXPortalUser); - xXPortalUser.setUserSource(RangerCommonEnums.USER_EXTERNAL); - List lstRole = new ArrayList(); - lstRole.add(RangerConstants.ROLE_SYS_ADMIN); - List xXModuleDefs=new ArrayList(); - - vXPortalUser.setUserRoleList(lstRole); - Mockito.when(userMgr.getUserProfileByLoginId(vXUser.getName())).thenReturn(vXPortalUser); - - Mockito.when(daoManager.getXXUser()).thenReturn(xxUserDao); - Mockito.when(xxUserDao.findByUserName(vXUser.getName())).thenReturn(xXUser); - Mockito.when(daoManager.getXXModuleDef()).thenReturn(xXModuleDefDao); - Mockito.when(xXModuleDefDao.getAll()).thenReturn(xXModuleDefs); - Mockito.when(xUserService.updateResource(vXUser)).thenReturn(vXUser); - - XXUserPermissionDao xUserPermissionDao = Mockito.mock(XXUserPermissionDao.class); - Mockito.when(daoManager.getXXUserPermission()).thenReturn(xUserPermissionDao); - List xUserPermissionsList = new ArrayList(); - XXUserPermission xUserPermissionObj = new XXUserPermission(); - xUserPermissionObj.setAddedByUserId(userId); - xUserPermissionObj.setCreateTime(new Date()); - xUserPermissionObj.setId(userId); - xUserPermissionObj.setIsAllowed(1); - xUserPermissionObj.setModuleId(1L); - xUserPermissionObj.setUpdatedByUserId(userId); - xUserPermissionObj.setUpdateTime(new Date()); - xUserPermissionObj.setUserId(userId); - xUserPermissionsList.add(xUserPermissionObj); - Mockito.when(xUserPermissionDao.findByUserPermissionId(vXPortalUser.getId())).thenReturn(xUserPermissionsList); - VXUser loggedInUser = vxUser(); - List loggedInUserRole = new ArrayList(); - loggedInUserRole.add(RangerConstants.ROLE_SYS_ADMIN); - loggedInUser.setId(8L); - loggedInUser.setName("testuser"); - loggedInUser.setUserRoleList(loggedInUserRole); - Mockito.when(xUserService.getXUserByUserName("admin")).thenReturn(loggedInUser); - xUserMgr.createOrUpdateXUsers(users); - vXUserList.clear(); - vXUser.setUserSource(RangerCommonEnums.USER_APP); - vXUser.setFirstName("testuser"); - vXUser.setLastName("testuser"); - vXUser.setPassword("TestPassword@123"); - vXUserList.add(vXUser); - users = new VXUserList(vXUserList); - vXPortalUser = userProfile(); - vXPortalUser.setUserSource(RangerCommonEnums.USER_APP); - vXPortalUser.setFirstName("testuser"); - vXPortalUser.setLastName("testuser"); - vXPortalUser.setPassword("TestPassword@123"); - vXPortalUser.setUserRoleList(lstRole); - Mockito.when(userMgr.getUserProfileByLoginId(vXUser.getName())).thenReturn(vXPortalUser); - Mockito.when(userMgr.updateUserWithPass((VXPortalUser) Mockito.any())).thenReturn(xXPortalUser); - xUserMgr.createOrUpdateXUsers(users); - vXUser.setPassword("*****"); - xUserMgr.createOrUpdateXUsers(users); - } - - @Test - public void test114CreateOrUpdateXGroups() { - destroySession(); - setup(); - VXGroup vXGroup = vxGroup(); - VXGroupList vXGroupListSort = new VXGroupList(); - List vXGroups = new ArrayList(); - vXGroups.add(vXGroup); - VXGroup vXGroup1 = vxGroup(); - vXGroup1.setName("null"); - vXGroups.add(vXGroup1); - vXGroupListSort.setVXGroups(vXGroups); - - VXUser vXUser = vxUser(); - List vXUserList=new ArrayList(); - vXUserList.add(vXUser); - VXPortalUser vXPortalUser = userProfile(); - XXPortalUser xXPortalUser = xxPortalUser(vXPortalUser); - xXPortalUser.setUserSource(RangerCommonEnums.USER_EXTERNAL); - List lstRole = new ArrayList(); - lstRole.add(RangerConstants.ROLE_SYS_ADMIN); - - vXPortalUser.setUserRoleList(lstRole); - - List xUserPermissionsList = new ArrayList(); - XXUserPermission xUserPermissionObj = new XXUserPermission(); - xUserPermissionObj.setAddedByUserId(userId); - xUserPermissionObj.setCreateTime(new Date()); - xUserPermissionObj.setId(userId); - xUserPermissionObj.setIsAllowed(1); - xUserPermissionObj.setModuleId(1L); - xUserPermissionObj.setUpdatedByUserId(userId); - xUserPermissionObj.setUpdateTime(new Date()); - xUserPermissionObj.setUserId(userId); - xUserPermissionsList.add(xUserPermissionObj); - xUserMgr.createOrUpdateXGroups(vXGroupListSort); - } - - @Test - public void test115UpdateUserRoleAssignments() { - destroySession(); - setup(); - UsersGroupRoleAssignments ugRoleAssignments = new UsersGroupRoleAssignments(); - Set addUsers = new HashSet(); - Set delUsers = new HashSet(); - addUsers.add("testuser"); - addUsers.add("testuser2"); - delUsers.add("testuser2"); - Map userMap = new HashMap(); - Map groupMap = new HashMap<>(); - List allUsers = new ArrayList<>(addUsers); - userMap.put("testuser", "role1"); - userMap.put("testuser2", "role2"); - groupMap.put("testgroup1", "role1"); - groupMap.put("testgroup2", "role2"); - ugRoleAssignments.setUsers(allUsers); - ugRoleAssignments.setGroupRoleAssignments(groupMap); - ugRoleAssignments.setUserRoleAssignments(userMap); - ugRoleAssignments.setWhiteListUserRoleAssignments(new HashMap<>()); - ugRoleAssignments.setWhiteListGroupRoleAssignments(new HashMap<>()); - VXUser vXUser = vxUser(); - List vXUserList=new ArrayList(); - vXUserList.add(vXUser); - VXPortalUser vXPortalUser = userProfile(); - XXPortalUser xXPortalUser = xxPortalUser(vXPortalUser); - xXPortalUser.setUserSource(RangerCommonEnums.USER_EXTERNAL); - List lstRole = new ArrayList(); - lstRole.add(RangerConstants.ROLE_SYS_ADMIN); - vXPortalUser.setUserRoleList(lstRole); - Mockito.when(userMgr.getUserProfileByLoginId(vXUser.getName())).thenReturn(vXPortalUser); - - XXUserPermissionDao xUserPermissionDao = Mockito.mock(XXUserPermissionDao.class); - Mockito.when(daoManager.getXXUserPermission()).thenReturn(xUserPermissionDao); - List xUserPermissionsList = new ArrayList(); - XXUserPermission xUserPermissionObj = new XXUserPermission(); - xUserPermissionObj.setAddedByUserId(userId); - xUserPermissionObj.setCreateTime(new Date()); - xUserPermissionObj.setId(userId); - xUserPermissionObj.setIsAllowed(1); - xUserPermissionObj.setModuleId(1L); - xUserPermissionObj.setUpdatedByUserId(userId); - xUserPermissionObj.setUpdateTime(new Date()); - xUserPermissionObj.setUserId(userId); - xUserPermissionsList.add(xUserPermissionObj); - Mockito.when(xUserPermissionDao.findByUserPermissionId(vXPortalUser.getId())).thenReturn(xUserPermissionsList); - - List xXModuleDefs = xxModuleDefs(); - XXModuleDefDao xXModuleDefDao = Mockito.mock(XXModuleDefDao.class); - Mockito.when(daoManager.getXXModuleDef()).thenReturn(xXModuleDefDao); - Mockito.when(daoManager.getXXModuleDef().getAll()).thenReturn(xXModuleDefs); - xUserMgr.updateUserRoleAssignments(ugRoleAssignments); - - allUsers.clear(); - allUsers.add("UnMappedUser"); - ugRoleAssignments.setUsers(allUsers); - ugRoleAssignments.setGroupRoleAssignments(groupMap); - ugRoleAssignments.setUserRoleAssignments(userMap); - - VXUserPermission userPermission = vxUserPermission(); - List userPermList = new ArrayList(); - userPermList.add(userPermission); - List xUserPermissionsList1 = new ArrayList(); - XXUserPermission xUserPermissionObj1 = xxUserPermission(); - xUserPermissionObj1.setModuleId(userPermission.getModuleId()); - xUserPermissionObj1.setUserId(userPermission.getUserId()); - xUserPermissionsList1.add(xUserPermissionObj1); - UserSessionBase userSession = Mockito.mock(UserSessionBase.class); - Set userSessions = new HashSet(); - userSessions.add(userSession); - xUserMgr.updateUserRoleAssignments(ugRoleAssignments); - - vXPortalUser.setUserSource(RangerCommonEnums.USER_APP); - Mockito.when(userMgr.getUserProfileByLoginId(Mockito.anyString())).thenReturn(vXPortalUser); - xUserMgr.updateUserRoleAssignments(ugRoleAssignments); - } - - @Test - public void test116GetGroups() { - destroySession(); - setup(); - VXGroup vXGroup = vxGroup(); - XXGroup xxGroup = new XXGroup(); - xxGroup.setId(vXGroup.getId()); - xxGroup.setName(vXGroup.getName()); - xxGroup.setDescription(vXGroup.getDescription()); - xxGroup.setIsVisible(vXGroup.getIsVisible()); - List resultList = new ArrayList(); - resultList.add(xxGroup); - xUserMgr.getGroups(); - } - - @Test - public void test117GetUserGroups() { - destroySession(); - setup(); - String user = "testuser1"; - Set userGroups = new HashSet(); - userGroups.add("group1"); - Map> userGroupMap = new HashMap>(); - userGroupMap.put(user, userGroups); - XXUserDao xxUserDao = Mockito.mock(XXUserDao.class); - Mockito.when(daoManager.getXXUser()).thenReturn(xxUserDao); - Mockito.when(xxUserDao.findGroupsByUserIds()).thenReturn(userGroupMap); - Map> userGroupMap1 = xUserMgr.getUserGroups(); - Assert.assertNotNull(userGroupMap1); - Assert.assertEquals(userGroupMap, userGroupMap1); - } - - @Test - public void test118GetUsers() { - destroySession(); - setup(); - VXUser vXUser = vxUser(); - UserInfo userInfo = new UserInfo(vXUser.getName(), vXUser.getDescription(), null); - Set userInfoSet = new HashSet(); - userInfoSet.add(userInfo); - List userInfoList = new ArrayList(); - userInfoList.add(userInfo); - XXUser xxUser = xxUser(vXUser); - List resultList = new ArrayList(); - resultList.add(xxUser); - Set userInfoSet1 = xUserMgr.getUsers(); - Assert.assertNotNull(userInfoSet1); - Mockito.when(xUserService.getUsers()).thenReturn(userInfoList); - Set userInfoSet2 = xUserMgr.getUsers(); - Assert.assertNotNull(userInfoSet2); - Assert.assertEquals(userInfoSet, userInfoSet2); - } - - @Test - public void test119GetRangerUserStore() throws Exception { - destroySession(); - setup(); - Long lastKnownUserStoreVersion=Long.valueOf(1); - Mockito.when(xxGlobalStateDao.getAppDataVersion(RANGER_USER_GROUP_GLOBAL_STATE_NAME)).thenReturn(lastKnownUserStoreVersion); - Map> userGroupMap = new HashMap>(); - XXUserDao xxUserDao = Mockito.mock(XXUserDao.class); - Mockito.when(daoManager.getXXUser()).thenReturn(xxUserDao); - Mockito.when(xxUserDao.findGroupsByUserIds()).thenReturn(userGroupMap); - xUserMgr.getRangerUserStoreIfUpdated(lastKnownUserStoreVersion); - } - - @Test - public void test120GetUserStoreVersion() throws Exception { - destroySession(); - setup(); - Long lastKnownUserStoreVersion=Long.valueOf(1); - Mockito.when(xxGlobalStateDao.getAppDataVersion(RANGER_USER_GROUP_GLOBAL_STATE_NAME)).thenReturn(lastKnownUserStoreVersion); - Long userStoreVersion = xUserMgr.getUserStoreVersion(); - Assert.assertNotNull(userStoreVersion); - Assert.assertEquals(lastKnownUserStoreVersion, userStoreVersion); - } - - @Test - public void test121UpdateDeletedUsers() { - destroySession(); - setup(); - XXUserDao xxUserDao = Mockito.mock(XXUserDao.class); - VXUser vxUser = vxUser(); - XXUser xXUser = xxUser(vxUser); - Set delUsers = new HashSet(); - delUsers.add(vxUser.getName()); - Mockito.when(daoManager.getXXUser()).thenReturn(xxUserDao); - Mockito.when(xxUserDao.findByUserName(vxUser.getName())).thenReturn(xXUser); - Mockito.when(xUserService.populateViewBean(xXUser)).thenReturn(vxUser); - Mockito.when(xUserService.updateResource(vxUser)).thenReturn(vxUser); - int count = xUserMgr.updateDeletedUsers(delUsers); - Assert.assertNotNull(count); - Assert.assertEquals(count, 1); - } - - @Test - public void test122UpdateDeletedGroups() { - destroySession(); - setup(); - XXGroupDao xxGroupDao = Mockito.mock(XXGroupDao.class); - VXGroup vxGroup = vxGroup(); - XXGroup xxGroup = new XXGroup(); - xxGroup.setId(vxGroup.getId()); - xxGroup.setName(vxGroup.getName()); - xxGroup.setDescription(vxGroup.getDescription()); - xxGroup.setIsVisible(vxGroup.getIsVisible()); - Set delGroups = new HashSet(); - delGroups.add(vxGroup.getName()); - Mockito.when(daoManager.getXXGroup()).thenReturn(xxGroupDao); - Mockito.when(xxGroupDao.findByGroupName(vxGroup.getName())).thenReturn(xxGroup); - Mockito.when(xGroupService.populateViewBean(xxGroup)).thenReturn(vxGroup); - Mockito.when(xGroupService.updateResource(vxGroup)).thenReturn(vxGroup); - int count = xUserMgr.updateDeletedGroups(delGroups); - Assert.assertNotNull(count); - Assert.assertEquals(count, 1); - } - - @Test - public void test123LookupXGroups() { - destroySession(); - setup(); - VXGroup vXGroup = vxGroup(); - VXGroupList vXGroupListSort = new VXGroupList(); - List vXGroups = new ArrayList(); - vXGroups.add(vXGroup); - vXGroupListSort.setVXGroups(vXGroups); - String groupName = vXGroup.getName(); - SearchCriteria testSearchCriteria = createsearchCriteria(); - testSearchCriteria.addParam("name", groupName); - Mockito.when(xGroupService.getGroupByGroupName(groupName)).thenReturn(vXGroup); - Mockito.when(xGroupService.searchXGroups((SearchCriteria) Mockito.any())).thenReturn(vXGroupListSort); - VXGroupList vXGroupList = xUserMgr.searchXGroups(testSearchCriteria); - testSearchCriteria.addParam("isvisible", "true"); - vXGroupList = xUserMgr.lookupXGroups(testSearchCriteria); - Assert.assertNotNull(vXGroupList); - testSearchCriteria = createsearchCriteria(); - testSearchCriteria.addParam("name", groupName); - testSearchCriteria.addParam("groupsource", 1L); - vXGroupList = xUserMgr.lookupXGroups(testSearchCriteria); - Assert.assertNotNull(vXGroupList); - testSearchCriteria = createsearchCriteria(); - testSearchCriteria.setSortBy(""); - testSearchCriteria.addParam("name", groupName); - Mockito.when(xGroupService.getGroupByGroupName(Mockito.anyString())).thenReturn(vXGroup); - vXGroupList = xUserMgr.lookupXGroups(testSearchCriteria); - Assert.assertNotNull(vXGroupList); - - SearchCriteria emptyCriteria = new SearchCriteria(); - Mockito.when(xGroupService.searchXGroups((SearchCriteria) Mockito.any())).thenReturn(null); - vXGroupList = xUserMgr.lookupXGroups(emptyCriteria); - Assert.assertNull(vXGroupList); - } - - @Test - public void test124LookupXUsers() { - destroySession(); - setup(); - VXUser vXUser = vxUser(); - VXUserList vXUserList1 = new VXUserList(); - List vXUsers = new ArrayList(); - vXUsers.add(vXUser); - vXUserList1.setVXUsers(vXUsers); - String groupName = vXUser.getName(); - SearchCriteria searchCriteria = createsearchCriteria(); - searchCriteria.addParam("name", groupName); - searchCriteria.addParam("isvisible", "true"); - Mockito.when(xUserService.lookupXUsers((SearchCriteria) Mockito.any(), (VXUserList) Mockito.any())).thenReturn(vXUserList1); - VXUserList vXUserList2 = xUserMgr.lookupXUsers(searchCriteria); - Assert.assertNotNull(vXUserList2); - Assert.assertEquals(vXUserList1, vXUserList2); - searchCriteria.setSortBy(""); - vXUserList2 = xUserMgr.lookupXUsers(searchCriteria); - Assert.assertNotNull(vXUserList2); - Assert.assertEquals(vXUserList1, vXUserList2); - } - - @Test - public void test125DeleteXUser() { - destroySession(); - setup(); - boolean force = true; - VXUser vXUser = vxUser(); - XXUser xXUser = new XXUser(); - XXUserDao xXUserDao = Mockito.mock(XXUserDao.class); - Mockito.when(daoManager.getXXUser()).thenReturn(xXUserDao); - Mockito.when(xXUserDao.getById(vXUser.getId())).thenReturn(xXUser); - Mockito.when(xUserService.populateViewBean(xXUser)).thenReturn(vXUser); - VXPermMapList vXPermMapList = new VXPermMapList(); - VXPermMap vXPermMap1=getVXPermMap(); - List vXPermMaps=new ArrayList(); - vXPermMaps.add(vXPermMap1); - vXPermMapList.setVXPermMaps(vXPermMaps); - VXAuditMapList vXAuditMapList = new VXAuditMapList(); - List vXAuditMaps=new ArrayList(); - VXAuditMap vXAuditMap=getVXAuditMap(); - vXAuditMaps.add(vXAuditMap); - vXAuditMapList.setVXAuditMaps(vXAuditMaps); - VXPortalUser vXPortalUser = userProfile(); - XXPortalUser xXPortalUser = xxPortalUser(vXPortalUser); - XXPortalUserDao xXPortalUserDao = Mockito.mock(XXPortalUserDao.class); - Mockito.when(daoManager.getXXPortalUser()).thenReturn(xXPortalUserDao); - Mockito.when(xXPortalUserDao.findByLoginId(vXUser.getName().trim())).thenReturn(xXPortalUser); - Mockito.when(xPortalUserService.populateViewBean(xXPortalUser)).thenReturn(vXPortalUser); - XXPortalUserRole XXPortalUserRole = new XXPortalUserRole(); - XXPortalUserRole.setId(userId); - XXPortalUserRole.setUserId(userId); - XXPortalUserRole.setUserRole("ROLE_USER"); - List xXAuthSessions=new ArrayList(); - XXAuthSession xXAuthSession = new XXAuthSession(); - xXAuthSession.setId(userId); - xXAuthSession.setLoginId(vXPortalUser.getLoginId()); - xXAuthSessions.add(xXAuthSession); - List xXUserPermissions=new ArrayList(); - xXUserPermissions.add(xxUserPermission()); - List xXPortalUserRoles=new ArrayList(); - xXPortalUserRoles.add(XXPortalUserRole); - List xXPolicyList = new ArrayList(); - XXPolicy xXPolicy=getXXPolicy(); - xXPolicyList.add(xXPolicy); - - XXSecurityZoneRefUser xZoneAdminUser = new XXSecurityZoneRefUser(); - xZoneAdminUser.setZoneId(2L); - xZoneAdminUser.setUserId(userId); - xZoneAdminUser.setUserName(vXUser.getName()); - xZoneAdminUser.setUserType(1); - List zoneSecRefUser=new ArrayList(); - zoneSecRefUser.add(xZoneAdminUser); - XXSecurityZoneRefUserDao zoneSecRefUserDao=Mockito.mock(XXSecurityZoneRefUserDao.class); - Mockito.when(daoManager.getXXSecurityZoneRefUser()).thenReturn(zoneSecRefUserDao); - Mockito.when(zoneSecRefUserDao.findByUserId(userId)).thenReturn(zoneSecRefUser); - - RangerSecurityZone securityZone = new RangerSecurityZone(); - securityZone.setId(2L); - securityZone.setName("sz1"); - XXSecurityZone xxSecurityZone = new XXSecurityZone(); - xxSecurityZone.setId(2L); - xxSecurityZone.setName("sz1"); - - XXSecurityZoneDao xXSecurityZoneDao = Mockito.mock(XXSecurityZoneDao.class); - Mockito.when(daoManager.getXXSecurityZoneDao()).thenReturn(xXSecurityZoneDao); - Mockito.when(xXSecurityZoneDao.getById(xZoneAdminUser.getZoneId())).thenReturn(xxSecurityZone); - - List roleRefUser=new ArrayList(); - XXRoleRefUser xRoleRefUser = new XXRoleRefUser(); - xRoleRefUser.setRoleId(userId); - xRoleRefUser.setUserId(userId); - xRoleRefUser.setUserName(vXUser.getName().trim()); - xRoleRefUser.setUserType(0); - roleRefUser.add(xRoleRefUser); - XXRole xRole = new XXRole(); - xRole.setId(userId); - xRole.setName("Role1"); - - VXResponse vXResponse = new VXResponse(); - vXResponse.setStatusCode(HttpServletResponse.SC_BAD_REQUEST); - vXResponse.setMsgDesc("Can Not Delete User '" + vXUser.getName().trim() + "' as its present in " + RangerConstants.ROLE_FIELD); - Mockito.when(restErrorUtil.generateRESTException((VXResponse) Mockito.any())).thenThrow(new WebApplicationException()); - thrown.expect(WebApplicationException.class); - - xUserMgr.deleteXUser(vXUser.getId(), force); - force=false; - xUserMgr.deleteXUser(vXUser.getId(), force); - } - - @Test - public void test126DeleteXGroup() { - destroySession(); - setup(); - boolean force = true; - VXGroup vXGroup = vxGroup(); - VXPermMapList vXPermMapList = new VXPermMapList(); - VXPermMap vXPermMap1=getVXPermMap(); - List vXPermMaps=new ArrayList(); - vXPermMaps.add(vXPermMap1); - vXPermMapList.setVXPermMaps(vXPermMaps); - VXAuditMapList vXAuditMapList = new VXAuditMapList(); - List vXAuditMaps=new ArrayList(); - VXAuditMap vXAuditMap=getVXAuditMap(); - vXAuditMaps.add(vXAuditMap); - vXAuditMapList.setVXAuditMaps(vXAuditMaps); - List xXGroupGroups = new ArrayList(); - XXGroupGroup xXGroupGroup = xxGroupGroup(); - xXGroupGroups.add(xXGroupGroup); - List xXGroupPermissions=new ArrayList(); - XXGroupPermission xGroupPermissionObj = xxGroupPermission(); - xXGroupPermissions.add(xGroupPermissionObj); - List xXPolicyList = new ArrayList(); - XXPolicy xXPolicy=getXXPolicy(); - xXPolicyList.add(xXPolicy); - List xResourceList = new ArrayList(); - XXResource xXResource = new XXResource(); - xXResource.setId(userId); - xXResource.setName("hadoopdev"); - xXResource.setIsRecursive(AppConstants.BOOL_TRUE); - xXResource.setResourceStatus(AppConstants.STATUS_ENABLED); - xResourceList.add(xXResource); - - XXSecurityZoneRefGroup xZoneAdminGroup = new XXSecurityZoneRefGroup(); - xZoneAdminGroup.setZoneId(2L); - xZoneAdminGroup.setGroupId(vXGroup.getId()); - xZoneAdminGroup.setGroupName(vXGroup.getName()); - xZoneAdminGroup.setGroupType(1); - List zoneSecRefGroup=new ArrayList(); - zoneSecRefGroup.add(xZoneAdminGroup); - XXSecurityZoneRefGroupDao zoneSecRefGroupDao=Mockito.mock(XXSecurityZoneRefGroupDao.class); - Mockito.when(daoManager.getXXSecurityZoneRefGroup()).thenReturn(zoneSecRefGroupDao); - Mockito.when(zoneSecRefGroupDao.findByGroupId(userId)).thenReturn(zoneSecRefGroup); - - RangerSecurityZone securityZone = new RangerSecurityZone(); - securityZone.setId(2L); - securityZone.setName("sz1"); - XXSecurityZone xxSecurityZone = new XXSecurityZone(); - xxSecurityZone.setId(2L); - xxSecurityZone.setName("sz1"); - - XXSecurityZoneDao xXSecurityZoneDao = Mockito.mock(XXSecurityZoneDao.class); - Mockito.when(daoManager.getXXSecurityZoneDao()).thenReturn(xXSecurityZoneDao); - Mockito.when(xXSecurityZoneDao.getById(xZoneAdminGroup.getZoneId())).thenReturn(xxSecurityZone); - - List roleRefGroup = new ArrayList(); - XXRoleRefGroup xRoleRefGroup = new XXRoleRefGroup(); - xRoleRefGroup.setRoleId(userId); - xRoleRefGroup.setGroupId(userId); - xRoleRefGroup.setGroupName(groupName); - xRoleRefGroup.setGroupType(0); - roleRefGroup.add(xRoleRefGroup); - - XXRole xRole = new XXRole(); - xRole.setId(userId); - xRole.setName("Role1"); - - VXResponse vXResponse = new VXResponse(); - vXResponse.setStatusCode(HttpServletResponse.SC_BAD_REQUEST); - vXResponse.setMsgDesc("Can Not Delete Group '" + vXGroup.getName().trim() + "' as its present in " + RangerConstants.ROLE_FIELD); - Mockito.when(restErrorUtil.generateRESTException((VXResponse) Mockito.any())).thenThrow(new WebApplicationException()); - thrown.expect(WebApplicationException.class); - - xUserMgr.deleteXGroup(vXGroup.getId(), force); - } - - @Test - public void test127DeleteXUser() { - destroySession(); - setup(); - boolean force = true; - VXUser vXUser = vxUser(); - XXUser xXUser = new XXUser(); - XXUserDao xXUserDao = Mockito.mock(XXUserDao.class); - Mockito.when(daoManager.getXXUser()).thenReturn(xXUserDao); - Mockito.when(xXUserDao.getById(vXUser.getId())).thenReturn(xXUser); - Mockito.when(xUserService.populateViewBean(xXUser)).thenReturn(vXUser); - VXPermMapList vXPermMapList = new VXPermMapList(); - VXPermMap vXPermMap1=getVXPermMap(); - List vXPermMaps=new ArrayList(); - vXPermMaps.add(vXPermMap1); - vXPermMapList.setVXPermMaps(vXPermMaps); - VXAuditMapList vXAuditMapList = new VXAuditMapList(); - List vXAuditMaps=new ArrayList(); - VXAuditMap vXAuditMap=getVXAuditMap(); - vXAuditMaps.add(vXAuditMap); - vXAuditMapList.setVXAuditMaps(vXAuditMaps); - VXPortalUser vXPortalUser = userProfile(); - XXPortalUser xXPortalUser = xxPortalUser(vXPortalUser); - XXPortalUserDao xXPortalUserDao = Mockito.mock(XXPortalUserDao.class); - Mockito.when(daoManager.getXXPortalUser()).thenReturn(xXPortalUserDao); - Mockito.when(xXPortalUserDao.findByLoginId(vXUser.getName().trim())).thenReturn(xXPortalUser); - Mockito.when(xPortalUserService.populateViewBean(xXPortalUser)).thenReturn(vXPortalUser); - XXPortalUserRole XXPortalUserRole = new XXPortalUserRole(); - XXPortalUserRole.setId(userId); - XXPortalUserRole.setUserId(userId); - XXPortalUserRole.setUserRole("ROLE_USER"); - List xXAuthSessions=new ArrayList(); - XXAuthSession xXAuthSession = new XXAuthSession(); - xXAuthSession.setId(userId); - xXAuthSession.setLoginId(vXPortalUser.getLoginId()); - xXAuthSessions.add(xXAuthSession); - List xXUserPermissions=new ArrayList(); - xXUserPermissions.add(xxUserPermission()); - List xXPortalUserRoles=new ArrayList(); - xXPortalUserRoles.add(XXPortalUserRole); - List xXPolicyList = new ArrayList(); - XXPolicy xXPolicy=getXXPolicy(); - xXPolicyList.add(xXPolicy); - - List zoneSecRefUser=new ArrayList(); - XXSecurityZoneRefUserDao zoneSecRefUserDao=Mockito.mock(XXSecurityZoneRefUserDao.class); - Mockito.when(daoManager.getXXSecurityZoneRefUser()).thenReturn(zoneSecRefUserDao); - Mockito.when(zoneSecRefUserDao.findByUserId(userId)).thenReturn(zoneSecRefUser); - - List roleRefUser=new ArrayList(); - XXRoleRefUser xRoleRefUser = new XXRoleRefUser(); - xRoleRefUser.setRoleId(userId); - xRoleRefUser.setUserId(userId); - xRoleRefUser.setUserName(vXUser.getName().trim()); - xRoleRefUser.setUserType(0); - roleRefUser.add(xRoleRefUser); - XXRoleRefUserDao roleRefUserDao=Mockito.mock(XXRoleRefUserDao.class); - Mockito.when(daoManager.getXXRoleRefUser()).thenReturn(roleRefUserDao); - Mockito.when(roleRefUserDao.findByUserId(userId)).thenReturn(roleRefUser); - XXRole xRole = new XXRole(); - xRole.setId(userId); - xRole.setName("Role1"); - XXRoleDao roleDao=Mockito.mock(XXRoleDao.class); - Mockito.when(daoManager.getXXRole()).thenReturn(roleDao); - Mockito.when(roleDao.getById(xRoleRefUser.getRoleId())).thenReturn(xRole); - - VXResponse vXResponse = new VXResponse(); - vXResponse.setStatusCode(HttpServletResponse.SC_BAD_REQUEST); - vXResponse.setMsgDesc("Can Not Delete User '" + vXUser.getName().trim() + "' as its present in " + RangerConstants.ROLE_FIELD); - Mockito.when(restErrorUtil.generateRESTException((VXResponse) Mockito.any())).thenThrow(new WebApplicationException()); - thrown.expect(WebApplicationException.class); - - xUserMgr.deleteXUser(vXUser.getId(), force); - force=false; - xUserMgr.deleteXUser(vXUser.getId(), force); - } - - @Test - public void test128DeleteXGroup() { - destroySession(); - setup(); - boolean force = true; - VXGroup vXGroup = vxGroup(); - VXPermMapList vXPermMapList = new VXPermMapList(); - VXPermMap vXPermMap1=getVXPermMap(); - List vXPermMaps=new ArrayList(); - vXPermMaps.add(vXPermMap1); - vXPermMapList.setVXPermMaps(vXPermMaps); - VXAuditMapList vXAuditMapList = new VXAuditMapList(); - List vXAuditMaps=new ArrayList(); - VXAuditMap vXAuditMap=getVXAuditMap(); - vXAuditMaps.add(vXAuditMap); - vXAuditMapList.setVXAuditMaps(vXAuditMaps); - List xXGroupGroups = new ArrayList(); - XXGroupGroup xXGroupGroup = xxGroupGroup(); - xXGroupGroups.add(xXGroupGroup); - List xXGroupPermissions=new ArrayList(); - XXGroupPermission xGroupPermissionObj = xxGroupPermission(); - xXGroupPermissions.add(xGroupPermissionObj); - List xXPolicyList = new ArrayList(); - XXPolicy xXPolicy=getXXPolicy(); - xXPolicyList.add(xXPolicy); - List xResourceList = new ArrayList(); - XXResource xXResource = new XXResource(); - xXResource.setId(userId); - xXResource.setName("hadoopdev"); - xXResource.setIsRecursive(AppConstants.BOOL_TRUE); - xXResource.setResourceStatus(AppConstants.STATUS_ENABLED); - xResourceList.add(xXResource); - - List zoneSecRefGroup=new ArrayList(); - XXSecurityZoneRefGroupDao zoneSecRefGroupDao=Mockito.mock(XXSecurityZoneRefGroupDao.class); - Mockito.when(daoManager.getXXSecurityZoneRefGroup()).thenReturn(zoneSecRefGroupDao); - Mockito.when(zoneSecRefGroupDao.findByGroupId(userId)).thenReturn(zoneSecRefGroup); - - List roleRefGroup = new ArrayList(); - XXRoleRefGroup xRoleRefGroup = new XXRoleRefGroup(); - xRoleRefGroup.setRoleId(userId); - xRoleRefGroup.setGroupId(userId); - xRoleRefGroup.setGroupName(groupName); - xRoleRefGroup.setGroupType(0); - roleRefGroup.add(xRoleRefGroup); - XXRoleRefGroupDao roleRefGroupDao = Mockito.mock(XXRoleRefGroupDao.class); - Mockito.when(daoManager.getXXRoleRefGroup()).thenReturn(roleRefGroupDao); - Mockito.when(roleRefGroupDao.findByGroupId(userId)).thenReturn(roleRefGroup); - - XXRole xRole = new XXRole(); - xRole.setId(userId); - xRole.setName("Role1"); - XXRoleDao roleDao=Mockito.mock(XXRoleDao.class); - Mockito.when(daoManager.getXXRole()).thenReturn(roleDao); - Mockito.when(roleDao.getById(xRoleRefGroup.getRoleId())).thenReturn(xRole); - - VXResponse vXResponse = new VXResponse(); - vXResponse.setStatusCode(HttpServletResponse.SC_BAD_REQUEST); - vXResponse.setMsgDesc("Can Not Delete Group '" + vXGroup.getName().trim() + "' as its present in " + RangerConstants.ROLE_FIELD); - Mockito.when(restErrorUtil.generateRESTException((VXResponse) Mockito.any())).thenThrow(new WebApplicationException()); - thrown.expect(WebApplicationException.class); - - xUserMgr.deleteXGroup(vXGroup.getId(), force); - } - - @Test - public void test129CreateOrUpdateUserPermisson() { - destroySession(); - setup(); - VXPortalUser vXPortalUser = userProfile(); - List xXModuleDefs = xxModuleDefs(); - - VXUserPermission userPermission = vxUserPermission(); - List userPermList = new ArrayList(); - userPermList.add(userPermission); - List xUserPermissionsList = new ArrayList(); - XXUserPermission xUserPermission = xxUserPermission(); - xUserPermission.setModuleId(userPermission.getModuleId()); - xUserPermission.setUserId(userPermission.getUserId()); - xUserPermissionsList.add(xUserPermission); - - XXUserPermissionDao xXUserPermissionDao= Mockito.mock(XXUserPermissionDao.class); - Mockito.when(daoManager.getXXUserPermission()).thenReturn(xXUserPermissionDao); - Mockito.when(xXUserPermissionDao.findByModuleIdAndPortalUserId(vXPortalUser.getId(),xXModuleDefs.get(0).getId())).thenReturn(xUserPermission); - - VXUser vxUser = vxUser(); - XXUser xXUser = xxUser(vxUser); - XXUserDao xxUserDao = Mockito.mock(XXUserDao.class); - Mockito.when(daoManager.getXXUser()).thenReturn(xxUserDao); - Mockito.when(xxUserDao.findByPortalUserId(vXPortalUser.getId())).thenReturn(xXUser); - - Mockito.when(xUserPermissionService.populateViewBean(xUserPermission)).thenReturn(userPermission); - - Mockito.when(xUserPermissionService.updateResource((VXUserPermission) Mockito.any())).thenReturn(userPermission); - UserSessionBase userSession = Mockito.mock(UserSessionBase.class); - Set userSessions = new HashSet(); - userSessions.add(userSession); - Mockito.when(sessionMgr.getActiveUserSessionsForPortalUserId(userId)).thenReturn(userSessions); - - Collection existingRoleList = new ArrayList(); - existingRoleList.add(RangerConstants.ROLE_SYS_ADMIN); - existingRoleList.add(RangerConstants.ROLE_KEY_ADMIN); - existingRoleList.add(RangerConstants.ROLE_KEY_ADMIN_AUDITOR); - existingRoleList.add(RangerConstants.ROLE_ADMIN_AUDITOR); - vXPortalUser.setUserRoleList(existingRoleList); - xUserMgr.createOrUpdateUserPermisson(vXPortalUser, xXModuleDefs.get(0).getId(), true); - Mockito.when(xXUserPermissionDao.findByModuleIdAndPortalUserId(vXPortalUser.getId(),xXModuleDefs.get(0).getId())).thenReturn(null); - Mockito.when(xxUserDao.findByPortalUserId(vXPortalUser.getId())).thenReturn(null); - xUserMgr.createOrUpdateUserPermisson(vXPortalUser, xXModuleDefs.get(0).getId(), true); - } - - @Test - public void test130UpdateXUser() { - destroySession(); - setup(); - VXUser vxUser = vxUser(); - Mockito.when(restErrorUtil.createRESTException("Please provide a valid username.",MessageEnums.INVALID_INPUT_DATA)).thenThrow(new WebApplicationException()); - thrown.expect(WebApplicationException.class); - vxUser = xUserMgr.updateXUser(null); - Assert.assertNull(vxUser); - } - - @Test - public void test131hasAccess() { - destroySession(); - setup(); - destroySession(); - boolean access = xUserMgr.hasAccess("test"); - Assert.assertEquals(access, false); - } - - @Test - public void test132CreateExternalUser() { - destroySession(); - setup(); - ArrayList roleList = new ArrayList(); - roleList.add(RangerConstants.ROLE_USER); - VXPortalUser vXPortalUser = userProfile(); - XXUserDao xxUserDao = Mockito.mock(XXUserDao.class); - VXUser vXUser = vxUser(); - VXUser createdXUser = vxUser(); - XXUser xXUser = xxUser(vXUser); - Mockito.when(daoManager.getXXUser()).thenReturn(xxUserDao); - Mockito.when(xxUserDao.findByUserName(vXUser.getName())).thenReturn(null, xXUser); - Mockito.when(xUserService.populateViewBean(xXUser)).thenReturn(vXUser); - - vXPortalUser.setUserRoleList(roleList); - List xUserPermissionsList = new ArrayList(); - XXUserPermission xUserPermissionObj = new XXUserPermission(); - xUserPermissionObj.setAddedByUserId(userId); - xUserPermissionObj.setCreateTime(new Date()); - xUserPermissionObj.setId(userId); - xUserPermissionObj.setIsAllowed(1); - xUserPermissionObj.setModuleId(1L); - xUserPermissionObj.setUpdatedByUserId(userId); - xUserPermissionObj.setUpdateTime(new Date()); - xUserPermissionObj.setUserId(userId); - xUserPermissionsList.add(xUserPermissionObj); - - createdXUser = xUserMgr.createExternalUser(vXUser.getName()); - Assert.assertNotNull(createdXUser); - Assert.assertEquals(createdXUser.getName(), vXUser.getName()); - } - - @Test - public void test01CreateXUser_federated() { - destroySession(); - setup(); - VXUser vxUser = vxUserFederated(); - vxUser.setFirstName("user12"); - vxUser.setLastName("test12"); - Collection groupIdList = new ArrayList(); - groupIdList.add(userId); - vxUser.setGroupIdList(groupIdList); - VXGroup vxGroup = vxGroup(); - vxGroup.setName("user12Grp"); - VXGroupUser vXGroupUser = new VXGroupUser(); - vXGroupUser.setParentGroupId(userId); - vXGroupUser.setUserId(userId); - vXGroupUser.setName(vxGroup.getName()); - Mockito.when(xGroupService.readResource(userId)).thenReturn(vxGroup); - Mockito.when(xGroupUserService.createResource((VXGroupUser) Mockito.any())).thenReturn(vXGroupUser); - ArrayList userRoleListVXPortaUser = getRoleList(); - VXPortalUser vXPortalUser = new VXPortalUser(); - vXPortalUser.setUserRoleList(userRoleListVXPortaUser); - Mockito.when(xUserService.createResource(vxUser)).thenReturn(vxUser); - XXModuleDefDao value = Mockito.mock(XXModuleDefDao.class); - Mockito.when(daoManager.getXXModuleDef()).thenReturn(value); - Mockito.when(userMgr.createDefaultAccountUser((VXPortalUser) Mockito.any())).thenReturn(vXPortalUser); - Mockito.when(stringUtil.validateEmail("test@test.com")).thenReturn(true); - VXUser dbUser = xUserMgr.createXUser(vxUser); - Assert.assertNotNull(dbUser); - userId = dbUser.getId(); - Assert.assertEquals(userId, dbUser.getId()); - Assert.assertEquals(dbUser.getDescription(), vxUser.getDescription()); - Assert.assertEquals(dbUser.getName(), vxUser.getName()); - Assert.assertEquals(dbUser.getUserRoleList(), vxUser.getUserRoleList()); - Assert.assertEquals(dbUser.getGroupNameList(), - vxUser.getGroupNameList()); - Assert.assertNotNull(dbUser.getPassword()); - Assert.assertEquals(dbUser.getUserSource(), RangerCommonEnums.USER_FEDERATED); - Mockito.verify(xUserService).createResource(vxUser); - Mockito.when(xUserService.readResourceWithOutLogin(userId)).thenReturn(vxUser); - - VXUser loggedInUser = vxUser(); - List loggedInUserRole = new ArrayList(); - loggedInUserRole.add(RangerConstants.ROLE_ADMIN); - loggedInUser.setId(8L); - loggedInUser.setName("testuser"); - loggedInUser.setUserRoleList(loggedInUserRole); - Mockito.when(xUserService.getXUserByUserName("admin")).thenReturn(loggedInUser); - Mockito.when(restErrorUtil.createRESTException(HttpServletResponse.SC_FORBIDDEN, "Logged-In user is not allowed to access requested user data", true)).thenThrow(new WebApplicationException()); - thrown.expect(WebApplicationException.class); - VXUser dbvxUser = xUserMgr.getXUser(userId); - Mockito.verify(userMgr).createDefaultAccountUser((VXPortalUser) Mockito.any()); - Assert.assertNotNull(dbvxUser); - Assert.assertEquals(userId, dbvxUser.getId()); - Assert.assertEquals(dbvxUser.getDescription(), vxUser.getDescription()); - Assert.assertEquals(dbvxUser.getName(), vxUser.getName()); - Assert.assertEquals(dbvxUser.getUserRoleList(),vxUser.getUserRoleList()); - Assert.assertEquals(dbvxUser.getGroupIdList(),vxUser.getGroupIdList()); - Assert.assertEquals(dbvxUser.getGroupNameList(),vxUser.getGroupNameList()); - Assert.assertNotNull(dbvxUser.getPassword()); - Assert.assertEquals(dbvxUser.getUserSource(), RangerCommonEnums.USER_FEDERATED); - Mockito.verify(xUserService).readResourceWithOutLogin(userId); - } + private static final String RANGER_USER_GROUP_GLOBAL_STATE_NAME = "RangerUserStore"; + private static Long userId = 8L; + private static final String adminLoginID = "admin"; + private static final String keyadminLoginID = "keyadmin"; + private static final String userLoginID = "testuser"; + private static final String groupName = "public"; + private static Integer emptyValue; + @Rule + public ExpectedException thrown = ExpectedException.none(); + @InjectMocks + XUserMgr xUserMgr = new XUserMgr(); + @Mock + XGroupService xGroupService; + @Mock + RangerDaoManager daoManager; + @Mock + RESTErrorUtil restErrorUtil; + @Mock + XGroupUserService xGroupUserService; + @Mock + StringUtil stringUtil; + @Mock + RangerBizUtil msBizUtil; + @Mock + UserMgr userMgr; + @Mock + RangerBizUtil xaBizUtil; + @Mock + XUserService xUserService; + @Mock + XModuleDefService xModuleDefService; + @Mock + XUserPermissionService xUserPermissionService; + @Mock + XGroupPermissionService xGroupPermissionService; + @Mock + ContextUtil contextUtil; + @Mock + RangerSecurityContext rangerSecurityContext; + @Mock + XPortalUserService xPortalUserService; + @Mock + SessionMgr sessionMgr; + @Mock + XPermMapService xPermMapService; + @Mock + XAuditMapService xAuditMapService; + @Mock + RangerPolicyService policyService; + @Mock + ServiceDBStore svcStore; + @Mock + GdsDBStore gdsStore; + @Mock + XGroupGroupService xGroupGroupService; + @Mock + XResourceService xResourceService; + @Mock + XUgsyncAuditInfoService xUgsyncAuditInfoService; + @Mock + RangerTransactionSynchronizationAdapter transactionSynchronizationAdapter; + @Mock + XXGlobalStateDao xxGlobalStateDao; + @Mock + @Qualifier(value = "transactionManager") + PlatformTransactionManager txManager; + + public void setup() { + RangerSecurityContext context = new RangerSecurityContext(); + context.setUserSession(new UserSessionBase()); + RangerContextHolder.setSecurityContext(context); + UserSessionBase currentUserSession = ContextUtil.getCurrentUserSession(); + currentUserSession.setUserAdmin(true); + XXPortalUser xXPortalUser = new XXPortalUser(); + xXPortalUser.setLoginId(adminLoginID); + xXPortalUser.setId(userId); + currentUserSession.setXXPortalUser(xXPortalUser); + Mockito.when(daoManager.getXXGlobalState()).thenReturn(xxGlobalStateDao); + } + + @After + public void destroySession() { + RangerSecurityContext context = new RangerSecurityContext(); + context.setUserSession(null); + RangerContextHolder.setSecurityContext(context); + } + + public void setupKeyAdmin() { + RangerSecurityContext context = new RangerSecurityContext(); + context.setUserSession(new UserSessionBase()); + RangerContextHolder.setSecurityContext(context); + UserSessionBase currentUserSession = ContextUtil.getCurrentUserSession(); + XXPortalUser userKeyAdmin = new XXPortalUser(); + userKeyAdmin.setId(userProfile().getId()); + userKeyAdmin.setLoginId(keyadminLoginID); + currentUserSession.setXXPortalUser(userKeyAdmin); + currentUserSession.setKeyAdmin(true); + } + + public void setupUser() { + RangerSecurityContext context = new RangerSecurityContext(); + context.setUserSession(new UserSessionBase()); + RangerContextHolder.setSecurityContext(context); + UserSessionBase currentUserSession = ContextUtil.getCurrentUserSession(); + XXPortalUser user = new XXPortalUser(); + user.setId(userProfile().getId()); + user.setLoginId(userProfile().getLoginId()); + currentUserSession.setXXPortalUser(user); + currentUserSession.setUserRoleList(getRoleList()); + } + + @Test + public void test01CreateXUser() { + setup(); + VXUser vxUser = vxUser(); + vxUser.setFirstName("user12"); + vxUser.setLastName("test12"); + Collection groupIdList = new ArrayList<>(); + groupIdList.add(userId); + vxUser.setGroupIdList(groupIdList); + VXGroup vxGroup = vxGroup(); + vxGroup.setName("user12Grp"); + VXGroupUser vXGroupUser = new VXGroupUser(); + vXGroupUser.setParentGroupId(userId); + vXGroupUser.setUserId(userId); + vXGroupUser.setName(vxGroup.getName()); + Mockito.when(xGroupService.readResource(userId)).thenReturn(vxGroup); + Mockito.when(xGroupUserService.createResource(Mockito.any())).thenReturn(vXGroupUser); + ArrayList userRoleListVXPortaUser = getRoleList(); + VXPortalUser vXPortalUser = new VXPortalUser(); + vXPortalUser.setUserRoleList(userRoleListVXPortaUser); + Mockito.when(xUserService.createResource(vxUser)).thenReturn(vxUser); + XXModuleDefDao value = Mockito.mock(XXModuleDefDao.class); + Mockito.when(daoManager.getXXModuleDef()).thenReturn(value); + Mockito.when(userMgr.createDefaultAccountUser(Mockito.any())).thenReturn(vXPortalUser); + Mockito.when(stringUtil.validateEmail("test@test.com")).thenReturn(true); + VXUser dbUser = xUserMgr.createXUser(vxUser); + Assert.assertNotNull(dbUser); + userId = dbUser.getId(); + Assert.assertEquals(userId, dbUser.getId()); + Assert.assertEquals(dbUser.getDescription(), vxUser.getDescription()); + Assert.assertEquals(dbUser.getName(), vxUser.getName()); + Assert.assertEquals(dbUser.getUserRoleList(), vxUser.getUserRoleList()); + Assert.assertEquals(dbUser.getGroupNameList(), + vxUser.getGroupNameList()); + Mockito.verify(xUserService).createResource(vxUser); + Mockito.when(xUserService.readResourceWithOutLogin(userId)).thenReturn(vxUser); + + VXUser loggedInUser = vxUser(); + List loggedInUserRole = new ArrayList<>(); + loggedInUserRole.add(RangerConstants.ROLE_ADMIN); + loggedInUser.setId(8L); + loggedInUser.setName("testuser"); + loggedInUser.setUserRoleList(loggedInUserRole); + Mockito.when(xUserService.getXUserByUserName("admin")).thenReturn(loggedInUser); + Mockito.when(restErrorUtil.createRESTException(HttpServletResponse.SC_FORBIDDEN, "Logged-In user is not allowed to access requested user data", true)).thenThrow(new WebApplicationException()); + thrown.expect(WebApplicationException.class); + VXUser dbvxUser = xUserMgr.getXUser(userId); + Mockito.verify(userMgr).createDefaultAccountUser(Mockito.any()); + Assert.assertNotNull(dbvxUser); + Assert.assertEquals(userId, dbvxUser.getId()); + Assert.assertEquals(dbvxUser.getDescription(), vxUser.getDescription()); + Assert.assertEquals(dbvxUser.getName(), vxUser.getName()); + Assert.assertEquals(dbvxUser.getUserRoleList(), vxUser.getUserRoleList()); + Assert.assertEquals(dbvxUser.getGroupIdList(), vxUser.getGroupIdList()); + Assert.assertEquals(dbvxUser.getGroupNameList(), vxUser.getGroupNameList()); + Mockito.verify(xUserService).readResourceWithOutLogin(userId); + } + + @Test + public void test02CreateXUser_WithBlankName() { + setup(); + VXUser vxUser = vxUser(); + ArrayList userRoleListVXPortaUser = getRoleList(); + VXPortalUser vXPortalUser = new VXPortalUser(); + vXPortalUser.setUserRoleList(userRoleListVXPortaUser); + vxUser.setName(null); + Mockito.when(restErrorUtil.createRESTException("Please provide a valid username.", MessageEnums.INVALID_INPUT_DATA)).thenThrow(new WebApplicationException()); + thrown.expect(WebApplicationException.class); + xUserMgr.createXUser(vxUser); + } + + @Test + public void test03CreateXUser_WithBlankName() { + destroySession(); + setup(); + VXUser vxUser = vxUser(); + ArrayList userRoleListVXPortaUser = getRoleList(); + VXPortalUser vXPortalUser = new VXPortalUser(); + vXPortalUser.setUserRoleList(userRoleListVXPortaUser); + vxUser.setName(""); + Mockito.when(restErrorUtil.createRESTException("Please provide a valid username.", MessageEnums.INVALID_INPUT_DATA)).thenThrow(new WebApplicationException()); + thrown.expect(WebApplicationException.class); + xUserMgr.createXUser(vxUser); + } + + @Test + public void testCreateXUser_WithBlankFirstName() { + destroySession(); + setup(); + VXUser vxUser = vxUser(); + vxUser.setName("test"); + vxUser.setFirstName(null); + Mockito.when(restErrorUtil.createRESTException("Please provide a valid first name.", MessageEnums.INVALID_INPUT_DATA)).thenThrow(new WebApplicationException()); + thrown.expect(WebApplicationException.class); + xUserMgr.createXUser(vxUser); + } + + @Test + public void test04CreateXUser_WithBlankValues() { + destroySession(); + setup(); + VXUser vxUser = vxUser(); + vxUser.setDescription(null); + vxUser.setFirstName("test"); + vxUser.setLastName("null"); + Mockito.when(restErrorUtil.createRESTException("Please provide valid email address.", MessageEnums.INVALID_INPUT_DATA)).thenThrow(new WebApplicationException()); + thrown.expect(WebApplicationException.class); + xUserMgr.createXUser(vxUser); + } + + @Test + public void testUpdateXUser_WithBlankFirstName() { + setup(); + VXUser vxUser = vxUser(); + ArrayList userRoleListVXPortaUser = getRoleList(); + VXPortalUser vXPortalUser = new VXPortalUser(); + vXPortalUser.setUserRoleList(userRoleListVXPortaUser); + vxUser.setDescription(null); + vxUser.setFirstName("null"); + Mockito.when(restErrorUtil.createRESTException("Please provide a valid first name.", MessageEnums.INVALID_INPUT_DATA)).thenThrow(new WebApplicationException()); + thrown.expect(WebApplicationException.class); + xUserMgr.updateXUser(vxUser); + } + + @Test + public void testUpdateXUser_WithBlankUserName() { + setup(); + VXUser vxUser = vxUser(); + ArrayList userRoleListVXPortaUser = getRoleList(); + VXPortalUser vXPortalUser = new VXPortalUser(); + vXPortalUser.setUserRoleList(userRoleListVXPortaUser); + vxUser.setDescription(null); + vxUser.setName("null"); + Mockito.when(restErrorUtil.createRESTException("Please provide a valid username.", MessageEnums.INVALID_INPUT_DATA)).thenThrow(new WebApplicationException()); + thrown.expect(WebApplicationException.class); + xUserMgr.updateXUser(vxUser); + } + + @Test + public void test05UpdateXUser() { + setup(); + XXUserPermissionDao xUserPermissionDao = Mockito.mock(XXUserPermissionDao.class); + Collection existingRoleList = new ArrayList<>(); + existingRoleList.add(RangerConstants.ROLE_USER); + Collection reqRoleList = new ArrayList<>(); + reqRoleList.add(RangerConstants.ROLE_SYS_ADMIN); + Collection groupIdList = new ArrayList<>(); + groupIdList.add(userId); + VXUser vxUser = vxUser(); + vxUser.setUserRoleList(reqRoleList); + vxUser.setUserSource(RangerCommonEnums.USER_EXTERNAL); + vxUser.setGroupIdList(groupIdList); + vxUser.setFirstName("user12"); + vxUser.setLastName("test12"); + Mockito.when(xUserService.updateResource(vxUser)).thenReturn(vxUser); + XXModuleDefDao xModuleDefDao = Mockito.mock(XXModuleDefDao.class); + VXPortalUser vXPortalUser = userProfile(); + vXPortalUser.setUserRoleList(existingRoleList); + Mockito.when(userMgr.getUserProfileByLoginId(vxUser.getName())).thenReturn(vXPortalUser); + Mockito.when(daoManager.getXXUserPermission()).thenReturn(xUserPermissionDao); + List xUserPermissionsList = new ArrayList<>(); + XXUserPermission xUserPermissionObj = new XXUserPermission(); + xUserPermissionObj.setAddedByUserId(userId); + xUserPermissionObj.setCreateTime(new Date()); + xUserPermissionObj.setId(userId); + xUserPermissionObj.setIsAllowed(1); + xUserPermissionObj.setModuleId(1L); + xUserPermissionObj.setUpdatedByUserId(userId); + xUserPermissionObj.setUpdateTime(new Date()); + xUserPermissionObj.setUserId(userId); + xUserPermissionsList.add(xUserPermissionObj); + List xXModuleDefs = xxModuleDefs(); + Mockito.when(xUserPermissionDao.findByUserPermissionId(vXPortalUser.getId())).thenReturn(xUserPermissionsList); + Mockito.when(daoManager.getXXModuleDef()).thenReturn(xModuleDefDao); + Mockito.when(xModuleDefDao.getAll()).thenReturn(xXModuleDefs); + XXUser xXUser = xxUser(vxUser); + XXUserDao xxUserDao = Mockito.mock(XXUserDao.class); + Mockito.when(daoManager.getXXUser()).thenReturn(xxUserDao); + Mockito.when(xxUserDao.findByPortalUserId(vXPortalUser.getId())).thenReturn(xXUser); + VXGroupUserList vxGroupUserList = vxGroupUserList(); + Mockito.when(xGroupUserService.searchXGroupUsers(Mockito.any())).thenReturn(vxGroupUserList); + UserSessionBase userSession = Mockito.mock(UserSessionBase.class); + Set userSessions = new HashSet<>(); + userSessions.add(userSession); + VXUserPermission vXUserPermission = vxUserPermission(); + Mockito.when(xUserPermissionService.createResource(Mockito.any())).thenReturn(vXUserPermission); + Mockito.when(sessionMgr.getActiveUserSessionsForPortalUserId(userId)).thenReturn(userSessions); + VXUser loggedInUser = vxUser(); + List loggedInUserRole = new ArrayList<>(); + loggedInUserRole.add(RangerConstants.ROLE_SYS_ADMIN); + loggedInUser.setId(8L); + loggedInUser.setName("testuser"); + loggedInUser.setUserRoleList(loggedInUserRole); + Mockito.when(xUserService.getXUserByUserName("admin")).thenReturn(loggedInUser); + VXUser dbvxUser = xUserMgr.updateXUser(vxUser); + Assert.assertNotNull(dbvxUser); + Assert.assertEquals(dbvxUser.getId(), vxUser.getId()); + Assert.assertEquals(dbvxUser.getDescription(), vxUser.getDescription()); + Assert.assertEquals(dbvxUser.getName(), vxUser.getName()); + Mockito.verify(xUserService).updateResource(vxUser); + groupIdList.clear(); + groupIdList.add(9L); + vxUser.setGroupIdList(groupIdList); + VXGroup vXGroup = vxGroup(); + Mockito.when(xGroupService.readResource(Mockito.anyLong())).thenReturn(vXGroup); + VXGroupUser vXGroupUser = vxGroupUser(); + Mockito.when(xGroupUserService.createResource(Mockito.any())).thenReturn(vXGroupUser); + dbvxUser = xUserMgr.updateXUser(vxUser); + Assert.assertNotNull(dbvxUser); + } + + @Test + public void test06ModifyUserVisibilitySetOne() { + setup(); + XXUserDao xxUserDao = Mockito.mock(XXUserDao.class); + XXUser xxUser = Mockito.mock(XXUser.class); + VXUser vxUser = vxUser(); + Mockito.when(xUserService.updateResource(vxUser)).thenReturn(vxUser); + HashMap visibilityMap = new HashMap<>(); + Integer value = 1; + visibilityMap.put(userId, value); + Mockito.when(daoManager.getXXUser()).thenReturn(xxUserDao); + Mockito.when(xxUserDao.getById(userId)).thenReturn(xxUser); + Mockito.when(xUserService.populateViewBean(xxUser)).thenReturn(vxUser); + xUserMgr.modifyUserVisibility(visibilityMap); + Assert.assertEquals(value, vxUser.getIsVisible()); + Assert.assertEquals(userId, vxUser.getId()); + Mockito.verify(xUserService).updateResource(vxUser); + Mockito.verify(daoManager).getXXUser(); + Mockito.verify(xUserService).populateViewBean(xxUser); + } + + @Test + public void test07ModifyUserVisibilitySetZero() { + setup(); + XXUserDao xxUserDao = Mockito.mock(XXUserDao.class); + XXUser xxUser = Mockito.mock(XXUser.class); + VXUser vxUser = vxUser(); + Mockito.when(xUserService.updateResource(vxUser)).thenReturn(vxUser); + HashMap visibilityMap = new HashMap<>(); + Integer value = 0; + visibilityMap.put(userId, value); + Mockito.when(daoManager.getXXUser()).thenReturn(xxUserDao); + Mockito.when(xxUserDao.getById(userId)).thenReturn(xxUser); + Mockito.when(xUserService.populateViewBean(xxUser)).thenReturn(vxUser); + xUserMgr.modifyUserVisibility(visibilityMap); + Assert.assertEquals(value, vxUser.getIsVisible()); + Assert.assertEquals(userId, vxUser.getId()); + Mockito.verify(xUserService).updateResource(vxUser); + Mockito.verify(daoManager).getXXUser(); + Mockito.verify(xUserService).populateViewBean(xxUser); + } + + @Test + public void test08ModifyUserVisibilitySetEmpty() { + setup(); + XXUserDao xxUserDao = Mockito.mock(XXUserDao.class); + XXUser xxUser = Mockito.mock(XXUser.class); + VXUser vxUser = vxUser(); + Mockito.when(xUserService.updateResource(vxUser)).thenReturn(vxUser); + HashMap visibilityMap = new HashMap<>(); + visibilityMap.put(userId, emptyValue); + Mockito.when(daoManager.getXXUser()).thenReturn(xxUserDao); + Mockito.when(xxUserDao.getById(userId)).thenReturn(xxUser); + Mockito.when(xUserService.populateViewBean(xxUser)).thenReturn(vxUser); + xUserMgr.modifyUserVisibility(visibilityMap); + Assert.assertEquals(emptyValue, vxUser.getIsVisible()); + Assert.assertEquals(userId, vxUser.getId()); + Mockito.verify(xUserService).updateResource(vxUser); + Mockito.verify(daoManager).getXXUser(); + Mockito.verify(xUserService).populateViewBean(xxUser); + } + + @Test + public void test09CreateXGroup() { + setup(); + VXGroup vXGroup = vxGroup(); + vXGroup.setDescription(null); + Mockito.when(xGroupService.createResource(vXGroup)).thenReturn(vXGroup); + VXGroup dbXGroup = xUserMgr.createXGroup(vXGroup); + Assert.assertNotNull(dbXGroup); + userId = dbXGroup.getId(); + Assert.assertEquals(userId, dbXGroup.getId()); + Assert.assertEquals(vXGroup.getName(), dbXGroup.getName()); + Mockito.verify(xGroupService).createResource(vXGroup); + Mockito.when(xGroupService.readResourceWithOutLogin(userId)).thenReturn(vXGroup); + VXGroup dbxGroup = xUserMgr.getXGroup(userId); + Assert.assertNotNull(dbXGroup); + Assert.assertEquals(userId, dbxGroup.getId()); + Assert.assertEquals(dbXGroup.getName(), dbxGroup.getName()); + Mockito.verify(xGroupService).readResourceWithOutLogin(userId); + } + + @Test + public void test10UpdateXGroup() { + XXGroupDao xxGroupDao = Mockito.mock(XXGroupDao.class); + XXGroupUserDao xxGroupUserDao = Mockito.mock(XXGroupUserDao.class); + List grpUsers = new ArrayList<>(); + setup(); + VXGroup vXGroup = vxGroup(); + XXGroup xxGroup = new XXGroup(); + xxGroup.setName(groupName); + Mockito.when(daoManager.getXXGroup()).thenReturn(xxGroupDao); + Mockito.when(xxGroupDao.getById(vXGroup.getId())).thenReturn(xxGroup); + Mockito.when(xGroupService.updateResource(vXGroup)).thenReturn(vXGroup); + Mockito.when(daoManager.getXXGroupUser()).thenReturn(xxGroupUserDao); + Mockito.when(xxGroupUserDao.findByGroupId(vXGroup.getId())).thenReturn(grpUsers); + VXGroup dbvxGroup = xUserMgr.updateXGroup(vXGroup); + Assert.assertNotNull(dbvxGroup); + userId = dbvxGroup.getId(); + Assert.assertEquals(userId, dbvxGroup.getId()); + Assert.assertEquals(vXGroup.getDescription(), dbvxGroup.getDescription()); + Assert.assertEquals(vXGroup.getName(), dbvxGroup.getName()); + Mockito.verify(daoManager).getXXGroup(); + Mockito.verify(daoManager).getXXGroupUser(); + Mockito.verify(xGroupService).updateResource(vXGroup); + Mockito.verify(xxGroupUserDao).findByGroupId(vXGroup.getId()); + Mockito.when(restErrorUtil.createRESTException("group name updates are not allowed.", MessageEnums.INVALID_INPUT_DATA)).thenThrow(new WebApplicationException()); + thrown.expect(WebApplicationException.class); + vXGroup.setName("UnknownGroup"); + xUserMgr.updateXGroup(vXGroup); + } + + @Test + public void test11ModifyGroupsVisibilitySetOne() { + setup(); + XXGroupDao xxGroupDao = Mockito.mock(XXGroupDao.class); + VXGroup vXGroup = vxGroup(); + XXGroup xxGroup = new XXGroup(); + HashMap groupVisibilityMap = new HashMap<>(); + Integer value = 1; + groupVisibilityMap.put(userId, value); + Mockito.when(daoManager.getXXGroup()).thenReturn(xxGroupDao); + Mockito.when(xxGroupDao.getById(vXGroup.getId())).thenReturn(xxGroup); + Mockito.when(xGroupService.populateViewBean(xxGroup)).thenReturn(vXGroup); + Mockito.when(xGroupService.updateResource(vXGroup)).thenReturn(vXGroup); + xUserMgr.modifyGroupsVisibility(groupVisibilityMap); + Assert.assertEquals(value, vXGroup.getIsVisible()); + Assert.assertEquals(userId, vXGroup.getId()); + Mockito.verify(daoManager).getXXGroup(); + Mockito.verify(xGroupService).populateViewBean(xxGroup); + Mockito.verify(xGroupService).updateResource(vXGroup); + } + + @Test + public void test12ModifyGroupsVisibilitySetZero() { + setup(); + XXGroupDao xxGroupDao = Mockito.mock(XXGroupDao.class); + VXGroup vXGroup = vxGroup(); + XXGroup xxGroup = new XXGroup(); + HashMap groupVisibilityMap = new HashMap<>(); + Integer value = 0; + groupVisibilityMap.put(userId, value); + Mockito.when(daoManager.getXXGroup()).thenReturn(xxGroupDao); + Mockito.when(xxGroupDao.getById(vXGroup.getId())).thenReturn(xxGroup); + Mockito.when(xGroupService.populateViewBean(xxGroup)).thenReturn(vXGroup); + Mockito.when(xGroupService.updateResource(vXGroup)).thenReturn(vXGroup); + xUserMgr.modifyGroupsVisibility(groupVisibilityMap); + Assert.assertEquals(value, vXGroup.getIsVisible()); + Assert.assertEquals(userId, vXGroup.getId()); + Mockito.verify(daoManager).getXXGroup(); + Mockito.verify(xGroupService).populateViewBean(xxGroup); + Mockito.verify(xGroupService).updateResource(vXGroup); + } + + @Test + public void test13ModifyGroupsVisibilitySetEmpty() { + setup(); + XXGroupDao xxGroupDao = Mockito.mock(XXGroupDao.class); + VXGroup vXGroup = vxGroup(); + XXGroup xxGroup = new XXGroup(); + HashMap groupVisibilityMap = new HashMap<>(); + groupVisibilityMap.put(userId, emptyValue); + Mockito.when(daoManager.getXXGroup()).thenReturn(xxGroupDao); + Mockito.when(xxGroupDao.getById(vXGroup.getId())).thenReturn(xxGroup); + Mockito.when(xGroupService.populateViewBean(xxGroup)).thenReturn(vXGroup); + Mockito.when(xGroupService.updateResource(vXGroup)).thenReturn(vXGroup); + xUserMgr.modifyGroupsVisibility(groupVisibilityMap); + Assert.assertEquals(emptyValue, vXGroup.getIsVisible()); + Assert.assertEquals(userId, vXGroup.getId()); + Mockito.verify(daoManager).getXXGroup(); + Mockito.verify(xGroupService).populateViewBean(xxGroup); + Mockito.verify(xGroupService).updateResource(vXGroup); + } + + @Test + public void test14createXGroupUser() { + setup(); + VXGroupUser vxGroupUser = vxGroupUser(); + Mockito.when(xGroupUserService.createXGroupUserWithOutLogin(vxGroupUser)).thenReturn(vxGroupUser); + VXGroupUser dbVXGroupUser = xUserMgr.createXGroupUser(vxGroupUser); + Assert.assertNotNull(dbVXGroupUser); + userId = dbVXGroupUser.getId(); + Assert.assertEquals(userId, dbVXGroupUser.getId()); + Assert.assertEquals(dbVXGroupUser.getOwner(), vxGroupUser.getOwner()); + Assert.assertEquals(dbVXGroupUser.getName(), vxGroupUser.getName()); + Assert.assertEquals(dbVXGroupUser.getUserId(), vxGroupUser.getUserId()); + Assert.assertEquals(dbVXGroupUser.getUpdatedBy(), vxGroupUser.getUpdatedBy()); + Mockito.verify(xGroupUserService).createXGroupUserWithOutLogin(vxGroupUser); + Mockito.when(xGroupUserService.readResourceWithOutLogin(userId)).thenReturn(vxGroupUser); + VXGroupUser dbvxGroupUser = xUserMgr.getXGroupUser(userId); + Assert.assertNotNull(dbvxGroupUser); + userId = dbvxGroupUser.getId(); + Assert.assertEquals(userId, dbvxGroupUser.getId()); + Assert.assertEquals(dbvxGroupUser.getOwner(), vxGroupUser.getOwner()); + Assert.assertEquals(dbvxGroupUser.getName(), vxGroupUser.getName()); + Assert.assertEquals(dbvxGroupUser.getUserId(), vxGroupUser.getUserId()); + Assert.assertEquals(dbvxGroupUser.getUpdatedBy(), vxGroupUser.getUpdatedBy()); + Mockito.verify(xGroupUserService).readResourceWithOutLogin(userId); + } + + @Test + public void test15GetXUserGroups() { + List vXGroupList = new ArrayList<>(); + final VXGroup vXGroup1 = vxGroup(); + vXGroup1.setName("users"); + vXGroup1.setDescription("users -added for unit testing"); + vXGroupList.add(vXGroup1); + SearchCriteria testSearchCriteria = createsearchCriteria(); + testSearchCriteria.addParam("xUserId", userId); + VXGroupUserList vxGroupUserList = vxGroupUserList(); + Mockito.when(xGroupUserService.searchXGroupUsers(Mockito.any())).thenReturn(vxGroupUserList); + VXGroupList dbVXGroupList = xUserMgr.getXUserGroups(userId); + Assert.assertNotNull(dbVXGroupList); + } + + @Test + public void test16GetXGroupUsers() { + SearchCriteria testSearchCriteria = createsearchCriteria(); + testSearchCriteria.addParam("xGroupId", userId); + VXGroupUserList vxGroupUserList = vxGroupUserList(); + Mockito.when(xGroupUserService.searchXGroupUsers(Mockito.any())).thenReturn(vxGroupUserList); + Mockito.when(msBizUtil.hasModuleAccess(RangerConstants.MODULE_USER_GROUPS)).thenReturn(true); + VXUserList dbVXUserList = xUserMgr.getXGroupUsers(testSearchCriteria); + Assert.assertNotNull(dbVXUserList); + Mockito.when(msBizUtil.hasModuleAccess(Mockito.anyString())).thenReturn(false); + Mockito.when(restErrorUtil.createRESTException(HttpServletResponse.SC_FORBIDDEN, "User is not having permissions on the " + RangerConstants.MODULE_USER_GROUPS + " module.", true)).thenThrow(new WebApplicationException()); + thrown.expect(WebApplicationException.class); + xUserMgr.getXGroupUsers(testSearchCriteria); + } + + @Test + public void test17GetXUserByUserName() { + setupUser(); + VXUser vxUser = vxUser(); + Mockito.when(xUserService.getXUserByUserName(vxUser.getName())).thenReturn(vxUser); + XXModuleDefDao xxModuleDefDao = Mockito.mock(XXModuleDefDao.class); + Mockito.when(daoManager.getXXModuleDef()).thenReturn(xxModuleDefDao); + VXUser dbVXUser = xUserMgr.getXUserByUserName(vxUser.getName()); + Assert.assertNotNull(dbVXUser); + userId = dbVXUser.getId(); + Assert.assertEquals(userId, dbVXUser.getId()); + Assert.assertEquals(dbVXUser.getName(), vxUser.getName()); + Assert.assertEquals(dbVXUser.getOwner(), vxUser.getOwner()); + Mockito.verify(xUserService, Mockito.atLeast(2)).getXUserByUserName(vxUser.getName()); + } + + @Test + public void test18CreateXUserWithOutLogin() { + setup(); + VXUser vxUser = vxUser(); + Mockito.when(xUserService.createXUserWithOutLogin(vxUser)).thenReturn(vxUser); + VXUser dbUser = xUserMgr.createXUserWithOutLogin(vxUser); + Assert.assertNotNull(dbUser); + userId = dbUser.getId(); + Assert.assertEquals(userId, dbUser.getId()); + Assert.assertEquals(dbUser.getDescription(), vxUser.getDescription()); + Assert.assertEquals(dbUser.getName(), vxUser.getName()); + Assert.assertEquals(dbUser.getUserRoleList(), vxUser.getUserRoleList()); + Assert.assertEquals(dbUser.getGroupNameList(), vxUser.getGroupNameList()); + Mockito.verify(xUserService).createXUserWithOutLogin(vxUser); + } + + @Test + public void test19CreateXGroupWithoutLogin() { + setup(); + VXGroup vXGroup = vxGroup(); + Mockito.when(xGroupService.createXGroupWithOutLogin(vXGroup)).thenReturn(vXGroup); + VXGroup dbVXGroup = xUserMgr.createXGroupWithoutLogin(vXGroup); + Assert.assertNotNull(dbVXGroup); + userId = dbVXGroup.getId(); + Assert.assertEquals(userId, dbVXGroup.getId()); + Assert.assertEquals(vXGroup.getDescription(), dbVXGroup.getDescription()); + Assert.assertEquals(vXGroup.getName(), dbVXGroup.getName()); + Mockito.verify(xGroupService).createXGroupWithOutLogin(vXGroup); + } + + @Test + public void test20DeleteXGroup() { + setup(); + boolean force = true; + VXGroup vXGroup = vxGroup(); + XXGroupDao xXGroupDao = Mockito.mock(XXGroupDao.class); + XXUserDao xXUserDao = Mockito.mock(XXUserDao.class); + VXUser vxUser = vxUser(); + XXUser xXUser = xxUser(vxUser); + Mockito.when(daoManager.getXXUser()).thenReturn(xXUserDao); + Mockito.when(xXUserDao.getById(xXUser.getId())).thenReturn(xXUser); + XXGroup xXGroup = new XXGroup(); + Mockito.when(daoManager.getXXGroup()).thenReturn(xXGroupDao); + Mockito.when(xXGroupDao.getById(vXGroup.getId())).thenReturn(xXGroup); + Mockito.when(xGroupService.populateViewBean(xXGroup)).thenReturn(vXGroup); + VXGroupUserList vxGroupUserList = vxGroupUserList(); + XXGroupUserDao xGroupUserDao = Mockito.mock(XXGroupUserDao.class); + Mockito.when(xGroupUserService.searchXGroupUsers(Mockito.any())).thenReturn(vxGroupUserList); + Mockito.when(daoManager.getXXGroupUser()).thenReturn(xGroupUserDao); + VXPermMapList vXPermMapList = new VXPermMapList(); + VXPermMap vXPermMap1 = getVXPermMap(); + List vXPermMaps = new ArrayList<>(); + vXPermMaps.add(vXPermMap1); + vXPermMapList.setVXPermMaps(vXPermMaps); + XXPermMapDao xXPermMapDao = Mockito.mock(XXPermMapDao.class); + Mockito.when(xPermMapService.searchXPermMaps(Mockito.any())).thenReturn(vXPermMapList); + Mockito.when(daoManager.getXXPermMap()).thenReturn(xXPermMapDao); + VXAuditMapList vXAuditMapList = new VXAuditMapList(); + List vXAuditMaps = new ArrayList<>(); + VXAuditMap vXAuditMap = getVXAuditMap(); + vXAuditMaps.add(vXAuditMap); + vXAuditMapList.setVXAuditMaps(vXAuditMaps); + XXAuditMapDao xXAuditMapDao = Mockito.mock(XXAuditMapDao.class); + Mockito.when(xAuditMapService.searchXAuditMaps(Mockito.any())).thenReturn(vXAuditMapList); + Mockito.when(daoManager.getXXAuditMap()).thenReturn(xXAuditMapDao); + XXGroupGroupDao xXGroupGroupDao = Mockito.mock(XXGroupGroupDao.class); + List xXGroupGroups = new ArrayList<>(); + XXGroupGroup xXGroupGroup = xxGroupGroup(); + xXGroupGroups.add(xXGroupGroup); + XXGroupPermissionDao xXGroupPermissionDao = Mockito.mock(XXGroupPermissionDao.class); + Mockito.when(daoManager.getXXGroupPermission()).thenReturn(xXGroupPermissionDao); + List xXGroupPermissions = new ArrayList<>(); + XXGroupPermission xGroupPermissionObj = xxGroupPermission(); + xXGroupPermissions.add(xGroupPermissionObj); + Mockito.when(xXGroupPermissionDao.findByGroupId(vXGroup.getId())).thenReturn(xXGroupPermissions); + XXPolicyDao xXPolicyDao = Mockito.mock(XXPolicyDao.class); + List xXPolicyList = new ArrayList<>(); + XXPolicy xXPolicy = getXXPolicy(); + xXPolicyList.add(xXPolicy); + Mockito.when(daoManager.getXXPolicy()).thenReturn(xXPolicyDao); + Mockito.when(xXPolicyDao.findByGroupId(userId)).thenReturn(xXPolicyList); + List xResourceList = new ArrayList<>(); + XXResource xXResource = new XXResource(); + xXResource.setId(userId); + xXResource.setName("hadoopdev"); + xXResource.setIsRecursive(AppConstants.BOOL_TRUE); + xXResource.setResourceStatus(AppConstants.STATUS_ENABLED); + xResourceList.add(xXResource); + XXResourceDao xxResourceDao = Mockito.mock(XXResourceDao.class); + Mockito.when(daoManager.getXXResource()).thenReturn(xxResourceDao); + Mockito.when(xxResourceDao.getById(Mockito.anyLong())).thenReturn(xXResource); + RangerPolicy rangerPolicy = rangerPolicy(); + Mockito.when(policyService.getPopulatedViewObject(xXPolicy)).thenReturn(rangerPolicy); + XXModuleDefDao xModuleDefDao = Mockito.mock(XXModuleDefDao.class); + Mockito.when(daoManager.getXXModuleDef()).thenReturn(xModuleDefDao); + XXModuleDef xModuleDef = xxModuleDef(); + Mockito.when(xModuleDefDao.findByModuleId(Mockito.anyLong())).thenReturn(xModuleDef); + List zoneSecRefGroup = new ArrayList<>(); + XXSecurityZoneRefGroupDao zoneSecRefGroupDao = Mockito.mock(XXSecurityZoneRefGroupDao.class); + Mockito.when(daoManager.getXXSecurityZoneRefGroup()).thenReturn(zoneSecRefGroupDao); + Mockito.when(zoneSecRefGroupDao.findByGroupId(userId)).thenReturn(zoneSecRefGroup); + List roleRefGroup = new ArrayList<>(); + XXRoleRefGroupDao roleRefGroupDao = Mockito.mock(XXRoleRefGroupDao.class); + Mockito.when(daoManager.getXXRoleRefGroup()).thenReturn(roleRefGroupDao); + Mockito.when(roleRefGroupDao.findByGroupId(userId)).thenReturn(roleRefGroup); + xUserMgr.deleteXGroup(vXGroup.getId(), force); + } + + @Test + public void test21DeleteXUser() { + setup(); + boolean force = true; + VXUser vXUser = vxUser(); + XXUser xXUser = new XXUser(); + XXUserDao xXUserDao = Mockito.mock(XXUserDao.class); + Mockito.when(daoManager.getXXUser()).thenReturn(xXUserDao); + Mockito.when(xXUserDao.getById(vXUser.getId())).thenReturn(xXUser); + Mockito.when(xUserService.populateViewBean(xXUser)).thenReturn(vXUser); + VXGroupUserList vxGroupUserList = vxGroupUserList(); + XXGroupUserDao xGroupUserDao = Mockito.mock(XXGroupUserDao.class); + Mockito.when(xGroupUserService.searchXGroupUsers(Mockito.any())).thenReturn(vxGroupUserList); + Mockito.when(daoManager.getXXGroupUser()).thenReturn(xGroupUserDao); + VXPermMapList vXPermMapList = new VXPermMapList(); + VXPermMap vXPermMap1 = getVXPermMap(); + List vXPermMaps = new ArrayList<>(); + vXPermMaps.add(vXPermMap1); + vXPermMapList.setVXPermMaps(vXPermMaps); + XXPermMapDao xXPermMapDao = Mockito.mock(XXPermMapDao.class); + Mockito.when(xPermMapService.searchXPermMaps(Mockito.any())).thenReturn(vXPermMapList); + Mockito.when(daoManager.getXXPermMap()).thenReturn(xXPermMapDao); + VXAuditMapList vXAuditMapList = new VXAuditMapList(); + List vXAuditMaps = new ArrayList<>(); + VXAuditMap vXAuditMap = getVXAuditMap(); + vXAuditMaps.add(vXAuditMap); + vXAuditMapList.setVXAuditMaps(vXAuditMaps); + XXAuditMapDao xXAuditMapDao = Mockito.mock(XXAuditMapDao.class); + Mockito.when(xAuditMapService.searchXAuditMaps(Mockito.any())).thenReturn(vXAuditMapList); + Mockito.when(daoManager.getXXAuditMap()).thenReturn(xXAuditMapDao); + VXPortalUser vXPortalUser = userProfile(); + XXPortalUser xXPortalUser = xxPortalUser(vXPortalUser); + XXPortalUserDao xXPortalUserDao = Mockito.mock(XXPortalUserDao.class); + Mockito.when(daoManager.getXXPortalUser()).thenReturn(xXPortalUserDao); + Mockito.when(xXPortalUserDao.findByLoginId(vXUser.getName().trim())).thenReturn(xXPortalUser); + Mockito.when(xPortalUserService.populateViewBean(xXPortalUser)).thenReturn(vXPortalUser); + XXPortalUserRole xxPortalUserRole = new XXPortalUserRole(); + xxPortalUserRole.setId(userId); + xxPortalUserRole.setUserId(userId); + xxPortalUserRole.setUserRole("ROLE_USER"); + XXModuleDefDao xModuleDefDao = Mockito.mock(XXModuleDefDao.class); + Mockito.when(daoManager.getXXModuleDef()).thenReturn(xModuleDefDao); + XXModuleDef xModuleDef = xxModuleDef(); + Mockito.when(xModuleDefDao.findByModuleId(Mockito.anyLong())).thenReturn(xModuleDef); + XXAuthSessionDao xXAuthSessionDao = Mockito.mock(XXAuthSessionDao.class); + XXUserPermissionDao xXUserPermissionDao = Mockito.mock(XXUserPermissionDao.class); + XXPortalUserRoleDao xXPortalUserRoleDao = Mockito.mock(XXPortalUserRoleDao.class); + Mockito.when(daoManager.getXXAuthSession()).thenReturn(xXAuthSessionDao); + Mockito.when(daoManager.getXXUserPermission()).thenReturn(xXUserPermissionDao); + Mockito.when(daoManager.getXXPortalUserRole()).thenReturn(xXPortalUserRoleDao); + List xXAuthSessions = new ArrayList<>(); + XXAuthSession xXAuthSession = new XXAuthSession(); + xXAuthSession.setId(userId); + xXAuthSession.setLoginId(vXPortalUser.getLoginId()); + xXAuthSessions.add(xXAuthSession); + List xXUserPermissions = new ArrayList<>(); + xXUserPermissions.add(xxUserPermission()); + List xXPortalUserRoles = new ArrayList<>(); + xXPortalUserRoles.add(xxPortalUserRole); + Mockito.when(xXUserPermissionDao.findByUserPermissionId(vXPortalUser.getId())).thenReturn(xXUserPermissions); + Mockito.when(xXPortalUserRoleDao.findByUserId(vXPortalUser.getId())).thenReturn(xXPortalUserRoles); + XXPolicyDao xXPolicyDao = Mockito.mock(XXPolicyDao.class); + List xXPolicyList = new ArrayList<>(); + XXPolicy xXPolicy = getXXPolicy(); + xXPolicyList.add(xXPolicy); + Mockito.when(daoManager.getXXPolicy()).thenReturn(xXPolicyDao); + Mockito.when(xXPolicyDao.findByUserId(vXUser.getId())).thenReturn(xXPolicyList); + RangerPolicy rangerPolicy = rangerPolicy(); + Mockito.when(policyService.getPopulatedViewObject(xXPolicy)).thenReturn(rangerPolicy); + List zoneSecRefUser = new ArrayList<>(); + XXSecurityZoneRefUserDao zoneSecRefUserDao = Mockito.mock(XXSecurityZoneRefUserDao.class); + Mockito.when(daoManager.getXXSecurityZoneRefUser()).thenReturn(zoneSecRefUserDao); + Mockito.when(zoneSecRefUserDao.findByUserId(userId)).thenReturn(zoneSecRefUser); + List roleRefUser = new ArrayList<>(); + XXRoleRefUserDao roleRefUserDao = Mockito.mock(XXRoleRefUserDao.class); + Mockito.when(daoManager.getXXRoleRefUser()).thenReturn(roleRefUserDao); + Mockito.when(roleRefUserDao.findByUserId(userId)).thenReturn(roleRefUser); + xUserMgr.deleteXUser(vXUser.getId(), force); + force = false; + xUserMgr.deleteXUser(vXUser.getId(), force); + } + + @Test + public void test22DeleteXGroupAndXUser() { + setup(); + VXUser vxUser = vxUser(); + VXGroup vxGroup = vxGroup(); + VXGroupUserList vxGroupUserList = new VXGroupUserList(); + List vXGroupUsers = new ArrayList<>(); + VXGroupUser vxGroupUser = vxGroupUser(); + vXGroupUsers.add(vxGroupUser); + vxGroupUserList.setVXGroupUsers(vXGroupUsers); + Mockito.when(xGroupService.getGroupByGroupName(Mockito.anyString())).thenReturn(vxGroup); + Mockito.when(xUserService.getXUserByUserName(Mockito.anyString())).thenReturn(vxUser); + Mockito.when(xGroupUserService.searchXGroupUsers(Mockito.any())).thenReturn(vxGroupUserList); + XXGroupUserDao xGrpUserDao = Mockito.mock(XXGroupUserDao.class); + Mockito.when(daoManager.getXXGroupUser()).thenReturn(xGrpUserDao); + Mockito.when(xGrpUserDao.remove(vxGroupUser.getId())).thenReturn(true); + xUserMgr.deleteXGroupAndXUser(groupName, userLoginID); + Mockito.verify(xGroupService).getGroupByGroupName(Mockito.anyString()); + Mockito.verify(xUserService).getXUserByUserName(Mockito.anyString()); + Mockito.verify(xGroupUserService).searchXGroupUsers(Mockito.any()); + } + + @Test + public void test23CreateVXUserGroupInfo() { + setup(); + VXUserGroupInfo vXUserGroupInfo = new VXUserGroupInfo(); + VXUser vXUser = vxUser(); + List vXGroupUserList = new ArrayList<>(); + List vXGroupList = new ArrayList<>(); + final VXGroup vXGroup1 = vxGroup(); + vXGroup1.setName("users"); + vXGroup1.setDescription("users -added for unit testing"); + vXGroupList.add(vXGroup1); + VXGroupUser vXGroupUser1 = vxGroupUser(); + vXGroupUser1.setName("users"); + vXGroupUserList.add(vXGroupUser1); + final VXGroup vXGroup2 = vxGroup(); + vXGroup2.setName("user1"); + vXGroup2.setDescription("user1 -added for unit testing"); + vXGroupList.add(vXGroup2); + VXGroupUser vXGroupUser2 = vxGroupUser(); + vXGroupUser2.setName("user1"); + vXGroupUserList.add(vXGroupUser2); + vXUserGroupInfo.setXuserInfo(vXUser); + vXUserGroupInfo.setXgroupInfo(vXGroupList); + Mockito.when(xUserService.createXUserWithOutLogin(vXUser)).thenReturn(vXUser); + Mockito.when(xGroupService.createXGroupWithOutLogin(vXGroup1)).thenReturn(vXGroup1); + Mockito.when(xGroupService.createXGroupWithOutLogin(vXGroup2)).thenReturn(vXGroup2); + XXPortalUserDao portalUser = Mockito.mock(XXPortalUserDao.class); + Mockito.when(daoManager.getXXPortalUser()).thenReturn(portalUser); + XXPortalUser user = new XXPortalUser(); + user.setId(1L); + user.setUserSource(RangerCommonEnums.USER_EXTERNAL); + Mockito.when(portalUser.findByLoginId(vXUser.getName())).thenReturn(user); + XXPortalUserRoleDao userDao = Mockito.mock(XXPortalUserRoleDao.class); + Mockito.when(daoManager.getXXPortalUserRole()).thenReturn(userDao); + List existingRole = new ArrayList<>(); + existingRole.add(RangerConstants.ROLE_USER); + List reqRoleList = new ArrayList<>(); + reqRoleList.add(RangerConstants.ROLE_SYS_ADMIN); + Mockito.when(userDao.findXPortalUserRolebyXPortalUserId(Mockito.anyLong())).thenReturn(reqRoleList); + VXPortalUser vXPortalUser = userProfile(); + Mockito.when(userMgr.getUserProfileByLoginId(Mockito.anyString())).thenReturn(vXPortalUser); + Mockito.when(userMgr.updateRoleForExternalUsers(Mockito.any(), Mockito.any(), Mockito.any())).thenReturn(vXPortalUser); + XXModuleDefDao xXModuleDefDao = Mockito.mock(XXModuleDefDao.class); + XXUserPermissionDao xXUserPermissionDao = Mockito.mock(XXUserPermissionDao.class); + XXUserDao xxUserDao = Mockito.mock(XXUserDao.class); + Collection userRoleList = new ArrayList<>(); + userRoleList.add("ROLE_USER"); + vXPortalUser.setUserRoleList(userRoleList); + VXUser vxUser = vxUser(); + XXUser xXUser = xxUser(vxUser); + List xXModuleDefs = xxModuleDefs(); + VXUserPermission userPermission = vxUserPermission(); + List userPermList = new ArrayList<>(); + userPermList.add(userPermission); + List xUserPermissionsList = new ArrayList<>(); + XXUserPermission xUserPermissionObj = xxUserPermission(); + xUserPermissionObj.setModuleId(userPermission.getModuleId()); + xUserPermissionObj.setUserId(userPermission.getUserId()); + xUserPermissionsList.add(xUserPermissionObj); + Mockito.when(daoManager.getXXModuleDef()).thenReturn(xXModuleDefDao); + Mockito.when(xXModuleDefDao.getAll()).thenReturn(xXModuleDefs); + Mockito.when(daoManager.getXXUserPermission()).thenReturn(xXUserPermissionDao); + Mockito.when(daoManager.getXXUser()).thenReturn(xxUserDao); + Mockito.when(xxUserDao.findByPortalUserId(vXPortalUser.getId())).thenReturn(xXUser); + UserSessionBase userSession = Mockito.mock(UserSessionBase.class); + Set userSessions = new HashSet<>(); + userSessions.add(userSession); + Mockito.when(xUserPermissionService.createResource(Mockito.any())).thenReturn(userPermission); + Mockito.when(sessionMgr.getActiveUserSessionsForPortalUserId(userId)).thenReturn(userSessions); + VXUserGroupInfo vxUserGroupTest = xUserMgr.createXUserGroupFromMap(vXUserGroupInfo); + Assert.assertEquals(userLoginID, vxUserGroupTest.getXuserInfo().getName()); + List result = vxUserGroupTest.getXgroupInfo(); + List expected = new ArrayList<>(); + expected.add(vXGroup1); + expected.add(vXGroup2); + Assert.assertTrue(result.containsAll(expected)); + Mockito.verify(portalUser).findByLoginId(vXUser.getName()); + Mockito.verify(userDao).findXPortalUserRolebyXPortalUserId(Mockito.anyLong()); + } + + @Test + public void test24createXModuleDefPermission() { + VXModuleDef vXModuleDef = vxModuleDef(); + Mockito.when(xModuleDefService.createResource(vXModuleDef)).thenReturn(vXModuleDef); + XXModuleDefDao obj = Mockito.mock(XXModuleDefDao.class); + Mockito.when(daoManager.getXXModuleDef()).thenReturn(obj); + VXModuleDef dbModuleDef = xUserMgr.createXModuleDefPermission(vXModuleDef); + Assert.assertNotNull(dbModuleDef); + Assert.assertEquals(dbModuleDef, vXModuleDef); + Assert.assertEquals(dbModuleDef.getId(), vXModuleDef.getId()); + Assert.assertEquals(dbModuleDef.getOwner(), vXModuleDef.getOwner()); + Assert.assertEquals(dbModuleDef.getUpdatedBy(), vXModuleDef.getUpdatedBy()); + Assert.assertEquals(dbModuleDef.getUrl(), vXModuleDef.getUrl()); + Assert.assertEquals(dbModuleDef.getAddedById(), vXModuleDef.getAddedById()); + Assert.assertEquals(dbModuleDef.getCreateDate(), vXModuleDef.getCreateDate()); + Assert.assertEquals(dbModuleDef.getCreateTime(), vXModuleDef.getCreateTime()); + Assert.assertEquals(dbModuleDef.getUserPermList(), vXModuleDef.getUserPermList()); + Assert.assertEquals(dbModuleDef.getGroupPermList(), vXModuleDef.getGroupPermList()); + Mockito.verify(xModuleDefService).createResource(vXModuleDef); + } + + @Test + public void test25getXModuleDefPermission() { + VXModuleDef vXModuleDef = vxModuleDef(); + Mockito.when(xModuleDefService.readResource(1L)).thenReturn(vXModuleDef); + VXModuleDef dbMuduleDef = xUserMgr.getXModuleDefPermission(1L); + Assert.assertNotNull(dbMuduleDef); + Assert.assertEquals(dbMuduleDef, vXModuleDef); + Assert.assertEquals(dbMuduleDef.getId(), vXModuleDef.getId()); + Assert.assertEquals(dbMuduleDef.getOwner(), vXModuleDef.getOwner()); + Assert.assertEquals(dbMuduleDef.getUpdatedBy(), vXModuleDef.getUpdatedBy()); + Assert.assertEquals(dbMuduleDef.getUrl(), vXModuleDef.getUrl()); + Assert.assertEquals(dbMuduleDef.getAddedById(), vXModuleDef.getAddedById()); + Assert.assertEquals(dbMuduleDef.getCreateDate(), vXModuleDef.getCreateDate()); + Assert.assertEquals(dbMuduleDef.getCreateTime(), vXModuleDef.getCreateTime()); + Assert.assertEquals(dbMuduleDef.getUserPermList(), vXModuleDef.getUserPermList()); + Assert.assertEquals(dbMuduleDef.getGroupPermList(), vXModuleDef.getGroupPermList()); + Mockito.verify(xModuleDefService).readResource(1L); + } + + @Test + public void test26updateXModuleDefPermission() { + XXModuleDefDao xModuleDefDao = Mockito.mock(XXModuleDefDao.class); + XXModuleDef xModuleDef = xxModuleDef(); + VXModuleDef vXModuleDef = vxModuleDef(); + Mockito.when(xModuleDefService.updateResource(vXModuleDef)).thenReturn(vXModuleDef); + Mockito.when(daoManager.getXXModuleDef()).thenReturn(xModuleDefDao); + Mockito.when(xModuleDefDao.getById(userId)).thenReturn(xModuleDef); + Map xXGroupNameMap = new HashMap<>(); + xXGroupNameMap.put(userId, groupName); + Mockito.when(xGroupService.getXXGroupIdNameMap()).thenReturn(xXGroupNameMap); + Object[] objArr = new Object[] {userId, userId, userLoginID}; + Map xXUserMap = new HashMap<>(); + xXUserMap.put(userId, objArr); + Mockito.when(xUserService.getXXPortalUserIdXXUserNameMap()).thenReturn(xXUserMap); + Mockito.when(xModuleDefService.populateViewBean(xModuleDef, xXUserMap, xXGroupNameMap, true)).thenReturn(vXModuleDef); + List xXGroupPermissions = new ArrayList<>(); + XXGroupPermission xGroupPermissionObj = xxGroupPermission(); + xXGroupPermissions.add(xGroupPermissionObj); + VXGroupPermission groupPermission = vxGroupPermission(); + List xXUserPermissions = new ArrayList<>(); + XXUserPermission xUserPermissionObj = xxUserPermission(); + xXUserPermissions.add(xUserPermissionObj); + VXUserPermission vxUserPermission = vxUserPermission(); + + Map groupPermMapOld = new HashMap<>(); + groupPermMapOld.put(groupPermission.getGroupId(), groupPermission); + Mockito.when(xGroupPermissionService.convertVListToVMap(Mockito.any())).thenReturn(groupPermMapOld); + + Map userPermMapOld = new HashMap<>(); + userPermMapOld.put(vxUserPermission.getUserId(), vxUserPermission); + Mockito.when(xUserPermissionService.convertVListToVMap(Mockito.any())).thenReturn(userPermMapOld); + + UserSessionBase userSession = Mockito.mock(UserSessionBase.class); + Set userSessions = new HashSet<>(); + userSessions.add(userSession); + VXModuleDef dbMuduleDef = xUserMgr.updateXModuleDefPermission(vXModuleDef); + Assert.assertEquals(dbMuduleDef, vXModuleDef); + Assert.assertNotNull(dbMuduleDef); + Assert.assertEquals(dbMuduleDef, vXModuleDef); + Assert.assertEquals(dbMuduleDef.getId(), vXModuleDef.getId()); + Assert.assertEquals(dbMuduleDef.getOwner(), vXModuleDef.getOwner()); + Assert.assertEquals(dbMuduleDef.getUpdatedBy(), vXModuleDef.getUpdatedBy()); + Assert.assertEquals(dbMuduleDef.getUrl(), vXModuleDef.getUrl()); + Assert.assertEquals(dbMuduleDef.getAddedById(), vXModuleDef.getAddedById()); + Assert.assertEquals(dbMuduleDef.getCreateDate(), vXModuleDef.getCreateDate()); + Assert.assertEquals(dbMuduleDef.getCreateTime(), vXModuleDef.getCreateTime()); + Assert.assertEquals(dbMuduleDef.getUserPermList(), vXModuleDef.getUserPermList()); + Assert.assertEquals(dbMuduleDef.getGroupPermList(), vXModuleDef.getGroupPermList()); + Mockito.verify(xModuleDefService).updateResource(vXModuleDef); + Mockito.verify(daoManager).getXXModuleDef(); + Mockito.verify(xModuleDefService).populateViewBean(xModuleDef, xXUserMap, xXGroupNameMap, true); + vXModuleDef.setModule("UnknownModule"); + Mockito.when(xModuleDefDao.getById(userId)).thenReturn(xModuleDef); + Mockito.when(restErrorUtil.createRESTException("Module name change is not allowed!", MessageEnums.DATA_NOT_UPDATABLE)).thenThrow(new WebApplicationException()); + thrown.expect(WebApplicationException.class); + xUserMgr.updateXModuleDefPermission(vXModuleDef); + } + + @Test + public void test27deleteXModuleDefPermission() { + Long moduleId = Long.valueOf(1); + XXUserPermissionDao xUserPermissionDao = Mockito.mock(XXUserPermissionDao.class); + XXGroupPermissionDao xGroupPermissionDao = Mockito.mock(XXGroupPermissionDao.class); + Mockito.when(daoManager.getXXUserPermission()).thenReturn(xUserPermissionDao); + Mockito.when(daoManager.getXXGroupPermission()).thenReturn(xGroupPermissionDao); + Mockito.doNothing().when(xUserPermissionDao).deleteByModuleId(moduleId); + Mockito.doNothing().when(xGroupPermissionDao).deleteByModuleId(moduleId); + Mockito.when(xModuleDefService.deleteResource(1L)).thenReturn(true); + xUserMgr.deleteXModuleDefPermission(1L, true); + Mockito.verify(xModuleDefService).deleteResource(1L); + } + + @Test + public void test28createXUserPermission() { + VXUserPermission vXUserPermission = vxUserPermission(); + Mockito.when(xUserPermissionService.createResource(vXUserPermission)).thenReturn(vXUserPermission); + VXUserPermission dbUserPermission = xUserMgr.createXUserPermission(vXUserPermission); + Assert.assertNotNull(dbUserPermission); + Assert.assertEquals(dbUserPermission, vXUserPermission); + Assert.assertEquals(dbUserPermission.getId(), vXUserPermission.getId()); + Assert.assertEquals(dbUserPermission.getOwner(), vXUserPermission.getOwner()); + Assert.assertEquals(dbUserPermission.getUpdatedBy(), vXUserPermission.getUpdatedBy()); + Assert.assertEquals(dbUserPermission.getUserName(), vXUserPermission.getUserName()); + Assert.assertEquals(dbUserPermission.getCreateDate(), vXUserPermission.getCreateDate()); + Assert.assertEquals(dbUserPermission.getIsAllowed(), vXUserPermission.getIsAllowed()); + Assert.assertEquals(dbUserPermission.getModuleId(), vXUserPermission.getModuleId()); + Assert.assertEquals(dbUserPermission.getUpdateDate(), vXUserPermission.getUpdateDate()); + Assert.assertEquals(dbUserPermission.getUserId(), vXUserPermission.getUserId()); + Mockito.verify(xUserPermissionService).createResource(vXUserPermission); + } + + @Test + public void test29getXUserPermission() { + VXUserPermission vXUserPermission = vxUserPermission(); + Mockito.when(xUserPermissionService.readResource(1L)).thenReturn(vXUserPermission); + VXUserPermission dbUserPermission = xUserMgr.getXUserPermission(1L); + Assert.assertNotNull(dbUserPermission); + Assert.assertEquals(dbUserPermission, vXUserPermission); + Assert.assertEquals(dbUserPermission.getId(), vXUserPermission.getId()); + Assert.assertEquals(dbUserPermission.getOwner(), vXUserPermission.getOwner()); + Assert.assertEquals(dbUserPermission.getUpdatedBy(), vXUserPermission.getUpdatedBy()); + Assert.assertEquals(dbUserPermission.getUserName(), vXUserPermission.getUserName()); + Assert.assertEquals(dbUserPermission.getCreateDate(), vXUserPermission.getCreateDate()); + Assert.assertEquals(dbUserPermission.getIsAllowed(), vXUserPermission.getIsAllowed()); + Assert.assertEquals(dbUserPermission.getModuleId(), vXUserPermission.getModuleId()); + Assert.assertEquals(dbUserPermission.getUpdateDate(), vXUserPermission.getUpdateDate()); + Assert.assertEquals(dbUserPermission.getUserId(), vXUserPermission.getUserId()); + Mockito.verify(xUserPermissionService).readResource(1L); + } + + @Test + public void test30updateXUserPermission() { + VXUserPermission vXUserPermission = vxUserPermission(); + Mockito.when(xUserPermissionService.updateResource(vXUserPermission)).thenReturn(vXUserPermission); + VXUserPermission dbUserPermission = xUserMgr.updateXUserPermission(vXUserPermission); + Assert.assertNotNull(dbUserPermission); + Assert.assertEquals(dbUserPermission, vXUserPermission); + Assert.assertEquals(dbUserPermission.getId(), vXUserPermission.getId()); + Assert.assertEquals(dbUserPermission.getOwner(), vXUserPermission.getOwner()); + Assert.assertEquals(dbUserPermission.getUpdatedBy(), vXUserPermission.getUpdatedBy()); + Assert.assertEquals(dbUserPermission.getUserName(), vXUserPermission.getUserName()); + Assert.assertEquals(dbUserPermission.getCreateDate(), vXUserPermission.getCreateDate()); + Assert.assertEquals(dbUserPermission.getIsAllowed(), vXUserPermission.getIsAllowed()); + Assert.assertEquals(dbUserPermission.getModuleId(), vXUserPermission.getModuleId()); + Assert.assertEquals(dbUserPermission.getUpdateDate(), vXUserPermission.getUpdateDate()); + Assert.assertEquals(dbUserPermission.getUserId(), vXUserPermission.getUserId()); + Mockito.verify(xUserPermissionService).updateResource(vXUserPermission); + } + + @Test + public void test31deleteXUserPermission() { + UserSessionBase userSession = Mockito.mock(UserSessionBase.class); + Set userSessions = new HashSet<>(); + userSessions.add(userSession); + XXUserPermission xUserPermissionObj = xxUserPermission(); + XXUserPermissionDao xUserPermDao = Mockito.mock(XXUserPermissionDao.class); + Mockito.when(daoManager.getXXUserPermission()).thenReturn(xUserPermDao); + Mockito.when(xUserPermDao.getById(1L)).thenReturn(xUserPermissionObj); + Mockito.when(xUserPermissionService.deleteResource(1L)).thenReturn(true); + Mockito.when(sessionMgr.getActiveUserSessionsForPortalUserId(xUserPermissionObj.getUserId())).thenReturn(userSessions); + xUserMgr.deleteXUserPermission(1L, true); + Mockito.verify(xUserPermissionService).deleteResource(1L); + } + + @Test + public void test32createXGroupPermission() { + VXGroupPermission vXGroupPermission = vxGroupPermission(); + XXGroupUserDao xGrpUserDao = Mockito.mock(XXGroupUserDao.class); + Mockito.when(daoManager.getXXGroupUser()).thenReturn(xGrpUserDao); + Mockito.when(xGroupPermissionService.createResource(vXGroupPermission)).thenReturn(vXGroupPermission); + List xXGroupUserList = new ArrayList<>(); + VXGroupUser vxGroupUser = vxGroupUser(); + XXGroupUser xXGroupUser = new XXGroupUser(); + xXGroupUser.setId(vxGroupUser.getId()); + xXGroupUser.setName(vxGroupUser.getName()); + xXGroupUser.setParentGroupId(vxGroupUser.getParentGroupId()); + xXGroupUser.setUserId(vxGroupUser.getUserId()); + xXGroupUserList.add(xXGroupUser); + Mockito.when(xGrpUserDao.findByGroupId(vXGroupPermission.getGroupId())).thenReturn(xXGroupUserList); + UserSessionBase userSession = Mockito.mock(UserSessionBase.class); + Set userSessions = new HashSet<>(); + userSessions.add(userSession); + Mockito.when(sessionMgr.getActiveUserSessionsForXUserId(xXGroupUser.getUserId())).thenReturn(userSessions); + VXGroupPermission dbGroupPermission = xUserMgr.createXGroupPermission(vXGroupPermission); + Assert.assertNotNull(dbGroupPermission); + Assert.assertEquals(dbGroupPermission, vXGroupPermission); + Assert.assertEquals(dbGroupPermission.getId(), vXGroupPermission.getId()); + Assert.assertEquals(dbGroupPermission.getGroupName(), vXGroupPermission.getGroupName()); + Assert.assertEquals(dbGroupPermission.getOwner(), vXGroupPermission.getOwner()); + Assert.assertEquals(dbGroupPermission.getUpdatedBy(), vXGroupPermission.getUpdatedBy()); + Assert.assertEquals(dbGroupPermission.getCreateDate(), vXGroupPermission.getCreateDate()); + Assert.assertEquals(dbGroupPermission.getGroupId(), vXGroupPermission.getGroupId()); + Assert.assertEquals(dbGroupPermission.getIsAllowed(), vXGroupPermission.getIsAllowed()); + Assert.assertEquals(dbGroupPermission.getModuleId(), vXGroupPermission.getModuleId()); + Assert.assertEquals(dbGroupPermission.getUpdateDate(), vXGroupPermission.getUpdateDate()); + Mockito.verify(xGroupPermissionService).createResource(vXGroupPermission); + } + + @Test + public void test33getXGroupPermission() { + VXGroupPermission vXGroupPermission = vxGroupPermission(); + Mockito.when(xGroupPermissionService.readResource(1L)).thenReturn(vXGroupPermission); + VXGroupPermission dbGroupPermission = xUserMgr.getXGroupPermission(1L); + Assert.assertNotNull(dbGroupPermission); + Assert.assertEquals(dbGroupPermission, vXGroupPermission); + Assert.assertEquals(dbGroupPermission.getId(), vXGroupPermission.getId()); + Assert.assertEquals(dbGroupPermission.getGroupName(), vXGroupPermission.getGroupName()); + Assert.assertEquals(dbGroupPermission.getOwner(), vXGroupPermission.getOwner()); + Assert.assertEquals(dbGroupPermission.getUpdatedBy(), vXGroupPermission.getUpdatedBy()); + Assert.assertEquals(dbGroupPermission.getCreateDate(), vXGroupPermission.getCreateDate()); + Assert.assertEquals(dbGroupPermission.getGroupId(), vXGroupPermission.getGroupId()); + Assert.assertEquals(dbGroupPermission.getIsAllowed(), vXGroupPermission.getIsAllowed()); + Assert.assertEquals(dbGroupPermission.getModuleId(), vXGroupPermission.getModuleId()); + Assert.assertEquals(dbGroupPermission.getUpdateDate(), vXGroupPermission.getUpdateDate()); + Mockito.verify(xGroupPermissionService).readResource(1L); + } + + @Test + public void test34updateXGroupPermission() { + setup(); + VXGroupPermission vXGroupPermission = vxGroupPermission(); + XXGroupUserDao xGrpUserDao = Mockito.mock(XXGroupUserDao.class); + Mockito.when(daoManager.getXXGroupUser()).thenReturn(xGrpUserDao); + Mockito.when(xGroupPermissionService.updateResource(vXGroupPermission)).thenReturn(vXGroupPermission); + UserSessionBase userSession = Mockito.mock(UserSessionBase.class); + Set userSessions = new HashSet<>(); + userSessions.add(userSession); + Mockito.when(sessionMgr.getActiveUserSessionsForXUserId(userId)).thenReturn(userSessions); + List xXGroupUserList = new ArrayList<>(); + VXGroupUser vxGroupUser = vxGroupUser(); + XXGroupUser xXGroupUser = new XXGroupUser(); + xXGroupUser.setId(vxGroupUser.getId()); + xXGroupUser.setName(vxGroupUser.getName()); + xXGroupUser.setParentGroupId(vxGroupUser.getParentGroupId()); + xXGroupUser.setUserId(vxGroupUser.getUserId()); + xXGroupUserList.add(xXGroupUser); + Mockito.when(xGrpUserDao.findByGroupId(vXGroupPermission.getGroupId())).thenReturn(xXGroupUserList); + VXGroupPermission dbGroupPermission = xUserMgr.updateXGroupPermission(vXGroupPermission); + Assert.assertNotNull(dbGroupPermission); + Assert.assertEquals(dbGroupPermission, vXGroupPermission); + Assert.assertEquals(dbGroupPermission.getId(), vXGroupPermission.getId()); + Assert.assertEquals(dbGroupPermission.getGroupName(), vXGroupPermission.getGroupName()); + Assert.assertEquals(dbGroupPermission.getOwner(), vXGroupPermission.getOwner()); + Assert.assertEquals(dbGroupPermission.getUpdatedBy(), vXGroupPermission.getUpdatedBy()); + Assert.assertEquals(dbGroupPermission.getCreateDate(), vXGroupPermission.getCreateDate()); + Assert.assertEquals(dbGroupPermission.getGroupId(), vXGroupPermission.getGroupId()); + Assert.assertEquals(dbGroupPermission.getIsAllowed(), vXGroupPermission.getIsAllowed()); + Assert.assertEquals(dbGroupPermission.getModuleId(), vXGroupPermission.getModuleId()); + Assert.assertEquals(dbGroupPermission.getUpdateDate(), vXGroupPermission.getUpdateDate()); + Mockito.verify(xGroupPermissionService).updateResource(vXGroupPermission); + } + + @Test + public void test35deleteXGroupPermission() { + XXGroupPermissionDao xGrpPermDao = Mockito.mock(XXGroupPermissionDao.class); + XXGroupPermission xGroupPermissionObj = xxGroupPermission(); + Mockito.when(daoManager.getXXGroupPermission()).thenReturn(xGrpPermDao); + Mockito.when(xGrpPermDao.getById(1L)).thenReturn(xGroupPermissionObj); + XXGroupUserDao xGrpUserDao = Mockito.mock(XXGroupUserDao.class); + Mockito.when(daoManager.getXXGroupUser()).thenReturn(xGrpUserDao); + List xXGroupUserList = new ArrayList<>(); + VXGroupUser vxGroupUser = vxGroupUser(); + XXGroupUser xXGroupUser = new XXGroupUser(); + xXGroupUser.setId(vxGroupUser.getId()); + xXGroupUser.setName(vxGroupUser.getName()); + xXGroupUser.setParentGroupId(vxGroupUser.getParentGroupId()); + xXGroupUser.setUserId(vxGroupUser.getUserId()); + xXGroupUserList.add(xXGroupUser); + Mockito.when(xGrpUserDao.findByGroupId(xGroupPermissionObj.getGroupId())).thenReturn(xXGroupUserList); + UserSessionBase userSession = Mockito.mock(UserSessionBase.class); + Set userSessions = new HashSet<>(); + userSessions.add(userSession); + Mockito.when(sessionMgr.getActiveUserSessionsForXUserId(userId)).thenReturn(userSessions); + Mockito.when(xGroupPermissionService.deleteResource(1L)).thenReturn(true); + xUserMgr.deleteXGroupPermission(1L, true); + Mockito.verify(xGroupPermissionService).deleteResource(1L); + } + + @Test + public void test36getGroupsForUser() { + setupUser(); + VXUser vxUser = vxUser(); + VXGroup vxGroup = vxGroup(); + String userName = userLoginID; + Mockito.when(xUserService.getXUserByUserName(userName)).thenReturn(vxUser); + VXGroupUserList vxGroupUserList = vxGroupUserList(); + Mockito.when(xGroupUserService.searchXGroupUsers(Mockito.any())).thenReturn(vxGroupUserList); + Mockito.when(xGroupService.readResource(userId)).thenReturn(vxGroup); + XXModuleDefDao modDef = Mockito.mock(XXModuleDefDao.class); + Mockito.when(daoManager.getXXModuleDef()).thenReturn(modDef); + List lstModule = new ArrayList<>(); + lstModule.add(RangerConstants.MODULE_USER_GROUPS); + lstModule.add(RangerConstants.MODULE_RESOURCE_BASED_POLICIES); + Mockito.when(modDef.findAccessibleModulesByUserId(Mockito.anyLong(), Mockito.anyLong())).thenReturn(lstModule); + Set list = xUserMgr.getGroupsForUser(userName); + Assert.assertNotNull(list); + Mockito.verify(xUserService, Mockito.atLeast(2)).getXUserByUserName(userName); + Mockito.verify(modDef).findAccessibleModulesByUserId(Mockito.anyLong(), Mockito.anyLong()); + Mockito.when(xUserService.getXUserByUserName(userName)).thenReturn(null); + list = xUserMgr.getGroupsForUser(userName); + Assert.assertTrue(list.isEmpty()); + Mockito.verify(xUserService, Mockito.atLeast(2)).getXUserByUserName(userName); + Mockito.verify(modDef).findAccessibleModulesByUserId(Mockito.anyLong(), Mockito.anyLong()); + Mockito.when(xUserService.getXUserByUserName(userName)).thenReturn(null); + list = xUserMgr.getGroupsForUser(userName); + Assert.assertTrue(list.isEmpty()); + Mockito.verify(xUserService, Mockito.atLeast(2)).getXUserByUserName(userName); + Mockito.verify(modDef).findAccessibleModulesByUserId(Mockito.anyLong(), Mockito.anyLong()); + } + + @Test + public void test37setUserRolesByExternalID() { + setup(); + VXUser vXUser = vxUser(); + List vStringRolesList = new ArrayList<>(); + VXString vXStringObj = new VXString(); + vXStringObj.setValue("ROLE_USER"); + vStringRolesList.add(vXStringObj); + List xPortalUserRoleList = new ArrayList<>(); + XXPortalUserRole xxPortalUserRole = new XXPortalUserRole(); + xxPortalUserRole.setId(userId); + xxPortalUserRole.setUserId(userId); + xxPortalUserRole.setUserRole("ROLE_USER"); + xPortalUserRoleList.add(xxPortalUserRole); + List xUserPermissionsList = new ArrayList<>(); + XXUserPermission xUserPermissionObj = xxUserPermission(); + xUserPermissionsList.add(xUserPermissionObj); + List xGroupPermissionList = new ArrayList<>(); + XXGroupPermission xGroupPermissionObj = xxGroupPermission(); + xGroupPermissionList.add(xGroupPermissionObj); + List groupPermList = new ArrayList<>(); + VXGroupPermission groupPermission = vxGroupPermission(); + groupPermList.add(groupPermission); + Mockito.when(xUserMgr.getXUser(userId)).thenReturn(vXUser); + + List permissionList = new ArrayList<>(); + permissionList.add(RangerConstants.MODULE_USER_GROUPS); + + VXUser loggedInUser = vxUser(); + List loggedInUserRole = new ArrayList<>(); + loggedInUserRole.add(RangerConstants.ROLE_ADMIN); + loggedInUser.setId(8L); + loggedInUser.setName("testuser"); + loggedInUser.setUserRoleList(loggedInUserRole); + Mockito.when(xUserService.getXUserByUserName("admin")).thenReturn(loggedInUser); + + Mockito.when(restErrorUtil.createRESTException(HttpServletResponse.SC_FORBIDDEN, "Logged-In user is not allowed to access requested user data", true)).thenThrow(new WebApplicationException()); + thrown.expect(WebApplicationException.class); + VXStringList vXStringList = xUserMgr.setUserRolesByExternalID(userId, vStringRolesList); + Assert.assertNotNull(vXStringList); + } + + @Test + public void test38setUserRolesByExternalID() { + destroySession(); + setup(); + VXUser vXUser = vxUser(); + List vStringRolesList = new ArrayList<>(); + VXString vXStringObj = new VXString(); + vXStringObj.setValue("ROLE_USER"); + vStringRolesList.add(vXStringObj); + List xPortalUserRoleList = new ArrayList<>(); + XXPortalUserRole xxPortalUserRole = new XXPortalUserRole(); + xxPortalUserRole.setId(userId); + xxPortalUserRole.setUserId(userId); + xxPortalUserRole.setUserRole("ROLE_USER"); + xPortalUserRoleList.add(xxPortalUserRole); + List xUserPermissionsList = new ArrayList<>(); + XXUserPermission xUserPermissionObj = xxUserPermission(); + xUserPermissionsList.add(xUserPermissionObj); + List xGroupPermissionList = new ArrayList<>(); + XXGroupPermission xGroupPermissionObj = xxGroupPermission(); + xGroupPermissionList.add(xGroupPermissionObj); + List groupPermList = new ArrayList<>(); + VXGroupPermission groupPermission = vxGroupPermission(); + groupPermList.add(groupPermission); + Mockito.when(xUserMgr.getXUser(userId)).thenReturn(vXUser); + + List permissionList = new ArrayList<>(); + permissionList.add(RangerConstants.MODULE_USER_GROUPS); + + VXUser loggedInUser = vxUser(); + List loggedInUserRole = new ArrayList<>(); + loggedInUserRole.add(RangerConstants.ROLE_ADMIN); + loggedInUser.setId(8L); + loggedInUser.setName("testuser"); + loggedInUser.setUserRoleList(loggedInUserRole); + Mockito.when(xUserService.getXUserByUserName("admin")).thenReturn(loggedInUser); + + Mockito.when(restErrorUtil.createRESTException(HttpServletResponse.SC_FORBIDDEN, "Logged-In user is not allowed to access requested user data", true)).thenThrow(new WebApplicationException()); + thrown.expect(WebApplicationException.class); + xUserMgr.setUserRolesByExternalID(userId, vStringRolesList); + } + + @Test + public void test39setUserRolesByExternalID() { + destroySession(); + setup(); + VXUser vXUser = vxUser(); + List vStringRolesList = new ArrayList<>(); + VXString vXStringObj = new VXString(); + vXStringObj.setValue("ROLE_USER"); + vStringRolesList.add(vXStringObj); + List xPortalUserRoleList = new ArrayList<>(); + XXPortalUserRole xxPortalUserRole = new XXPortalUserRole(); + xxPortalUserRole.setId(userId); + xxPortalUserRole.setUserId(userId); + xxPortalUserRole.setUserRole("ROLE_USER"); + xPortalUserRoleList.add(xxPortalUserRole); + List xUserPermissionsList = new ArrayList<>(); + XXUserPermission xUserPermissionObj = xxUserPermission(); + xUserPermissionsList.add(xUserPermissionObj); + List xGroupPermissionList = new ArrayList<>(); + XXGroupPermission xGroupPermissionObj = xxGroupPermission(); + xGroupPermissionList.add(xGroupPermissionObj); + List groupPermList = new ArrayList<>(); + VXGroupPermission groupPermission = vxGroupPermission(); + groupPermList.add(groupPermission); + Mockito.when(xUserMgr.getXUser(userId)).thenReturn(vXUser); + Mockito.when(xUserMgr.getXUser(0L)).thenReturn(null); + Mockito.when(restErrorUtil.createRESTException("User ID doesn't exist.", MessageEnums.INVALID_INPUT_DATA)).thenThrow(new WebApplicationException()); + thrown.expect(WebApplicationException.class); + xUserMgr.setUserRolesByExternalID(0L, vStringRolesList); + } + + @Test + public void test40setUserRolesByName() { + destroySession(); + setup(); + VXPortalUser userProfile = userProfile(); + List vStringRolesList = new ArrayList<>(); + VXString vXStringObj = new VXString(); + vXStringObj.setValue("ROLE_USER"); + vStringRolesList.add(vXStringObj); + List xPortalUserRoleList = new ArrayList<>(); + XXPortalUserRole xxPortalUserRole = new XXPortalUserRole(); + xxPortalUserRole.setId(userId); + xxPortalUserRole.setUserId(userId); + xxPortalUserRole.setUserRole("ROLE_USER"); + xPortalUserRoleList.add(xxPortalUserRole); + List xUserPermissionsList = new ArrayList<>(); + XXUserPermission xUserPermissionObj = xxUserPermission(); + xUserPermissionsList.add(xUserPermissionObj); + List xGroupPermissionList = new ArrayList<>(); + XXGroupPermission xGroupPermissionObj = xxGroupPermission(); + xGroupPermissionList.add(xGroupPermissionObj); + List groupPermList = new ArrayList<>(); + VXGroupPermission groupPermission = vxGroupPermission(); + groupPermList.add(groupPermission); + Mockito.when(restErrorUtil.createRESTException("Login ID doesn't exist.", MessageEnums.INVALID_INPUT_DATA)).thenThrow(new WebApplicationException()); + thrown.expect(WebApplicationException.class); + VXStringList vXStringList = xUserMgr.setUserRolesByName(userProfile.getLoginId(), vStringRolesList); + Assert.assertNotNull(vXStringList); + xUserMgr.setUserRolesByName(null, vStringRolesList); + } + + @Test + public void test41setUserRolesByName() { + destroySession(); + setup(); + VXPortalUser userProfile = userProfile(); + List vStringRolesList = new ArrayList<>(); + VXString vXStringObj = new VXString(); + vXStringObj.setValue("ROLE_USER"); + vStringRolesList.add(vXStringObj); + List xPortalUserRoleList = new ArrayList<>(); + XXPortalUserRole xxPortalUserRole = new XXPortalUserRole(); + xxPortalUserRole.setId(userId); + xxPortalUserRole.setUserId(userId); + xxPortalUserRole.setUserRole("ROLE_USER"); + xPortalUserRoleList.add(xxPortalUserRole); + List xUserPermissionsList = new ArrayList<>(); + XXUserPermission xUserPermissionObj = xxUserPermission(); + xUserPermissionsList.add(xUserPermissionObj); + List xGroupPermissionList = new ArrayList<>(); + XXGroupPermission xGroupPermissionObj = xxGroupPermission(); + xGroupPermissionList.add(xGroupPermissionObj); + List groupPermList = new ArrayList<>(); + VXGroupPermission groupPermission = vxGroupPermission(); + groupPermList.add(groupPermission); + Mockito.when(restErrorUtil.createRESTException("Login ID doesn't exist.", MessageEnums.INVALID_INPUT_DATA)).thenThrow(new WebApplicationException()); + thrown.expect(WebApplicationException.class); + VXStringList vXStringList = xUserMgr.setUserRolesByName(userProfile.getLoginId(), vStringRolesList); + Assert.assertNotNull(vXStringList); + xUserMgr.setUserRolesByName(null, vStringRolesList); + } + + @Test + public void test42getUserRolesByExternalID() { + destroySession(); + setup(); + VXUser vXUser = vxUser(); + List vStringRolesList = new ArrayList<>(); + VXString vXStringObj = new VXString(); + vXStringObj.setValue("ROLE_USER"); + vStringRolesList.add(vXStringObj); + List xPortalUserRoleList = new ArrayList<>(); + XXPortalUserRole xxPortalUserRole = new XXPortalUserRole(); + xxPortalUserRole.setId(userId); + xxPortalUserRole.setUserId(userId); + xxPortalUserRole.setUserRole("ROLE_USER"); + xPortalUserRoleList.add(xxPortalUserRole); + List xUserPermissionsList = new ArrayList<>(); + XXUserPermission xUserPermissionObj = xxUserPermission(); + xUserPermissionsList.add(xUserPermissionObj); + List xGroupPermissionList = new ArrayList<>(); + XXGroupPermission xGroupPermissionObj = xxGroupPermission(); + xGroupPermissionList.add(xGroupPermissionObj); + List groupPermList = new ArrayList<>(); + VXGroupPermission groupPermission = vxGroupPermission(); + groupPermList.add(groupPermission); + Mockito.when(xUserMgr.getXUser(userId)).thenReturn(vXUser); + + List permissionList = new ArrayList<>(); + permissionList.add(RangerConstants.MODULE_USER_GROUPS); + + VXUser loggedInUser = vxUser(); + List loggedInUserRole = new ArrayList<>(); + loggedInUserRole.add(RangerConstants.ROLE_ADMIN); + loggedInUser.setId(8L); + loggedInUser.setName("testuser"); + loggedInUser.setUserRoleList(loggedInUserRole); + Mockito.when(xUserService.getXUserByUserName("admin")).thenReturn(loggedInUser); + Mockito.when(restErrorUtil.createRESTException(HttpServletResponse.SC_FORBIDDEN, "Logged-In user is not allowed to access requested user data", true)).thenThrow(new WebApplicationException()); + thrown.expect(WebApplicationException.class); + VXStringList vXStringList = xUserMgr.getUserRolesByExternalID(userId); + Assert.assertNotNull(vXStringList); + Mockito.when(restErrorUtil.createRESTException("Please provide a valid ID", MessageEnums.INVALID_INPUT_DATA)).thenThrow(new WebApplicationException()); + thrown.expect(WebApplicationException.class); + Mockito.when(xUserService.readResourceWithOutLogin(Mockito.any())).thenReturn(null); + xUserMgr.getUserRolesByExternalID(userId); + } + + @Test + public void test43getUserRolesByExternalID() { + destroySession(); + setup(); + VXUser vXUser = vxUser(); + List vStringRolesList = new ArrayList<>(); + VXString vXStringObj = new VXString(); + vXStringObj.setValue("ROLE_USER"); + vStringRolesList.add(vXStringObj); + List xPortalUserRoleList = new ArrayList<>(); + XXPortalUserRole xxPortalUserRole = new XXPortalUserRole(); + xxPortalUserRole.setId(userId); + xxPortalUserRole.setUserId(userId); + xxPortalUserRole.setUserRole("ROLE_USER"); + xPortalUserRoleList.add(xxPortalUserRole); + List xUserPermissionsList = new ArrayList<>(); + XXUserPermission xUserPermissionObj = xxUserPermission(); + xUserPermissionsList.add(xUserPermissionObj); + List xGroupPermissionList = new ArrayList<>(); + XXGroupPermission xGroupPermissionObj = xxGroupPermission(); + xGroupPermissionList.add(xGroupPermissionObj); + List groupPermList = new ArrayList<>(); + VXGroupPermission groupPermission = vxGroupPermission(); + groupPermList.add(groupPermission); + Mockito.when(xUserMgr.getXUser(userId)).thenReturn(vXUser); + + List permissionList = new ArrayList<>(); + permissionList.add(RangerConstants.MODULE_USER_GROUPS); + + VXUser loggedInUser = vxUser(); + List loggedInUserRole = new ArrayList<>(); + loggedInUserRole.add(RangerConstants.ROLE_ADMIN); + loggedInUser.setId(8L); + loggedInUser.setName("testuser"); + loggedInUser.setUserRoleList(loggedInUserRole); + Mockito.when(xUserService.getXUserByUserName("admin")).thenReturn(loggedInUser); + Mockito.when(restErrorUtil.createRESTException(HttpServletResponse.SC_FORBIDDEN, "Logged-In user is not allowed to access requested user data", true)).thenThrow(new WebApplicationException()); + thrown.expect(WebApplicationException.class); + VXStringList vXStringList = xUserMgr.getUserRolesByExternalID(userId); + Assert.assertNotNull(vXStringList); + Mockito.when(restErrorUtil.createRESTException("User ID doesn't exist.", MessageEnums.INVALID_INPUT_DATA)).thenThrow(new WebApplicationException()); + thrown.expect(WebApplicationException.class); + Mockito.when(userMgr.getUserProfileByLoginId(Mockito.anyString())).thenReturn(null); + xUserMgr.getUserRolesByExternalID(userId); + } + + @Test + public void test44getUserRolesByName() { + destroySession(); + setup(); + XXPortalUserRoleDao xPortalUserRoleDao = Mockito.mock(XXPortalUserRoleDao.class); + VXPortalUser userProfile = userProfile(); + Collection userRoleList = new ArrayList<>(); + userRoleList.add("ROLE_USER"); + userProfile.setUserRoleList(userRoleList); + List vStringRolesList = new ArrayList<>(); + VXString vXStringObj = new VXString(); + vXStringObj.setValue("ROLE_USER"); + vStringRolesList.add(vXStringObj); + List xPortalUserRoleList = new ArrayList<>(); + XXPortalUserRole xxPortalUserRole = new XXPortalUserRole(); + xxPortalUserRole.setId(userId); + xxPortalUserRole.setUserId(userId); + xxPortalUserRole.setUserRole("ROLE_USER"); + xPortalUserRoleList.add(xxPortalUserRole); + List xUserPermissionsList = new ArrayList<>(); + XXUserPermission xUserPermissionObj = xxUserPermission(); + xUserPermissionsList.add(xUserPermissionObj); + List xGroupPermissionList = new ArrayList<>(); + XXGroupPermission xGroupPermissionObj = xxGroupPermission(); + xGroupPermissionList.add(xGroupPermissionObj); + List groupPermList = new ArrayList<>(); + VXGroupPermission groupPermission = vxGroupPermission(); + groupPermList.add(groupPermission); + Mockito.when(daoManager.getXXPortalUserRole()).thenReturn(xPortalUserRoleDao); + Mockito.when(xPortalUserRoleDao.findByUserId(userId)).thenReturn(xPortalUserRoleList); + Mockito.when(userMgr.getUserProfileByLoginId(userProfile.getLoginId())).thenReturn(userProfile); + VXUser loggedInUser = vxUser(); + List loggedInUserRole = new ArrayList<>(); + loggedInUserRole.add(RangerConstants.ROLE_SYS_ADMIN); + loggedInUser.setId(8L); + loggedInUser.setName("admin"); + loggedInUser.setUserRoleList(loggedInUserRole); + Mockito.when(xUserService.getXUserByUserName("admin")).thenReturn(loggedInUser); + VXUser testuser = vxUser(); + Mockito.when(xUserService.getXUserByUserName("testuser")).thenReturn(testuser); + VXStringList vXStringList = xUserMgr.getUserRolesByName(userProfile.getLoginId()); + Assert.assertNotNull(vXStringList); + Mockito.when(restErrorUtil.createRESTException("Please provide a valid userName", MessageEnums.INVALID_INPUT_DATA)).thenThrow(new WebApplicationException()); + thrown.expect(WebApplicationException.class); + Mockito.when(userMgr.getUserProfileByLoginId(Mockito.anyString())).thenReturn(null); + xUserMgr.getUserRolesByName(userProfile.getLoginId()); + } + + @Test + public void test45getUserRolesByName() { + destroySession(); + setup(); + XXPortalUserRoleDao xPortalUserRoleDao = Mockito.mock(XXPortalUserRoleDao.class); + VXPortalUser userProfile = userProfile(); + Collection userRoleList = new ArrayList<>(); + userRoleList.add("ROLE_USER"); + userProfile.setUserRoleList(userRoleList); + List vStringRolesList = new ArrayList<>(); + VXString vXStringObj = new VXString(); + vXStringObj.setValue("ROLE_USER"); + vStringRolesList.add(vXStringObj); + List xPortalUserRoleList = new ArrayList<>(); + XXPortalUserRole xxPortalUserRole = new XXPortalUserRole(); + xxPortalUserRole.setId(userId); + xxPortalUserRole.setUserId(userId); + xxPortalUserRole.setUserRole("ROLE_USER"); + xPortalUserRoleList.add(xxPortalUserRole); + List xUserPermissionsList = new ArrayList<>(); + XXUserPermission xUserPermissionObj = xxUserPermission(); + xUserPermissionsList.add(xUserPermissionObj); + List xGroupPermissionList = new ArrayList<>(); + XXGroupPermission xGroupPermissionObj = xxGroupPermission(); + xGroupPermissionList.add(xGroupPermissionObj); + List groupPermList = new ArrayList<>(); + VXGroupPermission groupPermission = vxGroupPermission(); + groupPermList.add(groupPermission); + Mockito.when(daoManager.getXXPortalUserRole()).thenReturn(xPortalUserRoleDao); + Mockito.when(xPortalUserRoleDao.findByUserId(userId)).thenReturn(xPortalUserRoleList); + Mockito.when(userMgr.getUserProfileByLoginId(userProfile.getLoginId())).thenReturn(userProfile); + VXUser loggedInUser = vxUser(); + List loggedInUserRole = new ArrayList<>(); + loggedInUserRole.add(RangerConstants.ROLE_SYS_ADMIN); + loggedInUser.setId(8L); + loggedInUser.setName("admin"); + loggedInUser.setUserRoleList(loggedInUserRole); + Mockito.when(xUserService.getXUserByUserName("admin")).thenReturn(loggedInUser); + VXUser testuser = vxUser(); + Mockito.when(xUserService.getXUserByUserName("testuser")).thenReturn(testuser); + VXStringList vXStringList = xUserMgr.getUserRolesByName(userProfile.getLoginId()); + Assert.assertNotNull(vXStringList); + Mockito.when(restErrorUtil.createRESTException("Please provide a valid userName", MessageEnums.INVALID_INPUT_DATA)).thenThrow(new WebApplicationException()); + thrown.expect(WebApplicationException.class); + xUserMgr.getUserRolesByName(""); + } + + @Test + public void test46hasAccess() { + setup(); + xUserMgr.hasAccess("test"); + } + + @Test + public void test47searchXUsers() { + VXUser vxUser = vxUser(); + vxUser.setStatus(1); + vxUser.setUserSource(1); + VXUserList vXUserListSort = new VXUserList(); + List vXUsers = new ArrayList<>(); + vXUsers.add(vxUser); + vXUserListSort.setVXUsers(vXUsers); + String userName = vxUser.getName(); + SearchCriteria testSearchCriteria = createsearchCriteria(); + testSearchCriteria.addParam("name", userName); + Mockito.when(xUserService.getXUserByUserName(userName)).thenReturn(vxUser); + Mockito.when(xUserService.searchXUsers(testSearchCriteria)).thenReturn(vXUserListSort); + VXUserList dbVXUserList = xUserMgr.searchXUsers(testSearchCriteria); + Assert.assertNotNull(dbVXUserList); + testSearchCriteria.addParam("isvisible", "true"); + dbVXUserList = xUserMgr.searchXUsers(testSearchCriteria); + Assert.assertNotNull(dbVXUserList); + testSearchCriteria = createsearchCriteria(); + testSearchCriteria.addParam("name", userName); + testSearchCriteria.addParam("usersource", vxUser.getUserSource()); + Mockito.when(xUserService.getXUserByUserName(userName)).thenReturn(vxUser); + Mockito.when(xUserService.searchXUsers(testSearchCriteria)).thenReturn(vXUserListSort); + List vXGroupList = new ArrayList<>(); + final VXGroup vXGroup1 = vxGroup(); + vXGroup1.setName("users"); + vXGroup1.setDescription("users -added for unit testing"); + vXGroupList.add(vXGroup1); + testSearchCriteria.addParam("xUserId", userId); + dbVXUserList = xUserMgr.searchXUsers(testSearchCriteria); + Assert.assertNotNull(dbVXUserList); + testSearchCriteria = createsearchCriteria(); + testSearchCriteria.addParam("name", userName); + testSearchCriteria.addParam("emailaddress", vxUser.getEmailAddress()); + Mockito.when(xUserService.getXUserByUserName(userName)).thenReturn(vxUser); + Mockito.when(xUserService.searchXUsers(testSearchCriteria)).thenReturn(vXUserListSort); + dbVXUserList = xUserMgr.searchXUsers(testSearchCriteria); + } + + @Test + public void test48searchXGroups() { + setupUser(); + VXGroup vXGroup = vxGroup(); + VXGroupList vXGroupListSort = new VXGroupList(); + List vXGroups = new ArrayList<>(); + vXGroups.add(vXGroup); + vXGroupListSort.setVXGroups(vXGroups); + String groupName = vXGroup.getName(); + SearchCriteria testSearchCriteria = createsearchCriteria(); + testSearchCriteria.addParam("name", groupName); + Mockito.when(xGroupService.getGroupByGroupName(groupName)).thenReturn(vXGroup); + Mockito.when(xGroupService.searchXGroups(testSearchCriteria)).thenReturn(vXGroupListSort); + VXGroupList vXGroupList = xUserMgr.searchXGroups(testSearchCriteria); + testSearchCriteria.addParam("isvisible", "true"); + vXGroupList = xUserMgr.searchXGroups(testSearchCriteria); + Assert.assertNotNull(vXGroupList); + testSearchCriteria = createsearchCriteria(); + testSearchCriteria.addParam("name", groupName); + testSearchCriteria.addParam("groupsource", 1L); + Mockito.when(xGroupService.searchXGroups(testSearchCriteria)).thenReturn(vXGroupListSort); + vXGroupList = xUserMgr.searchXGroups(testSearchCriteria); + Assert.assertNotNull(vXGroupList); + testSearchCriteria = createsearchCriteria(); + testSearchCriteria.addParam("name", groupName); + testSearchCriteria.addParam("userid", userId); + VXUser loggedInUser = vxUser(); + List loggedInUserRole = new ArrayList<>(); + loggedInUserRole.add(RangerConstants.ROLE_USER); + loggedInUser.setId(8L); + loggedInUser.setName("testuser"); + loggedInUser.setUserRoleList(loggedInUserRole); + Mockito.when(xUserService.getXUserByUserName(userLoginID)).thenReturn(loggedInUser); + Mockito.when(xGroupService.searchXGroups(testSearchCriteria)).thenReturn(vXGroupListSort); + + List groupIdList = new ArrayList<>(); + groupIdList.add(2L); + XXGroupUserDao mockxxGroupUserDao = Mockito.mock(XXGroupUserDao.class); + Mockito.when(daoManager.getXXGroupUser()).thenReturn(mockxxGroupUserDao); + Mockito.when(mockxxGroupUserDao.findGroupIdListByUserId(loggedInUser.getId())).thenReturn(groupIdList); + XXModuleDefDao modDef = Mockito.mock(XXModuleDefDao.class); + Mockito.when(daoManager.getXXModuleDef()).thenReturn(modDef); + List lstModule = new ArrayList<>(); + lstModule.add(RangerConstants.MODULE_USER_GROUPS); + Mockito.when(modDef.findAccessibleModulesByUserId(Mockito.anyLong(), Mockito.anyLong())).thenReturn(lstModule); + xUserMgr.searchXGroups(testSearchCriteria); + } + + @Test + public void test49createServiceConfigUser() { + XXUserDao xxUserDao = Mockito.mock(XXUserDao.class); + VXUser vxUser = vxUser(); + XXUser xXUser = xxUser(vxUser); + VXPortalUser userProfile = userProfile(); + Collection userRoleList = getRoleList(); + VXUserPermission vXUserPermission = vxUserPermission(); + XXUserPermission xUserPermissionObj = xxUserPermission(); + xUserPermissionObj.setModuleId(vXUserPermission.getModuleId()); + xUserPermissionObj.setUserId(vXUserPermission.getUserId()); + Mockito.when(daoManager.getXXUser()).thenReturn(xxUserDao); + Mockito.when(xxUserDao.findByUserName(vxUser.getName())).thenReturn(xXUser); + Mockito.when(xUserService.populateViewBean(xXUser)).thenReturn(vxUser); + VXUser serviceConfigUser = xUserMgr.createServiceConfigUser(vxUser.getName()); + Assert.assertNotNull(serviceConfigUser); + Assert.assertEquals(xXUser.getName(), serviceConfigUser.getName()); + Mockito.when(daoManager.getXXUser()).thenReturn(xxUserDao); + Mockito.when(xxUserDao.findByUserName(vxUser.getName())).thenReturn(null, xXUser); + Mockito.when(daoManager.getXXUser()).thenReturn(xxUserDao); + UserSessionBase userSession = Mockito.mock(UserSessionBase.class); + Set userSessions = new HashSet<>(); + userSessions.add(userSession); + + userProfile.setUserRoleList(userRoleList); + List xUserPermissionsList = new ArrayList<>(); + XXUserPermission xUserPermissionObj2 = new XXUserPermission(); + xUserPermissionObj2.setAddedByUserId(userId); + xUserPermissionObj2.setCreateTime(new Date()); + xUserPermissionObj2.setId(userId); + xUserPermissionObj2.setIsAllowed(1); + xUserPermissionObj2.setModuleId(1L); + xUserPermissionObj2.setUpdatedByUserId(userId); + xUserPermissionObj2.setUpdateTime(new Date()); + xUserPermissionObj2.setUserId(userId); + xUserPermissionsList.add(xUserPermissionObj2); + + serviceConfigUser = xUserMgr.createServiceConfigUser(vxUser.getName()); + Assert.assertNotNull(serviceConfigUser); + Assert.assertEquals(xXUser.getName(), serviceConfigUser.getName()); + } + + @Test + public void test50createServiceConfigUser_WithBlankName() { + destroySession(); + setup(); + Mockito.when(restErrorUtil.createRESTException("Please provide a valid username.", MessageEnums.INVALID_INPUT_DATA)).thenThrow(new WebApplicationException()); + thrown.expect(WebApplicationException.class); + xUserMgr.createServiceConfigUser(null); + } + + @Test + public void test51assignPermissionToUser() { + XXModuleDefDao xXModuleDefDao = Mockito.mock(XXModuleDefDao.class); + XXUserPermissionDao xXUserPermissionDao = Mockito.mock(XXUserPermissionDao.class); + XXUserDao xxUserDao = Mockito.mock(XXUserDao.class); + VXPortalUser vXPortalUser = userProfile(); + Collection userRoleList = new ArrayList<>(); + userRoleList.add("ROLE_USER"); + vXPortalUser.setUserRoleList(userRoleList); + VXUser vxUser = vxUser(); + XXUser xXUser = xxUser(vxUser); + List xXModuleDefs = xxModuleDefs(); + VXUserPermission userPermission = vxUserPermission(); + List userPermList = new ArrayList<>(); + userPermList.add(userPermission); + List xUserPermissionsList = new ArrayList<>(); + XXUserPermission xUserPermissionObj = xxUserPermission(); + xUserPermissionObj.setModuleId(userPermission.getModuleId()); + xUserPermissionObj.setUserId(userPermission.getUserId()); + xUserPermissionsList.add(xUserPermissionObj); + Mockito.when(daoManager.getXXModuleDef()).thenReturn(xXModuleDefDao); + Mockito.when(xXModuleDefDao.getAll()).thenReturn(xXModuleDefs); + Mockito.when(daoManager.getXXUserPermission()).thenReturn(xXUserPermissionDao); + Mockito.when(xXUserPermissionDao.findByModuleIdAndPortalUserId(vXPortalUser.getId(), xXModuleDefs.get(0).getId())).thenReturn(xUserPermissionObj); + Mockito.when(daoManager.getXXUser()).thenReturn(xxUserDao); + Mockito.when(xxUserDao.findByPortalUserId(vXPortalUser.getId())).thenReturn(xXUser); + UserSessionBase userSession = Mockito.mock(UserSessionBase.class); + Set userSessions = new HashSet<>(); + userSessions.add(userSession); + Mockito.when(xUserPermissionService.createResource(Mockito.any())).thenReturn(userPermission); + Mockito.when(xUserPermissionService.populateViewBean(xUserPermissionObj)).thenReturn(userPermission); + Mockito.when(xUserPermissionService.updateResource(Mockito.any())).thenReturn(userPermission); + Mockito.when(sessionMgr.getActiveUserSessionsForPortalUserId(userId)).thenReturn(userSessions); + xUserMgr.assignPermissionToUser(vXPortalUser, true); + userRoleList.clear(); + userRoleList.add("ROLE_SYS_ADMIN"); + vXPortalUser.setUserRoleList(userRoleList); + xUserMgr.assignPermissionToUser(vXPortalUser, true); + userRoleList.clear(); + userRoleList.add("ROLE_KEY_ADMIN"); + vXPortalUser.setUserRoleList(userRoleList); + xUserMgr.assignPermissionToUser(vXPortalUser, true); + userRoleList.clear(); + userRoleList.add("ROLE_KEY_ADMIN_AUDITOR"); + vXPortalUser.setUserRoleList(userRoleList); + xUserMgr.assignPermissionToUser(vXPortalUser, true); + userRoleList.clear(); + userRoleList.add("ROLE_ADMIN_AUDITOR"); + vXPortalUser.setUserRoleList(userRoleList); + xUserMgr.assignPermissionToUser(vXPortalUser, true); + Assert.assertNotNull(xXModuleDefs); + } + + @Test + public void test52createXGroupUserFromMap() { + setup(); + VXGroup vxGroup = vxGroup(); + VXUser vxUser = vxUser(); + List vXUserList = new ArrayList<>(); + vXUserList.add(vxUser); + VXGroupUserInfo vxGUInfo = new VXGroupUserInfo(); + vxGUInfo.setXgroupInfo(vxGroup); + vxGUInfo.setXuserInfo(vXUserList); + XXUserDao xxUserDao = Mockito.mock(XXUserDao.class); + XXPortalUserDao userDao = Mockito.mock(XXPortalUserDao.class); + XXPortalUserRoleDao userRoleDao = Mockito.mock(XXPortalUserRoleDao.class); + XXModuleDefDao xXModuleDefDao = Mockito.mock(XXModuleDefDao.class); + XXUser xXUser = xxUser(vxUser); + VXPortalUser userProfile = userProfile(); + XXPortalUser xXPortalUser = xxPortalUser(userProfile); + xXPortalUser.setUserSource(RangerCommonEnums.USER_EXTERNAL); + List lstRole = new ArrayList<>(); + lstRole.add(RangerConstants.ROLE_SYS_ADMIN); + List xXModuleDefs = new ArrayList<>(); + Mockito.when(daoManager.getXXUser()).thenReturn(xxUserDao); + Mockito.when(xxUserDao.findByUserName(vxUser.getName())).thenReturn(xXUser); + Mockito.when(daoManager.getXXPortalUser()).thenReturn(userDao); + Mockito.when(userDao.findByLoginId(vxUser.getName())).thenReturn(xXPortalUser); + Mockito.when(xGroupService.createXGroupWithOutLogin(vxGroup)).thenReturn(vxGroup); + Mockito.when(daoManager.getXXPortalUserRole()).thenReturn(userRoleDao); + Mockito.when(userMgr.mapXXPortalUserToVXPortalUserForDefaultAccount(xXPortalUser)).thenReturn(userProfile); + Mockito.when(daoManager.getXXModuleDef()).thenReturn(xXModuleDefDao); + Mockito.when(xXModuleDefDao.getAll()).thenReturn(xXModuleDefs); + VXGroupUserInfo vxGUInfoObj = xUserMgr.createXGroupUserFromMap(vxGUInfo); + Assert.assertNotNull(vxGUInfoObj); + } + + @Test + public void test53getXGroupUserFromMap() { + setup(); + VXGroup vxGroup = vxGroup(); + VXUser vxUser = vxUser(); + List vXUserList = new ArrayList<>(); + vXUserList.add(vxUser); + VXGroupUserInfo vxGUInfo = new VXGroupUserInfo(); + vxGUInfo.setXgroupInfo(vxGroup); + vxGUInfo.setXuserInfo(vXUserList); + XXGroupDao xxGroupDao = Mockito.mock(XXGroupDao.class); + XXGroup xxGroup = new XXGroup(); + xxGroup.setId(vxGroup.getId()); + xxGroup.setName(vxGroup.getName()); + xxGroup.setDescription(vxGroup.getDescription()); + xxGroup.setIsVisible(vxGroup.getIsVisible()); + VXPortalUser userProfile = userProfile(); + XXPortalUser xXPortalUser = xxPortalUser(userProfile); + xXPortalUser.setUserSource(RangerCommonEnums.USER_EXTERNAL); + VXGroupUserList vxGroupUserList = new VXGroupUserList(); + List vXGroupUsers = new ArrayList<>(); + VXGroupUser vxGroupUser = vxGroupUser(); + vXGroupUsers.add(vxGroupUser); + vxGroupUserList.setVXGroupUsers(vXGroupUsers); + List lstRole = new ArrayList<>(); + lstRole.add(RangerConstants.ROLE_USER); + Mockito.when(daoManager.getXXGroup()).thenReturn(xxGroupDao); + SearchCriteria searchCriteria = createsearchCriteria(); + searchCriteria.addParam("xGroupId", xxGroup.getId()); + Mockito.when(xxGroupDao.findByGroupName("")).thenReturn(null); + VXGroupUserInfo vxGUInfoObjNull = xUserMgr.getXGroupUserFromMap(""); + Assert.assertNull(vxGUInfoObjNull.getXgroupInfo()); + Mockito.when(xxGroupDao.findByGroupName(Mockito.anyString())).thenReturn(xxGroup); + Mockito.when(xGroupService.populateViewBean(xxGroup)).thenReturn(vxGroup); + Mockito.when(xGroupUserService.searchXGroupUsers(Mockito.any())).thenReturn(vxGroupUserList); + XXUser xXUser = xxUser(vxUser); + XXUserDao xxUserDao = Mockito.mock(XXUserDao.class); + Mockito.when(daoManager.getXXUser()).thenReturn(xxUserDao); + Mockito.when(xxUserDao.getById(userId)).thenReturn(xXUser); + XXPortalUserDao xXPortalUserDao = Mockito.mock(XXPortalUserDao.class); + Mockito.when(daoManager.getXXPortalUser()).thenReturn(xXPortalUserDao); + Mockito.when(xXPortalUserDao.findByLoginId(xXUser.getName().trim())).thenReturn(xXPortalUser); + XXPortalUserRoleDao xXPortalUserRoleDao = Mockito.mock(XXPortalUserRoleDao.class); + Mockito.when(daoManager.getXXPortalUserRole()).thenReturn(xXPortalUserRoleDao); + vxGUInfoObjNull = xUserMgr.getXGroupUserFromMap(xxGroup.getName()); + } + + @Test + public void test54modifyUserActiveStatus() { + setup(); + XXUserDao xxUserDao = Mockito.mock(XXUserDao.class); + VXPortalUser userProfile = userProfile(); + VXUser vxUser = vxUser(); + XXUser xXUser = xxUser(vxUser); + XXPortalUser xXPortalUser = xxPortalUser(userProfile); + xXPortalUser.setUserSource(RangerCommonEnums.USER_EXTERNAL); + Mockito.when(daoManager.getXXUser()).thenReturn(xxUserDao); + Mockito.when(xxUserDao.getById(xXUser.getId())).thenReturn(xXUser); + Mockito.when(userMgr.updateUser(userProfile)).thenReturn(xXPortalUser); + HashMap statusMap = new HashMap<>(); + statusMap.put(xXUser.getId(), 1); + Mockito.when(userMgr.getUserProfileByLoginId(vxUser.getName())).thenReturn(userProfile); + xUserMgr.modifyUserActiveStatus(statusMap); + } + + @Test + public void test55updateXGroupUser() { + setup(); + VXUser vxUser = vxUser(); + vxUser.setUserSource(RangerCommonEnums.USER_EXTERNAL); + VXGroupUser vxGroupUser = vxGroupUser(); + Mockito.when(xGroupUserService.updateResource(Mockito.any())).thenReturn(vxGroupUser); + VXGroupUser dbvxUser = xUserMgr.updateXGroupUser(vxGroupUser); + Assert.assertNotNull(dbvxUser); + Assert.assertEquals(dbvxUser.getId(), vxGroupUser.getId()); + Assert.assertEquals(dbvxUser.getName(), vxGroupUser.getName()); + Mockito.verify(xGroupUserService).updateResource(Mockito.any()); + } + + @Test + public void test59deleteXGroupUser() { + setup(); + VXUser vxUser = vxUser(); + vxUser.setUserSource(RangerCommonEnums.USER_EXTERNAL); + VXGroupUser vXGroupUser = vxGroupUser(); + Mockito.when(xGroupUserService.deleteResource(Mockito.any())).thenReturn(true); + xUserMgr.deleteXGroupUser(vXGroupUser.getId(), true); + Mockito.verify(xGroupUserService).deleteResource(Mockito.any()); + } + + @Test + public void test60postUserGroupAuditInfo() { + setup(); + VXUgsyncAuditInfo vxUgsyncAuditInfo = new VXUgsyncAuditInfo(); + vxUgsyncAuditInfo.setId(userId); + Mockito.when(xUgsyncAuditInfoService.createUgsyncAuditInfo(Mockito.any())).thenReturn(vxUgsyncAuditInfo); + VXUgsyncAuditInfo dbVXUgsyncAuditInfo = xUserMgr.postUserGroupAuditInfo(vxUgsyncAuditInfo); + Assert.assertNotNull(dbVXUgsyncAuditInfo); + Assert.assertEquals(dbVXUgsyncAuditInfo.getId(), vxUgsyncAuditInfo.getId()); + Mockito.verify(xUgsyncAuditInfoService).createUgsyncAuditInfo(Mockito.any()); + } + + @Test + public void test61createXGroupUser() { + setup(); + VXUser vxUser = vxUser(); + vxUser.setUserSource(RangerCommonEnums.USER_EXTERNAL); + VXGroupUser vxGroupUser = vxGroupUser(); + Mockito.when(xGroupUserService.createXGroupUserWithOutLogin(Mockito.any())).thenReturn(vxGroupUser); + VXGroupUser dbvxUser = xUserMgr.createXGroupUser(vxGroupUser); + Assert.assertNotNull(dbvxUser); + Assert.assertEquals(dbvxUser.getId(), vxGroupUser.getId()); + Assert.assertEquals(dbvxUser.getName(), vxGroupUser.getName()); + Mockito.verify(xGroupUserService).createXGroupUserWithOutLogin(Mockito.any()); + } + + @Test + public void test62createXGroupUser() { + setup(); + VXGroupUser vXGroupUser = vxGroupUser(); + VXGroup vxGroup = vxGroup(); + Mockito.when(xGroupService.readResource(userId)).thenReturn(vxGroup); + Mockito.when(xGroupUserService.createResource(Mockito.any())).thenReturn(vXGroupUser); + VXGroupUser dbVXGroupUser = xUserMgr.createXGroupUser(userId, vxGroup.getId()); + Assert.assertNotNull(dbVXGroupUser); + Assert.assertEquals(userId, dbVXGroupUser.getId()); + Assert.assertEquals(dbVXGroupUser.getOwner(), vXGroupUser.getOwner()); + Assert.assertEquals(dbVXGroupUser.getName(), vXGroupUser.getName()); + Assert.assertEquals(dbVXGroupUser.getUserId(), vXGroupUser.getUserId()); + Assert.assertEquals(dbVXGroupUser.getUpdatedBy(), vXGroupUser.getUpdatedBy()); + } + + @Test + public void test63searchXUsers_Cases() { + VXUser vxUser = vxUser(); + VXUserList vXUserListSort = new VXUserList(); + List vXUsers = new ArrayList<>(); + vXUsers.add(vxUser); + vXUserListSort.setVXUsers(vXUsers); + String userName = vxUser.getName(); + SearchCriteria testSearchCriteria = createsearchCriteria(); + testSearchCriteria.addParam("name", userName); + Mockito.when(xUserService.getXUserByUserName(userName)).thenReturn(vxUser); + Mockito.when(xUserService.searchXUsers(testSearchCriteria)).thenReturn(vXUserListSort); + VXUserList dbVXUserList = xUserMgr.searchXUsers(testSearchCriteria); + Assert.assertNotNull(dbVXUserList); + testSearchCriteria.addParam("isvisible", "true"); + dbVXUserList = xUserMgr.searchXUsers(testSearchCriteria); + Assert.assertNotNull(dbVXUserList); + testSearchCriteria = createsearchCriteria(); + testSearchCriteria.addParam("name", userName); + testSearchCriteria.addParam("status", RangerCommonEnums.USER_EXTERNAL); + Mockito.when(xUserService.searchXUsers(testSearchCriteria)).thenReturn(vXUserListSort); + dbVXUserList = xUserMgr.searchXUsers(testSearchCriteria); + Assert.assertNotNull(dbVXUserList); + testSearchCriteria = createsearchCriteria(); + testSearchCriteria.addParam("name", userName); + testSearchCriteria.addParam("usersource", 1L); + Mockito.when(xUserService.searchXUsers(testSearchCriteria)).thenReturn(vXUserListSort); + dbVXUserList = xUserMgr.searchXUsers(testSearchCriteria); + Assert.assertNotNull(dbVXUserList); + testSearchCriteria = createsearchCriteria(); + testSearchCriteria.addParam("name", userName); + testSearchCriteria.addParam("emailaddress", "new" + vxUser.getEmailAddress()); + Mockito.when(xUserService.searchXUsers(testSearchCriteria)).thenReturn(vXUserListSort); + dbVXUserList = xUserMgr.searchXUsers(testSearchCriteria); + Assert.assertNotNull(dbVXUserList); + testSearchCriteria = createsearchCriteria(); + testSearchCriteria.addParam("name", userName); + testSearchCriteria.addParam("userrole", RangerConstants.ROLE_USER); + Mockito.when(xUserService.searchXUsers(testSearchCriteria)).thenReturn(vXUserListSort); + dbVXUserList = xUserMgr.searchXUsers(testSearchCriteria); + Assert.assertNotNull(dbVXUserList); + testSearchCriteria = createsearchCriteria(); + testSearchCriteria.addParam("name", userName); + testSearchCriteria.addParam("userrolelist", vxUser.getUserRoleList()); + Mockito.when(xUserService.searchXUsers(testSearchCriteria)).thenReturn(vXUserListSort); + dbVXUserList = xUserMgr.searchXUsers(testSearchCriteria); + Assert.assertNotNull(dbVXUserList); + } + + @Test + public void test64checkAccessRolesAdmin() { + destroySession(); + setup(); + List userRoleList = new ArrayList<>(); + userRoleList.add("ROLE_KEY_ADMIN"); + Mockito.when(restErrorUtil.create403RESTException(Mockito.anyString())).thenThrow(new WebApplicationException()); + thrown.expect(WebApplicationException.class); + xUserMgr.checkAccessRoles(userRoleList); + } + + @Test + public void test65checkAccessRolesKeyAdmin() { + destroySession(); + List userRoleList = new ArrayList<>(); + setupKeyAdmin(); + userRoleList.add("ROLE_SYS_ADMIN"); + Mockito.when(restErrorUtil.create403RESTException(Mockito.anyString())).thenThrow(new WebApplicationException()); + thrown.expect(WebApplicationException.class); + xUserMgr.checkAccessRoles(userRoleList); + } + + @Test + public void test66checkAccessRolesUser() { + destroySession(); + setupUser(); + List userRoleList = new ArrayList<>(); + userRoleList.add("ROLE_USER"); + Mockito.when(restErrorUtil.create403RESTException(Mockito.anyString())).thenThrow(new WebApplicationException()); + thrown.expect(WebApplicationException.class); + xUserMgr.checkAccessRoles(userRoleList); + } + + @Test + public void test67checkAccessRolesUser() { + destroySession(); + List userRoleList = new ArrayList<>(); + userRoleList.add("ROLE_USER"); + VXResponse vXResponse = new VXResponse(); + vXResponse.setStatusCode(HttpServletResponse.SC_UNAUTHORIZED); + vXResponse.setMsgDesc("Bad Credentials"); + Mockito.when(restErrorUtil.generateRESTException(Mockito.any())).thenThrow(new WebApplicationException()); + thrown.expect(WebApplicationException.class); + xUserMgr.checkAccessRoles(userRoleList); + } + + @Test + public void test68getGroupByGroupName() { + destroySession(); + VXGroup vxGroup = vxGroup(); + Mockito.when(xGroupService.getGroupByGroupName(vxGroup.getName())).thenReturn(vxGroup); + VXGroup vxGroup1 = xUserMgr.getGroupByGroupName(vxGroup.getName()); + Assert.assertNotNull(vxGroup1); + Mockito.when(xGroupService.getGroupByGroupName(Mockito.anyString())).thenReturn(null); + Mockito.when(restErrorUtil.createRESTException(vxGroup.getName() + " is Not Found", MessageEnums.DATA_NOT_FOUND)).thenThrow(new WebApplicationException()); + thrown.expect(WebApplicationException.class); + VXGroup vxGroup2 = xUserMgr.getGroupByGroupName(vxGroup.getName()); + Assert.assertNull(vxGroup2); + } + + @Test + public void test69denySelfRoleChange() { + destroySession(); + setupUser(); + Mockito.when(restErrorUtil.create403RESTException(Mockito.anyString())).thenThrow(new WebApplicationException()); + thrown.expect(WebApplicationException.class); + xUserMgr.denySelfRoleChange(userProfile().getLoginId()); + } + + @Test + public void test70denySelfRoleChange() { + destroySession(); + setup(); + Mockito.when(restErrorUtil.create403RESTException(Mockito.anyString())).thenThrow(new WebApplicationException()); + thrown.expect(WebApplicationException.class); + xUserMgr.denySelfRoleChange(adminLoginID); + } + + @Test + public void test71denySelfRoleChange() { + destroySession(); + setupKeyAdmin(); + Mockito.when(restErrorUtil.create403RESTException(Mockito.anyString())).thenThrow(new WebApplicationException()); + thrown.expect(WebApplicationException.class); + xUserMgr.denySelfRoleChange(keyadminLoginID); + } + + @Test + public void test72UpdateXUser() { + destroySession(); + setup(); + Collection existingRoleList = new ArrayList<>(); + existingRoleList.add(RangerConstants.ROLE_USER); + Collection reqRoleList = new ArrayList<>(); + reqRoleList.add(RangerConstants.ROLE_SYS_ADMIN); + Collection groupIdList = new ArrayList<>(); + groupIdList.add(userId); + VXUser vxUser = vxUser(); + vxUser.setUserRoleList(reqRoleList); + vxUser.setUserSource(RangerCommonEnums.USER_EXTERNAL); + vxUser.setGroupIdList(groupIdList); + vxUser.setFirstName("user1"); + vxUser.setLastName("null"); + vxUser.setPassword("*****"); + Mockito.when(xUserService.updateResource(vxUser)).thenReturn(vxUser); + VXPortalUser oldUserProfile = userProfile(); + oldUserProfile.setUserSource(RangerCommonEnums.USER_APP); + oldUserProfile.setPassword(vxUser.getPassword()); + VXPortalUser vXPortalUser = userProfile(); + vXPortalUser.setUserRoleList(existingRoleList); + Mockito.when(userMgr.getUserProfileByLoginId(vxUser.getName())).thenReturn(oldUserProfile); + XXPortalUser xXPortalUser = xxPortalUser(vXPortalUser); + Mockito.when(userMgr.updateUserWithPass(Mockito.any())).thenReturn(xXPortalUser); + List xUserPermissionsList = new ArrayList<>(); + XXUserPermission xUserPermissionObj = new XXUserPermission(); + xUserPermissionObj.setAddedByUserId(userId); + xUserPermissionObj.setCreateTime(new Date()); + xUserPermissionObj.setId(userId); + xUserPermissionObj.setIsAllowed(1); + xUserPermissionObj.setModuleId(1L); + xUserPermissionObj.setUpdatedByUserId(userId); + xUserPermissionObj.setUpdateTime(new Date()); + xUserPermissionObj.setUserId(userId); + xUserPermissionsList.add(xUserPermissionObj); + VXGroupUserList vxGroupUserList = vxGroupUserList(); + Mockito.when(xGroupUserService.searchXGroupUsers(Mockito.any())).thenReturn(vxGroupUserList); + UserSessionBase userSession = Mockito.mock(UserSessionBase.class); + Set userSessions = new HashSet<>(); + userSessions.add(userSession); + VXUser loggedInUser = vxUser(); + List loggedInUserRole = new ArrayList<>(); + loggedInUserRole.add(RangerConstants.ROLE_SYS_ADMIN); + loggedInUser.setId(8L); + loggedInUser.setName("testuser"); + loggedInUser.setUserRoleList(loggedInUserRole); + Mockito.when(xUserService.getXUserByUserName("admin")).thenReturn(loggedInUser); + VXUser dbvxUser = xUserMgr.updateXUser(vxUser); + Assert.assertNotNull(dbvxUser); + Assert.assertEquals(dbvxUser.getId(), vxUser.getId()); + Assert.assertEquals(dbvxUser.getDescription(), vxUser.getDescription()); + Assert.assertEquals(dbvxUser.getName(), vxUser.getName()); + Mockito.verify(xUserService).updateResource(vxUser); + + groupIdList.clear(); + groupIdList.add(9L); + vxUser.setGroupIdList(groupIdList); + vxUser.setPassword("TestUser@1234"); + oldUserProfile.setPassword(vxUser.getPassword()); + vxGroupUserList.setVXGroupUsers(null); + Mockito.when(xGroupUserService.searchXGroupUsers(Mockito.any())).thenReturn(vxGroupUserList); + VXGroup vXGroup = vxGroup(); + Mockito.when(xGroupService.readResource(Mockito.anyLong())).thenReturn(vXGroup); + VXGroupUser vXGroupUser = vxGroupUser(); + Mockito.when(xGroupUserService.createResource(Mockito.any())).thenReturn(vXGroupUser); + dbvxUser = xUserMgr.updateXUser(vxUser); + Assert.assertNotNull(dbvxUser); + + Mockito.when(userMgr.getUserProfileByLoginId(Mockito.anyString())).thenReturn(null); + Mockito.when(restErrorUtil.createRESTException("user " + vxUser.getName() + " does not exist.", MessageEnums.INVALID_INPUT_DATA)).thenThrow(new WebApplicationException()); + thrown.expect(WebApplicationException.class); + vxUser = xUserMgr.updateXUser(vxUser); + Assert.assertNull(vxUser); + } + + @Test + public void test73restrictSelfAccountDeletion() { + destroySession(); + setupUser(); + Mockito.when(restErrorUtil.generateRESTException(Mockito.any())).thenThrow(new WebApplicationException()); + thrown.expect(WebApplicationException.class); + xUserMgr.restrictSelfAccountDeletion(userProfile().getLoginId()); + } + + @Test + public void test74restrictSelfAccountDeletion() { + destroySession(); + setup(); + Mockito.when(restErrorUtil.generateRESTException(Mockito.any())).thenThrow(new WebApplicationException()); + thrown.expect(WebApplicationException.class); + xUserMgr.restrictSelfAccountDeletion(adminLoginID); + } + + @Test + public void test75restrictSelfAccountDeletion() { + destroySession(); + setupKeyAdmin(); + Mockito.when(restErrorUtil.generateRESTException(Mockito.any())).thenThrow(new WebApplicationException()); + thrown.expect(WebApplicationException.class); + xUserMgr.restrictSelfAccountDeletion(keyadminLoginID); + } + + @Test + public void test76restrictSelfAccountDeletion() { + destroySession(); + Mockito.when(restErrorUtil.generateRESTException(Mockito.any())).thenThrow(new WebApplicationException()); + thrown.expect(WebApplicationException.class); + xUserMgr.restrictSelfAccountDeletion(userProfile().getLoginId()); + } + + @Test + public void test77updateUserRolesPermissions() { + setup(); + List existingRoleList = new ArrayList<>(); + existingRoleList.add(RangerConstants.ROLE_USER); + List reqRoleList = new ArrayList<>(); + reqRoleList.add(RangerConstants.ROLE_SYS_ADMIN); + Collection groupIdList = new ArrayList<>(); + groupIdList.add(userId); + VXUser vxUser = vxUser(); + vxUser.setUserRoleList(reqRoleList); + vxUser.setUserSource(RangerCommonEnums.USER_EXTERNAL); + vxUser.setGroupIdList(groupIdList); + vxUser.setFirstName("null"); + vxUser.setLastName("null"); + vxUser.setPassword("*****"); + VXPortalUser oldUserProfile = userProfile(); + oldUserProfile.setUserSource(RangerCommonEnums.USER_APP); + oldUserProfile.setPassword(vxUser.getPassword()); + oldUserProfile.setUserRoleList(existingRoleList); + VXPortalUser vXPortalUser = userProfile(); + vXPortalUser.setUserRoleList(reqRoleList); + List xUserPermissionsList = new ArrayList<>(); + XXUserPermission xUserPermissionObj = new XXUserPermission(); + xUserPermissionObj.setAddedByUserId(userId); + xUserPermissionObj.setCreateTime(new Date()); + xUserPermissionObj.setId(userId); + xUserPermissionObj.setIsAllowed(1); + xUserPermissionObj.setModuleId(1L); + xUserPermissionObj.setUpdatedByUserId(userId); + xUserPermissionObj.setUpdateTime(new Date()); + xUserPermissionObj.setUserId(userId); + xUserPermissionsList.add(xUserPermissionObj); + UserSessionBase userSession = Mockito.mock(UserSessionBase.class); + Set userSessions = new HashSet<>(); + userSessions.add(userSession); + XXUserPermissionDao xUserPermissionDao = Mockito.mock(XXUserPermissionDao.class); + Mockito.when(daoManager.getXXUserPermission()).thenReturn(xUserPermissionDao); + XXModuleDefDao xXModuleDefDao = Mockito.mock(XXModuleDefDao.class); + XXUserPermissionDao xXUserPermissionDao = Mockito.mock(XXUserPermissionDao.class); + XXUserDao xxUserDao = Mockito.mock(XXUserDao.class); + Collection userRoleList = new ArrayList<>(); + userRoleList.add("ROLE_USER"); + vXPortalUser.setUserRoleList(userRoleList); + XXUser xXUser = xxUser(vxUser); + List xXModuleDefs = xxModuleDefs(); + VXUserPermission userPermission = vxUserPermission(); + List userPermList = new ArrayList<>(); + userPermList.add(userPermission); + xUserPermissionObj.setModuleId(userPermission.getModuleId()); + xUserPermissionObj.setUserId(userPermission.getUserId()); + xUserPermissionsList.add(xUserPermissionObj); + Mockito.when(daoManager.getXXModuleDef()).thenReturn(xXModuleDefDao); + Mockito.when(xXModuleDefDao.getAll()).thenReturn(xXModuleDefs); + Mockito.when(daoManager.getXXUserPermission()).thenReturn(xXUserPermissionDao); + Mockito.when(daoManager.getXXUser()).thenReturn(xxUserDao); + Mockito.when(xxUserDao.findByPortalUserId(vXPortalUser.getId())).thenReturn(xXUser); + Mockito.when(xXUserPermissionDao.findByUserPermissionId(vXPortalUser.getId())).thenReturn(xUserPermissionsList); + Mockito.when(xUserPermissionService.createResource(Mockito.any())).thenReturn(userPermission); + Mockito.when(sessionMgr.getActiveUserSessionsForPortalUserId(userId)).thenReturn(userSessions); + xUserMgr.updateUserRolesPermissions(oldUserProfile, reqRoleList); + } + + @Test + public void test78checkAccess() { + destroySession(); + setupUser(); + VXUser vxUser = vxUser(); + Mockito.when(restErrorUtil.create403RESTException(Mockito.anyString())).thenThrow(new WebApplicationException()); + thrown.expect(WebApplicationException.class); + xUserMgr.checkAccess(vxUser); + } + + @Test + public void test79checkAccess() { + destroySession(); + VXUser vxUser = vxUser(); + VXUser loggedInUser = vxUser(); + List loggedInUserRole = new ArrayList<>(); + loggedInUserRole.add(RangerConstants.ROLE_SYS_ADMIN); + loggedInUser.setId(8L); + loggedInUser.setName("admin"); + loggedInUser.setUserRoleList(loggedInUserRole); + Mockito.when(restErrorUtil.generateRESTException(Mockito.any())).thenThrow(new WebApplicationException()); + thrown.expect(WebApplicationException.class); + xUserMgr.checkAccess(vxUser); + } + + @Test + public void test80checkAdminAccess() { + destroySession(); + setupUser(); + Mockito.when(restErrorUtil.generateRESTException(Mockito.any())).thenThrow(new WebApplicationException()); + thrown.expect(WebApplicationException.class); + xUserMgr.checkAdminAccess(); + } + + @Test + public void test81checkAdminAccess() { + destroySession(); + Mockito.when(restErrorUtil.generateRESTException(Mockito.any())).thenThrow(new WebApplicationException()); + thrown.expect(WebApplicationException.class); + xUserMgr.checkAdminAccess(); + } + + @Test + public void test82updateXgroupUserForGroupUpdate() { + setup(); + XXGroupUserDao xxGroupUserDao = Mockito.mock(XXGroupUserDao.class); + VXGroup vXGroup = vxGroup(); + List xXGroupUserList = new ArrayList<>(); + VXGroupUser vxGroupUser = vxGroupUser(); + XXGroupUser xXGroupUser = new XXGroupUser(); + xXGroupUser.setId(vxGroupUser.getId()); + xXGroupUser.setName(vxGroupUser.getName()); + xXGroupUser.setParentGroupId(vxGroupUser.getParentGroupId()); + xXGroupUser.setUserId(vxGroupUser.getUserId()); + xXGroupUserList.add(xXGroupUser); + Mockito.when(daoManager.getXXGroupUser()).thenReturn(xxGroupUserDao); + Mockito.when(xxGroupUserDao.findByGroupId(vXGroup.getId())).thenReturn(xXGroupUserList); + Mockito.when(xGroupUserService.populateViewBean(xXGroupUser)).thenReturn(vxGroupUser); + xUserMgr.updateXgroupUserForGroupUpdate(vXGroup); + Mockito.verify(daoManager).getXXGroupUser(); + Mockito.verify(xxGroupUserDao).findByGroupId(vXGroup.getId()); + } + + @Test + public void test83validatePassword() { + destroySession(); + setup(); + VXUser vxUser = vxUser(); + vxUser.setPassword(null); + Mockito.when(restErrorUtil.createRESTException("serverMsg.xuserMgrValidatePassword", MessageEnums.INVALID_PASSWORD, null, "Password cannot be blank/null", null)).thenThrow(new WebApplicationException()); + thrown.expect(WebApplicationException.class); + xUserMgr.validatePassword(vxUser); + } + + @Test + public void test84validatePassword() { + setup(); + VXUser vxUser = vxUser(); + xUserMgr.validatePassword(vxUser); + } + + @Test + public void test85validatePassword() { + destroySession(); + setup(); + VXUser vxUser = vxUser(); + vxUser.setPassword("password"); + Mockito.when(restErrorUtil.createRESTException("serverMsg.xuserMgrValidatePassword", MessageEnums.INVALID_PASSWORD, null, "Password should be minimum 8 characters, at least one uppercase letter, one lowercase letter and one numeric.", null)).thenThrow(new WebApplicationException()); + thrown.expect(WebApplicationException.class); + xUserMgr.validatePassword(vxUser); + } + + @Test + public void test86deleteXPermMap() { + setup(); + VXResource vxresource = new VXResource(); + XXPermMapDao xXPermMapDao = Mockito.mock(XXPermMapDao.class); + Mockito.when(daoManager.getXXPermMap()).thenReturn(xXPermMapDao); + VXPermMap vXPermMap1 = getVXPermMap(); + XXPermMap xXPermMap1 = new XXPermMap(); + xXPermMap1.setId(vXPermMap1.getId()); + xXPermMap1.setResourceId(vXPermMap1.getResourceId()); + Mockito.when(xXPermMapDao.getById(xXPermMap1.getId())).thenReturn(xXPermMap1); + Mockito.when(xResourceService.readResource(xXPermMap1.getResourceId())).thenReturn(vxresource); + Mockito.when(xPermMapService.deleteResource(Mockito.anyLong())).thenReturn(true); + xUserMgr.deleteXPermMap(vXPermMap1.getId(), true); + } + + @Test + public void test87deleteXPermMap() { + destroySession(); + setup(); + VXResource vxresource = new VXResource(); + XXPermMapDao xXPermMapDao = Mockito.mock(XXPermMapDao.class); + Mockito.when(daoManager.getXXPermMap()).thenReturn(xXPermMapDao); + VXPermMap vXPermMap1 = getVXPermMap(); + XXPermMap xXPermMap1 = new XXPermMap(); + xXPermMap1.setId(vXPermMap1.getId()); + xXPermMap1.setResourceId(vXPermMap1.getResourceId()); + Mockito.when(xXPermMapDao.getById(xXPermMap1.getId())).thenReturn(xXPermMap1); + Mockito.when(xResourceService.readResource(xXPermMap1.getResourceId())).thenReturn(vxresource); + Mockito.when(xResourceService.readResource(xXPermMap1.getResourceId())).thenReturn(null); + Mockito.when(restErrorUtil.createRESTException("Invalid Input Data - No resource found with Id: " + xXPermMap1.getResourceId(), MessageEnums.INVALID_INPUT_DATA)).thenThrow(new WebApplicationException()); + thrown.expect(WebApplicationException.class); + xUserMgr.deleteXPermMap(vXPermMap1.getId(), true); + } + + @Test + public void test88deleteXPermMap() { + destroySession(); + setup(); + VXPermMap vXPermMap1 = getVXPermMap(); + XXPermMap xXPermMap1 = new XXPermMap(); + xXPermMap1.setId(vXPermMap1.getId()); + xXPermMap1.setResourceId(vXPermMap1.getResourceId()); + Mockito.when(restErrorUtil.createRESTException("serverMsg.modelMgrBaseDeleteModel", MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY)).thenThrow(new WebApplicationException()); + thrown.expect(WebApplicationException.class); + xUserMgr.deleteXPermMap(vXPermMap1.getId(), false); + } + + @Test + public void test89deleteXAuditMap() { + destroySession(); + setup(); + VXResource vxresource = new VXResource(); + XXAuditMapDao xXAuditMapDao = Mockito.mock(XXAuditMapDao.class); + Mockito.when(daoManager.getXXAuditMap()).thenReturn(xXAuditMapDao); + VXAuditMap vXAuditMap = getVXAuditMap(); + XXAuditMap xXAuditMap = new XXAuditMap(); + xXAuditMap.setId(vXAuditMap.getId()); + xXAuditMap.setResourceId(vXAuditMap.getResourceId()); + Mockito.when(xXAuditMapDao.getById(vXAuditMap.getId())).thenReturn(xXAuditMap); + Mockito.when(xResourceService.readResource(xXAuditMap.getResourceId())).thenReturn(vxresource); + Mockito.when(xAuditMapService.deleteResource(Mockito.anyLong())).thenReturn(true); + xUserMgr.deleteXAuditMap(vXAuditMap.getId(), true); + Mockito.when(xResourceService.readResource(xXAuditMap.getResourceId())).thenReturn(null); + Mockito.when(restErrorUtil.createRESTException("Invalid Input Data - No resource found with Id: " + xXAuditMap.getResourceId(), MessageEnums.INVALID_INPUT_DATA)).thenThrow(new WebApplicationException()); + thrown.expect(WebApplicationException.class); + xUserMgr.deleteXAuditMap(vXAuditMap.getId(), true); + } + + @Test + public void test90getXPermMapSearchCount() { + SearchCriteria testSearchCriteria = createsearchCriteria(); + testSearchCriteria.addParam("xUserId", userId); + VXPermMap vXPermMap = getVXPermMap(); + List vXPermMapList = new ArrayList<>(); + vXPermMapList.add(vXPermMap); + VXPermMapList permMapList = new VXPermMapList(); + permMapList.setVXPermMaps(vXPermMapList); + Mockito.when(xPermMapService.searchXPermMaps(Mockito.any())).thenReturn(permMapList); + VXLong vXLong = new VXLong(); + vXLong.setValue(permMapList.getListSize()); + VXLong vXLong1 = xUserMgr.getXPermMapSearchCount(testSearchCriteria); + Assert.assertEquals(vXLong.getValue(), vXLong1.getValue()); + } + + @Test + public void test91getXAuditMapSearchCount() { + SearchCriteria testSearchCriteria = createsearchCriteria(); + testSearchCriteria.addParam("xUserId", userId); + VXAuditMap vXAuditMap = getVXAuditMap(); + List vXAuditMapList = new ArrayList<>(); + vXAuditMapList.add(vXAuditMap); + VXAuditMapList auditMapList = new VXAuditMapList(); + auditMapList.setVXAuditMaps(vXAuditMapList); + Mockito.when(xAuditMapService.searchXAuditMaps(Mockito.any())).thenReturn(auditMapList); + VXLong vXLong = new VXLong(); + vXLong.setValue(auditMapList.getListSize()); + VXLong vXLong1 = xUserMgr.getXAuditMapSearchCount(testSearchCriteria); + Assert.assertEquals(vXLong.getValue(), vXLong1.getValue()); + } + + @Test + public void test92searchXPermMap() { + SearchCriteria testSearchCriteria = createsearchCriteria(); + testSearchCriteria.addParam("xUserId", userId); + VXResource vxresource = new VXResource(); + VXPermMap vXPermMap = getVXPermMap(); + List vXPermMapList = new ArrayList<>(); + vXPermMapList.add(vXPermMap); + VXPermMapList permMapList = new VXPermMapList(); + permMapList.setVXPermMaps(vXPermMapList); + Mockito.when(xPermMapService.searchXPermMaps(Mockito.any())).thenReturn(permMapList); + List xResourceList = new ArrayList<>(); + XXResource xRes = new XXResource(); + xRes.setId(userId); + xRes.setName("hadoopdev"); + xRes.setIsRecursive(AppConstants.BOOL_TRUE); + xRes.setResourceStatus(AppConstants.STATUS_ENABLED); + xResourceList.add(xRes); + XXResourceDao xxResourceDao = Mockito.mock(XXResourceDao.class); + Mockito.when(daoManager.getXXResource()).thenReturn(xxResourceDao); + Mockito.when(xxResourceDao.getById(Mockito.anyLong())).thenReturn(xRes); + Mockito.when(xResourceService.populateViewBean(xRes)).thenReturn(vxresource); + VXResponse vXResponse = new VXResponse(); + vXResponse.setStatusCode(VXResponse.STATUS_SUCCESS); + Mockito.when(msBizUtil.hasPermission(vxresource, AppConstants.XA_PERM_TYPE_ADMIN)).thenReturn(vXResponse); + VXPermMapList returnList = xUserMgr.searchXPermMaps(testSearchCriteria); + Assert.assertNotNull(returnList); + Assert.assertEquals(permMapList.getListSize(), returnList.getListSize()); + } + + @Test + public void test93searchXAuditMap() { + SearchCriteria testSearchCriteria = createsearchCriteria(); + testSearchCriteria.addParam("xUserId", userId); + VXResource vxresource = new VXResource(); + VXAuditMap vXAuditMap = getVXAuditMap(); + List vXAuditMapList = new ArrayList<>(); + vXAuditMapList.add(vXAuditMap); + VXAuditMapList auditMapList = new VXAuditMapList(); + auditMapList.setVXAuditMaps(vXAuditMapList); + Mockito.when(xAuditMapService.searchXAuditMaps(Mockito.any())).thenReturn(auditMapList); + List xResourceList = new ArrayList<>(); + XXResource xRes = new XXResource(); + xRes.setId(userId); + xRes.setName("hadoopdev"); + xRes.setIsRecursive(AppConstants.BOOL_TRUE); + xRes.setResourceStatus(AppConstants.STATUS_ENABLED); + xResourceList.add(xRes); + XXResourceDao xxResourceDao = Mockito.mock(XXResourceDao.class); + Mockito.when(daoManager.getXXResource()).thenReturn(xxResourceDao); + Mockito.when(xxResourceDao.getById(Mockito.anyLong())).thenReturn(xRes); + Mockito.when(xResourceService.populateViewBean(xRes)).thenReturn(vxresource); + VXResponse vXResponse = new VXResponse(); + vXResponse.setStatusCode(VXResponse.STATUS_SUCCESS); + Mockito.when(msBizUtil.hasPermission(vxresource, AppConstants.XA_PERM_TYPE_ADMIN)).thenReturn(vXResponse); + VXAuditMapList returnList = xUserMgr.searchXAuditMaps(testSearchCriteria); + Assert.assertNotNull(returnList); + Assert.assertEquals(auditMapList.getListSize(), returnList.getListSize()); + } + + @Test + public void test94DeleteXUser() { + setup(); + boolean force = false; + VXUser vXUser = vxUser(); + XXUser xXUser = new XXUser(); + XXUserDao xXUserDao = Mockito.mock(XXUserDao.class); + Mockito.when(daoManager.getXXUser()).thenReturn(xXUserDao); + Mockito.when(xXUserDao.getById(vXUser.getId())).thenReturn(xXUser); + Mockito.when(xUserService.populateViewBean(xXUser)).thenReturn(vXUser); + VXGroupUserList vxGroupUserList = new VXGroupUserList(); + Mockito.when(xGroupUserService.searchXGroupUsers(Mockito.any())).thenReturn(vxGroupUserList); + VXAuditMapList vXAuditMapList = new VXAuditMapList(); + Mockito.when(xAuditMapService.searchXAuditMaps(Mockito.any())).thenReturn(vXAuditMapList); + VXPortalUser vXPortalUser = userProfile(); + XXPortalUser xXPortalUser = xxPortalUser(vXPortalUser); + XXPortalUserDao xXPortalUserDao = Mockito.mock(XXPortalUserDao.class); + Mockito.when(daoManager.getXXPortalUser()).thenReturn(xXPortalUserDao); + Mockito.when(xXPortalUserDao.findByLoginId(vXUser.getName().trim())).thenReturn(xXPortalUser); + Mockito.when(xPortalUserService.populateViewBean(xXPortalUser)).thenReturn(vXPortalUser); + XXPortalUserRole xxPortalUserRole = new XXPortalUserRole(); + xxPortalUserRole.setId(userId); + xxPortalUserRole.setUserId(userId); + xxPortalUserRole.setUserRole("ROLE_USER"); + XXAuthSessionDao xXAuthSessionDao = Mockito.mock(XXAuthSessionDao.class); + XXUserPermissionDao xXUserPermissionDao = Mockito.mock(XXUserPermissionDao.class); + XXPortalUserRoleDao xXPortalUserRoleDao = Mockito.mock(XXPortalUserRoleDao.class); + Mockito.when(daoManager.getXXAuthSession()).thenReturn(xXAuthSessionDao); + Mockito.when(daoManager.getXXUserPermission()).thenReturn(xXUserPermissionDao); + Mockito.when(daoManager.getXXPortalUserRole()).thenReturn(xXPortalUserRoleDao); + List xXAuthSessions = new ArrayList<>(); + XXAuthSession xXAuthSession = new XXAuthSession(); + xXAuthSession.setId(userId); + xXAuthSession.setLoginId(vXPortalUser.getLoginId()); + List xXUserPermissions = new ArrayList<>(); + List xXPortalUserRoles = new ArrayList<>(); + Mockito.when(xXUserPermissionDao.findByUserPermissionId(vXPortalUser.getId())).thenReturn(xXUserPermissions); + Mockito.when(xXPortalUserRoleDao.findByUserId(vXPortalUser.getId())).thenReturn(xXPortalUserRoles); + XXPolicyDao xXPolicyDao = Mockito.mock(XXPolicyDao.class); + List xXPolicyList = new ArrayList<>(); + Mockito.when(daoManager.getXXPolicy()).thenReturn(xXPolicyDao); + Mockito.when(xXPolicyDao.findByUserId(vXUser.getId())).thenReturn(xXPolicyList); + List zoneSecRefUser = new ArrayList<>(); + XXSecurityZoneRefUserDao zoneSecRefUserDao = Mockito.mock(XXSecurityZoneRefUserDao.class); + Mockito.when(daoManager.getXXSecurityZoneRefUser()).thenReturn(zoneSecRefUserDao); + Mockito.when(zoneSecRefUserDao.findByUserId(userId)).thenReturn(zoneSecRefUser); + List roleRefUser = new ArrayList<>(); + XXRoleRefUserDao roleRefUserDao = Mockito.mock(XXRoleRefUserDao.class); + Mockito.when(daoManager.getXXRoleRefUser()).thenReturn(roleRefUserDao); + Mockito.when(roleRefUserDao.findByUserId(userId)).thenReturn(roleRefUser); + xUserMgr.deleteXUser(vXUser.getId(), force); + Mockito.when(xGroupUserService.searchXGroupUsers(Mockito.any())).thenReturn(new VXGroupUserList()); + XXPolicy xXPolicy = getXXPolicy(); + xXPolicyList.add(xXPolicy); + Mockito.when(xXPolicyDao.findByUserId(userId)).thenReturn(xXPolicyList); + xUserMgr.deleteXUser(vXUser.getId(), force); + Mockito.when(xXPolicyDao.findByUserId(userId)).thenReturn(new ArrayList<>()); + VXPermMapList vXPermMapList = new VXPermMapList(); + VXPermMap vXPermMap1 = getVXPermMap(); + List vXPermMaps = new ArrayList<>(); + vXPermMaps.add(vXPermMap1); + vXPermMapList.setVXPermMaps(vXPermMaps); + Mockito.when(xPermMapService.searchXPermMaps(Mockito.any())).thenReturn(vXPermMapList); + xUserMgr.deleteXUser(vXUser.getId(), force); + Mockito.when(xPermMapService.searchXPermMaps(Mockito.any())).thenReturn(new VXPermMapList()); + List vXAuditMaps = new ArrayList<>(); + VXAuditMap vXAuditMap = getVXAuditMap(); + vXAuditMaps.add(vXAuditMap); + vXAuditMapList.setVXAuditMaps(vXAuditMaps); + Mockito.when(xAuditMapService.searchXAuditMaps(Mockito.any())).thenReturn(vXAuditMapList); + xUserMgr.deleteXUser(vXUser.getId(), force); + Mockito.when(xAuditMapService.searchXAuditMaps(Mockito.any())).thenReturn(new VXAuditMapList()); + xXAuthSessions.add(xXAuthSession); + xUserMgr.deleteXUser(vXUser.getId(), force); + XXUserPermission xUserPermissionObj = xxUserPermission(); + xXUserPermissions.add(xUserPermissionObj); + Mockito.when(xXUserPermissionDao.findByUserPermissionId(vXPortalUser.getId())).thenReturn(xXUserPermissions); + xUserMgr.deleteXUser(vXUser.getId(), force); + Mockito.when(xXUserPermissionDao.findByUserPermissionId(vXPortalUser.getId())).thenReturn(new ArrayList<>()); + xXPortalUserRoles.add(xxPortalUserRole); + Mockito.when(xXPortalUserRoleDao.findByUserId(vXPortalUser.getId())).thenReturn(xXPortalUserRoles); + xUserMgr.deleteXUser(vXUser.getId(), force); + Mockito.when(xXPortalUserRoleDao.findByUserId(vXPortalUser.getId())).thenReturn(new ArrayList<>()); + xUserMgr.deleteXUser(vXUser.getId(), force); + + vXUser.setName(""); + Mockito.when(xXUserDao.getById(vXUser.getId())).thenReturn(xXUser); + Mockito.when(xUserService.populateViewBean(xXUser)).thenReturn(vXUser); + thrown.expect(NullPointerException.class); + xUserMgr.deleteXUser(vXUser.getId(), force); + } + + @Test + public void test95DeleteXGroup() { + setup(); + boolean force = false; + VXGroup vXGroup = vxGroup(); + XXGroupDao xXGroupDao = Mockito.mock(XXGroupDao.class); + XXGroup xXGroup = new XXGroup(); + Mockito.when(daoManager.getXXGroup()).thenReturn(xXGroupDao); + Mockito.when(xXGroupDao.getById(vXGroup.getId())).thenReturn(xXGroup); + Mockito.when(xGroupService.populateViewBean(xXGroup)).thenReturn(vXGroup); + VXGroupUserList vxGroupUserList = vxGroupUserList(); + Mockito.when(xGroupUserService.searchXGroupUsers(Mockito.any())).thenReturn(vxGroupUserList); + VXPermMapList vXPermMapList = new VXPermMapList(); + VXPermMap vXPermMap1 = getVXPermMap(); + List vXPermMaps = new ArrayList<>(); + vXPermMaps.add(vXPermMap1); + VXAuditMapList vXAuditMapList = new VXAuditMapList(); + List vXAuditMaps = new ArrayList<>(); + VXAuditMap vXAuditMap = getVXAuditMap(); + vXAuditMaps.add(vXAuditMap); + XXGroupGroupDao xXGroupGroupDao = Mockito.mock(XXGroupGroupDao.class); + List xXGroupGroups = new ArrayList<>(); + XXGroupPermissionDao xXGroupPermissionDao = Mockito.mock(XXGroupPermissionDao.class); + Mockito.when(daoManager.getXXGroupPermission()).thenReturn(xXGroupPermissionDao); + List xXGroupPermissions = new ArrayList<>(); + Mockito.when(xXGroupPermissionDao.findByGroupId(vXGroup.getId())).thenReturn(xXGroupPermissions); + XXPolicyDao xXPolicyDao = Mockito.mock(XXPolicyDao.class); + List xXPolicyList = new ArrayList<>(); + Mockito.when(daoManager.getXXPolicy()).thenReturn(xXPolicyDao); + List xResourceList = new ArrayList<>(); + List zoneSecRefGroup = new ArrayList<>(); + XXSecurityZoneRefGroupDao zoneSecRefGroupDao = Mockito.mock(XXSecurityZoneRefGroupDao.class); + Mockito.when(daoManager.getXXSecurityZoneRefGroup()).thenReturn(zoneSecRefGroupDao); + List roleRefGroup = new ArrayList<>(); + XXRoleRefGroupDao roleRefGroupDao = Mockito.mock(XXRoleRefGroupDao.class); + Mockito.when(daoManager.getXXRoleRefGroup()).thenReturn(roleRefGroupDao); + Mockito.when(zoneSecRefGroupDao.findByGroupId(userId)).thenReturn(zoneSecRefGroup); + Mockito.when(roleRefGroupDao.findByGroupId(userId)).thenReturn(roleRefGroup); + XXResource xXResource = new XXResource(); + xXResource.setId(userId); + xXResource.setName("hadoopdev"); + xXResource.setIsRecursive(AppConstants.BOOL_TRUE); + xXResource.setResourceStatus(AppConstants.STATUS_ENABLED); + xResourceList.add(xXResource); + xUserMgr.deleteXGroup(vXGroup.getId(), force); + Mockito.when(xGroupUserService.searchXGroupUsers(Mockito.any())).thenReturn(new VXGroupUserList()); + XXPolicy xXPolicy = getXXPolicy(); + xXPolicyList.add(xXPolicy); + Mockito.when(xXPolicyDao.findByGroupId(userId)).thenReturn(xXPolicyList); + xUserMgr.deleteXGroup(vXGroup.getId(), force); + Mockito.when(xXPolicyDao.findByGroupId(userId)).thenReturn(new ArrayList<>()); + vXPermMapList.setVXPermMaps(vXPermMaps); + Mockito.when(xPermMapService.searchXPermMaps(Mockito.any())).thenReturn(vXPermMapList); + xUserMgr.deleteXGroup(vXGroup.getId(), force); + Mockito.when(xPermMapService.searchXPermMaps(Mockito.any())).thenReturn(new VXPermMapList()); + vXAuditMapList.setVXAuditMaps(vXAuditMaps); + Mockito.when(xAuditMapService.searchXAuditMaps(Mockito.any())).thenReturn(vXAuditMapList); + xUserMgr.deleteXGroup(vXGroup.getId(), force); + Mockito.when(xAuditMapService.searchXAuditMaps(Mockito.any())).thenReturn(new VXAuditMapList()); + XXGroupGroup xXGroupGroup = xxGroupGroup(); + xXGroupGroups.add(xXGroupGroup); + xUserMgr.deleteXGroup(vXGroup.getId(), force); + XXGroupPermission xGroupPermissionObj = xxGroupPermission(); + xXGroupPermissions.add(xGroupPermissionObj); + Mockito.when(xXGroupPermissionDao.findByGroupId(vXGroup.getId())).thenReturn(xXGroupPermissions); + xUserMgr.deleteXGroup(vXGroup.getId(), force); + Mockito.when(xXGroupPermissionDao.findByGroupId(vXGroup.getId())).thenReturn(new ArrayList<>()); + xUserMgr.deleteXGroup(vXGroup.getId(), force); + Mockito.when(xGroupService.populateViewBean(xXGroup)).thenReturn(null); + Mockito.when(restErrorUtil.createRESTException("Group ID doesn't exist.", MessageEnums.INVALID_INPUT_DATA)).thenThrow(new WebApplicationException()); + thrown.expect(WebApplicationException.class); + xUserMgr.deleteXGroup(vXGroup.getId(), force); + } + + @Test + public void test96updateXModuleDefPermission() { + XXModuleDefDao xModuleDefDao = Mockito.mock(XXModuleDefDao.class); + XXModuleDef xModuleDef = xxModuleDef(); + VXModuleDef vXModuleDef = vxModuleDef(); + Mockito.when(xModuleDefService.updateResource(vXModuleDef)).thenReturn(vXModuleDef); + Mockito.when(daoManager.getXXModuleDef()).thenReturn(xModuleDefDao); + Mockito.when(xModuleDefDao.getById(userId)).thenReturn(xModuleDef); + + Map xXGroupNameMap = new HashMap<>(); + xXGroupNameMap.put(userId, groupName); + Mockito.when(xGroupService.getXXGroupIdNameMap()).thenReturn(xXGroupNameMap); + + Object[] objArr = new Object[] {userId, userId, userLoginID}; + Map xXUserMap = new HashMap<>(); + xXUserMap.put(userId, objArr); + Mockito.when(xUserService.getXXPortalUserIdXXUserNameMap()).thenReturn(xXUserMap); + + Mockito.when(xModuleDefService.populateViewBean(xModuleDef, xXUserMap, xXGroupNameMap, true)).thenReturn(vXModuleDef); + List xXGroupPermissions = new ArrayList<>(); + XXGroupPermission xGroupPermissionObj = xxGroupPermission(); + xXGroupPermissions.add(xGroupPermissionObj); + List vXGroupPermissions = new ArrayList<>(); + VXGroupPermission vXGroupPermission = vxGroupPermission(); + vXGroupPermission.setIsAllowed(0); + vXGroupPermissions.add(vXGroupPermission); + List xXUserPermissions = new ArrayList<>(); + XXUserPermission xUserPermissionObj = xxUserPermission(); + xXUserPermissions.add(xUserPermissionObj); + VXUserPermission vxUserPermission = vxUserPermission(); + vxUserPermission.setIsAllowed(0); + UserSessionBase userSession = Mockito.mock(UserSessionBase.class); + Set userSessions = new HashSet<>(); + userSessions.add(userSession); + Map groupPermMapOld = new HashMap<>(); + groupPermMapOld.put(vXGroupPermission.getGroupId(), vXGroupPermission); + Mockito.when(xGroupPermissionService.convertVListToVMap(Mockito.any())).thenReturn(groupPermMapOld); + Mockito.when(xGroupPermissionService.updateResource(vXGroupPermission)).thenReturn(vXGroupPermission); + XXGroupUserDao xxGroupUserDao = Mockito.mock(XXGroupUserDao.class); + Mockito.when(daoManager.getXXGroupUser()).thenReturn(xxGroupUserDao); + List grpUsers = new ArrayList<>(); + Mockito.when(xxGroupUserDao.findByGroupId(vXGroupPermission.getGroupId())).thenReturn(grpUsers); + List userPermListOld = new ArrayList<>(); + userPermListOld.add(vxUserPermission); + Map userPermMapOld = new HashMap<>(); + userPermMapOld.put(vxUserPermission.getUserId(), vxUserPermission); + Mockito.when(xUserPermissionService.convertVListToVMap(Mockito.any())).thenReturn(userPermMapOld); + Mockito.when(xUserPermissionService.updateResource(vxUserPermission)).thenReturn(vxUserPermission); + Mockito.when(sessionMgr.getActiveUserSessionsForPortalUserId(vxUserPermission.getUserId())).thenReturn(userSessions); + VXModuleDef dbMuduleDef = xUserMgr.updateXModuleDefPermission(vXModuleDef); + Assert.assertEquals(dbMuduleDef, vXModuleDef); + Assert.assertNotNull(dbMuduleDef); + Assert.assertEquals(dbMuduleDef, vXModuleDef); + Assert.assertEquals(dbMuduleDef.getId(), vXModuleDef.getId()); + Assert.assertEquals(dbMuduleDef.getOwner(), vXModuleDef.getOwner()); + Assert.assertEquals(dbMuduleDef.getUpdatedBy(), vXModuleDef.getUpdatedBy()); + Assert.assertEquals(dbMuduleDef.getUrl(), vXModuleDef.getUrl()); + Assert.assertEquals(dbMuduleDef.getAddedById(), vXModuleDef.getAddedById()); + Assert.assertEquals(dbMuduleDef.getCreateDate(), vXModuleDef.getCreateDate()); + Assert.assertEquals(dbMuduleDef.getCreateTime(), vXModuleDef.getCreateTime()); + Assert.assertEquals(dbMuduleDef.getUserPermList(), vXModuleDef.getUserPermList()); + Assert.assertEquals(dbMuduleDef.getGroupPermList(), vXModuleDef.getGroupPermList()); + Mockito.verify(xModuleDefService).populateViewBean(xModuleDef, xXUserMap, xXGroupNameMap, true); + Mockito.verify(xModuleDefService).updateResource(vXModuleDef); + Mockito.verify(daoManager).getXXModuleDef(); + } + + @Test + public void test97updateXModuleDefPermission() { + XXModuleDefDao xModuleDefDao = Mockito.mock(XXModuleDefDao.class); + XXModuleDef xModuleDef = xxModuleDef(); + VXModuleDef vXModuleDef = vxModuleDef(); + Mockito.when(xModuleDefService.updateResource(vXModuleDef)).thenReturn(vXModuleDef); + Mockito.when(daoManager.getXXModuleDef()).thenReturn(xModuleDefDao); + Mockito.when(xModuleDefDao.getById(userId)).thenReturn(xModuleDef); + + Map xXGroupNameMap = new HashMap<>(); + xXGroupNameMap.put(userId, groupName); + Mockito.when(xGroupService.getXXGroupIdNameMap()).thenReturn(xXGroupNameMap); + + Object[] objArr = new Object[] {userId, userId, userLoginID}; + Map xXUserMap = new HashMap<>(); + xXUserMap.put(userId, objArr); + Mockito.when(xUserService.getXXPortalUserIdXXUserNameMap()).thenReturn(xXUserMap); + + Mockito.when(xModuleDefService.populateViewBean(xModuleDef, xXUserMap, xXGroupNameMap, true)).thenReturn(vXModuleDef); + List xXGroupPermissions = new ArrayList<>(); + XXGroupPermission xGroupPermissionObj = xxGroupPermission(); + xXGroupPermissions.add(xGroupPermissionObj); + VXGroupPermission vXGroupPermission = vxGroupPermission(); + vXGroupPermission.setIsAllowed(0); + List xXUserPermissions = new ArrayList<>(); + XXUserPermission xUserPermissionObj = xxUserPermission(); + xXUserPermissions.add(xUserPermissionObj); + VXUserPermission vxUserPermission = vxUserPermission(); + vxUserPermission.setIsAllowed(0); + UserSessionBase userSession = Mockito.mock(UserSessionBase.class); + Set userSessions = new HashSet<>(); + userSessions.add(userSession); + XXGroupUserDao xxGroupUserDao = Mockito.mock(XXGroupUserDao.class); + Mockito.when(daoManager.getXXGroupUser()).thenReturn(xxGroupUserDao); + List grpUsers = new ArrayList<>(); + Mockito.when(xxGroupUserDao.findByGroupId(vXGroupPermission.getGroupId())).thenReturn(grpUsers); + Mockito.when(sessionMgr.getActiveUserSessionsForPortalUserId(vxUserPermission.getUserId())).thenReturn(userSessions); + Mockito.when(xGroupPermissionService.createResource(Mockito.any())).thenReturn(vXGroupPermission); + Mockito.when(xUserPermissionService.createResource(Mockito.any())).thenReturn(vxUserPermission); + VXModuleDef dbModuleDef = xUserMgr.updateXModuleDefPermission(vXModuleDef); + Assert.assertEquals(dbModuleDef, vXModuleDef); + Assert.assertNotNull(dbModuleDef); + Assert.assertEquals(dbModuleDef, vXModuleDef); + Assert.assertEquals(dbModuleDef.getId(), vXModuleDef.getId()); + Assert.assertEquals(dbModuleDef.getOwner(), vXModuleDef.getOwner()); + Assert.assertEquals(dbModuleDef.getUpdatedBy(), vXModuleDef.getUpdatedBy()); + Assert.assertEquals(dbModuleDef.getUrl(), vXModuleDef.getUrl()); + Assert.assertEquals(dbModuleDef.getAddedById(), vXModuleDef.getAddedById()); + Assert.assertEquals(dbModuleDef.getCreateDate(), vXModuleDef.getCreateDate()); + Assert.assertEquals(dbModuleDef.getCreateTime(), vXModuleDef.getCreateTime()); + Assert.assertEquals(dbModuleDef.getUserPermList(), vXModuleDef.getUserPermList()); + Assert.assertEquals(dbModuleDef.getGroupPermList(), vXModuleDef.getGroupPermList()); + Mockito.verify(xModuleDefService).updateResource(vXModuleDef); + Mockito.verify(daoManager).getXXModuleDef(); + Mockito.verify(xModuleDefService).populateViewBean(xModuleDef, xXUserMap, xXGroupNameMap, true); + Mockito.verify(xGroupService).getXXGroupIdNameMap(); + Mockito.verify(xUserService).getXXPortalUserIdXXUserNameMap(); + } + + @Test + public void test98modifyUserActiveStatus() { + VXUser vxUser = vxUser(); + XXUser xXUser = xxUser(vxUser); + HashMap statusMap = new HashMap<>(); + statusMap.put(xXUser.getId(), 1); + RangerSecurityContext context = new RangerSecurityContext(); + context.setUserSession(new UserSessionBase()); + RangerContextHolder.setSecurityContext(context); + UserSessionBase currentUserSession = ContextUtil.getCurrentUserSession(); + currentUserSession.setUserAdmin(true); + XXPortalUser xXPortalUser = new XXPortalUser(); + xXPortalUser.setLoginId(null); + xXPortalUser.setId(userId); + currentUserSession.setXXPortalUser(xXPortalUser); + xUserMgr.modifyUserActiveStatus(statusMap); + } + + @Test + public void test99createServiceConfigUser() { + XXUserDao xxUserDao = Mockito.mock(XXUserDao.class); + VXUser vxUser = vxUser(); + XXUser xXUser = xxUser(vxUser); + VXUserPermission vXUserPermission = vxUserPermission(); + XXUserPermission xUserPermissionObj = xxUserPermission(); + xUserPermissionObj.setModuleId(vXUserPermission.getModuleId()); + xUserPermissionObj.setUserId(vXUserPermission.getUserId()); + Mockito.when(daoManager.getXXUser()).thenReturn(xxUserDao); + Mockito.when(xxUserDao.findByUserName(vxUser.getName())).thenReturn(xXUser); + Mockito.when(xUserService.populateViewBean(xXUser)).thenReturn(vxUser); + VXUser serviceConfigUser = xUserMgr.createServiceConfigUser(vxUser.getName()); + Assert.assertNotNull(serviceConfigUser); + Assert.assertEquals(xXUser.getName(), serviceConfigUser.getName()); + Mockito.when(daoManager.getXXUser()).thenReturn(xxUserDao); + Mockito.when(xxUserDao.findByUserName(vxUser.getName())).thenReturn(null); + Mockito.when(daoManager.getXXUser()).thenReturn(xxUserDao); + UserSessionBase userSession = Mockito.mock(UserSessionBase.class); + Set userSessions = new HashSet<>(); + userSessions.add(userSession); + serviceConfigUser = xUserMgr.createServiceConfigUser(vxUser.getName()); + Assert.assertNull(serviceConfigUser); + } + + @Test + public void test100getStringListFromUserRoleList() { + destroySession(); + VXStringList vXStringList = xUserMgr.getStringListFromUserRoleList(null); + Assert.assertNull(vXStringList); + } + + @Test + public void test101getAdminUserDetailsWithUserHavingUSER_ROLE() { + destroySession(); + + RangerSecurityContext context = new RangerSecurityContext(); + context.setUserSession(new UserSessionBase()); + RangerContextHolder.setSecurityContext(context); + UserSessionBase currentUserSession = ContextUtil.getCurrentUserSession(); + currentUserSession.setUserAdmin(false); + XXPortalUser xXPortalUser = new XXPortalUser(); + xXPortalUser.setLoginId(userLoginID); + xXPortalUser.setId(userId); + currentUserSession.setXXPortalUser(xXPortalUser); + + VXUser loggedInUser = vxUser(); + List loggedInUserRole = new ArrayList<>(); + loggedInUserRole.add(RangerConstants.ROLE_USER); + loggedInUser.setId(8L); + loggedInUser.setName("testuser"); + loggedInUser.setUserRoleList(loggedInUserRole); + + VXUser vxUser = vxUser(); + List userRole = new ArrayList<>(); + userRole.add(RangerConstants.ROLE_ADMIN); + vxUser.setId(5L); + vxUser.setName("test3"); + vxUser.setUserRoleList(userRole); + vxUser.setUserSource(RangerCommonEnums.USER_UNIX); + Mockito.when(xUserService.readResourceWithOutLogin(5L)).thenReturn(vxUser); + Mockito.when(xUserService.getXUserByUserName("testuser")).thenReturn(loggedInUser); + Mockito.when(restErrorUtil.createRESTException(HttpServletResponse.SC_FORBIDDEN, "Logged-In user is not allowed to access requested user data", true)).thenThrow(new WebApplicationException()); + thrown.expect(WebApplicationException.class); + xUserMgr.getXUser(5L); + } + + @Test + public void test102getKeyAdminUserDetailsWithUserHavingUSER_ROLE() { + destroySession(); + + RangerSecurityContext context = new RangerSecurityContext(); + context.setUserSession(new UserSessionBase()); + RangerContextHolder.setSecurityContext(context); + UserSessionBase currentUserSession = ContextUtil.getCurrentUserSession(); + currentUserSession.setUserAdmin(false); + XXPortalUser xXPortalUser = new XXPortalUser(); + xXPortalUser.setLoginId(userLoginID); + xXPortalUser.setId(userId); + currentUserSession.setXXPortalUser(xXPortalUser); + + VXUser loggedInUser = vxUser(); + List loggedInUserRole = new ArrayList<>(); + loggedInUserRole.add(RangerConstants.ROLE_USER); + loggedInUser.setId(8L); + loggedInUser.setName("testuser"); + loggedInUser.setUserRoleList(loggedInUserRole); + + VXUser vxUser = vxUser(); + List userRole = new ArrayList<>(); + userRole.add(RangerConstants.ROLE_KEY_ADMIN); + vxUser.setId(5L); + vxUser.setName("test3"); + vxUser.setUserRoleList(userRole); + vxUser.setUserSource(RangerCommonEnums.USER_UNIX); + Mockito.when(xUserService.readResourceWithOutLogin(5L)).thenReturn(vxUser); + Mockito.when(xUserService.getXUserByUserName("testuser")).thenReturn(loggedInUser); + Mockito.when(restErrorUtil.createRESTException(HttpServletResponse.SC_FORBIDDEN, "Logged-In user is not allowed to access requested user data", true)).thenThrow(new WebApplicationException()); + thrown.expect(WebApplicationException.class); + xUserMgr.getXUser(5L); + } + + @Test + public void test103getAdminAuditorUserDetailsWithUserHavingUSER_ROLE() { + destroySession(); + + RangerSecurityContext context = new RangerSecurityContext(); + context.setUserSession(new UserSessionBase()); + RangerContextHolder.setSecurityContext(context); + UserSessionBase currentUserSession = ContextUtil.getCurrentUserSession(); + currentUserSession.setUserAdmin(false); + XXPortalUser xXPortalUser = new XXPortalUser(); + xXPortalUser.setLoginId(userLoginID); + xXPortalUser.setId(userId); + currentUserSession.setXXPortalUser(xXPortalUser); + + VXUser loggedInUser = vxUser(); + List loggedInUserRole = new ArrayList<>(); + loggedInUserRole.add(RangerConstants.ROLE_USER); + loggedInUser.setId(8L); + loggedInUser.setName("testuser"); + loggedInUser.setUserRoleList(loggedInUserRole); + + VXUser vxUser = vxUser(); + List userRole = new ArrayList<>(); + userRole.add(RangerConstants.ROLE_ADMIN_AUDITOR); + vxUser.setId(5L); + vxUser.setName("test3"); + vxUser.setUserRoleList(userRole); + vxUser.setUserSource(RangerCommonEnums.USER_UNIX); + Mockito.when(xUserService.readResourceWithOutLogin(5L)).thenReturn(vxUser); + Mockito.when(xUserService.getXUserByUserName("testuser")).thenReturn(loggedInUser); + Mockito.when(restErrorUtil.createRESTException(HttpServletResponse.SC_FORBIDDEN, "Logged-In user is not allowed to access requested user data", true)).thenThrow(new WebApplicationException()); + thrown.expect(WebApplicationException.class); + xUserMgr.getXUser(5L); + } + + @Test + public void test104getKeyAdminAuditorUserDetailsWithUserHavingUSER_ROLE() { + destroySession(); + + RangerSecurityContext context = new RangerSecurityContext(); + context.setUserSession(new UserSessionBase()); + RangerContextHolder.setSecurityContext(context); + UserSessionBase currentUserSession = ContextUtil.getCurrentUserSession(); + currentUserSession.setUserAdmin(false); + XXPortalUser xXPortalUser = new XXPortalUser(); + xXPortalUser.setLoginId(userLoginID); + xXPortalUser.setId(userId); + currentUserSession.setXXPortalUser(xXPortalUser); + + VXUser loggedInUser = vxUser(); + List loggedInUserRole = new ArrayList<>(); + loggedInUserRole.add(RangerConstants.ROLE_USER); + loggedInUser.setId(8L); + loggedInUser.setName("testuser"); + loggedInUser.setUserRoleList(loggedInUserRole); + + VXUser vxUser = vxUser(); + List userRole = new ArrayList<>(); + userRole.add(RangerConstants.ROLE_KEY_ADMIN_AUDITOR); + vxUser.setId(5L); + vxUser.setName("test3"); + vxUser.setUserRoleList(userRole); + vxUser.setUserSource(RangerCommonEnums.USER_UNIX); + Mockito.when(xUserService.readResourceWithOutLogin(5L)).thenReturn(vxUser); + Mockito.when(xUserService.getXUserByUserName("testuser")).thenReturn(loggedInUser); + Mockito.when(restErrorUtil.createRESTException(HttpServletResponse.SC_FORBIDDEN, "Logged-In user is not allowed to access requested user data", true)).thenThrow(new WebApplicationException()); + thrown.expect(WebApplicationException.class); + xUserMgr.getXUser(5L); + } + + @Test + public void test105getUserDetailsOfItsOwn() { + destroySession(); + + RangerSecurityContext context = new RangerSecurityContext(); + context.setUserSession(new UserSessionBase()); + RangerContextHolder.setSecurityContext(context); + UserSessionBase currentUserSession = ContextUtil.getCurrentUserSession(); + currentUserSession.setUserAdmin(false); + XXPortalUser xXPortalUser = new XXPortalUser(); + xXPortalUser.setLoginId(userLoginID); + xXPortalUser.setId(userId); + currentUserSession.setXXPortalUser(xXPortalUser); + List permissionList = new ArrayList<>(); + permissionList.add(RangerConstants.MODULE_USER_GROUPS); + + VXUser loggedInUser = vxUser(); + List loggedInUserRole = new ArrayList<>(); + loggedInUserRole.add(RangerConstants.ROLE_USER); + loggedInUser.setId(8L); + loggedInUser.setName("testuser"); + loggedInUser.setUserRoleList(loggedInUserRole); + + VXUser vxUser = vxUser(); + List userRole = new ArrayList<>(); + userRole.add(RangerConstants.ROLE_USER); + vxUser.setId(8L); + vxUser.setName("test3"); + vxUser.setUserRoleList(userRole); + vxUser.setUserSource(RangerCommonEnums.USER_UNIX); + Mockito.when(xUserService.readResourceWithOutLogin(8L)).thenReturn(vxUser); + Mockito.when(xUserService.getXUserByUserName("testuser")).thenReturn(loggedInUser); + XXModuleDefDao mockxxModuleDefDao = Mockito.mock(XXModuleDefDao.class); + Mockito.when(daoManager.getXXModuleDef()).thenReturn(mockxxModuleDefDao); + Mockito.when(mockxxModuleDefDao.findAccessibleModulesByUserId(8L, 8L)).thenReturn(permissionList); + VXUser expectedVXUser = xUserMgr.getXUser(8L); + Assert.assertNotNull(expectedVXUser); + Assert.assertEquals(expectedVXUser.getName(), vxUser.getName()); + destroySession(); + Mockito.when(restErrorUtil.createRESTException(HttpServletResponse.SC_FORBIDDEN, "Logged-In user is not allowed to access requested user data", true)).thenThrow(new WebApplicationException()); + thrown.expect(WebApplicationException.class); + xUserMgr.getXUser(8L); + } + + @Test + public void test106getErrorWhenRoleUserFetchAnotherUserGroupInfo() { + destroySession(); + + RangerSecurityContext context = new RangerSecurityContext(); + context.setUserSession(new UserSessionBase()); + RangerContextHolder.setSecurityContext(context); + UserSessionBase currentUserSession = ContextUtil.getCurrentUserSession(); + currentUserSession.setUserAdmin(false); + XXPortalUser xXPortalUser = new XXPortalUser(); + xXPortalUser.setLoginId(userLoginID); + xXPortalUser.setId(userId); + currentUserSession.setXXPortalUser(xXPortalUser); + List permissionList = new ArrayList<>(); + permissionList.add(RangerConstants.MODULE_USER_GROUPS); + + List groupIdList = new ArrayList<>(); + groupIdList.add(2L); + + VXUser loggedInUser = vxUser(); + List loggedInUserRole = new ArrayList<>(); + loggedInUserRole.add(RangerConstants.ROLE_USER); + loggedInUser.setId(8L); + loggedInUser.setName("testuser"); + loggedInUser.setUserRoleList(loggedInUserRole); + loggedInUser.setGroupIdList(groupIdList); + + VXUser vxUser = vxUser(); + List userRole = new ArrayList<>(); + userRole.add(RangerConstants.ROLE_USER); + vxUser.setId(8L); + vxUser.setName("test3"); + vxUser.setUserRoleList(userRole); + vxUser.setUserSource(RangerCommonEnums.USER_UNIX); + + Mockito.when(xUserService.getXUserByUserName("testuser")).thenReturn(loggedInUser); + + XXGroupUserDao mockxxGroupUserDao = Mockito.mock(XXGroupUserDao.class); + + Mockito.when(daoManager.getXXGroupUser()).thenReturn(mockxxGroupUserDao); + Mockito.when(mockxxGroupUserDao.findGroupIdListByUserId(loggedInUser.getId())).thenReturn(groupIdList); + + Mockito.when(restErrorUtil.create403RESTException("Logged-In user is not allowed to access requested group data.")).thenThrow(new WebApplicationException()); + thrown.expect(WebApplicationException.class); + xUserMgr.getXGroup(5L); + } + + @Test + public void test107RoleUserWillFetchOnlyHisOwnGroupDetails() { + destroySession(); + + RangerSecurityContext context = new RangerSecurityContext(); + context.setUserSession(new UserSessionBase()); + RangerContextHolder.setSecurityContext(context); + UserSessionBase currentUserSession = ContextUtil.getCurrentUserSession(); + currentUserSession.setUserAdmin(false); + XXPortalUser xXPortalUser = new XXPortalUser(); + xXPortalUser.setLoginId(userLoginID); + xXPortalUser.setId(userId); + currentUserSession.setXXPortalUser(xXPortalUser); + List permissionList = new ArrayList<>(); + permissionList.add(RangerConstants.MODULE_USER_GROUPS); + + List groupIdList = new ArrayList<>(); + groupIdList.add(5L); + + VXGroup expectedVXGroup = new VXGroup(); + expectedVXGroup.setId(5L); + expectedVXGroup.setName("testGroup"); + + VXUser loggedInUser = vxUser(); + List loggedInUserRole = new ArrayList<>(); + loggedInUserRole.add(RangerConstants.ROLE_USER); + loggedInUser.setId(8L); + loggedInUser.setName("testuser"); + loggedInUser.setUserRoleList(loggedInUserRole); + loggedInUser.setGroupIdList(groupIdList); + + VXUser vxUser = vxUser(); + List userRole = new ArrayList<>(); + userRole.add(RangerConstants.ROLE_USER); + vxUser.setId(8L); + vxUser.setName("test3"); + vxUser.setUserRoleList(userRole); + vxUser.setUserSource(RangerCommonEnums.USER_UNIX); + Mockito.when(xGroupService.readResourceWithOutLogin(5L)).thenReturn(expectedVXGroup); + + VXGroup rcvVXGroup = xUserMgr.getXGroup(5L); + Assert.assertNotNull(rcvVXGroup); + Assert.assertEquals(expectedVXGroup.getId(), rcvVXGroup.getId()); + Assert.assertEquals(expectedVXGroup.getName(), rcvVXGroup.getName()); + } + + @Test + public void test108RoleUserWillSearchOnlyHisOwnGroupDetails() { + destroySession(); + + RangerSecurityContext context = new RangerSecurityContext(); + context.setUserSession(new UserSessionBase()); + RangerContextHolder.setSecurityContext(context); + UserSessionBase currentUserSession = ContextUtil.getCurrentUserSession(); + currentUserSession.setUserAdmin(false); + XXPortalUser xXPortalUser = new XXPortalUser(); + xXPortalUser.setLoginId(userLoginID); + xXPortalUser.setId(userId); + currentUserSession.setXXPortalUser(xXPortalUser); + List permissionList = new ArrayList<>(); + permissionList.add(RangerConstants.MODULE_USER_GROUPS); + + SearchCriteria testSearchCriteria = createsearchCriteria(); + + List groupIdList = new ArrayList<>(); + groupIdList.add(5L); + + VXGroup expectedVXGroup = new VXGroup(); + expectedVXGroup.setId(5L); + expectedVXGroup.setName("testGroup"); + + List grpList = new ArrayList<>(); + grpList.add(expectedVXGroup); + + VXGroupList expectedVXGroupList = new VXGroupList(); + expectedVXGroupList.setVXGroups(grpList); + + VXUser loggedInUser = vxUser(); + List loggedInUserRole = new ArrayList<>(); + loggedInUserRole.add(RangerConstants.ROLE_USER); + loggedInUser.setId(8L); + loggedInUser.setName("testuser"); + loggedInUser.setUserRoleList(loggedInUserRole); + loggedInUser.setGroupIdList(groupIdList); + + VXUser vxUser = vxUser(); + List userRole = new ArrayList<>(); + userRole.add(RangerConstants.ROLE_USER); + vxUser.setId(8L); + vxUser.setName("test3"); + vxUser.setUserRoleList(userRole); + vxUser.setUserSource(RangerCommonEnums.USER_UNIX); + Mockito.when(xUserService.getXUserByUserName("testuser")).thenReturn(loggedInUser); + Mockito.when(xGroupService.searchXGroups(testSearchCriteria)).thenReturn(expectedVXGroupList); + XXModuleDefDao mockxxModuleDefDao = Mockito.mock(XXModuleDefDao.class); + Mockito.when(daoManager.getXXModuleDef()).thenReturn(mockxxModuleDefDao); + Mockito.when(mockxxModuleDefDao.findAccessibleModulesByUserId(8L, 8L)).thenReturn(permissionList); + + VXGroupList rcvVXGroupList = xUserMgr.searchXGroups(testSearchCriteria); + Assert.assertNotNull(rcvVXGroupList); + + Assert.assertEquals(rcvVXGroupList.getList().get(0).getId(), expectedVXGroup.getId()); + Assert.assertEquals(rcvVXGroupList.getList().get(0).getName(), expectedVXGroup.getName()); + } + + @Test + public void test109AssignPermissionToUser() { + destroySession(); + setup(); + VXPortalUser vXPortalUser = userProfile(); + List xXModuleDefs = xxModuleDefs(); + XXModuleDefDao xXModuleDefDao = Mockito.mock(XXModuleDefDao.class); + Mockito.when(daoManager.getXXModuleDef()).thenReturn(xXModuleDefDao); + Mockito.when(daoManager.getXXModuleDef().getAll()).thenReturn(xXModuleDefs); + + VXUserPermission userPermission = vxUserPermission(); + List userPermList = new ArrayList<>(); + userPermList.add(userPermission); + List xUserPermissionsList = new ArrayList<>(); + XXUserPermission xUserPermission = xxUserPermission(); + xUserPermission.setModuleId(userPermission.getModuleId()); + xUserPermission.setUserId(userPermission.getUserId()); + xUserPermissionsList.add(xUserPermission); + + XXUserPermissionDao xXUserPermissionDao = Mockito.mock(XXUserPermissionDao.class); + Mockito.when(daoManager.getXXUserPermission()).thenReturn(xXUserPermissionDao); + Mockito.when(xXUserPermissionDao.findByModuleIdAndPortalUserId(vXPortalUser.getId(), xXModuleDefs.get(0).getId())).thenReturn(xUserPermission); + + VXUser vxUser = vxUser(); + XXUser xXUser = xxUser(vxUser); + XXUserDao xxUserDao = Mockito.mock(XXUserDao.class); + Mockito.when(daoManager.getXXUser()).thenReturn(xxUserDao); + Mockito.when(xxUserDao.findByPortalUserId(vXPortalUser.getId())).thenReturn(xXUser); + + Mockito.when(xUserPermissionService.populateViewBean(xUserPermission)).thenReturn(userPermission); + + Mockito.when(xUserPermissionService.createResource(Mockito.any())).thenReturn(userPermission); + Mockito.when(xUserPermissionService.updateResource(Mockito.any())).thenReturn(userPermission); + UserSessionBase userSession = Mockito.mock(UserSessionBase.class); + Set userSessions = new HashSet<>(); + userSessions.add(userSession); + Mockito.when(sessionMgr.getActiveUserSessionsForPortalUserId(userId)).thenReturn(userSessions); + + Collection existingRoleList = new ArrayList<>(); + existingRoleList.add(RangerConstants.ROLE_SYS_ADMIN); + vXPortalUser.setUserRoleList(existingRoleList); + xUserMgr.assignPermissionToUser(vXPortalUser, true); + existingRoleList.clear(); + existingRoleList.add(RangerConstants.ROLE_KEY_ADMIN); + vXPortalUser.setUserRoleList(existingRoleList); + xUserMgr.assignPermissionToUser(vXPortalUser, true); + existingRoleList.clear(); + existingRoleList.add(RangerConstants.ROLE_KEY_ADMIN_AUDITOR); + vXPortalUser.setUserRoleList(existingRoleList); + xUserMgr.assignPermissionToUser(vXPortalUser, true); + existingRoleList.clear(); + existingRoleList.add(RangerConstants.ROLE_ADMIN_AUDITOR); + vXPortalUser.setUserRoleList(existingRoleList); + xUserMgr.assignPermissionToUser(vXPortalUser, true); + } + + @Test + public void test110CreateOrDeleteXGroupUserList() { + destroySession(); + setup(); + GroupUserInfo groupUserInfo = new GroupUserInfo(); + groupUserInfo.setGroupName("public"); + Set addUsers = new HashSet<>(); + Set delUsers = new HashSet<>(); + addUsers.add("testuser1"); + addUsers.add("testuser2"); + delUsers.add("testuser3"); + groupUserInfo.setAddUsers(addUsers); + groupUserInfo.setDelUsers(delUsers); + List groupUserInfoList = new ArrayList<>(); + groupUserInfoList.add(groupUserInfo); + Map usersFromDB = new HashMap<>(); + usersFromDB.put("testuser1", 1L); + usersFromDB.put("testuser2", 2L); + XXUserDao xxUserDao = Mockito.mock(XXUserDao.class); + Mockito.when(daoManager.getXXUser()).thenReturn(xxUserDao); + Mockito.when(xxUserDao.getAllUserIds()).thenReturn(usersFromDB); + xUserMgr.createOrDeleteXGroupUserList(groupUserInfoList); + } + + @Test + public void test111CreateOrUpdateXUsers() { + destroySession(); + setup(); + List vXUserList = new ArrayList<>(); + VXUser vXUser = vxUser(); + VXUser vXUser1 = vxUser(); + VXUser vXUser2 = vxUser(); + vXUser2.setFirstName("user12"); + vXUser2.setEmailAddress(null); + vXUser.setFirstName("null"); + vXUser.setLastName("null"); + vXUser.setEmailAddress(""); + vXUser1.setName("null"); + Collection userRoleList = new ArrayList<>(); + userRoleList.add(RangerConstants.ROLE_USER); + userRoleList.add(RangerConstants.ROLE_SYS_ADMIN); + userRoleList.add(RangerConstants.ROLE_KEY_ADMIN); + userRoleList.add(RangerConstants.ROLE_KEY_ADMIN_AUDITOR); + userRoleList.add(RangerConstants.ROLE_ADMIN_AUDITOR); + vXUser.setUserRoleList(userRoleList); + vXUser1.setUserRoleList(userRoleList); + vXUser2.setUserRoleList(userRoleList); + vXUserList.add(vXUser); + vXUserList.add(vXUser1); + vXUserList.add(vXUser2); + VXUserList users = new VXUserList(vXUserList); + XXUserDao xxUserDao = Mockito.mock(XXUserDao.class); + XXPortalUserDao userDao = Mockito.mock(XXPortalUserDao.class); + XXModuleDefDao xXModuleDefDao = Mockito.mock(XXModuleDefDao.class); + XXUser xXUser = xxUser(vXUser); + VXPortalUser vXPortalUser = userProfile(); + vXPortalUser.setFirstName("null"); + vXPortalUser.setLastName("null"); + XXPortalUser xXPortalUser = xxPortalUser(vXPortalUser); + xXPortalUser.setUserSource(RangerCommonEnums.USER_EXTERNAL); + List lstRole = new ArrayList<>(); + lstRole.add(RangerConstants.ROLE_SYS_ADMIN); + List xXModuleDefs = xxModuleDefs(); + + vXPortalUser.setUserRoleList(lstRole); + Mockito.when(userMgr.getUserProfileByLoginId(vXUser.getName())).thenReturn(null); + + Mockito.when(daoManager.getXXUser()).thenReturn(xxUserDao); + Mockito.when(xxUserDao.findByUserName(vXUser.getName())).thenReturn(xXUser); + Mockito.when(daoManager.getXXPortalUser()).thenReturn(userDao); + Mockito.when(daoManager.getXXModuleDef()).thenReturn(xXModuleDefDao); + Mockito.when(xXModuleDefDao.getAll()).thenReturn(xXModuleDefs); + + Mockito.when(userMgr.mapVXPortalUserToXXPortalUser(Mockito.any())).thenReturn(xXPortalUser); + XXPortalUserDao xXPortalUserDao = Mockito.mock(XXPortalUserDao.class); + Mockito.when(daoManager.getXXPortalUser()).thenReturn(xXPortalUserDao); + Mockito.when(daoManager.getXXPortalUser().create(Mockito.any())).thenReturn(xXPortalUser); + XXUser xUser = xxUser(vXUser); + Mockito.when(daoManager.getXXUser()).thenReturn(xxUserDao); + Mockito.when(daoManager.getXXUser().findByUserName(vXUser.getName())).thenReturn(xUser); + Mockito.when(xUserService.populateViewBean(xUser)).thenReturn(vXUser); + + VXUserPermission userPermission = vxUserPermission(); + List userPermList = new ArrayList<>(); + userPermList.add(userPermission); + + List xUserPermissionsList = new ArrayList<>(); + XXUserPermission xUserPermissionObj = xxUserPermission(); + xUserPermissionObj.setModuleId(userPermission.getModuleId()); + xUserPermissionObj.setUserId(userPermission.getUserId()); + xUserPermissionsList.add(xUserPermissionObj); + + XXUserPermissionDao xUserPermissionDao = Mockito.mock(XXUserPermissionDao.class); + Mockito.when(daoManager.getXXUserPermission()).thenReturn(xUserPermissionDao); + UserSessionBase userSession = Mockito.mock(UserSessionBase.class); + Set userSessions = new HashSet<>(); + userSessions.add(userSession); + + Mockito.when(xUserPermissionService.createResource(Mockito.any())).thenReturn(userPermission); + Mockito.when(sessionMgr.getActiveUserSessionsForPortalUserId(userId)).thenReturn(userSessions); + Mockito.when(xUserPermissionDao.findByModuleIdAndPortalUserId(null, null)).thenReturn(xUserPermissionObj); + Mockito.when(xUserPermissionService.populateViewBean(xUserPermissionObj)).thenReturn(userPermission); + Mockito.when(xUserPermissionService.updateResource(Mockito.any())).thenReturn(userPermission); + Mockito.when(daoManager.getXXPortalUser()).thenReturn(xXPortalUserDao); + VXUser loggedInUser = vxUser(); + List loggedInUserRole = new ArrayList<>(); + loggedInUserRole.add(RangerConstants.ROLE_SYS_ADMIN); + loggedInUser.setId(8L); + loggedInUser.setName("testuser"); + loggedInUser.setUserRoleList(loggedInUserRole); + Mockito.when(xUserService.getXUserByUserName("admin")).thenReturn(loggedInUser); + int createdOrUpdatedUserCount = xUserMgr.createOrUpdateXUsers(users); + Assert.assertEquals(1, createdOrUpdatedUserCount); + } + + @Test + public void test112CreateOrUpdateXUsers() { + destroySession(); + setup(); + List vXUserList = new ArrayList<>(); + VXUser vXUser = vxUser(); + vXUser.setFirstName("testuser"); + vXUser.setLastName("testuser"); + vXUser.setPassword("TestPassword@123"); + vXUser.setEmailAddress(""); + vXUser.setUserSource(RangerCommonEnums.USER_APP); + Collection userRoleList = new ArrayList<>(); + userRoleList.add(RangerConstants.ROLE_USER); + userRoleList.add(RangerConstants.ROLE_SYS_ADMIN); + userRoleList.add(RangerConstants.ROLE_KEY_ADMIN); + userRoleList.add(RangerConstants.ROLE_KEY_ADMIN_AUDITOR); + userRoleList.add(RangerConstants.ROLE_ADMIN_AUDITOR); + vXUser.setUserRoleList(userRoleList); + vXUserList.add(vXUser); + VXUserList users = new VXUserList(vXUserList); + + VXPortalUser vXPortalUser = userProfile(); + vXPortalUser.setFirstName("testuser"); + vXPortalUser.setLastName("testuser"); + vXPortalUser.setPassword("TestPassword@123"); + XXPortalUser xXPortalUser = xxPortalUser(vXPortalUser); + List xXModuleDefs = xxModuleDefs(); + List xUserPermissionsList = new ArrayList<>(); + XXUserPermission xUserPermissionObj = xxUserPermission(); + VXUserPermission userPermission = vxUserPermission(); + List userPermList = new ArrayList<>(); + userPermList.add(userPermission); + xUserPermissionObj.setModuleId(userPermission.getModuleId()); + xUserPermissionObj.setUserId(userPermission.getUserId()); + xUserPermissionsList.add(xUserPermissionObj); + UserSessionBase userSession = Mockito.mock(UserSessionBase.class); + Set userSessions = new HashSet<>(); + userSessions.add(userSession); + + XXUserDao xxUserDao = Mockito.mock(XXUserDao.class); + XXPortalUserDao userDao = Mockito.mock(XXPortalUserDao.class); + XXModuleDefDao xXModuleDefDao = Mockito.mock(XXModuleDefDao.class); + XXUserPermissionDao xUserPermissionDao = Mockito.mock(XXUserPermissionDao.class); + + Mockito.when(daoManager.getXXUser()).thenReturn(xxUserDao); + Mockito.when(daoManager.getXXPortalUser()).thenReturn(userDao); + Mockito.when(daoManager.getXXPortalUser().create(Mockito.any())).thenReturn(xXPortalUser); + Mockito.when(daoManager.getXXModuleDef()).thenReturn(xXModuleDefDao); + Mockito.when(xXModuleDefDao.getAll()).thenReturn(xXModuleDefs); + Mockito.when(daoManager.getXXUserPermission()).thenReturn(xUserPermissionDao); + Mockito.when(xUserPermissionDao.findByModuleIdAndPortalUserId(null, null)).thenReturn(xUserPermissionObj); + Mockito.when(xUserPermissionService.createResource(Mockito.any())).thenReturn(userPermission); + Mockito.when(sessionMgr.getActiveUserSessionsForPortalUserId(userId)).thenReturn(userSessions); + Mockito.when(xUserService.createResource(Mockito.any())).thenReturn(vXUser); + Mockito.when(xUserPermissionService.populateViewBean(xUserPermissionObj)).thenReturn(userPermission); + Mockito.when(xUserPermissionService.updateResource(Mockito.any())).thenReturn(userPermission); + Mockito.when(daoManager.getXXPortalUser()).thenReturn(userDao); + VXUser loggedInUser = vxUser(); + List loggedInUserRole = new ArrayList<>(); + loggedInUserRole.add(RangerConstants.ROLE_SYS_ADMIN); + loggedInUser.setId(8L); + loggedInUser.setName("testuser"); + loggedInUser.setUserRoleList(loggedInUserRole); + Mockito.when(xUserService.getXUserByUserName("admin")).thenReturn(loggedInUser); + xUserMgr.createOrUpdateXUsers(users); + + vXUser.setPassword("*****"); + xUserMgr.createOrUpdateXUsers(users); + } + + @Test + public void test113CreateOrUpdateXUsers() { + destroySession(); + setup(); + VXUser vXUser = vxUser(); + vXUser.setFirstName("null"); + vXUser.setLastName("null"); + List vXUserList = new ArrayList<>(); + vXUserList.add(vXUser); + VXUserList users = new VXUserList(vXUserList); + XXUserDao xxUserDao = Mockito.mock(XXUserDao.class); + XXModuleDefDao xXModuleDefDao = Mockito.mock(XXModuleDefDao.class); + XXUser xXUser = xxUser(vXUser); + VXPortalUser vXPortalUser = userProfile(); + vXPortalUser.setFirstName("null"); + vXPortalUser.setLastName("null"); + XXPortalUser xXPortalUser = xxPortalUser(vXPortalUser); + xXPortalUser.setUserSource(RangerCommonEnums.USER_EXTERNAL); + List lstRole = new ArrayList<>(); + lstRole.add(RangerConstants.ROLE_SYS_ADMIN); + List xXModuleDefs = new ArrayList<>(); + + vXPortalUser.setUserRoleList(lstRole); + Mockito.when(userMgr.getUserProfileByLoginId(vXUser.getName())).thenReturn(vXPortalUser); + + Mockito.when(daoManager.getXXUser()).thenReturn(xxUserDao); + Mockito.when(xxUserDao.findByUserName(vXUser.getName())).thenReturn(xXUser); + Mockito.when(daoManager.getXXModuleDef()).thenReturn(xXModuleDefDao); + Mockito.when(xXModuleDefDao.getAll()).thenReturn(xXModuleDefs); + Mockito.when(xUserService.updateResource(vXUser)).thenReturn(vXUser); + + XXUserPermissionDao xUserPermissionDao = Mockito.mock(XXUserPermissionDao.class); + Mockito.when(daoManager.getXXUserPermission()).thenReturn(xUserPermissionDao); + List xUserPermissionsList = new ArrayList<>(); + XXUserPermission xUserPermissionObj = new XXUserPermission(); + xUserPermissionObj.setAddedByUserId(userId); + xUserPermissionObj.setCreateTime(new Date()); + xUserPermissionObj.setId(userId); + xUserPermissionObj.setIsAllowed(1); + xUserPermissionObj.setModuleId(1L); + xUserPermissionObj.setUpdatedByUserId(userId); + xUserPermissionObj.setUpdateTime(new Date()); + xUserPermissionObj.setUserId(userId); + xUserPermissionsList.add(xUserPermissionObj); + Mockito.when(xUserPermissionDao.findByUserPermissionId(vXPortalUser.getId())).thenReturn(xUserPermissionsList); + VXUser loggedInUser = vxUser(); + List loggedInUserRole = new ArrayList<>(); + loggedInUserRole.add(RangerConstants.ROLE_SYS_ADMIN); + loggedInUser.setId(8L); + loggedInUser.setName("testuser"); + loggedInUser.setUserRoleList(loggedInUserRole); + Mockito.when(xUserService.getXUserByUserName("admin")).thenReturn(loggedInUser); + xUserMgr.createOrUpdateXUsers(users); + vXUserList.clear(); + vXUser.setUserSource(RangerCommonEnums.USER_APP); + vXUser.setFirstName("testuser"); + vXUser.setLastName("testuser"); + vXUser.setPassword("TestPassword@123"); + vXUserList.add(vXUser); + users = new VXUserList(vXUserList); + vXPortalUser = userProfile(); + vXPortalUser.setUserSource(RangerCommonEnums.USER_APP); + vXPortalUser.setFirstName("testuser"); + vXPortalUser.setLastName("testuser"); + vXPortalUser.setPassword("TestPassword@123"); + vXPortalUser.setUserRoleList(lstRole); + Mockito.when(userMgr.getUserProfileByLoginId(vXUser.getName())).thenReturn(vXPortalUser); + Mockito.when(userMgr.updateUserWithPass(Mockito.any())).thenReturn(xXPortalUser); + xUserMgr.createOrUpdateXUsers(users); + vXUser.setPassword("*****"); + xUserMgr.createOrUpdateXUsers(users); + } + + @Test + public void test114CreateOrUpdateXGroups() { + destroySession(); + setup(); + VXGroup vXGroup = vxGroup(); + VXGroupList vXGroupListSort = new VXGroupList(); + List vXGroups = new ArrayList<>(); + vXGroups.add(vXGroup); + VXGroup vXGroup1 = vxGroup(); + vXGroup1.setName("null"); + vXGroups.add(vXGroup1); + vXGroupListSort.setVXGroups(vXGroups); + + VXUser vXUser = vxUser(); + List vXUserList = new ArrayList<>(); + vXUserList.add(vXUser); + VXPortalUser vXPortalUser = userProfile(); + XXPortalUser xXPortalUser = xxPortalUser(vXPortalUser); + xXPortalUser.setUserSource(RangerCommonEnums.USER_EXTERNAL); + List lstRole = new ArrayList<>(); + lstRole.add(RangerConstants.ROLE_SYS_ADMIN); + + vXPortalUser.setUserRoleList(lstRole); + + List xUserPermissionsList = new ArrayList<>(); + XXUserPermission xUserPermissionObj = new XXUserPermission(); + xUserPermissionObj.setAddedByUserId(userId); + xUserPermissionObj.setCreateTime(new Date()); + xUserPermissionObj.setId(userId); + xUserPermissionObj.setIsAllowed(1); + xUserPermissionObj.setModuleId(1L); + xUserPermissionObj.setUpdatedByUserId(userId); + xUserPermissionObj.setUpdateTime(new Date()); + xUserPermissionObj.setUserId(userId); + xUserPermissionsList.add(xUserPermissionObj); + xUserMgr.createOrUpdateXGroups(vXGroupListSort); + } + + @Test + public void test115UpdateUserRoleAssignments() { + destroySession(); + setup(); + UsersGroupRoleAssignments ugRoleAssignments = new UsersGroupRoleAssignments(); + Set addUsers = new HashSet<>(); + Set delUsers = new HashSet<>(); + addUsers.add("testuser"); + addUsers.add("testuser2"); + delUsers.add("testuser2"); + Map userMap = new HashMap<>(); + Map groupMap = new HashMap<>(); + List allUsers = new ArrayList<>(addUsers); + userMap.put("testuser", "role1"); + userMap.put("testuser2", "role2"); + groupMap.put("testgroup1", "role1"); + groupMap.put("testgroup2", "role2"); + ugRoleAssignments.setUsers(allUsers); + ugRoleAssignments.setGroupRoleAssignments(groupMap); + ugRoleAssignments.setUserRoleAssignments(userMap); + ugRoleAssignments.setWhiteListUserRoleAssignments(new HashMap<>()); + ugRoleAssignments.setWhiteListGroupRoleAssignments(new HashMap<>()); + VXUser vXUser = vxUser(); + List vXUserList = new ArrayList<>(); + vXUserList.add(vXUser); + VXPortalUser vXPortalUser = userProfile(); + XXPortalUser xXPortalUser = xxPortalUser(vXPortalUser); + xXPortalUser.setUserSource(RangerCommonEnums.USER_EXTERNAL); + List lstRole = new ArrayList<>(); + lstRole.add(RangerConstants.ROLE_SYS_ADMIN); + vXPortalUser.setUserRoleList(lstRole); + Mockito.when(userMgr.getUserProfileByLoginId(vXUser.getName())).thenReturn(vXPortalUser); + + XXUserPermissionDao xUserPermissionDao = Mockito.mock(XXUserPermissionDao.class); + Mockito.when(daoManager.getXXUserPermission()).thenReturn(xUserPermissionDao); + List xUserPermissionsList = new ArrayList<>(); + XXUserPermission xUserPermissionObj = new XXUserPermission(); + xUserPermissionObj.setAddedByUserId(userId); + xUserPermissionObj.setCreateTime(new Date()); + xUserPermissionObj.setId(userId); + xUserPermissionObj.setIsAllowed(1); + xUserPermissionObj.setModuleId(1L); + xUserPermissionObj.setUpdatedByUserId(userId); + xUserPermissionObj.setUpdateTime(new Date()); + xUserPermissionObj.setUserId(userId); + xUserPermissionsList.add(xUserPermissionObj); + Mockito.when(xUserPermissionDao.findByUserPermissionId(vXPortalUser.getId())).thenReturn(xUserPermissionsList); + + List xXModuleDefs = xxModuleDefs(); + XXModuleDefDao xXModuleDefDao = Mockito.mock(XXModuleDefDao.class); + Mockito.when(daoManager.getXXModuleDef()).thenReturn(xXModuleDefDao); + Mockito.when(daoManager.getXXModuleDef().getAll()).thenReturn(xXModuleDefs); + xUserMgr.updateUserRoleAssignments(ugRoleAssignments); + + allUsers.clear(); + allUsers.add("UnMappedUser"); + ugRoleAssignments.setUsers(allUsers); + ugRoleAssignments.setGroupRoleAssignments(groupMap); + ugRoleAssignments.setUserRoleAssignments(userMap); + + VXUserPermission userPermission = vxUserPermission(); + List userPermList = new ArrayList<>(); + userPermList.add(userPermission); + List xUserPermissionsList1 = new ArrayList<>(); + XXUserPermission xUserPermissionObj1 = xxUserPermission(); + xUserPermissionObj1.setModuleId(userPermission.getModuleId()); + xUserPermissionObj1.setUserId(userPermission.getUserId()); + xUserPermissionsList1.add(xUserPermissionObj1); + UserSessionBase userSession = Mockito.mock(UserSessionBase.class); + Set userSessions = new HashSet<>(); + userSessions.add(userSession); + xUserMgr.updateUserRoleAssignments(ugRoleAssignments); + + vXPortalUser.setUserSource(RangerCommonEnums.USER_APP); + Mockito.when(userMgr.getUserProfileByLoginId(Mockito.anyString())).thenReturn(vXPortalUser); + xUserMgr.updateUserRoleAssignments(ugRoleAssignments); + } + + @Test + public void test116GetGroups() { + destroySession(); + setup(); + VXGroup vXGroup = vxGroup(); + XXGroup xxGroup = new XXGroup(); + xxGroup.setId(vXGroup.getId()); + xxGroup.setName(vXGroup.getName()); + xxGroup.setDescription(vXGroup.getDescription()); + xxGroup.setIsVisible(vXGroup.getIsVisible()); + List resultList = new ArrayList<>(); + resultList.add(xxGroup); + xUserMgr.getGroups(); + } + + @Test + public void test117GetUserGroups() { + destroySession(); + setup(); + String user = "testuser1"; + Set userGroups = new HashSet<>(); + userGroups.add("group1"); + Map> userGroupMap = new HashMap<>(); + userGroupMap.put(user, userGroups); + XXUserDao xxUserDao = Mockito.mock(XXUserDao.class); + Mockito.when(daoManager.getXXUser()).thenReturn(xxUserDao); + Mockito.when(xxUserDao.findGroupsByUserIds()).thenReturn(userGroupMap); + Map> userGroupMap1 = xUserMgr.getUserGroups(); + Assert.assertNotNull(userGroupMap1); + Assert.assertEquals(userGroupMap, userGroupMap1); + } + + @Test + public void test118GetUsers() { + destroySession(); + setup(); + VXUser vXUser = vxUser(); + UserInfo userInfo = new UserInfo(vXUser.getName(), vXUser.getDescription(), null); + Set userInfoSet = new HashSet<>(); + userInfoSet.add(userInfo); + List userInfoList = new ArrayList<>(); + userInfoList.add(userInfo); + XXUser xxUser = xxUser(vXUser); + List resultList = new ArrayList<>(); + resultList.add(xxUser); + Set userInfoSet1 = xUserMgr.getUsers(); + Assert.assertNotNull(userInfoSet1); + Mockito.when(xUserService.getUsers()).thenReturn(userInfoList); + Set userInfoSet2 = xUserMgr.getUsers(); + Assert.assertNotNull(userInfoSet2); + Assert.assertEquals(userInfoSet, userInfoSet2); + } + + @Test + public void test119GetRangerUserStore() throws Exception { + destroySession(); + setup(); + Long lastKnownUserStoreVersion = Long.valueOf(1); + Mockito.when(xxGlobalStateDao.getAppDataVersion(RANGER_USER_GROUP_GLOBAL_STATE_NAME)).thenReturn(lastKnownUserStoreVersion); + Map> userGroupMap = new HashMap<>(); + XXUserDao xxUserDao = Mockito.mock(XXUserDao.class); + Mockito.when(daoManager.getXXUser()).thenReturn(xxUserDao); + Mockito.when(xxUserDao.findGroupsByUserIds()).thenReturn(userGroupMap); + xUserMgr.getRangerUserStoreIfUpdated(lastKnownUserStoreVersion); + } + + @Test + public void test120GetUserStoreVersion() { + destroySession(); + setup(); + Long lastKnownUserStoreVersion = Long.valueOf(1); + Mockito.when(xxGlobalStateDao.getAppDataVersion(RANGER_USER_GROUP_GLOBAL_STATE_NAME)).thenReturn(lastKnownUserStoreVersion); + Long userStoreVersion = xUserMgr.getUserStoreVersion(); + Assert.assertNotNull(userStoreVersion); + Assert.assertEquals(lastKnownUserStoreVersion, userStoreVersion); + } + + @Test + public void test121UpdateDeletedUsers() { + destroySession(); + setup(); + XXUserDao xxUserDao = Mockito.mock(XXUserDao.class); + VXUser vxUser = vxUser(); + XXUser xXUser = xxUser(vxUser); + Set delUsers = new HashSet<>(); + delUsers.add(vxUser.getName()); + Mockito.when(daoManager.getXXUser()).thenReturn(xxUserDao); + Mockito.when(xxUserDao.findByUserName(vxUser.getName())).thenReturn(xXUser); + Mockito.when(xUserService.populateViewBean(xXUser)).thenReturn(vxUser); + Mockito.when(xUserService.updateResource(vxUser)).thenReturn(vxUser); + int count = xUserMgr.updateDeletedUsers(delUsers); + Assert.assertNotNull(count); + Assert.assertEquals(1, count); + } + + @Test + public void test122UpdateDeletedGroups() { + destroySession(); + setup(); + XXGroupDao xxGroupDao = Mockito.mock(XXGroupDao.class); + VXGroup vxGroup = vxGroup(); + XXGroup xxGroup = new XXGroup(); + xxGroup.setId(vxGroup.getId()); + xxGroup.setName(vxGroup.getName()); + xxGroup.setDescription(vxGroup.getDescription()); + xxGroup.setIsVisible(vxGroup.getIsVisible()); + Set delGroups = new HashSet<>(); + delGroups.add(vxGroup.getName()); + Mockito.when(daoManager.getXXGroup()).thenReturn(xxGroupDao); + Mockito.when(xxGroupDao.findByGroupName(vxGroup.getName())).thenReturn(xxGroup); + Mockito.when(xGroupService.populateViewBean(xxGroup)).thenReturn(vxGroup); + Mockito.when(xGroupService.updateResource(vxGroup)).thenReturn(vxGroup); + int count = xUserMgr.updateDeletedGroups(delGroups); + Assert.assertNotNull(count); + Assert.assertEquals(1, count); + } + + @Test + public void test123LookupXGroups() { + destroySession(); + setup(); + VXGroup vXGroup = vxGroup(); + VXGroupList vXGroupListSort = new VXGroupList(); + List vXGroups = new ArrayList<>(); + vXGroups.add(vXGroup); + vXGroupListSort.setVXGroups(vXGroups); + String groupName = vXGroup.getName(); + SearchCriteria testSearchCriteria = createsearchCriteria(); + testSearchCriteria.addParam("name", groupName); + Mockito.when(xGroupService.getGroupByGroupName(groupName)).thenReturn(vXGroup); + Mockito.when(xGroupService.searchXGroups(Mockito.any())).thenReturn(vXGroupListSort); + VXGroupList vXGroupList = xUserMgr.searchXGroups(testSearchCriteria); + testSearchCriteria.addParam("isvisible", "true"); + vXGroupList = xUserMgr.lookupXGroups(testSearchCriteria); + Assert.assertNotNull(vXGroupList); + testSearchCriteria = createsearchCriteria(); + testSearchCriteria.addParam("name", groupName); + testSearchCriteria.addParam("groupsource", 1L); + vXGroupList = xUserMgr.lookupXGroups(testSearchCriteria); + Assert.assertNotNull(vXGroupList); + testSearchCriteria = createsearchCriteria(); + testSearchCriteria.setSortBy(""); + testSearchCriteria.addParam("name", groupName); + Mockito.when(xGroupService.getGroupByGroupName(Mockito.anyString())).thenReturn(vXGroup); + vXGroupList = xUserMgr.lookupXGroups(testSearchCriteria); + Assert.assertNotNull(vXGroupList); + + SearchCriteria emptyCriteria = new SearchCriteria(); + Mockito.when(xGroupService.searchXGroups(Mockito.any())).thenReturn(null); + vXGroupList = xUserMgr.lookupXGroups(emptyCriteria); + Assert.assertNull(vXGroupList); + } + + @Test + public void test124LookupXUsers() { + destroySession(); + setup(); + VXUser vXUser = vxUser(); + VXUserList vXUserList1 = new VXUserList(); + List vXUsers = new ArrayList<>(); + vXUsers.add(vXUser); + vXUserList1.setVXUsers(vXUsers); + String groupName = vXUser.getName(); + SearchCriteria searchCriteria = createsearchCriteria(); + searchCriteria.addParam("name", groupName); + searchCriteria.addParam("isvisible", "true"); + Mockito.when(xUserService.lookupXUsers(Mockito.any(), Mockito.any())).thenReturn(vXUserList1); + VXUserList vXUserList2 = xUserMgr.lookupXUsers(searchCriteria); + Assert.assertNotNull(vXUserList2); + Assert.assertEquals(vXUserList1, vXUserList2); + searchCriteria.setSortBy(""); + vXUserList2 = xUserMgr.lookupXUsers(searchCriteria); + Assert.assertNotNull(vXUserList2); + Assert.assertEquals(vXUserList1, vXUserList2); + } + + @Test + public void test125DeleteXUser() { + destroySession(); + setup(); + boolean force = true; + VXUser vXUser = vxUser(); + XXUser xXUser = new XXUser(); + XXUserDao xXUserDao = Mockito.mock(XXUserDao.class); + Mockito.when(daoManager.getXXUser()).thenReturn(xXUserDao); + Mockito.when(xXUserDao.getById(vXUser.getId())).thenReturn(xXUser); + Mockito.when(xUserService.populateViewBean(xXUser)).thenReturn(vXUser); + VXPermMapList vXPermMapList = new VXPermMapList(); + VXPermMap vXPermMap1 = getVXPermMap(); + List vXPermMaps = new ArrayList<>(); + vXPermMaps.add(vXPermMap1); + vXPermMapList.setVXPermMaps(vXPermMaps); + VXAuditMapList vXAuditMapList = new VXAuditMapList(); + List vXAuditMaps = new ArrayList<>(); + VXAuditMap vXAuditMap = getVXAuditMap(); + vXAuditMaps.add(vXAuditMap); + vXAuditMapList.setVXAuditMaps(vXAuditMaps); + VXPortalUser vXPortalUser = userProfile(); + XXPortalUser xXPortalUser = xxPortalUser(vXPortalUser); + XXPortalUserDao xXPortalUserDao = Mockito.mock(XXPortalUserDao.class); + Mockito.when(daoManager.getXXPortalUser()).thenReturn(xXPortalUserDao); + Mockito.when(xXPortalUserDao.findByLoginId(vXUser.getName().trim())).thenReturn(xXPortalUser); + Mockito.when(xPortalUserService.populateViewBean(xXPortalUser)).thenReturn(vXPortalUser); + XXPortalUserRole xxPortalUserRole = new XXPortalUserRole(); + xxPortalUserRole.setId(userId); + xxPortalUserRole.setUserId(userId); + xxPortalUserRole.setUserRole("ROLE_USER"); + List xXAuthSessions = new ArrayList<>(); + XXAuthSession xXAuthSession = new XXAuthSession(); + xXAuthSession.setId(userId); + xXAuthSession.setLoginId(vXPortalUser.getLoginId()); + xXAuthSessions.add(xXAuthSession); + List xXUserPermissions = new ArrayList<>(); + xXUserPermissions.add(xxUserPermission()); + List xXPortalUserRoles = new ArrayList<>(); + xXPortalUserRoles.add(xxPortalUserRole); + List xXPolicyList = new ArrayList<>(); + XXPolicy xXPolicy = getXXPolicy(); + xXPolicyList.add(xXPolicy); + + XXSecurityZoneRefUser xZoneAdminUser = new XXSecurityZoneRefUser(); + xZoneAdminUser.setZoneId(2L); + xZoneAdminUser.setUserId(userId); + xZoneAdminUser.setUserName(vXUser.getName()); + xZoneAdminUser.setUserType(1); + List zoneSecRefUser = new ArrayList<>(); + zoneSecRefUser.add(xZoneAdminUser); + XXSecurityZoneRefUserDao zoneSecRefUserDao = Mockito.mock(XXSecurityZoneRefUserDao.class); + Mockito.when(daoManager.getXXSecurityZoneRefUser()).thenReturn(zoneSecRefUserDao); + Mockito.when(zoneSecRefUserDao.findByUserId(userId)).thenReturn(zoneSecRefUser); + + RangerSecurityZone securityZone = new RangerSecurityZone(); + securityZone.setId(2L); + securityZone.setName("sz1"); + XXSecurityZone xxSecurityZone = new XXSecurityZone(); + xxSecurityZone.setId(2L); + xxSecurityZone.setName("sz1"); + + XXSecurityZoneDao xXSecurityZoneDao = Mockito.mock(XXSecurityZoneDao.class); + Mockito.when(daoManager.getXXSecurityZoneDao()).thenReturn(xXSecurityZoneDao); + Mockito.when(xXSecurityZoneDao.getById(xZoneAdminUser.getZoneId())).thenReturn(xxSecurityZone); + + List roleRefUser = new ArrayList<>(); + XXRoleRefUser xRoleRefUser = new XXRoleRefUser(); + xRoleRefUser.setRoleId(userId); + xRoleRefUser.setUserId(userId); + xRoleRefUser.setUserName(vXUser.getName().trim()); + xRoleRefUser.setUserType(0); + roleRefUser.add(xRoleRefUser); + XXRole xRole = new XXRole(); + xRole.setId(userId); + xRole.setName("Role1"); + + VXResponse vXResponse = new VXResponse(); + vXResponse.setStatusCode(HttpServletResponse.SC_BAD_REQUEST); + vXResponse.setMsgDesc("Can Not Delete User '" + vXUser.getName().trim() + "' as its present in " + RangerConstants.ROLE_FIELD); + Mockito.when(restErrorUtil.generateRESTException(Mockito.any())).thenThrow(new WebApplicationException()); + thrown.expect(WebApplicationException.class); + + xUserMgr.deleteXUser(vXUser.getId(), force); + force = false; + xUserMgr.deleteXUser(vXUser.getId(), force); + } + + @Test + public void test126DeleteXGroup() { + destroySession(); + setup(); + boolean force = true; + VXGroup vXGroup = vxGroup(); + VXPermMapList vXPermMapList = new VXPermMapList(); + VXPermMap vXPermMap1 = getVXPermMap(); + List vXPermMaps = new ArrayList<>(); + vXPermMaps.add(vXPermMap1); + vXPermMapList.setVXPermMaps(vXPermMaps); + VXAuditMapList vXAuditMapList = new VXAuditMapList(); + List vXAuditMaps = new ArrayList<>(); + VXAuditMap vXAuditMap = getVXAuditMap(); + vXAuditMaps.add(vXAuditMap); + vXAuditMapList.setVXAuditMaps(vXAuditMaps); + List xXGroupGroups = new ArrayList<>(); + XXGroupGroup xXGroupGroup = xxGroupGroup(); + xXGroupGroups.add(xXGroupGroup); + List xXGroupPermissions = new ArrayList<>(); + XXGroupPermission xGroupPermissionObj = xxGroupPermission(); + xXGroupPermissions.add(xGroupPermissionObj); + List xXPolicyList = new ArrayList<>(); + XXPolicy xXPolicy = getXXPolicy(); + xXPolicyList.add(xXPolicy); + List xResourceList = new ArrayList<>(); + XXResource xXResource = new XXResource(); + xXResource.setId(userId); + xXResource.setName("hadoopdev"); + xXResource.setIsRecursive(AppConstants.BOOL_TRUE); + xXResource.setResourceStatus(AppConstants.STATUS_ENABLED); + xResourceList.add(xXResource); + + XXSecurityZoneRefGroup xZoneAdminGroup = new XXSecurityZoneRefGroup(); + xZoneAdminGroup.setZoneId(2L); + xZoneAdminGroup.setGroupId(vXGroup.getId()); + xZoneAdminGroup.setGroupName(vXGroup.getName()); + xZoneAdminGroup.setGroupType(1); + List zoneSecRefGroup = new ArrayList<>(); + zoneSecRefGroup.add(xZoneAdminGroup); + XXSecurityZoneRefGroupDao zoneSecRefGroupDao = Mockito.mock(XXSecurityZoneRefGroupDao.class); + Mockito.when(daoManager.getXXSecurityZoneRefGroup()).thenReturn(zoneSecRefGroupDao); + Mockito.when(zoneSecRefGroupDao.findByGroupId(userId)).thenReturn(zoneSecRefGroup); + + RangerSecurityZone securityZone = new RangerSecurityZone(); + securityZone.setId(2L); + securityZone.setName("sz1"); + XXSecurityZone xxSecurityZone = new XXSecurityZone(); + xxSecurityZone.setId(2L); + xxSecurityZone.setName("sz1"); + + XXSecurityZoneDao xXSecurityZoneDao = Mockito.mock(XXSecurityZoneDao.class); + Mockito.when(daoManager.getXXSecurityZoneDao()).thenReturn(xXSecurityZoneDao); + Mockito.when(xXSecurityZoneDao.getById(xZoneAdminGroup.getZoneId())).thenReturn(xxSecurityZone); + + List roleRefGroup = new ArrayList<>(); + XXRoleRefGroup xRoleRefGroup = new XXRoleRefGroup(); + xRoleRefGroup.setRoleId(userId); + xRoleRefGroup.setGroupId(userId); + xRoleRefGroup.setGroupName(groupName); + xRoleRefGroup.setGroupType(0); + roleRefGroup.add(xRoleRefGroup); + + XXRole xRole = new XXRole(); + xRole.setId(userId); + xRole.setName("Role1"); + + VXResponse vXResponse = new VXResponse(); + vXResponse.setStatusCode(HttpServletResponse.SC_BAD_REQUEST); + vXResponse.setMsgDesc("Can Not Delete Group '" + vXGroup.getName().trim() + "' as its present in " + RangerConstants.ROLE_FIELD); + Mockito.when(restErrorUtil.generateRESTException(Mockito.any())).thenThrow(new WebApplicationException()); + thrown.expect(WebApplicationException.class); + + xUserMgr.deleteXGroup(vXGroup.getId(), force); + } + + @Test + public void test127DeleteXUser() { + destroySession(); + setup(); + boolean force = true; + VXUser vXUser = vxUser(); + XXUser xXUser = new XXUser(); + XXUserDao xXUserDao = Mockito.mock(XXUserDao.class); + Mockito.when(daoManager.getXXUser()).thenReturn(xXUserDao); + Mockito.when(xXUserDao.getById(vXUser.getId())).thenReturn(xXUser); + Mockito.when(xUserService.populateViewBean(xXUser)).thenReturn(vXUser); + VXPermMapList vXPermMapList = new VXPermMapList(); + VXPermMap vXPermMap1 = getVXPermMap(); + List vXPermMaps = new ArrayList<>(); + vXPermMaps.add(vXPermMap1); + vXPermMapList.setVXPermMaps(vXPermMaps); + VXAuditMapList vXAuditMapList = new VXAuditMapList(); + List vXAuditMaps = new ArrayList<>(); + VXAuditMap vXAuditMap = getVXAuditMap(); + vXAuditMaps.add(vXAuditMap); + vXAuditMapList.setVXAuditMaps(vXAuditMaps); + VXPortalUser vXPortalUser = userProfile(); + XXPortalUser xXPortalUser = xxPortalUser(vXPortalUser); + XXPortalUserDao xXPortalUserDao = Mockito.mock(XXPortalUserDao.class); + Mockito.when(daoManager.getXXPortalUser()).thenReturn(xXPortalUserDao); + Mockito.when(xXPortalUserDao.findByLoginId(vXUser.getName().trim())).thenReturn(xXPortalUser); + Mockito.when(xPortalUserService.populateViewBean(xXPortalUser)).thenReturn(vXPortalUser); + XXPortalUserRole xxPortalUserRole = new XXPortalUserRole(); + xxPortalUserRole.setId(userId); + xxPortalUserRole.setUserId(userId); + xxPortalUserRole.setUserRole("ROLE_USER"); + List xXAuthSessions = new ArrayList<>(); + XXAuthSession xXAuthSession = new XXAuthSession(); + xXAuthSession.setId(userId); + xXAuthSession.setLoginId(vXPortalUser.getLoginId()); + xXAuthSessions.add(xXAuthSession); + List xXUserPermissions = new ArrayList<>(); + xXUserPermissions.add(xxUserPermission()); + List xXPortalUserRoles = new ArrayList<>(); + xXPortalUserRoles.add(xxPortalUserRole); + List xXPolicyList = new ArrayList<>(); + XXPolicy xXPolicy = getXXPolicy(); + xXPolicyList.add(xXPolicy); + + List zoneSecRefUser = new ArrayList<>(); + XXSecurityZoneRefUserDao zoneSecRefUserDao = Mockito.mock(XXSecurityZoneRefUserDao.class); + Mockito.when(daoManager.getXXSecurityZoneRefUser()).thenReturn(zoneSecRefUserDao); + Mockito.when(zoneSecRefUserDao.findByUserId(userId)).thenReturn(zoneSecRefUser); + + List roleRefUser = new ArrayList<>(); + XXRoleRefUser xRoleRefUser = new XXRoleRefUser(); + xRoleRefUser.setRoleId(userId); + xRoleRefUser.setUserId(userId); + xRoleRefUser.setUserName(vXUser.getName().trim()); + xRoleRefUser.setUserType(0); + roleRefUser.add(xRoleRefUser); + XXRoleRefUserDao roleRefUserDao = Mockito.mock(XXRoleRefUserDao.class); + Mockito.when(daoManager.getXXRoleRefUser()).thenReturn(roleRefUserDao); + Mockito.when(roleRefUserDao.findByUserId(userId)).thenReturn(roleRefUser); + XXRole xRole = new XXRole(); + xRole.setId(userId); + xRole.setName("Role1"); + XXRoleDao roleDao = Mockito.mock(XXRoleDao.class); + Mockito.when(daoManager.getXXRole()).thenReturn(roleDao); + Mockito.when(roleDao.getById(xRoleRefUser.getRoleId())).thenReturn(xRole); + + VXResponse vXResponse = new VXResponse(); + vXResponse.setStatusCode(HttpServletResponse.SC_BAD_REQUEST); + vXResponse.setMsgDesc("Can Not Delete User '" + vXUser.getName().trim() + "' as its present in " + RangerConstants.ROLE_FIELD); + Mockito.when(restErrorUtil.generateRESTException(Mockito.any())).thenThrow(new WebApplicationException()); + thrown.expect(WebApplicationException.class); + + xUserMgr.deleteXUser(vXUser.getId(), force); + force = false; + xUserMgr.deleteXUser(vXUser.getId(), force); + } + + @Test + public void test128DeleteXGroup() { + destroySession(); + setup(); + boolean force = true; + VXGroup vXGroup = vxGroup(); + VXPermMapList vXPermMapList = new VXPermMapList(); + VXPermMap vXPermMap1 = getVXPermMap(); + List vXPermMaps = new ArrayList<>(); + vXPermMaps.add(vXPermMap1); + vXPermMapList.setVXPermMaps(vXPermMaps); + VXAuditMapList vXAuditMapList = new VXAuditMapList(); + List vXAuditMaps = new ArrayList<>(); + VXAuditMap vXAuditMap = getVXAuditMap(); + vXAuditMaps.add(vXAuditMap); + vXAuditMapList.setVXAuditMaps(vXAuditMaps); + List xXGroupGroups = new ArrayList<>(); + XXGroupGroup xXGroupGroup = xxGroupGroup(); + xXGroupGroups.add(xXGroupGroup); + List xXGroupPermissions = new ArrayList<>(); + XXGroupPermission xGroupPermissionObj = xxGroupPermission(); + xXGroupPermissions.add(xGroupPermissionObj); + List xXPolicyList = new ArrayList<>(); + XXPolicy xXPolicy = getXXPolicy(); + xXPolicyList.add(xXPolicy); + List xResourceList = new ArrayList<>(); + XXResource xXResource = new XXResource(); + xXResource.setId(userId); + xXResource.setName("hadoopdev"); + xXResource.setIsRecursive(AppConstants.BOOL_TRUE); + xXResource.setResourceStatus(AppConstants.STATUS_ENABLED); + xResourceList.add(xXResource); + + List zoneSecRefGroup = new ArrayList<>(); + XXSecurityZoneRefGroupDao zoneSecRefGroupDao = Mockito.mock(XXSecurityZoneRefGroupDao.class); + Mockito.when(daoManager.getXXSecurityZoneRefGroup()).thenReturn(zoneSecRefGroupDao); + Mockito.when(zoneSecRefGroupDao.findByGroupId(userId)).thenReturn(zoneSecRefGroup); + + List roleRefGroup = new ArrayList<>(); + XXRoleRefGroup xRoleRefGroup = new XXRoleRefGroup(); + xRoleRefGroup.setRoleId(userId); + xRoleRefGroup.setGroupId(userId); + xRoleRefGroup.setGroupName(groupName); + xRoleRefGroup.setGroupType(0); + roleRefGroup.add(xRoleRefGroup); + XXRoleRefGroupDao roleRefGroupDao = Mockito.mock(XXRoleRefGroupDao.class); + Mockito.when(daoManager.getXXRoleRefGroup()).thenReturn(roleRefGroupDao); + Mockito.when(roleRefGroupDao.findByGroupId(userId)).thenReturn(roleRefGroup); + + XXRole xRole = new XXRole(); + xRole.setId(userId); + xRole.setName("Role1"); + XXRoleDao roleDao = Mockito.mock(XXRoleDao.class); + Mockito.when(daoManager.getXXRole()).thenReturn(roleDao); + Mockito.when(roleDao.getById(xRoleRefGroup.getRoleId())).thenReturn(xRole); + + VXResponse vXResponse = new VXResponse(); + vXResponse.setStatusCode(HttpServletResponse.SC_BAD_REQUEST); + vXResponse.setMsgDesc("Can Not Delete Group '" + vXGroup.getName().trim() + "' as its present in " + RangerConstants.ROLE_FIELD); + Mockito.when(restErrorUtil.generateRESTException(Mockito.any())).thenThrow(new WebApplicationException()); + thrown.expect(WebApplicationException.class); + + xUserMgr.deleteXGroup(vXGroup.getId(), force); + } + + @Test + public void test129CreateOrUpdateUserPermisson() { + destroySession(); + setup(); + VXPortalUser vXPortalUser = userProfile(); + List xXModuleDefs = xxModuleDefs(); + + VXUserPermission userPermission = vxUserPermission(); + List userPermList = new ArrayList<>(); + userPermList.add(userPermission); + List xUserPermissionsList = new ArrayList<>(); + XXUserPermission xUserPermission = xxUserPermission(); + xUserPermission.setModuleId(userPermission.getModuleId()); + xUserPermission.setUserId(userPermission.getUserId()); + xUserPermissionsList.add(xUserPermission); + + XXUserPermissionDao xXUserPermissionDao = Mockito.mock(XXUserPermissionDao.class); + Mockito.when(daoManager.getXXUserPermission()).thenReturn(xXUserPermissionDao); + Mockito.when(xXUserPermissionDao.findByModuleIdAndPortalUserId(vXPortalUser.getId(), xXModuleDefs.get(0).getId())).thenReturn(xUserPermission); + + VXUser vxUser = vxUser(); + XXUser xXUser = xxUser(vxUser); + XXUserDao xxUserDao = Mockito.mock(XXUserDao.class); + Mockito.when(daoManager.getXXUser()).thenReturn(xxUserDao); + Mockito.when(xxUserDao.findByPortalUserId(vXPortalUser.getId())).thenReturn(xXUser); + + Mockito.when(xUserPermissionService.populateViewBean(xUserPermission)).thenReturn(userPermission); + + Mockito.when(xUserPermissionService.updateResource(Mockito.any())).thenReturn(userPermission); + UserSessionBase userSession = Mockito.mock(UserSessionBase.class); + Set userSessions = new HashSet<>(); + userSessions.add(userSession); + Mockito.when(sessionMgr.getActiveUserSessionsForPortalUserId(userId)).thenReturn(userSessions); + + Collection existingRoleList = new ArrayList<>(); + existingRoleList.add(RangerConstants.ROLE_SYS_ADMIN); + existingRoleList.add(RangerConstants.ROLE_KEY_ADMIN); + existingRoleList.add(RangerConstants.ROLE_KEY_ADMIN_AUDITOR); + existingRoleList.add(RangerConstants.ROLE_ADMIN_AUDITOR); + vXPortalUser.setUserRoleList(existingRoleList); + xUserMgr.createOrUpdateUserPermisson(vXPortalUser, xXModuleDefs.get(0).getId(), true); + Mockito.when(xXUserPermissionDao.findByModuleIdAndPortalUserId(vXPortalUser.getId(), xXModuleDefs.get(0).getId())).thenReturn(null); + Mockito.when(xxUserDao.findByPortalUserId(vXPortalUser.getId())).thenReturn(null); + xUserMgr.createOrUpdateUserPermisson(vXPortalUser, xXModuleDefs.get(0).getId(), true); + } + + @Test + public void test130UpdateXUser() { + destroySession(); + setup(); + VXUser vxUser = vxUser(); + Mockito.when(restErrorUtil.createRESTException("Please provide a valid username.", MessageEnums.INVALID_INPUT_DATA)).thenThrow(new WebApplicationException()); + thrown.expect(WebApplicationException.class); + vxUser = xUserMgr.updateXUser(null); + Assert.assertNull(vxUser); + } + + @Test + public void test131hasAccess() { + destroySession(); + setup(); + destroySession(); + boolean access = xUserMgr.hasAccess("test"); + Assert.assertFalse(access); + } + + @Test + public void test132CreateExternalUser() { + destroySession(); + setup(); + ArrayList roleList = new ArrayList<>(); + roleList.add(RangerConstants.ROLE_USER); + VXPortalUser vXPortalUser = userProfile(); + XXUserDao xxUserDao = Mockito.mock(XXUserDao.class); + VXUser vXUser = vxUser(); + VXUser createdXUser = vxUser(); + XXUser xXUser = xxUser(vXUser); + Mockito.when(daoManager.getXXUser()).thenReturn(xxUserDao); + Mockito.when(xxUserDao.findByUserName(vXUser.getName())).thenReturn(null, xXUser); + Mockito.when(xUserService.populateViewBean(xXUser)).thenReturn(vXUser); + + vXPortalUser.setUserRoleList(roleList); + List xUserPermissionsList = new ArrayList<>(); + XXUserPermission xUserPermissionObj = new XXUserPermission(); + xUserPermissionObj.setAddedByUserId(userId); + xUserPermissionObj.setCreateTime(new Date()); + xUserPermissionObj.setId(userId); + xUserPermissionObj.setIsAllowed(1); + xUserPermissionObj.setModuleId(1L); + xUserPermissionObj.setUpdatedByUserId(userId); + xUserPermissionObj.setUpdateTime(new Date()); + xUserPermissionObj.setUserId(userId); + xUserPermissionsList.add(xUserPermissionObj); + + createdXUser = xUserMgr.createExternalUser(vXUser.getName()); + Assert.assertNotNull(createdXUser); + Assert.assertEquals(createdXUser.getName(), vXUser.getName()); + } + + @Test + public void test01CreateXUser_federated() { + destroySession(); + setup(); + VXUser vxUser = vxUserFederated(); + vxUser.setFirstName("user12"); + vxUser.setLastName("test12"); + Collection groupIdList = new ArrayList<>(); + groupIdList.add(userId); + vxUser.setGroupIdList(groupIdList); + VXGroup vxGroup = vxGroup(); + vxGroup.setName("user12Grp"); + VXGroupUser vXGroupUser = new VXGroupUser(); + vXGroupUser.setParentGroupId(userId); + vXGroupUser.setUserId(userId); + vXGroupUser.setName(vxGroup.getName()); + Mockito.when(xGroupService.readResource(userId)).thenReturn(vxGroup); + Mockito.when(xGroupUserService.createResource(Mockito.any())).thenReturn(vXGroupUser); + ArrayList userRoleListVXPortaUser = getRoleList(); + VXPortalUser vXPortalUser = new VXPortalUser(); + vXPortalUser.setUserRoleList(userRoleListVXPortaUser); + Mockito.when(xUserService.createResource(vxUser)).thenReturn(vxUser); + XXModuleDefDao value = Mockito.mock(XXModuleDefDao.class); + Mockito.when(daoManager.getXXModuleDef()).thenReturn(value); + Mockito.when(userMgr.createDefaultAccountUser(Mockito.any())).thenReturn(vXPortalUser); + Mockito.when(stringUtil.validateEmail("test@test.com")).thenReturn(true); + VXUser dbUser = xUserMgr.createXUser(vxUser); + Assert.assertNotNull(dbUser); + userId = dbUser.getId(); + Assert.assertEquals(userId, dbUser.getId()); + Assert.assertEquals(dbUser.getDescription(), vxUser.getDescription()); + Assert.assertEquals(dbUser.getName(), vxUser.getName()); + Assert.assertEquals(dbUser.getUserRoleList(), vxUser.getUserRoleList()); + Assert.assertEquals(dbUser.getGroupNameList(), vxUser.getGroupNameList()); + Assert.assertNotNull(dbUser.getPassword()); + Assert.assertEquals(RangerCommonEnums.USER_FEDERATED, dbUser.getUserSource()); + Mockito.verify(xUserService).createResource(vxUser); + Mockito.when(xUserService.readResourceWithOutLogin(userId)).thenReturn(vxUser); + + VXUser loggedInUser = vxUser(); + List loggedInUserRole = new ArrayList<>(); + loggedInUserRole.add(RangerConstants.ROLE_ADMIN); + loggedInUser.setId(8L); + loggedInUser.setName("testuser"); + loggedInUser.setUserRoleList(loggedInUserRole); + Mockito.when(xUserService.getXUserByUserName("admin")).thenReturn(loggedInUser); + Mockito.when(restErrorUtil.createRESTException(HttpServletResponse.SC_FORBIDDEN, "Logged-In user is not allowed to access requested user data", true)).thenThrow(new WebApplicationException()); + thrown.expect(WebApplicationException.class); + VXUser dbvxUser = xUserMgr.getXUser(userId); + Mockito.verify(userMgr).createDefaultAccountUser(Mockito.any()); + Assert.assertNotNull(dbvxUser); + Assert.assertEquals(userId, dbvxUser.getId()); + Assert.assertEquals(dbvxUser.getDescription(), vxUser.getDescription()); + Assert.assertEquals(dbvxUser.getName(), vxUser.getName()); + Assert.assertEquals(dbvxUser.getUserRoleList(), vxUser.getUserRoleList()); + Assert.assertEquals(dbvxUser.getGroupIdList(), vxUser.getGroupIdList()); + Assert.assertEquals(dbvxUser.getGroupNameList(), vxUser.getGroupNameList()); + Assert.assertNotNull(dbvxUser.getPassword()); + Assert.assertEquals(RangerCommonEnums.USER_FEDERATED, dbvxUser.getUserSource()); + Mockito.verify(xUserService).readResourceWithOutLogin(userId); + } + + private VXUser vxUser() { + Collection userRoleList = new ArrayList<>(); + userRoleList.add("ROLE_USER"); + Collection groupNameList = new ArrayList<>(); + groupNameList.add(groupName); + VXUser vxUser = new VXUser(); + vxUser.setId(userId); + vxUser.setDescription("group test working"); + vxUser.setName(userLoginID); + vxUser.setUserRoleList(userRoleList); + vxUser.setGroupNameList(groupNameList); + vxUser.setPassword("Usertest123"); + vxUser.setEmailAddress("test@test.com"); + return vxUser; + } + + private VXUser vxUserFederated() { + Collection userRoleList = new ArrayList<>(); + userRoleList.add("ROLE_USER"); + Collection groupNameList = new ArrayList<>(); + groupNameList.add(groupName); + VXUser vxUser = new VXUser(); + vxUser.setId(userId); + vxUser.setDescription("group test working"); + vxUser.setName(userLoginID); + vxUser.setUserRoleList(userRoleList); + vxUser.setGroupNameList(groupNameList); + vxUser.setPassword(null); + vxUser.setEmailAddress("test@test.com"); + vxUser.setUserSource(RangerCommonEnums.USER_FEDERATED); + return vxUser; + } + + private XXUser xxUser(VXUser vxUser) { + XXUser xXUser = new XXUser(); + xXUser.setId(userId); + xXUser.setName(vxUser.getName()); + xXUser.setStatus(vxUser.getStatus()); + xXUser.setIsVisible(vxUser.getIsVisible()); + xXUser.setDescription(vxUser.getDescription()); + return xXUser; + } + + private VXGroup vxGroup() { + VXGroup vXGroup = new VXGroup(); + vXGroup.setId(userId); + vXGroup.setDescription("group test working"); + vXGroup.setName(groupName); + vXGroup.setIsVisible(1); + return vXGroup; + } + + private VXModuleDef vxModuleDef() { + VXUserPermission userPermission = vxUserPermission(); + List userPermList = new ArrayList<>(); + userPermList.add(userPermission); + VXGroupPermission groupPermission = vxGroupPermission(); + List groupPermList = new ArrayList<>(); + groupPermList.add(groupPermission); + VXModuleDef vxModuleDef = new VXModuleDef(); + vxModuleDef.setAddedById(userId); + vxModuleDef.setCreateDate(new Date()); + vxModuleDef.setCreateTime(new Date()); + vxModuleDef.setId(userId); + vxModuleDef.setModule("Policy manager"); + vxModuleDef.setOwner("admin"); + vxModuleDef.setUpdateDate(new Date()); + vxModuleDef.setUpdatedBy("admin"); + vxModuleDef.setUpdatedById(userId); + vxModuleDef.setUpdateTime(new Date()); + vxModuleDef.setUrl("/policy manager"); + vxModuleDef.setUserPermList(userPermList); + vxModuleDef.setGroupPermList(groupPermList); + return vxModuleDef; + } + + private VXUserPermission vxUserPermission() { + VXUserPermission userPermission = new VXUserPermission(); + userPermission.setId(1L); + userPermission.setIsAllowed(1); + userPermission.setModuleId(1L); + userPermission.setUserId(userId); + userPermission.setUserName(userLoginID); + userPermission.setOwner("admin"); + return userPermission; + } + + private VXGroupPermission vxGroupPermission() { + VXGroupPermission groupPermission = new VXGroupPermission(); + groupPermission.setId(1L); + groupPermission.setIsAllowed(1); + groupPermission.setModuleId(1L); + groupPermission.setGroupId(userId); + groupPermission.setGroupName(groupName); + groupPermission.setOwner("admin"); + return groupPermission; + } + + private VXPortalUser userProfile() { + VXPortalUser userProfile = new VXPortalUser(); + userProfile.setEmailAddress("test@test.com"); + userProfile.setFirstName("user12"); + userProfile.setLastName("test12"); + userProfile.setLoginId(userLoginID); + userProfile.setPassword("Usertest123"); + userProfile.setUserSource(1); + userProfile.setPublicScreenName("testuser"); + userProfile.setId(userId); + return userProfile; + } + + private XXPortalUser xxPortalUser(VXPortalUser userProfile) { + XXPortalUser xxPortalUser = new XXPortalUser(); + xxPortalUser.setEmailAddress(userProfile.getEmailAddress()); + xxPortalUser.setFirstName(userProfile.getFirstName()); + xxPortalUser.setLastName(userProfile.getLastName()); + xxPortalUser.setLoginId(userProfile.getLoginId()); + xxPortalUser.setPassword(userProfile.getPassword()); + xxPortalUser.setUserSource(userProfile.getUserSource()); + xxPortalUser.setPublicScreenName(userProfile.getPublicScreenName()); + return xxPortalUser; + } + + private List xxModuleDefs() { + List xXModuleDefs = new ArrayList<>(); + XXModuleDef xXModuleDef1 = xxModuleDef(); + XXModuleDef xXModuleDef2 = xxModuleDef(); + XXModuleDef xXModuleDef3 = xxModuleDef(); + XXModuleDef xXModuleDef4 = xxModuleDef(); + XXModuleDef xXModuleDef5 = xxModuleDef(); + xXModuleDef1.setId(1L); + xXModuleDef1.setModule("Resource Based Policies"); + xXModuleDef1.setId(2L); + xXModuleDef1.setModule("Users/Groups"); + xXModuleDef1.setId(3L); + xXModuleDef1.setModule("Reports"); + xXModuleDef1.setId(4L); + xXModuleDef1.setModule("Audit"); + xXModuleDef1.setId(5L); + xXModuleDef1.setModule("Key Manager"); + xXModuleDefs.add(xXModuleDef1); + xXModuleDefs.add(xXModuleDef2); + xXModuleDefs.add(xXModuleDef3); + xXModuleDefs.add(xXModuleDef4); + xXModuleDefs.add(xXModuleDef5); + return xXModuleDefs; + } + + private VXGroupUser vxGroupUser() { + VXUser vXUser = vxUser(); + VXGroupUser vxGroupUser = new VXGroupUser(); + vxGroupUser.setId(userId); + vxGroupUser.setName(vXUser.getName()); + vxGroupUser.setOwner("Admin"); + vxGroupUser.setUserId(vXUser.getId()); + vxGroupUser.setUpdatedBy("User"); + vxGroupUser.setParentGroupId(userId); + return vxGroupUser; + } + + private XXGroupGroup xxGroupGroup() { + XXGroupGroup xXGroupGroup = new XXGroupGroup(); + xXGroupGroup.setId(userId); + xXGroupGroup.setName("group user test"); + return xXGroupGroup; + } + + private XXPolicy getXXPolicy() { + XXPolicy xxPolicy = new XXPolicy(); + xxPolicy.setId(userId); + xxPolicy.setName("HDFS_1-1-20150316062453"); + xxPolicy.setAddedByUserId(userId); + xxPolicy.setCreateTime(new Date()); + xxPolicy.setDescription("test"); + xxPolicy.setIsAuditEnabled(false); + xxPolicy.setIsEnabled(false); + xxPolicy.setService(1L); + xxPolicy.setUpdatedByUserId(userId); + xxPolicy.setUpdateTime(new Date()); + return xxPolicy; + } + + private VXGroupUserList vxGroupUserList() { + VXGroupUserList vxGroupUserList = new VXGroupUserList(); + List vXGroupUsers = new ArrayList<>(); + VXGroupUser vxGroupUser = vxGroupUser(); + vXGroupUsers.add(vxGroupUser); + vxGroupUserList.setVXGroupUsers(vXGroupUsers); + return vxGroupUserList; + } + + private ArrayList getRoleList() { + ArrayList userRoleList = new ArrayList<>(); + userRoleList.add("ROLE_USER"); + return userRoleList; + } + + private SearchCriteria createsearchCriteria() { + SearchCriteria testsearchCriteria = new SearchCriteria(); + testsearchCriteria.setStartIndex(0); + testsearchCriteria.setMaxRows(Integer.MAX_VALUE); + testsearchCriteria.setSortBy("id"); + testsearchCriteria.setSortType("asc"); + testsearchCriteria.setGetCount(true); + testsearchCriteria.setOwnerId(null); + testsearchCriteria.setGetChildren(false); + testsearchCriteria.setDistinct(false); + return testsearchCriteria; + } + + private XXUserPermission xxUserPermission() { + XXUserPermission xUserPermissionObj = new XXUserPermission(); + xUserPermissionObj.setAddedByUserId(userId); + xUserPermissionObj.setCreateTime(new Date()); + xUserPermissionObj.setId(userId); + xUserPermissionObj.setIsAllowed(1); + xUserPermissionObj.setModuleId(1L); + xUserPermissionObj.setUpdatedByUserId(userId); + xUserPermissionObj.setUpdateTime(new Date()); + xUserPermissionObj.setUserId(userId); + return xUserPermissionObj; + } + + private XXGroupPermission xxGroupPermission() { + XXGroupPermission xGroupPermissionObj = new XXGroupPermission(); + xGroupPermissionObj.setAddedByUserId(userId); + xGroupPermissionObj.setCreateTime(new Date()); + xGroupPermissionObj.setId(userId); + xGroupPermissionObj.setIsAllowed(1); + xGroupPermissionObj.setModuleId(1L); + xGroupPermissionObj.setUpdatedByUserId(userId); + xGroupPermissionObj.setUpdateTime(new Date()); + xGroupPermissionObj.setGroupId(userId); + return xGroupPermissionObj; + } + + private XXModuleDef xxModuleDef() { + XXModuleDef xModuleDef = new XXModuleDef(); + xModuleDef.setUpdatedByUserId(userId); + xModuleDef.setAddedByUserId(userId); + xModuleDef.setCreateTime(new Date()); + xModuleDef.setId(userId); + xModuleDef.setModule("Policy manager"); + xModuleDef.setUpdateTime(new Date()); + xModuleDef.setUrl("/policy manager"); + return xModuleDef; + } + + private VXPermMap getVXPermMap() { + VXPermMap testVXPermMap = new VXPermMap(); + testVXPermMap.setCreateDate(new Date()); + testVXPermMap.setGroupId(userId); + testVXPermMap.setGroupName("testGroup"); + testVXPermMap.setId(userId); + testVXPermMap.setOwner("Admin"); + testVXPermMap.setPermGroup("testPermGroup"); + testVXPermMap.setPermType(1); + testVXPermMap.setResourceId(userId); + testVXPermMap.setUpdateDate(new Date()); + testVXPermMap.setUpdatedBy("Admin"); + testVXPermMap.setUserId(userId); + testVXPermMap.setUserName("testUser"); + testVXPermMap.setPermFor(1); + return testVXPermMap; + } + + private VXAuditMap getVXAuditMap() { + VXAuditMap testVXAuditMap = new VXAuditMap(); + testVXAuditMap.setAuditType(1); + testVXAuditMap.setCreateDate(new Date()); + testVXAuditMap.setGroupId(userId); + testVXAuditMap.setId(userId); + testVXAuditMap.setResourceId(userId); + testVXAuditMap.setUpdateDate(new Date()); + testVXAuditMap.setOwner("Admin"); + testVXAuditMap.setUpdatedBy("Admin"); + testVXAuditMap.setUserId(userId); + return testVXAuditMap; + } + + private RangerPolicy rangerPolicy() { + List accesses = new ArrayList<>(); + List users = new ArrayList<>(); + List groups = new ArrayList<>(); + List policyLabels = new ArrayList<>(); + List conditions = new ArrayList<>(); + List policyItems = new ArrayList<>(); + RangerPolicyItem rangerPolicyItem = new RangerPolicyItem(); + rangerPolicyItem.setAccesses(accesses); + rangerPolicyItem.setConditions(conditions); + rangerPolicyItem.setGroups(groups); + rangerPolicyItem.setUsers(users); + rangerPolicyItem.setDelegateAdmin(false); + + policyItems.add(rangerPolicyItem); + + Map policyResource = new HashMap<>(); + RangerPolicyResource rangerPolicyResource = new RangerPolicyResource(); + rangerPolicyResource.setIsExcludes(true); + rangerPolicyResource.setIsRecursive(true); + rangerPolicyResource.setValue("1"); + rangerPolicyResource.setValues(users); + RangerPolicy policy = new RangerPolicy(); + policy.setId(userId); + policy.setCreateTime(new Date()); + policy.setDescription("policy"); + policy.setGuid("policyguid"); + policy.setIsEnabled(true); + policy.setName("HDFS_1-1-20150316062453"); + policy.setUpdatedBy("Admin"); + policy.setUpdateTime(new Date()); + policy.setService("HDFS_1-1-20150316062453"); + policy.setIsAuditEnabled(true); + policy.setPolicyItems(policyItems); + policy.setResources(policyResource); + policy.setPolicyLabels(policyLabels); + policy.setServiceType("hdfs"); + return policy; + } } diff --git a/security-admin/src/test/java/org/apache/ranger/common/TestContextUtil.java b/security-admin/src/test/java/org/apache/ranger/common/TestContextUtil.java index 73bce2d3d4..c0b1a209a4 100644 --- a/security-admin/src/test/java/org/apache/ranger/common/TestContextUtil.java +++ b/security-admin/src/test/java/org/apache/ranger/common/TestContextUtil.java @@ -31,75 +31,70 @@ @RunWith(MockitoJUnitRunner.class) public class TestContextUtil { - - @InjectMocks - ContextUtil contextUtil = new ContextUtil(); - - UserSessionBase currentUserSession = new UserSessionBase(); - XXPortalUser gjUser = new XXPortalUser(); - RangerSecurityContext context = new RangerSecurityContext(); - - @Before - public void setup(){ - gjUser.setId(1L); - currentUserSession.setXXPortalUser(gjUser); - context.setUserSession(currentUserSession); - RangerContextHolder.setSecurityContext(context); - } - - @SuppressWarnings("static-access") - @Test - public void testGetCurrentUserId(){ - Long expectedId = 1L; - Long id = contextUtil.getCurrentUserId(); - - Assert.assertEquals(expectedId, id); - } - - @SuppressWarnings("static-access") - @Test - public void testGetCurrentUserPublicName(){ - String expectedName = "rangerAdmin"; - gjUser.setPublicScreenName("rangerAdmin"); - - String publicName = contextUtil.getCurrentUserPublicName(); - Assert.assertEquals(expectedName, publicName); - - } - - @SuppressWarnings("static-access") - @Test - public void testCurrentUserSession(){ - UserSessionBase expectedUserSession = contextUtil.getCurrentUserSession(); - Assert.assertNotNull(expectedUserSession); - } - - @SuppressWarnings("static-access") - @Test - public void testCurrentUserSessionAsNull(){ - context.setUserSession(null); - UserSessionBase expectedUserSession = contextUtil.getCurrentUserSession(); - Assert.assertNull(expectedUserSession); - } - - @SuppressWarnings("static-access") - @Test - public void testCurrentRequestContext(){ - RequestContext requestContext = new RequestContext(); - context.setRequestContext(requestContext); - RequestContext expectedContext = contextUtil.getCurrentRequestContext(); - Assert.assertNotNull(expectedContext); - - } - - @SuppressWarnings("static-access") - @Test - public void testCurrentUserLoginId(){ - String expectedLoginId = "rangerAdmin"; - gjUser.setLoginId("rangerAdmin"); - String loginId = contextUtil.getCurrentUserLoginId(); - Assert.assertEquals(expectedLoginId, loginId); - - } - + @InjectMocks + ContextUtil contextUtil = new ContextUtil(); + + UserSessionBase currentUserSession = new UserSessionBase(); + XXPortalUser gjUser = new XXPortalUser(); + RangerSecurityContext context = new RangerSecurityContext(); + + @Before + public void setup() { + gjUser.setId(1L); + currentUserSession.setXXPortalUser(gjUser); + context.setUserSession(currentUserSession); + RangerContextHolder.setSecurityContext(context); + } + + @SuppressWarnings("static-access") + @Test + public void testGetCurrentUserId() { + Long expectedId = 1L; + Long id = contextUtil.getCurrentUserId(); + + Assert.assertEquals(expectedId, id); + } + + @SuppressWarnings("static-access") + @Test + public void testGetCurrentUserPublicName() { + String expectedName = "rangerAdmin"; + gjUser.setPublicScreenName("rangerAdmin"); + + String publicName = contextUtil.getCurrentUserPublicName(); + Assert.assertEquals(expectedName, publicName); + } + + @SuppressWarnings("static-access") + @Test + public void testCurrentUserSession() { + UserSessionBase expectedUserSession = contextUtil.getCurrentUserSession(); + Assert.assertNotNull(expectedUserSession); + } + + @SuppressWarnings("static-access") + @Test + public void testCurrentUserSessionAsNull() { + context.setUserSession(null); + UserSessionBase expectedUserSession = contextUtil.getCurrentUserSession(); + Assert.assertNull(expectedUserSession); + } + + @SuppressWarnings("static-access") + @Test + public void testCurrentRequestContext() { + RequestContext requestContext = new RequestContext(); + context.setRequestContext(requestContext); + RequestContext expectedContext = contextUtil.getCurrentRequestContext(); + Assert.assertNotNull(expectedContext); + } + + @SuppressWarnings("static-access") + @Test + public void testCurrentUserLoginId() { + String expectedLoginId = "rangerAdmin"; + gjUser.setLoginId("rangerAdmin"); + String loginId = contextUtil.getCurrentUserLoginId(); + Assert.assertEquals(expectedLoginId, loginId); + } } diff --git a/security-admin/src/test/java/org/apache/ranger/common/TestDateUtil.java b/security-admin/src/test/java/org/apache/ranger/common/TestDateUtil.java index 2b66275150..54cce4f3ff 100644 --- a/security-admin/src/test/java/org/apache/ranger/common/TestDateUtil.java +++ b/security-admin/src/test/java/org/apache/ranger/common/TestDateUtil.java @@ -16,154 +16,145 @@ */ package org.apache.ranger.common; +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; +import org.springframework.beans.factory.annotation.Autowired; + import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.TimeZone; -import org.junit.Assert; -import org.junit.Ignore; -import org.junit.Test; -import org.springframework.beans.factory.annotation.Autowired; - @SuppressWarnings("deprecation") public class TestDateUtil { + private static final TimeZone gmtTimeZone = TimeZone.getTimeZone("GMT+0"); - private static final TimeZone gmtTimeZone = TimeZone.getTimeZone("GMT+0"); - - @Autowired - DateUtil dateUtil = new DateUtil(); + @Autowired + DateUtil dateUtil = new DateUtil(); @Test @Ignore - public void testGetDateFromNow() { - int days = 1; - Date dateCheck= dateUtil.getDateFromNow(days); - int minutes=dateCheck.getMinutes(); - int hourse=dateCheck.getHours(); - Assert.assertEquals(dateCheck.getDay(),days+2); - Assert.assertEquals(dateCheck.getMinutes(), minutes); - Assert.assertEquals(dateCheck.getHours(), hourse); - } + public void testGetDateFromNow() { + int days = 1; + Date dateCheck = dateUtil.getDateFromNow(days); + int minutes = dateCheck.getMinutes(); + int hourse = dateCheck.getHours(); + Assert.assertEquals(days + 2, dateCheck.getDay()); + Assert.assertEquals(dateCheck.getMinutes(), minutes); + Assert.assertEquals(dateCheck.getHours(), hourse); + } @Test - public void testDateFromNow(){ - - int days = 2; - int hours = 3; - int minutes = 50; - - Calendar cal = Calendar.getInstance(); - cal.add(Calendar.DATE, days); - cal.add(Calendar.HOUR, hours); - cal.add(Calendar.MINUTE, minutes); - Date expectedDate = cal.getTime(); - - - Date actualDate = dateUtil.getDateFromNow(days, hours, minutes); - - Assert.assertEquals(expectedDate.getYear(), actualDate.getYear()); - Assert.assertEquals(expectedDate.getDay(), actualDate.getDay()); - Assert.assertEquals(expectedDate.getMonth(), actualDate.getMonth()); - + public void testDateFromNow() { + int days = 2; + int hours = 3; + int minutes = 50; + + Calendar cal = Calendar.getInstance(); + cal.add(Calendar.DATE, days); + cal.add(Calendar.HOUR, hours); + cal.add(Calendar.MINUTE, minutes); + Date expectedDate = cal.getTime(); + + Date actualDate = dateUtil.getDateFromNow(days, hours, minutes); + + Assert.assertEquals(expectedDate.getYear(), actualDate.getYear()); + Assert.assertEquals(expectedDate.getDay(), actualDate.getDay()); + Assert.assertEquals(expectedDate.getMonth(), actualDate.getMonth()); } - @Test - public void testDateToString() { - Date date = new Date(); - SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("dd-MM-yyyy"); - String dateFromat = DATE_FORMAT.format(date); - String dateCheck = DateUtil.dateToString(date, dateFromat); - Assert.assertEquals(dateCheck,dateFromat); - } - - @Test - public void testGetDateFromGivenDate(){ - Date date = new Date(); - int days=0; - int hours=date.getHours(); - int minutes=date.getMinutes(); - int second=date.getSeconds(); - Date currentDate = dateUtil.getDateFromGivenDate(date, days, 0, 0, 0); - Assert.assertEquals(currentDate.getDay(),date.getDay()+days); - Assert.assertEquals(currentDate.getHours(),hours); - Assert.assertEquals(currentDate.getMinutes(),minutes); - Assert.assertEquals(currentDate.getSeconds(),second); - } - - @Test - public void testAddTimeOffset(){ - Date date = new Date(); - int mins=date.getMinutes(); - Date currentDate=dateUtil.addTimeOffset(date, 0); - Assert.assertEquals(currentDate.getDate(),date.getDate()); - Assert.assertEquals(currentDate.getMinutes(),mins); - } - - @Test - public void testStringToDate(){ - String dateString = "2018-05-31"; - String dateFormat = "yyyy-MM-dd"; - - Calendar cal = Calendar.getInstance(); - cal.set(2018 - 1900, 04, 31); - Date expectedDate = new Date(cal.get(Calendar.YEAR),cal.get(Calendar.MONTH),cal.get(Calendar.DATE)); - - Date actualDate = dateUtil.stringToDate(dateString, dateFormat); - if(actualDate != null){ - Assert.assertEquals(expectedDate.getYear(), actualDate.getYear()); - Assert.assertEquals(expectedDate.getDay(), actualDate.getDay()); - Assert.assertEquals(expectedDate.getMonth(), actualDate.getMonth()); - } - - } - - @Test - public void testGetUTCDate(){ - - 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); - Date expectedDate = utc.getTime(); - - Date actualDate = dateUtil.getUTCDate(); - Assert.assertEquals(actualDate.getDate(),expectedDate.getDate()); - Assert.assertEquals(actualDate.getMinutes(),expectedDate.getMinutes()); - } + @Test + public void testDateToString() { + Date date = new Date(); + SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy"); + String dateFormatStr = dateFormat.format(date); + String dateCheck = DateUtil.dateToString(date, dateFormatStr); + Assert.assertEquals(dateCheck, dateFormatStr); + } - @Test - public void testGetUTCDateEpoh(){ + @Test + public void testGetDateFromGivenDate() { + Date date = new Date(); + int days = 0; + int hours = date.getHours(); + int minutes = date.getMinutes(); + int second = date.getSeconds(); + Date currentDate = dateUtil.getDateFromGivenDate(date, days, 0, 0, 0); + Assert.assertEquals(currentDate.getDay(), date.getDay() + days); + Assert.assertEquals(currentDate.getHours(), hours); + Assert.assertEquals(currentDate.getMinutes(), minutes); + Assert.assertEquals(currentDate.getSeconds(), second); + } - Calendar local=Calendar.getInstance(); - int offset = local.getTimeZone().getOffset(2008); - GregorianCalendar utc = new GregorianCalendar(gmtTimeZone); - utc.setTimeInMillis(2008); - utc.add(Calendar.MILLISECOND, -offset); - Date expectedDate = utc.getTime(); + @Test + public void testAddTimeOffset() { + Date date = new Date(); + int mins = date.getMinutes(); + Date currentDate = dateUtil.addTimeOffset(date, 0); + Assert.assertEquals(currentDate.getDate(), date.getDate()); + Assert.assertEquals(currentDate.getMinutes(), mins); + } - Date actualDate = dateUtil.getUTCDate(2008); - Assert.assertEquals(actualDate.getDate(),expectedDate.getDate()); - Assert.assertEquals(actualDate.getMinutes(),expectedDate.getMinutes()); + @Test + public void testStringToDate() { + String dateString = "2018-05-31"; + String dateFormat = "yyyy-MM-dd"; + + Calendar cal = Calendar.getInstance(); + cal.set(2018 - 1900, 04, 31); + Date expectedDate = new Date(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DATE)); + + Date actualDate = DateUtil.stringToDate(dateString, dateFormat); + if (actualDate != null) { + Assert.assertEquals(expectedDate.getYear(), actualDate.getYear()); + Assert.assertEquals(expectedDate.getDay(), actualDate.getDay()); + Assert.assertEquals(expectedDate.getMonth(), actualDate.getMonth()); } + } - @Test - public void testGetLocalDateForUTCDate(){ - Date dt = new Date(); - Calendar local=Calendar.getInstance(); - int offset = local.getTimeZone().getOffset(local.getTimeInMillis()); - GregorianCalendar utc = new GregorianCalendar(gmtTimeZone); - utc.setTimeInMillis(dt.getTime()); - utc.add(Calendar.MILLISECOND, offset); - Date expectedDate = utc.getTime(); - - Date actualDate = dateUtil.getLocalDateForUTCDate(dt); - Assert.assertEquals(actualDate.getDate(),expectedDate.getDate()); - Assert.assertEquals(actualDate.getMinutes(),expectedDate.getMinutes()); - Assert.assertEquals(actualDate.getHours(),expectedDate.getHours()); + @Test + public void testGetUTCDate() { + 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); + Date expectedDate = utc.getTime(); + + Date actualDate = DateUtil.getUTCDate(); + Assert.assertEquals(actualDate.getDate(), expectedDate.getDate()); + Assert.assertEquals(actualDate.getMinutes(), expectedDate.getMinutes()); + } - } + @Test + public void testGetUTCDateEpoh() { + Calendar local = Calendar.getInstance(); + int offset = local.getTimeZone().getOffset(2008); + GregorianCalendar utc = new GregorianCalendar(gmtTimeZone); + utc.setTimeInMillis(2008); + utc.add(Calendar.MILLISECOND, -offset); + Date expectedDate = utc.getTime(); + + Date actualDate = DateUtil.getUTCDate(2008); + Assert.assertEquals(actualDate.getDate(), expectedDate.getDate()); + Assert.assertEquals(actualDate.getMinutes(), expectedDate.getMinutes()); + } + @Test + public void testGetLocalDateForUTCDate() { + Date dt = new Date(); + Calendar local = Calendar.getInstance(); + int offset = local.getTimeZone().getOffset(local.getTimeInMillis()); + GregorianCalendar utc = new GregorianCalendar(gmtTimeZone); + utc.setTimeInMillis(dt.getTime()); + utc.add(Calendar.MILLISECOND, offset); + Date expectedDate = utc.getTime(); + + Date actualDate = DateUtil.getLocalDateForUTCDate(dt); + Assert.assertEquals(actualDate.getDate(), expectedDate.getDate()); + Assert.assertEquals(actualDate.getMinutes(), expectedDate.getMinutes()); + Assert.assertEquals(actualDate.getHours(), expectedDate.getHours()); + } } diff --git a/security-admin/src/test/java/org/apache/ranger/common/TestJSONUtil.java b/security-admin/src/test/java/org/apache/ranger/common/TestJSONUtil.java index 09bbfaffaf..244ce63d6d 100644 --- a/security-admin/src/test/java/org/apache/ranger/common/TestJSONUtil.java +++ b/security-admin/src/test/java/org/apache/ranger/common/TestJSONUtil.java @@ -16,15 +16,6 @@ */ package org.apache.ranger.common; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import javax.servlet.http.HttpServletResponse; - import org.apache.ranger.view.VXResponse; import org.junit.Assert; import org.junit.FixMethodOrder; @@ -34,81 +25,84 @@ import org.junit.runners.MethodSorters; import org.springframework.beans.factory.annotation.Autowired; -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -public class TestJSONUtil { - - @Autowired - JSONUtil jsonUtil = new JSONUtil(); - - @Rule - public ExpectedException thrown = ExpectedException.none(); - - @Test - public void testJsonToMapNull() { - String jsonStr = null; - Map dbMap = jsonUtil.jsonToMap(jsonStr); - Assert.assertEquals(dbMap.get(jsonStr), jsonStr); - } - - @Test - public void testJsonToMapIsEmpty() { - String jsonStr = ""; - Map dbMap = jsonUtil.jsonToMap(jsonStr); - boolean isEmpty = dbMap.isEmpty(); - Assert.assertTrue(isEmpty); - } - - @Test - public void testJsonToMap() { - String jsonStr = "{\"username\":\"admin\",\"password\":\"admin\",\"fs.default.name\":\"defaultnamevalue\",\"hadoop.security.authorization\":\"authvalue\",\"hadoop.security.authentication\":\"authenticationvalue\",\"hadoop.security.auth_to_local\":\"localvalue\",\"dfs.datanode.kerberos.principal\":\"principalvalue\",\"dfs.namenode.kerberos.principal\":\"namenodeprincipalvalue\",\"dfs.secondary.namenode.kerberos.principal\":\"secprincipalvalue\",\"commonNameForCertificate\":\"certificatevalue\"}"; - Map dbMap = jsonUtil.jsonToMap(jsonStr); - Assert.assertNotNull(dbMap); - } - - @Test - public void testReadMapToString() { - Map map = new HashMap(); - String value = jsonUtil.readMapToString(map); - Assert.assertNotNull(value); - } - - @Test - public void testReadListToString() { - String expectedJsonString = "[\"hdfs\",\"hive\",\"knox\"]"; - List testList = new ArrayList(); - - testList.add("hdfs"); - testList.add("hive"); - testList.add("knox"); - - String actualJsonString = jsonUtil.readListToString(testList); - - Assert.assertEquals(expectedJsonString, actualJsonString); - } - - @Test - public void testWriteObjectAsString(){ - String expectedJsonString = "{\"statusCode\":200,\"msgDesc\":\"Logout Successful\"}"; - VXResponse vXResponse = new VXResponse(); - vXResponse.setStatusCode(HttpServletResponse.SC_OK); - vXResponse.setMsgDesc("Logout Successful"); - String actualJsonString = jsonUtil.writeObjectAsString(vXResponse); - - Assert.assertEquals(expectedJsonString, actualJsonString); - - } - - @Test - public void testWriteJsonToJavaObject(){ - String jsonString = "[\"hdfs\",\"hive\",\"knox\"]"; - Set expectedSet = new HashSet(); - expectedSet.add("hive"); - expectedSet.add("hdfs"); - expectedSet.add("knox"); - Set testSet = new HashSet<>(); - Set actualSet = jsonUtil.writeJsonToJavaObject(jsonString, testSet.getClass()); - Assert.assertEquals(expectedSet, actualSet); +import javax.servlet.http.HttpServletResponse; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; - } -} \ No newline at end of file +@FixMethodOrder(MethodSorters.NAME_ASCENDING) +public class TestJSONUtil { + @Rule + public ExpectedException thrown = ExpectedException.none(); + @Autowired + JSONUtil jsonUtil = new JSONUtil(); + + @Test + public void testJsonToMapNull() { + Map dbMap = jsonUtil.jsonToMap(null); + Assert.assertNull(dbMap.get(null)); + } + + @Test + public void testJsonToMapIsEmpty() { + String jsonStr = ""; + Map dbMap = jsonUtil.jsonToMap(jsonStr); + boolean isEmpty = dbMap.isEmpty(); + Assert.assertTrue(isEmpty); + } + + @Test + public void testJsonToMap() { + String jsonStr = "{\"username\":\"admin\",\"password\":\"admin\",\"fs.default.name\":\"defaultnamevalue\",\"hadoop.security.authorization\":\"authvalue\",\"hadoop.security.authentication\":\"authenticationvalue\",\"hadoop.security.auth_to_local\":\"localvalue\",\"dfs.datanode.kerberos.principal\":\"principalvalue\",\"dfs.namenode.kerberos.principal\":\"namenodeprincipalvalue\",\"dfs.secondary.namenode.kerberos.principal\":\"secprincipalvalue\",\"commonNameForCertificate\":\"certificatevalue\"}"; + Map dbMap = jsonUtil.jsonToMap(jsonStr); + Assert.assertNotNull(dbMap); + } + + @Test + public void testReadMapToString() { + Map map = new HashMap<>(); + String value = jsonUtil.readMapToString(map); + Assert.assertNotNull(value); + } + + @Test + public void testReadListToString() { + String expectedJsonString = "[\"hdfs\",\"hive\",\"knox\"]"; + List testList = new ArrayList<>(); + + testList.add("hdfs"); + testList.add("hive"); + testList.add("knox"); + + String actualJsonString = jsonUtil.readListToString(testList); + + Assert.assertEquals(expectedJsonString, actualJsonString); + } + + @Test + public void testWriteObjectAsString() { + String expectedJsonString = "{\"statusCode\":200,\"msgDesc\":\"Logout Successful\"}"; + VXResponse vXResponse = new VXResponse(); + vXResponse.setStatusCode(HttpServletResponse.SC_OK); + vXResponse.setMsgDesc("Logout Successful"); + String actualJsonString = jsonUtil.writeObjectAsString(vXResponse); + + Assert.assertEquals(expectedJsonString, actualJsonString); + } + + @Test + public void testWriteJsonToJavaObject() { + String jsonString = "[\"hdfs\",\"hive\",\"knox\"]"; + Set expectedSet = new HashSet<>(); + expectedSet.add("hive"); + expectedSet.add("hdfs"); + expectedSet.add("knox"); + Set testSet = new HashSet<>(); + Set actualSet = jsonUtil.writeJsonToJavaObject(jsonString, testSet.getClass()); + Assert.assertEquals(expectedSet, actualSet); + } +} diff --git a/security-admin/src/test/java/org/apache/ranger/common/TestPropertiesUtil.java b/security-admin/src/test/java/org/apache/ranger/common/TestPropertiesUtil.java index 959fede242..b27f13cfe8 100644 --- a/security-admin/src/test/java/org/apache/ranger/common/TestPropertiesUtil.java +++ b/security-admin/src/test/java/org/apache/ranger/common/TestPropertiesUtil.java @@ -23,110 +23,106 @@ import org.springframework.beans.factory.annotation.Autowired; public class TestPropertiesUtil { + @Rule + public ExpectedException thrown = ExpectedException.none(); + @Autowired + PropertiesUtil propertiesUtil; - @Autowired - PropertiesUtil propertiesUtil; - - @Rule - public ExpectedException thrown = ExpectedException.none(); - - @Test - public void testGetPropertyNull() { - String key=null; - String defaultValue="test"; - String value= PropertiesUtil.getProperty(key, defaultValue); - Assert.assertNull(value); - } - - @Test - public void testGetProperty() { - String key="1"; - String defaultValue="test"; - String value= PropertiesUtil.getProperty(key, defaultValue); - Assert.assertNotNull(value); - } - - @Test - public void testgetPropertyNullValue(){ - String key=null; - String value = PropertiesUtil.getProperty(key); - Assert.assertNull(value); - } - - @Test - public void testGetIntPropertyNull1(){ - String key=null; - Integer value = PropertiesUtil.getIntProperty(key); - Assert.assertNull(value); - } - - @Test - public void testGetIntPropertyl1(){ - String key="1"; - Integer value= PropertiesUtil.getIntProperty(key); - Assert.assertNull(value); - } - - @Test - public void testGetIntPropertyNull(){ - String key=null; - int defaultValue=0; - Integer value = PropertiesUtil.getIntProperty(key, defaultValue); - Assert.assertNotNull(value); - Assert.assertEquals(value.intValue(), defaultValue); - } - - @Test - public void testGetIntPropertyl(){ - String key="1"; - int defaultValue=1; - Integer value= PropertiesUtil.getIntProperty(key, defaultValue); - Assert.assertEquals(value, Integer.valueOf(defaultValue)); - } - - @Test - public void testGetLongProperty(){ - String key="longKey"; - long defaultValue=23L; - Long value = PropertiesUtil.getLongProperty(key, defaultValue); - Assert.assertNotNull(value); - Assert.assertEquals(value.intValue(), defaultValue); - } - - @Test - public void testGetBooleanPropertyNull() { - String key = null; - boolean defaultValue = true; - boolean returnAvlue = PropertiesUtil.getBooleanProperty(key , defaultValue); - Assert.assertTrue(returnAvlue); - } - - @Test - public void testGetBooleanProperty() { - String key = "1"; - boolean defaultValue = true; - boolean returnAvlue = PropertiesUtil.getBooleanProperty(key , defaultValue); - Assert.assertTrue(returnAvlue); - } - - @Test - public void testGetPropertyStringListForNull(){ - String key = null; - PropertiesUtil.getPropertyStringList(key); - Assert.assertNull(key); - } - - @Test - public void testGetPropertyStringList(){ - String key = "ranger.users.roles.list"; - - PropertiesUtil.getPropertiesMap().put("ranger.users.roles.list", "read,write,access"); - String[] actualroles = PropertiesUtil.getPropertyStringList(key); - - Assert.assertEquals("read", actualroles[0]); - Assert.assertEquals("write", actualroles[1]); - Assert.assertEquals("access", actualroles[2]); - - } - -} \ No newline at end of file + @Test + public void testGetPropertyNull() { + String key = null; + String defaultValue = "test"; + String value = PropertiesUtil.getProperty(key, defaultValue); + Assert.assertNull(value); + } + + @Test + public void testGetProperty() { + String key = "1"; + String defaultValue = "test"; + String value = PropertiesUtil.getProperty(key, defaultValue); + Assert.assertNotNull(value); + } + + @Test + public void testgetPropertyNullValue() { + String key = null; + String value = PropertiesUtil.getProperty(key); + Assert.assertNull(value); + } + + @Test + public void testGetIntPropertyNull1() { + String key = null; + Integer value = PropertiesUtil.getIntProperty(key); + Assert.assertNull(value); + } + + @Test + public void testGetIntPropertyl1() { + String key = "1"; + Integer value = PropertiesUtil.getIntProperty(key); + Assert.assertNull(value); + } + + @Test + public void testGetIntPropertyNull() { + String key = null; + int defaultValue = 0; + Integer value = PropertiesUtil.getIntProperty(key, defaultValue); + Assert.assertNotNull(value); + Assert.assertEquals(value.intValue(), defaultValue); + } + + @Test + public void testGetIntPropertyl() { + String key = "1"; + int defaultValue = 1; + Integer value = PropertiesUtil.getIntProperty(key, defaultValue); + Assert.assertEquals(value, Integer.valueOf(defaultValue)); + } + + @Test + public void testGetLongProperty() { + String key = "longKey"; + long defaultValue = 23L; + Long value = PropertiesUtil.getLongProperty(key, defaultValue); + Assert.assertNotNull(value); + Assert.assertEquals(defaultValue, value.intValue()); + } + + @Test + public void testGetBooleanPropertyNull() { + String key = null; + boolean defaultValue = true; + boolean returnValue = PropertiesUtil.getBooleanProperty(key, defaultValue); + Assert.assertTrue(returnValue); + } + + @Test + public void testGetBooleanProperty() { + String key = "1"; + boolean defaultValue = true; + boolean returnValue = PropertiesUtil.getBooleanProperty(key, defaultValue); + Assert.assertTrue(returnValue); + } + + @Test + public void testGetPropertyStringListForNull() { + String key = null; + PropertiesUtil.getPropertyStringList(key); + Assert.assertNull(key); + } + + @Test + public void testGetPropertyStringList() { + String key = "ranger.users.roles.list"; + + PropertiesUtil.getPropertiesMap().put("ranger.users.roles.list", "read,write,access"); + String[] actualRoles = PropertiesUtil.getPropertyStringList(key); + + Assert.assertEquals("read", actualRoles[0]); + Assert.assertEquals("write", actualRoles[1]); + Assert.assertEquals("access", actualRoles[2]); + } +} diff --git a/security-admin/src/test/java/org/apache/ranger/common/TestRangerConfigUtil.java b/security-admin/src/test/java/org/apache/ranger/common/TestRangerConfigUtil.java index 19297f89b7..5521e4ed95 100644 --- a/security-admin/src/test/java/org/apache/ranger/common/TestRangerConfigUtil.java +++ b/security-admin/src/test/java/org/apache/ranger/common/TestRangerConfigUtil.java @@ -21,31 +21,30 @@ import org.springframework.beans.factory.annotation.Autowired; public class TestRangerConfigUtil { + @Autowired + RangerConfigUtil xaConfigUtil = new RangerConfigUtil(); - @Autowired - RangerConfigUtil xaConfigUtil = new RangerConfigUtil(); + @Test + public void testGetDefaultMaxRows() { + int maxRow = xaConfigUtil.getDefaultMaxRows(); + Assert.assertEquals(maxRow, xaConfigUtil.defaultMaxRows); + } - @Test - public void testGetDefaultMaxRows() { - int maxrow = xaConfigUtil.getDefaultMaxRows(); - Assert.assertEquals(maxrow,xaConfigUtil.defaultMaxRows ); - } - - @Test - public void testIsAccessFilterEnabled() { - boolean value = xaConfigUtil.isAccessFilterEnabled(); + @Test + public void testIsAccessFilterEnabled() { + boolean value = xaConfigUtil.isAccessFilterEnabled(); Assert.assertTrue(value); - } - - @Test - public void testGetWebAppRootURL(){ - String returnValue = xaConfigUtil.getWebAppRootURL(); - Assert.assertEquals(returnValue,xaConfigUtil.webappRootURL); - } - - @Test - public void testGetRoles(){ - String[] str=xaConfigUtil.getRoles(); - Assert.assertArrayEquals(str, xaConfigUtil.roles); - } -} \ No newline at end of file + } + + @Test + public void testGetWebAppRootURL() { + String returnValue = xaConfigUtil.getWebAppRootURL(); + Assert.assertEquals(returnValue, xaConfigUtil.webappRootURL); + } + + @Test + public void testGetRoles() { + String[] str = xaConfigUtil.getRoles(); + Assert.assertArrayEquals(str, xaConfigUtil.roles); + } +} diff --git a/security-admin/src/test/java/org/apache/ranger/common/TestRangerSearchUtil.java b/security-admin/src/test/java/org/apache/ranger/common/TestRangerSearchUtil.java index 8c73ebbea0..41bcb9a31c 100644 --- a/security-admin/src/test/java/org/apache/ranger/common/TestRangerSearchUtil.java +++ b/security-admin/src/test/java/org/apache/ranger/common/TestRangerSearchUtil.java @@ -24,111 +24,109 @@ import java.util.List; public class TestRangerSearchUtil { - private final RangerSearchUtil searchUtil = new RangerSearchUtil(); - private final List searchFields = new ArrayList<>(); - - private static final String SEARCH_PARAM_ID = "id"; - private static final String SEARCH_PARAM_NAME = "name"; - private static final String SEARCH_PARAM_NAME_CONTAINS = "nameContains"; - private static final String SEARCH_PARAM_IS_ENABLED = "isEnabled"; - private static final String SEARCH_PARAM_CREATED_TIME = "createdTime"; - private static final String SEARCH_PARAM_CREATED_TIME_FROM = "createdTimeFrom"; - private static final String SEARCH_PARAM_CREATED_TIME_TO = "createdTimeTo"; - private static final String SEARCH_PARAM_EXCLUDE_ID = "excludeId"; - private static final String SEARCH_PARAM_EXCLUDE_NAME = "excludeName"; - - private static final String WHERE_PREFIX = "WHERE 1 = 1 "; - private static final String WHERE_PREFIX_AND = WHERE_PREFIX + " and "; - - public TestRangerSearchUtil() { - searchFields.add(new SearchField(SEARCH_PARAM_ID, "obj.id", SearchField.DATA_TYPE.INTEGER, SearchField.SEARCH_TYPE.FULL)); - searchFields.add(new SearchField(SEARCH_PARAM_NAME, "obj.name", SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.FULL)); - searchFields.add(new SearchField(SEARCH_PARAM_IS_ENABLED, "obj.isEnabled", SearchField.DATA_TYPE.BOOLEAN, SearchField.SEARCH_TYPE.FULL)); - searchFields.add(new SearchField(SEARCH_PARAM_CREATED_TIME, "obj.createdTime", SearchField.DATA_TYPE.DATE, SearchField.SEARCH_TYPE.FULL)); - searchFields.add(new SearchField(SEARCH_PARAM_NAME_CONTAINS, "obj.name", SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.PARTIAL)); - searchFields.add(new SearchField(SEARCH_PARAM_CREATED_TIME_FROM, "obj.createdTime", SearchField.DATA_TYPE.DATE, SearchField.SEARCH_TYPE.GREATER_EQUAL_THAN)); - searchFields.add(new SearchField(SEARCH_PARAM_CREATED_TIME_TO, "obj.createdTime", SearchField.DATA_TYPE.DATE, SearchField.SEARCH_TYPE.LESS_THAN)); - searchFields.add(new SearchField(SEARCH_PARAM_EXCLUDE_ID, "obj.id", SearchField.DATA_TYPE.INTEGER, SearchField.SEARCH_TYPE.NOT_EQUALS)); - searchFields.add(new SearchField(SEARCH_PARAM_EXCLUDE_NAME, "obj.name", SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.NOT_EQUALS)); - } - - @Test - public void testEmptyCriteria() { - SearchCriteria criteria = new SearchCriteria(); - String whereClause = searchUtil.buildWhereClause(criteria, searchFields).toString(); - - Assert.assertEquals(WHERE_PREFIX, whereClause); - } - - @Test - public void testIntEquals() { - SearchCriteria criteria = new SearchCriteria(SEARCH_PARAM_ID, 1); - String whereClause = searchUtil.buildWhereClause(criteria, searchFields).toString(); - - Assert.assertEquals(WHERE_PREFIX_AND + "obj.id = :id", whereClause); - } - - @Test - public void testStringEquals() { - SearchCriteria criteria = new SearchCriteria(SEARCH_PARAM_NAME, "test-name"); - String whereClause = searchUtil.buildWhereClause(criteria, searchFields).toString(); - - Assert.assertEquals(WHERE_PREFIX_AND + "LOWER(obj.name) = :name", whereClause); - } - - @Test - public void testBooleanEquals() { - SearchCriteria criteria = new SearchCriteria(SEARCH_PARAM_IS_ENABLED, false); - String whereClause = searchUtil.buildWhereClause(criteria, searchFields).toString(); - - Assert.assertEquals(WHERE_PREFIX_AND + "obj.isEnabled = :isEnabled", whereClause); - } - - @Test - public void testDateEquals() { - SearchCriteria criteria = new SearchCriteria(SEARCH_PARAM_CREATED_TIME, new Date()); - String whereClause = searchUtil.buildWhereClause(criteria, searchFields).toString(); - - Assert.assertEquals(WHERE_PREFIX_AND + "obj.createdTime = :createdTime", whereClause); - } - - @Test - public void testStringContains() { - SearchCriteria criteria = new SearchCriteria(SEARCH_PARAM_NAME_CONTAINS, "test-name"); - String whereClause = searchUtil.buildWhereClause(criteria, searchFields).toString(); - - Assert.assertEquals(WHERE_PREFIX_AND + "LOWER(obj.name) like :nameContains", whereClause); - } - - @Test - public void testDateFrom() { - SearchCriteria criteria = new SearchCriteria(SEARCH_PARAM_CREATED_TIME_FROM, new Date()); - String whereClause = searchUtil.buildWhereClause(criteria, searchFields).toString(); - - Assert.assertEquals(WHERE_PREFIX_AND + "obj.createdTime >= :createdTimeFrom", whereClause); - } - - @Test - public void testDateTo() { - SearchCriteria criteria = new SearchCriteria(SEARCH_PARAM_CREATED_TIME_TO, new Date()); - String whereClause = searchUtil.buildWhereClause(criteria, searchFields).toString(); - - Assert.assertEquals(WHERE_PREFIX_AND + "obj.createdTime < :createdTimeTo", whereClause); - } - - @Test - public void testIntNotEquals() { - SearchCriteria criteria = new SearchCriteria(SEARCH_PARAM_EXCLUDE_ID, 1); - String whereClause = searchUtil.buildWhereClause(criteria, searchFields).toString(); - - Assert.assertEquals(WHERE_PREFIX_AND + "obj.id != :excludeId", whereClause); - } - - @Test - public void testStringNotEquals() { - SearchCriteria criteria = new SearchCriteria(SEARCH_PARAM_EXCLUDE_NAME, "test-name"); - String whereClause = searchUtil.buildWhereClause(criteria, searchFields).toString(); - - Assert.assertEquals(WHERE_PREFIX_AND + "LOWER(obj.name) != :excludeName", whereClause); - } -} \ No newline at end of file + private static final String SEARCH_PARAM_ID = "id"; + private static final String SEARCH_PARAM_NAME = "name"; + private static final String SEARCH_PARAM_NAME_CONTAINS = "nameContains"; + private static final String SEARCH_PARAM_IS_ENABLED = "isEnabled"; + private static final String SEARCH_PARAM_CREATED_TIME = "createdTime"; + private static final String SEARCH_PARAM_CREATED_TIME_FROM = "createdTimeFrom"; + private static final String SEARCH_PARAM_CREATED_TIME_TO = "createdTimeTo"; + private static final String SEARCH_PARAM_EXCLUDE_ID = "excludeId"; + private static final String SEARCH_PARAM_EXCLUDE_NAME = "excludeName"; + private static final String WHERE_PREFIX = "WHERE 1 = 1 "; + private static final String WHERE_PREFIX_AND = WHERE_PREFIX + " and "; + private final RangerSearchUtil searchUtil = new RangerSearchUtil(); + private final List searchFields = new ArrayList<>(); + + public TestRangerSearchUtil() { + searchFields.add(new SearchField(SEARCH_PARAM_ID, "obj.id", SearchField.DATA_TYPE.INTEGER, SearchField.SEARCH_TYPE.FULL)); + searchFields.add(new SearchField(SEARCH_PARAM_NAME, "obj.name", SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.FULL)); + searchFields.add(new SearchField(SEARCH_PARAM_IS_ENABLED, "obj.isEnabled", SearchField.DATA_TYPE.BOOLEAN, SearchField.SEARCH_TYPE.FULL)); + searchFields.add(new SearchField(SEARCH_PARAM_CREATED_TIME, "obj.createdTime", SearchField.DATA_TYPE.DATE, SearchField.SEARCH_TYPE.FULL)); + searchFields.add(new SearchField(SEARCH_PARAM_NAME_CONTAINS, "obj.name", SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.PARTIAL)); + searchFields.add(new SearchField(SEARCH_PARAM_CREATED_TIME_FROM, "obj.createdTime", SearchField.DATA_TYPE.DATE, SearchField.SEARCH_TYPE.GREATER_EQUAL_THAN)); + searchFields.add(new SearchField(SEARCH_PARAM_CREATED_TIME_TO, "obj.createdTime", SearchField.DATA_TYPE.DATE, SearchField.SEARCH_TYPE.LESS_THAN)); + searchFields.add(new SearchField(SEARCH_PARAM_EXCLUDE_ID, "obj.id", SearchField.DATA_TYPE.INTEGER, SearchField.SEARCH_TYPE.NOT_EQUALS)); + searchFields.add(new SearchField(SEARCH_PARAM_EXCLUDE_NAME, "obj.name", SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.NOT_EQUALS)); + } + + @Test + public void testEmptyCriteria() { + SearchCriteria criteria = new SearchCriteria(); + String whereClause = searchUtil.buildWhereClause(criteria, searchFields).toString(); + + Assert.assertEquals(WHERE_PREFIX, whereClause); + } + + @Test + public void testIntEquals() { + SearchCriteria criteria = new SearchCriteria(SEARCH_PARAM_ID, 1); + String whereClause = searchUtil.buildWhereClause(criteria, searchFields).toString(); + + Assert.assertEquals(WHERE_PREFIX_AND + "obj.id = :id", whereClause); + } + + @Test + public void testStringEquals() { + SearchCriteria criteria = new SearchCriteria(SEARCH_PARAM_NAME, "test-name"); + String whereClause = searchUtil.buildWhereClause(criteria, searchFields).toString(); + + Assert.assertEquals(WHERE_PREFIX_AND + "LOWER(obj.name) = :name", whereClause); + } + + @Test + public void testBooleanEquals() { + SearchCriteria criteria = new SearchCriteria(SEARCH_PARAM_IS_ENABLED, false); + String whereClause = searchUtil.buildWhereClause(criteria, searchFields).toString(); + + Assert.assertEquals(WHERE_PREFIX_AND + "obj.isEnabled = :isEnabled", whereClause); + } + + @Test + public void testDateEquals() { + SearchCriteria criteria = new SearchCriteria(SEARCH_PARAM_CREATED_TIME, new Date()); + String whereClause = searchUtil.buildWhereClause(criteria, searchFields).toString(); + + Assert.assertEquals(WHERE_PREFIX_AND + "obj.createdTime = :createdTime", whereClause); + } + + @Test + public void testStringContains() { + SearchCriteria criteria = new SearchCriteria(SEARCH_PARAM_NAME_CONTAINS, "test-name"); + String whereClause = searchUtil.buildWhereClause(criteria, searchFields).toString(); + + Assert.assertEquals(WHERE_PREFIX_AND + "LOWER(obj.name) like :nameContains", whereClause); + } + + @Test + public void testDateFrom() { + SearchCriteria criteria = new SearchCriteria(SEARCH_PARAM_CREATED_TIME_FROM, new Date()); + String whereClause = searchUtil.buildWhereClause(criteria, searchFields).toString(); + + Assert.assertEquals(WHERE_PREFIX_AND + "obj.createdTime >= :createdTimeFrom", whereClause); + } + + @Test + public void testDateTo() { + SearchCriteria criteria = new SearchCriteria(SEARCH_PARAM_CREATED_TIME_TO, new Date()); + String whereClause = searchUtil.buildWhereClause(criteria, searchFields).toString(); + + Assert.assertEquals(WHERE_PREFIX_AND + "obj.createdTime < :createdTimeTo", whereClause); + } + + @Test + public void testIntNotEquals() { + SearchCriteria criteria = new SearchCriteria(SEARCH_PARAM_EXCLUDE_ID, 1); + String whereClause = searchUtil.buildWhereClause(criteria, searchFields).toString(); + + Assert.assertEquals(WHERE_PREFIX_AND + "obj.id != :excludeId", whereClause); + } + + @Test + public void testStringNotEquals() { + SearchCriteria criteria = new SearchCriteria(SEARCH_PARAM_EXCLUDE_NAME, "test-name"); + String whereClause = searchUtil.buildWhereClause(criteria, searchFields).toString(); + + Assert.assertEquals(WHERE_PREFIX_AND + "LOWER(obj.name) != :excludeName", whereClause); + } +} diff --git a/security-admin/src/test/java/org/apache/ranger/common/TestServiceUtil.java b/security-admin/src/test/java/org/apache/ranger/common/TestServiceUtil.java index 69ac2db9fc..8f03ed0d6e 100644 --- a/security-admin/src/test/java/org/apache/ranger/common/TestServiceUtil.java +++ b/security-admin/src/test/java/org/apache/ranger/common/TestServiceUtil.java @@ -19,14 +19,6 @@ package org.apache.ranger.common; -import java.util.ArrayList; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.servlet.http.HttpServletRequest; - import org.apache.ranger.biz.ServiceDBStore; import org.apache.ranger.db.RangerDaoManager; import org.apache.ranger.db.XXGroupDao; @@ -55,1848 +47,1767 @@ import org.mockito.Mockito; import org.mockito.junit.MockitoJUnitRunner; -@RunWith(MockitoJUnitRunner.class) -public class TestServiceUtil { - - @InjectMocks - ServiceUtil serviceUtil = new ServiceUtil(); - - @Mock - ServiceDBStore svcStore; - - @Mock - JSONUtil jsonUtil; - - @Mock - RangerDaoManager xaDaoMgr; - - @Mock - XXUserDao xxUserDao; - - @Mock - XXGroupDao xxGroupDao; - - @Test - public void testGetServiceByName() throws Exception{ - RangerService expectedRangerService = new RangerService(); - expectedRangerService.setId(1L); - expectedRangerService.setName("hdfs"); - Mockito.when(svcStore.getServiceByName("hdfs")).thenReturn(expectedRangerService); - RangerService actualRangerService = serviceUtil.getServiceByName("hdfs"); - - Assert.assertEquals(expectedRangerService.getName(), actualRangerService.getName()); - Assert.assertEquals(expectedRangerService.getId(), actualRangerService.getId()); - } - - @Test - public void testToRangerServiceForNull(){ - VXAsset vXAsset = null; - RangerService actualRangerService = serviceUtil.toRangerService(vXAsset); - Assert.assertNull(actualRangerService); - - } - @Test - public void testToRangerService(){ - Map map = new HashMap(); - RangerService expectedRangerService = new RangerService(); - expectedRangerService.setId(1L); - expectedRangerService.setName("hive"); - expectedRangerService.setDescription("hive Description"); - map.put("config", "hiveConfig"); - VXAsset vXAsset = new VXAsset(); - vXAsset.setId(1L); - vXAsset.setCreateDate(new Date()); - vXAsset.setUpdateDate(new Date()); - vXAsset.setOwner("ranger"); - vXAsset.setUpdatedBy("rangerAdmin"); - vXAsset.setAssetType(5); - vXAsset.setName("hive"); - vXAsset.setDescription("hive Description"); - vXAsset.setActiveStatus(1); - vXAsset.setConfig("{config : hiveConfig}"); - Mockito.when(jsonUtil.jsonToMap("{config : hiveConfig}")).thenReturn(map); - - RangerService actualRangerService = serviceUtil.toRangerService(vXAsset); - - Assert.assertNotNull(actualRangerService); - Assert.assertEquals(actualRangerService.getId(), expectedRangerService.getId()); - Assert.assertEquals(actualRangerService.getName(), expectedRangerService.getName()); - Assert.assertEquals(actualRangerService.getDescription(), expectedRangerService.getDescription()); - Assert.assertTrue(actualRangerService.getIsEnabled()); - - - } - @Test - public void testToVXAssetForNull(){ - RangerService rangerService = null; - VXAsset actualVXAsset = serviceUtil.toVXAsset(rangerService); - Assert.assertNull(actualVXAsset); - - } - - @Test - public void testToVXAsset(){ - RangerService rangerService = new RangerService(); - VXAsset expectedVXAssesst = new VXAsset(); - expectedVXAssesst.setId(1L); - expectedVXAssesst.setName("hive"); - expectedVXAssesst.setDescription("hive Description"); - expectedVXAssesst.setActiveStatus(1); - - Map map = new HashMap(); - map.put("config", "hiveConfig"); - rangerService.setId(1L); - rangerService.setCreateTime(new Date()); - rangerService.setUpdateTime(new Date()); - rangerService.setCreatedBy("ranger"); - rangerService.setUpdatedBy("rangerAdmin"); - - rangerService.setType("hive"); - rangerService.setName("hive"); - rangerService.setDescription("hive Description"); - rangerService.setIsEnabled(true); - rangerService.setConfigs(map); - - Mockito.when(jsonUtil.readMapToString(map)).thenReturn("{config : hiveConfig}"); - - VXAsset actualVXAsset = serviceUtil.toVXAsset(rangerService); - - Assert.assertNotNull(actualVXAsset); - Assert.assertEquals(actualVXAsset.getId(), expectedVXAssesst.getId()); - Assert.assertEquals(actualVXAsset.getName(), expectedVXAssesst.getName()); - Assert.assertEquals(actualVXAsset.getDescription(), expectedVXAssesst.getDescription()); - Assert.assertEquals(actualVXAsset.getActiveStatus(), RangerCommonEnums.STATUS_ENABLED); - - } - - - @Test - public void testToVXRepositoryForNull(){ - RangerService rangerService = null; - VXRepository actualvXRepository = serviceUtil.toVXRepository(rangerService); - Assert.assertNull(actualvXRepository); - - } - - @Test - public void testToVXRepository(){ - Map map = new HashMap(); - map.put("config", "hiveConfig"); - VXRepository expectedVXRepository = new VXRepository(); - expectedVXRepository.setRepositoryType("hive"); - expectedVXRepository.setName("hive"); - expectedVXRepository.setDescription("hive Description"); - expectedVXRepository.setIsActive(true); - expectedVXRepository.setVersion("3"); - - RangerService rangerService = new RangerService(); - rangerService.setId(1L); - rangerService.setCreateTime(new Date()); - rangerService.setUpdateTime(new Date()); - rangerService.setCreatedBy("ranger"); - rangerService.setUpdatedBy("rangerAdmin"); - rangerService.setType("hive"); - rangerService.setName("hive"); - rangerService.setDescription("hive Description"); - rangerService.setIsEnabled(true); - rangerService.setConfigs(map); - rangerService.setVersion(3L); - - Mockito.when(jsonUtil.readMapToString(map)).thenReturn("{config : hiveConfig}"); - - VXRepository actualvXRepository = serviceUtil.toVXRepository(rangerService); - Assert.assertNotNull(actualvXRepository); - Assert.assertEquals(actualvXRepository.getRepositoryType(), expectedVXRepository.getRepositoryType()); - Assert.assertEquals(actualvXRepository.getName(), expectedVXRepository.getName()); - Assert.assertEquals(actualvXRepository.getDescription(), expectedVXRepository.getDescription()); - Assert.assertTrue(actualvXRepository.getIsActive()); - Assert.assertEquals(actualvXRepository.getVersion(), expectedVXRepository.getVersion()); - - } - - @Test - public void testToRangerPolicyForNull(){ - VXResource resource = null; - RangerService rangerService = null; - RangerPolicy actualRangerPolicy = serviceUtil.toRangerPolicy(resource, rangerService); - Assert.assertNull(actualRangerPolicy); - } - - @Test - public void testToRangerPolicyForResourceTypePath(){ - RangerPolicy expectedRangerPolicy = new RangerPolicy(); - expectedRangerPolicy.setId(1L); - expectedRangerPolicy.setName("hive Policy"); - expectedRangerPolicy.setService("hive"); - expectedRangerPolicy.setDescription("hive policy description"); - - Map expectedMap = new HashMap(); - List valuesList = new ArrayList(); - valuesList.add("resource"); - - - VXAuditMap vXAuditMap = new VXAuditMap(); - vXAuditMap.setId(1L); - vXAuditMap.setOwner("rangerAdmin"); - List vXAuditMapList = new ArrayList(); - vXAuditMapList.add(vXAuditMap); - - RangerPolicyResource rangerPolicyResource = new RangerPolicyResource(); - rangerPolicyResource.setIsExcludes(false); - rangerPolicyResource.setIsRecursive(true); - rangerPolicyResource.setValue("/localhost/files"); - rangerPolicyResource.setValues(valuesList); - - expectedMap.put("path", rangerPolicyResource); - - expectedRangerPolicy.setResources(expectedMap); - - RangerService rangerService = new RangerService(); - rangerService.setName("hive"); - - - VXResource resource = new VXResource(); - resource.setId(1L); - resource.setName("resource"); - resource.setUpdateDate(new Date()); - resource.setCreateDate(new Date()); - resource.setOwner("rangerAdmin"); - resource.setUpdatedBy("rangerAdmin"); - resource.setPolicyName("hive Policy"); - resource.setDescription("hive policy description"); - resource.setResourceStatus(RangerCommonEnums.STATUS_ENABLED); - resource.setIsRecursive(1); - resource.setTableType(1); - resource.setColumnType(1); - - RangerPolicy actualRangerPolicy = serviceUtil.toRangerPolicy(resource, rangerService); - - Assert.assertNotNull(actualRangerPolicy); - Assert.assertEquals(expectedRangerPolicy.getId(), actualRangerPolicy.getId()); - Assert.assertEquals(expectedRangerPolicy.getName(), actualRangerPolicy.getName()); - Assert.assertEquals(expectedRangerPolicy.getService(), actualRangerPolicy.getService()); - Assert.assertEquals(expectedRangerPolicy.getDescription(), actualRangerPolicy.getDescription()); - Assert.assertEquals(expectedRangerPolicy.getResources(), actualRangerPolicy.getResources()); - - } - - @Test - public void testToRangerPolicyForResourceTypeTable(){ - - RangerPolicy expectedRangerPolicy = new RangerPolicy(); - expectedRangerPolicy.setId(1L); - expectedRangerPolicy.setName("hive Policy"); - expectedRangerPolicy.setService("hive"); - expectedRangerPolicy.setDescription("hive policy description"); - - Map expectedMap = new HashMap(); - List valuesList = new ArrayList(); - valuesList.add("xa_service"); - - - VXAuditMap vXAuditMap = new VXAuditMap(); - vXAuditMap.setId(1L); - vXAuditMap.setOwner("rangerAdmin"); - List vXAuditMapList = new ArrayList(); - vXAuditMapList.add(vXAuditMap); - - RangerPolicyResource rangerPolicyResource = new RangerPolicyResource(); - rangerPolicyResource.setIsExcludes(true); - rangerPolicyResource.setIsRecursive(false); - rangerPolicyResource.setValue("xa_service"); - rangerPolicyResource.setValues(valuesList); - - expectedMap.put("table", rangerPolicyResource); - - expectedRangerPolicy.setResources(expectedMap); - - RangerService rangerService = new RangerService(); - rangerService.setName("hive"); - - - VXResource resource = new VXResource(); - resource.setId(1L); - resource.setTables("xa_service"); - resource.setUpdateDate(new Date()); - resource.setCreateDate(new Date()); - resource.setOwner("rangerAdmin"); - resource.setUpdatedBy("rangerAdmin"); - resource.setPolicyName("hive Policy"); - resource.setDescription("hive policy description"); - resource.setResourceStatus(RangerCommonEnums.STATUS_ENABLED); - resource.setIsRecursive(1); - resource.setTableType(1); - resource.setColumnType(1); - - RangerPolicy actualRangerPolicy = serviceUtil.toRangerPolicy(resource, rangerService); - - Assert.assertNotNull(actualRangerPolicy); - Assert.assertEquals(expectedRangerPolicy.getId(), actualRangerPolicy.getId()); - Assert.assertEquals(expectedRangerPolicy.getName(), actualRangerPolicy.getName()); - Assert.assertEquals(expectedRangerPolicy.getService(), actualRangerPolicy.getService()); - Assert.assertEquals(expectedRangerPolicy.getDescription(), actualRangerPolicy.getDescription()); - Assert.assertEquals(expectedRangerPolicy.getResources(), actualRangerPolicy.getResources()); - - - } - - @Test - public void testToRangerPolicyForResourceTypeColumnFamily(){ - - RangerPolicy expectedRangerPolicy = new RangerPolicy(); - expectedRangerPolicy.setId(1L); - expectedRangerPolicy.setName("hive Policy"); - expectedRangerPolicy.setService("hive"); - expectedRangerPolicy.setDescription("hive policy description"); - - Map expectedMap = new HashMap(); - List valuesList = new ArrayList(); - valuesList.add("columnFamilies"); - - - VXAuditMap vXAuditMap = new VXAuditMap(); - vXAuditMap.setId(1L); - vXAuditMap.setOwner("rangerAdmin"); - List vXAuditMapList = new ArrayList(); - vXAuditMapList.add(vXAuditMap); - - RangerPolicyResource rangerPolicyResource = new RangerPolicyResource(); - rangerPolicyResource.setIsExcludes(false); - rangerPolicyResource.setIsRecursive(false); - rangerPolicyResource.setValue("columnFamilies"); - rangerPolicyResource.setValues(valuesList); - - expectedMap.put("column-family", rangerPolicyResource); - - expectedRangerPolicy.setResources(expectedMap); - - RangerService rangerService = new RangerService(); - rangerService.setName("hive"); - - - VXResource resource = new VXResource(); - resource.setId(1L); - resource.setColumnFamilies("columnFamilies"); - resource.setUpdateDate(new Date()); - resource.setCreateDate(new Date()); - resource.setOwner("rangerAdmin"); - resource.setUpdatedBy("rangerAdmin"); - resource.setPolicyName("hive Policy"); - resource.setDescription("hive policy description"); - resource.setResourceStatus(RangerCommonEnums.STATUS_ENABLED); - resource.setIsRecursive(1); - resource.setTableType(1); - resource.setColumnType(1); - - RangerPolicy actualRangerPolicy = serviceUtil.toRangerPolicy(resource, rangerService); - - Assert.assertNotNull(actualRangerPolicy); - Assert.assertEquals(expectedRangerPolicy.getId(), actualRangerPolicy.getId()); - Assert.assertEquals(expectedRangerPolicy.getName(), actualRangerPolicy.getName()); - Assert.assertEquals(expectedRangerPolicy.getService(), actualRangerPolicy.getService()); - Assert.assertEquals(expectedRangerPolicy.getDescription(), actualRangerPolicy.getDescription()); - Assert.assertEquals(expectedRangerPolicy.getResources(), actualRangerPolicy.getResources()); - - } - - @Test - public void testToRangerPolicyForResourceTypeColumn(){ - - RangerPolicy expectedRangerPolicy = new RangerPolicy(); - expectedRangerPolicy.setId(1L); - expectedRangerPolicy.setName("hive Policy"); - expectedRangerPolicy.setService("hive"); - expectedRangerPolicy.setDescription("hive policy description"); - - Map expectedMap = new HashMap(); - List valuesList = new ArrayList(); - valuesList.add("column"); - - - VXAuditMap vXAuditMap = new VXAuditMap(); - vXAuditMap.setId(1L); - vXAuditMap.setOwner("rangerAdmin"); - List vXAuditMapList = new ArrayList(); - vXAuditMapList.add(vXAuditMap); - - RangerPolicyResource rangerPolicyResource = new RangerPolicyResource(); - rangerPolicyResource.setIsExcludes(true); - rangerPolicyResource.setIsRecursive(false); - rangerPolicyResource.setValue("column"); - rangerPolicyResource.setValues(valuesList); - - expectedMap.put("column", rangerPolicyResource); - - expectedRangerPolicy.setResources(expectedMap); - - RangerService rangerService = new RangerService(); - rangerService.setName("hive"); - - - VXResource resource = new VXResource(); - resource.setId(1L); - resource.setColumns("column"); - resource.setUpdateDate(new Date()); - resource.setCreateDate(new Date()); - resource.setOwner("rangerAdmin"); - resource.setUpdatedBy("rangerAdmin"); - resource.setPolicyName("hive Policy"); - resource.setDescription("hive policy description"); - resource.setResourceStatus(RangerCommonEnums.STATUS_ENABLED); - resource.setIsRecursive(1); - resource.setTableType(1); - resource.setColumnType(1); - - RangerPolicy actualRangerPolicy = serviceUtil.toRangerPolicy(resource, rangerService); - - Assert.assertNotNull(actualRangerPolicy); - Assert.assertEquals(expectedRangerPolicy.getId(), actualRangerPolicy.getId()); - Assert.assertEquals(expectedRangerPolicy.getName(), actualRangerPolicy.getName()); - Assert.assertEquals(expectedRangerPolicy.getService(), actualRangerPolicy.getService()); - Assert.assertEquals(expectedRangerPolicy.getDescription(), actualRangerPolicy.getDescription()); - Assert.assertEquals(expectedRangerPolicy.getResources(), actualRangerPolicy.getResources()); - - } - - @Test - public void testToRangerPolicyForResourceTypeDatabase(){ - - RangerPolicy expectedRangerPolicy = new RangerPolicy(); - expectedRangerPolicy.setId(1L); - expectedRangerPolicy.setName("hive Policy"); - expectedRangerPolicy.setService("hive"); - expectedRangerPolicy.setDescription("hive policy description"); - - Map expectedMap = new HashMap(); - List valuesList = new ArrayList(); - valuesList.add("databases"); - - - VXAuditMap vXAuditMap = new VXAuditMap(); - vXAuditMap.setId(1L); - vXAuditMap.setOwner("rangerAdmin"); - List vXAuditMapList = new ArrayList(); - vXAuditMapList.add(vXAuditMap); - - RangerPolicyResource rangerPolicyResource = new RangerPolicyResource(); - rangerPolicyResource.setIsExcludes(false); - rangerPolicyResource.setIsRecursive(false); - rangerPolicyResource.setValue("databases"); - rangerPolicyResource.setValues(valuesList); - - expectedMap.put("database", rangerPolicyResource); - - expectedRangerPolicy.setResources(expectedMap); - - RangerService rangerService = new RangerService(); - rangerService.setName("hive"); - - - VXResource resource = new VXResource(); - resource.setId(1L); - resource.setDatabases("databases"); - resource.setUpdateDate(new Date()); - resource.setCreateDate(new Date()); - resource.setOwner("rangerAdmin"); - resource.setUpdatedBy("rangerAdmin"); - resource.setPolicyName("hive Policy"); - resource.setDescription("hive policy description"); - resource.setResourceStatus(RangerCommonEnums.STATUS_ENABLED); - resource.setIsRecursive(1); - resource.setTableType(1); - resource.setColumnType(1); - - RangerPolicy actualRangerPolicy = serviceUtil.toRangerPolicy(resource, rangerService); - - Assert.assertNotNull(actualRangerPolicy); - Assert.assertEquals(expectedRangerPolicy.getId(), actualRangerPolicy.getId()); - Assert.assertEquals(expectedRangerPolicy.getName(), actualRangerPolicy.getName()); - Assert.assertEquals(expectedRangerPolicy.getService(), actualRangerPolicy.getService()); - Assert.assertEquals(expectedRangerPolicy.getDescription(), actualRangerPolicy.getDescription()); - Assert.assertEquals(expectedRangerPolicy.getResources(), actualRangerPolicy.getResources()); - - } - - @Test - public void testToRangerPolicyForResourceTypeUDF(){ - - RangerPolicy expectedRangerPolicy = new RangerPolicy(); - expectedRangerPolicy.setId(1L); - expectedRangerPolicy.setName("hive Policy"); - expectedRangerPolicy.setService("hive"); - expectedRangerPolicy.setDescription("hive policy description"); - - Map expectedMap = new HashMap(); - List valuesList = new ArrayList(); - valuesList.add("udf"); - - - VXAuditMap vXAuditMap = new VXAuditMap(); - vXAuditMap.setId(1L); - vXAuditMap.setOwner("rangerAdmin"); - List vXAuditMapList = new ArrayList(); - vXAuditMapList.add(vXAuditMap); - - RangerPolicyResource rangerPolicyResource = new RangerPolicyResource(); - rangerPolicyResource.setIsExcludes(false); - rangerPolicyResource.setIsRecursive(false); - rangerPolicyResource.setValue("databases"); - rangerPolicyResource.setValues(valuesList); - - expectedMap.put("udf", rangerPolicyResource); - - expectedRangerPolicy.setResources(expectedMap); - - RangerService rangerService = new RangerService(); - rangerService.setName("hive"); - - - VXResource resource = new VXResource(); - resource.setId(1L); - resource.setUdfs("udf"); - resource.setUpdateDate(new Date()); - resource.setCreateDate(new Date()); - resource.setOwner("rangerAdmin"); - resource.setUpdatedBy("rangerAdmin"); - resource.setPolicyName("hive Policy"); - resource.setDescription("hive policy description"); - resource.setResourceStatus(RangerCommonEnums.STATUS_ENABLED); - resource.setIsRecursive(1); - resource.setTableType(1); - resource.setColumnType(1); - - RangerPolicy actualRangerPolicy = serviceUtil.toRangerPolicy(resource, rangerService); - - Assert.assertNotNull(actualRangerPolicy); - Assert.assertEquals(expectedRangerPolicy.getId(), actualRangerPolicy.getId()); - Assert.assertEquals(expectedRangerPolicy.getName(), actualRangerPolicy.getName()); - Assert.assertEquals(expectedRangerPolicy.getService(), actualRangerPolicy.getService()); - Assert.assertEquals(expectedRangerPolicy.getDescription(), actualRangerPolicy.getDescription()); - Assert.assertEquals(expectedRangerPolicy.getResources(), actualRangerPolicy.getResources()); - - } - - @Test - public void testToRangerPolicyForResourceTypeTopology(){ - - RangerPolicy expectedRangerPolicy = new RangerPolicy(); - expectedRangerPolicy.setId(1L); - expectedRangerPolicy.setName("hive Policy"); - expectedRangerPolicy.setService("hive"); - expectedRangerPolicy.setDescription("hive policy description"); - - Map expectedMap = new HashMap(); - List valuesList = new ArrayList(); - valuesList.add("topology"); - - - VXAuditMap vXAuditMap = new VXAuditMap(); - vXAuditMap.setId(1L); - vXAuditMap.setOwner("rangerAdmin"); - List vXAuditMapList = new ArrayList(); - vXAuditMapList.add(vXAuditMap); - - RangerPolicyResource rangerPolicyResource = new RangerPolicyResource(); - rangerPolicyResource.setIsExcludes(false); - rangerPolicyResource.setIsRecursive(false); - rangerPolicyResource.setValue("topology"); - rangerPolicyResource.setValues(valuesList); - - expectedMap.put("topology", rangerPolicyResource); - - expectedRangerPolicy.setResources(expectedMap); - - RangerService rangerService = new RangerService(); - rangerService.setName("hive"); - - - VXResource resource = new VXResource(); - resource.setId(1L); - resource.setTopologies("topology"); - resource.setUpdateDate(new Date()); - resource.setCreateDate(new Date()); - resource.setOwner("rangerAdmin"); - resource.setUpdatedBy("rangerAdmin"); - resource.setPolicyName("hive Policy"); - resource.setDescription("hive policy description"); - resource.setResourceStatus(RangerCommonEnums.STATUS_ENABLED); - resource.setIsRecursive(1); - resource.setTableType(1); - resource.setColumnType(1); - - RangerPolicy actualRangerPolicy = serviceUtil.toRangerPolicy(resource, rangerService); - - Assert.assertNotNull(actualRangerPolicy); - Assert.assertEquals(expectedRangerPolicy.getId(), actualRangerPolicy.getId()); - Assert.assertEquals(expectedRangerPolicy.getName(), actualRangerPolicy.getName()); - Assert.assertEquals(expectedRangerPolicy.getService(), actualRangerPolicy.getService()); - Assert.assertEquals(expectedRangerPolicy.getDescription(), actualRangerPolicy.getDescription()); - Assert.assertEquals(expectedRangerPolicy.getResources(), actualRangerPolicy.getResources()); - - } - - @Test - public void testToRangerPolicyForResourceTypeService(){ - - RangerPolicy expectedRangerPolicy = new RangerPolicy(); - expectedRangerPolicy.setId(1L); - expectedRangerPolicy.setName("hive Policy"); - expectedRangerPolicy.setService("hive"); - expectedRangerPolicy.setDescription("hive policy description"); - - Map expectedMap = new HashMap(); - List valuesList = new ArrayList(); - valuesList.add("service"); - - - VXAuditMap vXAuditMap = new VXAuditMap(); - vXAuditMap.setId(1L); - vXAuditMap.setOwner("rangerAdmin"); - List vXAuditMapList = new ArrayList(); - vXAuditMapList.add(vXAuditMap); - - RangerPolicyResource rangerPolicyResource = new RangerPolicyResource(); - rangerPolicyResource.setIsExcludes(false); - rangerPolicyResource.setIsRecursive(false); - rangerPolicyResource.setValue("service"); - rangerPolicyResource.setValues(valuesList); - - expectedMap.put("service", rangerPolicyResource); - - expectedRangerPolicy.setResources(expectedMap); - - RangerService rangerService = new RangerService(); - rangerService.setName("hive"); - - - VXResource resource = new VXResource(); - resource.setId(1L); - resource.setServices("service"); - resource.setUpdateDate(new Date()); - resource.setCreateDate(new Date()); - resource.setOwner("rangerAdmin"); - resource.setUpdatedBy("rangerAdmin"); - resource.setPolicyName("hive Policy"); - resource.setDescription("hive policy description"); - resource.setResourceStatus(RangerCommonEnums.STATUS_ENABLED); - resource.setIsRecursive(1); - resource.setTableType(1); - resource.setColumnType(1); - - RangerPolicy actualRangerPolicy = serviceUtil.toRangerPolicy(resource, rangerService); - - Assert.assertNotNull(actualRangerPolicy); - Assert.assertEquals(expectedRangerPolicy.getId(), actualRangerPolicy.getId()); - Assert.assertEquals(expectedRangerPolicy.getName(), actualRangerPolicy.getName()); - Assert.assertEquals(expectedRangerPolicy.getService(), actualRangerPolicy.getService()); - Assert.assertEquals(expectedRangerPolicy.getDescription(), actualRangerPolicy.getDescription()); - Assert.assertEquals(expectedRangerPolicy.getResources(), actualRangerPolicy.getResources()); - - } - - @Test - public void testToRangerPolicyForResourceTypeHiveService(){ - - RangerPolicy expectedRangerPolicy = new RangerPolicy(); - expectedRangerPolicy.setId(1L); - expectedRangerPolicy.setName("hive Policy"); - expectedRangerPolicy.setService("hive"); - expectedRangerPolicy.setDescription("hive policy description"); - - Map expectedMap = new HashMap(); - List valuesList = new ArrayList(); - valuesList.add("hiveservice"); - - - VXAuditMap vXAuditMap = new VXAuditMap(); - vXAuditMap.setId(1L); - vXAuditMap.setOwner("rangerAdmin"); - List vXAuditMapList = new ArrayList(); - vXAuditMapList.add(vXAuditMap); - - RangerPolicyResource rangerPolicyResource = new RangerPolicyResource(); - rangerPolicyResource.setIsExcludes(false); - rangerPolicyResource.setIsRecursive(false); - rangerPolicyResource.setValue("hiveservice"); - rangerPolicyResource.setValues(valuesList); - - expectedMap.put("service", rangerPolicyResource); - - expectedRangerPolicy.setResources(expectedMap); - - RangerService rangerService = new RangerService(); - rangerService.setName("hive"); - - - VXResource resource = new VXResource(); - resource.setId(1L); - resource.setServices("hiveservice"); - resource.setUpdateDate(new Date()); - resource.setCreateDate(new Date()); - resource.setOwner("rangerAdmin"); - resource.setUpdatedBy("rangerAdmin"); - resource.setPolicyName("hive Policy"); - resource.setDescription("hive policy description"); - resource.setResourceStatus(RangerCommonEnums.STATUS_ENABLED); - resource.setIsRecursive(1); - resource.setTableType(1); - resource.setColumnType(1); - - RangerPolicy actualRangerPolicy = serviceUtil.toRangerPolicy(resource, rangerService); - - Assert.assertNotNull(actualRangerPolicy); - Assert.assertEquals(expectedRangerPolicy.getId(), actualRangerPolicy.getId()); - Assert.assertEquals(expectedRangerPolicy.getName(), actualRangerPolicy.getName()); - Assert.assertEquals(expectedRangerPolicy.getService(), actualRangerPolicy.getService()); - Assert.assertEquals(expectedRangerPolicy.getDescription(), actualRangerPolicy.getDescription()); - Assert.assertEquals(expectedRangerPolicy.getResources(), actualRangerPolicy.getResources()); - - } - - @Test - public void testToRangerPolicyForPermGroup(){ - - RangerPolicyItemCondition rpic = new RangerPolicyItemCondition(); - List valuesList = new ArrayList(); - valuesList.add("10.129.25.56"); - rpic.setType("ipaddress"); - rpic.setValues(valuesList); - - List usersList = new ArrayList(); - usersList.add("rangerAdmin"); - - List groupList = new ArrayList(); - - List listRPIC = new ArrayList(); - listRPIC.add(rpic); - - RangerPolicyItemAccess rpia = new RangerPolicyItemAccess(); - rpia.setIsAllowed(true); - rpia.setType("drop"); - - List listRPIA = new ArrayList(); - listRPIA.add(rpia); - - RangerPolicyItem rangerPolicyItem = new RangerPolicyItem(); - rangerPolicyItem.setConditions(listRPIC); - rangerPolicyItem.setAccesses(listRPIA); - rangerPolicyItem.setDelegateAdmin(false); - rangerPolicyItem.setUsers(usersList); - rangerPolicyItem.setGroups(groupList); - - List listRangerPolicyItem = new ArrayList(); - listRangerPolicyItem.add(rangerPolicyItem); - - RangerPolicy expectedRangerPolicy = new RangerPolicy(); - expectedRangerPolicy.setId(1L); - expectedRangerPolicy.setName("hive Policy"); - expectedRangerPolicy.setService("hive"); - expectedRangerPolicy.setDescription("hive policy description"); - expectedRangerPolicy.setPolicyItems(listRangerPolicyItem); - - VXPermMap vXPermMap = new VXPermMap(); - vXPermMap.setId(5L); - vXPermMap.setGroupName("myGroup"); - vXPermMap.setPermGroup("permGroup"); - vXPermMap.setUserName("rangerAdmin"); - vXPermMap.setPermType(12); - vXPermMap.setPermFor(AppConstants.XA_PERM_FOR_USER); - vXPermMap.setIpAddress("10.129.25.56"); - - List vXPermMapList = new ArrayList(); - vXPermMapList.add(vXPermMap); - - - VXAuditMap vXAuditMap = new VXAuditMap(); - vXAuditMap.setId(1L); - vXAuditMap.setOwner("rangerAdmin"); - List vXAuditMapList = new ArrayList(); - vXAuditMapList.add(vXAuditMap); - - RangerService rangerService = new RangerService(); - rangerService.setName("hive"); - rangerService.setType("hive"); - - - VXResource resource = new VXResource(); - resource.setId(1L); - resource.setUpdateDate(new Date()); - resource.setCreateDate(new Date()); - resource.setOwner("rangerAdmin"); - resource.setUpdatedBy("rangerAdmin"); - resource.setPolicyName("hive Policy"); - resource.setDescription("hive policy description"); - resource.setResourceStatus(RangerCommonEnums.STATUS_ENABLED); - resource.setIsRecursive(1); - resource.setTableType(1); - resource.setColumnType(1); - resource.setPermMapList(vXPermMapList); - - RangerPolicy actualRangerPolicy = serviceUtil.toRangerPolicy(resource, rangerService); - - Assert.assertNotNull(actualRangerPolicy); - Assert.assertEquals(expectedRangerPolicy.getId(), actualRangerPolicy.getId()); - Assert.assertEquals(expectedRangerPolicy.getName(), actualRangerPolicy.getName()); - Assert.assertEquals(expectedRangerPolicy.getService(), actualRangerPolicy.getService()); - Assert.assertEquals(expectedRangerPolicy.getDescription(), actualRangerPolicy.getDescription()); - Assert.assertEquals(expectedRangerPolicy.getPolicyItems(), actualRangerPolicy.getPolicyItems()); - - } - - @Test - public void testToVXResourceForPolicyNull(){ - RangerPolicy policy = null; - RangerService rangerService = new RangerService(); - rangerService.setName("hive"); - rangerService.setType("hive"); - - VXResource vXResource = serviceUtil.toVXResource(policy, rangerService); - - Assert.assertNull(vXResource); - - } - - @Test - public void testToVXResourceForServiceNull(){ - RangerPolicy policy = new RangerPolicy(); - policy.setId(1L); - policy.setName("hive Policy"); - policy.setService("hive"); - policy.setDescription("hive policy description"); - - RangerService rangerService = null; - - VXResource vXResource = serviceUtil.toVXResource(policy, rangerService); - - Assert.assertNull(vXResource); - - } - - @Test - public void testToVXResourceForPath(){ - GUIDUtil guid = new GUIDUtil(); - String guidString = guid.genGUID(); - List auditList = new ArrayList(); - - VXAuditMap vxAuditMap = new VXAuditMap(); - vxAuditMap.setResourceId(1L); - vxAuditMap.setAuditType(AppConstants.XA_AUDIT_TYPE_ALL); - auditList.add(vxAuditMap); - - VXResource expectedVXResource = new VXResource(); - expectedVXResource.setName("resource"); - expectedVXResource.setGuid(guidString); - expectedVXResource.setPolicyName("hdfs Policy"); - expectedVXResource.setDescription("hdfs policy description"); - expectedVXResource.setResourceType(1); - expectedVXResource.setAssetName("hdfs"); - expectedVXResource.setAssetType(1); - expectedVXResource.setAuditList(auditList); - - Map rangerPolicyResourceMap = new HashMap(); - List valuesList = new ArrayList(); - valuesList.add("resource"); - - RangerPolicy policy = new RangerPolicy(); - policy.setId(1L); - policy.setName("hdfs Policy"); - policy.setService("hdfs"); - policy.setDescription("hdfs policy description"); - policy.setIsEnabled(true); - policy.setGuid(guidString); - policy.setIsAuditEnabled(true); - - RangerService rangerService = new RangerService(); - rangerService.setName("hdfs"); - rangerService.setType("hdfs"); - - RangerPolicyResource rangerPolicyResource = new RangerPolicyResource(); - rangerPolicyResource.setIsExcludes(false); - rangerPolicyResource.setIsRecursive(true); - rangerPolicyResource.setValue("/localhost/files"); - rangerPolicyResource.setValues(valuesList); - - rangerPolicyResourceMap.put("path", rangerPolicyResource); - - - policy.setResources(rangerPolicyResourceMap); - - VXResource actualVXResource = serviceUtil.toVXResource(policy, rangerService); - - - Assert.assertNotNull(actualVXResource); - Assert.assertEquals(expectedVXResource.getName(), actualVXResource.getName()); - Assert.assertEquals(expectedVXResource.getGuid(), actualVXResource.getGuid()); - Assert.assertEquals(expectedVXResource.getPolicyName(), actualVXResource.getPolicyName()); - Assert.assertEquals(expectedVXResource.getResourceType(), actualVXResource.getResourceType()); - Assert.assertEquals(expectedVXResource.getDescription(), actualVXResource.getDescription()); - Assert.assertEquals(expectedVXResource.getAssetName(), actualVXResource.getAssetName()); - Assert.assertEquals(expectedVXResource.getAssetType(), actualVXResource.getAssetType()); - Assert.assertEquals(expectedVXResource.getAuditList().get(0).getResourceId(), actualVXResource.getAuditList().get(0).getResourceId()); - Assert.assertEquals(expectedVXResource.getAuditList().get(0).getAuditType(), actualVXResource.getAuditList().get(0).getAuditType()); - - - } - - @Test - public void testToVXResourceForTablesColumnFamiliesAndColumn(){ - GUIDUtil guid = new GUIDUtil(); - String guidString = guid.genGUID(); - List auditList = new ArrayList(); - - VXAuditMap vxAuditMap = new VXAuditMap(); - vxAuditMap.setResourceId(1L); - vxAuditMap.setAuditType(AppConstants.XA_AUDIT_TYPE_ALL); - auditList.add(vxAuditMap); - - VXResource expectedVXResource = new VXResource(); - expectedVXResource.setName("/myTable/myColumnFamilies/myColumn"); - expectedVXResource.setTables("myTable"); - expectedVXResource.setColumnFamilies("myColumnFamilies"); - expectedVXResource.setColumns("myColumn"); - expectedVXResource.setGuid(guidString); - expectedVXResource.setPolicyName("hbase Policy"); - expectedVXResource.setDescription("hbase policy description"); - expectedVXResource.setResourceType(1); - expectedVXResource.setAssetName("hbase"); - expectedVXResource.setAssetType(2); - expectedVXResource.setResourceStatus(1); - expectedVXResource.setTableType(1); - expectedVXResource.setColumnType(1); - expectedVXResource.setAuditList(auditList); - - Map rangerPolicyResourceMap = new HashMap(); - List valuesListForTable = new ArrayList(); - valuesListForTable.add("myTable"); - - List valuesListForColumn = new ArrayList(); - valuesListForColumn.add("myColumn"); - - List valuesListForColumnFamilies = new ArrayList(); - valuesListForColumnFamilies.add("myColumnFamilies"); - - RangerPolicy policy = new RangerPolicy(); - policy.setId(1L); - policy.setName("hbase Policy"); - policy.setService("hbase"); - policy.setDescription("hbase policy description"); - policy.setIsEnabled(true); - policy.setGuid(guidString); - policy.setIsAuditEnabled(true); - - RangerService rangerService = new RangerService(); - rangerService.setName("hbase"); - rangerService.setType("hbase"); - - RangerPolicyResource rangerPolicyResourceForTable = new RangerPolicyResource(); - rangerPolicyResourceForTable.setIsExcludes(true); - rangerPolicyResourceForTable.setIsRecursive(true); - rangerPolicyResourceForTable.setValue("table"); - rangerPolicyResourceForTable.setValues(valuesListForTable); - - rangerPolicyResourceMap.put("table", rangerPolicyResourceForTable); - - RangerPolicyResource rangerPolicyResourceForColumn = new RangerPolicyResource(); - rangerPolicyResourceForColumn.setIsExcludes(true); - rangerPolicyResourceForColumn.setIsRecursive(true); - rangerPolicyResourceForColumn.setValue("table"); - rangerPolicyResourceForColumn.setValues(valuesListForColumn); - - rangerPolicyResourceMap.put("column", rangerPolicyResourceForColumn); - - RangerPolicyResource rangerPolicyResourceForColumnFamilies = new RangerPolicyResource(); - rangerPolicyResourceForColumnFamilies.setIsExcludes(true); - rangerPolicyResourceForColumnFamilies.setIsRecursive(true); - rangerPolicyResourceForColumnFamilies.setValue("table"); - rangerPolicyResourceForColumnFamilies.setValues(valuesListForColumnFamilies); - - rangerPolicyResourceMap.put("column-family", rangerPolicyResourceForColumnFamilies); - - - policy.setResources(rangerPolicyResourceMap); - - VXResource actualVXResource = serviceUtil.toVXResource(policy, rangerService); - - - Assert.assertNotNull(actualVXResource); - Assert.assertEquals(expectedVXResource.getName(), actualVXResource.getName()); - Assert.assertEquals(expectedVXResource.getGuid(), actualVXResource.getGuid()); - Assert.assertEquals(expectedVXResource.getPolicyName(), actualVXResource.getPolicyName()); - Assert.assertEquals(expectedVXResource.getResourceType(), actualVXResource.getResourceType()); - Assert.assertEquals(expectedVXResource.getDescription(), actualVXResource.getDescription()); - Assert.assertEquals(expectedVXResource.getAssetName(), actualVXResource.getAssetName()); - Assert.assertEquals(expectedVXResource.getAssetType(), actualVXResource.getAssetType()); - Assert.assertEquals(expectedVXResource.getResourceStatus(), actualVXResource.getResourceStatus()); - Assert.assertEquals(expectedVXResource.getTableType(), actualVXResource.getTableType()); - Assert.assertEquals(expectedVXResource.getColumnType(), actualVXResource.getColumnType()); - Assert.assertEquals(expectedVXResource.getTables(), actualVXResource.getTables()); - Assert.assertEquals(expectedVXResource.getColumns(), actualVXResource.getColumns()); - Assert.assertEquals(expectedVXResource.getColumnFamilies(), actualVXResource.getColumnFamilies()); - Assert.assertEquals(expectedVXResource.getAuditList().get(0).getResourceId(), actualVXResource.getAuditList().get(0).getResourceId()); - Assert.assertEquals(expectedVXResource.getAuditList().get(0).getAuditType(), actualVXResource.getAuditList().get(0).getAuditType()); - - - } - - @Test - public void testToVXResourceForTablesColumnsAndDatabase(){ - GUIDUtil guid = new GUIDUtil(); - String guidString = guid.genGUID(); - List auditList = new ArrayList(); - - VXAuditMap vxAuditMap = new VXAuditMap(); - vxAuditMap.setResourceId(1L); - vxAuditMap.setAuditType(AppConstants.XA_AUDIT_TYPE_ALL); - auditList.add(vxAuditMap); - - VXResource expectedVXResource = new VXResource(); - expectedVXResource.setName("/myDatabase/myTable/myColumn"); - expectedVXResource.setTables("myTable"); - expectedVXResource.setDatabases("myDatabase"); - expectedVXResource.setColumns("myColumn"); - expectedVXResource.setGuid(guidString); - expectedVXResource.setPolicyName("hive Policy"); - expectedVXResource.setDescription("hive policy description"); - expectedVXResource.setResourceType(1); - expectedVXResource.setAssetName("hive"); - expectedVXResource.setAssetType(3); - expectedVXResource.setResourceStatus(1); - expectedVXResource.setTableType(1); - expectedVXResource.setColumnType(1); - expectedVXResource.setAuditList(auditList); - - Map rangerPolicyResourceMap = new HashMap(); - List valuesListForTable = new ArrayList(); - valuesListForTable.add("myTable"); - - List valuesListForColumn = new ArrayList(); - valuesListForColumn.add("myColumn"); - - List valuesListForDatabase = new ArrayList(); - valuesListForDatabase.add("myDatabase"); - - RangerPolicy policy = new RangerPolicy(); - policy.setId(1L); - policy.setName("hive Policy"); - policy.setService("hive"); - policy.setDescription("hive policy description"); - policy.setIsEnabled(true); - policy.setGuid(guidString); - policy.setIsAuditEnabled(true); - - RangerService rangerService = new RangerService(); - rangerService.setName("hive"); - rangerService.setType("hive"); - - RangerPolicyResource rangerPolicyResourceForTable = new RangerPolicyResource(); - rangerPolicyResourceForTable.setIsExcludes(true); - rangerPolicyResourceForTable.setIsRecursive(true); - rangerPolicyResourceForTable.setValue("table"); - rangerPolicyResourceForTable.setValues(valuesListForTable); - - rangerPolicyResourceMap.put("table", rangerPolicyResourceForTable); - - RangerPolicyResource rangerPolicyResourceForColumn = new RangerPolicyResource(); - rangerPolicyResourceForColumn.setIsExcludes(true); - rangerPolicyResourceForColumn.setIsRecursive(true); - rangerPolicyResourceForColumn.setValue("column"); - rangerPolicyResourceForColumn.setValues(valuesListForColumn); - - rangerPolicyResourceMap.put("column", rangerPolicyResourceForColumn); - - RangerPolicyResource rangerPolicyResourceForDatabase = new RangerPolicyResource(); - rangerPolicyResourceForDatabase.setIsExcludes(true); - rangerPolicyResourceForDatabase.setIsRecursive(true); - rangerPolicyResourceForDatabase.setValue("database"); - rangerPolicyResourceForDatabase.setValues(valuesListForDatabase); - - rangerPolicyResourceMap.put("database", rangerPolicyResourceForDatabase); - - - policy.setResources(rangerPolicyResourceMap); - - VXResource actualVXResource = serviceUtil.toVXResource(policy, rangerService); - - - Assert.assertNotNull(actualVXResource); - Assert.assertEquals(expectedVXResource.getName(), actualVXResource.getName()); - Assert.assertEquals(expectedVXResource.getGuid(), actualVXResource.getGuid()); - Assert.assertEquals(expectedVXResource.getPolicyName(), actualVXResource.getPolicyName()); - Assert.assertEquals(expectedVXResource.getResourceType(), actualVXResource.getResourceType()); - Assert.assertEquals(expectedVXResource.getDescription(), actualVXResource.getDescription()); - Assert.assertEquals(expectedVXResource.getAssetName(), actualVXResource.getAssetName()); - Assert.assertEquals(expectedVXResource.getAssetType(), actualVXResource.getAssetType()); - Assert.assertEquals(expectedVXResource.getResourceStatus(), actualVXResource.getResourceStatus()); - Assert.assertEquals(expectedVXResource.getTableType(), actualVXResource.getTableType()); - Assert.assertEquals(expectedVXResource.getColumnType(), actualVXResource.getColumnType()); - Assert.assertEquals(expectedVXResource.getTables(), actualVXResource.getTables()); - Assert.assertEquals(expectedVXResource.getColumns(), actualVXResource.getColumns()); - Assert.assertEquals(expectedVXResource.getDatabases(), actualVXResource.getDatabases()); - Assert.assertEquals(expectedVXResource.getAuditList().get(0).getResourceId(), actualVXResource.getAuditList().get(0).getResourceId()); - Assert.assertEquals(expectedVXResource.getAuditList().get(0).getAuditType(), actualVXResource.getAuditList().get(0).getAuditType()); - - - } - - @Test - public void testToVXResourceForTopologyAndService(){ - GUIDUtil guid = new GUIDUtil(); - String guidString = guid.genGUID(); - List auditList = new ArrayList(); - - VXAuditMap vxAuditMap = new VXAuditMap(); - vxAuditMap.setResourceId(1L); - vxAuditMap.setAuditType(AppConstants.XA_AUDIT_TYPE_ALL); - auditList.add(vxAuditMap); - - VXResource expectedVXResource = new VXResource(); - expectedVXResource.setName("/myTopology/myService"); - expectedVXResource.setTopologies("myTopology"); - expectedVXResource.setServices("myService"); - expectedVXResource.setGuid(guidString); - expectedVXResource.setPolicyName("knox Policy"); - expectedVXResource.setDescription("knox policy description"); - expectedVXResource.setResourceType(1); - expectedVXResource.setAssetName("knox"); - expectedVXResource.setAssetType(5); - expectedVXResource.setResourceStatus(1); - expectedVXResource.setAuditList(auditList); - - Map rangerPolicyResourceMap = new HashMap(); - List valuesListForTopology = new ArrayList(); - valuesListForTopology.add("myTopology"); - - List valuesListForService = new ArrayList(); - valuesListForService.add("myService"); - - RangerPolicy policy = new RangerPolicy(); - policy.setId(1L); - policy.setName("knox Policy"); - policy.setService("knox"); - policy.setDescription("knox policy description"); - policy.setIsEnabled(true); - policy.setGuid(guidString); - policy.setIsAuditEnabled(true); - - RangerService rangerService = new RangerService(); - rangerService.setName("knox"); - rangerService.setType("knox"); - - RangerPolicyResource rangerPolicyResourceForTopology = new RangerPolicyResource(); - rangerPolicyResourceForTopology.setValue("topology"); - rangerPolicyResourceForTopology.setValues(valuesListForTopology); - - rangerPolicyResourceMap.put("topology", rangerPolicyResourceForTopology); - - RangerPolicyResource rangerPolicyResourceForService = new RangerPolicyResource(); - rangerPolicyResourceForService.setValue("service"); - rangerPolicyResourceForService.setValues(valuesListForService); - - rangerPolicyResourceMap.put("service", rangerPolicyResourceForService); - - policy.setResources(rangerPolicyResourceMap); - - VXResource actualVXResource = serviceUtil.toVXResource(policy, rangerService); - - - Assert.assertNotNull(actualVXResource); - Assert.assertEquals(expectedVXResource.getName(), actualVXResource.getName()); - Assert.assertEquals(expectedVXResource.getGuid(), actualVXResource.getGuid()); - Assert.assertEquals(expectedVXResource.getPolicyName(), actualVXResource.getPolicyName()); - Assert.assertEquals(expectedVXResource.getResourceType(), actualVXResource.getResourceType()); - Assert.assertEquals(expectedVXResource.getDescription(), actualVXResource.getDescription()); - Assert.assertEquals(expectedVXResource.getAssetName(), actualVXResource.getAssetName()); - Assert.assertEquals(expectedVXResource.getAssetType(), actualVXResource.getAssetType()); - Assert.assertEquals(expectedVXResource.getResourceStatus(), actualVXResource.getResourceStatus()); - Assert.assertEquals(expectedVXResource.getTopologies(), actualVXResource.getTopologies()); - Assert.assertEquals(expectedVXResource.getServices(), actualVXResource.getServices()); - Assert.assertEquals(expectedVXResource.getAuditList().get(0).getResourceId(), actualVXResource.getAuditList().get(0).getResourceId()); - Assert.assertEquals(expectedVXResource.getAuditList().get(0).getAuditType(), actualVXResource.getAuditList().get(0).getAuditType()); - - - } - - @Test - public void testToVXResourceForStormTopologyAndVXPermMapListWithUserList(){ - GUIDUtil guid = new GUIDUtil(); - String guidString = guid.genGUID(); - XXUser xxUser = new XXUser(); - xxUser.setId(6L); - xxUser.setName("rangerAdmin"); - List auditList = new ArrayList(); - - VXAuditMap vxAuditMap = new VXAuditMap(); - vxAuditMap.setResourceId(1L); - vxAuditMap.setAuditType(AppConstants.XA_AUDIT_TYPE_ALL); - auditList.add(vxAuditMap); - - List vXPermMapList = new ArrayList(); - VXPermMap vXPermMap1 = new VXPermMap(); - vXPermMap1.setPermFor(1); - vXPermMap1.setUserId(6L); - vXPermMap1.setPermType(12); - vXPermMap1.setUserName("rangerAdmin"); - vXPermMap1.setIpAddress("10.329.85.65"); - - vXPermMapList.add(vXPermMap1); - - VXPermMap vXPermMap2 = new VXPermMap(); - vXPermMap2.setPermFor(1); - vXPermMap2.setUserId(6L); - vXPermMap2.setPermType(6); - vXPermMap2.setUserName("rangerAdmin"); - vXPermMap2.setIpAddress("10.329.85.65"); - - vXPermMapList.add(vXPermMap2); - - VXResource expectedVXResource = new VXResource(); - expectedVXResource.setGuid(guidString); - expectedVXResource.setName("myTopology"); - expectedVXResource.setTopologies("myTopology"); - expectedVXResource.setPolicyName("storm Policy"); - expectedVXResource.setDescription("storm policy description"); - expectedVXResource.setResourceType(1); - expectedVXResource.setAssetName("storm"); - expectedVXResource.setAssetType(6); - expectedVXResource.setResourceStatus(1); - expectedVXResource.setAuditList(auditList); - expectedVXResource.setPermMapList(vXPermMapList); - - Map rangerPolicyResourceMap = new HashMap(); - List valuesListForTopology = new ArrayList(); - valuesListForTopology.add("myTopology"); - - RangerPolicyResource rangerPolicyResourceForTopology = new RangerPolicyResource(); - rangerPolicyResourceForTopology.setValue("topology"); - rangerPolicyResourceForTopology.setValues(valuesListForTopology); - - rangerPolicyResourceMap.put("topology", rangerPolicyResourceForTopology); - - - List valuesListForRangerPolicyItemCondition = new ArrayList(); - valuesListForRangerPolicyItemCondition.add("10.329.85.65"); - - List usersList = new ArrayList(); - usersList.add("rangerAdmin"); - - RangerPolicy policy = new RangerPolicy(); - policy.setId(1L); - policy.setName("storm Policy"); - policy.setService("storm"); - policy.setDescription("storm policy description"); - policy.setIsEnabled(true); - policy.setGuid(guidString); - policy.setIsAuditEnabled(true); - - RangerService rangerService = new RangerService(); - rangerService.setName("storm"); - rangerService.setType("storm"); - - List rangerPolicyItemList = new ArrayList(); - - RangerPolicyItem rangerPolicyItem = new RangerPolicyItem(); - - List rangerPolicyItemConditionList = new ArrayList(); - RangerPolicyItemCondition rangerPolicyItemCondition = new RangerPolicyItemCondition(); - rangerPolicyItemCondition.setType("ipaddress"); - rangerPolicyItemCondition.setValues(valuesListForRangerPolicyItemCondition); - rangerPolicyItemConditionList.add(rangerPolicyItemCondition); - - rangerPolicyItem.setConditions(rangerPolicyItemConditionList); - - rangerPolicyItem.setUsers(usersList); - - List rangerPolicyItemAccessList = new ArrayList(); - RangerPolicyItemAccess rangerPolicyItemAccess = new RangerPolicyItemAccess(); - rangerPolicyItemAccess.setIsAllowed(true); - rangerPolicyItemAccess.setType("drop"); - - rangerPolicyItemAccessList.add(rangerPolicyItemAccess); - - rangerPolicyItem.setAccesses(rangerPolicyItemAccessList); - - rangerPolicyItem.setDelegateAdmin(true); - - rangerPolicyItemList.add(rangerPolicyItem); - - policy.setPolicyItems(rangerPolicyItemList); - - policy.setResources(rangerPolicyResourceMap); - - Mockito.when(xaDaoMgr.getXXUser()).thenReturn(xxUserDao); - Mockito.when(xxUserDao.findByUserName("rangerAdmin")).thenReturn(xxUser); - - - VXResource actualVXResource = serviceUtil.toVXResource(policy, rangerService); - - - Assert.assertNotNull(actualVXResource); - Assert.assertEquals(expectedVXResource.getName(), actualVXResource.getName()); - Assert.assertEquals(expectedVXResource.getGuid(), actualVXResource.getGuid()); - Assert.assertEquals(expectedVXResource.getPolicyName(), actualVXResource.getPolicyName()); - Assert.assertEquals(expectedVXResource.getResourceType(), actualVXResource.getResourceType()); - Assert.assertEquals(expectedVXResource.getDescription(), actualVXResource.getDescription()); - Assert.assertEquals(expectedVXResource.getAssetName(), actualVXResource.getAssetName()); - Assert.assertEquals(expectedVXResource.getAssetType(), actualVXResource.getAssetType()); - Assert.assertEquals(expectedVXResource.getResourceStatus(), actualVXResource.getResourceStatus()); - Assert.assertEquals(expectedVXResource.getTopologies(), actualVXResource.getTopologies()); - Assert.assertEquals(expectedVXResource.getAuditList().get(0).getResourceId(), actualVXResource.getAuditList().get(0).getResourceId()); - Assert.assertEquals(expectedVXResource.getAuditList().get(0).getAuditType(), actualVXResource.getAuditList().get(0).getAuditType()); - Assert.assertEquals(expectedVXResource.getPermMapList().get(0).getPermFor(), actualVXResource.getPermMapList().get(0).getPermFor()); - Assert.assertEquals(expectedVXResource.getPermMapList().get(0).getPermType(), actualVXResource.getPermMapList().get(0).getPermType()); - Assert.assertEquals(expectedVXResource.getPermMapList().get(0).getUserName(), actualVXResource.getPermMapList().get(0).getUserName()); - Assert.assertEquals(expectedVXResource.getPermMapList().get(0).getIpAddress(), actualVXResource.getPermMapList().get(0).getIpAddress()); - Assert.assertEquals(expectedVXResource.getPermMapList().get(0).getUserId(), actualVXResource.getPermMapList().get(0).getUserId()); - - Assert.assertEquals(expectedVXResource.getPermMapList().get(1).getPermFor(), actualVXResource.getPermMapList().get(1).getPermFor()); - Assert.assertEquals(expectedVXResource.getPermMapList().get(1).getPermType(), actualVXResource.getPermMapList().get(1).getPermType()); - Assert.assertEquals(expectedVXResource.getPermMapList().get(1).getUserName(), actualVXResource.getPermMapList().get(1).getUserName()); - Assert.assertEquals(expectedVXResource.getPermMapList().get(1).getIpAddress(), actualVXResource.getPermMapList().get(1).getIpAddress()); - Assert.assertEquals(expectedVXResource.getPermMapList().get(1).getUserId(), actualVXResource.getPermMapList().get(1).getUserId()); - - - } - - - @Test - public void testToVXResourceForStormTopologyAndVXPermMapListWithGroupList(){ - GUIDUtil guid = new GUIDUtil(); - String guidString = guid.genGUID(); - XXGroup xxGroup = new XXGroup(); - xxGroup.setId(6L); - xxGroup.setName("rangerGroup"); - List auditList = new ArrayList(); - - VXAuditMap vxAuditMap = new VXAuditMap(); - vxAuditMap.setResourceId(1L); - vxAuditMap.setAuditType(AppConstants.XA_AUDIT_TYPE_ALL); - auditList.add(vxAuditMap); - - List vXPermMapList = new ArrayList(); - VXPermMap vXPermMap1 = new VXPermMap(); - vXPermMap1.setPermFor(2); - vXPermMap1.setPermType(12); - vXPermMap1.setGroupName("rangerGroup"); - vXPermMap1.setIpAddress("10.329.85.65"); - - vXPermMapList.add(vXPermMap1); - - VXPermMap vXPermMap2 = new VXPermMap(); - vXPermMap2.setPermFor(2); - vXPermMap2.setPermType(6); - vXPermMap2.setGroupName("rangerGroup"); - vXPermMap2.setIpAddress("10.329.85.65"); - - vXPermMapList.add(vXPermMap2); - - VXResource expectedVXResource = new VXResource(); - expectedVXResource.setGuid(guidString); - expectedVXResource.setName("myTopology"); - expectedVXResource.setTopologies("myTopology"); - expectedVXResource.setPolicyName("storm Policy"); - expectedVXResource.setDescription("storm policy description"); - expectedVXResource.setResourceType(1); - expectedVXResource.setAssetName("storm"); - expectedVXResource.setAssetType(6); - expectedVXResource.setResourceStatus(1); - expectedVXResource.setAuditList(auditList); - expectedVXResource.setPermMapList(vXPermMapList); - - Map rangerPolicyResourceMap = new HashMap(); - List valuesListForTopology = new ArrayList(); - valuesListForTopology.add("myTopology"); - - RangerPolicyResource rangerPolicyResourceForTopology = new RangerPolicyResource(); - rangerPolicyResourceForTopology.setValue("topology"); - rangerPolicyResourceForTopology.setValues(valuesListForTopology); - - rangerPolicyResourceMap.put("topology", rangerPolicyResourceForTopology); - - - List valuesListForRangerPolicyItemCondition = new ArrayList(); - valuesListForRangerPolicyItemCondition.add("10.329.85.65"); - - List groupList = new ArrayList(); - groupList.add("rangerGroup"); - - RangerPolicy policy = new RangerPolicy(); - policy.setId(1L); - policy.setName("storm Policy"); - policy.setService("storm"); - policy.setDescription("storm policy description"); - policy.setIsEnabled(true); - policy.setGuid(guidString); - policy.setIsAuditEnabled(true); - - RangerService rangerService = new RangerService(); - rangerService.setName("storm"); - rangerService.setType("storm"); - - List rangerPolicyItemList = new ArrayList(); - - RangerPolicyItem rangerPolicyItem = new RangerPolicyItem(); - - List rangerPolicyItemConditionList = new ArrayList(); - RangerPolicyItemCondition rangerPolicyItemCondition = new RangerPolicyItemCondition(); - rangerPolicyItemCondition.setType("ipaddress"); - rangerPolicyItemCondition.setValues(valuesListForRangerPolicyItemCondition); - rangerPolicyItemConditionList.add(rangerPolicyItemCondition); - - rangerPolicyItem.setConditions(rangerPolicyItemConditionList); - - rangerPolicyItem.setGroups(groupList); - - List rangerPolicyItemAccessList = new ArrayList(); - RangerPolicyItemAccess rangerPolicyItemAccess = new RangerPolicyItemAccess(); - rangerPolicyItemAccess.setIsAllowed(true); - rangerPolicyItemAccess.setType("drop"); - - rangerPolicyItemAccessList.add(rangerPolicyItemAccess); - - rangerPolicyItem.setAccesses(rangerPolicyItemAccessList); - - rangerPolicyItem.setDelegateAdmin(true); - - rangerPolicyItemList.add(rangerPolicyItem); - - policy.setPolicyItems(rangerPolicyItemList); - - policy.setResources(rangerPolicyResourceMap); - - Mockito.when(xaDaoMgr.getXXGroup()).thenReturn(xxGroupDao); - Mockito.when(xxGroupDao.findByGroupName("rangerGroup")).thenReturn(xxGroup); - - - VXResource actualVXResource = serviceUtil.toVXResource(policy, rangerService); - - - Assert.assertNotNull(actualVXResource); - Assert.assertEquals(expectedVXResource.getName(), actualVXResource.getName()); - Assert.assertEquals(expectedVXResource.getGuid(), actualVXResource.getGuid()); - Assert.assertEquals(expectedVXResource.getPolicyName(), actualVXResource.getPolicyName()); - Assert.assertEquals(expectedVXResource.getResourceType(), actualVXResource.getResourceType()); - Assert.assertEquals(expectedVXResource.getDescription(), actualVXResource.getDescription()); - Assert.assertEquals(expectedVXResource.getAssetName(), actualVXResource.getAssetName()); - Assert.assertEquals(expectedVXResource.getAssetType(), actualVXResource.getAssetType()); - Assert.assertEquals(expectedVXResource.getResourceStatus(), actualVXResource.getResourceStatus()); - Assert.assertEquals(expectedVXResource.getTopologies(), actualVXResource.getTopologies()); - Assert.assertEquals(expectedVXResource.getAuditList().get(0).getResourceId(), actualVXResource.getAuditList().get(0).getResourceId()); - Assert.assertEquals(expectedVXResource.getAuditList().get(0).getAuditType(), actualVXResource.getAuditList().get(0).getAuditType()); - Assert.assertEquals(expectedVXResource.getPermMapList().get(0).getPermFor(), actualVXResource.getPermMapList().get(0).getPermFor()); - Assert.assertEquals(expectedVXResource.getPermMapList().get(0).getPermType(), actualVXResource.getPermMapList().get(0).getPermType()); - Assert.assertEquals(expectedVXResource.getPermMapList().get(0).getUserName(), actualVXResource.getPermMapList().get(0).getUserName()); - Assert.assertEquals(expectedVXResource.getPermMapList().get(0).getIpAddress(), actualVXResource.getPermMapList().get(0).getIpAddress()); - Assert.assertEquals(expectedVXResource.getPermMapList().get(0).getUserId(), actualVXResource.getPermMapList().get(0).getUserId()); - - Assert.assertEquals(expectedVXResource.getPermMapList().get(1).getPermFor(), actualVXResource.getPermMapList().get(1).getPermFor()); - Assert.assertEquals(expectedVXResource.getPermMapList().get(1).getPermType(), actualVXResource.getPermMapList().get(1).getPermType()); - Assert.assertEquals(expectedVXResource.getPermMapList().get(1).getUserName(), actualVXResource.getPermMapList().get(1).getUserName()); - Assert.assertEquals(expectedVXResource.getPermMapList().get(1).getIpAddress(), actualVXResource.getPermMapList().get(1).getIpAddress()); - Assert.assertEquals(expectedVXResource.getPermMapList().get(1).getUserId(), actualVXResource.getPermMapList().get(1).getUserId()); - - - } - - @Test - public void testPublicObjecttoVXAsset(){ - Date date = new Date(); - - VXAsset expectedVXAsset = new VXAsset(); - expectedVXAsset.setId(1L); - expectedVXAsset.setCreateDate(date); - expectedVXAsset.setUpdateDate(date); - expectedVXAsset.setOwner("rangerAdmin"); - expectedVXAsset.setUpdatedBy("rangerAdmin"); - expectedVXAsset.setAssetType(3); - expectedVXAsset.setActiveStatus(RangerCommonEnums.STATUS_ENABLED); - expectedVXAsset.setName("hive"); - expectedVXAsset.setDescription("hive description"); - expectedVXAsset.setConfig("/myConfig"); - - VXRepository vXRepository = new VXRepository(); - vXRepository.setId(1L); - vXRepository.setCreateDate(date); - vXRepository.setUpdateDate(date); - vXRepository.setOwner("rangerAdmin"); - vXRepository.setUpdatedBy("rangerAdmin"); - vXRepository.setRepositoryType("hive"); - vXRepository.setIsActive(true); - vXRepository.setName("hive"); - vXRepository.setDescription("hive description"); - vXRepository.setConfig("/myConfig"); - - VXAsset actualVXAsset = serviceUtil.publicObjecttoVXAsset(vXRepository); - - Assert.assertNotNull(actualVXAsset); - Assert.assertEquals(actualVXAsset.getActiveStatus(), expectedVXAsset.getActiveStatus()); - Assert.assertEquals(actualVXAsset.getId(), expectedVXAsset.getId()); - Assert.assertEquals(actualVXAsset.getName(), expectedVXAsset.getName()); - Assert.assertEquals(actualVXAsset.getDescription(), expectedVXAsset.getDescription()); - Assert.assertEquals(actualVXAsset.getCreateDate(), expectedVXAsset.getCreateDate()); - Assert.assertEquals(actualVXAsset.getOwner(), expectedVXAsset.getOwner()); - Assert.assertEquals(actualVXAsset.getAssetType() , expectedVXAsset.getAssetType()); - Assert.assertEquals(actualVXAsset.getConfig() , expectedVXAsset.getConfig()); - - - - } - - @Test - public void testVXAssetToPublicObject(){ - - Date date = new Date(); - - VXRepository expectedVXRepository = new VXRepository(); - expectedVXRepository.setId(1L); - expectedVXRepository.setCreateDate(date); - expectedVXRepository.setUpdateDate(date); - expectedVXRepository.setOwner("rangerAdmin"); - expectedVXRepository.setUpdatedBy("rangerAdmin"); - expectedVXRepository.setRepositoryType("hive"); - expectedVXRepository.setIsActive(true); - expectedVXRepository.setName("hive"); - expectedVXRepository.setDescription("hive description"); - expectedVXRepository.setConfig("/myConfig"); - - VXAsset vXAsset = new VXAsset(); - vXAsset.setId(1L); - vXAsset.setCreateDate(date); - vXAsset.setUpdateDate(date); - vXAsset.setOwner("rangerAdmin"); - vXAsset.setUpdatedBy("rangerAdmin"); - vXAsset.setAssetType(3); - vXAsset.setActiveStatus(RangerCommonEnums.STATUS_ENABLED); - vXAsset.setName("hive"); - vXAsset.setDescription("hive description"); - vXAsset.setConfig("/myConfig"); - - VXRepository actualVXRepository = serviceUtil.vXAssetToPublicObject(vXAsset); - - Assert.assertNotNull(actualVXRepository); - Assert.assertEquals(expectedVXRepository.getId(), actualVXRepository.getId()); - Assert.assertEquals(expectedVXRepository.getName(), actualVXRepository.getName()); - Assert.assertEquals(expectedVXRepository.getDescription(), actualVXRepository.getDescription()); - Assert.assertTrue(actualVXRepository.getIsActive()); - Assert.assertEquals(expectedVXRepository.getCreateDate(), actualVXRepository.getCreateDate()); - Assert.assertEquals(expectedVXRepository.getOwner(), actualVXRepository.getOwner()); - Assert.assertEquals(expectedVXRepository.getRepositoryType() , actualVXRepository.getRepositoryType()); - Assert.assertEquals(expectedVXRepository.getConfig() , actualVXRepository.getConfig()); - - } - - @Test - public void testGetMappedSearchParams(){ - ArrayList statusList = new ArrayList(); - statusList.add(RangerCommonEnums.STATUS_DISABLED); - statusList.add(RangerCommonEnums.STATUS_ENABLED); - - SearchCriteria expectedSearchCriteria = new SearchCriteria(); - expectedSearchCriteria.addParam("status", statusList); - expectedSearchCriteria.addParam("type", 3); - - SearchCriteria sc = new SearchCriteria(); - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - - sc.addParam("status", null); - sc.addParam("type", "hive"); - - SearchCriteria actualSearchCriteria = serviceUtil.getMappedSearchParams(request, sc); - - Assert.assertNotNull(actualSearchCriteria); - Assert.assertEquals(expectedSearchCriteria.getParamValue("type"), actualSearchCriteria.getParamValue("type")); - Assert.assertEquals(expectedSearchCriteria.getParamValue("status"), actualSearchCriteria.getParamValue("status")); - - } - - @Test - public void testIsValidService() throws Exception{ - RangerService rangerService = new RangerService(); - rangerService.setId(1L); - rangerService.setName("hiveService"); - rangerService.setIsEnabled(true); - - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - String serviceName = "hiveService"; - - - Mockito.when(svcStore.getServiceByName(serviceName)).thenReturn(rangerService); - boolean isValid = serviceUtil.isValidService(serviceName, request); - - Assert.assertTrue(isValid); - - - } - - @Test - public void testIsValidateHttpsAuthentication() throws Exception{ - - RangerService rangerService = new RangerService(); - rangerService.setId(1L); - rangerService.setName("hiveService"); - rangerService.setIsEnabled(true); - - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - String serviceName = "hiveService"; - - - Mockito.when(svcStore.getServiceByName(serviceName)).thenReturn(rangerService); - boolean isValidAuthentication = serviceUtil.isValidateHttpsAuthentication(serviceName, request); - - Assert.assertTrue(isValidAuthentication); - - - } - - @Test - public void testToGrantRevokeRequestForHive() throws Exception{ - GrantRevokeRequest expectedGrantRevokeRequest = new GrantRevokeRequest(); - expectedGrantRevokeRequest.setGrantor("rangerAdmin"); - expectedGrantRevokeRequest.setEnableAudit(true); - expectedGrantRevokeRequest.setIsRecursive(false); - expectedGrantRevokeRequest.setReplaceExistingPermissions(true); - - Map mapResource = new HashMap(); - mapResource.put("database", "myDatabase"); - mapResource.put("table", "myTable"); - mapResource.put("column", "myColumn"); - - expectedGrantRevokeRequest.setResource(mapResource); - - String serviceName = "hive"; - - RangerService rangerService = new RangerService(); - rangerService.setId(1L); - rangerService.setName("hiveService"); - rangerService.setIsEnabled(true); - rangerService.setType("hive"); - - VXPolicy vXPolicy = new VXPolicy(); - vXPolicy.setRepositoryName("hive"); - vXPolicy.setGrantor("rangerAdmin"); - vXPolicy.setReplacePerm(true); - vXPolicy.setDatabases("myDatabase"); - vXPolicy.setColumns("myColumn"); - vXPolicy.setTables("myTable"); - - Mockito.when(svcStore.getServiceByName(serviceName)).thenReturn(rangerService); - - GrantRevokeRequest actualGrantRevokeRequest = serviceUtil.toGrantRevokeRequest(vXPolicy); - - Assert.assertNotNull(actualGrantRevokeRequest); - Assert.assertTrue(actualGrantRevokeRequest.getEnableAudit()); - Assert.assertFalse(actualGrantRevokeRequest.getIsRecursive()); - Assert.assertTrue(actualGrantRevokeRequest.getReplaceExistingPermissions()); - Assert.assertEquals(expectedGrantRevokeRequest.getGrantor(), actualGrantRevokeRequest.getGrantor()); - Assert.assertEquals(expectedGrantRevokeRequest.getResource(), actualGrantRevokeRequest.getResource()); - } - - @Test - public void testToGrantRevokeRequestForHbase() throws Exception{ - GrantRevokeRequest expectedGrantRevokeRequest = new GrantRevokeRequest(); - expectedGrantRevokeRequest.setGrantor("rangerAdmin"); - expectedGrantRevokeRequest.setEnableAudit(true); - expectedGrantRevokeRequest.setIsRecursive(false); - expectedGrantRevokeRequest.setReplaceExistingPermissions(true); - - Map mapResource = new HashMap(); - mapResource.put("table", "myTable"); - mapResource.put("column", "myColumn"); - - mapResource.put("column-family", "myColumnFamily"); - expectedGrantRevokeRequest.setResource(mapResource); - - String serviceName = "hbase"; - - RangerService rangerService = new RangerService(); - rangerService.setId(1L); - rangerService.setName("hbaseService"); - rangerService.setIsEnabled(true); - rangerService.setType("hbase"); +import javax.servlet.http.HttpServletRequest; - VXPolicy vXPolicy = new VXPolicy(); - vXPolicy.setRepositoryName("hbase"); - vXPolicy.setGrantor("rangerAdmin"); - vXPolicy.setReplacePerm(true); - vXPolicy.setColumns("myColumn"); - vXPolicy.setColumnFamilies("myColumnFamily"); - vXPolicy.setTables("myTable"); +import java.util.ArrayList; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; - Mockito.when(svcStore.getServiceByName(serviceName)).thenReturn(rangerService); +@RunWith(MockitoJUnitRunner.class) +public class TestServiceUtil { + @InjectMocks + ServiceUtil serviceUtil = new ServiceUtil(); + + @Mock + ServiceDBStore svcStore; + + @Mock + JSONUtil jsonUtil; + + @Mock + RangerDaoManager xaDaoMgr; + + @Mock + XXUserDao xxUserDao; + + @Mock + XXGroupDao xxGroupDao; + + @Test + public void testGetServiceByName() throws Exception { + RangerService expectedRangerService = new RangerService(); + expectedRangerService.setId(1L); + expectedRangerService.setName("hdfs"); + Mockito.when(svcStore.getServiceByName("hdfs")).thenReturn(expectedRangerService); + RangerService actualRangerService = serviceUtil.getServiceByName("hdfs"); + + Assert.assertEquals(expectedRangerService.getName(), actualRangerService.getName()); + Assert.assertEquals(expectedRangerService.getId(), actualRangerService.getId()); + } + + @Test + public void testToRangerServiceForNull() { + VXAsset vXAsset = null; + RangerService actualRangerService = serviceUtil.toRangerService(vXAsset); + Assert.assertNull(actualRangerService); + } + + @Test + public void testToRangerService() { + Map map = new HashMap<>(); + RangerService expectedRangerService = new RangerService(); + expectedRangerService.setId(1L); + expectedRangerService.setName("hive"); + expectedRangerService.setDescription("hive Description"); + map.put("config", "hiveConfig"); + VXAsset vXAsset = new VXAsset(); + vXAsset.setId(1L); + vXAsset.setCreateDate(new Date()); + vXAsset.setUpdateDate(new Date()); + vXAsset.setOwner("ranger"); + vXAsset.setUpdatedBy("rangerAdmin"); + vXAsset.setAssetType(5); + vXAsset.setName("hive"); + vXAsset.setDescription("hive Description"); + vXAsset.setActiveStatus(1); + vXAsset.setConfig("{config : hiveConfig}"); + Mockito.when(jsonUtil.jsonToMap("{config : hiveConfig}")).thenReturn(map); + + RangerService actualRangerService = serviceUtil.toRangerService(vXAsset); + + Assert.assertNotNull(actualRangerService); + Assert.assertEquals(actualRangerService.getId(), expectedRangerService.getId()); + Assert.assertEquals(actualRangerService.getName(), expectedRangerService.getName()); + Assert.assertEquals(actualRangerService.getDescription(), expectedRangerService.getDescription()); + Assert.assertTrue(actualRangerService.getIsEnabled()); + } + + @Test + public void testToVXAssetForNull() { + RangerService rangerService = null; + VXAsset actualVXAsset = serviceUtil.toVXAsset(rangerService); + Assert.assertNull(actualVXAsset); + } + + @Test + public void testToVXAsset() { + RangerService rangerService = new RangerService(); + VXAsset expectedVXAssesst = new VXAsset(); + expectedVXAssesst.setId(1L); + expectedVXAssesst.setName("hive"); + expectedVXAssesst.setDescription("hive Description"); + expectedVXAssesst.setActiveStatus(1); + + Map map = new HashMap<>(); + map.put("config", "hiveConfig"); + rangerService.setId(1L); + rangerService.setCreateTime(new Date()); + rangerService.setUpdateTime(new Date()); + rangerService.setCreatedBy("ranger"); + rangerService.setUpdatedBy("rangerAdmin"); + + rangerService.setType("hive"); + rangerService.setName("hive"); + rangerService.setDescription("hive Description"); + rangerService.setIsEnabled(true); + rangerService.setConfigs(map); + + Mockito.when(jsonUtil.readMapToString(map)).thenReturn("{config : hiveConfig}"); + + VXAsset actualVXAsset = serviceUtil.toVXAsset(rangerService); + + Assert.assertNotNull(actualVXAsset); + Assert.assertEquals(actualVXAsset.getId(), expectedVXAssesst.getId()); + Assert.assertEquals(actualVXAsset.getName(), expectedVXAssesst.getName()); + Assert.assertEquals(actualVXAsset.getDescription(), expectedVXAssesst.getDescription()); + Assert.assertEquals(RangerCommonEnums.STATUS_ENABLED, actualVXAsset.getActiveStatus()); + } + + @Test + public void testToVXRepositoryForNull() { + RangerService rangerService = null; + VXRepository actualvXRepository = serviceUtil.toVXRepository(rangerService); + Assert.assertNull(actualvXRepository); + } + + @Test + public void testToVXRepository() { + Map map = new HashMap<>(); + map.put("config", "hiveConfig"); + VXRepository expectedVXRepository = new VXRepository(); + expectedVXRepository.setRepositoryType("hive"); + expectedVXRepository.setName("hive"); + expectedVXRepository.setDescription("hive Description"); + expectedVXRepository.setIsActive(true); + expectedVXRepository.setVersion("3"); + + RangerService rangerService = new RangerService(); + rangerService.setId(1L); + rangerService.setCreateTime(new Date()); + rangerService.setUpdateTime(new Date()); + rangerService.setCreatedBy("ranger"); + rangerService.setUpdatedBy("rangerAdmin"); + rangerService.setType("hive"); + rangerService.setName("hive"); + rangerService.setDescription("hive Description"); + rangerService.setIsEnabled(true); + rangerService.setConfigs(map); + rangerService.setVersion(3L); + + Mockito.when(jsonUtil.readMapToString(map)).thenReturn("{config : hiveConfig}"); + + VXRepository actualvXRepository = serviceUtil.toVXRepository(rangerService); + Assert.assertNotNull(actualvXRepository); + Assert.assertEquals(actualvXRepository.getRepositoryType(), expectedVXRepository.getRepositoryType()); + Assert.assertEquals(actualvXRepository.getName(), expectedVXRepository.getName()); + Assert.assertEquals(actualvXRepository.getDescription(), expectedVXRepository.getDescription()); + Assert.assertTrue(actualvXRepository.getIsActive()); + Assert.assertEquals(actualvXRepository.getVersion(), expectedVXRepository.getVersion()); + } + + @Test + public void testToRangerPolicyForNull() { + VXResource resource = null; + RangerService rangerService = null; + RangerPolicy actualRangerPolicy = serviceUtil.toRangerPolicy(resource, rangerService); + Assert.assertNull(actualRangerPolicy); + } + + @Test + public void testToRangerPolicyForResourceTypePath() { + RangerPolicy expectedRangerPolicy = new RangerPolicy(); + expectedRangerPolicy.setId(1L); + expectedRangerPolicy.setName("hive Policy"); + expectedRangerPolicy.setService("hive"); + expectedRangerPolicy.setDescription("hive policy description"); + + Map expectedMap = new HashMap<>(); + List valuesList = new ArrayList<>(); + valuesList.add("resource"); + + VXAuditMap vXAuditMap = new VXAuditMap(); + vXAuditMap.setId(1L); + vXAuditMap.setOwner("rangerAdmin"); + List vXAuditMapList = new ArrayList<>(); + vXAuditMapList.add(vXAuditMap); + + RangerPolicyResource rangerPolicyResource = new RangerPolicyResource(); + rangerPolicyResource.setIsExcludes(false); + rangerPolicyResource.setIsRecursive(true); + rangerPolicyResource.setValue("/localhost/files"); + rangerPolicyResource.setValues(valuesList); + + expectedMap.put("path", rangerPolicyResource); + + expectedRangerPolicy.setResources(expectedMap); + + RangerService rangerService = new RangerService(); + rangerService.setName("hive"); + + VXResource resource = new VXResource(); + resource.setId(1L); + resource.setName("resource"); + resource.setUpdateDate(new Date()); + resource.setCreateDate(new Date()); + resource.setOwner("rangerAdmin"); + resource.setUpdatedBy("rangerAdmin"); + resource.setPolicyName("hive Policy"); + resource.setDescription("hive policy description"); + resource.setResourceStatus(RangerCommonEnums.STATUS_ENABLED); + resource.setIsRecursive(1); + resource.setTableType(1); + resource.setColumnType(1); + + RangerPolicy actualRangerPolicy = serviceUtil.toRangerPolicy(resource, rangerService); + + Assert.assertNotNull(actualRangerPolicy); + Assert.assertEquals(expectedRangerPolicy.getId(), actualRangerPolicy.getId()); + Assert.assertEquals(expectedRangerPolicy.getName(), actualRangerPolicy.getName()); + Assert.assertEquals(expectedRangerPolicy.getService(), actualRangerPolicy.getService()); + Assert.assertEquals(expectedRangerPolicy.getDescription(), actualRangerPolicy.getDescription()); + Assert.assertEquals(expectedRangerPolicy.getResources(), actualRangerPolicy.getResources()); + } + + @Test + public void testToRangerPolicyForResourceTypeTable() { + RangerPolicy expectedRangerPolicy = new RangerPolicy(); + expectedRangerPolicy.setId(1L); + expectedRangerPolicy.setName("hive Policy"); + expectedRangerPolicy.setService("hive"); + expectedRangerPolicy.setDescription("hive policy description"); + + Map expectedMap = new HashMap<>(); + List valuesList = new ArrayList<>(); + valuesList.add("xa_service"); + + VXAuditMap vXAuditMap = new VXAuditMap(); + vXAuditMap.setId(1L); + vXAuditMap.setOwner("rangerAdmin"); + List vXAuditMapList = new ArrayList<>(); + vXAuditMapList.add(vXAuditMap); + + RangerPolicyResource rangerPolicyResource = new RangerPolicyResource(); + rangerPolicyResource.setIsExcludes(true); + rangerPolicyResource.setIsRecursive(false); + rangerPolicyResource.setValue("xa_service"); + rangerPolicyResource.setValues(valuesList); + + expectedMap.put("table", rangerPolicyResource); + + expectedRangerPolicy.setResources(expectedMap); + + RangerService rangerService = new RangerService(); + rangerService.setName("hive"); + + VXResource resource = new VXResource(); + resource.setId(1L); + resource.setTables("xa_service"); + resource.setUpdateDate(new Date()); + resource.setCreateDate(new Date()); + resource.setOwner("rangerAdmin"); + resource.setUpdatedBy("rangerAdmin"); + resource.setPolicyName("hive Policy"); + resource.setDescription("hive policy description"); + resource.setResourceStatus(RangerCommonEnums.STATUS_ENABLED); + resource.setIsRecursive(1); + resource.setTableType(1); + resource.setColumnType(1); + + RangerPolicy actualRangerPolicy = serviceUtil.toRangerPolicy(resource, rangerService); + + Assert.assertNotNull(actualRangerPolicy); + Assert.assertEquals(expectedRangerPolicy.getId(), actualRangerPolicy.getId()); + Assert.assertEquals(expectedRangerPolicy.getName(), actualRangerPolicy.getName()); + Assert.assertEquals(expectedRangerPolicy.getService(), actualRangerPolicy.getService()); + Assert.assertEquals(expectedRangerPolicy.getDescription(), actualRangerPolicy.getDescription()); + Assert.assertEquals(expectedRangerPolicy.getResources(), actualRangerPolicy.getResources()); + } + + @Test + public void testToRangerPolicyForResourceTypeColumnFamily() { + RangerPolicy expectedRangerPolicy = new RangerPolicy(); + expectedRangerPolicy.setId(1L); + expectedRangerPolicy.setName("hive Policy"); + expectedRangerPolicy.setService("hive"); + expectedRangerPolicy.setDescription("hive policy description"); + + Map expectedMap = new HashMap<>(); + List valuesList = new ArrayList<>(); + valuesList.add("columnFamilies"); + + VXAuditMap vXAuditMap = new VXAuditMap(); + vXAuditMap.setId(1L); + vXAuditMap.setOwner("rangerAdmin"); + List vXAuditMapList = new ArrayList<>(); + vXAuditMapList.add(vXAuditMap); + + RangerPolicyResource rangerPolicyResource = new RangerPolicyResource(); + rangerPolicyResource.setIsExcludes(false); + rangerPolicyResource.setIsRecursive(false); + rangerPolicyResource.setValue("columnFamilies"); + rangerPolicyResource.setValues(valuesList); + + expectedMap.put("column-family", rangerPolicyResource); + + expectedRangerPolicy.setResources(expectedMap); + + RangerService rangerService = new RangerService(); + rangerService.setName("hive"); + + VXResource resource = new VXResource(); + resource.setId(1L); + resource.setColumnFamilies("columnFamilies"); + resource.setUpdateDate(new Date()); + resource.setCreateDate(new Date()); + resource.setOwner("rangerAdmin"); + resource.setUpdatedBy("rangerAdmin"); + resource.setPolicyName("hive Policy"); + resource.setDescription("hive policy description"); + resource.setResourceStatus(RangerCommonEnums.STATUS_ENABLED); + resource.setIsRecursive(1); + resource.setTableType(1); + resource.setColumnType(1); + + RangerPolicy actualRangerPolicy = serviceUtil.toRangerPolicy(resource, rangerService); + + Assert.assertNotNull(actualRangerPolicy); + Assert.assertEquals(expectedRangerPolicy.getId(), actualRangerPolicy.getId()); + Assert.assertEquals(expectedRangerPolicy.getName(), actualRangerPolicy.getName()); + Assert.assertEquals(expectedRangerPolicy.getService(), actualRangerPolicy.getService()); + Assert.assertEquals(expectedRangerPolicy.getDescription(), actualRangerPolicy.getDescription()); + Assert.assertEquals(expectedRangerPolicy.getResources(), actualRangerPolicy.getResources()); + } + + @Test + public void testToRangerPolicyForResourceTypeColumn() { + RangerPolicy expectedRangerPolicy = new RangerPolicy(); + expectedRangerPolicy.setId(1L); + expectedRangerPolicy.setName("hive Policy"); + expectedRangerPolicy.setService("hive"); + expectedRangerPolicy.setDescription("hive policy description"); + + Map expectedMap = new HashMap<>(); + List valuesList = new ArrayList<>(); + valuesList.add("column"); + + VXAuditMap vXAuditMap = new VXAuditMap(); + vXAuditMap.setId(1L); + vXAuditMap.setOwner("rangerAdmin"); + List vXAuditMapList = new ArrayList<>(); + vXAuditMapList.add(vXAuditMap); + + RangerPolicyResource rangerPolicyResource = new RangerPolicyResource(); + rangerPolicyResource.setIsExcludes(true); + rangerPolicyResource.setIsRecursive(false); + rangerPolicyResource.setValue("column"); + rangerPolicyResource.setValues(valuesList); + + expectedMap.put("column", rangerPolicyResource); + + expectedRangerPolicy.setResources(expectedMap); + + RangerService rangerService = new RangerService(); + rangerService.setName("hive"); + + VXResource resource = new VXResource(); + resource.setId(1L); + resource.setColumns("column"); + resource.setUpdateDate(new Date()); + resource.setCreateDate(new Date()); + resource.setOwner("rangerAdmin"); + resource.setUpdatedBy("rangerAdmin"); + resource.setPolicyName("hive Policy"); + resource.setDescription("hive policy description"); + resource.setResourceStatus(RangerCommonEnums.STATUS_ENABLED); + resource.setIsRecursive(1); + resource.setTableType(1); + resource.setColumnType(1); + + RangerPolicy actualRangerPolicy = serviceUtil.toRangerPolicy(resource, rangerService); + + Assert.assertNotNull(actualRangerPolicy); + Assert.assertEquals(expectedRangerPolicy.getId(), actualRangerPolicy.getId()); + Assert.assertEquals(expectedRangerPolicy.getName(), actualRangerPolicy.getName()); + Assert.assertEquals(expectedRangerPolicy.getService(), actualRangerPolicy.getService()); + Assert.assertEquals(expectedRangerPolicy.getDescription(), actualRangerPolicy.getDescription()); + Assert.assertEquals(expectedRangerPolicy.getResources(), actualRangerPolicy.getResources()); + } + + @Test + public void testToRangerPolicyForResourceTypeDatabase() { + RangerPolicy expectedRangerPolicy = new RangerPolicy(); + expectedRangerPolicy.setId(1L); + expectedRangerPolicy.setName("hive Policy"); + expectedRangerPolicy.setService("hive"); + expectedRangerPolicy.setDescription("hive policy description"); + + Map expectedMap = new HashMap<>(); + List valuesList = new ArrayList<>(); + valuesList.add("databases"); + + VXAuditMap vXAuditMap = new VXAuditMap(); + vXAuditMap.setId(1L); + vXAuditMap.setOwner("rangerAdmin"); + List vXAuditMapList = new ArrayList<>(); + vXAuditMapList.add(vXAuditMap); + + RangerPolicyResource rangerPolicyResource = new RangerPolicyResource(); + rangerPolicyResource.setIsExcludes(false); + rangerPolicyResource.setIsRecursive(false); + rangerPolicyResource.setValue("databases"); + rangerPolicyResource.setValues(valuesList); + + expectedMap.put("database", rangerPolicyResource); + + expectedRangerPolicy.setResources(expectedMap); + + RangerService rangerService = new RangerService(); + rangerService.setName("hive"); + + VXResource resource = new VXResource(); + resource.setId(1L); + resource.setDatabases("databases"); + resource.setUpdateDate(new Date()); + resource.setCreateDate(new Date()); + resource.setOwner("rangerAdmin"); + resource.setUpdatedBy("rangerAdmin"); + resource.setPolicyName("hive Policy"); + resource.setDescription("hive policy description"); + resource.setResourceStatus(RangerCommonEnums.STATUS_ENABLED); + resource.setIsRecursive(1); + resource.setTableType(1); + resource.setColumnType(1); + + RangerPolicy actualRangerPolicy = serviceUtil.toRangerPolicy(resource, rangerService); + + Assert.assertNotNull(actualRangerPolicy); + Assert.assertEquals(expectedRangerPolicy.getId(), actualRangerPolicy.getId()); + Assert.assertEquals(expectedRangerPolicy.getName(), actualRangerPolicy.getName()); + Assert.assertEquals(expectedRangerPolicy.getService(), actualRangerPolicy.getService()); + Assert.assertEquals(expectedRangerPolicy.getDescription(), actualRangerPolicy.getDescription()); + Assert.assertEquals(expectedRangerPolicy.getResources(), actualRangerPolicy.getResources()); + } + + @Test + public void testToRangerPolicyForResourceTypeUDF() { + RangerPolicy expectedRangerPolicy = new RangerPolicy(); + expectedRangerPolicy.setId(1L); + expectedRangerPolicy.setName("hive Policy"); + expectedRangerPolicy.setService("hive"); + expectedRangerPolicy.setDescription("hive policy description"); + + Map expectedMap = new HashMap<>(); + List valuesList = new ArrayList<>(); + valuesList.add("udf"); + + VXAuditMap vXAuditMap = new VXAuditMap(); + vXAuditMap.setId(1L); + vXAuditMap.setOwner("rangerAdmin"); + List vXAuditMapList = new ArrayList<>(); + vXAuditMapList.add(vXAuditMap); + + RangerPolicyResource rangerPolicyResource = new RangerPolicyResource(); + rangerPolicyResource.setIsExcludes(false); + rangerPolicyResource.setIsRecursive(false); + rangerPolicyResource.setValue("databases"); + rangerPolicyResource.setValues(valuesList); + + expectedMap.put("udf", rangerPolicyResource); + + expectedRangerPolicy.setResources(expectedMap); + + RangerService rangerService = new RangerService(); + rangerService.setName("hive"); + + VXResource resource = new VXResource(); + resource.setId(1L); + resource.setUdfs("udf"); + resource.setUpdateDate(new Date()); + resource.setCreateDate(new Date()); + resource.setOwner("rangerAdmin"); + resource.setUpdatedBy("rangerAdmin"); + resource.setPolicyName("hive Policy"); + resource.setDescription("hive policy description"); + resource.setResourceStatus(RangerCommonEnums.STATUS_ENABLED); + resource.setIsRecursive(1); + resource.setTableType(1); + resource.setColumnType(1); + + RangerPolicy actualRangerPolicy = serviceUtil.toRangerPolicy(resource, rangerService); + + Assert.assertNotNull(actualRangerPolicy); + Assert.assertEquals(expectedRangerPolicy.getId(), actualRangerPolicy.getId()); + Assert.assertEquals(expectedRangerPolicy.getName(), actualRangerPolicy.getName()); + Assert.assertEquals(expectedRangerPolicy.getService(), actualRangerPolicy.getService()); + Assert.assertEquals(expectedRangerPolicy.getDescription(), actualRangerPolicy.getDescription()); + Assert.assertEquals(expectedRangerPolicy.getResources(), actualRangerPolicy.getResources()); + } + + @Test + public void testToRangerPolicyForResourceTypeTopology() { + RangerPolicy expectedRangerPolicy = new RangerPolicy(); + expectedRangerPolicy.setId(1L); + expectedRangerPolicy.setName("hive Policy"); + expectedRangerPolicy.setService("hive"); + expectedRangerPolicy.setDescription("hive policy description"); + + Map expectedMap = new HashMap<>(); + List valuesList = new ArrayList<>(); + valuesList.add("topology"); + + VXAuditMap vXAuditMap = new VXAuditMap(); + vXAuditMap.setId(1L); + vXAuditMap.setOwner("rangerAdmin"); + List vXAuditMapList = new ArrayList<>(); + vXAuditMapList.add(vXAuditMap); + + RangerPolicyResource rangerPolicyResource = new RangerPolicyResource(); + rangerPolicyResource.setIsExcludes(false); + rangerPolicyResource.setIsRecursive(false); + rangerPolicyResource.setValue("topology"); + rangerPolicyResource.setValues(valuesList); + + expectedMap.put("topology", rangerPolicyResource); + + expectedRangerPolicy.setResources(expectedMap); + + RangerService rangerService = new RangerService(); + rangerService.setName("hive"); + + VXResource resource = new VXResource(); + resource.setId(1L); + resource.setTopologies("topology"); + resource.setUpdateDate(new Date()); + resource.setCreateDate(new Date()); + resource.setOwner("rangerAdmin"); + resource.setUpdatedBy("rangerAdmin"); + resource.setPolicyName("hive Policy"); + resource.setDescription("hive policy description"); + resource.setResourceStatus(RangerCommonEnums.STATUS_ENABLED); + resource.setIsRecursive(1); + resource.setTableType(1); + resource.setColumnType(1); + + RangerPolicy actualRangerPolicy = serviceUtil.toRangerPolicy(resource, rangerService); + + Assert.assertNotNull(actualRangerPolicy); + Assert.assertEquals(expectedRangerPolicy.getId(), actualRangerPolicy.getId()); + Assert.assertEquals(expectedRangerPolicy.getName(), actualRangerPolicy.getName()); + Assert.assertEquals(expectedRangerPolicy.getService(), actualRangerPolicy.getService()); + Assert.assertEquals(expectedRangerPolicy.getDescription(), actualRangerPolicy.getDescription()); + Assert.assertEquals(expectedRangerPolicy.getResources(), actualRangerPolicy.getResources()); + } + + @Test + public void testToRangerPolicyForResourceTypeService() { + RangerPolicy expectedRangerPolicy = new RangerPolicy(); + expectedRangerPolicy.setId(1L); + expectedRangerPolicy.setName("hive Policy"); + expectedRangerPolicy.setService("hive"); + expectedRangerPolicy.setDescription("hive policy description"); + + Map expectedMap = new HashMap<>(); + List valuesList = new ArrayList<>(); + valuesList.add("service"); + + VXAuditMap vXAuditMap = new VXAuditMap(); + vXAuditMap.setId(1L); + vXAuditMap.setOwner("rangerAdmin"); + List vXAuditMapList = new ArrayList<>(); + vXAuditMapList.add(vXAuditMap); + + RangerPolicyResource rangerPolicyResource = new RangerPolicyResource(); + rangerPolicyResource.setIsExcludes(false); + rangerPolicyResource.setIsRecursive(false); + rangerPolicyResource.setValue("service"); + rangerPolicyResource.setValues(valuesList); + + expectedMap.put("service", rangerPolicyResource); + + expectedRangerPolicy.setResources(expectedMap); + + RangerService rangerService = new RangerService(); + rangerService.setName("hive"); + + VXResource resource = new VXResource(); + resource.setId(1L); + resource.setServices("service"); + resource.setUpdateDate(new Date()); + resource.setCreateDate(new Date()); + resource.setOwner("rangerAdmin"); + resource.setUpdatedBy("rangerAdmin"); + resource.setPolicyName("hive Policy"); + resource.setDescription("hive policy description"); + resource.setResourceStatus(RangerCommonEnums.STATUS_ENABLED); + resource.setIsRecursive(1); + resource.setTableType(1); + resource.setColumnType(1); + + RangerPolicy actualRangerPolicy = serviceUtil.toRangerPolicy(resource, rangerService); + + Assert.assertNotNull(actualRangerPolicy); + Assert.assertEquals(expectedRangerPolicy.getId(), actualRangerPolicy.getId()); + Assert.assertEquals(expectedRangerPolicy.getName(), actualRangerPolicy.getName()); + Assert.assertEquals(expectedRangerPolicy.getService(), actualRangerPolicy.getService()); + Assert.assertEquals(expectedRangerPolicy.getDescription(), actualRangerPolicy.getDescription()); + Assert.assertEquals(expectedRangerPolicy.getResources(), actualRangerPolicy.getResources()); + } + + @Test + public void testToRangerPolicyForResourceTypeHiveService() { + RangerPolicy expectedRangerPolicy = new RangerPolicy(); + expectedRangerPolicy.setId(1L); + expectedRangerPolicy.setName("hive Policy"); + expectedRangerPolicy.setService("hive"); + expectedRangerPolicy.setDescription("hive policy description"); + + Map expectedMap = new HashMap<>(); + List valuesList = new ArrayList<>(); + valuesList.add("hiveservice"); + + VXAuditMap vXAuditMap = new VXAuditMap(); + vXAuditMap.setId(1L); + vXAuditMap.setOwner("rangerAdmin"); + List vXAuditMapList = new ArrayList<>(); + vXAuditMapList.add(vXAuditMap); + + RangerPolicyResource rangerPolicyResource = new RangerPolicyResource(); + rangerPolicyResource.setIsExcludes(false); + rangerPolicyResource.setIsRecursive(false); + rangerPolicyResource.setValue("hiveservice"); + rangerPolicyResource.setValues(valuesList); + + expectedMap.put("service", rangerPolicyResource); + + expectedRangerPolicy.setResources(expectedMap); + + RangerService rangerService = new RangerService(); + rangerService.setName("hive"); + + VXResource resource = new VXResource(); + resource.setId(1L); + resource.setServices("hiveservice"); + resource.setUpdateDate(new Date()); + resource.setCreateDate(new Date()); + resource.setOwner("rangerAdmin"); + resource.setUpdatedBy("rangerAdmin"); + resource.setPolicyName("hive Policy"); + resource.setDescription("hive policy description"); + resource.setResourceStatus(RangerCommonEnums.STATUS_ENABLED); + resource.setIsRecursive(1); + resource.setTableType(1); + resource.setColumnType(1); + + RangerPolicy actualRangerPolicy = serviceUtil.toRangerPolicy(resource, rangerService); + + Assert.assertNotNull(actualRangerPolicy); + Assert.assertEquals(expectedRangerPolicy.getId(), actualRangerPolicy.getId()); + Assert.assertEquals(expectedRangerPolicy.getName(), actualRangerPolicy.getName()); + Assert.assertEquals(expectedRangerPolicy.getService(), actualRangerPolicy.getService()); + Assert.assertEquals(expectedRangerPolicy.getDescription(), actualRangerPolicy.getDescription()); + Assert.assertEquals(expectedRangerPolicy.getResources(), actualRangerPolicy.getResources()); + } + + @Test + public void testToRangerPolicyForPermGroup() { + RangerPolicyItemCondition rpic = new RangerPolicyItemCondition(); + List valuesList = new ArrayList<>(); + valuesList.add("10.129.25.56"); + rpic.setType("ipaddress"); + rpic.setValues(valuesList); + + List usersList = new ArrayList<>(); + usersList.add("rangerAdmin"); + + List groupList = new ArrayList<>(); + + List listRPIC = new ArrayList<>(); + listRPIC.add(rpic); + + RangerPolicyItemAccess rpia = new RangerPolicyItemAccess(); + rpia.setIsAllowed(true); + rpia.setType("drop"); + + List listRPIA = new ArrayList<>(); + listRPIA.add(rpia); + + RangerPolicyItem rangerPolicyItem = new RangerPolicyItem(); + rangerPolicyItem.setConditions(listRPIC); + rangerPolicyItem.setAccesses(listRPIA); + rangerPolicyItem.setDelegateAdmin(false); + rangerPolicyItem.setUsers(usersList); + rangerPolicyItem.setGroups(groupList); + + List listRangerPolicyItem = new ArrayList<>(); + listRangerPolicyItem.add(rangerPolicyItem); + + RangerPolicy expectedRangerPolicy = new RangerPolicy(); + expectedRangerPolicy.setId(1L); + expectedRangerPolicy.setName("hive Policy"); + expectedRangerPolicy.setService("hive"); + expectedRangerPolicy.setDescription("hive policy description"); + expectedRangerPolicy.setPolicyItems(listRangerPolicyItem); + + VXPermMap vXPermMap = new VXPermMap(); + vXPermMap.setId(5L); + vXPermMap.setGroupName("myGroup"); + vXPermMap.setPermGroup("permGroup"); + vXPermMap.setUserName("rangerAdmin"); + vXPermMap.setPermType(12); + vXPermMap.setPermFor(AppConstants.XA_PERM_FOR_USER); + vXPermMap.setIpAddress("10.129.25.56"); + + List vXPermMapList = new ArrayList<>(); + vXPermMapList.add(vXPermMap); + + VXAuditMap vXAuditMap = new VXAuditMap(); + vXAuditMap.setId(1L); + vXAuditMap.setOwner("rangerAdmin"); + List vXAuditMapList = new ArrayList<>(); + vXAuditMapList.add(vXAuditMap); + + RangerService rangerService = new RangerService(); + rangerService.setName("hive"); + rangerService.setType("hive"); + + VXResource resource = new VXResource(); + resource.setId(1L); + resource.setUpdateDate(new Date()); + resource.setCreateDate(new Date()); + resource.setOwner("rangerAdmin"); + resource.setUpdatedBy("rangerAdmin"); + resource.setPolicyName("hive Policy"); + resource.setDescription("hive policy description"); + resource.setResourceStatus(RangerCommonEnums.STATUS_ENABLED); + resource.setIsRecursive(1); + resource.setTableType(1); + resource.setColumnType(1); + resource.setPermMapList(vXPermMapList); + + RangerPolicy actualRangerPolicy = serviceUtil.toRangerPolicy(resource, rangerService); + + Assert.assertNotNull(actualRangerPolicy); + Assert.assertEquals(expectedRangerPolicy.getId(), actualRangerPolicy.getId()); + Assert.assertEquals(expectedRangerPolicy.getName(), actualRangerPolicy.getName()); + Assert.assertEquals(expectedRangerPolicy.getService(), actualRangerPolicy.getService()); + Assert.assertEquals(expectedRangerPolicy.getDescription(), actualRangerPolicy.getDescription()); + Assert.assertEquals(expectedRangerPolicy.getPolicyItems(), actualRangerPolicy.getPolicyItems()); + } + + @Test + public void testToVXResourceForPolicyNull() { + RangerPolicy policy = null; + RangerService rangerService = new RangerService(); + rangerService.setName("hive"); + rangerService.setType("hive"); + + VXResource vXResource = serviceUtil.toVXResource(policy, rangerService); + + Assert.assertNull(vXResource); + } + + @Test + public void testToVXResourceForServiceNull() { + RangerPolicy policy = new RangerPolicy(); + policy.setId(1L); + policy.setName("hive Policy"); + policy.setService("hive"); + policy.setDescription("hive policy description"); + + RangerService rangerService = null; + + VXResource vXResource = serviceUtil.toVXResource(policy, rangerService); + + Assert.assertNull(vXResource); + } + + @Test + public void testToVXResourceForPath() { + GUIDUtil guid = new GUIDUtil(); + String guidString = guid.genGUID(); + List auditList = new ArrayList<>(); + + VXAuditMap vxAuditMap = new VXAuditMap(); + vxAuditMap.setResourceId(1L); + vxAuditMap.setAuditType(AppConstants.XA_AUDIT_TYPE_ALL); + auditList.add(vxAuditMap); + + VXResource expectedVXResource = new VXResource(); + expectedVXResource.setName("resource"); + expectedVXResource.setGuid(guidString); + expectedVXResource.setPolicyName("hdfs Policy"); + expectedVXResource.setDescription("hdfs policy description"); + expectedVXResource.setResourceType(1); + expectedVXResource.setAssetName("hdfs"); + expectedVXResource.setAssetType(1); + expectedVXResource.setAuditList(auditList); + + Map rangerPolicyResourceMap = new HashMap<>(); + List valuesList = new ArrayList<>(); + valuesList.add("resource"); + + RangerPolicy policy = new RangerPolicy(); + policy.setId(1L); + policy.setName("hdfs Policy"); + policy.setService("hdfs"); + policy.setDescription("hdfs policy description"); + policy.setIsEnabled(true); + policy.setGuid(guidString); + policy.setIsAuditEnabled(true); + + RangerService rangerService = new RangerService(); + rangerService.setName("hdfs"); + rangerService.setType("hdfs"); + + RangerPolicyResource rangerPolicyResource = new RangerPolicyResource(); + rangerPolicyResource.setIsExcludes(false); + rangerPolicyResource.setIsRecursive(true); + rangerPolicyResource.setValue("/localhost/files"); + rangerPolicyResource.setValues(valuesList); + + rangerPolicyResourceMap.put("path", rangerPolicyResource); + + policy.setResources(rangerPolicyResourceMap); + + VXResource actualVXResource = serviceUtil.toVXResource(policy, rangerService); + + Assert.assertNotNull(actualVXResource); + Assert.assertEquals(expectedVXResource.getName(), actualVXResource.getName()); + Assert.assertEquals(expectedVXResource.getGuid(), actualVXResource.getGuid()); + Assert.assertEquals(expectedVXResource.getPolicyName(), actualVXResource.getPolicyName()); + Assert.assertEquals(expectedVXResource.getResourceType(), actualVXResource.getResourceType()); + Assert.assertEquals(expectedVXResource.getDescription(), actualVXResource.getDescription()); + Assert.assertEquals(expectedVXResource.getAssetName(), actualVXResource.getAssetName()); + Assert.assertEquals(expectedVXResource.getAssetType(), actualVXResource.getAssetType()); + Assert.assertEquals(expectedVXResource.getAuditList().get(0).getResourceId(), actualVXResource.getAuditList().get(0).getResourceId()); + Assert.assertEquals(expectedVXResource.getAuditList().get(0).getAuditType(), actualVXResource.getAuditList().get(0).getAuditType()); + } + + @Test + public void testToVXResourceForTablesColumnFamiliesAndColumn() { + GUIDUtil guid = new GUIDUtil(); + String guidString = guid.genGUID(); + List auditList = new ArrayList<>(); + + VXAuditMap vxAuditMap = new VXAuditMap(); + vxAuditMap.setResourceId(1L); + vxAuditMap.setAuditType(AppConstants.XA_AUDIT_TYPE_ALL); + auditList.add(vxAuditMap); + + VXResource expectedVXResource = new VXResource(); + expectedVXResource.setName("/myTable/myColumnFamilies/myColumn"); + expectedVXResource.setTables("myTable"); + expectedVXResource.setColumnFamilies("myColumnFamilies"); + expectedVXResource.setColumns("myColumn"); + expectedVXResource.setGuid(guidString); + expectedVXResource.setPolicyName("hbase Policy"); + expectedVXResource.setDescription("hbase policy description"); + expectedVXResource.setResourceType(1); + expectedVXResource.setAssetName("hbase"); + expectedVXResource.setAssetType(2); + expectedVXResource.setResourceStatus(1); + expectedVXResource.setTableType(1); + expectedVXResource.setColumnType(1); + expectedVXResource.setAuditList(auditList); + + Map rangerPolicyResourceMap = new HashMap<>(); + List valuesListForTable = new ArrayList<>(); + valuesListForTable.add("myTable"); + + List valuesListForColumn = new ArrayList<>(); + valuesListForColumn.add("myColumn"); + + List valuesListForColumnFamilies = new ArrayList<>(); + valuesListForColumnFamilies.add("myColumnFamilies"); + + RangerPolicy policy = new RangerPolicy(); + policy.setId(1L); + policy.setName("hbase Policy"); + policy.setService("hbase"); + policy.setDescription("hbase policy description"); + policy.setIsEnabled(true); + policy.setGuid(guidString); + policy.setIsAuditEnabled(true); + + RangerService rangerService = new RangerService(); + rangerService.setName("hbase"); + rangerService.setType("hbase"); + + RangerPolicyResource rangerPolicyResourceForTable = new RangerPolicyResource(); + rangerPolicyResourceForTable.setIsExcludes(true); + rangerPolicyResourceForTable.setIsRecursive(true); + rangerPolicyResourceForTable.setValue("table"); + rangerPolicyResourceForTable.setValues(valuesListForTable); + + rangerPolicyResourceMap.put("table", rangerPolicyResourceForTable); + + RangerPolicyResource rangerPolicyResourceForColumn = new RangerPolicyResource(); + rangerPolicyResourceForColumn.setIsExcludes(true); + rangerPolicyResourceForColumn.setIsRecursive(true); + rangerPolicyResourceForColumn.setValue("table"); + rangerPolicyResourceForColumn.setValues(valuesListForColumn); + + rangerPolicyResourceMap.put("column", rangerPolicyResourceForColumn); + + RangerPolicyResource rangerPolicyResourceForColumnFamilies = new RangerPolicyResource(); + rangerPolicyResourceForColumnFamilies.setIsExcludes(true); + rangerPolicyResourceForColumnFamilies.setIsRecursive(true); + rangerPolicyResourceForColumnFamilies.setValue("table"); + rangerPolicyResourceForColumnFamilies.setValues(valuesListForColumnFamilies); + + rangerPolicyResourceMap.put("column-family", rangerPolicyResourceForColumnFamilies); + + policy.setResources(rangerPolicyResourceMap); + + VXResource actualVXResource = serviceUtil.toVXResource(policy, rangerService); + + Assert.assertNotNull(actualVXResource); + Assert.assertEquals(expectedVXResource.getName(), actualVXResource.getName()); + Assert.assertEquals(expectedVXResource.getGuid(), actualVXResource.getGuid()); + Assert.assertEquals(expectedVXResource.getPolicyName(), actualVXResource.getPolicyName()); + Assert.assertEquals(expectedVXResource.getResourceType(), actualVXResource.getResourceType()); + Assert.assertEquals(expectedVXResource.getDescription(), actualVXResource.getDescription()); + Assert.assertEquals(expectedVXResource.getAssetName(), actualVXResource.getAssetName()); + Assert.assertEquals(expectedVXResource.getAssetType(), actualVXResource.getAssetType()); + Assert.assertEquals(expectedVXResource.getResourceStatus(), actualVXResource.getResourceStatus()); + Assert.assertEquals(expectedVXResource.getTableType(), actualVXResource.getTableType()); + Assert.assertEquals(expectedVXResource.getColumnType(), actualVXResource.getColumnType()); + Assert.assertEquals(expectedVXResource.getTables(), actualVXResource.getTables()); + Assert.assertEquals(expectedVXResource.getColumns(), actualVXResource.getColumns()); + Assert.assertEquals(expectedVXResource.getColumnFamilies(), actualVXResource.getColumnFamilies()); + Assert.assertEquals(expectedVXResource.getAuditList().get(0).getResourceId(), actualVXResource.getAuditList().get(0).getResourceId()); + Assert.assertEquals(expectedVXResource.getAuditList().get(0).getAuditType(), actualVXResource.getAuditList().get(0).getAuditType()); + } + + @Test + public void testToVXResourceForTablesColumnsAndDatabase() { + GUIDUtil guid = new GUIDUtil(); + String guidString = guid.genGUID(); + List auditList = new ArrayList<>(); + + VXAuditMap vxAuditMap = new VXAuditMap(); + vxAuditMap.setResourceId(1L); + vxAuditMap.setAuditType(AppConstants.XA_AUDIT_TYPE_ALL); + auditList.add(vxAuditMap); + + VXResource expectedVXResource = new VXResource(); + expectedVXResource.setName("/myDatabase/myTable/myColumn"); + expectedVXResource.setTables("myTable"); + expectedVXResource.setDatabases("myDatabase"); + expectedVXResource.setColumns("myColumn"); + expectedVXResource.setGuid(guidString); + expectedVXResource.setPolicyName("hive Policy"); + expectedVXResource.setDescription("hive policy description"); + expectedVXResource.setResourceType(1); + expectedVXResource.setAssetName("hive"); + expectedVXResource.setAssetType(3); + expectedVXResource.setResourceStatus(1); + expectedVXResource.setTableType(1); + expectedVXResource.setColumnType(1); + expectedVXResource.setAuditList(auditList); + + Map rangerPolicyResourceMap = new HashMap<>(); + List valuesListForTable = new ArrayList<>(); + valuesListForTable.add("myTable"); + + List valuesListForColumn = new ArrayList<>(); + valuesListForColumn.add("myColumn"); + + List valuesListForDatabase = new ArrayList<>(); + valuesListForDatabase.add("myDatabase"); + + RangerPolicy policy = new RangerPolicy(); + policy.setId(1L); + policy.setName("hive Policy"); + policy.setService("hive"); + policy.setDescription("hive policy description"); + policy.setIsEnabled(true); + policy.setGuid(guidString); + policy.setIsAuditEnabled(true); + + RangerService rangerService = new RangerService(); + rangerService.setName("hive"); + rangerService.setType("hive"); + + RangerPolicyResource rangerPolicyResourceForTable = new RangerPolicyResource(); + rangerPolicyResourceForTable.setIsExcludes(true); + rangerPolicyResourceForTable.setIsRecursive(true); + rangerPolicyResourceForTable.setValue("table"); + rangerPolicyResourceForTable.setValues(valuesListForTable); + + rangerPolicyResourceMap.put("table", rangerPolicyResourceForTable); + + RangerPolicyResource rangerPolicyResourceForColumn = new RangerPolicyResource(); + rangerPolicyResourceForColumn.setIsExcludes(true); + rangerPolicyResourceForColumn.setIsRecursive(true); + rangerPolicyResourceForColumn.setValue("column"); + rangerPolicyResourceForColumn.setValues(valuesListForColumn); + + rangerPolicyResourceMap.put("column", rangerPolicyResourceForColumn); + + RangerPolicyResource rangerPolicyResourceForDatabase = new RangerPolicyResource(); + rangerPolicyResourceForDatabase.setIsExcludes(true); + rangerPolicyResourceForDatabase.setIsRecursive(true); + rangerPolicyResourceForDatabase.setValue("database"); + rangerPolicyResourceForDatabase.setValues(valuesListForDatabase); + + rangerPolicyResourceMap.put("database", rangerPolicyResourceForDatabase); + + policy.setResources(rangerPolicyResourceMap); + + VXResource actualVXResource = serviceUtil.toVXResource(policy, rangerService); + + Assert.assertNotNull(actualVXResource); + Assert.assertEquals(expectedVXResource.getName(), actualVXResource.getName()); + Assert.assertEquals(expectedVXResource.getGuid(), actualVXResource.getGuid()); + Assert.assertEquals(expectedVXResource.getPolicyName(), actualVXResource.getPolicyName()); + Assert.assertEquals(expectedVXResource.getResourceType(), actualVXResource.getResourceType()); + Assert.assertEquals(expectedVXResource.getDescription(), actualVXResource.getDescription()); + Assert.assertEquals(expectedVXResource.getAssetName(), actualVXResource.getAssetName()); + Assert.assertEquals(expectedVXResource.getAssetType(), actualVXResource.getAssetType()); + Assert.assertEquals(expectedVXResource.getResourceStatus(), actualVXResource.getResourceStatus()); + Assert.assertEquals(expectedVXResource.getTableType(), actualVXResource.getTableType()); + Assert.assertEquals(expectedVXResource.getColumnType(), actualVXResource.getColumnType()); + Assert.assertEquals(expectedVXResource.getTables(), actualVXResource.getTables()); + Assert.assertEquals(expectedVXResource.getColumns(), actualVXResource.getColumns()); + Assert.assertEquals(expectedVXResource.getDatabases(), actualVXResource.getDatabases()); + Assert.assertEquals(expectedVXResource.getAuditList().get(0).getResourceId(), actualVXResource.getAuditList().get(0).getResourceId()); + Assert.assertEquals(expectedVXResource.getAuditList().get(0).getAuditType(), actualVXResource.getAuditList().get(0).getAuditType()); + } + + @Test + public void testToVXResourceForTopologyAndService() { + GUIDUtil guid = new GUIDUtil(); + String guidString = guid.genGUID(); + List auditList = new ArrayList<>(); + + VXAuditMap vxAuditMap = new VXAuditMap(); + vxAuditMap.setResourceId(1L); + vxAuditMap.setAuditType(AppConstants.XA_AUDIT_TYPE_ALL); + auditList.add(vxAuditMap); + + VXResource expectedVXResource = new VXResource(); + expectedVXResource.setName("/myTopology/myService"); + expectedVXResource.setTopologies("myTopology"); + expectedVXResource.setServices("myService"); + expectedVXResource.setGuid(guidString); + expectedVXResource.setPolicyName("knox Policy"); + expectedVXResource.setDescription("knox policy description"); + expectedVXResource.setResourceType(1); + expectedVXResource.setAssetName("knox"); + expectedVXResource.setAssetType(5); + expectedVXResource.setResourceStatus(1); + expectedVXResource.setAuditList(auditList); + + Map rangerPolicyResourceMap = new HashMap<>(); + List valuesListForTopology = new ArrayList<>(); + valuesListForTopology.add("myTopology"); + + List valuesListForService = new ArrayList<>(); + valuesListForService.add("myService"); + + RangerPolicy policy = new RangerPolicy(); + policy.setId(1L); + policy.setName("knox Policy"); + policy.setService("knox"); + policy.setDescription("knox policy description"); + policy.setIsEnabled(true); + policy.setGuid(guidString); + policy.setIsAuditEnabled(true); + + RangerService rangerService = new RangerService(); + rangerService.setName("knox"); + rangerService.setType("knox"); + + RangerPolicyResource rangerPolicyResourceForTopology = new RangerPolicyResource(); + rangerPolicyResourceForTopology.setValue("topology"); + rangerPolicyResourceForTopology.setValues(valuesListForTopology); + + rangerPolicyResourceMap.put("topology", rangerPolicyResourceForTopology); + + RangerPolicyResource rangerPolicyResourceForService = new RangerPolicyResource(); + rangerPolicyResourceForService.setValue("service"); + rangerPolicyResourceForService.setValues(valuesListForService); + + rangerPolicyResourceMap.put("service", rangerPolicyResourceForService); + + policy.setResources(rangerPolicyResourceMap); + + VXResource actualVXResource = serviceUtil.toVXResource(policy, rangerService); + + Assert.assertNotNull(actualVXResource); + Assert.assertEquals(expectedVXResource.getName(), actualVXResource.getName()); + Assert.assertEquals(expectedVXResource.getGuid(), actualVXResource.getGuid()); + Assert.assertEquals(expectedVXResource.getPolicyName(), actualVXResource.getPolicyName()); + Assert.assertEquals(expectedVXResource.getResourceType(), actualVXResource.getResourceType()); + Assert.assertEquals(expectedVXResource.getDescription(), actualVXResource.getDescription()); + Assert.assertEquals(expectedVXResource.getAssetName(), actualVXResource.getAssetName()); + Assert.assertEquals(expectedVXResource.getAssetType(), actualVXResource.getAssetType()); + Assert.assertEquals(expectedVXResource.getResourceStatus(), actualVXResource.getResourceStatus()); + Assert.assertEquals(expectedVXResource.getTopologies(), actualVXResource.getTopologies()); + Assert.assertEquals(expectedVXResource.getServices(), actualVXResource.getServices()); + Assert.assertEquals(expectedVXResource.getAuditList().get(0).getResourceId(), actualVXResource.getAuditList().get(0).getResourceId()); + Assert.assertEquals(expectedVXResource.getAuditList().get(0).getAuditType(), actualVXResource.getAuditList().get(0).getAuditType()); + } + + @Test + public void testToVXResourceForStormTopologyAndVXPermMapListWithUserList() { + GUIDUtil guid = new GUIDUtil(); + String guidString = guid.genGUID(); + XXUser xxUser = new XXUser(); + xxUser.setId(6L); + xxUser.setName("rangerAdmin"); + List auditList = new ArrayList<>(); + + VXAuditMap vxAuditMap = new VXAuditMap(); + vxAuditMap.setResourceId(1L); + vxAuditMap.setAuditType(AppConstants.XA_AUDIT_TYPE_ALL); + auditList.add(vxAuditMap); + + List vXPermMapList = new ArrayList<>(); + VXPermMap vXPermMap1 = new VXPermMap(); + vXPermMap1.setPermFor(1); + vXPermMap1.setUserId(6L); + vXPermMap1.setPermType(12); + vXPermMap1.setUserName("rangerAdmin"); + vXPermMap1.setIpAddress("10.329.85.65"); + + vXPermMapList.add(vXPermMap1); + + VXPermMap vXPermMap2 = new VXPermMap(); + vXPermMap2.setPermFor(1); + vXPermMap2.setUserId(6L); + vXPermMap2.setPermType(6); + vXPermMap2.setUserName("rangerAdmin"); + vXPermMap2.setIpAddress("10.329.85.65"); + + vXPermMapList.add(vXPermMap2); + + VXResource expectedVXResource = new VXResource(); + expectedVXResource.setGuid(guidString); + expectedVXResource.setName("myTopology"); + expectedVXResource.setTopologies("myTopology"); + expectedVXResource.setPolicyName("storm Policy"); + expectedVXResource.setDescription("storm policy description"); + expectedVXResource.setResourceType(1); + expectedVXResource.setAssetName("storm"); + expectedVXResource.setAssetType(6); + expectedVXResource.setResourceStatus(1); + expectedVXResource.setAuditList(auditList); + expectedVXResource.setPermMapList(vXPermMapList); + + Map rangerPolicyResourceMap = new HashMap<>(); + List valuesListForTopology = new ArrayList<>(); + valuesListForTopology.add("myTopology"); + + RangerPolicyResource rangerPolicyResourceForTopology = new RangerPolicyResource(); + rangerPolicyResourceForTopology.setValue("topology"); + rangerPolicyResourceForTopology.setValues(valuesListForTopology); + + rangerPolicyResourceMap.put("topology", rangerPolicyResourceForTopology); + + List valuesListForRangerPolicyItemCondition = new ArrayList<>(); + valuesListForRangerPolicyItemCondition.add("10.329.85.65"); + + List usersList = new ArrayList<>(); + usersList.add("rangerAdmin"); + + RangerPolicy policy = new RangerPolicy(); + policy.setId(1L); + policy.setName("storm Policy"); + policy.setService("storm"); + policy.setDescription("storm policy description"); + policy.setIsEnabled(true); + policy.setGuid(guidString); + policy.setIsAuditEnabled(true); + + RangerService rangerService = new RangerService(); + rangerService.setName("storm"); + rangerService.setType("storm"); + + List rangerPolicyItemList = new ArrayList<>(); + + RangerPolicyItem rangerPolicyItem = new RangerPolicyItem(); + + List rangerPolicyItemConditionList = new ArrayList<>(); + RangerPolicyItemCondition rangerPolicyItemCondition = new RangerPolicyItemCondition(); + rangerPolicyItemCondition.setType("ipaddress"); + rangerPolicyItemCondition.setValues(valuesListForRangerPolicyItemCondition); + rangerPolicyItemConditionList.add(rangerPolicyItemCondition); + + rangerPolicyItem.setConditions(rangerPolicyItemConditionList); + + rangerPolicyItem.setUsers(usersList); + + List rangerPolicyItemAccessList = new ArrayList<>(); + RangerPolicyItemAccess rangerPolicyItemAccess = new RangerPolicyItemAccess(); + rangerPolicyItemAccess.setIsAllowed(true); + rangerPolicyItemAccess.setType("drop"); + + rangerPolicyItemAccessList.add(rangerPolicyItemAccess); + + rangerPolicyItem.setAccesses(rangerPolicyItemAccessList); + + rangerPolicyItem.setDelegateAdmin(true); + + rangerPolicyItemList.add(rangerPolicyItem); + + policy.setPolicyItems(rangerPolicyItemList); + + policy.setResources(rangerPolicyResourceMap); + + Mockito.when(xaDaoMgr.getXXUser()).thenReturn(xxUserDao); + Mockito.when(xxUserDao.findByUserName("rangerAdmin")).thenReturn(xxUser); + + VXResource actualVXResource = serviceUtil.toVXResource(policy, rangerService); + + Assert.assertNotNull(actualVXResource); + Assert.assertEquals(expectedVXResource.getName(), actualVXResource.getName()); + Assert.assertEquals(expectedVXResource.getGuid(), actualVXResource.getGuid()); + Assert.assertEquals(expectedVXResource.getPolicyName(), actualVXResource.getPolicyName()); + Assert.assertEquals(expectedVXResource.getResourceType(), actualVXResource.getResourceType()); + Assert.assertEquals(expectedVXResource.getDescription(), actualVXResource.getDescription()); + Assert.assertEquals(expectedVXResource.getAssetName(), actualVXResource.getAssetName()); + Assert.assertEquals(expectedVXResource.getAssetType(), actualVXResource.getAssetType()); + Assert.assertEquals(expectedVXResource.getResourceStatus(), actualVXResource.getResourceStatus()); + Assert.assertEquals(expectedVXResource.getTopologies(), actualVXResource.getTopologies()); + Assert.assertEquals(expectedVXResource.getAuditList().get(0).getResourceId(), actualVXResource.getAuditList().get(0).getResourceId()); + Assert.assertEquals(expectedVXResource.getAuditList().get(0).getAuditType(), actualVXResource.getAuditList().get(0).getAuditType()); + Assert.assertEquals(expectedVXResource.getPermMapList().get(0).getPermFor(), actualVXResource.getPermMapList().get(0).getPermFor()); + Assert.assertEquals(expectedVXResource.getPermMapList().get(0).getPermType(), actualVXResource.getPermMapList().get(0).getPermType()); + Assert.assertEquals(expectedVXResource.getPermMapList().get(0).getUserName(), actualVXResource.getPermMapList().get(0).getUserName()); + Assert.assertEquals(expectedVXResource.getPermMapList().get(0).getIpAddress(), actualVXResource.getPermMapList().get(0).getIpAddress()); + Assert.assertEquals(expectedVXResource.getPermMapList().get(0).getUserId(), actualVXResource.getPermMapList().get(0).getUserId()); + + Assert.assertEquals(expectedVXResource.getPermMapList().get(1).getPermFor(), actualVXResource.getPermMapList().get(1).getPermFor()); + Assert.assertEquals(expectedVXResource.getPermMapList().get(1).getPermType(), actualVXResource.getPermMapList().get(1).getPermType()); + Assert.assertEquals(expectedVXResource.getPermMapList().get(1).getUserName(), actualVXResource.getPermMapList().get(1).getUserName()); + Assert.assertEquals(expectedVXResource.getPermMapList().get(1).getIpAddress(), actualVXResource.getPermMapList().get(1).getIpAddress()); + Assert.assertEquals(expectedVXResource.getPermMapList().get(1).getUserId(), actualVXResource.getPermMapList().get(1).getUserId()); + } + + @Test + public void testToVXResourceForStormTopologyAndVXPermMapListWithGroupList() { + GUIDUtil guid = new GUIDUtil(); + String guidString = guid.genGUID(); + XXGroup xxGroup = new XXGroup(); + xxGroup.setId(6L); + xxGroup.setName("rangerGroup"); + List auditList = new ArrayList<>(); - GrantRevokeRequest actualGrantRevokeRequest = serviceUtil.toGrantRevokeRequest(vXPolicy); + VXAuditMap vxAuditMap = new VXAuditMap(); + vxAuditMap.setResourceId(1L); + vxAuditMap.setAuditType(AppConstants.XA_AUDIT_TYPE_ALL); + auditList.add(vxAuditMap); - Assert.assertNotNull(actualGrantRevokeRequest); - Assert.assertTrue(actualGrantRevokeRequest.getEnableAudit()); - Assert.assertFalse(actualGrantRevokeRequest.getIsRecursive()); - Assert.assertTrue(actualGrantRevokeRequest.getReplaceExistingPermissions()); - Assert.assertEquals(expectedGrantRevokeRequest.getGrantor(), actualGrantRevokeRequest.getGrantor()); - Assert.assertEquals(expectedGrantRevokeRequest.getResource(), actualGrantRevokeRequest.getResource()); - } - - @Test - public void testToGrantRevokeRequestForPermMapList() throws Exception{ - GrantRevokeRequest expectedGrantRevokeRequest = new GrantRevokeRequest(); - expectedGrantRevokeRequest.setGrantor("rangerAdmin"); - expectedGrantRevokeRequest.setEnableAudit(true); - expectedGrantRevokeRequest.setIsRecursive(false); - expectedGrantRevokeRequest.setReplaceExistingPermissions(true); - - List userList = new ArrayList(); - userList.add("rangerAdmin"); - - List groupList = new ArrayList(); - groupList.add("rangerGroup"); - - List permObjList = new ArrayList(); - permObjList.add("Admin"); - - Map mapResource = new HashMap(); - mapResource.put("database", "myDatabase"); - mapResource.put("table", "myTable"); - mapResource.put("column", "myColumn"); - - expectedGrantRevokeRequest.setResource(mapResource); - - List vXPermObjList = new ArrayList(); - VXPermObj vXPermObj = new VXPermObj(); - vXPermObj.setUserList(userList); - vXPermObj.setGroupList(groupList); - vXPermObj.setPermList(permObjList); - - vXPermObjList.add(vXPermObj); - - - String serviceName = "hive"; - - RangerService rangerService = new RangerService(); - rangerService.setId(1L); - rangerService.setName("hiveService"); - rangerService.setIsEnabled(true); - rangerService.setType("hive"); - - VXPolicy vXPolicy = new VXPolicy(); - vXPolicy.setRepositoryName("hive"); - vXPolicy.setGrantor("rangerAdmin"); - vXPolicy.setReplacePerm(true); - vXPolicy.setColumns("myColumn"); - vXPolicy.setDatabases("myDatabase"); - vXPolicy.setTables("myTable"); - vXPolicy.setPermMapList(vXPermObjList); - - Mockito.when(svcStore.getServiceByName(serviceName)).thenReturn(rangerService); - - GrantRevokeRequest actualGrantRevokeRequest = serviceUtil.toGrantRevokeRequest(vXPolicy); - - Assert.assertNotNull(actualGrantRevokeRequest); - Assert.assertTrue(actualGrantRevokeRequest.getEnableAudit()); - Assert.assertTrue(actualGrantRevokeRequest.getDelegateAdmin()); - Assert.assertFalse(actualGrantRevokeRequest.getIsRecursive()); - Assert.assertTrue(actualGrantRevokeRequest.getReplaceExistingPermissions()); - Assert.assertTrue(actualGrantRevokeRequest.getUsers().contains("rangerAdmin")); - Assert.assertTrue(actualGrantRevokeRequest.getGroups().contains("rangerGroup")); - Assert.assertEquals(expectedGrantRevokeRequest.getGrantor(), actualGrantRevokeRequest.getGrantor()); - Assert.assertEquals(expectedGrantRevokeRequest.getResource(), actualGrantRevokeRequest.getResource()); - } - - @Test - public void testToRangerPolicyForNullServiceAndNullVXPolicy(){ - VXPolicy vXPolicy = null; - RangerService service = null; - - RangerPolicy actualRangerPolicy = serviceUtil.toRangerPolicy(vXPolicy, service); - Assert.assertNull(actualRangerPolicy); - } - - @Test - public void testToRangerPolicy(){ - Date date = new Date(); - - List userList = new ArrayList(); - userList.add("rangerAdmin"); - - List groupList = new ArrayList(); - groupList.add("rangerGroup"); - - List permObjList = new ArrayList(); - permObjList.add("Admin"); - - Map resourceMap = new HashMap(); - List valuesList = new ArrayList(); - valuesList.add("resource"); - - RangerPolicyResource rangerPolicyResource = new RangerPolicyResource(); - rangerPolicyResource.setIsExcludes(false); - rangerPolicyResource.setIsRecursive(true); - rangerPolicyResource.setValues(valuesList); - - resourceMap.put("path", rangerPolicyResource); - - List rangerPolicyItemList = new ArrayList(); - RangerPolicyItem rangerPolicyItem = new RangerPolicyItem(); - rangerPolicyItem.setUsers(userList); - rangerPolicyItem.setGroups(groupList); - - List rangerPolicyItemConditionList = new ArrayList(); - RangerPolicyItemCondition rangerPolicyItemCondition = new RangerPolicyItemCondition(); - rangerPolicyItemCondition.setType("ipaddress"); - List conditionValueList = new ArrayList(); - conditionValueList.add("10.129.35.86"); - rangerPolicyItemCondition.setValues(conditionValueList); - rangerPolicyItemConditionList.add(rangerPolicyItemCondition); - rangerPolicyItem.setConditions(rangerPolicyItemConditionList); - rangerPolicyItem.setDelegateAdmin(true); - - rangerPolicyItemList.add(rangerPolicyItem); - - RangerPolicy expectedRangerPolicy = new RangerPolicy(); - expectedRangerPolicy.setId(1L); - expectedRangerPolicy.setName("hdfs"); - expectedRangerPolicy.setCreatedBy("rangerAdmin"); - expectedRangerPolicy.setCreateTime(date); - expectedRangerPolicy.setDescription("hdfs policy description"); - expectedRangerPolicy.setIsAuditEnabled(true); - expectedRangerPolicy.setResources(resourceMap); - expectedRangerPolicy.setPolicyItems(rangerPolicyItemList); - - VXPolicy vXPolicy = new VXPolicy(); - vXPolicy.setId(1L); - vXPolicy.setCreateDate(date); - vXPolicy.setUpdateDate(date); - vXPolicy.setOwner("rangerAdmin"); - vXPolicy.setUpdatedBy("rangerAdmin"); - vXPolicy.setPolicyName("hdfs"); - vXPolicy.setDescription("hdfs policy description"); - vXPolicy.setIsEnabled(true); - vXPolicy.setIsAuditEnabled(true); - vXPolicy.setIsRecursive(true); - vXPolicy.setResourceName("resource"); - - RangerService service = new RangerService(); - service.setId(1L); - service.setName("hdfsService"); - service.setType("hdfs"); - - List vXPermObjList = new ArrayList(); - VXPermObj vXPermObj = new VXPermObj(); - vXPermObj.setUserList(userList); - vXPermObj.setGroupList(groupList); - vXPermObj.setPermList(permObjList); - - vXPermObj.setIpAddress("10.129.35.86"); - - vXPermObjList.add(vXPermObj); - - vXPolicy.setPermMapList(vXPermObjList); - - RangerPolicy actualRangerPolicy = serviceUtil.toRangerPolicy(vXPolicy, service); - - Assert.assertNotNull(actualRangerPolicy); - Assert.assertEquals(expectedRangerPolicy.getId(), actualRangerPolicy.getId()); - Assert.assertEquals(expectedRangerPolicy.getName(), actualRangerPolicy.getName()); - Assert.assertEquals(expectedRangerPolicy.getDescription(), actualRangerPolicy.getDescription()); - Assert.assertEquals(expectedRangerPolicy.getCreatedBy(), actualRangerPolicy.getCreatedBy()); - Assert.assertTrue(actualRangerPolicy.getIsAuditEnabled()); - Assert.assertEquals(expectedRangerPolicy.getResources(), actualRangerPolicy.getResources()); - Assert.assertEquals(expectedRangerPolicy.getPolicyItems(), actualRangerPolicy.getPolicyItems()); - } + List vXPermMapList = new ArrayList<>(); + VXPermMap vXPermMap1 = new VXPermMap(); + vXPermMap1.setPermFor(2); + vXPermMap1.setPermType(12); + vXPermMap1.setGroupName("rangerGroup"); + vXPermMap1.setIpAddress("10.329.85.65"); + + vXPermMapList.add(vXPermMap1); + + VXPermMap vXPermMap2 = new VXPermMap(); + vXPermMap2.setPermFor(2); + vXPermMap2.setPermType(6); + vXPermMap2.setGroupName("rangerGroup"); + vXPermMap2.setIpAddress("10.329.85.65"); + + vXPermMapList.add(vXPermMap2); + + VXResource expectedVXResource = new VXResource(); + expectedVXResource.setGuid(guidString); + expectedVXResource.setName("myTopology"); + expectedVXResource.setTopologies("myTopology"); + expectedVXResource.setPolicyName("storm Policy"); + expectedVXResource.setDescription("storm policy description"); + expectedVXResource.setResourceType(1); + expectedVXResource.setAssetName("storm"); + expectedVXResource.setAssetType(6); + expectedVXResource.setResourceStatus(1); + expectedVXResource.setAuditList(auditList); + expectedVXResource.setPermMapList(vXPermMapList); + + Map rangerPolicyResourceMap = new HashMap<>(); + List valuesListForTopology = new ArrayList<>(); + valuesListForTopology.add("myTopology"); + + RangerPolicyResource rangerPolicyResourceForTopology = new RangerPolicyResource(); + rangerPolicyResourceForTopology.setValue("topology"); + rangerPolicyResourceForTopology.setValues(valuesListForTopology); + + rangerPolicyResourceMap.put("topology", rangerPolicyResourceForTopology); + + List valuesListForRangerPolicyItemCondition = new ArrayList<>(); + valuesListForRangerPolicyItemCondition.add("10.329.85.65"); + + List groupList = new ArrayList<>(); + groupList.add("rangerGroup"); + + RangerPolicy policy = new RangerPolicy(); + policy.setId(1L); + policy.setName("storm Policy"); + policy.setService("storm"); + policy.setDescription("storm policy description"); + policy.setIsEnabled(true); + policy.setGuid(guidString); + policy.setIsAuditEnabled(true); + + RangerService rangerService = new RangerService(); + rangerService.setName("storm"); + rangerService.setType("storm"); + + List rangerPolicyItemList = new ArrayList<>(); + + RangerPolicyItem rangerPolicyItem = new RangerPolicyItem(); + + List rangerPolicyItemConditionList = new ArrayList<>(); + RangerPolicyItemCondition rangerPolicyItemCondition = new RangerPolicyItemCondition(); + rangerPolicyItemCondition.setType("ipaddress"); + rangerPolicyItemCondition.setValues(valuesListForRangerPolicyItemCondition); + rangerPolicyItemConditionList.add(rangerPolicyItemCondition); + + rangerPolicyItem.setConditions(rangerPolicyItemConditionList); + + rangerPolicyItem.setGroups(groupList); + + List rangerPolicyItemAccessList = new ArrayList<>(); + RangerPolicyItemAccess rangerPolicyItemAccess = new RangerPolicyItemAccess(); + rangerPolicyItemAccess.setIsAllowed(true); + rangerPolicyItemAccess.setType("drop"); + + rangerPolicyItemAccessList.add(rangerPolicyItemAccess); + + rangerPolicyItem.setAccesses(rangerPolicyItemAccessList); + + rangerPolicyItem.setDelegateAdmin(true); + + rangerPolicyItemList.add(rangerPolicyItem); + + policy.setPolicyItems(rangerPolicyItemList); + + policy.setResources(rangerPolicyResourceMap); + + Mockito.when(xaDaoMgr.getXXGroup()).thenReturn(xxGroupDao); + Mockito.when(xxGroupDao.findByGroupName("rangerGroup")).thenReturn(xxGroup); + + VXResource actualVXResource = serviceUtil.toVXResource(policy, rangerService); + + Assert.assertNotNull(actualVXResource); + Assert.assertEquals(expectedVXResource.getName(), actualVXResource.getName()); + Assert.assertEquals(expectedVXResource.getGuid(), actualVXResource.getGuid()); + Assert.assertEquals(expectedVXResource.getPolicyName(), actualVXResource.getPolicyName()); + Assert.assertEquals(expectedVXResource.getResourceType(), actualVXResource.getResourceType()); + Assert.assertEquals(expectedVXResource.getDescription(), actualVXResource.getDescription()); + Assert.assertEquals(expectedVXResource.getAssetName(), actualVXResource.getAssetName()); + Assert.assertEquals(expectedVXResource.getAssetType(), actualVXResource.getAssetType()); + Assert.assertEquals(expectedVXResource.getResourceStatus(), actualVXResource.getResourceStatus()); + Assert.assertEquals(expectedVXResource.getTopologies(), actualVXResource.getTopologies()); + Assert.assertEquals(expectedVXResource.getAuditList().get(0).getResourceId(), actualVXResource.getAuditList().get(0).getResourceId()); + Assert.assertEquals(expectedVXResource.getAuditList().get(0).getAuditType(), actualVXResource.getAuditList().get(0).getAuditType()); + Assert.assertEquals(expectedVXResource.getPermMapList().get(0).getPermFor(), actualVXResource.getPermMapList().get(0).getPermFor()); + Assert.assertEquals(expectedVXResource.getPermMapList().get(0).getPermType(), actualVXResource.getPermMapList().get(0).getPermType()); + Assert.assertEquals(expectedVXResource.getPermMapList().get(0).getUserName(), actualVXResource.getPermMapList().get(0).getUserName()); + Assert.assertEquals(expectedVXResource.getPermMapList().get(0).getIpAddress(), actualVXResource.getPermMapList().get(0).getIpAddress()); + Assert.assertEquals(expectedVXResource.getPermMapList().get(0).getUserId(), actualVXResource.getPermMapList().get(0).getUserId()); + + Assert.assertEquals(expectedVXResource.getPermMapList().get(1).getPermFor(), actualVXResource.getPermMapList().get(1).getPermFor()); + Assert.assertEquals(expectedVXResource.getPermMapList().get(1).getPermType(), actualVXResource.getPermMapList().get(1).getPermType()); + Assert.assertEquals(expectedVXResource.getPermMapList().get(1).getUserName(), actualVXResource.getPermMapList().get(1).getUserName()); + Assert.assertEquals(expectedVXResource.getPermMapList().get(1).getIpAddress(), actualVXResource.getPermMapList().get(1).getIpAddress()); + Assert.assertEquals(expectedVXResource.getPermMapList().get(1).getUserId(), actualVXResource.getPermMapList().get(1).getUserId()); + } + + @Test + public void testPublicObjecttoVXAsset() { + Date date = new Date(); + + VXAsset expectedVXAsset = new VXAsset(); + expectedVXAsset.setId(1L); + expectedVXAsset.setCreateDate(date); + expectedVXAsset.setUpdateDate(date); + expectedVXAsset.setOwner("rangerAdmin"); + expectedVXAsset.setUpdatedBy("rangerAdmin"); + expectedVXAsset.setAssetType(3); + expectedVXAsset.setActiveStatus(RangerCommonEnums.STATUS_ENABLED); + expectedVXAsset.setName("hive"); + expectedVXAsset.setDescription("hive description"); + expectedVXAsset.setConfig("/myConfig"); + + VXRepository vXRepository = new VXRepository(); + vXRepository.setId(1L); + vXRepository.setCreateDate(date); + vXRepository.setUpdateDate(date); + vXRepository.setOwner("rangerAdmin"); + vXRepository.setUpdatedBy("rangerAdmin"); + vXRepository.setRepositoryType("hive"); + vXRepository.setIsActive(true); + vXRepository.setName("hive"); + vXRepository.setDescription("hive description"); + vXRepository.setConfig("/myConfig"); + + VXAsset actualVXAsset = serviceUtil.publicObjecttoVXAsset(vXRepository); + + Assert.assertNotNull(actualVXAsset); + Assert.assertEquals(actualVXAsset.getActiveStatus(), expectedVXAsset.getActiveStatus()); + Assert.assertEquals(actualVXAsset.getId(), expectedVXAsset.getId()); + Assert.assertEquals(actualVXAsset.getName(), expectedVXAsset.getName()); + Assert.assertEquals(actualVXAsset.getDescription(), expectedVXAsset.getDescription()); + Assert.assertEquals(actualVXAsset.getCreateDate(), expectedVXAsset.getCreateDate()); + Assert.assertEquals(actualVXAsset.getOwner(), expectedVXAsset.getOwner()); + Assert.assertEquals(actualVXAsset.getAssetType(), expectedVXAsset.getAssetType()); + Assert.assertEquals(actualVXAsset.getConfig(), expectedVXAsset.getConfig()); + } + + @Test + public void testVXAssetToPublicObject() { + Date date = new Date(); + + VXRepository expectedVXRepository = new VXRepository(); + expectedVXRepository.setId(1L); + expectedVXRepository.setCreateDate(date); + expectedVXRepository.setUpdateDate(date); + expectedVXRepository.setOwner("rangerAdmin"); + expectedVXRepository.setUpdatedBy("rangerAdmin"); + expectedVXRepository.setRepositoryType("hive"); + expectedVXRepository.setIsActive(true); + expectedVXRepository.setName("hive"); + expectedVXRepository.setDescription("hive description"); + expectedVXRepository.setConfig("/myConfig"); + + VXAsset vXAsset = new VXAsset(); + vXAsset.setId(1L); + vXAsset.setCreateDate(date); + vXAsset.setUpdateDate(date); + vXAsset.setOwner("rangerAdmin"); + vXAsset.setUpdatedBy("rangerAdmin"); + vXAsset.setAssetType(3); + vXAsset.setActiveStatus(RangerCommonEnums.STATUS_ENABLED); + vXAsset.setName("hive"); + vXAsset.setDescription("hive description"); + vXAsset.setConfig("/myConfig"); + + VXRepository actualVXRepository = serviceUtil.vXAssetToPublicObject(vXAsset); + + Assert.assertNotNull(actualVXRepository); + Assert.assertEquals(expectedVXRepository.getId(), actualVXRepository.getId()); + Assert.assertEquals(expectedVXRepository.getName(), actualVXRepository.getName()); + Assert.assertEquals(expectedVXRepository.getDescription(), actualVXRepository.getDescription()); + Assert.assertTrue(actualVXRepository.getIsActive()); + Assert.assertEquals(expectedVXRepository.getCreateDate(), actualVXRepository.getCreateDate()); + Assert.assertEquals(expectedVXRepository.getOwner(), actualVXRepository.getOwner()); + Assert.assertEquals(expectedVXRepository.getRepositoryType(), actualVXRepository.getRepositoryType()); + Assert.assertEquals(expectedVXRepository.getConfig(), actualVXRepository.getConfig()); + } + + @Test + public void testGetMappedSearchParams() { + ArrayList statusList = new ArrayList<>(); + statusList.add(RangerCommonEnums.STATUS_DISABLED); + statusList.add(RangerCommonEnums.STATUS_ENABLED); + + SearchCriteria expectedSearchCriteria = new SearchCriteria(); + expectedSearchCriteria.addParam("status", statusList); + expectedSearchCriteria.addParam("type", 3); + + SearchCriteria sc = new SearchCriteria(); + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + + sc.addParam("status", null); + sc.addParam("type", "hive"); + + SearchCriteria actualSearchCriteria = serviceUtil.getMappedSearchParams(request, sc); + + Assert.assertNotNull(actualSearchCriteria); + Assert.assertEquals(expectedSearchCriteria.getParamValue("type"), actualSearchCriteria.getParamValue("type")); + Assert.assertEquals(expectedSearchCriteria.getParamValue("status"), actualSearchCriteria.getParamValue("status")); + } + + @Test + public void testIsValidService() throws Exception { + RangerService rangerService = new RangerService(); + rangerService.setId(1L); + rangerService.setName("hiveService"); + rangerService.setIsEnabled(true); + + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + String serviceName = "hiveService"; + + Mockito.when(svcStore.getServiceByName(serviceName)).thenReturn(rangerService); + boolean isValid = serviceUtil.isValidService(serviceName, request); + + Assert.assertTrue(isValid); + } + + @Test + public void testIsValidateHttpsAuthentication() throws Exception { + RangerService rangerService = new RangerService(); + rangerService.setId(1L); + rangerService.setName("hiveService"); + rangerService.setIsEnabled(true); + + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + String serviceName = "hiveService"; + + Mockito.when(svcStore.getServiceByName(serviceName)).thenReturn(rangerService); + boolean isValidAuthentication = serviceUtil.isValidateHttpsAuthentication(serviceName, request); + + Assert.assertTrue(isValidAuthentication); + } + + @Test + public void testToGrantRevokeRequestForHive() throws Exception { + GrantRevokeRequest expectedGrantRevokeRequest = new GrantRevokeRequest(); + expectedGrantRevokeRequest.setGrantor("rangerAdmin"); + expectedGrantRevokeRequest.setEnableAudit(true); + expectedGrantRevokeRequest.setIsRecursive(false); + expectedGrantRevokeRequest.setReplaceExistingPermissions(true); + + Map mapResource = new HashMap<>(); + mapResource.put("database", "myDatabase"); + mapResource.put("table", "myTable"); + mapResource.put("column", "myColumn"); + + expectedGrantRevokeRequest.setResource(mapResource); + + String serviceName = "hive"; + + RangerService rangerService = new RangerService(); + rangerService.setId(1L); + rangerService.setName("hiveService"); + rangerService.setIsEnabled(true); + rangerService.setType("hive"); + + VXPolicy vXPolicy = new VXPolicy(); + vXPolicy.setRepositoryName("hive"); + vXPolicy.setGrantor("rangerAdmin"); + vXPolicy.setReplacePerm(true); + vXPolicy.setDatabases("myDatabase"); + vXPolicy.setColumns("myColumn"); + vXPolicy.setTables("myTable"); + + Mockito.when(svcStore.getServiceByName(serviceName)).thenReturn(rangerService); + + GrantRevokeRequest actualGrantRevokeRequest = serviceUtil.toGrantRevokeRequest(vXPolicy); + + Assert.assertNotNull(actualGrantRevokeRequest); + Assert.assertTrue(actualGrantRevokeRequest.getEnableAudit()); + Assert.assertFalse(actualGrantRevokeRequest.getIsRecursive()); + Assert.assertTrue(actualGrantRevokeRequest.getReplaceExistingPermissions()); + Assert.assertEquals(expectedGrantRevokeRequest.getGrantor(), actualGrantRevokeRequest.getGrantor()); + Assert.assertEquals(expectedGrantRevokeRequest.getResource(), actualGrantRevokeRequest.getResource()); + } + + @Test + public void testToGrantRevokeRequestForHbase() throws Exception { + GrantRevokeRequest expectedGrantRevokeRequest = new GrantRevokeRequest(); + expectedGrantRevokeRequest.setGrantor("rangerAdmin"); + expectedGrantRevokeRequest.setEnableAudit(true); + expectedGrantRevokeRequest.setIsRecursive(false); + expectedGrantRevokeRequest.setReplaceExistingPermissions(true); + + Map mapResource = new HashMap<>(); + mapResource.put("table", "myTable"); + mapResource.put("column", "myColumn"); + + mapResource.put("column-family", "myColumnFamily"); + expectedGrantRevokeRequest.setResource(mapResource); + + String serviceName = "hbase"; + + RangerService rangerService = new RangerService(); + rangerService.setId(1L); + rangerService.setName("hbaseService"); + rangerService.setIsEnabled(true); + rangerService.setType("hbase"); + + VXPolicy vXPolicy = new VXPolicy(); + vXPolicy.setRepositoryName("hbase"); + vXPolicy.setGrantor("rangerAdmin"); + vXPolicy.setReplacePerm(true); + vXPolicy.setColumns("myColumn"); + vXPolicy.setColumnFamilies("myColumnFamily"); + vXPolicy.setTables("myTable"); + + Mockito.when(svcStore.getServiceByName(serviceName)).thenReturn(rangerService); + + GrantRevokeRequest actualGrantRevokeRequest = serviceUtil.toGrantRevokeRequest(vXPolicy); + + Assert.assertNotNull(actualGrantRevokeRequest); + Assert.assertTrue(actualGrantRevokeRequest.getEnableAudit()); + Assert.assertFalse(actualGrantRevokeRequest.getIsRecursive()); + Assert.assertTrue(actualGrantRevokeRequest.getReplaceExistingPermissions()); + Assert.assertEquals(expectedGrantRevokeRequest.getGrantor(), actualGrantRevokeRequest.getGrantor()); + Assert.assertEquals(expectedGrantRevokeRequest.getResource(), actualGrantRevokeRequest.getResource()); + } + + @Test + public void testToGrantRevokeRequestForPermMapList() throws Exception { + GrantRevokeRequest expectedGrantRevokeRequest = new GrantRevokeRequest(); + expectedGrantRevokeRequest.setGrantor("rangerAdmin"); + expectedGrantRevokeRequest.setEnableAudit(true); + expectedGrantRevokeRequest.setIsRecursive(false); + expectedGrantRevokeRequest.setReplaceExistingPermissions(true); + + List userList = new ArrayList<>(); + userList.add("rangerAdmin"); + + List groupList = new ArrayList<>(); + groupList.add("rangerGroup"); + + List permObjList = new ArrayList<>(); + permObjList.add("Admin"); + + Map mapResource = new HashMap<>(); + mapResource.put("database", "myDatabase"); + mapResource.put("table", "myTable"); + mapResource.put("column", "myColumn"); + + expectedGrantRevokeRequest.setResource(mapResource); + + List vXPermObjList = new ArrayList<>(); + VXPermObj vXPermObj = new VXPermObj(); + vXPermObj.setUserList(userList); + vXPermObj.setGroupList(groupList); + vXPermObj.setPermList(permObjList); + + vXPermObjList.add(vXPermObj); + + String serviceName = "hive"; + + RangerService rangerService = new RangerService(); + rangerService.setId(1L); + rangerService.setName("hiveService"); + rangerService.setIsEnabled(true); + rangerService.setType("hive"); + + VXPolicy vXPolicy = new VXPolicy(); + vXPolicy.setRepositoryName("hive"); + vXPolicy.setGrantor("rangerAdmin"); + vXPolicy.setReplacePerm(true); + vXPolicy.setColumns("myColumn"); + vXPolicy.setDatabases("myDatabase"); + vXPolicy.setTables("myTable"); + vXPolicy.setPermMapList(vXPermObjList); + + Mockito.when(svcStore.getServiceByName(serviceName)).thenReturn(rangerService); + + GrantRevokeRequest actualGrantRevokeRequest = serviceUtil.toGrantRevokeRequest(vXPolicy); + + Assert.assertNotNull(actualGrantRevokeRequest); + Assert.assertTrue(actualGrantRevokeRequest.getEnableAudit()); + Assert.assertTrue(actualGrantRevokeRequest.getDelegateAdmin()); + Assert.assertFalse(actualGrantRevokeRequest.getIsRecursive()); + Assert.assertTrue(actualGrantRevokeRequest.getReplaceExistingPermissions()); + Assert.assertTrue(actualGrantRevokeRequest.getUsers().contains("rangerAdmin")); + Assert.assertTrue(actualGrantRevokeRequest.getGroups().contains("rangerGroup")); + Assert.assertEquals(expectedGrantRevokeRequest.getGrantor(), actualGrantRevokeRequest.getGrantor()); + Assert.assertEquals(expectedGrantRevokeRequest.getResource(), actualGrantRevokeRequest.getResource()); + } + + @Test + public void testToRangerPolicyForNullServiceAndNullVXPolicy() { + VXPolicy vXPolicy = null; + RangerService service = null; + + RangerPolicy actualRangerPolicy = serviceUtil.toRangerPolicy((VXPolicy) null, null); + Assert.assertNull(actualRangerPolicy); + } + + @Test + public void testToRangerPolicy() { + Date date = new Date(); + + List userList = new ArrayList<>(); + userList.add("rangerAdmin"); + + List groupList = new ArrayList<>(); + groupList.add("rangerGroup"); + + List permObjList = new ArrayList<>(); + permObjList.add("Admin"); + + Map resourceMap = new HashMap<>(); + List valuesList = new ArrayList<>(); + valuesList.add("resource"); + + RangerPolicyResource rangerPolicyResource = new RangerPolicyResource(); + rangerPolicyResource.setIsExcludes(false); + rangerPolicyResource.setIsRecursive(true); + rangerPolicyResource.setValues(valuesList); + + resourceMap.put("path", rangerPolicyResource); + + List rangerPolicyItemList = new ArrayList<>(); + RangerPolicyItem rangerPolicyItem = new RangerPolicyItem(); + rangerPolicyItem.setUsers(userList); + rangerPolicyItem.setGroups(groupList); + + List rangerPolicyItemConditionList = new ArrayList<>(); + RangerPolicyItemCondition rangerPolicyItemCondition = new RangerPolicyItemCondition(); + rangerPolicyItemCondition.setType("ipaddress"); + List conditionValueList = new ArrayList<>(); + conditionValueList.add("10.129.35.86"); + rangerPolicyItemCondition.setValues(conditionValueList); + rangerPolicyItemConditionList.add(rangerPolicyItemCondition); + rangerPolicyItem.setConditions(rangerPolicyItemConditionList); + rangerPolicyItem.setDelegateAdmin(true); + + rangerPolicyItemList.add(rangerPolicyItem); + + RangerPolicy expectedRangerPolicy = new RangerPolicy(); + expectedRangerPolicy.setId(1L); + expectedRangerPolicy.setName("hdfs"); + expectedRangerPolicy.setCreatedBy("rangerAdmin"); + expectedRangerPolicy.setCreateTime(date); + expectedRangerPolicy.setDescription("hdfs policy description"); + expectedRangerPolicy.setIsAuditEnabled(true); + expectedRangerPolicy.setResources(resourceMap); + expectedRangerPolicy.setPolicyItems(rangerPolicyItemList); + + VXPolicy vXPolicy = new VXPolicy(); + vXPolicy.setId(1L); + vXPolicy.setCreateDate(date); + vXPolicy.setUpdateDate(date); + vXPolicy.setOwner("rangerAdmin"); + vXPolicy.setUpdatedBy("rangerAdmin"); + vXPolicy.setPolicyName("hdfs"); + vXPolicy.setDescription("hdfs policy description"); + vXPolicy.setIsEnabled(true); + vXPolicy.setIsAuditEnabled(true); + vXPolicy.setIsRecursive(true); + vXPolicy.setResourceName("resource"); + + RangerService service = new RangerService(); + service.setId(1L); + service.setName("hdfsService"); + service.setType("hdfs"); + + List vXPermObjList = new ArrayList<>(); + VXPermObj vXPermObj = new VXPermObj(); + vXPermObj.setUserList(userList); + vXPermObj.setGroupList(groupList); + vXPermObj.setPermList(permObjList); + + vXPermObj.setIpAddress("10.129.35.86"); + + vXPermObjList.add(vXPermObj); + + vXPolicy.setPermMapList(vXPermObjList); + + RangerPolicy actualRangerPolicy = serviceUtil.toRangerPolicy(vXPolicy, service); + + Assert.assertNotNull(actualRangerPolicy); + Assert.assertEquals(expectedRangerPolicy.getId(), actualRangerPolicy.getId()); + Assert.assertEquals(expectedRangerPolicy.getName(), actualRangerPolicy.getName()); + Assert.assertEquals(expectedRangerPolicy.getDescription(), actualRangerPolicy.getDescription()); + Assert.assertEquals(expectedRangerPolicy.getCreatedBy(), actualRangerPolicy.getCreatedBy()); + Assert.assertTrue(actualRangerPolicy.getIsAuditEnabled()); + Assert.assertEquals(expectedRangerPolicy.getResources(), actualRangerPolicy.getResources()); + Assert.assertEquals(expectedRangerPolicy.getPolicyItems(), actualRangerPolicy.getPolicyItems()); + } } diff --git a/security-admin/src/test/java/org/apache/ranger/common/TestStringUtil.java b/security-admin/src/test/java/org/apache/ranger/common/TestStringUtil.java index 5514b14401..94074f1e2c 100644 --- a/security-admin/src/test/java/org/apache/ranger/common/TestStringUtil.java +++ b/security-admin/src/test/java/org/apache/ranger/common/TestStringUtil.java @@ -14,176 +14,170 @@ * 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; +package org.apache.ranger.common; import org.junit.Assert; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; +import java.util.ArrayList; +import java.util.List; + public class TestStringUtil { + @Autowired + StringUtil stringUtil = new StringUtil(); + + @Test + public void testToCamelCaseAllWords() { + String camelcase = "hello world"; + String camelCaseWords = stringUtil.toCamelCaseAllWords(camelcase); + Assert.assertEquals("Hello World", camelCaseWords); + } + + @Test + public void testNullValidatePassword() { + String[] invalidValues = {"aa", "bb", "aa12345dd"}; + boolean value = stringUtil.validatePassword(null, invalidValues); + Assert.assertFalse(value); + } + + @Test + public void testValidatePassword() { + String password = "Aa1234ddas12"; + String[] invalidValues = {"aa", "bb", "aa12345dd"}; + boolean value = stringUtil.validatePassword(password, invalidValues); + Assert.assertTrue(password.length() >= 8); + Assert.assertTrue(value); + } + + @Test + public void testNotValidatePassword() { + String password = "aassasavcvcvc"; + String[] invalidValues = {"aa", "bb", "aa12345dd"}; + boolean value = stringUtil.validatePassword(password, invalidValues); + Assert.assertTrue(password.length() >= 8); + Assert.assertFalse(value); + } + + @Test + public void testIsEmptyValue() { + String str = ""; + boolean value = stringUtil.isEmpty(str); + Assert.assertTrue(value); + } + + @Test + public void testIsNullValue() { + boolean value = stringUtil.isEmpty((String) null); + Assert.assertTrue(value); + } + + @Test + public void testIsWithValue() { + String str = "test value"; + boolean value = stringUtil.isEmpty(str); + Assert.assertFalse(value); + } + + @Test + public void testEquals() { + String str1 = "test"; + String str2 = "test"; + boolean value = stringUtil.equals(str1, str2); + Assert.assertTrue(value); + } + + @Test + public void testNormalizeEmail() { + String email = "test.Demo@test.COM"; + String lowercase = stringUtil.normalizeEmail(email); + String emailId = email.toLowerCase(); + boolean value = emailId.equals(lowercase); + Assert.assertTrue(value); + } + + @Test + public void testNormalizeEmailIdNull() { + String lowercase = stringUtil.normalizeEmail(null); + Assert.assertNull(lowercase); + } + + @Test + public void testSplit() { + String str1 = "Test1"; + String str2 = "Test2"; + String str3 = "Test3"; + String value = str1 + "," + str2 + "," + str3; + String[] stringArray = stringUtil.split(value); + Assert.assertEquals(3, stringArray.length); + Assert.assertEquals(str1, stringArray[0]); + Assert.assertEquals(str2, stringArray[1]); + Assert.assertEquals(str3, stringArray[2]); + } + + @Test + public void testTrim() { + String str = "test"; + String dataString = StringUtil.trim(str); + Assert.assertEquals(str, dataString); + } + + @Test + public void testValidateEmailId() { + String email = "rangerqa@apache.org"; + boolean value = stringUtil.validateEmail(email); + Assert.assertTrue(email.length() < 128); + Assert.assertTrue(value); + } + + @Test + public void testNullEmailId() { + boolean value = stringUtil.validateEmail(null); + Assert.assertFalse(value); + } + + @Test + public void testValidateString() { + String regExStr = "^[\\w]([\\-\\.\\w])+[\\w]+@[\\w]+[\\w\\-]+[\\w]*\\.([\\w]+[\\w\\-]+[\\w]*(\\.[a-z][a-z|0-9]*)?)$"; + String str = "test.test@gmail.com"; + boolean value = stringUtil.validateString(regExStr, str); + Assert.assertTrue(value); + } + + @Test + public void testNotValidateString() { + String regExStr = "^[\\w]([\\-\\.\\w])+[\\w]+[\\w]*\\.([\\w]+[\\w\\-]+[\\w]*(\\.[a-z][a-z|0-9]*)?)$"; + String str = "test.test@gmail.com"; + boolean value = stringUtil.validateString(regExStr, str); + Assert.assertFalse(value); + } + + @Test + public void testIsListEmpty() { + List list = new ArrayList<>(); + boolean listValue = stringUtil.isEmpty(list); + Assert.assertTrue(listValue); + } + + @Test + public void testIsListNotEmpty() { + List list = new ArrayList<>(); + list.add("a"); + list.add("b"); + boolean listValue = stringUtil.isEmpty(list); + Assert.assertFalse(listValue); + } + + @Test + public void testIsValidName() { + String name = "test"; + boolean value = stringUtil.isValidName(name); + Assert.assertTrue(value); + } - @Autowired - StringUtil stringUtil=new StringUtil(); - - @Test - public void testToCamelCaseAllWords(){ - String camelcase="hello world"; - String camelCaseWords=stringUtil.toCamelCaseAllWords(camelcase); - Assert.assertEquals("Hello World",camelCaseWords); - } - - @Test - public void testNullValidatePassword(){ - String password=null; - String[] invalidValues={"aa","bb","aa12345dd"}; - boolean value=stringUtil.validatePassword(password, invalidValues); - Assert.assertFalse(value); - } - - @Test - public void testValidatePassword(){ - String password="Aa1234ddas12"; - String[] invalidValues={"aa","bb","aa12345dd"}; - boolean value=stringUtil.validatePassword(password, invalidValues); - Assert.assertTrue(password.length() >= 8); - Assert.assertTrue(value); - } - - @Test - public void testNotValidatePassword(){ - String password="aassasavcvcvc"; - String[] invalidValues={"aa","bb","aa12345dd"}; - boolean value=stringUtil.validatePassword(password, invalidValues); - Assert.assertTrue(password.length() >= 8); - Assert.assertFalse(value); - } - - @Test - public void testIsEmptyValue(){ - String str=""; - boolean value=stringUtil.isEmpty(str); - Assert.assertTrue(value); - } - @Test - public void testIsNullValue(){ - String str=null; - boolean value=stringUtil.isEmpty(str); - Assert.assertTrue(value); - } - - @Test - public void testIsWithValue(){ - String str="test value"; - boolean value=stringUtil.isEmpty(str); - Assert.assertFalse(value); - } - - @Test - public void testEquals(){ - String str1="test"; - String str2="test"; - boolean value = stringUtil.equals(str1, str2); - Assert.assertTrue(value); - } - - @Test - public void testNormalizeEmail(){ - String email="test.Demo@test.COM"; - String lowercase=stringUtil.normalizeEmail(email); - String emailId=email.toLowerCase(); - boolean value = emailId.equals(lowercase); - Assert.assertTrue(value); - } - - @Test - public void testNormalizeEmailIdNull(){ - String email=null; - String lowercase=stringUtil.normalizeEmail(email); - Assert.assertEquals(lowercase,email); - Assert.assertNull(lowercase); - } - - @Test - public void testSplit(){ - String str1 = "Test1"; - String str2 = "Test2"; - String str3 = "Test3"; - String value = str1 + "," + str2 + "," + str3; - String[] stringArray = stringUtil.split(value); - Assert.assertTrue(stringArray.length == 3); - Assert.assertEquals(stringArray[0],str1); - Assert.assertEquals(stringArray[1],str2); - Assert.assertEquals(stringArray[2],str3); - } - - @Test - public void testTrim(){ - String str="test"; - String dataString = StringUtil.trim(str); - Assert.assertEquals(str,dataString); - } - - @Test - public void testValidateEmailId(){ - String email="rangerqa@apache.org"; - boolean value=stringUtil.validateEmail(email); - Assert.assertTrue(email.length() < 128); - Assert.assertTrue(value); - } - - @Test - public void testNullEmailId(){ - String email=null; - boolean value=stringUtil.validateEmail(email); - Assert.assertFalse(value); - } - - @Test - public void testValidateString(){ - String regExStr = "^[\\w]([\\-\\.\\w])+[\\w]+@[\\w]+[\\w\\-]+[\\w]*\\.([\\w]+[\\w\\-]+[\\w]*(\\.[a-z][a-z|0-9]*)?)$"; - String str="test.test@gmail.com"; - boolean value = stringUtil.validateString(regExStr, str); - Assert.assertTrue(value); - } - - @Test - public void testNotValidateString(){ - String regExStr = "^[\\w]([\\-\\.\\w])+[\\w]+[\\w]*\\.([\\w]+[\\w\\-]+[\\w]*(\\.[a-z][a-z|0-9]*)?)$"; - String str="test.test@gmail.com"; - boolean value = stringUtil.validateString(regExStr, str); - Assert.assertFalse(value); - } - - @Test - public void testIsListEmpty(){ - List list=new ArrayList(); - boolean listValue = stringUtil.isEmpty(list); - Assert.assertTrue(listValue); - } - - @Test - public void testIsListNotEmpty(){ - List list=new ArrayList(); - list.add("a"); - list.add("b"); - boolean listValue = stringUtil.isEmpty(list); - Assert.assertFalse(listValue); - } - - @Test - public void testIsValidName(){ - String name="test"; - boolean value = stringUtil.isValidName(name); - Assert.assertTrue(value); - } - - @Test - public void testIsValidNameNull(){ - String name=null; - boolean value = stringUtil.isValidName(name); - Assert.assertFalse(value); - } -} \ No newline at end of file + @Test + public void testIsValidNameNull() { + boolean value = stringUtil.isValidName(null); + Assert.assertFalse(value); + } +} diff --git a/security-admin/src/test/java/org/apache/ranger/common/TestTimedExecutor.java b/security-admin/src/test/java/org/apache/ranger/common/TestTimedExecutor.java index 479b4000e8..94f83090d1 100644 --- a/security-admin/src/test/java/org/apache/ranger/common/TestTimedExecutor.java +++ b/security-admin/src/test/java/org/apache/ranger/common/TestTimedExecutor.java @@ -19,8 +19,10 @@ package org.apache.ranger.common; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import org.junit.Before; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.List; @@ -35,156 +37,149 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; -import org.junit.Before; -import org.junit.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; public class TestTimedExecutor { + private static final Logger LOG = LoggerFactory.getLogger(TestTimedExecutor.class); + + static final String format = "%15s id: %2d"; + + private final TimedExecutor executor = new TimedExecutor(); + + private TimedExecutorConfigurator configurator; + + static void recordResult(ConcurrentMap results, String key) { + if (results.containsKey(key)) { + results.get(key).incrementAndGet(); + } else { + AtomicInteger previous = results.putIfAbsent(key, new AtomicInteger(1)); + if (previous != null) { // a value was already associated with the key + previous.incrementAndGet(); + } + } + } + + static void recordResult(ConcurrentMap results, Exception e) { + String exceptionName = e.getClass().getCanonicalName(); + recordResult(results, exceptionName); + } + + @Before + public void before() { + } + + @Test + public void test() throws InterruptedException { + /* + * Create a pool with 2 threads and queue size of 3 such that 6th item should get rejected right away due to capacity. + */ + int poolSize = 2; + int queueSize = 3; + configurator = new TimedExecutorConfigurator(poolSize, queueSize); + // Just to avoid thread shutting down and restarting set keep alive to high value. + executor.initialize(configurator); + + // now create 2 callables that would keep waiting unless we ask them to proceed + // create an executor which would simulate simultaneous threads calling into executor to perform lookups + ExecutorService executorService = Executors.newCachedThreadPool(); + List> futures = new ArrayList<>(); + /* + * We would have 2 permits for 10 callables, such that + * - 2 should succeed + * - 5 should timeout (2 in pool + 3 in queue) + * - 3 should get rejected. + */ + Semaphore semaphore = new Semaphore(2); + /* + * We need a latch to keep track of when the processing is done so we can check the results of teh test + */ + CountDownLatch latch = new CountDownLatch(10); + // Callables will record exception in this map + final ConcurrentMap results = new ConcurrentHashMap<>(); + for (int i = 0; i < 10; i++) { + LookupTask lookupTask = new LookupTask(i, semaphore); + TimedTask timedTask = new TimedTask(executor, lookupTask, 1, TimeUnit.SECONDS, results, latch); + Future aFuture = executorService.submit(timedTask); + futures.add(aFuture); + } + // Let's wait for the threads to finish + LOG.debug("Starting to wait for threadpool to finish"); + latch.await(); + /* + * depending on how threads get scheduled the count in results would vary, except we know for sure that. + * - 2 must succeed since we have exactly 2 permits available. + * - sum of timed out and rejected must be equal to 8. + * - at least 3 and no more than 5 tasks must get rejected. + * - at least 3 and no more than 5 tasks must get timed out + */ + int successCount = results.get("success").get(); + int timeoutCount = results.get("java.util.concurrent.TimeoutException").get(); + int rejectedCount = results.get("java.util.concurrent.RejectedExecutionException").get(); + assertEquals("success count", 2, successCount); + assertTrue("timeout[" + timeoutCount + "]: 3 <= count(timeout) <= 5", timeoutCount >= 3 && timeoutCount <= 5); + assertTrue("rejected[" + rejectedCount + "]: 3 <= count(timeout) <= 5", rejectedCount >= 3 && rejectedCount <= 5); + assertEquals("total should equal 10", 10, successCount + timeoutCount + rejectedCount); + executor.shutdown(); + } + + static class LookupTask implements Callable { + final int id; + private final Semaphore semaphore; + + public LookupTask(int id1, Semaphore latch) { + id = id1; + semaphore = latch; + } + + @Override + public Integer call() throws Exception { + LOG.debug(String.format(format, "Starting", id)); + semaphore.acquire(); + LOG.debug(String.format(format, "Acquired", id)); + LOG.debug(String.format(format, "Ended", id)); + return id; + } + + int getId() { + return id; + } + } + + static class TimedTask implements Callable { + final LookupTask callable; + final TimedExecutor executor; + final ConcurrentMap results; + final long timeout; + final TimeUnit unit; + final CountDownLatch latch; + + public TimedTask(TimedExecutor executor, LookupTask callable, int timout, TimeUnit unit, ConcurrentMap results, CountDownLatch latch) { + this.callable = callable; + this.executor = executor; + this.results = results; + this.timeout = timout; + this.unit = unit; + this.latch = latch; + } - private static final Logger LOG = LoggerFactory.getLogger(TestTimedExecutor.class); - - @Before - public void before() { - - } - - @Test - public void test() throws InterruptedException { - /* - * Create a pool with 2 threads and queue size of 3 such that 6th item should get rejected right away due to capacity. - */ - int poolSize = 2; - int queueSize = 3; - _configurator = new TimedExecutorConfigurator(poolSize, queueSize); - // Just toa void thread shutting down and restarting set keep alive to high value. - _executor.initialize(_configurator); - - // now create 2 callalbles that would keep waiting unless we ask them to proceed - // create an executor which would simulate simultaneous threads calling into executor to perform lookups - ExecutorService executorService = Executors.newCachedThreadPool(); - List> futures = new ArrayList>(); - /* - * We would have 2 permits for 10 callables, such that - * - 2 should succeed - * - 5 should timeout (2 in pool + 3 in queue) - * - 3 should get rejected. - */ - Semaphore semaphore = new Semaphore(2); - /* - * We need a latch to keep track of when the processing is done so we can check the results of teh test - */ - CountDownLatch latch = new CountDownLatch(10); - // Callables will record exception in this map - final ConcurrentMap results = new ConcurrentHashMap(); - for (int i = 0; i < 10; i++) { - LookupTask lookupTask = new LookupTask(i, semaphore); - TimedTask timedTask = new TimedTask(_executor, lookupTask, 1, TimeUnit.SECONDS, results, latch); - Future aFuture = executorService.submit(timedTask); - futures.add(aFuture); - } - // Let's wait for the threads to finish - LOG.debug("Starting to wait for threadpool to finish"); - latch.await(); - /* - * depending on how threads get scheduled the count in results would vary, except we know for sure that. - * - 2 must succeed since we have exactly 2 permits available. - * - sum of timed out and rejected must be equal to 8. - * - at least 3 and no more than 5 tasks must get rejected. - * - at least 3 and no more than 5 tasks must get timed out - */ - int successCount = results.get("success").get(); - int timeoutCount = results.get("java.util.concurrent.TimeoutException").get(); - int rejectedCount = results.get("java.util.concurrent.RejectedExecutionException").get(); - assertEquals("success count", 2, successCount); - assertTrue("timeout[" + timeoutCount + "]: 3 <= count(timeout) <= 5", timeoutCount >= 3 && timeoutCount <= 5); - assertTrue("rejected[" + rejectedCount + "]: 3 <= count(timeout) <= 5", rejectedCount >= 3 && rejectedCount <= 5); - assertEquals("total should equal 10", 10, successCount + timeoutCount + rejectedCount); - _executor.shutdown(); - } - - static final String format = "%15s id: %2d"; - - static class LookupTask implements Callable { - - final int _id; - final private Semaphore _semaphore; - - public LookupTask(int id, Semaphore latch) { - _id = id; - _semaphore = latch; - } - - int getId() { - return _id; - } - - @Override - public Integer call() throws Exception { - LOG.debug(String.format(format, "Starting", _id)); - _semaphore.acquire(); - LOG.debug(String.format(format, "Acquired", _id)); - LOG.debug(String.format(format, "Ended", _id)); - return _id; - } - - } - - static class TimedTask implements Callable { - - final LookupTask _callable; - final TimedExecutor _executor; - final ConcurrentMap _results; - final long _timeout; - final TimeUnit _unit; - final CountDownLatch _latch; - - public TimedTask(TimedExecutor executor, LookupTask callable, int timout, TimeUnit unit, ConcurrentMap results, CountDownLatch latch) { - _callable = callable; - _executor = executor; - _results = results; - _timeout = timout; - _unit = unit; - _latch = latch; - } - - @Override - public Integer call() throws Exception { - int id = _callable.getId(); - LOG.debug(String.format(format, "Submitting", id)); - try { - Integer result = _executor.timedTask(_callable, _timeout, _unit); - LOG.debug(String.format(format, "Finished", id)); - recordResult(_results, "success"); - return result; - } catch (Exception e) { - LOG.debug(String.format(format, "Exception", id)); - recordResult(_results, e); - // re-throw caught exception - throw e; - } finally { - _latch.countDown(); - } - } - - } - - static void recordResult(ConcurrentMap results, String key) { - if (results.containsKey(key)) { - results.get(key).incrementAndGet(); - } else { - AtomicInteger previous = results.putIfAbsent(key, new AtomicInteger(1)); - if (previous != null) { // a value was already associated with the key - previous.incrementAndGet(); - } - } - } - - static void recordResult(ConcurrentMap results, Exception e) { - String exceptionName = e.getClass().getCanonicalName(); - recordResult(results, exceptionName); - } - - private TimedExecutorConfigurator _configurator; - private TimedExecutor _executor = new TimedExecutor(); + @Override + public Integer call() throws Exception { + int id = callable.getId(); + LOG.debug(String.format(format, "Submitting", id)); + try { + Integer result = executor.timedTask(callable, timeout, unit); + LOG.debug(String.format(format, "Finished", id)); + recordResult(results, "success"); + return result; + } catch (Exception e) { + LOG.debug(String.format(format, "Exception", id)); + recordResult(results, e); + // re-throw caught exception + throw e; + } finally { + latch.countDown(); + } + } + } } diff --git a/security-admin/src/test/java/org/apache/ranger/common/db/TestRangerTransactionSynchronizationAdapter.java b/security-admin/src/test/java/org/apache/ranger/common/db/TestRangerTransactionSynchronizationAdapter.java index 735c741fb7..fb789e25ce 100644 --- a/security-admin/src/test/java/org/apache/ranger/common/db/TestRangerTransactionSynchronizationAdapter.java +++ b/security-admin/src/test/java/org/apache/ranger/common/db/TestRangerTransactionSynchronizationAdapter.java @@ -25,7 +25,6 @@ import java.util.concurrent.atomic.AtomicInteger; public class TestRangerTransactionSynchronizationAdapter { - @Test public void testNestedRunnableAfterCompletion() { TransactionSynchronizationManager.initSynchronization(); @@ -42,6 +41,5 @@ public void testNestedRunnableAfterCompletion() { } finally { TransactionSynchronizationManager.clear(); } - } } diff --git a/security-admin/src/test/java/org/apache/ranger/elasticsearch/ElasticSearchAccessAuditsServiceTest.java b/security-admin/src/test/java/org/apache/ranger/elasticsearch/ElasticSearchAccessAuditsServiceTest.java index bbf303715a..b63e062896 100644 --- a/security-admin/src/test/java/org/apache/ranger/elasticsearch/ElasticSearchAccessAuditsServiceTest.java +++ b/security-admin/src/test/java/org/apache/ranger/elasticsearch/ElasticSearchAccessAuditsServiceTest.java @@ -19,19 +19,10 @@ package org.apache.ranger.elasticsearch; -import static org.apache.ranger.audit.destination.ElasticSearchAuditDestination.CONFIG_PREFIX; - import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectWriter; import com.fasterxml.jackson.databind.SerializationFeature; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Calendar; -import java.util.Date; -import java.util.HashSet; -import java.util.Map; -import java.util.Properties; import org.apache.ranger.audit.destination.ElasticSearchAuditDestination; import org.apache.ranger.audit.model.AuthzAuditEvent; import org.apache.ranger.common.PropertiesUtil; @@ -39,11 +30,22 @@ import org.apache.ranger.common.SearchCriteria; import org.apache.ranger.common.StringUtil; import org.apache.ranger.view.VXAccessAuditList; +import org.junit.Assert; import org.junit.Ignore; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.Collections; +import java.util.Date; +import java.util.HashSet; +import java.util.Map; +import java.util.Properties; + +import static org.apache.ranger.audit.destination.ElasticSearchAuditDestination.CONFIG_PREFIX; + public class ElasticSearchAccessAuditsServiceTest { private static final Logger LOGGER = LoggerFactory.getLogger(ElasticSearchAccessAuditsServiceTest.class); @@ -51,14 +53,14 @@ public class ElasticSearchAccessAuditsServiceTest { @Ignore // For manual execution only public void testQuery() { ElasticSearchAccessAuditsService elasticSearchAccessAuditsService = new ElasticSearchAccessAuditsService(); - Map properties = PropertiesUtil.getPropertiesMap(); + Map properties = PropertiesUtil.getPropertiesMap(); properties.put("ranger.audit.elasticsearch.urls", "localhost"); properties.put("ranger.audit.elasticsearch.protocol", "http"); properties.put("ranger.audit.elasticsearch.user", "elastic"); properties.put("ranger.audit.elasticsearch.password", "password1"); properties.put("ranger.audit.elasticsearch.port", "9200"); - elasticSearchAccessAuditsService.elasticSearchMgr = new ElasticSearchMgr(); - elasticSearchAccessAuditsService.elasticSearchUtil = new ElasticSearchUtil(); + elasticSearchAccessAuditsService.elasticSearchMgr = new ElasticSearchMgr(); + elasticSearchAccessAuditsService.elasticSearchUtil = new ElasticSearchUtil(); elasticSearchAccessAuditsService.elasticSearchUtil.stringUtil = new StringUtil(); elasticSearchAccessAuditsService.setRestErrorUtil(new RESTErrorUtil()); LOGGER.info("Running searchXAccessAudits:"); @@ -74,6 +76,18 @@ public void testQuery() { }); } + @Test + @Ignore // For manual execution only + public void testWrite() { + ElasticSearchAuditDestination elasticSearchAuditDestination = new ElasticSearchAuditDestination(); + Properties properties = new Properties(); + properties.put(CONFIG_PREFIX + "." + ElasticSearchAuditDestination.CONFIG_URLS, "localhost"); + properties.put(CONFIG_PREFIX + "." + ElasticSearchAuditDestination.CONFIG_USER, "elastic"); + properties.put(CONFIG_PREFIX + "." + ElasticSearchAuditDestination.CONFIG_PWRD, "password1"); + elasticSearchAuditDestination.init(properties, CONFIG_PREFIX); + Assert.assertTrue(elasticSearchAuditDestination.log(Collections.singletonList(getAuthzAuditEvent()))); + } + private SearchCriteria getSearchCriteria() { SearchCriteria searchCriteria = new SearchCriteria(); searchCriteria.setDistinct(false); @@ -85,7 +99,7 @@ private SearchCriteria getSearchCriteria() { searchCriteria.setSortType("desc"); searchCriteria.setStartIndex(0); Calendar calendar = Calendar.getInstance(); - calendar.set(2019, 11,13); + calendar.set(2019, 11, 13); searchCriteria.getParamList().put("startDate", calendar.getTime()); searchCriteria.getParamList().put("-repoType", 7); searchCriteria.getParamList().put("-requestUser", new ArrayList<>()); @@ -94,18 +108,6 @@ private SearchCriteria getSearchCriteria() { return searchCriteria; } - @Test - @Ignore // For manual execution only - public void testWrite() { - ElasticSearchAuditDestination elasticSearchAuditDestination = new ElasticSearchAuditDestination(); - Properties properties = new Properties(); - properties.put(CONFIG_PREFIX + "." + ElasticSearchAuditDestination.CONFIG_URLS, "localhost"); - properties.put(CONFIG_PREFIX + "." + ElasticSearchAuditDestination.CONFIG_USER, "elastic"); - properties.put(CONFIG_PREFIX + "." + ElasticSearchAuditDestination.CONFIG_PWRD, "password1"); - elasticSearchAuditDestination.init(properties, CONFIG_PREFIX); - assert elasticSearchAuditDestination.log(Arrays.asList(getAuthzAuditEvent())); - } - private AuthzAuditEvent getAuthzAuditEvent() { AuthzAuditEvent event = new AuthzAuditEvent(); event.setAccessResult((short) 1); @@ -124,7 +126,7 @@ private AuthzAuditEvent getAuthzAuditEvent() { event.setEventTime(new Date()); event.setLogType(""); event.setPolicyId(1); - event.setPolicyVersion(1l); + event.setPolicyVersion(1L); event.setRepositoryName(""); event.setRequestData(""); event.setRepositoryName(""); diff --git a/security-admin/src/test/java/org/apache/ranger/patch/cliutil/TestRoleBasedUserSearchUtil.java b/security-admin/src/test/java/org/apache/ranger/patch/cliutil/TestRoleBasedUserSearchUtil.java index 891ac10630..4d5d67b317 100644 --- a/security-admin/src/test/java/org/apache/ranger/patch/cliutil/TestRoleBasedUserSearchUtil.java +++ b/security-admin/src/test/java/org/apache/ranger/patch/cliutil/TestRoleBasedUserSearchUtil.java @@ -1,5 +1,5 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one + * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file @@ -18,14 +18,9 @@ */ package org.apache.ranger.patch.cliutil; -import static org.junit.Assert.fail; - -import java.util.ArrayList; -import java.util.List; import org.apache.ranger.biz.UserMgr; import org.apache.ranger.biz.XUserMgr; import org.apache.ranger.common.RangerConstants; - import org.apache.ranger.db.RangerDaoManager; import org.apache.ranger.db.XXModuleDefDao; import org.apache.ranger.db.XXPortalUserDao; @@ -42,6 +37,11 @@ import org.mockito.Mockito; import org.mockito.runners.MockitoJUnitRunner; +import java.util.ArrayList; +import java.util.List; + +import static org.junit.Assert.fail; + @RunWith(MockitoJUnitRunner.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class TestRoleBasedUserSearchUtil { @@ -55,65 +55,62 @@ public class TestRoleBasedUserSearchUtil { UserMgr userMgr; @Mock - XUserMgr xUserMgr; + XUserMgr xUserMgr; @Mock XXPortalUserDao xXPortalUserDao; - @InjectMocks RoleBasedUserSearchUtil roleBasedUserSearchUtil = new RoleBasedUserSearchUtil(); - public TestRoleBasedUserSearchUtil() { - } + @Test - public void TestGetUsersBasedOnRole() { - try { - XXPortalUser xXPortalUser = new XXPortalUser(); - xXPortalUser.setLoginId("testUser"); - xXPortalUser.setId(1L); - xXPortalUser.setFirstName("testUser"); - xXPortalUser.setPublicScreenName("testUser"); - xXPortalUser.setPassword("testUserPassword"); - List listXXPortalUser = new ArrayList(); - listXXPortalUser.add(xXPortalUser); - List userRoleList = new ArrayList(); - userRoleList.add("ROLE_SYS_ADMIN"); - - Mockito.when(daoMgr.getXXPortalUser()).thenReturn(xXPortalUserDao); - Mockito.when(xXPortalUserDao.findByRole(RangerConstants.ROLE_SYS_ADMIN)).thenReturn(listXXPortalUser); - - roleBasedUserSearchUtil.getUsersBasedOnRole(userRoleList); - - - Mockito.verify(xXPortalUserDao).findByRole(RangerConstants.ROLE_SYS_ADMIN); - - } catch(Exception e) { - fail("test failed due to: " + e.getMessage()); - } + public void testGetUsersBasedOnRole() { + try { + XXPortalUser xXPortalUser = new XXPortalUser(); + xXPortalUser.setLoginId("testUser"); + xXPortalUser.setId(1L); + xXPortalUser.setFirstName("testUser"); + xXPortalUser.setPublicScreenName("testUser"); + xXPortalUser.setPassword("testUserPassword"); + List listXXPortalUser = new ArrayList<>(); + listXXPortalUser.add(xXPortalUser); + List userRoleList = new ArrayList<>(); + userRoleList.add("ROLE_SYS_ADMIN"); + + Mockito.when(daoMgr.getXXPortalUser()).thenReturn(xXPortalUserDao); + Mockito.when(xXPortalUserDao.findByRole(RangerConstants.ROLE_SYS_ADMIN)).thenReturn(listXXPortalUser); + + roleBasedUserSearchUtil.getUsersBasedOnRole(userRoleList); + + Mockito.verify(xXPortalUserDao).findByRole(RangerConstants.ROLE_SYS_ADMIN); + } catch (Exception e) { + fail("test failed due to: " + e.getMessage()); + } } + @Test - public void TestValidateUserAndFetchUserList() { - List permissionList = new ArrayList(); + public void testValidateUserAndFetchUserList() { + List permissionList = new ArrayList<>(); permissionList.add(RangerConstants.MODULE_USER_GROUPS); - String currentEncryptedPassword = "testpassword"; - XXPortalUser xxPortalUser = new XXPortalUser(); + String currentEncryptedPassword = "testpassword"; + XXPortalUser xxPortalUser = new XXPortalUser(); xxPortalUser.setId(1L); xxPortalUser.setLoginId("testUser"); xxPortalUser.setPassword("testpassword"); xxPortalUser.setFirstName("testUser"); VXUser vxUser = new VXUser(); vxUser.setId(1L); - VXUserList vXUserList = new VXUserList(); - List vXUsers = new ArrayList(); + VXUserList vXUserList = new VXUserList(); + List vXUsers = new ArrayList<>(); vXUsers.add(vxUser); - vXUserList.setVXUsers(vXUsers ); + vXUserList.setVXUsers(vXUsers); - List userRoleList = new ArrayList(); + List userRoleList = new ArrayList<>(); userRoleList.add("ROLE_SYS_ADMIN"); - List listXXPortalUser = new ArrayList(); - listXXPortalUser.add(xxPortalUser); + List listXXPortalUser = new ArrayList<>(); + listXXPortalUser.add(xxPortalUser); vxUser.setUserRoleList(userRoleList); XXModuleDefDao xXModuleDefDao = Mockito.mock(XXModuleDefDao.class); @@ -122,7 +119,7 @@ public void TestValidateUserAndFetchUserList() { Mockito.when(xUserService.getXUserByUserName(xxPortalUser.getLoginId())).thenReturn(vxUser); Mockito.when(daoMgr.getXXModuleDef()).thenReturn(xXModuleDefDao); Mockito.when(xXModuleDefDao.findAccessibleModulesByUserId(Mockito.anyLong(), Mockito.anyLong())).thenReturn(permissionList); - Mockito.when(userMgr.encrypt(Mockito.anyString(),Mockito.anyString())).thenReturn(currentEncryptedPassword); + Mockito.when(userMgr.encrypt(Mockito.anyString(), Mockito.anyString())).thenReturn(currentEncryptedPassword); Mockito.when(xXPortalUserDao.findByRole(Mockito.anyString())).thenReturn(listXXPortalUser); roleBasedUserSearchUtil.validateUserAndFetchUserList(); @@ -131,9 +128,7 @@ public void TestValidateUserAndFetchUserList() { Mockito.verify(xUserService).getXUserByUserName(xxPortalUser.getLoginId()); Mockito.verify(xXModuleDefDao).findAccessibleModulesByUserId(Mockito.anyLong(), Mockito.anyLong()); - Mockito.verify(userMgr).encrypt(Mockito.anyString(),Mockito.anyString()); + Mockito.verify(userMgr).encrypt(Mockito.anyString(), Mockito.anyString()); Mockito.verify(xXPortalUserDao, Mockito.atLeast(2)).findByRole(Mockito.anyString()); - } - } diff --git a/security-admin/src/test/java/org/apache/ranger/rest/TestAssetREST.java b/security-admin/src/test/java/org/apache/ranger/rest/TestAssetREST.java index ec7b79677b..352c63228f 100644 --- a/security-admin/src/test/java/org/apache/ranger/rest/TestAssetREST.java +++ b/security-admin/src/test/java/org/apache/ranger/rest/TestAssetREST.java @@ -16,18 +16,6 @@ */ package org.apache.ranger.rest; -import static org.junit.Assert.fail; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.WebApplicationException; - import org.apache.commons.lang.StringUtils; import org.apache.ranger.admin.client.datatype.RESTResponse; import org.apache.ranger.biz.AssetMgr; @@ -50,12 +38,12 @@ import org.apache.ranger.plugin.store.EmbeddedServiceDefsUtil; import org.apache.ranger.plugin.util.GrantRevokeRequest; import org.apache.ranger.plugin.util.SearchFilter; +import org.apache.ranger.service.RangerTrxLogV2Service; import org.apache.ranger.service.XAccessAuditService; import org.apache.ranger.service.XAssetService; import org.apache.ranger.service.XCredentialStoreService; import org.apache.ranger.service.XPolicyExportAuditService; import org.apache.ranger.service.XResourceService; -import org.apache.ranger.service.RangerTrxLogV2Service; import org.apache.ranger.view.VXAccessAudit; import org.apache.ranger.view.VXAccessAuditList; import org.apache.ranger.view.VXAsset; @@ -83,887 +71,801 @@ import org.mockito.Mockito; import org.mockito.junit.MockitoJUnitRunner; +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.WebApplicationException; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.junit.Assert.fail; + @RunWith(MockitoJUnitRunner.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class TestAssetREST { - private static Long Id = 8L; - @Mock - ServiceREST serviceREST; - - @Mock - ServiceUtil serviceUtil; - - @Mock - RangerSearchUtil searchUtil; - - @Mock - RangerBizUtil xaBizUtil; - - @Mock - XAssetService xAssetService; - - @Mock - XResourceService xResourceService; - - @Mock - XCredentialStoreService xCredentialStoreService; - - @Mock - AssetMgr assetMgr; - - @Mock - HttpServletRequest request; - - @Mock - RangerTrxLogV2Service xTrxLogService; - - @Mock - XPolicyExportAuditService xPolicyExportAudits; - - @Mock - XAccessAuditService xAccessAuditService; - - @Mock - XXServiceDefDao xxServiceDefDao; - - @Mock - RangerBizUtil msBizUtil; - - @Mock - RangerDaoManager daoManager; - - @InjectMocks - AssetREST assetREST = new AssetREST(); - - @Rule public ExpectedException thrown = ExpectedException.none(); - @Mock RESTErrorUtil restErrorUtil; - @Mock WebApplicationException webApplicationException; - - - public void TestAssetRest() { - - } - - private VXCredentialStore vXCredentialStore() { - VXCredentialStore vXCredentialStore = new VXCredentialStore(); - vXCredentialStore.setId(Id); - vXCredentialStore.setName("TestAssetRest"); - vXCredentialStore.setDescription("TestAssetRest"); - vXCredentialStore.setOwner("owner"); - return vXCredentialStore; - } - - private RangerService rangerService(Long id) { - RangerService rangerService = new RangerService(); - rangerService.setId(id); - rangerService.setConfigs(getSampleConfig()); - rangerService.setCreateTime(new Date()); - rangerService.setDescription("service policy"); - rangerService.setGuid("1427365526516_835_0"); - rangerService.setIsEnabled(true); - rangerService.setName("HDFS_1"); - rangerService.setPolicyUpdateTime(new Date()); - rangerService.setType("1"); - rangerService.setUpdatedBy("Admin"); - rangerService.setUpdateTime(new Date()); - - return rangerService; - } - - private VXAsset vXAsset(Long id) { - Map configs = new HashMap(); - configs.put("username", "servicemgr"); - configs.put("password", "servicemgr"); - configs.put("namenode", "servicemgr"); - configs.put("hadoop.security.authorization", "No"); - configs.put("hadoop.security.authentication", "Simple"); - configs.put("hadoop.security.auth_to_local", ""); - configs.put("dfs.datanode.kerberos.principal", ""); - configs.put("dfs.namenode.kerberos.principal", ""); - configs.put("dfs.secondary.namenode.kerberos.principal", ""); - configs.put("hadoop.rpc.protection", "Privacy"); - configs.put("commonNameForCertificate", ""); - - VXAsset vXAsset = new VXAsset(); - vXAsset.setId(id); - vXAsset.setActiveStatus(1); - vXAsset.setAssetType(1); - vXAsset.setDescription("service policy"); - vXAsset.setSupportNative(false); - vXAsset.setName("HDFS_1"); - vXAsset.setUpdatedBy("Admin"); - vXAsset.setConfig(getSampleConfig().toString()); - return vXAsset; - } - - private VXResource vxResource(Long id) { - VXResource vXResource = new VXResource(); - vXResource.setName("HDFS_1-1-20150316062453"); - vXResource.setId(id); - vXResource.setAssetId(id); - return vXResource; - } - - private RangerPolicy rangerPolicy(Long id) { - List accesses = new ArrayList(); - List users = new ArrayList(); - List groups = new ArrayList(); - List conditions = new ArrayList(); - List policyItems = new ArrayList(); - RangerPolicyItem rangerPolicyItem = new RangerPolicyItem(); - rangerPolicyItem.setAccesses(accesses); - rangerPolicyItem.setConditions(conditions); - rangerPolicyItem.setGroups(groups); - rangerPolicyItem.setUsers(users); - rangerPolicyItem.setDelegateAdmin(false); - - policyItems.add(rangerPolicyItem); - - Map policyResource = new HashMap(); - RangerPolicyResource rangerPolicyResource = new RangerPolicyResource(); - rangerPolicyResource.setIsExcludes(true); - rangerPolicyResource.setIsRecursive(true); - rangerPolicyResource.setValue("1"); - rangerPolicyResource.setValues(users); - policyResource.put("resource", rangerPolicyResource); - RangerPolicy policy = new RangerPolicy(); - policy.setId(id); - policy.setCreateTime(new Date()); - policy.setDescription("policy"); - policy.setGuid("policyguid"); - policy.setIsEnabled(true); - policy.setName("HDFS_1-1-20150316062453"); - policy.setUpdatedBy("Admin"); - policy.setUpdateTime(new Date()); - policy.setService("HDFS_1-1-20150316062453"); - policy.setIsAuditEnabled(true); - policy.setPolicyItems(policyItems); - policy.setResources(policyResource); - policy.setService("HDFS_1"); - - return policy; - } - - private VXPolicy vXPolicy(RangerPolicy policy, RangerService service) { - VXPolicy ret = new VXPolicy(); - ret.setPolicyName(StringUtils.trim(policy.getName())); - ret.setDescription(policy.getDescription()); - ret.setRepositoryName(policy.getService()); - ret.setIsEnabled(policy.getIsEnabled() ? true : false); - ret.setRepositoryType(service.getType()); - ret.setIsAuditEnabled(policy.getIsAuditEnabled()); - return ret; - } - - @Test - public void testGetXAsset() { - RangerService rangerService = rangerService(Id); - VXAsset vXAsset = vXAsset(Id); - Mockito.when(serviceREST.getService(rangerService.getId())).thenReturn(rangerService); - Mockito.when(serviceUtil.toVXAsset(rangerService)).thenReturn(vXAsset); - VXAsset asset = assetREST.getXAsset(Id); - Assert.assertNotNull(asset); - Assert.assertEquals(vXAsset, asset); - Mockito.verify(serviceREST).getService(rangerService.getId()); - Mockito.verify(serviceUtil).toVXAsset(rangerService); - } - - @Test - public void testCreateXAsset() { - RangerService rangerService = rangerService(Id); - VXAsset vXAsset = vXAsset(Id); - Mockito.when(serviceREST.createService(rangerService)).thenReturn(rangerService); - Mockito.when(serviceUtil.toRangerService(vXAsset)).thenReturn(rangerService); - Mockito.when(serviceUtil.toVXAsset(rangerService)).thenReturn(vXAsset); - VXAsset asset = assetREST.createXAsset(vXAsset); - Assert.assertNotNull(asset); - Assert.assertEquals(vXAsset, asset); - Mockito.verify(serviceREST).createService(rangerService); - Mockito.verify(serviceUtil).toRangerService(vXAsset); - Mockito.verify(serviceUtil).toVXAsset(rangerService); - } - - @Test - public void testUpdateXAsset() { - RangerService rangerService = rangerService(Id); - HttpServletRequest request = null; - VXAsset vXAsset = vXAsset(Id); - Mockito.when(serviceUtil.toRangerService(vXAsset)).thenReturn(rangerService); - Mockito.when(serviceREST.updateService(rangerService, request)).thenReturn(rangerService); - Mockito.when(serviceUtil.toVXAsset(rangerService)).thenReturn(vXAsset); - VXAsset asset = assetREST.updateXAsset(vXAsset); - Assert.assertNotNull(asset); - Assert.assertEquals(vXAsset, asset); - Mockito.verify(serviceREST).updateService(rangerService, request); - Mockito.verify(serviceUtil).toRangerService(vXAsset); - Mockito.verify(serviceUtil).toVXAsset(rangerService); - } - - @Test - public void testDeleteXAsset() { - RangerService rangerService = rangerService(Id); - - Mockito.doNothing().when(serviceREST).deleteService(Id); - assetREST.deleteXAsset(rangerService.getId(), request); - Mockito.verify(serviceREST).deleteService(rangerService.getId()); - } - - @Test - public void testConfigTest() { - RangerService rangerService = rangerService(Id); - VXResponse expectedVxResponse = new VXResponse(); - expectedVxResponse.setStatusCode(VXResponse.STATUS_SUCCESS); - expectedVxResponse.setMsgDesc("test connection successful"); - VXAsset vXAsset = vXAsset(Id); - Mockito.when(serviceUtil.toRangerService(vXAsset)).thenReturn(rangerService); - Mockito.when(serviceREST.validateConfig(rangerService)).thenReturn(expectedVxResponse); - VXResponse actualVxResponse = assetREST.configTest(vXAsset); - Assert.assertNotNull(actualVxResponse); - Assert.assertEquals(expectedVxResponse, actualVxResponse); - Mockito.verify(serviceUtil).toRangerService(vXAsset); - Mockito.verify(serviceREST).validateConfig(rangerService); - } - - @Test - public void testSearchXAssets() { - RangerService rangerService1 = rangerService(Id); - RangerService rangerService2 = rangerService(9L); - VXAsset vXAsset1 = vXAsset(Id); - VXAsset vXAsset2 = vXAsset(9L); - VXAssetList expectedVXAsset = new VXAssetList(); - List vXAsset = Arrays.asList(vXAsset1, vXAsset2); - expectedVXAsset.setVXAssets(vXAsset); - List services = Arrays.asList(rangerService1, rangerService2); - - SearchFilter searchFilter = new SearchFilter(); - Mockito.when(searchUtil.getSearchFilterFromLegacyRequestForRepositorySearch(request, null)) - .thenReturn(searchFilter); - Mockito.when(serviceREST.getServices(searchFilter)).thenReturn(services); - Mockito.when(serviceUtil.toVXAsset(rangerService1)).thenReturn(vXAsset1); - Mockito.when(serviceUtil.toVXAsset(rangerService2)).thenReturn(vXAsset2); - VXAssetList vXAssetList = assetREST.searchXAssets(request); - Assert.assertNotNull(vXAssetList); - Assert.assertEquals(expectedVXAsset.getVXAssets(), vXAssetList.getVXAssets()); - Mockito.verify(searchUtil).getSearchFilterFromLegacyRequestForRepositorySearch(request, null); - Mockito.verify(serviceREST).getServices(searchFilter); - Mockito.verify(serviceUtil, Mockito.times(1)).toVXAsset(rangerService1); - Mockito.verify(serviceUtil, Mockito.times(1)).toVXAsset(rangerService2); - } - - @Test - public void testCountXAssets() { - RangerService rangerService1 = rangerService(Id); - RangerService rangerService2 = rangerService(9L); - VXAsset vXAsset1 = vXAsset(Id); - VXAsset vXAsset2 = vXAsset(9L); - VXAssetList expectedVXAsset = new VXAssetList(); - List vXAsset = Arrays.asList(vXAsset1, vXAsset2); - expectedVXAsset.setVXAssets(vXAsset); - VXLong expectedAsset = new VXLong(); - expectedAsset.setValue(2l); - - List services = Arrays.asList(rangerService1, rangerService2); - SearchFilter searchFilter = new SearchFilter(); - Mockito.when(searchUtil.getSearchFilterFromLegacyRequest(request, null)) - .thenReturn(searchFilter); - Mockito.when(serviceREST.getServices(searchFilter)).thenReturn(services); - Mockito.when(serviceUtil.toVXAsset(rangerService1)).thenReturn(vXAsset1); - Mockito.when(serviceUtil.toVXAsset(rangerService2)).thenReturn(vXAsset2); - VXLong actualAsset = assetREST.countXAssets(request); - Assert.assertEquals(expectedAsset.getValue(), actualAsset.getValue()); - } - - @Test - public void testGetXResource() { - VXResource expectedvxResource = vxResource(Id); - RangerPolicy rangerPolicy = rangerPolicy(Id); - RangerService rangerService = rangerService(Id); - Mockito.when(serviceREST.getPolicy(Id)).thenReturn(rangerPolicy); - Mockito.when(serviceREST.getServiceByName(rangerPolicy.getService())).thenReturn(rangerService); - Mockito.when(serviceUtil.toVXResource(rangerPolicy, rangerService)).thenReturn(expectedvxResource); - VXResource actualvxResource = assetREST.getXResource(Id); - Assert.assertNotNull(actualvxResource); - Assert.assertEquals(expectedvxResource, actualvxResource); - } - - @Test - public void testCreateXResource() { - VXResource vxResource = vxResource(Id); - RangerPolicy rangerPolicy = rangerPolicy(Id); - RangerService rangerService = rangerService(Id); - Mockito.when(serviceREST.getService(vxResource.getAssetId())).thenReturn(rangerService); - Mockito.when(serviceREST.createPolicy(rangerPolicy, null)).thenReturn(rangerPolicy); - Mockito.when(serviceUtil.toRangerPolicy(vxResource, rangerService)).thenReturn(rangerPolicy); - Mockito.when(serviceUtil.toVXResource(rangerPolicy, rangerService)).thenReturn(vxResource); - VXResource actualvxResource = assetREST.createXResource(vxResource); - Assert.assertNotNull(actualvxResource); - Assert.assertEquals(vxResource, actualvxResource); - Mockito.verify(serviceREST).getService(vxResource.getAssetId()); - Mockito.verify(serviceREST).createPolicy(rangerPolicy, null); - Mockito.verify(serviceUtil).toRangerPolicy(vxResource, rangerService); - Mockito.verify(serviceUtil).toVXResource(rangerPolicy, rangerService); - } - - @Test - public void testUpdateXResource() { - VXResource vxResource = vxResource(Id); - RangerPolicy rangerPolicy = rangerPolicy(Id); - RangerService rangerService = rangerService(Id); - Mockito.when(serviceREST.getService(vxResource.getAssetId())).thenReturn(rangerService); - Mockito.when(serviceREST.updatePolicy(rangerPolicy, Id)).thenReturn(rangerPolicy); - Mockito.when(serviceUtil.toRangerPolicy(vxResource, rangerService)).thenReturn(rangerPolicy); - Mockito.when(serviceUtil.toVXResource(rangerPolicy, rangerService)).thenReturn(vxResource); - VXResource actualvxResource = assetREST.updateXResource(vxResource, Id); - Assert.assertNotNull(actualvxResource); - Assert.assertEquals(vxResource, actualvxResource); - Mockito.verify(serviceREST).getService(vxResource.getAssetId()); - Mockito.verify(serviceREST).updatePolicy(rangerPolicy, Id); - Mockito.verify(serviceUtil).toRangerPolicy(vxResource, rangerService); - Mockito.verify(serviceUtil).toVXResource(rangerPolicy, rangerService); - } - - @Test - public void testUpdateXResourceForInvalidResourceId() { - VXResource vxResource = vxResource(Id); - RangerPolicy rangerPolicy = rangerPolicy(Id); - RangerService rangerService = rangerService(Id); - Mockito.when(restErrorUtil.createRESTException(Mockito.anyInt(), Mockito.anyString(), Mockito.anyBoolean())).thenThrow(new WebApplicationException()); - thrown.expect(WebApplicationException.class); - VXResource actualvxResource = assetREST.updateXResource(vxResource, -11L); - Assert.assertNotNull(actualvxResource); - Assert.assertEquals(vxResource, actualvxResource); - Mockito.verify(serviceREST).getService(vxResource.getAssetId()); - Mockito.verify(serviceREST).updatePolicy(rangerPolicy, Id); - Mockito.verify(serviceUtil).toRangerPolicy(vxResource, rangerService); - Mockito.verify(serviceUtil).toVXResource(rangerPolicy, rangerService); - } - - @Test - public void testUpdateXResourceWhenResourceIdIsNull() { - VXResource vxResource = vxResource(Id); - vxResource.setId(null); - RangerPolicy rangerPolicy = rangerPolicy(Id); - RangerService rangerService = rangerService(Id); - Mockito.when(serviceREST.getService(vxResource.getAssetId())).thenReturn(rangerService); - Mockito.when(serviceREST.updatePolicy(rangerPolicy, Id)).thenReturn(rangerPolicy); - Mockito.when(serviceUtil.toRangerPolicy(vxResource, rangerService)).thenReturn(rangerPolicy); - Mockito.when(serviceUtil.toVXResource(rangerPolicy, rangerService)).thenReturn(vxResource); - VXResource actualvxResource = assetREST.updateXResource(vxResource, Id); - Assert.assertNotNull(actualvxResource); - Assert.assertEquals(vxResource, actualvxResource); - Mockito.verify(serviceREST).getService(vxResource.getAssetId()); - Mockito.verify(serviceREST).updatePolicy(rangerPolicy, Id); - Mockito.verify(serviceUtil).toRangerPolicy(vxResource, rangerService); - Mockito.verify(serviceUtil).toVXResource(rangerPolicy, rangerService); - } - - @Test - public void testDeleteXResource() { - Mockito.doNothing().when(serviceREST).deletePolicy(Id); - assetREST.deleteXResource(Id, request); - Mockito.verify(serviceREST).deletePolicy(Id); - } - - @Test - public void testSearchXResource() { - List rangerPolicyList = new ArrayList(); - List vXResourcesList = new ArrayList(); - RangerService rangerService = rangerService(Id); - long i; - for (i = 1; i <= 2; i++) { - RangerPolicy rangerPolicy = rangerPolicy(i); - VXResource vXresource = vxResource(i); - rangerPolicyList.add(rangerPolicy); - vXResourcesList.add(vXresource); - Mockito.when(serviceUtil.toVXResource(rangerPolicy, rangerService)).thenReturn(vXresource); - } - Mockito.when(serviceREST.getServiceByName(rangerPolicyList.get(0).getService())).thenReturn(rangerService); - VXResourceList expectedVXResourceList = new VXResourceList(); - expectedVXResourceList.setVXResources(vXResourcesList); - - SearchFilter searchFilter = new SearchFilter(); - Mockito.when(searchUtil.getSearchFilterFromLegacyRequest(request, null)).thenReturn(searchFilter); - Mockito.when(serviceREST.getPolicies(searchFilter)).thenReturn(rangerPolicyList); - VXResourceList actualVXResourceList = assetREST.searchXResources(request); - Assert.assertNotNull(actualVXResourceList); - Assert.assertEquals(expectedVXResourceList.getVXResources(), actualVXResourceList.getVXResources()); - Mockito.verify(searchUtil).getSearchFilterFromLegacyRequest(request, null); - Mockito.verify(serviceREST).getPolicies(searchFilter); - for (i = 0; i < 2; i++) { - Mockito.verify(serviceUtil, Mockito.times(1)).toVXResource(rangerPolicyList.get((int) i), rangerService); - } - Mockito.verify(serviceREST, Mockito.times(2)).getServiceByName(rangerPolicyList.get(0).getService()); - } - - @Test - public void testCountXResource() { - List rangerPolicyList = new ArrayList(); - List vXResourcesList = new ArrayList(); - RangerService rangerService = rangerService(Id); - long i; - for (i = 1; i <= 2; i++) { - RangerPolicy rangerPolicy = rangerPolicy(i); - VXResource vXresource = vxResource(i); - rangerPolicyList.add(rangerPolicy); - vXResourcesList.add(vXresource); - Mockito.when(serviceUtil.toVXResource(rangerPolicy, rangerService)).thenReturn(vXresource); - } - VXLong expectedXResouce = new VXLong(); - expectedXResouce.setValue(2l); - Mockito.when(serviceREST.getServiceByName(rangerPolicyList.get(0).getService())).thenReturn(rangerService); - VXResourceList expectedVXResourceList = new VXResourceList(); - expectedVXResourceList.setVXResources(vXResourcesList); - - SearchFilter searchFilter = new SearchFilter(); - Mockito.when(searchUtil.getSearchFilterFromLegacyRequest(request, null)).thenReturn(searchFilter); - Mockito.when(serviceREST.getPolicies(searchFilter)).thenReturn(rangerPolicyList); - VXLong actualXResource = assetREST.countXResources(request); - Assert.assertEquals(expectedXResouce.getValue(), actualXResource.getValue()); - } - - @Test - public void testGetXCredentialStore() { - VXCredentialStore vXCredentialStore = vXCredentialStore(); - Mockito.when(assetMgr.getXCredentialStore(Id)).thenReturn(vXCredentialStore); - VXCredentialStore actualvXCredentialStore = assetREST.getXCredentialStore(Id); - Assert.assertNotNull(actualvXCredentialStore); - Assert.assertEquals(vXCredentialStore, actualvXCredentialStore); - Mockito.verify(assetMgr).getXCredentialStore(Id); - } - - @Test - public void testCreateXCredentialStore() { - VXCredentialStore vXCredentialStore = vXCredentialStore(); - Mockito.when(assetMgr.createXCredentialStore(vXCredentialStore)).thenReturn(vXCredentialStore); - VXCredentialStore actualvXCredentialStore = assetREST.createXCredentialStore(vXCredentialStore); - Assert.assertNotNull(actualvXCredentialStore); - Assert.assertEquals(vXCredentialStore, actualvXCredentialStore); - Mockito.verify(assetMgr).createXCredentialStore(vXCredentialStore); - } - - @Test - public void testUpdateXCredentialStoree() { - VXCredentialStore vXCredentialStore = vXCredentialStore(); - Mockito.when(assetMgr.updateXCredentialStore(vXCredentialStore)).thenReturn(vXCredentialStore); - VXCredentialStore actualvXCredentialStore = assetREST.updateXCredentialStore(vXCredentialStore); - Assert.assertNotNull(actualvXCredentialStore); - Assert.assertEquals(vXCredentialStore, actualvXCredentialStore); - Mockito.verify(assetMgr).updateXCredentialStore(vXCredentialStore); - } - - @Test - public void testDeleteXCredentialStore() { - Mockito.doNothing().when(assetMgr).deleteXCredentialStore(Id, false); - assetREST.deleteXCredentialStore(Id, request); - Mockito.verify(assetMgr).deleteXCredentialStore(Id, false); - } - - @Test - public void testSearchXCredentialStores() { - VXCredentialStore vXCredentialStore = vXCredentialStore(); - List vXCredentialStores = Arrays.asList(vXCredentialStore); - VXCredentialStoreList vXCredentialStoreList = new VXCredentialStoreList(); - vXCredentialStoreList.setVXCredentialStores(vXCredentialStores); - SearchCriteria searchCriteria = new SearchCriteria(); - List sortFields = null; - Mockito.when(searchUtil.extractCommonCriterias(request, sortFields)).thenReturn(searchCriteria); - Mockito.when(assetMgr.searchXCredentialStores(searchCriteria)).thenReturn(vXCredentialStoreList); - VXCredentialStoreList actualvxCredentialStoreList = assetREST.searchXCredentialStores(request); - Assert.assertEquals(vXCredentialStoreList.getVXCredentialStores(), - actualvxCredentialStoreList.getVXCredentialStores()); - Mockito.verify(assetMgr).searchXCredentialStores(searchCriteria); - } - - @Test - public void testCountXCredentialStores() { - VXLong expectedvXLong = new VXLong(); - SearchCriteria searchCriteria = new SearchCriteria(); - List sortFields = null; - Mockito.when(searchUtil.extractCommonCriterias(request, sortFields)).thenReturn(searchCriteria); - Mockito.when(assetMgr.getXCredentialStoreSearchCount(searchCriteria)).thenReturn(expectedvXLong); - VXLong actualvXLong = assetREST.countXCredentialStores(request); - Assert.assertEquals(expectedvXLong, actualvXLong); - Mockito.verify(assetMgr).getXCredentialStoreSearchCount(searchCriteria); - } - - @Test - public void testSearchXPolicyExportAudits() { - SearchCriteria searchCriteria = new SearchCriteria(); - List sortFields = null; - List vXPolicyExportAudits = new ArrayList(); - VXPolicyExportAuditList vXPolicyExportAuditList = new VXPolicyExportAuditList(); - vXPolicyExportAuditList.setVXPolicyExportAudits(vXPolicyExportAudits); - Mockito.when(searchUtil.extractCommonCriterias(request, sortFields)).thenReturn(searchCriteria); - Mockito.when(searchUtil.extractString((HttpServletRequest) Mockito.any(), - (SearchCriteria) Mockito.any(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) - .thenReturn("test"); - Mockito.when(searchUtil.extractInt((HttpServletRequest) Mockito.any(), - (SearchCriteria) Mockito.any(), Mockito.anyString(), Mockito.anyString())) - .thenReturn((Integer) 8); - Mockito.when(assetMgr.searchXPolicyExportAudits(searchCriteria)).thenReturn(vXPolicyExportAuditList); - VXPolicyExportAuditList expectedVXPolicyExportAuditList = assetREST.searchXPolicyExportAudits(request); - Assert.assertEquals(vXPolicyExportAuditList, expectedVXPolicyExportAuditList); - Mockito.verify(searchUtil).extractCommonCriterias(request, sortFields); - Mockito.verify(searchUtil, Mockito.times(5)).extractString((HttpServletRequest) Mockito.any(), - (SearchCriteria) Mockito.any(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString()); - Mockito.verify(searchUtil).extractInt((HttpServletRequest) Mockito.any(), - (SearchCriteria) Mockito.any(), Mockito.anyString(), Mockito.anyString()); - Mockito.verify(searchUtil, Mockito.times(2)).extractDate((HttpServletRequest) Mockito.any(), - (SearchCriteria) Mockito.any(), Mockito.anyString(), Mockito.anyString(), (String)Mockito.isNull()); - Mockito.verify(searchUtil).extractCommonCriterias(request, sortFields); - Mockito.verify(assetMgr).searchXPolicyExportAudits(searchCriteria); - } - - @Test - public void testGetReportLogs() { - SearchCriteria searchCriteria = new SearchCriteria(); - List sortFields = xTrxLogService.getSortFields(); - List vXTrxLogs = new ArrayList(); - VXTrxLogList vXTrxLogList = new VXTrxLogList(); - vXTrxLogList.setVXTrxLogs(vXTrxLogs); - Mockito.when(searchUtil.extractCommonCriterias(request, sortFields)).thenReturn(searchCriteria); - Mockito.when(searchUtil.extractString((HttpServletRequest) Mockito.any(), - (SearchCriteria) Mockito.any(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) - .thenReturn("test"); - Mockito.when(searchUtil.extractInt((HttpServletRequest) Mockito.any(), - (SearchCriteria) Mockito.any(), Mockito.anyString(), Mockito.anyString())) - .thenReturn((Integer) 8); - Mockito.when(searchUtil.extractDate((HttpServletRequest) Mockito.any(), - (SearchCriteria) Mockito.any(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) - .thenReturn(new Date()); - Mockito.when(assetMgr.getReportLogs(searchCriteria)).thenReturn(vXTrxLogList); - VXTrxLogList expectedVXTrxLogListt = assetREST.getReportLogs(request); - Assert.assertEquals(vXTrxLogList, expectedVXTrxLogListt); - Mockito.verify(searchUtil, Mockito.times(4)).extractString((HttpServletRequest) Mockito.any(), - (SearchCriteria) Mockito.any(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString()); - Mockito.verify(searchUtil, Mockito.times(2)).extractInt((HttpServletRequest) Mockito.any(), - (SearchCriteria) Mockito.any(), Mockito.anyString(), Mockito.anyString()); - Mockito.verify(searchUtil, Mockito.times(2)).extractDate((HttpServletRequest) Mockito.any(), - (SearchCriteria) Mockito.any(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString()); - Mockito.verify(assetMgr).getReportLogs(searchCriteria); - Mockito.verify(searchUtil).extractCommonCriterias(request, sortFields); - } - - @Test - public void testGetTransactionReport() { - List vXTrxLogs = new ArrayList(); - VXTrxLogList vXTrxLogList = new VXTrxLogList(); - vXTrxLogList.setVXTrxLogs(vXTrxLogs); - String transactionId = "123456"; - Mockito.when(assetMgr.getTransactionReport(transactionId)).thenReturn(vXTrxLogList); - VXTrxLogList expectedVXTrxLogListt = assetREST.getTransactionReport(request, transactionId); - Assert.assertEquals(vXTrxLogList, expectedVXTrxLogListt); - Mockito.verify(assetMgr).getTransactionReport(transactionId); - } - - @Test - public void testGetAccessLogs() { - SearchCriteria searchCriteria = new SearchCriteria(); - List sortFields = null; - List vXAccessAudits = new ArrayList(); - VXAccessAuditList vXAccessAuditList = new VXAccessAuditList(); - vXAccessAuditList.setVXAccessAudits(vXAccessAudits); - Mockito.when(searchUtil.extractCommonCriterias(request, sortFields)).thenReturn(searchCriteria); - Mockito.when(searchUtil.extractString((HttpServletRequest) Mockito.any(), - (SearchCriteria) Mockito.any(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) - .thenReturn("test"); - Mockito.when(searchUtil.extractInt((HttpServletRequest) Mockito.any(), - (SearchCriteria) Mockito.any(), Mockito.anyString(), Mockito.anyString())) - .thenReturn((Integer) 8); - Mockito.when(searchUtil.extractDate((HttpServletRequest) Mockito.any(), - (SearchCriteria) Mockito.any(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) - .thenReturn(new Date()); - Mockito.when(searchUtil.extractLong((HttpServletRequest) Mockito.any(), - (SearchCriteria) Mockito.any(), Mockito.anyString(), Mockito.anyString())).thenReturn((Long) 8l); - Mockito.when(msBizUtil.isKeyAdmin()).thenReturn(false); - Mockito.when(daoManager.getXXServiceDef()).thenReturn(xxServiceDefDao); - XXServiceDef xServiceDef = new XXServiceDef(); - xServiceDef.setId(Id); - Mockito.when(xxServiceDefDao.findByName(EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_KMS_NAME)) - .thenReturn(xServiceDef); - Mockito.when(assetMgr.getAccessLogs(searchCriteria)).thenReturn(vXAccessAuditList); - VXAccessAuditList expectedVXAccessAuditList = assetREST.getAccessLogs(request, null); - Assert.assertEquals(vXAccessAuditList, expectedVXAccessAuditList); - Mockito.verify(msBizUtil).isKeyAdmin(); - Mockito.verify(assetMgr).getAccessLogs(searchCriteria); - Mockito.verify(daoManager).getXXServiceDef(); - Mockito.verify(searchUtil, Mockito.times(14)).extractString((HttpServletRequest) Mockito.any(), - (SearchCriteria) Mockito.any(), Mockito.anyString(), Mockito.anyString(), Mockito.nullable(String.class)); - Mockito.verify(searchUtil, Mockito.times(4)).extractInt((HttpServletRequest) Mockito.any(), - (SearchCriteria) Mockito.any(), Mockito.anyString(), Mockito.anyString()); - Mockito.verify(searchUtil, Mockito.times(2)).extractDate((HttpServletRequest) Mockito.any(), - (SearchCriteria) Mockito.any(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString()); - Mockito.verify(searchUtil).extractLong((HttpServletRequest) Mockito.any(), - (SearchCriteria) Mockito.any(), Mockito.anyString(), Mockito.anyString()); - Mockito.verify(searchUtil).extractStringList(Mockito.any(HttpServletRequest.class), - (SearchCriteria) Mockito.any(), Mockito.eq("requestUser"), Mockito.eq("Users"), Mockito.eq("requestUser"), - Mockito.any(), Mockito.eq(StringUtil.VALIDATION_TEXT)); - Mockito.verify(searchUtil).extractStringList(Mockito.any(HttpServletRequest.class), - (SearchCriteria) Mockito.any(), Mockito.eq("excludeUser"), Mockito.eq("Exclude Users"), Mockito.eq("-requestUser"), - Mockito.any(), Mockito.eq(StringUtil.VALIDATION_TEXT)); - Mockito.verify(searchUtil).extractStringList(Mockito.any(HttpServletRequest.class), - (SearchCriteria) Mockito.any(), Mockito.eq("zoneName"), Mockito.eq("Zone Name List"), Mockito.eq("zoneName"), - Mockito.eq(null), Mockito.eq(null)); - Mockito.verify(searchUtil).extractCommonCriterias(Mockito.any(HttpServletRequest.class), - (List) Mockito.any()); - Mockito.verifyNoMoreInteractions(searchUtil, assetMgr, daoManager); - - } - - @Test - public void testGetAccessLogsForKms() { - SearchCriteria searchCriteria = new SearchCriteria(); - List sortFields = null; - List vXAccessAudits = new ArrayList(); - VXAccessAuditList vXAccessAuditList = new VXAccessAuditList(); - vXAccessAuditList.setVXAccessAudits(vXAccessAudits); - Mockito.when(searchUtil.extractCommonCriterias(request, sortFields)).thenReturn(searchCriteria); - Mockito.when(searchUtil.extractString((HttpServletRequest) Mockito.any(), - (SearchCriteria) Mockito.any(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) - .thenReturn("test"); - Mockito.when(searchUtil.extractInt((HttpServletRequest) Mockito.any(), - (SearchCriteria) Mockito.any(), Mockito.anyString(), Mockito.anyString())) - .thenReturn((Integer) 8); - Mockito.when(searchUtil.extractDate((HttpServletRequest) Mockito.any(), - (SearchCriteria) Mockito.any(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) - .thenReturn(new Date()); - Mockito.when(searchUtil.extractLong((HttpServletRequest) Mockito.any(), - (SearchCriteria) Mockito.any(), Mockito.anyString(), Mockito.anyString())).thenReturn((Long) 8l); - Mockito.when(searchUtil.extractLong((HttpServletRequest) Mockito.any(), - (SearchCriteria) Mockito.any(), Mockito.anyString(), Mockito.anyString())).thenReturn((Long) 8l); - Mockito.when(msBizUtil.isKeyAdmin()).thenReturn(true); - Mockito.when(daoManager.getXXServiceDef()).thenReturn(xxServiceDefDao); - XXServiceDef xServiceDef = new XXServiceDef(); - xServiceDef.setId(Id); - Mockito.when(xxServiceDefDao.findByName(EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_KMS_NAME)) - .thenReturn(xServiceDef); - Mockito.when(assetMgr.getAccessLogs(searchCriteria)).thenReturn(vXAccessAuditList); - VXAccessAuditList expectedVXAccessAuditList = assetREST.getAccessLogs(request, null); - Assert.assertEquals(vXAccessAuditList, expectedVXAccessAuditList); - Mockito.verify(msBizUtil).isKeyAdmin(); - Mockito.verify(assetMgr).getAccessLogs(searchCriteria); - Mockito.verify(daoManager).getXXServiceDef(); - Mockito.verify(searchUtil, Mockito.times(14)).extractString((HttpServletRequest) Mockito.any(), - (SearchCriteria) Mockito.any(), Mockito.anyString(), Mockito.anyString(), Mockito.nullable(String.class)); - Mockito.verify(searchUtil, Mockito.times(4)).extractInt((HttpServletRequest) Mockito.any(), - (SearchCriteria) Mockito.any(), Mockito.anyString(), Mockito.anyString()); - Mockito.verify(searchUtil, Mockito.times(2)).extractDate((HttpServletRequest) Mockito.any(), - (SearchCriteria) Mockito.any(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString()); - Mockito.verify(searchUtil).extractLong((HttpServletRequest) Mockito.any(), - (SearchCriteria) Mockito.any(), Mockito.anyString(), Mockito.anyString()); - Mockito.verify(searchUtil).extractStringList(Mockito.any(HttpServletRequest.class), - (SearchCriteria) Mockito.any(), Mockito.eq("requestUser"), Mockito.eq("Users"), Mockito.eq("requestUser"), - Mockito.any(), Mockito.eq(StringUtil.VALIDATION_TEXT)); - Mockito.verify(searchUtil).extractStringList(Mockito.any(HttpServletRequest.class), - (SearchCriteria) Mockito.any(), Mockito.eq("excludeUser"), Mockito.eq("Exclude Users"), Mockito.eq("-requestUser"), - Mockito.any(), Mockito.eq(StringUtil.VALIDATION_TEXT)); - Mockito.verify(searchUtil).extractStringList(Mockito.any(HttpServletRequest.class), - (SearchCriteria) Mockito.any(), Mockito.eq("zoneName"), Mockito.eq("Zone Name List"), Mockito.eq("zoneName"), - Mockito.eq(null), Mockito.eq(null)); - Mockito.verify(searchUtil).extractCommonCriterias(Mockito.any(HttpServletRequest.class), - (List) Mockito.any()); - Mockito.verifyNoMoreInteractions(searchUtil, assetMgr, daoManager); - } - - @Test - public void testGrantPermission() { - RangerPolicy policy = rangerPolicy(Id); - RangerService service = rangerService(Id); - VXPolicy vXPolicy = vXPolicy(policy, service); - GrantRevokeRequest grantRequestObj = new GrantRevokeRequest(); - grantRequestObj.setAccessTypes(null); - grantRequestObj.setDelegateAdmin(true); - grantRequestObj.setEnableAudit(true); - grantRequestObj.setGrantor("read"); - grantRequestObj.setIsRecursive(true); - RESTResponse response = Mockito.mock(RESTResponse.class); - Mockito.when(serviceUtil.toGrantRevokeRequest(vXPolicy)).thenReturn(grantRequestObj); - try { - Mockito.when(serviceREST.grantAccess(vXPolicy.getRepositoryName(), grantRequestObj, request)) - .thenReturn(response); - } catch (Exception e) { - fail("test failed due to: " + e.getMessage()); - } - VXPolicy expectedVXPolicy = assetREST.grantPermission(request, vXPolicy); - Assert.assertEquals(vXPolicy, expectedVXPolicy); - Mockito.verify(serviceUtil).toGrantRevokeRequest(vXPolicy); - try { - Mockito.verify(serviceREST).grantAccess(vXPolicy.getRepositoryName(), grantRequestObj, request); - } catch (Exception e) { - fail("test failed due to: " + e.getMessage()); - } - } - - @Test - public void testGrantPermissionWebApplicationException() { - RangerPolicy policy = rangerPolicy(Id); - RangerService service = rangerService(Id); - VXPolicy vXPolicy = vXPolicy(policy, service); - GrantRevokeRequest grantRequestObj = new GrantRevokeRequest(); - grantRequestObj.setAccessTypes(null); - grantRequestObj.setDelegateAdmin(true); - grantRequestObj.setEnableAudit(true); - grantRequestObj.setGrantor("read"); - grantRequestObj.setIsRecursive(true); - WebApplicationException webApplicationException = new WebApplicationException(); - Mockito.when(serviceUtil.toGrantRevokeRequest(vXPolicy)).thenReturn(grantRequestObj); - try { - Mockito.when(serviceREST.grantAccess(vXPolicy.getRepositoryName(), grantRequestObj, request)) - .thenThrow(webApplicationException); - } catch (Exception e) { - fail("test failed due to: " + e.getMessage()); - } - try { - assetREST.grantPermission(request, vXPolicy); - fail("Exception not thrown"); - } catch (WebApplicationException e) { - Assert.assertTrue(true); - } - Mockito.verify(serviceUtil).toGrantRevokeRequest(vXPolicy); - try { - Mockito.verify(serviceREST).grantAccess(vXPolicy.getRepositoryName(), grantRequestObj, request); - } catch (Exception e) { - fail("test failed due to: " + e.getMessage()); - } - - } - - @Test - public void testRevokePermission() { - RangerPolicy policy = rangerPolicy(Id); - RangerService service = rangerService(Id); - VXPolicy vXPolicy = vXPolicy(policy, service); - GrantRevokeRequest grantRequestObj = new GrantRevokeRequest(); - grantRequestObj.setAccessTypes(null); - grantRequestObj.setDelegateAdmin(true); - grantRequestObj.setEnableAudit(true); - grantRequestObj.setGrantor("read"); - grantRequestObj.setIsRecursive(true); - RESTResponse response = Mockito.mock(RESTResponse.class); - Mockito.when(serviceUtil.toGrantRevokeRequest(vXPolicy)).thenReturn(grantRequestObj); - try { - Mockito.when(serviceREST.revokeAccess(vXPolicy.getRepositoryName(), grantRequestObj, request)) - .thenReturn(response); - } catch (Exception e) { - fail("test failed due to: " + e.getMessage()); - } - VXPolicy expectedVXPolicy = assetREST.revokePermission(request, vXPolicy); - Assert.assertEquals(vXPolicy, expectedVXPolicy); - Mockito.verify(serviceUtil).toGrantRevokeRequest(vXPolicy); - try { - Mockito.verify(serviceREST).revokeAccess(vXPolicy.getRepositoryName(), grantRequestObj, request); - } catch (Exception e) { - fail("test failed due to: " + e.getMessage()); - } - } - - @Test - public void testRevokePermissionWebApplicationException() { - RangerPolicy policy = rangerPolicy(Id); - RangerService service = rangerService(Id); - VXPolicy vXPolicy = vXPolicy(policy, service); - GrantRevokeRequest grantRequestObj = new GrantRevokeRequest(); - grantRequestObj.setAccessTypes(null); - grantRequestObj.setDelegateAdmin(true); - grantRequestObj.setEnableAudit(true); - grantRequestObj.setGrantor("read"); - grantRequestObj.setIsRecursive(true); - WebApplicationException webApplicationException = new WebApplicationException(); - Mockito.when(serviceUtil.toGrantRevokeRequest(vXPolicy)).thenReturn(grantRequestObj); - try { - Mockito.when(serviceREST.revokeAccess(vXPolicy.getRepositoryName(), grantRequestObj, request)) - .thenThrow(webApplicationException); - } catch (Exception e) { - fail("test failed due to: " + e.getMessage()); - } - try { - assetREST.revokePermission(request, vXPolicy); - fail("Exception not thrown"); - } catch (WebApplicationException e) { - Assert.assertTrue(true); - } - Mockito.verify(serviceUtil).toGrantRevokeRequest(vXPolicy); - try { - Mockito.verify(serviceREST).revokeAccess(vXPolicy.getRepositoryName(), grantRequestObj, request); - } catch (Exception e) { - fail("test failed due to: " + e.getMessage()); - } - - } - - @Test - public void testGetReportLogsForAuditAdmin() { - SearchCriteria searchCriteria = new SearchCriteria(); - List vXTrxLogs = new ArrayList(); - VXTrxLogList vXTrxLogList = new VXTrxLogList(); - vXTrxLogList.setVXTrxLogs(vXTrxLogs); - Mockito.when(searchUtil.extractCommonCriterias(request, xTrxLogService.getSortFields())).thenReturn(searchCriteria); - Mockito.when(searchUtil.extractString((HttpServletRequest) Mockito.any(), - (SearchCriteria) Mockito.any(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) - .thenReturn("test"); - Mockito.when(searchUtil.extractInt((HttpServletRequest) Mockito.any(), - (SearchCriteria) Mockito.any(), Mockito.anyString(), Mockito.anyString())) - .thenReturn((Integer) 8); - Mockito.when(searchUtil.extractDate((HttpServletRequest) Mockito.any(), - (SearchCriteria) Mockito.any(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) - .thenReturn(new Date()); - Mockito.when(assetMgr.getReportLogs(searchCriteria)).thenReturn(vXTrxLogList); - VXTrxLogList expectedVXTrxLogListt = assetREST.getReportLogs(request); - Assert.assertEquals(vXTrxLogList, expectedVXTrxLogListt); - Mockito.verify(searchUtil, Mockito.times(4)).extractString((HttpServletRequest) Mockito.any(), - (SearchCriteria) Mockito.any(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString()); - Mockito.verify(searchUtil, Mockito.times(2)).extractInt((HttpServletRequest) Mockito.any(), - (SearchCriteria) Mockito.any(), Mockito.anyString(), Mockito.anyString()); - Mockito.verify(searchUtil, Mockito.times(2)).extractDate((HttpServletRequest) Mockito.any(), - (SearchCriteria) Mockito.any(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString()); - Mockito.verify(assetMgr).getReportLogs(searchCriteria); - Mockito.verify(searchUtil).extractCommonCriterias(request, xTrxLogService.getSortFields()); + private static final Long Id = 8L; + @Rule public ExpectedException thrown = ExpectedException.none(); + @Mock + ServiceREST serviceREST; + @Mock + ServiceUtil serviceUtil; + @Mock + RangerSearchUtil searchUtil; + @Mock + RangerBizUtil xaBizUtil; + @Mock + XAssetService xAssetService; + @Mock + XResourceService xResourceService; + @Mock + XCredentialStoreService xCredentialStoreService; + @Mock + AssetMgr assetMgr; + @Mock + HttpServletRequest request; + @Mock + RangerTrxLogV2Service xTrxLogService; + @Mock + XPolicyExportAuditService xPolicyExportAudits; + @Mock + XAccessAuditService xAccessAuditService; + @Mock + XXServiceDefDao xxServiceDefDao; + @Mock + RangerBizUtil msBizUtil; + @Mock + RangerDaoManager daoManager; + @InjectMocks + AssetREST assetREST = new AssetREST(); + @Mock RESTErrorUtil restErrorUtil; + @Mock WebApplicationException webApplicationException; + + @Test + public void testAssetRest() { + } + + @Test + public void testGetXAsset() { + RangerService rangerService = rangerService(Id); + VXAsset vXAsset = vXAsset(Id); + Mockito.when(serviceREST.getService(rangerService.getId())).thenReturn(rangerService); + Mockito.when(serviceUtil.toVXAsset(rangerService)).thenReturn(vXAsset); + VXAsset asset = assetREST.getXAsset(Id); + Assert.assertNotNull(asset); + Assert.assertEquals(vXAsset, asset); + Mockito.verify(serviceREST).getService(rangerService.getId()); + Mockito.verify(serviceUtil).toVXAsset(rangerService); + } + + @Test + public void testCreateXAsset() { + RangerService rangerService = rangerService(Id); + VXAsset vXAsset = vXAsset(Id); + Mockito.when(serviceREST.createService(rangerService)).thenReturn(rangerService); + Mockito.when(serviceUtil.toRangerService(vXAsset)).thenReturn(rangerService); + Mockito.when(serviceUtil.toVXAsset(rangerService)).thenReturn(vXAsset); + VXAsset asset = assetREST.createXAsset(vXAsset); + Assert.assertNotNull(asset); + Assert.assertEquals(vXAsset, asset); + Mockito.verify(serviceREST).createService(rangerService); + Mockito.verify(serviceUtil).toRangerService(vXAsset); + Mockito.verify(serviceUtil).toVXAsset(rangerService); + } + + @Test + public void testUpdateXAsset() { + RangerService rangerService = rangerService(Id); + HttpServletRequest request = null; + VXAsset vXAsset = vXAsset(Id); + Mockito.when(serviceUtil.toRangerService(vXAsset)).thenReturn(rangerService); + Mockito.when(serviceREST.updateService(rangerService, request)).thenReturn(rangerService); + Mockito.when(serviceUtil.toVXAsset(rangerService)).thenReturn(vXAsset); + VXAsset asset = assetREST.updateXAsset(vXAsset); + Assert.assertNotNull(asset); + Assert.assertEquals(vXAsset, asset); + Mockito.verify(serviceREST).updateService(rangerService, request); + Mockito.verify(serviceUtil).toRangerService(vXAsset); + Mockito.verify(serviceUtil).toVXAsset(rangerService); + } + + @Test + public void testDeleteXAsset() { + RangerService rangerService = rangerService(Id); + + Mockito.doNothing().when(serviceREST).deleteService(Id); + assetREST.deleteXAsset(rangerService.getId(), request); + Mockito.verify(serviceREST).deleteService(rangerService.getId()); + } + + @Test + public void testConfigTest() { + RangerService rangerService = rangerService(Id); + VXResponse expectedVxResponse = new VXResponse(); + expectedVxResponse.setStatusCode(VXResponse.STATUS_SUCCESS); + expectedVxResponse.setMsgDesc("test connection successful"); + VXAsset vXAsset = vXAsset(Id); + Mockito.when(serviceUtil.toRangerService(vXAsset)).thenReturn(rangerService); + Mockito.when(serviceREST.validateConfig(rangerService)).thenReturn(expectedVxResponse); + VXResponse actualVxResponse = assetREST.configTest(vXAsset); + Assert.assertNotNull(actualVxResponse); + Assert.assertEquals(expectedVxResponse, actualVxResponse); + Mockito.verify(serviceUtil).toRangerService(vXAsset); + Mockito.verify(serviceREST).validateConfig(rangerService); + } + + @Test + public void testSearchXAssets() { + RangerService rangerService1 = rangerService(Id); + RangerService rangerService2 = rangerService(9L); + VXAsset vXAsset1 = vXAsset(Id); + VXAsset vXAsset2 = vXAsset(9L); + VXAssetList expectedVXAsset = new VXAssetList(); + List vXAsset = Arrays.asList(vXAsset1, vXAsset2); + expectedVXAsset.setVXAssets(vXAsset); + List services = Arrays.asList(rangerService1, rangerService2); + + SearchFilter searchFilter = new SearchFilter(); + Mockito.when(searchUtil.getSearchFilterFromLegacyRequestForRepositorySearch(request, null)).thenReturn(searchFilter); + Mockito.when(serviceREST.getServices(searchFilter)).thenReturn(services); + Mockito.when(serviceUtil.toVXAsset(rangerService1)).thenReturn(vXAsset1); + Mockito.when(serviceUtil.toVXAsset(rangerService2)).thenReturn(vXAsset2); + VXAssetList vXAssetList = assetREST.searchXAssets(request); + Assert.assertNotNull(vXAssetList); + Assert.assertEquals(expectedVXAsset.getVXAssets(), vXAssetList.getVXAssets()); + Mockito.verify(searchUtil).getSearchFilterFromLegacyRequestForRepositorySearch(request, null); + Mockito.verify(serviceREST).getServices(searchFilter); + Mockito.verify(serviceUtil, Mockito.times(1)).toVXAsset(rangerService1); + Mockito.verify(serviceUtil, Mockito.times(1)).toVXAsset(rangerService2); + } + + @Test + public void testCountXAssets() { + RangerService rangerService1 = rangerService(Id); + RangerService rangerService2 = rangerService(9L); + VXAsset vXAsset1 = vXAsset(Id); + VXAsset vXAsset2 = vXAsset(9L); + VXAssetList expectedVXAsset = new VXAssetList(); + List vXAsset = Arrays.asList(vXAsset1, vXAsset2); + expectedVXAsset.setVXAssets(vXAsset); + VXLong expectedAsset = new VXLong(); + expectedAsset.setValue(2L); + + List services = Arrays.asList(rangerService1, rangerService2); + SearchFilter searchFilter = new SearchFilter(); + Mockito.when(searchUtil.getSearchFilterFromLegacyRequest(request, null)).thenReturn(searchFilter); + Mockito.when(serviceREST.getServices(searchFilter)).thenReturn(services); + Mockito.when(serviceUtil.toVXAsset(rangerService1)).thenReturn(vXAsset1); + Mockito.when(serviceUtil.toVXAsset(rangerService2)).thenReturn(vXAsset2); + VXLong actualAsset = assetREST.countXAssets(request); + Assert.assertEquals(expectedAsset.getValue(), actualAsset.getValue()); + } + + @Test + public void testGetXResource() { + VXResource expectedvxResource = vxResource(Id); + RangerPolicy rangerPolicy = rangerPolicy(Id); + RangerService rangerService = rangerService(Id); + Mockito.when(serviceREST.getPolicy(Id)).thenReturn(rangerPolicy); + Mockito.when(serviceREST.getServiceByName(rangerPolicy.getService())).thenReturn(rangerService); + Mockito.when(serviceUtil.toVXResource(rangerPolicy, rangerService)).thenReturn(expectedvxResource); + VXResource actualvxResource = assetREST.getXResource(Id); + Assert.assertNotNull(actualvxResource); + Assert.assertEquals(expectedvxResource, actualvxResource); + } + + @Test + public void testCreateXResource() { + VXResource vxResource = vxResource(Id); + RangerPolicy rangerPolicy = rangerPolicy(Id); + RangerService rangerService = rangerService(Id); + Mockito.when(serviceREST.getService(vxResource.getAssetId())).thenReturn(rangerService); + Mockito.when(serviceREST.createPolicy(rangerPolicy, null)).thenReturn(rangerPolicy); + Mockito.when(serviceUtil.toRangerPolicy(vxResource, rangerService)).thenReturn(rangerPolicy); + Mockito.when(serviceUtil.toVXResource(rangerPolicy, rangerService)).thenReturn(vxResource); + VXResource actualvxResource = assetREST.createXResource(vxResource); + Assert.assertNotNull(actualvxResource); + Assert.assertEquals(vxResource, actualvxResource); + Mockito.verify(serviceREST).getService(vxResource.getAssetId()); + Mockito.verify(serviceREST).createPolicy(rangerPolicy, null); + Mockito.verify(serviceUtil).toRangerPolicy(vxResource, rangerService); + Mockito.verify(serviceUtil).toVXResource(rangerPolicy, rangerService); + } + + @Test + public void testUpdateXResource() { + VXResource vxResource = vxResource(Id); + RangerPolicy rangerPolicy = rangerPolicy(Id); + RangerService rangerService = rangerService(Id); + Mockito.when(serviceREST.getService(vxResource.getAssetId())).thenReturn(rangerService); + Mockito.when(serviceREST.updatePolicy(rangerPolicy, Id)).thenReturn(rangerPolicy); + Mockito.when(serviceUtil.toRangerPolicy(vxResource, rangerService)).thenReturn(rangerPolicy); + Mockito.when(serviceUtil.toVXResource(rangerPolicy, rangerService)).thenReturn(vxResource); + VXResource actualvxResource = assetREST.updateXResource(vxResource, Id); + Assert.assertNotNull(actualvxResource); + Assert.assertEquals(vxResource, actualvxResource); + Mockito.verify(serviceREST).getService(vxResource.getAssetId()); + Mockito.verify(serviceREST).updatePolicy(rangerPolicy, Id); + Mockito.verify(serviceUtil).toRangerPolicy(vxResource, rangerService); + Mockito.verify(serviceUtil).toVXResource(rangerPolicy, rangerService); + } + + @Test + public void testUpdateXResourceForInvalidResourceId() { + VXResource vxResource = vxResource(Id); + RangerPolicy rangerPolicy = rangerPolicy(Id); + RangerService rangerService = rangerService(Id); + Mockito.when(restErrorUtil.createRESTException(Mockito.anyInt(), Mockito.anyString(), Mockito.anyBoolean())).thenThrow(new WebApplicationException()); + thrown.expect(WebApplicationException.class); + VXResource actualvxResource = assetREST.updateXResource(vxResource, -11L); + Assert.assertNotNull(actualvxResource); + Assert.assertEquals(vxResource, actualvxResource); + Mockito.verify(serviceREST).getService(vxResource.getAssetId()); + Mockito.verify(serviceREST).updatePolicy(rangerPolicy, Id); + Mockito.verify(serviceUtil).toRangerPolicy(vxResource, rangerService); + Mockito.verify(serviceUtil).toVXResource(rangerPolicy, rangerService); + } + + @Test + public void testUpdateXResourceWhenResourceIdIsNull() { + VXResource vxResource = vxResource(Id); + vxResource.setId(null); + RangerPolicy rangerPolicy = rangerPolicy(Id); + RangerService rangerService = rangerService(Id); + Mockito.when(serviceREST.getService(vxResource.getAssetId())).thenReturn(rangerService); + Mockito.when(serviceREST.updatePolicy(rangerPolicy, Id)).thenReturn(rangerPolicy); + Mockito.when(serviceUtil.toRangerPolicy(vxResource, rangerService)).thenReturn(rangerPolicy); + Mockito.when(serviceUtil.toVXResource(rangerPolicy, rangerService)).thenReturn(vxResource); + VXResource actualvxResource = assetREST.updateXResource(vxResource, Id); + Assert.assertNotNull(actualvxResource); + Assert.assertEquals(vxResource, actualvxResource); + Mockito.verify(serviceREST).getService(vxResource.getAssetId()); + Mockito.verify(serviceREST).updatePolicy(rangerPolicy, Id); + Mockito.verify(serviceUtil).toRangerPolicy(vxResource, rangerService); + Mockito.verify(serviceUtil).toVXResource(rangerPolicy, rangerService); + } + + @Test + public void testDeleteXResource() { + Mockito.doNothing().when(serviceREST).deletePolicy(Id); + assetREST.deleteXResource(Id, request); + Mockito.verify(serviceREST).deletePolicy(Id); + } + + @Test + public void testSearchXResource() { + List rangerPolicyList = new ArrayList<>(); + List vXResourcesList = new ArrayList<>(); + RangerService rangerService = rangerService(Id); + long i; + for (i = 1; i <= 2; i++) { + RangerPolicy rangerPolicy = rangerPolicy(i); + VXResource vXresource = vxResource(i); + rangerPolicyList.add(rangerPolicy); + vXResourcesList.add(vXresource); + Mockito.when(serviceUtil.toVXResource(rangerPolicy, rangerService)).thenReturn(vXresource); } - - - @Test - public void testGetReportLogsForAuditKeyAdmin() { - SearchCriteria searchCriteria = new SearchCriteria(); - List vXTrxLogs = new ArrayList(); - VXTrxLogList vXTrxLogList = new VXTrxLogList(); - vXTrxLogList.setVXTrxLogs(vXTrxLogs); - Mockito.when(searchUtil.extractCommonCriterias(request, xTrxLogService.getSortFields())).thenReturn(searchCriteria); - Mockito.when(searchUtil.extractString((HttpServletRequest) Mockito.any(), - (SearchCriteria) Mockito.any(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) - .thenReturn("test"); - Mockito.when(searchUtil.extractInt((HttpServletRequest) Mockito.any(), - (SearchCriteria) Mockito.any(), Mockito.anyString(), Mockito.anyString())) - .thenReturn((Integer) 8); - Mockito.when(searchUtil.extractDate((HttpServletRequest) Mockito.any(), - (SearchCriteria) Mockito.any(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) - .thenReturn(new Date()); - Mockito.when(assetMgr.getReportLogs(searchCriteria)).thenReturn(vXTrxLogList); - VXTrxLogList expectedVXTrxLogListt = assetREST.getReportLogs(request); - Assert.assertEquals(vXTrxLogList, expectedVXTrxLogListt); - Mockito.verify(searchUtil, Mockito.times(4)).extractString((HttpServletRequest) Mockito.any(), - (SearchCriteria) Mockito.any(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString()); - Mockito.verify(searchUtil, Mockito.times(2)).extractInt((HttpServletRequest) Mockito.any(), - (SearchCriteria) Mockito.any(), Mockito.anyString(), Mockito.anyString()); - Mockito.verify(searchUtil, Mockito.times(2)).extractDate((HttpServletRequest) Mockito.any(), - (SearchCriteria) Mockito.any(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString()); - Mockito.verify(assetMgr).getReportLogs(searchCriteria); - Mockito.verify(searchUtil).extractCommonCriterias(request, xTrxLogService.getSortFields()); + Mockito.when(serviceREST.getServiceByName(rangerPolicyList.get(0).getService())).thenReturn(rangerService); + VXResourceList expectedVXResourceList = new VXResourceList(); + expectedVXResourceList.setVXResources(vXResourcesList); + + SearchFilter searchFilter = new SearchFilter(); + Mockito.when(searchUtil.getSearchFilterFromLegacyRequest(request, null)).thenReturn(searchFilter); + Mockito.when(serviceREST.getPolicies(searchFilter)).thenReturn(rangerPolicyList); + VXResourceList actualVXResourceList = assetREST.searchXResources(request); + Assert.assertNotNull(actualVXResourceList); + Assert.assertEquals(expectedVXResourceList.getVXResources(), actualVXResourceList.getVXResources()); + Mockito.verify(searchUtil).getSearchFilterFromLegacyRequest(request, null); + Mockito.verify(serviceREST).getPolicies(searchFilter); + for (i = 0; i < 2; i++) { + Mockito.verify(serviceUtil, Mockito.times(1)).toVXResource(rangerPolicyList.get((int) i), rangerService); } - - public Map getSampleConfig() { - Map configs = new HashMap(); - configs.put("username", "servicemgr"); - configs.put("password", "servicemgr"); - configs.put("namenode", "servicemgr"); - configs.put("hadoop.security.authorization", "No"); - configs.put("hadoop.security.authentication", "Simple"); - configs.put("hadoop.security.auth_to_local", ""); - configs.put("dfs.datanode.kerberos.principal", ""); - configs.put("dfs.namenode.kerberos.principal", ""); - configs.put("dfs.secondary.namenode.kerberos.principal", ""); - configs.put("hadoop.rpc.protection", "Privacy"); - configs.put("commonNameForCertificate", ""); - return configs; - } - + Mockito.verify(serviceREST, Mockito.times(2)).getServiceByName(rangerPolicyList.get(0).getService()); + } + + @Test + public void testCountXResource() { + List rangerPolicyList = new ArrayList<>(); + List vXResourcesList = new ArrayList<>(); + RangerService rangerService = rangerService(Id); + long i; + for (i = 1; i <= 2; i++) { + RangerPolicy rangerPolicy = rangerPolicy(i); + VXResource vXresource = vxResource(i); + rangerPolicyList.add(rangerPolicy); + vXResourcesList.add(vXresource); + Mockito.when(serviceUtil.toVXResource(rangerPolicy, rangerService)).thenReturn(vXresource); + } + VXLong expectedXResouce = new VXLong(); + expectedXResouce.setValue(2L); + Mockito.when(serviceREST.getServiceByName(rangerPolicyList.get(0).getService())).thenReturn(rangerService); + VXResourceList expectedVXResourceList = new VXResourceList(); + expectedVXResourceList.setVXResources(vXResourcesList); + + SearchFilter searchFilter = new SearchFilter(); + Mockito.when(searchUtil.getSearchFilterFromLegacyRequest(request, null)).thenReturn(searchFilter); + Mockito.when(serviceREST.getPolicies(searchFilter)).thenReturn(rangerPolicyList); + VXLong actualXResource = assetREST.countXResources(request); + Assert.assertEquals(expectedXResouce.getValue(), actualXResource.getValue()); + } + + @Test + public void testGetXCredentialStore() { + VXCredentialStore vXCredentialStore = vXCredentialStore(); + Mockito.when(assetMgr.getXCredentialStore(Id)).thenReturn(vXCredentialStore); + VXCredentialStore actualvXCredentialStore = assetREST.getXCredentialStore(Id); + Assert.assertNotNull(actualvXCredentialStore); + Assert.assertEquals(vXCredentialStore, actualvXCredentialStore); + Mockito.verify(assetMgr).getXCredentialStore(Id); + } + + @Test + public void testCreateXCredentialStore() { + VXCredentialStore vXCredentialStore = vXCredentialStore(); + Mockito.when(assetMgr.createXCredentialStore(vXCredentialStore)).thenReturn(vXCredentialStore); + VXCredentialStore actualvXCredentialStore = assetREST.createXCredentialStore(vXCredentialStore); + Assert.assertNotNull(actualvXCredentialStore); + Assert.assertEquals(vXCredentialStore, actualvXCredentialStore); + Mockito.verify(assetMgr).createXCredentialStore(vXCredentialStore); + } + + @Test + public void testUpdateXCredentialStoree() { + VXCredentialStore vXCredentialStore = vXCredentialStore(); + Mockito.when(assetMgr.updateXCredentialStore(vXCredentialStore)).thenReturn(vXCredentialStore); + VXCredentialStore actualvXCredentialStore = assetREST.updateXCredentialStore(vXCredentialStore); + Assert.assertNotNull(actualvXCredentialStore); + Assert.assertEquals(vXCredentialStore, actualvXCredentialStore); + Mockito.verify(assetMgr).updateXCredentialStore(vXCredentialStore); + } + + @Test + public void testDeleteXCredentialStore() { + Mockito.doNothing().when(assetMgr).deleteXCredentialStore(Id, false); + assetREST.deleteXCredentialStore(Id, request); + Mockito.verify(assetMgr).deleteXCredentialStore(Id, false); + } + + @Test + public void testSearchXCredentialStores() { + VXCredentialStore vXCredentialStore = vXCredentialStore(); + List vXCredentialStores = Collections.singletonList(vXCredentialStore); + VXCredentialStoreList vXCredentialStoreList = new VXCredentialStoreList(); + vXCredentialStoreList.setVXCredentialStores(vXCredentialStores); + SearchCriteria searchCriteria = new SearchCriteria(); + List sortFields = null; + Mockito.when(searchUtil.extractCommonCriterias(request, sortFields)).thenReturn(searchCriteria); + Mockito.when(assetMgr.searchXCredentialStores(searchCriteria)).thenReturn(vXCredentialStoreList); + VXCredentialStoreList actualvxCredentialStoreList = assetREST.searchXCredentialStores(request); + Assert.assertEquals(vXCredentialStoreList.getVXCredentialStores(), actualvxCredentialStoreList.getVXCredentialStores()); + Mockito.verify(assetMgr).searchXCredentialStores(searchCriteria); + } + + @Test + public void testCountXCredentialStores() { + VXLong expectedvXLong = new VXLong(); + SearchCriteria searchCriteria = new SearchCriteria(); + List sortFields = null; + Mockito.when(searchUtil.extractCommonCriterias(request, sortFields)).thenReturn(searchCriteria); + Mockito.when(assetMgr.getXCredentialStoreSearchCount(searchCriteria)).thenReturn(expectedvXLong); + VXLong actualvXLong = assetREST.countXCredentialStores(request); + Assert.assertEquals(expectedvXLong, actualvXLong); + Mockito.verify(assetMgr).getXCredentialStoreSearchCount(searchCriteria); + } + + @Test + public void testSearchXPolicyExportAudits() { + SearchCriteria searchCriteria = new SearchCriteria(); + List sortFields = null; + List vXPolicyExportAudits = new ArrayList<>(); + VXPolicyExportAuditList vXPolicyExportAuditList = new VXPolicyExportAuditList(); + vXPolicyExportAuditList.setVXPolicyExportAudits(vXPolicyExportAudits); + Mockito.when(searchUtil.extractCommonCriterias(request, sortFields)).thenReturn(searchCriteria); + Mockito.when(searchUtil.extractString(Mockito.any(), Mockito.any(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())).thenReturn("test"); + Mockito.when(searchUtil.extractInt(Mockito.any(), Mockito.any(), Mockito.anyString(), Mockito.anyString())).thenReturn(8); + Mockito.when(assetMgr.searchXPolicyExportAudits(searchCriteria)).thenReturn(vXPolicyExportAuditList); + VXPolicyExportAuditList expectedVXPolicyExportAuditList = assetREST.searchXPolicyExportAudits(request); + Assert.assertEquals(vXPolicyExportAuditList, expectedVXPolicyExportAuditList); + Mockito.verify(searchUtil).extractCommonCriterias(request, sortFields); + Mockito.verify(searchUtil, Mockito.times(5)).extractString(Mockito.any(), Mockito.any(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString()); + Mockito.verify(searchUtil).extractInt(Mockito.any(), Mockito.any(), Mockito.anyString(), Mockito.anyString()); + Mockito.verify(searchUtil, Mockito.times(2)).extractDate(Mockito.any(), Mockito.any(), Mockito.anyString(), Mockito.anyString(), Mockito.isNull()); + Mockito.verify(searchUtil).extractCommonCriterias(request, sortFields); + Mockito.verify(assetMgr).searchXPolicyExportAudits(searchCriteria); + } + + @Test + public void testGetReportLogs() { + SearchCriteria searchCriteria = new SearchCriteria(); + List sortFields = xTrxLogService.getSortFields(); + List vXTrxLogs = new ArrayList<>(); + VXTrxLogList vXTrxLogList = new VXTrxLogList(); + vXTrxLogList.setVXTrxLogs(vXTrxLogs); + Mockito.when(searchUtil.extractCommonCriterias(request, sortFields)).thenReturn(searchCriteria); + Mockito.when(searchUtil.extractString(Mockito.any(), Mockito.any(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())).thenReturn("test"); + Mockito.when(searchUtil.extractInt(Mockito.any(), Mockito.any(), Mockito.anyString(), Mockito.anyString())).thenReturn(8); + Mockito.when(searchUtil.extractDate(Mockito.any(), Mockito.any(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())).thenReturn(new Date()); + Mockito.when(assetMgr.getReportLogs(searchCriteria)).thenReturn(vXTrxLogList); + VXTrxLogList expectedVXTrxLogListt = assetREST.getReportLogs(request); + Assert.assertEquals(vXTrxLogList, expectedVXTrxLogListt); + Mockito.verify(searchUtil, Mockito.times(4)).extractString(Mockito.any(), Mockito.any(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString()); + Mockito.verify(searchUtil, Mockito.times(2)).extractInt(Mockito.any(), Mockito.any(), Mockito.anyString(), Mockito.anyString()); + Mockito.verify(searchUtil, Mockito.times(2)).extractDate(Mockito.any(), Mockito.any(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString()); + Mockito.verify(assetMgr).getReportLogs(searchCriteria); + Mockito.verify(searchUtil).extractCommonCriterias(request, sortFields); + } + + @Test + public void testGetTransactionReport() { + List vXTrxLogs = new ArrayList<>(); + VXTrxLogList vXTrxLogList = new VXTrxLogList(); + vXTrxLogList.setVXTrxLogs(vXTrxLogs); + String transactionId = "123456"; + Mockito.when(assetMgr.getTransactionReport(transactionId)).thenReturn(vXTrxLogList); + VXTrxLogList expectedVXTrxLogListt = assetREST.getTransactionReport(request, transactionId); + Assert.assertEquals(vXTrxLogList, expectedVXTrxLogListt); + Mockito.verify(assetMgr).getTransactionReport(transactionId); + } + + @Test + public void testGetAccessLogs() { + SearchCriteria searchCriteria = new SearchCriteria(); + List sortFields = null; + List vXAccessAudits = new ArrayList<>(); + VXAccessAuditList vXAccessAuditList = new VXAccessAuditList(); + vXAccessAuditList.setVXAccessAudits(vXAccessAudits); + Mockito.when(searchUtil.extractCommonCriterias(request, sortFields)).thenReturn(searchCriteria); + Mockito.when(searchUtil.extractString(Mockito.any(), Mockito.any(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())).thenReturn("test"); + Mockito.when(searchUtil.extractInt(Mockito.any(), Mockito.any(), Mockito.anyString(), Mockito.anyString())).thenReturn(8); + Mockito.when(searchUtil.extractDate(Mockito.any(), Mockito.any(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())).thenReturn(new Date()); + Mockito.when(searchUtil.extractLong(Mockito.any(), Mockito.any(), Mockito.anyString(), Mockito.anyString())).thenReturn(8L); + Mockito.when(msBizUtil.isKeyAdmin()).thenReturn(false); + Mockito.when(daoManager.getXXServiceDef()).thenReturn(xxServiceDefDao); + XXServiceDef xServiceDef = new XXServiceDef(); + xServiceDef.setId(Id); + Mockito.when(xxServiceDefDao.findByName(EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_KMS_NAME)).thenReturn(xServiceDef); + Mockito.when(assetMgr.getAccessLogs(searchCriteria)).thenReturn(vXAccessAuditList); + VXAccessAuditList expectedVXAccessAuditList = assetREST.getAccessLogs(request, null); + Assert.assertEquals(vXAccessAuditList, expectedVXAccessAuditList); + Mockito.verify(msBizUtil).isKeyAdmin(); + Mockito.verify(assetMgr).getAccessLogs(searchCriteria); + Mockito.verify(daoManager).getXXServiceDef(); + Mockito.verify(searchUtil, Mockito.times(14)).extractString(Mockito.any(), Mockito.any(), Mockito.anyString(), Mockito.anyString(), Mockito.nullable(String.class)); + Mockito.verify(searchUtil, Mockito.times(4)).extractInt(Mockito.any(), Mockito.any(), Mockito.anyString(), Mockito.anyString()); + Mockito.verify(searchUtil, Mockito.times(2)).extractDate(Mockito.any(), Mockito.any(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString()); + Mockito.verify(searchUtil).extractLong(Mockito.any(), Mockito.any(), Mockito.anyString(), Mockito.anyString()); + Mockito.verify(searchUtil).extractStringList(Mockito.any(HttpServletRequest.class), (SearchCriteria) Mockito.any(), Mockito.eq("requestUser"), Mockito.eq("Users"), Mockito.eq("requestUser"), Mockito.any(), Mockito.eq(StringUtil.VALIDATION_TEXT)); + Mockito.verify(searchUtil).extractStringList(Mockito.any(HttpServletRequest.class), (SearchCriteria) Mockito.any(), Mockito.eq("excludeUser"), Mockito.eq("Exclude Users"), Mockito.eq("-requestUser"), Mockito.any(), Mockito.eq(StringUtil.VALIDATION_TEXT)); + Mockito.verify(searchUtil).extractStringList(Mockito.any(HttpServletRequest.class), (SearchCriteria) Mockito.any(), Mockito.eq("zoneName"), Mockito.eq("Zone Name List"), Mockito.eq("zoneName"), Mockito.eq(null), Mockito.eq(null)); + Mockito.verify(searchUtil).extractCommonCriterias(Mockito.any(HttpServletRequest.class), Mockito.any()); + Mockito.verifyNoMoreInteractions(searchUtil, assetMgr, daoManager); + } + + @Test + public void testGetAccessLogsForKms() { + SearchCriteria searchCriteria = new SearchCriteria(); + List sortFields = null; + List vXAccessAudits = new ArrayList<>(); + VXAccessAuditList vXAccessAuditList = new VXAccessAuditList(); + vXAccessAuditList.setVXAccessAudits(vXAccessAudits); + Mockito.when(searchUtil.extractCommonCriterias(request, sortFields)).thenReturn(searchCriteria); + Mockito.when(searchUtil.extractString(Mockito.any(), Mockito.any(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())).thenReturn("test"); + Mockito.when(searchUtil.extractInt(Mockito.any(), Mockito.any(), Mockito.anyString(), Mockito.anyString())).thenReturn(8); + Mockito.when(searchUtil.extractDate(Mockito.any(), Mockito.any(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())).thenReturn(new Date()); + Mockito.when(searchUtil.extractLong(Mockito.any(), Mockito.any(), Mockito.anyString(), Mockito.anyString())).thenReturn(8L); + Mockito.when(searchUtil.extractLong(Mockito.any(), Mockito.any(), Mockito.anyString(), Mockito.anyString())).thenReturn(8L); + Mockito.when(msBizUtil.isKeyAdmin()).thenReturn(true); + Mockito.when(daoManager.getXXServiceDef()).thenReturn(xxServiceDefDao); + XXServiceDef xServiceDef = new XXServiceDef(); + xServiceDef.setId(Id); + Mockito.when(xxServiceDefDao.findByName(EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_KMS_NAME)).thenReturn(xServiceDef); + Mockito.when(assetMgr.getAccessLogs(searchCriteria)).thenReturn(vXAccessAuditList); + VXAccessAuditList expectedVXAccessAuditList = assetREST.getAccessLogs(request, null); + Assert.assertEquals(vXAccessAuditList, expectedVXAccessAuditList); + Mockito.verify(msBizUtil).isKeyAdmin(); + Mockito.verify(assetMgr).getAccessLogs(searchCriteria); + Mockito.verify(daoManager).getXXServiceDef(); + Mockito.verify(searchUtil, Mockito.times(14)).extractString(Mockito.any(), Mockito.any(), Mockito.anyString(), Mockito.anyString(), Mockito.nullable(String.class)); + Mockito.verify(searchUtil, Mockito.times(4)).extractInt(Mockito.any(), Mockito.any(), Mockito.anyString(), Mockito.anyString()); + Mockito.verify(searchUtil, Mockito.times(2)).extractDate(Mockito.any(), Mockito.any(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString()); + Mockito.verify(searchUtil).extractLong(Mockito.any(), Mockito.any(), Mockito.anyString(), Mockito.anyString()); + Mockito.verify(searchUtil).extractStringList(Mockito.any(HttpServletRequest.class), (SearchCriteria) Mockito.any(), Mockito.eq("requestUser"), Mockito.eq("Users"), Mockito.eq("requestUser"), Mockito.any(), Mockito.eq(StringUtil.VALIDATION_TEXT)); + Mockito.verify(searchUtil).extractStringList(Mockito.any(HttpServletRequest.class), (SearchCriteria) Mockito.any(), Mockito.eq("excludeUser"), Mockito.eq("Exclude Users"), Mockito.eq("-requestUser"), Mockito.any(), Mockito.eq(StringUtil.VALIDATION_TEXT)); + Mockito.verify(searchUtil).extractStringList(Mockito.any(HttpServletRequest.class), (SearchCriteria) Mockito.any(), Mockito.eq("zoneName"), Mockito.eq("Zone Name List"), Mockito.eq("zoneName"), Mockito.eq(null), Mockito.eq(null)); + Mockito.verify(searchUtil).extractCommonCriterias(Mockito.any(HttpServletRequest.class), Mockito.any()); + Mockito.verifyNoMoreInteractions(searchUtil, assetMgr, daoManager); + } + + @Test + public void testGrantPermission() { + RangerPolicy policy = rangerPolicy(Id); + RangerService service = rangerService(Id); + VXPolicy vXPolicy = vXPolicy(policy, service); + GrantRevokeRequest grantRequestObj = new GrantRevokeRequest(); + grantRequestObj.setAccessTypes(null); + grantRequestObj.setDelegateAdmin(true); + grantRequestObj.setEnableAudit(true); + grantRequestObj.setGrantor("read"); + grantRequestObj.setIsRecursive(true); + RESTResponse response = Mockito.mock(RESTResponse.class); + Mockito.when(serviceUtil.toGrantRevokeRequest(vXPolicy)).thenReturn(grantRequestObj); + try { + Mockito.when(serviceREST.grantAccess(vXPolicy.getRepositoryName(), grantRequestObj, request)).thenReturn(response); + } catch (Exception e) { + fail("test failed due to: " + e.getMessage()); + } + VXPolicy expectedVXPolicy = assetREST.grantPermission(request, vXPolicy); + Assert.assertEquals(vXPolicy, expectedVXPolicy); + Mockito.verify(serviceUtil).toGrantRevokeRequest(vXPolicy); + try { + Mockito.verify(serviceREST).grantAccess(vXPolicy.getRepositoryName(), grantRequestObj, request); + } catch (Exception e) { + fail("test failed due to: " + e.getMessage()); + } + } + + @Test + public void testGrantPermissionWebApplicationException() { + RangerPolicy policy = rangerPolicy(Id); + RangerService service = rangerService(Id); + VXPolicy vXPolicy = vXPolicy(policy, service); + GrantRevokeRequest grantRequestObj = new GrantRevokeRequest(); + grantRequestObj.setAccessTypes(null); + grantRequestObj.setDelegateAdmin(true); + grantRequestObj.setEnableAudit(true); + grantRequestObj.setGrantor("read"); + grantRequestObj.setIsRecursive(true); + WebApplicationException webApplicationException = new WebApplicationException(); + Mockito.when(serviceUtil.toGrantRevokeRequest(vXPolicy)).thenReturn(grantRequestObj); + try { + Mockito.when(serviceREST.grantAccess(vXPolicy.getRepositoryName(), grantRequestObj, request)) + .thenThrow(webApplicationException); + } catch (Exception e) { + fail("test failed due to: " + e.getMessage()); + } + try { + assetREST.grantPermission(request, vXPolicy); + fail("Exception not thrown"); + } catch (WebApplicationException e) { + Assert.assertTrue(true); + } + Mockito.verify(serviceUtil).toGrantRevokeRequest(vXPolicy); + try { + Mockito.verify(serviceREST).grantAccess(vXPolicy.getRepositoryName(), grantRequestObj, request); + } catch (Exception e) { + fail("test failed due to: " + e.getMessage()); + } + } + + @Test + public void testRevokePermission() { + RangerPolicy policy = rangerPolicy(Id); + RangerService service = rangerService(Id); + VXPolicy vXPolicy = vXPolicy(policy, service); + GrantRevokeRequest grantRequestObj = new GrantRevokeRequest(); + grantRequestObj.setAccessTypes(null); + grantRequestObj.setDelegateAdmin(true); + grantRequestObj.setEnableAudit(true); + grantRequestObj.setGrantor("read"); + grantRequestObj.setIsRecursive(true); + RESTResponse response = Mockito.mock(RESTResponse.class); + Mockito.when(serviceUtil.toGrantRevokeRequest(vXPolicy)).thenReturn(grantRequestObj); + try { + Mockito.when(serviceREST.revokeAccess(vXPolicy.getRepositoryName(), grantRequestObj, request)) + .thenReturn(response); + } catch (Exception e) { + fail("test failed due to: " + e.getMessage()); + } + VXPolicy expectedVXPolicy = assetREST.revokePermission(request, vXPolicy); + Assert.assertEquals(vXPolicy, expectedVXPolicy); + Mockito.verify(serviceUtil).toGrantRevokeRequest(vXPolicy); + try { + Mockito.verify(serviceREST).revokeAccess(vXPolicy.getRepositoryName(), grantRequestObj, request); + } catch (Exception e) { + fail("test failed due to: " + e.getMessage()); + } + } + + @Test + public void testRevokePermissionWebApplicationException() { + RangerPolicy policy = rangerPolicy(Id); + RangerService service = rangerService(Id); + VXPolicy vXPolicy = vXPolicy(policy, service); + GrantRevokeRequest grantRequestObj = new GrantRevokeRequest(); + grantRequestObj.setAccessTypes(null); + grantRequestObj.setDelegateAdmin(true); + grantRequestObj.setEnableAudit(true); + grantRequestObj.setGrantor("read"); + grantRequestObj.setIsRecursive(true); + WebApplicationException webApplicationException = new WebApplicationException(); + Mockito.when(serviceUtil.toGrantRevokeRequest(vXPolicy)).thenReturn(grantRequestObj); + try { + Mockito.when(serviceREST.revokeAccess(vXPolicy.getRepositoryName(), grantRequestObj, request)) + .thenThrow(webApplicationException); + } catch (Exception e) { + fail("test failed due to: " + e.getMessage()); + } + try { + assetREST.revokePermission(request, vXPolicy); + fail("Exception not thrown"); + } catch (WebApplicationException e) { + Assert.assertTrue(true); + } + Mockito.verify(serviceUtil).toGrantRevokeRequest(vXPolicy); + try { + Mockito.verify(serviceREST).revokeAccess(vXPolicy.getRepositoryName(), grantRequestObj, request); + } catch (Exception e) { + fail("test failed due to: " + e.getMessage()); + } + } + + @Test + public void testGetReportLogsForAuditAdmin() { + SearchCriteria searchCriteria = new SearchCriteria(); + List vXTrxLogs = new ArrayList<>(); + VXTrxLogList vXTrxLogList = new VXTrxLogList(); + vXTrxLogList.setVXTrxLogs(vXTrxLogs); + Mockito.when(searchUtil.extractCommonCriterias(request, xTrxLogService.getSortFields())).thenReturn(searchCriteria); + Mockito.when(searchUtil.extractString(Mockito.any(), Mockito.any(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())).thenReturn("test"); + Mockito.when(searchUtil.extractInt(Mockito.any(), Mockito.any(), Mockito.anyString(), Mockito.anyString())).thenReturn(8); + Mockito.when(searchUtil.extractDate(Mockito.any(), Mockito.any(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())).thenReturn(new Date()); + Mockito.when(assetMgr.getReportLogs(searchCriteria)).thenReturn(vXTrxLogList); + VXTrxLogList expectedVXTrxLogListt = assetREST.getReportLogs(request); + Assert.assertEquals(vXTrxLogList, expectedVXTrxLogListt); + Mockito.verify(searchUtil, Mockito.times(4)).extractString(Mockito.any(), Mockito.any(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString()); + Mockito.verify(searchUtil, Mockito.times(2)).extractInt(Mockito.any(), Mockito.any(), Mockito.anyString(), Mockito.anyString()); + Mockito.verify(searchUtil, Mockito.times(2)).extractDate(Mockito.any(), Mockito.any(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString()); + Mockito.verify(assetMgr).getReportLogs(searchCriteria); + Mockito.verify(searchUtil).extractCommonCriterias(request, xTrxLogService.getSortFields()); + } + + @Test + public void testGetReportLogsForAuditKeyAdmin() { + SearchCriteria searchCriteria = new SearchCriteria(); + List vXTrxLogs = new ArrayList<>(); + VXTrxLogList vXTrxLogList = new VXTrxLogList(); + vXTrxLogList.setVXTrxLogs(vXTrxLogs); + Mockito.when(searchUtil.extractCommonCriterias(request, xTrxLogService.getSortFields())).thenReturn(searchCriteria); + Mockito.when(searchUtil.extractString(Mockito.any(), Mockito.any(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())).thenReturn("test"); + Mockito.when(searchUtil.extractInt(Mockito.any(), Mockito.any(), Mockito.anyString(), Mockito.anyString())).thenReturn(8); + Mockito.when(searchUtil.extractDate(Mockito.any(), Mockito.any(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())).thenReturn(new Date()); + Mockito.when(assetMgr.getReportLogs(searchCriteria)).thenReturn(vXTrxLogList); + VXTrxLogList expectedVXTrxLogListt = assetREST.getReportLogs(request); + Assert.assertEquals(vXTrxLogList, expectedVXTrxLogListt); + Mockito.verify(searchUtil, Mockito.times(4)).extractString(Mockito.any(), Mockito.any(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString()); + Mockito.verify(searchUtil, Mockito.times(2)).extractInt(Mockito.any(), Mockito.any(), Mockito.anyString(), Mockito.anyString()); + Mockito.verify(searchUtil, Mockito.times(2)).extractDate(Mockito.any(), Mockito.any(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString()); + Mockito.verify(assetMgr).getReportLogs(searchCriteria); + Mockito.verify(searchUtil).extractCommonCriterias(request, xTrxLogService.getSortFields()); + } + + public Map getSampleConfig() { + Map configs = new HashMap<>(); + configs.put("username", "servicemgr"); + configs.put("password", "servicemgr"); + configs.put("namenode", "servicemgr"); + configs.put("hadoop.security.authorization", "No"); + configs.put("hadoop.security.authentication", "Simple"); + configs.put("hadoop.security.auth_to_local", ""); + configs.put("dfs.datanode.kerberos.principal", ""); + configs.put("dfs.namenode.kerberos.principal", ""); + configs.put("dfs.secondary.namenode.kerberos.principal", ""); + configs.put("hadoop.rpc.protection", "Privacy"); + configs.put("commonNameForCertificate", ""); + return configs; + } + + private VXCredentialStore vXCredentialStore() { + VXCredentialStore vXCredentialStore = new VXCredentialStore(); + vXCredentialStore.setId(Id); + vXCredentialStore.setName("TestAssetRest"); + vXCredentialStore.setDescription("TestAssetRest"); + vXCredentialStore.setOwner("owner"); + return vXCredentialStore; + } + + private RangerService rangerService(Long id) { + RangerService rangerService = new RangerService(); + rangerService.setId(id); + rangerService.setConfigs(getSampleConfig()); + rangerService.setCreateTime(new Date()); + rangerService.setDescription("service policy"); + rangerService.setGuid("1427365526516_835_0"); + rangerService.setIsEnabled(true); + rangerService.setName("HDFS_1"); + rangerService.setPolicyUpdateTime(new Date()); + rangerService.setType("1"); + rangerService.setUpdatedBy("Admin"); + rangerService.setUpdateTime(new Date()); + + return rangerService; + } + + private VXAsset vXAsset(Long id) { + Map configs = new HashMap<>(); + configs.put("username", "servicemgr"); + configs.put("password", "servicemgr"); + configs.put("namenode", "servicemgr"); + configs.put("hadoop.security.authorization", "No"); + configs.put("hadoop.security.authentication", "Simple"); + configs.put("hadoop.security.auth_to_local", ""); + configs.put("dfs.datanode.kerberos.principal", ""); + configs.put("dfs.namenode.kerberos.principal", ""); + configs.put("dfs.secondary.namenode.kerberos.principal", ""); + configs.put("hadoop.rpc.protection", "Privacy"); + configs.put("commonNameForCertificate", ""); + + VXAsset vXAsset = new VXAsset(); + vXAsset.setId(id); + vXAsset.setActiveStatus(1); + vXAsset.setAssetType(1); + vXAsset.setDescription("service policy"); + vXAsset.setSupportNative(false); + vXAsset.setName("HDFS_1"); + vXAsset.setUpdatedBy("Admin"); + vXAsset.setConfig(getSampleConfig().toString()); + return vXAsset; + } + + private VXResource vxResource(Long id) { + VXResource vXResource = new VXResource(); + vXResource.setName("HDFS_1-1-20150316062453"); + vXResource.setId(id); + vXResource.setAssetId(id); + return vXResource; + } + + private RangerPolicy rangerPolicy(Long id) { + List accesses = new ArrayList<>(); + List users = new ArrayList<>(); + List groups = new ArrayList<>(); + List conditions = new ArrayList<>(); + List policyItems = new ArrayList<>(); + RangerPolicyItem rangerPolicyItem = new RangerPolicyItem(); + rangerPolicyItem.setAccesses(accesses); + rangerPolicyItem.setConditions(conditions); + rangerPolicyItem.setGroups(groups); + rangerPolicyItem.setUsers(users); + rangerPolicyItem.setDelegateAdmin(false); + + policyItems.add(rangerPolicyItem); + + Map policyResource = new HashMap<>(); + RangerPolicyResource rangerPolicyResource = new RangerPolicyResource(); + rangerPolicyResource.setIsExcludes(true); + rangerPolicyResource.setIsRecursive(true); + rangerPolicyResource.setValue("1"); + rangerPolicyResource.setValues(users); + policyResource.put("resource", rangerPolicyResource); + RangerPolicy policy = new RangerPolicy(); + policy.setId(id); + policy.setCreateTime(new Date()); + policy.setDescription("policy"); + policy.setGuid("policyguid"); + policy.setIsEnabled(true); + policy.setName("HDFS_1-1-20150316062453"); + policy.setUpdatedBy("Admin"); + policy.setUpdateTime(new Date()); + policy.setService("HDFS_1-1-20150316062453"); + policy.setIsAuditEnabled(true); + policy.setPolicyItems(policyItems); + policy.setResources(policyResource); + policy.setService("HDFS_1"); + + return policy; + } + + private VXPolicy vXPolicy(RangerPolicy policy, RangerService service) { + VXPolicy ret = new VXPolicy(); + ret.setPolicyName(StringUtils.trim(policy.getName())); + ret.setDescription(policy.getDescription()); + ret.setRepositoryName(policy.getService()); + ret.setIsEnabled(policy.getIsEnabled()); + ret.setRepositoryType(service.getType()); + ret.setIsAuditEnabled(policy.getIsAuditEnabled()); + return ret; + } } diff --git a/security-admin/src/test/java/org/apache/ranger/rest/TestGdsREST.java b/security-admin/src/test/java/org/apache/ranger/rest/TestGdsREST.java index cdfce50b93..68d62fc31a 100644 --- a/security-admin/src/test/java/org/apache/ranger/rest/TestGdsREST.java +++ b/security-admin/src/test/java/org/apache/ranger/rest/TestGdsREST.java @@ -15,12 +15,12 @@ * limitations under the License. */ package org.apache.ranger.rest; + import org.apache.ranger.common.RangerSearchUtil; import org.apache.ranger.plugin.model.RangerGds; import org.apache.ranger.plugin.model.RangerGrant; import org.apache.ranger.plugin.model.RangerPolicy; import org.apache.ranger.plugin.model.RangerPrincipal; - import org.junit.FixMethodOrder; import org.junit.Test; import org.junit.runner.RunWith; @@ -31,223 +31,216 @@ import org.mockito.junit.MockitoJUnitRunner; import javax.servlet.http.HttpServletRequest; -import java.util.Arrays; + import java.util.ArrayList; +import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Random; import java.util.UUID; - - -import static org.junit.Assert.*; -import static org.mockito.Mockito.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.when; @RunWith(MockitoJUnitRunner.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class TestGdsREST { + private final HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + @Mock + RangerSearchUtil searchUtil; + @InjectMocks + private GdsREST gdsREST = new GdsREST(); - @InjectMocks - private GdsREST gdsREST = new GdsREST(); - - @Mock - RangerSearchUtil searchUtil; - - private final HttpServletRequest request = Mockito.mock(HttpServletRequest.class);; - - @Test - public void testAddDataSetGrants() throws Exception { - - RangerGds.RangerDataset rangerDataset = createRangerDataSet(); - RangerPolicy policy = createPolicyForDataSet(rangerDataset); - - List policyItems = new ArrayList<>(policy.getPolicyItems()); - List rangerGrants = createAndGetSampleGrantData(); + @Test + public void testAddDataSetGrants() { + RangerGds.RangerDataset rangerDataset = createRangerDataSet(); + RangerPolicy policy = createPolicyForDataSet(rangerDataset); - policy = gdsREST.updatePolicyWithModifiedGrants(policy, rangerGrants); + List policyItems = new ArrayList<>(policy.getPolicyItems()); + List rangerGrants = createAndGetSampleGrantData(); - List updatedPolicyItems = policy.getPolicyItems(); + policy = gdsREST.updatePolicyWithModifiedGrants(policy, rangerGrants); - assertNotEquals(policyItems, updatedPolicyItems); + List updatedPolicyItems = policy.getPolicyItems(); - assertEquals(policyItems.size() + rangerGrants.size(), updatedPolicyItems.size()); + assertNotEquals(policyItems, updatedPolicyItems); - List filteredPolicyItems = new ArrayList<>(gdsREST.filterPolicyItemsByRequest(policy, request)); - assertEquals(filteredPolicyItems, updatedPolicyItems); - } + assertEquals(policyItems.size() + rangerGrants.size(), updatedPolicyItems.size()); - @Test - public void testUpdateDataSetGrants() throws Exception { - RangerGds.RangerDataset rangerDataset = createRangerDataSet(); - RangerPolicy policy = createPolicyForDataSet(rangerDataset); + List filteredPolicyItems = new ArrayList<>(gdsREST.filterPolicyItemsByRequest(policy, request)); + assertEquals(filteredPolicyItems, updatedPolicyItems); + } - List rangerGrants = createAndGetSampleGrantData(); - policy = gdsREST.updatePolicyWithModifiedGrants(policy, rangerGrants); + @Test + public void testUpdateDataSetGrants() { + RangerGds.RangerDataset rangerDataset = createRangerDataSet(); + RangerPolicy policy = createPolicyForDataSet(rangerDataset); - String[] requestedPrincipals = {"group:hdfs"}; - when(searchUtil.getParamMultiValues(request, "principal")).thenReturn(requestedPrincipals); + List rangerGrants = createAndGetSampleGrantData(); + policy = gdsREST.updatePolicyWithModifiedGrants(policy, rangerGrants); - List hdfsPolicyItems = new ArrayList<>(gdsREST.filterPolicyItemsByRequest(policy, request)); + String[] requestedPrincipals = {"group:hdfs"}; + when(searchUtil.getParamMultiValues(request, "principal")).thenReturn(requestedPrincipals); - RangerGrant grant3 = new RangerGrant(new RangerPrincipal(RangerPrincipal.PrincipalType.GROUP, "hdfs"), - Arrays.asList("_READ"), Collections.emptyList()); - policy = gdsREST.updatePolicyWithModifiedGrants(policy, Arrays.asList(grant3)); + List hdfsPolicyItems = new ArrayList<>(gdsREST.filterPolicyItemsByRequest(policy, request)); - List updatedHdfsPolicyItems = new ArrayList<>(gdsREST.filterPolicyItemsByRequest(policy, request)); + RangerGrant grant3 = new RangerGrant(new RangerPrincipal(RangerPrincipal.PrincipalType.GROUP, "hdfs"), Collections.singletonList("_READ"), Collections.emptyList()); + policy = gdsREST.updatePolicyWithModifiedGrants(policy, Collections.singletonList(grant3)); - assertNotNull(updatedHdfsPolicyItems); - assertEquals(hdfsPolicyItems.size(), updatedHdfsPolicyItems.size()); - assertNotEquals(hdfsPolicyItems, updatedHdfsPolicyItems); - } + List updatedHdfsPolicyItems = new ArrayList<>(gdsREST.filterPolicyItemsByRequest(policy, request)); - @Test - public void testRemoveDataSetGrants() throws Exception { - RangerGds.RangerDataset rangerDataset = createRangerDataSet(); - RangerPolicy policy = createPolicyForDataSet(rangerDataset); - List rangerGrants = createAndGetSampleGrantData(); + assertNotNull(updatedHdfsPolicyItems); + assertEquals(hdfsPolicyItems.size(), updatedHdfsPolicyItems.size()); + assertNotEquals(hdfsPolicyItems, updatedHdfsPolicyItems); + } - policy = gdsREST.updatePolicyWithModifiedGrants(policy, rangerGrants); - List newPolicyItems = policy.getPolicyItems(); + @Test + public void testRemoveDataSetGrants() { + RangerGds.RangerDataset rangerDataset = createRangerDataSet(); + RangerPolicy policy = createPolicyForDataSet(rangerDataset); + List rangerGrants = createAndGetSampleGrantData(); + policy = gdsREST.updatePolicyWithModifiedGrants(policy, rangerGrants); + List newPolicyItems = policy.getPolicyItems(); - String[] requestedPrincipals = {"group:hdfs"}; - when(searchUtil.getParamMultiValues(request, "principal")).thenReturn(requestedPrincipals); + String[] requestedPrincipals = {"group:hdfs"}; + when(searchUtil.getParamMultiValues(request, "principal")).thenReturn(requestedPrincipals); - List existingHdfsPolicyItems = new ArrayList<>(gdsREST.filterPolicyItemsByRequest(policy, request)); + List existingHdfsPolicyItems = new ArrayList<>(gdsREST.filterPolicyItemsByRequest(policy, request)); - RangerGrant grant4 = new RangerGrant(new RangerPrincipal(RangerPrincipal.PrincipalType.GROUP, "hdfs"), - Collections.emptyList(), Collections.emptyList()); - policy = gdsREST.updatePolicyWithModifiedGrants(policy, Arrays.asList(grant4)); + RangerGrant grant4 = new RangerGrant(new RangerPrincipal(RangerPrincipal.PrincipalType.GROUP, "hdfs"), Collections.emptyList(), Collections.emptyList()); + policy = gdsREST.updatePolicyWithModifiedGrants(policy, Collections.singletonList(grant4)); - List updatedHdfsPolicyItems = gdsREST.filterPolicyItemsByRequest(policy, request); + List updatedHdfsPolicyItems = gdsREST.filterPolicyItemsByRequest(policy, request); - assertNotEquals(existingHdfsPolicyItems, updatedHdfsPolicyItems); - assertTrue( "Grants for "+ Arrays.toString(requestedPrincipals) +" should be empty", updatedHdfsPolicyItems.isEmpty()); - } + assertNotEquals(existingHdfsPolicyItems, updatedHdfsPolicyItems); + assertTrue("Grants for " + Arrays.toString(requestedPrincipals) + " should be empty", updatedHdfsPolicyItems.isEmpty()); + } - @Test - public void testGetAllDataSetGrants() { - RangerGds.RangerDataset rangerDataset = createRangerDataSet(); - RangerPolicy policy = createPolicyForDataSet(rangerDataset); - List rangerGrants = createAndGetSampleGrantData(); + @Test + public void testGetAllDataSetGrants() { + RangerGds.RangerDataset rangerDataset = createRangerDataSet(); + RangerPolicy policy = createPolicyForDataSet(rangerDataset); + List rangerGrants = createAndGetSampleGrantData(); - policy = gdsREST.updatePolicyWithModifiedGrants(policy, rangerGrants); + policy = gdsREST.updatePolicyWithModifiedGrants(policy, rangerGrants); - List policyItems = new ArrayList<>(gdsREST.filterPolicyItemsByRequest(policy, request)); - List policyItemsAsGrants = gdsREST.transformPolicyItemsToGrants(policyItems); + List policyItems = new ArrayList<>(gdsREST.filterPolicyItemsByRequest(policy, request)); + List policyItemsAsGrants = gdsREST.transformPolicyItemsToGrants(policyItems); - assertEquals(rangerGrants, policyItemsAsGrants); - } + assertEquals(rangerGrants, policyItemsAsGrants); + } - @Test - public void testGetDataSetGrantsByPrincipal() throws Exception { - RangerGds.RangerDataset rangerDataset = createRangerDataSet(); - RangerPolicy policy = createPolicyForDataSet(rangerDataset); - List rangerGrants = createAndGetSampleGrantData(); + @Test + public void testGetDataSetGrantsByPrincipal() { + RangerGds.RangerDataset rangerDataset = createRangerDataSet(); + RangerPolicy policy = createPolicyForDataSet(rangerDataset); + List rangerGrants = createAndGetSampleGrantData(); - policy = gdsREST.updatePolicyWithModifiedGrants(policy, rangerGrants); + policy = gdsREST.updatePolicyWithModifiedGrants(policy, rangerGrants); - String[] existingRequestedPrincipals = {"user:hive"}; - when(searchUtil.getParamMultiValues(request, "principal")).thenReturn(existingRequestedPrincipals); + String[] existingRequestedPrincipals = {"user:hive"}; + when(searchUtil.getParamMultiValues(request, "principal")).thenReturn(existingRequestedPrincipals); - List filteredPolicyItemsByPrincipal = new ArrayList<>(gdsREST.filterPolicyItemsByRequest(policy, request)); + List filteredPolicyItemsByPrincipal = new ArrayList<>(gdsREST.filterPolicyItemsByRequest(policy, request)); - assertTrue(filteredPolicyItemsByPrincipal.size() == 1); - assertTrue(filteredPolicyItemsByPrincipal.get(0).getUsers().contains("hive")); + assertEquals(1, filteredPolicyItemsByPrincipal.size()); + assertTrue(filteredPolicyItemsByPrincipal.get(0).getUsers().contains("hive")); - String[] nonexistentRequestedPrincipals = {"user:hadoop"}; - when(searchUtil.getParamMultiValues(request, "principal")).thenReturn(nonexistentRequestedPrincipals); + String[] nonexistentRequestedPrincipals = {"user:hadoop"}; + when(searchUtil.getParamMultiValues(request, "principal")).thenReturn(nonexistentRequestedPrincipals); - filteredPolicyItemsByPrincipal = new ArrayList<>(gdsREST.filterPolicyItemsByRequest(policy, request)); - assertTrue("Grants for Principals: "+ Arrays.toString(nonexistentRequestedPrincipals) +" should be empty", filteredPolicyItemsByPrincipal.size() == 0); - } + filteredPolicyItemsByPrincipal = new ArrayList<>(gdsREST.filterPolicyItemsByRequest(policy, request)); + assertEquals("Grants for Principals: " + Arrays.toString(nonexistentRequestedPrincipals) + " should be empty", 0, filteredPolicyItemsByPrincipal.size()); + } - @Test - public void testGetDataSetGrantsByAccessType() throws Exception { - RangerGds.RangerDataset rangerDataset = createRangerDataSet(); - RangerPolicy policy = createPolicyForDataSet(rangerDataset); - List rangerGrants = createAndGetSampleGrantData(); + @Test + public void testGetDataSetGrantsByAccessType() { + RangerGds.RangerDataset rangerDataset = createRangerDataSet(); + RangerPolicy policy = createPolicyForDataSet(rangerDataset); + List rangerGrants = createAndGetSampleGrantData(); - policy = gdsREST.updatePolicyWithModifiedGrants(policy, rangerGrants); + policy = gdsREST.updatePolicyWithModifiedGrants(policy, rangerGrants); - String[] requestedAccessTypes = {"_MANAGE"}; - when(searchUtil.getParamMultiValues(request, "accessType")).thenReturn(requestedAccessTypes); + String[] requestedAccessTypes = {"_MANAGE"}; + when(searchUtil.getParamMultiValues(request, "accessType")).thenReturn(requestedAccessTypes); - List policyItemsByAccessType = new ArrayList<>(gdsREST.filterPolicyItemsByRequest(policy, request)); + List policyItemsByAccessType = new ArrayList<>(gdsREST.filterPolicyItemsByRequest(policy, request)); - assertTrue(policyItemsByAccessType.size() == 1); - assertTrue(policyItemsByAccessType.get(0).getAccesses().stream().anyMatch(x -> Arrays.asList(requestedAccessTypes).contains(x.getType()))); + assertEquals(1, policyItemsByAccessType.size()); + assertTrue(policyItemsByAccessType.get(0).getAccesses().stream().anyMatch(x -> Arrays.asList(requestedAccessTypes).contains(x.getType()))); - String[] nonexistentRequestedAccessTypes = {"_DELETE"}; - when(searchUtil.getParamMultiValues(request, "accessType")).thenReturn(nonexistentRequestedAccessTypes); + String[] nonexistentRequestedAccessTypes = {"_DELETE"}; + when(searchUtil.getParamMultiValues(request, "accessType")).thenReturn(nonexistentRequestedAccessTypes); - List updatedPolicyItemsByAccessType = new ArrayList<>(gdsREST.filterPolicyItemsByRequest(policy, request)); - assertTrue( "Grants for AccessTypes: "+ Arrays.toString(nonexistentRequestedAccessTypes) +" should be empty", updatedPolicyItemsByAccessType.isEmpty()); - } + List updatedPolicyItemsByAccessType = new ArrayList<>(gdsREST.filterPolicyItemsByRequest(policy, request)); + assertTrue("Grants for AccessTypes: " + Arrays.toString(nonexistentRequestedAccessTypes) + " should be empty", updatedPolicyItemsByAccessType.isEmpty()); + } - @Test - public void testGetDataSetGrantsByPrincipalAndAccessType() throws Exception { - RangerGds.RangerDataset rangerDataset = createRangerDataSet(); - RangerPolicy policy = createPolicyForDataSet(rangerDataset); - List rangerGrants = createAndGetSampleGrantData(); + @Test + public void testGetDataSetGrantsByPrincipalAndAccessType() { + RangerGds.RangerDataset rangerDataset = createRangerDataSet(); + RangerPolicy policy = createPolicyForDataSet(rangerDataset); + List rangerGrants = createAndGetSampleGrantData(); - policy = gdsREST.updatePolicyWithModifiedGrants(policy, rangerGrants); + policy = gdsREST.updatePolicyWithModifiedGrants(policy, rangerGrants); - String[] requestedPrincipals = {"user:hive"}; - String[] requestedAccessTypes = {"_READ"}; + String[] requestedPrincipals = {"user:hive"}; + String[] requestedAccessTypes = {"_READ"}; - when(searchUtil.getParamMultiValues(request, "principal")).thenReturn(requestedPrincipals); - when(searchUtil.getParamMultiValues(request, "accessType")).thenReturn(requestedAccessTypes); + when(searchUtil.getParamMultiValues(request, "principal")).thenReturn(requestedPrincipals); + when(searchUtil.getParamMultiValues(request, "accessType")).thenReturn(requestedAccessTypes); - List filteredPolicyItems = new ArrayList<>(gdsREST.filterPolicyItemsByRequest(policy, request)); + List filteredPolicyItems = new ArrayList<>(gdsREST.filterPolicyItemsByRequest(policy, request)); - assertTrue("Grants for Principals: "+ Arrays.toString(requestedPrincipals) + " and AccessTypes: "+ Arrays.toString(requestedAccessTypes) +" should exist", filteredPolicyItems.size() == 1); - assertTrue("Grants for Principals: "+ Arrays.toString(requestedPrincipals) + "should exist", filteredPolicyItems.get(0).getUsers().contains("hive")); - assertTrue("Grants for AccessTypes: "+ Arrays.toString(requestedAccessTypes) + "should exist", filteredPolicyItems.get(0).getAccesses().stream().anyMatch(x -> Arrays.asList(requestedAccessTypes).contains(x.getType()))); + assertEquals("Grants for Principals: " + Arrays.toString(requestedPrincipals) + " and AccessTypes: " + Arrays.toString(requestedAccessTypes) + " should exist", 1, filteredPolicyItems.size()); + assertTrue("Grants for Principals: " + Arrays.toString(requestedPrincipals) + "should exist", filteredPolicyItems.get(0).getUsers().contains("hive")); + assertTrue("Grants for AccessTypes: " + Arrays.toString(requestedAccessTypes) + "should exist", filteredPolicyItems.get(0).getAccesses().stream().anyMatch(x -> Arrays.asList(requestedAccessTypes).contains(x.getType()))); - String[] nonexistentRequestedAccessTypes = {"_DELETE"}; - when(searchUtil.getParamMultiValues(request, "accessType")).thenReturn(nonexistentRequestedAccessTypes); + String[] nonexistentRequestedAccessTypes = {"_DELETE"}; + when(searchUtil.getParamMultiValues(request, "accessType")).thenReturn(nonexistentRequestedAccessTypes); - List updatedPolicyItemsByAccessType = new ArrayList<>(gdsREST.filterPolicyItemsByRequest(policy, request)); - assertTrue( "Grants for Principals: "+ Arrays.toString(requestedPrincipals) + " and AccessTypes: "+ Arrays.toString(nonexistentRequestedAccessTypes) +" should be empty", updatedPolicyItemsByAccessType.isEmpty()); - } + List updatedPolicyItemsByAccessType = new ArrayList<>(gdsREST.filterPolicyItemsByRequest(policy, request)); + assertTrue("Grants for Principals: " + Arrays.toString(requestedPrincipals) + " and AccessTypes: " + Arrays.toString(nonexistentRequestedAccessTypes) + " should be empty", updatedPolicyItemsByAccessType.isEmpty()); + } - private RangerGds.RangerDataset createRangerDataSet() { - long id = new Random().nextInt(100); - RangerGds.RangerDataset dataset = new RangerGds.RangerDataset(); - dataset.setId(id); - dataset.setName("dataset-" + id); - dataset.setGuid(UUID.randomUUID().toString()); + private RangerGds.RangerDataset createRangerDataSet() { + long id = new Random().nextInt(100); + RangerGds.RangerDataset dataset = new RangerGds.RangerDataset(); + dataset.setId(id); + dataset.setName("dataset-" + id); + dataset.setGuid(UUID.randomUUID().toString()); - return dataset; - } + return dataset; + } - private RangerPolicy createPolicyForDataSet(RangerGds.RangerDataset dataset) { - RangerPolicy policy = new RangerPolicy(); - policy.setName("DATASET: " + dataset.getName() + "@" + System.currentTimeMillis()); - policy.setDescription("Policy for dataset: " + dataset.getName()); - policy.setServiceType("gds"); - policy.setService("_gds"); - policy.setZoneName(null); - policy.setResources(Collections.singletonMap("dataset-id", new RangerPolicy.RangerPolicyResource(dataset.getId().toString()))); - policy.setPolicyType(RangerPolicy.POLICY_TYPE_ACCESS); - policy.setPolicyPriority(RangerPolicy.POLICY_PRIORITY_NORMAL); - policy.setAllowExceptions(Collections.emptyList()); - policy.setDenyPolicyItems(Collections.emptyList()); - policy.setDenyExceptions(Collections.emptyList()); - policy.setDataMaskPolicyItems(Collections.emptyList()); - policy.setRowFilterPolicyItems(Collections.emptyList()); - policy.setIsDenyAllElse(Boolean.FALSE); + private RangerPolicy createPolicyForDataSet(RangerGds.RangerDataset dataset) { + RangerPolicy policy = new RangerPolicy(); + policy.setName("DATASET: " + dataset.getName() + "@" + System.currentTimeMillis()); + policy.setDescription("Policy for dataset: " + dataset.getName()); + policy.setServiceType("gds"); + policy.setService("_gds"); + policy.setZoneName(null); + policy.setResources(Collections.singletonMap("dataset-id", new RangerPolicy.RangerPolicyResource(dataset.getId().toString()))); + policy.setPolicyType(RangerPolicy.POLICY_TYPE_ACCESS); + policy.setPolicyPriority(RangerPolicy.POLICY_PRIORITY_NORMAL); + policy.setAllowExceptions(Collections.emptyList()); + policy.setDenyPolicyItems(Collections.emptyList()); + policy.setDenyExceptions(Collections.emptyList()); + policy.setDataMaskPolicyItems(Collections.emptyList()); + policy.setRowFilterPolicyItems(Collections.emptyList()); + policy.setIsDenyAllElse(Boolean.FALSE); - return policy; - } + return policy; + } - private List createAndGetSampleGrantData() { - RangerGrant grant1 = new RangerGrant(new RangerPrincipal(RangerPrincipal.PrincipalType.USER, "hive"), - Arrays.asList("_READ"), Arrays.asList("IS_ACCESSED_BEFORE('2024/12/12')")); - RangerGrant grant2 = new RangerGrant(new RangerPrincipal(RangerPrincipal.PrincipalType.GROUP, "hdfs"), - Arrays.asList("_MANAGE"), Collections.emptyList()); + private List createAndGetSampleGrantData() { + RangerGrant grant1 = new RangerGrant(new RangerPrincipal(RangerPrincipal.PrincipalType.USER, "hive"), Collections.singletonList("_READ"), Collections.singletonList("IS_ACCESSED_BEFORE('2024/12/12')")); + RangerGrant grant2 = new RangerGrant(new RangerPrincipal(RangerPrincipal.PrincipalType.GROUP, "hdfs"), Collections.singletonList("_MANAGE"), Collections.emptyList()); - return Arrays.asList(grant1, grant2); - } + return Arrays.asList(grant1, grant2); + } } diff --git a/security-admin/src/test/java/org/apache/ranger/rest/TestMetricsREST.java b/security-admin/src/test/java/org/apache/ranger/rest/TestMetricsREST.java index 3b2a0c3e1d..efcbff603b 100644 --- a/security-admin/src/test/java/org/apache/ranger/rest/TestMetricsREST.java +++ b/security-admin/src/test/java/org/apache/ranger/rest/TestMetricsREST.java @@ -19,8 +19,6 @@ package org.apache.ranger.rest; -import java.util.LinkedHashMap; -import java.util.Map; import org.apache.ranger.plugin.model.RangerMetrics; import org.apache.ranger.util.RangerMetricsUtil; import org.junit.Assert; @@ -33,6 +31,9 @@ import org.mockito.Mockito; import org.mockito.junit.MockitoJUnitRunner; +import java.util.LinkedHashMap; +import java.util.Map; + @RunWith(MockitoJUnitRunner.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class TestMetricsREST { @@ -42,9 +43,8 @@ public class TestMetricsREST { @Mock RangerMetricsUtil jvmMetricUtil; - @Test - public void testGetStatus() throws Exception { + public void testGetStatus() { Map rangerMetricsValues = getRangerMetricsValues(); Mockito.when(jvmMetricUtil.getValues()).thenReturn(rangerMetricsValues); @@ -55,7 +55,7 @@ public void testGetStatus() throws Exception { Assert.assertNotNull(rangerMetrics.getData()); Assert.assertNotNull(rangerMetrics.getData().get("jvm")); - Map jvmMetricsMap = (Map)rangerMetrics.getData().get("jvm"); + Map jvmMetricsMap = (Map) rangerMetrics.getData().get("jvm"); Assert.assertNotNull(jvmMetricsMap.get("JVM Machine Actual Name")); Assert.assertNotNull(jvmMetricsMap.get("version")); @@ -64,19 +64,18 @@ public void testGetStatus() throws Exception { Assert.assertEquals("8", jvmMetricsMap.get("os.vcpus")); Assert.assertNotNull(jvmMetricsMap.get("memory")); - Map memoryDetailsMap = (Map)jvmMetricsMap.get("memory"); + Map memoryDetailsMap = (Map) jvmMetricsMap.get("memory"); Assert.assertEquals("7635730432", memoryDetailsMap.get("heapMax")); Assert.assertEquals("40424768", memoryDetailsMap.get("heapUsed")); } - private Map getRangerMetricsValues() { - Map rangerMetricsMap = new LinkedHashMap<>(); + Map rangerMetricsMap = new LinkedHashMap<>(); rangerMetricsMap.put("os.spec", "Mac OS X, x86_64, 12.6.3"); rangerMetricsMap.put("os.vcpus", "8"); - Map memoryDetailsMap = new LinkedHashMap<>(); + Map memoryDetailsMap = new LinkedHashMap<>(); memoryDetailsMap.put("heapMax", String.valueOf(7635730432L)); memoryDetailsMap.put("heapCommitted", String.valueOf(514850816L)); memoryDetailsMap.put("heapUsed", String.valueOf(40424768L)); diff --git a/security-admin/src/test/java/org/apache/ranger/rest/TestPublicAPIs.java b/security-admin/src/test/java/org/apache/ranger/rest/TestPublicAPIs.java index aa7e9b8620..1f2d7312cb 100644 --- a/security-admin/src/test/java/org/apache/ranger/rest/TestPublicAPIs.java +++ b/security-admin/src/test/java/org/apache/ranger/rest/TestPublicAPIs.java @@ -17,14 +17,6 @@ package org.apache.ranger.rest; -import java.util.ArrayList; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.servlet.http.HttpServletRequest; - import org.apache.commons.lang.StringUtils; import org.apache.ranger.common.ContextUtil; import org.apache.ranger.common.JSONUtil; @@ -38,11 +30,11 @@ import org.apache.ranger.entity.XXPolicy; import org.apache.ranger.entity.XXService; import org.apache.ranger.plugin.model.RangerPolicy; -import org.apache.ranger.plugin.model.RangerService; import org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyItem; import org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyItemAccess; import org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyItemCondition; import org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyResource; +import org.apache.ranger.plugin.model.RangerService; import org.apache.ranger.plugin.util.SearchFilter; import org.apache.ranger.security.context.RangerContextHolder; import org.apache.ranger.security.context.RangerSecurityContext; @@ -67,424 +59,406 @@ import org.mockito.Mockito; import org.mockito.junit.MockitoJUnitRunner; +import javax.servlet.http.HttpServletRequest; + +import java.util.ArrayList; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + @RunWith(MockitoJUnitRunner.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class TestPublicAPIs { + private static final Long Id = 8L; + @Rule + public ExpectedException thrown = ExpectedException.none(); + @InjectMocks + PublicAPIs publicAPIs = new PublicAPIs(); + @Mock + ServiceREST serviceREST; + @Mock + ServiceUtil serviceUtil; + @Mock + RESTErrorUtil restErrorUtil; + @Mock + JSONUtil jsonUtil; + @Mock + RangerDaoManager daoMgr; + @Mock + RangerSearchUtil searchUtil; + @Mock + XAssetService xAssetService; + @Mock + RangerPolicyService policyService; + @Mock + AssetREST assetREST; + + @Before + public void setup() throws Exception { + RangerSecurityContext context = new RangerSecurityContext(); + context.setUserSession(new UserSessionBase()); + RangerContextHolder.setSecurityContext(context); + UserSessionBase currentUserSession = ContextUtil.getCurrentUserSession(); + currentUserSession.setUserAdmin(true); + } + + @Test + public void test1getRepository() { + RangerService rangerService = rangerService(); + VXRepository vXRepository = vXRepository(rangerService); + Mockito.when(serviceREST.getService(rangerService.getId())).thenReturn(rangerService); + Mockito.when(serviceUtil.toVXRepository(rangerService)).thenReturn(vXRepository); + VXRepository dbVXRepository = publicAPIs.getRepository(Id); + + Assert.assertNotNull(dbVXRepository); + Assert.assertEquals(dbVXRepository, vXRepository); + Assert.assertEquals(dbVXRepository.getId(), vXRepository.getId()); + Assert.assertEquals(dbVXRepository.getName(), vXRepository.getName()); + Mockito.verify(serviceREST).getService(Id); + Mockito.verify(serviceUtil).toVXRepository(rangerService); + } + + @Test + public void test2createRepository() { + VXAsset vXAsset = new VXAsset(); + RangerService rangerService = rangerService(); + VXRepository vXRepository = vXRepository(rangerService); + Mockito.when(serviceUtil.publicObjecttoVXAsset(vXRepository)).thenReturn(vXAsset); + Mockito.when(serviceUtil.toRangerService(vXAsset)).thenReturn(rangerService); + Mockito.when(serviceREST.createService(rangerService)).thenReturn(rangerService); + Mockito.when(serviceUtil.toVXAsset(rangerService)).thenReturn(vXAsset); + Mockito.when(serviceUtil.vXAssetToPublicObject(vXAsset)).thenReturn(vXRepository); + VXRepository dbVXRepository = publicAPIs.createRepository(vXRepository); + + Assert.assertNotNull(dbVXRepository); + Assert.assertEquals(dbVXRepository, vXRepository); + Assert.assertEquals(dbVXRepository.getId(), + vXRepository.getId()); + Assert.assertEquals(dbVXRepository.getName(), + vXRepository.getName()); + Mockito.verify(serviceREST).createService(rangerService); + Mockito.verify(serviceUtil).publicObjecttoVXAsset(vXRepository); + Mockito.verify(serviceUtil).toRangerService(vXAsset); + Mockito.verify(serviceUtil).toVXAsset(rangerService); + Mockito.verify(serviceUtil).vXAssetToPublicObject(vXAsset); + } + + @Test + public void test3updateRepository() { + VXAsset vXAsset = new VXAsset(); + RangerService rangerService = rangerService(); + HttpServletRequest request = null; + VXRepository vXRepository = vXRepository(rangerService); + XXService xService = xService(); + XXServiceDao xServiceDao = Mockito.mock(XXServiceDao.class); + Mockito.when(daoMgr.getXXService()).thenReturn(xServiceDao); + Mockito.when(xServiceDao.getById(Id)).thenReturn(xService); + Mockito.when(serviceUtil.publicObjecttoVXAsset(vXRepository)).thenReturn(vXAsset); + Mockito.when(serviceUtil.toRangerService(vXAsset)).thenReturn(rangerService); + Mockito.when(serviceREST.updateService(rangerService, request)).thenReturn(rangerService); + Mockito.when(serviceUtil.toVXAsset(rangerService)).thenReturn(vXAsset); + Mockito.when(serviceUtil.vXAssetToPublicObject(vXAsset)).thenReturn(vXRepository); + VXRepository dbVXRepository = publicAPIs.updateRepository(vXRepository, Id); + + Assert.assertNotNull(dbVXRepository); + Assert.assertEquals(dbVXRepository, vXRepository); + Assert.assertEquals(dbVXRepository.getId(), vXRepository.getId()); + Assert.assertEquals(dbVXRepository.getName(), vXRepository.getName()); + Mockito.verify(serviceREST).updateService(rangerService, request); + Mockito.verify(serviceUtil).publicObjecttoVXAsset(vXRepository); + Mockito.verify(serviceUtil).toRangerService(vXAsset); + Mockito.verify(serviceUtil).toVXAsset(rangerService); + Mockito.verify(serviceUtil).vXAssetToPublicObject(vXAsset); + Mockito.verify(daoMgr).getXXService(); + } + + @Test + public void test4deleteRepository() { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + Mockito.doNothing().when(serviceREST).deleteService(Id); + publicAPIs.deleteRepository(Id, request); + Mockito.verify(serviceREST).deleteService(Id); + } + + @Test + public void test5searchRepositories() { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + List ret = new ArrayList<>(); + RangerService rangerService = rangerService(); + VXRepository vXRepository = vXRepository(rangerService); + List repoList = new ArrayList<>(); + repoList.add(vXRepository); + VXRepositoryList vXRepositoryList = new VXRepositoryList(repoList); + SearchFilter filter = new SearchFilter(); + filter.setParam(SearchFilter.POLICY_NAME, "policyName"); + filter.setParam(SearchFilter.SERVICE_NAME, "serviceName"); + Mockito.when(searchUtil.getSearchFilterFromLegacyRequestForRepositorySearch(request, xAssetService.sortFields)).thenReturn(filter); + Mockito.when(serviceREST.getServices(filter)).thenReturn(ret); + Mockito.when(serviceUtil.rangerServiceListToPublicObjectList(ret)).thenReturn(vXRepositoryList); + VXRepositoryList dbVXRepositoryList = publicAPIs.searchRepositories(request); + Assert.assertNotNull(dbVXRepositoryList); + Assert.assertEquals(dbVXRepositoryList.getResultSize(), vXRepositoryList.getResultSize()); + } + + @Test + public void test6countRepositories() { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + + VXLong resultExpected = new VXLong(); + resultExpected.setValue(4L); + + Mockito.when(assetREST.countXAssets(request)).thenReturn(resultExpected); + + VXLong resultActual = publicAPIs.countRepositories(request); + + Assert.assertEquals(resultExpected.getValue(), resultActual.getValue()); + Mockito.verify(assetREST).countXAssets(request); + } + + @Test + public void test7getPolicy() { + RangerPolicy policy = rangerPolicy(); + RangerService service = rangerService(); + VXPolicy vXPolicy = vXPolicy(policy, service); + Mockito.when(serviceREST.getPolicy(policy.getId())).thenReturn(policy); + Mockito.when(serviceREST.getServiceByName(policy.getService())).thenReturn(service); + Mockito.when(serviceUtil.toVXPolicy(policy, service)).thenReturn(vXPolicy); + VXPolicy dbVXPolicy = publicAPIs.getPolicy(Id); + Assert.assertNotNull(dbVXPolicy); + Assert.assertEquals(dbVXPolicy, vXPolicy); + Assert.assertEquals(dbVXPolicy.getPolicyName(), vXPolicy.getPolicyName()); + Assert.assertEquals(dbVXPolicy.getRepositoryType(), vXPolicy.getRepositoryType()); + Mockito.verify(serviceREST).getPolicy(Id); + Mockito.verify(serviceREST).getServiceByName(policy.getService()); + Mockito.verify(serviceUtil).toVXPolicy(policy, service); + } + + @Test + public void test8createPolicy() { + RangerPolicy policy = rangerPolicy(); + RangerService service = rangerService(); + VXPolicy vXPolicy = vXPolicy(policy, service); + Mockito.when(serviceREST.getServiceByName(vXPolicy.getRepositoryName())).thenReturn(service); + Mockito.when(serviceUtil.toRangerPolicy(vXPolicy, service)).thenReturn(policy); + Mockito.when(serviceREST.createPolicy(policy, null)).thenReturn(policy); + Mockito.when(serviceUtil.toVXPolicy(policy, service)).thenReturn(vXPolicy); + VXPolicy dbVXPolicy = publicAPIs.createPolicy(vXPolicy); + Assert.assertNotNull(dbVXPolicy); + Assert.assertEquals(dbVXPolicy, vXPolicy); + Assert.assertEquals(dbVXPolicy.getId(), vXPolicy.getId()); + Assert.assertEquals(dbVXPolicy.getRepositoryName(), vXPolicy.getRepositoryName()); + Mockito.verify(serviceREST).createPolicy(policy, null); + Mockito.verify(serviceREST).getServiceByName(vXPolicy.getRepositoryName()); + Mockito.verify(serviceUtil).toVXPolicy(policy, service); + Mockito.verify(serviceUtil).toRangerPolicy(vXPolicy, service); + } + + @Test + public void test9updatePolicy() { + RangerPolicy policy = rangerPolicy(); + RangerService service = rangerService(); + VXPolicy vXPolicy = vXPolicy(policy, service); + XXPolicyDao xXPolicyDao = Mockito.mock(XXPolicyDao.class); + XXPolicy xXPolicy = policy(); + Mockito.when(daoMgr.getXXPolicy()).thenReturn(xXPolicyDao); + Mockito.when(xXPolicyDao.getById(Id)).thenReturn(xXPolicy); + Mockito.when(serviceREST.getServiceByName(vXPolicy.getRepositoryName())).thenReturn(service); + Mockito.when(serviceUtil.toRangerPolicy(vXPolicy, service)).thenReturn(policy); + Mockito.when(serviceREST.updatePolicy(policy, Id)).thenReturn(policy); + Mockito.when(serviceUtil.toVXPolicy(policy, service)).thenReturn(vXPolicy); + VXPolicy dbVXPolicy = publicAPIs.updatePolicy(vXPolicy, Id); + + Assert.assertNotNull(dbVXPolicy); + Assert.assertEquals(dbVXPolicy, vXPolicy); + Assert.assertEquals(dbVXPolicy.getId(), vXPolicy.getId()); + Assert.assertEquals(dbVXPolicy.getRepositoryName(), vXPolicy.getRepositoryName()); + Mockito.verify(serviceREST).updatePolicy(policy, Id); + Mockito.verify(serviceREST).getServiceByName(vXPolicy.getRepositoryName()); + Mockito.verify(serviceUtil).toVXPolicy(policy, service); + Mockito.verify(serviceUtil).toRangerPolicy(vXPolicy, service); + Mockito.verify(daoMgr).getXXPolicy(); + Mockito.verify(xXPolicyDao).getById(Id); + } + + @Test + public void test10deletePolicy() { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + Mockito.doNothing().when(serviceREST).deletePolicy(Id); + publicAPIs.deletePolicy(Id, request); + Mockito.verify(serviceREST).deletePolicy(Id); + } + + @Test + public void test11searchPolicies() { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + RangerService service = rangerService(); + RangerPolicy policy = rangerPolicy(); + List policyList = new ArrayList<>(); + policyList.add(policy); + VXPolicy vXPolicy = vXPolicy(policy, service); + List vXPolicies = new ArrayList<>(); + vXPolicies.add(vXPolicy); + VXPolicyList vXPolicyList = new VXPolicyList(vXPolicies); + SearchFilter filter = new SearchFilter(); + filter.setParam(SearchFilter.POLICY_NAME, "policyName"); + filter.setParam(SearchFilter.SERVICE_NAME, "serviceName"); + filter.setStartIndex(0); + filter.setMaxRows(10); + Mockito.when(searchUtil.getSearchFilterFromLegacyRequest(request, policyService.sortFields)).thenReturn(filter); + Mockito.when(serviceREST.getPolicies(filter)).thenReturn(policyList); + Mockito.when(serviceUtil.rangerPolicyListToPublic(policyList, filter)).thenReturn(vXPolicyList); + VXPolicyList dbVXPolicyList = publicAPIs.searchPolicies(request); + Assert.assertNotNull(dbVXPolicyList); + Assert.assertEquals(dbVXPolicyList.getResultSize(), vXPolicyList.getResultSize()); + Mockito.verify(searchUtil).getSearchFilterFromLegacyRequest(request, policyService.sortFields); + Mockito.verify(serviceREST).getPolicies(filter); + Mockito.verify(serviceUtil).rangerPolicyListToPublic(policyList, filter); + } + + @Test + public void test12countPolicies() { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + + VXLong resultExpected = new VXLong(); + resultExpected.setValue(6L); + + Mockito.when(assetREST.countXResources(request)).thenReturn(resultExpected); + + VXLong resultActual = publicAPIs.countPolicies(request); + + Assert.assertEquals(resultExpected.getValue(), resultActual.getValue()); + Mockito.verify(assetREST).countXResources(request); + } + + private RangerService rangerService() { + Map configs = new HashMap<>(); + configs.put("username", "servicemgr"); + configs.put("password", "servicemgr"); + configs.put("namenode", "servicemgr"); + configs.put("hadoop.security.authorization", "No"); + configs.put("hadoop.security.authentication", "Simple"); + configs.put("hadoop.security.auth_to_local", ""); + configs.put("dfs.datanode.kerberos.principal", ""); + configs.put("dfs.namenode.kerberos.principal", ""); + configs.put("dfs.secondary.namenode.kerberos.principal", ""); + configs.put("hadoop.rpc.protection", "Privacy"); + configs.put("commonNameForCertificate", ""); + + RangerService rangerService = new RangerService(); + rangerService.setId(Id); + rangerService.setConfigs(configs); + rangerService.setCreateTime(new Date()); + rangerService.setDescription("service policy"); + rangerService.setGuid("1427365526516_835_0"); + rangerService.setIsEnabled(true); + rangerService.setName("HDFS_1"); + rangerService.setPolicyUpdateTime(new Date()); + rangerService.setType("1"); + rangerService.setUpdatedBy("Admin"); + rangerService.setUpdateTime(new Date()); + + return rangerService; + } + + private XXService xService() { + XXService xService = new XXService(); + xService.setAddedByUserId(Id); + xService.setCreateTime(new Date()); + xService.setDescription("Hdfs service"); + xService.setGuid("serviceguid"); + xService.setId(Id); + xService.setIsEnabled(true); + xService.setName("Hdfs"); + xService.setPolicyUpdateTime(new Date()); + xService.setPolicyVersion(1L); + xService.setType(1L); + xService.setUpdatedByUserId(Id); + xService.setUpdateTime(new Date()); + + return xService; + } + + private VXRepository vXRepository(RangerService service) { + VXRepository ret = new VXRepository(); + ret.setRepositoryType(service.getType()); + ret.setName(service.getName()); + ret.setDescription(service.getDescription()); + ret.setIsActive(service.getIsEnabled()); + ret.setConfig(jsonUtil.readMapToString(service.getConfigs())); + ret.setId(service.getId()); + ret.setCreateDate(service.getCreateTime()); + ret.setUpdateDate(service.getUpdateTime()); + ret.setOwner(service.getCreatedBy()); + ret.setUpdatedBy(service.getUpdatedBy()); + + return ret; + } + + private VXPolicy vXPolicy(RangerPolicy policy, RangerService service) { + VXPolicy ret = new VXPolicy(); + ret.setPolicyName(StringUtils.trim(policy.getName())); + ret.setDescription(policy.getDescription()); + ret.setRepositoryName(policy.getService()); + ret.setIsEnabled(policy.getIsEnabled()); + ret.setRepositoryType(service.getType()); + ret.setIsAuditEnabled(policy.getIsAuditEnabled()); + return ret; + } + + private RangerPolicy rangerPolicy() { + List accesses = new ArrayList<>(); + List users = new ArrayList<>(); + List groups = new ArrayList<>(); + List conditions = new ArrayList<>(); + List policyItems = new ArrayList<>(); + RangerPolicyItem rangerPolicyItem = new RangerPolicyItem(); + rangerPolicyItem.setAccesses(accesses); + rangerPolicyItem.setConditions(conditions); + rangerPolicyItem.setGroups(groups); + rangerPolicyItem.setUsers(users); + rangerPolicyItem.setDelegateAdmin(false); + + policyItems.add(rangerPolicyItem); + + Map policyResource = new HashMap<>(); + RangerPolicyResource rangerPolicyResource = new RangerPolicyResource(); + rangerPolicyResource.setIsExcludes(true); + rangerPolicyResource.setIsRecursive(true); + rangerPolicyResource.setValue("1"); + rangerPolicyResource.setValues(users); + policyResource.put("resource", rangerPolicyResource); + RangerPolicy policy = new RangerPolicy(); + policy.setId(Id); + policy.setCreateTime(new Date()); + policy.setDescription("policy"); + policy.setGuid("policyguid"); + policy.setIsEnabled(true); + policy.setName("HDFS_1-1-20150316062453"); + policy.setUpdatedBy("Admin"); + policy.setUpdateTime(new Date()); + policy.setService("HDFS_1-1-20150316062453"); + policy.setIsAuditEnabled(true); + policy.setPolicyItems(policyItems); + policy.setResources(policyResource); + policy.setService("HDFS_1"); - private static Long Id = 8L; - - @InjectMocks - PublicAPIs publicAPIs = new PublicAPIs(); - - @Mock - ServiceREST serviceREST; - - @Mock - ServiceUtil serviceUtil; - - @Mock - RESTErrorUtil restErrorUtil; - - @Mock - JSONUtil jsonUtil; - - @Mock - RangerDaoManager daoMgr; - - @Mock - RangerSearchUtil searchUtil; - - @Mock - XAssetService xAssetService; - - @Mock - RangerPolicyService policyService; - - @Mock - AssetREST assetREST; - - @Rule - public ExpectedException thrown = ExpectedException.none(); - - @Before - public void setup() throws Exception { - RangerSecurityContext context = new RangerSecurityContext(); - context.setUserSession(new UserSessionBase()); - RangerContextHolder.setSecurityContext(context); - UserSessionBase currentUserSession = ContextUtil - .getCurrentUserSession(); - currentUserSession.setUserAdmin(true); - } - - private RangerService rangerService() { - Map configs = new HashMap(); - configs.put("username", "servicemgr"); - configs.put("password", "servicemgr"); - configs.put("namenode", "servicemgr"); - configs.put("hadoop.security.authorization", "No"); - configs.put("hadoop.security.authentication", "Simple"); - configs.put("hadoop.security.auth_to_local", ""); - configs.put("dfs.datanode.kerberos.principal", ""); - configs.put("dfs.namenode.kerberos.principal", ""); - configs.put("dfs.secondary.namenode.kerberos.principal", ""); - configs.put("hadoop.rpc.protection", "Privacy"); - configs.put("commonNameForCertificate", ""); - - RangerService rangerService = new RangerService(); - rangerService.setId(Id); - rangerService.setConfigs(configs); - rangerService.setCreateTime(new Date()); - rangerService.setDescription("service policy"); - rangerService.setGuid("1427365526516_835_0"); - rangerService.setIsEnabled(true); - rangerService.setName("HDFS_1"); - rangerService.setPolicyUpdateTime(new Date()); - rangerService.setType("1"); - rangerService.setUpdatedBy("Admin"); - rangerService.setUpdateTime(new Date()); - - return rangerService; - } - - private XXService xService() { - XXService xService = new XXService(); - xService.setAddedByUserId(Id); - xService.setCreateTime(new Date()); - xService.setDescription("Hdfs service"); - xService.setGuid("serviceguid"); - xService.setId(Id); - xService.setIsEnabled(true); - xService.setName("Hdfs"); - xService.setPolicyUpdateTime(new Date()); - xService.setPolicyVersion(1L); - xService.setType(1L); - xService.setUpdatedByUserId(Id); - xService.setUpdateTime(new Date()); - - return xService; - } - - private VXRepository vXRepository(RangerService service) { - VXRepository ret = new VXRepository(); - ret.setRepositoryType(service.getType()); - ret.setName(service.getName()); - ret.setDescription(service.getDescription()); - ret.setIsActive(service.getIsEnabled()); - ret.setConfig(jsonUtil.readMapToString(service.getConfigs())); - //ret.setVersion(Long.toString(service.getVersion())); - ret.setId(service.getId()); - ret.setCreateDate(service.getCreateTime()); - ret.setUpdateDate(service.getUpdateTime()); - ret.setOwner(service.getCreatedBy()); - ret.setUpdatedBy(service.getUpdatedBy()); - - return ret; - } - - private VXPolicy vXPolicy(RangerPolicy policy, RangerService service) { - VXPolicy ret = new VXPolicy(); - ret.setPolicyName(StringUtils.trim(policy.getName())); - ret.setDescription(policy.getDescription()); - ret.setRepositoryName(policy.getService()); - ret.setIsEnabled(policy.getIsEnabled() ? true : false); - ret.setRepositoryType(service.getType()); - ret.setIsAuditEnabled(policy.getIsAuditEnabled()); - return ret; - } - - private RangerPolicy rangerPolicy() { - List accesses = new ArrayList(); - List users = new ArrayList(); - List groups = new ArrayList(); - List conditions = new ArrayList(); - List policyItems = new ArrayList(); - RangerPolicyItem rangerPolicyItem = new RangerPolicyItem(); - rangerPolicyItem.setAccesses(accesses); - rangerPolicyItem.setConditions(conditions); - rangerPolicyItem.setGroups(groups); - rangerPolicyItem.setUsers(users); - rangerPolicyItem.setDelegateAdmin(false); - - policyItems.add(rangerPolicyItem); - - Map policyResource = new HashMap(); - RangerPolicyResource rangerPolicyResource = new RangerPolicyResource(); - rangerPolicyResource.setIsExcludes(true); - rangerPolicyResource.setIsRecursive(true); - rangerPolicyResource.setValue("1"); - rangerPolicyResource.setValues(users); - policyResource.put("resource", rangerPolicyResource); - RangerPolicy policy = new RangerPolicy(); - policy.setId(Id); - policy.setCreateTime(new Date()); - policy.setDescription("policy"); - policy.setGuid("policyguid"); - policy.setIsEnabled(true); - policy.setName("HDFS_1-1-20150316062453"); - policy.setUpdatedBy("Admin"); - policy.setUpdateTime(new Date()); - policy.setService("HDFS_1-1-20150316062453"); - policy.setIsAuditEnabled(true); - policy.setPolicyItems(policyItems); - policy.setResources(policyResource); - policy.setService("HDFS_1"); - - return policy; - } - - private XXPolicy policy() { - XXPolicy xxPolicy = new XXPolicy(); - xxPolicy.setId(Id); - xxPolicy.setName("HDFS_1-1-20150316062453"); - xxPolicy.setAddedByUserId(Id); - xxPolicy.setCreateTime(new Date()); - xxPolicy.setDescription("test"); - xxPolicy.setIsAuditEnabled(false); - xxPolicy.setIsEnabled(false); - xxPolicy.setService(1L); - xxPolicy.setUpdatedByUserId(Id); - xxPolicy.setUpdateTime(new Date()); - xxPolicy.setVersion(Id); - return xxPolicy; - } - - @Test - public void test1getRepository() throws Exception { - RangerService rangerService = rangerService(); - VXRepository vXRepository = vXRepository(rangerService); - Mockito.when(serviceREST.getService(rangerService.getId())).thenReturn(rangerService); - Mockito.when(serviceUtil.toVXRepository(rangerService)).thenReturn(vXRepository); - VXRepository dbVXRepository = publicAPIs.getRepository(Id); - - Assert.assertNotNull(dbVXRepository); - Assert.assertEquals(dbVXRepository, vXRepository); - Assert.assertEquals(dbVXRepository.getId(), - vXRepository.getId()); - Assert.assertEquals(dbVXRepository.getName(), - vXRepository.getName()); - Mockito.verify(serviceREST).getService(Id); - Mockito.verify(serviceUtil).toVXRepository(rangerService); - - } - - @Test - public void test2createRepository() throws Exception { - VXAsset vXAsset = new VXAsset(); - RangerService rangerService = rangerService(); - VXRepository vXRepository = vXRepository(rangerService); - Mockito.when(serviceUtil.publicObjecttoVXAsset(vXRepository)).thenReturn(vXAsset); - Mockito.when(serviceUtil.toRangerService(vXAsset)).thenReturn(rangerService); - Mockito.when(serviceREST.createService(rangerService)).thenReturn(rangerService); - Mockito.when(serviceUtil.toVXAsset(rangerService)).thenReturn(vXAsset); - Mockito.when(serviceUtil.vXAssetToPublicObject(vXAsset)).thenReturn(vXRepository); - VXRepository dbVXRepository = publicAPIs.createRepository(vXRepository); - - Assert.assertNotNull(dbVXRepository); - Assert.assertEquals(dbVXRepository, vXRepository); - Assert.assertEquals(dbVXRepository.getId(), - vXRepository.getId()); - Assert.assertEquals(dbVXRepository.getName(), - vXRepository.getName()); - Mockito.verify(serviceREST).createService(rangerService); - Mockito.verify(serviceUtil).publicObjecttoVXAsset(vXRepository); - Mockito.verify(serviceUtil).toRangerService(vXAsset); - Mockito.verify(serviceUtil).toVXAsset(rangerService); - Mockito.verify(serviceUtil).vXAssetToPublicObject(vXAsset); - } - - @Test - public void test3updateRepository() throws Exception { - VXAsset vXAsset = new VXAsset(); - RangerService rangerService = rangerService(); - HttpServletRequest request = null; - VXRepository vXRepository = vXRepository(rangerService); - XXService xService = xService(); - XXServiceDao xServiceDao = Mockito.mock(XXServiceDao.class); - Mockito.when(daoMgr.getXXService()).thenReturn(xServiceDao); - Mockito.when(xServiceDao.getById(Id)).thenReturn(xService); - Mockito.when(serviceUtil.publicObjecttoVXAsset(vXRepository)).thenReturn(vXAsset); - Mockito.when(serviceUtil.toRangerService(vXAsset)).thenReturn(rangerService); - Mockito.when(serviceREST.updateService(rangerService, request)).thenReturn(rangerService); - Mockito.when(serviceUtil.toVXAsset(rangerService)).thenReturn(vXAsset); - Mockito.when(serviceUtil.vXAssetToPublicObject(vXAsset)).thenReturn(vXRepository); - VXRepository dbVXRepository = publicAPIs.updateRepository(vXRepository, Id); - - Assert.assertNotNull(dbVXRepository); - Assert.assertEquals(dbVXRepository, vXRepository); - Assert.assertEquals(dbVXRepository.getId(), - vXRepository.getId()); - Assert.assertEquals(dbVXRepository.getName(), - vXRepository.getName()); - Mockito.verify(serviceREST).updateService(rangerService, request); - Mockito.verify(serviceUtil).publicObjecttoVXAsset(vXRepository); - Mockito.verify(serviceUtil).toRangerService(vXAsset); - Mockito.verify(serviceUtil).toVXAsset(rangerService); - Mockito.verify(serviceUtil).vXAssetToPublicObject(vXAsset); - Mockito.verify(daoMgr).getXXService(); - } - - @Test - public void test4deleteRepository() throws Exception { - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - Mockito.doNothing().when(serviceREST).deleteService(Id); - publicAPIs.deleteRepository(Id, request); - Mockito.verify(serviceREST).deleteService(Id); - } - - @Test - public void test5searchRepositories() throws Exception { - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - List ret = new ArrayList(); - RangerService rangerService = rangerService(); - VXRepository vXRepository = vXRepository(rangerService); - List repoList = new ArrayList(); - repoList.add(vXRepository); - VXRepositoryList vXRepositoryList = new VXRepositoryList(repoList); - SearchFilter filter = new SearchFilter(); - filter.setParam(SearchFilter.POLICY_NAME, "policyName"); - filter.setParam(SearchFilter.SERVICE_NAME, "serviceName"); - Mockito.when(searchUtil.getSearchFilterFromLegacyRequestForRepositorySearch(request, xAssetService.sortFields)).thenReturn(filter); - Mockito.when(serviceREST.getServices(filter)).thenReturn(ret); - Mockito.when(serviceUtil.rangerServiceListToPublicObjectList(ret)).thenReturn(vXRepositoryList); - VXRepositoryList dbVXRepositoryList = publicAPIs.searchRepositories(request); - Assert.assertNotNull(dbVXRepositoryList); - Assert.assertEquals(dbVXRepositoryList.getResultSize(), vXRepositoryList.getResultSize()); - } - - @Test - public void test6countRepositories() throws Exception { - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - - VXLong resultExpected = new VXLong(); - resultExpected.setValue(4l); - - Mockito.when(assetREST.countXAssets(request)).thenReturn(resultExpected); - - VXLong resultActual = publicAPIs.countRepositories(request); - - Assert.assertEquals(resultExpected.getValue(), resultActual.getValue()); - Mockito.verify(assetREST).countXAssets(request); - } - - @Test - public void test7getPolicy() throws Exception { - RangerPolicy policy = rangerPolicy(); - RangerService service = rangerService(); - VXPolicy vXPolicy = vXPolicy(policy, service); - Mockito.when(serviceREST.getPolicy(policy.getId())).thenReturn(policy); - Mockito.when(serviceREST.getServiceByName(policy.getService())).thenReturn(service); - Mockito.when(serviceUtil.toVXPolicy(policy, service)).thenReturn(vXPolicy); - VXPolicy dbVXPolicy = publicAPIs.getPolicy(Id); - Assert.assertNotNull(dbVXPolicy); - Assert.assertEquals(dbVXPolicy, vXPolicy); - Assert.assertEquals(dbVXPolicy.getPolicyName(), vXPolicy.getPolicyName()); - Assert.assertEquals(dbVXPolicy.getRepositoryType(), vXPolicy.getRepositoryType()); - Mockito.verify(serviceREST).getPolicy(Id); - Mockito.verify(serviceREST).getServiceByName(policy.getService()); - Mockito.verify(serviceUtil).toVXPolicy(policy, service); - } - - @Test - public void test8createPolicy() throws Exception { - RangerPolicy policy = rangerPolicy(); - RangerService service = rangerService(); - VXPolicy vXPolicy = vXPolicy(policy, service); - Mockito.when(serviceREST.getServiceByName(vXPolicy.getRepositoryName())).thenReturn(service); - Mockito.when(serviceUtil.toRangerPolicy(vXPolicy,service)).thenReturn(policy); - Mockito.when(serviceREST.createPolicy(policy, null)).thenReturn(policy); - Mockito.when(serviceUtil.toVXPolicy(policy, service)).thenReturn(vXPolicy); - VXPolicy dbVXPolicy = publicAPIs.createPolicy(vXPolicy); - Assert.assertNotNull(dbVXPolicy); - Assert.assertEquals(dbVXPolicy, vXPolicy); - Assert.assertEquals(dbVXPolicy.getId(), - vXPolicy.getId()); - Assert.assertEquals(dbVXPolicy.getRepositoryName(), - vXPolicy.getRepositoryName()); - Mockito.verify(serviceREST).createPolicy(policy, null); - Mockito.verify(serviceREST).getServiceByName(vXPolicy.getRepositoryName()); - Mockito.verify(serviceUtil).toVXPolicy(policy, service); - Mockito.verify(serviceUtil).toRangerPolicy(vXPolicy,service); - - } - - @Test - public void test9updatePolicy() throws Exception { - RangerPolicy policy = rangerPolicy(); - RangerService service = rangerService(); - VXPolicy vXPolicy = vXPolicy(policy, service); - XXPolicyDao xXPolicyDao = Mockito.mock(XXPolicyDao.class); - XXPolicy xXPolicy = policy(); - Mockito.when(daoMgr.getXXPolicy()).thenReturn(xXPolicyDao); - Mockito.when(xXPolicyDao.getById(Id)).thenReturn(xXPolicy); - Mockito.when(serviceREST.getServiceByName(vXPolicy.getRepositoryName())).thenReturn(service); - Mockito.when(serviceUtil.toRangerPolicy(vXPolicy,service)).thenReturn(policy); - Mockito.when(serviceREST.updatePolicy(policy, Id)).thenReturn(policy); - Mockito.when(serviceUtil.toVXPolicy(policy, service)).thenReturn(vXPolicy); - VXPolicy dbVXPolicy = publicAPIs.updatePolicy(vXPolicy, Id); - - Assert.assertNotNull(dbVXPolicy); - Assert.assertEquals(dbVXPolicy, vXPolicy); - Assert.assertEquals(dbVXPolicy.getId(), - vXPolicy.getId()); - Assert.assertEquals(dbVXPolicy.getRepositoryName(), - vXPolicy.getRepositoryName()); - Mockito.verify(serviceREST).updatePolicy(policy, Id); - Mockito.verify(serviceREST).getServiceByName(vXPolicy.getRepositoryName()); - Mockito.verify(serviceUtil).toVXPolicy(policy, service); - Mockito.verify(serviceUtil).toRangerPolicy(vXPolicy,service); - Mockito.verify(daoMgr).getXXPolicy(); - Mockito.verify(xXPolicyDao).getById(Id); - } - - @Test - public void test10deletePolicy() throws Exception { - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - Mockito.doNothing().when(serviceREST).deletePolicy(Id); - publicAPIs.deletePolicy(Id, request); - Mockito.verify(serviceREST).deletePolicy(Id); - } - - @Test - public void test11searchPolicies() throws Exception { - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - RangerService service = rangerService(); - RangerPolicy policy = rangerPolicy(); - List policyList = new ArrayList(); - policyList.add(policy); - VXPolicy vXPolicy = vXPolicy(policy, service); - List vXPolicies = new ArrayList(); - vXPolicies.add(vXPolicy); - VXPolicyList vXPolicyList = new VXPolicyList(vXPolicies); - SearchFilter filter = new SearchFilter(); - filter.setParam(SearchFilter.POLICY_NAME, "policyName"); - filter.setParam(SearchFilter.SERVICE_NAME, "serviceName"); - filter.setStartIndex(0); - filter.setMaxRows(10); - Mockito.when(searchUtil.getSearchFilterFromLegacyRequest(request, policyService.sortFields)).thenReturn(filter); - Mockito.when(serviceREST.getPolicies(filter)).thenReturn(policyList); - Mockito.when(serviceUtil.rangerPolicyListToPublic(policyList,filter)).thenReturn(vXPolicyList); - VXPolicyList dbVXPolicyList = publicAPIs.searchPolicies(request); - Assert.assertNotNull(dbVXPolicyList); - Assert.assertEquals(dbVXPolicyList.getResultSize(), vXPolicyList.getResultSize()); - Mockito.verify(searchUtil).getSearchFilterFromLegacyRequest(request, policyService.sortFields); - Mockito.verify(serviceREST).getPolicies(filter); - Mockito.verify(serviceUtil).rangerPolicyListToPublic(policyList,filter); - - } - - @Test - public void test12countPolicies() throws Exception { - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - - VXLong resultExpected = new VXLong(); - resultExpected.setValue(6l); - - Mockito.when(assetREST.countXResources(request)).thenReturn(resultExpected); - - VXLong resultActual = publicAPIs.countPolicies(request); - - Assert.assertEquals(resultExpected.getValue(), resultActual.getValue()); - Mockito.verify(assetREST).countXResources(request); - } + return policy; + } + private XXPolicy policy() { + XXPolicy xxPolicy = new XXPolicy(); + xxPolicy.setId(Id); + xxPolicy.setName("HDFS_1-1-20150316062453"); + xxPolicy.setAddedByUserId(Id); + xxPolicy.setCreateTime(new Date()); + xxPolicy.setDescription("test"); + xxPolicy.setIsAuditEnabled(false); + xxPolicy.setIsEnabled(false); + xxPolicy.setService(1L); + xxPolicy.setUpdatedByUserId(Id); + xxPolicy.setUpdateTime(new Date()); + xxPolicy.setVersion(Id); + return xxPolicy; + } } diff --git a/security-admin/src/test/java/org/apache/ranger/rest/TestPublicAPIsv2.java b/security-admin/src/test/java/org/apache/ranger/rest/TestPublicAPIsv2.java index 0fba41ee76..be33dc11de 100644 --- a/security-admin/src/test/java/org/apache/ranger/rest/TestPublicAPIsv2.java +++ b/security-admin/src/test/java/org/apache/ranger/rest/TestPublicAPIsv2.java @@ -17,35 +17,26 @@ package org.apache.ranger.rest; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.servlet.http.HttpServletRequest; - import org.apache.ranger.biz.SecurityZoneDBStore; import org.apache.ranger.common.ContextUtil; import org.apache.ranger.common.RESTErrorUtil; import org.apache.ranger.common.RangerSearchUtil; import org.apache.ranger.common.UserSessionBase; import org.apache.ranger.plugin.model.RangerPolicy; -import org.apache.ranger.plugin.model.RangerSecurityZoneHeaderInfo; -import org.apache.ranger.plugin.model.RangerService; -import org.apache.ranger.plugin.model.RangerServiceDef; -import org.apache.ranger.plugin.model.RangerServiceHeaderInfo; import org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyItem; import org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyItemAccess; import org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyItemCondition; import org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyResource; +import org.apache.ranger.plugin.model.RangerSecurityZoneHeaderInfo; +import org.apache.ranger.plugin.model.RangerService; +import org.apache.ranger.plugin.model.RangerServiceDef; import org.apache.ranger.plugin.model.RangerServiceDef.RangerAccessTypeDef; import org.apache.ranger.plugin.model.RangerServiceDef.RangerContextEnricherDef; import org.apache.ranger.plugin.model.RangerServiceDef.RangerEnumDef; import org.apache.ranger.plugin.model.RangerServiceDef.RangerPolicyConditionDef; import org.apache.ranger.plugin.model.RangerServiceDef.RangerResourceDef; import org.apache.ranger.plugin.model.RangerServiceDef.RangerServiceConfigDef; +import org.apache.ranger.plugin.model.RangerServiceHeaderInfo; import org.apache.ranger.security.context.RangerContextHolder; import org.apache.ranger.security.context.RangerSecurityContext; import org.apache.ranger.service.RangerPolicyService; @@ -65,554 +56,388 @@ import org.mockito.Mockito; import org.mockito.junit.MockitoJUnitRunner; +import javax.servlet.http.HttpServletRequest; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + @RunWith(MockitoJUnitRunner.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class TestPublicAPIsv2 { + private static final Long Id = 8L; + private static final Long Id2 = 10L; + @Rule + public ExpectedException thrown = ExpectedException.none(); + @InjectMocks + PublicAPIsv2 publicAPIsv2 = new PublicAPIsv2(); + @Mock + ServiceREST serviceREST; + @Mock + RangerSearchUtil searchUtil; + @Mock + RangerPolicyService policyService; + @Mock + RESTErrorUtil restErrorUtil; + @Mock + SecurityZoneDBStore securityZoneStore; + + @Before + public void setup() { + RangerSecurityContext context = new RangerSecurityContext(); + context.setUserSession(new UserSessionBase()); + RangerContextHolder.setSecurityContext(context); + UserSessionBase currentUserSession = ContextUtil.getCurrentUserSession(); + currentUserSession.setUserAdmin(true); + } + + @Test + public void test1getServiceDef() { + RangerServiceDef rangerServiceDef = rangerServiceDef(); + Mockito.when(serviceREST.getServiceDef(rangerServiceDef.getId())).thenReturn(rangerServiceDef); + RangerServiceDef dbRangerServiceDef = publicAPIsv2.getServiceDef(Id); + Assert.assertNotNull(dbRangerServiceDef); + Assert.assertEquals(dbRangerServiceDef, rangerServiceDef); + Assert.assertEquals(dbRangerServiceDef.getId(), rangerServiceDef.getId()); + Assert.assertEquals(dbRangerServiceDef.getName(), rangerServiceDef.getName()); + Mockito.verify(serviceREST).getServiceDef(Id); + } + + @Test + public void test2getServiceDefByName() { + RangerServiceDef rangerServiceDef = rangerServiceDef(); + String name = rangerServiceDef.getName(); + Mockito.when(serviceREST.getServiceDefByName(name)).thenReturn(rangerServiceDef); + RangerServiceDef dbRangerServiceDef = publicAPIsv2.getServiceDefByName(name); + Assert.assertNotNull(dbRangerServiceDef); + Assert.assertEquals(dbRangerServiceDef, rangerServiceDef); + Assert.assertEquals(dbRangerServiceDef.getId(), rangerServiceDef.getId()); + Assert.assertEquals(dbRangerServiceDef.getName(), rangerServiceDef.getName()); + Mockito.verify(serviceREST).getServiceDefByName(name); + } + + @Test + public void test3searchServiceDefs() { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + List serviceDefsList = new ArrayList<>(); + RangerServiceDef serviceDef = rangerServiceDef(); + serviceDefsList.add(serviceDef); + RangerServiceDefList serviceDefList = new RangerServiceDefList(serviceDefsList); + Mockito.when(serviceREST.getServiceDefs(request)).thenReturn(serviceDefList); + List dbRangerServiceDefList = publicAPIsv2.searchServiceDefs(request); + Assert.assertNotNull(dbRangerServiceDefList); + Assert.assertEquals(dbRangerServiceDefList.size(), serviceDefsList.size()); + Mockito.verify(serviceREST).getServiceDefs(request); + } + + @Test + public void test4createServiceDef() { + RangerServiceDef rangerServiceDef = rangerServiceDef(); + Mockito.when(serviceREST.createServiceDef(rangerServiceDef)).thenReturn(rangerServiceDef); + RangerServiceDef dbRangerServiceDef = publicAPIsv2.createServiceDef(rangerServiceDef); + Assert.assertNotNull(dbRangerServiceDef); + Assert.assertEquals(dbRangerServiceDef, rangerServiceDef); + Assert.assertEquals(dbRangerServiceDef.getId(), rangerServiceDef.getId()); + Assert.assertEquals(dbRangerServiceDef.getName(), rangerServiceDef.getName()); + Mockito.verify(serviceREST).createServiceDef(rangerServiceDef); + } + + @Test + public void test5updateServiceDef() { + RangerServiceDef rangerServiceDef = rangerServiceDef(); + Mockito.when(serviceREST.updateServiceDef(rangerServiceDef, rangerServiceDef.getId())).thenReturn(rangerServiceDef); + RangerServiceDef dbRangerServiceDef = publicAPIsv2.updateServiceDef(rangerServiceDef, Id); + Assert.assertNotNull(dbRangerServiceDef); + Assert.assertEquals(dbRangerServiceDef, rangerServiceDef); + Assert.assertEquals(dbRangerServiceDef.getId(), rangerServiceDef.getId()); + Assert.assertEquals(dbRangerServiceDef.getName(), rangerServiceDef.getName()); + Mockito.verify(serviceREST).updateServiceDef(rangerServiceDef, rangerServiceDef.getId()); + } + + @Test + public void test6updateServiceDefByName() { + RangerServiceDef rangerServiceDef = rangerServiceDef(); + String name = rangerServiceDef.getName(); + Mockito.when(serviceREST.getServiceDefByName(name)).thenReturn(rangerServiceDef); + Mockito.when(serviceREST.updateServiceDef(rangerServiceDef, rangerServiceDef.getId())).thenReturn(rangerServiceDef); + RangerServiceDef dbRangerServiceDef = publicAPIsv2.updateServiceDefByName(rangerServiceDef, name); + Assert.assertNotNull(dbRangerServiceDef); + Assert.assertEquals(dbRangerServiceDef, rangerServiceDef); + Assert.assertEquals(dbRangerServiceDef.getId(), rangerServiceDef.getId()); + Assert.assertEquals(dbRangerServiceDef.getName(), rangerServiceDef.getName()); + Mockito.verify(serviceREST).updateServiceDef(rangerServiceDef, dbRangerServiceDef.getId()); + Mockito.verify(serviceREST).getServiceDefByName(name); + } + + @Test + public void test7deleteServiceDef() { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + Mockito.doNothing().when(serviceREST).deleteServiceDef(Id, request); + publicAPIsv2.deleteServiceDef(Id, request); + Mockito.verify(serviceREST).deleteServiceDef(Id, request); + } + + @Test + public void test8deleteServiceDefByName() { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + RangerServiceDef rangerServiceDef = rangerServiceDef(); + String name = rangerServiceDef.getName(); + Mockito.when(serviceREST.getServiceDefByName(name)).thenReturn(rangerServiceDef); + Mockito.doNothing().when(serviceREST).deleteServiceDef(rangerServiceDef.getId(), request); + publicAPIsv2.deleteServiceDefByName(name, request); + Mockito.verify(serviceREST).deleteServiceDef(rangerServiceDef.getId(), request); + Mockito.verify(serviceREST).getServiceDefByName(name); + } + + @Test + public void test9getService() { + RangerService rangerService = rangerService(); + Mockito.when(serviceREST.getService(rangerService.getId())).thenReturn(rangerService); + RangerService dbRangerService = publicAPIsv2.getService(Id); + Assert.assertNotNull(dbRangerService); + Assert.assertEquals(dbRangerService, rangerService); + Assert.assertEquals(dbRangerService.getId(), rangerService.getId()); + Assert.assertEquals(dbRangerService.getName(), rangerService.getName()); + Mockito.verify(serviceREST).getService(Id); + } + + @Test + public void test10getServiceByName() { + RangerService rangerService = rangerService(); + String name = rangerService.getName(); + Mockito.when(serviceREST.getServiceByName(name)).thenReturn(rangerService); + RangerService dbRangerService = publicAPIsv2.getServiceByName(name); + Assert.assertNotNull(dbRangerService); + Assert.assertEquals(dbRangerService, rangerService); + Assert.assertEquals(dbRangerService.getId(), rangerService.getId()); + Assert.assertEquals(dbRangerService.getName(), rangerService.getName()); + Mockito.verify(serviceREST).getServiceByName(name); + } + + @Test + public void test11searchServices() { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + List servicesList = new ArrayList<>(); + RangerService service = rangerService(); + servicesList.add(service); + RangerServiceList serviceList = new RangerServiceList(servicesList); + Mockito.when(serviceREST.getServices(request)).thenReturn(serviceList); + List dbRangerServiceList = publicAPIsv2.searchServices(request); + Assert.assertNotNull(dbRangerServiceList); + Assert.assertEquals(dbRangerServiceList.size(), servicesList.size()); + Mockito.verify(serviceREST).getServices(request); + } + + @Test + public void test12createService() { + RangerService rangerService = rangerService(); + Mockito.when(serviceREST.createService(rangerService)).thenReturn(rangerService); + RangerService dbRangerService = publicAPIsv2.createService(rangerService); + Assert.assertNotNull(dbRangerService); + Assert.assertEquals(dbRangerService, rangerService); + Assert.assertEquals(dbRangerService.getId(), rangerService.getId()); + Assert.assertEquals(dbRangerService.getName(), rangerService.getName()); + Mockito.verify(serviceREST).createService(rangerService); + } + + @Test + public void test13updateService() { + RangerService rangerService = rangerService(); + HttpServletRequest request = null; + Mockito.when(serviceREST.updateService(rangerService, request)).thenReturn(rangerService); + RangerService dbRangerService = publicAPIsv2.updateService(rangerService, Id, request); + Assert.assertNotNull(dbRangerService); + Assert.assertEquals(dbRangerService, rangerService); + Assert.assertEquals(dbRangerService.getId(), + rangerService.getId()); + Assert.assertEquals(dbRangerService.getName(), + rangerService.getName()); + Mockito.verify(serviceREST).updateService(rangerService, request); + } + + @Test + public void test14updateServiceByName() { + RangerService rangerService = rangerService(); + HttpServletRequest request = null; + String name = rangerService.getName(); + Mockito.when(serviceREST.getServiceByName(name)).thenReturn(rangerService); + Mockito.when(serviceREST.updateService(rangerService, request)).thenReturn(rangerService); + RangerService dbRangerService = publicAPIsv2.updateServiceByName(rangerService, name, request); + Assert.assertNotNull(dbRangerService); + Assert.assertEquals(dbRangerService, rangerService); + Assert.assertEquals(dbRangerService.getId(), rangerService.getId()); + Assert.assertEquals(dbRangerService.getName(), rangerService.getName()); + Mockito.verify(serviceREST).updateService(rangerService, request); + Mockito.verify(serviceREST).getServiceByName(name); + } + + @Test + public void test15deleteService() { + Mockito.doNothing().when(serviceREST).deleteService(Id); + publicAPIsv2.deleteService(Id); + Mockito.verify(serviceREST).deleteService(Id); + } + + @Test + public void test16deleteServiceByName() { + RangerService rangerService = rangerService(); + String name = rangerService.getName(); + Mockito.when(serviceREST.getServiceByName(name)).thenReturn(rangerService); + Mockito.doNothing().when(serviceREST).deleteService(rangerService.getId()); + publicAPIsv2.deleteServiceByName(name); + Mockito.verify(serviceREST).deleteService(rangerService.getId()); + Mockito.verify(serviceREST).getServiceByName(name); + } + + @Test + public void test17getPolicy() { + RangerPolicy rangerPolicy = rangerPolicy(); + Mockito.when(serviceREST.getPolicy(rangerPolicy.getId())).thenReturn(rangerPolicy); + RangerPolicy dbRangerPolicy = publicAPIsv2.getPolicy(Id); + Assert.assertNotNull(dbRangerPolicy); + Assert.assertEquals(dbRangerPolicy, rangerPolicy); + Assert.assertEquals(dbRangerPolicy.getId(), rangerPolicy.getId()); + Assert.assertEquals(dbRangerPolicy.getName(), rangerPolicy.getName()); + Mockito.verify(serviceREST).getPolicy(Id); + } - private static Long Id = 8L; - - private static Long Id2 =10L; - - @InjectMocks - PublicAPIsv2 publicAPIsv2 = new PublicAPIsv2(); - - @Mock - ServiceREST serviceREST; - - @Mock - RangerSearchUtil searchUtil; - - @Mock - RangerPolicyService policyService; - - @Mock - RESTErrorUtil restErrorUtil; - - @Mock - SecurityZoneDBStore securityZoneStore; - - @Rule - public ExpectedException thrown = ExpectedException.none(); - - @Before - public void setup() throws Exception { - RangerSecurityContext context = new RangerSecurityContext(); - context.setUserSession(new UserSessionBase()); - RangerContextHolder.setSecurityContext(context); - UserSessionBase currentUserSession = ContextUtil - .getCurrentUserSession(); - currentUserSession.setUserAdmin(true); - } - - private RangerServiceDef rangerServiceDef() { - List configs = new ArrayList(); - List resources = new ArrayList(); - List accessTypes = new ArrayList(); - List policyConditions = new ArrayList(); - List contextEnrichers = new ArrayList(); - List enums = new ArrayList(); - - RangerServiceDef rangerServiceDef = new RangerServiceDef(); - rangerServiceDef.setId(Id); - rangerServiceDef.setName("RangerServiceHdfs"); - rangerServiceDef.setImplClass("RangerServiceHdfs"); - rangerServiceDef.setLabel("HDFS Repository"); - rangerServiceDef.setDescription("HDFS Repository"); - rangerServiceDef.setRbKeyDescription(null); - rangerServiceDef.setUpdatedBy("Admin"); - rangerServiceDef.setUpdateTime(new Date()); - rangerServiceDef.setConfigs(configs); - rangerServiceDef.setResources(resources); - rangerServiceDef.setAccessTypes(accessTypes); - rangerServiceDef.setPolicyConditions(policyConditions); - rangerServiceDef.setContextEnrichers(contextEnrichers); - rangerServiceDef.setEnums(enums); - - return rangerServiceDef; - } - - private RangerService rangerService() { - Map configs = new HashMap(); - configs.put("username", "servicemgr"); - configs.put("password", "servicemgr"); - configs.put("namenode", "servicemgr"); - configs.put("hadoop.security.authorization", "No"); - configs.put("hadoop.security.authentication", "Simple"); - configs.put("hadoop.security.auth_to_local", ""); - configs.put("dfs.datanode.kerberos.principal", ""); - configs.put("dfs.namenode.kerberos.principal", ""); - configs.put("dfs.secondary.namenode.kerberos.principal", ""); - configs.put("hadoop.rpc.protection", "Privacy"); - configs.put("commonNameForCertificate", ""); - - RangerService rangerService = new RangerService(); - rangerService.setId(Id); - rangerService.setConfigs(configs); - rangerService.setCreateTime(new Date()); - rangerService.setDescription("service policy"); - rangerService.setGuid("1427365526516_835_0"); - rangerService.setIsEnabled(true); - rangerService.setName("HDFS_1"); - rangerService.setPolicyUpdateTime(new Date()); - rangerService.setType("1"); - rangerService.setUpdatedBy("Admin"); - rangerService.setUpdateTime(new Date()); - - return rangerService; - } - - private RangerPolicy rangerPolicy() { - List accesses = new ArrayList(); - List users = new ArrayList(); - List groups = new ArrayList(); - List conditions = new ArrayList(); - List policyItems = new ArrayList(); - RangerPolicyItem rangerPolicyItem = new RangerPolicyItem(); - rangerPolicyItem.setAccesses(accesses); - rangerPolicyItem.setConditions(conditions); - rangerPolicyItem.setGroups(groups); - rangerPolicyItem.setUsers(users); - rangerPolicyItem.setDelegateAdmin(false); - - policyItems.add(rangerPolicyItem); - - Map policyResource = new HashMap(); - RangerPolicyResource rangerPolicyResource = new RangerPolicyResource(); - rangerPolicyResource.setIsExcludes(true); - rangerPolicyResource.setIsRecursive(true); - rangerPolicyResource.setValue("1"); - rangerPolicyResource.setValues(users); - policyResource.put("resource", rangerPolicyResource); - RangerPolicy policy = new RangerPolicy(); - policy.setId(Id); - policy.setCreateTime(new Date()); - policy.setDescription("policy"); - policy.setGuid("policyguid"); - policy.setIsEnabled(true); - policy.setName("HDFS_1-1-20150316062453"); - policy.setUpdatedBy("Admin"); - policy.setUpdateTime(new Date()); - policy.setService("HDFS_1-1-20150316062453"); - policy.setIsAuditEnabled(true); - policy.setPolicyItems(policyItems); - policy.setResources(policyResource); - policy.setService("HDFS_1"); - - return policy; - } - - private RangerPolicy rangerPolicy1() { - List accesses = new ArrayList(); - List users = new ArrayList(); - List groups = new ArrayList(); - List conditions = new ArrayList(); - List policyItems = new ArrayList(); - RangerPolicyItem rangerPolicyItem = new RangerPolicyItem(); - rangerPolicyItem.setAccesses(accesses); - rangerPolicyItem.setConditions(conditions); - rangerPolicyItem.setGroups(groups); - rangerPolicyItem.setUsers(users); - rangerPolicyItem.setDelegateAdmin(false); - - policyItems.add(rangerPolicyItem); - - Map policyResource = new HashMap(); - RangerPolicyResource rangerPolicyResource = new RangerPolicyResource(); - rangerPolicyResource.setIsExcludes(true); - rangerPolicyResource.setIsRecursive(true); - rangerPolicyResource.setValue("2"); - rangerPolicyResource.setValues(users); - policyResource.put("resource", rangerPolicyResource); - RangerPolicy policy = new RangerPolicy(); - policy.setId(Id2); - policy.setCreateTime(new Date()); - policy.setDescription("policy"); - policy.setGuid("policyguid"); - policy.setIsEnabled(true); - policy.setName("HDFS_1-1-20150316062454"); - policy.setUpdatedBy("Admin"); - policy.setUpdateTime(new Date()); - policy.setService("HDFS_1-1-20150316062454"); - policy.setIsAuditEnabled(true); - policy.setPolicyItems(policyItems); - policy.setResources(policyResource); - policy.setService("HDFS_2"); - - return policy; - } - - @Test - public void test1getServiceDef() throws Exception { - RangerServiceDef rangerServiceDef = rangerServiceDef(); - Mockito.when(serviceREST.getServiceDef(rangerServiceDef.getId())).thenReturn(rangerServiceDef); - RangerServiceDef dbRangerServiceDef = publicAPIsv2.getServiceDef(Id); - Assert.assertNotNull(dbRangerServiceDef); - Assert.assertEquals(dbRangerServiceDef, rangerServiceDef); - Assert.assertEquals(dbRangerServiceDef.getId(), - rangerServiceDef.getId()); - Assert.assertEquals(dbRangerServiceDef.getName(), - rangerServiceDef.getName()); - Mockito.verify(serviceREST).getServiceDef(Id); - } - - @Test - public void test2getServiceDefByName() throws Exception { - RangerServiceDef rangerServiceDef = rangerServiceDef(); - String name = rangerServiceDef.getName(); - Mockito.when(serviceREST.getServiceDefByName(name)).thenReturn(rangerServiceDef); - RangerServiceDef dbRangerServiceDef = publicAPIsv2.getServiceDefByName(name); - Assert.assertNotNull(dbRangerServiceDef); - Assert.assertEquals(dbRangerServiceDef, rangerServiceDef); - Assert.assertEquals(dbRangerServiceDef.getId(), - rangerServiceDef.getId()); - Assert.assertEquals(dbRangerServiceDef.getName(), - rangerServiceDef.getName()); - Mockito.verify(serviceREST).getServiceDefByName(name); - } - - @Test - public void test3searchServiceDefs() throws Exception { - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - List serviceDefsList = new ArrayList(); - RangerServiceDef serviceDef = rangerServiceDef(); - serviceDefsList.add(serviceDef); - RangerServiceDefList serviceDefList = new RangerServiceDefList(serviceDefsList); - Mockito.when(serviceREST.getServiceDefs(request)).thenReturn(serviceDefList); - List dbRangerServiceDefList = publicAPIsv2.searchServiceDefs(request); - Assert.assertNotNull(dbRangerServiceDefList); - Assert.assertEquals(dbRangerServiceDefList.size(), serviceDefsList.size()); - Mockito.verify(serviceREST).getServiceDefs(request); - } - - @Test - public void test4createServiceDef() throws Exception { - RangerServiceDef rangerServiceDef = rangerServiceDef(); - Mockito.when(serviceREST.createServiceDef(rangerServiceDef)).thenReturn(rangerServiceDef); - RangerServiceDef dbRangerServiceDef = publicAPIsv2.createServiceDef(rangerServiceDef); - Assert.assertNotNull(dbRangerServiceDef); - Assert.assertEquals(dbRangerServiceDef, rangerServiceDef); - Assert.assertEquals(dbRangerServiceDef.getId(), - rangerServiceDef.getId()); - Assert.assertEquals(dbRangerServiceDef.getName(), - rangerServiceDef.getName()); - Mockito.verify(serviceREST).createServiceDef(rangerServiceDef); - } - - @Test - public void test5updateServiceDef() throws Exception { - RangerServiceDef rangerServiceDef = rangerServiceDef(); - Mockito.when(serviceREST.updateServiceDef(rangerServiceDef, rangerServiceDef.getId())).thenReturn(rangerServiceDef); - RangerServiceDef dbRangerServiceDef = publicAPIsv2.updateServiceDef(rangerServiceDef, Id); - Assert.assertNotNull(dbRangerServiceDef); - Assert.assertEquals(dbRangerServiceDef, rangerServiceDef); - Assert.assertEquals(dbRangerServiceDef.getId(), - rangerServiceDef.getId()); - Assert.assertEquals(dbRangerServiceDef.getName(), - rangerServiceDef.getName()); - Mockito.verify(serviceREST).updateServiceDef(rangerServiceDef, rangerServiceDef.getId()); - } - - @Test - public void test6updateServiceDefByName() throws Exception { - RangerServiceDef rangerServiceDef = rangerServiceDef(); - String name = rangerServiceDef.getName(); - Mockito.when(serviceREST.getServiceDefByName(name)).thenReturn(rangerServiceDef); - Mockito.when(serviceREST.updateServiceDef(rangerServiceDef, rangerServiceDef.getId())).thenReturn(rangerServiceDef); - RangerServiceDef dbRangerServiceDef = publicAPIsv2.updateServiceDefByName(rangerServiceDef, name); - Assert.assertNotNull(dbRangerServiceDef); - Assert.assertEquals(dbRangerServiceDef, rangerServiceDef); - Assert.assertEquals(dbRangerServiceDef.getId(), - rangerServiceDef.getId()); - Assert.assertEquals(dbRangerServiceDef.getName(), - rangerServiceDef.getName()); - Mockito.verify(serviceREST).updateServiceDef(rangerServiceDef, dbRangerServiceDef.getId()); - Mockito.verify(serviceREST).getServiceDefByName(name); - } - - @Test - public void test7deleteServiceDef() throws Exception { - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - Mockito.doNothing().when(serviceREST).deleteServiceDef(Id, request); - publicAPIsv2.deleteServiceDef(Id, request); - Mockito.verify(serviceREST).deleteServiceDef(Id, request); - } - - @Test - public void test8deleteServiceDefByName() throws Exception { - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - RangerServiceDef rangerServiceDef = rangerServiceDef(); - String name = rangerServiceDef.getName(); - Mockito.when(serviceREST.getServiceDefByName(name)).thenReturn(rangerServiceDef); - Mockito.doNothing().when(serviceREST).deleteServiceDef(rangerServiceDef.getId(), request); - publicAPIsv2.deleteServiceDefByName(name, request); - Mockito.verify(serviceREST).deleteServiceDef(rangerServiceDef.getId(), request); - Mockito.verify(serviceREST).getServiceDefByName(name); - } - - @Test - public void test9getService() throws Exception { - RangerService rangerService = rangerService(); - Mockito.when(serviceREST.getService(rangerService.getId())).thenReturn(rangerService); - RangerService dbRangerService = publicAPIsv2.getService(Id); - Assert.assertNotNull(dbRangerService); - Assert.assertEquals(dbRangerService, rangerService); - Assert.assertEquals(dbRangerService.getId(), - rangerService.getId()); - Assert.assertEquals(dbRangerService.getName(), - rangerService.getName()); - Mockito.verify(serviceREST).getService(Id); - } - - @Test - public void test10getServiceByName() throws Exception { - RangerService rangerService = rangerService(); - String name = rangerService.getName(); - Mockito.when(serviceREST.getServiceByName(name)).thenReturn(rangerService); - RangerService dbRangerService = publicAPIsv2.getServiceByName(name); - Assert.assertNotNull(dbRangerService); - Assert.assertEquals(dbRangerService, rangerService); - Assert.assertEquals(dbRangerService.getId(), - rangerService.getId()); - Assert.assertEquals(dbRangerService.getName(), - rangerService.getName()); - Mockito.verify(serviceREST).getServiceByName(name); - } - - @Test - public void test11searchServices() throws Exception { - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - List servicesList = new ArrayList(); - RangerService service = rangerService(); - servicesList.add(service); - RangerServiceList serviceList = new RangerServiceList(servicesList); - Mockito.when(serviceREST.getServices(request)).thenReturn(serviceList); - List dbRangerServiceList = publicAPIsv2.searchServices(request); - Assert.assertNotNull(dbRangerServiceList); - Assert.assertEquals(dbRangerServiceList.size(), servicesList.size()); - Mockito.verify(serviceREST).getServices(request); - } - - @Test - public void test12createService() throws Exception { - RangerService rangerService = rangerService(); - Mockito.when(serviceREST.createService(rangerService)).thenReturn(rangerService); - RangerService dbRangerService = publicAPIsv2.createService(rangerService); - Assert.assertNotNull(dbRangerService); - Assert.assertEquals(dbRangerService, rangerService); - Assert.assertEquals(dbRangerService.getId(), - rangerService.getId()); - Assert.assertEquals(dbRangerService.getName(), - rangerService.getName()); - Mockito.verify(serviceREST).createService(rangerService); - } - - @Test - public void test13updateService() throws Exception { - RangerService rangerService = rangerService(); - HttpServletRequest request = null; - Mockito.when(serviceREST.updateService(rangerService, request)).thenReturn(rangerService); - RangerService dbRangerService = publicAPIsv2.updateService(rangerService, Id, request); - Assert.assertNotNull(dbRangerService); - Assert.assertEquals(dbRangerService, rangerService); - Assert.assertEquals(dbRangerService.getId(), - rangerService.getId()); - Assert.assertEquals(dbRangerService.getName(), - rangerService.getName()); - Mockito.verify(serviceREST).updateService(rangerService, request); - } - - @Test - public void test14updateServiceByName() throws Exception { - RangerService rangerService = rangerService(); - HttpServletRequest request = null; - String name = rangerService.getName(); - Mockito.when(serviceREST.getServiceByName(name)).thenReturn(rangerService); - Mockito.when(serviceREST.updateService(rangerService, request)).thenReturn(rangerService); - RangerService dbRangerService = publicAPIsv2.updateServiceByName(rangerService, name, request); - Assert.assertNotNull(dbRangerService); - Assert.assertEquals(dbRangerService, rangerService); - Assert.assertEquals(dbRangerService.getId(), - rangerService.getId()); - Assert.assertEquals(dbRangerService.getName(), - rangerService.getName()); - Mockito.verify(serviceREST).updateService(rangerService, request); - Mockito.verify(serviceREST).getServiceByName(name); - } - - @Test - public void test15deleteService() throws Exception { - Mockito.doNothing().when(serviceREST).deleteService(Id); - publicAPIsv2.deleteService(Id); - Mockito.verify(serviceREST).deleteService(Id); - } - - @Test - public void test16deleteServiceByName() throws Exception { - RangerService rangerService = rangerService(); - String name = rangerService.getName(); - Mockito.when(serviceREST.getServiceByName(name)).thenReturn(rangerService); - Mockito.doNothing().when(serviceREST).deleteService(rangerService.getId()); - publicAPIsv2.deleteServiceByName(name); - Mockito.verify(serviceREST).deleteService(rangerService.getId()); - Mockito.verify(serviceREST).getServiceByName(name); - } - - @Test - public void test17getPolicy() throws Exception { - RangerPolicy rangerPolicy = rangerPolicy(); - Mockito.when(serviceREST.getPolicy(rangerPolicy.getId())).thenReturn(rangerPolicy); - RangerPolicy dbRangerPolicy = publicAPIsv2.getPolicy(Id); - Assert.assertNotNull(dbRangerPolicy); - Assert.assertEquals(dbRangerPolicy, rangerPolicy); - Assert.assertEquals(dbRangerPolicy.getId(), - rangerPolicy.getId()); - Assert.assertEquals(dbRangerPolicy.getName(), - rangerPolicy.getName()); - Mockito.verify(serviceREST).getPolicy(Id); - } - - @Test - public void test18getPolicyByName() throws Exception { - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - RangerPolicy rangerPolicy = rangerPolicy(); - RangerService rangerService = rangerService(); - String serviceName = rangerService.getName(); - String policyName = rangerPolicy.getName(); - String zoneName = "zone-1"; - Mockito.when(serviceREST.getPolicyByName(Mockito.anyString(),Mockito.anyString(),Mockito.anyString())).thenReturn(rangerPolicy); - RangerPolicy dbRangerPolicy = publicAPIsv2.getPolicyByName(serviceName, policyName, zoneName, request); - Assert.assertNotNull(dbRangerPolicy); - Assert.assertEquals(dbRangerPolicy, rangerPolicy); - Assert.assertEquals(dbRangerPolicy.getId(), - rangerPolicy.getId()); - Assert.assertEquals(dbRangerPolicy.getName(), - rangerPolicy.getName()); - Mockito.verify(serviceREST).getPolicyByName(Mockito.anyString(),Mockito.anyString(),Mockito.anyString()); - } - - @Test - public void test19searchPolicies() throws Exception { - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - List policiesList = new ArrayList(); - RangerService service = rangerService(); - String serviceName = service.getName(); - RangerPolicy rangerPolicy = rangerPolicy(); - policiesList.add(rangerPolicy); - RangerPolicyList policyList = new RangerPolicyList(policiesList); - Mockito.when(serviceREST.getServicePoliciesByName(serviceName, request)).thenReturn(policyList); - List dbRangerPolicyList = publicAPIsv2.searchPolicies(serviceName, request); - Assert.assertNotNull(dbRangerPolicyList); - Assert.assertEquals(dbRangerPolicyList.size(), policiesList.size()); - Mockito.verify(serviceREST).getServicePoliciesByName(serviceName, request); - } - - @Test - public void test20createPolicy() throws Exception { - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - RangerPolicy rangerPolicy = rangerPolicy(); - Mockito.when(serviceREST.createPolicy(rangerPolicy, request)).thenReturn(rangerPolicy); - RangerPolicy dbRangerPolicy = publicAPIsv2.createPolicy(rangerPolicy, request); - Assert.assertNotNull(dbRangerPolicy); - Assert.assertEquals(dbRangerPolicy, rangerPolicy); - Assert.assertEquals(dbRangerPolicy.getId(), - rangerPolicy.getId()); - Assert.assertEquals(dbRangerPolicy.getName(), - rangerPolicy.getName()); - Mockito.verify(serviceREST).createPolicy(rangerPolicy, request); - } - - @Test - public void test21applyPolicy() throws Exception { - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - RangerPolicy rangerPolicy = rangerPolicy(); - Mockito.when(serviceREST.applyPolicy(rangerPolicy, request)).thenReturn(rangerPolicy); - RangerPolicy dbRangerPolicy = publicAPIsv2.applyPolicy(rangerPolicy, request); - Assert.assertNotNull(dbRangerPolicy); - Assert.assertEquals(dbRangerPolicy, rangerPolicy); - Assert.assertEquals(dbRangerPolicy.getId(), - rangerPolicy.getId()); - Assert.assertEquals(dbRangerPolicy.getName(), - rangerPolicy.getName()); - Mockito.verify(serviceREST).applyPolicy(rangerPolicy, request); - } - - @Test - public void test22updatePolicy() throws Exception { - RangerPolicy rangerPolicy = rangerPolicy(); - Mockito.when(serviceREST.updatePolicy(rangerPolicy, Id)).thenReturn(rangerPolicy); - RangerPolicy dbRangerPolicy = publicAPIsv2.updatePolicy(rangerPolicy, Id); - Assert.assertNotNull(dbRangerPolicy); - Assert.assertEquals(dbRangerPolicy, rangerPolicy); - Assert.assertEquals(dbRangerPolicy.getId(), - rangerPolicy.getId()); - Assert.assertEquals(dbRangerPolicy.getName(), - rangerPolicy.getName()); - Mockito.verify(serviceREST).updatePolicy(rangerPolicy, Id); - } - - @Test - public void test23updatePolicyByName() throws Exception { - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - RangerPolicy rangerPolicy = rangerPolicy(); - String policyName = rangerPolicy.getName(); - RangerService rangerService = rangerService(); - String serviceName = rangerService.getName(); - String zoneName = "zone-1"; - Mockito.when(serviceREST.getPolicyByName(Mockito.anyString(),Mockito.anyString(),Mockito.anyString())).thenReturn(rangerPolicy); - Mockito.when(serviceREST.updatePolicy(rangerPolicy, rangerPolicy.getId())).thenReturn(rangerPolicy); - RangerPolicy dbRangerPolicy = publicAPIsv2.updatePolicyByName(rangerPolicy, serviceName, policyName, zoneName, request); - Assert.assertNotNull(dbRangerPolicy); - Assert.assertEquals(dbRangerPolicy, rangerPolicy); - Assert.assertEquals(dbRangerPolicy.getId(), - rangerPolicy.getId()); - Assert.assertEquals(dbRangerPolicy.getName(), - rangerPolicy.getName()); - Mockito.verify(serviceREST).updatePolicy(rangerPolicy, rangerPolicy.getId()); - Mockito.verify(serviceREST).getPolicyByName(Mockito.anyString(),Mockito.anyString(),Mockito.anyString()); - } - - @Test - public void test24deletePolicy() throws Exception { - Mockito.doNothing().when(serviceREST).deletePolicy(Id); - publicAPIsv2.deletePolicy(Id); - Mockito.verify(serviceREST).deletePolicy(Id); - } - - @Test - public void test25deletePolicyByName() throws Exception { - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - RangerPolicy rangerPolicy = rangerPolicy(); - String policyName = rangerPolicy.getName(); - RangerService rangerService = rangerService(); - String serviceName = rangerService.getName(); - String zoneName = "zone-1"; - Mockito.when(serviceREST.getPolicyByName(Mockito.anyString(),Mockito.anyString(),Mockito.anyString())).thenReturn(rangerPolicy); - Mockito.doNothing().when(serviceREST).deletePolicy(Id); - publicAPIsv2.deletePolicyByName(serviceName, policyName, zoneName, request); - Mockito.verify(serviceREST).getPolicyByName(Mockito.anyString(),Mockito.anyString(),Mockito.anyString()); - Mockito.verify(serviceREST).deletePolicy(Id); - } - - @Test - public void test26getPolicies() throws Exception { - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - RangerPolicyList policyList = Mockito.mock(RangerPolicyList.class); - List rangerPolicies = new ArrayList(); - RangerPolicy rangerpolicy1 = rangerPolicy(); - RangerPolicy rangerpolicy2 = rangerPolicy1(); - rangerPolicies.add(rangerpolicy1); - rangerPolicies.add(rangerpolicy2); - Mockito.when(serviceREST.getPolicies(request)).thenReturn(policyList); - Mockito.when(policyList.getPolicies()).thenReturn(rangerPolicies); - List dbRangerPolicies = publicAPIsv2.getPolicies(request); - Assert.assertNotNull(dbRangerPolicies); - Assert.assertEquals(dbRangerPolicies.size(), rangerPolicies.size()); - Mockito.verify(serviceREST).getPolicies(request); - } - - @Test - public void testGetAllZoneNames() throws Exception { - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + @Test + public void test18getPolicyByName() { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + RangerPolicy rangerPolicy = rangerPolicy(); + RangerService rangerService = rangerService(); + String serviceName = rangerService.getName(); + String policyName = rangerPolicy.getName(); + String zoneName = "zone-1"; + Mockito.when(serviceREST.getPolicyByName(Mockito.anyString(), Mockito.anyString(), Mockito.anyString())).thenReturn(rangerPolicy); + RangerPolicy dbRangerPolicy = publicAPIsv2.getPolicyByName(serviceName, policyName, zoneName, request); + Assert.assertNotNull(dbRangerPolicy); + Assert.assertEquals(dbRangerPolicy, rangerPolicy); + Assert.assertEquals(dbRangerPolicy.getId(), + rangerPolicy.getId()); + Assert.assertEquals(dbRangerPolicy.getName(), + rangerPolicy.getName()); + Mockito.verify(serviceREST).getPolicyByName(Mockito.anyString(), Mockito.anyString(), Mockito.anyString()); + } + + @Test + public void test19searchPolicies() { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + List policiesList = new ArrayList<>(); + RangerService service = rangerService(); + String serviceName = service.getName(); + RangerPolicy rangerPolicy = rangerPolicy(); + policiesList.add(rangerPolicy); + RangerPolicyList policyList = new RangerPolicyList(policiesList); + Mockito.when(serviceREST.getServicePoliciesByName(serviceName, request)).thenReturn(policyList); + List dbRangerPolicyList = publicAPIsv2.searchPolicies(serviceName, request); + Assert.assertNotNull(dbRangerPolicyList); + Assert.assertEquals(dbRangerPolicyList.size(), policiesList.size()); + Mockito.verify(serviceREST).getServicePoliciesByName(serviceName, request); + } + + @Test + public void test20createPolicy() { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + RangerPolicy rangerPolicy = rangerPolicy(); + Mockito.when(serviceREST.createPolicy(rangerPolicy, request)).thenReturn(rangerPolicy); + RangerPolicy dbRangerPolicy = publicAPIsv2.createPolicy(rangerPolicy, request); + Assert.assertNotNull(dbRangerPolicy); + Assert.assertEquals(dbRangerPolicy, rangerPolicy); + Assert.assertEquals(dbRangerPolicy.getId(), rangerPolicy.getId()); + Assert.assertEquals(dbRangerPolicy.getName(), rangerPolicy.getName()); + Mockito.verify(serviceREST).createPolicy(rangerPolicy, request); + } + + @Test + public void test21applyPolicy() { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + RangerPolicy rangerPolicy = rangerPolicy(); + Mockito.when(serviceREST.applyPolicy(rangerPolicy, request)).thenReturn(rangerPolicy); + RangerPolicy dbRangerPolicy = publicAPIsv2.applyPolicy(rangerPolicy, request); + Assert.assertNotNull(dbRangerPolicy); + Assert.assertEquals(dbRangerPolicy, rangerPolicy); + Assert.assertEquals(dbRangerPolicy.getId(), rangerPolicy.getId()); + Assert.assertEquals(dbRangerPolicy.getName(), rangerPolicy.getName()); + Mockito.verify(serviceREST).applyPolicy(rangerPolicy, request); + } + + @Test + public void test22updatePolicy() { + RangerPolicy rangerPolicy = rangerPolicy(); + Mockito.when(serviceREST.updatePolicy(rangerPolicy, Id)).thenReturn(rangerPolicy); + RangerPolicy dbRangerPolicy = publicAPIsv2.updatePolicy(rangerPolicy, Id); + Assert.assertNotNull(dbRangerPolicy); + Assert.assertEquals(dbRangerPolicy, rangerPolicy); + Assert.assertEquals(dbRangerPolicy.getId(), rangerPolicy.getId()); + Assert.assertEquals(dbRangerPolicy.getName(), rangerPolicy.getName()); + Mockito.verify(serviceREST).updatePolicy(rangerPolicy, Id); + } + + @Test + public void test23updatePolicyByName() { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + RangerPolicy rangerPolicy = rangerPolicy(); + String policyName = rangerPolicy.getName(); + RangerService rangerService = rangerService(); + String serviceName = rangerService.getName(); + String zoneName = "zone-1"; + Mockito.when(serviceREST.getPolicyByName(Mockito.anyString(), Mockito.anyString(), Mockito.anyString())).thenReturn(rangerPolicy); + Mockito.when(serviceREST.updatePolicy(rangerPolicy, rangerPolicy.getId())).thenReturn(rangerPolicy); + RangerPolicy dbRangerPolicy = publicAPIsv2.updatePolicyByName(rangerPolicy, serviceName, policyName, zoneName, request); + Assert.assertNotNull(dbRangerPolicy); + Assert.assertEquals(dbRangerPolicy, rangerPolicy); + Assert.assertEquals(dbRangerPolicy.getId(), rangerPolicy.getId()); + Assert.assertEquals(dbRangerPolicy.getName(), rangerPolicy.getName()); + Mockito.verify(serviceREST).updatePolicy(rangerPolicy, rangerPolicy.getId()); + Mockito.verify(serviceREST).getPolicyByName(Mockito.anyString(), Mockito.anyString(), Mockito.anyString()); + } + + @Test + public void test24deletePolicy() { + Mockito.doNothing().when(serviceREST).deletePolicy(Id); + publicAPIsv2.deletePolicy(Id); + Mockito.verify(serviceREST).deletePolicy(Id); + } + + @Test + public void test25deletePolicyByName() { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + RangerPolicy rangerPolicy = rangerPolicy(); + String policyName = rangerPolicy.getName(); + RangerService rangerService = rangerService(); + String serviceName = rangerService.getName(); + String zoneName = "zone-1"; + Mockito.when(serviceREST.getPolicyByName(Mockito.anyString(), Mockito.anyString(), Mockito.anyString())).thenReturn(rangerPolicy); + Mockito.doNothing().when(serviceREST).deletePolicy(Id); + publicAPIsv2.deletePolicyByName(serviceName, policyName, zoneName, request); + Mockito.verify(serviceREST).getPolicyByName(Mockito.anyString(), Mockito.anyString(), Mockito.anyString()); + Mockito.verify(serviceREST).deletePolicy(Id); + } + + @Test + public void test26getPolicies() { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + RangerPolicyList policyList = Mockito.mock(RangerPolicyList.class); + List rangerPolicies = new ArrayList<>(); + RangerPolicy rangerpolicy1 = rangerPolicy(); + RangerPolicy rangerpolicy2 = rangerPolicy1(); + rangerPolicies.add(rangerpolicy1); + rangerPolicies.add(rangerpolicy2); + Mockito.when(serviceREST.getPolicies(request)).thenReturn(policyList); + Mockito.when(policyList.getPolicies()).thenReturn(rangerPolicies); + List dbRangerPolicies = publicAPIsv2.getPolicies(request); + Assert.assertNotNull(dbRangerPolicies); + Assert.assertEquals(dbRangerPolicies.size(), rangerPolicies.size()); + Mockito.verify(serviceREST).getPolicies(request); + } + + @Test + public void testGetAllZoneNames() { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); List zoneHeaderInfoList = new ArrayList<>(); zoneHeaderInfoList.add(new RangerSecurityZoneHeaderInfo(2L, "zone-1")); @@ -627,13 +452,13 @@ public void testGetAllZoneNames() throws Exception { } @Test - public void testGetServiceNamesForZone() throws Exception { + public void testGetServiceNamesForZone() { Long zoneId1 = 2L; Long zoneId2 = 3L; Long nonExistingZondId = 101L; - List rangerServiceList1 = new ArrayList(); - List rangerServiceList2 = new ArrayList(); + List rangerServiceList1 = new ArrayList<>(); + List rangerServiceList2 = new ArrayList<>(); rangerServiceList1.add(new RangerServiceHeaderInfo(1L, "hdfs_1", false)); rangerServiceList1.add(new RangerServiceHeaderInfo(2L, "hive_1", false)); @@ -653,13 +478,13 @@ public void testGetServiceNamesForZone() throws Exception { List returnedServicesNull = publicAPIsv2.getServiceHeaderInfoListByZoneId(null, request); Mockito.verify(securityZoneStore, Mockito.times(1)).getServiceHeaderInfoListByZoneId(null, request); - Assert.assertEquals(returnedServicesNull.size(), 0); + Assert.assertEquals(0, returnedServicesNull.size()); // Non existing zoneId List returnedServicesNonExisting = publicAPIsv2.getServiceHeaderInfoListByZoneId(nonExistingZondId, request); Mockito.verify(securityZoneStore, Mockito.times(1)).getServiceHeaderInfoListByZoneId(null, request); - Assert.assertEquals(returnedServicesNonExisting.size(), 0); + Assert.assertEquals(0, returnedServicesNonExisting.size()); // zoneId1 List returnedServicesZone1 = publicAPIsv2.getServiceHeaderInfoListByZoneId(zoneId1, request); @@ -674,48 +499,185 @@ public void testGetServiceNamesForZone() throws Exception { Assert.assertEquals(returnedServicesZone2.size(), rangerServiceList2.size()); } - @Test - public void testGetPolicyByGUIDAndServiceNameAndZoneName() throws Exception { - RangerPolicy rangerPolicy = rangerPolicy(); - RangerService rangerService = rangerService(); - String serviceName = rangerService.getName(); - Mockito.when(serviceREST.getPolicyByGUIDAndServiceNameAndZoneName(rangerPolicy.getGuid(), serviceName, "zone-1")).thenReturn(rangerPolicy); - RangerPolicy dbRangerPolicy = publicAPIsv2.getPolicyByGUIDAndServiceNameAndZoneName(rangerPolicy.getGuid(), serviceName, "zone-1"); - Assert.assertNotNull(dbRangerPolicy); - Assert.assertEquals(dbRangerPolicy, rangerPolicy); - Assert.assertEquals(dbRangerPolicy.getId(), rangerPolicy.getId()); - Assert.assertEquals(dbRangerPolicy.getName(), rangerPolicy.getName()); - Mockito.verify(serviceREST).getPolicyByGUIDAndServiceNameAndZoneName(rangerPolicy.getGuid(), serviceName, "zone-1"); - } - - @Test - public void testGetPolicyByGUID() throws Exception { - RangerPolicy rangerPolicy = rangerPolicy(); - Mockito.when(serviceREST.getPolicyByGUIDAndServiceNameAndZoneName(rangerPolicy.getGuid(), null, null)).thenReturn(rangerPolicy); - RangerPolicy dbRangerPolicy = publicAPIsv2.getPolicyByGUIDAndServiceNameAndZoneName(rangerPolicy.getGuid(), null, null); - Assert.assertNotNull(dbRangerPolicy); - Assert.assertEquals(dbRangerPolicy, rangerPolicy); - Assert.assertEquals(dbRangerPolicy.getId(), rangerPolicy.getId()); - Assert.assertEquals(dbRangerPolicy.getName(), rangerPolicy.getName()); - Mockito.verify(serviceREST).getPolicyByGUIDAndServiceNameAndZoneName(rangerPolicy.getGuid(), null, null); - } - - @Test - public void testDeletePolicyByGUIDAndServiceNameAndZoneName() throws Exception { - RangerPolicy rangerPolicy = rangerPolicy(); - RangerService rangerService = rangerService(); - String serviceName = rangerService.getName(); - String zoneName = "zone-1"; - Mockito.doNothing().when(serviceREST).deletePolicyByGUIDAndServiceNameAndZoneName(rangerPolicy.getGuid(), serviceName, zoneName); - publicAPIsv2.deletePolicyByGUIDAndServiceNameAndZoneName(rangerPolicy.getGuid(), serviceName, zoneName); - Mockito.verify(serviceREST).deletePolicyByGUIDAndServiceNameAndZoneName(rangerPolicy.getGuid(), serviceName, zoneName); - } - - @Test - public void testDeletePolicyByGUID() throws Exception { - RangerPolicy rangerPolicy = rangerPolicy(); - Mockito.doNothing().when(serviceREST).deletePolicyByGUIDAndServiceNameAndZoneName(rangerPolicy.getGuid(), null, null); - publicAPIsv2.deletePolicyByGUIDAndServiceNameAndZoneName(rangerPolicy.getGuid(), null, null); - Mockito.verify(serviceREST).deletePolicyByGUIDAndServiceNameAndZoneName(rangerPolicy.getGuid(), null, null); - } + @Test + public void testGetPolicyByGUIDAndServiceNameAndZoneName() { + RangerPolicy rangerPolicy = rangerPolicy(); + RangerService rangerService = rangerService(); + String serviceName = rangerService.getName(); + Mockito.when(serviceREST.getPolicyByGUIDAndServiceNameAndZoneName(rangerPolicy.getGuid(), serviceName, "zone-1")).thenReturn(rangerPolicy); + RangerPolicy dbRangerPolicy = publicAPIsv2.getPolicyByGUIDAndServiceNameAndZoneName(rangerPolicy.getGuid(), serviceName, "zone-1"); + Assert.assertNotNull(dbRangerPolicy); + Assert.assertEquals(dbRangerPolicy, rangerPolicy); + Assert.assertEquals(dbRangerPolicy.getId(), rangerPolicy.getId()); + Assert.assertEquals(dbRangerPolicy.getName(), rangerPolicy.getName()); + Mockito.verify(serviceREST).getPolicyByGUIDAndServiceNameAndZoneName(rangerPolicy.getGuid(), serviceName, "zone-1"); + } + + @Test + public void testGetPolicyByGUID() { + RangerPolicy rangerPolicy = rangerPolicy(); + Mockito.when(serviceREST.getPolicyByGUIDAndServiceNameAndZoneName(rangerPolicy.getGuid(), null, null)).thenReturn(rangerPolicy); + RangerPolicy dbRangerPolicy = publicAPIsv2.getPolicyByGUIDAndServiceNameAndZoneName(rangerPolicy.getGuid(), null, null); + Assert.assertNotNull(dbRangerPolicy); + Assert.assertEquals(dbRangerPolicy, rangerPolicy); + Assert.assertEquals(dbRangerPolicy.getId(), rangerPolicy.getId()); + Assert.assertEquals(dbRangerPolicy.getName(), rangerPolicy.getName()); + Mockito.verify(serviceREST).getPolicyByGUIDAndServiceNameAndZoneName(rangerPolicy.getGuid(), null, null); + } + + @Test + public void testDeletePolicyByGUIDAndServiceNameAndZoneName() { + RangerPolicy rangerPolicy = rangerPolicy(); + RangerService rangerService = rangerService(); + String serviceName = rangerService.getName(); + String zoneName = "zone-1"; + Mockito.doNothing().when(serviceREST).deletePolicyByGUIDAndServiceNameAndZoneName(rangerPolicy.getGuid(), serviceName, zoneName); + publicAPIsv2.deletePolicyByGUIDAndServiceNameAndZoneName(rangerPolicy.getGuid(), serviceName, zoneName); + Mockito.verify(serviceREST).deletePolicyByGUIDAndServiceNameAndZoneName(rangerPolicy.getGuid(), serviceName, zoneName); + } + + @Test + public void testDeletePolicyByGUID() { + RangerPolicy rangerPolicy = rangerPolicy(); + Mockito.doNothing().when(serviceREST).deletePolicyByGUIDAndServiceNameAndZoneName(rangerPolicy.getGuid(), null, null); + publicAPIsv2.deletePolicyByGUIDAndServiceNameAndZoneName(rangerPolicy.getGuid(), null, null); + Mockito.verify(serviceREST).deletePolicyByGUIDAndServiceNameAndZoneName(rangerPolicy.getGuid(), null, null); + } + + private RangerServiceDef rangerServiceDef() { + List configs = new ArrayList<>(); + List resources = new ArrayList<>(); + List accessTypes = new ArrayList<>(); + List policyConditions = new ArrayList<>(); + List contextEnrichers = new ArrayList<>(); + List enums = new ArrayList<>(); + + RangerServiceDef rangerServiceDef = new RangerServiceDef(); + rangerServiceDef.setId(Id); + rangerServiceDef.setName("RangerServiceHdfs"); + rangerServiceDef.setImplClass("RangerServiceHdfs"); + rangerServiceDef.setLabel("HDFS Repository"); + rangerServiceDef.setDescription("HDFS Repository"); + rangerServiceDef.setRbKeyDescription(null); + rangerServiceDef.setUpdatedBy("Admin"); + rangerServiceDef.setUpdateTime(new Date()); + rangerServiceDef.setConfigs(configs); + rangerServiceDef.setResources(resources); + rangerServiceDef.setAccessTypes(accessTypes); + rangerServiceDef.setPolicyConditions(policyConditions); + rangerServiceDef.setContextEnrichers(contextEnrichers); + rangerServiceDef.setEnums(enums); + + return rangerServiceDef; + } + + private RangerService rangerService() { + Map configs = new HashMap<>(); + configs.put("username", "servicemgr"); + configs.put("password", "servicemgr"); + configs.put("namenode", "servicemgr"); + configs.put("hadoop.security.authorization", "No"); + configs.put("hadoop.security.authentication", "Simple"); + configs.put("hadoop.security.auth_to_local", ""); + configs.put("dfs.datanode.kerberos.principal", ""); + configs.put("dfs.namenode.kerberos.principal", ""); + configs.put("dfs.secondary.namenode.kerberos.principal", ""); + configs.put("hadoop.rpc.protection", "Privacy"); + configs.put("commonNameForCertificate", ""); + + RangerService rangerService = new RangerService(); + rangerService.setId(Id); + rangerService.setConfigs(configs); + rangerService.setCreateTime(new Date()); + rangerService.setDescription("service policy"); + rangerService.setGuid("1427365526516_835_0"); + rangerService.setIsEnabled(true); + rangerService.setName("HDFS_1"); + rangerService.setPolicyUpdateTime(new Date()); + rangerService.setType("1"); + rangerService.setUpdatedBy("Admin"); + rangerService.setUpdateTime(new Date()); + + return rangerService; + } + + private RangerPolicy rangerPolicy() { + List accesses = new ArrayList<>(); + List users = new ArrayList<>(); + List groups = new ArrayList<>(); + List conditions = new ArrayList<>(); + List policyItems = new ArrayList<>(); + RangerPolicyItem rangerPolicyItem = new RangerPolicyItem(); + rangerPolicyItem.setAccesses(accesses); + rangerPolicyItem.setConditions(conditions); + rangerPolicyItem.setGroups(groups); + rangerPolicyItem.setUsers(users); + rangerPolicyItem.setDelegateAdmin(false); + + policyItems.add(rangerPolicyItem); + + Map policyResource = new HashMap<>(); + RangerPolicyResource rangerPolicyResource = new RangerPolicyResource(); + rangerPolicyResource.setIsExcludes(true); + rangerPolicyResource.setIsRecursive(true); + rangerPolicyResource.setValue("1"); + rangerPolicyResource.setValues(users); + policyResource.put("resource", rangerPolicyResource); + RangerPolicy policy = new RangerPolicy(); + policy.setId(Id); + policy.setCreateTime(new Date()); + policy.setDescription("policy"); + policy.setGuid("policyguid"); + policy.setIsEnabled(true); + policy.setName("HDFS_1-1-20150316062453"); + policy.setUpdatedBy("Admin"); + policy.setUpdateTime(new Date()); + policy.setService("HDFS_1-1-20150316062453"); + policy.setIsAuditEnabled(true); + policy.setPolicyItems(policyItems); + policy.setResources(policyResource); + policy.setService("HDFS_1"); + + return policy; + } + + private RangerPolicy rangerPolicy1() { + List accesses = new ArrayList<>(); + List users = new ArrayList<>(); + List groups = new ArrayList<>(); + List conditions = new ArrayList<>(); + List policyItems = new ArrayList<>(); + RangerPolicyItem rangerPolicyItem = new RangerPolicyItem(); + rangerPolicyItem.setAccesses(accesses); + rangerPolicyItem.setConditions(conditions); + rangerPolicyItem.setGroups(groups); + rangerPolicyItem.setUsers(users); + rangerPolicyItem.setDelegateAdmin(false); + + policyItems.add(rangerPolicyItem); + + Map policyResource = new HashMap<>(); + RangerPolicyResource rangerPolicyResource = new RangerPolicyResource(); + rangerPolicyResource.setIsExcludes(true); + rangerPolicyResource.setIsRecursive(true); + rangerPolicyResource.setValue("2"); + rangerPolicyResource.setValues(users); + policyResource.put("resource", rangerPolicyResource); + RangerPolicy policy = new RangerPolicy(); + policy.setId(Id2); + policy.setCreateTime(new Date()); + policy.setDescription("policy"); + policy.setGuid("policyguid"); + policy.setIsEnabled(true); + policy.setName("HDFS_1-1-20150316062454"); + policy.setUpdatedBy("Admin"); + policy.setUpdateTime(new Date()); + policy.setService("HDFS_1-1-20150316062454"); + policy.setIsAuditEnabled(true); + policy.setPolicyItems(policyItems); + policy.setResources(policyResource); + policy.setService("HDFS_2"); + + return policy; + } } diff --git a/security-admin/src/test/java/org/apache/ranger/rest/TestRangerHealthREST.java b/security-admin/src/test/java/org/apache/ranger/rest/TestRangerHealthREST.java index e641c00b59..67ec1e17f2 100644 --- a/security-admin/src/test/java/org/apache/ranger/rest/TestRangerHealthREST.java +++ b/security-admin/src/test/java/org/apache/ranger/rest/TestRangerHealthREST.java @@ -17,11 +17,6 @@ package org.apache.ranger.rest; -import static org.apache.ranger.plugin.model.RangerServerHealth.RangerServerStatus.UP; - -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.Map; import org.apache.ranger.biz.RangerBizUtil; import org.apache.ranger.plugin.model.RangerServerHealth; import org.apache.ranger.util.RangerServerHealthUtil; @@ -35,18 +30,24 @@ import org.mockito.Mockito; import org.mockito.junit.MockitoJUnitRunner; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.Map; + +import static org.apache.ranger.plugin.model.RangerServerHealth.RangerServerStatus.UP; + @RunWith(MockitoJUnitRunner.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class TestRangerHealthREST { @Mock RangerServerHealthUtil rangerServerHealthUtil; @InjectMocks - RangerHealthREST rangerHealthREST = new RangerHealthREST(); + RangerHealthREST rangerHealthREST = new RangerHealthREST(); @Mock - RangerBizUtil xaBizUtil; + RangerBizUtil xaBizUtil; @Test - public void testHealthCheckStatusAPI() throws Exception { + public void testHealthCheckStatusAPI() { String dbVersion = "23.2.0"; Mockito.when(xaBizUtil.getDBVersion()).thenReturn(dbVersion); Mockito.when(rangerServerHealthUtil.getRangerServerHealth(dbVersion)).thenReturn(createRangerServerHealth()); @@ -58,21 +59,21 @@ public void testHealthCheckStatusAPI() throws Exception { private RangerServerHealth createRangerServerHealth() { Map componentsMap = new HashMap<>(); - Map dbMap = new LinkedHashMap<>(); + Map dbMap = new LinkedHashMap<>(); dbMap.put("status", UP); Map dbDetailsMap = new LinkedHashMap<>(); - dbDetailsMap.put("database","Oracle 21.3c"); - dbDetailsMap.put("validationQuery","SELECT banner from v$version where rownum<2"); - dbMap.put("details",dbDetailsMap); - componentsMap.put("db",dbMap); + dbDetailsMap.put("database", "Oracle 21.3c"); + dbDetailsMap.put("validationQuery", "SELECT banner from v$version where rownum<2"); + dbMap.put("details", dbDetailsMap); + componentsMap.put("db", dbMap); Map auditProviderMap = new LinkedHashMap<>(); auditProviderMap.put("status", UP); Map auditProviderDetailsMap = new LinkedHashMap<>(); - auditProviderDetailsMap.put("provider","Elastic Search"); - auditProviderDetailsMap.put("providerHealthCheckEndpoint","http://localhost:9200/_cluster/health?pretty"); + auditProviderDetailsMap.put("provider", "Elastic Search"); + auditProviderDetailsMap.put("providerHealthCheckEndpoint", "http://localhost:9200/_cluster/health?pretty"); auditProviderDetailsMap.put("details", auditProviderDetailsMap); - componentsMap.put("auditProvider",auditProviderMap); + componentsMap.put("auditProvider", auditProviderMap); RangerServerHealth rangerRServerHealth = RangerServerHealth.up().withDetail("components", componentsMap).build(); return rangerRServerHealth; } -} \ No newline at end of file +} diff --git a/security-admin/src/test/java/org/apache/ranger/rest/TestRoleREST.java b/security-admin/src/test/java/org/apache/ranger/rest/TestRoleREST.java index 175af395f5..ae2095d499 100644 --- a/security-admin/src/test/java/org/apache/ranger/rest/TestRoleREST.java +++ b/security-admin/src/test/java/org/apache/ranger/rest/TestRoleREST.java @@ -6,7 +6,7 @@ * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -16,12 +16,30 @@ */ package org.apache.ranger.rest; +import com.sun.jersey.core.header.FormDataContentDisposition; import org.apache.ranger.admin.client.datatype.RESTResponse; -import org.apache.ranger.biz.*; +import org.apache.ranger.biz.AssetMgr; +import org.apache.ranger.biz.RangerBizUtil; +import org.apache.ranger.biz.RoleDBStore; +import org.apache.ranger.biz.RoleRefUpdater; +import org.apache.ranger.biz.ServiceDBStore; import org.apache.ranger.biz.ServiceDBStore.JSON_FILE_NAME_TYPE; -import org.apache.ranger.common.*; -import org.apache.ranger.db.*; -import org.apache.ranger.entity.*; +import org.apache.ranger.biz.XUserMgr; +import org.apache.ranger.common.ContextUtil; +import org.apache.ranger.common.RESTErrorUtil; +import org.apache.ranger.common.RangerSearchUtil; +import org.apache.ranger.common.RangerValidatorFactory; +import org.apache.ranger.common.ServiceUtil; +import org.apache.ranger.common.UserSessionBase; +import org.apache.ranger.db.RangerDaoManager; +import org.apache.ranger.db.XXRoleDao; +import org.apache.ranger.db.XXRoleRefGroupDao; +import org.apache.ranger.db.XXRoleRefRoleDao; +import org.apache.ranger.db.XXRoleRefUserDao; +import org.apache.ranger.entity.XXPortalUser; +import org.apache.ranger.entity.XXRoleRefGroup; +import org.apache.ranger.entity.XXRoleRefUser; +import org.apache.ranger.entity.XXService; import org.apache.ranger.plugin.model.RangerPolicy; import org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyItem; import org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyResource; @@ -41,42 +59,53 @@ import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; -import org.mockito.*; +import org.mockito.AdditionalAnswers; +import org.mockito.Answers; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; import org.mockito.junit.MockitoJUnitRunner; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import java.util.*; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; -import com.sun.jersey.core.header.FormDataContentDisposition; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.Date; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; import static org.mockito.ArgumentMatchers.eq; - @RunWith(MockitoJUnitRunner.class) public class TestRoleREST { - private static final Long userId = 8L; - private static final Long roleId = 9L; - private static final String adminLoginID = "admin"; - private static final JSON_FILE_NAME_TYPE ROLE = JSON_FILE_NAME_TYPE.ROLE; - String importRoleTestFilePath = "./src/test/java/org/apache/ranger/rest/importRole/import_role_test_file.json"; - private static Long Id = 7L; + private static final Long userId = 8L; + private static final Long roleId = 9L; + private static final Long Id = 7L; + private static final String adminLoginID = "admin"; + private static final JSON_FILE_NAME_TYPE ROLE = JSON_FILE_NAME_TYPE.ROLE; + String importRoleTestFilePath = "./src/test/java/org/apache/ranger/rest/importRole/import_role_test_file.json"; @Mock RangerRole role; @Mock RESTErrorUtil restErrorUtil; @Mock - AssetMgr assetMgr; + AssetMgr assetMgr; @Mock(answer = Answers.RETURNS_DEEP_STUBS) - RangerDaoManager daoMgr; + RangerDaoManager daoMgr; @Mock - RoleDBStore roleStore; + RoleDBStore roleStore; @Mock RangerRoleService roleService; @@ -136,18 +165,17 @@ public void destroySession() { } @Test - public void test1CreateRole(){ + public void test1CreateRole() { boolean createNonExistUserGroup = true; Mockito.when(validatorFactory.getRangerRoleValidator(roleStore)).thenReturn(Mockito.mock(RangerRoleValidator.class)); Mockito.when(bizUtil.isUserRangerAdmin(Mockito.anyString())).thenReturn(true); RangerRole rangerRole = createRole(); try { - Mockito.when(roleStore.createRole(Mockito.any(RangerRole.class), eq(createNonExistUserGroup))). - thenReturn(rangerRole); + Mockito.when(roleStore.createRole(Mockito.any(RangerRole.class), eq(createNonExistUserGroup))).thenReturn(rangerRole); } catch (Exception e) { throw new RuntimeException(e); } - RangerRole createdRole = roleRest.createRole("admin", rangerRole ,createNonExistUserGroup); + RangerRole createdRole = roleRest.createRole("admin", rangerRole, createNonExistUserGroup); Assert.assertNotNull(createdRole); Assert.assertEquals(createdRole.getName(), rangerRole.getName()); Assert.assertEquals(createdRole.getDescription(), rangerRole.getDescription()); @@ -155,21 +183,21 @@ public void test1CreateRole(){ } @Test - public void test2UpdateRole(){ - Boolean createNonExistUserGroup = Boolean.TRUE; - RangerRole rangerRole = createRole(); - RangerRole rangerRoleOld = createRoleOld(); + public void test2UpdateRole() { + Boolean createNonExistUserGroup = Boolean.TRUE; + RangerRole rangerRole = createRole(); + RangerRole rangerRoleOld = createRoleOld(); Mockito.when(validatorFactory.getRangerRoleValidator(roleStore)).thenReturn(Mockito.mock(RangerRoleValidator.class)); XXRoleDao xxRoleDao = Mockito.mock(XXRoleDao.class); Mockito.when(daoMgr.getXXRole()).thenReturn(xxRoleDao); - Mockito.when(daoMgr.getXXPolicyRefRole().findRoleRefPolicyCount(Mockito.anyString())).thenReturn(0l); + Mockito.when(daoMgr.getXXPolicyRefRole().findRoleRefPolicyCount(Mockito.anyString())).thenReturn(0L); try { Mockito.when(roleStore.getRole(Mockito.anyLong())).thenReturn(rangerRoleOld); } catch (Exception e) { throw new RuntimeException(e); } try { - Mockito.when(roleStore.updateRole(Mockito.any(RangerRole.class),Mockito.anyBoolean())).thenReturn(rangerRole); + Mockito.when(roleStore.updateRole(Mockito.any(RangerRole.class), Mockito.anyBoolean())).thenReturn(rangerRole); } catch (Exception e) { throw new RuntimeException(e); } @@ -180,11 +208,11 @@ public void test2UpdateRole(){ } @Test - public void test3DeleteRoleByName(){ + public void test3DeleteRoleByName() { RangerRole rangerRole = createRole(); Mockito.doReturn(true).when(bizUtil).isUserRangerAdmin(Mockito.anyString()); Mockito.when(validatorFactory.getRangerRoleValidator(roleStore)).thenReturn(Mockito.mock(RangerRoleValidator.class)); - roleRest.deleteRole("admin", adminLoginID ,rangerRole.getName()); + roleRest.deleteRole("admin", adminLoginID, rangerRole.getName()); try { Mockito.verify(roleStore, Mockito.times(1)).deleteRole(Mockito.anyString()); } catch (Exception e) { @@ -193,7 +221,7 @@ public void test3DeleteRoleByName(){ } @Test - public void test4DeleteRoleById(){ + public void test4DeleteRoleById() { RangerRole rangerRole = createRole(); Mockito.doReturn(true).when(bizUtil).isUserRangerAdmin(Mockito.anyString()); Mockito.when(validatorFactory.getRangerRoleValidator(roleStore)).thenReturn(Mockito.mock(RangerRoleValidator.class)); @@ -206,7 +234,7 @@ public void test4DeleteRoleById(){ } @Test - public void test5GetRoleByName(){ + public void test5GetRoleByName() { RangerRole rangerRole = createRole(); Mockito.doReturn(true).when(bizUtil).isUserRangerAdmin(Mockito.anyString()); try { @@ -214,13 +242,13 @@ public void test5GetRoleByName(){ } catch (Exception e) { throw new RuntimeException(e); } - RangerRole returnedRole = roleRest.getRole("admin", adminLoginID ,rangerRole.getName()); + RangerRole returnedRole = roleRest.getRole("admin", adminLoginID, rangerRole.getName()); Assert.assertNotNull(returnedRole); Assert.assertEquals(returnedRole.getName(), rangerRole.getName()); } @Test - public void test6GetRoleById(){ + public void test6GetRoleById() { RangerRole rangerRole = createRole(); try { Mockito.when(roleStore.getRole(Mockito.anyLong())).thenReturn(rangerRole); @@ -234,10 +262,9 @@ public void test6GetRoleById(){ } @Test - public void test7GetAllRoles(){ + public void test7GetAllRoles() { RangerRoleList rangerRoleList = new RangerRoleList(); - Mockito.when(searchUtil.getSearchFilter(Mockito.any(HttpServletRequest.class), eq(roleService.sortFields))). - thenReturn(Mockito.mock(SearchFilter.class)); + Mockito.when(searchUtil.getSearchFilter(Mockito.any(HttpServletRequest.class), eq(roleService.sortFields))).thenReturn(Mockito.mock(SearchFilter.class)); Mockito.when(bizUtil.isUserRangerAdmin(Mockito.anyString())).thenReturn(true); RangerRoleList returnedRangerRoleList = roleRest.getAllRoles(Mockito.mock(HttpServletRequest.class)); Assert.assertNotNull(returnedRangerRoleList); @@ -245,20 +272,19 @@ public void test7GetAllRoles(){ } @Test - public void test8GetAllRolesForUser(){ + public void test8GetAllRolesForUser() { RangerRoleList rangerRoleList = new RangerRoleList(); - SearchFilter searchFilter = new SearchFilter(); - Mockito.when(searchUtil.getSearchFilter(Mockito.any(HttpServletRequest.class), eq(roleService.sortFields))). - thenReturn(searchFilter); + SearchFilter searchFilter = new SearchFilter(); + Mockito.when(searchUtil.getSearchFilter(Mockito.any(HttpServletRequest.class), eq(roleService.sortFields))).thenReturn(searchFilter); RangerRoleList returnedRangerRoleList = roleRest.getAllRolesForUser(Mockito.mock(HttpServletRequest.class)); Assert.assertNotNull(returnedRangerRoleList); Assert.assertEquals(returnedRangerRoleList.getListSize(), rangerRoleList.getListSize()); } + @Test - public void test9GetAllRoleNames(){ + public void test9GetAllRoleNames() { List roleList = createRoleList(); - Mockito.when(searchUtil.getSearchFilter(Mockito.any(HttpServletRequest.class), eq(roleService.sortFields))). - thenReturn(Mockito.mock(SearchFilter.class)); + Mockito.when(searchUtil.getSearchFilter(Mockito.any(HttpServletRequest.class), eq(roleService.sortFields))).thenReturn(Mockito.mock(SearchFilter.class)); Mockito.when(bizUtil.isUserRangerAdmin(Mockito.anyString())).thenReturn(true); try { Mockito.when(roleStore.getRoleNames(Mockito.any(SearchFilter.class))).thenReturn(roleList); @@ -269,12 +295,13 @@ public void test9GetAllRoleNames(){ Assert.assertNotNull(returnedRoleList); Assert.assertEquals(returnedRoleList.size(), roleList.size()); } + @Test - public void test10AddUsersAndGroups(){ - RangerRole rangerRole = createRole(); - List users = new ArrayList<>(Arrays.asList("test-role","admin")); - List groups = new ArrayList<>(Arrays.asList("group1","group2")); - Boolean isAdmin = true; + public void test10AddUsersAndGroups() { + RangerRole rangerRole = createRole(); + List users = new ArrayList<>(Arrays.asList("test-role", "admin")); + List groups = new ArrayList<>(Arrays.asList("group1", "group2")); + Boolean isAdmin = true; Mockito.when(bizUtil.isUserRangerAdmin(Mockito.anyString())).thenReturn(true); try { Mockito.when(roleStore.getRole(Mockito.anyLong())).thenReturn(rangerRole); @@ -282,8 +309,7 @@ public void test10AddUsersAndGroups(){ throw new RuntimeException(e); } try { - Mockito.when(roleStore.updateRole(Mockito.any(RangerRole.class),Mockito.anyBoolean())). - then(AdditionalAnswers.returnsFirstArg()); + Mockito.when(roleStore.updateRole(Mockito.any(RangerRole.class), Mockito.anyBoolean())).then(AdditionalAnswers.returnsFirstArg()); } catch (Exception e) { throw new RuntimeException(e); } @@ -292,17 +318,18 @@ public void test10AddUsersAndGroups(){ Assert.assertEquals(returnedRole.getUsers().size(), users.size()); Assert.assertEquals(returnedRole.getGroups().size(), groups.size()); } + @Test - public void test11RemoveUsersAndGroups(){ - RangerRole rangerRole = createRoleWithUsersAndGroups(); - List users = new ArrayList<>(Arrays.asList("test-role","admin")); - List groups = new ArrayList<>(Arrays.asList("test-group","admin")); + public void test11RemoveUsersAndGroups() { + RangerRole rangerRole = createRoleWithUsersAndGroups(); + List users = new ArrayList<>(Arrays.asList("test-role", "admin")); + List groups = new ArrayList<>(Arrays.asList("test-group", "admin")); List createdRoleUsers = new ArrayList<>(); - for(RangerRole.RoleMember roleMember : rangerRole.getUsers()){ + for (RangerRole.RoleMember roleMember : rangerRole.getUsers()) { createdRoleUsers.add(roleMember.getName()); } List createdRoleGroups = new ArrayList<>(); - for(RangerRole.RoleMember groupMember : rangerRole.getGroups()){ + for (RangerRole.RoleMember groupMember : rangerRole.getGroups()) { createdRoleGroups.add(groupMember.getName()); } Mockito.when(bizUtil.isUserRangerAdmin(Mockito.anyString())).thenReturn(true); @@ -312,36 +339,35 @@ public void test11RemoveUsersAndGroups(){ throw new RuntimeException(e); } try { - Mockito.when(roleStore.updateRole(Mockito.any(RangerRole.class),Mockito.anyBoolean())). - then(AdditionalAnswers.returnsFirstArg()); + Mockito.when(roleStore.updateRole(Mockito.any(RangerRole.class), Mockito.anyBoolean())).then(AdditionalAnswers.returnsFirstArg()); } catch (Exception e) { throw new RuntimeException(e); } RangerRole returnedRole = roleRest.removeUsersAndGroups(roleId, users, groups); Assert.assertNotNull(returnedRole); - Assert.assertEquals(createdRoleUsers,users); - Assert.assertEquals(createdRoleGroups,groups); - Assert.assertEquals(returnedRole.getUsers().size(), 0); - Assert.assertEquals(returnedRole.getGroups().size(), 0); + Assert.assertEquals(createdRoleUsers, users); + Assert.assertEquals(createdRoleGroups, groups); + Assert.assertEquals(0, returnedRole.getUsers().size()); + Assert.assertEquals(0, returnedRole.getGroups().size()); } @Test - public void test12RemoveAdminFromUsersAndGroups(){ + public void test12RemoveAdminFromUsersAndGroups() { RangerRole rangerRole = createRoleWithUsersAndGroups(); - for (RangerRole.RoleMember role: rangerRole.getUsers()){ + for (RangerRole.RoleMember role : rangerRole.getUsers()) { Assert.assertTrue(role.getIsAdmin()); } - for (RangerRole.RoleMember group: rangerRole.getGroups()){ + for (RangerRole.RoleMember group : rangerRole.getGroups()) { Assert.assertTrue(group.getIsAdmin()); } - List users = new ArrayList<>(Arrays.asList("test-role","admin")); - List groups = new ArrayList<>(Arrays.asList("test-group","admin")); + List users = new ArrayList<>(Arrays.asList("test-role", "admin")); + List groups = new ArrayList<>(Arrays.asList("test-group", "admin")); List createdRoleUsers = new ArrayList<>(); - for(RangerRole.RoleMember roleMember : rangerRole.getUsers()){ + for (RangerRole.RoleMember roleMember : rangerRole.getUsers()) { createdRoleUsers.add(roleMember.getName()); } List createdRoleGroups = new ArrayList<>(); - for(RangerRole.RoleMember groupMember : rangerRole.getGroups()){ + for (RangerRole.RoleMember groupMember : rangerRole.getGroups()) { createdRoleGroups.add(groupMember.getName()); } Mockito.when(bizUtil.isUserRangerAdmin(Mockito.anyString())).thenReturn(true); @@ -351,111 +377,102 @@ public void test12RemoveAdminFromUsersAndGroups(){ throw new RuntimeException(e); } try { - Mockito.when(roleStore.updateRole(Mockito.any(RangerRole.class),Mockito.anyBoolean())). - then(AdditionalAnswers.returnsFirstArg()); + Mockito.when(roleStore.updateRole(Mockito.any(RangerRole.class), Mockito.anyBoolean())).then(AdditionalAnswers.returnsFirstArg()); } catch (Exception e) { throw new RuntimeException(e); } RangerRole returnedRole = roleRest.removeAdminFromUsersAndGroups(roleId, users, groups); Assert.assertNotNull(returnedRole); - Assert.assertEquals(createdRoleUsers,users); - Assert.assertEquals(createdRoleGroups,groups); - for (RangerRole.RoleMember role: returnedRole.getUsers()){ + Assert.assertEquals(createdRoleUsers, users); + Assert.assertEquals(createdRoleGroups, groups); + for (RangerRole.RoleMember role : returnedRole.getUsers()) { Assert.assertFalse(role.getIsAdmin()); } - for (RangerRole.RoleMember group: returnedRole.getGroups()){ + for (RangerRole.RoleMember group : returnedRole.getGroups()) { Assert.assertFalse(group.getIsAdmin()); } } + @Test - public void test13GrantRole(){ - RangerRole rangerRole = createRole(); - String serviceName = "serviceName"; + public void test13GrantRole() { + RangerRole rangerRole = createRole(); + String serviceName = "serviceName"; GrantRevokeRoleRequest grantRevokeRoleRequest = createGrantRevokeRoleRequest(); - Mockito.when(bizUtil.isUserRangerAdmin(Mockito.anyString())).thenReturn(true,true,true); + Mockito.when(bizUtil.isUserRangerAdmin(Mockito.anyString())).thenReturn(true, true, true); try { - Mockito.when(roleStore.updateRole(Mockito.any(RangerRole.class),Mockito.anyBoolean())). - then(AdditionalAnswers.returnsFirstArg()); + Mockito.when(roleStore.updateRole(Mockito.any(RangerRole.class), Mockito.anyBoolean())).then(AdditionalAnswers.returnsFirstArg()); } catch (Exception e) { throw new RuntimeException(e); } try { - Mockito.when(roleStore.getRole(Mockito.anyString())).thenReturn(rangerRole,rangerRole,rangerRole,rangerRole); + Mockito.when(roleStore.getRole(Mockito.anyString())).thenReturn(rangerRole, rangerRole, rangerRole, rangerRole); } catch (Exception e) { throw new RuntimeException(e); } - RESTResponse resp = roleRest.grantRole(serviceName, grantRevokeRoleRequest, - Mockito.mock(HttpServletRequest.class)); + RESTResponse resp = roleRest.grantRole(serviceName, grantRevokeRoleRequest, Mockito.mock(HttpServletRequest.class)); Assert.assertNotNull(resp); - Assert.assertEquals(resp.getStatusCode(), RESTResponse.STATUS_SUCCESS); + Assert.assertEquals(RESTResponse.STATUS_SUCCESS, resp.getStatusCode()); } @Test - public void test14RevokeRole(){ - RangerRole rangerRole = createRole(); - String serviceName = "serviceName"; + public void test14RevokeRole() { + RangerRole rangerRole = createRole(); + String serviceName = "serviceName"; GrantRevokeRoleRequest grantRevokeRoleRequest = createGrantRevokeRoleRequest(); - Mockito.when(bizUtil.isUserRangerAdmin(Mockito.anyString())).thenReturn(true,true,true); + Mockito.when(bizUtil.isUserRangerAdmin(Mockito.anyString())).thenReturn(true, true, true); try { - Mockito.when(roleStore.getRole(Mockito.anyString())).thenReturn(rangerRole,rangerRole,rangerRole,rangerRole); + Mockito.when(roleStore.getRole(Mockito.anyString())).thenReturn(rangerRole, rangerRole, rangerRole, rangerRole); } catch (Exception e) { throw new RuntimeException(e); } try { - Mockito.when(roleStore.updateRole(Mockito.any(RangerRole.class),Mockito.anyBoolean())). - then(AdditionalAnswers.returnsFirstArg()); + Mockito.when(roleStore.updateRole(Mockito.any(RangerRole.class), Mockito.anyBoolean())).then(AdditionalAnswers.returnsFirstArg()); } catch (Exception e) { throw new RuntimeException(e); } - RESTResponse resp = roleRest.revokeRole(serviceName, grantRevokeRoleRequest, - Mockito.mock(HttpServletRequest.class)); + RESTResponse resp = roleRest.revokeRole(serviceName, grantRevokeRoleRequest, Mockito.mock(HttpServletRequest.class)); Assert.assertNotNull(resp); - Assert.assertEquals(resp.getStatusCode(), RESTResponse.STATUS_SUCCESS); + Assert.assertEquals(RESTResponse.STATUS_SUCCESS, resp.getStatusCode()); } @Test - public void test15GetUserRoles(){ + public void test15GetUserRoles() { Set rangerRoles = new HashSet<>(); - RangerRole rangerRole = createRole(); + RangerRole rangerRole = createRole(); rangerRoles.add(rangerRole); List xxRoleRefGroupList = createXXRoleRefGroupList(); - List xxRoleRefRoleList = createXXRoleRefUserList(); - Set groups = new HashSet<>(Arrays.asList("group1", "group2")); + List xxRoleRefRoleList = createXXRoleRefUserList(); + Set groups = new HashSet<>(Arrays.asList("group1", "group2")); Mockito.when(xUserService.getXUserByUserName(Mockito.anyString())).thenReturn(createVXUser()); Mockito.when(userMgr.getGroupsForUser(Mockito.anyString())).thenReturn(groups); - Mockito.when(roleRefUpdater.getRangerDaoManager().getXXRoleRefUser().findByUserName(adminLoginID)). - thenReturn(xxRoleRefRoleList); - Mockito.when(roleRefUpdater.getRangerDaoManager().getXXRoleRefGroup().findByGroupName(adminLoginID)). - thenReturn(xxRoleRefGroupList); + Mockito.when(roleRefUpdater.getRangerDaoManager().getXXRoleRefUser().findByUserName(adminLoginID)).thenReturn(xxRoleRefRoleList); + Mockito.when(roleRefUpdater.getRangerDaoManager().getXXRoleRefGroup().findByGroupName(adminLoginID)).thenReturn(xxRoleRefGroupList); try { - Mockito.when(roleStore.getRoleNames(Mockito.anyString(),eq(groups))).thenReturn(rangerRoles); + Mockito.when(roleStore.getRoleNames(Mockito.anyString(), eq(groups))).thenReturn(rangerRoles); } catch (Exception e) { throw new RuntimeException(e); } - List returnedRoles = roleRest.getUserRoles(adminLoginID,Mockito.mock(HttpServletRequest.class)); + List returnedRoles = roleRest.getUserRoles(adminLoginID, Mockito.mock(HttpServletRequest.class)); Assert.assertNotNull(returnedRoles); Assert.assertEquals(returnedRoles.size(), rangerRoles.size()); } @Test public void test16GetRangerRolesIfUpdated() { - RangerRoles rangerRoles = createRangerRoles(); - String serviceName = "serviceName"; - String pluginId = "pluginId"; - String clusterName = ""; - String pluginCapabilities = ""; + RangerRoles rangerRoles = createRangerRoles(); + String serviceName = "serviceName"; + String pluginId = "pluginId"; + String clusterName = ""; + String pluginCapabilities = ""; RangerRoles returnedRangeRoles; - Mockito.when(serviceUtil.isValidService(Mockito.anyString(),Mockito.any(HttpServletRequest.class))). - thenReturn(true); + Mockito.when(serviceUtil.isValidService(Mockito.anyString(), Mockito.any(HttpServletRequest.class))).thenReturn(true); try { Mockito.when(roleStore.getRoles(Mockito.anyString(), Mockito.anyLong())).thenReturn(rangerRoles); } catch (Exception e) { throw new RuntimeException(e); } try { - returnedRangeRoles = roleRest.getRangerRolesIfUpdated(serviceName, - -1l, 0l, pluginId, clusterName, pluginCapabilities, - Mockito.mock(HttpServletRequest.class)); + returnedRangeRoles = roleRest.getRangerRolesIfUpdated(serviceName, -1L, 0L, pluginId, clusterName, pluginCapabilities, Mockito.mock(HttpServletRequest.class)); } catch (Exception e) { throw new RuntimeException(e); } @@ -464,15 +481,14 @@ public void test16GetRangerRolesIfUpdated() { } @Test - public void test17GetSecureRangerRolesIfUpdated(){ - RangerRoles rangerRoles = createRangerRoles(); - String serviceName = "serviceName"; - String pluginId = "pluginId"; - String clusterName = ""; - String pluginCapabilities = ""; + public void test17GetSecureRangerRolesIfUpdated() { + RangerRoles rangerRoles = createRangerRoles(); + String serviceName = "serviceName"; + String pluginId = "pluginId"; + String clusterName = ""; + String pluginCapabilities = ""; RangerRoles returnedRangeRoles; - Mockito.when(serviceUtil.isValidService(Mockito.anyString(),Mockito.any(HttpServletRequest.class))). - thenReturn(true); + Mockito.when(serviceUtil.isValidService(Mockito.anyString(), Mockito.any(HttpServletRequest.class))).thenReturn(true); try { Mockito.when(roleStore.getRoles(Mockito.anyString(), Mockito.anyLong())).thenReturn(rangerRoles); } catch (Exception e) { @@ -481,9 +497,7 @@ public void test17GetSecureRangerRolesIfUpdated(){ Mockito.when(daoMgr.getXXService().findByName(Mockito.anyString())).thenReturn(createXXService()); Mockito.when(bizUtil.isAdmin()).thenReturn(true); try { - returnedRangeRoles = roleRest.getSecureRangerRolesIfUpdated(serviceName, - -1l, 0l, pluginId, clusterName, pluginCapabilities, - Mockito.mock(HttpServletRequest.class)); + returnedRangeRoles = roleRest.getSecureRangerRolesIfUpdated(serviceName, -1L, 0L, pluginId, clusterName, pluginCapabilities, Mockito.mock(HttpServletRequest.class)); } catch (Exception e) { throw new RuntimeException(e); } @@ -492,22 +506,23 @@ public void test17GetSecureRangerRolesIfUpdated(){ } @Test(expected = Throwable.class) - public void test1bCreateRole(){ + public void test1bCreateRole() { boolean createNonExistUserGroup = true; Mockito.when(validatorFactory.getRangerRoleValidator(roleStore)).thenReturn(Mockito.mock(RangerRoleValidator.class)); Mockito.when(bizUtil.isUserRangerAdmin(Mockito.anyString())).thenReturn(true); RangerRole rangerRole = createRoleInvalidMember(); - roleRest.createRole("admin", rangerRole ,createNonExistUserGroup); + roleRest.createRole("admin", rangerRole, createNonExistUserGroup); } + @Test(expected = Throwable.class) - public void test2bUpdateRole(){ - Boolean createNonExistUserGroup = Boolean.TRUE; - RangerRole rangerRole = createRoleInvalidMember(); - RangerRole rangerRoleOld = createRoleOld(); + public void test2bUpdateRole() { + Boolean createNonExistUserGroup = Boolean.TRUE; + RangerRole rangerRole = createRoleInvalidMember(); + RangerRole rangerRoleOld = createRoleOld(); Mockito.when(validatorFactory.getRangerRoleValidator(roleStore)).thenReturn(Mockito.mock(RangerRoleValidator.class)); XXRoleDao xxRoleDao = Mockito.mock(XXRoleDao.class); Mockito.when(daoMgr.getXXRole()).thenReturn(xxRoleDao); - Mockito.when(daoMgr.getXXPolicyRefRole().findRoleRefPolicyCount(Mockito.anyString())).thenReturn(0l); + Mockito.when(daoMgr.getXXPolicyRefRole().findRoleRefPolicyCount(Mockito.anyString())).thenReturn(0L); try { Mockito.when(roleStore.getRole(Mockito.anyLong())).thenReturn(rangerRoleOld); } catch (Exception e) { @@ -515,12 +530,13 @@ public void test2bUpdateRole(){ } roleRest.updateRole(roleId, rangerRole, eq(createNonExistUserGroup)); } + @Test(expected = Throwable.class) - public void test3bDeleteRoleByName(){ + public void test3bDeleteRoleByName() { RangerRole rangerRole = createRole(); Mockito.doReturn(false).when(bizUtil).isUserRangerAdmin(Mockito.anyString()); Mockito.when(validatorFactory.getRangerRoleValidator(roleStore)).thenReturn(Mockito.mock(RangerRoleValidator.class)); - roleRest.deleteRole("admin", adminLoginID ,rangerRole.getName()); + roleRest.deleteRole("admin", adminLoginID, rangerRole.getName()); try { Mockito.verify(roleStore, Mockito.times(1)).deleteRole(Mockito.anyString()); } catch (Exception e) { @@ -529,7 +545,7 @@ public void test3bDeleteRoleByName(){ } @Test(expected = Throwable.class) - public void test4bDeleteRoleById(){ + public void test4bDeleteRoleById() { RangerRole rangerRole = createRole(); Mockito.when(validatorFactory.getRangerRoleValidator(roleStore)).thenReturn(Mockito.mock(RangerRoleValidator.class)); roleRest.deleteRole(rangerRole.getId()); @@ -541,13 +557,13 @@ public void test4bDeleteRoleById(){ } @Test(expected = Throwable.class) - public void test5bGetRoleByName(){ + public void test5bGetRoleByName() { RangerRole rangerRole = createRole(); - roleRest.getRole("admin", adminLoginID ,rangerRole.getName()); + roleRest.getRole("admin", adminLoginID, rangerRole.getName()); } @Test(expected = Throwable.class) - public void test6bGetRoleById(){ + public void test6bGetRoleById() { RangerRole rangerRole = createRole(); try { Mockito.when(roleStore.getRole(Mockito.anyLong())).thenThrow(new Exception("test")); @@ -558,46 +574,43 @@ public void test6bGetRoleById(){ } @Test(expected = Throwable.class) - public void test7bGetAllRoles(){ + public void test7bGetAllRoles() { SearchFilter searchFilter = new SearchFilter(); try { Mockito.when(roleStore.getRoles(searchFilter, Mockito.any(RangerRoleList.class))).thenThrow(new Exception("test")); } catch (Exception e) { throw new RuntimeException(e); } - Mockito.when(searchUtil.getSearchFilter(Mockito.any(HttpServletRequest.class), eq(roleService.sortFields))). - thenReturn(Mockito.mock(SearchFilter.class)); + Mockito.when(searchUtil.getSearchFilter(Mockito.any(HttpServletRequest.class), eq(roleService.sortFields))).thenReturn(Mockito.mock(SearchFilter.class)); roleRest.getAllRoles(Mockito.mock(HttpServletRequest.class)); } @Test - public void test8bGetAllRolesForUser(){ + public void test8bGetAllRolesForUser() { RangerRoleList rangerRoleList = new RangerRoleList(); - SearchFilter searchFilter = new SearchFilter(); - Mockito.when(searchUtil.getSearchFilter(Mockito.any(HttpServletRequest.class), eq(roleService.sortFields))). - thenReturn(searchFilter); + SearchFilter searchFilter = new SearchFilter(); + Mockito.when(searchUtil.getSearchFilter(Mockito.any(HttpServletRequest.class), eq(roleService.sortFields))).thenReturn(searchFilter); RangerRoleList returnedRangerRoleList = roleRest.getAllRolesForUser(Mockito.mock(HttpServletRequest.class)); Assert.assertNotNull(returnedRangerRoleList); Assert.assertEquals(returnedRangerRoleList.getListSize(), rangerRoleList.getListSize()); } @Test(expected = Throwable.class) - public void test9bGetAllRoleNames(){ + public void test9bGetAllRoleNames() { List roleList = createRoleList(); - Mockito.when(searchUtil.getSearchFilter(Mockito.any(HttpServletRequest.class), eq(roleService.sortFields))). - thenReturn(Mockito.mock(SearchFilter.class)); + Mockito.when(searchUtil.getSearchFilter(Mockito.any(HttpServletRequest.class), eq(roleService.sortFields))).thenReturn(Mockito.mock(SearchFilter.class)); List returnedRoleList = roleRest.getAllRoleNames(adminLoginID, adminLoginID, Mockito.mock(HttpServletRequest.class)); Assert.assertNotNull(returnedRoleList); Assert.assertEquals(returnedRoleList.size(), roleList.size()); } + @Test - public void test10bAddUsersAndGroups(){ - RangerRole rangerRole = createRoleWithUsersAndGroups(); - int currentUsersCount = rangerRole.getUsers().size(); - int currentGroupsCount = rangerRole.getGroups().size(); - List users = new ArrayList<>(Arrays.asList("test-role2","test-role3")); - List groups = new ArrayList<>(Arrays.asList("test-group2","test-group3")); - Boolean isAdmin = Boolean.TRUE; + public void test10bAddUsersAndGroups() { + RangerRole rangerRole = createRoleWithUsersAndGroups(); + int currentUsersCount = rangerRole.getUsers().size(); + int currentGroupsCount = rangerRole.getGroups().size(); + List users = new ArrayList<>(Arrays.asList("test-role2", "test-role3")); + List groups = new ArrayList<>(Arrays.asList("test-group2", "test-group3")); Mockito.when(bizUtil.isUserRangerAdmin(Mockito.anyString())).thenReturn(true); try { Mockito.when(roleStore.getRole(Mockito.anyLong())).thenReturn(rangerRole); @@ -605,127 +618,118 @@ public void test10bAddUsersAndGroups(){ throw new RuntimeException(e); } try { - Mockito.when(roleStore.updateRole(Mockito.any(RangerRole.class),Mockito.anyBoolean())). - then(AdditionalAnswers.returnsFirstArg()); + Mockito.when(roleStore.updateRole(Mockito.any(RangerRole.class), Mockito.anyBoolean())).then(AdditionalAnswers.returnsFirstArg()); } catch (Exception e) { throw new RuntimeException(e); } - RangerRole returnedRole = roleRest.addUsersAndGroups(roleId, users, groups, isAdmin); + RangerRole returnedRole = roleRest.addUsersAndGroups(roleId, users, groups, true); Assert.assertNotNull(returnedRole); Assert.assertEquals(returnedRole.getGroups().size(), groups.size() + currentGroupsCount); } @Test(expected = Throwable.class) - public void test10cAddUsersAndGroups(){ - RangerRole rangerRole = createRole(); - List users = new ArrayList<>(Arrays.asList("{OWNER}","test-role3")); - List groups = new ArrayList<>(Arrays.asList("test-group2","test-group3")); - Boolean isAdmin = Boolean.TRUE; - roleRest.addUsersAndGroups(roleId, users, groups, isAdmin); + public void test10cAddUsersAndGroups() { + RangerRole rangerRole = createRole(); + List users = new ArrayList<>(Arrays.asList("{OWNER}", "test-role3")); + List groups = new ArrayList<>(Arrays.asList("test-group2", "test-group3")); + roleRest.addUsersAndGroups(roleId, users, groups, true); } @Test(expected = Throwable.class) - public void test11bRemoveUsersAndGroups(){ - RangerRole rangerRole = createRole(); - List users = new ArrayList<>(Arrays.asList("test-role","admin")); - List groups = new ArrayList<>(); + public void test11bRemoveUsersAndGroups() { + RangerRole rangerRole = createRole(); + List users = new ArrayList<>(Arrays.asList("test-role", "admin")); + List groups = new ArrayList<>(); List createdRoleUsers = new ArrayList<>(); - for(RangerRole.RoleMember roleMember : rangerRole.getUsers()){ + for (RangerRole.RoleMember roleMember : rangerRole.getUsers()) { createdRoleUsers.add(roleMember.getName()); } roleRest.removeUsersAndGroups(roleId, users, groups); } @Test(expected = Throwable.class) - public void test12bRemoveAdminFromUsersAndGroups(){ + public void test12bRemoveAdminFromUsersAndGroups() { RangerRole rangerRole = createRole(); - for (RangerRole.RoleMember role: rangerRole.getUsers()){ + for (RangerRole.RoleMember role : rangerRole.getUsers()) { Assert.assertTrue(role.getIsAdmin()); } - List users = new ArrayList<>(Arrays.asList("test-role","admin")); - List groups = new ArrayList<>(); + List users = new ArrayList<>(Arrays.asList("test-role", "admin")); + List groups = new ArrayList<>(); List createdRoleUsers = new ArrayList<>(); - for(RangerRole.RoleMember roleMember : rangerRole.getUsers()){ + for (RangerRole.RoleMember roleMember : rangerRole.getUsers()) { createdRoleUsers.add(roleMember.getName()); } roleRest.removeAdminFromUsersAndGroups(roleId, users, groups); } @Test(expected = Throwable.class) - public void test13bGrantRole(){ - RangerRole rangerRole = createRole(); - String serviceName = "serviceName"; + public void test13bGrantRole() { + RangerRole rangerRole = createRole(); + String serviceName = "serviceName"; GrantRevokeRoleRequest grantRevokeRoleRequest = createGrantRevokeRoleRequest(); - roleRest.grantRole(serviceName, grantRevokeRoleRequest, - Mockito.mock(HttpServletRequest.class)); + roleRest.grantRole(serviceName, grantRevokeRoleRequest, Mockito.mock(HttpServletRequest.class)); } @Test - public void test14bRevokeRole(){ - RangerRole rangerRole = createRole(); - String serviceName = "serviceName"; + public void test14bRevokeRole() { + RangerRole rangerRole = createRole(); + String serviceName = "serviceName"; GrantRevokeRoleRequest grantRevokeRoleRequest = createGrantRevokeRoleRequest(); grantRevokeRoleRequest.setGrantOption(Boolean.TRUE); - Mockito.when(bizUtil.isUserRangerAdmin(Mockito.anyString())).thenReturn(true,true,true); + Mockito.when(bizUtil.isUserRangerAdmin(Mockito.anyString())).thenReturn(true, true, true); try { - Mockito.when(roleStore.getRole(Mockito.anyString())).thenReturn(rangerRole,rangerRole,rangerRole,rangerRole); + Mockito.when(roleStore.getRole(Mockito.anyString())).thenReturn(rangerRole, rangerRole, rangerRole, rangerRole); } catch (Exception e) { throw new RuntimeException(e); } try { - Mockito.when(roleStore.updateRole(Mockito.any(RangerRole.class),Mockito.anyBoolean())). - then(AdditionalAnswers.returnsFirstArg()); + Mockito.when(roleStore.updateRole(Mockito.any(RangerRole.class), Mockito.anyBoolean())).then(AdditionalAnswers.returnsFirstArg()); } catch (Exception e) { throw new RuntimeException(e); } - RESTResponse resp = roleRest.revokeRole(serviceName, grantRevokeRoleRequest, - Mockito.mock(HttpServletRequest.class)); + RESTResponse resp = roleRest.revokeRole(serviceName, grantRevokeRoleRequest, Mockito.mock(HttpServletRequest.class)); Assert.assertNotNull(resp); - Assert.assertEquals(resp.getStatusCode(), RESTResponse.STATUS_SUCCESS); + Assert.assertEquals(RESTResponse.STATUS_SUCCESS, resp.getStatusCode()); } @Test(expected = Throwable.class) - public void test14cRevokeRole(){ - RangerRole rangerRole = createRole(); - String serviceName = "serviceName"; + public void test14cRevokeRole() { + RangerRole rangerRole = createRole(); + String serviceName = "serviceName"; GrantRevokeRoleRequest grantRevokeRoleRequest = createGrantRevokeRoleRequest(); grantRevokeRoleRequest.setGrantOption(Boolean.TRUE); - grantRevokeRoleRequest.setGrantorGroups(new HashSet<>(Arrays.asList("group1","group2"))); - roleRest.revokeRole(serviceName, grantRevokeRoleRequest, - Mockito.mock(HttpServletRequest.class)); + grantRevokeRoleRequest.setGrantorGroups(new HashSet<>(Arrays.asList("group1", "group2"))); + roleRest.revokeRole(serviceName, grantRevokeRoleRequest, Mockito.mock(HttpServletRequest.class)); } @Test(expected = Throwable.class) - public void test15bGetUserRoles(){ + public void test15bGetUserRoles() { Set rangerRoles = new HashSet<>(); - RangerRole rangerRole = createRole(); + RangerRole rangerRole = createRole(); rangerRoles.add(rangerRole); List xxRoleRefGroupList = createXXRoleRefGroupList(); - List xxRoleRefRoleList = createXXRoleRefUserList(); - Set groups = new HashSet<>(Arrays.asList("group1", "group2")); + List xxRoleRefRoleList = createXXRoleRefUserList(); + Set groups = new HashSet<>(Arrays.asList("group1", "group2")); Mockito.when(xUserService.getXUserByUserName(Mockito.anyString())).thenReturn(null); - Mockito.when(roleRefUpdater.getRangerDaoManager().getXXRoleRefUser().findByUserName(adminLoginID)). - thenReturn(xxRoleRefRoleList); - Mockito.when(roleRefUpdater.getRangerDaoManager().getXXRoleRefGroup().findByGroupName(adminLoginID)). - thenReturn(xxRoleRefGroupList); - roleRest.getUserRoles(adminLoginID,Mockito.mock(HttpServletRequest.class)); + Mockito.when(roleRefUpdater.getRangerDaoManager().getXXRoleRefUser().findByUserName(adminLoginID)).thenReturn(xxRoleRefRoleList); + Mockito.when(roleRefUpdater.getRangerDaoManager().getXXRoleRefGroup().findByGroupName(adminLoginID)).thenReturn(xxRoleRefGroupList); + roleRest.getUserRoles(adminLoginID, Mockito.mock(HttpServletRequest.class)); } @Test(expected = Throwable.class) public void test16bGetRangerRolesIfUpdated() { - RangerRoles rangerRoles = createRangerRoles(); - String serviceName = "serviceName"; - String pluginId = "pluginId"; - String clusterName = ""; - String pluginCapabilities = ""; + RangerRoles rangerRoles = createRangerRoles(); + String serviceName = "serviceName"; + String pluginId = "pluginId"; + String clusterName = ""; + String pluginCapabilities = ""; try { Mockito.doThrow(new Exception()).when(bizUtil).failUnauthenticatedDownloadIfNotAllowed(); } catch (Exception e) { throw new RuntimeException(e); } try { - roleRest.getRangerRolesIfUpdated(serviceName, -1l, 0l, pluginId, clusterName, - pluginCapabilities, Mockito.mock(HttpServletRequest.class)); + roleRest.getRangerRolesIfUpdated(serviceName, -1L, 0L, pluginId, clusterName, pluginCapabilities, Mockito.mock(HttpServletRequest.class)); } catch (Exception e) { throw new RuntimeException(e); } @@ -733,34 +737,31 @@ public void test16bGetRangerRolesIfUpdated() { @Test(expected = Throwable.class) public void test16cGetRangerRolesIfUpdated() { - String serviceName = "serviceName"; - String pluginId = "pluginId"; - String clusterName = ""; + String serviceName = "serviceName"; + String pluginId = "pluginId"; + String clusterName = ""; String pluginCapabilities = ""; - Mockito.when(serviceUtil.isValidService(Mockito.anyString(),Mockito.any(HttpServletRequest.class))). - thenReturn(true); + Mockito.when(serviceUtil.isValidService(Mockito.anyString(), Mockito.any(HttpServletRequest.class))).thenReturn(true); try { Mockito.when(roleStore.getRoles(Mockito.anyString(), Mockito.anyLong())).thenReturn(null); } catch (Exception e) { throw new RuntimeException(e); } try { - roleRest.getRangerRolesIfUpdated(serviceName, -1l, 0l, pluginId, clusterName, - pluginCapabilities, Mockito.mock(HttpServletRequest.class)); + roleRest.getRangerRolesIfUpdated(serviceName, -1L, 0L, pluginId, clusterName, pluginCapabilities, Mockito.mock(HttpServletRequest.class)); } catch (Exception e) { throw new RuntimeException(e); } } @Test(expected = Throwable.class) - public void test17bGetSecureRangerRolesIfUpdated(){ - RangerRoles rangerRoles = createRangerRoles(); - String serviceName = "serviceName"; - String pluginId = "pluginId"; - String clusterName = ""; - String pluginCapabilities = ""; - Mockito.when(serviceUtil.isValidService(eq(null),Mockito.any(HttpServletRequest.class))). - thenThrow(new Exception()); + public void test17bGetSecureRangerRolesIfUpdated() { + RangerRoles rangerRoles = createRangerRoles(); + String serviceName = "serviceName"; + String pluginId = "pluginId"; + String clusterName = ""; + String pluginCapabilities = ""; + Mockito.when(serviceUtil.isValidService(eq(null), Mockito.any(HttpServletRequest.class))).thenThrow(new Exception()); try { Mockito.when(roleStore.getRoles(Mockito.anyString(), Mockito.anyLong())).thenReturn(rangerRoles); } catch (Exception e) { @@ -769,40 +770,35 @@ public void test17bGetSecureRangerRolesIfUpdated(){ Mockito.when(daoMgr.getXXService().findByName(Mockito.anyString())).thenReturn(createXXService()); Mockito.when(bizUtil.isAdmin()).thenReturn(true); try { - roleRest.getSecureRangerRolesIfUpdated(serviceName, -1l, 0l, pluginId, - clusterName, pluginCapabilities, Mockito.mock(HttpServletRequest.class)); + roleRest.getSecureRangerRolesIfUpdated(serviceName, -1L, 0L, pluginId, clusterName, pluginCapabilities, Mockito.mock(HttpServletRequest.class)); } catch (Exception e) { throw new RuntimeException(e); } } @Test(expected = Throwable.class) - public void test17cGetSecureRangerRolesIfUpdated(){ - String serviceName = "serviceName"; - String pluginId = "pluginId"; - String clusterName = ""; + public void test17cGetSecureRangerRolesIfUpdated() { + String serviceName = "serviceName"; + String pluginId = "pluginId"; + String clusterName = ""; String pluginCapabilities = ""; - Mockito.when(serviceUtil.isValidService(Mockito.anyString(), Mockito.any(HttpServletRequest.class))). - thenReturn(true); + Mockito.when(serviceUtil.isValidService(Mockito.anyString(), Mockito.any(HttpServletRequest.class))).thenReturn(true); Mockito.when(daoMgr.getXXService().findByName(Mockito.anyString())).thenReturn(null); Mockito.when(bizUtil.isAdmin()).thenReturn(true); try { - roleRest.getSecureRangerRolesIfUpdated(serviceName, -1l, 0l, pluginId, - clusterName, pluginCapabilities, Mockito.mock(HttpServletRequest.class)); + roleRest.getSecureRangerRolesIfUpdated(serviceName, -1L, 0L, pluginId, clusterName, pluginCapabilities, Mockito.mock(HttpServletRequest.class)); } catch (Exception e) { throw new RuntimeException(e); } } @Test(expected = Throwable.class) - public void test17dGetSecureRangerRolesIfUpdated(){ - - String serviceName = "serviceName"; - String pluginId = "pluginId"; - String clusterName = ""; + public void test17dGetSecureRangerRolesIfUpdated() { + String serviceName = "serviceName"; + String pluginId = "pluginId"; + String clusterName = ""; String pluginCapabilities = ""; - Mockito.when(serviceUtil.isValidService(Mockito.anyString(), Mockito.any(HttpServletRequest.class))). - thenReturn(true); + Mockito.when(serviceUtil.isValidService(Mockito.anyString(), Mockito.any(HttpServletRequest.class))).thenReturn(true); try { Mockito.when(roleStore.getRoles(Mockito.anyString(), Mockito.anyLong())).thenReturn(null); } catch (Exception e) { @@ -811,417 +807,439 @@ public void test17dGetSecureRangerRolesIfUpdated(){ Mockito.when(daoMgr.getXXService().findByName(Mockito.anyString())).thenReturn(createXXService()); Mockito.when(bizUtil.isAdmin()).thenReturn(true); try { - roleRest.getSecureRangerRolesIfUpdated(serviceName, -1l, 0l, pluginId, - clusterName, pluginCapabilities, Mockito.mock(HttpServletRequest.class)); + roleRest.getSecureRangerRolesIfUpdated(serviceName, -1L, 0L, pluginId, clusterName, pluginCapabilities, Mockito.mock(HttpServletRequest.class)); } catch (Exception e) { throw new RuntimeException(e); } } - // empty request roles (requestParamRoles = 0, dbRoles = 5, return = all dbRoles) - @Test - public void test18GetRolesInJson() throws Exception { - // pre-requisites - List rangerRolesProcessed = new ArrayList<>(); - - rangerRolesProcessed.add(createRangerRole("role1", true)); - rangerRolesProcessed.add(createRangerRole("role2", false)); - rangerRolesProcessed.add(createRangerRole("role3", false)); - rangerRolesProcessed.add(createRangerRole("adm", true)); - rangerRolesProcessed.add(createRangerRole("user", false)); - - // mock - HttpServletRequest requestMock = Mockito.mock(HttpServletRequest.class); - HttpServletResponse responseMock = Mockito.mock(HttpServletResponse.class); - - // stubs - Mockito.when(roleRest.getAllFilteredRoleList(requestMock)).thenReturn(rangerRolesProcessed); - - // test - roleRest.getRolesInJson(requestMock, responseMock); - Mockito.verify(svcStore).getObjectInJson(rangerRolesProcessed, responseMock, ROLE); - } - - // non-empty request roles (requestParamRoles = 2, dbRoles = 5, return = 2 requestParamRoles) - @Test - public void test18bGetRolesInJson() throws Exception { - // pre-requisites - List rangerRolesProcessed = new ArrayList<>(); - - RangerRole admRole = createRangerRole("adm", true); - RangerRole userRole = createRangerRole("user", false); - - rangerRolesProcessed.add(admRole); - rangerRolesProcessed.add(userRole); - - // mock - HttpServletRequest requestMock = Mockito.mock(HttpServletRequest.class); - HttpServletResponse responseMock = Mockito.mock(HttpServletResponse.class); - - // stubs - Mockito.when(roleRest.getAllFilteredRoleList(requestMock)).thenReturn(rangerRolesProcessed); - - // test - roleRest.getRolesInJson(requestMock, responseMock); - Mockito.verify(svcStore).getObjectInJson(rangerRolesProcessed, responseMock, ROLE); - } - - // non-empty request roles (requestParamRoles = 3, dbRoles = 0, return = 0 dbRoles) - @Test - public void test18cGetRolesInJson() throws Exception { - // pre-requisites - List rangerRolesProcessed = new ArrayList<>(); - - // mock - HttpServletRequest requestMock = Mockito.mock(HttpServletRequest.class); - HttpServletResponse responseMock = Mockito.mock(HttpServletResponse.class); - - // stubs - Mockito.when(roleRest.getAllFilteredRoleList(requestMock)).thenReturn(rangerRolesProcessed); - - // test - roleRest.getRolesInJson(requestMock, responseMock); - Mockito.verify(svcStore, Mockito.never()).getObjectInJson(rangerRolesProcessed, responseMock, ROLE); - } - - // getAllFilteredRoleList throws Exception - @Test(expected = Throwable.class) - public void test18dGetRolesInJson() throws Exception { - // pre-requisites - List rangerRolesProcessed = new ArrayList<>(); - - // mock - HttpServletRequest requestMock = Mockito.mock(HttpServletRequest.class); - HttpServletResponse responseMock = Mockito.mock(HttpServletResponse.class); - - // stubs - Mockito.when(roleRest.getAllFilteredRoleList(requestMock)).thenThrow(new Throwable()); - - // test - Assert.assertThrows(Throwable.class, () -> roleRest.getRolesInJson(requestMock, responseMock)); - Mockito.verify(svcStore, Mockito.never()).getObjectInJson(rangerRolesProcessed, responseMock, ROLE); - Mockito.verify(restErrorUtil).createRESTException(Mockito.anyString()); - } - - // full match: requestParamRoles = 0, dbRoles = 5, return = all dbRoles - @Test - public void test19GetAllFilteredRoleList() throws Exception { - // pre-requisites - String requestParamRoles = ""; - List rangerRolesDb = new ArrayList<>(); - List rangerRolesProcessedExpected = new ArrayList<>(); - - rangerRolesDb.add(createRangerRole("role1", true)); - rangerRolesDb.add(createRangerRole("role2", false)); - rangerRolesDb.add(createRangerRole("role3", false)); - rangerRolesDb.add(createRangerRole("adm", true)); - rangerRolesDb.add(createRangerRole("user", false)); - - rangerRolesProcessedExpected.addAll(rangerRolesDb); - - // mock - HttpServletRequest requestMock = Mockito.mock(HttpServletRequest.class); - - // stubs - Mockito.when(requestMock.getParameter(RoleREST.PARAM_ROLE_NAME)).thenReturn(requestParamRoles); - Mockito.when(roleStore.getRoles(Mockito.any(SearchFilter.class))).thenReturn(rangerRolesDb); - - // test - List rangerRolesProcessedActual = roleRest.getAllFilteredRoleList(requestMock); - Assert.assertNotNull(rangerRolesProcessedActual); - Assert.assertEquals(rangerRolesProcessedActual.size(), rangerRolesProcessedExpected.size()); - Assert.assertEquals(rangerRolesProcessedActual, rangerRolesProcessedExpected); - } - - // partial match: requestParamRoles = 2, dbRoles = 5, match = 2 - @Test - public void test19bGetAllFilteredRoleList() throws Exception { - // pre-requisites - String requestParamRoles = "adm,user"; - List rangerRolesDb = new ArrayList<>(); - List rangerRolesProcessedExpected = new ArrayList<>(); - - rangerRolesDb.add(createRangerRole("role1", true)); - rangerRolesDb.add(createRangerRole("role2", false)); - rangerRolesDb.add(createRangerRole("role3", false)); - - RangerRole admRole = createRangerRole("adm", true); - RangerRole userRole = createRangerRole("user", false); - - rangerRolesDb.add(admRole); - rangerRolesDb.add(userRole); - - rangerRolesProcessedExpected.add(admRole); - rangerRolesProcessedExpected.add(userRole); - - // mock - HttpServletRequest requestMock = Mockito.mock(HttpServletRequest.class); - - // stubs - Mockito.when(requestMock.getParameter(RoleREST.PARAM_ROLE_NAME)).thenReturn(requestParamRoles); - Mockito.when(roleStore.getRoles(Mockito.any(SearchFilter.class))).thenReturn(rangerRolesDb); - - // test - List rangerRolesProcessedActual = roleRest.getAllFilteredRoleList(requestMock); - Assert.assertNotNull(rangerRolesProcessedActual); - Assert.assertEquals(rangerRolesProcessedActual.size(), rangerRolesProcessedExpected.size()); - Assert.assertEquals(rangerRolesProcessedActual, rangerRolesProcessedExpected); - } - - // partial match: requestParamRoles = 4, dbRoles = 5, match = 2 - @Test - public void test19cGetAllFilteredRoleList() throws Exception { - // pre-requisites - String requestParamRoles = "adm,key-adm,delegate-adm,user"; - List rangerRolesDb = new ArrayList<>(); - List rangerRolesProcessedExpected = new ArrayList<>(); - - rangerRolesDb.add(createRangerRole("role1", true)); - rangerRolesDb.add(createRangerRole("role2", false)); - rangerRolesDb.add(createRangerRole("role3", false)); - - RangerRole admRole = createRangerRole("adm", true); - RangerRole userRole = createRangerRole("user", false); - - rangerRolesDb.add(admRole); - rangerRolesDb.add(userRole); - - rangerRolesProcessedExpected.add(admRole); - rangerRolesProcessedExpected.add(userRole); - - // mock - HttpServletRequest requestMock = Mockito.mock(HttpServletRequest.class); - - // stubs - Mockito.when(requestMock.getParameter(RoleREST.PARAM_ROLE_NAME)).thenReturn(requestParamRoles); - Mockito.when(roleStore.getRoles(Mockito.any(SearchFilter.class))).thenReturn(rangerRolesDb); - - // test - List rangerRolesProcessedActual = roleRest.getAllFilteredRoleList(requestMock); - Assert.assertNotNull(rangerRolesProcessedActual); - Assert.assertEquals(rangerRolesProcessedActual.size(), rangerRolesProcessedExpected.size()); - Assert.assertEquals(rangerRolesProcessedActual, rangerRolesProcessedExpected); - } - - // no match: requestParamRoles = 3, dbRoles = 5, match = 0 - @Test - public void test19dGetAllFilteredRoleList() throws Exception { - // pre-requisites - String requestParamRoles = "sys-adm,key-adm,delegate-adm"; - List rangerRolesDb = new ArrayList<>(); - List rangerRolesProcessedExpected = new ArrayList<>(); - - rangerRolesDb.add(createRangerRole("role1", true)); - rangerRolesDb.add(createRangerRole("role2", false)); - rangerRolesDb.add(createRangerRole("role3", false)); - - RangerRole admRole = createRangerRole("adm", true); - RangerRole userRole = createRangerRole("user", false); - - rangerRolesDb.add(admRole); - rangerRolesDb.add(userRole); - - // mock - HttpServletRequest requestMock = Mockito.mock(HttpServletRequest.class); - - // stubs - Mockito.when(requestMock.getParameter(RoleREST.PARAM_ROLE_NAME)).thenReturn(requestParamRoles); - Mockito.when(roleStore.getRoles(Mockito.any(SearchFilter.class))).thenReturn(rangerRolesDb); - - // test - List rangerRolesProcessedActual = roleRest.getAllFilteredRoleList(requestMock); - Assert.assertNotNull(rangerRolesProcessedActual); - Assert.assertEquals(rangerRolesProcessedActual.size(), rangerRolesProcessedExpected.size()); - Assert.assertEquals(rangerRolesProcessedActual, rangerRolesProcessedExpected); - } - - // no match: requestParamRoles = 3, dbRoles = 0, match = 0 - @Test - public void test19eGetAllFilteredRoleList() throws Exception { - // pre-requisites - String requestParamRoles = "sys-adm,key-adm,delegate-adm"; - List rangerRolesDb = new ArrayList<>(); - List rangerRolesProcessedExpected = Collections.emptyList(); - - // mock - HttpServletRequest requestMock = Mockito.mock(HttpServletRequest.class); - - // stubs - Mockito.when(requestMock.getParameter(RoleREST.PARAM_ROLE_NAME)).thenReturn(requestParamRoles); - Mockito.when(roleStore.getRoles(Mockito.any(SearchFilter.class))).thenReturn(rangerRolesDb); - - // test - List rangerRolesProcessedActual = roleRest.getAllFilteredRoleList(requestMock); - Assert.assertNotNull(rangerRolesProcessedActual); - Assert.assertEquals(rangerRolesProcessedActual.size(), rangerRolesProcessedExpected.size()); - Assert.assertEquals(rangerRolesProcessedActual, rangerRolesProcessedExpected); - } - - // full match: requestParamRoles = null, dbRoles = 5, return = all dbRoles - @Test - public void test19fGetAllFilteredRoleList() throws Exception { - // pre-requisites - String requestParamRoles = null; - List rangerRolesDb = new ArrayList<>(); - List rangerRolesProcessedExpected = new ArrayList<>(); - - rangerRolesDb.add(createRangerRole("role1", true)); - rangerRolesDb.add(createRangerRole("role2", false)); - rangerRolesDb.add(createRangerRole("role3", false)); - rangerRolesDb.add(createRangerRole("adm", true)); - rangerRolesDb.add(createRangerRole("user", false)); - - rangerRolesProcessedExpected.addAll(rangerRolesDb); - - // mock - HttpServletRequest requestMock = Mockito.mock(HttpServletRequest.class); - - // stubs - Mockito.when(requestMock.getParameter(RoleREST.PARAM_ROLE_NAME)).thenReturn(requestParamRoles); - Mockito.when(roleStore.getRoles(Mockito.any(SearchFilter.class))).thenReturn(rangerRolesDb); - - // test - List rangerRolesProcessedActual = roleRest.getAllFilteredRoleList(requestMock); - Assert.assertNotNull(rangerRolesProcessedActual); - Assert.assertEquals(rangerRolesProcessedActual.size(), rangerRolesProcessedExpected.size()); - Assert.assertEquals(rangerRolesProcessedActual, rangerRolesProcessedExpected); - } - - // import role with updateIfExists=false and createNonExistUserGroupRole=false - @SuppressWarnings("unchecked") - @Test - public void test20importRolesFromFile() throws Exception { - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - - List roleList = createRoleList(); - RangerRole rangerRole = createRole(); - - SearchFilter filter = new SearchFilter(); - - File jsonRoleFile = new File(importRoleTestFilePath); - InputStream uploadedInputStream = new FileInputStream(jsonRoleFile); - FormDataContentDisposition fileDetail = FormDataContentDisposition.name("file").fileName(jsonRoleFile.getName()) - .size(uploadedInputStream.toString().length()).build(); - boolean updateIfExists = false; - boolean createNonExistUserGroupRole = false; - - Mockito.when(searchUtil.getSearchFilter(request, roleService.sortFields)).thenReturn(filter); - Mockito.when(roleStore.getRoleNames(Mockito.any(SearchFilter.class))).thenReturn(roleList); - Mockito.when(roleStore.createRole(Mockito.any(RangerRole.class), eq(createNonExistUserGroupRole))) - .thenReturn(rangerRole); - - RESTResponse resp = roleRest.importRolesFromFile(request, uploadedInputStream, fileDetail, updateIfExists, - createNonExistUserGroupRole); - Assert.assertNotNull(resp); - Assert.assertEquals(resp.getStatusCode(), RESTResponse.STATUS_SUCCESS); - Assert.assertEquals(resp.getMsgDesc(), "Total Role Created = 6 , Total Role Unchanged = 1"); - } - - // import role with updateIfExists=false and createNonExistUserGroupRole=true - @SuppressWarnings("unchecked") - @Test - public void test20bimportRolesFromFile() throws Exception { - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - - List roleList = createRoleList(); - RangerRole rangerRole = createRoleWithUsersAndGroups(); - - SearchFilter filter = new SearchFilter(); - - File jsonRoleFile = new File(importRoleTestFilePath); - InputStream uploadedInputStream = new FileInputStream(jsonRoleFile); - FormDataContentDisposition fileDetail = FormDataContentDisposition.name("file").fileName(jsonRoleFile.getName()) - .size(uploadedInputStream.toString().length()).build(); - boolean updateIfExists = false; - boolean createNonExistUserGroupRole = true; - - Mockito.when(searchUtil.getSearchFilter(request, roleService.sortFields)).thenReturn(filter); - Mockito.when(roleStore.getRoleNames(Mockito.any(SearchFilter.class))).thenReturn(roleList); - Mockito.when(roleStore.createRole(Mockito.any(RangerRole.class), eq(createNonExistUserGroupRole))) - .thenReturn(rangerRole); - - RESTResponse resp = roleRest.importRolesFromFile(request, uploadedInputStream, fileDetail, updateIfExists, - createNonExistUserGroupRole); - Assert.assertNotNull(resp); - Assert.assertEquals(resp.getStatusCode(), RESTResponse.STATUS_SUCCESS); - Assert.assertEquals(resp.getMsgDesc(), "Total Role Created = 6 , Total Role Unchanged = 1"); - } - - // import role with updateIfExists=true and createNonExistUserGroupRole=true - @SuppressWarnings("unchecked") - @Test - public void test20cimportRolesFromFileWithUpdate() throws Exception { - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - - List roleList = createRoleList(); - RangerRole rangerRole = createRole(); - - SearchFilter filter = new SearchFilter(); - - File jsonRoleFile = new File(importRoleTestFilePath); - InputStream uploadedInputStream = new FileInputStream(jsonRoleFile); - FormDataContentDisposition fileDetail = FormDataContentDisposition.name("file").fileName(jsonRoleFile.getName()) - .size(uploadedInputStream.toString().length()).build(); - boolean updateIfExists = true; - boolean createNonExistUserGroupRole = true; - - Mockito.when(searchUtil.getSearchFilter(request, roleService.sortFields)).thenReturn(filter); - Mockito.when(roleStore.getRoleNames(Mockito.any(SearchFilter.class))).thenReturn(roleList); - Mockito.when(roleStore.getRole(Mockito.anyString())).thenReturn(rangerRole); - Mockito.when(roleStore.createRole(Mockito.any(RangerRole.class), eq(createNonExistUserGroupRole))) - .thenReturn(rangerRole); - - RESTResponse resp = roleRest.importRolesFromFile(request, uploadedInputStream, fileDetail, updateIfExists, - createNonExistUserGroupRole); - Assert.assertNotNull(resp); - Assert.assertEquals(resp.getStatusCode(), RESTResponse.STATUS_SUCCESS); - Assert.assertEquals(resp.getMsgDesc(), - "Total Role Created = 6 , Total Role Updated = 1 , Total Role Unchanged = 0"); - } - - // import role throws exceptions - @SuppressWarnings("unchecked") - @Test(expected = Throwable.class) - public void test20dimportRolesFromFileWithUpdate() throws Exception { - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - - File jsonRoleFile = new File(importRoleTestFilePath); - InputStream uploadedInputStream = new FileInputStream(jsonRoleFile); - FormDataContentDisposition fileDetail = FormDataContentDisposition.name("file").fileName(jsonRoleFile.getName()) - .size(uploadedInputStream.toString().length()).build(); - boolean updateIfExists = false; - boolean createNonExistUserGroupRole = false; - - Mockito.when(roleStore.getRoleNames(Mockito.any(SearchFilter.class))).thenThrow(new Throwable()); - - Assert.assertThrows(Throwable.class, () -> roleRest.importRolesFromFile(request, uploadedInputStream, - fileDetail, updateIfExists, createNonExistUserGroupRole)); - Mockito.verify(restErrorUtil).createRESTException(Mockito.anyString()); - } - - private RangerRole createRole(){ - String name = "test-role"; - String name2 = "admin"; - RangerRole.RoleMember rm1 = new RangerRole.RoleMember(name,true); - RangerRole.RoleMember rm2 = new RangerRole.RoleMember(name2, true); - List usersList = new ArrayList<>(Arrays.asList(rm1,rm2)); - RangerRole rangerRole = new RangerRole(name, name, null, usersList, null); + // empty request roles (requestParamRoles = 0, dbRoles = 5, return = all dbRoles) + @Test + public void test18GetRolesInJson() throws Exception { + // pre-requisites + List rangerRolesProcessed = new ArrayList<>(); + + rangerRolesProcessed.add(createRangerRole("role1", true)); + rangerRolesProcessed.add(createRangerRole("role2", false)); + rangerRolesProcessed.add(createRangerRole("role3", false)); + rangerRolesProcessed.add(createRangerRole("adm", true)); + rangerRolesProcessed.add(createRangerRole("user", false)); + + // mock + HttpServletRequest requestMock = Mockito.mock(HttpServletRequest.class); + HttpServletResponse responseMock = Mockito.mock(HttpServletResponse.class); + + // stubs + Mockito.when(roleRest.getAllFilteredRoleList(requestMock)).thenReturn(rangerRolesProcessed); + + // test + roleRest.getRolesInJson(requestMock, responseMock); + Mockito.verify(svcStore).getObjectInJson(rangerRolesProcessed, responseMock, ROLE); + } + + // non-empty request roles (requestParamRoles = 2, dbRoles = 5, return = 2 requestParamRoles) + @Test + public void test18bGetRolesInJson() throws Exception { + // pre-requisites + List rangerRolesProcessed = new ArrayList<>(); + + RangerRole admRole = createRangerRole("adm", true); + RangerRole userRole = createRangerRole("user", false); + + rangerRolesProcessed.add(admRole); + rangerRolesProcessed.add(userRole); + + // mock + HttpServletRequest requestMock = Mockito.mock(HttpServletRequest.class); + HttpServletResponse responseMock = Mockito.mock(HttpServletResponse.class); + + // stubs + Mockito.when(roleRest.getAllFilteredRoleList(requestMock)).thenReturn(rangerRolesProcessed); + + // test + roleRest.getRolesInJson(requestMock, responseMock); + Mockito.verify(svcStore).getObjectInJson(rangerRolesProcessed, responseMock, ROLE); + } + + // non-empty request roles (requestParamRoles = 3, dbRoles = 0, return = 0 dbRoles) + @Test + public void test18cGetRolesInJson() throws Exception { + // pre-requisites + List rangerRolesProcessed = new ArrayList<>(); + + // mock + HttpServletRequest requestMock = Mockito.mock(HttpServletRequest.class); + HttpServletResponse responseMock = Mockito.mock(HttpServletResponse.class); + + // stubs + Mockito.when(roleRest.getAllFilteredRoleList(requestMock)).thenReturn(rangerRolesProcessed); + + // test + roleRest.getRolesInJson(requestMock, responseMock); + Mockito.verify(svcStore, Mockito.never()).getObjectInJson(rangerRolesProcessed, responseMock, ROLE); + } + + // getAllFilteredRoleList throws Exception + @Test(expected = Throwable.class) + public void test18dGetRolesInJson() throws Exception { + // pre-requisites + List rangerRolesProcessed = new ArrayList<>(); + + // mock + HttpServletRequest requestMock = Mockito.mock(HttpServletRequest.class); + HttpServletResponse responseMock = Mockito.mock(HttpServletResponse.class); + + // stubs + Mockito.when(roleRest.getAllFilteredRoleList(requestMock)).thenThrow(new Throwable()); + + // test + Assert.assertThrows(Throwable.class, () -> roleRest.getRolesInJson(requestMock, responseMock)); + Mockito.verify(svcStore, Mockito.never()).getObjectInJson(rangerRolesProcessed, responseMock, ROLE); + Mockito.verify(restErrorUtil).createRESTException(Mockito.anyString()); + } + + // full match: requestParamRoles = 0, dbRoles = 5, return = all dbRoles + @Test + public void test19GetAllFilteredRoleList() throws Exception { + // pre-requisites + String requestParamRoles = ""; + List rangerRolesDb = new ArrayList<>(); + List rangerRolesProcessedExpected = new ArrayList<>(); + + rangerRolesDb.add(createRangerRole("role1", true)); + rangerRolesDb.add(createRangerRole("role2", false)); + rangerRolesDb.add(createRangerRole("role3", false)); + rangerRolesDb.add(createRangerRole("adm", true)); + rangerRolesDb.add(createRangerRole("user", false)); + + rangerRolesProcessedExpected.addAll(rangerRolesDb); + + // mock + HttpServletRequest requestMock = Mockito.mock(HttpServletRequest.class); + + // stubs + Mockito.when(requestMock.getParameter(RoleREST.PARAM_ROLE_NAME)).thenReturn(requestParamRoles); + Mockito.when(roleStore.getRoles(Mockito.any(SearchFilter.class))).thenReturn(rangerRolesDb); + + // test + List rangerRolesProcessedActual = roleRest.getAllFilteredRoleList(requestMock); + Assert.assertNotNull(rangerRolesProcessedActual); + Assert.assertEquals(rangerRolesProcessedActual.size(), rangerRolesProcessedExpected.size()); + Assert.assertEquals(rangerRolesProcessedActual, rangerRolesProcessedExpected); + } + + // partial match: requestParamRoles = 2, dbRoles = 5, match = 2 + @Test + public void test19bGetAllFilteredRoleList() throws Exception { + // pre-requisites + String requestParamRoles = "adm,user"; + List rangerRolesDb = new ArrayList<>(); + List rangerRolesProcessedExpected = new ArrayList<>(); + + rangerRolesDb.add(createRangerRole("role1", true)); + rangerRolesDb.add(createRangerRole("role2", false)); + rangerRolesDb.add(createRangerRole("role3", false)); + + RangerRole admRole = createRangerRole("adm", true); + RangerRole userRole = createRangerRole("user", false); + + rangerRolesDb.add(admRole); + rangerRolesDb.add(userRole); + + rangerRolesProcessedExpected.add(admRole); + rangerRolesProcessedExpected.add(userRole); + + // mock + HttpServletRequest requestMock = Mockito.mock(HttpServletRequest.class); + + // stubs + Mockito.when(requestMock.getParameter(RoleREST.PARAM_ROLE_NAME)).thenReturn(requestParamRoles); + Mockito.when(roleStore.getRoles(Mockito.any(SearchFilter.class))).thenReturn(rangerRolesDb); + + // test + List rangerRolesProcessedActual = roleRest.getAllFilteredRoleList(requestMock); + Assert.assertNotNull(rangerRolesProcessedActual); + Assert.assertEquals(rangerRolesProcessedActual.size(), rangerRolesProcessedExpected.size()); + Assert.assertEquals(rangerRolesProcessedActual, rangerRolesProcessedExpected); + } + + // partial match: requestParamRoles = 4, dbRoles = 5, match = 2 + @Test + public void test19cGetAllFilteredRoleList() throws Exception { + // pre-requisites + String requestParamRoles = "adm,key-adm,delegate-adm,user"; + List rangerRolesDb = new ArrayList<>(); + List rangerRolesProcessedExpected = new ArrayList<>(); + + rangerRolesDb.add(createRangerRole("role1", true)); + rangerRolesDb.add(createRangerRole("role2", false)); + rangerRolesDb.add(createRangerRole("role3", false)); + + RangerRole admRole = createRangerRole("adm", true); + RangerRole userRole = createRangerRole("user", false); + + rangerRolesDb.add(admRole); + rangerRolesDb.add(userRole); + + rangerRolesProcessedExpected.add(admRole); + rangerRolesProcessedExpected.add(userRole); + + // mock + HttpServletRequest requestMock = Mockito.mock(HttpServletRequest.class); + + // stubs + Mockito.when(requestMock.getParameter(RoleREST.PARAM_ROLE_NAME)).thenReturn(requestParamRoles); + Mockito.when(roleStore.getRoles(Mockito.any(SearchFilter.class))).thenReturn(rangerRolesDb); + + // test + List rangerRolesProcessedActual = roleRest.getAllFilteredRoleList(requestMock); + Assert.assertNotNull(rangerRolesProcessedActual); + Assert.assertEquals(rangerRolesProcessedActual.size(), rangerRolesProcessedExpected.size()); + Assert.assertEquals(rangerRolesProcessedActual, rangerRolesProcessedExpected); + } + + // no match: requestParamRoles = 3, dbRoles = 5, match = 0 + @Test + public void test19dGetAllFilteredRoleList() throws Exception { + // pre-requisites + String requestParamRoles = "sys-adm,key-adm,delegate-adm"; + List rangerRolesDb = new ArrayList<>(); + List rangerRolesProcessedExpected = new ArrayList<>(); + + rangerRolesDb.add(createRangerRole("role1", true)); + rangerRolesDb.add(createRangerRole("role2", false)); + rangerRolesDb.add(createRangerRole("role3", false)); + + RangerRole admRole = createRangerRole("adm", true); + RangerRole userRole = createRangerRole("user", false); + + rangerRolesDb.add(admRole); + rangerRolesDb.add(userRole); + + // mock + HttpServletRequest requestMock = Mockito.mock(HttpServletRequest.class); + + // stubs + Mockito.when(requestMock.getParameter(RoleREST.PARAM_ROLE_NAME)).thenReturn(requestParamRoles); + Mockito.when(roleStore.getRoles(Mockito.any(SearchFilter.class))).thenReturn(rangerRolesDb); + + // test + List rangerRolesProcessedActual = roleRest.getAllFilteredRoleList(requestMock); + Assert.assertNotNull(rangerRolesProcessedActual); + Assert.assertEquals(rangerRolesProcessedActual.size(), rangerRolesProcessedExpected.size()); + Assert.assertEquals(rangerRolesProcessedActual, rangerRolesProcessedExpected); + } + + // no match: requestParamRoles = 3, dbRoles = 0, match = 0 + @Test + public void test19eGetAllFilteredRoleList() throws Exception { + // pre-requisites + String requestParamRoles = "sys-adm,key-adm,delegate-adm"; + List rangerRolesDb = new ArrayList<>(); + List rangerRolesProcessedExpected = Collections.emptyList(); + + // mock + HttpServletRequest requestMock = Mockito.mock(HttpServletRequest.class); + + // stubs + Mockito.when(requestMock.getParameter(RoleREST.PARAM_ROLE_NAME)).thenReturn(requestParamRoles); + Mockito.when(roleStore.getRoles(Mockito.any(SearchFilter.class))).thenReturn(rangerRolesDb); + + // test + List rangerRolesProcessedActual = roleRest.getAllFilteredRoleList(requestMock); + Assert.assertNotNull(rangerRolesProcessedActual); + Assert.assertEquals(rangerRolesProcessedActual.size(), rangerRolesProcessedExpected.size()); + Assert.assertEquals(rangerRolesProcessedActual, rangerRolesProcessedExpected); + } + + // full match: requestParamRoles = null, dbRoles = 5, return = all dbRoles + @Test + public void test19fGetAllFilteredRoleList() throws Exception { + // pre-requisites + String requestParamRoles = null; + List rangerRolesDb = new ArrayList<>(); + List rangerRolesProcessedExpected = new ArrayList<>(); + + rangerRolesDb.add(createRangerRole("role1", true)); + rangerRolesDb.add(createRangerRole("role2", false)); + rangerRolesDb.add(createRangerRole("role3", false)); + rangerRolesDb.add(createRangerRole("adm", true)); + rangerRolesDb.add(createRangerRole("user", false)); + + rangerRolesProcessedExpected.addAll(rangerRolesDb); + + // mock + HttpServletRequest requestMock = Mockito.mock(HttpServletRequest.class); + + // stubs + Mockito.when(requestMock.getParameter(RoleREST.PARAM_ROLE_NAME)).thenReturn(requestParamRoles); + Mockito.when(roleStore.getRoles(Mockito.any(SearchFilter.class))).thenReturn(rangerRolesDb); + + // test + List rangerRolesProcessedActual = roleRest.getAllFilteredRoleList(requestMock); + Assert.assertNotNull(rangerRolesProcessedActual); + Assert.assertEquals(rangerRolesProcessedActual.size(), rangerRolesProcessedExpected.size()); + Assert.assertEquals(rangerRolesProcessedActual, rangerRolesProcessedExpected); + } + + // import role with updateIfExists=false and createNonExistUserGroupRole=false + @SuppressWarnings("unchecked") + @Test + public void test20importRolesFromFile() throws Exception { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + + List roleList = createRoleList(); + RangerRole rangerRole = createRole(); + + SearchFilter filter = new SearchFilter(); + + File jsonRoleFile = new File(importRoleTestFilePath); + InputStream uploadedInputStream = new FileInputStream(jsonRoleFile); + FormDataContentDisposition fileDetail = FormDataContentDisposition.name("file").fileName(jsonRoleFile.getName()).size(uploadedInputStream.toString().length()).build(); + boolean updateIfExists = false; + boolean createNonExistUserGroupRole = false; + + Mockito.when(searchUtil.getSearchFilter(request, roleService.sortFields)).thenReturn(filter); + Mockito.when(roleStore.getRoleNames(Mockito.any(SearchFilter.class))).thenReturn(roleList); + Mockito.when(roleStore.createRole(Mockito.any(RangerRole.class), eq(createNonExistUserGroupRole))).thenReturn(rangerRole); + + RESTResponse resp = roleRest.importRolesFromFile(request, uploadedInputStream, fileDetail, updateIfExists, createNonExistUserGroupRole); + Assert.assertNotNull(resp); + Assert.assertEquals(RESTResponse.STATUS_SUCCESS, resp.getStatusCode()); + Assert.assertEquals("Total Role Created = 6 , Total Role Unchanged = 1", resp.getMsgDesc()); + } + + // import role with updateIfExists=false and createNonExistUserGroupRole=true + @SuppressWarnings("unchecked") + @Test + public void test20bimportRolesFromFile() throws Exception { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + + List roleList = createRoleList(); + RangerRole rangerRole = createRoleWithUsersAndGroups(); + + SearchFilter filter = new SearchFilter(); + + File jsonRoleFile = new File(importRoleTestFilePath); + InputStream uploadedInputStream = new FileInputStream(jsonRoleFile); + FormDataContentDisposition fileDetail = FormDataContentDisposition.name("file").fileName(jsonRoleFile.getName()).size(uploadedInputStream.toString().length()).build(); + boolean updateIfExists = false; + boolean createNonExistUserGroupRole = true; + + Mockito.when(searchUtil.getSearchFilter(request, roleService.sortFields)).thenReturn(filter); + Mockito.when(roleStore.getRoleNames(Mockito.any(SearchFilter.class))).thenReturn(roleList); + Mockito.when(roleStore.createRole(Mockito.any(RangerRole.class), eq(createNonExistUserGroupRole))).thenReturn(rangerRole); + + RESTResponse resp = roleRest.importRolesFromFile(request, uploadedInputStream, fileDetail, updateIfExists, createNonExistUserGroupRole); + Assert.assertNotNull(resp); + Assert.assertEquals(RESTResponse.STATUS_SUCCESS, resp.getStatusCode()); + Assert.assertEquals("Total Role Created = 6 , Total Role Unchanged = 1", resp.getMsgDesc()); + } + + // import role with updateIfExists=true and createNonExistUserGroupRole=true + @SuppressWarnings("unchecked") + @Test + public void test20cimportRolesFromFileWithUpdate() throws Exception { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + + List roleList = createRoleList(); + RangerRole rangerRole = createRole(); + + SearchFilter filter = new SearchFilter(); + + File jsonRoleFile = new File(importRoleTestFilePath); + InputStream uploadedInputStream = new FileInputStream(jsonRoleFile); + FormDataContentDisposition fileDetail = FormDataContentDisposition.name("file").fileName(jsonRoleFile.getName()).size(uploadedInputStream.toString().length()).build(); + boolean updateIfExists = true; + boolean createNonExistUserGroupRole = true; + + Mockito.when(searchUtil.getSearchFilter(request, roleService.sortFields)).thenReturn(filter); + Mockito.when(roleStore.getRoleNames(Mockito.any(SearchFilter.class))).thenReturn(roleList); + Mockito.when(roleStore.getRole(Mockito.anyString())).thenReturn(rangerRole); + Mockito.when(roleStore.createRole(Mockito.any(RangerRole.class), eq(createNonExistUserGroupRole))).thenReturn(rangerRole); + + RESTResponse resp = roleRest.importRolesFromFile(request, uploadedInputStream, fileDetail, updateIfExists, createNonExistUserGroupRole); + Assert.assertNotNull(resp); + Assert.assertEquals(RESTResponse.STATUS_SUCCESS, resp.getStatusCode()); + Assert.assertEquals("Total Role Created = 6 , Total Role Updated = 1 , Total Role Unchanged = 0", resp.getMsgDesc()); + } + + // import role throws exceptions + @SuppressWarnings("unchecked") + @Test(expected = Throwable.class) + public void test20dimportRolesFromFileWithUpdate() throws Exception { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + + File jsonRoleFile = new File(importRoleTestFilePath); + InputStream uploadedInputStream = new FileInputStream(jsonRoleFile); + FormDataContentDisposition fileDetail = FormDataContentDisposition.name("file").fileName(jsonRoleFile.getName()).size(uploadedInputStream.toString().length()).build(); + boolean updateIfExists = false; + boolean createNonExistUserGroupRole = false; + + Mockito.when(roleStore.getRoleNames(Mockito.any(SearchFilter.class))).thenThrow(new Throwable()); + + Assert.assertThrows(Throwable.class, () -> roleRest.importRolesFromFile(request, uploadedInputStream, fileDetail, updateIfExists, createNonExistUserGroupRole)); + Mockito.verify(restErrorUtil).createRESTException(Mockito.anyString()); + } + + @Test(expected = Throwable.class) + public void test21deleteRoleWithinPolicy() { + RangerRole rangerRole = createRole(); + rangerPolicy(rangerRole); + try { + Mockito.doThrow(new Throwable()).when(roleStore).deleteRole(Mockito.anyLong()); + } catch (Throwable e) { + throw new RuntimeException(e); + } + + try { + Assert.assertThrows(Throwable.class, () -> roleRest.deleteRole(rangerRole.getId())); + Mockito.verify(restErrorUtil, Mockito.times(1)).createRESTException(Mockito.anyString()); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + @Test(expected = Throwable.class) + public void test22deleteRoleWithValidationError() { + RangerRole rangerRole = createRole(); + try { + Mockito.when(validatorFactory.getRangerRoleValidator(roleStore)).thenThrow(new Exception()); + } catch (Throwable e) { + throw new RuntimeException(e); + } + + try { + Assert.assertThrows(Throwable.class, () -> roleRest.deleteRole(rangerRole.getId())); + Mockito.verify(restErrorUtil, Mockito.times(1)).createRESTException(Mockito.anyString()); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + private RangerRole createRole() { + String name = "test-role"; + String name2 = "admin"; + RangerRole.RoleMember rm1 = new RangerRole.RoleMember(name, true); + RangerRole.RoleMember rm2 = new RangerRole.RoleMember(name2, true); + List usersList = new ArrayList<>(Arrays.asList(rm1, rm2)); + RangerRole rangerRole = new RangerRole(name, name, null, usersList, null); rangerRole.setCreatedByUser(name); rangerRole.setId(roleId); return rangerRole; } - private RangerRole createRoleWithUsersAndGroups(){ - String userName1 = "test-role"; - String userName2 = "admin"; - String groupName1 = "test-group"; - String groupName2 = "admin"; - RangerRole.RoleMember rm1 = new RangerRole.RoleMember(userName1,true); - RangerRole.RoleMember rm2 = new RangerRole.RoleMember(userName2, true); - List usersList = new ArrayList<>(Arrays.asList(rm1,rm2)); - RangerRole.RoleMember rm3 = new RangerRole.RoleMember(groupName1,true); - RangerRole.RoleMember rm4 = new RangerRole.RoleMember(groupName2, true); - List groupList = new ArrayList<>(Arrays.asList(rm3,rm4)); + private RangerRole createRoleWithUsersAndGroups() { + String userName1 = "test-role"; + String userName2 = "admin"; + String groupName1 = "test-group"; + String groupName2 = "admin"; + RangerRole.RoleMember rm1 = new RangerRole.RoleMember(userName1, true); + RangerRole.RoleMember rm2 = new RangerRole.RoleMember(userName2, true); + List usersList = new ArrayList<>(Arrays.asList(rm1, rm2)); + RangerRole.RoleMember rm3 = new RangerRole.RoleMember(groupName1, true); + RangerRole.RoleMember rm4 = new RangerRole.RoleMember(groupName2, true); + List groupList = new ArrayList<>(Arrays.asList(rm3, rm4)); RangerRole rangerRole = new RangerRole(userName1, userName1, null, usersList, groupList); rangerRole.setCreatedByUser(userName1); @@ -1229,32 +1247,33 @@ private RangerRole createRoleWithUsersAndGroups(){ return rangerRole; } - private RangerRole createRoleInvalidMember(){ - String name = "{OWNER}"; - String name2 = "admin"; - RangerRole.RoleMember rm1 = new RangerRole.RoleMember(name,true); - RangerRole.RoleMember rm2 = new RangerRole.RoleMember(name2, true); - List usersList = new ArrayList<>(Arrays.asList(rm1,rm2)); - RangerRole rangerRole = new RangerRole(name, name, null, usersList, null); + private RangerRole createRoleInvalidMember() { + String name = "{OWNER}"; + String name2 = "admin"; + RangerRole.RoleMember rm1 = new RangerRole.RoleMember(name, true); + RangerRole.RoleMember rm2 = new RangerRole.RoleMember(name2, true); + List usersList = new ArrayList<>(Arrays.asList(rm1, rm2)); + RangerRole rangerRole = new RangerRole(name, name, null, usersList, null); rangerRole.setCreatedByUser(name); rangerRole.setId(roleId); return rangerRole; } - private RangerRole createRoleOld(){ - String name = "test-role2"; - String name2 = "admin"; - RangerRole.RoleMember rm1 = new RangerRole.RoleMember(name,true); - RangerRole.RoleMember rm2 = new RangerRole.RoleMember(name2, true); - List usersList = Arrays.asList(rm1,rm2); - RangerRole rangerRole = new RangerRole(name, name, null, usersList, null); + private RangerRole createRoleOld() { + String name = "test-role2"; + String name2 = "admin"; + RangerRole.RoleMember rm1 = new RangerRole.RoleMember(name, true); + RangerRole.RoleMember rm2 = new RangerRole.RoleMember(name2, true); + List usersList = Arrays.asList(rm1, rm2); + RangerRole rangerRole = new RangerRole(name, name, null, usersList, null); rangerRole.setCreatedByUser(name); rangerRole.setId(roleId); return rangerRole; } + private VXUser createVXUser() { - VXUser testVXUser= new VXUser(); - Collection c = new ArrayList(); + VXUser testVXUser = new VXUser(); + Collection c = new ArrayList<>(); testVXUser.setId(userId); testVXUser.setCreateDate(new Date()); testVXUser.setUpdateDate(new Date()); @@ -1274,37 +1293,37 @@ private VXUser createVXUser() { return testVXUser; } - private List createXXRoleRefGroupList(){ - List xxRoleRefGroupList = new ArrayList(); - XXRoleRefGroup xxRoleRefGroup1 = new XXRoleRefGroup(); + private List createXXRoleRefGroupList() { + List xxRoleRefGroupList = new ArrayList<>(); + XXRoleRefGroup xxRoleRefGroup1 = new XXRoleRefGroup(); xxRoleRefGroup1.setRoleId(roleId); xxRoleRefGroupList.add(xxRoleRefGroup1); return xxRoleRefGroupList; } - private List createXXRoleRefUserList(){ - List xxRoleRefUserList = new ArrayList(); - XXRoleRefUser xxRoleRefUser1 = new XXRoleRefUser(); + private List createXXRoleRefUserList() { + List xxRoleRefUserList = new ArrayList<>(); + XXRoleRefUser xxRoleRefUser1 = new XXRoleRefUser(); xxRoleRefUser1.setRoleId(roleId); xxRoleRefUserList.add(xxRoleRefUser1); return xxRoleRefUserList; } - private List createRoleList(){ - List roleList = new ArrayList(); + private List createRoleList() { + List roleList = new ArrayList<>(); roleList.add("admin"); roleList.add("user"); return roleList; } - private RangerRoles createRangerRoles(){ - Set rangerRolesSet = new HashSet<>(Arrays.asList(createRole())); - RangerRoles rangerRoles = new RangerRoles(); + private RangerRoles createRangerRoles() { + Set rangerRolesSet = new HashSet<>(Collections.singletonList(createRole())); + RangerRoles rangerRoles = new RangerRoles(); rangerRoles.setRangerRoles(rangerRolesSet); return rangerRoles; } - private XXService createXXService(){ + private XXService createXXService() { XXService xxService = new XXService(); xxService.setId(1L); xxService.setName("test-service"); @@ -1315,75 +1334,40 @@ private XXService createXXService(){ return xxService; } - private GrantRevokeRoleRequest createGrantRevokeRoleRequest(){ - Set users = new HashSet<>(Arrays.asList("test-role","admin")); - Set groups = new HashSet<>(Arrays.asList("test-group","admin")); + private GrantRevokeRoleRequest createGrantRevokeRoleRequest() { + Set users = new HashSet<>(Arrays.asList("test-role", "admin")); + Set groups = new HashSet<>(Arrays.asList("test-group", "admin")); GrantRevokeRoleRequest roleRequest = new GrantRevokeRoleRequest(); roleRequest.setUsers(users); roleRequest.setGroups(groups); roleRequest.setGrantor("admin"); - roleRequest.setTargetRoles(new HashSet<>(Arrays.asList("role1","role2"))); + roleRequest.setTargetRoles(new HashSet<>(Arrays.asList("role1", "role2"))); return roleRequest; } private RangerRole createRangerRole(String name, boolean isAdmin) { - RangerRole.RoleMember roleMember = new RangerRole.RoleMember(name, isAdmin); - List usersList = Collections.singletonList(roleMember); - RangerRole rangerRole = new RangerRole(name, name, null, usersList, null); + RangerRole.RoleMember roleMember = new RangerRole.RoleMember(name, isAdmin); + List usersList = Collections.singletonList(roleMember); + RangerRole rangerRole = new RangerRole(name, name, null, usersList, null); rangerRole.setCreatedByUser(name); rangerRole.setId(roleId); return rangerRole; } - @Test(expected = Throwable.class) - public void test21deleteRoleWithinPolicy() { - RangerRole rangerRole = createRole(); - rangerPolicy(rangerRole); - try { - Mockito.doThrow(new Throwable()).when(roleStore).deleteRole(Mockito.anyLong()); - } catch (Throwable e) { - throw new RuntimeException(e); - } - - try { - Assert.assertThrows(Throwable.class, () -> roleRest.deleteRole(rangerRole.getId())); - Mockito.verify(restErrorUtil, Mockito.times(1)).createRESTException(Mockito.anyString()); - } catch (Exception e) { - throw new RuntimeException(e); - } - } - - @Test(expected = Throwable.class) - public void test22deleteRoleWithValidationError() { - RangerRole rangerRole = createRole(); - try { - Mockito.when(validatorFactory.getRangerRoleValidator(roleStore)).thenThrow(new Exception()); - } catch (Throwable e) { - throw new RuntimeException(e); - } - - try { - Assert.assertThrows(Throwable.class,() -> roleRest.deleteRole(rangerRole.getId())); - Mockito.verify(restErrorUtil, Mockito.times(1)).createRESTException(Mockito.anyString()); - } catch (Exception e) { - throw new RuntimeException(e); - } - } - - private RangerPolicy rangerPolicy(RangerRole rangerRole) { - List roles = new ArrayList<>(); - roles.add(rangerRole.getName()); + private RangerPolicy rangerPolicy(RangerRole rangerRole) { + List roles = new ArrayList<>(); + roles.add(rangerRole.getName()); - List policyItems = new ArrayList<>(); + List policyItems = new ArrayList<>(); - policyItems.add(new RangerPolicyItem(new ArrayList<>(), new ArrayList<>(), new ArrayList<>(), roles, new ArrayList<>(), false)); + policyItems.add(new RangerPolicyItem(new ArrayList<>(), new ArrayList<>(), new ArrayList<>(), roles, new ArrayList<>(), false)); - Map policyResource = new HashMap<>(); + Map policyResource = new HashMap<>(); - policyResource.put("resource", new RangerPolicyResource("1", true, true)); + policyResource.put("resource", new RangerPolicyResource("1", true, true)); - return getRangerPolicy(policyItems, policyResource); - } + return getRangerPolicy(policyItems, policyResource); + } private static RangerPolicy getRangerPolicy(List policyItems, Map policyResource) { RangerPolicy policy = new RangerPolicy(); diff --git a/security-admin/src/test/java/org/apache/ranger/rest/TestSecurityZoneREST.java b/security-admin/src/test/java/org/apache/ranger/rest/TestSecurityZoneREST.java index f433719ed3..21f161f33b 100644 --- a/security-admin/src/test/java/org/apache/ranger/rest/TestSecurityZoneREST.java +++ b/security-admin/src/test/java/org/apache/ranger/rest/TestSecurityZoneREST.java @@ -17,21 +17,6 @@ */ package org.apache.ranger.rest; -import static org.junit.Assert.assertEquals; -import static org.mockito.Mockito.doNothing; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.WebApplicationException; - import org.apache.ranger.biz.RangerBizUtil; import org.apache.ranger.biz.SecurityZoneDBStore; import org.apache.ranger.biz.ServiceDBStore; @@ -59,228 +44,236 @@ import org.mockito.Mockito; import org.mockito.junit.MockitoJUnitRunner; +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.WebApplicationException; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + @RunWith(MockitoJUnitRunner.Silent.class) public class TestSecurityZoneREST { - @InjectMocks - SecurityZoneREST securityZoneREST = new SecurityZoneREST(); - @Mock - RangerValidatorFactory validatorFactory; - @Mock - RangerSecurityZoneValidator validator; - @Mock - SecurityZoneDBStore securityZoneStore; - @Mock - RangerBizUtil rangerBizUtil; - @Mock - ServiceDBStore svcStore; - @Mock - RangerSearchUtil searchUtil; - @Mock + @Rule + public ExpectedException thrown = ExpectedException.none(); + @InjectMocks + SecurityZoneREST securityZoneREST = new SecurityZoneREST(); + @Mock + RangerValidatorFactory validatorFactory; + @Mock + RangerSecurityZoneValidator validator; + @Mock + SecurityZoneDBStore securityZoneStore; + @Mock + RangerBizUtil rangerBizUtil; + @Mock + ServiceDBStore svcStore; + @Mock + RangerSearchUtil searchUtil; + @Mock RangerSecurityZoneServiceService securityZoneService; - @Mock - RESTErrorUtil restErrorUtil; - @Mock - RangerDaoManager daoManager; - @Mock - XXServiceDef xServiceDef; - - @Rule - public ExpectedException thrown = ExpectedException.none(); - - private RangerSecurityZone createRangerSecurityZone() { - String testZone1 = "testzone1"; - List testZone1ResoursesList = new ArrayList(Arrays.asList("/path/to/resource1", "/path/to/resource2")); - List userGroupList = new ArrayList(Arrays.asList("testuser", "testgroup")); - - RangerSecurityZone zone = new RangerSecurityZone(); - zone.setName(testZone1); - zone.setAdminUserGroups(userGroupList); - zone.setAdminUsers(userGroupList); - zone.setAuditUserGroups(userGroupList); - zone.setAuditUsers(userGroupList); - Map services = new HashMap<>(); - - List>> resources = new ArrayList<>(); - HashMap> resource = new HashMap>(); - - resource.put("resource_path", testZone1ResoursesList); - - resources.add(resource); - - RangerSecurityZoneService zoneService = new RangerSecurityZoneService(); - - zoneService.setResources(resources); - services.put("test_service_1", zoneService); - zone.setServices(services); - return zone; - } - - @Test - public void testCreateSecurityZone() throws Exception { - RangerSecurityZone rangerSecurityZone = createRangerSecurityZone(); - XXServiceDao xServiceDao = Mockito.mock(XXServiceDao.class); - XXService xService = Mockito.mock(XXService.class); - XXServiceDefDao xServiceDefDao = Mockito.mock(XXServiceDefDao.class); - when(rangerBizUtil.isAdmin()).thenReturn(true); - when(daoManager.getXXService()).thenReturn(xServiceDao); - when(xServiceDao.findByName("test_service_1")).thenReturn(xService); - - when(daoManager.getXXServiceDef()).thenReturn(xServiceDefDao); - when(xServiceDefDao.getById(xService.getType())).thenReturn(xServiceDef); - - when(validatorFactory.getSecurityZoneValidator(svcStore, securityZoneStore)).thenReturn(validator); - doNothing().when(validator).validate(rangerSecurityZone, RangerValidator.Action.CREATE); - when(securityZoneStore.createSecurityZone(rangerSecurityZone)).thenReturn(rangerSecurityZone); - RangerSecurityZone createdRangerSecurityZone = securityZoneREST.createSecurityZone(rangerSecurityZone); - assertEquals(createdRangerSecurityZone.getName(), rangerSecurityZone.getName()); - verify(validator, times(1)).validate(rangerSecurityZone, RangerValidator.Action.CREATE); - } - - @Test - public void testUpdateSecurityZone() throws Exception { - RangerSecurityZone rangerSecurityZoneToUpdate = createRangerSecurityZone(); - Long securityZoneId = 2L; - XXServiceDao xServiceDao = Mockito.mock(XXServiceDao.class); - XXService xService = Mockito.mock(XXService.class); - XXServiceDefDao xServiceDefDao = Mockito.mock(XXServiceDefDao.class); - rangerSecurityZoneToUpdate.setId(securityZoneId); - when(rangerBizUtil.isAdmin()).thenReturn(true); - when(validatorFactory.getSecurityZoneValidator(svcStore, securityZoneStore)).thenReturn(validator); - - when(daoManager.getXXService()).thenReturn(xServiceDao); - when(xServiceDao.findByName("test_service_1")).thenReturn(xService); - - when(daoManager.getXXServiceDef()).thenReturn(xServiceDefDao); - when(xServiceDefDao.getById(xService.getType())).thenReturn(xServiceDef); - - doNothing().when(validator).validate(rangerSecurityZoneToUpdate, RangerValidator.Action.UPDATE); - when(securityZoneStore.updateSecurityZoneById(rangerSecurityZoneToUpdate)) - .thenReturn(rangerSecurityZoneToUpdate); - RangerSecurityZone updatedRangerSecurityZone = securityZoneREST.updateSecurityZone(securityZoneId, - rangerSecurityZoneToUpdate); - assertEquals(rangerSecurityZoneToUpdate.getId(), updatedRangerSecurityZone.getId()); - verify(validator, times(1)).validate(rangerSecurityZoneToUpdate, RangerValidator.Action.UPDATE); - } - - @Test - public void testUpdateSecurityZoneWithMisMatchId() throws Exception { - RangerSecurityZone rangerSecurityZoneToUpdate = createRangerSecurityZone(); - Long securityZoneId = 2L; - XXServiceDefDao xServiceDefDao = Mockito.mock(XXServiceDefDao.class); - XXServiceDao xServiceDao = Mockito.mock(XXServiceDao.class); - XXService xService = Mockito.mock(XXService.class); - - rangerSecurityZoneToUpdate.setId(securityZoneId); - when(rangerBizUtil.isAdmin()).thenReturn(true); - - when(daoManager.getXXService()).thenReturn(xServiceDao); - when(xServiceDao.findByName("test_service_1")).thenReturn(xService); - - when(daoManager.getXXServiceDef()).thenReturn(xServiceDefDao); - when(xServiceDefDao.getById(xService.getType())).thenReturn(xServiceDef); - - when(validatorFactory.getSecurityZoneValidator(svcStore, securityZoneStore)).thenReturn(validator); - doNothing().when(validator).validate(rangerSecurityZoneToUpdate, RangerValidator.Action.UPDATE); - when(securityZoneStore.updateSecurityZoneById(rangerSecurityZoneToUpdate)) - .thenReturn(rangerSecurityZoneToUpdate); - when(restErrorUtil.createRESTException(Mockito.anyString())).thenThrow(new WebApplicationException()); - thrown.expect(WebApplicationException.class); - RangerSecurityZone updatedRangerSecurityZone = securityZoneREST.updateSecurityZone(9L, - rangerSecurityZoneToUpdate); - assertEquals(rangerSecurityZoneToUpdate.getId(), updatedRangerSecurityZone.getId()); - verify(validator, times(1)).validate(rangerSecurityZoneToUpdate, RangerValidator.Action.UPDATE); - } - - @Test(expected = WebApplicationException.class) - public void testGetSecurityZoneById() throws Exception { - RangerSecurityZone securityZone = createRangerSecurityZone(); - Long securityZoneId = 2L; - securityZone.setId(securityZoneId); - when(securityZoneStore.getSecurityZone(securityZoneId)).thenReturn(securityZone); - when(rangerBizUtil.hasModuleAccess(Mockito.anyString())).thenReturn(true); - RangerSecurityZone rangerSecurityZone = securityZoneREST.getSecurityZone(securityZoneId); - assertEquals(securityZoneId, rangerSecurityZone.getId()); - verify(securityZoneStore, times(1)).getSecurityZone(securityZoneId); - - //No access - when(rangerBizUtil.hasModuleAccess(Mockito.anyString())).thenReturn(false); - when(restErrorUtil.createRESTException(Mockito.anyString(), Mockito.any())).thenReturn(new WebApplicationException()); - securityZoneREST.getSecurityZone(securityZoneId); - verify(securityZoneStore, times(0)).getSecurityZone(securityZoneId); - } - - @Test(expected = WebApplicationException.class) - public void testGetSecurityZoneByName() throws Exception { - RangerSecurityZone securityZone = createRangerSecurityZone(); - Long securityZoneId = 2L; - String securityZoneName = securityZone.getName(); - securityZone.setId(securityZoneId); - when(securityZoneStore.getSecurityZoneByName(securityZoneName)).thenReturn(securityZone); - when(rangerBizUtil.hasModuleAccess(Mockito.anyString())).thenReturn(true); - RangerSecurityZone rangerSecurityZone = securityZoneREST.getSecurityZone(securityZoneName); - assertEquals(securityZoneName, rangerSecurityZone.getName()); - verify(securityZoneStore, times(1)).getSecurityZoneByName(securityZoneName); - - //No access - when(rangerBizUtil.hasModuleAccess(Mockito.anyString())).thenReturn(false); - when(restErrorUtil.createRESTException(Mockito.anyString(), Mockito.any())).thenReturn(new WebApplicationException()); - securityZoneREST.getSecurityZone(securityZoneName); - verify(securityZoneStore, times(0)).getSecurityZoneByName(securityZoneName); - } - - @Test(expected = WebApplicationException.class) - public void testGetAllSecurityZone() throws Exception { - RangerSecurityZone securityZone = createRangerSecurityZone(); - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - SearchFilter filter = new SearchFilter(); - when( - searchUtil.getSearchFilter(request, securityZoneService.sortFields)) - .thenReturn(filter); - Long securityZoneId = 2L; - securityZone.setId(securityZoneId); - List zonesList = new ArrayList<>(); - zonesList.add(securityZone); - RangerSecurityZoneList rangerZoneList = new RangerSecurityZoneList(); - rangerZoneList.setSecurityZoneList(zonesList); - - when(securityZoneStore.getSecurityZones(filter)).thenReturn(zonesList); - when(rangerBizUtil.hasModuleAccess(Mockito.anyString())).thenReturn(true); - - RangerSecurityZoneList returnedZonesList = securityZoneREST.getAllZones(request); - assertEquals(returnedZonesList.getResultSize(), rangerZoneList.getList().size()); - verify(securityZoneStore, times(1)).getSecurityZones(filter); - - //No access - when(rangerBizUtil.hasModuleAccess(Mockito.anyString())).thenReturn(false); - when(restErrorUtil.createRESTException(Mockito.anyString(), Mockito.any())).thenReturn(new WebApplicationException()); - securityZoneREST.getAllZones(request); - verify(securityZoneStore, times(0)).getSecurityZones(filter); - } - - @Test - public void testDeleteSecurityZoneById() throws Exception { - RangerSecurityZone securityZone = createRangerSecurityZone(); - Long securityZoneId = 2L; - securityZone.setId(securityZoneId); - when(rangerBizUtil.isAdmin()).thenReturn(true); - when(validatorFactory.getSecurityZoneValidator(svcStore, securityZoneStore)).thenReturn(validator); - doNothing().when(validator).validate(securityZoneId, RangerValidator.Action.DELETE); - securityZoneREST.deleteSecurityZone(securityZoneId); - verify(securityZoneStore, times(1)).deleteSecurityZoneById(securityZoneId); - - } - - @Test - public void testDeleteSecurityZoneByName() throws Exception { - RangerSecurityZone securityZone = createRangerSecurityZone(); - Long securityZoneId = 2L; - securityZone.setId(securityZoneId); - String securityZoneName = securityZone.getName(); - when(rangerBizUtil.isAdmin()).thenReturn(true); - when(validatorFactory.getSecurityZoneValidator(svcStore, securityZoneStore)).thenReturn(validator); - doNothing().when(validator).validate(securityZoneName, RangerValidator.Action.DELETE); - securityZoneREST.deleteSecurityZone(securityZoneName); - verify(securityZoneStore, times(1)).deleteSecurityZoneByName(securityZoneName); - - } + @Mock + RESTErrorUtil restErrorUtil; + @Mock + RangerDaoManager daoManager; + @Mock + XXServiceDef xServiceDef; + + @Test + public void testCreateSecurityZone() throws Exception { + RangerSecurityZone rangerSecurityZone = createRangerSecurityZone(); + XXServiceDao xServiceDao = Mockito.mock(XXServiceDao.class); + XXService xService = Mockito.mock(XXService.class); + XXServiceDefDao xServiceDefDao = Mockito.mock(XXServiceDefDao.class); + when(rangerBizUtil.isAdmin()).thenReturn(true); + when(daoManager.getXXService()).thenReturn(xServiceDao); + when(xServiceDao.findByName("test_service_1")).thenReturn(xService); + + when(daoManager.getXXServiceDef()).thenReturn(xServiceDefDao); + when(xServiceDefDao.getById(xService.getType())).thenReturn(xServiceDef); + + when(validatorFactory.getSecurityZoneValidator(svcStore, securityZoneStore)).thenReturn(validator); + doNothing().when(validator).validate(rangerSecurityZone, RangerValidator.Action.CREATE); + when(securityZoneStore.createSecurityZone(rangerSecurityZone)).thenReturn(rangerSecurityZone); + RangerSecurityZone createdRangerSecurityZone = securityZoneREST.createSecurityZone(rangerSecurityZone); + assertEquals(createdRangerSecurityZone.getName(), rangerSecurityZone.getName()); + verify(validator, times(1)).validate(rangerSecurityZone, RangerValidator.Action.CREATE); + } + + @Test + public void testUpdateSecurityZone() throws Exception { + RangerSecurityZone rangerSecurityZoneToUpdate = createRangerSecurityZone(); + Long securityZoneId = 2L; + XXServiceDao xServiceDao = Mockito.mock(XXServiceDao.class); + XXService xService = Mockito.mock(XXService.class); + XXServiceDefDao xServiceDefDao = Mockito.mock(XXServiceDefDao.class); + rangerSecurityZoneToUpdate.setId(securityZoneId); + when(rangerBizUtil.isAdmin()).thenReturn(true); + when(validatorFactory.getSecurityZoneValidator(svcStore, securityZoneStore)).thenReturn(validator); + + when(daoManager.getXXService()).thenReturn(xServiceDao); + when(xServiceDao.findByName("test_service_1")).thenReturn(xService); + + when(daoManager.getXXServiceDef()).thenReturn(xServiceDefDao); + when(xServiceDefDao.getById(xService.getType())).thenReturn(xServiceDef); + + doNothing().when(validator).validate(rangerSecurityZoneToUpdate, RangerValidator.Action.UPDATE); + when(securityZoneStore.updateSecurityZoneById(rangerSecurityZoneToUpdate)).thenReturn(rangerSecurityZoneToUpdate); + RangerSecurityZone updatedRangerSecurityZone = securityZoneREST.updateSecurityZone(securityZoneId, rangerSecurityZoneToUpdate); + assertEquals(rangerSecurityZoneToUpdate.getId(), updatedRangerSecurityZone.getId()); + verify(validator, times(1)).validate(rangerSecurityZoneToUpdate, RangerValidator.Action.UPDATE); + } + + @Test + public void testUpdateSecurityZoneWithMisMatchId() throws Exception { + RangerSecurityZone rangerSecurityZoneToUpdate = createRangerSecurityZone(); + Long securityZoneId = 2L; + XXServiceDefDao xServiceDefDao = Mockito.mock(XXServiceDefDao.class); + XXServiceDao xServiceDao = Mockito.mock(XXServiceDao.class); + XXService xService = Mockito.mock(XXService.class); + + rangerSecurityZoneToUpdate.setId(securityZoneId); + when(rangerBizUtil.isAdmin()).thenReturn(true); + + when(daoManager.getXXService()).thenReturn(xServiceDao); + when(xServiceDao.findByName("test_service_1")).thenReturn(xService); + + when(daoManager.getXXServiceDef()).thenReturn(xServiceDefDao); + when(xServiceDefDao.getById(xService.getType())).thenReturn(xServiceDef); + + when(validatorFactory.getSecurityZoneValidator(svcStore, securityZoneStore)).thenReturn(validator); + doNothing().when(validator).validate(rangerSecurityZoneToUpdate, RangerValidator.Action.UPDATE); + when(securityZoneStore.updateSecurityZoneById(rangerSecurityZoneToUpdate)).thenReturn(rangerSecurityZoneToUpdate); + when(restErrorUtil.createRESTException(Mockito.anyString())).thenThrow(new WebApplicationException()); + thrown.expect(WebApplicationException.class); + RangerSecurityZone updatedRangerSecurityZone = securityZoneREST.updateSecurityZone(9L, rangerSecurityZoneToUpdate); + assertEquals(rangerSecurityZoneToUpdate.getId(), updatedRangerSecurityZone.getId()); + verify(validator, times(1)).validate(rangerSecurityZoneToUpdate, RangerValidator.Action.UPDATE); + } + + @Test(expected = WebApplicationException.class) + public void testGetSecurityZoneById() throws Exception { + RangerSecurityZone securityZone = createRangerSecurityZone(); + Long securityZoneId = 2L; + securityZone.setId(securityZoneId); + when(securityZoneStore.getSecurityZone(securityZoneId)).thenReturn(securityZone); + when(rangerBizUtil.hasModuleAccess(Mockito.anyString())).thenReturn(true); + RangerSecurityZone rangerSecurityZone = securityZoneREST.getSecurityZone(securityZoneId); + assertEquals(securityZoneId, rangerSecurityZone.getId()); + verify(securityZoneStore, times(1)).getSecurityZone(securityZoneId); + + //No access + when(rangerBizUtil.hasModuleAccess(Mockito.anyString())).thenReturn(false); + when(restErrorUtil.createRESTException(Mockito.anyString(), Mockito.any())).thenReturn(new WebApplicationException()); + securityZoneREST.getSecurityZone(securityZoneId); + verify(securityZoneStore, times(0)).getSecurityZone(securityZoneId); + } + + @Test(expected = WebApplicationException.class) + public void testGetSecurityZoneByName() throws Exception { + RangerSecurityZone securityZone = createRangerSecurityZone(); + Long securityZoneId = 2L; + String securityZoneName = securityZone.getName(); + securityZone.setId(securityZoneId); + when(securityZoneStore.getSecurityZoneByName(securityZoneName)).thenReturn(securityZone); + when(rangerBizUtil.hasModuleAccess(Mockito.anyString())).thenReturn(true); + RangerSecurityZone rangerSecurityZone = securityZoneREST.getSecurityZone(securityZoneName); + assertEquals(securityZoneName, rangerSecurityZone.getName()); + verify(securityZoneStore, times(1)).getSecurityZoneByName(securityZoneName); + + //No access + when(rangerBizUtil.hasModuleAccess(Mockito.anyString())).thenReturn(false); + when(restErrorUtil.createRESTException(Mockito.anyString(), Mockito.any())).thenReturn(new WebApplicationException()); + securityZoneREST.getSecurityZone(securityZoneName); + verify(securityZoneStore, times(0)).getSecurityZoneByName(securityZoneName); + } + + @Test(expected = WebApplicationException.class) + public void testGetAllSecurityZone() throws Exception { + RangerSecurityZone securityZone = createRangerSecurityZone(); + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + SearchFilter filter = new SearchFilter(); + when( + searchUtil.getSearchFilter(request, securityZoneService.sortFields)) + .thenReturn(filter); + Long securityZoneId = 2L; + securityZone.setId(securityZoneId); + List zonesList = new ArrayList<>(); + zonesList.add(securityZone); + RangerSecurityZoneList rangerZoneList = new RangerSecurityZoneList(); + rangerZoneList.setSecurityZoneList(zonesList); + + when(securityZoneStore.getSecurityZones(filter)).thenReturn(zonesList); + when(rangerBizUtil.hasModuleAccess(Mockito.anyString())).thenReturn(true); + + RangerSecurityZoneList returnedZonesList = securityZoneREST.getAllZones(request); + assertEquals(returnedZonesList.getResultSize(), rangerZoneList.getList().size()); + verify(securityZoneStore, times(1)).getSecurityZones(filter); + + //No access + when(rangerBizUtil.hasModuleAccess(Mockito.anyString())).thenReturn(false); + when(restErrorUtil.createRESTException(Mockito.anyString(), Mockito.any())).thenReturn(new WebApplicationException()); + securityZoneREST.getAllZones(request); + verify(securityZoneStore, times(0)).getSecurityZones(filter); + } + + @Test + public void testDeleteSecurityZoneById() throws Exception { + RangerSecurityZone securityZone = createRangerSecurityZone(); + Long securityZoneId = 2L; + securityZone.setId(securityZoneId); + when(rangerBizUtil.isAdmin()).thenReturn(true); + when(validatorFactory.getSecurityZoneValidator(svcStore, securityZoneStore)).thenReturn(validator); + doNothing().when(validator).validate(securityZoneId, RangerValidator.Action.DELETE); + securityZoneREST.deleteSecurityZone(securityZoneId); + verify(securityZoneStore, times(1)).deleteSecurityZoneById(securityZoneId); + } + + @Test + public void testDeleteSecurityZoneByName() throws Exception { + RangerSecurityZone securityZone = createRangerSecurityZone(); + Long securityZoneId = 2L; + securityZone.setId(securityZoneId); + String securityZoneName = securityZone.getName(); + when(rangerBizUtil.isAdmin()).thenReturn(true); + when(validatorFactory.getSecurityZoneValidator(svcStore, securityZoneStore)).thenReturn(validator); + doNothing().when(validator).validate(securityZoneName, RangerValidator.Action.DELETE); + securityZoneREST.deleteSecurityZone(securityZoneName); + verify(securityZoneStore, times(1)).deleteSecurityZoneByName(securityZoneName); + } + + private RangerSecurityZone createRangerSecurityZone() { + String testZone1 = "testzone1"; + List testZone1ResoursesList = new ArrayList(Arrays.asList("/path/to/resource1", "/path/to/resource2")); + List userGroupList = new ArrayList(Arrays.asList("testuser", "testgroup")); + + RangerSecurityZone zone = new RangerSecurityZone(); + zone.setName(testZone1); + zone.setAdminUserGroups(userGroupList); + zone.setAdminUsers(userGroupList); + zone.setAuditUserGroups(userGroupList); + zone.setAuditUsers(userGroupList); + Map services = new HashMap<>(); + + List>> resources = new ArrayList<>(); + HashMap> resource = new HashMap<>(); + + resource.put("resource_path", testZone1ResoursesList); + + resources.add(resource); + + RangerSecurityZoneService zoneService = new RangerSecurityZoneService(); + + zoneService.setResources(resources); + services.put("test_service_1", zoneService); + zone.setServices(services); + return zone; + } } diff --git a/security-admin/src/test/java/org/apache/ranger/rest/TestServiceREST.java b/security-admin/src/test/java/org/apache/ranger/rest/TestServiceREST.java index 15011a34ac..3683442be9 100644 --- a/security-admin/src/test/java/org/apache/ranger/rest/TestServiceREST.java +++ b/security-admin/src/test/java/org/apache/ranger/rest/TestServiceREST.java @@ -17,23 +17,14 @@ */ package org.apache.ranger.rest; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.*; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.ws.rs.WebApplicationException; - +import com.sun.jersey.core.header.FormDataContentDisposition; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.StringUtils; import org.apache.ranger.admin.client.datatype.RESTResponse; import org.apache.ranger.biz.AssetMgr; -import org.apache.ranger.biz.RangerPolicyAdmin; import org.apache.ranger.biz.RangerBizUtil; +import org.apache.ranger.biz.RangerPolicyAdmin; import org.apache.ranger.biz.SecurityZoneDBStore; import org.apache.ranger.biz.ServiceDBStore; import org.apache.ranger.biz.ServiceDBStore.JSON_FILE_NAME_TYPE; @@ -41,7 +32,6 @@ import org.apache.ranger.biz.TagDBStore; import org.apache.ranger.biz.XUserMgr; import org.apache.ranger.common.ContextUtil; -import org.apache.ranger.common.MessageEnums; import org.apache.ranger.common.RESTErrorUtil; import org.apache.ranger.common.RangerConstants; import org.apache.ranger.common.RangerSearchUtil; @@ -57,18 +47,29 @@ import org.apache.ranger.db.XXSecurityZoneRefTagServiceDao; import org.apache.ranger.db.XXServiceDao; import org.apache.ranger.db.XXServiceDefDao; -import org.apache.ranger.entity.*; -import org.apache.ranger.plugin.model.*; +import org.apache.ranger.entity.XXPolicy; +import org.apache.ranger.entity.XXPortalUser; +import org.apache.ranger.entity.XXRole; +import org.apache.ranger.entity.XXSecurityZone; +import org.apache.ranger.entity.XXSecurityZoneRefService; +import org.apache.ranger.entity.XXSecurityZoneRefTagService; +import org.apache.ranger.entity.XXService; +import org.apache.ranger.entity.XXServiceDef; +import org.apache.ranger.plugin.model.RangerPluginInfo; +import org.apache.ranger.plugin.model.RangerPolicy; import org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyItem; import org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyItemAccess; import org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyItemCondition; import org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyResource; +import org.apache.ranger.plugin.model.RangerService; +import org.apache.ranger.plugin.model.RangerServiceDef; import org.apache.ranger.plugin.model.RangerServiceDef.RangerAccessTypeDef; import org.apache.ranger.plugin.model.RangerServiceDef.RangerContextEnricherDef; import org.apache.ranger.plugin.model.RangerServiceDef.RangerEnumDef; import org.apache.ranger.plugin.model.RangerServiceDef.RangerPolicyConditionDef; import org.apache.ranger.plugin.model.RangerServiceDef.RangerResourceDef; import org.apache.ranger.plugin.model.RangerServiceDef.RangerServiceConfigDef; +import org.apache.ranger.plugin.model.ServiceDeleteResponse; import org.apache.ranger.plugin.model.validation.RangerPolicyValidator; import org.apache.ranger.plugin.model.validation.RangerServiceDefValidator; import org.apache.ranger.plugin.model.validation.RangerServiceValidator; @@ -92,10 +93,18 @@ import org.apache.ranger.service.RangerServiceDefService; import org.apache.ranger.service.RangerServiceService; import org.apache.ranger.service.XUserService; -import org.apache.ranger.view.*; +import org.apache.ranger.view.RangerExportPolicyList; +import org.apache.ranger.view.RangerPluginInfoList; +import org.apache.ranger.view.RangerPolicyList; +import org.apache.ranger.view.RangerServiceDefList; +import org.apache.ranger.view.RangerServiceList; +import org.apache.ranger.view.VXGroup; +import org.apache.ranger.view.VXResponse; +import org.apache.ranger.view.VXString; +import org.apache.ranger.view.VXUser; import org.junit.Assert; -import org.junit.Ignore; import org.junit.FixMethodOrder; +import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; @@ -106,2702 +115,2472 @@ import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.junit.MockitoJUnitRunner; - -import com.sun.jersey.core.header.FormDataContentDisposition; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.WebApplicationException; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Date; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + import static org.mockito.ArgumentMatchers.eq; @RunWith(MockitoJUnitRunner.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class TestServiceREST { + private static final Long Id = 8L; + + private final String grantor = "test-grantor-1"; + private final String ownerUser = "test-owner-user-1"; + private final String zoneName = "test-zone-1"; + @Rule + public ExpectedException thrown = ExpectedException.none(); + String importPoliceTestFilePath = "./src/test/java/org/apache/ranger/rest/importPolicy/import_policy_test_file.json"; + @InjectMocks + ServiceREST serviceREST = new ServiceREST(); + @Mock + RangerValidatorFactory validatorFactory; + @Mock(answer = Answers.RETURNS_DEEP_STUBS) + RangerDaoManager daoManager; + @Mock + ServiceDBStore svcStore; + @Mock + SecurityZoneDBStore zoneStore; + @Mock + TagDBStore tagStore; + @Mock + RangerServiceService svcService; + @Mock + RangerDataHistService dataHistService; + @Mock + RangerExportPolicyList rangerExportPolicyList; + @Mock + RangerServiceDefService serviceDefService; + @Mock + RangerPolicyService policyService; + @Mock + StringUtil stringUtil; + @Mock + XUserService xUserService; + @Mock + XUserMgr xUserMgr; + @Mock + XUserMgr userMgr; + @Mock + RangerAuditFields rangerAuditFields; + @Mock + ContextUtil contextUtil; + @Mock + RangerBizUtil bizUtil; + @Mock + RESTErrorUtil restErrorUtil; + @Mock + RangerServiceDefValidator serviceDefValidator; + @Mock + RangerServiceValidator serviceValidator; + @Mock + RangerPolicyValidator policyValidator; + @Mock + ServiceMgr serviceMgr; + @Mock + VXResponse vXResponse; + @Mock + ServiceUtil serviceUtil; + @Mock + RangerSearchUtil searchUtil; + @Mock + StringUtils stringUtils; + @Mock + AssetMgr assetMgr; + @Mock + RangerPolicyLabelsService policyLabelsService; + @Mock + RangerPluginInfoService pluginInfoService; + @Mock + XXServiceDao xServiceDao; + @Mock + RangerPolicyEngineImpl rpImpl; + @Mock + RangerPolicyAdmin policyAdmin; + @Mock + RangerTransactionSynchronizationAdapter rangerTransactionSynchronizationAdapter; + private String capabilityVector; + + public void setup() { + RangerSecurityContext context = new RangerSecurityContext(); + context.setUserSession(new UserSessionBase()); + RangerContextHolder.setSecurityContext(context); + UserSessionBase currentUserSession = ContextUtil.getCurrentUserSession(); + currentUserSession.setXXPortalUser(new XXPortalUser()); + currentUserSession.setUserAdmin(true); + capabilityVector = Long.toHexString(new RangerPluginCapability().getPluginCapabilities()); + } + + public RangerServiceDef rangerServiceDef() { + List configs = new ArrayList<>(); + List resources = new ArrayList<>(); + List accessTypes = new ArrayList<>(); + List policyConditions = new ArrayList<>(); + List contextEnrichers = new ArrayList<>(); + List enums = new ArrayList<>(); + + RangerServiceDef rangerServiceDef = new RangerServiceDef(); + rangerServiceDef.setId(Id); + rangerServiceDef.setImplClass("RangerServiceHdfs"); + rangerServiceDef.setLabel("HDFS Repository"); + rangerServiceDef.setDescription("HDFS Repository"); + rangerServiceDef.setRbKeyDescription(null); + rangerServiceDef.setUpdatedBy("Admin"); + rangerServiceDef.setUpdateTime(new Date()); + rangerServiceDef.setConfigs(configs); + rangerServiceDef.setResources(resources); + rangerServiceDef.setAccessTypes(accessTypes); + rangerServiceDef.setPolicyConditions(policyConditions); + rangerServiceDef.setContextEnrichers(contextEnrichers); + rangerServiceDef.setEnums(enums); + + return rangerServiceDef; + } + + public RangerService rangerService() { + Map configs = new HashMap<>(); + configs.put("username", "servicemgr"); + configs.put("password", "servicemgr"); + configs.put("namenode", "servicemgr"); + configs.put("hadoop.security.authorization", "No"); + configs.put("hadoop.security.authentication", "Simple"); + configs.put("hadoop.security.auth_to_local", ""); + configs.put("dfs.datanode.kerberos.principal", ""); + configs.put("dfs.namenode.kerberos.principal", ""); + configs.put("dfs.secondary.namenode.kerberos.principal", ""); + configs.put("hadoop.rpc.protection", "Privacy"); + configs.put("commonNameForCertificate", ""); + + RangerService rangerService = new RangerService(); + rangerService.setId(Id); + rangerService.setConfigs(configs); + rangerService.setCreateTime(new Date()); + rangerService.setDescription("service policy"); + rangerService.setGuid("1427365526516_835_0"); + rangerService.setIsEnabled(true); + rangerService.setName("HDFS_1"); + rangerService.setDisplayName("HDFS_1"); + rangerService.setPolicyUpdateTime(new Date()); + rangerService.setType("1"); + rangerService.setUpdatedBy("Admin"); + rangerService.setUpdateTime(new Date()); + + return rangerService; + } + + public XXServiceDef serviceDef() { + XXServiceDef xServiceDef = new XXServiceDef(); + xServiceDef.setAddedByUserId(Id); + xServiceDef.setCreateTime(new Date()); + xServiceDef.setDescription("HDFS Repository"); + xServiceDef.setGuid("1427365526516_835_0"); + xServiceDef.setId(Id); + xServiceDef.setUpdateTime(new Date()); + xServiceDef.setUpdatedByUserId(Id); + xServiceDef.setImplclassname("RangerServiceHdfs"); + xServiceDef.setLabel("HDFS Repository"); + xServiceDef.setRbkeylabel(null); + xServiceDef.setRbkeydescription(null); + xServiceDef.setIsEnabled(true); + + return xServiceDef; + } + + public XXService xService() { + XXService xService = new XXService(); + xService.setAddedByUserId(Id); + xService.setCreateTime(new Date()); + xService.setDescription("Hdfs service"); + xService.setGuid("serviceguid"); + xService.setId(Id); + xService.setIsEnabled(true); + xService.setName("Hdfs"); + xService.setPolicyUpdateTime(new Date()); + xService.setPolicyVersion(1L); + xService.setType(1L); + xService.setUpdatedByUserId(Id); + xService.setUpdateTime(new Date()); + + return xService; + } + + public ServicePolicies servicePolicies() { + ServicePolicies sp = new ServicePolicies(); + sp.setAuditMode("auditMode"); + RangerPolicy rangerPolicy = rangerPolicy(); + List rpolList = new ArrayList<>(); + rpolList.add(rangerPolicy); + sp.setPolicies(rpolList); + sp.setPolicyVersion(1L); + sp.setServiceName("serviceName"); + sp.setServiceId(1L); + return sp; + } + + @Test + public void test1createServiceDef() throws Exception { + RangerServiceDef rangerServiceDef = rangerServiceDef(); + + Mockito.when(validatorFactory.getServiceDefValidator(svcStore)).thenReturn(serviceDefValidator); + Mockito.when(svcStore.createServiceDef(Mockito.any())).thenReturn(rangerServiceDef); + + RangerServiceDef dbRangerServiceDef = serviceREST.createServiceDef(rangerServiceDef); + Assert.assertNotNull(dbRangerServiceDef); + Assert.assertEquals(dbRangerServiceDef, rangerServiceDef); + Assert.assertEquals(dbRangerServiceDef.getId(), rangerServiceDef.getId()); + Assert.assertEquals(dbRangerServiceDef.getName(), rangerServiceDef.getName()); + Assert.assertEquals(dbRangerServiceDef.getImplClass(), rangerServiceDef.getImplClass()); + Assert.assertEquals(dbRangerServiceDef.getLabel(), rangerServiceDef.getLabel()); + Assert.assertEquals(dbRangerServiceDef.getDescription(), rangerServiceDef.getDescription()); + Assert.assertEquals(dbRangerServiceDef.getRbKeyDescription(), rangerServiceDef.getRbKeyDescription()); + Assert.assertEquals(dbRangerServiceDef.getUpdatedBy(), rangerServiceDef.getUpdatedBy()); + Assert.assertEquals(dbRangerServiceDef.getUpdateTime(), rangerServiceDef.getUpdateTime()); + Assert.assertEquals(dbRangerServiceDef.getVersion(), rangerServiceDef.getVersion()); + Assert.assertEquals(dbRangerServiceDef.getConfigs(), rangerServiceDef.getConfigs()); + + Mockito.verify(validatorFactory).getServiceDefValidator(svcStore); + Mockito.verify(svcStore).createServiceDef(rangerServiceDef); + } + + @Test + public void test2updateServiceDef() throws Exception { + RangerServiceDef rangerServiceDef = rangerServiceDef(); + + Mockito.when(validatorFactory.getServiceDefValidator(svcStore)).thenReturn(serviceDefValidator); + Mockito.when(svcStore.updateServiceDef(Mockito.any())).thenReturn(rangerServiceDef); + + RangerServiceDef dbRangerServiceDef = serviceREST.updateServiceDef(rangerServiceDef, rangerServiceDef.getId()); + Assert.assertNotNull(dbRangerServiceDef); + Assert.assertEquals(dbRangerServiceDef, rangerServiceDef); + Assert.assertEquals(dbRangerServiceDef.getId(), rangerServiceDef.getId()); + Assert.assertEquals(dbRangerServiceDef.getName(), rangerServiceDef.getName()); + Assert.assertEquals(dbRangerServiceDef.getImplClass(), rangerServiceDef.getImplClass()); + Assert.assertEquals(dbRangerServiceDef.getLabel(), rangerServiceDef.getLabel()); + Assert.assertEquals(dbRangerServiceDef.getDescription(), rangerServiceDef.getDescription()); + Assert.assertEquals(dbRangerServiceDef.getRbKeyDescription(), rangerServiceDef.getRbKeyDescription()); + Assert.assertEquals(dbRangerServiceDef.getUpdatedBy(), rangerServiceDef.getUpdatedBy()); + Assert.assertEquals(dbRangerServiceDef.getUpdateTime(), rangerServiceDef.getUpdateTime()); + Assert.assertEquals(dbRangerServiceDef.getVersion(), rangerServiceDef.getVersion()); + Assert.assertEquals(dbRangerServiceDef.getConfigs(), rangerServiceDef.getConfigs()); + + Mockito.verify(validatorFactory).getServiceDefValidator(svcStore); + Mockito.verify(svcStore).updateServiceDef(rangerServiceDef); + } + + @Test + public void test3deleteServiceDef() { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + RangerServiceDef rangerServiceDef = rangerServiceDef(); + XXServiceDef xServiceDef = serviceDef(); + XXServiceDefDao xServiceDefDao = Mockito.mock(XXServiceDefDao.class); + Mockito.when(validatorFactory.getServiceDefValidator(svcStore)) + .thenReturn(serviceDefValidator); + Mockito.when(daoManager.getXXServiceDef()).thenReturn(xServiceDefDao); + Mockito.when(xServiceDefDao.getById(Id)).thenReturn(xServiceDef); + + serviceREST.deleteServiceDef(rangerServiceDef.getId(), request); + Mockito.verify(validatorFactory).getServiceDefValidator(svcStore); + Mockito.verify(daoManager).getXXServiceDef(); + } + + @Test + public void test4getServiceDefById() throws Exception { + RangerServiceDef rangerServiceDef = rangerServiceDef(); + XXServiceDef xServiceDef = serviceDef(); + XXServiceDefDao xServiceDefDao = Mockito.mock(XXServiceDefDao.class); + + Mockito.when(daoManager.getXXServiceDef()).thenReturn(xServiceDefDao); + Mockito.when(xServiceDefDao.getById(Id)).thenReturn(xServiceDef); + Mockito.when(!bizUtil.hasAccess(xServiceDef, null)).thenReturn(true); + Mockito.when(svcStore.getServiceDef(rangerServiceDef.getId())).thenReturn(rangerServiceDef); + RangerServiceDef dbRangerServiceDef = serviceREST.getServiceDef(rangerServiceDef.getId()); + Assert.assertNotNull(dbRangerServiceDef); + Assert.assertEquals(dbRangerServiceDef.getId(), rangerServiceDef.getId()); + Mockito.verify(svcStore).getServiceDef(rangerServiceDef.getId()); + Mockito.verify(daoManager).getXXServiceDef(); + Mockito.verify(bizUtil).hasAccess(xServiceDef, null); + } + + @Test + public void test5getServiceDefByName() throws Exception { + RangerServiceDef rangerServiceDef = rangerServiceDef(); + XXServiceDef xServiceDef = serviceDef(); + XXServiceDefDao xServiceDefDao = Mockito.mock(XXServiceDefDao.class); + + Mockito.when(daoManager.getXXServiceDef()).thenReturn(xServiceDefDao); + Mockito.when(xServiceDefDao.findByName(xServiceDef.getName())).thenReturn(xServiceDef); + Mockito.when(!bizUtil.hasAccess(xServiceDef, null)).thenReturn(true); + Mockito.when(svcStore.getServiceDefByName(rangerServiceDef.getName())).thenReturn(rangerServiceDef); + RangerServiceDef dbRangerServiceDef = serviceREST.getServiceDefByName(rangerServiceDef.getName()); + Assert.assertNotNull(dbRangerServiceDef); + Assert.assertEquals(dbRangerServiceDef.getName(), rangerServiceDef.getName()); + Mockito.verify(svcStore).getServiceDefByName(rangerServiceDef.getName()); + Mockito.verify(daoManager).getXXServiceDef(); + } + + @Test + public void test6createService() throws Exception { + RangerService rangerService = rangerService(); + XXServiceDef xServiceDef = serviceDef(); + XXServiceDefDao xServiceDefDao = Mockito.mock(XXServiceDefDao.class); + Mockito.when(validatorFactory.getServiceValidator(svcStore)).thenReturn(serviceValidator); + + Mockito.when(daoManager.getXXServiceDef()).thenReturn(xServiceDefDao); + Mockito.when(xServiceDefDao.findByName(rangerService.getType())).thenReturn(xServiceDef); + + Mockito.when(svcStore.createService(Mockito.any())).thenReturn(rangerService); + + RangerService dbRangerService = serviceREST.createService(rangerService); + Assert.assertNotNull(dbRangerService); + Assert.assertEquals(rangerService, dbRangerService); + Assert.assertEquals(rangerService.getId(), dbRangerService.getId()); + Assert.assertEquals(rangerService.getConfigs(), dbRangerService.getConfigs()); + Assert.assertEquals(rangerService.getDescription(), dbRangerService.getDescription()); + Assert.assertEquals(rangerService.getGuid(), dbRangerService.getGuid()); + Assert.assertEquals(rangerService.getName(), dbRangerService.getName()); + Assert.assertEquals(rangerService.getPolicyVersion(), dbRangerService.getPolicyVersion()); + Assert.assertEquals(rangerService.getType(), dbRangerService.getType()); + Assert.assertEquals(rangerService.getVersion(), dbRangerService.getVersion()); + Assert.assertEquals(rangerService.getCreateTime(), dbRangerService.getCreateTime()); + Assert.assertEquals(rangerService.getUpdateTime(), dbRangerService.getUpdateTime()); + Assert.assertEquals(rangerService.getUpdatedBy(), dbRangerService.getUpdatedBy()); + + Mockito.verify(validatorFactory).getServiceValidator(svcStore); + Mockito.verify(svcStore).createService(rangerService); + } + + @Test + public void test7getServiceDefs() throws Exception { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + SearchFilter filter = new SearchFilter(); + filter.setParam(SearchFilter.POLICY_NAME, "policyName"); + filter.setParam(SearchFilter.SERVICE_NAME, "serviceName"); + Mockito.when(searchUtil.getSearchFilter(request, serviceDefService.sortFields)).thenReturn(filter); + + List serviceDefsList = new ArrayList<>(); + RangerServiceDef serviceDef = rangerServiceDef(); + serviceDefsList.add(serviceDef); + PList serviceDefList = new PList<>(); + serviceDefList.setPageSize(0); + serviceDefList.setResultSize(1); + serviceDefList.setSortBy("asc"); + serviceDefList.setSortType("1"); + serviceDefList.setStartIndex(0); + serviceDefList.setTotalCount(10); + serviceDefList.setList(serviceDefsList); + Mockito.when(bizUtil.hasModuleAccess(RangerConstants.MODULE_RESOURCE_BASED_POLICIES)).thenReturn(true); + Mockito.when(svcStore.getPaginatedServiceDefs(filter)).thenReturn(serviceDefList); + RangerServiceDefList dbRangerServiceDef = serviceREST.getServiceDefs(request); + Assert.assertNotNull(dbRangerServiceDef); + Mockito.verify(searchUtil).getSearchFilter(request, serviceDefService.sortFields); + Mockito.verify(svcStore).getPaginatedServiceDefs(filter); + } + + @Test + public void test8updateServiceDef() throws Exception { + RangerService rangerService = rangerService(); + XXServiceDef xServiceDef = serviceDef(); + HttpServletRequest request = null; + Map options = null; + + XXServiceDefDao xServiceDefDao = Mockito.mock(XXServiceDefDao.class); + Mockito.when(validatorFactory.getServiceValidator(svcStore)).thenReturn(serviceValidator); + + Mockito.when(daoManager.getXXServiceDef()).thenReturn(xServiceDefDao); + Mockito.when(xServiceDefDao.findByName(rangerService.getType())).thenReturn(xServiceDef); + + Mockito.when(svcStore.updateService(Mockito.any(), Mockito.any())).thenReturn(rangerService); + + RangerService dbRangerService = serviceREST.updateService(rangerService, request); + Assert.assertNotNull(dbRangerService); + Assert.assertNotNull(dbRangerService); + Assert.assertEquals(rangerService, dbRangerService); + Assert.assertEquals(rangerService.getId(), dbRangerService.getId()); + Assert.assertEquals(rangerService.getConfigs(), dbRangerService.getConfigs()); + Assert.assertEquals(rangerService.getDescription(), dbRangerService.getDescription()); + Assert.assertEquals(rangerService.getGuid(), dbRangerService.getGuid()); + Assert.assertEquals(rangerService.getName(), dbRangerService.getName()); + Assert.assertEquals(rangerService.getPolicyVersion(), dbRangerService.getPolicyVersion()); + Assert.assertEquals(rangerService.getType(), dbRangerService.getType()); + Assert.assertEquals(rangerService.getVersion(), dbRangerService.getVersion()); + Assert.assertEquals(rangerService.getCreateTime(), dbRangerService.getCreateTime()); + Assert.assertEquals(rangerService.getUpdateTime(), dbRangerService.getUpdateTime()); + Assert.assertEquals(rangerService.getUpdatedBy(), dbRangerService.getUpdatedBy()); + Mockito.verify(validatorFactory).getServiceValidator(svcStore); + Mockito.verify(daoManager).getXXServiceDef(); + Mockito.verify(svcStore).updateService(rangerService, options); + } + + @Test + public void test9deleteService() { + RangerService rangerService = rangerService(); + XXServiceDef xServiceDef = serviceDef(); + XXService xService = xService(); + XXServiceDefDao xServiceDefDao = Mockito.mock(XXServiceDefDao.class); + XXServiceDao xServiceDao = Mockito.mock(XXServiceDao.class); + Mockito.when(validatorFactory.getServiceValidator(svcStore)).thenReturn(serviceValidator); + + Mockito.when(daoManager.getXXService()).thenReturn(xServiceDao); + Mockito.when(xServiceDao.getById(Id)).thenReturn(xService); + Mockito.when(daoManager.getXXServiceDef()).thenReturn(xServiceDefDao); + Mockito.when(xServiceDefDao.getById(xService.getType())).thenReturn(xServiceDef); + + serviceREST.deleteService(rangerService.getId()); + + Mockito.verify(validatorFactory).getServiceValidator(svcStore); + Mockito.verify(daoManager).getXXService(); + Mockito.verify(daoManager).getXXServiceDef(); + } + + @Test + public void test10getServiceById() throws Exception { + RangerService rangerService = rangerService(); + Mockito.when(svcStore.getService(rangerService.getId())).thenReturn(rangerService); + RangerService dbRangerService = serviceREST.getService(rangerService.getId()); + Assert.assertNotNull(dbRangerService); + Mockito.verify(svcStore).getService(dbRangerService.getId()); + } + + @Test + public void test11getServiceByName() throws Exception { + RangerService rangerService = rangerService(); + Mockito.when(svcStore.getServiceByName(rangerService.getName())).thenReturn(rangerService); + RangerService dbRangerService = serviceREST.getServiceByName(rangerService.getName()); + Assert.assertNotNull(dbRangerService); + Mockito.verify(svcStore).getServiceByName(dbRangerService.getName()); + } + + @Test + public void test12deleteServiceDef() { + RangerServiceDef rangerServiceDef = rangerServiceDef(); + XXServiceDef xServiceDef = serviceDef(); + XXServiceDefDao xServiceDefDao = Mockito.mock(XXServiceDefDao.class); + Mockito.when(validatorFactory.getServiceDefValidator(svcStore)) + .thenReturn(serviceDefValidator); + + Mockito.when(daoManager.getXXServiceDef()).thenReturn(xServiceDefDao); + Mockito.when(xServiceDefDao.getById(Id)).thenReturn(xServiceDef); + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + serviceREST.deleteServiceDef(rangerServiceDef.getId(), request); + Mockito.verify(validatorFactory).getServiceDefValidator(svcStore); + Mockito.verify(daoManager).getXXServiceDef(); + } + + @Test + public void test13lookupResource() { + String serviceName = "HDFS_1"; + ResourceLookupContext context = new ResourceLookupContext(); + context.setResourceName(serviceName); + context.setUserInput("HDFS"); + List list = serviceREST.lookupResource(serviceName, context); + Assert.assertNotNull(list); + } + + @Test + public void test14grantAccess() throws Exception { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + String serviceName = "HDFS_1"; + GrantRevokeRequest grantRequestObj = new GrantRevokeRequest(); + grantRequestObj.setAccessTypes(null); + grantRequestObj.setDelegateAdmin(true); + grantRequestObj.setEnableAudit(true); + grantRequestObj.setGrantor("read"); + grantRequestObj.setIsRecursive(true); + + Mockito.when(serviceUtil.isValidateHttpsAuthentication(serviceName, request)).thenReturn(false); + RESTResponse restResponse = serviceREST.grantAccess(serviceName, grantRequestObj, request); + Assert.assertNotNull(restResponse); + Mockito.verify(serviceUtil).isValidateHttpsAuthentication(serviceName, request); + } + + @Test + public void test14_1_grantAccessWithMultiColumns() throws Exception { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + + String serviceName = "HIVE"; + Set userList = new HashSet<>(); + userList.add("user1"); + userList.add("user2"); + userList.add("user3"); + + Map grantResource = new HashMap<>(); + grantResource.put("database", "demo"); + grantResource.put("table", "testtbl"); + grantResource.put("column", "column1,column2,colum3"); + GrantRevokeRequest grantRequestObj = new GrantRevokeRequest(); + + grantRequestObj.setResource(grantResource); + grantRequestObj.setUsers(userList); + grantRequestObj.setAccessTypes(new HashSet<>(Collections.singletonList("select"))); + grantRequestObj.setDelegateAdmin(true); + grantRequestObj.setEnableAudit(true); + grantRequestObj.setGrantor("systest"); + grantRequestObj.setIsRecursive(true); + + RangerAccessResource resource = new RangerAccessResourceImpl(ServiceREST.getAccessResourceObjectMap(grantRequestObj.getResource()), "systest"); + + RangerPolicy createPolicy = new RangerPolicy(); + createPolicy.setService(serviceName); + createPolicy.setName("grant-" + System.currentTimeMillis()); + createPolicy.setDescription("created by grant"); + createPolicy.setIsAuditEnabled(grantRequestObj.getEnableAudit()); + + Map policyResources = new HashMap<>(); + Set resourceNames = resource.getKeys(); + + if (!CollectionUtils.isEmpty(resourceNames)) { + for (String resourceName : resourceNames) { + policyResources.put(resourceName, serviceREST.getPolicyResource(resource.getValue(resourceName), grantRequestObj)); + } + } + createPolicy.setResources(policyResources); + + RangerPolicyItem policyItem = new RangerPolicyItem(); + policyItem.setDelegateAdmin(grantRequestObj.getDelegateAdmin()); + policyItem.addUsers(grantRequestObj.getUsers()); + for (String accessType : grantRequestObj.getAccessTypes()) { + policyItem.addAccess(new RangerPolicyItemAccess(accessType, Boolean.TRUE)); + } + createPolicy.addPolicyItem(policyItem); + createPolicy.setZoneName(null); + + List grantColumns = (List) resource.getValue("column"); + Map policyResourceMap = createPolicy.getResources(); + List createdPolicyColumns = policyResourceMap.get("column").getValues(); + + Assert.assertTrue(createdPolicyColumns.containsAll(grantColumns)); + + Mockito.when(serviceUtil.isValidateHttpsAuthentication(serviceName, request)).thenReturn(false); + RESTResponse restResponse = serviceREST.grantAccess(serviceName, grantRequestObj, request); + Assert.assertNotNull(restResponse); + Mockito.verify(serviceUtil).isValidateHttpsAuthentication(serviceName, request); + } + + @Test + public void test15revokeAccess() throws Exception { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + String serviceName = "HDFS_1"; + Set userList = new HashSet<>(); + userList.add("user1"); + userList.add("user2"); + userList.add("user3"); + Set groupList = new HashSet<>(); + groupList.add("group1"); + groupList.add("group2"); + groupList.add("group3"); + GrantRevokeRequest revokeRequest = new GrantRevokeRequest(); + revokeRequest.setDelegateAdmin(true); + revokeRequest.setEnableAudit(true); + revokeRequest.setGrantor("read"); + revokeRequest.setGroups(groupList); + revokeRequest.setUsers(userList); + + RESTResponse restResponse = serviceREST.revokeAccess(serviceName, revokeRequest, request); + Assert.assertNotNull(restResponse); + } + + @Test + public void test16createPolicyFalse() throws Exception { + RangerPolicy rangerPolicy = rangerPolicy(); + RangerServiceDef rangerServiceDef = rangerServiceDef(); + + List policies = new ArrayList<>(); + RangerPolicy rangPolicy = new RangerPolicy(); + policies.add(rangPolicy); + + String userName = "admin"; + Set userGroupsList = new HashSet<>(); + userGroupsList.add("group1"); + userGroupsList.add("group2"); + + ServicePolicies servicePolicies = new ServicePolicies(); + servicePolicies.setServiceId(Id); + servicePolicies.setServiceName("Hdfs_1"); + servicePolicies.setPolicyVersion(1L); + servicePolicies.setPolicyUpdateTime(new Date()); + servicePolicies.setServiceDef(rangerServiceDef); + servicePolicies.setPolicies(policies); + + List rangerAccessTypeDefList = new ArrayList<>(); + RangerAccessTypeDef rangerAccessTypeDefObj = new RangerAccessTypeDef(); + rangerAccessTypeDefObj.setLabel("Read"); + rangerAccessTypeDefObj.setName("read"); + rangerAccessTypeDefObj.setRbKeyLabel(null); + rangerAccessTypeDefList.add(rangerAccessTypeDefObj); + XXServiceDef xServiceDef = serviceDef(); + XXService xService = xService(); + XXServiceDefDao xServiceDefDao = Mockito.mock(XXServiceDefDao.class); + XXServiceDao xServiceDao = Mockito.mock(XXServiceDao.class); + + Mockito.when(validatorFactory.getPolicyValidator(svcStore)).thenReturn(policyValidator); + Mockito.when(bizUtil.isAdmin()).thenReturn(true); + Mockito.when(bizUtil.getCurrentUserLoginId()).thenReturn(userName); + Mockito.when(daoManager.getXXService()).thenReturn(xServiceDao); + Mockito.when(xServiceDao.findByName(Mockito.anyString())).thenReturn(xService); + Mockito.when(daoManager.getXXServiceDef()).thenReturn(xServiceDefDao); + Mockito.when(xServiceDefDao.getById(xService.getType())).thenReturn(xServiceDef); + Mockito.when(svcStore.createPolicy(Mockito.any())).thenReturn(rangPolicy); + + RangerPolicy dbRangerPolicy = serviceREST.createPolicy(rangerPolicy, null); + Assert.assertNotNull(dbRangerPolicy); + Mockito.verify(bizUtil, Mockito.times(2)).isAdmin(); + Mockito.verify(validatorFactory).getPolicyValidator(svcStore); + + Mockito.verify(daoManager).getXXService(); + Mockito.verify(daoManager, Mockito.atLeastOnce()).getXXServiceDef(); + } + + @Test + public void test17updatePolicyFalse() { + RangerPolicy rangerPolicy = rangerPolicy(); + String userName = "admin"; + + Set userGroupsList = new HashSet<>(); + userGroupsList.add("group1"); + userGroupsList.add("group2"); + + List rangerAccessTypeDefList = new ArrayList<>(); + RangerAccessTypeDef rangerAccessTypeDefObj = new RangerAccessTypeDef(); + rangerAccessTypeDefObj.setLabel("Read"); + rangerAccessTypeDefObj.setName("read"); + rangerAccessTypeDefObj.setRbKeyLabel(null); + rangerAccessTypeDefList.add(rangerAccessTypeDefObj); + XXServiceDef xServiceDef = serviceDef(); + XXService xService = xService(); + XXServiceDefDao xServiceDefDao = Mockito.mock(XXServiceDefDao.class); + XXServiceDao xServiceDao = Mockito.mock(XXServiceDao.class); + + Mockito.when(validatorFactory.getPolicyValidator(svcStore)).thenReturn( + policyValidator); + Mockito.when(bizUtil.isAdmin()).thenReturn(true); + Mockito.when(bizUtil.getCurrentUserLoginId()).thenReturn(userName); + Mockito.when(daoManager.getXXService()).thenReturn(xServiceDao); + Mockito.when(xServiceDao.findByName(Mockito.anyString())).thenReturn(xService); + Mockito.when(daoManager.getXXServiceDef()).thenReturn(xServiceDefDao); + Mockito.when(xServiceDefDao.getById(xService.getType())).thenReturn(xServiceDef); + RangerPolicy dbRangerPolicy = serviceREST.updatePolicy(rangerPolicy, Id); + Assert.assertNull(dbRangerPolicy); + Mockito.verify(validatorFactory).getPolicyValidator(svcStore); + } + + @Test + public void test18deletePolicyFalse() throws Exception { + RangerPolicy rangerPolicy = rangerPolicy(); + + Mockito.when(validatorFactory.getPolicyValidator(svcStore)).thenReturn(policyValidator); + String userName = "admin"; + + Set userGroupsList = new HashSet<>(); + userGroupsList.add("group1"); + userGroupsList.add("group2"); + + List rangerAccessTypeDefList = new ArrayList<>(); + RangerAccessTypeDef rangerAccessTypeDefObj = new RangerAccessTypeDef(); + rangerAccessTypeDefObj.setLabel("Read"); + rangerAccessTypeDefObj.setName("read"); + rangerAccessTypeDefObj.setRbKeyLabel(null); + rangerAccessTypeDefList.add(rangerAccessTypeDefObj); + XXServiceDef xServiceDef = serviceDef(); + XXService xService = xService(); + XXServiceDefDao xServiceDefDao = Mockito.mock(XXServiceDefDao.class); + XXServiceDao xServiceDao = Mockito.mock(XXServiceDao.class); + Mockito.when(validatorFactory.getPolicyValidator(svcStore)).thenReturn(policyValidator); + Mockito.when(bizUtil.isAdmin()).thenReturn(true); + Mockito.when(bizUtil.getCurrentUserLoginId()).thenReturn(userName); + Mockito.when(svcStore.getPolicy(Id)).thenReturn(rangerPolicy); + Mockito.when(daoManager.getXXService()).thenReturn(xServiceDao); + Mockito.when(xServiceDao.findByName(Mockito.anyString())).thenReturn(xService); + Mockito.when(daoManager.getXXServiceDef()).thenReturn(xServiceDefDao); + Mockito.when(xServiceDefDao.getById(xService.getType())).thenReturn(xServiceDef); + serviceREST.deletePolicy(rangerPolicy.getId()); + Mockito.verify(validatorFactory).getPolicyValidator(svcStore); + } + + @Test + public void test19getPolicyFalse() throws Exception { + RangerPolicy rangerPolicy = rangerPolicy(); + Mockito.when(svcStore.getPolicy(rangerPolicy.getId())).thenReturn(rangerPolicy); + String userName = "admin"; + + Set userGroupsList = new HashSet<>(); + userGroupsList.add("group1"); + userGroupsList.add("group2"); + + List rangerAccessTypeDefList = new ArrayList<>(); + RangerAccessTypeDef rangerAccessTypeDefObj = new RangerAccessTypeDef(); + rangerAccessTypeDefObj.setLabel("Read"); + rangerAccessTypeDefObj.setName("read"); + rangerAccessTypeDefObj.setRbKeyLabel(null); + rangerAccessTypeDefList.add(rangerAccessTypeDefObj); + XXServiceDef xServiceDef = serviceDef(); + XXService xService = xService(); + XXServiceDefDao xServiceDefDao = Mockito.mock(XXServiceDefDao.class); + XXServiceDao xServiceDao = Mockito.mock(XXServiceDao.class); + Mockito.when(bizUtil.isAdmin()).thenReturn(true); + Mockito.when(bizUtil.getCurrentUserLoginId()).thenReturn(userName); + Mockito.when(daoManager.getXXService()).thenReturn(xServiceDao); + Mockito.when(xServiceDao.findByName(Mockito.anyString())).thenReturn(xService); + Mockito.when(daoManager.getXXServiceDef()).thenReturn(xServiceDefDao); + Mockito.when(xServiceDefDao.getById(xService.getType())).thenReturn(xServiceDef); + RangerPolicy dbRangerPolicy = serviceREST.getPolicy(rangerPolicy.getId()); + Assert.assertNotNull(dbRangerPolicy); + Assert.assertEquals(dbRangerPolicy.getId(), rangerPolicy.getId()); + Mockito.verify(svcStore).getPolicy(rangerPolicy.getId()); + } + + @Test + public void test20getPolicies() { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + SearchFilter filter = new SearchFilter(); + filter.setParam(SearchFilter.POLICY_NAME, "policyName"); + filter.setParam(SearchFilter.SERVICE_NAME, "serviceName"); + Mockito.when(searchUtil.getSearchFilter(request, policyService.sortFields)).thenReturn(filter); + RangerPolicyList dbRangerPolicy = serviceREST.getPolicies(request); + Assert.assertNotNull(dbRangerPolicy); + Assert.assertEquals(0, dbRangerPolicy.getListSize()); + Mockito.verify(searchUtil).getSearchFilter(request, policyService.sortFields); + } + + @Test + public void test21countPolicies() { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + + SearchFilter filter = new SearchFilter(); + filter.setParam(SearchFilter.POLICY_NAME, "policyName"); + filter.setParam(SearchFilter.SERVICE_NAME, "serviceName"); + Mockito.when(searchUtil.getSearchFilter(request, policyService.sortFields)).thenReturn(filter); + + Long data = serviceREST.countPolicies(request); + Assert.assertNotNull(data); + Mockito.verify(searchUtil).getSearchFilter(request, policyService.sortFields); + } + + @Test + public void test22getServicePoliciesById() throws Exception { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + RangerPolicy rangerPolicy = rangerPolicy(); + + SearchFilter filter = new SearchFilter(); + filter.setParam(SearchFilter.POLICY_NAME, "policyName"); + filter.setParam(SearchFilter.SERVICE_NAME, "serviceName"); + Mockito.when(searchUtil.getSearchFilter(request, policyService.sortFields)).thenReturn(filter); + + RangerPolicyList dbRangerPolicy = serviceREST.getServicePolicies(rangerPolicy.getId(), request); + Assert.assertNotNull(dbRangerPolicy); + Mockito.verify(searchUtil).getSearchFilter(request, policyService.sortFields); + Mockito.verify(svcStore).getServicePolicies(Id, filter); + } + + @Test + public void test23getServicePoliciesByName() throws Exception { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + RangerPolicy rangerPolicy = rangerPolicy(); + + List ret = Mockito.mock(List.class); + SearchFilter filter = new SearchFilter(); + + filter.setParam(SearchFilter.POLICY_NAME, "policyName"); + filter.setParam(SearchFilter.SERVICE_NAME, "serviceName"); + + Mockito.when(searchUtil.getSearchFilter(request, policyService.sortFields)).thenReturn(filter); + Mockito.when(svcStore.getServicePolicies(rangerPolicy.getName(), filter)).thenReturn(ret); + + RangerPolicyList dbRangerPolicy = serviceREST.getServicePoliciesByName(rangerPolicy.getName(), request); + Assert.assertNotNull(dbRangerPolicy); + } + + @Test + public void test24getServicePoliciesIfUpdated() throws Exception { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + String serviceName = "HDFS_1"; + Long lastKnownVersion = 1L; + String pluginId = "1"; + + ServicePolicies dbServicePolicies = serviceREST.getServicePoliciesIfUpdated(serviceName, lastKnownVersion, 0L, pluginId, "", "", false, capabilityVector, request); + Assert.assertNull(dbServicePolicies); + } + + @Test + public void test25getPolicies() throws Exception { + List ret = new ArrayList<>(); + SearchFilter filter = new SearchFilter(); + filter.setParam(SearchFilter.POLICY_NAME, "policyName"); + filter.setParam(SearchFilter.SERVICE_NAME, "serviceName"); + Mockito.when(svcStore.getPolicies(filter)).thenReturn(ret); + + List dbRangerPolicyList = serviceREST.getPolicies(filter); + Assert.assertNotNull(dbRangerPolicyList); + Mockito.verify(svcStore).getPolicies(filter); + } + + @Test + public void test26getServices() throws Exception { + List ret = new ArrayList<>(); + SearchFilter filter = new SearchFilter(); + filter.setParam(SearchFilter.POLICY_NAME, "policyName"); + filter.setParam(SearchFilter.SERVICE_NAME, "serviceName"); + Mockito.when(svcStore.getServices(filter)).thenReturn(ret); + + List dbRangerService = serviceREST.getServices(filter); + Assert.assertNotNull(dbRangerService); + Mockito.verify(svcStore).getServices(filter); + } + + @Test + public void test27getPoliciesWithoutServiceAdmin() throws Exception { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + SearchFilter filter = new SearchFilter(); + List policies = new ArrayList<>(); + policies.add(rangerPolicy()); + filter.setParam(SearchFilter.POLICY_NAME, "policyName"); + filter.setParam(SearchFilter.SERVICE_NAME, "serviceName"); + Mockito.when(searchUtil.getSearchFilter(request, policyService.sortFields)).thenReturn(filter); + Mockito.when(svcStore.getPolicies(filter)).thenReturn(policies); + RangerPolicyList dbRangerPolicy = serviceREST.getPolicies(request); + Assert.assertNotNull(dbRangerPolicy); + /* here we are not setting service admin role,hence we will not get any policy without the service admin roles */ + Assert.assertEquals(0, dbRangerPolicy.getListSize()); + Mockito.verify(searchUtil).getSearchFilter(request, policyService.sortFields); + } + + @Test + public void test28getPoliciesWithServiceAdmin() throws Exception { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + SearchFilter filter = new SearchFilter(); + XXService xs = Mockito.mock(XXService.class); + xs.setType(3L); + ServiceREST spySVCRest = Mockito.spy(serviceREST); + List policies = new ArrayList<>(); + ServicePolicies svcPolicies = new ServicePolicies(); + svcPolicies.setPolicies(policies); + svcPolicies.setServiceName("HDFS_1-1-20150316062453"); + RangerPolicy rPol = rangerPolicy(); + policies.add(rPol); + filter.setParam(SearchFilter.POLICY_NAME, "policyName"); + filter.setParam(SearchFilter.SERVICE_NAME, "serviceName"); + Mockito.when(searchUtil.getSearchFilter(request, policyService.sortFields)).thenReturn(filter); + Mockito.when(svcStore.getPolicies(filter)).thenReturn(policies); + + /*here we are setting serviceAdminRole, so we will get the required policy with serviceAdmi role*/ + Mockito.when(svcStore.isServiceAdminUser(rPol.getService(), null)).thenReturn(true); + RangerPolicyList dbRangerPolicy = spySVCRest.getPolicies(request); + Assert.assertNotNull(dbRangerPolicy); + Assert.assertEquals(1, dbRangerPolicy.getListSize()); + Mockito.verify(searchUtil).getSearchFilter(request, policyService.sortFields); + Mockito.verify(svcStore).getPolicies(filter); + Mockito.verify(svcStore).isServiceAdminUser(rPol.getService(), null); + } + + @Test + public void test30getPolicyFromEventTime() { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + + String strdt = new Date().toString(); + String userName = "Admin"; + Set userGroupsList = new HashSet<>(); + + userGroupsList.add("group1"); + userGroupsList.add("group2"); + Mockito.when(request.getParameter("eventTime")).thenReturn(strdt); + Mockito.when(request.getParameter("policyId")).thenReturn("1"); + Mockito.when(request.getParameter("versionNo")).thenReturn("1"); + RangerPolicy policy = new RangerPolicy(); + Map resources = new HashMap<>(); + policy.setService("services"); + policy.setResources(resources); + Mockito.when(svcStore.getPolicyFromEventTime(strdt, 1L)).thenReturn(policy); + Mockito.when(bizUtil.isAdmin()).thenReturn(false); + Mockito.when(bizUtil.getCurrentUserLoginId()).thenReturn(userName); + + Mockito.when(restErrorUtil.createRESTException(Mockito.anyInt(), Mockito.anyString(), Mockito.anyBoolean())).thenThrow(new WebApplicationException()); + thrown.expect(WebApplicationException.class); + + RangerPolicy dbRangerPolicy = serviceREST.getPolicyFromEventTime(request); + Assert.assertNull(dbRangerPolicy); + Mockito.verify(request).getParameter("eventTime"); + Mockito.verify(request).getParameter("policyId"); + Mockito.verify(request).getParameter("versionNo"); + } + + @Test + public void test31getServices() { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + SearchFilter filter = new SearchFilter(); + filter.setParam(SearchFilter.POLICY_NAME, "policyName"); + filter.setParam(SearchFilter.SERVICE_NAME, "serviceName"); + RangerServiceList dbRangerService = serviceREST.getServices(request); + Assert.assertNull(dbRangerService); + } + + @Test + public void test32getPolicyVersionList() { + VXString vXString = new VXString(); + vXString.setValue("1"); + Mockito.when(svcStore.getPolicyVersionList(Id)).thenReturn(vXString); + + VXString dbVXString = serviceREST.getPolicyVersionList(Id); + Assert.assertNotNull(dbVXString); + Mockito.verify(svcStore).getPolicyVersionList(Id); + } + + @Test + public void test33getPolicyForVersionNumber() { + RangerPolicy rangerPolicy = rangerPolicy(); + Mockito.when(svcStore.getPolicyForVersionNumber(Id, 1)).thenReturn(rangerPolicy); + Mockito.when(bizUtil.isAdmin()).thenReturn(true); + RangerPolicy dbRangerPolicy = serviceREST.getPolicyForVersionNumber(Id, 1); + Assert.assertNotNull(dbRangerPolicy); + Mockito.verify(svcStore).getPolicyForVersionNumber(Id, 1); + } + + @Test + public void test34countServices() throws Exception { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + PList ret = Mockito.mock(PList.class); + SearchFilter filter = new SearchFilter(); + filter.setParam(SearchFilter.POLICY_NAME, "policyName"); + filter.setParam(SearchFilter.SERVICE_NAME, "serviceName"); + Mockito.when(searchUtil.getSearchFilter(request, policyService.sortFields)).thenReturn(filter); + + Mockito.when(svcStore.getPaginatedServices(filter)).thenReturn(ret); + Long data = serviceREST.countServices(request); + Assert.assertNotNull(data); + Mockito.verify(searchUtil).getSearchFilter(request, policyService.sortFields); + Mockito.verify(svcStore).getPaginatedServices(filter); + } + + @Test + public void test35validateConfig() throws Exception { + RangerService rangerService = rangerService(); + Mockito.when(serviceMgr.validateConfig(rangerService, svcStore)).thenReturn(vXResponse); + VXResponse dbVXResponse = serviceREST.validateConfig(rangerService); + Assert.assertNotNull(dbVXResponse); + Mockito.verify(serviceMgr).validateConfig(rangerService, svcStore); + } + + @Test + public void test40applyPolicy() { + RangerPolicy existingPolicy = rangerPolicy(); + RangerPolicy appliedPolicy = rangerPolicy(); + + List policyItem = new ArrayList<>(); + existingPolicy.setPolicyItems(policyItem); + appliedPolicy.setPolicyItems(null); + + Map policyResources = new HashMap<>(); + RangerPolicyResource rangerPolicyResource = new RangerPolicyResource("/tmp"); + rangerPolicyResource.setIsExcludes(true); + rangerPolicyResource.setIsRecursive(true); + policyResources.put("path", rangerPolicyResource); + + existingPolicy.setResources(policyResources); + appliedPolicy.setResources(policyResources); + + RangerPolicyItem rangerPolicyItem = new RangerPolicyItem(); + rangerPolicyItem.addAccess(new RangerPolicyItemAccess("read", true)); + rangerPolicyItem.addAccess(new RangerPolicyItemAccess("write", true)); + rangerPolicyItem.addGroup("group1"); + rangerPolicyItem.addGroup("group2"); + rangerPolicyItem.addUser("user1"); + rangerPolicyItem.addUser("user2"); + rangerPolicyItem.setDelegateAdmin(true); + + existingPolicy.addPolicyItem(rangerPolicyItem); + + rangerPolicyItem = new RangerPolicyItem(); + rangerPolicyItem.addAccess(new RangerPolicyItemAccess("delete", true)); + rangerPolicyItem.addGroup("group1"); + rangerPolicyItem.addGroup("public"); + rangerPolicyItem.addUser("user1"); + rangerPolicyItem.addUser("finance"); + rangerPolicyItem.setDelegateAdmin(false); + + appliedPolicy.addPolicyItem(rangerPolicyItem); + + String existingPolicyStr = existingPolicy.toString(); + System.out.println("existingPolicy = " + existingPolicyStr); + + ServiceRESTUtil.processApplyPolicy(existingPolicy, appliedPolicy); + + String resultPolicyStr = existingPolicy.toString(); + System.out.println("resultPolicy = " + resultPolicyStr); + + Assert.assertTrue(true); + } + + @Test + public void test41applyPolicy() { + RangerPolicy existingPolicy = rangerPolicy(); + RangerPolicy appliedPolicy = rangerPolicy(); + + List policyItem = new ArrayList<>(); + existingPolicy.setPolicyItems(policyItem); + appliedPolicy.setPolicyItems(null); + + Map policyResources = new HashMap<>(); + RangerPolicyResource rangerPolicyResource = new RangerPolicyResource("/tmp"); + rangerPolicyResource.setIsExcludes(true); + rangerPolicyResource.setIsRecursive(true); + policyResources.put("path", rangerPolicyResource); + + existingPolicy.setResources(policyResources); + appliedPolicy.setResources(policyResources); + + RangerPolicyItem rangerPolicyItem = new RangerPolicyItem(); + rangerPolicyItem.addAccess(new RangerPolicyItemAccess("read", true)); + rangerPolicyItem.addAccess(new RangerPolicyItemAccess("write", true)); + rangerPolicyItem.addAccess(new RangerPolicyItemAccess("delete", true)); + rangerPolicyItem.addAccess(new RangerPolicyItemAccess("lock", true)); + rangerPolicyItem.addGroup("group1"); + rangerPolicyItem.addGroup("group2"); + rangerPolicyItem.addUser("user1"); + rangerPolicyItem.addUser("user2"); + rangerPolicyItem.setDelegateAdmin(true); + + rangerPolicyItem = new RangerPolicyItem(); + rangerPolicyItem.addAccess(new RangerPolicyItemAccess("read", true)); + rangerPolicyItem.addAccess(new RangerPolicyItemAccess("write", true)); + rangerPolicyItem.addAccess(new RangerPolicyItemAccess("delete", true)); + rangerPolicyItem.addAccess(new RangerPolicyItemAccess("lock", true)); + rangerPolicyItem.addGroup("group3"); + rangerPolicyItem.addUser("user3"); + rangerPolicyItem.setDelegateAdmin(true); + + existingPolicy.addPolicyItem(rangerPolicyItem); + + rangerPolicyItem = new RangerPolicyItem(); + rangerPolicyItem.addAccess(new RangerPolicyItemAccess("delete", true)); + rangerPolicyItem.addAccess(new RangerPolicyItemAccess("lock", true)); + rangerPolicyItem.addGroup("group1"); + rangerPolicyItem.addGroup("group2"); + rangerPolicyItem.addUser("user1"); + rangerPolicyItem.addUser("user2"); + rangerPolicyItem.setDelegateAdmin(false); + + existingPolicy.addAllowException(rangerPolicyItem); + + rangerPolicyItem = new RangerPolicyItem(); + rangerPolicyItem.addAccess(new RangerPolicyItemAccess("delete", true)); + rangerPolicyItem.addGroup("group2"); + rangerPolicyItem.addUser("user2"); + rangerPolicyItem.setDelegateAdmin(false); + + existingPolicy.addDenyPolicyItem(rangerPolicyItem); + + rangerPolicyItem = new RangerPolicyItem(); + rangerPolicyItem.addAccess(new RangerPolicyItemAccess("index", true)); + rangerPolicyItem.addGroup("public"); + rangerPolicyItem.addUser("user"); + rangerPolicyItem.setDelegateAdmin(false); + + existingPolicy.addDenyPolicyItem(rangerPolicyItem); + + rangerPolicyItem = new RangerPolicyItem(); + rangerPolicyItem.addAccess(new RangerPolicyItemAccess("delete", true)); + rangerPolicyItem.addAccess(new RangerPolicyItemAccess("index", true)); + + rangerPolicyItem.addGroup("group1"); + rangerPolicyItem.addUser("user1"); + rangerPolicyItem.setDelegateAdmin(false); + + appliedPolicy.addPolicyItem(rangerPolicyItem); + + rangerPolicyItem = new RangerPolicyItem(); + rangerPolicyItem.addAccess(new RangerPolicyItemAccess("delete", true)); + + rangerPolicyItem.addGroup("public"); + rangerPolicyItem.addUser("user1"); + rangerPolicyItem.setDelegateAdmin(false); + + appliedPolicy.addDenyPolicyItem(rangerPolicyItem); - private static Long Id = 8L; - - String importPoliceTestFilePath = "./src/test/java/org/apache/ranger/rest/importPolicy/import_policy_test_file.json"; - - @InjectMocks - ServiceREST serviceREST = new ServiceREST(); - - @Mock - RangerValidatorFactory validatorFactory; - - @Mock(answer = Answers.RETURNS_DEEP_STUBS) - RangerDaoManager daoManager; - - @Mock - ServiceDBStore svcStore; - - @Mock - SecurityZoneDBStore zoneStore; - - @Mock - TagDBStore tagStore; - - @Mock - RangerServiceService svcService; - - @Mock - RangerDataHistService dataHistService; - - @Mock - RangerExportPolicyList rangerExportPolicyList; - - @Mock - RangerServiceDefService serviceDefService; - - @Mock - RangerPolicyService policyService; - - @Mock - StringUtil stringUtil; - - @Mock - XUserService xUserService; - - @Mock - XUserMgr xUserMgr; - - @Mock - XUserMgr userMgr; - - @Mock - RangerAuditFields rangerAuditFields; - - @Mock - ContextUtil contextUtil; - - @Mock - RangerBizUtil bizUtil; - - @Mock - RESTErrorUtil restErrorUtil; - - @Mock - RangerServiceDefValidator serviceDefValidator; - - @Mock - RangerServiceValidator serviceValidator; - - @Mock - RangerPolicyValidator policyValidator; - - @Mock - ServiceMgr serviceMgr; - - @Mock - VXResponse vXResponse; - - @Mock - ServiceUtil serviceUtil; + String existingPolicyStr = existingPolicy.toString(); + System.out.println("existingPolicy=" + existingPolicyStr); - @Mock - RangerSearchUtil searchUtil; + ServiceRESTUtil.processApplyPolicy(existingPolicy, appliedPolicy); - @Mock - StringUtils stringUtils; + String resultPolicyStr = existingPolicy.toString(); + System.out.println("resultPolicy = " + resultPolicyStr); + + Assert.assertTrue(true); + } + + @Test + public void test42grant() { + RangerPolicy existingPolicy = rangerPolicy(); + List policyItem = new ArrayList<>(); + existingPolicy.setPolicyItems(policyItem); + + Map policyResources = new HashMap<>(); + RangerPolicyResource rangerPolicyResource = new RangerPolicyResource("/tmp"); + rangerPolicyResource.setIsExcludes(true); + rangerPolicyResource.setIsRecursive(true); + policyResources.put("path", rangerPolicyResource); + + existingPolicy.setResources(policyResources); + + RangerPolicyItem rangerPolicyItem = new RangerPolicyItem(); + rangerPolicyItem.addAccess(new RangerPolicyItemAccess("read", true)); + rangerPolicyItem.addAccess(new RangerPolicyItemAccess("write", true)); + rangerPolicyItem.addAccess(new RangerPolicyItemAccess("delete", true)); + rangerPolicyItem.addAccess(new RangerPolicyItemAccess("lock", true)); + rangerPolicyItem.addGroup("group1"); + rangerPolicyItem.addGroup("group2"); + rangerPolicyItem.addUser("user1"); + rangerPolicyItem.addUser("user2"); + rangerPolicyItem.setDelegateAdmin(true); + + existingPolicy.addPolicyItem(rangerPolicyItem); + + rangerPolicyItem = new RangerPolicyItem(); + rangerPolicyItem.addAccess(new RangerPolicyItemAccess("read", true)); + rangerPolicyItem.addAccess(new RangerPolicyItemAccess("write", true)); + rangerPolicyItem.addAccess(new RangerPolicyItemAccess("delete", true)); + rangerPolicyItem.addAccess(new RangerPolicyItemAccess("lock", true)); + rangerPolicyItem.addGroup("group3"); + rangerPolicyItem.addUser("user3"); + rangerPolicyItem.setDelegateAdmin(true); + + existingPolicy.addPolicyItem(rangerPolicyItem); + + rangerPolicyItem = new RangerPolicyItem(); + rangerPolicyItem.addAccess(new RangerPolicyItemAccess("delete", true)); + rangerPolicyItem.addAccess(new RangerPolicyItemAccess("lock", true)); + rangerPolicyItem.addGroup("group1"); + rangerPolicyItem.addGroup("group2"); + rangerPolicyItem.addUser("user1"); + rangerPolicyItem.addUser("user2"); + rangerPolicyItem.setDelegateAdmin(false); + + existingPolicy.addAllowException(rangerPolicyItem); + + rangerPolicyItem = new RangerPolicyItem(); + rangerPolicyItem.addAccess(new RangerPolicyItemAccess("delete", true)); + rangerPolicyItem.addGroup("group2"); + rangerPolicyItem.addUser("user2"); + rangerPolicyItem.setDelegateAdmin(false); + + existingPolicy.addDenyPolicyItem(rangerPolicyItem); + + rangerPolicyItem = new RangerPolicyItem(); + rangerPolicyItem.addAccess(new RangerPolicyItemAccess("index", true)); + rangerPolicyItem.addGroup("public"); + rangerPolicyItem.addUser("user"); + rangerPolicyItem.setDelegateAdmin(false); + + existingPolicy.addDenyPolicyItem(rangerPolicyItem); - @Mock - AssetMgr assetMgr; - - @Mock - RangerPolicyLabelsService policyLabelsService; + GrantRevokeRequest grantRequestObj = new GrantRevokeRequest(); + Map resource = new HashMap<>(); + resource.put("path", "/tmp"); + grantRequestObj.setResource(resource); - @Mock - RangerPluginInfoService pluginInfoService; - - @Mock - XXServiceDao xServiceDao; + grantRequestObj.getUsers().add("user1"); + grantRequestObj.getGroups().add("group1"); - @Mock - RangerPolicyEngineImpl rpImpl; - - @Mock - RangerPolicyAdmin policyAdmin; + grantRequestObj.getAccessTypes().add("delete"); + grantRequestObj.getAccessTypes().add("index"); - @Mock - RangerTransactionSynchronizationAdapter rangerTransactionSynchronizationAdapter; - - @Rule - public ExpectedException thrown = ExpectedException.none(); - - private String capabilityVector; - - private final String grantor = "test-grantor-1"; - - private final String owner_user = "test-owner-user-1"; - - private final String zone_name = "test-zone-1"; - - public void setup() { - RangerSecurityContext context = new RangerSecurityContext(); - context.setUserSession(new UserSessionBase()); - RangerContextHolder.setSecurityContext(context); - UserSessionBase currentUserSession = ContextUtil - .getCurrentUserSession(); - currentUserSession.setXXPortalUser(new XXPortalUser()); - currentUserSession.setUserAdmin(true); - capabilityVector = Long.toHexString(new RangerPluginCapability().getPluginCapabilities()); - } - - public RangerServiceDef rangerServiceDef() { - List configs = new ArrayList(); - List resources = new ArrayList(); - List accessTypes = new ArrayList(); - List policyConditions = new ArrayList(); - List contextEnrichers = new ArrayList(); - List enums = new ArrayList(); - - RangerServiceDef rangerServiceDef = new RangerServiceDef(); - rangerServiceDef.setId(Id); - rangerServiceDef.setImplClass("RangerServiceHdfs"); - rangerServiceDef.setLabel("HDFS Repository"); - rangerServiceDef.setDescription("HDFS Repository"); - rangerServiceDef.setRbKeyDescription(null); - rangerServiceDef.setUpdatedBy("Admin"); - rangerServiceDef.setUpdateTime(new Date()); - rangerServiceDef.setConfigs(configs); - rangerServiceDef.setResources(resources); - rangerServiceDef.setAccessTypes(accessTypes); - rangerServiceDef.setPolicyConditions(policyConditions); - rangerServiceDef.setContextEnrichers(contextEnrichers); - rangerServiceDef.setEnums(enums); - - return rangerServiceDef; - } - - public RangerService rangerService() { - Map configs = new HashMap(); - configs.put("username", "servicemgr"); - configs.put("password", "servicemgr"); - configs.put("namenode", "servicemgr"); - configs.put("hadoop.security.authorization", "No"); - configs.put("hadoop.security.authentication", "Simple"); - configs.put("hadoop.security.auth_to_local", ""); - configs.put("dfs.datanode.kerberos.principal", ""); - configs.put("dfs.namenode.kerberos.principal", ""); - configs.put("dfs.secondary.namenode.kerberos.principal", ""); - configs.put("hadoop.rpc.protection", "Privacy"); - configs.put("commonNameForCertificate", ""); - - RangerService rangerService = new RangerService(); - rangerService.setId(Id); - rangerService.setConfigs(configs); - rangerService.setCreateTime(new Date()); - rangerService.setDescription("service policy"); - rangerService.setGuid("1427365526516_835_0"); - rangerService.setIsEnabled(true); - rangerService.setName("HDFS_1"); - rangerService.setDisplayName("HDFS_1"); - rangerService.setPolicyUpdateTime(new Date()); - rangerService.setType("1"); - rangerService.setUpdatedBy("Admin"); - rangerService.setUpdateTime(new Date()); - - return rangerService; - } - - RangerPolicy rangerPolicy() { - List accesses = new ArrayList(); - List users = new ArrayList(); - List groups = new ArrayList(); - List conditions = new ArrayList(); - List policyItems = new ArrayList(); - RangerPolicyItem rangerPolicyItem = new RangerPolicyItem(); - rangerPolicyItem.setAccesses(accesses); - rangerPolicyItem.setConditions(conditions); - rangerPolicyItem.setGroups(groups); - rangerPolicyItem.setUsers(users); - rangerPolicyItem.setDelegateAdmin(false); - - policyItems.add(rangerPolicyItem); - - Map policyResource = new HashMap(); - RangerPolicyResource rangerPolicyResource = new RangerPolicyResource(); - rangerPolicyResource.setIsExcludes(true); - rangerPolicyResource.setIsRecursive(true); - rangerPolicyResource.setValue("1"); - rangerPolicyResource.setValues(users); - policyResource.put("resource", rangerPolicyResource); - RangerPolicy policy = new RangerPolicy(); - policy.setId(Id); - policy.setCreateTime(new Date()); - policy.setDescription("policy"); - policy.setGuid("policyguid"); - policy.setIsEnabled(true); - policy.setName("HDFS_1-1-20150316062453"); - policy.setUpdatedBy("Admin"); - policy.setUpdateTime(new Date()); - policy.setService("HDFS_1-1-20150316062453"); - policy.setIsAuditEnabled(true); - policy.setPolicyItems(policyItems); - policy.setResources(policyResource); - - return policy; - } - - public XXServiceDef serviceDef() { - XXServiceDef xServiceDef = new XXServiceDef(); - xServiceDef.setAddedByUserId(Id); - xServiceDef.setCreateTime(new Date()); - xServiceDef.setDescription("HDFS Repository"); - xServiceDef.setGuid("1427365526516_835_0"); - xServiceDef.setId(Id); - xServiceDef.setUpdateTime(new Date()); - xServiceDef.setUpdatedByUserId(Id); - xServiceDef.setImplclassname("RangerServiceHdfs"); - xServiceDef.setLabel("HDFS Repository"); - xServiceDef.setRbkeylabel(null); - xServiceDef.setRbkeydescription(null); - xServiceDef.setIsEnabled(true); - - return xServiceDef; - } - - public XXService xService() { - XXService xService = new XXService(); - xService.setAddedByUserId(Id); - xService.setCreateTime(new Date()); - xService.setDescription("Hdfs service"); - xService.setGuid("serviceguid"); - xService.setId(Id); - xService.setIsEnabled(true); - xService.setName("Hdfs"); - xService.setPolicyUpdateTime(new Date()); - xService.setPolicyVersion(1L); - xService.setType(1L); - xService.setUpdatedByUserId(Id); - xService.setUpdateTime(new Date()); - - return xService; - } - - public ServicePolicies servicePolicies() { - ServicePolicies sp = new ServicePolicies(); - sp.setAuditMode("auditMode"); - RangerPolicy rangerPolicy = rangerPolicy(); - List rpolList = new ArrayList(); - rpolList.add(rangerPolicy); - sp.setPolicies(rpolList); - sp.setPolicyVersion(1l); - sp.setServiceName("serviceName"); - sp.setServiceId(1l); - return sp; - } - private List createLongList(){ - List list = new ArrayList(); - list.add(1L); - list.add(2L); - list.add(3L); - return list; - } - private ArrayList createUserList() { - ArrayList userList = new ArrayList(); - userList.add("test-user-1"); - return userList; - } - private ArrayList createGroupList() { - ArrayList groupList = new ArrayList(); - groupList.add("test-group-1"); - return groupList; - } - private ArrayList createRoleList() { - ArrayList roleList = new ArrayList(); - roleList.add("test-role-1"); - return roleList; - } - private ArrayList createGrantorGroupList() { - ArrayList grantorGroupList = new ArrayList(); - grantorGroupList.add("test-grantor-group-1"); - return grantorGroupList; - } - - private HashMap createResourceMap() { - HashMap resourceMap = new HashMap(); - resourceMap.put("test-resource-1", "test-resource-value-1"); - return resourceMap; - } - - private ArrayList createAccessTypeList() { - ArrayList accessTypeList = new ArrayList(); - accessTypeList.add("test-access-type-1"); - return accessTypeList; - } - private GrantRevokeRequest createValidGrantRevokeRequest() { - GrantRevokeRequest grantRevokeRequest = new GrantRevokeRequest(); - grantRevokeRequest.setUsers(new HashSet<>(createUserList())); - grantRevokeRequest.setGroups(new HashSet<>(createGroupList())); - grantRevokeRequest.setRoles(new HashSet<>(createRoleList())); - grantRevokeRequest.setGrantor(grantor); - grantRevokeRequest.setGrantorGroups(new HashSet<>(createGrantorGroupList())); - grantRevokeRequest.setOwnerUser(owner_user); - grantRevokeRequest.setResource(createResourceMap()); - grantRevokeRequest.setAccessTypes(new HashSet<>(createAccessTypeList())); - grantRevokeRequest.setZoneName(zone_name); - grantRevokeRequest.setIsRecursive(true); - return grantRevokeRequest; - } - - private XXPolicy getXXPolicy() { - XXPolicy xxPolicy = new XXPolicy(); - xxPolicy.setId(Id); - xxPolicy.setName("HDFS_1-1-20150316062453"); - xxPolicy.setAddedByUserId(Id); - xxPolicy.setDescription("policy"); - xxPolicy.setGuid("policyguid"); - xxPolicy.setCreateTime(new Date()); - xxPolicy.setIsAuditEnabled(true); - xxPolicy.setIsEnabled(true); - xxPolicy.setService(1L); - xxPolicy.setUpdatedByUserId(Id); - xxPolicy.setUpdateTime(new Date()); - return xxPolicy; - } - - @Test - public void test1createServiceDef() throws Exception { - RangerServiceDef rangerServiceDef = rangerServiceDef(); - - Mockito.when(validatorFactory.getServiceDefValidator(svcStore)) - .thenReturn(serviceDefValidator); - - Mockito.when( - svcStore.createServiceDef((RangerServiceDef) Mockito - .any())).thenReturn(rangerServiceDef); - - RangerServiceDef dbRangerServiceDef = serviceREST - .createServiceDef(rangerServiceDef); - Assert.assertNotNull(dbRangerServiceDef); - Assert.assertEquals(dbRangerServiceDef, rangerServiceDef); - Assert.assertEquals(dbRangerServiceDef.getId(), - rangerServiceDef.getId()); - Assert.assertEquals(dbRangerServiceDef.getName(), - rangerServiceDef.getName()); - Assert.assertEquals(dbRangerServiceDef.getImplClass(), - rangerServiceDef.getImplClass()); - Assert.assertEquals(dbRangerServiceDef.getLabel(), - rangerServiceDef.getLabel()); - Assert.assertEquals(dbRangerServiceDef.getDescription(), - rangerServiceDef.getDescription()); - Assert.assertEquals(dbRangerServiceDef.getRbKeyDescription(), - rangerServiceDef.getRbKeyDescription()); - Assert.assertEquals(dbRangerServiceDef.getUpdatedBy(), - rangerServiceDef.getUpdatedBy()); - Assert.assertEquals(dbRangerServiceDef.getUpdateTime(), - rangerServiceDef.getUpdateTime()); - Assert.assertEquals(dbRangerServiceDef.getVersion(), - rangerServiceDef.getVersion()); - Assert.assertEquals(dbRangerServiceDef.getConfigs(), - rangerServiceDef.getConfigs()); - - Mockito.verify(validatorFactory).getServiceDefValidator(svcStore); - Mockito.verify(svcStore).createServiceDef(rangerServiceDef); - } - - @Test - public void test2updateServiceDef() throws Exception { - RangerServiceDef rangerServiceDef = rangerServiceDef(); - - Mockito.when(validatorFactory.getServiceDefValidator(svcStore)) - .thenReturn(serviceDefValidator); - - Mockito.when( - svcStore.updateServiceDef((RangerServiceDef) Mockito - .any())).thenReturn(rangerServiceDef); - - RangerServiceDef dbRangerServiceDef = serviceREST - .updateServiceDef(rangerServiceDef, rangerServiceDef.getId()); - Assert.assertNotNull(dbRangerServiceDef); - Assert.assertEquals(dbRangerServiceDef, rangerServiceDef); - Assert.assertEquals(dbRangerServiceDef.getId(), - rangerServiceDef.getId()); - Assert.assertEquals(dbRangerServiceDef.getName(), - rangerServiceDef.getName()); - Assert.assertEquals(dbRangerServiceDef.getImplClass(), - rangerServiceDef.getImplClass()); - Assert.assertEquals(dbRangerServiceDef.getLabel(), - rangerServiceDef.getLabel()); - Assert.assertEquals(dbRangerServiceDef.getDescription(), - rangerServiceDef.getDescription()); - Assert.assertEquals(dbRangerServiceDef.getRbKeyDescription(), - rangerServiceDef.getRbKeyDescription()); - Assert.assertEquals(dbRangerServiceDef.getUpdatedBy(), - rangerServiceDef.getUpdatedBy()); - Assert.assertEquals(dbRangerServiceDef.getUpdateTime(), - rangerServiceDef.getUpdateTime()); - Assert.assertEquals(dbRangerServiceDef.getVersion(), - rangerServiceDef.getVersion()); - Assert.assertEquals(dbRangerServiceDef.getConfigs(), - rangerServiceDef.getConfigs()); - - Mockito.verify(validatorFactory).getServiceDefValidator(svcStore); - Mockito.verify(svcStore).updateServiceDef(rangerServiceDef); - } - - @Test - public void test3deleteServiceDef() throws Exception { - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - RangerServiceDef rangerServiceDef = rangerServiceDef(); - XXServiceDef xServiceDef = serviceDef(); - XXServiceDefDao xServiceDefDao = Mockito.mock(XXServiceDefDao.class); - Mockito.when(validatorFactory.getServiceDefValidator(svcStore)) - .thenReturn(serviceDefValidator); - Mockito.when(daoManager.getXXServiceDef()).thenReturn(xServiceDefDao); - Mockito.when(xServiceDefDao.getById(Id)).thenReturn(xServiceDef); - - serviceREST.deleteServiceDef(rangerServiceDef.getId(), request); - Mockito.verify(validatorFactory).getServiceDefValidator(svcStore); - Mockito.verify(daoManager).getXXServiceDef(); - } - - @Test - public void test4getServiceDefById() throws Exception { - RangerServiceDef rangerServiceDef = rangerServiceDef(); - XXServiceDef xServiceDef = serviceDef(); - XXServiceDefDao xServiceDefDao = Mockito.mock(XXServiceDefDao.class); - - Mockito.when(daoManager.getXXServiceDef()).thenReturn(xServiceDefDao); - Mockito.when(xServiceDefDao.getById(Id)).thenReturn(xServiceDef); - Mockito.when(!bizUtil.hasAccess(xServiceDef, null)).thenReturn(true); - Mockito.when(svcStore.getServiceDef(rangerServiceDef.getId())) - .thenReturn(rangerServiceDef); - RangerServiceDef dbRangerServiceDef = serviceREST - .getServiceDef(rangerServiceDef.getId()); - Assert.assertNotNull(dbRangerServiceDef); - Assert.assertEquals(dbRangerServiceDef.getId(), - rangerServiceDef.getId()); - Mockito.verify(svcStore).getServiceDef(rangerServiceDef.getId()); - Mockito.verify(daoManager).getXXServiceDef(); - Mockito.verify(bizUtil).hasAccess(xServiceDef, null); - } - - @Test - public void test5getServiceDefByName() throws Exception { - RangerServiceDef rangerServiceDef = rangerServiceDef(); - XXServiceDef xServiceDef = serviceDef(); - XXServiceDefDao xServiceDefDao = Mockito.mock(XXServiceDefDao.class); - - Mockito.when(daoManager.getXXServiceDef()).thenReturn(xServiceDefDao); - Mockito.when(xServiceDefDao.findByName(xServiceDef.getName())) - .thenReturn(xServiceDef); - Mockito.when(!bizUtil.hasAccess(xServiceDef, null)).thenReturn(true); - Mockito.when(svcStore.getServiceDefByName(rangerServiceDef.getName())) - .thenReturn(rangerServiceDef); - RangerServiceDef dbRangerServiceDef = serviceREST - .getServiceDefByName(rangerServiceDef.getName()); - Assert.assertNotNull(dbRangerServiceDef); - Assert.assertEquals(dbRangerServiceDef.getName(), - rangerServiceDef.getName()); - Mockito.verify(svcStore) - .getServiceDefByName(rangerServiceDef.getName()); - Mockito.verify(daoManager).getXXServiceDef(); - } - - @Test - public void test6createService() throws Exception { - - RangerService rangerService = rangerService(); - XXServiceDef xServiceDef = serviceDef(); - XXServiceDefDao xServiceDefDao = Mockito.mock(XXServiceDefDao.class); - Mockito.when(validatorFactory.getServiceValidator(svcStore)) - .thenReturn(serviceValidator); - - Mockito.when(daoManager.getXXServiceDef()).thenReturn(xServiceDefDao); - Mockito.when(xServiceDefDao.findByName(rangerService.getType())) - .thenReturn(xServiceDef); - - Mockito.when( - svcStore.createService((RangerService) Mockito.any())) - .thenReturn(rangerService); - - RangerService dbRangerService = serviceREST - .createService(rangerService); - Assert.assertNotNull(dbRangerService); - Assert.assertEquals(rangerService, dbRangerService); - Assert.assertEquals(rangerService.getId(), dbRangerService.getId()); - Assert.assertEquals(rangerService.getConfigs(), - dbRangerService.getConfigs()); - Assert.assertEquals(rangerService.getDescription(), - dbRangerService.getDescription()); - Assert.assertEquals(rangerService.getGuid(), dbRangerService.getGuid()); - Assert.assertEquals(rangerService.getName(), dbRangerService.getName()); - Assert.assertEquals(rangerService.getPolicyVersion(), - dbRangerService.getPolicyVersion()); - Assert.assertEquals(rangerService.getType(), dbRangerService.getType()); - Assert.assertEquals(rangerService.getVersion(), - dbRangerService.getVersion()); - Assert.assertEquals(rangerService.getCreateTime(), - dbRangerService.getCreateTime()); - Assert.assertEquals(rangerService.getUpdateTime(), - dbRangerService.getUpdateTime()); - Assert.assertEquals(rangerService.getUpdatedBy(), - dbRangerService.getUpdatedBy()); - - Mockito.verify(validatorFactory).getServiceValidator(svcStore); - Mockito.verify(svcStore).createService(rangerService); - } - - @Test - public void test7getServiceDefs() throws Exception { - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - SearchFilter filter = new SearchFilter(); - filter.setParam(SearchFilter.POLICY_NAME, "policyName"); - filter.setParam(SearchFilter.SERVICE_NAME, "serviceName"); - Mockito.when( - searchUtil.getSearchFilter(request, - serviceDefService.sortFields)).thenReturn(filter); - - List serviceDefsList = new ArrayList(); - RangerServiceDef serviceDef = rangerServiceDef(); - serviceDefsList.add(serviceDef); - PList serviceDefList = new PList(); - serviceDefList.setPageSize(0); - serviceDefList.setResultSize(1); - serviceDefList.setSortBy("asc"); - serviceDefList.setSortType("1"); - serviceDefList.setStartIndex(0); - serviceDefList.setTotalCount(10); - serviceDefList.setList(serviceDefsList); - Mockito.when(bizUtil.hasModuleAccess(RangerConstants.MODULE_RESOURCE_BASED_POLICIES)).thenReturn(true); - Mockito.when(svcStore.getPaginatedServiceDefs(filter)).thenReturn( - serviceDefList); - RangerServiceDefList dbRangerServiceDef = serviceREST - .getServiceDefs(request); - Assert.assertNotNull(dbRangerServiceDef); - Mockito.verify(searchUtil).getSearchFilter(request, - serviceDefService.sortFields); - Mockito.verify(svcStore).getPaginatedServiceDefs(filter); - } - - @Test - public void test8updateServiceDef() throws Exception { - - RangerService rangerService = rangerService(); - XXServiceDef xServiceDef = serviceDef(); - HttpServletRequest request = null; - Map options = null; - - XXServiceDefDao xServiceDefDao = Mockito.mock(XXServiceDefDao.class); - Mockito.when(validatorFactory.getServiceValidator(svcStore)) - .thenReturn(serviceValidator); - - Mockito.when(daoManager.getXXServiceDef()).thenReturn(xServiceDefDao); - Mockito.when(xServiceDefDao.findByName(rangerService.getType())) - .thenReturn(xServiceDef); - - Mockito.when( - svcStore.updateService((RangerService) Mockito.any(), (Map) Mockito.any())) - .thenReturn(rangerService); - - RangerService dbRangerService = serviceREST - .updateService(rangerService, request); - Assert.assertNotNull(dbRangerService); - Assert.assertNotNull(dbRangerService); - Assert.assertEquals(rangerService, dbRangerService); - Assert.assertEquals(rangerService.getId(), dbRangerService.getId()); - Assert.assertEquals(rangerService.getConfigs(), - dbRangerService.getConfigs()); - Assert.assertEquals(rangerService.getDescription(), - dbRangerService.getDescription()); - Assert.assertEquals(rangerService.getGuid(), dbRangerService.getGuid()); - Assert.assertEquals(rangerService.getName(), dbRangerService.getName()); - Assert.assertEquals(rangerService.getPolicyVersion(), - dbRangerService.getPolicyVersion()); - Assert.assertEquals(rangerService.getType(), dbRangerService.getType()); - Assert.assertEquals(rangerService.getVersion(), - dbRangerService.getVersion()); - Assert.assertEquals(rangerService.getCreateTime(), - dbRangerService.getCreateTime()); - Assert.assertEquals(rangerService.getUpdateTime(), - dbRangerService.getUpdateTime()); - Assert.assertEquals(rangerService.getUpdatedBy(), - dbRangerService.getUpdatedBy()); - Mockito.verify(validatorFactory).getServiceValidator(svcStore); - Mockito.verify(daoManager).getXXServiceDef(); - Mockito.verify(svcStore).updateService(rangerService, options); - } - - @Test - public void test9deleteService() throws Exception { - RangerService rangerService = rangerService(); - XXServiceDef xServiceDef = serviceDef(); - XXService xService = xService(); - XXServiceDefDao xServiceDefDao = Mockito.mock(XXServiceDefDao.class); - XXServiceDao xServiceDao = Mockito.mock(XXServiceDao.class); - Mockito.when(validatorFactory.getServiceValidator(svcStore)) - .thenReturn(serviceValidator); - - Mockito.when(daoManager.getXXService()).thenReturn(xServiceDao); - Mockito.when(xServiceDao.getById(Id)).thenReturn(xService); - Mockito.when(daoManager.getXXServiceDef()).thenReturn(xServiceDefDao); - Mockito.when(xServiceDefDao.getById(xService.getType())).thenReturn( - xServiceDef); - - serviceREST.deleteService(rangerService.getId()); - - Mockito.verify(validatorFactory).getServiceValidator(svcStore); - Mockito.verify(daoManager).getXXService(); - Mockito.verify(daoManager).getXXServiceDef(); - } - - @Test - public void test10getServiceById() throws Exception { - RangerService rangerService = rangerService(); - Mockito.when(svcStore.getService(rangerService.getId())).thenReturn( - rangerService); - RangerService dbRangerService = serviceREST.getService(rangerService - .getId()); - Assert.assertNotNull(dbRangerService); - Assert.assertEquals(dbRangerService.getId(), dbRangerService.getId()); - Mockito.verify(svcStore).getService(dbRangerService.getId()); - } - - @Test - public void test11getServiceByName() throws Exception { - RangerService rangerService = rangerService(); - Mockito.when(svcStore.getServiceByName(rangerService.getName())) - .thenReturn(rangerService); - RangerService dbRangerService = serviceREST - .getServiceByName(rangerService.getName()); - Assert.assertNotNull(dbRangerService); - Assert.assertEquals(dbRangerService.getName(), - dbRangerService.getName()); - Mockito.verify(svcStore).getServiceByName(dbRangerService.getName()); - } - - @Test - public void test12deleteServiceDef() { - RangerServiceDef rangerServiceDef = rangerServiceDef(); - XXServiceDef xServiceDef = serviceDef(); - XXServiceDefDao xServiceDefDao = Mockito.mock(XXServiceDefDao.class); - Mockito.when(validatorFactory.getServiceDefValidator(svcStore)) - .thenReturn(serviceDefValidator); - - Mockito.when(daoManager.getXXServiceDef()).thenReturn(xServiceDefDao); - Mockito.when(xServiceDefDao.getById(Id)).thenReturn(xServiceDef); - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - serviceREST.deleteServiceDef(rangerServiceDef.getId(), request); - Mockito.verify(validatorFactory).getServiceDefValidator(svcStore); - Mockito.verify(daoManager).getXXServiceDef(); - } - - @Test - public void test13lookupResource() throws Exception { - String serviceName = "HDFS_1"; - ResourceLookupContext context = new ResourceLookupContext(); - context.setResourceName(serviceName); - context.setUserInput("HDFS"); - List list = serviceREST.lookupResource(serviceName, context); - Assert.assertNotNull(list); - } - - @Test - public void test14grantAccess() throws Exception { - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - String serviceName = "HDFS_1"; - GrantRevokeRequest grantRequestObj = new GrantRevokeRequest(); - grantRequestObj.setAccessTypes(null); - grantRequestObj.setDelegateAdmin(true); - grantRequestObj.setEnableAudit(true); - grantRequestObj.setGrantor("read"); - grantRequestObj.setIsRecursive(true); - - Mockito.when( - serviceUtil.isValidateHttpsAuthentication(serviceName, request)) - .thenReturn(false); - RESTResponse restResponse = serviceREST.grantAccess(serviceName, - grantRequestObj, request); - Assert.assertNotNull(restResponse); - Mockito.verify(serviceUtil).isValidateHttpsAuthentication(serviceName, - request); - } - - @Test - public void test14_1_grantAccessWithMultiColumns() throws Exception { - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - - String serviceName = "HIVE"; - Set userList = new HashSet(); - userList.add("user1"); - userList.add("user2"); - userList.add("user3"); - - Map grantResource = new HashMap<>(); - grantResource.put("database", "demo"); - grantResource.put("table", "testtbl"); - grantResource.put("column", "column1,column2,colum3"); - GrantRevokeRequest grantRequestObj = new GrantRevokeRequest(); - - grantRequestObj.setResource(grantResource); - grantRequestObj.setUsers(userList); - grantRequestObj.setAccessTypes(new HashSet<>(Arrays.asList("select"))); - grantRequestObj.setDelegateAdmin(true); - grantRequestObj.setEnableAudit(true); - grantRequestObj.setGrantor("systest"); - grantRequestObj.setIsRecursive(true); - - RangerAccessResource resource = new RangerAccessResourceImpl(serviceREST.getAccessResourceObjectMap(grantRequestObj.getResource()), "systest"); - - RangerPolicy createPolicy = new RangerPolicy(); - createPolicy.setService(serviceName); - createPolicy.setName("grant-" + System.currentTimeMillis()); - createPolicy.setDescription("created by grant"); - createPolicy.setIsAuditEnabled(grantRequestObj.getEnableAudit()); - - Map policyResources = new HashMap<>(); - Set resourceNames = resource.getKeys(); - - if (!CollectionUtils.isEmpty(resourceNames)) { - for (String resourceName : resourceNames) { - policyResources.put(resourceName, serviceREST.getPolicyResource(resource.getValue(resourceName), grantRequestObj)); - } - } - createPolicy.setResources(policyResources); - - RangerPolicyItem policyItem = new RangerPolicyItem(); - policyItem.setDelegateAdmin(grantRequestObj.getDelegateAdmin()); - policyItem.addUsers(grantRequestObj.getUsers()); - for (String accessType : grantRequestObj.getAccessTypes()) { - policyItem.addAccess(new RangerPolicyItemAccess(accessType, Boolean.TRUE)); - } - createPolicy.addPolicyItem(policyItem); - createPolicy.setZoneName(null); - - List grantColumns = (List) resource.getValue("column"); - Map policyResourceMap = createPolicy.getResources(); - List createdPolicyColumns = policyResourceMap.get("column").getValues(); - - Assert.assertTrue(createdPolicyColumns.containsAll(grantColumns)); - - Mockito.when( - serviceUtil.isValidateHttpsAuthentication(serviceName, request)) - .thenReturn(false); - RESTResponse restResponse = serviceREST.grantAccess(serviceName, - grantRequestObj, request); - Assert.assertNotNull(restResponse); - Mockito.verify(serviceUtil).isValidateHttpsAuthentication(serviceName, - request); - } - - @Test - public void test15revokeAccess() throws Exception { - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - String serviceName = "HDFS_1"; - Set userList = new HashSet(); - userList.add("user1"); - userList.add("user2"); - userList.add("user3"); - Set groupList = new HashSet(); - groupList.add("group1"); - groupList.add("group2"); - groupList.add("group3"); - GrantRevokeRequest revokeRequest = new GrantRevokeRequest(); - revokeRequest.setDelegateAdmin(true); - revokeRequest.setEnableAudit(true); - revokeRequest.setGrantor("read"); - revokeRequest.setGroups(groupList); - revokeRequest.setUsers(userList); - - RESTResponse restResponse = serviceREST.revokeAccess(serviceName, - revokeRequest, request); - Assert.assertNotNull(restResponse); - } - - @Test - public void test16createPolicyFalse() throws Exception { - RangerPolicy rangerPolicy = rangerPolicy(); - RangerServiceDef rangerServiceDef = rangerServiceDef(); - - List policies = new ArrayList(); - RangerPolicy rangPolicy = new RangerPolicy(); - policies.add(rangPolicy); - - String userName = "admin"; - Set userGroupsList = new HashSet(); - userGroupsList.add("group1"); - userGroupsList.add("group2"); - - ServicePolicies servicePolicies = new ServicePolicies(); - servicePolicies.setServiceId(Id); - servicePolicies.setServiceName("Hdfs_1"); - servicePolicies.setPolicyVersion(1L); - servicePolicies.setPolicyUpdateTime(new Date()); - servicePolicies.setServiceDef(rangerServiceDef); - servicePolicies.setPolicies(policies); - - List rangerAccessTypeDefList = new ArrayList(); - RangerAccessTypeDef rangerAccessTypeDefObj = new RangerAccessTypeDef(); - rangerAccessTypeDefObj.setLabel("Read"); - rangerAccessTypeDefObj.setName("read"); - rangerAccessTypeDefObj.setRbKeyLabel(null); - rangerAccessTypeDefList.add(rangerAccessTypeDefObj); - XXServiceDef xServiceDef = serviceDef(); - XXService xService = xService(); - XXServiceDefDao xServiceDefDao = Mockito.mock(XXServiceDefDao.class); - XXServiceDao xServiceDao = Mockito.mock(XXServiceDao.class); - - Mockito.when(validatorFactory.getPolicyValidator(svcStore)).thenReturn( - policyValidator); - Mockito.when(bizUtil.isAdmin()).thenReturn(true); - Mockito.when(bizUtil.getCurrentUserLoginId()).thenReturn(userName); - Mockito.when(daoManager.getXXService()).thenReturn(xServiceDao); - Mockito.when(xServiceDao.findByName(Mockito.anyString())).thenReturn( - xService); - Mockito.when(daoManager.getXXServiceDef()).thenReturn(xServiceDefDao); - Mockito.when(xServiceDefDao.getById(xService.getType())).thenReturn( - xServiceDef); - Mockito.when(svcStore.createPolicy((RangerPolicy) Mockito.any())) - .thenReturn(rangPolicy); - - RangerPolicy dbRangerPolicy = serviceREST.createPolicy(rangerPolicy,null); - Assert.assertNotNull(dbRangerPolicy); - Mockito.verify(bizUtil, Mockito.times(2)).isAdmin(); - Mockito.verify(validatorFactory).getPolicyValidator(svcStore); - - Mockito.verify(daoManager).getXXService(); - Mockito.verify(daoManager, Mockito.atLeastOnce()).getXXServiceDef(); - } - - @Test - public void test17updatePolicyFalse() throws Exception { - RangerPolicy rangerPolicy = rangerPolicy(); - String userName = "admin"; - - Set userGroupsList = new HashSet(); - userGroupsList.add("group1"); - userGroupsList.add("group2"); - - List rangerAccessTypeDefList = new ArrayList(); - RangerAccessTypeDef rangerAccessTypeDefObj = new RangerAccessTypeDef(); - rangerAccessTypeDefObj.setLabel("Read"); - rangerAccessTypeDefObj.setName("read"); - rangerAccessTypeDefObj.setRbKeyLabel(null); - rangerAccessTypeDefList.add(rangerAccessTypeDefObj); - XXServiceDef xServiceDef = serviceDef(); - XXService xService = xService(); - XXServiceDefDao xServiceDefDao = Mockito.mock(XXServiceDefDao.class); - XXServiceDao xServiceDao = Mockito.mock(XXServiceDao.class); - - Mockito.when(validatorFactory.getPolicyValidator(svcStore)).thenReturn( - policyValidator); - Mockito.when(bizUtil.isAdmin()).thenReturn(true); - Mockito.when(bizUtil.getCurrentUserLoginId()).thenReturn(userName); - Mockito.when(daoManager.getXXService()).thenReturn(xServiceDao); - Mockito.when(xServiceDao.findByName(Mockito.anyString())).thenReturn(xService); - Mockito.when(daoManager.getXXServiceDef()).thenReturn(xServiceDefDao); - Mockito.when(xServiceDefDao.getById(xService.getType())).thenReturn(xServiceDef); - RangerPolicy dbRangerPolicy = serviceREST.updatePolicy(rangerPolicy, Id); - Assert.assertNull(dbRangerPolicy); - Mockito.verify(validatorFactory).getPolicyValidator(svcStore); - } - - @Test - public void test18deletePolicyFalse() throws Exception { - RangerPolicy rangerPolicy = rangerPolicy(); - - Mockito.when(validatorFactory.getPolicyValidator(svcStore)).thenReturn( - policyValidator); - String userName = "admin"; - - Set userGroupsList = new HashSet(); - userGroupsList.add("group1"); - userGroupsList.add("group2"); - - List rangerAccessTypeDefList = new ArrayList(); - RangerAccessTypeDef rangerAccessTypeDefObj = new RangerAccessTypeDef(); - rangerAccessTypeDefObj.setLabel("Read"); - rangerAccessTypeDefObj.setName("read"); - rangerAccessTypeDefObj.setRbKeyLabel(null); - rangerAccessTypeDefList.add(rangerAccessTypeDefObj); - XXServiceDef xServiceDef = serviceDef(); - XXService xService = xService(); - XXServiceDefDao xServiceDefDao = Mockito.mock(XXServiceDefDao.class); - XXServiceDao xServiceDao = Mockito.mock(XXServiceDao.class); - Mockito.when(validatorFactory.getPolicyValidator(svcStore)).thenReturn( - policyValidator); - Mockito.when(bizUtil.isAdmin()).thenReturn(true); - Mockito.when(bizUtil.getCurrentUserLoginId()).thenReturn(userName); - Mockito.when(svcStore.getPolicy(Id)).thenReturn(rangerPolicy); - Mockito.when(daoManager.getXXService()).thenReturn(xServiceDao); - Mockito.when(xServiceDao.findByName(Mockito.anyString())).thenReturn(xService); - Mockito.when(daoManager.getXXServiceDef()).thenReturn(xServiceDefDao); - Mockito.when(xServiceDefDao.getById(xService.getType())).thenReturn(xServiceDef); - serviceREST.deletePolicy(rangerPolicy.getId()); - Mockito.verify(validatorFactory).getPolicyValidator(svcStore); - } - - @Test - public void test19getPolicyFalse() throws Exception { - RangerPolicy rangerPolicy = rangerPolicy(); - Mockito.when(svcStore.getPolicy(rangerPolicy.getId())).thenReturn( - rangerPolicy); - String userName = "admin"; - - Set userGroupsList = new HashSet(); - userGroupsList.add("group1"); - userGroupsList.add("group2"); - - List rangerAccessTypeDefList = new ArrayList(); - RangerAccessTypeDef rangerAccessTypeDefObj = new RangerAccessTypeDef(); - rangerAccessTypeDefObj.setLabel("Read"); - rangerAccessTypeDefObj.setName("read"); - rangerAccessTypeDefObj.setRbKeyLabel(null); - rangerAccessTypeDefList.add(rangerAccessTypeDefObj); - XXServiceDef xServiceDef = serviceDef(); - XXService xService = xService(); - XXServiceDefDao xServiceDefDao = Mockito.mock(XXServiceDefDao.class); - XXServiceDao xServiceDao = Mockito.mock(XXServiceDao.class); - Mockito.when(bizUtil.isAdmin()).thenReturn(true); - Mockito.when(bizUtil.getCurrentUserLoginId()).thenReturn(userName); - Mockito.when(daoManager.getXXService()).thenReturn(xServiceDao); - Mockito.when(xServiceDao.findByName(Mockito.anyString())).thenReturn(xService); - Mockito.when(daoManager.getXXServiceDef()).thenReturn(xServiceDefDao); - Mockito.when(xServiceDefDao.getById(xService.getType())).thenReturn(xServiceDef); - RangerPolicy dbRangerPolicy = serviceREST.getPolicy(rangerPolicy - .getId()); - Assert.assertNotNull(dbRangerPolicy); - Assert.assertEquals(dbRangerPolicy.getId(), rangerPolicy.getId()); - Mockito.verify(svcStore).getPolicy(rangerPolicy.getId()); - } - - @Test - public void test20getPolicies() throws Exception { - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - SearchFilter filter = new SearchFilter(); - filter.setParam(SearchFilter.POLICY_NAME, "policyName"); - filter.setParam(SearchFilter.SERVICE_NAME, "serviceName"); - Mockito.when( - searchUtil.getSearchFilter(request, policyService.sortFields)) - .thenReturn(filter); - RangerPolicyList dbRangerPolicy = serviceREST.getPolicies(request); - Assert.assertNotNull(dbRangerPolicy); - Assert.assertEquals(dbRangerPolicy.getListSize(), 0); - Mockito.verify(searchUtil).getSearchFilter(request, - policyService.sortFields); - } - - @Test - public void test21countPolicies() throws Exception { - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - - SearchFilter filter = new SearchFilter(); - filter.setParam(SearchFilter.POLICY_NAME, "policyName"); - filter.setParam(SearchFilter.SERVICE_NAME, "serviceName"); - Mockito.when( - searchUtil.getSearchFilter(request, policyService.sortFields)) - .thenReturn(filter); - - Long data = serviceREST.countPolicies(request); - Assert.assertNotNull(data); - Mockito.verify(searchUtil).getSearchFilter(request, - policyService.sortFields); - } - - @Test - public void test22getServicePoliciesById() throws Exception { - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - RangerPolicy rangerPolicy = rangerPolicy(); - - SearchFilter filter = new SearchFilter(); - filter.setParam(SearchFilter.POLICY_NAME, "policyName"); - filter.setParam(SearchFilter.SERVICE_NAME, "serviceName"); - Mockito.when( - searchUtil.getSearchFilter(request, policyService.sortFields)) - .thenReturn(filter); - - RangerPolicyList dbRangerPolicy = serviceREST.getServicePolicies( - rangerPolicy.getId(), request); - Assert.assertNotNull(dbRangerPolicy); - Mockito.verify(searchUtil).getSearchFilter(request, - policyService.sortFields); - Mockito.verify(svcStore).getServicePolicies(Id, filter); - } - - @Test - public void test23getServicePoliciesByName() throws Exception { - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - RangerPolicy rangerPolicy = rangerPolicy(); - - List ret = Mockito.mock(List.class); - SearchFilter filter = new SearchFilter(); - filter.setParam(SearchFilter.POLICY_NAME, "policyName"); - filter.setParam(SearchFilter.SERVICE_NAME, "serviceName"); - Mockito.when( - searchUtil.getSearchFilter(request, policyService.sortFields)) - .thenReturn(filter); - - Mockito.when( - svcStore.getServicePolicies(rangerPolicy.getName(), - filter)).thenReturn(ret); - - RangerPolicyList dbRangerPolicy = serviceREST.getServicePoliciesByName( - rangerPolicy.getName(), request); - Assert.assertNotNull(dbRangerPolicy); - } - - @Test - public void test24getServicePoliciesIfUpdated() throws Exception { - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - String serviceName = "HDFS_1"; - Long lastKnownVersion = 1L; - String pluginId = "1"; - - ServicePolicies dbServicePolicies = serviceREST - .getServicePoliciesIfUpdated(serviceName, lastKnownVersion, 0L, - pluginId, "", "", false, capabilityVector, request); - Assert.assertNull(dbServicePolicies); - } - - - @Test - public void test25getPolicies() throws Exception { - List ret = new ArrayList(); - SearchFilter filter = new SearchFilter(); - filter.setParam(SearchFilter.POLICY_NAME, "policyName"); - filter.setParam(SearchFilter.SERVICE_NAME, "serviceName"); - Mockito.when(svcStore.getPolicies(filter)).thenReturn(ret); - - List dbRangerPolicyList = serviceREST.getPolicies(filter); - Assert.assertNotNull(dbRangerPolicyList); - Mockito.verify(svcStore).getPolicies(filter); - - } - - @Test - public void test26getServices() throws Exception { - List ret = new ArrayList(); - SearchFilter filter = new SearchFilter(); - filter.setParam(SearchFilter.POLICY_NAME, "policyName"); - filter.setParam(SearchFilter.SERVICE_NAME, "serviceName"); - Mockito.when(svcStore.getServices(filter)).thenReturn(ret); - - List dbRangerService = serviceREST.getServices(filter); - Assert.assertNotNull(dbRangerService); - Mockito.verify(svcStore).getServices(filter); - } - - @Test - public void test27getPoliciesWithoutServiceAdmin() throws Exception { - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - SearchFilter filter = new SearchFilter(); - List policies = new ArrayList(); - policies.add(rangerPolicy()); - filter.setParam(SearchFilter.POLICY_NAME, "policyName"); - filter.setParam(SearchFilter.SERVICE_NAME, "serviceName"); - Mockito.when(searchUtil.getSearchFilter(request, policyService.sortFields)).thenReturn(filter); - Mockito.when(svcStore.getPolicies(filter)).thenReturn(policies); - RangerPolicyList dbRangerPolicy = serviceREST.getPolicies(request); - Assert.assertNotNull(dbRangerPolicy); - /*here we are not setting service admin role,hence we will not get any policy without the service admin roles*/ - Assert.assertEquals(dbRangerPolicy.getListSize(), 0); - Mockito.verify(searchUtil).getSearchFilter(request, - policyService.sortFields); - } - - @Test - public void test28getPoliciesWithServiceAdmin() throws Exception { - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - SearchFilter filter = new SearchFilter(); - XXService xs = Mockito.mock(XXService.class); - xs.setType(3L); - ServiceREST spySVCRest = Mockito.spy(serviceREST); - List policies = new ArrayList(); - ServicePolicies svcPolicies = new ServicePolicies(); - svcPolicies.setPolicies(policies); - svcPolicies.setServiceName("HDFS_1-1-20150316062453"); - RangerPolicy rPol=rangerPolicy(); - policies.add(rPol); - filter.setParam(SearchFilter.POLICY_NAME, "policyName"); - filter.setParam(SearchFilter.SERVICE_NAME, "serviceName"); - Mockito.when(searchUtil.getSearchFilter(request, policyService.sortFields)).thenReturn(filter); - Mockito.when(svcStore.getPolicies(filter)).thenReturn(policies); - /*here we are setting serviceAdminRole, so we will get the required policy with serviceAdmi role*/ - Mockito.when(svcStore.isServiceAdminUser(rPol.getService(), null)).thenReturn(true); - RangerPolicyList dbRangerPolicy = spySVCRest.getPolicies(request); - Assert.assertNotNull(dbRangerPolicy); - Assert.assertEquals(dbRangerPolicy.getListSize(), 1); - Mockito.verify(searchUtil).getSearchFilter(request, - policyService.sortFields); - Mockito.verify(svcStore).getPolicies(filter); - Mockito.verify(svcStore).isServiceAdminUser(rPol.getService(), null); - } - - - @Test - public void test30getPolicyFromEventTime() throws Exception { - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - - String strdt = new Date().toString(); - String userName="Admin"; - Set userGroupsList = new HashSet(); - userGroupsList.add("group1"); - userGroupsList.add("group2"); - Mockito.when(request.getParameter("eventTime")).thenReturn(strdt); - Mockito.when(request.getParameter("policyId")).thenReturn("1"); - Mockito.when(request.getParameter("versionNo")).thenReturn("1"); - RangerPolicy policy=new RangerPolicy(); - Map resources=new HashMap(); - policy.setService("services"); - policy.setResources(resources); - Mockito.when(svcStore.getPolicyFromEventTime(strdt, 1l)).thenReturn(policy); - Mockito.when(bizUtil.isAdmin()).thenReturn(false); - Mockito.when(bizUtil.getCurrentUserLoginId()).thenReturn(userName); - - Mockito.when(restErrorUtil.createRESTException(Mockito.anyInt(), Mockito.anyString(), Mockito.anyBoolean())) - .thenThrow(new WebApplicationException()); - thrown.expect(WebApplicationException.class); - - RangerPolicy dbRangerPolicy = serviceREST - .getPolicyFromEventTime(request); - Assert.assertNull(dbRangerPolicy); - Mockito.verify(request).getParameter("eventTime"); - Mockito.verify(request).getParameter("policyId"); - Mockito.verify(request).getParameter("versionNo"); - } - - @Test - public void test31getServices() throws Exception { - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - SearchFilter filter = new SearchFilter(); - filter.setParam(SearchFilter.POLICY_NAME, "policyName"); - filter.setParam(SearchFilter.SERVICE_NAME, "serviceName"); - RangerServiceList dbRangerService = serviceREST.getServices(request); - Assert.assertNull(dbRangerService); - } - - - @Test - public void test32getPolicyVersionList() throws Exception { - VXString vXString = new VXString(); - vXString.setValue("1"); - Mockito.when(svcStore.getPolicyVersionList(Id)).thenReturn(vXString); - - VXString dbVXString = serviceREST.getPolicyVersionList(Id); - Assert.assertNotNull(dbVXString); - Mockito.verify(svcStore).getPolicyVersionList(Id); - } - - @Test - public void test33getPolicyForVersionNumber() throws Exception { - RangerPolicy rangerPolicy = rangerPolicy(); - Mockito.when(svcStore.getPolicyForVersionNumber(Id, 1)).thenReturn(rangerPolicy); - Mockito.when(bizUtil.isAdmin()).thenReturn(true); - RangerPolicy dbRangerPolicy = serviceREST.getPolicyForVersionNumber(Id, 1); - Assert.assertNotNull(dbRangerPolicy); - Mockito.verify(svcStore).getPolicyForVersionNumber(Id, 1); - } - - @Test - public void test34countServices() throws Exception { - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - PList ret = Mockito.mock(PList.class); - SearchFilter filter = new SearchFilter(); - filter.setParam(SearchFilter.POLICY_NAME, "policyName"); - filter.setParam(SearchFilter.SERVICE_NAME, "serviceName"); - Mockito.when( - searchUtil.getSearchFilter(request, policyService.sortFields)) - .thenReturn(filter); - - Mockito.when(svcStore.getPaginatedServices(filter)).thenReturn(ret); - Long data = serviceREST.countServices(request); - Assert.assertNotNull(data); - Mockito.verify(searchUtil).getSearchFilter(request, - policyService.sortFields); - Mockito.verify(svcStore).getPaginatedServices(filter); - } - - @Test - public void test35validateConfig() throws Exception { - RangerService rangerService = rangerService(); - Mockito.when(serviceMgr.validateConfig(rangerService, svcStore)) - .thenReturn(vXResponse); - VXResponse dbVXResponse = serviceREST.validateConfig(rangerService); - Assert.assertNotNull(dbVXResponse); - Mockito.verify(serviceMgr).validateConfig(rangerService, svcStore); - } - - @Test - public void test40applyPolicy() { - RangerPolicy existingPolicy = rangerPolicy(); - RangerPolicy appliedPolicy = rangerPolicy(); - - List policyItem = new ArrayList(); - existingPolicy.setPolicyItems(policyItem ); - appliedPolicy.setPolicyItems(null); - - Map policyResources = new HashMap(); - RangerPolicyResource rangerPolicyResource = new RangerPolicyResource("/tmp"); - rangerPolicyResource.setIsExcludes(true); - rangerPolicyResource.setIsRecursive(true); - policyResources.put("path", rangerPolicyResource); - - existingPolicy.setResources(policyResources); - appliedPolicy.setResources(policyResources); - - RangerPolicyItem rangerPolicyItem = new RangerPolicyItem(); - rangerPolicyItem.addAccess(new RangerPolicyItemAccess("read", true)); - rangerPolicyItem.addAccess(new RangerPolicyItemAccess("write", true)); - rangerPolicyItem.addGroup("group1"); - rangerPolicyItem.addGroup("group2"); - rangerPolicyItem.addUser("user1"); - rangerPolicyItem.addUser("user2"); - rangerPolicyItem.setDelegateAdmin(true); - - existingPolicy.addPolicyItem(rangerPolicyItem); - - rangerPolicyItem = new RangerPolicyItem(); - rangerPolicyItem.addAccess(new RangerPolicyItemAccess("delete", true)); - rangerPolicyItem.addGroup("group1"); - rangerPolicyItem.addGroup("public"); - rangerPolicyItem.addUser("user1"); - rangerPolicyItem.addUser("finance"); - rangerPolicyItem.setDelegateAdmin(false); - - appliedPolicy.addPolicyItem(rangerPolicyItem); - - String existingPolicyStr = existingPolicy.toString(); - System.out.println("existingPolicy=" + existingPolicyStr); - - ServiceRESTUtil.processApplyPolicy(existingPolicy, appliedPolicy); - - String resultPolicyStr = existingPolicy.toString(); - System.out.println("resultPolicy=" + resultPolicyStr); - - assert(true); - } - - @Test - public void test41applyPolicy() { - RangerPolicy existingPolicy = rangerPolicy(); - RangerPolicy appliedPolicy = rangerPolicy(); - - List policyItem = new ArrayList(); - existingPolicy.setPolicyItems(policyItem); - appliedPolicy.setPolicyItems(null); - - Map policyResources = new HashMap(); - RangerPolicyResource rangerPolicyResource = new RangerPolicyResource("/tmp"); - rangerPolicyResource.setIsExcludes(true); - rangerPolicyResource.setIsRecursive(true); - policyResources.put("path", rangerPolicyResource); - - existingPolicy.setResources(policyResources); - appliedPolicy.setResources(policyResources); - - RangerPolicyItem rangerPolicyItem = new RangerPolicyItem(); - rangerPolicyItem.addAccess(new RangerPolicyItemAccess("read", true)); - rangerPolicyItem.addAccess(new RangerPolicyItemAccess("write", true)); - rangerPolicyItem.addAccess(new RangerPolicyItemAccess("delete", true)); - rangerPolicyItem.addAccess(new RangerPolicyItemAccess("lock", true)); - rangerPolicyItem.addGroup("group1"); - rangerPolicyItem.addGroup("group2"); - rangerPolicyItem.addUser("user1"); - rangerPolicyItem.addUser("user2"); - rangerPolicyItem.setDelegateAdmin(true); - - rangerPolicyItem = new RangerPolicyItem(); - rangerPolicyItem.addAccess(new RangerPolicyItemAccess("read", true)); - rangerPolicyItem.addAccess(new RangerPolicyItemAccess("write", true)); - rangerPolicyItem.addAccess(new RangerPolicyItemAccess("delete", true)); - rangerPolicyItem.addAccess(new RangerPolicyItemAccess("lock", true)); - rangerPolicyItem.addGroup("group3"); - rangerPolicyItem.addUser("user3"); - rangerPolicyItem.setDelegateAdmin(true); - - existingPolicy.addPolicyItem(rangerPolicyItem); - - rangerPolicyItem = new RangerPolicyItem(); - rangerPolicyItem.addAccess(new RangerPolicyItemAccess("delete", true)); - rangerPolicyItem.addAccess(new RangerPolicyItemAccess("lock", true)); - rangerPolicyItem.addGroup("group1"); - rangerPolicyItem.addGroup("group2"); - rangerPolicyItem.addUser("user1"); - rangerPolicyItem.addUser("user2"); - rangerPolicyItem.setDelegateAdmin(false); - - existingPolicy.addAllowException(rangerPolicyItem); - - rangerPolicyItem = new RangerPolicyItem(); - rangerPolicyItem.addAccess(new RangerPolicyItemAccess("delete", true)); - rangerPolicyItem.addGroup("group2"); - rangerPolicyItem.addUser("user2"); - rangerPolicyItem.setDelegateAdmin(false); - - existingPolicy.addDenyPolicyItem(rangerPolicyItem); - - rangerPolicyItem = new RangerPolicyItem(); - rangerPolicyItem.addAccess(new RangerPolicyItemAccess("index", true)); - rangerPolicyItem.addGroup("public"); - rangerPolicyItem.addUser("user"); - rangerPolicyItem.setDelegateAdmin(false); - - existingPolicy.addDenyPolicyItem(rangerPolicyItem); - - rangerPolicyItem = new RangerPolicyItem(); - rangerPolicyItem.addAccess(new RangerPolicyItemAccess("delete", true)); - rangerPolicyItem.addAccess(new RangerPolicyItemAccess("index", true)); - - rangerPolicyItem.addGroup("group1"); - rangerPolicyItem.addUser("user1"); - rangerPolicyItem.setDelegateAdmin(false); - - appliedPolicy.addPolicyItem(rangerPolicyItem); - - rangerPolicyItem = new RangerPolicyItem(); - rangerPolicyItem.addAccess(new RangerPolicyItemAccess("delete", true)); - - rangerPolicyItem.addGroup("public"); - rangerPolicyItem.addUser("user1"); - rangerPolicyItem.setDelegateAdmin(false); - - appliedPolicy.addDenyPolicyItem(rangerPolicyItem); + grantRequestObj.setDelegateAdmin(true); - String existingPolicyStr = existingPolicy.toString(); - System.out.println("existingPolicy=" + existingPolicyStr); + grantRequestObj.setEnableAudit(true); + grantRequestObj.setIsRecursive(true); - ServiceRESTUtil.processApplyPolicy(existingPolicy, appliedPolicy); + grantRequestObj.setGrantor("test42Grant"); - String resultPolicyStr = existingPolicy.toString(); - System.out.println("resultPolicy=" + resultPolicyStr); - - assert(true); - } - - @Test - public void test42grant() { - RangerPolicy existingPolicy = rangerPolicy(); - List policyItem = new ArrayList(); - existingPolicy.setPolicyItems(policyItem ); - - Map policyResources = new HashMap(); - RangerPolicyResource rangerPolicyResource = new RangerPolicyResource("/tmp"); - rangerPolicyResource.setIsExcludes(true); - rangerPolicyResource.setIsRecursive(true); - policyResources.put("path", rangerPolicyResource); - - existingPolicy.setResources(policyResources); - - RangerPolicyItem rangerPolicyItem = new RangerPolicyItem(); - rangerPolicyItem.addAccess(new RangerPolicyItemAccess("read", true)); - rangerPolicyItem.addAccess(new RangerPolicyItemAccess("write", true)); - rangerPolicyItem.addAccess(new RangerPolicyItemAccess("delete", true)); - rangerPolicyItem.addAccess(new RangerPolicyItemAccess("lock", true)); - rangerPolicyItem.addGroup("group1"); - rangerPolicyItem.addGroup("group2"); - rangerPolicyItem.addUser("user1"); - rangerPolicyItem.addUser("user2"); - rangerPolicyItem.setDelegateAdmin(true); - - existingPolicy.addPolicyItem(rangerPolicyItem); - - rangerPolicyItem = new RangerPolicyItem(); - rangerPolicyItem.addAccess(new RangerPolicyItemAccess("read", true)); - rangerPolicyItem.addAccess(new RangerPolicyItemAccess("write", true)); - rangerPolicyItem.addAccess(new RangerPolicyItemAccess("delete", true)); - rangerPolicyItem.addAccess(new RangerPolicyItemAccess("lock", true)); - rangerPolicyItem.addGroup("group3"); - rangerPolicyItem.addUser("user3"); - rangerPolicyItem.setDelegateAdmin(true); - - existingPolicy.addPolicyItem(rangerPolicyItem); - - rangerPolicyItem = new RangerPolicyItem(); - rangerPolicyItem.addAccess(new RangerPolicyItemAccess("delete", true)); - rangerPolicyItem.addAccess(new RangerPolicyItemAccess("lock", true)); - rangerPolicyItem.addGroup("group1"); - rangerPolicyItem.addGroup("group2"); - rangerPolicyItem.addUser("user1"); - rangerPolicyItem.addUser("user2"); - rangerPolicyItem.setDelegateAdmin(false); - - existingPolicy.addAllowException(rangerPolicyItem); - - rangerPolicyItem = new RangerPolicyItem(); - rangerPolicyItem.addAccess(new RangerPolicyItemAccess("delete", true)); - rangerPolicyItem.addGroup("group2"); - rangerPolicyItem.addUser("user2"); - rangerPolicyItem.setDelegateAdmin(false); - - existingPolicy.addDenyPolicyItem(rangerPolicyItem); - - rangerPolicyItem = new RangerPolicyItem(); - rangerPolicyItem.addAccess(new RangerPolicyItemAccess("index", true)); - rangerPolicyItem.addGroup("public"); - rangerPolicyItem.addUser("user"); - rangerPolicyItem.setDelegateAdmin(false); - - existingPolicy.addDenyPolicyItem(rangerPolicyItem); + String existingPolicyStr = existingPolicy.toString(); + System.out.println("existingPolicy = " + existingPolicyStr); - GrantRevokeRequest grantRequestObj = new GrantRevokeRequest(); - Map resource = new HashMap(); - resource.put("path", "/tmp"); - grantRequestObj.setResource(resource); + ServiceRESTUtil.processGrantRequest(existingPolicy, grantRequestObj); - grantRequestObj.getUsers().add("user1"); - grantRequestObj.getGroups().add("group1"); + String resultPolicyStr = existingPolicy.toString(); + System.out.println("resultPolicy = " + resultPolicyStr); - grantRequestObj.getAccessTypes().add("delete"); - grantRequestObj.getAccessTypes().add("index"); + Assert.assertTrue(true); + } - grantRequestObj.setDelegateAdmin(true); + @Test + public void test43revoke() { + RangerPolicy existingPolicy = rangerPolicy(); + + List policyItem = new ArrayList<>(); + existingPolicy.setPolicyItems(policyItem); + + Map policyResources = new HashMap<>(); + RangerPolicyResource rangerPolicyResource = new RangerPolicyResource("/tmp"); + rangerPolicyResource.setIsExcludes(true); + rangerPolicyResource.setIsRecursive(true); + policyResources.put("path", rangerPolicyResource); + + existingPolicy.setResources(policyResources); + + RangerPolicyItem rangerPolicyItem = new RangerPolicyItem(); + rangerPolicyItem.addAccess(new RangerPolicyItemAccess("read", true)); + rangerPolicyItem.addAccess(new RangerPolicyItemAccess("write", true)); + rangerPolicyItem.addAccess(new RangerPolicyItemAccess("delete", true)); + rangerPolicyItem.addAccess(new RangerPolicyItemAccess("lock", true)); + rangerPolicyItem.addGroup("group1"); + rangerPolicyItem.addGroup("group2"); + rangerPolicyItem.addUser("user1"); + rangerPolicyItem.addUser("user2"); + rangerPolicyItem.setDelegateAdmin(true); + + existingPolicy.addPolicyItem(rangerPolicyItem); + + rangerPolicyItem = new RangerPolicyItem(); + rangerPolicyItem.addAccess(new RangerPolicyItemAccess("read", true)); + rangerPolicyItem.addAccess(new RangerPolicyItemAccess("write", true)); + rangerPolicyItem.addAccess(new RangerPolicyItemAccess("delete", true)); + rangerPolicyItem.addAccess(new RangerPolicyItemAccess("lock", true)); + rangerPolicyItem.addGroup("group3"); + rangerPolicyItem.addUser("user3"); + rangerPolicyItem.setDelegateAdmin(true); + + existingPolicy.addPolicyItem(rangerPolicyItem); + + rangerPolicyItem = new RangerPolicyItem(); + rangerPolicyItem.addAccess(new RangerPolicyItemAccess("delete", true)); + rangerPolicyItem.addAccess(new RangerPolicyItemAccess("lock", true)); + rangerPolicyItem.addGroup("group1"); + rangerPolicyItem.addGroup("group2"); + rangerPolicyItem.addUser("user1"); + rangerPolicyItem.addUser("user2"); + rangerPolicyItem.setDelegateAdmin(false); - grantRequestObj.setEnableAudit(true); - grantRequestObj.setIsRecursive(true); + existingPolicy.addAllowException(rangerPolicyItem); - grantRequestObj.setGrantor("test42Grant"); + rangerPolicyItem = new RangerPolicyItem(); + rangerPolicyItem.addAccess(new RangerPolicyItemAccess("delete", true)); + rangerPolicyItem.addGroup("group2"); + rangerPolicyItem.addUser("user2"); + rangerPolicyItem.setDelegateAdmin(false); - String existingPolicyStr = existingPolicy.toString(); - System.out.println("existingPolicy=" + existingPolicyStr); + existingPolicy.addDenyPolicyItem(rangerPolicyItem); - ServiceRESTUtil.processGrantRequest(existingPolicy, grantRequestObj); + rangerPolicyItem = new RangerPolicyItem(); + rangerPolicyItem.addAccess(new RangerPolicyItemAccess("index", true)); + rangerPolicyItem.addGroup("public"); + rangerPolicyItem.addUser("user"); + rangerPolicyItem.setDelegateAdmin(false); + + existingPolicy.addDenyPolicyItem(rangerPolicyItem); + + GrantRevokeRequest revokeRequestObj = new GrantRevokeRequest(); + Map resource = new HashMap<>(); + resource.put("path", "/tmp"); + revokeRequestObj.setResource(resource); - String resultPolicyStr = existingPolicy.toString(); - System.out.println("resultPolicy=" + resultPolicyStr); + revokeRequestObj.getUsers().add("user1"); + revokeRequestObj.getGroups().add("group1"); + + revokeRequestObj.getAccessTypes().add("delete"); + revokeRequestObj.getAccessTypes().add("index"); + + revokeRequestObj.setDelegateAdmin(true); - assert(true); - } - - @Test - public void test43revoke() { - RangerPolicy existingPolicy = rangerPolicy(); - - List policyItem = new ArrayList(); - existingPolicy.setPolicyItems(policyItem ); - - Map policyResources = new HashMap(); - RangerPolicyResource rangerPolicyResource = new RangerPolicyResource("/tmp"); - rangerPolicyResource.setIsExcludes(true); - rangerPolicyResource.setIsRecursive(true); - policyResources.put("path", rangerPolicyResource); - - existingPolicy.setResources(policyResources); - - RangerPolicyItem rangerPolicyItem = new RangerPolicyItem(); - rangerPolicyItem.addAccess(new RangerPolicyItemAccess("read", true)); - rangerPolicyItem.addAccess(new RangerPolicyItemAccess("write", true)); - rangerPolicyItem.addAccess(new RangerPolicyItemAccess("delete", true)); - rangerPolicyItem.addAccess(new RangerPolicyItemAccess("lock", true)); - rangerPolicyItem.addGroup("group1"); - rangerPolicyItem.addGroup("group2"); - rangerPolicyItem.addUser("user1"); - rangerPolicyItem.addUser("user2"); - rangerPolicyItem.setDelegateAdmin(true); - - existingPolicy.addPolicyItem(rangerPolicyItem); - - rangerPolicyItem = new RangerPolicyItem(); - rangerPolicyItem.addAccess(new RangerPolicyItemAccess("read", true)); - rangerPolicyItem.addAccess(new RangerPolicyItemAccess("write", true)); - rangerPolicyItem.addAccess(new RangerPolicyItemAccess("delete", true)); - rangerPolicyItem.addAccess(new RangerPolicyItemAccess("lock", true)); - rangerPolicyItem.addGroup("group3"); - rangerPolicyItem.addUser("user3"); - rangerPolicyItem.setDelegateAdmin(true); - - existingPolicy.addPolicyItem(rangerPolicyItem); - - rangerPolicyItem = new RangerPolicyItem(); - rangerPolicyItem.addAccess(new RangerPolicyItemAccess("delete", true)); - rangerPolicyItem.addAccess(new RangerPolicyItemAccess("lock", true)); - rangerPolicyItem.addGroup("group1"); - rangerPolicyItem.addGroup("group2"); - rangerPolicyItem.addUser("user1"); - rangerPolicyItem.addUser("user2"); - rangerPolicyItem.setDelegateAdmin(false); - - existingPolicy.addAllowException(rangerPolicyItem); - - rangerPolicyItem = new RangerPolicyItem(); - rangerPolicyItem.addAccess(new RangerPolicyItemAccess("delete", true)); - rangerPolicyItem.addGroup("group2"); - rangerPolicyItem.addUser("user2"); - rangerPolicyItem.setDelegateAdmin(false); - - existingPolicy.addDenyPolicyItem(rangerPolicyItem); - - rangerPolicyItem = new RangerPolicyItem(); - rangerPolicyItem.addAccess(new RangerPolicyItemAccess("index", true)); - rangerPolicyItem.addGroup("public"); - rangerPolicyItem.addUser("user"); - rangerPolicyItem.setDelegateAdmin(false); - - existingPolicy.addDenyPolicyItem(rangerPolicyItem); - - GrantRevokeRequest revokeRequestObj = new GrantRevokeRequest(); - Map resource = new HashMap(); - resource.put("path", "/tmp"); - revokeRequestObj.setResource(resource); - - revokeRequestObj.getUsers().add("user1"); - revokeRequestObj.getGroups().add("group1"); - - revokeRequestObj.getAccessTypes().add("delete"); - revokeRequestObj.getAccessTypes().add("index"); - - revokeRequestObj.setDelegateAdmin(true); - - revokeRequestObj.setEnableAudit(true); - revokeRequestObj.setIsRecursive(true); - - revokeRequestObj.setGrantor("test43Revoke"); - - String existingPolicyStr = existingPolicy.toString(); - System.out.println("existingPolicy=" + existingPolicyStr); - - ServiceRESTUtil.processRevokeRequest(existingPolicy, revokeRequestObj); - - String resultPolicyStr = existingPolicy.toString(); - System.out.println("resultPolicy=" + resultPolicyStr); - - assert(true); - } - - @Test - public void test44getPolicyLabels() throws Exception { - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - SearchFilter filter = new SearchFilter(); - Mockito.when(searchUtil.getSearchFilter(request, policyLabelsService.sortFields)).thenReturn(filter); - List ret = new ArrayList(); - Mockito.when(svcStore.getPolicyLabels(filter)).thenReturn(ret); - ret = serviceREST.getPolicyLabels(request); - Assert.assertNotNull(ret); - Mockito.verify(searchUtil).getSearchFilter(request, policyLabelsService.sortFields); - } - - @Test - public void test45exportPoliciesInJSON() throws Exception { - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - - List rangerPolicyList = new ArrayList(); - - RangerPolicy rangerPolicy = rangerPolicy(); - rangerPolicyList.add(rangerPolicy); - XXService xService = xService(); - - XXServiceDao xServiceDao = Mockito.mock(XXServiceDao.class); - XXServiceDef xServiceDef = serviceDef(); - XXServiceDefDao xServiceDefDao = Mockito.mock(XXServiceDefDao.class); - - request.setAttribute("serviceType", "hdfs,hbase,hive,yarn,knox,storm,solr,kafka,nifi,atlas,sqoop"); - HttpServletResponse response = Mockito.mock(HttpServletResponse.class); - SearchFilter filter = new SearchFilter(); - filter.setParam("zoneName", "zone1"); - Mockito.when(searchUtil.getSearchFilter(request, policyService.sortFields)).thenReturn(filter); - Mockito.when(svcStore.getPolicies(filter)).thenReturn(rangerPolicyList); - Mockito.when(bizUtil.isAdmin()).thenReturn(true); - Mockito.when(bizUtil.isKeyAdmin()).thenReturn(false); - Mockito.when(bizUtil.getCurrentUserLoginId()).thenReturn("admin"); - Mockito.when(bizUtil.isAuditAdmin()).thenReturn(false); - Mockito.when(bizUtil.isAuditKeyAdmin()).thenReturn(false); - Mockito.when(daoManager.getXXService()).thenReturn(xServiceDao); - - Mockito.when(daoManager.getXXServiceDef()).thenReturn(xServiceDefDao); - Mockito.when(daoManager.getXXService().findByName("HDFS_1-1-20150316062453")).thenReturn(xService); - Mockito.when(daoManager.getXXServiceDef().getById(xService.getType())).thenReturn(xServiceDef); - serviceREST.getPoliciesInJson(request, response, false); - - Mockito.verify(svcStore).getObjectInJson(rangerPolicyList, response, JSON_FILE_NAME_TYPE.POLICY); - } - - @Test - public void test46exportPoliciesInCSV() throws Exception { - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - - List rangerPolicyList = new ArrayList(); - - RangerPolicy rangerPolicy = rangerPolicy(); - rangerPolicyList.add(rangerPolicy); - XXService xService = xService(); - - XXServiceDao xServiceDao = Mockito.mock(XXServiceDao.class); - XXServiceDef xServiceDef = serviceDef(); - XXServiceDefDao xServiceDefDao = Mockito.mock(XXServiceDefDao.class); - - request.setAttribute("serviceType", "hdfs,hbase,hive,yarn,knox,storm,solr,kafka,nifi,atlas,sqoop"); - HttpServletResponse response = Mockito.mock(HttpServletResponse.class); - SearchFilter filter = new SearchFilter(); - - Mockito.when(searchUtil.getSearchFilter(request, policyService.sortFields)).thenReturn(filter); - Mockito.when(svcStore.getPolicies(filter)).thenReturn(rangerPolicyList); - Mockito.when(bizUtil.isAdmin()).thenReturn(true); - Mockito.when(bizUtil.isKeyAdmin()).thenReturn(false); - Mockito.when(bizUtil.getCurrentUserLoginId()).thenReturn("admin"); - Mockito.when(bizUtil.isAuditAdmin()).thenReturn(false); - Mockito.when(bizUtil.isAuditKeyAdmin()).thenReturn(false); - Mockito.when(daoManager.getXXService()).thenReturn(xServiceDao); - - Mockito.when(daoManager.getXXServiceDef()).thenReturn(xServiceDefDao); - - Mockito.when(daoManager.getXXService().findByName("HDFS_1-1-20150316062453")).thenReturn(xService); - Mockito.when(daoManager.getXXServiceDef().getById(xService.getType())).thenReturn(xServiceDef); - serviceREST.getPoliciesInCsv(request, response); - - Mockito.verify(svcStore).getPoliciesInCSV(rangerPolicyList, response); - } - - /* @Test - public void test47WhenPolicyListIsEmpty() throws Exception { - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - - List rangerPolicyList = new ArrayList(); - request.setAttribute("serviceType", "hdfs,hbase,hive,yarn,knox,storm,solr,kafka,nifi,atlas,sqoop"); - HttpServletResponse response = Mockito.mock(HttpServletResponse.class); - SearchFilter filter = new SearchFilter(); - - Mockito.when(searchUtil.getSearchFilter(request, policyService.sortFields)).thenReturn(filter); - Mockito.when(svcStore.getPolicies(filter)).thenReturn(rangerPolicyList); - - Mockito.when(((Object) response).getStatus()).thenReturn(204); - serviceREST.getPoliciesInCsv(request, response); - - Assert.assertEquals(HttpServletResponse.SC_NO_CONTENT, response.getStatus()); - } -*/ - @Test - public void test48exportPoliciesInExcel() throws Exception { - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - - List rangerPolicyList = new ArrayList(); - - RangerPolicy rangerPolicy = rangerPolicy(); - rangerPolicyList.add(rangerPolicy); - XXService xService = xService(); - - XXServiceDao xServiceDao = Mockito.mock(XXServiceDao.class); - XXServiceDef xServiceDef = serviceDef(); - XXServiceDefDao xServiceDefDao = Mockito.mock(XXServiceDefDao.class); - - request.setAttribute("serviceType", "hdfs,hbase,hive,yarn,knox,storm,solr,kafka,nifi,atlas,sqoop"); - HttpServletResponse response = Mockito.mock(HttpServletResponse.class); - SearchFilter filter = new SearchFilter(); - - Mockito.when(searchUtil.getSearchFilter(request, policyService.sortFields)).thenReturn(filter); - Mockito.when(svcStore.getPolicies(filter)).thenReturn(rangerPolicyList); - Mockito.when(bizUtil.isAdmin()).thenReturn(true); - Mockito.when(bizUtil.isKeyAdmin()).thenReturn(false); - Mockito.when(bizUtil.getCurrentUserLoginId()).thenReturn("admin"); - Mockito.when(bizUtil.isAuditAdmin()).thenReturn(false); - Mockito.when(bizUtil.isAuditKeyAdmin()).thenReturn(false); - Mockito.when(daoManager.getXXService()).thenReturn(xServiceDao); - - Mockito.when(daoManager.getXXServiceDef()).thenReturn(xServiceDefDao); - - Mockito.when(daoManager.getXXService().findByName("HDFS_1-1-20150316062453")).thenReturn(xService); - Mockito.when(daoManager.getXXServiceDef().getById(xService.getType())).thenReturn(xServiceDef); - serviceREST.getPoliciesInExcel(request, response); - Mockito.verify(svcStore).getPoliciesInExcel(rangerPolicyList, response); - } - - - @SuppressWarnings("unchecked") - @Test - public void test49importPoliciesFromFileAllowingOverride() throws Exception { - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - RangerPolicyValidator policyValidator = Mockito.mock(RangerPolicyValidator.class) ; - Map policiesMap = new LinkedHashMap(); - RangerPolicy rangerPolicy = rangerPolicy(); - RangerService service = rangerService(); - XXService xService = xService(); - policiesMap.put("Name", rangerPolicy); - XXServiceDao xServiceDao = Mockito.mock(XXServiceDao.class); - XXServiceDef xServiceDef = serviceDef(); - XXServiceDefDao xServiceDefDao = Mockito.mock(XXServiceDefDao.class); - XXSecurityZoneRefServiceDao xSecZoneRefServiceDao = Mockito.mock(XXSecurityZoneRefServiceDao.class); - XXSecurityZoneRefTagServiceDao xSecZoneRefTagServiceDao = Mockito.mock(XXSecurityZoneRefTagServiceDao.class); - XXSecurityZoneRefService xSecZoneRefService = Mockito.mock(XXSecurityZoneRefService.class); - XXSecurityZoneRefTagService xSecZoneRefTagService = Mockito.mock(XXSecurityZoneRefTagService.class); - XXSecurityZoneDao xSecZoneDao = Mockito.mock(XXSecurityZoneDao.class); - XXSecurityZone xSecZone = Mockito.mock(XXSecurityZone.class); - List zoneServiceList = new ArrayList<>(); - List zoneTagServiceList = new ArrayList<>(); - zoneServiceList.add(xSecZoneRefService); - zoneTagServiceList.add(xSecZoneRefTagService); - Map zoneMappingMap = new LinkedHashMap(); - zoneMappingMap.put("ZoneSource", "ZoneDestination"); - - String PARAM_SERVICE_TYPE = "serviceType"; - String serviceTypeList = "hdfs,hbase,hive,yarn,knox,storm,solr,kafka,nifi,atlas,sqoop"; - request.setAttribute("serviceType", "hdfs,hbase,hive,yarn,knox,storm,solr,kafka,nifi,atlas,sqoop"); - SearchFilter filter = new SearchFilter(); - filter.setParam("serviceType", "value"); - - File jsonPolicyFile = getFile(importPoliceTestFilePath); - InputStream uploadedInputStream = new FileInputStream(jsonPolicyFile); - FormDataContentDisposition fileDetail = FormDataContentDisposition.name("file") - .fileName(jsonPolicyFile.getName()).size(uploadedInputStream.toString().length()).build(); - boolean isOverride = true; - - InputStream zoneInputStream =IOUtils.toInputStream("ZoneSource=ZoneDestination", "UTF-8"); - - Mockito.when(searchUtil.getSearchFilter(request, policyService.sortFields)).thenReturn(filter); - Mockito.when(request.getParameter(PARAM_SERVICE_TYPE)).thenReturn(serviceTypeList); - Mockito.when(svcStore.createPolicyMap(Mockito.any(Map.class), Mockito.any(List.class),Mockito.anyString(),Mockito.any(Map.class), Mockito.any(List.class), Mockito.any(List.class), - Mockito.any(RangerPolicy.class), Mockito.any(Map.class))).thenReturn(policiesMap); - Mockito.when(validatorFactory.getPolicyValidator(svcStore)).thenReturn(policyValidator); - Mockito.when(bizUtil.isAdmin()).thenReturn(true); - Mockito.when(daoManager.getXXService()).thenReturn(xServiceDao); - - Mockito.when(daoManager.getXXServiceDef()).thenReturn(xServiceDefDao); - - Mockito.when(daoManager.getXXService().findByName("HDFS_1-1-20150316062453")).thenReturn(xService); - Mockito.when(daoManager.getXXServiceDef().getById(xService.getType())).thenReturn(xServiceDef); - Mockito.when(validatorFactory.getPolicyValidator(svcStore)).thenReturn(policyValidator); - Mockito.when(svcStore.getMapFromInputStream(zoneInputStream)).thenReturn(zoneMappingMap); - Mockito.when(daoManager.getXXSecurityZoneDao()).thenReturn(xSecZoneDao); - Mockito.when(xSecZoneDao.findByZoneName(Mockito.anyString())).thenReturn(xSecZone); - Mockito.when(daoManager.getXXSecurityZoneRefService()).thenReturn(xSecZoneRefServiceDao); - Mockito.when(xSecZoneRefServiceDao.findByServiceNameAndZoneId(Mockito.anyString(),Mockito.anyLong())).thenReturn(zoneServiceList); - Mockito.when(daoManager.getXXSecurityZoneRefTagService()).thenReturn(xSecZoneRefTagServiceDao); - Mockito.when(xSecZoneRefTagServiceDao.findByTagServiceNameAndZoneId(Mockito.anyString(),Mockito.anyLong())).thenReturn(zoneTagServiceList); - Mockito.when(svcStore.getServiceByName(Mockito.anyString())).thenReturn(service); - serviceREST.importPoliciesFromFile(request, null, zoneInputStream, uploadedInputStream, fileDetail, isOverride , "unzoneToZone"); - - Mockito.verify(svcStore).createPolicy(rangerPolicy); - - } - - @SuppressWarnings("unchecked") - @Test - public void test50importPoliciesFromFileNotAllowingOverride() throws Exception { - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - Map policiesMap = new LinkedHashMap(); - RangerPolicy rangerPolicy = rangerPolicy(); - XXService xService = xService(); - policiesMap.put("Name", rangerPolicy); - XXServiceDao xServiceDao = Mockito.mock(XXServiceDao.class); - XXServiceDef xServiceDef = serviceDef(); - XXServiceDefDao xServiceDefDao = Mockito.mock(XXServiceDefDao.class); - XXSecurityZoneRefServiceDao xSecZoneRefServiceDao = Mockito.mock(XXSecurityZoneRefServiceDao.class); - XXSecurityZoneRefTagServiceDao xSecZoneRefTagServiceDao = Mockito.mock(XXSecurityZoneRefTagServiceDao.class); - XXSecurityZoneRefService xSecZoneRefService = Mockito.mock(XXSecurityZoneRefService.class); - XXSecurityZoneRefTagService xSecZoneRefTagService = Mockito.mock(XXSecurityZoneRefTagService.class); - XXSecurityZoneDao xSecZoneDao = Mockito.mock(XXSecurityZoneDao.class); - XXSecurityZone xSecZone = Mockito.mock(XXSecurityZone.class); - List zoneServiceList = new ArrayList<>(); - List zoneTagServiceList = new ArrayList<>(); - zoneServiceList.add(xSecZoneRefService); - zoneTagServiceList.add(xSecZoneRefTagService); - Map zoneMappingMap = new LinkedHashMap(); - zoneMappingMap.put("ZoneSource", "ZoneDestination"); - - String PARAM_SERVICE_TYPE = "serviceType"; - String serviceTypeList = "hdfs,hbase,hive,yarn,knox,storm,solr,kafka,nifi,atlas,sqoop"; - request.setAttribute("serviceType", "hdfs,hbase,hive,yarn,knox,storm,solr,kafka,nifi,atlas,sqoop"); - SearchFilter filter = new SearchFilter(); - filter.setParam("serviceType", "value"); - - File jsonPolicyFile = getFile(importPoliceTestFilePath); - InputStream uploadedInputStream = new FileInputStream(jsonPolicyFile); - FormDataContentDisposition fileDetail = FormDataContentDisposition.name("file") - .fileName(jsonPolicyFile.getName()).size(uploadedInputStream.toString().length()).build(); - boolean isOverride = false; - - InputStream zoneInputStream = IOUtils.toInputStream("ZoneSource=ZoneDestination", "UTF-8"); - - Mockito.when(searchUtil.getSearchFilter(request, policyService.sortFields)).thenReturn(filter); - Mockito.when(request.getParameter(PARAM_SERVICE_TYPE)).thenReturn(serviceTypeList); - Mockito.when(svcStore.createPolicyMap(Mockito.any(Map.class), Mockito.any(List.class),Mockito.anyString(),Mockito.any(Map.class), Mockito.any(List.class), Mockito.any(List.class), - Mockito.any(RangerPolicy.class), Mockito.any(Map.class))).thenReturn(policiesMap); - Mockito.when(validatorFactory.getPolicyValidator(svcStore)).thenReturn(policyValidator); - Mockito.when(bizUtil.isAdmin()).thenReturn(true); - Mockito.when(daoManager.getXXService()).thenReturn(xServiceDao); - - Mockito.when(daoManager.getXXServiceDef()).thenReturn(xServiceDefDao); - - Mockito.when(daoManager.getXXService().findByName("HDFS_1-1-20150316062453")).thenReturn(xService); - Mockito.when(daoManager.getXXServiceDef().getById(xService.getType())).thenReturn(xServiceDef); - - Mockito.when(svcStore.getMapFromInputStream(zoneInputStream)).thenReturn(zoneMappingMap); - Mockito.when(daoManager.getXXSecurityZoneDao()).thenReturn(xSecZoneDao); - Mockito.when(xSecZoneDao.findByZoneName(Mockito.anyString())).thenReturn(xSecZone); - Mockito.when(daoManager.getXXSecurityZoneRefService()).thenReturn(xSecZoneRefServiceDao); - Mockito.when(xSecZoneRefServiceDao.findByServiceNameAndZoneId(Mockito.anyString(),Mockito.anyLong())).thenReturn(zoneServiceList); - Mockito.when(daoManager.getXXSecurityZoneRefTagService()).thenReturn(xSecZoneRefTagServiceDao); - Mockito.when(xSecZoneRefTagServiceDao.findByTagServiceNameAndZoneId(Mockito.anyString(),Mockito.anyLong())).thenReturn(zoneTagServiceList); - serviceREST.importPoliciesFromFile(request, null, zoneInputStream, uploadedInputStream, fileDetail, isOverride, "unzoneToUnZone"); - Mockito.verify(svcStore).createPolicy(rangerPolicy); - - } - - private File getFile(String testFilePath) throws IOException { - File jsonPolicyFile = new File(testFilePath); - if (jsonPolicyFile.getCanonicalPath().contains("/target/jstest")) { - jsonPolicyFile = new File(jsonPolicyFile.getCanonicalPath().replace("/target/jstest", "")); - } - return jsonPolicyFile; - } - - @Test - public void test51getMetricByType() throws Exception { - String type = "usergroup"; - String ret = "{\"groupCount\":1,\"userCountOfUserRole\":0,\"userCountOfKeyAdminRole\":1," - + "\"userCountOfSysAdminRole\":3,\"userCountOfKeyadminAuditorRole\":0,\"userCountOfSysAdminAuditorRole\":0,\"userTotalCount\":4}"; - ServiceDBStore.METRIC_TYPE metricType = ServiceDBStore.METRIC_TYPE.getMetricTypeByName(type); - Mockito.when(svcStore.getMetricByType(metricType)).thenReturn(ret); - serviceREST.getMetricByType(type); - Mockito.verify(svcStore).getMetricByType(metricType); - } - - @Test - public void test52deleteService() throws Exception { - - RangerService rangerService = rangerService(); - XXService xService = xService(); - List referringServices = new ArrayList(); - referringServices.add(xService); - EmbeddedServiceDefsUtil embeddedServiceDefsUtil = EmbeddedServiceDefsUtil.instance(); - xService.setType(embeddedServiceDefsUtil.getTagServiceDefId()); - XXServiceDao xServiceDao = Mockito.mock(XXServiceDao.class); - - String userLoginID = "testuser"; - Long userId = 8L; - RangerSecurityContext context = new RangerSecurityContext(); - context.setUserSession(new UserSessionBase()); - RangerContextHolder.setSecurityContext(context); - UserSessionBase session = ContextUtil.getCurrentUserSession(); - session.setUserAdmin(true); - XXPortalUser xXPortalUser = new XXPortalUser(); - xXPortalUser.setLoginId(userLoginID); - xXPortalUser.setId(userId); - session.setXXPortalUser(xXPortalUser); - - Mockito.when(validatorFactory.getServiceValidator(svcStore)).thenReturn(serviceValidator); - Mockito.when(daoManager.getXXService()).thenReturn(xServiceDao); - Mockito.when(xServiceDao.findByTagServiceId(Mockito.anyLong())).thenReturn(referringServices); - Mockito.when(xServiceDao.getById(Id)).thenReturn(xService); - Mockito.when(restErrorUtil.createRESTException(Mockito.anyString(), (MessageEnums) Mockito.any())) - .thenThrow(new WebApplicationException()); - thrown.expect(WebApplicationException.class); - serviceREST.deleteService(rangerService.getId()); - } - - @Test - public void test53getPoliciesForResource() throws Exception { - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - List rsList = new ArrayList(); - RangerService rs = rangerService(); - rsList.add(rs); - - Mockito.when(restErrorUtil.createRESTException(Mockito.anyString(), (MessageEnums) Mockito.any())) - .thenThrow(new WebApplicationException()); - thrown.expect(WebApplicationException.class); - - serviceREST.getPoliciesForResource("servicedefname", "servicename", request); - } - - @Test - public void test54getPluginsInfo() throws Exception { - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - SearchFilter filter = new SearchFilter(); - filter.setParam(SearchFilter.POLICY_NAME, "policyName"); - filter.setParam(SearchFilter.SERVICE_NAME, "serviceName"); - PList paginatedPluginsInfo = new PList(); - Mockito.when(searchUtil.getSearchFilter(request, pluginInfoService.getSortFields())).thenReturn(filter); - Mockito.when(pluginInfoService.searchRangerPluginInfo(filter)).thenReturn(paginatedPluginsInfo); - RangerPluginInfoList rPluginInfoList = serviceREST.getPluginsInfo(request); - Assert.assertNotNull(rPluginInfoList); - Mockito.verify(searchUtil).getSearchFilter(request, pluginInfoService.getSortFields()); - Mockito.verify(pluginInfoService).searchRangerPluginInfo(filter); - } - - @Test - public void test55getServicePoliciesIfUpdatedCatch() throws Exception { - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - String serviceName = "HDFS_1"; - Long lastKnownVersion = 1L; - String pluginId = "1"; - Mockito.when(serviceUtil.isValidateHttpsAuthentication(serviceName, request)).thenReturn(true); - Mockito.when(restErrorUtil.createRESTException(Mockito.anyInt(), Mockito.anyString(), Mockito.anyBoolean())) - .thenThrow(new WebApplicationException()); - thrown.expect(WebApplicationException.class); - serviceREST.getServicePoliciesIfUpdated(serviceName, lastKnownVersion, 0L, pluginId, "", "", false, capabilityVector, request); - } - - @Test - public void test56getServicePoliciesIfUpdated() throws Exception { - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - ServicePolicies servicePolicies = servicePolicies(); - String serviceName = "HDFS_1"; - Long lastKnownVersion = 1L; - String pluginId = "1"; - Mockito.when(serviceUtil.isValidateHttpsAuthentication(serviceName, request)).thenReturn(true); - Mockito.when(svcStore.getServicePoliciesIfUpdated(Mockito.anyString(), Mockito.anyLong(), Mockito.anyBoolean())).thenReturn(servicePolicies); - ServicePolicies dbServicePolicies = serviceREST.getServicePoliciesIfUpdated(serviceName, lastKnownVersion, 0L, - pluginId, "", "", true, capabilityVector, request); - Assert.assertNotNull(dbServicePolicies); - } - - @Test - public void test57getSecureServicePoliciesIfUpdatedFail() throws Exception { - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - Long lastKnownVersion = 1L; - String pluginId = "1"; - XXService xService = xService(); - XXServiceDef xServiceDef = serviceDef(); - String serviceName = xService.getName(); - RangerService rs = rangerService(); - XXServiceDefDao xServiceDefDao = Mockito.mock(XXServiceDefDao.class); - Mockito.when(serviceUtil.isValidService(serviceName, request)).thenReturn(true); - Mockito.when(daoManager.getXXService()).thenReturn(xServiceDao); - Mockito.when(xServiceDao.findByName(serviceName)).thenReturn(xService); - Mockito.when(daoManager.getXXServiceDef()).thenReturn(xServiceDefDao); - Mockito.when(xServiceDefDao.getById(xService.getType())).thenReturn(xServiceDef); - Mockito.when(svcStore.getServiceByName(serviceName)).thenReturn(rs); - Mockito.when(restErrorUtil.createRESTException(Mockito.anyInt(), Mockito.anyString(), Mockito.anyBoolean())) - .thenThrow(new WebApplicationException()); - thrown.expect(WebApplicationException.class); - - serviceREST.getSecureServicePoliciesIfUpdated(serviceName, lastKnownVersion, 0L, pluginId, "", "", false, capabilityVector, request); - } - - @Test - public void test58getSecureServicePoliciesIfUpdatedAllowedFail() throws Exception { - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - - Long lastKnownVersion = 1L; - String pluginId = "1"; - XXService xService = xService(); - XXServiceDef xServiceDef = serviceDef(); - xServiceDef.setImplclassname("org.apache.ranger.services.kms.RangerServiceKMS"); - String serviceName = xService.getName(); - RangerService rs = rangerService(); - XXServiceDefDao xServiceDefDao = Mockito.mock(XXServiceDefDao.class); - Mockito.when(serviceUtil.isValidService(serviceName, request)).thenReturn(true); - Mockito.when(daoManager.getXXService()).thenReturn(xServiceDao); - Mockito.when(xServiceDao.findByName(serviceName)).thenReturn(xService); - Mockito.when(daoManager.getXXServiceDef()).thenReturn(xServiceDefDao); - Mockito.when(xServiceDefDao.getById(xService.getType())).thenReturn(xServiceDef); - Mockito.when(svcStore.getServiceByNameForDP(serviceName)).thenReturn(rs); - Mockito.when(bizUtil.isUserAllowed(rs, ServiceREST.Allowed_User_List_For_Grant_Revoke)).thenReturn(true); - Mockito.when(restErrorUtil.createRESTException(Mockito.anyInt(), Mockito.anyString(), Mockito.anyBoolean())) - .thenThrow(new WebApplicationException()); - thrown.expect(WebApplicationException.class); - - serviceREST.getSecureServicePoliciesIfUpdated(serviceName, lastKnownVersion, 0L, pluginId, "", "", false, capabilityVector, request); - } - - @Test - public void test59getSecureServicePoliciesIfUpdatedSuccess() throws Exception { - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - - Long lastKnownVersion = 1L; - String pluginId = "1"; - XXService xService = xService(); - XXServiceDef xServiceDef = serviceDef(); - xServiceDef.setImplclassname("org.apache.ranger.services.kms.RangerServiceKMS"); - String serviceName = xService.getName(); - RangerService rs = rangerService(); - ServicePolicies sp = servicePolicies(); - XXServiceDefDao xServiceDefDao = Mockito.mock(XXServiceDefDao.class); - Mockito.when(serviceUtil.isValidService(serviceName, request)).thenReturn(true); - Mockito.when(daoManager.getXXService()).thenReturn(xServiceDao); - Mockito.when(xServiceDao.findByName(serviceName)).thenReturn(xService); - Mockito.when(daoManager.getXXServiceDef()).thenReturn(xServiceDefDao); - Mockito.when(xServiceDefDao.getById(xService.getType())).thenReturn(xServiceDef); - Mockito.when(svcStore.getServiceByNameForDP(serviceName)).thenReturn(rs); - Mockito.when(bizUtil.isUserAllowed(rs, ServiceREST.Allowed_User_List_For_Grant_Revoke)).thenReturn(true); - Mockito.when(svcStore.getServicePoliciesIfUpdated(Mockito.anyString(), Mockito.anyLong(), Mockito.anyBoolean())).thenReturn(sp); - ServicePolicies dbServiceSecurePolicies = serviceREST.getSecureServicePoliciesIfUpdated(serviceName, - lastKnownVersion, 0L, pluginId, "", "", true, capabilityVector, request); - Assert.assertNotNull(dbServiceSecurePolicies); - Mockito.verify(serviceUtil).isValidService(serviceName, request); - Mockito.verify(xServiceDao).findByName(serviceName); - Mockito.verify(xServiceDefDao).getById(xService.getType()); - Mockito.verify(svcStore).getServiceByNameForDP(serviceName); - Mockito.verify(bizUtil).isUserAllowed(rs, ServiceREST.Allowed_User_List_For_Grant_Revoke); - Mockito.verify(svcStore).getServicePoliciesIfUpdated(serviceName, lastKnownVersion, false); - } - - @Test - public void test60getPolicyFromEventTime() throws Exception { - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - - String strdt = new Date().toString(); - Set userGroupsList = new HashSet(); - userGroupsList.add("group1"); - userGroupsList.add("group2"); - Mockito.when(request.getParameter("eventTime")).thenReturn(strdt); - Mockito.when(request.getParameter("policyId")).thenReturn("1"); - Mockito.when(request.getParameter("versionNo")).thenReturn("1"); - RangerPolicy policy = new RangerPolicy(); - Map resources = new HashMap(); - policy.setService("services"); - policy.setResources(resources); - Mockito.when(svcStore.getPolicyFromEventTime(strdt, 1l)).thenReturn(null); - - Mockito.when(restErrorUtil.createRESTException(Mockito.anyInt(), Mockito.anyString(), Mockito.anyBoolean())) - .thenThrow(new WebApplicationException()); - thrown.expect(WebApplicationException.class); - - serviceREST.getPolicyFromEventTime(request); - } - - @Test - public void test61getServiceWillOnlyReturnNameIdAndTypeForRoleUser() throws Exception { - RangerService actualService = rangerService(); - - String userLoginID = "testuser"; - Long userId = 8L; - - RangerSecurityContext context = new RangerSecurityContext(); - context.setUserSession(new UserSessionBase()); - RangerContextHolder.setSecurityContext(context); - UserSessionBase currentUserSession = ContextUtil.getCurrentUserSession(); - currentUserSession.setUserAdmin(false); - XXPortalUser xXPortalUser = new XXPortalUser(); - xXPortalUser.setLoginId(userLoginID); - xXPortalUser.setId(userId); - currentUserSession.setXXPortalUser(xXPortalUser); - - VXUser loggedInUser = new VXUser(); - List loggedInUserRole = new ArrayList(); - loggedInUserRole.add(RangerConstants.ROLE_USER); - loggedInUser.setId(8L); - loggedInUser.setName("testuser"); - loggedInUser.setUserRoleList(loggedInUserRole); - Mockito.when(xUserService.getXUserByUserName("testuser")).thenReturn(loggedInUser); - Mockito.when(svcStore.getService(Id)).thenReturn(actualService); - - RangerService service = serviceREST.getService(Id); - Assert.assertNotNull(service); - Mockito.verify(svcStore).getService(Id); - Assert.assertNull(service.getDescription()); - Assert.assertTrue(service.getConfigs().isEmpty()); - Assert.assertEquals(service.getId(), Id); - Assert.assertEquals(service.getName(), "HDFS_1"); - Assert.assertEquals(service.getType(), "1"); - } - - @Test - public void test62getServiceByNameWillOnlyReturnNameIdAndTypeForRoleUser() throws Exception { - RangerService actualService = rangerService(); - - String userLoginID = "testuser"; - Long userId = 8L; - - RangerSecurityContext context = new RangerSecurityContext(); - context.setUserSession(new UserSessionBase()); - RangerContextHolder.setSecurityContext(context); - UserSessionBase currentUserSession = ContextUtil.getCurrentUserSession(); - currentUserSession.setUserAdmin(false); - XXPortalUser xXPortalUser = new XXPortalUser(); - xXPortalUser.setLoginId(userLoginID); - xXPortalUser.setId(userId); - currentUserSession.setXXPortalUser(xXPortalUser); - - VXUser loggedInUser = new VXUser(); - List loggedInUserRole = new ArrayList(); - loggedInUserRole.add(RangerConstants.ROLE_USER); - loggedInUser.setId(8L); - loggedInUser.setName("testuser"); - loggedInUser.setUserRoleList(loggedInUserRole); - Mockito.when(xUserService.getXUserByUserName("testuser")).thenReturn(loggedInUser); - Mockito.when(svcStore.getServiceByName(actualService.getName())).thenReturn(actualService); - - RangerService service = serviceREST.getServiceByName(actualService.getName()); - Assert.assertNotNull(service); - Mockito.verify(svcStore).getServiceByName(actualService.getName()); - Assert.assertNull(service.getDescription()); - Assert.assertTrue(service.getConfigs().isEmpty()); - Assert.assertEquals(service.getId(), Id); - Assert.assertEquals(service.getName(), "HDFS_1"); - Assert.assertEquals(service.getType(), "1"); - } - - @Test - public void test63getServices() throws Exception{ - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - PList paginatedSvcs = new PList(); - RangerService svc1 = rangerService(); - - String userLoginID = "testuser"; - Long userId = 8L; - - RangerSecurityContext context = new RangerSecurityContext(); - context.setUserSession(new UserSessionBase()); - RangerContextHolder.setSecurityContext(context); - UserSessionBase currentUserSession = ContextUtil.getCurrentUserSession(); - currentUserSession.setUserAdmin(false); - XXPortalUser xXPortalUser = new XXPortalUser(); - xXPortalUser.setLoginId(userLoginID); - xXPortalUser.setId(userId); - currentUserSession.setXXPortalUser(xXPortalUser); - - VXUser loggedInUser = new VXUser(); - List loggedInUserRole = new ArrayList(); - loggedInUserRole.add(RangerConstants.ROLE_USER); - loggedInUser.setId(8L); - loggedInUser.setName("testuser"); - loggedInUser.setUserRoleList(loggedInUserRole); - - Map configs = new HashMap(); - configs.put("username", "servicemgr"); - configs.put("password", "servicemgr"); - configs.put("namenode", "servicemgr"); - configs.put("hadoop.security.authorization", "No"); - configs.put("hadoop.security.authentication", "Simple"); - configs.put("hadoop.security.auth_to_local", ""); - configs.put("dfs.datanode.kerberos.principal", ""); - configs.put("dfs.namenode.kerberos.principal", ""); - configs.put("dfs.secondary.namenode.kerberos.principal", ""); - configs.put("hadoop.rpc.protection", "Privacy"); - configs.put("commonNameForCertificate", ""); - - RangerService svc2 = new RangerService(); - svc2.setId(9L); - svc2.setConfigs(configs); - svc2.setCreateTime(new Date()); - svc2.setDescription("service policy"); - svc2.setGuid("1427365526516_835_1"); - svc2.setIsEnabled(true); - svc2.setName("YARN_1"); - svc2.setPolicyUpdateTime(new Date()); - svc2.setType("yarn"); - svc2.setUpdatedBy("Admin"); - svc2.setUpdateTime(new Date()); - - List rangerServiceList = new ArrayList(); - rangerServiceList.add(svc1); - rangerServiceList.add(svc2); - - paginatedSvcs.setList(rangerServiceList); - - SearchFilter filter = new SearchFilter(); - Mockito.when(searchUtil.getSearchFilter(request, svcService.sortFields)).thenReturn(filter); - Mockito.when(svcStore.getPaginatedServices(filter)).thenReturn(paginatedSvcs); - Mockito.when(xUserService.getXUserByUserName("testuser")).thenReturn(loggedInUser); - RangerServiceList retServiceList = serviceREST.getServices(request); - Assert.assertNotNull(retServiceList); - Assert.assertNull(retServiceList.getServices().get(0).getDescription()); - Assert.assertTrue(retServiceList.getServices().get(0).getConfigs().isEmpty()); - Assert.assertNull(retServiceList.getServices().get(1).getDescription()); - Assert.assertTrue(retServiceList.getServices().get(1).getConfigs().isEmpty()); - Assert.assertEquals(retServiceList.getServices().get(0).getId(), Id); - Assert.assertEquals(retServiceList.getServices().get(0).getName(), "HDFS_1"); - Assert.assertEquals(retServiceList.getServices().get(0).getType(), "1"); - - Assert.assertEquals(retServiceList.getServices().get(1).getId(), svc2.getId()); - Assert.assertEquals(retServiceList.getServices().get(1).getName(), "YARN_1"); - Assert.assertEquals(retServiceList.getServices().get(1).getType(), "yarn"); - - - } - - public void mockValidateGrantRevokeRequest(){ - Mockito.when(xUserService.getXUserByUserName(Mockito.anyString())).thenReturn(Mockito.mock(VXUser.class)); - Mockito.when(userMgr.getGroupByGroupName(Mockito.anyString())).thenReturn(Mockito.mock(VXGroup.class)); - Mockito.when(daoManager.getXXRole().findByRoleName(Mockito.anyString())).thenReturn(Mockito.mock(XXRole.class)); - } - - @Test - @Ignore - public void test14bGrantAccess() throws Exception { - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - String serviceName = "HDFS_1"; - GrantRevokeRequest grantRequestObj = createValidGrantRevokeRequest(); - Mockito.when(serviceUtil.isValidateHttpsAuthentication(serviceName, request)) - .thenReturn(true); - Mockito.doNothing().when(bizUtil).failUnauthenticatedIfNotAllowed(); - mockValidateGrantRevokeRequest(); - Mockito.when(xUserService.getXUserByUserName(Mockito.anyString())).thenReturn(Mockito.mock(VXUser.class)); - Mockito.when(svcStore.getServiceByName(Mockito.anyString())).thenReturn(Mockito.mock(RangerService.class)); - Mockito.when(bizUtil.isUserRangerAdmin(Mockito.anyString())).thenReturn(true); - RESTResponse restResponse = serviceREST.grantAccess(serviceName, - grantRequestObj, request); - Mockito.verify(svcStore, Mockito.times(1)).createPolicy(Mockito.any(RangerPolicy.class)); - assert restResponse != null; - assert restResponse.getStatusCode() == RESTResponse.STATUS_SUCCESS; - } - @Test - @Ignore - public void test64SecureGrantAccess(){ - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - String serviceName = "HDFS_1"; - GrantRevokeRequest grantRequestObj = createValidGrantRevokeRequest(); - Mockito.when(serviceUtil.isValidService(serviceName, request)).thenReturn(true); - Mockito.when(daoManager.getXXService().findByName(Mockito.anyString())).thenReturn(Mockito.mock(XXService.class)); - Mockito.when(daoManager.getXXServiceDef().getById(Mockito.anyLong())).thenReturn(Mockito.mock(XXServiceDef.class)); - try { - Mockito.when(svcStore.getServiceByName(Mockito.anyString())).thenReturn(Mockito.mock(RangerService.class)); - } catch (Exception e) { - throw new RuntimeException(e); - } - mockValidateGrantRevokeRequest(); - Mockito.when(bizUtil.isAdmin()).thenReturn(true); - Mockito.when(bizUtil.isUserServiceAdmin(Mockito.any(RangerService.class), Mockito.anyString())).thenReturn(true); - RESTResponse restResponse; - try { - restResponse = serviceREST.secureGrantAccess(serviceName, grantRequestObj, request); - } catch (Exception e) { - throw new RuntimeException(e); - } - try { - Mockito.verify(svcStore, Mockito.times(1)).createPolicy(Mockito.any(RangerPolicy.class)); - } catch (Exception e) { - throw new RuntimeException(e); - } - assert restResponse != null; - assert restResponse.getStatusCode() == RESTResponse.STATUS_SUCCESS; - } - - @Test - public void test15bRevokeAccess() throws Exception { - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - String serviceName = "HDFS_1"; - GrantRevokeRequest revokeRequest = createValidGrantRevokeRequest(); - Mockito.when(serviceUtil.isValidateHttpsAuthentication(serviceName, request)) - .thenReturn(true); - Mockito.doNothing().when(bizUtil).failUnauthenticatedIfNotAllowed(); - mockValidateGrantRevokeRequest(); - Mockito.when(xUserService.getXUserByUserName(Mockito.anyString())).thenReturn(Mockito.mock(VXUser.class)); - Mockito.when(bizUtil.isUserRangerAdmin(Mockito.anyString())).thenReturn(true); - RESTResponse restResponse = serviceREST.revokeAccess(serviceName, - revokeRequest, request); - assert restResponse != null; - assert restResponse.getStatusCode() == RESTResponse.STATUS_SUCCESS; - } - @Test - public void test65SecureRevokeAccess(){ - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - String serviceName = "HDFS_1"; - GrantRevokeRequest revokeRequest = createValidGrantRevokeRequest(); - Mockito.when(serviceUtil.isValidService(serviceName, request)).thenReturn(true); - Mockito.when(daoManager.getXXService().findByName(Mockito.anyString())).thenReturn(Mockito.mock(XXService.class)); - Mockito.when(daoManager.getXXServiceDef().getById(Mockito.anyLong())).thenReturn(Mockito.mock(XXServiceDef.class)); - try { - Mockito.when(svcStore.getServiceByName(Mockito.anyString())).thenReturn(Mockito.mock(RangerService.class)); - } catch (Exception e) { - throw new RuntimeException(e); - } - mockValidateGrantRevokeRequest(); - Mockito.when(bizUtil.isAdmin()).thenReturn(true); - Mockito.when(bizUtil.isUserRangerAdmin(Mockito.anyString())).thenReturn(true); - RESTResponse restResponse = null; - try { - restResponse = serviceREST.secureRevokeAccess(serviceName, - revokeRequest, request); - } catch (Exception e) { - throw new RuntimeException(e); - } - assert restResponse != null; - assert restResponse.getStatusCode() == RESTResponse.STATUS_SUCCESS; - } - - @Test - public void test66ApplyPolicy(){ - ServiceREST serviceRESTSpy = Mockito.spy(serviceREST); - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - RangerPolicy policy = rangerPolicy(); - Mockito.doReturn(policy).when(serviceRESTSpy).createPolicy(Mockito.any(RangerPolicy.class), eq(null)); - RangerPolicy returnedPolicy = serviceRESTSpy.applyPolicy(policy, request); - assert returnedPolicy != null; - assert returnedPolicy.getId().equals(policy.getId()); - assert returnedPolicy.getName().equals(policy.getName()); - } - - @Test - public void test67ResetPolicyCacheForAdmin(){ - boolean res = true; - String serviceName = "HDFS_1"; - Mockito.when(bizUtil.isAdmin()).thenReturn(true); - RangerService rangerService = rangerService(); - try { - Mockito.when(svcStore.getServiceByName(serviceName)).thenReturn(rangerService); - } catch (Exception e) { - } - Mockito.when(svcStore.resetPolicyCache(serviceName)).thenReturn(res); - boolean isReset = serviceREST.resetPolicyCache(serviceName); - assert isReset == res; - try { - Mockito.verify(svcStore).getServiceByName(serviceName); - } catch (Exception e) { - } - } - - @Test - public void test68ResetPolicyCacheAll(){ - boolean res = true; - Mockito.when(bizUtil.isAdmin()).thenReturn(true); - Mockito.when(svcStore.resetPolicyCache(null)).thenReturn(res); - boolean isReset = serviceREST.resetPolicyCacheAll(); - assert isReset == res; - } - - @Test - public void test69DeletePolicyDeltas() { - int val = 1; - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - serviceREST.deletePolicyDeltas(val, request); - Mockito.verify(svcStore).resetPolicyUpdateLog(Mockito.anyInt(), Mockito.anyInt()); - } - - @Test - public void test70PurgeEmptyPolicies() { - ServiceREST serviceRESTSpy = Mockito.spy(serviceREST); - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - String serviceName = "HDFS_1"; - try { - Mockito.when(svcStore.getServiceByName(Mockito.anyString())).thenReturn(Mockito.mock(RangerService.class)); - } catch (Exception e) { - throw new RuntimeException(e); - } - try { - Mockito.when(svcStore.getServicePolicies(Mockito.anyString(), Mockito.anyLong())).thenReturn(servicePolicies()); - } catch (Exception e) { - throw new RuntimeException(e); - } - serviceRESTSpy.purgeEmptyPolicies(serviceName, request); - Mockito.verify(serviceRESTSpy, Mockito.never()).deletePolicy(Mockito.anyLong()); - } - - @Test - public void test71DeleteClusterServices(){ - String clusterName = "cluster1"; - List idsToDelete = createLongList(); - Mockito.when(daoManager.getXXServiceConfigMap().findServiceIdsByClusterName(Mockito.anyString())). - thenReturn(idsToDelete); - XXServiceDef xServiceDef = serviceDef(); - XXService xService = xService(); - XXServiceDefDao xServiceDefDao = Mockito.mock(XXServiceDefDao.class); - Mockito.when(validatorFactory.getServiceValidator(svcStore)) - .thenReturn(serviceValidator); - Mockito.when(daoManager.getXXService().getById(Mockito.anyLong())).thenReturn(xService); - Mockito.when(daoManager.getXXServiceDef()).thenReturn(xServiceDefDao); - Mockito.when(xServiceDefDao.getById(xService.getType())).thenReturn( - xServiceDef); - ResponseEntity> deletedResponse = serviceREST.deleteClusterServices(clusterName); - assert deletedResponse.getStatusCode() == HttpStatus.OK; - assert deletedResponse.getBody() != null; - for (ServiceDeleteResponse response : deletedResponse.getBody()) { - assert response.getIsDeleted(); - } - } - - @Test - public void test72updatePolicyWithPolicyIdIsNull() throws Exception { - RangerPolicy rangerPolicy = rangerPolicy(); - Long policyId = rangerPolicy.getId(); - rangerPolicy.setId(null); - String userName = "admin"; - - Set userGroupsList = new HashSet(); - userGroupsList.add("group1"); - userGroupsList.add("group2"); - - List rangerAccessTypeDefList = new ArrayList(); - RangerAccessTypeDef rangerAccessTypeDefObj = new RangerAccessTypeDef(); - rangerAccessTypeDefObj.setLabel("Read"); - rangerAccessTypeDefObj.setName("read"); - rangerAccessTypeDefObj.setRbKeyLabel(null); - rangerAccessTypeDefList.add(rangerAccessTypeDefObj); - XXServiceDef xServiceDef = serviceDef(); - XXService xService = xService(); - XXServiceDefDao xServiceDefDao = Mockito.mock(XXServiceDefDao.class); - XXServiceDao xServiceDao = Mockito.mock(XXServiceDao.class); - - Mockito.when(validatorFactory.getPolicyValidator(svcStore)).thenReturn( - policyValidator); - Mockito.when(bizUtil.isAdmin()).thenReturn(true); - Mockito.when(bizUtil.getCurrentUserLoginId()).thenReturn(userName); - Mockito.when(daoManager.getXXService()).thenReturn(xServiceDao); - Mockito.when(xServiceDao.findByName(Mockito.anyString())).thenReturn(xService); - Mockito.when(daoManager.getXXServiceDef()).thenReturn(xServiceDefDao); - Mockito.when(xServiceDefDao.getById(xService.getType())).thenReturn(xServiceDef); - RangerPolicy dbRangerPolicy = serviceREST.updatePolicy(rangerPolicy, policyId); - Assert.assertNull(dbRangerPolicy); - Mockito.verify(validatorFactory).getPolicyValidator(svcStore); - } - - @Test - public void test72updatePolicyWithInvalidPolicyId() throws Exception { - RangerPolicy rangerPolicy = rangerPolicy(); - String userName = "admin"; - - Set userGroupsList = new HashSet(); - userGroupsList.add("group1"); - userGroupsList.add("group2"); - - List rangerAccessTypeDefList = new ArrayList(); - RangerAccessTypeDef rangerAccessTypeDefObj = new RangerAccessTypeDef(); - rangerAccessTypeDefObj.setLabel("Read"); - rangerAccessTypeDefObj.setName("read"); - rangerAccessTypeDefObj.setRbKeyLabel(null); - rangerAccessTypeDefList.add(rangerAccessTypeDefObj); - XXServiceDefDao xServiceDefDao = Mockito.mock(XXServiceDefDao.class); - XXServiceDao xServiceDao = Mockito.mock(XXServiceDao.class); - - Mockito.when(daoManager.getXXService()).thenReturn(xServiceDao); - Mockito.when(daoManager.getXXServiceDef()).thenReturn(xServiceDefDao); - Mockito.when(restErrorUtil.createRESTException(Mockito.anyInt(), Mockito.anyString(), Mockito.anyBoolean())).thenThrow(new WebApplicationException()); - thrown.expect(WebApplicationException.class); - RangerPolicy dbRangerPolicy = serviceREST.updatePolicy(rangerPolicy, -11L); - Assert.assertNull(dbRangerPolicy); - Mockito.verify(validatorFactory).getPolicyValidator(svcStore); - } - - @Test - public void test73updateServiceDefWhenIdIsNull() throws Exception { - RangerServiceDef rangerServiceDef = rangerServiceDef(); - Long id = rangerServiceDef.getId(); - rangerServiceDef.setId(null); - - Mockito.when(validatorFactory.getServiceDefValidator(svcStore)) - .thenReturn(serviceDefValidator); - - Mockito.when( - svcStore.updateServiceDef((RangerServiceDef) Mockito - .any())).thenReturn(rangerServiceDef); - - RangerServiceDef dbRangerServiceDef = serviceREST - .updateServiceDef(rangerServiceDef, rangerServiceDef.getId()); - Assert.assertNotNull(dbRangerServiceDef); - Assert.assertEquals(dbRangerServiceDef, rangerServiceDef); - Assert.assertEquals(dbRangerServiceDef.getId(), - rangerServiceDef.getId()); - Assert.assertEquals(dbRangerServiceDef.getName(), - rangerServiceDef.getName()); - Assert.assertEquals(dbRangerServiceDef.getImplClass(), - rangerServiceDef.getImplClass()); - Assert.assertEquals(dbRangerServiceDef.getLabel(), - rangerServiceDef.getLabel()); - Assert.assertEquals(dbRangerServiceDef.getDescription(), - rangerServiceDef.getDescription()); - Assert.assertEquals(dbRangerServiceDef.getRbKeyDescription(), - rangerServiceDef.getRbKeyDescription()); - Assert.assertEquals(dbRangerServiceDef.getUpdatedBy(), - rangerServiceDef.getUpdatedBy()); - Assert.assertEquals(dbRangerServiceDef.getUpdateTime(), - rangerServiceDef.getUpdateTime()); - Assert.assertEquals(dbRangerServiceDef.getVersion(), - rangerServiceDef.getVersion()); - Assert.assertEquals(dbRangerServiceDef.getConfigs(), - rangerServiceDef.getConfigs()); - - Mockito.verify(validatorFactory).getServiceDefValidator(svcStore); - Mockito.verify(svcStore).updateServiceDef(rangerServiceDef); - } - @Test - public void test74updateServiceDefWithInvalidDefId() throws Exception { - RangerServiceDef rangerServiceDef = rangerServiceDef(); - - Mockito.when(restErrorUtil.createRESTException(Mockito.anyInt(), Mockito.anyString(), Mockito.anyBoolean())).thenThrow(new WebApplicationException()); - thrown.expect(WebApplicationException.class); - - RangerServiceDef dbRangerServiceDef = serviceREST - .updateServiceDef(rangerServiceDef, -1L); - Assert.assertNotNull(dbRangerServiceDef); - Assert.assertEquals(dbRangerServiceDef, rangerServiceDef); - Assert.assertEquals(dbRangerServiceDef.getId(), - rangerServiceDef.getId()); - Assert.assertEquals(dbRangerServiceDef.getName(), - rangerServiceDef.getName()); - Assert.assertEquals(dbRangerServiceDef.getImplClass(), - rangerServiceDef.getImplClass()); - Assert.assertEquals(dbRangerServiceDef.getLabel(), - rangerServiceDef.getLabel()); - Assert.assertEquals(dbRangerServiceDef.getDescription(), - rangerServiceDef.getDescription()); - Assert.assertEquals(dbRangerServiceDef.getRbKeyDescription(), - rangerServiceDef.getRbKeyDescription()); - Assert.assertEquals(dbRangerServiceDef.getUpdatedBy(), - rangerServiceDef.getUpdatedBy()); - Assert.assertEquals(dbRangerServiceDef.getUpdateTime(), - rangerServiceDef.getUpdateTime()); - Assert.assertEquals(dbRangerServiceDef.getVersion(), - rangerServiceDef.getVersion()); - Assert.assertEquals(dbRangerServiceDef.getConfigs(), - rangerServiceDef.getConfigs()); - - Mockito.verify(validatorFactory).getServiceDefValidator(svcStore); - Mockito.verify(svcStore).updateServiceDef(rangerServiceDef); - } - - @Test - public void test75GetPolicyByGUIDAndServiceNameAndZoneName() throws Exception { - RangerPolicy rangerPolicy = rangerPolicy(); - RangerService rangerService = rangerService(); - String serviceName = rangerService.getName(); - String zoneName = "zone-1"; - String userName = "admin"; - XXServiceDef xServiceDef = serviceDef(); - XXService xService = xService(); - XXServiceDefDao xServiceDefDao = Mockito.mock(XXServiceDefDao.class); - XXServiceDao xServiceDao = Mockito.mock(XXServiceDao.class); - Mockito.when(bizUtil.isAdmin()).thenReturn(true); - Mockito.when(bizUtil.getCurrentUserLoginId()).thenReturn(userName); - Mockito.when(daoManager.getXXService()).thenReturn(xServiceDao); - Mockito.when(xServiceDao.findByName(Mockito.anyString())).thenReturn(xService); - Mockito.when(daoManager.getXXServiceDef()).thenReturn(xServiceDefDao); - Mockito.when(xServiceDefDao.getById(xService.getType())).thenReturn(xServiceDef); - Mockito.when(svcStore.getPolicy(rangerPolicy.getGuid(), serviceName, zoneName)).thenReturn(rangerPolicy); - RangerPolicy dbRangerPolicy = serviceREST.getPolicyByGUIDAndServiceNameAndZoneName(rangerPolicy.getGuid(), serviceName, zoneName); - Assert.assertNotNull(dbRangerPolicy); - Assert.assertEquals(dbRangerPolicy.getId(), rangerPolicy.getId()); - Mockito.verify(svcStore).getPolicy(rangerPolicy.getGuid(), serviceName, zoneName); - } - - @Test - public void test76GetPolicyByGUID() throws Exception { - RangerPolicy rangerPolicy = rangerPolicy(); - String userName = "admin"; - - Set userGroupsList = new HashSet(); - userGroupsList.add("group1"); - userGroupsList.add("group2"); - - List rangerAccessTypeDefList = new ArrayList(); - RangerAccessTypeDef rangerAccessTypeDefObj = new RangerAccessTypeDef(); - rangerAccessTypeDefObj.setLabel("Read"); - rangerAccessTypeDefObj.setName("read"); - rangerAccessTypeDefObj.setRbKeyLabel(null); - rangerAccessTypeDefList.add(rangerAccessTypeDefObj); - XXServiceDef xServiceDef = serviceDef(); - XXService xService = xService(); - XXServiceDefDao xServiceDefDao = Mockito.mock(XXServiceDefDao.class); - XXServiceDao xServiceDao = Mockito.mock(XXServiceDao.class); - Mockito.when(bizUtil.isAdmin()).thenReturn(true); - Mockito.when(bizUtil.getCurrentUserLoginId()).thenReturn(userName); - Mockito.when(daoManager.getXXService()).thenReturn(xServiceDao); - Mockito.when(xServiceDao.findByName(Mockito.anyString())).thenReturn(xService); - Mockito.when(daoManager.getXXServiceDef()).thenReturn(xServiceDefDao); - Mockito.when(xServiceDefDao.getById(xService.getType())).thenReturn(xServiceDef); - Mockito.when(svcStore.getPolicy(rangerPolicy.getGuid(), null, null)).thenReturn(rangerPolicy); - RangerPolicy dbRangerPolicy = serviceREST.getPolicyByGUIDAndServiceNameAndZoneName(rangerPolicy.getGuid(), null, null); - Assert.assertNotNull(dbRangerPolicy); - Assert.assertEquals(dbRangerPolicy.getId(), rangerPolicy.getId()); - Mockito.verify(svcStore).getPolicy(rangerPolicy.getGuid(), null, null); - } - - @Test - public void test76DeletePolicyByGUIDAndServiceNameAndZoneName() throws Exception { - RangerPolicy rangerPolicy = rangerPolicy(); - RangerService rangerService = rangerService(); - String serviceName = rangerService.getName(); - Mockito.when(validatorFactory.getPolicyValidator(svcStore)).thenReturn(policyValidator); - String zoneName = "zone-1"; - String userName = "admin"; - XXServiceDef xServiceDef = serviceDef(); - XXService xService = xService(); - XXServiceDefDao xServiceDefDao = Mockito.mock(XXServiceDefDao.class); - XXServiceDao xServiceDao = Mockito.mock(XXServiceDao.class); - Mockito.when(bizUtil.isAdmin()).thenReturn(true); - Mockito.when(bizUtil.getCurrentUserLoginId()).thenReturn(userName); - Mockito.when(daoManager.getXXService()).thenReturn(xServiceDao); - Mockito.when(xServiceDao.findByName(Mockito.anyString())).thenReturn(xService); - Mockito.when(daoManager.getXXServiceDef()).thenReturn(xServiceDefDao); - Mockito.when(xServiceDefDao.getById(xService.getType())).thenReturn(xServiceDef); - Mockito.when(svcStore.getPolicy(Id)).thenReturn(rangerPolicy); - Mockito.when(svcStore.getPolicy(rangerPolicy.getGuid(), serviceName, zoneName)).thenReturn(rangerPolicy); - serviceREST.deletePolicyByGUIDAndServiceNameAndZoneName(rangerPolicy.getGuid(), serviceName, zoneName); - Mockito.verify(validatorFactory).getPolicyValidator(svcStore); - Mockito.verify(svcStore).getPolicy(rangerPolicy.getGuid(), serviceName, zoneName); - } - - @Test - public void test77DeletePolicyByGUID() throws Exception { - RangerPolicy rangerPolicy = rangerPolicy(); - Mockito.when(validatorFactory.getPolicyValidator(svcStore)).thenReturn(policyValidator); - String userName = "admin"; - XXServiceDef xServiceDef = serviceDef(); - XXService xService = xService(); - XXServiceDefDao xServiceDefDao = Mockito.mock(XXServiceDefDao.class); - XXServiceDao xServiceDao = Mockito.mock(XXServiceDao.class); - Mockito.when(bizUtil.isAdmin()).thenReturn(true); - Mockito.when(bizUtil.getCurrentUserLoginId()).thenReturn(userName); - Mockito.when(daoManager.getXXService()).thenReturn(xServiceDao); - Mockito.when(xServiceDao.findByName(Mockito.anyString())).thenReturn(xService); - Mockito.when(daoManager.getXXServiceDef()).thenReturn(xServiceDefDao); - Mockito.when(xServiceDefDao.getById(xService.getType())).thenReturn(xServiceDef); - Mockito.when(svcStore.getPolicy(Id)).thenReturn(rangerPolicy); - Mockito.when(svcStore.getPolicy(rangerPolicy.getGuid(), null, null)).thenReturn(rangerPolicy); - serviceREST.deletePolicyByGUIDAndServiceNameAndZoneName(rangerPolicy.getGuid(), null, null); - Mockito.verify(validatorFactory).getPolicyValidator(svcStore); - Mockito.verify(svcStore).getPolicy(rangerPolicy.getGuid(), null, null); - } - - @Test - public void test78ResetPolicyCacheByServiceNameForServiceAdmin() { - boolean isAdmin = false; - boolean res = true; - RangerService rangerService = rangerService(); - String serviceName = rangerService.getName(); - Mockito.when(bizUtil.isAdmin()).thenReturn(isAdmin); - String userName = "admin"; - Mockito.when(bizUtil.getCurrentUserLoginId()).thenReturn(userName); - try { - Mockito.when(svcStore.getServiceByName(serviceName)).thenReturn(rangerService); - } catch (Exception e) { - } - Mockito.when(bizUtil.isUserServiceAdmin(Mockito.any(RangerService.class), Mockito.anyString())).thenReturn(true); - try { - Mockito.when(svcStore.resetPolicyCache(serviceName)).thenReturn(true); - } catch (Exception e) { - } - boolean isReset =serviceREST.resetPolicyCache(serviceName); - assert isReset == res; - Mockito.verify(bizUtil).isAdmin(); - Mockito.verify(bizUtil).isUserServiceAdmin(Mockito.any(RangerService.class), Mockito.anyString()); - try { - Mockito.verify(svcStore).getServiceByName(serviceName); - } catch (Exception e) { - } - try { - Mockito.verify(svcStore).resetPolicyCache(serviceName); - } catch (Exception e) { - } - - } - - @Test - public void test79ResetPolicyCacheWhenServiceNameIsInvalid(){ - String serviceName = "HDFS_1"; - try { - Mockito.when(svcStore.getServiceByName(serviceName)).thenReturn(null); - } catch (Exception e) { - } - Mockito.when(restErrorUtil.createRESTException(Mockito.anyInt(), Mockito.anyString(), Mockito.anyBoolean())).thenThrow(new WebApplicationException()); - thrown.expect(WebApplicationException.class); - serviceREST.resetPolicyCache(serviceName); - Mockito.verify(restErrorUtil).createRESTException(Mockito.anyInt(), Mockito.anyString(), Mockito.anyBoolean()); - } - - @Test - public void test80GetPolicyByNameAndServiceNameWithZoneName() throws Exception { - RangerPolicy rangerPolicy = rangerPolicy(); - RangerService rangerService = rangerService(); - XXPolicy xxPolicy = new XXPolicy(); - String serviceName = rangerService.getName(); - String policyName = rangerPolicy.getName(); - String zoneName = "zone-1"; - XXPolicyDao xXPolicyDao = Mockito.mock(XXPolicyDao.class); - Mockito.when(daoManager.getXXPolicy()).thenReturn(xXPolicyDao); - Mockito.when(daoManager.getXXPolicy().findPolicy(policyName,serviceName,zoneName)).thenReturn(xxPolicy); - Mockito.when(policyService.getPopulatedViewObject(xxPolicy)).thenReturn(rangerPolicy); - Mockito.when(bizUtil.isAdmin()).thenReturn(true); - RangerPolicy dbRangerPolicy = serviceREST.getPolicyByName(serviceName, policyName, zoneName); - Assert.assertNotNull(dbRangerPolicy); - Assert.assertEquals(dbRangerPolicy, rangerPolicy); - Assert.assertEquals(dbRangerPolicy.getId(), rangerPolicy.getId()); - Assert.assertEquals(dbRangerPolicy.getName(), rangerPolicy.getName()); - } - - @Test - public void test81GetPolicyByNameAndServiceNameWithZoneNameIsNull() throws Exception { - RangerPolicy rangerPolicy = rangerPolicy(); - RangerService rangerService = rangerService(); - XXPolicy xxPolicy = new XXPolicy(); - String serviceName = rangerService.getName(); - String policyName = rangerPolicy.getName(); - XXPolicyDao xXPolicyDao = Mockito.mock(XXPolicyDao.class); - Mockito.when(daoManager.getXXPolicy()).thenReturn(xXPolicyDao); - Mockito.when(daoManager.getXXPolicy().findPolicy(policyName,serviceName,null)).thenReturn(xxPolicy); - Mockito.when(policyService.getPopulatedViewObject(xxPolicy)).thenReturn(rangerPolicy); - Mockito.when(bizUtil.isAdmin()).thenReturn(true); - RangerPolicy dbRangerPolicy = serviceREST.getPolicyByName(serviceName, policyName, null); - Assert.assertNotNull(dbRangerPolicy); - Assert.assertEquals(dbRangerPolicy, rangerPolicy); - Assert.assertEquals(dbRangerPolicy.getId(), rangerPolicy.getId()); - Assert.assertEquals(dbRangerPolicy.getName(), rangerPolicy.getName()); - } + revokeRequestObj.setEnableAudit(true); + revokeRequestObj.setIsRecursive(true); + + revokeRequestObj.setGrantor("test43Revoke"); + + String existingPolicyStr = existingPolicy.toString(); + System.out.println("existingPolicy=" + existingPolicyStr); + + ServiceRESTUtil.processRevokeRequest(existingPolicy, revokeRequestObj); + + String resultPolicyStr = existingPolicy.toString(); + System.out.println("resultPolicy=" + resultPolicyStr); + + Assert.assertTrue(true); + } + + @Test + public void test44getPolicyLabels() { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + SearchFilter filter = new SearchFilter(); + Mockito.when(searchUtil.getSearchFilter(request, policyLabelsService.sortFields)).thenReturn(filter); + List ret = new ArrayList<>(); + Mockito.when(svcStore.getPolicyLabels(filter)).thenReturn(ret); + ret = serviceREST.getPolicyLabels(request); + Assert.assertNotNull(ret); + Mockito.verify(searchUtil).getSearchFilter(request, policyLabelsService.sortFields); + } + + @Test + public void test45exportPoliciesInJSON() throws Exception { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + + List rangerPolicyList = new ArrayList<>(); + + RangerPolicy rangerPolicy = rangerPolicy(); + rangerPolicyList.add(rangerPolicy); + XXService xService = xService(); + + XXServiceDao xServiceDao = Mockito.mock(XXServiceDao.class); + XXServiceDef xServiceDef = serviceDef(); + XXServiceDefDao xServiceDefDao = Mockito.mock(XXServiceDefDao.class); + + request.setAttribute("serviceType", "hdfs,hbase,hive,yarn,knox,storm,solr,kafka,nifi,atlas,sqoop"); + HttpServletResponse response = Mockito.mock(HttpServletResponse.class); + SearchFilter filter = new SearchFilter(); + filter.setParam("zoneName", "zone1"); + Mockito.when(searchUtil.getSearchFilter(request, policyService.sortFields)).thenReturn(filter); + Mockito.when(svcStore.getPolicies(filter)).thenReturn(rangerPolicyList); + Mockito.when(bizUtil.isAdmin()).thenReturn(true); + Mockito.when(bizUtil.isKeyAdmin()).thenReturn(false); + Mockito.when(bizUtil.getCurrentUserLoginId()).thenReturn("admin"); + Mockito.when(bizUtil.isAuditAdmin()).thenReturn(false); + Mockito.when(bizUtil.isAuditKeyAdmin()).thenReturn(false); + Mockito.when(daoManager.getXXService()).thenReturn(xServiceDao); + + Mockito.when(daoManager.getXXServiceDef()).thenReturn(xServiceDefDao); + Mockito.when(daoManager.getXXService().findByName("HDFS_1-1-20150316062453")).thenReturn(xService); + Mockito.when(daoManager.getXXServiceDef().getById(xService.getType())).thenReturn(xServiceDef); + serviceREST.getPoliciesInJson(request, response, false); + + Mockito.verify(svcStore).getObjectInJson(rangerPolicyList, response, JSON_FILE_NAME_TYPE.POLICY); + } + + @Test + public void test46exportPoliciesInCSV() throws Exception { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + + List rangerPolicyList = new ArrayList<>(); + + RangerPolicy rangerPolicy = rangerPolicy(); + rangerPolicyList.add(rangerPolicy); + XXService xService = xService(); + + XXServiceDao xServiceDao = Mockito.mock(XXServiceDao.class); + XXServiceDef xServiceDef = serviceDef(); + XXServiceDefDao xServiceDefDao = Mockito.mock(XXServiceDefDao.class); + + request.setAttribute("serviceType", "hdfs,hbase,hive,yarn,knox,storm,solr,kafka,nifi,atlas,sqoop"); + HttpServletResponse response = Mockito.mock(HttpServletResponse.class); + SearchFilter filter = new SearchFilter(); + + Mockito.when(searchUtil.getSearchFilter(request, policyService.sortFields)).thenReturn(filter); + Mockito.when(svcStore.getPolicies(filter)).thenReturn(rangerPolicyList); + Mockito.when(bizUtil.isAdmin()).thenReturn(true); + Mockito.when(bizUtil.isKeyAdmin()).thenReturn(false); + Mockito.when(bizUtil.getCurrentUserLoginId()).thenReturn("admin"); + Mockito.when(bizUtil.isAuditAdmin()).thenReturn(false); + Mockito.when(bizUtil.isAuditKeyAdmin()).thenReturn(false); + Mockito.when(daoManager.getXXService()).thenReturn(xServiceDao); + + Mockito.when(daoManager.getXXServiceDef()).thenReturn(xServiceDefDao); + + Mockito.when(daoManager.getXXService().findByName("HDFS_1-1-20150316062453")).thenReturn(xService); + Mockito.when(daoManager.getXXServiceDef().getById(xService.getType())).thenReturn(xServiceDef); + serviceREST.getPoliciesInCsv(request, response); + + Mockito.verify(svcStore).getPoliciesInCSV(rangerPolicyList, response); + } + + @Test + public void test48exportPoliciesInExcel() throws Exception { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + List rangerPolicyList = new ArrayList<>(); + RangerPolicy rangerPolicy = rangerPolicy(); + + rangerPolicyList.add(rangerPolicy); + + XXService xService = xService(); + XXServiceDao xServiceDao = Mockito.mock(XXServiceDao.class); + XXServiceDef xServiceDef = serviceDef(); + XXServiceDefDao xServiceDefDao = Mockito.mock(XXServiceDefDao.class); + + request.setAttribute("serviceType", "hdfs,hbase,hive,yarn,knox,storm,solr,kafka,nifi,atlas,sqoop"); + HttpServletResponse response = Mockito.mock(HttpServletResponse.class); + SearchFilter filter = new SearchFilter(); + + Mockito.when(searchUtil.getSearchFilter(request, policyService.sortFields)).thenReturn(filter); + Mockito.when(svcStore.getPolicies(filter)).thenReturn(rangerPolicyList); + Mockito.when(bizUtil.isAdmin()).thenReturn(true); + Mockito.when(bizUtil.isKeyAdmin()).thenReturn(false); + Mockito.when(bizUtil.getCurrentUserLoginId()).thenReturn("admin"); + Mockito.when(bizUtil.isAuditAdmin()).thenReturn(false); + Mockito.when(bizUtil.isAuditKeyAdmin()).thenReturn(false); + Mockito.when(daoManager.getXXService()).thenReturn(xServiceDao); + + Mockito.when(daoManager.getXXServiceDef()).thenReturn(xServiceDefDao); + + Mockito.when(daoManager.getXXService().findByName("HDFS_1-1-20150316062453")).thenReturn(xService); + Mockito.when(daoManager.getXXServiceDef().getById(xService.getType())).thenReturn(xServiceDef); + serviceREST.getPoliciesInExcel(request, response); + Mockito.verify(svcStore).getPoliciesInExcel(rangerPolicyList, response); + } + + @SuppressWarnings("unchecked") + @Test + public void test49importPoliciesFromFileAllowingOverride() throws Exception { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + RangerPolicyValidator policyValidator = Mockito.mock(RangerPolicyValidator.class); + Map policiesMap = new LinkedHashMap<>(); + RangerPolicy rangerPolicy = rangerPolicy(); + RangerService service = rangerService(); + XXService xService = xService(); + policiesMap.put("Name", rangerPolicy); + XXServiceDao xServiceDao = Mockito.mock(XXServiceDao.class); + XXServiceDef xServiceDef = serviceDef(); + XXServiceDefDao xServiceDefDao = Mockito.mock(XXServiceDefDao.class); + XXSecurityZoneRefServiceDao xSecZoneRefServiceDao = Mockito.mock(XXSecurityZoneRefServiceDao.class); + XXSecurityZoneRefTagServiceDao xSecZoneRefTagServiceDao = Mockito.mock(XXSecurityZoneRefTagServiceDao.class); + XXSecurityZoneRefService xSecZoneRefService = Mockito.mock(XXSecurityZoneRefService.class); + XXSecurityZoneRefTagService xSecZoneRefTagService = Mockito.mock(XXSecurityZoneRefTagService.class); + XXSecurityZoneDao xSecZoneDao = Mockito.mock(XXSecurityZoneDao.class); + XXSecurityZone xSecZone = Mockito.mock(XXSecurityZone.class); + List zoneServiceList = new ArrayList<>(); + List zoneTagServiceList = new ArrayList<>(); + zoneServiceList.add(xSecZoneRefService); + zoneTagServiceList.add(xSecZoneRefTagService); + Map zoneMappingMap = new LinkedHashMap<>(); + zoneMappingMap.put("ZoneSource", "ZoneDestination"); + + String paramServiceType = "serviceType"; + String serviceTypeList = "hdfs,hbase,hive,yarn,knox,storm,solr,kafka,nifi,atlas,sqoop"; + request.setAttribute("serviceType", "hdfs,hbase,hive,yarn,knox,storm,solr,kafka,nifi,atlas,sqoop"); + SearchFilter filter = new SearchFilter(); + filter.setParam("serviceType", "value"); + + File jsonPolicyFile = getFile(importPoliceTestFilePath); + InputStream uploadedInputStream = new FileInputStream(jsonPolicyFile); + FormDataContentDisposition fileDetail = FormDataContentDisposition.name("file").fileName(jsonPolicyFile.getName()).size(uploadedInputStream.toString().length()).build(); + boolean isOverride = true; + + InputStream zoneInputStream = IOUtils.toInputStream("ZoneSource=ZoneDestination", "UTF-8"); + + Mockito.when(searchUtil.getSearchFilter(request, policyService.sortFields)).thenReturn(filter); + Mockito.when(request.getParameter(paramServiceType)).thenReturn(serviceTypeList); + Mockito.when(svcStore.createPolicyMap(Mockito.any(Map.class), Mockito.any(List.class), Mockito.anyString(), Mockito.any(Map.class), Mockito.any(List.class), Mockito.any(List.class), Mockito.any(RangerPolicy.class), Mockito.any(Map.class))).thenReturn(policiesMap); + Mockito.when(validatorFactory.getPolicyValidator(svcStore)).thenReturn(policyValidator); + Mockito.when(bizUtil.isAdmin()).thenReturn(true); + Mockito.when(daoManager.getXXService()).thenReturn(xServiceDao); + Mockito.when(daoManager.getXXServiceDef()).thenReturn(xServiceDefDao); + Mockito.when(daoManager.getXXService().findByName("HDFS_1-1-20150316062453")).thenReturn(xService); + Mockito.when(daoManager.getXXServiceDef().getById(xService.getType())).thenReturn(xServiceDef); + Mockito.when(validatorFactory.getPolicyValidator(svcStore)).thenReturn(policyValidator); + Mockito.when(svcStore.getMapFromInputStream(zoneInputStream)).thenReturn(zoneMappingMap); + Mockito.when(daoManager.getXXSecurityZoneDao()).thenReturn(xSecZoneDao); + Mockito.when(xSecZoneDao.findByZoneName(Mockito.anyString())).thenReturn(xSecZone); + Mockito.when(daoManager.getXXSecurityZoneRefService()).thenReturn(xSecZoneRefServiceDao); + Mockito.when(xSecZoneRefServiceDao.findByServiceNameAndZoneId(Mockito.anyString(), Mockito.anyLong())).thenReturn(zoneServiceList); + Mockito.when(daoManager.getXXSecurityZoneRefTagService()).thenReturn(xSecZoneRefTagServiceDao); + Mockito.when(xSecZoneRefTagServiceDao.findByTagServiceNameAndZoneId(Mockito.anyString(), Mockito.anyLong())).thenReturn(zoneTagServiceList); + Mockito.when(svcStore.getServiceByName(Mockito.anyString())).thenReturn(service); + serviceREST.importPoliciesFromFile(request, null, zoneInputStream, uploadedInputStream, fileDetail, isOverride, "unzoneToZone"); + + Mockito.verify(svcStore).createPolicy(rangerPolicy); + } + + @SuppressWarnings("unchecked") + @Test + public void test50importPoliciesFromFileNotAllowingOverride() throws Exception { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + Map policiesMap = new LinkedHashMap<>(); + RangerPolicy rangerPolicy = rangerPolicy(); + XXService xService = xService(); + policiesMap.put("Name", rangerPolicy); + XXServiceDao xServiceDao = Mockito.mock(XXServiceDao.class); + XXServiceDef xServiceDef = serviceDef(); + XXServiceDefDao xServiceDefDao = Mockito.mock(XXServiceDefDao.class); + XXSecurityZoneRefServiceDao xSecZoneRefServiceDao = Mockito.mock(XXSecurityZoneRefServiceDao.class); + XXSecurityZoneRefTagServiceDao xSecZoneRefTagServiceDao = Mockito.mock(XXSecurityZoneRefTagServiceDao.class); + XXSecurityZoneRefService xSecZoneRefService = Mockito.mock(XXSecurityZoneRefService.class); + XXSecurityZoneRefTagService xSecZoneRefTagService = Mockito.mock(XXSecurityZoneRefTagService.class); + XXSecurityZoneDao xSecZoneDao = Mockito.mock(XXSecurityZoneDao.class); + XXSecurityZone xSecZone = Mockito.mock(XXSecurityZone.class); + List zoneServiceList = new ArrayList<>(); + List zoneTagServiceList = new ArrayList<>(); + zoneServiceList.add(xSecZoneRefService); + zoneTagServiceList.add(xSecZoneRefTagService); + Map zoneMappingMap = new LinkedHashMap<>(); + zoneMappingMap.put("ZoneSource", "ZoneDestination"); + + String paramServiceType = "serviceType"; + String serviceTypeList = "hdfs,hbase,hive,yarn,knox,storm,solr,kafka,nifi,atlas,sqoop"; + request.setAttribute("serviceType", "hdfs,hbase,hive,yarn,knox,storm,solr,kafka,nifi,atlas,sqoop"); + SearchFilter filter = new SearchFilter(); + filter.setParam("serviceType", "value"); + + File jsonPolicyFile = getFile(importPoliceTestFilePath); + InputStream uploadedInputStream = new FileInputStream(jsonPolicyFile); + FormDataContentDisposition fileDetail = FormDataContentDisposition.name("file").fileName(jsonPolicyFile.getName()).size(uploadedInputStream.toString().length()).build(); + boolean isOverride = false; + + InputStream zoneInputStream = IOUtils.toInputStream("ZoneSource=ZoneDestination", "UTF-8"); + + Mockito.when(searchUtil.getSearchFilter(request, policyService.sortFields)).thenReturn(filter); + Mockito.when(request.getParameter(paramServiceType)).thenReturn(serviceTypeList); + Mockito.when(svcStore.createPolicyMap(Mockito.any(Map.class), Mockito.any(List.class), Mockito.anyString(), Mockito.any(Map.class), Mockito.any(List.class), Mockito.any(List.class), Mockito.any(RangerPolicy.class), Mockito.any(Map.class))).thenReturn(policiesMap); + Mockito.when(validatorFactory.getPolicyValidator(svcStore)).thenReturn(policyValidator); + Mockito.when(bizUtil.isAdmin()).thenReturn(true); + Mockito.when(daoManager.getXXService()).thenReturn(xServiceDao); + Mockito.when(daoManager.getXXServiceDef()).thenReturn(xServiceDefDao); + Mockito.when(daoManager.getXXService().findByName("HDFS_1-1-20150316062453")).thenReturn(xService); + Mockito.when(daoManager.getXXServiceDef().getById(xService.getType())).thenReturn(xServiceDef); + Mockito.when(svcStore.getMapFromInputStream(zoneInputStream)).thenReturn(zoneMappingMap); + Mockito.when(daoManager.getXXSecurityZoneDao()).thenReturn(xSecZoneDao); + Mockito.when(xSecZoneDao.findByZoneName(Mockito.anyString())).thenReturn(xSecZone); + Mockito.when(daoManager.getXXSecurityZoneRefService()).thenReturn(xSecZoneRefServiceDao); + Mockito.when(xSecZoneRefServiceDao.findByServiceNameAndZoneId(Mockito.anyString(), Mockito.anyLong())).thenReturn(zoneServiceList); + Mockito.when(daoManager.getXXSecurityZoneRefTagService()).thenReturn(xSecZoneRefTagServiceDao); + Mockito.when(xSecZoneRefTagServiceDao.findByTagServiceNameAndZoneId(Mockito.anyString(), Mockito.anyLong())).thenReturn(zoneTagServiceList); + serviceREST.importPoliciesFromFile(request, null, zoneInputStream, uploadedInputStream, fileDetail, isOverride, "unzoneToUnZone"); + Mockito.verify(svcStore).createPolicy(rangerPolicy); + } + + @Test + public void test51getMetricByType() throws Exception { + String type = "usergroup"; + String ret = "{\"groupCount\":1,\"userCountOfUserRole\":0,\"userCountOfKeyAdminRole\":1," + + "\"userCountOfSysAdminRole\":3,\"userCountOfKeyadminAuditorRole\":0,\"userCountOfSysAdminAuditorRole\":0,\"userTotalCount\":4}"; + ServiceDBStore.METRIC_TYPE metricType = ServiceDBStore.METRIC_TYPE.getMetricTypeByName(type); + Mockito.when(svcStore.getMetricByType(metricType)).thenReturn(ret); + serviceREST.getMetricByType(type); + Mockito.verify(svcStore).getMetricByType(metricType); + } + + @Test + public void test52deleteService() { + RangerService rangerService = rangerService(); + XXService xService = xService(); + List referringServices = new ArrayList<>(); + referringServices.add(xService); + EmbeddedServiceDefsUtil embeddedServiceDefsUtil = EmbeddedServiceDefsUtil.instance(); + xService.setType(embeddedServiceDefsUtil.getTagServiceDefId()); + XXServiceDao xServiceDao = Mockito.mock(XXServiceDao.class); + + String userLoginID = "testuser"; + Long userId = 8L; + RangerSecurityContext context = new RangerSecurityContext(); + context.setUserSession(new UserSessionBase()); + RangerContextHolder.setSecurityContext(context); + UserSessionBase session = ContextUtil.getCurrentUserSession(); + session.setUserAdmin(true); + XXPortalUser xXPortalUser = new XXPortalUser(); + xXPortalUser.setLoginId(userLoginID); + xXPortalUser.setId(userId); + session.setXXPortalUser(xXPortalUser); + + Mockito.when(validatorFactory.getServiceValidator(svcStore)).thenReturn(serviceValidator); + Mockito.when(daoManager.getXXService()).thenReturn(xServiceDao); + Mockito.when(xServiceDao.findByTagServiceId(Mockito.anyLong())).thenReturn(referringServices); + Mockito.when(xServiceDao.getById(Id)).thenReturn(xService); + Mockito.when(restErrorUtil.createRESTException(Mockito.anyString(), Mockito.any())).thenThrow(new WebApplicationException()); + thrown.expect(WebApplicationException.class); + serviceREST.deleteService(rangerService.getId()); + } + + @Test + public void test53getPoliciesForResource() { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + List rsList = new ArrayList<>(); + RangerService rs = rangerService(); + rsList.add(rs); + + Mockito.when(restErrorUtil.createRESTException(Mockito.anyString(), Mockito.any())).thenThrow(new WebApplicationException()); + thrown.expect(WebApplicationException.class); + + serviceREST.getPoliciesForResource("servicedefname", "servicename", request); + } + + @Test + public void test54getPluginsInfo() { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + SearchFilter filter = new SearchFilter(); + filter.setParam(SearchFilter.POLICY_NAME, "policyName"); + filter.setParam(SearchFilter.SERVICE_NAME, "serviceName"); + PList paginatedPluginsInfo = new PList<>(); + Mockito.when(searchUtil.getSearchFilter(request, pluginInfoService.getSortFields())).thenReturn(filter); + Mockito.when(pluginInfoService.searchRangerPluginInfo(filter)).thenReturn(paginatedPluginsInfo); + RangerPluginInfoList rPluginInfoList = serviceREST.getPluginsInfo(request); + Assert.assertNotNull(rPluginInfoList); + Mockito.verify(searchUtil).getSearchFilter(request, pluginInfoService.getSortFields()); + Mockito.verify(pluginInfoService).searchRangerPluginInfo(filter); + } + + @Test + public void test55getServicePoliciesIfUpdatedCatch() throws Exception { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + String serviceName = "HDFS_1"; + Long lastKnownVersion = 1L; + String pluginId = "1"; + Mockito.when(serviceUtil.isValidateHttpsAuthentication(serviceName, request)).thenReturn(true); + Mockito.when(restErrorUtil.createRESTException(Mockito.anyInt(), Mockito.anyString(), Mockito.anyBoolean())).thenThrow(new WebApplicationException()); + thrown.expect(WebApplicationException.class); + serviceREST.getServicePoliciesIfUpdated(serviceName, lastKnownVersion, 0L, pluginId, "", "", false, capabilityVector, request); + } + + @Test + public void test56getServicePoliciesIfUpdated() throws Exception { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + ServicePolicies servicePolicies = servicePolicies(); + String serviceName = "HDFS_1"; + Long lastKnownVersion = 1L; + String pluginId = "1"; + Mockito.when(serviceUtil.isValidateHttpsAuthentication(serviceName, request)).thenReturn(true); + Mockito.when(svcStore.getServicePoliciesIfUpdated(Mockito.anyString(), Mockito.anyLong(), Mockito.anyBoolean())).thenReturn(servicePolicies); + ServicePolicies dbServicePolicies = serviceREST.getServicePoliciesIfUpdated(serviceName, lastKnownVersion, 0L, pluginId, "", "", true, capabilityVector, request); + Assert.assertNotNull(dbServicePolicies); + } + + @Test + public void test57getSecureServicePoliciesIfUpdatedFail() throws Exception { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + Long lastKnownVersion = 1L; + String pluginId = "1"; + XXService xService = xService(); + XXServiceDef xServiceDef = serviceDef(); + String serviceName = xService.getName(); + RangerService rs = rangerService(); + XXServiceDefDao xServiceDefDao = Mockito.mock(XXServiceDefDao.class); + Mockito.when(serviceUtil.isValidService(serviceName, request)).thenReturn(true); + Mockito.when(daoManager.getXXService()).thenReturn(xServiceDao); + Mockito.when(xServiceDao.findByName(serviceName)).thenReturn(xService); + Mockito.when(daoManager.getXXServiceDef()).thenReturn(xServiceDefDao); + Mockito.when(xServiceDefDao.getById(xService.getType())).thenReturn(xServiceDef); + Mockito.when(svcStore.getServiceByName(serviceName)).thenReturn(rs); + Mockito.when(restErrorUtil.createRESTException(Mockito.anyInt(), Mockito.anyString(), Mockito.anyBoolean())).thenThrow(new WebApplicationException()); + thrown.expect(WebApplicationException.class); + + serviceREST.getSecureServicePoliciesIfUpdated(serviceName, lastKnownVersion, 0L, pluginId, "", "", false, capabilityVector, request); + } + + @Test + public void test58getSecureServicePoliciesIfUpdatedAllowedFail() throws Exception { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + + Long lastKnownVersion = 1L; + String pluginId = "1"; + XXService xService = xService(); + XXServiceDef xServiceDef = serviceDef(); + xServiceDef.setImplclassname("org.apache.ranger.services.kms.RangerServiceKMS"); + String serviceName = xService.getName(); + RangerService rs = rangerService(); + XXServiceDefDao xServiceDefDao = Mockito.mock(XXServiceDefDao.class); + Mockito.when(serviceUtil.isValidService(serviceName, request)).thenReturn(true); + Mockito.when(daoManager.getXXService()).thenReturn(xServiceDao); + Mockito.when(xServiceDao.findByName(serviceName)).thenReturn(xService); + Mockito.when(daoManager.getXXServiceDef()).thenReturn(xServiceDefDao); + Mockito.when(xServiceDefDao.getById(xService.getType())).thenReturn(xServiceDef); + Mockito.when(svcStore.getServiceByNameForDP(serviceName)).thenReturn(rs); + Mockito.when(bizUtil.isUserAllowed(rs, ServiceREST.Allowed_User_List_For_Grant_Revoke)).thenReturn(true); + Mockito.when(restErrorUtil.createRESTException(Mockito.anyInt(), Mockito.anyString(), Mockito.anyBoolean())).thenThrow(new WebApplicationException()); + thrown.expect(WebApplicationException.class); + + serviceREST.getSecureServicePoliciesIfUpdated(serviceName, lastKnownVersion, 0L, pluginId, "", "", false, capabilityVector, request); + } + + @Test + public void test59getSecureServicePoliciesIfUpdatedSuccess() throws Exception { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + + Long lastKnownVersion = 1L; + String pluginId = "1"; + XXService xService = xService(); + XXServiceDef xServiceDef = serviceDef(); + xServiceDef.setImplclassname("org.apache.ranger.services.kms.RangerServiceKMS"); + String serviceName = xService.getName(); + RangerService rs = rangerService(); + ServicePolicies sp = servicePolicies(); + XXServiceDefDao xServiceDefDao = Mockito.mock(XXServiceDefDao.class); + Mockito.when(serviceUtil.isValidService(serviceName, request)).thenReturn(true); + Mockito.when(daoManager.getXXService()).thenReturn(xServiceDao); + Mockito.when(xServiceDao.findByName(serviceName)).thenReturn(xService); + Mockito.when(daoManager.getXXServiceDef()).thenReturn(xServiceDefDao); + Mockito.when(xServiceDefDao.getById(xService.getType())).thenReturn(xServiceDef); + Mockito.when(svcStore.getServiceByNameForDP(serviceName)).thenReturn(rs); + Mockito.when(bizUtil.isUserAllowed(rs, ServiceREST.Allowed_User_List_For_Grant_Revoke)).thenReturn(true); + Mockito.when(svcStore.getServicePoliciesIfUpdated(Mockito.anyString(), Mockito.anyLong(), Mockito.anyBoolean())).thenReturn(sp); + ServicePolicies dbServiceSecurePolicies = serviceREST.getSecureServicePoliciesIfUpdated(serviceName, lastKnownVersion, 0L, pluginId, "", "", true, capabilityVector, request); + Assert.assertNotNull(dbServiceSecurePolicies); + Mockito.verify(serviceUtil).isValidService(serviceName, request); + Mockito.verify(xServiceDao).findByName(serviceName); + Mockito.verify(xServiceDefDao).getById(xService.getType()); + Mockito.verify(svcStore).getServiceByNameForDP(serviceName); + Mockito.verify(bizUtil).isUserAllowed(rs, ServiceREST.Allowed_User_List_For_Grant_Revoke); + Mockito.verify(svcStore).getServicePoliciesIfUpdated(serviceName, lastKnownVersion, false); + } + + @Test + public void test60getPolicyFromEventTime() { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + + String strdt = new Date().toString(); + Set userGroupsList = new HashSet<>(); + userGroupsList.add("group1"); + userGroupsList.add("group2"); + Mockito.when(request.getParameter("eventTime")).thenReturn(strdt); + Mockito.when(request.getParameter("policyId")).thenReturn("1"); + Mockito.when(request.getParameter("versionNo")).thenReturn("1"); + RangerPolicy policy = new RangerPolicy(); + Map resources = new HashMap<>(); + policy.setService("services"); + policy.setResources(resources); + Mockito.when(svcStore.getPolicyFromEventTime(strdt, 1L)).thenReturn(null); + + Mockito.when(restErrorUtil.createRESTException(Mockito.anyInt(), Mockito.anyString(), Mockito.anyBoolean())).thenThrow(new WebApplicationException()); + thrown.expect(WebApplicationException.class); + + serviceREST.getPolicyFromEventTime(request); + } + + @Test + public void test61getServiceWillOnlyReturnNameIdAndTypeForRoleUser() throws Exception { + RangerService actualService = rangerService(); + + String userLoginID = "testuser"; + Long userId = 8L; + + RangerSecurityContext context = new RangerSecurityContext(); + context.setUserSession(new UserSessionBase()); + RangerContextHolder.setSecurityContext(context); + UserSessionBase currentUserSession = ContextUtil.getCurrentUserSession(); + currentUserSession.setUserAdmin(false); + XXPortalUser xXPortalUser = new XXPortalUser(); + xXPortalUser.setLoginId(userLoginID); + xXPortalUser.setId(userId); + currentUserSession.setXXPortalUser(xXPortalUser); + + VXUser loggedInUser = new VXUser(); + List loggedInUserRole = new ArrayList<>(); + loggedInUserRole.add(RangerConstants.ROLE_USER); + loggedInUser.setId(8L); + loggedInUser.setName("testuser"); + loggedInUser.setUserRoleList(loggedInUserRole); + Mockito.when(xUserService.getXUserByUserName("testuser")).thenReturn(loggedInUser); + Mockito.when(svcStore.getService(Id)).thenReturn(actualService); + + RangerService service = serviceREST.getService(Id); + Assert.assertNotNull(service); + Mockito.verify(svcStore).getService(Id); + Assert.assertNull(service.getDescription()); + Assert.assertTrue(service.getConfigs().isEmpty()); + Assert.assertEquals(Id, service.getId()); + Assert.assertEquals("HDFS_1", service.getName()); + Assert.assertEquals("1", service.getType()); + } + + @Test + public void test62getServiceByNameWillOnlyReturnNameIdAndTypeForRoleUser() throws Exception { + RangerService actualService = rangerService(); + + String userLoginID = "testuser"; + Long userId = 8L; + + RangerSecurityContext context = new RangerSecurityContext(); + context.setUserSession(new UserSessionBase()); + RangerContextHolder.setSecurityContext(context); + UserSessionBase currentUserSession = ContextUtil.getCurrentUserSession(); + currentUserSession.setUserAdmin(false); + XXPortalUser xXPortalUser = new XXPortalUser(); + xXPortalUser.setLoginId(userLoginID); + xXPortalUser.setId(userId); + currentUserSession.setXXPortalUser(xXPortalUser); + + VXUser loggedInUser = new VXUser(); + List loggedInUserRole = new ArrayList<>(); + loggedInUserRole.add(RangerConstants.ROLE_USER); + loggedInUser.setId(8L); + loggedInUser.setName("testuser"); + loggedInUser.setUserRoleList(loggedInUserRole); + Mockito.when(xUserService.getXUserByUserName("testuser")).thenReturn(loggedInUser); + Mockito.when(svcStore.getServiceByName(actualService.getName())).thenReturn(actualService); + + RangerService service = serviceREST.getServiceByName(actualService.getName()); + Assert.assertNotNull(service); + Mockito.verify(svcStore).getServiceByName(actualService.getName()); + Assert.assertNull(service.getDescription()); + Assert.assertTrue(service.getConfigs().isEmpty()); + Assert.assertEquals(Id, service.getId()); + Assert.assertEquals("HDFS_1", service.getName()); + Assert.assertEquals("1", service.getType()); + } + + @Test + public void test63getServices() throws Exception { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + PList paginatedSvcs = new PList<>(); + RangerService svc1 = rangerService(); + + String userLoginID = "testuser"; + Long userId = 8L; + + RangerSecurityContext context = new RangerSecurityContext(); + context.setUserSession(new UserSessionBase()); + RangerContextHolder.setSecurityContext(context); + UserSessionBase currentUserSession = ContextUtil.getCurrentUserSession(); + currentUserSession.setUserAdmin(false); + XXPortalUser xXPortalUser = new XXPortalUser(); + xXPortalUser.setLoginId(userLoginID); + xXPortalUser.setId(userId); + currentUserSession.setXXPortalUser(xXPortalUser); + + VXUser loggedInUser = new VXUser(); + List loggedInUserRole = new ArrayList<>(); + loggedInUserRole.add(RangerConstants.ROLE_USER); + loggedInUser.setId(8L); + loggedInUser.setName("testuser"); + loggedInUser.setUserRoleList(loggedInUserRole); + + Map configs = new HashMap<>(); + configs.put("username", "servicemgr"); + configs.put("password", "servicemgr"); + configs.put("namenode", "servicemgr"); + configs.put("hadoop.security.authorization", "No"); + configs.put("hadoop.security.authentication", "Simple"); + configs.put("hadoop.security.auth_to_local", ""); + configs.put("dfs.datanode.kerberos.principal", ""); + configs.put("dfs.namenode.kerberos.principal", ""); + configs.put("dfs.secondary.namenode.kerberos.principal", ""); + configs.put("hadoop.rpc.protection", "Privacy"); + configs.put("commonNameForCertificate", ""); + + RangerService svc2 = new RangerService(); + svc2.setId(9L); + svc2.setConfigs(configs); + svc2.setCreateTime(new Date()); + svc2.setDescription("service policy"); + svc2.setGuid("1427365526516_835_1"); + svc2.setIsEnabled(true); + svc2.setName("YARN_1"); + svc2.setPolicyUpdateTime(new Date()); + svc2.setType("yarn"); + svc2.setUpdatedBy("Admin"); + svc2.setUpdateTime(new Date()); + + List rangerServiceList = new ArrayList<>(); + rangerServiceList.add(svc1); + rangerServiceList.add(svc2); + + paginatedSvcs.setList(rangerServiceList); + + SearchFilter filter = new SearchFilter(); + Mockito.when(searchUtil.getSearchFilter(request, svcService.sortFields)).thenReturn(filter); + Mockito.when(svcStore.getPaginatedServices(filter)).thenReturn(paginatedSvcs); + Mockito.when(xUserService.getXUserByUserName("testuser")).thenReturn(loggedInUser); + RangerServiceList retServiceList = serviceREST.getServices(request); + Assert.assertNotNull(retServiceList); + Assert.assertNull(retServiceList.getServices().get(0).getDescription()); + Assert.assertTrue(retServiceList.getServices().get(0).getConfigs().isEmpty()); + Assert.assertNull(retServiceList.getServices().get(1).getDescription()); + Assert.assertTrue(retServiceList.getServices().get(1).getConfigs().isEmpty()); + Assert.assertEquals(Id, retServiceList.getServices().get(0).getId()); + Assert.assertEquals("HDFS_1", retServiceList.getServices().get(0).getName()); + Assert.assertEquals("1", retServiceList.getServices().get(0).getType()); + + Assert.assertEquals(retServiceList.getServices().get(1).getId(), svc2.getId()); + Assert.assertEquals("YARN_1", retServiceList.getServices().get(1).getName()); + Assert.assertEquals("yarn", retServiceList.getServices().get(1).getType()); + } + + public void mockValidateGrantRevokeRequest() { + Mockito.when(xUserService.getXUserByUserName(Mockito.anyString())).thenReturn(Mockito.mock(VXUser.class)); + Mockito.when(userMgr.getGroupByGroupName(Mockito.anyString())).thenReturn(Mockito.mock(VXGroup.class)); + Mockito.when(daoManager.getXXRole().findByRoleName(Mockito.anyString())).thenReturn(Mockito.mock(XXRole.class)); + } + + @Test + @Ignore + public void test14bGrantAccess() throws Exception { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + String serviceName = "HDFS_1"; + GrantRevokeRequest grantRequestObj = createValidGrantRevokeRequest(); + Mockito.when(serviceUtil.isValidateHttpsAuthentication(serviceName, request)).thenReturn(true); + Mockito.doNothing().when(bizUtil).failUnauthenticatedIfNotAllowed(); + mockValidateGrantRevokeRequest(); + Mockito.when(xUserService.getXUserByUserName(Mockito.anyString())).thenReturn(Mockito.mock(VXUser.class)); + Mockito.when(svcStore.getServiceByName(Mockito.anyString())).thenReturn(Mockito.mock(RangerService.class)); + Mockito.when(bizUtil.isUserRangerAdmin(Mockito.anyString())).thenReturn(true); + RESTResponse restResponse = serviceREST.grantAccess(serviceName, grantRequestObj, request); + Mockito.verify(svcStore, Mockito.times(1)).createPolicy(Mockito.any(RangerPolicy.class)); + + Assert.assertNotNull(restResponse); + Assert.assertEquals(RESTResponse.STATUS_SUCCESS, restResponse.getStatusCode()); + } + + @Test + @Ignore + public void test64SecureGrantAccess() { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + String serviceName = "HDFS_1"; + GrantRevokeRequest grantRequestObj = createValidGrantRevokeRequest(); + Mockito.when(serviceUtil.isValidService(serviceName, request)).thenReturn(true); + Mockito.when(daoManager.getXXService().findByName(Mockito.anyString())).thenReturn(Mockito.mock(XXService.class)); + Mockito.when(daoManager.getXXServiceDef().getById(Mockito.anyLong())).thenReturn(Mockito.mock(XXServiceDef.class)); + try { + Mockito.when(svcStore.getServiceByName(Mockito.anyString())).thenReturn(Mockito.mock(RangerService.class)); + } catch (Exception e) { + throw new RuntimeException(e); + } + mockValidateGrantRevokeRequest(); + Mockito.when(bizUtil.isAdmin()).thenReturn(true); + Mockito.when(bizUtil.isUserServiceAdmin(Mockito.any(RangerService.class), Mockito.anyString())).thenReturn(true); + RESTResponse restResponse; + try { + restResponse = serviceREST.secureGrantAccess(serviceName, grantRequestObj, request); + } catch (Exception e) { + throw new RuntimeException(e); + } + try { + Mockito.verify(svcStore, Mockito.times(1)).createPolicy(Mockito.any(RangerPolicy.class)); + } catch (Exception e) { + throw new RuntimeException(e); + } + + Assert.assertNotNull(restResponse); + Assert.assertEquals(RESTResponse.STATUS_SUCCESS, restResponse.getStatusCode()); + } + + @Test + public void test15bRevokeAccess() throws Exception { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + String serviceName = "HDFS_1"; + GrantRevokeRequest revokeRequest = createValidGrantRevokeRequest(); + Mockito.when(serviceUtil.isValidateHttpsAuthentication(serviceName, request)).thenReturn(true); + Mockito.doNothing().when(bizUtil).failUnauthenticatedIfNotAllowed(); + mockValidateGrantRevokeRequest(); + Mockito.when(xUserService.getXUserByUserName(Mockito.anyString())).thenReturn(Mockito.mock(VXUser.class)); + Mockito.when(bizUtil.isUserRangerAdmin(Mockito.anyString())).thenReturn(true); + RESTResponse restResponse = serviceREST.revokeAccess(serviceName, revokeRequest, request); + Assert.assertNotNull(restResponse); + Assert.assertEquals(RESTResponse.STATUS_SUCCESS, restResponse.getStatusCode()); + } + + @Test + public void test65SecureRevokeAccess() { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + String serviceName = "HDFS_1"; + GrantRevokeRequest revokeRequest = createValidGrantRevokeRequest(); + Mockito.when(serviceUtil.isValidService(serviceName, request)).thenReturn(true); + Mockito.when(daoManager.getXXService().findByName(Mockito.anyString())).thenReturn(Mockito.mock(XXService.class)); + Mockito.when(daoManager.getXXServiceDef().getById(Mockito.anyLong())).thenReturn(Mockito.mock(XXServiceDef.class)); + try { + Mockito.when(svcStore.getServiceByName(Mockito.anyString())).thenReturn(Mockito.mock(RangerService.class)); + } catch (Exception e) { + throw new RuntimeException(e); + } + mockValidateGrantRevokeRequest(); + Mockito.when(bizUtil.isAdmin()).thenReturn(true); + Mockito.when(bizUtil.isUserRangerAdmin(Mockito.anyString())).thenReturn(true); + RESTResponse restResponse = null; + try { + restResponse = serviceREST.secureRevokeAccess(serviceName, + revokeRequest, request); + } catch (Exception e) { + throw new RuntimeException(e); + } + Assert.assertNotNull(restResponse); + Assert.assertEquals(RESTResponse.STATUS_SUCCESS, restResponse.getStatusCode()); + } + + @Test + public void test66ApplyPolicy() { + ServiceREST serviceRESTSpy = Mockito.spy(serviceREST); + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + RangerPolicy policy = rangerPolicy(); + Mockito.doReturn(policy).when(serviceRESTSpy).createPolicy(Mockito.any(RangerPolicy.class), eq(null)); + RangerPolicy returnedPolicy = serviceRESTSpy.applyPolicy(policy, request); + Assert.assertNotNull(returnedPolicy); + Assert.assertEquals(returnedPolicy.getId(), policy.getId()); + Assert.assertEquals(returnedPolicy.getName(), policy.getName()); + } + + @Test + public void test67ResetPolicyCacheForAdmin() { + boolean res = true; + String serviceName = "HDFS_1"; + Mockito.when(bizUtil.isAdmin()).thenReturn(true); + RangerService rangerService = rangerService(); + try { + Mockito.when(svcStore.getServiceByName(serviceName)).thenReturn(rangerService); + } catch (Exception ignored) { + } + Mockito.when(svcStore.resetPolicyCache(serviceName)).thenReturn(res); + boolean isReset = serviceREST.resetPolicyCache(serviceName); + Assert.assertEquals(res, isReset); + try { + Mockito.verify(svcStore).getServiceByName(serviceName); + } catch (Exception ignored) { + } + } + + @Test + public void test68ResetPolicyCacheAll() { + boolean res = true; + Mockito.when(bizUtil.isAdmin()).thenReturn(true); + Mockito.when(svcStore.resetPolicyCache(null)).thenReturn(res); + boolean isReset = serviceREST.resetPolicyCacheAll(); + Assert.assertEquals(res, isReset); + } + + @Test + public void test69DeletePolicyDeltas() { + int val = 1; + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + serviceREST.deletePolicyDeltas(val, request); + Mockito.verify(svcStore).resetPolicyUpdateLog(Mockito.anyInt(), Mockito.anyInt()); + } + + @Test + public void test70PurgeEmptyPolicies() { + ServiceREST serviceRESTSpy = Mockito.spy(serviceREST); + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + String serviceName = "HDFS_1"; + try { + Mockito.when(svcStore.getServiceByName(Mockito.anyString())).thenReturn(Mockito.mock(RangerService.class)); + } catch (Exception e) { + throw new RuntimeException(e); + } + try { + Mockito.when(svcStore.getServicePolicies(Mockito.anyString(), Mockito.anyLong())).thenReturn(servicePolicies()); + } catch (Exception e) { + throw new RuntimeException(e); + } + serviceRESTSpy.purgeEmptyPolicies(serviceName, request); + Mockito.verify(serviceRESTSpy, Mockito.never()).deletePolicy(Mockito.anyLong()); + } + + @Test + public void test71DeleteClusterServices() { + String clusterName = "cluster1"; + List idsToDelete = createLongList(); + Mockito.when(daoManager.getXXServiceConfigMap().findServiceIdsByClusterName(Mockito.anyString())).thenReturn(idsToDelete); + XXServiceDef xServiceDef = serviceDef(); + XXService xService = xService(); + XXServiceDefDao xServiceDefDao = Mockito.mock(XXServiceDefDao.class); + Mockito.when(validatorFactory.getServiceValidator(svcStore)).thenReturn(serviceValidator); + Mockito.when(daoManager.getXXService().getById(Mockito.anyLong())).thenReturn(xService); + Mockito.when(daoManager.getXXServiceDef()).thenReturn(xServiceDefDao); + Mockito.when(xServiceDefDao.getById(xService.getType())).thenReturn(xServiceDef); + ResponseEntity> deletedResponse = serviceREST.deleteClusterServices(clusterName); + Assert.assertEquals(HttpStatus.OK, deletedResponse.getStatusCode()); + Assert.assertNotEquals(null, deletedResponse.getBody()); + for (ServiceDeleteResponse response : deletedResponse.getBody()) { + Assert.assertTrue(response.getIsDeleted()); + } + } + + @Test + public void test72updatePolicyWithPolicyIdIsNull() { + RangerPolicy rangerPolicy = rangerPolicy(); + Long policyId = rangerPolicy.getId(); + rangerPolicy.setId(null); + String userName = "admin"; + + Set userGroupsList = new HashSet<>(); + userGroupsList.add("group1"); + userGroupsList.add("group2"); + + List rangerAccessTypeDefList = new ArrayList<>(); + RangerAccessTypeDef rangerAccessTypeDefObj = new RangerAccessTypeDef(); + rangerAccessTypeDefObj.setLabel("Read"); + rangerAccessTypeDefObj.setName("read"); + rangerAccessTypeDefObj.setRbKeyLabel(null); + rangerAccessTypeDefList.add(rangerAccessTypeDefObj); + XXServiceDef xServiceDef = serviceDef(); + XXService xService = xService(); + XXServiceDefDao xServiceDefDao = Mockito.mock(XXServiceDefDao.class); + XXServiceDao xServiceDao = Mockito.mock(XXServiceDao.class); + + Mockito.when(validatorFactory.getPolicyValidator(svcStore)).thenReturn(policyValidator); + Mockito.when(bizUtil.isAdmin()).thenReturn(true); + Mockito.when(bizUtil.getCurrentUserLoginId()).thenReturn(userName); + Mockito.when(daoManager.getXXService()).thenReturn(xServiceDao); + Mockito.when(xServiceDao.findByName(Mockito.anyString())).thenReturn(xService); + Mockito.when(daoManager.getXXServiceDef()).thenReturn(xServiceDefDao); + Mockito.when(xServiceDefDao.getById(xService.getType())).thenReturn(xServiceDef); + RangerPolicy dbRangerPolicy = serviceREST.updatePolicy(rangerPolicy, policyId); + Assert.assertNull(dbRangerPolicy); + Mockito.verify(validatorFactory).getPolicyValidator(svcStore); + } + + @Test + public void test72updatePolicyWithInvalidPolicyId() { + RangerPolicy rangerPolicy = rangerPolicy(); + + Set userGroupsList = new HashSet<>(); + userGroupsList.add("group1"); + userGroupsList.add("group2"); + + List rangerAccessTypeDefList = new ArrayList<>(); + RangerAccessTypeDef rangerAccessTypeDefObj = new RangerAccessTypeDef(); + rangerAccessTypeDefObj.setLabel("Read"); + rangerAccessTypeDefObj.setName("read"); + rangerAccessTypeDefObj.setRbKeyLabel(null); + rangerAccessTypeDefList.add(rangerAccessTypeDefObj); + XXServiceDefDao xServiceDefDao = Mockito.mock(XXServiceDefDao.class); + XXServiceDao xServiceDao = Mockito.mock(XXServiceDao.class); + + Mockito.when(daoManager.getXXService()).thenReturn(xServiceDao); + Mockito.when(daoManager.getXXServiceDef()).thenReturn(xServiceDefDao); + Mockito.when(restErrorUtil.createRESTException(Mockito.anyInt(), Mockito.anyString(), Mockito.anyBoolean())).thenThrow(new WebApplicationException()); + thrown.expect(WebApplicationException.class); + RangerPolicy dbRangerPolicy = serviceREST.updatePolicy(rangerPolicy, -11L); + Assert.assertNull(dbRangerPolicy); + Mockito.verify(validatorFactory).getPolicyValidator(svcStore); + } + + @Test + public void test73updateServiceDefWhenIdIsNull() throws Exception { + RangerServiceDef rangerServiceDef = rangerServiceDef(); + rangerServiceDef.setId(null); + + Mockito.when(validatorFactory.getServiceDefValidator(svcStore)).thenReturn(serviceDefValidator); + Mockito.when(svcStore.updateServiceDef(Mockito.any())).thenReturn(rangerServiceDef); + + RangerServiceDef dbRangerServiceDef = serviceREST.updateServiceDef(rangerServiceDef, rangerServiceDef.getId()); + Assert.assertNotNull(dbRangerServiceDef); + Assert.assertEquals(dbRangerServiceDef, rangerServiceDef); + Assert.assertEquals(dbRangerServiceDef.getId(), rangerServiceDef.getId()); + Assert.assertEquals(dbRangerServiceDef.getName(), rangerServiceDef.getName()); + Assert.assertEquals(dbRangerServiceDef.getImplClass(), rangerServiceDef.getImplClass()); + Assert.assertEquals(dbRangerServiceDef.getLabel(), rangerServiceDef.getLabel()); + Assert.assertEquals(dbRangerServiceDef.getDescription(), rangerServiceDef.getDescription()); + Assert.assertEquals(dbRangerServiceDef.getRbKeyDescription(), rangerServiceDef.getRbKeyDescription()); + Assert.assertEquals(dbRangerServiceDef.getUpdatedBy(), rangerServiceDef.getUpdatedBy()); + Assert.assertEquals(dbRangerServiceDef.getUpdateTime(), rangerServiceDef.getUpdateTime()); + Assert.assertEquals(dbRangerServiceDef.getVersion(), rangerServiceDef.getVersion()); + Assert.assertEquals(dbRangerServiceDef.getConfigs(), rangerServiceDef.getConfigs()); + + Mockito.verify(validatorFactory).getServiceDefValidator(svcStore); + Mockito.verify(svcStore).updateServiceDef(rangerServiceDef); + } + + @Test + public void test74updateServiceDefWithInvalidDefId() throws Exception { + RangerServiceDef rangerServiceDef = rangerServiceDef(); + + Mockito.when(restErrorUtil.createRESTException(Mockito.anyInt(), Mockito.anyString(), Mockito.anyBoolean())).thenThrow(new WebApplicationException()); + thrown.expect(WebApplicationException.class); + + RangerServiceDef dbRangerServiceDef = serviceREST.updateServiceDef(rangerServiceDef, -1L); + Assert.assertNotNull(dbRangerServiceDef); + Assert.assertEquals(dbRangerServiceDef, rangerServiceDef); + Assert.assertEquals(dbRangerServiceDef.getId(), rangerServiceDef.getId()); + Assert.assertEquals(dbRangerServiceDef.getName(), rangerServiceDef.getName()); + Assert.assertEquals(dbRangerServiceDef.getImplClass(), rangerServiceDef.getImplClass()); + Assert.assertEquals(dbRangerServiceDef.getLabel(), rangerServiceDef.getLabel()); + Assert.assertEquals(dbRangerServiceDef.getDescription(), rangerServiceDef.getDescription()); + Assert.assertEquals(dbRangerServiceDef.getRbKeyDescription(), rangerServiceDef.getRbKeyDescription()); + Assert.assertEquals(dbRangerServiceDef.getUpdatedBy(), rangerServiceDef.getUpdatedBy()); + Assert.assertEquals(dbRangerServiceDef.getUpdateTime(), rangerServiceDef.getUpdateTime()); + Assert.assertEquals(dbRangerServiceDef.getVersion(), rangerServiceDef.getVersion()); + Assert.assertEquals(dbRangerServiceDef.getConfigs(), rangerServiceDef.getConfigs()); + + Mockito.verify(validatorFactory).getServiceDefValidator(svcStore); + Mockito.verify(svcStore).updateServiceDef(rangerServiceDef); + } + + @Test + public void test75GetPolicyByGUIDAndServiceNameAndZoneName() throws Exception { + RangerPolicy rangerPolicy = rangerPolicy(); + RangerService rangerService = rangerService(); + String serviceName = rangerService.getName(); + String zoneName = "zone-1"; + String userName = "admin"; + XXServiceDef xServiceDef = serviceDef(); + XXService xService = xService(); + XXServiceDefDao xServiceDefDao = Mockito.mock(XXServiceDefDao.class); + XXServiceDao xServiceDao = Mockito.mock(XXServiceDao.class); + Mockito.when(bizUtil.isAdmin()).thenReturn(true); + Mockito.when(bizUtil.getCurrentUserLoginId()).thenReturn(userName); + Mockito.when(daoManager.getXXService()).thenReturn(xServiceDao); + Mockito.when(xServiceDao.findByName(Mockito.anyString())).thenReturn(xService); + Mockito.when(daoManager.getXXServiceDef()).thenReturn(xServiceDefDao); + Mockito.when(xServiceDefDao.getById(xService.getType())).thenReturn(xServiceDef); + Mockito.when(svcStore.getPolicy(rangerPolicy.getGuid(), serviceName, zoneName)).thenReturn(rangerPolicy); + RangerPolicy dbRangerPolicy = serviceREST.getPolicyByGUIDAndServiceNameAndZoneName(rangerPolicy.getGuid(), serviceName, zoneName); + Assert.assertNotNull(dbRangerPolicy); + Assert.assertEquals(dbRangerPolicy.getId(), rangerPolicy.getId()); + Mockito.verify(svcStore).getPolicy(rangerPolicy.getGuid(), serviceName, zoneName); + } + + @Test + public void test76GetPolicyByGUID() throws Exception { + RangerPolicy rangerPolicy = rangerPolicy(); + String userName = "admin"; + + Set userGroupsList = new HashSet<>(); + userGroupsList.add("group1"); + userGroupsList.add("group2"); + + List rangerAccessTypeDefList = new ArrayList<>(); + RangerAccessTypeDef rangerAccessTypeDefObj = new RangerAccessTypeDef(); + rangerAccessTypeDefObj.setLabel("Read"); + rangerAccessTypeDefObj.setName("read"); + rangerAccessTypeDefObj.setRbKeyLabel(null); + rangerAccessTypeDefList.add(rangerAccessTypeDefObj); + XXServiceDef xServiceDef = serviceDef(); + XXService xService = xService(); + XXServiceDefDao xServiceDefDao = Mockito.mock(XXServiceDefDao.class); + XXServiceDao xServiceDao = Mockito.mock(XXServiceDao.class); + Mockito.when(bizUtil.isAdmin()).thenReturn(true); + Mockito.when(bizUtil.getCurrentUserLoginId()).thenReturn(userName); + Mockito.when(daoManager.getXXService()).thenReturn(xServiceDao); + Mockito.when(xServiceDao.findByName(Mockito.anyString())).thenReturn(xService); + Mockito.when(daoManager.getXXServiceDef()).thenReturn(xServiceDefDao); + Mockito.when(xServiceDefDao.getById(xService.getType())).thenReturn(xServiceDef); + Mockito.when(svcStore.getPolicy(rangerPolicy.getGuid(), null, null)).thenReturn(rangerPolicy); + RangerPolicy dbRangerPolicy = serviceREST.getPolicyByGUIDAndServiceNameAndZoneName(rangerPolicy.getGuid(), null, null); + Assert.assertNotNull(dbRangerPolicy); + Assert.assertEquals(dbRangerPolicy.getId(), rangerPolicy.getId()); + Mockito.verify(svcStore).getPolicy(rangerPolicy.getGuid(), null, null); + } + + @Test + public void test76DeletePolicyByGUIDAndServiceNameAndZoneName() throws Exception { + RangerPolicy rangerPolicy = rangerPolicy(); + RangerService rangerService = rangerService(); + String serviceName = rangerService.getName(); + Mockito.when(validatorFactory.getPolicyValidator(svcStore)).thenReturn(policyValidator); + String zoneName = "zone-1"; + String userName = "admin"; + XXServiceDef xServiceDef = serviceDef(); + XXService xService = xService(); + XXServiceDefDao xServiceDefDao = Mockito.mock(XXServiceDefDao.class); + XXServiceDao xServiceDao = Mockito.mock(XXServiceDao.class); + Mockito.when(bizUtil.isAdmin()).thenReturn(true); + Mockito.when(bizUtil.getCurrentUserLoginId()).thenReturn(userName); + Mockito.when(daoManager.getXXService()).thenReturn(xServiceDao); + Mockito.when(xServiceDao.findByName(Mockito.anyString())).thenReturn(xService); + Mockito.when(daoManager.getXXServiceDef()).thenReturn(xServiceDefDao); + Mockito.when(xServiceDefDao.getById(xService.getType())).thenReturn(xServiceDef); + Mockito.when(svcStore.getPolicy(Id)).thenReturn(rangerPolicy); + Mockito.when(svcStore.getPolicy(rangerPolicy.getGuid(), serviceName, zoneName)).thenReturn(rangerPolicy); + serviceREST.deletePolicyByGUIDAndServiceNameAndZoneName(rangerPolicy.getGuid(), serviceName, zoneName); + Mockito.verify(validatorFactory).getPolicyValidator(svcStore); + Mockito.verify(svcStore).getPolicy(rangerPolicy.getGuid(), serviceName, zoneName); + } + + @Test + public void test77DeletePolicyByGUID() throws Exception { + RangerPolicy rangerPolicy = rangerPolicy(); + Mockito.when(validatorFactory.getPolicyValidator(svcStore)).thenReturn(policyValidator); + String userName = "admin"; + XXServiceDef xServiceDef = serviceDef(); + XXService xService = xService(); + XXServiceDefDao xServiceDefDao = Mockito.mock(XXServiceDefDao.class); + XXServiceDao xServiceDao = Mockito.mock(XXServiceDao.class); + Mockito.when(bizUtil.isAdmin()).thenReturn(true); + Mockito.when(bizUtil.getCurrentUserLoginId()).thenReturn(userName); + Mockito.when(daoManager.getXXService()).thenReturn(xServiceDao); + Mockito.when(xServiceDao.findByName(Mockito.anyString())).thenReturn(xService); + Mockito.when(daoManager.getXXServiceDef()).thenReturn(xServiceDefDao); + Mockito.when(xServiceDefDao.getById(xService.getType())).thenReturn(xServiceDef); + Mockito.when(svcStore.getPolicy(Id)).thenReturn(rangerPolicy); + Mockito.when(svcStore.getPolicy(rangerPolicy.getGuid(), null, null)).thenReturn(rangerPolicy); + serviceREST.deletePolicyByGUIDAndServiceNameAndZoneName(rangerPolicy.getGuid(), null, null); + Mockito.verify(validatorFactory).getPolicyValidator(svcStore); + Mockito.verify(svcStore).getPolicy(rangerPolicy.getGuid(), null, null); + } + + @Test + public void test78ResetPolicyCacheByServiceNameForServiceAdmin() { + boolean isAdmin = false; + boolean res = true; + RangerService rangerService = rangerService(); + String serviceName = rangerService.getName(); + Mockito.when(bizUtil.isAdmin()).thenReturn(isAdmin); + String userName = "admin"; + Mockito.when(bizUtil.getCurrentUserLoginId()).thenReturn(userName); + try { + Mockito.when(svcStore.getServiceByName(serviceName)).thenReturn(rangerService); + } catch (Exception ignored) { + } + Mockito.when(bizUtil.isUserServiceAdmin(Mockito.any(RangerService.class), Mockito.anyString())).thenReturn(true); + try { + Mockito.when(svcStore.resetPolicyCache(serviceName)).thenReturn(true); + } catch (Exception ignored) { + } + boolean isReset = serviceREST.resetPolicyCache(serviceName); + Assert.assertEquals(res, isReset); + Mockito.verify(bizUtil).isAdmin(); + Mockito.verify(bizUtil).isUserServiceAdmin(Mockito.any(RangerService.class), Mockito.anyString()); + try { + Mockito.verify(svcStore).getServiceByName(serviceName); + } catch (Exception ignored) { + } + try { + Mockito.verify(svcStore).resetPolicyCache(serviceName); + } catch (Exception ignored) { + } + } + + @Test + public void test79ResetPolicyCacheWhenServiceNameIsInvalid() { + String serviceName = "HDFS_1"; + try { + Mockito.when(svcStore.getServiceByName(serviceName)).thenReturn(null); + } catch (Exception ignored) { + } + Mockito.when(restErrorUtil.createRESTException(Mockito.anyInt(), Mockito.anyString(), Mockito.anyBoolean())).thenThrow(new WebApplicationException()); + thrown.expect(WebApplicationException.class); + serviceREST.resetPolicyCache(serviceName); + Mockito.verify(restErrorUtil).createRESTException(Mockito.anyInt(), Mockito.anyString(), Mockito.anyBoolean()); + } + + @Test + public void test80GetPolicyByNameAndServiceNameWithZoneName() { + RangerPolicy rangerPolicy = rangerPolicy(); + RangerService rangerService = rangerService(); + XXPolicy xxPolicy = new XXPolicy(); + String serviceName = rangerService.getName(); + String policyName = rangerPolicy.getName(); + String zoneName = "zone-1"; + XXPolicyDao xXPolicyDao = Mockito.mock(XXPolicyDao.class); + Mockito.when(daoManager.getXXPolicy()).thenReturn(xXPolicyDao); + Mockito.when(daoManager.getXXPolicy().findPolicy(policyName, serviceName, zoneName)).thenReturn(xxPolicy); + Mockito.when(policyService.getPopulatedViewObject(xxPolicy)).thenReturn(rangerPolicy); + Mockito.when(bizUtil.isAdmin()).thenReturn(true); + RangerPolicy dbRangerPolicy = serviceREST.getPolicyByName(serviceName, policyName, zoneName); + Assert.assertNotNull(dbRangerPolicy); + Assert.assertEquals(dbRangerPolicy, rangerPolicy); + Assert.assertEquals(dbRangerPolicy.getId(), rangerPolicy.getId()); + Assert.assertEquals(dbRangerPolicy.getName(), rangerPolicy.getName()); + } + + @Test + public void test81GetPolicyByNameAndServiceNameWithZoneNameIsNull() { + RangerPolicy rangerPolicy = rangerPolicy(); + RangerService rangerService = rangerService(); + XXPolicy xxPolicy = new XXPolicy(); + String serviceName = rangerService.getName(); + String policyName = rangerPolicy.getName(); + XXPolicyDao xXPolicyDao = Mockito.mock(XXPolicyDao.class); + Mockito.when(daoManager.getXXPolicy()).thenReturn(xXPolicyDao); + Mockito.when(daoManager.getXXPolicy().findPolicy(policyName, serviceName, null)).thenReturn(xxPolicy); + Mockito.when(policyService.getPopulatedViewObject(xxPolicy)).thenReturn(rangerPolicy); + Mockito.when(bizUtil.isAdmin()).thenReturn(true); + RangerPolicy dbRangerPolicy = serviceREST.getPolicyByName(serviceName, policyName, null); + Assert.assertNotNull(dbRangerPolicy); + Assert.assertEquals(dbRangerPolicy, rangerPolicy); + Assert.assertEquals(dbRangerPolicy.getId(), rangerPolicy.getId()); + Assert.assertEquals(dbRangerPolicy.getName(), rangerPolicy.getName()); + } + + RangerPolicy rangerPolicy() { + List accesses = new ArrayList<>(); + List users = new ArrayList<>(); + List groups = new ArrayList<>(); + List conditions = new ArrayList<>(); + List policyItems = new ArrayList<>(); + RangerPolicyItem rangerPolicyItem = new RangerPolicyItem(); + rangerPolicyItem.setAccesses(accesses); + rangerPolicyItem.setConditions(conditions); + rangerPolicyItem.setGroups(groups); + rangerPolicyItem.setUsers(users); + rangerPolicyItem.setDelegateAdmin(false); + + policyItems.add(rangerPolicyItem); + + Map policyResource = new HashMap<>(); + RangerPolicyResource rangerPolicyResource = new RangerPolicyResource(); + rangerPolicyResource.setIsExcludes(true); + rangerPolicyResource.setIsRecursive(true); + rangerPolicyResource.setValue("1"); + rangerPolicyResource.setValues(users); + policyResource.put("resource", rangerPolicyResource); + RangerPolicy policy = new RangerPolicy(); + policy.setId(Id); + policy.setCreateTime(new Date()); + policy.setDescription("policy"); + policy.setGuid("policyguid"); + policy.setIsEnabled(true); + policy.setName("HDFS_1-1-20150316062453"); + policy.setUpdatedBy("Admin"); + policy.setUpdateTime(new Date()); + policy.setService("HDFS_1-1-20150316062453"); + policy.setIsAuditEnabled(true); + policy.setPolicyItems(policyItems); + policy.setResources(policyResource); + + return policy; + } + + private List createLongList() { + List list = new ArrayList<>(); + list.add(1L); + list.add(2L); + list.add(3L); + return list; + } + + private ArrayList createUserList() { + ArrayList userList = new ArrayList<>(); + userList.add("test-user-1"); + return userList; + } + + private ArrayList createGroupList() { + ArrayList groupList = new ArrayList<>(); + groupList.add("test-group-1"); + return groupList; + } + + private ArrayList createRoleList() { + ArrayList roleList = new ArrayList<>(); + roleList.add("test-role-1"); + return roleList; + } + + private ArrayList createGrantorGroupList() { + ArrayList grantorGroupList = new ArrayList<>(); + grantorGroupList.add("test-grantor-group-1"); + return grantorGroupList; + } + + private HashMap createResourceMap() { + HashMap resourceMap = new HashMap<>(); + resourceMap.put("test-resource-1", "test-resource-value-1"); + return resourceMap; + } + + private ArrayList createAccessTypeList() { + ArrayList accessTypeList = new ArrayList<>(); + accessTypeList.add("test-access-type-1"); + return accessTypeList; + } + + private GrantRevokeRequest createValidGrantRevokeRequest() { + GrantRevokeRequest grantRevokeRequest = new GrantRevokeRequest(); + grantRevokeRequest.setUsers(new HashSet<>(createUserList())); + grantRevokeRequest.setGroups(new HashSet<>(createGroupList())); + grantRevokeRequest.setRoles(new HashSet<>(createRoleList())); + grantRevokeRequest.setGrantor(grantor); + grantRevokeRequest.setGrantorGroups(new HashSet<>(createGrantorGroupList())); + grantRevokeRequest.setOwnerUser(ownerUser); + grantRevokeRequest.setResource(createResourceMap()); + grantRevokeRequest.setAccessTypes(new HashSet<>(createAccessTypeList())); + grantRevokeRequest.setZoneName(zoneName); + grantRevokeRequest.setIsRecursive(true); + return grantRevokeRequest; + } + + private File getFile(String testFilePath) throws IOException { + File jsonPolicyFile = new File(testFilePath); + if (jsonPolicyFile.getCanonicalPath().contains("/target/jstest")) { + jsonPolicyFile = new File(jsonPolicyFile.getCanonicalPath().replace("/target/jstest", "")); + } + return jsonPolicyFile; + } } diff --git a/security-admin/src/test/java/org/apache/ranger/rest/TestServiceTagProcessor.java b/security-admin/src/test/java/org/apache/ranger/rest/TestServiceTagProcessor.java index 952463318b..46b44806ce 100644 --- a/security-admin/src/test/java/org/apache/ranger/rest/TestServiceTagProcessor.java +++ b/security-admin/src/test/java/org/apache/ranger/rest/TestServiceTagProcessor.java @@ -15,15 +15,9 @@ * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. - -*/ -package org.apache.ranger.rest; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; + */ +package org.apache.ranger.rest; import org.apache.ranger.common.RangerValidatorFactory; import org.apache.ranger.plugin.model.RangerPolicy; @@ -42,244 +36,243 @@ import org.mockito.Mock; import org.mockito.Mockito; -public class TestServiceTagProcessor { - - @InjectMocks - ServiceTagsProcessor sTagProcessor = new ServiceTagsProcessor(null); - - @Mock - ServiceTags serviceTags; - - @Mock - RangerValidatorFactory validatorFactory; - - @Mock - TestServiceREST testServiceRest; - - @Rule - public ExpectedException thrown = ExpectedException.none(); - - @Test - public void test1processError() throws Exception { - ServiceTagsProcessor sTagProcessor = new ServiceTagsProcessor(null); - sTagProcessor.process(serviceTags); - Assert.assertNull(serviceTags); - } - - @Test - public void test2processAddOrUpdate() throws Exception { - serviceTags = new ServiceTags(); - Map fd = new HashMap<>(); - List associatedTags = new ArrayList<>(); - RangerTagDef rTagDef = Mockito.mock(RangerTagDef.class); - rTagDef.setGuid("guid"); - rTagDef.setName("rTagDefname"); - fd.put(1l, rTagDef); - serviceTags.setTagDefinitions(fd); - List serviceResources = new ArrayList(); - RangerServiceResource rserRes = new RangerServiceResource(); - testServiceRest = new TestServiceREST(); - RangerPolicy rp = testServiceRest.rangerPolicy(); - rserRes.setResourceElements(rp.getResources()); - rserRes.setGuid("guId"); - rserRes.setId(1L); - serviceResources.add(rserRes); - serviceTags.setServiceResources(serviceResources); - Map> resourceToTagIds = new HashMap<>(); - resourceToTagIds.put(1L, new ArrayList(Arrays.asList(11L, 1L, 13L))); - serviceTags.setResourceToTagIds(resourceToTagIds); - - RangerTag rTag = new RangerTag(); - rTag.setId(22L); - rTag.setOwner((short) 1); - Map tags = new HashMap<>(); - tags.put(1L, rTag); - serviceTags.setTags(tags); - - RangerTag rTag2 = new RangerTag(); - rTag2.setId(22L); - rTag2.setOwner((short) 1); - Map tags2 = new HashMap<>(); - tags2.put(1L, rTag2); - associatedTags.add(rTag2); - - TagStore tagStore = Mockito.mock(TagStore.class); - sTagProcessor = new ServiceTagsProcessor(tagStore); - Mockito.when(tagStore.createTagDef(rTagDef)).thenReturn(rTagDef); - Mockito.when(tagStore.getServiceResourceByGuid(rserRes.getGuid())).thenReturn(rserRes); - Mockito.when(tagStore.createTag(rTag2)).thenReturn(rTag); - - Mockito.when(tagStore.getTagsForResourceId(rserRes.getId())).thenReturn(associatedTags); - sTagProcessor.process(serviceTags); - Mockito.verify(tagStore).createTagDef(rTagDef); - Mockito.verify(tagStore).getServiceResourceByGuid(rserRes.getGuid()); - Mockito.verify(tagStore).createTag(rTag2); - } - - @Test - public void test3process() throws Exception { - serviceTags = new ServiceTags(); - Map fd = new HashMap<>(); - List associatedTags = new ArrayList<>(); - RangerTagDef rTagDef = Mockito.mock(RangerTagDef.class); - rTagDef.setGuid("guid"); - rTagDef.setName("rTagDefname"); - fd.put(1l, rTagDef); - serviceTags.setTagDefinitions(fd); - List serviceResources = new ArrayList(); - RangerServiceResource rserRes = new RangerServiceResource(); - testServiceRest = new TestServiceREST(); - RangerPolicy rp = testServiceRest.rangerPolicy(); - rserRes.setResourceElements(rp.getResources()); - rserRes.setGuid("guId"); - rserRes.setId(1L); - serviceResources.add(rserRes); - serviceTags.setServiceResources(serviceResources); - - Map> resourceToTagIds = new HashMap<>(); - resourceToTagIds.put(1L, new ArrayList(Arrays.asList(22L, 1L, 0L))); - serviceTags.setResourceToTagIds(resourceToTagIds); - - RangerTag rTag = new RangerTag(); - rTag.setId(22L); - rTag.setType("type1"); - Map tags = new HashMap<>(); - rTag.setOwner((short) 0); - tags.put(1L, rTag); - serviceTags.setTags(tags); - - associatedTags.add(rTag); - - TagStore tagStore = Mockito.mock(TagStore.class); - sTagProcessor = new ServiceTagsProcessor(tagStore); - Mockito.when(tagStore.createTagDef(rTagDef)).thenReturn(rTagDef); - Mockito.when(tagStore.getServiceResourceByGuid(rserRes.getGuid())).thenReturn(rserRes); - Mockito.when(tagStore.getTagsForResourceId(rserRes.getId())).thenReturn(associatedTags); - - sTagProcessor.process(serviceTags); - - Mockito.verify(tagStore).createTagDef(rTagDef); - Mockito.verify(tagStore).getServiceResourceByGuid(rserRes.getGuid()); - Mockito.verify(tagStore).getTagsForResourceId(rserRes.getId()); - } - - @Test - public void test4processDelete() throws Exception { - serviceTags = new ServiceTags(); - serviceTags.setOp(ServiceTags.OP_DELETE); - Map fd = new HashMap<>(); - List associatedTags = new ArrayList<>(); - RangerTagDef rTagDef = Mockito.mock(RangerTagDef.class); - rTagDef.setGuid("guid"); - rTagDef.setName("rTagDefName"); - fd.put(1l, rTagDef); - serviceTags.setTagDefinitions(fd); - List serviceResources = new ArrayList(); - RangerServiceResource rserRes = new RangerServiceResource(); - testServiceRest = new TestServiceREST(); - RangerPolicy rp = testServiceRest.rangerPolicy(); - rserRes.setResourceElements(rp.getResources()); - rserRes.setGuid("guId"); - rserRes.setId(1L); - rserRes.setServiceName("serviceName1"); - serviceResources.add(rserRes); - serviceTags.setServiceResources(serviceResources); - List tagResourceMaps = new ArrayList(); - tagResourceMaps.add(new RangerTagResourceMap()); - Map> resourceToTagIds = new HashMap<>(); - resourceToTagIds.put(1L, new ArrayList(Arrays.asList(22L, 1L, 0L))); - serviceTags.setResourceToTagIds(resourceToTagIds); - - RangerTag rTag = new RangerTag(); - rTag.setId(22L); - rTag.setType("type1"); - rTag.setGuid("tagGuID"); - Map tags = new HashMap<>(); - rTag.setOwner((short) 0); - tags.put(1L, rTag); - serviceTags.setTags(tags); - - RangerServiceResourceSignature serializer = new RangerServiceResourceSignature(rserRes); - String serviceResourceSignature = serializer.getSignature(); - associatedTags.add(rTag); - TagStore tagStore = Mockito.mock(TagStore.class); - sTagProcessor = new ServiceTagsProcessor(tagStore); - - Mockito.when(tagStore.getServiceResourceByGuid(rserRes.getGuid())).thenReturn(null); - Mockito.when(tagStore.getServiceResourceByServiceAndResourceSignature(rserRes.getServiceName(), - serviceResourceSignature)).thenReturn(rserRes); - Mockito.when(tagStore.getTagResourceMapsForResourceGuid(rserRes.getGuid())).thenReturn(tagResourceMaps); - Mockito.doNothing().when(tagStore).deleteServiceResource(rserRes.getId()); - Mockito.when(tagStore.getTagByGuid(rTag.getGuid())).thenReturn(rTag); - Mockito.doNothing().when(tagStore).deleteTag(rTag.getId()); - Mockito.when(tagStore.getTagDefByGuid(rTagDef.getGuid())).thenReturn(rTagDef); - - sTagProcessor.process(serviceTags); - - Mockito.verify(tagStore).getServiceResourceByGuid(rserRes.getGuid()); - Mockito.verify(tagStore).getServiceResourceByServiceAndResourceSignature(rserRes.getServiceName(), - serviceResourceSignature); - Mockito.verify(tagStore).getTagResourceMapsForResourceGuid(rserRes.getGuid()); - Mockito.verify(tagStore).deleteServiceResource(rserRes.getId()); - Mockito.verify(tagStore).getTagByGuid(rTag.getGuid()); - Mockito.verify(tagStore).deleteTag(rTag.getId()); - Mockito.verify(tagStore).getTagDefByGuid(rTagDef.getGuid()); - } - - @Test - public void test5processReplace() throws Exception { - serviceTags = new ServiceTags(); - serviceTags.setOp(ServiceTags.OP_REPLACE); - Map fd = new HashMap<>(); - List associatedTags = new ArrayList<>(); - RangerTagDef rTagDef = Mockito.mock(RangerTagDef.class); - rTagDef.setGuid("guid"); - rTagDef.setName("rTagDefName"); - fd.put(1l, rTagDef); - serviceTags.setTagDefinitions(fd); - List serviceResources = new ArrayList(); - RangerServiceResource rserRes = new RangerServiceResource(); - testServiceRest = new TestServiceREST(); - RangerPolicy rp = testServiceRest.rangerPolicy(); - rserRes.setResourceElements(rp.getResources()); - rserRes.setGuid("guId"); - rserRes.setId(1L); - rserRes.setServiceName("serviceName1"); - serviceResources.add(rserRes); - serviceTags.setServiceResources(serviceResources); - List tagResourceMaps = new ArrayList(); - serviceTags.setServiceName("tagServiceName"); - RangerTagResourceMap rangerTagRmp = new RangerTagResourceMap(); - rangerTagRmp.setId(2L); - tagResourceMaps.add(rangerTagRmp); - Map> resourceToTagIds = new HashMap<>(); - resourceToTagIds.put(1L, new ArrayList(Arrays.asList(22L, 1L, 0L))); - serviceTags.setResourceToTagIds(resourceToTagIds); - - RangerTag rTag = new RangerTag(); - rTag.setId(22L); - rTag.setType("type1"); - rTag.setGuid("tagGuID"); - Map tags = new HashMap<>(); - rTag.setOwner((short) 0); - tags.put(1L, rTag); - serviceTags.setTags(tags); - associatedTags.add(rTag); - TagStore tagStore = Mockito.mock(TagStore.class); - sTagProcessor = new ServiceTagsProcessor(tagStore); - - List serviceResourcesInDb = new ArrayList<>(Arrays.asList("guid")); - Mockito.when(tagStore.getServiceResourceGuidsByService(serviceTags.getServiceName())) - .thenReturn(serviceResourcesInDb); - Mockito.when(tagStore.getTagResourceMapsForResourceGuid(Mockito.anyString())).thenReturn(tagResourceMaps); - Mockito.doNothing().when(tagStore).deleteTagResourceMap(rangerTagRmp.getId()); - Mockito.doNothing().when(tagStore).deleteServiceResourceByGuid(Mockito.anyString()); - - sTagProcessor.process(serviceTags); +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; - Mockito.verify(tagStore).getServiceResourceGuidsByService(serviceTags.getServiceName()); - Mockito.verify(tagStore).getTagResourceMapsForResourceGuid(Mockito.anyString()); - Mockito.verify(tagStore).deleteTagResourceMap(rangerTagRmp.getId()); - Mockito.verify(tagStore).deleteServiceResourceByGuid(Mockito.anyString()); - } +public class TestServiceTagProcessor { + @Rule + public ExpectedException thrown = ExpectedException.none(); + @InjectMocks + ServiceTagsProcessor sTagProcessor = new ServiceTagsProcessor(null); + @Mock + ServiceTags serviceTags; + @Mock + RangerValidatorFactory validatorFactory; + @Mock + TestServiceREST testServiceRest; + + @Test + public void test1processError() throws Exception { + ServiceTagsProcessor sTagProcessor = new ServiceTagsProcessor(null); + sTagProcessor.process(serviceTags); + Assert.assertNull(serviceTags); + } + + @Test + public void test2processAddOrUpdate() throws Exception { + serviceTags = new ServiceTags(); + Map fd = new HashMap<>(); + List associatedTags = new ArrayList<>(); + RangerTagDef rTagDef = Mockito.mock(RangerTagDef.class); + rTagDef.setGuid("guid"); + rTagDef.setName("rTagDefname"); + fd.put(1L, rTagDef); + serviceTags.setTagDefinitions(fd); + List serviceResources = new ArrayList<>(); + RangerServiceResource rserRes = new RangerServiceResource(); + testServiceRest = new TestServiceREST(); + RangerPolicy rp = testServiceRest.rangerPolicy(); + rserRes.setResourceElements(rp.getResources()); + rserRes.setGuid("guId"); + rserRes.setId(1L); + serviceResources.add(rserRes); + serviceTags.setServiceResources(serviceResources); + Map> resourceToTagIds = new HashMap<>(); + resourceToTagIds.put(1L, new ArrayList<>(Arrays.asList(11L, 1L, 13L))); + serviceTags.setResourceToTagIds(resourceToTagIds); + + RangerTag rTag = new RangerTag(); + rTag.setId(22L); + rTag.setOwner((short) 1); + Map tags = new HashMap<>(); + tags.put(1L, rTag); + serviceTags.setTags(tags); + + RangerTag rTag2 = new RangerTag(); + rTag2.setId(22L); + rTag2.setOwner((short) 1); + Map tags2 = new HashMap<>(); + tags2.put(1L, rTag2); + associatedTags.add(rTag2); + + TagStore tagStore = Mockito.mock(TagStore.class); + sTagProcessor = new ServiceTagsProcessor(tagStore); + Mockito.when(tagStore.createTagDef(rTagDef)).thenReturn(rTagDef); + Mockito.when(tagStore.getServiceResourceByGuid(rserRes.getGuid())).thenReturn(rserRes); + Mockito.when(tagStore.createTag(rTag2)).thenReturn(rTag); + + Mockito.when(tagStore.getTagsForResourceId(rserRes.getId())).thenReturn(associatedTags); + sTagProcessor.process(serviceTags); + Mockito.verify(tagStore).createTagDef(rTagDef); + Mockito.verify(tagStore).getServiceResourceByGuid(rserRes.getGuid()); + Mockito.verify(tagStore).createTag(rTag2); + } + + @Test + public void test3process() throws Exception { + serviceTags = new ServiceTags(); + Map fd = new HashMap<>(); + List associatedTags = new ArrayList<>(); + RangerTagDef rTagDef = Mockito.mock(RangerTagDef.class); + rTagDef.setGuid("guid"); + rTagDef.setName("rTagDefname"); + fd.put(1L, rTagDef); + serviceTags.setTagDefinitions(fd); + List serviceResources = new ArrayList<>(); + RangerServiceResource rserRes = new RangerServiceResource(); + testServiceRest = new TestServiceREST(); + RangerPolicy rp = testServiceRest.rangerPolicy(); + rserRes.setResourceElements(rp.getResources()); + rserRes.setGuid("guId"); + rserRes.setId(1L); + serviceResources.add(rserRes); + serviceTags.setServiceResources(serviceResources); + + Map> resourceToTagIds = new HashMap<>(); + resourceToTagIds.put(1L, new ArrayList<>(Arrays.asList(22L, 1L, 0L))); + serviceTags.setResourceToTagIds(resourceToTagIds); + + RangerTag rTag = new RangerTag(); + rTag.setId(22L); + rTag.setType("type1"); + Map tags = new HashMap<>(); + rTag.setOwner((short) 0); + tags.put(1L, rTag); + serviceTags.setTags(tags); + + associatedTags.add(rTag); + + TagStore tagStore = Mockito.mock(TagStore.class); + sTagProcessor = new ServiceTagsProcessor(tagStore); + Mockito.when(tagStore.createTagDef(rTagDef)).thenReturn(rTagDef); + Mockito.when(tagStore.getServiceResourceByGuid(rserRes.getGuid())).thenReturn(rserRes); + Mockito.when(tagStore.getTagsForResourceId(rserRes.getId())).thenReturn(associatedTags); + + sTagProcessor.process(serviceTags); + + Mockito.verify(tagStore).createTagDef(rTagDef); + Mockito.verify(tagStore).getServiceResourceByGuid(rserRes.getGuid()); + Mockito.verify(tagStore).getTagsForResourceId(rserRes.getId()); + } + + @Test + public void test4processDelete() throws Exception { + serviceTags = new ServiceTags(); + serviceTags.setOp(ServiceTags.OP_DELETE); + Map fd = new HashMap<>(); + List associatedTags = new ArrayList<>(); + RangerTagDef rTagDef = Mockito.mock(RangerTagDef.class); + rTagDef.setGuid("guid"); + rTagDef.setName("rTagDefName"); + fd.put(1L, rTagDef); + serviceTags.setTagDefinitions(fd); + List serviceResources = new ArrayList<>(); + RangerServiceResource rserRes = new RangerServiceResource(); + testServiceRest = new TestServiceREST(); + RangerPolicy rp = testServiceRest.rangerPolicy(); + rserRes.setResourceElements(rp.getResources()); + rserRes.setGuid("guId"); + rserRes.setId(1L); + rserRes.setServiceName("serviceName1"); + serviceResources.add(rserRes); + serviceTags.setServiceResources(serviceResources); + List tagResourceMaps = new ArrayList<>(); + tagResourceMaps.add(new RangerTagResourceMap()); + Map> resourceToTagIds = new HashMap<>(); + resourceToTagIds.put(1L, new ArrayList<>(Arrays.asList(22L, 1L, 0L))); + serviceTags.setResourceToTagIds(resourceToTagIds); + + RangerTag rTag = new RangerTag(); + rTag.setId(22L); + rTag.setType("type1"); + rTag.setGuid("tagGuID"); + Map tags = new HashMap<>(); + rTag.setOwner((short) 0); + tags.put(1L, rTag); + serviceTags.setTags(tags); + + RangerServiceResourceSignature serializer = new RangerServiceResourceSignature(rserRes); + String serviceResourceSignature = serializer.getSignature(); + associatedTags.add(rTag); + TagStore tagStore = Mockito.mock(TagStore.class); + sTagProcessor = new ServiceTagsProcessor(tagStore); + + Mockito.when(tagStore.getServiceResourceByGuid(rserRes.getGuid())).thenReturn(null); + Mockito.when(tagStore.getServiceResourceByServiceAndResourceSignature(rserRes.getServiceName(), serviceResourceSignature)).thenReturn(rserRes); + Mockito.when(tagStore.getTagResourceMapsForResourceGuid(rserRes.getGuid())).thenReturn(tagResourceMaps); + Mockito.doNothing().when(tagStore).deleteServiceResource(rserRes.getId()); + Mockito.when(tagStore.getTagByGuid(rTag.getGuid())).thenReturn(rTag); + Mockito.doNothing().when(tagStore).deleteTag(rTag.getId()); + Mockito.when(tagStore.getTagDefByGuid(rTagDef.getGuid())).thenReturn(rTagDef); + + sTagProcessor.process(serviceTags); + + Mockito.verify(tagStore).getServiceResourceByGuid(rserRes.getGuid()); + Mockito.verify(tagStore).getServiceResourceByServiceAndResourceSignature(rserRes.getServiceName(), serviceResourceSignature); + Mockito.verify(tagStore).getTagResourceMapsForResourceGuid(rserRes.getGuid()); + Mockito.verify(tagStore).deleteServiceResource(rserRes.getId()); + Mockito.verify(tagStore).getTagByGuid(rTag.getGuid()); + Mockito.verify(tagStore).deleteTag(rTag.getId()); + Mockito.verify(tagStore).getTagDefByGuid(rTagDef.getGuid()); + } + + @Test + public void test5processReplace() throws Exception { + serviceTags = new ServiceTags(); + serviceTags.setOp(ServiceTags.OP_REPLACE); + Map fd = new HashMap<>(); + List associatedTags = new ArrayList<>(); + RangerTagDef rTagDef = Mockito.mock(RangerTagDef.class); + rTagDef.setGuid("guid"); + rTagDef.setName("rTagDefName"); + fd.put(1L, rTagDef); + serviceTags.setTagDefinitions(fd); + List serviceResources = new ArrayList<>(); + RangerServiceResource rserRes = new RangerServiceResource(); + testServiceRest = new TestServiceREST(); + RangerPolicy rp = testServiceRest.rangerPolicy(); + rserRes.setResourceElements(rp.getResources()); + rserRes.setGuid("guId"); + rserRes.setId(1L); + rserRes.setServiceName("serviceName1"); + serviceResources.add(rserRes); + serviceTags.setServiceResources(serviceResources); + List tagResourceMaps = new ArrayList<>(); + serviceTags.setServiceName("tagServiceName"); + RangerTagResourceMap rangerTagRmp = new RangerTagResourceMap(); + rangerTagRmp.setId(2L); + tagResourceMaps.add(rangerTagRmp); + Map> resourceToTagIds = new HashMap<>(); + resourceToTagIds.put(1L, new ArrayList<>(Arrays.asList(22L, 1L, 0L))); + serviceTags.setResourceToTagIds(resourceToTagIds); + + RangerTag rTag = new RangerTag(); + rTag.setId(22L); + rTag.setType("type1"); + rTag.setGuid("tagGuID"); + Map tags = new HashMap<>(); + rTag.setOwner((short) 0); + tags.put(1L, rTag); + serviceTags.setTags(tags); + associatedTags.add(rTag); + TagStore tagStore = Mockito.mock(TagStore.class); + sTagProcessor = new ServiceTagsProcessor(tagStore); + + List serviceResourcesInDb = new ArrayList<>(Collections.singletonList("guid")); + Mockito.when(tagStore.getServiceResourceGuidsByService(serviceTags.getServiceName())).thenReturn(serviceResourcesInDb); + Mockito.when(tagStore.getTagResourceMapsForResourceGuid(Mockito.anyString())).thenReturn(tagResourceMaps); + Mockito.doNothing().when(tagStore).deleteTagResourceMap(rangerTagRmp.getId()); + Mockito.doNothing().when(tagStore).deleteServiceResourceByGuid(Mockito.anyString()); + + sTagProcessor.process(serviceTags); + + Mockito.verify(tagStore).getServiceResourceGuidsByService(serviceTags.getServiceName()); + Mockito.verify(tagStore).getTagResourceMapsForResourceGuid(Mockito.anyString()); + Mockito.verify(tagStore).deleteTagResourceMap(rangerTagRmp.getId()); + Mockito.verify(tagStore).deleteServiceResourceByGuid(Mockito.anyString()); + } } diff --git a/security-admin/src/test/java/org/apache/ranger/rest/TestTagREST.java b/security-admin/src/test/java/org/apache/ranger/rest/TestTagREST.java index 34122dd799..8766817b59 100755 --- a/security-admin/src/test/java/org/apache/ranger/rest/TestTagREST.java +++ b/security-admin/src/test/java/org/apache/ranger/rest/TestTagREST.java @@ -16,14 +16,6 @@ */ package org.apache.ranger.rest; -import static org.mockito.ArgumentMatchers.eq; - -import java.util.ArrayList; -import java.util.List; - -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.WebApplicationException; - import org.apache.ranger.biz.AssetMgr; import org.apache.ranger.biz.RangerBizUtil; import org.apache.ranger.biz.ServiceDBStore; @@ -63,1955 +55,1948 @@ import org.mockito.Mockito; import org.mockito.junit.MockitoJUnitRunner; +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.WebApplicationException; + +import java.util.ArrayList; +import java.util.List; + +import static org.mockito.ArgumentMatchers.eq; + @RunWith(MockitoJUnitRunner.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class TestTagREST { - private static Long id = 1L; - private static String gId = "1427365526516_835_0"; - private static String name = "test"; - private static String serviceName = "HDFS"; - private static String resourceSignature = "testResourceSign"; - private static String tagGuid = "8787878787_09_1"; - private static String resourceGuid = "9898989898_09_1"; - private static Long lastKnownVersion = 10L; - private static String pluginId = "1"; - private static String Allowed_User_List_For_Tag_Download = "tag.download.auth.users"; - - @InjectMocks - TagREST tagREST = new TagREST(); - - @Mock - TagValidator validator; - - @Mock - TagDBStore tagStore; - - @Mock - RESTErrorUtil restErrorUtil; - - @Mock - RangerBizUtil bizUtil; - - @Mock - RangerDaoManager daoManager; - - @Mock - ServiceDBStore svcStore; - - @Mock - AssetMgr assetMgr; - - @Mock - RangerSearchUtil searchUtil; - - @Mock - RangerTagDefService tagDefService; - - @Mock - RangerTagService tagService; - - @Mock - RangerServiceResourceService resourceService; - - @Mock - RangerServiceResourceWithTagsService serviceResourceWithTagsService; - - @Rule - public ExpectedException thrown = ExpectedException.none(); - - private static String capabilityVector; - - static { - capabilityVector = Long.toHexString(new RangerPluginCapability().getPluginCapabilities()); - } - - @Test - public void test1createTagDef() { - RangerTagDef oldTagDef = null; - RangerTagDef newTagDef = new RangerTagDef(); - newTagDef.setId(id); - newTagDef.setName(name); - - try { - Mockito.when(validator.preCreateTagDef(oldTagDef, false)).thenReturn(null); - } catch (Exception e) { - } - try { - Mockito.when(tagStore.createTagDef(oldTagDef)).thenReturn(newTagDef); - } catch (Exception e) { - } - RangerTagDef rangerTagDef = tagREST.createTagDef(oldTagDef, false); - - Assert.assertEquals(rangerTagDef.getId(), newTagDef.getId()); - Assert.assertNotNull(rangerTagDef); - Assert.assertEquals(rangerTagDef.getName(), newTagDef.getName()); - - try { - Mockito.verify(validator).preCreateTagDef(oldTagDef, false); - } catch (Exception e) { - } - try { - Mockito.verify(tagStore).createTagDef(oldTagDef); - } catch (Exception e) { - } - } - - @Test - public void test2createTagDef() { - RangerTagDef oldTagDef = new RangerTagDef(); - RangerTagDef newTagDef = new RangerTagDef(); - oldTagDef.setId(id); - newTagDef.setId(id); - newTagDef.setName(name); - - try { - Mockito.when(validator.preCreateTagDef(oldTagDef, true)).thenReturn( - oldTagDef); - } catch (Exception e) { - } - try { - Mockito.when(tagStore.updateTagDef(oldTagDef)).thenReturn(newTagDef); - } catch (Exception e) { - } - - RangerTagDef rangerTagDef = tagREST.createTagDef(oldTagDef, true); - Assert.assertEquals(rangerTagDef.getName(), newTagDef.getName()); - Assert.assertEquals(rangerTagDef.getId(), newTagDef.getId()); - Assert.assertNotEquals(oldTagDef.getName(), rangerTagDef.getName()); - - try { - Mockito.verify(validator).preCreateTagDef(oldTagDef, true); - } catch (Exception e) { - } - try { - Mockito.verify(tagStore).updateTagDef(oldTagDef); - } catch (Exception e) { - } - } - - @Test - public void test3createTagDef() { - RangerTagDef oldTagDef = new RangerTagDef(); - RangerTagDef newTagDef = new RangerTagDef(); - oldTagDef.setId(null); - newTagDef.setId(id); - newTagDef.setName(name); - - try { - Mockito.when(validator.preCreateTagDef(oldTagDef, true)).thenReturn(oldTagDef); - } catch (Exception e) { - } - try { - Mockito.when(tagStore.updateTagDef(oldTagDef)).thenReturn(newTagDef); - } catch (Exception e) { - } - - RangerTagDef rangerTagDef = tagREST.createTagDef(oldTagDef, true); - - Assert.assertNotNull(rangerTagDef); - Assert.assertEquals(rangerTagDef.getId(), newTagDef.getId()); - Assert.assertEquals(rangerTagDef.getName(), newTagDef.getName()); - Assert.assertNotEquals(rangerTagDef.getName(), oldTagDef.getName()); - - try { - Mockito.verify(validator).preCreateTagDef(oldTagDef, true); - } catch (Exception e) { - } - try { - Mockito.verify(tagStore).updateTagDef(oldTagDef); - } catch (Exception e) { - } - } - - @Test - public void test4createTagDef() { - RangerTagDef oldtagDef = new RangerTagDef(); - oldtagDef.setId(id); - - try { - Mockito.when(validator.preCreateTagDef(oldtagDef, false)).thenReturn( - oldtagDef); - } catch (Exception e) { - } - Mockito.when( - restErrorUtil.createRESTException(Mockito.anyInt(), - Mockito.anyString(), Mockito.anyBoolean())).thenThrow( - new WebApplicationException()); - thrown.expect(WebApplicationException.class); - tagREST.createTagDef(oldtagDef, false); - - try { - Mockito.verify(validator).preCreateTagDef(oldtagDef, false); - } catch (Exception e) { - } - Mockito.verify(restErrorUtil).createRESTException(Mockito.anyInt(), - Mockito.anyString(), Mockito.anyBoolean()); - } - - @Test - public void test5deleteTagDef(){ - try { - Mockito.doNothing().when(tagStore).deleteTagDef(id); - } catch (Exception e) { - } - tagREST.deleteTagDef(id); - try { - Mockito.verify(tagStore).deleteTagDef(id); - } catch (Exception e) { - } - } - - @Test - public void test6deleteTagDefByGuid() { - RangerTagDef oldTagDef = new RangerTagDef(); - oldTagDef.setId(id); - oldTagDef.setGuid(gId); - - try { - Mockito.when(tagStore.getTagDefByGuid(oldTagDef.getGuid())).thenReturn(oldTagDef); - } catch (Exception e) { - } - try { - Mockito.doNothing().when(tagStore).deleteTagDef(oldTagDef.getId()); - } catch (Exception e) { - } - - tagREST.deleteTagDefByGuid(oldTagDef.getGuid()); - Assert.assertNotNull(oldTagDef.getId()); - Assert.assertNotNull(oldTagDef.getGuid()); - - try { - Mockito.verify(tagStore).getTagDefByGuid(oldTagDef.getGuid()); - } catch (Exception e) { - } - try { - Mockito.verify(tagStore).deleteTagDef(oldTagDef.getId()); - } catch (Exception e) { - } - } - - @Test - public void test7deleteTagDefByGuid() { - try { - Mockito.when(tagStore.getTagDefByGuid(gId)).thenReturn(null); - } catch (Exception e) { - } - tagREST.deleteTagDefByGuid(gId); - try { - Mockito.verify(tagStore).getTagDefByGuid(gId); - } catch (Exception e) { - } - } - - @Test - public void test8getTagDef() { - RangerTagDef oldTagDef = new RangerTagDef(); - oldTagDef.setId(id); - oldTagDef.setName(name); - - try { - Mockito.when(tagStore.getTagDef(id)).thenReturn(oldTagDef); - } catch (Exception e) { - } - - RangerTagDef rangerTagDef = tagREST.getTagDef(id); - Assert.assertNotNull(rangerTagDef.getId()); - Assert.assertEquals(rangerTagDef.getId(), oldTagDef.getId()); - Assert.assertEquals(rangerTagDef.getName(), oldTagDef.getName()); - - try { - Mockito.verify(tagStore).getTagDef(id); - } catch (Exception e) { - } - } - - @Test - public void test9getTagDef() { - try { - Mockito.when(tagStore.getTagDef(id)).thenReturn(null); - } catch (Exception e) { - } - Mockito.when(restErrorUtil.createRESTException(Mockito.anyInt(), Mockito.anyString(), Mockito.anyBoolean())).thenThrow(new WebApplicationException()); - thrown.expect(WebApplicationException.class); - tagREST.getTagDef(id); - - try { - Mockito.verify(tagStore).getTagDef(id); - } catch (Exception e) { - } - Mockito.verify(restErrorUtil).createRESTException(Mockito.anyInt(), - Mockito.anyString(), Mockito.anyBoolean()); - } - - @Test - public void test10getTagDefByGuid() { - RangerTagDef oldTagDef = new RangerTagDef(); - oldTagDef.setId(id); - oldTagDef.setGuid(gId); - - try { - Mockito.when(tagStore.getTagDefByGuid(gId)).thenReturn(oldTagDef); - } catch (Exception e) { - } - - RangerTagDef rangerTagDef = tagREST.getTagDefByGuid(gId); - Assert.assertNotNull(oldTagDef.getGuid()); - Assert.assertEquals(rangerTagDef.getGuid(), oldTagDef.getGuid()); - Assert.assertEquals(rangerTagDef.getId(), oldTagDef.getId()); - - try { - Mockito.verify(tagStore).getTagDefByGuid(gId); - } catch (Exception e) { - } - } - - @Test - public void test11getTagDefByGuid() { - try { - Mockito.when(tagStore.getTagDefByGuid(gId)).thenReturn(null); - } catch (Exception e) { - } - Mockito.when(restErrorUtil.createRESTException(Mockito.anyInt(), Mockito.anyString(), Mockito.anyBoolean())).thenThrow(new WebApplicationException()); - thrown.expect(WebApplicationException.class); - tagREST.getTagDefByGuid(gId); - - try { - Mockito.verify(tagStore).getTagDefByGuid(gId); - } catch (Exception e) { - } - Mockito.verify(restErrorUtil).createRESTException(Mockito.anyInt(), - Mockito.anyString(), Mockito.anyBoolean()); - } - - @Test - public void test12getTagDefByName() { - RangerTagDef oldTagDef = new RangerTagDef(); - oldTagDef.setId(id); - oldTagDef.setName(name); - - try { - Mockito.when(tagStore.getTagDefByName(name)).thenReturn(oldTagDef); - } catch (Exception e) { - } - - RangerTagDef rangerTagDef = tagREST.getTagDefByName(name); - Assert.assertNotNull(rangerTagDef.getName()); - Assert.assertEquals(rangerTagDef.getName(), oldTagDef.getName()); - Assert.assertEquals(rangerTagDef.getId(), oldTagDef.getId()); - - try { - Mockito.verify(tagStore).getTagDefByName(name); - } catch (Exception e) { - } - } - - @Test - public void test13getTagDefByName() { - try { - Mockito.when(tagStore.getTagDefByName(name)).thenReturn(null); - } catch (Exception e) { - } - Mockito.when(restErrorUtil.createRESTException(Mockito.anyInt(), Mockito.anyString(), Mockito.anyBoolean())).thenThrow(new WebApplicationException()); - thrown.expect(WebApplicationException.class); - tagREST.getTagDefByName(name); - - try { - Mockito.verify(tagStore).getTagDefByName(name); - } catch (Exception e) { - } - Mockito.verify(restErrorUtil).createRESTException(Mockito.anyInt(), - Mockito.anyString(), Mockito.anyBoolean()); - } - - @Test - public void test14getAllTagDefs() { - List ret = new ArrayList(); - RangerTagDef rangerTagDef = new RangerTagDef(); - rangerTagDef.setId(id); - rangerTagDef.setVersion(5L); - ret.add(rangerTagDef); - - try { - Mockito.when(tagStore.getTagDefs((SearchFilter)Mockito.any())).thenReturn(ret); - } catch (Exception e) { - } - List result = tagREST.getAllTagDefs(); - - Assert.assertNotNull(result); - Assert.assertEquals(result.get(0).getId(), ret.get(0).getId()); - Assert.assertEquals(result.get(0).getVersion(), ret.get(0).getVersion()); - - try { - Mockito.verify(tagStore).getTagDefs((SearchFilter)Mockito.any()); - } catch (Exception e) { - } - } - - @Test - public void test62getTagDefs() { - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - PList ret = new PList(); - List tagDefList = new ArrayList(); - SearchFilter searchFilter = new SearchFilter(); - RangerTagDef rangerTagDef = new RangerTagDef(); - - rangerTagDef.setId(id); - rangerTagDef.setVersion(5L); - tagDefList.add(rangerTagDef); - ret.setList(tagDefList); - - Mockito.when(searchUtil.getSearchFilter(Mockito.any(HttpServletRequest.class), eq(tagDefService.sortFields))) - .thenReturn(searchFilter); - - try { - Mockito.when(tagStore.getPaginatedTagDefs((SearchFilter) Mockito.any())).thenReturn(ret); - } catch (Exception e) { - } - PList result = tagREST.getTagDefs(request); - - Assert.assertNotNull(result); - Assert.assertEquals(result.getList().get(0).getId(), tagDefList.get(0).getId()); - Assert.assertEquals(result.getList().get(0).getVersion(), tagDefList.get(0).getVersion()); - - try { - Mockito.verify(tagStore).getPaginatedTagDefs((SearchFilter) Mockito.any()); - } catch (Exception e) { - } - } - - @Test - public void test15getAllTagDefs() { - try { - Mockito.when(tagStore.getTagDefs((SearchFilter)Mockito.any())).thenReturn(null); - } catch (Exception e) { - } - Mockito.when(restErrorUtil.createRESTException(Mockito.anyInt(), Mockito.anyString(), Mockito.anyBoolean())).thenThrow(new WebApplicationException()); - thrown.expect(WebApplicationException.class); - tagREST.getAllTagDefs(); - - try { - Mockito.verify(tagStore).getTagDefs((SearchFilter)Mockito.any()); - } catch (Exception e) { - } - Mockito.verify(restErrorUtil).createRESTException(Mockito.anyInt(), - Mockito.anyString(), Mockito.anyBoolean()); - } - - @Test - public void test16getTagTypes(){ - boolean isAdmin = true; - List ret = new ArrayList(); - ret.add(name); - - try { - Mockito.when(bizUtil.isAdmin()).thenReturn(isAdmin); - Mockito.when(tagStore.getTagTypes()).thenReturn(ret); - } catch (Exception e) { - } - List result = tagREST.getTagTypes(); - Assert.assertNotNull(result); - - try { - Mockito.verify(tagStore).getTagTypes(); - } catch (Exception e) { - } - } - - @Test - public void test17createTag() { - RangerTag oldTag = null; - RangerTag newTag = new RangerTag(); - newTag.setId(id); - newTag.setGuid(gId); - - try { - Mockito.when(validator.preCreateTag(oldTag)).thenReturn(oldTag); - } catch (Exception e) { - } - try { - Mockito.when(tagStore.createTag(oldTag)).thenReturn(newTag); - } catch (Exception e) { - } - RangerTag rangerTag = tagREST.createTag(oldTag, false); - - Assert.assertEquals(rangerTag.getId(),newTag.getId()); - Assert.assertEquals(rangerTag.getGuid(), newTag.getGuid()); - - try { - Mockito.verify(validator).preCreateTag(oldTag); - } catch (Exception e) { - } - try { - Mockito.verify(tagStore).createTag(oldTag); - } catch (Exception e) { - } - } - - @Test - public void test18createTag(){ - RangerTag oldTag = new RangerTag(); - RangerTag newTag = new RangerTag(); - oldTag.setId(id); - newTag.setId(id); - newTag.setVersion(5L); - - try { - Mockito.when(validator.preCreateTag(oldTag)).thenReturn(oldTag); - } catch (Exception e) { - } - try { - Mockito.doNothing().when(validator).preUpdateTag(oldTag.getId(), oldTag); - } catch (Exception e1) { - } - try { - Mockito.when(tagStore.updateTag(oldTag)).thenReturn(newTag); - } catch (Exception e) { - } - - RangerTag rangerTag = tagREST.createTag(oldTag,true); - Assert.assertEquals(rangerTag.getVersion(), newTag.getVersion()); - Assert.assertNotNull(newTag.getVersion()); - Assert.assertNotEquals(oldTag.getVersion(), newTag.getVersion()); - Assert.assertEquals(oldTag.getId(), newTag.getId()); - - try { - Mockito.verify(validator).preCreateTag(oldTag); - } catch (Exception e) { - } - try { - Mockito.verify(validator).preUpdateTag(oldTag.getId(), oldTag); - } catch (Exception e1) { - } - try { - Mockito.verify(tagStore).updateTag(oldTag); - } catch (Exception e) { - } - } - - @Test - public void test19createTag(){ - RangerTag oldTag = new RangerTag(); - oldTag.setId(id); - - try { - Mockito.when(validator.preCreateTag(oldTag)).thenReturn(oldTag); - } catch (Exception e) { - } - Mockito.when(restErrorUtil.createRESTException(Mockito.anyInt(), Mockito.anyString(), Mockito.anyBoolean())).thenThrow(new WebApplicationException()); - thrown.expect(WebApplicationException.class); - tagREST.createTag(oldTag,false); - - try { - Mockito.verify(validator).preCreateTag(oldTag); - } catch (Exception e) { - } - Mockito.verify(restErrorUtil).createRESTException(Mockito.anyInt(), Mockito.anyString(), Mockito.anyBoolean()); - } - - @Test - public void test20updateTagByGuid() { - RangerTag oldTag = new RangerTag(); - RangerTag newTag = new RangerTag(); - oldTag.setGuid(gId); - newTag.setGuid(gId); - newTag.setVersion(5L); - - try { - Mockito.doNothing().when(validator).preUpdateTagByGuid(gId, oldTag); - } catch (Exception e) { - } - try { - Mockito.when(tagStore.updateTag(oldTag)).thenReturn(newTag); - } catch (Exception e) { - } - - RangerTag rangerTag = tagREST.updateTagByGuid(gId, oldTag); - Assert.assertEquals(oldTag.getGuid(), newTag.getGuid()); - Assert.assertNotEquals(rangerTag.getVersion(), oldTag.getVersion()); - Assert.assertEquals(rangerTag.getVersion(), newTag.getVersion()); - - try { - Mockito.verify(validator).preUpdateTagByGuid(gId, oldTag); - } catch (Exception e) { - } - try { - Mockito.verify(tagStore).updateTag(oldTag); - } catch (Exception e) { - } - } - - @Test - public void test21deleteTag() { - RangerTag oldTag = new RangerTag(); - oldTag.setId(id); - - try { - Mockito.when(validator.preDeleteTag(id)).thenReturn(oldTag); - } catch (Exception e) { - } - try { - Mockito.doNothing().when(tagStore).deleteTag(id); - } catch (Exception e) { - } - - tagREST.deleteTag(id); - Assert.assertNotNull(oldTag.getId()); - - try { - Mockito.verify(validator).preDeleteTag(id); - } catch (Exception e) { - } - try { - Mockito.verify(tagStore).deleteTag(id); - } catch (Exception e) { - } - } - - @Test - public void test22deleteTagByGuid() { - RangerTag oldTag = new RangerTag(); - oldTag.setId(id); - oldTag.setGuid(gId); - - try { - Mockito.when(validator.preDeleteTagByGuid(gId)).thenReturn(oldTag); - } catch (Exception e) { - } - try { - Mockito.doNothing().when(tagStore).deleteTag(oldTag.getId()); - } catch (Exception e) { - } - - tagREST.deleteTagByGuid(gId); - Assert.assertNotNull(oldTag.getId()); - Assert.assertNotNull(oldTag.getGuid()); - - try { - Mockito.verify(validator).preDeleteTagByGuid(gId); - } catch (Exception e) { - } - try { - Mockito.verify(tagStore).deleteTag(oldTag.getId()); - } catch (Exception e) { - } - } - - @Test - public void test23getTag() { - RangerTag oldTag = new RangerTag(); - oldTag.setId(id); - oldTag.setGuid(gId); - - try { - Mockito.when(tagStore.getTag(id)).thenReturn(oldTag); - } catch (Exception e) { - } - RangerTag rangerTag = tagREST.getTag(id); - Assert.assertNotNull(oldTag.getId()); - Assert.assertEquals(rangerTag.getId(), oldTag.getId()); - Assert.assertEquals(rangerTag.getGuid(), oldTag.getGuid()); - - try { - Mockito.verify(tagStore).getTag(id); - } catch (Exception e) { - } - } - - @Test - public void test24getTagByGuid() { - RangerTag oldTag = new RangerTag(); - oldTag.setId(id); - oldTag.setGuid(gId); - - try { - Mockito.when(tagStore.getTagByGuid(gId)).thenReturn(oldTag); - } catch (Exception e) { - } - RangerTag rangerTag = tagREST.getTagByGuid(gId); - Assert.assertNotNull(oldTag.getGuid()); - Assert.assertEquals(rangerTag.getGuid(), oldTag.getGuid()); - Assert.assertEquals(rangerTag.getId(), oldTag.getId()); - Assert.assertNotNull(rangerTag.getId()); - - try { - Mockito.verify(tagStore).getTagByGuid(gId); - } catch (Exception e) { - } - } - - @Test - public void test25getTagsByType() { - String type = "file"; - List tag = new ArrayList(); - RangerTag rTag = new RangerTag(); - rTag.setType(type); - tag.add(rTag); - - try { - Mockito.when(tagStore.getTagsByType(type)).thenReturn(tag); - } catch (Exception e) { - } - List rangerTag = tagREST.getTagsByType(type); - Assert.assertEquals(rangerTag.get(0).getType(), tag.get(0).getType()); - - try { - Mockito.verify(tagStore).getTagsByType(type); - } catch (Exception e) { - } - } - - @Test - public void test26getAllTags() { - boolean isAdmin = true; - List ret = new ArrayList(); - RangerTag rangerTag = new RangerTag(); - rangerTag.setId(id); - rangerTag.setGuid(gId); - ret.add(rangerTag); - - try { - Mockito.when(bizUtil.isAdmin()).thenReturn(isAdmin); - Mockito.when(tagStore.getTags((SearchFilter)Mockito.any())).thenReturn(ret); - } catch (Exception e) { - } - - List result = tagREST.getAllTags(); - Assert.assertEquals(result.get(0).getId(), ret.get(0).getId()); - Assert.assertEquals(result.get(0).getVersion(), ret.get(0).getVersion()); - Assert.assertNotNull(result.get(0).getId()); - - try { - Mockito.verify(tagStore).getTags((SearchFilter)Mockito.any()); - } catch (Exception e) { - } - } - - @Test - public void test60getAllTags() { - boolean isAdmin = true; - List ret = new ArrayList(); - try { - Mockito.when(bizUtil.isAdmin()).thenReturn(isAdmin); - Mockito.when(tagStore.getTags((SearchFilter)Mockito.any())).thenReturn(ret); - } catch (Exception e) { - } - - List result = tagREST.getAllTags(); - Assert.assertNotNull(result); - - try { - Mockito.verify(tagStore).getTags((SearchFilter)Mockito.any()); - } catch (Exception e) { - } - } - - @Test - public void test63getTags() { - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - SearchFilter searchFilter = new SearchFilter(); - String testTagType = "TAG-TYPE"; - PList ret = new PList(); - List tagList = new ArrayList(); - RangerTag tag = new RangerTag(); - - tag.setType(testTagType); - tagList.add(tag); - ret.setList(tagList); - - Mockito.when(searchUtil.getSearchFilter(Mockito.any(HttpServletRequest.class), eq(tagService.sortFields))) - .thenReturn(searchFilter); - - try { - Mockito.when(tagStore.getPaginatedTags(searchFilter)).thenReturn(ret); - } catch (Exception e) { - } - - PList result = tagREST.getTags(request); - - Assert.assertNotNull(result); - Assert.assertEquals(result.getList().get(0).getType(), tagList.get(0).getType()); - - try { - Mockito.verify(tagStore).getPaginatedTags((SearchFilter) Mockito.any()); - } catch (Exception e) { - } - } - - @Test - public void test27createServiceResource() { - RangerServiceResource oldRSR = null; - RangerServiceResource newRSR = new RangerServiceResource(); - newRSR.setId(id); - newRSR.setGuid(gId); - - try { - Mockito.when(validator.preCreateServiceResource(oldRSR)).thenReturn(oldRSR); - } catch (Exception e) { - } - try { - Mockito.when(tagStore.createServiceResource(oldRSR)).thenReturn(newRSR); - } catch (Exception e) { - } - - RangerServiceResource rangerServiceResource = tagREST.createServiceResource(oldRSR, false); - Assert.assertNotNull(rangerServiceResource.getId()); - Assert.assertEquals(rangerServiceResource.getId(), newRSR.getId()); - Assert.assertEquals(rangerServiceResource.getGuid(), newRSR.getGuid()); - - try { - Mockito.verify(validator).preCreateServiceResource(oldRSR); - } catch (Exception e) { - } - try { - Mockito.verify(tagStore).createServiceResource(oldRSR); - } catch (Exception e) { - } - } - - @Test - public void test28createServiceResource() { - RangerServiceResource oldRSR = new RangerServiceResource(); - RangerServiceResource newRSR = new RangerServiceResource(); - oldRSR.setId(id); - newRSR.setId(id); - newRSR.setVersion(5L); - - try { - Mockito.when(validator.preCreateServiceResource(oldRSR)).thenReturn(oldRSR); - } catch (Exception e) { - } - try { - Mockito.doNothing().when(validator).preUpdateServiceResource(oldRSR.getId(), oldRSR); - } catch (Exception e) { - } - try { - Mockito.when(tagStore.updateServiceResource(oldRSR)).thenReturn(newRSR); - } catch (Exception e) { - } - - RangerServiceResource rangerServiceResource = tagREST.createServiceResource(oldRSR, true); - Assert.assertNotEquals(oldRSR.getVersion(), newRSR.getVersion()); - Assert.assertEquals(rangerServiceResource.getId(), newRSR.getId()); - Assert.assertEquals(rangerServiceResource.getId(), oldRSR.getId()); - - try { - Mockito.verify(validator).preCreateServiceResource(oldRSR); - } catch (Exception e) { - } - try { - Mockito.verify(validator).preUpdateServiceResource(oldRSR.getId(), oldRSR); - } catch (Exception e) { - } - try { - Mockito.verify(tagStore).updateServiceResource(oldRSR); - } catch (Exception e) { - } - } - - @Test - public void test29createServiceResource(){ - RangerServiceResource oldRSR = new RangerServiceResource(); - - try { - Mockito.when(validator.preCreateServiceResource(oldRSR)).thenReturn(oldRSR); - } catch (Exception e) { - } - Mockito.when(restErrorUtil.createRESTException(Mockito.anyInt(), Mockito.anyString(), Mockito.anyBoolean())).thenThrow(new WebApplicationException()); - thrown.expect(WebApplicationException.class); - tagREST.createServiceResource(oldRSR, false); - - try { - Mockito.verify(validator).preCreateServiceResource(oldRSR); - } catch (Exception e) { - } - Mockito.verify(restErrorUtil).createRESTException(Mockito.anyInt(), Mockito.anyString(), Mockito.anyBoolean()); - } - - @Test - public void test30updateServiceResourceByGuid() { - RangerServiceResource oldSRS = new RangerServiceResource(); - RangerServiceResource newSRS = new RangerServiceResource(); - oldSRS.setId(id); - oldSRS.setGuid(gId); - newSRS.setId(id); - newSRS.setGuid(gId); - newSRS.setVersion(5L); - - try { - Mockito.doNothing().when(validator).preUpdateServiceResourceByGuid(gId, oldSRS); - } catch (Exception e) { - } - try { - Mockito.when(tagStore.updateServiceResource(oldSRS)).thenReturn(newSRS); - } catch (Exception e) { - } - - RangerServiceResource rangerServiceResource = tagREST.updateServiceResourceByGuid(gId, oldSRS); - Assert.assertEquals(oldSRS.getId(), newSRS.getId()); - Assert.assertEquals(oldSRS.getGuid(), newSRS.getGuid()); - Assert.assertNotEquals(oldSRS.getVersion(), newSRS.getVersion()); - Assert.assertEquals(rangerServiceResource.getVersion(), newSRS.getVersion()); - - try { - Mockito.verify(validator).preUpdateServiceResourceByGuid(gId, oldSRS); - } catch (Exception e) { - } - try { - Mockito.verify(tagStore).updateServiceResource(oldSRS); - } catch (Exception e) { - } - } - - @Test - public void test31deleteServiceResource() { - RangerServiceResource oldSRS = new RangerServiceResource(); - oldSRS.setId(id); - - try { - Mockito.when(validator.preDeleteServiceResource(id)).thenReturn(oldSRS); - } catch (Exception e) { - } - try { - Mockito.doNothing().when(tagStore).deleteServiceResource(id); - } catch (Exception e) { - } - - tagREST.deleteServiceResource(id); - Assert.assertNotNull(oldSRS.getId()); - - try { - Mockito.verify(validator).preDeleteServiceResource(id); - } catch (Exception e) { - } - try { - Mockito.verify(tagStore).deleteServiceResource(id); - } catch (Exception e) { - } - } - - @Test - public void test32getServiceResource() { - RangerServiceResource oldSRS = new RangerServiceResource(); - oldSRS.setId(id); - oldSRS.setGuid(gId); - - try { - Mockito.when(tagStore.getServiceResource(id)).thenReturn(oldSRS); - } catch (Exception e) { - } - RangerServiceResource rangerServiceResource = tagREST.getServiceResource(id); - - Assert.assertNotNull(rangerServiceResource); - Assert.assertEquals(rangerServiceResource.getId(), oldSRS.getId()); - Assert.assertEquals(rangerServiceResource.getGuid(), oldSRS.getGuid()); - try { - Mockito.verify(tagStore).getServiceResource(id); - } catch (Exception e) { - } - } - - @Test - public void test33getServiceResourceByGuid() { - RangerServiceResource oldSRS = new RangerServiceResource(); - oldSRS.setId(id); - oldSRS.setGuid(gId); - - try { - Mockito.when(tagStore.getServiceResourceByGuid(gId)).thenReturn(oldSRS); - } catch (Exception e) { - } - RangerServiceResource rangerServiceResource = tagREST.getServiceResourceByGuid(gId); - - Assert.assertNotNull(rangerServiceResource); - Assert.assertEquals(rangerServiceResource.getGuid(), oldSRS.getGuid()); - Assert.assertEquals(rangerServiceResource.getId(), oldSRS.getId()); - try { - Mockito.verify(tagStore).getServiceResourceByGuid(gId); - } catch (Exception e) { - } - } - - @Test - public void test34getServiceResourcesByService() { - List ret = new ArrayList(); - RangerServiceResource rangerServiceResource = new RangerServiceResource(); - rangerServiceResource.setId(id); - rangerServiceResource.setServiceName(serviceName); - ret.add(rangerServiceResource); - - try { - Mockito.when(tagStore.getServiceResourcesByService(serviceName)).thenReturn(ret); - } catch (Exception e) { - } - - List reslut = tagREST.getServiceResourcesByService(serviceName); - Assert.assertNotNull(reslut.get(0).getId()); - Assert.assertEquals(reslut.get(0).getId(), ret.get(0).getId()); - Assert.assertEquals(reslut.get(0).getServiceName(), ret.get(0).getServiceName()); - - try { - Mockito.verify(tagStore).getServiceResourcesByService(serviceName); - } catch (Exception e) { - } - } - - @Test - public void test35getServiceResourcesByService() { - List oldSRS = new ArrayList(); - RangerServiceResource rangerServiceResource = new RangerServiceResource(); - rangerServiceResource.setId(id); - rangerServiceResource.setServiceName(serviceName); - oldSRS.add(rangerServiceResource); - - try { - Mockito.when(tagStore.getServiceResourcesByService(serviceName)).thenReturn(oldSRS); - } catch (Exception e) { - } - - List result = tagREST.getServiceResourcesByService(serviceName); - Assert.assertNotNull(result); - Assert.assertEquals(result.size(), 1); - Assert.assertEquals(result.get(0).getId(), id); - Assert.assertEquals(result.get(0).getServiceName(), serviceName); - - try { - Mockito.verify(tagStore).getServiceResourcesByService(serviceName); - } catch (Exception e) { - } - } - - @Test - public void test59getServiceResourcesByService() { - List oldSRS = new ArrayList(); - - try { - Mockito.when(tagStore.getServiceResourcesByService(serviceName)).thenReturn(oldSRS); - } catch (Exception e) { - } - - List result = tagREST.getServiceResourcesByService(serviceName); - Assert.assertNotNull(result); - - try { - Mockito.verify(tagStore).getServiceResourcesByService(serviceName); - } catch (Exception e) { - } - } - - @Test - public void test36getServiceResourceByServiceAndResourceSignature() { - RangerServiceResource oldSRS = new RangerServiceResource(); - oldSRS.setId(id); - oldSRS.setResourceSignature(resourceSignature); - oldSRS.setServiceName(serviceName); - - try { - Mockito.when(tagStore.getServiceResourceByServiceAndResourceSignature(serviceName, resourceSignature)).thenReturn(oldSRS); - } catch (Exception e) { - } - - RangerServiceResource rangerServiceResource = tagREST.getServiceResourceByServiceAndResourceSignature(serviceName, resourceSignature); - Assert.assertEquals(rangerServiceResource.getId(), oldSRS.getId()); - Assert.assertEquals(rangerServiceResource.getServiceName(), oldSRS.getServiceName()); - Assert.assertEquals(rangerServiceResource.getResourceSignature(), oldSRS.getResourceSignature()); - - try { - Mockito.verify(tagStore).getServiceResourceByServiceAndResourceSignature(serviceName, resourceSignature); - } catch (Exception e) { - } - } - - @Test - public void test37getAllServiceResources() { - boolean isAdmin = true; - List ret = new ArrayList(); - RangerServiceResource rangerServiceResource = new RangerServiceResource(); - rangerServiceResource.setId(id); - rangerServiceResource.setServiceName(serviceName); - ret.add(rangerServiceResource); - - try { - Mockito.when(bizUtil.isAdmin()).thenReturn(isAdmin); - Mockito.when(tagStore.getServiceResources((SearchFilter)Mockito.any())).thenReturn(ret); - } catch (Exception e) { - } - List result = tagREST.getAllServiceResources(); - Assert.assertNotNull(result.get(0).getId()); - Assert.assertEquals(result.get(0).getId(), ret.get(0).getId()); - Assert.assertEquals(result.get(0).getServiceName(), ret.get(0).getServiceName()); - - try { - Mockito.verify(tagStore).getServiceResources((SearchFilter)Mockito.any()); - } catch (Exception e) { - } - } - - @Test - public void test64getServiceResourcesWithTags() { - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - SearchFilter searchFilter = new SearchFilter(); - RangerServiceResourceWithTagsList ret = new RangerServiceResourceWithTagsList(); - List serviceResourceList = new ArrayList(); - RangerServiceResourceWithTags rangerServiceResource = new RangerServiceResourceWithTags(); - List associatedTags = new ArrayList(); - RangerTag rangerTag = new RangerTag(); - - rangerTag.setId(id); - rangerTag.setGuid(gId); - rangerTag.setType(name); - associatedTags.add(rangerTag); - - rangerServiceResource.setId(id); - rangerServiceResource.setServiceName(serviceName); - rangerServiceResource.setAssociatedTags(associatedTags); - serviceResourceList.add(rangerServiceResource); - ret.setResourceList(serviceResourceList); - - Mockito.when(searchUtil.getSearchFilter(Mockito.any(HttpServletRequest.class), eq(resourceService.sortFields))).thenReturn(searchFilter); - - try { - Mockito.when(tagStore.getPaginatedServiceResourcesWithTags(Mockito.any())).thenReturn(ret); - } catch (Exception e) { - } - - RangerServiceResourceWithTagsList result = tagREST.getServiceResourcesWithTags(request); - - Assert.assertNotNull(result.getResourceList().get(0).getId()); - Assert.assertEquals(result.getResourceList().get(0).getId(), serviceResourceList.get(0).getId()); - Assert.assertEquals(result.getResourceList().get(0).getServiceName(), serviceResourceList.get(0).getServiceName()); - Assert.assertEquals(result.getResourceList().get(0).getAssociatedTags().size(), 1); - Assert.assertEquals(result.getResourceList().get(0).getAssociatedTags().get(0).getType(), name); - - try { - Mockito.verify(tagStore).getPaginatedServiceResourcesWithTags((SearchFilter) Mockito.any()); - } catch (Exception e) { - } - } - - @Test - public void test38createTagResourceMap() { - RangerTagResourceMap oldTagResourceMap = null; - RangerTagResourceMap newTagResourceMap = new RangerTagResourceMap(); - - newTagResourceMap.setTagId(id); - newTagResourceMap.setResourceId(id); - - try { - Mockito.when(tagStore.getTagResourceMapForTagAndResourceGuid(tagGuid, resourceGuid)).thenReturn(oldTagResourceMap); - } catch (Exception e) { - } - try { - Mockito.when(validator.preCreateTagResourceMap(tagGuid, resourceGuid)).thenReturn(newTagResourceMap); - } catch (Exception e) { - } - try { - Mockito.when(tagStore.createTagResourceMap(newTagResourceMap)).thenReturn(newTagResourceMap); - } catch (Exception e) { - } - - RangerTagResourceMap rangerTagResourceMap = tagREST.createTagResourceMap(tagGuid, resourceGuid, false); - - Assert.assertEquals(rangerTagResourceMap.getTagId(), newTagResourceMap.getTagId()); - Assert.assertEquals(rangerTagResourceMap.getResourceId(), newTagResourceMap.getResourceId()); - - try { - Mockito.verify(tagStore).getTagResourceMapForTagAndResourceGuid(tagGuid, resourceGuid); - } catch (Exception e) { - } - - try { - Mockito.verify(validator).preCreateTagResourceMap(tagGuid, resourceGuid); - } catch (Exception e) { - } - - try { - Mockito.verify(tagStore).createTagResourceMap(newTagResourceMap); - } catch (Exception e) { - } - } - - @Test - public void test39createTagResourceMap() { - RangerTagResourceMap oldTagResourceMap = new RangerTagResourceMap(); - - try { - Mockito.when(tagStore.getTagResourceMapForTagAndResourceGuid(tagGuid, resourceGuid)).thenReturn(oldTagResourceMap); - } catch (Exception e) { - } - - Mockito.when(restErrorUtil.createRESTException(Mockito.anyInt(),Mockito.anyString(), Mockito.anyBoolean())).thenThrow(new WebApplicationException()); - - thrown.expect(WebApplicationException.class); - tagREST.createTagResourceMap(tagGuid, resourceGuid, false); - - try { - Mockito.verify(tagStore).getTagResourceMapForTagAndResourceGuid(tagGuid, resourceGuid); - } catch (Exception e) { - } - Mockito.verify(restErrorUtil).createRESTException(Mockito.anyInt(),Mockito.anyString(), Mockito.anyBoolean()); - } - - @Test - public void test40createTagResourceMap() { - RangerTagResourceMap oldTagResourceMap = null; - RangerTagResourceMap newTagResourceMap = new RangerTagResourceMap(); - newTagResourceMap.setId(id); - newTagResourceMap.setGuid(gId); - RangerTagResourceMap finalTagResourceMap = new RangerTagResourceMap(); - finalTagResourceMap.setId(id); - finalTagResourceMap.setGuid(gId); - finalTagResourceMap.setVersion(5L); - - try { - Mockito.when(tagStore.getTagResourceMapForTagAndResourceGuid(tagGuid, resourceGuid)).thenReturn(oldTagResourceMap); - } catch (Exception e) { - } - try { - Mockito.when(validator.preCreateTagResourceMap(tagGuid, resourceGuid)).thenReturn(newTagResourceMap); - } catch (Exception e1) { - } - try { - Mockito.when(tagStore.createTagResourceMap(newTagResourceMap)).thenReturn(finalTagResourceMap); - } catch (Exception e1) { - } - RangerTagResourceMap result = tagREST.createTagResourceMap(tagGuid, resourceGuid, true); - Assert.assertNotNull(result.getId()); - Assert.assertEquals(result.getGuid(), finalTagResourceMap.getGuid()); - Assert.assertEquals(result.getId(), finalTagResourceMap.getId()); - Assert.assertEquals(result.getVersion(), finalTagResourceMap.getVersion()); - - try { - Mockito.verify(tagStore).getTagResourceMapForTagAndResourceGuid(tagGuid, resourceGuid); - } catch (Exception e) { - } - try { - Mockito.verify(validator).preCreateTagResourceMap(tagGuid, resourceGuid); - } catch (Exception e) { - } - try { - Mockito.verify(tagStore).createTagResourceMap(newTagResourceMap); - } catch (Exception e) { - } - } - - @Test - public void test41deleteTagResourceMap() { - RangerTagResourceMap oldTagResourceMap = new RangerTagResourceMap(); - oldTagResourceMap.setId(id); - try { - Mockito.when(validator.preDeleteTagResourceMap(id)).thenReturn(oldTagResourceMap); - } catch (Exception e) { - } - try { - Mockito.doNothing().when(tagStore).deleteTagResourceMap(id); - } catch (Exception e) { - } - - tagREST.deleteTagResourceMap(id); - Assert.assertNotNull(oldTagResourceMap.getId()); - try { - Mockito.verify(validator).preDeleteTagResourceMap(id); - } catch (Exception e) { - } - try { - Mockito.verify(tagStore).deleteTagResourceMap(id); - } catch (Exception e) { - } - } - - @Test - public void test42deleteTagResourceMapByGuid() { - RangerTagResourceMap oldTagResourceMap = new RangerTagResourceMap(); - oldTagResourceMap.setId(id); - oldTagResourceMap.setGuid(gId); - try { - Mockito.when(validator.preDeleteTagResourceMapByGuid(gId)).thenReturn(oldTagResourceMap); - } catch (Exception e) { - } - try { - Mockito.doNothing().when(tagStore).deleteTagResourceMap(oldTagResourceMap.getId()); - } catch (Exception e) { - } - - tagREST.deleteTagResourceMapByGuid(gId); - Assert.assertNotNull(oldTagResourceMap.getId()); - Assert.assertNotNull(oldTagResourceMap.getGuid()); - - try { - Mockito.verify(validator).preDeleteTagResourceMapByGuid(gId); - } catch (Exception e) { - } - try { - Mockito.verify(tagStore).deleteTagResourceMap(oldTagResourceMap.getId()); - } catch (Exception e) { - } - } - - @Test - public void test43deleteTagResourceMap() { - RangerTagResourceMap oldTagResourceMap = new RangerTagResourceMap(); - oldTagResourceMap.setId(id); - - try { - Mockito.when(validator.preDeleteTagResourceMap(tagGuid, resourceGuid)).thenReturn(oldTagResourceMap); - } catch (Exception e) { - } - try { - Mockito.doNothing().when(tagStore).deleteTagResourceMap(oldTagResourceMap.getId()); - } catch (Exception e) { - } - - tagREST.deleteTagResourceMap(tagGuid, resourceGuid); - try { - Mockito.verify(validator).preDeleteTagResourceMap(tagGuid, resourceGuid); - } catch (Exception e) { - } - } - - @Test - public void test44getTagResourceMap() { - RangerTagResourceMap oldTagResourceMap = new RangerTagResourceMap(); - oldTagResourceMap.setId(id); - oldTagResourceMap.setGuid(gId); - - try { - Mockito.when(tagStore.getTagResourceMap(id)).thenReturn(oldTagResourceMap); - } catch (Exception e) { - } - - RangerTagResourceMap rangerTagResourceMap = tagREST.getTagResourceMap(id); - Assert.assertNotNull(rangerTagResourceMap.getId()); - Assert.assertEquals(rangerTagResourceMap.getId(), oldTagResourceMap.getId()); - Assert.assertEquals(rangerTagResourceMap.getGuid(), oldTagResourceMap.getGuid()); - try { - Mockito.verify(tagStore).getTagResourceMap(id); - } catch (Exception e) { - } - } - - @Test - public void test45getTagResourceMapByGuid() { - RangerTagResourceMap oldTagResourceMap = new RangerTagResourceMap(); - oldTagResourceMap.setId(id); - oldTagResourceMap.setGuid(gId); - - try { - Mockito.when(tagStore.getTagResourceMapByGuid(gId)).thenReturn(oldTagResourceMap); - } catch (Exception e) { - } - - RangerTagResourceMap rangerTagResourceMap = tagREST.getTagResourceMapByGuid(gId); - Assert.assertNotNull(rangerTagResourceMap.getId()); - Assert.assertEquals(rangerTagResourceMap.getId(), oldTagResourceMap.getId()); - Assert.assertEquals(rangerTagResourceMap.getGuid(), oldTagResourceMap.getGuid()); - try { - Mockito.verify(tagStore).getTagResourceMapByGuid(gId); - } catch (Exception e) { - } - } - - @Test - public void test46getTagResourceMap() { - RangerTagResourceMap oldTagResourceMap = new RangerTagResourceMap(); - oldTagResourceMap.setId(id); - oldTagResourceMap.setTagId(id); - - try { - Mockito.when(tagStore.getTagResourceMapForTagAndResourceGuid(tagGuid, resourceGuid)).thenReturn(oldTagResourceMap); - } catch (Exception e) { - } - RangerTagResourceMap rangerTagResourceMap = tagREST.getTagResourceMap(tagGuid, resourceGuid); - Assert.assertNotNull(rangerTagResourceMap.getId()); - Assert.assertEquals(rangerTagResourceMap.getId(), oldTagResourceMap.getId()); - Assert.assertEquals(rangerTagResourceMap.getTagId(), oldTagResourceMap.getTagId()); - try { - Mockito.verify(tagStore).getTagResourceMapForTagAndResourceGuid(tagGuid, resourceGuid); - } catch (Exception e) { - } - } - - @Test - public void test47getAllTagResourceMaps() { - List ret = new ArrayList(); - RangerTagResourceMap rangerTagResourceMap = new RangerTagResourceMap(); - rangerTagResourceMap.setId(id); - rangerTagResourceMap.setTagId(id); - ret.add(rangerTagResourceMap); - - try { - Mockito.when(tagStore.getTagResourceMaps((SearchFilter)Mockito.any())).thenReturn(ret); - } catch (Exception e) { - } - - List result = tagREST.getAllTagResourceMaps(); - Assert.assertNotNull(result.get(0).getId()); - Assert.assertEquals(result.get(0).getId(), ret.get(0).getId()); - Assert.assertEquals(result.get(0).getTagId(), ret.get(0).getTagId()); - - try { - Mockito.verify(tagStore).getTagResourceMaps((SearchFilter)Mockito.any()); - } catch (Exception e) { - } - } - - @Test - public void test58getAllTagResourceMaps() { - List ret = new ArrayList(); - - try { - Mockito.when(tagStore.getTagResourceMaps((SearchFilter)Mockito.any())).thenReturn(ret); - } catch (Exception e) { - } - - List result = tagREST.getAllTagResourceMaps(); - Assert.assertNotNull(result); - - try { - Mockito.verify(tagStore).getTagResourceMaps((SearchFilter)Mockito.any()); - } catch (Exception e) { - } - } - - @Test - public void test48deleteServiceResourceByGuid() { - RangerServiceResource oldRSR = new RangerServiceResource(); - oldRSR.setId(id); - oldRSR.setGuid(gId); - List tagResourceMaps = new ArrayList(); - RangerTagResourceMap rangerTagResourceMap = new RangerTagResourceMap(); - rangerTagResourceMap.setId(id); - rangerTagResourceMap.setTagId(id); - tagResourceMaps.add(rangerTagResourceMap); - - try { - Mockito.when(validator.preDeleteServiceResourceByGuid(gId, true)).thenReturn(oldRSR); - } catch (Exception e) { - } - try { - Mockito.when(tagStore.getTagResourceMapsForResourceGuid(oldRSR.getGuid())).thenReturn(tagResourceMaps); - } catch (Exception e) { - } - tagREST.deleteServiceResourceByGuid(gId, true); - - try { - Mockito.verify(validator).preDeleteServiceResourceByGuid(gId, true); - } catch (Exception e) { - } - try { - Mockito.verify(tagStore).getTagResourceMapsForResourceGuid(oldRSR.getGuid()); - } catch (Exception e) { - } - } - - @Test - public void test49deleteServiceResourceByGuid() { - RangerServiceResource oldRSR = new RangerServiceResource(); - oldRSR.setId(id); - oldRSR.setGuid(gId); - - try { - Mockito.when(validator.preDeleteServiceResourceByGuid(gId, false)).thenReturn(oldRSR); - } catch (Exception e) { - } - try { - Mockito.doNothing().when(tagStore).deleteServiceResource(oldRSR.getId()); - } catch (Exception e) { - } - - tagREST.deleteServiceResourceByGuid(gId, false); - - try { - Mockito.verify(validator).preDeleteServiceResourceByGuid(gId, false); - } catch (Exception e) { - } - } - - @Test - public void test61deleteServiceResourceByGuid() { - RangerServiceResource oldRSR = new RangerServiceResource(); - oldRSR.setId(id); - oldRSR.setGuid(gId); - List tagResourceMaps = new ArrayList(); - - try { - Mockito.when(validator.preDeleteServiceResourceByGuid(gId, true)).thenReturn(oldRSR); - } catch (Exception e) { - } - try { - Mockito.when(tagStore.getTagResourceMapsForResourceGuid(oldRSR.getGuid())).thenReturn(tagResourceMaps); - } catch (Exception e) { - } - tagREST.deleteServiceResourceByGuid(gId, true); - - try { - Mockito.verify(validator).preDeleteServiceResourceByGuid(gId, true); - } catch (Exception e) { - } - try { - Mockito.verify(tagStore).getTagResourceMapsForResourceGuid(oldRSR.getGuid()); - } catch (Exception e) { - } - } - - @Test - public void test50getServiceTagsIfUpdated() { - ServiceTags oldServiceTag = null; - - try { - Mockito.when(tagStore.getServiceTagsIfUpdated(serviceName, lastKnownVersion, true)).thenReturn(oldServiceTag); - } catch (Exception e) { - } - Mockito.when(restErrorUtil.createRESTException(Mockito.anyInt(),Mockito.anyString(), Mockito.anyBoolean())).thenThrow(new WebApplicationException()); - thrown.expect(WebApplicationException.class); - - tagREST.getServiceTagsIfUpdated(serviceName, lastKnownVersion, 0L, pluginId, false, capabilityVector, null); - - try { - Mockito.verify(tagStore).getServiceTagsIfUpdated(serviceName, lastKnownVersion, true); - } catch (Exception e) { - } - Mockito.verify(restErrorUtil).createRESTException(Mockito.anyInt(),Mockito.anyString(), Mockito.anyBoolean()); - } - - @Test - public void test51getServiceTagsIfUpdated() { - ServiceTags oldServiceTag = new ServiceTags(); - oldServiceTag.setServiceName(serviceName); - oldServiceTag.setTagVersion(5L); - - try { - Mockito.when(tagStore.getServiceTagsIfUpdated(serviceName, lastKnownVersion, true)).thenReturn(oldServiceTag); - } catch (Exception e) { - } - ServiceTags serviceTags = tagREST.getServiceTagsIfUpdated(serviceName, lastKnownVersion, 0L, pluginId, false, capabilityVector, null); - Assert.assertEquals(serviceTags.getServiceName(), oldServiceTag.getServiceName()); - Assert.assertEquals(serviceTags.getTagVersion(), oldServiceTag.getTagVersion()); - - try { - Mockito.verify(tagStore).getServiceTagsIfUpdated(serviceName, lastKnownVersion, true); - } catch (Exception e) { - } - } - - @Test - public void test52getSecureServiceTagsIfUpdatedIsKeyAdminTrue() { - boolean isAdmin = false; - boolean isKeyAdmin = true; - ServiceTags oldServiceTag = new ServiceTags(); - oldServiceTag.setServiceName(serviceName); - oldServiceTag.setTagVersion(5L); - - XXService xService = new XXService(); - xService.setId(id); - xService.setName(serviceName); - xService.setType(5L); - - XXServiceDef xServiceDef = new XXServiceDef(); - xServiceDef.setId(id); - xServiceDef.setVersion(5L); - xServiceDef.setImplclassname("org.apache.ranger.services.kms.RangerServiceKMS"); - - RangerService rangerService = new RangerService(); - rangerService.setId(id); - rangerService.setName(serviceName); - - XXServiceDao xXServiceDao = Mockito.mock(XXServiceDao.class); - XXServiceDefDao xXServiceDefDao = Mockito.mock(XXServiceDefDao.class); - - Mockito.when(bizUtil.isAdmin()).thenReturn(isAdmin); - Mockito.when(bizUtil.isKeyAdmin()).thenReturn(isKeyAdmin); - - Mockito.when(daoManager.getXXService()).thenReturn(xXServiceDao); - Mockito.when(xXServiceDao.findByName(serviceName)).thenReturn(xService); - Mockito.when(daoManager.getXXServiceDef()).thenReturn(xXServiceDefDao); - Mockito.when(xXServiceDefDao.getById(xService.getType())).thenReturn(xServiceDef); - try { - Mockito.when(svcStore.getServiceByName(serviceName)).thenReturn(rangerService); - } catch (Exception e) { - } - - try { - Mockito.when(tagStore.getServiceTagsIfUpdated(serviceName, lastKnownVersion, true)).thenReturn(oldServiceTag); - } catch (Exception e) { - } - - ServiceTags result = tagREST.getSecureServiceTagsIfUpdated(serviceName, lastKnownVersion, 0L, pluginId, false, capabilityVector, null); - Assert.assertNotNull(result.getServiceName()); - Assert.assertEquals(result.getServiceName(), oldServiceTag.getServiceName()); - Assert.assertEquals(result.getTagVersion(), oldServiceTag.getTagVersion()); - - Mockito.verify(bizUtil).isAdmin(); - Mockito.verify(bizUtil).isKeyAdmin(); - Mockito.verify(daoManager).getXXService(); - Mockito.verify(xXServiceDao).findByName(serviceName); - Mockito.verify(daoManager).getXXServiceDef(); - Mockito.verify(xXServiceDefDao).getById(xService.getType()); - try { - Mockito.verify(svcStore).getServiceByName(serviceName); - } catch (Exception e) { - } - try { - Mockito.verify(tagStore).getServiceTagsIfUpdated(serviceName, lastKnownVersion, true); - } catch (Exception e) { - } - } - - @Test - public void test53getSecureServiceTagsIfUpdatedIsAdminTrue() { - boolean isAdmin = true; - boolean isKeyAdmin = false; - ServiceTags oldServiceTag = new ServiceTags(); - oldServiceTag.setServiceName(serviceName); - oldServiceTag.setTagVersion(5L); - - XXService xService = new XXService(); - xService.setId(id); - xService.setName(serviceName); - xService.setType(5L); - - XXServiceDef xServiceDef = new XXServiceDef(); - xServiceDef.setId(id); - xServiceDef.setVersion(5L); - - RangerService rangerService = new RangerService(); - rangerService.setId(id); - rangerService.setName(serviceName); - - XXServiceDao xXServiceDao = Mockito.mock(XXServiceDao.class); - XXServiceDefDao xXServiceDefDao = Mockito.mock(XXServiceDefDao.class); - - Mockito.when(bizUtil.isAdmin()).thenReturn(isAdmin); - Mockito.when(bizUtil.isKeyAdmin()).thenReturn(isKeyAdmin); - - Mockito.when(daoManager.getXXService()).thenReturn(xXServiceDao); - Mockito.when(xXServiceDao.findByName(serviceName)).thenReturn(xService); - Mockito.when(daoManager.getXXServiceDef()).thenReturn(xXServiceDefDao); - Mockito.when(xXServiceDefDao.getById(xService.getType())).thenReturn(xServiceDef); - try { - Mockito.when(svcStore.getServiceByName(serviceName)).thenReturn(rangerService); - } catch (Exception e) { - } - - try { - Mockito.when(tagStore.getServiceTagsIfUpdated(serviceName, lastKnownVersion, true)).thenReturn(oldServiceTag); - } catch (Exception e) { - } - - ServiceTags result = tagREST.getSecureServiceTagsIfUpdated(serviceName, lastKnownVersion, 0L, pluginId, false, capabilityVector, null); - Assert.assertNotNull(result.getServiceName()); - Assert.assertEquals(result.getServiceName(), oldServiceTag.getServiceName()); - Assert.assertEquals(result.getTagVersion(), oldServiceTag.getTagVersion()); - - Mockito.verify(bizUtil).isAdmin(); - Mockito.verify(bizUtil).isKeyAdmin(); - Mockito.verify(daoManager).getXXService(); - Mockito.verify(xXServiceDao).findByName(serviceName); - Mockito.verify(daoManager).getXXServiceDef(); - Mockito.verify(xXServiceDefDao).getById(xService.getType()); - try { - Mockito.verify(svcStore).getServiceByName(serviceName); - } catch (Exception e) { - } - try { - Mockito.verify(tagStore).getServiceTagsIfUpdated(serviceName, lastKnownVersion, true); - } catch (Exception e) { - } - } - - @Test - public void test54getSecureServiceTagsIfUpdatedIsKeyAdminFalse() { - boolean isAdmin = false; - boolean isKeyAdmin = false; - boolean isAllowed = true; - ServiceTags oldServiceTag = new ServiceTags(); - oldServiceTag.setServiceName(serviceName); - oldServiceTag.setTagVersion(5L); - - XXService xService = new XXService(); - xService.setId(id); - xService.setName(serviceName); - xService.setType(5L); - - XXServiceDef xServiceDef = new XXServiceDef(); - xServiceDef.setId(id); - xServiceDef.setVersion(5L); - xServiceDef.setImplclassname("org.apache.ranger.services.kms.RangerServiceKMS"); - - RangerService rangerService = new RangerService(); - rangerService.setId(id); - rangerService.setName(serviceName); - - XXServiceDao xXServiceDao = Mockito.mock(XXServiceDao.class); - XXServiceDefDao xXServiceDefDao = Mockito.mock(XXServiceDefDao.class); - - Mockito.when(bizUtil.isAdmin()).thenReturn(isAdmin); - Mockito.when(bizUtil.isKeyAdmin()).thenReturn(isKeyAdmin); - - Mockito.when(daoManager.getXXService()).thenReturn(xXServiceDao); - Mockito.when(xXServiceDao.findByName(serviceName)).thenReturn(xService); - Mockito.when(daoManager.getXXServiceDef()).thenReturn(xXServiceDefDao); - Mockito.when(xXServiceDefDao.getById(xService.getType())).thenReturn(xServiceDef); - try { - Mockito.when(svcStore.getServiceByName(serviceName)).thenReturn(rangerService); - } catch (Exception e) { - } - - Mockito.when(bizUtil.isUserAllowed(rangerService, Allowed_User_List_For_Tag_Download)).thenReturn(isAllowed); - try { - Mockito.when(tagStore.getServiceTagsIfUpdated(serviceName, lastKnownVersion, true)).thenReturn(oldServiceTag); - } catch (Exception e) { - } - - ServiceTags result = tagREST.getSecureServiceTagsIfUpdated(serviceName, lastKnownVersion, 0L, pluginId, false, capabilityVector, null); - Assert.assertNotNull(result.getServiceName()); - Assert.assertEquals(result.getServiceName(), oldServiceTag.getServiceName()); - Assert.assertEquals(result.getTagVersion(), oldServiceTag.getTagVersion()); - - Mockito.verify(bizUtil).isAdmin(); - Mockito.verify(bizUtil).isKeyAdmin(); - Mockito.verify(daoManager).getXXService(); - Mockito.verify(xXServiceDao).findByName(serviceName); - Mockito.verify(daoManager).getXXServiceDef(); - Mockito.verify(xXServiceDefDao).getById(xService.getType()); - try { - Mockito.verify(svcStore).getServiceByName(serviceName); - } catch (Exception e) { - } - Mockito.verify(bizUtil).isUserAllowed(rangerService, Allowed_User_List_For_Tag_Download); - try { - Mockito.verify(tagStore).getServiceTagsIfUpdated(serviceName, lastKnownVersion, true); - } catch (Exception e) { - } - } - - @Test - public void test55getSecureServiceTagsIfUpdatedIsAdminFalse() { - boolean isAdmin = false; - boolean isKeyAdmin = false; - boolean isAllowed = true; - ServiceTags oldServiceTag = new ServiceTags(); - oldServiceTag.setServiceName(serviceName); - oldServiceTag.setTagVersion(5L); - - XXService xService = new XXService(); - xService.setId(id); - xService.setName(serviceName); - xService.setType(5L); - - XXServiceDef xServiceDef = new XXServiceDef(); - xServiceDef.setId(id); - xServiceDef.setVersion(5L); - - RangerService rangerService = new RangerService(); - rangerService.setId(id); - rangerService.setName(serviceName); - - XXServiceDao xXServiceDao = Mockito.mock(XXServiceDao.class); - XXServiceDefDao xXServiceDefDao = Mockito.mock(XXServiceDefDao.class); - - Mockito.when(bizUtil.isAdmin()).thenReturn(isAdmin); - Mockito.when(bizUtil.isKeyAdmin()).thenReturn(isKeyAdmin); - - Mockito.when(daoManager.getXXService()).thenReturn(xXServiceDao); - Mockito.when(xXServiceDao.findByName(serviceName)).thenReturn(xService); - Mockito.when(daoManager.getXXServiceDef()).thenReturn(xXServiceDefDao); - Mockito.when(xXServiceDefDao.getById(xService.getType())).thenReturn(xServiceDef); - try { - Mockito.when(svcStore.getServiceByName(serviceName)).thenReturn(rangerService); - } catch (Exception e) { - } - - Mockito.when(bizUtil.isUserAllowed(rangerService, Allowed_User_List_For_Tag_Download)).thenReturn(isAllowed); - try { - Mockito.when(tagStore.getServiceTagsIfUpdated(serviceName, lastKnownVersion, true)).thenReturn(oldServiceTag); - } catch (Exception e) { - } - - ServiceTags result = tagREST.getSecureServiceTagsIfUpdated(serviceName, lastKnownVersion, 0L, pluginId, false, capabilityVector, null); - Assert.assertNotNull(result.getServiceName()); - Assert.assertEquals(result.getServiceName(), oldServiceTag.getServiceName()); - Assert.assertEquals(result.getTagVersion(), oldServiceTag.getTagVersion()); - - Mockito.verify(bizUtil).isAdmin(); - Mockito.verify(bizUtil).isKeyAdmin(); - Mockito.verify(daoManager).getXXService(); - Mockito.verify(xXServiceDao).findByName(serviceName); - Mockito.verify(daoManager).getXXServiceDef(); - Mockito.verify(xXServiceDefDao).getById(xService.getType()); - try { - Mockito.verify(svcStore).getServiceByName(serviceName); - } catch (Exception e) { - } - Mockito.verify(bizUtil).isUserAllowed(rangerService, Allowed_User_List_For_Tag_Download); - try { - Mockito.verify(tagStore).getServiceTagsIfUpdated(serviceName, lastKnownVersion, true); - } catch (Exception e) { - } - } - - @Test - public void test56getSecureServiceTagsIfUpdatedIsAllowedFalse() { - boolean isAdmin = false; - boolean isKeyAdmin = false; - boolean isAllowed = false; - ServiceTags oldServiceTag = new ServiceTags(); - oldServiceTag.setServiceName(serviceName); - oldServiceTag.setTagVersion(5L); - - XXService xService = new XXService(); - xService.setId(id); - xService.setName(serviceName); - xService.setType(5L); - - XXServiceDef xServiceDef = new XXServiceDef(); - xServiceDef.setId(id); - xServiceDef.setVersion(5L); - - RangerService rangerService = new RangerService(); - rangerService.setId(id); - rangerService.setName(serviceName); - - XXServiceDao xXServiceDao = Mockito.mock(XXServiceDao.class); - XXServiceDefDao xXServiceDefDao = Mockito.mock(XXServiceDefDao.class); - - Mockito.when(bizUtil.isAdmin()).thenReturn(isAdmin); - Mockito.when(bizUtil.isKeyAdmin()).thenReturn(isKeyAdmin); - - Mockito.when(daoManager.getXXService()).thenReturn(xXServiceDao); - Mockito.when(xXServiceDao.findByName(serviceName)).thenReturn(xService); - Mockito.when(daoManager.getXXServiceDef()).thenReturn(xXServiceDefDao); - Mockito.when(xXServiceDefDao.getById(xService.getType())).thenReturn(xServiceDef); - try { - Mockito.when(svcStore.getServiceByName(serviceName)).thenReturn(rangerService); - } catch (Exception e) { - } - - Mockito.when(bizUtil.isUserAllowed(rangerService, Allowed_User_List_For_Tag_Download)).thenReturn(isAllowed); - Mockito.when(restErrorUtil.createRESTException(Mockito.anyInt(), Mockito.anyString(), Mockito.anyBoolean())).thenThrow(new WebApplicationException()); - thrown.expect(WebApplicationException.class); - - tagREST.getSecureServiceTagsIfUpdated(serviceName, lastKnownVersion, 0L, pluginId, false, capabilityVector, null); - - Mockito.verify(bizUtil).isAdmin(); - Mockito.verify(bizUtil).isKeyAdmin(); - Mockito.verify(daoManager).getXXService(); - Mockito.verify(xXServiceDao).findByName(serviceName); - Mockito.verify(daoManager).getXXServiceDef(); - Mockito.verify(xXServiceDefDao).getById(xService.getType()); - try { - Mockito.verify(svcStore).getServiceByName(serviceName); - } catch (Exception e) { - } - Mockito.verify(bizUtil).isUserAllowed(rangerService, Allowed_User_List_For_Tag_Download); - Mockito.verify(restErrorUtil).createRESTException(Mockito.anyInt(), Mockito.anyString(), Mockito.anyBoolean()); - } - - @Test - public void test57getSecureServiceTagsIfUpdated() { - boolean isAdmin = false; - boolean isKeyAdmin = false; - boolean isAllowed = true; - ServiceTags oldServiceTag = null; - - XXService xService = new XXService(); - xService.setId(id); - xService.setName(serviceName); - xService.setType(5L); - - XXServiceDef xServiceDef = new XXServiceDef(); - xServiceDef.setId(id); - xServiceDef.setVersion(5L); - - RangerService rangerService = new RangerService(); - rangerService.setId(id); - rangerService.setName(serviceName); - - XXServiceDao xXServiceDao = Mockito.mock(XXServiceDao.class); - XXServiceDefDao xXServiceDefDao = Mockito.mock(XXServiceDefDao.class); - - Mockito.when(bizUtil.isAdmin()).thenReturn(isAdmin); - Mockito.when(bizUtil.isKeyAdmin()).thenReturn(isKeyAdmin); - - Mockito.when(daoManager.getXXService()).thenReturn(xXServiceDao); - Mockito.when(xXServiceDao.findByName(serviceName)).thenReturn(xService); - Mockito.when(daoManager.getXXServiceDef()).thenReturn(xXServiceDefDao); - Mockito.when(xXServiceDefDao.getById(xService.getType())).thenReturn(xServiceDef); - try { - Mockito.when(svcStore.getServiceByName(serviceName)).thenReturn(rangerService); - } catch (Exception e) { - } - - Mockito.when(bizUtil.isUserAllowed(rangerService, Allowed_User_List_For_Tag_Download)).thenReturn(isAllowed); - try { - Mockito.when(tagStore.getServiceTagsIfUpdated(serviceName, lastKnownVersion, true)).thenReturn(oldServiceTag); - } catch (Exception e) { - } - Mockito.when(restErrorUtil.createRESTException(Mockito.anyInt(), Mockito.anyString(), Mockito.anyBoolean())).thenThrow(new WebApplicationException()); - thrown.expect(WebApplicationException.class); - - tagREST.getSecureServiceTagsIfUpdated(serviceName, lastKnownVersion, 0L, pluginId, false, capabilityVector, null); - - Mockito.verify(bizUtil).isAdmin(); - Mockito.verify(bizUtil).isKeyAdmin(); - Mockito.verify(daoManager).getXXService(); - Mockito.verify(xXServiceDao).findByName(serviceName); - Mockito.verify(daoManager).getXXServiceDef(); - Mockito.verify(xXServiceDefDao).getById(xService.getType()); - try { - Mockito.verify(svcStore).getServiceByName(serviceName); - } catch (Exception e) { - } - Mockito.verify(bizUtil).isUserAllowed(rangerService, Allowed_User_List_For_Tag_Download); - try { - Mockito.verify(tagStore).getServiceTagsIfUpdated(serviceName, lastKnownVersion, false); - } catch (Exception e) { - } - Mockito.verify(restErrorUtil).createRESTException(Mockito.anyInt(), Mockito.anyString(), Mockito.anyBoolean()); - } - - @Test - public void test58resetTagCacheByServiceNameForServiceAdmin() { - boolean isAdmin = false; - boolean res = true; - RangerService rangerService = new RangerService(); - rangerService.setId(id); - rangerService.setName(serviceName); - String userName = "admin"; - Mockito.when(bizUtil.getCurrentUserLoginId()).thenReturn(userName); - - Mockito.when(bizUtil.isAdmin()).thenReturn(isAdmin); - try { - Mockito.when(svcStore.getServiceByName(serviceName)).thenReturn(rangerService); - } catch (Exception e) { - } - Mockito.when(bizUtil.isUserServiceAdmin(Mockito.any(RangerService.class), Mockito.anyString())).thenReturn(true); - try { - Mockito.when(tagStore.resetTagCache(serviceName)).thenReturn(true); - } catch (Exception e) { - } - boolean isReset = tagREST.resetTagCache(serviceName); - assert isReset == res; - Mockito.verify(bizUtil).isAdmin(); - Mockito.verify(bizUtil).isUserServiceAdmin(Mockito.any(RangerService.class), Mockito.anyString()); - try { - Mockito.verify(svcStore).getServiceByName(serviceName); - } catch (Exception e) { - } - - try { - Mockito.verify(tagStore).resetTagCache(serviceName); - } catch (Exception e) { - } - } - @Test - public void test59resetTagCacheWhenServiceNameIsInvalid() { - try { - Mockito.when(svcStore.getServiceByName(serviceName)).thenReturn(null); - } catch (Exception e) { - } - Mockito.when(restErrorUtil.createRESTException(Mockito.anyInt(), Mockito.anyString(), Mockito.anyBoolean())).thenThrow(new WebApplicationException()); - thrown.expect(WebApplicationException.class); - tagREST.resetTagCache(serviceName); - Mockito.verify(restErrorUtil).createRESTException(Mockito.anyInt(), Mockito.anyString(), Mockito.anyBoolean()); - } + private static final Long id = 1L; + private static final String gId = "1427365526516_835_0"; + private static final String name = "test"; + private static final String serviceName = "HDFS"; + private static final String resourceSignature = "testResourceSign"; + private static final String tagGuid = "8787878787_09_1"; + private static final String resourceGuid = "9898989898_09_1"; + private static final Long lastKnownVersion = 10L; + private static final String pluginId = "1"; + private static final String Allowed_User_List_For_Tag_Download = "tag.download.auth.users"; + private static final String capabilityVector; + @Rule + public ExpectedException thrown = ExpectedException.none(); + @InjectMocks + TagREST tagREST = new TagREST(); + @Mock + TagValidator validator; + @Mock + TagDBStore tagStore; + @Mock + RESTErrorUtil restErrorUtil; + @Mock + RangerBizUtil bizUtil; + @Mock + RangerDaoManager daoManager; + @Mock + ServiceDBStore svcStore; + @Mock + AssetMgr assetMgr; + @Mock + RangerSearchUtil searchUtil; + @Mock + RangerTagDefService tagDefService; + @Mock + RangerTagService tagService; + @Mock + RangerServiceResourceService resourceService; + @Mock + RangerServiceResourceWithTagsService serviceResourceWithTagsService; + + @Test + public void test1createTagDef() { + RangerTagDef oldTagDef = null; + RangerTagDef newTagDef = new RangerTagDef(); + newTagDef.setId(id); + newTagDef.setName(name); + + try { + Mockito.when(validator.preCreateTagDef(oldTagDef, false)).thenReturn(null); + } catch (Exception ignored) { + } + try { + Mockito.when(tagStore.createTagDef(oldTagDef)).thenReturn(newTagDef); + } catch (Exception ignored) { + } + RangerTagDef rangerTagDef = tagREST.createTagDef(oldTagDef, false); + + Assert.assertEquals(rangerTagDef.getId(), newTagDef.getId()); + Assert.assertNotNull(rangerTagDef); + Assert.assertEquals(rangerTagDef.getName(), newTagDef.getName()); + + try { + Mockito.verify(validator).preCreateTagDef(oldTagDef, false); + } catch (Exception ignored) { + } + try { + Mockito.verify(tagStore).createTagDef(oldTagDef); + } catch (Exception ignored) { + } + } + + @Test + public void test2createTagDef() { + RangerTagDef oldTagDef = new RangerTagDef(); + RangerTagDef newTagDef = new RangerTagDef(); + oldTagDef.setId(id); + newTagDef.setId(id); + newTagDef.setName(name); + + try { + Mockito.when(validator.preCreateTagDef(oldTagDef, true)).thenReturn( + oldTagDef); + } catch (Exception ignored) { + } + try { + Mockito.when(tagStore.updateTagDef(oldTagDef)).thenReturn(newTagDef); + } catch (Exception ignored) { + } + + RangerTagDef rangerTagDef = tagREST.createTagDef(oldTagDef, true); + Assert.assertEquals(rangerTagDef.getName(), newTagDef.getName()); + Assert.assertEquals(rangerTagDef.getId(), newTagDef.getId()); + Assert.assertNotEquals(oldTagDef.getName(), rangerTagDef.getName()); + + try { + Mockito.verify(validator).preCreateTagDef(oldTagDef, true); + } catch (Exception ignored) { + } + try { + Mockito.verify(tagStore).updateTagDef(oldTagDef); + } catch (Exception ignored) { + } + } + + @Test + public void test3createTagDef() { + RangerTagDef oldTagDef = new RangerTagDef(); + RangerTagDef newTagDef = new RangerTagDef(); + oldTagDef.setId(null); + newTagDef.setId(id); + newTagDef.setName(name); + + try { + Mockito.when(validator.preCreateTagDef(oldTagDef, true)).thenReturn(oldTagDef); + } catch (Exception ignored) { + } + try { + Mockito.when(tagStore.updateTagDef(oldTagDef)).thenReturn(newTagDef); + } catch (Exception ignored) { + } + + RangerTagDef rangerTagDef = tagREST.createTagDef(oldTagDef, true); + + Assert.assertNotNull(rangerTagDef); + Assert.assertEquals(rangerTagDef.getId(), newTagDef.getId()); + Assert.assertEquals(rangerTagDef.getName(), newTagDef.getName()); + Assert.assertNotEquals(rangerTagDef.getName(), oldTagDef.getName()); + + try { + Mockito.verify(validator).preCreateTagDef(oldTagDef, true); + } catch (Exception ignored) { + } + try { + Mockito.verify(tagStore).updateTagDef(oldTagDef); + } catch (Exception ignored) { + } + } + + @Test + public void test4createTagDef() { + RangerTagDef oldtagDef = new RangerTagDef(); + oldtagDef.setId(id); + + try { + Mockito.when(validator.preCreateTagDef(oldtagDef, false)).thenReturn( + oldtagDef); + } catch (Exception ignored) { + } + Mockito.when( + restErrorUtil.createRESTException(Mockito.anyInt(), + Mockito.anyString(), Mockito.anyBoolean())).thenThrow( + new WebApplicationException()); + thrown.expect(WebApplicationException.class); + tagREST.createTagDef(oldtagDef, false); + + try { + Mockito.verify(validator).preCreateTagDef(oldtagDef, false); + } catch (Exception ignored) { + } + Mockito.verify(restErrorUtil).createRESTException(Mockito.anyInt(), + Mockito.anyString(), Mockito.anyBoolean()); + } + + @Test + public void test5deleteTagDef() { + try { + Mockito.doNothing().when(tagStore).deleteTagDef(id); + } catch (Exception ignored) { + } + tagREST.deleteTagDef(id); + try { + Mockito.verify(tagStore).deleteTagDef(id); + } catch (Exception ignored) { + } + } + + @Test + public void test6deleteTagDefByGuid() { + RangerTagDef oldTagDef = new RangerTagDef(); + oldTagDef.setId(id); + oldTagDef.setGuid(gId); + + try { + Mockito.when(tagStore.getTagDefByGuid(oldTagDef.getGuid())).thenReturn(oldTagDef); + } catch (Exception ignored) { + } + try { + Mockito.doNothing().when(tagStore).deleteTagDef(oldTagDef.getId()); + } catch (Exception ignored) { + } + + tagREST.deleteTagDefByGuid(oldTagDef.getGuid()); + Assert.assertNotNull(oldTagDef.getId()); + Assert.assertNotNull(oldTagDef.getGuid()); + + try { + Mockito.verify(tagStore).getTagDefByGuid(oldTagDef.getGuid()); + } catch (Exception ignored) { + } + try { + Mockito.verify(tagStore).deleteTagDef(oldTagDef.getId()); + } catch (Exception ignored) { + } + } + + @Test + public void test7deleteTagDefByGuid() { + try { + Mockito.when(tagStore.getTagDefByGuid(gId)).thenReturn(null); + } catch (Exception ignored) { + } + tagREST.deleteTagDefByGuid(gId); + try { + Mockito.verify(tagStore).getTagDefByGuid(gId); + } catch (Exception ignored) { + } + } + + @Test + public void test8getTagDef() { + RangerTagDef oldTagDef = new RangerTagDef(); + oldTagDef.setId(id); + oldTagDef.setName(name); + + try { + Mockito.when(tagStore.getTagDef(id)).thenReturn(oldTagDef); + } catch (Exception ignored) { + } + + RangerTagDef rangerTagDef = tagREST.getTagDef(id); + Assert.assertNotNull(rangerTagDef.getId()); + Assert.assertEquals(rangerTagDef.getId(), oldTagDef.getId()); + Assert.assertEquals(rangerTagDef.getName(), oldTagDef.getName()); + + try { + Mockito.verify(tagStore).getTagDef(id); + } catch (Exception ignored) { + } + } + + @Test + public void test9getTagDef() { + try { + Mockito.when(tagStore.getTagDef(id)).thenReturn(null); + } catch (Exception ignored) { + } + Mockito.when(restErrorUtil.createRESTException(Mockito.anyInt(), Mockito.anyString(), Mockito.anyBoolean())).thenThrow(new WebApplicationException()); + thrown.expect(WebApplicationException.class); + tagREST.getTagDef(id); + + try { + Mockito.verify(tagStore).getTagDef(id); + } catch (Exception ignored) { + } + Mockito.verify(restErrorUtil).createRESTException(Mockito.anyInt(), + Mockito.anyString(), Mockito.anyBoolean()); + } + + @Test + public void test10getTagDefByGuid() { + RangerTagDef oldTagDef = new RangerTagDef(); + oldTagDef.setId(id); + oldTagDef.setGuid(gId); + + try { + Mockito.when(tagStore.getTagDefByGuid(gId)).thenReturn(oldTagDef); + } catch (Exception ignored) { + } + + RangerTagDef rangerTagDef = tagREST.getTagDefByGuid(gId); + Assert.assertNotNull(oldTagDef.getGuid()); + Assert.assertEquals(rangerTagDef.getGuid(), oldTagDef.getGuid()); + Assert.assertEquals(rangerTagDef.getId(), oldTagDef.getId()); + + try { + Mockito.verify(tagStore).getTagDefByGuid(gId); + } catch (Exception ignored) { + } + } + + @Test + public void test11getTagDefByGuid() { + try { + Mockito.when(tagStore.getTagDefByGuid(gId)).thenReturn(null); + } catch (Exception ignored) { + } + Mockito.when(restErrorUtil.createRESTException(Mockito.anyInt(), Mockito.anyString(), Mockito.anyBoolean())).thenThrow(new WebApplicationException()); + thrown.expect(WebApplicationException.class); + tagREST.getTagDefByGuid(gId); + + try { + Mockito.verify(tagStore).getTagDefByGuid(gId); + } catch (Exception ignored) { + } + Mockito.verify(restErrorUtil).createRESTException(Mockito.anyInt(), + Mockito.anyString(), Mockito.anyBoolean()); + } + + @Test + public void test12getTagDefByName() { + RangerTagDef oldTagDef = new RangerTagDef(); + oldTagDef.setId(id); + oldTagDef.setName(name); + + try { + Mockito.when(tagStore.getTagDefByName(name)).thenReturn(oldTagDef); + } catch (Exception ignored) { + } + + RangerTagDef rangerTagDef = tagREST.getTagDefByName(name); + Assert.assertNotNull(rangerTagDef.getName()); + Assert.assertEquals(rangerTagDef.getName(), oldTagDef.getName()); + Assert.assertEquals(rangerTagDef.getId(), oldTagDef.getId()); + + try { + Mockito.verify(tagStore).getTagDefByName(name); + } catch (Exception ignored) { + } + } + + @Test + public void test13getTagDefByName() { + try { + Mockito.when(tagStore.getTagDefByName(name)).thenReturn(null); + } catch (Exception ignored) { + } + Mockito.when(restErrorUtil.createRESTException(Mockito.anyInt(), Mockito.anyString(), Mockito.anyBoolean())).thenThrow(new WebApplicationException()); + thrown.expect(WebApplicationException.class); + tagREST.getTagDefByName(name); + + try { + Mockito.verify(tagStore).getTagDefByName(name); + } catch (Exception ignored) { + } + Mockito.verify(restErrorUtil).createRESTException(Mockito.anyInt(), + Mockito.anyString(), Mockito.anyBoolean()); + } + + @Test + public void test14getAllTagDefs() { + List ret = new ArrayList<>(); + RangerTagDef rangerTagDef = new RangerTagDef(); + rangerTagDef.setId(id); + rangerTagDef.setVersion(5L); + ret.add(rangerTagDef); + + try { + Mockito.when(tagStore.getTagDefs(Mockito.any())).thenReturn(ret); + } catch (Exception ignored) { + } + List result = tagREST.getAllTagDefs(); + + Assert.assertNotNull(result); + Assert.assertEquals(result.get(0).getId(), ret.get(0).getId()); + Assert.assertEquals(result.get(0).getVersion(), ret.get(0).getVersion()); + + try { + Mockito.verify(tagStore).getTagDefs(Mockito.any()); + } catch (Exception ignored) { + } + } + + @Test + public void test62getTagDefs() { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + PList ret = new PList<>(); + List tagDefList = new ArrayList<>(); + SearchFilter searchFilter = new SearchFilter(); + RangerTagDef rangerTagDef = new RangerTagDef(); + + rangerTagDef.setId(id); + rangerTagDef.setVersion(5L); + tagDefList.add(rangerTagDef); + ret.setList(tagDefList); + + Mockito.when(searchUtil.getSearchFilter(Mockito.any(HttpServletRequest.class), eq(tagDefService.sortFields))) + .thenReturn(searchFilter); + + try { + Mockito.when(tagStore.getPaginatedTagDefs(Mockito.any())).thenReturn(ret); + } catch (Exception ignored) { + } + PList result = tagREST.getTagDefs(request); + + Assert.assertNotNull(result); + Assert.assertEquals(result.getList().get(0).getId(), tagDefList.get(0).getId()); + Assert.assertEquals(result.getList().get(0).getVersion(), tagDefList.get(0).getVersion()); + + try { + Mockito.verify(tagStore).getPaginatedTagDefs(Mockito.any()); + } catch (Exception ignored) { + } + } + + @Test + public void test15getAllTagDefs() { + try { + Mockito.when(tagStore.getTagDefs(Mockito.any())).thenReturn(null); + } catch (Exception ignored) { + } + Mockito.when(restErrorUtil.createRESTException(Mockito.anyInt(), Mockito.anyString(), Mockito.anyBoolean())).thenThrow(new WebApplicationException()); + thrown.expect(WebApplicationException.class); + tagREST.getAllTagDefs(); + + try { + Mockito.verify(tagStore).getTagDefs(Mockito.any()); + } catch (Exception ignored) { + } + Mockito.verify(restErrorUtil).createRESTException(Mockito.anyInt(), Mockito.anyString(), Mockito.anyBoolean()); + } + + @Test + public void test16getTagTypes() { + boolean isAdmin = true; + List ret = new ArrayList<>(); + ret.add(name); + + try { + Mockito.when(bizUtil.isAdmin()).thenReturn(isAdmin); + Mockito.when(tagStore.getTagTypes()).thenReturn(ret); + } catch (Exception ignored) { + } + List result = tagREST.getTagTypes(); + Assert.assertNotNull(result); + + try { + Mockito.verify(tagStore).getTagTypes(); + } catch (Exception ignored) { + } + } + + @Test + public void test17createTag() { + RangerTag oldTag = null; + RangerTag newTag = new RangerTag(); + newTag.setId(id); + newTag.setGuid(gId); + + try { + Mockito.when(validator.preCreateTag(oldTag)).thenReturn(oldTag); + } catch (Exception ignored) { + } + try { + Mockito.when(tagStore.createTag(oldTag)).thenReturn(newTag); + } catch (Exception ignored) { + } + RangerTag rangerTag = tagREST.createTag(oldTag, false); + + Assert.assertEquals(rangerTag.getId(), newTag.getId()); + Assert.assertEquals(rangerTag.getGuid(), newTag.getGuid()); + + try { + Mockito.verify(validator).preCreateTag(oldTag); + } catch (Exception ignored) { + } + try { + Mockito.verify(tagStore).createTag(oldTag); + } catch (Exception ignored) { + } + } + + @Test + public void test18createTag() { + RangerTag oldTag = new RangerTag(); + RangerTag newTag = new RangerTag(); + oldTag.setId(id); + newTag.setId(id); + newTag.setVersion(5L); + + try { + Mockito.when(validator.preCreateTag(oldTag)).thenReturn(oldTag); + } catch (Exception ignored) { + } + try { + Mockito.doNothing().when(validator).preUpdateTag(oldTag.getId(), oldTag); + } catch (Exception ignored) { + } + try { + Mockito.when(tagStore.updateTag(oldTag)).thenReturn(newTag); + } catch (Exception ignored) { + } + + RangerTag rangerTag = tagREST.createTag(oldTag, true); + Assert.assertEquals(rangerTag.getVersion(), newTag.getVersion()); + Assert.assertNotNull(newTag.getVersion()); + Assert.assertNotEquals(oldTag.getVersion(), newTag.getVersion()); + Assert.assertEquals(oldTag.getId(), newTag.getId()); + + try { + Mockito.verify(validator).preCreateTag(oldTag); + } catch (Exception ignored) { + } + try { + Mockito.verify(validator).preUpdateTag(oldTag.getId(), oldTag); + } catch (Exception ignored) { + } + try { + Mockito.verify(tagStore).updateTag(oldTag); + } catch (Exception ignored) { + } + } + + @Test + public void test19createTag() { + RangerTag oldTag = new RangerTag(); + oldTag.setId(id); + + try { + Mockito.when(validator.preCreateTag(oldTag)).thenReturn(oldTag); + } catch (Exception ignored) { + } + Mockito.when(restErrorUtil.createRESTException(Mockito.anyInt(), Mockito.anyString(), Mockito.anyBoolean())).thenThrow(new WebApplicationException()); + thrown.expect(WebApplicationException.class); + tagREST.createTag(oldTag, false); + + try { + Mockito.verify(validator).preCreateTag(oldTag); + } catch (Exception ignored) { + } + Mockito.verify(restErrorUtil).createRESTException(Mockito.anyInt(), Mockito.anyString(), Mockito.anyBoolean()); + } + + @Test + public void test20updateTagByGuid() { + RangerTag oldTag = new RangerTag(); + RangerTag newTag = new RangerTag(); + oldTag.setGuid(gId); + newTag.setGuid(gId); + newTag.setVersion(5L); + + try { + Mockito.doNothing().when(validator).preUpdateTagByGuid(gId, oldTag); + } catch (Exception ignored) { + } + try { + Mockito.when(tagStore.updateTag(oldTag)).thenReturn(newTag); + } catch (Exception ignored) { + } + + RangerTag rangerTag = tagREST.updateTagByGuid(gId, oldTag); + Assert.assertEquals(oldTag.getGuid(), newTag.getGuid()); + Assert.assertNotEquals(rangerTag.getVersion(), oldTag.getVersion()); + Assert.assertEquals(rangerTag.getVersion(), newTag.getVersion()); + + try { + Mockito.verify(validator).preUpdateTagByGuid(gId, oldTag); + } catch (Exception ignored) { + } + try { + Mockito.verify(tagStore).updateTag(oldTag); + } catch (Exception ignored) { + } + } + + @Test + public void test21deleteTag() { + RangerTag oldTag = new RangerTag(); + oldTag.setId(id); + + try { + Mockito.when(validator.preDeleteTag(id)).thenReturn(oldTag); + } catch (Exception ignored) { + } + try { + Mockito.doNothing().when(tagStore).deleteTag(id); + } catch (Exception ignored) { + } + + tagREST.deleteTag(id); + Assert.assertNotNull(oldTag.getId()); + + try { + Mockito.verify(validator).preDeleteTag(id); + } catch (Exception ignored) { + } + try { + Mockito.verify(tagStore).deleteTag(id); + } catch (Exception ignored) { + } + } + + @Test + public void test22deleteTagByGuid() { + RangerTag oldTag = new RangerTag(); + oldTag.setId(id); + oldTag.setGuid(gId); + + try { + Mockito.when(validator.preDeleteTagByGuid(gId)).thenReturn(oldTag); + } catch (Exception ignored) { + } + try { + Mockito.doNothing().when(tagStore).deleteTag(oldTag.getId()); + } catch (Exception ignored) { + } + + tagREST.deleteTagByGuid(gId); + Assert.assertNotNull(oldTag.getId()); + Assert.assertNotNull(oldTag.getGuid()); + + try { + Mockito.verify(validator).preDeleteTagByGuid(gId); + } catch (Exception ignored) { + } + try { + Mockito.verify(tagStore).deleteTag(oldTag.getId()); + } catch (Exception ignored) { + } + } + + @Test + public void test23getTag() { + RangerTag oldTag = new RangerTag(); + oldTag.setId(id); + oldTag.setGuid(gId); + + try { + Mockito.when(tagStore.getTag(id)).thenReturn(oldTag); + } catch (Exception ignored) { + } + RangerTag rangerTag = tagREST.getTag(id); + Assert.assertNotNull(oldTag.getId()); + Assert.assertEquals(rangerTag.getId(), oldTag.getId()); + Assert.assertEquals(rangerTag.getGuid(), oldTag.getGuid()); + + try { + Mockito.verify(tagStore).getTag(id); + } catch (Exception ignored) { + } + } + + @Test + public void test24getTagByGuid() { + RangerTag oldTag = new RangerTag(); + oldTag.setId(id); + oldTag.setGuid(gId); + + try { + Mockito.when(tagStore.getTagByGuid(gId)).thenReturn(oldTag); + } catch (Exception ignored) { + } + RangerTag rangerTag = tagREST.getTagByGuid(gId); + Assert.assertNotNull(oldTag.getGuid()); + Assert.assertEquals(rangerTag.getGuid(), oldTag.getGuid()); + Assert.assertEquals(rangerTag.getId(), oldTag.getId()); + Assert.assertNotNull(rangerTag.getId()); + + try { + Mockito.verify(tagStore).getTagByGuid(gId); + } catch (Exception ignored) { + } + } + + @Test + public void test25getTagsByType() { + String type = "file"; + List tag = new ArrayList<>(); + RangerTag rTag = new RangerTag(); + rTag.setType(type); + tag.add(rTag); + + try { + Mockito.when(tagStore.getTagsByType(type)).thenReturn(tag); + } catch (Exception ignored) { + } + List rangerTag = tagREST.getTagsByType(type); + Assert.assertEquals(rangerTag.get(0).getType(), tag.get(0).getType()); + + try { + Mockito.verify(tagStore).getTagsByType(type); + } catch (Exception ignored) { + } + } + + @Test + public void test26getAllTags() { + boolean isAdmin = true; + List ret = new ArrayList<>(); + RangerTag rangerTag = new RangerTag(); + rangerTag.setId(id); + rangerTag.setGuid(gId); + ret.add(rangerTag); + + try { + Mockito.when(bizUtil.isAdmin()).thenReturn(isAdmin); + Mockito.when(tagStore.getTags(Mockito.any())).thenReturn(ret); + } catch (Exception ignored) { + } + + List result = tagREST.getAllTags(); + Assert.assertEquals(result.get(0).getId(), ret.get(0).getId()); + Assert.assertEquals(result.get(0).getVersion(), ret.get(0).getVersion()); + Assert.assertNotNull(result.get(0).getId()); + + try { + Mockito.verify(tagStore).getTags(Mockito.any()); + } catch (Exception ignored) { + } + } + + @Test + public void test60getAllTags() { + boolean isAdmin = true; + List ret = new ArrayList<>(); + try { + Mockito.when(bizUtil.isAdmin()).thenReturn(isAdmin); + Mockito.when(tagStore.getTags(Mockito.any())).thenReturn(ret); + } catch (Exception ignored) { + } + + List result = tagREST.getAllTags(); + Assert.assertNotNull(result); + + try { + Mockito.verify(tagStore).getTags(Mockito.any()); + } catch (Exception ignored) { + } + } + + @Test + public void test63getTags() { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + SearchFilter searchFilter = new SearchFilter(); + String testTagType = "TAG-TYPE"; + PList ret = new PList<>(); + List tagList = new ArrayList<>(); + RangerTag tag = new RangerTag(); + + tag.setType(testTagType); + tagList.add(tag); + ret.setList(tagList); + + Mockito.when(searchUtil.getSearchFilter(Mockito.any(HttpServletRequest.class), eq(tagService.sortFields))) + .thenReturn(searchFilter); + + try { + Mockito.when(tagStore.getPaginatedTags(searchFilter)).thenReturn(ret); + } catch (Exception ignored) { + } + + PList result = tagREST.getTags(request); + + Assert.assertNotNull(result); + Assert.assertEquals(result.getList().get(0).getType(), tagList.get(0).getType()); + + try { + Mockito.verify(tagStore).getPaginatedTags(Mockito.any()); + } catch (Exception ignored) { + } + } + + @Test + public void test27createServiceResource() { + RangerServiceResource oldRSR = null; + RangerServiceResource newRSR = new RangerServiceResource(); + newRSR.setId(id); + newRSR.setGuid(gId); + + try { + Mockito.when(validator.preCreateServiceResource(oldRSR)).thenReturn(oldRSR); + } catch (Exception ignored) { + } + try { + Mockito.when(tagStore.createServiceResource(oldRSR)).thenReturn(newRSR); + } catch (Exception ignored) { + } + + RangerServiceResource rangerServiceResource = tagREST.createServiceResource(oldRSR, false); + Assert.assertNotNull(rangerServiceResource.getId()); + Assert.assertEquals(rangerServiceResource.getId(), newRSR.getId()); + Assert.assertEquals(rangerServiceResource.getGuid(), newRSR.getGuid()); + + try { + Mockito.verify(validator).preCreateServiceResource(oldRSR); + } catch (Exception ignored) { + } + try { + Mockito.verify(tagStore).createServiceResource(oldRSR); + } catch (Exception ignored) { + } + } + + @Test + public void test28createServiceResource() { + RangerServiceResource oldRSR = new RangerServiceResource(); + RangerServiceResource newRSR = new RangerServiceResource(); + oldRSR.setId(id); + newRSR.setId(id); + newRSR.setVersion(5L); + + try { + Mockito.when(validator.preCreateServiceResource(oldRSR)).thenReturn(oldRSR); + } catch (Exception ignored) { + } + try { + Mockito.doNothing().when(validator).preUpdateServiceResource(oldRSR.getId(), oldRSR); + } catch (Exception ignored) { + } + try { + Mockito.when(tagStore.updateServiceResource(oldRSR)).thenReturn(newRSR); + } catch (Exception ignored) { + } + + RangerServiceResource rangerServiceResource = tagREST.createServiceResource(oldRSR, true); + Assert.assertNotEquals(oldRSR.getVersion(), newRSR.getVersion()); + Assert.assertEquals(rangerServiceResource.getId(), newRSR.getId()); + Assert.assertEquals(rangerServiceResource.getId(), oldRSR.getId()); + + try { + Mockito.verify(validator).preCreateServiceResource(oldRSR); + } catch (Exception ignored) { + } + try { + Mockito.verify(validator).preUpdateServiceResource(oldRSR.getId(), oldRSR); + } catch (Exception ignored) { + } + try { + Mockito.verify(tagStore).updateServiceResource(oldRSR); + } catch (Exception ignored) { + } + } + + @Test + public void test29createServiceResource() { + RangerServiceResource oldRSR = new RangerServiceResource(); + + try { + Mockito.when(validator.preCreateServiceResource(oldRSR)).thenReturn(oldRSR); + } catch (Exception ignored) { + } + Mockito.when(restErrorUtil.createRESTException(Mockito.anyInt(), Mockito.anyString(), Mockito.anyBoolean())).thenThrow(new WebApplicationException()); + thrown.expect(WebApplicationException.class); + tagREST.createServiceResource(oldRSR, false); + + try { + Mockito.verify(validator).preCreateServiceResource(oldRSR); + } catch (Exception ignored) { + } + Mockito.verify(restErrorUtil).createRESTException(Mockito.anyInt(), Mockito.anyString(), Mockito.anyBoolean()); + } + + @Test + public void test30updateServiceResourceByGuid() { + RangerServiceResource oldSRS = new RangerServiceResource(); + RangerServiceResource newSRS = new RangerServiceResource(); + oldSRS.setId(id); + oldSRS.setGuid(gId); + newSRS.setId(id); + newSRS.setGuid(gId); + newSRS.setVersion(5L); + + try { + Mockito.doNothing().when(validator).preUpdateServiceResourceByGuid(gId, oldSRS); + } catch (Exception ignored) { + } + try { + Mockito.when(tagStore.updateServiceResource(oldSRS)).thenReturn(newSRS); + } catch (Exception ignored) { + } + + RangerServiceResource rangerServiceResource = tagREST.updateServiceResourceByGuid(gId, oldSRS); + Assert.assertEquals(oldSRS.getId(), newSRS.getId()); + Assert.assertEquals(oldSRS.getGuid(), newSRS.getGuid()); + Assert.assertNotEquals(oldSRS.getVersion(), newSRS.getVersion()); + Assert.assertEquals(rangerServiceResource.getVersion(), newSRS.getVersion()); + + try { + Mockito.verify(validator).preUpdateServiceResourceByGuid(gId, oldSRS); + } catch (Exception ignored) { + } + try { + Mockito.verify(tagStore).updateServiceResource(oldSRS); + } catch (Exception ignored) { + } + } + + @Test + public void test31deleteServiceResource() { + RangerServiceResource oldSRS = new RangerServiceResource(); + oldSRS.setId(id); + + try { + Mockito.when(validator.preDeleteServiceResource(id)).thenReturn(oldSRS); + } catch (Exception ignored) { + } + try { + Mockito.doNothing().when(tagStore).deleteServiceResource(id); + } catch (Exception ignored) { + } + + tagREST.deleteServiceResource(id); + Assert.assertNotNull(oldSRS.getId()); + + try { + Mockito.verify(validator).preDeleteServiceResource(id); + } catch (Exception ignored) { + } + try { + Mockito.verify(tagStore).deleteServiceResource(id); + } catch (Exception ignored) { + } + } + + @Test + public void test32getServiceResource() { + RangerServiceResource oldSRS = new RangerServiceResource(); + oldSRS.setId(id); + oldSRS.setGuid(gId); + + try { + Mockito.when(tagStore.getServiceResource(id)).thenReturn(oldSRS); + } catch (Exception ignored) { + } + RangerServiceResource rangerServiceResource = tagREST.getServiceResource(id); + + Assert.assertNotNull(rangerServiceResource); + Assert.assertEquals(rangerServiceResource.getId(), oldSRS.getId()); + Assert.assertEquals(rangerServiceResource.getGuid(), oldSRS.getGuid()); + try { + Mockito.verify(tagStore).getServiceResource(id); + } catch (Exception ignored) { + } + } + + @Test + public void test33getServiceResourceByGuid() { + RangerServiceResource oldSRS = new RangerServiceResource(); + oldSRS.setId(id); + oldSRS.setGuid(gId); + + try { + Mockito.when(tagStore.getServiceResourceByGuid(gId)).thenReturn(oldSRS); + } catch (Exception ignored) { + } + RangerServiceResource rangerServiceResource = tagREST.getServiceResourceByGuid(gId); + + Assert.assertNotNull(rangerServiceResource); + Assert.assertEquals(rangerServiceResource.getGuid(), oldSRS.getGuid()); + Assert.assertEquals(rangerServiceResource.getId(), oldSRS.getId()); + try { + Mockito.verify(tagStore).getServiceResourceByGuid(gId); + } catch (Exception ignored) { + } + } + + @Test + public void test34getServiceResourcesByService() { + List ret = new ArrayList<>(); + RangerServiceResource rangerServiceResource = new RangerServiceResource(); + rangerServiceResource.setId(id); + rangerServiceResource.setServiceName(serviceName); + ret.add(rangerServiceResource); + + try { + Mockito.when(tagStore.getServiceResourcesByService(serviceName)).thenReturn(ret); + } catch (Exception ignored) { + } + + List reslut = tagREST.getServiceResourcesByService(serviceName); + Assert.assertNotNull(reslut.get(0).getId()); + Assert.assertEquals(reslut.get(0).getId(), ret.get(0).getId()); + Assert.assertEquals(reslut.get(0).getServiceName(), ret.get(0).getServiceName()); + + try { + Mockito.verify(tagStore).getServiceResourcesByService(serviceName); + } catch (Exception ignored) { + } + } + + @Test + public void test35getServiceResourcesByService() { + List oldSRS = new ArrayList<>(); + RangerServiceResource rangerServiceResource = new RangerServiceResource(); + rangerServiceResource.setId(id); + rangerServiceResource.setServiceName(serviceName); + oldSRS.add(rangerServiceResource); + + try { + Mockito.when(tagStore.getServiceResourcesByService(serviceName)).thenReturn(oldSRS); + } catch (Exception ignored) { + } + + List result = tagREST.getServiceResourcesByService(serviceName); + Assert.assertNotNull(result); + Assert.assertEquals(1, result.size()); + Assert.assertEquals(id, result.get(0).getId()); + Assert.assertEquals(serviceName, result.get(0).getServiceName()); + + try { + Mockito.verify(tagStore).getServiceResourcesByService(serviceName); + } catch (Exception ignored) { + } + } + + @Test + public void test59getServiceResourcesByService() { + List oldSRS = new ArrayList<>(); + + try { + Mockito.when(tagStore.getServiceResourcesByService(serviceName)).thenReturn(oldSRS); + } catch (Exception ignored) { + } + + List result = tagREST.getServiceResourcesByService(serviceName); + Assert.assertNotNull(result); + + try { + Mockito.verify(tagStore).getServiceResourcesByService(serviceName); + } catch (Exception ignored) { + } + } + + @Test + public void test36getServiceResourceByServiceAndResourceSignature() { + RangerServiceResource oldSRS = new RangerServiceResource(); + oldSRS.setId(id); + oldSRS.setResourceSignature(resourceSignature); + oldSRS.setServiceName(serviceName); + + try { + Mockito.when(tagStore.getServiceResourceByServiceAndResourceSignature(serviceName, resourceSignature)).thenReturn(oldSRS); + } catch (Exception ignored) { + } + + RangerServiceResource rangerServiceResource = tagREST.getServiceResourceByServiceAndResourceSignature(serviceName, resourceSignature); + Assert.assertEquals(rangerServiceResource.getId(), oldSRS.getId()); + Assert.assertEquals(rangerServiceResource.getServiceName(), oldSRS.getServiceName()); + Assert.assertEquals(rangerServiceResource.getResourceSignature(), oldSRS.getResourceSignature()); + + try { + Mockito.verify(tagStore).getServiceResourceByServiceAndResourceSignature(serviceName, resourceSignature); + } catch (Exception ignored) { + } + } + + @Test + public void test37getAllServiceResources() { + boolean isAdmin = true; + List ret = new ArrayList<>(); + RangerServiceResource rangerServiceResource = new RangerServiceResource(); + rangerServiceResource.setId(id); + rangerServiceResource.setServiceName(serviceName); + ret.add(rangerServiceResource); + + try { + Mockito.when(bizUtil.isAdmin()).thenReturn(isAdmin); + Mockito.when(tagStore.getServiceResources(Mockito.any())).thenReturn(ret); + } catch (Exception ignored) { + } + List result = tagREST.getAllServiceResources(); + Assert.assertNotNull(result.get(0).getId()); + Assert.assertEquals(result.get(0).getId(), ret.get(0).getId()); + Assert.assertEquals(result.get(0).getServiceName(), ret.get(0).getServiceName()); + + try { + Mockito.verify(tagStore).getServiceResources(Mockito.any()); + } catch (Exception ignored) { + } + } + + @Test + public void test64getServiceResourcesWithTags() { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + SearchFilter searchFilter = new SearchFilter(); + RangerServiceResourceWithTagsList ret = new RangerServiceResourceWithTagsList(); + List serviceResourceList = new ArrayList<>(); + RangerServiceResourceWithTags rangerServiceResource = new RangerServiceResourceWithTags(); + List associatedTags = new ArrayList<>(); + RangerTag rangerTag = new RangerTag(); + + rangerTag.setId(id); + rangerTag.setGuid(gId); + rangerTag.setType(name); + associatedTags.add(rangerTag); + + rangerServiceResource.setId(id); + rangerServiceResource.setServiceName(serviceName); + rangerServiceResource.setAssociatedTags(associatedTags); + serviceResourceList.add(rangerServiceResource); + ret.setResourceList(serviceResourceList); + + Mockito.when(searchUtil.getSearchFilter(Mockito.any(HttpServletRequest.class), eq(resourceService.sortFields))).thenReturn(searchFilter); + + try { + Mockito.when(tagStore.getPaginatedServiceResourcesWithTags(Mockito.any())).thenReturn(ret); + } catch (Exception ignored) { + } + + RangerServiceResourceWithTagsList result = tagREST.getServiceResourcesWithTags(request); + + Assert.assertNotNull(result.getResourceList().get(0).getId()); + Assert.assertEquals(result.getResourceList().get(0).getId(), serviceResourceList.get(0).getId()); + Assert.assertEquals(result.getResourceList().get(0).getServiceName(), serviceResourceList.get(0).getServiceName()); + Assert.assertEquals(1, result.getResourceList().get(0).getAssociatedTags().size()); + Assert.assertEquals(name, result.getResourceList().get(0).getAssociatedTags().get(0).getType()); + + try { + Mockito.verify(tagStore).getPaginatedServiceResourcesWithTags(Mockito.any()); + } catch (Exception ignored) { + } + } + + @Test + public void test38createTagResourceMap() { + RangerTagResourceMap oldTagResourceMap = null; + RangerTagResourceMap newTagResourceMap = new RangerTagResourceMap(); + + newTagResourceMap.setTagId(id); + newTagResourceMap.setResourceId(id); + + try { + Mockito.when(tagStore.getTagResourceMapForTagAndResourceGuid(tagGuid, resourceGuid)).thenReturn(oldTagResourceMap); + } catch (Exception ignored) { + } + try { + Mockito.when(validator.preCreateTagResourceMap(tagGuid, resourceGuid)).thenReturn(newTagResourceMap); + } catch (Exception ignored) { + } + try { + Mockito.when(tagStore.createTagResourceMap(newTagResourceMap)).thenReturn(newTagResourceMap); + } catch (Exception ignored) { + } + + RangerTagResourceMap rangerTagResourceMap = tagREST.createTagResourceMap(tagGuid, resourceGuid, false); + + Assert.assertEquals(rangerTagResourceMap.getTagId(), newTagResourceMap.getTagId()); + Assert.assertEquals(rangerTagResourceMap.getResourceId(), newTagResourceMap.getResourceId()); + + try { + Mockito.verify(tagStore).getTagResourceMapForTagAndResourceGuid(tagGuid, resourceGuid); + } catch (Exception ignored) { + } + + try { + Mockito.verify(validator).preCreateTagResourceMap(tagGuid, resourceGuid); + } catch (Exception ignored) { + } + + try { + Mockito.verify(tagStore).createTagResourceMap(newTagResourceMap); + } catch (Exception ignored) { + } + } + + @Test + public void test39createTagResourceMap() { + RangerTagResourceMap oldTagResourceMap = new RangerTagResourceMap(); + + try { + Mockito.when(tagStore.getTagResourceMapForTagAndResourceGuid(tagGuid, resourceGuid)).thenReturn(oldTagResourceMap); + } catch (Exception ignored) { + } + + Mockito.when(restErrorUtil.createRESTException(Mockito.anyInt(), Mockito.anyString(), Mockito.anyBoolean())).thenThrow(new WebApplicationException()); + + thrown.expect(WebApplicationException.class); + tagREST.createTagResourceMap(tagGuid, resourceGuid, false); + + try { + Mockito.verify(tagStore).getTagResourceMapForTagAndResourceGuid(tagGuid, resourceGuid); + } catch (Exception ignored) { + } + Mockito.verify(restErrorUtil).createRESTException(Mockito.anyInt(), Mockito.anyString(), Mockito.anyBoolean()); + } + + @Test + public void test40createTagResourceMap() { + RangerTagResourceMap oldTagResourceMap = null; + RangerTagResourceMap newTagResourceMap = new RangerTagResourceMap(); + newTagResourceMap.setId(id); + newTagResourceMap.setGuid(gId); + RangerTagResourceMap finalTagResourceMap = new RangerTagResourceMap(); + finalTagResourceMap.setId(id); + finalTagResourceMap.setGuid(gId); + finalTagResourceMap.setVersion(5L); + + try { + Mockito.when(tagStore.getTagResourceMapForTagAndResourceGuid(tagGuid, resourceGuid)).thenReturn(oldTagResourceMap); + } catch (Exception ignored) { + } + try { + Mockito.when(validator.preCreateTagResourceMap(tagGuid, resourceGuid)).thenReturn(newTagResourceMap); + } catch (Exception ignored) { + } + try { + Mockito.when(tagStore.createTagResourceMap(newTagResourceMap)).thenReturn(finalTagResourceMap); + } catch (Exception ignored) { + } + RangerTagResourceMap result = tagREST.createTagResourceMap(tagGuid, resourceGuid, true); + Assert.assertNotNull(result.getId()); + Assert.assertEquals(result.getGuid(), finalTagResourceMap.getGuid()); + Assert.assertEquals(result.getId(), finalTagResourceMap.getId()); + Assert.assertEquals(result.getVersion(), finalTagResourceMap.getVersion()); + + try { + Mockito.verify(tagStore).getTagResourceMapForTagAndResourceGuid(tagGuid, resourceGuid); + } catch (Exception ignored) { + } + try { + Mockito.verify(validator).preCreateTagResourceMap(tagGuid, resourceGuid); + } catch (Exception ignored) { + } + try { + Mockito.verify(tagStore).createTagResourceMap(newTagResourceMap); + } catch (Exception ignored) { + } + } + + @Test + public void test41deleteTagResourceMap() { + RangerTagResourceMap oldTagResourceMap = new RangerTagResourceMap(); + oldTagResourceMap.setId(id); + try { + Mockito.when(validator.preDeleteTagResourceMap(id)).thenReturn(oldTagResourceMap); + } catch (Exception ignored) { + } + try { + Mockito.doNothing().when(tagStore).deleteTagResourceMap(id); + } catch (Exception ignored) { + } + + tagREST.deleteTagResourceMap(id); + Assert.assertNotNull(oldTagResourceMap.getId()); + try { + Mockito.verify(validator).preDeleteTagResourceMap(id); + } catch (Exception ignored) { + } + try { + Mockito.verify(tagStore).deleteTagResourceMap(id); + } catch (Exception ignored) { + } + } + + @Test + public void test42deleteTagResourceMapByGuid() { + RangerTagResourceMap oldTagResourceMap = new RangerTagResourceMap(); + oldTagResourceMap.setId(id); + oldTagResourceMap.setGuid(gId); + try { + Mockito.when(validator.preDeleteTagResourceMapByGuid(gId)).thenReturn(oldTagResourceMap); + } catch (Exception ignored) { + } + try { + Mockito.doNothing().when(tagStore).deleteTagResourceMap(oldTagResourceMap.getId()); + } catch (Exception ignored) { + } + + tagREST.deleteTagResourceMapByGuid(gId); + Assert.assertNotNull(oldTagResourceMap.getId()); + Assert.assertNotNull(oldTagResourceMap.getGuid()); + + try { + Mockito.verify(validator).preDeleteTagResourceMapByGuid(gId); + } catch (Exception ignored) { + } + try { + Mockito.verify(tagStore).deleteTagResourceMap(oldTagResourceMap.getId()); + } catch (Exception ignored) { + } + } + + @Test + public void test43deleteTagResourceMap() { + RangerTagResourceMap oldTagResourceMap = new RangerTagResourceMap(); + oldTagResourceMap.setId(id); + + try { + Mockito.when(validator.preDeleteTagResourceMap(tagGuid, resourceGuid)).thenReturn(oldTagResourceMap); + } catch (Exception ignored) { + } + try { + Mockito.doNothing().when(tagStore).deleteTagResourceMap(oldTagResourceMap.getId()); + } catch (Exception ignored) { + } + + tagREST.deleteTagResourceMap(tagGuid, resourceGuid); + try { + Mockito.verify(validator).preDeleteTagResourceMap(tagGuid, resourceGuid); + } catch (Exception ignored) { + } + } + + @Test + public void test44getTagResourceMap() { + RangerTagResourceMap oldTagResourceMap = new RangerTagResourceMap(); + oldTagResourceMap.setId(id); + oldTagResourceMap.setGuid(gId); + + try { + Mockito.when(tagStore.getTagResourceMap(id)).thenReturn(oldTagResourceMap); + } catch (Exception ignored) { + } + + RangerTagResourceMap rangerTagResourceMap = tagREST.getTagResourceMap(id); + Assert.assertNotNull(rangerTagResourceMap.getId()); + Assert.assertEquals(rangerTagResourceMap.getId(), oldTagResourceMap.getId()); + Assert.assertEquals(rangerTagResourceMap.getGuid(), oldTagResourceMap.getGuid()); + try { + Mockito.verify(tagStore).getTagResourceMap(id); + } catch (Exception ignored) { + } + } + + @Test + public void test45getTagResourceMapByGuid() { + RangerTagResourceMap oldTagResourceMap = new RangerTagResourceMap(); + oldTagResourceMap.setId(id); + oldTagResourceMap.setGuid(gId); + + try { + Mockito.when(tagStore.getTagResourceMapByGuid(gId)).thenReturn(oldTagResourceMap); + } catch (Exception ignored) { + } + + RangerTagResourceMap rangerTagResourceMap = tagREST.getTagResourceMapByGuid(gId); + Assert.assertNotNull(rangerTagResourceMap.getId()); + Assert.assertEquals(rangerTagResourceMap.getId(), oldTagResourceMap.getId()); + Assert.assertEquals(rangerTagResourceMap.getGuid(), oldTagResourceMap.getGuid()); + try { + Mockito.verify(tagStore).getTagResourceMapByGuid(gId); + } catch (Exception ignored) { + } + } + + @Test + public void test46getTagResourceMap() { + RangerTagResourceMap oldTagResourceMap = new RangerTagResourceMap(); + oldTagResourceMap.setId(id); + oldTagResourceMap.setTagId(id); + + try { + Mockito.when(tagStore.getTagResourceMapForTagAndResourceGuid(tagGuid, resourceGuid)).thenReturn(oldTagResourceMap); + } catch (Exception ignored) { + } + RangerTagResourceMap rangerTagResourceMap = tagREST.getTagResourceMap(tagGuid, resourceGuid); + Assert.assertNotNull(rangerTagResourceMap.getId()); + Assert.assertEquals(rangerTagResourceMap.getId(), oldTagResourceMap.getId()); + Assert.assertEquals(rangerTagResourceMap.getTagId(), oldTagResourceMap.getTagId()); + try { + Mockito.verify(tagStore).getTagResourceMapForTagAndResourceGuid(tagGuid, resourceGuid); + } catch (Exception ignored) { + } + } + + @Test + public void test47getAllTagResourceMaps() { + List ret = new ArrayList<>(); + RangerTagResourceMap rangerTagResourceMap = new RangerTagResourceMap(); + rangerTagResourceMap.setId(id); + rangerTagResourceMap.setTagId(id); + ret.add(rangerTagResourceMap); + + try { + Mockito.when(tagStore.getTagResourceMaps(Mockito.any())).thenReturn(ret); + } catch (Exception ignored) { + } + + List result = tagREST.getAllTagResourceMaps(); + Assert.assertNotNull(result.get(0).getId()); + Assert.assertEquals(result.get(0).getId(), ret.get(0).getId()); + Assert.assertEquals(result.get(0).getTagId(), ret.get(0).getTagId()); + + try { + Mockito.verify(tagStore).getTagResourceMaps(Mockito.any()); + } catch (Exception ignored) { + } + } + + @Test + public void test58getAllTagResourceMaps() { + List ret = new ArrayList<>(); + + try { + Mockito.when(tagStore.getTagResourceMaps(Mockito.any())).thenReturn(ret); + } catch (Exception ignored) { + } + + List result = tagREST.getAllTagResourceMaps(); + Assert.assertNotNull(result); + + try { + Mockito.verify(tagStore).getTagResourceMaps(Mockito.any()); + } catch (Exception ignored) { + } + } + + @Test + public void test48deleteServiceResourceByGuid() { + RangerServiceResource oldRSR = new RangerServiceResource(); + oldRSR.setId(id); + oldRSR.setGuid(gId); + List tagResourceMaps = new ArrayList<>(); + RangerTagResourceMap rangerTagResourceMap = new RangerTagResourceMap(); + rangerTagResourceMap.setId(id); + rangerTagResourceMap.setTagId(id); + tagResourceMaps.add(rangerTagResourceMap); + + try { + Mockito.when(validator.preDeleteServiceResourceByGuid(gId, true)).thenReturn(oldRSR); + } catch (Exception ignored) { + } + try { + Mockito.when(tagStore.getTagResourceMapsForResourceGuid(oldRSR.getGuid())).thenReturn(tagResourceMaps); + } catch (Exception ignored) { + } + tagREST.deleteServiceResourceByGuid(gId, true); + + try { + Mockito.verify(validator).preDeleteServiceResourceByGuid(gId, true); + } catch (Exception ignored) { + } + try { + Mockito.verify(tagStore).getTagResourceMapsForResourceGuid(oldRSR.getGuid()); + } catch (Exception ignored) { + } + } + + @Test + public void test49deleteServiceResourceByGuid() { + RangerServiceResource oldRSR = new RangerServiceResource(); + oldRSR.setId(id); + oldRSR.setGuid(gId); + + try { + Mockito.when(validator.preDeleteServiceResourceByGuid(gId, false)).thenReturn(oldRSR); + } catch (Exception ignored) { + } + try { + Mockito.doNothing().when(tagStore).deleteServiceResource(oldRSR.getId()); + } catch (Exception ignored) { + } + + tagREST.deleteServiceResourceByGuid(gId, false); + + try { + Mockito.verify(validator).preDeleteServiceResourceByGuid(gId, false); + } catch (Exception ignored) { + } + } + + @Test + public void test61deleteServiceResourceByGuid() { + RangerServiceResource oldRSR = new RangerServiceResource(); + oldRSR.setId(id); + oldRSR.setGuid(gId); + List tagResourceMaps = new ArrayList<>(); + + try { + Mockito.when(validator.preDeleteServiceResourceByGuid(gId, true)).thenReturn(oldRSR); + } catch (Exception ignored) { + } + try { + Mockito.when(tagStore.getTagResourceMapsForResourceGuid(oldRSR.getGuid())).thenReturn(tagResourceMaps); + } catch (Exception ignored) { + } + tagREST.deleteServiceResourceByGuid(gId, true); + + try { + Mockito.verify(validator).preDeleteServiceResourceByGuid(gId, true); + } catch (Exception ignored) { + } + try { + Mockito.verify(tagStore).getTagResourceMapsForResourceGuid(oldRSR.getGuid()); + } catch (Exception ignored) { + } + } + + @Test + public void test50getServiceTagsIfUpdated() { + ServiceTags oldServiceTag = null; + + try { + Mockito.when(tagStore.getServiceTagsIfUpdated(serviceName, lastKnownVersion, true)).thenReturn(oldServiceTag); + } catch (Exception ignored) { + } + Mockito.when(restErrorUtil.createRESTException(Mockito.anyInt(), Mockito.anyString(), Mockito.anyBoolean())).thenThrow(new WebApplicationException()); + thrown.expect(WebApplicationException.class); + + tagREST.getServiceTagsIfUpdated(serviceName, lastKnownVersion, 0L, pluginId, false, capabilityVector, null); + + try { + Mockito.verify(tagStore).getServiceTagsIfUpdated(serviceName, lastKnownVersion, true); + } catch (Exception ignored) { + } + Mockito.verify(restErrorUtil).createRESTException(Mockito.anyInt(), Mockito.anyString(), Mockito.anyBoolean()); + } + + @Test + public void test51getServiceTagsIfUpdated() { + ServiceTags oldServiceTag = new ServiceTags(); + oldServiceTag.setServiceName(serviceName); + oldServiceTag.setTagVersion(5L); + + try { + Mockito.when(tagStore.getServiceTagsIfUpdated(serviceName, lastKnownVersion, true)).thenReturn(oldServiceTag); + } catch (Exception ignored) { + } + ServiceTags serviceTags = tagREST.getServiceTagsIfUpdated(serviceName, lastKnownVersion, 0L, pluginId, false, capabilityVector, null); + Assert.assertEquals(serviceTags.getServiceName(), oldServiceTag.getServiceName()); + Assert.assertEquals(serviceTags.getTagVersion(), oldServiceTag.getTagVersion()); + + try { + Mockito.verify(tagStore).getServiceTagsIfUpdated(serviceName, lastKnownVersion, true); + } catch (Exception ignored) { + } + } + + @Test + public void test52getSecureServiceTagsIfUpdatedIsKeyAdminTrue() { + boolean isAdmin = false; + boolean isKeyAdmin = true; + ServiceTags oldServiceTag = new ServiceTags(); + oldServiceTag.setServiceName(serviceName); + oldServiceTag.setTagVersion(5L); + + XXService xService = new XXService(); + xService.setId(id); + xService.setName(serviceName); + xService.setType(5L); + + XXServiceDef xServiceDef = new XXServiceDef(); + xServiceDef.setId(id); + xServiceDef.setVersion(5L); + xServiceDef.setImplclassname("org.apache.ranger.services.kms.RangerServiceKMS"); + + RangerService rangerService = new RangerService(); + rangerService.setId(id); + rangerService.setName(serviceName); + + XXServiceDao xXServiceDao = Mockito.mock(XXServiceDao.class); + XXServiceDefDao xXServiceDefDao = Mockito.mock(XXServiceDefDao.class); + + Mockito.when(bizUtil.isAdmin()).thenReturn(isAdmin); + Mockito.when(bizUtil.isKeyAdmin()).thenReturn(isKeyAdmin); + + Mockito.when(daoManager.getXXService()).thenReturn(xXServiceDao); + Mockito.when(xXServiceDao.findByName(serviceName)).thenReturn(xService); + Mockito.when(daoManager.getXXServiceDef()).thenReturn(xXServiceDefDao); + Mockito.when(xXServiceDefDao.getById(xService.getType())).thenReturn(xServiceDef); + try { + Mockito.when(svcStore.getServiceByName(serviceName)).thenReturn(rangerService); + } catch (Exception ignored) { + } + + try { + Mockito.when(tagStore.getServiceTagsIfUpdated(serviceName, lastKnownVersion, true)).thenReturn(oldServiceTag); + } catch (Exception ignored) { + } + + ServiceTags result = tagREST.getSecureServiceTagsIfUpdated(serviceName, lastKnownVersion, 0L, pluginId, false, capabilityVector, null); + Assert.assertNotNull(result.getServiceName()); + Assert.assertEquals(result.getServiceName(), oldServiceTag.getServiceName()); + Assert.assertEquals(result.getTagVersion(), oldServiceTag.getTagVersion()); + + Mockito.verify(bizUtil).isAdmin(); + Mockito.verify(bizUtil).isKeyAdmin(); + Mockito.verify(daoManager).getXXService(); + Mockito.verify(xXServiceDao).findByName(serviceName); + Mockito.verify(daoManager).getXXServiceDef(); + Mockito.verify(xXServiceDefDao).getById(xService.getType()); + try { + Mockito.verify(svcStore).getServiceByName(serviceName); + } catch (Exception ignored) { + } + try { + Mockito.verify(tagStore).getServiceTagsIfUpdated(serviceName, lastKnownVersion, true); + } catch (Exception ignored) { + } + } + + @Test + public void test53getSecureServiceTagsIfUpdatedIsAdminTrue() { + boolean isAdmin = true; + boolean isKeyAdmin = false; + ServiceTags oldServiceTag = new ServiceTags(); + oldServiceTag.setServiceName(serviceName); + oldServiceTag.setTagVersion(5L); + + XXService xService = new XXService(); + xService.setId(id); + xService.setName(serviceName); + xService.setType(5L); + + XXServiceDef xServiceDef = new XXServiceDef(); + xServiceDef.setId(id); + xServiceDef.setVersion(5L); + + RangerService rangerService = new RangerService(); + rangerService.setId(id); + rangerService.setName(serviceName); + + XXServiceDao xXServiceDao = Mockito.mock(XXServiceDao.class); + XXServiceDefDao xXServiceDefDao = Mockito.mock(XXServiceDefDao.class); + + Mockito.when(bizUtil.isAdmin()).thenReturn(isAdmin); + Mockito.when(bizUtil.isKeyAdmin()).thenReturn(isKeyAdmin); + + Mockito.when(daoManager.getXXService()).thenReturn(xXServiceDao); + Mockito.when(xXServiceDao.findByName(serviceName)).thenReturn(xService); + Mockito.when(daoManager.getXXServiceDef()).thenReturn(xXServiceDefDao); + Mockito.when(xXServiceDefDao.getById(xService.getType())).thenReturn(xServiceDef); + try { + Mockito.when(svcStore.getServiceByName(serviceName)).thenReturn(rangerService); + } catch (Exception ignored) { + } + + try { + Mockito.when(tagStore.getServiceTagsIfUpdated(serviceName, lastKnownVersion, true)).thenReturn(oldServiceTag); + } catch (Exception ignored) { + } + + ServiceTags result = tagREST.getSecureServiceTagsIfUpdated(serviceName, lastKnownVersion, 0L, pluginId, false, capabilityVector, null); + Assert.assertNotNull(result.getServiceName()); + Assert.assertEquals(result.getServiceName(), oldServiceTag.getServiceName()); + Assert.assertEquals(result.getTagVersion(), oldServiceTag.getTagVersion()); + + Mockito.verify(bizUtil).isAdmin(); + Mockito.verify(bizUtil).isKeyAdmin(); + Mockito.verify(daoManager).getXXService(); + Mockito.verify(xXServiceDao).findByName(serviceName); + Mockito.verify(daoManager).getXXServiceDef(); + Mockito.verify(xXServiceDefDao).getById(xService.getType()); + try { + Mockito.verify(svcStore).getServiceByName(serviceName); + } catch (Exception ignored) { + } + try { + Mockito.verify(tagStore).getServiceTagsIfUpdated(serviceName, lastKnownVersion, true); + } catch (Exception ignored) { + } + } + + @Test + public void test54getSecureServiceTagsIfUpdatedIsKeyAdminFalse() { + boolean isAdmin = false; + boolean isKeyAdmin = false; + boolean isAllowed = true; + ServiceTags oldServiceTag = new ServiceTags(); + oldServiceTag.setServiceName(serviceName); + oldServiceTag.setTagVersion(5L); + + XXService xService = new XXService(); + xService.setId(id); + xService.setName(serviceName); + xService.setType(5L); + + XXServiceDef xServiceDef = new XXServiceDef(); + xServiceDef.setId(id); + xServiceDef.setVersion(5L); + xServiceDef.setImplclassname("org.apache.ranger.services.kms.RangerServiceKMS"); + + RangerService rangerService = new RangerService(); + rangerService.setId(id); + rangerService.setName(serviceName); + + XXServiceDao xXServiceDao = Mockito.mock(XXServiceDao.class); + XXServiceDefDao xXServiceDefDao = Mockito.mock(XXServiceDefDao.class); + + Mockito.when(bizUtil.isAdmin()).thenReturn(isAdmin); + Mockito.when(bizUtil.isKeyAdmin()).thenReturn(isKeyAdmin); + + Mockito.when(daoManager.getXXService()).thenReturn(xXServiceDao); + Mockito.when(xXServiceDao.findByName(serviceName)).thenReturn(xService); + Mockito.when(daoManager.getXXServiceDef()).thenReturn(xXServiceDefDao); + Mockito.when(xXServiceDefDao.getById(xService.getType())).thenReturn(xServiceDef); + try { + Mockito.when(svcStore.getServiceByName(serviceName)).thenReturn(rangerService); + } catch (Exception ignored) { + } + + Mockito.when(bizUtil.isUserAllowed(rangerService, Allowed_User_List_For_Tag_Download)).thenReturn(isAllowed); + try { + Mockito.when(tagStore.getServiceTagsIfUpdated(serviceName, lastKnownVersion, true)).thenReturn(oldServiceTag); + } catch (Exception ignored) { + } + + ServiceTags result = tagREST.getSecureServiceTagsIfUpdated(serviceName, lastKnownVersion, 0L, pluginId, false, capabilityVector, null); + Assert.assertNotNull(result.getServiceName()); + Assert.assertEquals(result.getServiceName(), oldServiceTag.getServiceName()); + Assert.assertEquals(result.getTagVersion(), oldServiceTag.getTagVersion()); + + Mockito.verify(bizUtil).isAdmin(); + Mockito.verify(bizUtil).isKeyAdmin(); + Mockito.verify(daoManager).getXXService(); + Mockito.verify(xXServiceDao).findByName(serviceName); + Mockito.verify(daoManager).getXXServiceDef(); + Mockito.verify(xXServiceDefDao).getById(xService.getType()); + try { + Mockito.verify(svcStore).getServiceByName(serviceName); + } catch (Exception ignored) { + } + Mockito.verify(bizUtil).isUserAllowed(rangerService, Allowed_User_List_For_Tag_Download); + try { + Mockito.verify(tagStore).getServiceTagsIfUpdated(serviceName, lastKnownVersion, true); + } catch (Exception ignored) { + } + } + + @Test + public void test55getSecureServiceTagsIfUpdatedIsAdminFalse() { + boolean isAdmin = false; + boolean isKeyAdmin = false; + boolean isAllowed = true; + ServiceTags oldServiceTag = new ServiceTags(); + oldServiceTag.setServiceName(serviceName); + oldServiceTag.setTagVersion(5L); + + XXService xService = new XXService(); + xService.setId(id); + xService.setName(serviceName); + xService.setType(5L); + + XXServiceDef xServiceDef = new XXServiceDef(); + xServiceDef.setId(id); + xServiceDef.setVersion(5L); + + RangerService rangerService = new RangerService(); + rangerService.setId(id); + rangerService.setName(serviceName); + + XXServiceDao xXServiceDao = Mockito.mock(XXServiceDao.class); + XXServiceDefDao xXServiceDefDao = Mockito.mock(XXServiceDefDao.class); + + Mockito.when(bizUtil.isAdmin()).thenReturn(isAdmin); + Mockito.when(bizUtil.isKeyAdmin()).thenReturn(isKeyAdmin); + + Mockito.when(daoManager.getXXService()).thenReturn(xXServiceDao); + Mockito.when(xXServiceDao.findByName(serviceName)).thenReturn(xService); + Mockito.when(daoManager.getXXServiceDef()).thenReturn(xXServiceDefDao); + Mockito.when(xXServiceDefDao.getById(xService.getType())).thenReturn(xServiceDef); + try { + Mockito.when(svcStore.getServiceByName(serviceName)).thenReturn(rangerService); + } catch (Exception ignored) { + } + + Mockito.when(bizUtil.isUserAllowed(rangerService, Allowed_User_List_For_Tag_Download)).thenReturn(isAllowed); + try { + Mockito.when(tagStore.getServiceTagsIfUpdated(serviceName, lastKnownVersion, true)).thenReturn(oldServiceTag); + } catch (Exception ignored) { + } + + ServiceTags result = tagREST.getSecureServiceTagsIfUpdated(serviceName, lastKnownVersion, 0L, pluginId, false, capabilityVector, null); + Assert.assertNotNull(result.getServiceName()); + Assert.assertEquals(result.getServiceName(), oldServiceTag.getServiceName()); + Assert.assertEquals(result.getTagVersion(), oldServiceTag.getTagVersion()); + + Mockito.verify(bizUtil).isAdmin(); + Mockito.verify(bizUtil).isKeyAdmin(); + Mockito.verify(daoManager).getXXService(); + Mockito.verify(xXServiceDao).findByName(serviceName); + Mockito.verify(daoManager).getXXServiceDef(); + Mockito.verify(xXServiceDefDao).getById(xService.getType()); + try { + Mockito.verify(svcStore).getServiceByName(serviceName); + } catch (Exception ignored) { + } + Mockito.verify(bizUtil).isUserAllowed(rangerService, Allowed_User_List_For_Tag_Download); + try { + Mockito.verify(tagStore).getServiceTagsIfUpdated(serviceName, lastKnownVersion, true); + } catch (Exception ignored) { + } + } + + @Test + public void test56getSecureServiceTagsIfUpdatedIsAllowedFalse() { + boolean isAdmin = false; + boolean isKeyAdmin = false; + boolean isAllowed = false; + ServiceTags oldServiceTag = new ServiceTags(); + oldServiceTag.setServiceName(serviceName); + oldServiceTag.setTagVersion(5L); + + XXService xService = new XXService(); + xService.setId(id); + xService.setName(serviceName); + xService.setType(5L); + + XXServiceDef xServiceDef = new XXServiceDef(); + xServiceDef.setId(id); + xServiceDef.setVersion(5L); + + RangerService rangerService = new RangerService(); + rangerService.setId(id); + rangerService.setName(serviceName); + + XXServiceDao xXServiceDao = Mockito.mock(XXServiceDao.class); + XXServiceDefDao xXServiceDefDao = Mockito.mock(XXServiceDefDao.class); + + Mockito.when(bizUtil.isAdmin()).thenReturn(isAdmin); + Mockito.when(bizUtil.isKeyAdmin()).thenReturn(isKeyAdmin); + + Mockito.when(daoManager.getXXService()).thenReturn(xXServiceDao); + Mockito.when(xXServiceDao.findByName(serviceName)).thenReturn(xService); + Mockito.when(daoManager.getXXServiceDef()).thenReturn(xXServiceDefDao); + Mockito.when(xXServiceDefDao.getById(xService.getType())).thenReturn(xServiceDef); + try { + Mockito.when(svcStore.getServiceByName(serviceName)).thenReturn(rangerService); + } catch (Exception ignored) { + } + + Mockito.when(bizUtil.isUserAllowed(rangerService, Allowed_User_List_For_Tag_Download)).thenReturn(isAllowed); + Mockito.when(restErrorUtil.createRESTException(Mockito.anyInt(), Mockito.anyString(), Mockito.anyBoolean())).thenThrow(new WebApplicationException()); + thrown.expect(WebApplicationException.class); + + tagREST.getSecureServiceTagsIfUpdated(serviceName, lastKnownVersion, 0L, pluginId, false, capabilityVector, null); + + Mockito.verify(bizUtil).isAdmin(); + Mockito.verify(bizUtil).isKeyAdmin(); + Mockito.verify(daoManager).getXXService(); + Mockito.verify(xXServiceDao).findByName(serviceName); + Mockito.verify(daoManager).getXXServiceDef(); + Mockito.verify(xXServiceDefDao).getById(xService.getType()); + try { + Mockito.verify(svcStore).getServiceByName(serviceName); + } catch (Exception ignored) { + } + Mockito.verify(bizUtil).isUserAllowed(rangerService, Allowed_User_List_For_Tag_Download); + Mockito.verify(restErrorUtil).createRESTException(Mockito.anyInt(), Mockito.anyString(), Mockito.anyBoolean()); + } + + @Test + public void test57getSecureServiceTagsIfUpdated() { + boolean isAdmin = false; + boolean isKeyAdmin = false; + boolean isAllowed = true; + ServiceTags oldServiceTag = null; + + XXService xService = new XXService(); + xService.setId(id); + xService.setName(serviceName); + xService.setType(5L); + + XXServiceDef xServiceDef = new XXServiceDef(); + xServiceDef.setId(id); + xServiceDef.setVersion(5L); + + RangerService rangerService = new RangerService(); + rangerService.setId(id); + rangerService.setName(serviceName); + + XXServiceDao xXServiceDao = Mockito.mock(XXServiceDao.class); + XXServiceDefDao xXServiceDefDao = Mockito.mock(XXServiceDefDao.class); + + Mockito.when(bizUtil.isAdmin()).thenReturn(isAdmin); + Mockito.when(bizUtil.isKeyAdmin()).thenReturn(isKeyAdmin); + + Mockito.when(daoManager.getXXService()).thenReturn(xXServiceDao); + Mockito.when(xXServiceDao.findByName(serviceName)).thenReturn(xService); + Mockito.when(daoManager.getXXServiceDef()).thenReturn(xXServiceDefDao); + Mockito.when(xXServiceDefDao.getById(xService.getType())).thenReturn(xServiceDef); + try { + Mockito.when(svcStore.getServiceByName(serviceName)).thenReturn(rangerService); + } catch (Exception ignored) { + } + + Mockito.when(bizUtil.isUserAllowed(rangerService, Allowed_User_List_For_Tag_Download)).thenReturn(isAllowed); + try { + Mockito.when(tagStore.getServiceTagsIfUpdated(serviceName, lastKnownVersion, true)).thenReturn(oldServiceTag); + } catch (Exception ignored) { + } + Mockito.when(restErrorUtil.createRESTException(Mockito.anyInt(), Mockito.anyString(), Mockito.anyBoolean())).thenThrow(new WebApplicationException()); + thrown.expect(WebApplicationException.class); + + tagREST.getSecureServiceTagsIfUpdated(serviceName, lastKnownVersion, 0L, pluginId, false, capabilityVector, null); + + Mockito.verify(bizUtil).isAdmin(); + Mockito.verify(bizUtil).isKeyAdmin(); + Mockito.verify(daoManager).getXXService(); + Mockito.verify(xXServiceDao).findByName(serviceName); + Mockito.verify(daoManager).getXXServiceDef(); + Mockito.verify(xXServiceDefDao).getById(xService.getType()); + try { + Mockito.verify(svcStore).getServiceByName(serviceName); + } catch (Exception ignored) { + } + Mockito.verify(bizUtil).isUserAllowed(rangerService, Allowed_User_List_For_Tag_Download); + try { + Mockito.verify(tagStore).getServiceTagsIfUpdated(serviceName, lastKnownVersion, false); + } catch (Exception ignored) { + } + Mockito.verify(restErrorUtil).createRESTException(Mockito.anyInt(), Mockito.anyString(), Mockito.anyBoolean()); + } + + @Test + public void test58resetTagCacheByServiceNameForServiceAdmin() { + boolean isAdmin = false; + boolean res = true; + RangerService rangerService = new RangerService(); + rangerService.setId(id); + rangerService.setName(serviceName); + String userName = "admin"; + Mockito.when(bizUtil.getCurrentUserLoginId()).thenReturn(userName); + + Mockito.when(bizUtil.isAdmin()).thenReturn(isAdmin); + try { + Mockito.when(svcStore.getServiceByName(serviceName)).thenReturn(rangerService); + } catch (Exception ignored) { + } + Mockito.when(bizUtil.isUserServiceAdmin(Mockito.any(RangerService.class), Mockito.anyString())).thenReturn(true); + try { + Mockito.when(tagStore.resetTagCache(serviceName)).thenReturn(true); + } catch (Exception ignored) { + } + boolean isReset = tagREST.resetTagCache(serviceName); + Assert.assertEquals(res, isReset); + Mockito.verify(bizUtil).isAdmin(); + Mockito.verify(bizUtil).isUserServiceAdmin(Mockito.any(RangerService.class), Mockito.anyString()); + try { + Mockito.verify(svcStore).getServiceByName(serviceName); + } catch (Exception ignored) { + } + + try { + Mockito.verify(tagStore).resetTagCache(serviceName); + } catch (Exception ignored) { + } + } + + @Test + public void test59resetTagCacheWhenServiceNameIsInvalid() { + try { + Mockito.when(svcStore.getServiceByName(serviceName)).thenReturn(null); + } catch (Exception ignored) { + } + Mockito.when(restErrorUtil.createRESTException(Mockito.anyInt(), Mockito.anyString(), Mockito.anyBoolean())).thenThrow(new WebApplicationException()); + thrown.expect(WebApplicationException.class); + tagREST.resetTagCache(serviceName); + Mockito.verify(restErrorUtil).createRESTException(Mockito.anyInt(), Mockito.anyString(), Mockito.anyBoolean()); + } + + static { + capabilityVector = Long.toHexString(new RangerPluginCapability().getPluginCapabilities()); + } } diff --git a/security-admin/src/test/java/org/apache/ranger/rest/TestUserREST.java b/security-admin/src/test/java/org/apache/ranger/rest/TestUserREST.java index 4af1769763..eabed08d12 100644 --- a/security-admin/src/test/java/org/apache/ranger/rest/TestUserREST.java +++ b/security-admin/src/test/java/org/apache/ranger/rest/TestUserREST.java @@ -17,13 +17,6 @@ package org.apache.ranger.rest; -import java.util.ArrayList; -import java.util.List; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpSession; -import javax.ws.rs.WebApplicationException; - import org.apache.ranger.biz.UserMgr; import org.apache.ranger.biz.XUserMgr; import org.apache.ranger.common.MessageEnums; @@ -56,427 +49,396 @@ import org.mockito.Mockito; import org.mockito.junit.MockitoJUnitRunner; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpSession; +import javax.ws.rs.WebApplicationException; + +import java.util.ArrayList; +import java.util.List; + @RunWith(MockitoJUnitRunner.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class TestUserREST { - - @InjectMocks - UserREST userREST = new UserREST(); - - @Mock - HttpServletRequest request; - - @Mock - SearchUtil searchUtil; - - @Mock - RangerConfigUtil configUtil; - - @Mock - UserMgr userManager; - - @Mock - RangerDaoManager daoManager; - - @Mock - XUserMgr xUserMgr; - - @Mock - RESTErrorUtil restErrorUtil; - - @Mock - VXPortalUserList vXPUserExpList; - - @Mock - RangerRestUtil msRestUtil; - - @Mock - VXPortalUser vxPUserAct; - - @Mock - VXPasswordChange changePassword; - - @Mock - VXResponse responseExp; - - @Mock - StringUtil stringUtil; - - @Rule - public ExpectedException thrown = ExpectedException.none(); - - Long userId = 10l; - int pageSize = 100; - String firstName = "abc"; - String lastName = "xyz"; - String loginId = "xyzId"; - String emailId = "abc@Example.com"; - - String oldPassword = "ranger123$"; - String newPassword = "rangerAdmin1234$"; - - @Test - public void test1SearchUsers() { - SearchCriteria searchCriteria = new SearchCriteria(); - vXPUserExpList = new VXPortalUserList(); - vXPUserExpList.setPageSize(pageSize); - List status = new ArrayList(); - String publicScreenName = "nrp"; - List roles = new ArrayList(); - - Mockito.when(searchUtil.extractCommonCriterias(Matchers.eq(request), Matchers.anyListOf(SortField.class))).thenReturn(searchCriteria); - Mockito.when(searchUtil.extractLong(request, searchCriteria, "userId", "User Id")).thenReturn(userId); - Mockito.when(searchUtil.extractString(request, searchCriteria, "loginId", "Login Id", null)) - .thenReturn(loginId); - Mockito.when(searchUtil.extractString(request, searchCriteria, "emailAddress", "Email Address", null)) - .thenReturn(emailId); - Mockito.when(searchUtil.extractString(request, searchCriteria, "firstName", "First Name", - StringUtil.VALIDATION_NAME)).thenReturn(firstName); - Mockito.when( - searchUtil.extractString(request, searchCriteria, "lastName", "Last Name", StringUtil.VALIDATION_NAME)) - .thenReturn(lastName); - Mockito.when(searchUtil.extractEnum(request, searchCriteria, "status", "Status", "statusList", - RangerConstants.ActivationStatus_MAX)).thenReturn(status); - Mockito.when(searchUtil.extractString(request, searchCriteria, "publicScreenName", "Public Screen Name", - StringUtil.VALIDATION_NAME)).thenReturn(publicScreenName); - Mockito.when(searchUtil.extractStringList(request, searchCriteria, "role", "Role", "roleList", - configUtil.getRoles(), StringUtil.VALIDATION_NAME)).thenReturn(roles); - Mockito.when(userManager.searchUsers(searchCriteria)).thenReturn(vXPUserExpList); - - VXPortalUserList vXPUserListAct = userREST.searchUsers(request); - - Assert.assertNotNull(vXPUserListAct); - Assert.assertEquals(vXPUserExpList, vXPUserListAct); - Assert.assertEquals(vXPUserExpList.getPageSize(), vXPUserListAct.getPageSize()); - - Mockito.verify(searchUtil).extractCommonCriterias(Matchers.eq(request), Matchers.anyListOf(SortField.class)); - Mockito.verify(searchUtil).extractLong(request, searchCriteria, "userId", "User Id"); - Mockito.verify(searchUtil).extractString(request, searchCriteria, "loginId", "Login Id", null); - Mockito.verify(searchUtil).extractString(request, searchCriteria, "emailAddress", "Email Address", null); - Mockito.verify(searchUtil).extractString(request, searchCriteria, "firstName", "First Name", - StringUtil.VALIDATION_NAME); - Mockito.verify(searchUtil).extractString(request, searchCriteria, "lastName", "Last Name", - StringUtil.VALIDATION_NAME); - Mockito.verify(searchUtil).extractEnum(request, searchCriteria, "status", "Status", "statusList", - RangerConstants.ActivationStatus_MAX); - Mockito.verify(searchUtil).extractString(request, searchCriteria, "publicScreenName", "Public Screen Name", - StringUtil.VALIDATION_NAME); - Mockito.verify(searchUtil).extractStringList(request, searchCriteria, "role", "Role", "roleList", - configUtil.getRoles(), StringUtil.VALIDATION_NAME); - Mockito.verify(userManager).searchUsers(searchCriteria); - } - - @Test - public void test2GetUserProfileForUser() { - VXPortalUser vxPUserExp = CreateVXPortalUser(); - - Mockito.when(userManager.getUserProfile(userId)).thenReturn(vxPUserExp); - - VXPortalUser VXPUserAct = userREST.getUserProfileForUser(userId); - - Assert.assertNotNull(VXPUserAct); - Assert.assertEquals(vxPUserExp, VXPUserAct); - Assert.assertEquals(vxPUserExp.getLoginId(), VXPUserAct.getLoginId()); - Assert.assertEquals(vxPUserExp.getFirstName(), VXPUserAct.getFirstName()); - Assert.assertEquals(vxPUserExp.getEmailAddress(), VXPUserAct.getEmailAddress()); - Assert.assertEquals(vxPUserExp.getId(), VXPUserAct.getId()); - - Mockito.verify(userManager).getUserProfile(userId); - } - - @Test - public void test3GetUserProfileForUser() { - VXPortalUser vxPUserExp = new VXPortalUser(); - vxPUserExp = null; - - Mockito.when(userManager.getUserProfile(userId)).thenReturn(vxPUserExp); - - VXPortalUser VXPUserAct = userREST.getUserProfileForUser(userId); - - Assert.assertEquals(vxPUserExp, VXPUserAct); - - Mockito.verify(userManager).getUserProfile(userId); - } - - @Test - public void test6Create() { - VXPortalUser vxPUserExp = CreateVXPortalUser(); - - Mockito.when(userManager.createUser(vxPUserExp)).thenReturn(vxPUserExp); - - VXPortalUser VXPUserAct = userREST.create(vxPUserExp, request); - - Assert.assertNotNull(VXPUserAct); - Assert.assertEquals(vxPUserExp.getLoginId(), VXPUserAct.getLoginId()); - Assert.assertEquals(vxPUserExp.getFirstName(), VXPUserAct.getFirstName()); - Assert.assertEquals(vxPUserExp.getLastName(), VXPUserAct.getLastName()); - Assert.assertEquals(vxPUserExp.getEmailAddress(), VXPUserAct.getEmailAddress()); - - Mockito.verify(userManager).createUser(vxPUserExp); - } - - @Test - public void test7CreateDefaultAccountUser() { - VXPortalUser vxPUserExp = new VXPortalUser(); - vxPUserExp = null; - Mockito.when(userManager.createDefaultAccountUser(vxPUserExp)).thenReturn(vxPUserExp); - - VXPortalUser VXPUserAct = userREST.createDefaultAccountUser(vxPUserExp, request); - - Assert.assertNull(VXPUserAct); - - Mockito.verify(userManager).createDefaultAccountUser(vxPUserExp); - } - - @Test - public void test8CreateDefaultAccountUser() { - VXPortalUser vxPUserExp = CreateVXPortalUser(); - - Mockito.when(userManager.createDefaultAccountUser(vxPUserExp)).thenReturn(vxPUserExp); - Mockito.doNothing().when(xUserMgr).assignPermissionToUser(vxPUserExp, true); - - VXPortalUser VXPUserAct = userREST.createDefaultAccountUser(vxPUserExp, request); - - Assert.assertNotNull(VXPUserAct); - Assert.assertEquals(vxPUserExp, VXPUserAct); - Assert.assertEquals(vxPUserExp.getLoginId(), VXPUserAct.getLoginId()); - Assert.assertEquals(vxPUserExp.getFirstName(), VXPUserAct.getFirstName()); - Assert.assertEquals(vxPUserExp.getLastName(), VXPUserAct.getLastName()); - Assert.assertEquals(vxPUserExp.getEmailAddress(), VXPUserAct.getEmailAddress()); - - Mockito.verify(userManager).createDefaultAccountUser(vxPUserExp); - Mockito.verify(xUserMgr).assignPermissionToUser(vxPUserExp, true); - } - - @Test - public void test8Update() { - VXPortalUser vxPUserExp = CreateVXPortalUser(); - vxPUserExp.setLoginId(loginId); - XXPortalUser xxPUserExp = new XXPortalUser(); - xxPUserExp.setLoginId(loginId); - XXPortalUserDao xxPortalUserDao = Mockito.mock(XXPortalUserDao.class); - - Mockito.when(daoManager.getXXPortalUser()).thenReturn(xxPortalUserDao); - Mockito.when(xxPortalUserDao.getById(Mockito.anyLong())).thenReturn(xxPUserExp); - Mockito.doNothing().when(userManager).checkAccess(xxPUserExp); - Mockito.doNothing().when(msRestUtil).validateVUserProfileForUpdate(xxPUserExp, vxPUserExp); - Mockito.when(userManager.updateUser(vxPUserExp)).thenReturn(xxPUserExp); - Mockito.when(userManager.mapXXPortalUserVXPortalUser(xxPUserExp)).thenReturn(vxPUserExp); - - VXPortalUser vxPUserAct = userREST.update(vxPUserExp, request); - - Assert.assertNotNull(vxPUserAct); - Assert.assertEquals(xxPUserExp.getLoginId(), vxPUserAct.getLoginId()); - Assert.assertEquals(vxPUserExp.getId(), vxPUserAct.getId()); - Assert.assertEquals(vxPUserExp.getFirstName(), vxPUserAct.getFirstName()); - - Mockito.verify(daoManager).getXXPortalUser(); - Mockito.verify(xxPortalUserDao).getById(Mockito.anyLong()); - Mockito.verify(userManager).checkAccess(xxPUserExp); - Mockito.verify(msRestUtil).validateVUserProfileForUpdate(xxPUserExp, vxPUserExp); - Mockito.verify(userManager).updateUser(vxPUserExp); - Mockito.verify(userManager).mapXXPortalUserVXPortalUser(xxPUserExp); - } - - @Test - public void test9Update() { - VXPortalUser vxPUserExp = new VXPortalUser(); - XXPortalUser xxPUserExp = new XXPortalUser(); - xxPUserExp = null; - XXPortalUserDao xxPortalUserDao = Mockito.mock(XXPortalUserDao.class); - - Mockito.when(daoManager.getXXPortalUser()).thenReturn(xxPortalUserDao); - Mockito.doNothing().when(userManager).checkAccess(xxPUserExp); - Mockito.when(restErrorUtil.createRESTException(Mockito.anyString(), (MessageEnums) Mockito.any(), - Mockito.nullable(Long.class), Mockito.nullable(String.class), Mockito.anyString())).thenReturn(new WebApplicationException()); - - thrown.expect(WebApplicationException.class); - - userREST.update(vxPUserExp, request); - - Mockito.verify(daoManager).getXXPortalUser(); - Mockito.verify(xxPortalUserDao).getById(Mockito.anyLong()); - Mockito.verify(userManager).checkAccess(xxPUserExp); - Mockito.verify(restErrorUtil).createRESTException(Mockito.anyString(), (MessageEnums) Mockito.any(), - Mockito.anyLong(), Mockito.anyString(), Mockito.anyString()); - } - - @Test - public void test10SetUserRoles() { - Long userId = 10L; - VXResponse responseExp = new VXResponse(); - VXStringList roleList = new VXStringList(); - Mockito.doNothing().when(userManager).checkAccess(userId); - Mockito.doNothing().when(userManager).setUserRoles(userId, roleList.getVXStrings()); - - VXResponse responseAct = userREST.setUserRoles(userId, roleList); - - Assert.assertNotNull(responseAct); - Assert.assertEquals(responseExp.getStatusCode(), responseAct.getStatusCode()); - - Mockito.verify(userManager).checkAccess(userId); - Mockito.verify(userManager).setUserRoles(userId, roleList.getVXStrings()); - } - - @Test - public void test11DeactivateUser() { - VXPortalUser vxPUserExp = CreateVXPortalUser(); - XXPortalUser xxPUserExp = new XXPortalUser(); - xxPUserExp.setLoginId(loginId); - xxPUserExp.setStatus(1); - vxPUserExp.setStatus(5); - - XXPortalUserDao xxPortalUserDao = Mockito.mock(XXPortalUserDao.class); - - Mockito.when(daoManager.getXXPortalUser()).thenReturn(xxPortalUserDao); - Mockito.when(xxPortalUserDao.getById(userId)).thenReturn(xxPUserExp); - Mockito.when(userManager.deactivateUser(xxPUserExp)).thenReturn(vxPUserExp); - - VXPortalUser vxPUserAct = userREST.deactivateUser(userId); - Assert.assertNotNull(vxPUserAct); - Assert.assertEquals(xxPUserExp.getLoginId(), vxPUserAct.getLoginId()); - Assert.assertEquals(vxPUserExp.getStatus(), vxPUserAct.getStatus()); - Assert.assertEquals(vxPUserExp.getId(), vxPUserAct.getId()); - Assert.assertEquals(vxPUserExp.getFirstName(), vxPUserAct.getFirstName()); - - Mockito.verify(daoManager).getXXPortalUser(); - Mockito.verify(xxPortalUserDao).getById(userId); - Mockito.verify(userManager).deactivateUser(xxPUserExp); - } - - @Test - public void test12DeactivateUser() { - XXPortalUser xxPUserExp = new XXPortalUser(); - xxPUserExp = null; - XXPortalUserDao xxPortalUserDao = Mockito.mock(XXPortalUserDao.class); - - Mockito.when(daoManager.getXXPortalUser()).thenReturn(xxPortalUserDao); - Mockito.when(xxPortalUserDao.getById(userId)).thenReturn(xxPUserExp); - Mockito.when(restErrorUtil.createRESTException(Mockito.anyString(), (MessageEnums) Mockito.any(), - Mockito.nullable(Long.class), Mockito.nullable(String.class), Mockito.anyString())).thenReturn(new WebApplicationException()); - thrown.expect(WebApplicationException.class); - - userREST.deactivateUser(userId); - - Mockito.verify(daoManager).getXXPortalUser(); - Mockito.verify(xxPortalUserDao).getById(userId); - Mockito.verify(restErrorUtil).createRESTException(Mockito.anyString(), (MessageEnums) Mockito.any(), - Mockito.anyLong(), Mockito.anyString(), Mockito.anyString()); - } - - @Test - public void test13GetUserProfile() { - HttpSession hs = Mockito.mock(HttpSession.class); - VXPortalUser vxPUserExp = CreateVXPortalUser(); - Mockito.when(userManager.getUserProfileByLoginId()).thenReturn(vxPUserExp); - Mockito.when(request.getSession()).thenReturn(hs); - Mockito.when(hs.getId()).thenReturn("id"); - - VXPortalUser vxPUserAct = userREST.getUserProfile(request); - - Assert.assertNotNull(vxPUserAct); - Assert.assertEquals(vxPUserExp, vxPUserAct); - Assert.assertEquals(vxPUserExp.getId(), vxPUserAct.getId()); - Assert.assertEquals(vxPUserExp.getFirstName(), vxPUserAct.getFirstName()); - - Mockito.verify(userManager).getUserProfileByLoginId(); - } - - @Test - public void test16ChangePassword() { - XXPortalUser xxPUser = new XXPortalUser(); - VXResponse vxResponseExp = new VXResponse(); - VXPasswordChange vxPasswordChange = createPasswordChange(); - vxResponseExp.setStatusCode(10); - XXPortalUserDao xxPortalUserDao = Mockito.mock(XXPortalUserDao.class); - - Mockito.when(daoManager.getXXPortalUser()).thenReturn(xxPortalUserDao); - Mockito.when(restErrorUtil.createRESTException("serverMsg.userRestUser",MessageEnums.DATA_NOT_FOUND, null, null, vxPasswordChange.getLoginId())).thenThrow(new WebApplicationException()); - thrown.expect(WebApplicationException.class); - VXResponse vxResponseAct = userREST.changePassword(userId, vxPasswordChange); - - Assert.assertNotNull(vxResponseAct); - Assert.assertEquals(vxResponseExp, vxResponseAct); - Assert.assertEquals(vxResponseExp.getStatusCode(), vxResponseAct.getStatusCode()); - - Mockito.verify(daoManager).getXXPortalUser(); - Mockito.verify(xxPortalUserDao).getById(userId); - Mockito.verify(userManager).checkAccess(xxPUser); - Mockito.verify(userManager).changePassword(vxPasswordChange); - } - - @Test - public void test17ChangePassword() { - XXPortalUserDao xxPortalUserDao = Mockito.mock(XXPortalUserDao.class); - Mockito.when(restErrorUtil.createRESTException(Mockito.anyString(), (MessageEnums) Mockito.any(), - Mockito.nullable(Long.class), Mockito.nullable(String.class), Mockito.nullable(String.class))).thenReturn(new WebApplicationException()); - thrown.expect(WebApplicationException.class); - - userREST.changePassword(userId, changePassword); - - Mockito.verify(daoManager).getXXPortalUser(); - Mockito.verify(xxPortalUserDao).getById(userId); - Mockito.verify(restErrorUtil).createRESTException(Mockito.anyString(), (MessageEnums) Mockito.any(), - Mockito.anyLong(), Mockito.anyString(), Mockito.anyString()); - } - - @Test - public void test18ChangeEmailAddress() { - XXPortalUser xxPUser = new XXPortalUser(); - VXPortalUser vxPUserExp = CreateVXPortalUser(); - VXPasswordChange changeEmail = createPasswordChange(); - - XXPortalUserDao xxPortalUserDao = Mockito.mock(XXPortalUserDao.class); - - Mockito.when(daoManager.getXXPortalUser()).thenReturn(xxPortalUserDao); - Mockito.when(restErrorUtil.createRESTException("serverMsg.userRestUser",MessageEnums.DATA_NOT_FOUND, null, null, changeEmail.getLoginId())).thenThrow(new WebApplicationException()); - thrown.expect(WebApplicationException.class); - VXPortalUser vxPortalUserAct = userREST.changeEmailAddress(userId, changeEmail); - - Assert.assertNotNull(vxPortalUserAct); - Assert.assertEquals(vxPUserExp, vxPortalUserAct); - Assert.assertEquals(vxPUserExp.getId(), vxPortalUserAct.getId()); - Assert.assertEquals(vxPUserExp.getFirstName(), vxPortalUserAct.getFirstName()); - - Mockito.verify(daoManager).getXXPortalUser(); - Mockito.verify(xxPortalUserDao).getById(userId); - Mockito.verify(userManager).checkAccess(xxPUser); - Mockito.verify(userManager).changeEmailAddress(xxPUser, changeEmail); - } - - @Test - public void test19ChangeEmailAddress() { - XXPortalUserDao xxPortalUserDao = Mockito.mock(XXPortalUserDao.class); - Mockito.when(restErrorUtil.createRESTException(Mockito.anyString(), (MessageEnums) Mockito.any(), - Mockito.nullable(Long.class), Mockito.nullable(String.class), Mockito.nullable(String.class))).thenReturn(new WebApplicationException()); - thrown.expect(WebApplicationException.class); - - userREST.changeEmailAddress(userId, changePassword); - - Mockito.verify(daoManager).getXXPortalUser(); - Mockito.verify(xxPortalUserDao).getById(userId); - Mockito.verify(restErrorUtil).createRESTException(Mockito.anyString(), (MessageEnums) Mockito.any(), - Mockito.anyLong(), Mockito.anyString(), Mockito.anyString()); - } - - private VXPortalUser CreateVXPortalUser() { - - VXPortalUser vxPUserExp = new VXPortalUser(); - vxPUserExp.setId(userId); - vxPUserExp.setFirstName(firstName); - vxPUserExp.setLastName(lastName); - vxPUserExp.setEmailAddress(emailId); - vxPUserExp.setLoginId(loginId); - return vxPUserExp; - } - - private VXPasswordChange createPasswordChange() { - VXPasswordChange vxPasswordChange = new VXPasswordChange(); - vxPasswordChange.setId(userId); - vxPasswordChange.setOldPassword(oldPassword); - vxPasswordChange.setUpdPassword(newPassword); - vxPasswordChange.setEmailAddress(emailId); - vxPasswordChange.setLoginId(loginId); - return vxPasswordChange; - } + @Rule + public ExpectedException thrown = ExpectedException.none(); + @InjectMocks + UserREST userREST = new UserREST(); + @Mock + HttpServletRequest request; + @Mock + SearchUtil searchUtil; + @Mock + RangerConfigUtil configUtil; + @Mock + UserMgr userManager; + @Mock + RangerDaoManager daoManager; + @Mock + XUserMgr xUserMgr; + @Mock + RESTErrorUtil restErrorUtil; + @Mock + VXPortalUserList vXPUserExpList; + @Mock + RangerRestUtil msRestUtil; + @Mock + VXPortalUser vxPUserAct; + @Mock + VXPasswordChange changePassword; + @Mock + VXResponse responseExp; + @Mock + StringUtil stringUtil; + Long userId = 10L; + int pageSize = 100; + String firstName = "abc"; + String lastName = "xyz"; + String loginId = "xyzId"; + String emailId = "abc@Example.com"; + + String oldPassword = "ranger123$"; + String newPassword = "rangerAdmin1234$"; + + @Test + public void test1SearchUsers() { + SearchCriteria searchCriteria = new SearchCriteria(); + vXPUserExpList = new VXPortalUserList(); + vXPUserExpList.setPageSize(pageSize); + List status = new ArrayList<>(); + String publicScreenName = "nrp"; + List roles = new ArrayList<>(); + + Mockito.when(searchUtil.extractCommonCriterias(Matchers.eq(request), Matchers.anyListOf(SortField.class))).thenReturn(searchCriteria); + Mockito.when(searchUtil.extractLong(request, searchCriteria, "userId", "User Id")).thenReturn(userId); + Mockito.when(searchUtil.extractString(request, searchCriteria, "loginId", "Login Id", null)).thenReturn(loginId); + Mockito.when(searchUtil.extractString(request, searchCriteria, "emailAddress", "Email Address", null)).thenReturn(emailId); + Mockito.when(searchUtil.extractString(request, searchCriteria, "firstName", "First Name", StringUtil.VALIDATION_NAME)).thenReturn(firstName); + Mockito.when(searchUtil.extractString(request, searchCriteria, "lastName", "Last Name", StringUtil.VALIDATION_NAME)).thenReturn(lastName); + Mockito.when(searchUtil.extractEnum(request, searchCriteria, "status", "Status", "statusList", RangerConstants.ActivationStatus_MAX)).thenReturn(status); + Mockito.when(searchUtil.extractString(request, searchCriteria, "publicScreenName", "Public Screen Name", StringUtil.VALIDATION_NAME)).thenReturn(publicScreenName); + Mockito.when(searchUtil.extractStringList(request, searchCriteria, "role", "Role", "roleList", configUtil.getRoles(), StringUtil.VALIDATION_NAME)).thenReturn(roles); + Mockito.when(userManager.searchUsers(searchCriteria)).thenReturn(vXPUserExpList); + + VXPortalUserList vXPUserListAct = userREST.searchUsers(request); + + Assert.assertNotNull(vXPUserListAct); + Assert.assertEquals(vXPUserExpList, vXPUserListAct); + Assert.assertEquals(vXPUserExpList.getPageSize(), vXPUserListAct.getPageSize()); + + Mockito.verify(searchUtil).extractCommonCriterias(Matchers.eq(request), Matchers.anyListOf(SortField.class)); + Mockito.verify(searchUtil).extractLong(request, searchCriteria, "userId", "User Id"); + Mockito.verify(searchUtil).extractString(request, searchCriteria, "loginId", "Login Id", null); + Mockito.verify(searchUtil).extractString(request, searchCriteria, "emailAddress", "Email Address", null); + Mockito.verify(searchUtil).extractString(request, searchCriteria, "firstName", "First Name", StringUtil.VALIDATION_NAME); + Mockito.verify(searchUtil).extractString(request, searchCriteria, "lastName", "Last Name", StringUtil.VALIDATION_NAME); + Mockito.verify(searchUtil).extractEnum(request, searchCriteria, "status", "Status", "statusList", RangerConstants.ActivationStatus_MAX); + Mockito.verify(searchUtil).extractString(request, searchCriteria, "publicScreenName", "Public Screen Name", StringUtil.VALIDATION_NAME); + Mockito.verify(searchUtil).extractStringList(request, searchCriteria, "role", "Role", "roleList", configUtil.getRoles(), StringUtil.VALIDATION_NAME); + Mockito.verify(userManager).searchUsers(searchCriteria); + } + + @Test + public void test2GetUserProfileForUser() { + VXPortalUser vxPUserExp = createVXPortalUser(); + + Mockito.when(userManager.getUserProfile(userId)).thenReturn(vxPUserExp); + + VXPortalUser vxPUserAct = userREST.getUserProfileForUser(userId); + + Assert.assertNotNull(vxPUserAct); + Assert.assertEquals(vxPUserExp, vxPUserAct); + Assert.assertEquals(vxPUserExp.getLoginId(), vxPUserAct.getLoginId()); + Assert.assertEquals(vxPUserExp.getFirstName(), vxPUserAct.getFirstName()); + Assert.assertEquals(vxPUserExp.getEmailAddress(), vxPUserAct.getEmailAddress()); + Assert.assertEquals(vxPUserExp.getId(), vxPUserAct.getId()); + + Mockito.verify(userManager).getUserProfile(userId); + } + + @Test + public void test3GetUserProfileForUser() { + VXPortalUser vxPUserExp = new VXPortalUser(); + vxPUserExp = null; + + Mockito.when(userManager.getUserProfile(userId)).thenReturn(vxPUserExp); + + VXPortalUser vxPUserAct = userREST.getUserProfileForUser(userId); + + Assert.assertEquals(vxPUserExp, vxPUserAct); + + Mockito.verify(userManager).getUserProfile(userId); + } + + @Test + public void test6Create() { + VXPortalUser vxPUserExp = createVXPortalUser(); + + Mockito.when(userManager.createUser(vxPUserExp)).thenReturn(vxPUserExp); + + VXPortalUser vxPUserAct = userREST.create(vxPUserExp, request); + + Assert.assertNotNull(vxPUserAct); + Assert.assertEquals(vxPUserExp.getLoginId(), vxPUserAct.getLoginId()); + Assert.assertEquals(vxPUserExp.getFirstName(), vxPUserAct.getFirstName()); + Assert.assertEquals(vxPUserExp.getLastName(), vxPUserAct.getLastName()); + Assert.assertEquals(vxPUserExp.getEmailAddress(), vxPUserAct.getEmailAddress()); + + Mockito.verify(userManager).createUser(vxPUserExp); + } + + @Test + public void test7CreateDefaultAccountUser() { + VXPortalUser vxPUserExp = new VXPortalUser(); + vxPUserExp = null; + Mockito.when(userManager.createDefaultAccountUser(vxPUserExp)).thenReturn(vxPUserExp); + + VXPortalUser vxPUserAct = userREST.createDefaultAccountUser(vxPUserExp, request); + + Assert.assertNull(vxPUserAct); + + Mockito.verify(userManager).createDefaultAccountUser(vxPUserExp); + } + + @Test + public void test8CreateDefaultAccountUser() { + VXPortalUser vxPUserExp = createVXPortalUser(); + + Mockito.when(userManager.createDefaultAccountUser(vxPUserExp)).thenReturn(vxPUserExp); + Mockito.doNothing().when(xUserMgr).assignPermissionToUser(vxPUserExp, true); + + VXPortalUser vxPUserAct = userREST.createDefaultAccountUser(vxPUserExp, request); + + Assert.assertNotNull(vxPUserAct); + Assert.assertEquals(vxPUserExp, vxPUserAct); + Assert.assertEquals(vxPUserExp.getLoginId(), vxPUserAct.getLoginId()); + Assert.assertEquals(vxPUserExp.getFirstName(), vxPUserAct.getFirstName()); + Assert.assertEquals(vxPUserExp.getLastName(), vxPUserAct.getLastName()); + Assert.assertEquals(vxPUserExp.getEmailAddress(), vxPUserAct.getEmailAddress()); + + Mockito.verify(userManager).createDefaultAccountUser(vxPUserExp); + Mockito.verify(xUserMgr).assignPermissionToUser(vxPUserExp, true); + } + + @Test + public void test8Update() { + VXPortalUser vxPUserExp = createVXPortalUser(); + vxPUserExp.setLoginId(loginId); + XXPortalUser xxPUserExp = new XXPortalUser(); + xxPUserExp.setLoginId(loginId); + XXPortalUserDao xxPortalUserDao = Mockito.mock(XXPortalUserDao.class); + + Mockito.when(daoManager.getXXPortalUser()).thenReturn(xxPortalUserDao); + Mockito.when(xxPortalUserDao.getById(Mockito.anyLong())).thenReturn(xxPUserExp); + Mockito.doNothing().when(userManager).checkAccess(xxPUserExp); + Mockito.doNothing().when(msRestUtil).validateVUserProfileForUpdate(xxPUserExp, vxPUserExp); + Mockito.when(userManager.updateUser(vxPUserExp)).thenReturn(xxPUserExp); + Mockito.when(userManager.mapXXPortalUserVXPortalUser(xxPUserExp)).thenReturn(vxPUserExp); + + VXPortalUser vxPUserAct = userREST.update(vxPUserExp, request); + + Assert.assertNotNull(vxPUserAct); + Assert.assertEquals(xxPUserExp.getLoginId(), vxPUserAct.getLoginId()); + Assert.assertEquals(vxPUserExp.getId(), vxPUserAct.getId()); + Assert.assertEquals(vxPUserExp.getFirstName(), vxPUserAct.getFirstName()); + + Mockito.verify(daoManager).getXXPortalUser(); + Mockito.verify(xxPortalUserDao).getById(Mockito.anyLong()); + Mockito.verify(userManager).checkAccess(xxPUserExp); + Mockito.verify(msRestUtil).validateVUserProfileForUpdate(xxPUserExp, vxPUserExp); + Mockito.verify(userManager).updateUser(vxPUserExp); + Mockito.verify(userManager).mapXXPortalUserVXPortalUser(xxPUserExp); + } + + @Test + public void test9Update() { + VXPortalUser vxPUserExp = new VXPortalUser(); + XXPortalUser xxPUserExp = new XXPortalUser(); + xxPUserExp = null; + XXPortalUserDao xxPortalUserDao = Mockito.mock(XXPortalUserDao.class); + + Mockito.when(daoManager.getXXPortalUser()).thenReturn(xxPortalUserDao); + Mockito.doNothing().when(userManager).checkAccess(xxPUserExp); + Mockito.when(restErrorUtil.createRESTException(Mockito.anyString(), Mockito.any(), Mockito.nullable(Long.class), Mockito.nullable(String.class), Mockito.anyString())).thenReturn(new WebApplicationException()); + + thrown.expect(WebApplicationException.class); + + userREST.update(vxPUserExp, request); + + Mockito.verify(daoManager).getXXPortalUser(); + Mockito.verify(xxPortalUserDao).getById(Mockito.anyLong()); + Mockito.verify(userManager).checkAccess(xxPUserExp); + Mockito.verify(restErrorUtil).createRESTException(Mockito.anyString(), Mockito.any(), Mockito.anyLong(), Mockito.anyString(), Mockito.anyString()); + } + + @Test + public void test10SetUserRoles() { + Long userId = 10L; + VXResponse responseExp = new VXResponse(); + VXStringList roleList = new VXStringList(); + Mockito.doNothing().when(userManager).checkAccess(userId); + Mockito.doNothing().when(userManager).setUserRoles(userId, roleList.getVXStrings()); + + VXResponse responseAct = userREST.setUserRoles(userId, roleList); + + Assert.assertNotNull(responseAct); + Assert.assertEquals(responseExp.getStatusCode(), responseAct.getStatusCode()); + + Mockito.verify(userManager).checkAccess(userId); + Mockito.verify(userManager).setUserRoles(userId, roleList.getVXStrings()); + } + + @Test + public void test11DeactivateUser() { + VXPortalUser vxPUserExp = createVXPortalUser(); + XXPortalUser xxPUserExp = new XXPortalUser(); + xxPUserExp.setLoginId(loginId); + xxPUserExp.setStatus(1); + vxPUserExp.setStatus(5); + + XXPortalUserDao xxPortalUserDao = Mockito.mock(XXPortalUserDao.class); + + Mockito.when(daoManager.getXXPortalUser()).thenReturn(xxPortalUserDao); + Mockito.when(xxPortalUserDao.getById(userId)).thenReturn(xxPUserExp); + Mockito.when(userManager.deactivateUser(xxPUserExp)).thenReturn(vxPUserExp); + + VXPortalUser vxPUserAct = userREST.deactivateUser(userId); + Assert.assertNotNull(vxPUserAct); + Assert.assertEquals(xxPUserExp.getLoginId(), vxPUserAct.getLoginId()); + Assert.assertEquals(vxPUserExp.getStatus(), vxPUserAct.getStatus()); + Assert.assertEquals(vxPUserExp.getId(), vxPUserAct.getId()); + Assert.assertEquals(vxPUserExp.getFirstName(), vxPUserAct.getFirstName()); + + Mockito.verify(daoManager).getXXPortalUser(); + Mockito.verify(xxPortalUserDao).getById(userId); + Mockito.verify(userManager).deactivateUser(xxPUserExp); + } + + @Test + public void test12DeactivateUser() { + XXPortalUser xxPUserExp = new XXPortalUser(); + xxPUserExp = null; + XXPortalUserDao xxPortalUserDao = Mockito.mock(XXPortalUserDao.class); + + Mockito.when(daoManager.getXXPortalUser()).thenReturn(xxPortalUserDao); + Mockito.when(xxPortalUserDao.getById(userId)).thenReturn(xxPUserExp); + Mockito.when(restErrorUtil.createRESTException(Mockito.anyString(), Mockito.any(), Mockito.nullable(Long.class), Mockito.nullable(String.class), Mockito.anyString())).thenReturn(new WebApplicationException()); + thrown.expect(WebApplicationException.class); + + userREST.deactivateUser(userId); + + Mockito.verify(daoManager).getXXPortalUser(); + Mockito.verify(xxPortalUserDao).getById(userId); + Mockito.verify(restErrorUtil).createRESTException(Mockito.anyString(), Mockito.any(), Mockito.anyLong(), Mockito.anyString(), Mockito.anyString()); + } + + @Test + public void test13GetUserProfile() { + HttpSession hs = Mockito.mock(HttpSession.class); + VXPortalUser vxPUserExp = createVXPortalUser(); + Mockito.when(userManager.getUserProfileByLoginId()).thenReturn(vxPUserExp); + Mockito.when(request.getSession()).thenReturn(hs); + Mockito.when(hs.getId()).thenReturn("id"); + + VXPortalUser vxPUserAct = userREST.getUserProfile(request); + + Assert.assertNotNull(vxPUserAct); + Assert.assertEquals(vxPUserExp, vxPUserAct); + Assert.assertEquals(vxPUserExp.getId(), vxPUserAct.getId()); + Assert.assertEquals(vxPUserExp.getFirstName(), vxPUserAct.getFirstName()); + + Mockito.verify(userManager).getUserProfileByLoginId(); + } + + @Test + public void test16ChangePassword() { + XXPortalUser xxPUser = new XXPortalUser(); + VXResponse vxResponseExp = new VXResponse(); + VXPasswordChange vxPasswordChange = createPasswordChange(); + vxResponseExp.setStatusCode(10); + XXPortalUserDao xxPortalUserDao = Mockito.mock(XXPortalUserDao.class); + + Mockito.when(daoManager.getXXPortalUser()).thenReturn(xxPortalUserDao); + Mockito.when(restErrorUtil.createRESTException("serverMsg.userRestUser", MessageEnums.DATA_NOT_FOUND, null, null, vxPasswordChange.getLoginId())).thenThrow(new WebApplicationException()); + thrown.expect(WebApplicationException.class); + VXResponse vxResponseAct = userREST.changePassword(userId, vxPasswordChange); + + Assert.assertNotNull(vxResponseAct); + Assert.assertEquals(vxResponseExp, vxResponseAct); + Assert.assertEquals(vxResponseExp.getStatusCode(), vxResponseAct.getStatusCode()); + + Mockito.verify(daoManager).getXXPortalUser(); + Mockito.verify(xxPortalUserDao).getById(userId); + Mockito.verify(userManager).checkAccess(xxPUser); + Mockito.verify(userManager).changePassword(vxPasswordChange); + } + + @Test + public void test17ChangePassword() { + XXPortalUserDao xxPortalUserDao = Mockito.mock(XXPortalUserDao.class); + Mockito.when(restErrorUtil.createRESTException(Mockito.anyString(), Mockito.any(), Mockito.nullable(Long.class), Mockito.nullable(String.class), Mockito.nullable(String.class))).thenReturn(new WebApplicationException()); + thrown.expect(WebApplicationException.class); + + userREST.changePassword(userId, changePassword); + + Mockito.verify(daoManager).getXXPortalUser(); + Mockito.verify(xxPortalUserDao).getById(userId); + Mockito.verify(restErrorUtil).createRESTException(Mockito.anyString(), Mockito.any(), Mockito.anyLong(), Mockito.anyString(), Mockito.anyString()); + } + + @Test + public void test18ChangeEmailAddress() { + XXPortalUser xxPUser = new XXPortalUser(); + VXPortalUser vxPUserExp = createVXPortalUser(); + VXPasswordChange changeEmail = createPasswordChange(); + + XXPortalUserDao xxPortalUserDao = Mockito.mock(XXPortalUserDao.class); + + Mockito.when(daoManager.getXXPortalUser()).thenReturn(xxPortalUserDao); + Mockito.when(restErrorUtil.createRESTException("serverMsg.userRestUser", MessageEnums.DATA_NOT_FOUND, null, null, changeEmail.getLoginId())).thenThrow(new WebApplicationException()); + thrown.expect(WebApplicationException.class); + VXPortalUser vxPortalUserAct = userREST.changeEmailAddress(userId, changeEmail); + + Assert.assertNotNull(vxPortalUserAct); + Assert.assertEquals(vxPUserExp, vxPortalUserAct); + Assert.assertEquals(vxPUserExp.getId(), vxPortalUserAct.getId()); + Assert.assertEquals(vxPUserExp.getFirstName(), vxPortalUserAct.getFirstName()); + + Mockito.verify(daoManager).getXXPortalUser(); + Mockito.verify(xxPortalUserDao).getById(userId); + Mockito.verify(userManager).checkAccess(xxPUser); + Mockito.verify(userManager).changeEmailAddress(xxPUser, changeEmail); + } + + @Test + public void test19ChangeEmailAddress() { + XXPortalUserDao xxPortalUserDao = Mockito.mock(XXPortalUserDao.class); + Mockito.when(restErrorUtil.createRESTException(Mockito.anyString(), Mockito.any(), Mockito.nullable(Long.class), Mockito.nullable(String.class), Mockito.nullable(String.class))).thenReturn(new WebApplicationException()); + thrown.expect(WebApplicationException.class); + + userREST.changeEmailAddress(userId, changePassword); + + Mockito.verify(daoManager).getXXPortalUser(); + Mockito.verify(xxPortalUserDao).getById(userId); + Mockito.verify(restErrorUtil).createRESTException(Mockito.anyString(), Mockito.any(), Mockito.anyLong(), Mockito.anyString(), Mockito.anyString()); + } + + private VXPortalUser createVXPortalUser() { + VXPortalUser vxPUserExp = new VXPortalUser(); + vxPUserExp.setId(userId); + vxPUserExp.setFirstName(firstName); + vxPUserExp.setLastName(lastName); + vxPUserExp.setEmailAddress(emailId); + vxPUserExp.setLoginId(loginId); + return vxPUserExp; + } + + private VXPasswordChange createPasswordChange() { + VXPasswordChange vxPasswordChange = new VXPasswordChange(); + vxPasswordChange.setId(userId); + vxPasswordChange.setOldPassword(oldPassword); + vxPasswordChange.setUpdPassword(newPassword); + vxPasswordChange.setEmailAddress(emailId); + vxPasswordChange.setLoginId(loginId); + return vxPasswordChange; + } } diff --git a/security-admin/src/test/java/org/apache/ranger/rest/TestXAuditREST.java b/security-admin/src/test/java/org/apache/ranger/rest/TestXAuditREST.java index c0a86ca00f..013970731c 100644 --- a/security-admin/src/test/java/org/apache/ranger/rest/TestXAuditREST.java +++ b/security-admin/src/test/java/org/apache/ranger/rest/TestXAuditREST.java @@ -16,14 +16,9 @@ */ package org.apache.ranger.rest; -import java.util.List; - -import javax.servlet.http.HttpServletRequest; - import org.apache.ranger.biz.XAuditMgr; import org.apache.ranger.common.SearchCriteria; import org.apache.ranger.common.SearchUtil; -import org.apache.ranger.common.SortField; import org.apache.ranger.service.RangerTrxLogV2Service; import org.apache.ranger.service.XAccessAuditService; import org.apache.ranger.view.VXAccessAuditList; @@ -40,181 +35,169 @@ import org.mockito.Mockito; import org.mockito.junit.MockitoJUnitRunner; +import javax.servlet.http.HttpServletRequest; + @RunWith(MockitoJUnitRunner.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class TestXAuditREST { + @InjectMocks + XAuditREST auditREST = new XAuditREST(); + + @Mock + XAuditMgr xAuditMgr; + + @Mock + SearchUtil searchUtil; + + @Mock + XAccessAuditService xAccessAuditSrv; + + @Mock + VXTrxLogList vxExpList; + + @Mock + RangerTrxLogV2Service xTrxLogService; + + @Mock + HttpServletRequest request; + + @Mock + SearchCriteria searchCriteria; + + Long id = 5L; + String name = "test"; + + @Test + public void test1getXTrxLog() { + VXTrxLog vxExp = new VXTrxLog(); + vxExp.setId(id); + vxExp.setObjectName(name); + Mockito.when(xAuditMgr.getXTrxLog(id)).thenReturn(vxExp); + VXTrxLog vxAct = auditREST.getXTrxLog(id); + Assert.assertNotNull(vxAct); + Assert.assertEquals(vxExp, vxAct); + Assert.assertEquals(vxExp.getId(), vxAct.getId()); + Assert.assertEquals(vxExp.getObjectName(), vxAct.getObjectName()); + Mockito.verify(xAuditMgr).getXTrxLog(id); + } + + @Test + public void test2createXTrxLog() { + VXTrxLog vxExp = new VXTrxLog(); + vxExp.setId(id); + vxExp.setObjectName(name); + Mockito.when(xAuditMgr.createXTrxLog(vxExp)).thenReturn(vxExp); + VXTrxLog vxAct = auditREST.createXTrxLog(vxExp); + Assert.assertNotNull(vxAct); + Assert.assertEquals(vxExp, vxAct); + Assert.assertEquals(vxExp.getId(), vxAct.getId()); + Assert.assertEquals(vxExp.getObjectName(), vxAct.getObjectName()); + Mockito.verify(xAuditMgr).createXTrxLog(vxExp); + } + + @Test + public void test3updateXTrxLog() { + VXTrxLog vxPrev = new VXTrxLog(); + vxPrev.setId(id); + vxPrev.setObjectName(name); + VXTrxLog vxExp = new VXTrxLog(); + vxExp.setId(id); + vxExp.setObjectName("test1"); + + Mockito.when(xAuditMgr.updateXTrxLog(vxPrev)).thenReturn(vxExp); + + VXTrxLog vxAct = auditREST.updateXTrxLog(vxPrev); + + Assert.assertNotNull(vxAct); + Assert.assertEquals(vxExp, vxAct); + Assert.assertEquals(vxExp.getObjectName(), vxAct.getObjectName()); + + Mockito.verify(xAuditMgr).updateXTrxLog(vxPrev); + } + + @Test + public void test4deleteXTrxLog() { + Mockito.doNothing().when(xAuditMgr).deleteXTrxLog(id, false); + + auditREST.deleteXTrxLog(id, request); + + Mockito.verify(xAuditMgr).deleteXTrxLog(id, false); + } + + @Test + public void test5searchXTrxLog() { + VXTrxLogList vxExpList = new VXTrxLogList(); + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + searchCriteria.addParam("name", name); + + Mockito.when(searchUtil.extractCommonCriterias(Mockito.any(), Mockito.any())).thenReturn(searchCriteria); + Mockito.when(xAuditMgr.searchXTrxLogs(searchCriteria)).thenReturn(vxExpList); + + VXTrxLogList vxActList = auditREST.searchXTrxLogs(request); + + Assert.assertNotNull(vxActList); + Assert.assertEquals(vxExpList, vxActList); + + Mockito.verify(searchUtil).extractCommonCriterias(Mockito.any(), Mockito.any()); + Mockito.verify(xAuditMgr).searchXTrxLogs(searchCriteria); + } - @InjectMocks - XAuditREST auditREST = new XAuditREST(); - - @Mock - XAuditMgr xAuditMgr; - - @Mock - SearchUtil searchUtil; - - @Mock - XAccessAuditService xAccessAuditSrv; - - @Mock - VXTrxLogList vxExpList; - - @Mock - RangerTrxLogV2Service xTrxLogService; - - @Mock - HttpServletRequest request; - - @Mock - SearchCriteria searchCriteria; - - Long id = 5L; - String name = "test"; - - @Test - public void Test1getXTrxLog() { - VXTrxLog vxExp = new VXTrxLog(); - vxExp.setId(id); - vxExp.setObjectName(name); - Mockito.when(xAuditMgr.getXTrxLog(id)).thenReturn(vxExp); - VXTrxLog vxAct = auditREST.getXTrxLog(id); - Assert.assertNotNull(vxAct); - Assert.assertEquals(vxExp, vxAct); - Assert.assertEquals(vxExp.getId(), vxAct.getId()); - Assert.assertEquals(vxExp.getObjectName(), vxAct.getObjectName()); - Mockito.verify(xAuditMgr).getXTrxLog(id); - } - - @Test - public void Test2createXTrxLog() { - VXTrxLog vxExp = new VXTrxLog(); - vxExp.setId(id); - vxExp.setObjectName(name); - Mockito.when(xAuditMgr.createXTrxLog(vxExp)).thenReturn(vxExp); - VXTrxLog vxAct = auditREST.createXTrxLog(vxExp); - Assert.assertNotNull(vxAct); - Assert.assertEquals(vxExp, vxAct); - Assert.assertEquals(vxExp.getId(), vxAct.getId()); - Assert.assertEquals(vxExp.getObjectName(), vxAct.getObjectName()); - Mockito.verify(xAuditMgr).createXTrxLog(vxExp); - } - - @Test - public void Test3updateXTrxLog() { - VXTrxLog vxPrev = new VXTrxLog(); - vxPrev.setId(id); - vxPrev.setObjectName(name); - VXTrxLog vxExp = new VXTrxLog(); - vxExp.setId(id); - vxExp.setObjectName("test1"); - - Mockito.when(xAuditMgr.updateXTrxLog(vxPrev)).thenReturn(vxExp); - - VXTrxLog vxAct = auditREST.updateXTrxLog(vxPrev); - - Assert.assertNotNull(vxAct); - Assert.assertEquals(vxExp, vxAct); - Assert.assertEquals(vxExp.getObjectName(), vxAct.getObjectName()); - - Mockito.verify(xAuditMgr).updateXTrxLog(vxPrev); - } - - @Test - public void Test4deleteXTrxLog() { - Mockito.doNothing().when(xAuditMgr).deleteXTrxLog(id, false); - - auditREST.deleteXTrxLog(id, request); - - Mockito.verify(xAuditMgr).deleteXTrxLog(id, false); - } - - @SuppressWarnings("unchecked") - @Test - public void Test5searchXTrxLog() { - VXTrxLogList vxExpList = new VXTrxLogList(); - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - searchCriteria.addParam("name", name); - - Mockito.when(searchUtil.extractCommonCriterias((HttpServletRequest) Mockito.any(), - (List) Mockito.any())).thenReturn(searchCriteria); - Mockito.when(xAuditMgr.searchXTrxLogs(searchCriteria)).thenReturn(vxExpList); - - VXTrxLogList vxActList = auditREST.searchXTrxLogs(request); - - Assert.assertNotNull(vxActList); - Assert.assertEquals(vxExpList, vxActList); - - Mockito.verify(searchUtil).extractCommonCriterias((HttpServletRequest) Mockito.any(), - (List) Mockito.any()); - Mockito.verify(xAuditMgr).searchXTrxLogs(searchCriteria); - } - - @SuppressWarnings("unchecked") - @Test - public void Test6countXTrxLogs() { - VXLong vxLongExp = new VXLong(); - vxLongExp.setValue(id); - - Mockito.when(searchUtil.extractCommonCriterias((HttpServletRequest) Mockito.any(), - (List) Mockito.any())).thenReturn(searchCriteria); - Mockito.when(xAuditMgr.getXTrxLogSearchCount(searchCriteria)).thenReturn(vxLongExp); - - VXLong vxLongAct = auditREST.countXTrxLogs(request); - - Assert.assertNotNull(vxLongAct); - Assert.assertEquals(vxLongExp, vxLongAct); - Assert.assertEquals(vxLongExp.getValue(), vxLongAct.getValue()); - - Mockito.verify(searchUtil).extractCommonCriterias((HttpServletRequest) Mockito.any(), - (List) Mockito.any()); - Mockito.verify(xAuditMgr).getXTrxLogSearchCount(searchCriteria); - } - - @SuppressWarnings("unchecked") - @Test - public void Test7searchXAccessAudits() { - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - searchCriteria.addParam("name", name); - VXAccessAuditList vxAAListExp = new VXAccessAuditList(); - vxAAListExp.setTotalCount(6L); - - Mockito.when(searchUtil.extractCommonCriterias((HttpServletRequest) Mockito.any(), - (List) Mockito.any())).thenReturn(searchCriteria); - Mockito.when(xAuditMgr.searchXAccessAudits(searchCriteria)).thenReturn(vxAAListExp); - - VXAccessAuditList vxAAListAct = auditREST.searchXAccessAudits(request); - - Assert.assertNotNull(vxAAListAct); - Assert.assertEquals(vxAAListExp, vxAAListAct); - Assert.assertEquals(vxAAListExp.getTotalCount(), vxAAListAct.getTotalCount()); - - Mockito.verify(searchUtil).extractCommonCriterias((HttpServletRequest) Mockito.any(), - (List) Mockito.any()); - Mockito.verify(xAuditMgr).searchXAccessAudits(searchCriteria); - } - - @SuppressWarnings("unchecked") - @Test - public void Test8countXAccessAudits() { - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - searchCriteria.addParam("name", name); - VXAccessAuditList vxAuditList = new VXAccessAuditList(); - vxAuditList.setTotalCount(id); + @Test + public void test6countXTrxLogs() { + VXLong vxLongExp = new VXLong(); + vxLongExp.setValue(id); + + Mockito.when(searchUtil.extractCommonCriterias(Mockito.any(), Mockito.any())).thenReturn(searchCriteria); + Mockito.when(xAuditMgr.getXTrxLogSearchCount(searchCriteria)).thenReturn(vxLongExp); + + VXLong vxLongAct = auditREST.countXTrxLogs(request); + + Assert.assertNotNull(vxLongAct); + Assert.assertEquals(vxLongExp, vxLongAct); + Assert.assertEquals(vxLongExp.getValue(), vxLongAct.getValue()); + + Mockito.verify(searchUtil).extractCommonCriterias(Mockito.any(), Mockito.any()); + Mockito.verify(xAuditMgr).getXTrxLogSearchCount(searchCriteria); + } + + @Test + public void test7searchXAccessAudits() { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + searchCriteria.addParam("name", name); + VXAccessAuditList vxAAListExp = new VXAccessAuditList(); + vxAAListExp.setTotalCount(6L); + + Mockito.when(searchUtil.extractCommonCriterias(Mockito.any(), Mockito.any())).thenReturn(searchCriteria); + Mockito.when(xAuditMgr.searchXAccessAudits(searchCriteria)).thenReturn(vxAAListExp); + + VXAccessAuditList vxAAListAct = auditREST.searchXAccessAudits(request); + + Assert.assertNotNull(vxAAListAct); + Assert.assertEquals(vxAAListExp, vxAAListAct); + Assert.assertEquals(vxAAListExp.getTotalCount(), vxAAListAct.getTotalCount()); + + Mockito.verify(searchUtil).extractCommonCriterias(Mockito.any(), Mockito.any()); + Mockito.verify(xAuditMgr).searchXAccessAudits(searchCriteria); + } - Mockito.when(searchUtil.extractCommonCriterias((HttpServletRequest) Mockito.any(), - (List) Mockito.any())).thenReturn(searchCriteria); - Mockito.when(auditREST.searchXAccessAudits(request)).thenReturn(vxAuditList); + @Test + public void test8countXAccessAudits() { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + searchCriteria.addParam("name", name); + VXAccessAuditList vxAuditList = new VXAccessAuditList(); + vxAuditList.setTotalCount(id); - VXLong vXLongExpect = new VXLong(); - vXLongExpect.setValue(vxAuditList.getTotalCount()); + Mockito.when(searchUtil.extractCommonCriterias(Mockito.any(), Mockito.any())).thenReturn(searchCriteria); + Mockito.when(auditREST.searchXAccessAudits(request)).thenReturn(vxAuditList); - VXLong vxLongAct = auditREST.countXAccessAudits(request); + VXLong vXLongExpect = new VXLong(); + vXLongExpect.setValue(vxAuditList.getTotalCount()); - Assert.assertNotNull(vxLongAct); - Assert.assertEquals(vXLongExpect.getValue(), vxLongAct.getValue()); + VXLong vxLongAct = auditREST.countXAccessAudits(request); - Mockito.verify(searchUtil, Mockito.times(2)).extractCommonCriterias((HttpServletRequest) Mockito.any(), - (List) Mockito.any()); - } + Assert.assertNotNull(vxLongAct); + Assert.assertEquals(vXLongExpect.getValue(), vxLongAct.getValue()); + Mockito.verify(searchUtil, Mockito.times(2)).extractCommonCriterias(Mockito.any(), Mockito.any()); + } } diff --git a/security-admin/src/test/java/org/apache/ranger/rest/TestXKeyREST.java b/security-admin/src/test/java/org/apache/ranger/rest/TestXKeyREST.java index 3fa40f4617..28fbd34aac 100644 --- a/security-admin/src/test/java/org/apache/ranger/rest/TestXKeyREST.java +++ b/security-admin/src/test/java/org/apache/ranger/rest/TestXKeyREST.java @@ -16,11 +16,8 @@ */ package org.apache.ranger.rest; -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.WebApplicationException; import org.apache.ranger.biz.KmsKeyMgr; import org.apache.ranger.biz.XAuditMgr; -import org.apache.ranger.common.MessageEnums; import org.apache.ranger.common.RESTErrorUtil; import org.apache.ranger.common.SearchUtil; import org.apache.ranger.service.XAccessAuditService; @@ -38,195 +35,186 @@ import org.mockito.Mockito; import org.mockito.junit.MockitoJUnitRunner; +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.WebApplicationException; + @RunWith(MockitoJUnitRunner.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class TestXKeyREST { - @InjectMocks - XKeyREST keyREST = new XKeyREST(); - - @Mock - XAuditMgr xAuditMgr; - - @Mock - SearchUtil searchUtil; - - @Mock - XAccessAuditService xAccessAuditSrv; - - @Mock - KmsKeyMgr keyMgr; - - @Mock - VXKmsKey vxKmsKey; - - @Mock - RESTErrorUtil restErrorUtil; - - @Mock - HttpServletRequest request; - - @Rule - public ExpectedException thrown = ExpectedException.none(); - - String provider = "providerX"; - String name = "xyz"; - String nameNl = ""; + @Rule + public ExpectedException thrown = ExpectedException.none(); + @InjectMocks + XKeyREST keyREST = new XKeyREST(); + @Mock + XAuditMgr xAuditMgr; + @Mock + SearchUtil searchUtil; + @Mock + XAccessAuditService xAccessAuditSrv; + @Mock + KmsKeyMgr keyMgr; + @Mock + VXKmsKey vxKmsKey; + @Mock + RESTErrorUtil restErrorUtil; + @Mock + HttpServletRequest request; + String provider = "providerX"; + String name = "xyz"; + String nameNl = ""; - @Test - public void Test1Searchkeys() throws Exception { - VXKmsKeyList vxKeyListExp = new VXKmsKeyList(); + @Test + public void test1Searchkeys() throws Exception { + VXKmsKeyList vxKeyListExp = new VXKmsKeyList(); - Mockito.when(keyMgr.searchKeys(request, provider)).thenReturn(vxKeyListExp); + Mockito.when(keyMgr.searchKeys(request, provider)).thenReturn(vxKeyListExp); - VXKmsKeyList vxKeyListAct = keyREST.searchKeys(request, provider); + VXKmsKeyList vxKeyListAct = keyREST.searchKeys(request, provider); - Assert.assertNotNull(vxKeyListAct); - Assert.assertEquals(vxKeyListExp, vxKeyListAct); + Assert.assertNotNull(vxKeyListAct); + Assert.assertEquals(vxKeyListExp, vxKeyListAct); - Mockito.verify(keyMgr).searchKeys(request, provider); - } + Mockito.verify(keyMgr).searchKeys(request, provider); + } - @Test - public void Test2RolloverKey() throws Exception { - VXKmsKey vxKeyExp = new VXKmsKey(); - vxKeyExp.setName(name); - vxKeyExp.setCipher("CipherX"); + @Test + public void test2RolloverKey() throws Exception { + VXKmsKey vxKeyExp = new VXKmsKey(); + vxKeyExp.setName(name); + vxKeyExp.setCipher("CipherX"); - Mockito.when(keyMgr.rolloverKey(provider, vxKeyExp)).thenReturn(vxKeyExp); + Mockito.when(keyMgr.rolloverKey(provider, vxKeyExp)).thenReturn(vxKeyExp); - VXKmsKey vxKeyAct = keyREST.rolloverKey(provider, vxKeyExp); + VXKmsKey vxKeyAct = keyREST.rolloverKey(provider, vxKeyExp); - Assert.assertNotNull(vxKeyAct); - Assert.assertEquals(vxKeyExp, vxKeyAct); - Assert.assertEquals(vxKeyExp.getName(), vxKeyAct.getName()); - Mockito.verify(keyMgr).rolloverKey(provider, vxKeyExp); - } + Assert.assertNotNull(vxKeyAct); + Assert.assertEquals(vxKeyExp, vxKeyAct); + Assert.assertEquals(vxKeyExp.getName(), vxKeyAct.getName()); + Mockito.verify(keyMgr).rolloverKey(provider, vxKeyExp); + } - @Test - public void Test3RolloverKey() throws Exception { - VXKmsKey vxKeyExp = new VXKmsKey(); - vxKeyExp.setName(name); + @Test + public void test3RolloverKey() throws Exception { + VXKmsKey vxKeyExp = new VXKmsKey(); + vxKeyExp.setName(name); - Mockito.when(keyMgr.rolloverKey(provider, vxKeyExp)).thenReturn(vxKeyExp); + Mockito.when(keyMgr.rolloverKey(provider, vxKeyExp)).thenReturn(vxKeyExp); - VXKmsKey vxKeyAct = keyREST.rolloverKey(provider, vxKeyExp); + VXKmsKey vxKeyAct = keyREST.rolloverKey(provider, vxKeyExp); - Assert.assertNotNull(vxKeyAct); - Assert.assertEquals(vxKeyExp, vxKeyAct); - Assert.assertEquals(vxKeyExp.getName(), vxKeyAct.getName()); - Assert.assertNull(vxKeyAct.getCipher()); + Assert.assertNotNull(vxKeyAct); + Assert.assertEquals(vxKeyExp, vxKeyAct); + Assert.assertEquals(vxKeyExp.getName(), vxKeyAct.getName()); + Assert.assertNull(vxKeyAct.getCipher()); - Mockito.verify(keyMgr).rolloverKey(provider, vxKeyExp); - } + Mockito.verify(keyMgr).rolloverKey(provider, vxKeyExp); + } - @Test - public void Test4RolloverKey() throws Exception { - VXKmsKey vxKeyExp = new VXKmsKey(); + @Test + public void test4RolloverKey() { + VXKmsKey vxKeyExp = new VXKmsKey(); - Mockito.when(restErrorUtil.createRESTException(Mockito.nullable(String.class), (MessageEnums) Mockito.any())) - .thenReturn(new WebApplicationException()); - thrown.expect(WebApplicationException.class); + Mockito.when(restErrorUtil.createRESTException(Mockito.nullable(String.class), Mockito.any())) + .thenReturn(new WebApplicationException()); + thrown.expect(WebApplicationException.class); - keyREST.rolloverKey(provider, vxKeyExp); + keyREST.rolloverKey(provider, vxKeyExp); - Mockito.verify(restErrorUtil).createRESTException(Mockito.anyString(), (MessageEnums) Mockito.any()); - } + Mockito.verify(restErrorUtil).createRESTException(Mockito.anyString(), Mockito.any()); + } - @Test - public void Test5DeleteKey() throws Exception { - Mockito.doNothing().when(keyMgr).deleteKey(provider, name); + @Test + public void test5DeleteKey() throws Exception { + Mockito.doNothing().when(keyMgr).deleteKey(provider, name); - keyREST.deleteKey(name, provider, request); + keyREST.deleteKey(name, provider, request); - Mockito.verify(keyMgr).deleteKey(provider, name); - } + Mockito.verify(keyMgr).deleteKey(provider, name); + } - @Test - public void Test6DeleteKey() throws Exception { - Mockito.when(restErrorUtil.createRESTException(Mockito.nullable(String.class), (MessageEnums) Mockito.any())) - .thenReturn(new WebApplicationException()); + @Test + public void test6DeleteKey() { + Mockito.when(restErrorUtil.createRESTException(Mockito.nullable(String.class), Mockito.any())).thenReturn(new WebApplicationException()); - thrown.expect(WebApplicationException.class); + thrown.expect(WebApplicationException.class); - keyREST.deleteKey(nameNl, provider, request); + keyREST.deleteKey(nameNl, provider, request); - Mockito.verify(restErrorUtil).createRESTException(Mockito.anyString(), (MessageEnums) Mockito.any()); - } + Mockito.verify(restErrorUtil).createRESTException(Mockito.anyString(), Mockito.any()); + } - @Test - public void Test6CreateKey() throws Exception { - VXKmsKey vxKeyExp = new VXKmsKey(); - vxKeyExp.setName(name); - vxKeyExp.setCipher("CipherX"); + @Test + public void test6CreateKey() throws Exception { + VXKmsKey vxKeyExp = new VXKmsKey(); + vxKeyExp.setName(name); + vxKeyExp.setCipher("CipherX"); - Mockito.when(keyMgr.createKey(provider, vxKeyExp)).thenReturn(vxKeyExp); - VXKmsKey vxKeyAct = keyREST.createKey(provider, vxKeyExp); + Mockito.when(keyMgr.createKey(provider, vxKeyExp)).thenReturn(vxKeyExp); + VXKmsKey vxKeyAct = keyREST.createKey(provider, vxKeyExp); - Assert.assertNotNull(vxKeyAct); - Assert.assertEquals(vxKeyAct, vxKeyExp); - Assert.assertEquals(vxKeyExp.getName(), vxKeyAct.getName()); - Assert.assertEquals(vxKeyExp.getCipher(), vxKeyAct.getCipher()); + Assert.assertNotNull(vxKeyAct); + Assert.assertEquals(vxKeyAct, vxKeyExp); + Assert.assertEquals(vxKeyExp.getName(), vxKeyAct.getName()); + Assert.assertEquals(vxKeyExp.getCipher(), vxKeyAct.getCipher()); - Mockito.verify(keyMgr).createKey(provider, vxKeyExp); - } + Mockito.verify(keyMgr).createKey(provider, vxKeyExp); + } - @Test - public void Test7CreateKey() throws Exception { - VXKmsKey vxKeyExp = new VXKmsKey(); - vxKeyExp.setName(name); + @Test + public void test7CreateKey() throws Exception { + VXKmsKey vxKeyExp = new VXKmsKey(); + vxKeyExp.setName(name); - Mockito.when(keyMgr.createKey(provider, vxKeyExp)).thenReturn(vxKeyExp); + Mockito.when(keyMgr.createKey(provider, vxKeyExp)).thenReturn(vxKeyExp); - VXKmsKey vxKeyAct = keyREST.createKey(provider, vxKeyExp); + VXKmsKey vxKeyAct = keyREST.createKey(provider, vxKeyExp); - Assert.assertNotNull(vxKeyAct); - Assert.assertEquals(vxKeyAct, vxKeyExp); - Assert.assertEquals(vxKeyExp.getName(), vxKeyAct.getName()); - Assert.assertNull(vxKeyAct.getCipher()); + Assert.assertNotNull(vxKeyAct); + Assert.assertEquals(vxKeyAct, vxKeyExp); + Assert.assertEquals(vxKeyExp.getName(), vxKeyAct.getName()); + Assert.assertNull(vxKeyAct.getCipher()); - Mockito.verify(keyMgr).createKey(provider, vxKeyExp); - } + Mockito.verify(keyMgr).createKey(provider, vxKeyExp); + } - @Test - public void Test8CreateKey() throws Exception { - VXKmsKey vxKeyExp = new VXKmsKey(); + @Test + public void test8CreateKey() { + VXKmsKey vxKeyExp = new VXKmsKey(); - Mockito.when(restErrorUtil.createRESTException(Mockito.nullable(String.class), (MessageEnums) Mockito.any())) - .thenReturn(new WebApplicationException()); - thrown.expect(WebApplicationException.class); + Mockito.when(restErrorUtil.createRESTException(Mockito.nullable(String.class), Mockito.any())).thenReturn(new WebApplicationException()); + thrown.expect(WebApplicationException.class); - VXKmsKey vxKeyAct = keyREST.createKey(provider, vxKeyExp); + VXKmsKey vxKeyAct = keyREST.createKey(provider, vxKeyExp); - Mockito.verify(restErrorUtil).createRESTException(Mockito.anyString(), (MessageEnums) Mockito.any()); + Mockito.verify(restErrorUtil).createRESTException(Mockito.anyString(), Mockito.any()); - Assert.assertNull(vxKeyAct); - } + Assert.assertNull(vxKeyAct); + } - @Test - public void Test9GetKey() throws Exception { - VXKmsKey vxKeyExp = new VXKmsKey(); + @Test + public void test9GetKey() throws Exception { + VXKmsKey vxKeyExp = new VXKmsKey(); - Mockito.when(keyMgr.getKey(provider, name)).thenReturn(vxKeyExp); + Mockito.when(keyMgr.getKey(provider, name)).thenReturn(vxKeyExp); - VXKmsKey vxKeyAct = keyREST.getKey(name, provider); + VXKmsKey vxKeyAct = keyREST.getKey(name, provider); - Assert.assertNotNull(vxKeyAct); - Assert.assertEquals(vxKeyAct, vxKeyExp); - Assert.assertEquals(vxKeyExp.getName(), vxKeyAct.getName()); + Assert.assertNotNull(vxKeyAct); + Assert.assertEquals(vxKeyAct, vxKeyExp); + Assert.assertEquals(vxKeyExp.getName(), vxKeyAct.getName()); - Mockito.verify(keyMgr).getKey(provider, name); - } + Mockito.verify(keyMgr).getKey(provider, name); + } - @Test - public void Test10GetKey() throws Exception { - Mockito.when(restErrorUtil.createRESTException(Mockito.nullable(String.class), (MessageEnums) Mockito.any())) - .thenReturn(new WebApplicationException()); - thrown.expect(WebApplicationException.class); + @Test + public void test10GetKey() { + Mockito.when(restErrorUtil.createRESTException(Mockito.nullable(String.class), Mockito.any())).thenReturn(new WebApplicationException()); + thrown.expect(WebApplicationException.class); - VXKmsKey vxKeyAct = keyREST.getKey(nameNl, provider); + VXKmsKey vxKeyAct = keyREST.getKey(nameNl, provider); - Assert.assertNull(vxKeyAct); + Assert.assertNull(vxKeyAct); - Mockito.verify(restErrorUtil).createRESTException(Mockito.anyString(), (MessageEnums) Mockito.any()); - } + Mockito.verify(restErrorUtil).createRESTException(Mockito.anyString(), Mockito.any()); + } } diff --git a/security-admin/src/test/java/org/apache/ranger/rest/TestXUserREST.java b/security-admin/src/test/java/org/apache/ranger/rest/TestXUserREST.java index 4727d0990d..4d86c56097 100644 --- a/security-admin/src/test/java/org/apache/ranger/rest/TestXUserREST.java +++ b/security-admin/src/test/java/org/apache/ranger/rest/TestXUserREST.java @@ -16,41 +16,50 @@ */ package org.apache.ranger.rest; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertEquals; - -import javax.ws.rs.WebApplicationException; -import javax.ws.rs.core.Response; - import org.apache.ranger.biz.RangerBizUtil; import org.apache.ranger.biz.SessionMgr; import org.apache.ranger.biz.XUserMgr; +import org.apache.ranger.common.AppConstants; import org.apache.ranger.common.ContextUtil; -import org.apache.ranger.common.MessageEnums; import org.apache.ranger.common.RESTErrorUtil; +import org.apache.ranger.common.RangerConstants; import org.apache.ranger.common.SearchCriteria; import org.apache.ranger.common.SearchUtil; -import org.apache.ranger.common.SortField; -import org.apache.ranger.common.AppConstants; -import org.apache.ranger.common.RangerConstants; import org.apache.ranger.common.StringUtil; import org.apache.ranger.common.UserSessionBase; import org.apache.ranger.db.RangerDaoManager; +import org.apache.ranger.db.XXAuditMapDao; import org.apache.ranger.db.XXGroupDao; +import org.apache.ranger.db.XXGroupPermissionDao; +import org.apache.ranger.db.XXGroupUserDao; +import org.apache.ranger.db.XXPermMapDao; +import org.apache.ranger.db.XXPolicyDao; +import org.apache.ranger.db.XXResourceDao; +import org.apache.ranger.db.XXUserDao; +import org.apache.ranger.entity.XXAsset; +import org.apache.ranger.entity.XXAuditMap; +import org.apache.ranger.entity.XXGroup; +import org.apache.ranger.entity.XXGroupGroup; +import org.apache.ranger.entity.XXGroupPermission; +import org.apache.ranger.entity.XXPermMap; +import org.apache.ranger.entity.XXPolicy; +import org.apache.ranger.entity.XXPortalUser; import org.apache.ranger.entity.XXResource; +import org.apache.ranger.entity.XXUser; import org.apache.ranger.plugin.model.RangerPolicy; -import org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyItem; import org.apache.ranger.plugin.model.RangerPolicy.RangerDataMaskPolicyItem; +import org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyItem; import org.apache.ranger.plugin.model.RangerPolicy.RangerRowFilterPolicyItem; import org.apache.ranger.security.context.RangerContextHolder; import org.apache.ranger.security.context.RangerSecurityContext; import org.apache.ranger.service.AuthSessionService; +import org.apache.ranger.service.XAuditMapService; import org.apache.ranger.service.XGroupGroupService; import org.apache.ranger.service.XGroupPermissionService; import org.apache.ranger.service.XGroupService; import org.apache.ranger.service.XGroupUserService; import org.apache.ranger.service.XModuleDefService; +import org.apache.ranger.service.XPermMapService; import org.apache.ranger.service.XResourceService; import org.apache.ranger.service.XUserPermissionService; import org.apache.ranger.service.XUserService; @@ -58,6 +67,7 @@ import org.apache.ranger.view.VXAuditMapList; import org.apache.ranger.view.VXAuthSession; import org.apache.ranger.view.VXAuthSessionList; +import org.apache.ranger.view.VXDataObject; import org.apache.ranger.view.VXGroup; import org.apache.ranger.view.VXGroupList; import org.apache.ranger.view.VXGroupPermission; @@ -69,24 +79,15 @@ import org.apache.ranger.view.VXModuleDefList; import org.apache.ranger.view.VXPermMap; import org.apache.ranger.view.VXPermMapList; +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.apache.ranger.view.VXUser; import org.apache.ranger.view.VXUserGroupInfo; import org.apache.ranger.view.VXUserList; -import org.apache.ranger.view.VXDataObject; -import org.apache.ranger.view.VXResource; import org.apache.ranger.view.VXUserPermission; import org.apache.ranger.view.VXUserPermissionList; -import org.apache.ranger.entity.XXAuditMap; -import org.apache.ranger.service.XAuditMapService; -import org.apache.ranger.entity.XXAsset; -import org.apache.ranger.entity.XXGroupGroup; -import org.apache.ranger.entity.XXGroupPermission; -import org.apache.ranger.entity.XXPermMap; -import org.apache.ranger.entity.XXPortalUser; -import org.apache.ranger.service.XPermMapService; import org.junit.After; import org.junit.FixMethodOrder; import org.junit.Rule; @@ -98,16 +99,10 @@ import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.junit.MockitoJUnitRunner; -import org.apache.ranger.entity.XXGroup; -import org.apache.ranger.db.XXGroupPermissionDao; -import org.apache.ranger.db.XXResourceDao; -import org.apache.ranger.db.XXPermMapDao; -import org.apache.ranger.db.XXPolicyDao; -import org.apache.ranger.db.XXGroupUserDao; -import org.apache.ranger.db.XXUserDao; -import org.apache.ranger.entity.XXPolicy; -import org.apache.ranger.entity.XXUser; -import org.apache.ranger.db.XXAuditMapDao; + +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.WebApplicationException; +import javax.ws.rs.core.Response; import java.util.ArrayList; import java.util.Collection; @@ -115,2156 +110,2093 @@ import java.util.HashMap; import java.util.List; -import javax.servlet.http.HttpServletRequest; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; @RunWith(MockitoJUnitRunner.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class TestXUserREST { - @Rule - public ExpectedException thrown = ExpectedException.none(); - - @InjectMocks - XUserREST xUserRest = new XUserREST(); - - VXUser vxUser=createVXUser(); - Long id=1L; - - @Mock XUserMgr xUserMgr; - @Mock VXGroup vxGroup; - @Mock SearchCriteria searchCriteria; - @Mock XGroupService xGroupService; - @Mock SearchUtil searchUtil; - @Mock StringUtil stringUtil; - @Mock VXLong vXLong; - @Mock HttpServletRequest request; - @Mock VXUser vXUser1; - @Mock VXUserGroupInfo vXUserGroupInfo; - @Mock RangerBizUtil bizUtil; - @Mock XUserService xUserService; - @Mock VXUserList vXUserList; - @Mock VXGroupUser vXGroupUser; - @Mock XGroupUserService xGroupUserService; - @Mock VXGroupUserList vXGroupUserList; - @Mock XGroupGroupService xGroupGroupService; - @Mock VXPermMap vXPermMap; - @Mock RESTErrorUtil restErrorUtil; - @Mock WebApplicationException webApplicationException; - @Mock XResourceService xResourceService; - @Mock VXDataObject VXDataObject; - @Mock AppConstants AppConstants; - @Mock RangerConstants RangerConstants; - @Mock VXResource vXResource; - @Mock VXResponse vXResponse; - @Mock XXResource xXResource; - @Mock XXAuditMap XXAuditMap; - @Mock XAuditMapService xAuditMapService; - @Mock XPermMapService xPermMapService; - @Mock XXAsset XXAsset; - @Mock RangerDaoManager rangerDaoManager; - @Mock XXPermMap XXPermMap; - @Mock Response response; - @Mock VXPermMapList vXPermMapList; - @Mock VXAuditMap vXAuditMap; - @Mock VXAuditMapList vXAuditMapList; - @Mock AuthSessionService authSessionService; - @Mock SessionMgr sessionMgr; - @Mock VXAuthSessionList vXAuthSessionList; - @Mock VXModuleDef vXModuleDef; - @Mock VXUserPermission vXUserPermission; - @Mock VXUserPermissionList vXUserPermissionList; - @Mock VXGroupPermission vXGroupPermission; - @Mock XModuleDefService xModuleDefService; - @Mock VXModuleDefList VXModuleDefList; - @Mock XUserPermissionService xUserPermissionService; - @Mock VXGroupPermissionList vXGroupPermissionList; - @Mock XGroupPermissionService xGroupPermissionService; - @Mock VXStringList vXStringList; - @Mock VXString vXString; - @Mock XXGroupDao xXGroupDao; - @Mock XXGroup xXGroup; - @Mock XXGroupGroup xXGroupGroup; - @Mock XXGroupPermission xXGroupPermission; - @Mock XXGroupPermissionDao xXGroupPermissionDao; - @Mock XXPolicyDao xXPolicyDao; - @Mock XXPolicy xXPolicy; - @Mock XXGroupUserDao xXGroupUserDao; - @Mock XXUserDao xXUserDao; - @Mock XXUser xXUser; - @Mock XXPermMapDao xXPermMapDao; - @Mock XXResourceDao xXResourceDao; - @Mock XXAuditMapDao xXAuditMapDao; - @Mock RangerPolicy rangerPolicy; - @Mock RangerPolicyItem rangerPolicyItem; - @Mock RangerDataMaskPolicyItem rangerDataMaskPolicyItem; - @Mock RangerRowFilterPolicyItem rangerRowFilterPolicyItem; - - @Test - public void test1getXGroup() { - VXGroup compareTestVXGroup=createVXGroup(); - - Mockito.when(xUserMgr.getXGroup(id)).thenReturn(compareTestVXGroup); - VXGroup retVxGroup= xUserRest.getXGroup(id); - - assertNotNull(retVxGroup); - assertEquals(compareTestVXGroup.getId(),retVxGroup.getId()); - assertEquals(compareTestVXGroup.getName(),retVxGroup.getName()); - Mockito.verify(xUserMgr).getXGroup(id); - } - - @Test - public void test2secureGetXGroup() { - VXGroup compareTestVXGroup=createVXGroup(); - - Mockito.when(xUserMgr.getXGroup(id)).thenReturn(compareTestVXGroup); - VXGroup retVxGroup=xUserRest.secureGetXGroup(id); - - assertNotNull(retVxGroup); - assertEquals(compareTestVXGroup.getId(),retVxGroup.getId()); - assertEquals(compareTestVXGroup.getName(),retVxGroup.getName()); - Mockito.verify(xUserMgr).getXGroup(id); - } - - @Test - public void test3createXGroup() { - VXGroup compareTestVXGroup=createVXGroup(); - - Mockito.when(xUserMgr.createXGroupWithoutLogin(compareTestVXGroup)).thenReturn(compareTestVXGroup); - VXGroup retVxGroup=xUserRest.createXGroup(compareTestVXGroup); - - assertNotNull(retVxGroup); - assertEquals(compareTestVXGroup.getId(),retVxGroup.getId()); - assertEquals(compareTestVXGroup.getName(),retVxGroup.getName()); - Mockito.verify(xUserMgr).createXGroupWithoutLogin(compareTestVXGroup); - } - @Test - public void test4secureCreateXGroup() { - VXGroup compareTestVXGroup=createVXGroup(); - - Mockito.when(xUserMgr.createXGroup(compareTestVXGroup)).thenReturn(compareTestVXGroup); - VXGroup retVxGroup=xUserRest.secureCreateXGroup(compareTestVXGroup); - - assertNotNull(retVxGroup); - assertEquals(compareTestVXGroup.getId(),retVxGroup.getId()); - assertEquals(compareTestVXGroup.getName(),retVxGroup.getName()); - Mockito.verify(xUserMgr).createXGroup(compareTestVXGroup); - } - @Test - public void test5updateXGroup() { - VXGroup compareTestVXGroup=createVXGroup(); - - Mockito.when(xUserMgr.updateXGroup(compareTestVXGroup)).thenReturn(compareTestVXGroup); - VXGroup retVxGroup=xUserRest.updateXGroup(compareTestVXGroup); - - assertNotNull(retVxGroup); - assertEquals(compareTestVXGroup.getId(),retVxGroup.getId()); - assertEquals(compareTestVXGroup.getName(),retVxGroup.getName()); - Mockito.verify(xUserMgr).updateXGroup(compareTestVXGroup); - } - @Test - public void test6secureUpdateXGroup() { - VXGroup compareTestVXGroup=createVXGroup(); - - Mockito.when(xUserMgr.updateXGroup(compareTestVXGroup)).thenReturn(compareTestVXGroup); - VXGroup retVxGroup=xUserRest.secureUpdateXGroup(compareTestVXGroup); - - assertNotNull(retVxGroup); - assertEquals(compareTestVXGroup.getId(),retVxGroup.getId()); - assertEquals(compareTestVXGroup.getName(),retVxGroup.getName()); - Mockito.verify(xUserMgr).updateXGroup(compareTestVXGroup); - } - @Test - public void test7modifyGroupsVisibility() { - HashMap groupVisibilityMap=creategroupVisibilityMap(); - xUserRest.modifyGroupsVisibility(groupVisibilityMap); - - Mockito.verify(xUserMgr).modifyGroupsVisibility(groupVisibilityMap); - } - @Test - public void test8deleteXGroupTrue() { - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - String TestforceDeleteStr="true"; - boolean forceDelete = false; - Mockito.when(request.getParameter("forceDelete")).thenReturn(TestforceDeleteStr); - - forceDelete=true; - Mockito.doNothing().when(xUserMgr).deleteXGroup(id, forceDelete); - xUserRest.deleteXGroup(id,request); - Mockito.verify(xUserMgr).deleteXGroup(id,forceDelete); - Mockito.verify(request).getParameter("forceDelete"); - } - @Test - public void test9deleteXGroupFalse() { - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - String TestforceDeleteStr="false"; - boolean forceDelete ; - Mockito.when(request.getParameter("forceDelete")).thenReturn(TestforceDeleteStr); - - forceDelete=false; - Mockito.doNothing().when(xUserMgr).deleteXGroup(id, forceDelete); - xUserRest.deleteXGroup(id,request); - Mockito.verify(xUserMgr).deleteXGroup(id,forceDelete); - Mockito.verify(request).getParameter("forceDelete"); - } - @Test - public void test10deleteXGroupNotEmpty() { - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - String TestforceDeleteStr=null; - boolean forceDelete ; - Mockito.when(request.getParameter("forceDelete")).thenReturn(TestforceDeleteStr); - - forceDelete=false; - Mockito.doNothing().when(xUserMgr).deleteXGroup(id, forceDelete); - xUserRest.deleteXGroup(id,request); - Mockito.verify(xUserMgr).deleteXGroup(id,forceDelete); - Mockito.verify(request).getParameter("forceDelete"); - } - @SuppressWarnings("unchecked") - @Test - public void test11searchXGroups() { - - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - SearchCriteria testSearchCriteria=createsearchCriteria(); - Mockito.when(searchUtil.extractCommonCriterias((HttpServletRequest)Mockito.any() ,(List)Mockito.any())).thenReturn(testSearchCriteria); - - Mockito.when(searchUtil.extractString(request, testSearchCriteria, "name", "group name", null)).thenReturn(""); - Mockito.when(searchUtil.extractInt(request, testSearchCriteria, "isVisible", "Group Visibility")).thenReturn(1); - Mockito.when(searchUtil.extractInt(request, testSearchCriteria, "groupSource", "group source")).thenReturn(1); - VXGroupList testvXGroupList=createxGroupList(); - Mockito.when(xUserMgr.searchXGroups(testSearchCriteria)).thenReturn(testvXGroupList); - VXGroupList outputvXGroupList=xUserRest.searchXGroups(request); - - Mockito.verify(xUserMgr).searchXGroups(testSearchCriteria); - Mockito.verify(searchUtil).extractCommonCriterias((HttpServletRequest)Mockito.any() ,(List)Mockito.any()); - Mockito.verify(searchUtil).extractString(request, testSearchCriteria, "name", "group name", null); - Mockito.verify(searchUtil).extractInt(request, testSearchCriteria, "isVisible", "Group Visibility"); - Mockito.verify(searchUtil).extractInt(request, testSearchCriteria, "groupSource", "group source"); - assertNotNull(outputvXGroupList); - assertEquals(outputvXGroupList.getTotalCount(),testvXGroupList.getTotalCount()); - assertEquals(outputvXGroupList.getClass(),testvXGroupList.getClass()); - - } - @SuppressWarnings("unchecked") - @Test - public void test12countXGroups() { - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - SearchCriteria testSearchCriteria=createsearchCriteria(); - - Mockito.when(searchUtil.extractCommonCriterias((HttpServletRequest)Mockito.any() ,(List)Mockito.any())).thenReturn(testSearchCriteria); - - vXLong.setValue(1); - - Mockito.when(xUserMgr.getXGroupSearchCount(testSearchCriteria)).thenReturn(vXLong); - VXLong testvxLong=xUserRest.countXGroups(request); - Mockito.verify(xUserMgr).getXGroupSearchCount(testSearchCriteria); - Mockito.verify(searchUtil).extractCommonCriterias((HttpServletRequest)Mockito.any() ,(List)Mockito.any()); - - assertNotNull(testvxLong); - assertEquals(testvxLong.getValue(),vXLong.getValue()); - assertEquals(testvxLong.getClass(),vXLong.getClass()); - - } - @Test - public void test13getXUser() { - - Mockito.when(xUserMgr.getXUser(id)).thenReturn(vxUser); - VXUser gotVXUser=xUserRest.getXUser(id); - Mockito.verify(xUserMgr).getXUser(id); - - assertNotNull(gotVXUser); - assertEquals(vxUser.getId(), gotVXUser.getId()); - assertEquals(vxUser.getName(), gotVXUser.getName()); - } - @Test - public void test14secureGetXUser() { - - Mockito.when(xUserMgr.getXUser(id)).thenReturn(vxUser); - VXUser gotVXUser=xUserRest.secureGetXUser(id); - Mockito.verify(xUserMgr).getXUser(id); - - assertNotNull(gotVXUser); - assertEquals(vxUser.getId(), gotVXUser.getId()); - assertEquals(vxUser.getName(), gotVXUser.getName()); - } - @Test - public void test15createXUser() { - - Mockito.when(xUserMgr.createXUserWithOutLogin(vxUser)).thenReturn(vxUser); - VXUser gotVXUser=xUserRest.createXUser(vxUser); - Mockito.verify(xUserMgr).createXUserWithOutLogin(vxUser); - - assertNotNull(gotVXUser); - assertEquals(vxUser.getId(), gotVXUser.getId()); - assertEquals(vxUser.getName(), gotVXUser.getName()); - } - @Test - public void test16createXUserGroupFromMap() { - VXUserGroupInfo vXUserGroupInfo= new VXUserGroupInfo(); - vXUserGroupInfo.setXuserInfo(vxUser); - - Mockito.when(xUserMgr.createXUserGroupFromMap(vXUserGroupInfo)).thenReturn(vXUserGroupInfo); - VXUserGroupInfo gotVXUserGroupInfo=xUserRest.createXUserGroupFromMap(vXUserGroupInfo); - Mockito.verify(xUserMgr).createXUserGroupFromMap(vXUserGroupInfo); - - assertNotNull(gotVXUserGroupInfo); - assertEquals(vXUserGroupInfo.getId(), gotVXUserGroupInfo.getId()); - assertEquals(vXUserGroupInfo.getOwner(), gotVXUserGroupInfo.getOwner()); - } - @Test - public void test17secureCreateXUser() { - Boolean val= true; - Mockito.when(bizUtil.checkUserAccessible(vxUser)).thenReturn(val); - Mockito.when(xUserMgr.createXUser(vxUser)).thenReturn(vxUser); - VXUser gotVXUser=xUserRest.secureCreateXUser(vxUser); - Mockito.verify(xUserMgr).createXUser(vxUser); - Mockito.verify(bizUtil).checkUserAccessible(vxUser); - assertNotNull(gotVXUser); - assertEquals(vxUser.getId(), gotVXUser.getId()); - assertEquals(vxUser.getName(), gotVXUser.getName()); - - } - @Test - public void test18updateXUser() { - Mockito.when(xUserMgr.updateXUser(vxUser)).thenReturn(vxUser); - VXUser gotVXUser=xUserRest.updateXUser(vxUser); - Mockito.verify(xUserMgr).updateXUser(vxUser); - assertNotNull(gotVXUser); - assertEquals(vxUser.getId(), gotVXUser.getId()); - assertEquals(vxUser.getName(), gotVXUser.getName()); - } - @Test - public void test19secureUpdateXUser() { - - Boolean val= true; - Mockito.when(bizUtil.checkUserAccessible(vxUser)).thenReturn(val); - Mockito.when(xUserMgr.updateXUser(vxUser)).thenReturn(vxUser); - VXUser gotVXUser=xUserRest.secureUpdateXUser(vxUser); - Mockito.verify(xUserMgr).updateXUser(vxUser); - Mockito.verify(bizUtil).checkUserAccessible(vxUser); - - assertNotNull(gotVXUser); - assertEquals(vxUser.getId(), gotVXUser.getId()); - assertEquals(vxUser.getName(), gotVXUser.getName()); - } - @Test - public void test20modifyUserVisibility() { - HashMap testVisibilityMap= new HashMap(); - testVisibilityMap.put(1L,0); - Mockito.doNothing().when(xUserMgr).modifyUserVisibility(testVisibilityMap); - xUserRest.modifyUserVisibility(testVisibilityMap); - Mockito.verify(xUserMgr).modifyUserVisibility(testVisibilityMap); - } - @Test - public void test21deleteXUser() { - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - - boolean forceDelete = false; - String TestforceDeleteStr="true"; - Mockito.when(request.getParameter("forceDelete")).thenReturn(TestforceDeleteStr); - forceDelete = true; - Mockito.doNothing().when(xUserMgr).deleteXUser(id, forceDelete); - xUserRest.deleteXUser(id, request); - Mockito.verify(xUserMgr).deleteXUser(id,forceDelete); - Mockito.verify(request).getParameter("forceDelete"); - } - @Test - public void test22deleteXUserFalse() { - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - String TestforceDeleteStr="false"; - boolean forceDelete ; - Mockito.when(request.getParameter("forceDelete")).thenReturn(TestforceDeleteStr); - - forceDelete=false; - Mockito.doNothing().when(xUserMgr).deleteXUser(id, forceDelete); - xUserRest.deleteXUser(id,request); - Mockito.verify(xUserMgr).deleteXUser(id,forceDelete); - Mockito.verify(request).getParameter("forceDelete"); - } - @Test - public void test23deleteXUserNotEmpty() { - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - String TestforceDeleteStr=null; - boolean forceDelete ; - Mockito.when(request.getParameter("forceDelete")).thenReturn(TestforceDeleteStr); - - forceDelete=false; - Mockito.doNothing().when(xUserMgr).deleteXUser(id, forceDelete); - xUserRest.deleteXUser(id,request); - Mockito.verify(xUserMgr).deleteXUser(id,forceDelete); - Mockito.verify(request).getParameter("forceDelete"); - } - @SuppressWarnings("unchecked") - @Test - public void test24searchXUsers() { - - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - SearchCriteria testSearchCriteria=createsearchCriteria(); - - Mockito.when(searchUtil.extractCommonCriterias((HttpServletRequest)Mockito.any(), (List)Mockito.any())).thenReturn(testSearchCriteria); - - Mockito.when(searchUtil.extractString(request, testSearchCriteria, "name", "User name", null)).thenReturn(""); - Mockito.when(searchUtil.extractString(request, testSearchCriteria, "emailAddress", "Email Address",null)).thenReturn(""); - Mockito.when(searchUtil.extractInt(request, testSearchCriteria, "userSource", "User Source")).thenReturn(1); - Mockito.when(searchUtil.extractInt(request, testSearchCriteria, "isVisible", "User Visibility")).thenReturn(1); - Mockito.when(searchUtil.extractInt(request, testSearchCriteria, "status", "User Status")).thenReturn(1); - Mockito.when(searchUtil.extractStringList(request, testSearchCriteria, "userRoleList", "User Role List", "userRoleList", null,null)).thenReturn(new ArrayList()); - Mockito.when(searchUtil.extractRoleString(request, testSearchCriteria, "userRole", "Role", null)).thenReturn(""); - - List vXUsersList= new ArrayList(); - vXUsersList.add(vxUser); - VXUserList testVXUserList= new VXUserList(); - testVXUserList.setVXUsers(vXUsersList); - - Mockito.when(xUserMgr.searchXUsers(testSearchCriteria)).thenReturn(testVXUserList); - VXUserList gotVXUserList=xUserRest.searchXUsers(request, null, null); - - Mockito.verify(xUserMgr).searchXUsers(testSearchCriteria); - Mockito.verify(searchUtil).extractCommonCriterias((HttpServletRequest)Mockito.any() ,(List)Mockito.any()); - - Mockito.verify(searchUtil).extractString(request, testSearchCriteria, "name", "User name", null); - Mockito.verify(searchUtil).extractString(request, testSearchCriteria, "emailAddress", "Email Address",null); - Mockito.verify(searchUtil).extractInt(request, testSearchCriteria, "userSource", "User Source"); - Mockito.verify(searchUtil).extractInt(request, testSearchCriteria, "isVisible", "User Visibility"); - Mockito.verify(searchUtil).extractInt(request, testSearchCriteria, "status", "User Status"); - Mockito.verify(searchUtil).extractStringList(request, testSearchCriteria, "userRoleList", "User Role List", "userRoleList", null,null); - Mockito.verify(searchUtil).extractRoleString(request, testSearchCriteria, "userRole", "Role", null); - assertNotNull(gotVXUserList); - assertEquals(testVXUserList.getTotalCount(),gotVXUserList.getTotalCount()); - assertEquals(testVXUserList.getClass(),gotVXUserList.getClass()); - } - - - - @SuppressWarnings("unchecked") - @Test - public void test25countXUsers() { - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - SearchCriteria testSearchCriteria=createsearchCriteria(); - - Mockito.when(searchUtil.extractCommonCriterias((HttpServletRequest)Mockito.any() ,(List)Mockito.any())).thenReturn(testSearchCriteria); - - vXLong.setValue(1); - - Mockito.when(xUserMgr.getXUserSearchCount(testSearchCriteria)).thenReturn(vXLong); - VXLong testvxLong=xUserRest.countXUsers(request); - Mockito.verify(xUserMgr).getXUserSearchCount(testSearchCriteria); - Mockito.verify(searchUtil).extractCommonCriterias((HttpServletRequest)Mockito.any() ,(List)Mockito.any()); - - assertNotNull(testvxLong); - assertEquals(testvxLong.getValue(),vXLong.getValue()); - assertEquals(testvxLong.getClass(),vXLong.getClass()); - } - @Test - public void test26getXGroupUser() { - VXGroupUser testVXGroupUser= createVXGroupUser(); - - Mockito.when(xUserMgr.getXGroupUser(id)).thenReturn(testVXGroupUser); - VXGroupUser retVxGroupUser= xUserRest.getXGroupUser(id); - - assertNotNull(retVxGroupUser); - assertEquals(testVXGroupUser.getClass(),retVxGroupUser.getClass()); - assertEquals(testVXGroupUser.getId(),retVxGroupUser.getId()); - Mockito.verify(xUserMgr).getXGroupUser(id); - } - @Test - public void test27createXGroupUser() { - VXGroupUser testVXGroupUser= createVXGroupUser(); - - Mockito.when(xUserMgr.createXGroupUser(testVXGroupUser)).thenReturn(testVXGroupUser); - VXGroupUser retVxGroupUser= xUserRest.createXGroupUser(testVXGroupUser); - - assertNotNull(retVxGroupUser); - assertEquals(testVXGroupUser.getClass(),retVxGroupUser.getClass()); - assertEquals(testVXGroupUser.getId(),retVxGroupUser.getId()); - Mockito.verify(xUserMgr).createXGroupUser(testVXGroupUser); - } - @Test - public void test28updateXGroupUser() { - VXGroupUser testVXGroupUser= createVXGroupUser(); - - Mockito.when(xUserMgr.updateXGroupUser(testVXGroupUser)).thenReturn(testVXGroupUser); - VXGroupUser retVxGroupUser= xUserRest.updateXGroupUser(testVXGroupUser); - - assertNotNull(retVxGroupUser); - assertEquals(testVXGroupUser.getClass(),retVxGroupUser.getClass()); - assertEquals(testVXGroupUser.getId(),retVxGroupUser.getId()); - Mockito.verify(xUserMgr).updateXGroupUser(testVXGroupUser); - } - - @Test - public void test29deleteXGroupUser() { - boolean force = true; - - Mockito.doNothing().when(xUserMgr).deleteXGroupUser(id, force); - xUserRest.deleteXGroupUser(id,request); - Mockito.verify(xUserMgr).deleteXGroupUser(id,force); - } - @SuppressWarnings("unchecked") - @Test - public void test30searchXGroupUsers() { - - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - SearchCriteria testSearchCriteria=createsearchCriteria(); - - Mockito.when(searchUtil.extractCommonCriterias((HttpServletRequest)Mockito.any() ,(List)Mockito.any())).thenReturn(testSearchCriteria); - - VXGroupUserList testVXGroupUserList=new VXGroupUserList(); - VXGroupUser vXGroupUser = createVXGroupUser(); - List vXGroupUsers= new ArrayList(); - vXGroupUsers.add(vXGroupUser); - testVXGroupUserList.setVXGroupUsers(vXGroupUsers); - Mockito.when(xUserMgr.searchXGroupUsers(testSearchCriteria)).thenReturn(testVXGroupUserList); - VXGroupUserList outputvXGroupList=xUserRest.searchXGroupUsers(request); - - Mockito.verify(xUserMgr).searchXGroupUsers(testSearchCriteria); - Mockito.verify(searchUtil).extractCommonCriterias((HttpServletRequest)Mockito.any() ,(List)Mockito.any()); - - assertNotNull(outputvXGroupList); - assertEquals(outputvXGroupList.getClass(),testVXGroupUserList.getClass()); - assertEquals(outputvXGroupList.getResultSize(),testVXGroupUserList.getResultSize()); - - } @SuppressWarnings("unchecked") - @Test - public void test31countXGroupUserst() { - - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - SearchCriteria testSearchCriteria=createsearchCriteria(); - - Mockito.when(searchUtil.extractCommonCriterias((HttpServletRequest)Mockito.any() ,(List)Mockito.any())).thenReturn(testSearchCriteria); - - vXLong.setValue(1); - - Mockito.when(xUserMgr.getXGroupUserSearchCount(testSearchCriteria)).thenReturn(vXLong); - VXLong testvxLong=xUserRest.countXGroupUsers(request); - Mockito.verify(xUserMgr).getXGroupUserSearchCount(testSearchCriteria); - Mockito.verify(searchUtil).extractCommonCriterias((HttpServletRequest)Mockito.any() ,(List)Mockito.any()); - - assertNotNull(testvxLong); - assertEquals(testvxLong.getValue(),vXLong.getValue()); - assertEquals(testvxLong.getClass(),vXLong.getClass()); - } - @Test - public void test38getXPermMapVXResourceNull() throws Exception{ - VXPermMap permMap = testcreateXPermMap(); - - Mockito.when(xUserMgr.getXPermMap(id)).thenReturn(permMap); - - Mockito.when(restErrorUtil.createRESTException(Mockito.anyString(), (MessageEnums)Mockito.any())).thenThrow(new WebApplicationException()); - thrown.expect(WebApplicationException.class); - - VXPermMap retVxGroup= xUserRest.getXPermMap(id); - - Mockito.verify(xUserMgr).getXPermMap(id); - Mockito.verify(xResourceService).readResource(null); - Mockito.verify(restErrorUtil).createRESTException(Mockito.anyString(), (MessageEnums)Mockito.any()); - assertEquals(permMap.getId(),retVxGroup.getId()); - assertEquals(permMap.getClass(),retVxGroup.getClass()); - assertNotNull(retVxGroup); - - - } - @Test - public void test39getXPermMapNotNull() throws Exception{ - VXPermMap permMap = testcreateXPermMap(); - - Mockito.when(xUserMgr.getXPermMap(id)).thenReturn(permMap); - VXResource testVxResource= new VXResource(); - Mockito.when(xResourceService.readResource(id)).thenReturn(testVxResource); - - VXPermMap retVxGroup=xUserRest.getXPermMap(id); - assertEquals(permMap.getId(),retVxGroup.getId()); - assertEquals(permMap.getClass(),retVxGroup.getClass()); - assertNotNull(retVxGroup); - Mockito.verify(xUserMgr).getXPermMap(id); - Mockito.verify(xResourceService).readResource(id); - } - @Test - public void test40getXPermMapNull() { - - Mockito.when(xUserMgr.getXPermMap(id)).thenReturn(null); - VXPermMap retVxGroup=xUserRest.getXPermMap(id); - assertNull(retVxGroup); - Mockito.verify(xUserMgr).getXPermMap(id); - } - - @Test - public void test41createXPermMap() { - - VXPermMap permMap = testcreateXPermMap(); - permMap.setResourceId(null); - Mockito.when(xResourceService.readResource(permMap.getResourceId())).thenReturn(null); - Mockito.when(restErrorUtil.createRESTException(Mockito.anyString(), (MessageEnums)Mockito.any())).thenThrow(new WebApplicationException()); - thrown.expect(WebApplicationException.class); - - VXPermMap retVxGroup=xUserRest.createXPermMap(permMap); - - assertEquals(permMap.getId(),retVxGroup.getId()); - assertEquals(permMap.getClass(),retVxGroup.getClass()); - assertNotNull(retVxGroup); - - Mockito.verify(xUserMgr).createXPermMap(permMap); - Mockito.verify(xResourceService).readResource(permMap.getResourceId()); - Mockito.verify(restErrorUtil).createRESTException(Mockito.anyString(), (MessageEnums)Mockito.any()); - } - - @Test - public void test42createXPermMapNull() { - - Mockito.when(xUserMgr.createXPermMap(null)).thenReturn(null); - VXPermMap retVxGroup=xUserRest.createXPermMap(null); - Mockito.verify(xUserMgr).createXPermMap(null); - assertNull(retVxGroup); - - } - - @Test - public void test43createXPermMapNullVXResource() { - VXPermMap permMap = testcreateXPermMap(); - permMap.setResourceId(null); - Mockito.when(xUserMgr.createXPermMap(permMap)).thenReturn(permMap); - VXResource testVxResource= new VXResource(); - Mockito.when(xResourceService.readResource(permMap.getResourceId())).thenReturn(testVxResource); - - VXPermMap retVxGroup=xUserRest.createXPermMap(permMap); - - assertEquals(permMap.getId(),retVxGroup.getId()); - assertEquals(permMap.getClass(),retVxGroup.getClass()); - assertNotNull(retVxGroup); - - Mockito.verify(xUserMgr).createXPermMap(permMap); - Mockito.verify(xResourceService).readResource(permMap.getResourceId()); - } - - @Test - public void test44updateXPermMap() { - - VXPermMap permMap = testcreateXPermMap(); - - VXResource testVxResource= new VXResource(); - Mockito.when(xResourceService.readResource(id)).thenReturn(testVxResource); - Mockito.when(xUserMgr.updateXPermMap(permMap)).thenReturn(permMap); - VXPermMap retVxGroup=xUserRest.updateXPermMap(permMap); - - assertEquals(permMap.getId(),retVxGroup.getId()); - assertEquals(permMap.getClass(),retVxGroup.getClass()); - assertNotNull(retVxGroup); - - Mockito.verify(xUserMgr).updateXPermMap(permMap); - Mockito.verify(xResourceService).readResource(permMap.getResourceId()); - } - @Test - public void test45updateXPermMap() { - VXPermMap vXPermMap=null ; - VXPermMap retVxGroup=xUserRest.updateXPermMap(vXPermMap); - assertNull(retVxGroup); - } - @Test - public void test46updateXPermMap() { - VXPermMap permMap = testcreateXPermMap(); - - Mockito.when(xResourceService.readResource(permMap.getResourceId())).thenReturn(null); - Mockito.when(restErrorUtil.createRESTException(Mockito.anyString())).thenThrow(new WebApplicationException()); - thrown.expect(WebApplicationException.class); - - VXPermMap retVxGroup=xUserRest.updateXPermMap(permMap); - - assertEquals(permMap.getId(),retVxGroup.getId()); - assertEquals(permMap.getClass(),retVxGroup.getClass()); - assertNotNull(retVxGroup); - - Mockito.verify(xUserMgr).updateXPermMap(permMap); - Mockito.verify(xResourceService).readResource(permMap.getResourceId()); - Mockito.verify(restErrorUtil).createRESTException(Mockito.anyString()); - - } - @Test - public void test47deleteXPermMap() { - Boolean forceDelete=false; - Mockito.doNothing().when(xUserMgr).deleteXPermMap(id, forceDelete); - xUserRest.deleteXPermMap(id,request); - Mockito.verify(xUserMgr).deleteXPermMap(id,forceDelete); - } - @SuppressWarnings("unchecked") - @Test - public void test48searchXPermMaps() { - VXPermMap permMap = testcreateXPermMap(); - - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - SearchCriteria testSearchCriteria=createsearchCriteria(); - Mockito.when(searchUtil.extractCommonCriterias((HttpServletRequest)Mockito.any() ,(List)Mockito.any())).thenReturn(testSearchCriteria); - - List vXPermMaps= new ArrayList(); - vXPermMaps.add(permMap); - VXPermMapList testvXGroupList=new VXPermMapList() ; - testvXGroupList.setTotalCount(1); - testvXGroupList.setVXPermMaps(vXPermMaps); - Mockito.when(xUserMgr.searchXPermMaps(testSearchCriteria)).thenReturn(testvXGroupList); - VXPermMapList outputvXGroupList=xUserRest.searchXPermMaps(request); - - Mockito.verify(xUserMgr).searchXPermMaps(testSearchCriteria); - Mockito.verify(searchUtil).extractCommonCriterias((HttpServletRequest)Mockito.any() ,(List)Mockito.any()); - - assertNotNull(outputvXGroupList); - assertEquals(outputvXGroupList.getClass(),testvXGroupList.getClass()); - assertEquals(outputvXGroupList.getTotalCount(),testvXGroupList.getTotalCount()); - } - @SuppressWarnings("unchecked") - @Test - public void test49countXPermMaps() { - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - SearchCriteria testSearchCriteria=createsearchCriteria(); - - Mockito.when(searchUtil.extractCommonCriterias((HttpServletRequest)Mockito.any() ,(List)Mockito.any())).thenReturn(testSearchCriteria); - - vXLong.setValue(1); - Mockito.when(xUserMgr.getXPermMapSearchCount(testSearchCriteria)).thenReturn(vXLong); - VXLong testvxLong=xUserRest.countXPermMaps(request); - Mockito.verify(xUserMgr).getXPermMapSearchCount(testSearchCriteria); - Mockito.verify(searchUtil).extractCommonCriterias((HttpServletRequest)Mockito.any() ,(List)Mockito.any()); - - assertNotNull(testvxLong); - } - @Test - public void test50getXAuditMapVXAuditMapNull() { - VXAuditMap testvXAuditMap = createVXAuditMapObj(); - Mockito.when(xUserMgr.getXAuditMap(testvXAuditMap.getResourceId())).thenReturn(testvXAuditMap); - - Mockito.when(restErrorUtil.createRESTException(Mockito.anyString(), (MessageEnums)Mockito.any())).thenThrow(new WebApplicationException()); - thrown.expect(WebApplicationException.class); - - VXAuditMap retVXAuditMap=xUserRest.getXAuditMap(testvXAuditMap.getResourceId()); - - assertEquals(testvXAuditMap.getId(),retVXAuditMap.getId()); - assertEquals(testvXAuditMap.getClass(),retVXAuditMap.getClass()); - assertNotNull(retVXAuditMap); - - Mockito.verify(xUserMgr).getXAuditMap(testvXAuditMap.getResourceId()); - Mockito.verify(xResourceService).readResource(null); - Mockito.verify(restErrorUtil.createRESTException(Mockito.anyString(), (MessageEnums)Mockito.any())); - - } - @Test - public void test51getXAuditMapNull() { - VXAuditMap testvXAuditMap = createVXAuditMapObj(); - Mockito.when(xUserMgr.getXAuditMap(testvXAuditMap.getResourceId())).thenReturn(null); - VXAuditMap retVXAuditMap=xUserRest.getXAuditMap(testvXAuditMap.getResourceId()); - - assertNull(retVXAuditMap); - - Mockito.verify(xUserMgr).getXAuditMap(testvXAuditMap.getResourceId()); - - - } - @Test - public void test52getXAuditMap() { - VXAuditMap testvXAuditMap = createVXAuditMapObj(); - - - Mockito.when(xUserMgr.getXAuditMap(id)).thenReturn(testvXAuditMap); - VXResource testVxResource= createVXResource(); - Mockito.when(xResourceService.readResource(testvXAuditMap.getResourceId())).thenReturn(testVxResource); - - VXAuditMap retVXAuditMap=xUserRest.getXAuditMap(id); - - assertEquals(testvXAuditMap.getId(),retVXAuditMap.getId()); - assertEquals(testvXAuditMap.getClass(),retVXAuditMap.getClass()); - assertNotNull(retVXAuditMap); - - Mockito.verify(xUserMgr).getXAuditMap(id); - Mockito.verify(xResourceService).readResource(testvXAuditMap.getResourceId()); - - - } - - @Test - public void test53createXAuditMap() { - VXAuditMap testvXAuditMap = createVXAuditMapObj(); - - Mockito.when(xUserMgr.createXAuditMap(testvXAuditMap)).thenReturn(testvXAuditMap); - VXResource testVxResource= createVXResource(); - Mockito.when(xResourceService.readResource(testvXAuditMap.getResourceId())).thenReturn(testVxResource); - VXAuditMap retvXAuditMap= xUserRest.createXAuditMap(testvXAuditMap); - assertEquals(testvXAuditMap.getId(),retvXAuditMap.getId()); - assertEquals(testvXAuditMap.getClass(),retvXAuditMap.getClass()); - assertNotNull(retvXAuditMap); - - Mockito.verify(xUserMgr).createXAuditMap(testvXAuditMap); - Mockito.verify(xResourceService).readResource(testvXAuditMap.getResourceId()); - - - } - - @Test - public void test54createXAuditMapVxResourceNull() { - - VXAuditMap testvXAuditMap = createVXAuditMapObj(); - testvXAuditMap.setResourceId(null); - - Mockito.when(xResourceService.readResource(testvXAuditMap.getResourceId())).thenReturn(null); - - Mockito.when(restErrorUtil.createRESTException(Mockito.anyString(), (MessageEnums)Mockito.any())).thenThrow(new WebApplicationException()); - thrown.expect(WebApplicationException.class); - - VXAuditMap retvXAuditMap= xUserRest.createXAuditMap(testvXAuditMap); - assertEquals(testvXAuditMap.getId(),retvXAuditMap.getId()); - assertEquals(testvXAuditMap.getClass(),retvXAuditMap.getClass()); - assertNotNull(retvXAuditMap); - - Mockito.verify(xUserMgr).createXAuditMap(testvXAuditMap); - Mockito.verify(xResourceService).readResource(testvXAuditMap.getResourceId()); - Mockito.verify(restErrorUtil.createRESTException(Mockito.anyString(), (MessageEnums)Mockito.any())); - - }@Test - public void test55createXAuditMapNull() { - VXAuditMap testvXAuditMap = createVXAuditMapObj(); - testvXAuditMap.setResourceId(null); - VXAuditMap retvXAuditMap=xUserRest.createXAuditMap(null); - assertNull(retvXAuditMap); - Mockito.verify(xUserMgr).createXAuditMap(null); - - } - - @Test - public void test56updateXAuditMap() { - VXAuditMap testvXAuditMap = createVXAuditMapObj(); - testvXAuditMap.setResourceId(id); - Mockito.when(xUserMgr.updateXAuditMap(testvXAuditMap)).thenReturn(testvXAuditMap); - VXResource testVxResource= createVXResource(); - Mockito.when(xResourceService.readResource(testvXAuditMap.getResourceId())).thenReturn(testVxResource); - - VXAuditMap retvXAuditMap=xUserRest.updateXAuditMap(testvXAuditMap); - assertEquals(testvXAuditMap.getId(),retvXAuditMap.getId()); - assertEquals(testvXAuditMap.getClass(),retvXAuditMap.getClass()); - assertNotNull(retvXAuditMap); - - Mockito.verify(xUserMgr).updateXAuditMap(testvXAuditMap); - Mockito.verify(xResourceService).readResource(testvXAuditMap.getResourceId()); - - - } - @Test - public void test57updateXAuditMapNull() { - VXAuditMap testvXAuditMap = createVXAuditMapObj(); - - - Mockito.when(restErrorUtil.createRESTException(Mockito.anyString(), (MessageEnums)Mockito.any())).thenThrow(new WebApplicationException()); - thrown.expect(WebApplicationException.class); - VXAuditMap retvXAuditMap=xUserRest.updateXAuditMap(testvXAuditMap); - assertNull(retvXAuditMap); - Mockito.verify(xUserMgr).updateXAuditMap(testvXAuditMap); - Mockito.verify(xResourceService).readResource(null); - Mockito.verify(restErrorUtil.createRESTException(Mockito.anyString(), (MessageEnums)Mockito.any())); - } - @Test - public void test58updateXAuditMapVXResourceNull() { - VXAuditMap vXAuditMap =null; - VXAuditMap retvXAuditMap=xUserRest.updateXAuditMap(vXAuditMap); - assertNull(retvXAuditMap); - } - @Test - public void test59deleteXAuditMap() { - - Boolean forceDelete=false; - Mockito.doNothing().when(xUserMgr).deleteXAuditMap(id, forceDelete); - xUserRest.deleteXAuditMap(id,request); - Mockito.verify(xUserMgr).deleteXAuditMap(id,forceDelete); - } - @SuppressWarnings("unchecked") - @Test - public void test60searchXAuditMaps() { - VXAuditMap testvXAuditMap = createVXAuditMapObj(); - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - SearchCriteria testSearchCriteria=createsearchCriteria(); - Mockito.when(searchUtil.extractCommonCriterias((HttpServletRequest)Mockito.any() ,(List)Mockito.any())).thenReturn(testSearchCriteria); - - List testvXAuditMaps= new ArrayList(); - testvXAuditMaps.add(testvXAuditMap); - VXAuditMapList testVXAuditMapList=new VXAuditMapList() ; - testVXAuditMapList.setVXAuditMaps(testvXAuditMaps); - Mockito.when(xUserMgr.searchXAuditMaps(testSearchCriteria)).thenReturn(testVXAuditMapList); - VXAuditMapList outputVXAuditMapList=xUserRest.searchXAuditMaps(request); - - Mockito.verify(xUserMgr).searchXAuditMaps(testSearchCriteria); - Mockito.verify(searchUtil).extractCommonCriterias((HttpServletRequest)Mockito.any() ,(List)Mockito.any()); - - assertNotNull(outputVXAuditMapList); - assertEquals(outputVXAuditMapList.getClass(),testVXAuditMapList.getClass()); - assertEquals(outputVXAuditMapList.getResultSize(),testVXAuditMapList.getResultSize()); - - - } - @SuppressWarnings("unchecked") - @Test - public void test61countXAuditMaps() { - - - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - SearchCriteria testSearchCriteria=createsearchCriteria(); - - Mockito.when(searchUtil.extractCommonCriterias((HttpServletRequest)Mockito.any() ,(List)Mockito.any())).thenReturn(testSearchCriteria); - - vXLong.setValue(1); - Mockito.when(xUserMgr.getXAuditMapSearchCount(testSearchCriteria)).thenReturn(vXLong); - VXLong testvxLong=xUserRest.countXAuditMaps(request); - Mockito.verify(xUserMgr).getXAuditMapSearchCount(testSearchCriteria); - Mockito.verify(searchUtil).extractCommonCriterias((HttpServletRequest)Mockito.any() ,(List)Mockito.any()); - assertEquals(testvxLong.getClass(),vXLong.getClass()); - assertEquals(testvxLong.getValue(),vXLong.getValue()); - assertNotNull(testvxLong); - } - @Test - public void test62getXUserByUserName() { - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - - VXUser compareTestVxUser=createVXUser(); - - Mockito.when(xUserMgr.getXUserByUserName("User1")).thenReturn(compareTestVxUser); - VXUser retVXUser= xUserRest.getXUserByUserName(request,"User1"); - - assertNotNull(retVXUser); - assertEquals(compareTestVxUser.getClass(),retVXUser.getClass()); - assertEquals(compareTestVxUser.getId(),retVXUser.getId()); - Mockito.verify(xUserMgr).getXUserByUserName("User1"); - } - @Test - public void test63getXGroupByGroupName() { - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - - VXGroup compareTestVXGroup=createVXGroup(); - - Mockito.when(xGroupService.getGroupByGroupName(compareTestVXGroup.getName())).thenReturn(compareTestVXGroup); - - VXGroup retVxGroup= xUserRest.getXGroupByGroupName(request,compareTestVXGroup.getName()); - - assertNotNull(retVxGroup); - assertEquals(compareTestVXGroup.getClass(),compareTestVXGroup.getClass()); - assertEquals(compareTestVXGroup.getId(),compareTestVXGroup.getId()); - Mockito.verify(xGroupService).getGroupByGroupName(compareTestVXGroup.getName()); - } - @Test - public void test64deleteXUserByUserName() { - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - String TestforceDeleteStr="true"; - boolean forceDelete = false; - Mockito.when(request.getParameter("forceDelete")).thenReturn(TestforceDeleteStr); - VXUser testUser= createVXUser(); - Mockito.when(xUserService.getXUserByUserName(testUser.getName())).thenReturn(testUser); - forceDelete=true; - Mockito.doNothing().when(xUserMgr).deleteXUser(testUser.getId(), forceDelete); - xUserRest.deleteXUserByUserName(testUser.getName(),request); - Mockito.verify(xUserMgr).deleteXUser(testUser.getId(),forceDelete); - Mockito.verify(xUserService).getXUserByUserName(testUser.getName()); - Mockito.verify(request).getParameter("forceDelete"); - - } - @Test - public void test65deleteXUserByUserNametrue() { - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - String TestforceDeleteStr="false"; - boolean forceDelete = true; - Mockito.when(request.getParameter("forceDelete")).thenReturn(TestforceDeleteStr); - VXUser testUser= createVXUser(); - Mockito.when(xUserService.getXUserByUserName(testUser.getName())).thenReturn(testUser); - forceDelete=false; - Mockito.doNothing().when(xUserMgr).deleteXUser(testUser.getId(), forceDelete); - xUserRest.deleteXUserByUserName(testUser.getName(),request); - Mockito.verify(xUserMgr).deleteXUser(testUser.getId(),forceDelete); - Mockito.verify(xUserService).getXUserByUserName(testUser.getName()); - Mockito.verify(request).getParameter("forceDelete"); - - } - @Test - public void test66deleteXUserByUserNameNull() { - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - String TestforceDeleteStr=null; - boolean forceDelete = true; - Mockito.when(request.getParameter("forceDelete")).thenReturn(TestforceDeleteStr); - VXUser testUser= createVXUser(); - Mockito.when(xUserService.getXUserByUserName(testUser.getName())).thenReturn(testUser); - forceDelete=false; - Mockito.doNothing().when(xUserMgr).deleteXUser(testUser.getId(), forceDelete); - xUserRest.deleteXUserByUserName(testUser.getName(),request); - Mockito.verify(xUserMgr).deleteXUser(testUser.getId(),forceDelete); - Mockito.verify(xUserService).getXUserByUserName(testUser.getName()); - Mockito.verify(request).getParameter("forceDelete"); - - } - @Test - public void test67deleteXGroupByGroupName() { - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - String TestforceDeleteStr="false"; - boolean forceDelete = true; - Mockito.when(request.getParameter("forceDelete")).thenReturn(TestforceDeleteStr); - VXGroup testVXGroup= createVXGroup(); - Mockito.when(xGroupService.getGroupByGroupName(testVXGroup.getName())).thenReturn(testVXGroup); - forceDelete=false; - Mockito.doNothing().when(xUserMgr).deleteXGroup(testVXGroup.getId(), forceDelete); - xUserRest.deleteXGroupByGroupName(testVXGroup.getName(),request); - Mockito.verify(xUserMgr).deleteXGroup(testVXGroup.getId(),forceDelete); - Mockito.verify(xGroupService).getGroupByGroupName(testVXGroup.getName()); - Mockito.verify(request).getParameter("forceDelete"); - - } - @Test - public void test68deleteXGroupByGroupNameNull() { - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - String TestforceDeleteStr=null; - boolean forceDelete = true; - Mockito.when(request.getParameter("forceDelete")).thenReturn(TestforceDeleteStr); - VXGroup testVXGroup= createVXGroup(); - Mockito.when(xGroupService.getGroupByGroupName(testVXGroup.getName())).thenReturn(testVXGroup); - forceDelete=false; - Mockito.doNothing().when(xUserMgr).deleteXGroup(testVXGroup.getId(), forceDelete); - xUserRest.deleteXGroupByGroupName(testVXGroup.getName(),request); - Mockito.verify(xUserMgr).deleteXGroup(testVXGroup.getId(),forceDelete); - Mockito.verify(xGroupService).getGroupByGroupName(testVXGroup.getName()); - Mockito.verify(request).getParameter("forceDelete"); - - } - @Test - public void test69deleteXGroupByGroupNameflase() { - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - String TestforceDeleteStr="true"; - boolean forceDelete = false; - Mockito.when(request.getParameter("forceDelete")).thenReturn(TestforceDeleteStr); - VXGroup testVXGroup= createVXGroup(); - Mockito.when(xGroupService.getGroupByGroupName(testVXGroup.getName())).thenReturn(testVXGroup); - forceDelete=true; - Mockito.doNothing().when(xUserMgr).deleteXGroup(testVXGroup.getId(), forceDelete); - xUserRest.deleteXGroupByGroupName(testVXGroup.getName(),request); - Mockito.verify(xUserMgr).deleteXGroup(testVXGroup.getId(),forceDelete); - Mockito.verify(xGroupService).getGroupByGroupName(testVXGroup.getName()); - Mockito.verify(request).getParameter("forceDelete"); - - } - @Test - public void test70deleteXGroupAndXUser() { - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - - VXGroup testVXGroup= createVXGroup(); - VXUser testVXuser= createVXUser(); - - Mockito.doNothing().when(xUserMgr).deleteXGroupAndXUser(testVXGroup.getName(),testVXuser.getName()); - xUserRest.deleteXGroupAndXUser(testVXGroup.getName(),testVXuser.getName(),request); - Mockito.verify(xUserMgr).deleteXGroupAndXUser(testVXGroup.getName(),testVXuser.getName()); - - - } - @Test - public void test71getXUserGroups() { - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - - VXGroupList groupList = createxGroupList(); - Mockito.when(xUserMgr.getXUserGroups(id)).thenReturn(groupList); - VXGroupList retVxGroupList= xUserRest.getXUserGroups(request,id); - - assertNotNull(retVxGroupList); - assertEquals(groupList.getClass(),retVxGroupList.getClass()); - assertEquals(groupList.getResultSize(),retVxGroupList.getResultSize()); - Mockito.verify(xUserMgr).getXUserGroups(id); - } - @Test - public void test72getXGroupUsers() { - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - - VXGroupList groupList = createxGroupList(); - Mockito.when(xUserMgr.getXUserGroups(id)).thenReturn(groupList); - VXGroupList retVxGroupList= xUserRest.getXUserGroups(request,id); - - assertNotNull(retVxGroupList); - assertEquals(groupList.getClass(),retVxGroupList.getClass()); - assertEquals(groupList.getResultSize(),retVxGroupList.getResultSize()); - Mockito.verify(xUserMgr).getXUserGroups(id); - } - @SuppressWarnings("unchecked") - @Test - public void test73getXGroupUsers() { - - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - SearchCriteria testSearchCriteria=createsearchCriteria(); - testSearchCriteria.addParam("xGroupId", id); - - Mockito.when(searchUtil.extractCommonCriterias((HttpServletRequest)Mockito.any() ,(List)Mockito.any())).thenReturn(testSearchCriteria); - - VXUser testVXUser=createVXUser(); - VXUserList testVXUserList= new VXUserList(); - List testVXUsers = new ArrayList(); - testVXUsers.add(testVXUser); - testVXUserList.setVXUsers(testVXUsers); - testVXUserList.setStartIndex(1); - testVXUserList.setTotalCount(1); - Mockito.when(xUserMgr.getXGroupUsers(testSearchCriteria)).thenReturn(testVXUserList); - VXUserList retVxGroupList= xUserRest.getXGroupUsers(request,id); - - assertNotNull(retVxGroupList); - assertEquals(testVXUserList.getTotalCount(),retVxGroupList.getTotalCount()); - assertEquals(testVXUserList.getStartIndex(),retVxGroupList.getStartIndex()); - Mockito.verify(xUserMgr).getXGroupUsers(testSearchCriteria); - } - @SuppressWarnings("unchecked") - @Test - public void test74getAuthSessions() { - - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - SearchCriteria testSearchCriteria=createsearchCriteria(); - - - Mockito.when(searchUtil.extractCommonCriterias((HttpServletRequest)Mockito.any() ,(List)Mockito.any())).thenReturn(testSearchCriteria); - - - Mockito.when(searchUtil.extractLong(request, testSearchCriteria, "id", "Auth Session Id")).thenReturn(1L); - Mockito.when(searchUtil.extractLong(request, testSearchCriteria, "userId", "User Id")).thenReturn(1L); - Mockito.when(searchUtil.extractInt(request, testSearchCriteria, "authStatus", "Auth Status")).thenReturn(1); - Mockito.when(searchUtil.extractInt(request, testSearchCriteria, "deviceType", "Device Type")).thenReturn(1); - Mockito.when(searchUtil.extractString(request, testSearchCriteria, "firstName", "User First Name", StringUtil.VALIDATION_NAME)).thenReturn(""); - Mockito.when(searchUtil.extractString(request, testSearchCriteria, "lastName", "User Last Name", StringUtil.VALIDATION_NAME)).thenReturn(""); - Mockito.when(searchUtil.extractString(request, testSearchCriteria, "requestUserAgent", "User Agent", StringUtil.VALIDATION_TEXT)).thenReturn(""); - Mockito.when(searchUtil.extractString(request, testSearchCriteria, "requestIP", "Request IP Address", StringUtil.VALIDATION_IP_ADDRESS)).thenReturn(""); - Mockito.when(searchUtil.extractString(request, testSearchCriteria, "loginId", "Login ID", StringUtil.VALIDATION_TEXT)).thenReturn(""); - - - VXAuthSessionList testVXAuthSessionList=new VXAuthSessionList(); - testVXAuthSessionList.setTotalCount(1); - testVXAuthSessionList.setStartIndex(1); - VXAuthSession testVXAuthSession = createVXAuthSession(); - List testvXAuthSessions = new ArrayList(); - testvXAuthSessions.add(testVXAuthSession); - - testVXAuthSessionList.setVXAuthSessions(testvXAuthSessions); - Mockito.when(sessionMgr.searchAuthSessions(testSearchCriteria)).thenReturn(testVXAuthSessionList); - VXAuthSessionList outputvXGroupList=xUserRest.getAuthSessions(request); - - Mockito.verify(sessionMgr).searchAuthSessions(testSearchCriteria); - Mockito.verify(searchUtil).extractCommonCriterias((HttpServletRequest)Mockito.any() ,(List)Mockito.any()); - Mockito.verify(searchUtil).extractLong(request, testSearchCriteria, "id", "Auth Session Id"); - Mockito.verify(searchUtil).extractLong(request, testSearchCriteria, "userId", "User Id"); - Mockito.verify(searchUtil).extractInt(request, testSearchCriteria, "authStatus", "Auth Status"); - Mockito.verify(searchUtil).extractInt(request, testSearchCriteria, "authType", "Login Type"); - Mockito.verify(searchUtil).extractInt(request, testSearchCriteria, "deviceType", "Device Type"); - Mockito.verify(searchUtil).extractString(request, testSearchCriteria, "firstName", "User First Name", StringUtil.VALIDATION_NAME); - Mockito.verify(searchUtil).extractString(request, testSearchCriteria, "lastName", "User Last Name", StringUtil.VALIDATION_NAME); - Mockito.verify(searchUtil).extractString(request, testSearchCriteria, "requestUserAgent", "User Agent", StringUtil.VALIDATION_TEXT); - Mockito.verify(searchUtil).extractString(request, testSearchCriteria, "requestIP", "Request IP Address", StringUtil.VALIDATION_IP_ADDRESS); - Mockito.verify(searchUtil).extractString(request, testSearchCriteria, "loginId", "Login ID", StringUtil.VALIDATION_TEXT); - Mockito.verify(searchUtil).extractDate(request, testSearchCriteria, "startDate", "Start Date", null); - Mockito.verify(searchUtil).extractDate(request, testSearchCriteria, "endDate", "End Date", null); - assertNotNull(outputvXGroupList); - assertEquals(outputvXGroupList.getStartIndex(),testVXAuthSessionList.getStartIndex()); - assertEquals(outputvXGroupList.getTotalCount(), testVXAuthSessionList.getTotalCount()); - } - @Test - public void test75getAuthSession() { - String authSessionId ="testauthSessionId"; - VXAuthSession testVXAuthSession= createVXAuthSession(); - - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - Mockito.when(request.getParameter("extSessionId")).thenReturn(authSessionId); - Mockito.when(sessionMgr.getAuthSessionBySessionId(authSessionId)).thenReturn(testVXAuthSession); - VXAuthSession retVXAuthSession=xUserRest.getAuthSession(request); - Mockito.verify(sessionMgr).getAuthSessionBySessionId(authSessionId); - Mockito.verify(request).getParameter("extSessionId"); - assertEquals(testVXAuthSession.getId(), retVXAuthSession.getId()); - assertEquals(testVXAuthSession.getClass(), retVXAuthSession.getClass()); - assertNotNull(retVXAuthSession); - } - @Test - public void test76createXModuleDefPermission() { - - VXModuleDef testVXModuleDef = createVXModuleDef(); - - Mockito.doNothing().when(xUserMgr).checkAdminAccess(); - - Mockito.when(xUserMgr.createXModuleDefPermission(testVXModuleDef)).thenReturn(testVXModuleDef); - VXModuleDef retVxModuleDef=xUserRest.createXModuleDefPermission(testVXModuleDef); - - assertNotNull(retVxModuleDef); - assertEquals(testVXModuleDef.getId(),retVxModuleDef.getId()); - assertEquals(testVXModuleDef.getOwner(),retVxModuleDef.getOwner()); - Mockito.verify(xUserMgr).createXModuleDefPermission(testVXModuleDef); - Mockito.verify(xUserMgr).checkAdminAccess(); - - } - @Test - public void test77getXModuleDefPermission() { - VXModuleDef testVXModuleDef=createVXModuleDef(); - Mockito.when(xUserMgr.getXModuleDefPermission(testVXModuleDef.getId())).thenReturn(testVXModuleDef); - VXModuleDef retVxModuleDef=xUserRest.getXModuleDefPermission(testVXModuleDef.getId()); - - assertNotNull(retVxModuleDef); - assertEquals(testVXModuleDef.getId(),retVxModuleDef.getId()); - assertEquals(testVXModuleDef.getOwner(),retVxModuleDef.getOwner()); - - Mockito.verify(xUserMgr).getXModuleDefPermission(testVXModuleDef.getId()); - - } - @Test - public void test78updateXModuleDefPermission() { - - VXModuleDef testVXModuleDef = createVXModuleDef(); - - Mockito.doNothing().when(xUserMgr).checkAdminAccess(); - - Mockito.when(xUserMgr.updateXModuleDefPermission(testVXModuleDef)).thenReturn(testVXModuleDef); - VXModuleDef retVxModuleDef=xUserRest.updateXModuleDefPermission(testVXModuleDef); - - assertNotNull(retVxModuleDef); - assertEquals(testVXModuleDef.getId(),retVxModuleDef.getId()); - assertEquals(testVXModuleDef.getOwner(),retVxModuleDef.getOwner()); - - Mockito.verify(xUserMgr).updateXModuleDefPermission(testVXModuleDef); - Mockito.verify(xUserMgr).checkAdminAccess(); - } - @Test - public void test79deleteXModuleDefPermission() { - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - - boolean forceDelete = true; - Mockito.doNothing().when(xUserMgr).checkAdminAccess(); - Mockito.doNothing().when(xUserMgr).deleteXModuleDefPermission(id, forceDelete); - xUserRest.deleteXModuleDefPermission(id,request); - Mockito.verify(xUserMgr).deleteXModuleDefPermission(id,forceDelete); - Mockito.verify(xUserMgr).checkAdminAccess(); - - } - @SuppressWarnings("unchecked") - @Test - public void test80searchXModuleDef() { - VXModuleDefList testVXModuleDefList= new VXModuleDefList() ; - VXModuleDef vXModuleDef=createVXModuleDef(); - List VXModuleDefs= new ArrayList(); - VXModuleDefs.add(vXModuleDef); - testVXModuleDefList.setvXModuleDef(VXModuleDefs); - testVXModuleDefList.setTotalCount(1); - testVXModuleDefList.setStartIndex(1); - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - SearchCriteria testSearchCriteria=createsearchCriteria(); - - Mockito.when(searchUtil.extractCommonCriterias((HttpServletRequest)Mockito.any() ,(List)Mockito.any())).thenReturn(testSearchCriteria); - Mockito.when(searchUtil.extractString(request, testSearchCriteria, "module","modulename", null)).thenReturn(""); - Mockito.when(searchUtil.extractString(request, testSearchCriteria, "moduleDefList","id", null)).thenReturn(""); - Mockito.when(searchUtil.extractString(request, testSearchCriteria, "userName","userName", null)).thenReturn(""); - Mockito.when(searchUtil.extractString(request, testSearchCriteria, "groupName","groupName", null)).thenReturn(""); - - Mockito.when(xUserMgr.searchXModuleDef(testSearchCriteria)).thenReturn(testVXModuleDefList); - VXModuleDefList outputVXModuleDefList=xUserRest.searchXModuleDef(request); - assertNotNull(outputVXModuleDefList); - assertEquals(outputVXModuleDefList.getTotalCount(),testVXModuleDefList.getTotalCount()); - assertEquals(outputVXModuleDefList.getStartIndex(),testVXModuleDefList.getStartIndex()); - - Mockito.verify(xUserMgr).searchXModuleDef(testSearchCriteria); - Mockito.verify(searchUtil).extractCommonCriterias((HttpServletRequest)Mockito.any() ,(List)Mockito.any()); - Mockito.verify(searchUtil).extractString(request, testSearchCriteria, "module","modulename", null); - Mockito.verify(searchUtil).extractString(request, testSearchCriteria, "moduleDefList","id", null); - Mockito.verify(searchUtil).extractString(request, testSearchCriteria, "userName","userName", null); - Mockito.verify(searchUtil).extractString(request, testSearchCriteria, "groupName","groupName", null); - - } - @SuppressWarnings("unchecked") - @Test - public void test81countXModuleDef() { - - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - SearchCriteria testSearchCriteria=createsearchCriteria(); - - - Mockito.when(searchUtil.extractCommonCriterias((HttpServletRequest)Mockito.any() ,(List)Mockito.any())).thenReturn(testSearchCriteria); - - vXLong.setValue(1); - - Mockito.when(xUserMgr.getXModuleDefSearchCount(testSearchCriteria)).thenReturn(vXLong); - VXLong testvxLong=xUserRest.countXModuleDef(request); - Mockito.verify(xUserMgr).getXModuleDefSearchCount(testSearchCriteria); - Mockito.verify(searchUtil).extractCommonCriterias((HttpServletRequest)Mockito.any() ,(List)Mockito.any()); - - assertNotNull(testvxLong); - assertEquals(testvxLong.getValue(),vXLong.getValue()); - assertEquals(testvxLong.getClass(),vXLong.getClass()); - } - @Test - public void test82createXUserPermission() { - VXUserPermission testvXUserPermission = createVXUserPermission(); - - Mockito.doNothing().when(xUserMgr).checkAdminAccess(); - Mockito.when(xUserMgr.createXUserPermission(testvXUserPermission)).thenReturn(testvXUserPermission); - VXUserPermission retVXUserPermission=xUserRest.createXUserPermission(testvXUserPermission); - Mockito.verify(xUserMgr).createXUserPermission(testvXUserPermission); - Mockito.verify(xUserMgr).checkAdminAccess(); - assertNotNull(retVXUserPermission); - assertEquals(retVXUserPermission.getId(), testvXUserPermission.getId()); - assertEquals(retVXUserPermission.getUserName(), testvXUserPermission.getUserName()); - } - @Test - public void test83getXUserPermission() { - VXUserPermission testVXUserPermission=createVXUserPermission(); - Mockito.when(xUserMgr.getXUserPermission(testVXUserPermission.getId())).thenReturn(testVXUserPermission); - VXUserPermission retVXUserPermission=xUserRest.getXUserPermission(testVXUserPermission.getId()); - Mockito.verify(xUserMgr).getXUserPermission(id); - assertNotNull(retVXUserPermission); - assertEquals(retVXUserPermission.getId(), testVXUserPermission.getId()); - assertEquals(retVXUserPermission.getUserName(), testVXUserPermission.getUserName()); - } - @Test - public void test84updateXUserPermission() { - VXUserPermission testvXUserPermission = createVXUserPermission(); - Mockito.doNothing().when(xUserMgr).checkAdminAccess(); - Mockito.when(xUserMgr.updateXUserPermission(testvXUserPermission)).thenReturn(testvXUserPermission); - VXUserPermission retVXUserPermission=xUserRest.updateXUserPermission(testvXUserPermission); - Mockito.verify(xUserMgr).updateXUserPermission(testvXUserPermission); - Mockito.verify(xUserMgr).checkAdminAccess(); - assertNotNull(retVXUserPermission); - assertEquals(retVXUserPermission.getId(), testvXUserPermission.getId()); - assertEquals(retVXUserPermission.getUserName(), testvXUserPermission.getUserName()); - - } - @Test - public void test85deleteXUserPermission() { - boolean forceDelete = true; - - Mockito.doNothing().when(xUserMgr).checkAdminAccess(); - - Mockito.doNothing().when(xUserMgr).deleteXUserPermission(id, forceDelete); - xUserRest.deleteXUserPermission(id,request); - Mockito.verify(xUserMgr).deleteXUserPermission(id,forceDelete); - Mockito.verify(xUserMgr).checkAdminAccess(); - - } - @SuppressWarnings("unchecked") - @Test - public void test86searchXUserPermission() { - VXUserPermissionList testVXUserPermissionList= new VXUserPermissionList() ; - testVXUserPermissionList.setTotalCount(1); - testVXUserPermissionList.setStartIndex(1); - VXUserPermission testVXUserPermission=createVXUserPermission(); - List testVXUserPermissions= new ArrayList(); - testVXUserPermissions.add(testVXUserPermission); - testVXUserPermissionList.setvXModuleDef(testVXUserPermissions); - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - SearchCriteria testSearchCriteria=createsearchCriteria(); - Mockito.when(searchUtil.extractCommonCriterias((HttpServletRequest)Mockito.any() ,(List)Mockito.any())).thenReturn(testSearchCriteria); - Mockito.when(searchUtil.extractString(request, testSearchCriteria, "id", "id",StringUtil.VALIDATION_NAME)).thenReturn(""); - Mockito.when(searchUtil.extractString(request, testSearchCriteria, "userPermissionList","userId", StringUtil.VALIDATION_NAME)).thenReturn(""); - - - Mockito.when(xUserMgr.searchXUserPermission(testSearchCriteria)).thenReturn(testVXUserPermissionList); - VXUserPermissionList outputVXUserPermissionList=xUserRest.searchXUserPermission(request); - assertNotNull(outputVXUserPermissionList); - assertEquals(outputVXUserPermissionList.getStartIndex(),testVXUserPermissionList.getStartIndex()); - assertEquals(outputVXUserPermissionList.getTotalCount(),testVXUserPermissionList.getTotalCount()); - - Mockito.verify(xUserMgr).searchXUserPermission(testSearchCriteria); - Mockito.verify(searchUtil).extractCommonCriterias((HttpServletRequest)Mockito.any() ,(List)Mockito.any()); - Mockito.verify(searchUtil).extractString(request, testSearchCriteria, "id", "id",StringUtil.VALIDATION_NAME); - Mockito.verify(searchUtil).extractString(request, testSearchCriteria, "userPermissionList","userId", StringUtil.VALIDATION_NAME); - - } - @SuppressWarnings("unchecked") - @Test - public void test87countXUserPermission() { - - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - SearchCriteria testSearchCriteria=createsearchCriteria(); - - - Mockito.when(searchUtil.extractCommonCriterias((HttpServletRequest)Mockito.any() ,(List)Mockito.any())).thenReturn(testSearchCriteria); - - vXLong.setValue(1); - - Mockito.when(xUserMgr.getXUserPermissionSearchCount(testSearchCriteria)).thenReturn(vXLong); - VXLong testvxLong=xUserRest.countXUserPermission(request); - Mockito.verify(xUserMgr).getXUserPermissionSearchCount(testSearchCriteria); - Mockito.verify(searchUtil).extractCommonCriterias((HttpServletRequest)Mockito.any() ,(List)Mockito.any()); - - assertNotNull(testvxLong); - assertEquals(testvxLong.getValue(),vXLong.getValue()); - assertEquals(testvxLong.getClass(),vXLong.getClass()); - - } - @Test - public void test88createXGroupPermission() { - - VXGroupPermission testVXGroupPermission = createVXGroupPermission(); - - Mockito.doNothing().when(xUserMgr).checkAdminAccess(); - Mockito.when(xUserMgr.createXGroupPermission(testVXGroupPermission)).thenReturn(testVXGroupPermission); - VXGroupPermission retVXGroupPermission=xUserRest.createXGroupPermission(testVXGroupPermission); - Mockito.verify(xUserMgr).createXGroupPermission(testVXGroupPermission); - Mockito.verify(xUserMgr).checkAdminAccess(); - assertNotNull(retVXGroupPermission); - assertEquals(retVXGroupPermission.getId(), testVXGroupPermission.getId()); - assertEquals(retVXGroupPermission.getClass(), testVXGroupPermission.getClass()); - - } - @Test - public void test89getXGroupPermission() { - VXGroupPermission testVXGroupPermission =createVXGroupPermission(); - Mockito.when(xUserMgr.getXGroupPermission(testVXGroupPermission.getId())).thenReturn(testVXGroupPermission); - VXGroupPermission retVXGroupPermission=xUserRest.getXGroupPermission(testVXGroupPermission.getId()); - Mockito.verify(xUserMgr).getXGroupPermission(testVXGroupPermission.getId()); - assertNotNull(retVXGroupPermission); - assertEquals(retVXGroupPermission.getId(), testVXGroupPermission.getId()); - assertEquals(retVXGroupPermission.getClass(), testVXGroupPermission.getClass()); - - } - @Test - public void test90updateXGroupPermission() { - - VXGroupPermission testVXGroupPermission = createVXGroupPermission(); - Mockito.doNothing().when(xUserMgr).checkAdminAccess(); - Mockito.when(xUserMgr.updateXGroupPermission(testVXGroupPermission)).thenReturn(testVXGroupPermission); - VXGroupPermission retVXGroupPermission=xUserRest.updateXGroupPermission(testVXGroupPermission.getId(), testVXGroupPermission); - Mockito.verify(xUserMgr).updateXGroupPermission(testVXGroupPermission); - Mockito.verify(xUserMgr).checkAdminAccess(); - assertNotNull(retVXGroupPermission); - assertEquals(retVXGroupPermission.getId(), testVXGroupPermission.getId()); - assertEquals(retVXGroupPermission.getClass(), testVXGroupPermission.getClass()); - - } - @Test - public void test91deleteXGroupPermission() { - - boolean forceDelete = true; - - Mockito.doNothing().when(xUserMgr).checkAdminAccess(); - - Mockito.doNothing().when(xUserMgr).deleteXGroupPermission(id, forceDelete); - xUserRest.deleteXGroupPermission(id,request); - Mockito.verify(xUserMgr).deleteXGroupPermission(id,forceDelete); - Mockito.verify(xUserMgr).checkAdminAccess(); - } - @SuppressWarnings("unchecked") - @Test - public void test92searchXGroupPermission() { - VXGroupPermissionList testVXGroupPermissionList= new VXGroupPermissionList() ; - testVXGroupPermissionList.setTotalCount(1); - VXGroupPermission testVXGroupPermission=createVXGroupPermission(); - List testVXGroupPermissions= new ArrayList(); - testVXGroupPermissions.add(testVXGroupPermission); - testVXGroupPermissionList.setvXGroupPermission(testVXGroupPermissions); - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - SearchCriteria testSearchCriteria=createsearchCriteria(); - Mockito.when(searchUtil.extractCommonCriterias((HttpServletRequest)Mockito.any() ,(List)Mockito.any())).thenReturn(testSearchCriteria); - Mockito.when(searchUtil.extractString(request, testSearchCriteria, "id", "id",StringUtil.VALIDATION_NAME)).thenReturn(""); - Mockito.when(searchUtil.extractString(request, testSearchCriteria,"groupPermissionList", "groupId", StringUtil.VALIDATION_NAME)).thenReturn(""); - Mockito.when(xUserMgr.searchXGroupPermission(testSearchCriteria)).thenReturn(testVXGroupPermissionList); - VXGroupPermissionList outputVXGroupPermissionList=xUserRest.searchXGroupPermission(request); - assertNotNull(outputVXGroupPermissionList); - assertEquals(outputVXGroupPermissionList.getClass(),testVXGroupPermissionList.getClass()); - assertEquals(outputVXGroupPermissionList.getTotalCount(),testVXGroupPermissionList.getTotalCount()); - - Mockito.verify(xUserMgr).searchXGroupPermission(testSearchCriteria); - - Mockito.verify(searchUtil).extractCommonCriterias((HttpServletRequest)Mockito.any() ,(List)Mockito.any()); - Mockito.verify(searchUtil).extractString(request, testSearchCriteria, "id", "id",StringUtil.VALIDATION_NAME); - Mockito.verify(searchUtil).extractString(request, testSearchCriteria,"groupPermissionList", "groupId", StringUtil.VALIDATION_NAME); - } - @SuppressWarnings("unchecked") - @Test - public void test93countXGroupPermission() { - - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - SearchCriteria testSearchCriteria=createsearchCriteria(); - - Mockito.when(searchUtil.extractCommonCriterias((HttpServletRequest)Mockito.any() ,(List)Mockito.any())).thenReturn(testSearchCriteria); - - vXLong.setValue(1); - - Mockito.when(xUserMgr.getXGroupPermissionSearchCount(testSearchCriteria)).thenReturn(vXLong); - VXLong testvxLong=xUserRest.countXGroupPermission(request); - Mockito.verify(xUserMgr).getXGroupPermissionSearchCount(testSearchCriteria); - Mockito.verify(searchUtil).extractCommonCriterias((HttpServletRequest)Mockito.any() ,(List)Mockito.any()); - - assertNotNull(testvxLong); - assertEquals(testvxLong.getValue(),vXLong.getValue()); - assertEquals(testvxLong.getClass(),vXLong.getClass()); - - } - @Test - public void test94modifyUserActiveStatus() { - HashMap statusMap= new HashMap(); - statusMap.put(id, 1); - Mockito.doNothing().when(xUserMgr).modifyUserActiveStatus(statusMap); - xUserRest.modifyUserActiveStatus(statusMap); - Mockito.verify(xUserMgr).modifyUserActiveStatus(statusMap); - } - @Test - public void test95setUserRolesByExternalID() { - VXStringList testVXStringList= createVXStringList(); - Mockito.when(xUserMgr.setUserRolesByExternalID(id, testVXStringList.getVXStrings())).thenReturn(testVXStringList); - VXStringList retVXStringList=xUserRest.setUserRolesByExternalID(id, testVXStringList); - Mockito.verify(xUserMgr).setUserRolesByExternalID(id, testVXStringList.getVXStrings()); - - assertNotNull(retVXStringList); - assertEquals(testVXStringList.getTotalCount(), retVXStringList.getTotalCount()); - assertEquals(testVXStringList.getClass(), retVXStringList.getClass()); - } - @Test - public void test96setUserRolesByName() { - VXStringList testVXStringList= createVXStringList(); - Mockito.when(xUserMgr.setUserRolesByName("Admin", testVXStringList.getVXStrings())).thenReturn(testVXStringList); - VXStringList retVXStringList=xUserRest.setUserRolesByName("Admin", testVXStringList); - Mockito.verify(xUserMgr).setUserRolesByName("Admin", testVXStringList.getVXStrings()); - - assertNotNull(retVXStringList); - assertEquals(testVXStringList.getTotalCount(), retVXStringList.getTotalCount()); - assertEquals(testVXStringList.getClass(), retVXStringList.getClass()); - } - @Test - public void test97getUserRolesByExternalID() { - VXStringList testVXStringList=createVXStringList(); - - Mockito.when(xUserMgr.getUserRolesByExternalID(id)).thenReturn(testVXStringList); - VXStringList retVXStringList=xUserRest.getUserRolesByExternalID(id); - Mockito.verify(xUserMgr).getUserRolesByExternalID(id); - assertNotNull(retVXStringList); - assertEquals(testVXStringList.getTotalCount(), retVXStringList.getTotalCount()); - assertEquals(testVXStringList.getClass(), retVXStringList.getClass()); - - } - @Test - public void test98getUserRolesByName() { - - VXStringList testVXStringList=createVXStringList(); - - Mockito.when(xUserMgr.getUserRolesByName("Admin")).thenReturn(testVXStringList); - VXStringList retVXStringList=xUserRest.getUserRolesByName("Admin"); - Mockito.verify(xUserMgr).getUserRolesByName("Admin"); - assertNotNull(retVXStringList); - assertEquals(testVXStringList.getTotalCount(), retVXStringList.getTotalCount()); - assertEquals(testVXStringList.getClass(), retVXStringList.getClass()); - } - @Test - public void test99deleteUsersByUserName() { - - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - String TestforceDeleteStr="true"; - boolean forceDelete = false; - Mockito.when(request.getParameter("forceDelete")).thenReturn(TestforceDeleteStr); - VXString testVXString= new VXString(); - testVXString.setValue("User1"); - VXUser testVXUser= createVXUser(); - VXStringList vxStringList=createVXStringList(); - - Mockito.when(xUserService.getXUserByUserName(testVXString.getValue())).thenReturn(testVXUser); - forceDelete=true; - Mockito.doNothing().when(xUserMgr).deleteXUser(testVXUser.getId(), forceDelete); - xUserRest.deleteUsersByUserName(request,vxStringList); - Mockito.verify(xUserMgr).deleteXUser(testVXUser.getId(),forceDelete); - Mockito.verify(xUserService).getXUserByUserName(testVXString.getValue()); - Mockito.verify(request).getParameter("forceDelete"); - - } - @Test - public void test100deleteUsersByUserNameNull() { - - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - String TestforceDeleteStr="false"; - boolean forceDelete = true; - Mockito.when(request.getParameter("forceDelete")).thenReturn(TestforceDeleteStr); - VXString testVXString= new VXString(); - testVXString.setValue("User1"); - VXUser testVXUser= createVXUser(); - VXStringList vxStringList=createVXStringList(); - - Mockito.when(xUserService.getXUserByUserName(testVXString.getValue())).thenReturn(testVXUser); - forceDelete=false; - Mockito.doNothing().when(xUserMgr).deleteXUser(testVXUser.getId(), forceDelete); - xUserRest.deleteUsersByUserName(request,vxStringList); - Mockito.verify(xUserMgr).deleteXUser(testVXUser.getId(),forceDelete); - Mockito.verify(xUserService).getXUserByUserName(testVXString.getValue()); - Mockito.verify(request).getParameter("forceDelete"); - - } - @Test - public void test101deleteUsersByUserNameNull() { - - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - String TestforceDeleteStr=null; - boolean forceDelete = true; - Mockito.when(request.getParameter("forceDelete")).thenReturn(TestforceDeleteStr); - VXString testVXString= new VXString(); - testVXString.setValue("User1"); - VXUser testVXUser= createVXUser(); - VXStringList vxStringList=createVXStringList(); - - Mockito.when(xUserService.getXUserByUserName(testVXString.getValue())).thenReturn(testVXUser); - forceDelete=false; - Mockito.doNothing().when(xUserMgr).deleteXUser(testVXUser.getId(), forceDelete); - xUserRest.deleteUsersByUserName(request,vxStringList); - Mockito.verify(xUserMgr).deleteXUser(testVXUser.getId(),forceDelete); - Mockito.verify(xUserService).getXUserByUserName(testVXString.getValue()); - Mockito.verify(request).getParameter("forceDelete"); - - } - @Test - public void test102deleteUsersByUserNameSetValueNull() { - - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - String TestforceDeleteStr="false"; - boolean forceDelete = true; - Mockito.when(request.getParameter("forceDelete")).thenReturn(TestforceDeleteStr); - VXString testVXString= new VXString(); - testVXString.setValue("User1"); - VXUser testVXUser= createVXUser(); - VXStringList vxStringList=createVXStringList(); - - Mockito.when(xUserService.getXUserByUserName(testVXString.getValue())).thenReturn(testVXUser); - forceDelete=false; - Mockito.doNothing().when(xUserMgr).deleteXUser(testVXUser.getId(), forceDelete); - xUserRest.deleteUsersByUserName(request,vxStringList); - Mockito.verify(xUserMgr).deleteXUser(testVXUser.getId(),forceDelete); - Mockito.verify(xUserService).getXUserByUserName(testVXString.getValue()); - Mockito.verify(request).getParameter("forceDelete"); - - } - @Test - public void test103deleteUsersByUserNameListNull() { - - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - String TestforceDeleteStr="false"; - Mockito.when(request.getParameter("forceDelete")).thenReturn(TestforceDeleteStr); - VXString testVXString= new VXString(); - testVXString.setValue("User1"); - xUserRest.deleteUsersByUserName(request,null); - Mockito.verify(request).getParameter("forceDelete"); - - } - @Test - public void test104deleteUsersByUserNameListGetListNull() { - - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - String TestforceDeleteStr="false"; - - Mockito.when(request.getParameter("forceDelete")).thenReturn(TestforceDeleteStr); - VXStringList vxStringList=createVXStringList(); - vxStringList.setVXStrings(null); - xUserRest.deleteUsersByUserName(request,vxStringList); - Mockito.verify(request).getParameter("forceDelete"); - - } - @Test - public void test105deleteUsersByUserNameNull() { - - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - String TestforceDeleteStr="true"; - - Mockito.when(request.getParameter("forceDelete")).thenReturn(TestforceDeleteStr); - VXString testVXString= new VXString(); - testVXString.setValue(null); - - VXStringList vxStringList=createVXStringList(); - List testVXStrings=new ArrayList(); - testVXStrings.add(testVXString); - vxStringList.setVXStrings(testVXStrings); - xUserRest.deleteUsersByUserName(request,vxStringList); - Mockito.verify(request).getParameter("forceDelete"); - - } - //////////////////////////////// - @Test - public void test106deleteGroupsByGroupName() { - - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - String TestforceDeleteStr="true"; - boolean forceDelete = false; - Mockito.when(request.getParameter("forceDelete")).thenReturn(TestforceDeleteStr); - VXString testVXString= new VXString(); - testVXString.setValue("testVXGroup"); - VXGroup testVXGroup= createVXGroup(); - VXStringList vxStringList=createVXStringListGroup(); - - Mockito.when(xGroupService.getGroupByGroupName(testVXString.getValue())).thenReturn(testVXGroup); - forceDelete=true; - Mockito.doNothing().when(xUserMgr).deleteXGroup(testVXGroup.getId(), forceDelete); - xUserRest.deleteGroupsByGroupName(request,vxStringList); - Mockito.verify(xUserMgr).deleteXGroup(testVXGroup.getId(),forceDelete); - Mockito.verify(xGroupService).getGroupByGroupName(testVXString.getValue()); - Mockito.verify(request).getParameter("forceDelete"); - - } - @Test - public void test107GroupsByGroupNameNull() { - - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - String TestforceDeleteStr="false"; - boolean forceDelete = true; - Mockito.when(request.getParameter("forceDelete")).thenReturn(TestforceDeleteStr); - VXString testVXString= new VXString(); - testVXString.setValue("testVXGroup"); - VXGroup testVXGroup= createVXGroup(); - VXStringList vxStringList=createVXStringListGroup(); - - Mockito.when(xGroupService.getGroupByGroupName(testVXString.getValue())).thenReturn(testVXGroup); - forceDelete=false; - Mockito.doNothing().when(xUserMgr).deleteXGroup(testVXGroup.getId(), forceDelete); - xUserRest.deleteGroupsByGroupName(request,vxStringList); - Mockito.verify(xUserMgr).deleteXGroup(testVXGroup.getId(),forceDelete); - Mockito.verify(xGroupService).getGroupByGroupName(testVXString.getValue()); - Mockito.verify(request).getParameter("forceDelete"); - - } - @Test - public void test108deleteGroupsByGroupNameNull() { - - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - String TestforceDeleteStr=null; - boolean forceDelete = true; - Mockito.when(request.getParameter("forceDelete")).thenReturn(TestforceDeleteStr); - VXString testVXString= new VXString(); - testVXString.setValue("testVXGroup"); - VXGroup testVXGroup= createVXGroup(); - VXStringList vxStringList=createVXStringListGroup(); - - Mockito.when(xGroupService.getGroupByGroupName(testVXString.getValue())).thenReturn(testVXGroup); - forceDelete=false; - Mockito.doNothing().when(xUserMgr).deleteXGroup(testVXGroup.getId(), forceDelete); - xUserRest.deleteGroupsByGroupName(request,vxStringList); - Mockito.verify(xUserMgr).deleteXGroup(testVXGroup.getId(),forceDelete); - Mockito.verify(xGroupService).getGroupByGroupName(testVXString.getValue()); - Mockito.verify(request).getParameter("forceDelete"); - - } - @Test - public void test109deleteGroupsByGroupNameSetValueNull() { - - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - String TestforceDeleteStr="false"; - boolean forceDelete = true; - Mockito.when(request.getParameter("forceDelete")).thenReturn(TestforceDeleteStr); - VXString testVXString= new VXString(); - testVXString.setValue("testVXGroup"); - VXGroup testVXGroup= createVXGroup(); - VXStringList vxStringList=createVXStringListGroup(); - - Mockito.when(xGroupService.getGroupByGroupName(testVXString.getValue())).thenReturn(testVXGroup); - forceDelete=false; - Mockito.doNothing().when(xUserMgr).deleteXGroup(testVXGroup.getId(), forceDelete); - xUserRest.deleteGroupsByGroupName(request,vxStringList); - Mockito.verify(xUserMgr).deleteXGroup(testVXGroup.getId(),forceDelete); - Mockito.verify(xGroupService).getGroupByGroupName(testVXString.getValue()); - Mockito.verify(request).getParameter("forceDelete"); - - } - @Test - public void test110deleteGroupsByGroupNameListNull() { - - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - String TestforceDeleteStr="false"; - Mockito.when(request.getParameter("forceDelete")).thenReturn(TestforceDeleteStr); - VXString testVXString= new VXString(); - testVXString.setValue("testVXGroup"); - xUserRest.deleteGroupsByGroupName(request,null); - Mockito.verify(request).getParameter("forceDelete"); - - } - @Test - public void test111deleteUsersByUserNameListGetListNull() { - - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - String TestforceDeleteStr="false"; - - Mockito.when(request.getParameter("forceDelete")).thenReturn(TestforceDeleteStr); - VXStringList vxStringList=createVXStringList(); - vxStringList.setVXStrings(null); - xUserRest.deleteGroupsByGroupName(request,vxStringList); - Mockito.verify(request).getParameter("forceDelete"); - - } - @Test - public void test112deleteUsersByUserNameNull() { - - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - String TestforceDeleteStr="true"; - - Mockito.when(request.getParameter("forceDelete")).thenReturn(TestforceDeleteStr); - VXString testVXString= new VXString(); - testVXString.setValue(null); - - VXStringList vxStringList=createVXStringListGroup(); - List testVXStrings=new ArrayList(); - testVXStrings.add(testVXString); - vxStringList.setVXStrings(testVXStrings); - xUserRest.deleteGroupsByGroupName(request,vxStringList); - Mockito.verify(request).getParameter("forceDelete"); - - } - - @SuppressWarnings({ "unchecked", "static-access" }) - @Test - public void test113ErrorWhenRoleUserIsTryingToFetchAnotherUserDetails() { - - destroySession(); - String userLoginID = "testuser"; - Long userId = 8L; - - RangerSecurityContext context = new RangerSecurityContext(); - context.setUserSession(new UserSessionBase()); - RangerContextHolder.setSecurityContext(context); - UserSessionBase currentUserSession = ContextUtil.getCurrentUserSession(); - currentUserSession.setUserAdmin(false); - XXPortalUser xXPortalUser = new XXPortalUser(); - xXPortalUser.setLoginId(userLoginID); - xXPortalUser.setId(userId); - currentUserSession.setXXPortalUser(xXPortalUser); - - VXUser loggedInUser = createVXUser(); - List loggedInUserRole = new ArrayList(); - loggedInUserRole.add(RangerConstants.ROLE_USER); - loggedInUser.setId(8L); - loggedInUser.setName("testuser"); - loggedInUser.setUserRoleList(loggedInUserRole); - - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - SearchCriteria testSearchCriteria=createsearchCriteria(); - testSearchCriteria.addParam("name", "admin"); - - Mockito.when(searchUtil.extractCommonCriterias((HttpServletRequest)Mockito.any(), (List)Mockito.any())).thenReturn(testSearchCriteria); - - Mockito.when(searchUtil.extractCommonCriterias(request, xUserService.sortFields)).thenReturn(testSearchCriteria); - Mockito.when(searchUtil.extractString(request, testSearchCriteria, "emailAddress", "Email Address",null)).thenReturn(""); - Mockito.when(searchUtil.extractInt(request, testSearchCriteria, "userSource", "User Source")).thenReturn(1); - Mockito.when(searchUtil.extractInt(request, testSearchCriteria, "isVisible", "User Visibility")).thenReturn(1); - Mockito.when(searchUtil.extractInt(request, testSearchCriteria, "status", "User Status")).thenReturn(1); - Mockito.when(searchUtil.extractStringList(request, testSearchCriteria, "userRoleList", "User Role List", "userRoleList", null,null)).thenReturn(new ArrayList()); - Mockito.when(searchUtil.extractRoleString(request, testSearchCriteria, "userRole", "Role", null)).thenReturn(""); - Mockito.when(xUserService.getXUserByUserName("testuser")).thenReturn(loggedInUser); - Mockito.when(restErrorUtil.create403RESTException("Logged-In user is not allowed to access requested user data.")).thenThrow(new WebApplicationException()); - thrown.expect(WebApplicationException.class); - - xUserRest.searchXUsers(request, null, null); - } - - @SuppressWarnings({ "unchecked", "static-access" }) - @Test - public void test114RoleUserWillGetOnlyHisOwnUserDetails() { - - destroySession(); - String userLoginID = "testuser"; - Long userId = 8L; - - RangerSecurityContext context = new RangerSecurityContext(); - context.setUserSession(new UserSessionBase()); - RangerContextHolder.setSecurityContext(context); - UserSessionBase currentUserSession = ContextUtil.getCurrentUserSession(); - currentUserSession.setUserAdmin(false); - XXPortalUser xXPortalUser = new XXPortalUser(); - xXPortalUser.setLoginId(userLoginID); - xXPortalUser.setId(userId); - currentUserSession.setXXPortalUser(xXPortalUser); - - VXUser loggedInUser = createVXUser(); - List loggedInUserRole = new ArrayList(); - loggedInUserRole.add(RangerConstants.ROLE_USER); - loggedInUser.setId(8L); - loggedInUser.setName("testuser"); - loggedInUser.setUserRoleList(loggedInUserRole); - - VXUserList expecteUserList = new VXUserList(); - VXUser expectedUser = new VXUser(); - expectedUser.setId(8L); - expectedUser.setName("testuser"); - List userList = new ArrayList(); - userList.add(expectedUser); - expecteUserList.setVXUsers(userList); - - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - SearchCriteria testSearchCriteria=createsearchCriteria(); - - Mockito.when(searchUtil.extractCommonCriterias((HttpServletRequest)Mockito.any(), (List)Mockito.any())).thenReturn(testSearchCriteria); - - Mockito.when(searchUtil.extractCommonCriterias(request, xUserService.sortFields)).thenReturn(testSearchCriteria); - Mockito.when(searchUtil.extractString(request, testSearchCriteria, "emailAddress", "Email Address",null)).thenReturn(""); - Mockito.when(searchUtil.extractInt(request, testSearchCriteria, "userSource", "User Source")).thenReturn(1); - Mockito.when(searchUtil.extractInt(request, testSearchCriteria, "isVisible", "User Visibility")).thenReturn(1); - Mockito.when(searchUtil.extractInt(request, testSearchCriteria, "status", "User Status")).thenReturn(1); - Mockito.when(searchUtil.extractStringList(request, testSearchCriteria, "userRoleList", "User Role List", "userRoleList", null,null)).thenReturn(new ArrayList()); - Mockito.when(searchUtil.extractRoleString(request, testSearchCriteria, "userRole", "Role", null)).thenReturn(""); - Mockito.when(xUserService.getXUserByUserName("testuser")).thenReturn(loggedInUser); - Mockito.when(xUserMgr.searchXUsers(testSearchCriteria)).thenReturn(expecteUserList); - VXUserList gotVXUserList=xUserRest.searchXUsers(request, null, null); - - assertEquals(gotVXUserList.getList().size(), 1); - assertEquals(gotVXUserList.getList().get(0).getId(), expectedUser.getId()); - assertEquals(gotVXUserList.getList().get(0).getName(), expectedUser.getName()); - } - - @Test - public void test115updateXGroupPermissionWithInvalidPermissionId() { - - VXGroupPermission testVXGroupPermission = createVXGroupPermission(); - Mockito.when(restErrorUtil.createRESTException(Mockito.anyInt(), Mockito.anyString(), Mockito.anyBoolean())).thenThrow(new WebApplicationException()); - thrown.expect(WebApplicationException.class); - VXGroupPermission retVXGroupPermission=xUserRest.updateXGroupPermission(-1L, testVXGroupPermission); - Mockito.verify(xUserMgr).updateXGroupPermission(testVXGroupPermission); - Mockito.verify(xUserMgr).checkAdminAccess(); - assertNotNull(retVXGroupPermission); - assertEquals(retVXGroupPermission.getId(), testVXGroupPermission.getId()); - assertEquals(retVXGroupPermission.getClass(), testVXGroupPermission.getClass()); - - } - - @Test - public void test116updateXGroupPermissionWithPermissionIdIsNull() { - - VXGroupPermission testVXGroupPermission = createVXGroupPermission(); - Long testVXGroupPermissionId = testVXGroupPermission.getId(); - testVXGroupPermission.setId(null); - Mockito.doNothing().when(xUserMgr).checkAdminAccess(); - Mockito.when(xUserMgr.updateXGroupPermission(testVXGroupPermission)).thenReturn(testVXGroupPermission); - VXGroupPermission retVXGroupPermission=xUserRest.updateXGroupPermission(testVXGroupPermissionId, testVXGroupPermission); - Mockito.verify(xUserMgr).updateXGroupPermission(testVXGroupPermission); - Mockito.verify(xUserMgr).checkAdminAccess(); - assertNotNull(retVXGroupPermission); - assertEquals(retVXGroupPermission.getId(), testVXGroupPermission.getId()); - assertEquals(retVXGroupPermission.getClass(), testVXGroupPermission.getClass()); - - } - - @After - public void destroySession() { - RangerSecurityContext context = new RangerSecurityContext(); - context.setUserSession(null); - RangerContextHolder.setSecurityContext(context); - } - - private HashMap creategroupVisibilityMap() - { - HashMap groupVisibilityMap=new HashMap(); - groupVisibilityMap.put(id, 1); - return groupVisibilityMap; - } - private SearchCriteria createsearchCriteria(){ - SearchCriteria testsearchCriteria = new SearchCriteria(); - testsearchCriteria.setStartIndex(0); - testsearchCriteria.setMaxRows(Integer.MAX_VALUE); - testsearchCriteria.setSortBy("id"); - testsearchCriteria.setSortType("asc"); - testsearchCriteria.setGetCount(true); - testsearchCriteria.setOwnerId(null); - testsearchCriteria.setGetChildren(false); - testsearchCriteria.setDistinct(false); - - return testsearchCriteria; - } - private VXGroupList createxGroupList() { - - VXGroupList testVXGroupList= new VXGroupList(); - VXGroup VXGroup1= createVXGroup(); - List vXGroups = new ArrayList(); - vXGroups.add(VXGroup1); - testVXGroupList.setVXGroups(vXGroups); - testVXGroupList.setStartIndex(0); - testVXGroupList.setTotalCount(1); - - return testVXGroupList; - } - private VXUser createVXUser() { - VXUser testVXUser= new VXUser(); - Collectionc = new ArrayList(); - testVXUser.setId(id); - testVXUser.setCreateDate(new Date()); - testVXUser.setUpdateDate(new Date()); - testVXUser.setOwner("Admin"); - testVXUser.setUpdatedBy("Admin"); - testVXUser.setName("User1"); - testVXUser.setFirstName("FnameUser1"); - testVXUser.setLastName("LnameUser1"); - testVXUser.setPassword("User1"); - testVXUser.setGroupIdList(null); - testVXUser.setGroupNameList(null); - testVXUser.setStatus(1); - testVXUser.setIsVisible(1); - testVXUser.setUserSource(0); - c.add("ROLE_USER"); - testVXUser.setUserRoleList(c); - - return testVXUser; - - } - private VXGroupUser createVXGroupUser(){ - VXGroupUser testVXGroupUser= new VXGroupUser(); - testVXGroupUser.setId(id); - testVXGroupUser.setCreateDate(new Date()); - testVXGroupUser.setUpdateDate(new Date()); - testVXGroupUser.setOwner("Admin"); - testVXGroupUser.setUpdatedBy("Admin"); - testVXGroupUser.setName("finance"); - testVXGroupUser.setParentGroupId(id); - testVXGroupUser.setUserId(id); - return testVXGroupUser; - } - - private VXPermMap testcreateXPermMap(){ - VXPermMap testVXPermMap= new VXPermMap(); - testVXPermMap.setCreateDate(new Date()); - testVXPermMap.setGroupId(id); - testVXPermMap.setGroupName("testGroup"); - testVXPermMap.setId(id); - testVXPermMap.setOwner("Admin"); - testVXPermMap.setPermGroup("testPermGroup"); - testVXPermMap.setPermType(1); - testVXPermMap.setResourceId(id); - testVXPermMap.setUpdateDate(new Date()); - testVXPermMap.setUpdatedBy("Admin"); - testVXPermMap.setUserId(id); - testVXPermMap.setUserName("testUser"); - testVXPermMap.setPermFor(1); - - return testVXPermMap; - } - private VXAuditMap createVXAuditMapObj() { - VXAuditMap testVXAuditMap=new VXAuditMap(); - testVXAuditMap.setAuditType(1); - testVXAuditMap.setCreateDate(new Date()); - testVXAuditMap.setGroupId(id); - testVXAuditMap.setId(id); - testVXAuditMap.setResourceId(id); - testVXAuditMap.setUpdateDate(new Date()); - testVXAuditMap.setOwner("Admin"); - testVXAuditMap.setUpdatedBy("Admin"); - testVXAuditMap.setUserId(id); - return testVXAuditMap; - } - private VXResource createVXResource(){ - VXResource testVXResource= new VXResource(); - testVXResource.setAssetId(id); - testVXResource.setAssetName("AdminAsset"); - testVXResource.setAssetType(1); - testVXResource.setCreateDate(new Date()); - testVXResource.setOwner("Admin"); - testVXResource.setUpdateDate(new Date()); - testVXResource.setUpdatedBy("Admin"); - testVXResource.setParentId(id); - testVXResource.setName("User"); - - return testVXResource; - } - private VXGroup createVXGroup() { - VXGroup testVXGroup= new VXGroup(); - testVXGroup.setName("testVXGroup"); - testVXGroup.setCreateDate(new Date()); - testVXGroup.setUpdateDate(new Date()); - testVXGroup.setUpdatedBy("Admin"); - testVXGroup.setOwner("Admin"); - testVXGroup.setId(id); - testVXGroup.setGroupType(1); - testVXGroup.setCredStoreId(1L); - testVXGroup.setGroupSource(1); - testVXGroup.setIsVisible(1); - return testVXGroup; - } - private VXAuthSession createVXAuthSession() { - VXAuthSession testVXAuthSession = new VXAuthSession(); - testVXAuthSession.setAuthProvider(1); - testVXAuthSession.setAuthStatus(1); - testVXAuthSession.setAuthTime(new Date()); - testVXAuthSession.setCityName("Mumbai"); - testVXAuthSession.setCountryName("India"); - testVXAuthSession.setCreateDate(new Date()); - testVXAuthSession.setDeviceType(1); - testVXAuthSession.setEmailAddress("email@EXAMPLE.COM"); - testVXAuthSession.setFamilyScreenName("testfamilyScreenName"); - testVXAuthSession.setFirstName("testAuthSessionName"); - testVXAuthSession.setId(id); - testVXAuthSession.setLoginId("Admin"); - testVXAuthSession.setOwner("Admin"); - testVXAuthSession.setPublicScreenName("Admin"); - testVXAuthSession.setUpdatedBy("Admin"); - testVXAuthSession.setUpdateDate(new Date()); - testVXAuthSession.setUserId(id); - testVXAuthSession.setStateName("Maharashtra"); - return testVXAuthSession; - } - private VXUserPermission createVXUserPermission() { - - VXUserPermission testVXUserPermission= new VXUserPermission(); - - testVXUserPermission.setCreateDate(new Date()); - testVXUserPermission.setId(id); - testVXUserPermission.setIsAllowed(1); - testVXUserPermission.setModuleId(id); - testVXUserPermission.setModuleName("testModule"); - testVXUserPermission.setOwner("Admin"); - testVXUserPermission.setUpdateDate(new Date()); - testVXUserPermission.setUpdatedBy("Admin"); - testVXUserPermission.setUserId(id); - testVXUserPermission.setUserName("testVXUser"); - - return testVXUserPermission; - - } - private VXGroupPermission createVXGroupPermission() { - VXGroupPermission testVXGroupPermission = new VXGroupPermission(); - - testVXGroupPermission.setCreateDate(new Date()); - testVXGroupPermission.setGroupId(id); - testVXGroupPermission.setGroupName("testVXGroup"); - testVXGroupPermission.setId(id); - testVXGroupPermission.setIsAllowed(1); - testVXGroupPermission.setModuleId(id); - testVXGroupPermission.setModuleName("testModule"); - testVXGroupPermission.setOwner("Admin"); - testVXGroupPermission.setUpdateDate(new Date()); - testVXGroupPermission.setUpdatedBy("Admin"); - - return testVXGroupPermission; - - } - private VXModuleDef createVXModuleDef() { - VXModuleDef testVXModuleDef= new VXModuleDef(); - testVXModuleDef.setAddedById(id); - testVXModuleDef.setCreateDate(new Date()); - testVXModuleDef.setCreateTime(new Date()); - - VXGroupPermission testVXGroupPermission= createVXGroupPermission(); - List groupPermList= new ArrayList(); - groupPermList.add(testVXGroupPermission); - testVXModuleDef.setGroupPermList(groupPermList); - - testVXModuleDef.setId(id); - testVXModuleDef.setModule("testModule"); - testVXModuleDef.setOwner("Admin"); - testVXModuleDef.setUpdateDate(new Date()); - testVXModuleDef.setUpdatedBy("Admin"); - testVXModuleDef.setUpdatedById(id); - testVXModuleDef.setUpdateTime(new Date()); - testVXModuleDef.setUrl("testUrrl"); - - List< VXUserPermission> userPermList= new ArrayList(); - VXUserPermission testVXUserPermission= createVXUserPermission(); - userPermList.add(testVXUserPermission); - testVXModuleDef.setUserPermList(userPermList); - - return testVXModuleDef; - } - private VXStringList createVXStringList() { - VXStringList testVXStringList= new VXStringList(); - VXString testVXString= new VXString(); - testVXString.setValue("User1"); - List testVXStrings=new ArrayList(); - - testVXStrings.add(testVXString); - - testVXStringList.setVXStrings(testVXStrings); - testVXStringList.setResultSize(1); - testVXStringList.setPageSize(1); - testVXStringList.setSortBy("Id"); - testVXStringList.setStartIndex(1); - testVXStringList.setTotalCount(1); - return testVXStringList; - } - private VXStringList createVXStringListGroup() { - VXStringList testVXStringList= new VXStringList(); - VXString testVXString= new VXString(); - testVXString.setValue("testVXGroup"); - List testVXStrings=new ArrayList(); - - testVXStrings.add(testVXString); - - testVXStringList.setVXStrings(testVXStrings); - testVXStringList.setResultSize(1); - testVXStringList.setPageSize(1); - testVXStringList.setSortBy("Id"); - testVXStringList.setStartIndex(1); - testVXStringList.setTotalCount(1); - return testVXStringList; - } + @Rule + public ExpectedException thrown = ExpectedException.none(); + + @InjectMocks + XUserREST xUserRest = new XUserREST(); + Long id = 1L; + VXUser vxUser = createVXUser(); + @Mock XUserMgr xUserMgr; + @Mock VXGroup vxGroup; + @Mock SearchCriteria searchCriteria; + @Mock XGroupService xGroupService; + @Mock SearchUtil searchUtil; + @Mock StringUtil stringUtil; + @Mock VXLong vXLong; + @Mock HttpServletRequest request; + @Mock VXUser vXUser1; + @Mock VXUserGroupInfo vXUserGroupInfo; + @Mock RangerBizUtil bizUtil; + @Mock XUserService xUserService; + @Mock VXUserList vXUserList; + @Mock VXGroupUser vXGroupUser; + @Mock XGroupUserService xGroupUserService; + @Mock VXGroupUserList vXGroupUserList; + @Mock XGroupGroupService xGroupGroupService; + @Mock VXPermMap vXPermMap; + @Mock RESTErrorUtil restErrorUtil; + @Mock WebApplicationException webApplicationException; + @Mock XResourceService xResourceService; + @Mock VXDataObject vxDataObject; + @Mock AppConstants appConstants; + @Mock RangerConstants rangerConstants; + @Mock VXResource vxResource; + @Mock VXResponse vxResponse; + @Mock XXResource xxResource; + @Mock XXAuditMap xxAuditMap; + @Mock XAuditMapService xAuditMapService; + @Mock XPermMapService xPermMapService; + @Mock XXAsset xxAsset; + @Mock RangerDaoManager rangerDaoManager; + @Mock XXPermMap xxPermMap; + @Mock Response response; + @Mock VXPermMapList vXPermMapList; + @Mock VXAuditMap vXAuditMap; + @Mock VXAuditMapList vXAuditMapList; + @Mock AuthSessionService authSessionService; + @Mock SessionMgr sessionMgr; + @Mock VXAuthSessionList vXAuthSessionList; + @Mock VXModuleDef vXModuleDef; + @Mock VXUserPermission vXUserPermission; + @Mock VXUserPermissionList vXUserPermissionList; + @Mock VXGroupPermission vXGroupPermission; + @Mock XModuleDefService xModuleDefService; + @Mock VXModuleDefList vxModuleDefList; + @Mock XUserPermissionService xUserPermissionService; + @Mock VXGroupPermissionList vXGroupPermissionList; + @Mock XGroupPermissionService xGroupPermissionService; + @Mock VXStringList vXStringList; + @Mock VXString vXString; + @Mock XXGroupDao xXGroupDao; + @Mock XXGroup xXGroup; + @Mock XXGroupGroup xXGroupGroup; + @Mock XXGroupPermission xXGroupPermission; + @Mock XXGroupPermissionDao xXGroupPermissionDao; + @Mock XXPolicyDao xXPolicyDao; + @Mock XXPolicy xXPolicy; + @Mock XXGroupUserDao xXGroupUserDao; + @Mock XXUserDao xXUserDao; + @Mock XXUser xXUser; + @Mock XXPermMapDao xXPermMapDao; + @Mock XXResourceDao xXResourceDao; + @Mock XXAuditMapDao xXAuditMapDao; + @Mock RangerPolicy rangerPolicy; + @Mock RangerPolicyItem rangerPolicyItem; + @Mock RangerDataMaskPolicyItem rangerDataMaskPolicyItem; + @Mock RangerRowFilterPolicyItem rangerRowFilterPolicyItem; + + @Test + public void test1getXGroup() { + VXGroup compareTestVXGroup = createVXGroup(); + + Mockito.when(xUserMgr.getXGroup(id)).thenReturn(compareTestVXGroup); + VXGroup retVxGroup = xUserRest.getXGroup(id); + + assertNotNull(retVxGroup); + assertEquals(compareTestVXGroup.getId(), retVxGroup.getId()); + assertEquals(compareTestVXGroup.getName(), retVxGroup.getName()); + Mockito.verify(xUserMgr).getXGroup(id); + } + + @Test + public void test2secureGetXGroup() { + VXGroup compareTestVXGroup = createVXGroup(); + + Mockito.when(xUserMgr.getXGroup(id)).thenReturn(compareTestVXGroup); + VXGroup retVxGroup = xUserRest.secureGetXGroup(id); + + assertNotNull(retVxGroup); + assertEquals(compareTestVXGroup.getId(), retVxGroup.getId()); + assertEquals(compareTestVXGroup.getName(), retVxGroup.getName()); + Mockito.verify(xUserMgr).getXGroup(id); + } + + @Test + public void test3createXGroup() { + VXGroup compareTestVXGroup = createVXGroup(); + + Mockito.when(xUserMgr.createXGroupWithoutLogin(compareTestVXGroup)).thenReturn(compareTestVXGroup); + VXGroup retVxGroup = xUserRest.createXGroup(compareTestVXGroup); + + assertNotNull(retVxGroup); + assertEquals(compareTestVXGroup.getId(), retVxGroup.getId()); + assertEquals(compareTestVXGroup.getName(), retVxGroup.getName()); + Mockito.verify(xUserMgr).createXGroupWithoutLogin(compareTestVXGroup); + } + + @Test + public void test4secureCreateXGroup() { + VXGroup compareTestVXGroup = createVXGroup(); + + Mockito.when(xUserMgr.createXGroup(compareTestVXGroup)).thenReturn(compareTestVXGroup); + VXGroup retVxGroup = xUserRest.secureCreateXGroup(compareTestVXGroup); + + assertNotNull(retVxGroup); + assertEquals(compareTestVXGroup.getId(), retVxGroup.getId()); + assertEquals(compareTestVXGroup.getName(), retVxGroup.getName()); + Mockito.verify(xUserMgr).createXGroup(compareTestVXGroup); + } + + @Test + public void test5updateXGroup() { + VXGroup compareTestVXGroup = createVXGroup(); + + Mockito.when(xUserMgr.updateXGroup(compareTestVXGroup)).thenReturn(compareTestVXGroup); + VXGroup retVxGroup = xUserRest.updateXGroup(compareTestVXGroup); + + assertNotNull(retVxGroup); + assertEquals(compareTestVXGroup.getId(), retVxGroup.getId()); + assertEquals(compareTestVXGroup.getName(), retVxGroup.getName()); + Mockito.verify(xUserMgr).updateXGroup(compareTestVXGroup); + } + + @Test + public void test6secureUpdateXGroup() { + VXGroup compareTestVXGroup = createVXGroup(); + + Mockito.when(xUserMgr.updateXGroup(compareTestVXGroup)).thenReturn(compareTestVXGroup); + VXGroup retVxGroup = xUserRest.secureUpdateXGroup(compareTestVXGroup); + + assertNotNull(retVxGroup); + assertEquals(compareTestVXGroup.getId(), retVxGroup.getId()); + assertEquals(compareTestVXGroup.getName(), retVxGroup.getName()); + Mockito.verify(xUserMgr).updateXGroup(compareTestVXGroup); + } + + @Test + public void test7modifyGroupsVisibility() { + HashMap groupVisibilityMap = creategroupVisibilityMap(); + xUserRest.modifyGroupsVisibility(groupVisibilityMap); + + Mockito.verify(xUserMgr).modifyGroupsVisibility(groupVisibilityMap); + } + + @Test + public void test8deleteXGroupTrue() { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + String testForceDeleteStr = "true"; + Mockito.when(request.getParameter("forceDelete")).thenReturn(testForceDeleteStr); + + Mockito.doNothing().when(xUserMgr).deleteXGroup(id, true); + xUserRest.deleteXGroup(id, request); + Mockito.verify(xUserMgr).deleteXGroup(id, true); + Mockito.verify(request).getParameter("forceDelete"); + } + + @Test + public void test9deleteXGroupFalse() { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + String testForceDeleteStr = "false"; + Mockito.when(request.getParameter("forceDelete")).thenReturn(testForceDeleteStr); + + Mockito.doNothing().when(xUserMgr).deleteXGroup(id, false); + xUserRest.deleteXGroup(id, request); + Mockito.verify(xUserMgr).deleteXGroup(id, false); + Mockito.verify(request).getParameter("forceDelete"); + } + + @Test + public void test10deleteXGroupNotEmpty() { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + Mockito.when(request.getParameter("forceDelete")).thenReturn(null); + + Mockito.doNothing().when(xUserMgr).deleteXGroup(id, false); + xUserRest.deleteXGroup(id, request); + Mockito.verify(xUserMgr).deleteXGroup(id, false); + Mockito.verify(request).getParameter("forceDelete"); + } + + @Test + public void test11searchXGroups() { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + SearchCriteria testSearchCriteria = createsearchCriteria(); + Mockito.when(searchUtil.extractCommonCriterias(Mockito.any(), Mockito.any())).thenReturn(testSearchCriteria); + + Mockito.when(searchUtil.extractString(request, testSearchCriteria, "name", "group name", null)).thenReturn(""); + Mockito.when(searchUtil.extractInt(request, testSearchCriteria, "isVisible", "Group Visibility")).thenReturn(1); + Mockito.when(searchUtil.extractInt(request, testSearchCriteria, "groupSource", "group source")).thenReturn(1); + VXGroupList testvXGroupList = createXGroupList(); + Mockito.when(xUserMgr.searchXGroups(testSearchCriteria)).thenReturn(testvXGroupList); + VXGroupList outputvXGroupList = xUserRest.searchXGroups(request); + + Mockito.verify(xUserMgr).searchXGroups(testSearchCriteria); + Mockito.verify(searchUtil).extractCommonCriterias(Mockito.any(), Mockito.any()); + Mockito.verify(searchUtil).extractString(request, testSearchCriteria, "name", "group name", null); + Mockito.verify(searchUtil).extractInt(request, testSearchCriteria, "isVisible", "Group Visibility"); + Mockito.verify(searchUtil).extractInt(request, testSearchCriteria, "groupSource", "group source"); + assertNotNull(outputvXGroupList); + assertEquals(outputvXGroupList.getTotalCount(), testvXGroupList.getTotalCount()); + assertEquals(outputvXGroupList.getClass(), testvXGroupList.getClass()); + } + + @Test + public void test12countXGroups() { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + SearchCriteria testSearchCriteria = createsearchCriteria(); + + Mockito.when(searchUtil.extractCommonCriterias(Mockito.any(), Mockito.any())).thenReturn(testSearchCriteria); + + vXLong.setValue(1); + + Mockito.when(xUserMgr.getXGroupSearchCount(testSearchCriteria)).thenReturn(vXLong); + VXLong testvxLong = xUserRest.countXGroups(request); + Mockito.verify(xUserMgr).getXGroupSearchCount(testSearchCriteria); + Mockito.verify(searchUtil).extractCommonCriterias(Mockito.any(), Mockito.any()); + + assertNotNull(testvxLong); + assertEquals(testvxLong.getValue(), vXLong.getValue()); + assertEquals(testvxLong.getClass(), vXLong.getClass()); + } + + @Test + public void test13getXUser() { + Mockito.when(xUserMgr.getXUser(id)).thenReturn(vxUser); + VXUser gotVXUser = xUserRest.getXUser(id); + Mockito.verify(xUserMgr).getXUser(id); + + assertNotNull(gotVXUser); + assertEquals(vxUser.getId(), gotVXUser.getId()); + assertEquals(vxUser.getName(), gotVXUser.getName()); + } + + @Test + public void test14secureGetXUser() { + Mockito.when(xUserMgr.getXUser(id)).thenReturn(vxUser); + VXUser gotVXUser = xUserRest.secureGetXUser(id); + Mockito.verify(xUserMgr).getXUser(id); + + assertNotNull(gotVXUser); + assertEquals(vxUser.getId(), gotVXUser.getId()); + assertEquals(vxUser.getName(), gotVXUser.getName()); + } + + @Test + public void test15createXUser() { + Mockito.when(xUserMgr.createXUserWithOutLogin(vxUser)).thenReturn(vxUser); + VXUser gotVXUser = xUserRest.createXUser(vxUser); + Mockito.verify(xUserMgr).createXUserWithOutLogin(vxUser); + + assertNotNull(gotVXUser); + assertEquals(vxUser.getId(), gotVXUser.getId()); + assertEquals(vxUser.getName(), gotVXUser.getName()); + } + + @Test + public void test16createXUserGroupFromMap() { + VXUserGroupInfo vXUserGroupInfo = new VXUserGroupInfo(); + vXUserGroupInfo.setXuserInfo(vxUser); + + Mockito.when(xUserMgr.createXUserGroupFromMap(vXUserGroupInfo)).thenReturn(vXUserGroupInfo); + VXUserGroupInfo gotVXUserGroupInfo = xUserRest.createXUserGroupFromMap(vXUserGroupInfo); + Mockito.verify(xUserMgr).createXUserGroupFromMap(vXUserGroupInfo); + + assertNotNull(gotVXUserGroupInfo); + assertEquals(vXUserGroupInfo.getId(), gotVXUserGroupInfo.getId()); + assertEquals(vXUserGroupInfo.getOwner(), gotVXUserGroupInfo.getOwner()); + } + + @Test + public void test17secureCreateXUser() { + Boolean val = true; + Mockito.when(bizUtil.checkUserAccessible(vxUser)).thenReturn(val); + Mockito.when(xUserMgr.createXUser(vxUser)).thenReturn(vxUser); + VXUser gotVXUser = xUserRest.secureCreateXUser(vxUser); + Mockito.verify(xUserMgr).createXUser(vxUser); + Mockito.verify(bizUtil).checkUserAccessible(vxUser); + assertNotNull(gotVXUser); + assertEquals(vxUser.getId(), gotVXUser.getId()); + assertEquals(vxUser.getName(), gotVXUser.getName()); + } + + @Test + public void test18updateXUser() { + Mockito.when(xUserMgr.updateXUser(vxUser)).thenReturn(vxUser); + VXUser gotVXUser = xUserRest.updateXUser(vxUser); + Mockito.verify(xUserMgr).updateXUser(vxUser); + assertNotNull(gotVXUser); + assertEquals(vxUser.getId(), gotVXUser.getId()); + assertEquals(vxUser.getName(), gotVXUser.getName()); + } + + @Test + public void test19secureUpdateXUser() { + Boolean val = true; + Mockito.when(bizUtil.checkUserAccessible(vxUser)).thenReturn(val); + Mockito.when(xUserMgr.updateXUser(vxUser)).thenReturn(vxUser); + VXUser gotVXUser = xUserRest.secureUpdateXUser(vxUser); + Mockito.verify(xUserMgr).updateXUser(vxUser); + Mockito.verify(bizUtil).checkUserAccessible(vxUser); + + assertNotNull(gotVXUser); + assertEquals(vxUser.getId(), gotVXUser.getId()); + assertEquals(vxUser.getName(), gotVXUser.getName()); + } + + @Test + public void test20modifyUserVisibility() { + HashMap testVisibilityMap = new HashMap<>(); + testVisibilityMap.put(1L, 0); + Mockito.doNothing().when(xUserMgr).modifyUserVisibility(testVisibilityMap); + xUserRest.modifyUserVisibility(testVisibilityMap); + Mockito.verify(xUserMgr).modifyUserVisibility(testVisibilityMap); + } + + @Test + public void test21deleteXUser() { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + String testForceDeleteStr = "true"; + Mockito.when(request.getParameter("forceDelete")).thenReturn(testForceDeleteStr); + Mockito.doNothing().when(xUserMgr).deleteXUser(id, true); + xUserRest.deleteXUser(id, request); + Mockito.verify(xUserMgr).deleteXUser(id, true); + Mockito.verify(request).getParameter("forceDelete"); + } + + @Test + public void test22deleteXUserFalse() { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + String testForceDeleteStr = "false"; + Mockito.when(request.getParameter("forceDelete")).thenReturn(testForceDeleteStr); + + Mockito.doNothing().when(xUserMgr).deleteXUser(id, false); + xUserRest.deleteXUser(id, request); + Mockito.verify(xUserMgr).deleteXUser(id, false); + Mockito.verify(request).getParameter("forceDelete"); + } + + @Test + public void test23deleteXUserNotEmpty() { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + Mockito.when(request.getParameter("forceDelete")).thenReturn(null); + + Mockito.doNothing().when(xUserMgr).deleteXUser(id, false); + xUserRest.deleteXUser(id, request); + Mockito.verify(xUserMgr).deleteXUser(id, false); + Mockito.verify(request).getParameter("forceDelete"); + } + + @Test + public void test24searchXUsers() { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + SearchCriteria testSearchCriteria = createsearchCriteria(); + + Mockito.when(searchUtil.extractCommonCriterias(Mockito.any(), Mockito.any())).thenReturn(testSearchCriteria); + + Mockito.when(searchUtil.extractString(request, testSearchCriteria, "name", "User name", null)).thenReturn(""); + Mockito.when(searchUtil.extractString(request, testSearchCriteria, "emailAddress", "Email Address", null)).thenReturn(""); + Mockito.when(searchUtil.extractInt(request, testSearchCriteria, "userSource", "User Source")).thenReturn(1); + Mockito.when(searchUtil.extractInt(request, testSearchCriteria, "isVisible", "User Visibility")).thenReturn(1); + Mockito.when(searchUtil.extractInt(request, testSearchCriteria, "status", "User Status")).thenReturn(1); + Mockito.when(searchUtil.extractStringList(request, testSearchCriteria, "userRoleList", "User Role List", "userRoleList", null, null)).thenReturn(new ArrayList<>()); + Mockito.when(searchUtil.extractRoleString(request, testSearchCriteria, "userRole", "Role", null)).thenReturn(""); + + List vXUsersList = new ArrayList<>(); + vXUsersList.add(vxUser); + VXUserList testVXUserList = new VXUserList(); + testVXUserList.setVXUsers(vXUsersList); + + Mockito.when(xUserMgr.searchXUsers(testSearchCriteria)).thenReturn(testVXUserList); + VXUserList gotVXUserList = xUserRest.searchXUsers(request, null, null); + + Mockito.verify(xUserMgr).searchXUsers(testSearchCriteria); + Mockito.verify(searchUtil).extractCommonCriterias(Mockito.any(), Mockito.any()); + + Mockito.verify(searchUtil).extractString(request, testSearchCriteria, "name", "User name", null); + Mockito.verify(searchUtil).extractString(request, testSearchCriteria, "emailAddress", "Email Address", null); + Mockito.verify(searchUtil).extractInt(request, testSearchCriteria, "userSource", "User Source"); + Mockito.verify(searchUtil).extractInt(request, testSearchCriteria, "isVisible", "User Visibility"); + Mockito.verify(searchUtil).extractInt(request, testSearchCriteria, "status", "User Status"); + Mockito.verify(searchUtil).extractStringList(request, testSearchCriteria, "userRoleList", "User Role List", "userRoleList", null, null); + Mockito.verify(searchUtil).extractRoleString(request, testSearchCriteria, "userRole", "Role", null); + assertNotNull(gotVXUserList); + assertEquals(testVXUserList.getTotalCount(), gotVXUserList.getTotalCount()); + assertEquals(testVXUserList.getClass(), gotVXUserList.getClass()); + } + + @Test + public void test25countXUsers() { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + SearchCriteria testSearchCriteria = createsearchCriteria(); + + Mockito.when(searchUtil.extractCommonCriterias(Mockito.any(), Mockito.any())).thenReturn(testSearchCriteria); + + vXLong.setValue(1); + + Mockito.when(xUserMgr.getXUserSearchCount(testSearchCriteria)).thenReturn(vXLong); + VXLong testvxLong = xUserRest.countXUsers(request); + Mockito.verify(xUserMgr).getXUserSearchCount(testSearchCriteria); + Mockito.verify(searchUtil).extractCommonCriterias(Mockito.any(), Mockito.any()); + + assertNotNull(testvxLong); + assertEquals(testvxLong.getValue(), vXLong.getValue()); + assertEquals(testvxLong.getClass(), vXLong.getClass()); + } + + @Test + public void test26getXGroupUser() { + VXGroupUser testVXGroupUser = createVXGroupUser(); + + Mockito.when(xUserMgr.getXGroupUser(id)).thenReturn(testVXGroupUser); + VXGroupUser retVxGroupUser = xUserRest.getXGroupUser(id); + + assertNotNull(retVxGroupUser); + assertEquals(testVXGroupUser.getClass(), retVxGroupUser.getClass()); + assertEquals(testVXGroupUser.getId(), retVxGroupUser.getId()); + Mockito.verify(xUserMgr).getXGroupUser(id); + } + + @Test + public void test27createXGroupUser() { + VXGroupUser testVXGroupUser = createVXGroupUser(); + + Mockito.when(xUserMgr.createXGroupUser(testVXGroupUser)).thenReturn(testVXGroupUser); + VXGroupUser retVxGroupUser = xUserRest.createXGroupUser(testVXGroupUser); + + assertNotNull(retVxGroupUser); + assertEquals(testVXGroupUser.getClass(), retVxGroupUser.getClass()); + assertEquals(testVXGroupUser.getId(), retVxGroupUser.getId()); + Mockito.verify(xUserMgr).createXGroupUser(testVXGroupUser); + } + + @Test + public void test28updateXGroupUser() { + VXGroupUser testVXGroupUser = createVXGroupUser(); + + Mockito.when(xUserMgr.updateXGroupUser(testVXGroupUser)).thenReturn(testVXGroupUser); + VXGroupUser retVxGroupUser = xUserRest.updateXGroupUser(testVXGroupUser); + + assertNotNull(retVxGroupUser); + assertEquals(testVXGroupUser.getClass(), retVxGroupUser.getClass()); + assertEquals(testVXGroupUser.getId(), retVxGroupUser.getId()); + Mockito.verify(xUserMgr).updateXGroupUser(testVXGroupUser); + } + + @Test + public void test29deleteXGroupUser() { + boolean force = true; + + Mockito.doNothing().when(xUserMgr).deleteXGroupUser(id, force); + xUserRest.deleteXGroupUser(id, request); + Mockito.verify(xUserMgr).deleteXGroupUser(id, force); + } + + @Test + public void test30searchXGroupUsers() { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + SearchCriteria testSearchCriteria = createsearchCriteria(); + + Mockito.when(searchUtil.extractCommonCriterias(Mockito.any(), Mockito.any())).thenReturn(testSearchCriteria); + + VXGroupUserList testVXGroupUserList = new VXGroupUserList(); + VXGroupUser vXGroupUser = createVXGroupUser(); + List vXGroupUsers = new ArrayList<>(); + vXGroupUsers.add(vXGroupUser); + testVXGroupUserList.setVXGroupUsers(vXGroupUsers); + Mockito.when(xUserMgr.searchXGroupUsers(testSearchCriteria)).thenReturn(testVXGroupUserList); + VXGroupUserList outputvXGroupList = xUserRest.searchXGroupUsers(request); + + Mockito.verify(xUserMgr).searchXGroupUsers(testSearchCriteria); + Mockito.verify(searchUtil).extractCommonCriterias(Mockito.any(), Mockito.any()); + + assertNotNull(outputvXGroupList); + assertEquals(outputvXGroupList.getClass(), testVXGroupUserList.getClass()); + assertEquals(outputvXGroupList.getResultSize(), testVXGroupUserList.getResultSize()); + } + + @Test + public void test31countXGroupUserst() { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + SearchCriteria testSearchCriteria = createsearchCriteria(); + + Mockito.when(searchUtil.extractCommonCriterias(Mockito.any(), Mockito.any())).thenReturn(testSearchCriteria); + + vXLong.setValue(1); + + Mockito.when(xUserMgr.getXGroupUserSearchCount(testSearchCriteria)).thenReturn(vXLong); + VXLong testvxLong = xUserRest.countXGroupUsers(request); + Mockito.verify(xUserMgr).getXGroupUserSearchCount(testSearchCriteria); + Mockito.verify(searchUtil).extractCommonCriterias(Mockito.any(), Mockito.any()); + + assertNotNull(testvxLong); + assertEquals(testvxLong.getValue(), vXLong.getValue()); + assertEquals(testvxLong.getClass(), vXLong.getClass()); + } + + @Test + public void test38getXPermMapVXResourceNull() { + VXPermMap permMap = testcreateXPermMap(); + + Mockito.when(xUserMgr.getXPermMap(id)).thenReturn(permMap); + + Mockito.when(restErrorUtil.createRESTException(Mockito.anyString(), Mockito.any())).thenThrow(new WebApplicationException()); + thrown.expect(WebApplicationException.class); + + VXPermMap retVxGroup = xUserRest.getXPermMap(id); + + Mockito.verify(xUserMgr).getXPermMap(id); + Mockito.verify(xResourceService).readResource(null); + Mockito.verify(restErrorUtil).createRESTException(Mockito.anyString(), Mockito.any()); + assertEquals(permMap.getId(), retVxGroup.getId()); + assertEquals(permMap.getClass(), retVxGroup.getClass()); + assertNotNull(retVxGroup); + } + + @Test + public void test39getXPermMapNotNull() { + VXPermMap permMap = testcreateXPermMap(); + + Mockito.when(xUserMgr.getXPermMap(id)).thenReturn(permMap); + VXResource testVxResource = new VXResource(); + Mockito.when(xResourceService.readResource(id)).thenReturn(testVxResource); + + VXPermMap retVxGroup = xUserRest.getXPermMap(id); + assertEquals(permMap.getId(), retVxGroup.getId()); + assertEquals(permMap.getClass(), retVxGroup.getClass()); + assertNotNull(retVxGroup); + Mockito.verify(xUserMgr).getXPermMap(id); + Mockito.verify(xResourceService).readResource(id); + } + + @Test + public void test40getXPermMapNull() { + Mockito.when(xUserMgr.getXPermMap(id)).thenReturn(null); + VXPermMap retVxGroup = xUserRest.getXPermMap(id); + assertNull(retVxGroup); + Mockito.verify(xUserMgr).getXPermMap(id); + } + + @Test + public void test41createXPermMap() { + VXPermMap permMap = testcreateXPermMap(); + permMap.setResourceId(null); + Mockito.when(xResourceService.readResource(permMap.getResourceId())).thenReturn(null); + Mockito.when(restErrorUtil.createRESTException(Mockito.anyString(), Mockito.any())).thenThrow(new WebApplicationException()); + thrown.expect(WebApplicationException.class); + + VXPermMap retVxGroup = xUserRest.createXPermMap(permMap); + + assertEquals(permMap.getId(), retVxGroup.getId()); + assertEquals(permMap.getClass(), retVxGroup.getClass()); + assertNotNull(retVxGroup); + + Mockito.verify(xUserMgr).createXPermMap(permMap); + Mockito.verify(xResourceService).readResource(permMap.getResourceId()); + Mockito.verify(restErrorUtil).createRESTException(Mockito.anyString(), Mockito.any()); + } + + @Test + public void test42createXPermMapNull() { + Mockito.when(xUserMgr.createXPermMap(null)).thenReturn(null); + VXPermMap retVxGroup = xUserRest.createXPermMap(null); + Mockito.verify(xUserMgr).createXPermMap(null); + assertNull(retVxGroup); + } + + @Test + public void test43createXPermMapNullVXResource() { + VXPermMap permMap = testcreateXPermMap(); + permMap.setResourceId(null); + Mockito.when(xUserMgr.createXPermMap(permMap)).thenReturn(permMap); + VXResource testVxResource = new VXResource(); + Mockito.when(xResourceService.readResource(permMap.getResourceId())).thenReturn(testVxResource); + + VXPermMap retVxGroup = xUserRest.createXPermMap(permMap); + + assertEquals(permMap.getId(), retVxGroup.getId()); + assertEquals(permMap.getClass(), retVxGroup.getClass()); + assertNotNull(retVxGroup); + + Mockito.verify(xUserMgr).createXPermMap(permMap); + Mockito.verify(xResourceService).readResource(permMap.getResourceId()); + } + + @Test + public void test44updateXPermMap() { + VXPermMap permMap = testcreateXPermMap(); + + VXResource testVxResource = new VXResource(); + Mockito.when(xResourceService.readResource(id)).thenReturn(testVxResource); + Mockito.when(xUserMgr.updateXPermMap(permMap)).thenReturn(permMap); + VXPermMap retVxGroup = xUserRest.updateXPermMap(permMap); + + assertEquals(permMap.getId(), retVxGroup.getId()); + assertEquals(permMap.getClass(), retVxGroup.getClass()); + assertNotNull(retVxGroup); + + Mockito.verify(xUserMgr).updateXPermMap(permMap); + Mockito.verify(xResourceService).readResource(permMap.getResourceId()); + } + + @Test + public void test45updateXPermMap() { + VXPermMap vXPermMap = null; + VXPermMap retVxGroup = xUserRest.updateXPermMap(vXPermMap); + assertNull(retVxGroup); + } + + @Test + public void test46updateXPermMap() { + VXPermMap permMap = testcreateXPermMap(); + + Mockito.when(xResourceService.readResource(permMap.getResourceId())).thenReturn(null); + Mockito.when(restErrorUtil.createRESTException(Mockito.anyString())).thenThrow(new WebApplicationException()); + thrown.expect(WebApplicationException.class); + + VXPermMap retVxGroup = xUserRest.updateXPermMap(permMap); + + assertEquals(permMap.getId(), retVxGroup.getId()); + assertEquals(permMap.getClass(), retVxGroup.getClass()); + assertNotNull(retVxGroup); + + Mockito.verify(xUserMgr).updateXPermMap(permMap); + Mockito.verify(xResourceService).readResource(permMap.getResourceId()); + Mockito.verify(restErrorUtil).createRESTException(Mockito.anyString()); + } + + @Test + public void test47deleteXPermMap() { + boolean forceDelete = false; + Mockito.doNothing().when(xUserMgr).deleteXPermMap(id, forceDelete); + xUserRest.deleteXPermMap(id, request); + Mockito.verify(xUserMgr).deleteXPermMap(id, forceDelete); + } + + @SuppressWarnings("unchecked") + @Test + public void test48searchXPermMaps() { + VXPermMap permMap = testcreateXPermMap(); + + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + SearchCriteria testSearchCriteria = createsearchCriteria(); + Mockito.when(searchUtil.extractCommonCriterias(Mockito.any(), Mockito.any())).thenReturn(testSearchCriteria); + + List vXPermMaps = new ArrayList<>(); + vXPermMaps.add(permMap); + VXPermMapList testvXGroupList = new VXPermMapList(); + testvXGroupList.setTotalCount(1); + testvXGroupList.setVXPermMaps(vXPermMaps); + Mockito.when(xUserMgr.searchXPermMaps(testSearchCriteria)).thenReturn(testvXGroupList); + VXPermMapList outputvXGroupList = xUserRest.searchXPermMaps(request); + + Mockito.verify(xUserMgr).searchXPermMaps(testSearchCriteria); + Mockito.verify(searchUtil).extractCommonCriterias(Mockito.any(), Mockito.any()); + + assertNotNull(outputvXGroupList); + assertEquals(outputvXGroupList.getClass(), testvXGroupList.getClass()); + assertEquals(outputvXGroupList.getTotalCount(), testvXGroupList.getTotalCount()); + } + + @Test + public void test49countXPermMaps() { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + SearchCriteria testSearchCriteria = createsearchCriteria(); + + Mockito.when(searchUtil.extractCommonCriterias(Mockito.any(), Mockito.any())).thenReturn(testSearchCriteria); + + vXLong.setValue(1); + Mockito.when(xUserMgr.getXPermMapSearchCount(testSearchCriteria)).thenReturn(vXLong); + VXLong testvxLong = xUserRest.countXPermMaps(request); + Mockito.verify(xUserMgr).getXPermMapSearchCount(testSearchCriteria); + Mockito.verify(searchUtil).extractCommonCriterias(Mockito.any(), Mockito.any()); + + assertNotNull(testvxLong); + } + + @Test + public void test50getXAuditMapVXAuditMapNull() { + VXAuditMap testvXAuditMap = createVXAuditMapObj(); + Mockito.when(xUserMgr.getXAuditMap(testvXAuditMap.getResourceId())).thenReturn(testvXAuditMap); + + Mockito.when(restErrorUtil.createRESTException(Mockito.anyString(), Mockito.any())).thenThrow(new WebApplicationException()); + thrown.expect(WebApplicationException.class); + + VXAuditMap retVXAuditMap = xUserRest.getXAuditMap(testvXAuditMap.getResourceId()); + + assertEquals(testvXAuditMap.getId(), retVXAuditMap.getId()); + assertEquals(testvXAuditMap.getClass(), retVXAuditMap.getClass()); + assertNotNull(retVXAuditMap); + + Mockito.verify(xUserMgr).getXAuditMap(testvXAuditMap.getResourceId()); + Mockito.verify(xResourceService).readResource(null); + Mockito.verify(restErrorUtil.createRESTException(Mockito.anyString(), Mockito.any())); + } + + @Test + public void test51getXAuditMapNull() { + VXAuditMap testvXAuditMap = createVXAuditMapObj(); + Mockito.when(xUserMgr.getXAuditMap(testvXAuditMap.getResourceId())).thenReturn(null); + VXAuditMap retVXAuditMap = xUserRest.getXAuditMap(testvXAuditMap.getResourceId()); + + assertNull(retVXAuditMap); + + Mockito.verify(xUserMgr).getXAuditMap(testvXAuditMap.getResourceId()); + } + + @Test + public void test52getXAuditMap() { + VXAuditMap testvXAuditMap = createVXAuditMapObj(); + + Mockito.when(xUserMgr.getXAuditMap(id)).thenReturn(testvXAuditMap); + VXResource testVxResource = createVXResource(); + Mockito.when(xResourceService.readResource(testvXAuditMap.getResourceId())).thenReturn(testVxResource); + + VXAuditMap retVXAuditMap = xUserRest.getXAuditMap(id); + + assertEquals(testvXAuditMap.getId(), retVXAuditMap.getId()); + assertEquals(testvXAuditMap.getClass(), retVXAuditMap.getClass()); + assertNotNull(retVXAuditMap); + + Mockito.verify(xUserMgr).getXAuditMap(id); + Mockito.verify(xResourceService).readResource(testvXAuditMap.getResourceId()); + } + + @Test + public void test53createXAuditMap() { + VXAuditMap testvXAuditMap = createVXAuditMapObj(); + + Mockito.when(xUserMgr.createXAuditMap(testvXAuditMap)).thenReturn(testvXAuditMap); + VXResource testVxResource = createVXResource(); + Mockito.when(xResourceService.readResource(testvXAuditMap.getResourceId())).thenReturn(testVxResource); + VXAuditMap retvXAuditMap = xUserRest.createXAuditMap(testvXAuditMap); + assertEquals(testvXAuditMap.getId(), retvXAuditMap.getId()); + assertEquals(testvXAuditMap.getClass(), retvXAuditMap.getClass()); + assertNotNull(retvXAuditMap); + + Mockito.verify(xUserMgr).createXAuditMap(testvXAuditMap); + Mockito.verify(xResourceService).readResource(testvXAuditMap.getResourceId()); + } + + @Test + public void test54createXAuditMapVxResourceNull() { + VXAuditMap testvXAuditMap = createVXAuditMapObj(); + testvXAuditMap.setResourceId(null); + + Mockito.when(xResourceService.readResource(testvXAuditMap.getResourceId())).thenReturn(null); + + Mockito.when(restErrorUtil.createRESTException(Mockito.anyString(), Mockito.any())).thenThrow(new WebApplicationException()); + thrown.expect(WebApplicationException.class); + + VXAuditMap retvXAuditMap = xUserRest.createXAuditMap(testvXAuditMap); + assertEquals(testvXAuditMap.getId(), retvXAuditMap.getId()); + assertEquals(testvXAuditMap.getClass(), retvXAuditMap.getClass()); + assertNotNull(retvXAuditMap); + + Mockito.verify(xUserMgr).createXAuditMap(testvXAuditMap); + Mockito.verify(xResourceService).readResource(testvXAuditMap.getResourceId()); + Mockito.verify(restErrorUtil.createRESTException(Mockito.anyString(), Mockito.any())); + } + + @Test + public void test55createXAuditMapNull() { + VXAuditMap testvXAuditMap = createVXAuditMapObj(); + testvXAuditMap.setResourceId(null); + VXAuditMap retvXAuditMap = xUserRest.createXAuditMap(null); + assertNull(retvXAuditMap); + Mockito.verify(xUserMgr).createXAuditMap(null); + } + + @Test + public void test56updateXAuditMap() { + VXAuditMap testvXAuditMap = createVXAuditMapObj(); + testvXAuditMap.setResourceId(id); + Mockito.when(xUserMgr.updateXAuditMap(testvXAuditMap)).thenReturn(testvXAuditMap); + VXResource testVxResource = createVXResource(); + Mockito.when(xResourceService.readResource(testvXAuditMap.getResourceId())).thenReturn(testVxResource); + + VXAuditMap retvXAuditMap = xUserRest.updateXAuditMap(testvXAuditMap); + assertEquals(testvXAuditMap.getId(), retvXAuditMap.getId()); + assertEquals(testvXAuditMap.getClass(), retvXAuditMap.getClass()); + assertNotNull(retvXAuditMap); + + Mockito.verify(xUserMgr).updateXAuditMap(testvXAuditMap); + Mockito.verify(xResourceService).readResource(testvXAuditMap.getResourceId()); + } + + @Test + public void test57updateXAuditMapNull() { + VXAuditMap testvXAuditMap = createVXAuditMapObj(); + + Mockito.when(restErrorUtil.createRESTException(Mockito.anyString(), Mockito.any())).thenThrow(new WebApplicationException()); + thrown.expect(WebApplicationException.class); + VXAuditMap retvXAuditMap = xUserRest.updateXAuditMap(testvXAuditMap); + assertNull(retvXAuditMap); + Mockito.verify(xUserMgr).updateXAuditMap(testvXAuditMap); + Mockito.verify(xResourceService).readResource(null); + Mockito.verify(restErrorUtil.createRESTException(Mockito.anyString(), Mockito.any())); + } + + @Test + public void test58updateXAuditMapVXResourceNull() { + VXAuditMap vXAuditMap = null; + VXAuditMap retvXAuditMap = xUserRest.updateXAuditMap(vXAuditMap); + assertNull(retvXAuditMap); + } + + @Test + public void test59deleteXAuditMap() { + boolean forceDelete = false; + Mockito.doNothing().when(xUserMgr).deleteXAuditMap(id, forceDelete); + xUserRest.deleteXAuditMap(id, request); + Mockito.verify(xUserMgr).deleteXAuditMap(id, forceDelete); + } + + @Test + public void test60searchXAuditMaps() { + VXAuditMap testvXAuditMap = createVXAuditMapObj(); + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + SearchCriteria testSearchCriteria = createsearchCriteria(); + Mockito.when(searchUtil.extractCommonCriterias(Mockito.any(), Mockito.any())).thenReturn(testSearchCriteria); + + List testVXAuditMaps = new ArrayList<>(); + testVXAuditMaps.add(testvXAuditMap); + VXAuditMapList testVXAuditMapList = new VXAuditMapList(); + testVXAuditMapList.setVXAuditMaps(testVXAuditMaps); + Mockito.when(xUserMgr.searchXAuditMaps(testSearchCriteria)).thenReturn(testVXAuditMapList); + VXAuditMapList outputVXAuditMapList = xUserRest.searchXAuditMaps(request); + + Mockito.verify(xUserMgr).searchXAuditMaps(testSearchCriteria); + Mockito.verify(searchUtil).extractCommonCriterias(Mockito.any(), Mockito.any()); + + assertNotNull(outputVXAuditMapList); + assertEquals(outputVXAuditMapList.getClass(), testVXAuditMapList.getClass()); + assertEquals(outputVXAuditMapList.getResultSize(), testVXAuditMapList.getResultSize()); + } + + @Test + public void test61countXAuditMaps() { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + SearchCriteria testSearchCriteria = createsearchCriteria(); + + Mockito.when(searchUtil.extractCommonCriterias(Mockito.any(), Mockito.any())).thenReturn(testSearchCriteria); + + vXLong.setValue(1); + Mockito.when(xUserMgr.getXAuditMapSearchCount(testSearchCriteria)).thenReturn(vXLong); + VXLong testvxLong = xUserRest.countXAuditMaps(request); + Mockito.verify(xUserMgr).getXAuditMapSearchCount(testSearchCriteria); + Mockito.verify(searchUtil).extractCommonCriterias(Mockito.any(), Mockito.any()); + assertEquals(testvxLong.getClass(), vXLong.getClass()); + assertEquals(testvxLong.getValue(), vXLong.getValue()); + assertNotNull(testvxLong); + } + + @Test + public void test62getXUserByUserName() { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + + VXUser compareTestVxUser = createVXUser(); + + Mockito.when(xUserMgr.getXUserByUserName("User1")).thenReturn(compareTestVxUser); + VXUser retVXUser = xUserRest.getXUserByUserName(request, "User1"); + + assertNotNull(retVXUser); + assertEquals(compareTestVxUser.getClass(), retVXUser.getClass()); + assertEquals(compareTestVxUser.getId(), retVXUser.getId()); + Mockito.verify(xUserMgr).getXUserByUserName("User1"); + } + + @Test + public void test63getXGroupByGroupName() { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + + VXGroup compareTestVXGroup = createVXGroup(); + + Mockito.when(xGroupService.getGroupByGroupName(compareTestVXGroup.getName())).thenReturn(compareTestVXGroup); + + VXGroup retVxGroup = xUserRest.getXGroupByGroupName(request, compareTestVXGroup.getName()); + + assertNotNull(retVxGroup); + assertEquals(compareTestVXGroup.getClass(), compareTestVXGroup.getClass()); + assertEquals(compareTestVXGroup.getId(), compareTestVXGroup.getId()); + Mockito.verify(xGroupService).getGroupByGroupName(compareTestVXGroup.getName()); + } + + @Test + public void test64deleteXUserByUserName() { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + String testForceDeleteStr = "true"; + Mockito.when(request.getParameter("forceDelete")).thenReturn(testForceDeleteStr); + VXUser testUser = createVXUser(); + Mockito.when(xUserService.getXUserByUserName(testUser.getName())).thenReturn(testUser); + + Mockito.doNothing().when(xUserMgr).deleteXUser(testUser.getId(), true); + xUserRest.deleteXUserByUserName(testUser.getName(), request); + Mockito.verify(xUserMgr).deleteXUser(testUser.getId(), true); + Mockito.verify(xUserService).getXUserByUserName(testUser.getName()); + Mockito.verify(request).getParameter("forceDelete"); + } + + @Test + public void test65deleteXUserByUserNameTrue() { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + String testForceDeleteStr = "false"; + Mockito.when(request.getParameter("forceDelete")).thenReturn(testForceDeleteStr); + VXUser testUser = createVXUser(); + Mockito.when(xUserService.getXUserByUserName(testUser.getName())).thenReturn(testUser); + + Mockito.doNothing().when(xUserMgr).deleteXUser(testUser.getId(), false); + xUserRest.deleteXUserByUserName(testUser.getName(), request); + Mockito.verify(xUserMgr).deleteXUser(testUser.getId(), false); + Mockito.verify(xUserService).getXUserByUserName(testUser.getName()); + Mockito.verify(request).getParameter("forceDelete"); + } + + @Test + public void test66deleteXUserByUserNameNull() { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + String testForceDeleteStr = null; + Mockito.when(request.getParameter("forceDelete")).thenReturn(testForceDeleteStr); + VXUser testUser = createVXUser(); + Mockito.when(xUserService.getXUserByUserName(testUser.getName())).thenReturn(testUser); + + Mockito.doNothing().when(xUserMgr).deleteXUser(testUser.getId(), false); + xUserRest.deleteXUserByUserName(testUser.getName(), request); + Mockito.verify(xUserMgr).deleteXUser(testUser.getId(), false); + Mockito.verify(xUserService).getXUserByUserName(testUser.getName()); + Mockito.verify(request).getParameter("forceDelete"); + } + + @Test + public void test67deleteXGroupByGroupName() { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + String testForceDeleteStr = "false"; + Mockito.when(request.getParameter("forceDelete")).thenReturn(testForceDeleteStr); + VXGroup testVXGroup = createVXGroup(); + Mockito.when(xGroupService.getGroupByGroupName(testVXGroup.getName())).thenReturn(testVXGroup); + + Mockito.doNothing().when(xUserMgr).deleteXGroup(testVXGroup.getId(), false); + xUserRest.deleteXGroupByGroupName(testVXGroup.getName(), request); + Mockito.verify(xUserMgr).deleteXGroup(testVXGroup.getId(), false); + Mockito.verify(xGroupService).getGroupByGroupName(testVXGroup.getName()); + Mockito.verify(request).getParameter("forceDelete"); + } + + @Test + public void test68deleteXGroupByGroupNameNull() { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + Mockito.when(request.getParameter("forceDelete")).thenReturn(null); + VXGroup testVXGroup = createVXGroup(); + Mockito.when(xGroupService.getGroupByGroupName(testVXGroup.getName())).thenReturn(testVXGroup); + + Mockito.doNothing().when(xUserMgr).deleteXGroup(testVXGroup.getId(), false); + xUserRest.deleteXGroupByGroupName(testVXGroup.getName(), request); + Mockito.verify(xUserMgr).deleteXGroup(testVXGroup.getId(), false); + Mockito.verify(xGroupService).getGroupByGroupName(testVXGroup.getName()); + Mockito.verify(request).getParameter("forceDelete"); + } + + @Test + public void test69deleteXGroupByGroupNameFalse() { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + String testForceDeleteStr = "true"; + Mockito.when(request.getParameter("forceDelete")).thenReturn(testForceDeleteStr); + VXGroup testVXGroup = createVXGroup(); + Mockito.when(xGroupService.getGroupByGroupName(testVXGroup.getName())).thenReturn(testVXGroup); + + Mockito.doNothing().when(xUserMgr).deleteXGroup(testVXGroup.getId(), true); + xUserRest.deleteXGroupByGroupName(testVXGroup.getName(), request); + Mockito.verify(xUserMgr).deleteXGroup(testVXGroup.getId(), true); + Mockito.verify(xGroupService).getGroupByGroupName(testVXGroup.getName()); + Mockito.verify(request).getParameter("forceDelete"); + } + + @Test + public void test70deleteXGroupAndXUser() { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + + VXGroup testVXGroup = createVXGroup(); + VXUser testVXuser = createVXUser(); + + Mockito.doNothing().when(xUserMgr).deleteXGroupAndXUser(testVXGroup.getName(), testVXuser.getName()); + xUserRest.deleteXGroupAndXUser(testVXGroup.getName(), testVXuser.getName(), request); + Mockito.verify(xUserMgr).deleteXGroupAndXUser(testVXGroup.getName(), testVXuser.getName()); + } + + @Test + public void test71getXUserGroups() { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + + VXGroupList groupList = createXGroupList(); + Mockito.when(xUserMgr.getXUserGroups(id)).thenReturn(groupList); + VXGroupList retVxGroupList = xUserRest.getXUserGroups(request, id); + + assertNotNull(retVxGroupList); + assertEquals(groupList.getClass(), retVxGroupList.getClass()); + assertEquals(groupList.getResultSize(), retVxGroupList.getResultSize()); + Mockito.verify(xUserMgr).getXUserGroups(id); + } + + @Test + public void test72getXGroupUsers() { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + + VXGroupList groupList = createXGroupList(); + Mockito.when(xUserMgr.getXUserGroups(id)).thenReturn(groupList); + VXGroupList retVxGroupList = xUserRest.getXUserGroups(request, id); + + assertNotNull(retVxGroupList); + assertEquals(groupList.getClass(), retVxGroupList.getClass()); + assertEquals(groupList.getResultSize(), retVxGroupList.getResultSize()); + Mockito.verify(xUserMgr).getXUserGroups(id); + } + + @Test + public void test73getXGroupUsers() { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + SearchCriteria testSearchCriteria = createsearchCriteria(); + testSearchCriteria.addParam("xGroupId", id); + + Mockito.when(searchUtil.extractCommonCriterias(Mockito.any(), Mockito.any())).thenReturn(testSearchCriteria); + + VXUser testVXUser = createVXUser(); + VXUserList testVXUserList = new VXUserList(); + List testVXUsers = new ArrayList<>(); + testVXUsers.add(testVXUser); + testVXUserList.setVXUsers(testVXUsers); + testVXUserList.setStartIndex(1); + testVXUserList.setTotalCount(1); + Mockito.when(xUserMgr.getXGroupUsers(testSearchCriteria)).thenReturn(testVXUserList); + VXUserList retVxGroupList = xUserRest.getXGroupUsers(request, id); + + assertNotNull(retVxGroupList); + assertEquals(testVXUserList.getTotalCount(), retVxGroupList.getTotalCount()); + assertEquals(testVXUserList.getStartIndex(), retVxGroupList.getStartIndex()); + Mockito.verify(xUserMgr).getXGroupUsers(testSearchCriteria); + } + + @SuppressWarnings("unchecked") + @Test + public void test74getAuthSessions() { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + SearchCriteria testSearchCriteria = createsearchCriteria(); + + Mockito.when(searchUtil.extractCommonCriterias(Mockito.any(), Mockito.any())).thenReturn(testSearchCriteria); + + Mockito.when(searchUtil.extractLong(request, testSearchCriteria, "id", "Auth Session Id")).thenReturn(1L); + Mockito.when(searchUtil.extractLong(request, testSearchCriteria, "userId", "User Id")).thenReturn(1L); + Mockito.when(searchUtil.extractInt(request, testSearchCriteria, "authStatus", "Auth Status")).thenReturn(1); + Mockito.when(searchUtil.extractInt(request, testSearchCriteria, "deviceType", "Device Type")).thenReturn(1); + Mockito.when(searchUtil.extractString(request, testSearchCriteria, "firstName", "User First Name", StringUtil.VALIDATION_NAME)).thenReturn(""); + Mockito.when(searchUtil.extractString(request, testSearchCriteria, "lastName", "User Last Name", StringUtil.VALIDATION_NAME)).thenReturn(""); + Mockito.when(searchUtil.extractString(request, testSearchCriteria, "requestUserAgent", "User Agent", StringUtil.VALIDATION_TEXT)).thenReturn(""); + Mockito.when(searchUtil.extractString(request, testSearchCriteria, "requestIP", "Request IP Address", StringUtil.VALIDATION_IP_ADDRESS)).thenReturn(""); + Mockito.when(searchUtil.extractString(request, testSearchCriteria, "loginId", "Login ID", StringUtil.VALIDATION_TEXT)).thenReturn(""); + + VXAuthSessionList testVXAuthSessionList = new VXAuthSessionList(); + testVXAuthSessionList.setTotalCount(1); + testVXAuthSessionList.setStartIndex(1); + VXAuthSession testVXAuthSession = createVXAuthSession(); + List testvXAuthSessions = new ArrayList<>(); + testvXAuthSessions.add(testVXAuthSession); + + testVXAuthSessionList.setVXAuthSessions(testvXAuthSessions); + Mockito.when(sessionMgr.searchAuthSessions(testSearchCriteria)).thenReturn(testVXAuthSessionList); + VXAuthSessionList outputvXGroupList = xUserRest.getAuthSessions(request); + + Mockito.verify(sessionMgr).searchAuthSessions(testSearchCriteria); + Mockito.verify(searchUtil).extractCommonCriterias(Mockito.any(), Mockito.any()); + Mockito.verify(searchUtil).extractLong(request, testSearchCriteria, "id", "Auth Session Id"); + Mockito.verify(searchUtil).extractLong(request, testSearchCriteria, "userId", "User Id"); + Mockito.verify(searchUtil).extractInt(request, testSearchCriteria, "authStatus", "Auth Status"); + Mockito.verify(searchUtil).extractInt(request, testSearchCriteria, "authType", "Login Type"); + Mockito.verify(searchUtil).extractInt(request, testSearchCriteria, "deviceType", "Device Type"); + Mockito.verify(searchUtil).extractString(request, testSearchCriteria, "firstName", "User First Name", StringUtil.VALIDATION_NAME); + Mockito.verify(searchUtil).extractString(request, testSearchCriteria, "lastName", "User Last Name", StringUtil.VALIDATION_NAME); + Mockito.verify(searchUtil).extractString(request, testSearchCriteria, "requestUserAgent", "User Agent", StringUtil.VALIDATION_TEXT); + Mockito.verify(searchUtil).extractString(request, testSearchCriteria, "requestIP", "Request IP Address", StringUtil.VALIDATION_IP_ADDRESS); + Mockito.verify(searchUtil).extractString(request, testSearchCriteria, "loginId", "Login ID", StringUtil.VALIDATION_TEXT); + Mockito.verify(searchUtil).extractDate(request, testSearchCriteria, "startDate", "Start Date", null); + Mockito.verify(searchUtil).extractDate(request, testSearchCriteria, "endDate", "End Date", null); + assertNotNull(outputvXGroupList); + assertEquals(outputvXGroupList.getStartIndex(), testVXAuthSessionList.getStartIndex()); + assertEquals(outputvXGroupList.getTotalCount(), testVXAuthSessionList.getTotalCount()); + } + + @Test + public void test75getAuthSession() { + String authSessionId = "testauthSessionId"; + VXAuthSession testVXAuthSession = createVXAuthSession(); + + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + Mockito.when(request.getParameter("extSessionId")).thenReturn(authSessionId); + Mockito.when(sessionMgr.getAuthSessionBySessionId(authSessionId)).thenReturn(testVXAuthSession); + VXAuthSession retVXAuthSession = xUserRest.getAuthSession(request); + Mockito.verify(sessionMgr).getAuthSessionBySessionId(authSessionId); + Mockito.verify(request).getParameter("extSessionId"); + assertEquals(testVXAuthSession.getId(), retVXAuthSession.getId()); + assertEquals(testVXAuthSession.getClass(), retVXAuthSession.getClass()); + assertNotNull(retVXAuthSession); + } + + @Test + public void test76createXModuleDefPermission() { + VXModuleDef testVXModuleDef = createVXModuleDef(); + + Mockito.doNothing().when(xUserMgr).checkAdminAccess(); + + Mockito.when(xUserMgr.createXModuleDefPermission(testVXModuleDef)).thenReturn(testVXModuleDef); + VXModuleDef retVxModuleDef = xUserRest.createXModuleDefPermission(testVXModuleDef); + + assertNotNull(retVxModuleDef); + assertEquals(testVXModuleDef.getId(), retVxModuleDef.getId()); + assertEquals(testVXModuleDef.getOwner(), retVxModuleDef.getOwner()); + Mockito.verify(xUserMgr).createXModuleDefPermission(testVXModuleDef); + Mockito.verify(xUserMgr).checkAdminAccess(); + } + + @Test + public void test77getXModuleDefPermission() { + VXModuleDef testVXModuleDef = createVXModuleDef(); + Mockito.when(xUserMgr.getXModuleDefPermission(testVXModuleDef.getId())).thenReturn(testVXModuleDef); + VXModuleDef retVxModuleDef = xUserRest.getXModuleDefPermission(testVXModuleDef.getId()); + + assertNotNull(retVxModuleDef); + assertEquals(testVXModuleDef.getId(), retVxModuleDef.getId()); + assertEquals(testVXModuleDef.getOwner(), retVxModuleDef.getOwner()); + + Mockito.verify(xUserMgr).getXModuleDefPermission(testVXModuleDef.getId()); + } + + @Test + public void test78updateXModuleDefPermission() { + VXModuleDef testVXModuleDef = createVXModuleDef(); + + Mockito.doNothing().when(xUserMgr).checkAdminAccess(); + + Mockito.when(xUserMgr.updateXModuleDefPermission(testVXModuleDef)).thenReturn(testVXModuleDef); + VXModuleDef retVxModuleDef = xUserRest.updateXModuleDefPermission(testVXModuleDef); + + assertNotNull(retVxModuleDef); + assertEquals(testVXModuleDef.getId(), retVxModuleDef.getId()); + assertEquals(testVXModuleDef.getOwner(), retVxModuleDef.getOwner()); + + Mockito.verify(xUserMgr).updateXModuleDefPermission(testVXModuleDef); + Mockito.verify(xUserMgr).checkAdminAccess(); + } + + @Test + public void test79deleteXModuleDefPermission() { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + + boolean forceDelete = true; + Mockito.doNothing().when(xUserMgr).checkAdminAccess(); + Mockito.doNothing().when(xUserMgr).deleteXModuleDefPermission(id, forceDelete); + xUserRest.deleteXModuleDefPermission(id, request); + Mockito.verify(xUserMgr).deleteXModuleDefPermission(id, forceDelete); + Mockito.verify(xUserMgr).checkAdminAccess(); + } + + @SuppressWarnings("unchecked") + @Test + public void test80searchXModuleDef() { + VXModuleDefList testVXModuleDefList = new VXModuleDefList(); + VXModuleDef vXModuleDef = createVXModuleDef(); + List vxModuleDefs = new ArrayList<>(); + vxModuleDefs.add(vXModuleDef); + testVXModuleDefList.setvXModuleDef(vxModuleDefs); + testVXModuleDefList.setTotalCount(1); + testVXModuleDefList.setStartIndex(1); + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + SearchCriteria testSearchCriteria = createsearchCriteria(); + + Mockito.when(searchUtil.extractCommonCriterias(Mockito.any(), Mockito.any())).thenReturn(testSearchCriteria); + Mockito.when(searchUtil.extractString(request, testSearchCriteria, "module", "modulename", null)).thenReturn(""); + Mockito.when(searchUtil.extractString(request, testSearchCriteria, "moduleDefList", "id", null)).thenReturn(""); + Mockito.when(searchUtil.extractString(request, testSearchCriteria, "userName", "userName", null)).thenReturn(""); + Mockito.when(searchUtil.extractString(request, testSearchCriteria, "groupName", "groupName", null)).thenReturn(""); + + Mockito.when(xUserMgr.searchXModuleDef(testSearchCriteria)).thenReturn(testVXModuleDefList); + VXModuleDefList outputVXModuleDefList = xUserRest.searchXModuleDef(request); + assertNotNull(outputVXModuleDefList); + assertEquals(outputVXModuleDefList.getTotalCount(), testVXModuleDefList.getTotalCount()); + assertEquals(outputVXModuleDefList.getStartIndex(), testVXModuleDefList.getStartIndex()); + + Mockito.verify(xUserMgr).searchXModuleDef(testSearchCriteria); + Mockito.verify(searchUtil).extractCommonCriterias(Mockito.any(), Mockito.any()); + Mockito.verify(searchUtil).extractString(request, testSearchCriteria, "module", "modulename", null); + Mockito.verify(searchUtil).extractString(request, testSearchCriteria, "moduleDefList", "id", null); + Mockito.verify(searchUtil).extractString(request, testSearchCriteria, "userName", "userName", null); + Mockito.verify(searchUtil).extractString(request, testSearchCriteria, "groupName", "groupName", null); + } + + @Test + public void test81countXModuleDef() { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + SearchCriteria testSearchCriteria = createsearchCriteria(); + + Mockito.when(searchUtil.extractCommonCriterias(Mockito.any(), Mockito.any())).thenReturn(testSearchCriteria); + + vXLong.setValue(1); + + Mockito.when(xUserMgr.getXModuleDefSearchCount(testSearchCriteria)).thenReturn(vXLong); + VXLong testvxLong = xUserRest.countXModuleDef(request); + Mockito.verify(xUserMgr).getXModuleDefSearchCount(testSearchCriteria); + Mockito.verify(searchUtil).extractCommonCriterias(Mockito.any(), Mockito.any()); + + assertNotNull(testvxLong); + assertEquals(testvxLong.getValue(), vXLong.getValue()); + assertEquals(testvxLong.getClass(), vXLong.getClass()); + } + + @Test + public void test82createXUserPermission() { + VXUserPermission testvXUserPermission = createVXUserPermission(); + + Mockito.doNothing().when(xUserMgr).checkAdminAccess(); + Mockito.when(xUserMgr.createXUserPermission(testvXUserPermission)).thenReturn(testvXUserPermission); + VXUserPermission retVXUserPermission = xUserRest.createXUserPermission(testvXUserPermission); + Mockito.verify(xUserMgr).createXUserPermission(testvXUserPermission); + Mockito.verify(xUserMgr).checkAdminAccess(); + assertNotNull(retVXUserPermission); + assertEquals(retVXUserPermission.getId(), testvXUserPermission.getId()); + assertEquals(retVXUserPermission.getUserName(), testvXUserPermission.getUserName()); + } + + @Test + public void test83getXUserPermission() { + VXUserPermission testVXUserPermission = createVXUserPermission(); + Mockito.when(xUserMgr.getXUserPermission(testVXUserPermission.getId())).thenReturn(testVXUserPermission); + VXUserPermission retVXUserPermission = xUserRest.getXUserPermission(testVXUserPermission.getId()); + Mockito.verify(xUserMgr).getXUserPermission(id); + assertNotNull(retVXUserPermission); + assertEquals(retVXUserPermission.getId(), testVXUserPermission.getId()); + assertEquals(retVXUserPermission.getUserName(), testVXUserPermission.getUserName()); + } + + @Test + public void test84updateXUserPermission() { + VXUserPermission testvXUserPermission = createVXUserPermission(); + Mockito.doNothing().when(xUserMgr).checkAdminAccess(); + Mockito.when(xUserMgr.updateXUserPermission(testvXUserPermission)).thenReturn(testvXUserPermission); + VXUserPermission retVXUserPermission = xUserRest.updateXUserPermission(testvXUserPermission); + Mockito.verify(xUserMgr).updateXUserPermission(testvXUserPermission); + Mockito.verify(xUserMgr).checkAdminAccess(); + assertNotNull(retVXUserPermission); + assertEquals(retVXUserPermission.getId(), testvXUserPermission.getId()); + assertEquals(retVXUserPermission.getUserName(), testvXUserPermission.getUserName()); + } + + @Test + public void test85deleteXUserPermission() { + boolean forceDelete = true; + + Mockito.doNothing().when(xUserMgr).checkAdminAccess(); + + Mockito.doNothing().when(xUserMgr).deleteXUserPermission(id, forceDelete); + xUserRest.deleteXUserPermission(id, request); + Mockito.verify(xUserMgr).deleteXUserPermission(id, forceDelete); + Mockito.verify(xUserMgr).checkAdminAccess(); + } + + @SuppressWarnings("unchecked") + @Test + public void test86searchXUserPermission() { + VXUserPermissionList testVXUserPermissionList = new VXUserPermissionList(); + testVXUserPermissionList.setTotalCount(1); + testVXUserPermissionList.setStartIndex(1); + VXUserPermission testVXUserPermission = createVXUserPermission(); + List testVXUserPermissions = new ArrayList<>(); + testVXUserPermissions.add(testVXUserPermission); + testVXUserPermissionList.setvXModuleDef(testVXUserPermissions); + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + SearchCriteria testSearchCriteria = createsearchCriteria(); + Mockito.when(searchUtil.extractCommonCriterias(Mockito.any(), Mockito.any())).thenReturn(testSearchCriteria); + Mockito.when(searchUtil.extractString(request, testSearchCriteria, "id", "id", StringUtil.VALIDATION_NAME)).thenReturn(""); + Mockito.when(searchUtil.extractString(request, testSearchCriteria, "userPermissionList", "userId", StringUtil.VALIDATION_NAME)).thenReturn(""); + + Mockito.when(xUserMgr.searchXUserPermission(testSearchCriteria)).thenReturn(testVXUserPermissionList); + VXUserPermissionList outputVXUserPermissionList = xUserRest.searchXUserPermission(request); + assertNotNull(outputVXUserPermissionList); + assertEquals(outputVXUserPermissionList.getStartIndex(), testVXUserPermissionList.getStartIndex()); + assertEquals(outputVXUserPermissionList.getTotalCount(), testVXUserPermissionList.getTotalCount()); + + Mockito.verify(xUserMgr).searchXUserPermission(testSearchCriteria); + Mockito.verify(searchUtil).extractCommonCriterias(Mockito.any(), Mockito.any()); + Mockito.verify(searchUtil).extractString(request, testSearchCriteria, "id", "id", StringUtil.VALIDATION_NAME); + Mockito.verify(searchUtil).extractString(request, testSearchCriteria, "userPermissionList", "userId", StringUtil.VALIDATION_NAME); + } + + @Test + public void test87countXUserPermission() { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + SearchCriteria testSearchCriteria = createsearchCriteria(); + + Mockito.when(searchUtil.extractCommonCriterias(Mockito.any(), Mockito.any())).thenReturn(testSearchCriteria); + + vXLong.setValue(1); + + Mockito.when(xUserMgr.getXUserPermissionSearchCount(testSearchCriteria)).thenReturn(vXLong); + VXLong testvxLong = xUserRest.countXUserPermission(request); + Mockito.verify(xUserMgr).getXUserPermissionSearchCount(testSearchCriteria); + Mockito.verify(searchUtil).extractCommonCriterias(Mockito.any(), Mockito.any()); + + assertNotNull(testvxLong); + assertEquals(testvxLong.getValue(), vXLong.getValue()); + assertEquals(testvxLong.getClass(), vXLong.getClass()); + } + + @Test + public void test88createXGroupPermission() { + VXGroupPermission testVXGroupPermission = createVXGroupPermission(); + + Mockito.doNothing().when(xUserMgr).checkAdminAccess(); + Mockito.when(xUserMgr.createXGroupPermission(testVXGroupPermission)).thenReturn(testVXGroupPermission); + VXGroupPermission retVXGroupPermission = xUserRest.createXGroupPermission(testVXGroupPermission); + Mockito.verify(xUserMgr).createXGroupPermission(testVXGroupPermission); + Mockito.verify(xUserMgr).checkAdminAccess(); + assertNotNull(retVXGroupPermission); + assertEquals(retVXGroupPermission.getId(), testVXGroupPermission.getId()); + assertEquals(retVXGroupPermission.getClass(), testVXGroupPermission.getClass()); + } + + @Test + public void test89getXGroupPermission() { + VXGroupPermission testVXGroupPermission = createVXGroupPermission(); + Mockito.when(xUserMgr.getXGroupPermission(testVXGroupPermission.getId())).thenReturn(testVXGroupPermission); + VXGroupPermission retVXGroupPermission = xUserRest.getXGroupPermission(testVXGroupPermission.getId()); + Mockito.verify(xUserMgr).getXGroupPermission(testVXGroupPermission.getId()); + assertNotNull(retVXGroupPermission); + assertEquals(retVXGroupPermission.getId(), testVXGroupPermission.getId()); + assertEquals(retVXGroupPermission.getClass(), testVXGroupPermission.getClass()); + } + + @Test + public void test90updateXGroupPermission() { + VXGroupPermission testVXGroupPermission = createVXGroupPermission(); + Mockito.doNothing().when(xUserMgr).checkAdminAccess(); + Mockito.when(xUserMgr.updateXGroupPermission(testVXGroupPermission)).thenReturn(testVXGroupPermission); + VXGroupPermission retVXGroupPermission = xUserRest.updateXGroupPermission(testVXGroupPermission.getId(), testVXGroupPermission); + Mockito.verify(xUserMgr).updateXGroupPermission(testVXGroupPermission); + Mockito.verify(xUserMgr).checkAdminAccess(); + assertNotNull(retVXGroupPermission); + assertEquals(retVXGroupPermission.getId(), testVXGroupPermission.getId()); + assertEquals(retVXGroupPermission.getClass(), testVXGroupPermission.getClass()); + } + + @Test + public void test91deleteXGroupPermission() { + boolean forceDelete = true; + + Mockito.doNothing().when(xUserMgr).checkAdminAccess(); + + Mockito.doNothing().when(xUserMgr).deleteXGroupPermission(id, forceDelete); + xUserRest.deleteXGroupPermission(id, request); + Mockito.verify(xUserMgr).deleteXGroupPermission(id, forceDelete); + Mockito.verify(xUserMgr).checkAdminAccess(); + } + + @SuppressWarnings("unchecked") + @Test + public void test92searchXGroupPermission() { + VXGroupPermissionList testVXGroupPermissionList = new VXGroupPermissionList(); + testVXGroupPermissionList.setTotalCount(1); + VXGroupPermission testVXGroupPermission = createVXGroupPermission(); + List testVXGroupPermissions = new ArrayList<>(); + testVXGroupPermissions.add(testVXGroupPermission); + testVXGroupPermissionList.setvXGroupPermission(testVXGroupPermissions); + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + SearchCriteria testSearchCriteria = createsearchCriteria(); + Mockito.when(searchUtil.extractCommonCriterias(Mockito.any(), Mockito.any())).thenReturn(testSearchCriteria); + Mockito.when(searchUtil.extractString(request, testSearchCriteria, "id", "id", StringUtil.VALIDATION_NAME)).thenReturn(""); + Mockito.when(searchUtil.extractString(request, testSearchCriteria, "groupPermissionList", "groupId", StringUtil.VALIDATION_NAME)).thenReturn(""); + Mockito.when(xUserMgr.searchXGroupPermission(testSearchCriteria)).thenReturn(testVXGroupPermissionList); + VXGroupPermissionList outputVXGroupPermissionList = xUserRest.searchXGroupPermission(request); + assertNotNull(outputVXGroupPermissionList); + assertEquals(outputVXGroupPermissionList.getClass(), testVXGroupPermissionList.getClass()); + assertEquals(outputVXGroupPermissionList.getTotalCount(), testVXGroupPermissionList.getTotalCount()); + + Mockito.verify(xUserMgr).searchXGroupPermission(testSearchCriteria); + + Mockito.verify(searchUtil).extractCommonCriterias(Mockito.any(), Mockito.any()); + Mockito.verify(searchUtil).extractString(request, testSearchCriteria, "id", "id", StringUtil.VALIDATION_NAME); + Mockito.verify(searchUtil).extractString(request, testSearchCriteria, "groupPermissionList", "groupId", StringUtil.VALIDATION_NAME); + } + + @Test + public void test93countXGroupPermission() { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + SearchCriteria testSearchCriteria = createsearchCriteria(); + + Mockito.when(searchUtil.extractCommonCriterias(Mockito.any(), Mockito.any())).thenReturn(testSearchCriteria); + + vXLong.setValue(1); + + Mockito.when(xUserMgr.getXGroupPermissionSearchCount(testSearchCriteria)).thenReturn(vXLong); + VXLong testvxLong = xUserRest.countXGroupPermission(request); + Mockito.verify(xUserMgr).getXGroupPermissionSearchCount(testSearchCriteria); + Mockito.verify(searchUtil).extractCommonCriterias(Mockito.any(), Mockito.any()); + + assertNotNull(testvxLong); + assertEquals(testvxLong.getValue(), vXLong.getValue()); + assertEquals(testvxLong.getClass(), vXLong.getClass()); + } + + @Test + public void test94modifyUserActiveStatus() { + HashMap statusMap = new HashMap<>(); + statusMap.put(id, 1); + Mockito.doNothing().when(xUserMgr).modifyUserActiveStatus(statusMap); + xUserRest.modifyUserActiveStatus(statusMap); + Mockito.verify(xUserMgr).modifyUserActiveStatus(statusMap); + } + + @Test + public void test95setUserRolesByExternalID() { + VXStringList testVXStringList = createVXStringList(); + Mockito.when(xUserMgr.setUserRolesByExternalID(id, testVXStringList.getVXStrings())).thenReturn(testVXStringList); + VXStringList retVXStringList = xUserRest.setUserRolesByExternalID(id, testVXStringList); + Mockito.verify(xUserMgr).setUserRolesByExternalID(id, testVXStringList.getVXStrings()); + + assertNotNull(retVXStringList); + assertEquals(testVXStringList.getTotalCount(), retVXStringList.getTotalCount()); + assertEquals(testVXStringList.getClass(), retVXStringList.getClass()); + } + + @Test + public void test96setUserRolesByName() { + VXStringList testVXStringList = createVXStringList(); + Mockito.when(xUserMgr.setUserRolesByName("Admin", testVXStringList.getVXStrings())).thenReturn(testVXStringList); + VXStringList retVXStringList = xUserRest.setUserRolesByName("Admin", testVXStringList); + Mockito.verify(xUserMgr).setUserRolesByName("Admin", testVXStringList.getVXStrings()); + + assertNotNull(retVXStringList); + assertEquals(testVXStringList.getTotalCount(), retVXStringList.getTotalCount()); + assertEquals(testVXStringList.getClass(), retVXStringList.getClass()); + } + + @Test + public void test97getUserRolesByExternalID() { + VXStringList testVXStringList = createVXStringList(); + + Mockito.when(xUserMgr.getUserRolesByExternalID(id)).thenReturn(testVXStringList); + VXStringList retVXStringList = xUserRest.getUserRolesByExternalID(id); + Mockito.verify(xUserMgr).getUserRolesByExternalID(id); + assertNotNull(retVXStringList); + assertEquals(testVXStringList.getTotalCount(), retVXStringList.getTotalCount()); + assertEquals(testVXStringList.getClass(), retVXStringList.getClass()); + } + + @Test + public void test98getUserRolesByName() { + VXStringList testVXStringList = createVXStringList(); + + Mockito.when(xUserMgr.getUserRolesByName("Admin")).thenReturn(testVXStringList); + VXStringList retVXStringList = xUserRest.getUserRolesByName("Admin"); + Mockito.verify(xUserMgr).getUserRolesByName("Admin"); + assertNotNull(retVXStringList); + assertEquals(testVXStringList.getTotalCount(), retVXStringList.getTotalCount()); + assertEquals(testVXStringList.getClass(), retVXStringList.getClass()); + } + + @Test + public void test99deleteUsersByUserName() { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + String testForceDeleteStr = "true"; + Mockito.when(request.getParameter("forceDelete")).thenReturn(testForceDeleteStr); + VXString testVXString = new VXString(); + testVXString.setValue("User1"); + VXUser testVXUser = createVXUser(); + VXStringList vxStringList = createVXStringList(); + + Mockito.when(xUserService.getXUserByUserName(testVXString.getValue())).thenReturn(testVXUser); + Mockito.doNothing().when(xUserMgr).deleteXUser(testVXUser.getId(), true); + xUserRest.deleteUsersByUserName(request, vxStringList); + Mockito.verify(xUserMgr).deleteXUser(testVXUser.getId(), true); + Mockito.verify(xUserService).getXUserByUserName(testVXString.getValue()); + Mockito.verify(request).getParameter("forceDelete"); + } + + @Test + public void test100deleteUsersByUserNameNull() { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + String testForceDeleteStr = "false"; + Mockito.when(request.getParameter("forceDelete")).thenReturn(testForceDeleteStr); + VXString testVXString = new VXString(); + testVXString.setValue("User1"); + VXUser testVXUser = createVXUser(); + VXStringList vxStringList = createVXStringList(); + + Mockito.when(xUserService.getXUserByUserName(testVXString.getValue())).thenReturn(testVXUser); + Mockito.doNothing().when(xUserMgr).deleteXUser(testVXUser.getId(), false); + xUserRest.deleteUsersByUserName(request, vxStringList); + Mockito.verify(xUserMgr).deleteXUser(testVXUser.getId(), false); + Mockito.verify(xUserService).getXUserByUserName(testVXString.getValue()); + Mockito.verify(request).getParameter("forceDelete"); + } + + @Test + public void test101deleteUsersByUserNameNull() { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + String testForceDeleteStr = null; + Mockito.when(request.getParameter("forceDelete")).thenReturn(testForceDeleteStr); + VXString testVXString = new VXString(); + testVXString.setValue("User1"); + VXUser testVXUser = createVXUser(); + VXStringList vxStringList = createVXStringList(); + + Mockito.when(xUserService.getXUserByUserName(testVXString.getValue())).thenReturn(testVXUser); + Mockito.doNothing().when(xUserMgr).deleteXUser(testVXUser.getId(), false); + xUserRest.deleteUsersByUserName(request, vxStringList); + Mockito.verify(xUserMgr).deleteXUser(testVXUser.getId(), false); + Mockito.verify(xUserService).getXUserByUserName(testVXString.getValue()); + Mockito.verify(request).getParameter("forceDelete"); + } + + @Test + public void test102deleteUsersByUserNameSetValueNull() { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + String testForceDeleteStr = "false"; + Mockito.when(request.getParameter("forceDelete")).thenReturn(testForceDeleteStr); + VXString testVXString = new VXString(); + testVXString.setValue("User1"); + VXUser testVXUser = createVXUser(); + VXStringList vxStringList = createVXStringList(); + + Mockito.when(xUserService.getXUserByUserName(testVXString.getValue())).thenReturn(testVXUser); + Mockito.doNothing().when(xUserMgr).deleteXUser(testVXUser.getId(), false); + xUserRest.deleteUsersByUserName(request, vxStringList); + Mockito.verify(xUserMgr).deleteXUser(testVXUser.getId(), false); + Mockito.verify(xUserService).getXUserByUserName(testVXString.getValue()); + Mockito.verify(request).getParameter("forceDelete"); + } + + @Test + public void test103deleteUsersByUserNameListNull() { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + String testForceDeleteStr = "false"; + Mockito.when(request.getParameter("forceDelete")).thenReturn(testForceDeleteStr); + VXString testVXString = new VXString(); + testVXString.setValue("User1"); + xUserRest.deleteUsersByUserName(request, null); + Mockito.verify(request).getParameter("forceDelete"); + } + + @Test + public void test104deleteUsersByUserNameListGetListNull() { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + String testForceDeleteStr = "false"; + + Mockito.when(request.getParameter("forceDelete")).thenReturn(testForceDeleteStr); + VXStringList vxStringList = createVXStringList(); + vxStringList.setVXStrings(null); + xUserRest.deleteUsersByUserName(request, vxStringList); + Mockito.verify(request).getParameter("forceDelete"); + } + + @Test + public void test105deleteUsersByUserNameNull() { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + String testForceDeleteStr = "true"; + + Mockito.when(request.getParameter("forceDelete")).thenReturn(testForceDeleteStr); + VXString testVXString = new VXString(); + testVXString.setValue(null); + + VXStringList vxStringList = createVXStringList(); + List testVXStrings = new ArrayList<>(); + testVXStrings.add(testVXString); + vxStringList.setVXStrings(testVXStrings); + xUserRest.deleteUsersByUserName(request, vxStringList); + Mockito.verify(request).getParameter("forceDelete"); + } + + @Test + public void test106deleteGroupsByGroupName() { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + String testForceDeleteStr = "true"; + Mockito.when(request.getParameter("forceDelete")).thenReturn(testForceDeleteStr); + VXString testVXString = new VXString(); + testVXString.setValue("testVXGroup"); + VXGroup testVXGroup = createVXGroup(); + VXStringList vxStringList = createVXStringListGroup(); + + Mockito.when(xGroupService.getGroupByGroupName(testVXString.getValue())).thenReturn(testVXGroup); + Mockito.doNothing().when(xUserMgr).deleteXGroup(testVXGroup.getId(), true); + xUserRest.deleteGroupsByGroupName(request, vxStringList); + Mockito.verify(xUserMgr).deleteXGroup(testVXGroup.getId(), true); + Mockito.verify(xGroupService).getGroupByGroupName(testVXString.getValue()); + Mockito.verify(request).getParameter("forceDelete"); + } + + @Test + public void test107GroupsByGroupNameNull() { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + String testForceDeleteStr = "false"; + Mockito.when(request.getParameter("forceDelete")).thenReturn(testForceDeleteStr); + VXString testVXString = new VXString(); + testVXString.setValue("testVXGroup"); + VXGroup testVXGroup = createVXGroup(); + VXStringList vxStringList = createVXStringListGroup(); + + Mockito.when(xGroupService.getGroupByGroupName(testVXString.getValue())).thenReturn(testVXGroup); + Mockito.doNothing().when(xUserMgr).deleteXGroup(testVXGroup.getId(), false); + xUserRest.deleteGroupsByGroupName(request, vxStringList); + Mockito.verify(xUserMgr).deleteXGroup(testVXGroup.getId(), false); + Mockito.verify(xGroupService).getGroupByGroupName(testVXString.getValue()); + Mockito.verify(request).getParameter("forceDelete"); + } + + @Test + public void test108deleteGroupsByGroupNameNull() { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + String testForceDeleteStr = null; + Mockito.when(request.getParameter("forceDelete")).thenReturn(testForceDeleteStr); + VXString testVXString = new VXString(); + testVXString.setValue("testVXGroup"); + VXGroup testVXGroup = createVXGroup(); + VXStringList vxStringList = createVXStringListGroup(); + + Mockito.when(xGroupService.getGroupByGroupName(testVXString.getValue())).thenReturn(testVXGroup); + Mockito.doNothing().when(xUserMgr).deleteXGroup(testVXGroup.getId(), false); + xUserRest.deleteGroupsByGroupName(request, vxStringList); + Mockito.verify(xUserMgr).deleteXGroup(testVXGroup.getId(), false); + Mockito.verify(xGroupService).getGroupByGroupName(testVXString.getValue()); + Mockito.verify(request).getParameter("forceDelete"); + } + + @Test + public void test109deleteGroupsByGroupNameSetValueNull() { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + String testForceDeleteStr = "false"; + Mockito.when(request.getParameter("forceDelete")).thenReturn(testForceDeleteStr); + VXString testVXString = new VXString(); + testVXString.setValue("testVXGroup"); + VXGroup testVXGroup = createVXGroup(); + VXStringList vxStringList = createVXStringListGroup(); + + Mockito.when(xGroupService.getGroupByGroupName(testVXString.getValue())).thenReturn(testVXGroup); + Mockito.doNothing().when(xUserMgr).deleteXGroup(testVXGroup.getId(), false); + xUserRest.deleteGroupsByGroupName(request, vxStringList); + Mockito.verify(xUserMgr).deleteXGroup(testVXGroup.getId(), false); + Mockito.verify(xGroupService).getGroupByGroupName(testVXString.getValue()); + Mockito.verify(request).getParameter("forceDelete"); + } + + @Test + public void test110deleteGroupsByGroupNameListNull() { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + String testForceDeleteStr = "false"; + Mockito.when(request.getParameter("forceDelete")).thenReturn(testForceDeleteStr); + VXString testVXString = new VXString(); + testVXString.setValue("testVXGroup"); + xUserRest.deleteGroupsByGroupName(request, null); + Mockito.verify(request).getParameter("forceDelete"); + } + + @Test + public void test111deleteUsersByUserNameListGetListNull() { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + String testForceDeleteStr = "false"; + + Mockito.when(request.getParameter("forceDelete")).thenReturn(testForceDeleteStr); + VXStringList vxStringList = createVXStringList(); + vxStringList.setVXStrings(null); + xUserRest.deleteGroupsByGroupName(request, vxStringList); + Mockito.verify(request).getParameter("forceDelete"); + } + + @Test + public void test112deleteUsersByUserNameNull() { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + String testForceDeleteStr = "true"; + + Mockito.when(request.getParameter("forceDelete")).thenReturn(testForceDeleteStr); + VXString testVXString = new VXString(); + testVXString.setValue(null); + + VXStringList vxStringList = createVXStringListGroup(); + List testVXStrings = new ArrayList<>(); + testVXStrings.add(testVXString); + vxStringList.setVXStrings(testVXStrings); + xUserRest.deleteGroupsByGroupName(request, vxStringList); + Mockito.verify(request).getParameter("forceDelete"); + } + + @Test + public void test113ErrorWhenRoleUserIsTryingToFetchAnotherUserDetails() { + destroySession(); + String userLoginID = "testuser"; + Long userId = 8L; + + RangerSecurityContext context = new RangerSecurityContext(); + context.setUserSession(new UserSessionBase()); + RangerContextHolder.setSecurityContext(context); + UserSessionBase currentUserSession = ContextUtil.getCurrentUserSession(); + currentUserSession.setUserAdmin(false); + XXPortalUser xXPortalUser = new XXPortalUser(); + xXPortalUser.setLoginId(userLoginID); + xXPortalUser.setId(userId); + currentUserSession.setXXPortalUser(xXPortalUser); + + VXUser loggedInUser = createVXUser(); + List loggedInUserRole = new ArrayList<>(); + loggedInUserRole.add(RangerConstants.ROLE_USER); + loggedInUser.setId(8L); + loggedInUser.setName("testuser"); + loggedInUser.setUserRoleList(loggedInUserRole); + + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + SearchCriteria testSearchCriteria = createsearchCriteria(); + testSearchCriteria.addParam("name", "admin"); + + Mockito.when(searchUtil.extractCommonCriterias(Mockito.any(), Mockito.any())).thenReturn(testSearchCriteria); + + Mockito.when(searchUtil.extractCommonCriterias(request, xUserService.sortFields)).thenReturn(testSearchCriteria); + Mockito.when(searchUtil.extractString(request, testSearchCriteria, "emailAddress", "Email Address", null)).thenReturn(""); + Mockito.when(searchUtil.extractInt(request, testSearchCriteria, "userSource", "User Source")).thenReturn(1); + Mockito.when(searchUtil.extractInt(request, testSearchCriteria, "isVisible", "User Visibility")).thenReturn(1); + Mockito.when(searchUtil.extractInt(request, testSearchCriteria, "status", "User Status")).thenReturn(1); + Mockito.when(searchUtil.extractStringList(request, testSearchCriteria, "userRoleList", "User Role List", "userRoleList", null, null)).thenReturn(new ArrayList<>()); + Mockito.when(searchUtil.extractRoleString(request, testSearchCriteria, "userRole", "Role", null)).thenReturn(""); + Mockito.when(xUserService.getXUserByUserName("testuser")).thenReturn(loggedInUser); + Mockito.when(restErrorUtil.create403RESTException("Logged-In user is not allowed to access requested user data.")).thenThrow(new WebApplicationException()); + thrown.expect(WebApplicationException.class); + + xUserRest.searchXUsers(request, null, null); + } + + @SuppressWarnings({"unchecked", "static-access"}) + @Test + public void test114RoleUserWillGetOnlyHisOwnUserDetails() { + destroySession(); + String userLoginID = "testuser"; + Long userId = 8L; + + RangerSecurityContext context = new RangerSecurityContext(); + context.setUserSession(new UserSessionBase()); + RangerContextHolder.setSecurityContext(context); + UserSessionBase currentUserSession = ContextUtil.getCurrentUserSession(); + currentUserSession.setUserAdmin(false); + XXPortalUser xXPortalUser = new XXPortalUser(); + xXPortalUser.setLoginId(userLoginID); + xXPortalUser.setId(userId); + currentUserSession.setXXPortalUser(xXPortalUser); + + VXUser loggedInUser = createVXUser(); + List loggedInUserRole = new ArrayList<>(); + loggedInUserRole.add(RangerConstants.ROLE_USER); + loggedInUser.setId(8L); + loggedInUser.setName("testuser"); + loggedInUser.setUserRoleList(loggedInUserRole); + + VXUserList expecteUserList = new VXUserList(); + VXUser expectedUser = new VXUser(); + expectedUser.setId(8L); + expectedUser.setName("testuser"); + List userList = new ArrayList<>(); + userList.add(expectedUser); + expecteUserList.setVXUsers(userList); + + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + SearchCriteria testSearchCriteria = createsearchCriteria(); + + Mockito.when(searchUtil.extractCommonCriterias(Mockito.any(), Mockito.any())).thenReturn(testSearchCriteria); + + Mockito.when(searchUtil.extractCommonCriterias(request, xUserService.sortFields)).thenReturn(testSearchCriteria); + Mockito.when(searchUtil.extractString(request, testSearchCriteria, "emailAddress", "Email Address", null)).thenReturn(""); + Mockito.when(searchUtil.extractInt(request, testSearchCriteria, "userSource", "User Source")).thenReturn(1); + Mockito.when(searchUtil.extractInt(request, testSearchCriteria, "isVisible", "User Visibility")).thenReturn(1); + Mockito.when(searchUtil.extractInt(request, testSearchCriteria, "status", "User Status")).thenReturn(1); + Mockito.when(searchUtil.extractStringList(request, testSearchCriteria, "userRoleList", "User Role List", "userRoleList", null, null)).thenReturn(new ArrayList<>()); + Mockito.when(searchUtil.extractRoleString(request, testSearchCriteria, "userRole", "Role", null)).thenReturn(""); + Mockito.when(xUserService.getXUserByUserName("testuser")).thenReturn(loggedInUser); + Mockito.when(xUserMgr.searchXUsers(testSearchCriteria)).thenReturn(expecteUserList); + VXUserList gotVXUserList = xUserRest.searchXUsers(request, null, null); + + assertEquals(1, gotVXUserList.getList().size()); + assertEquals(gotVXUserList.getList().get(0).getId(), expectedUser.getId()); + assertEquals(gotVXUserList.getList().get(0).getName(), expectedUser.getName()); + } + + @Test + public void test115updateXGroupPermissionWithInvalidPermissionId() { + VXGroupPermission testVXGroupPermission = createVXGroupPermission(); + Mockito.when(restErrorUtil.createRESTException(Mockito.anyInt(), Mockito.anyString(), Mockito.anyBoolean())).thenThrow(new WebApplicationException()); + thrown.expect(WebApplicationException.class); + VXGroupPermission retVXGroupPermission = xUserRest.updateXGroupPermission(-1L, testVXGroupPermission); + Mockito.verify(xUserMgr).updateXGroupPermission(testVXGroupPermission); + Mockito.verify(xUserMgr).checkAdminAccess(); + assertNotNull(retVXGroupPermission); + assertEquals(retVXGroupPermission.getId(), testVXGroupPermission.getId()); + assertEquals(retVXGroupPermission.getClass(), testVXGroupPermission.getClass()); + } + + @Test + public void test116updateXGroupPermissionWithPermissionIdIsNull() { + VXGroupPermission testVXGroupPermission = createVXGroupPermission(); + Long testVXGroupPermissionId = testVXGroupPermission.getId(); + testVXGroupPermission.setId(null); + Mockito.doNothing().when(xUserMgr).checkAdminAccess(); + Mockito.when(xUserMgr.updateXGroupPermission(testVXGroupPermission)).thenReturn(testVXGroupPermission); + VXGroupPermission retVXGroupPermission = xUserRest.updateXGroupPermission(testVXGroupPermissionId, testVXGroupPermission); + Mockito.verify(xUserMgr).updateXGroupPermission(testVXGroupPermission); + Mockito.verify(xUserMgr).checkAdminAccess(); + assertNotNull(retVXGroupPermission); + assertEquals(retVXGroupPermission.getId(), testVXGroupPermission.getId()); + assertEquals(retVXGroupPermission.getClass(), testVXGroupPermission.getClass()); + } + + @After + public void destroySession() { + RangerSecurityContext context = new RangerSecurityContext(); + context.setUserSession(null); + RangerContextHolder.setSecurityContext(context); + } + + private HashMap creategroupVisibilityMap() { + HashMap groupVisibilityMap = new HashMap<>(); + groupVisibilityMap.put(id, 1); + return groupVisibilityMap; + } + + private SearchCriteria createsearchCriteria() { + SearchCriteria testsearchCriteria = new SearchCriteria(); + testsearchCriteria.setStartIndex(0); + testsearchCriteria.setMaxRows(Integer.MAX_VALUE); + testsearchCriteria.setSortBy("id"); + testsearchCriteria.setSortType("asc"); + testsearchCriteria.setGetCount(true); + testsearchCriteria.setOwnerId(null); + testsearchCriteria.setGetChildren(false); + testsearchCriteria.setDistinct(false); + + return testsearchCriteria; + } + + private VXGroupList createXGroupList() { + VXGroupList testVXGroupList = new VXGroupList(); + VXGroup vXGroup1 = createVXGroup(); + List vXGroups = new ArrayList<>(); + vXGroups.add(vXGroup1); + testVXGroupList.setVXGroups(vXGroups); + testVXGroupList.setStartIndex(0); + testVXGroupList.setTotalCount(1); + + return testVXGroupList; + } + + private VXUser createVXUser() { + VXUser testVXUser = new VXUser(); + Collection c = new ArrayList<>(); + testVXUser.setId(id); + testVXUser.setCreateDate(new Date()); + testVXUser.setUpdateDate(new Date()); + testVXUser.setOwner("Admin"); + testVXUser.setUpdatedBy("Admin"); + testVXUser.setName("User1"); + testVXUser.setFirstName("FnameUser1"); + testVXUser.setLastName("LnameUser1"); + testVXUser.setPassword("User1"); + testVXUser.setGroupIdList(null); + testVXUser.setGroupNameList(null); + testVXUser.setStatus(1); + testVXUser.setIsVisible(1); + testVXUser.setUserSource(0); + c.add("ROLE_USER"); + testVXUser.setUserRoleList(c); + + return testVXUser; + } + + private VXGroupUser createVXGroupUser() { + VXGroupUser testVXGroupUser = new VXGroupUser(); + testVXGroupUser.setId(id); + testVXGroupUser.setCreateDate(new Date()); + testVXGroupUser.setUpdateDate(new Date()); + testVXGroupUser.setOwner("Admin"); + testVXGroupUser.setUpdatedBy("Admin"); + testVXGroupUser.setName("finance"); + testVXGroupUser.setParentGroupId(id); + testVXGroupUser.setUserId(id); + return testVXGroupUser; + } + + private VXPermMap testcreateXPermMap() { + VXPermMap testVXPermMap = new VXPermMap(); + testVXPermMap.setCreateDate(new Date()); + testVXPermMap.setGroupId(id); + testVXPermMap.setGroupName("testGroup"); + testVXPermMap.setId(id); + testVXPermMap.setOwner("Admin"); + testVXPermMap.setPermGroup("testPermGroup"); + testVXPermMap.setPermType(1); + testVXPermMap.setResourceId(id); + testVXPermMap.setUpdateDate(new Date()); + testVXPermMap.setUpdatedBy("Admin"); + testVXPermMap.setUserId(id); + testVXPermMap.setUserName("testUser"); + testVXPermMap.setPermFor(1); + + return testVXPermMap; + } + + private VXAuditMap createVXAuditMapObj() { + VXAuditMap testVXAuditMap = new VXAuditMap(); + testVXAuditMap.setAuditType(1); + testVXAuditMap.setCreateDate(new Date()); + testVXAuditMap.setGroupId(id); + testVXAuditMap.setId(id); + testVXAuditMap.setResourceId(id); + testVXAuditMap.setUpdateDate(new Date()); + testVXAuditMap.setOwner("Admin"); + testVXAuditMap.setUpdatedBy("Admin"); + testVXAuditMap.setUserId(id); + return testVXAuditMap; + } + + private VXResource createVXResource() { + VXResource testVXResource = new VXResource(); + testVXResource.setAssetId(id); + testVXResource.setAssetName("AdminAsset"); + testVXResource.setAssetType(1); + testVXResource.setCreateDate(new Date()); + testVXResource.setOwner("Admin"); + testVXResource.setUpdateDate(new Date()); + testVXResource.setUpdatedBy("Admin"); + testVXResource.setParentId(id); + testVXResource.setName("User"); + + return testVXResource; + } + + private VXGroup createVXGroup() { + VXGroup testVXGroup = new VXGroup(); + testVXGroup.setName("testVXGroup"); + testVXGroup.setCreateDate(new Date()); + testVXGroup.setUpdateDate(new Date()); + testVXGroup.setUpdatedBy("Admin"); + testVXGroup.setOwner("Admin"); + testVXGroup.setId(id); + testVXGroup.setGroupType(1); + testVXGroup.setCredStoreId(1L); + testVXGroup.setGroupSource(1); + testVXGroup.setIsVisible(1); + return testVXGroup; + } + + private VXAuthSession createVXAuthSession() { + VXAuthSession testVXAuthSession = new VXAuthSession(); + testVXAuthSession.setAuthProvider(1); + testVXAuthSession.setAuthStatus(1); + testVXAuthSession.setAuthTime(new Date()); + testVXAuthSession.setCityName("Mumbai"); + testVXAuthSession.setCountryName("India"); + testVXAuthSession.setCreateDate(new Date()); + testVXAuthSession.setDeviceType(1); + testVXAuthSession.setEmailAddress("email@EXAMPLE.COM"); + testVXAuthSession.setFamilyScreenName("testfamilyScreenName"); + testVXAuthSession.setFirstName("testAuthSessionName"); + testVXAuthSession.setId(id); + testVXAuthSession.setLoginId("Admin"); + testVXAuthSession.setOwner("Admin"); + testVXAuthSession.setPublicScreenName("Admin"); + testVXAuthSession.setUpdatedBy("Admin"); + testVXAuthSession.setUpdateDate(new Date()); + testVXAuthSession.setUserId(id); + testVXAuthSession.setStateName("Maharashtra"); + return testVXAuthSession; + } + + private VXUserPermission createVXUserPermission() { + VXUserPermission testVXUserPermission = new VXUserPermission(); + + testVXUserPermission.setCreateDate(new Date()); + testVXUserPermission.setId(id); + testVXUserPermission.setIsAllowed(1); + testVXUserPermission.setModuleId(id); + testVXUserPermission.setModuleName("testModule"); + testVXUserPermission.setOwner("Admin"); + testVXUserPermission.setUpdateDate(new Date()); + testVXUserPermission.setUpdatedBy("Admin"); + testVXUserPermission.setUserId(id); + testVXUserPermission.setUserName("testVXUser"); + + return testVXUserPermission; + } + + private VXGroupPermission createVXGroupPermission() { + VXGroupPermission testVXGroupPermission = new VXGroupPermission(); + + testVXGroupPermission.setCreateDate(new Date()); + testVXGroupPermission.setGroupId(id); + testVXGroupPermission.setGroupName("testVXGroup"); + testVXGroupPermission.setId(id); + testVXGroupPermission.setIsAllowed(1); + testVXGroupPermission.setModuleId(id); + testVXGroupPermission.setModuleName("testModule"); + testVXGroupPermission.setOwner("Admin"); + testVXGroupPermission.setUpdateDate(new Date()); + testVXGroupPermission.setUpdatedBy("Admin"); + + return testVXGroupPermission; + } + + private VXModuleDef createVXModuleDef() { + VXModuleDef testVXModuleDef = new VXModuleDef(); + testVXModuleDef.setAddedById(id); + testVXModuleDef.setCreateDate(new Date()); + testVXModuleDef.setCreateTime(new Date()); + + VXGroupPermission testVXGroupPermission = createVXGroupPermission(); + List groupPermList = new ArrayList<>(); + groupPermList.add(testVXGroupPermission); + testVXModuleDef.setGroupPermList(groupPermList); + + testVXModuleDef.setId(id); + testVXModuleDef.setModule("testModule"); + testVXModuleDef.setOwner("Admin"); + testVXModuleDef.setUpdateDate(new Date()); + testVXModuleDef.setUpdatedBy("Admin"); + testVXModuleDef.setUpdatedById(id); + testVXModuleDef.setUpdateTime(new Date()); + testVXModuleDef.setUrl("testUrrl"); + + List userPermList = new ArrayList<>(); + VXUserPermission testVXUserPermission = createVXUserPermission(); + userPermList.add(testVXUserPermission); + testVXModuleDef.setUserPermList(userPermList); + + return testVXModuleDef; + } + + private VXStringList createVXStringList() { + VXStringList testVXStringList = new VXStringList(); + VXString testVXString = new VXString(); + testVXString.setValue("User1"); + List testVXStrings = new ArrayList<>(); + + testVXStrings.add(testVXString); + + testVXStringList.setVXStrings(testVXStrings); + testVXStringList.setResultSize(1); + testVXStringList.setPageSize(1); + testVXStringList.setSortBy("Id"); + testVXStringList.setStartIndex(1); + testVXStringList.setTotalCount(1); + return testVXStringList; + } + + private VXStringList createVXStringListGroup() { + VXStringList testVXStringList = new VXStringList(); + VXString testVXString = new VXString(); + testVXString.setValue("testVXGroup"); + List testVXStrings = new ArrayList<>(); + + testVXStrings.add(testVXString); + + testVXStringList.setVXStrings(testVXStrings); + testVXStringList.setResultSize(1); + testVXStringList.setPageSize(1); + testVXStringList.setSortBy("Id"); + testVXStringList.setStartIndex(1); + testVXStringList.setTotalCount(1); + return testVXStringList; + } } diff --git a/security-admin/src/test/java/org/apache/ranger/security/web/filter/TestRangerCSRFPreventionFilter.java b/security-admin/src/test/java/org/apache/ranger/security/web/filter/TestRangerCSRFPreventionFilter.java index ac9712ec32..5fbaa7e522 100644 --- a/security-admin/src/test/java/org/apache/ranger/security/web/filter/TestRangerCSRFPreventionFilter.java +++ b/security-admin/src/test/java/org/apache/ranger/security/web/filter/TestRangerCSRFPreventionFilter.java @@ -18,8 +18,8 @@ */ package org.apache.ranger.security.web.filter; -import java.io.IOException; -import java.io.PrintWriter; +import org.junit.Test; +import org.mockito.Mockito; import javax.servlet.FilterChain; import javax.servlet.ServletException; @@ -27,161 +27,157 @@ import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; -import org.junit.Test; -import org.mockito.Mockito; +import java.io.IOException; +import java.io.PrintWriter; import static org.mockito.Mockito.atLeastOnce; public class TestRangerCSRFPreventionFilter { - - private static final String EXPECTED_MESSAGE = "Missing header or invalid Header value for CSRF Vulnerability Protection"; - private static final String X_CUSTOM_HEADER = "X-CUSTOM_HEADER"; - private String userAgent = "Mozilla"; - - @Test - public void testNoHeaderDefaultConfig_badRequest() throws ServletException, IOException { - // CSRF has not been sent - HttpServletRequest mockReq = Mockito.mock(HttpServletRequest.class); - Mockito.when(mockReq.getHeader(RangerCSRFPreventionFilter.HEADER_DEFAULT)).thenReturn(null); - Mockito.when(mockReq.getHeader(RangerCSRFPreventionFilter.HEADER_USER_AGENT)).thenReturn(userAgent); - - Mockito.when(mockReq.getMethod()).thenReturn("POST"); - - HttpSession session = Mockito.mock(HttpSession.class); - Mockito.when(session.getAttribute(RangerCSRFPreventionFilter.CSRF_TOKEN)).thenReturn("valueUnimportant"); - Mockito.when(mockReq.getSession()).thenReturn(session); - - // Objects to verify interactions based on request - HttpServletResponse mockRes = Mockito.mock(HttpServletResponse.class); - FilterChain mockChain = Mockito.mock(FilterChain.class); - - // Object under test - RangerCSRFPreventionFilter filter = new RangerCSRFPreventionFilter(); - filter.doFilter(mockReq, mockRes, mockChain); - - Mockito.verify(mockRes, atLeastOnce()).sendError(HttpServletResponse.SC_BAD_REQUEST, EXPECTED_MESSAGE); - Mockito.verifyZeroInteractions(mockChain); - } - - @Test - public void testHeaderPresentDefaultConfig_goodRequest() throws ServletException, IOException { - // CSRF HAS been sent - HttpServletRequest mockReq = Mockito.mock(HttpServletRequest.class); - Mockito.when(mockReq.getHeader(RangerCSRFPreventionFilter.HEADER_DEFAULT)).thenReturn("valueUnimportant"); - Mockito.when(mockReq.getHeader(RangerCSRFPreventionFilter.HEADER_USER_AGENT)).thenReturn(userAgent); - - Mockito.when(mockReq.getMethod()).thenReturn("POST"); - - HttpSession session = Mockito.mock(HttpSession.class); - Mockito.when(session.getAttribute(RangerCSRFPreventionFilter.CSRF_TOKEN)).thenReturn("valueUnimportant"); - Mockito.when(mockReq.getSession()).thenReturn(session); - - // Objects to verify interactions based on request - HttpServletResponse mockRes = Mockito.mock(HttpServletResponse.class); - FilterChain mockChain = Mockito.mock(FilterChain.class); - - // Object under test - RangerCSRFPreventionFilter filter = new RangerCSRFPreventionFilter(); - filter.doFilter(mockReq, mockRes, mockChain); - - Mockito.verify(mockChain).doFilter(mockReq, mockRes); - } - - @Test - public void testHeaderPresentDefaultConfig_badRequest() throws ServletException, IOException { - // CSRF HAS been sent - HttpServletRequest mockReq = Mockito.mock(HttpServletRequest.class); - Mockito.when(mockReq.getHeader(RangerCSRFPreventionFilter.HEADER_DEFAULT)).thenReturn("valueUnimportant"); - Mockito.when(mockReq.getHeader(RangerCSRFPreventionFilter.HEADER_USER_AGENT)).thenReturn(userAgent); - Mockito.when(mockReq.getMethod()).thenReturn("POST"); - - // Objects to verify interactions based on request - HttpServletResponse mockRes = Mockito.mock(HttpServletResponse.class); - PrintWriter mockWriter = Mockito.mock(PrintWriter.class); - Mockito.when(mockRes.getWriter()).thenReturn(mockWriter); - - FilterChain mockChain = Mockito.mock(FilterChain.class); - - // Object under test - RangerCSRFPreventionFilter filter = new RangerCSRFPreventionFilter(); - filter.doFilter(mockReq, mockRes, mockChain); - - Mockito.verify(mockChain, Mockito.never()).doFilter(mockReq, mockRes); - } - - @Test - public void testHeaderPresentCustomHeaderConfig_goodRequest() throws ServletException, IOException { - // CSRF HAS been sent - HttpServletRequest mockReq = Mockito.mock(HttpServletRequest.class); - Mockito.when(mockReq.getHeader(X_CUSTOM_HEADER)).thenReturn("valueUnimportant"); - - // Objects to verify interactions based on request - HttpServletResponse mockRes = Mockito.mock(HttpServletResponse.class); - FilterChain mockChain = Mockito.mock(FilterChain.class); - - // Object under test - RangerCSRFPreventionFilter filter = new RangerCSRFPreventionFilter(); - filter.doFilter(mockReq, mockRes, mockChain); - - Mockito.verify(mockChain).doFilter(mockReq, mockRes); - } - - @Test - public void testMissingHeaderWithCustomHeaderConfig_badRequest() throws ServletException, IOException { - // CSRF has not been sent - HttpServletRequest mockReq = Mockito.mock(HttpServletRequest.class); - Mockito.when(mockReq.getHeader(X_CUSTOM_HEADER)).thenReturn(null); - Mockito.when(mockReq.getHeader(RangerCSRFPreventionFilter.HEADER_USER_AGENT)).thenReturn(userAgent); - - // Objects to verify interactions based on request - HttpServletResponse mockRes = Mockito.mock(HttpServletResponse.class); - FilterChain mockChain = Mockito.mock(FilterChain.class); - - // Object under test - RangerCSRFPreventionFilter filter = new RangerCSRFPreventionFilter(); - filter.doFilter(mockReq, mockRes, mockChain); - - Mockito.verifyZeroInteractions(mockChain); - } - - @Test - public void testMissingHeaderIgnoreGETMethodConfig_goodRequest() - throws ServletException, IOException { - // CSRF has not been sent - HttpServletRequest mockReq = Mockito.mock(HttpServletRequest.class); - Mockito.when(mockReq.getHeader(RangerCSRFPreventionFilter.HEADER_DEFAULT)).thenReturn(null); - Mockito.when(mockReq.getMethod()).thenReturn("GET"); - Mockito.when(mockReq.getHeader(RangerCSRFPreventionFilter.HEADER_USER_AGENT)).thenReturn(userAgent); - - // Objects to verify interactions based on request - HttpServletResponse mockRes = Mockito.mock(HttpServletResponse.class); - FilterChain mockChain = Mockito.mock(FilterChain.class); - - // Object under test - RangerCSRFPreventionFilter filter = new RangerCSRFPreventionFilter(); - filter.doFilter(mockReq, mockRes, mockChain); - - Mockito.verify(mockChain).doFilter(mockReq, mockRes); - } - - @Test - public void testMissingHeaderMultipleIgnoreMethodsConfig_badRequest() - throws ServletException, IOException { - // CSRF has not been sent - HttpServletRequest mockReq = Mockito.mock(HttpServletRequest.class); - Mockito.when(mockReq.getHeader(RangerCSRFPreventionFilter.HEADER_DEFAULT)) - .thenReturn(null); - Mockito.when(mockReq.getMethod()).thenReturn("PUT"); - Mockito.when(mockReq.getHeader(RangerCSRFPreventionFilter.HEADER_USER_AGENT)).thenReturn(userAgent); - - // Objects to verify interactions based on request - HttpServletResponse mockRes = Mockito.mock(HttpServletResponse.class); - FilterChain mockChain = Mockito.mock(FilterChain.class); - - // Object under test - RangerCSRFPreventionFilter filter = new RangerCSRFPreventionFilter(); - filter.doFilter(mockReq, mockRes, mockChain); - - Mockito.verifyZeroInteractions(mockChain); - } + private static final String EXPECTED_MESSAGE = "Missing header or invalid Header value for CSRF Vulnerability Protection"; + private static final String X_CUSTOM_HEADER = "X-CUSTOM_HEADER"; + private final String userAgent = "Mozilla"; + + @Test + public void testNoHeaderDefaultConfig_badRequest() throws ServletException, IOException { + // CSRF has not been sent + HttpServletRequest mockReq = Mockito.mock(HttpServletRequest.class); + Mockito.when(mockReq.getHeader(RangerCSRFPreventionFilter.HEADER_DEFAULT)).thenReturn(null); + Mockito.when(mockReq.getHeader(RangerCSRFPreventionFilter.HEADER_USER_AGENT)).thenReturn(userAgent); + + Mockito.when(mockReq.getMethod()).thenReturn("POST"); + + HttpSession session = Mockito.mock(HttpSession.class); + Mockito.when(session.getAttribute(RangerCSRFPreventionFilter.CSRF_TOKEN)).thenReturn("valueUnimportant"); + Mockito.when(mockReq.getSession()).thenReturn(session); + + // Objects to verify interactions based on request + HttpServletResponse mockRes = Mockito.mock(HttpServletResponse.class); + FilterChain mockChain = Mockito.mock(FilterChain.class); + + // Object under test + RangerCSRFPreventionFilter filter = new RangerCSRFPreventionFilter(); + filter.doFilter(mockReq, mockRes, mockChain); + + Mockito.verify(mockRes, atLeastOnce()).sendError(HttpServletResponse.SC_BAD_REQUEST, EXPECTED_MESSAGE); + Mockito.verifyZeroInteractions(mockChain); + } + + @Test + public void testHeaderPresentDefaultConfig_goodRequest() throws ServletException, IOException { + // CSRF HAS been sent + HttpServletRequest mockReq = Mockito.mock(HttpServletRequest.class); + Mockito.when(mockReq.getHeader(RangerCSRFPreventionFilter.HEADER_DEFAULT)).thenReturn("valueUnimportant"); + Mockito.when(mockReq.getHeader(RangerCSRFPreventionFilter.HEADER_USER_AGENT)).thenReturn(userAgent); + + Mockito.when(mockReq.getMethod()).thenReturn("POST"); + + HttpSession session = Mockito.mock(HttpSession.class); + Mockito.when(session.getAttribute(RangerCSRFPreventionFilter.CSRF_TOKEN)).thenReturn("valueUnimportant"); + Mockito.when(mockReq.getSession()).thenReturn(session); + + // Objects to verify interactions based on request + HttpServletResponse mockRes = Mockito.mock(HttpServletResponse.class); + FilterChain mockChain = Mockito.mock(FilterChain.class); + + // Object under test + RangerCSRFPreventionFilter filter = new RangerCSRFPreventionFilter(); + filter.doFilter(mockReq, mockRes, mockChain); + + Mockito.verify(mockChain).doFilter(mockReq, mockRes); + } + + @Test + public void testHeaderPresentDefaultConfig_badRequest() throws ServletException, IOException { + // CSRF HAS been sent + HttpServletRequest mockReq = Mockito.mock(HttpServletRequest.class); + Mockito.when(mockReq.getHeader(RangerCSRFPreventionFilter.HEADER_DEFAULT)).thenReturn("valueUnimportant"); + Mockito.when(mockReq.getHeader(RangerCSRFPreventionFilter.HEADER_USER_AGENT)).thenReturn(userAgent); + Mockito.when(mockReq.getMethod()).thenReturn("POST"); + + // Objects to verify interactions based on request + HttpServletResponse mockRes = Mockito.mock(HttpServletResponse.class); + PrintWriter mockWriter = Mockito.mock(PrintWriter.class); + Mockito.when(mockRes.getWriter()).thenReturn(mockWriter); + + FilterChain mockChain = Mockito.mock(FilterChain.class); + + // Object under test + RangerCSRFPreventionFilter filter = new RangerCSRFPreventionFilter(); + filter.doFilter(mockReq, mockRes, mockChain); + + Mockito.verify(mockChain, Mockito.never()).doFilter(mockReq, mockRes); + } + + @Test + public void testHeaderPresentCustomHeaderConfig_goodRequest() throws ServletException, IOException { + // CSRF HAS been sent + HttpServletRequest mockReq = Mockito.mock(HttpServletRequest.class); + Mockito.when(mockReq.getHeader(X_CUSTOM_HEADER)).thenReturn("valueUnimportant"); + + // Objects to verify interactions based on request + HttpServletResponse mockRes = Mockito.mock(HttpServletResponse.class); + FilterChain mockChain = Mockito.mock(FilterChain.class); + + // Object under test + RangerCSRFPreventionFilter filter = new RangerCSRFPreventionFilter(); + filter.doFilter(mockReq, mockRes, mockChain); + + Mockito.verify(mockChain).doFilter(mockReq, mockRes); + } + + @Test + public void testMissingHeaderWithCustomHeaderConfig_badRequest() throws ServletException, IOException { + // CSRF has not been sent + HttpServletRequest mockReq = Mockito.mock(HttpServletRequest.class); + Mockito.when(mockReq.getHeader(X_CUSTOM_HEADER)).thenReturn(null); + Mockito.when(mockReq.getHeader(RangerCSRFPreventionFilter.HEADER_USER_AGENT)).thenReturn(userAgent); + + // Objects to verify interactions based on request + HttpServletResponse mockRes = Mockito.mock(HttpServletResponse.class); + FilterChain mockChain = Mockito.mock(FilterChain.class); + + // Object under test + RangerCSRFPreventionFilter filter = new RangerCSRFPreventionFilter(); + filter.doFilter(mockReq, mockRes, mockChain); + + Mockito.verifyZeroInteractions(mockChain); + } + + @Test + public void testMissingHeaderIgnoreGETMethodConfig_goodRequest() throws ServletException, IOException { + // CSRF has not been sent + HttpServletRequest mockReq = Mockito.mock(HttpServletRequest.class); + Mockito.when(mockReq.getHeader(RangerCSRFPreventionFilter.HEADER_DEFAULT)).thenReturn(null); + Mockito.when(mockReq.getMethod()).thenReturn("GET"); + Mockito.when(mockReq.getHeader(RangerCSRFPreventionFilter.HEADER_USER_AGENT)).thenReturn(userAgent); + + // Objects to verify interactions based on request + HttpServletResponse mockRes = Mockito.mock(HttpServletResponse.class); + FilterChain mockChain = Mockito.mock(FilterChain.class); + + // Object under test + RangerCSRFPreventionFilter filter = new RangerCSRFPreventionFilter(); + filter.doFilter(mockReq, mockRes, mockChain); + + Mockito.verify(mockChain).doFilter(mockReq, mockRes); + } + + @Test + public void testMissingHeaderMultipleIgnoreMethodsConfig_badRequest() throws ServletException, IOException { + // CSRF has not been sent + HttpServletRequest mockReq = Mockito.mock(HttpServletRequest.class); + Mockito.when(mockReq.getHeader(RangerCSRFPreventionFilter.HEADER_DEFAULT)).thenReturn(null); + Mockito.when(mockReq.getMethod()).thenReturn("PUT"); + Mockito.when(mockReq.getHeader(RangerCSRFPreventionFilter.HEADER_USER_AGENT)).thenReturn(userAgent); + + // Objects to verify interactions based on request + HttpServletResponse mockRes = Mockito.mock(HttpServletResponse.class); + FilterChain mockChain = Mockito.mock(FilterChain.class); + + // Object under test + RangerCSRFPreventionFilter filter = new RangerCSRFPreventionFilter(); + filter.doFilter(mockReq, mockRes, mockChain); + + Mockito.verifyZeroInteractions(mockChain); + } } diff --git a/security-admin/src/test/java/org/apache/ranger/security/web/filter/TestRangerMDCFilter.java b/security-admin/src/test/java/org/apache/ranger/security/web/filter/TestRangerMDCFilter.java index d89a1fd59e..bfc8610728 100644 --- a/security-admin/src/test/java/org/apache/ranger/security/web/filter/TestRangerMDCFilter.java +++ b/security-admin/src/test/java/org/apache/ranger/security/web/filter/TestRangerMDCFilter.java @@ -19,16 +19,17 @@ package org.apache.ranger.security.web.filter; -import java.io.IOException; +import org.junit.Test; +import org.mockito.Mockito; + import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import org.junit.Test; -import org.mockito.Mockito; -public class TestRangerMDCFilter { +import java.io.IOException; +public class TestRangerMDCFilter { @Test public void testRequestContainRequestIdHeader() throws ServletException, IOException { HttpServletRequest mockReq = Mockito.mock(HttpServletRequest.class); diff --git a/security-admin/src/test/java/org/apache/ranger/service/PasswordComparisonAuthenticator.java b/security-admin/src/test/java/org/apache/ranger/service/PasswordComparisonAuthenticator.java index e6e91c3a2a..daea29d751 100644 --- a/security-admin/src/test/java/org/apache/ranger/service/PasswordComparisonAuthenticator.java +++ b/security-admin/src/test/java/org/apache/ranger/service/PasswordComparisonAuthenticator.java @@ -1,22 +1,24 @@ -/* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR 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.service; -import java.util.Iterator; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.ldap.NameNotFoundException; @@ -32,6 +34,8 @@ import org.springframework.security.ldap.authentication.AbstractLdapAuthenticator; import org.springframework.util.Assert; +import java.util.Iterator; + /** * An {@link org.springframework.security.providers.ldap.LdapAuthenticator * LdapAuthenticator} which compares the login password with the value stored in @@ -44,92 +48,81 @@ * * @author Luke Taylor * @version $Id: PasswordComparisonAuthenticator.java 2729 2008-03-13 16:49:19Z - * luke_t $ + * luke_t $ */ -public final class PasswordComparisonAuthenticator extends - AbstractLdapAuthenticator { - // ~ Static fields/initializers - // ===================================================================================== - - private static final Logger logger = LoggerFactory - .getLogger(PasswordComparisonAuthenticator.class); - - // ~ Instance fields - // ================================================================================================ - - private PasswordEncoder passwordEncoder = new LdapShaPasswordEncoder(); - private String passwordAttributeName = "userPassword"; - - // ~ Constructors - // =================================================================================================== - - public PasswordComparisonAuthenticator( - BaseLdapPathContextSource contextSource) { - super(contextSource); - } - - // ~ Methods - // ======================================================================================================== - - public DirContextOperations authenticate(final Authentication authentication) { - Assert.isInstanceOf(UsernamePasswordAuthenticationToken.class, - authentication, - "Can only process UsernamePasswordAuthenticationToken objects"); - // locate the user and check the password - - DirContextOperations user = null; - String username = authentication.getName(); - String password = (String) authentication.getCredentials(); - - Iterator dns = getUserDns(username).iterator(); - - SpringSecurityLdapTemplate ldapTemplate = new SpringSecurityLdapTemplate( - getContextSource()); - - while (dns.hasNext() && user == null) { - final String userDn = (String) dns.next(); - - try { - user = ldapTemplate.retrieveEntry(userDn, getUserAttributes()); - } catch (NameNotFoundException ignore) { - } - } - - if (user == null && getUserSearch() != null) { - user = getUserSearch().searchForUser(username); - } - - if (user == null) { - throw new UsernameNotFoundException("User not found: " + username); - } - - if (logger.isDebugEnabled()) { - logger.debug("Performing LDAP compare of password attribute '" - + passwordAttributeName + "' for user '" + user.getDn() - + "'"); - } - - String encodedPassword = passwordEncoder.encode(password); - byte[] passwordBytes = encodedPassword.getBytes(); - - if (!ldapTemplate.compare(user.getDn().toString(), - passwordAttributeName, passwordBytes)) { - throw new BadCredentialsException(messages.getMessage( - "PasswordComparisonAuthenticator.badCredentials", - "Bad credentials")); - } - - return user; - } - - public void setPasswordAttributeName(String passwordAttribute) { - Assert.hasLength(passwordAttribute, - "passwordAttributeName must not be empty or null"); - this.passwordAttributeName = passwordAttribute; - } - - public void setPasswordEncoder(PasswordEncoder passwordEncoder) { - Assert.notNull(passwordEncoder, "passwordEncoder must not be null."); - this.passwordEncoder = passwordEncoder; - } +public final class PasswordComparisonAuthenticator extends AbstractLdapAuthenticator { + // ~ Static fields/initializers + // ===================================================================================== + + private static final Logger logger = LoggerFactory.getLogger(PasswordComparisonAuthenticator.class); + + // ~ Instance fields + // ================================================================================================ + + private PasswordEncoder passwordEncoder = new LdapShaPasswordEncoder(); + private String passwordAttributeName = "userPassword"; + + // ~ Constructors + // =================================================================================================== + + public PasswordComparisonAuthenticator( + BaseLdapPathContextSource contextSource) { + super(contextSource); + } + + // ~ Methods + // ======================================================================================================== + + public DirContextOperations authenticate(final Authentication authentication) { + Assert.isInstanceOf(UsernamePasswordAuthenticationToken.class, authentication, "Can only process UsernamePasswordAuthenticationToken objects"); + // locate the user and check the password + + DirContextOperations user = null; + String username = authentication.getName(); + String password = (String) authentication.getCredentials(); + + Iterator dns = getUserDns(username).iterator(); + + SpringSecurityLdapTemplate ldapTemplate = new SpringSecurityLdapTemplate(getContextSource()); + + while (dns.hasNext() && user == null) { + final String userDn = (String) dns.next(); + + try { + user = ldapTemplate.retrieveEntry(userDn, getUserAttributes()); + } catch (NameNotFoundException ignore) { + } + } + + if (user == null && getUserSearch() != null) { + user = getUserSearch().searchForUser(username); + } + + if (user == null) { + throw new UsernameNotFoundException("User not found: " + username); + } + + if (logger.isDebugEnabled()) { + logger.debug("Performing LDAP compare of password attribute '{}' for user '{}'", passwordAttributeName, user.getDn()); + } + + String encodedPassword = passwordEncoder.encode(password); + byte[] passwordBytes = encodedPassword.getBytes(); + + if (!ldapTemplate.compare(user.getDn().toString(), passwordAttributeName, passwordBytes)) { + throw new BadCredentialsException(messages.getMessage("PasswordComparisonAuthenticator.badCredentials", "Bad credentials")); + } + + return user; + } + + public void setPasswordAttributeName(String passwordAttribute) { + Assert.hasLength(passwordAttribute, "passwordAttributeName must not be empty or null"); + this.passwordAttributeName = passwordAttribute; + } + + public void setPasswordEncoder(PasswordEncoder passwordEncoder) { + Assert.notNull(passwordEncoder, "passwordEncoder must not be null."); + this.passwordEncoder = passwordEncoder; + } } diff --git a/security-admin/src/test/java/org/apache/ranger/service/TestAuthSessionService.java b/security-admin/src/test/java/org/apache/ranger/service/TestAuthSessionService.java index 292777e854..8d98b68033 100644 --- a/security-admin/src/test/java/org/apache/ranger/service/TestAuthSessionService.java +++ b/security-admin/src/test/java/org/apache/ranger/service/TestAuthSessionService.java @@ -19,16 +19,11 @@ package org.apache.ranger.service; -import javax.persistence.EntityManager; - import org.apache.ranger.common.SearchCriteria; - import org.apache.ranger.common.SearchUtil; - import org.apache.ranger.common.db.BaseDao; import org.apache.ranger.entity.XXAuthSession; import org.apache.ranger.view.VXAuthSession; - import org.junit.FixMethodOrder; import org.junit.Test; import org.junit.runner.RunWith; @@ -41,60 +36,59 @@ @RunWith(MockitoJUnitRunner.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class TestAuthSessionService { - @InjectMocks - AuthSessionService authSessionService = new AuthSessionService(); - - @Mock - VXAuthSession vXAuthSession; - - @Mock - XXAuthSession mObj; - - @Mock - XXAuthSession xXAuthSession; - - @Mock - SearchCriteria searchCriteria; - - @Mock - SearchUtil searchUtil; - - @Mock - BaseDao entityDao; - - @Test - public void test1GetResourceName() { - authSessionService.getResourceName(); - } - - @Test - public void test2CreateEntityObject() { - authSessionService.createEntityObject(); - } - - @Test - public void test3CreateViewObject() { - authSessionService.createViewObject(); - } - - @Test - public void test4search() { - SearchCriteria testSearchCriteria = createsearchCriteria(); - EntityManager em = null; - Mockito.when(authSessionService.getDao().getEntityManager()).thenReturn(em); - authSessionService.search(testSearchCriteria); - } - - private SearchCriteria createsearchCriteria() { - SearchCriteria testsearchCriteria = new SearchCriteria(); - testsearchCriteria.setStartIndex(0); - testsearchCriteria.setMaxRows(Integer.MAX_VALUE); - testsearchCriteria.setSortBy("id"); - testsearchCriteria.setSortType("asc"); - testsearchCriteria.setGetCount(true); - testsearchCriteria.setOwnerId(null); - testsearchCriteria.setGetChildren(false); - testsearchCriteria.setDistinct(false); - return testsearchCriteria; - } + @InjectMocks + AuthSessionService authSessionService = new AuthSessionService(); + + @Mock + VXAuthSession vXAuthSession; + + @Mock + XXAuthSession mObj; + + @Mock + XXAuthSession xXAuthSession; + + @Mock + SearchCriteria searchCriteria; + + @Mock + SearchUtil searchUtil; + + @Mock + BaseDao entityDao; + + @Test + public void test1GetResourceName() { + authSessionService.getResourceName(); + } + + @Test + public void test2CreateEntityObject() { + authSessionService.createEntityObject(); + } + + @Test + public void test3CreateViewObject() { + authSessionService.createViewObject(); + } + + @Test + public void test4search() { + SearchCriteria testSearchCriteria = createsearchCriteria(); + Mockito.when(authSessionService.getDao().getEntityManager()).thenReturn(null); + authSessionService.search(testSearchCriteria); + } + + private SearchCriteria createsearchCriteria() { + SearchCriteria testsearchCriteria = new SearchCriteria(); + testsearchCriteria.setStartIndex(0); + testsearchCriteria.setMaxRows(Integer.MAX_VALUE); + testsearchCriteria.setSortBy("id"); + testsearchCriteria.setSortType("asc"); + testsearchCriteria.setGetCount(true); + testsearchCriteria.setOwnerId(null); + testsearchCriteria.setGetChildren(false); + testsearchCriteria.setDistinct(false); + return testsearchCriteria; + } } diff --git a/security-admin/src/test/java/org/apache/ranger/service/TestRangerAuditFields.java b/security-admin/src/test/java/org/apache/ranger/service/TestRangerAuditFields.java index 1d71bc3f1a..bfa2466efd 100644 --- a/security-admin/src/test/java/org/apache/ranger/service/TestRangerAuditFields.java +++ b/security-admin/src/test/java/org/apache/ranger/service/TestRangerAuditFields.java @@ -1,16 +1,20 @@ -/* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR 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.service; @@ -27,22 +31,19 @@ @RunWith(MockitoJUnitRunner.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class TestRangerAuditFields { + @InjectMocks + RangerAuditFields rangerAuditFields; - @InjectMocks - RangerAuditFields rangerAuditFields; - - @Mock - XXDBBase XXDBBase; - - @Test - public void test1PopulateAuditFields() { - rangerAuditFields.populateAuditFields(XXDBBase, XXDBBase); - } - - @Test - public void test2PopulateAuditFieldsForCreate() { + @Mock + XXDBBase xxDBBase; - rangerAuditFields.populateAuditFieldsForCreate(XXDBBase); - } + @Test + public void test1PopulateAuditFields() { + rangerAuditFields.populateAuditFields(xxDBBase, xxDBBase); + } + @Test + public void test2PopulateAuditFieldsForCreate() { + rangerAuditFields.populateAuditFieldsForCreate(xxDBBase); + } } diff --git a/security-admin/src/test/java/org/apache/ranger/service/TestRangerDataHistService.java b/security-admin/src/test/java/org/apache/ranger/service/TestRangerDataHistService.java index 65e273c4ea..0b42cbb6da 100644 --- a/security-admin/src/test/java/org/apache/ranger/service/TestRangerDataHistService.java +++ b/security-admin/src/test/java/org/apache/ranger/service/TestRangerDataHistService.java @@ -1,16 +1,20 @@ -/* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR 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.service; @@ -29,24 +33,22 @@ @RunWith(MockitoJUnitRunner.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class TestRangerDataHistService { - - @InjectMocks - RangerDataHistService rangerDataHistService; - - @Mock - RangerBaseModelObject baseModelObj; - - @Mock - RangerDaoManager daoMgr; - @Mock - org.apache.ranger.db.XXDataHistDao XXDataHistDao; - - @Test - public void test1CreateObjectDataHistory() { - String action = "create"; - RangerBaseModelObject baseModelObj = new RangerBaseModelObject(); - Mockito.when(daoMgr.getXXDataHist()).thenReturn(XXDataHistDao); - rangerDataHistService.createObjectDataHistory(baseModelObj, action); - - } + @InjectMocks + RangerDataHistService rangerDataHistService; + + @Mock + RangerBaseModelObject baseModelObj; + + @Mock + RangerDaoManager daoMgr; + @Mock + org.apache.ranger.db.XXDataHistDao xxDataHistDao; + + @Test + public void test1CreateObjectDataHistory() { + String action = "create"; + RangerBaseModelObject baseModelObj = new RangerBaseModelObject(); + Mockito.when(daoMgr.getXXDataHist()).thenReturn(xxDataHistDao); + rangerDataHistService.createObjectDataHistory(baseModelObj, action); + } } diff --git a/security-admin/src/test/java/org/apache/ranger/service/TestRangerPolicyService.java b/security-admin/src/test/java/org/apache/ranger/service/TestRangerPolicyService.java index c97835b0bf..dbffb8f8b9 100644 --- a/security-admin/src/test/java/org/apache/ranger/service/TestRangerPolicyService.java +++ b/security-admin/src/test/java/org/apache/ranger/service/TestRangerPolicyService.java @@ -16,12 +16,6 @@ */ package org.apache.ranger.service; -import java.util.ArrayList; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - import org.apache.ranger.biz.RangerBizUtil; import org.apache.ranger.common.ContextUtil; import org.apache.ranger.common.JSONUtil; @@ -47,122 +41,117 @@ import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; +import java.util.ArrayList; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + @RunWith(MockitoJUnitRunner.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class TestRangerPolicyService { - - private static Long Id = 8L; - - @InjectMocks - RangerPolicyService policyService = new RangerPolicyService(); - - @Mock - RangerDaoManager daoManager; - - @Mock - RangerServiceService svcService; - - @Mock - JSONUtil jsonUtil; - - @Mock - RangerServiceDefService serviceDefService; - - @Mock - StringUtil stringUtil; - - @Mock - XUserService xUserService; - - @Mock - RangerBizUtil bizUtil; - - @Rule - public ExpectedException thrown = ExpectedException.none(); - - public void setup() { - RangerSecurityContext context = new RangerSecurityContext(); - context.setUserSession(new UserSessionBase()); - RangerContextHolder.setSecurityContext(context); - UserSessionBase currentUserSession = ContextUtil - .getCurrentUserSession(); - currentUserSession.setUserAdmin(true); - } - - private RangerPolicy rangerPolicy() { - List accesses = new ArrayList(); - List users = new ArrayList(); - List groups = new ArrayList(); - List conditions = new ArrayList(); - List policyItems = new ArrayList(); - RangerPolicyItem rangerPolicyItem = new RangerPolicyItem(); - rangerPolicyItem.setAccesses(accesses); - rangerPolicyItem.setConditions(conditions); - rangerPolicyItem.setGroups(groups); - rangerPolicyItem.setUsers(users); - rangerPolicyItem.setDelegateAdmin(false); - - policyItems.add(rangerPolicyItem); - - Map policyResource = new HashMap(); - RangerPolicyResource rangerPolicyResource = new RangerPolicyResource(); - rangerPolicyResource.setIsExcludes(true); - rangerPolicyResource.setIsRecursive(true); - rangerPolicyResource.setValue("1"); - rangerPolicyResource.setValues(users); - RangerPolicy policy = new RangerPolicy(); - policy.setId(Id); - policy.setCreateTime(new Date()); - policy.setDescription("policy"); - policy.setGuid("policyguid"); - policy.setIsEnabled(true); - policy.setName("HDFS_1-1-20150316062453"); - policy.setUpdatedBy("Admin"); - policy.setUpdateTime(new Date()); - policy.setService("HDFS_1-1-20150316062453"); - policy.setIsAuditEnabled(true); - policy.setPolicyItems(policyItems); - policy.setResources(policyResource); - policy.setPolicyType(0); - - return policy; - } - - private XXPolicy policy() { - XXPolicy xxPolicy = new XXPolicy(); - xxPolicy.setId(Id); - xxPolicy.setName("HDFS_1-1-20150316062453"); - xxPolicy.setAddedByUserId(Id); - xxPolicy.setCreateTime(new Date()); - xxPolicy.setDescription("test"); - xxPolicy.setIsAuditEnabled(false); - xxPolicy.setIsEnabled(false); - xxPolicy.setService(1L); - xxPolicy.setUpdatedByUserId(Id); - xxPolicy.setUpdateTime(new Date()); - return xxPolicy; - } - - @Test - public void test1ValidateForCreate() { - RangerPolicy rangerPolicy = rangerPolicy(); - policyService.validateForCreate(rangerPolicy); - Assert.assertNotNull(rangerPolicy); - } - - @Test - public void test2ValidateForUpdate() { - RangerPolicy rangerPolicy = rangerPolicy(); - XXPolicy policy = policy(); - policyService.validateForUpdate(rangerPolicy, policy); - - Assert.assertNotNull(rangerPolicy); - } - - @Test - public void test8getTransactionLog() { - RangerPolicy rangerPolicy = rangerPolicy(); - - policyService.createTransactionLog(rangerPolicy, null, 1); - } + private static final Long Id = 8L; + @Rule + public ExpectedException thrown = ExpectedException.none(); + @InjectMocks + RangerPolicyService policyService = new RangerPolicyService(); + @Mock + RangerDaoManager daoManager; + @Mock + RangerServiceService svcService; + @Mock + JSONUtil jsonUtil; + @Mock + RangerServiceDefService serviceDefService; + @Mock + StringUtil stringUtil; + @Mock + XUserService xUserService; + @Mock + RangerBizUtil bizUtil; + + public void setup() { + RangerSecurityContext context = new RangerSecurityContext(); + context.setUserSession(new UserSessionBase()); + RangerContextHolder.setSecurityContext(context); + UserSessionBase currentUserSession = ContextUtil.getCurrentUserSession(); + currentUserSession.setUserAdmin(true); + } + + @Test + public void test1ValidateForCreate() { + RangerPolicy rangerPolicy = rangerPolicy(); + policyService.validateForCreate(rangerPolicy); + Assert.assertNotNull(rangerPolicy); + } + + @Test + public void test2ValidateForUpdate() { + RangerPolicy rangerPolicy = rangerPolicy(); + XXPolicy policy = policy(); + policyService.validateForUpdate(rangerPolicy, policy); + + Assert.assertNotNull(rangerPolicy); + } + + @Test + public void test8getTransactionLog() { + RangerPolicy rangerPolicy = rangerPolicy(); + + policyService.createTransactionLog(rangerPolicy, null, 1); + } + + private RangerPolicy rangerPolicy() { + List accesses = new ArrayList<>(); + List users = new ArrayList<>(); + List groups = new ArrayList<>(); + List conditions = new ArrayList<>(); + List policyItems = new ArrayList<>(); + RangerPolicyItem rangerPolicyItem = new RangerPolicyItem(); + rangerPolicyItem.setAccesses(accesses); + rangerPolicyItem.setConditions(conditions); + rangerPolicyItem.setGroups(groups); + rangerPolicyItem.setUsers(users); + rangerPolicyItem.setDelegateAdmin(false); + + policyItems.add(rangerPolicyItem); + + Map policyResource = new HashMap<>(); + RangerPolicyResource rangerPolicyResource = new RangerPolicyResource(); + rangerPolicyResource.setIsExcludes(true); + rangerPolicyResource.setIsRecursive(true); + rangerPolicyResource.setValue("1"); + rangerPolicyResource.setValues(users); + RangerPolicy policy = new RangerPolicy(); + policy.setId(Id); + policy.setCreateTime(new Date()); + policy.setDescription("policy"); + policy.setGuid("policyguid"); + policy.setIsEnabled(true); + policy.setName("HDFS_1-1-20150316062453"); + policy.setUpdatedBy("Admin"); + policy.setUpdateTime(new Date()); + policy.setService("HDFS_1-1-20150316062453"); + policy.setIsAuditEnabled(true); + policy.setPolicyItems(policyItems); + policy.setResources(policyResource); + policy.setPolicyType(0); + + return policy; + } + + private XXPolicy policy() { + XXPolicy xxPolicy = new XXPolicy(); + xxPolicy.setId(Id); + xxPolicy.setName("HDFS_1-1-20150316062453"); + xxPolicy.setAddedByUserId(Id); + xxPolicy.setCreateTime(new Date()); + xxPolicy.setDescription("test"); + xxPolicy.setIsAuditEnabled(false); + xxPolicy.setIsEnabled(false); + xxPolicy.setService(1L); + xxPolicy.setUpdatedByUserId(Id); + xxPolicy.setUpdateTime(new Date()); + return xxPolicy; + } } diff --git a/security-admin/src/test/java/org/apache/ranger/service/TestRangerPolicyServiceBase.java b/security-admin/src/test/java/org/apache/ranger/service/TestRangerPolicyServiceBase.java index 6422866d8f..bca06f23c9 100644 --- a/security-admin/src/test/java/org/apache/ranger/service/TestRangerPolicyServiceBase.java +++ b/security-admin/src/test/java/org/apache/ranger/service/TestRangerPolicyServiceBase.java @@ -16,12 +16,6 @@ */ package org.apache.ranger.service; -import java.util.ArrayList; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import javax.ws.rs.WebApplicationException; import org.apache.ranger.biz.RangerBizUtil; import org.apache.ranger.common.ContextUtil; import org.apache.ranger.common.MessageEnums; @@ -53,195 +47,174 @@ import org.mockito.Mockito; import org.mockito.junit.MockitoJUnitRunner; +import javax.ws.rs.WebApplicationException; + +import java.util.ArrayList; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + @RunWith(MockitoJUnitRunner.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class TestRangerPolicyServiceBase { - - private static Long Id = 8L; - - @InjectMocks - RangerPolicyService policyService = new RangerPolicyService(); - - @Mock - RangerDaoManager daoManager; - - @Mock - RESTErrorUtil restErrorUtil; - - @Mock - ContextUtil contextUtil; - - @Mock - RangerBizUtil rangerBizUtil; - - @Mock - RangerSearchUtil searchUtil; - - @Rule - public ExpectedException thrown = ExpectedException.none(); - - public void setup() { - RangerSecurityContext context = new RangerSecurityContext(); - context.setUserSession(new UserSessionBase()); - RangerContextHolder.setSecurityContext(context); - UserSessionBase currentUserSession = ContextUtil - .getCurrentUserSession(); - currentUserSession.setUserAdmin(true); - } - - private RangerPolicy rangerPolicy() { - List accesses = new ArrayList(); - List users = new ArrayList(); - List groups = new ArrayList(); - List conditions = new ArrayList(); - List policyItems = new ArrayList(); - RangerPolicyItem rangerPolicyItem = new RangerPolicyItem(); - rangerPolicyItem.setAccesses(accesses); - rangerPolicyItem.setConditions(conditions); - rangerPolicyItem.setGroups(groups); - rangerPolicyItem.setUsers(users); - rangerPolicyItem.setDelegateAdmin(false); - - policyItems.add(rangerPolicyItem); - - Map policyResource = new HashMap(); - RangerPolicyResource rangerPolicyResource = new RangerPolicyResource(); - rangerPolicyResource.setIsExcludes(true); - rangerPolicyResource.setIsRecursive(true); - rangerPolicyResource.setValue("1"); - rangerPolicyResource.setValues(users); - RangerPolicy policy = new RangerPolicy(); - policy.setId(Id); - policy.setCreateTime(new Date()); - policy.setDescription("policy"); - policy.setGuid("policyguid"); - policy.setIsEnabled(true); - policy.setName("HDFS_1-1-20150316062453"); - policy.setUpdatedBy("Admin"); - policy.setUpdateTime(new Date()); - policy.setService("HDFS_1-1-20150316062453"); - policy.setIsAuditEnabled(true); - policy.setPolicyItems(policyItems); - policy.setResources(policyResource); - policy.setZoneName(""); - - return policy; - } - - private XXPolicy policy() { - XXPolicy xxPolicy = new XXPolicy(); - xxPolicy.setId(Id); - xxPolicy.setName("HDFS_1-1-20150316062453"); - xxPolicy.setAddedByUserId(Id); - xxPolicy.setCreateTime(new Date()); - xxPolicy.setDescription("test"); - xxPolicy.setIsAuditEnabled(false); - xxPolicy.setIsEnabled(false); - xxPolicy.setService(1L); - xxPolicy.setUpdatedByUserId(Id); - xxPolicy.setUpdateTime(new Date()); - xxPolicy.setZoneId(1L); - return xxPolicy; - } - - @Test - public void test1mapViewToEntityBean() { - XXServiceDao xServiceDao = Mockito.mock(XXServiceDao.class); - XXService xService = Mockito.mock(XXService.class); - XXServiceDefDao xServiceDefDao = Mockito.mock(XXServiceDefDao.class); - XXServiceDef xServiceDef = Mockito.mock(XXServiceDef.class); - RangerPolicy rangerPolicy = rangerPolicy(); - XXPolicy policy = policy(); - int OPERATION_CONTEXT = 0; - - Mockito.when(daoManager.getXXService()).thenReturn(xServiceDao); - Mockito.when(xServiceDao.findByName(rangerPolicy.getService())) - .thenReturn(xService); - Mockito.when(daoManager.getXXServiceDef()).thenReturn(xServiceDefDao); - Mockito.when(xServiceDefDao.getById(xService.getType())).thenReturn(xServiceDef); - - XXPolicy dbPolicy = policyService.mapViewToEntityBean(rangerPolicy, - policy, OPERATION_CONTEXT); - Assert.assertNotNull(dbPolicy); - Assert.assertEquals(dbPolicy.getId(), policy.getId()); - Assert.assertEquals(dbPolicy.getGuid(), policy.getGuid()); - Assert.assertEquals(dbPolicy.getName(), policy.getName()); - Assert.assertEquals(dbPolicy.getAddedByUserId(), - policy.getAddedByUserId()); - Assert.assertEquals(dbPolicy.getIsEnabled(), policy.getIsEnabled()); - Assert.assertEquals(dbPolicy.getVersion(), policy.getVersion()); - Assert.assertEquals(dbPolicy.getDescription(), policy.getDescription()); - - Mockito.verify(daoManager).getXXService(); - } - - @Test - public void test2mapViewToEntityBeanNullValue() { - XXServiceDao xServiceDao = Mockito.mock(XXServiceDao.class); - RangerPolicy rangerPolicy = rangerPolicy(); - XXPolicy policy = policy(); - int OPERATION_CONTEXT = 0; - - Mockito.when( - restErrorUtil.createRESTException( - "No corresponding service found for policyName: " - + rangerPolicy.getName() - + "Service Not Found : " - + rangerPolicy.getName(), - MessageEnums.INVALID_INPUT_DATA)).thenThrow( - new WebApplicationException()); - - thrown.expect(WebApplicationException.class); - - Mockito.when(daoManager.getXXService()).thenReturn(xServiceDao); - Mockito.when(xServiceDao.findByName(rangerPolicy.getService())) - .thenReturn(null); - - XXPolicy dbPolicy = policyService.mapViewToEntityBean(rangerPolicy, - policy, OPERATION_CONTEXT); - Assert.assertNotNull(dbPolicy); - Assert.assertEquals(dbPolicy.getId(), policy.getId()); - Assert.assertEquals(dbPolicy.getGuid(), policy.getGuid()); - Assert.assertEquals(dbPolicy.getName(), policy.getName()); - Assert.assertEquals(dbPolicy.getAddedByUserId(), - policy.getAddedByUserId()); - Assert.assertEquals(dbPolicy.getIsEnabled(), policy.getIsEnabled()); - Assert.assertEquals(dbPolicy.getVersion(), policy.getVersion()); - Assert.assertEquals(dbPolicy.getDescription(), policy.getDescription()); - - Mockito.verify(daoManager).getXXService(); - } - - @Test - public void test3mapEntityToViewBean() { - XXServiceDao xServiceDao = Mockito.mock(XXServiceDao.class); - XXService xService = Mockito.mock(XXService.class); - XXServiceDefDao xServiceDefDao = Mockito.mock(XXServiceDefDao.class); - XXServiceDef xServiceDef = Mockito.mock(XXServiceDef.class); - RangerPolicy rangerPolicy = rangerPolicy(); - XXPolicy policy = policy(); - - Mockito.when(daoManager.getXXService()).thenReturn(xServiceDao); - Mockito.when(xServiceDao.getById(policy.getService())).thenReturn( - xService); - Mockito.when(daoManager.getXXServiceDef()).thenReturn(xServiceDefDao); - Mockito.when(xServiceDefDao.getById(xService.getType())).thenReturn( - xServiceDef); - RangerPolicy dbRangerPolicy = policyService.mapEntityToViewBean( - rangerPolicy, policy); - - Assert.assertNotNull(dbRangerPolicy); - Assert.assertEquals(dbRangerPolicy.getId(), rangerPolicy.getId()); - Assert.assertEquals(dbRangerPolicy.getGuid(), rangerPolicy.getGuid()); - Assert.assertEquals(dbRangerPolicy.getName(), rangerPolicy.getName()); - Assert.assertEquals(dbRangerPolicy.getIsEnabled(), - rangerPolicy.getIsEnabled()); - Assert.assertEquals(dbRangerPolicy.getVersion(), - rangerPolicy.getVersion()); - Assert.assertEquals(dbRangerPolicy.getDescription(), - rangerPolicy.getDescription()); - - Mockito.verify(daoManager).getXXService(); - } - + private static final Long Id = 8L; + @Rule + public ExpectedException thrown = ExpectedException.none(); + @InjectMocks + RangerPolicyService policyService = new RangerPolicyService(); + @Mock + RangerDaoManager daoManager; + @Mock + RESTErrorUtil restErrorUtil; + @Mock + ContextUtil contextUtil; + @Mock + RangerBizUtil rangerBizUtil; + @Mock + RangerSearchUtil searchUtil; + + public void setup() { + RangerSecurityContext context = new RangerSecurityContext(); + context.setUserSession(new UserSessionBase()); + RangerContextHolder.setSecurityContext(context); + UserSessionBase currentUserSession = ContextUtil.getCurrentUserSession(); + currentUserSession.setUserAdmin(true); + } + + @Test + public void test1mapViewToEntityBean() { + XXServiceDao xServiceDao = Mockito.mock(XXServiceDao.class); + XXService xService = Mockito.mock(XXService.class); + XXServiceDefDao xServiceDefDao = Mockito.mock(XXServiceDefDao.class); + XXServiceDef xServiceDef = Mockito.mock(XXServiceDef.class); + RangerPolicy rangerPolicy = rangerPolicy(); + XXPolicy policy = policy(); + int operationContext = 0; + + Mockito.when(daoManager.getXXService()).thenReturn(xServiceDao); + Mockito.when(xServiceDao.findByName(rangerPolicy.getService())).thenReturn(xService); + Mockito.when(daoManager.getXXServiceDef()).thenReturn(xServiceDefDao); + Mockito.when(xServiceDefDao.getById(xService.getType())).thenReturn(xServiceDef); + + XXPolicy dbPolicy = policyService.mapViewToEntityBean(rangerPolicy, policy, operationContext); + Assert.assertNotNull(dbPolicy); + Assert.assertEquals(dbPolicy.getId(), policy.getId()); + Assert.assertEquals(dbPolicy.getGuid(), policy.getGuid()); + Assert.assertEquals(dbPolicy.getName(), policy.getName()); + Assert.assertEquals(dbPolicy.getAddedByUserId(), policy.getAddedByUserId()); + Assert.assertEquals(dbPolicy.getIsEnabled(), policy.getIsEnabled()); + Assert.assertEquals(dbPolicy.getVersion(), policy.getVersion()); + Assert.assertEquals(dbPolicy.getDescription(), policy.getDescription()); + + Mockito.verify(daoManager).getXXService(); + } + + @Test + public void test2mapViewToEntityBeanNullValue() { + XXServiceDao xServiceDao = Mockito.mock(XXServiceDao.class); + RangerPolicy rangerPolicy = rangerPolicy(); + XXPolicy policy = policy(); + int operationContext = 0; + + Mockito.when(restErrorUtil.createRESTException("No corresponding service found for policyName: " + rangerPolicy.getName() + "Service Not Found : " + rangerPolicy.getName(), MessageEnums.INVALID_INPUT_DATA)).thenThrow(new WebApplicationException()); + + thrown.expect(WebApplicationException.class); + + Mockito.when(daoManager.getXXService()).thenReturn(xServiceDao); + Mockito.when(xServiceDao.findByName(rangerPolicy.getService())).thenReturn(null); + + XXPolicy dbPolicy = policyService.mapViewToEntityBean(rangerPolicy, policy, operationContext); + Assert.assertNotNull(dbPolicy); + Assert.assertEquals(dbPolicy.getId(), policy.getId()); + Assert.assertEquals(dbPolicy.getGuid(), policy.getGuid()); + Assert.assertEquals(dbPolicy.getName(), policy.getName()); + Assert.assertEquals(dbPolicy.getAddedByUserId(), policy.getAddedByUserId()); + Assert.assertEquals(dbPolicy.getIsEnabled(), policy.getIsEnabled()); + Assert.assertEquals(dbPolicy.getVersion(), policy.getVersion()); + Assert.assertEquals(dbPolicy.getDescription(), policy.getDescription()); + + Mockito.verify(daoManager).getXXService(); + } + + @Test + public void test3mapEntityToViewBean() { + XXServiceDao xServiceDao = Mockito.mock(XXServiceDao.class); + XXService xService = Mockito.mock(XXService.class); + XXServiceDefDao xServiceDefDao = Mockito.mock(XXServiceDefDao.class); + XXServiceDef xServiceDef = Mockito.mock(XXServiceDef.class); + RangerPolicy rangerPolicy = rangerPolicy(); + XXPolicy policy = policy(); + + Mockito.when(daoManager.getXXService()).thenReturn(xServiceDao); + Mockito.when(xServiceDao.getById(policy.getService())).thenReturn(xService); + Mockito.when(daoManager.getXXServiceDef()).thenReturn(xServiceDefDao); + Mockito.when(xServiceDefDao.getById(xService.getType())).thenReturn(xServiceDef); + RangerPolicy dbRangerPolicy = policyService.mapEntityToViewBean(rangerPolicy, policy); + + Assert.assertNotNull(dbRangerPolicy); + Assert.assertEquals(dbRangerPolicy.getId(), rangerPolicy.getId()); + Assert.assertEquals(dbRangerPolicy.getGuid(), rangerPolicy.getGuid()); + Assert.assertEquals(dbRangerPolicy.getName(), rangerPolicy.getName()); + Assert.assertEquals(dbRangerPolicy.getIsEnabled(), rangerPolicy.getIsEnabled()); + Assert.assertEquals(dbRangerPolicy.getVersion(), rangerPolicy.getVersion()); + Assert.assertEquals(dbRangerPolicy.getDescription(), rangerPolicy.getDescription()); + + Mockito.verify(daoManager).getXXService(); + } + + private RangerPolicy rangerPolicy() { + List accesses = new ArrayList<>(); + List users = new ArrayList<>(); + List groups = new ArrayList<>(); + List conditions = new ArrayList<>(); + List policyItems = new ArrayList<>(); + RangerPolicyItem rangerPolicyItem = new RangerPolicyItem(); + rangerPolicyItem.setAccesses(accesses); + rangerPolicyItem.setConditions(conditions); + rangerPolicyItem.setGroups(groups); + rangerPolicyItem.setUsers(users); + rangerPolicyItem.setDelegateAdmin(false); + + policyItems.add(rangerPolicyItem); + + Map policyResource = new HashMap<>(); + RangerPolicyResource rangerPolicyResource = new RangerPolicyResource(); + rangerPolicyResource.setIsExcludes(true); + rangerPolicyResource.setIsRecursive(true); + rangerPolicyResource.setValue("1"); + rangerPolicyResource.setValues(users); + RangerPolicy policy = new RangerPolicy(); + policy.setId(Id); + policy.setCreateTime(new Date()); + policy.setDescription("policy"); + policy.setGuid("policyguid"); + policy.setIsEnabled(true); + policy.setName("HDFS_1-1-20150316062453"); + policy.setUpdatedBy("Admin"); + policy.setUpdateTime(new Date()); + policy.setService("HDFS_1-1-20150316062453"); + policy.setIsAuditEnabled(true); + policy.setPolicyItems(policyItems); + policy.setResources(policyResource); + policy.setZoneName(""); + + return policy; + } + + private XXPolicy policy() { + XXPolicy xxPolicy = new XXPolicy(); + xxPolicy.setId(Id); + xxPolicy.setName("HDFS_1-1-20150316062453"); + xxPolicy.setAddedByUserId(Id); + xxPolicy.setCreateTime(new Date()); + xxPolicy.setDescription("test"); + xxPolicy.setIsAuditEnabled(false); + xxPolicy.setIsEnabled(false); + xxPolicy.setService(1L); + xxPolicy.setUpdatedByUserId(Id); + xxPolicy.setUpdateTime(new Date()); + xxPolicy.setZoneId(1L); + return xxPolicy; + } } diff --git a/security-admin/src/test/java/org/apache/ranger/service/TestRangerServiceDefService.java b/security-admin/src/test/java/org/apache/ranger/service/TestRangerServiceDefService.java index 7894288549..e077fb91a3 100644 --- a/security-admin/src/test/java/org/apache/ranger/service/TestRangerServiceDefService.java +++ b/security-admin/src/test/java/org/apache/ranger/service/TestRangerServiceDefService.java @@ -16,21 +16,36 @@ */ package org.apache.ranger.service; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Date; -import java.util.List; - import org.apache.commons.lang.StringUtils; import org.apache.ranger.common.ContextUtil; import org.apache.ranger.common.JSONUtil; import org.apache.ranger.common.PropertiesUtil; import org.apache.ranger.common.StringUtil; import org.apache.ranger.common.UserSessionBase; -import org.apache.ranger.db.*; - -import org.apache.ranger.entity.*; - +import org.apache.ranger.db.RangerDaoManager; +import org.apache.ranger.db.XXAccessTypeDefDao; +import org.apache.ranger.db.XXAccessTypeDefGrantsDao; +import org.apache.ranger.db.XXContextEnricherDefDao; +import org.apache.ranger.db.XXDataMaskTypeDefDao; +import org.apache.ranger.db.XXEnumDefDao; +import org.apache.ranger.db.XXEnumElementDefDao; +import org.apache.ranger.db.XXPolicyConditionDefDao; +import org.apache.ranger.db.XXPortalUserDao; +import org.apache.ranger.db.XXResourceDefDao; +import org.apache.ranger.db.XXServiceConfigDefDao; +import org.apache.ranger.db.XXServiceDefDao; +import org.apache.ranger.entity.XXContextEnricherDef; +import org.apache.ranger.entity.XXDataMaskTypeDef; +import org.apache.ranger.entity.XXEnumDef; +import org.apache.ranger.entity.XXEnumElementDef; +import org.apache.ranger.entity.XXPolicyConditionDef; +import org.apache.ranger.entity.XXPolicyItem; +import org.apache.ranger.entity.XXPolicyItemAccess; +import org.apache.ranger.entity.XXPolicyItemCondition; +import org.apache.ranger.entity.XXPortalUser; +import org.apache.ranger.entity.XXResourceDef; +import org.apache.ranger.entity.XXServiceConfigDef; +import org.apache.ranger.entity.XXServiceDef; import org.apache.ranger.plugin.model.RangerServiceDef; import org.apache.ranger.plugin.model.RangerServiceDef.RangerAccessTypeDef; import org.apache.ranger.plugin.model.RangerServiceDef.RangerContextEnricherDef; @@ -53,754 +68,692 @@ import org.mockito.Mockito; import org.mockito.junit.MockitoJUnitRunner; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Date; +import java.util.List; + import static org.apache.ranger.service.RangerServiceDefService.PROP_ENABLE_IMPLICIT_CONDITION_EXPRESSION; @RunWith(MockitoJUnitRunner.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class TestRangerServiceDefService { - - private static Long Id = 8L; - - @InjectMocks - RangerServiceDefService serviceDefService = new RangerServiceDefService(); - - @Mock - RangerDaoManager daoManager; - - @Mock - JSONUtil jsonUtil; - - @Mock - RangerPolicyService policyService; - - @Mock - StringUtil stringUtil; - - @Mock - XUserService xUserService; - - @Mock - XXServiceDefDao xServiceDefDao; - - @Rule - public ExpectedException thrown = ExpectedException.none(); - - public void setup() { - RangerSecurityContext context = new RangerSecurityContext(); - context.setUserSession(new UserSessionBase()); - RangerContextHolder.setSecurityContext(context); - UserSessionBase currentUserSession = ContextUtil - .getCurrentUserSession(); - currentUserSession.setUserAdmin(true); - } - - private RangerServiceDef rangerServiceDef() { - List configs = new ArrayList(); - List resources = new ArrayList(); - List accessTypes = new ArrayList(); - List policyConditions = new ArrayList(); - List contextEnrichers = new ArrayList(); - List enums = new ArrayList(); - - RangerServiceDef rangerServiceDef = new RangerServiceDef(); - rangerServiceDef.setId(Id); - rangerServiceDef.setImplClass("RangerServiceHdfs"); - rangerServiceDef.setLabel("HDFS Repository"); - rangerServiceDef.setDescription("HDFS Repository"); - rangerServiceDef.setRbKeyDescription(null); - rangerServiceDef.setUpdatedBy("Admin"); - rangerServiceDef.setUpdateTime(new Date()); - rangerServiceDef.setConfigs(configs); - rangerServiceDef.setResources(resources); - rangerServiceDef.setAccessTypes(accessTypes); - rangerServiceDef.setPolicyConditions(policyConditions); - rangerServiceDef.setContextEnrichers(contextEnrichers); - rangerServiceDef.setEnums(enums); - - return rangerServiceDef; - } - - private XXServiceDef serviceDef() { - XXServiceDef xServiceDef = new XXServiceDef(); - xServiceDef.setAddedByUserId(Id); - xServiceDef.setCreateTime(new Date()); - xServiceDef.setDescription("HDFS Repository"); - xServiceDef.setGuid("1427365526516_835_0"); - xServiceDef.setId(Id); - xServiceDef.setUpdateTime(new Date()); - xServiceDef.setUpdatedByUserId(Id); - xServiceDef.setImplclassname("RangerServiceHdfs"); - xServiceDef.setLabel("HDFS Repository"); - xServiceDef.setRbkeylabel(null); - xServiceDef.setRbkeydescription(null); - xServiceDef.setIsEnabled(true); - - return xServiceDef; - } - - @Test - public void test1ValidateForCreate() { - RangerServiceDef rangerServiceDef = rangerServiceDef(); - serviceDefService.validateForCreate(rangerServiceDef); - Assert.assertNotNull(rangerServiceDef); - } - - @Test - public void test2ValidateForUpdate() { - RangerServiceDef rangerServiceDef = rangerServiceDef(); - XXServiceDef serviceDef = serviceDef(); - serviceDefService.validateForUpdate(rangerServiceDef, serviceDef); - - Assert.assertNotNull(rangerServiceDef); - } - - @Test - public void test3PopulateViewBean() { - - XXPortalUserDao xPortalUserDao = Mockito.mock(XXPortalUserDao.class); - XXResourceDefDao xResourceDefDao = Mockito.mock(XXResourceDefDao.class); - XXAccessTypeDefDao xAccessTypeDefDao = Mockito - .mock(XXAccessTypeDefDao.class); - XXAccessTypeDefGrantsDao xxAccessTypeDefGrantsDao = Mockito.mock(XXAccessTypeDefGrantsDao.class); - XXPolicyConditionDefDao xPolicyConditionDefDao = Mockito - .mock(XXPolicyConditionDefDao.class); - XXServiceConfigDefDao xServiceConfigDefDao = Mockito - .mock(XXServiceConfigDefDao.class); - XXContextEnricherDefDao xContextEnricherDefDao = Mockito - .mock(XXContextEnricherDefDao.class); - XXEnumDefDao xEnumDefDao = Mockito.mock(XXEnumDefDao.class); - XXEnumElementDefDao xEnumElementDefDao = Mockito - .mock(XXEnumElementDefDao.class); - - XXServiceDef serviceDef = serviceDef(); - - String name = "fdfdfds"; - XXPortalUser tUser = new XXPortalUser(); - tUser.setAddedByUserId(Id); - tUser.setCreateTime(new Date()); - tUser.setEmailAddress("test@gmail.com"); - tUser.setFirstName(name); - tUser.setId(Id); - tUser.setLastName(name); - - List resDefList = new ArrayList(); - XXResourceDef resourceDef = new XXResourceDef(); - resourceDef.setAddedByUserId(Id); - resourceDef.setCreateTime(new Date()); - resourceDef.setDefid(Id); - resourceDef.setDescription("test"); - resourceDef.setId(Id); - resDefList.add(resourceDef); - - List xPolicyItemList = new ArrayList(); - XXPolicyItem xPolicyItem = new XXPolicyItem(); - xPolicyItem.setDelegateAdmin(false); - xPolicyItem.setAddedByUserId(null); - xPolicyItem.setCreateTime(new Date()); - xPolicyItem.setGUID(null); - xPolicyItem.setId(Id); - xPolicyItem.setOrder(null); - xPolicyItem.setPolicyId(Id); - xPolicyItem.setUpdatedByUserId(null); - xPolicyItem.setUpdateTime(new Date()); - xPolicyItemList.add(xPolicyItem); - - List policyItemAccessList = new ArrayList(); - XXPolicyItemAccess policyItemAccess = new XXPolicyItemAccess(); - policyItemAccess.setAddedByUserId(Id); - policyItemAccess.setCreateTime(new Date()); - policyItemAccess.setPolicyitemid(Id); - policyItemAccess.setId(Id); - policyItemAccess.setOrder(1); - policyItemAccess.setUpdatedByUserId(Id); - policyItemAccess.setUpdateTime(new Date()); - policyItemAccessList.add(policyItemAccess); - - List xConditionDefList = new ArrayList(); - XXPolicyConditionDef policyConditionDefObj = new XXPolicyConditionDef(); - policyConditionDefObj.setAddedByUserId(Id); - policyConditionDefObj.setCreateTime(new Date()); - policyConditionDefObj.setDefid(Id); - policyConditionDefObj.setDescription("policy conditio"); - policyConditionDefObj.setId(Id); - policyConditionDefObj.setName(name); - policyConditionDefObj.setOrder(1); - policyConditionDefObj.setLabel("label"); - xConditionDefList.add(policyConditionDefObj); - - List policyItemConditionList = new ArrayList(); - XXPolicyItemCondition policyItemCondition = new XXPolicyItemCondition(); - policyItemCondition.setAddedByUserId(Id); - policyItemCondition.setCreateTime(new Date()); - policyItemCondition.setType(1L); - policyItemCondition.setId(Id); - policyItemCondition.setOrder(1); - policyItemCondition.setPolicyItemId(Id); - policyItemCondition.setUpdatedByUserId(Id); - policyItemCondition.setUpdateTime(new Date()); - policyItemConditionList.add(policyItemCondition); - - List serviceConfigDefList = new ArrayList(); - XXServiceConfigDef serviceConfigDefObj = new XXServiceConfigDef(); - serviceConfigDefObj.setAddedByUserId(Id); - serviceConfigDefObj.setCreateTime(new Date()); - serviceConfigDefObj.setDefaultvalue("simple"); - serviceConfigDefObj.setDescription("service config"); - serviceConfigDefObj.setId(Id); - serviceConfigDefObj.setIsMandatory(true); - serviceConfigDefObj.setName(name); - serviceConfigDefObj.setLabel("username"); - serviceConfigDefObj.setRbkeydescription(null); - serviceConfigDefObj.setRbkeylabel(null); - serviceConfigDefObj.setRbKeyValidationMessage(null); - serviceConfigDefObj.setType("password"); - serviceConfigDefList.add(serviceConfigDefObj); - - List contextEnrichersList = new ArrayList(); - XXContextEnricherDef contextEnricherDefObj = new XXContextEnricherDef(); - contextEnricherDefObj.setAddedByUserId(Id); - contextEnricherDefObj.setCreateTime(new Date()); - contextEnricherDefObj.setDefid(Id); - contextEnricherDefObj.setEnricher("RangerCountryProvider"); - contextEnricherDefObj.setName("country-provider"); - contextEnricherDefObj.setId(Id); - contextEnricherDefObj.setOrder(0); - contextEnricherDefObj.setUpdatedByUserId(Id); - contextEnricherDefObj.setUpdateTime(new Date()); - contextEnrichersList.add(contextEnricherDefObj); - - List xEnumList = new ArrayList(); - XXEnumDef enumDefObj = new XXEnumDef(); - enumDefObj.setAddedByUserId(Id); - enumDefObj.setCreateTime(new Date()); - enumDefObj.setDefaultindex(null); - enumDefObj.setDefid(Id); - enumDefObj.setId(Id); - enumDefObj.setName(name); - enumDefObj.setUpdatedByUserId(Id); - enumDefObj.setUpdateTime(new Date()); - xEnumList.add(enumDefObj); - - List xElementsList = new ArrayList(); - XXEnumElementDef enumElementDefObj = new XXEnumElementDef(); - enumElementDefObj.setAddedByUserId(Id); - enumElementDefObj.setCreateTime(new Date()); - enumElementDefObj.setEnumdefid(Id); - enumElementDefObj.setId(Id); - enumElementDefObj.setLabel("Authentication"); - enumElementDefObj.setName("authentication"); - enumElementDefObj.setUpdateTime(new Date()); - enumElementDefObj.setUpdatedByUserId(Id); - enumElementDefObj.setRbkeylabel(null); - enumElementDefObj.setOrder(0); - xElementsList.add(enumElementDefObj); - - Mockito.when(daoManager.getXXPortalUser()).thenReturn(xPortalUserDao); - Mockito.when(xPortalUserDao.getById(Id)).thenReturn(tUser); - - Mockito.when(daoManager.getXXServiceConfigDef()).thenReturn( - xServiceConfigDefDao); - Mockito.when( - xServiceConfigDefDao.findByServiceDefId(serviceDef.getId())) - .thenReturn(serviceConfigDefList); - - Mockito.when(daoManager.getXXResourceDef()).thenReturn(xResourceDefDao); - - Mockito.when(daoManager.getXXAccessTypeDef()).thenReturn( - xAccessTypeDefDao); - Mockito.when(xxAccessTypeDefGrantsDao.findImpliedGrantsByServiceDefId(Mockito.anyLong())).thenReturn(Collections.emptyMap()); - Mockito.when(daoManager.getXXAccessTypeDefGrants()).thenReturn(xxAccessTypeDefGrantsDao); - - Mockito.when(daoManager.getXXPolicyConditionDef()).thenReturn( - xPolicyConditionDefDao); - - Mockito.when(daoManager.getXXContextEnricherDef()).thenReturn( - xContextEnricherDefDao); - Mockito.when( - xContextEnricherDefDao.findByServiceDefId(serviceDef.getId())) - .thenReturn(contextEnrichersList); - - Mockito.when(daoManager.getXXEnumDef()).thenReturn(xEnumDefDao); - Mockito.when(xEnumDefDao.findByServiceDefId(serviceDef.getId())) - .thenReturn(xEnumList); - - Mockito.when(daoManager.getXXEnumElementDef()).thenReturn( - xEnumElementDefDao); - Mockito.when( - xEnumElementDefDao.findByEnumDefId(enumElementDefObj.getId())) - .thenReturn(xElementsList); - - XXDataMaskTypeDefDao xDataMaskTypeDao = Mockito.mock(XXDataMaskTypeDefDao.class); - List xDataMaskTypeDefs = new ArrayList(); - Mockito.when(daoManager.getXXDataMaskTypeDef()).thenReturn(xDataMaskTypeDao); - Mockito.when(xDataMaskTypeDao.findByServiceDefId(serviceDef.getId())).thenReturn(xDataMaskTypeDefs); - - RangerServiceDef dbRangerServiceDef = serviceDefService - .populateViewBean(serviceDef); - Assert.assertNotNull(dbRangerServiceDef); - Assert.assertEquals(dbRangerServiceDef.getId(), serviceDef.getId()); - Assert.assertEquals(dbRangerServiceDef.getName(), serviceDef.getName()); - Assert.assertEquals(dbRangerServiceDef.getDescription(), - serviceDef.getDescription()); - Assert.assertEquals(dbRangerServiceDef.getGuid(), serviceDef.getGuid()); - Assert.assertEquals(dbRangerServiceDef.getVersion(), - serviceDef.getVersion()); - Mockito.verify(daoManager).getXXServiceConfigDef(); - Mockito.verify(daoManager).getXXResourceDef(); - Mockito.verify(daoManager).getXXAccessTypeDef(); - Mockito.verify(daoManager).getXXPolicyConditionDef(); - Mockito.verify(daoManager).getXXContextEnricherDef(); - Mockito.verify(daoManager).getXXEnumDef(); - Mockito.verify(daoManager).getXXEnumElementDef(); - } - - @Test - public void test4getAllServiceDefs() { - XXPortalUserDao xPortalUserDao = Mockito.mock(XXPortalUserDao.class); - - XXResourceDefDao xResourceDefDao = Mockito.mock(XXResourceDefDao.class); - XXAccessTypeDefDao xAccessTypeDefDao = Mockito - .mock(XXAccessTypeDefDao.class); - XXAccessTypeDefGrantsDao xxAccessTypeDefGrantsDao = Mockito.mock(XXAccessTypeDefGrantsDao.class); - XXPolicyConditionDefDao xPolicyConditionDefDao = Mockito - .mock(XXPolicyConditionDefDao.class); - XXServiceConfigDefDao xServiceConfigDefDao = Mockito - .mock(XXServiceConfigDefDao.class); - XXContextEnricherDefDao xContextEnricherDefDao = Mockito - .mock(XXContextEnricherDefDao.class); - XXEnumDefDao xEnumDefDao = Mockito.mock(XXEnumDefDao.class); - XXEnumElementDefDao xEnumElementDefDao = Mockito - .mock(XXEnumElementDefDao.class); - - List xServiceDefList = new ArrayList(); - XXServiceDef serviceDef = new XXServiceDef(); - serviceDef.setAddedByUserId(Id); - serviceDef.setCreateTime(new Date()); - serviceDef.setDescription("HDFS Repository"); - serviceDef.setGuid("1427365526516_835_0"); - serviceDef.setId(Id); - serviceDef.setUpdateTime(new Date()); - serviceDef.setUpdatedByUserId(Id); - serviceDef.setImplclassname("RangerServiceHdfs"); - serviceDef.setLabel("HDFS Repository"); - serviceDef.setRbkeylabel(null); - serviceDef.setRbkeydescription(null); - serviceDef.setIsEnabled(true); - xServiceDefList.add(serviceDef); - - String name = "fdfdfds"; - XXPortalUser tUser = new XXPortalUser(); - tUser.setAddedByUserId(Id); - tUser.setCreateTime(new Date()); - tUser.setEmailAddress("test@gmail.com"); - tUser.setFirstName(name); - tUser.setId(Id); - tUser.setLastName(name); - - List resDefList = new ArrayList(); - XXResourceDef resourceDef = new XXResourceDef(); - resourceDef.setAddedByUserId(Id); - resourceDef.setCreateTime(new Date()); - resourceDef.setDefid(Id); - resourceDef.setDescription("test"); - resourceDef.setId(Id); - resDefList.add(resourceDef); - - List xPolicyItemList = new ArrayList(); - XXPolicyItem xPolicyItem = new XXPolicyItem(); - xPolicyItem.setDelegateAdmin(false); - xPolicyItem.setAddedByUserId(null); - xPolicyItem.setCreateTime(new Date()); - xPolicyItem.setGUID(null); - xPolicyItem.setId(Id); - xPolicyItem.setOrder(null); - xPolicyItem.setPolicyId(Id); - xPolicyItem.setUpdatedByUserId(null); - xPolicyItem.setUpdateTime(new Date()); - xPolicyItemList.add(xPolicyItem); - - List policyItemAccessList = new ArrayList(); - XXPolicyItemAccess policyItemAccess = new XXPolicyItemAccess(); - policyItemAccess.setAddedByUserId(Id); - policyItemAccess.setCreateTime(new Date()); - policyItemAccess.setPolicyitemid(Id); - policyItemAccess.setId(Id); - policyItemAccess.setOrder(1); - policyItemAccess.setUpdatedByUserId(Id); - policyItemAccess.setUpdateTime(new Date()); - policyItemAccessList.add(policyItemAccess); - - List xConditionDefList = new ArrayList(); - XXPolicyConditionDef policyConditionDefObj = new XXPolicyConditionDef(); - policyConditionDefObj.setAddedByUserId(Id); - policyConditionDefObj.setCreateTime(new Date()); - policyConditionDefObj.setDefid(Id); - policyConditionDefObj.setDescription("policy conditio"); - policyConditionDefObj.setId(Id); - policyConditionDefObj.setName(name); - policyConditionDefObj.setOrder(1); - policyConditionDefObj.setLabel("label"); - xConditionDefList.add(policyConditionDefObj); - - List policyItemConditionList = new ArrayList(); - XXPolicyItemCondition policyItemCondition = new XXPolicyItemCondition(); - policyItemCondition.setAddedByUserId(Id); - policyItemCondition.setCreateTime(new Date()); - policyItemCondition.setType(1L); - policyItemCondition.setId(Id); - policyItemCondition.setOrder(1); - policyItemCondition.setPolicyItemId(Id); - policyItemCondition.setUpdatedByUserId(Id); - policyItemCondition.setUpdateTime(new Date()); - policyItemConditionList.add(policyItemCondition); - - List serviceConfigDefList = new ArrayList(); - XXServiceConfigDef serviceConfigDefObj = new XXServiceConfigDef(); - serviceConfigDefObj.setAddedByUserId(Id); - serviceConfigDefObj.setCreateTime(new Date()); - serviceConfigDefObj.setDefaultvalue("simple"); - serviceConfigDefObj.setDescription("service config"); - serviceConfigDefObj.setId(Id); - serviceConfigDefObj.setIsMandatory(true); - serviceConfigDefObj.setName(name); - serviceConfigDefObj.setLabel("username"); - serviceConfigDefObj.setRbkeydescription(null); - serviceConfigDefObj.setRbkeylabel(null); - serviceConfigDefObj.setRbKeyValidationMessage(null); - serviceConfigDefObj.setType("password"); - serviceConfigDefList.add(serviceConfigDefObj); - - List contextEnrichersList = new ArrayList(); - XXContextEnricherDef contextEnricherDefObj = new XXContextEnricherDef(); - contextEnricherDefObj.setAddedByUserId(Id); - contextEnricherDefObj.setCreateTime(new Date()); - contextEnricherDefObj.setDefid(Id); - contextEnricherDefObj.setEnricher("RangerCountryProvider"); - contextEnricherDefObj.setName("country-provider"); - contextEnricherDefObj.setId(Id); - contextEnricherDefObj.setOrder(0); - contextEnricherDefObj.setUpdatedByUserId(Id); - contextEnricherDefObj.setUpdateTime(new Date()); - contextEnrichersList.add(contextEnricherDefObj); - - List xEnumList = new ArrayList(); - XXEnumDef enumDefObj = new XXEnumDef(); - enumDefObj.setAddedByUserId(Id); - enumDefObj.setCreateTime(new Date()); - enumDefObj.setDefaultindex(null); - enumDefObj.setDefid(Id); - enumDefObj.setId(Id); - enumDefObj.setName(name); - enumDefObj.setUpdatedByUserId(Id); - enumDefObj.setUpdateTime(new Date()); - xEnumList.add(enumDefObj); - - List xElementsList = new ArrayList(); - XXEnumElementDef enumElementDefObj = new XXEnumElementDef(); - enumElementDefObj.setAddedByUserId(Id); - enumElementDefObj.setCreateTime(new Date()); - enumElementDefObj.setEnumdefid(Id); - enumElementDefObj.setId(Id); - enumElementDefObj.setLabel("Authentication"); - enumElementDefObj.setName("authentication"); - enumElementDefObj.setUpdateTime(new Date()); - enumElementDefObj.setUpdatedByUserId(Id); - enumElementDefObj.setRbkeylabel(null); - enumElementDefObj.setOrder(0); - xElementsList.add(enumElementDefObj); - - Mockito.when(xServiceDefDao.getAll()).thenReturn(xServiceDefList); - - Mockito.when(daoManager.getXXPortalUser()).thenReturn(xPortalUserDao); - Mockito.when(xPortalUserDao.getById(Id)).thenReturn(tUser); - - Mockito.when(daoManager.getXXServiceConfigDef()).thenReturn( - xServiceConfigDefDao); - Mockito.when( - xServiceConfigDefDao.findByServiceDefId(serviceDef.getId())) - .thenReturn(serviceConfigDefList); - - Mockito.when(daoManager.getXXResourceDef()).thenReturn(xResourceDefDao); - - Mockito.when(daoManager.getXXAccessTypeDef()).thenReturn( - xAccessTypeDefDao); - Mockito.when(xxAccessTypeDefGrantsDao.findImpliedGrantsByServiceDefId(Mockito.anyLong())).thenReturn(Collections.emptyMap()); - Mockito.when(daoManager.getXXAccessTypeDefGrants()).thenReturn(xxAccessTypeDefGrantsDao); - - Mockito.when(daoManager.getXXPolicyConditionDef()).thenReturn( - xPolicyConditionDefDao); - - Mockito.when(daoManager.getXXContextEnricherDef()).thenReturn( - xContextEnricherDefDao); - Mockito.when( - xContextEnricherDefDao.findByServiceDefId(serviceDef.getId())) - .thenReturn(contextEnrichersList); - - Mockito.when(daoManager.getXXEnumDef()).thenReturn(xEnumDefDao); - Mockito.when(xEnumDefDao.findByServiceDefId(serviceDef.getId())) - .thenReturn(xEnumList); - - Mockito.when(daoManager.getXXEnumElementDef()).thenReturn( - xEnumElementDefDao); - Mockito.when( - xEnumElementDefDao.findByEnumDefId(enumElementDefObj.getId())) - .thenReturn(xElementsList); - - XXDataMaskTypeDefDao xDataMaskTypeDao = Mockito.mock(XXDataMaskTypeDefDao.class); - List xDataMaskTypeDefs = new ArrayList(); - Mockito.when(daoManager.getXXDataMaskTypeDef()).thenReturn(xDataMaskTypeDao); - Mockito.when(xDataMaskTypeDao.findByServiceDefId(serviceDef.getId())).thenReturn(xDataMaskTypeDefs); - - List dbRangerServiceDef = serviceDefService - .getAllServiceDefs(); - Assert.assertNotNull(dbRangerServiceDef); - Mockito.verify(daoManager).getXXResourceDef(); - Mockito.verify(daoManager).getXXAccessTypeDef(); - Mockito.verify(daoManager).getXXPolicyConditionDef(); - Mockito.verify(daoManager).getXXContextEnricherDef(); - Mockito.verify(daoManager).getXXEnumDef(); - Mockito.verify(daoManager).getXXEnumElementDef(); - } - - @Test - public void test5getPopulatedViewObject() { - XXPortalUserDao xPortalUserDao = Mockito.mock(XXPortalUserDao.class); - XXServiceConfigDefDao xServiceConfigDefDao = Mockito - .mock(XXServiceConfigDefDao.class); - - XXResourceDefDao xResourceDefDao = Mockito.mock(XXResourceDefDao.class); - XXAccessTypeDefDao xAccessTypeDefDao = Mockito - .mock(XXAccessTypeDefDao.class); - XXAccessTypeDefGrantsDao xxAccessTypeDefGrantsDao = Mockito.mock(XXAccessTypeDefGrantsDao.class); - XXPolicyConditionDefDao xPolicyConditionDefDao = Mockito - .mock(XXPolicyConditionDefDao.class); - XXContextEnricherDefDao xContextEnricherDefDao = Mockito - .mock(XXContextEnricherDefDao.class); - XXEnumDefDao xEnumDefDao = Mockito.mock(XXEnumDefDao.class); - XXEnumElementDefDao xEnumElementDefDao = Mockito - .mock(XXEnumElementDefDao.class); - - XXServiceDef serviceDef = serviceDef(); - String name = "fdfdfds"; - XXPortalUser tUser = new XXPortalUser(); - tUser.setAddedByUserId(Id); - tUser.setCreateTime(new Date()); - tUser.setEmailAddress("test@gmail.com"); - tUser.setFirstName(name); - tUser.setId(Id); - tUser.setLastName(name); - - List serviceConfigDefList = new ArrayList(); - XXServiceConfigDef serviceConfigDefObj = new XXServiceConfigDef(); - serviceConfigDefObj.setAddedByUserId(Id); - serviceConfigDefObj.setCreateTime(new Date()); - serviceConfigDefObj.setDefaultvalue("simple"); - serviceConfigDefObj.setDescription("service config"); - serviceConfigDefObj.setId(Id); - serviceConfigDefObj.setIsMandatory(true); - serviceConfigDefObj.setName(name); - serviceConfigDefObj.setLabel("username"); - serviceConfigDefObj.setRbkeydescription(null); - serviceConfigDefObj.setRbkeylabel(null); - serviceConfigDefObj.setRbKeyValidationMessage(null); - serviceConfigDefObj.setType("password"); - serviceConfigDefList.add(serviceConfigDefObj); - - List resDefList = new ArrayList(); - XXResourceDef resourceDef = new XXResourceDef(); - resourceDef.setAddedByUserId(Id); - resourceDef.setCreateTime(new Date()); - resourceDef.setDefid(Id); - resourceDef.setDescription("test"); - resourceDef.setId(Id); - resDefList.add(resourceDef); - - List xPolicyItemList = new ArrayList(); - XXPolicyItem xPolicyItem = new XXPolicyItem(); - xPolicyItem.setDelegateAdmin(false); - xPolicyItem.setAddedByUserId(null); - xPolicyItem.setCreateTime(new Date()); - xPolicyItem.setGUID(null); - xPolicyItem.setId(Id); - xPolicyItem.setOrder(null); - xPolicyItem.setPolicyId(Id); - xPolicyItem.setUpdatedByUserId(null); - xPolicyItem.setUpdateTime(new Date()); - xPolicyItemList.add(xPolicyItem); - - List policyItemAccessList = new ArrayList(); - XXPolicyItemAccess policyItemAccess = new XXPolicyItemAccess(); - policyItemAccess.setAddedByUserId(Id); - policyItemAccess.setCreateTime(new Date()); - policyItemAccess.setPolicyitemid(Id); - policyItemAccess.setId(Id); - policyItemAccess.setOrder(1); - policyItemAccess.setUpdatedByUserId(Id); - policyItemAccess.setUpdateTime(new Date()); - policyItemAccessList.add(policyItemAccess); - - List xConditionDefList = new ArrayList(); - XXPolicyConditionDef policyConditionDefObj = new XXPolicyConditionDef(); - policyConditionDefObj.setAddedByUserId(Id); - policyConditionDefObj.setCreateTime(new Date()); - policyConditionDefObj.setDefid(Id); - policyConditionDefObj.setDescription("policy conditio"); - policyConditionDefObj.setId(Id); - policyConditionDefObj.setName(name); - policyConditionDefObj.setOrder(1); - policyConditionDefObj.setLabel("label"); - xConditionDefList.add(policyConditionDefObj); - - List policyItemConditionList = new ArrayList(); - XXPolicyItemCondition policyItemCondition = new XXPolicyItemCondition(); - policyItemCondition.setAddedByUserId(Id); - policyItemCondition.setCreateTime(new Date()); - policyItemCondition.setType(1L); - policyItemCondition.setId(Id); - policyItemCondition.setOrder(1); - policyItemCondition.setPolicyItemId(Id); - policyItemCondition.setUpdatedByUserId(Id); - policyItemCondition.setUpdateTime(new Date()); - policyItemConditionList.add(policyItemCondition); - - List contextEnrichersList = new ArrayList(); - XXContextEnricherDef contextEnricherDefObj = new XXContextEnricherDef(); - contextEnricherDefObj.setAddedByUserId(Id); - contextEnricherDefObj.setCreateTime(new Date()); - contextEnricherDefObj.setDefid(Id); - contextEnricherDefObj.setEnricher("RangerCountryProvider"); - contextEnricherDefObj.setName("country-provider"); - contextEnricherDefObj.setId(Id); - contextEnricherDefObj.setOrder(0); - contextEnricherDefObj.setUpdatedByUserId(Id); - contextEnricherDefObj.setUpdateTime(new Date()); - contextEnrichersList.add(contextEnricherDefObj); - - List xEnumList = new ArrayList(); - XXEnumDef enumDefObj = new XXEnumDef(); - enumDefObj.setAddedByUserId(Id); - enumDefObj.setCreateTime(new Date()); - enumDefObj.setDefaultindex(null); - enumDefObj.setDefid(Id); - enumDefObj.setId(Id); - enumDefObj.setName(name); - enumDefObj.setUpdatedByUserId(Id); - enumDefObj.setUpdateTime(new Date()); - xEnumList.add(enumDefObj); - - List xElementsList = new ArrayList(); - XXEnumElementDef enumElementDefObj = new XXEnumElementDef(); - enumElementDefObj.setAddedByUserId(Id); - enumElementDefObj.setCreateTime(new Date()); - enumElementDefObj.setEnumdefid(Id); - enumElementDefObj.setId(Id); - enumElementDefObj.setLabel("Authentication"); - enumElementDefObj.setName("authentication"); - enumElementDefObj.setUpdateTime(new Date()); - enumElementDefObj.setUpdatedByUserId(Id); - enumElementDefObj.setRbkeylabel(null); - enumElementDefObj.setOrder(0); - xElementsList.add(enumElementDefObj); - - Mockito.when(daoManager.getXXPortalUser()).thenReturn(xPortalUserDao); - Mockito.when(xPortalUserDao.getById(Id)).thenReturn(tUser); - - Mockito.when(daoManager.getXXServiceConfigDef()).thenReturn( - xServiceConfigDefDao); - Mockito.when( - xServiceConfigDefDao.findByServiceDefId(serviceDef.getId())) - .thenReturn(serviceConfigDefList); - - Mockito.when(daoManager.getXXResourceDef()).thenReturn(xResourceDefDao); - - Mockito.when(daoManager.getXXAccessTypeDef()).thenReturn( - xAccessTypeDefDao); - Mockito.when(xxAccessTypeDefGrantsDao.findImpliedGrantsByServiceDefId(Mockito.anyLong())).thenReturn(Collections.emptyMap()); - Mockito.when(daoManager.getXXAccessTypeDefGrants()).thenReturn(xxAccessTypeDefGrantsDao); - - Mockito.when(daoManager.getXXPolicyConditionDef()).thenReturn( - xPolicyConditionDefDao); - - Mockito.when(daoManager.getXXContextEnricherDef()).thenReturn( - xContextEnricherDefDao); - Mockito.when( - xContextEnricherDefDao.findByServiceDefId(serviceDef.getId())) - .thenReturn(contextEnrichersList); - - Mockito.when(daoManager.getXXEnumDef()).thenReturn(xEnumDefDao); - Mockito.when(xEnumDefDao.findByServiceDefId(serviceDef.getId())) - .thenReturn(xEnumList); - - Mockito.when(daoManager.getXXEnumElementDef()).thenReturn( - xEnumElementDefDao); - Mockito.when( - xEnumElementDefDao.findByEnumDefId(enumElementDefObj.getId())) - .thenReturn(xElementsList); - - XXDataMaskTypeDefDao xDataMaskTypeDao = Mockito.mock(XXDataMaskTypeDefDao.class); - List xDataMaskTypeDefs = new ArrayList(); - Mockito.when(daoManager.getXXDataMaskTypeDef()).thenReturn(xDataMaskTypeDao); - Mockito.when(xDataMaskTypeDao.findByServiceDefId(serviceDef.getId())).thenReturn(xDataMaskTypeDefs); - - RangerServiceDef dbRangerServiceDef = serviceDefService - .getPopulatedViewObject(serviceDef); - Assert.assertNotNull(dbRangerServiceDef); - Mockito.verify(daoManager).getXXServiceConfigDef(); - Mockito.verify(daoManager).getXXResourceDef(); - Mockito.verify(daoManager).getXXAccessTypeDef(); - Mockito.verify(daoManager).getXXPolicyConditionDef(); - Mockito.verify(daoManager).getXXContextEnricherDef(); - Mockito.verify(daoManager).getXXEnumDef(); - } - - @Test - public void testImplicitConditionExpression() { - RangerServiceDef serviceDef = rangerServiceDef(); - int initCount = serviceDef.getPolicyConditions().size(); - boolean isAdded = serviceDefService.addImplicitConditionExpressionIfNeeded(serviceDef); - - // serviceDef doesn't have RangerScriptConditionEvaluator condition, hence should be added - Assert.assertTrue(isAdded); - - int postCount = serviceDef.getPolicyConditions().size(); - - Assert.assertEquals(initCount + 1, postCount); - - boolean exists = false; - - for (RangerPolicyConditionDef conditionDef : serviceDef.getPolicyConditions()) { - if (StringUtils.equals(conditionDef.getEvaluator(), ServiceDefUtil.IMPLICIT_CONDITION_EXPRESSION_EVALUATOR)) { - exists = true; - - break; - } - } - - Assert.assertTrue(exists); - - isAdded = serviceDefService.addImplicitConditionExpressionIfNeeded(serviceDef); - - // serviceDef already has RangerScriptConditionEvaluator, hence shouldn't be added again - Assert.assertFalse(isAdded); - } - - @Test - public void testImplicitConditionExpressionDisabled() { - PropertiesUtil.getPropertiesMap().put(PROP_ENABLE_IMPLICIT_CONDITION_EXPRESSION, Boolean.FALSE.toString()); - - try { - RangerServiceDef serviceDef = rangerServiceDef(); - int initCount = serviceDef.getPolicyConditions().size(); - boolean isAdded = serviceDefService.addImplicitConditionExpressionIfNeeded(serviceDef); - - // PROP_ENABLE_IMPLICIT_CONDITION_EXPR is false, hence shouldn't be added - Assert.assertFalse(isAdded); - - int postCount = serviceDef.getPolicyConditions().size(); - - Assert.assertEquals(initCount, postCount); - } finally { - PropertiesUtil.getPropertiesMap().remove(PROP_ENABLE_IMPLICIT_CONDITION_EXPRESSION); - } - } + private static final Long Id = 8L; + @Rule + public ExpectedException thrown = ExpectedException.none(); + @InjectMocks + RangerServiceDefService serviceDefService = new RangerServiceDefService(); + @Mock + RangerDaoManager daoManager; + @Mock + JSONUtil jsonUtil; + @Mock + RangerPolicyService policyService; + @Mock + StringUtil stringUtil; + @Mock + XUserService xUserService; + @Mock + XXServiceDefDao xServiceDefDao; + + public void setup() { + RangerSecurityContext context = new RangerSecurityContext(); + context.setUserSession(new UserSessionBase()); + RangerContextHolder.setSecurityContext(context); + UserSessionBase currentUserSession = ContextUtil.getCurrentUserSession(); + currentUserSession.setUserAdmin(true); + } + + @Test + public void test1ValidateForCreate() { + RangerServiceDef rangerServiceDef = rangerServiceDef(); + serviceDefService.validateForCreate(rangerServiceDef); + Assert.assertNotNull(rangerServiceDef); + } + + @Test + public void test2ValidateForUpdate() { + RangerServiceDef rangerServiceDef = rangerServiceDef(); + XXServiceDef serviceDef = serviceDef(); + serviceDefService.validateForUpdate(rangerServiceDef, serviceDef); + + Assert.assertNotNull(rangerServiceDef); + } + + @Test + public void test3PopulateViewBean() { + XXPortalUserDao xPortalUserDao = Mockito.mock(XXPortalUserDao.class); + XXResourceDefDao xResourceDefDao = Mockito.mock(XXResourceDefDao.class); + XXAccessTypeDefDao xAccessTypeDefDao = Mockito.mock(XXAccessTypeDefDao.class); + XXAccessTypeDefGrantsDao xxAccessTypeDefGrantsDao = Mockito.mock(XXAccessTypeDefGrantsDao.class); + XXPolicyConditionDefDao xPolicyConditionDefDao = Mockito.mock(XXPolicyConditionDefDao.class); + XXServiceConfigDefDao xServiceConfigDefDao = Mockito.mock(XXServiceConfigDefDao.class); + XXContextEnricherDefDao xContextEnricherDefDao = Mockito.mock(XXContextEnricherDefDao.class); + XXEnumDefDao xEnumDefDao = Mockito.mock(XXEnumDefDao.class); + XXEnumElementDefDao xEnumElementDefDao = Mockito.mock(XXEnumElementDefDao.class); + + XXServiceDef serviceDef = serviceDef(); + + String name = "fdfdfds"; + XXPortalUser tUser = new XXPortalUser(); + tUser.setAddedByUserId(Id); + tUser.setCreateTime(new Date()); + tUser.setEmailAddress("test@gmail.com"); + tUser.setFirstName(name); + tUser.setId(Id); + tUser.setLastName(name); + + List resDefList = new ArrayList<>(); + XXResourceDef resourceDef = new XXResourceDef(); + resourceDef.setAddedByUserId(Id); + resourceDef.setCreateTime(new Date()); + resourceDef.setDefid(Id); + resourceDef.setDescription("test"); + resourceDef.setId(Id); + resDefList.add(resourceDef); + + List xPolicyItemList = new ArrayList<>(); + XXPolicyItem xPolicyItem = new XXPolicyItem(); + xPolicyItem.setDelegateAdmin(false); + xPolicyItem.setAddedByUserId(null); + xPolicyItem.setCreateTime(new Date()); + xPolicyItem.setGUID(null); + xPolicyItem.setId(Id); + xPolicyItem.setOrder(null); + xPolicyItem.setPolicyId(Id); + xPolicyItem.setUpdatedByUserId(null); + xPolicyItem.setUpdateTime(new Date()); + xPolicyItemList.add(xPolicyItem); + + List policyItemAccessList = new ArrayList<>(); + XXPolicyItemAccess policyItemAccess = new XXPolicyItemAccess(); + policyItemAccess.setAddedByUserId(Id); + policyItemAccess.setCreateTime(new Date()); + policyItemAccess.setPolicyitemid(Id); + policyItemAccess.setId(Id); + policyItemAccess.setOrder(1); + policyItemAccess.setUpdatedByUserId(Id); + policyItemAccess.setUpdateTime(new Date()); + policyItemAccessList.add(policyItemAccess); + + List xConditionDefList = new ArrayList<>(); + XXPolicyConditionDef policyConditionDefObj = new XXPolicyConditionDef(); + policyConditionDefObj.setAddedByUserId(Id); + policyConditionDefObj.setCreateTime(new Date()); + policyConditionDefObj.setDefid(Id); + policyConditionDefObj.setDescription("policy condition"); + policyConditionDefObj.setId(Id); + policyConditionDefObj.setName(name); + policyConditionDefObj.setOrder(1); + policyConditionDefObj.setLabel("label"); + xConditionDefList.add(policyConditionDefObj); + + List policyItemConditionList = new ArrayList<>(); + XXPolicyItemCondition policyItemCondition = new XXPolicyItemCondition(); + policyItemCondition.setAddedByUserId(Id); + policyItemCondition.setCreateTime(new Date()); + policyItemCondition.setType(1L); + policyItemCondition.setId(Id); + policyItemCondition.setOrder(1); + policyItemCondition.setPolicyItemId(Id); + policyItemCondition.setUpdatedByUserId(Id); + policyItemCondition.setUpdateTime(new Date()); + policyItemConditionList.add(policyItemCondition); + + List serviceConfigDefList = new ArrayList<>(); + XXServiceConfigDef serviceConfigDefObj = new XXServiceConfigDef(); + serviceConfigDefObj.setAddedByUserId(Id); + serviceConfigDefObj.setCreateTime(new Date()); + serviceConfigDefObj.setDefaultvalue("simple"); + serviceConfigDefObj.setDescription("service config"); + serviceConfigDefObj.setId(Id); + serviceConfigDefObj.setIsMandatory(true); + serviceConfigDefObj.setName(name); + serviceConfigDefObj.setLabel("username"); + serviceConfigDefObj.setRbkeydescription(null); + serviceConfigDefObj.setRbkeylabel(null); + serviceConfigDefObj.setRbKeyValidationMessage(null); + serviceConfigDefObj.setType("password"); + serviceConfigDefList.add(serviceConfigDefObj); + + List contextEnrichersList = new ArrayList<>(); + XXContextEnricherDef contextEnricherDefObj = new XXContextEnricherDef(); + contextEnricherDefObj.setAddedByUserId(Id); + contextEnricherDefObj.setCreateTime(new Date()); + contextEnricherDefObj.setDefid(Id); + contextEnricherDefObj.setEnricher("RangerCountryProvider"); + contextEnricherDefObj.setName("country-provider"); + contextEnricherDefObj.setId(Id); + contextEnricherDefObj.setOrder(0); + contextEnricherDefObj.setUpdatedByUserId(Id); + contextEnricherDefObj.setUpdateTime(new Date()); + contextEnrichersList.add(contextEnricherDefObj); + + List xEnumList = new ArrayList<>(); + XXEnumDef enumDefObj = new XXEnumDef(); + enumDefObj.setAddedByUserId(Id); + enumDefObj.setCreateTime(new Date()); + enumDefObj.setDefaultindex(null); + enumDefObj.setDefid(Id); + enumDefObj.setId(Id); + enumDefObj.setName(name); + enumDefObj.setUpdatedByUserId(Id); + enumDefObj.setUpdateTime(new Date()); + xEnumList.add(enumDefObj); + + List xElementsList = new ArrayList<>(); + XXEnumElementDef enumElementDefObj = new XXEnumElementDef(); + enumElementDefObj.setAddedByUserId(Id); + enumElementDefObj.setCreateTime(new Date()); + enumElementDefObj.setEnumdefid(Id); + enumElementDefObj.setId(Id); + enumElementDefObj.setLabel("Authentication"); + enumElementDefObj.setName("authentication"); + enumElementDefObj.setUpdateTime(new Date()); + enumElementDefObj.setUpdatedByUserId(Id); + enumElementDefObj.setRbkeylabel(null); + enumElementDefObj.setOrder(0); + xElementsList.add(enumElementDefObj); + + Mockito.when(daoManager.getXXPortalUser()).thenReturn(xPortalUserDao); + Mockito.when(xPortalUserDao.getById(Id)).thenReturn(tUser); + + Mockito.when(daoManager.getXXServiceConfigDef()).thenReturn(xServiceConfigDefDao); + Mockito.when(xServiceConfigDefDao.findByServiceDefId(serviceDef.getId())).thenReturn(serviceConfigDefList); + + Mockito.when(daoManager.getXXResourceDef()).thenReturn(xResourceDefDao); + + Mockito.when(daoManager.getXXAccessTypeDef()).thenReturn(xAccessTypeDefDao); + Mockito.when(xxAccessTypeDefGrantsDao.findImpliedGrantsByServiceDefId(Mockito.anyLong())).thenReturn(Collections.emptyMap()); + Mockito.when(daoManager.getXXAccessTypeDefGrants()).thenReturn(xxAccessTypeDefGrantsDao); + + Mockito.when(daoManager.getXXPolicyConditionDef()).thenReturn(xPolicyConditionDefDao); + + Mockito.when(daoManager.getXXContextEnricherDef()).thenReturn(xContextEnricherDefDao); + Mockito.when(xContextEnricherDefDao.findByServiceDefId(serviceDef.getId())).thenReturn(contextEnrichersList); + + Mockito.when(daoManager.getXXEnumDef()).thenReturn(xEnumDefDao); + Mockito.when(xEnumDefDao.findByServiceDefId(serviceDef.getId())).thenReturn(xEnumList); + + Mockito.when(daoManager.getXXEnumElementDef()).thenReturn(xEnumElementDefDao); + Mockito.when(xEnumElementDefDao.findByEnumDefId(enumElementDefObj.getId())).thenReturn(xElementsList); + + XXDataMaskTypeDefDao xDataMaskTypeDao = Mockito.mock(XXDataMaskTypeDefDao.class); + List xDataMaskTypeDefs = new ArrayList<>(); + Mockito.when(daoManager.getXXDataMaskTypeDef()).thenReturn(xDataMaskTypeDao); + Mockito.when(xDataMaskTypeDao.findByServiceDefId(serviceDef.getId())).thenReturn(xDataMaskTypeDefs); + + RangerServiceDef dbRangerServiceDef = serviceDefService.populateViewBean(serviceDef); + Assert.assertNotNull(dbRangerServiceDef); + Assert.assertEquals(dbRangerServiceDef.getId(), serviceDef.getId()); + Assert.assertEquals(dbRangerServiceDef.getName(), serviceDef.getName()); + Assert.assertEquals(dbRangerServiceDef.getDescription(), serviceDef.getDescription()); + Assert.assertEquals(dbRangerServiceDef.getGuid(), serviceDef.getGuid()); + Assert.assertEquals(dbRangerServiceDef.getVersion(), serviceDef.getVersion()); + Mockito.verify(daoManager).getXXServiceConfigDef(); + Mockito.verify(daoManager).getXXResourceDef(); + Mockito.verify(daoManager).getXXAccessTypeDef(); + Mockito.verify(daoManager).getXXPolicyConditionDef(); + Mockito.verify(daoManager).getXXContextEnricherDef(); + Mockito.verify(daoManager).getXXEnumDef(); + Mockito.verify(daoManager).getXXEnumElementDef(); + } + + @Test + public void test4getAllServiceDefs() { + XXPortalUserDao xPortalUserDao = Mockito.mock(XXPortalUserDao.class); + + XXResourceDefDao xResourceDefDao = Mockito.mock(XXResourceDefDao.class); + XXAccessTypeDefDao xAccessTypeDefDao = Mockito.mock(XXAccessTypeDefDao.class); + XXAccessTypeDefGrantsDao xxAccessTypeDefGrantsDao = Mockito.mock(XXAccessTypeDefGrantsDao.class); + XXPolicyConditionDefDao xPolicyConditionDefDao = Mockito.mock(XXPolicyConditionDefDao.class); + XXServiceConfigDefDao xServiceConfigDefDao = Mockito.mock(XXServiceConfigDefDao.class); + XXContextEnricherDefDao xContextEnricherDefDao = Mockito.mock(XXContextEnricherDefDao.class); + XXEnumDefDao xEnumDefDao = Mockito.mock(XXEnumDefDao.class); + XXEnumElementDefDao xEnumElementDefDao = Mockito.mock(XXEnumElementDefDao.class); + + List xServiceDefList = new ArrayList<>(); + XXServiceDef serviceDef = new XXServiceDef(); + serviceDef.setAddedByUserId(Id); + serviceDef.setCreateTime(new Date()); + serviceDef.setDescription("HDFS Repository"); + serviceDef.setGuid("1427365526516_835_0"); + serviceDef.setId(Id); + serviceDef.setUpdateTime(new Date()); + serviceDef.setUpdatedByUserId(Id); + serviceDef.setImplclassname("RangerServiceHdfs"); + serviceDef.setLabel("HDFS Repository"); + serviceDef.setRbkeylabel(null); + serviceDef.setRbkeydescription(null); + serviceDef.setIsEnabled(true); + xServiceDefList.add(serviceDef); + + String name = "fdfdfds"; + XXPortalUser tUser = new XXPortalUser(); + tUser.setAddedByUserId(Id); + tUser.setCreateTime(new Date()); + tUser.setEmailAddress("test@gmail.com"); + tUser.setFirstName(name); + tUser.setId(Id); + tUser.setLastName(name); + + List resDefList = new ArrayList<>(); + XXResourceDef resourceDef = new XXResourceDef(); + resourceDef.setAddedByUserId(Id); + resourceDef.setCreateTime(new Date()); + resourceDef.setDefid(Id); + resourceDef.setDescription("test"); + resourceDef.setId(Id); + resDefList.add(resourceDef); + + List xPolicyItemList = new ArrayList<>(); + XXPolicyItem xPolicyItem = new XXPolicyItem(); + xPolicyItem.setDelegateAdmin(false); + xPolicyItem.setAddedByUserId(null); + xPolicyItem.setCreateTime(new Date()); + xPolicyItem.setGUID(null); + xPolicyItem.setId(Id); + xPolicyItem.setOrder(null); + xPolicyItem.setPolicyId(Id); + xPolicyItem.setUpdatedByUserId(null); + xPolicyItem.setUpdateTime(new Date()); + xPolicyItemList.add(xPolicyItem); + + List policyItemAccessList = new ArrayList<>(); + XXPolicyItemAccess policyItemAccess = new XXPolicyItemAccess(); + policyItemAccess.setAddedByUserId(Id); + policyItemAccess.setCreateTime(new Date()); + policyItemAccess.setPolicyitemid(Id); + policyItemAccess.setId(Id); + policyItemAccess.setOrder(1); + policyItemAccess.setUpdatedByUserId(Id); + policyItemAccess.setUpdateTime(new Date()); + policyItemAccessList.add(policyItemAccess); + + List xConditionDefList = new ArrayList<>(); + XXPolicyConditionDef policyConditionDefObj = new XXPolicyConditionDef(); + policyConditionDefObj.setAddedByUserId(Id); + policyConditionDefObj.setCreateTime(new Date()); + policyConditionDefObj.setDefid(Id); + policyConditionDefObj.setDescription("policy condition"); + policyConditionDefObj.setId(Id); + policyConditionDefObj.setName(name); + policyConditionDefObj.setOrder(1); + policyConditionDefObj.setLabel("label"); + xConditionDefList.add(policyConditionDefObj); + + List policyItemConditionList = new ArrayList<>(); + XXPolicyItemCondition policyItemCondition = new XXPolicyItemCondition(); + policyItemCondition.setAddedByUserId(Id); + policyItemCondition.setCreateTime(new Date()); + policyItemCondition.setType(1L); + policyItemCondition.setId(Id); + policyItemCondition.setOrder(1); + policyItemCondition.setPolicyItemId(Id); + policyItemCondition.setUpdatedByUserId(Id); + policyItemCondition.setUpdateTime(new Date()); + policyItemConditionList.add(policyItemCondition); + + List serviceConfigDefList = new ArrayList<>(); + XXServiceConfigDef serviceConfigDefObj = new XXServiceConfigDef(); + serviceConfigDefObj.setAddedByUserId(Id); + serviceConfigDefObj.setCreateTime(new Date()); + serviceConfigDefObj.setDefaultvalue("simple"); + serviceConfigDefObj.setDescription("service config"); + serviceConfigDefObj.setId(Id); + serviceConfigDefObj.setIsMandatory(true); + serviceConfigDefObj.setName(name); + serviceConfigDefObj.setLabel("username"); + serviceConfigDefObj.setRbkeydescription(null); + serviceConfigDefObj.setRbkeylabel(null); + serviceConfigDefObj.setRbKeyValidationMessage(null); + serviceConfigDefObj.setType("password"); + serviceConfigDefList.add(serviceConfigDefObj); + + List contextEnrichersList = new ArrayList<>(); + XXContextEnricherDef contextEnricherDefObj = new XXContextEnricherDef(); + contextEnricherDefObj.setAddedByUserId(Id); + contextEnricherDefObj.setCreateTime(new Date()); + contextEnricherDefObj.setDefid(Id); + contextEnricherDefObj.setEnricher("RangerCountryProvider"); + contextEnricherDefObj.setName("country-provider"); + contextEnricherDefObj.setId(Id); + contextEnricherDefObj.setOrder(0); + contextEnricherDefObj.setUpdatedByUserId(Id); + contextEnricherDefObj.setUpdateTime(new Date()); + contextEnrichersList.add(contextEnricherDefObj); + + List xEnumList = new ArrayList<>(); + XXEnumDef enumDefObj = new XXEnumDef(); + enumDefObj.setAddedByUserId(Id); + enumDefObj.setCreateTime(new Date()); + enumDefObj.setDefaultindex(null); + enumDefObj.setDefid(Id); + enumDefObj.setId(Id); + enumDefObj.setName(name); + enumDefObj.setUpdatedByUserId(Id); + enumDefObj.setUpdateTime(new Date()); + xEnumList.add(enumDefObj); + + List xElementsList = new ArrayList<>(); + XXEnumElementDef enumElementDefObj = new XXEnumElementDef(); + enumElementDefObj.setAddedByUserId(Id); + enumElementDefObj.setCreateTime(new Date()); + enumElementDefObj.setEnumdefid(Id); + enumElementDefObj.setId(Id); + enumElementDefObj.setLabel("Authentication"); + enumElementDefObj.setName("authentication"); + enumElementDefObj.setUpdateTime(new Date()); + enumElementDefObj.setUpdatedByUserId(Id); + enumElementDefObj.setRbkeylabel(null); + enumElementDefObj.setOrder(0); + xElementsList.add(enumElementDefObj); + + Mockito.when(xServiceDefDao.getAll()).thenReturn(xServiceDefList); + + Mockito.when(daoManager.getXXPortalUser()).thenReturn(xPortalUserDao); + Mockito.when(xPortalUserDao.getById(Id)).thenReturn(tUser); + + Mockito.when(daoManager.getXXServiceConfigDef()).thenReturn(xServiceConfigDefDao); + Mockito.when(xServiceConfigDefDao.findByServiceDefId(serviceDef.getId())).thenReturn(serviceConfigDefList); + + Mockito.when(daoManager.getXXResourceDef()).thenReturn(xResourceDefDao); + + Mockito.when(daoManager.getXXAccessTypeDef()).thenReturn(xAccessTypeDefDao); + Mockito.when(xxAccessTypeDefGrantsDao.findImpliedGrantsByServiceDefId(Mockito.anyLong())).thenReturn(Collections.emptyMap()); + Mockito.when(daoManager.getXXAccessTypeDefGrants()).thenReturn(xxAccessTypeDefGrantsDao); + + Mockito.when(daoManager.getXXPolicyConditionDef()).thenReturn(xPolicyConditionDefDao); + + Mockito.when(daoManager.getXXContextEnricherDef()).thenReturn(xContextEnricherDefDao); + Mockito.when(xContextEnricherDefDao.findByServiceDefId(serviceDef.getId())).thenReturn(contextEnrichersList); + + Mockito.when(daoManager.getXXEnumDef()).thenReturn(xEnumDefDao); + Mockito.when(xEnumDefDao.findByServiceDefId(serviceDef.getId())).thenReturn(xEnumList); + + Mockito.when(daoManager.getXXEnumElementDef()).thenReturn(xEnumElementDefDao); + Mockito.when(xEnumElementDefDao.findByEnumDefId(enumElementDefObj.getId())).thenReturn(xElementsList); + + XXDataMaskTypeDefDao xDataMaskTypeDao = Mockito.mock(XXDataMaskTypeDefDao.class); + List xDataMaskTypeDefs = new ArrayList<>(); + Mockito.when(daoManager.getXXDataMaskTypeDef()).thenReturn(xDataMaskTypeDao); + Mockito.when(xDataMaskTypeDao.findByServiceDefId(serviceDef.getId())).thenReturn(xDataMaskTypeDefs); + + List dbRangerServiceDef = serviceDefService.getAllServiceDefs(); + Assert.assertNotNull(dbRangerServiceDef); + Mockito.verify(daoManager).getXXResourceDef(); + Mockito.verify(daoManager).getXXAccessTypeDef(); + Mockito.verify(daoManager).getXXPolicyConditionDef(); + Mockito.verify(daoManager).getXXContextEnricherDef(); + Mockito.verify(daoManager).getXXEnumDef(); + Mockito.verify(daoManager).getXXEnumElementDef(); + } + + @Test + public void test5getPopulatedViewObject() { + XXPortalUserDao xPortalUserDao = Mockito.mock(XXPortalUserDao.class); + XXServiceConfigDefDao xServiceConfigDefDao = Mockito.mock(XXServiceConfigDefDao.class); + + XXResourceDefDao xResourceDefDao = Mockito.mock(XXResourceDefDao.class); + XXAccessTypeDefDao xAccessTypeDefDao = Mockito.mock(XXAccessTypeDefDao.class); + XXAccessTypeDefGrantsDao xxAccessTypeDefGrantsDao = Mockito.mock(XXAccessTypeDefGrantsDao.class); + XXPolicyConditionDefDao xPolicyConditionDefDao = Mockito.mock(XXPolicyConditionDefDao.class); + XXContextEnricherDefDao xContextEnricherDefDao = Mockito.mock(XXContextEnricherDefDao.class); + XXEnumDefDao xEnumDefDao = Mockito.mock(XXEnumDefDao.class); + XXEnumElementDefDao xEnumElementDefDao = Mockito.mock(XXEnumElementDefDao.class); + + XXServiceDef serviceDef = serviceDef(); + String name = "fdfdfds"; + XXPortalUser tUser = new XXPortalUser(); + tUser.setAddedByUserId(Id); + tUser.setCreateTime(new Date()); + tUser.setEmailAddress("test@gmail.com"); + tUser.setFirstName(name); + tUser.setId(Id); + tUser.setLastName(name); + + List serviceConfigDefList = new ArrayList<>(); + XXServiceConfigDef serviceConfigDefObj = new XXServiceConfigDef(); + serviceConfigDefObj.setAddedByUserId(Id); + serviceConfigDefObj.setCreateTime(new Date()); + serviceConfigDefObj.setDefaultvalue("simple"); + serviceConfigDefObj.setDescription("service config"); + serviceConfigDefObj.setId(Id); + serviceConfigDefObj.setIsMandatory(true); + serviceConfigDefObj.setName(name); + serviceConfigDefObj.setLabel("username"); + serviceConfigDefObj.setRbkeydescription(null); + serviceConfigDefObj.setRbkeylabel(null); + serviceConfigDefObj.setRbKeyValidationMessage(null); + serviceConfigDefObj.setType("password"); + serviceConfigDefList.add(serviceConfigDefObj); + + List resDefList = new ArrayList<>(); + XXResourceDef resourceDef = new XXResourceDef(); + resourceDef.setAddedByUserId(Id); + resourceDef.setCreateTime(new Date()); + resourceDef.setDefid(Id); + resourceDef.setDescription("test"); + resourceDef.setId(Id); + resDefList.add(resourceDef); + + List xPolicyItemList = new ArrayList<>(); + XXPolicyItem xPolicyItem = new XXPolicyItem(); + xPolicyItem.setDelegateAdmin(false); + xPolicyItem.setAddedByUserId(null); + xPolicyItem.setCreateTime(new Date()); + xPolicyItem.setGUID(null); + xPolicyItem.setId(Id); + xPolicyItem.setOrder(null); + xPolicyItem.setPolicyId(Id); + xPolicyItem.setUpdatedByUserId(null); + xPolicyItem.setUpdateTime(new Date()); + xPolicyItemList.add(xPolicyItem); + + List policyItemAccessList = new ArrayList<>(); + XXPolicyItemAccess policyItemAccess = new XXPolicyItemAccess(); + policyItemAccess.setAddedByUserId(Id); + policyItemAccess.setCreateTime(new Date()); + policyItemAccess.setPolicyitemid(Id); + policyItemAccess.setId(Id); + policyItemAccess.setOrder(1); + policyItemAccess.setUpdatedByUserId(Id); + policyItemAccess.setUpdateTime(new Date()); + policyItemAccessList.add(policyItemAccess); + + List xConditionDefList = new ArrayList<>(); + XXPolicyConditionDef policyConditionDefObj = new XXPolicyConditionDef(); + policyConditionDefObj.setAddedByUserId(Id); + policyConditionDefObj.setCreateTime(new Date()); + policyConditionDefObj.setDefid(Id); + policyConditionDefObj.setDescription("policy condition"); + policyConditionDefObj.setId(Id); + policyConditionDefObj.setName(name); + policyConditionDefObj.setOrder(1); + policyConditionDefObj.setLabel("label"); + xConditionDefList.add(policyConditionDefObj); + + List policyItemConditionList = new ArrayList<>(); + XXPolicyItemCondition policyItemCondition = new XXPolicyItemCondition(); + policyItemCondition.setAddedByUserId(Id); + policyItemCondition.setCreateTime(new Date()); + policyItemCondition.setType(1L); + policyItemCondition.setId(Id); + policyItemCondition.setOrder(1); + policyItemCondition.setPolicyItemId(Id); + policyItemCondition.setUpdatedByUserId(Id); + policyItemCondition.setUpdateTime(new Date()); + policyItemConditionList.add(policyItemCondition); + + List contextEnrichersList = new ArrayList<>(); + XXContextEnricherDef contextEnricherDefObj = new XXContextEnricherDef(); + contextEnricherDefObj.setAddedByUserId(Id); + contextEnricherDefObj.setCreateTime(new Date()); + contextEnricherDefObj.setDefid(Id); + contextEnricherDefObj.setEnricher("RangerCountryProvider"); + contextEnricherDefObj.setName("country-provider"); + contextEnricherDefObj.setId(Id); + contextEnricherDefObj.setOrder(0); + contextEnricherDefObj.setUpdatedByUserId(Id); + contextEnricherDefObj.setUpdateTime(new Date()); + contextEnrichersList.add(contextEnricherDefObj); + + List xEnumList = new ArrayList<>(); + XXEnumDef enumDefObj = new XXEnumDef(); + enumDefObj.setAddedByUserId(Id); + enumDefObj.setCreateTime(new Date()); + enumDefObj.setDefaultindex(null); + enumDefObj.setDefid(Id); + enumDefObj.setId(Id); + enumDefObj.setName(name); + enumDefObj.setUpdatedByUserId(Id); + enumDefObj.setUpdateTime(new Date()); + xEnumList.add(enumDefObj); + + List xElementsList = new ArrayList<>(); + XXEnumElementDef enumElementDefObj = new XXEnumElementDef(); + enumElementDefObj.setAddedByUserId(Id); + enumElementDefObj.setCreateTime(new Date()); + enumElementDefObj.setEnumdefid(Id); + enumElementDefObj.setId(Id); + enumElementDefObj.setLabel("Authentication"); + enumElementDefObj.setName("authentication"); + enumElementDefObj.setUpdateTime(new Date()); + enumElementDefObj.setUpdatedByUserId(Id); + enumElementDefObj.setRbkeylabel(null); + enumElementDefObj.setOrder(0); + xElementsList.add(enumElementDefObj); + + Mockito.when(daoManager.getXXPortalUser()).thenReturn(xPortalUserDao); + Mockito.when(xPortalUserDao.getById(Id)).thenReturn(tUser); + + Mockito.when(daoManager.getXXServiceConfigDef()).thenReturn(xServiceConfigDefDao); + Mockito.when(xServiceConfigDefDao.findByServiceDefId(serviceDef.getId())).thenReturn(serviceConfigDefList); + + Mockito.when(daoManager.getXXResourceDef()).thenReturn(xResourceDefDao); + + Mockito.when(daoManager.getXXAccessTypeDef()).thenReturn(xAccessTypeDefDao); + Mockito.when(xxAccessTypeDefGrantsDao.findImpliedGrantsByServiceDefId(Mockito.anyLong())).thenReturn(Collections.emptyMap()); + Mockito.when(daoManager.getXXAccessTypeDefGrants()).thenReturn(xxAccessTypeDefGrantsDao); + + Mockito.when(daoManager.getXXPolicyConditionDef()).thenReturn(xPolicyConditionDefDao); + + Mockito.when(daoManager.getXXContextEnricherDef()).thenReturn(xContextEnricherDefDao); + Mockito.when(xContextEnricherDefDao.findByServiceDefId(serviceDef.getId())).thenReturn(contextEnrichersList); + + Mockito.when(daoManager.getXXEnumDef()).thenReturn(xEnumDefDao); + Mockito.when(xEnumDefDao.findByServiceDefId(serviceDef.getId())).thenReturn(xEnumList); + + Mockito.when(daoManager.getXXEnumElementDef()).thenReturn(xEnumElementDefDao); + Mockito.when(xEnumElementDefDao.findByEnumDefId(enumElementDefObj.getId())).thenReturn(xElementsList); + + XXDataMaskTypeDefDao xDataMaskTypeDao = Mockito.mock(XXDataMaskTypeDefDao.class); + List xDataMaskTypeDefs = new ArrayList<>(); + Mockito.when(daoManager.getXXDataMaskTypeDef()).thenReturn(xDataMaskTypeDao); + Mockito.when(xDataMaskTypeDao.findByServiceDefId(serviceDef.getId())).thenReturn(xDataMaskTypeDefs); + + RangerServiceDef dbRangerServiceDef = serviceDefService.getPopulatedViewObject(serviceDef); + Assert.assertNotNull(dbRangerServiceDef); + Mockito.verify(daoManager).getXXServiceConfigDef(); + Mockito.verify(daoManager).getXXResourceDef(); + Mockito.verify(daoManager).getXXAccessTypeDef(); + Mockito.verify(daoManager).getXXPolicyConditionDef(); + Mockito.verify(daoManager).getXXContextEnricherDef(); + Mockito.verify(daoManager).getXXEnumDef(); + } + + @Test + public void testImplicitConditionExpression() { + RangerServiceDef serviceDef = rangerServiceDef(); + int initCount = serviceDef.getPolicyConditions().size(); + boolean isAdded = serviceDefService.addImplicitConditionExpressionIfNeeded(serviceDef); + + // serviceDef doesn't have RangerScriptConditionEvaluator condition, hence should be added + Assert.assertTrue(isAdded); + + int postCount = serviceDef.getPolicyConditions().size(); + + Assert.assertEquals(initCount + 1, postCount); + + boolean exists = false; + + for (RangerPolicyConditionDef conditionDef : serviceDef.getPolicyConditions()) { + if (StringUtils.equals(conditionDef.getEvaluator(), ServiceDefUtil.IMPLICIT_CONDITION_EXPRESSION_EVALUATOR)) { + exists = true; + + break; + } + } + + Assert.assertTrue(exists); + + isAdded = serviceDefService.addImplicitConditionExpressionIfNeeded(serviceDef); + + // serviceDef already has RangerScriptConditionEvaluator, hence shouldn't be added again + Assert.assertFalse(isAdded); + } + + @Test + public void testImplicitConditionExpressionDisabled() { + PropertiesUtil.getPropertiesMap().put(PROP_ENABLE_IMPLICIT_CONDITION_EXPRESSION, Boolean.FALSE.toString()); + + try { + RangerServiceDef serviceDef = rangerServiceDef(); + int initCount = serviceDef.getPolicyConditions().size(); + boolean isAdded = serviceDefService.addImplicitConditionExpressionIfNeeded(serviceDef); + + // PROP_ENABLE_IMPLICIT_CONDITION_EXPR is false, hence shouldn't be added + Assert.assertFalse(isAdded); + + int postCount = serviceDef.getPolicyConditions().size(); + + Assert.assertEquals(initCount, postCount); + } finally { + PropertiesUtil.getPropertiesMap().remove(PROP_ENABLE_IMPLICIT_CONDITION_EXPRESSION); + } + } + + private RangerServiceDef rangerServiceDef() { + List configs = new ArrayList<>(); + List resources = new ArrayList<>(); + List accessTypes = new ArrayList<>(); + List policyConditions = new ArrayList<>(); + List contextEnrichers = new ArrayList<>(); + List enums = new ArrayList<>(); + + RangerServiceDef rangerServiceDef = new RangerServiceDef(); + rangerServiceDef.setId(Id); + rangerServiceDef.setImplClass("RangerServiceHdfs"); + rangerServiceDef.setLabel("HDFS Repository"); + rangerServiceDef.setDescription("HDFS Repository"); + rangerServiceDef.setRbKeyDescription(null); + rangerServiceDef.setUpdatedBy("Admin"); + rangerServiceDef.setUpdateTime(new Date()); + rangerServiceDef.setConfigs(configs); + rangerServiceDef.setResources(resources); + rangerServiceDef.setAccessTypes(accessTypes); + rangerServiceDef.setPolicyConditions(policyConditions); + rangerServiceDef.setContextEnrichers(contextEnrichers); + rangerServiceDef.setEnums(enums); + + return rangerServiceDef; + } + + private XXServiceDef serviceDef() { + XXServiceDef xServiceDef = new XXServiceDef(); + xServiceDef.setAddedByUserId(Id); + xServiceDef.setCreateTime(new Date()); + xServiceDef.setDescription("HDFS Repository"); + xServiceDef.setGuid("1427365526516_835_0"); + xServiceDef.setId(Id); + xServiceDef.setUpdateTime(new Date()); + xServiceDef.setUpdatedByUserId(Id); + xServiceDef.setImplclassname("RangerServiceHdfs"); + xServiceDef.setLabel("HDFS Repository"); + xServiceDef.setRbkeylabel(null); + xServiceDef.setRbkeydescription(null); + xServiceDef.setIsEnabled(true); + + return xServiceDef; + } } diff --git a/security-admin/src/test/java/org/apache/ranger/service/TestRangerServiceDefServiceBase.java b/security-admin/src/test/java/org/apache/ranger/service/TestRangerServiceDefServiceBase.java index b54c9a2ac1..f4640b9c7c 100644 --- a/security-admin/src/test/java/org/apache/ranger/service/TestRangerServiceDefServiceBase.java +++ b/security-admin/src/test/java/org/apache/ranger/service/TestRangerServiceDefServiceBase.java @@ -16,13 +16,6 @@ */ package org.apache.ranger.service; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Date; -import java.util.List; - -import javax.ws.rs.WebApplicationException; - import org.apache.ranger.biz.RangerBizUtil; import org.apache.ranger.common.ContextUtil; import org.apache.ranger.common.GUIDUtil; @@ -67,717 +60,569 @@ import org.mockito.Mockito; import org.mockito.junit.MockitoJUnitRunner; +import javax.ws.rs.WebApplicationException; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.Date; +import java.util.List; + @RunWith(MockitoJUnitRunner.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class TestRangerServiceDefServiceBase { - - private static Long Id = 8L; - - @InjectMocks - RangerServiceDefService rangerServiceDefService = new RangerServiceDefService(); - - @Mock - RangerDaoManager daoManager; - - @Mock - RESTErrorUtil restErrorUtil; - - @Mock - ContextUtil contextUtil; - - @Mock - RangerAuditFields rangerAuditFields; - - @Mock - RangerBizUtil rangerBizUtil; - - @Mock - RangerSearchUtil searchUtil; - - @Mock - GUIDUtil guidUtil; - - @Mock - JSONUtil jsonUtil; - - @Mock - BaseDao baseDao; - - @Rule - public ExpectedException thrown = ExpectedException.none(); - - public void setup() { - RangerSecurityContext context = new RangerSecurityContext(); - context.setUserSession(new UserSessionBase()); - RangerContextHolder.setSecurityContext(context); - UserSessionBase currentUserSession = ContextUtil - .getCurrentUserSession(); - currentUserSession.setUserAdmin(true); - } - - private RangerServiceDef rangerServiceDef() { - List configs = new ArrayList(); - List resources = new ArrayList(); - List accessTypes = new ArrayList(); - List policyConditions = new ArrayList(); - List contextEnrichers = new ArrayList(); - List enums = new ArrayList(); - - RangerServiceDef rangerServiceDef = new RangerServiceDef(); - rangerServiceDef.setId(Id); - rangerServiceDef.setImplClass("RangerServiceHdfs"); - rangerServiceDef.setLabel("HDFS Repository"); - rangerServiceDef.setDescription("HDFS Repository"); - rangerServiceDef.setRbKeyDescription(null); - rangerServiceDef.setUpdatedBy("Admin"); - rangerServiceDef.setUpdateTime(new Date()); - rangerServiceDef.setConfigs(configs); - rangerServiceDef.setResources(resources); - rangerServiceDef.setAccessTypes(accessTypes); - rangerServiceDef.setPolicyConditions(policyConditions); - rangerServiceDef.setContextEnrichers(contextEnrichers); - rangerServiceDef.setEnums(enums); - - return rangerServiceDef; - } - - private XXServiceDef serviceDef() { - XXServiceDef xServiceDef = new XXServiceDef(); - xServiceDef.setAddedByUserId(Id); - xServiceDef.setCreateTime(new Date()); - xServiceDef.setDescription("HDFS Repository"); - xServiceDef.setGuid("0d047247-bafe-4cf8-8e9b-d5d377284b2d"); - xServiceDef.setId(Id); - xServiceDef.setImplclassname("RangerServiceHdfs"); - xServiceDef.setIsEnabled(true); - xServiceDef.setLabel("HDFS Repository"); - xServiceDef.setName("hdfs"); - xServiceDef.setRbkeydescription(null); - xServiceDef.setRbkeylabel(null); - xServiceDef.setUpdatedByUserId(Id); - xServiceDef.setUpdateTime(new Date()); - - return xServiceDef; - } - - @Test - public void test1MapViewToEntityBean() { - RangerServiceDef rangerServiceDef = rangerServiceDef(); - XXServiceDef serviceDef = serviceDef(); - int operationContext = 1; - - XXServiceDef dbServiceDef = rangerServiceDefService - .mapViewToEntityBean(rangerServiceDef, serviceDef, - operationContext); - Assert.assertNotNull(dbServiceDef); - Assert.assertEquals(dbServiceDef, serviceDef); - Assert.assertEquals(dbServiceDef.getDescription(), - serviceDef.getDescription()); - Assert.assertEquals(dbServiceDef.getGuid(), serviceDef.getGuid()); - Assert.assertEquals(dbServiceDef.getName(), serviceDef.getName()); - Assert.assertEquals(dbServiceDef.getAddedByUserId(), - serviceDef.getAddedByUserId()); - Assert.assertEquals(dbServiceDef.getId(), serviceDef.getId()); - Assert.assertEquals(dbServiceDef.getVersion(), serviceDef.getVersion()); - Assert.assertEquals(dbServiceDef.getImplclassname(), - serviceDef.getImplclassname()); - Assert.assertEquals(dbServiceDef.getUpdatedByUserId(), - serviceDef.getUpdatedByUserId()); - } - - @Test - public void test2MapEntityToViewBean() { - RangerServiceDef rangerServiceDef = rangerServiceDef(); - XXServiceDef serviceDef = serviceDef(); - - RangerServiceDef dbRangerServiceDef = rangerServiceDefService - .mapEntityToViewBean(rangerServiceDef, serviceDef); - Assert.assertNotNull(dbRangerServiceDef); - Assert.assertEquals(dbRangerServiceDef, rangerServiceDef); - Assert.assertEquals(dbRangerServiceDef.getDescription(), - rangerServiceDef.getDescription()); - Assert.assertEquals(dbRangerServiceDef.getGuid(), - rangerServiceDef.getGuid()); - Assert.assertEquals(dbRangerServiceDef.getName(), - rangerServiceDef.getName()); - Assert.assertEquals(dbRangerServiceDef.getId(), - rangerServiceDef.getId()); - Assert.assertEquals(dbRangerServiceDef.getVersion(), - rangerServiceDef.getVersion()); - - } - - @Test - public void test3populateRangerServiceConfigDefToXX() { - RangerServiceConfigDef serviceConfigDefObj = new RangerServiceConfigDef(); - XXServiceConfigDef configDefObj = new XXServiceConfigDef(); - XXServiceDef serviceDefObj = new XXServiceDef(); - - Mockito.when( - (XXServiceConfigDef) rangerAuditFields.populateAuditFields( - configDefObj, serviceDefObj)).thenReturn(configDefObj); - - XXServiceConfigDef dbServiceConfigDef = rangerServiceDefService - .populateRangerServiceConfigDefToXX(serviceConfigDefObj, - configDefObj, serviceDefObj, 1); - Assert.assertNotNull(dbServiceConfigDef); - - } - - @Test - public void test4populateXXToRangerServiceConfigDef() { - XXServiceConfigDef serviceConfigDefObj = new XXServiceConfigDef(); - - RangerServiceConfigDef dbserviceConfigDefObj = rangerServiceDefService - .populateXXToRangerServiceConfigDef(serviceConfigDefObj); - Assert.assertNotNull(dbserviceConfigDefObj); - } - - @Test - public void test5populateRangerResourceDefToXX() { - RangerResourceDef rangerResourceDefObj = new RangerResourceDef(); - rangerResourceDefObj.setDescription("HDFS Repository"); - rangerResourceDefObj.setExcludesSupported(false); - rangerResourceDefObj.setLabel("HDFS Repository"); - rangerResourceDefObj.setName("HDFs"); - - XXResourceDef resourceDefObj = new XXResourceDef(); - resourceDefObj.setAddedByUserId(Id); - resourceDefObj.setCreateTime(new Date()); - resourceDefObj.setDefid(Id); - resourceDefObj.setDescription("HDFS Repository"); - resourceDefObj.setId(Id); - - XXServiceDef serviceDefObj = new XXServiceDef(); - serviceDefObj.setAddedByUserId(Id); - serviceDefObj.setCreateTime(new Date()); - serviceDefObj.setDescription("HDFS Repository"); - serviceDefObj.setGuid("1427365526516_835_0"); - serviceDefObj.setId(Id); - - Mockito.when( - (XXResourceDef) rangerAuditFields.populateAuditFields( - resourceDefObj, serviceDefObj)).thenReturn( - resourceDefObj); - - XXResourceDef dbResourceDef = rangerServiceDefService - .populateRangerResourceDefToXX(rangerResourceDefObj, - resourceDefObj, serviceDefObj, 1); - Assert.assertNotNull(dbResourceDef); - Assert.assertEquals(dbResourceDef, resourceDefObj); - Assert.assertEquals(dbResourceDef.getId(), resourceDefObj.getId()); - Assert.assertEquals(dbResourceDef.getLabel(), resourceDefObj.getLabel()); - Assert.assertEquals(dbResourceDef.getName(), resourceDefObj.getName()); - Assert.assertEquals(dbResourceDef.getDescription(), - resourceDefObj.getDescription()); - - } - - @Test - public void test6populateXXToRangerResourceDef() { - XXResourceDefDao xResourceDefDao = Mockito.mock(XXResourceDefDao.class); - XXResourceDef resourceDefObj = new XXResourceDef(); - resourceDefObj.setAddedByUserId(Id); - resourceDefObj.setCreateTime(new Date()); - resourceDefObj.setDefid(Id); - resourceDefObj.setDescription("HDFS Repository"); - resourceDefObj.setId(Id); - - Mockito.when(daoManager.getXXResourceDef()).thenReturn(xResourceDefDao); - - RangerResourceDef dbRangerResourceDef = rangerServiceDefService - .populateXXToRangerResourceDef(resourceDefObj); - Assert.assertNotNull(dbRangerResourceDef); - Assert.assertEquals(dbRangerResourceDef.getName(), - resourceDefObj.getName()); - Assert.assertEquals(dbRangerResourceDef.getDescription(), - resourceDefObj.getDescription()); - Assert.assertEquals(dbRangerResourceDef.getType(), - resourceDefObj.getType()); - Assert.assertEquals(dbRangerResourceDef.getRbKeyDescription(), - resourceDefObj.getRbkeydescription()); - Mockito.verify(daoManager).getXXResourceDef(); - } - - @Test - public void test7populateRangerAccessTypeDefToXX() { - RangerAccessTypeDef rangerAccessTypeDefObj = new RangerAccessTypeDef(); - rangerAccessTypeDefObj.setLabel("Read"); - rangerAccessTypeDefObj.setName("read"); - rangerAccessTypeDefObj.setRbKeyLabel(null); - XXAccessTypeDef accessTypeDefObj = new XXAccessTypeDef(); - accessTypeDefObj.setAddedByUserId(Id); - accessTypeDefObj.setCreateTime(new Date()); - accessTypeDefObj.setDefid(Id); - accessTypeDefObj.setId(Id); - accessTypeDefObj.setLabel("Read"); - accessTypeDefObj.setName("read"); - accessTypeDefObj.setOrder(null); - accessTypeDefObj.setRbkeylabel(null); - accessTypeDefObj.setUpdatedByUserId(Id); - accessTypeDefObj.setUpdateTime(new Date()); - XXServiceDef serviceDefObj = new XXServiceDef(); - serviceDefObj.setAddedByUserId(Id); - serviceDefObj.setCreateTime(new Date()); - serviceDefObj.setDescription("HDFS Repository"); - serviceDefObj.setGuid("1427365526516_835_0"); - serviceDefObj.setId(Id); - - Mockito.when( - (XXAccessTypeDef) rangerAuditFields.populateAuditFields( - accessTypeDefObj, serviceDefObj)).thenReturn( - accessTypeDefObj); - - XXAccessTypeDef dbAccessTypeDef = rangerServiceDefService - .populateRangerAccessTypeDefToXX(rangerAccessTypeDefObj, - accessTypeDefObj, serviceDefObj, 1); - Assert.assertNotNull(dbAccessTypeDef); - Assert.assertEquals(dbAccessTypeDef, accessTypeDefObj); - Assert.assertEquals(dbAccessTypeDef.getName(), - accessTypeDefObj.getName()); - Assert.assertEquals(dbAccessTypeDef.getLabel(), - accessTypeDefObj.getLabel()); - Assert.assertEquals(dbAccessTypeDef.getRbkeylabel(), - accessTypeDefObj.getRbkeylabel()); - Assert.assertEquals(dbAccessTypeDef.getDefid(), - accessTypeDefObj.getDefid()); - Assert.assertEquals(dbAccessTypeDef.getId(), accessTypeDefObj.getId()); - Assert.assertEquals(dbAccessTypeDef.getCreateTime(), - accessTypeDefObj.getCreateTime()); - Assert.assertEquals(dbAccessTypeDef.getOrder(), - accessTypeDefObj.getOrder()); - - } - - @Test - public void test8populateRangerAccessTypeDefToXXNullValue() { - RangerAccessTypeDef rangerAccessTypeDefObj = null; - XXAccessTypeDef accessTypeDefObj = null; - XXServiceDef serviceDefObj = null; - Mockito.when( - restErrorUtil.createRESTException( - "RangerServiceDef cannot be null.", - MessageEnums.DATA_NOT_FOUND)).thenThrow( - new WebApplicationException()); - - thrown.expect(WebApplicationException.class); - XXAccessTypeDef dbAccessTypeDef = rangerServiceDefService - .populateRangerAccessTypeDefToXX(rangerAccessTypeDefObj, - accessTypeDefObj, serviceDefObj, 1); - Assert.assertNull(dbAccessTypeDef); - } - - @Test - public void test9populateXXToRangerAccessTypeDef() { - - XXAccessTypeDef accessTypeDefObj = new XXAccessTypeDef(); - accessTypeDefObj.setAddedByUserId(Id); - accessTypeDefObj.setCreateTime(new Date()); - accessTypeDefObj.setDefid(Id); - accessTypeDefObj.setId(Id); - accessTypeDefObj.setLabel("Read"); - accessTypeDefObj.setName("read"); - accessTypeDefObj.setOrder(null); - accessTypeDefObj.setRbkeylabel(null); - accessTypeDefObj.setUpdatedByUserId(Id); - accessTypeDefObj.setUpdateTime(new Date()); - - RangerAccessTypeDef dbRangerAccessTypeDef = rangerServiceDefService - .populateXXToRangerAccessTypeDef(accessTypeDefObj, Collections.emptyList()); - Assert.assertNotNull(dbRangerAccessTypeDef); - Assert.assertEquals(dbRangerAccessTypeDef.getName(), - accessTypeDefObj.getName()); - Assert.assertEquals(dbRangerAccessTypeDef.getLabel(), - accessTypeDefObj.getLabel()); - Assert.assertEquals(dbRangerAccessTypeDef.getRbKeyLabel(), - accessTypeDefObj.getRbkeylabel()); - } - - @Test - public void test10populateRangerPolicyConditionDefToXX() { - RangerPolicyConditionDef rangerConditionDefvObj = new RangerPolicyConditionDef(); - rangerConditionDefvObj.setDescription("Countries"); - rangerConditionDefvObj.setEvaluator("COUNTRY"); - rangerConditionDefvObj.setLabel("Countries"); - rangerConditionDefvObj.setName("country"); - rangerConditionDefvObj.setRbKeyDescription(null); - rangerConditionDefvObj.setRbKeyLabel(null); - XXPolicyConditionDef policyConditionDefObj = new XXPolicyConditionDef(); - policyConditionDefObj.setAddedByUserId(Id); - policyConditionDefObj.setCreateTime(new Date()); - policyConditionDefObj.setDefid(Id); - policyConditionDefObj.setDescription("policy"); - policyConditionDefObj.setId(Id); - policyConditionDefObj.setName("country"); - policyConditionDefObj.setOrder(0); - policyConditionDefObj.setUpdatedByUserId(Id); - policyConditionDefObj.setUpdateTime(new Date()); - XXServiceDef serviceDefObj = new XXServiceDef(); - serviceDefObj.setAddedByUserId(Id); - serviceDefObj.setCreateTime(new Date()); - serviceDefObj.setDescription("HDFS Repository"); - serviceDefObj.setGuid("1427365526516_835_0"); - serviceDefObj.setId(Id); - Mockito.when( - (XXPolicyConditionDef) rangerAuditFields.populateAuditFields( - policyConditionDefObj, serviceDefObj)).thenReturn( - policyConditionDefObj); - XXPolicyConditionDef dbPolicyConditionDef = rangerServiceDefService - .populateRangerPolicyConditionDefToXX(rangerConditionDefvObj, - policyConditionDefObj, serviceDefObj, 1); - Assert.assertNotNull(dbPolicyConditionDef); - Assert.assertEquals(dbPolicyConditionDef.getName(), - policyConditionDefObj.getName()); - Assert.assertEquals(dbPolicyConditionDef.getDescription(), - policyConditionDefObj.getDescription()); - Assert.assertEquals(dbPolicyConditionDef.getEvaluator(), - policyConditionDefObj.getEvaluator()); - Assert.assertEquals(dbPolicyConditionDef.getLabel(), - policyConditionDefObj.getLabel()); - Assert.assertEquals(dbPolicyConditionDef.getId(), - policyConditionDefObj.getId()); - Assert.assertEquals(dbPolicyConditionDef.getRbkeydescription(), - policyConditionDefObj.getRbkeydescription()); - Assert.assertEquals(dbPolicyConditionDef.getOrder(), - policyConditionDefObj.getOrder()); - Assert.assertEquals(dbPolicyConditionDef.getUpdatedByUserId(), - policyConditionDefObj.getUpdatedByUserId()); - Assert.assertEquals(dbPolicyConditionDef.getUpdateTime(), - policyConditionDefObj.getUpdateTime()); - - } - - @Test - public void test11populateRangerPolicyConditionDefToXXnullValue() { - RangerPolicyConditionDef rangerConditionDefvObj = null; - XXPolicyConditionDef policyConditionDefObj = null; - XXServiceDef serviceDefObj = null; - - Mockito.when( - restErrorUtil.createRESTException( - "RangerServiceDef cannot be null.", - MessageEnums.DATA_NOT_FOUND)).thenThrow( - new WebApplicationException()); - - thrown.expect(WebApplicationException.class); - - XXPolicyConditionDef dbPolicyConditionDef = rangerServiceDefService - .populateRangerPolicyConditionDefToXX(rangerConditionDefvObj, - policyConditionDefObj, serviceDefObj, 1); - Assert.assertNull(dbPolicyConditionDef); - } - - @Test - public void test12populateXXToRangerPolicyConditionDef() { - XXPolicyConditionDef policyConditionDefObj = new XXPolicyConditionDef(); - policyConditionDefObj.setAddedByUserId(Id); - policyConditionDefObj.setCreateTime(new Date()); - policyConditionDefObj.setDefid(Id); - policyConditionDefObj.setDescription("policy"); - policyConditionDefObj.setId(Id); - policyConditionDefObj.setName("country"); - policyConditionDefObj.setOrder(0); - policyConditionDefObj.setUpdatedByUserId(Id); - policyConditionDefObj.setUpdateTime(new Date()); - - RangerPolicyConditionDef dbRangerPolicyConditionDef = rangerServiceDefService - .populateXXToRangerPolicyConditionDef(policyConditionDefObj); - Assert.assertNotNull(dbRangerPolicyConditionDef); - Assert.assertEquals(dbRangerPolicyConditionDef.getName(), - policyConditionDefObj.getName()); - Assert.assertEquals(dbRangerPolicyConditionDef.getDescription(), - policyConditionDefObj.getDescription()); - Assert.assertEquals(dbRangerPolicyConditionDef.getEvaluator(), - policyConditionDefObj.getEvaluator()); - Assert.assertEquals(dbRangerPolicyConditionDef.getLabel(), - policyConditionDefObj.getLabel()); - } - - @Test - public void test13populateRangerContextEnricherDefToXX() { - RangerContextEnricherDef rangerContextEnricherDefObj = new RangerContextEnricherDef(); - rangerContextEnricherDefObj.setName("country-provider"); - rangerContextEnricherDefObj.setEnricher("RangerCountryProvider"); - - XXContextEnricherDef contextEnricherDefObj = new XXContextEnricherDef(); - contextEnricherDefObj.setAddedByUserId(Id); - contextEnricherDefObj.setCreateTime(new Date()); - contextEnricherDefObj.setDefid(Id); - contextEnricherDefObj.setId(Id); - contextEnricherDefObj.setName("country-provider"); - contextEnricherDefObj - .setEnricherOptions("contextName=COUNTRY;dataFile=/etc/ranger/data/userCountry.properties"); - contextEnricherDefObj.setEnricher("RangerCountryProvider"); - contextEnricherDefObj.setOrder(null); - contextEnricherDefObj.setUpdatedByUserId(Id); - contextEnricherDefObj.setUpdateTime(new Date()); - XXServiceDef serviceDefObj = new XXServiceDef(); - serviceDefObj.setAddedByUserId(Id); - serviceDefObj.setCreateTime(new Date()); - serviceDefObj.setDescription("HDFS Repository"); - serviceDefObj.setGuid("1427365526516_835_0"); - serviceDefObj.setId(Id); - - Mockito.when( - (XXContextEnricherDef) rangerAuditFields.populateAuditFields( - contextEnricherDefObj, serviceDefObj)).thenReturn( - contextEnricherDefObj); - - XXContextEnricherDef dbContextEnricherDef = rangerServiceDefService - .populateRangerContextEnricherDefToXX( - rangerContextEnricherDefObj, contextEnricherDefObj, - serviceDefObj, 1); - Assert.assertNotNull(dbContextEnricherDef); - Assert.assertEquals(dbContextEnricherDef.getEnricher(), - contextEnricherDefObj.getEnricher()); - Assert.assertEquals(dbContextEnricherDef.getEnricherOptions(), - contextEnricherDefObj.getEnricherOptions()); - Assert.assertEquals(dbContextEnricherDef.getName(), - contextEnricherDefObj.getName()); - Assert.assertEquals(dbContextEnricherDef.getCreateTime(), - contextEnricherDefObj.getCreateTime()); - Assert.assertEquals(dbContextEnricherDef.getId(), - contextEnricherDefObj.getId()); - Assert.assertEquals(dbContextEnricherDef.getOrder(), - contextEnricherDefObj.getOrder()); - Assert.assertEquals(dbContextEnricherDef.getUpdatedByUserId(), - contextEnricherDefObj.getUpdatedByUserId()); - Assert.assertEquals(dbContextEnricherDef.getUpdateTime(), - contextEnricherDefObj.getUpdateTime()); - - } - - @Test - public void test14populateRangerContextEnricherDefToXXnullValue() { - RangerContextEnricherDef rangerContextEnricherDefObj = null; - XXContextEnricherDef contextEnricherDefObj = null; - XXServiceDef serviceDefObj = null; - - Mockito.when( - restErrorUtil.createRESTException( - "RangerServiceDef cannot be null.", - MessageEnums.DATA_NOT_FOUND)).thenThrow( - new WebApplicationException()); - - thrown.expect(WebApplicationException.class); - - XXContextEnricherDef dbContextEnricherDef = rangerServiceDefService - .populateRangerContextEnricherDefToXX( - rangerContextEnricherDefObj, contextEnricherDefObj, - serviceDefObj, 1); - Assert.assertNull(dbContextEnricherDef); - - } - - @Test - public void test15populateXXToRangerContextEnricherDef() { - XXContextEnricherDef contextEnricherDefObj = new XXContextEnricherDef(); - contextEnricherDefObj.setAddedByUserId(Id); - contextEnricherDefObj.setCreateTime(new Date()); - contextEnricherDefObj.setDefid(Id); - contextEnricherDefObj.setId(Id); - contextEnricherDefObj.setName("country-provider"); - contextEnricherDefObj - .setEnricherOptions("contextName=COUNTRY;dataFile=/etc/ranger/data/userCountry.properties"); - contextEnricherDefObj.setEnricher("RangerCountryProvider"); - contextEnricherDefObj.setOrder(null); - contextEnricherDefObj.setUpdatedByUserId(Id); - contextEnricherDefObj.setUpdateTime(new Date()); - - RangerContextEnricherDef dbRangerContextEnricherDef = rangerServiceDefService - .populateXXToRangerContextEnricherDef(contextEnricherDefObj); - Assert.assertNotNull(dbRangerContextEnricherDef); - Assert.assertEquals(dbRangerContextEnricherDef.getEnricher(), - contextEnricherDefObj.getEnricher()); - Assert.assertEquals(dbRangerContextEnricherDef.getName(), - contextEnricherDefObj.getName()); - - } - - @Test - public void test16populateRangerEnumDefToXX() { - RangerEnumDef rangerEnumDefObj = new RangerEnumDef(); - rangerEnumDefObj.setName("authnType"); - rangerEnumDefObj.setDefaultIndex(0); - XXEnumDef enumDefObj = new XXEnumDef(); - enumDefObj.setAddedByUserId(Id); - enumDefObj.setCreateTime(new Date()); - enumDefObj.setDefaultindex(0); - enumDefObj.setDefid(Id); - enumDefObj.setId(Id); - enumDefObj.setName("authnType"); - enumDefObj.setUpdatedByUserId(Id); - enumDefObj.setUpdateTime(new Date()); - XXServiceDef serviceDefObj = new XXServiceDef(); - serviceDefObj.setAddedByUserId(Id); - serviceDefObj.setCreateTime(new Date()); - serviceDefObj.setDescription("HDFS Repository"); - serviceDefObj.setGuid("1427365526516_835_0"); - serviceDefObj.setId(Id); - - Mockito.when( - (XXEnumDef) rangerAuditFields.populateAuditFields(enumDefObj, - serviceDefObj)).thenReturn(enumDefObj); - - XXEnumDef dbEnumDef = rangerServiceDefService - .populateRangerEnumDefToXX(rangerEnumDefObj, enumDefObj, - serviceDefObj,1); - Assert.assertNotNull(dbEnumDef); - Assert.assertEquals(dbEnumDef, enumDefObj); - Assert.assertEquals(dbEnumDef.getName(), enumDefObj.getName()); - Assert.assertEquals(dbEnumDef.getDefid(), enumDefObj.getDefid()); - Assert.assertEquals(dbEnumDef.getId(), enumDefObj.getId()); - Assert.assertEquals(dbEnumDef.getCreateTime(), - enumDefObj.getCreateTime()); - - } - - @Test - public void test17populateRangerEnumDefToXXnullValue() { - RangerEnumDef rangerEnumDefObj = null; - XXEnumDef enumDefObj = null; - XXServiceDef serviceDefObj = null; - - Mockito.when( - restErrorUtil.createRESTException( - "RangerServiceDef cannot be null.", - MessageEnums.DATA_NOT_FOUND)).thenThrow( - new WebApplicationException()); - - thrown.expect(WebApplicationException.class); - - XXEnumDef dbEnumDef = rangerServiceDefService - .populateRangerEnumDefToXX(rangerEnumDefObj, enumDefObj, - serviceDefObj, 1); - Assert.assertNull(dbEnumDef); - - } - - @Test - public void test18populateXXToRangerEnumDef() { - XXEnumElementDefDao xEnumElementDefDao = Mockito - .mock(XXEnumElementDefDao.class); - - List enumElementDefList = new ArrayList(); - XXEnumElementDef enumElementDefObj = new XXEnumElementDef(); - enumElementDefObj.setAddedByUserId(Id); - enumElementDefObj.setCreateTime(new Date()); - enumElementDefObj.setEnumdefid(Id); - enumElementDefObj.setId(Id); - enumElementDefObj.setLabel("Simple"); - enumElementDefObj.setName("simple"); - enumElementDefObj.setOrder(0); - enumElementDefObj.setUpdatedByUserId(Id); - enumElementDefObj.setUpdateTime(new Date()); - enumElementDefList.add(enumElementDefObj); - - XXEnumDef enumDefObj = new XXEnumDef(); - enumDefObj.setAddedByUserId(Id); - enumDefObj.setCreateTime(new Date()); - enumDefObj.setDefaultindex(0); - enumDefObj.setDefid(Id); - enumDefObj.setId(Id); - enumDefObj.setName("authnType"); - enumDefObj.setUpdatedByUserId(Id); - enumDefObj.setUpdateTime(new Date()); - - Mockito.when(daoManager.getXXEnumElementDef()).thenReturn( - xEnumElementDefDao); - Mockito.when(xEnumElementDefDao.findByEnumDefId(enumDefObj.getId())) - .thenReturn(enumElementDefList); - - RangerEnumDef dbRangerEnumDef = rangerServiceDefService - .populateXXToRangerEnumDef(enumDefObj); - Assert.assertNotNull(dbRangerEnumDef); - Assert.assertEquals(dbRangerEnumDef.getName(), enumDefObj.getName()); - - Mockito.verify(daoManager).getXXEnumElementDef(); - } - - @Test - public void test19populateRangerEnumElementDefToXX() { - - RangerEnumElementDef rangerEnumElementDefObj = new RangerEnumElementDef(); - rangerEnumElementDefObj.setLabel("Simple"); - rangerEnumElementDefObj.setName("simple"); - rangerEnumElementDefObj.setRbKeyLabel(null); - XXEnumElementDef enumElementDefObj = new XXEnumElementDef(); - enumElementDefObj.setAddedByUserId(Id); - enumElementDefObj.setCreateTime(new Date()); - enumElementDefObj.setEnumdefid(Id); - enumElementDefObj.setId(Id); - enumElementDefObj.setLabel("Simple"); - enumElementDefObj.setName("simple"); - enumElementDefObj.setOrder(0); - enumElementDefObj.setUpdatedByUserId(Id); - enumElementDefObj.setUpdateTime(new Date()); - XXEnumDef enumDefObj = new XXEnumDef(); - enumDefObj.setAddedByUserId(Id); - enumDefObj.setCreateTime(new Date()); - enumDefObj.setDefaultindex(0); - enumDefObj.setDefid(Id); - enumDefObj.setId(Id); - enumDefObj.setName("authnType"); - enumDefObj.setUpdatedByUserId(Id); - enumDefObj.setUpdateTime(new Date()); - - Mockito.when( - (XXEnumElementDef) rangerAuditFields.populateAuditFields( - enumElementDefObj, enumDefObj)).thenReturn( - enumElementDefObj); - XXEnumElementDef dbEnumElementDef = rangerServiceDefService - .populateRangerEnumElementDefToXX(rangerEnumElementDefObj, - enumElementDefObj, enumDefObj, 1); - Assert.assertNotNull(dbEnumElementDef); - Assert.assertEquals(dbEnumElementDef.getId(), enumElementDefObj.getId()); - Assert.assertEquals(dbEnumElementDef.getName(), - enumElementDefObj.getName()); - Assert.assertEquals(dbEnumElementDef.getLabel(), - enumElementDefObj.getLabel()); - Assert.assertEquals(dbEnumElementDef.getCreateTime(), - enumElementDefObj.getCreateTime()); - Assert.assertEquals(dbEnumElementDef.getAddedByUserId(), - enumElementDefObj.getAddedByUserId()); - Assert.assertEquals(dbEnumElementDef.getUpdateTime(), - enumElementDefObj.getUpdateTime()); - Assert.assertEquals(dbEnumElementDef.getUpdatedByUserId(), - enumElementDefObj.getUpdatedByUserId()); - Mockito.verify(rangerAuditFields).populateAuditFields( - enumElementDefObj, enumDefObj); - } - - @Test - public void test20populateXXToRangerEnumElementDef() { - XXEnumElementDef enumElementDefObj = new XXEnumElementDef(); - enumElementDefObj.setAddedByUserId(Id); - enumElementDefObj.setCreateTime(new Date()); - enumElementDefObj.setEnumdefid(Id); - enumElementDefObj.setId(Id); - enumElementDefObj.setLabel("Simple"); - enumElementDefObj.setName("simple"); - enumElementDefObj.setOrder(0); - enumElementDefObj.setUpdatedByUserId(Id); - enumElementDefObj.setUpdateTime(new Date()); - - RangerEnumElementDef dbRangerEnumElementDef = rangerServiceDefService - .populateXXToRangerEnumElementDef(enumElementDefObj); - Assert.assertNotNull(dbRangerEnumElementDef); - Assert.assertEquals(dbRangerEnumElementDef.getLabel(), - enumElementDefObj.getLabel()); - Assert.assertEquals(dbRangerEnumElementDef.getName(), - enumElementDefObj.getName()); - - } - - @Test - public void test21searchRangerServiceDefs() { - setup(); - SearchFilter searchFilter = new SearchFilter(); - searchFilter.setParam(SearchFilter.POLICY_NAME, "policyName"); - searchFilter.setParam(SearchFilter.SERVICE_NAME, "serviceName"); - - RangerServiceDefList dbRangerServiceDefList = rangerServiceDefService - .searchRangerServiceDefs(searchFilter); - Assert.assertNotNull(dbRangerServiceDefList); - } + private static final Long Id = 8L; + @Rule + public ExpectedException thrown = ExpectedException.none(); + @InjectMocks + RangerServiceDefService rangerServiceDefService = new RangerServiceDefService(); + @Mock + RangerDaoManager daoManager; + @Mock + RESTErrorUtil restErrorUtil; + @Mock + ContextUtil contextUtil; + @Mock + RangerAuditFields rangerAuditFields; + @Mock + RangerBizUtil rangerBizUtil; + @Mock + RangerSearchUtil searchUtil; + @Mock + GUIDUtil guidUtil; + @Mock + JSONUtil jsonUtil; + @Mock + BaseDao baseDao; + + public void setup() { + RangerSecurityContext context = new RangerSecurityContext(); + context.setUserSession(new UserSessionBase()); + RangerContextHolder.setSecurityContext(context); + UserSessionBase currentUserSession = ContextUtil + .getCurrentUserSession(); + currentUserSession.setUserAdmin(true); + } + + @Test + public void test1MapViewToEntityBean() { + RangerServiceDef rangerServiceDef = rangerServiceDef(); + XXServiceDef serviceDef = serviceDef(); + int operationContext = 1; + + XXServiceDef dbServiceDef = rangerServiceDefService.mapViewToEntityBean(rangerServiceDef, serviceDef, operationContext); + Assert.assertNotNull(dbServiceDef); + Assert.assertEquals(dbServiceDef, serviceDef); + Assert.assertEquals(dbServiceDef.getDescription(), serviceDef.getDescription()); + Assert.assertEquals(dbServiceDef.getGuid(), serviceDef.getGuid()); + Assert.assertEquals(dbServiceDef.getName(), serviceDef.getName()); + Assert.assertEquals(dbServiceDef.getAddedByUserId(), serviceDef.getAddedByUserId()); + Assert.assertEquals(dbServiceDef.getId(), serviceDef.getId()); + Assert.assertEquals(dbServiceDef.getVersion(), serviceDef.getVersion()); + Assert.assertEquals(dbServiceDef.getImplclassname(), serviceDef.getImplclassname()); + Assert.assertEquals(dbServiceDef.getUpdatedByUserId(), serviceDef.getUpdatedByUserId()); + } + + @Test + public void test2MapEntityToViewBean() { + RangerServiceDef rangerServiceDef = rangerServiceDef(); + XXServiceDef serviceDef = serviceDef(); + + RangerServiceDef dbRangerServiceDef = rangerServiceDefService.mapEntityToViewBean(rangerServiceDef, serviceDef); + Assert.assertNotNull(dbRangerServiceDef); + Assert.assertEquals(dbRangerServiceDef, rangerServiceDef); + Assert.assertEquals(dbRangerServiceDef.getDescription(), rangerServiceDef.getDescription()); + Assert.assertEquals(dbRangerServiceDef.getGuid(), rangerServiceDef.getGuid()); + Assert.assertEquals(dbRangerServiceDef.getName(), rangerServiceDef.getName()); + Assert.assertEquals(dbRangerServiceDef.getId(), rangerServiceDef.getId()); + Assert.assertEquals(dbRangerServiceDef.getVersion(), rangerServiceDef.getVersion()); + } + + @Test + public void test3populateRangerServiceConfigDefToXX() { + RangerServiceConfigDef serviceConfigDefObj = new RangerServiceConfigDef(); + XXServiceConfigDef configDefObj = new XXServiceConfigDef(); + XXServiceDef serviceDefObj = new XXServiceDef(); + + Mockito.when((XXServiceConfigDef) rangerAuditFields.populateAuditFields(configDefObj, serviceDefObj)).thenReturn(configDefObj); + + XXServiceConfigDef dbServiceConfigDef = rangerServiceDefService.populateRangerServiceConfigDefToXX(serviceConfigDefObj, configDefObj, serviceDefObj, 1); + Assert.assertNotNull(dbServiceConfigDef); + } + + @Test + public void test4populateXXToRangerServiceConfigDef() { + XXServiceConfigDef serviceConfigDefObj = new XXServiceConfigDef(); + + RangerServiceConfigDef dbserviceConfigDefObj = rangerServiceDefService.populateXXToRangerServiceConfigDef(serviceConfigDefObj); + Assert.assertNotNull(dbserviceConfigDefObj); + } + + @Test + public void test5populateRangerResourceDefToXX() { + RangerResourceDef rangerResourceDefObj = new RangerResourceDef(); + rangerResourceDefObj.setDescription("HDFS Repository"); + rangerResourceDefObj.setExcludesSupported(false); + rangerResourceDefObj.setLabel("HDFS Repository"); + rangerResourceDefObj.setName("HDFs"); + + XXResourceDef resourceDefObj = new XXResourceDef(); + resourceDefObj.setAddedByUserId(Id); + resourceDefObj.setCreateTime(new Date()); + resourceDefObj.setDefid(Id); + resourceDefObj.setDescription("HDFS Repository"); + resourceDefObj.setId(Id); + + XXServiceDef serviceDefObj = new XXServiceDef(); + serviceDefObj.setAddedByUserId(Id); + serviceDefObj.setCreateTime(new Date()); + serviceDefObj.setDescription("HDFS Repository"); + serviceDefObj.setGuid("1427365526516_835_0"); + serviceDefObj.setId(Id); + + Mockito.when((XXResourceDef) rangerAuditFields.populateAuditFields(resourceDefObj, serviceDefObj)).thenReturn(resourceDefObj); + + XXResourceDef dbResourceDef = rangerServiceDefService.populateRangerResourceDefToXX(rangerResourceDefObj, resourceDefObj, serviceDefObj, 1); + Assert.assertNotNull(dbResourceDef); + Assert.assertEquals(dbResourceDef, resourceDefObj); + Assert.assertEquals(dbResourceDef.getId(), resourceDefObj.getId()); + Assert.assertEquals(dbResourceDef.getLabel(), resourceDefObj.getLabel()); + Assert.assertEquals(dbResourceDef.getName(), resourceDefObj.getName()); + Assert.assertEquals(dbResourceDef.getDescription(), resourceDefObj.getDescription()); + } + + @Test + public void test6populateXXToRangerResourceDef() { + XXResourceDefDao xResourceDefDao = Mockito.mock(XXResourceDefDao.class); + XXResourceDef resourceDefObj = new XXResourceDef(); + resourceDefObj.setAddedByUserId(Id); + resourceDefObj.setCreateTime(new Date()); + resourceDefObj.setDefid(Id); + resourceDefObj.setDescription("HDFS Repository"); + resourceDefObj.setId(Id); + + Mockito.when(daoManager.getXXResourceDef()).thenReturn(xResourceDefDao); + + RangerResourceDef dbRangerResourceDef = rangerServiceDefService.populateXXToRangerResourceDef(resourceDefObj); + Assert.assertNotNull(dbRangerResourceDef); + Assert.assertEquals(dbRangerResourceDef.getName(), resourceDefObj.getName()); + Assert.assertEquals(dbRangerResourceDef.getDescription(), resourceDefObj.getDescription()); + Assert.assertEquals(dbRangerResourceDef.getType(), resourceDefObj.getType()); + Assert.assertEquals(dbRangerResourceDef.getRbKeyDescription(), resourceDefObj.getRbkeydescription()); + Mockito.verify(daoManager).getXXResourceDef(); + } + + @Test + public void test7populateRangerAccessTypeDefToXX() { + RangerAccessTypeDef rangerAccessTypeDefObj = new RangerAccessTypeDef(); + rangerAccessTypeDefObj.setLabel("Read"); + rangerAccessTypeDefObj.setName("read"); + rangerAccessTypeDefObj.setRbKeyLabel(null); + XXAccessTypeDef accessTypeDefObj = new XXAccessTypeDef(); + accessTypeDefObj.setAddedByUserId(Id); + accessTypeDefObj.setCreateTime(new Date()); + accessTypeDefObj.setDefid(Id); + accessTypeDefObj.setId(Id); + accessTypeDefObj.setLabel("Read"); + accessTypeDefObj.setName("read"); + accessTypeDefObj.setOrder(null); + accessTypeDefObj.setRbkeylabel(null); + accessTypeDefObj.setUpdatedByUserId(Id); + accessTypeDefObj.setUpdateTime(new Date()); + XXServiceDef serviceDefObj = new XXServiceDef(); + serviceDefObj.setAddedByUserId(Id); + serviceDefObj.setCreateTime(new Date()); + serviceDefObj.setDescription("HDFS Repository"); + serviceDefObj.setGuid("1427365526516_835_0"); + serviceDefObj.setId(Id); + + Mockito.when((XXAccessTypeDef) rangerAuditFields.populateAuditFields(accessTypeDefObj, serviceDefObj)).thenReturn(accessTypeDefObj); + + XXAccessTypeDef dbAccessTypeDef = rangerServiceDefService.populateRangerAccessTypeDefToXX(rangerAccessTypeDefObj, accessTypeDefObj, serviceDefObj, 1); + Assert.assertNotNull(dbAccessTypeDef); + Assert.assertEquals(dbAccessTypeDef, accessTypeDefObj); + Assert.assertEquals(dbAccessTypeDef.getName(), accessTypeDefObj.getName()); + Assert.assertEquals(dbAccessTypeDef.getLabel(), accessTypeDefObj.getLabel()); + Assert.assertEquals(dbAccessTypeDef.getRbkeylabel(), accessTypeDefObj.getRbkeylabel()); + Assert.assertEquals(dbAccessTypeDef.getDefid(), accessTypeDefObj.getDefid()); + Assert.assertEquals(dbAccessTypeDef.getId(), accessTypeDefObj.getId()); + Assert.assertEquals(dbAccessTypeDef.getCreateTime(), accessTypeDefObj.getCreateTime()); + Assert.assertEquals(dbAccessTypeDef.getOrder(), accessTypeDefObj.getOrder()); + } + + @Test + public void test8populateRangerAccessTypeDefToXXNullValue() { + RangerAccessTypeDef rangerAccessTypeDefObj = null; + XXAccessTypeDef accessTypeDefObj = null; + XXServiceDef serviceDefObj = null; + Mockito.when(restErrorUtil.createRESTException("RangerServiceDef cannot be null.", MessageEnums.DATA_NOT_FOUND)).thenThrow(new WebApplicationException()); + + thrown.expect(WebApplicationException.class); + XXAccessTypeDef dbAccessTypeDef = rangerServiceDefService.populateRangerAccessTypeDefToXX(rangerAccessTypeDefObj, accessTypeDefObj, serviceDefObj, 1); + Assert.assertNull(dbAccessTypeDef); + } + + @Test + public void test9populateXXToRangerAccessTypeDef() { + XXAccessTypeDef accessTypeDefObj = new XXAccessTypeDef(); + accessTypeDefObj.setAddedByUserId(Id); + accessTypeDefObj.setCreateTime(new Date()); + accessTypeDefObj.setDefid(Id); + accessTypeDefObj.setId(Id); + accessTypeDefObj.setLabel("Read"); + accessTypeDefObj.setName("read"); + accessTypeDefObj.setOrder(null); + accessTypeDefObj.setRbkeylabel(null); + accessTypeDefObj.setUpdatedByUserId(Id); + accessTypeDefObj.setUpdateTime(new Date()); + + RangerAccessTypeDef dbRangerAccessTypeDef = rangerServiceDefService.populateXXToRangerAccessTypeDef(accessTypeDefObj, Collections.emptyList()); + Assert.assertNotNull(dbRangerAccessTypeDef); + Assert.assertEquals(dbRangerAccessTypeDef.getName(), accessTypeDefObj.getName()); + Assert.assertEquals(dbRangerAccessTypeDef.getLabel(), accessTypeDefObj.getLabel()); + Assert.assertEquals(dbRangerAccessTypeDef.getRbKeyLabel(), accessTypeDefObj.getRbkeylabel()); + } + + @Test + public void test10populateRangerPolicyConditionDefToXX() { + RangerPolicyConditionDef rangerConditionDefvObj = new RangerPolicyConditionDef(); + rangerConditionDefvObj.setDescription("Countries"); + rangerConditionDefvObj.setEvaluator("COUNTRY"); + rangerConditionDefvObj.setLabel("Countries"); + rangerConditionDefvObj.setName("country"); + rangerConditionDefvObj.setRbKeyDescription(null); + rangerConditionDefvObj.setRbKeyLabel(null); + XXPolicyConditionDef policyConditionDefObj = new XXPolicyConditionDef(); + policyConditionDefObj.setAddedByUserId(Id); + policyConditionDefObj.setCreateTime(new Date()); + policyConditionDefObj.setDefid(Id); + policyConditionDefObj.setDescription("policy"); + policyConditionDefObj.setId(Id); + policyConditionDefObj.setName("country"); + policyConditionDefObj.setOrder(0); + policyConditionDefObj.setUpdatedByUserId(Id); + policyConditionDefObj.setUpdateTime(new Date()); + XXServiceDef serviceDefObj = new XXServiceDef(); + serviceDefObj.setAddedByUserId(Id); + serviceDefObj.setCreateTime(new Date()); + serviceDefObj.setDescription("HDFS Repository"); + serviceDefObj.setGuid("1427365526516_835_0"); + serviceDefObj.setId(Id); + Mockito.when((XXPolicyConditionDef) rangerAuditFields.populateAuditFields(policyConditionDefObj, serviceDefObj)).thenReturn(policyConditionDefObj); + XXPolicyConditionDef dbPolicyConditionDef = rangerServiceDefService.populateRangerPolicyConditionDefToXX(rangerConditionDefvObj, policyConditionDefObj, serviceDefObj, 1); + Assert.assertNotNull(dbPolicyConditionDef); + Assert.assertEquals(dbPolicyConditionDef.getName(), policyConditionDefObj.getName()); + Assert.assertEquals(dbPolicyConditionDef.getDescription(), policyConditionDefObj.getDescription()); + Assert.assertEquals(dbPolicyConditionDef.getEvaluator(), policyConditionDefObj.getEvaluator()); + Assert.assertEquals(dbPolicyConditionDef.getLabel(), policyConditionDefObj.getLabel()); + Assert.assertEquals(dbPolicyConditionDef.getId(), policyConditionDefObj.getId()); + Assert.assertEquals(dbPolicyConditionDef.getRbkeydescription(), policyConditionDefObj.getRbkeydescription()); + Assert.assertEquals(dbPolicyConditionDef.getOrder(), policyConditionDefObj.getOrder()); + Assert.assertEquals(dbPolicyConditionDef.getUpdatedByUserId(), policyConditionDefObj.getUpdatedByUserId()); + Assert.assertEquals(dbPolicyConditionDef.getUpdateTime(), policyConditionDefObj.getUpdateTime()); + } + + @Test + public void test11populateRangerPolicyConditionDefToXXnullValue() { + RangerPolicyConditionDef rangerConditionDefvObj = null; + XXPolicyConditionDef policyConditionDefObj = null; + XXServiceDef serviceDefObj = null; + + Mockito.when(restErrorUtil.createRESTException("RangerServiceDef cannot be null.", MessageEnums.DATA_NOT_FOUND)).thenThrow(new WebApplicationException()); + + thrown.expect(WebApplicationException.class); + + XXPolicyConditionDef dbPolicyConditionDef = rangerServiceDefService.populateRangerPolicyConditionDefToXX(rangerConditionDefvObj, policyConditionDefObj, serviceDefObj, 1); + Assert.assertNull(dbPolicyConditionDef); + } + + @Test + public void test12populateXXToRangerPolicyConditionDef() { + XXPolicyConditionDef policyConditionDefObj = new XXPolicyConditionDef(); + policyConditionDefObj.setAddedByUserId(Id); + policyConditionDefObj.setCreateTime(new Date()); + policyConditionDefObj.setDefid(Id); + policyConditionDefObj.setDescription("policy"); + policyConditionDefObj.setId(Id); + policyConditionDefObj.setName("country"); + policyConditionDefObj.setOrder(0); + policyConditionDefObj.setUpdatedByUserId(Id); + policyConditionDefObj.setUpdateTime(new Date()); + + RangerPolicyConditionDef dbRangerPolicyConditionDef = rangerServiceDefService.populateXXToRangerPolicyConditionDef(policyConditionDefObj); + Assert.assertNotNull(dbRangerPolicyConditionDef); + Assert.assertEquals(dbRangerPolicyConditionDef.getName(), policyConditionDefObj.getName()); + Assert.assertEquals(dbRangerPolicyConditionDef.getDescription(), policyConditionDefObj.getDescription()); + Assert.assertEquals(dbRangerPolicyConditionDef.getEvaluator(), policyConditionDefObj.getEvaluator()); + Assert.assertEquals(dbRangerPolicyConditionDef.getLabel(), policyConditionDefObj.getLabel()); + } + + @Test + public void test13populateRangerContextEnricherDefToXX() { + RangerContextEnricherDef rangerContextEnricherDefObj = new RangerContextEnricherDef(); + rangerContextEnricherDefObj.setName("country-provider"); + rangerContextEnricherDefObj.setEnricher("RangerCountryProvider"); + + XXContextEnricherDef contextEnricherDefObj = new XXContextEnricherDef(); + contextEnricherDefObj.setAddedByUserId(Id); + contextEnricherDefObj.setCreateTime(new Date()); + contextEnricherDefObj.setDefid(Id); + contextEnricherDefObj.setId(Id); + contextEnricherDefObj.setName("country-provider"); + contextEnricherDefObj.setEnricherOptions("contextName=COUNTRY;dataFile=/etc/ranger/data/userCountry.properties"); + contextEnricherDefObj.setEnricher("RangerCountryProvider"); + contextEnricherDefObj.setOrder(null); + contextEnricherDefObj.setUpdatedByUserId(Id); + contextEnricherDefObj.setUpdateTime(new Date()); + XXServiceDef serviceDefObj = new XXServiceDef(); + serviceDefObj.setAddedByUserId(Id); + serviceDefObj.setCreateTime(new Date()); + serviceDefObj.setDescription("HDFS Repository"); + serviceDefObj.setGuid("1427365526516_835_0"); + serviceDefObj.setId(Id); + + Mockito.when((XXContextEnricherDef) rangerAuditFields.populateAuditFields(contextEnricherDefObj, serviceDefObj)).thenReturn(contextEnricherDefObj); + + XXContextEnricherDef dbContextEnricherDef = rangerServiceDefService.populateRangerContextEnricherDefToXX(rangerContextEnricherDefObj, contextEnricherDefObj, serviceDefObj, 1); + Assert.assertNotNull(dbContextEnricherDef); + Assert.assertEquals(dbContextEnricherDef.getEnricher(), contextEnricherDefObj.getEnricher()); + Assert.assertEquals(dbContextEnricherDef.getEnricherOptions(), contextEnricherDefObj.getEnricherOptions()); + Assert.assertEquals(dbContextEnricherDef.getName(), contextEnricherDefObj.getName()); + Assert.assertEquals(dbContextEnricherDef.getCreateTime(), contextEnricherDefObj.getCreateTime()); + Assert.assertEquals(dbContextEnricherDef.getId(), contextEnricherDefObj.getId()); + Assert.assertEquals(dbContextEnricherDef.getOrder(), contextEnricherDefObj.getOrder()); + Assert.assertEquals(dbContextEnricherDef.getUpdatedByUserId(), contextEnricherDefObj.getUpdatedByUserId()); + Assert.assertEquals(dbContextEnricherDef.getUpdateTime(), contextEnricherDefObj.getUpdateTime()); + } + + @Test + public void test14populateRangerContextEnricherDefToXXnullValue() { + RangerContextEnricherDef rangerContextEnricherDefObj = null; + XXContextEnricherDef contextEnricherDefObj = null; + XXServiceDef serviceDefObj = null; + + Mockito.when(restErrorUtil.createRESTException("RangerServiceDef cannot be null.", MessageEnums.DATA_NOT_FOUND)).thenThrow(new WebApplicationException()); + + thrown.expect(WebApplicationException.class); + + XXContextEnricherDef dbContextEnricherDef = rangerServiceDefService.populateRangerContextEnricherDefToXX(rangerContextEnricherDefObj, contextEnricherDefObj, serviceDefObj, 1); + Assert.assertNull(dbContextEnricherDef); + } + + @Test + public void test15populateXXToRangerContextEnricherDef() { + XXContextEnricherDef contextEnricherDefObj = new XXContextEnricherDef(); + contextEnricherDefObj.setAddedByUserId(Id); + contextEnricherDefObj.setCreateTime(new Date()); + contextEnricherDefObj.setDefid(Id); + contextEnricherDefObj.setId(Id); + contextEnricherDefObj.setName("country-provider"); + contextEnricherDefObj.setEnricherOptions("contextName=COUNTRY;dataFile=/etc/ranger/data/userCountry.properties"); + contextEnricherDefObj.setEnricher("RangerCountryProvider"); + contextEnricherDefObj.setOrder(null); + contextEnricherDefObj.setUpdatedByUserId(Id); + contextEnricherDefObj.setUpdateTime(new Date()); + + RangerContextEnricherDef dbRangerContextEnricherDef = rangerServiceDefService.populateXXToRangerContextEnricherDef(contextEnricherDefObj); + Assert.assertNotNull(dbRangerContextEnricherDef); + Assert.assertEquals(dbRangerContextEnricherDef.getEnricher(), contextEnricherDefObj.getEnricher()); + Assert.assertEquals(dbRangerContextEnricherDef.getName(), contextEnricherDefObj.getName()); + } + + @Test + public void test16populateRangerEnumDefToXX() { + RangerEnumDef rangerEnumDefObj = new RangerEnumDef(); + rangerEnumDefObj.setName("authnType"); + rangerEnumDefObj.setDefaultIndex(0); + XXEnumDef enumDefObj = new XXEnumDef(); + enumDefObj.setAddedByUserId(Id); + enumDefObj.setCreateTime(new Date()); + enumDefObj.setDefaultindex(0); + enumDefObj.setDefid(Id); + enumDefObj.setId(Id); + enumDefObj.setName("authnType"); + enumDefObj.setUpdatedByUserId(Id); + enumDefObj.setUpdateTime(new Date()); + XXServiceDef serviceDefObj = new XXServiceDef(); + serviceDefObj.setAddedByUserId(Id); + serviceDefObj.setCreateTime(new Date()); + serviceDefObj.setDescription("HDFS Repository"); + serviceDefObj.setGuid("1427365526516_835_0"); + serviceDefObj.setId(Id); + + Mockito.when((XXEnumDef) rangerAuditFields.populateAuditFields(enumDefObj, serviceDefObj)).thenReturn(enumDefObj); + + XXEnumDef dbEnumDef = rangerServiceDefService.populateRangerEnumDefToXX(rangerEnumDefObj, enumDefObj, serviceDefObj, 1); + Assert.assertNotNull(dbEnumDef); + Assert.assertEquals(dbEnumDef, enumDefObj); + Assert.assertEquals(dbEnumDef.getName(), enumDefObj.getName()); + Assert.assertEquals(dbEnumDef.getDefid(), enumDefObj.getDefid()); + Assert.assertEquals(dbEnumDef.getId(), enumDefObj.getId()); + Assert.assertEquals(dbEnumDef.getCreateTime(), enumDefObj.getCreateTime()); + } + + @Test + public void test17populateRangerEnumDefToXXnullValue() { + RangerEnumDef rangerEnumDefObj = null; + XXEnumDef enumDefObj = null; + XXServiceDef serviceDefObj = null; + + Mockito.when(restErrorUtil.createRESTException("RangerServiceDef cannot be null.", MessageEnums.DATA_NOT_FOUND)).thenThrow(new WebApplicationException()); + + thrown.expect(WebApplicationException.class); + + XXEnumDef dbEnumDef = rangerServiceDefService.populateRangerEnumDefToXX(rangerEnumDefObj, enumDefObj, serviceDefObj, 1); + Assert.assertNull(dbEnumDef); + } + + @Test + public void test18populateXXToRangerEnumDef() { + XXEnumElementDefDao xEnumElementDefDao = Mockito.mock(XXEnumElementDefDao.class); + + List enumElementDefList = new ArrayList<>(); + XXEnumElementDef enumElementDefObj = new XXEnumElementDef(); + enumElementDefObj.setAddedByUserId(Id); + enumElementDefObj.setCreateTime(new Date()); + enumElementDefObj.setEnumdefid(Id); + enumElementDefObj.setId(Id); + enumElementDefObj.setLabel("Simple"); + enumElementDefObj.setName("simple"); + enumElementDefObj.setOrder(0); + enumElementDefObj.setUpdatedByUserId(Id); + enumElementDefObj.setUpdateTime(new Date()); + enumElementDefList.add(enumElementDefObj); + + XXEnumDef enumDefObj = new XXEnumDef(); + enumDefObj.setAddedByUserId(Id); + enumDefObj.setCreateTime(new Date()); + enumDefObj.setDefaultindex(0); + enumDefObj.setDefid(Id); + enumDefObj.setId(Id); + enumDefObj.setName("authnType"); + enumDefObj.setUpdatedByUserId(Id); + enumDefObj.setUpdateTime(new Date()); + + Mockito.when(daoManager.getXXEnumElementDef()).thenReturn(xEnumElementDefDao); + Mockito.when(xEnumElementDefDao.findByEnumDefId(enumDefObj.getId())).thenReturn(enumElementDefList); + + RangerEnumDef dbRangerEnumDef = rangerServiceDefService.populateXXToRangerEnumDef(enumDefObj); + Assert.assertNotNull(dbRangerEnumDef); + Assert.assertEquals(dbRangerEnumDef.getName(), enumDefObj.getName()); + + Mockito.verify(daoManager).getXXEnumElementDef(); + } + + @Test + public void test19populateRangerEnumElementDefToXX() { + RangerEnumElementDef rangerEnumElementDefObj = new RangerEnumElementDef(); + rangerEnumElementDefObj.setLabel("Simple"); + rangerEnumElementDefObj.setName("simple"); + rangerEnumElementDefObj.setRbKeyLabel(null); + XXEnumElementDef enumElementDefObj = new XXEnumElementDef(); + enumElementDefObj.setAddedByUserId(Id); + enumElementDefObj.setCreateTime(new Date()); + enumElementDefObj.setEnumdefid(Id); + enumElementDefObj.setId(Id); + enumElementDefObj.setLabel("Simple"); + enumElementDefObj.setName("simple"); + enumElementDefObj.setOrder(0); + enumElementDefObj.setUpdatedByUserId(Id); + enumElementDefObj.setUpdateTime(new Date()); + XXEnumDef enumDefObj = new XXEnumDef(); + enumDefObj.setAddedByUserId(Id); + enumDefObj.setCreateTime(new Date()); + enumDefObj.setDefaultindex(0); + enumDefObj.setDefid(Id); + enumDefObj.setId(Id); + enumDefObj.setName("authnType"); + enumDefObj.setUpdatedByUserId(Id); + enumDefObj.setUpdateTime(new Date()); + + Mockito.when((XXEnumElementDef) rangerAuditFields.populateAuditFields(enumElementDefObj, enumDefObj)).thenReturn(enumElementDefObj); + XXEnumElementDef dbEnumElementDef = rangerServiceDefService.populateRangerEnumElementDefToXX(rangerEnumElementDefObj, enumElementDefObj, enumDefObj, 1); + Assert.assertNotNull(dbEnumElementDef); + Assert.assertEquals(dbEnumElementDef.getId(), enumElementDefObj.getId()); + Assert.assertEquals(dbEnumElementDef.getName(), enumElementDefObj.getName()); + Assert.assertEquals(dbEnumElementDef.getLabel(), enumElementDefObj.getLabel()); + Assert.assertEquals(dbEnumElementDef.getCreateTime(), enumElementDefObj.getCreateTime()); + Assert.assertEquals(dbEnumElementDef.getAddedByUserId(), enumElementDefObj.getAddedByUserId()); + Assert.assertEquals(dbEnumElementDef.getUpdateTime(), enumElementDefObj.getUpdateTime()); + Assert.assertEquals(dbEnumElementDef.getUpdatedByUserId(), enumElementDefObj.getUpdatedByUserId()); + Mockito.verify(rangerAuditFields).populateAuditFields(enumElementDefObj, enumDefObj); + } + + @Test + public void test20populateXXToRangerEnumElementDef() { + XXEnumElementDef enumElementDefObj = new XXEnumElementDef(); + enumElementDefObj.setAddedByUserId(Id); + enumElementDefObj.setCreateTime(new Date()); + enumElementDefObj.setEnumdefid(Id); + enumElementDefObj.setId(Id); + enumElementDefObj.setLabel("Simple"); + enumElementDefObj.setName("simple"); + enumElementDefObj.setOrder(0); + enumElementDefObj.setUpdatedByUserId(Id); + enumElementDefObj.setUpdateTime(new Date()); + + RangerEnumElementDef dbRangerEnumElementDef = rangerServiceDefService.populateXXToRangerEnumElementDef(enumElementDefObj); + Assert.assertNotNull(dbRangerEnumElementDef); + Assert.assertEquals(dbRangerEnumElementDef.getLabel(), enumElementDefObj.getLabel()); + Assert.assertEquals(dbRangerEnumElementDef.getName(), enumElementDefObj.getName()); + } + + @Test + public void test21searchRangerServiceDefs() { + setup(); + SearchFilter searchFilter = new SearchFilter(); + searchFilter.setParam(SearchFilter.POLICY_NAME, "policyName"); + searchFilter.setParam(SearchFilter.SERVICE_NAME, "serviceName"); + + RangerServiceDefList dbRangerServiceDefList = rangerServiceDefService + .searchRangerServiceDefs(searchFilter); + Assert.assertNotNull(dbRangerServiceDefList); + } + + private RangerServiceDef rangerServiceDef() { + List configs = new ArrayList<>(); + List resources = new ArrayList<>(); + List accessTypes = new ArrayList<>(); + List policyConditions = new ArrayList<>(); + List contextEnrichers = new ArrayList<>(); + List enums = new ArrayList<>(); + + RangerServiceDef rangerServiceDef = new RangerServiceDef(); + rangerServiceDef.setId(Id); + rangerServiceDef.setImplClass("RangerServiceHdfs"); + rangerServiceDef.setLabel("HDFS Repository"); + rangerServiceDef.setDescription("HDFS Repository"); + rangerServiceDef.setRbKeyDescription(null); + rangerServiceDef.setUpdatedBy("Admin"); + rangerServiceDef.setUpdateTime(new Date()); + rangerServiceDef.setConfigs(configs); + rangerServiceDef.setResources(resources); + rangerServiceDef.setAccessTypes(accessTypes); + rangerServiceDef.setPolicyConditions(policyConditions); + rangerServiceDef.setContextEnrichers(contextEnrichers); + rangerServiceDef.setEnums(enums); + + return rangerServiceDef; + } + + private XXServiceDef serviceDef() { + XXServiceDef xServiceDef = new XXServiceDef(); + xServiceDef.setAddedByUserId(Id); + xServiceDef.setCreateTime(new Date()); + xServiceDef.setDescription("HDFS Repository"); + xServiceDef.setGuid("0d047247-bafe-4cf8-8e9b-d5d377284b2d"); + xServiceDef.setId(Id); + xServiceDef.setImplclassname("RangerServiceHdfs"); + xServiceDef.setIsEnabled(true); + xServiceDef.setLabel("HDFS Repository"); + xServiceDef.setName("hdfs"); + xServiceDef.setRbkeydescription(null); + xServiceDef.setRbkeylabel(null); + xServiceDef.setUpdatedByUserId(Id); + xServiceDef.setUpdateTime(new Date()); + + return xServiceDef; + } } diff --git a/security-admin/src/test/java/org/apache/ranger/service/TestRangerServiceService.java b/security-admin/src/test/java/org/apache/ranger/service/TestRangerServiceService.java index d7f2f1ad08..9ca9bc78b0 100644 --- a/security-admin/src/test/java/org/apache/ranger/service/TestRangerServiceService.java +++ b/security-admin/src/test/java/org/apache/ranger/service/TestRangerServiceService.java @@ -16,12 +16,6 @@ */ package org.apache.ranger.service; -import java.util.ArrayList; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - import org.apache.ranger.biz.RangerBizUtil; import org.apache.ranger.common.ContextUtil; import org.apache.ranger.common.JSONUtil; @@ -32,7 +26,6 @@ import org.apache.ranger.db.XXServiceConfigMapDao; import org.apache.ranger.db.XXServiceDao; import org.apache.ranger.db.XXServiceDefDao; - import org.apache.ranger.db.XXServiceVersionInfoDao; import org.apache.ranger.entity.XXPortalUser; import org.apache.ranger.entity.XXService; @@ -40,7 +33,6 @@ import org.apache.ranger.entity.XXServiceDef; import org.apache.ranger.entity.XXServiceVersionInfo; import org.apache.ranger.plugin.model.RangerService; - import org.apache.ranger.security.context.RangerContextHolder; import org.apache.ranger.security.context.RangerSecurityContext; import org.junit.Assert; @@ -55,372 +47,345 @@ import org.mockito.Mockito; import org.mockito.junit.MockitoJUnitRunner; +import java.util.ArrayList; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + @RunWith(MockitoJUnitRunner.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class TestRangerServiceService { - - private static Long userId = 8L; - - @InjectMocks - RangerServiceService serviceService = new RangerServiceService(); - - @Mock - RangerDaoManager daoManager; - - @Mock - RangerBizUtil bizUtil; - - @Mock - RangerServiceService svcService; - - @Mock - JSONUtil jsonUtil; - - @Mock - RangerServiceDefService serviceDefService; - - @Mock - RangerPolicyService policyService; - - @Mock - StringUtil stringUtil; - - @Mock - XUserService xUserService; - - @Rule - public ExpectedException thrown = ExpectedException.none(); - - public void setup() { - RangerSecurityContext context = new RangerSecurityContext(); - context.setUserSession(new UserSessionBase()); - RangerContextHolder.setSecurityContext(context); - UserSessionBase currentUserSession = ContextUtil - .getCurrentUserSession(); - currentUserSession.setUserAdmin(true); - } - - private RangerService rangerService() { - Map configs = new HashMap(); - configs.put("username", "servicemgr"); - configs.put("password", "servicemgr"); - configs.put("namenode", "servicemgr"); - configs.put("hadoop.security.authorization", "No"); - configs.put("hadoop.security.authentication", "Simple"); - configs.put("hadoop.security.auth_to_local", ""); - configs.put("dfs.datanode.kerberos.principal", ""); - configs.put("dfs.namenode.kerberos.principal", ""); - configs.put("dfs.secondary.namenode.kerberos.principal", ""); - configs.put("hadoop.rpc.protection", "Privacy"); - configs.put("commonNameForCertificate", ""); - - RangerService rangerService = new RangerService(); - rangerService.setId(userId); - rangerService.setConfigs(configs); - rangerService.setCreateTime(new Date()); - rangerService.setDescription("service"); - rangerService.setGuid("serviceguid"); - rangerService.setIsEnabled(true); - rangerService.setName("Hdfs service"); - rangerService.setPolicyUpdateTime(new Date()); - rangerService.setPolicyVersion(1L); - rangerService.setType(null); - rangerService.setUpdatedBy("Admin"); - rangerService.setUpdateTime(new Date()); - rangerService.setVersion(userId); - - return rangerService; - } - - private XXService xService() { - XXService xService = new XXService(); - xService.setAddedByUserId(userId); - xService.setCreateTime(new Date()); - xService.setDescription("Hdfs service"); - xService.setGuid("serviceguid"); - xService.setId(userId); - xService.setIsEnabled(true); - xService.setName("Hdfs"); - xService.setPolicyUpdateTime(new Date()); - xService.setPolicyVersion(1L); - xService.setType(1L); - xService.setUpdatedByUserId(userId); - xService.setUpdateTime(new Date()); - - return xService; - } - - @Test - public void test1ValidateForCreate() { - RangerService service = rangerService(); - serviceService.validateForCreate(service); - Assert.assertNotNull(service); - } - - @Test - public void test2ValidateForUpdate() { - RangerService vService = rangerService(); - XXService xService = xService(); - - serviceService.validateForUpdate(vService, xService); - Assert.assertNotNull(vService); - } - - @Test - public void test3PopulateViewBean() { - XXServiceConfigMapDao xServiceConfigMapDao = Mockito - .mock(XXServiceConfigMapDao.class); - XXPortalUserDao xPortalUserDao = Mockito.mock(XXPortalUserDao.class); - XXServiceDefDao xServiceDefDao = Mockito.mock(XXServiceDefDao.class); - XXService xService = xService(); - String name = "fdfdfds"; - - List svcConfigMapList = new ArrayList(); - XXServiceConfigMap xConfMap = new XXServiceConfigMap(); - xConfMap.setAddedByUserId(null); - xConfMap.setConfigkey(name); - xConfMap.setConfigvalue(name); - xConfMap.setCreateTime(new Date()); - xConfMap.setServiceId(null); - - xConfMap.setUpdatedByUserId(null); - xConfMap.setUpdateTime(new Date()); - svcConfigMapList.add(xConfMap); - - XXPortalUser tUser = new XXPortalUser(); - tUser.setAddedByUserId(userId); - tUser.setCreateTime(new Date()); - tUser.setEmailAddress("test@gmail.com"); - tUser.setFirstName(name); - tUser.setId(userId); - tUser.setLastName(name); - - XXServiceDef xServiceDef = new XXServiceDef(); - xServiceDef.setAddedByUserId(userId); - xServiceDef.setCreateTime(new Date()); - xServiceDef.setDescription("test"); - xServiceDef.setGuid("1427365526516_835_0"); - xServiceDef.setId(userId); - - XXServiceVersionInfoDao xServiceVersionInfoDao = Mockito.mock(XXServiceVersionInfoDao.class); - - XXServiceVersionInfo serviceVersionInfo = new XXServiceVersionInfo(); - serviceVersionInfo.setServiceId(xService.getId()); - serviceVersionInfo.setPolicyVersion(xService.getPolicyVersion()); - serviceVersionInfo.setPolicyUpdateTime(xService.getPolicyUpdateTime()); - serviceVersionInfo.setTagVersion(xService.getTagVersion()); - serviceVersionInfo.setTagUpdateTime(xService.getTagUpdateTime()); - - Mockito.when(daoManager.getXXServiceVersionInfo()).thenReturn(xServiceVersionInfoDao); - Mockito.when(xServiceVersionInfoDao.findByServiceId(xService.getId())).thenReturn( - serviceVersionInfo); - - Mockito.when(daoManager.getXXPortalUser()).thenReturn(xPortalUserDao); - Mockito.when(xPortalUserDao.getById(userId)).thenReturn(tUser); - - Mockito.when(daoManager.getXXServiceDef()).thenReturn(xServiceDefDao); - Mockito.when(xServiceDefDao.getById(xService.getType())).thenReturn( - xServiceDef); - - Mockito.when(daoManager.getXXServiceConfigMap()).thenReturn( - xServiceConfigMapDao); - Mockito.when(xServiceConfigMapDao.findByServiceId(xService.getId())) - .thenReturn(svcConfigMapList); - - RangerService dbService = serviceService.populateViewBean(xService); - - Assert.assertNotNull(dbService); - Assert.assertEquals(userId, dbService.getId()); - Assert.assertEquals(xService.getAddedByUserId(), dbService.getId()); - Assert.assertEquals(xService.getId(), dbService.getId()); - Assert.assertEquals(xService.getDescription(), - dbService.getDescription()); - Assert.assertEquals(xService.getGuid(), dbService.getGuid()); - Assert.assertEquals(xService.getName(), dbService.getName()); - Assert.assertEquals(xService.getPolicyUpdateTime(), - dbService.getPolicyUpdateTime()); - Assert.assertEquals(xService.getPolicyVersion(), - dbService.getPolicyVersion()); - Assert.assertEquals(xService.getVersion(), dbService.getVersion()); - - Mockito.verify(daoManager).getXXServiceDef(); - Mockito.verify(daoManager).getXXServiceConfigMap(); - } - - @Test - public void test4GetPopulatedViewObject() { - XXServiceConfigMapDao xServiceConfigMapDao = Mockito - .mock(XXServiceConfigMapDao.class); - XXPortalUserDao xPortalUserDao = Mockito.mock(XXPortalUserDao.class); - XXServiceDefDao xServiceDefDao = Mockito.mock(XXServiceDefDao.class); - XXService xService = xService(); - String name = "fdfdfds"; - - List svcConfigMapList = new ArrayList(); - XXServiceConfigMap xConfMap = new XXServiceConfigMap(); - xConfMap.setAddedByUserId(null); - xConfMap.setConfigkey(name); - xConfMap.setConfigvalue(name); - xConfMap.setCreateTime(new Date()); - xConfMap.setServiceId(null); - xConfMap.setUpdatedByUserId(null); - xConfMap.setUpdateTime(new Date()); - svcConfigMapList.add(xConfMap); - - XXPortalUser tUser = new XXPortalUser(); - tUser.setAddedByUserId(userId); - tUser.setCreateTime(new Date()); - tUser.setEmailAddress("test@gmail.com"); - tUser.setFirstName(name); - tUser.setId(userId); - tUser.setLastName(name); - - XXServiceDef xServiceDef = new XXServiceDef(); - xServiceDef.setAddedByUserId(userId); - xServiceDef.setCreateTime(new Date()); - xServiceDef.setDescription("test"); - xServiceDef.setGuid("1427365526516_835_0"); - xServiceDef.setId(userId); - - XXServiceVersionInfoDao xServiceVersionInfoDao = Mockito.mock(XXServiceVersionInfoDao.class); - - XXServiceVersionInfo serviceVersionInfo = new XXServiceVersionInfo(); - serviceVersionInfo.setServiceId(xService.getId()); - serviceVersionInfo.setPolicyVersion(xService.getPolicyVersion()); - serviceVersionInfo.setPolicyUpdateTime(xService.getPolicyUpdateTime()); - serviceVersionInfo.setTagVersion(xService.getTagVersion()); - serviceVersionInfo.setTagUpdateTime(xService.getTagUpdateTime()); - - Mockito.when(daoManager.getXXServiceVersionInfo()).thenReturn(xServiceVersionInfoDao); - Mockito.when(xServiceVersionInfoDao.findByServiceId(xService.getId())).thenReturn( - serviceVersionInfo); - - Mockito.when(daoManager.getXXPortalUser()).thenReturn(xPortalUserDao); - Mockito.when(xPortalUserDao.getById(userId)).thenReturn(tUser); - - Mockito.when(daoManager.getXXServiceDef()).thenReturn(xServiceDefDao); - Mockito.when(xServiceDefDao.getById(xService.getType())).thenReturn( - xServiceDef); - - Mockito.when(daoManager.getXXServiceConfigMap()).thenReturn( - xServiceConfigMapDao); - Mockito.when(xServiceConfigMapDao.findByServiceId(xService.getId())) - .thenReturn(svcConfigMapList); - - RangerService dbService = serviceService - .getPopulatedViewObject(xService); - - Assert.assertNotNull(dbService); - Assert.assertEquals(userId, dbService.getId()); - Assert.assertEquals(xService.getAddedByUserId(), dbService.getId()); - Assert.assertEquals(xService.getId(), dbService.getId()); - Assert.assertEquals(xService.getDescription(), - dbService.getDescription()); - Assert.assertEquals(xService.getGuid(), dbService.getGuid()); - Assert.assertEquals(xService.getName(), dbService.getName()); - Assert.assertEquals(xService.getPolicyUpdateTime(), - dbService.getPolicyUpdateTime()); - Assert.assertEquals(xService.getPolicyVersion(), - dbService.getPolicyVersion()); - Assert.assertEquals(xService.getVersion(), dbService.getVersion()); - - Mockito.verify(daoManager).getXXServiceDef(); - Mockito.verify(daoManager).getXXServiceConfigMap(); - } - - @Test - public void test5GetAllServices() { - XXServiceDao xServiceDao = Mockito.mock(XXServiceDao.class); - XXPortalUserDao xPortalUserDao = Mockito.mock(XXPortalUserDao.class); - XXServiceConfigMapDao xServiceConfigMapDao = Mockito - .mock(XXServiceConfigMapDao.class); - XXServiceDefDao xServiceDefDao = Mockito.mock(XXServiceDefDao.class); - - String name = "fdfdfds"; - - List svcConfigMapList = new ArrayList(); - XXServiceConfigMap xConfMap = new XXServiceConfigMap(); - xConfMap.setAddedByUserId(null); - xConfMap.setConfigkey(name); - xConfMap.setConfigvalue(name); - xConfMap.setCreateTime(new Date()); - xConfMap.setServiceId(null); - xConfMap.setUpdatedByUserId(null); - xConfMap.setUpdateTime(new Date()); - svcConfigMapList.add(xConfMap); - - List xServiceList = new ArrayList(); - XXService xService = xService(); - xServiceList.add(xService); - - XXPortalUser tUser = new XXPortalUser(); - tUser.setAddedByUserId(userId); - tUser.setCreateTime(new Date()); - tUser.setEmailAddress("test@gmail.com"); - tUser.setFirstName(name); - tUser.setId(userId); - tUser.setLastName(name); - - XXServiceDef xServiceDef = new XXServiceDef(); - xServiceDef.setAddedByUserId(userId); - xServiceDef.setCreateTime(new Date()); - xServiceDef.setDescription("test"); - xServiceDef.setGuid("1427365526516_835_0"); - xServiceDef.setId(userId); - - XXServiceVersionInfoDao xServiceVersionInfoDao = Mockito.mock(XXServiceVersionInfoDao.class); - - XXServiceVersionInfo serviceVersionInfo = new XXServiceVersionInfo(); - serviceVersionInfo.setServiceId(xService.getId()); - serviceVersionInfo.setPolicyVersion(xService.getPolicyVersion()); - serviceVersionInfo.setPolicyUpdateTime(xService.getPolicyUpdateTime()); - serviceVersionInfo.setTagVersion(xService.getTagVersion()); - serviceVersionInfo.setTagUpdateTime(xService.getTagUpdateTime()); - - Mockito.when(daoManager.getXXServiceVersionInfo()).thenReturn(xServiceVersionInfoDao); - Mockito.when(xServiceVersionInfoDao.findByServiceId(xService.getId())).thenReturn( - serviceVersionInfo); - - Mockito.when(daoManager.getXXService()).thenReturn(xServiceDao); - Mockito.when(xServiceDao.getAll()).thenReturn(xServiceList); - - Mockito.when(daoManager.getXXPortalUser()).thenReturn(xPortalUserDao); - Mockito.when(xPortalUserDao.getById(userId)).thenReturn(tUser); - - Mockito.when(daoManager.getXXServiceDef()).thenReturn(xServiceDefDao); - Mockito.when(xServiceDefDao.getById(xService.getType())).thenReturn( - xServiceDef); - - Mockito.when(daoManager.getXXServiceConfigMap()).thenReturn( - xServiceConfigMapDao); - Mockito.when(xServiceConfigMapDao.findByServiceId(xService.getId())) - .thenReturn(svcConfigMapList); - - List dbServiceList = serviceService.getAllServices(); - Assert.assertNotNull(dbServiceList); - - Mockito.verify(daoManager).getXXServiceDef(); - Mockito.verify(daoManager).getXXServiceConfigMap(); - } - - @Test - public void test6GetTransactionLogCreate() { - RangerService rangerService = rangerService(); - - serviceService.createTransactionLog(rangerService, null, 1); - } - - @Test - public void test7GetTransactionLogUpdate() { - RangerService rangerService = rangerService(); - - serviceService.createTransactionLog(rangerService, null, 2); - } - - @Test - public void test8GetTransactionLogDelete() { - RangerService rangerService = rangerService(); - - serviceService.createTransactionLog(rangerService, null, 3); - } + private static final Long userId = 8L; + @Rule + public ExpectedException thrown = ExpectedException.none(); + @InjectMocks + RangerServiceService serviceService = new RangerServiceService(); + @Mock + RangerDaoManager daoManager; + @Mock + RangerBizUtil bizUtil; + @Mock + RangerServiceService svcService; + @Mock + JSONUtil jsonUtil; + @Mock + RangerServiceDefService serviceDefService; + @Mock + RangerPolicyService policyService; + @Mock + StringUtil stringUtil; + @Mock + XUserService xUserService; + + public void setup() { + RangerSecurityContext context = new RangerSecurityContext(); + context.setUserSession(new UserSessionBase()); + RangerContextHolder.setSecurityContext(context); + UserSessionBase currentUserSession = ContextUtil.getCurrentUserSession(); + currentUserSession.setUserAdmin(true); + } + + @Test + public void test1ValidateForCreate() { + RangerService service = rangerService(); + serviceService.validateForCreate(service); + Assert.assertNotNull(service); + } + + @Test + public void test2ValidateForUpdate() { + RangerService vService = rangerService(); + XXService xService = xService(); + + serviceService.validateForUpdate(vService, xService); + Assert.assertNotNull(vService); + } + + @Test + public void test3PopulateViewBean() { + XXServiceConfigMapDao xServiceConfigMapDao = Mockito + .mock(XXServiceConfigMapDao.class); + XXPortalUserDao xPortalUserDao = Mockito.mock(XXPortalUserDao.class); + XXServiceDefDao xServiceDefDao = Mockito.mock(XXServiceDefDao.class); + XXService xService = xService(); + String name = "fdfdfds"; + + List svcConfigMapList = new ArrayList<>(); + XXServiceConfigMap xConfMap = new XXServiceConfigMap(); + xConfMap.setAddedByUserId(null); + xConfMap.setConfigkey(name); + xConfMap.setConfigvalue(name); + xConfMap.setCreateTime(new Date()); + xConfMap.setServiceId(null); + + xConfMap.setUpdatedByUserId(null); + xConfMap.setUpdateTime(new Date()); + svcConfigMapList.add(xConfMap); + + XXPortalUser tUser = new XXPortalUser(); + tUser.setAddedByUserId(userId); + tUser.setCreateTime(new Date()); + tUser.setEmailAddress("test@gmail.com"); + tUser.setFirstName(name); + tUser.setId(userId); + tUser.setLastName(name); + + XXServiceDef xServiceDef = new XXServiceDef(); + xServiceDef.setAddedByUserId(userId); + xServiceDef.setCreateTime(new Date()); + xServiceDef.setDescription("test"); + xServiceDef.setGuid("1427365526516_835_0"); + xServiceDef.setId(userId); + + XXServiceVersionInfoDao xServiceVersionInfoDao = Mockito.mock(XXServiceVersionInfoDao.class); + + XXServiceVersionInfo serviceVersionInfo = new XXServiceVersionInfo(); + serviceVersionInfo.setServiceId(xService.getId()); + serviceVersionInfo.setPolicyVersion(xService.getPolicyVersion()); + serviceVersionInfo.setPolicyUpdateTime(xService.getPolicyUpdateTime()); + serviceVersionInfo.setTagVersion(xService.getTagVersion()); + serviceVersionInfo.setTagUpdateTime(xService.getTagUpdateTime()); + + Mockito.when(daoManager.getXXServiceVersionInfo()).thenReturn(xServiceVersionInfoDao); + Mockito.when(xServiceVersionInfoDao.findByServiceId(xService.getId())).thenReturn(serviceVersionInfo); + + Mockito.when(daoManager.getXXPortalUser()).thenReturn(xPortalUserDao); + Mockito.when(xPortalUserDao.getById(userId)).thenReturn(tUser); + + Mockito.when(daoManager.getXXServiceDef()).thenReturn(xServiceDefDao); + Mockito.when(xServiceDefDao.getById(xService.getType())).thenReturn(xServiceDef); + + Mockito.when(daoManager.getXXServiceConfigMap()).thenReturn(xServiceConfigMapDao); + Mockito.when(xServiceConfigMapDao.findByServiceId(xService.getId())).thenReturn(svcConfigMapList); + + RangerService dbService = serviceService.populateViewBean(xService); + + Assert.assertNotNull(dbService); + Assert.assertEquals(userId, dbService.getId()); + Assert.assertEquals(xService.getAddedByUserId(), dbService.getId()); + Assert.assertEquals(xService.getId(), dbService.getId()); + Assert.assertEquals(xService.getDescription(), dbService.getDescription()); + Assert.assertEquals(xService.getGuid(), dbService.getGuid()); + Assert.assertEquals(xService.getName(), dbService.getName()); + Assert.assertEquals(xService.getPolicyUpdateTime(), dbService.getPolicyUpdateTime()); + Assert.assertEquals(xService.getPolicyVersion(), dbService.getPolicyVersion()); + Assert.assertEquals(xService.getVersion(), dbService.getVersion()); + + Mockito.verify(daoManager).getXXServiceDef(); + Mockito.verify(daoManager).getXXServiceConfigMap(); + } + + @Test + public void test4GetPopulatedViewObject() { + XXServiceConfigMapDao xServiceConfigMapDao = Mockito.mock(XXServiceConfigMapDao.class); + XXPortalUserDao xPortalUserDao = Mockito.mock(XXPortalUserDao.class); + XXServiceDefDao xServiceDefDao = Mockito.mock(XXServiceDefDao.class); + XXService xService = xService(); + String name = "fdfdfds"; + + List svcConfigMapList = new ArrayList<>(); + XXServiceConfigMap xConfMap = new XXServiceConfigMap(); + xConfMap.setAddedByUserId(null); + xConfMap.setConfigkey(name); + xConfMap.setConfigvalue(name); + xConfMap.setCreateTime(new Date()); + xConfMap.setServiceId(null); + xConfMap.setUpdatedByUserId(null); + xConfMap.setUpdateTime(new Date()); + svcConfigMapList.add(xConfMap); + + XXPortalUser tUser = new XXPortalUser(); + tUser.setAddedByUserId(userId); + tUser.setCreateTime(new Date()); + tUser.setEmailAddress("test@gmail.com"); + tUser.setFirstName(name); + tUser.setId(userId); + tUser.setLastName(name); + + XXServiceDef xServiceDef = new XXServiceDef(); + xServiceDef.setAddedByUserId(userId); + xServiceDef.setCreateTime(new Date()); + xServiceDef.setDescription("test"); + xServiceDef.setGuid("1427365526516_835_0"); + xServiceDef.setId(userId); + + XXServiceVersionInfoDao xServiceVersionInfoDao = Mockito.mock(XXServiceVersionInfoDao.class); + + XXServiceVersionInfo serviceVersionInfo = new XXServiceVersionInfo(); + serviceVersionInfo.setServiceId(xService.getId()); + serviceVersionInfo.setPolicyVersion(xService.getPolicyVersion()); + serviceVersionInfo.setPolicyUpdateTime(xService.getPolicyUpdateTime()); + serviceVersionInfo.setTagVersion(xService.getTagVersion()); + serviceVersionInfo.setTagUpdateTime(xService.getTagUpdateTime()); + + Mockito.when(daoManager.getXXServiceVersionInfo()).thenReturn(xServiceVersionInfoDao); + Mockito.when(xServiceVersionInfoDao.findByServiceId(xService.getId())).thenReturn(serviceVersionInfo); + + Mockito.when(daoManager.getXXPortalUser()).thenReturn(xPortalUserDao); + Mockito.when(xPortalUserDao.getById(userId)).thenReturn(tUser); + + Mockito.when(daoManager.getXXServiceDef()).thenReturn(xServiceDefDao); + Mockito.when(xServiceDefDao.getById(xService.getType())).thenReturn(xServiceDef); + + Mockito.when(daoManager.getXXServiceConfigMap()).thenReturn(xServiceConfigMapDao); + Mockito.when(xServiceConfigMapDao.findByServiceId(xService.getId())).thenReturn(svcConfigMapList); + + RangerService dbService = serviceService.getPopulatedViewObject(xService); + + Assert.assertNotNull(dbService); + Assert.assertEquals(userId, dbService.getId()); + Assert.assertEquals(xService.getAddedByUserId(), dbService.getId()); + Assert.assertEquals(xService.getId(), dbService.getId()); + Assert.assertEquals(xService.getDescription(), dbService.getDescription()); + Assert.assertEquals(xService.getGuid(), dbService.getGuid()); + Assert.assertEquals(xService.getName(), dbService.getName()); + Assert.assertEquals(xService.getPolicyUpdateTime(), dbService.getPolicyUpdateTime()); + Assert.assertEquals(xService.getPolicyVersion(), dbService.getPolicyVersion()); + Assert.assertEquals(xService.getVersion(), dbService.getVersion()); + + Mockito.verify(daoManager).getXXServiceDef(); + Mockito.verify(daoManager).getXXServiceConfigMap(); + } + + @Test + public void test5GetAllServices() { + XXServiceDao xServiceDao = Mockito.mock(XXServiceDao.class); + XXPortalUserDao xPortalUserDao = Mockito.mock(XXPortalUserDao.class); + XXServiceConfigMapDao xServiceConfigMapDao = Mockito.mock(XXServiceConfigMapDao.class); + XXServiceDefDao xServiceDefDao = Mockito.mock(XXServiceDefDao.class); + + String name = "fdfdfds"; + + List svcConfigMapList = new ArrayList<>(); + XXServiceConfigMap xConfMap = new XXServiceConfigMap(); + xConfMap.setAddedByUserId(null); + xConfMap.setConfigkey(name); + xConfMap.setConfigvalue(name); + xConfMap.setCreateTime(new Date()); + xConfMap.setServiceId(null); + xConfMap.setUpdatedByUserId(null); + xConfMap.setUpdateTime(new Date()); + svcConfigMapList.add(xConfMap); + + List xServiceList = new ArrayList<>(); + XXService xService = xService(); + xServiceList.add(xService); + + XXPortalUser tUser = new XXPortalUser(); + tUser.setAddedByUserId(userId); + tUser.setCreateTime(new Date()); + tUser.setEmailAddress("test@gmail.com"); + tUser.setFirstName(name); + tUser.setId(userId); + tUser.setLastName(name); + + XXServiceDef xServiceDef = new XXServiceDef(); + xServiceDef.setAddedByUserId(userId); + xServiceDef.setCreateTime(new Date()); + xServiceDef.setDescription("test"); + xServiceDef.setGuid("1427365526516_835_0"); + xServiceDef.setId(userId); + + XXServiceVersionInfoDao xServiceVersionInfoDao = Mockito.mock(XXServiceVersionInfoDao.class); + + XXServiceVersionInfo serviceVersionInfo = new XXServiceVersionInfo(); + serviceVersionInfo.setServiceId(xService.getId()); + serviceVersionInfo.setPolicyVersion(xService.getPolicyVersion()); + serviceVersionInfo.setPolicyUpdateTime(xService.getPolicyUpdateTime()); + serviceVersionInfo.setTagVersion(xService.getTagVersion()); + serviceVersionInfo.setTagUpdateTime(xService.getTagUpdateTime()); + + Mockito.when(daoManager.getXXServiceVersionInfo()).thenReturn(xServiceVersionInfoDao); + Mockito.when(xServiceVersionInfoDao.findByServiceId(xService.getId())).thenReturn(serviceVersionInfo); + + Mockito.when(daoManager.getXXService()).thenReturn(xServiceDao); + Mockito.when(xServiceDao.getAll()).thenReturn(xServiceList); + + Mockito.when(daoManager.getXXPortalUser()).thenReturn(xPortalUserDao); + Mockito.when(xPortalUserDao.getById(userId)).thenReturn(tUser); + + Mockito.when(daoManager.getXXServiceDef()).thenReturn(xServiceDefDao); + Mockito.when(xServiceDefDao.getById(xService.getType())).thenReturn(xServiceDef); + + Mockito.when(daoManager.getXXServiceConfigMap()).thenReturn(xServiceConfigMapDao); + Mockito.when(xServiceConfigMapDao.findByServiceId(xService.getId())).thenReturn(svcConfigMapList); + + List dbServiceList = serviceService.getAllServices(); + Assert.assertNotNull(dbServiceList); + + Mockito.verify(daoManager).getXXServiceDef(); + Mockito.verify(daoManager).getXXServiceConfigMap(); + } + + @Test + public void test6GetTransactionLogCreate() { + RangerService rangerService = rangerService(); + + serviceService.createTransactionLog(rangerService, null, 1); + } + + @Test + public void test7GetTransactionLogUpdate() { + RangerService rangerService = rangerService(); + + serviceService.createTransactionLog(rangerService, null, 2); + } + + @Test + public void test8GetTransactionLogDelete() { + RangerService rangerService = rangerService(); + + serviceService.createTransactionLog(rangerService, null, 3); + } + + private RangerService rangerService() { + Map configs = new HashMap(); + configs.put("username", "servicemgr"); + configs.put("password", "servicemgr"); + configs.put("namenode", "servicemgr"); + configs.put("hadoop.security.authorization", "No"); + configs.put("hadoop.security.authentication", "Simple"); + configs.put("hadoop.security.auth_to_local", ""); + configs.put("dfs.datanode.kerberos.principal", ""); + configs.put("dfs.namenode.kerberos.principal", ""); + configs.put("dfs.secondary.namenode.kerberos.principal", ""); + configs.put("hadoop.rpc.protection", "Privacy"); + configs.put("commonNameForCertificate", ""); + + RangerService rangerService = new RangerService(); + rangerService.setId(userId); + rangerService.setConfigs(configs); + rangerService.setCreateTime(new Date()); + rangerService.setDescription("service"); + rangerService.setGuid("serviceguid"); + rangerService.setIsEnabled(true); + rangerService.setName("Hdfs service"); + rangerService.setPolicyUpdateTime(new Date()); + rangerService.setPolicyVersion(1L); + rangerService.setType(null); + rangerService.setUpdatedBy("Admin"); + rangerService.setUpdateTime(new Date()); + rangerService.setVersion(userId); + + return rangerService; + } + + private XXService xService() { + XXService xService = new XXService(); + xService.setAddedByUserId(userId); + xService.setCreateTime(new Date()); + xService.setDescription("Hdfs service"); + xService.setGuid("serviceguid"); + xService.setId(userId); + xService.setIsEnabled(true); + xService.setName("Hdfs"); + xService.setPolicyUpdateTime(new Date()); + xService.setPolicyVersion(1L); + xService.setType(1L); + xService.setUpdatedByUserId(userId); + xService.setUpdateTime(new Date()); + + return xService; + } } diff --git a/security-admin/src/test/java/org/apache/ranger/service/TestRangerServiceServiceBase.java b/security-admin/src/test/java/org/apache/ranger/service/TestRangerServiceServiceBase.java index d90e978a1e..2b3529804f 100644 --- a/security-admin/src/test/java/org/apache/ranger/service/TestRangerServiceServiceBase.java +++ b/security-admin/src/test/java/org/apache/ranger/service/TestRangerServiceServiceBase.java @@ -16,10 +16,6 @@ */ package org.apache.ranger.service; -import java.util.Date; -import java.util.HashMap; -import java.util.Map; - import org.apache.ranger.biz.RangerBizUtil; import org.apache.ranger.common.ContextUtil; import org.apache.ranger.common.RangerSearchUtil; @@ -48,169 +44,153 @@ import org.mockito.Mockito; import org.mockito.junit.MockitoJUnitRunner; +import java.util.Date; +import java.util.HashMap; +import java.util.Map; + @RunWith(MockitoJUnitRunner.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class TestRangerServiceServiceBase { - - private static Long Id = 8L; - - @InjectMocks - RangerServiceService rangerServiceService = new RangerServiceService(); - - @Mock - RangerDaoManager daoManager; - - @Mock - RangerSearchUtil searchUtil; - - @Mock - RangerBizUtil bizUtil; - - @Mock - BaseDao baseDao; - - @Rule - public ExpectedException thrown = ExpectedException.none(); - - public void setup() { - RangerSecurityContext context = new RangerSecurityContext(); - context.setUserSession(new UserSessionBase()); - RangerContextHolder.setSecurityContext(context); - UserSessionBase currentUserSession = ContextUtil - .getCurrentUserSession(); - currentUserSession.setUserAdmin(true); - } - - private RangerService rangerService() { - Map configs = new HashMap(); - configs.put("username", "servicemgr"); - configs.put("password", "servicemgr"); - configs.put("namenode", "servicemgr"); - configs.put("hadoop.security.authorization", "No"); - configs.put("hadoop.security.authentication", "Simple"); - configs.put("hadoop.security.auth_to_local", ""); - configs.put("dfs.datanode.kerberos.principal", ""); - configs.put("dfs.namenode.kerberos.principal", ""); - configs.put("dfs.secondary.namenode.kerberos.principal", ""); - configs.put("hadoop.rpc.protection", "Privacy"); - configs.put("commonNameForCertificate", ""); - - RangerService rangerService = new RangerService(); - rangerService.setId(Id); - rangerService.setConfigs(configs); - rangerService.setCreateTime(new Date()); - rangerService.setDescription("service"); - rangerService.setGuid("serviceguid"); - rangerService.setIsEnabled(true); - rangerService.setName("Hdfs service"); - rangerService.setPolicyUpdateTime(new Date()); - rangerService.setPolicyVersion(1L); - rangerService.setType(null); - rangerService.setUpdatedBy("Admin"); - rangerService.setUpdateTime(new Date()); - rangerService.setVersion(Id); - - return rangerService; - } - - private XXService service() { - XXService xService = new XXService(); - xService.setAddedByUserId(Id); - xService.setCreateTime(new Date()); - xService.setDescription("Hdfs service"); - xService.setGuid("serviceguid"); - xService.setId(Id); - xService.setIsEnabled(true); - xService.setName("Hdfs"); - xService.setPolicyUpdateTime(new Date()); - xService.setPolicyVersion(1L); - xService.setType(1L); - xService.setUpdatedByUserId(Id); - xService.setUpdateTime(new Date()); - - return xService; - } - - @Test - public void test1MapViewToEntityBean() { - XXServiceDefDao xServiceDefDao = Mockito.mock(XXServiceDefDao.class); - XXServiceDef xServiceDef = Mockito.mock(XXServiceDef.class); - RangerService rangerService = rangerService(); - XXService service = service(); - int OPERATION_CONTEXT = 1; - - Mockito.when(daoManager.getXXServiceDef()).thenReturn(xServiceDefDao); - Mockito.when(xServiceDefDao.findByName(rangerService.getType())) - .thenReturn(xServiceDef); - - XXService dbService = rangerServiceService.mapViewToEntityBean( - rangerService, service, OPERATION_CONTEXT); - Assert.assertNotNull(dbService); - Assert.assertEquals(dbService, service); - Assert.assertEquals(dbService.getDescription(), - service.getDescription()); - Assert.assertEquals(dbService.getGuid(), service.getGuid()); - Assert.assertEquals(dbService.getName(), service.getName()); - Assert.assertEquals(dbService.getAddedByUserId(), - service.getAddedByUserId()); - Assert.assertEquals(dbService.getId(), service.getId()); - Assert.assertEquals(dbService.getVersion(), service.getVersion()); - Assert.assertEquals(dbService.getType(), service.getType()); - Assert.assertEquals(dbService.getUpdatedByUserId(), - service.getUpdatedByUserId()); - - Mockito.verify(daoManager).getXXServiceDef(); - } - - @Test - public void test2mapEntityToViewBean() { - XXServiceDefDao xServiceDefDao = Mockito.mock(XXServiceDefDao.class); - XXServiceDef xServiceDef = Mockito.mock(XXServiceDef.class); - RangerService rangerService = rangerService(); - XXService service = service(); - - XXServiceVersionInfoDao xServiceVersionInfoDao = Mockito.mock(XXServiceVersionInfoDao.class); - - XXServiceVersionInfo serviceVersionInfo = new XXServiceVersionInfo(); - serviceVersionInfo.setServiceId(service.getId()); - serviceVersionInfo.setPolicyVersion(service.getPolicyVersion()); - serviceVersionInfo.setPolicyUpdateTime(service.getPolicyUpdateTime()); - serviceVersionInfo.setTagVersion(service.getTagVersion()); - serviceVersionInfo.setPolicyUpdateTime(service.getTagUpdateTime()); - - Mockito.when(daoManager.getXXServiceVersionInfo()).thenReturn(xServiceVersionInfoDao); - Mockito.when(xServiceVersionInfoDao.findByServiceId(service.getId())).thenReturn( - serviceVersionInfo); - - Mockito.when(daoManager.getXXServiceDef()).thenReturn(xServiceDefDao); - Mockito.when(xServiceDefDao.getById(service.getType())).thenReturn( - xServiceDef); - - RangerService dbRangerService = rangerServiceService - .mapEntityToViewBean(rangerService, service); - Assert.assertNotNull(dbRangerService); - Assert.assertEquals(dbRangerService, rangerService); - Assert.assertEquals(dbRangerService.getDescription(), - rangerService.getDescription()); - Assert.assertEquals(dbRangerService.getGuid(), rangerService.getGuid()); - Assert.assertEquals(dbRangerService.getName(), rangerService.getName()); - Assert.assertEquals(dbRangerService.getId(), rangerService.getId()); - Assert.assertEquals(dbRangerService.getVersion(), - rangerService.getVersion()); - Assert.assertEquals(dbRangerService.getType(), rangerService.getType()); - - Mockito.verify(daoManager).getXXServiceDef(); - } - - @Test - public void test3searchRangerServices() { - SearchFilter searchFilter = new SearchFilter(); - searchFilter.setParam(SearchFilter.POLICY_NAME, "policyName"); - searchFilter.setParam(SearchFilter.SERVICE_NAME, "serviceName"); - - RangerServiceList dbRangerServiceList = rangerServiceService - .searchRangerServices(searchFilter); - Assert.assertNotNull(dbRangerServiceList); - - } + private static final Long Id = 8L; + @Rule + public ExpectedException thrown = ExpectedException.none(); + @InjectMocks + RangerServiceService rangerServiceService = new RangerServiceService(); + @Mock + RangerDaoManager daoManager; + @Mock + RangerSearchUtil searchUtil; + @Mock + RangerBizUtil bizUtil; + @Mock + BaseDao baseDao; + + public void setup() { + RangerSecurityContext context = new RangerSecurityContext(); + context.setUserSession(new UserSessionBase()); + RangerContextHolder.setSecurityContext(context); + UserSessionBase currentUserSession = ContextUtil.getCurrentUserSession(); + currentUserSession.setUserAdmin(true); + } + + @Test + public void test1MapViewToEntityBean() { + XXServiceDefDao xServiceDefDao = Mockito.mock(XXServiceDefDao.class); + XXServiceDef xServiceDef = Mockito.mock(XXServiceDef.class); + RangerService rangerService = rangerService(); + XXService service = service(); + int operationContext = 1; + + Mockito.when(daoManager.getXXServiceDef()).thenReturn(xServiceDefDao); + Mockito.when(xServiceDefDao.findByName(rangerService.getType())).thenReturn(xServiceDef); + + XXService dbService = rangerServiceService.mapViewToEntityBean(rangerService, service, operationContext); + Assert.assertNotNull(dbService); + Assert.assertEquals(dbService, service); + Assert.assertEquals(dbService.getDescription(), service.getDescription()); + Assert.assertEquals(dbService.getGuid(), service.getGuid()); + Assert.assertEquals(dbService.getName(), service.getName()); + Assert.assertEquals(dbService.getAddedByUserId(), service.getAddedByUserId()); + Assert.assertEquals(dbService.getId(), service.getId()); + Assert.assertEquals(dbService.getVersion(), service.getVersion()); + Assert.assertEquals(dbService.getType(), service.getType()); + Assert.assertEquals(dbService.getUpdatedByUserId(), service.getUpdatedByUserId()); + + Mockito.verify(daoManager).getXXServiceDef(); + } + + @Test + public void test2mapEntityToViewBean() { + XXServiceDefDao xServiceDefDao = Mockito.mock(XXServiceDefDao.class); + XXServiceDef xServiceDef = Mockito.mock(XXServiceDef.class); + RangerService rangerService = rangerService(); + XXService service = service(); + + XXServiceVersionInfoDao xServiceVersionInfoDao = Mockito.mock(XXServiceVersionInfoDao.class); + + XXServiceVersionInfo serviceVersionInfo = new XXServiceVersionInfo(); + serviceVersionInfo.setServiceId(service.getId()); + serviceVersionInfo.setPolicyVersion(service.getPolicyVersion()); + serviceVersionInfo.setPolicyUpdateTime(service.getPolicyUpdateTime()); + serviceVersionInfo.setTagVersion(service.getTagVersion()); + serviceVersionInfo.setPolicyUpdateTime(service.getTagUpdateTime()); + + Mockito.when(daoManager.getXXServiceVersionInfo()).thenReturn(xServiceVersionInfoDao); + Mockito.when(xServiceVersionInfoDao.findByServiceId(service.getId())).thenReturn(serviceVersionInfo); + + Mockito.when(daoManager.getXXServiceDef()).thenReturn(xServiceDefDao); + Mockito.when(xServiceDefDao.getById(service.getType())).thenReturn(xServiceDef); + + RangerService dbRangerService = rangerServiceService.mapEntityToViewBean(rangerService, service); + Assert.assertNotNull(dbRangerService); + Assert.assertEquals(dbRangerService, rangerService); + Assert.assertEquals(dbRangerService.getDescription(), rangerService.getDescription()); + Assert.assertEquals(dbRangerService.getGuid(), rangerService.getGuid()); + Assert.assertEquals(dbRangerService.getName(), rangerService.getName()); + Assert.assertEquals(dbRangerService.getId(), rangerService.getId()); + Assert.assertEquals(dbRangerService.getVersion(), rangerService.getVersion()); + Assert.assertEquals(dbRangerService.getType(), rangerService.getType()); + + Mockito.verify(daoManager).getXXServiceDef(); + } + + @Test + public void test3searchRangerServices() { + SearchFilter searchFilter = new SearchFilter(); + searchFilter.setParam(SearchFilter.POLICY_NAME, "policyName"); + searchFilter.setParam(SearchFilter.SERVICE_NAME, "serviceName"); + + RangerServiceList dbRangerServiceList = rangerServiceService.searchRangerServices(searchFilter); + Assert.assertNotNull(dbRangerServiceList); + } + + private RangerService rangerService() { + Map configs = new HashMap<>(); + configs.put("username", "servicemgr"); + configs.put("password", "servicemgr"); + configs.put("namenode", "servicemgr"); + configs.put("hadoop.security.authorization", "No"); + configs.put("hadoop.security.authentication", "Simple"); + configs.put("hadoop.security.auth_to_local", ""); + configs.put("dfs.datanode.kerberos.principal", ""); + configs.put("dfs.namenode.kerberos.principal", ""); + configs.put("dfs.secondary.namenode.kerberos.principal", ""); + configs.put("hadoop.rpc.protection", "Privacy"); + configs.put("commonNameForCertificate", ""); + + RangerService rangerService = new RangerService(); + rangerService.setId(Id); + rangerService.setConfigs(configs); + rangerService.setCreateTime(new Date()); + rangerService.setDescription("service"); + rangerService.setGuid("serviceguid"); + rangerService.setIsEnabled(true); + rangerService.setName("Hdfs service"); + rangerService.setPolicyUpdateTime(new Date()); + rangerService.setPolicyVersion(1L); + rangerService.setType(null); + rangerService.setUpdatedBy("Admin"); + rangerService.setUpdateTime(new Date()); + rangerService.setVersion(Id); + + return rangerService; + } + + private XXService service() { + XXService xService = new XXService(); + xService.setAddedByUserId(Id); + xService.setCreateTime(new Date()); + xService.setDescription("Hdfs service"); + xService.setGuid("serviceguid"); + xService.setId(Id); + xService.setIsEnabled(true); + xService.setName("Hdfs"); + xService.setPolicyUpdateTime(new Date()); + xService.setPolicyVersion(1L); + xService.setType(1L); + xService.setUpdatedByUserId(Id); + xService.setUpdateTime(new Date()); + + return xService; + } } diff --git a/security-admin/src/test/java/org/apache/ranger/service/TestRangerServiceWithAssignedIdService.java b/security-admin/src/test/java/org/apache/ranger/service/TestRangerServiceWithAssignedIdService.java index c5221cda55..4ab6f58916 100644 --- a/security-admin/src/test/java/org/apache/ranger/service/TestRangerServiceWithAssignedIdService.java +++ b/security-admin/src/test/java/org/apache/ranger/service/TestRangerServiceWithAssignedIdService.java @@ -17,19 +17,15 @@ package org.apache.ranger.service; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; - import org.apache.ranger.db.RangerDaoManager; import org.apache.ranger.db.XXServiceConfigMapDao; import org.apache.ranger.db.XXServiceDao; import org.apache.ranger.db.XXServiceVersionInfoDao; import org.apache.ranger.entity.XXService; import org.apache.ranger.entity.XXServiceConfigMap; - import org.apache.ranger.entity.XXServiceVersionInfo; import org.apache.ranger.entity.XXServiceWithAssignedId; +import org.apache.ranger.plugin.model.RangerService; import org.junit.FixMethodOrder; import org.junit.Test; import org.junit.runner.RunWith; @@ -38,70 +34,72 @@ import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.junit.MockitoJUnitRunner; -import org.apache.ranger.plugin.model.RangerService; + +import java.util.ArrayList; +import java.util.Date; +import java.util.List; @RunWith(MockitoJUnitRunner.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class TestRangerServiceWithAssignedIdService { - - @InjectMocks - RangerServiceWithAssignedIdService rangerServiceWithAssignedIdService; - - @Mock - RangerDaoManager daoMgr; - @Mock - XXServiceConfigMapDao xXServiceConfigMapDao; - - @Mock - org.apache.ranger.entity.XXServiceDef xXServiceDef; - - @Mock - org.apache.ranger.db.XXServiceDefDao xXServiceDefDao; - - @Mock - XXServiceDao xXServiceDao; - - @Mock - XXService xXService; - - @Mock - RangerService RangerService; - - @Mock - org.apache.ranger.db.XXPortalUserDao xXPortalUserDao; - - @Mock - XXServiceVersionInfoDao xXServiceVersionInfoDao; - - @Mock - XXServiceVersionInfo xXServiceVersionInfo; - - @Test - public void test1GetPopulatedViewObject() { - XXServiceWithAssignedId xXServiceWithAssignedId = new XXServiceWithAssignedId(); - xXServiceWithAssignedId.setId(1L); - Date date = new Date(); - xXServiceWithAssignedId.setIsEnabled(true); - xXServiceWithAssignedId.setName("testService"); - xXServiceWithAssignedId.setPolicyVersion(1L); - xXServiceWithAssignedId.setVersion(1L); - xXServiceWithAssignedId.setCreateTime(date); - xXServiceWithAssignedId.setTagService(1L); - xXServiceWithAssignedId.setTagVersion(1L); - xXServiceWithAssignedId.setUpdateTime(date); - xXServiceWithAssignedId.setUpdatedByUserId(1L); - xXServiceWithAssignedId.setAddedByUserId(1L); - xXServiceWithAssignedId.setType(1L); - List svcConfigMapList = new ArrayList(); - Mockito.when(daoMgr.getXXPortalUser()).thenReturn(xXPortalUserDao); - Mockito.when(daoMgr.getXXServiceDef()).thenReturn(xXServiceDefDao); - Mockito.when(xXServiceDefDao.getById(1L)).thenReturn(xXServiceDef); - Mockito.when(daoMgr.getXXService()).thenReturn(xXServiceDao); - Mockito.when(xXServiceDao.getById(1L)).thenReturn(xXService); - Mockito.when(daoMgr.getXXServiceVersionInfo()).thenReturn(xXServiceVersionInfoDao); - Mockito.when(xXServiceVersionInfoDao.findByServiceId(1L)).thenReturn(xXServiceVersionInfo); - Mockito.when(daoMgr.getXXServiceConfigMap()).thenReturn(xXServiceConfigMapDao); - Mockito.when(xXServiceConfigMapDao.findByServiceId(1L)).thenReturn(svcConfigMapList); - rangerServiceWithAssignedIdService.getPopulatedViewObject(xXServiceWithAssignedId); - } + @InjectMocks + RangerServiceWithAssignedIdService rangerServiceWithAssignedIdService; + + @Mock + RangerDaoManager daoMgr; + @Mock + XXServiceConfigMapDao xXServiceConfigMapDao; + + @Mock + org.apache.ranger.entity.XXServiceDef xXServiceDef; + + @Mock + org.apache.ranger.db.XXServiceDefDao xXServiceDefDao; + + @Mock + XXServiceDao xXServiceDao; + + @Mock + XXService xXService; + + @Mock + RangerService rangerService; + + @Mock + org.apache.ranger.db.XXPortalUserDao xXPortalUserDao; + + @Mock + XXServiceVersionInfoDao xXServiceVersionInfoDao; + + @Mock + XXServiceVersionInfo xXServiceVersionInfo; + + @Test + public void test1GetPopulatedViewObject() { + XXServiceWithAssignedId xXServiceWithAssignedId = new XXServiceWithAssignedId(); + xXServiceWithAssignedId.setId(1L); + Date date = new Date(); + xXServiceWithAssignedId.setIsEnabled(true); + xXServiceWithAssignedId.setName("testService"); + xXServiceWithAssignedId.setPolicyVersion(1L); + xXServiceWithAssignedId.setVersion(1L); + xXServiceWithAssignedId.setCreateTime(date); + xXServiceWithAssignedId.setTagService(1L); + xXServiceWithAssignedId.setTagVersion(1L); + xXServiceWithAssignedId.setUpdateTime(date); + xXServiceWithAssignedId.setUpdatedByUserId(1L); + xXServiceWithAssignedId.setAddedByUserId(1L); + xXServiceWithAssignedId.setType(1L); + List svcConfigMapList = new ArrayList<>(); + Mockito.when(daoMgr.getXXPortalUser()).thenReturn(xXPortalUserDao); + Mockito.when(daoMgr.getXXServiceDef()).thenReturn(xXServiceDefDao); + Mockito.when(xXServiceDefDao.getById(1L)).thenReturn(xXServiceDef); + Mockito.when(daoMgr.getXXService()).thenReturn(xXServiceDao); + Mockito.when(xXServiceDao.getById(1L)).thenReturn(xXService); + Mockito.when(daoMgr.getXXServiceVersionInfo()).thenReturn(xXServiceVersionInfoDao); + Mockito.when(xXServiceVersionInfoDao.findByServiceId(1L)).thenReturn(xXServiceVersionInfo); + Mockito.when(daoMgr.getXXServiceConfigMap()).thenReturn(xXServiceConfigMapDao); + Mockito.when(xXServiceConfigMapDao.findByServiceId(1L)).thenReturn(svcConfigMapList); + rangerServiceWithAssignedIdService.getPopulatedViewObject(xXServiceWithAssignedId); + } } diff --git a/security-admin/src/test/java/org/apache/ranger/service/TestRangerTagDefService.java b/security-admin/src/test/java/org/apache/ranger/service/TestRangerTagDefService.java index c031c942c9..4b443c74df 100644 --- a/security-admin/src/test/java/org/apache/ranger/service/TestRangerTagDefService.java +++ b/security-admin/src/test/java/org/apache/ranger/service/TestRangerTagDefService.java @@ -16,10 +16,6 @@ */ package org.apache.ranger.service; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; - import org.apache.ranger.db.RangerDaoManager; import org.apache.ranger.db.XXTagDefDao; import org.apache.ranger.entity.XXTagAttributeDef; @@ -35,196 +31,198 @@ import org.mockito.Mockito; import org.mockito.runners.MockitoJUnitRunner; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + @RunWith(MockitoJUnitRunner.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class TestRangerTagDefService { - Long id = 1L; - String guid = "989898_01_1"; - String name = "test"; - Long serviceId = 5L; - - @InjectMocks - RangerTagDefService rangerTagDefService = new RangerTagDefService(); - - @Mock - RangerDaoManager daoMgr; - - @Test - public void test1ValidateForCreate() { - RangerTagDef rangerServiceDef = new RangerTagDef(); - - rangerTagDefService.validateForCreate(rangerServiceDef); - Assert.assertNotNull(rangerServiceDef); - } - - @Test - public void test2validateForUpdate() { - RangerTagDef rangerServiceDef = new RangerTagDef(); - XXTagDef xXTagDef = new XXTagDef(); - - rangerTagDefService.validateForUpdate(rangerServiceDef, xXTagDef); - Assert.assertNotNull(rangerServiceDef); - } - - @Test - public void test3postUpdate(){ - XXTagDef tagDef = new XXTagDef(); - tagDef.setId(id); - tagDef.setName(name); - tagDef.setUpdateTime(new Date()); - - List tagAttrDefList = new ArrayList(); - XXTagAttributeDef xxTagAttributeDef = new XXTagAttributeDef(); - xxTagAttributeDef.setId(id); - xxTagAttributeDef.setName(name); - tagAttrDefList.add(xxTagAttributeDef); - - RangerTagDef result = rangerTagDefService.postUpdate(tagDef); - Assert.assertEquals(result.getId(), tagAttrDefList.get(0).getId()); - Assert.assertEquals(result.getName(), tagAttrDefList.get(0).getName()); - - } - - @Test - public void test4getTagDefByGuid(){ - XXTagDef xxTagDef = new XXTagDef(); - xxTagDef.setId(id); - xxTagDef.setName(name); - xxTagDef.setUpdateTime(new Date()); - - XXTagDefDao xXTagDefDao = Mockito.mock(XXTagDefDao.class); - Mockito.when(daoMgr.getXXTagDef()).thenReturn(xXTagDefDao); - Mockito.when(xXTagDefDao.findByGuid(guid)).thenReturn(xxTagDef); - - List tagAttrDefList = new ArrayList(); - XXTagAttributeDef xxTagAttributeDef = new XXTagAttributeDef(); - xxTagAttributeDef.setId(id); - xxTagAttributeDef.setName(name); - tagAttrDefList.add(xxTagAttributeDef); - - RangerTagDef result = rangerTagDefService.getTagDefByGuid(guid); - Assert.assertEquals(result.getId(), tagAttrDefList.get(0).getId()); - Assert.assertEquals(result.getName(), tagAttrDefList.get(0).getName()); - - Mockito.verify(daoMgr).getXXTagDef(); - Mockito.verify(xXTagDefDao).findByGuid(guid); - } - - @Test - public void test5getTagDefByGuid(){ - XXTagDef xxTagDef = null; - - XXTagDefDao xXTagDefDao = Mockito.mock(XXTagDefDao.class); - Mockito.when(daoMgr.getXXTagDef()).thenReturn(xXTagDefDao); - Mockito.when(xXTagDefDao.findByGuid(guid)).thenReturn(xxTagDef); - - RangerTagDef result = rangerTagDefService.getTagDefByGuid(guid); - Assert.assertNull(result); - - Mockito.verify(daoMgr).getXXTagDef(); - Mockito.verify(xXTagDefDao).findByGuid(guid); - } - - @Test - public void test6getTagDefByName(){ - RangerTagDef oldTagDef = new RangerTagDef(); - oldTagDef.setId(id); - oldTagDef.setName(name); - XXTagDef xxTagDef = new XXTagDef(); - xxTagDef.setId(id); - xxTagDef.setName(name); - xxTagDef.setUpdateTime(new Date()); - - XXTagDefDao xXTagDefDao = Mockito.mock(XXTagDefDao.class); - Mockito.when(daoMgr.getXXTagDef()).thenReturn(xXTagDefDao); - Mockito.when(xXTagDefDao.findByName(name)).thenReturn(xxTagDef); - - List tagAttrDefList = new ArrayList(); - XXTagAttributeDef xxTagAttributeDef = new XXTagAttributeDef(); - xxTagAttributeDef.setId(id); - xxTagAttributeDef.setName(name); - tagAttrDefList.add(xxTagAttributeDef); - - RangerTagDef result = rangerTagDefService.getTagDefByName(name); - Assert.assertEquals(result.getId(), tagAttrDefList.get(0).getId()); - Assert.assertEquals(result.getName(), tagAttrDefList.get(0).getName()); - - Mockito.verify(daoMgr).getXXTagDef(); - Mockito.verify(xXTagDefDao).findByName(name); - } - - @Test - public void test7getTagDefByName(){ - XXTagDef xxTagDef = null; - - XXTagDefDao xXTagDefDao = Mockito.mock(XXTagDefDao.class); - Mockito.when(daoMgr.getXXTagDef()).thenReturn(xXTagDefDao); - Mockito.when(xXTagDefDao.findByName(name)).thenReturn(xxTagDef); - - RangerTagDef result = rangerTagDefService.getTagDefByName(name); - Assert.assertNull(result); - - Mockito.verify(daoMgr).getXXTagDef(); - Mockito.verify(xXTagDefDao).findByName(name); - } - - @Test - public void test8getTagDefsByServiceId(){ - List xxTagDefs = new ArrayList(); - XXTagDef xxTagDef = new XXTagDef(); - xxTagDef.setId(id); - xxTagDef.setName(name); - xxTagDefs.add(xxTagDef); - - XXTagDefDao xXTagDefDao = Mockito.mock(XXTagDefDao.class); - Mockito.when(daoMgr.getXXTagDef()).thenReturn(xXTagDefDao); - Mockito.when(xXTagDefDao.findByServiceId(serviceId)).thenReturn(xxTagDefs); - - List tagAttrDefList = new ArrayList(); - XXTagAttributeDef xxTagAttributeDef = new XXTagAttributeDef(); - xxTagAttributeDef.setId(id); - xxTagAttributeDef.setName(name); - tagAttrDefList.add(xxTagAttributeDef); - - List result = rangerTagDefService.getTagDefsByServiceId(serviceId); - Assert.assertEquals(result.get(0).getId(), tagAttrDefList.get(0).getId()); - Assert.assertEquals(result.get(0).getName(), tagAttrDefList.get(0).getName()); - - Mockito.verify(daoMgr).getXXTagDef(); - Mockito.verify(xXTagDefDao).findByServiceId(serviceId); - } - - - @Test - public void test9getTagDefsByServiceId(){ - List xxTagDefs = new ArrayList(); - - XXTagDefDao xXTagDefDao = Mockito.mock(XXTagDefDao.class); - Mockito.when(daoMgr.getXXTagDef()).thenReturn(xXTagDefDao); - Mockito.when(xXTagDefDao.findByServiceId(serviceId)).thenReturn(xxTagDefs); - - List result = rangerTagDefService.getTagDefsByServiceId(serviceId); - Assert.assertNotNull(result); - - Mockito.verify(daoMgr).getXXTagDef(); - Mockito.verify(xXTagDefDao).findByServiceId(serviceId); - } - - @Test - public void test10getPopulatedViewObject(){ - XXTagDef xxTagDef = new XXTagDef(); - xxTagDef.setId(id); - xxTagDef.setName(name); - xxTagDef.setUpdateTime(new Date()); - - List tagAttrDefList = new ArrayList(); - XXTagAttributeDef xxTagAttributeDef = new XXTagAttributeDef(); - xxTagAttributeDef.setId(id); - xxTagAttributeDef.setName(name); - tagAttrDefList.add(xxTagAttributeDef); - - RangerTagDef result = rangerTagDefService.getPopulatedViewObject(xxTagDef); - Assert.assertEquals(result.getId(), tagAttrDefList.get(0).getId()); - Assert.assertEquals(result.getName(), tagAttrDefList.get(0).getName()); - } + Long id = 1L; + String guid = "989898_01_1"; + String name = "test"; + Long serviceId = 5L; + + @InjectMocks + RangerTagDefService rangerTagDefService = new RangerTagDefService(); + + @Mock + RangerDaoManager daoMgr; + + @Test + public void test1ValidateForCreate() { + RangerTagDef rangerServiceDef = new RangerTagDef(); + + rangerTagDefService.validateForCreate(rangerServiceDef); + Assert.assertNotNull(rangerServiceDef); + } + + @Test + public void test2validateForUpdate() { + RangerTagDef rangerServiceDef = new RangerTagDef(); + XXTagDef xXTagDef = new XXTagDef(); + + rangerTagDefService.validateForUpdate(rangerServiceDef, xXTagDef); + Assert.assertNotNull(rangerServiceDef); + } + + @Test + public void test3postUpdate() { + XXTagDef tagDef = new XXTagDef(); + tagDef.setId(id); + tagDef.setName(name); + tagDef.setUpdateTime(new Date()); + + List tagAttrDefList = new ArrayList<>(); + XXTagAttributeDef xxTagAttributeDef = new XXTagAttributeDef(); + xxTagAttributeDef.setId(id); + xxTagAttributeDef.setName(name); + tagAttrDefList.add(xxTagAttributeDef); + + RangerTagDef result = rangerTagDefService.postUpdate(tagDef); + Assert.assertEquals(result.getId(), tagAttrDefList.get(0).getId()); + Assert.assertEquals(result.getName(), tagAttrDefList.get(0).getName()); + } + + @Test + public void test4getTagDefByGuid() { + XXTagDef xxTagDef = new XXTagDef(); + xxTagDef.setId(id); + xxTagDef.setName(name); + xxTagDef.setUpdateTime(new Date()); + + XXTagDefDao xXTagDefDao = Mockito.mock(XXTagDefDao.class); + Mockito.when(daoMgr.getXXTagDef()).thenReturn(xXTagDefDao); + Mockito.when(xXTagDefDao.findByGuid(guid)).thenReturn(xxTagDef); + + List tagAttrDefList = new ArrayList<>(); + XXTagAttributeDef xxTagAttributeDef = new XXTagAttributeDef(); + xxTagAttributeDef.setId(id); + xxTagAttributeDef.setName(name); + tagAttrDefList.add(xxTagAttributeDef); + + RangerTagDef result = rangerTagDefService.getTagDefByGuid(guid); + Assert.assertEquals(result.getId(), tagAttrDefList.get(0).getId()); + Assert.assertEquals(result.getName(), tagAttrDefList.get(0).getName()); + + Mockito.verify(daoMgr).getXXTagDef(); + Mockito.verify(xXTagDefDao).findByGuid(guid); + } + + @Test + public void test5getTagDefByGuid() { + XXTagDef xxTagDef = null; + + XXTagDefDao xXTagDefDao = Mockito.mock(XXTagDefDao.class); + Mockito.when(daoMgr.getXXTagDef()).thenReturn(xXTagDefDao); + Mockito.when(xXTagDefDao.findByGuid(guid)).thenReturn(xxTagDef); + + RangerTagDef result = rangerTagDefService.getTagDefByGuid(guid); + Assert.assertNull(result); + + Mockito.verify(daoMgr).getXXTagDef(); + Mockito.verify(xXTagDefDao).findByGuid(guid); + } + + @Test + public void test6getTagDefByName() { + RangerTagDef oldTagDef = new RangerTagDef(); + oldTagDef.setId(id); + oldTagDef.setName(name); + XXTagDef xxTagDef = new XXTagDef(); + xxTagDef.setId(id); + xxTagDef.setName(name); + xxTagDef.setUpdateTime(new Date()); + + XXTagDefDao xXTagDefDao = Mockito.mock(XXTagDefDao.class); + Mockito.when(daoMgr.getXXTagDef()).thenReturn(xXTagDefDao); + Mockito.when(xXTagDefDao.findByName(name)).thenReturn(xxTagDef); + + List tagAttrDefList = new ArrayList<>(); + XXTagAttributeDef xxTagAttributeDef = new XXTagAttributeDef(); + xxTagAttributeDef.setId(id); + xxTagAttributeDef.setName(name); + tagAttrDefList.add(xxTagAttributeDef); + + RangerTagDef result = rangerTagDefService.getTagDefByName(name); + Assert.assertEquals(result.getId(), tagAttrDefList.get(0).getId()); + Assert.assertEquals(result.getName(), tagAttrDefList.get(0).getName()); + + Mockito.verify(daoMgr).getXXTagDef(); + Mockito.verify(xXTagDefDao).findByName(name); + } + + @Test + public void test7getTagDefByName() { + XXTagDef xxTagDef = null; + + XXTagDefDao xXTagDefDao = Mockito.mock(XXTagDefDao.class); + Mockito.when(daoMgr.getXXTagDef()).thenReturn(xXTagDefDao); + Mockito.when(xXTagDefDao.findByName(name)).thenReturn(xxTagDef); + + RangerTagDef result = rangerTagDefService.getTagDefByName(name); + Assert.assertNull(result); + + Mockito.verify(daoMgr).getXXTagDef(); + Mockito.verify(xXTagDefDao).findByName(name); + } + + @Test + public void test8getTagDefsByServiceId() { + List xxTagDefs = new ArrayList<>(); + XXTagDef xxTagDef = new XXTagDef(); + xxTagDef.setId(id); + xxTagDef.setName(name); + xxTagDefs.add(xxTagDef); + + XXTagDefDao xXTagDefDao = Mockito.mock(XXTagDefDao.class); + Mockito.when(daoMgr.getXXTagDef()).thenReturn(xXTagDefDao); + Mockito.when(xXTagDefDao.findByServiceId(serviceId)).thenReturn(xxTagDefs); + + List tagAttrDefList = new ArrayList<>(); + XXTagAttributeDef xxTagAttributeDef = new XXTagAttributeDef(); + xxTagAttributeDef.setId(id); + xxTagAttributeDef.setName(name); + tagAttrDefList.add(xxTagAttributeDef); + + List result = rangerTagDefService.getTagDefsByServiceId(serviceId); + Assert.assertEquals(result.get(0).getId(), tagAttrDefList.get(0).getId()); + Assert.assertEquals(result.get(0).getName(), tagAttrDefList.get(0).getName()); + + Mockito.verify(daoMgr).getXXTagDef(); + Mockito.verify(xXTagDefDao).findByServiceId(serviceId); + } + + @Test + public void test9getTagDefsByServiceId() { + List xxTagDefs = new ArrayList<>(); + + XXTagDefDao xXTagDefDao = Mockito.mock(XXTagDefDao.class); + Mockito.when(daoMgr.getXXTagDef()).thenReturn(xXTagDefDao); + Mockito.when(xXTagDefDao.findByServiceId(serviceId)).thenReturn(xxTagDefs); + + List result = rangerTagDefService.getTagDefsByServiceId(serviceId); + Assert.assertNotNull(result); + + Mockito.verify(daoMgr).getXXTagDef(); + Mockito.verify(xXTagDefDao).findByServiceId(serviceId); + } + + @Test + public void test10getPopulatedViewObject() { + XXTagDef xxTagDef = new XXTagDef(); + xxTagDef.setId(id); + xxTagDef.setName(name); + xxTagDef.setUpdateTime(new Date()); + + List tagAttrDefList = new ArrayList<>(); + XXTagAttributeDef xxTagAttributeDef = new XXTagAttributeDef(); + xxTagAttributeDef.setId(id); + xxTagAttributeDef.setName(name); + tagAttrDefList.add(xxTagAttributeDef); + + RangerTagDef result = rangerTagDefService.getPopulatedViewObject(xxTagDef); + Assert.assertEquals(result.getId(), tagAttrDefList.get(0).getId()); + Assert.assertEquals(result.getName(), tagAttrDefList.get(0).getName()); + } } diff --git a/security-admin/src/test/java/org/apache/ranger/service/TestRangerTagDefServiceBase.java b/security-admin/src/test/java/org/apache/ranger/service/TestRangerTagDefServiceBase.java index a759c20d7d..099744642f 100644 --- a/security-admin/src/test/java/org/apache/ranger/service/TestRangerTagDefServiceBase.java +++ b/security-admin/src/test/java/org/apache/ranger/service/TestRangerTagDefServiceBase.java @@ -33,41 +33,38 @@ @RunWith(MockitoJUnitRunner.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class TestRangerTagDefServiceBase { - Long id = 1L; - String guid = "989898_01_1"; - String name = "test"; - Long version = 5L; - String type = "typo"; - Long totalCount = 50L; + @Rule + public ExpectedException thrown = ExpectedException.none(); + Long id = 1L; + String guid = "989898_01_1"; + String name = "test"; + Long version = 5L; + String type = "typo"; + Long totalCount = 50L; + @InjectMocks + RangerTagDefService rangerTagDefService = new RangerTagDefService(); + @Mock + RangerDaoManager daoMgr; - @InjectMocks - RangerTagDefService rangerTagDefService = new RangerTagDefService(); - - @Mock - RangerDaoManager daoMgr; - - @Rule - public ExpectedException thrown = ExpectedException.none(); - - @Test - public void test1mapViewToEntityBean() { - RangerTagDef rangerTagDef = new RangerTagDef(); - rangerTagDef.setId(id); - rangerTagDef.setGuid(guid); - - XXTagDef xxTagDef = new XXTagDef(); - xxTagDef.setId(id); - xxTagDef.setGuid(guid); - xxTagDef.setName(name); - xxTagDef.setVersion(version); - int operationContext = 1; + @Test + public void test1mapViewToEntityBean() { + RangerTagDef rangerTagDef = new RangerTagDef(); + rangerTagDef.setId(id); + rangerTagDef.setGuid(guid); - XXTagDef result = rangerTagDefService.mapViewToEntityBean(rangerTagDef,xxTagDef,operationContext); - Assert.assertNotNull(result); - Assert.assertEquals(result, xxTagDef); - Assert.assertEquals(result.getGuid(), xxTagDef.getGuid()); - Assert.assertEquals(result.getName(), xxTagDef.getName()); - Assert.assertEquals(result.getId(), xxTagDef.getId()); - Assert.assertEquals(result.getVersion(), xxTagDef.getVersion()); - } -} + XXTagDef xxTagDef = new XXTagDef(); + xxTagDef.setId(id); + xxTagDef.setGuid(guid); + xxTagDef.setName(name); + xxTagDef.setVersion(version); + int operationContext = 1; + + XXTagDef result = rangerTagDefService.mapViewToEntityBean(rangerTagDef, xxTagDef, operationContext); + Assert.assertNotNull(result); + Assert.assertEquals(result, xxTagDef); + Assert.assertEquals(result.getGuid(), xxTagDef.getGuid()); + Assert.assertEquals(result.getName(), xxTagDef.getName()); + Assert.assertEquals(result.getId(), xxTagDef.getId()); + Assert.assertEquals(result.getVersion(), xxTagDef.getVersion()); + } +} diff --git a/security-admin/src/test/java/org/apache/ranger/service/TestRangerTagResourceMapService.java b/security-admin/src/test/java/org/apache/ranger/service/TestRangerTagResourceMapService.java index 1e17af8bac..a75048d139 100644 --- a/security-admin/src/test/java/org/apache/ranger/service/TestRangerTagResourceMapService.java +++ b/security-admin/src/test/java/org/apache/ranger/service/TestRangerTagResourceMapService.java @@ -34,99 +34,88 @@ @RunWith(MockitoJUnitRunner.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class TestRangerTagResourceMapService { - @InjectMocks - RangerTagResourceMapService rangerTagResourceMapService; - - @Mock - XXTagResourceMap xXTagResourceMap; - - @Mock - RangerDaoManager daoMgr; - - @Mock - XXServiceVersionInfoDao xXServiceVersionInfoDao; - - @Mock - org.apache.ranger.db.XXPortalUserDao XXPortalUserDao; - - @Mock - XXTagResourceMapDao xXTagResourceMapDao; - - @Test - public void test1PostCreate() { - Mockito.when(daoMgr.getXXPortalUser()).thenReturn(XXPortalUserDao); - Mockito.when(daoMgr.getXXServiceVersionInfo()).thenReturn(xXServiceVersionInfoDao); - rangerTagResourceMapService.postCreate(xXTagResourceMap); - - } - - @Test - public void test3GetPopulatedViewObject() { - Mockito.when(daoMgr.getXXPortalUser()).thenReturn(XXPortalUserDao); - rangerTagResourceMapService.getPopulatedViewObject(xXTagResourceMap); - - } - - @Test - public void test4GetByTagId() { - Mockito.when(daoMgr.getXXTagResourceMap()).thenReturn(xXTagResourceMapDao); - rangerTagResourceMapService.getByTagId(1L); - - } - - @Test - public void test5GetByTagGuid() { - Mockito.when(daoMgr.getXXTagResourceMap()).thenReturn(xXTagResourceMapDao); - rangerTagResourceMapService.getByTagGuid("1"); - - } - - @Test - public void test6GetByResourceId() { - Mockito.when(daoMgr.getXXTagResourceMap()).thenReturn(xXTagResourceMapDao); - rangerTagResourceMapService.getByResourceId(1L); - - } - - @Test - public void test7GetTagIdsForResourceId() { - Mockito.when(daoMgr.getXXTagResourceMap()).thenReturn(xXTagResourceMapDao); - rangerTagResourceMapService.getTagIdsForResourceId(1L); - - } - - @Test - public void test8GetByResourceGuid() { - Mockito.when(daoMgr.getXXTagResourceMap()).thenReturn(xXTagResourceMapDao); - rangerTagResourceMapService.getByResourceGuid("1"); - - } - - @Test - public void test9GetByGuid() { - Mockito.when(daoMgr.getXXTagResourceMap()).thenReturn(xXTagResourceMapDao); - rangerTagResourceMapService.getByGuid("1"); - - } - - @Test - public void test10GetByTagAndResourceId() { - Mockito.when(daoMgr.getXXTagResourceMap()).thenReturn(xXTagResourceMapDao); - rangerTagResourceMapService.getByTagAndResourceId(1L, 1L); - - } - - @Test - public void test11GetByTagAndResourceGuid() { - Mockito.when(daoMgr.getXXTagResourceMap()).thenReturn(xXTagResourceMapDao); - rangerTagResourceMapService.getByTagAndResourceGuid("1", "1"); - - } - - @Test - public void test12GetTagResourceMapsByServiceId() { - Mockito.when(daoMgr.getXXTagResourceMap()).thenReturn(xXTagResourceMapDao); - rangerTagResourceMapService.getTagResourceMapsByServiceId(1L); - - } + @InjectMocks + RangerTagResourceMapService rangerTagResourceMapService; + + @Mock + XXTagResourceMap xXTagResourceMap; + + @Mock + RangerDaoManager daoMgr; + + @Mock + XXServiceVersionInfoDao xXServiceVersionInfoDao; + + @Mock + org.apache.ranger.db.XXPortalUserDao xXPortalUserDao; + + @Mock + XXTagResourceMapDao xXTagResourceMapDao; + + @Test + public void test1PostCreate() { + Mockito.when(daoMgr.getXXPortalUser()).thenReturn(xXPortalUserDao); + Mockito.when(daoMgr.getXXServiceVersionInfo()).thenReturn(xXServiceVersionInfoDao); + rangerTagResourceMapService.postCreate(xXTagResourceMap); + } + + @Test + public void test3GetPopulatedViewObject() { + Mockito.when(daoMgr.getXXPortalUser()).thenReturn(xXPortalUserDao); + rangerTagResourceMapService.getPopulatedViewObject(xXTagResourceMap); + } + + @Test + public void test4GetByTagId() { + Mockito.when(daoMgr.getXXTagResourceMap()).thenReturn(xXTagResourceMapDao); + rangerTagResourceMapService.getByTagId(1L); + } + + @Test + public void test5GetByTagGuid() { + Mockito.when(daoMgr.getXXTagResourceMap()).thenReturn(xXTagResourceMapDao); + rangerTagResourceMapService.getByTagGuid("1"); + } + + @Test + public void test6GetByResourceId() { + Mockito.when(daoMgr.getXXTagResourceMap()).thenReturn(xXTagResourceMapDao); + rangerTagResourceMapService.getByResourceId(1L); + } + + @Test + public void test7GetTagIdsForResourceId() { + Mockito.when(daoMgr.getXXTagResourceMap()).thenReturn(xXTagResourceMapDao); + rangerTagResourceMapService.getTagIdsForResourceId(1L); + } + + @Test + public void test8GetByResourceGuid() { + Mockito.when(daoMgr.getXXTagResourceMap()).thenReturn(xXTagResourceMapDao); + rangerTagResourceMapService.getByResourceGuid("1"); + } + + @Test + public void test9GetByGuid() { + Mockito.when(daoMgr.getXXTagResourceMap()).thenReturn(xXTagResourceMapDao); + rangerTagResourceMapService.getByGuid("1"); + } + + @Test + public void test10GetByTagAndResourceId() { + Mockito.when(daoMgr.getXXTagResourceMap()).thenReturn(xXTagResourceMapDao); + rangerTagResourceMapService.getByTagAndResourceId(1L, 1L); + } + + @Test + public void test11GetByTagAndResourceGuid() { + Mockito.when(daoMgr.getXXTagResourceMap()).thenReturn(xXTagResourceMapDao); + rangerTagResourceMapService.getByTagAndResourceGuid("1", "1"); + } + + @Test + public void test12GetTagResourceMapsByServiceId() { + Mockito.when(daoMgr.getXXTagResourceMap()).thenReturn(xXTagResourceMapDao); + rangerTagResourceMapService.getTagResourceMapsByServiceId(1L); + } } diff --git a/security-admin/src/test/java/org/apache/ranger/service/TestRangerTagService.java b/security-admin/src/test/java/org/apache/ranger/service/TestRangerTagService.java index af80ed11d1..eab6897716 100644 --- a/security-admin/src/test/java/org/apache/ranger/service/TestRangerTagService.java +++ b/security-admin/src/test/java/org/apache/ranger/service/TestRangerTagService.java @@ -18,8 +18,16 @@ */ package org.apache.ranger.service; +import org.apache.ranger.db.RangerDaoManager; +import org.apache.ranger.db.XXPortalUserDao; import org.apache.ranger.db.XXServiceResourceDao; +import org.apache.ranger.db.XXServiceVersionInfoDao; +import org.apache.ranger.db.XXTagAttributeDao; +import org.apache.ranger.db.XXTagDao; +import org.apache.ranger.db.XXTagDefDao; import org.apache.ranger.entity.XXServiceResource; +import org.apache.ranger.entity.XXTag; +import org.apache.ranger.entity.XXTagDef; import org.junit.FixMethodOrder; import org.junit.Test; import org.junit.runner.RunWith; @@ -31,119 +39,103 @@ import java.util.Date; -import org.apache.ranger.db.RangerDaoManager; -import org.apache.ranger.db.XXPortalUserDao; -import org.apache.ranger.db.XXServiceVersionInfoDao; -import org.apache.ranger.db.XXTagAttributeDao; -import org.apache.ranger.db.XXTagDao; -import org.apache.ranger.db.XXTagDefDao; -import org.apache.ranger.entity.XXTag; -import org.apache.ranger.entity.XXTagDef; - @RunWith(MockitoJUnitRunner.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class TestRangerTagService { + @InjectMocks + RangerTagService rangerTagService; - @InjectMocks - RangerTagService rangerTagService; - - @Mock - XXTag xXTag; + @Mock + XXTag xXTag; - @Mock - RangerDaoManager daoMgr; + @Mock + RangerDaoManager daoMgr; - @Mock - XXPortalUserDao xXPortalUserDao; + @Mock + XXPortalUserDao xXPortalUserDao; - @Mock - XXServiceVersionInfoDao xXServiceVersionInfoDao; + @Mock + XXServiceVersionInfoDao xXServiceVersionInfoDao; - @Mock - XXTagDefDao xXTagDefDao; + @Mock + XXTagDefDao xXTagDefDao; - @Mock - XXTagDef xXTagDef; + @Mock + XXTagDef xXTagDef; - @Mock - XXTagAttributeDao xXTagAttributeDao; + @Mock + XXTagAttributeDao xXTagAttributeDao; - @Mock - XXTagDao xXTagDao; + @Mock + XXTagDao xXTagDao; - @Mock + @Mock XXServiceResourceDao xxServiceResourceDao; - @Mock - XXServiceResource xxServiceResource; - - @Test - public void test1postUpdate() { - Mockito.when(daoMgr.getXXPortalUser()).thenReturn(xXPortalUserDao); - Mockito.when(daoMgr.getXXTagDef()).thenReturn(xXTagDefDao); - Mockito.when(xXTagDefDao.getById(xXTag.getType())).thenReturn(xXTagDef); - Mockito.when(daoMgr.getXXServiceVersionInfo()).thenReturn(xXServiceVersionInfoDao); - rangerTagService.postUpdate(xXTag); - - } - - @Test - public void test2GetPopulatedViewObject() { - Mockito.when(daoMgr.getXXPortalUser()).thenReturn(xXPortalUserDao); - Mockito.when(daoMgr.getXXTagDef()).thenReturn(xXTagDefDao); - XXTag xXTag = createXXTag(); - Mockito.when(xXTagDefDao.getById(1L)).thenReturn(xXTagDef); - rangerTagService.getPopulatedViewObject(xXTag); - - } - - @Test - public void test3GetTagByGuid() { - Mockito.when(daoMgr.getXXTag()).thenReturn(xXTagDao); - rangerTagService.getTagByGuid("1"); - - } - - @Test - public void test4GetTagsByType() { - Mockito.when(daoMgr.getXXTag()).thenReturn(xXTagDao); - rangerTagService.getTagsByType("testTagName"); - - } - - @Test - public void test5GetTagsForResourceId() { - Mockito.when(daoMgr.getXXServiceResource()).thenReturn(xxServiceResourceDao); - Mockito.when(xxServiceResourceDao.getById(1L)).thenReturn(xxServiceResource); - - rangerTagService.getTagsForResourceId(1L); - - } - - @Test - public void test6GetTagsForResourceGuid() { - Mockito.when(daoMgr.getXXServiceResource()).thenReturn(xxServiceResourceDao); - Mockito.when(xxServiceResourceDao.findByGuid("1")).thenReturn(xxServiceResource); - rangerTagService.getTagsForResourceGuid("1"); - - } - - @Test - public void test7getTagsByServiceId() { - Mockito.when(daoMgr.getXXTag()).thenReturn(xXTagDao); - rangerTagService.getTagsByServiceId(1L); - } - - private XXTag createXXTag() { - XXTag xXTag = new XXTag(); - xXTag.setAddedByUserId(1L); - Date date = new Date(); - xXTag.setCreateTime(date); - xXTag.setGuid("1"); - xXTag.setType(1L); - xXTag.setUpdatedByUserId(1L); - xXTag.setVersion(1L); - xXTag.setId(1L); - return xXTag; - } + @Mock + XXServiceResource xxServiceResource; + + @Test + public void test1postUpdate() { + Mockito.when(daoMgr.getXXPortalUser()).thenReturn(xXPortalUserDao); + Mockito.when(daoMgr.getXXTagDef()).thenReturn(xXTagDefDao); + Mockito.when(xXTagDefDao.getById(xXTag.getType())).thenReturn(xXTagDef); + Mockito.when(daoMgr.getXXServiceVersionInfo()).thenReturn(xXServiceVersionInfoDao); + rangerTagService.postUpdate(xXTag); + } + + @Test + public void test2GetPopulatedViewObject() { + Mockito.when(daoMgr.getXXPortalUser()).thenReturn(xXPortalUserDao); + Mockito.when(daoMgr.getXXTagDef()).thenReturn(xXTagDefDao); + XXTag xXTag = createXXTag(); + Mockito.when(xXTagDefDao.getById(1L)).thenReturn(xXTagDef); + rangerTagService.getPopulatedViewObject(xXTag); + } + + @Test + public void test3GetTagByGuid() { + Mockito.when(daoMgr.getXXTag()).thenReturn(xXTagDao); + rangerTagService.getTagByGuid("1"); + } + + @Test + public void test4GetTagsByType() { + Mockito.when(daoMgr.getXXTag()).thenReturn(xXTagDao); + rangerTagService.getTagsByType("testTagName"); + } + + @Test + public void test5GetTagsForResourceId() { + Mockito.when(daoMgr.getXXServiceResource()).thenReturn(xxServiceResourceDao); + Mockito.when(xxServiceResourceDao.getById(1L)).thenReturn(xxServiceResource); + + rangerTagService.getTagsForResourceId(1L); + } + + @Test + public void test6GetTagsForResourceGuid() { + Mockito.when(daoMgr.getXXServiceResource()).thenReturn(xxServiceResourceDao); + Mockito.when(xxServiceResourceDao.findByGuid("1")).thenReturn(xxServiceResource); + rangerTagService.getTagsForResourceGuid("1"); + } + + @Test + public void test7getTagsByServiceId() { + Mockito.when(daoMgr.getXXTag()).thenReturn(xXTagDao); + rangerTagService.getTagsByServiceId(1L); + } + + private XXTag createXXTag() { + XXTag xXTag = new XXTag(); + xXTag.setAddedByUserId(1L); + Date date = new Date(); + xXTag.setCreateTime(date); + xXTag.setGuid("1"); + xXTag.setType(1L); + xXTag.setUpdatedByUserId(1L); + xXTag.setVersion(1L); + xXTag.setId(1L); + return xXTag; + } } diff --git a/security-admin/src/test/java/org/apache/ranger/service/TestRangerTransactionService.java b/security-admin/src/test/java/org/apache/ranger/service/TestRangerTransactionService.java index 283544f54b..dc4746b005 100644 --- a/security-admin/src/test/java/org/apache/ranger/service/TestRangerTransactionService.java +++ b/security-admin/src/test/java/org/apache/ranger/service/TestRangerTransactionService.java @@ -18,8 +18,6 @@ */ package org.apache.ranger.service; -import java.util.concurrent.ScheduledExecutorService; - import org.junit.FixMethodOrder; import org.junit.Test; import org.junit.runner.RunWith; @@ -28,34 +26,32 @@ import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; +import java.util.concurrent.ScheduledExecutorService; + @RunWith(MockitoJUnitRunner.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class TestRangerTransactionService { + @InjectMocks + RangerTransactionService rangerTransactionService; - @InjectMocks - RangerTransactionService rangerTransactionService; - - @Mock - ScheduledExecutorService scheduler; - - @Mock - Runnable task; - - @Test - public void test1Init() { - rangerTransactionService.init(); - - } + @Mock + ScheduledExecutorService scheduler; - @Test - public void test2Destroy() { - rangerTransactionService.destroy(); + @Mock + Runnable task; - } + @Test + public void test1Init() { + rangerTransactionService.init(); + } - @Test - public void test3ExecuteAfterTransactionComplete() { - rangerTransactionService.scheduleToExecuteInOwnTransaction(task, 1000L); + @Test + public void test2Destroy() { + rangerTransactionService.destroy(); + } - } + @Test + public void test3ExecuteAfterTransactionComplete() { + rangerTransactionService.scheduleToExecuteInOwnTransaction(task, 1000L); + } } diff --git a/security-admin/src/test/java/org/apache/ranger/service/TestUserService.java b/security-admin/src/test/java/org/apache/ranger/service/TestUserService.java index c48739b945..4818997faf 100644 --- a/security-admin/src/test/java/org/apache/ranger/service/TestUserService.java +++ b/security-admin/src/test/java/org/apache/ranger/service/TestUserService.java @@ -34,30 +34,29 @@ @RunWith(MockitoJUnitRunner.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class TestUserService { + @InjectMocks + UserService userService; - @InjectMocks - UserService userService; + @Mock + XXPortalUser xXPortalUser; - @Mock - XXPortalUser xXPortalUser; + @Mock + VXPortalUser vXPortalUser; - @Mock - VXPortalUser vXPortalUser; + @Mock + RangerDaoManager daoManager; - @Mock - RangerDaoManager daoManager; + @Mock + XXPortalUserRoleDao xXPortalUserRoleDao; - @Mock - XXPortalUserRoleDao xXPortalUserRoleDao; + @Test + public void test1GetInstance() { + UserService.getInstance(); + } - @Test - public void test1GetInstance() { - userService.getInstance(); - } - - @Test - public void test2GjUserToUserProfile() { - Mockito.when(daoManager.getXXPortalUserRole()).thenReturn(xXPortalUserRoleDao); - userService.gjUserToUserProfile(xXPortalUser, vXPortalUser); - } + @Test + public void test2GjUserToUserProfile() { + Mockito.when(daoManager.getXXPortalUserRole()).thenReturn(xXPortalUserRoleDao); + userService.gjUserToUserProfile(xXPortalUser, vXPortalUser); + } } diff --git a/security-admin/src/test/java/org/apache/ranger/service/TestXAccessAuditService.java b/security-admin/src/test/java/org/apache/ranger/service/TestXAccessAuditService.java index 877110bfd5..c166b207bc 100644 --- a/security-admin/src/test/java/org/apache/ranger/service/TestXAccessAuditService.java +++ b/security-admin/src/test/java/org/apache/ranger/service/TestXAccessAuditService.java @@ -18,9 +18,6 @@ */ package org.apache.ranger.service; -import javax.persistence.EntityManager; -import javax.persistence.Query; - import org.apache.ranger.common.SearchCriteria; import org.apache.ranger.common.SearchField; import org.apache.ranger.common.SearchUtil; @@ -40,73 +37,73 @@ import org.mockito.Mockito; import org.mockito.junit.MockitoJUnitRunner; +import javax.persistence.EntityManager; +import javax.persistence.Query; + @RunWith(MockitoJUnitRunner.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class TestXAccessAuditService { + @InjectMocks + XAccessAuditService xAccessAuditService; - @InjectMocks - XAccessAuditService xAccessAuditService; - - @Mock - SearchCriteria searchCriteria; - - @Mock - SearchUtil searchUtil; - - @Mock - SortField sortField; + @Mock + SearchCriteria searchCriteria; - @Mock - SearchField searchField; + @Mock + SearchUtil searchUtil; - @Mock - BaseDao entityDao; + @Mock + SortField sortField; - @Mock - Query query; + @Mock + SearchField searchField; - @Mock - VList vList; + @Mock + BaseDao entityDao; - @Mock - XXAccessAudit xXAccessAudit; + @Mock + Query query; - @Mock - VXAccessAuditList vXAccessAuditList; + @Mock + VList vList; - @Mock - EntityManager em; + @Mock + XXAccessAudit xXAccessAudit; - @Mock - RangerDaoManager daoManager; + @Mock + VXAccessAuditList vXAccessAuditList; - @Mock - XXServiceDao xXServiceDao; + @Mock + EntityManager em; - @Test - public void test1SearchXAccessAudits() { - SearchCriteria testSearchCriteria = createsearchCriteria(); - xAccessAuditService.searchXAccessAudits(testSearchCriteria); + @Mock + RangerDaoManager daoManager; - } + @Mock + XXServiceDao xXServiceDao; - @Test - public void test2PopulateViewBean() { - Mockito.when(daoManager.getXXService()).thenReturn(xXServiceDao); - xAccessAuditService.populateViewBean(xXAccessAudit); + @Test + public void test1SearchXAccessAudits() { + SearchCriteria testSearchCriteria = createsearchCriteria(); + xAccessAuditService.searchXAccessAudits(testSearchCriteria); + } - } + @Test + public void test2PopulateViewBean() { + Mockito.when(daoManager.getXXService()).thenReturn(xXServiceDao); + xAccessAuditService.populateViewBean(xXAccessAudit); + } - private SearchCriteria createsearchCriteria() { - SearchCriteria testsearchCriteria = new SearchCriteria(); - testsearchCriteria.setStartIndex(0); - testsearchCriteria.setMaxRows(Integer.MAX_VALUE); - testsearchCriteria.setSortBy("id"); - testsearchCriteria.setSortType("asc"); - testsearchCriteria.setGetCount(true); - testsearchCriteria.setOwnerId(null); - testsearchCriteria.setGetChildren(false); - testsearchCriteria.setDistinct(false); - return testsearchCriteria; - } + private SearchCriteria createsearchCriteria() { + SearchCriteria testsearchCriteria = new SearchCriteria(); + testsearchCriteria.setStartIndex(0); + testsearchCriteria.setMaxRows(Integer.MAX_VALUE); + testsearchCriteria.setSortBy("id"); + testsearchCriteria.setSortType("asc"); + testsearchCriteria.setGetCount(true); + testsearchCriteria.setOwnerId(null); + testsearchCriteria.setGetChildren(false); + testsearchCriteria.setDistinct(false); + return testsearchCriteria; + } } diff --git a/security-admin/src/test/java/org/apache/ranger/service/TestXAssetService.java b/security-admin/src/test/java/org/apache/ranger/service/TestXAssetService.java index cdac6cce6c..ff6e850d02 100644 --- a/security-admin/src/test/java/org/apache/ranger/service/TestXAssetService.java +++ b/security-admin/src/test/java/org/apache/ranger/service/TestXAssetService.java @@ -19,8 +19,6 @@ package org.apache.ranger.service; -import java.util.Date; - import org.apache.ranger.biz.RangerBizUtil; import org.apache.ranger.common.JSONUtil; import org.apache.ranger.entity.XXAsset; @@ -34,75 +32,74 @@ import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; -import static org.apache.ranger.service.RangerBaseModelService.OPERATION_UPDATE_CONTEXT; +import java.util.Date; + import static org.apache.ranger.service.RangerBaseModelService.OPERATION_DELETE_CONTEXT; +import static org.apache.ranger.service.RangerBaseModelService.OPERATION_UPDATE_CONTEXT; @RunWith(MockitoJUnitRunner.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class TestXAssetService { - - @InjectMocks - XAssetService xAssetService; - - @Mock - VXAsset vXAsset; - - @Mock - XXAsset xXAsset; - - @Mock - RangerEnumUtil xaEnumUtil; - - @Mock - JSONUtil jsonUtil; - - @Mock - RangerBizUtil bizUtil; - - @Test - public void test1ValidateConfig() { - xAssetService.validateConfig(vXAsset); - } - - @Test - public void test2GetTransactionLog() { - xAssetService.createTransactionLog(vXAsset, null, OPERATION_UPDATE_CONTEXT); - } - - @Test - public void test3GetTransactionLog() { - VXAsset vXAsset = new VXAsset(); - VXAsset xXAsset = createXXAssetObject(); - - xAssetService.createTransactionLog(vXAsset, xXAsset, OPERATION_DELETE_CONTEXT); - } - - @Test - public void test4GetConfigWithEncryptedPassword() { - xAssetService.getConfigWithEncryptedPassword("testconfig", false); - - } - - @Test - public void test5GetConfigWithDecryptedPassword() { - xAssetService.getConfigWithDecryptedPassword("testConfig"); - - } - - public VXAsset createXXAssetObject() { - VXAsset xXAsset = new VXAsset(); - xXAsset.setId(1L); - xXAsset.setAssetType(1); - xXAsset.setName("testName"); - xXAsset.setConfig("testconfig"); - xXAsset.setActiveStatus(1); - xXAsset.setOwner("admin"); - xXAsset.setSupportNative(true); - xXAsset.setUpdatedBy("admin"); - Date date = new Date(); - xXAsset.setCreateDate(date); - xXAsset.setUpdateDate(date); - xXAsset.setDescription("this is test description"); - return xXAsset; - } + @InjectMocks + XAssetService xAssetService; + + @Mock + VXAsset vXAsset; + + @Mock + XXAsset xXAsset; + + @Mock + RangerEnumUtil xaEnumUtil; + + @Mock + JSONUtil jsonUtil; + + @Mock + RangerBizUtil bizUtil; + + @Test + public void test1ValidateConfig() { + xAssetService.validateConfig(vXAsset); + } + + @Test + public void test2GetTransactionLog() { + xAssetService.createTransactionLog(vXAsset, null, OPERATION_UPDATE_CONTEXT); + } + + @Test + public void test3GetTransactionLog() { + VXAsset vXAsset = new VXAsset(); + VXAsset xXAsset = createXXAssetObject(); + + xAssetService.createTransactionLog(vXAsset, xXAsset, OPERATION_DELETE_CONTEXT); + } + + @Test + public void test4GetConfigWithEncryptedPassword() { + xAssetService.getConfigWithEncryptedPassword("testconfig", false); + } + + @Test + public void test5GetConfigWithDecryptedPassword() { + xAssetService.getConfigWithDecryptedPassword("testConfig"); + } + + public VXAsset createXXAssetObject() { + VXAsset xXAsset = new VXAsset(); + xXAsset.setId(1L); + xXAsset.setAssetType(1); + xXAsset.setName("testName"); + xXAsset.setConfig("testconfig"); + xXAsset.setActiveStatus(1); + xXAsset.setOwner("admin"); + xXAsset.setSupportNative(true); + xXAsset.setUpdatedBy("admin"); + Date date = new Date(); + xXAsset.setCreateDate(date); + xXAsset.setUpdateDate(date); + xXAsset.setDescription("this is test description"); + return xXAsset; + } } diff --git a/security-admin/src/test/java/org/apache/ranger/service/TestXAuditMapService.java b/security-admin/src/test/java/org/apache/ranger/service/TestXAuditMapService.java index a843502d67..4285ebe262 100644 --- a/security-admin/src/test/java/org/apache/ranger/service/TestXAuditMapService.java +++ b/security-admin/src/test/java/org/apache/ranger/service/TestXAuditMapService.java @@ -20,6 +20,7 @@ package org.apache.ranger.service; import org.apache.ranger.biz.RangerBizUtil; +import org.apache.ranger.view.VXAuditMap; import org.junit.FixMethodOrder; import org.junit.Test; import org.junit.runner.RunWith; @@ -27,29 +28,28 @@ import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; -import org.apache.ranger.view.VXAuditMap; import static org.apache.ranger.service.RangerBaseModelService.OPERATION_DELETE_CONTEXT; @RunWith(MockitoJUnitRunner.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class TestXAuditMapService { - @InjectMocks - XAuditMapService XAuditMapService; + @InjectMocks + XAuditMapService xAuditMapService; - @Mock - VXAuditMap vXAuditMap; + @Mock + VXAuditMap vXAuditMap; - @Mock - RangerBizUtil bizUtil; + @Mock + RangerBizUtil bizUtil; - @Test - public void test1GetTransactionLog() { - XAuditMapService.createTransactionLog(vXAuditMap, null, OPERATION_DELETE_CONTEXT); - } + @Test + public void test1GetTransactionLog() { + xAuditMapService.createTransactionLog(vXAuditMap, null, OPERATION_DELETE_CONTEXT); + } - @Test - public void test2GetTransactionLog() { - XAuditMapService.createTransactionLog(vXAuditMap, vXAuditMap, OPERATION_DELETE_CONTEXT); - } + @Test + public void test2GetTransactionLog() { + xAuditMapService.createTransactionLog(vXAuditMap, vXAuditMap, OPERATION_DELETE_CONTEXT); + } } diff --git a/security-admin/src/test/java/org/apache/ranger/service/TestXGroupPermissionService.java b/security-admin/src/test/java/org/apache/ranger/service/TestXGroupPermissionService.java index e2e9e2e018..b00480cb38 100644 --- a/security-admin/src/test/java/org/apache/ranger/service/TestXGroupPermissionService.java +++ b/security-admin/src/test/java/org/apache/ranger/service/TestXGroupPermissionService.java @@ -19,9 +19,9 @@ package org.apache.ranger.service; +import org.apache.ranger.entity.XXGroup; import org.apache.ranger.entity.XXGroupPermission; import org.apache.ranger.view.VXModuleDef; - import org.junit.FixMethodOrder; import org.junit.Test; import org.junit.runner.RunWith; @@ -34,35 +34,31 @@ import java.util.List; import java.util.Map; -import org.apache.ranger.entity.XXGroup; - @RunWith(MockitoJUnitRunner.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class TestXGroupPermissionService { - @Mock - XGroupPermissionService xGroupPermissionService; - - @Mock - XXGroupPermission xXGroupPermission; - - @Mock - XXGroup XXGroup; + @Mock + XGroupPermissionService xGroupPermissionService; - @Mock - VXModuleDef vXModuleDef; + @Mock + XXGroupPermission xXGroupPermission; - @Test - public void test1PopulateViewBean() { - xGroupPermissionService.populateViewBean(xXGroupPermission); + @Mock + XXGroup xxGroup; - } + @Mock + VXModuleDef vXModuleDef; - @Test - public void test2GetPopulatedVXGroupPermissionList() { - List xgroupPermissionList = new ArrayList(); - Map xXGroupNameMap = new HashMap(); - xXGroupNameMap.put(XXGroup.getId(), XXGroup.getName()); - xGroupPermissionService.getPopulatedVXGroupPermissionList(xgroupPermissionList, xXGroupNameMap, vXModuleDef); + @Test + public void test1PopulateViewBean() { + xGroupPermissionService.populateViewBean(xXGroupPermission); + } - } + @Test + public void test2GetPopulatedVXGroupPermissionList() { + List xgroupPermissionList = new ArrayList<>(); + Map xXGroupNameMap = new HashMap<>(); + xXGroupNameMap.put(xxGroup.getId(), xxGroup.getName()); + xGroupPermissionService.getPopulatedVXGroupPermissionList(xgroupPermissionList, xXGroupNameMap, vXModuleDef); + } } diff --git a/security-admin/src/test/java/org/apache/ranger/service/TestXGroupService.java b/security-admin/src/test/java/org/apache/ranger/service/TestXGroupService.java index 33cee3cf2a..9b0fdb6bb0 100644 --- a/security-admin/src/test/java/org/apache/ranger/service/TestXGroupService.java +++ b/security-admin/src/test/java/org/apache/ranger/service/TestXGroupService.java @@ -19,9 +19,16 @@ package org.apache.ranger.service; import org.apache.ranger.biz.RangerBizUtil; +import org.apache.ranger.common.StringUtil; +import org.apache.ranger.common.db.BaseDao; import org.apache.ranger.db.RangerDaoManager; import org.apache.ranger.db.XXGroupDao; import org.apache.ranger.db.XXPortalUserDao; +import org.apache.ranger.entity.XXDBBase; +import org.apache.ranger.entity.XXGroup; +import org.apache.ranger.entity.XXPortalUser; +import org.apache.ranger.util.RangerEnumUtil; +import org.apache.ranger.view.VXGroup; import org.junit.FixMethodOrder; import org.junit.Test; import org.junit.runner.RunWith; @@ -30,139 +37,129 @@ import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.junit.MockitoJUnitRunner; -import org.apache.ranger.entity.XXDBBase; -import org.apache.ranger.entity.XXGroup; -import org.apache.ranger.entity.XXPortalUser; -import org.apache.ranger.util.RangerEnumUtil; -import org.apache.ranger.view.VXGroup; import java.util.Date; -import org.apache.ranger.common.StringUtil; -import org.apache.ranger.common.db.BaseDao; - import static org.apache.ranger.service.RangerBaseModelService.OPERATION_CREATE_CONTEXT; import static org.apache.ranger.service.RangerBaseModelService.OPERATION_UPDATE_CONTEXT; @RunWith(MockitoJUnitRunner.Silent.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class TestXGroupService { - - @InjectMocks - XGroupService XGroupService; - - @Mock - RangerDaoManager daoManager; - - @Mock - XXGroupDao xXGroupDao; - - @Mock - XXGroup resource; - - @Mock - VXGroup vxGroup; - - @Mock - XXPortalUserDao xXPortalUserDao; - - @Mock - BaseDao entityDao; - - @Mock - XXDBBase xXDBBase; - - @Mock - XXPortalUser tUser; - - @Mock - RangerEnumUtil xaEnumUtil; - - @Mock - StringUtil stringUtil; - - @Mock - RangerBizUtil bizUtil; - - @Mock - AbstractBaseResourceService abstractBaseResourceService; - - @Test - public void test1GetGroupByGroupName() { - Mockito.when(daoManager.getXXGroup()).thenReturn(xXGroupDao); - XXGroup xxGroup = createXXGroup(); - Mockito.when(xXGroupDao.findByGroupName(xxGroup.getName())).thenReturn(xxGroup); - Mockito.when(daoManager.getXXPortalUser()).thenReturn(xXPortalUserDao); - Mockito.when(xXPortalUserDao.getById(xxGroup.getAddedByUserId())).thenReturn(tUser); - XGroupService.getGroupByGroupName(xxGroup.getName()); - } - - @Test - public void test2CreateXGroupWithOutLogin() { - VXGroup vxGroup = createvXGroup(); - Mockito.when(daoManager.getXXGroup()).thenReturn(xXGroupDao); - XXGroup resource = createXXGroup(); - Mockito.when(xXGroupDao.findByGroupName(vxGroup.getName())).thenReturn(resource); - Mockito.when(daoManager.getXXPortalUser()).thenReturn(xXPortalUserDao); - Mockito.when(xXPortalUserDao.getById(1l)).thenReturn(tUser); - Mockito.when(entityDao.update(resource)).thenReturn(resource); - XGroupService.createXGroupWithOutLogin(vxGroup); - } - - @Test - public void test3ReadResourceWithOutLogin() { - XXGroup resource = createXXGroup(); - Mockito.when(entityDao.getById(resource.getId())).thenReturn(resource); - Mockito.when(daoManager.getXXPortalUser()).thenReturn(xXPortalUserDao); - Mockito.when(xXPortalUserDao.getById(resource.getAddedByUserId())).thenReturn(tUser); - XGroupService.readResourceWithOutLogin(resource.getId()); - } - - @Test - public void test4GetTransactionLog() { - VXGroup vObj = createvXGroup(); - XGroupService.createTransactionLog(vObj, null, OPERATION_UPDATE_CONTEXT); - } - - @Test - public void test5GetTransactionLog() { - VXGroup vObj = createvXGroup(); - - XGroupService.createTransactionLog(vObj, null, OPERATION_CREATE_CONTEXT); - } - - public VXGroup createvXGroup() { - VXGroup vXGroup = new VXGroup(); - Date date = new Date(); - vXGroup.setCreateDate(date); - vXGroup.setCredStoreId(1L); - vXGroup.setDescription("this is test description"); - vXGroup.setGroupSource(0); - vXGroup.setGroupType(1); - vXGroup.setId(1L); - vXGroup.setIsVisible(1); - vXGroup.setName("testGroup"); - vXGroup.setMObj(xXDBBase); - vXGroup.setOwner("admin"); - vXGroup.setUpdateDate(date); - vXGroup.setUpdatedBy("admin"); - return vXGroup; - } - - private XXGroup createXXGroup() { - XXGroup xXGroup = new XXGroup(); - Date date = new Date(); - xXGroup.setAddedByUserId(1L); - xXGroup.setCreateTime(date); - xXGroup.setCredStoreId(1L); - xXGroup.setDescription("this is test description"); - xXGroup.setGroupSource(0); - xXGroup.setGroupType(1); - xXGroup.setId(1L); - xXGroup.setIsVisible(1); - xXGroup.setName("testGroup"); - xXGroup.setUpdateTime(date); - return xXGroup; - } - + @InjectMocks + XGroupService xGroupService; + + @Mock + RangerDaoManager daoManager; + + @Mock + XXGroupDao xXGroupDao; + + @Mock + XXGroup resource; + + @Mock + VXGroup vxGroup; + + @Mock + XXPortalUserDao xXPortalUserDao; + + @Mock + BaseDao entityDao; + + @Mock + XXDBBase xXDBBase; + + @Mock + XXPortalUser tUser; + + @Mock + RangerEnumUtil xaEnumUtil; + + @Mock + StringUtil stringUtil; + + @Mock + RangerBizUtil bizUtil; + + @Mock + AbstractBaseResourceService abstractBaseResourceService; + + @Test + public void test1GetGroupByGroupName() { + Mockito.when(daoManager.getXXGroup()).thenReturn(xXGroupDao); + XXGroup xxGroup = createXXGroup(); + Mockito.when(xXGroupDao.findByGroupName(xxGroup.getName())).thenReturn(xxGroup); + Mockito.when(daoManager.getXXPortalUser()).thenReturn(xXPortalUserDao); + Mockito.when(xXPortalUserDao.getById(xxGroup.getAddedByUserId())).thenReturn(tUser); + xGroupService.getGroupByGroupName(xxGroup.getName()); + } + + @Test + public void test2CreateXGroupWithOutLogin() { + VXGroup vxGroup = createvXGroup(); + Mockito.when(daoManager.getXXGroup()).thenReturn(xXGroupDao); + XXGroup resource = createXXGroup(); + Mockito.when(xXGroupDao.findByGroupName(vxGroup.getName())).thenReturn(resource); + Mockito.when(daoManager.getXXPortalUser()).thenReturn(xXPortalUserDao); + Mockito.when(xXPortalUserDao.getById(1L)).thenReturn(tUser); + Mockito.when(entityDao.update(resource)).thenReturn(resource); + xGroupService.createXGroupWithOutLogin(vxGroup); + } + + @Test + public void test3ReadResourceWithOutLogin() { + XXGroup resource = createXXGroup(); + Mockito.when(entityDao.getById(resource.getId())).thenReturn(resource); + Mockito.when(daoManager.getXXPortalUser()).thenReturn(xXPortalUserDao); + Mockito.when(xXPortalUserDao.getById(resource.getAddedByUserId())).thenReturn(tUser); + xGroupService.readResourceWithOutLogin(resource.getId()); + } + + @Test + public void test4GetTransactionLog() { + VXGroup vObj = createvXGroup(); + xGroupService.createTransactionLog(vObj, null, OPERATION_UPDATE_CONTEXT); + } + + @Test + public void test5GetTransactionLog() { + VXGroup vObj = createvXGroup(); + + xGroupService.createTransactionLog(vObj, null, OPERATION_CREATE_CONTEXT); + } + + public VXGroup createvXGroup() { + VXGroup vXGroup = new VXGroup(); + Date date = new Date(); + vXGroup.setCreateDate(date); + vXGroup.setCredStoreId(1L); + vXGroup.setDescription("this is test description"); + vXGroup.setGroupSource(0); + vXGroup.setGroupType(1); + vXGroup.setId(1L); + vXGroup.setIsVisible(1); + vXGroup.setName("testGroup"); + vXGroup.setMObj(xXDBBase); + vXGroup.setOwner("admin"); + vXGroup.setUpdateDate(date); + vXGroup.setUpdatedBy("admin"); + return vXGroup; + } + + private XXGroup createXXGroup() { + XXGroup xXGroup = new XXGroup(); + Date date = new Date(); + xXGroup.setAddedByUserId(1L); + xXGroup.setCreateTime(date); + xXGroup.setCredStoreId(1L); + xXGroup.setDescription("this is test description"); + xXGroup.setGroupSource(0); + xXGroup.setGroupType(1); + xXGroup.setId(1L); + xXGroup.setIsVisible(1); + xXGroup.setName("testGroup"); + xXGroup.setUpdateTime(date); + return xXGroup; + } } diff --git a/security-admin/src/test/java/org/apache/ranger/service/TestXGroupUserService.java b/security-admin/src/test/java/org/apache/ranger/service/TestXGroupUserService.java index f7b9139396..91dbaed2ea 100644 --- a/security-admin/src/test/java/org/apache/ranger/service/TestXGroupUserService.java +++ b/security-admin/src/test/java/org/apache/ranger/service/TestXGroupUserService.java @@ -18,8 +18,6 @@ */ package org.apache.ranger.service; -import java.util.Date; - import org.apache.ranger.biz.RangerBizUtil; import org.apache.ranger.common.db.BaseDao; import org.apache.ranger.db.RangerDaoManager; @@ -42,156 +40,154 @@ import org.mockito.Mockito; import org.mockito.junit.MockitoJUnitRunner; +import java.util.Date; + import static org.apache.ranger.service.RangerBaseModelService.OPERATION_CREATE_CONTEXT; @RunWith(MockitoJUnitRunner.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class TestXGroupUserService { - - @InjectMocks - XGroupUserService xGroupUserService; - - @Mock - VXGroupUser vxGroupUser; - - @Mock - RangerDaoManager daoManager; - - @Mock - XXGroupUserDao xXGroupUserDao; - - @Mock - XXGroupUser xXGroupUser; - - @Mock - XXGroupDao xXGroupDao; - - @Mock - XXGroup xXGroup; - - @Mock - XXDBBase gjObj; - - @Mock - XXPortalUserDao xXPortalUserDao; - - @Mock - XXPortalUser tUser; - - @Mock - BaseDao entityDao; - - @Mock - XXUserDao xXUserDao; - - @Mock - RangerBizUtil bizUtil; - - @Mock - AbstractBaseResourceService abstractBaseResourceService; - - @Test - public void test1CreateXGroupUserWithOutLogin() { - XXGroupUser resource = createXXGroupUser(); - Mockito.when(daoManager.getXXGroupUser()).thenReturn(xXGroupUserDao); - Mockito.when(xXGroupUserDao.findByGroupNameAndUserId(resource.getName(), resource.getId())) - .thenReturn(resource); - Mockito.when(daoManager.getXXGroup()).thenReturn(xXGroupDao); - XXGroup xGroup = createXXGroup(); - VXGroupUser vxGroupUser = createVXGroupUser(); - Mockito.when(xXGroupDao.findByGroupName(vxGroupUser.getName())).thenReturn(xGroup); - Mockito.when(daoManager.getXXPortalUser()).thenReturn(xXPortalUserDao); - Mockito.when(xXPortalUserDao.getById(vxGroupUser.getId())).thenReturn(tUser); - Mockito.when(entityDao.update(resource)).thenReturn(resource); - xGroupUserService.createXGroupUserWithOutLogin(vxGroupUser); - - } - - @Test - public void test2GetTransactionLog() { - VXGroupUser vXGroupUser = createVXGroupUser(); - Mockito.when(daoManager.getXXGroup()).thenReturn(xXGroupDao); - XXGroup xGroup = createXXGroup(); - Mockito.when(xXGroupDao.getById(1L)).thenReturn(xGroup); - Mockito.when(daoManager.getXXUser()).thenReturn(xXUserDao); - XXUser xUser = createXXUser(); - Mockito.when(xXUserDao.getById(1L)).thenReturn(xUser); - xGroupUserService.createTransactionLog(vXGroupUser, null, OPERATION_CREATE_CONTEXT); - } - - @Test - public void test3GetTransactionLog() { - VXGroupUser vObj = createVXGroupUser(); - Mockito.when(daoManager.getXXGroup()).thenReturn(xXGroupDao); - XXGroup xGroup = createXXGroup(); - Mockito.when(xXGroupDao.getById(1L)).thenReturn(xGroup); - Mockito.when(daoManager.getXXUser()).thenReturn(xXUserDao); - XXUser xUser = createXXUser(); - Mockito.when(xXUserDao.getById(1L)).thenReturn(xUser); - xGroupUserService.createTransactionLog(vObj, null, OPERATION_CREATE_CONTEXT); - } - - private XXGroup createXXGroup() { - XXGroup xXGroup = new XXGroup(); - Date date = new Date(); - xXGroup.setAddedByUserId(1L); - xXGroup.setCreateTime(date); - xXGroup.setCredStoreId(1L); - xXGroup.setDescription("this is test description"); - xXGroup.setGroupSource(0); - xXGroup.setGroupType(1); - xXGroup.setId(1L); - xXGroup.setIsVisible(1); - xXGroup.setName("testName"); - xXGroup.setUpdateTime(date); - - return xXGroup; - } - - private VXGroupUser createVXGroupUser() { - VXGroupUser vxGroupUser = new VXGroupUser(); - Date date = new Date(); - vxGroupUser.setCreateDate(date); - vxGroupUser.setId(1l); - vxGroupUser.setMObj(gjObj); - vxGroupUser.setName("testGroupUser"); - vxGroupUser.setOwner("admin"); - vxGroupUser.setParentGroupId(1L); - vxGroupUser.setUpdateDate(date); - vxGroupUser.setUpdatedBy("admin"); - vxGroupUser.setUserId(1L); - return vxGroupUser; - } - - private XXGroupUser createXXGroupUser() { - XXGroupUser xXGroupUser = new XXGroupUser(); - xXGroupUser.setAddedByUserId(1L); - Date date = new Date(); - xXGroupUser.setCreateTime(date); - xXGroupUser.setId(1L); - xXGroupUser.setName("testGroupUser"); - xXGroupUser.setParentGroupId(1L); - xXGroupUser.setUpdatedByUserId(1L); - xXGroupUser.setUpdateTime(date); - xXGroupUser.setUserId(1L); - return xXGroupUser; - - } - - private XXUser createXXUser() { - XXUser xUser = new XXUser(); - xUser.setAddedByUserId(1L); - Date date = new Date(); - xUser.setCreateTime(date); - xUser.setCredStoreId(1L); - xUser.setDescription("this is test xUser"); - xUser.setId(1L); - xUser.setIsVisible(1); - xUser.setName("testUser"); - xUser.setStatus(1); - xUser.setUpdatedByUserId(1L); - xUser.setUpdateTime(date); - return xUser; - - } + @InjectMocks + XGroupUserService xGroupUserService; + + @Mock + VXGroupUser vxGroupUser; + + @Mock + RangerDaoManager daoManager; + + @Mock + XXGroupUserDao xXGroupUserDao; + + @Mock + XXGroupUser xXGroupUser; + + @Mock + XXGroupDao xXGroupDao; + + @Mock + XXGroup xXGroup; + + @Mock + XXDBBase gjObj; + + @Mock + XXPortalUserDao xXPortalUserDao; + + @Mock + XXPortalUser tUser; + + @Mock + BaseDao entityDao; + + @Mock + XXUserDao xXUserDao; + + @Mock + RangerBizUtil bizUtil; + + @Mock + AbstractBaseResourceService abstractBaseResourceService; + + @Test + public void test1CreateXGroupUserWithOutLogin() { + XXGroupUser resource = createXXGroupUser(); + Mockito.when(daoManager.getXXGroupUser()).thenReturn(xXGroupUserDao); + Mockito.when(xXGroupUserDao.findByGroupNameAndUserId(resource.getName(), resource.getId())) + .thenReturn(resource); + Mockito.when(daoManager.getXXGroup()).thenReturn(xXGroupDao); + XXGroup xGroup = createXXGroup(); + VXGroupUser vxGroupUser = createVXGroupUser(); + Mockito.when(xXGroupDao.findByGroupName(vxGroupUser.getName())).thenReturn(xGroup); + Mockito.when(daoManager.getXXPortalUser()).thenReturn(xXPortalUserDao); + Mockito.when(xXPortalUserDao.getById(vxGroupUser.getId())).thenReturn(tUser); + Mockito.when(entityDao.update(resource)).thenReturn(resource); + xGroupUserService.createXGroupUserWithOutLogin(vxGroupUser); + } + + @Test + public void test2GetTransactionLog() { + VXGroupUser vXGroupUser = createVXGroupUser(); + Mockito.when(daoManager.getXXGroup()).thenReturn(xXGroupDao); + XXGroup xGroup = createXXGroup(); + Mockito.when(xXGroupDao.getById(1L)).thenReturn(xGroup); + Mockito.when(daoManager.getXXUser()).thenReturn(xXUserDao); + XXUser xUser = createXXUser(); + Mockito.when(xXUserDao.getById(1L)).thenReturn(xUser); + xGroupUserService.createTransactionLog(vXGroupUser, null, OPERATION_CREATE_CONTEXT); + } + + @Test + public void test3GetTransactionLog() { + VXGroupUser vObj = createVXGroupUser(); + Mockito.when(daoManager.getXXGroup()).thenReturn(xXGroupDao); + XXGroup xGroup = createXXGroup(); + Mockito.when(xXGroupDao.getById(1L)).thenReturn(xGroup); + Mockito.when(daoManager.getXXUser()).thenReturn(xXUserDao); + XXUser xUser = createXXUser(); + Mockito.when(xXUserDao.getById(1L)).thenReturn(xUser); + xGroupUserService.createTransactionLog(vObj, null, OPERATION_CREATE_CONTEXT); + } + + private XXGroup createXXGroup() { + XXGroup xXGroup = new XXGroup(); + Date date = new Date(); + xXGroup.setAddedByUserId(1L); + xXGroup.setCreateTime(date); + xXGroup.setCredStoreId(1L); + xXGroup.setDescription("this is test description"); + xXGroup.setGroupSource(0); + xXGroup.setGroupType(1); + xXGroup.setId(1L); + xXGroup.setIsVisible(1); + xXGroup.setName("testName"); + xXGroup.setUpdateTime(date); + + return xXGroup; + } + + private VXGroupUser createVXGroupUser() { + VXGroupUser vxGroupUser = new VXGroupUser(); + Date date = new Date(); + vxGroupUser.setCreateDate(date); + vxGroupUser.setId(1L); + vxGroupUser.setMObj(gjObj); + vxGroupUser.setName("testGroupUser"); + vxGroupUser.setOwner("admin"); + vxGroupUser.setParentGroupId(1L); + vxGroupUser.setUpdateDate(date); + vxGroupUser.setUpdatedBy("admin"); + vxGroupUser.setUserId(1L); + return vxGroupUser; + } + + private XXGroupUser createXXGroupUser() { + XXGroupUser xXGroupUser = new XXGroupUser(); + xXGroupUser.setAddedByUserId(1L); + Date date = new Date(); + xXGroupUser.setCreateTime(date); + xXGroupUser.setId(1L); + xXGroupUser.setName("testGroupUser"); + xXGroupUser.setParentGroupId(1L); + xXGroupUser.setUpdatedByUserId(1L); + xXGroupUser.setUpdateTime(date); + xXGroupUser.setUserId(1L); + return xXGroupUser; + } + + private XXUser createXXUser() { + XXUser xUser = new XXUser(); + xUser.setAddedByUserId(1L); + Date date = new Date(); + xUser.setCreateTime(date); + xUser.setCredStoreId(1L); + xUser.setDescription("this is test xUser"); + xUser.setId(1L); + xUser.setIsVisible(1); + xUser.setName("testUser"); + xUser.setStatus(1); + xUser.setUpdatedByUserId(1L); + xUser.setUpdateTime(date); + return xUser; + } } diff --git a/security-admin/src/test/java/org/apache/ranger/service/TestXPermMapService.java b/security-admin/src/test/java/org/apache/ranger/service/TestXPermMapService.java index 9e861eeae4..55742f979b 100644 --- a/security-admin/src/test/java/org/apache/ranger/service/TestXPermMapService.java +++ b/security-admin/src/test/java/org/apache/ranger/service/TestXPermMapService.java @@ -19,8 +19,6 @@ package org.apache.ranger.service; -import java.util.Date; - import org.apache.ranger.biz.RangerBizUtil; import org.apache.ranger.common.StringUtil; import org.apache.ranger.common.UserSessionBase; @@ -48,169 +46,168 @@ import org.mockito.Mockito; import org.mockito.junit.MockitoJUnitRunner; +import java.util.Date; + import static org.apache.ranger.service.RangerBaseModelService.OPERATION_CREATE_CONTEXT; import static org.apache.ranger.service.RangerBaseModelService.OPERATION_UPDATE_CONTEXT; @RunWith(MockitoJUnitRunner.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class TestXPermMapService { - - @InjectMocks - XPermMapService xPermMapService; - - @Mock - XXPermMap xXPermMap; - - @Mock - UserSessionBase currentUserSession; - - @Mock - RangerDaoManager daoManager; - - @Mock - StringUtil stringUtil; - - @Mock - XXPortalUserDao xXPortalUserDao; - - @Mock - XXPortalUser tUser; - - @Mock - XGroupService xGroupService; - - @Mock - VXGroup vXGroup; - - @Mock - XUserService xUserService; - - @Mock - VXUser vXUser; - - @Mock - XXDBBase gjObj; - - @Mock - XXGroupDao xXGroupDao; - - @Mock - XXResourceDao xXResourceDao; - - @Mock - XXResource xXResource; - - @Mock - XXAssetDao xXAssetDao; - - @Mock - XXAsset xXAsset; - - @Mock - RangerEnumUtil xaEnumUtil; - - @Mock - RangerBizUtil bizUtil; - - @Mock - AbstractBaseResourceService abstractBaseResourceService; - - @Test - public void test1GetGroupName() { - Mockito.when(xGroupService.readResource(1L)).thenReturn(vXGroup); - xPermMapService.getGroupName(1L); - - } - - @Test - public void test2GetUserName() { - Mockito.when(xUserService.readResource(1L)).thenReturn(vXUser); - xPermMapService.getUserName(1L); - - } - - @Test - public void test3GetTransactionLog() { - VXPermMap vXPermMap = createVXPermMap(); - Mockito.when(daoManager.getXXGroup()).thenReturn(xXGroupDao); - XXGroup xGroup = createXXGroup(); - Mockito.when(xXGroupDao.getById(1L)).thenReturn(xGroup); - xPermMapService.createTransactionLog(vXPermMap, null, OPERATION_CREATE_CONTEXT); - } - - @Test - public void test4GetTransactionLog() { - VXPermMap vObj = createVXPermMap(); - VXPermMap vObj2 = createVXPermMap2(); - Mockito.when(daoManager.getXXGroup()).thenReturn(xXGroupDao); - XXGroup xGroup = createXXGroup(); - Mockito.when(xXGroupDao.getById(1L)).thenReturn(xGroup); - xPermMapService.createTransactionLog(vObj, vObj2, OPERATION_UPDATE_CONTEXT); - } - - private VXPermMap createVXPermMap() { - VXPermMap vXPermMap = new VXPermMap(); - Date date = new Date(); - vXPermMap.setCreateDate(date); - vXPermMap.setGrantOrRevoke(false); - vXPermMap.setGroupId(1L); - vXPermMap.setGroupName("testGroupName"); - vXPermMap.setId(1L); - vXPermMap.setIpAddress("123.45.678.90"); - vXPermMap.setIsRecursive(0); - vXPermMap.setIsWildCard(false); - vXPermMap.setMObj(gjObj); - vXPermMap.setOwner("admin"); - vXPermMap.setPermFor(0); - vXPermMap.setPermGroup(""); - vXPermMap.setPermType(0); - vXPermMap.setResourceId(1L); - vXPermMap.setUpdateDate(date); - vXPermMap.setUpdatedBy("admin"); - vXPermMap.setUserId(1L); - vXPermMap.setUserName("testUser"); - return vXPermMap; - } - - private VXPermMap createVXPermMap2() { - VXPermMap vXPermMap = new VXPermMap(); - Date date = new Date(); - vXPermMap.setCreateDate(date); - vXPermMap.setGrantOrRevoke(false); - vXPermMap.setGroupId(1L); - vXPermMap.setGroupName("testGroupName1"); - vXPermMap.setId(1L); - vXPermMap.setIpAddress("123.45.678.91"); - vXPermMap.setIsRecursive(0); - vXPermMap.setIsWildCard(false); - vXPermMap.setMObj(gjObj); - vXPermMap.setOwner("admin"); - vXPermMap.setPermFor(0); - vXPermMap.setPermGroup(""); - vXPermMap.setPermType(0); - vXPermMap.setResourceId(1L); - vXPermMap.setUpdateDate(date); - vXPermMap.setUpdatedBy("admin"); - vXPermMap.setUserId(1L); - vXPermMap.setUserName("testUser"); - return vXPermMap; - } - - public XXGroup createXXGroup() { - XXGroup xGroup = new XXGroup(); - xGroup.setAddedByUserId(1L); - Date date = new Date(); - xGroup.setCreateTime(date); - xGroup.setCredStoreId(1L); - xGroup.setDescription("this is test xGroup"); - xGroup.setGroupSource(1); - xGroup.setGroupType(1); - xGroup.setId(1L); - xGroup.setIsVisible(1); - xGroup.setName("testxGroup"); - xGroup.setStatus(1); - xGroup.setUpdatedByUserId(1L); - xGroup.setUpdateTime(date); - return xGroup; - } + @InjectMocks + XPermMapService xPermMapService; + + @Mock + XXPermMap xXPermMap; + + @Mock + UserSessionBase currentUserSession; + + @Mock + RangerDaoManager daoManager; + + @Mock + StringUtil stringUtil; + + @Mock + XXPortalUserDao xXPortalUserDao; + + @Mock + XXPortalUser tUser; + + @Mock + XGroupService xGroupService; + + @Mock + VXGroup vXGroup; + + @Mock + XUserService xUserService; + + @Mock + VXUser vXUser; + + @Mock + XXDBBase gjObj; + + @Mock + XXGroupDao xXGroupDao; + + @Mock + XXResourceDao xXResourceDao; + + @Mock + XXResource xXResource; + + @Mock + XXAssetDao xXAssetDao; + + @Mock + XXAsset xXAsset; + + @Mock + RangerEnumUtil xaEnumUtil; + + @Mock + RangerBizUtil bizUtil; + + @Mock + AbstractBaseResourceService abstractBaseResourceService; + + @Test + public void test1GetGroupName() { + Mockito.when(xGroupService.readResource(1L)).thenReturn(vXGroup); + xPermMapService.getGroupName(1L); + } + + @Test + public void test2GetUserName() { + Mockito.when(xUserService.readResource(1L)).thenReturn(vXUser); + xPermMapService.getUserName(1L); + } + + @Test + public void test3GetTransactionLog() { + VXPermMap vXPermMap = createVXPermMap(); + Mockito.when(daoManager.getXXGroup()).thenReturn(xXGroupDao); + XXGroup xGroup = createXXGroup(); + Mockito.when(xXGroupDao.getById(1L)).thenReturn(xGroup); + xPermMapService.createTransactionLog(vXPermMap, null, OPERATION_CREATE_CONTEXT); + } + + @Test + public void test4GetTransactionLog() { + VXPermMap vObj = createVXPermMap(); + VXPermMap vObj2 = createVXPermMap2(); + Mockito.when(daoManager.getXXGroup()).thenReturn(xXGroupDao); + XXGroup xGroup = createXXGroup(); + Mockito.when(xXGroupDao.getById(1L)).thenReturn(xGroup); + xPermMapService.createTransactionLog(vObj, vObj2, OPERATION_UPDATE_CONTEXT); + } + + public XXGroup createXXGroup() { + XXGroup xGroup = new XXGroup(); + xGroup.setAddedByUserId(1L); + Date date = new Date(); + xGroup.setCreateTime(date); + xGroup.setCredStoreId(1L); + xGroup.setDescription("this is test xGroup"); + xGroup.setGroupSource(1); + xGroup.setGroupType(1); + xGroup.setId(1L); + xGroup.setIsVisible(1); + xGroup.setName("testxGroup"); + xGroup.setStatus(1); + xGroup.setUpdatedByUserId(1L); + xGroup.setUpdateTime(date); + return xGroup; + } + + private VXPermMap createVXPermMap() { + VXPermMap vXPermMap = new VXPermMap(); + Date date = new Date(); + vXPermMap.setCreateDate(date); + vXPermMap.setGrantOrRevoke(false); + vXPermMap.setGroupId(1L); + vXPermMap.setGroupName("testGroupName"); + vXPermMap.setId(1L); + vXPermMap.setIpAddress("123.45.678.90"); + vXPermMap.setIsRecursive(0); + vXPermMap.setIsWildCard(false); + vXPermMap.setMObj(gjObj); + vXPermMap.setOwner("admin"); + vXPermMap.setPermFor(0); + vXPermMap.setPermGroup(""); + vXPermMap.setPermType(0); + vXPermMap.setResourceId(1L); + vXPermMap.setUpdateDate(date); + vXPermMap.setUpdatedBy("admin"); + vXPermMap.setUserId(1L); + vXPermMap.setUserName("testUser"); + return vXPermMap; + } + + private VXPermMap createVXPermMap2() { + VXPermMap vXPermMap = new VXPermMap(); + Date date = new Date(); + vXPermMap.setCreateDate(date); + vXPermMap.setGrantOrRevoke(false); + vXPermMap.setGroupId(1L); + vXPermMap.setGroupName("testGroupName1"); + vXPermMap.setId(1L); + vXPermMap.setIpAddress("123.45.678.91"); + vXPermMap.setIsRecursive(0); + vXPermMap.setIsWildCard(false); + vXPermMap.setMObj(gjObj); + vXPermMap.setOwner("admin"); + vXPermMap.setPermFor(0); + vXPermMap.setPermGroup(""); + vXPermMap.setPermType(0); + vXPermMap.setResourceId(1L); + vXPermMap.setUpdateDate(date); + vXPermMap.setUpdatedBy("admin"); + vXPermMap.setUserId(1L); + vXPermMap.setUserName("testUser"); + return vXPermMap; + } } diff --git a/security-admin/src/test/java/org/apache/ranger/service/filter/TestRangerRESTAPIFilter.java b/security-admin/src/test/java/org/apache/ranger/service/filter/TestRangerRESTAPIFilter.java index 176fcafaab..bfe3c1508c 100644 --- a/security-admin/src/test/java/org/apache/ranger/service/filter/TestRangerRESTAPIFilter.java +++ b/security-admin/src/test/java/org/apache/ranger/service/filter/TestRangerRESTAPIFilter.java @@ -19,6 +19,7 @@ package org.apache.ranger.service.filter; +import com.sun.jersey.spi.container.ContainerRequest; import org.junit.FixMethodOrder; import org.junit.Test; import org.junit.runner.RunWith; @@ -27,22 +28,17 @@ import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; -import com.sun.jersey.spi.container.ContainerRequest; - @RunWith(MockitoJUnitRunner.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class TestRangerRESTAPIFilter { + @InjectMocks + RangerRESTAPIFilter rangerRESTAPIFilter = new RangerRESTAPIFilter(); - @InjectMocks - RangerRESTAPIFilter rangerRESTAPIFilter = new RangerRESTAPIFilter(); - - @Mock - ContainerRequest request; - - @Test - public void test1Filter() { - rangerRESTAPIFilter.filter(request); - - } + @Mock + ContainerRequest request; + @Test + public void test1Filter() { + rangerRESTAPIFilter.filter(request); + } } diff --git a/security-admin/src/test/java/org/apache/ranger/util/BaseTest.java b/security-admin/src/test/java/org/apache/ranger/util/BaseTest.java index fd19a112a3..c8b6e1b7df 100644 --- a/security-admin/src/test/java/org/apache/ranger/util/BaseTest.java +++ b/security-admin/src/test/java/org/apache/ranger/util/BaseTest.java @@ -17,7 +17,7 @@ * under the License. */ - /** +/** * */ package org.apache.ranger.util; @@ -37,71 +37,66 @@ @Transactional @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(locations = { "classpath:applicationContext.xml", - "classpath:asynctask-applicationContext.xml" }) -@TestExecutionListeners({ DependencyInjectionTestExecutionListener.class, - DirtiesContextTestExecutionListener.class, - TransactionalTestExecutionListener.class }) -abstract public class BaseTest { +@ContextConfiguration(locations = {"classpath:applicationContext.xml", + "classpath:asynctask-applicationContext.xml"}) +@TestExecutionListeners({DependencyInjectionTestExecutionListener.class, + DirtiesContextTestExecutionListener.class, + TransactionalTestExecutionListener.class}) +public abstract class BaseTest { + /** + * MockHttpSession, SubStitute of HttpSession + */ + protected MockHttpSession session; + /** + * MockHttpServletRequest, SubStitute of HttpServletRequest + */ + protected MockHttpServletRequest request; - /** - * MockHttpSession, SubStitute of HttpSession - */ - protected MockHttpSession session; - /** - * MockHttpServletRequest, SubStitute of HttpServletRequest - */ - protected MockHttpServletRequest request; + public BaseTest() { + init(); + } - public BaseTest() { - init(); - } + public void authenticate() throws Exception { + CLIUtil cliUtil = (CLIUtil) CLIUtil.getBean(CLIUtil.class); + cliUtil.authenticate(); + } - public void authenticate() throws Exception { - CLIUtil cliUtil = (CLIUtil) CLIUtil.getBean(CLIUtil.class); - cliUtil.authenticate(); - } + public void init() { + } - /* - * Start New MockHttpSession - */ - protected void startSession() { - session = new MockHttpSession(); - } + /* + * Start New MockHttpSession + */ + protected void startSession() { + session = new MockHttpSession(); + } - /* - * Destroy MockHttpSession, if exists - */ - protected void endSession() { - if (session != null) { - session.clearAttributes(); - } - session = null; - } + /* + * Destroy MockHttpSession, if exists + */ + protected void endSession() { + if (session != null) { + session.clearAttributes(); + } + session = null; + } - /* - * Create New MockHttpServletRequest - */ - protected MockHttpServletRequest startRequest() { - request = new MockHttpServletRequest(); - request.setSession(session); - RequestContextHolder.setRequestAttributes(new ServletRequestAttributes( - request)); - return request; - } - - /* - * terminate existing MockHttpServletRequest - */ - protected void endRequest() { - ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()) - .requestCompleted(); - RequestContextHolder.resetRequestAttributes(); - request = null; - } - - public void init() { - - } + /* + * Create New MockHttpServletRequest + */ + protected MockHttpServletRequest startRequest() { + request = new MockHttpServletRequest(); + request.setSession(session); + RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(request)); + return request; + } + /* + * terminate existing MockHttpServletRequest + */ + protected void endRequest() { + ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).requestCompleted(); + RequestContextHolder.resetRequestAttributes(); + request = null; + } } diff --git a/security-admin/src/test/java/org/apache/ranger/util/TestRangerEnumUtil.java b/security-admin/src/test/java/org/apache/ranger/util/TestRangerEnumUtil.java index fa27cf359f..fbec7e84af 100644 --- a/security-admin/src/test/java/org/apache/ranger/util/TestRangerEnumUtil.java +++ b/security-admin/src/test/java/org/apache/ranger/util/TestRangerEnumUtil.java @@ -16,9 +16,6 @@ */ package org.apache.ranger.util; -import java.util.ArrayList; -import java.util.List; - import org.apache.ranger.common.view.VEnum; import org.apache.ranger.common.view.VEnumElement; import org.junit.Assert; @@ -27,99 +24,97 @@ import org.junit.rules.ExpectedException; import org.springframework.beans.factory.annotation.Autowired; -public class TestRangerEnumUtil { +import java.util.ArrayList; +import java.util.List; - @Autowired - RangerEnumUtil xaEnumUtil = new RangerEnumUtil(); - - @Rule - public ExpectedException thrown = ExpectedException.none(); - - @Test - public void testGetEnums() { - - VEnumElement VEnumElement = new VEnumElement(); - VEnumElement.setEnumName("test1"); - VEnumElement.setElementName("test2"); - VEnumElement.setElementLabel("test3"); - VEnumElement.setElementValue(0); - VEnumElement.setRbKey("11"); - List listVEnumElement = new ArrayList(); - - VEnum vEnum = new VEnum(); - vEnum.setEnumName("test"); - vEnum.setElementList(listVEnumElement); - xaEnumUtil.enumList.add(vEnum); - List dbvEnum= xaEnumUtil.getEnums(); - Assert.assertNotNull(dbvEnum); - } - - @Test - public void testGetEnumEmpty() { - - String enumName = ""; - xaEnumUtil.getEnum(enumName); - Assert.assertNotNull(xaEnumUtil.enumList.size() > 0); - } - - @Test - public void testGetEnum() { - - String enumName = "enumtest"; - - VEnumElement vEnumElement1 = new VEnumElement(); - vEnumElement1.setEnumName(enumName); - vEnumElement1.setElementName("test12"); - vEnumElement1.setElementLabel("test13"); - vEnumElement1.setElementValue(1); - vEnumElement1.setRbKey("11"); - List VEnumElement = new ArrayList(); - VEnumElement.add(vEnumElement1); - - VEnum vEnum = new VEnum(); - vEnum.setEnumName(enumName); - vEnum.setElementList(VEnumElement); - - xaEnumUtil.enumMap.put(enumName, vEnum); - - VEnum dbvEnum = xaEnumUtil.getEnum(enumName); - - Assert.assertNotNull(dbvEnum); - Assert.assertEquals(enumName, dbvEnum.getEnumName()); - } - - @Test - public void testGetLabelIsNUll() { - String enumName = "CommonEnums.ActiveStatus"; - int enumValue = 1; - String value = xaEnumUtil.getLabel(enumName, enumValue); - boolean checkValue=value.isEmpty(); - Assert.assertFalse(checkValue); - } - - @Test - public void testGetLabel() { - testGetEnum(); - String enumName = "CommonEnums.ActiveStatus"; - int enumValue = 1; - String value = xaEnumUtil.getLabel(enumName, enumValue); - Assert.assertNotNull(value); - } - - @Test - public void testgetValueIsNull() { - String enumName = "CommonEnums.BooleanValue"; - String elementName = "BOOL_NONE"; - int value = xaEnumUtil.getValue(enumName, elementName); - Assert.assertEquals(0, value); - } - - @Test - public void testgetValue() { - testGetEnum(); - String enumName = "CommonEnums.ActivationStatus"; - String elementName = "ACT_STATUS_DISABLED"; - int value = xaEnumUtil.getValue(enumName, elementName); - Assert.assertEquals(0, value); - } -} \ No newline at end of file +public class TestRangerEnumUtil { + @Rule + public ExpectedException thrown = ExpectedException.none(); + @Autowired + RangerEnumUtil xaEnumUtil = new RangerEnumUtil(); + + @Test + public void testGetEnums() { + VEnumElement vEnumElement = new VEnumElement(); + vEnumElement.setEnumName("test1"); + vEnumElement.setElementName("test2"); + vEnumElement.setElementLabel("test3"); + vEnumElement.setElementValue(0); + vEnumElement.setRbKey("11"); + List listVEnumElement = new ArrayList<>(); + + VEnum vEnum = new VEnum(); + vEnum.setEnumName("test"); + vEnum.setElementList(listVEnumElement); + xaEnumUtil.enumList.add(vEnum); + List dbvEnum = xaEnumUtil.getEnums(); + Assert.assertNotNull(dbvEnum); + } + + @Test + public void testGetEnumEmpty() { + String enumName = ""; + xaEnumUtil.getEnum(enumName); + Assert.assertNotNull(xaEnumUtil.enumList.size() > 0); + } + + @Test + public void testGetEnum() { + String enumName = "enumtest"; + + VEnumElement vEnumElement1 = new VEnumElement(); + vEnumElement1.setEnumName(enumName); + vEnumElement1.setElementName("test12"); + vEnumElement1.setElementLabel("test13"); + vEnumElement1.setElementValue(1); + vEnumElement1.setRbKey("11"); + List vEnumElement = new ArrayList<>(); + vEnumElement.add(vEnumElement1); + + VEnum vEnum = new VEnum(); + vEnum.setEnumName(enumName); + vEnum.setElementList(vEnumElement); + + xaEnumUtil.enumMap.put(enumName, vEnum); + + VEnum dbvEnum = xaEnumUtil.getEnum(enumName); + + Assert.assertNotNull(dbvEnum); + Assert.assertEquals(enumName, dbvEnum.getEnumName()); + } + + @Test + public void testGetLabelIsNUll() { + String enumName = "CommonEnums.ActiveStatus"; + int enumValue = 1; + String value = xaEnumUtil.getLabel(enumName, enumValue); + boolean checkValue = value.isEmpty(); + Assert.assertFalse(checkValue); + } + + @Test + public void testGetLabel() { + testGetEnum(); + String enumName = "CommonEnums.ActiveStatus"; + int enumValue = 1; + String value = xaEnumUtil.getLabel(enumName, enumValue); + Assert.assertNotNull(value); + } + + @Test + public void testGetValueIsNull() { + String enumName = "CommonEnums.BooleanValue"; + String elementName = "BOOL_NONE"; + int value = xaEnumUtil.getValue(enumName, elementName); + Assert.assertEquals(0, value); + } + + @Test + public void testGetValue() { + testGetEnum(); + String enumName = "CommonEnums.ActivationStatus"; + String elementName = "ACT_STATUS_DISABLED"; + int value = xaEnumUtil.getValue(enumName, elementName); + Assert.assertEquals(0, value); + } +} diff --git a/security-admin/src/test/java/org/apache/ranger/util/TestRangerMetricsUtil.java b/security-admin/src/test/java/org/apache/ranger/util/TestRangerMetricsUtil.java index ff306c1ee8..e9b340a381 100644 --- a/security-admin/src/test/java/org/apache/ranger/util/TestRangerMetricsUtil.java +++ b/security-admin/src/test/java/org/apache/ranger/util/TestRangerMetricsUtil.java @@ -19,17 +19,18 @@ package org.apache.ranger.util; -import java.util.Map; import org.junit.Assert; import org.junit.Test; import org.mockito.InjectMocks; +import java.util.Map; + public class TestRangerMetricsUtil { @InjectMocks RangerMetricsUtil rangerMetricsUtil = new RangerMetricsUtil(); @Test - public void testGetRangerMetricsValues() throws Exception { + public void testGetRangerMetricsValues() { Map rangerMetricsMap = rangerMetricsUtil.getValues(); Assert.assertNotNull(rangerMetricsMap); @@ -37,14 +38,14 @@ public void testGetRangerMetricsValues() throws Exception { Assert.assertNotNull(rangerMetricsMap.get("os.vcpus")); Assert.assertNotNull(rangerMetricsMap.get("memory")); - Map memoryDetailsMap = (Map)rangerMetricsMap.get("memory"); + Map memoryDetailsMap = (Map) rangerMetricsMap.get("memory"); Assert.assertNotNull(memoryDetailsMap.get("heapMax")); Assert.assertNotNull(memoryDetailsMap.get("heapCommitted")); Assert.assertNotNull(memoryDetailsMap.get("heapUsed")); Assert.assertNotNull(memoryDetailsMap.get("memory_pool_usages")); - Map poolDivisionDetailsMap = (Map)memoryDetailsMap.get("memory_pool_usages"); + Map poolDivisionDetailsMap = (Map) memoryDetailsMap.get("memory_pool_usages"); Assert.assertTrue(poolDivisionDetailsMap.size() > 0); } diff --git a/security-admin/src/test/java/org/apache/ranger/util/TestRangerServerHealthUtil.java b/security-admin/src/test/java/org/apache/ranger/util/TestRangerServerHealthUtil.java index 7603767f0d..d182cbfeeb 100644 --- a/security-admin/src/test/java/org/apache/ranger/util/TestRangerServerHealthUtil.java +++ b/security-admin/src/test/java/org/apache/ranger/util/TestRangerServerHealthUtil.java @@ -17,17 +17,19 @@ package org.apache.ranger.util; -import static org.apache.ranger.plugin.model.RangerServerHealth.RangerServerStatus.*; - -import java.util.Map; import org.apache.ranger.plugin.model.RangerServerHealth; import org.junit.Assert; import org.junit.Test; import org.mockito.InjectMocks; +import java.util.Map; + +import static org.apache.ranger.plugin.model.RangerServerHealth.RangerServerStatus.DOWN; + public class TestRangerServerHealthUtil { @InjectMocks RangerServerHealthUtil rangerServerHealthUtil = new RangerServerHealthUtil(); + @Test public void testGetRangerServerHealth() { RangerServerHealth rangerServerHealth = rangerServerHealthUtil.getRangerServerHealth("21.3c"); @@ -35,5 +37,4 @@ public void testGetRangerServerHealth() { Assert.assertEquals("RangerHealth.getDetails()", 1, rangerServerHealth.getDetails().size()); Assert.assertEquals("RangerHealth.getDetails('component')", 1, ((Map) rangerServerHealth.getDetails().get("components")).size()); } - } From 5c6f87bf293faeeff2619a9e1aad0de1efd88e4f Mon Sep 17 00:00:00 2001 From: Dineshkumar Yadav <59435896+dineshkumar-yadav@users.noreply.github.com> Date: Sat, 4 Jan 2025 00:20:24 +0530 Subject: [PATCH 03/15] RANGER-5061: checkstyle compliance updates - security-admin module for org.apache.ranger.amazon and org.apache.ranger.authentication (#490) --- .../CloudWatchAccessAuditsService.java | 506 +++++++++--------- .../amazon/cloudwatch/CloudWatchMgr.java | 83 +-- .../amazon/cloudwatch/CloudWatchUtil.java | 468 ++++++++-------- .../unix/jaas/RoleUserAuthorityGranter.java | 26 +- 4 files changed, 554 insertions(+), 529 deletions(-) diff --git a/security-admin/src/main/java/org/apache/ranger/amazon/cloudwatch/CloudWatchAccessAuditsService.java b/security-admin/src/main/java/org/apache/ranger/amazon/cloudwatch/CloudWatchAccessAuditsService.java index 06a21a3c23..f15076427f 100644 --- a/security-admin/src/main/java/org/apache/ranger/amazon/cloudwatch/CloudWatchAccessAuditsService.java +++ b/security-admin/src/main/java/org/apache/ranger/amazon/cloudwatch/CloudWatchAccessAuditsService.java @@ -19,11 +19,8 @@ package org.apache.ranger.amazon.cloudwatch; -import java.io.UnsupportedEncodingException; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - +import com.amazonaws.services.logs.AWSLogs; +import com.amazonaws.services.logs.model.FilteredLogEvent; import org.apache.commons.collections.CollectionUtils; import org.apache.ranger.audit.model.AuthzAuditEvent; import org.apache.ranger.audit.provider.MiscUtil; @@ -43,257 +40,256 @@ import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Service; -import com.amazonaws.services.logs.AWSLogs; -import com.amazonaws.services.logs.model.FilteredLogEvent; +import java.io.UnsupportedEncodingException; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; @Service @Scope("singleton") public class CloudWatchAccessAuditsService extends org.apache.ranger.AccessAuditsService { - private static final Logger LOGGER = LoggerFactory.getLogger(CloudWatchAccessAuditsService.class); - - @Autowired - CloudWatchMgr cloudWatchMgr; - - @Autowired - CloudWatchUtil cloudWatchUtil; - - @Autowired - JSONUtil jsonUtil; - - public VXAccessAuditList searchXAccessAudits(SearchCriteria searchCriteria) { - - final boolean hiveQueryVisibility = PropertiesUtil.getBooleanProperty("ranger.audit.hive.query.visibility", true); - AWSLogs client = cloudWatchMgr.getClient(); - if (client == null) { - LOGGER.warn("CloudWatch client is null, so not running the query."); - throw restErrorUtil.createRESTException("Error connecting to cloudwatch", MessageEnums.ERROR_SYSTEM); - } - - List xAccessAuditList = new ArrayList(); - Map paramList = searchCriteria.getParamList(); - updateUserExclusion(paramList); - - List result; - try { - result = cloudWatchUtil.searchResources(client, searchCriteria, searchFields, sortFields); - } catch (Exception e) { - LOGGER.warn(String.format("CloudWatch query failed: %s", e.getMessage())); - throw restErrorUtil.createRESTException("Error querying search engine", MessageEnums.ERROR_SYSTEM); - } - - VXAccessAuditList returnList = new VXAccessAuditList(); - if (result != null && CollectionUtils.isNotEmpty(result)) { - int recordCount = 0; - int endIndex = result.size() - 1; - endIndex = endIndex - searchCriteria.getStartIndex() < 0 ? endIndex : endIndex - searchCriteria.getStartIndex(); - for (int index = endIndex; recordCount < searchCriteria.getMaxRows() && index >=0 ; index--) { - FilteredLogEvent event = result.get(index); - AuthzAuditEvent auditEvent = null; - try { - auditEvent = MiscUtil.fromJson(event.getMessage(), AuthzAuditEvent.class); - } catch (Exception ex) { - LOGGER.error("Error while parsing json data" , ex); - } - VXAccessAudit vXAccessAudit = populateViewBean(auditEvent); - if (vXAccessAudit != null) { - String serviceType = vXAccessAudit.getServiceType(); - boolean isHive = "hive".equalsIgnoreCase(serviceType); - if (!hiveQueryVisibility && isHive) { - vXAccessAudit.setRequestData(null); - } else if (isHive) { - String accessType = vXAccessAudit.getAccessType(); - if ("grant".equalsIgnoreCase(accessType) || "revoke".equalsIgnoreCase(accessType)) { - String requestData = vXAccessAudit.getRequestData(); - if (requestData != null) { - try { - vXAccessAudit.setRequestData(java.net.URLDecoder.decode(requestData, "UTF-8")); - } catch (UnsupportedEncodingException e) { - LOGGER.warn("Error while encoding request data: " + requestData, e); - } - } else { - LOGGER.warn("Error in request data of audit from cloudwatch. AuditData: "+ vXAccessAudit.toString()); - } - } - } - } - xAccessAuditList.add(vXAccessAudit); - recordCount++; - } - returnList.setResultSize(result.size()); - returnList.setTotalCount(result.size()); - } - - returnList.setPageSize(searchCriteria.getMaxRows()); - returnList.setStartIndex(searchCriteria.getStartIndex()); - returnList.setVXAccessAudits(xAccessAuditList); - return returnList; - } - - public void setRestErrorUtil(RESTErrorUtil restErrorUtil) { - this.restErrorUtil = restErrorUtil; - } - - public VXLong getXAccessAuditSearchCount(SearchCriteria searchCriteria) { - long count = 100; - VXLong vXLong = new VXLong(); - vXLong.setValue(count); - return vXLong; - } - - private VXAccessAudit populateViewBean(AuthzAuditEvent auditEvent) { - VXAccessAudit accessAudit = new VXAccessAudit(); - - Object value = null; - if(LOGGER.isDebugEnabled()) { - LOGGER.debug("doc=" + auditEvent.toString()); - } - - value = auditEvent.getEventId(); - if (value != null) { - accessAudit.setId((long) value.hashCode()); - accessAudit.setEventId(value.toString()); - } - - value = auditEvent.getClusterName(); - if (value != null) { - accessAudit.setClusterName(value.toString()); - } - - value = auditEvent.getZoneName(); - if (value != null) { - accessAudit.setZoneName(value.toString()); - } - - value = auditEvent.getAgentHostname(); - if (value != null) { - accessAudit.setAgentHost(value.toString()); - } - - value = auditEvent.getPolicyVersion(); - if (value != null) { - accessAudit.setPolicyVersion(MiscUtil.toLong(value)); - } - - value = auditEvent.getAccessType(); - if (value != null) { - accessAudit.setAccessType(value.toString()); - } - - value = auditEvent.getAclEnforcer(); - if (value != null) { - accessAudit.setAclEnforcer(value.toString()); - } - - value = auditEvent.getAgentId(); - if (value != null) { - accessAudit.setAgentId(value.toString()); - } - - value = auditEvent.getRepositoryName(); - if (value != null) { - accessAudit.setRepoName(value.toString()); - XXService xxService = daoManager.getXXService().findByName(accessAudit.getRepoName()); - - if(xxService != null) { - accessAudit.setRepoDisplayName(xxService.getDisplayName()); - } - } - - value = auditEvent.getSessionId(); - if (value != null) { - accessAudit.setSessionId(value.toString()); - } - - value = auditEvent.getUser(); - if (value != null) { - accessAudit.setRequestUser(value.toString()); - } - - value = auditEvent.getRequestData(); - if (value != null) { - accessAudit.setRequestData(value.toString()); - } - value = auditEvent.getResourcePath(); - if (value != null) { - accessAudit.setResourcePath(value.toString()); - } - - value = auditEvent.getClientIP(); - if (value != null) { - accessAudit.setClientIP(value.toString()); - } - - value = auditEvent.getAccessResult(); - if (value != null) { - accessAudit.setAccessResult(MiscUtil.toInt(value)); - } - - value = auditEvent.getPolicyId(); - if (value != null) { - accessAudit.setPolicyId(MiscUtil.toLong(value)); - } - - value = auditEvent.getRepositoryType(); - if (value != null) { - accessAudit.setRepoType(MiscUtil.toInt(value)); - XXServiceDef xServiceDef = daoManager.getXXServiceDef().getById((long) accessAudit.getRepoType()); - if (xServiceDef != null) { - accessAudit.setServiceType(xServiceDef.getName()); - accessAudit.setServiceTypeDisplayName(xServiceDef.getDisplayName()); - } - } - - value = auditEvent.getResourceType(); - if (value != null) { - accessAudit.setResourceType(value.toString()); - } - - value = auditEvent.getResultReason(); - if (value != null) { - accessAudit.setResultReason(value.toString()); - } - - value = auditEvent.getAction(); - if (value != null) { - accessAudit.setAction(value.toString()); - } - - value = auditEvent.getEventTime(); - if (value != null) { - accessAudit.setEventTime(MiscUtil.toLocalDate(value)); - } - - value = auditEvent.getSeqNum(); - if (value != null) { - accessAudit.setSequenceNumber(MiscUtil.toLong(value)); - } - - value = auditEvent.getEventCount(); - if (value != null) { - accessAudit.setEventCount(MiscUtil.toLong(value)); - } - - value = auditEvent.getEventDurationMS(); - if (value != null) { - accessAudit.setEventDuration(MiscUtil.toLong(value)); - } - - value = auditEvent.getTags(); - if (value != null) { - accessAudit.setTags(value.toString()); - } - - value = auditEvent.getDatasets(); - if (value != null) { - accessAudit.setDatasets(value.toString()); - } - - value = auditEvent.getProjects(); - if (value != null) { - accessAudit.setProjects(value.toString()); - } - - return accessAudit; - } - -} \ No newline at end of file + private static final Logger LOGGER = LoggerFactory.getLogger(CloudWatchAccessAuditsService.class); + + @Autowired + CloudWatchMgr cloudWatchMgr; + + @Autowired + CloudWatchUtil cloudWatchUtil; + + @Autowired + JSONUtil jsonUtil; + + public VXAccessAuditList searchXAccessAudits(SearchCriteria searchCriteria) { + final boolean hiveQueryVisibility = PropertiesUtil.getBooleanProperty("ranger.audit.hive.query.visibility", true); + AWSLogs client = cloudWatchMgr.getClient(); + + if (client == null) { + LOGGER.warn("CloudWatch client is null, so not running the query."); + + throw restErrorUtil.createRESTException("Error connecting to cloudwatch", MessageEnums.ERROR_SYSTEM); + } + + List xAccessAuditList = new ArrayList(); + Map paramList = searchCriteria.getParamList(); + + updateUserExclusion(paramList); + + List result; + + try { + result = cloudWatchUtil.searchResources(client, searchCriteria, searchFields, sortFields); + } catch (Exception e) { + LOGGER.warn("CloudWatch query failed: {}", e.getMessage()); + + throw restErrorUtil.createRESTException("Error querying search engine", MessageEnums.ERROR_SYSTEM); + } + + VXAccessAuditList returnList = new VXAccessAuditList(); + + if (CollectionUtils.isNotEmpty(result)) { + int recordCount = 0; + int endIndex = result.size() - 1; + + endIndex = endIndex - searchCriteria.getStartIndex() < 0 ? endIndex : endIndex - searchCriteria.getStartIndex(); + + for (int index = endIndex; recordCount < searchCriteria.getMaxRows() && index >= 0; index--) { + FilteredLogEvent event = result.get(index); + AuthzAuditEvent auditEvent = null; + + try { + auditEvent = MiscUtil.fromJson(event.getMessage(), AuthzAuditEvent.class); + } catch (Exception ex) { + LOGGER.error("Error while parsing json data", ex); + } + + VXAccessAudit vXAccessAudit = populateViewBean(auditEvent); + + if (vXAccessAudit != null) { + String serviceType = vXAccessAudit.getServiceType(); + boolean isHive = "hive".equalsIgnoreCase(serviceType); + + if (!hiveQueryVisibility && isHive) { + vXAccessAudit.setRequestData(null); + } else if (isHive) { + String accessType = vXAccessAudit.getAccessType(); + + if ("grant".equalsIgnoreCase(accessType) || "revoke".equalsIgnoreCase(accessType)) { + String requestData = vXAccessAudit.getRequestData(); + + if (requestData != null) { + try { + vXAccessAudit.setRequestData(java.net.URLDecoder.decode(requestData, "UTF-8")); + } catch (UnsupportedEncodingException e) { + LOGGER.warn("Error while encoding request data:{}", requestData, e); + } + } else { + LOGGER.warn("Error in request data of audit from cloudwatch. AuditData:{} ", vXAccessAudit); + } + } + } + } + + xAccessAuditList.add(vXAccessAudit); + + recordCount++; + } + + returnList.setResultSize(result.size()); + returnList.setTotalCount(result.size()); + } + + returnList.setPageSize(searchCriteria.getMaxRows()); + returnList.setStartIndex(searchCriteria.getStartIndex()); + returnList.setVXAccessAudits(xAccessAuditList); + + return returnList; + } + + public void setRestErrorUtil(RESTErrorUtil restErrorUtil) { + this.restErrorUtil = restErrorUtil; + } + + public VXLong getXAccessAuditSearchCount(SearchCriteria searchCriteria) { + long count = 100; + VXLong vXLong = new VXLong(); + + vXLong.setValue(count); + + return vXLong; + } + + private VXAccessAudit populateViewBean(AuthzAuditEvent auditEvent) { + LOGGER.debug("doc= {}", auditEvent); + + VXAccessAudit accessAudit = new VXAccessAudit(); + Object value; + + value = auditEvent.getEventId(); + if (value != null) { + accessAudit.setId((long) value.hashCode()); + accessAudit.setEventId(value.toString()); + } + + value = auditEvent.getClusterName(); + if (value != null) { + accessAudit.setClusterName(value.toString()); + } + + value = auditEvent.getZoneName(); + if (value != null) { + accessAudit.setZoneName(value.toString()); + } + + value = auditEvent.getAgentHostname(); + if (value != null) { + accessAudit.setAgentHost(value.toString()); + } + + value = auditEvent.getPolicyVersion(); + if (value != null) { + accessAudit.setPolicyVersion(MiscUtil.toLong(value)); + } + + value = auditEvent.getAccessType(); + if (value != null) { + accessAudit.setAccessType(value.toString()); + } + + value = auditEvent.getAclEnforcer(); + if (value != null) { + accessAudit.setAclEnforcer(value.toString()); + } + + value = auditEvent.getAgentId(); + if (value != null) { + accessAudit.setAgentId(value.toString()); + } + + value = auditEvent.getRepositoryName(); + if (value != null) { + accessAudit.setRepoName(value.toString()); + + XXService xxService = daoManager.getXXService().findByName(accessAudit.getRepoName()); + + if (xxService != null) { + accessAudit.setRepoDisplayName(xxService.getDisplayName()); + } + } + + value = auditEvent.getSessionId(); + if (value != null) { + accessAudit.setSessionId(value.toString()); + } + + value = auditEvent.getUser(); + if (value != null) { + accessAudit.setRequestUser(value.toString()); + } + + value = auditEvent.getRequestData(); + if (value != null) { + accessAudit.setRequestData(value.toString()); + } + value = auditEvent.getResourcePath(); + if (value != null) { + accessAudit.setResourcePath(value.toString()); + } + + value = auditEvent.getClientIP(); + if (value != null) { + accessAudit.setClientIP(value.toString()); + } + + accessAudit.setAccessResult(auditEvent.getAccessResult()); + accessAudit.setPolicyId(auditEvent.getPolicyId()); + accessAudit.setRepoType(auditEvent.getRepositoryType()); + + XXServiceDef xServiceDef = daoManager.getXXServiceDef().getById((long) accessAudit.getRepoType()); + + if (xServiceDef != null) { + accessAudit.setServiceType(xServiceDef.getName()); + accessAudit.setServiceTypeDisplayName(xServiceDef.getDisplayName()); + } + + value = auditEvent.getResourceType(); + if (value != null) { + accessAudit.setResourceType(value.toString()); + } + + value = auditEvent.getResultReason(); + if (value != null) { + accessAudit.setResultReason(value.toString()); + } + + value = auditEvent.getAction(); + if (value != null) { + accessAudit.setAction(value.toString()); + } + + value = auditEvent.getEventTime(); + if (value != null) { + accessAudit.setEventTime(MiscUtil.toLocalDate(value)); + } + + accessAudit.setSequenceNumber(auditEvent.getSeqNum()); + accessAudit.setEventCount(auditEvent.getEventCount()); + accessAudit.setEventDuration(auditEvent.getEventDurationMS()); + + value = auditEvent.getTags(); + if (value != null) { + accessAudit.setTags(value.toString()); + } + + value = auditEvent.getDatasets(); + if (value != null) { + accessAudit.setDatasets(value.toString()); + } + + value = auditEvent.getProjects(); + if (value != null) { + accessAudit.setProjects(value.toString()); + } + + return accessAudit; + } +} diff --git a/security-admin/src/main/java/org/apache/ranger/amazon/cloudwatch/CloudWatchMgr.java b/security-admin/src/main/java/org/apache/ranger/amazon/cloudwatch/CloudWatchMgr.java index 4dcc6b2b88..ba08c6f404 100644 --- a/security-admin/src/main/java/org/apache/ranger/amazon/cloudwatch/CloudWatchMgr.java +++ b/security-admin/src/main/java/org/apache/ranger/amazon/cloudwatch/CloudWatchMgr.java @@ -19,60 +19,65 @@ package org.apache.ranger.amazon.cloudwatch; -import static org.apache.ranger.audit.destination.AmazonCloudWatchAuditDestination.CONFIG_PREFIX; -import static org.apache.ranger.audit.destination.AmazonCloudWatchAuditDestination.PROP_REGION; - +import com.amazonaws.services.logs.AWSLogs; +import com.amazonaws.services.logs.AWSLogsClientBuilder; import org.apache.commons.lang.StringUtils; import org.apache.ranger.common.PropertiesUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; -import com.amazonaws.services.logs.AWSLogs; -import com.amazonaws.services.logs.AWSLogsClientBuilder; +import static org.apache.ranger.audit.destination.AmazonCloudWatchAuditDestination.CONFIG_PREFIX; +import static org.apache.ranger.audit.destination.AmazonCloudWatchAuditDestination.PROP_REGION; /** * This class initializes the CloudWatch client - * */ @Component public class CloudWatchMgr { + private static final Logger LOGGER = LoggerFactory.getLogger(CloudWatchMgr.class); + + private AWSLogs client; + private String regionName; + + public AWSLogs getClient() { + AWSLogs me = client; + + if (me == null) { + me = connect(); + } + + return me; + } + + synchronized AWSLogs connect() { + AWSLogs me = client; + + if (me == null) { + synchronized (CloudWatchMgr.class) { + me = client; - private static final Logger LOGGER = LoggerFactory.getLogger(CloudWatchMgr.class); + if (me == null) { + try { + me = newClient(); + client = me; + } catch (Throwable t) { + LOGGER.error("Can't connect to CloudWatch region:{} ", regionName, t); + } + } + } + } - private AWSLogs client = null; - private String regionName; + return me; + } - synchronized void connect() { - if (client == null) { - synchronized (CloudWatchMgr.class) { - if (client == null) { - regionName = PropertiesUtil.getProperty(CONFIG_PREFIX + "." + PROP_REGION); - try { - client = newClient(); - } catch (Throwable t) { - LOGGER.error("Can't connect to CloudWatch region: " + regionName, t); - } - } - } - } - } + private AWSLogs newClient() { + regionName = PropertiesUtil.getProperty(CONFIG_PREFIX + "." + PROP_REGION); - public AWSLogs getClient() { - if (client == null) { - synchronized (CloudWatchMgr.class) { - if (client == null) { - connect(); - } - } - } - return client; - } + if (StringUtils.isBlank(regionName)) { + return AWSLogsClientBuilder.standard().build(); + } - private AWSLogs newClient() { - if (StringUtils.isBlank(regionName)) { - return AWSLogsClientBuilder.standard().build(); - } - return AWSLogsClientBuilder.standard().withRegion(regionName).build(); - } + return AWSLogsClientBuilder.standard().withRegion(regionName).build(); + } } diff --git a/security-admin/src/main/java/org/apache/ranger/amazon/cloudwatch/CloudWatchUtil.java b/security-admin/src/main/java/org/apache/ranger/amazon/cloudwatch/CloudWatchUtil.java index b7d3cad97b..ffe43582f6 100644 --- a/security-admin/src/main/java/org/apache/ranger/amazon/cloudwatch/CloudWatchUtil.java +++ b/security-admin/src/main/java/org/apache/ranger/amazon/cloudwatch/CloudWatchUtil.java @@ -19,241 +19,267 @@ package org.apache.ranger.amazon.cloudwatch; -import static org.apache.ranger.audit.destination.AmazonCloudWatchAuditDestination.CONFIG_PREFIX; -import static org.apache.ranger.audit.destination.AmazonCloudWatchAuditDestination.PROP_LOG_GROUP_NAME; -import static org.apache.ranger.audit.destination.AmazonCloudWatchAuditDestination.PROP_LOG_STREAM_PREFIX; - -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.Collection; -import java.util.Date; -import java.util.List; -import java.util.TimeZone; - +import com.amazonaws.services.logs.AWSLogs; +import com.amazonaws.services.logs.model.FilterLogEventsRequest; +import com.amazonaws.services.logs.model.FilterLogEventsResult; +import com.amazonaws.services.logs.model.FilteredLogEvent; import org.apache.commons.collections.CollectionUtils; -import org.apache.commons.lang.time.DateUtils; import org.apache.commons.lang.StringUtils; +import org.apache.commons.lang.time.DateUtils; import org.apache.ranger.common.PropertiesUtil; import org.apache.ranger.common.SearchCriteria; import org.apache.ranger.common.SearchField; import org.apache.ranger.common.SearchField.SEARCH_TYPE; import org.apache.ranger.common.SortField; -import org.apache.ranger.common.StringUtil; import org.apache.solr.client.solrj.util.ClientUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; -import com.amazonaws.services.logs.AWSLogs; -import com.amazonaws.services.logs.model.FilterLogEventsRequest; -import com.amazonaws.services.logs.model.FilterLogEventsResult; -import com.amazonaws.services.logs.model.FilteredLogEvent; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.Collection; +import java.util.Date; +import java.util.List; +import java.util.TimeZone; + +import static org.apache.ranger.audit.destination.AmazonCloudWatchAuditDestination.CONFIG_PREFIX; +import static org.apache.ranger.audit.destination.AmazonCloudWatchAuditDestination.PROP_LOG_GROUP_NAME; +import static org.apache.ranger.audit.destination.AmazonCloudWatchAuditDestination.PROP_LOG_STREAM_PREFIX; @Component public class CloudWatchUtil { - private static final Logger LOGGER = LoggerFactory.getLogger(CloudWatchUtil.class); - - @Autowired - StringUtil stringUtil; - - String dateFormateStr = "yyyy-MM-dd'T'HH:mm:ss'Z'"; - SimpleDateFormat dateFormat = new SimpleDateFormat(dateFormateStr); - private String logGroupName; - private String logStreamPrefix; - - public CloudWatchUtil() { - logGroupName = PropertiesUtil.getProperty(CONFIG_PREFIX + "." + PROP_LOG_GROUP_NAME, "ranger_audits"); - logStreamPrefix = PropertiesUtil.getProperty(CONFIG_PREFIX + "." + PROP_LOG_STREAM_PREFIX, ""); - String timeZone = PropertiesUtil.getProperty("ranger.cloudwatch.timezone"); - if (timeZone != null) { - LOGGER.info("Setting timezone to " + timeZone); - try { - dateFormat.setTimeZone(TimeZone.getTimeZone(timeZone)); - } catch (Throwable t) { - LOGGER.error("Error setting timezone. TimeZone = " + timeZone); - } - } - } - - public List searchResources(AWSLogs client, SearchCriteria searchCriteria, - List searchFields, List sortFieldList) { - List result = new ArrayList(); - try { - String nextToken = null; - FilterLogEventsRequest filterLogEventsRequest = getFilterLogEventsRequest(client, searchCriteria, searchFields); - boolean done = false; - //TODO: Improve response time - //This approach is slow as cloudwatch doesn't provide timestamp based sorting in descending order - do { - if (nextToken != null) { - filterLogEventsRequest = filterLogEventsRequest.withNextToken(nextToken); - } - - FilterLogEventsResult response = client.filterLogEvents(filterLogEventsRequest); - if (response != null) { - if (CollectionUtils.isNotEmpty(response.getEvents())) { - //To handle outofmemory issue, max 10k records are stored in the list - if (result.size() > 10000) { - result.clear(); - } - result.addAll(response.getEvents()); - } else { - done = true; - break; - } - // check if token is the same - if (response.getNextToken().equals(nextToken)) { - done = true; - break; - } - // save new token - nextToken = response.getNextToken(); - if (nextToken == null) { - done = true; - break; - } - } - } while (!done); - LOGGER.info("Successfully got CloudWatch log events!"); - } catch (Exception e) { - LOGGER.error("Error searching records from CloudWatch", e); - } - return result; - } - - public FilterLogEventsRequest getFilterLogEventsRequest(AWSLogs client, SearchCriteria searchCriteria, - List searchFields) { - FilterLogEventsRequest filterLogEventsRequest = null; - StringBuilder filterPattern = new StringBuilder(""); - Date fromDate = null; - Date toDate = null; - - if (searchCriteria.getParamList() != null) { - List filterExpr = new ArrayList(); - - for (SearchField searchField : searchFields) { - Object paramValue = searchCriteria.getParamValue(searchField.getClientFieldName()); - if (paramValue == null || paramValue.toString().isEmpty()) { - continue; - } - - String fieldName = searchField.getFieldName(); - if (searchField.getDataType() == SearchField.DATA_TYPE.DATE) { - if (!(paramValue instanceof Date)) { - LOGGER.error("Search field is not a Java Date Object, paramValue = " + paramValue); - } else { - if (searchField.getSearchType() == SEARCH_TYPE.GREATER_EQUAL_THAN || searchField.getSearchType() == SEARCH_TYPE.GREATER_THAN) { - fromDate = (Date) paramValue; - } else if (searchField.getSearchType() == SEARCH_TYPE.LESS_EQUAL_THAN || searchField.getSearchType() == SEARCH_TYPE.LESS_THAN) { - toDate = (Date) paramValue; - } - } - } else if (paramValue instanceof Collection) { - String fq = orList(fieldName, (Collection) paramValue); - if (StringUtils.isNotBlank(fq)) { - filterExpr.add(fq); - } - } else { - String fq = null; - if (searchField.getSearchType() == SEARCH_TYPE.PARTIAL) { - fq = setFieldForPartialSearch(fieldName, paramValue); - } else { - fq = setField(fieldName, paramValue); - } - if (StringUtils.isNotBlank(fq)) { - filterExpr.add(fq); - } - } - } - - if (fromDate == null) { - fromDate = DateUtils.truncate(new Date(), Calendar.DAY_OF_MONTH); - } - if (toDate == null) { - Date today = DateUtils.truncate(new Date(), Calendar.DAY_OF_MONTH); - toDate = DateUtils.addDays(today, 1); - } - - // Syntax : { ($.user.id = 1) && ($.users[0].email = "user@example.com") } - if (CollectionUtils.isNotEmpty(filterExpr)) { - String strExpr = ""; - int count = -1; - for (String fq : filterExpr) { - count++; - if (count > 0) { - strExpr += " &&"; - } - strExpr = strExpr.concat("(" + fq + ")"); - } - if (strExpr.endsWith("&&")) { - strExpr = strExpr.substring(0, strExpr.length() - 3); - } - if (StringUtils.isNotBlank(strExpr)) { - filterPattern.append("{" + strExpr + "}"); - } - } - } - - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("filterExpression for cloudwatch request " + filterPattern.toString()); - } - - // Add FilterPattern which will only fetch logs required - filterLogEventsRequest = new FilterLogEventsRequest() - .withLogGroupName(logGroupName) - .withStartTime(fromDate.getTime()) - .withEndTime(toDate.getTime()) - .withFilterPattern(filterPattern.toString()); - - if (StringUtils.isNotBlank(logStreamPrefix)) { - filterLogEventsRequest.setLogStreamNamePrefix(logStreamPrefix); - } - - return filterLogEventsRequest; - } - - //Syntax { $.user.email = "user@example.com" || $.coordinates[0][1] = nonmatch && $.actions[2] = nomatch } - private String orList(String fieldName, Collection valueList) { - if (valueList == null || valueList.isEmpty()) { - return null; - } - String expr = ""; - int count = -1; - for (Object value : valueList) { - count++; - if (count > 0) { - expr += " || "; - } - expr += setField(fieldName, value); - } - return expr; - } - - private String setField(String fieldName, Object value) { - if (value == null || StringUtils.isBlank(value.toString())) { - return null; - } - if (value instanceof Integer || value instanceof Long) { - if (fieldName.startsWith("-")) { - fieldName = fieldName.substring(1); - return "$." + fieldName + " != " + ClientUtils.escapeQueryChars(value.toString().trim().toLowerCase()); - } - return "$." + fieldName + " = " + ClientUtils.escapeQueryChars(value.toString().trim().toLowerCase()); - } - if (fieldName.startsWith("-")) { - fieldName = fieldName.substring(1); - return "$." + fieldName + " != \"" + ClientUtils.escapeQueryChars(value.toString().trim().toLowerCase()) + "\""; - } - return "$." + fieldName + " = \"" + ClientUtils.escapeQueryChars(value.toString().trim().toLowerCase()) + "\""; - } - - private String setFieldForPartialSearch(String fieldName, Object value) { - if (value == null || StringUtils.isBlank(value.toString())) { - return null; - } - return "$." + fieldName + "= \"*" + ClientUtils.escapeQueryChars(value.toString().trim().toLowerCase()) + "*\""; - } + private static final Logger LOGGER = LoggerFactory.getLogger(CloudWatchUtil.class); + + String dateFormateStr = "yyyy-MM-dd'T'HH:mm:ss'Z'"; + SimpleDateFormat dateFormat = new SimpleDateFormat(dateFormateStr); + + private final String logGroupName; + private final String logStreamPrefix; + + public CloudWatchUtil() { + logGroupName = PropertiesUtil.getProperty(CONFIG_PREFIX + "." + PROP_LOG_GROUP_NAME, "ranger_audits"); + logStreamPrefix = PropertiesUtil.getProperty(CONFIG_PREFIX + "." + PROP_LOG_STREAM_PREFIX, ""); + + String timeZone = PropertiesUtil.getProperty("ranger.cloudwatch.timezone"); + + if (timeZone != null) { + LOGGER.info("Setting timezone to {}", timeZone); + + try { + dateFormat.setTimeZone(TimeZone.getTimeZone(timeZone)); + } catch (Throwable t) { + LOGGER.error("Error setting timezone. TimeZone ={} ", timeZone); + } + } + } + + public List searchResources(AWSLogs client, SearchCriteria searchCriteria, List searchFields, List sortFieldList) { + List result = new ArrayList(); + + try { + String nextToken = null; + FilterLogEventsRequest filterLogEventsRequest = getFilterLogEventsRequest(client, searchCriteria, searchFields); + boolean done = false; + + //TODO: Improve response time + //This approach is slow as cloudwatch doesn't provide timestamp based sorting in descending order + do { + if (nextToken != null) { + filterLogEventsRequest = filterLogEventsRequest.withNextToken(nextToken); + } + + FilterLogEventsResult response = client.filterLogEvents(filterLogEventsRequest); + + if (response != null) { + if (CollectionUtils.isNotEmpty(response.getEvents())) { + //To handle outofmemory issue, max 10k records are stored in the list + if (result.size() > 10000) { + result.clear(); + } + + result.addAll(response.getEvents()); + } else { + done = true; + break; + } + + // check if token is the same + if (response.getNextToken().equals(nextToken)) { + done = true; + break; + } + + // save new token + nextToken = response.getNextToken(); + + if (nextToken == null) { + done = true; + break; + } + } + } + while (!done); + + LOGGER.info("Successfully got CloudWatch log events!"); + } catch (Exception e) { + LOGGER.error("Error searching records from CloudWatch", e); + } + + return result; + } + + public FilterLogEventsRequest getFilterLogEventsRequest(AWSLogs client, SearchCriteria searchCriteria, List searchFields) { + StringBuilder filterPattern = new StringBuilder(); + Date fromDate = null; + Date toDate = null; + + if (searchCriteria.getParamList() != null) { + List filterExpr = new ArrayList(); + + for (SearchField searchField : searchFields) { + Object paramValue = searchCriteria.getParamValue(searchField.getClientFieldName()); + + if (paramValue == null || paramValue.toString().isEmpty()) { + continue; + } + + String fieldName = searchField.getFieldName(); + + if (searchField.getDataType() == SearchField.DATA_TYPE.DATE) { + if (!(paramValue instanceof Date)) { + LOGGER.error("Search field is not a Java Date Object, paramValue = {}", paramValue); + } else { + if (searchField.getSearchType() == SEARCH_TYPE.GREATER_EQUAL_THAN || searchField.getSearchType() == SEARCH_TYPE.GREATER_THAN) { + fromDate = (Date) paramValue; + } else if (searchField.getSearchType() == SEARCH_TYPE.LESS_EQUAL_THAN || searchField.getSearchType() == SEARCH_TYPE.LESS_THAN) { + toDate = (Date) paramValue; + } + } + } else if (paramValue instanceof Collection) { + String fq = orList(fieldName, (Collection) paramValue); + + if (StringUtils.isNotBlank(fq)) { + filterExpr.add(fq); + } + } else { + String fq; + + if (searchField.getSearchType() == SEARCH_TYPE.PARTIAL) { + fq = setFieldForPartialSearch(fieldName, paramValue); + } else { + fq = setField(fieldName, paramValue); + } + + if (StringUtils.isNotBlank(fq)) { + filterExpr.add(fq); + } + } + } + + if (fromDate == null) { + fromDate = DateUtils.truncate(new Date(), Calendar.DAY_OF_MONTH); + } + + if (toDate == null) { + Date today = DateUtils.truncate(new Date(), Calendar.DAY_OF_MONTH); + + toDate = DateUtils.addDays(today, 1); + } + + // Syntax : { ($.user.id = 1) && ($.users[0].email = "user@example.com") } + if (CollectionUtils.isNotEmpty(filterExpr)) { + String strExpr = ""; + int count = -1; + + for (String fq : filterExpr) { + count++; + + if (count > 0) { + strExpr += " &&"; + } + + strExpr = strExpr.concat("(" + fq + ")"); + } + + if (strExpr.endsWith("&&")) { + strExpr = strExpr.substring(0, strExpr.length() - 3); + } + + if (StringUtils.isNotBlank(strExpr)) { + filterPattern.append("{" + strExpr + "}"); + } + } + } + + LOGGER.debug("filterExpression for cloudwatch request {}", filterPattern); + + // Add FilterPattern which will only fetch logs required + FilterLogEventsRequest filterLogEventsRequest = new FilterLogEventsRequest() + .withLogGroupName(logGroupName) + .withStartTime(fromDate.getTime()) + .withEndTime(toDate.getTime()) + .withFilterPattern(filterPattern.toString()); + + if (StringUtils.isNotBlank(logStreamPrefix)) { + filterLogEventsRequest.setLogStreamNamePrefix(logStreamPrefix); + } + + return filterLogEventsRequest; + } + + //Syntax { $.user.email = "user@example.com" || $.coordinates[0][1] = nonmatch && $.actions[2] = nomatch } + private String orList(String fieldName, Collection valueList) { + if (valueList == null || valueList.isEmpty()) { + return null; + } + + String expr = ""; + int count = -1; + + for (Object value : valueList) { + count++; + + if (count > 0) { + expr += " || "; + } + + expr += setField(fieldName, value); + } + + return expr; + } + + private String setField(String fieldName, Object value) { + if (value == null || StringUtils.isBlank(value.toString())) { + return null; + } + + if (value instanceof Integer || value instanceof Long) { + if (fieldName.startsWith("-")) { + fieldName = fieldName.substring(1); + + return "$." + fieldName + " != " + ClientUtils.escapeQueryChars(value.toString().trim().toLowerCase()); + } + + return "$." + fieldName + " = " + ClientUtils.escapeQueryChars(value.toString().trim().toLowerCase()); + } + + if (fieldName.startsWith("-")) { + fieldName = fieldName.substring(1); + + return "$." + fieldName + " != \"" + ClientUtils.escapeQueryChars(value.toString().trim().toLowerCase()) + "\""; + } + + return "$." + fieldName + " = \"" + ClientUtils.escapeQueryChars(value.toString().trim().toLowerCase()) + "\""; + } + + private String setFieldForPartialSearch(String fieldName, Object value) { + if (value == null || StringUtils.isBlank(value.toString())) { + return null; + } + return "$." + fieldName + "= \"*" + ClientUtils.escapeQueryChars(value.toString().trim().toLowerCase()) + "*\""; + } } 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 index b10ac1bf13..6f6404fecd 100644 --- 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 @@ -17,24 +17,22 @@ * under the License. */ - package org.apache.ranger.authentication.unix.jaas; +package org.apache.ranger.authentication.unix.jaas; + +import org.springframework.security.authentication.jaas.AuthorityGranter; 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 grant(Principal principal) { - if (principal instanceof UnixGroupPrincipal) { - Collections.singleton(principal.getName()); - } - else { - Collections.singleton("ROLE_USER"); - } - return null; - } + @Override + public Set grant(Principal principal) { + if (principal instanceof UnixGroupPrincipal) { + Collections.singleton(principal.getName()); + } else { + Collections.singleton("ROLE_USER"); + } + return null; + } } From 9c3ac972f60bba28a6751d830b51d1ef238d484f Mon Sep 17 00:00:00 2001 From: Vyom Mani Tiwari Date: Sat, 4 Jan 2025 00:47:39 +0530 Subject: [PATCH 04/15] RANGER-5061: security-admin module(elasticsearch package): update for code readability improvement (#488) * RANGER-5069: Add ability to Kafka authorizer to define super users through Kafka config Co-authored-by: Daniel Fonai Signed-off-by: Madhan Neethiraj --- .../ElasticSearchAccessAuditsService.java | 541 +++++++++--------- .../elasticsearch/ElasticSearchMgr.java | 220 +++---- .../elasticsearch/ElasticSearchUtil.java | 130 +++-- 3 files changed, 486 insertions(+), 405 deletions(-) diff --git a/security-admin/src/main/java/org/apache/ranger/elasticsearch/ElasticSearchAccessAuditsService.java b/security-admin/src/main/java/org/apache/ranger/elasticsearch/ElasticSearchAccessAuditsService.java index a64cb111ea..4f6c808ff2 100644 --- a/security-admin/src/main/java/org/apache/ranger/elasticsearch/ElasticSearchAccessAuditsService.java +++ b/security-admin/src/main/java/org/apache/ranger/elasticsearch/ElasticSearchAccessAuditsService.java @@ -27,10 +27,10 @@ import org.apache.ranger.db.XXServiceDefDao; import org.apache.ranger.entity.XXService; import org.apache.ranger.entity.XXServiceDef; +import org.apache.ranger.plugin.util.JsonUtilsV2; import org.apache.ranger.view.VXAccessAudit; import org.apache.ranger.view.VXAccessAuditList; import org.apache.ranger.view.VXLong; -import org.apache.ranger.plugin.util.JsonUtilsV2; import org.elasticsearch.action.get.GetResponse; import org.elasticsearch.action.get.MultiGetItemResponse; import org.elasticsearch.action.search.SearchResponse; @@ -50,260 +50,289 @@ @Service @Scope("singleton") public class ElasticSearchAccessAuditsService extends org.apache.ranger.AccessAuditsService { - private static final Logger LOGGER = LoggerFactory.getLogger(ElasticSearchAccessAuditsService.class); - - @Autowired - ElasticSearchMgr elasticSearchMgr; - - @Autowired - ElasticSearchUtil elasticSearchUtil; - - - public VXAccessAuditList searchXAccessAudits(SearchCriteria searchCriteria) { - - RestHighLevelClient client = elasticSearchMgr.getClient(); - final boolean hiveQueryVisibility = PropertiesUtil.getBooleanProperty("ranger.audit.hive.query.visibility", true); - if (client == null) { - LOGGER.warn("ElasticSearch client is null, so not running the query."); - throw restErrorUtil.createRESTException( - "Error connecting to search engine", - MessageEnums.ERROR_SYSTEM); - } - List xAccessAuditList = new ArrayList(); - Map paramList = searchCriteria.getParamList(); - updateUserExclusion(paramList); - - SearchResponse response; - try { - response = elasticSearchUtil.searchResources(searchCriteria, searchFields, sortFields, client, elasticSearchMgr.index); - } catch (IOException e) { - LOGGER.warn(String.format("ElasticSearch query failed: %s", e.getMessage())); - throw restErrorUtil.createRESTException( - "Error querying search engine", - MessageEnums.ERROR_SYSTEM); - } - MultiGetItemResponse[] docs; - try { - docs = elasticSearchUtil.fetch(client, elasticSearchMgr.index, response.getHits().getHits()); - } catch (IOException e) { - LOGGER.warn(String.format("ElasticSearch fetch failed: %s", e.getMessage())); - throw restErrorUtil.createRESTException( - "Error querying search engine", - MessageEnums.ERROR_SYSTEM); - } - for (int i = 0; i < docs.length; i++) { // NOPMD - This for loop can be replaced by a foreach loop - MultiGetItemResponse doc = docs[i]; - VXAccessAudit vXAccessAudit = populateViewBean(doc.getResponse()); - if (vXAccessAudit != null) { - String serviceType = vXAccessAudit.getServiceType(); - boolean isHive = "hive".equalsIgnoreCase(serviceType); - if (!hiveQueryVisibility && isHive) { - vXAccessAudit.setRequestData(null); - } else if (isHive) { - String accessType = vXAccessAudit.getAccessType(); - if ("grant".equalsIgnoreCase(accessType) - || "revoke".equalsIgnoreCase(accessType)) { - String requestData = vXAccessAudit.getRequestData(); - if (requestData != null) { - try { - vXAccessAudit.setRequestData( - java.net.URLDecoder.decode(requestData, "UTF-8")); - } catch (UnsupportedEncodingException e) { - LOGGER.warn("Error while encoding request data: " + requestData, e); - } - } else { - LOGGER.warn( - "Error in request data of audit from elasticSearch. AuditData: " - + vXAccessAudit.toString()); - } - } - } - } - xAccessAuditList.add(vXAccessAudit); - } - - VXAccessAuditList returnList = new VXAccessAuditList(); - returnList.setPageSize(searchCriteria.getMaxRows()); - returnList.setResultSize(response.getHits().getHits().length); - returnList.setTotalCount(response.getHits().getTotalHits().value); - returnList.setStartIndex(searchCriteria.getStartIndex()); - returnList.setVXAccessAudits(xAccessAuditList); - return returnList; - } - - public void setRestErrorUtil(RESTErrorUtil restErrorUtil) { - this.restErrorUtil = restErrorUtil; - } - - - /** - * @param doc - * @return - */ - private VXAccessAudit populateViewBean(GetResponse doc) { - VXAccessAudit accessAudit = new VXAccessAudit(); - - Object value = null; - if(LOGGER.isDebugEnabled()) { - LOGGER.debug("doc=" + doc.toString()); - } - - Map source = doc.getSource(); - value = source.get("id"); - if (value != null) { - // TODO: Converting ID to hashcode for now - accessAudit.setId((long) value.hashCode()); - } - - value = source.get("cluster"); - if (value != null) { - accessAudit.setClusterName(value.toString()); - } - - value = source.get("zoneName"); - if (value != null) { - accessAudit.setZoneName(value.toString()); - } - - value = source.get("agentHost"); - if (value != null) { - accessAudit.setAgentHost(value.toString()); - } - - value = source.get("policyVersion"); - if (value != null) { - accessAudit.setPolicyVersion(MiscUtil.toLong(value)); - } - - value = source.get("access"); - if (value != null) { - accessAudit.setAccessType(value.toString()); - } - - value = source.get("enforcer"); - if (value != null) { - accessAudit.setAclEnforcer(value.toString()); - } - value = source.get("agent"); - if (value != null) { - accessAudit.setAgentId(value.toString()); - } - value = source.get("repo"); - if (value != null) { - accessAudit.setRepoName(value.toString()); - XXService xxService = daoManager.getXXService().findByName(accessAudit.getRepoName()); - - if(xxService != null) { - accessAudit.setRepoDisplayName(xxService.getDisplayName()); - } - } - value = source.get("sess"); - if (value != null) { - accessAudit.setSessionId(value.toString()); - } - value = source.get("reqUser"); - if (value != null) { - accessAudit.setRequestUser(value.toString()); - } - value = source.get("reqData"); - if (value != null) { - accessAudit.setRequestData(value.toString()); - } - value = source.get("resource"); - if (value != null) { - accessAudit.setResourcePath(value.toString()); - } - value = source.get("cliIP"); - if (value != null) { - accessAudit.setClientIP(value.toString()); - } - value = source.get("logType"); - //if (value != null) { - // TODO: Need to see what logType maps to in UI -// accessAudit.setAuditType(solrUtil.toInt(value)); - //} - value = source.get("result"); - if (value != null) { - accessAudit.setAccessResult(MiscUtil.toInt(value)); - } - value = source.get("policy"); - if (value != null) { - accessAudit.setPolicyId(MiscUtil.toLong(value)); - } - value = source.get("repoType"); - if (value != null) { - accessAudit.setRepoType(MiscUtil.toInt(value)); - if(null != daoManager) { - XXServiceDefDao xxServiceDef = daoManager.getXXServiceDef(); - if(xxServiceDef != null) { - XXServiceDef xServiceDef = xxServiceDef.getById((long) accessAudit.getRepoType()); - if (xServiceDef != null) { - accessAudit.setServiceType(xServiceDef.getName()); - accessAudit.setServiceTypeDisplayName(xServiceDef.getDisplayName()); - } - } - } - } - value = source.get("resType"); - if (value != null) { - accessAudit.setResourceType(value.toString()); - } - value = source.get("reason"); - if (value != null) { - accessAudit.setResultReason(value.toString()); - } - value = source.get("action"); - if (value != null) { - accessAudit.setAction(value.toString()); - } - value = source.get("evtTime"); - if (value != null) { - accessAudit.setEventTime(MiscUtil.toLocalDate(value)); - } - value = source.get("seq_num"); - if (value != null) { - accessAudit.setSequenceNumber(MiscUtil.toLong(value)); - } - value = source.get("event_count"); - if (value != null) { - accessAudit.setEventCount(MiscUtil.toLong(value)); - } - value = source.get("event_dur_ms"); - if (value != null) { - accessAudit.setEventDuration(MiscUtil.toLong(value)); - } - value = source.get("tags"); - if (value != null) { - accessAudit.setTags(value.toString()); - } - value = source.get("datasets"); - if (value != null) { - try { - accessAudit.setDatasets(JsonUtilsV2.nonSerializableObjToJson(value)); - } catch (Exception e) { - LOGGER.warn("Failed to convert datasets to json", e); - } - } - value = source.get("projects"); - if (value != null) { - try { - accessAudit.setProjects(JsonUtilsV2.nonSerializableObjToJson(value)); - } catch (Exception e) { - LOGGER.warn("Failed to convert projects to json", e); - } - } - return accessAudit; - } - - /** - * @param searchCriteria - * @return - */ - public VXLong getXAccessAuditSearchCount(SearchCriteria searchCriteria) { - long count = 100; - VXLong vXLong = new VXLong(); - vXLong.setValue(count); - return vXLong; - } + private static final Logger LOGGER = LoggerFactory.getLogger(ElasticSearchAccessAuditsService.class); + + @Autowired + ElasticSearchMgr elasticSearchMgr; + + @Autowired + ElasticSearchUtil elasticSearchUtil; + + public VXAccessAuditList searchXAccessAudits(SearchCriteria searchCriteria) { + RestHighLevelClient client = elasticSearchMgr.getClient(); + final boolean hiveQueryVisibility = PropertiesUtil.getBooleanProperty("ranger.audit.hive.query.visibility", true); + + if (client == null) { + LOGGER.warn("ElasticSearch client is null, so not running the query."); + + throw restErrorUtil.createRESTException("Error connecting to search engine", MessageEnums.ERROR_SYSTEM); + } + + List xAccessAuditList = new ArrayList(); + Map paramList = searchCriteria.getParamList(); + + updateUserExclusion(paramList); + + SearchResponse response; + + try { + response = elasticSearchUtil.searchResources(searchCriteria, searchFields, sortFields, client, elasticSearchMgr.index); + } catch (IOException e) { + LOGGER.warn("ElasticSearch query failed: {}", e.getMessage()); + + throw restErrorUtil.createRESTException("Error querying search engine", MessageEnums.ERROR_SYSTEM); + } + + MultiGetItemResponse[] docs; + + try { + docs = elasticSearchUtil.fetch(client, elasticSearchMgr.index, response.getHits().getHits()); + } catch (IOException e) { + LOGGER.warn("ElasticSearch fetch failed: {}", e.getMessage()); + + throw restErrorUtil.createRESTException("Error querying search engine", MessageEnums.ERROR_SYSTEM); + } + + for (int i = 0; i < docs.length; i++) { // NOPMD - This for loop can be replaced by a foreach loop + MultiGetItemResponse doc = docs[i]; + VXAccessAudit vXAccessAudit = populateViewBean(doc.getResponse()); + + if (vXAccessAudit != null) { + String serviceType = vXAccessAudit.getServiceType(); + boolean isHive = "hive".equalsIgnoreCase(serviceType); + + if (!hiveQueryVisibility && isHive) { + vXAccessAudit.setRequestData(null); + } else if (isHive) { + String accessType = vXAccessAudit.getAccessType(); + + if ("grant".equalsIgnoreCase(accessType) || "revoke".equalsIgnoreCase(accessType)) { + String requestData = vXAccessAudit.getRequestData(); + + if (requestData != null) { + try { + vXAccessAudit.setRequestData(java.net.URLDecoder.decode(requestData, "UTF-8")); + } catch (UnsupportedEncodingException e) { + LOGGER.warn("Error while encoding request data: {}", requestData, e); + } + } else { + LOGGER.warn("Error in request data of audit from elasticSearch. AuditData: {}", vXAccessAudit); + } + } + } + } + + xAccessAuditList.add(vXAccessAudit); + } + + VXAccessAuditList returnList = new VXAccessAuditList(); + + returnList.setPageSize(searchCriteria.getMaxRows()); + returnList.setResultSize(response.getHits().getHits().length); + returnList.setTotalCount(response.getHits().getTotalHits().value); + returnList.setStartIndex(searchCriteria.getStartIndex()); + returnList.setVXAccessAudits(xAccessAuditList); + + return returnList; + } + + public void setRestErrorUtil(RESTErrorUtil restErrorUtil) { + this.restErrorUtil = restErrorUtil; + } + + /** + * @param searchCriteria + * @return + */ + public VXLong getXAccessAuditSearchCount(SearchCriteria searchCriteria) { + long count = 100; + VXLong vXLong = new VXLong(); + + vXLong.setValue(count); + + return vXLong; + } + + /** + * @param doc + * @return + */ + private VXAccessAudit populateViewBean(GetResponse doc) { + LOGGER.debug("doc={}", doc); + + VXAccessAudit accessAudit = new VXAccessAudit(); + Map source = doc.getSource(); + Object value; + + value = source.get("id"); + if (value != null) { + // TODO: Converting ID to hashcode for now + accessAudit.setId((long) value.hashCode()); + } + + value = source.get("cluster"); + if (value != null) { + accessAudit.setClusterName(value.toString()); + } + + value = source.get("zoneName"); + if (value != null) { + accessAudit.setZoneName(value.toString()); + } + + value = source.get("agentHost"); + if (value != null) { + accessAudit.setAgentHost(value.toString()); + } + + value = source.get("policyVersion"); + if (value != null) { + accessAudit.setPolicyVersion(MiscUtil.toLong(value)); + } + + value = source.get("access"); + if (value != null) { + accessAudit.setAccessType(value.toString()); + } + + value = source.get("enforcer"); + if (value != null) { + accessAudit.setAclEnforcer(value.toString()); + } + + value = source.get("agent"); + if (value != null) { + accessAudit.setAgentId(value.toString()); + } + + value = source.get("repo"); + if (value != null) { + accessAudit.setRepoName(value.toString()); + + XXService xxService = daoManager.getXXService().findByName(accessAudit.getRepoName()); + + if (xxService != null) { + accessAudit.setRepoDisplayName(xxService.getDisplayName()); + } + } + + value = source.get("sess"); + if (value != null) { + accessAudit.setSessionId(value.toString()); + } + + value = source.get("reqUser"); + if (value != null) { + accessAudit.setRequestUser(value.toString()); + } + + value = source.get("reqData"); + if (value != null) { + accessAudit.setRequestData(value.toString()); + } + + value = source.get("resource"); + if (value != null) { + accessAudit.setResourcePath(value.toString()); + } + + value = source.get("cliIP"); + if (value != null) { + accessAudit.setClientIP(value.toString()); + } + + // TODO: Need to see what logType maps to in UI + //value = source.get("logType"); + //if (value != null) { + // accessAudit.setAuditType(solrUtil.toInt(value)); + //} + + value = source.get("result"); + if (value != null) { + accessAudit.setAccessResult(MiscUtil.toInt(value)); + } + + value = source.get("policy"); + if (value != null) { + accessAudit.setPolicyId(MiscUtil.toLong(value)); + } + + value = source.get("repoType"); + if (value != null) { + accessAudit.setRepoType(MiscUtil.toInt(value)); + + if (null != daoManager) { + XXServiceDefDao xxServiceDef = daoManager.getXXServiceDef(); + + if (xxServiceDef != null) { + XXServiceDef xServiceDef = xxServiceDef.getById((long) accessAudit.getRepoType()); + + if (xServiceDef != null) { + accessAudit.setServiceType(xServiceDef.getName()); + accessAudit.setServiceTypeDisplayName(xServiceDef.getDisplayName()); + } + } + } + } + + value = source.get("resType"); + if (value != null) { + accessAudit.setResourceType(value.toString()); + } + + value = source.get("reason"); + if (value != null) { + accessAudit.setResultReason(value.toString()); + } + + value = source.get("action"); + if (value != null) { + accessAudit.setAction(value.toString()); + } + + value = source.get("evtTime"); + if (value != null) { + accessAudit.setEventTime(MiscUtil.toLocalDate(value)); + } + + value = source.get("seq_num"); + if (value != null) { + accessAudit.setSequenceNumber(MiscUtil.toLong(value)); + } + + value = source.get("event_count"); + if (value != null) { + accessAudit.setEventCount(MiscUtil.toLong(value)); + } + + value = source.get("event_dur_ms"); + if (value != null) { + accessAudit.setEventDuration(MiscUtil.toLong(value)); + } + + value = source.get("tags"); + if (value != null) { + accessAudit.setTags(value.toString()); + } + + value = source.get("datasets"); + if (value != null) { + try { + accessAudit.setDatasets(JsonUtilsV2.nonSerializableObjToJson(value)); + } catch (Exception e) { + LOGGER.warn("Failed to convert datasets to json", e); + } + } + + value = source.get("projects"); + if (value != null) { + try { + accessAudit.setProjects(JsonUtilsV2.nonSerializableObjToJson(value)); + } catch (Exception e) { + LOGGER.warn("Failed to convert projects to json", e); + } + } + return accessAudit; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/elasticsearch/ElasticSearchMgr.java b/security-admin/src/main/java/org/apache/ranger/elasticsearch/ElasticSearchMgr.java index 6987f6eb1a..2895782905 100644 --- a/security-admin/src/main/java/org/apache/ranger/elasticsearch/ElasticSearchMgr.java +++ b/security-admin/src/main/java/org/apache/ranger/elasticsearch/ElasticSearchMgr.java @@ -47,110 +47,134 @@ import java.util.Date; import java.util.Locale; -import static org.apache.ranger.audit.destination.ElasticSearchAuditDestination.*; +import static org.apache.ranger.audit.destination.ElasticSearchAuditDestination.CONFIG_INDEX; +import static org.apache.ranger.audit.destination.ElasticSearchAuditDestination.CONFIG_PORT; +import static org.apache.ranger.audit.destination.ElasticSearchAuditDestination.CONFIG_PREFIX; +import static org.apache.ranger.audit.destination.ElasticSearchAuditDestination.CONFIG_PROTOCOL; +import static org.apache.ranger.audit.destination.ElasticSearchAuditDestination.CONFIG_PWRD; +import static org.apache.ranger.audit.destination.ElasticSearchAuditDestination.CONFIG_URLS; +import static org.apache.ranger.audit.destination.ElasticSearchAuditDestination.CONFIG_USER; /** * This class initializes the ElasticSearch client - * */ @Component public class ElasticSearchMgr { + private static final Logger logger = LoggerFactory.getLogger(ElasticSearchMgr.class); + + public String index; + + Subject subject; + String user; + String password; + RestHighLevelClient client; + + public static RestClientBuilder getRestClientBuilder(String urls, String protocol, String user, String password, int port) { + RestClientBuilder restClientBuilder = RestClient.builder(MiscUtil.toArray(urls, ",").stream().map(x -> new HttpHost(x, port, protocol)).toArray(i -> new HttpHost[i])); + + if (StringUtils.isNotBlank(user) && StringUtils.isNotBlank(password) && !user.equalsIgnoreCase("NONE") && !password.equalsIgnoreCase("NONE")) { + if (password.contains("keytab") && new File(password).exists()) { + final KerberosCredentialsProvider credentialsProvider = CredentialsProviderUtil.getKerberosCredentials(user, password); + Lookup authSchemeRegistry = RegistryBuilder.create().register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory()).build(); + + restClientBuilder.setHttpClientConfigCallback(clientBuilder -> { + clientBuilder.setDefaultCredentialsProvider(credentialsProvider); + clientBuilder.setDefaultAuthSchemeRegistry(authSchemeRegistry); + + return clientBuilder; + }); + } else { + final CredentialsProvider credentialsProvider = CredentialsProviderUtil.getBasicCredentials(user, password); + + restClientBuilder.setHttpClientConfigCallback(clientBuilder -> clientBuilder.setDefaultCredentialsProvider(credentialsProvider)); + } + } else { + logger.error("ElasticSearch Credentials not provided!!"); + + final CredentialsProvider credentialsProvider = null; + + restClientBuilder.setHttpClientConfigCallback(clientBuilder -> clientBuilder.setDefaultCredentialsProvider(credentialsProvider)); + } + + return restClientBuilder; + } + + public RestHighLevelClient getClient() { + RestHighLevelClient me = client; + + if (me != null && subject != null) { + KerberosTicket ticket = CredentialsProviderUtil.getTGT(subject); + + try { + if (new Date().getTime() > ticket.getEndTime().getTime()) { + client = null; + CredentialsProviderUtil.ticketExpireTime80 = 0; + + me = connect(); + } else if (CredentialsProviderUtil.ticketWillExpire(ticket)) { + subject = CredentialsProviderUtil.login(user, password); + } + } catch (PrivilegedActionException e) { + logger.error("PrivilegedActionException:", e); + + throw new RuntimeException(e); + } + + return me; + } else { + me = connect(); + } + + return me; + } + + synchronized RestHighLevelClient connect() { + RestHighLevelClient me = client; + + if (me == null) { + synchronized (ElasticSearchAuditDestination.class) { + me = client; + + if (me == null) { + String urls = PropertiesUtil.getProperty(CONFIG_PREFIX + "." + CONFIG_URLS); + String protocol = PropertiesUtil.getProperty(CONFIG_PREFIX + "." + CONFIG_PROTOCOL, "http"); + + user = PropertiesUtil.getProperty(CONFIG_PREFIX + "." + CONFIG_USER, ""); + password = PropertiesUtil.getProperty(CONFIG_PREFIX + "." + CONFIG_PWRD, ""); + + int port = Integer.parseInt(PropertiesUtil.getProperty(CONFIG_PREFIX + "." + CONFIG_PORT)); + + this.index = PropertiesUtil.getProperty(CONFIG_PREFIX + "." + CONFIG_INDEX, "ranger_audits"); + + String parameterString = String.format(Locale.ROOT, "User:%s, %s://%s:%s/%s", user, protocol, urls, port, index); + + logger.info("Initializing ElasticSearch {}", parameterString); + + if (urls != null) { + urls = urls.trim(); + } + + if (StringUtils.isBlank(urls) || "NONE".equalsIgnoreCase(urls.trim())) { + logger.info("Clearing URI config value: {}", urls); + + urls = null; + } + + try { + if (StringUtils.isNotBlank(user) && StringUtils.isNotBlank(password) && password.contains("keytab") && new File(password).exists()) { + subject = CredentialsProviderUtil.login(user, password); + } + + RestClientBuilder restClientBuilder = getRestClientBuilder(urls, protocol, user, password, port); - private static final Logger logger = LoggerFactory.getLogger(ElasticSearchMgr.class); - public String index; - Subject subject; - String user; - String password; - - synchronized void connect() { - if (client == null) { - synchronized (ElasticSearchAuditDestination.class) { - if (client == null) { - - String urls = PropertiesUtil.getProperty(CONFIG_PREFIX + "." + CONFIG_URLS); - String protocol = PropertiesUtil.getProperty(CONFIG_PREFIX + "." + CONFIG_PROTOCOL, "http"); - user = PropertiesUtil.getProperty(CONFIG_PREFIX + "." + CONFIG_USER, ""); - password = PropertiesUtil.getProperty(CONFIG_PREFIX + "." + CONFIG_PWRD, ""); - int port = Integer.parseInt(PropertiesUtil.getProperty(CONFIG_PREFIX + "." + CONFIG_PORT)); - this.index = PropertiesUtil.getProperty(CONFIG_PREFIX + "." + CONFIG_INDEX, "ranger_audits"); - String parameterString = String.format(Locale.ROOT,"User:%s, %s://%s:%s/%s", user, protocol, urls, port, index); - logger.info("Initializing ElasticSearch " + parameterString); - if (urls != null) { - urls = urls.trim(); - } - if (StringUtils.isBlank(urls) || "NONE".equalsIgnoreCase(urls.trim())) { - logger.info(String.format("Clearing URI config value: %s", urls)); - urls = null; - } - - try { - if (StringUtils.isNotBlank(user) && StringUtils.isNotBlank(password) && password.contains("keytab") && new File(password).exists()) { - subject = CredentialsProviderUtil.login(user, password); - } - RestClientBuilder restClientBuilder = - getRestClientBuilder(urls, protocol, user, password, port); - client = new RestHighLevelClient(restClientBuilder); - } catch (Throwable t) { - logger.error("Can't connect to ElasticSearch: " + parameterString, t); - } - } - } - } - } - - public static RestClientBuilder getRestClientBuilder(String urls, String protocol, String user, String password, int port) { - RestClientBuilder restClientBuilder = RestClient.builder( - MiscUtil.toArray(urls, ",").stream() - .map(x -> new HttpHost(x, port, protocol)) - .toArray(i -> new HttpHost[i]) - ); - if (StringUtils.isNotBlank(user) && StringUtils.isNotBlank(password) && !user.equalsIgnoreCase("NONE") && !password.equalsIgnoreCase("NONE")) { - if (password.contains("keytab") && new File(password).exists()) { - final KerberosCredentialsProvider credentialsProvider = - CredentialsProviderUtil.getKerberosCredentials(user, password); - Lookup authSchemeRegistry = RegistryBuilder.create() - .register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory()).build(); - restClientBuilder.setHttpClientConfigCallback(clientBuilder -> { - clientBuilder.setDefaultCredentialsProvider(credentialsProvider); - clientBuilder.setDefaultAuthSchemeRegistry(authSchemeRegistry); - return clientBuilder; - }); - } else { - final CredentialsProvider credentialsProvider = - CredentialsProviderUtil.getBasicCredentials(user, password); - restClientBuilder.setHttpClientConfigCallback(clientBuilder -> - clientBuilder.setDefaultCredentialsProvider(credentialsProvider)); - } - } else { - logger.error("ElasticSearch Credentials not provided!!"); - final CredentialsProvider credentialsProvider = null; - restClientBuilder.setHttpClientConfigCallback(clientBuilder -> - clientBuilder.setDefaultCredentialsProvider(credentialsProvider)); - } - return restClientBuilder; - } - - RestHighLevelClient client = null; - public RestHighLevelClient getClient() { - if (client != null && subject != null) { - KerberosTicket ticket = CredentialsProviderUtil.getTGT(subject); - try { - if (new Date().getTime() > ticket.getEndTime().getTime()){ - client = null; - CredentialsProviderUtil.ticketExpireTime80 = 0; - connect(); - } else if (CredentialsProviderUtil.ticketWillExpire(ticket)) { - subject = CredentialsProviderUtil.login(user, password); - } - } catch (PrivilegedActionException e) { - logger.error("PrivilegedActionException:", e); - throw new RuntimeException(e); - } - return client; - } else { - connect(); - } - return client; - } + client = new RestHighLevelClient(restClientBuilder); + } catch (Throwable t) { + logger.error("Can't connect to ElasticSearch: {}", parameterString, t); + } + } + } + } + return me; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/elasticsearch/ElasticSearchUtil.java b/security-admin/src/main/java/org/apache/ranger/elasticsearch/ElasticSearchUtil.java index 1344366671..f9cbcbe438 100644 --- a/security-admin/src/main/java/org/apache/ranger/elasticsearch/ElasticSearchUtil.java +++ b/security-admin/src/main/java/org/apache/ranger/elasticsearch/ElasticSearchUtil.java @@ -19,7 +19,11 @@ package org.apache.ranger.elasticsearch; -import org.apache.ranger.common.*; +import org.apache.ranger.common.PropertiesUtil; +import org.apache.ranger.common.SearchCriteria; +import org.apache.ranger.common.SearchField; +import org.apache.ranger.common.SortField; +import org.apache.ranger.common.StringUtil; import org.apache.solr.client.solrj.util.ClientUtils; import org.elasticsearch.action.get.MultiGetItemResponse; import org.elasticsearch.action.get.MultiGetRequest; @@ -42,10 +46,11 @@ import java.io.IOException; import java.text.SimpleDateFormat; -import java.time.LocalDateTime; -import java.time.ZoneId; -import java.time.format.DateTimeFormatter; -import java.util.*; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Date; +import java.util.List; +import java.util.TimeZone; @Component public class ElasticSearchUtil { @@ -54,17 +59,19 @@ public class ElasticSearchUtil { @Autowired StringUtil stringUtil; - String dateFormateStr = "yyyy-MM-dd'T'HH:mm:ss'Z'"; - SimpleDateFormat dateFormat = new SimpleDateFormat(dateFormateStr); + final String dateFormateStr = "yyyy-MM-dd'T'HH:mm:ss'Z'"; + final SimpleDateFormat dateFormat = new SimpleDateFormat(dateFormateStr); public ElasticSearchUtil() { String timeZone = PropertiesUtil.getProperty("xa.elasticSearch.timezone"); + if (timeZone != null) { - logger.info("Setting timezone to " + timeZone); + logger.info("Setting timezone to {}", timeZone); + try { dateFormat.setTimeZone(TimeZone.getTimeZone(timeZone)); } catch (Throwable t) { - logger.error("Error setting timezone. TimeZone = " + timeZone); + logger.error("Error setting timezone. TimeZone = {}", timeZone); } } } @@ -72,8 +79,10 @@ public ElasticSearchUtil() { public SearchResponse searchResources(SearchCriteria searchCriteria, List searchFields, List sortFields, RestHighLevelClient client, String index) throws IOException { // See Also: https://www.elastic.co/guide/en/elasticsearch/client/java-rest/current/java-rest-high-query-builders.html QueryAccumulator queryAccumulator = new QueryAccumulator(searchCriteria); + if (searchCriteria.getParamList() != null) { searchFields.stream().forEach(queryAccumulator::addQuery); + // For now assuming there is only date field where range query will // be done. If we there are more than one, then we should create a // hashmap for each field name @@ -81,31 +90,39 @@ public SearchResponse searchResources(SearchCriteria searchCriteria, List x != null).forEach(boolQueryBuilder::must); + SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder(); + setSortClause(searchCriteria, sortFields, searchSourceBuilder); + searchSourceBuilder.from(searchCriteria.getStartIndex()); searchSourceBuilder.size(searchCriteria.getMaxRows()); searchSourceBuilder.fetchSource(true); + SearchRequest query = new SearchRequest(); + query.indices(index); query.source(searchSourceBuilder.query(boolQueryBuilder)); + return client.search(query, RequestOptions.DEFAULT); } - public void setSortClause(SearchCriteria searchCriteria, - List sortFields, - SearchSourceBuilder searchSourceBuilder) { - + public void setSortClause(SearchCriteria searchCriteria, List sortFields, SearchSourceBuilder searchSourceBuilder) { // TODO: We are supporting single sort field only for now - String sortBy = searchCriteria.getSortBy(); + 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; @@ -117,6 +134,7 @@ public void setSortClause(SearchCriteria searchCriteria, 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()); @@ -127,11 +145,13 @@ public void setSortClause(SearchCriteria searchCriteria, if (querySortBy != null) { // Add sort type - String sortType = searchCriteria.getSortType(); - SortOrder order = SortOrder.ASC; - if (sortType != null && "desc".equalsIgnoreCase(sortType)) { + String sortType = searchCriteria.getSortType(); + SortOrder order = SortOrder.ASC; + + if ("desc".equalsIgnoreCase(sortType)) { order = SortOrder.DESC; } + searchSourceBuilder.sort(querySortBy, order); } } @@ -140,6 +160,7 @@ public QueryBuilder orList(String fieldName, Collection valueList) { if (valueList == null || valueList.isEmpty()) { return null; } + if (valueList.isEmpty()) { return null; } else { @@ -152,63 +173,73 @@ public QueryBuilder orList(String fieldName, Collection valueList) { } } - - private String filterText(Object value) { - return ClientUtils.escapeQueryChars(value.toString().trim().toLowerCase()); - } - public QueryBuilder setDateRange(String fieldName, Date fromDate, Date toDate) { RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery(fieldName).format(dateFormateStr); + if (fromDate != null) { rangeQueryBuilder.from(dateFormat.format(fromDate)); } + if (toDate != null) { rangeQueryBuilder.to(dateFormat.format(toDate)); } + return rangeQueryBuilder; } public MultiGetItemResponse[] fetch(RestHighLevelClient client, String index, SearchHit... hits) throws IOException { - if(0 == hits.length) { + if (0 == hits.length) { return new MultiGetItemResponse[0]; } + MultiGetRequest multiGetRequest = new MultiGetRequest(); + for (SearchHit hit : hits) { MultiGetRequest.Item item = new MultiGetRequest.Item(index, null, hit.getId()); + item.fetchSourceContext(FetchSourceContext.FETCH_SOURCE); + multiGetRequest.add(item); } + return client.multiGet(multiGetRequest, RequestOptions.DEFAULT).getResponses(); } + private String filterText(Object value) { + return ClientUtils.escapeQueryChars(value.toString().trim().toLowerCase()); + } + private class QueryAccumulator { public final List queries = new ArrayList<>(); - public final SearchCriteria searchCriteria; - public Date fromDate; - public Date toDate; - public String dateFieldName; + public final SearchCriteria searchCriteria; + public Date fromDate; + public Date toDate; + public String dateFieldName; private QueryAccumulator(SearchCriteria searchCriteria) { this.searchCriteria = searchCriteria; - this.fromDate = null; - this.toDate = null; - this.dateFieldName = null; + this.fromDate = null; + this.toDate = null; + this.dateFieldName = null; } public QueryAccumulator addQuery(SearchField searchField) { QueryBuilder queryBuilder = getQueryBuilder(searchField); + if (null != queryBuilder) { queries.add(queryBuilder); } + return this; } public QueryBuilder getQueryBuilder(SearchField searchField) { - String clientFieldName = searchField.getClientFieldName(); - String fieldName = searchField.getFieldName(); - SearchField.DATA_TYPE dataType = searchField.getDataType(); - SearchField.SEARCH_TYPE searchType = searchField.getSearchType(); - Object paramValue = searchCriteria.getParamValue(clientFieldName); + String clientFieldName = searchField.getClientFieldName(); + String fieldName = searchField.getFieldName(); + SearchField.DATA_TYPE dataType = searchField.getDataType(); + SearchField.SEARCH_TYPE searchType = searchField.getSearchType(); + Object paramValue = searchCriteria.getParamValue(clientFieldName); + return getQueryBuilder(dataType, searchType, fieldName, paramValue); } @@ -216,12 +247,15 @@ private QueryBuilder getQueryBuilder(SearchField.DATA_TYPE dataType, SearchField if (paramValue == null || paramValue.toString().isEmpty()) { return null; } + if (fieldName.startsWith("-")) { QueryBuilder negativeQuery = getQueryBuilder(dataType, searchType, fieldName.substring(1), paramValue); return null == negativeQuery ? null : QueryBuilders.boolQuery().mustNot(negativeQuery); } + if (paramValue instanceof Collection) { Collection valueList = (Collection) paramValue; + if (valueList.isEmpty()) { return null; } else { @@ -235,27 +269,22 @@ private QueryBuilder getQueryBuilder(SearchField.DATA_TYPE dataType, SearchField } else { if (dataType == SearchField.DATA_TYPE.DATE) { if (!(paramValue instanceof Date)) { - logger.error(String.format( - "Search value is not a Java Date Object: %s %s %s", - fieldName, searchType, paramValue)); + logger.error("Search value is not a Java Date Object: {} {} {}", fieldName, searchType, paramValue); } else { - if (searchType == SearchField.SEARCH_TYPE.GREATER_EQUAL_THAN - || searchType == SearchField.SEARCH_TYPE.GREATER_THAN) { - fromDate = (Date) paramValue; + if (searchType == SearchField.SEARCH_TYPE.GREATER_EQUAL_THAN || searchType == SearchField.SEARCH_TYPE.GREATER_THAN) { + fromDate = (Date) paramValue; dateFieldName = fieldName; - } else if (searchType == SearchField.SEARCH_TYPE.LESS_EQUAL_THAN - || searchType == SearchField.SEARCH_TYPE.LESS_THAN) { - toDate = (Date) paramValue; + } else if (searchType == SearchField.SEARCH_TYPE.LESS_EQUAL_THAN || searchType == SearchField.SEARCH_TYPE.LESS_THAN) { + toDate = (Date) paramValue; dateFieldName = fieldName; } } + return null; - } else if (searchType == SearchField.SEARCH_TYPE.GREATER_EQUAL_THAN - || searchType == SearchField.SEARCH_TYPE.GREATER_THAN - || searchType == SearchField.SEARCH_TYPE.LESS_EQUAL_THAN - || searchType == SearchField.SEARCH_TYPE.LESS_THAN) { //NOPMD - logger.warn(String.format("Range Queries Not Implemented: %s %s %s", - fieldName, searchType, paramValue)); + } else if (searchType == SearchField.SEARCH_TYPE.GREATER_EQUAL_THAN || searchType == SearchField.SEARCH_TYPE.GREATER_THAN + || searchType == SearchField.SEARCH_TYPE.LESS_EQUAL_THAN || searchType == SearchField.SEARCH_TYPE.LESS_THAN) { //NOPMD + logger.warn("Range Queries Not Implemented: {} {} {}", fieldName, searchType, paramValue); + return null; } else { if (searchType == SearchField.SEARCH_TYPE.PARTIAL) { @@ -274,6 +303,5 @@ private QueryBuilder getQueryBuilder(SearchField.DATA_TYPE dataType, SearchField } } } - } } From 04a69db2f45c8f86ede690ce6cbe2d200df93172 Mon Sep 17 00:00:00 2001 From: Madhan Neethiraj Date: Fri, 3 Jan 2025 11:26:02 -0800 Subject: [PATCH 05/15] RANGER-5061: checkstyle compliance updates - security-admin elasticsearch --- .../ElasticSearchAccessAuditsService.java | 46 +++++++++---------- .../elasticsearch/ElasticSearchUtil.java | 25 +++++----- 2 files changed, 32 insertions(+), 39 deletions(-) diff --git a/security-admin/src/main/java/org/apache/ranger/elasticsearch/ElasticSearchAccessAuditsService.java b/security-admin/src/main/java/org/apache/ranger/elasticsearch/ElasticSearchAccessAuditsService.java index 4f6c808ff2..5c24db1167 100644 --- a/security-admin/src/main/java/org/apache/ranger/elasticsearch/ElasticSearchAccessAuditsService.java +++ b/security-admin/src/main/java/org/apache/ranger/elasticsearch/ElasticSearchAccessAuditsService.java @@ -68,7 +68,7 @@ public VXAccessAuditList searchXAccessAudits(SearchCriteria searchCriteria) { throw restErrorUtil.createRESTException("Error connecting to search engine", MessageEnums.ERROR_SYSTEM); } - List xAccessAuditList = new ArrayList(); + List xAccessAuditList = new ArrayList<>(); Map paramList = searchCriteria.getParamList(); updateUserExclusion(paramList); @@ -93,31 +93,27 @@ public VXAccessAuditList searchXAccessAudits(SearchCriteria searchCriteria) { throw restErrorUtil.createRESTException("Error querying search engine", MessageEnums.ERROR_SYSTEM); } - for (int i = 0; i < docs.length; i++) { // NOPMD - This for loop can be replaced by a foreach loop - MultiGetItemResponse doc = docs[i]; - VXAccessAudit vXAccessAudit = populateViewBean(doc.getResponse()); - - if (vXAccessAudit != null) { - String serviceType = vXAccessAudit.getServiceType(); - boolean isHive = "hive".equalsIgnoreCase(serviceType); - - if (!hiveQueryVisibility && isHive) { - vXAccessAudit.setRequestData(null); - } else if (isHive) { - String accessType = vXAccessAudit.getAccessType(); - - if ("grant".equalsIgnoreCase(accessType) || "revoke".equalsIgnoreCase(accessType)) { - String requestData = vXAccessAudit.getRequestData(); - - if (requestData != null) { - try { - vXAccessAudit.setRequestData(java.net.URLDecoder.decode(requestData, "UTF-8")); - } catch (UnsupportedEncodingException e) { - LOGGER.warn("Error while encoding request data: {}", requestData, e); - } - } else { - LOGGER.warn("Error in request data of audit from elasticSearch. AuditData: {}", vXAccessAudit); + for (MultiGetItemResponse doc : docs) { + VXAccessAudit vXAccessAudit = populateViewBean(doc.getResponse()); + String serviceType = vXAccessAudit.getServiceType(); + boolean isHive = "hive".equalsIgnoreCase(serviceType); + + if (!hiveQueryVisibility && isHive) { + vXAccessAudit.setRequestData(null); + } else if (isHive) { + String accessType = vXAccessAudit.getAccessType(); + + if ("grant".equalsIgnoreCase(accessType) || "revoke".equalsIgnoreCase(accessType)) { + String requestData = vXAccessAudit.getRequestData(); + + if (requestData != null) { + try { + vXAccessAudit.setRequestData(java.net.URLDecoder.decode(requestData, "UTF-8")); + } catch (UnsupportedEncodingException e) { + LOGGER.warn("Error while encoding request data: {}", requestData, e); } + } else { + LOGGER.warn("Error in request data of audit from elasticSearch. AuditData: {}", vXAccessAudit); } } } diff --git a/security-admin/src/main/java/org/apache/ranger/elasticsearch/ElasticSearchUtil.java b/security-admin/src/main/java/org/apache/ranger/elasticsearch/ElasticSearchUtil.java index f9cbcbe438..2f177e7624 100644 --- a/security-admin/src/main/java/org/apache/ranger/elasticsearch/ElasticSearchUtil.java +++ b/security-admin/src/main/java/org/apache/ranger/elasticsearch/ElasticSearchUtil.java @@ -50,6 +50,7 @@ import java.util.Collection; import java.util.Date; import java.util.List; +import java.util.Objects; import java.util.TimeZone; @Component @@ -81,7 +82,7 @@ public SearchResponse searchResources(SearchCriteria searchCriteria, List x != null).forEach(boolQueryBuilder::must); + queryAccumulator.queries.stream().filter(Objects::nonNull).forEach(boolQueryBuilder::must); SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder(); @@ -161,16 +162,12 @@ public QueryBuilder orList(String fieldName, Collection valueList) { return null; } - if (valueList.isEmpty()) { - return null; - } else { - return QueryBuilders.queryStringQuery(valueList.stream() - .map(this::filterText) - .map(x -> "(" + x + ")") - .reduce((a, b) -> a + " OR " + b) - .get() - ).defaultField(fieldName); - } + return QueryBuilders.queryStringQuery(valueList.stream() + .map(this::filterText) + .map(x -> "(" + x + ")") + .reduce((a, b) -> a + " OR " + b) + .get() + ).defaultField(fieldName); } public QueryBuilder setDateRange(String fieldName, Date fromDate, Date toDate) { @@ -288,13 +285,13 @@ private QueryBuilder getQueryBuilder(SearchField.DATA_TYPE dataType, SearchField return null; } else { if (searchType == SearchField.SEARCH_TYPE.PARTIAL) { - if (paramValue.toString().trim().length() == 0) { + if (paramValue.toString().trim().isEmpty()) { return null; } else { return QueryBuilders.queryStringQuery("*" + filterText(paramValue) + "*").defaultField(fieldName); } } else { - if (paramValue.toString().trim().length() > 0) { + if (!paramValue.toString().trim().isEmpty()) { return QueryBuilders.matchPhraseQuery(fieldName, filterText(paramValue)); } else { return null; From 29d7277c9269de5555e8e17b80a8b8942d5bd264 Mon Sep 17 00:00:00 2001 From: Madhan Neethiraj Date: Fri, 3 Jan 2025 11:29:53 -0800 Subject: [PATCH 06/15] RANGER-5061: checkstyle compliance updates - security-admin module for org.apache.ranger.amazon --- .../CloudWatchAccessAuditsService.java | 41 +++++++++---------- .../amazon/cloudwatch/CloudWatchUtil.java | 10 ++--- 2 files changed, 24 insertions(+), 27 deletions(-) diff --git a/security-admin/src/main/java/org/apache/ranger/amazon/cloudwatch/CloudWatchAccessAuditsService.java b/security-admin/src/main/java/org/apache/ranger/amazon/cloudwatch/CloudWatchAccessAuditsService.java index f15076427f..41d7121dd7 100644 --- a/security-admin/src/main/java/org/apache/ranger/amazon/cloudwatch/CloudWatchAccessAuditsService.java +++ b/security-admin/src/main/java/org/apache/ranger/amazon/cloudwatch/CloudWatchAccessAuditsService.java @@ -69,7 +69,7 @@ public VXAccessAuditList searchXAccessAudits(SearchCriteria searchCriteria) { throw restErrorUtil.createRESTException("Error connecting to cloudwatch", MessageEnums.ERROR_SYSTEM); } - List xAccessAuditList = new ArrayList(); + List xAccessAuditList = new ArrayList<>(); Map paramList = searchCriteria.getParamList(); updateUserExclusion(paramList); @@ -103,28 +103,25 @@ public VXAccessAuditList searchXAccessAudits(SearchCriteria searchCriteria) { } VXAccessAudit vXAccessAudit = populateViewBean(auditEvent); - - if (vXAccessAudit != null) { - String serviceType = vXAccessAudit.getServiceType(); - boolean isHive = "hive".equalsIgnoreCase(serviceType); - - if (!hiveQueryVisibility && isHive) { - vXAccessAudit.setRequestData(null); - } else if (isHive) { - String accessType = vXAccessAudit.getAccessType(); - - if ("grant".equalsIgnoreCase(accessType) || "revoke".equalsIgnoreCase(accessType)) { - String requestData = vXAccessAudit.getRequestData(); - - if (requestData != null) { - try { - vXAccessAudit.setRequestData(java.net.URLDecoder.decode(requestData, "UTF-8")); - } catch (UnsupportedEncodingException e) { - LOGGER.warn("Error while encoding request data:{}", requestData, e); - } - } else { - LOGGER.warn("Error in request data of audit from cloudwatch. AuditData:{} ", vXAccessAudit); + String serviceType = vXAccessAudit.getServiceType(); + boolean isHive = "hive".equalsIgnoreCase(serviceType); + + if (!hiveQueryVisibility && isHive) { + vXAccessAudit.setRequestData(null); + } else if (isHive) { + String accessType = vXAccessAudit.getAccessType(); + + if ("grant".equalsIgnoreCase(accessType) || "revoke".equalsIgnoreCase(accessType)) { + String requestData = vXAccessAudit.getRequestData(); + + if (requestData != null) { + try { + vXAccessAudit.setRequestData(java.net.URLDecoder.decode(requestData, "UTF-8")); + } catch (UnsupportedEncodingException e) { + LOGGER.warn("Error while encoding request data:{}", requestData, e); } + } else { + LOGGER.warn("Error in request data of audit from cloudwatch. AuditData:{} ", vXAccessAudit); } } } diff --git a/security-admin/src/main/java/org/apache/ranger/amazon/cloudwatch/CloudWatchUtil.java b/security-admin/src/main/java/org/apache/ranger/amazon/cloudwatch/CloudWatchUtil.java index ffe43582f6..473498dc1d 100644 --- a/security-admin/src/main/java/org/apache/ranger/amazon/cloudwatch/CloudWatchUtil.java +++ b/security-admin/src/main/java/org/apache/ranger/amazon/cloudwatch/CloudWatchUtil.java @@ -52,8 +52,8 @@ public class CloudWatchUtil { private static final Logger LOGGER = LoggerFactory.getLogger(CloudWatchUtil.class); - String dateFormateStr = "yyyy-MM-dd'T'HH:mm:ss'Z'"; - SimpleDateFormat dateFormat = new SimpleDateFormat(dateFormateStr); + final String dateFormateStr = "yyyy-MM-dd'T'HH:mm:ss'Z'"; + final SimpleDateFormat dateFormat = new SimpleDateFormat(dateFormateStr); private final String logGroupName; private final String logStreamPrefix; @@ -76,7 +76,7 @@ public CloudWatchUtil() { } public List searchResources(AWSLogs client, SearchCriteria searchCriteria, List searchFields, List sortFieldList) { - List result = new ArrayList(); + List result = new ArrayList<>(); try { String nextToken = null; @@ -136,7 +136,7 @@ public FilterLogEventsRequest getFilterLogEventsRequest(AWSLogs client, SearchCr Date toDate = null; if (searchCriteria.getParamList() != null) { - List filterExpr = new ArrayList(); + List filterExpr = new ArrayList<>(); for (SearchField searchField : searchFields) { Object paramValue = searchCriteria.getParamValue(searchField.getClientFieldName()); @@ -208,7 +208,7 @@ public FilterLogEventsRequest getFilterLogEventsRequest(AWSLogs client, SearchCr } if (StringUtils.isNotBlank(strExpr)) { - filterPattern.append("{" + strExpr + "}"); + filterPattern.append("{").append(strExpr).append("}"); } } } From e920ec75f6dd349c709ee80d861933f7a50e29b9 Mon Sep 17 00:00:00 2001 From: Dineshkumar Yadav <59435896+dineshkumar-yadav@users.noreply.github.com> Date: Mon, 6 Jan 2025 09:47:08 +0530 Subject: [PATCH 07/15] RANGER-5061: checkstyle compliance updates - security-admin module org.apache.ranger.db and org.apache.ranger.credentialapi(#496) Co-authored-by: Abhishek Kumar Co-authored-by: Madhan Neethiraj --- .../credentialapi/CredentialReader.java | 133 ++- .../apache/ranger/db/RangerDaoManager.java | 62 +- .../ranger/db/RangerDaoManagerBase.java | 614 ++++++------ .../apache/ranger/db/XXAccessAuditDao.java | 198 ++-- .../apache/ranger/db/XXAccessTypeDefDao.java | 96 +- .../ranger/db/XXAccessTypeDefGrantsDao.java | 153 ++- .../java/org/apache/ranger/db/XXAssetDao.java | 47 +- .../org/apache/ranger/db/XXAuditMapDao.java | 54 +- .../apache/ranger/db/XXAuthSessionDao.java | 149 ++- .../ranger/db/XXContextEnricherDefDao.java | 69 +- .../ranger/db/XXCredentialStoreDao.java | 8 +- .../org/apache/ranger/db/XXDBBaseDao.java | 8 +- .../org/apache/ranger/db/XXDataHistDao.java | 139 +-- .../ranger/db/XXDataMaskTypeDefDao.java | 94 +- .../org/apache/ranger/db/XXEnumDefDao.java | 42 +- .../apache/ranger/db/XXEnumElementDefDao.java | 46 +- .../apache/ranger/db/XXGdsDataShareDao.java | 270 ++--- .../ranger/db/XXGdsDataShareInDatasetDao.java | 215 ++-- .../org/apache/ranger/db/XXGdsDatasetDao.java | 210 ++-- .../ranger/db/XXGdsDatasetInProjectDao.java | 136 +-- .../ranger/db/XXGdsDatasetPolicyMapDao.java | 88 +- .../org/apache/ranger/db/XXGdsProjectDao.java | 178 ++-- .../ranger/db/XXGdsProjectPolicyMapDao.java | 88 +- .../ranger/db/XXGdsSharedResourceDao.java | 230 ++--- .../apache/ranger/db/XXGlobalStateDao.java | 112 ++- .../java/org/apache/ranger/db/XXGroupDao.java | 207 ++-- .../org/apache/ranger/db/XXGroupGroupDao.java | 84 +- .../ranger/db/XXGroupPermissionDao.java | 220 ++--- .../org/apache/ranger/db/XXGroupUserDao.java | 301 +++--- .../org/apache/ranger/db/XXModuleDefDao.java | 234 +++-- .../org/apache/ranger/db/XXPermMapDao.java | 53 +- .../org/apache/ranger/db/XXPluginInfoDao.java | 164 +-- .../ranger/db/XXPolicyChangeLogDao.java | 60 +- .../ranger/db/XXPolicyConditionDefDao.java | 76 +- .../org/apache/ranger/db/XXPolicyDao.java | 935 +++++++++--------- .../ranger/db/XXPolicyExportAuditDao.java | 7 +- .../ranger/db/XXPolicyItemAccessDao.java | 81 +- .../ranger/db/XXPolicyItemConditionDao.java | 81 +- .../org/apache/ranger/db/XXPolicyItemDao.java | 118 +-- .../db/XXPolicyItemDataMaskInfoDao.java | 82 +- .../ranger/db/XXPolicyItemGroupPermDao.java | 82 +- .../db/XXPolicyItemRowFilterInfoDao.java | 73 +- .../ranger/db/XXPolicyItemUserPermDao.java | 82 +- .../apache/ranger/db/XXPolicyLabelDao.java | 134 +-- .../apache/ranger/db/XXPolicyLabelMapDao.java | 75 +- .../ranger/db/XXPolicyRefAccessTypeDao.java | 125 +-- .../ranger/db/XXPolicyRefConditionDao.java | 153 +-- .../ranger/db/XXPolicyRefDataMaskTypeDao.java | 102 +- .../apache/ranger/db/XXPolicyRefGroupDao.java | 127 +-- .../ranger/db/XXPolicyRefResourceDao.java | 183 ++-- .../apache/ranger/db/XXPolicyRefRoleDao.java | 79 +- .../apache/ranger/db/XXPolicyRefUserDao.java | 152 +-- .../apache/ranger/db/XXPolicyResourceDao.java | 104 +- .../ranger/db/XXPolicyResourceMapDao.java | 82 +- .../ranger/db/XXPolicyWithAssignedIdDao.java | 8 +- .../org/apache/ranger/db/XXPortalUserDao.java | 279 +++--- .../apache/ranger/db/XXPortalUserRoleDao.java | 92 +- .../ranger/db/XXRMSMappingProviderDao.java | 24 +- .../ranger/db/XXRMSNotificationDao.java | 194 ++-- .../ranger/db/XXRMSResourceMappingDao.java | 209 ++-- .../ranger/db/XXRMSServiceResourceDao.java | 441 +++++---- .../org/apache/ranger/db/XXResourceDao.java | 478 +++++---- .../apache/ranger/db/XXResourceDefDao.java | 146 +-- .../java/org/apache/ranger/db/XXRoleDao.java | 78 +- .../apache/ranger/db/XXRoleRefGroupDao.java | 41 +- .../apache/ranger/db/XXRoleRefRoleDao.java | 69 +- .../apache/ranger/db/XXRoleRefUserDao.java | 40 +- .../apache/ranger/db/XXSecurityZoneDao.java | 97 +- .../ranger/db/XXSecurityZoneRefGroupDao.java | 58 +- .../db/XXSecurityZoneRefResourceDao.java | 46 +- .../ranger/db/XXSecurityZoneRefRoleDao.java | 52 +- .../db/XXSecurityZoneRefServiceDao.java | 100 +- .../db/XXSecurityZoneRefTagServiceDao.java | 51 +- .../ranger/db/XXSecurityZoneRefUserDao.java | 56 +- .../ranger/db/XXServiceConfigDefDao.java | 72 +- .../ranger/db/XXServiceConfigMapDao.java | 209 ++-- .../org/apache/ranger/db/XXServiceDao.java | 312 +++--- .../org/apache/ranger/db/XXServiceDefDao.java | 314 +++--- .../db/XXServiceDefWithAssignedIdDao.java | 8 +- .../ranger/db/XXServiceResourceDao.java | 182 ++-- .../db/XXServiceResourceElementDao.java | 89 +- .../db/XXServiceResourceElementValueDao.java | 136 +-- .../ranger/db/XXServiceVersionInfoDao.java | 273 ++--- .../ranger/db/XXServiceWithAssignedIdDao.java | 8 +- .../apache/ranger/db/XXTagAttributeDao.java | 112 ++- .../ranger/db/XXTagAttributeDefDao.java | 84 +- .../apache/ranger/db/XXTagChangeLogDao.java | 47 +- .../java/org/apache/ranger/db/XXTagDao.java | 227 ++--- .../org/apache/ranger/db/XXTagDefDao.java | 112 ++- .../apache/ranger/db/XXTagResourceMapDao.java | 331 ++++--- .../org/apache/ranger/db/XXTrxLogV2Dao.java | 11 +- .../ranger/db/XXUgsyncAuditInfoDao.java | 79 +- .../java/org/apache/ranger/db/XXUserDao.java | 359 ++++--- .../apache/ranger/db/XXUserPermissionDao.java | 251 ++--- 94 files changed, 6851 insertions(+), 6619 deletions(-) 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 index f63828c200..116c04e478 100644 --- a/security-admin/src/main/java/org/apache/ranger/credentialapi/CredentialReader.java +++ b/security-admin/src/main/java/org/apache/ranger/credentialapi/CredentialReader.java @@ -17,78 +17,77 @@ * under the License. */ - package org.apache.ranger.credentialapi; -import java.util.ArrayList; -import java.util.List; +package org.apache.ranger.credentialapi; + import org.apache.commons.lang.StringUtils; 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; + +import java.util.List; + public class CredentialReader { + private CredentialReader(){ + // to block instantiation + } + + public static String getDecryptedString(String crendentialProviderPath, String alias, String storeType) { + String credential = null; + + try { + if (crendentialProviderPath == null || alias == null || crendentialProviderPath.trim().isEmpty() || alias.trim().isEmpty()) { + return null; + } + + String crendentialProviderPrefixJceks = (JavaKeyStoreProvider.SCHEME_NAME + "://file").toLowerCase(); + String crendentialProviderPrefixLocalJceks = "localjceks://file"; + String crendentialProviderPrefixBcfks = "bcfks://file"; + String crendentialProviderPrefixLocalBcfks = "localbcfks://file"; + + crendentialProviderPath = crendentialProviderPath.trim(); + alias = alias.trim(); + + Configuration conf = new Configuration(); + + if (crendentialProviderPath.toLowerCase().startsWith(crendentialProviderPrefixJceks) || + crendentialProviderPath.toLowerCase().startsWith(crendentialProviderPrefixLocalJceks) || + crendentialProviderPath.toLowerCase().startsWith(crendentialProviderPrefixBcfks) || + crendentialProviderPath.toLowerCase().startsWith(crendentialProviderPrefixLocalBcfks)) { + conf.set(CredentialProviderFactory.CREDENTIAL_PROVIDER_PATH, crendentialProviderPath); + } else { + if (crendentialProviderPath.startsWith("/")) { + if (StringUtils.equalsIgnoreCase(storeType, "bcfks")) { + conf.set(CredentialProviderFactory.CREDENTIAL_PROVIDER_PATH, crendentialProviderPath); + } else { + conf.set(CredentialProviderFactory.CREDENTIAL_PROVIDER_PATH, JavaKeyStoreProvider.SCHEME_NAME + "://file" + crendentialProviderPath); + } + } else { + conf.set(CredentialProviderFactory.CREDENTIAL_PROVIDER_PATH, JavaKeyStoreProvider.SCHEME_NAME + "://file/" + crendentialProviderPath); + } + } + + List providers = CredentialProviderFactory.getProviders(conf); + + for (CredentialProvider provider : providers) { + List aliasesList = provider.getAliases(); + + if (aliasesList != null && aliasesList.contains(alias.toLowerCase())) { + CredentialProvider.CredentialEntry credEntry = provider.getCredentialEntry(alias.toLowerCase()); + char[] pass = credEntry.getCredential(); + + if (pass != null && pass.length > 0) { + credential = String.valueOf(pass); + + break; + } + } + } + } catch (Exception ex) { + ex.printStackTrace(); + credential = null; + } - public static String getDecryptedString(String CrendentialProviderPath,String alias, String storeType) { - String credential=null; - try{ - if(CrendentialProviderPath==null || alias==null||CrendentialProviderPath.trim().isEmpty()||alias.trim().isEmpty()){ - return null; - } - char[] pass = null; - Configuration conf = new Configuration(); - String crendentialProviderPrefixJceks=JavaKeyStoreProvider.SCHEME_NAME + "://file"; - String crendentialProviderPrefixLocalJceks="localjceks://file"; - crendentialProviderPrefixJceks=crendentialProviderPrefixJceks.toLowerCase(); - - String crendentialProviderPrefixBcfks= "bcfks" + "://file"; - String crendentialProviderPrefixLocalBcfks= "localbcfks" + "://file"; - crendentialProviderPrefixBcfks=crendentialProviderPrefixBcfks.toLowerCase(); - crendentialProviderPrefixLocalBcfks=crendentialProviderPrefixLocalBcfks.toLowerCase(); - - CrendentialProviderPath=CrendentialProviderPath.trim(); - alias=alias.trim(); - if(CrendentialProviderPath.toLowerCase().startsWith(crendentialProviderPrefixJceks) || - CrendentialProviderPath.toLowerCase().startsWith(crendentialProviderPrefixLocalJceks) || - CrendentialProviderPath.toLowerCase().startsWith(crendentialProviderPrefixBcfks) || - CrendentialProviderPath.toLowerCase().startsWith(crendentialProviderPrefixLocalBcfks)){ - conf.set(CredentialProviderFactory.CREDENTIAL_PROVIDER_PATH, - //UserProvider.SCHEME_NAME + ":///," + - CrendentialProviderPath); - }else{ - if(CrendentialProviderPath.startsWith("/")){ - if(StringUtils.equalsIgnoreCase(storeType, "bcfks")) { - conf.set(CredentialProviderFactory.CREDENTIAL_PROVIDER_PATH, CrendentialProviderPath); - } else { - 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 providers = CredentialProviderFactory.getProviders(conf); - List aliasesList=new ArrayList(); - 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.toLowerCase()); - pass = credEntry.getCredential(); - if(pass!=null && pass.length>0){ - credential=String.valueOf(pass); - break; - } - } - } - }catch(Exception ex){ - ex.printStackTrace(); - credential=null; - } - return credential; - } + return credential; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/db/RangerDaoManager.java b/security-admin/src/main/java/org/apache/ranger/db/RangerDaoManager.java index 81f9a16811..380c2e1345 100644 --- a/security-admin/src/main/java/org/apache/ranger/db/RangerDaoManager.java +++ b/security-admin/src/main/java/org/apache/ranger/db/RangerDaoManager.java @@ -17,12 +17,7 @@ * under the License. */ - package org.apache.ranger.db; - - - -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; +package org.apache.ranger.db; import org.apache.ranger.common.StringUtil; import org.apache.ranger.common.db.RangerTransactionSynchronizationAdapter; @@ -31,42 +26,41 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; + @Component public class RangerDaoManager extends RangerDaoManagerBase { - private static final Logger logger = LoggerFactory.getLogger(RangerDaoManager.class); - - @PersistenceContext(unitName = "defaultPU") - private EntityManager em; + private static final Logger logger = LoggerFactory.getLogger(RangerDaoManager.class); - @Autowired - StringUtil stringUtil; + @Autowired + StringUtil stringUtil; - @Autowired - RangerTransactionSynchronizationAdapter transactionSynchronizationAdapter; + @Autowired + RangerTransactionSynchronizationAdapter transactionSynchronizationAdapter; - @Override - public EntityManager getEntityManager() { - return em; - } + @PersistenceContext(unitName = "defaultPU") + private EntityManager em; - public EntityManager getEntityManager(String persistenceContextUnit) { - if(logger.isDebugEnabled()) { - logger.debug("RangerDaoManager.getEntityManager(" + persistenceContextUnit + ")"); - } + @Override + public EntityManager getEntityManager() { + return em; + } - return getEntityManager(); - } + public EntityManager getEntityManager(String persistenceContextUnit) { + logger.debug("RangerDaoManager.getEntityManager({})", persistenceContextUnit); - - /** - * @return the stringUtil - */ - public StringUtil getStringUtil() { - return stringUtil; - } + return getEntityManager(); + } - public RangerTransactionSynchronizationAdapter getRangerTransactionSynchronizationAdapter() { - return transactionSynchronizationAdapter; - } + /** + * @return the stringUtil + */ + public StringUtil getStringUtil() { + return stringUtil; + } + public RangerTransactionSynchronizationAdapter getRangerTransactionSynchronizationAdapter() { + return transactionSynchronizationAdapter; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/db/RangerDaoManagerBase.java b/security-admin/src/main/java/org/apache/ranger/db/RangerDaoManagerBase.java index 6b56527ae9..aa1aa6ad9c 100644 --- a/security-admin/src/main/java/org/apache/ranger/db/RangerDaoManagerBase.java +++ b/security-admin/src/main/java/org/apache/ranger/db/RangerDaoManagerBase.java @@ -17,7 +17,7 @@ * under the License. */ - package org.apache.ranger.db; +package org.apache.ranger.db; /** * @@ -26,311 +26,375 @@ import javax.persistence.EntityManager; public abstract class RangerDaoManagerBase { + public RangerDaoManagerBase() { + } - abstract public EntityManager getEntityManager(); + public abstract EntityManager getEntityManager(); - public RangerDaoManagerBase() { - } + public XXDBBaseDao getXXDBBase() { + return new XXDBBaseDao(this); + } - public XXDBBaseDao getXXDBBase() { - return new XXDBBaseDao(this); - } + public XXAuthSessionDao getXXAuthSession() { + return new XXAuthSessionDao(this); + } - public XXAuthSessionDao getXXAuthSession() { - return new XXAuthSessionDao(this); - } + public XXPortalUserDao getXXPortalUser() { + return new XXPortalUserDao(this); + } - public XXPortalUserDao getXXPortalUser() { - return new XXPortalUserDao(this); - } + public XXPortalUserRoleDao getXXPortalUserRole() { + return new XXPortalUserRoleDao(this); + } - public XXPortalUserRoleDao getXXPortalUserRole() { - return new XXPortalUserRoleDao(this); - } + public XXAssetDao getXXAsset() { + return new XXAssetDao(this); + } - public XXAssetDao getXXAsset() { - return new XXAssetDao(this); - } + public XXResourceDao getXXResource() { + return new XXResourceDao(this); + } - public XXResourceDao getXXResource() { - return new XXResourceDao(this); - } + public XXCredentialStoreDao getXXCredentialStore() { + return new XXCredentialStoreDao(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 XXTrxLogV2Dao getXXTrxLogV2() { - return new XXTrxLogV2Dao(this); - } - - public XXAccessAuditDao getXXAccessAudit() { - //Load appropriate class based on audit store - //TODO: Need to fix this, currently hard coding Solr - - return new XXAccessAuditDao(this); - } - - public XXPolicyDao getXXPolicy() { - return new XXPolicyDao(this); - } - - public XXServiceDao getXXService() { - return new XXServiceDao(this); - } - - public XXPolicyItemDao getXXPolicyItem() { - return new XXPolicyItemDao(this); - } - - public XXServiceDefDao getXXServiceDef() { - return new XXServiceDefDao(this); - } - - public XXServiceConfigDefDao getXXServiceConfigDef() { - return new XXServiceConfigDefDao(this); - } - - public XXResourceDefDao getXXResourceDef() { - return new XXResourceDefDao(this); - } - - public XXPolicyLabelDao getXXPolicyLabels() { - return new XXPolicyLabelDao(this); - } - - public XXPolicyLabelMapDao getXXPolicyLabelMap() { - return new XXPolicyLabelMapDao(this); - } - - public XXAccessTypeDefDao getXXAccessTypeDef() { - return new XXAccessTypeDefDao(this); - } - - public XXAccessTypeDefGrantsDao getXXAccessTypeDefGrants() { - return new XXAccessTypeDefGrantsDao(this); - } - - public XXPolicyConditionDefDao getXXPolicyConditionDef() { - return new XXPolicyConditionDefDao(this); - } - - public XXContextEnricherDefDao getXXContextEnricherDef() { - return new XXContextEnricherDefDao(this); - } - - public XXEnumDefDao getXXEnumDef() { - return new XXEnumDefDao(this); - } - - public XXEnumElementDefDao getXXEnumElementDef() { - return new XXEnumElementDefDao(this); - } - - public XXServiceConfigMapDao getXXServiceConfigMap() { - return new XXServiceConfigMapDao(this); - } - - public XXPolicyResourceDao getXXPolicyResource() { - return new XXPolicyResourceDao(this); - } - - public XXPolicyResourceMapDao getXXPolicyResourceMap() { - return new XXPolicyResourceMapDao(this); - } - - public XXPolicyItemAccessDao getXXPolicyItemAccess() { - return new XXPolicyItemAccessDao(this); - } - - public XXPolicyItemConditionDao getXXPolicyItemCondition() { - return new XXPolicyItemConditionDao(this); - } - - public XXPolicyItemUserPermDao getXXPolicyItemUserPerm() { - return new XXPolicyItemUserPermDao(this); - } - - public XXPolicyItemGroupPermDao getXXPolicyItemGroupPerm() { - return new XXPolicyItemGroupPermDao(this); - } - - public XXDataHistDao getXXDataHist() { - return new XXDataHistDao(this); - } - - public XXPolicyWithAssignedIdDao getXXPolicyWithAssignedId() { - return new XXPolicyWithAssignedIdDao(this); - } - - public XXServiceWithAssignedIdDao getXXServiceWithAssignedId() { - return new XXServiceWithAssignedIdDao(this); - } - - public XXModuleDefDao getXXModuleDef(){ - return new XXModuleDefDao(this); - } - - public XXUserPermissionDao getXXUserPermission(){ - return new XXUserPermissionDao(this); - } - - public XXGroupPermissionDao getXXGroupPermission(){ - return new XXGroupPermissionDao(this); - } - - public XXServiceDefWithAssignedIdDao getXXServiceDefWithAssignedId() { - return new XXServiceDefWithAssignedIdDao(this); - } - - public XXTagDefDao getXXTagDef() { - return new XXTagDefDao(this); - } - - public XXTagAttributeDefDao getXXTagAttributeDef() { - return new XXTagAttributeDefDao(this); - } + public XXGroupDao getXXGroup() { + return new XXGroupDao(this); + } - public XXServiceResourceDao getXXServiceResource() { - return new XXServiceResourceDao(this); - } - - public XXServiceResourceElementDao getXXServiceResourceElement() { - return new XXServiceResourceElementDao(this); - } - - public XXServiceResourceElementValueDao getXXServiceResourceElementValue() { - return new XXServiceResourceElementValueDao(this); - } - - public XXTagDao getXXTag() { - return new XXTagDao(this); - } - - public XXTagAttributeDao getXXTagAttribute() { - return new XXTagAttributeDao(this); - } - - public XXTagResourceMapDao getXXTagResourceMap() { - return new XXTagResourceMapDao(this); - } - - public XXDataMaskTypeDefDao getXXDataMaskTypeDef() { return new XXDataMaskTypeDefDao(this); } - - public XXPolicyItemDataMaskInfoDao getXXPolicyItemDataMaskInfo() { - return new XXPolicyItemDataMaskInfoDao(this); - } - - public XXPolicyItemRowFilterInfoDao getXXPolicyItemRowFilterInfo() { - return new XXPolicyItemRowFilterInfoDao(this); - } - - public XXServiceVersionInfoDao getXXServiceVersionInfo() { - return new XXServiceVersionInfoDao(this); - } - - public XXPluginInfoDao getXXPluginInfo() { - return new XXPluginInfoDao(this); - } - - public XXUgsyncAuditInfoDao getXXUgsyncAuditInfo() { - return new XXUgsyncAuditInfoDao(this); - } + public XXUserDao getXXUser() { + return new XXUserDao(this); + } - public XXPolicyRefConditionDao getXXPolicyRefCondition() { - return new XXPolicyRefConditionDao(this); - } + public XXGroupUserDao getXXGroupUser() { + return new XXGroupUserDao(this); + } - public XXPolicyRefGroupDao getXXPolicyRefGroup() { - return new XXPolicyRefGroupDao(this); - } + public XXGroupGroupDao getXXGroupGroup() { + return new XXGroupGroupDao(this); + } - public XXPolicyRefDataMaskTypeDao getXXPolicyRefDataMaskType() { - return new XXPolicyRefDataMaskTypeDao(this); - } + public XXPermMapDao getXXPermMap() { + return new XXPermMapDao(this); + } - public XXPolicyRefResourceDao getXXPolicyRefResource() { - return new XXPolicyRefResourceDao(this); - } + public XXAuditMapDao getXXAuditMap() { + return new XXAuditMapDao(this); + } - public XXPolicyRefUserDao getXXPolicyRefUser() { - return new XXPolicyRefUserDao(this); - } + public XXPolicyExportAuditDao getXXPolicyExportAudit() { + return new XXPolicyExportAuditDao(this); + } - public XXPolicyRefAccessTypeDao getXXPolicyRefAccessType() { - return new XXPolicyRefAccessTypeDao(this); - } + public XXTrxLogV2Dao getXXTrxLogV2() { + return new XXTrxLogV2Dao(this); + } - public XXSecurityZoneDao getXXSecurityZoneDao() { return new XXSecurityZoneDao(this); } + public XXAccessAuditDao getXXAccessAudit() { + //Load appropriate class based on audit store + //TODO: Need to fix this, currently hard coding Solr - public XXSecurityZoneRefServiceDao getXXSecurityZoneRefService() { return new XXSecurityZoneRefServiceDao(this); } + return new XXAccessAuditDao(this); + } - public XXSecurityZoneRefTagServiceDao getXXSecurityZoneRefTagService() { return new XXSecurityZoneRefTagServiceDao(this); } + public XXPolicyDao getXXPolicy() { + return new XXPolicyDao(this); + } - public XXSecurityZoneRefResourceDao getXXSecurityZoneRefResource() { return new XXSecurityZoneRefResourceDao(this); } + public XXServiceDao getXXService() { + return new XXServiceDao(this); + } - public XXSecurityZoneRefUserDao getXXSecurityZoneRefUser() { return new XXSecurityZoneRefUserDao(this); } + public XXPolicyItemDao getXXPolicyItem() { + return new XXPolicyItemDao(this); + } - public XXSecurityZoneRefGroupDao getXXSecurityZoneRefGroup() { return new XXSecurityZoneRefGroupDao(this); } + public XXServiceDefDao getXXServiceDef() { + return new XXServiceDefDao(this); + } - public XXSecurityZoneRefRoleDao getXXSecurityZoneRefRole() { return new XXSecurityZoneRefRoleDao(this); } + public XXServiceConfigDefDao getXXServiceConfigDef() { + return new XXServiceConfigDefDao(this); + } - public XXGlobalStateDao getXXGlobalState() { return new XXGlobalStateDao(this); } + public XXResourceDefDao getXXResourceDef() { + return new XXResourceDefDao(this); + } - public XXPolicyChangeLogDao getXXPolicyChangeLog() { return new XXPolicyChangeLogDao(this); } + public XXPolicyLabelDao getXXPolicyLabels() { + return new XXPolicyLabelDao(this); + } - public XXRoleDao getXXRole() { return new XXRoleDao(this); } + public XXPolicyLabelMapDao getXXPolicyLabelMap() { + return new XXPolicyLabelMapDao(this); + } - public XXPolicyRefRoleDao getXXPolicyRefRole() { return new XXPolicyRefRoleDao(this); } + public XXAccessTypeDefDao getXXAccessTypeDef() { + return new XXAccessTypeDefDao(this); + } - public XXRoleRefUserDao getXXRoleRefUser() { return new XXRoleRefUserDao(this); } + public XXAccessTypeDefGrantsDao getXXAccessTypeDefGrants() { + return new XXAccessTypeDefGrantsDao(this); + } - public XXRoleRefGroupDao getXXRoleRefGroup() { return new XXRoleRefGroupDao(this); } + public XXPolicyConditionDefDao getXXPolicyConditionDef() { + return new XXPolicyConditionDefDao(this); + } - public XXRoleRefRoleDao getXXRoleRefRole() { return new XXRoleRefRoleDao(this); } + public XXContextEnricherDefDao getXXContextEnricherDef() { + return new XXContextEnricherDefDao(this); + } - public XXTagChangeLogDao getXXTagChangeLog() { return new XXTagChangeLogDao(this); } + public XXEnumDefDao getXXEnumDef() { + return new XXEnumDefDao(this); + } - public XXRMSMappingProviderDao getXXRMSMappingProvider() { return new XXRMSMappingProviderDao(this); } - public XXRMSNotificationDao getXXRMSNotification() { return new XXRMSNotificationDao(this); } - public XXRMSServiceResourceDao getXXRMSServiceResource() { return new XXRMSServiceResourceDao(this); } - public XXRMSResourceMappingDao getXXRMSResourceMapping() { return new XXRMSResourceMappingDao(this); } + public XXEnumElementDefDao getXXEnumElementDef() { + return new XXEnumElementDefDao(this); + } - public XXGdsDatasetDao getXXGdsDataset() { return new XXGdsDatasetDao(this); } - public XXGdsProjectDao getXXGdsProject() { return new XXGdsProjectDao(this); } - public XXGdsDataShareDao getXXGdsDataShare() { return new XXGdsDataShareDao(this); } - public XXGdsSharedResourceDao getXXGdsSharedResource() { return new XXGdsSharedResourceDao(this); } - public XXGdsDataShareInDatasetDao getXXGdsDataShareInDataset() { return new XXGdsDataShareInDatasetDao(this); } - public XXGdsDatasetInProjectDao getXXGdsDatasetInProject() { return new XXGdsDatasetInProjectDao(this); } - public XXGdsDatasetPolicyMapDao getXXGdsDatasetPolicyMap() { return new XXGdsDatasetPolicyMapDao(this); } - public XXGdsProjectPolicyMapDao getXXGdsProjectPolicyMap() { return new XXGdsProjectPolicyMapDao(this); } -} + public XXServiceConfigMapDao getXXServiceConfigMap() { + return new XXServiceConfigMapDao(this); + } + + public XXPolicyResourceDao getXXPolicyResource() { + return new XXPolicyResourceDao(this); + } + + public XXPolicyResourceMapDao getXXPolicyResourceMap() { + return new XXPolicyResourceMapDao(this); + } + + public XXPolicyItemAccessDao getXXPolicyItemAccess() { + return new XXPolicyItemAccessDao(this); + } + + public XXPolicyItemConditionDao getXXPolicyItemCondition() { + return new XXPolicyItemConditionDao(this); + } + + public XXPolicyItemUserPermDao getXXPolicyItemUserPerm() { + return new XXPolicyItemUserPermDao(this); + } + + public XXPolicyItemGroupPermDao getXXPolicyItemGroupPerm() { + return new XXPolicyItemGroupPermDao(this); + } + + public XXDataHistDao getXXDataHist() { + return new XXDataHistDao(this); + } + + public XXPolicyWithAssignedIdDao getXXPolicyWithAssignedId() { + return new XXPolicyWithAssignedIdDao(this); + } + + public XXServiceWithAssignedIdDao getXXServiceWithAssignedId() { + return new XXServiceWithAssignedIdDao(this); + } + + public XXModuleDefDao getXXModuleDef() { + return new XXModuleDefDao(this); + } + + public XXUserPermissionDao getXXUserPermission() { + return new XXUserPermissionDao(this); + } + + public XXGroupPermissionDao getXXGroupPermission() { + return new XXGroupPermissionDao(this); + } + + public XXServiceDefWithAssignedIdDao getXXServiceDefWithAssignedId() { + return new XXServiceDefWithAssignedIdDao(this); + } + + public XXTagDefDao getXXTagDef() { + return new XXTagDefDao(this); + } + + public XXTagAttributeDefDao getXXTagAttributeDef() { + return new XXTagAttributeDefDao(this); + } + + public XXServiceResourceDao getXXServiceResource() { + return new XXServiceResourceDao(this); + } + + public XXServiceResourceElementDao getXXServiceResourceElement() { + return new XXServiceResourceElementDao(this); + } + + public XXServiceResourceElementValueDao getXXServiceResourceElementValue() { + return new XXServiceResourceElementValueDao(this); + } + + public XXTagDao getXXTag() { + return new XXTagDao(this); + } + + public XXTagAttributeDao getXXTagAttribute() { + return new XXTagAttributeDao(this); + } + + public XXTagResourceMapDao getXXTagResourceMap() { + return new XXTagResourceMapDao(this); + } + + public XXDataMaskTypeDefDao getXXDataMaskTypeDef() { + return new XXDataMaskTypeDefDao(this); + } + + public XXPolicyItemDataMaskInfoDao getXXPolicyItemDataMaskInfo() { + return new XXPolicyItemDataMaskInfoDao(this); + } + + public XXPolicyItemRowFilterInfoDao getXXPolicyItemRowFilterInfo() { + return new XXPolicyItemRowFilterInfoDao(this); + } + + public XXServiceVersionInfoDao getXXServiceVersionInfo() { + return new XXServiceVersionInfoDao(this); + } + + public XXPluginInfoDao getXXPluginInfo() { + return new XXPluginInfoDao(this); + } + + public XXUgsyncAuditInfoDao getXXUgsyncAuditInfo() { + return new XXUgsyncAuditInfoDao(this); + } + + public XXPolicyRefConditionDao getXXPolicyRefCondition() { + return new XXPolicyRefConditionDao(this); + } + + public XXPolicyRefGroupDao getXXPolicyRefGroup() { + return new XXPolicyRefGroupDao(this); + } + + public XXPolicyRefDataMaskTypeDao getXXPolicyRefDataMaskType() { + return new XXPolicyRefDataMaskTypeDao(this); + } + public XXPolicyRefResourceDao getXXPolicyRefResource() { + return new XXPolicyRefResourceDao(this); + } + + public XXPolicyRefUserDao getXXPolicyRefUser() { + return new XXPolicyRefUserDao(this); + } + + public XXPolicyRefAccessTypeDao getXXPolicyRefAccessType() { + return new XXPolicyRefAccessTypeDao(this); + } + + public XXSecurityZoneDao getXXSecurityZoneDao() { + return new XXSecurityZoneDao(this); + } + + public XXSecurityZoneRefServiceDao getXXSecurityZoneRefService() { + return new XXSecurityZoneRefServiceDao(this); + } + + public XXSecurityZoneRefTagServiceDao getXXSecurityZoneRefTagService() { + return new XXSecurityZoneRefTagServiceDao(this); + } + + public XXSecurityZoneRefResourceDao getXXSecurityZoneRefResource() { + return new XXSecurityZoneRefResourceDao(this); + } + + public XXSecurityZoneRefUserDao getXXSecurityZoneRefUser() { + return new XXSecurityZoneRefUserDao(this); + } + + public XXSecurityZoneRefGroupDao getXXSecurityZoneRefGroup() { + return new XXSecurityZoneRefGroupDao(this); + } + + public XXSecurityZoneRefRoleDao getXXSecurityZoneRefRole() { + return new XXSecurityZoneRefRoleDao(this); + } + + public XXGlobalStateDao getXXGlobalState() { + return new XXGlobalStateDao(this); + } + + public XXPolicyChangeLogDao getXXPolicyChangeLog() { + return new XXPolicyChangeLogDao(this); + } + + public XXRoleDao getXXRole() { + return new XXRoleDao(this); + } + + public XXPolicyRefRoleDao getXXPolicyRefRole() { + return new XXPolicyRefRoleDao(this); + } + + public XXRoleRefUserDao getXXRoleRefUser() { + return new XXRoleRefUserDao(this); + } + + public XXRoleRefGroupDao getXXRoleRefGroup() { + return new XXRoleRefGroupDao(this); + } + + public XXRoleRefRoleDao getXXRoleRefRole() { + return new XXRoleRefRoleDao(this); + } + + public XXTagChangeLogDao getXXTagChangeLog() { + return new XXTagChangeLogDao(this); + } + + public XXRMSMappingProviderDao getXXRMSMappingProvider() { + return new XXRMSMappingProviderDao(this); + } + + public XXRMSNotificationDao getXXRMSNotification() { + return new XXRMSNotificationDao(this); + } + + public XXRMSServiceResourceDao getXXRMSServiceResource() { + return new XXRMSServiceResourceDao(this); + } + + public XXRMSResourceMappingDao getXXRMSResourceMapping() { + return new XXRMSResourceMappingDao(this); + } + + public XXGdsDatasetDao getXXGdsDataset() { + return new XXGdsDatasetDao(this); + } + + public XXGdsProjectDao getXXGdsProject() { + return new XXGdsProjectDao(this); + } + + public XXGdsDataShareDao getXXGdsDataShare() { + return new XXGdsDataShareDao(this); + } + + public XXGdsSharedResourceDao getXXGdsSharedResource() { + return new XXGdsSharedResourceDao(this); + } + + public XXGdsDataShareInDatasetDao getXXGdsDataShareInDataset() { + return new XXGdsDataShareInDatasetDao(this); + } + + public XXGdsDatasetInProjectDao getXXGdsDatasetInProject() { + return new XXGdsDatasetInProjectDao(this); + } + + public XXGdsDatasetPolicyMapDao getXXGdsDatasetPolicyMap() { + return new XXGdsDatasetPolicyMapDao(this); + } + + public XXGdsProjectPolicyMapDao getXXGdsProjectPolicyMap() { + return new XXGdsProjectPolicyMapDao(this); + } +} 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 index 7d60c5f676..f387142b25 100644 --- a/security-admin/src/main/java/org/apache/ranger/db/XXAccessAuditDao.java +++ b/security-admin/src/main/java/org/apache/ranger/db/XXAccessAuditDao.java @@ -17,11 +17,8 @@ * under the License. */ - package org.apache.ranger.db; +package org.apache.ranger.db; -import java.util.ArrayList; -import java.util.List; -import javax.persistence.NoResultException; import org.apache.ranger.common.db.BaseDao; import org.apache.ranger.entity.XXAccessAudit; import org.apache.ranger.entity.XXAccessAuditV4; @@ -30,89 +27,118 @@ import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; +import javax.persistence.NoResultException; + +import java.util.ArrayList; +import java.util.List; + @Service public class XXAccessAuditDao extends BaseDao { - private static final Logger logger = LoggerFactory.getLogger(XXAccessAuditDao.class); - public XXAccessAuditDao( RangerDaoManagerBase daoManager ) { - super(daoManager); + private static final Logger logger = LoggerFactory.getLogger(XXAccessAuditDao.class); + + public XXAccessAuditDao(RangerDaoManagerBase daoManager) { + super(daoManager); } - public Long getMaxIdOfXXAccessAudit(){ - Long maxXXAccessAuditID=Long.valueOf(0L); - try { - maxXXAccessAuditID = (Long) getEntityManager() - .createNamedQuery("XXAccessAudit.getMaxIdOfXXAccessAudit", Long.class) - .getSingleResult(); - } catch (NoResultException e) { - logger.debug(e.getMessage()); - }finally{ - if(maxXXAccessAuditID==null){ - maxXXAccessAuditID=Long.valueOf(0L); - } - } - return maxXXAccessAuditID; - } - - @SuppressWarnings("unchecked") - public List getColumnNames(String db_flavor){ - List columnList=new ArrayList(); - String sqlStr=null; - if("MYSQL".equalsIgnoreCase(db_flavor)){ - sqlStr="SELECT lower(column_name) FROM information_schema.columns WHERE table_schema=database() AND table_name = 'xa_access_audit'"; - }else if("ORACLE".equalsIgnoreCase(db_flavor)){ - sqlStr="SELECT lower(column_name) FROM user_tab_cols WHERE table_name = upper('XA_ACCESS_AUDIT')"; - }else if("POSTGRES".equalsIgnoreCase(db_flavor)){ - sqlStr="SELECT lower(attname) FROM pg_attribute WHERE attrelid IN(SELECT oid FROM pg_class WHERE relname='xa_access_audit')"; - }else if("MSSQL".equalsIgnoreCase(db_flavor)){ - sqlStr="SELECT lower(column_name) FROM INFORMATION_SCHEMA.columns WHERE table_name = 'xa_access_audit'"; - }else if("SQLA".equalsIgnoreCase(db_flavor)){ - sqlStr="SELECT lower(cname) FROM SYS.SYSCOLUMNS WHERE tname = 'xa_access_audit'"; - }else{ - return columnList; - } - try { - columnList=getEntityManager().createNativeQuery(sqlStr).getResultList(); - } catch (NoResultException e) { - } - return columnList; - } - public List getByIdRangeV4(long idFrom,long idTo){ - //idFrom and idTo both exclusive - List xXAccessAuditList = new ArrayList(); - try { - xXAccessAuditList= getEntityManager().createNamedQuery("XXAccessAuditV4.getByIdRangeV4", XXAccessAuditV4.class) - .setParameter("idFrom", idFrom) - .setParameter("idTo", idTo) - .getResultList(); - } catch (NoResultException e) { - logger.debug(e.getMessage()); - } - return xXAccessAuditList; - } - public List getByIdRangeV5(long idFrom,long idTo){ - //idFrom and idTo both exclusive - List xXAccessAuditList = new ArrayList(); - try { - xXAccessAuditList= getEntityManager().createNamedQuery("XXAccessAuditV5.getByIdRangeV5", XXAccessAuditV5.class) - .setParameter("idFrom", idFrom) - .setParameter("idTo", idTo) - .getResultList(); - } catch (NoResultException e) { - logger.debug(e.getMessage()); - } - return xXAccessAuditList; - } - public List getByIdRangeV6(long idFrom,long idTo){ - //idFrom and idTo both exclusive - List xXAccessAuditList = new ArrayList(); - try { - xXAccessAuditList= getEntityManager().createNamedQuery("XXAccessAudit.getByIdRangeV6", XXAccessAudit.class) - .setParameter("idFrom", idFrom) - .setParameter("idTo", idTo) - .getResultList(); - } catch (NoResultException e) { - logger.debug(e.getMessage()); - } - return xXAccessAuditList; - } -} + public Long getMaxIdOfXXAccessAudit() { + Long maxXXAccessAuditID = null; + + try { + maxXXAccessAuditID = getEntityManager().createNamedQuery("XXAccessAudit.getMaxIdOfXXAccessAudit", Long.class).getSingleResult(); + } catch (NoResultException e) { + logger.debug(e.getMessage()); + } finally { + if (maxXXAccessAuditID == null) { + maxXXAccessAuditID = 0L; + } + } + + return maxXXAccessAuditID; + } + + @SuppressWarnings("unchecked") + public List getColumnNames(String dbFlavor) { + List columnList = null; + String sqlStr = null; + + if ("MYSQL".equalsIgnoreCase(dbFlavor)) { + sqlStr = "SELECT lower(column_name) FROM information_schema.columns WHERE table_schema=database() AND table_name = 'xa_access_audit'"; + } else if ("ORACLE".equalsIgnoreCase(dbFlavor)) { + sqlStr = "SELECT lower(column_name) FROM user_tab_cols WHERE table_name = upper('XA_ACCESS_AUDIT')"; + } else if ("POSTGRES".equalsIgnoreCase(dbFlavor)) { + sqlStr = "SELECT lower(attname) FROM pg_attribute WHERE attrelid IN(SELECT oid FROM pg_class WHERE relname='xa_access_audit')"; + } else if ("MSSQL".equalsIgnoreCase(dbFlavor)) { + sqlStr = "SELECT lower(column_name) FROM INFORMATION_SCHEMA.columns WHERE table_name = 'xa_access_audit'"; + } else if ("SQLA".equalsIgnoreCase(dbFlavor)) { + sqlStr = "SELECT lower(cname) FROM SYS.SYSCOLUMNS WHERE tname = 'xa_access_audit'"; + } + + try { + if (sqlStr != null) { + columnList = getEntityManager().createNativeQuery(sqlStr).getResultList(); + } + } catch (NoResultException e) { + logger.debug(e.getMessage()); + } finally { + if (columnList == null) { + columnList = new ArrayList<>(); + } + } + + return columnList; + } + + public List getByIdRangeV4(long idFrom, long idTo) { + List xXAccessAuditList = null; + + try { + //idFrom and idTo both exclusive + xXAccessAuditList = getEntityManager().createNamedQuery("XXAccessAuditV4.getByIdRangeV4", XXAccessAuditV4.class) + .setParameter("idFrom", idFrom).setParameter("idTo", idTo).getResultList(); + } catch (NoResultException e) { + logger.debug(e.getMessage()); + } finally { + if (xXAccessAuditList == null) { + xXAccessAuditList = new ArrayList<>(); + } + } + + return xXAccessAuditList; + } + + public List getByIdRangeV5(long idFrom, long idTo) { + List xXAccessAuditList = null; + + try { + //idFrom and idTo both exclusive + xXAccessAuditList = getEntityManager().createNamedQuery("XXAccessAuditV5.getByIdRangeV5", XXAccessAuditV5.class) + .setParameter("idFrom", idFrom).setParameter("idTo", idTo).getResultList(); + } catch (NoResultException e) { + logger.debug(e.getMessage()); + } finally { + if (xXAccessAuditList == null) { + xXAccessAuditList = new ArrayList<>(); + } + } + + return xXAccessAuditList; + } + + public List getByIdRangeV6(long idFrom, long idTo) { + List xXAccessAuditList = null; + + try { + //idFrom and idTo both exclusive + xXAccessAuditList = getEntityManager().createNamedQuery("XXAccessAudit.getByIdRangeV6", XXAccessAudit.class) + .setParameter("idFrom", idFrom).setParameter("idTo", idTo).getResultList(); + } catch (NoResultException e) { + logger.debug(e.getMessage()); + } finally { + if (xXAccessAuditList == null) { + xXAccessAuditList = new ArrayList<>(); + } + } + + return xXAccessAuditList; + } +} diff --git a/security-admin/src/main/java/org/apache/ranger/db/XXAccessTypeDefDao.java b/security-admin/src/main/java/org/apache/ranger/db/XXAccessTypeDefDao.java index 5f4cda7c54..b5244e889e 100644 --- a/security-admin/src/main/java/org/apache/ranger/db/XXAccessTypeDefDao.java +++ b/security-admin/src/main/java/org/apache/ranger/db/XXAccessTypeDefDao.java @@ -17,63 +17,63 @@ package org.apache.ranger.db; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import javax.persistence.NoResultException; - import org.apache.ranger.common.db.BaseDao; import org.apache.ranger.entity.XXAccessTypeDef; import org.springframework.stereotype.Service; +import javax.persistence.NoResultException; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + @Service public class XXAccessTypeDefDao extends BaseDao { + public XXAccessTypeDefDao(RangerDaoManagerBase daoManager) { + super(daoManager); + } + + public List findByServiceDefId(Long serviceDefId) { + if (serviceDefId == null) { + return new ArrayList<>(); + } + + try { + return getEntityManager() + .createNamedQuery("XXAccessTypeDef.findByServiceDefId", tClass) + .setParameter("serviceDefId", serviceDefId).getResultList(); + } catch (NoResultException e) { + return new ArrayList<>(); + } + } - public XXAccessTypeDefDao(RangerDaoManagerBase daoManager) { - super(daoManager); - } - - public List findByServiceDefId(Long serviceDefId) { - if (serviceDefId == null) { - return new ArrayList(); - } - try { - List retList = getEntityManager() - .createNamedQuery("XXAccessTypeDef.findByServiceDefId", tClass) - .setParameter("serviceDefId", serviceDefId).getResultList(); - return retList; - } catch (NoResultException e) { - return new ArrayList(); - } - } + public XXAccessTypeDef findByNameAndServiceId(String name, Long serviceId) { + if (name == null || serviceId == null) { + return null; + } - public XXAccessTypeDef findByNameAndServiceId(String name, Long serviceId) { - if(name == null || serviceId == null) { - return null; - } - try { - return getEntityManager() - .createNamedQuery("XXAccessTypeDef.findByNameAndServiceId", tClass) - .setParameter("name", name).setParameter("serviceId", serviceId) - .getSingleResult(); - } catch (NoResultException e) { - return null; - } - } + try { + return getEntityManager() + .createNamedQuery("XXAccessTypeDef.findByNameAndServiceId", tClass) + .setParameter("name", name).setParameter("serviceId", serviceId) + .getSingleResult(); + } catch (NoResultException e) { + return null; + } + } - public List getNamesByServiceName(String serviceName) { - List ret = null; + public List getNamesByServiceName(String serviceName) { + List ret = null; - if (serviceName != null) { - try { - ret = getEntityManager().createNamedQuery("XXAccessTypeDef.getNamesByServiceName", String.class) - .setParameter("serviceName", serviceName).getResultList(); - } catch (NoResultException excp) { - // ignore - } - } + if (serviceName != null) { + try { + ret = getEntityManager().createNamedQuery("XXAccessTypeDef.getNamesByServiceName", String.class) + .setParameter("serviceName", serviceName).getResultList(); + } catch (NoResultException excp) { + // ignore + } + } - return ret != null ? ret : Collections.emptyList(); - } + return ret != null ? ret : Collections.emptyList(); + } } diff --git a/security-admin/src/main/java/org/apache/ranger/db/XXAccessTypeDefGrantsDao.java b/security-admin/src/main/java/org/apache/ranger/db/XXAccessTypeDefGrantsDao.java index f980d621f0..75b6965166 100644 --- a/security-admin/src/main/java/org/apache/ranger/db/XXAccessTypeDefGrantsDao.java +++ b/security-admin/src/main/java/org/apache/ranger/db/XXAccessTypeDefGrantsDao.java @@ -17,92 +17,83 @@ package org.apache.ranger.db; +import org.apache.ranger.common.db.BaseDao; +import org.apache.ranger.entity.XXAccessTypeDefGrants; +import org.springframework.stereotype.Service; + +import javax.persistence.NoResultException; + import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; -import javax.persistence.NoResultException; - -import org.apache.ranger.common.db.BaseDao; -import org.apache.ranger.entity.XXAccessTypeDefGrants; -import org.springframework.stereotype.Service; - @Service public class XXAccessTypeDefGrantsDao extends BaseDao { - - public XXAccessTypeDefGrantsDao(RangerDaoManagerBase daoManager) { - super(daoManager); - } - - @SuppressWarnings("unchecked") - public List findImpliedGrantsByATDId(Long atdId) { - if(atdId == null) { - return new ArrayList(); - } - try { - List returnList = getEntityManager() - .createNamedQuery("XXAccessTypeDefGrants.findImpliedGrantsByATDId") - .setParameter("atdId", atdId).getResultList(); - - return returnList; - } catch (NoResultException e) { - return new ArrayList(); - } - } - - public Map> findImpliedGrantsByServiceDefId(Long serviceDefId) { - final Map> ret = new HashMap<>(); - - if (serviceDefId != null) { - @SuppressWarnings("unchecked") - List rows = (List) getEntityManager() - .createNamedQuery("XXAccessTypeDefGrants.findByServiceDefId") - .setParameter("serviceDefId", serviceDefId) - .getResultList(); - - if (rows != null) { - for (Object[] row : rows) { - String accessType = (String) row[0]; - String impliedGrant = (String) row[1]; - List impliedGrants = ret.get(accessType); - - if (impliedGrants == null) { - impliedGrants = new ArrayList<>(); - - ret.put(accessType, impliedGrants); - } - - impliedGrants.add(impliedGrant); - } - } - } - - return ret; - } - - public XXAccessTypeDefGrants findByNameAndATDId(Long atdId, String name) { - if (atdId == null || name == null) { - return null; - } - try { - return getEntityManager().createNamedQuery("XXAccessTypeDefGrants.findByNameAndATDId", tClass) - .setParameter("atdId", atdId).setParameter("name", name).getSingleResult(); - } catch (NoResultException e) { - return null; - } - } - - public List findByATDId(Long atdId) { - if (atdId == null) { - return new ArrayList(); - } - try { - return getEntityManager().createNamedQuery("XXAccessTypeDefGrants.findByATDId", tClass) - .setParameter("atdId", atdId).getResultList(); - } catch (NoResultException e) { - return new ArrayList(); - } - } - + public XXAccessTypeDefGrantsDao(RangerDaoManagerBase daoManager) { + super(daoManager); + } + + public List findImpliedGrantsByATDId(Long atdId) { + if (atdId == null) { + return new ArrayList<>(); + } + + try { + return getEntityManager() + .createNamedQuery("XXAccessTypeDefGrants.findImpliedGrantsByATDId", String.class) + .setParameter("atdId", atdId).getResultList(); + } catch (NoResultException e) { + return new ArrayList<>(); + } + } + + public Map> findImpliedGrantsByServiceDefId(Long serviceDefId) { + final Map> ret = new HashMap<>(); + + if (serviceDefId != null) { + List rows = getEntityManager() + .createNamedQuery("XXAccessTypeDefGrants.findByServiceDefId", Object[].class) + .setParameter("serviceDefId", serviceDefId) + .getResultList(); + + if (rows != null) { + for (Object[] row : rows) { + String accessType = (String) row[0]; + String impliedGrant = (String) row[1]; + List impliedGrants = ret.computeIfAbsent(accessType, k -> new ArrayList<>()); + + impliedGrants.add(impliedGrant); + } + } + } + + return ret; + } + + public XXAccessTypeDefGrants findByNameAndATDId(Long atdId, String name) { + if (atdId == null || name == null) { + return null; + } + + try { + return getEntityManager().createNamedQuery("XXAccessTypeDefGrants.findByNameAndATDId", tClass) + .setParameter("atdId", atdId).setParameter("name", name).getSingleResult(); + } catch (NoResultException e) { + return null; + } + } + + public List findByATDId(Long atdId) { + if (atdId == null) { + return new ArrayList<>(); + } + + try { + return getEntityManager().createNamedQuery("XXAccessTypeDefGrants.findByATDId", tClass) + .setParameter("atdId", atdId).getResultList(); + } catch (NoResultException e) { + return new ArrayList<>(); + } + } } 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 index ff54c30052..b9f80bf441 100644 --- a/security-admin/src/main/java/org/apache/ranger/db/XXAssetDao.java +++ b/security-admin/src/main/java/org/apache/ranger/db/XXAssetDao.java @@ -17,9 +17,7 @@ * under the License. */ - package org.apache.ranger.db; - -import javax.persistence.NoResultException; +package org.apache.ranger.db; import org.apache.ranger.common.RangerCommonEnums; import org.apache.ranger.common.db.BaseDao; @@ -28,30 +26,33 @@ import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; +import javax.persistence.NoResultException; + @Service public class XXAssetDao extends BaseDao { - private static final Logger logger = LoggerFactory.getLogger(XXAssetDao.class); + private static final Logger logger = LoggerFactory.getLogger(XXAssetDao.class); - public XXAssetDao( RangerDaoManagerBase daoManager ) { - super(daoManager); + public XXAssetDao(RangerDaoManagerBase 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",RangerCommonEnums.STATUS_DELETED) - .getSingleResult(); - } catch (NoResultException e) { - // ignore - } - return null; - } + 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", RangerCommonEnums.STATUS_DELETED) + .getSingleResult(); + } catch (NoResultException e) { + // ignore + } + return null; + } +} 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 index 713dbe81fc..db1b1acfb4 100644 --- a/security-admin/src/main/java/org/apache/ranger/db/XXAuditMapDao.java +++ b/security-admin/src/main/java/org/apache/ranger/db/XXAuditMapDao.java @@ -17,12 +17,7 @@ * under the License. */ - package org.apache.ranger.db; - -import java.util.ArrayList; -import java.util.List; - -import javax.persistence.NoResultException; +package org.apache.ranger.db; import org.apache.ranger.common.db.BaseDao; import org.apache.ranger.entity.XXAuditMap; @@ -30,30 +25,35 @@ import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; +import javax.persistence.NoResultException; + +import java.util.ArrayList; +import java.util.List; + @Service public class XXAuditMapDao extends BaseDao { - private static final Logger logger = LoggerFactory.getLogger(XXAssetDao.class); + private static final Logger logger = LoggerFactory.getLogger(XXAuditMapDao.class); - public XXAuditMapDao( RangerDaoManagerBase daoManager ) { - super(daoManager); + public XXAuditMapDao(RangerDaoManagerBase daoManager) { + super(daoManager); } - public List 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(); - } - return new ArrayList(); - } - + public List 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<>(); + } + + return new ArrayList<>(); + } } - 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 index 645c27cbde..91d4a0d51d 100644 --- a/security-admin/src/main/java/org/apache/ranger/db/XXAuthSessionDao.java +++ b/security-admin/src/main/java/org/apache/ranger/db/XXAuthSessionDao.java @@ -17,13 +17,7 @@ * under the License. */ - package org.apache.ranger.db; - - import java.util.Date; - import java.util.List; - import java.util.concurrent.TimeUnit; - -import javax.persistence.NoResultException; +package org.apache.ranger.db; import org.apache.ranger.common.DateUtil; import org.apache.ranger.common.db.BaseDao; @@ -32,80 +26,83 @@ import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; +import javax.persistence.NoResultException; + +import java.util.Date; +import java.util.List; +import java.util.concurrent.TimeUnit; + @Service public class XXAuthSessionDao extends BaseDao { + private static final Logger LOG = LoggerFactory.getLogger(XXAuthSessionDao.class); - private static final Logger LOG = LoggerFactory.getLogger(XXAuthSessionDao.class); + public XXAuthSessionDao(RangerDaoManagerBase daoManager) { + super(daoManager); + } - public XXAuthSessionDao( RangerDaoManagerBase daoManager ) { - super(daoManager); + public List getUserLoggedIn() { + return getEntityManager() + .createNamedQuery("XXAuthSession.getUserLoggedIn", Object[].class) + .getResultList(); } - @SuppressWarnings("unchecked") - public List 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; + } } - - public XXAuthSession getAuthSessionBySessionId(String sessionId){ - try{ - return (XXAuthSession) getEntityManager() - .createNamedQuery("XXAuthSession.getAuthSessionBySessionId") - .setParameter("sessionId", sessionId) - .getSingleResult(); - } catch(NoResultException ignoreNoResultFound) { - return null; - } - } - - @SuppressWarnings("unchecked") - public List getAuthSessionByUserId(Long userId){ - try{ - return getEntityManager() - .createNamedQuery("XXAuthSession.getAuthSessionByUserId") - .setParameter("userId", userId) - .getResultList(); - } catch(NoResultException ignoreNoResultFound) { - return null; - } - } - - public long getRecentAuthFailureCountByLoginId(String loginId, int timeRangezSecond){ - Date authWindowStartTime = new Date(DateUtil.getUTCDate().getTime() - timeRangezSecond * 1000); - - return getEntityManager() - .createNamedQuery("XXAuthSession.getRecentAuthFailureCountByLoginId", Long.class) - .setParameter("loginId", loginId) - .setParameter("authWindowStartTime", authWindowStartTime) - .getSingleResult(); - } - public List getAuthSessionIdsByUserId(Long userId) { - if(userId == null) { - return null; - } - - return getEntityManager() - .createNamedQuery("XXAuthSession.findIdsByUserId", Long.class) - .setParameter("userId", userId) - .getResultList(); - } - - public void deleteAuthSessionsByIds(List ids){ - batchDeleteByIds("XXAuthSession.deleteByIds", ids, "ids"); - } - - public long deleteOlderThan(int olderThanInDays) { - Date since = new Date(System.currentTimeMillis() - TimeUnit.DAYS.toMillis(olderThanInDays)); - - LOG.info("Deleting x_auth_sess records that are older than " + olderThanInDays + " days, that is, older than " + since); - long ret = getEntityManager().createNamedQuery("XXAuthSession.deleteOlderThan").setParameter("olderThan", since).executeUpdate(); - LOG.info("Deleted " + ret + " x_auth_sess records"); - - LOG.info("Updating x_trx_log.sess_id with null which are older than " + olderThanInDays + " days, that is, older than " + since); - long updated = getEntityManager().createNamedQuery("XXTrxLog.updateSessIdWithNull").setParameter("olderThan", since).executeUpdate(); - LOG.info("Updated " + updated + " x_trx_log records"); - return ret; - } -} + public List getAuthSessionByUserId(Long userId) { + try { + return getEntityManager() + .createNamedQuery("XXAuthSession.getAuthSessionByUserId", tClass) + .setParameter("userId", userId) + .getResultList(); + } catch (NoResultException ignoreNoResultFound) { + return null; + } + } + + public long getRecentAuthFailureCountByLoginId(String loginId, int timeRangezSecond) { + Date authWindowStartTime = new Date(DateUtil.getUTCDate().getTime() - timeRangezSecond * 1000L); + + return getEntityManager() + .createNamedQuery("XXAuthSession.getRecentAuthFailureCountByLoginId", Long.class) + .setParameter("loginId", loginId) + .setParameter("authWindowStartTime", authWindowStartTime) + .getSingleResult(); + } + + public List getAuthSessionIdsByUserId(Long userId) { + if (userId == null) { + return null; + } + + return getEntityManager() + .createNamedQuery("XXAuthSession.findIdsByUserId", Long.class) + .setParameter("userId", userId) + .getResultList(); + } + + public void deleteAuthSessionsByIds(List ids) { + batchDeleteByIds("XXAuthSession.deleteByIds", ids, "ids"); + } + + public long deleteOlderThan(int olderThanInDays) { + Date since = new Date(System.currentTimeMillis() - TimeUnit.DAYS.toMillis(olderThanInDays)); + + LOG.info("Deleting x_auth_sess records that are older than {} days, that is, older than {}", olderThanInDays, since); + long ret = getEntityManager().createNamedQuery("XXAuthSession.deleteOlderThan").setParameter("olderThan", since).executeUpdate(); + LOG.info("Deleted {} x_auth_sess records", ret); + + LOG.info("Updating x_trx_log.sess_id with null which are older than {} days, that is, older than {}", olderThanInDays, since); + long updated = getEntityManager().createNamedQuery("XXTrxLog.updateSessIdWithNull").setParameter("olderThan", since).executeUpdate(); + LOG.info("Updated {} x_trx_log records", updated); + return ret; + } +} diff --git a/security-admin/src/main/java/org/apache/ranger/db/XXContextEnricherDefDao.java b/security-admin/src/main/java/org/apache/ranger/db/XXContextEnricherDefDao.java index 57fbe8badf..55a19fcebf 100644 --- a/security-admin/src/main/java/org/apache/ranger/db/XXContextEnricherDefDao.java +++ b/security-admin/src/main/java/org/apache/ranger/db/XXContextEnricherDefDao.java @@ -19,48 +19,47 @@ package org.apache.ranger.db; -import java.util.ArrayList; -import java.util.List; - -import javax.persistence.NoResultException; - import org.apache.ranger.common.db.BaseDao; import org.apache.ranger.entity.XXContextEnricherDef; import org.springframework.stereotype.Service; +import javax.persistence.NoResultException; + +import java.util.ArrayList; +import java.util.List; + @Service public class XXContextEnricherDefDao extends BaseDao { + public XXContextEnricherDefDao(RangerDaoManagerBase daoManager) { + super(daoManager); + } + + public List findByServiceDefId(Long serviceDefId) { + if (serviceDefId == null) { + return new ArrayList<>(); + } - public XXContextEnricherDefDao(RangerDaoManagerBase daoManager) { - super(daoManager); - } + try { + return getEntityManager() + .createNamedQuery("XXContextEnricherDef.findByServiceDefId", tClass) + .setParameter("serviceDefId", serviceDefId).getResultList(); + } catch (NoResultException e) { + return new ArrayList<>(); + } + } - public List findByServiceDefId(Long serviceDefId) { - if (serviceDefId == null) { - return new ArrayList(); - } - try { - List retList = getEntityManager() - .createNamedQuery("XXContextEnricherDef.findByServiceDefId", tClass) - .setParameter("serviceDefId", serviceDefId).getResultList(); - return retList; - } catch (NoResultException e) { - return new ArrayList(); - } - } + public XXContextEnricherDef findByServiceDefIdAndName(Long serviceDefId, String name) { + if (serviceDefId == null) { + return null; + } - public XXContextEnricherDef findByServiceDefIdAndName(Long serviceDefId, String name) { - if (serviceDefId == null) { - return null; - } - try { - XXContextEnricherDef retList = getEntityManager() - .createNamedQuery("XXContextEnricherDef.findByServiceDefIdAndName", tClass) - .setParameter("serviceDefId", serviceDefId) - .setParameter("name", name).getSingleResult(); - return retList; - } catch (NoResultException e) { - return null; - } - } + try { + return getEntityManager() + .createNamedQuery("XXContextEnricherDef.findByServiceDefIdAndName", tClass) + .setParameter("serviceDefId", serviceDefId) + .setParameter("name", name).getSingleResult(); + } catch (NoResultException e) { + return null; + } + } } 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 index 93c297f50d..4a7bdf6526 100644 --- a/security-admin/src/main/java/org/apache/ranger/db/XXCredentialStoreDao.java +++ b/security-admin/src/main/java/org/apache/ranger/db/XXCredentialStoreDao.java @@ -17,7 +17,7 @@ * under the License. */ - package org.apache.ranger.db; +package org.apache.ranger.db; import org.apache.ranger.common.db.BaseDao; import org.apache.ranger.entity.XXCredentialStore; @@ -25,9 +25,7 @@ @Service public class XXCredentialStoreDao extends BaseDao { - - public XXCredentialStoreDao( RangerDaoManagerBase daoManager ) { - super(daoManager); + public XXCredentialStoreDao(RangerDaoManagerBase daoManager) { + super(daoManager); } } - 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 index ddb0811ea9..8fdf15f810 100644 --- a/security-admin/src/main/java/org/apache/ranger/db/XXDBBaseDao.java +++ b/security-admin/src/main/java/org/apache/ranger/db/XXDBBaseDao.java @@ -17,7 +17,7 @@ * under the License. */ - package org.apache.ranger.db; +package org.apache.ranger.db; import org.apache.ranger.common.db.BaseDao; import org.apache.ranger.entity.XXDBBase; @@ -25,9 +25,7 @@ @Service public class XXDBBaseDao extends BaseDao { - - public XXDBBaseDao( RangerDaoManagerBase daoManager ) { - super(daoManager); + public XXDBBaseDao(RangerDaoManagerBase daoManager) { + super(daoManager); } } - diff --git a/security-admin/src/main/java/org/apache/ranger/db/XXDataHistDao.java b/security-admin/src/main/java/org/apache/ranger/db/XXDataHistDao.java index 595912eb75..7012a06419 100644 --- a/security-admin/src/main/java/org/apache/ranger/db/XXDataHistDao.java +++ b/security-admin/src/main/java/org/apache/ranger/db/XXDataHistDao.java @@ -17,83 +17,86 @@ package org.apache.ranger.db; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; - -import javax.persistence.NoResultException; - +import org.apache.ranger.common.DateUtil; import org.apache.ranger.common.db.BaseDao; import org.apache.ranger.entity.XXDataHist; -import org.apache.ranger.common.DateUtil; import org.springframework.stereotype.Service; +import javax.persistence.NoResultException; + +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + @Service public class XXDataHistDao extends BaseDao { + public XXDataHistDao(RangerDaoManagerBase daoManager) { + super(daoManager); + } + + public XXDataHist findLatestByObjectClassTypeAndObjectId(Integer classType, Long objectId) { + if (classType == null || objectId == null) { + return null; + } + + try { + return getEntityManager() + .createNamedQuery("XXDataHist.findLatestByObjectClassTypeAndObjectId", tClass) + .setParameter("classType", classType) + .setParameter("objectId", objectId) + .setMaxResults(1).getSingleResult(); + } catch (NoResultException e) { + return null; + } + } + + public XXDataHist findObjByEventTimeClassTypeAndId(String eventTime, int classType, Long objId) { + if (eventTime == null || objId == null) { + return null; + } + + Date date = DateUtil.stringToDate(eventTime, "yyyy-MM-dd'T'HH:mm:ss'Z'"); + + if (date == null) { + return null; + } - public XXDataHistDao(RangerDaoManagerBase daoManager) { - super(daoManager); - } + try { + return getEntityManager() + .createNamedQuery("XXDataHist.findLatestByObjectClassTypeAndObjectIdAndEventTime", tClass) + .setParameter("classType", classType) + .setParameter("objectId", objId) + .setParameter("createTime", date) + .setMaxResults(1).getSingleResult(); + } catch (NoResultException e) { + return null; + } + } - public XXDataHist findLatestByObjectClassTypeAndObjectId(Integer classType, Long objectId) { - if(classType == null || objectId == null) { - return null; - } - try { - return getEntityManager() - .createNamedQuery("XXDataHist.findLatestByObjectClassTypeAndObjectId", tClass) - .setParameter("classType", classType) - .setParameter("objectId", objectId) - .setMaxResults(1).getSingleResult(); - } catch (NoResultException e) { - return null; - } - } - - public XXDataHist findObjByEventTimeClassTypeAndId(String eventTime, int classType, Long objId) { - if (eventTime == null || objId == null) { - return null; - } - Date date=DateUtil.stringToDate(eventTime,"yyyy-MM-dd'T'HH:mm:ss'Z'"); - if(date==null){ - return null; - } - try { - return getEntityManager() - .createNamedQuery("XXDataHist.findLatestByObjectClassTypeAndObjectIdAndEventTime", tClass) - .setParameter("classType", classType) - .setParameter("objectId", objId) - .setParameter("createTime", date) - .setMaxResults(1).getSingleResult(); - } catch (NoResultException e) { - return null; - } - } + public List getVersionListOfObject(Long objId, int classType) { + if (objId == null) { + return new ArrayList<>(); + } - @SuppressWarnings("unchecked") - public List getVersionListOfObject(Long objId, int classType) { - if (objId == null) { - return new ArrayList(); - } - try { - return getEntityManager().createNamedQuery("XXDataHist.getVersionListOfObject") - .setParameter("objId", objId).setParameter("classType", classType).getResultList(); - } catch (NoResultException e) { - return new ArrayList(); - } - } + try { + return getEntityManager().createNamedQuery("XXDataHist.getVersionListOfObject", Integer.class) + .setParameter("objId", objId).setParameter("classType", classType).getResultList(); + } catch (NoResultException e) { + return new ArrayList<>(); + } + } - public XXDataHist findObjectByVersionNumber(Long objId, int classType, int versionNo) { - if (objId == null) { - return null; - } - try { - return getEntityManager().createNamedQuery("XXDataHist.findObjectByVersionNumber", tClass) - .setParameter("objId", objId).setParameter("classType", classType) - .setParameter("version", versionNo).getSingleResult(); - } catch (NoResultException e) { - return null; - } - } + public XXDataHist findObjectByVersionNumber(Long objId, int classType, int versionNo) { + if (objId == null) { + return null; + } + try { + return getEntityManager().createNamedQuery("XXDataHist.findObjectByVersionNumber", tClass) + .setParameter("objId", objId).setParameter("classType", classType) + .setParameter("version", versionNo).getSingleResult(); + } catch (NoResultException e) { + return null; + } + } } diff --git a/security-admin/src/main/java/org/apache/ranger/db/XXDataMaskTypeDefDao.java b/security-admin/src/main/java/org/apache/ranger/db/XXDataMaskTypeDefDao.java index 5a0611f893..5deab9cc70 100644 --- a/security-admin/src/main/java/org/apache/ranger/db/XXDataMaskTypeDefDao.java +++ b/security-admin/src/main/java/org/apache/ranger/db/XXDataMaskTypeDefDao.java @@ -17,63 +17,63 @@ package org.apache.ranger.db; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import javax.persistence.NoResultException; - import org.apache.ranger.common.db.BaseDao; import org.apache.ranger.entity.XXDataMaskTypeDef; import org.springframework.stereotype.Service; +import javax.persistence.NoResultException; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + @Service public class XXDataMaskTypeDefDao extends BaseDao { + public XXDataMaskTypeDefDao(RangerDaoManagerBase daoManager) { + super(daoManager); + } + + public List findByServiceDefId(Long serviceDefId) { + if (serviceDefId == null) { + return new ArrayList<>(); + } - public XXDataMaskTypeDefDao(RangerDaoManagerBase daoManager) { - super(daoManager); - } + try { + return getEntityManager() + .createNamedQuery("XXDataMaskTypeDef.findByServiceDefId", tClass) + .setParameter("serviceDefId", serviceDefId).getResultList(); + } catch (NoResultException e) { + return new ArrayList<>(); + } + } - public List findByServiceDefId(Long serviceDefId) { - if (serviceDefId == null) { - return new ArrayList(); - } - try { - List retList = getEntityManager() - .createNamedQuery("XXDataMaskTypeDef.findByServiceDefId", tClass) - .setParameter("serviceDefId", serviceDefId).getResultList(); - return retList; - } catch (NoResultException e) { - return new ArrayList(); - } - } + public XXDataMaskTypeDef findByNameAndServiceId(String name, Long serviceId) { + if (name == null || serviceId == null) { + return null; + } - public XXDataMaskTypeDef findByNameAndServiceId(String name, Long serviceId) { - if(name == null || serviceId == null) { - return null; - } - try { - return getEntityManager() - .createNamedQuery("XXDataMaskTypeDef.findByNameAndServiceId", tClass) - .setParameter("name", name).setParameter("serviceId", serviceId) - .getSingleResult(); - } catch (NoResultException e) { - return null; - } - } + try { + return getEntityManager() + .createNamedQuery("XXDataMaskTypeDef.findByNameAndServiceId", tClass) + .setParameter("name", name).setParameter("serviceId", serviceId) + .getSingleResult(); + } catch (NoResultException e) { + return null; + } + } - public List getNamesByServiceName(String serviceName) { - List ret = null; + public List getNamesByServiceName(String serviceName) { + List ret = null; - if (serviceName != null) { - try { - ret = getEntityManager().createNamedQuery("XXDataMaskTypeDef.getNamesByServiceName", String.class) - .setParameter("serviceName", serviceName).getResultList(); - } catch (NoResultException excp) { - // ignore - } - } + if (serviceName != null) { + try { + ret = getEntityManager().createNamedQuery("XXDataMaskTypeDef.getNamesByServiceName", String.class) + .setParameter("serviceName", serviceName).getResultList(); + } catch (NoResultException excp) { + // ignore + } + } - return ret != null ? ret : Collections.emptyList(); - } + return ret != null ? ret : Collections.emptyList(); + } } diff --git a/security-admin/src/main/java/org/apache/ranger/db/XXEnumDefDao.java b/security-admin/src/main/java/org/apache/ranger/db/XXEnumDefDao.java index bcfd36d53b..148f3cec87 100644 --- a/security-admin/src/main/java/org/apache/ranger/db/XXEnumDefDao.java +++ b/security-admin/src/main/java/org/apache/ranger/db/XXEnumDefDao.java @@ -17,34 +17,32 @@ package org.apache.ranger.db; -import java.util.ArrayList; -import java.util.List; - -import javax.persistence.NoResultException; - import org.apache.ranger.common.db.BaseDao; import org.apache.ranger.entity.XXEnumDef; import org.springframework.stereotype.Service; +import javax.persistence.NoResultException; + +import java.util.ArrayList; +import java.util.List; + @Service public class XXEnumDefDao extends BaseDao { + public XXEnumDefDao(RangerDaoManagerBase daoManager) { + super(daoManager); + } - public XXEnumDefDao(RangerDaoManagerBase daoManager) { - super(daoManager); - } + public List findByServiceDefId(Long serviceDefId) { + if (serviceDefId == null) { + return new ArrayList<>(); + } - public List findByServiceDefId(Long serviceDefId) { - if (serviceDefId == null) { - return new ArrayList(); - } - try { - List retList = getEntityManager() - .createNamedQuery("XXEnumDef.findByServiceDefId", tClass) - .setParameter("serviceDefId", serviceDefId).getResultList(); - return retList; - } catch (NoResultException e) { - return new ArrayList(); - } - } - + try { + return getEntityManager() + .createNamedQuery("XXEnumDef.findByServiceDefId", tClass) + .setParameter("serviceDefId", serviceDefId).getResultList(); + } catch (NoResultException e) { + return new ArrayList<>(); + } + } } diff --git a/security-admin/src/main/java/org/apache/ranger/db/XXEnumElementDefDao.java b/security-admin/src/main/java/org/apache/ranger/db/XXEnumElementDefDao.java index 370282176a..4e795da3c3 100644 --- a/security-admin/src/main/java/org/apache/ranger/db/XXEnumElementDefDao.java +++ b/security-admin/src/main/java/org/apache/ranger/db/XXEnumElementDefDao.java @@ -17,34 +17,32 @@ package org.apache.ranger.db; -import java.util.ArrayList; -import java.util.List; - -import javax.persistence.NoResultException; - import org.apache.ranger.common.db.BaseDao; import org.apache.ranger.entity.XXEnumElementDef; import org.springframework.stereotype.Service; -@Service -public class XXEnumElementDefDao extends BaseDao { - - public XXEnumElementDefDao(RangerDaoManagerBase daoManager) { - super(daoManager); - } +import javax.persistence.NoResultException; - public List findByEnumDefId(Long enumDefId) { - if(enumDefId == null) { - return new ArrayList(); - } - try { - List returnList = getEntityManager() - .createNamedQuery("XXEnumElementDef.findByEnumDefId", tClass) - .setParameter("enumDefId", enumDefId).getResultList(); - return returnList; - } catch (NoResultException e) { - return new ArrayList(); - } - } +import java.util.ArrayList; +import java.util.List; +@Service +public class XXEnumElementDefDao extends BaseDao { + public XXEnumElementDefDao(RangerDaoManagerBase daoManager) { + super(daoManager); + } + + public List findByEnumDefId(Long enumDefId) { + if (enumDefId == null) { + return new ArrayList<>(); + } + + try { + return getEntityManager() + .createNamedQuery("XXEnumElementDef.findByEnumDefId", tClass) + .setParameter("enumDefId", enumDefId).getResultList(); + } catch (NoResultException e) { + return new ArrayList<>(); + } + } } diff --git a/security-admin/src/main/java/org/apache/ranger/db/XXGdsDataShareDao.java b/security-admin/src/main/java/org/apache/ranger/db/XXGdsDataShareDao.java index 20084bcfbc..ad32aeeb0d 100644 --- a/security-admin/src/main/java/org/apache/ranger/db/XXGdsDataShareDao.java +++ b/security-admin/src/main/java/org/apache/ranger/db/XXGdsDataShareDao.java @@ -29,146 +29,146 @@ import org.springframework.stereotype.Service; import javax.persistence.NoResultException; + import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; - @Service public class XXGdsDataShareDao extends BaseDao { - private static final Logger LOG = LoggerFactory.getLogger(XXGdsDataShareDao.class); - - public XXGdsDataShareDao(RangerDaoManagerBase daoManager) { - super(daoManager); - } - - public XXGdsDataShare findByGuid(String guid) { - XXGdsDataShare ret = null; - - if (StringUtils.isNotBlank(guid)) { - try { - ret = getEntityManager().createNamedQuery("XXGdsDataShare.findByGuid", tClass) - .setParameter("guid", guid).getSingleResult(); - } catch (NoResultException e) { - LOG.debug("findByGuid({}): ", guid, e); - } - } - - return ret; - } - - public XXGdsDataShare findByName(String name) { - XXGdsDataShare ret = null; - - if (StringUtils.isNotBlank(name)) { - try { - ret = getEntityManager().createNamedQuery("XXGdsDataShare.findByName", tClass) - .setParameter("name", name).getSingleResult(); - } catch (NoResultException e) { - LOG.debug("findByName({}): ", name, e); - } - } - - return ret; - } - - public List findByServiceId(Long serviceId) { - List ret = null; - - if (serviceId != null) { - try { - ret = getEntityManager().createNamedQuery("XXGdsDataShare.findByServiceId", tClass) - .setParameter("serviceId", serviceId).getResultList(); - } catch (NoResultException e) { - LOG.debug("findByServiceId({}): ", serviceId, e); - } - } - - return ret != null ? ret : Collections.emptyList(); - } - - public List findByZoneId(Long zoneId) { - List ret = null; - - if (zoneId != null) { - try { - ret = getEntityManager().createNamedQuery("XXGdsDataShare.findByZoneId", tClass) - .setParameter("zoneId", zoneId).getResultList(); - } catch (NoResultException e) { - LOG.debug("findByZoneId({}): ", zoneId, e); - } - } - - return ret != null ? ret : Collections.emptyList(); - } - - public List findByServiceIdAndZoneId(Long serviceId, Long zoneId) { - List ret = null; - - if (serviceId != null && zoneId != null) { - try { - ret = getEntityManager().createNamedQuery("XXGdsDataShare.findByServiceIdAndZoneId", tClass) - .setParameter("serviceId", serviceId) - .setParameter("zoneId", zoneId).getResultList(); - } catch (NoResultException e) { - LOG.debug("findByServiceIdAndZoneId({}, {}): ", serviceId, zoneId, e); - } - } - - return ret != null ? ret : Collections.emptyList(); - } - - public List findByDatasetId(Long datasetId) { - List ret = null; - - if (datasetId != null) { - try { - ret = getEntityManager().createNamedQuery("XXGdsDataShare.findByDatasetId", tClass) - .setParameter("datasetId", datasetId).getResultList(); - } catch (NoResultException e) { - LOG.debug("findByDatasetId({}): ", datasetId, e); - } - } - - return ret != null ? ret : Collections.emptyList(); - } - - public List findServiceIdsForDataShareId(Long dataShareId) { - List ret = null; - - if (dataShareId != null) { - try { - ret = getEntityManager().createNamedQuery("XXGdsDataShare.findServiceIds", Long.class) - .setParameter("dataShareId", dataShareId).getResultList(); - } catch (NoResultException e) { - LOG.debug("findServiceIdsForDataShareId({}): ", dataShareId, e); - } - } - - return ret != null ? ret : Collections.emptyList(); - } - - public Map getDataShareIdsAndACLs() { - Map ret = new HashMap<>(); - - try { - List rows = getEntityManager().createNamedQuery("XXGdsDataShare.getDataShareIdsAndACLs", Object[].class).getResultList(); - - if (rows != null) { - for (Object[] row : rows) { - Long id = (Long) row[0]; - RangerGdsObjectACL acl = JsonUtils.jsonToObject((String) row[1], RangerGdsObjectACL.class); - - if (acl != null) { - ret.put(id, acl); - } - } - } - } catch (NoResultException e) { - LOG.debug("getDataShareIdsAndACLs()", e); - } - - return ret; - } + private static final Logger LOG = LoggerFactory.getLogger(XXGdsDataShareDao.class); + + public XXGdsDataShareDao(RangerDaoManagerBase daoManager) { + super(daoManager); + } + + public XXGdsDataShare findByGuid(String guid) { + XXGdsDataShare ret = null; + + if (StringUtils.isNotBlank(guid)) { + try { + ret = getEntityManager().createNamedQuery("XXGdsDataShare.findByGuid", tClass) + .setParameter("guid", guid).getSingleResult(); + } catch (NoResultException e) { + LOG.debug("findByGuid({}): ", guid, e); + } + } + + return ret; + } + + public XXGdsDataShare findByName(String name) { + XXGdsDataShare ret = null; + + if (StringUtils.isNotBlank(name)) { + try { + ret = getEntityManager().createNamedQuery("XXGdsDataShare.findByName", tClass) + .setParameter("name", name).getSingleResult(); + } catch (NoResultException e) { + LOG.debug("findByName({}): ", name, e); + } + } + + return ret; + } + + public List findByServiceId(Long serviceId) { + List ret = null; + + if (serviceId != null) { + try { + ret = getEntityManager().createNamedQuery("XXGdsDataShare.findByServiceId", tClass) + .setParameter("serviceId", serviceId).getResultList(); + } catch (NoResultException e) { + LOG.debug("findByServiceId({}): ", serviceId, e); + } + } + + return ret != null ? ret : Collections.emptyList(); + } + + public List findByZoneId(Long zoneId) { + List ret = null; + + if (zoneId != null) { + try { + ret = getEntityManager().createNamedQuery("XXGdsDataShare.findByZoneId", tClass) + .setParameter("zoneId", zoneId).getResultList(); + } catch (NoResultException e) { + LOG.debug("findByZoneId({}): ", zoneId, e); + } + } + + return ret != null ? ret : Collections.emptyList(); + } + + public List findByServiceIdAndZoneId(Long serviceId, Long zoneId) { + List ret = null; + + if (serviceId != null && zoneId != null) { + try { + ret = getEntityManager().createNamedQuery("XXGdsDataShare.findByServiceIdAndZoneId", tClass) + .setParameter("serviceId", serviceId) + .setParameter("zoneId", zoneId).getResultList(); + } catch (NoResultException e) { + LOG.debug("findByServiceIdAndZoneId({}, {}): ", serviceId, zoneId, e); + } + } + + return ret != null ? ret : Collections.emptyList(); + } + + public List findByDatasetId(Long datasetId) { + List ret = null; + + if (datasetId != null) { + try { + ret = getEntityManager().createNamedQuery("XXGdsDataShare.findByDatasetId", tClass) + .setParameter("datasetId", datasetId).getResultList(); + } catch (NoResultException e) { + LOG.debug("findByDatasetId({}): ", datasetId, e); + } + } + + return ret != null ? ret : Collections.emptyList(); + } + + public List findServiceIdsForDataShareId(Long dataShareId) { + List ret = null; + + if (dataShareId != null) { + try { + ret = getEntityManager().createNamedQuery("XXGdsDataShare.findServiceIds", Long.class) + .setParameter("dataShareId", dataShareId).getResultList(); + } catch (NoResultException e) { + LOG.debug("findServiceIdsForDataShareId({}): ", dataShareId, e); + } + } + + return ret != null ? ret : Collections.emptyList(); + } + + public Map getDataShareIdsAndACLs() { + Map ret = new HashMap<>(); + + try { + List rows = getEntityManager().createNamedQuery("XXGdsDataShare.getDataShareIdsAndACLs", Object[].class).getResultList(); + + if (rows != null) { + for (Object[] row : rows) { + Long id = (Long) row[0]; + RangerGdsObjectACL acl = JsonUtils.jsonToObject((String) row[1], RangerGdsObjectACL.class); + + if (acl != null) { + ret.put(id, acl); + } + } + } + } catch (NoResultException e) { + LOG.debug("getDataShareIdsAndACLs()", e); + } + + return ret; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/db/XXGdsDataShareInDatasetDao.java b/security-admin/src/main/java/org/apache/ranger/db/XXGdsDataShareInDatasetDao.java index 130a260ccb..e49e9e531e 100755 --- a/security-admin/src/main/java/org/apache/ranger/db/XXGdsDataShareInDatasetDao.java +++ b/security-admin/src/main/java/org/apache/ranger/db/XXGdsDataShareInDatasetDao.java @@ -27,6 +27,7 @@ import org.springframework.stereotype.Service; import javax.persistence.NoResultException; + import java.util.Collections; import java.util.HashMap; import java.util.List; @@ -36,111 +37,111 @@ @Service public class XXGdsDataShareInDatasetDao extends BaseDao { - private static final Logger LOG = LoggerFactory.getLogger(XXGdsDataShareInDatasetDao.class); - - public XXGdsDataShareInDatasetDao(RangerDaoManagerBase daoManager) { - super(daoManager); - } - - public XXGdsDataShareInDataset findByGuid(String guid) { - XXGdsDataShareInDataset ret = null; - - if (StringUtils.isNotBlank(guid)) { - try { - ret = getEntityManager().createNamedQuery("XXGdsDataShareInDataset.findByGuid", tClass) - .setParameter("guid", guid).getSingleResult(); - } catch (NoResultException e) { - LOG.debug("findByGuid({}): ", guid, e); - } - } - - return ret; - } - - public XXGdsDataShareInDataset findByDataShareIdAndDatasetId(Long dataShareId, Long datasetId) { - XXGdsDataShareInDataset ret = null; - - if (dataShareId != null && datasetId != null) { - try { - ret = getEntityManager().createNamedQuery("XXGdsDataShareInDataset.findByDataShareIdAndDatasetId", tClass) - .setParameter("dataShareId", dataShareId) - .setParameter("datasetId", datasetId).getSingleResult(); - } catch (NoResultException e) { - LOG.debug("findByDataShareIdAndDatasetId({}): ", dataShareId, e); - } - } - - return ret; - } - - public List findByDataShareId(Long dataShareId) { - List ret = null; - - if (dataShareId != null) { - try { - ret = getEntityManager().createNamedQuery("XXGdsDataShareInDataset.findByDataShareId", tClass) - .setParameter("dataShareId", dataShareId).getResultList(); - } catch (NoResultException e) { - LOG.debug("findByDataShareId({}): ", dataShareId, e); - } - } - - return ret != null ? ret : Collections.emptyList(); - } - - public List findByDatasetId(Long datasetId) { - List ret = null; - - if (datasetId != null) { - try { - ret = getEntityManager().createNamedQuery("XXGdsDataShareInDataset.findByDatasetId", tClass) - .setParameter("datasetId", datasetId).getResultList(); - } catch (NoResultException e) { - LOG.debug("findByDatasetId({}): ", datasetId, e); - } - } - - return ret != null ? ret : Collections.emptyList(); - } - - public Map getDataSharesInDatasetCountByStatus(Long datasetId) { - Map ret = Collections.emptyMap(); - - if (datasetId != null) { - try { - List rows = getEntityManager().createNamedQuery("XXGdsDataShareInDataset.getDataSharesInDatasetCountByStatus", Object[].class) - .setParameter("datasetId", datasetId).getResultList(); - if (rows != null) { - ret = new HashMap<>(); - - for (Object[] row : rows) { - if (Objects.nonNull(row) && Objects.nonNull(row[0]) && Objects.nonNull(row[1]) && (!row[0].toString().isEmpty())) { - ret.put((Short) row[0], (Long) row[1]); - } - } - } - } catch (NoResultException e) { - LOG.debug("getDataSharesInDatasetCountByStatus({}): ", datasetId, e); - } - } - - return ret; - } - - public List findDataShareIdsInStatuses(Long datasetId, Set statuses) { - List ret = null; - - if (datasetId != null) { - try { - ret = getEntityManager().createNamedQuery("XXGdsDataShareInDataset.findDataShareIdsInStatuses", Long.class) - .setParameter("datasetId", datasetId) - .setParameter("statuses", statuses) - .getResultList(); - } catch (NoResultException e) { - LOG.debug("XXGdsDataShareInDataset({}, {}): ", datasetId, statuses, e); - } - } - - return ret != null ? ret : Collections.emptyList(); - } + private static final Logger LOG = LoggerFactory.getLogger(XXGdsDataShareInDatasetDao.class); + + public XXGdsDataShareInDatasetDao(RangerDaoManagerBase daoManager) { + super(daoManager); + } + + public XXGdsDataShareInDataset findByGuid(String guid) { + XXGdsDataShareInDataset ret = null; + + if (StringUtils.isNotBlank(guid)) { + try { + ret = getEntityManager().createNamedQuery("XXGdsDataShareInDataset.findByGuid", tClass) + .setParameter("guid", guid).getSingleResult(); + } catch (NoResultException e) { + LOG.debug("findByGuid({}): ", guid, e); + } + } + + return ret; + } + + public XXGdsDataShareInDataset findByDataShareIdAndDatasetId(Long dataShareId, Long datasetId) { + XXGdsDataShareInDataset ret = null; + + if (dataShareId != null && datasetId != null) { + try { + ret = getEntityManager().createNamedQuery("XXGdsDataShareInDataset.findByDataShareIdAndDatasetId", tClass) + .setParameter("dataShareId", dataShareId) + .setParameter("datasetId", datasetId).getSingleResult(); + } catch (NoResultException e) { + LOG.debug("findByDataShareIdAndDatasetId({}): ", dataShareId, e); + } + } + + return ret; + } + + public List findByDataShareId(Long dataShareId) { + List ret = null; + + if (dataShareId != null) { + try { + ret = getEntityManager().createNamedQuery("XXGdsDataShareInDataset.findByDataShareId", tClass) + .setParameter("dataShareId", dataShareId).getResultList(); + } catch (NoResultException e) { + LOG.debug("findByDataShareId({}): ", dataShareId, e); + } + } + + return ret != null ? ret : Collections.emptyList(); + } + + public List findByDatasetId(Long datasetId) { + List ret = null; + + if (datasetId != null) { + try { + ret = getEntityManager().createNamedQuery("XXGdsDataShareInDataset.findByDatasetId", tClass) + .setParameter("datasetId", datasetId).getResultList(); + } catch (NoResultException e) { + LOG.debug("findByDatasetId({}): ", datasetId, e); + } + } + + return ret != null ? ret : Collections.emptyList(); + } + + public Map getDataSharesInDatasetCountByStatus(Long datasetId) { + Map ret = Collections.emptyMap(); + + if (datasetId != null) { + try { + List rows = getEntityManager().createNamedQuery("XXGdsDataShareInDataset.getDataSharesInDatasetCountByStatus", Object[].class) + .setParameter("datasetId", datasetId).getResultList(); + if (rows != null) { + ret = new HashMap<>(); + + for (Object[] row : rows) { + if (Objects.nonNull(row) && Objects.nonNull(row[0]) && Objects.nonNull(row[1]) && (!row[0].toString().isEmpty())) { + ret.put((Short) row[0], (Long) row[1]); + } + } + } + } catch (NoResultException e) { + LOG.debug("getDataSharesInDatasetCountByStatus({}): ", datasetId, e); + } + } + + return ret; + } + + public List findDataShareIdsInStatuses(Long datasetId, Set statuses) { + List ret = null; + + if (datasetId != null) { + try { + ret = getEntityManager().createNamedQuery("XXGdsDataShareInDataset.findDataShareIdsInStatuses", Long.class) + .setParameter("datasetId", datasetId) + .setParameter("statuses", statuses) + .getResultList(); + } catch (NoResultException e) { + LOG.debug("XXGdsDataShareInDataset({}, {}): ", datasetId, statuses, e); + } + } + + return ret != null ? ret : Collections.emptyList(); + } } diff --git a/security-admin/src/main/java/org/apache/ranger/db/XXGdsDatasetDao.java b/security-admin/src/main/java/org/apache/ranger/db/XXGdsDatasetDao.java index 4661b41187..b0dbef3e8d 100644 --- a/security-admin/src/main/java/org/apache/ranger/db/XXGdsDatasetDao.java +++ b/security-admin/src/main/java/org/apache/ranger/db/XXGdsDatasetDao.java @@ -23,121 +23,121 @@ import org.apache.ranger.authorization.utils.JsonUtils; import org.apache.ranger.common.db.BaseDao; import org.apache.ranger.entity.XXGdsDataset; +import org.apache.ranger.plugin.model.RangerGds.RangerGdsObjectACL; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import javax.persistence.NoResultException; + import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; -import org.apache.ranger.plugin.model.RangerGds.RangerGdsObjectACL; - @Service public class XXGdsDatasetDao extends BaseDao { - private static final Logger LOG = LoggerFactory.getLogger(XXGdsDatasetDao.class); - - public XXGdsDatasetDao(RangerDaoManagerBase daoManager) { - super(daoManager); - } - - public XXGdsDataset findByGuid(String guid) { - XXGdsDataset ret = null; - - if (StringUtils.isNotBlank(guid)) { - try { - ret = getEntityManager().createNamedQuery("XXGdsDataset.findByGuid", tClass) - .setParameter("guid", guid).getSingleResult(); - } catch (NoResultException e) { - LOG.debug("findByGuid({}): ", guid, e); - } - } - - return ret; - } - - public XXGdsDataset findByName(String name) { - XXGdsDataset ret = null; - - if (StringUtils.isNotBlank(name)) { - try { - ret = getEntityManager().createNamedQuery("XXGdsDataset.findByName", tClass) - .setParameter("name", name).getSingleResult(); - } catch (NoResultException e) { - LOG.debug("findByName({}): ", name, e); - } - } - - return ret; - } - - public List findByDataShareId(Long dataShareId) { - List ret = null; - - if (dataShareId != null) { - try { - ret = getEntityManager().createNamedQuery("XXGdsDataset.findByDataShareId", tClass) - .setParameter("dataShareId", dataShareId).getResultList(); - } catch (NoResultException e) { - LOG.debug("findByDataShareId({}): ", dataShareId, e); - } - } - - return ret != null ? ret : Collections.emptyList(); - } - - public List findByProjectId(Long projectId) { - List ret = null; - - if (projectId != null) { - try { - ret = getEntityManager().createNamedQuery("XXGdsDataset.findByProjectId", tClass) - .setParameter("projectId", projectId).getResultList(); - } catch (NoResultException e) { - LOG.debug("findByProjectId({}): ", projectId, e); - } - } - - return ret != null ? ret : Collections.emptyList(); - } - - public List findServiceIdsForDataset(Long datasetId) { - List ret = null; - - if (datasetId != null) { - try { - ret = getEntityManager().createNamedQuery("XXGdsDataset.findServiceIds", Long.class) - .setParameter("datasetId", datasetId).getResultList(); - } catch (NoResultException e) { - LOG.debug("findServiceIdsForDataset({}): ", datasetId, e); - } - } - - return ret != null ? ret : Collections.emptyList(); - } - - public Map getDatasetIdsAndACLs() { - Map ret = new HashMap<>(); - - try { - List rows = getEntityManager().createNamedQuery("XXGdsDataset.getDatasetIdsAndACLs", Object[].class).getResultList(); - - if (rows != null) { - for (Object[] row : rows) { - Long id = (Long) row[0]; - RangerGdsObjectACL acl = JsonUtils.jsonToObject((String) row[1], RangerGdsObjectACL.class); - - if (acl != null) { - ret.put(id, acl); - } - } - } - } catch (NoResultException e) { - LOG.debug("getDatasetIdsAndACLs()", e); - } - - return ret; - } + private static final Logger LOG = LoggerFactory.getLogger(XXGdsDatasetDao.class); + + public XXGdsDatasetDao(RangerDaoManagerBase daoManager) { + super(daoManager); + } + + public XXGdsDataset findByGuid(String guid) { + XXGdsDataset ret = null; + + if (StringUtils.isNotBlank(guid)) { + try { + ret = getEntityManager().createNamedQuery("XXGdsDataset.findByGuid", tClass) + .setParameter("guid", guid).getSingleResult(); + } catch (NoResultException e) { + LOG.debug("findByGuid({}): ", guid, e); + } + } + + return ret; + } + + public XXGdsDataset findByName(String name) { + XXGdsDataset ret = null; + + if (StringUtils.isNotBlank(name)) { + try { + ret = getEntityManager().createNamedQuery("XXGdsDataset.findByName", tClass) + .setParameter("name", name).getSingleResult(); + } catch (NoResultException e) { + LOG.debug("findByName({}): ", name, e); + } + } + + return ret; + } + + public List findByDataShareId(Long dataShareId) { + List ret = null; + + if (dataShareId != null) { + try { + ret = getEntityManager().createNamedQuery("XXGdsDataset.findByDataShareId", tClass) + .setParameter("dataShareId", dataShareId).getResultList(); + } catch (NoResultException e) { + LOG.debug("findByDataShareId({}): ", dataShareId, e); + } + } + + return ret != null ? ret : Collections.emptyList(); + } + + public List findByProjectId(Long projectId) { + List ret = null; + + if (projectId != null) { + try { + ret = getEntityManager().createNamedQuery("XXGdsDataset.findByProjectId", tClass) + .setParameter("projectId", projectId).getResultList(); + } catch (NoResultException e) { + LOG.debug("findByProjectId({}): ", projectId, e); + } + } + + return ret != null ? ret : Collections.emptyList(); + } + + public List findServiceIdsForDataset(Long datasetId) { + List ret = null; + + if (datasetId != null) { + try { + ret = getEntityManager().createNamedQuery("XXGdsDataset.findServiceIds", Long.class) + .setParameter("datasetId", datasetId).getResultList(); + } catch (NoResultException e) { + LOG.debug("findServiceIdsForDataset({}): ", datasetId, e); + } + } + + return ret != null ? ret : Collections.emptyList(); + } + + public Map getDatasetIdsAndACLs() { + Map ret = new HashMap<>(); + + try { + List rows = getEntityManager().createNamedQuery("XXGdsDataset.getDatasetIdsAndACLs", Object[].class).getResultList(); + + if (rows != null) { + for (Object[] row : rows) { + Long id = (Long) row[0]; + RangerGdsObjectACL acl = JsonUtils.jsonToObject((String) row[1], RangerGdsObjectACL.class); + + if (acl != null) { + ret.put(id, acl); + } + } + } + } catch (NoResultException e) { + LOG.debug("getDatasetIdsAndACLs()", e); + } + + return ret; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/db/XXGdsDatasetInProjectDao.java b/security-admin/src/main/java/org/apache/ranger/db/XXGdsDatasetInProjectDao.java index 06bf671056..47575516de 100644 --- a/security-admin/src/main/java/org/apache/ranger/db/XXGdsDatasetInProjectDao.java +++ b/security-admin/src/main/java/org/apache/ranger/db/XXGdsDatasetInProjectDao.java @@ -27,77 +27,77 @@ import org.springframework.stereotype.Service; import javax.persistence.NoResultException; + import java.util.Collections; import java.util.List; - @Service public class XXGdsDatasetInProjectDao extends BaseDao { - private static final Logger LOG = LoggerFactory.getLogger(XXGdsDatasetInProjectDao.class); - - public XXGdsDatasetInProjectDao(RangerDaoManagerBase daoManager) { - super(daoManager); - } - - public XXGdsDatasetInProject findByGuid(String guid) { - XXGdsDatasetInProject ret = null; - - if (StringUtils.isNotBlank(guid)) { - try { - ret = getEntityManager().createNamedQuery("XXGdsDatasetInProject.findByGuid", tClass) - .setParameter("guid", guid).getSingleResult(); - } catch (NoResultException e) { - LOG.debug("findByGuid({}): ", guid, e); - } - } - - return ret; - } - - public XXGdsDatasetInProject findByDatasetIdAndProjectId(Long datasetId, Long projectId) { - XXGdsDatasetInProject ret = null; - - if (datasetId != null && projectId != null) { - try { - ret = getEntityManager().createNamedQuery("XXGdsDatasetInProject.findByDatasetIdAndProjectId", tClass) - .setParameter("datasetId", datasetId) - .setParameter("projectId", projectId) - .getSingleResult(); - } catch (NoResultException e) { - LOG.debug("findByDatasetIdAndProjectId({}): ", datasetId, e); - } - } - - return ret; - } - - public List findByDatasetId(Long datasetId) { - List ret = null; - - if (datasetId != null) { - try { - ret = getEntityManager().createNamedQuery("XXGdsDatasetInProject.findByDatasetId", tClass) - .setParameter("datasetId", datasetId).getResultList(); - } catch (NoResultException e) { - LOG.debug("findByDatasetId({}): ", datasetId, e); - } - } - - return ret != null ? ret : Collections.emptyList(); - } - - public List findByProjectId(Long projectId) { - List ret = null; - - if (projectId != null) { - try { - ret = getEntityManager().createNamedQuery("XXGdsDatasetInProject.findByProjectId", tClass) - .setParameter("projectId", projectId).getResultList(); - } catch (NoResultException e) { - LOG.debug("findByProjectId({}): ", projectId, e); - } - } - - return ret != null ? ret : Collections.emptyList(); - } + private static final Logger LOG = LoggerFactory.getLogger(XXGdsDatasetInProjectDao.class); + + public XXGdsDatasetInProjectDao(RangerDaoManagerBase daoManager) { + super(daoManager); + } + + public XXGdsDatasetInProject findByGuid(String guid) { + XXGdsDatasetInProject ret = null; + + if (StringUtils.isNotBlank(guid)) { + try { + ret = getEntityManager().createNamedQuery("XXGdsDatasetInProject.findByGuid", tClass) + .setParameter("guid", guid).getSingleResult(); + } catch (NoResultException e) { + LOG.debug("findByGuid({}): ", guid, e); + } + } + + return ret; + } + + public XXGdsDatasetInProject findByDatasetIdAndProjectId(Long datasetId, Long projectId) { + XXGdsDatasetInProject ret = null; + + if (datasetId != null && projectId != null) { + try { + ret = getEntityManager().createNamedQuery("XXGdsDatasetInProject.findByDatasetIdAndProjectId", tClass) + .setParameter("datasetId", datasetId) + .setParameter("projectId", projectId) + .getSingleResult(); + } catch (NoResultException e) { + LOG.debug("findByDatasetIdAndProjectId({}): ", datasetId, e); + } + } + + return ret; + } + + public List findByDatasetId(Long datasetId) { + List ret = null; + + if (datasetId != null) { + try { + ret = getEntityManager().createNamedQuery("XXGdsDatasetInProject.findByDatasetId", tClass) + .setParameter("datasetId", datasetId).getResultList(); + } catch (NoResultException e) { + LOG.debug("findByDatasetId({}): ", datasetId, e); + } + } + + return ret != null ? ret : Collections.emptyList(); + } + + public List findByProjectId(Long projectId) { + List ret = null; + + if (projectId != null) { + try { + ret = getEntityManager().createNamedQuery("XXGdsDatasetInProject.findByProjectId", tClass) + .setParameter("projectId", projectId).getResultList(); + } catch (NoResultException e) { + LOG.debug("findByProjectId({}): ", projectId, e); + } + } + + return ret != null ? ret : Collections.emptyList(); + } } diff --git a/security-admin/src/main/java/org/apache/ranger/db/XXGdsDatasetPolicyMapDao.java b/security-admin/src/main/java/org/apache/ranger/db/XXGdsDatasetPolicyMapDao.java index f28d3a5ecf..b1ff36ad0e 100644 --- a/security-admin/src/main/java/org/apache/ranger/db/XXGdsDatasetPolicyMapDao.java +++ b/security-admin/src/main/java/org/apache/ranger/db/XXGdsDatasetPolicyMapDao.java @@ -24,62 +24,62 @@ import org.springframework.stereotype.Service; import javax.persistence.NoResultException; + import java.util.Collections; import java.util.List; - @Service public class XXGdsDatasetPolicyMapDao extends BaseDao { - public XXGdsDatasetPolicyMapDao(RangerDaoManagerBase daoManager) { - super(daoManager); - } + public XXGdsDatasetPolicyMapDao(RangerDaoManagerBase daoManager) { + super(daoManager); + } - public XXGdsDatasetPolicyMap getDatasetPolicyMap(Long datasetId, Long policyId) { - XXGdsDatasetPolicyMap ret = null; + public XXGdsDatasetPolicyMap getDatasetPolicyMap(Long datasetId, Long policyId) { + XXGdsDatasetPolicyMap ret = null; - if (datasetId != null && policyId != null) { - try { - ret = getEntityManager().createNamedQuery("XXGdsDatasetPolicyMap.getDatasetPolicyMap", tClass) - .setParameter("datasetId", datasetId) - .setParameter("policyId", policyId) - .getSingleResult(); - } catch (NoResultException e) { - // ignore - } - } + if (datasetId != null && policyId != null) { + try { + ret = getEntityManager().createNamedQuery("XXGdsDatasetPolicyMap.getDatasetPolicyMap", tClass) + .setParameter("datasetId", datasetId) + .setParameter("policyId", policyId) + .getSingleResult(); + } catch (NoResultException e) { + // ignore + } + } - return ret; - } + return ret; + } - public List getDatasetPolicyMaps(Long datasetId) { - List ret = Collections.emptyList(); + public List getDatasetPolicyMaps(Long datasetId) { + List ret = Collections.emptyList(); - if (datasetId != null) { - try { - ret = getEntityManager().createNamedQuery("XXGdsDatasetPolicyMap.getDatasetPolicyMaps", tClass) - .setParameter("datasetId", datasetId) - .getResultList(); - } catch (NoResultException e) { - // ignore - } - } + if (datasetId != null) { + try { + ret = getEntityManager().createNamedQuery("XXGdsDatasetPolicyMap.getDatasetPolicyMaps", tClass) + .setParameter("datasetId", datasetId) + .getResultList(); + } catch (NoResultException e) { + // ignore + } + } - return ret; - } + return ret; + } - public List getDatasetPolicyIds(Long datasetId) { - List ret = Collections.emptyList(); + public List getDatasetPolicyIds(Long datasetId) { + List ret = Collections.emptyList(); - if (datasetId != null) { - try { - ret = getEntityManager().createNamedQuery("XXGdsDatasetPolicyMap.getDatasetPolicyIds", Long.class) - .setParameter("datasetId", datasetId) - .getResultList(); - } catch (NoResultException e) { - // ignore - } - } + if (datasetId != null) { + try { + ret = getEntityManager().createNamedQuery("XXGdsDatasetPolicyMap.getDatasetPolicyIds", Long.class) + .setParameter("datasetId", datasetId) + .getResultList(); + } catch (NoResultException e) { + // ignore + } + } - return ret; - } + return ret; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/db/XXGdsProjectDao.java b/security-admin/src/main/java/org/apache/ranger/db/XXGdsProjectDao.java index ba8f6c66ab..a005519e72 100644 --- a/security-admin/src/main/java/org/apache/ranger/db/XXGdsProjectDao.java +++ b/security-admin/src/main/java/org/apache/ranger/db/XXGdsProjectDao.java @@ -29,100 +29,100 @@ import org.springframework.stereotype.Service; import javax.persistence.NoResultException; + import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; - @Service public class XXGdsProjectDao extends BaseDao { - private static final Logger LOG = LoggerFactory.getLogger(XXGdsProjectDao.class); - - public XXGdsProjectDao(RangerDaoManagerBase daoManager) { - super(daoManager); - } - - public XXGdsProject findByGuid(String guid) { - XXGdsProject ret = null; - - if (StringUtils.isNotBlank(guid)) { - try { - ret = getEntityManager().createNamedQuery("XXGdsProject.findByGuid", tClass) - .setParameter("guid", guid).getSingleResult(); - } catch (NoResultException e) { - LOG.debug("findByGuid({}): ", guid, e); - } - } - - return ret; - } - - public XXGdsProject findByName(String name) { - XXGdsProject ret = null; - - if (StringUtils.isNotBlank(name)) { - try { - ret = getEntityManager().createNamedQuery("XXGdsProject.findByName", tClass) - .setParameter("name", name).getSingleResult(); - } catch (NoResultException e) { - LOG.debug("findByName({}): ", name, e); - } - } - - return ret; - } - - public List findByDatasetId(Long datasetId) { - List ret = null; - - if (datasetId != null) { - try { - ret = getEntityManager().createNamedQuery("XXGdsProject.findByDatasetId", tClass) - .setParameter("datasetId", datasetId).getResultList(); - } catch (NoResultException e) { - LOG.debug("findByDatasetId({}): ", datasetId, e); - } - } - - return ret != null ? ret : Collections.emptyList(); - } - - public List findServiceIdsForProject(Long projectId) { - List ret = null; - - if (projectId != null) { - try { - ret = getEntityManager().createNamedQuery("XXGdsProject.findServiceIds", Long.class) - .setParameter("projectId", projectId).getResultList(); - } catch (NoResultException e) { - LOG.debug("findServiceIdsForProject({}): ", projectId, e); - } - } - - return ret != null ? ret : Collections.emptyList(); - } - - public Map getProjectIdsAndACLs() { - Map ret = new HashMap<>(); - - try { - List rows = getEntityManager().createNamedQuery("XXGdsProject.getProjectIdsAndACLs", Object[].class).getResultList(); - - if (rows != null) { - for (Object[] row : rows) { - Long id = (Long) row[0]; - RangerGdsObjectACL acl = JsonUtils.jsonToObject((String) row[1], RangerGdsObjectACL.class); - - if (acl != null) { - ret.put(id, acl); - } - } - } - } catch (NoResultException e) { - LOG.debug("getProjectIdsAndACLs()", e); - } - - return ret; - } + private static final Logger LOG = LoggerFactory.getLogger(XXGdsProjectDao.class); + + public XXGdsProjectDao(RangerDaoManagerBase daoManager) { + super(daoManager); + } + + public XXGdsProject findByGuid(String guid) { + XXGdsProject ret = null; + + if (StringUtils.isNotBlank(guid)) { + try { + ret = getEntityManager().createNamedQuery("XXGdsProject.findByGuid", tClass) + .setParameter("guid", guid).getSingleResult(); + } catch (NoResultException e) { + LOG.debug("findByGuid({}): ", guid, e); + } + } + + return ret; + } + + public XXGdsProject findByName(String name) { + XXGdsProject ret = null; + + if (StringUtils.isNotBlank(name)) { + try { + ret = getEntityManager().createNamedQuery("XXGdsProject.findByName", tClass) + .setParameter("name", name).getSingleResult(); + } catch (NoResultException e) { + LOG.debug("findByName({}): ", name, e); + } + } + + return ret; + } + + public List findByDatasetId(Long datasetId) { + List ret = null; + + if (datasetId != null) { + try { + ret = getEntityManager().createNamedQuery("XXGdsProject.findByDatasetId", tClass) + .setParameter("datasetId", datasetId).getResultList(); + } catch (NoResultException e) { + LOG.debug("findByDatasetId({}): ", datasetId, e); + } + } + + return ret != null ? ret : Collections.emptyList(); + } + + public List findServiceIdsForProject(Long projectId) { + List ret = null; + + if (projectId != null) { + try { + ret = getEntityManager().createNamedQuery("XXGdsProject.findServiceIds", Long.class) + .setParameter("projectId", projectId).getResultList(); + } catch (NoResultException e) { + LOG.debug("findServiceIdsForProject({}): ", projectId, e); + } + } + + return ret != null ? ret : Collections.emptyList(); + } + + public Map getProjectIdsAndACLs() { + Map ret = new HashMap<>(); + + try { + List rows = getEntityManager().createNamedQuery("XXGdsProject.getProjectIdsAndACLs", Object[].class).getResultList(); + + if (rows != null) { + for (Object[] row : rows) { + Long id = (Long) row[0]; + RangerGdsObjectACL acl = JsonUtils.jsonToObject((String) row[1], RangerGdsObjectACL.class); + + if (acl != null) { + ret.put(id, acl); + } + } + } + } catch (NoResultException e) { + LOG.debug("getProjectIdsAndACLs()", e); + } + + return ret; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/db/XXGdsProjectPolicyMapDao.java b/security-admin/src/main/java/org/apache/ranger/db/XXGdsProjectPolicyMapDao.java index 4cfd03db28..b3529e8409 100644 --- a/security-admin/src/main/java/org/apache/ranger/db/XXGdsProjectPolicyMapDao.java +++ b/security-admin/src/main/java/org/apache/ranger/db/XXGdsProjectPolicyMapDao.java @@ -24,62 +24,62 @@ import org.springframework.stereotype.Service; import javax.persistence.NoResultException; + import java.util.Collections; import java.util.List; - @Service public class XXGdsProjectPolicyMapDao extends BaseDao { - public XXGdsProjectPolicyMapDao(RangerDaoManagerBase daoManager) { - super(daoManager); - } + public XXGdsProjectPolicyMapDao(RangerDaoManagerBase daoManager) { + super(daoManager); + } - public XXGdsProjectPolicyMap getProjectPolicyMap(Long projectId, Long policyId) { - XXGdsProjectPolicyMap ret = null; + public XXGdsProjectPolicyMap getProjectPolicyMap(Long projectId, Long policyId) { + XXGdsProjectPolicyMap ret = null; - if (projectId != null && policyId != null) { - try { - ret = getEntityManager().createNamedQuery("XXGdsProjectPolicyMap.getProjectPolicyMap", tClass) - .setParameter("projectId", projectId) - .setParameter("policyId", policyId) - .getSingleResult(); - } catch (NoResultException e) { - // ignore - } - } + if (projectId != null && policyId != null) { + try { + ret = getEntityManager().createNamedQuery("XXGdsProjectPolicyMap.getProjectPolicyMap", tClass) + .setParameter("projectId", projectId) + .setParameter("policyId", policyId) + .getSingleResult(); + } catch (NoResultException e) { + // ignore + } + } - return ret; - } + return ret; + } - public List getProjectPolicyMaps(Long projectId) { - List ret = Collections.emptyList(); + public List getProjectPolicyMaps(Long projectId) { + List ret = Collections.emptyList(); - if (projectId != null) { - try { - ret = getEntityManager().createNamedQuery("XXGdsProjectPolicyMap.getProjectPolicyMaps", tClass) - .setParameter("projectId", projectId) - .getResultList(); - } catch (NoResultException e) { - // ignore - } - } + if (projectId != null) { + try { + ret = getEntityManager().createNamedQuery("XXGdsProjectPolicyMap.getProjectPolicyMaps", tClass) + .setParameter("projectId", projectId) + .getResultList(); + } catch (NoResultException e) { + // ignore + } + } - return ret; - } + return ret; + } - public List getProjectPolicyIds(Long projectId) { - List ret = Collections.emptyList(); + public List getProjectPolicyIds(Long projectId) { + List ret = Collections.emptyList(); - if (projectId != null) { - try { - ret = getEntityManager().createNamedQuery("XXGdsProjectPolicyMap.getProjectPolicyIds", Long.class) - .setParameter("projectId", projectId) - .getResultList(); - } catch (NoResultException e) { - // ignore - } - } + if (projectId != null) { + try { + ret = getEntityManager().createNamedQuery("XXGdsProjectPolicyMap.getProjectPolicyIds", Long.class) + .setParameter("projectId", projectId) + .getResultList(); + } catch (NoResultException e) { + // ignore + } + } - return ret; - } + return ret; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/db/XXGdsSharedResourceDao.java b/security-admin/src/main/java/org/apache/ranger/db/XXGdsSharedResourceDao.java index c7acd81a21..0ec97ccf7f 100644 --- a/security-admin/src/main/java/org/apache/ranger/db/XXGdsSharedResourceDao.java +++ b/security-admin/src/main/java/org/apache/ranger/db/XXGdsSharedResourceDao.java @@ -27,124 +27,124 @@ import org.springframework.stereotype.Service; import javax.persistence.NoResultException; + import java.util.Collections; import java.util.List; - @Service public class XXGdsSharedResourceDao extends BaseDao { - private static final Logger LOG = LoggerFactory.getLogger(XXGdsSharedResourceDao.class); - - public XXGdsSharedResourceDao(RangerDaoManagerBase daoManager) { - super(daoManager); - } - - public XXGdsSharedResource findByGuid(String guid) { - XXGdsSharedResource ret = null; - - if (StringUtils.isNotBlank(guid)) { - try { - ret = getEntityManager().createNamedQuery("XXGdsSharedResource.findByGuid", tClass) - .setParameter("guid", guid).getSingleResult(); - } catch (NoResultException e) { - LOG.debug("findByGuid({}): ", guid, e); - } - } - - return ret; - } - - public XXGdsSharedResource findByName(String name) { - XXGdsSharedResource ret = null; - - if (StringUtils.isNotBlank(name)) { - try { - ret = getEntityManager().createNamedQuery("XXGdsSharedResource.findByName", tClass) - .setParameter("name", name).getSingleResult(); - } catch (NoResultException e) { - LOG.debug("findByName({}): ", name, e); - } - } - - return ret; - } - - public List findByServiceId(Long serviceId) { - List ret = null; - - if (serviceId != null) { - try { - ret = getEntityManager().createNamedQuery("XXGdsSharedResource.findByServiceId", tClass) - .setParameter("serviceId", serviceId).getResultList(); - } catch (NoResultException e) { - LOG.debug("findByServiceId({}): ", serviceId, e); - } - } - - return ret != null ? ret : Collections.emptyList(); - } - - public List findByServiceIdAndZoneId(Long serviceId, Long zoneId) { - List ret = null; - - if (serviceId != null) { - try { - ret = getEntityManager().createNamedQuery("XXGdsSharedResource.findByServiceIdAndZoneId", tClass) - .setParameter("serviceId", serviceId) - .setParameter("zoneId", zoneId).getResultList(); - } catch (NoResultException e) { - LOG.debug("findByServiceIdAndZoneId({}): ", serviceId, e); - } - } - - return ret != null ? ret : Collections.emptyList(); - } - - public List findByDatasetId(Long datasetId) { - List ret = null; - - if (datasetId != null) { - try { - ret = getEntityManager().createNamedQuery("XXGdsSharedResource.findByDatasetId", tClass) - .setParameter("datasetId", datasetId).getResultList(); - } catch (NoResultException e) { - LOG.debug("findByDatasetId({}): ", datasetId, e); - } - } - - return ret != null ? ret : Collections.emptyList(); - } - - public Long getIdByDataShareIdAndName(Long dataShareId, String name) { - Long ret = null; - - if (dataShareId != null && name != null) { - try { - ret = getEntityManager().createNamedQuery("XXGdsSharedResource.getIdByDataShareIdAndName", Long.class) - .setParameter("dataShareId", dataShareId) - .setParameter("name", name).getSingleResult(); - } catch (NoResultException e) { - LOG.debug("getIdByDataShareIdAndName({}, {}): ", dataShareId, name, e); - } - } - - return ret; - } - - public Long getIdByDataShareIdAndResourceSignature(Long dataShareId, String resourceSignature) { - Long ret = null; - - if (dataShareId != null && resourceSignature != null) { - try { - ret = getEntityManager() - .createNamedQuery("XXGdsSharedResource.getIdByDataShareIdAndResourceSignature", Long.class) - .setParameter("dataShareId", dataShareId).setParameter("resourceSignature", resourceSignature) - .getSingleResult(); - } catch (NoResultException e) { - LOG.debug("getIdByDataShareIdAndName({}, {}): ", dataShareId, resourceSignature, e); - } - } - - return ret; - } + private static final Logger LOG = LoggerFactory.getLogger(XXGdsSharedResourceDao.class); + + public XXGdsSharedResourceDao(RangerDaoManagerBase daoManager) { + super(daoManager); + } + + public XXGdsSharedResource findByGuid(String guid) { + XXGdsSharedResource ret = null; + + if (StringUtils.isNotBlank(guid)) { + try { + ret = getEntityManager().createNamedQuery("XXGdsSharedResource.findByGuid", tClass) + .setParameter("guid", guid).getSingleResult(); + } catch (NoResultException e) { + LOG.debug("findByGuid({}): ", guid, e); + } + } + + return ret; + } + + public XXGdsSharedResource findByName(String name) { + XXGdsSharedResource ret = null; + + if (StringUtils.isNotBlank(name)) { + try { + ret = getEntityManager().createNamedQuery("XXGdsSharedResource.findByName", tClass) + .setParameter("name", name).getSingleResult(); + } catch (NoResultException e) { + LOG.debug("findByName({}): ", name, e); + } + } + + return ret; + } + + public List findByServiceId(Long serviceId) { + List ret = null; + + if (serviceId != null) { + try { + ret = getEntityManager().createNamedQuery("XXGdsSharedResource.findByServiceId", tClass) + .setParameter("serviceId", serviceId).getResultList(); + } catch (NoResultException e) { + LOG.debug("findByServiceId({}): ", serviceId, e); + } + } + + return ret != null ? ret : Collections.emptyList(); + } + + public List findByServiceIdAndZoneId(Long serviceId, Long zoneId) { + List ret = null; + + if (serviceId != null) { + try { + ret = getEntityManager().createNamedQuery("XXGdsSharedResource.findByServiceIdAndZoneId", tClass) + .setParameter("serviceId", serviceId) + .setParameter("zoneId", zoneId).getResultList(); + } catch (NoResultException e) { + LOG.debug("findByServiceIdAndZoneId({}): ", serviceId, e); + } + } + + return ret != null ? ret : Collections.emptyList(); + } + + public List findByDatasetId(Long datasetId) { + List ret = null; + + if (datasetId != null) { + try { + ret = getEntityManager().createNamedQuery("XXGdsSharedResource.findByDatasetId", tClass) + .setParameter("datasetId", datasetId).getResultList(); + } catch (NoResultException e) { + LOG.debug("findByDatasetId({}): ", datasetId, e); + } + } + + return ret != null ? ret : Collections.emptyList(); + } + + public Long getIdByDataShareIdAndName(Long dataShareId, String name) { + Long ret = null; + + if (dataShareId != null && name != null) { + try { + ret = getEntityManager().createNamedQuery("XXGdsSharedResource.getIdByDataShareIdAndName", Long.class) + .setParameter("dataShareId", dataShareId) + .setParameter("name", name).getSingleResult(); + } catch (NoResultException e) { + LOG.debug("getIdByDataShareIdAndName({}, {}): ", dataShareId, name, e); + } + } + + return ret; + } + + public Long getIdByDataShareIdAndResourceSignature(Long dataShareId, String resourceSignature) { + Long ret = null; + + if (dataShareId != null && resourceSignature != null) { + try { + ret = getEntityManager() + .createNamedQuery("XXGdsSharedResource.getIdByDataShareIdAndResourceSignature", Long.class) + .setParameter("dataShareId", dataShareId).setParameter("resourceSignature", resourceSignature) + .getSingleResult(); + } catch (NoResultException e) { + LOG.debug("getIdByDataShareIdAndName({}, {}): ", dataShareId, resourceSignature, e); + } + } + + return ret; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/db/XXGlobalStateDao.java b/security-admin/src/main/java/org/apache/ranger/db/XXGlobalStateDao.java index 222807b441..7e95dbfdbe 100644 --- a/security-admin/src/main/java/org/apache/ranger/db/XXGlobalStateDao.java +++ b/security-admin/src/main/java/org/apache/ranger/db/XXGlobalStateDao.java @@ -38,67 +38,83 @@ public class XXGlobalStateDao extends BaseDao { private static final Logger logger = LoggerFactory.getLogger(XXGlobalStateDao.class); - public final static String RANGER_GLOBAL_STATE_NAME_GDS = "RangerGDS"; - public final static String RANGER_GLOBAL_STATE_NAME_ROLE = "RangerRole"; - public final static String RANGER_GLOBAL_STATE_NAME_USER_GROUP = "RangerUserStore"; - public final static String APP_DATA_ENTRY_VERSION = "Version"; + public static final String RANGER_GLOBAL_STATE_NAME_GDS = "RangerGDS"; + public static final String RANGER_GLOBAL_STATE_NAME_ROLE = "RangerRole"; + public static final String RANGER_GLOBAL_STATE_NAME_USER_GROUP = "RangerUserStore"; + public static final String APP_DATA_ENTRY_VERSION = "Version"; + /** + * Default Constructor + */ + public XXGlobalStateDao(RangerDaoManagerBase daoManager) { + super(daoManager); + } public void onGlobalStateChange(String stateName) throws Exception { - if (StringUtils.isBlank(stateName)) { - logger.error("Invalid name for state:[" + stateName +"]"); - throw new Exception("Invalid name for state:[" + stateName +"]"); + logger.error("Invalid name for state:[{}]", stateName); + + throw new Exception("Invalid name for state:[" + stateName + "]"); } else { try { XXGlobalState globalState = findByStateName(stateName); + if (globalState == null) { globalState = new XXGlobalState(); + globalState.setStateName(stateName); + create(globalState); } else { Date date = DateUtil.getUTCDate(); + if (date == null) { date = new Date(); } + globalState.setAppData(date.toString()); update(globalState); } } catch (Exception exception) { - logger.error("Cannot create/update GlobalState for state:[" + stateName + "]", exception); + logger.error("Cannot create/update GlobalState for state:[{}]", stateName, exception); + throw exception; } } } - public void onGlobalAppDataChange(String stateName) throws Exception { - - if (StringUtils.isBlank(stateName)) { - logger.error("Invalid name for state:[" + stateName + "]"); - throw new Exception("Invalid name for state:[" + stateName + "]"); - } else { - try { - XXGlobalState globalState = findByStateName(stateName); - if (globalState == null) { - createGlobalStateForAppDataVersion(stateName); - } else { - updateGlobalStateForAppDataVersion(globalState, stateName); - } - } catch (OptimisticLockException | org.eclipse.persistence.exceptions.OptimisticLockException ole) { - logger.warn("One or more objects cannot be updated because it has changed or been deleted since it was last read. Unable to update GlobalState for state:[" + stateName + "] continuing..."); - } catch (Exception exception) { - logger.warn("Cannot create/update GlobalState for state:[" + stateName + "] continuing..."); - } - } - } + public void onGlobalAppDataChange(String stateName) throws Exception { + if (StringUtils.isBlank(stateName)) { + logger.error("Invalid name for state:[{}]", stateName); + + throw new Exception("Invalid name for state:[" + stateName + "]"); + } else { + try { + XXGlobalState globalState = findByStateName(stateName); + + if (globalState == null) { + createGlobalStateForAppDataVersion(stateName); + } else { + updateGlobalStateForAppDataVersion(globalState, stateName); + } + } catch (OptimisticLockException | org.eclipse.persistence.exceptions.OptimisticLockException ole) { + logger.warn("One or more objects cannot be updated because it has changed or been deleted since it was last read. Unable to update GlobalState for state:[{}] continuing...", stateName); + } catch (Exception exception) { + logger.warn("Cannot create/update GlobalState for state:[{}] continuing...", stateName); + } + } + } public Long getAppDataVersion(String stateName) { Long ret = null; + try { - XXGlobalState globalState = findByStateName(stateName); + XXGlobalState globalState = findByStateName(stateName); + if (globalState != null) { Map appDataVersionJson = new Gson().fromJson(globalState.getAppData(), Map.class); + if (MapUtils.isNotEmpty(appDataVersionJson)) { ret = Long.valueOf(appDataVersionJson.get(APP_DATA_ENTRY_VERSION)); } else { @@ -106,43 +122,37 @@ public Long getAppDataVersion(String stateName) { } } } catch (Exception exception) { - if (logger.isDebugEnabled()) { - logger.debug("Unable to find the version for " + stateName + " in Ranger Database", exception); - } + logger.debug("Unable to find the version for {} in Ranger Database", stateName, exception); } + return ret; } - /** - * Default Constructor - */ - public XXGlobalStateDao(RangerDaoManagerBase daoManager) { - super(daoManager); - } public XXGlobalState findByStateId(Long stateId) { if (stateId == null) { return null; } + try { - XXGlobalState xxGlobalState = getEntityManager() + return getEntityManager() .createNamedQuery("XXGlobalState.findByStateId", tClass) .setParameter("stateId", stateId) .getSingleResult(); - return xxGlobalState; } catch (NoResultException e) { return null; } } + public XXGlobalState findByStateName(String stateName) { if (StringUtils.isBlank(stateName)) { return null; } + try { - XXGlobalState xxGlobalState = getEntityManager() + return getEntityManager() .createNamedQuery("XXGlobalState.findByStateName", tClass) .setParameter("stateName", stateName) .getSingleResult(); - return xxGlobalState; } catch (NoResultException e) { return null; } @@ -150,19 +160,28 @@ public XXGlobalState findByStateName(String stateName) { private void createGlobalStateForAppDataVersion(String stateName) { XXGlobalState globalState = new XXGlobalState(); + globalState.setStateName(stateName); - Map appDataVersion = new HashMap<>(); - appDataVersion.put(APP_DATA_ENTRY_VERSION,new String(Long.toString(1L))); + + Map appDataVersion = new HashMap<>(); + + appDataVersion.put(APP_DATA_ENTRY_VERSION, Long.toString(1L)); + globalState.setAppData(new Gson().toJson(appDataVersion)); + create(globalState); } private void updateGlobalStateForAppDataVersion(XXGlobalState globalState, String stateName) { - Map appDataVersionJson = new Gson().fromJson(globalState.getAppData(),Map.class); + Map appDataVersionJson = new Gson().fromJson(globalState.getAppData(), Map.class); + if (MapUtils.isNotEmpty(appDataVersionJson)) { Long appDataVersion = Long.valueOf(appDataVersionJson.get(APP_DATA_ENTRY_VERSION)) + 1L; - appDataVersionJson.put(APP_DATA_ENTRY_VERSION, new String(Long.toString(appDataVersion))); + + appDataVersionJson.put(APP_DATA_ENTRY_VERSION, Long.toString(appDataVersion)); + globalState.setAppData(new Gson().toJson(appDataVersionJson)); + update(globalState); } else { //if not present create Global State for state name Version. @@ -170,4 +189,3 @@ private void updateGlobalStateForAppDataVersion(XXGlobalState globalState, Strin } } } - 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 index 12708f6a3f..68c6ceb45e 100644 --- a/security-admin/src/main/java/org/apache/ranger/db/XXGroupDao.java +++ b/security-admin/src/main/java/org/apache/ranger/db/XXGroupDao.java @@ -19,12 +19,6 @@ package org.apache.ranger.db; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - import org.apache.commons.lang3.StringUtils; import org.apache.ranger.authorization.utils.JsonUtils; import org.apache.ranger.common.RangerCommonEnums; @@ -37,113 +31,116 @@ import javax.persistence.NoResultException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + import static org.apache.ranger.plugin.util.RangerCommonConstants.SCRIPT_FIELD__IS_INTERNAL; import static org.apache.ranger.plugin.util.RangerCommonConstants.SCRIPT_FIELD__SYNC_SOURCE; @Service public class XXGroupDao extends BaseDao { - private static final Logger logger = LoggerFactory.getLogger(XXGroupDao.class); - - public XXGroupDao(RangerDaoManagerBase daoManager) { - super(daoManager); - } - - @SuppressWarnings("unchecked") - public List findByUserId(Long userId) { - if (userId == null) { - return new ArrayList(); - } - - List groupList = (List) getEntityManager() - .createNamedQuery("XXGroup.findByUserId") - .setParameter("userId", userId).getResultList(); - - if (groupList == null) { - groupList = new ArrayList(); - } - - return groupList; - } - - 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; - } - - public Map getAllGroupIdNames() { - Map groups = new HashMap(); - try { - List rows = (List) getEntityManager().createNamedQuery("XXGroup.getAllGroupIdNames").getResultList(); - if (rows != null) { - for (Object[] row : rows) { - groups.put((Long)row[0], (String)row[1]); - } - } - } catch (Exception ex) { - } - return groups; - } - - - public List getAllGroupsInfo() { - List ret = new ArrayList<>(); - - try { - List rows = getEntityManager().createNamedQuery("XXGroup.getAllGroupsInfo", Object[].class).getResultList(); - - if (rows != null) { - for (Object[] row : rows) { - - ret.add(toGroupInfo(row)); - } - } - } catch (NoResultException excp) { - if (logger.isDebugEnabled()) { - logger.debug(excp.getMessage()); - } - } - - return ret; - } - - private GroupInfo toGroupInfo(Object[] row) { - String name = (String) row[0]; - String description = (String) row[1]; - String attributes = (String) row[2]; - String syncSource = (String) row[3]; - Number groupSource = (Number) row[4]; - Boolean isInternal = groupSource != null && groupSource.equals(RangerCommonEnums.GROUP_INTERNAL); - Map attrMap = null; - - if (StringUtils.isNotBlank(attributes)) { - try { + private static final Logger logger = LoggerFactory.getLogger(XXGroupDao.class); + + public XXGroupDao(RangerDaoManagerBase daoManager) { + super(daoManager); + } + + public List findByUserId(Long userId) { + if (userId == null) { + return new ArrayList<>(); + } + + List groupList = (List) getEntityManager() + .createNamedQuery("XXGroup.findByUserId", tClass) + .setParameter("userId", userId).getResultList(); + + if (groupList == null) { + groupList = new ArrayList<>(); + } + + return groupList; + } + + 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; + } + } + + public Map getAllGroupIdNames() { + Map groups = new HashMap<>(); + + try { + List rows = getEntityManager().createNamedQuery("XXGroup.getAllGroupIdNames", Object[].class).getResultList(); + + if (rows != null) { + for (Object[] row : rows) { + groups.put((Long) row[0], (String) row[1]); + } + } + } catch (Exception ex) { + return new HashMap<>(); + } + + return groups; + } + + public List getAllGroupsInfo() { + List ret = new ArrayList<>(); + + try { + List rows = getEntityManager().createNamedQuery("XXGroup.getAllGroupsInfo", Object[].class).getResultList(); + + if (rows != null) { + for (Object[] row : rows) { + ret.add(toGroupInfo(row)); + } + } + } catch (NoResultException excp) { + logger.debug(excp.getMessage()); + } + + return ret; + } + + private GroupInfo toGroupInfo(Object[] row) { + String name = (String) row[0]; + String description = (String) row[1]; + String attributes = (String) row[2]; + String syncSource = (String) row[3]; + Number groupSource = (Number) row[4]; + boolean isInternal = groupSource != null && groupSource.equals(RangerCommonEnums.GROUP_INTERNAL); + Map attrMap = null; + + if (StringUtils.isNotBlank(attributes)) { + try { attrMap = JsonUtils.jsonToMapStringString(attributes); - } catch (Exception excp) { - // ignore - } - } + } catch (Exception excp) { + // ignore + } + } - if (attrMap == null) { - attrMap = new HashMap<>(); - } + if (attrMap == null) { + attrMap = new HashMap<>(); + } - if (StringUtils.isNotBlank(syncSource)) { - attrMap.put(SCRIPT_FIELD__SYNC_SOURCE, syncSource); - } + if (StringUtils.isNotBlank(syncSource)) { + attrMap.put(SCRIPT_FIELD__SYNC_SOURCE, syncSource); + } - attrMap.put(SCRIPT_FIELD__IS_INTERNAL, isInternal.toString()); + attrMap.put(SCRIPT_FIELD__IS_INTERNAL, Boolean.toString(isInternal)); - return new GroupInfo(name, description, attrMap); - } + return new GroupInfo(name, description, attrMap); + } } 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 index 0f6e94c138..79e4541b10 100644 --- a/security-admin/src/main/java/org/apache/ranger/db/XXGroupGroupDao.java +++ b/security-admin/src/main/java/org/apache/ranger/db/XXGroupGroupDao.java @@ -17,61 +17,61 @@ * under the License. */ - package org.apache.ranger.db; +package org.apache.ranger.db; + +import org.apache.ranger.common.db.BaseDao; +import org.apache.ranger.entity.XXGroupGroup; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Service; + +import javax.persistence.NoResultException; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; -import javax.persistence.NoResultException; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.apache.ranger.common.db.BaseDao; -import org.apache.ranger.entity.XXGroupGroup; -import org.springframework.stereotype.Service; - @Service public class XXGroupGroupDao extends BaseDao { + private static final Logger logger = LoggerFactory.getLogger(XXGroupGroupDao.class); - private static final Logger logger = LoggerFactory.getLogger(XXGroupGroupDao.class); - - public XXGroupGroupDao( RangerDaoManagerBase daoManager ) { - super(daoManager); + public XXGroupGroupDao(RangerDaoManagerBase daoManager) { + super(daoManager); } + public List findByGroupId(Long groupId) { - if (groupId == null) { - return new ArrayList(); - } - try { - return getEntityManager().createNamedQuery("XXGroupGroup.findByGroupId", tClass) - .setParameter("groupId", groupId) - .setParameter("parentGroupId", groupId) - .getResultList(); - } catch (NoResultException e) { - return new ArrayList(); - } - } + if (groupId == null) { + return new ArrayList<>(); + } - public Set findGroupNamesByGroupName(String groupName) { - List groupList = null; + try { + return getEntityManager().createNamedQuery("XXGroupGroup.findByGroupId", tClass) + .setParameter("groupId", groupId) + .setParameter("parentGroupId", groupId) + .getResultList(); + } catch (NoResultException e) { + return new ArrayList<>(); + } + } - if (groupName != null) { - try { - groupList = getEntityManager().createNamedQuery("XXGroupGroup.findGroupNamesByGroupName", String.class).setParameter("groupName", groupName).getResultList(); - } catch (NoResultException e) { - logger.debug(e.getMessage()); - } - } else { - logger.debug("GroupName not provided..."); - } + public Set findGroupNamesByGroupName(String groupName) { + List groupList = null; - if(groupList != null) { - return new HashSet(groupList); - } + if (groupName != null) { + try { + groupList = getEntityManager().createNamedQuery("XXGroupGroup.findGroupNamesByGroupName", String.class).setParameter("groupName", groupName).getResultList(); + } catch (NoResultException e) { + logger.debug(e.getMessage()); + } + } else { + logger.debug("GroupName not provided..."); + } - return new HashSet(); - } -} + if (groupList != null) { + return new HashSet<>(groupList); + } + return new HashSet<>(); + } +} diff --git a/security-admin/src/main/java/org/apache/ranger/db/XXGroupPermissionDao.java b/security-admin/src/main/java/org/apache/ranger/db/XXGroupPermissionDao.java index 2647c6f7be..1f5fec92de 100644 --- a/security-admin/src/main/java/org/apache/ranger/db/XXGroupPermissionDao.java +++ b/security-admin/src/main/java/org/apache/ranger/db/XXGroupPermissionDao.java @@ -17,11 +17,6 @@ package org.apache.ranger.db; -import java.util.ArrayList; -import java.util.List; - -import javax.persistence.NoResultException; - import org.apache.ranger.common.RangerCommonEnums; import org.apache.ranger.common.db.BaseDao; import org.apache.ranger.entity.XXGroupPermission; @@ -29,121 +24,108 @@ import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; +import javax.persistence.NoResultException; + +import java.util.ArrayList; +import java.util.List; + @Service public class XXGroupPermissionDao extends BaseDao { + private static final Logger logger = LoggerFactory.getLogger(XXGroupPermissionDao.class); + + public XXGroupPermissionDao(RangerDaoManagerBase daoManager) { + super(daoManager); + } + + public List findByModuleId(Long moduleId, boolean isUpdate) { + if (moduleId != null) { + try { + if (isUpdate) { + return getEntityManager().createNamedQuery("XXGroupPermissionUpdates.findByModuleId", XXGroupPermission.class).setParameter("moduleId", moduleId).getResultList(); + } + + return getEntityManager().createNamedQuery("XXGroupPermission.findByModuleId", XXGroupPermission.class).setParameter("moduleId", moduleId).setParameter("isAllowed", RangerCommonEnums.IS_ALLOWED).getResultList(); + } catch (NoResultException e) { + logger.debug(e.getMessage()); + } + } else { + logger.debug("ResourcegroupId not provided."); + + return new ArrayList<>(); + } + + return null; + } + + public List findByGroupId(Long groupId) { + if (groupId != null) { + try { + return getEntityManager().createNamedQuery("XXGroupPermission.findByGroupId", XXGroupPermission.class).setParameter("groupId", groupId).getResultList(); + } catch (NoResultException e) { + logger.debug(e.getMessage()); + } + } else { + logger.debug("ResourcegroupId not provided."); + + return new ArrayList<>(); + } + + return null; + } + + public List findbyVXPortalUserId(Long userId) { + if (userId != null) { + try { + return getEntityManager().createNamedQuery("XXGroupPermission.findByVXPoratUserId", XXGroupPermission.class).setParameter("userId", userId).setParameter("isAllowed", RangerCommonEnums.IS_ALLOWED).getResultList(); + } catch (NoResultException e) { + logger.debug(e.getMessage()); + } + } else { + logger.debug("ResourcegroupId not provided."); + + return new ArrayList<>(); + } + + return null; + } + + public XXGroupPermission findByModuleIdAndGroupId(Long groupId, Long moduleId) { + if (groupId != null && moduleId != null) { + try { + return getEntityManager().createNamedQuery("XXGroupPermission.findByModuleIdAndGroupId", tClass).setParameter("groupId", groupId).setParameter("moduleId", moduleId).getSingleResult(); + } catch (NoResultException e) { + logger.debug(e.getMessage()); + } + } else { + return null; + } + + return null; + } + + public void deleteByModuleId(Long moduleId) { + if (moduleId != null) { + try { + getEntityManager().createNamedQuery("XXGroupPermission.deleteByModuleId", XXGroupPermission.class).setParameter("moduleId", moduleId).executeUpdate(); + } catch (Exception e) { + logger.debug(e.getMessage()); + } + } else { + logger.debug("ModuleId not provided."); + } + } + + public List findModuleGroupsByModuleId(Long moduleId) { + if (moduleId != null) { + try { + return getEntityManager().createNamedQuery("XXGroupPermission.findModuleGroupsByModuleId", String.class).setParameter("moduleId", moduleId).setParameter("isAllowed", RangerCommonEnums.IS_ALLOWED).getResultList(); + } catch (Exception e) { + logger.debug(e.getMessage()); + } + } else { + logger.debug("ModuleId not provided."); + } - private static final Logger logger = LoggerFactory.getLogger(XXGroupPermissionDao.class); - - public XXGroupPermissionDao(RangerDaoManagerBase daoManager) { - super(daoManager); - } - - public List findByModuleId(Long moduleId, - boolean isUpdate) { - if (moduleId != null) { - try { - if (isUpdate) { - return getEntityManager() - .createNamedQuery( - "XXGroupPermissionUpdates.findByModuleId", - XXGroupPermission.class) - .setParameter("moduleId", moduleId).getResultList(); - } - return getEntityManager() - .createNamedQuery( - "XXGroupPermission.findByModuleId", - XXGroupPermission.class) - .setParameter("moduleId", moduleId) - .setParameter("isAllowed", RangerCommonEnums.IS_ALLOWED) - .getResultList(); - } catch (NoResultException e) { - logger.debug(e.getMessage()); - } - } else { - logger.debug("ResourcegropuIdId not provided."); - return new ArrayList(); - } - return null; - } - - public List findByGroupId(Long groupId) { - if (groupId != null) { - try { - return getEntityManager() - .createNamedQuery( - "XXGroupPermission.findByGroupId", - XXGroupPermission.class) - .setParameter("groupId", groupId).getResultList(); - } catch (NoResultException e) { - logger.debug(e.getMessage()); - } - } else { - logger.debug("ResourcegropuIdId not provided."); - return new ArrayList(); - } - return null; - } - public List findbyVXPortalUserId(Long userId) { - if (userId != null) { - try { - return getEntityManager() - .createNamedQuery( - "XXGroupPermission.findByVXPoratUserId", - XXGroupPermission.class) - .setParameter("userId", userId) - .setParameter("isAllowed", RangerCommonEnums.IS_ALLOWED) - .getResultList(); - } catch (NoResultException e) { - logger.debug(e.getMessage()); - } - } else { - logger.debug("ResourcegropuIdId not provided."); - return new ArrayList(); - } - return null; - } - - public XXGroupPermission findByModuleIdAndGroupId(Long groupId, Long moduleId) { - if (groupId != null && moduleId != null) { - try { - return getEntityManager().createNamedQuery("XXGroupPermission.findByModuleIdAndGroupId", tClass).setParameter("groupId", groupId).setParameter("moduleId", moduleId) - .getSingleResult(); - } catch (NoResultException e) { - logger.debug(e.getMessage()); - } - } else { - return null; - } - return null; - } - public void deleteByModuleId(Long moduleId) { - if (moduleId != null) { - try { - getEntityManager() - .createNamedQuery("XXGroupPermission.deleteByModuleId", XXGroupPermission.class) - .setParameter("moduleId", moduleId) - .executeUpdate(); - } catch (Exception e) { - logger.debug(e.getMessage()); - } - } else { - logger.debug("ModuleId not provided."); - } - } - - public List findModuleGroupsByModuleId(Long moduleId) { - if (moduleId != null) { - try { - return getEntityManager().createNamedQuery("XXGroupPermission.findModuleGroupsByModuleId", String.class) - .setParameter("moduleId", moduleId) - .setParameter("isAllowed",RangerCommonEnums.IS_ALLOWED) - .getResultList(); - } catch (Exception e) { - logger.debug(e.getMessage()); - } - } else { - logger.debug("ModuleId not provided."); - } - return null; - } + return null; + } } 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 index 76cdd93f55..d64a278b2f 100644 --- a/security-admin/src/main/java/org/apache/ranger/db/XXGroupUserDao.java +++ b/security-admin/src/main/java/org/apache/ranger/db/XXGroupUserDao.java @@ -17,12 +17,7 @@ * under the License. */ - package org.apache.ranger.db; - - -import java.util.*; - -import javax.persistence.NoResultException; +package org.apache.ranger.db; import org.apache.commons.lang.StringUtils; import org.apache.ranger.common.db.BaseDao; @@ -31,153 +26,153 @@ import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; +import javax.persistence.NoResultException; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + @Service public class XXGroupUserDao extends BaseDao { - private static final Logger logger = LoggerFactory.getLogger(XXGroupUserDao.class); - - public XXGroupUserDao(RangerDaoManagerBase daoManager) { - super(daoManager); - } - - public void deleteByGroupIdAndUserId(Long groupId, Long userId) { - getEntityManager() - .createNamedQuery("XXGroupUser.deleteByGroupIdAndUserId") - .setParameter("userId", userId) - .setParameter("parentGroupId", groupId).executeUpdate(); - - } - - public List 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(); - } - return null; - } - - /** - * @param xUserId - * -- Id of X_USER table - * @return - */ - @SuppressWarnings("unchecked") - public List findGroupIdListByUserId(Long xUserId) { - if (xUserId != null) { - try { - return getEntityManager().createNamedQuery("XXGroupUser.findGroupIdListByUserId").setParameter("xUserId", xUserId).getResultList(); - } catch (NoResultException e) { - logger.debug(e.getMessage()); - } - } else { - logger.debug("UserId not provided."); - return new ArrayList(); - } - return null; - } - - public Set findGroupNamesByUserName(String userName) { - List groupList = null; - - if (userName != null) { - try { - groupList = getEntityManager().createNamedQuery("XXGroupUser.findGroupNamesByUserName", String.class).setParameter("userName", userName).getResultList(); - } catch (NoResultException e) { - logger.debug(e.getMessage()); - } - } else { - logger.debug("UserId not provided."); - } - - if(groupList != null) { - return new HashSet(groupList); - } - - return new HashSet(); - } - - public List findByGroupId(Long groupId) { - if (groupId == null) { - return new ArrayList(); - } - try { - return getEntityManager().createNamedQuery("XXGroupUser.findByGroupId", tClass).setParameter("groupId", groupId).getResultList(); - } catch (NoResultException e) { - return new ArrayList(); - } - } - - public XXGroupUser findByGroupNameAndUserId(String groupName, Long userId) { - if (StringUtils.isNotBlank(groupName) && userId != null) { - try { - return getEntityManager() - .createNamedQuery("XXGroupUser.findByGroupNameAndUserId", XXGroupUser.class) - .setParameter("userId", userId) - .setParameter("groupName", groupName) - .getSingleResult(); - } catch (NoResultException e) { - logger.debug(e.getMessage()); - } - } else { - logger.debug("userId and/or groupId not provided."); - return new XXGroupUser(); - } - return null; - } - - public Map> findUsersByGroupIds() { - Map> groupUsers = new HashMap<>(); - - try { - List rows = (List) getEntityManager() - .createNamedQuery("XXGroupUser.findUsersByGroupIds") - .getResultList(); - if (rows != null) { - for (Object[] row : rows) { - if (groupUsers.containsKey((String)row[0])) { - groupUsers.get((String)row[0]).add((String)row[1]); - } else { - Set users = new HashSet<>(); - users.add((String)row[1]); - groupUsers.put((String)row[0], users); - } - } - } - } catch (NoResultException e) { - //Ignore - } - return groupUsers; - } - - public Map findUsersByGroupName(String groupName) { - Map users = new HashMap<>(); - - if (StringUtils.isNotBlank(groupName)) { - try { - List rows = (List) getEntityManager() - .createNamedQuery("XXGroupUser.findUsersByGroupName") - .setParameter("groupName", groupName) - .getResultList(); - if (rows != null) { - for (Object[] row : rows) { - users.put((String)row[0], (XXGroupUser)row[1]); - } - } - } catch (NoResultException e) { - if (logger.isDebugEnabled()) { - logger.debug(e.getMessage()); - } - } - } - - return users; - } + private static final Logger logger = LoggerFactory.getLogger(XXGroupUserDao.class); + + public XXGroupUserDao(RangerDaoManagerBase daoManager) { + super(daoManager); + } + + public void deleteByGroupIdAndUserId(Long groupId, Long userId) { + getEntityManager().createNamedQuery("XXGroupUser.deleteByGroupIdAndUserId").setParameter("userId", userId).setParameter("parentGroupId", groupId).executeUpdate(); + } + + public List 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<>(); + } + + return null; + } + + /** + * @param xUserId -- Id of X_USER table + * @return + */ + public List findGroupIdListByUserId(Long xUserId) { + if (xUserId != null) { + try { + return getEntityManager().createNamedQuery("XXGroupUser.findGroupIdListByUserId", Long.class).setParameter("xUserId", xUserId).getResultList(); + } catch (NoResultException e) { + logger.debug(e.getMessage()); + } + } else { + logger.debug("UserId not provided."); + + return new ArrayList<>(); + } + + return null; + } + + public Set findGroupNamesByUserName(String userName) { + List groupList = null; + + if (userName != null) { + try { + groupList = getEntityManager().createNamedQuery("XXGroupUser.findGroupNamesByUserName", String.class).setParameter("userName", userName).getResultList(); + } catch (NoResultException e) { + logger.debug(e.getMessage()); + } + } else { + logger.debug("UserId not provided."); + } + + if (groupList != null) { + return new HashSet<>(groupList); + } + + return new HashSet<>(); + } + + public List findByGroupId(Long groupId) { + if (groupId == null) { + return new ArrayList<>(); + } + + try { + return getEntityManager().createNamedQuery("XXGroupUser.findByGroupId", tClass).setParameter("groupId", groupId).getResultList(); + } catch (NoResultException e) { + return new ArrayList<>(); + } + } + + public XXGroupUser findByGroupNameAndUserId(String groupName, Long userId) { + if (StringUtils.isNotBlank(groupName) && userId != null) { + try { + return getEntityManager().createNamedQuery("XXGroupUser.findByGroupNameAndUserId", XXGroupUser.class).setParameter("userId", userId).setParameter("groupName", groupName).getSingleResult(); + } catch (NoResultException e) { + logger.debug(e.getMessage()); + } + } else { + logger.debug("userId and/or groupId not provided."); + + return new XXGroupUser(); + } + + return null; + } + + public Map> findUsersByGroupIds() { + Map> groupUsers = new HashMap<>(); + + try { + List rows = getEntityManager().createNamedQuery("XXGroupUser.findUsersByGroupIds", Object[].class).getResultList(); + + if (rows != null) { + for (Object[] row : rows) { + if (groupUsers.containsKey((String) row[0])) { + groupUsers.get((String) row[0]).add((String) row[1]); + } else { + Set users = new HashSet<>(); + + users.add((String) row[1]); + groupUsers.put((String) row[0], users); + } + } + } + } catch (NoResultException e) { + //Ignore + } + + return groupUsers; + } + + public Map findUsersByGroupName(String groupName) { + Map users = new HashMap<>(); + + if (StringUtils.isNotBlank(groupName)) { + try { + List rows = getEntityManager().createNamedQuery("XXGroupUser.findUsersByGroupName", Object[].class).setParameter("groupName", groupName).getResultList(); + + if (rows != null) { + for (Object[] row : rows) { + users.put((String) row[0], (XXGroupUser) row[1]); + } + } + } catch (NoResultException e) { + logger.debug(e.getMessage()); + } + } + + return users; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/db/XXModuleDefDao.java b/security-admin/src/main/java/org/apache/ranger/db/XXModuleDefDao.java index c5b0daf445..461fcffb30 100644 --- a/security-admin/src/main/java/org/apache/ranger/db/XXModuleDefDao.java +++ b/security-admin/src/main/java/org/apache/ranger/db/XXModuleDefDao.java @@ -17,129 +17,127 @@ package org.apache.ranger.db; -import java.util.ArrayList; -import java.util.List; - -import javax.persistence.NoResultException; - import org.apache.commons.collections.CollectionUtils; import org.apache.ranger.common.RangerCommonEnums; import org.apache.ranger.common.db.BaseDao; import org.apache.ranger.entity.XXModuleDef; import org.springframework.stereotype.Service; -@Service -public class XXModuleDefDao extends BaseDao{ - - public XXModuleDefDao(RangerDaoManagerBase daoManager) { - super(daoManager); - } - - public XXModuleDef findByModuleName(String moduleName){ - if (moduleName == null) { - return null; - } - try { - - return (XXModuleDef) getEntityManager() - .createNamedQuery("XXModuleDef.findByModuleName") - .setParameter("moduleName", moduleName) - .getSingleResult(); - } catch (Exception e) { - - } - return null; - } - - - public XXModuleDef findByModuleId(Long id) { - if(id == null) { - return new XXModuleDef(); - } - try { - List xxModuelDefs=getEntityManager() - .createNamedQuery("XXModuleDef.findByModuleId", tClass) - .setParameter("id", id).getResultList(); - return xxModuelDefs.get(0); - } catch (NoResultException e) { - return new XXModuleDef(); - } - } - - @SuppressWarnings("unchecked") - public List findModuleURLOfPemittedModules(Long userId) { - try { - - String query="select"; - query+=" url"; - query+=" FROM"; - query+=" x_modules_master"; - query+=" WHERE"; - query+=" url NOT IN (SELECT "; - query+=" moduleMaster.url"; - query+=" FROM"; - query+=" x_modules_master moduleMaster,"; - query+=" x_user_module_perm userModulePermission"; - query+=" WHERE"; - query+=" moduleMaster.id = userModulePermission.module_id"; - query+=" AND userModulePermission.user_id = "+userId+")"; - query+=" AND "; - query+=" id NOT IN (SELECT DISTINCT"; - query+=" gmp.module_id"; - query+=" FROM"; - query+=" x_group_users xgu,"; - query+=" x_user xu,"; - query+=" x_group_module_perm gmp,"; - query+=" x_portal_user xpu"; - query+=" WHERE"; - query+=" xu.user_name = xpu.login_id"; - query+=" AND xu.id = xgu.user_id"; - query+=" AND xgu.p_group_id = gmp.group_id"; - query+=" AND xpu.id = "+userId+")"; - - return getEntityManager() - .createNativeQuery(query) - .getResultList(); - - } catch (Exception e) { - e.printStackTrace(); - return null; - } - } - - @SuppressWarnings("unchecked") - public List findAccessibleModulesByGroupIdList(List grpIdList) { - if (CollectionUtils.isEmpty(grpIdList)) { - return new ArrayList(); - } - try { - return getEntityManager().createNamedQuery("XXModuleDef.findAccessibleModulesByGroupId").setParameter("grpIdList", grpIdList) - .setParameter("isAllowed", RangerCommonEnums.ACCESS_RESULT_ALLOWED).getResultList(); - } catch (NoResultException e) { - return new ArrayList(); - } - } - - /** - * @param portalUserId - * @param xUserId - * @return This function will return all the modules accessible for particular user, considering all the groups as well in which that user belongs - */ - @SuppressWarnings("unchecked") - public List findAccessibleModulesByUserId(Long portalUserId, Long xUserId) { - if (portalUserId == null || xUserId == null) { - return new ArrayList(); - } - try { - - List userPermList = getEntityManager().createNamedQuery("XXModuleDef.findAllAccessibleModulesByUserId").setParameter("portalUserId", portalUserId) - .setParameter("xUserId", xUserId).setParameter("isAllowed", RangerCommonEnums.ACCESS_RESULT_ALLOWED).getResultList(); - - return userPermList; - - } catch (NoResultException e) { - return new ArrayList(); - } - } +import javax.persistence.NoResultException; +import java.util.ArrayList; +import java.util.List; + +@Service +public class XXModuleDefDao extends BaseDao { + public XXModuleDefDao(RangerDaoManagerBase daoManager) { + super(daoManager); + } + + public XXModuleDef findByModuleName(String moduleName) { + if (moduleName == null) { + return null; + } + + try { + return getEntityManager() + .createNamedQuery("XXModuleDef.findByModuleName", tClass) + .setParameter("moduleName", moduleName) + .getSingleResult(); + } catch (Exception e) { + return null; + } + } + + public XXModuleDef findByModuleId(Long id) { + if (id == null) { + return new XXModuleDef(); + } + + try { + List xxModuelDefs = getEntityManager() + .createNamedQuery("XXModuleDef.findByModuleId", tClass) + .setParameter("id", id).getResultList(); + return xxModuelDefs.get(0); + } catch (NoResultException e) { + return new XXModuleDef(); + } + } + + @SuppressWarnings("unchecked") + public List findModuleURLOfPemittedModules(Long userId) { + try { + String query = "select"; + + query += " url"; + query += " FROM"; + query += " x_modules_master"; + query += " WHERE"; + query += " url NOT IN (SELECT "; + query += " moduleMaster.url"; + query += " FROM"; + query += " x_modules_master moduleMaster,"; + query += " x_user_module_perm userModulePermission"; + query += " WHERE"; + query += " moduleMaster.id = userModulePermission.module_id"; + query += " AND userModulePermission.user_id = " + userId + ")"; + query += " AND "; + query += " id NOT IN (SELECT DISTINCT"; + query += " gmp.module_id"; + query += " FROM"; + query += " x_group_users xgu,"; + query += " x_user xu,"; + query += " x_group_module_perm gmp,"; + query += " x_portal_user xpu"; + query += " WHERE"; + query += " xu.user_name = xpu.login_id"; + query += " AND xu.id = xgu.user_id"; + query += " AND xgu.p_group_id = gmp.group_id"; + query += " AND xpu.id = " + userId + ")"; + + return getEntityManager() + .createNativeQuery(query) + .getResultList(); + } catch (Exception e) { + e.printStackTrace(); + + return null; + } + } + + public List findAccessibleModulesByGroupIdList(List grpIdList) { + if (CollectionUtils.isEmpty(grpIdList)) { + return new ArrayList<>(); + } + + try { + return getEntityManager() + .createNamedQuery("XXModuleDef.findAccessibleModulesByGroupId", String.class) + .setParameter("grpIdList", grpIdList) + .setParameter("isAllowed", RangerCommonEnums.ACCESS_RESULT_ALLOWED) + .getResultList(); + } catch (NoResultException e) { + return new ArrayList<>(); + } + } + + /** + * @param portalUserId + * @param xUserId + * @return This function will return all the modules accessible for particular user, considering all the groups as well in which that user belongs + */ + public List findAccessibleModulesByUserId(Long portalUserId, Long xUserId) { + if (portalUserId == null || xUserId == null) { + return new ArrayList<>(); + } + + try { + return getEntityManager().createNamedQuery("XXModuleDef.findAllAccessibleModulesByUserId", String.class) + .setParameter("portalUserId", portalUserId) + .setParameter("xUserId", xUserId).setParameter("isAllowed", RangerCommonEnums.ACCESS_RESULT_ALLOWED) + .getResultList(); + } catch (NoResultException e) { + return new ArrayList<>(); + } + } } 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 index 03feb5a79b..fcc6082147 100644 --- a/security-admin/src/main/java/org/apache/ranger/db/XXPermMapDao.java +++ b/security-admin/src/main/java/org/apache/ranger/db/XXPermMapDao.java @@ -17,12 +17,7 @@ * under the License. */ - package org.apache.ranger.db; - -import java.util.ArrayList; -import java.util.List; - -import javax.persistence.NoResultException; +package org.apache.ranger.db; import org.apache.ranger.common.db.BaseDao; import org.apache.ranger.entity.XXPermMap; @@ -30,29 +25,35 @@ import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; +import javax.persistence.NoResultException; + +import java.util.ArrayList; +import java.util.List; + @Service public class XXPermMapDao extends BaseDao { - private static final Logger logger = LoggerFactory.getLogger(XXResourceDao.class); + private static final Logger logger = LoggerFactory.getLogger(XXPermMapDao.class); - public XXPermMapDao( RangerDaoManagerBase daoManager ) { - super(daoManager); + public XXPermMapDao(RangerDaoManagerBase daoManager) { + super(daoManager); } - public List 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(); - } - return null; - } + public List 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<>(); + } + + return null; + } } - diff --git a/security-admin/src/main/java/org/apache/ranger/db/XXPluginInfoDao.java b/security-admin/src/main/java/org/apache/ranger/db/XXPluginInfoDao.java index 57cdfeaae0..409bc06f5e 100644 --- a/security-admin/src/main/java/org/apache/ranger/db/XXPluginInfoDao.java +++ b/security-admin/src/main/java/org/apache/ranger/db/XXPluginInfoDao.java @@ -17,92 +17,100 @@ package org.apache.ranger.db; -import java.util.List; - -import javax.persistence.NoResultException; - import org.apache.ranger.common.DateUtil; import org.apache.ranger.common.db.BaseDao; import org.apache.ranger.entity.XXPluginInfo; import org.springframework.stereotype.Service; +import javax.persistence.NoResultException; + +import java.util.List; + /** + * */ @Service public class XXPluginInfoDao extends BaseDao { - /** - * Default Constructor - */ - public XXPluginInfoDao(RangerDaoManagerBase daoManager) { - super(daoManager); - } - - @Override - public XXPluginInfo create(XXPluginInfo obj) { - obj.setCreateTime(DateUtil.getUTCDate()); - obj.setUpdateTime(DateUtil.getUTCDate()); - return super.create(obj); - } - - @Override - public XXPluginInfo update(XXPluginInfo obj) { - obj.setUpdateTime(DateUtil.getUTCDate()); - return super.update(obj); - } - public XXPluginInfo find(String serviceName, String hostName, String appType) { - if (serviceName == null || hostName == null || appType == null) { - return null; - } - try { - return getEntityManager() - .createNamedQuery("XXPluginInfo.find", tClass) - .setParameter("serviceName", serviceName) - .setParameter("appType", appType) - .setParameter("hostName", hostName) - .getSingleResult(); - } catch (NoResultException e) { - return null; - } - } - public List findByServiceName(String serviceName) { - if (serviceName == null) { - return null; - } - try { - return getEntityManager() - .createNamedQuery("XXPluginInfo.findByServiceName", tClass) - .setParameter("serviceName", serviceName).getResultList(); - } catch (NoResultException e) { - return null; - } - } - - public List findByServiceId(Long serviceId) { - if (serviceId == null) { - return null; - } - try { - return getEntityManager() - .createNamedQuery("XXPluginInfo.findByServiceId", tClass) - .setParameter("serviceId", serviceId).getResultList(); - } catch (NoResultException e) { - return null; - } - } - - public List findByServiceAndHostName(String serviceName, String hostName) { - if (serviceName == null || hostName == null) { - return null; - } - try { - return getEntityManager() - .createNamedQuery("XXPluginInfo.findByServiceAndHostName", tClass) - .setParameter("serviceName", serviceName) - .setParameter("hostName", hostName) - .getResultList(); - } catch (NoResultException e) { - return null; - } - } + /** + * Default Constructor + */ + public XXPluginInfoDao(RangerDaoManagerBase daoManager) { + super(daoManager); + } + + @Override + public XXPluginInfo create(XXPluginInfo obj) { + obj.setCreateTime(DateUtil.getUTCDate()); + obj.setUpdateTime(DateUtil.getUTCDate()); + + return super.create(obj); + } + + @Override + public XXPluginInfo update(XXPluginInfo obj) { + obj.setUpdateTime(DateUtil.getUTCDate()); + + return super.update(obj); + } + + public XXPluginInfo find(String serviceName, String hostName, String appType) { + if (serviceName == null || hostName == null || appType == null) { + return null; + } + + try { + return getEntityManager() + .createNamedQuery("XXPluginInfo.find", tClass) + .setParameter("serviceName", serviceName) + .setParameter("appType", appType) + .setParameter("hostName", hostName) + .getSingleResult(); + } catch (NoResultException e) { + return null; + } + } + + public List findByServiceName(String serviceName) { + if (serviceName == null) { + return null; + } + + try { + return getEntityManager() + .createNamedQuery("XXPluginInfo.findByServiceName", tClass) + .setParameter("serviceName", serviceName).getResultList(); + } catch (NoResultException e) { + return null; + } + } + + public List findByServiceId(Long serviceId) { + if (serviceId == null) { + return null; + } + + try { + return getEntityManager() + .createNamedQuery("XXPluginInfo.findByServiceId", tClass) + .setParameter("serviceId", serviceId).getResultList(); + } catch (NoResultException e) { + return null; + } + } + + public List findByServiceAndHostName(String serviceName, String hostName) { + if (serviceName == null || hostName == null) { + return null; + } + try { + return getEntityManager() + .createNamedQuery("XXPluginInfo.findByServiceAndHostName", tClass) + .setParameter("serviceName", serviceName) + .setParameter("hostName", hostName) + .getResultList(); + } catch (NoResultException e) { + return null; + } + } } diff --git a/security-admin/src/main/java/org/apache/ranger/db/XXPolicyChangeLogDao.java b/security-admin/src/main/java/org/apache/ranger/db/XXPolicyChangeLogDao.java index bdf05cdb72..4196c7aca5 100644 --- a/security-admin/src/main/java/org/apache/ranger/db/XXPolicyChangeLogDao.java +++ b/security-admin/src/main/java/org/apache/ranger/db/XXPolicyChangeLogDao.java @@ -17,12 +17,6 @@ package org.apache.ranger.db; -import java.util.ArrayList; -import java.util.Date; -import java.util.Iterator; -import java.util.List; -import java.util.concurrent.TimeUnit; - import org.apache.commons.collections.CollectionUtils; import org.apache.ranger.authorization.utils.JsonUtils; import org.apache.ranger.common.db.BaseDao; @@ -34,11 +28,17 @@ import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; +import java.util.ArrayList; +import java.util.Date; +import java.util.Iterator; +import java.util.List; +import java.util.concurrent.TimeUnit; + /** + * */ @Service public class XXPolicyChangeLogDao extends BaseDao { - private static final Logger LOG = LoggerFactory.getLogger(XXPolicyChangeLogDao.class); private static final int POLICY_CHANGE_LOG_RECORD_ID_COLUMN_NUMBER = 0; @@ -58,6 +58,7 @@ public XXPolicyChangeLogDao(RangerDaoManagerBase daoManager) { public List findLaterThan(Long version, Long maxVersion, Long serviceId) { final List ret; + if (version != null) { List logs = getEntityManager() .createNamedQuery("XXPolicyChangeLog.findSinceVersion", Object[].class) @@ -68,12 +69,13 @@ public List findLaterThan(Long version, Long maxVersion, Long // Ensure that first record has the same version as the base-version from where the records are fetched if (CollectionUtils.isNotEmpty(logs)) { - Iterator iter = logs.iterator(); - boolean foundAndRemoved = false; + Iterator iter = logs.iterator(); + boolean foundAndRemoved = false; while (iter.hasNext()) { - Object[] record = iter.next(); - Long recordVersion = (Long) record[POLICY_CHANGE_LOG_RECORD_POLICY_VERSION_COLUMN_NUMBER]; + Object[] record = iter.next(); + Long recordVersion = (Long) record[POLICY_CHANGE_LOG_RECORD_POLICY_VERSION_COLUMN_NUMBER]; + if (version.equals(recordVersion)) { iter.remove(); foundAndRemoved = true; @@ -81,6 +83,7 @@ public List findLaterThan(Long version, Long maxVersion, Long break; } } + if (foundAndRemoved) { ret = convert(logs); } else { @@ -92,11 +95,13 @@ public List findLaterThan(Long version, Long maxVersion, Long } else { ret = null; } + return ret; } public List findGreaterThan(Long id, Long maxVersion, Long serviceId) { final List ret; + if (id != null) { List logs = getEntityManager() .createNamedQuery("XXPolicyChangeLog.findGreaterThan", Object[].class) @@ -108,32 +113,25 @@ public List findGreaterThan(Long id, Long maxVersion, Long se } else { ret = null; } + return ret; } public void deleteOlderThan(int olderThanInDays) { - Date since = new Date(System.currentTimeMillis() - TimeUnit.DAYS.toMillis(olderThanInDays)); - if (LOG.isDebugEnabled()) { - LOG.debug("Deleting records from x_policy_change_log that are older than " + olderThanInDays + " days, that is, older than " + since); - } + LOG.debug("Deleting records from x_policy_change_log that are older than {} days, that is, older than {}", olderThanInDays, since); getEntityManager().createNamedQuery("XXPolicyChangeLog.deleteOlderThan").setParameter("olderThan", since).executeUpdate(); } private List convert(List queryResult) { - final List ret; if (CollectionUtils.isNotEmpty(queryResult)) { - ret = new ArrayList<>(queryResult.size()); for (Object[] log : queryResult) { - - RangerPolicy policy; - Long logRecordId = (Long) log[POLICY_CHANGE_LOG_RECORD_ID_COLUMN_NUMBER]; Integer policyChangeType = (Integer) log[POLICY_CHANGE_LOG_RECORD_CHANGE_TYPE_COLUMN_NUMBER]; Long policiesVersion = (Long) log[POLICY_CHANGE_LOG_RECORD_POLICY_VERSION_COLUMN_NUMBER]; @@ -141,28 +139,37 @@ private List convert(List queryResult) { Long policyId = (Long) log[POLICY_CHANGE_LOG_RECORD_POLICY_ID_COLUMN_NUMBER]; if (policyId != null) { - XXPolicy xxPolicy = daoManager.getXXPolicy().getById(policyId); + XXPolicy xxPolicy = daoManager.getXXPolicy().getById(policyId); + RangerPolicy policy; + if (xxPolicy != null) { try { policy = JsonUtils.jsonToObject(xxPolicy.getPolicyText(), RangerPolicy.class); + policy.setId(policyId); + if (policy.getServiceType() == null) { policy.setServiceType(serviceType); } + policy.setVersion(xxPolicy.getVersion()); } catch (Exception e) { - LOG.error("Cannot read policy:[" + policyId + "]. Should not have come here!! Offending log-record-id:[" + logRecordId + "] and returning...", e); + LOG.error("Cannot read policy:[{}]. Should not have come here!! Offending log-record-id:[{}] and returning...", policyId, logRecordId, e); + ret.clear(); ret.add(new RangerPolicyDelta(logRecordId, RangerPolicyDelta.CHANGE_TYPE_LOG_ERROR, null, null)); + break; } } else { if (policyChangeType == RangerPolicyDelta.CHANGE_TYPE_POLICY_CREATE || policyChangeType == RangerPolicyDelta.CHANGE_TYPE_POLICY_UPDATE) { - LOG.warn((policyChangeType == RangerPolicyDelta.CHANGE_TYPE_POLICY_CREATE ? "POLICY_CREATE" : "POLICY_UPDATE") + " type change for policy-id:[" + policyId + "], log-id:[" + logRecordId + "] was not found.. probably already deleted"); + LOG.warn("{} type change for policy-id:[{}], log-id:[{}] was not found.. probably already deleted", (policyChangeType == RangerPolicyDelta.CHANGE_TYPE_POLICY_CREATE ? "POLICY_CREATE" : "POLICY_UPDATE"), policyId, logRecordId); // Create a placeholder delta with a dummy policy as the created/updated policy cannot be found - If there is a subsequent POLICY_DELETE, this delta will be cleaned-up in ServiceDBStore.compressDeltas() } + // Create a placeholder delta with a dummy policy policy = new RangerPolicy(); + policy.setId(policyId); policy.setServiceType(serviceType); policy.setPolicyType((Integer) log[POLICY_CHANGE_LOG_RECORD_POLICY_TYPE_COLUMN_NUMBER]); @@ -171,17 +178,18 @@ private List convert(List queryResult) { ret.add(new RangerPolicyDelta(logRecordId, policyChangeType, policiesVersion, policy)); } else { - LOG.info("delta-reset-event: log-record-id=" + logRecordId + "; service-type=" + serviceType + "; policy-change-type=" + policyChangeType + ". Discarding " + ret.size() + " deltas"); + LOG.info("delta-reset-event: log-record-id={}; service-type={}; policy-change-type={}. Discarding {} deltas", logRecordId, serviceType, policyChangeType, ret.size()); + ret.clear(); ret.add(new RangerPolicyDelta(logRecordId, policyChangeType, null, null)); + break; } } } else { ret = null; } - return ret; + return ret; } - } diff --git a/security-admin/src/main/java/org/apache/ranger/db/XXPolicyConditionDefDao.java b/security-admin/src/main/java/org/apache/ranger/db/XXPolicyConditionDefDao.java index de2c47dc42..ac17b295ac 100644 --- a/security-admin/src/main/java/org/apache/ranger/db/XXPolicyConditionDefDao.java +++ b/security-admin/src/main/java/org/apache/ranger/db/XXPolicyConditionDefDao.java @@ -17,49 +17,47 @@ package org.apache.ranger.db; -import java.util.ArrayList; -import java.util.List; - -import javax.persistence.NoResultException; - import org.apache.ranger.common.db.BaseDao; import org.apache.ranger.entity.XXPolicyConditionDef; import org.springframework.stereotype.Service; -@Service -public class XXPolicyConditionDefDao extends BaseDao { - - public XXPolicyConditionDefDao(RangerDaoManagerBase daoManager) { - super(daoManager); - } +import javax.persistence.NoResultException; - public List findByServiceDefId(Long serviceDefId) { - if (serviceDefId == null) { - return new ArrayList(); - } - try { - List retList = getEntityManager() - .createNamedQuery("XXPolicyConditionDef.findByServiceDefId", tClass) - .setParameter("serviceDefId", serviceDefId).getResultList(); - return retList; - } catch (NoResultException e) { - return new ArrayList(); - } - } +import java.util.ArrayList; +import java.util.List; - public XXPolicyConditionDef findByServiceDefIdAndName(Long serviceDefId, String name) { - if (serviceDefId == null) { - return null; - } - try { - XXPolicyConditionDef retList = getEntityManager() - .createNamedQuery("XXPolicyConditionDef.findByServiceDefIdAndName", tClass) - .setParameter("serviceDefId", serviceDefId) - .setParameter("name", name).getSingleResult(); - return retList; - } catch (NoResultException e) { - return null; - } - } - +@Service +public class XXPolicyConditionDefDao extends BaseDao { + public XXPolicyConditionDefDao(RangerDaoManagerBase daoManager) { + super(daoManager); + } + + public List findByServiceDefId(Long serviceDefId) { + if (serviceDefId == null) { + return new ArrayList<>(); + } + + try { + return getEntityManager() + .createNamedQuery("XXPolicyConditionDef.findByServiceDefId", tClass) + .setParameter("serviceDefId", serviceDefId).getResultList(); + } catch (NoResultException e) { + return new ArrayList<>(); + } + } + + public XXPolicyConditionDef findByServiceDefIdAndName(Long serviceDefId, String name) { + if (serviceDefId == null) { + return null; + } + + try { + return getEntityManager() + .createNamedQuery("XXPolicyConditionDef.findByServiceDefIdAndName", tClass) + .setParameter("serviceDefId", serviceDefId) + .setParameter("name", name).getSingleResult(); + } catch (NoResultException e) { + return null; + } + } } diff --git a/security-admin/src/main/java/org/apache/ranger/db/XXPolicyDao.java b/security-admin/src/main/java/org/apache/ranger/db/XXPolicyDao.java index 48ca58c08e..e8ea726cbd 100755 --- a/security-admin/src/main/java/org/apache/ranger/db/XXPolicyDao.java +++ b/security-admin/src/main/java/org/apache/ranger/db/XXPolicyDao.java @@ -17,466 +17,499 @@ package org.apache.ranger.db; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.persistence.NoResultException; -import javax.persistence.Query; - -import org.apache.commons.collections.ListUtils; import org.apache.commons.lang.StringUtils; import org.apache.ranger.common.db.BaseDao; import org.apache.ranger.entity.XXPolicy; import org.apache.ranger.plugin.model.RangerSecurityZone; import org.springframework.stereotype.Service; +import javax.persistence.NoResultException; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + /** + * */ @Service public class XXPolicyDao extends BaseDao { - /** - * Default Constructor - */ - public XXPolicyDao(RangerDaoManagerBase daoManager) { - super(daoManager); - } - - public long getCountById(Long policyId) { - return getEntityManager() - .createNamedQuery("XXPolicy.countById", Long.class) - .setParameter("policyId", policyId) - .getSingleResult(); - } - - public XXPolicy findByNameAndServiceId(String polName, Long serviceId) { - return findByNameAndServiceIdAndZoneId(polName, serviceId, RangerSecurityZone.RANGER_UNZONED_SECURITY_ZONE_ID); - } - - public XXPolicy findByNameAndServiceIdAndZoneId(String polName, Long serviceId, Long zoneId) { - if (polName == null || serviceId == null) { - return null; - } - - XXPolicy ret; - - try { - ret = getEntityManager() - .createNamedQuery("XXPolicy.findByNameAndServiceIdAndZoneId", tClass) - .setParameter("polName", polName).setParameter("serviceId", serviceId).setParameter("zoneId", zoneId) - .getSingleResult(); - - } catch (NoResultException e) { - ret = null; - } - - return ret; - } - - public XXPolicy findByPolicyName(String polName) { - if (polName == null) { - return null; - } - try { - XXPolicy xPol = getEntityManager().createNamedQuery("XXPolicy.findByPolicyName", tClass) - .setParameter("polName", polName).getSingleResult(); - return xPol; - } catch (NoResultException e) { - return null; - } - } - - public List findByServiceId(Long serviceId) { - if (serviceId == null) { - return new ArrayList(); - } - try { - return getEntityManager() - .createNamedQuery("XXPolicy.findByServiceId", tClass) - .setParameter("serviceId", serviceId).getResultList(); - } catch (NoResultException e) { - return new ArrayList(); - } - } - - public List findPolicyIdsByServiceId(Long serviceId) { - List ret = new ArrayList(); - try { - ret = getEntityManager() - .createNamedQuery("XXPolicy.findPolicyIdsByServiceId", Long.class) - .setParameter("serviceId", serviceId).getResultList(); - } catch (Exception e) { - } - return ret; - } - - public Long getMaxIdOfXXPolicy() { - try { - return (Long) getEntityManager().createNamedQuery("XXPolicy.getMaxIdOfXXPolicy").getSingleResult(); - } catch (NoResultException e) { - return null; - } - } - - public List findByResourceSignatureByPolicyStatus(String serviceName, String policySignature, Boolean isPolicyEnabled) { - if (policySignature == null || serviceName == null || isPolicyEnabled == null) { - return new ArrayList(); - } - try { - return getEntityManager().createNamedQuery("XXPolicy.findByResourceSignatureByPolicyStatus", tClass) - .setParameter("resSignature", policySignature) - .setParameter("serviceName", serviceName) - .setParameter("isPolicyEnabled", isPolicyEnabled) - .getResultList(); - } catch (NoResultException e) { - return new ArrayList(); - } - } - - public List findByResourceSignature(String serviceName, String policySignature) { - if (policySignature == null || serviceName == null) { - return new ArrayList(); - } - try { - return getEntityManager().createNamedQuery("XXPolicy.findByResourceSignature", tClass) - .setParameter("resSignature", policySignature) - .setParameter("serviceName", serviceName) - .getResultList(); - } catch (NoResultException e) { - return new ArrayList(); - } - } - - public List findByServiceDefId(Long serviceDefId) { - if(serviceDefId == null) { - return new ArrayList(); - } - try { - return getEntityManager().createNamedQuery("XXPolicy.findByServiceDefId", tClass) - .setParameter("serviceDefId", serviceDefId).getResultList(); - } catch (NoResultException e) { - return new ArrayList(); - } - } - - public void updateSequence() { - Long maxId = getMaxIdOfXXPolicy(); - - if(maxId == null) { - return; - } - - updateSequence("X_POLICY_SEQ", maxId + 1); - } - public List findByUserId(Long userId) { - if(userId == null || userId.equals(Long.valueOf(0L))) { - return new ArrayList(); - } - try { - return getEntityManager() - .createNamedQuery("XXPolicy.findByUserId", tClass) - .setParameter("userId", userId).getResultList(); - } catch (NoResultException e) { - return new ArrayList(); - } - } - public List findByGroupId(Long groupId) { - if(groupId == null || groupId.equals(Long.valueOf(0L))) { - return new ArrayList(); - } - try { - return getEntityManager() - .createNamedQuery("XXPolicy.findByGroupId", tClass) - .setParameter("groupId", groupId).getResultList(); - } catch (NoResultException e) { - return new ArrayList(); - } - } - - public List findPolicyIdsByServiceNameAndZoneId(String serviceName, Long zoneId) { - List ret = new ArrayList(); - try { - ret = getEntityManager() - .createNamedQuery("XXPolicy.findPolicyIdsByServiceNameAndZoneId", Long.class) - .setParameter("serviceName", serviceName) - .setParameter("zoneId", zoneId) - .getResultList(); - } catch (Exception e) { - } - return ret; - } - - public List findByRoleId(Long roleId) { - List ret = ListUtils.EMPTY_LIST; - if (roleId != null) { - try { - ret = getEntityManager().createNamedQuery("XXPolicy.findByRoleId", tClass) - .setParameter("roleId", roleId) - .getResultList(); - } catch (NoResultException excp) { - } - } - return ret; - } - public List findServiceIdsByRoleId(Long roleId) { - List ret = ListUtils.EMPTY_LIST; - if (roleId != null) { - try { - ret = getEntityManager().createNamedQuery("XXPolicy.findServiceIdsByRoleId", Long.class) - .setParameter("roleId", roleId) - .getResultList(); - } catch (NoResultException excp) { - } - } - return ret; - } - - public long findRoleRefPolicyCount(String roleName, Long serviceId) { - long ret = -1; - try { - return getEntityManager() - .createNamedQuery("XXPolicy.findRoleRefPolicyCount", Long.class) - .setParameter("serviceId", serviceId) - .setParameter("roleName", roleName).getSingleResult(); - } catch (Exception e) { - } - return ret; - } - - public long getPoliciesCount(String serviceName) { - long ret = 0L; - try { - return getEntityManager() - .createNamedQuery("XXPolicy.getPoliciesCount", Long.class) - .setParameter("serviceName", serviceName).getSingleResult(); - } catch (Exception e) { - } - return ret; - } - - public XXPolicy findPolicy(String policyName, String serviceName, String zoneName) { - if (policyName == null || serviceName == null) { - return null; - } - - try { - if (zoneName == null) { - return getEntityManager().createNamedQuery("XXPolicy.findPolicyByPolicyNameAndServiceName", tClass) - .setParameter("policyName", policyName).setParameter("serviceName", serviceName) - .setParameter("zoneId", RangerSecurityZone.RANGER_UNZONED_SECURITY_ZONE_ID) - .getSingleResult(); - } else { - return getEntityManager() - .createNamedQuery("XXPolicy.findPolicyByPolicyNameAndServiceNameAndZoneName", tClass) - .setParameter("policyName", policyName).setParameter("serviceName", serviceName) - .setParameter("zoneName", zoneName).getSingleResult(); - } - } catch (NoResultException e) { - return null; - } - - } - - public List getAllByPolicyItem() { - List ret = ListUtils.EMPTY_LIST; - try { - ret = getEntityManager().createNamedQuery("XXPolicy.getAllByPolicyItem", tClass) - .getResultList(); - } catch (NoResultException excp) { - } - return ret; - } - - public XXPolicy findPolicyByGUIDAndServiceNameAndZoneName(String guid, String serviceName, String zoneName) { - if (guid == null) { - return null; - } - - try { - if (StringUtils.isNotBlank(serviceName)) { - if (StringUtils.isNotBlank(zoneName)) { - return getEntityManager() - .createNamedQuery("XXPolicy.findPolicyByPolicyGUIDAndServiceNameAndZoneName", tClass) - .setParameter("guid", guid) - .setParameter("serviceName", serviceName) - .setParameter("zoneName", zoneName) - .getSingleResult(); - } else { - return getEntityManager().createNamedQuery("XXPolicy.findPolicyByPolicyGUIDAndServiceName", tClass) - .setParameter("guid", guid) - .setParameter("serviceName", serviceName) - .setParameter("zoneId", RangerSecurityZone.RANGER_UNZONED_SECURITY_ZONE_ID) - .getSingleResult(); - } - } else { - if (StringUtils.isNotBlank(zoneName)) { - return getEntityManager() - .createNamedQuery("XXPolicy.findPolicyByPolicyGUIDAndZoneName", tClass) - .setParameter("guid", guid) - .setParameter("zoneName", zoneName) - .getSingleResult(); - } else { - return getEntityManager() - .createNamedQuery("XXPolicy.findPolicyByPolicyGUID", tClass) - .setParameter("guid", guid) - .setParameter("zoneId", RangerSecurityZone.RANGER_UNZONED_SECURITY_ZONE_ID) - .getSingleResult(); - } - } - } catch (NoResultException e) { - return null; - } - } - - public List findByPolicyStatus(Boolean isPolicyEnabled) { - if (isPolicyEnabled == null) { - return new ArrayList(); - } - try { - return getEntityManager().createNamedQuery("XXPolicy.findByPolicyStatus", tClass) - .setParameter("isPolicyEnabled", isPolicyEnabled) - .getResultList(); - } catch (NoResultException e) { - return new ArrayList(); - } - } - - public List findDuplicateGUIDByServiceIdAndZoneId(Long serviceId, Long zoneId) { - List ret = ListUtils.EMPTY_LIST; - if(serviceId == null || zoneId == null) { - return ret; - } - try { - ret = getEntityManager().createNamedQuery("XXPolicy.findDuplicateGUIDByServiceIdAndZoneId", String.class) - .setParameter("serviceId", serviceId) - .setParameter("zoneId", zoneId) - .getResultList(); - - } catch (Exception e) { - } - return ret; - } - - public List findPolicyByGUIDAndServiceIdAndZoneId(String guid, Long serviceId, Long zoneId) { - List ret = ListUtils.EMPTY_LIST; - if (guid == null || serviceId == null || zoneId == null) { - return ret; - } - try { - ret = getEntityManager().createNamedQuery("XXPolicy.findPolicyByGUIDAndServiceIdAndZoneId", tClass) - .setParameter("guid", guid) - .setParameter("serviceId", serviceId) - .setParameter("zoneId", zoneId) - .getResultList(); - - } catch (NoResultException excp) { - } - return ret; - } - - public Map findDuplicatePoliciesByServiceAndResourceSignature() { - Map policies = new HashMap(); - try { - List rows = (List) getEntityManager().createNamedQuery("XXPolicy.findDuplicatePoliciesByServiceAndResourceSignature").getResultList(); - if (rows != null) { - for (Object[] row : rows) { - policies.put((String) row[0], (Long) row[1]); - } - } - } catch (NoResultException e) { - return null; - } catch (Exception ex) { - } - return policies; - } - - public List findByServiceIdAndResourceSignature(Long serviceId, String policySignature) { - if (policySignature == null || serviceId == null) { - return new ArrayList(); - } - try { - return getEntityManager().createNamedQuery("XXPolicy.findByServiceIdAndResourceSignature", tClass) - .setParameter("serviceId", serviceId) - .setParameter("resSignature", policySignature) - .getResultList(); - } catch (NoResultException e) { - return new ArrayList(); - } - } - - public List findByZoneId(Long zoneId) { - if (zoneId == null) { - return new ArrayList(); - } - try { - return getEntityManager() - .createNamedQuery("XXPolicy.findByZoneId", tClass) - .setParameter("zoneId", zoneId).getResultList(); - } catch (NoResultException e) { - return new ArrayList(); - } - } - - public List findByServiceType(String serviceType) { - List ret = Collections.emptyList(); - - if (serviceType != null && !serviceType.isEmpty()) { - try { - ret = getEntityManager().createNamedQuery("XXPolicy.findByServiceType", tClass) - .setParameter("serviceType", serviceType) - .getResultList(); - } catch (NoResultException e) { - // ignore - } - } - - return ret; - } - - public XXPolicy getProjectPolicy(Long projectId, Long policyId) { - XXPolicy ret = null; - - if (projectId != null && policyId != null) { - try { - ret = getEntityManager().createNamedQuery("XXPolicy.getProjectPolicy", tClass) - .setParameter("projectId", projectId) - .setParameter("policyId", policyId) - .getSingleResult(); - } catch (NoResultException e) { - // ignore - } - } - - return ret; - } - - public List getMetaAttributesForPolicies(List policyIds) { - if (policyIds == null || policyIds.isEmpty()) { - return Collections.emptyList(); - } - - Query query = getEntityManager().createNamedQuery("XXPolicy.getMetaAttributesForPolicies", tClass); - query.setParameter("policyIds", policyIds); - - return query.getResultList(); - } - - public List getProjectPolicies(Long projectId) { - List ret = Collections.emptyList(); - - if (projectId != null) { - try { - ret = getEntityManager().createNamedQuery("XXPolicy.getProjectPolicies", tClass) - .setParameter("projectId", projectId) - .getResultList(); - } catch (NoResultException e) { - // ignore - } - } - - return ret; - } + /** + * Default Constructor + */ + public XXPolicyDao(RangerDaoManagerBase daoManager) { + super(daoManager); + } + + public long getCountById(Long policyId) { + return getEntityManager() + .createNamedQuery("XXPolicy.countById", Long.class) + .setParameter("policyId", policyId) + .getSingleResult(); + } + + public XXPolicy findByNameAndServiceId(String polName, Long serviceId) { + return findByNameAndServiceIdAndZoneId(polName, serviceId, RangerSecurityZone.RANGER_UNZONED_SECURITY_ZONE_ID); + } + + public XXPolicy findByNameAndServiceIdAndZoneId(String polName, Long serviceId, Long zoneId) { + if (polName == null || serviceId == null) { + return null; + } + + XXPolicy ret; + + try { + ret = getEntityManager() + .createNamedQuery("XXPolicy.findByNameAndServiceIdAndZoneId", tClass) + .setParameter("polName", polName).setParameter("serviceId", serviceId).setParameter("zoneId", zoneId) + .getSingleResult(); + } catch (NoResultException e) { + ret = null; + } + + return ret; + } + + public XXPolicy findByPolicyName(String polName) { + if (polName == null) { + return null; + } + + try { + return getEntityManager().createNamedQuery("XXPolicy.findByPolicyName", tClass) + .setParameter("polName", polName).getSingleResult(); + } catch (NoResultException e) { + return null; + } + } + + public List findByServiceId(Long serviceId) { + if (serviceId == null) { + return new ArrayList<>(); + } + + try { + return getEntityManager() + .createNamedQuery("XXPolicy.findByServiceId", tClass) + .setParameter("serviceId", serviceId).getResultList(); + } catch (NoResultException e) { + return new ArrayList<>(); + } + } + + public List findPolicyIdsByServiceId(Long serviceId) { + List ret; + + try { + ret = getEntityManager() + .createNamedQuery("XXPolicy.findPolicyIdsByServiceId", Long.class) + .setParameter("serviceId", serviceId).getResultList(); + } catch (Exception e) { + ret = new ArrayList<>(); + } + + return ret; + } + + public Long getMaxIdOfXXPolicy() { + try { + return (Long) getEntityManager().createNamedQuery("XXPolicy.getMaxIdOfXXPolicy").getSingleResult(); + } catch (NoResultException e) { + return null; + } + } + + public List findByResourceSignatureByPolicyStatus(String serviceName, String policySignature, Boolean isPolicyEnabled) { + if (policySignature == null || serviceName == null || isPolicyEnabled == null) { + return new ArrayList<>(); + } + + try { + return getEntityManager().createNamedQuery("XXPolicy.findByResourceSignatureByPolicyStatus", tClass) + .setParameter("resSignature", policySignature) + .setParameter("serviceName", serviceName) + .setParameter("isPolicyEnabled", isPolicyEnabled) + .getResultList(); + } catch (NoResultException e) { + return new ArrayList<>(); + } + } + + public List findByResourceSignature(String serviceName, String policySignature) { + if (policySignature == null || serviceName == null) { + return new ArrayList<>(); + } + + try { + return getEntityManager().createNamedQuery("XXPolicy.findByResourceSignature", tClass) + .setParameter("resSignature", policySignature) + .setParameter("serviceName", serviceName) + .getResultList(); + } catch (NoResultException e) { + return new ArrayList<>(); + } + } + + public List findByServiceDefId(Long serviceDefId) { + if (serviceDefId == null) { + return new ArrayList<>(); + } + + try { + return getEntityManager().createNamedQuery("XXPolicy.findByServiceDefId", tClass) + .setParameter("serviceDefId", serviceDefId).getResultList(); + } catch (NoResultException e) { + return new ArrayList<>(); + } + } + + public void updateSequence() { + Long maxId = getMaxIdOfXXPolicy(); + + if (maxId == null) { + return; + } + + updateSequence("X_POLICY_SEQ", maxId + 1); + } + + public List findByUserId(Long userId) { + if (userId == null || userId.equals(0L)) { + return new ArrayList<>(); + } + + try { + return getEntityManager() + .createNamedQuery("XXPolicy.findByUserId", tClass) + .setParameter("userId", userId).getResultList(); + } catch (NoResultException e) { + return new ArrayList<>(); + } + } + + public List findByGroupId(Long groupId) { + if (groupId == null || groupId.equals(0L)) { + return new ArrayList<>(); + } + + try { + return getEntityManager() + .createNamedQuery("XXPolicy.findByGroupId", tClass) + .setParameter("groupId", groupId).getResultList(); + } catch (NoResultException e) { + return new ArrayList<>(); + } + } + + public List findPolicyIdsByServiceNameAndZoneId(String serviceName, Long zoneId) { + List ret; + + try { + ret = getEntityManager() + .createNamedQuery("XXPolicy.findPolicyIdsByServiceNameAndZoneId", Long.class) + .setParameter("serviceName", serviceName) + .setParameter("zoneId", zoneId) + .getResultList(); + } catch (Exception e) { + ret = new ArrayList<>(); + } + + return ret; + } + + public List findByRoleId(Long roleId) { + List ret = Collections.emptyList(); + + if (roleId != null) { + try { + ret = getEntityManager().createNamedQuery("XXPolicy.findByRoleId", tClass) + .setParameter("roleId", roleId) + .getResultList(); + } catch (NoResultException excp) { + // ignore + } + } + + return ret; + } + + public List findServiceIdsByRoleId(Long roleId) { + List ret = Collections.emptyList(); + + if (roleId != null) { + try { + ret = getEntityManager().createNamedQuery("XXPolicy.findServiceIdsByRoleId", Long.class) + .setParameter("roleId", roleId) + .getResultList(); + } catch (NoResultException excp) { + // ignore + } + } + + return ret; + } + + public long findRoleRefPolicyCount(String roleName, Long serviceId) { + try { + return getEntityManager() + .createNamedQuery("XXPolicy.findRoleRefPolicyCount", Long.class) + .setParameter("serviceId", serviceId) + .setParameter("roleName", roleName).getSingleResult(); + } catch (Exception e) { + // ignore + } + + return -1; + } + + public long getPoliciesCount(String serviceName) { + try { + return getEntityManager() + .createNamedQuery("XXPolicy.getPoliciesCount", Long.class) + .setParameter("serviceName", serviceName).getSingleResult(); + } catch (Exception e) { + // ignore + } + + return 0L; + } + + public XXPolicy findPolicy(String policyName, String serviceName, String zoneName) { + if (policyName == null || serviceName == null) { + return null; + } + + try { + if (zoneName == null) { + return getEntityManager().createNamedQuery("XXPolicy.findPolicyByPolicyNameAndServiceName", tClass) + .setParameter("policyName", policyName).setParameter("serviceName", serviceName) + .setParameter("zoneId", RangerSecurityZone.RANGER_UNZONED_SECURITY_ZONE_ID) + .getSingleResult(); + } else { + return getEntityManager() + .createNamedQuery("XXPolicy.findPolicyByPolicyNameAndServiceNameAndZoneName", tClass) + .setParameter("policyName", policyName).setParameter("serviceName", serviceName) + .setParameter("zoneName", zoneName).getSingleResult(); + } + } catch (NoResultException e) { + return null; + } + } + + public List getAllByPolicyItem() { + List ret; + + try { + ret = getEntityManager().createNamedQuery("XXPolicy.getAllByPolicyItem", tClass) + .getResultList(); + } catch (NoResultException excp) { + ret = Collections.emptyList(); + } + + return ret; + } + + public XXPolicy findPolicyByGUIDAndServiceNameAndZoneName(String guid, String serviceName, String zoneName) { + if (guid == null) { + return null; + } + + try { + if (StringUtils.isNotBlank(serviceName)) { + if (StringUtils.isNotBlank(zoneName)) { + return getEntityManager() + .createNamedQuery("XXPolicy.findPolicyByPolicyGUIDAndServiceNameAndZoneName", tClass) + .setParameter("guid", guid) + .setParameter("serviceName", serviceName) + .setParameter("zoneName", zoneName) + .getSingleResult(); + } else { + return getEntityManager().createNamedQuery("XXPolicy.findPolicyByPolicyGUIDAndServiceName", tClass) + .setParameter("guid", guid) + .setParameter("serviceName", serviceName) + .setParameter("zoneId", RangerSecurityZone.RANGER_UNZONED_SECURITY_ZONE_ID) + .getSingleResult(); + } + } else { + if (StringUtils.isNotBlank(zoneName)) { + return getEntityManager() + .createNamedQuery("XXPolicy.findPolicyByPolicyGUIDAndZoneName", tClass) + .setParameter("guid", guid) + .setParameter("zoneName", zoneName) + .getSingleResult(); + } else { + return getEntityManager() + .createNamedQuery("XXPolicy.findPolicyByPolicyGUID", tClass) + .setParameter("guid", guid) + .setParameter("zoneId", RangerSecurityZone.RANGER_UNZONED_SECURITY_ZONE_ID) + .getSingleResult(); + } + } + } catch (NoResultException e) { + return null; + } + } + + public List findByPolicyStatus(Boolean isPolicyEnabled) { + if (isPolicyEnabled == null) { + return new ArrayList<>(); + } + + try { + return getEntityManager().createNamedQuery("XXPolicy.findByPolicyStatus", tClass) + .setParameter("isPolicyEnabled", isPolicyEnabled) + .getResultList(); + } catch (NoResultException e) { + return new ArrayList<>(); + } + } + + public List findDuplicateGUIDByServiceIdAndZoneId(Long serviceId, Long zoneId) { + List ret = Collections.emptyList(); + + if (serviceId == null || zoneId == null) { + return ret; + } + + try { + ret = getEntityManager().createNamedQuery("XXPolicy.findDuplicateGUIDByServiceIdAndZoneId", String.class) + .setParameter("serviceId", serviceId) + .setParameter("zoneId", zoneId) + .getResultList(); + } catch (Exception e) { + // ignore + } + + return ret; + } + + public List findPolicyByGUIDAndServiceIdAndZoneId(String guid, Long serviceId, Long zoneId) { + List ret = Collections.emptyList(); + + if (guid == null || serviceId == null || zoneId == null) { + return ret; + } + + try { + ret = getEntityManager().createNamedQuery("XXPolicy.findPolicyByGUIDAndServiceIdAndZoneId", tClass) + .setParameter("guid", guid) + .setParameter("serviceId", serviceId) + .setParameter("zoneId", zoneId) + .getResultList(); + } catch (NoResultException excp) { + // ignore + } + + return ret; + } + + public Map findDuplicatePoliciesByServiceAndResourceSignature() { + Map policies = new HashMap<>(); + + try { + List rows = getEntityManager().createNamedQuery("XXPolicy.findDuplicatePoliciesByServiceAndResourceSignature", Object[].class).getResultList(); + + if (rows != null) { + for (Object[] row : rows) { + policies.put((String) row[0], (Long) row[1]); + } + } + } catch (NoResultException e) { + return null; + } catch (Exception ex) { + // ignore + } + + return policies; + } + + public List findByServiceIdAndResourceSignature(Long serviceId, String policySignature) { + if (policySignature == null || serviceId == null) { + return new ArrayList<>(); + } + + try { + return getEntityManager().createNamedQuery("XXPolicy.findByServiceIdAndResourceSignature", tClass) + .setParameter("serviceId", serviceId) + .setParameter("resSignature", policySignature) + .getResultList(); + } catch (NoResultException e) { + return new ArrayList<>(); + } + } + + public List findByZoneId(Long zoneId) { + if (zoneId == null) { + return new ArrayList<>(); + } + + try { + return getEntityManager() + .createNamedQuery("XXPolicy.findByZoneId", tClass) + .setParameter("zoneId", zoneId).getResultList(); + } catch (NoResultException e) { + return new ArrayList<>(); + } + } + + public List findByServiceType(String serviceType) { + List ret = Collections.emptyList(); + + if (serviceType != null && !serviceType.isEmpty()) { + try { + ret = getEntityManager().createNamedQuery("XXPolicy.findByServiceType", tClass) + .setParameter("serviceType", serviceType) + .getResultList(); + } catch (NoResultException e) { + // ignore + } + } + + return ret; + } + + public XXPolicy getProjectPolicy(Long projectId, Long policyId) { + XXPolicy ret = null; + + if (projectId != null && policyId != null) { + try { + ret = getEntityManager().createNamedQuery("XXPolicy.getProjectPolicy", tClass) + .setParameter("projectId", projectId) + .setParameter("policyId", policyId) + .getSingleResult(); + } catch (NoResultException e) { + // ignore + } + } + + return ret; + } + + public List getMetaAttributesForPolicies(List policyIds) { + if (policyIds == null || policyIds.isEmpty()) { + return Collections.emptyList(); + } + + return getEntityManager().createNamedQuery("XXPolicy.getMetaAttributesForPolicies", Object[].class).setParameter("policyIds", policyIds).getResultList(); + } + + public List getProjectPolicies(Long projectId) { + List ret = Collections.emptyList(); + + if (projectId != null) { + try { + ret = getEntityManager().createNamedQuery("XXPolicy.getProjectPolicies", tClass) + .setParameter("projectId", projectId) + .getResultList(); + } catch (NoResultException e) { + // ignore + } + } + + return ret; + } } 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 index 1d13feb027..be253f0b9e 100644 --- a/security-admin/src/main/java/org/apache/ranger/db/XXPolicyExportAuditDao.java +++ b/security-admin/src/main/java/org/apache/ranger/db/XXPolicyExportAuditDao.java @@ -17,7 +17,7 @@ * under the License. */ - package org.apache.ranger.db; +package org.apache.ranger.db; import org.apache.ranger.common.db.BaseDao; import org.apache.ranger.entity.XXPolicyExportAudit; @@ -32,8 +32,8 @@ public class XXPolicyExportAuditDao extends BaseDao { private static final Logger logger = LoggerFactory.getLogger(XXPolicyExportAuditDao.class); - public XXPolicyExportAuditDao( RangerDaoManagerBase daoManager ) { - super(daoManager); + public XXPolicyExportAuditDao(RangerDaoManagerBase daoManager) { + super(daoManager); } public long deleteOlderThan(int olderThanInDays) { @@ -48,4 +48,3 @@ public long deleteOlderThan(int olderThanInDays) { return ret; } } - diff --git a/security-admin/src/main/java/org/apache/ranger/db/XXPolicyItemAccessDao.java b/security-admin/src/main/java/org/apache/ranger/db/XXPolicyItemAccessDao.java index e396d2da66..41f5bada98 100644 --- a/security-admin/src/main/java/org/apache/ranger/db/XXPolicyItemAccessDao.java +++ b/security-admin/src/main/java/org/apache/ranger/db/XXPolicyItemAccessDao.java @@ -17,54 +17,55 @@ package org.apache.ranger.db; -import java.util.ArrayList; -import java.util.List; - -import javax.persistence.NoResultException; - import org.apache.ranger.common.db.BaseDao; import org.apache.ranger.entity.XXPolicyItemAccess; import org.springframework.stereotype.Service; +import javax.persistence.NoResultException; + +import java.util.ArrayList; +import java.util.List; + @Service public class XXPolicyItemAccessDao extends BaseDao { + public XXPolicyItemAccessDao(RangerDaoManagerBase daoManager) { + super(daoManager); + } + + public List findByPolicyId(Long policyId) { + if (policyId == null) { + return new ArrayList<>(); + } - public XXPolicyItemAccessDao(RangerDaoManagerBase daoManager) { - super(daoManager); - } + try { + return getEntityManager() + .createNamedQuery("XXPolicyItemAccess.findByPolicyId", tClass) + .setParameter("policyId", policyId).getResultList(); + } catch (NoResultException e) { + return new ArrayList<>(); + } + } - public List findByPolicyId(Long policyId) { - if(policyId == null) { - return new ArrayList(); - } - try { - return getEntityManager() - .createNamedQuery("XXPolicyItemAccess.findByPolicyId", tClass) - .setParameter("policyId", policyId).getResultList(); - } catch (NoResultException e) { - return new ArrayList(); - } - } + public List findByServiceId(Long serviceId) { + if (serviceId == null) { + return new ArrayList<>(); + } - public List findByServiceId(Long serviceId) { - if(serviceId == null) { - return new ArrayList(); - } - try { - return getEntityManager() - .createNamedQuery("XXPolicyItemAccess.findByServiceId", tClass) - .setParameter("serviceId", serviceId).getResultList(); - } catch (NoResultException e) { - return new ArrayList(); - } - } + try { + return getEntityManager() + .createNamedQuery("XXPolicyItemAccess.findByServiceId", tClass) + .setParameter("serviceId", serviceId).getResultList(); + } catch (NoResultException e) { + return new ArrayList<>(); + } + } - public void deleteByPolicyId(Long policyId) { - if(policyId == null) { - return; - } - getEntityManager() - .createNamedQuery("XXPolicyItemAccess.deleteByPolicyId", tClass) - .setParameter("policyId", policyId).executeUpdate(); - } + public void deleteByPolicyId(Long policyId) { + if (policyId == null) { + return; + } + getEntityManager() + .createNamedQuery("XXPolicyItemAccess.deleteByPolicyId", tClass) + .setParameter("policyId", policyId).executeUpdate(); + } } diff --git a/security-admin/src/main/java/org/apache/ranger/db/XXPolicyItemConditionDao.java b/security-admin/src/main/java/org/apache/ranger/db/XXPolicyItemConditionDao.java index bcc30b3ec9..1e59e5b36f 100644 --- a/security-admin/src/main/java/org/apache/ranger/db/XXPolicyItemConditionDao.java +++ b/security-admin/src/main/java/org/apache/ranger/db/XXPolicyItemConditionDao.java @@ -17,54 +17,55 @@ package org.apache.ranger.db; -import java.util.ArrayList; -import java.util.List; - -import javax.persistence.NoResultException; - import org.apache.ranger.common.db.BaseDao; import org.apache.ranger.entity.XXPolicyItemCondition; import org.springframework.stereotype.Service; +import javax.persistence.NoResultException; + +import java.util.ArrayList; +import java.util.List; + @Service public class XXPolicyItemConditionDao extends BaseDao { + public XXPolicyItemConditionDao(RangerDaoManagerBase daoManager) { + super(daoManager); + } + + public List findByPolicyId(Long policyId) { + if (policyId == null) { + return new ArrayList<>(); + } - public XXPolicyItemConditionDao(RangerDaoManagerBase daoManager) { - super(daoManager); - } + try { + return getEntityManager() + .createNamedQuery("XXPolicyItemCondition.findByPolicyId", tClass) + .setParameter("policyId", policyId).getResultList(); + } catch (NoResultException e) { + return new ArrayList<>(); + } + } - public List findByPolicyId(Long policyId) { - if(policyId == null) { - return new ArrayList(); - } - try { - return getEntityManager() - .createNamedQuery("XXPolicyItemCondition.findByPolicyId", tClass) - .setParameter("policyId", policyId).getResultList(); - } catch (NoResultException e) { - return new ArrayList(); - } - } + public List findByServiceId(Long serviceId) { + if (serviceId == null) { + return new ArrayList<>(); + } - public List findByServiceId(Long serviceId) { - if(serviceId == null) { - return new ArrayList(); - } - try { - return getEntityManager() - .createNamedQuery("XXPolicyItemCondition.findByServiceId", tClass) - .setParameter("serviceId", serviceId).getResultList(); - } catch (NoResultException e) { - return new ArrayList(); - } - } + try { + return getEntityManager() + .createNamedQuery("XXPolicyItemCondition.findByServiceId", tClass) + .setParameter("serviceId", serviceId).getResultList(); + } catch (NoResultException e) { + return new ArrayList<>(); + } + } - public void deleteByPolicyId(Long policyId) { - if(policyId == null) { - return; - } - getEntityManager() - .createNamedQuery("XXPolicyItemCondition.deleteByPolicyId", tClass) - .setParameter("policyId", policyId).executeUpdate(); - } + public void deleteByPolicyId(Long policyId) { + if (policyId == null) { + return; + } + getEntityManager() + .createNamedQuery("XXPolicyItemCondition.deleteByPolicyId", tClass) + .setParameter("policyId", policyId).executeUpdate(); + } } diff --git a/security-admin/src/main/java/org/apache/ranger/db/XXPolicyItemDao.java b/security-admin/src/main/java/org/apache/ranger/db/XXPolicyItemDao.java index 4c981be7a0..223e6ebc4f 100644 --- a/security-admin/src/main/java/org/apache/ranger/db/XXPolicyItemDao.java +++ b/security-admin/src/main/java/org/apache/ranger/db/XXPolicyItemDao.java @@ -17,67 +17,75 @@ package org.apache.ranger.db; -import java.util.ArrayList; -import java.util.List; - -import javax.persistence.NoResultException; - import org.apache.ranger.common.db.BaseDao; import org.apache.ranger.entity.XXPolicyItem; import org.springframework.stereotype.Service; +import javax.persistence.NoResultException; + +import java.util.ArrayList; +import java.util.List; + /** + * */ @Service public class XXPolicyItemDao extends BaseDao { - /** - * Default Constructor - */ - public XXPolicyItemDao(RangerDaoManagerBase daoManager) { - super(daoManager); - } - - public List findByPolicyId(Long policyId) { - if (policyId == null) { - return new ArrayList(); - } - try { - List returnList = getEntityManager() - .createNamedQuery("XXPolicyItem.findByPolicyId", tClass) - .setParameter("policyId", policyId).getResultList(); - if (returnList == null) { - return new ArrayList(); - } - return returnList; - } catch (NoResultException e) { - return new ArrayList(); - } - } - - public List findByServiceId(Long serviceId) { - if (serviceId == null) { - return new ArrayList(); - } - try { - List returnList = getEntityManager() - .createNamedQuery("XXPolicyItem.findByServiceId", tClass) - .setParameter("serviceId", serviceId).getResultList(); - if (returnList == null) { - return new ArrayList(); - } - return returnList; - } catch (NoResultException e) { - return new ArrayList(); - } - } - - public void deleteByPolicyId(Long policyId) { - if(policyId == null) { - return; - } - getEntityManager() - .createNamedQuery("XXPolicyItem.deleteByPolicyId", tClass) - .setParameter("policyId", policyId).executeUpdate(); - } -} \ No newline at end of file + /** + * Default Constructor + */ + public XXPolicyItemDao(RangerDaoManagerBase daoManager) { + super(daoManager); + } + + public List findByPolicyId(Long policyId) { + if (policyId == null) { + return new ArrayList<>(); + } + + try { + List returnList = getEntityManager() + .createNamedQuery("XXPolicyItem.findByPolicyId", tClass) + .setParameter("policyId", policyId).getResultList(); + + if (returnList == null) { + return new ArrayList<>(); + } + + return returnList; + } catch (NoResultException e) { + return new ArrayList<>(); + } + } + + public List findByServiceId(Long serviceId) { + if (serviceId == null) { + return new ArrayList<>(); + } + + try { + List returnList = getEntityManager() + .createNamedQuery("XXPolicyItem.findByServiceId", tClass) + .setParameter("serviceId", serviceId).getResultList(); + + if (returnList == null) { + return new ArrayList<>(); + } + + return returnList; + } catch (NoResultException e) { + return new ArrayList<>(); + } + } + + public void deleteByPolicyId(Long policyId) { + if (policyId == null) { + return; + } + + getEntityManager() + .createNamedQuery("XXPolicyItem.deleteByPolicyId", tClass) + .setParameter("policyId", policyId).executeUpdate(); + } +} diff --git a/security-admin/src/main/java/org/apache/ranger/db/XXPolicyItemDataMaskInfoDao.java b/security-admin/src/main/java/org/apache/ranger/db/XXPolicyItemDataMaskInfoDao.java index fe6d9ea37a..0f147509c4 100644 --- a/security-admin/src/main/java/org/apache/ranger/db/XXPolicyItemDataMaskInfoDao.java +++ b/security-admin/src/main/java/org/apache/ranger/db/XXPolicyItemDataMaskInfoDao.java @@ -17,54 +17,56 @@ package org.apache.ranger.db; -import java.util.ArrayList; -import java.util.List; - -import javax.persistence.NoResultException; - import org.apache.ranger.common.db.BaseDao; import org.apache.ranger.entity.XXPolicyItemDataMaskInfo; import org.springframework.stereotype.Service; +import javax.persistence.NoResultException; + +import java.util.ArrayList; +import java.util.List; + @Service public class XXPolicyItemDataMaskInfoDao extends BaseDao { + public XXPolicyItemDataMaskInfoDao(RangerDaoManagerBase daoManager) { + super(daoManager); + } + + public List findByPolicyId(Long policyId) { + if (policyId == null) { + return new ArrayList<>(); + } + + try { + return getEntityManager() + .createNamedQuery("XXPolicyItemDataMaskInfo.findByPolicyId", tClass) + .setParameter("policyId", policyId).getResultList(); + } catch (NoResultException e) { + return new ArrayList<>(); + } + } - public XXPolicyItemDataMaskInfoDao(RangerDaoManagerBase daoManager) { - super(daoManager); - } + public List findByServiceId(Long serviceId) { + if (serviceId == null) { + return new ArrayList<>(); + } - public List findByPolicyId(Long policyId) { - if(policyId == null) { - return new ArrayList(); - } - try { - return getEntityManager() - .createNamedQuery("XXPolicyItemDataMaskInfo.findByPolicyId", tClass) - .setParameter("policyId", policyId).getResultList(); - } catch (NoResultException e) { - return new ArrayList(); - } - } + try { + return getEntityManager() + .createNamedQuery("XXPolicyItemDataMaskInfo.findByServiceId", tClass) + .setParameter("serviceId", serviceId).getResultList(); + } catch (NoResultException e) { + return new ArrayList<>(); + } + } - public List findByServiceId(Long serviceId) { - if(serviceId == null) { - return new ArrayList(); - } - try { - return getEntityManager() - .createNamedQuery("XXPolicyItemDataMaskInfo.findByServiceId", tClass) - .setParameter("serviceId", serviceId).getResultList(); - } catch (NoResultException e) { - return new ArrayList(); - } - } + public void deleteByPolicyId(Long policyId) { + if (policyId == null) { + return; + } - public void deleteByPolicyId(Long policyId) { - if(policyId == null) { - return; - } - getEntityManager() - .createNamedQuery("XXPolicyItemDataMaskInfo.deleteByPolicyId", tClass) - .setParameter("policyId", policyId).executeUpdate(); - } + getEntityManager() + .createNamedQuery("XXPolicyItemDataMaskInfo.deleteByPolicyId", tClass) + .setParameter("policyId", policyId).executeUpdate(); + } } diff --git a/security-admin/src/main/java/org/apache/ranger/db/XXPolicyItemGroupPermDao.java b/security-admin/src/main/java/org/apache/ranger/db/XXPolicyItemGroupPermDao.java index faa0a8c60a..68d776a445 100644 --- a/security-admin/src/main/java/org/apache/ranger/db/XXPolicyItemGroupPermDao.java +++ b/security-admin/src/main/java/org/apache/ranger/db/XXPolicyItemGroupPermDao.java @@ -17,54 +17,56 @@ package org.apache.ranger.db; -import java.util.ArrayList; -import java.util.List; - -import javax.persistence.NoResultException; - import org.apache.ranger.common.db.BaseDao; import org.apache.ranger.entity.XXPolicyItemGroupPerm; import org.springframework.stereotype.Service; +import javax.persistence.NoResultException; + +import java.util.ArrayList; +import java.util.List; + @Service public class XXPolicyItemGroupPermDao extends BaseDao { + public XXPolicyItemGroupPermDao(RangerDaoManagerBase daoManager) { + super(daoManager); + } + + public List findByPolicyId(Long policyId) { + if (policyId == null) { + return new ArrayList<>(); + } + + try { + return getEntityManager() + .createNamedQuery("XXPolicyItemGroupPerm.findByPolicyId", tClass) + .setParameter("policyId", policyId).getResultList(); + } catch (NoResultException e) { + return new ArrayList<>(); + } + } - public XXPolicyItemGroupPermDao(RangerDaoManagerBase daoManager) { - super(daoManager); - } + public List findByServiceId(Long serviceId) { + if (serviceId == null) { + return new ArrayList<>(); + } - public List findByPolicyId(Long policyId) { - if(policyId == null) { - return new ArrayList(); - } - try { - return getEntityManager() - .createNamedQuery("XXPolicyItemGroupPerm.findByPolicyId", tClass) - .setParameter("policyId", policyId).getResultList(); - } catch (NoResultException e) { - return new ArrayList(); - } - } + try { + return getEntityManager() + .createNamedQuery("XXPolicyItemGroupPerm.findByServiceId", tClass) + .setParameter("serviceId", serviceId).getResultList(); + } catch (NoResultException e) { + return new ArrayList<>(); + } + } - public List findByServiceId(Long serviceId) { - if(serviceId == null) { - return new ArrayList(); - } - try { - return getEntityManager() - .createNamedQuery("XXPolicyItemGroupPerm.findByServiceId", tClass) - .setParameter("serviceId", serviceId).getResultList(); - } catch (NoResultException e) { - return new ArrayList(); - } - } + public void deleteByPolicyId(Long policyId) { + if (policyId == null) { + return; + } - public void deleteByPolicyId(Long policyId) { - if(policyId == null) { - return; - } - getEntityManager() - .createNamedQuery("XXPolicyItemGroupPerm.deleteByPolicyId", tClass) - .setParameter("policyId", policyId).executeUpdate(); - } + getEntityManager() + .createNamedQuery("XXPolicyItemGroupPerm.deleteByPolicyId", tClass) + .setParameter("policyId", policyId).executeUpdate(); + } } diff --git a/security-admin/src/main/java/org/apache/ranger/db/XXPolicyItemRowFilterInfoDao.java b/security-admin/src/main/java/org/apache/ranger/db/XXPolicyItemRowFilterInfoDao.java index d596c15582..7961f835ab 100644 --- a/security-admin/src/main/java/org/apache/ranger/db/XXPolicyItemRowFilterInfoDao.java +++ b/security-admin/src/main/java/org/apache/ranger/db/XXPolicyItemRowFilterInfoDao.java @@ -22,48 +22,51 @@ import org.springframework.stereotype.Service; import javax.persistence.NoResultException; + import java.util.ArrayList; import java.util.List; @Service public class XXPolicyItemRowFilterInfoDao extends BaseDao { + public XXPolicyItemRowFilterInfoDao(RangerDaoManagerBase daoManager) { + super(daoManager); + } + + public List findByPolicyId(Long policyId) { + if (policyId == null) { + return new ArrayList<>(); + } + + try { + return getEntityManager() + .createNamedQuery("XXPolicyItemRowFilterInfo.findByPolicyId", tClass) + .setParameter("policyId", policyId).getResultList(); + } catch (NoResultException e) { + return new ArrayList<>(); + } + } - public XXPolicyItemRowFilterInfoDao(RangerDaoManagerBase daoManager) { - super(daoManager); - } + public List findByServiceId(Long serviceId) { + if (serviceId == null) { + return new ArrayList<>(); + } - public List findByPolicyId(Long policyId) { - if(policyId == null) { - return new ArrayList(); - } - try { - return getEntityManager() - .createNamedQuery("XXPolicyItemRowFilterInfo.findByPolicyId", tClass) - .setParameter("policyId", policyId).getResultList(); - } catch (NoResultException e) { - return new ArrayList(); - } - } + try { + return getEntityManager() + .createNamedQuery("XXPolicyItemRowFilterInfo.findByServiceId", tClass) + .setParameter("serviceId", serviceId).getResultList(); + } catch (NoResultException e) { + return new ArrayList<>(); + } + } - public List findByServiceId(Long serviceId) { - if(serviceId == null) { - return new ArrayList(); - } - try { - return getEntityManager() - .createNamedQuery("XXPolicyItemRowFilterInfo.findByServiceId", tClass) - .setParameter("serviceId", serviceId).getResultList(); - } catch (NoResultException e) { - return new ArrayList(); - } - } + public void deleteByPolicyId(Long policyId) { + if (policyId == null) { + return; + } - public void deleteByPolicyId(Long policyId) { - if(policyId == null) { - return; - } - getEntityManager() - .createNamedQuery("XXPolicyItemRowFilterInfo.deleteByPolicyId", tClass) - .setParameter("policyId", policyId).executeUpdate(); - } + getEntityManager() + .createNamedQuery("XXPolicyItemRowFilterInfo.deleteByPolicyId", tClass) + .setParameter("policyId", policyId).executeUpdate(); + } } diff --git a/security-admin/src/main/java/org/apache/ranger/db/XXPolicyItemUserPermDao.java b/security-admin/src/main/java/org/apache/ranger/db/XXPolicyItemUserPermDao.java index 96d1e5e43e..50a6c1fc91 100644 --- a/security-admin/src/main/java/org/apache/ranger/db/XXPolicyItemUserPermDao.java +++ b/security-admin/src/main/java/org/apache/ranger/db/XXPolicyItemUserPermDao.java @@ -17,54 +17,56 @@ package org.apache.ranger.db; -import java.util.ArrayList; -import java.util.List; - -import javax.persistence.NoResultException; - import org.apache.ranger.common.db.BaseDao; import org.apache.ranger.entity.XXPolicyItemUserPerm; import org.springframework.stereotype.Service; +import javax.persistence.NoResultException; + +import java.util.ArrayList; +import java.util.List; + @Service public class XXPolicyItemUserPermDao extends BaseDao { + public XXPolicyItemUserPermDao(RangerDaoManagerBase daoManager) { + super(daoManager); + } + + public List findByPolicyId(Long policyId) { + if (policyId == null) { + return new ArrayList<>(); + } + + try { + return getEntityManager() + .createNamedQuery("XXPolicyItemUserPerm.findByPolicyId", tClass) + .setParameter("policyId", policyId).getResultList(); + } catch (NoResultException e) { + return new ArrayList<>(); + } + } - public XXPolicyItemUserPermDao(RangerDaoManagerBase daoManager) { - super(daoManager); - } + public List findByServiceId(Long serviceId) { + if (serviceId == null) { + return new ArrayList<>(); + } - public List findByPolicyId(Long policyId) { - if(policyId == null) { - return new ArrayList(); - } - try { - return getEntityManager() - .createNamedQuery("XXPolicyItemUserPerm.findByPolicyId", tClass) - .setParameter("policyId", policyId).getResultList(); - } catch (NoResultException e) { - return new ArrayList(); - } - } + try { + return getEntityManager() + .createNamedQuery("XXPolicyItemUserPerm.findByServiceId", tClass) + .setParameter("serviceId", serviceId).getResultList(); + } catch (NoResultException e) { + return new ArrayList<>(); + } + } - public List findByServiceId(Long serviceId) { - if(serviceId == null) { - return new ArrayList(); - } - try { - return getEntityManager() - .createNamedQuery("XXPolicyItemUserPerm.findByServiceId", tClass) - .setParameter("serviceId", serviceId).getResultList(); - } catch (NoResultException e) { - return new ArrayList(); - } - } + public void deleteByPolicyId(Long policyId) { + if (policyId == null) { + return; + } - public void deleteByPolicyId(Long policyId) { - if(policyId == null) { - return; - } - getEntityManager() - .createNamedQuery("XXPolicyItemUserPerm.deleteByPolicyId", tClass) - .setParameter("policyId", policyId).executeUpdate(); - } + getEntityManager() + .createNamedQuery("XXPolicyItemUserPerm.deleteByPolicyId", tClass) + .setParameter("policyId", policyId).executeUpdate(); + } } diff --git a/security-admin/src/main/java/org/apache/ranger/db/XXPolicyLabelDao.java b/security-admin/src/main/java/org/apache/ranger/db/XXPolicyLabelDao.java index 9a8f198e43..a4aa455135 100644 --- a/security-admin/src/main/java/org/apache/ranger/db/XXPolicyLabelDao.java +++ b/security-admin/src/main/java/org/apache/ranger/db/XXPolicyLabelDao.java @@ -17,90 +17,92 @@ package org.apache.ranger.db; -import java.util.ArrayList; -import java.util.List; - -import javax.persistence.NoResultException; - import org.apache.ranger.common.db.BaseDao; import org.apache.ranger.entity.XXPolicyLabel; import org.springframework.stereotype.Service; +import javax.persistence.NoResultException; + +import java.util.ArrayList; +import java.util.List; + @Service public class XXPolicyLabelDao extends BaseDao { + public XXPolicyLabelDao(RangerDaoManagerBase daoMgr) { + super(daoMgr); + } - public XXPolicyLabelDao(RangerDaoManagerBase daoMgr) { - super(daoMgr); + public List getAllPolicyLabels() { + try { + return getEntityManager().createNamedQuery("XXPolicyLabel.getAllPolicyLabels", tClass) + .getResultList(); + } catch (NoResultException e) { + return new ArrayList<>(); } + } - public List getAllPolicyLabels() { - try { - return getEntityManager().createNamedQuery("XXPolicyLabel.getAllPolicyLabels", tClass) - .getResultList(); - } catch (NoResultException e) { - return new ArrayList(); - } + public XXPolicyLabel findByName(String policyLabel) { + if (policyLabel == null) { + return null; } - public XXPolicyLabel findByName(String policyLabel) { - if (policyLabel == null) { - return null; - } - try { - return getEntityManager().createNamedQuery("XXPolicyLabel.findByName", tClass) - .setParameter("policyLabel", policyLabel).getSingleResult(); - } catch (NoResultException e) { - return null; - } + try { + return getEntityManager().createNamedQuery("XXPolicyLabel.findByName", tClass) + .setParameter("policyLabel", policyLabel).getSingleResult(); + } catch (NoResultException e) { + return null; } + } - public List getByName(String policyLabel) { - if (policyLabel == null) { - return null; - } - try { - return getEntityManager().createNamedQuery("XXPolicyLabel.findByName", tClass) - .setParameter("policyLabel", policyLabel).getResultList(); - } catch (NoResultException e) { - return null; - } + public List getByName(String policyLabel) { + if (policyLabel == null) { + return null; + } + + try { + return getEntityManager().createNamedQuery("XXPolicyLabel.findByName", tClass) + .setParameter("policyLabel", policyLabel).getResultList(); + } catch (NoResultException e) { + return null; + } + } + + public XXPolicyLabel findByPolicyLabelId(Long policyLabelId) { + if (policyLabelId == null) { + return null; + } + + try { + return getEntityManager().createNamedQuery("XXPolicyLabel.findByPolicyLabelId", tClass) + .setParameter("policyLabelId", policyLabelId).getSingleResult(); + } catch (NoResultException e) { + return null; + } } + public List findByServiceId(Long serviceId) { + if (serviceId == null) { + return null; + } - public XXPolicyLabel findByPolicyLabelId(Long policyLabelId) { - if (policyLabelId == null) { - return null; - } - try { - return (XXPolicyLabel) getEntityManager().createNamedQuery("XXPolicyLabel.findByPolicyLabelId", tClass) - .setParameter("policyLabelId", policyLabelId).getSingleResult(); - } catch (NoResultException e) { - return null; - } + try { + return getEntityManager().createNamedQuery("XXPolicyLabel.findByServiceId", tClass) + .setParameter("serviceId", serviceId).getResultList(); + } catch (NoResultException e) { + return null; } + } - public List findByServiceId(Long serviceId) { - if (serviceId == null) { - return null; - } - try { - return getEntityManager().createNamedQuery("XXPolicyLabel.findByServiceId", tClass) - .setParameter("serviceId", serviceId).getResultList(); - } catch (NoResultException e) { - return null; - } - } - - public List findByPolicyId(Long policyId) { - if (policyId == null) { - return null; - } - try { - return getEntityManager().createNamedQuery("XXPolicyLabel.findByPolicyId", tClass) - .setParameter("policyId", policyId).getResultList(); - } catch (NoResultException e) { - return null; - } + public List findByPolicyId(Long policyId) { + if (policyId == null) { + return null; } + try { + return getEntityManager().createNamedQuery("XXPolicyLabel.findByPolicyId", tClass) + .setParameter("policyId", policyId).getResultList(); + } catch (NoResultException e) { + return null; + } + } } diff --git a/security-admin/src/main/java/org/apache/ranger/db/XXPolicyLabelMapDao.java b/security-admin/src/main/java/org/apache/ranger/db/XXPolicyLabelMapDao.java index 942cd11174..9ac6d6c2e0 100644 --- a/security-admin/src/main/java/org/apache/ranger/db/XXPolicyLabelMapDao.java +++ b/security-admin/src/main/java/org/apache/ranger/db/XXPolicyLabelMapDao.java @@ -17,56 +17,57 @@ 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.XXPolicyLabelMap; import org.springframework.stereotype.Service; +import javax.persistence.NoResultException; + +import java.util.List; + @Service public class XXPolicyLabelMapDao extends BaseDao { + public XXPolicyLabelMapDao(RangerDaoManagerBase daoMgr) { + super(daoMgr); + } - public XXPolicyLabelMapDao(RangerDaoManagerBase daoMgr) { - super(daoMgr); + public List findByPolicyId(Long policyId) { + if (policyId == null) { + return null; } - public List findByPolicyId(Long policyId) { - if(policyId == null) { - return null; - } - try { - return getEntityManager() - .createNamedQuery("XXPolicyLabelMap.findByPolicyId", tClass) - .setParameter("policyId", policyId).getResultList(); - } catch (NoResultException e) { - return null; - } + try { + return getEntityManager() + .createNamedQuery("XXPolicyLabelMap.findByPolicyId", tClass) + .setParameter("policyId", policyId).getResultList(); + } catch (NoResultException e) { + return null; } + } - public XXPolicyLabelMap findByPolicyLabelId(Long policyLabelId) { - if (policyLabelId == null) { - return null; - } - try { - return (XXPolicyLabelMap) getEntityManager().createNamedQuery("XXPolicyLabelMap.findByPolicyLabelId", tClass) - .setParameter("policyLabelId", policyLabelId).getResultList(); - } catch (NoResultException e) { - return null; - } + public XXPolicyLabelMap findByPolicyLabelId(Long policyLabelId) { + if (policyLabelId == null) { + return null; } - public List findByServiceId(Long serviceId) { - if (serviceId == null) { - return null; - } - try { - return getEntityManager().createNamedQuery("XXPolicyLabelMap.findByServiceId", tClass) - .setParameter("serviceId", serviceId).getResultList(); - } catch (NoResultException e) { - return null; - } + try { + return (XXPolicyLabelMap) getEntityManager().createNamedQuery("XXPolicyLabelMap.findByPolicyLabelId", tClass) + .setParameter("policyLabelId", policyLabelId).getResultList(); + } catch (NoResultException e) { + return null; } + } + public List findByServiceId(Long serviceId) { + if (serviceId == null) { + return null; + } + + try { + return getEntityManager().createNamedQuery("XXPolicyLabelMap.findByServiceId", tClass) + .setParameter("serviceId", serviceId).getResultList(); + } catch (NoResultException e) { + return null; + } + } } diff --git a/security-admin/src/main/java/org/apache/ranger/db/XXPolicyRefAccessTypeDao.java b/security-admin/src/main/java/org/apache/ranger/db/XXPolicyRefAccessTypeDao.java index 0857d35005..d83fbc5764 100644 --- a/security-admin/src/main/java/org/apache/ranger/db/XXPolicyRefAccessTypeDao.java +++ b/security-admin/src/main/java/org/apache/ranger/db/XXPolicyRefAccessTypeDao.java @@ -19,101 +19,106 @@ package org.apache.ranger.db; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import javax.persistence.NoResultException; - import org.apache.commons.collections.CollectionUtils; import org.apache.ranger.biz.RangerPolicyRetriever; import org.apache.ranger.common.db.BaseDao; import org.apache.ranger.entity.XXPolicyRefAccessType; import org.springframework.stereotype.Service; +import javax.persistence.NoResultException; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + @Service public class XXPolicyRefAccessTypeDao extends BaseDao { + public XXPolicyRefAccessTypeDao(RangerDaoManagerBase daoManager) { + super(daoManager); + } + + public List findByPolicyId(Long polId) { + if (polId == null) { + return Collections.emptyList(); + } + + try { + return getEntityManager() + .createNamedQuery("XXPolicyRefAccessType.findByPolicyId", tClass) + .setParameter("policyId", polId).getResultList(); + } catch (NoResultException e) { + return Collections.emptyList(); + } + } + + public List findByAccessTypeDefId(Long accessTypeDefId) { + if (accessTypeDefId == null) { + return Collections.emptyList(); + } + + try { + return getEntityManager().createNamedQuery("XXPolicyRefAccessType.findByAccessTypeDefId", tClass) + .setParameter("accessDefId", accessTypeDefId) + .getResultList(); + } catch (NoResultException e) { + return Collections.emptyList(); + } + } - public XXPolicyRefAccessTypeDao(RangerDaoManagerBase daoManager) { - super(daoManager); - } - - public List findByPolicyId(Long polId) { - if(polId == null) { - return Collections.EMPTY_LIST; - } - try { - return getEntityManager() - .createNamedQuery("XXPolicyRefAccessType.findByPolicyId", tClass) - .setParameter("policyId", polId).getResultList(); - } catch (NoResultException e) { - return Collections.EMPTY_LIST; - } - } - - public List findByAccessTypeDefId(Long accessTypeDefId) { - if (accessTypeDefId == null) { - return Collections.EMPTY_LIST; - } - try { - return getEntityManager().createNamedQuery("XXPolicyRefAccessType.findByAccessTypeDefId", tClass) - .setParameter("accessDefId", accessTypeDefId) - .getResultList(); - } catch (NoResultException e) { - return Collections.EMPTY_LIST; - } - } - - @SuppressWarnings("unchecked") public List findUpdatedAccessNamesByPolicy(Long policyId) { List ret = new ArrayList<>(); + if (policyId != null) { - List rows = (List) getEntityManager() - .createNamedQuery("XXPolicyRefAccessType.findUpdatedAccessNamesByPolicy") + List rows = getEntityManager() + .createNamedQuery("XXPolicyRefAccessType.findUpdatedAccessNamesByPolicy", Object[].class) .setParameter("policy", policyId) .getResultList(); + if (rows != null) { for (Object[] row : rows) { - ret.add(new RangerPolicyRetriever.PolicyTextNameMap((Long)row[0], (String)row[1], (String)row[2])); + ret.add(new RangerPolicyRetriever.PolicyTextNameMap((Long) row[0], (String) row[1], (String) row[2])); } } } + return ret; } - @SuppressWarnings("unchecked") - public List findUpdatedAccessNamesByService(Long serviceId) { + public List findUpdatedAccessNamesByService(Long serviceId) { List ret = new ArrayList<>(); + if (serviceId != null) { - List rows = (List) getEntityManager() - .createNamedQuery("XXPolicyRefAccessType.findUpdatedAccessNamesByService") + List rows = getEntityManager() + .createNamedQuery("XXPolicyRefAccessType.findUpdatedAccessNamesByService", Object[].class) .setParameter("service", serviceId) .getResultList(); + if (rows != null) { for (Object[] row : rows) { - ret.add(new RangerPolicyRetriever.PolicyTextNameMap((Long)row[0], (String)row[1], (String)row[2])); + ret.add(new RangerPolicyRetriever.PolicyTextNameMap((Long) row[0], (String) row[1], (String) row[2])); } } } + return ret; } - public void deleteByPolicyId(Long policyId) { - if(policyId == null) { - return; - } + public void deleteByPolicyId(Long policyId) { + if (policyId == null) { + return; + } - // First select ids according to policyId, then delete records according to ids - // The purpose of dividing the delete sql into these two steps is to avoid deadlocks at rr isolation level - List ids = getEntityManager() - .createNamedQuery("XXPolicyRefAccessType.findIdsByPolicyId", Long.class) - .setParameter("policyId", policyId) - .getResultList(); + // First select ids according to policyId, then delete records according to ids + // The purpose of dividing the delete sql into these two steps is to avoid deadlocks at rr isolation level + List ids = getEntityManager() + .createNamedQuery("XXPolicyRefAccessType.findIdsByPolicyId", Long.class) + .setParameter("policyId", policyId) + .getResultList(); - if (CollectionUtils.isEmpty(ids)) { - return; - } + if (CollectionUtils.isEmpty(ids)) { + return; + } - batchDeleteByIds("XXPolicyRefAccessType.deleteByIds", ids, "ids"); - } + batchDeleteByIds("XXPolicyRefAccessType.deleteByIds", ids, "ids"); + } } diff --git a/security-admin/src/main/java/org/apache/ranger/db/XXPolicyRefConditionDao.java b/security-admin/src/main/java/org/apache/ranger/db/XXPolicyRefConditionDao.java index aca36e89eb..74fc74c8a3 100644 --- a/security-admin/src/main/java/org/apache/ranger/db/XXPolicyRefConditionDao.java +++ b/security-admin/src/main/java/org/apache/ranger/db/XXPolicyRefConditionDao.java @@ -19,112 +19,119 @@ package org.apache.ranger.db; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import javax.persistence.NoResultException; - import org.apache.commons.collections.CollectionUtils; import org.apache.ranger.biz.RangerPolicyRetriever; import org.apache.ranger.common.db.BaseDao; import org.apache.ranger.entity.XXPolicyRefCondition; import org.springframework.stereotype.Service; +import javax.persistence.NoResultException; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + @Service -public class XXPolicyRefConditionDao extends BaseDao { - - public XXPolicyRefConditionDao(RangerDaoManagerBase daoManager) { - super(daoManager); - } - - public List findByPolicyId(Long polId) { - if(polId == null) { - return Collections.EMPTY_LIST; - } - try { - return getEntityManager() - .createNamedQuery("XXPolicyRefCondition.findByPolicyId", tClass) - .setParameter("policyId", polId).getResultList(); - } catch (NoResultException e) { - return Collections.EMPTY_LIST; - } - } - public List findByConditionName(String conditionName) { - if (conditionName == null) { - return Collections.EMPTY_LIST; - } - try { - return getEntityManager().createNamedQuery("XXPolicyRefCondition.findByConditionName", tClass) - .setParameter("conditionName", conditionName).getResultList(); - } catch (NoResultException e) { - return Collections.EMPTY_LIST; - } - } - - public List findByConditionDefId(Long conditionDefId) { - if (conditionDefId == null) { - return Collections.EMPTY_LIST; - } - try { - return getEntityManager().createNamedQuery("XXPolicyRefCondition.findByConditionDefId", tClass) - .setParameter("conditionDefId", conditionDefId) - .getResultList(); - } catch (NoResultException e) { - return Collections.EMPTY_LIST; - } - } - - @SuppressWarnings("unchecked") +public class XXPolicyRefConditionDao extends BaseDao { + public XXPolicyRefConditionDao(RangerDaoManagerBase daoManager) { + super(daoManager); + } + + public List findByPolicyId(Long polId) { + if (polId == null) { + return Collections.emptyList(); + } + + try { + return getEntityManager() + .createNamedQuery("XXPolicyRefCondition.findByPolicyId", tClass) + .setParameter("policyId", polId).getResultList(); + } catch (NoResultException e) { + return Collections.emptyList(); + } + } + + public List findByConditionName(String conditionName) { + if (conditionName == null) { + return Collections.emptyList(); + } + + try { + return getEntityManager().createNamedQuery("XXPolicyRefCondition.findByConditionName", tClass) + .setParameter("conditionName", conditionName).getResultList(); + } catch (NoResultException e) { + return Collections.emptyList(); + } + } + + public List findByConditionDefId(Long conditionDefId) { + if (conditionDefId == null) { + return Collections.emptyList(); + } + + try { + return getEntityManager().createNamedQuery("XXPolicyRefCondition.findByConditionDefId", tClass) + .setParameter("conditionDefId", conditionDefId) + .getResultList(); + } catch (NoResultException e) { + return Collections.emptyList(); + } + } + public List findUpdatedConditionNamesByPolicy(Long policyId) { List ret = new ArrayList<>(); + if (policyId != null) { - List rows = (List) getEntityManager() - .createNamedQuery("XXPolicyRefCondition.findUpdatedConditionNamesByPolicy") + List rows = getEntityManager() + .createNamedQuery("XXPolicyRefCondition.findUpdatedConditionNamesByPolicy", Object[].class) .setParameter("policy", policyId) .getResultList(); + if (rows != null) { for (Object[] row : rows) { - ret.add(new RangerPolicyRetriever.PolicyTextNameMap((Long)row[0], (String)row[1], (String)row[2])); + ret.add(new RangerPolicyRetriever.PolicyTextNameMap((Long) row[0], (String) row[1], (String) row[2])); } } } + return ret; } - @SuppressWarnings("unchecked") - public List findUpdatedConditionNamesByService(Long serviceId) { + public List findUpdatedConditionNamesByService(Long serviceId) { List ret = new ArrayList<>(); + if (serviceId != null) { - List rows = (List) getEntityManager() - .createNamedQuery("XXPolicyRefCondition.findUpdatedConditionNamesByService") + List rows = getEntityManager() + .createNamedQuery("XXPolicyRefCondition.findUpdatedConditionNamesByService", Object[].class) .setParameter("service", serviceId) .getResultList(); + if (rows != null) { for (Object[] row : rows) { - ret.add(new RangerPolicyRetriever.PolicyTextNameMap((Long)row[0], (String)row[1], (String)row[2])); + ret.add(new RangerPolicyRetriever.PolicyTextNameMap((Long) row[0], (String) row[1], (String) row[2])); } } } + return ret; } - public void deleteByPolicyId(Long policyId) { - if(policyId == null) { - return; - } + public void deleteByPolicyId(Long policyId) { + if (policyId == null) { + return; + } - // First select ids according to policyId, then delete records according to ids - // The purpose of dividing the delete sql into these two steps is to avoid deadlocks at rr isolation level - List ids = getEntityManager() - .createNamedQuery("XXPolicyRefCondition.findIdsByPolicyId", Long.class) - .setParameter("policyId", policyId) - .getResultList(); + // First select ids according to policyId, then delete records according to ids + // The purpose of dividing the delete sql into these two steps is to avoid deadlocks at rr isolation level + List ids = getEntityManager() + .createNamedQuery("XXPolicyRefCondition.findIdsByPolicyId", Long.class) + .setParameter("policyId", policyId) + .getResultList(); - if (CollectionUtils.isEmpty(ids)) { - return; - } + if (CollectionUtils.isEmpty(ids)) { + return; + } - batchDeleteByIds("XXPolicyRefCondition.deleteByIds", ids, "ids"); - } + batchDeleteByIds("XXPolicyRefCondition.deleteByIds", ids, "ids"); + } } diff --git a/security-admin/src/main/java/org/apache/ranger/db/XXPolicyRefDataMaskTypeDao.java b/security-admin/src/main/java/org/apache/ranger/db/XXPolicyRefDataMaskTypeDao.java index dd89fbbfb6..f4f728228d 100644 --- a/security-admin/src/main/java/org/apache/ranger/db/XXPolicyRefDataMaskTypeDao.java +++ b/security-admin/src/main/java/org/apache/ranger/db/XXPolicyRefDataMaskTypeDao.java @@ -19,88 +19,92 @@ package org.apache.ranger.db; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import javax.persistence.NoResultException; - import org.apache.commons.collections.CollectionUtils; import org.apache.ranger.biz.RangerPolicyRetriever; import org.apache.ranger.common.db.BaseDao; import org.apache.ranger.entity.XXPolicyRefDataMaskType; import org.springframework.stereotype.Service; +import javax.persistence.NoResultException; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + @Service -public class XXPolicyRefDataMaskTypeDao extends BaseDao{ - - public XXPolicyRefDataMaskTypeDao(RangerDaoManagerBase daoManager) { - super(daoManager); - } - - public List findByPolicyId(Long policyId) { - if(policyId == null) { - return Collections.EMPTY_LIST; - } - try { - return getEntityManager() - .createNamedQuery("XXPolicyRefDataMaskType.findByPolicyId", tClass) - .setParameter("policyId", policyId).getResultList(); - } catch (NoResultException e) { - return Collections.EMPTY_LIST; - } - } - - @SuppressWarnings("unchecked") +public class XXPolicyRefDataMaskTypeDao extends BaseDao { + public XXPolicyRefDataMaskTypeDao(RangerDaoManagerBase daoManager) { + super(daoManager); + } + + public List findByPolicyId(Long policyId) { + if (policyId == null) { + return Collections.emptyList(); + } + + try { + return getEntityManager() + .createNamedQuery("XXPolicyRefDataMaskType.findByPolicyId", tClass) + .setParameter("policyId", policyId).getResultList(); + } catch (NoResultException e) { + return Collections.emptyList(); + } + } + public List findUpdatedDataMaskNamesByPolicy(Long policyId) { List ret = new ArrayList<>(); + if (policyId != null) { - List rows = (List) getEntityManager() - .createNamedQuery("XXPolicyRefDataMaskType.findUpdatedDataMaskNamesByPolicy") + List rows = getEntityManager() + .createNamedQuery("XXPolicyRefDataMaskType.findUpdatedDataMaskNamesByPolicy", Object[].class) .setParameter("policy", policyId) .getResultList(); + if (rows != null) { for (Object[] row : rows) { - ret.add(new RangerPolicyRetriever.PolicyTextNameMap((Long)row[0], (String)row[1], (String)row[2])); + ret.add(new RangerPolicyRetriever.PolicyTextNameMap((Long) row[0], (String) row[1], (String) row[2])); } } } + return ret; } - @SuppressWarnings("unchecked") - public List findUpdatedDataMaskNamesByService(Long serviceId) { + public List findUpdatedDataMaskNamesByService(Long serviceId) { List ret = new ArrayList<>(); + if (serviceId != null) { - List rows = (List) getEntityManager() - .createNamedQuery("XXPolicyRefDataMaskType.findUpdatedDataMaskNamesByService") + List rows = getEntityManager() + .createNamedQuery("XXPolicyRefDataMaskType.findUpdatedDataMaskNamesByService", Object[].class) .setParameter("service", serviceId) .getResultList(); + if (rows != null) { for (Object[] row : rows) { - ret.add(new RangerPolicyRetriever.PolicyTextNameMap((Long)row[0], (String)row[1], (String)row[2])); + ret.add(new RangerPolicyRetriever.PolicyTextNameMap((Long) row[0], (String) row[1], (String) row[2])); } } } + return ret; } - public void deleteByPolicyId(Long policyId) { - if(policyId == null) { - return; - } + public void deleteByPolicyId(Long policyId) { + if (policyId == null) { + return; + } - // First select ids according to policyId, then delete records according to ids - // The purpose of dividing the delete sql into these two steps is to avoid deadlocks at rr isolation level - List ids = getEntityManager() - .createNamedQuery("XXPolicyRefDataMaskType.findIdsByPolicyId", Long.class) - .setParameter("policyId", policyId) - .getResultList(); + // First select ids according to policyId, then delete records according to ids + // The purpose of dividing the delete sql into these two steps is to avoid deadlocks at rr isolation level + List ids = getEntityManager() + .createNamedQuery("XXPolicyRefDataMaskType.findIdsByPolicyId", Long.class) + .setParameter("policyId", policyId) + .getResultList(); - if (CollectionUtils.isEmpty(ids)) { - return; - } + if (CollectionUtils.isEmpty(ids)) { + return; + } - batchDeleteByIds("XXPolicyRefDataMaskType.deleteByIds", ids, "ids"); - } + batchDeleteByIds("XXPolicyRefDataMaskType.deleteByIds", ids, "ids"); + } } diff --git a/security-admin/src/main/java/org/apache/ranger/db/XXPolicyRefGroupDao.java b/security-admin/src/main/java/org/apache/ranger/db/XXPolicyRefGroupDao.java index 3ce371306a..21496a81a1 100644 --- a/security-admin/src/main/java/org/apache/ranger/db/XXPolicyRefGroupDao.java +++ b/security-admin/src/main/java/org/apache/ranger/db/XXPolicyRefGroupDao.java @@ -19,100 +19,105 @@ package org.apache.ranger.db; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import javax.persistence.NoResultException; - import org.apache.commons.collections.CollectionUtils; import org.apache.ranger.biz.RangerPolicyRetriever; import org.apache.ranger.common.db.BaseDao; import org.apache.ranger.entity.XXPolicyRefGroup; import org.springframework.stereotype.Service; +import javax.persistence.NoResultException; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + @Service -public class XXPolicyRefGroupDao extends BaseDao{ - - - public XXPolicyRefGroupDao(RangerDaoManagerBase daoManager) { - super(daoManager); - } - - public List findByPolicyId(Long policyId) { - if(policyId == null) { - return Collections.EMPTY_LIST; - } - try { - return getEntityManager() - .createNamedQuery("XXPolicyRefGroup.findByPolicyId", tClass) - .setParameter("policyId", policyId).getResultList(); - } catch (NoResultException e) { - return Collections.EMPTY_LIST; - } - } - public List findByGroupName(String groupName) { - if (groupName == null) { - return Collections.EMPTY_LIST; - } - try { - return getEntityManager().createNamedQuery("XXPolicyRefGroup.findByGroupName", tClass) - .setParameter("groupName", groupName).getResultList(); - } catch (NoResultException e) { - return Collections.EMPTY_LIST; - } - } - - @SuppressWarnings("unchecked") +public class XXPolicyRefGroupDao extends BaseDao { + public XXPolicyRefGroupDao(RangerDaoManagerBase daoManager) { + super(daoManager); + } + + public List findByPolicyId(Long policyId) { + if (policyId == null) { + return Collections.emptyList(); + } + + try { + return getEntityManager() + .createNamedQuery("XXPolicyRefGroup.findByPolicyId", tClass) + .setParameter("policyId", policyId).getResultList(); + } catch (NoResultException e) { + return Collections.emptyList(); + } + } + + public List findByGroupName(String groupName) { + if (groupName == null) { + return Collections.emptyList(); + } + + try { + return getEntityManager().createNamedQuery("XXPolicyRefGroup.findByGroupName", tClass) + .setParameter("groupName", groupName).getResultList(); + } catch (NoResultException e) { + return Collections.emptyList(); + } + } + public List findUpdatedGroupNamesByPolicy(Long policyId) { List ret = new ArrayList<>(); + if (policyId != null) { - List rows = (List) getEntityManager() - .createNamedQuery("XXPolicyRefGroup.findUpdatedGroupNamesByPolicy") + List rows = getEntityManager() + .createNamedQuery("XXPolicyRefGroup.findUpdatedGroupNamesByPolicy", Object[].class) .setParameter("policy", policyId) .getResultList(); + if (rows != null) { for (Object[] row : rows) { - ret.add(new RangerPolicyRetriever.PolicyTextNameMap((Long)row[0], (String)row[1], (String)row[2])); + ret.add(new RangerPolicyRetriever.PolicyTextNameMap((Long) row[0], (String) row[1], (String) row[2])); } } } + return ret; } - @SuppressWarnings("unchecked") - public List findUpdatedGroupNamesByService(Long serviceId) { + public List findUpdatedGroupNamesByService(Long serviceId) { List ret = new ArrayList<>(); + if (serviceId != null) { - List rows = (List) getEntityManager() - .createNamedQuery("XXPolicyRefGroup.findUpdatedGroupNamesByService") + List rows = getEntityManager() + .createNamedQuery("XXPolicyRefGroup.findUpdatedGroupNamesByService", Object[].class) .setParameter("service", serviceId) .getResultList(); + if (rows != null) { for (Object[] row : rows) { - ret.add(new RangerPolicyRetriever.PolicyTextNameMap((Long)row[0], (String)row[1], (String)row[2])); + ret.add(new RangerPolicyRetriever.PolicyTextNameMap((Long) row[0], (String) row[1], (String) row[2])); } } } + return ret; } - public void deleteByPolicyId(Long policyId) { - if(policyId == null) { - return; - } + public void deleteByPolicyId(Long policyId) { + if (policyId == null) { + return; + } - // First select ids according to policyId, then delete records according to ids - // The purpose of dividing the delete sql into these two steps is to avoid deadlocks at rr isolation level - List ids = getEntityManager() - .createNamedQuery("XXPolicyRefGroup.findIdsByPolicyId", Long.class) - .setParameter("policyId", policyId) - .getResultList(); + // First select ids according to policyId, then delete records according to ids + // The purpose of dividing the delete sql into these two steps is to avoid deadlocks at rr isolation level + List ids = getEntityManager() + .createNamedQuery("XXPolicyRefGroup.findIdsByPolicyId", Long.class) + .setParameter("policyId", policyId) + .getResultList(); - if (CollectionUtils.isEmpty(ids)) { - return; - } + if (CollectionUtils.isEmpty(ids)) { + return; + } - batchDeleteByIds("XXPolicyRefGroup.deleteByIds", ids, "ids"); - } + batchDeleteByIds("XXPolicyRefGroup.deleteByIds", ids, "ids"); + } } diff --git a/security-admin/src/main/java/org/apache/ranger/db/XXPolicyRefResourceDao.java b/security-admin/src/main/java/org/apache/ranger/db/XXPolicyRefResourceDao.java index c198b93013..dc25662810 100644 --- a/security-admin/src/main/java/org/apache/ranger/db/XXPolicyRefResourceDao.java +++ b/security-admin/src/main/java/org/apache/ranger/db/XXPolicyRefResourceDao.java @@ -19,100 +19,105 @@ package org.apache.ranger.db; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import javax.persistence.NoResultException; - import org.apache.commons.collections.CollectionUtils; import org.apache.ranger.biz.RangerPolicyRetriever; import org.apache.ranger.common.db.BaseDao; import org.apache.ranger.entity.XXPolicyRefResource; import org.springframework.stereotype.Service; +import javax.persistence.NoResultException; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + @Service -public class XXPolicyRefResourceDao extends BaseDao{ - - public XXPolicyRefResourceDao(RangerDaoManagerBase daoManager) { - super(daoManager); - } - - public List findByPolicyId(Long policyId) { - if(policyId == null) { - return Collections.EMPTY_LIST; - } - try { - return getEntityManager() - .createNamedQuery("XXPolicyRefResource.findByPolicyId", tClass) - .setParameter("policyId", policyId).getResultList(); - } catch (NoResultException e) { - return Collections.EMPTY_LIST; - } - } - - public List findByResourceDefID(Long resourceDefId) { - if (resourceDefId == null) { - return Collections.EMPTY_LIST; - } - try { - return getEntityManager().createNamedQuery("XXPolicyRefResource.findByResourceDefId", tClass) - .setParameter("resourceDefId", resourceDefId).getResultList(); - } catch (NoResultException e) { - return Collections.EMPTY_LIST; - } - } - - public void deleteByPolicyId(Long policyId) { - if(policyId == null) { - return; - } - - // First select ids according to policyId, then delete records according to ids - // The purpose of dividing the delete sql into these two steps is to avoid deadlocks at rr isolation level - List ids = getEntityManager() - .createNamedQuery("XXPolicyRefResource.findIdsByPolicyId", Long.class) - .setParameter("policyId", policyId) - .getResultList(); - - if (CollectionUtils.isEmpty(ids)) { - return; - } - - batchDeleteByIds("XXPolicyRefResource.deleteByIds", ids, "ids"); - } - - @SuppressWarnings("unchecked") - public List findUpdatedResourceNamesByPolicy(Long policyId) { - List ret = new ArrayList<>(); - if (policyId != null) { - List rows = (List) getEntityManager() - .createNamedQuery("XXPolicyRefResource.findUpdatedResourceNamesByPolicy") - .setParameter("policy", policyId) - .getResultList(); - if (rows != null) { - for (Object[] row : rows) { - ret.add(new RangerPolicyRetriever.PolicyTextNameMap((Long)row[0], (String)row[1], (String)row[2])); - } - } - } - return ret; - } - - @SuppressWarnings("unchecked") - public List findUpdatedResourceNamesByService(Long serviceId) { - List ret = new ArrayList<>(); - if (serviceId != null) { - List rows = (List) getEntityManager() - .createNamedQuery("XXPolicyRefResource.findUpdatedResourceNamesByService") - .setParameter("service", serviceId) - .getResultList(); - if (rows != null) { - for (Object[] row : rows) { - ret.add(new RangerPolicyRetriever.PolicyTextNameMap((Long)row[0], (String)row[1], (String)row[2])); - } - } - } - return ret; - } +public class XXPolicyRefResourceDao extends BaseDao { + public XXPolicyRefResourceDao(RangerDaoManagerBase daoManager) { + super(daoManager); + } + + public List findByPolicyId(Long policyId) { + if (policyId == null) { + return Collections.emptyList(); + } + + try { + return getEntityManager() + .createNamedQuery("XXPolicyRefResource.findByPolicyId", tClass) + .setParameter("policyId", policyId).getResultList(); + } catch (NoResultException e) { + return Collections.emptyList(); + } + } + + public List findByResourceDefID(Long resourceDefId) { + if (resourceDefId == null) { + return Collections.emptyList(); + } + + try { + return getEntityManager().createNamedQuery("XXPolicyRefResource.findByResourceDefId", tClass) + .setParameter("resourceDefId", resourceDefId).getResultList(); + } catch (NoResultException e) { + return Collections.emptyList(); + } + } + + public void deleteByPolicyId(Long policyId) { + if (policyId == null) { + return; + } + + // First select ids according to policyId, then delete records according to ids + // The purpose of dividing the delete sql into these two steps is to avoid deadlocks at rr isolation level + List ids = getEntityManager() + .createNamedQuery("XXPolicyRefResource.findIdsByPolicyId", Long.class) + .setParameter("policyId", policyId) + .getResultList(); + + if (CollectionUtils.isEmpty(ids)) { + return; + } + + batchDeleteByIds("XXPolicyRefResource.deleteByIds", ids, "ids"); + } + + public List findUpdatedResourceNamesByPolicy(Long policyId) { + List ret = new ArrayList<>(); + + if (policyId != null) { + List rows = getEntityManager() + .createNamedQuery("XXPolicyRefResource.findUpdatedResourceNamesByPolicy", Object[].class) + .setParameter("policy", policyId) + .getResultList(); + + if (rows != null) { + for (Object[] row : rows) { + ret.add(new RangerPolicyRetriever.PolicyTextNameMap((Long) row[0], (String) row[1], (String) row[2])); + } + } + } + + return ret; + } + + public List findUpdatedResourceNamesByService(Long serviceId) { + List ret = new ArrayList<>(); + + if (serviceId != null) { + List rows = getEntityManager() + .createNamedQuery("XXPolicyRefResource.findUpdatedResourceNamesByService", Object[].class) + .setParameter("service", serviceId) + .getResultList(); + + if (rows != null) { + for (Object[] row : rows) { + ret.add(new RangerPolicyRetriever.PolicyTextNameMap((Long) row[0], (String) row[1], (String) row[2])); + } + } + } + + return ret; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/db/XXPolicyRefRoleDao.java b/security-admin/src/main/java/org/apache/ranger/db/XXPolicyRefRoleDao.java index 29d2bc4c94..69b82d6732 100644 --- a/security-admin/src/main/java/org/apache/ranger/db/XXPolicyRefRoleDao.java +++ b/security-admin/src/main/java/org/apache/ranger/db/XXPolicyRefRoleDao.java @@ -19,100 +19,106 @@ package org.apache.ranger.db; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import javax.persistence.NoResultException; - import org.apache.commons.collections.CollectionUtils; import org.apache.ranger.biz.RangerPolicyRetriever; import org.apache.ranger.common.db.BaseDao; import org.apache.ranger.entity.XXPolicyRefRole; import org.springframework.stereotype.Service; -@Service -public class XXPolicyRefRoleDao extends BaseDao{ +import javax.persistence.NoResultException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; - public XXPolicyRefRoleDao(RangerDaoManagerBase daoManager) { +@Service +public class XXPolicyRefRoleDao extends BaseDao { + public XXPolicyRefRoleDao(RangerDaoManagerBase daoManager) { super(daoManager); } public List findByPolicyId(Long policyId) { - if(policyId == null) { - return Collections.EMPTY_LIST; + if (policyId == null) { + return Collections.emptyList(); } + try { return getEntityManager() .createNamedQuery("XXPolicyRefRole.findByPolicyId", tClass) .setParameter("policyId", policyId).getResultList(); } catch (NoResultException e) { - return Collections.EMPTY_LIST; + return Collections.emptyList(); } } + public List findByRoleName(String roleName) { if (roleName == null) { - return Collections.EMPTY_LIST; + return Collections.emptyList(); } + try { return getEntityManager().createNamedQuery("XXPolicyRefRole.findByRoleName", tClass) .setParameter("roleName", roleName).getResultList(); } catch (NoResultException e) { - return Collections.EMPTY_LIST; + return Collections.emptyList(); } } - @SuppressWarnings("unchecked") public List findUpdatedRoleNamesByPolicy(Long policyId) { List ret = new ArrayList<>(); + if (policyId != null) { - List rows = (List) getEntityManager() - .createNamedQuery("XXPolicyRefRole.findUpdatedRoleNamesByPolicy") + List rows = getEntityManager() + .createNamedQuery("XXPolicyRefRole.findUpdatedRoleNamesByPolicy", Object[].class) .setParameter("policy", policyId) .getResultList(); + if (rows != null) { for (Object[] row : rows) { - ret.add(new RangerPolicyRetriever.PolicyTextNameMap((Long)row[0], (String)row[1], (String)row[2])); + ret.add(new RangerPolicyRetriever.PolicyTextNameMap((Long) row[0], (String) row[1], (String) row[2])); } } } + return ret; } - @SuppressWarnings("unchecked") public List findUpdatedRoleNamesByService(Long serviceId) { List ret = new ArrayList<>(); + if (serviceId != null) { - List rows = (List) getEntityManager() - .createNamedQuery("XXPolicyRefRole.findUpdatedRoleNamesByService") + List rows = getEntityManager() + .createNamedQuery("XXPolicyRefRole.findUpdatedRoleNamesByService", Object[].class) .setParameter("service", serviceId) .getResultList(); + if (rows != null) { for (Object[] row : rows) { - ret.add(new RangerPolicyRetriever.PolicyTextNameMap((Long)row[0], (String)row[1], (String)row[2])); + ret.add(new RangerPolicyRetriever.PolicyTextNameMap((Long) row[0], (String) row[1], (String) row[2])); } } } + return ret; } - public Long findRoleRefPolicyCount(String roleName) { - Long ret = -1L; + public Long findRoleRefPolicyCount(String roleName) { + Long ret = -1L; - try { - ret = getEntityManager().createNamedQuery("XXPolicyRefRole.findRoleRefPolicyCount", Long.class) - .setParameter("roleName", roleName).getSingleResult(); - } catch (Exception e) { - } + try { + ret = getEntityManager().createNamedQuery("XXPolicyRefRole.findRoleRefPolicyCount", Long.class) + .setParameter("roleName", roleName).getSingleResult(); + } catch (Exception e) { + // ignore + } - return ret; - } + return ret; + } - public void deleteByPolicyId(Long policyId) { - if(policyId == null) { - return; - } + public void deleteByPolicyId(Long policyId) { + if (policyId == null) { + return; + } // First select ids according to policyId, then delete records according to ids // The purpose of dividing the delete sql into these two steps is to avoid deadlocks at rr isolation level @@ -126,6 +132,5 @@ public void deleteByPolicyId(Long policyId) { } batchDeleteByIds("XXPolicyRefRole.deleteByIds", ids, "ids"); - } + } } - diff --git a/security-admin/src/main/java/org/apache/ranger/db/XXPolicyRefUserDao.java b/security-admin/src/main/java/org/apache/ranger/db/XXPolicyRefUserDao.java index 07d94ceb9f..d70ebd50e4 100644 --- a/security-admin/src/main/java/org/apache/ranger/db/XXPolicyRefUserDao.java +++ b/security-admin/src/main/java/org/apache/ranger/db/XXPolicyRefUserDao.java @@ -19,112 +19,118 @@ package org.apache.ranger.db; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import javax.persistence.NoResultException; - import org.apache.commons.collections.CollectionUtils; import org.apache.ranger.biz.RangerPolicyRetriever; import org.apache.ranger.common.db.BaseDao; import org.apache.ranger.entity.XXPolicyRefUser; import org.springframework.stereotype.Service; +import javax.persistence.NoResultException; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + @Service -public class XXPolicyRefUserDao extends BaseDao{ - - - public XXPolicyRefUserDao(RangerDaoManagerBase daoManager) { - super(daoManager); - } - - public List findByPolicyId(Long policyId) { - if(policyId == null) { - return Collections.EMPTY_LIST; - } - try { - return getEntityManager() - .createNamedQuery("XXPolicyRefUser.findByPolicyId", tClass) - .setParameter("policyId", policyId).getResultList(); - } catch (NoResultException e) { - return Collections.EMPTY_LIST; - } - } - public List findByUserName(String userName) { - if (userName == null) { - return Collections.EMPTY_LIST; - } - try { - return getEntityManager().createNamedQuery("XXPolicyRefUser.findByUserName", tClass) - .setParameter("userName", userName).getResultList(); - } catch (NoResultException e) { - return Collections.EMPTY_LIST; - } - } - - public List findByUserId(String userID) { - if (userID == null) { - return Collections.EMPTY_LIST; - } - try { - return getEntityManager().createNamedQuery("XXPolicyRefUser.findByUserId", tClass) - .setParameter("userID", userID).getResultList(); - } catch (NoResultException e) { - return Collections.EMPTY_LIST; - } - } - - @SuppressWarnings("unchecked") +public class XXPolicyRefUserDao extends BaseDao { + public XXPolicyRefUserDao(RangerDaoManagerBase daoManager) { + super(daoManager); + } + + public List findByPolicyId(Long policyId) { + if (policyId == null) { + return Collections.emptyList(); + } + + try { + return getEntityManager() + .createNamedQuery("XXPolicyRefUser.findByPolicyId", tClass) + .setParameter("policyId", policyId).getResultList(); + } catch (NoResultException e) { + return Collections.emptyList(); + } + } + + public List findByUserName(String userName) { + if (userName == null) { + return Collections.emptyList(); + } + + try { + return getEntityManager().createNamedQuery("XXPolicyRefUser.findByUserName", tClass) + .setParameter("userName", userName).getResultList(); + } catch (NoResultException e) { + return Collections.emptyList(); + } + } + + public List findByUserId(String userID) { + if (userID == null) { + return Collections.emptyList(); + } + + try { + return getEntityManager().createNamedQuery("XXPolicyRefUser.findByUserId", tClass) + .setParameter("userID", userID).getResultList(); + } catch (NoResultException e) { + return Collections.emptyList(); + } + } + public List findUpdatedUserNamesByPolicy(Long policyId) { List ret = new ArrayList<>(); + if (policyId != null) { - List rows = (List) getEntityManager() - .createNamedQuery("XXPolicyRefUser.findUpdatedUserNamesByPolicy") + List rows = getEntityManager() + .createNamedQuery("XXPolicyRefUser.findUpdatedUserNamesByPolicy", Object[].class) .setParameter("policy", policyId) .getResultList(); + if (rows != null) { for (Object[] row : rows) { - ret.add(new RangerPolicyRetriever.PolicyTextNameMap((Long)row[0], (String)row[1], (String)row[2])); + ret.add(new RangerPolicyRetriever.PolicyTextNameMap((Long) row[0], (String) row[1], (String) row[2])); } } } + return ret; } - @SuppressWarnings("unchecked") - public List findUpdatedUserNamesByService(Long serviceId) { + public List findUpdatedUserNamesByService(Long serviceId) { List ret = new ArrayList<>(); + if (serviceId != null) { - List rows = (List) getEntityManager() - .createNamedQuery("XXPolicyRefUser.findUpdatedUserNamesByService") + List rows = getEntityManager() + .createNamedQuery("XXPolicyRefUser.findUpdatedUserNamesByService", Object[].class) .setParameter("service", serviceId) .getResultList(); + if (rows != null) { for (Object[] row : rows) { - ret.add(new RangerPolicyRetriever.PolicyTextNameMap((Long)row[0], (String)row[1], (String)row[2])); + ret.add(new RangerPolicyRetriever.PolicyTextNameMap((Long) row[0], (String) row[1], (String) row[2])); } } } + return ret; } - public void deleteByPolicyId(Long policyId) { - if(policyId == null) { - return; - } + public void deleteByPolicyId(Long policyId) { + if (policyId == null) { + return; + } - // First select ids according to policyId, then delete records according to ids - // The purpose of dividing the delete sql into these two steps is to avoid deadlocks at rr isolation level - List ids = getEntityManager() - .createNamedQuery("XXPolicyRefUser.findIdsByPolicyId", Long.class) - .setParameter("policyId", policyId) - .getResultList(); + // First select ids according to policyId, then delete records according to ids + // The purpose of dividing the delete sql into these two steps is to avoid deadlocks at rr isolation level + List ids = getEntityManager() + .createNamedQuery("XXPolicyRefUser.findIdsByPolicyId", Long.class) + .setParameter("policyId", policyId) + .getResultList(); - if (CollectionUtils.isEmpty(ids)) { - return; - } + if (CollectionUtils.isEmpty(ids)) { + return; + } - batchDeleteByIds("XXPolicyRefUser.deleteByIds", ids, "ids"); - } + batchDeleteByIds("XXPolicyRefUser.deleteByIds", ids, "ids"); + } } diff --git a/security-admin/src/main/java/org/apache/ranger/db/XXPolicyResourceDao.java b/security-admin/src/main/java/org/apache/ranger/db/XXPolicyResourceDao.java index 9069e611a3..693aff93f5 100644 --- a/security-admin/src/main/java/org/apache/ranger/db/XXPolicyResourceDao.java +++ b/security-admin/src/main/java/org/apache/ranger/db/XXPolicyResourceDao.java @@ -17,66 +17,68 @@ package org.apache.ranger.db; -import java.util.ArrayList; -import java.util.List; - -import javax.persistence.NoResultException; - import org.apache.ranger.common.db.BaseDao; import org.apache.ranger.entity.XXPolicyResource; import org.springframework.stereotype.Service; +import javax.persistence.NoResultException; + +import java.util.ArrayList; +import java.util.List; + @Service public class XXPolicyResourceDao extends BaseDao { + public XXPolicyResourceDao(RangerDaoManagerBase daoManager) { + super(daoManager); + } + + public List findByPolicyId(Long policyId) { + if (policyId == null) { + return new ArrayList<>(); + } + + try { + return getEntityManager() + .createNamedQuery("XXPolicyResource.findByPolicyId", tClass) + .setParameter("policyId", policyId).getResultList(); + } catch (NoResultException e) { + return new ArrayList<>(); + } + } - public XXPolicyResourceDao(RangerDaoManagerBase daoManager) { - super(daoManager); - } + public List findByServiceId(Long serviceId) { + if (serviceId == null) { + return new ArrayList<>(); + } - public List findByPolicyId(Long policyId) { - if(policyId == null) { - return new ArrayList(); - } - try { - return getEntityManager() - .createNamedQuery("XXPolicyResource.findByPolicyId", tClass) - .setParameter("policyId", policyId).getResultList(); - } catch (NoResultException e) { - return new ArrayList(); - } - } + try { + return getEntityManager() + .createNamedQuery("XXPolicyResource.findByServiceId", tClass) + .setParameter("serviceId", serviceId).getResultList(); + } catch (NoResultException e) { + return new ArrayList<>(); + } + } - public List findByServiceId(Long serviceId) { - if(serviceId == null) { - return new ArrayList(); - } - try { - return getEntityManager() - .createNamedQuery("XXPolicyResource.findByServiceId", tClass) - .setParameter("serviceId", serviceId).getResultList(); - } catch (NoResultException e) { - return new ArrayList(); - } - } + public List findByResDefId(Long resDefId) { + if (resDefId == null) { + return new ArrayList<>(); + } - public List findByResDefId(Long resDefId) { - if (resDefId == null) { - return new ArrayList(); - } - try { - return getEntityManager().createNamedQuery("XXPolicyResource.findByResDefId", tClass) - .setParameter("resDefId", resDefId).getResultList(); - } catch (NoResultException e) { - return new ArrayList(); - } - } + try { + return getEntityManager().createNamedQuery("XXPolicyResource.findByResDefId", tClass) + .setParameter("resDefId", resDefId).getResultList(); + } catch (NoResultException e) { + return new ArrayList<>(); + } + } - public void deleteByPolicyId(Long policyId) { - if(policyId == null) { - return; - } - getEntityManager() - .createNamedQuery("XXPolicyResource.deleteByPolicyId", tClass) - .setParameter("policyId", policyId).executeUpdate(); - } + public void deleteByPolicyId(Long policyId) { + if (policyId == null) { + return; + } + getEntityManager() + .createNamedQuery("XXPolicyResource.deleteByPolicyId", tClass) + .setParameter("policyId", policyId).executeUpdate(); + } } diff --git a/security-admin/src/main/java/org/apache/ranger/db/XXPolicyResourceMapDao.java b/security-admin/src/main/java/org/apache/ranger/db/XXPolicyResourceMapDao.java index c5e6a2fe35..cee95b32a2 100644 --- a/security-admin/src/main/java/org/apache/ranger/db/XXPolicyResourceMapDao.java +++ b/security-admin/src/main/java/org/apache/ranger/db/XXPolicyResourceMapDao.java @@ -17,54 +17,56 @@ package org.apache.ranger.db; -import java.util.ArrayList; -import java.util.List; - -import javax.persistence.NoResultException; - import org.apache.ranger.common.db.BaseDao; import org.apache.ranger.entity.XXPolicyResourceMap; import org.springframework.stereotype.Service; +import javax.persistence.NoResultException; + +import java.util.ArrayList; +import java.util.List; + @Service public class XXPolicyResourceMapDao extends BaseDao { + public XXPolicyResourceMapDao(RangerDaoManagerBase daoManager) { + super(daoManager); + } + + public List findByPolicyId(Long policyId) { + if (policyId == null) { + return new ArrayList<>(); + } + + try { + return getEntityManager() + .createNamedQuery("XXPolicyResourceMap.findByPolicyId", tClass) + .setParameter("policyId", policyId).getResultList(); + } catch (NoResultException e) { + return new ArrayList<>(); + } + } - public XXPolicyResourceMapDao(RangerDaoManagerBase daoManager) { - super(daoManager); - } + public List findByServiceId(Long serviceId) { + if (serviceId == null) { + return new ArrayList<>(); + } - public List findByPolicyId(Long policyId) { - if(policyId == null) { - return new ArrayList(); - } - try { - return getEntityManager() - .createNamedQuery("XXPolicyResourceMap.findByPolicyId", tClass) - .setParameter("policyId", policyId).getResultList(); - } catch (NoResultException e) { - return new ArrayList(); - } - } + try { + return getEntityManager() + .createNamedQuery("XXPolicyResourceMap.findByServiceId", tClass) + .setParameter("serviceId", serviceId).getResultList(); + } catch (NoResultException e) { + return new ArrayList<>(); + } + } - public List findByServiceId(Long serviceId) { - if(serviceId == null) { - return new ArrayList(); - } - try { - return getEntityManager() - .createNamedQuery("XXPolicyResourceMap.findByServiceId", tClass) - .setParameter("serviceId", serviceId).getResultList(); - } catch (NoResultException e) { - return new ArrayList(); - } - } + public void deleteByPolicyId(Long policyId) { + if (policyId == null) { + return; + } - public void deleteByPolicyId(Long policyId) { - if(policyId == null) { - return; - } - getEntityManager() - .createNamedQuery("XXPolicyResourceMap.deleteByPolicyId", tClass) - .setParameter("policyId", policyId).executeUpdate(); - } + getEntityManager() + .createNamedQuery("XXPolicyResourceMap.deleteByPolicyId", tClass) + .setParameter("policyId", policyId).executeUpdate(); + } } diff --git a/security-admin/src/main/java/org/apache/ranger/db/XXPolicyWithAssignedIdDao.java b/security-admin/src/main/java/org/apache/ranger/db/XXPolicyWithAssignedIdDao.java index 21c4b647a7..a27241fa90 100644 --- a/security-admin/src/main/java/org/apache/ranger/db/XXPolicyWithAssignedIdDao.java +++ b/security-admin/src/main/java/org/apache/ranger/db/XXPolicyWithAssignedIdDao.java @@ -23,9 +23,7 @@ @Service public class XXPolicyWithAssignedIdDao extends BaseDao { - - public XXPolicyWithAssignedIdDao(RangerDaoManagerBase daoManager) { - super(daoManager); - } - + public XXPolicyWithAssignedIdDao(RangerDaoManagerBase daoManager) { + super(daoManager); + } } 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 index 18ef22cc7f..c2bc655fd7 100644 --- a/security-admin/src/main/java/org/apache/ranger/db/XXPortalUserDao.java +++ b/security-admin/src/main/java/org/apache/ranger/db/XXPortalUserDao.java @@ -19,153 +19,156 @@ package org.apache.ranger.db; -import java.util.List; -import java.util.Map; -import java.util.HashMap; -import java.util.Collections; -import java.util.Objects; - -import javax.persistence.NoResultException; - import org.apache.ranger.common.RangerCommonEnums; import org.apache.ranger.common.RangerConstants; import org.apache.ranger.common.db.BaseDao; import org.apache.ranger.entity.XXPortalUser; import org.springframework.stereotype.Service; +import javax.persistence.NoResultException; + +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; + @Service public class XXPortalUserDao extends BaseDao { + public XXPortalUserDao(RangerDaoManagerBase daoManager) { + super(daoManager); + } + + public XXPortalUser findByLoginId(String loginId) { + if (daoManager.getStringUtil().isEmpty(loginId)) { + return null; + } + + List resultList = getEntityManager() + .createNamedQuery("XXPortalUser.findByLoginId", tClass) + .setParameter("loginId", loginId).getResultList(); + + if (!resultList.isEmpty()) { + return resultList.get(0); + } + + return null; + } + + public XXPortalUser findByEmailAddress(String emailAddress) { + if (daoManager.getStringUtil().isEmpty(emailAddress)) { + return null; + } + + List resultList = getEntityManager() + .createNamedQuery("XXPortalUser.findByEmailAddress", tClass) + .setParameter("emailAddress", emailAddress) + .getResultList(); + + if (!resultList.isEmpty()) { + return resultList.get(0); + } - public XXPortalUserDao(RangerDaoManagerBase 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 findByRole(String userRole) { - return getEntityManager().createNamedQuery("XXPortalUser.findByRole") - .setParameter("userRole", userRole.toUpperCase()) - .getResultList(); - } - - @SuppressWarnings("unchecked") - public List getUserAddedReport(){ - return getEntityManager() - .createNamedQuery("XXPortalUser.getUserAddedReport") - .getResultList(); + return null; } - public XXPortalUser findByXUserId(Long xUserId) { - if (xUserId == null) { - return null; - } - try { - return getEntityManager().createNamedQuery("XXPortalUser.findByXUserId", tClass) - .setParameter("id", xUserId).getSingleResult(); - } catch (NoResultException e) { - return null; - } - } - - @SuppressWarnings("unchecked") - public List findAllXPortalUser() { - - try { - return getEntityManager().createNamedQuery( - "XXPortalUser.findAllXPortalUser").getResultList(); - - } catch (Exception e) { - return null; - } - - } - - @SuppressWarnings("unchecked") - public List getNonUserRoleExternalUsers() { - try { - return getEntityManager().createNamedQuery("XXPortalUser.getNonUserRoleExternalUsers", String.class) - .setParameter("userRole", RangerConstants.ROLE_USER) - .setParameter("userSource", RangerCommonEnums.USER_EXTERNAL) - .getResultList(); - } catch (Exception e) { - return null; - } - } - - public List findByUserSourceAndStatus(final int source, final int status) { - try { - return getEntityManager().createNamedQuery("XXPortalUser.findByUserSourceAndStatus", tClass) - .setParameter("userSource", source) - .setParameter("status", status) - .getResultList(); - } catch (Exception e) { - return null; - } - } - - public XXPortalUser findById(Long id) { - XXPortalUser xXPortalUser = null; - if (id == null) { - return xXPortalUser; - } - try { - xXPortalUser = new XXPortalUser(); - Object[] row = (Object[]) getEntityManager().createNamedQuery("XXPortalUser.findById").setParameter("id", id).getSingleResult(); - if (row != null) { - xXPortalUser.setFirstName((String) row[0]); - xXPortalUser.setLastName((String) row[1]); - xXPortalUser.setPublicScreenName((String) row[2]); - xXPortalUser.setLoginId((String) row[3]); - return xXPortalUser; - } - } catch (NoResultException e) { - return null; - } - return xXPortalUser; - } - - public Map getCountByUserRole() { - Map ret = Collections.emptyMap(); - List rows = (List) getEntityManager().createNamedQuery("XXPortalUser.getCountByUserRole").getResultList(); - if (rows != null) { - ret = new HashMap<>(); - for (Object[] row : rows) { - if (Objects.nonNull(row) && Objects.nonNull(row[0]) && Objects.nonNull(row[1]) && (!row[0].toString().isEmpty())) { - // since group by query will not return empty count field, no need to check - ret.put((String) row[0], (Long) row[1]); - } - } - } - return ret; - } + public List findByRole(String userRole) { + return getEntityManager().createNamedQuery("XXPortalUser.findByRole", tClass) + .setParameter("userRole", userRole.toUpperCase()) + .getResultList(); + } + + public List getUserAddedReport() { + return getEntityManager() + .createNamedQuery("XXPortalUser.getUserAddedReport", Object[].class) + .getResultList(); + } + + public XXPortalUser findByXUserId(Long xUserId) { + if (xUserId == null) { + return null; + } + + try { + return getEntityManager().createNamedQuery("XXPortalUser.findByXUserId", tClass) + .setParameter("id", xUserId).getSingleResult(); + } catch (NoResultException e) { + return null; + } + } + + public List findAllXPortalUser() { + try { + return getEntityManager().createNamedQuery("XXPortalUser.findAllXPortalUser", tClass).getResultList(); + } catch (Exception e) { + return null; + } + } + + public List getNonUserRoleExternalUsers() { + try { + return getEntityManager().createNamedQuery("XXPortalUser.getNonUserRoleExternalUsers", String.class) + .setParameter("userRole", RangerConstants.ROLE_USER) + .setParameter("userSource", RangerCommonEnums.USER_EXTERNAL) + .getResultList(); + } catch (Exception e) { + return null; + } + } + + public List findByUserSourceAndStatus(final int source, final int status) { + try { + return getEntityManager().createNamedQuery("XXPortalUser.findByUserSourceAndStatus", tClass) + .setParameter("userSource", source) + .setParameter("status", status) + .getResultList(); + } catch (Exception e) { + return null; + } + } + + public XXPortalUser findById(Long id) { + XXPortalUser xXPortalUser; + + if (id == null) { + return null; + } + + try { + xXPortalUser = new XXPortalUser(); + + Object[] row = getEntityManager().createNamedQuery("XXPortalUser.findById", Object[].class).setParameter("id", id).getSingleResult(); + + if (row != null) { + xXPortalUser.setFirstName((String) row[0]); + xXPortalUser.setLastName((String) row[1]); + xXPortalUser.setPublicScreenName((String) row[2]); + xXPortalUser.setLoginId((String) row[3]); + + return xXPortalUser; + } + } catch (NoResultException e) { + return null; + } + + return xXPortalUser; + } + + public Map getCountByUserRole() { + Map ret = Collections.emptyMap(); + List rows = getEntityManager().createNamedQuery("XXPortalUser.getCountByUserRole", Object[].class).getResultList(); + + if (rows != null) { + ret = new HashMap<>(); + + for (Object[] row : rows) { + if (Objects.nonNull(row) && Objects.nonNull(row[0]) && Objects.nonNull(row[1]) && (!row[0].toString().isEmpty())) { + // since group by query will not return empty count field, no need to check + ret.put((String) row[0], (Long) row[1]); + } + } + } + + return ret; + } } 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 index 8146c51e49..427b015905 100644 --- a/security-admin/src/main/java/org/apache/ranger/db/XXPortalUserRoleDao.java +++ b/security-admin/src/main/java/org/apache/ranger/db/XXPortalUserRoleDao.java @@ -17,59 +17,59 @@ * under the License. */ - package org.apache.ranger.db; - - -import java.util.ArrayList; -import java.util.List; - -import javax.persistence.NoResultException; +package org.apache.ranger.db; import org.apache.ranger.common.db.BaseDao; import org.apache.ranger.entity.XXPortalUserRole; import org.springframework.stereotype.Service; +import javax.persistence.NoResultException; + +import java.util.ArrayList; +import java.util.List; + @Service public class XXPortalUserRoleDao extends BaseDao { + public XXPortalUserRoleDao(RangerDaoManagerBase daoManager) { + super(daoManager); + } + + public List findByUserId(Long userId) { + if (userId == null) { + return new ArrayList<>(); + } + + return getEntityManager().createNamedQuery("XXPortalUserRole.findByUserId", tClass) + .setParameter("userId", userId).getResultList(); + } + + public XXPortalUserRole findByRoleUserId(Long userId, String role) { + if (userId == null || role == null || role.isEmpty()) { + return null; + } + + try { + return getEntityManager().createNamedQuery("XXPortalUserRole.findByRoleUserId", tClass) + .setParameter("userId", userId) + .setParameter("userRole", role).getSingleResult(); + } catch (NoResultException e) { + //doNothing; + } + + return null; + } - public XXPortalUserRoleDao(RangerDaoManagerBase daoManager) { - super(daoManager); - } + public List findXPortalUserRolebyXPortalUserId(Long userId) { + if (userId == null) { + return new ArrayList<>(); + } - @SuppressWarnings("unchecked") - public List findByUserId(Long userId) { - if (userId == null) { - return new ArrayList(); - } - 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; - } - @SuppressWarnings("unchecked") - public List findXPortalUserRolebyXPortalUserId(Long userId) { - if (userId == null) { - return new ArrayList(); - } - try { - List returnList = getEntityManager() - .createNamedQuery("XXPortalUserRole.findXPortalUserRolebyXPortalUserId") - .setParameter("userId", userId).getResultList(); - return returnList; - } catch (NoResultException e) { - return new ArrayList(); - } - } + try { + return getEntityManager() + .createNamedQuery("XXPortalUserRole.findXPortalUserRolebyXPortalUserId", String.class) + .setParameter("userId", userId).getResultList(); + } catch (NoResultException e) { + return new ArrayList<>(); + } + } } diff --git a/security-admin/src/main/java/org/apache/ranger/db/XXRMSMappingProviderDao.java b/security-admin/src/main/java/org/apache/ranger/db/XXRMSMappingProviderDao.java index fd52d6c3ec..9dd564c56a 100644 --- a/security-admin/src/main/java/org/apache/ranger/db/XXRMSMappingProviderDao.java +++ b/security-admin/src/main/java/org/apache/ranger/db/XXRMSMappingProviderDao.java @@ -17,22 +17,22 @@ package org.apache.ranger.db; -import java.util.Date; -import java.util.List; - -import javax.persistence.NoResultException; - import org.apache.ranger.common.db.BaseDao; import org.apache.ranger.entity.XXRMSMappingProvider; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; +import javax.persistence.NoResultException; + +import java.util.Date; +import java.util.List; + /** + * */ @Service public class XXRMSMappingProviderDao extends BaseDao { - private static final Logger LOG = LoggerFactory.getLogger(XXRMSMappingProviderDao.class); public XXRMSMappingProviderDao(RangerDaoManagerBase daoManager) { @@ -40,14 +40,14 @@ public XXRMSMappingProviderDao(RangerDaoManagerBase daoManager) { } public List getResource() { - List allResource = getAll(); - return allResource; + return getAll(); } public XXRMSMappingProvider findByName(String name) { if (name == null) { return null; } + try { return getEntityManager() .createNamedQuery("XXRMSMappingProvider.findByName", tClass) @@ -58,14 +58,12 @@ public XXRMSMappingProvider findByName(String name) { } public Long getLastKnownVersion(String providerName) { - XXRMSMappingProvider mappingProvider = findByName(providerName); return mappingProvider != null ? mappingProvider.getLastKnownVersion() : 0L; } public void updateLastKnownVersion(String providerName, long currentNotificationId) { - XXRMSMappingProvider mappingProvider = findByName(providerName); if (mappingProvider != null) { @@ -77,11 +75,7 @@ public void updateLastKnownVersion(String providerName, long currentNotification LOG.error("currentNotificationId cannot be set to a value less than -1"); } } else { - LOG.error("Cannot update lastKnownVersion for providerName:[" + providerName + "]"); + LOG.error("Cannot update lastKnownVersion for providerName:[{}]", providerName); } } - - - } - diff --git a/security-admin/src/main/java/org/apache/ranger/db/XXRMSNotificationDao.java b/security-admin/src/main/java/org/apache/ranger/db/XXRMSNotificationDao.java index 2b6cf1a34a..b5f2a4c94e 100644 --- a/security-admin/src/main/java/org/apache/ranger/db/XXRMSNotificationDao.java +++ b/security-admin/src/main/java/org/apache/ranger/db/XXRMSNotificationDao.java @@ -17,11 +17,6 @@ package org.apache.ranger.db; -import java.util.ArrayList; -import java.util.List; - -import javax.persistence.NoResultException; - import org.apache.commons.collections.CollectionUtils; import org.apache.ranger.common.db.BaseDao; import org.apache.ranger.entity.XXRMSNotification; @@ -29,95 +24,110 @@ import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; +import javax.persistence.NoResultException; + +import java.util.ArrayList; +import java.util.List; + /** + * */ @Service public class XXRMSNotificationDao extends BaseDao { - - private static final Logger LOG = LoggerFactory.getLogger(XXRMSNotificationDao.class); - - public XXRMSNotificationDao(RangerDaoManagerBase daoManager) { - super(daoManager); - } - - public List getResource() { - List allResource = getAll(); - return allResource; - } - - public Long getMaxIdOfNotifications(long llServiceId, long hlServiceId) { - Long lastNotificationId = 0L; - try { - lastNotificationId = getEntityManager() - .createNamedQuery("XXRMSNotification.getMaxIdOfNotifications", Long.class) - .setParameter("llServiceId", llServiceId) - .setParameter("hlServiceId", hlServiceId) - .getSingleResult(); - - } catch (NoResultException e) { - LOG.debug(e.getMessage()); - } finally{ - if (lastNotificationId == null){ - lastNotificationId = 0L; - } - } - return lastNotificationId; - } - - public List getAllAfterNotificationId(long llServiceId, long hlServiceId, long notificationId) { - List notifications = new ArrayList<>(); - try { - notifications = getEntityManager() - .createNamedQuery("XXRMSNotification.getAllAfterNotificationId", XXRMSNotification.class) - .setParameter("llServiceId", llServiceId) - .setParameter("hlServiceId", hlServiceId) - .setParameter("notificationId", notificationId) - .getResultList(); - } catch (NoResultException e) { - LOG.debug("There are no relevant notifications after notification_id:[" + notificationId + "]"); - } - return notifications; - } - - public Long findLatestInvalidNotificationId(long llServiceId, long hlServiceId, long lastKnownVersion) { - Long latestInvalidNotificationId = -1L; - - List notifications = getNotificationWithTypeAfterNotificationId(llServiceId, hlServiceId, "invalid", lastKnownVersion); - - if (CollectionUtils.isNotEmpty(notifications)) { - latestInvalidNotificationId = notifications.get(notifications.size()-1).getNotificationId(); - } - - return latestInvalidNotificationId; - } - - public List getNotificationWithTypeAfterNotificationId(long llServiceId, long hlServiceId, String changeType, long notificationId) { - List notifications = new ArrayList<>(); - try { - notifications = getEntityManager() - .createNamedQuery("XXRMSNotification.getNotificationWithTypeAfterNotificationId", XXRMSNotification.class) - .setParameter("llServiceId", llServiceId) - .setParameter("hlServiceId", hlServiceId) - .setParameter("changeType", changeType) - .setParameter("notificationId", notificationId) - .getResultList(); - } catch (NoResultException e) { - - } - return notifications; - } - - public List getDeletedNotificationsByHlResourceId(long hlResourceId, long lastKnownVersion) { - List notifications = new ArrayList<>(); - try { - notifications = getEntityManager() - .createNamedQuery("XXRMSNotification.getDeletedNotificationsByHlResourceId", XXRMSNotification.class) - .setParameter("hlResourceId", hlResourceId) - .setParameter("lastKnownVersion", lastKnownVersion) - .getResultList(); - } catch (NoResultException e) { - - } - return notifications; - } + private static final Logger LOG = LoggerFactory.getLogger(XXRMSNotificationDao.class); + + public XXRMSNotificationDao(RangerDaoManagerBase daoManager) { + super(daoManager); + } + + public List getResource() { + return getAll(); + } + + public Long getMaxIdOfNotifications(long llServiceId, long hlServiceId) { + Long lastNotificationId = 0L; + + try { + lastNotificationId = getEntityManager() + .createNamedQuery("XXRMSNotification.getMaxIdOfNotifications", Long.class) + .setParameter("llServiceId", llServiceId) + .setParameter("hlServiceId", hlServiceId) + .getSingleResult(); + } catch (NoResultException e) { + LOG.debug(e.getMessage()); + } finally { + if (lastNotificationId == null) { + lastNotificationId = 0L; + } + } + + return lastNotificationId; + } + + public List getAllAfterNotificationId(long llServiceId, long hlServiceId, long notificationId) { + List notifications; + + try { + notifications = getEntityManager() + .createNamedQuery("XXRMSNotification.getAllAfterNotificationId", XXRMSNotification.class) + .setParameter("llServiceId", llServiceId) + .setParameter("hlServiceId", hlServiceId) + .setParameter("notificationId", notificationId) + .getResultList(); + } catch (NoResultException e) { + LOG.debug("There are no relevant notifications after notification_id:[{}]", notificationId); + + notifications = new ArrayList<>(); + } + + return notifications; + } + + public Long findLatestInvalidNotificationId(long llServiceId, long hlServiceId, long lastKnownVersion) { + List notifications = getNotificationWithTypeAfterNotificationId(llServiceId, hlServiceId, "invalid", lastKnownVersion); + + Long latestInvalidNotificationId; + + if (CollectionUtils.isNotEmpty(notifications)) { + latestInvalidNotificationId = notifications.get(notifications.size() - 1).getNotificationId(); + } else { + latestInvalidNotificationId = -1L; + } + + return latestInvalidNotificationId; + } + + public List getNotificationWithTypeAfterNotificationId(long llServiceId, long hlServiceId, String changeType, long notificationId) { + List notifications; + + try { + notifications = getEntityManager() + .createNamedQuery("XXRMSNotification.getNotificationWithTypeAfterNotificationId", XXRMSNotification.class) + .setParameter("llServiceId", llServiceId) + .setParameter("hlServiceId", hlServiceId) + .setParameter("changeType", changeType) + .setParameter("notificationId", notificationId) + .getResultList(); + } catch (NoResultException e) { + notifications = new ArrayList<>(); + } + + return notifications; + } + + public List getDeletedNotificationsByHlResourceId(long hlResourceId, long lastKnownVersion) { + List notifications; + + try { + notifications = getEntityManager() + .createNamedQuery("XXRMSNotification.getDeletedNotificationsByHlResourceId", XXRMSNotification.class) + .setParameter("hlResourceId", hlResourceId) + .setParameter("lastKnownVersion", lastKnownVersion) + .getResultList(); + } catch (NoResultException e) { + notifications = new ArrayList<>(); + } + + return notifications; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/db/XXRMSResourceMappingDao.java b/security-admin/src/main/java/org/apache/ranger/db/XXRMSResourceMappingDao.java index 763e1ae683..93d0852418 100644 --- a/security-admin/src/main/java/org/apache/ranger/db/XXRMSResourceMappingDao.java +++ b/security-admin/src/main/java/org/apache/ranger/db/XXRMSResourceMappingDao.java @@ -17,117 +17,116 @@ package org.apache.ranger.db; -import java.util.ArrayList; -import java.util.List; - -import javax.persistence.NoResultException; - import org.apache.commons.collections.CollectionUtils; import org.apache.ranger.common.db.BaseDao; -import org.apache.ranger.plugin.model.RangerServiceResource; import org.apache.ranger.entity.XXRMSResourceMapping; import org.apache.ranger.entity.XXRMSServiceResource; +import org.apache.ranger.plugin.model.RangerServiceResource; import org.springframework.stereotype.Service; -/** - */ -@Service -public class XXRMSResourceMappingDao extends BaseDao { +import javax.persistence.NoResultException; - //private static final Log LOG = LogFactory.getLog(XXRMSResourceMappingDao.class); - - public XXRMSResourceMappingDao(RangerDaoManagerBase daoManager) { - super(daoManager); - } - - @SuppressWarnings("unchecked") - public List getResourceMappings() { - return getEntityManager().createNamedQuery("XXRMSResourceMapping.getResourceMapping").getResultList(); - } - - public void deleteByHlResourceId(Long resourceId) { - getEntityManager() - .createNamedQuery("XXRMSResourceMapping.deleteByHlResourceId") - .setParameter("resourceId", resourceId) - .executeUpdate(); - } - - public void deleteByLlResourceId(Long resourceId) { - getEntityManager() - .createNamedQuery("XXRMSResourceMapping.deleteByLlResourceId") - .setParameter("resourceId", resourceId) - .executeUpdate(); - } - - public void deleteByHlAndLlResourceId(Long hlResourceId, Long llResourceId) { - getEntityManager() - .createNamedQuery("XXRMSResourceMapping.deleteByHlAndLlResourceId") - .setParameter("hlResourceId", hlResourceId) - .setParameter("llResourceId", llResourceId) - .executeUpdate(); - } - - public XXRMSResourceMapping findByHlAndLlResourceId(Long hlResourceId, Long llResourceId) { - try { - return getEntityManager() - .createNamedQuery("XXRMSResourceMapping.findByHlAndLlResourceId", XXRMSResourceMapping.class) - .setParameter("hlResourceId", hlResourceId) - .setParameter("llResourceId", llResourceId) - .getSingleResult(); - } catch (NoResultException e) { - } - return null; - } - - public List findByHlResource(RangerServiceResource hlResource) { - return findByHlResourceId(hlResource.getId()); - } - - public List findByHlResourceId(Long hlResourceId) { - return getEntityManager() - .createNamedQuery("XXRMSResourceMapping.findByHlResourceId", Long.class) - .setParameter("hlResourceId", hlResourceId) - .getResultList(); - } - - public List findByLlResource(RangerServiceResource llResource) { - return findByLlResourceId(llResource.getId()); - } - - public List findByLlResourceId(Long llResourceId) { - return getEntityManager() - .createNamedQuery("XXRMSResourceMapping.findByLlResourceId", Long.class) - .setParameter("llResourceId", llResourceId) - .getResultList(); - } - - public List getServiceResourcesByLlResourceId(long llResourceId) { - List ret = new ArrayList<>(); - - List rows = null; - try { - rows = getEntityManager() - .createNamedQuery("XXRMSResourceMapping.getServiceResourcesByLlResourceId", Object[].class) - .setParameter("llResourceId", llResourceId) - .getResultList(); - } catch (NoResultException e) { - // Nothing - } - - if (CollectionUtils.isNotEmpty(rows)) { - for (Object[] row : rows) { - XXRMSServiceResource xxServiceResource = new XXRMSServiceResource(); - xxServiceResource.setId((Long) row[0]); - xxServiceResource.setGuid((String) row[1]); - xxServiceResource.setVersion((Long) row[2]); - xxServiceResource.setIsEnabled((Boolean) row[3]); - xxServiceResource.setResourceSignature((String) row[4]); - xxServiceResource.setServiceId((Long) row[5]); - xxServiceResource.setServiceResourceElements((String) row[6]); - ret.add(XXRMSServiceResourceDao.populateViewBean(xxServiceResource)); - } - } - return ret; - } +import java.util.ArrayList; +import java.util.List; +@Service +public class XXRMSResourceMappingDao extends BaseDao { + public XXRMSResourceMappingDao(RangerDaoManagerBase daoManager) { + super(daoManager); + } + + public List getResourceMappings() { + return getEntityManager().createNamedQuery("XXRMSResourceMapping.getResourceMapping", Object[].class).getResultList(); + } + + public void deleteByHlResourceId(Long resourceId) { + getEntityManager() + .createNamedQuery("XXRMSResourceMapping.deleteByHlResourceId") + .setParameter("resourceId", resourceId) + .executeUpdate(); + } + + public void deleteByLlResourceId(Long resourceId) { + getEntityManager() + .createNamedQuery("XXRMSResourceMapping.deleteByLlResourceId") + .setParameter("resourceId", resourceId) + .executeUpdate(); + } + + public void deleteByHlAndLlResourceId(Long hlResourceId, Long llResourceId) { + getEntityManager() + .createNamedQuery("XXRMSResourceMapping.deleteByHlAndLlResourceId") + .setParameter("hlResourceId", hlResourceId) + .setParameter("llResourceId", llResourceId) + .executeUpdate(); + } + + public XXRMSResourceMapping findByHlAndLlResourceId(Long hlResourceId, Long llResourceId) { + try { + return getEntityManager() + .createNamedQuery("XXRMSResourceMapping.findByHlAndLlResourceId", XXRMSResourceMapping.class) + .setParameter("hlResourceId", hlResourceId) + .setParameter("llResourceId", llResourceId) + .getSingleResult(); + } catch (NoResultException e) { + // ignore + } + + return null; + } + + public List findByHlResource(RangerServiceResource hlResource) { + return findByHlResourceId(hlResource.getId()); + } + + public List findByHlResourceId(Long hlResourceId) { + return getEntityManager() + .createNamedQuery("XXRMSResourceMapping.findByHlResourceId", Long.class) + .setParameter("hlResourceId", hlResourceId) + .getResultList(); + } + + public List findByLlResource(RangerServiceResource llResource) { + return findByLlResourceId(llResource.getId()); + } + + public List findByLlResourceId(Long llResourceId) { + return getEntityManager() + .createNamedQuery("XXRMSResourceMapping.findByLlResourceId", Long.class) + .setParameter("llResourceId", llResourceId) + .getResultList(); + } + + public List getServiceResourcesByLlResourceId(long llResourceId) { + List ret = new ArrayList<>(); + + List rows = null; + + try { + rows = getEntityManager() + .createNamedQuery("XXRMSResourceMapping.getServiceResourcesByLlResourceId", Object[].class) + .setParameter("llResourceId", llResourceId) + .getResultList(); + } catch (NoResultException e) { + // Nothing + } + + if (CollectionUtils.isNotEmpty(rows)) { + for (Object[] row : rows) { + XXRMSServiceResource xxServiceResource = new XXRMSServiceResource(); + + xxServiceResource.setId((Long) row[0]); + xxServiceResource.setGuid((String) row[1]); + xxServiceResource.setVersion((Long) row[2]); + xxServiceResource.setIsEnabled((Boolean) row[3]); + xxServiceResource.setResourceSignature((String) row[4]); + xxServiceResource.setServiceId((Long) row[5]); + xxServiceResource.setServiceResourceElements((String) row[6]); + + ret.add(XXRMSServiceResourceDao.populateViewBean(xxServiceResource)); + } + } + + return ret; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/db/XXRMSServiceResourceDao.java b/security-admin/src/main/java/org/apache/ranger/db/XXRMSServiceResourceDao.java index 8a7f08e8df..6ea6ec84ea 100644 --- a/security-admin/src/main/java/org/apache/ranger/db/XXRMSServiceResourceDao.java +++ b/security-admin/src/main/java/org/apache/ranger/db/XXRMSServiceResourceDao.java @@ -19,233 +19,244 @@ package org.apache.ranger.db; -import java.util.ArrayList; -import java.util.List; -import javax.persistence.NoResultException; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang.StringUtils; import org.apache.ranger.authorization.utils.StringUtil; import org.apache.ranger.common.DateUtil; import org.apache.ranger.common.GUIDUtil; import org.apache.ranger.common.db.BaseDao; -import org.apache.ranger.entity.XXService; import org.apache.ranger.entity.XXRMSServiceResource; +import org.apache.ranger.entity.XXService; import org.apache.ranger.plugin.model.RangerServiceResource; import org.apache.ranger.plugin.store.StoredServiceResource; import org.apache.ranger.plugin.util.JsonUtilsV2; import org.springframework.stereotype.Service; +import javax.persistence.NoResultException; + +import java.util.ArrayList; +import java.util.List; + @Service public class XXRMSServiceResourceDao extends BaseDao { - - private static RangerDaoManagerBase _daoManager = null; - - public XXRMSServiceResourceDao(RangerDaoManagerBase daoManager) { - super(daoManager); - _daoManager = daoManager; - } - - public XXRMSServiceResource findByGuid(String guid) { - if (StringUtil.isEmpty(guid)) { - return null; - } - try { - return getEntityManager().createNamedQuery("XXRMSServiceResource.findByGuid", tClass) - .setParameter("guid", guid).getSingleResult(); - } catch (NoResultException e) { - return null; - } - } - - public List findByServiceId(Long serviceId) { - List ret = new ArrayList<>(); - - if (serviceId != null) { - List rows = null; - try { - rows = getEntityManager() - .createNamedQuery("XXRMSServiceResource.findByServiceId", Object[].class) - .setParameter("serviceId", serviceId).getResultList(); - } catch (NoResultException e) { - // Nothing - } - - if (CollectionUtils.isNotEmpty(rows)) { - for (Object[] row : rows) { - XXRMSServiceResource xxServiceResource = new XXRMSServiceResource(); - xxServiceResource.setId((Long) row[0]); - xxServiceResource.setGuid((String) row[1]); - xxServiceResource.setVersion((Long) row[2]); - xxServiceResource.setIsEnabled((Boolean) row[3]); - xxServiceResource.setResourceSignature((String) row[4]); - xxServiceResource.setServiceId((Long) row[5]); - xxServiceResource.setServiceResourceElements((String) row[6]); - ret.add(XXRMSServiceResourceDao.populateViewBean(xxServiceResource)); - } - } - } - return ret; - } - - public XXRMSServiceResource findByServiceAndResourceSignature(Long serviceId, String resourceSignature) { - if (StringUtils.isBlank(resourceSignature)) { - return null; - } - try { - return getEntityManager().createNamedQuery("XXRMSServiceResource.findByServiceAndResourceSignature", tClass) - .setParameter("serviceId", serviceId).setParameter("resourceSignature", resourceSignature) - .getSingleResult(); - } catch (NoResultException e) { - return null; - } - } - - public RangerServiceResource getServiceResourceByServiceAndResourceSignature(String serviceName, String resourceSignature) { - RangerServiceResource ret = null; - - if (StringUtils.isNotBlank(resourceSignature)) { - Long serviceId = daoManager.getXXService().findIdByName(serviceName); - - if (serviceId != null) { - try { - XXRMSServiceResource xxServiceResource = getEntityManager().createNamedQuery("XXRMSServiceResource.findByServiceAndResourceSignature", tClass) - .setParameter("serviceId", serviceId).setParameter("resourceSignature", resourceSignature) - .getSingleResult(); - ret = populateViewBean(xxServiceResource); - - } catch (NoResultException e) { - return null; - } - } - } - - return ret; - } - - public static RangerServiceResource populateViewBean(XXRMSServiceResource xxServiceResource) { - - RangerServiceResource ret = null; - - XXService service = _daoManager == null ? null : _daoManager.getXXService().getById(xxServiceResource.getServiceId()); - - if (service != null) { - ret = new RangerServiceResource(); - ret.setId(xxServiceResource.getId()); - ret.setCreateTime(xxServiceResource.getCreateTime()); - ret.setUpdateTime(xxServiceResource.getUpdateTime()); - ret.setGuid(xxServiceResource.getGuid()); - ret.setResourceSignature(xxServiceResource.getResourceSignature()); - - ret.setServiceName(service.getName()); - - if (StringUtils.isNotEmpty(xxServiceResource.getServiceResourceElements())) { - try { - StoredServiceResource storedServiceResource = JsonUtilsV2.jsonToObj(xxServiceResource.getServiceResourceElements(), StoredServiceResource.class); - ret.setResourceElements(storedServiceResource.getResourceElements()); - ret.setOwnerUser(storedServiceResource.getOwnerName()); - ret.setAdditionalInfo(storedServiceResource.getAdditionalInfo()); - } catch (Exception e){ - ret = null; - } - } else { - ret = null; - } - } - - return ret; - } - - public XXRMSServiceResource populateEntityBean(RangerServiceResource serviceResource) { - - XXRMSServiceResource ret = new XXRMSServiceResource(); - - ret.setId(serviceResource.getId()); - ret.setCreateTime(serviceResource.getCreateTime() != null ? serviceResource.getCreateTime() : DateUtil.getUTCDate()); - ret.setUpdateTime(serviceResource.getUpdateTime() != null ? serviceResource.getUpdateTime() : DateUtil.getUTCDate()); - ret.setAddedByUserId(0L); - ret.setUpdatedByUserId(0L); - - String guid = (StringUtils.isEmpty(serviceResource.getGuid())) ? new GUIDUtil().genGUID() : serviceResource.getGuid(); - - ret.setGuid(guid); - ret.setVersion(serviceResource.getVersion()); - ret.setIsEnabled(serviceResource.getIsEnabled()); - ret.setResourceSignature(serviceResource.getResourceSignature()); - - Long serviceId = daoManager.getXXService().findIdByName(serviceResource.getServiceName()); - - if (serviceId != null) { - ret.setServiceId(serviceId); - - StoredServiceResource storedServiceResource = new StoredServiceResource(serviceResource.getResourceElements(), serviceResource.getOwnerUser(), serviceResource.getAdditionalInfo()); - try { - String serviceResourceString = JsonUtilsV2.objToJson(storedServiceResource); - ret.setServiceResourceElements(serviceResourceString); - } catch (Exception e) { - ret = null; - } - - } else { - ret = null; - } - - return ret; - } - - public RangerServiceResource createServiceResource(RangerServiceResource viewObject) { - XXRMSServiceResource dbObject = populateEntityBean(viewObject); - if (dbObject != null) { - dbObject = daoManager.getXXRMSServiceResource().create(dbObject); - if (dbObject != null) { - return populateViewBean(dbObject); - } - } - return null; - } - - public void deleteById(Long serviceResourceId) { - getEntityManager() - .createNamedQuery("XXRMSServiceResource.deleteById") - .setParameter("resourceId", serviceResourceId) - .executeUpdate(); - } - - public List findByLlServiceId(long llServiceId) { - return findByServiceId(llServiceId); - } - - public List getLlResourceIdForHlResourceId(long hlResourceId, long lastKnownVersion) { - List ret = new ArrayList<>(); - try { - List list = getEntityManager().createNamedQuery("XXRMSServiceResource.getLlResourceIdForHlResourceId", tClass) - .setParameter("hlResourceId", hlResourceId) - .setParameter("lastKnownVersion", lastKnownVersion) - .getResultList(); - if (CollectionUtils.isNotEmpty(list)) { - //ret = list.stream().map(XXRMSServiceResourceDao::populateViewBean).collect(Collectors.toList()); - for (XXRMSServiceResource entityBean : list) { - RangerServiceResource viewBean = populateViewBean(entityBean); - ret.add(viewBean); - } - } - } catch (NoResultException e) { - } - return ret; - } - - public void purge(long serviceId) { - - getEntityManager().createNamedQuery("XXRMSNotification.deleteByServiceId") - .setParameter("serviceId", serviceId) - .executeUpdate(); - - getEntityManager().createNamedQuery("XXRMSResourceMapping.deleteByServiceId") - .setParameter("serviceId", serviceId) - .executeUpdate(); - - getEntityManager().createNamedQuery("XXRMSServiceResource.deleteByServiceId") - .setParameter("serviceId", serviceId) - .executeUpdate(); - - } + private static RangerDaoManagerBase daoManagerBase; + + public XXRMSServiceResourceDao(RangerDaoManagerBase daoManager) { + super(daoManager); + + daoManagerBase = daoManager; + } + + public static RangerServiceResource populateViewBean(XXRMSServiceResource xxServiceResource) { + RangerServiceResource ret = null; + + XXService service = daoManagerBase == null ? null : daoManagerBase.getXXService().getById(xxServiceResource.getServiceId()); + + if (service != null) { + ret = new RangerServiceResource(); + + ret.setId(xxServiceResource.getId()); + ret.setCreateTime(xxServiceResource.getCreateTime()); + ret.setUpdateTime(xxServiceResource.getUpdateTime()); + ret.setGuid(xxServiceResource.getGuid()); + ret.setResourceSignature(xxServiceResource.getResourceSignature()); + ret.setServiceName(service.getName()); + + if (StringUtils.isNotEmpty(xxServiceResource.getServiceResourceElements())) { + try { + StoredServiceResource storedServiceResource = JsonUtilsV2.jsonToObj(xxServiceResource.getServiceResourceElements(), StoredServiceResource.class); + + ret.setResourceElements(storedServiceResource.getResourceElements()); + ret.setOwnerUser(storedServiceResource.getOwnerName()); + ret.setAdditionalInfo(storedServiceResource.getAdditionalInfo()); + } catch (Exception e) { + ret = null; + } + } else { + ret = null; + } + } + + return ret; + } + + public XXRMSServiceResource findByGuid(String guid) { + if (StringUtil.isEmpty(guid)) { + return null; + } + + try { + return getEntityManager().createNamedQuery("XXRMSServiceResource.findByGuid", tClass) + .setParameter("guid", guid).getSingleResult(); + } catch (NoResultException e) { + return null; + } + } + + public List findByServiceId(Long serviceId) { + List ret = new ArrayList<>(); + + if (serviceId != null) { + List rows = null; + + try { + rows = getEntityManager() + .createNamedQuery("XXRMSServiceResource.findByServiceId", Object[].class) + .setParameter("serviceId", serviceId).getResultList(); + } catch (NoResultException e) { + // Nothing + } + + if (CollectionUtils.isNotEmpty(rows)) { + for (Object[] row : rows) { + XXRMSServiceResource xxServiceResource = new XXRMSServiceResource(); + xxServiceResource.setId((Long) row[0]); + xxServiceResource.setGuid((String) row[1]); + xxServiceResource.setVersion((Long) row[2]); + xxServiceResource.setIsEnabled((Boolean) row[3]); + xxServiceResource.setResourceSignature((String) row[4]); + xxServiceResource.setServiceId((Long) row[5]); + xxServiceResource.setServiceResourceElements((String) row[6]); + ret.add(XXRMSServiceResourceDao.populateViewBean(xxServiceResource)); + } + } + } + return ret; + } + + public XXRMSServiceResource findByServiceAndResourceSignature(Long serviceId, String resourceSignature) { + if (StringUtils.isBlank(resourceSignature)) { + return null; + } + + try { + return getEntityManager().createNamedQuery("XXRMSServiceResource.findByServiceAndResourceSignature", tClass) + .setParameter("serviceId", serviceId).setParameter("resourceSignature", resourceSignature) + .getSingleResult(); + } catch (NoResultException e) { + return null; + } + } + + public RangerServiceResource getServiceResourceByServiceAndResourceSignature(String serviceName, String resourceSignature) { + RangerServiceResource ret = null; + + if (StringUtils.isNotBlank(resourceSignature)) { + Long serviceId = daoManager.getXXService().findIdByName(serviceName); + + if (serviceId != null) { + try { + XXRMSServiceResource xxServiceResource = getEntityManager().createNamedQuery("XXRMSServiceResource.findByServiceAndResourceSignature", tClass) + .setParameter("serviceId", serviceId).setParameter("resourceSignature", resourceSignature) + .getSingleResult(); + + ret = populateViewBean(xxServiceResource); + } catch (NoResultException e) { + return null; + } + } + } + + return ret; + } + + public XXRMSServiceResource populateEntityBean(RangerServiceResource serviceResource) { + XXRMSServiceResource ret = new XXRMSServiceResource(); + + ret.setId(serviceResource.getId()); + ret.setCreateTime(serviceResource.getCreateTime() != null ? serviceResource.getCreateTime() : DateUtil.getUTCDate()); + ret.setUpdateTime(serviceResource.getUpdateTime() != null ? serviceResource.getUpdateTime() : DateUtil.getUTCDate()); + ret.setAddedByUserId(0L); + ret.setUpdatedByUserId(0L); + + String guid = (StringUtils.isEmpty(serviceResource.getGuid())) ? new GUIDUtil().genGUID() : serviceResource.getGuid(); + + ret.setGuid(guid); + ret.setVersion(serviceResource.getVersion()); + ret.setIsEnabled(serviceResource.getIsEnabled()); + ret.setResourceSignature(serviceResource.getResourceSignature()); + + Long serviceId = daoManager.getXXService().findIdByName(serviceResource.getServiceName()); + + if (serviceId != null) { + ret.setServiceId(serviceId); + + StoredServiceResource storedServiceResource = new StoredServiceResource(serviceResource.getResourceElements(), serviceResource.getOwnerUser(), serviceResource.getAdditionalInfo()); + + try { + String serviceResourceString = JsonUtilsV2.objToJson(storedServiceResource); + + ret.setServiceResourceElements(serviceResourceString); + } catch (Exception e) { + ret = null; + } + } else { + ret = null; + } + + return ret; + } + + public RangerServiceResource createServiceResource(RangerServiceResource viewObject) { + XXRMSServiceResource dbObject = populateEntityBean(viewObject); + + if (dbObject != null) { + dbObject = daoManager.getXXRMSServiceResource().create(dbObject); + + if (dbObject != null) { + return populateViewBean(dbObject); + } + } + + return null; + } + + public void deleteById(Long serviceResourceId) { + getEntityManager() + .createNamedQuery("XXRMSServiceResource.deleteById") + .setParameter("resourceId", serviceResourceId) + .executeUpdate(); + } + + public List findByLlServiceId(long llServiceId) { + return findByServiceId(llServiceId); + } + + public List getLlResourceIdForHlResourceId(long hlResourceId, long lastKnownVersion) { + List ret = new ArrayList<>(); + + try { + List list = getEntityManager().createNamedQuery("XXRMSServiceResource.getLlResourceIdForHlResourceId", tClass) + .setParameter("hlResourceId", hlResourceId) + .setParameter("lastKnownVersion", lastKnownVersion) + .getResultList(); + + if (CollectionUtils.isNotEmpty(list)) { + //ret = list.stream().map(XXRMSServiceResourceDao::populateViewBean).collect(Collectors.toList()); + for (XXRMSServiceResource entityBean : list) { + RangerServiceResource viewBean = populateViewBean(entityBean); + + ret.add(viewBean); + } + } + } catch (NoResultException e) { + // ignore + } + + return ret; + } + + public void purge(long serviceId) { + getEntityManager().createNamedQuery("XXRMSNotification.deleteByServiceId") + .setParameter("serviceId", serviceId) + .executeUpdate(); + + getEntityManager().createNamedQuery("XXRMSResourceMapping.deleteByServiceId") + .setParameter("serviceId", serviceId) + .executeUpdate(); + + getEntityManager().createNamedQuery("XXRMSServiceResource.deleteByServiceId") + .setParameter("serviceId", serviceId) + .executeUpdate(); + } } 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 index 09bd3099f5..2da5ff7b64 100644 --- a/security-admin/src/main/java/org/apache/ranger/db/XXResourceDao.java +++ b/security-admin/src/main/java/org/apache/ranger/db/XXResourceDao.java @@ -17,15 +17,7 @@ * under the License. */ - package org.apache.ranger.db; - - -import java.sql.Timestamp; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; - -import javax.persistence.NoResultException; +package org.apache.ranger.db; import org.apache.ranger.common.db.BaseDao; import org.apache.ranger.entity.XXResource; @@ -33,244 +25,236 @@ import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; +import javax.persistence.NoResultException; + +import java.sql.Timestamp; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + @Service public class XXResourceDao extends BaseDao { - private static final Logger logger = LoggerFactory.getLogger(XXResourceDao.class); - - public XXResourceDao(RangerDaoManagerBase 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 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(); - } - return null; - } - - public List findByAssetId(Long assetId) { - List 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(); - } - } else { - logger.debug("AssetId not provided."); - xResourceList = new ArrayList(); - } - return xResourceList; - } - - public List findByAssetType(Integer assetType) { - List 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(); - } - } else { - logger.debug("AssetType not provided."); - xResourceList = new ArrayList(); - } - 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 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(); - } - return null; - } - - public List 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 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 findByAssetIdAndResourceTypes(Long assetId, - List resourceType) { - if (assetId == null) { - logger.debug("assetId is null"); - return null; - } - try { - StringBuilder query = new StringBuilder( - "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 resourceTypes) { - StringBuilder whereClause = new StringBuilder(); - 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 findByAssetIdAndResourceStatus(Long assetId, int resourceStatus) { - List 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(); - } - } else { - logger.debug("AssetId not provided."); - xResourceList = new ArrayList(); - } - return xResourceList; - } + private static final Logger logger = LoggerFactory.getLogger(XXResourceDao.class); + + public XXResourceDao(RangerDaoManagerBase 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 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<>(); + } + + return null; + } + + public List findByAssetId(Long assetId) { + List xResourceList = null; + + if (assetId != null) { + try { + xResourceList = getEntityManager().createNamedQuery("XXResource.findByAssetId", XXResource.class).setParameter("assetId", assetId).getResultList(); + } catch (NoResultException e) { + logger.debug(e.getMessage()); + } + + if (xResourceList == null) { + xResourceList = new ArrayList<>(); + } + } else { + logger.debug("AssetId not provided."); + + xResourceList = new ArrayList<>(); + } + + return xResourceList; + } + + public List findByAssetType(Integer assetType) { + List xResourceList = null; + + if (assetType != null) { + try { + xResourceList = getEntityManager().createNamedQuery("XXResource.findByAssetType", XXResource.class).setParameter("assetType", assetType).getResultList(); + } catch (NoResultException e) { + logger.debug(e.getMessage()); + } + + if (xResourceList == null) { + xResourceList = new ArrayList<>(); + } + } else { + logger.debug("AssetType not provided."); + + xResourceList = new ArrayList<>(); + } + + 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) { + return new Timestamp(date.getTime()); + } else { + return null; + } + } catch (NoResultException e) { + // ignore + } + return null; + } + + public List 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<>(); + } + + return null; + } + + public List 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() + "%"; + + 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 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() + "%"; + + return getEntityManager().createNamedQuery("XXResource.findByResourceNameAndAssetIdAndResourceType", XXResource.class).setParameter("name", resourceName).setParameter("assetId", assetId).setParameter("resourceType", resourceType).getResultList(); + } catch (NoResultException e) { + // ignore + } + + return null; + } + + public List findByAssetIdAndResourceTypes(Long assetId, List resourceType) { + if (assetId == null) { + logger.debug("assetId is null"); + + return null; + } + + try { + StringBuilder query = new StringBuilder("SELECT obj FROM XXResource obj WHERE obj.assetId=" + assetId); + String whereClause = makeWhereClauseForResourceType(resourceType); + + if (!whereClause.trim().isEmpty()) { + query.append(" and ( ").append(whereClause).append(" )"); + } + + return getEntityManager().createQuery(query.toString(), tClass).getResultList(); + } catch (NoResultException e) { + // ignore + } + + return null; + } + + public List findByAssetIdAndResourceStatus(Long assetId, int resourceStatus) { + List xResourceList = null; + + if (assetId != null) { + try { + xResourceList = getEntityManager().createNamedQuery("XXResource.findByAssetIdAndResourceStatus", XXResource.class).setParameter("assetId", assetId).setParameter("resourceStatus", resourceStatus).getResultList(); + } catch (NoResultException e) { + logger.debug(e.getMessage()); + } + + if (xResourceList == null) { + xResourceList = new ArrayList<>(); + } + } else { + logger.debug("AssetId not provided."); + + xResourceList = new ArrayList<>(); + } + + return xResourceList; + } + + private String makeWhereClauseForResourceType(List resourceTypes) { + StringBuilder whereClause = new StringBuilder(); + + if (resourceTypes != null && !resourceTypes.isEmpty()) { + for (int i = 0; i < resourceTypes.size() - 1; i++) { + whereClause.append("obj.resourceType=").append(resourceTypes.get(i)).append(" OR "); + } + + whereClause.append("obj.resourceType=").append(resourceTypes.get(resourceTypes.size() - 1)); + } + + return whereClause.toString(); + } } diff --git a/security-admin/src/main/java/org/apache/ranger/db/XXResourceDefDao.java b/security-admin/src/main/java/org/apache/ranger/db/XXResourceDefDao.java index 56139027b8..bc0b064318 100644 --- a/security-admin/src/main/java/org/apache/ranger/db/XXResourceDefDao.java +++ b/security-admin/src/main/java/org/apache/ranger/db/XXResourceDefDao.java @@ -17,86 +17,88 @@ package org.apache.ranger.db; -import java.util.ArrayList; -import java.util.List; - -import javax.persistence.NoResultException; - import org.apache.ranger.common.db.BaseDao; import org.apache.ranger.entity.XXResourceDef; import org.springframework.stereotype.Service; +import javax.persistence.NoResultException; + +import java.util.ArrayList; +import java.util.List; + @Service public class XXResourceDefDao extends BaseDao { + public XXResourceDefDao(RangerDaoManagerBase daoMgr) { + super(daoMgr); + } + + public XXResourceDef findByNameAndServiceDefId(String name, Long defId) { + if (name == null || defId == null) { + return null; + } + + try { + return getEntityManager().createNamedQuery("XXResourceDef.findByNameAndDefId", tClass) + .setParameter("name", name).setParameter("defId", defId) + .getSingleResult(); + } catch (NoResultException e) { + return null; + } + } + + public List findByServiceDefId(Long serviceDefId) { + if (serviceDefId == null) { + return new ArrayList<>(); + } + + try { + return getEntityManager() + .createNamedQuery("XXResourceDef.findByServiceDefId", tClass) + .setParameter("serviceDefId", serviceDefId).getResultList(); + } catch (NoResultException e) { + return new ArrayList<>(); + } + } + + public List findByPolicyId(Long policyId) { + if (policyId == null) { + return new ArrayList<>(); + } + + try { + return getEntityManager() + .createNamedQuery("XXResourceDef.findByPolicyId", tClass) + .setParameter("policyId", policyId).getResultList(); + } catch (NoResultException e) { + return new ArrayList<>(); + } + } - public XXResourceDefDao(RangerDaoManagerBase daoMgr) { - super(daoMgr); - } - - public XXResourceDef findByNameAndServiceDefId(String name, Long defId) { - if(name == null || defId == null) { - return null; - } - try { - return getEntityManager().createNamedQuery( - "XXResourceDef.findByNameAndDefId", tClass) - .setParameter("name", name).setParameter("defId", defId) - .getSingleResult(); - } catch (NoResultException e) { - return null; - } - } + public XXResourceDef findByNameAndPolicyId(String name, Long policyId) { + if (policyId == null || name == null) { + return null; + } - public List findByServiceDefId(Long serviceDefId) { - if (serviceDefId == null) { - return new ArrayList(); - } - try { - List retList = getEntityManager() - .createNamedQuery("XXResourceDef.findByServiceDefId", tClass) - .setParameter("serviceDefId", serviceDefId).getResultList(); - return retList; - } catch (NoResultException e) { - return new ArrayList(); - } - } - - public List findByPolicyId(Long policyId) { - if(policyId == null) { - return new ArrayList(); - } - try { - return getEntityManager() - .createNamedQuery("XXResourceDef.findByPolicyId", tClass) - .setParameter("policyId", policyId).getResultList(); - } catch (NoResultException e) { - return new ArrayList(); - } - } + try { + return getEntityManager() + .createNamedQuery("XXResourceDef.findByNameAndPolicyId", tClass) + .setParameter("policyId", policyId) + .setParameter("name", name).getSingleResult(); + } catch (NoResultException e) { + return null; + } + } - public XXResourceDef findByNameAndPolicyId(String name, Long policyId) { - if(policyId == null || name == null) { - return null; - } - try { - return getEntityManager() - .createNamedQuery("XXResourceDef.findByNameAndPolicyId", tClass) - .setParameter("policyId", policyId) - .setParameter("name", name).getSingleResult(); - } catch (NoResultException e) { - return null; - } - } + public List findByParentResId(Long parentId) { + if (parentId == null) { + return new ArrayList<>(); + } - public List findByParentResId(Long parentId) { - if(parentId == null) { - return new ArrayList(); - } - try { - return getEntityManager().createNamedQuery("XXResourceDef.findByParentResId", tClass) - .setParameter("parentId", parentId).getResultList(); - } catch (NoResultException e) { - return new ArrayList(); - } - } + try { + return getEntityManager().createNamedQuery("XXResourceDef.findByParentResId", tClass) + .setParameter("parentId", parentId).getResultList(); + } catch (NoResultException e) { + return new ArrayList<>(); + } + } } diff --git a/security-admin/src/main/java/org/apache/ranger/db/XXRoleDao.java b/security-admin/src/main/java/org/apache/ranger/db/XXRoleDao.java index 4e5b692b5f..b83cfb02e4 100644 --- a/security-admin/src/main/java/org/apache/ranger/db/XXRoleDao.java +++ b/security-admin/src/main/java/org/apache/ranger/db/XXRoleDao.java @@ -17,14 +17,15 @@ package org.apache.ranger.db; -import org.apache.commons.collections.ListUtils; import org.apache.commons.lang.StringUtils; import org.apache.ranger.common.db.BaseDao; import org.apache.ranger.entity.XXRole; import org.springframework.stereotype.Service; import javax.persistence.NoResultException; + import java.util.ArrayList; +import java.util.Collections; import java.util.List; @Service @@ -35,57 +36,52 @@ public class XXRoleDao extends BaseDao { public XXRoleDao(RangerDaoManagerBase daoManager) { super(daoManager); } + public XXRole findByRoleId(Long roleId) { if (roleId == null) { return null; } + try { - XXRole xxRole = getEntityManager() - .createNamedQuery("XXRole.findByRoleId", tClass) - .setParameter("roleId", roleId) - .getSingleResult(); - return xxRole; + return getEntityManager().createNamedQuery("XXRole.findByRoleId", tClass).setParameter("roleId", roleId).getSingleResult(); } catch (NoResultException e) { return null; } } + public XXRole findByRoleName(String roleName) { if (StringUtils.isBlank(roleName)) { return null; } + try { - XXRole xxRole = getEntityManager() - .createNamedQuery("XXRole.findByRoleName", tClass) - .setParameter("roleName", roleName) - .getSingleResult(); - return xxRole; + return getEntityManager().createNamedQuery("XXRole.findByRoleName", tClass).setParameter("roleName", roleName).getSingleResult(); } catch (NoResultException e) { return null; } } + public List findByServiceId(Long serviceId) { List ret; + try { - ret = getEntityManager() - .createNamedQuery("XXRole.findByServiceId", tClass) - .setParameter("serviceId", serviceId) - .getResultList(); + ret = getEntityManager().createNamedQuery("XXRole.findByServiceId", tClass).setParameter("serviceId", serviceId).getResultList(); } catch (NoResultException e) { - ret = ListUtils.EMPTY_LIST; + ret = Collections.emptyList(); } + return ret; } public List findRoleNamesByServiceId(Long serviceId) { List ret; + try { - ret = getEntityManager() - .createNamedQuery("XXRole.findRoleNamesByServiceId", String.class) - .setParameter("serviceId", serviceId) - .getResultList(); + ret = getEntityManager().createNamedQuery("XXRole.findRoleNamesByServiceId", String.class).setParameter("serviceId", serviceId).getResultList(); } catch (NoResultException e) { - ret = ListUtils.EMPTY_LIST; + ret = Collections.emptyList(); } + return ret; } @@ -93,38 +89,36 @@ public List getAllNames() { try { return getEntityManager().createNamedQuery("XXRole.getAllNames", String.class).getResultList(); } catch (NoResultException e) { - return new ArrayList(); + return new ArrayList<>(); } } - @SuppressWarnings("unchecked") - public List findByUserId(Long UserId) { - if (UserId == null) { - return null; - } - List ret; - try { - ret = getEntityManager().createNamedQuery("XXRole.findByUserId", tClass).setParameter("userId", UserId) - .getResultList(); - } catch (NoResultException e) { - ret = ListUtils.EMPTY_LIST; - } - return ret; - } - - @SuppressWarnings("unchecked") + public List findByUserId(Long userId) { + if (userId == null) { + return null; + } + + List ret; + + try { + ret = getEntityManager().createNamedQuery("XXRole.findByUserId", tClass).setParameter("userId", userId).getResultList(); + } catch (NoResultException e) { + ret = Collections.emptyList(); + } + + return ret; + } + public List findByGroupId(Long groupId) { if (groupId == null) { return null; } List ret; try { - ret = getEntityManager().createNamedQuery("XXRole.findByGroupId", tClass).setParameter("groupId", groupId) - .getResultList(); + ret = getEntityManager().createNamedQuery("XXRole.findByGroupId", tClass).setParameter("groupId", groupId).getResultList(); } catch (NoResultException e) { - ret = ListUtils.EMPTY_LIST; + ret = Collections.emptyList(); } return ret; } } - diff --git a/security-admin/src/main/java/org/apache/ranger/db/XXRoleRefGroupDao.java b/security-admin/src/main/java/org/apache/ranger/db/XXRoleRefGroupDao.java index aba66cc6f4..5a7e008af0 100644 --- a/security-admin/src/main/java/org/apache/ranger/db/XXRoleRefGroupDao.java +++ b/security-admin/src/main/java/org/apache/ranger/db/XXRoleRefGroupDao.java @@ -19,51 +19,52 @@ package org.apache.ranger.db; -import java.util.Collections; -import java.util.List; - -import javax.persistence.NoResultException; - import org.apache.commons.collections.CollectionUtils; import org.apache.ranger.common.db.BaseDao; import org.apache.ranger.entity.XXRoleRefGroup; import org.springframework.stereotype.Service; -@Service -public class XXRoleRefGroupDao extends BaseDao{ +import javax.persistence.NoResultException; - public XXRoleRefGroupDao(RangerDaoManagerBase daoManager) { +import java.util.Collections; +import java.util.List; + +@Service +public class XXRoleRefGroupDao extends BaseDao { + public XXRoleRefGroupDao(RangerDaoManagerBase daoManager) { super(daoManager); } public List findByRoleId(Long roleId) { - if(roleId == null) { - return Collections.EMPTY_LIST; + if (roleId == null) { + return Collections.emptyList(); } + try { return getEntityManager() .createNamedQuery("XXRoleRefGroup.findByRoleId", tClass) .setParameter("roleId", roleId).getResultList(); } catch (NoResultException e) { - return Collections.EMPTY_LIST; + return Collections.emptyList(); } } public List findByGroupId(Long groupId) { - if(groupId == null) { - return Collections.EMPTY_LIST; + if (groupId == null) { + return Collections.emptyList(); } + try { return getEntityManager() .createNamedQuery("XXRoleRefGroup.findByGroupId", tClass) .setParameter("groupId", groupId).getResultList(); } catch (NoResultException e) { - return Collections.EMPTY_LIST; + return Collections.emptyList(); } } public List findIdsByRoleId(Long roleId) { - List ret = Collections.EMPTY_LIST; + List ret = Collections.emptyList(); if (roleId != null) { try { @@ -71,7 +72,7 @@ public List findIdsByRoleId(Long roleId) { .createNamedQuery("XXRoleRefGroup.findIdsByRoleId", Long.class) .setParameter("roleId", roleId).getResultList(); } catch (NoResultException e) { - ret = Collections.EMPTY_LIST; + // ignore } } @@ -80,13 +81,14 @@ public List findIdsByRoleId(Long roleId) { public List findByGroupName(String groupName) { if (groupName == null) { - return Collections.EMPTY_LIST; + return Collections.emptyList(); } + try { return getEntityManager().createNamedQuery("XXRoleRefGroup.findByGroupName", tClass) .setParameter("groupName", groupName).getResultList(); } catch (NoResultException e) { - return Collections.EMPTY_LIST; + return Collections.emptyList(); } } @@ -95,5 +97,4 @@ public void deleteRoleRefGroupByIds(List ids) { batchDeleteByIds("XXRoleRefGroup.deleteRoleRefGroupByIds", ids, "ids"); } } - -} \ No newline at end of file +} diff --git a/security-admin/src/main/java/org/apache/ranger/db/XXRoleRefRoleDao.java b/security-admin/src/main/java/org/apache/ranger/db/XXRoleRefRoleDao.java index 58d3195148..2416a301d8 100644 --- a/security-admin/src/main/java/org/apache/ranger/db/XXRoleRefRoleDao.java +++ b/security-admin/src/main/java/org/apache/ranger/db/XXRoleRefRoleDao.java @@ -19,40 +19,40 @@ package org.apache.ranger.db; -import java.util.Collections; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import javax.persistence.NoResultException; - import org.apache.commons.collections.CollectionUtils; import org.apache.ranger.common.db.BaseDao; import org.apache.ranger.entity.XXRoleRefRole; import org.springframework.stereotype.Service; -@Service -public class XXRoleRefRoleDao extends BaseDao{ +import javax.persistence.NoResultException; + +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Set; - public XXRoleRefRoleDao(RangerDaoManagerBase daoManager) { +@Service +public class XXRoleRefRoleDao extends BaseDao { + public XXRoleRefRoleDao(RangerDaoManagerBase daoManager) { super(daoManager); } public List findByRoleId(Long roleId) { - if(roleId == null) { - return Collections.EMPTY_LIST; + if (roleId == null) { + return Collections.emptyList(); } + try { return getEntityManager() .createNamedQuery("XXRoleRefRole.findByRoleId", tClass) .setParameter("roleId", roleId).getResultList(); } catch (NoResultException e) { - return Collections.EMPTY_LIST; + return Collections.emptyList(); } } public List findIdsByRoleId(Long roleId) { - List ret = Collections.EMPTY_LIST; + List ret = Collections.emptyList(); if (roleId != null) { try { @@ -60,7 +60,7 @@ public List findIdsByRoleId(Long roleId) { .createNamedQuery("XXRoleRefRole.findIdsByRoleId", Long.class) .setParameter("roleId", roleId).getResultList(); } catch (NoResultException e) { - ret = Collections.EMPTY_LIST; + ret = Collections.emptyList(); } } @@ -68,54 +68,57 @@ public List findIdsByRoleId(Long roleId) { } public List findBySubRoleId(Long subRoleId) { - if(subRoleId == null) { - return Collections.EMPTY_LIST; + if (subRoleId == null) { + return Collections.emptyList(); } + try { return getEntityManager() .createNamedQuery("XXRoleRefRole.findBySubRoleId", tClass) .setParameter("subRoleId", subRoleId).getResultList(); } catch (NoResultException e) { - return Collections.EMPTY_LIST; + return Collections.emptyList(); } } public List findBySubRoleName(String subRoleName) { if (subRoleName == null) { - return Collections.EMPTY_LIST; + return Collections.emptyList(); } + try { return getEntityManager().createNamedQuery("XXRoleRefRole.findBySubRoleName", tClass) .setParameter("subRoleName", subRoleName).getResultList(); } catch (NoResultException e) { - return Collections.EMPTY_LIST; + return Collections.emptyList(); } } - public Long findRoleRefRoleCount(String subRoleName) { - Long ret = -1L; + public Long findRoleRefRoleCount(String subRoleName) { + Long ret = -1L; - try { - ret = getEntityManager().createNamedQuery("XXRoleRefRole.findRoleRefRoleCount", Long.class) - .setParameter("subRoleName", subRoleName).getSingleResult(); - } catch (Exception e) { - } + try { + ret = getEntityManager().createNamedQuery("XXRoleRefRole.findRoleRefRoleCount", Long.class) + .setParameter("subRoleName", subRoleName).getSingleResult(); + } catch (Exception e) { + // ignore + } - return ret; - } + return ret; + } public Set getContainingRoles(Long subRoleId) { - Set ret; - + Set ret; List roles = findBySubRoleId(subRoleId); if (CollectionUtils.isNotEmpty(roles)) { ret = new HashSet<>(); + for (XXRoleRefRole role : roles) { ret.add(role.getRoleId()); } } else { - ret = Collections.EMPTY_SET; + ret = Collections.emptySet(); } return ret; @@ -126,4 +129,4 @@ public void deleteRoleRefRoleByIds(List ids) { batchDeleteByIds("XXRoleRefRole.deleteRoleRefRoleByIds", ids, "ids"); } } -} \ No newline at end of file +} diff --git a/security-admin/src/main/java/org/apache/ranger/db/XXRoleRefUserDao.java b/security-admin/src/main/java/org/apache/ranger/db/XXRoleRefUserDao.java index 59c9230380..8e276a7b52 100644 --- a/security-admin/src/main/java/org/apache/ranger/db/XXRoleRefUserDao.java +++ b/security-admin/src/main/java/org/apache/ranger/db/XXRoleRefUserDao.java @@ -19,38 +19,38 @@ package org.apache.ranger.db; -import java.util.Collections; -import java.util.List; - -import javax.persistence.NoResultException; - import org.apache.commons.collections.CollectionUtils; import org.apache.ranger.common.db.BaseDao; import org.apache.ranger.entity.XXRoleRefUser; import org.springframework.stereotype.Service; -@Service -public class XXRoleRefUserDao extends BaseDao{ +import javax.persistence.NoResultException; - public XXRoleRefUserDao(RangerDaoManagerBase daoManager) { +import java.util.Collections; +import java.util.List; + +@Service +public class XXRoleRefUserDao extends BaseDao { + public XXRoleRefUserDao(RangerDaoManagerBase daoManager) { super(daoManager); } public List findByRoleId(Long roleId) { - if(roleId == null) { - return Collections.EMPTY_LIST; + if (roleId == null) { + return Collections.emptyList(); } + try { return getEntityManager() .createNamedQuery("XXRoleRefUser.findByRoleId", tClass) .setParameter("roleId", roleId).getResultList(); } catch (NoResultException e) { - return Collections.EMPTY_LIST; + return Collections.emptyList(); } } public List findIdsByRoleId(Long roleId) { - List ret = Collections.EMPTY_LIST; + List ret = Collections.emptyList(); if (roleId != null) { try { @@ -58,7 +58,7 @@ public List findIdsByRoleId(Long roleId) { .createNamedQuery("XXRoleRefUser.findIdsByRoleId", Long.class) .setParameter("roleId", roleId).getResultList(); } catch (NoResultException e) { - ret = Collections.EMPTY_LIST; + // ignore } } @@ -66,27 +66,29 @@ public List findIdsByRoleId(Long roleId) { } public List findByUserId(Long userId) { - if(userId == null) { - return Collections.EMPTY_LIST; + if (userId == null) { + return Collections.emptyList(); } + try { return getEntityManager() .createNamedQuery("XXRoleRefUser.findByUserId", tClass) .setParameter("userId", userId).getResultList(); } catch (NoResultException e) { - return Collections.EMPTY_LIST; + return Collections.emptyList(); } } public List findByUserName(String userName) { if (userName == null) { - return Collections.EMPTY_LIST; + return Collections.emptyList(); } + try { return getEntityManager().createNamedQuery("XXRoleRefUser.findByUserName", tClass) .setParameter("userName", userName).getResultList(); } catch (NoResultException e) { - return Collections.EMPTY_LIST; + return Collections.emptyList(); } } @@ -95,4 +97,4 @@ public void deleteRoleRefUserByIds(List ids) { batchDeleteByIds("XXRoleRefUser.deleteRoleRefUserByIds", ids, "ids"); } } -} \ No newline at end of file +} diff --git a/security-admin/src/main/java/org/apache/ranger/db/XXSecurityZoneDao.java b/security-admin/src/main/java/org/apache/ranger/db/XXSecurityZoneDao.java index 5fe0e856dd..51b4d1a1ec 100644 --- a/security-admin/src/main/java/org/apache/ranger/db/XXSecurityZoneDao.java +++ b/security-admin/src/main/java/org/apache/ranger/db/XXSecurityZoneDao.java @@ -23,6 +23,7 @@ import org.apache.ranger.plugin.model.RangerSecurityZone; import org.apache.ranger.plugin.model.RangerSecurityZoneHeaderInfo; import org.springframework.stereotype.Service; + import javax.persistence.NoResultException; import java.util.ArrayList; @@ -37,38 +38,42 @@ public class XXSecurityZoneDao extends BaseDao { public XXSecurityZoneDao(RangerDaoManagerBase daoManager) { super(daoManager); } + public XXSecurityZone findByZoneId(Long zoneId) { if (zoneId == null) { return null; } + try { - XXSecurityZone xxRangerSecurityZone = getEntityManager() + return getEntityManager() .createNamedQuery("XXSecurityZone.findByZoneId", tClass) .setParameter("zoneId", zoneId) .getSingleResult(); - return xxRangerSecurityZone; } catch (NoResultException e) { return null; } } + public XXSecurityZone findByZoneName(String zoneName) { if (StringUtils.isBlank(zoneName)) { return null; } + try { - XXSecurityZone xxRangerSecurityZone = getEntityManager() + return getEntityManager() .createNamedQuery("XXSecurityZone.findByZoneName", tClass) .setParameter("zoneName", zoneName) .getSingleResult(); - return xxRangerSecurityZone; } catch (NoResultException e) { return null; } } + public List findZonesByServiceName(String serviceName) { if (serviceName == null) { return Collections.emptyList(); } + try { return getEntityManager().createNamedQuery("XXSecurityZone.findByServiceName", String.class) .setParameter("serviceName", serviceName).getResultList(); @@ -76,10 +81,12 @@ public List findZonesByServiceName(String serviceName) { return Collections.emptyList(); } } + public List findZonesByTagServiceName(String tagServiceName) { if (tagServiceName == null) { return Collections.emptyList(); } + try { return getEntityManager().createNamedQuery("XXSecurityZone.findByTagServiceName", String.class) .setParameter("tagServiceName", tagServiceName).getResultList(); @@ -87,35 +94,38 @@ public List findZonesByTagServiceName(String tagServiceName) { return Collections.emptyList(); } } - public List findZoneNamesByUserId(Long userId) { - if (userId == null) { - return Collections.emptyList(); - } - try { - return getEntityManager().createNamedQuery("XXSecurityZone.findZoneNamesByUserId", String.class) - .setParameter("userId", userId).getResultList(); - } catch (NoResultException e) { - return Collections.emptyList(); - } - } - - public List findZoneNamesByGroupId(Long groupId) { - if (groupId == null) { - return Collections.emptyList(); - } - try { - return getEntityManager().createNamedQuery("XXSecurityZone.findZoneNamesByGroupId", String.class) - .setParameter("groupId", groupId).getResultList(); - } catch (NoResultException e) { - return Collections.emptyList(); - } - } + + public List findZoneNamesByUserId(Long userId) { + if (userId == null) { + return Collections.emptyList(); + } + + try { + return getEntityManager().createNamedQuery("XXSecurityZone.findZoneNamesByUserId", String.class) + .setParameter("userId", userId).getResultList(); + } catch (NoResultException e) { + return Collections.emptyList(); + } + } + + public List findZoneNamesByGroupId(Long groupId) { + if (groupId == null) { + return Collections.emptyList(); + } + + try { + return getEntityManager().createNamedQuery("XXSecurityZone.findZoneNamesByGroupId", String.class) + .setParameter("groupId", groupId).getResultList(); + } catch (NoResultException e) { + return Collections.emptyList(); + } + } public List findAllZoneHeaderInfos() { - @SuppressWarnings("unchecked") - List results = getEntityManager().createNamedQuery("XXSecurityZone.findAllZoneHeaderInfos").setParameter("unzoneId", RangerSecurityZone.RANGER_UNZONED_SECURITY_ZONE_ID).getResultList(); + List results = getEntityManager().createNamedQuery("XXSecurityZone.findAllZoneHeaderInfos", Object[].class).setParameter("unzoneId", RangerSecurityZone.RANGER_UNZONED_SECURITY_ZONE_ID).getResultList(); + + List securityZoneList = new ArrayList<>(results.size()); - List securityZoneList = new ArrayList(results.size()); for (Object[] result : results) { securityZoneList.add(new RangerSecurityZoneHeaderInfo((Long) result[0], (String) result[1])); } @@ -124,21 +134,24 @@ public List findAllZoneHeaderInfos() { } public List findAllZoneHeaderInfosByServiceId(Long serviceId, Boolean isTagService) { - if(serviceId == null){ - return Collections.emptyList(); + if (serviceId == null) { + return Collections.emptyList(); } - List results = null; - if(isTagService){ - results = getEntityManager().createNamedQuery("XXSecurityZone.findAllZoneHeaderInfosByTagServiceId") - .setParameter("tagServiceId", serviceId) - .getResultList(); - }else{ - results = getEntityManager().createNamedQuery("XXSecurityZone.findAllZoneHeaderInfosByServiceId") - .setParameter("serviceId", serviceId) - .getResultList(); + + List results; + + if (isTagService) { + results = getEntityManager().createNamedQuery("XXSecurityZone.findAllZoneHeaderInfosByTagServiceId", Object[].class) + .setParameter("tagServiceId", serviceId) + .getResultList(); + } else { + results = getEntityManager().createNamedQuery("XXSecurityZone.findAllZoneHeaderInfosByServiceId", Object[].class) + .setParameter("serviceId", serviceId) + .getResultList(); } - List securityZoneList = new ArrayList(results.size()); + List securityZoneList = new ArrayList<>(results.size()); + for (Object[] result : results) { securityZoneList.add(new RangerSecurityZoneHeaderInfo((Long) result[0], (String) result[1])); } diff --git a/security-admin/src/main/java/org/apache/ranger/db/XXSecurityZoneRefGroupDao.java b/security-admin/src/main/java/org/apache/ranger/db/XXSecurityZoneRefGroupDao.java index 2e9640ef2d..d1306534fd 100644 --- a/security-admin/src/main/java/org/apache/ranger/db/XXSecurityZoneRefGroupDao.java +++ b/security-admin/src/main/java/org/apache/ranger/db/XXSecurityZoneRefGroupDao.java @@ -19,74 +19,74 @@ package org.apache.ranger.db; -import java.util.Collections; -import java.util.List; - -import javax.persistence.NoResultException; - import org.apache.ranger.common.db.BaseDao; import org.apache.ranger.entity.XXSecurityZoneRefGroup; -public class XXSecurityZoneRefGroupDao extends BaseDao{ +import javax.persistence.NoResultException; - public XXSecurityZoneRefGroupDao(RangerDaoManagerBase daoManager) { - super(daoManager); - } +import java.util.Collections; +import java.util.List; + +public class XXSecurityZoneRefGroupDao extends BaseDao { + public XXSecurityZoneRefGroupDao(RangerDaoManagerBase daoManager) { + super(daoManager); + } - public List findByZoneId(Long zoneId) { + public List findByZoneId(Long zoneId) { if (zoneId == null) { return null; } + try { - List xxZoneRefService = getEntityManager() + return getEntityManager() .createNamedQuery("XXSecurityZoneRefGroup.findByZoneId", tClass) .setParameter("zoneId", zoneId) .getResultList(); - return xxZoneRefService; } catch (NoResultException e) { return null; } } - public List findByGroupId(Long groupId) { - if (groupId == null) { - return Collections.emptyList(); - } - try { - return getEntityManager().createNamedQuery("XXSecurityZoneRefGroup.findByGroupId", tClass) - .setParameter("groupId", groupId).getResultList(); - } catch (NoResultException e) { - return Collections.emptyList(); - } - } + public List findByGroupId(Long groupId) { + if (groupId == null) { + return Collections.emptyList(); + } - public List findAdminGroupByZoneId(Long zoneId) { + try { + return getEntityManager().createNamedQuery("XXSecurityZoneRefGroup.findByGroupId", tClass) + .setParameter("groupId", groupId).getResultList(); + } catch (NoResultException e) { + return Collections.emptyList(); + } + } + + public List findAdminGroupByZoneId(Long zoneId) { if (zoneId == null) { return null; } + try { - List xxZoneRefGroup = getEntityManager() + return getEntityManager() .createNamedQuery("XXSecurityZoneRefGroup.findGroupTypeByZoneId", tClass) .setParameter("zoneId", zoneId) .setParameter("groupType", "1") .getResultList(); - return xxZoneRefGroup; } catch (NoResultException e) { return null; } } - public List findAuditGroupByZoneId(Long zoneId) { + public List findAuditGroupByZoneId(Long zoneId) { if (zoneId == null) { return null; } + try { - List xxZoneRefGroup = getEntityManager() + return getEntityManager() .createNamedQuery("XXSecurityZoneRefGroup.findGroupTypeByZoneId", tClass) .setParameter("zoneId", zoneId) .setParameter("groupType", "0") .getResultList(); - return xxZoneRefGroup; } catch (NoResultException e) { return null; } diff --git a/security-admin/src/main/java/org/apache/ranger/db/XXSecurityZoneRefResourceDao.java b/security-admin/src/main/java/org/apache/ranger/db/XXSecurityZoneRefResourceDao.java index c2bd661073..eb770813a4 100644 --- a/security-admin/src/main/java/org/apache/ranger/db/XXSecurityZoneRefResourceDao.java +++ b/security-admin/src/main/java/org/apache/ranger/db/XXSecurityZoneRefResourceDao.java @@ -19,44 +19,44 @@ package org.apache.ranger.db; -import java.util.Collections; -import java.util.List; - -import javax.persistence.NoResultException; - import org.apache.ranger.common.db.BaseDao; import org.apache.ranger.entity.XXSecurityZoneRefResource; -public class XXSecurityZoneRefResourceDao extends BaseDao{ +import javax.persistence.NoResultException; - public XXSecurityZoneRefResourceDao(RangerDaoManagerBase daoManager) { - super(daoManager); - } +import java.util.Collections; +import java.util.List; - public List findByZoneId(Long zoneId) { +public class XXSecurityZoneRefResourceDao extends BaseDao { + public XXSecurityZoneRefResourceDao(RangerDaoManagerBase daoManager) { + super(daoManager); + } + + public List findByZoneId(Long zoneId) { if (zoneId == null) { return null; } + try { - List xxZoneRefResource = getEntityManager() + return getEntityManager() .createNamedQuery("XXSecurityZoneRefResource.findByZoneId", tClass) .setParameter("zoneId", zoneId) .getResultList(); - return xxZoneRefResource; } catch (NoResultException e) { return null; } } - public List findByResourceDefId(Long resourceDefId) { - if (resourceDefId == null) { - return Collections.emptyList(); - } - try { - return getEntityManager().createNamedQuery("XXSecurityZoneRefResource.findByResourceDefId", tClass) - .setParameter("resourceDefId", resourceDefId).getResultList(); - } catch (NoResultException e) { - return Collections.emptyList(); - } - } + public List findByResourceDefId(Long resourceDefId) { + if (resourceDefId == null) { + return Collections.emptyList(); + } + + try { + return getEntityManager().createNamedQuery("XXSecurityZoneRefResource.findByResourceDefId", tClass) + .setParameter("resourceDefId", resourceDefId).getResultList(); + } catch (NoResultException e) { + return Collections.emptyList(); + } + } } diff --git a/security-admin/src/main/java/org/apache/ranger/db/XXSecurityZoneRefRoleDao.java b/security-admin/src/main/java/org/apache/ranger/db/XXSecurityZoneRefRoleDao.java index 65c602dea5..da8a19676f 100644 --- a/security-admin/src/main/java/org/apache/ranger/db/XXSecurityZoneRefRoleDao.java +++ b/security-admin/src/main/java/org/apache/ranger/db/XXSecurityZoneRefRoleDao.java @@ -23,41 +23,42 @@ import org.apache.ranger.entity.XXSecurityZoneRefRole; import javax.persistence.NoResultException; + import java.util.Collections; import java.util.List; -public class XXSecurityZoneRefRoleDao extends BaseDao{ - - public XXSecurityZoneRefRoleDao(RangerDaoManagerBase daoManager) { - super(daoManager); - } +public class XXSecurityZoneRefRoleDao extends BaseDao { + public XXSecurityZoneRefRoleDao(RangerDaoManagerBase daoManager) { + super(daoManager); + } - public List findByZoneId(Long zoneId) { + public List findByZoneId(Long zoneId) { if (zoneId == null) { return null; } + try { - List xxZoneRefService = getEntityManager() + return getEntityManager() .createNamedQuery("XXSecurityZoneRefRole.findByZoneId", tClass) .setParameter("zoneId", zoneId) .getResultList(); - return xxZoneRefService; } catch (NoResultException e) { return null; } } - public List findByRoleId(Long roleId) { - if (roleId == null) { - return Collections.emptyList(); - } - try { - return getEntityManager().createNamedQuery("XXSecurityZoneRefRole.findByRoleId", tClass) - .setParameter("roleId", roleId).getResultList(); - } catch (NoResultException e) { - return Collections.emptyList(); - } - } + public List findByRoleId(Long roleId) { + if (roleId == null) { + return Collections.emptyList(); + } + + try { + return getEntityManager().createNamedQuery("XXSecurityZoneRefRole.findByRoleId", tClass) + .setParameter("roleId", roleId).getResultList(); + } catch (NoResultException e) { + return Collections.emptyList(); + } + } public Long findRoleRefZoneCount(String roleName) { Long ret = -1L; @@ -66,38 +67,39 @@ public Long findRoleRefZoneCount(String roleName) { ret = getEntityManager().createNamedQuery("XXSecurityZoneRefRole.findRoleRefZoneCount", Long.class) .setParameter("roleName", roleName).getSingleResult(); } catch (Exception e) { + // ignore } return ret; } - public List findAdminRoleByZoneId(Long zoneId) { + public List findAdminRoleByZoneId(Long zoneId) { if (zoneId == null) { return null; } + try { - List xxZoneRefRole = getEntityManager() + return getEntityManager() .createNamedQuery("XXSecurityZoneRefRole.findRoleTypeByZoneId", tClass) .setParameter("zoneId", zoneId) .setParameter("roleType", "1") .getResultList(); - return xxZoneRefRole; } catch (NoResultException e) { return null; } } - public List findAuditRoleByZoneId(Long zoneId) { + public List findAuditRoleByZoneId(Long zoneId) { if (zoneId == null) { return null; } + try { - List xxZoneRefRole = getEntityManager() + return getEntityManager() .createNamedQuery("XXSecurityZoneRefRole.findRoleTypeByZoneId", tClass) .setParameter("zoneId", zoneId) .setParameter("roleType", "0") .getResultList(); - return xxZoneRefRole; } catch (NoResultException e) { return null; } diff --git a/security-admin/src/main/java/org/apache/ranger/db/XXSecurityZoneRefServiceDao.java b/security-admin/src/main/java/org/apache/ranger/db/XXSecurityZoneRefServiceDao.java index 00d157e5c0..601be13e35 100644 --- a/security-admin/src/main/java/org/apache/ranger/db/XXSecurityZoneRefServiceDao.java +++ b/security-admin/src/main/java/org/apache/ranger/db/XXSecurityZoneRefServiceDao.java @@ -19,80 +19,82 @@ package org.apache.ranger.db; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import javax.persistence.NoResultException; - import org.apache.ranger.common.db.BaseDao; import org.apache.ranger.entity.XXSecurityZoneRefService; import org.apache.ranger.plugin.model.RangerSecurityZone; import org.apache.ranger.plugin.model.RangerServiceHeaderInfo; -public class XXSecurityZoneRefServiceDao extends BaseDao{ +import javax.persistence.NoResultException; - public XXSecurityZoneRefServiceDao(RangerDaoManagerBase daoManager) { - super(daoManager); - } +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +public class XXSecurityZoneRefServiceDao extends BaseDao { + public XXSecurityZoneRefServiceDao(RangerDaoManagerBase daoManager) { + super(daoManager); + } - public List findByZoneId(Long zoneId) { + public List findByZoneId(Long zoneId) { if (zoneId == null) { return null; } + try { - List xxZoneRefService = getEntityManager() + return getEntityManager() .createNamedQuery("XXSecurityZoneRefService.findByZoneId", tClass) .setParameter("zoneId", zoneId) .getResultList(); - return xxZoneRefService; } catch (NoResultException e) { return null; } } - public List findByServiceId(Long serviceId) { - if (serviceId == null) { - return Collections.emptyList(); - } - try { - return getEntityManager().createNamedQuery("XXSecurityZoneRefService.findByServiceId", tClass) - .setParameter("serviceId", serviceId).getResultList(); - } catch (NoResultException e) { - return Collections.emptyList(); - } - } - - public List findByServiceName(String serviceName) { - if (serviceName == null) { - return Collections.emptyList(); - } - try { - return getEntityManager().createNamedQuery("XXSecurityZoneRefService.findByServiceName", tClass) - .setParameter("serviceName", serviceName).getResultList(); - } catch (NoResultException e) { - return Collections.emptyList(); - } - } - - public List findByServiceNameAndZoneId(String serviceName, Long zoneId) { - if (serviceName == null) { - return Collections.emptyList(); - } - try { - return getEntityManager().createNamedQuery("XXSecurityZoneRefService.findByServiceNameAndZoneId", tClass) - .setParameter("serviceName", serviceName).setParameter("zoneId", zoneId).getResultList(); - } catch (NoResultException e) { - return Collections.emptyList(); - } - } + public List findByServiceId(Long serviceId) { + if (serviceId == null) { + return Collections.emptyList(); + } + + try { + return getEntityManager().createNamedQuery("XXSecurityZoneRefService.findByServiceId", tClass) + .setParameter("serviceId", serviceId).getResultList(); + } catch (NoResultException e) { + return Collections.emptyList(); + } + } + + public List findByServiceName(String serviceName) { + if (serviceName == null) { + return Collections.emptyList(); + } + + try { + return getEntityManager().createNamedQuery("XXSecurityZoneRefService.findByServiceName", tClass) + .setParameter("serviceName", serviceName).getResultList(); + } catch (NoResultException e) { + return Collections.emptyList(); + } + } + + public List findByServiceNameAndZoneId(String serviceName, Long zoneId) { + if (serviceName == null) { + return Collections.emptyList(); + } + + try { + return getEntityManager().createNamedQuery("XXSecurityZoneRefService.findByServiceNameAndZoneId", tClass) + .setParameter("serviceName", serviceName).setParameter("zoneId", zoneId).getResultList(); + } catch (NoResultException e) { + return Collections.emptyList(); + } + } public List findServiceHeaderInfosByZoneId(Long zoneId) { List ret; if (zoneId != null && zoneId > RangerSecurityZone.RANGER_UNZONED_SECURITY_ZONE_ID) { List results = getEntityManager().createNamedQuery("XXSecurityZoneRefService.findServiceHeaderInfosByZoneId", Object[].class) - .setParameter("zoneId", zoneId).getResultList(); + .setParameter("zoneId", zoneId).getResultList(); ret = new ArrayList<>(results.size()); diff --git a/security-admin/src/main/java/org/apache/ranger/db/XXSecurityZoneRefTagServiceDao.java b/security-admin/src/main/java/org/apache/ranger/db/XXSecurityZoneRefTagServiceDao.java index 9a587891ee..cbec46d026 100644 --- a/security-admin/src/main/java/org/apache/ranger/db/XXSecurityZoneRefTagServiceDao.java +++ b/security-admin/src/main/java/org/apache/ranger/db/XXSecurityZoneRefTagServiceDao.java @@ -18,56 +18,57 @@ */ package org.apache.ranger.db; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import javax.persistence.NoResultException; - import org.apache.ranger.common.db.BaseDao; import org.apache.ranger.entity.XXSecurityZoneRefTagService; import org.apache.ranger.plugin.model.RangerSecurityZone; import org.apache.ranger.plugin.model.RangerServiceHeaderInfo; -public class XXSecurityZoneRefTagServiceDao extends BaseDao{ +import javax.persistence.NoResultException; - public XXSecurityZoneRefTagServiceDao(RangerDaoManagerBase daoManager) { - super(daoManager); - } +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +public class XXSecurityZoneRefTagServiceDao extends BaseDao { + public XXSecurityZoneRefTagServiceDao(RangerDaoManagerBase daoManager) { + super(daoManager); + } - public List findByZoneId(Long zoneId) { + public List findByZoneId(Long zoneId) { if (zoneId == null) { return null; } + try { - List xxZoneRefTagService = getEntityManager() + return getEntityManager() .createNamedQuery("XXSecurityZoneRefTagService.findByZoneId", tClass) .setParameter("zoneId", zoneId) .getResultList(); - return xxZoneRefTagService; } catch (NoResultException e) { return null; } } - public List findByTagServiceNameAndZoneId(String tagServiceName, Long zoneId) { - if (tagServiceName == null) { - return Collections.emptyList(); - } - try { - return getEntityManager().createNamedQuery("XXSecurityZoneRefTagService.findByTagServiceNameAndZoneId", tClass) - .setParameter("tagServiceName", tagServiceName).setParameter("zoneId", zoneId).getResultList(); - } catch (NoResultException e) { - return Collections.emptyList(); - } - } + public List findByTagServiceNameAndZoneId(String tagServiceName, Long zoneId) { + if (tagServiceName == null) { + return Collections.emptyList(); + } + + try { + return getEntityManager().createNamedQuery("XXSecurityZoneRefTagService.findByTagServiceNameAndZoneId", tClass) + .setParameter("tagServiceName", tagServiceName) + .setParameter("zoneId", zoneId).getResultList(); + } catch (NoResultException e) { + return Collections.emptyList(); + } + } public List findServiceHeaderInfosByZoneId(Long zoneId) { List ret; if (zoneId != null && zoneId > RangerSecurityZone.RANGER_UNZONED_SECURITY_ZONE_ID) { List results = getEntityManager().createNamedQuery("XXSecurityZoneRefTagService.findServiceHeaderInfosByZoneId", Object[].class) - .setParameter("zoneId", zoneId).getResultList(); + .setParameter("zoneId", zoneId).getResultList(); ret = new ArrayList<>(results.size()); diff --git a/security-admin/src/main/java/org/apache/ranger/db/XXSecurityZoneRefUserDao.java b/security-admin/src/main/java/org/apache/ranger/db/XXSecurityZoneRefUserDao.java index e5b37111c0..54926934f6 100644 --- a/security-admin/src/main/java/org/apache/ranger/db/XXSecurityZoneRefUserDao.java +++ b/security-admin/src/main/java/org/apache/ranger/db/XXSecurityZoneRefUserDao.java @@ -19,74 +19,76 @@ package org.apache.ranger.db; -import java.util.Collections; -import java.util.List; -import javax.persistence.NoResultException; import org.apache.ranger.common.db.BaseDao; import org.apache.ranger.entity.XXSecurityZoneRefUser; -public class XXSecurityZoneRefUserDao extends BaseDao{ +import javax.persistence.NoResultException; - public XXSecurityZoneRefUserDao(RangerDaoManagerBase daoManager) { - super(daoManager); - } +import java.util.Collections; +import java.util.List; + +public class XXSecurityZoneRefUserDao extends BaseDao { + public XXSecurityZoneRefUserDao(RangerDaoManagerBase daoManager) { + super(daoManager); + } - public List findByZoneId(Long zoneId) { + public List findByZoneId(Long zoneId) { if (zoneId == null) { return null; } + try { - List xxZoneRefService = getEntityManager() + return getEntityManager() .createNamedQuery("XXSecurityZoneRefUser.findByZoneId", tClass) .setParameter("zoneId", zoneId) .getResultList(); - return xxZoneRefService; } catch (NoResultException e) { return null; } } - public List findAdminUsersByZoneId(Long zoneId) { + public List findAdminUsersByZoneId(Long zoneId) { if (zoneId == null) { return null; } + try { - List xxZoneRefService = getEntityManager() + return getEntityManager() .createNamedQuery("XXSecurityZoneRefUser.findUserTypeByZoneId", tClass) .setParameter("zoneId", zoneId) .setParameter("userType", "1") .getResultList(); - return xxZoneRefService; } catch (NoResultException e) { return null; } } - public List findAuditUsersByZoneId(Long zoneId) { + public List findAuditUsersByZoneId(Long zoneId) { if (zoneId == null) { return null; } + try { - List xxZoneRefService = getEntityManager() + return getEntityManager() .createNamedQuery("XXSecurityZoneRefUser.findUserTypeByZoneId", tClass) .setParameter("zoneId", zoneId) .setParameter("userType", "0") .getResultList(); - return xxZoneRefService; } catch (NoResultException e) { return null; } } - public List findByUserId(Long userId) { - if (userId == null) { - return Collections.emptyList(); - } - try { - return getEntityManager().createNamedQuery("XXSecurityZoneRefUser.findByUserId", tClass) - .setParameter("userId", userId).getResultList(); - } catch (NoResultException e) { - return Collections.emptyList(); - } - } + public List findByUserId(Long userId) { + if (userId == null) { + return Collections.emptyList(); + } + + try { + return getEntityManager().createNamedQuery("XXSecurityZoneRefUser.findByUserId", tClass) + .setParameter("userId", userId).getResultList(); + } catch (NoResultException e) { + return Collections.emptyList(); + } + } } diff --git a/security-admin/src/main/java/org/apache/ranger/db/XXServiceConfigDefDao.java b/security-admin/src/main/java/org/apache/ranger/db/XXServiceConfigDefDao.java index 5d54876c7f..7bd84c121f 100644 --- a/security-admin/src/main/java/org/apache/ranger/db/XXServiceConfigDefDao.java +++ b/security-admin/src/main/java/org/apache/ranger/db/XXServiceConfigDefDao.java @@ -17,48 +17,46 @@ package org.apache.ranger.db; -import java.util.ArrayList; -import java.util.List; - -import javax.persistence.NoResultException; - import org.apache.ranger.common.db.BaseDao; import org.apache.ranger.entity.XXServiceConfigDef; import org.springframework.stereotype.Service; +import javax.persistence.NoResultException; + +import java.util.ArrayList; +import java.util.List; + @Service public class XXServiceConfigDefDao extends BaseDao { - - public XXServiceConfigDefDao(RangerDaoManagerBase daoMgr) { - super(daoMgr); - } + public XXServiceConfigDefDao(RangerDaoManagerBase daoMgr) { + super(daoMgr); + } + + public List findByServiceDefId(Long serviceDefId) { + if (serviceDefId == null) { + return new ArrayList<>(); + } + + try { + return getEntityManager() + .createNamedQuery("XXServiceConfigDef.findByServiceDefId", tClass) + .setParameter("serviceDefId", serviceDefId).getResultList(); + } catch (NoResultException e) { + return new ArrayList<>(); + } + } + + public List findByServiceDefName(String serviceDef) { + if (serviceDef == null) { + return new ArrayList<>(); + } - public List findByServiceDefId(Long serviceDefId) { - if (serviceDefId == null) { - return new ArrayList(); - } - try { - List retList = getEntityManager() - .createNamedQuery("XXServiceConfigDef.findByServiceDefId", tClass) - .setParameter("serviceDefId", serviceDefId).getResultList(); - return retList; - } catch (NoResultException e) { - return new ArrayList(); - } - } - - public List findByServiceDefName(String serviceDef) { - if (serviceDef == null) { - return new ArrayList(); - } - try { - List retList = getEntityManager() - .createNamedQuery("XXServiceConfigDef.findByServiceDefName", tClass) - .setParameter("serviceDef", serviceDef).getResultList(); - return retList; - } catch (NoResultException e) { - return new ArrayList(); - } - } - + try { + return getEntityManager() + .createNamedQuery("XXServiceConfigDef.findByServiceDefName", tClass) + .setParameter("serviceDef", serviceDef).getResultList(); + } catch (NoResultException e) { + return new ArrayList<>(); + } + } } diff --git a/security-admin/src/main/java/org/apache/ranger/db/XXServiceConfigMapDao.java b/security-admin/src/main/java/org/apache/ranger/db/XXServiceConfigMapDao.java index b99a7df500..ffc99eb007 100644 --- a/security-admin/src/main/java/org/apache/ranger/db/XXServiceConfigMapDao.java +++ b/security-admin/src/main/java/org/apache/ranger/db/XXServiceConfigMapDao.java @@ -17,116 +17,117 @@ package org.apache.ranger.db; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import javax.persistence.NoResultException; - import org.apache.ranger.common.db.BaseDao; import org.apache.ranger.entity.XXServiceConfigMap; import org.apache.ranger.services.tag.RangerServiceTag; import org.springframework.stereotype.Service; +import javax.persistence.NoResultException; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + @Service public class XXServiceConfigMapDao extends BaseDao { + private static final String SERVICE_CLUSTER_NAME_CONF_KEY = "cluster.name"; + + public XXServiceConfigMapDao(RangerDaoManagerBase daoManager) { + super(daoManager); + } + + public List findByServiceId(Long serviceId) { + if (serviceId == null) { + return new ArrayList<>(); + } + + try { + return getEntityManager() + .createNamedQuery("XXServiceConfigMap.findByServiceId", tClass) + .setParameter("serviceId", serviceId) + .getResultList(); + } catch (NoResultException e) { + return new ArrayList<>(); + } + } + + public XXServiceConfigMap findByServiceAndConfigKey(Long serviceId, String configKey) { + if (serviceId == null || configKey == null) { + return null; + } + + try { + return getEntityManager() + .createNamedQuery("XXServiceConfigMap.findByServiceAndConfigKey", tClass) + .setParameter("serviceId", serviceId) + .setParameter("configKey", configKey).getSingleResult(); + } catch (NoResultException e) { + return null; + } + } + + public XXServiceConfigMap findByServiceNameAndConfigKey(String serviceName, String configKey) { + if (serviceName == null || configKey == null) { + return null; + } + + try { + return getEntityManager() + .createNamedQuery("XXServiceConfigMap.findByServiceNameAndConfigKey", tClass) + .setParameter("name", serviceName) + .setParameter("configKey", configKey).getSingleResult(); + } catch (NoResultException e) { + return null; + } + } + + /** + * Get resource based service IDs, using supplied clusterName + * + * @param clusterName + * @return {@link java.util.List List} of service IDs if found, empty {@link java.util.List List} otherwise. + */ + public List findServiceIdsByClusterName(String clusterName) { + if (clusterName == null) { + return Collections.emptyList(); + } + + return findServiceIdsByConfigKeyAndConfigValueFilterByServiceType(SERVICE_CLUSTER_NAME_CONF_KEY, clusterName, RangerServiceTag.TAG_RESOURCE_NAME); + } + + public List findByConfigKey(String configKey) { + if (configKey == null) { + return Collections.emptyList(); + } + + try { + return getEntityManager() + .createNamedQuery("XXServiceConfigMap.findByConfigKey", tClass) + .setParameter("configKey", configKey).getResultList(); + } catch (NoResultException e) { + return Collections.emptyList(); + } + } - private static final String SERVICE_CLUSTER_NAME_CONF_KEY = "cluster.name"; - - public XXServiceConfigMapDao(RangerDaoManagerBase daoManager) { - super(daoManager); - } - - public List findByServiceId(Long serviceId) { - if (serviceId == null) { - return new ArrayList(); - } - try { - return getEntityManager() - .createNamedQuery("XXServiceConfigMap.findByServiceId", tClass) - .setParameter("serviceId", serviceId) - .getResultList(); - } catch (NoResultException e) { - return new ArrayList(); - } - } - - public XXServiceConfigMap findByServiceAndConfigKey(Long serviceId, - String configKey) { - if(serviceId == null || configKey == null) { - return null; - } - try { - return getEntityManager() - .createNamedQuery("XXServiceConfigMap.findByServiceAndConfigKey", tClass) - .setParameter("serviceId", serviceId) - .setParameter("configKey", configKey).getSingleResult(); - } catch (NoResultException e) { - return null; - } - } - - public XXServiceConfigMap findByServiceNameAndConfigKey(String serviceName, String configKey) { - if(serviceName == null || configKey == null) { - return null; - } - try { - return getEntityManager() - .createNamedQuery("XXServiceConfigMap.findByServiceNameAndConfigKey", tClass) - .setParameter("name", serviceName) - .setParameter("configKey", configKey).getSingleResult(); - } catch (NoResultException e) { - return null; - } - } - - /** - * Get resource based service IDs, using supplied clusterName - * @param clusterName - * @return {@link java.util.List List} of service IDs if found, empty {@link java.util.List List} otherwise. - */ - public List findServiceIdsByClusterName(String clusterName) { - if(clusterName == null) { - return Collections.emptyList(); - } - - return findServiceIdsByConfigKeyAndConfigValueFilterByServiceType(SERVICE_CLUSTER_NAME_CONF_KEY, clusterName, RangerServiceTag.TAG_RESOURCE_NAME); - } - - /** - * Get service IDs, using supplied configKey and configValue and are not of provided serviceType. - * Caller of this method must make sure, {@code configKey} and {@code configValue) passed as method parameter are not null. - * - * @param configKey - * @param configValue - * @param serviceType - * @return {@link java.util.List list} of service IDs if found, empty {@link java.util.List list} otherwise. - */ - private List findServiceIdsByConfigKeyAndConfigValueFilterByServiceType(String configKey, String configValue, String serviceType) { - try { - return getEntityManager() - .createNamedQuery("XXServiceConfigMap.findServiceIdsByConfigKeyAndConfigValueAndFilterByServiceType", Long.class) - .setParameter("configKey", configKey) - .setParameter("configValue", configValue) - .setParameter("serviceType", serviceType) - .getResultList(); - } - - catch (NoResultException e) { - return Collections.emptyList(); - } - } - - public List findByConfigKey(String configKey) { - if(configKey == null) { - return Collections.emptyList(); - } - try { - return getEntityManager() - .createNamedQuery("XXServiceConfigMap.findByConfigKey", tClass) - .setParameter("configKey", configKey).getResultList(); - } catch (NoResultException e) { - return Collections.emptyList(); - } - } + /** + * Get service IDs, using supplied configKey and configValue and are not of provided serviceType. + * Caller of this method must make sure, {@code configKey} and {@code configValue) passed as method parameter are not null. + * + * @param configKey + * @param configValue + * @param serviceType + * @return {@link java.util.List list} of service IDs if found, empty {@link java.util.List list} otherwise. + */ + private List findServiceIdsByConfigKeyAndConfigValueFilterByServiceType(String configKey, String configValue, String serviceType) { + try { + return getEntityManager() + .createNamedQuery("XXServiceConfigMap.findServiceIdsByConfigKeyAndConfigValueAndFilterByServiceType", Long.class) + .setParameter("configKey", configKey) + .setParameter("configValue", configValue) + .setParameter("serviceType", serviceType) + .getResultList(); + } catch (NoResultException e) { + return Collections.emptyList(); + } + } } diff --git a/security-admin/src/main/java/org/apache/ranger/db/XXServiceDao.java b/security-admin/src/main/java/org/apache/ranger/db/XXServiceDao.java index a1f93b152b..797a6988f8 100644 --- a/security-admin/src/main/java/org/apache/ranger/db/XXServiceDao.java +++ b/security-admin/src/main/java/org/apache/ranger/db/XXServiceDao.java @@ -17,168 +17,172 @@ package org.apache.ranger.db; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import javax.persistence.NoResultException; - import org.apache.ranger.common.db.BaseDao; import org.apache.ranger.entity.XXService; import org.apache.ranger.plugin.model.RangerServiceHeaderInfo; import org.springframework.stereotype.Service; +import javax.persistence.NoResultException; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + /** + * */ @Service public class XXServiceDao extends BaseDao { - /** - * Default Constructor - */ - public XXServiceDao(RangerDaoManagerBase daoManager) { - super(daoManager); - } - - public Long findIdByName(String name) { - Long ret = null; - - if (name != null) { - try { - ret = getEntityManager() - .createNamedQuery("XXService.findIdByName", Long.class) - .setParameter("name", name).getSingleResult(); - } catch (NoResultException e) { - // ignore - } - } - - return ret; - } - - public XXService findByName(String name) { - if (name == null) { - return null; - } - try { - return getEntityManager() - .createNamedQuery("XXService.findByName", tClass) - .setParameter("name", name).getSingleResult(); - } catch (NoResultException e) { - return null; - } - } - - public XXService findByDisplayName(String displayName) { - if (displayName == null) { - return null; - } - try { - return getEntityManager() - .createNamedQuery("XXService.findByDisplayName", tClass) - .setParameter("displayName", displayName).getSingleResult(); - } catch (NoResultException e) { - return null; - } - } - - public Long getMaxIdOfXXService() { - try { - return (Long) getEntityManager().createNamedQuery("XXService.getMaxIdOfXXService").getSingleResult(); - } catch (NoResultException e) { - return null; - } - } - - public List findByServiceDefId(Long serviceDefId) { - if (serviceDefId == null) { - return new ArrayList(); - } - try { - return getEntityManager().createNamedQuery("XXService.findByServiceDefId", tClass) - .setParameter("serviceDefId", serviceDefId).getResultList(); - } catch (NoResultException e) { - return new ArrayList(); - } - } - - public List findByTagServiceId(Long tagServiceId) { - if (tagServiceId == null) { - return new ArrayList(); - } - try { - return getEntityManager().createNamedQuery("XXService.findByTagServiceId", tClass) - .setParameter("tagServiceId", tagServiceId).getResultList(); - } catch (NoResultException e) { - return new ArrayList(); - } - } - - public List findIdsByTagServiceId(Long tagServiceId) { - List ret = null; - - try { - ret = getEntityManager().createNamedQuery("XXService.findIdsByTagServiceId", Long.class) - .setParameter("tagServiceId", tagServiceId).getResultList(); - } catch (NoResultException e) { - // ignre - } - - return ret != null ? ret : Collections.emptyList(); - } - - public XXService findAssociatedTagService(String serviceName) { - try { - return getEntityManager().createNamedQuery("XXService.findAssociatedTagService", tClass) - .setParameter("serviceName", serviceName).getSingleResult(); - } catch (NoResultException e) { - return null; - } - } - - public List getAllServicesWithTagService() { - try { - return getEntityManager().createNamedQuery("XXService.getAllServicesWithTagService", tClass) - .getResultList(); - } catch (NoResultException e) { - return new ArrayList(); - } - } - - public void updateSequence() { - Long maxId = getMaxIdOfXXService(); - - if(maxId == null) { - return; - } - - updateSequence("X_SERVICE_SEQ", maxId + 1); - } - - public List getAllServiceIds() { - try { - return getEntityManager().createNamedQuery("XXService.getAllServiceIds", Long.class) - .getResultList(); - } catch (NoResultException e) { - return new ArrayList<>(); - } - } - - public List findServiceHeaders() { - List ret; - - try { - List results = getEntityManager().createNamedQuery("XXService.getAllServiceHeaders", Object[].class).getResultList(); - - ret = new ArrayList<>(results.size()); - - for (Object[] result : results) { - ret.add(new RangerServiceHeaderInfo((Long) result[0], (String) result[1], (String) result[2], (String) result[3], (Boolean) result[4])); - } - } catch (NoResultException excp) { - ret = Collections.emptyList(); - } - - return ret; - } + /** + * Default Constructor + */ + public XXServiceDao(RangerDaoManagerBase daoManager) { + super(daoManager); + } + + public Long findIdByName(String name) { + Long ret = null; + + if (name != null) { + try { + ret = getEntityManager() + .createNamedQuery("XXService.findIdByName", Long.class) + .setParameter("name", name).getSingleResult(); + } catch (NoResultException e) { + // ignore + } + } + + return ret; + } + + public XXService findByName(String name) { + if (name == null) { + return null; + } + try { + return getEntityManager() + .createNamedQuery("XXService.findByName", tClass) + .setParameter("name", name).getSingleResult(); + } catch (NoResultException e) { + return null; + } + } + + public XXService findByDisplayName(String displayName) { + if (displayName == null) { + return null; + } + + try { + return getEntityManager() + .createNamedQuery("XXService.findByDisplayName", tClass) + .setParameter("displayName", displayName).getSingleResult(); + } catch (NoResultException e) { + return null; + } + } + + public Long getMaxIdOfXXService() { + try { + return (Long) getEntityManager().createNamedQuery("XXService.getMaxIdOfXXService").getSingleResult(); + } catch (NoResultException e) { + return null; + } + } + + public List findByServiceDefId(Long serviceDefId) { + if (serviceDefId == null) { + return new ArrayList<>(); + } + + try { + return getEntityManager().createNamedQuery("XXService.findByServiceDefId", tClass) + .setParameter("serviceDefId", serviceDefId).getResultList(); + } catch (NoResultException e) { + return new ArrayList<>(); + } + } + + public List findByTagServiceId(Long tagServiceId) { + if (tagServiceId == null) { + return new ArrayList<>(); + } + + try { + return getEntityManager().createNamedQuery("XXService.findByTagServiceId", tClass) + .setParameter("tagServiceId", tagServiceId).getResultList(); + } catch (NoResultException e) { + return new ArrayList<>(); + } + } + + public List findIdsByTagServiceId(Long tagServiceId) { + List ret = null; + + try { + ret = getEntityManager().createNamedQuery("XXService.findIdsByTagServiceId", Long.class) + .setParameter("tagServiceId", tagServiceId).getResultList(); + } catch (NoResultException e) { + // ignre + } + + return ret != null ? ret : Collections.emptyList(); + } + + public XXService findAssociatedTagService(String serviceName) { + try { + return getEntityManager().createNamedQuery("XXService.findAssociatedTagService", tClass) + .setParameter("serviceName", serviceName).getSingleResult(); + } catch (NoResultException e) { + return null; + } + } + + public List getAllServicesWithTagService() { + try { + return getEntityManager().createNamedQuery("XXService.getAllServicesWithTagService", tClass) + .getResultList(); + } catch (NoResultException e) { + return new ArrayList<>(); + } + } + + public void updateSequence() { + Long maxId = getMaxIdOfXXService(); + + if (maxId == null) { + return; + } + + updateSequence("X_SERVICE_SEQ", maxId + 1); + } + + public List getAllServiceIds() { + try { + return getEntityManager().createNamedQuery("XXService.getAllServiceIds", Long.class) + .getResultList(); + } catch (NoResultException e) { + return new ArrayList<>(); + } + } + + public List findServiceHeaders() { + List ret; + + try { + List results = getEntityManager().createNamedQuery("XXService.getAllServiceHeaders", Object[].class).getResultList(); + + ret = new ArrayList<>(results.size()); + + for (Object[] result : results) { + ret.add(new RangerServiceHeaderInfo((Long) result[0], (String) result[1], (String) result[2], (String) result[3], (Boolean) result[4])); + } + } catch (NoResultException excp) { + ret = Collections.emptyList(); + } + + return ret; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/db/XXServiceDefDao.java b/security-admin/src/main/java/org/apache/ranger/db/XXServiceDefDao.java index 13642417df..fe1053e75d 100644 --- a/security-admin/src/main/java/org/apache/ranger/db/XXServiceDefDao.java +++ b/security-admin/src/main/java/org/apache/ranger/db/XXServiceDefDao.java @@ -17,165 +17,183 @@ package org.apache.ranger.db; -import javax.persistence.NoResultException; - import org.apache.commons.lang.StringUtils; import org.apache.ranger.common.db.BaseDao; import org.apache.ranger.entity.XXServiceDef; import org.springframework.stereotype.Service; +import javax.persistence.NoResultException; + +import java.util.Collections; +import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.HashMap; -import java.util.Collections; import java.util.Objects; @Service public class XXServiceDefDao extends BaseDao { - /** - * Default Constructor - */ - public XXServiceDefDao(RangerDaoManagerBase daoManager) { - super(daoManager); - } - - public XXServiceDef findByName(String name) { - if (name == null) { - return null; - } - try { - XXServiceDef xServiceDef = getEntityManager() - .createNamedQuery("XXServiceDef.findByName", tClass) - .setParameter("name", name).getSingleResult(); - return xServiceDef; - } catch (NoResultException e) { - return null; - } - } - - public XXServiceDef findByDisplayName(String displayName) { - if (Objects.isNull(displayName)) { - return null; - } - try { - XXServiceDef xServiceDef = getEntityManager() - .createNamedQuery("XXServiceDef.findByDisplayName", tClass) - .setParameter("displayName", displayName).getSingleResult(); - return xServiceDef; - } catch (NoResultException e) { - return null; - } - } - - - public Long getMaxIdOfXXServiceDef() { - try { - return (Long) getEntityManager().createNamedQuery("XXServiceDef.getMaxIdOfXXServiceDef").getSingleResult(); - } catch (NoResultException e) { - return null; - } - } - - public void updateSequence() { - Long maxId = getMaxIdOfXXServiceDef(); - - if(maxId == null) { - return; - } - - updateSequence("X_SERVICE_DEF_SEQ", maxId + 1); - } - - public String findServiceDefTypeByServiceName(String serviceName) { - String serviceType = null; - if (StringUtils.isNotBlank(serviceName)) { - try { - serviceType = getEntityManager() - .createNamedQuery("XXServiceDef.findServiceDefNameByServiceName", String.class) - .setParameter("name", serviceName).getSingleResult(); - } catch (NoResultException e) { - return null; - } + /** + * Default Constructor + */ + public XXServiceDefDao(RangerDaoManagerBase daoManager) { + super(daoManager); + } + + public XXServiceDef findByName(String name) { + if (name == null) { + return null; + } + + try { + return getEntityManager() + .createNamedQuery("XXServiceDef.findByName", tClass) + .setParameter("name", name).getSingleResult(); + } catch (NoResultException e) { + return null; + } + } + + public XXServiceDef findByDisplayName(String displayName) { + if (Objects.isNull(displayName)) { + return null; + } + + try { + return getEntityManager() + .createNamedQuery("XXServiceDef.findByDisplayName", tClass) + .setParameter("displayName", displayName).getSingleResult(); + } catch (NoResultException e) { + return null; + } + } + + public Long getMaxIdOfXXServiceDef() { + try { + return (Long) getEntityManager().createNamedQuery("XXServiceDef.getMaxIdOfXXServiceDef").getSingleResult(); + } catch (NoResultException e) { + return null; + } + } + + public void updateSequence() { + Long maxId = getMaxIdOfXXServiceDef(); + + if (maxId == null) { + return; + } + + updateSequence("X_SERVICE_DEF_SEQ", maxId + 1); + } + + public String findServiceDefTypeByServiceName(String serviceName) { + String serviceType = null; + + if (StringUtils.isNotBlank(serviceName)) { + try { + serviceType = getEntityManager() + .createNamedQuery("XXServiceDef.findServiceDefNameByServiceName", String.class) + .setParameter("name", serviceName) + .getSingleResult(); + } catch (NoResultException e) { + return null; + } + } + + return serviceType; + } + + public String findServiceDefTypeByServiceId(Long serviceId) { + String serviceType; + + try { + serviceType = getEntityManager() + .createNamedQuery("XXServiceDef.findServiceDefNameByServiceId", String.class) + .setParameter("id", serviceId) + .getSingleResult(); + } catch (NoResultException e) { + return null; + } + + return serviceType; + } + + /** + * Fetch and return names of service type/ def which are using context enrichers. + * + * @return {@link java.util.List list} of {@link java.lang.String strings} representing service type/ def + */ + public List findAllHavingEnrichers() { + return getEntityManager().createNamedQuery("XXServiceDef.getNameByHasEnricher", String.class).getResultList(); + } + + /** + * Fetch and return count of services for each service type/ def + * + * @return {@link java.util.Map map} representing service type/ def as key and their respective service count as value + */ + public Map getServiceCount() { + Map ret = Collections.emptyMap(); + List rows = getEntityManager().createNamedQuery("XXServiceDef.getServiceCount", Object[].class).getResultList(); + + if (rows != null) { + ret = new HashMap<>(); + + for (Object[] row : rows) { + if (Objects.nonNull(row) && Objects.nonNull(row[0]) && Objects.nonNull(row[1]) && (!row[0].toString().isEmpty())) { + // since group by query will not return empty count field, no need to check + ret.put((String) row[0], (Long) row[1]); + } + } + } + + return ret; + } + + /** + * Fetch and return count of policies for each service type/ def + * + * @return {@link java.util.Map map} representing service type/ def as key and their respective policy count as value + */ + public Map getPolicyCountByType(int policyType) { + Map ret = Collections.emptyMap(); + List rows = getEntityManager().createNamedQuery("XXServiceDef.getPolicyCountByType", Object[].class) + .setParameter("policyType", policyType) + .getResultList(); + + if (rows != null) { + ret = new HashMap<>(); + + for (Object[] row : rows) { + if (Objects.nonNull(row) && Objects.nonNull(row[0]) && Objects.nonNull(row[1]) && (!row[0].toString().isEmpty())) { + // since group by query will not return empty count field, no need to check + ret.put((String) row[0], (Long) row[1]); + } + } + } + + return ret; + } + + /** + * Fetch and return count of deny items (conditions) for each service type/ def + * + * @return {@link java.util.Map map} representing service type/ def as key and their respective deny items (conditions) count as value + */ + public Map getPolicyCountByDenyItems() { + Map ret = Collections.emptyMap(); + List rows = getEntityManager().createNamedQuery("XXServiceDef.getPolicyCountByDenyItems", Object[].class).getResultList(); + + if (rows != null) { + ret = new HashMap<>(); + + for (Object[] row : rows) { + if (Objects.nonNull(row) && Objects.nonNull(row[0]) && Objects.nonNull(row[1]) && (!row[0].toString().isEmpty())) { + // since group by query will not return empty count field, no need to check + ret.put((String) row[0], (Long) row[1]); } - return serviceType; + } } - public String findServiceDefTypeByServiceId(Long serviceId) { - String serviceType = null; - try { - serviceType = getEntityManager() - .createNamedQuery("XXServiceDef.findServiceDefNameByServiceId", String.class) - .setParameter("id", serviceId).getSingleResult(); - } catch (NoResultException e) { - return null; - } - return serviceType; - } - - /** - * Fetch and return names of service type/ def which are using context enrichers. - * @return {@link java.util.List list} of {@link java.lang.String strings} representing service type/ def - */ - public List findAllHavingEnrichers() { - return getEntityManager().createNamedQuery("XXServiceDef.getNameByHasEnricher", String.class).getResultList(); - } - - /** - * Fetch and return count of services for each service type/ def - * @return {@link java.util.Map map} representing service type/ def as key and their respective service count as value - */ - public Map getServiceCount() { - Map ret = Collections.emptyMap(); - List rows = (List) getEntityManager().createNamedQuery("XXServiceDef.getServiceCount").getResultList(); - if (rows != null) { - ret = new HashMap<>(); - for (Object[] row : rows) { - if (Objects.nonNull(row) && Objects.nonNull(row[0]) && Objects.nonNull(row[1]) && (!row[0].toString().isEmpty())) { - // since group by query will not return empty count field, no need to check - ret.put((String) row[0], (Long) row[1]); - } - } - } - return ret; - } - - /** - * Fetch and return count of policies for each service type/ def - * @return {@link java.util.Map map} representing service type/ def as key and their respective policy count as value - */ - public Map getPolicyCountByType(int policyType) { - Map ret = Collections.emptyMap(); - List rows = (List) getEntityManager().createNamedQuery("XXServiceDef.getPolicyCountByType") - .setParameter("policyType", policyType) - .getResultList(); - if (rows != null) { - ret = new HashMap<>(); - for (Object[] row : rows) { - if (Objects.nonNull(row) && Objects.nonNull(row[0]) && Objects.nonNull(row[1]) && (!row[0].toString().isEmpty())) { - // since group by query will not return empty count field, no need to check - ret.put((String) row[0], (Long) row[1]); - } - } - } - return ret; - } - - /** - * Fetch and return count of deny items (conditions) for each service type/ def - * @return {@link java.util.Map map} representing service type/ def as key and their respective deny items (conditions) count as value - */ - public Map getPolicyCountByDenyItems() { - Map ret = Collections.emptyMap(); - List rows = (List) getEntityManager().createNamedQuery("XXServiceDef.getPolicyCountByDenyItems").getResultList(); - if (rows != null) { - ret = new HashMap<>(); - for (Object[] row : rows) { - if (Objects.nonNull(row) && Objects.nonNull(row[0]) && Objects.nonNull(row[1]) && (!row[0].toString().isEmpty())) { - // since group by query will not return empty count field, no need to check - ret.put((String) row[0], (Long) row[1]); - } - } - } - return ret; - } -} \ No newline at end of file + return ret; + } +} diff --git a/security-admin/src/main/java/org/apache/ranger/db/XXServiceDefWithAssignedIdDao.java b/security-admin/src/main/java/org/apache/ranger/db/XXServiceDefWithAssignedIdDao.java index 5a4eb115c7..2a2e58e3fc 100644 --- a/security-admin/src/main/java/org/apache/ranger/db/XXServiceDefWithAssignedIdDao.java +++ b/security-admin/src/main/java/org/apache/ranger/db/XXServiceDefWithAssignedIdDao.java @@ -23,9 +23,7 @@ @Service public class XXServiceDefWithAssignedIdDao extends BaseDao { - - public XXServiceDefWithAssignedIdDao(RangerDaoManagerBase daoManager) { - super(daoManager); - } - + public XXServiceDefWithAssignedIdDao(RangerDaoManagerBase daoManager) { + super(daoManager); + } } diff --git a/security-admin/src/main/java/org/apache/ranger/db/XXServiceResourceDao.java b/security-admin/src/main/java/org/apache/ranger/db/XXServiceResourceDao.java index 5c0878cb95..2121aec502 100644 --- a/security-admin/src/main/java/org/apache/ranger/db/XXServiceResourceDao.java +++ b/security-admin/src/main/java/org/apache/ranger/db/XXServiceResourceDao.java @@ -19,11 +19,6 @@ package org.apache.ranger.db; -import java.util.ArrayList; -import java.util.List; - -import javax.persistence.NoResultException; - import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang.StringUtils; import org.apache.ranger.authorization.utils.StringUtil; @@ -31,63 +26,74 @@ import org.apache.ranger.entity.XXServiceResource; import org.springframework.stereotype.Service; +import javax.persistence.NoResultException; + +import java.util.ArrayList; +import java.util.List; + @Service public class XXServiceResourceDao extends BaseDao { + public XXServiceResourceDao(RangerDaoManagerBase daoManager) { + super(daoManager); + } + + public XXServiceResource findByGuid(String guid) { + if (StringUtil.isEmpty(guid)) { + return null; + } + + try { + return getEntityManager().createNamedQuery("XXServiceResource.findByGuid", tClass) + .setParameter("guid", guid).getSingleResult(); + } catch (NoResultException e) { + return null; + } + } + + public List findByServiceId(Long serviceId) { + if (serviceId == null) { + return new ArrayList<>(); + } + + try { + return getEntityManager().createNamedQuery("XXServiceResource.findByServiceId", tClass) + .setParameter("serviceId", serviceId).getResultList(); + } catch (NoResultException e) { + return new ArrayList<>(); + } + } + + public XXServiceResource findByServiceAndResourceSignature(Long serviceId, String resourceSignature) { + if (StringUtils.isBlank(resourceSignature)) { + return null; + } - public XXServiceResourceDao(RangerDaoManagerBase daoManager) { - super(daoManager); - } - - public XXServiceResource findByGuid(String guid) { - if (StringUtil.isEmpty(guid)) { - return null; - } - try { - return getEntityManager().createNamedQuery("XXServiceResource.findByGuid", tClass) - .setParameter("guid", guid).getSingleResult(); - } catch (NoResultException e) { - return null; - } - } - - public List findByServiceId(Long serviceId) { - if (serviceId == null) { - return new ArrayList(); - } - try { - return getEntityManager().createNamedQuery("XXServiceResource.findByServiceId", tClass) - .setParameter("serviceId", serviceId).getResultList(); - } catch (NoResultException e) { - return new ArrayList(); - } - } - - public XXServiceResource findByServiceAndResourceSignature(Long serviceId, String resourceSignature) { - if (StringUtils.isBlank(resourceSignature)) { - return null; - } - try { - return getEntityManager().createNamedQuery("XXServiceResource.findByServiceAndResourceSignature", tClass) - .setParameter("serviceId", serviceId).setParameter("resourceSignature", resourceSignature) - .getSingleResult(); - } catch (NoResultException e) { - return null; - } - } - - public List findTaggedResourcesInServiceId(Long serviceId) { - List ret = new ArrayList<>(); - if (serviceId != null) { + try { + return getEntityManager().createNamedQuery("XXServiceResource.findByServiceAndResourceSignature", tClass) + .setParameter("serviceId", serviceId).setParameter("resourceSignature", resourceSignature) + .getSingleResult(); + } catch (NoResultException e) { + return null; + } + } + + public List findTaggedResourcesInServiceId(Long serviceId) { + List ret = new ArrayList<>(); + + if (serviceId != null) { List rows = null; + try { rows = getEntityManager().createNamedQuery("XXServiceResource.findTaggedResourcesInServiceId", Object[].class) .setParameter("serviceId", serviceId).getResultList(); } catch (NoResultException e) { // Nothing } + if (CollectionUtils.isNotEmpty(rows)) { for (Object[] row : rows) { XXServiceResource xxServiceResource = new XXServiceResource(); + xxServiceResource.setId((Long) row[0]); xxServiceResource.setGuid((String) row[1]); xxServiceResource.setVersion((Long) row[2]); @@ -101,42 +107,46 @@ public List findTaggedResourcesInServiceId(Long serviceId) { } } } + return ret; - } - - public long countTaggedResourcesInServiceId(Long serviceId) { - if (serviceId == null) { - return -1; - } - try { - return getEntityManager().createNamedQuery("XXServiceResource.countTaggedResourcesInServiceId", Long.class) - .setParameter("serviceId", serviceId).getSingleResult(); - } catch (NoResultException e) { - return -1; - } - } - - public List findForServicePlugin(Long serviceId) { - if (serviceId == null) { - return new ArrayList(); - } - try { - return getEntityManager().createNamedQuery("XXServiceResource.findForServicePlugin", tClass) - .setParameter("serviceId", serviceId).getResultList(); - } catch (NoResultException e) { - return new ArrayList(); - } - } - - public List findServiceResourceGuidsInServiceId(Long serviceId) { - if (serviceId == null) { - return new ArrayList(); - } - try { - return getEntityManager().createNamedQuery("XXServiceResource.findServiceResourceGuidsInServiceId", String.class) - .setParameter("serviceId", serviceId).getResultList(); - } catch (NoResultException e) { - return new ArrayList(); - } - } + } + + public long countTaggedResourcesInServiceId(Long serviceId) { + if (serviceId == null) { + return -1; + } + + try { + return getEntityManager().createNamedQuery("XXServiceResource.countTaggedResourcesInServiceId", Long.class) + .setParameter("serviceId", serviceId).getSingleResult(); + } catch (NoResultException e) { + return -1; + } + } + + public List findForServicePlugin(Long serviceId) { + if (serviceId == null) { + return new ArrayList<>(); + } + + try { + return getEntityManager().createNamedQuery("XXServiceResource.findForServicePlugin", tClass) + .setParameter("serviceId", serviceId).getResultList(); + } catch (NoResultException e) { + return new ArrayList<>(); + } + } + + public List findServiceResourceGuidsInServiceId(Long serviceId) { + if (serviceId == null) { + return new ArrayList<>(); + } + + try { + return getEntityManager().createNamedQuery("XXServiceResource.findServiceResourceGuidsInServiceId", String.class) + .setParameter("serviceId", serviceId).getResultList(); + } catch (NoResultException e) { + return new ArrayList<>(); + } + } } diff --git a/security-admin/src/main/java/org/apache/ranger/db/XXServiceResourceElementDao.java b/security-admin/src/main/java/org/apache/ranger/db/XXServiceResourceElementDao.java index ece8c2e311..abdd59f291 100644 --- a/security-admin/src/main/java/org/apache/ranger/db/XXServiceResourceElementDao.java +++ b/security-admin/src/main/java/org/apache/ranger/db/XXServiceResourceElementDao.java @@ -19,59 +19,60 @@ package org.apache.ranger.db; -import java.util.ArrayList; -import java.util.List; - -import javax.persistence.NoResultException; - import org.apache.ranger.common.db.BaseDao; import org.apache.ranger.entity.XXServiceResourceElement; import org.springframework.stereotype.Service; +import javax.persistence.NoResultException; + +import java.util.ArrayList; +import java.util.List; + @Service public class XXServiceResourceElementDao extends BaseDao { + public XXServiceResourceElementDao(RangerDaoManagerBase daoManager) { + super(daoManager); + } + + public List findByResourceId(Long resourceId) { + if (resourceId == null) { + return new ArrayList<>(); + } - public XXServiceResourceElementDao(RangerDaoManagerBase daoManager) { - super(daoManager); - } + try { + return getEntityManager().createNamedQuery("XXServiceResourceElement.findByResourceId", tClass) + .setParameter("resourceId", resourceId) + .getResultList(); + } catch (NoResultException e) { + return new ArrayList<>(); + } + } - public List findByResourceId(Long resourceId) { - if (resourceId == null) { - return new ArrayList(); - } - try { - return getEntityManager().createNamedQuery("XXServiceResourceElement.findByResourceId", tClass) - .setParameter("resourceId", resourceId) - .getResultList(); - } catch (NoResultException e) { - return new ArrayList(); - } - } + public List findByServiceId(Long serviceId) { + if (serviceId == null) { + return new ArrayList<>(); + } - public List findByServiceId(Long serviceId) { - if (serviceId == null) { - return new ArrayList(); - } - try { - return getEntityManager().createNamedQuery("XXServiceResourceElement.findByServiceId", tClass) - .setParameter("serviceId", serviceId) - .getResultList(); - } catch (NoResultException e) { - return new ArrayList(); - } - } + try { + return getEntityManager().createNamedQuery("XXServiceResourceElement.findByServiceId", tClass) + .setParameter("serviceId", serviceId) + .getResultList(); + } catch (NoResultException e) { + return new ArrayList<>(); + } + } - public List findTaggedResourcesInServiceId(Long serviceId) { - if (serviceId == null) { - return new ArrayList(); - } - try { - return getEntityManager().createNamedQuery("XXServiceResourceElement.findTaggedResourcesInServiceId", tClass) - .setParameter("serviceId", serviceId) - .getResultList(); - } catch (NoResultException e) { - return new ArrayList(); - } - } + public List findTaggedResourcesInServiceId(Long serviceId) { + if (serviceId == null) { + return new ArrayList<>(); + } + try { + return getEntityManager().createNamedQuery("XXServiceResourceElement.findTaggedResourcesInServiceId", tClass) + .setParameter("serviceId", serviceId) + .getResultList(); + } catch (NoResultException e) { + return new ArrayList<>(); + } + } } diff --git a/security-admin/src/main/java/org/apache/ranger/db/XXServiceResourceElementValueDao.java b/security-admin/src/main/java/org/apache/ranger/db/XXServiceResourceElementValueDao.java index 1d6a1ea994..f56d9297b3 100644 --- a/security-admin/src/main/java/org/apache/ranger/db/XXServiceResourceElementValueDao.java +++ b/security-admin/src/main/java/org/apache/ranger/db/XXServiceResourceElementValueDao.java @@ -19,83 +19,83 @@ package org.apache.ranger.db; -import java.util.ArrayList; -import java.util.List; - -import javax.persistence.NoResultException; - import org.apache.ranger.common.db.BaseDao; import org.apache.ranger.entity.XXServiceResourceElementValue; import org.springframework.stereotype.Service; +import javax.persistence.NoResultException; + +import java.util.ArrayList; +import java.util.List; + @Service public class XXServiceResourceElementValueDao extends BaseDao { + public XXServiceResourceElementValueDao(RangerDaoManagerBase daoManager) { + super(daoManager); + } + + public List findByResValueId(Long resElementId) { + if (resElementId == null) { + return new ArrayList<>(); + } + + try { + return getEntityManager().createNamedQuery("XXServiceResourceElementValue.findByResElementId", tClass) + .setParameter("resElementId", resElementId).getResultList(); + } catch (NoResultException e) { + return new ArrayList<>(); + } + } + + public List findValuesByResElementId(Long resElementId) { + if (resElementId == null) { + return new ArrayList<>(); + } + + try { + return getEntityManager().createNamedQuery("XXServiceResourceElementValue.findValuesByResElementId", String.class) + .setParameter("resElementId", resElementId).getResultList(); + } catch (NoResultException e) { + return new ArrayList<>(); + } + } + + public List findByServiceId(Long serviceId) { + if (serviceId == null) { + return new ArrayList<>(); + } - public XXServiceResourceElementValueDao(RangerDaoManagerBase daoManager) { - super(daoManager); - } + try { + return getEntityManager().createNamedQuery("XXServiceResourceElementValue.findByServiceId", tClass) + .setParameter("serviceId", serviceId).getResultList(); + } catch (NoResultException e) { + return new ArrayList<>(); + } + } - public List findByResValueId(Long resElementId) { - if (resElementId == null) { - return new ArrayList(); - } - try { - return getEntityManager().createNamedQuery("XXServiceResourceElementValue.findByResElementId", tClass) - .setParameter("resElementId", resElementId).getResultList(); - } catch (NoResultException e) { - return new ArrayList(); - } - } - - @SuppressWarnings("unchecked") - public List findValuesByResElementId(Long resElementId) { - if (resElementId == null) { - return new ArrayList(); - } - try { - return getEntityManager().createNamedQuery("XXServiceResourceElementValue.findValuesByResElementId") - .setParameter("resElementId", resElementId).getResultList(); - } catch (NoResultException e) { - return new ArrayList(); - } - } + public List findTaggedResourcesInServiceId(Long serviceId) { + if (serviceId == null) { + return new ArrayList<>(); + } - @SuppressWarnings("unchecked") - public List findByServiceId(Long serviceId) { - if (serviceId == null) { - return new ArrayList(); - } - try { - return getEntityManager().createNamedQuery("XXServiceResourceElementValue.findByServiceId") - .setParameter("serviceId", serviceId).getResultList(); - } catch (NoResultException e) { - return new ArrayList(); - } - } + try { + return getEntityManager().createNamedQuery("XXServiceResourceElementValue.findTaggedResourcesInServiceId", tClass) + .setParameter("serviceId", serviceId).getResultList(); + } catch (NoResultException e) { + return new ArrayList<>(); + } + } - @SuppressWarnings("unchecked") - public List findTaggedResourcesInServiceId(Long serviceId) { - if (serviceId == null) { - return new ArrayList(); - } - try { - return getEntityManager().createNamedQuery("XXServiceResourceElementValue.findTaggedResourcesInServiceId") - .setParameter("serviceId", serviceId).getResultList(); - } catch (NoResultException e) { - return new ArrayList(); - } - } + public List findByResourceId(Long resourceId) { + if (resourceId == null) { + return new ArrayList<>(); + } - @SuppressWarnings("unchecked") - public List findByResourceId(Long resourceId) { - if (resourceId == null) { - return new ArrayList(); - } - try { - return getEntityManager().createNamedQuery("XXServiceResourceElementValue.findByResourceId") - .setParameter("resourceId", resourceId).getResultList(); - } catch (NoResultException e) { - return new ArrayList(); - } - } + try { + return getEntityManager().createNamedQuery("XXServiceResourceElementValue.findByResourceId", tClass) + .setParameter("resourceId", resourceId).getResultList(); + } catch (NoResultException e) { + return new ArrayList<>(); + } + } } diff --git a/security-admin/src/main/java/org/apache/ranger/db/XXServiceVersionInfoDao.java b/security-admin/src/main/java/org/apache/ranger/db/XXServiceVersionInfoDao.java index 1e4995af56..05bba57617 100644 --- a/security-admin/src/main/java/org/apache/ranger/db/XXServiceVersionInfoDao.java +++ b/security-admin/src/main/java/org/apache/ranger/db/XXServiceVersionInfoDao.java @@ -17,10 +17,6 @@ package org.apache.ranger.db; -import java.util.List; - -import javax.persistence.NoResultException; - import org.apache.commons.collections.CollectionUtils; import org.apache.ranger.biz.ServiceDBStore; import org.apache.ranger.common.db.BaseDao; @@ -30,137 +26,148 @@ import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; +import javax.persistence.NoResultException; + +import java.util.List; + /** + * */ @Service public class XXServiceVersionInfoDao extends BaseDao { - - private static final Logger LOG = LoggerFactory.getLogger(XXServiceVersionInfoDao.class); - - /** - * Default Constructor - */ - public XXServiceVersionInfoDao(RangerDaoManagerBase daoManager) { - super(daoManager); - } - - public XXServiceVersionInfo findByServiceName(String serviceName) { - if (serviceName == null) { - return null; - } - try { - return getEntityManager() - .createNamedQuery("XXServiceVersionInfo.findByServiceName", tClass) - .setParameter("serviceName", serviceName).getSingleResult(); - } catch (NoResultException e) { - return null; - } - } - - public XXServiceVersionInfo findByServiceId(Long serviceId) { - if (serviceId == null) { - return null; - } - try { - return getEntityManager().createNamedQuery("XXServiceVersionInfo.findByServiceId", tClass) - .setParameter("serviceId", serviceId).getSingleResult(); - } catch (NoResultException e) { - return null; - } - } - - @SuppressWarnings("unchecked") - public List getAllWithServiceNames(){ - return getEntityManager() - .createNamedQuery("XXServiceVersionInfo.getAllWithServiceNames") - .getResultList(); - } - - public void updateServiceVersionInfoForTagResourceMapCreate(Long resourceId, Long tagId) { - if (resourceId == null || tagId == null) { - LOG.warn("Unexpected null value for resourceId and/or tagId"); - return; - } - - try { - List serviceVersionInfos = getEntityManager().createNamedQuery("XXServiceVersionInfo.findByServiceResourceId", tClass).setParameter("resourceId", resourceId).getResultList(); - - updateTagVersionAndTagUpdateTime(serviceVersionInfos, resourceId, tagId); - } catch (NoResultException e) { - } - } - - public void updateServiceVersionInfoForTagResourceMapDelete(Long resourceId, Long tagId) { - if (resourceId == null || tagId == null) { - LOG.warn("Unexpected null value for resourceId and/or tagId"); - return; - } - - try { - List serviceVersionInfos = getEntityManager().createNamedQuery("XXServiceVersionInfo.findByServiceResourceId", tClass).setParameter("resourceId", resourceId).getResultList(); - - updateTagVersionAndTagUpdateTime(serviceVersionInfos, resourceId, tagId); - } catch (NoResultException e) { - } - } - public void updateServiceVersionInfoForServiceResourceUpdate(Long resourceId) { - if (resourceId == null) { - LOG.warn("Unexpected null value for resourceId"); - return; - } - - Long tagId = null; - - try { - List serviceVersionInfos = getEntityManager().createNamedQuery("XXServiceVersionInfo.findByServiceResourceId", tClass).setParameter("resourceId", resourceId).getResultList(); - - updateTagVersionAndTagUpdateTime(serviceVersionInfos, resourceId, tagId); - } catch (NoResultException e) { - } - } - - public void updateServiceVersionInfoForTagUpdate(Long tagId) { - if (tagId == null) { - LOG.warn("Unexpected null value for tagId"); - return; - } - - Long resourceId = null; - try { - List serviceVersionInfos = getEntityManager().createNamedQuery("XXServiceVersionInfo.findByTagId", tClass).setParameter("tagId", tagId).getResultList(); - - updateTagVersionAndTagUpdateTime(serviceVersionInfos, resourceId, tagId); - } catch (NoResultException e) { - } - } - - private void updateTagVersionAndTagUpdateTime(List serviceVersionInfos, Long resourceId, Long tagId) { - - if (resourceId != null || tagId != null) { - if (CollectionUtils.isNotEmpty(serviceVersionInfos)) { - - final ServiceDBStore.VERSION_TYPE versionType = ServiceDBStore.VERSION_TYPE.TAG_VERSION; - final ServiceTags.TagsChangeType tagChangeType; - - if (tagId == null) { - tagChangeType = ServiceTags.TagsChangeType.SERVICE_RESOURCE_UPDATE; - } else if (resourceId == null) { - tagChangeType = ServiceTags.TagsChangeType.TAG_UPDATE; - } else { - tagChangeType = ServiceTags.TagsChangeType.TAG_RESOURCE_MAP_UPDATE; - } - - for (XXServiceVersionInfo serviceVersionInfo : serviceVersionInfos) { - - final Long serviceId = serviceVersionInfo.getServiceId(); - final Runnable serviceVersionUpdater = new ServiceDBStore.ServiceVersionUpdater(daoManager, serviceId, versionType, tagChangeType, resourceId, tagId); - - daoManager.getRangerTransactionSynchronizationAdapter().executeOnTransactionCommit(serviceVersionUpdater); - } - } - } else { - LOG.warn("Both resourceId and tagId are null! Should not have come here!"); - } - - } + private static final Logger LOG = LoggerFactory.getLogger(XXServiceVersionInfoDao.class); + + /** + * Default Constructor + */ + public XXServiceVersionInfoDao(RangerDaoManagerBase daoManager) { + super(daoManager); + } + + public XXServiceVersionInfo findByServiceName(String serviceName) { + if (serviceName == null) { + return null; + } + + try { + return getEntityManager() + .createNamedQuery("XXServiceVersionInfo.findByServiceName", tClass) + .setParameter("serviceName", serviceName).getSingleResult(); + } catch (NoResultException e) { + return null; + } + } + + public XXServiceVersionInfo findByServiceId(Long serviceId) { + if (serviceId == null) { + return null; + } + + try { + return getEntityManager().createNamedQuery("XXServiceVersionInfo.findByServiceId", tClass) + .setParameter("serviceId", serviceId).getSingleResult(); + } catch (NoResultException e) { + return null; + } + } + + public List getAllWithServiceNames() { + return getEntityManager() + .createNamedQuery("XXServiceVersionInfo.getAllWithServiceNames", Object[].class) + .getResultList(); + } + + public void updateServiceVersionInfoForTagResourceMapCreate(Long resourceId, Long tagId) { + if (resourceId == null || tagId == null) { + LOG.warn("Unexpected null value for resourceId and/or tagId"); + + return; + } + + try { + List serviceVersionInfos = getEntityManager().createNamedQuery("XXServiceVersionInfo.findByServiceResourceId", tClass).setParameter("resourceId", resourceId).getResultList(); + + updateTagVersionAndTagUpdateTime(serviceVersionInfos, resourceId, tagId); + } catch (NoResultException e) { + // ignore + } + } + + public void updateServiceVersionInfoForTagResourceMapDelete(Long resourceId, Long tagId) { + if (resourceId == null || tagId == null) { + LOG.warn("Unexpected null value for resourceId and/or tagId"); + + return; + } + + try { + List serviceVersionInfos = getEntityManager().createNamedQuery("XXServiceVersionInfo.findByServiceResourceId", tClass).setParameter("resourceId", resourceId).getResultList(); + + updateTagVersionAndTagUpdateTime(serviceVersionInfos, resourceId, tagId); + } catch (NoResultException e) { + // ignore + } + } + + public void updateServiceVersionInfoForServiceResourceUpdate(Long resourceId) { + if (resourceId == null) { + LOG.warn("Unexpected null value for resourceId"); + + return; + } + + Long tagId = null; + + try { + List serviceVersionInfos = getEntityManager().createNamedQuery("XXServiceVersionInfo.findByServiceResourceId", tClass).setParameter("resourceId", resourceId).getResultList(); + + updateTagVersionAndTagUpdateTime(serviceVersionInfos, resourceId, tagId); + } catch (NoResultException e) { + // ignore + } + } + + public void updateServiceVersionInfoForTagUpdate(Long tagId) { + if (tagId == null) { + LOG.warn("Unexpected null value for tagId"); + + return; + } + + Long resourceId = null; + + try { + List serviceVersionInfos = getEntityManager().createNamedQuery("XXServiceVersionInfo.findByTagId", tClass).setParameter("tagId", tagId).getResultList(); + + updateTagVersionAndTagUpdateTime(serviceVersionInfos, resourceId, tagId); + } catch (NoResultException e) { + // ignore + } + } + + private void updateTagVersionAndTagUpdateTime(List serviceVersionInfos, Long resourceId, Long tagId) { + if (resourceId != null || tagId != null) { + if (CollectionUtils.isNotEmpty(serviceVersionInfos)) { + final ServiceDBStore.VERSION_TYPE versionType = ServiceDBStore.VERSION_TYPE.TAG_VERSION; + final ServiceTags.TagsChangeType tagChangeType; + + if (tagId == null) { + tagChangeType = ServiceTags.TagsChangeType.SERVICE_RESOURCE_UPDATE; + } else if (resourceId == null) { + tagChangeType = ServiceTags.TagsChangeType.TAG_UPDATE; + } else { + tagChangeType = ServiceTags.TagsChangeType.TAG_RESOURCE_MAP_UPDATE; + } + + for (XXServiceVersionInfo serviceVersionInfo : serviceVersionInfos) { + final Long serviceId = serviceVersionInfo.getServiceId(); + final Runnable serviceVersionUpdater = new ServiceDBStore.ServiceVersionUpdater(daoManager, serviceId, versionType, tagChangeType, resourceId, tagId); + + daoManager.getRangerTransactionSynchronizationAdapter().executeOnTransactionCommit(serviceVersionUpdater); + } + } + } else { + LOG.warn("Both resourceId and tagId are null! Should not have come here!"); + } + } } diff --git a/security-admin/src/main/java/org/apache/ranger/db/XXServiceWithAssignedIdDao.java b/security-admin/src/main/java/org/apache/ranger/db/XXServiceWithAssignedIdDao.java index 6f11d16b97..44d8f56856 100644 --- a/security-admin/src/main/java/org/apache/ranger/db/XXServiceWithAssignedIdDao.java +++ b/security-admin/src/main/java/org/apache/ranger/db/XXServiceWithAssignedIdDao.java @@ -23,9 +23,7 @@ @Service public class XXServiceWithAssignedIdDao extends BaseDao { - - public XXServiceWithAssignedIdDao(RangerDaoManagerBase daoManager) { - super(daoManager); - } - + public XXServiceWithAssignedIdDao(RangerDaoManagerBase daoManager) { + super(daoManager); + } } diff --git a/security-admin/src/main/java/org/apache/ranger/db/XXTagAttributeDao.java b/security-admin/src/main/java/org/apache/ranger/db/XXTagAttributeDao.java index 474ef2811e..73317f69c2 100644 --- a/security-admin/src/main/java/org/apache/ranger/db/XXTagAttributeDao.java +++ b/security-admin/src/main/java/org/apache/ranger/db/XXTagAttributeDao.java @@ -19,68 +19,72 @@ package org.apache.ranger.db; -import java.util.ArrayList; -import java.util.List; - -import javax.persistence.NoResultException; - import org.apache.ranger.common.db.BaseDao; import org.apache.ranger.entity.XXTagAttribute; import org.springframework.stereotype.Service; +import javax.persistence.NoResultException; + +import java.util.ArrayList; +import java.util.List; + @Service public class XXTagAttributeDao extends BaseDao { + public XXTagAttributeDao(RangerDaoManagerBase daoManager) { + super(daoManager); + } + + public List findByTagId(Long tagId) { + if (tagId == null) { + return new ArrayList<>(); + } + + try { + return getEntityManager().createNamedQuery("XXTagAttribute.findByTagId", tClass) + .setParameter("tagId", tagId).getResultList(); + } catch (NoResultException e) { + return new ArrayList<>(); + } + } + + public List findByServiceId(Long serviceId) { + if (serviceId == null) { + return new ArrayList<>(); + } + + try { + return getEntityManager().createNamedQuery("XXTagAttribute.findByServiceId", tClass) + .setParameter("serviceId", serviceId).getResultList(); + } catch (NoResultException e) { + return new ArrayList<>(); + } + } - public XXTagAttributeDao(RangerDaoManagerBase daoManager) { - super(daoManager); - } + public List findByServiceIdAndOwner(Long serviceId, Short owner) { + if (serviceId == null) { + return new ArrayList<>(); + } - public List findByTagId(Long tagId) { - if (tagId == null) { - return new ArrayList(); - } - try { - return getEntityManager().createNamedQuery("XXTagAttribute.findByTagId", tClass) - .setParameter("tagId", tagId).getResultList(); - } catch (NoResultException e) { - return new ArrayList(); - } - } + try { + return getEntityManager().createNamedQuery("XXTagAttribute.findByServiceIdAndOwner", tClass) + .setParameter("serviceId", serviceId) + .setParameter("owner", owner) + .getResultList(); + } catch (NoResultException e) { + return new ArrayList<>(); + } + } - public List findByServiceId(Long serviceId) { - if (serviceId == null) { - return new ArrayList(); - } - try { - return getEntityManager().createNamedQuery("XXTagAttribute.findByServiceId", tClass) - .setParameter("serviceId", serviceId).getResultList(); - } catch (NoResultException e) { - return new ArrayList(); - } - } + public List findByResourceId(Long resourceId) { + if (resourceId == null) { + return new ArrayList<>(); + } - public List findByServiceIdAndOwner(Long serviceId, Short owner) { - if (serviceId == null) { - return new ArrayList(); - } - try { - return getEntityManager().createNamedQuery("XXTagAttribute.findByServiceIdAndOwner", tClass) - .setParameter("serviceId", serviceId) - .setParameter("owner", owner) - .getResultList(); - } catch (NoResultException e) { - return new ArrayList(); - } - } - public List findByResourceId(Long resourceId) { - if (resourceId == null) { - return new ArrayList(); - } - try { - return getEntityManager().createNamedQuery("XXTagAttribute.findByResourceId", tClass) - .setParameter("resourceId", resourceId).getResultList(); - } catch (NoResultException e) { - return new ArrayList(); - } - } + try { + return getEntityManager().createNamedQuery("XXTagAttribute.findByResourceId", tClass) + .setParameter("resourceId", resourceId).getResultList(); + } catch (NoResultException e) { + return new ArrayList<>(); + } + } } diff --git a/security-admin/src/main/java/org/apache/ranger/db/XXTagAttributeDefDao.java b/security-admin/src/main/java/org/apache/ranger/db/XXTagAttributeDefDao.java index 3a9cf2c846..6ed5e5a943 100644 --- a/security-admin/src/main/java/org/apache/ranger/db/XXTagAttributeDefDao.java +++ b/security-admin/src/main/java/org/apache/ranger/db/XXTagAttributeDefDao.java @@ -19,55 +19,57 @@ package org.apache.ranger.db; -import java.util.ArrayList; -import java.util.List; - -import javax.persistence.NoResultException; - import org.apache.ranger.common.db.BaseDao; import org.apache.ranger.entity.XXTagAttributeDef; import org.springframework.stereotype.Service; +import javax.persistence.NoResultException; + +import java.util.ArrayList; +import java.util.List; + @Service public class XXTagAttributeDefDao extends BaseDao { + public XXTagAttributeDefDao(RangerDaoManagerBase daoManager) { + super(daoManager); + } + + public List findByTagDefId(Long tagDefId) { + if (tagDefId == null) { + return new ArrayList<>(); + } + + try { + return getEntityManager().createNamedQuery("XXTagAttributeDef.findByTagDefId", tClass) + .setParameter("tagDefId", tagDefId).getResultList(); + } catch (NoResultException e) { + return new ArrayList<>(); + } + } - public XXTagAttributeDefDao(RangerDaoManagerBase daoManager) { - super(daoManager); - } + public List findByServiceId(Long serviceId) { + if (serviceId == null) { + return new ArrayList<>(); + } - public List findByTagDefId(Long tagDefId) { - if (tagDefId == null) { - return new ArrayList(); - } - try { - return getEntityManager().createNamedQuery("XXTagAttributeDef.findByTagDefId", tClass) - .setParameter("tagDefId", tagDefId).getResultList(); - } catch (NoResultException e) { - return new ArrayList(); - } - } + try { + return getEntityManager().createNamedQuery("XXTagAttributeDef.findByServiceId", tClass) + .setParameter("serviceId", serviceId).getResultList(); + } catch (NoResultException e) { + return new ArrayList<>(); + } + } - public List findByServiceId(Long serviceId) { - if (serviceId == null) { - return new ArrayList(); - } - try { - return getEntityManager().createNamedQuery("XXTagAttributeDef.findByServiceId", tClass) - .setParameter("serviceId", serviceId).getResultList(); - } catch (NoResultException e) { - return new ArrayList(); - } - } + public List findByResourceId(Long resourceId) { + if (resourceId == null) { + return new ArrayList<>(); + } - public List findByResourceId(Long resourceId) { - if (resourceId == null) { - return new ArrayList(); - } - try { - return getEntityManager().createNamedQuery("XXTagAttributeDef.findByResourceId", tClass) - .setParameter("resourceId", resourceId).getResultList(); - } catch (NoResultException e) { - return new ArrayList(); - } - } + try { + return getEntityManager().createNamedQuery("XXTagAttributeDef.findByResourceId", tClass) + .setParameter("resourceId", resourceId).getResultList(); + } catch (NoResultException e) { + return new ArrayList<>(); + } + } } diff --git a/security-admin/src/main/java/org/apache/ranger/db/XXTagChangeLogDao.java b/security-admin/src/main/java/org/apache/ranger/db/XXTagChangeLogDao.java index 08b7f2f168..b3db540eb8 100644 --- a/security-admin/src/main/java/org/apache/ranger/db/XXTagChangeLogDao.java +++ b/security-admin/src/main/java/org/apache/ranger/db/XXTagChangeLogDao.java @@ -17,12 +17,6 @@ package org.apache.ranger.db; -import java.util.ArrayList; -import java.util.Date; -import java.util.Iterator; -import java.util.List; -import java.util.concurrent.TimeUnit; - import org.apache.commons.collections.CollectionUtils; import org.apache.ranger.common.db.BaseDao; import org.apache.ranger.entity.XXTagChangeLog; @@ -30,11 +24,17 @@ import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; +import java.util.ArrayList; +import java.util.Date; +import java.util.Iterator; +import java.util.List; +import java.util.concurrent.TimeUnit; + /** + * */ @Service public class XXTagChangeLogDao extends BaseDao { - private static final Logger LOG = LoggerFactory.getLogger(XXTagChangeLogDao.class); private static final int TAG_CHANGE_LOG_RECORD_ID_COLUMN_NUMBER = 0; @@ -52,20 +52,23 @@ public XXTagChangeLogDao(RangerDaoManagerBase daoManager) { public List findLaterThan(Long version, Long serviceId) { final List ret; + if (version != null) { List logs = getEntityManager() .createNamedQuery("XXTagChangeLog.findSinceVersion", Object[].class) .setParameter("version", version) .setParameter("serviceId", serviceId) .getResultList(); + // Ensure that first record has the same version as the base-version from where the records are fetched if (CollectionUtils.isNotEmpty(logs)) { - Iterator iter = logs.iterator(); - boolean foundAndRemoved = false; + Iterator iter = logs.iterator(); + boolean foundAndRemoved = false; while (iter.hasNext()) { - Object[] record = iter.next(); - Long recordVersion = (Long) record[TAG_CHANGE_LOG_RECORD_VERSION_ID_COLUMN_NUMBER]; + Object[] record = iter.next(); + Long recordVersion = (Long) record[TAG_CHANGE_LOG_RECORD_VERSION_ID_COLUMN_NUMBER]; + if (version.equals(recordVersion)) { iter.remove(); foundAndRemoved = true; @@ -73,6 +76,7 @@ public List findLaterThan(Long version, Long serviceId) { break; } } + if (foundAndRemoved) { ret = convert(logs); } else { @@ -89,31 +93,25 @@ public List findLaterThan(Long version, Long serviceId) { } public void deleteOlderThan(int olderThanInDays) { - Date since = new Date(System.currentTimeMillis() - TimeUnit.DAYS.toMillis(olderThanInDays)); - if (LOG.isDebugEnabled()) { - LOG.debug("Deleting records from x_tag_change_log that are older than " + olderThanInDays + " days, that is, older than " + since); - } + LOG.debug("Deleting records from x_tag_change_log that are older than {} days, that is, older than {}", olderThanInDays, since); getEntityManager().createNamedQuery("XXTagChangeLog.deleteOlderThan").setParameter("olderThan", since).executeUpdate(); } private List convert(List queryResult) { - final List ret; if (CollectionUtils.isNotEmpty(queryResult)) { - ret = new ArrayList<>(queryResult.size()); for (Object[] log : queryResult) { - - Long logRecordId = (Long) log[TAG_CHANGE_LOG_RECORD_ID_COLUMN_NUMBER]; - Integer tagChangeType = (Integer) log[TAG_CHANGE_LOG_RECORD_CHANGE_TYPE_COLUMN_NUMBER]; - Long serviceTagsVersion = (Long) log[TAG_CHANGE_LOG_RECORD_VERSION_ID_COLUMN_NUMBER]; - Long serviceResourceId = (Long) log[TAG_CHANGE_LOG_RECORD_SERVICE_RESOURCE_ID_COLUMN_NUMBER]; - Long tagId = (Long) log[TAG_CHANGE_LOG_RECORD_TAG_ID_COLUMN_NUMBER]; + Long logRecordId = (Long) log[TAG_CHANGE_LOG_RECORD_ID_COLUMN_NUMBER]; + Integer tagChangeType = (Integer) log[TAG_CHANGE_LOG_RECORD_CHANGE_TYPE_COLUMN_NUMBER]; + Long serviceTagsVersion = (Long) log[TAG_CHANGE_LOG_RECORD_VERSION_ID_COLUMN_NUMBER]; + Long serviceResourceId = (Long) log[TAG_CHANGE_LOG_RECORD_SERVICE_RESOURCE_ID_COLUMN_NUMBER]; + Long tagId = (Long) log[TAG_CHANGE_LOG_RECORD_TAG_ID_COLUMN_NUMBER]; ret.add(new XXTagChangeLog(logRecordId, tagChangeType, serviceTagsVersion, serviceResourceId, tagId)); } @@ -121,8 +119,5 @@ private List convert(List queryResult) { ret = null; } return ret; - } - } - diff --git a/security-admin/src/main/java/org/apache/ranger/db/XXTagDao.java b/security-admin/src/main/java/org/apache/ranger/db/XXTagDao.java index c3aed9d9c4..bf93380f9d 100644 --- a/security-admin/src/main/java/org/apache/ranger/db/XXTagDao.java +++ b/security-admin/src/main/java/org/apache/ranger/db/XXTagDao.java @@ -19,125 +19,126 @@ package org.apache.ranger.db; -import java.util.ArrayList; -import java.util.List; - -import javax.persistence.NoResultException; - import org.apache.commons.lang.StringUtils; import org.apache.ranger.authorization.utils.StringUtil; import org.apache.ranger.common.db.BaseDao; import org.apache.ranger.entity.XXTag; import org.springframework.stereotype.Service; +import javax.persistence.NoResultException; + +import java.util.ArrayList; +import java.util.List; + @Service public class XXTagDao extends BaseDao { - - public XXTagDao(RangerDaoManagerBase daoManager) { - super(daoManager); - } - - public List findByResourceId(Long resourceId) { - if (resourceId == null) { - return new ArrayList(); - } - try { - return getEntityManager().createNamedQuery("XXTag.findByResourceId", tClass) - .setParameter("resourceId", resourceId).getResultList(); - } catch (NoResultException e) { - return new ArrayList(); - } - } - - @SuppressWarnings("unchecked") - public List findTagTypesByServiceId(Long serviceId) { - if (serviceId == null) { - return new ArrayList(); - } - try { - return getEntityManager().createNamedQuery("XXTag.findTagTypesByServiceId") - .setParameter("serviceId", serviceId).getResultList(); - } catch (NoResultException e) { - return new ArrayList(); - } - } - - public XXTag findByGuid(String guid) { - if (StringUtil.isEmpty(guid)) { - return null; - } - try { - return getEntityManager().createNamedQuery("XXTag.findByGuid", tClass) - .setParameter("guid", guid).getSingleResult(); - } catch (NoResultException e) { - return null; - } - } - - public List findByName(String name) { - if (StringUtils.isEmpty(name)) { - return new ArrayList(); - } - - try { - return getEntityManager().createNamedQuery("XXTag.findByName", tClass) - .setParameter("name", name).getResultList(); - } catch (NoResultException e) { - return new ArrayList(); - } - } - - public List findForResourceId(Long resourceId) { - if (resourceId == null) { - return new ArrayList(); - } - - try { - return getEntityManager().createNamedQuery("XXTag.findByResourceId", tClass) - .setParameter("resourceId", resourceId).getResultList(); - } catch (NoResultException e) { - return new ArrayList(); - } - } - - public List findForResourceGuid(String resourceGuid) { - if (StringUtils.isEmpty(resourceGuid)) { - return new ArrayList(); - } - - try { - return getEntityManager().createNamedQuery("XXTag.findByResourceGuid", tClass) - .setParameter("resourceGuid", resourceGuid).getResultList(); - } catch (NoResultException e) { - return new ArrayList(); - } - } - - public List findByServiceId(Long serviceId) { - if (serviceId == null) { - return new ArrayList(); - } - - try { - return getEntityManager().createNamedQuery("XXTag.findByServiceId", tClass) - .setParameter("serviceId", serviceId).getResultList(); - } catch (NoResultException e) { - return new ArrayList(); - } - } - - public List findByServiceIdAndOwner(Long serviceId, Short owner) { - if (serviceId == null) { - return new ArrayList(); - } - - try { - return getEntityManager().createNamedQuery("XXTag.findByServiceIdAndOwner", tClass) - .setParameter("serviceId", serviceId) - .setParameter("owner", owner) - .getResultList(); - } catch (NoResultException e) { - return new ArrayList(); - } - } + public XXTagDao(RangerDaoManagerBase daoManager) { + super(daoManager); + } + + public List findByResourceId(Long resourceId) { + if (resourceId == null) { + return new ArrayList<>(); + } + + try { + return getEntityManager().createNamedQuery("XXTag.findByResourceId", tClass) + .setParameter("resourceId", resourceId).getResultList(); + } catch (NoResultException e) { + return new ArrayList<>(); + } + } + + public List findTagTypesByServiceId(Long serviceId) { + if (serviceId == null) { + return new ArrayList<>(); + } + + try { + return getEntityManager().createNamedQuery("XXTag.findTagTypesByServiceId", String.class) + .setParameter("serviceId", serviceId).getResultList(); + } catch (NoResultException e) { + return new ArrayList<>(); + } + } + + public XXTag findByGuid(String guid) { + if (StringUtil.isEmpty(guid)) { + return null; + } + + try { + return getEntityManager().createNamedQuery("XXTag.findByGuid", tClass) + .setParameter("guid", guid).getSingleResult(); + } catch (NoResultException e) { + return null; + } + } + + public List findByName(String name) { + if (StringUtils.isEmpty(name)) { + return new ArrayList<>(); + } + + try { + return getEntityManager().createNamedQuery("XXTag.findByName", tClass) + .setParameter("name", name).getResultList(); + } catch (NoResultException e) { + return new ArrayList<>(); + } + } + + public List findForResourceId(Long resourceId) { + if (resourceId == null) { + return new ArrayList<>(); + } + + try { + return getEntityManager().createNamedQuery("XXTag.findByResourceId", tClass) + .setParameter("resourceId", resourceId).getResultList(); + } catch (NoResultException e) { + return new ArrayList<>(); + } + } + + public List findForResourceGuid(String resourceGuid) { + if (StringUtils.isEmpty(resourceGuid)) { + return new ArrayList<>(); + } + + try { + return getEntityManager().createNamedQuery("XXTag.findByResourceGuid", tClass) + .setParameter("resourceGuid", resourceGuid).getResultList(); + } catch (NoResultException e) { + return new ArrayList<>(); + } + } + + public List findByServiceId(Long serviceId) { + if (serviceId == null) { + return new ArrayList<>(); + } + + try { + return getEntityManager().createNamedQuery("XXTag.findByServiceId", tClass) + .setParameter("serviceId", serviceId).getResultList(); + } catch (NoResultException e) { + return new ArrayList<>(); + } + } + + public List findByServiceIdAndOwner(Long serviceId, Short owner) { + if (serviceId == null) { + return new ArrayList<>(); + } + + try { + return getEntityManager().createNamedQuery("XXTag.findByServiceIdAndOwner", tClass) + .setParameter("serviceId", serviceId) + .setParameter("owner", owner) + .getResultList(); + } catch (NoResultException e) { + return new ArrayList<>(); + } + } } diff --git a/security-admin/src/main/java/org/apache/ranger/db/XXTagDefDao.java b/security-admin/src/main/java/org/apache/ranger/db/XXTagDefDao.java index f6c0bbf137..3fe13a02c9 100644 --- a/security-admin/src/main/java/org/apache/ranger/db/XXTagDefDao.java +++ b/security-admin/src/main/java/org/apache/ranger/db/XXTagDefDao.java @@ -19,63 +19,66 @@ package org.apache.ranger.db; -import java.util.ArrayList; -import java.util.List; - -import javax.persistence.NoResultException; - import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang.StringUtils; import org.apache.ranger.common.db.BaseDao; import org.apache.ranger.entity.XXTagDef; import org.springframework.stereotype.Service; +import javax.persistence.NoResultException; + +import java.util.ArrayList; +import java.util.List; + @Service public class XXTagDefDao extends BaseDao { + public XXTagDefDao(RangerDaoManagerBase daoManager) { + super(daoManager); + } + + public XXTagDef findByGuid(String guid) { + if (StringUtils.isEmpty(guid)) { + return null; + } + + try { + return getEntityManager().createNamedQuery("XXTagDef.findByGuid", tClass) + .setParameter("guid", guid).getSingleResult(); + } catch (NoResultException e) { + return null; + } + } - public XXTagDefDao(RangerDaoManagerBase daoManager) { - super(daoManager); - } - - public XXTagDef findByGuid(String guid) { - if (StringUtils.isEmpty(guid)) { - return null; - } - - try { - return getEntityManager().createNamedQuery("XXTagDef.findByGuid", tClass) - .setParameter("guid", guid).getSingleResult(); - } catch (NoResultException e) { - return null; - } - } - - public XXTagDef findByName(String name) { - if (StringUtils.isEmpty(name)) { - return null; - } - - try { - return getEntityManager().createNamedQuery("XXTagDef.findByName", tClass) - .setParameter("name", name).getSingleResult(); - } catch (NoResultException e) { - return null; - } - } + public XXTagDef findByName(String name) { + if (StringUtils.isEmpty(name)) { + return null; + } + + try { + return getEntityManager().createNamedQuery("XXTagDef.findByName", tClass) + .setParameter("name", name).getSingleResult(); + } catch (NoResultException e) { + return null; + } + } public List findByServiceId(Long serviceId) { List ret = new ArrayList<>(); + if (serviceId != null) { List rows = null; + try { rows = getEntityManager().createNamedQuery("XXTagDef.findByServiceId", Object[].class) .setParameter("serviceId", serviceId).getResultList(); } catch (NoResultException e) { // Nothing } + if (CollectionUtils.isNotEmpty(rows)) { for (Object[] row : rows) { XXTagDef xxTagDef = new XXTagDef(); + xxTagDef.setId((Long) row[0]); xxTagDef.setGuid((String) row[1]); xxTagDef.setVersion((Long) row[2]); @@ -88,27 +91,28 @@ public List findByServiceId(Long serviceId) { } } } + return ret; } - public List getAllNames() { - try { - return getEntityManager().createNamedQuery("XXTagDef.getAllNames", String.class).getResultList(); - } catch (NoResultException e) { - return new ArrayList(); - } - } - - public List findByResourceId(Long resourceId) { - if (resourceId == null) { - return new ArrayList(); - } - - try { - return getEntityManager().createNamedQuery("XXTagDef.findByResourceId", tClass) - .setParameter("resourceId", resourceId).getResultList(); - } catch (NoResultException e) { - return new ArrayList(); - } - } + public List getAllNames() { + try { + return getEntityManager().createNamedQuery("XXTagDef.getAllNames", String.class).getResultList(); + } catch (NoResultException e) { + return new ArrayList<>(); + } + } + + public List findByResourceId(Long resourceId) { + if (resourceId == null) { + return new ArrayList<>(); + } + + try { + return getEntityManager().createNamedQuery("XXTagDef.findByResourceId", tClass) + .setParameter("resourceId", resourceId).getResultList(); + } catch (NoResultException e) { + return new ArrayList<>(); + } + } } diff --git a/security-admin/src/main/java/org/apache/ranger/db/XXTagResourceMapDao.java b/security-admin/src/main/java/org/apache/ranger/db/XXTagResourceMapDao.java index 1b70d0a8b4..699fd42b9d 100644 --- a/security-admin/src/main/java/org/apache/ranger/db/XXTagResourceMapDao.java +++ b/security-admin/src/main/java/org/apache/ranger/db/XXTagResourceMapDao.java @@ -19,176 +19,179 @@ package org.apache.ranger.db; -import java.util.ArrayList; -import java.util.List; - -import javax.persistence.NoResultException; - import org.apache.commons.collections.CollectionUtils; import org.apache.ranger.authorization.utils.StringUtil; import org.apache.ranger.common.db.BaseDao; import org.apache.ranger.entity.XXTagResourceMap; import org.springframework.stereotype.Service; +import javax.persistence.NoResultException; + +import java.util.ArrayList; +import java.util.List; + @Service public class XXTagResourceMapDao extends BaseDao { - - public XXTagResourceMapDao(RangerDaoManagerBase daoManager) { - super(daoManager); - } - - public XXTagResourceMap findByGuid(String resourceGuid) { - if (StringUtil.isEmpty(resourceGuid)) { - return null; - } - try { - return getEntityManager().createNamedQuery("XXTagResourceMap.findByGuid", tClass) - .setParameter("guid", resourceGuid).getSingleResult(); - } catch (NoResultException e) { - return null; - } - } - - public List findByResourceId(Long resourceId) { - List ret = null; - - if (resourceId == null) { - ret = new ArrayList<>(); - } else { - try { - List rows = getEntityManager().createNamedQuery("XXTagResourceMap.findByResourceId", Object[].class) - .setParameter("resourceId", resourceId).getResultList(); - - ret = fromRows(rows); - } catch (NoResultException e) { - ret = new ArrayList<>(); - } - } - - return ret; - } - - public List findByResourceGuid(String resourceGuid) { - List ret = null; - - if (resourceGuid == null) { - ret = new ArrayList<>(); - } else { - try { - List rows = getEntityManager().createNamedQuery("XXTagResourceMap.findByResourceGuid", Object[].class) - .setParameter("resourceGuid", resourceGuid).getResultList(); - - ret = fromRows(rows); - } catch (NoResultException e) { - ret = new ArrayList<>(); - } - } - - return ret; - } - - public List findTagIdsForResourceId(Long resourceId) { - try { - return getEntityManager().createNamedQuery("XXTagResourceMap.getTagIdsForResourceId", Long.class) - .setParameter("resourceId", resourceId).getResultList(); - } catch (NoResultException e) { - return new ArrayList(); - } - } - - public List findByTagId(Long tagId) { - List ret = null; - - if (tagId == null) { - ret = new ArrayList<>(); - } else { - try { - List rows = getEntityManager().createNamedQuery("XXTagResourceMap.findByTagId", Object[].class) - .setParameter("tagId", tagId).getResultList(); - - ret = fromRows(rows); - } catch (NoResultException e) { - ret = new ArrayList<>(); - } - } - - return ret; - } - - public List findByTagGuid(String tagGuid) { - if (StringUtil.isEmpty(tagGuid)) { - return new ArrayList(); - } - try { - return getEntityManager().createNamedQuery("XXTagResourceMap.findByTagGuid", tClass) - .setParameter("tagGuid", tagGuid).getResultList(); - } catch (NoResultException e) { - return new ArrayList(); - } - } - - public XXTagResourceMap findByTagAndResourceId(Long tagId, Long resourceId) { - if (tagId == null || resourceId == null) { - return null; - } - try { - return getEntityManager().createNamedQuery("XXTagResourceMap.findByTagAndResourceId", tClass) - .setParameter("tagId", tagId) - .setParameter("resourceId", resourceId).getSingleResult(); - } catch (NoResultException e) { - return null; - } - } - - public XXTagResourceMap findByTagAndResourceGuid(String tagGuid, String resourceGuid) { - if (tagGuid == null || resourceGuid == null) { - return null; - } - try { - return getEntityManager().createNamedQuery("XXTagResourceMap.findByTagAndResourceGuid", tClass) - .setParameter("tagGuid", tagGuid) - .setParameter("resourceGuid", resourceGuid).getSingleResult(); - } catch (NoResultException e) { - return null; - } - } - - public List findByServiceId(Long serviceId) { - if (serviceId == null) { - return new ArrayList(); - } - try { - return getEntityManager().createNamedQuery("XXTagResourceMap.findByServiceId", tClass) - .setParameter("serviceId", serviceId).getResultList(); - } catch (NoResultException e) { - return new ArrayList(); - } - } - - private XXTagResourceMap fromRow(Object[] row) { - XXTagResourceMap ret = new XXTagResourceMap(); - - ret.setId((Long) row[0]); - ret.setGuid((String) row[1]); - ret.setTagId((Long) row[2]); - ret.setResourceId((Long) row[3]); - - return ret; - } - - private List fromRows(List rows) { - final List ret; - - if (CollectionUtils.isNotEmpty(rows)) { - ret = new ArrayList<>(rows.size()); - - for (Object[] row : rows) { - ret.add(fromRow(row)); - } - } else { - ret = new ArrayList<>(); - } - - return ret; - } + public XXTagResourceMapDao(RangerDaoManagerBase daoManager) { + super(daoManager); + } + + public XXTagResourceMap findByGuid(String resourceGuid) { + if (StringUtil.isEmpty(resourceGuid)) { + return null; + } + + try { + return getEntityManager().createNamedQuery("XXTagResourceMap.findByGuid", tClass) + .setParameter("guid", resourceGuid).getSingleResult(); + } catch (NoResultException e) { + return null; + } + } + + public List findByResourceId(Long resourceId) { + List ret; + + if (resourceId == null) { + ret = new ArrayList<>(); + } else { + try { + List rows = getEntityManager().createNamedQuery("XXTagResourceMap.findByResourceId", Object[].class) + .setParameter("resourceId", resourceId).getResultList(); + + ret = fromRows(rows); + } catch (NoResultException e) { + ret = new ArrayList<>(); + } + } + + return ret; + } + + public List findByResourceGuid(String resourceGuid) { + List ret; + + if (resourceGuid == null) { + ret = new ArrayList<>(); + } else { + try { + List rows = getEntityManager().createNamedQuery("XXTagResourceMap.findByResourceGuid", Object[].class) + .setParameter("resourceGuid", resourceGuid).getResultList(); + + ret = fromRows(rows); + } catch (NoResultException e) { + ret = new ArrayList<>(); + } + } + + return ret; + } + + public List findTagIdsForResourceId(Long resourceId) { + try { + return getEntityManager().createNamedQuery("XXTagResourceMap.getTagIdsForResourceId", Long.class) + .setParameter("resourceId", resourceId).getResultList(); + } catch (NoResultException e) { + return new ArrayList<>(); + } + } + + public List findByTagId(Long tagId) { + List ret; + + if (tagId == null) { + ret = new ArrayList<>(); + } else { + try { + List rows = getEntityManager().createNamedQuery("XXTagResourceMap.findByTagId", Object[].class) + .setParameter("tagId", tagId).getResultList(); + + ret = fromRows(rows); + } catch (NoResultException e) { + ret = new ArrayList<>(); + } + } + + return ret; + } + + public List findByTagGuid(String tagGuid) { + if (StringUtil.isEmpty(tagGuid)) { + return new ArrayList<>(); + } + try { + return getEntityManager().createNamedQuery("XXTagResourceMap.findByTagGuid", tClass) + .setParameter("tagGuid", tagGuid).getResultList(); + } catch (NoResultException e) { + return new ArrayList<>(); + } + } + + public XXTagResourceMap findByTagAndResourceId(Long tagId, Long resourceId) { + if (tagId == null || resourceId == null) { + return null; + } + + try { + return getEntityManager().createNamedQuery("XXTagResourceMap.findByTagAndResourceId", tClass) + .setParameter("tagId", tagId) + .setParameter("resourceId", resourceId).getSingleResult(); + } catch (NoResultException e) { + return null; + } + } + + public XXTagResourceMap findByTagAndResourceGuid(String tagGuid, String resourceGuid) { + if (tagGuid == null || resourceGuid == null) { + return null; + } + + try { + return getEntityManager().createNamedQuery("XXTagResourceMap.findByTagAndResourceGuid", tClass) + .setParameter("tagGuid", tagGuid) + .setParameter("resourceGuid", resourceGuid).getSingleResult(); + } catch (NoResultException e) { + return null; + } + } + + public List findByServiceId(Long serviceId) { + if (serviceId == null) { + return new ArrayList<>(); + } + + try { + return getEntityManager().createNamedQuery("XXTagResourceMap.findByServiceId", tClass) + .setParameter("serviceId", serviceId).getResultList(); + } catch (NoResultException e) { + return new ArrayList<>(); + } + } + + private XXTagResourceMap fromRow(Object[] row) { + XXTagResourceMap ret = new XXTagResourceMap(); + + ret.setId((Long) row[0]); + ret.setGuid((String) row[1]); + ret.setTagId((Long) row[2]); + ret.setResourceId((Long) row[3]); + + return ret; + } + + private List fromRows(List rows) { + final List ret; + + if (CollectionUtils.isNotEmpty(rows)) { + ret = new ArrayList<>(rows.size()); + + for (Object[] row : rows) { + ret.add(fromRow(row)); + } + } else { + ret = new ArrayList<>(); + } + + return ret; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/db/XXTrxLogV2Dao.java b/security-admin/src/main/java/org/apache/ranger/db/XXTrxLogV2Dao.java index 429f871dfa..a4818d7cb2 100644 --- a/security-admin/src/main/java/org/apache/ranger/db/XXTrxLogV2Dao.java +++ b/security-admin/src/main/java/org/apache/ranger/db/XXTrxLogV2Dao.java @@ -17,7 +17,7 @@ * under the License. */ - package org.apache.ranger.db; +package org.apache.ranger.db; import org.apache.ranger.common.db.BaseDao; import org.apache.ranger.entity.XXTrxLogV2; @@ -26,6 +26,7 @@ import org.springframework.stereotype.Service; import javax.persistence.NoResultException; + import java.util.Date; import java.util.List; import java.util.concurrent.TimeUnit; @@ -34,11 +35,11 @@ public class XXTrxLogV2Dao extends BaseDao { private static final Logger logger = LoggerFactory.getLogger(XXTrxLogV2Dao.class); - public XXTrxLogV2Dao(RangerDaoManagerBase daoManager ) { + public XXTrxLogV2Dao(RangerDaoManagerBase daoManager) { super(daoManager); } - public List findByTransactionId(String transactionId){ + public List findByTransactionId(String transactionId) { List ret = null; if (transactionId != null) { @@ -55,11 +56,11 @@ public List findByTransactionId(String transactionId){ public long deleteOlderThan(int olderThanInDays) { Date since = new Date(System.currentTimeMillis() - TimeUnit.DAYS.toMillis(olderThanInDays)); - logger.info("Deleting x_trx_log_v2 records that are older than " + olderThanInDays + " days, that is, older than " + since); + logger.info("Deleting x_trx_log_v2 records that are older than {} days, that is, older than {}", olderThanInDays, since); long ret = getEntityManager().createNamedQuery("XXTrxLogV2.deleteOlderThan").setParameter("olderThan", since).executeUpdate(); - logger.info("Deleted " + ret + " x_trx_log_v2 records"); + logger.info("Deleted {} x_trx_log_v2 records", ret); return ret; } diff --git a/security-admin/src/main/java/org/apache/ranger/db/XXUgsyncAuditInfoDao.java b/security-admin/src/main/java/org/apache/ranger/db/XXUgsyncAuditInfoDao.java index 8d02b7cf02..175fc7aac4 100644 --- a/security-admin/src/main/java/org/apache/ranger/db/XXUgsyncAuditInfoDao.java +++ b/security-admin/src/main/java/org/apache/ranger/db/XXUgsyncAuditInfoDao.java @@ -25,51 +25,48 @@ import org.springframework.stereotype.Service; import javax.persistence.NoResultException; -import java.util.List; -/** - */ +import java.util.List; @Service public class XXUgsyncAuditInfoDao extends BaseDao { - protected static final Logger logger = LoggerFactory - .getLogger(XXUgsyncAuditInfoDao.class); - /** - * Default Constructor - */ - public XXUgsyncAuditInfoDao(RangerDaoManagerBase daoManager) { - super(daoManager); - } + protected static final Logger logger = LoggerFactory.getLogger(XXUgsyncAuditInfoDao.class); + + /** + * Default Constructor + */ + public XXUgsyncAuditInfoDao(RangerDaoManagerBase daoManager) { + super(daoManager); + } + + @Override + public XXUgsyncAuditInfo create(XXUgsyncAuditInfo obj) { + obj.setEventTime(DateUtil.getUTCDate()); + + return super.create(obj); + } + + public XXUgsyncAuditInfo findBySessionId(String sessionId) { + if (sessionId == null) { + return null; + } + + try { + return getEntityManager().createNamedQuery("XXUgsyncAuditInfo.findBySessionId", tClass).setParameter("sessionId", sessionId).getSingleResult(); + } catch (NoResultException e) { + return null; + } + } - @Override - public XXUgsyncAuditInfo create(XXUgsyncAuditInfo obj) { - obj.setEventTime(DateUtil.getUTCDate()); - return super.create(obj); - } + public List findBySyncSource(String syncSource) { + if (syncSource == null) { + return null; + } - public XXUgsyncAuditInfo findBySessionId(String sessionId) { - if (sessionId == null) { - return null; - } - try { - return getEntityManager() - .createNamedQuery("XXUgsyncAuditInfo.findBySessionId", tClass) - .setParameter("sessionId", sessionId) - .getSingleResult(); - } catch (NoResultException e) { - return null; - } - } - public List findBySyncSource(String syncSource) { - if (syncSource == null) { - return null; - } - try { - return getEntityManager() - .createNamedQuery("XXUgsyncAuditInfo.findBySyncSource", tClass) - .setParameter("syncSource", syncSource).getResultList(); - } catch (NoResultException e) { - return null; - } - } + try { + return getEntityManager().createNamedQuery("XXUgsyncAuditInfo.findBySyncSource", tClass).setParameter("syncSource", syncSource).getResultList(); + } catch (NoResultException e) { + return null; + } + } } 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 index 05c65322a6..520241268f 100755 --- a/security-admin/src/main/java/org/apache/ranger/db/XXUserDao.java +++ b/security-admin/src/main/java/org/apache/ranger/db/XXUserDao.java @@ -19,9 +19,6 @@ package org.apache.ranger.db; -import javax.persistence.NoResultException; - -import org.apache.commons.collections.ListUtils; import org.apache.commons.lang3.StringUtils; import org.apache.ranger.authorization.utils.JsonUtils; import org.apache.ranger.common.RangerCommonEnums; @@ -33,187 +30,189 @@ import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; -import java.util.List; -import java.util.Set; -import java.util.HashSet; -import java.util.Map; +import javax.persistence.NoResultException; + import java.util.ArrayList; +import java.util.Collections; import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; -import static org.apache.ranger.plugin.util.RangerCommonConstants.*; - +import static org.apache.ranger.plugin.util.RangerCommonConstants.SCRIPT_FIELD__EMAIL_ADDRESS; +import static org.apache.ranger.plugin.util.RangerCommonConstants.SCRIPT_FIELD__IS_INTERNAL; +import static org.apache.ranger.plugin.util.RangerCommonConstants.SCRIPT_FIELD__SYNC_SOURCE; @Service public class XXUserDao extends BaseDao { - private static final Logger logger = LoggerFactory.getLogger(XXUserDao.class); - - public XXUserDao(RangerDaoManagerBase 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; - } - - public XXUser findByPortalUserId(Long portalUserId) { - if (portalUserId == null) { - return null; - } - try { - return getEntityManager().createNamedQuery("XXUser.findByPortalUserId", tClass) - .setParameter("portalUserId", portalUserId).getSingleResult(); - } catch (NoResultException e) { - return null; - } - } - - public Map> findGroupsByUserIds() { - Map> userGroups = new HashMap<>(); - - try { - List rows = (List) getEntityManager() - .createNamedQuery("XXUser.findGroupsByUserIds") - .getResultList(); - if (rows != null) { - for (Object[] row : rows) { - if (userGroups.containsKey((String)row[0])) { - userGroups.get((String)row[0]).add((String)row[1]); - } else { - Set groups = new HashSet<>(); - groups.add((String)row[1]); - userGroups.put((String)row[0], groups); - } - } - } - } catch (NoResultException e) { - //Ignore - } - return userGroups; - } - - public Map getAllUserIds() { - Map users = new HashMap<>(); - try { - List rows = (List) getEntityManager().createNamedQuery("XXUser.getAllUserIds").getResultList(); - if (rows != null) { - for (Object[] row : rows) { - users.put((String)row[0], (Long)row[1]); - } - } - } catch (NoResultException e) { - if (logger.isDebugEnabled()) { - logger.debug(e.getMessage()); - } - } - return users; - } - - public List getAllUserIdNames() { - List users = new ArrayList(); - try { - users = (List) getEntityManager().createNamedQuery("XXUser.getAllUserIdNames").getResultList(); - } catch (NoResultException e) { - if (logger.isDebugEnabled()) { - logger.debug(e.getMessage()); - } - } - return users; - } - - public List lookupPrincipalByName(String principalName, int startIndex, int pageSize) { - List ret = new ArrayList<>(); - - try { - List results = getEntityManager().createNamedQuery("VXXPrincipal.lookupByName", Object[].class) - .setParameter("principalName", principalName + "%") - .setFirstResult(startIndex) - .setMaxResults(pageSize).getResultList(); - - if (results != null) { - for (Object[] result : results) { - String name = (String) result[0]; - Number type = (Number) result[1]; - - switch (type.intValue()) { - case 0: - ret.add(new RangerPrincipal(RangerPrincipal.PrincipalType.USER, name)); - break; - case 1: - ret.add(new RangerPrincipal(RangerPrincipal.PrincipalType.GROUP, name)); - break; - case 2: - ret.add(new RangerPrincipal(RangerPrincipal.PrincipalType.ROLE, name)); - break; - } - } - } - } catch (NoResultException e) { - ret = ListUtils.EMPTY_LIST; - } - return ret; - } - - public List getAllUsersInfo() { - List ret = new ArrayList<>(); - - try { - List rows = getEntityManager().createNamedQuery("XXUser.getAllUsersInfo", Object[].class).getResultList(); - - if (rows != null) { - for (Object[] row : rows) { - - ret.add(toUserInfo(row)); - } - } - } catch (NoResultException excp) { - if (logger.isDebugEnabled()) { - logger.debug(excp.getMessage()); - } - } - - return ret; - } - - private UserInfo toUserInfo(Object[] row) { - String name = (String) row[0]; - String description = (String) row[1]; - String attributes = (String) row[2]; - String syncSource = (String) row[3]; - Number userSource = (Number) row[4]; - String emailAddress = (String) row[5]; - Boolean isInternal = userSource != null && userSource.equals(RangerCommonEnums.USER_APP); - Map attrMap = null; - - if (StringUtils.isNotBlank(attributes)) { - attrMap = JsonUtils.jsonToMapStringString(attributes); - } - - if (attrMap == null) { - attrMap = new HashMap<>(); - } - - if (StringUtils.isNotBlank(syncSource)) { - attrMap.put(SCRIPT_FIELD__SYNC_SOURCE, syncSource); - } - - if (StringUtils.isNotBlank(emailAddress)) { - attrMap.put(SCRIPT_FIELD__EMAIL_ADDRESS, emailAddress); - } - - attrMap.put(SCRIPT_FIELD__IS_INTERNAL, isInternal.toString()); - - return new UserInfo(name, description, attrMap); - } + private static final Logger logger = LoggerFactory.getLogger(XXUserDao.class); + + public XXUserDao(RangerDaoManagerBase 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; + } + + public XXUser findByPortalUserId(Long portalUserId) { + if (portalUserId == null) { + return null; + } + + try { + return getEntityManager().createNamedQuery("XXUser.findByPortalUserId", tClass).setParameter("portalUserId", portalUserId).getSingleResult(); + } catch (NoResultException e) { + return null; + } + } + + public Map> findGroupsByUserIds() { + Map> userGroups = new HashMap<>(); + + try { + List rows = getEntityManager().createNamedQuery("XXUser.findGroupsByUserIds", Object[].class).getResultList(); + + if (rows != null) { + for (Object[] row : rows) { + if (userGroups.containsKey((String) row[0])) { + userGroups.get((String) row[0]).add((String) row[1]); + } else { + Set groups = new HashSet<>(); + + groups.add((String) row[1]); + userGroups.put((String) row[0], groups); + } + } + } + } catch (NoResultException e) { + //Ignore + } + + return userGroups; + } + + public Map getAllUserIds() { + Map users = new HashMap<>(); + + try { + List rows = getEntityManager().createNamedQuery("XXUser.getAllUserIds", Object[].class).getResultList(); + + if (rows != null) { + for (Object[] row : rows) { + users.put((String) row[0], (Long) row[1]); + } + } + } catch (NoResultException e) { + logger.debug(e.getMessage()); + } + return users; + } + + public List getAllUserIdNames() { + List users; + + try { + users = getEntityManager().createNamedQuery("XXUser.getAllUserIdNames", Object[].class).getResultList(); + } catch (NoResultException e) { + logger.debug(e.getMessage()); + + users = new ArrayList<>(); + } + + return users; + } + + public List lookupPrincipalByName(String principalName, int startIndex, int pageSize) { + List ret = new ArrayList<>(); + + try { + List results = getEntityManager().createNamedQuery("VXXPrincipal.lookupByName", Object[].class).setParameter("principalName", principalName + "%").setFirstResult(startIndex).setMaxResults(pageSize).getResultList(); + + if (results != null) { + for (Object[] result : results) { + String name = (String) result[0]; + Number type = (Number) result[1]; + + switch (type.intValue()) { + case 0: + ret.add(new RangerPrincipal(RangerPrincipal.PrincipalType.USER, name)); + break; + case 1: + ret.add(new RangerPrincipal(RangerPrincipal.PrincipalType.GROUP, name)); + break; + case 2: + ret.add(new RangerPrincipal(RangerPrincipal.PrincipalType.ROLE, name)); + break; + } + } + } + } catch (NoResultException e) { + ret = Collections.emptyList(); + } + + return ret; + } + + public List getAllUsersInfo() { + List ret = new ArrayList<>(); + + try { + List rows = getEntityManager().createNamedQuery("XXUser.getAllUsersInfo", Object[].class).getResultList(); + + if (rows != null) { + for (Object[] row : rows) { + ret.add(toUserInfo(row)); + } + } + } catch (NoResultException excp) { + logger.debug(excp.getMessage()); + } + + return ret; + } + + private UserInfo toUserInfo(Object[] row) { + String name = (String) row[0]; + String description = (String) row[1]; + String attributes = (String) row[2]; + String syncSource = (String) row[3]; + Number userSource = (Number) row[4]; + String emailAddress = (String) row[5]; + boolean isInternal = userSource != null && userSource.equals(RangerCommonEnums.USER_APP); + Map attrMap = null; + + if (StringUtils.isNotBlank(attributes)) { + attrMap = JsonUtils.jsonToMapStringString(attributes); + } + + if (attrMap == null) { + attrMap = new HashMap<>(); + } + + if (StringUtils.isNotBlank(syncSource)) { + attrMap.put(SCRIPT_FIELD__SYNC_SOURCE, syncSource); + } + + if (StringUtils.isNotBlank(emailAddress)) { + attrMap.put(SCRIPT_FIELD__EMAIL_ADDRESS, emailAddress); + } + + attrMap.put(SCRIPT_FIELD__IS_INTERNAL, Boolean.toString(isInternal)); + + return new UserInfo(name, description, attrMap); + } } diff --git a/security-admin/src/main/java/org/apache/ranger/db/XXUserPermissionDao.java b/security-admin/src/main/java/org/apache/ranger/db/XXUserPermissionDao.java index bf42e28ba4..4d7b5281f3 100644 --- a/security-admin/src/main/java/org/apache/ranger/db/XXUserPermissionDao.java +++ b/security-admin/src/main/java/org/apache/ranger/db/XXUserPermissionDao.java @@ -17,11 +17,6 @@ package org.apache.ranger.db; -import java.util.ArrayList; -import java.util.List; - -import javax.persistence.NoResultException; - import org.apache.ranger.common.RangerCommonEnums; import org.apache.ranger.common.db.BaseDao; import org.apache.ranger.entity.XXUserPermission; @@ -29,124 +24,132 @@ import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; +import javax.persistence.NoResultException; + +import java.util.ArrayList; +import java.util.List; + @Service -public class XXUserPermissionDao extends BaseDao{ - - private static final Logger logger = LoggerFactory.getLogger(XXUserPermissionDao.class); - - public XXUserPermissionDao(RangerDaoManagerBase daoManager) { - super(daoManager); - } - - public List findByModuleId(Long moduleId,boolean isUpdate) { - if (moduleId != null) { - try { - - if(isUpdate) - { - return getEntityManager() - .createNamedQuery("XXUserPermissionUpdates.findByModuleId", XXUserPermission.class) - .setParameter("moduleId", moduleId) - .getResultList(); - } - return getEntityManager() - .createNamedQuery("XXUserPermission.findByModuleId", XXUserPermission.class) - .setParameter("moduleId", moduleId) - .setParameter("isAllowed",RangerCommonEnums.IS_ALLOWED) - .getResultList(); - } catch (NoResultException e) { - logger.debug(e.getMessage()); - } - } else { - logger.debug("ResourceUserId not provided."); - return new ArrayList(); - } - return null; - } - - @SuppressWarnings("unchecked") - public List findByUserPermissionIdAndIsAllowed(Long userId) { - if (userId != null) { - try { - return getEntityManager() - .createNamedQuery("XXUserPermission.findByUserPermissionIdAndIsAllowed") - .setParameter("userId", userId) - .setParameter("isAllowed",RangerCommonEnums.IS_ALLOWED) - .getResultList(); - } catch (NoResultException e) { - logger.debug(e.getMessage()); - } - } else { - logger.debug("ResourceUserId not provided."); - return new ArrayList(); - } - return null; - } - - - public List findByUserPermissionId(Long userId) { - if (userId != null) { - try { - return getEntityManager() - .createNamedQuery("XXUserPermission.findByUserPermissionId", XXUserPermission.class) - .setParameter("userId", userId) - .getResultList(); - } catch (NoResultException e) { - logger.debug(e.getMessage()); - } - } else { - logger.debug("ResourceUserId not provided."); - return new ArrayList(); - } - return null; - } - - public XXUserPermission findByModuleIdAndPortalUserId(Long userId, Long moduleId) { - if (userId != null) { - try { - return getEntityManager().createNamedQuery("XXUserPermission.findByModuleIdAndPortalUserId", XXUserPermission.class) - .setParameter("userId", userId) - .setParameter("moduleId", moduleId) - .getSingleResult(); - } catch (NoResultException e) { - logger.debug(e.getMessage()); - } - } else { - logger.debug("ResourceUserId not provided."); - return null; - } - return null; - } - - public void deleteByModuleId(Long moduleId) { - if (moduleId != null) { - try { - getEntityManager() - .createNamedQuery("XXUserPermission.deleteByModuleId", XXUserPermission.class) - .setParameter("moduleId", moduleId) - .executeUpdate(); - } catch (Exception e) { - logger.debug(e.getMessage()); - } - } else { - logger.debug("ModuleId not provided."); - } - } - - @SuppressWarnings("unchecked") - public List findModuleUsersByModuleId(Long moduleId) { - if (moduleId != null) { - try { - return getEntityManager().createNamedQuery("XXUserPermission.findModuleUsersByModuleId", String.class) - .setParameter("moduleId", moduleId) - .setParameter("isAllowed",RangerCommonEnums.IS_ALLOWED) - .getResultList(); - } catch (Exception e) { - logger.debug(e.getMessage()); - } - } else { - logger.debug("ModuleId not provided."); - } - return null; - } +public class XXUserPermissionDao extends BaseDao { + private static final Logger logger = LoggerFactory.getLogger(XXUserPermissionDao.class); + + public XXUserPermissionDao(RangerDaoManagerBase daoManager) { + super(daoManager); + } + + public List findByModuleId(Long moduleId, boolean isUpdate) { + if (moduleId != null) { + try { + if (isUpdate) { + return getEntityManager() + .createNamedQuery("XXUserPermissionUpdates.findByModuleId", XXUserPermission.class) + .setParameter("moduleId", moduleId) + .getResultList(); + } + return getEntityManager() + .createNamedQuery("XXUserPermission.findByModuleId", XXUserPermission.class) + .setParameter("moduleId", moduleId) + .setParameter("isAllowed", RangerCommonEnums.IS_ALLOWED) + .getResultList(); + } catch (NoResultException e) { + logger.debug(e.getMessage()); + } + } else { + logger.debug("ResourceUserId not provided."); + + return new ArrayList<>(); + } + + return null; + } + + public List findByUserPermissionIdAndIsAllowed(Long userId) { + if (userId != null) { + try { + return getEntityManager() + .createNamedQuery("XXUserPermission.findByUserPermissionIdAndIsAllowed", tClass) + .setParameter("userId", userId) + .setParameter("isAllowed", RangerCommonEnums.IS_ALLOWED) + .getResultList(); + } catch (NoResultException e) { + logger.debug(e.getMessage()); + } + } else { + logger.debug("ResourceUserId not provided."); + + return new ArrayList<>(); + } + + return null; + } + + public List findByUserPermissionId(Long userId) { + if (userId != null) { + try { + return getEntityManager() + .createNamedQuery("XXUserPermission.findByUserPermissionId", XXUserPermission.class) + .setParameter("userId", userId) + .getResultList(); + } catch (NoResultException e) { + logger.debug(e.getMessage()); + } + } else { + logger.debug("ResourceUserId not provided."); + + return new ArrayList<>(); + } + + return null; + } + + public XXUserPermission findByModuleIdAndPortalUserId(Long userId, Long moduleId) { + if (userId != null) { + try { + return getEntityManager().createNamedQuery("XXUserPermission.findByModuleIdAndPortalUserId", XXUserPermission.class) + .setParameter("userId", userId) + .setParameter("moduleId", moduleId) + .getSingleResult(); + } catch (NoResultException e) { + logger.debug(e.getMessage()); + } + } else { + logger.debug("ResourceUserId not provided."); + + return null; + } + + return null; + } + + public void deleteByModuleId(Long moduleId) { + if (moduleId != null) { + try { + getEntityManager() + .createNamedQuery("XXUserPermission.deleteByModuleId", XXUserPermission.class) + .setParameter("moduleId", moduleId) + .executeUpdate(); + } catch (Exception e) { + logger.debug(e.getMessage()); + } + } else { + logger.debug("ModuleId not provided."); + } + } + + public List findModuleUsersByModuleId(Long moduleId) { + if (moduleId != null) { + try { + return getEntityManager().createNamedQuery("XXUserPermission.findModuleUsersByModuleId", String.class) + .setParameter("moduleId", moduleId) + .setParameter("isAllowed", RangerCommonEnums.IS_ALLOWED) + .getResultList(); + } catch (Exception e) { + logger.debug(e.getMessage()); + } + } else { + logger.debug("ModuleId not provided."); + } + + return null; + } } From 19cf1ac044d0b4b2154d19bbf68d4b27ab37adde Mon Sep 17 00:00:00 2001 From: Ramesh Date: Sun, 5 Jan 2025 20:38:11 -0800 Subject: [PATCH 08/15] RANGER-5061: checkstyle compliance updates - security-admin module - org.apache.ranger.util (#498) --- .../java/org/apache/ranger/util/CLIUtil.java | 82 +- .../util/Pbkdf2PasswordEncoderCust.java | 38 +- .../apache/ranger/util/RangerAdminCache.java | 28 +- .../apache/ranger/util/RangerEnumUtil.java | 3973 ++++++++--------- .../apache/ranger/util/RangerMetricsUtil.java | 59 +- .../apache/ranger/util/RangerRestUtil.java | 66 +- .../ranger/util/RangerServerHealthUtil.java | 15 +- .../java/org/apache/ranger/util/RestUtil.java | 112 +- 8 files changed, 2159 insertions(+), 2214 deletions(-) diff --git a/security-admin/src/main/java/org/apache/ranger/util/CLIUtil.java b/security-admin/src/main/java/org/apache/ranger/util/CLIUtil.java index 556d750dec..0fd584761b 100644 --- a/security-admin/src/main/java/org/apache/ranger/util/CLIUtil.java +++ b/security-admin/src/main/java/org/apache/ranger/util/CLIUtil.java @@ -17,16 +17,8 @@ * under the License. */ - /** - * - */ package org.apache.ranger.util; -import java.util.Locale; - -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; - import org.apache.commons.lang.StringUtils; import org.apache.ranger.common.PropertiesUtil; import org.apache.ranger.common.UserSessionBase; @@ -41,13 +33,15 @@ import org.springframework.stereotype.Component; import org.springframework.web.context.support.WebApplicationContextUtils; -/** - * - * - */ +import javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; + +import java.util.Locale; + @Component public class CLIUtil { private static final Logger logger = LoggerFactory.getLogger(CLIUtil.class); + private static final String JAVA_PATCHES_CLASS_NAME_PREFIX = "Patch"; @Autowired @@ -57,10 +51,7 @@ public class CLIUtil { public static void init() { if (context == null) { - context = new ClassPathXmlApplicationContext( - "applicationContext.xml", - "security-applicationContext.xml", - "asynctask-applicationContext.xml"); + context = new ClassPathXmlApplicationContext("applicationContext.xml", "security-applicationContext.xml", "asynctask-applicationContext.xml"); } } @@ -70,35 +61,42 @@ public static Object getBean(Class beanClass) { return context.getBean(beanClass); } - private static void checkIfJavaPatchesExecuting(Class beanClass) { - if (beanClass != null) { - final String className = beanClass.getSimpleName(); - if (StringUtils.isNotEmpty(className)) { - if (className.startsWith(JAVA_PATCHES_CLASS_NAME_PREFIX)) { - UserSessionBase userSessBase = new UserSessionBase(); - userSessBase.setUserAdmin(true); - userSessBase.setAuditUserAdmin(true); - userSessBase.setKeyAdmin(true); - userSessBase.setAuditKeyAdmin(true); - RangerSecurityContext rangerSecCtx = new RangerSecurityContext(); - rangerSecCtx.setUserSession(userSessBase); - RangerContextHolder.setSecurityContext(rangerSecCtx); - } - } - } - } - public void authenticate() throws Exception { String user = PropertiesUtil.getProperty("xa.cli.user"); - String pwd = PropertiesUtil.getProperty("xa.cli.password"); - logger.info("Authenticating user:" + user); + String pwd = PropertiesUtil.getProperty("xa.cli.password"); + + logger.info("Authenticating user: {}", user); + securityHandler.login(user, pwd, context); } - public static String getMessage(String messagekey,HttpServletRequest request){ - ServletContext servletContext = request.getSession().getServletContext(); - ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(servletContext); - Object[] args = new Object[] {}; - String messageValue=ctx.getMessage(messagekey, args, Locale.getDefault()); - return messageValue; + + public static String getMessage(String messagekey, HttpServletRequest request) { + ServletContext servletContext = request.getSession().getServletContext(); + ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(servletContext); + Object[] args = new Object[] {}; + + return ctx.getMessage(messagekey, args, Locale.getDefault()); + } + + private static void checkIfJavaPatchesExecuting(Class beanClass) { + if (beanClass != null) { + final String className = beanClass.getSimpleName(); + + if (StringUtils.isNotEmpty(className)) { + if (className.startsWith(JAVA_PATCHES_CLASS_NAME_PREFIX)) { + UserSessionBase userSessBase = new UserSessionBase(); + + userSessBase.setUserAdmin(true); + userSessBase.setAuditUserAdmin(true); + userSessBase.setKeyAdmin(true); + userSessBase.setAuditKeyAdmin(true); + + RangerSecurityContext rangerSecCtx = new RangerSecurityContext(); + + rangerSecCtx.setUserSession(userSessBase); + RangerContextHolder.setSecurityContext(rangerSecCtx); + } + } + } } } diff --git a/security-admin/src/main/java/org/apache/ranger/util/Pbkdf2PasswordEncoderCust.java b/security-admin/src/main/java/org/apache/ranger/util/Pbkdf2PasswordEncoderCust.java index 3a85cf047a..813ae87179 100644 --- a/security-admin/src/main/java/org/apache/ranger/util/Pbkdf2PasswordEncoderCust.java +++ b/security-admin/src/main/java/org/apache/ranger/util/Pbkdf2PasswordEncoderCust.java @@ -30,6 +30,7 @@ import javax.crypto.SecretKeyFactory; import javax.crypto.spec.PBEKeySpec; + import java.security.GeneralSecurityException; import java.security.NoSuchAlgorithmException; import java.util.Arrays; @@ -37,12 +38,13 @@ public class Pbkdf2PasswordEncoderCust implements PasswordEncoder { private static final int DEFAULT_HASH_WIDTH = 256; private static final int DEFAULT_ITERATIONS = 185000; + private final BytesKeyGenerator saltGenerator; - private final byte[] secret; - private final int hashWidth; - private final int iterations; - private String algorithm; - private boolean encodeHashAsBase64; + private String algorithm; + private final byte[] secret; + private final int hashWidth; + private final int iterations; + private boolean encodeHashAsBase64; public Pbkdf2PasswordEncoderCust(CharSequence secret) { this(secret, DEFAULT_ITERATIONS, DEFAULT_HASH_WIDTH); @@ -50,10 +52,10 @@ public Pbkdf2PasswordEncoderCust(CharSequence secret) { public Pbkdf2PasswordEncoderCust(CharSequence secret, int iterations, int hashWidth) { this.saltGenerator = KeyGenerators.secureRandom(16); - this.algorithm = Pbkdf2PasswordEncoder.SecretKeyFactoryAlgorithm.PBKDF2WithHmacSHA512.name(); - this.secret = Utf8.encode(secret); - this.iterations = iterations; - this.hashWidth = hashWidth; + this.algorithm = Pbkdf2PasswordEncoder.SecretKeyFactoryAlgorithm.PBKDF2WithHmacSHA512.name(); + this.secret = Utf8.encode(secret); + this.iterations = iterations; + this.hashWidth = hashWidth; } public void setAlgorithm(Pbkdf2PasswordEncoder.SecretKeyFactoryAlgorithm secretKeyFactoryAlgorithm) { @@ -74,8 +76,9 @@ public void setAlgorithm(Pbkdf2PasswordEncoder.SecretKeyFactoryAlgorithm secretK @Override public String encode(CharSequence rawPassword) { - byte[] salt = this.saltGenerator.generateKey(); + byte[] salt = this.saltGenerator.generateKey(); byte[] encoded = this.encode(rawPassword, salt); + return this.encode(encoded); } @@ -90,24 +93,25 @@ private String encode(byte[] bytes) { @Override public boolean matches(CharSequence rawPassword, String encodedPassword) { byte[] digested = this.decode(encodedPassword); - byte[] salt = EncodingUtils.subArray(digested, 0, this.saltGenerator.getKeyLength()); + byte[] salt = EncodingUtils.subArray(digested, 0, this.saltGenerator.getKeyLength()); + return matches(digested, this.encode(rawPassword, salt)); } - + private static boolean matches(byte[] expected, byte[] actual) { - return Arrays.equals(expected, actual); + return Arrays.equals(expected, actual); } - private byte[] decode(String encodedBytes) { return this.encodeHashAsBase64 ? Base64.decode(Utf8.encode(encodedBytes)) : Hex.decode(encodedBytes); } private byte[] encode(CharSequence rawPassword, byte[] salt) { try { - PBEKeySpec spec = new PBEKeySpec(rawPassword.toString().toCharArray(), EncodingUtils.concatenate(new byte[][]{salt, this.secret}), this.iterations, this.hashWidth); - SecretKeyFactory skf = SecretKeyFactory.getInstance(this.algorithm); - return EncodingUtils.concatenate(new byte[][]{salt, skf.generateSecret(spec).getEncoded()}); + PBEKeySpec spec = new PBEKeySpec(rawPassword.toString().toCharArray(), EncodingUtils.concatenate(new byte[][] {salt, this.secret}), this.iterations, this.hashWidth); + SecretKeyFactory skf = SecretKeyFactory.getInstance(this.algorithm); + + return EncodingUtils.concatenate(new byte[][] {salt, skf.generateSecret(spec).getEncoded()}); } catch (GeneralSecurityException var5) { throw new IllegalStateException("Could not create hash", var5); } diff --git a/security-admin/src/main/java/org/apache/ranger/util/RangerAdminCache.java b/security-admin/src/main/java/org/apache/ranger/util/RangerAdminCache.java index 2d5da7d303..ea98957796 100644 --- a/security-admin/src/main/java/org/apache/ranger/util/RangerAdminCache.java +++ b/security-admin/src/main/java/org/apache/ranger/util/RangerAdminCache.java @@ -51,22 +51,10 @@ protected RangerAdminCache(String name, RangerDBValueLoader loader, int lo } @Override - public V get(K key) { + public V get(K key) { return super.get(key, RangerContextHolder.getSecurityContext()); } - private static int getLoaderThreadPoolSize(String cacheName) { - return RangerAdminConfig.getInstance().getInt(PROP_PREFIX + cacheName + PROP_LOADER_THREAD_POOL_SIZE, DEFAULT_ADMIN_CACHE_LOADER_THREADS_COUNT); - } - - private static long getValueInitLoadTimeout(String cacheName) { - return RangerAdminConfig.getInstance().getLong(PROP_PREFIX + cacheName + PROP_VALUE_INIT_TIMEOUT_MS, DEFAULT_ADMIN_CACHE_VALUE_INIT_TIMEOUT_MS); - } - - private static long getValueRefreshLoadTimeout(String cacheName) { - return RangerAdminConfig.getInstance().getLong(PROP_PREFIX + cacheName + PROP_VALUE_REFRESH_TIMEOUT_MS, DEFAULT_ADMIN_CACHE_VALUE_REFRESH_TIMEOUT_MS); - } - public abstract static class RangerDBValueLoader extends ValueLoader { private final TransactionTemplate txTemplate; @@ -77,7 +65,7 @@ public RangerDBValueLoader(PlatformTransactionManager txManager) { } @Override - final public RefreshableValue load(K key, RefreshableValue currentValue, Object context) throws Exception { + public final RefreshableValue load(K key, RefreshableValue currentValue, Object context) throws Exception { Exception[] ex = new Exception[1]; RefreshableValue ret = txTemplate.execute(status -> { @@ -113,4 +101,16 @@ final public RefreshableValue load(K key, RefreshableValue currentValue, O protected abstract RefreshableValue dbLoad(K key, RefreshableValue currentValue) throws Exception; } + + private static int getLoaderThreadPoolSize(String cacheName) { + return RangerAdminConfig.getInstance().getInt(PROP_PREFIX + cacheName + PROP_LOADER_THREAD_POOL_SIZE, DEFAULT_ADMIN_CACHE_LOADER_THREADS_COUNT); + } + + private static long getValueInitLoadTimeout(String cacheName) { + return RangerAdminConfig.getInstance().getLong(PROP_PREFIX + cacheName + PROP_VALUE_INIT_TIMEOUT_MS, DEFAULT_ADMIN_CACHE_VALUE_INIT_TIMEOUT_MS); + } + + private static long getValueRefreshLoadTimeout(String cacheName) { + return RangerAdminConfig.getInstance().getLong(PROP_PREFIX + cacheName + PROP_VALUE_REFRESH_TIMEOUT_MS, DEFAULT_ADMIN_CACHE_VALUE_REFRESH_TIMEOUT_MS); + } } diff --git a/security-admin/src/main/java/org/apache/ranger/util/RangerEnumUtil.java b/security-admin/src/main/java/org/apache/ranger/util/RangerEnumUtil.java index be09165a33..0ca1f769b7 100644 --- a/security-admin/src/main/java/org/apache/ranger/util/RangerEnumUtil.java +++ b/security-admin/src/main/java/org/apache/ranger/util/RangerEnumUtil.java @@ -17,16 +17,7 @@ * under the License. */ - package org.apache.ranger.util; - -/** - * - */ - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Map; -import java.util.List; +package org.apache.ranger.util; import org.apache.ranger.common.view.VEnum; import org.apache.ranger.common.view.VEnumElement; @@ -34,76 +25,80 @@ import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + @Component public class RangerEnumUtil { - private static final Logger logger = LoggerFactory.getLogger(RangerEnumUtil.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_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 Map enumMap = new HashMap(); - protected List enumList = new ArrayList(); + 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 Map enumMap = new HashMap(); + protected List enumList = new ArrayList(); public List getEnums() { - if (enumList.isEmpty()) { - init(); - } - return enumList; + if (enumList.isEmpty()) { + init(); + } + return enumList; } public VEnum getEnum(String enumName) { - if (enumList.isEmpty()) { - init(); - } - return enumMap.get(enumName); + if (enumList.isEmpty()) { + 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 ""; + VEnum vEnum = getEnum(enumName); + if (vEnum == null) { + logger.error("Enum not found. enum={}", enumName, new Throwable()); + return ""; + } + for (VEnumElement vEnumElement : vEnum.getElementList()) { + if (vEnumElement.getElementValue() == enumValue) { + return vEnumElement.getElementLabel(); + } + } + logger.error("Enum value not found. enum={}, value={}", enumName, 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()); + logger.error("Enum not found. enum={}", enumName, new Throwable()); return -1; } for (VEnumElement vEnumElement : vEnum.getElementList()) { @@ -111,1950 +106,1920 @@ public int getValue(String enumName, String elementName) { return vEnumElement.getElementValue(); } } - logger.error("Enum value not found. enum=" + enumName - + ", elementName=" + elementName, new Throwable()); + logger.error("Enum value not found. enum={}, elementName={}", enumName, 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()); - 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()); - 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()); - 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()); - 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()); - 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()); - 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()); - 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()); - 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()); - 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()); - 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()); - 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()); - 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()); - 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()); - 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()); - 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()); - 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()); - 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()); - 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()); - 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()); - 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()); - 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); - - vElement = new VEnumElement(); - vElement.setElementName("RESOURCE_GLOBAL"); - vElement.setElementValue(11); - vElement.setElementLabel("Global"); - vElement.setRbKey("xa.enum.ResourceType.RESOURCE_GLOBAL"); - vElement.setEnumName(vEnum.getEnumName()); - - vEnum.getElementList().add(vElement); - /////////////////////////////////// - // CommonEnums::XAGroupType - /////////////////////////////////// - vEnum = new VEnum(); - vEnum.setEnumName(ENUM_CommonEnums_XAGroupType); - vEnum.setElementList(new ArrayList()); - 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()); - 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()); - 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()); - 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()); - 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()); - 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); - - vElement = new VEnumElement(); - vElement.setElementName("AUTH_TYPE_KERBEROS"); - vElement.setElementValue(2); - vElement.setElementLabel("Kerberos"); - vElement.setRbKey("xa.enum.AuthType.AUTH_TYPE_KERBEROS"); - vElement.setEnumName(vEnum.getEnumName()); - - vEnum.getElementList().add(vElement); - - vElement = new VEnumElement(); - vElement.setElementName("AUTH_TYPE_SSO"); - vElement.setElementValue(3); - vElement.setElementLabel("SingleSignOn"); - vElement.setRbKey("xa.enum.AuthType.AUTH_TYPE_SSO"); - vElement.setEnumName(vEnum.getEnumName()); - - vEnum.getElementList().add(vElement); - - vElement = new VEnumElement(); - vElement.setElementName("AUTH_TYPE_TRUSTED_PROXY"); - vElement.setElementValue(4); - vElement.setElementLabel("Trusted Proxy"); - vElement.setRbKey("xa.enum.AuthType.AUTH_TYPE_TRUSTED_PROXY"); - vElement.setEnumName(vEnum.getEnumName()); - - vEnum.getElementList().add(vElement); - - /////////////////////////////////// - // XResponse::ResponseStatus - /////////////////////////////////// - vEnum = new VEnum(); - vEnum.setEnumName(ENUM_XResponse_ResponseStatus); - vEnum.setElementList(new ArrayList()); - 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); - - + VEnum vEnum; + VEnumElement vElement; + + /////////////////////////////////// + // CommonEnums::ActiveStatus + /////////////////////////////////// + vEnum = new VEnum(); + vEnum.setEnumName(ENUM_CommonEnums_ActiveStatus); + vEnum.setElementList(new ArrayList()); + 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()); + 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()); + 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()); + 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()); + 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()); + 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()); + 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()); + 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()); + 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()); + 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()); + 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()); + 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()); + 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()); + 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()); + 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()); + 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()); + 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()); + 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()); + 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()); + 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()); + 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); + + vElement = new VEnumElement(); + vElement.setElementName("RESOURCE_GLOBAL"); + vElement.setElementValue(11); + vElement.setElementLabel("Global"); + vElement.setRbKey("xa.enum.ResourceType.RESOURCE_GLOBAL"); + vElement.setEnumName(vEnum.getEnumName()); + + vEnum.getElementList().add(vElement); + + /////////////////////////////////// + // CommonEnums::XAGroupType + /////////////////////////////////// + vEnum = new VEnum(); + vEnum.setEnumName(ENUM_CommonEnums_XAGroupType); + vEnum.setElementList(new ArrayList()); + 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()); + 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()); + 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()); + 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()); + 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()); + 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); + + vElement = new VEnumElement(); + vElement.setElementName("AUTH_TYPE_KERBEROS"); + vElement.setElementValue(2); + vElement.setElementLabel("Kerberos"); + vElement.setRbKey("xa.enum.AuthType.AUTH_TYPE_KERBEROS"); + vElement.setEnumName(vEnum.getEnumName()); + + vEnum.getElementList().add(vElement); + + vElement = new VEnumElement(); + vElement.setElementName("AUTH_TYPE_SSO"); + vElement.setElementValue(3); + vElement.setElementLabel("SingleSignOn"); + vElement.setRbKey("xa.enum.AuthType.AUTH_TYPE_SSO"); + vElement.setEnumName(vEnum.getEnumName()); + + vEnum.getElementList().add(vElement); + + vElement = new VEnumElement(); + vElement.setElementName("AUTH_TYPE_TRUSTED_PROXY"); + vElement.setElementValue(4); + vElement.setElementLabel("Trusted Proxy"); + vElement.setRbKey("xa.enum.AuthType.AUTH_TYPE_TRUSTED_PROXY"); + vElement.setEnumName(vEnum.getEnumName()); + + vEnum.getElementList().add(vElement); + + /////////////////////////////////// + // XResponse::ResponseStatus + /////////////////////////////////// + vEnum = new VEnum(); + vEnum.setEnumName(ENUM_XResponse_ResponseStatus); + vEnum.setElementList(new ArrayList()); + 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); } - } - diff --git a/security-admin/src/main/java/org/apache/ranger/util/RangerMetricsUtil.java b/security-admin/src/main/java/org/apache/ranger/util/RangerMetricsUtil.java index b50a1a8387..56cb35c247 100644 --- a/security-admin/src/main/java/org/apache/ranger/util/RangerMetricsUtil.java +++ b/security-admin/src/main/java/org/apache/ranger/util/RangerMetricsUtil.java @@ -20,49 +20,45 @@ package org.apache.ranger.util; import org.apache.commons.lang.StringUtils; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import java.lang.management.ManagementFactory; import java.lang.management.MemoryMXBean; +import java.lang.management.MemoryPoolMXBean; +import java.lang.management.MemoryType; +import java.lang.management.MemoryUsage; import java.lang.management.OperatingSystemMXBean; import java.util.Arrays; import java.util.LinkedHashMap; import java.util.Map; -import java.lang.management.MemoryPoolMXBean; -import java.lang.management.MemoryType; -import java.lang.management.MemoryUsage; /** * Connect Worker system and runtime information. */ @Component public class RangerMetricsUtil { - private static final Logger LOG = LoggerFactory.getLogger(RangerMetricsUtil.class); + private static final OperatingSystemMXBean OS; - private static final MemoryMXBean MEM_BEAN; + private static final MemoryMXBean MEM_BEAN; static { - OS = ManagementFactory.getOperatingSystemMXBean(); + OS = ManagementFactory.getOperatingSystemMXBean(); MEM_BEAN = ManagementFactory.getMemoryMXBean(); } public Map getValues() { - if (LOG.isDebugEnabled()) { - LOG.debug("==> RangerMetricsUtil.getValues()"); - } - + LOG.debug("==> RangerMetricsUtil.getValues()"); + Map values = new LinkedHashMap<>(); + values.put("os.spec", StringUtils.join(Arrays.asList(addSystemInfo()), ", ")); values.put("os.vcpus", String.valueOf(OS.getAvailableProcessors())); values.put("memory", addMemoryDetails()); - if (LOG.isDebugEnabled()) { - LOG.debug("<== RangerMetricsUtil.getValues()" + values); - } + LOG.debug("<== RangerMetricsUtil.getValues() {}", values); return values; } @@ -71,20 +67,17 @@ public Map getValues() { * collect the pool division of java */ protected Map getPoolDivision() { - if (LOG.isDebugEnabled()) { - LOG.debug("==> RangerMetricsUtil.getPoolDivision()"); - } + LOG.debug("==> RangerMetricsUtil.getPoolDivision()"); Map poolDivisionValues = new LinkedHashMap<>(); + for (MemoryPoolMXBean mpBean : ManagementFactory.getMemoryPoolMXBeans()) { if (mpBean.getType() == MemoryType.HEAP) { poolDivisionValues.put(mpBean.getName(), mpBean.getUsage()); } } - if (LOG.isDebugEnabled()) { - LOG.debug("<== RangerMetricsUtil.getPoolDivision()" + poolDivisionValues); - } + LOG.debug("<== RangerMetricsUtil.getPoolDivision() {}", poolDivisionValues); return poolDivisionValues; } @@ -93,13 +86,12 @@ protected Map getPoolDivision() { * Add memory details */ protected Map addMemoryDetails() { - if (LOG.isDebugEnabled()) { - LOG.debug("==> RangerMetricsUtil.addMemoryDetails()"); - } + LOG.debug("==> RangerMetricsUtil.addMemoryDetails()"); + + Map memory = new LinkedHashMap<>(); + MemoryUsage memHeapUsage = MEM_BEAN.getHeapMemoryUsage(); + MemoryUsage nonHeapUsage = MEM_BEAN.getNonHeapMemoryUsage(); - Map memory = new LinkedHashMap<>(); - MemoryUsage memHeapUsage = MEM_BEAN.getHeapMemoryUsage(); - MemoryUsage nonHeapUsage = MEM_BEAN.getNonHeapMemoryUsage(); memory.put("heapInit", String.valueOf(memHeapUsage.getInit())); memory.put("heapMax", String.valueOf(memHeapUsage.getMax())); memory.put("heapCommitted", String.valueOf(memHeapUsage.getCommitted())); @@ -110,9 +102,7 @@ protected Map addMemoryDetails() { memory.put("nonHeapUsed", String.valueOf(nonHeapUsage.getUsed())); memory.put("memory_pool_usages", getPoolDivision()); - if (LOG.isDebugEnabled()) { - LOG.debug("<== RangerMetricsUtil.addMemoryDetails()" + memory); - } + LOG.debug("<== RangerMetricsUtil.addMemoryDetails() {}", memory); return memory; } @@ -121,14 +111,11 @@ protected Map addMemoryDetails() { * Collect system information. */ protected String[] addSystemInfo() { - if (LOG.isDebugEnabled()) { - LOG.debug("==> RangerMetricsUtil.addSystemInfo()"); - } + LOG.debug("==> RangerMetricsUtil.addSystemInfo()"); - String[] osInfo = { OS.getName(), OS.getArch(), OS.getVersion() }; - if (LOG.isDebugEnabled()) { - LOG.debug("<== RangerMetricsUtil.addSystemInfo()" + osInfo); - } + String[] osInfo = {OS.getName(), OS.getArch(), OS.getVersion()}; + + LOG.debug("<== RangerMetricsUtil.addSystemInfo() {}", osInfo); return osInfo; } diff --git a/security-admin/src/main/java/org/apache/ranger/util/RangerRestUtil.java b/security-admin/src/main/java/org/apache/ranger/util/RangerRestUtil.java index 31da69265a..7316f2177b 100644 --- a/security-admin/src/main/java/org/apache/ranger/util/RangerRestUtil.java +++ b/security-admin/src/main/java/org/apache/ranger/util/RangerRestUtil.java @@ -17,12 +17,7 @@ * under the License. */ - package org.apache.ranger.util; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.List; +package org.apache.ranger.util; import org.apache.ranger.common.MessageEnums; import org.apache.ranger.common.RESTErrorUtil; @@ -37,6 +32,11 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.List; + @Component public class RangerRestUtil { private static final Logger logger = LoggerFactory.getLogger(RangerRestUtil.class); @@ -54,7 +54,7 @@ void splitUserRoleList(Collection collection) { Collection newCollection = new ArrayList(); for (String role : collection) { String[] roles = role.split(","); - newCollection.addAll(Arrays.asList(roles)); + newCollection.addAll(Arrays.asList(roles)); } collection.clear(); collection.addAll(newCollection); @@ -66,11 +66,8 @@ void splitUserRoleList(Collection collection) { * @param userProfile * @return */ - public void validateVUserProfileForUpdate(XXPortalUser gjUser, - VXPortalUser userProfile) { - + public void validateVUserProfileForUpdate(XXPortalUser gjUser, VXPortalUser userProfile) { List messageList = new ArrayList(); - // Email Update is allowed. // if (userProfile.getEmailAddress() != null // && !userProfile.getEmailAddress().equalsIgnoreCase( @@ -82,64 +79,41 @@ public void validateVUserProfileForUpdate(XXPortalUser gjUser, // } // 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()); + 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.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")); - // firstName if (!stringUtil.isValidName(userProfile.getFirstName())) { - logger.info("Invalid first name." + userProfile); - messageList.add(MessageEnums.INVALID_INPUT_DATA.getMessage(null, - "firstName")); + logger.info("Invalid first name. {}", userProfile); + messageList.add(MessageEnums.INVALID_INPUT_DATA.getMessage(null, "firstName")); } - // create the public screen name - userProfile.setPublicScreenName(userProfile.getFirstName() + " " - + userProfile.getLastName()); + 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")); + 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"); + restErrorUtil.validateStringList(userRole, configUtil.getRoles(), "Invalid role", null, "userRoleList"); } - } + if (!messageList.isEmpty()) { 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); + logger.info("Validation Error in updateUser() userProfile={}, error={}", userProfile, gjResponse); throw restErrorUtil.createRESTException(gjResponse); } - } - } diff --git a/security-admin/src/main/java/org/apache/ranger/util/RangerServerHealthUtil.java b/security-admin/src/main/java/org/apache/ranger/util/RangerServerHealthUtil.java index 4605745837..ba2a23fc7c 100644 --- a/security-admin/src/main/java/org/apache/ranger/util/RangerServerHealthUtil.java +++ b/security-admin/src/main/java/org/apache/ranger/util/RangerServerHealthUtil.java @@ -19,21 +19,20 @@ package org.apache.ranger.util; -import static org.apache.ranger.plugin.model.RangerServerHealth.RangerServerStatus.*; - -import java.util.HashMap; import org.apache.commons.lang.StringUtils; - import org.apache.ranger.biz.RangerBizUtil; import org.apache.ranger.common.AppConstants; import org.apache.ranger.plugin.model.RangerServerHealth; - import org.springframework.stereotype.Component; +import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; import java.util.Objects; +import static org.apache.ranger.plugin.model.RangerServerHealth.RangerServerStatus.DOWN; +import static org.apache.ranger.plugin.model.RangerServerHealth.RangerServerStatus.UP; + @Component public class RangerServerHealthUtil { private static final String COMPONENTS = "components"; @@ -71,7 +70,7 @@ public RangerServerHealth getRangerServerHealth(String dbVersion) { final RangerServerHealth ret; - if (Objects.equals(dbStatus.get(STATUS), UP) ){ + if (Objects.equals(dbStatus.get(STATUS), UP)) { ret = RangerServerHealth.up().withDetail(COMPONENTS, components).build(); } else { ret = RangerServerHealth.down().withDetail(COMPONENTS, components).build(); @@ -82,8 +81,8 @@ public RangerServerHealth getRangerServerHealth(String dbVersion) { private Map getDbStatus(String dbVersion) { Map ret = new LinkedHashMap<>(); - int dbFlavor = RangerBizUtil.getDBFlavor(); Map details = new LinkedHashMap<>(); + int dbFlavor = RangerBizUtil.getDBFlavor(); details.put(DB_FLAVOR, RangerBizUtil.getDBFlavorType(dbFlavor)); details.put(DB_VERSION, dbVersion); @@ -91,7 +90,7 @@ private Map getDbStatus(String dbVersion) { ret.put(DETAILS, details); - if (dbFlavor == AppConstants.DB_FLAVOR_UNKNOWN || StringUtils.contains(dbVersion, NOT_AVAILABLE) ){ + if (dbFlavor == AppConstants.DB_FLAVOR_UNKNOWN || StringUtils.contains(dbVersion, NOT_AVAILABLE)) { ret.put(STATUS, DOWN); } else { ret.put(STATUS, UP); diff --git a/security-admin/src/main/java/org/apache/ranger/util/RestUtil.java b/security-admin/src/main/java/org/apache/ranger/util/RestUtil.java index f012704b3f..cf91a09784 100644 --- a/security-admin/src/main/java/org/apache/ranger/util/RestUtil.java +++ b/security-admin/src/main/java/org/apache/ranger/util/RestUtil.java @@ -19,15 +19,15 @@ package org.apache.ranger.util; -import javax.servlet.http.Cookie; -import javax.servlet.http.HttpServletRequest; - import org.apache.commons.lang.StringUtils; import org.apache.ranger.security.context.RangerContextHolder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; +import javax.servlet.http.Cookie; +import javax.servlet.http.HttpServletRequest; + import java.time.Instant; import java.time.ZoneId; import java.time.ZonedDateTime; @@ -37,25 +37,28 @@ @Component public class RestUtil { - private static final Logger LOG = LoggerFactory.getLogger(RestUtil.class); - public static final String timeOffsetCookieName = "clientTimeOffset"; - public static final String TIMEOUT_ACTION = "timeout"; + private static final String PROXY_RANGER_URL_PATH = "/ranger"; - public static final String LOCAL_LOGIN_URL = "locallogin"; + + public static final String timeOffsetCookieName = "clientTimeOffset"; + public static final String TIMEOUT_ACTION = "timeout"; + public static final String LOCAL_LOGIN_URL = "locallogin"; public static final String ZONED_EVENT_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss z"; public static Integer getTimeOffset(HttpServletRequest request) { Integer cookieVal = 0; - try{ - Cookie[] cookies = request.getCookies(); - String timeOffset = null; + + try { + Cookie[] cookies = request.getCookies(); + String timeOffset = null; if (cookies != null) { for (Cookie cookie : cookies) { try { if (timeOffsetCookieName.equals(cookie.getName())) { timeOffset = cookie.getValue(); + if (timeOffset != null) { cookieVal = Integer.parseInt(timeOffset); } @@ -66,43 +69,50 @@ public static Integer getTimeOffset(HttpServletRequest request) { } } } - }catch(Exception ex){ - + } catch (Exception ex) { + // ignored } + return cookieVal; } - public static int getClientTimeOffset(){ + public static int getClientTimeOffset() { int clientTimeOffsetInMinute = 0; - try{ - clientTimeOffsetInMinute= RangerContextHolder.getSecurityContext().getRequestContext().getClientTimeOffsetInMinute(); - }catch(Exception ex){ - + + try { + clientTimeOffsetInMinute = RangerContextHolder.getSecurityContext().getRequestContext().getClientTimeOffsetInMinute(); + } catch (Exception ex) { + // ignored } - if(clientTimeOffsetInMinute==0){ - try{ - clientTimeOffsetInMinute= RangerContextHolder.getSecurityContext().getUserSession().getClientTimeOffsetInMinute(); - }catch(Exception ex){ - + + if (clientTimeOffsetInMinute == 0) { + try { + clientTimeOffsetInMinute = RangerContextHolder.getSecurityContext().getUserSession().getClientTimeOffsetInMinute(); + } catch (Exception ex) { + // ignored } } + return clientTimeOffsetInMinute; } public static String constructForwardableURL(HttpServletRequest httpRequest) { - String xForwardedProto = ""; - String xForwardedHost = ""; - String xForwardedContext = ""; - Enumeration names = httpRequest.getHeaderNames(); + String xForwardedProto = ""; + String xForwardedHost = ""; + String xForwardedContext = ""; + Enumeration names = httpRequest.getHeaderNames(); + while (names.hasMoreElements()) { - String name = (String) names.nextElement(); + String name = (String) names.nextElement(); Enumeration values = httpRequest.getHeaders(name); - String value = ""; + String value = ""; + if (values != null) { while (values.hasMoreElements()) { value = (String) values.nextElement(); } } + if (StringUtils.trimToNull(name) != null && StringUtils.trimToNull(value) != null) { if (name.equalsIgnoreCase("x-forwarded-proto")) { xForwardedProto = value; @@ -113,13 +123,15 @@ public static String constructForwardableURL(HttpServletRequest httpRequest) { } } } + if (xForwardedHost.contains(",")) { - if (LOG.isDebugEnabled()) { - LOG.debug("xForwardedHost value is " + xForwardedHost + " it contains multiple hosts, selecting the first host."); - } + LOG.debug("xForwardedHost value is {}, it contains multiple hosts, selecting the first host.", xForwardedHost); + xForwardedHost = xForwardedHost.split(",")[0].trim(); } + String xForwardedURL = ""; + if (StringUtils.trimToNull(xForwardedProto) != null) { //if header contains x-forwarded-host and x-forwarded-context if (StringUtils.trimToNull(xForwardedHost) != null && StringUtils.trimToNull(xForwardedContext) != null) { @@ -131,47 +143,41 @@ public static String constructForwardableURL(HttpServletRequest httpRequest) { //if header does not contains x-forwarded-host and x-forwarded-context //preserve the x-forwarded-proto value coming from the request. String requestURL = httpRequest.getRequestURL().toString(); + if (StringUtils.trimToNull(requestURL) != null && requestURL.startsWith("http:")) { requestURL = requestURL.replaceFirst("http", xForwardedProto); } + xForwardedURL = requestURL; } } + return xForwardedURL; } public static String constructRedirectURL(HttpServletRequest request, String redirectUrl, String xForwardedURL, String originalUrlQueryParam) { String delimiter = "?"; + if (redirectUrl.contains("?")) { delimiter = "&"; } + String loginURL = redirectUrl + delimiter + originalUrlQueryParam + "="; + if (StringUtils.trimToNull(xForwardedURL) != null) { loginURL += xForwardedURL + getOriginalQueryString(request); } else { loginURL += request.getRequestURL().append(getOriginalQueryString(request)); } - return loginURL; - } - private static String getOriginalQueryString(HttpServletRequest request) { - String originalQueryString = request.getQueryString(); - if (LOG.isDebugEnabled()) { - LOG.debug("originalQueryString = " + originalQueryString); - } - if (originalQueryString == null || originalQueryString.contains("action")) { - return ""; - } else { - return "?" + originalQueryString; - } + return loginURL; } public static String convertToTimeZone(Date date, String timeZone) { try { - Instant utcInstant = date.toInstant(); - + Instant utcInstant = date.toInstant(); // Get the ZoneId from the request parameter - ZoneId zoneId = ZoneId.of(timeZone); + ZoneId zoneId = ZoneId.of(timeZone); // Convert the UTC date to the specified timezone ZonedDateTime zonedDateTime = utcInstant.atZone(zoneId); @@ -181,4 +187,16 @@ public static String convertToTimeZone(Date date, String timeZone) { return null; } } -} \ No newline at end of file + + private static String getOriginalQueryString(HttpServletRequest request) { + String originalQueryString = request.getQueryString(); + + LOG.debug("originalQueryString = {} ", originalQueryString); + + if (originalQueryString == null || originalQueryString.contains("action")) { + return ""; + } else { + return "?" + originalQueryString; + } + } +} From 7fb9a397c1801e2a52acdb0bd067a600afd8c75a Mon Sep 17 00:00:00 2001 From: Vyom Mani Tiwari Date: Tue, 7 Jan 2025 00:37:54 +0530 Subject: [PATCH 09/15] RANGER-5061: checkstyle compliance updates - security-admin org.apache.ranger.common (#487) --- dev-support/checkstyle-suppressions.xml | 9 + .../apache/ranger/common/AppConstants.java | 2549 +++++++------ .../org/apache/ranger/common/ContextUtil.java | 145 +- .../org/apache/ranger/common/DateUtil.java | 200 +- .../ranger/common/ErrorMessageUtil.java | 41 +- .../org/apache/ranger/common/GUIDUtil.java | 21 +- .../org/apache/ranger/common/HTTPUtil.java | 51 +- .../org/apache/ranger/common/JSONUtil.java | 146 +- .../org/apache/ranger/common/MapUtil.java | 50 +- .../apache/ranger/common/MessageEnums.java | 44 +- .../org/apache/ranger/common/MyCallBack.java | 3 +- .../apache/ranger/common/PropertiesUtil.java | 854 +++-- .../apache/ranger/common/RESTErrorUtil.java | 843 +++-- .../ranger/common/RangerAdminTagEnricher.java | 93 +- .../common/RangerAdminUserStoreEnricher.java | 28 +- .../ranger/common/RangerCommonEnums.java | 2864 ++++++++------- .../ranger/common/RangerConfigUtil.java | 87 +- .../apache/ranger/common/RangerConstants.java | 310 +- .../apache/ranger/common/RangerFactory.java | 6 +- .../common/RangerJAXBContextResolver.java | 65 +- .../RangerJsonMappingExceptionMapper.java | 16 +- .../RangerJsonParserExceptionMapper.java | 21 +- .../ranger/common/RangerJsonProvider.java | 7 +- .../ranger/common/RangerProperties.java | 40 +- .../apache/ranger/common/RangerRoleCache.java | 226 +- .../ranger/common/RangerSearchUtil.java | 1366 +++---- .../common/RangerServicePoliciesCache.java | 932 +++-- .../ranger/common/RangerServiceTagsCache.java | 686 ++-- .../ranger/common/RangerUserStoreCache.java | 194 +- .../ranger/common/RangerValidatorFactory.java | 30 +- .../apache/ranger/common/RequestContext.java | 267 +- .../apache/ranger/common/SearchCriteria.java | 339 +- .../org/apache/ranger/common/SearchField.java | 363 +- .../org/apache/ranger/common/SearchGroup.java | 234 +- .../org/apache/ranger/common/SearchUtil.java | 1418 ++++---- .../org/apache/ranger/common/SearchValue.java | 44 +- .../ranger/common/ServiceGdsInfoCache.java | 11 +- .../org/apache/ranger/common/ServiceUtil.java | 3145 +++++++++-------- .../org/apache/ranger/common/SortField.java | 52 +- .../org/apache/ranger/common/StringUtil.java | 452 +-- .../apache/ranger/common/TimedEventUtil.java | 83 +- .../apache/ranger/common/TimedExecutor.java | 276 +- .../common/TimedExecutorConfigurator.java | 131 +- .../apache/ranger/common/UserSessionBase.java | 291 +- .../ranger/common/XMLPropertiesUtil.java | 20 +- .../annotation/RangerAnnotationClassName.java | 5 +- .../annotation/RangerAnnotationJSMgrName.java | 5 +- .../annotation/RangerAnnotationRestAPI.java | 11 +- .../org/apache/ranger/common/db/BaseDao.java | 711 ++-- .../ranger/common/db/JPABeanCallbacks.java | 156 +- ...ngerTransactionSynchronizationAdapter.java | 134 +- .../org/apache/ranger/common/view/VEnum.java | 139 +- .../ranger/common/view/VEnumElement.java | 279 +- .../org/apache/ranger/common/view/VList.java | 127 +- .../ranger/common/view/VTrxLogAttr.java | 318 +- .../ranger/common/view/ViewBaseBean.java | 15 +- 56 files changed, 10367 insertions(+), 10586 deletions(-) diff --git a/dev-support/checkstyle-suppressions.xml b/dev-support/checkstyle-suppressions.xml index b13973cf82..b68cfc108a 100644 --- a/dev-support/checkstyle-suppressions.xml +++ b/dev-support/checkstyle-suppressions.xml @@ -25,6 +25,15 @@ + + + + + + + + + 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 index 7886a7a278..077b33e41c 100644 --- a/security-admin/src/main/java/org/apache/ranger/common/AppConstants.java +++ b/security-admin/src/main/java/org/apache/ranger/common/AppConstants.java @@ -17,1328 +17,1317 @@ * under the License. */ - package org.apache.ranger.common; - +package org.apache.ranger.common; public class AppConstants extends RangerCommonEnums { + /*************************************************************** + * 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 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 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 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; + /*************************************************************** + * 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 ResourceType_MAX - */ - public static final int ResourceType_MAX = 10; + /*************************************************************** + * 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 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; + /*************************************************************** + * 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 XAGroupType_MAX - */ - public static final int XAGroupType_MAX = 3; + /** + * 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; - /*************************************************************** - * 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 XAGroupType_MAX + */ + public static final int XAGroupType_MAX = 3; - /** - * Max value for enum XAPermForType_MAX - */ - public static final int XAPermForType_MAX = 2; + /*************************************************************** + * 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; - /** - * XA_PERM_TYPE_REPLADMIN is an element of enum XAPermType. Its value is "XA_PERM_TYPE_REPLADMIN". - */ - public static final int XA_PERM_TYPE_REPLADMIN = 32; - /** - * XA_PERM_TYPE_SERVICEADMIN is an element of enum XAPermType. Its value is "XA_PERM_TYPE_HIVE_SERVICE". - */ - public static final int XA_PERM_TYPE_SERVICEADMIN = 33; - /** - * XA_PERM_TYPE_TEMPUDFADMIN is an element of enum XAPermType. Its value is "XA_PERM_TYPE_TEMPUDFADMIN". - */ - public static final int XA_PERM_TYPE_TEMPUDFADMIN = 34; - /** - * XA_PERM_TYPE_IDEMPOTENT_WRITE is an element of enum XAPermType. Its value is "XA_PERM_TYPE_IDEMPOTENT_WRITE". - */ - public static final int XA_PERM_TYPE_IDEMPOTENT_WRITE = 35; - /** - * XA_PERM_TYPE_DESCRIBE_CONFIGS is an element of enum XAPermType. Its value is "XA_PERM_TYPE_DESCRIBE_CONFIGS". - */ - public static final int XA_PERM_TYPE_DESCRIBE_CONFIGS = 36; - /** - * XA_PERM_TYPE_ALTER_CONFIGS is an element of enum XAPermType. Its value is "XA_PERM_TYPE_ALTER_CONFIGS". - */ - public static final int XA_PERM_TYPE_ALTER_CONFIGS = 37; - /** - * XA_PERM_TYPE_CLUSTER_ACTION is an element of enum XAPermType. Its value is "XA_PERM_TYPE_CLUSTER_ACTION". - */ - public static final int XA_PERM_TYPE_CLUSTER_ACTION = 38; + /*************************************************************** + * 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; + /** + * XA_PERM_TYPE_REPLADMIN is an element of enum XAPermType. Its value is "XA_PERM_TYPE_REPLADMIN". + */ + public static final int XA_PERM_TYPE_REPLADMIN = 32; + /** + * XA_PERM_TYPE_SERVICEADMIN is an element of enum XAPermType. Its value is "XA_PERM_TYPE_HIVE_SERVICE". + */ + public static final int XA_PERM_TYPE_SERVICEADMIN = 33; + /** + * XA_PERM_TYPE_TEMPUDFADMIN is an element of enum XAPermType. Its value is "XA_PERM_TYPE_TEMPUDFADMIN". + */ + public static final int XA_PERM_TYPE_TEMPUDFADMIN = 34; + /** + * XA_PERM_TYPE_IDEMPOTENT_WRITE is an element of enum XAPermType. Its value is "XA_PERM_TYPE_IDEMPOTENT_WRITE". + */ + public static final int XA_PERM_TYPE_IDEMPOTENT_WRITE = 35; + /** + * XA_PERM_TYPE_DESCRIBE_CONFIGS is an element of enum XAPermType. Its value is "XA_PERM_TYPE_DESCRIBE_CONFIGS". + */ + public static final int XA_PERM_TYPE_DESCRIBE_CONFIGS = 36; + /** + * XA_PERM_TYPE_ALTER_CONFIGS is an element of enum XAPermType. Its value is "XA_PERM_TYPE_ALTER_CONFIGS". + */ + public static final int XA_PERM_TYPE_ALTER_CONFIGS = 37; + /** + * XA_PERM_TYPE_CLUSTER_ACTION is an element of enum XAPermType. Its value is "XA_PERM_TYPE_CLUSTER_ACTION". + */ + public static final int XA_PERM_TYPE_CLUSTER_ACTION = 38; - /** - * Max value for enum XAPermType_MAX - */ - public static final int XAPermType_MAX = 38; + /** + * Max value for enum XAPermType_MAX + */ + public static final int XAPermType_MAX = 38; - /*************************************************************** - * 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; - /** - * DB Favor Postgres - */ - public static final int DB_FLAVOR_POSTGRES = 3; - /** - * DB Favor SQLServer - */ - public static final int DB_FLAVOR_SQLSERVER = 4; - public static final int DB_FLAVOR_SQLANYWHERE = 5; + /*************************************************************** + * 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; + /** + * DB Favor Postgres + */ + public static final int DB_FLAVOR_POSTGRES = 3; + /** + * DB Favor SQLServer + */ + public static final int DB_FLAVOR_SQLSERVER = 4; + public static final int DB_FLAVOR_SQLANYWHERE = 5; + /*************************************************************** + * 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; + /** + * CLASS_TYPE_XA_ACCESS_TYPE_DEF is an element of enum ClassTypes. Its value is "CLASS_TYPE_XA_ACCESS_TYPE_DEF". + */ + public static final int CLASS_TYPE_XA_ACCESS_TYPE_DEF = 1015; + /** + * CLASS_TYPE_XA_ACCESS_TYPE_DEF_GRANTS is an element of enum ClassTypes. Its value is "CLASS_TYPE_XA_ACCESS_TYPE_DEF_GRANTS". + */ + public static final int CLASS_TYPE_XA_ACCESS_TYPE_DEF_GRANTS = 1016; + /** + * CLASS_TYPE_XA_DATA_HIST is an element of enum ClassTypes. Its value is "CLASS_TYPE_XA_DATA_HIST". + */ + public static final int CLASS_TYPE_XA_DATA_HIST = 1017; + /** + * CLASS_TYPE_XA_ENUM_DEF is an element of enum ClassTypes. Its value is "CLASS_TYPE_XA_ENUM_DEF". + */ + public static final int CLASS_TYPE_XA_ENUM_DEF = 1018; + /** + * CLASS_TYPE_XA_ENUM_DEF_ELEMENT is an element of enum ClassTypes. Its value is "CLASS_TYPE_XA_ENUM_DEF_ELEMENT". + */ + public static final int CLASS_TYPE_XA_ENUM_ELEMENT_DEF = 1019; + /** + * CLASS_TYPE_RANGER_POLICY is an element of enum ClassTypes. Its value is "CLASS_TYPE_RANGER_POLICY". + */ + public static final int CLASS_TYPE_RANGER_POLICY = 1020; + /** + * CLASS_TYPE_RANGER_POLICY_CONDITION_DEF is an element of enum ClassTypes. Its value is "CLASS_TYPE_RANGER_POLICY_CONDITION_DEF". + */ + public static final int CLASS_TYPE_RANGER_POLICY_CONDITION_DEF = 1021; + /** + * CLASS_TYPE_RANGER_POLICY_ITEM is an element of enum ClassTypes. Its value is "CLASS_TYPE_RANGER_POLICY_ITEM". + */ + public static final int CLASS_TYPE_RANGER_POLICY_ITEM = 1022; + /** + * CLASS_TYPE_RANGER_POLICY_ITEM_ACCESS is an element of enum ClassTypes. Its value is "CLASS_TYPE_RANGER_POLICY_ITEM_ACCESS". + */ + public static final int CLASS_TYPE_RANGER_POLICY_ITEM_ACCESS = 1023; + /** + * CLASS_TYPE_RANGER_POLICY_CONDITION is an element of enum ClassTypes. Its value is "CLASS_TYPE_RANGER_POLICY_CONDITION". + */ + public static final int CLASS_TYPE_RANGER_POLICY_ITEM_CONDITION = 1024; + /** + * CLASS_TYPE_RANGER_POLICY_ITEM_GRP_PERM is an element of enum ClassTypes. Its value is "CLASS_TYPE_RANGER_POLICY_ITEM_GRP_PERM". + */ + public static final int CLASS_TYPE_RANGER_POLICY_ITEM_GRP_PERM = 1025; + /** + * CLASS_TYPE_RANGER_POLICY_ITEM_USER_PERM is an element of enum ClassTypes. Its value is "CLASS_TYPE_RANGER_POLICY_ITEM_USER_PERM". + */ + public static final int CLASS_TYPE_RANGER_POLICY_ITEM_USER_PERM = 1026; + /** + * CLASS_TYPE_RANGER_POLICY_RESOURCE is an element of enum ClassTypes. Its value is "CLASS_TYPE_RANGER_POLICY_RESOURCE". + */ + public static final int CLASS_TYPE_RANGER_POLICY_RESOURCE = 1027; + /** + * CLASS_TYPE_RANGER_POLICY_RESOURCE_MAP is an element of enum ClassTypes. Its value is "CLASS_TYPE_RANGER_POLICY_RESOURCE_MAP". + */ + public static final int CLASS_TYPE_RANGER_POLICY_RESOURCE_MAP = 1028; + /** + * CLASS_TYPE_XA_RESOURCE_DEF is an element of enum ClassTypes. Its value is "CLASS_TYPE_XA_RESOURCE_DEF". + */ + public static final int CLASS_TYPE_XA_RESOURCE_DEF = 1029; + /** + * CLASS_TYPE_XA_SERVICE is an element of enum ClassTypes. Its value is "CLASS_TYPE_XA_SERVICE". + */ + public static final int CLASS_TYPE_XA_SERVICE = 1030; + /** + * CLASS_TYPE_XA_SERVICE_CONFIG_DEF is an element of enum ClassTypes. Its value is "CLASS_TYPE_XA_SERVICE_CONFIG_DEF". + */ + public static final int CLASS_TYPE_XA_SERVICE_CONFIG_DEF = 1031; + /** + * CLASS_TYPE_XA_SERVICE_CONFIG_MAP is an element of enum ClassTypes. Its value is "CLASS_TYPE_XA_SERVICE_CONFIG_MAP". + */ + public static final int CLASS_TYPE_XA_SERVICE_CONFIG_MAP = 1032; + /** + * CLASS_TYPE_XA_SERVICE_DEF is an element of enum ClassTypes. Its value is "CLASS_TYPE_XA_SERVICE_DEF". + */ + public static final int CLASS_TYPE_XA_SERVICE_DEF = 1033; - /*************************************************************** - * 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; - /** - * CLASS_TYPE_XA_ACCESS_TYPE_DEF is an element of enum ClassTypes. Its value is "CLASS_TYPE_XA_ACCESS_TYPE_DEF". - */ - public static final int CLASS_TYPE_XA_ACCESS_TYPE_DEF = 1015; - /** - * CLASS_TYPE_XA_ACCESS_TYPE_DEF_GRANTS is an element of enum ClassTypes. Its value is "CLASS_TYPE_XA_ACCESS_TYPE_DEF_GRANTS". - */ - public static final int CLASS_TYPE_XA_ACCESS_TYPE_DEF_GRANTS = 1016; - /** - * CLASS_TYPE_XA_DATA_HIST is an element of enum ClassTypes. Its value is "CLASS_TYPE_XA_DATA_HIST". - */ - public static final int CLASS_TYPE_XA_DATA_HIST = 1017; - /** - * CLASS_TYPE_XA_ENUM_DEF is an element of enum ClassTypes. Its value is "CLASS_TYPE_XA_ENUM_DEF". - */ - public static final int CLASS_TYPE_XA_ENUM_DEF = 1018; - /** - * CLASS_TYPE_XA_ENUM_DEF_ELEMENT is an element of enum ClassTypes. Its value is "CLASS_TYPE_XA_ENUM_DEF_ELEMENT". - */ - public static final int CLASS_TYPE_XA_ENUM_ELEMENT_DEF = 1019; - /** - * CLASS_TYPE_RANGER_POLICY is an element of enum ClassTypes. Its value is "CLASS_TYPE_RANGER_POLICY". - */ - public static final int CLASS_TYPE_RANGER_POLICY = 1020; - /** - * CLASS_TYPE_RANGER_POLICY_CONDITION_DEF is an element of enum ClassTypes. Its value is "CLASS_TYPE_RANGER_POLICY_CONDITION_DEF". - */ - public static final int CLASS_TYPE_RANGER_POLICY_CONDITION_DEF = 1021; - /** - * CLASS_TYPE_RANGER_POLICY_ITEM is an element of enum ClassTypes. Its value is "CLASS_TYPE_RANGER_POLICY_ITEM". - */ - public static final int CLASS_TYPE_RANGER_POLICY_ITEM = 1022; - /** - * CLASS_TYPE_RANGER_POLICY_ITEM_ACCESS is an element of enum ClassTypes. Its value is "CLASS_TYPE_RANGER_POLICY_ITEM_ACCESS". - */ - public static final int CLASS_TYPE_RANGER_POLICY_ITEM_ACCESS = 1023; - /** - * CLASS_TYPE_RANGER_POLICY_CONDITION is an element of enum ClassTypes. Its value is "CLASS_TYPE_RANGER_POLICY_CONDITION". - */ - public static final int CLASS_TYPE_RANGER_POLICY_ITEM_CONDITION = 1024; - /** - * CLASS_TYPE_RANGER_POLICY_ITEM_GRP_PERM is an element of enum ClassTypes. Its value is "CLASS_TYPE_RANGER_POLICY_ITEM_GRP_PERM". - */ - public static final int CLASS_TYPE_RANGER_POLICY_ITEM_GRP_PERM = 1025; - /** - * CLASS_TYPE_RANGER_POLICY_ITEM_USER_PERM is an element of enum ClassTypes. Its value is "CLASS_TYPE_RANGER_POLICY_ITEM_USER_PERM". - */ - public static final int CLASS_TYPE_RANGER_POLICY_ITEM_USER_PERM = 1026; - /** - * CLASS_TYPE_RANGER_POLICY_RESOURCE is an element of enum ClassTypes. Its value is "CLASS_TYPE_RANGER_POLICY_RESOURCE". - */ - public static final int CLASS_TYPE_RANGER_POLICY_RESOURCE = 1027; - /** - * CLASS_TYPE_RANGER_POLICY_RESOURCE_MAP is an element of enum ClassTypes. Its value is "CLASS_TYPE_RANGER_POLICY_RESOURCE_MAP". - */ - public static final int CLASS_TYPE_RANGER_POLICY_RESOURCE_MAP = 1028; - /** - * CLASS_TYPE_XA_RESOURCE_DEF is an element of enum ClassTypes. Its value is "CLASS_TYPE_XA_RESOURCE_DEF". - */ - public static final int CLASS_TYPE_XA_RESOURCE_DEF = 1029; - /** - * CLASS_TYPE_XA_SERVICE is an element of enum ClassTypes. Its value is "CLASS_TYPE_XA_SERVICE". - */ - public static final int CLASS_TYPE_XA_SERVICE = 1030; - /** - * CLASS_TYPE_XA_SERVICE_CONFIG_DEF is an element of enum ClassTypes. Its value is "CLASS_TYPE_XA_SERVICE_CONFIG_DEF". - */ - public static final int CLASS_TYPE_XA_SERVICE_CONFIG_DEF = 1031; - /** - * CLASS_TYPE_XA_SERVICE_CONFIG_MAP is an element of enum ClassTypes. Its value is "CLASS_TYPE_XA_SERVICE_CONFIG_MAP". - */ - public static final int CLASS_TYPE_XA_SERVICE_CONFIG_MAP = 1032; - /** - * CLASS_TYPE_XA_SERVICE_DEF is an element of enum ClassTypes. Its value is "CLASS_TYPE_XA_SERVICE_DEF". - */ - public static final int CLASS_TYPE_XA_SERVICE_DEF = 1033; + /** + * CLASS_TYPE_RANGER_MODULE_DEF is an element of enum ClassTypes. Its value is "CLASS_TYPE_RANGER_MODULE_DEF". + */ + public static final int CLASS_TYPE_RANGER_MODULE_DEF = 1034; + /** + * CLASS_TYPE_RANGER_USER_PERMISSION is an element of enum ClassTypes. Its value is "CLASS_TYPE_RANGER_USER_PERMISSION". + */ + public static final int CLASS_TYPE_RANGER_USER_PERMISSION = 1035; + /** + * CLASS_TYPE_RANGER_GROUP_PERMISSION is an element of enum ClassTypes. Its value is "CLASS_TYPE_RANGER_GROUP_PERMISSION". + */ + public static final int CLASS_TYPE_RANGER_GROUP_PERMISSION = 1036; + /** + * CLASS_TYPE_XA_KMS_KEY is an element of enum ClassTypes. Its value is "CLASS_TYPE_XA_KMS_KEY". + */ + public static final int CLASS_TYPE_XA_KMS_KEY = 1037; + /** + * CLASS_TYPE_RANGER_POLICY_WITH_ASSIGNED_ID is an element of enum ClassTypes. Its value is "CLASS_TYPE_RANGER_POLICY_WITH_ASSIGNED_ID". + */ + public static final int CLASS_TYPE_RANGER_POLICY_WITH_ASSIGNED_ID = 1038; + /** + * CLASS_TYPE_RANGER_SERVICE_WITH_ASSIGNED_ID is an element of enum ClassTypes. Its value is "CLASS_TYPE_RANGER_SERVICE_WITH_ASSIGNED_ID". + */ + public static final int CLASS_TYPE_RANGER_SERVICE_WITH_ASSIGNED_ID = 1039; + /** + * CLASS_TYPE_RANGER_SERVICE_DEF_WITH_ASSIGNED_ID is an element of enum ClassTypes. Its value is "CLASS_TYPE_RANGER_SERVICE_DEF_WITH_ASSIGNED_ID". + */ + public static final int CLASS_TYPE_RANGER_SERVICE_DEF_WITH_ASSIGNED_ID = 1040; + /** + * Class type of XXTagDef + */ + public static final int CLASS_TYPE_XA_TAG_DEF = 1041; + /** + * Class type of XXTagAttributeDef + */ + public static final int CLASS_TYPE_XA_TAG_ATTR_DEF = 1042; + /** + * Class type of XXServiceResource + */ + public static final int CLASS_TYPE_XA_SERVICE_RESOURCE = 1043; + /** + * Class type of XXServiceResourceElement + */ + public static final int CLASS_TYPE_XA_SERVICE_RESOURCE_ELEMENT = 1044; + /** + * Class type of XXServiceResourceElementValue + */ + public static final int CLASS_TYPE_XA_SERVICE_RESOURCE_ELEMENT_VALUE = 1045; + /** + * Class type of XXTag + */ + public static final int CLASS_TYPE_XA_TAG = 1046; + /** + * Class type of XXTagAttribute + */ + public static final int CLASS_TYPE_XA_TAG_ATTR = 1047; + /** + * Class type of XXTagResourceMap + */ + public static final int CLASS_TYPE_XA_TAG_RESOURCE_MAP = 1048; + /** + * CLASS_TYPE_XA_DATAMASK_DEF is an element of enum ClassTypes. Its value is "CLASS_TYPE_XA_DATAMASK_DEF". + */ + public static final int CLASS_TYPE_XA_DATAMASK_DEF = 1049; + /** + * CLASS_TYPE_RANGER_POLICY_ITEM_DATAMASK_INFO is an element of enum ClassTypes. Its value is "CLASS_TYPE_RANGER_POLICY_ITEM_DATAMASK_INFO". + */ + public static final int CLASS_TYPE_RANGER_POLICY_ITEM_DATAMASK_INFO = 1050; + /** + * CLASS_TYPE_RANGER_POLICY_ITEM_ROWFILTER_INFO is an element of enum ClassTypes. Its value is "CLASS_TYPE_RANGER_POLICY_ITEM_ROWFILTER_INFO". + */ + public static final int CLASS_TYPE_RANGER_POLICY_ITEM_ROWFILTER_INFO = 1051; - /** - * CLASS_TYPE_RANGER_MODULE_DEF is an element of enum ClassTypes. Its value is "CLASS_TYPE_RANGER_MODULE_DEF". - */ - public static final int CLASS_TYPE_RANGER_MODULE_DEF = 1034; - /** - * CLASS_TYPE_RANGER_USER_PERMISSION is an element of enum ClassTypes. Its value is "CLASS_TYPE_RANGER_USER_PERMISSION". - */ - public static final int CLASS_TYPE_RANGER_USER_PERMISSION = 1035; - /** - * CLASS_TYPE_RANGER_GROUP_PERMISSION is an element of enum ClassTypes. Its value is "CLASS_TYPE_RANGER_GROUP_PERMISSION". - */ - public static final int CLASS_TYPE_RANGER_GROUP_PERMISSION = 1036; - /** - * CLASS_TYPE_XA_KMS_KEY is an element of enum ClassTypes. Its value is "CLASS_TYPE_XA_KMS_KEY". - */ - public static final int CLASS_TYPE_XA_KMS_KEY = 1037; - /** - * CLASS_TYPE_RANGER_POLICY_WITH_ASSIGNED_ID is an element of enum ClassTypes. Its value is "CLASS_TYPE_RANGER_POLICY_WITH_ASSIGNED_ID". - */ - public static final int CLASS_TYPE_RANGER_POLICY_WITH_ASSIGNED_ID = 1038; - /** - * CLASS_TYPE_RANGER_SERVICE_WITH_ASSIGNED_ID is an element of enum ClassTypes. Its value is "CLASS_TYPE_RANGER_SERVICE_WITH_ASSIGNED_ID". - */ - public static final int CLASS_TYPE_RANGER_SERVICE_WITH_ASSIGNED_ID = 1039; - /** - * CLASS_TYPE_RANGER_SERVICE_DEF_WITH_ASSIGNED_ID is an element of enum ClassTypes. Its value is "CLASS_TYPE_RANGER_SERVICE_DEF_WITH_ASSIGNED_ID". - */ - public static final int CLASS_TYPE_RANGER_SERVICE_DEF_WITH_ASSIGNED_ID = 1040; - /** - * Class type of XXTagDef - */ - public static final int CLASS_TYPE_XA_TAG_DEF = 1041; - /** - * Class type of XXTagAttributeDef - */ - public static final int CLASS_TYPE_XA_TAG_ATTR_DEF = 1042; - /** - * Class type of XXServiceResource - */ - public static final int CLASS_TYPE_XA_SERVICE_RESOURCE = 1043; - /** - * Class type of XXServiceResourceElement - */ - public static final int CLASS_TYPE_XA_SERVICE_RESOURCE_ELEMENT = 1044; - /** - * Class type of XXServiceResourceElementValue - */ - public static final int CLASS_TYPE_XA_SERVICE_RESOURCE_ELEMENT_VALUE = 1045; - /** - * Class type of XXTag - */ - public static final int CLASS_TYPE_XA_TAG = 1046; - /** - * Class type of XXTagAttribute - */ - public static final int CLASS_TYPE_XA_TAG_ATTR = 1047; - /** - * Class type of XXTagResourceMap - */ - public static final int CLASS_TYPE_XA_TAG_RESOURCE_MAP = 1048; - /** - * CLASS_TYPE_XA_DATAMASK_DEF is an element of enum ClassTypes. Its value is "CLASS_TYPE_XA_DATAMASK_DEF". - */ - public static final int CLASS_TYPE_XA_DATAMASK_DEF = 1049; - /** - * CLASS_TYPE_RANGER_POLICY_ITEM_DATAMASK_INFO is an element of enum ClassTypes. Its value is "CLASS_TYPE_RANGER_POLICY_ITEM_DATAMASK_INFO". - */ - public static final int CLASS_TYPE_RANGER_POLICY_ITEM_DATAMASK_INFO = 1050; - /** - * CLASS_TYPE_RANGER_POLICY_ITEM_ROWFILTER_INFO is an element of enum ClassTypes. Its value is "CLASS_TYPE_RANGER_POLICY_ITEM_ROWFILTER_INFO". - */ - public static final int CLASS_TYPE_RANGER_POLICY_ITEM_ROWFILTER_INFO = 1051; + /** + * CLASS_TYPE_XA_SERVICE_VERSION_INFO is an element of enum ClassTypes. Its value is "CLASS_TYPE_XA_SERVICE_VERSION_INFO". + */ + public static final int CLASS_TYPE_XA_SERVICE_VERSION_INFO = 1052; + public static final int CLASS_TYPE_XA_ACCESS_AUDIT_V4 = 1053; + public static final int CLASS_TYPE_XA_ACCESS_AUDIT_V5 = 1054; + public static final int CLASS_TYPE_UGYNC_AUDIT_INFO = 1055; - /** - * CLASS_TYPE_XA_SERVICE_VERSION_INFO is an element of enum ClassTypes. Its value is "CLASS_TYPE_XA_SERVICE_VERSION_INFO". - */ - public static final int CLASS_TYPE_XA_SERVICE_VERSION_INFO = 1052; - public static final int CLASS_TYPE_XA_ACCESS_AUDIT_V4 = 1053; - public static final int CLASS_TYPE_XA_ACCESS_AUDIT_V5 = 1054; - public static final int CLASS_TYPE_UGYNC_AUDIT_INFO = 1055; + /** + * Class type of RangerSecurityZone + */ - /** - * Class type of RangerSecurityZone - */ + public static final int CLASS_TYPE_RANGER_SECURITY_ZONE = 1056; + public static final int CLASS_TYPE_RANGER_ROLE = 1057; - public static final int CLASS_TYPE_RANGER_SECURITY_ZONE = 1056; - public static final int CLASS_TYPE_RANGER_ROLE = 1057; + public static final int CLASS_TYPE_RMS_MAPPING_PROVIDER = 1058; + public static final int CLASS_TYPE_RMS_NOTIFICATION = 1059; + public static final int CLASS_TYPE_RMS_SERVICE_RESOURCE = 1060; + public static final int CLASS_TYPE_RMS_RESOURCE_MAPPING = 1061; - public static final int CLASS_TYPE_RMS_MAPPING_PROVIDER = 1058; - public static final int CLASS_TYPE_RMS_NOTIFICATION = 1059; - public static final int CLASS_TYPE_RMS_SERVICE_RESOURCE = 1060; - public static final int CLASS_TYPE_RMS_RESOURCE_MAPPING = 1061; + /** + * Class type of RangerGds + */ + public static final int CLASS_TYPE_GDS_DATASET = 1062; + public static final int CLASS_TYPE_GDS_PROJECT = 1063; + public static final int CLASS_TYPE_GDS_DATA_SHARE = 1064; + public static final int CLASS_TYPE_GDS_SHARED_RESOURCE = 1065; + public static final int CLASS_TYPE_GDS_DATA_SHARE_IN_DATASET = 1066; + public static final int CLASS_TYPE_GDS_DATASET_IN_PROJECT = 1067; + public static final int CLASS_TYPE_GDS_DATASET_POLICY_MAP = 1068; + public static final int CLASS_TYPE_GDS_PROJECT_POLICY_MAP = 1069; - /** - * Class type of RangerGds - */ - public static final int CLASS_TYPE_GDS_DATASET = 1062; - public static final int CLASS_TYPE_GDS_PROJECT = 1063; - public static final int CLASS_TYPE_GDS_DATA_SHARE = 1064; - public static final int CLASS_TYPE_GDS_SHARED_RESOURCE = 1065; - public static final int CLASS_TYPE_GDS_DATA_SHARE_IN_DATASET = 1066; - public static final int CLASS_TYPE_GDS_DATASET_IN_PROJECT = 1067; - public static final int CLASS_TYPE_GDS_DATASET_POLICY_MAP = 1068; - public static final int CLASS_TYPE_GDS_PROJECT_POLICY_MAP = 1069; + /** + * Max value for enum ClassTypes_MAX + */ + public static final int ClassTypes_MAX = 1069; - /** - * Max value for enum ClassTypes_MAX - */ - public static final int ClassTypes_MAX = 1069; + /*************************************************************** + * Enum values for Default SortOrder + **************************************************************/ + public static final int DEFAULT_SORT_ORDER = 0; - - /*************************************************************** - * Enum values for Default SortOrder - **************************************************************/ - public static final int DEFAULT_SORT_ORDER = 0; - - /*************************************************************** - * Enum values for STATUS of XXDataHist object - **************************************************************/ - public static final int HIST_OBJ_STATUS_UNKNOWN = 0; - public static final int HIST_OBJ_STATUS_CREATED = 1; - public static final int HIST_OBJ_STATUS_UPDATED = 2; - public static final int HIST_OBJ_STATUS_DELETED = 3; - public static final int MAX_HIST_OBJ_STATUS = 3; + /*************************************************************** + * Enum values for STATUS of XXDataHist object + **************************************************************/ + public static final int HIST_OBJ_STATUS_UNKNOWN = 0; + public static final int HIST_OBJ_STATUS_CREATED = 1; + public static final int HIST_OBJ_STATUS_UPDATED = 2; + public static final int HIST_OBJ_STATUS_DELETED = 3; + public static final int MAX_HIST_OBJ_STATUS = 3; - public static final String Masked_String = "*****"; + public static final String Masked_String = "*****"; + public static 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_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; - } + public static 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; - } + public static 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; - } + public static 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; - } + public static 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; - } + public static 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"; - } - if( elementValue == 32 ) { - // return "Repl Admin"; //XA_PERM_TYPE_REPL_ADMIN - return "repladmin"; - } - if( elementValue == 33 ) { - // return "serviceadmin"; //XA_PERM_TYPE_SERVICEADMIN - return "serviceadmin"; - } - if( elementValue == 34 ) { - // return "tempudfadmin"; //XA_PERM_TYPE_TEMPUDFADMIN - return "tempudfadmin"; - } - if( elementValue == 35 ) { - // return "Idempotent Write"; //XA_PERM_TYPE_IDEMPOTENT_WRITE - return "idempotent_write"; - } - if( elementValue == 36 ) { - // return "Describe Configs"; //XA_PERM_TYPE_DESCRIBE_CONFIGS - return "describe_configs"; - } - if( elementValue == 37 ) { - // return "Alter Configs"; //XA_PERM_TYPE_ALTER_CONFIGS - return "alter_configs"; - } - if( elementValue == 38 ) { - // return "Cluster Action"; //XA_PERM_TYPE_CLUSTER_ACTION - return "cluster_action"; - } - return null; - } + public static 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"; + } + if (elementValue == 32) { + // return "Repl Admin"; //XA_PERM_TYPE_REPL_ADMIN + return "repladmin"; + } + if (elementValue == 33) { + // return "serviceadmin"; //XA_PERM_TYPE_SERVICEADMIN + return "serviceadmin"; + } + if (elementValue == 34) { + // return "tempudfadmin"; //XA_PERM_TYPE_TEMPUDFADMIN + return "tempudfadmin"; + } + if (elementValue == 35) { + // return "Idempotent Write"; //XA_PERM_TYPE_IDEMPOTENT_WRITE + return "idempotent_write"; + } + if (elementValue == 36) { + // return "Describe Configs"; //XA_PERM_TYPE_DESCRIBE_CONFIGS + return "describe_configs"; + } + if (elementValue == 37) { + // return "Alter Configs"; //XA_PERM_TYPE_ALTER_CONFIGS + return "alter_configs"; + } + if (elementValue == 38) { + // return "Cluster Action"; //XA_PERM_TYPE_CLUSTER_ACTION + return "cluster_action"; + } + 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 - } - if( elementValue == 1014 ) { - return "Trx Log Attribute"; //CLASS_TYPE_XA_TRANSACTION_LOG_ATTRIBUTE - } - if( elementValue == 1015 ) { - return "XA AccessType Def"; //CLASS_TYPE_XA_ACCESS_TYPE_DEF - } - if( elementValue == 1016 ) { - return "XA AccessType Def Grants"; //CLASS_TYPE_XA_ACCESS_TYPE_DEF_GRANTS - } - if( elementValue == 1017 ) { - return "XA Data History"; //CLASS_TYPE_XA_DATA_HIST - } - if( elementValue == 1018 ) { - return "XA Enum Defination"; //CLASS_TYPE_XA_ENUM_DEF - } - if( elementValue == 1019 ) { - return "XA EnumElement Def"; //CLASS_TYPE_XA_ENUM_DEF_ELEMENT - } - if( elementValue == 1020 ) { - return "Ranger Policy"; //CLASS_TYPE_RANGER_POLICY - } - if( elementValue == 1021 ) { - return "RangerPolicy Condition Def"; //CLASS_TYPE_RANGER_POLICY_CONDITION_DEF - } - if( elementValue == 1022 ) { - return "RangerPolicy Item"; //CLASS_TYPE_RANGER_POLICY_ITEM - } - if( elementValue == 1023 ) { - return "RangerPolicy Item Access"; //CLASS_TYPE_RANGER_POLICY_ITEM_ACCESS - } - if( elementValue == 1024 ) { - return "RangerPolicyItem Condition "; //CLASS_TYPE_RANGER_POLICY_CONDITION - } - if( elementValue == 1025 ) { - return "RangerPolicy ItemGrp Map"; //CLASS_TYPE_RANGER_POLICY_ITEM_GRP_PERM - } - if( elementValue == 1026 ) { - return "RangerPolicy ItemUser Map"; //CLASS_TYPE_RANGER_POLICY_ITEM_USER_PERM - } - if( elementValue == 1027 ) { - return "RangerPolicy Resource"; //CLASS_TYPE_RANGER_POLICY_RESOURCE - } - if( elementValue == 1028 ) { - return "RangerPolicy Resource Map"; //CLASS_TYPE_RANGER_POLICY_RESOURCE_MAP - } - if( elementValue == 1029 ) { - return "XA Resource Def"; //CLASS_TYPE_XA_RESOURCE_DEF - } - if( elementValue == 1030 ) { - return "XA Service"; //CLASS_TYPE_XA_SERVICE - } - if( elementValue == 1031 ) { - return "XA Service Config Def"; //CLASS_TYPE_XA_SERVICE_CONFIG_DEF - } - if( elementValue == 1032 ) { - return "XA Service Config Map"; //CLASS_TYPE_XA_SERVICE_CONFIG_MAP - } - if( elementValue == 1033 ) { - return "XA Service Def"; //CLASS_TYPE_XA_SERVICE_DEF - } - if( elementValue == 1052 ) { - return "XA Service Version Info"; //CLASS_TYPE_XA_SERVICE_VERSION_INFO - } - if( elementValue == 1053 ) { - return "Access Audit V4"; //CLASS_TYPE_XA_ACCESS_AUDIT_V4 - } - if( elementValue == 1054 ) { - return "Access Audit V5"; //CLASS_TYPE_XA_ACCESS_AUDIT_V5 - } - if( elementValue == 1055 ) { - return "Usersync Audit Info"; //CLASS_TYPE_UGYNC_AUDIT_INFO - } - if( elementValue == 1056 ) { - return "Ranger Security Zone"; //CLASS_TYPE_RANGER_SECURITY_ZONE - } - if( elementValue == 1057 ) { - return "Ranger Role"; //CLASS_TYPE_RANGER_ROLE - } + public static 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 + } + if (elementValue == 1014) { + return "Trx Log Attribute"; //CLASS_TYPE_XA_TRANSACTION_LOG_ATTRIBUTE + } + if (elementValue == 1015) { + return "XA AccessType Def"; //CLASS_TYPE_XA_ACCESS_TYPE_DEF + } + if (elementValue == 1016) { + return "XA AccessType Def Grants"; //CLASS_TYPE_XA_ACCESS_TYPE_DEF_GRANTS + } + if (elementValue == 1017) { + return "XA Data History"; //CLASS_TYPE_XA_DATA_HIST + } + if (elementValue == 1018) { + return "XA Enum Defination"; //CLASS_TYPE_XA_ENUM_DEF + } + if (elementValue == 1019) { + return "XA EnumElement Def"; //CLASS_TYPE_XA_ENUM_DEF_ELEMENT + } + if (elementValue == 1020) { + return "Ranger Policy"; //CLASS_TYPE_RANGER_POLICY + } + if (elementValue == 1021) { + return "RangerPolicy Condition Def"; //CLASS_TYPE_RANGER_POLICY_CONDITION_DEF + } + if (elementValue == 1022) { + return "RangerPolicy Item"; //CLASS_TYPE_RANGER_POLICY_ITEM + } + if (elementValue == 1023) { + return "RangerPolicy Item Access"; //CLASS_TYPE_RANGER_POLICY_ITEM_ACCESS + } + if (elementValue == 1024) { + return "RangerPolicyItem Condition "; //CLASS_TYPE_RANGER_POLICY_CONDITION + } + if (elementValue == 1025) { + return "RangerPolicy ItemGrp Map"; //CLASS_TYPE_RANGER_POLICY_ITEM_GRP_PERM + } + if (elementValue == 1026) { + return "RangerPolicy ItemUser Map"; //CLASS_TYPE_RANGER_POLICY_ITEM_USER_PERM + } + if (elementValue == 1027) { + return "RangerPolicy Resource"; //CLASS_TYPE_RANGER_POLICY_RESOURCE + } + if (elementValue == 1028) { + return "RangerPolicy Resource Map"; //CLASS_TYPE_RANGER_POLICY_RESOURCE_MAP + } + if (elementValue == 1029) { + return "XA Resource Def"; //CLASS_TYPE_XA_RESOURCE_DEF + } + if (elementValue == 1030) { + return "XA Service"; //CLASS_TYPE_XA_SERVICE + } + if (elementValue == 1031) { + return "XA Service Config Def"; //CLASS_TYPE_XA_SERVICE_CONFIG_DEF + } + if (elementValue == 1032) { + return "XA Service Config Map"; //CLASS_TYPE_XA_SERVICE_CONFIG_MAP + } + if (elementValue == 1033) { + return "XA Service Def"; //CLASS_TYPE_XA_SERVICE_DEF + } + if (elementValue == 1052) { + return "XA Service Version Info"; //CLASS_TYPE_XA_SERVICE_VERSION_INFO + } + if (elementValue == 1053) { + return "Access Audit V4"; //CLASS_TYPE_XA_ACCESS_AUDIT_V4 + } + if (elementValue == 1054) { + return "Access Audit V5"; //CLASS_TYPE_XA_ACCESS_AUDIT_V5 + } + if (elementValue == 1055) { + return "Usersync Audit Info"; //CLASS_TYPE_UGYNC_AUDIT_INFO + } + if (elementValue == 1056) { + return "Ranger Security Zone"; //CLASS_TYPE_RANGER_SECURITY_ZONE + } + if (elementValue == 1057) { + return "Ranger Role"; //CLASS_TYPE_RANGER_ROLE + } - if( elementValue == 1058 ) { - return "Ranger Security Zone"; //CLAS - } - if( elementValue == 1059 ) { - return "Ranger Security Zone"; //CLAS - } - if( elementValue == 1060 ) { - return "Ranger Security Zone"; //CLAS - } - if( elementValue == 1061 ) { - return "Ranger Security Zone"; //CLAS - } - return null; - } + if (elementValue == 1058) { + return "Ranger Security Zone"; //CLAS + } + if (elementValue == 1059) { + return "Ranger Security Zone"; //CLAS + } + if (elementValue == 1060) { + return "Ranger Security Zone"; //CLAS + } + if (elementValue == 1061) { + return "Ranger Security Zone"; //CLAS + } + return null; + } - static public int getEnumFor_AssetType(String label) { - if (label == null) { - return 0; - } - if ("Unknown".equalsIgnoreCase(label)) { - return AppConstants.ASSET_UNKNOWN; // ASSET_UNKNOWN - } - if ("HDFS".equalsIgnoreCase(label)) { - return AppConstants.ASSET_HDFS; // ASSET_HDFS - } - if ("HBase".equalsIgnoreCase(label)) { - return AppConstants.ASSET_HBASE; // ASSET_HBASE - } - if ("Hive".equalsIgnoreCase(label)) { - return AppConstants.ASSET_HIVE; // ASSET_HIVE - } - if ("Knox".equalsIgnoreCase(label)) { - return AppConstants.ASSET_KNOX; // ASSET_KNOX - } - if ("Storm".equalsIgnoreCase(label)) { - return AppConstants.ASSET_STORM; // ASSET_STORM - } - return 0; - } + public static int getEnumFor_AssetType(String label) { + if (label == null) { + return 0; + } + if ("Unknown".equalsIgnoreCase(label)) { + return AppConstants.ASSET_UNKNOWN; // ASSET_UNKNOWN + } + if ("HDFS".equalsIgnoreCase(label)) { + return AppConstants.ASSET_HDFS; // ASSET_HDFS + } + if ("HBase".equalsIgnoreCase(label)) { + return AppConstants.ASSET_HBASE; // ASSET_HBASE + } + if ("Hive".equalsIgnoreCase(label)) { + return AppConstants.ASSET_HIVE; // ASSET_HIVE + } + if ("Knox".equalsIgnoreCase(label)) { + return AppConstants.ASSET_KNOX; // ASSET_KNOX + } + if ("Storm".equalsIgnoreCase(label)) { + 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; - } - } + public static 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; - } + public static 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 ("Unknown".equalsIgnoreCase(label)) { - return AppConstants.RESOURCE_UNKNOWN; // RESOURCE_UNKNOWN - } - if ("Path".equalsIgnoreCase(label)) { - return AppConstants.RESOURCE_PATH; // RESOURCE_PATH - } - if ("Database".equalsIgnoreCase(label)) { - return AppConstants.RESOURCE_DB; // RESOURCE_DB - } - if ("Table".equalsIgnoreCase(label)) { - return AppConstants.RESOURCE_TABLE; // RESOURCE_TABLE - } - if ("Column Family".equalsIgnoreCase(label)) { - return AppConstants.RESOURCE_COL_FAM; // RESOURCE_COL_FAM - } - if ("Column".equalsIgnoreCase(label)) { - return AppConstants.RESOURCE_COLUMN; // RESOURCE_COLUMN - } - if ("VIEW".equalsIgnoreCase(label)) { - return AppConstants.RESOURCE_VIEW; // RESOURCE_VIEW - } - if ("UDF".equalsIgnoreCase(label)) { - return AppConstants.RESOURCE_UDF; // RESOURCE_UDF - } - if ("View Column".equalsIgnoreCase(label)) { - return AppConstants.RESOURCE_VIEW_COL; // RESOURCE_VIEW_COL - } - if ("Topology".equalsIgnoreCase(label)) { - return AppConstants.RESOURCE_TOPOLOGY; // RESOURCE_TOPOLOGY - } - if ("Service".equalsIgnoreCase(label)) { - return AppConstants.RESOURCE_SERVICE_NAME; // RESOURCE_SERVICE_NAME - } - return 0; - } + public static int getEnumFor_ResourceType(String label) { + if (label == null) { + return 0; + } + if ("Unknown".equalsIgnoreCase(label)) { + return AppConstants.RESOURCE_UNKNOWN; // RESOURCE_UNKNOWN + } + if ("Path".equalsIgnoreCase(label)) { + return AppConstants.RESOURCE_PATH; // RESOURCE_PATH + } + if ("Database".equalsIgnoreCase(label)) { + return AppConstants.RESOURCE_DB; // RESOURCE_DB + } + if ("Table".equalsIgnoreCase(label)) { + return AppConstants.RESOURCE_TABLE; // RESOURCE_TABLE + } + if ("Column Family".equalsIgnoreCase(label)) { + return AppConstants.RESOURCE_COL_FAM; // RESOURCE_COL_FAM + } + if ("Column".equalsIgnoreCase(label)) { + return AppConstants.RESOURCE_COLUMN; // RESOURCE_COLUMN + } + if ("VIEW".equalsIgnoreCase(label)) { + return AppConstants.RESOURCE_VIEW; // RESOURCE_VIEW + } + if ("UDF".equalsIgnoreCase(label)) { + return AppConstants.RESOURCE_UDF; // RESOURCE_UDF + } + if ("View Column".equalsIgnoreCase(label)) { + return AppConstants.RESOURCE_VIEW_COL; // RESOURCE_VIEW_COL + } + if ("Topology".equalsIgnoreCase(label)) { + return AppConstants.RESOURCE_TOPOLOGY; // RESOURCE_TOPOLOGY + } + if ("Service".equalsIgnoreCase(label)) { + return AppConstants.RESOURCE_SERVICE_NAME; // RESOURCE_SERVICE_NAME + } + return 0; + } - static public int getEnumFor_XAPermType(String label) { - if (label == null) { - return 0; - } - if ("Unknown".equalsIgnoreCase(label)) { - return AppConstants.XA_PERM_TYPE_UNKNOWN; // XA_PERM_TYPE_UNKNOWN - } - if ("Reset".equalsIgnoreCase(label)) { - return AppConstants.XA_PERM_TYPE_RESET; // XA_PERM_TYPE_RESET - } - if ("Read".equalsIgnoreCase(label)) { - return AppConstants.XA_PERM_TYPE_READ; // XA_PERM_TYPE_READ - } - if ("Write".equalsIgnoreCase(label)) { - return AppConstants.XA_PERM_TYPE_WRITE; // XA_PERM_TYPE_WRITE - } - if ("Create".equalsIgnoreCase(label)) { - return AppConstants.XA_PERM_TYPE_CREATE; // XA_PERM_TYPE_CREATE - } - if ("Delete".equalsIgnoreCase(label)) { - return AppConstants.XA_PERM_TYPE_DELETE; // XA_PERM_TYPE_DELETE - } - if ("Admin".equalsIgnoreCase(label)) { - return AppConstants.XA_PERM_TYPE_ADMIN; // XA_PERM_TYPE_ADMIN - } - if ("Obfuscate".equalsIgnoreCase(label)) { - return AppConstants.XA_PERM_TYPE_OBFUSCATE; // XA_PERM_TYPE_OBFUSCATE - } - if ("Mask".equalsIgnoreCase(label)) { - return AppConstants.XA_PERM_TYPE_MASK; // XA_PERM_TYPE_MASK - } - if ("Execute".equalsIgnoreCase(label)) { - return AppConstants.XA_PERM_TYPE_EXECUTE; // XA_PERM_TYPE_EXECUTE - } - if ("Select".equalsIgnoreCase(label)) { - return AppConstants.XA_PERM_TYPE_SELECT; // XA_PERM_TYPE_SELECT - } - if ("Update".equalsIgnoreCase(label)) { - return AppConstants.XA_PERM_TYPE_UPDATE; // XA_PERM_TYPE_UPDATE - } - if ("Drop".equalsIgnoreCase(label)) { - return AppConstants.XA_PERM_TYPE_DROP; // XA_PERM_TYPE_DROP - } - if ("Alter".equalsIgnoreCase(label)) { - return AppConstants.XA_PERM_TYPE_ALTER; // XA_PERM_TYPE_ALTER - } - if ("Index".equalsIgnoreCase(label)) { - return AppConstants.XA_PERM_TYPE_INDEX; // XA_PERM_TYPE_INDEX - } - if ("Lock".equalsIgnoreCase(label)) { - return AppConstants.XA_PERM_TYPE_LOCK; // XA_PERM_TYPE_LOCK - } - if ("All".equalsIgnoreCase(label)) { - return AppConstants.XA_PERM_TYPE_ALL; // XA_PERM_TYPE_ALL - } - if("Allow".equalsIgnoreCase(label)) { - return AppConstants.XA_PERM_TYPE_ALLOW; //XA_PERM_TYPE_ALLOW - } - if("submitTopology".equalsIgnoreCase(label)) { - return AppConstants.XA_PERM_TYPE_SUBMIT_TOPOLOGY; //XA_PERM_TYPE_SUBMIT_TOPOLOGY - } - if("fileUpload".equalsIgnoreCase(label)) { - return AppConstants.XA_PERM_TYPE_FILE_UPLOAD; //XA_PERM_TYPE_FILE_UPLOAD - } - if("getNimbusConf".equalsIgnoreCase(label)) { - return AppConstants.XA_PERM_TYPE_GET_NIMBUS; //XA_PERM_TYPE_GET_NIMBUS - } - if("getClusterInfo".equalsIgnoreCase(label)) { - return AppConstants.XA_PERM_TYPE_GET_CLUSTER_INFO; //XA_PERM_TYPE_GET_CLUSTER_INFO - } - if("fileDownload".equalsIgnoreCase(label)) { - return AppConstants.XA_PERM_TYPE_FILE_DOWNLOAD; //XA_PERM_TYPE_FILE_DOWNLOAD - } - if("killTopology".equalsIgnoreCase(label)) { - return AppConstants.XA_PERM_TYPE_KILL_TOPOLOGY; //XA_PERM_TYPE_KILL_TOPOLOGY - } - if("rebalance".equalsIgnoreCase(label)) { - return AppConstants.XA_PERM_TYPE_REBALANCE; //XA_PERM_TYPE_REBALANCE - } - if("activate".equalsIgnoreCase(label)) { - return AppConstants.XA_PERM_TYPE_ACTIVATE; //XA_PERM_TYPE_ACTIVATE - } - if("deactivate".equalsIgnoreCase(label)) { - return AppConstants.XA_PERM_TYPE_DEACTIVATE; //XA_PERM_TYPE_DEACTIVATE - } - if("getTopologyConf".equalsIgnoreCase(label)) { - return AppConstants.XA_PERM_TYPE_GET_TOPOLOGY_CONF; //XA_PERM_TYPE_GET_TOPOLOGY_CONF - } - if("getTopology".equalsIgnoreCase(label)) { - return AppConstants.XA_PERM_TYPE_GET_TOPOLOGY; //XA_PERM_TYPE_GET_TOPOLOGY - } - if("getUserTopology".equalsIgnoreCase(label)) { - return AppConstants.XA_PERM_TYPE_GET_USER_TOPOLOGY; //XA_PERM_TYPE_GET_USER_TOPOLOGY - } - if("getTopologyInfo".equalsIgnoreCase(label)) { - return AppConstants.XA_PERM_TYPE_GET_TOPOLOGY_INFO; //XA_PERM_TYPE_GET_TOPOLOGY_INFO - } - if("uploadNewCredentials".equalsIgnoreCase(label)) { - return AppConstants.XA_PERM_TYPE_UPLOAD_NEW_CREDENTIAL; //XA_PERM_TYPE_UPLOAD_NEW_CREDENTIAL - } - if(label.equalsIgnoreCase("repladmin")) { - return AppConstants.XA_PERM_TYPE_REPLADMIN; //XA_PERM_TYPE_REPLADMIN - } - if(label.equalsIgnoreCase("serviceadmin")) { - return AppConstants.XA_PERM_TYPE_SERVICEADMIN; //XA_PERM_TYPE_SERVICEADMIN - } - if("tempudfadmin".equalsIgnoreCase(label)) { - return AppConstants.XA_PERM_TYPE_TEMPUDFADMIN; //XA_PERM_TYPE_TEMPUDFADMIN - } - if("idempotent_write".equalsIgnoreCase(label)) { - return AppConstants.XA_PERM_TYPE_IDEMPOTENT_WRITE; //XA_PERM_TYPE_IDEMPOTENT_WRITE - } - if("describe_configs".equalsIgnoreCase(label)) { - return AppConstants.XA_PERM_TYPE_DESCRIBE_CONFIGS; //XA_PERM_TYPE_DESCRIBE_CONFIGS - } - if("alter_configs".equalsIgnoreCase(label)) { - return AppConstants.XA_PERM_TYPE_ALTER_CONFIGS; //XA_PERM_TYPE_ALTER_CONFIGS - } - if("cluster_action".equalsIgnoreCase(label)) { - return AppConstants.XA_PERM_TYPE_CLUSTER_ACTION; //XA_PERM_TYPE_CLUSTER_ACTION - } - return 0; - } + public static int getEnumFor_XAPermType(String label) { + if (label == null) { + return 0; + } + if ("Unknown".equalsIgnoreCase(label)) { + return AppConstants.XA_PERM_TYPE_UNKNOWN; // XA_PERM_TYPE_UNKNOWN + } + if ("Reset".equalsIgnoreCase(label)) { + return AppConstants.XA_PERM_TYPE_RESET; // XA_PERM_TYPE_RESET + } + if ("Read".equalsIgnoreCase(label)) { + return AppConstants.XA_PERM_TYPE_READ; // XA_PERM_TYPE_READ + } + if ("Write".equalsIgnoreCase(label)) { + return AppConstants.XA_PERM_TYPE_WRITE; // XA_PERM_TYPE_WRITE + } + if ("Create".equalsIgnoreCase(label)) { + return AppConstants.XA_PERM_TYPE_CREATE; // XA_PERM_TYPE_CREATE + } + if ("Delete".equalsIgnoreCase(label)) { + return AppConstants.XA_PERM_TYPE_DELETE; // XA_PERM_TYPE_DELETE + } + if ("Admin".equalsIgnoreCase(label)) { + return AppConstants.XA_PERM_TYPE_ADMIN; // XA_PERM_TYPE_ADMIN + } + if ("Obfuscate".equalsIgnoreCase(label)) { + return AppConstants.XA_PERM_TYPE_OBFUSCATE; // XA_PERM_TYPE_OBFUSCATE + } + if ("Mask".equalsIgnoreCase(label)) { + return AppConstants.XA_PERM_TYPE_MASK; // XA_PERM_TYPE_MASK + } + if ("Execute".equalsIgnoreCase(label)) { + return AppConstants.XA_PERM_TYPE_EXECUTE; // XA_PERM_TYPE_EXECUTE + } + if ("Select".equalsIgnoreCase(label)) { + return AppConstants.XA_PERM_TYPE_SELECT; // XA_PERM_TYPE_SELECT + } + if ("Update".equalsIgnoreCase(label)) { + return AppConstants.XA_PERM_TYPE_UPDATE; // XA_PERM_TYPE_UPDATE + } + if ("Drop".equalsIgnoreCase(label)) { + return AppConstants.XA_PERM_TYPE_DROP; // XA_PERM_TYPE_DROP + } + if ("Alter".equalsIgnoreCase(label)) { + return AppConstants.XA_PERM_TYPE_ALTER; // XA_PERM_TYPE_ALTER + } + if ("Index".equalsIgnoreCase(label)) { + return AppConstants.XA_PERM_TYPE_INDEX; // XA_PERM_TYPE_INDEX + } + if ("Lock".equalsIgnoreCase(label)) { + return AppConstants.XA_PERM_TYPE_LOCK; // XA_PERM_TYPE_LOCK + } + if ("All".equalsIgnoreCase(label)) { + return AppConstants.XA_PERM_TYPE_ALL; // XA_PERM_TYPE_ALL + } + if ("Allow".equalsIgnoreCase(label)) { + return AppConstants.XA_PERM_TYPE_ALLOW; //XA_PERM_TYPE_ALLOW + } + if ("submitTopology".equalsIgnoreCase(label)) { + return AppConstants.XA_PERM_TYPE_SUBMIT_TOPOLOGY; //XA_PERM_TYPE_SUBMIT_TOPOLOGY + } + if ("fileUpload".equalsIgnoreCase(label)) { + return AppConstants.XA_PERM_TYPE_FILE_UPLOAD; //XA_PERM_TYPE_FILE_UPLOAD + } + if ("getNimbusConf".equalsIgnoreCase(label)) { + return AppConstants.XA_PERM_TYPE_GET_NIMBUS; //XA_PERM_TYPE_GET_NIMBUS + } + if ("getClusterInfo".equalsIgnoreCase(label)) { + return AppConstants.XA_PERM_TYPE_GET_CLUSTER_INFO; //XA_PERM_TYPE_GET_CLUSTER_INFO + } + if ("fileDownload".equalsIgnoreCase(label)) { + return AppConstants.XA_PERM_TYPE_FILE_DOWNLOAD; //XA_PERM_TYPE_FILE_DOWNLOAD + } + if ("killTopology".equalsIgnoreCase(label)) { + return AppConstants.XA_PERM_TYPE_KILL_TOPOLOGY; //XA_PERM_TYPE_KILL_TOPOLOGY + } + if ("rebalance".equalsIgnoreCase(label)) { + return AppConstants.XA_PERM_TYPE_REBALANCE; //XA_PERM_TYPE_REBALANCE + } + if ("activate".equalsIgnoreCase(label)) { + return AppConstants.XA_PERM_TYPE_ACTIVATE; //XA_PERM_TYPE_ACTIVATE + } + if ("deactivate".equalsIgnoreCase(label)) { + return AppConstants.XA_PERM_TYPE_DEACTIVATE; //XA_PERM_TYPE_DEACTIVATE + } + if ("getTopologyConf".equalsIgnoreCase(label)) { + return AppConstants.XA_PERM_TYPE_GET_TOPOLOGY_CONF; //XA_PERM_TYPE_GET_TOPOLOGY_CONF + } + if ("getTopology".equalsIgnoreCase(label)) { + return AppConstants.XA_PERM_TYPE_GET_TOPOLOGY; //XA_PERM_TYPE_GET_TOPOLOGY + } + if ("getUserTopology".equalsIgnoreCase(label)) { + return AppConstants.XA_PERM_TYPE_GET_USER_TOPOLOGY; //XA_PERM_TYPE_GET_USER_TOPOLOGY + } + if ("getTopologyInfo".equalsIgnoreCase(label)) { + return AppConstants.XA_PERM_TYPE_GET_TOPOLOGY_INFO; //XA_PERM_TYPE_GET_TOPOLOGY_INFO + } + if ("uploadNewCredentials".equalsIgnoreCase(label)) { + return AppConstants.XA_PERM_TYPE_UPLOAD_NEW_CREDENTIAL; //XA_PERM_TYPE_UPLOAD_NEW_CREDENTIAL + } + if (label.equalsIgnoreCase("repladmin")) { + return AppConstants.XA_PERM_TYPE_REPLADMIN; //XA_PERM_TYPE_REPLADMIN + } + if (label.equalsIgnoreCase("serviceadmin")) { + return AppConstants.XA_PERM_TYPE_SERVICEADMIN; //XA_PERM_TYPE_SERVICEADMIN + } + if ("tempudfadmin".equalsIgnoreCase(label)) { + return AppConstants.XA_PERM_TYPE_TEMPUDFADMIN; //XA_PERM_TYPE_TEMPUDFADMIN + } + if ("idempotent_write".equalsIgnoreCase(label)) { + return AppConstants.XA_PERM_TYPE_IDEMPOTENT_WRITE; //XA_PERM_TYPE_IDEMPOTENT_WRITE + } + if ("describe_configs".equalsIgnoreCase(label)) { + return AppConstants.XA_PERM_TYPE_DESCRIBE_CONFIGS; //XA_PERM_TYPE_DESCRIBE_CONFIGS + } + if ("alter_configs".equalsIgnoreCase(label)) { + return AppConstants.XA_PERM_TYPE_ALTER_CONFIGS; //XA_PERM_TYPE_ALTER_CONFIGS + } + if ("cluster_action".equalsIgnoreCase(label)) { + return AppConstants.XA_PERM_TYPE_CLUSTER_ACTION; //XA_PERM_TYPE_CLUSTER_ACTION + } + return 0; + } - static public int getEnumFor_PolicyType(String label) { - if (label == null) { - return 0; - } - if ("Inclusion".equalsIgnoreCase(label)) { - return AppConstants.POLICY_INCLUSION; // POLICY_INCLUSION - } - if ("Exclusion".equalsIgnoreCase(label)) { - return AppConstants.POLICY_EXCLUSION; // POLICY_EXCLUSION - } - return 0; - } + public static int getEnumFor_PolicyType(String label) { + if (label == null) { + return 0; + } + if ("Inclusion".equalsIgnoreCase(label)) { + return AppConstants.POLICY_INCLUSION; // POLICY_INCLUSION + } + if ("Exclusion".equalsIgnoreCase(label)) { + 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 - } - if ("POSTGRES".equalsIgnoreCase(label)) { - return DB_FLAVOR_POSTGRES; // DB_FLAVOR_POSTGRES - } - if ("MSSQL".equalsIgnoreCase(label)) { - return DB_FLAVOR_SQLSERVER; // DB_FLAVOR_MSSQL - } - if ("SQLA".equalsIgnoreCase(label)) { - return DB_FLAVOR_SQLANYWHERE; // DB_FLAVOR_SQLANYWHERE - } - 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 - } - if (elementValue == DB_FLAVOR_POSTGRES) { - return "POSTGRES"; // POSTGRES - } - if (elementValue == DB_FLAVOR_SQLSERVER) { - return "MSSQL"; // MSSQL - } - if (elementValue == DB_FLAVOR_SQLANYWHERE) { - return "SQLA"; // SQLA - } - return null; - } + public static 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 + } + if ("POSTGRES".equalsIgnoreCase(label)) { + return DB_FLAVOR_POSTGRES; // DB_FLAVOR_POSTGRES + } + if ("MSSQL".equalsIgnoreCase(label)) { + return DB_FLAVOR_SQLSERVER; // DB_FLAVOR_MSSQL + } + if ("SQLA".equalsIgnoreCase(label)) { + return DB_FLAVOR_SQLANYWHERE; // DB_FLAVOR_SQLANYWHERE + } + return DB_FLAVOR_UNKNOWN; + } + public static 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 + } + if (elementValue == DB_FLAVOR_POSTGRES) { + return "POSTGRES"; // POSTGRES + } + if (elementValue == DB_FLAVOR_SQLSERVER) { + return "MSSQL"; // MSSQL + } + if (elementValue == DB_FLAVOR_SQLANYWHERE) { + return "SQLA"; // SQLA + } + return null; + } } - 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 index dd7b73e020..52dff6c6de 100644 --- a/security-admin/src/main/java/org/apache/ranger/common/ContextUtil.java +++ b/security-admin/src/main/java/org/apache/ranger/common/ContextUtil.java @@ -17,78 +17,91 @@ * under the License. */ - package org.apache.ranger.common; +package org.apache.ranger.common; import org.apache.ranger.security.context.RangerAdminOpContext; import org.apache.ranger.security.context.RangerContextHolder; import org.apache.ranger.security.context.RangerSecurityContext; public class ContextUtil { + /** + * Singleton class + */ + public ContextUtil() { + } - /** - * Singleton class - */ - public ContextUtil() { - } - - public static Long getCurrentUserId() { - RangerSecurityContext context = RangerContextHolder.getSecurityContext(); - if (context != null) { - UserSessionBase userSession = context.getUserSession(); - if (userSession != null) { - return userSession.getUserId(); - } - } - return null; - } - - public static String getCurrentUserPublicName() { - RangerSecurityContext context = RangerContextHolder.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; - RangerSecurityContext context = RangerContextHolder.getSecurityContext(); - if (context != null) { - userSession = context.getUserSession(); - } - return userSession; - } - - public static RequestContext getCurrentRequestContext() { - RangerSecurityContext context = RangerContextHolder.getSecurityContext(); - if (context != null) { - return context.getRequestContext(); - } - return null; - } - - public static String getCurrentUserLoginId() { - RangerSecurityContext context = RangerContextHolder.getSecurityContext(); - if (context != null) { - UserSessionBase userSession = context.getUserSession(); - if (userSession != null) { - return userSession.getLoginId(); - } - } - return null; - } - - public static boolean isBulkModeContext() { - RangerAdminOpContext context = RangerContextHolder.getOpContext(); - boolean bulkMode = false; - if (context != null) { - bulkMode = context.isBulkModeContext(); - } - return bulkMode; - } + public static Long getCurrentUserId() { + RangerSecurityContext context = RangerContextHolder.getSecurityContext(); + if (context != null) { + UserSessionBase userSession = context.getUserSession(); + + if (userSession != null) { + return userSession.getUserId(); + } + } + + return null; + } + + public static String getCurrentUserPublicName() { + RangerSecurityContext context = RangerContextHolder.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; + RangerSecurityContext context = RangerContextHolder.getSecurityContext(); + + if (context != null) { + userSession = context.getUserSession(); + } + + return userSession; + } + + public static RequestContext getCurrentRequestContext() { + RangerSecurityContext context = RangerContextHolder.getSecurityContext(); + + if (context != null) { + return context.getRequestContext(); + } + + return null; + } + + public static String getCurrentUserLoginId() { + RangerSecurityContext context = RangerContextHolder.getSecurityContext(); + + if (context != null) { + UserSessionBase userSession = context.getUserSession(); + + if (userSession != null) { + return userSession.getLoginId(); + } + } + + return null; + } + + public static boolean isBulkModeContext() { + RangerAdminOpContext context = RangerContextHolder.getOpContext(); + boolean bulkMode = false; + + if (context != null) { + bulkMode = context.isBulkModeContext(); + } + + return bulkMode; + } } 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 index 7babd8040a..834b0c9f0a 100644 --- a/security-admin/src/main/java/org/apache/ranger/common/DateUtil.java +++ b/security-admin/src/main/java/org/apache/ranger/common/DateUtil.java @@ -17,115 +17,131 @@ * under the License. */ - /** +/** * */ package org.apache.ranger.common; + +import org.apache.commons.lang.StringUtils; +import org.springframework.stereotype.Component; + import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.TimeZone; -import org.apache.commons.lang.StringUtils; -import org.springframework.stereotype.Component; - - @Component public class DateUtil { - private static final TimeZone gmtTimeZone = TimeZone.getTimeZone("GMT+0"); + public static String dateToString(Date date, String dateFromat) { + SimpleDateFormat formatter = new SimpleDateFormat(dateFromat); + + return formatter.format(date); + } + + 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; + } + } + + public static Date getLocalDateForUTCDate(Date date) { + Calendar local = Calendar.getInstance(); + int offset = local.getTimeZone().getOffset(local.getTimeInMillis()); + GregorianCalendar utc = new GregorianCalendar(); + + utc.setTimeInMillis(date.getTime()); + utc.add(Calendar.MILLISECOND, offset); + + return utc.getTime(); + } + + public static Date stringToDate(String dateString, String dateFromat) { + Date date = null; + + if (!StringUtils.isEmpty(dateString) && !StringUtils.isEmpty(dateFromat)) { + try { + SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFromat); + + date = simpleDateFormat.parse(dateString); + } catch (Exception ex) { + return null; + } + } + + return date; + } + public Date getDateFromNow(int days) { - return getDateFromNow(days, 0, 0); + 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(); + 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; - } - } - public static Date getLocalDateForUTCDate(Date date) { - Calendar local = Calendar.getInstance(); - int offset = local.getTimeZone().getOffset(local.getTimeInMillis()); - GregorianCalendar utc = new GregorianCalendar(); - utc.setTimeInMillis(date.getTime()); - utc.add(Calendar.MILLISECOND, offset); - return utc.getTime(); - } - - public static Date stringToDate(String dateString, String dateFromat){ - SimpleDateFormat simpleDateFormat = null; - Date date = null; - if(!StringUtils.isEmpty(dateString) && !StringUtils.isEmpty(dateFromat)){ - try{ - simpleDateFormat = new SimpleDateFormat(dateFromat); - date = simpleDateFormat.parse(dateString); - }catch(Exception ex){ - return null; - } - } - return date; - } + 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 null; + } + + long t = date.getTime(); + + return new Date(t + (mins * 60000L)); + } } 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 index a6c8fb78bd..da3c78a1ac 100644 --- a/security-admin/src/main/java/org/apache/ranger/common/ErrorMessageUtil.java +++ b/security-admin/src/main/java/org/apache/ranger/common/ErrorMessageUtil.java @@ -17,45 +17,42 @@ * under the License. */ - /** +/** * */ package org.apache.ranger.common; +import org.springframework.beans.BeansException; +import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; +import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer; + 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 messageMap; private ErrorMessageUtil() { + } + public static String getMessage(String key) { + return messageMap.get(key); } @Override - protected void processProperties( - ConfigurableListableBeanFactory beanFactory, Properties props) - throws BeansException { - super.processProperties(beanFactory, props); - - messageMap = new HashMap(); - Set keySet = props.keySet(); - - for (Object key : keySet) { - String keyStr = key.toString(); - messageMap.put(keyStr, props.getProperty(keyStr)); - } - } + protected void processProperties(ConfigurableListableBeanFactory beanFactory, Properties props) throws BeansException { + super.processProperties(beanFactory, props); + messageMap = new HashMap<>(); - public static String getMessage(String key) { - return messageMap.get(key); - } + Set keySet = props.keySet(); + + for (Object key : keySet) { + String keyStr = key.toString(); -} \ No newline at end of file + messageMap.put(keyStr, props.getProperty(keyStr)); + } + } +} 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 index 2554a6c3b7..cbc544e785 100644 --- a/security-admin/src/main/java/org/apache/ranger/common/GUIDUtil.java +++ b/security-admin/src/main/java/org/apache/ranger/common/GUIDUtil.java @@ -19,23 +19,22 @@ package org.apache.ranger.common; -import java.io.Serializable; -import java.util.UUID; - import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Service; +import java.io.Serializable; +import java.util.UUID; + @Service @Scope("singleton") public class GUIDUtil implements Serializable { - - private static final long serialVersionUID = -7284237762948427019L; + private static final long serialVersionUID = -7284237762948427019L; - public String genGUID() { - return UUID.randomUUID().toString(); - } + public String genGUID() { + return UUID.randomUUID().toString(); + } - public long genLong() { - return UUID.randomUUID().getMostSignificantBits(); - } + public long genLong() { + return UUID.randomUUID().getMostSignificantBits(); + } } 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 index b4c632cfc9..d06500b348 100644 --- a/security-admin/src/main/java/org/apache/ranger/common/HTTPUtil.java +++ b/security-admin/src/main/java/org/apache/ranger/common/HTTPUtil.java @@ -17,47 +17,42 @@ * under the License. */ - /** +/** * */ package org.apache.ranger.common; -import javax.servlet.http.HttpServletRequest; - import org.springframework.stereotype.Component; +import javax.servlet.http.HttpServletRequest; + @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 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)); - + return getDeviceType(httpRequest.getHeader(USER_AGENT)); } public int getDeviceType(String userAgent) { - if (userAgent == null) { - return RangerCommonEnums.DEVICE_UNKNOWN; - } - - if (userAgent.contains(IPHONE)) { - return RangerCommonEnums.DEVICE_IPHONE; - } else if (userAgent.contains(IPAD)) { - return RangerCommonEnums.DEVICE_IPAD; - } else if (userAgent.contains(IPOD)) { - return RangerCommonEnums.DEVICE_IPOD; - } else if (userAgent.contains(ANDROID)) { - return RangerCommonEnums.DEVICE_ANDROID; - } else { - return RangerCommonEnums.DEVICE_BROWSER; - } + if (userAgent == null) { + return RangerCommonEnums.DEVICE_UNKNOWN; + } + + if (userAgent.contains(IPHONE)) { + return RangerCommonEnums.DEVICE_IPHONE; + } else if (userAgent.contains(IPAD)) { + return RangerCommonEnums.DEVICE_IPAD; + } else if (userAgent.contains(IPOD)) { + return RangerCommonEnums.DEVICE_IPOD; + } else if (userAgent.contains(ANDROID)) { + return RangerCommonEnums.DEVICE_ANDROID; + } else { + return RangerCommonEnums.DEVICE_BROWSER; + } } - - } 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 index 5b53139eda..4c4264e845 100644 --- a/security-admin/src/main/java/org/apache/ranger/common/JSONUtil.java +++ b/security-admin/src/main/java/org/apache/ranger/common/JSONUtil.java @@ -17,98 +17,74 @@ * under the License. */ - /** - * - */ package org.apache.ranger.common; -import java.io.File; -import java.io.IOException; -import java.io.Serializable; -import java.util.List; -import java.util.Map; - -import com.fasterxml.jackson.core.JsonGenerationException; import com.fasterxml.jackson.core.util.DefaultPrettyPrinter; -import com.fasterxml.jackson.databind.JsonMappingException; import org.apache.ranger.common.view.ViewBaseBean; import org.apache.ranger.plugin.util.JsonUtilsV2; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; +import java.io.File; +import java.io.IOException; +import java.io.Serializable; +import java.util.List; +import java.util.Map; + @Component public class JSONUtil { - - @Autowired - RESTErrorUtil restErrorUtil; - - public File writeJsonToFile(ViewBaseBean viewBean, String fileName) - throws JsonGenerationException, JsonMappingException, IOException { - - if (fileName.length() < 3) { - fileName = "file_" + fileName; - } - - File file = File.createTempFile(fileName, ".json"); - JsonUtilsV2.getMapper().writer(new DefaultPrettyPrinter()).writeValue(file, viewBean); //defaultPrettyPrintingWriter().writeValue(file, viewBean); - - return file; - } - - public Map jsonToMap(String jsonStr) { - - try { - return JsonUtilsV2.jsonToMap(jsonStr); - - } catch (Exception e) { - throw restErrorUtil.createRESTException( - "Invalid input data: " + e.getMessage(), - MessageEnums.INVALID_INPUT_DATA); - } - - } - - public String readMapToString(Map map) { - - try { - return JsonUtilsV2.mapToJson(map); - } catch (Exception e) { - throw restErrorUtil.createRESTException( - "Invalid input data: " + e.getMessage(), - MessageEnums.INVALID_INPUT_DATA); - } - } - - public String readListToString(List list) { - - try { - return JsonUtilsV2.listToJson(list); - } catch (Exception e) { - throw restErrorUtil.createRESTException( - "Invalid input data: " + e.getMessage(), - MessageEnums.INVALID_INPUT_DATA); - } - } - - public String writeObjectAsString(Serializable obj) { - - try { - return JsonUtilsV2.objToJson(obj); - } catch (Exception e) { - throw restErrorUtil.createRESTException( - "Invalid input data: " + e.getMessage(), - MessageEnums.INVALID_INPUT_DATA); - } - } - - public T writeJsonToJavaObject(String json, Class tClass) { - - try { - return JsonUtilsV2.jsonToObj(json, tClass); - } catch (Exception e) { - throw restErrorUtil.createRESTException("Invalid input data: " + e.getMessage(), - MessageEnums.INVALID_INPUT_DATA); - } - } - -} \ No newline at end of file + @Autowired + RESTErrorUtil restErrorUtil; + + public File writeJsonToFile(ViewBaseBean viewBean, String fileName) throws IOException { + if (fileName.length() < 3) { + fileName = "file_" + fileName; + } + + File file = File.createTempFile(fileName, ".json"); + + JsonUtilsV2.getMapper().writer(new DefaultPrettyPrinter()).writeValue(file, viewBean); + + return file; + } + + public Map jsonToMap(String jsonStr) { + try { + return JsonUtilsV2.jsonToMap(jsonStr); + } catch (Exception e) { + throw restErrorUtil.createRESTException("Invalid input data: " + e.getMessage(), MessageEnums.INVALID_INPUT_DATA); + } + } + + public String readMapToString(Map map) { + try { + return JsonUtilsV2.mapToJson(map); + } catch (Exception e) { + throw restErrorUtil.createRESTException("Invalid input data: " + e.getMessage(), MessageEnums.INVALID_INPUT_DATA); + } + } + + public String readListToString(List list) { + try { + return JsonUtilsV2.listToJson(list); + } catch (Exception e) { + throw restErrorUtil.createRESTException("Invalid input data: " + e.getMessage(), MessageEnums.INVALID_INPUT_DATA); + } + } + + public String writeObjectAsString(Serializable obj) { + try { + return JsonUtilsV2.objToJson(obj); + } catch (Exception e) { + throw restErrorUtil.createRESTException("Invalid input data: " + e.getMessage(), MessageEnums.INVALID_INPUT_DATA); + } + } + + public T writeJsonToJavaObject(String json, Class tClass) { + try { + return JsonUtilsV2.jsonToObj(json, tClass); + } catch (Exception e) { + throw restErrorUtil.createRESTException("Invalid input data: " + e.getMessage(), MessageEnums.INVALID_INPUT_DATA); + } + } +} diff --git a/security-admin/src/main/java/org/apache/ranger/common/MapUtil.java b/security-admin/src/main/java/org/apache/ranger/common/MapUtil.java index 59d733358b..345af927bd 100644 --- a/security-admin/src/main/java/org/apache/ranger/common/MapUtil.java +++ b/security-admin/src/main/java/org/apache/ranger/common/MapUtil.java @@ -17,42 +17,46 @@ * under the License. */ - /** +/** * */ package org.apache.ranger.common; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Service; + import java.io.Serializable; import java.util.HashMap; import java.util.Map; -import org.springframework.context.annotation.Scope; -import org.springframework.stereotype.Service; - @Service @Scope("singleton") -public class MapUtil implements Serializable{ - static Map policyExportAuditSyncStatusMessageMap=new HashMap(); +public class MapUtil implements Serializable { + static Map policyExportAuditSyncStatusMessageMap = new HashMap<>(); public static void init() { - policyExportAuditSyncStatusMessageMap=new HashMap(); - policyExportAuditSyncStatusMessageMap.put(Integer.valueOf(200), "Policies synced to plugin"); - policyExportAuditSyncStatusMessageMap.put(Integer.valueOf(202), "Error syncing policies"); - policyExportAuditSyncStatusMessageMap.put(Integer.valueOf(400), "Error syncing policies"); - policyExportAuditSyncStatusMessageMap.put(Integer.valueOf(401), "Bad Credentials"); - policyExportAuditSyncStatusMessageMap.put(Integer.valueOf(403), "Error syncing policies"); - policyExportAuditSyncStatusMessageMap.put(Integer.valueOf(404), "Error syncing policies"); - policyExportAuditSyncStatusMessageMap.put(Integer.valueOf(500), "Error syncing policies"); + policyExportAuditSyncStatusMessageMap = new HashMap<>(); + + policyExportAuditSyncStatusMessageMap.put(200, "Policies synced to plugin"); + policyExportAuditSyncStatusMessageMap.put(202, "Error syncing policies"); + policyExportAuditSyncStatusMessageMap.put(400, "Error syncing policies"); + policyExportAuditSyncStatusMessageMap.put(401, "Bad Credentials"); + policyExportAuditSyncStatusMessageMap.put(403, "Error syncing policies"); + policyExportAuditSyncStatusMessageMap.put(404, "Error syncing policies"); + policyExportAuditSyncStatusMessageMap.put(500, "Error syncing policies"); } public static String getPolicyExportAuditSyncStatus(int key) { - String status=""; - if(policyExportAuditSyncStatusMessageMap==null || policyExportAuditSyncStatusMessageMap.isEmpty()){ - init(); - } - if(policyExportAuditSyncStatusMessageMap!=null && policyExportAuditSyncStatusMessageMap.containsKey(key)){ - status=policyExportAuditSyncStatusMessageMap.get(key); - } - return status; + String status = ""; + + if (policyExportAuditSyncStatusMessageMap == null || policyExportAuditSyncStatusMessageMap.isEmpty()) { + init(); + } + + if (policyExportAuditSyncStatusMessageMap != null && policyExportAuditSyncStatusMessageMap.containsKey(key)) { + status = policyExportAuditSyncStatusMessageMap.get(key); + } + + return status; } -} \ No newline at end of file +} 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 index 0ad1ee3820..a23838725d 100644 --- a/security-admin/src/main/java/org/apache/ranger/common/MessageEnums.java +++ b/security-admin/src/main/java/org/apache/ranger/common/MessageEnums.java @@ -17,21 +17,19 @@ * under the License. */ - package org.apache.ranger.common; +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_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"), + 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_DELETE_OBJECT("xa.error.delete_object", "Error deleting object"), @@ -39,34 +37,34 @@ public enum MessageEnums { OPER_NO_EXPORT("xa.error.oper_no_export", "repository is disabled"), // Common Validations - INVALID_PASSWORD( "xa.validation.invalid_password", "Invalid password"), + 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; + final String rbKey; + final String messageDesc; MessageEnums(String rbKey, String messageDesc) { - this.rbKey = rbKey; - this.messageDesc = 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; + 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; + VXMessage msg = new VXMessage(); + msg.setName(this.toString()); + msg.setRbKey(rbKey); + msg.setMessage(messageDesc); + msg.setObjectId(objectId); + msg.setFieldName(fieldName); + return msg; } } 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 index 2a5d37ca6e..ff50cc4d39 100644 --- a/security-admin/src/main/java/org/apache/ranger/common/MyCallBack.java +++ b/security-admin/src/main/java/org/apache/ranger/common/MyCallBack.java @@ -17,12 +17,11 @@ * under the License. */ - /** +/** * */ package org.apache.ranger.common; - public interface MyCallBack { /** * Make sure to add @Transactional annotation to the implementation method. 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 index 0ff9a95e66..b9a673eece 100644 --- a/security-admin/src/main/java/org/apache/ranger/common/PropertiesUtil.java +++ b/security-admin/src/main/java/org/apache/ranger/common/PropertiesUtil.java @@ -17,22 +17,11 @@ * under the License. */ - /** +/** * */ package org.apache.ranger.common; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.security.KeyStore; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Properties; -import java.util.Set; - import org.apache.commons.lang.StringUtils; import org.apache.ranger.biz.RangerBizUtil; import org.apache.ranger.credentialapi.CredentialReader; @@ -43,405 +32,498 @@ import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer; - +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.security.KeyStore; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.Set; public class PropertiesUtil extends PropertyPlaceholderConfigurer { - private static final Logger LOG = LoggerFactory.getLogger(PropertiesUtil.class); + private static final Logger LOG = LoggerFactory.getLogger(PropertiesUtil.class); - private static Map propertiesMap = new HashMap<>(); - protected List xmlPropertyConfigurer = new ArrayList<>(); + private static final Map propertiesMap = new HashMap<>(); + protected List xmlPropertyConfigurer = new ArrayList<>(); private PropertiesUtil() { - - } - - @Override - protected void processProperties( - ConfigurableListableBeanFactory beanFactory, Properties props) - throws BeansException { - - // First let's add the system properties - Set 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()); - } - - String storeType = propertiesMap.get("ranger.keystore.file.type"); - // update system trust store path with custom trust store. - if (propertiesMap!=null && propertiesMap.containsKey("ranger.truststore.file")) { - if(!StringUtils.isEmpty(propertiesMap.get("ranger.truststore.file"))){ - System.setProperty("javax.net.ssl.trustStore", propertiesMap.get("ranger.truststore.file")); - System.setProperty("javax.net.ssl.trustStoreType", KeyStore.getDefaultType()); - Path trustStoreFile = Paths.get(propertiesMap.get("ranger.truststore.file")); - if (!Files.exists(trustStoreFile) || !Files.isReadable(trustStoreFile)) { - LOG.debug("Could not find or read truststore file '"+propertiesMap.get("ranger.truststore.file")+"'"); - }else{ - if(propertiesMap!=null && propertiesMap.containsKey("ranger.credential.provider.path")){ - String path=propertiesMap.get("ranger.credential.provider.path"); - String trustStoreAlias=getProperty("ranger.truststore.alias","trustStoreAlias"); - if(path!=null && trustStoreAlias!=null){ - String trustStorePassword=CredentialReader.getDecryptedString(path.trim(), trustStoreAlias.trim(), storeType); - if(trustStorePassword!=null&& !trustStorePassword.trim().isEmpty() && !trustStorePassword.trim().equalsIgnoreCase("none")){ - propertiesMap.put("ranger.truststore.password", trustStorePassword); - props.put("ranger.truststore.password", trustStorePassword); - }else{ - LOG.info("trustStorePassword password not applied; clear text password shall be applicable"); - } - } - } - } - } - System.setProperty("javax.net.ssl.trustStorePassword", propertiesMap.get("ranger.truststore.password")); - } - - // update system key store path with custom key store. - if (propertiesMap!=null && propertiesMap.containsKey("ranger.keystore.file")) { - if(!StringUtils.isEmpty(propertiesMap.get("ranger.keystore.file"))){ - System.setProperty("javax.net.ssl.keyStore", propertiesMap.get("ranger.keystore.file")); - System.setProperty("javax.net.ssl.keyStoreType", KeyStore.getDefaultType()); - Path keyStoreFile = Paths.get(propertiesMap.get("ranger.keystore.file")); - if (!Files.exists(keyStoreFile) || !Files.isReadable(keyStoreFile)) { - LOG.debug("Could not find or read keystore file '"+propertiesMap.get("ranger.keystore.file")+"'"); - }else{ - if(propertiesMap!=null && propertiesMap.containsKey("ranger.credential.provider.path")){ - String path=propertiesMap.get("ranger.credential.provider.path"); - String keyStoreAlias=getProperty("ranger.keystore.alias","keyStoreAlias"); - if(path!=null && keyStoreAlias!=null){ - String keyStorePassword=CredentialReader.getDecryptedString(path.trim(), keyStoreAlias.trim(), storeType); - if(keyStorePassword!=null&& !keyStorePassword.trim().isEmpty() && !keyStorePassword.trim().equalsIgnoreCase("none")){ - propertiesMap.put("ranger.keystore.password", keyStorePassword); - props.put("ranger.keystore.password", keyStorePassword); - }else{ - LOG.info("keyStorePassword password not applied; clear text password shall be applicable"); - } - } - } - } - } - System.setProperty("javax.net.ssl.keyStorePassword", propertiesMap.get("ranger.keystore.password")); - } - - //update unixauth keystore and truststore credentials - if(propertiesMap!=null && propertiesMap.containsKey("ranger.credential.provider.path")){ - String path=propertiesMap.get("ranger.credential.provider.path"); - if(path!=null){ - String unixAuthKeyStoreAlias=getProperty("ranger.unixauth.keystore.alias","unixAuthKeyStoreAlias"); - if(unixAuthKeyStoreAlias!=null){ - String unixAuthKeyStorePass=CredentialReader.getDecryptedString(path.trim(),unixAuthKeyStoreAlias.trim(), storeType); - if(unixAuthKeyStorePass!=null&& !unixAuthKeyStorePass.trim().isEmpty() &&!unixAuthKeyStorePass.trim().equalsIgnoreCase("none")){ - propertiesMap.put("ranger.unixauth.keystore.password", unixAuthKeyStorePass); - props.put("ranger.unixauth.keystore.password", unixAuthKeyStorePass); - }else{ - LOG.info("unixauth keystore password not applied; clear text password shall be applicable"); - } - } - // - String unixAuthTrustStoreAlias=getProperty("ranger.unixauth.truststore.alias","unixAuthTrustStoreAlias"); - if(unixAuthTrustStoreAlias!=null){ - String unixAuthTrustStorePass=CredentialReader.getDecryptedString(path.trim(),unixAuthTrustStoreAlias.trim(), storeType); - if(unixAuthTrustStorePass!=null&& !unixAuthTrustStorePass.trim().isEmpty() &&!unixAuthTrustStorePass.trim().equalsIgnoreCase("none")){ - propertiesMap.put("ranger.unixauth.truststore.password", unixAuthTrustStorePass); - props.put("ranger.unixauth.truststore.password", unixAuthTrustStorePass); - }else{ - LOG.info("unixauth truststore password not applied; clear text password shall be applicable"); - } - } - } - } - - //update credential from keystore - if(propertiesMap!=null && propertiesMap.containsKey("ranger.credential.provider.path") && propertiesMap.containsKey("ranger.jpa.jdbc.credential.alias")){ - String path=propertiesMap.get("ranger.credential.provider.path"); - String alias=propertiesMap.get("ranger.jpa.jdbc.credential.alias"); - if(path!=null && alias!=null){ - String xaDBPassword=CredentialReader.getDecryptedString(path.trim(),alias.trim(), storeType); - if(xaDBPassword!=null&& !xaDBPassword.trim().isEmpty() && - !"none".equalsIgnoreCase(xaDBPassword.trim())){ - propertiesMap.put("ranger.jpa.jdbc.password", xaDBPassword); - props.put("ranger.jpa.jdbc.password", xaDBPassword); - }else{ - LOG.info("Credential keystore password not applied for Ranger DB; clear text password shall be applicable"); - } - } - } - if(propertiesMap!=null && propertiesMap.containsKey("ranger.credential.provider.path") && propertiesMap.containsKey("ranger.jpa.audit.jdbc.credential.alias")){ - String path=propertiesMap.get("ranger.credential.provider.path"); - String alias=propertiesMap.get("ranger.jpa.audit.jdbc.credential.alias"); - if(path!=null && alias!=null){ - String auditDBPassword=CredentialReader.getDecryptedString(path.trim(), alias.trim(), storeType); - if(auditDBPassword!=null&& !auditDBPassword.trim().isEmpty() && - !"none".equalsIgnoreCase(auditDBPassword.trim())){ - propertiesMap.put("ranger.jpa.audit.jdbc.password", auditDBPassword); - props.put("ranger.jpa.audit.jdbc.password", auditDBPassword); - }else{ - LOG.info("Credential keystore password not applied for Audit DB; clear text password shall be applicable"); - } - } - } - if(propertiesMap!=null && propertiesMap.containsKey("ranger.authentication.method")){ - String authenticationMethod=propertiesMap.get("ranger.authentication.method"); - if(authenticationMethod!=null && ("ACTIVE_DIRECTORY".equalsIgnoreCase(authenticationMethod)||"AD".equalsIgnoreCase(authenticationMethod))){ - if(propertiesMap!=null && propertiesMap.containsKey("ranger.credential.provider.path") && propertiesMap.containsKey("ranger.ldap.ad.binddn.credential.alias")){ - String path=propertiesMap.get("ranger.credential.provider.path"); - String alias=propertiesMap.get("ranger.ldap.ad.binddn.credential.alias"); - if(path!=null && alias!=null){ - String bindDNPassword=CredentialReader.getDecryptedString(path.trim(), alias.trim(), storeType); - if(bindDNPassword!=null&& !bindDNPassword.trim().isEmpty() && - !"none".equalsIgnoreCase(bindDNPassword.trim())){ - propertiesMap.put("ranger.ldap.ad.bind.password", bindDNPassword); - props.put("ranger.ldap.ad.bind.password", bindDNPassword); - }else{ - LOG.info("Credential keystore password not applied for AD Bind DN; clear text password shall be applicable"); - } - } - } - } - } - if(propertiesMap!=null && propertiesMap.containsKey("ranger.authentication.method")){ - String authenticationMethod=propertiesMap.get("ranger.authentication.method"); - if(authenticationMethod!=null && ("LDAP".equalsIgnoreCase(authenticationMethod))){ - if(propertiesMap!=null && propertiesMap.containsKey("ranger.credential.provider.path") && propertiesMap.containsKey("ranger.ldap.binddn.credential.alias")){ - String path=propertiesMap.get("ranger.credential.provider.path"); - String alias=propertiesMap.get("ranger.ldap.binddn.credential.alias"); - if(path!=null && alias!=null){ - String bindDNPassword=CredentialReader.getDecryptedString(path.trim(), alias.trim(), storeType); - if(bindDNPassword!=null&& !bindDNPassword.trim().isEmpty() && - !"none".equalsIgnoreCase(bindDNPassword.trim())){ - propertiesMap.put("ranger.ldap.bind.password", bindDNPassword); - props.put("ranger.ldap.bind.password", bindDNPassword); - }else{ - LOG.info("Credential keystore password not applied for LDAP Bind DN; clear text password shall be applicable"); - } - } - } - } - } - if(propertiesMap!=null && propertiesMap.containsKey("ranger.audit.source.type")){ - String auditStore=propertiesMap.get("ranger.audit.source.type"); - if(auditStore!=null && ("solr".equalsIgnoreCase(auditStore))){ - if(propertiesMap!=null && propertiesMap.containsKey("ranger.credential.provider.path") && propertiesMap.containsKey("ranger.solr.audit.credential.alias")){ - String path=propertiesMap.get("ranger.credential.provider.path"); - String alias=propertiesMap.get("ranger.solr.audit.credential.alias"); - if(path!=null && alias!=null){ - String solrAuditPassword=CredentialReader.getDecryptedString(path.trim(), alias.trim(), storeType); - if(solrAuditPassword!=null&& !solrAuditPassword.trim().isEmpty() && - !"none".equalsIgnoreCase(solrAuditPassword.trim())){ - propertiesMap.put("ranger.solr.audit.user.password", solrAuditPassword); - props.put("ranger.solr.audit.user.password", solrAuditPassword); - }else{ - LOG.info("Credential keystore password not applied for Solr; clear text password shall be applicable"); - } - } - } - } - } - if(propertiesMap!=null){ - String sha256PasswordUpdateDisable="false"; - if(propertiesMap.containsKey("ranger.sha256Password.update.disable")){ - sha256PasswordUpdateDisable=propertiesMap.get("ranger.sha256Password.update.disable"); - if(sha256PasswordUpdateDisable==null || sha256PasswordUpdateDisable.trim().isEmpty()|| !"true".equalsIgnoreCase(sha256PasswordUpdateDisable)){ - sha256PasswordUpdateDisable="false"; - } - } - propertiesMap.put("ranger.sha256Password.update.disable", sha256PasswordUpdateDisable); - props.put("ranger.sha256Password.update.disable", sha256PasswordUpdateDisable); - } - if(RangerBizUtil.getDBFlavor()==AppConstants.DB_FLAVOR_MYSQL || RangerBizUtil.getDBFlavor()==AppConstants.DB_FLAVOR_POSTGRES){ - if(propertiesMap!=null && propertiesMap.containsKey("ranger.db.ssl.enabled")){ - String db_ssl_enabled=propertiesMap.get("ranger.db.ssl.enabled"); - if(StringUtils.isEmpty(db_ssl_enabled)|| !"true".equalsIgnoreCase(db_ssl_enabled)){ - db_ssl_enabled="false"; - } - db_ssl_enabled=db_ssl_enabled.toLowerCase(); - String ranger_jpa_jdbc_url=propertiesMap.get("ranger.jpa.jdbc.url"); - if("true".equalsIgnoreCase(db_ssl_enabled)){ - String db_ssl_required=propertiesMap.get("ranger.db.ssl.required"); - if(StringUtils.isEmpty(db_ssl_required)|| !"true".equalsIgnoreCase(db_ssl_required)){ - db_ssl_required="false"; - } - db_ssl_required=db_ssl_required.toLowerCase(); - String db_ssl_verifyServerCertificate=propertiesMap.get("ranger.db.ssl.verifyServerCertificate"); - if(StringUtils.isEmpty(db_ssl_verifyServerCertificate)|| !"true".equalsIgnoreCase(db_ssl_verifyServerCertificate)){ - db_ssl_verifyServerCertificate="false"; - } - db_ssl_verifyServerCertificate=db_ssl_verifyServerCertificate.toLowerCase(); - String db_ssl_auth_type=propertiesMap.get("ranger.db.ssl.auth.type"); - if(StringUtils.isEmpty(db_ssl_auth_type)|| !"1-way".equalsIgnoreCase(db_ssl_auth_type)){ - db_ssl_auth_type="2-way"; - } - propertiesMap.put("ranger.db.ssl.enabled", db_ssl_enabled); - props.put("ranger.db.ssl.enabled", db_ssl_enabled); - propertiesMap.put("ranger.db.ssl.required", db_ssl_required); - props.put("ranger.db.ssl.required", db_ssl_required); - propertiesMap.put("ranger.db.ssl.verifyServerCertificate", db_ssl_verifyServerCertificate); - props.put("ranger.db.ssl.verifyServerCertificate", db_ssl_verifyServerCertificate); - propertiesMap.put("ranger.db.ssl.auth.type", db_ssl_auth_type); - props.put("ranger.db.ssl.auth.type", db_ssl_auth_type); - - if(StringUtils.isNotEmpty(ranger_jpa_jdbc_url) && !ranger_jpa_jdbc_url.contains("?")){ - StringBuffer ranger_jpa_jdbc_url_ssl=new StringBuffer(ranger_jpa_jdbc_url); - if (RangerBizUtil.getDBFlavor()==AppConstants.DB_FLAVOR_MYSQL) { - ranger_jpa_jdbc_url_ssl.append("?useSSL="+db_ssl_enabled+"&requireSSL="+db_ssl_required+"&verifyServerCertificate="+db_ssl_verifyServerCertificate); - }else if(RangerBizUtil.getDBFlavor()==AppConstants.DB_FLAVOR_POSTGRES) { - String db_ssl_certificate_file = propertiesMap.get("ranger.db.ssl.certificateFile"); - if(StringUtils.isNotEmpty(db_ssl_certificate_file)) { - ranger_jpa_jdbc_url_ssl.append("?ssl="+db_ssl_enabled+"&sslmode=verify-full"+"&sslrootcert="+db_ssl_certificate_file); - } else if ("true".equalsIgnoreCase(db_ssl_verifyServerCertificate) || "true".equalsIgnoreCase(db_ssl_required)) { - ranger_jpa_jdbc_url_ssl.append("?ssl="+db_ssl_enabled+"&sslmode=verify-full"+"&sslfactory=org.postgresql.ssl.DefaultJavaSSLFactory"); - } else { - ranger_jpa_jdbc_url_ssl.append("?ssl="+db_ssl_enabled); - } - } - propertiesMap.put("ranger.jpa.jdbc.url", ranger_jpa_jdbc_url_ssl.toString()); - } - ranger_jpa_jdbc_url=propertiesMap.get("ranger.jpa.jdbc.url"); - if(StringUtils.isNotEmpty(ranger_jpa_jdbc_url)) { - props.put("ranger.jpa.jdbc.url", ranger_jpa_jdbc_url); - } - LOG.info("ranger.jpa.jdbc.url="+ranger_jpa_jdbc_url); - } else { - String ranger_jpa_jdbc_url_extra_args=""; - if(!StringUtils.isEmpty(ranger_jpa_jdbc_url)) { - if (ranger_jpa_jdbc_url.contains("?")) { - ranger_jpa_jdbc_url_extra_args = ranger_jpa_jdbc_url.substring(ranger_jpa_jdbc_url.indexOf("?")+1); - ranger_jpa_jdbc_url = ranger_jpa_jdbc_url.substring(0, ranger_jpa_jdbc_url.indexOf("?")); - } - if (RangerBizUtil.getDBFlavor()==AppConstants.DB_FLAVOR_MYSQL) { - StringBuilder ranger_jpa_jdbc_url_no_ssl=new StringBuilder(ranger_jpa_jdbc_url); - if (!ranger_jpa_jdbc_url_extra_args.contains("useSSL")) { - ranger_jpa_jdbc_url_no_ssl.append("?useSSL=false"); - } - if (!StringUtils.isEmpty(ranger_jpa_jdbc_url_extra_args) && ranger_jpa_jdbc_url_no_ssl.toString().contains("useSSL")) { - ranger_jpa_jdbc_url_no_ssl.append("&").append(ranger_jpa_jdbc_url_extra_args); - } else if (!StringUtils.isEmpty(ranger_jpa_jdbc_url_extra_args) && !ranger_jpa_jdbc_url_no_ssl.toString().contains("useSSL")) { - ranger_jpa_jdbc_url_no_ssl.append("?").append(ranger_jpa_jdbc_url_extra_args); - } - propertiesMap.put("ranger.jpa.jdbc.url", ranger_jpa_jdbc_url_no_ssl.toString()); - } - ranger_jpa_jdbc_url=propertiesMap.get("ranger.jpa.jdbc.url"); - if(StringUtils.isNotEmpty(ranger_jpa_jdbc_url)) { - props.put("ranger.jpa.jdbc.url", ranger_jpa_jdbc_url); - } - LOG.info("ranger.jpa.jdbc.url="+ranger_jpa_jdbc_url); - } - } - } - } - - if (propertiesMap != null && propertiesMap.containsKey(RangerCommonConstants.PROP_COOKIE_NAME)) { - String cookieName = propertiesMap.get(RangerCommonConstants.PROP_COOKIE_NAME); - if (StringUtils.isBlank(cookieName)) { - cookieName = RangerCommonConstants.DEFAULT_COOKIE_NAME; - } - propertiesMap.put(RangerCommonConstants.PROP_COOKIE_NAME, cookieName); - props.put(RangerCommonConstants.PROP_COOKIE_NAME, cookieName); - } - - keySet = props.keySet(); - for (Object key : keySet) { - String keyStr = key.toString(); - if (LOG.isDebugEnabled()) { - LOG.debug("PropertiesUtil:[" + keyStr + "][" + (keyStr.toLowerCase().contains("pass") ? "********]" : props.get(keyStr)) + "]"); - } - } - - 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; + 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); + 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]; - } + 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 defaultValue; - } - String rtrnVal = propertiesMap.get(key); - if (rtrnVal == null) { - return defaultValue; - } - return Integer.valueOf(rtrnVal); + if (key == null) { + return defaultValue; + } + + String rtrnVal = propertiesMap.get(key); + + if (rtrnVal == null) { + return defaultValue; + } + + return Integer.valueOf(rtrnVal); } public static long getLongProperty(String key, long defaultValue) { - if (key == null) { - return defaultValue; - } - String rtrnVal = propertiesMap.get(key); - if (rtrnVal == null) { - return defaultValue; - } - return Long.valueOf(rtrnVal); + if (key == null) { + return defaultValue; + } + + String rtrnVal = propertiesMap.get(key); + + if (rtrnVal == null) { + return defaultValue; + } + + return Long.parseLong(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); + 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); + if (key == null) { + return defaultValue; + } + + String value = getProperty(key); + + if (value == null) { + return defaultValue; + } + + return Boolean.parseBoolean(value); + } + + public static Map getPropertiesMap() { + return propertiesMap; + } + + public static Properties getProps() { + Properties ret = new Properties(); + + ret.putAll(propertiesMap); + + return ret; + } + + @Override + protected void processProperties(ConfigurableListableBeanFactory beanFactory, Properties props) throws BeansException { + // First let's add the system properties + Set 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()); + } + + String storeType = propertiesMap.get("ranger.keystore.file.type"); + + // update system trust store path with custom trust store. + if (propertiesMap.containsKey("ranger.truststore.file")) { + if (!StringUtils.isEmpty(propertiesMap.get("ranger.truststore.file"))) { + System.setProperty("javax.net.ssl.trustStore", propertiesMap.get("ranger.truststore.file")); + System.setProperty("javax.net.ssl.trustStoreType", KeyStore.getDefaultType()); + + Path trustStoreFile = Paths.get(propertiesMap.get("ranger.truststore.file")); + + if (!Files.exists(trustStoreFile) || !Files.isReadable(trustStoreFile)) { + LOG.debug("Could not find or read truststore file '{}'", propertiesMap.get("ranger.truststore.file")); + } else { + if (propertiesMap.containsKey("ranger.credential.provider.path")) { + String path = propertiesMap.get("ranger.credential.provider.path"); + String trustStoreAlias = getProperty("ranger.truststore.alias", "trustStoreAlias"); + + if (path != null && trustStoreAlias != null) { + String trustStorePassword = CredentialReader.getDecryptedString(path.trim(), trustStoreAlias.trim(), storeType); + + if (trustStorePassword != null && !trustStorePassword.trim().isEmpty() && !trustStorePassword.trim().equalsIgnoreCase("none")) { + propertiesMap.put("ranger.truststore.password", trustStorePassword); + props.put("ranger.truststore.password", trustStorePassword); + } else { + LOG.info("trustStorePassword password not applied; clear text password shall be applicable"); + } + } + } + } + } + + System.setProperty("javax.net.ssl.trustStorePassword", propertiesMap.get("ranger.truststore.password")); + } + + // update system key store path with custom key store. + if (propertiesMap.containsKey("ranger.keystore.file")) { + if (!StringUtils.isEmpty(propertiesMap.get("ranger.keystore.file"))) { + System.setProperty("javax.net.ssl.keyStore", propertiesMap.get("ranger.keystore.file")); + System.setProperty("javax.net.ssl.keyStoreType", KeyStore.getDefaultType()); + + Path keyStoreFile = Paths.get(propertiesMap.get("ranger.keystore.file")); + + if (!Files.exists(keyStoreFile) || !Files.isReadable(keyStoreFile)) { + LOG.debug("Could not find or read keystore file '{}'", propertiesMap.get("ranger.keystore.file")); + } else { + if (propertiesMap.containsKey("ranger.credential.provider.path")) { + String path = propertiesMap.get("ranger.credential.provider.path"); + String keyStoreAlias = getProperty("ranger.keystore.alias", "keyStoreAlias"); + + if (path != null && keyStoreAlias != null) { + String keyStorePassword = CredentialReader.getDecryptedString(path.trim(), keyStoreAlias.trim(), storeType); + + if (keyStorePassword != null && !keyStorePassword.trim().isEmpty() && !keyStorePassword.trim().equalsIgnoreCase("none")) { + propertiesMap.put("ranger.keystore.password", keyStorePassword); + props.put("ranger.keystore.password", keyStorePassword); + } else { + LOG.info("keyStorePassword password not applied; clear text password shall be applicable"); + } + } + } + } + } + + System.setProperty("javax.net.ssl.keyStorePassword", propertiesMap.get("ranger.keystore.password")); + } + + //update unixauth keystore and truststore credentials + if (propertiesMap.containsKey("ranger.credential.provider.path")) { + String path = propertiesMap.get("ranger.credential.provider.path"); + + if (path != null) { + String unixAuthKeyStoreAlias = getProperty("ranger.unixauth.keystore.alias", "unixAuthKeyStoreAlias"); + + if (unixAuthKeyStoreAlias != null) { + String unixAuthKeyStorePass = CredentialReader.getDecryptedString(path.trim(), unixAuthKeyStoreAlias.trim(), storeType); + + if (unixAuthKeyStorePass != null && !unixAuthKeyStorePass.trim().isEmpty() && !unixAuthKeyStorePass.trim().equalsIgnoreCase("none")) { + propertiesMap.put("ranger.unixauth.keystore.password", unixAuthKeyStorePass); + props.put("ranger.unixauth.keystore.password", unixAuthKeyStorePass); + } else { + LOG.info("unixauth keystore password not applied; clear text password shall be applicable"); + } + } + + // + String unixAuthTrustStoreAlias = getProperty("ranger.unixauth.truststore.alias", "unixAuthTrustStoreAlias"); + + if (unixAuthTrustStoreAlias != null) { + String unixAuthTrustStorePass = CredentialReader.getDecryptedString(path.trim(), unixAuthTrustStoreAlias.trim(), storeType); + + if (unixAuthTrustStorePass != null && !unixAuthTrustStorePass.trim().isEmpty() && !unixAuthTrustStorePass.trim().equalsIgnoreCase("none")) { + propertiesMap.put("ranger.unixauth.truststore.password", unixAuthTrustStorePass); + props.put("ranger.unixauth.truststore.password", unixAuthTrustStorePass); + } else { + LOG.info("unixauth truststore password not applied; clear text password shall be applicable"); + } + } + } + } + + //update credential from keystore + if (propertiesMap.containsKey("ranger.credential.provider.path") && propertiesMap.containsKey("ranger.jpa.jdbc.credential.alias")) { + String path = propertiesMap.get("ranger.credential.provider.path"); + String alias = propertiesMap.get("ranger.jpa.jdbc.credential.alias"); + + if (path != null && alias != null) { + String xaDBPassword = CredentialReader.getDecryptedString(path.trim(), alias.trim(), storeType); + + if (xaDBPassword != null && !xaDBPassword.trim().isEmpty() && !"none".equalsIgnoreCase(xaDBPassword.trim())) { + propertiesMap.put("ranger.jpa.jdbc.password", xaDBPassword); + props.put("ranger.jpa.jdbc.password", xaDBPassword); + } else { + LOG.info("Credential keystore password not applied for Ranger DB; clear text password shall be applicable"); + } + } + } + + if (propertiesMap.containsKey("ranger.credential.provider.path") && propertiesMap.containsKey("ranger.jpa.audit.jdbc.credential.alias")) { + String path = propertiesMap.get("ranger.credential.provider.path"); + String alias = propertiesMap.get("ranger.jpa.audit.jdbc.credential.alias"); + + if (path != null && alias != null) { + String auditDBPassword = CredentialReader.getDecryptedString(path.trim(), alias.trim(), storeType); + + if (auditDBPassword != null && !auditDBPassword.trim().isEmpty() && !"none".equalsIgnoreCase(auditDBPassword.trim())) { + propertiesMap.put("ranger.jpa.audit.jdbc.password", auditDBPassword); + props.put("ranger.jpa.audit.jdbc.password", auditDBPassword); + } else { + LOG.info("Credential keystore password not applied for Audit DB; clear text password shall be applicable"); + } + } + } + + if (propertiesMap.containsKey("ranger.authentication.method")) { + String authenticationMethod = propertiesMap.get("ranger.authentication.method"); + + if (("ACTIVE_DIRECTORY".equalsIgnoreCase(authenticationMethod) || "AD".equalsIgnoreCase(authenticationMethod))) { + if (propertiesMap.containsKey("ranger.credential.provider.path") && propertiesMap.containsKey("ranger.ldap.ad.binddn.credential.alias")) { + String path = propertiesMap.get("ranger.credential.provider.path"); + String alias = propertiesMap.get("ranger.ldap.ad.binddn.credential.alias"); + + if (path != null && alias != null) { + String bindDNPassword = CredentialReader.getDecryptedString(path.trim(), alias.trim(), storeType); + + if (bindDNPassword != null && !bindDNPassword.trim().isEmpty() && !"none".equalsIgnoreCase(bindDNPassword.trim())) { + propertiesMap.put("ranger.ldap.ad.bind.password", bindDNPassword); + props.put("ranger.ldap.ad.bind.password", bindDNPassword); + } else { + LOG.info("Credential keystore password not applied for AD Bind DN; clear text password shall be applicable"); + } + } + } + } + } + + if (propertiesMap.containsKey("ranger.authentication.method")) { + String authenticationMethod = propertiesMap.get("ranger.authentication.method"); + + if (("LDAP".equalsIgnoreCase(authenticationMethod))) { + if (propertiesMap.containsKey("ranger.credential.provider.path") && propertiesMap.containsKey("ranger.ldap.binddn.credential.alias")) { + String path = propertiesMap.get("ranger.credential.provider.path"); + String alias = propertiesMap.get("ranger.ldap.binddn.credential.alias"); + + if (path != null && alias != null) { + String bindDNPassword = CredentialReader.getDecryptedString(path.trim(), alias.trim(), storeType); + + if (bindDNPassword != null && !bindDNPassword.trim().isEmpty() && !"none".equalsIgnoreCase(bindDNPassword.trim())) { + propertiesMap.put("ranger.ldap.bind.password", bindDNPassword); + props.put("ranger.ldap.bind.password", bindDNPassword); + } else { + LOG.info("Credential keystore password not applied for LDAP Bind DN; clear text password shall be applicable"); + } + } + } + } + } + + if (propertiesMap.containsKey("ranger.audit.source.type")) { + String auditStore = propertiesMap.get("ranger.audit.source.type"); + + if (("solr".equalsIgnoreCase(auditStore))) { + if (propertiesMap.containsKey("ranger.credential.provider.path") && propertiesMap.containsKey("ranger.solr.audit.credential.alias")) { + String path = propertiesMap.get("ranger.credential.provider.path"); + String alias = propertiesMap.get("ranger.solr.audit.credential.alias"); + + if (path != null && alias != null) { + String solrAuditPassword = CredentialReader.getDecryptedString(path.trim(), alias.trim(), storeType); + + if (solrAuditPassword != null && !solrAuditPassword.trim().isEmpty() && !"none".equalsIgnoreCase(solrAuditPassword.trim())) { + propertiesMap.put("ranger.solr.audit.user.password", solrAuditPassword); + props.put("ranger.solr.audit.user.password", solrAuditPassword); + } else { + LOG.info("Credential keystore password not applied for Solr; clear text password shall be applicable"); + } + } + } + } + } + + String sha256PasswordUpdateDisable = "false"; + + if (propertiesMap.containsKey("ranger.sha256Password.update.disable")) { + sha256PasswordUpdateDisable = propertiesMap.get("ranger.sha256Password.update.disable"); + + if (sha256PasswordUpdateDisable == null || sha256PasswordUpdateDisable.trim().isEmpty() || !"true".equalsIgnoreCase(sha256PasswordUpdateDisable)) { + sha256PasswordUpdateDisable = "false"; + } + } + + propertiesMap.put("ranger.sha256Password.update.disable", sha256PasswordUpdateDisable); + props.put("ranger.sha256Password.update.disable", sha256PasswordUpdateDisable); + + if (RangerBizUtil.getDBFlavor() == AppConstants.DB_FLAVOR_MYSQL || RangerBizUtil.getDBFlavor() == AppConstants.DB_FLAVOR_POSTGRES) { + if (propertiesMap.containsKey("ranger.db.ssl.enabled")) { + String dbSslEnabled = propertiesMap.get("ranger.db.ssl.enabled"); + + if (StringUtils.isEmpty(dbSslEnabled) || !"true".equalsIgnoreCase(dbSslEnabled)) { + dbSslEnabled = "false"; + } + + dbSslEnabled = dbSslEnabled.toLowerCase(); + + String rangerJpaJdbcUrl = propertiesMap.get("ranger.jpa.jdbc.url"); + + if ("true".equalsIgnoreCase(dbSslEnabled)) { + String dbSslRequired = propertiesMap.get("ranger.db.ssl.required"); + + if (StringUtils.isEmpty(dbSslRequired) || !"true".equalsIgnoreCase(dbSslRequired)) { + dbSslRequired = "false"; + } + + dbSslRequired = dbSslRequired.toLowerCase(); + + String dbSslVerifyServerCertificate = propertiesMap.get("ranger.db.ssl.verifyServerCertificate"); + + if (StringUtils.isEmpty(dbSslVerifyServerCertificate) || !"true".equalsIgnoreCase(dbSslVerifyServerCertificate)) { + dbSslVerifyServerCertificate = "false"; + } + + dbSslVerifyServerCertificate = dbSslVerifyServerCertificate.toLowerCase(); + + String dbSslAuthType = propertiesMap.get("ranger.db.ssl.auth.type"); + + if (StringUtils.isEmpty(dbSslAuthType) || !"1-way".equalsIgnoreCase(dbSslAuthType)) { + dbSslAuthType = "2-way"; + } + + propertiesMap.put("ranger.db.ssl.enabled", dbSslEnabled); + props.put("ranger.db.ssl.enabled", dbSslEnabled); + propertiesMap.put("ranger.db.ssl.required", dbSslRequired); + props.put("ranger.db.ssl.required", dbSslRequired); + propertiesMap.put("ranger.db.ssl.verifyServerCertificate", dbSslVerifyServerCertificate); + props.put("ranger.db.ssl.verifyServerCertificate", dbSslVerifyServerCertificate); + propertiesMap.put("ranger.db.ssl.auth.type", dbSslAuthType); + props.put("ranger.db.ssl.auth.type", dbSslAuthType); + + if (StringUtils.isNotEmpty(rangerJpaJdbcUrl) && !rangerJpaJdbcUrl.contains("?")) { + StringBuilder rangerJpaJdbcUrlSsl = new StringBuilder(rangerJpaJdbcUrl); + + if (RangerBizUtil.getDBFlavor() == AppConstants.DB_FLAVOR_MYSQL) { + rangerJpaJdbcUrlSsl.append("?useSSL=").append(dbSslEnabled).append("&requireSSL=").append(dbSslRequired).append("&verifyServerCertificate=").append(dbSslVerifyServerCertificate); + } else if (RangerBizUtil.getDBFlavor() == AppConstants.DB_FLAVOR_POSTGRES) { + String dbSslCertificateFile = propertiesMap.get("ranger.db.ssl.certificateFile"); + + if (StringUtils.isNotEmpty(dbSslCertificateFile)) { + rangerJpaJdbcUrlSsl.append("?ssl=").append(dbSslEnabled).append("&sslmode=verify-full").append("&sslrootcert=").append(dbSslCertificateFile); + } else if ("true".equalsIgnoreCase(dbSslVerifyServerCertificate) || "true".equalsIgnoreCase(dbSslRequired)) { + rangerJpaJdbcUrlSsl.append("?ssl=").append(dbSslEnabled).append("&sslmode=verify-full").append("&sslfactory=org.postgresql.ssl.DefaultJavaSSLFactory"); + } else { + rangerJpaJdbcUrlSsl.append("?ssl=").append(dbSslEnabled); + } + } + + propertiesMap.put("ranger.jpa.jdbc.url", rangerJpaJdbcUrlSsl.toString()); + } + + rangerJpaJdbcUrl = propertiesMap.get("ranger.jpa.jdbc.url"); + + if (StringUtils.isNotEmpty(rangerJpaJdbcUrl)) { + props.put("ranger.jpa.jdbc.url", rangerJpaJdbcUrl); + } + + LOG.info("ranger.jpa.jdbc.url={}", rangerJpaJdbcUrl); + } else { + String rangerJpaJdbcUrlExtraArgs = ""; + + if (!StringUtils.isEmpty(rangerJpaJdbcUrl)) { + if (rangerJpaJdbcUrl.contains("?")) { + rangerJpaJdbcUrlExtraArgs = rangerJpaJdbcUrl.substring(rangerJpaJdbcUrl.indexOf("?") + 1); + rangerJpaJdbcUrl = rangerJpaJdbcUrl.substring(0, rangerJpaJdbcUrl.indexOf("?")); + } + + if (RangerBizUtil.getDBFlavor() == AppConstants.DB_FLAVOR_MYSQL) { + StringBuilder rangerJpaJdbcUrlNoSsl = new StringBuilder(rangerJpaJdbcUrl); + + if (!rangerJpaJdbcUrlExtraArgs.contains("useSSL")) { + rangerJpaJdbcUrlNoSsl.append("?useSSL=false"); + } + + if (!StringUtils.isEmpty(rangerJpaJdbcUrlExtraArgs) && rangerJpaJdbcUrlNoSsl.toString().contains("useSSL")) { + rangerJpaJdbcUrlNoSsl.append("&").append(rangerJpaJdbcUrlExtraArgs); + } else if (!StringUtils.isEmpty(rangerJpaJdbcUrlExtraArgs) && !rangerJpaJdbcUrlNoSsl.toString().contains("useSSL")) { + rangerJpaJdbcUrlNoSsl.append("?").append(rangerJpaJdbcUrlExtraArgs); + } + + propertiesMap.put("ranger.jpa.jdbc.url", rangerJpaJdbcUrlNoSsl.toString()); + } + + rangerJpaJdbcUrl = propertiesMap.get("ranger.jpa.jdbc.url"); + + if (StringUtils.isNotEmpty(rangerJpaJdbcUrl)) { + props.put("ranger.jpa.jdbc.url", rangerJpaJdbcUrl); + } + + LOG.info("ranger.jpa.jdbc.url={}", rangerJpaJdbcUrl); + } + } + } + } + + if (propertiesMap.containsKey(RangerCommonConstants.PROP_COOKIE_NAME)) { + String cookieName = propertiesMap.get(RangerCommonConstants.PROP_COOKIE_NAME); + + if (StringUtils.isBlank(cookieName)) { + cookieName = RangerCommonConstants.DEFAULT_COOKIE_NAME; + } + + propertiesMap.put(RangerCommonConstants.PROP_COOKIE_NAME, cookieName); + props.put(RangerCommonConstants.PROP_COOKIE_NAME, cookieName); + } + + keySet = props.keySet(); + + for (Object key : keySet) { + String keyStr = key.toString(); + + if (LOG.isDebugEnabled()) { + LOG.debug("PropertiesUtil:[{}][{}]", keyStr, keyStr.toLowerCase().contains("pass") ? "********]" : props.get(keyStr)); + } + } + + super.processProperties(beanFactory, props); } - public static Map getPropertiesMap() { - return propertiesMap; - } - public static Properties getProps() { - Properties ret = new Properties(); - if (propertiesMap != null) { - ret.putAll(propertiesMap); - } - return ret; - } } 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 index 50e13e0487..e323dc1fa0 100644 --- a/security-admin/src/main/java/org/apache/ranger/common/RESTErrorUtil.java +++ b/security-admin/src/main/java/org/apache/ranger/common/RESTErrorUtil.java @@ -17,17 +17,7 @@ * under the License. */ - package org.apache.ranger.common; - -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Date; -import java.util.List; - -import javax.ws.rs.WebApplicationException; -import javax.ws.rs.core.Response; +package org.apache.ranger.common; import org.apache.ranger.admin.client.datatype.RESTResponse; import org.apache.ranger.view.VXMessage; @@ -37,437 +27,410 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; +import javax.ws.rs.WebApplicationException; +import javax.ws.rs.core.Response; + +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Date; +import java.util.List; @Component public class RESTErrorUtil { + private static final Logger logger = LoggerFactory.getLogger(RESTErrorUtil.class); + + public static final String TRUE = "true"; + + @Autowired + StringUtil stringUtil; + + 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(); + String loginId = null; + + if (userSession != null) { + loginId = userSession.getLoginId(); + } + + logger.info("Request failed. loginId={}, logMessage={}", loginId, gjResponse.getMsgDesc(), restException); + + return restException; + } + + public WebApplicationException generateRESTException(VXResponse gjResponse) { + Response errorResponse = Response.status(gjResponse.getStatusCode()).entity(gjResponse).build(); + WebApplicationException restException = new WebApplicationException(errorResponse); + + restException.fillInStackTrace(); + + UserSessionBase userSession = ContextUtil.getCurrentUserSession(); + String loginId = null; + + if (userSession != null) { + loginId = userSession.getLoginId(); + } + + logger.info("Request failed. loginId={}, logMessage={}", loginId, gjResponse.getMsgDesc(), restException); + + return restException; + } + + /** + * @param logMessage This is optional + * @return + */ + public WebApplicationException create403RESTException(String logMessage) { + RESTResponse resp = new RESTResponse(); + + resp.setMsgDesc(logMessage); + + Response errorResponse = Response.status(javax.servlet.http.HttpServletResponse.SC_FORBIDDEN).entity(resp).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(); + String loginId = null; + + if (userSession != null) { + loginId = userSession.getLoginId(); + } + + 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. loginId={}, logMessage={}, requestInfo={}", loginId, logMessage, requestInfo, restException); + + return restException; + } + + public WebApplicationException create403RESTException(VXResponse gjResponse) { + gjResponse.setStatusCode(VXResponse.STATUS_ERROR); + gjResponse.setMessageList(Collections.singletonList(MessageEnums.OPER_NO_PERMISSION.getMessage())); + + Response errorResponse = Response.status(javax.servlet.http.HttpServletResponse.SC_FORBIDDEN).entity(gjResponse).build(); + WebApplicationException restException = new WebApplicationException(errorResponse); + + restException.fillInStackTrace(); + + if (logger.isInfoEnabled()) { + UserSessionBase userSession = ContextUtil.getCurrentUserSession(); + String loginId = (userSession != null) ? userSession.getLoginId() : null; + + logger.info("Request failed. loginId={}, logMessage={}", loginId, gjResponse.getMsgDesc(), restException); + } + + return restException; + } + + public WebApplicationException createGrantRevokeRESTException(String logMessage) { + RESTResponse resp = new RESTResponse(); + + resp.setMsgDesc(logMessage); + + Response errorResponse = Response.status(javax.servlet.http.HttpServletResponse.SC_FORBIDDEN).entity(resp).build(); + WebApplicationException restException = new WebApplicationException(errorResponse); + + restException.fillInStackTrace(); + + UserSessionBase userSession = ContextUtil.getCurrentUserSession(); + String loginId = null; + + if (userSession != null) { + loginId = userSession.getLoginId(); + } + + logger.info("Request failed. loginId={}, logMessage={}", loginId, logMessage, 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 Integer.valueOf(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 defaultValue; + } else { + return Integer.valueOf(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 Long.valueOf(value.trim()); + } + + public Long parseLong(String value, String errorMessage, MessageEnums messageEnum, Long objectId, String fieldName) { + try { + if (stringUtil.isEmpty(value)) { + return null; + } else { + return Long.valueOf(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.isEmpty()) { + 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 (String validValue : validValues) { + if (validValue.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 messageList = new ArrayList<>(); + + 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={}, response={}", logMessage, gjResponse, webAppEx); + + return webAppEx; + } + + public WebApplicationException createRESTException(String errorMessage) { + VXResponse gjResponse = new VXResponse(); + + gjResponse.setStatusCode(VXResponse.STATUS_ERROR); + gjResponse.setMsgDesc(errorMessage); + + WebApplicationException webAppEx = createRESTException(gjResponse); + + logger.info("Operation error. response={}", gjResponse, webAppEx); + + return webAppEx; + } + + public WebApplicationException createRESTException(String errorMessage, MessageEnums messageEnum) { + List messageList = new ArrayList<>(); + + 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) { + VXResponse response = new VXResponse(); + + response.setMsgDesc(logMessage); + + Response errorResponse = Response.status(responseCode).entity(response).build(); + WebApplicationException restException = new WebApplicationException(errorResponse); + + restException.fillInStackTrace(); + + UserSessionBase userSession = ContextUtil.getCurrentUserSession(); + String loginId = null; + + if (userSession != null) { + loginId = userSession.getLoginId(); + } + + if (logError) { + logger.info("Request failed. loginId={}, logMessage={}", loginId, 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 Boolean.valueOf(value.trim()); + } + } catch (Throwable t) { + throw createRESTException(errorMessage, messageEnum, objectId, fieldName, value); + } + } + + public WebApplicationException createRESTException(String errorMessage, MessageEnums messageEnum, Long objectId, String fieldName, String logMessage, int statusCode) { + List messageList = new ArrayList(); + + messageList.add(messageEnum.getMessage(objectId, fieldName)); + + VXResponse vResponse = new VXResponse(); + + vResponse.setStatusCode(VXResponse.STATUS_ERROR); + vResponse.setMsgDesc(errorMessage); + vResponse.setMessageList(messageList); + + Response errorResponse = Response.status(statusCode).entity(vResponse).build(); + WebApplicationException restException = new WebApplicationException(errorResponse); + + restException.fillInStackTrace(); + + UserSessionBase userSession = ContextUtil.getCurrentUserSession(); + String loginId = null; + + if (userSession != null) { + loginId = userSession.getLoginId(); + } + + logger.info("Request failed. loginId={}, logMessage={}", loginId, vResponse.getMsgDesc(), restException); + + return restException; + } + + public WebApplicationException create404RESTException(String errorMessage, MessageEnums messageEnum, Long objectId, String fieldName, String logMessage) { + List messageList = new ArrayList(); + + messageList.add(messageEnum.getMessage(objectId, fieldName)); + + VXResponse gjResponse = new VXResponse(); + + gjResponse.setStatusCode(VXResponse.STATUS_ERROR); + gjResponse.setMsgDesc(errorMessage); + gjResponse.setMessageList(messageList); + + Response errorResponse = Response.status(javax.servlet.http.HttpServletResponse.SC_NOT_FOUND).entity(gjResponse).build(); + WebApplicationException restException = new WebApplicationException(errorResponse); + + restException.fillInStackTrace(); + + UserSessionBase userSession = ContextUtil.getCurrentUserSession(); + String loginId = null; + + if (userSession != null) { + loginId = userSession.getLoginId(); + } + + logger.info("Request failed. loginId={}, logMessage={}", loginId, gjResponse.getMsgDesc(), restException); - private static final Logger logger = LoggerFactory.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(); - String loginId = null; - if (userSession != null) { - loginId = userSession.getLoginId(); - } - - logger.info("Request failed. loginId=" - + loginId + ", logMessage=" + gjResponse.getMsgDesc(), - restException); - - return restException; - } - - public WebApplicationException generateRESTException(VXResponse gjResponse) { - Response errorResponse = Response - .status(gjResponse.getStatusCode()) - .entity(gjResponse).build(); - - WebApplicationException restException = new WebApplicationException( - errorResponse); - restException.fillInStackTrace(); - UserSessionBase userSession = ContextUtil.getCurrentUserSession(); - String loginId = null; - if (userSession != null) { - loginId = userSession.getLoginId(); - } - - logger.info("Request failed. loginId=" - + loginId + ", logMessage=" + gjResponse.getMsgDesc(), - restException); - - return restException; - } - /** - * - * @param logMessage - * This is optional - * @return - */ - public WebApplicationException create403RESTException(String logMessage) { - RESTResponse resp = new RESTResponse(); - resp.setMsgDesc(logMessage); - - Response errorResponse = Response.status( - javax.servlet.http.HttpServletResponse.SC_FORBIDDEN).entity(resp).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(); - String loginId = null; - if (userSession != null) { - loginId = userSession.getLoginId(); - } - - 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. loginId=" - + loginId + ", logMessage=" + logMessage + ", requestInfo=" - + requestInfo, restException); - - return restException; - } - - public WebApplicationException create403RESTException(VXResponse gjResponse) { - gjResponse.setStatusCode(VXResponse.STATUS_ERROR); - gjResponse.setMessageList(Collections.singletonList(MessageEnums.OPER_NO_PERMISSION.getMessage())); - - Response errorResponse = Response.status(javax.servlet.http.HttpServletResponse.SC_FORBIDDEN).entity(gjResponse).build(); - WebApplicationException restException = new WebApplicationException(errorResponse); - - restException.fillInStackTrace(); - - if (logger.isInfoEnabled()) { - UserSessionBase userSession = ContextUtil.getCurrentUserSession(); - String loginId = (userSession != null) ? userSession.getLoginId() : null; - - logger.info("Request failed. loginId=" + loginId + ", logMessage=" + gjResponse.getMsgDesc(), restException); - } - - return restException; - } - - public WebApplicationException createGrantRevokeRESTException(String logMessage) { - RESTResponse resp = new RESTResponse(); - resp.setMsgDesc(logMessage); - - Response errorResponse = Response.status( - javax.servlet.http.HttpServletResponse.SC_FORBIDDEN).entity(resp).build(); - - WebApplicationException restException = new WebApplicationException( - errorResponse); - restException.fillInStackTrace(); - UserSessionBase userSession = ContextUtil.getCurrentUserSession(); - String loginId = null; - if (userSession != null) { - loginId = userSession.getLoginId(); - } - - logger.info("Request failed. loginId=" - + loginId + ", logMessage=" + logMessage, - 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 Integer.valueOf(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 Integer.valueOf(defaultValue); - } else { - return Integer.valueOf(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 Long.valueOf(value.trim()); - } - - public Long parseLong(String value, String errorMessage, - MessageEnums messageEnum, Long objectId, String fieldName) { - try { - if (stringUtil.isEmpty(value)) { - return null; - } else { - return Long.valueOf(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 (String validValue : validValues) { - if (validValue.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 messageList = new ArrayList(); - 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) { - VXResponse gjResponse = new VXResponse(); - gjResponse.setStatusCode(VXResponse.STATUS_ERROR); - gjResponse.setMsgDesc(errorMessage); - WebApplicationException webAppEx = createRESTException(gjResponse); - logger.info("Operation error. response=" + gjResponse, webAppEx); - return webAppEx; - } - - public WebApplicationException createRESTException(String errorMessage, - MessageEnums messageEnum) { - List messageList = new ArrayList(); - 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) { - VXResponse response = new VXResponse(); - - response.setMsgDesc(logMessage); - - Response errorResponse = Response - .status(responseCode).entity(response).build(); - - WebApplicationException restException = new WebApplicationException( - errorResponse); - restException.fillInStackTrace(); - UserSessionBase userSession = ContextUtil.getCurrentUserSession(); - String loginId = null; - if (userSession != null) { - loginId = userSession.getLoginId(); - } - - if (logError) { - logger.info("Request failed. 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 Boolean.valueOf(value.trim()); - } - } catch (Throwable t) { - throw createRESTException(errorMessage, messageEnum, objectId, - fieldName, value); - } - } - - public WebApplicationException createRESTException(String errorMessage, - MessageEnums messageEnum, Long objectId, String fieldName, - String logMessage,int statusCode) - { - List messageList = new ArrayList(); - messageList.add(messageEnum.getMessage(objectId, fieldName)); - VXResponse vResponse = new VXResponse(); - vResponse.setStatusCode(vResponse.STATUS_ERROR); - vResponse.setMsgDesc(errorMessage); - vResponse.setMessageList(messageList); - Response errorResponse = Response.status(statusCode).entity(vResponse).build(); - WebApplicationException restException = new WebApplicationException(errorResponse); - restException.fillInStackTrace(); - UserSessionBase userSession = ContextUtil.getCurrentUserSession(); - String loginId = null; - if (userSession != null) { - loginId = userSession.getLoginId(); - } - logger.info("Request failed. loginId=" - + loginId + ", logMessage=" + vResponse.getMsgDesc(), - restException); - return restException; - } - - public WebApplicationException create404RESTException(String errorMessage, - MessageEnums messageEnum, Long objectId, String fieldName, - String logMessage) { - List messageList = new ArrayList(); - messageList.add(messageEnum.getMessage(objectId, fieldName)); - - VXResponse gjResponse = new VXResponse(); - gjResponse.setStatusCode(VXResponse.STATUS_ERROR); - gjResponse.setMsgDesc(errorMessage); - gjResponse.setMessageList(messageList); - - Response errorResponse = Response - .status(javax.servlet.http.HttpServletResponse.SC_NOT_FOUND) - .entity(gjResponse).build(); - - WebApplicationException restException = new WebApplicationException( - errorResponse); - restException.fillInStackTrace(); - UserSessionBase userSession = ContextUtil.getCurrentUserSession(); - String loginId = null; - if (userSession != null) { - loginId = userSession.getLoginId(); - } - - logger.info("Request failed. loginId=" - + loginId + ", logMessage=" + gjResponse.getMsgDesc(), - restException); - - return restException; - } + return restException; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/common/RangerAdminTagEnricher.java b/security-admin/src/main/java/org/apache/ranger/common/RangerAdminTagEnricher.java index 9af59bf65f..0d6d9fcc71 100644 --- a/security-admin/src/main/java/org/apache/ranger/common/RangerAdminTagEnricher.java +++ b/security-admin/src/main/java/org/apache/ranger/common/RangerAdminTagEnricher.java @@ -23,7 +23,6 @@ import org.apache.ranger.db.RangerDaoManager; import org.apache.ranger.entity.XXServiceVersionInfo; import org.apache.ranger.plugin.contextenricher.RangerTagEnricher; - import org.apache.ranger.plugin.model.RangerService; import org.apache.ranger.plugin.policyengine.RangerAccessRequest; import org.apache.ranger.plugin.store.ServiceStore; @@ -36,16 +35,16 @@ public class RangerAdminTagEnricher extends RangerTagEnricher { private static final Logger LOG = LoggerFactory.getLogger(RangerAdminTagEnricher.class); - private static TagStore tagStore = null; - private static RangerDaoManager daoManager = null; + private static TagStore tagStore; + private static RangerDaoManager daoManager; - private static boolean ADMIN_TAG_ENRICHER_SUPPORTS_TAG_DELTAS_INITIALIZED = false; + private static boolean ADMIN_TAG_ENRICHER_SUPPORTS_TAG_DELTAS_INITIALIZED; private static boolean ADMIN_TAG_ENRICHER_SUPPORTS_TAG_DELTAS; private Long serviceId; public static void setTagStore(TagStore tagStore) { - RangerAdminTagEnricher.tagStore = tagStore; + RangerAdminTagEnricher.tagStore = tagStore; } public static void setDaoManager(RangerDaoManager daoManager) { @@ -54,9 +53,8 @@ public static void setDaoManager(RangerDaoManager daoManager) { @Override public void init() { - if (LOG.isDebugEnabled()) { - LOG.debug("==> RangerAdminTagEnricher.init()"); - } + LOG.debug("==> RangerAdminTagEnricher.init()"); + super.init(); if (!ADMIN_TAG_ENRICHER_SUPPORTS_TAG_DELTAS_INITIALIZED) { @@ -73,92 +71,83 @@ public void init() { LOG.error("ServiceDBStore/TagDBStore is not initialized!! Internal Error!"); } else { super.init(); + try { RangerService service = svcStore.getServiceByName(serviceName); + serviceId = service.getId(); + createLock(); } catch (Exception e) { - LOG.error("Cannot find service with name:[" + serviceName + "]", e); + LOG.error("Cannot find service with name:[{}]", serviceName, e); LOG.error("This will cause tag-enricher in Ranger-Admin to fail!!"); } } - if (LOG.isDebugEnabled()) { - LOG.debug("<== RangerAdminTagEnricher.init()"); - } + + LOG.debug("<== RangerAdminTagEnricher.init()"); + } + + @Override + public void enrich(RangerAccessRequest request) { + LOG.debug("==> RangerAdminTagEnricher.enrich({})", request); + + refreshTagsIfNeeded(); + super.enrich(request); + + LOG.debug("<== RangerAdminTagEnricher.enrich({})", request); } @Override protected RangerReadWriteLock createLock() { boolean useReadWriteLock = tagStore != null && tagStore.isInPlaceTagUpdateSupported(); - LOG.info("Policy-Engine will" + (useReadWriteLock ? " " : " not ") + "use read-write locking to update tags in place when tag-deltas are provided"); + LOG.info("Policy-Engine will{}use read-write locking to update tags in place when tag-deltas are provided", useReadWriteLock ? " " : " not "); return new RangerReadWriteLock(useReadWriteLock); } @Override - public void enrich(RangerAccessRequest request) { - if (LOG.isDebugEnabled()) { - LOG.debug("==> RangerAdminTagEnricher.enrich(" + request + ")"); - } - - refreshTagsIfNeeded(); - super.enrich(request); - - if (LOG.isDebugEnabled()) { - LOG.debug("<== RangerAdminTagEnricher.enrich(" + request + ")"); - } + public String toString() { + return "RangerAdminTagEnricher={serviceName=" + serviceName + ", " + "serviceId=" + serviceId + "}"; } private void refreshTagsIfNeeded() { - - final Long enrichedServiceTagsVersion = getServiceTagsVersion(); - final Long resourceTrieVersion = getResourceTrieVersion(); - ServiceTags serviceTags = null; + final Long enrichedServiceTagsVersion = getServiceTagsVersion(); + final Long resourceTrieVersion = getResourceTrieVersion(); + ServiceTags serviceTags = null; try { - - boolean needsBackwardCompatibility = !ADMIN_TAG_ENRICHER_SUPPORTS_TAG_DELTAS || enrichedServiceTagsVersion == -1L; - - XXServiceVersionInfo serviceVersionInfoDbObj = daoManager.getXXServiceVersionInfo().findByServiceName(serviceName); + boolean needsBackwardCompatibility = !ADMIN_TAG_ENRICHER_SUPPORTS_TAG_DELTAS || enrichedServiceTagsVersion == -1L; + XXServiceVersionInfo serviceVersionInfoDbObj = daoManager.getXXServiceVersionInfo().findByServiceName(serviceName); if (serviceVersionInfoDbObj == null) { - LOG.warn("serviceVersionInfo does not exist. name=" + serviceName); + LOG.warn("serviceVersionInfo does not exist. name={}", serviceName); } if (serviceVersionInfoDbObj == null || serviceVersionInfoDbObj.getTagVersion() == null || !enrichedServiceTagsVersion.equals(serviceVersionInfoDbObj.getTagVersion())) { serviceTags = RangerServiceTagsCache.getInstance().getServiceTags(serviceName, serviceId, enrichedServiceTagsVersion, needsBackwardCompatibility, tagStore); } else { - if (LOG.isDebugEnabled()) { - LOG.debug("Have the latest tag version already. Only need to check if it needs to be rebuilt"); - } + LOG.debug("Have the latest tag version already. Only need to check if it needs to be rebuilt"); + if (!enrichedServiceTagsVersion.equals(resourceTrieVersion)) { serviceTags = RangerServiceTagsCache.getInstance().getServiceTags(serviceName, serviceId, resourceTrieVersion, needsBackwardCompatibility, tagStore); } } - } catch (Exception e) { LOG.error("Could not get cached service-tags, continue to use old ones..", e); - serviceTags = null; } - if (LOG.isDebugEnabled()) { - LOG.debug("Received serviceTags:[" + serviceTags + "]"); - } + LOG.debug("Received serviceTags:[{}]", serviceTags); if (serviceTags != null) { - - if (LOG.isDebugEnabled()) { - LOG.debug("enrichedServiceTagsVersion=" + enrichedServiceTagsVersion + ", serviceTags-version=" + serviceTags.getTagVersion()); - } + LOG.debug("enrichedServiceTagsVersion={}, serviceTags-version={}", enrichedServiceTagsVersion, serviceTags.getTagVersion()); if (!enrichedServiceTagsVersion.equals(serviceTags.getTagVersion()) || !resourceTrieVersion.equals(serviceTags.getTagVersion())) { - - synchronized(this) { - + synchronized (this) { if (serviceTags.getIsDelta()) { // Avoid rebuilding service-tags - applyDelta may not work correctly if called twice boolean rebuildOnlyIndex = true; + setServiceTags(serviceTags, rebuildOnlyIndex); } else { setServiceTags(serviceTags); @@ -167,12 +156,4 @@ private void refreshTagsIfNeeded() { } } } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("RangerAdminTagEnricher={serviceName=").append(serviceName).append(", "); - sb.append("serviceId=").append(serviceId).append("}"); - return sb.toString(); - } } diff --git a/security-admin/src/main/java/org/apache/ranger/common/RangerAdminUserStoreEnricher.java b/security-admin/src/main/java/org/apache/ranger/common/RangerAdminUserStoreEnricher.java index 92bb8cc5c5..28475d009a 100644 --- a/security-admin/src/main/java/org/apache/ranger/common/RangerAdminUserStoreEnricher.java +++ b/security-admin/src/main/java/org/apache/ranger/common/RangerAdminUserStoreEnricher.java @@ -30,30 +30,27 @@ public class RangerAdminUserStoreEnricher extends RangerUserStoreEnricher { @Override public void init() { - if (LOG.isDebugEnabled()) { - LOG.debug("==> RangerAdminUserStoreEnricher.init()"); - } + LOG.debug("==> RangerAdminUserStoreEnricher.init()"); super.init(); - if (LOG.isDebugEnabled()) { - LOG.debug("<== RangerAdminUserStoreEnricher.init()"); - } + LOG.debug("<== RangerAdminUserStoreEnricher.init()"); } @Override public void enrich(RangerAccessRequest request) { - if (LOG.isDebugEnabled()) { - LOG.debug("==> RangerAdminUserStoreEnricher.enrich(" + request + ")"); - } + LOG.debug("==> RangerAdminUserStoreEnricher.enrich({})", request); refreshUserStoreIfNeeded(); super.enrich(request); - if (LOG.isDebugEnabled()) { - LOG.debug("<== RangerAdminUserStoreEnricher.enrich(" + request + ")"); - } + LOG.debug("<== RangerAdminUserStoreEnricher.enrich({})", request); + } + + @Override + public String toString() { + return "RangerAdminUserStoreEnricher={serviceName=" + serviceName + "}"; } private void refreshUserStoreIfNeeded() { @@ -70,11 +67,4 @@ private void refreshUserStoreIfNeeded() { } } } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("RangerAdminUserStoreEnricher={serviceName=").append(serviceName).append("}"); - return sb.toString(); - } } diff --git a/security-admin/src/main/java/org/apache/ranger/common/RangerCommonEnums.java b/security-admin/src/main/java/org/apache/ranger/common/RangerCommonEnums.java index 0234e47bb6..2aefb8aaca 100644 --- a/security-admin/src/main/java/org/apache/ranger/common/RangerCommonEnums.java +++ b/security-admin/src/main/java/org/apache/ranger/common/RangerCommonEnums.java @@ -17,1454 +17,1430 @@ * under the License. */ - package org.apache.ranger.common; +package org.apache.ranger.common; /** * */ - public class RangerCommonEnums { - - /*************************************************************** - * Enum values for AllowedPermission - **************************************************************/ - /** - * IS_ALLOWED is an element of enum AllowedPermission. Its value is "IS_ALLOWED". - */ - public static final int IS_ALLOWED = 1; - - /*************************************************************** - * Enum values for VisibilityStatus - **************************************************************/ - /** - * IS_VISIBLE is an element of enum VisibilityStatus. Its value is "IS_VISIBLE". - */ - public static final int IS_VISIBLE = 1; - /** - * IS_HIDDEN is an element of enum VisibilityStatus. Its value is "IS_HIDDEN". - */ - public static final int IS_HIDDEN = 0; - - /*************************************************************** - * 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 USER_FEDERATED = 6; - - 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_VisibilityStatus( int elementValue ) { - if( elementValue == 0 ) { - return "Hidden"; //IS_HIDDEN - } - if( elementValue == 1 ) { - return "Visible"; //IS_VISIBLE - } - return null; - } - - 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; - } - - + /*************************************************************** + * Enum values for AllowedPermission + **************************************************************/ + /** + * IS_ALLOWED is an element of enum AllowedPermission. Its value is "IS_ALLOWED". + */ + public static final int IS_ALLOWED = 1; + + /*************************************************************** + * Enum values for VisibilityStatus + **************************************************************/ + /** + * IS_VISIBLE is an element of enum VisibilityStatus. Its value is "IS_VISIBLE". + */ + public static final int IS_VISIBLE = 1; + /** + * IS_HIDDEN is an element of enum VisibilityStatus. Its value is "IS_HIDDEN". + */ + public static final int IS_HIDDEN = 0; + + /*************************************************************** + * 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 USER_FEDERATED = 6; + + 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; + + public static String getLabelFor_VisibilityStatus(int elementValue) { + if (elementValue == 0) { + return "Hidden"; //IS_HIDDEN + } + if (elementValue == 1) { + return "Visible"; //IS_VISIBLE + } + return null; + } + + public static 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; + } + + public static 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; + } + + public static 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; + } + + public static 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; + } + + public static 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; + } + + public static 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; + } + + public static String getLabelFor_FileType(int elementValue) { + if (elementValue == 0) { + return "File"; //FILE_FILE + } + if (elementValue == 1) { + return "Directory"; //FILE_DIR + } + return null; + } + + public static 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; + } + + public static 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; + } + + public static 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; + } + + public static 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; + } + + public static 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; + } + + public static 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; + } + + public static 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; + } + + public static String getLabelFor_RelationType(int elementValue) { + if (elementValue == 0) { + return "None"; //REL_NONE + } + if (elementValue == 1) { + return "Self"; //REL_SELF + } + return null; + } + + public static 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; + } + + public static 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; + } + + public static String getLabelFor_AccessResult(int elementValue) { + if (elementValue == 0) { + return "Denied"; //ACCESS_RESULT_DENIED + } + if (elementValue == 1) { + return "Allowed"; //ACCESS_RESULT_ALLOWED + } + return null; + } + + public static String getLabelFor_PolicyType(int elementValue) { + if (elementValue == 0) { + return "Inclusion"; //POLICY_INCLUSION + } + if (elementValue == 1) { + return "Exclusion"; //POLICY_EXCLUSION + } + return null; + } + + public static 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; + } + + public static 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; + } + + public static 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; + } + + public static 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; + } + + public static 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; + } + + public static 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; + } } - diff --git a/security-admin/src/main/java/org/apache/ranger/common/RangerConfigUtil.java b/security-admin/src/main/java/org/apache/ranger/common/RangerConfigUtil.java index 7bbf1ad262..afd17f84d6 100644 --- a/security-admin/src/main/java/org/apache/ranger/common/RangerConfigUtil.java +++ b/security-admin/src/main/java/org/apache/ranger/common/RangerConfigUtil.java @@ -24,62 +24,59 @@ import org.springframework.stereotype.Component; /** - * * */ @Component public class RangerConfigUtil { - private static final Logger logger = LoggerFactory.getLogger(RangerConfigUtil.class); - - String webappRootURL; - int defaultMaxRows = 250; - String[] roles; - boolean accessFilterEnabled = true; - boolean isModerationEnabled = false; - boolean isUserPrefEnabled = false; + private static final Logger logger = LoggerFactory.getLogger(RangerConfigUtil.class); - public RangerConfigUtil() { + String webappRootURL; + int defaultMaxRows = 250; + String[] roles; + boolean accessFilterEnabled; + boolean isModerationEnabled; + boolean isUserPrefEnabled; - webappRootURL = PropertiesUtil.getProperty("ranger.externalurl"); - if (webappRootURL == null || webappRootURL.trim().length() == 0) { - logger.error("webapp URL is not set. Please ranger.externalurl property"); - } + public RangerConfigUtil() { + webappRootURL = PropertiesUtil.getProperty("ranger.externalurl"); - defaultMaxRows = PropertiesUtil.getIntProperty( - "ranger.db.maxrows.default", defaultMaxRows); - roles = PropertiesUtil.getPropertyStringList("ranger.users.roles.list"); + if (webappRootURL == null || webappRootURL.trim().isEmpty()) { + logger.error("webapp URL is not set. Please ranger.externalurl property"); + } - accessFilterEnabled = PropertiesUtil.getBooleanProperty("ranger.db.access.filter.enable", true); - isModerationEnabled = PropertiesUtil.getBooleanProperty("ranger.moderation.enabled", isModerationEnabled); - isUserPrefEnabled = PropertiesUtil.getBooleanProperty("ranger.userpref.enabled", isUserPrefEnabled); - } + defaultMaxRows = PropertiesUtil.getIntProperty("ranger.db.maxrows.default", defaultMaxRows); + roles = PropertiesUtil.getPropertyStringList("ranger.users.roles.list"); - /** - * @return the defaultMaxRows - */ - public int getDefaultMaxRows() { - return defaultMaxRows; - } + accessFilterEnabled = PropertiesUtil.getBooleanProperty("ranger.db.access.filter.enable", true); + isModerationEnabled = PropertiesUtil.getBooleanProperty("ranger.moderation.enabled", isModerationEnabled); + isUserPrefEnabled = PropertiesUtil.getBooleanProperty("ranger.userpref.enabled", isUserPrefEnabled); + } - /** - * @return the roles - */ - public String[] getRoles() { - return roles; - } + /** + * @return the defaultMaxRows + */ + public int getDefaultMaxRows() { + return defaultMaxRows; + } - /** - * @return the accessFilterEnabled - */ - public boolean isAccessFilterEnabled() { - return accessFilterEnabled; - } + /** + * @return the roles + */ + public String[] getRoles() { + return roles; + } - /** - * @return the webAppRootURL - */ - public String getWebAppRootURL() { - return webappRootURL; - } + /** + * @return the accessFilterEnabled + */ + public boolean isAccessFilterEnabled() { + return accessFilterEnabled; + } + /** + * @return the webAppRootURL + */ + public String getWebAppRootURL() { + return webappRootURL; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/common/RangerConstants.java b/security-admin/src/main/java/org/apache/ranger/common/RangerConstants.java index 33330d1797..99b6821d49 100644 --- a/security-admin/src/main/java/org/apache/ranger/common/RangerConstants.java +++ b/security-admin/src/main/java/org/apache/ranger/common/RangerConstants.java @@ -17,7 +17,7 @@ * under the License. */ - /** +/** * */ @@ -28,169 +28,147 @@ import java.util.List; public class RangerConstants extends RangerCommonEnums { - - // 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_KEY_ADMIN = "ROLE_KEY_ADMIN"; - 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"; - public final static String ROLE_ADMIN_AUDITOR = "ROLE_ADMIN_AUDITOR"; - public final static String ROLE_KEY_ADMIN_AUDITOR = "ROLE_KEY_ADMIN_AUDITOR"; - public final static String ROLE_FIELD = "Roles"; - // 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"; - - //Permission Names - public static final String MODULE_RESOURCE_BASED_POLICIES="Resource Based Policies"; - public static final String MODULE_USER_GROUPS="Users/Groups"; - public static final String MODULE_REPORTS="Reports"; - public static final String MODULE_AUDIT="Audit"; - public static final String MODULE_PERMISSION="Permissions"; - public static final String MODULE_KEY_MANAGER="Key Manager"; - public static final String MODULE_TAG_BASED_POLICIES="Tag Based Policies"; - public static final String MODULE_SECURITY_ZONE="Security Zone"; - public static final String MODULE_GOVERNED_DATA_SHARING = "Governed Data Sharing"; - - // 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 ."; - 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 = - - 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; - - //Constant for Tag_Service Type. - public final static int TAG_SERVICE_TYPE = 100; - - public static final List VALID_USER_ROLE_LIST = new ArrayList(Arrays.asList(RangerConstants.ROLE_USER, - RangerConstants.ROLE_SYS_ADMIN, RangerConstants.ROLE_KEY_ADMIN, RangerConstants.ROLE_ADMIN_AUDITOR, - RangerConstants.ROLE_KEY_ADMIN_AUDITOR)); - - public static final String DEFAULT_SORT_ORDER = "asc"; - - public static enum RBAC_PERM { - ALLOW_NONE, - ALLOW_READ, - ALLOW_WRITE, - ALLOW_DELETE - } - //HTTP STATUS code for authentication timeout - public static final int SC_AUTHENTICATION_TIMEOUT = 419; + // Default Roles + public static final String ROLE_SYS_ADMIN = "ROLE_SYS_ADMIN"; + public static final String ROLE_ADMIN = "ROLE_ADMIN"; + public static final String ROLE_INTEGRATOR = "ROLE_INTEGRATOR"; + public static final String ROLE_DATA_ANALYST = "ROLE_DATA_ANALYST"; + public static final String ROLE_BIZ_MGR = "ROLE_BIZ_MGR"; + public static final String ROLE_KEY_ADMIN = "ROLE_KEY_ADMIN"; + public static final String ROLE_USER = "ROLE_USER"; + public static final String ROLE_ANON = "ROLE_ANON"; + public static final String ROLE_OTHER = "ROLE_OTHER"; + public static final String GROUP_PUBLIC = "public"; + public static final String ROLE_ADMIN_AUDITOR = "ROLE_ADMIN_AUDITOR"; + public static final String ROLE_KEY_ADMIN_AUDITOR = "ROLE_KEY_ADMIN_AUDITOR"; + public static final String ROLE_FIELD = "Roles"; + + // Action constants + public static final String ACTION_EDIT = "edit"; + public static final String ACTION_CHANGE = "change"; + public static final String ACTION_DELETE = "delete"; + public static final String ACTION_MARK_SPAM = "mark_spam"; + public static final String ACTION_RATE = "rate"; + public static final String ACTION_SELECT = "select"; + public static final String ACTION_UNSELECT = "unselect"; + public static final String ACTION_HIDE = "hide"; + public static final String ACTION_UNHIDE = "unhide"; + public static final String ACTION_SHARE = "share"; + public static final String ACTION_UNSHARE = "unshare"; + public static final String ACTION_BOOKMARK = "bookmark"; + public static final 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"; + + //Permission Names + public static final String MODULE_RESOURCE_BASED_POLICIES = "Resource Based Policies"; + public static final String MODULE_USER_GROUPS = "Users/Groups"; + public static final String MODULE_REPORTS = "Reports"; + public static final String MODULE_AUDIT = "Audit"; + public static final String MODULE_PERMISSION = "Permissions"; + public static final String MODULE_KEY_MANAGER = "Key Manager"; + public static final String MODULE_TAG_BASED_POLICIES = "Tag Based Policies"; + public static final String MODULE_SECURITY_ZONE = "Security Zone"; + public static final String MODULE_GOVERNED_DATA_SHARING = "Governed Data Sharing"; + public static final String USER_PENDING_APPROVAL_MSG = "User is yet not reviewed by Administrator. Please contact at ."; + + // these constants will be used in setting GjResponse object. + public static final int USER_PENDING_APPROVAL_STATUS_CODE = 0; + public static final String USER_APPROVAL_MSG = "User is approved"; + public static final int USER_APPROVAL_STATUS_CODE = 1; + public static final String USER_REJECTION_MSG = "User is rejected"; + public static final int USER_REJECTION_STATUS_CODE = 1; + public static final String USER_STATUS_ALREADY_CHANGED_MSG = "Can not change user status. it is either already activated/approved/rejected"; + public static final int USER_STATUS_ALREADY_CHANGED_STATUS_CODE = 0; + public static final 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 static final int USER_ALREADY_ACTIVATED_STATUS_CODE = 0; + public static final String USER_STATUS_NOT_ACTIVE_MSG = "User is not in active status. Please activate your account first."; + public static final int USER_STATUS_NOT_ACTIVE_STATUS_CODE = 0; + public static final String INVALID_EMAIL_ADDRESS_MSG = "Invalid email address"; + public static final int INVALID_EMAIL_ADDRESS_STATUS_CODE = 0; + public static final String WRONG_ACTIVATION_CODE_MSG = "Wrong activation code"; + public static final int WRONG_ACTIVATION_CODE_STATUS_CODE = 0; + public static final String VALID_EMAIL_ADDRESS_MSG = "Valid email address"; + public static final int VALID_EMAIL_ADDRESS_STATUS_CODE = 1; + public static final String NO_ACTIVATION_RECORD_FOR_USER_ERR_MSG = "No activation record found for user:"; + public static final String NO_ACTIVATION_ENTRY = "activation entry not found"; + public static final String VALIDATION_INVALID_DATA_DESC = "Invalid value for"; + public static final int VALIDATION_INVALID_DATA_CODE = 0; + public static final String GROUP_MODERATORS = "GROUP_MODERATORS"; + public static final String PWD_RESET_FAILED_MSG = "Invalid password reset request"; + + // public static final String EMAIL_WELCOME_MSG = + // "Welcome to iSchoolCircle"; + // public static final 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 = + public static final 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; + + //Constant for Tag_Service Type. + public static final int TAG_SERVICE_TYPE = 100; + + public static final List VALID_USER_ROLE_LIST = new ArrayList<>(Arrays.asList(RangerConstants.ROLE_USER, + RangerConstants.ROLE_SYS_ADMIN, RangerConstants.ROLE_KEY_ADMIN, RangerConstants.ROLE_ADMIN_AUDITOR, + RangerConstants.ROLE_KEY_ADMIN_AUDITOR)); + + public static final String DEFAULT_SORT_ORDER = "asc"; + + //HTTP STATUS code for authentication timeout + public static final int SC_AUTHENTICATION_TIMEOUT = 419; + + // 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"); + + final String rbKey; + final String message; + + ValidationUserProfile(String rbKey, String message) { + this.rbKey = rbKey; + this.message = message; + } + } + + public enum RBAC_PERM { + ALLOW_NONE, + ALLOW_READ, + ALLOW_WRITE, + ALLOW_DELETE + } } diff --git a/security-admin/src/main/java/org/apache/ranger/common/RangerFactory.java b/security-admin/src/main/java/org/apache/ranger/common/RangerFactory.java index 136083b80d..e111298dc9 100644 --- a/security-admin/src/main/java/org/apache/ranger/common/RangerFactory.java +++ b/security-admin/src/main/java/org/apache/ranger/common/RangerFactory.java @@ -27,7 +27,7 @@ @Service @Scope("singleton") public class RangerFactory { - public RangerPolicyResourceSignature createPolicyResourceSignature(RangerPolicy policy) { - return new RangerPolicyResourceSignature(policy); - } + public RangerPolicyResourceSignature createPolicyResourceSignature(RangerPolicy policy) { + return new RangerPolicyResourceSignature(policy); + } } diff --git a/security-admin/src/main/java/org/apache/ranger/common/RangerJAXBContextResolver.java b/security-admin/src/main/java/org/apache/ranger/common/RangerJAXBContextResolver.java index 1373ecd050..8e6ba53437 100644 --- a/security-admin/src/main/java/org/apache/ranger/common/RangerJAXBContextResolver.java +++ b/security-admin/src/main/java/org/apache/ranger/common/RangerJAXBContextResolver.java @@ -17,55 +17,54 @@ * under the License. */ - package org.apache.ranger.common; +package org.apache.ranger.common; + +import com.sun.jersey.api.json.JSONConfiguration; +import com.sun.jersey.api.json.JSONJAXBContext; 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 RangerJAXBContextResolver implements ContextResolver { - - 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 + private final JAXBContext context; + private final 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 RangerJAXBContextResolver() throws Exception { - JSONConfiguration config = JSONConfiguration.natural().build(); - context = new JSONJAXBContext(config, types); + 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; + // return context; + for (Class type : types) { + if (type.getName().equals(objectType.getName())) { + return context; + } + } + + return null; } } - diff --git a/security-admin/src/main/java/org/apache/ranger/common/RangerJsonMappingExceptionMapper.java b/security-admin/src/main/java/org/apache/ranger/common/RangerJsonMappingExceptionMapper.java index c098a9762f..704b0ea2e9 100644 --- a/security-admin/src/main/java/org/apache/ranger/common/RangerJsonMappingExceptionMapper.java +++ b/security-admin/src/main/java/org/apache/ranger/common/RangerJsonMappingExceptionMapper.java @@ -6,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + *

+ * http://www.apache.org/licenses/LICENSE-2.0 + *

* Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,11 +20,11 @@ import com.fasterxml.jackson.databind.JsonMappingException; import org.apache.hadoop.util.HttpExceptionUtils; import org.springframework.stereotype.Component; + import javax.ws.rs.core.Response; import javax.ws.rs.ext.ExceptionMapper; import javax.ws.rs.ext.Provider; - /** * Invalid attribute type or Invalid JSON format in JSON request body * @@ -37,8 +37,8 @@ @Component @Provider public class RangerJsonMappingExceptionMapper implements ExceptionMapper { - @Override - public Response toResponse(JsonMappingException excp) { - return HttpExceptionUtils.createJerseyExceptionResponse(Response.Status.BAD_REQUEST, excp); - } + @Override + public Response toResponse(JsonMappingException excp) { + return HttpExceptionUtils.createJerseyExceptionResponse(Response.Status.BAD_REQUEST, excp); + } } diff --git a/security-admin/src/main/java/org/apache/ranger/common/RangerJsonParserExceptionMapper.java b/security-admin/src/main/java/org/apache/ranger/common/RangerJsonParserExceptionMapper.java index f793654972..a0d88bdd54 100644 --- a/security-admin/src/main/java/org/apache/ranger/common/RangerJsonParserExceptionMapper.java +++ b/security-admin/src/main/java/org/apache/ranger/common/RangerJsonParserExceptionMapper.java @@ -6,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + *

+ * http://www.apache.org/licenses/LICENSE-2.0 + *

* Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,14 +17,13 @@ */ package org.apache.ranger.common; -import javax.ws.rs.core.Response; -import javax.ws.rs.ext.ExceptionMapper; -import javax.ws.rs.ext.Provider; - import com.fasterxml.jackson.core.JsonParseException; import org.apache.hadoop.util.HttpExceptionUtils; import org.springframework.stereotype.Component; +import javax.ws.rs.core.Response; +import javax.ws.rs.ext.ExceptionMapper; +import javax.ws.rs.ext.Provider; /** * Invalid JSON format @@ -34,8 +33,8 @@ @Component @Provider public class RangerJsonParserExceptionMapper implements ExceptionMapper { - @Override - public Response toResponse(JsonParseException excp) { - return HttpExceptionUtils.createJerseyExceptionResponse(Response.Status.BAD_REQUEST, excp); - } + @Override + public Response toResponse(JsonParseException excp) { + return HttpExceptionUtils.createJerseyExceptionResponse(Response.Status.BAD_REQUEST, excp); + } } diff --git a/security-admin/src/main/java/org/apache/ranger/common/RangerJsonProvider.java b/security-admin/src/main/java/org/apache/ranger/common/RangerJsonProvider.java index cd5ad385aa..8a04d696a9 100644 --- a/security-admin/src/main/java/org/apache/ranger/common/RangerJsonProvider.java +++ b/security-admin/src/main/java/org/apache/ranger/common/RangerJsonProvider.java @@ -6,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + *

+ * http://www.apache.org/licenses/LICENSE-2.0 + *

* Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -29,7 +29,6 @@ import javax.ws.rs.core.MediaType; import javax.ws.rs.ext.Provider; - @Provider @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) diff --git a/security-admin/src/main/java/org/apache/ranger/common/RangerProperties.java b/security-admin/src/main/java/org/apache/ranger/common/RangerProperties.java index 1787e19a02..c1671a845d 100644 --- a/security-admin/src/main/java/org/apache/ranger/common/RangerProperties.java +++ b/security-admin/src/main/java/org/apache/ranger/common/RangerProperties.java @@ -19,36 +19,32 @@ package org.apache.ranger.common; -import java.util.HashMap; - import org.apache.ranger.plugin.util.XMLUtils; -public class RangerProperties extends HashMap { - - private static final long serialVersionUID = -4094378755892810987L; +import java.util.HashMap; - private static final String XMLCONFIG_FILENAME_DELIMITOR = ","; +public class RangerProperties extends HashMap { + private static final long serialVersionUID = -4094378755892810987L; - private String xmlConfigFileNames = null; + private static final String XMLCONFIG_FILENAME_DELIMITOR = ","; - public RangerProperties(String xmlConfigFileNames) { - this.xmlConfigFileNames = xmlConfigFileNames; - initProperties(); - } + private String xmlConfigFileNames; - private void initProperties() { - - if (xmlConfigFileNames == null || xmlConfigFileNames.isEmpty()) { - return; - } + public RangerProperties(String xmlConfigFileNames) { + this.xmlConfigFileNames = xmlConfigFileNames; - String[] fnList = xmlConfigFileNames.split(XMLCONFIG_FILENAME_DELIMITOR); + initProperties(); + } - for (String fn : fnList) { - XMLUtils.loadConfig(fn, this); - } + private void initProperties() { + if (xmlConfigFileNames == null || xmlConfigFileNames.isEmpty()) { + return; + } - } + String[] fnList = xmlConfigFileNames.split(XMLCONFIG_FILENAME_DELIMITOR); - + for (String fn : fnList) { + XMLUtils.loadConfig(fn, this); + } + } } diff --git a/security-admin/src/main/java/org/apache/ranger/common/RangerRoleCache.java b/security-admin/src/main/java/org/apache/ranger/common/RangerRoleCache.java index 933104a16f..247a48b468 100644 --- a/security-admin/src/main/java/org/apache/ranger/common/RangerRoleCache.java +++ b/security-admin/src/main/java/org/apache/ranger/common/RangerRoleCache.java @@ -22,7 +22,6 @@ import org.apache.ranger.authorization.hadoop.config.RangerAdminConfig; import org.apache.ranger.biz.RoleDBStore; import org.apache.ranger.plugin.model.RangerRole; - import org.apache.ranger.plugin.util.RangerRoles; import org.apache.ranger.plugin.util.SearchFilter; import org.slf4j.Logger; @@ -35,118 +34,115 @@ import java.util.concurrent.locks.ReentrantLock; public class RangerRoleCache { - private static final Logger LOG = LoggerFactory.getLogger(RangerRoleCache.class); - - private static final int MAX_WAIT_TIME_FOR_UPDATE = 10; - - private static volatile RangerRoleCache sInstance = null; - - private final int waitTimeInSeconds; - private final ReentrantLock lock = new ReentrantLock(); - - RangerRoleCacheWrapper roleCacheWrapper = null; - - public static RangerRoleCache getInstance() { - if (sInstance == null) { - synchronized (RangerRoleCache.class) { - if (sInstance == null) { - sInstance = new RangerRoleCache(); - } - } - } - return sInstance; - } - - private RangerRoleCache() { - RangerAdminConfig config = RangerAdminConfig.getInstance(); - - waitTimeInSeconds = config.getInt("ranger.admin.policy.download.cache.max.waittime.for.update", MAX_WAIT_TIME_FOR_UPDATE); - } - - public RangerRoles getLatestRangerRoleOrCached(String serviceName, RoleDBStore roleDBStore, Long lastKnownRoleVersion, Long rangerRoleVersionInDB) throws Exception { - final RangerRoles ret; - - if (lastKnownRoleVersion == null || !lastKnownRoleVersion.equals(rangerRoleVersionInDB)) { - roleCacheWrapper = new RangerRoleCacheWrapper(); - ret = roleCacheWrapper.getLatestRangerRoles(serviceName, roleDBStore, lastKnownRoleVersion, rangerRoleVersionInDB); - } else { - ret = null; - } - - return ret; - } - - private class RangerRoleCacheWrapper { - RangerRoles roles; - Long rolesVersion; - - RangerRoleCacheWrapper() { - this.roles = null; - this.rolesVersion = -1L; - } - - public RangerRoles getRoles() { - return this.roles; - } - - public Long getRolesVersion() { - return this.rolesVersion; - } - - public RangerRoles getLatestRangerRoles(String serviceName, RoleDBStore roleDBStore, Long lastKnownRoleVersion, Long rolesVersionInDB) throws Exception { - RangerRoles ret = null; - boolean lockResult = false; - - if (LOG.isDebugEnabled()) { - LOG.debug("==> RangerRoleCache.getLatestRangerRoles(ServiceName= " + serviceName + " lastKnownRoleVersion= " + lastKnownRoleVersion + " rolesVersionInDB= " + rolesVersionInDB + ")"); - } - - try { - lockResult = lock.tryLock(waitTimeInSeconds, TimeUnit.SECONDS); - - if (lockResult) { - // We are getting all the Roles to be downloaded for now. Should do downloades for each service based on what roles are there in the policies. - final long startTimeMs = System.currentTimeMillis(); - SearchFilter searchFilter = null; - final Set rolesInDB = new HashSet<>(roleDBStore.getRoles(searchFilter)); - final long dbLoadTimeMs = System.currentTimeMillis() - startTimeMs; - Date updateTime = new Date(); - - if (rolesInDB != null) { - if (LOG.isDebugEnabled()) { - LOG.debug("loading Roles from database and it took:" + TimeUnit.MILLISECONDS.toSeconds(dbLoadTimeMs) + " seconds"); - } - ret = new RangerRoles(); - - ret.setRangerRoles(rolesInDB); - ret.setRoleUpdateTime(updateTime); - ret.setRoleVersion(rolesVersionInDB); - - rolesVersion = rolesVersionInDB; - roles = ret; - } else { - LOG.error("Could not get Ranger Roles from database ..."); - } - } else { - if (LOG.isDebugEnabled()) { - LOG.debug("Could not get lock in [" + waitTimeInSeconds + "] seconds, returning cached RangerRoles"); - } - ret = getRoles(); - } - } catch (InterruptedException exception) { - LOG.error("RangerRoleCache.getLatestRangerRoles:lock got interrupted..", exception); - } finally { - if (lockResult) { - lock.unlock(); - } - } - - if (LOG.isDebugEnabled()) { - LOG.debug("<== RangerRoleCache.getLatestRangerRoles(ServiceName= " + serviceName + " lastKnownRoleVersion= " + lastKnownRoleVersion + " rolesVersionInDB= " + rolesVersionInDB + " RangerRoles= " + ret + ")"); - } - - return ret; - } - } -} + private static final Logger LOG = LoggerFactory.getLogger(RangerRoleCache.class); + + private static final int MAX_WAIT_TIME_FOR_UPDATE = 10; + + private static volatile RangerRoleCache sInstance; + + private final int waitTimeInSeconds; + private final ReentrantLock lock = new ReentrantLock(); + + RangerRoleCacheWrapper roleCacheWrapper; + + private RangerRoleCache() { + RangerAdminConfig config = RangerAdminConfig.getInstance(); + + waitTimeInSeconds = config.getInt("ranger.admin.policy.download.cache.max.waittime.for.update", MAX_WAIT_TIME_FOR_UPDATE); + } + + public static RangerRoleCache getInstance() { + RangerRoleCache me = sInstance; + + if (me == null) { + synchronized (RangerRoleCache.class) { + me = sInstance; + + if (me == null) { + me = new RangerRoleCache(); + sInstance = me; + } + } + } + + return me; + } + + public RangerRoles getLatestRangerRoleOrCached(String serviceName, RoleDBStore roleDBStore, Long lastKnownRoleVersion, Long rangerRoleVersionInDB) throws Exception { + final RangerRoles ret; + + if (lastKnownRoleVersion == null || !lastKnownRoleVersion.equals(rangerRoleVersionInDB)) { + roleCacheWrapper = new RangerRoleCacheWrapper(); + ret = roleCacheWrapper.getLatestRangerRoles(serviceName, roleDBStore, lastKnownRoleVersion, rangerRoleVersionInDB); + } else { + ret = null; + } + + return ret; + } + private class RangerRoleCacheWrapper { + RangerRoles roles; + Long rolesVersion; + + RangerRoleCacheWrapper() { + this.roles = null; + this.rolesVersion = -1L; + } + + public RangerRoles getRoles() { + return this.roles; + } + + public Long getRolesVersion() { + return this.rolesVersion; + } + + public RangerRoles getLatestRangerRoles(String serviceName, RoleDBStore roleDBStore, Long lastKnownRoleVersion, Long rolesVersionInDB) throws Exception { + RangerRoles ret = null; + boolean lockResult = false; + + LOG.debug("==> RangerRoleCache.getLatestRangerRoles(ServiceName= {} lastKnownRoleVersion= {} rolesVersionInDB= {})", serviceName, lastKnownRoleVersion, rolesVersionInDB); + + try { + lockResult = lock.tryLock(waitTimeInSeconds, TimeUnit.SECONDS); + + if (lockResult) { + // We are getting all the Roles to be downloaded for now. Should do downloades for each service based on what roles are there in the policies. + final long startTimeMs = System.currentTimeMillis(); + SearchFilter searchFilter = null; + final Set rolesInDB = new HashSet<>(roleDBStore.getRoles(searchFilter)); + final long dbLoadTimeMs = System.currentTimeMillis() - startTimeMs; + Date updateTime = new Date(); + + if (LOG.isDebugEnabled()) { + LOG.debug("loading Roles from database and it took:{} seconds", TimeUnit.MILLISECONDS.toSeconds(dbLoadTimeMs)); + } + + ret = new RangerRoles(); + + ret.setRangerRoles(rolesInDB); + ret.setRoleUpdateTime(updateTime); + ret.setRoleVersion(rolesVersionInDB); + + rolesVersion = rolesVersionInDB; + roles = ret; + } else { + LOG.debug("Could not get lock in [{}] seconds, returning cached RangerRoles", waitTimeInSeconds); + + ret = getRoles(); + } + } catch (InterruptedException exception) { + LOG.error("RangerRoleCache.getLatestRangerRoles:lock got interrupted..", exception); + } finally { + if (lockResult) { + lock.unlock(); + } + } + + LOG.debug("<== RangerRoleCache.getLatestRangerRoles(ServiceName= {} lastKnownRoleVersion= {} rolesVersionInDB= {} RangerRoles= {})", serviceName, lastKnownRoleVersion, rolesVersionInDB, ret); + + return ret; + } + } +} diff --git a/security-admin/src/main/java/org/apache/ranger/common/RangerSearchUtil.java b/security-admin/src/main/java/org/apache/ranger/common/RangerSearchUtil.java index 0f143e303d..4da6a35368 100755 --- a/security-admin/src/main/java/org/apache/ranger/common/RangerSearchUtil.java +++ b/security-admin/src/main/java/org/apache/ranger/common/RangerSearchUtil.java @@ -17,14 +17,7 @@ * under the License. */ - package org.apache.ranger.common; - -import java.util.*; - -import javax.annotation.Nonnull; -import javax.persistence.EntityManager; -import javax.persistence.Query; -import javax.servlet.http.HttpServletRequest; +package org.apache.ranger.common; import org.apache.commons.collections.MapUtils; import org.apache.commons.lang.ArrayUtils; @@ -35,677 +28,694 @@ import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; +import javax.annotation.Nonnull; +import javax.persistence.EntityManager; +import javax.persistence.Query; +import javax.servlet.http.HttpServletRequest; + +import java.util.ArrayList; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + @Component public class RangerSearchUtil extends SearchUtil { - final static Logger logger = LoggerFactory.getLogger(RangerSearchUtil.class); - - int dbMinInListLength = 20; - - public RangerSearchUtil() { - dbMinInListLength = PropertiesUtil.getIntProperty("ranger.db.min_inlist", dbMinInListLength); - } - - public SearchFilter getSearchFilter(@Nonnull HttpServletRequest request, List sortFields) { - Validate.notNull(request, "request"); - SearchFilter ret = new SearchFilter(); - - if (MapUtils.isEmpty(request.getParameterMap())) { - ret.setParams(new HashMap()); - } - - ret.setParam(SearchFilter.SERVICE_TYPE, request.getParameter(SearchFilter.SERVICE_TYPE)); - ret.setParam(SearchFilter.SERVICE_TYPE_DISPLAY_NAME, request.getParameter(SearchFilter.SERVICE_TYPE_DISPLAY_NAME)); - ret.setParam(SearchFilter.SERVICE_TYPE_ID, request.getParameter(SearchFilter.SERVICE_TYPE_ID)); - ret.setParam(SearchFilter.SERVICE_NAME, request.getParameter(SearchFilter.SERVICE_NAME)); - ret.setParam(SearchFilter.SERVICE_DISPLAY_NAME, request.getParameter(SearchFilter.SERVICE_DISPLAY_NAME)); - ret.setParam(SearchFilter.SERVICE_NAME_PARTIAL, request.getParameter(SearchFilter.SERVICE_NAME_PARTIAL)); - ret.setParam(SearchFilter.SERVICE_DISPLAY_NAME_PARTIAL, request.getParameter(SearchFilter.SERVICE_DISPLAY_NAME_PARTIAL)); - ret.setParam(SearchFilter.SERVICE_ID, request.getParameter(SearchFilter.SERVICE_ID)); - ret.setParam(SearchFilter.POLICY_NAME, request.getParameter(SearchFilter.POLICY_NAME)); - ret.setParam(SearchFilter.POLICY_NAME_PARTIAL, request.getParameter(SearchFilter.POLICY_NAME_PARTIAL)); - ret.setParam(SearchFilter.POLICY_ID, request.getParameter(SearchFilter.POLICY_ID)); - ret.setParam(SearchFilter.IS_ENABLED, request.getParameter(SearchFilter.IS_ENABLED)); - ret.setParam(SearchFilter.IS_RECURSIVE, request.getParameter(SearchFilter.IS_RECURSIVE)); - ret.setParam(SearchFilter.USER, request.getParameter(SearchFilter.USER)); - ret.setParam(SearchFilter.GROUP, request.getParameter(SearchFilter.GROUP)); - ret.setParam(SearchFilter.ROLE, request.getParameter(SearchFilter.ROLE)); - ret.setParam(SearchFilter.POL_RESOURCE, request.getParameter(SearchFilter.POL_RESOURCE)); - ret.setParam(SearchFilter.RESOURCE_SIGNATURE, request.getParameter(SearchFilter.RESOURCE_SIGNATURE)); - ret.setParam(SearchFilter.POLICY_TYPE, request.getParameter(SearchFilter.POLICY_TYPE)); - ret.setParam(SearchFilter.POLICY_LABEL, request.getParameter(SearchFilter.POLICY_LABEL)); - ret.setParam(SearchFilter.POLICY_LABELS_PARTIAL, request.getParameter(SearchFilter.POLICY_LABELS_PARTIAL)); - ret.setParam(SearchFilter.PLUGIN_HOST_NAME, request.getParameter(SearchFilter.PLUGIN_HOST_NAME)); - ret.setParam(SearchFilter.PLUGIN_APP_TYPE, request.getParameter(SearchFilter.PLUGIN_APP_TYPE)); - ret.setParam(SearchFilter.PLUGIN_ENTITY_TYPE, request.getParameter(SearchFilter.PLUGIN_ENTITY_TYPE)); - ret.setParam(SearchFilter.PLUGIN_IP_ADDRESS, request.getParameter(SearchFilter.PLUGIN_IP_ADDRESS)); - ret.setParam(SearchFilter.ZONE_NAME, request.getParameter(SearchFilter.ZONE_NAME)); - ret.setParam(SearchFilter.ZONE_NAME_PARTIAL, request.getParameter(SearchFilter.ZONE_NAME_PARTIAL)); - ret.setParam(SearchFilter.ZONE_ID, request.getParameter(SearchFilter.ZONE_ID)); - ret.setParam(SearchFilter.TAG_SERVICE_ID, request.getParameter(SearchFilter.TAG_SERVICE_ID)); - ret.setParam(SearchFilter.ROLE_NAME, request.getParameter(SearchFilter.ROLE_NAME)); - ret.setParam(SearchFilter.ROLE_ID, request.getParameter(SearchFilter.ROLE_ID)); - ret.setParam(SearchFilter.GROUP_NAME, request.getParameter(SearchFilter.GROUP_NAME)); - ret.setParam(SearchFilter.USER_NAME, request.getParameter(SearchFilter.USER_NAME)); - ret.setParam(SearchFilter.ROLE_NAME_PARTIAL, request.getParameter(SearchFilter.ROLE_NAME_PARTIAL)); - ret.setParam(SearchFilter.GROUP_NAME_PARTIAL, request.getParameter(SearchFilter.GROUP_NAME_PARTIAL)); - ret.setParam(SearchFilter.USER_NAME_PARTIAL, request.getParameter(SearchFilter.USER_NAME_PARTIAL)); - ret.setParam(SearchFilter.CLUSTER_NAME, request.getParameter(SearchFilter.CLUSTER_NAME)); - ret.setParam(SearchFilter.FETCH_ZONE_UNZONE_POLICIES, request.getParameter(SearchFilter.FETCH_ZONE_UNZONE_POLICIES)); - ret.setParam(SearchFilter.FETCH_TAG_POLICIES, request.getParameter(SearchFilter.FETCH_TAG_POLICIES)); - ret.setParam(SearchFilter.SERVICE_NAME_PREFIX, request.getParameter(SearchFilter.SERVICE_NAME_PREFIX)); - ret.setParam(SearchFilter.ZONE_NAME_PREFIX, request.getParameter(SearchFilter.ZONE_NAME_PREFIX)); - ret.setParam(SearchFilter.TAG_TYPE, request.getParameter(SearchFilter.TAG_TYPE)); - ret.setParam(SearchFilter.TAG_TYPE_PARTIAL, request.getParameter(SearchFilter.TAG_TYPE_PARTIAL)); - ret.setParam(SearchFilter.TAG_SOURCE, request.getParameter(SearchFilter.TAG_SOURCE)); - ret.setParam(SearchFilter.TAG_SOURCE_PARTIAL, request.getParameter(SearchFilter.TAG_SOURCE_PARTIAL)); - ret.setParam(SearchFilter.TAG_SERVICE_NAME, request.getParameter(SearchFilter.TAG_SERVICE_NAME)); - ret.setParam(SearchFilter.TAG_SERVICE_NAME_PARTIAL, request.getParameter(SearchFilter.TAG_SERVICE_NAME_PARTIAL)); - ret.setParam(SearchFilter.TAG_RESOURCE_GUID, request.getParameter(SearchFilter.TAG_RESOURCE_GUID)); - ret.setParam(SearchFilter.TAG_RESOURCE_SIGNATURE, request.getParameter(SearchFilter.TAG_RESOURCE_SIGNATURE)); - ret.setParam(SearchFilter.TAG_RESOURCE_ELEMENTS, request.getParameter(SearchFilter.TAG_RESOURCE_ELEMENTS)); - ret.setParam(SearchFilter.TAG_DEF_GUID, request.getParameter(SearchFilter.TAG_DEF_GUID)); - ret.setParam(SearchFilter.TAG_DEF_ID, request.getParameter(SearchFilter.TAG_DEF_ID)); - ret.setParam(SearchFilter.TAG_ID, request.getParameter(SearchFilter.TAG_ID)); - ret.setParam(SearchFilter.CREATED_BY, request.getParameter(SearchFilter.CREATED_BY)); - ret.setParam(SearchFilter.APPROVER, request.getParameter(SearchFilter.APPROVER)); - ret.setParam(SearchFilter.SHARE_STATUS, request.getParameter(SearchFilter.SHARE_STATUS)); - - for (Map.Entry e : request.getParameterMap().entrySet()) { - String name = e.getKey(); - String[] values = e.getValue(); - - if (!StringUtils.isEmpty(name) && !ArrayUtils.isEmpty(values) - && name.startsWith(SearchFilter.RESOURCE_PREFIX)) { - ret.setParam(name, values[0]); - } - } - ret.setParam(SearchFilter.RESOURCE_MATCH_SCOPE, request.getParameter(SearchFilter.RESOURCE_MATCH_SCOPE)); - - ret.setParam(SearchFilter.DATASET_NAME, request.getParameter(SearchFilter.DATASET_NAME)); - ret.setParam(SearchFilter.DATASET_NAME_PARTIAL, request.getParameter(SearchFilter.DATASET_NAME_PARTIAL)); - ret.setParam(SearchFilter.DATASET_ID, request.getParameter(SearchFilter.DATASET_ID)); - ret.setParam(SearchFilter.DATASET_LABEL, request.getParameter(SearchFilter.DATASET_LABEL)); - ret.setParam(SearchFilter.DATASET_KEYWORD, request.getParameter(SearchFilter.DATASET_KEYWORD)); - ret.setParam(SearchFilter.PROJECT_NAME, request.getParameter(SearchFilter.PROJECT_NAME)); - ret.setParam(SearchFilter.PROJECT_NAME_PARTIAL, request.getParameter(SearchFilter.PROJECT_NAME_PARTIAL)); - ret.setParam(SearchFilter.PROJECT_ID, request.getParameter(SearchFilter.PROJECT_ID)); - ret.setParam(SearchFilter.DATA_SHARE_NAME, request.getParameter(SearchFilter.DATA_SHARE_NAME)); - ret.setParam(SearchFilter.DATA_SHARE_NAME_PARTIAL, request.getParameter(SearchFilter.DATA_SHARE_NAME_PARTIAL)); - ret.setParam(SearchFilter.DATA_SHARE_ID, request.getParameter(SearchFilter.DATA_SHARE_ID)); - ret.setParam(SearchFilter.EXCLUDE_DATASET_ID, request.getParameter(SearchFilter.EXCLUDE_DATASET_ID)); - ret.setParam(SearchFilter.SHARED_RESOURCE_ID, request.getParameter(SearchFilter.SHARED_RESOURCE_ID)); - ret.setParam(SearchFilter.SHARED_RESOURCE_NAME, request.getParameter(SearchFilter.SHARED_RESOURCE_NAME)); - ret.setParam(SearchFilter.SHARED_RESOURCE_NAME_PARTIAL, request.getParameter(SearchFilter.SHARED_RESOURCE_NAME_PARTIAL)); - ret.setParam(SearchFilter.PROFILE_NAME, request.getParameter(SearchFilter.PROFILE_NAME)); - ret.setParam(SearchFilter.OWNER_NAME, request.getParameter(SearchFilter.OWNER_NAME)); - ret.setParam(SearchFilter.OWNER_TYPE, request.getParameter(SearchFilter.OWNER_TYPE)); - ret.setParam(SearchFilter.GDS_PERMISSION, request.getParameter(SearchFilter.GDS_PERMISSION)); - ret.setParam(SearchFilter.CREATE_TIME_START, request.getParameter(SearchFilter.CREATE_TIME_START)); - ret.setParam(SearchFilter.CREATE_TIME_END, request.getParameter(SearchFilter.CREATE_TIME_END)); - ret.setParam(SearchFilter.UPDATE_TIME_START, request.getParameter(SearchFilter.UPDATE_TIME_START)); - ret.setParam(SearchFilter.UPDATE_TIME_END, request.getParameter(SearchFilter.UPDATE_TIME_END)); - ret.setParam(SearchFilter.RESOURCE_CONTAINS, request.getParameter(SearchFilter.RESOURCE_CONTAINS)); - ret.setParam(SearchFilter.SHARED_WITH_ME, request.getParameter(SearchFilter.SHARED_WITH_ME)); - - extractCommonCriteriasForFilter(request, ret, sortFields); - - return ret; - } - - public SearchFilter getSearchFilterFromLegacyRequestForRepositorySearch(HttpServletRequest request, List sortFields) { - if (request == null) { - return null; - } - - SearchFilter ret = new SearchFilter(); - - if (MapUtils.isEmpty(request.getParameterMap())) { - ret.setParams(new HashMap()); - } - - ret.setParam(SearchFilter.SERVICE_NAME, request.getParameter("name")); - ret.setParam(SearchFilter.IS_ENABLED, request.getParameter("status")); - String serviceType = request.getParameter("type"); - if (serviceType != null) { - serviceType = serviceType.toLowerCase(); - } - ret.setParam(SearchFilter.SERVICE_TYPE,serviceType); - extractCommonCriteriasForFilter(request, ret, sortFields); - - return ret; - } - - - public SearchFilter getSearchFilterFromLegacyRequest(HttpServletRequest request, List sortFields) { - Validate.notNull(request, "request"); - SearchFilter ret = new SearchFilter(); - - if (MapUtils.isEmpty(request.getParameterMap())) { - ret.setParams(new HashMap()); - } - - String repositoryType = request.getParameter("repositoryType"); - - if (repositoryType != null) { - repositoryType = repositoryType.toLowerCase(); - } - - String repositoryId = request.getParameter("repositoryId"); - if(repositoryId == null) { - repositoryId = request.getParameter("assetId"); - } - - ret.setParam(SearchFilter.SERVICE_TYPE, repositoryType); - ret.setParam(SearchFilter.SERVICE_NAME, request.getParameter("repositoryName")); - ret.setParam(SearchFilter.SERVICE_ID, repositoryId); - ret.setParam(SearchFilter.POLICY_NAME, request.getParameter("policyName")); - ret.setParam(SearchFilter.USER, request.getParameter("userName")); - ret.setParam(SearchFilter.GROUP, request.getParameter("groupName")); - ret.setParam(SearchFilter.IS_ENABLED, request.getParameter("isEnabled")); - ret.setParam(SearchFilter.IS_RECURSIVE, request.getParameter("isRecursive")); - ret.setParam(SearchFilter.POL_RESOURCE, request.getParameter(SearchFilter.POL_RESOURCE)); - ret.setParam(SearchFilter.RESOURCE_PREFIX + "path", request.getParameter("resourceName")); - ret.setParam(SearchFilter.RESOURCE_PREFIX + "database", request.getParameter("databases")); - ret.setParam(SearchFilter.RESOURCE_PREFIX + "table", request.getParameter("tables")); - ret.setParam(SearchFilter.RESOURCE_PREFIX + "udf", request.getParameter("udfs")); - ret.setParam(SearchFilter.RESOURCE_PREFIX + "column", request.getParameter("columns")); - ret.setParam(SearchFilter.RESOURCE_PREFIX + "column-family", request.getParameter("columnFamilies")); - ret.setParam(SearchFilter.RESOURCE_PREFIX + "topology", request.getParameter("topologies")); - ret.setParam(SearchFilter.RESOURCE_PREFIX + "service", request.getParameter("services")); - - extractCommonCriteriasForFilter(request, ret, sortFields); - - return ret; - } - - public SearchFilter extractCommonCriteriasForFilter(HttpServletRequest request, SearchFilter ret, List sortFields) { - int startIndex = restErrorUtil.parseInt(request.getParameter(SearchFilter.START_INDEX), 0, - "Invalid value for parameter startIndex", MessageEnums.INVALID_INPUT_DATA, null, - SearchFilter.START_INDEX); - startIndex = startIndex < 0 ? 0 : startIndex; - ret.setStartIndex(startIndex); - - int pageSize = restErrorUtil.parseInt(request.getParameter(SearchFilter.PAGE_SIZE), - configUtil.getDefaultMaxRows(), "Invalid value for parameter pageSize", - MessageEnums.INVALID_INPUT_DATA, null, SearchFilter.PAGE_SIZE); - ret.setMaxRows(validatePageSize(pageSize)); - - if (request.getParameter(SearchFilter.POLICY_TYPE) != null) { - int policyType = restErrorUtil.parseInt(request.getParameter(SearchFilter.POLICY_TYPE), 0, - "Invalid value for parameter policyType", MessageEnums.INVALID_INPUT_DATA, null, - SearchFilter.POLICY_TYPE); - ret.setParam(SearchFilter.POLICY_TYPE, Integer.toString(policyType)); - } - - ret.setGetCount(restErrorUtil.parseBoolean(request.getParameter("getCount"), true)); - String sortBy = restErrorUtil.validateString(request.getParameter(SearchFilter.SORT_BY), - StringUtil.VALIDATION_ALPHA, "Invalid value for parameter sortBy", MessageEnums.INVALID_INPUT_DATA, - null, SearchFilter.SORT_BY); - - if (!StringUtils.isEmpty(sortBy)) { - boolean sortSet = false; - - for (SortField sortField : sortFields) { - if (sortField.getParamName().equalsIgnoreCase(sortBy)) { - ret.setSortBy(sortField.getParamName()); - sortSet = true; - break; - } - } - - if (!sortSet) { - logger.info("Invalid or unsupported sortBy field passed. sortBy=" + sortBy, new Throwable()); - } - } - - String sortType = restErrorUtil.validateString(request.getParameter("sortType"), - StringUtil.VALIDATION_ALPHA, "Invalid value for parameter sortType", - MessageEnums.INVALID_INPUT_DATA, null, "sortType"); - ret.setSortType(sortType); - - if(ret.getParams() == null) { - ret.setParams(new HashMap()); - } - return ret; - } - - public Query createSearchQuery(EntityManager em, String queryStr, String sortClause, - SearchFilter searchCriteria, List searchFields, - boolean isCountQuery) { - return createSearchQuery(em, queryStr, sortClause, searchCriteria, searchFields, false, isCountQuery); - } - - public Query createSearchQuery(EntityManager em, String queryStr, String sortClause, - SearchFilter searchCriteria, List searchFields, - boolean hasAttributes, boolean isCountQuery) { - - StringBuilder queryClause = buildWhereClause(searchCriteria, searchFields); - super.addOrderByClause(queryClause, sortClause); - Query query = em.createQuery(queryStr + queryClause); - resolveQueryParams(query, searchCriteria, searchFields); - - final boolean skipPagination = isCountQuery || Boolean.parseBoolean(searchCriteria.getParam(SearchFilter.RETRIEVE_ALL_PAGES)); - - if (!skipPagination) { - query.setFirstResult(searchCriteria.getStartIndex()); - updateQueryPageSize(query, searchCriteria); - } - - return query; - } - - private StringBuilder buildWhereClause(SearchFilter searchCriteria, List searchFields) { - return buildWhereClause(searchCriteria, searchFields, false); - } - - private StringBuilder buildWhereClause(SearchFilter searchCriteria, - List searchFields, - boolean excludeWhereKeyword) { - - StringBuilder whereClause = new StringBuilder(excludeWhereKeyword ? "" : "WHERE 1 = 1 "); - - List joinTableList = new ArrayList(); - - for (SearchField searchField : searchFields) { - int startWhereLen = whereClause.length(); - - if (searchField.getFieldName() == null && searchField.getCustomCondition() == null) { - continue; - } - - Object[] multiValue = searchCriteria.getMultiValueParam(searchField.getClientFieldName()); - boolean isMultiValue = multiValue != null && multiValue.length > 0; - - if (searchField.getDataType() == SearchField.DATA_TYPE.INT_LIST || (isMultiValue && searchField.getDataType() == SearchField.DATA_TYPE.INTEGER)) { - List intValueList = new ArrayList<>(); - - if (isMultiValue) { - for (Object value : multiValue) { - if (value instanceof Integer || value instanceof Long) { - intValueList.add((Number) value); - } else if (value != null) { - intValueList.add(restErrorUtil.parseInt(value.toString(), "Invalid value for " + searchField.getClientFieldName(), MessageEnums.INVALID_INPUT_DATA, null, searchField.getClientFieldName())); - } - } - } else { - String paramVal = searchCriteria.getParam(searchField.getClientFieldName()); - - if (paramVal != null) { - intValueList.add(restErrorUtil.parseInt(paramVal, "Invalid value for " + searchField.getClientFieldName(), MessageEnums.INVALID_INPUT_DATA, null, searchField.getClientFieldName())); - } - } - - if (!intValueList.isEmpty()) { - if (searchField.getCustomCondition() == null) { - if (intValueList.size() <= dbMinInListLength) { - 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()).append("_").append(count); - } - - if (intValueList.size() > 1) { - whereClause.append(" ) "); - } - - } else { - whereClause.append(" and ") - .append(searchField.getFieldName()) - .append(" in ") - .append(" (:").append(searchField.getClientFieldName()).append(")"); - } - } else { - whereClause.append(" and ").append(searchField.getCustomCondition()); - } - } - } else if (searchField.getDataType() == SearchField.DATA_TYPE.STR_LIST || (isMultiValue && searchField.getDataType() == SearchField.DATA_TYPE.STRING)) { - List strValueList = new ArrayList<>(); - - for (Object value : multiValue) { - strValueList.add(String.valueOf(value)); - } - - if (!strValueList.isEmpty()) { - if (searchField.getCustomCondition() == null) { - if (strValueList.size() <= dbMinInListLength) { - whereClause.append(" and "); - - if (strValueList.size() > 1) { - whereClause.append(" ( "); - } - - for (int count = 0; count < strValueList.size(); count++) { - if (count > 0) { - whereClause.append(" or "); - } - - whereClause.append("LOWER(").append(searchField.getFieldName()).append(")") - .append(getSqlOperator(searchField.getSearchType())) - .append(":").append(searchField.getClientFieldName()).append("_").append(count); - } - - if (strValueList.size() > 1) { - whereClause.append(" ) "); - } - - } else { - whereClause.append(" and ") - .append(searchField.getFieldName()) - .append(" in ") - .append(" (:").append(searchField.getClientFieldName()).append(")"); - } - } else { - whereClause.append(" and ").append(searchField.getCustomCondition()); - } - } - } else if (searchField.getDataType() == SearchField.DATA_TYPE.INTEGER) { - Integer paramVal = restErrorUtil.parseInt(searchCriteria.getParam(searchField.getClientFieldName()), - "Invalid value for " + searchField.getClientFieldName(), - MessageEnums.INVALID_INPUT_DATA, null, searchField.getClientFieldName()); - - Number intFieldValue = paramVal != null ? (Number) paramVal : null; - if (intFieldValue != null) { - if (searchField.getCustomCondition() == null) { - whereClause.append(" and ") - .append(searchField.getFieldName()) - .append(getSqlOperator(searchField.getSearchType())) - .append(":").append(searchField.getClientFieldName()); - } else { - whereClause.append(" and ").append(searchField.getCustomCondition()); - } - } - } else if (searchField.getDataType() == SearchField.DATA_TYPE.STRING) { - String strFieldValue = searchCriteria.getParam(searchField.getClientFieldName()); - if (strFieldValue != null) { - if (searchField.getCustomCondition() == null) { - whereClause.append(" and ").append("LOWER(").append(searchField.getFieldName()).append(")") - .append(getSqlOperator(searchField.getSearchType())) - .append(":").append(searchField.getClientFieldName()); - } else { - whereClause.append(" and ").append(searchField.getCustomCondition()); - } - } - } else if (searchField.getDataType() == SearchField.DATA_TYPE.BOOLEAN) { - Boolean boolFieldValue = restErrorUtil.parseBoolean(searchCriteria.getParam(searchField.getClientFieldName()), - "Invalid value for " + searchField.getClientFieldName(), - MessageEnums.INVALID_INPUT_DATA, null, searchField.getClientFieldName()); - - if (boolFieldValue != null) { - if (searchField.getCustomCondition() == null) { - whereClause.append(" and ") - .append(searchField.getFieldName()) - .append(getSqlOperator(searchField.getSearchType())) - .append(":").append(searchField.getClientFieldName()); - } else { - whereClause.append(" and ").append(searchField.getCustomCondition()); - } - } - } else if (searchField.getDataType() == SearchField.DATA_TYPE.DATE) { - Date fieldValue = restErrorUtil.parseDate(searchCriteria.getParam(searchField.getClientFieldName()), - "Invalid value for " + searchField.getClientFieldName(), MessageEnums.INVALID_INPUT_DATA, - null, searchField.getClientFieldName(), null); - if (fieldValue != null) { - if (searchField.getCustomCondition() == null) { - whereClause.append(" and ").append(searchField.getFieldName()) - .append(getSqlOperator(searchField.getSearchType())) - .append(":").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 (String joinTable : joinTableList) { - whereClause.insert(0, ", " + joinTable + " "); - } - - return whereClause; - } - - protected void resolveQueryParams(Query query, SearchFilter searchCriteria, List searchFields) { - Map params = searchCriteria.getParams(); - Map multiValueParams = searchCriteria.getMultiValueParams(); - - for (SearchField searchField : searchFields) { - Object[] multiValue = multiValueParams != null ? multiValueParams.get(searchField.getClientFieldName()) : null; - boolean isMultiValue = multiValue != null && multiValue.length > 0; - - if (searchField.getDataType() == SearchField.DATA_TYPE.INT_LIST || (isMultiValue && searchField.getDataType() == SearchField.DATA_TYPE.INTEGER)) { - List intValueList = new ArrayList<>(); - - if (isMultiValue) { - for (Object value : multiValue) { - if (value instanceof Integer || value instanceof Long) { - intValueList.add((Number) value); - } else if (value != null) { - intValueList.add(restErrorUtil.parseInt(value.toString(), "Invalid value for " + searchField.getClientFieldName(), MessageEnums.INVALID_INPUT_DATA, null, searchField.getClientFieldName())); - } - } - } else { - String paramVal = params != null ? params.get(searchField.getClientFieldName()) : null; - - if (paramVal != null) { - intValueList.add(restErrorUtil.parseInt(paramVal, "Invalid value for " + searchField.getClientFieldName(), MessageEnums.INVALID_INPUT_DATA, null, searchField.getClientFieldName())); - } - } - - if (!intValueList.isEmpty()) { - if (intValueList.size() <= dbMinInListLength) { - for (int idx = 0; idx < intValueList.size(); idx++) { - query.setParameter(searchField.getClientFieldName() + "_" + idx, intValueList.get(idx)); - } - } else { - query.setParameter(searchField.getClientFieldName(), intValueList); - } - } - } else if (searchField.getDataType() == SearchField.DATA_TYPE.STR_LIST || (isMultiValue && searchField.getDataType() == SearchField.DATA_TYPE.STRING)) { - List strValueList = new ArrayList<>(); - - for (Object value : multiValue) { - strValueList.add(String.valueOf(value)); - } - - if (!strValueList.isEmpty()) { - if (strValueList.size() <= dbMinInListLength) { - for (int idx = 0; idx < strValueList.size(); idx++) { - if (searchField.getSearchType() == SearchField.SEARCH_TYPE.FULL) { - query.setParameter(searchField.getClientFieldName() + "_" + idx, strValueList.get(idx).trim().toLowerCase()); - } else { - query.setParameter(searchField.getClientFieldName() + "_" + idx, "%" + strValueList.get(idx).trim().toLowerCase() + "%"); - } - } - } else { - query.setParameter(searchField.getClientFieldName(), strValueList); - } - } - } else if (searchField.getDataType() == SearchField.DATA_TYPE.INTEGER) { - Integer paramVal = restErrorUtil.parseInt(searchCriteria.getParam(searchField.getClientFieldName()), - "Invalid value for " + searchField.getClientFieldName(), - MessageEnums.INVALID_INPUT_DATA, null, searchField.getClientFieldName()); - - Number intFieldValue = paramVal != null ? (Number) paramVal : null; - if (intFieldValue != null) { - query.setParameter(searchField.getClientFieldName(), intFieldValue); - } - } else if (searchField.getDataType() == SearchField.DATA_TYPE.STRING) { - String strFieldValue = searchCriteria.getParam(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 = restErrorUtil.parseBoolean(searchCriteria.getParam(searchField.getClientFieldName()), - "Invalid value for " + searchField.getClientFieldName(), - MessageEnums.INVALID_INPUT_DATA, null, searchField.getClientFieldName()); - - if (boolFieldValue != null) { - query.setParameter(searchField.getClientFieldName(), boolFieldValue); - } - } else if (searchField.getDataType() == SearchField.DATA_TYPE.DATE) { - Date fieldValue = restErrorUtil.parseDate(searchCriteria.getParam(searchField.getClientFieldName()), - "Invalid value for " + searchField.getClientFieldName(), MessageEnums.INVALID_INPUT_DATA, - null, searchField.getClientFieldName(), null); - if (fieldValue != null) { - query.setParameter(searchField.getClientFieldName(), fieldValue); - } - } - } - } - - public void updateQueryPageSize(Query query, SearchFilter searchCriteria) { - int pageSize = super.validatePageSize(searchCriteria.getMaxRows()); - query.setMaxResults(pageSize); - - query.setHint("eclipselink.jdbc.max-rows", "" + pageSize); - } - - public String constructSortClause(SearchFilter searchCriteria, List sortFields) { - String ret = null; - String sortBy = searchCriteria.getSortBy(); - String sortType = getSortType(searchCriteria); - 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()); - - if(sortType == null) { - sortType = sortField.getDefaultOrder().name(); - } - - searchCriteria.setSortType(sortType); - break; - } - } - } - - if (querySortBy != null) { - String querySortType = stringUtil.isEmpty(sortType) ? RangerConstants.DEFAULT_SORT_ORDER : sortType; - - searchCriteria.setSortType(querySortType.toLowerCase()); - - ret = " ORDER BY " + querySortBy + " " + querySortType; - } - - return ret; - } - - private String getSortType(SearchFilter searchCriteria) { - String ret = null; - String sortType = searchCriteria.getSortType(); - - if (!stringUtil.isEmpty(sortType)) { - if ("asc".equalsIgnoreCase(sortType) || "desc".equalsIgnoreCase(sortType)) { - ret = sortType; - } else { - logger.error("Invalid sortType. sortType=" + sortType); - } - } - - return ret; - } - - public void extractIntList(HttpServletRequest request, SearchFilter searchFilter, String paramName, String userFriendlyParamName) { - String[] values = getParamMultiValues(request, paramName); - - if (values != null) { - List intValues = new ArrayList<>(values.length); - - for (String value : values) { - Integer intValue = restErrorUtil.parseInt(value, "Invalid value for " + userFriendlyParamName, MessageEnums.INVALID_INPUT_DATA, null, paramName); - - intValues.add(intValue); - } - - searchFilter.setMultiValueParam(paramName, intValues.toArray()); - } - } - - public void extractStringList(HttpServletRequest request, SearchFilter searchFilter, String paramName, - String userFriendlyParamName, String listName, String[] validValues, String regEx) { - String[] values = getParamMultiValues(request, paramName); - - if (values != null) { - List stringList = new ArrayList<>(values.length); - - for (String value : values) { - if (!stringUtil.isEmpty(regEx)) { - restErrorUtil.validateString(value, regEx, "Invalid value for " + userFriendlyParamName, MessageEnums.INVALID_INPUT_DATA, null, paramName); - } - - stringList.add(value); - } - - searchFilter.setMultiValueParam(paramName, stringList.toArray()); - } - } - - public Map getMultiValueParamsWithPrefix(HttpServletRequest request, String prefix, boolean stripPrefix) { - Map ret = new HashMap(); - for (Map.Entry e : request.getParameterMap().entrySet()) { - String name = e.getKey(); - String[] values = e.getValue(); - - if (!StringUtils.isEmpty(name) && !ArrayUtils.isEmpty(values) - && name.startsWith(prefix)) { - if(stripPrefix) { - name = name.substring(prefix.length()); - } - ret.put(name, values); - } - } + static final Logger logger = LoggerFactory.getLogger(RangerSearchUtil.class); + + int dbMinInListLength = 20; + + public RangerSearchUtil() { + dbMinInListLength = PropertiesUtil.getIntProperty("ranger.db.min_inlist", dbMinInListLength); + } + + public SearchFilter getSearchFilter(@Nonnull HttpServletRequest request, List sortFields) { + Validate.notNull(request, "request"); + + SearchFilter ret = new SearchFilter(); + + if (MapUtils.isEmpty(request.getParameterMap())) { + ret.setParams(new HashMap<>()); + } + + ret.setParam(SearchFilter.SERVICE_TYPE, request.getParameter(SearchFilter.SERVICE_TYPE)); + ret.setParam(SearchFilter.SERVICE_TYPE_DISPLAY_NAME, request.getParameter(SearchFilter.SERVICE_TYPE_DISPLAY_NAME)); + ret.setParam(SearchFilter.SERVICE_TYPE_ID, request.getParameter(SearchFilter.SERVICE_TYPE_ID)); + ret.setParam(SearchFilter.SERVICE_NAME, request.getParameter(SearchFilter.SERVICE_NAME)); + ret.setParam(SearchFilter.SERVICE_DISPLAY_NAME, request.getParameter(SearchFilter.SERVICE_DISPLAY_NAME)); + ret.setParam(SearchFilter.SERVICE_NAME_PARTIAL, request.getParameter(SearchFilter.SERVICE_NAME_PARTIAL)); + ret.setParam(SearchFilter.SERVICE_DISPLAY_NAME_PARTIAL, request.getParameter(SearchFilter.SERVICE_DISPLAY_NAME_PARTIAL)); + ret.setParam(SearchFilter.SERVICE_ID, request.getParameter(SearchFilter.SERVICE_ID)); + ret.setParam(SearchFilter.POLICY_NAME, request.getParameter(SearchFilter.POLICY_NAME)); + ret.setParam(SearchFilter.POLICY_NAME_PARTIAL, request.getParameter(SearchFilter.POLICY_NAME_PARTIAL)); + ret.setParam(SearchFilter.POLICY_ID, request.getParameter(SearchFilter.POLICY_ID)); + ret.setParam(SearchFilter.IS_ENABLED, request.getParameter(SearchFilter.IS_ENABLED)); + ret.setParam(SearchFilter.IS_RECURSIVE, request.getParameter(SearchFilter.IS_RECURSIVE)); + ret.setParam(SearchFilter.USER, request.getParameter(SearchFilter.USER)); + ret.setParam(SearchFilter.GROUP, request.getParameter(SearchFilter.GROUP)); + ret.setParam(SearchFilter.ROLE, request.getParameter(SearchFilter.ROLE)); + ret.setParam(SearchFilter.POL_RESOURCE, request.getParameter(SearchFilter.POL_RESOURCE)); + ret.setParam(SearchFilter.RESOURCE_SIGNATURE, request.getParameter(SearchFilter.RESOURCE_SIGNATURE)); + ret.setParam(SearchFilter.POLICY_TYPE, request.getParameter(SearchFilter.POLICY_TYPE)); + ret.setParam(SearchFilter.POLICY_LABEL, request.getParameter(SearchFilter.POLICY_LABEL)); + ret.setParam(SearchFilter.POLICY_LABELS_PARTIAL, request.getParameter(SearchFilter.POLICY_LABELS_PARTIAL)); + ret.setParam(SearchFilter.PLUGIN_HOST_NAME, request.getParameter(SearchFilter.PLUGIN_HOST_NAME)); + ret.setParam(SearchFilter.PLUGIN_APP_TYPE, request.getParameter(SearchFilter.PLUGIN_APP_TYPE)); + ret.setParam(SearchFilter.PLUGIN_ENTITY_TYPE, request.getParameter(SearchFilter.PLUGIN_ENTITY_TYPE)); + ret.setParam(SearchFilter.PLUGIN_IP_ADDRESS, request.getParameter(SearchFilter.PLUGIN_IP_ADDRESS)); + ret.setParam(SearchFilter.ZONE_NAME, request.getParameter(SearchFilter.ZONE_NAME)); + ret.setParam(SearchFilter.ZONE_NAME_PARTIAL, request.getParameter(SearchFilter.ZONE_NAME_PARTIAL)); + ret.setParam(SearchFilter.ZONE_ID, request.getParameter(SearchFilter.ZONE_ID)); + ret.setParam(SearchFilter.TAG_SERVICE_ID, request.getParameter(SearchFilter.TAG_SERVICE_ID)); + ret.setParam(SearchFilter.ROLE_NAME, request.getParameter(SearchFilter.ROLE_NAME)); + ret.setParam(SearchFilter.ROLE_ID, request.getParameter(SearchFilter.ROLE_ID)); + ret.setParam(SearchFilter.GROUP_NAME, request.getParameter(SearchFilter.GROUP_NAME)); + ret.setParam(SearchFilter.USER_NAME, request.getParameter(SearchFilter.USER_NAME)); + ret.setParam(SearchFilter.ROLE_NAME_PARTIAL, request.getParameter(SearchFilter.ROLE_NAME_PARTIAL)); + ret.setParam(SearchFilter.GROUP_NAME_PARTIAL, request.getParameter(SearchFilter.GROUP_NAME_PARTIAL)); + ret.setParam(SearchFilter.USER_NAME_PARTIAL, request.getParameter(SearchFilter.USER_NAME_PARTIAL)); + ret.setParam(SearchFilter.CLUSTER_NAME, request.getParameter(SearchFilter.CLUSTER_NAME)); + ret.setParam(SearchFilter.FETCH_ZONE_UNZONE_POLICIES, request.getParameter(SearchFilter.FETCH_ZONE_UNZONE_POLICIES)); + ret.setParam(SearchFilter.FETCH_TAG_POLICIES, request.getParameter(SearchFilter.FETCH_TAG_POLICIES)); + ret.setParam(SearchFilter.SERVICE_NAME_PREFIX, request.getParameter(SearchFilter.SERVICE_NAME_PREFIX)); + ret.setParam(SearchFilter.ZONE_NAME_PREFIX, request.getParameter(SearchFilter.ZONE_NAME_PREFIX)); + ret.setParam(SearchFilter.TAG_TYPE, request.getParameter(SearchFilter.TAG_TYPE)); + ret.setParam(SearchFilter.TAG_TYPE_PARTIAL, request.getParameter(SearchFilter.TAG_TYPE_PARTIAL)); + ret.setParam(SearchFilter.TAG_SOURCE, request.getParameter(SearchFilter.TAG_SOURCE)); + ret.setParam(SearchFilter.TAG_SOURCE_PARTIAL, request.getParameter(SearchFilter.TAG_SOURCE_PARTIAL)); + ret.setParam(SearchFilter.TAG_SERVICE_NAME, request.getParameter(SearchFilter.TAG_SERVICE_NAME)); + ret.setParam(SearchFilter.TAG_SERVICE_NAME_PARTIAL, request.getParameter(SearchFilter.TAG_SERVICE_NAME_PARTIAL)); + ret.setParam(SearchFilter.TAG_RESOURCE_GUID, request.getParameter(SearchFilter.TAG_RESOURCE_GUID)); + ret.setParam(SearchFilter.TAG_RESOURCE_SIGNATURE, request.getParameter(SearchFilter.TAG_RESOURCE_SIGNATURE)); + ret.setParam(SearchFilter.TAG_RESOURCE_ELEMENTS, request.getParameter(SearchFilter.TAG_RESOURCE_ELEMENTS)); + ret.setParam(SearchFilter.TAG_DEF_GUID, request.getParameter(SearchFilter.TAG_DEF_GUID)); + ret.setParam(SearchFilter.TAG_DEF_ID, request.getParameter(SearchFilter.TAG_DEF_ID)); + ret.setParam(SearchFilter.TAG_ID, request.getParameter(SearchFilter.TAG_ID)); + ret.setParam(SearchFilter.CREATED_BY, request.getParameter(SearchFilter.CREATED_BY)); + ret.setParam(SearchFilter.APPROVER, request.getParameter(SearchFilter.APPROVER)); + ret.setParam(SearchFilter.SHARE_STATUS, request.getParameter(SearchFilter.SHARE_STATUS)); + + for (Map.Entry e : request.getParameterMap().entrySet()) { + String name = e.getKey(); + String[] values = e.getValue(); + + if (!StringUtils.isEmpty(name) && !ArrayUtils.isEmpty(values) && name.startsWith(SearchFilter.RESOURCE_PREFIX)) { + ret.setParam(name, values[0]); + } + } + + ret.setParam(SearchFilter.RESOURCE_MATCH_SCOPE, request.getParameter(SearchFilter.RESOURCE_MATCH_SCOPE)); + ret.setParam(SearchFilter.DATASET_NAME, request.getParameter(SearchFilter.DATASET_NAME)); + ret.setParam(SearchFilter.DATASET_NAME_PARTIAL, request.getParameter(SearchFilter.DATASET_NAME_PARTIAL)); + ret.setParam(SearchFilter.DATASET_ID, request.getParameter(SearchFilter.DATASET_ID)); + ret.setParam(SearchFilter.DATASET_LABEL, request.getParameter(SearchFilter.DATASET_LABEL)); + ret.setParam(SearchFilter.DATASET_KEYWORD, request.getParameter(SearchFilter.DATASET_KEYWORD)); + ret.setParam(SearchFilter.PROJECT_NAME, request.getParameter(SearchFilter.PROJECT_NAME)); + ret.setParam(SearchFilter.PROJECT_NAME_PARTIAL, request.getParameter(SearchFilter.PROJECT_NAME_PARTIAL)); + ret.setParam(SearchFilter.PROJECT_ID, request.getParameter(SearchFilter.PROJECT_ID)); + ret.setParam(SearchFilter.DATA_SHARE_NAME, request.getParameter(SearchFilter.DATA_SHARE_NAME)); + ret.setParam(SearchFilter.DATA_SHARE_NAME_PARTIAL, request.getParameter(SearchFilter.DATA_SHARE_NAME_PARTIAL)); + ret.setParam(SearchFilter.DATA_SHARE_ID, request.getParameter(SearchFilter.DATA_SHARE_ID)); + ret.setParam(SearchFilter.EXCLUDE_DATASET_ID, request.getParameter(SearchFilter.EXCLUDE_DATASET_ID)); + ret.setParam(SearchFilter.SHARED_RESOURCE_ID, request.getParameter(SearchFilter.SHARED_RESOURCE_ID)); + ret.setParam(SearchFilter.SHARED_RESOURCE_NAME, request.getParameter(SearchFilter.SHARED_RESOURCE_NAME)); + ret.setParam(SearchFilter.SHARED_RESOURCE_NAME_PARTIAL, request.getParameter(SearchFilter.SHARED_RESOURCE_NAME_PARTIAL)); + ret.setParam(SearchFilter.PROFILE_NAME, request.getParameter(SearchFilter.PROFILE_NAME)); + ret.setParam(SearchFilter.OWNER_NAME, request.getParameter(SearchFilter.OWNER_NAME)); + ret.setParam(SearchFilter.OWNER_TYPE, request.getParameter(SearchFilter.OWNER_TYPE)); + ret.setParam(SearchFilter.GDS_PERMISSION, request.getParameter(SearchFilter.GDS_PERMISSION)); + ret.setParam(SearchFilter.CREATE_TIME_START, request.getParameter(SearchFilter.CREATE_TIME_START)); + ret.setParam(SearchFilter.CREATE_TIME_END, request.getParameter(SearchFilter.CREATE_TIME_END)); + ret.setParam(SearchFilter.UPDATE_TIME_START, request.getParameter(SearchFilter.UPDATE_TIME_START)); + ret.setParam(SearchFilter.UPDATE_TIME_END, request.getParameter(SearchFilter.UPDATE_TIME_END)); + ret.setParam(SearchFilter.RESOURCE_CONTAINS, request.getParameter(SearchFilter.RESOURCE_CONTAINS)); + ret.setParam(SearchFilter.SHARED_WITH_ME, request.getParameter(SearchFilter.SHARED_WITH_ME)); + + extractCommonCriteriasForFilter(request, ret, sortFields); + + return ret; + } + + public SearchFilter getSearchFilterFromLegacyRequestForRepositorySearch(HttpServletRequest request, List sortFields) { + if (request == null) { + return null; + } + + SearchFilter ret = new SearchFilter(); + + if (MapUtils.isEmpty(request.getParameterMap())) { + ret.setParams(new HashMap<>()); + } + + ret.setParam(SearchFilter.SERVICE_NAME, request.getParameter("name")); + ret.setParam(SearchFilter.IS_ENABLED, request.getParameter("status")); + + String serviceType = request.getParameter("type"); + + if (serviceType != null) { + serviceType = serviceType.toLowerCase(); + } + + ret.setParam(SearchFilter.SERVICE_TYPE, serviceType); + + extractCommonCriteriasForFilter(request, ret, sortFields); + + return ret; + } + + public SearchFilter getSearchFilterFromLegacyRequest(HttpServletRequest request, List sortFields) { + Validate.notNull(request, "request"); + + SearchFilter ret = new SearchFilter(); + + if (MapUtils.isEmpty(request.getParameterMap())) { + ret.setParams(new HashMap<>()); + } + + String repositoryType = request.getParameter("repositoryType"); + + if (repositoryType != null) { + repositoryType = repositoryType.toLowerCase(); + } + + String repositoryId = request.getParameter("repositoryId"); + + if (repositoryId == null) { + repositoryId = request.getParameter("assetId"); + } + + ret.setParam(SearchFilter.SERVICE_TYPE, repositoryType); + ret.setParam(SearchFilter.SERVICE_NAME, request.getParameter("repositoryName")); + ret.setParam(SearchFilter.SERVICE_ID, repositoryId); + ret.setParam(SearchFilter.POLICY_NAME, request.getParameter("policyName")); + ret.setParam(SearchFilter.USER, request.getParameter("userName")); + ret.setParam(SearchFilter.GROUP, request.getParameter("groupName")); + ret.setParam(SearchFilter.IS_ENABLED, request.getParameter("isEnabled")); + ret.setParam(SearchFilter.IS_RECURSIVE, request.getParameter("isRecursive")); + ret.setParam(SearchFilter.POL_RESOURCE, request.getParameter(SearchFilter.POL_RESOURCE)); + ret.setParam(SearchFilter.RESOURCE_PREFIX + "path", request.getParameter("resourceName")); + ret.setParam(SearchFilter.RESOURCE_PREFIX + "database", request.getParameter("databases")); + ret.setParam(SearchFilter.RESOURCE_PREFIX + "table", request.getParameter("tables")); + ret.setParam(SearchFilter.RESOURCE_PREFIX + "udf", request.getParameter("udfs")); + ret.setParam(SearchFilter.RESOURCE_PREFIX + "column", request.getParameter("columns")); + ret.setParam(SearchFilter.RESOURCE_PREFIX + "column-family", request.getParameter("columnFamilies")); + ret.setParam(SearchFilter.RESOURCE_PREFIX + "topology", request.getParameter("topologies")); + ret.setParam(SearchFilter.RESOURCE_PREFIX + "service", request.getParameter("services")); + + extractCommonCriteriasForFilter(request, ret, sortFields); + + return ret; + } + + public SearchFilter extractCommonCriteriasForFilter(HttpServletRequest request, SearchFilter ret, List sortFields) { + int startIndex = restErrorUtil.parseInt(request.getParameter(SearchFilter.START_INDEX), 0, + "Invalid value for parameter startIndex", MessageEnums.INVALID_INPUT_DATA, null, SearchFilter.START_INDEX); + + startIndex = startIndex < 0 ? 0 : startIndex; + + ret.setStartIndex(startIndex); + + int pageSize = restErrorUtil.parseInt(request.getParameter(SearchFilter.PAGE_SIZE), configUtil.getDefaultMaxRows(), + "Invalid value for parameter pageSize", MessageEnums.INVALID_INPUT_DATA, null, SearchFilter.PAGE_SIZE); + + ret.setMaxRows(validatePageSize(pageSize)); + + if (request.getParameter(SearchFilter.POLICY_TYPE) != null) { + int policyType = restErrorUtil.parseInt(request.getParameter(SearchFilter.POLICY_TYPE), 0, + "Invalid value for parameter policyType", MessageEnums.INVALID_INPUT_DATA, null, SearchFilter.POLICY_TYPE); + + ret.setParam(SearchFilter.POLICY_TYPE, Integer.toString(policyType)); + } + + ret.setGetCount(restErrorUtil.parseBoolean(request.getParameter("getCount"), true)); + + String sortBy = restErrorUtil.validateString(request.getParameter(SearchFilter.SORT_BY), StringUtil.VALIDATION_ALPHA, + "Invalid value for parameter sortBy", MessageEnums.INVALID_INPUT_DATA, null, SearchFilter.SORT_BY); + + if (!StringUtils.isEmpty(sortBy)) { + boolean sortSet = false; + + for (SortField sortField : sortFields) { + if (sortField.getParamName().equalsIgnoreCase(sortBy)) { + ret.setSortBy(sortField.getParamName()); + + sortSet = true; + break; + } + } + + if (!sortSet) { + logger.info("Invalid or unsupported sortBy field passed. sortBy={}", sortBy, new Throwable()); + } + } + + String sortType = restErrorUtil.validateString(request.getParameter("sortType"), StringUtil.VALIDATION_ALPHA, + "Invalid value for parameter sortType", MessageEnums.INVALID_INPUT_DATA, null, "sortType"); + + ret.setSortType(sortType); + + if (ret.getParams() == null) { + ret.setParams(new HashMap<>()); + } + + return ret; + } + + public Query createSearchQuery(EntityManager em, String queryStr, String sortClause, SearchFilter searchCriteria, List searchFields, boolean isCountQuery) { + return createSearchQuery(em, queryStr, sortClause, searchCriteria, searchFields, false, isCountQuery); + } + + public Query createSearchQuery(EntityManager em, String queryStr, String sortClause, SearchFilter searchCriteria, List searchFields, boolean hasAttributes, boolean isCountQuery) { + StringBuilder queryClause = buildWhereClause(searchCriteria, searchFields); + + super.addOrderByClause(queryClause, sortClause); + + Query query = em.createQuery(queryStr + queryClause); + + resolveQueryParams(query, searchCriteria, searchFields); + + final boolean skipPagination = isCountQuery || Boolean.parseBoolean(searchCriteria.getParam(SearchFilter.RETRIEVE_ALL_PAGES)); + + if (!skipPagination) { + query.setFirstResult(searchCriteria.getStartIndex()); + updateQueryPageSize(query, searchCriteria); + } + + return query; + } + + public void updateQueryPageSize(Query query, SearchFilter searchCriteria) { + int pageSize = super.validatePageSize(searchCriteria.getMaxRows()); + + query.setMaxResults(pageSize); + + query.setHint("eclipselink.jdbc.max-rows", "" + pageSize); + } + + public String constructSortClause(SearchFilter searchCriteria, List sortFields) { + String ret = null; + String sortBy = searchCriteria.getSortBy(); + String sortType = getSortType(searchCriteria); + 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()); + + if (sortType == null) { + sortType = sortField.getDefaultOrder().name(); + } + + searchCriteria.setSortType(sortType); + break; + } + } + } + + if (querySortBy != null) { + String querySortType = stringUtil.isEmpty(sortType) ? RangerConstants.DEFAULT_SORT_ORDER : sortType; + + searchCriteria.setSortType(querySortType.toLowerCase()); + + ret = " ORDER BY " + querySortBy + " " + querySortType; + } + + return ret; + } + + public void extractIntList(HttpServletRequest request, SearchFilter searchFilter, String paramName, String userFriendlyParamName) { + String[] values = getParamMultiValues(request, paramName); + + if (values != null) { + List intValues = new ArrayList<>(values.length); + + for (String value : values) { + Integer intValue = restErrorUtil.parseInt(value, "Invalid value for " + userFriendlyParamName, MessageEnums.INVALID_INPUT_DATA, null, paramName); + + intValues.add(intValue); + } + + searchFilter.setMultiValueParam(paramName, intValues.toArray()); + } + } + + public void extractStringList(HttpServletRequest request, SearchFilter searchFilter, String paramName, String userFriendlyParamName, String listName, String[] validValues, String regEx) { + String[] values = getParamMultiValues(request, paramName); + + if (values != null) { + List stringList = new ArrayList<>(values.length); + + for (String value : values) { + if (!stringUtil.isEmpty(regEx)) { + restErrorUtil.validateString(value, regEx, "Invalid value for " + userFriendlyParamName, MessageEnums.INVALID_INPUT_DATA, null, paramName); + } + + stringList.add(value); + } + + searchFilter.setMultiValueParam(paramName, stringList.toArray()); + } + } + + public Map getMultiValueParamsWithPrefix(HttpServletRequest request, String prefix, boolean stripPrefix) { + Map ret = new HashMap<>(); + + for (Map.Entry e : request.getParameterMap().entrySet()) { + String name = e.getKey(); + String[] values = e.getValue(); + + if (!StringUtils.isEmpty(name) && !ArrayUtils.isEmpty(values) && name.startsWith(prefix)) { + if (stripPrefix) { + name = name.substring(prefix.length()); + } + + ret.put(name, values); + } + } + + return ret; + } + + /** + * @param request + * @param paramName + * @return + */ + public String[] getParamMultiValues(HttpServletRequest request, String paramName) { + String[] values = request.getParameterValues(paramName); + + if (values == null || values.length == 0) { + values = request.getParameterValues(paramName + "[]"); + } + + return values; + } + + protected void resolveQueryParams(Query query, SearchFilter searchCriteria, List searchFields) { + Map params = searchCriteria.getParams(); + Map multiValueParams = searchCriteria.getMultiValueParams(); + + for (SearchField searchField : searchFields) { + Object[] multiValue = multiValueParams != null ? multiValueParams.get(searchField.getClientFieldName()) : null; + boolean isMultiValue = multiValue != null && multiValue.length > 0; + + if (searchField.getDataType() == SearchField.DATA_TYPE.INT_LIST || (isMultiValue && searchField.getDataType() == SearchField.DATA_TYPE.INTEGER)) { + List intValueList = new ArrayList<>(); + + if (isMultiValue) { + for (Object value : multiValue) { + if (value instanceof Integer || value instanceof Long) { + intValueList.add((Number) value); + } else if (value != null) { + intValueList.add(restErrorUtil.parseInt(value.toString(), "Invalid value for " + searchField.getClientFieldName(), MessageEnums.INVALID_INPUT_DATA, null, searchField.getClientFieldName())); + } + } + } else { + String paramVal = params != null ? params.get(searchField.getClientFieldName()) : null; + + if (paramVal != null) { + intValueList.add(restErrorUtil.parseInt(paramVal, "Invalid value for " + searchField.getClientFieldName(), MessageEnums.INVALID_INPUT_DATA, null, searchField.getClientFieldName())); + } + } + + if (!intValueList.isEmpty()) { + if (intValueList.size() <= dbMinInListLength) { + for (int idx = 0; idx < intValueList.size(); idx++) { + query.setParameter(searchField.getClientFieldName() + "_" + idx, intValueList.get(idx)); + } + } else { + query.setParameter(searchField.getClientFieldName(), intValueList); + } + } + } else if (searchField.getDataType() == SearchField.DATA_TYPE.STR_LIST || (isMultiValue && searchField.getDataType() == SearchField.DATA_TYPE.STRING)) { + List strValueList = new ArrayList<>(); + + for (Object value : multiValue) { + strValueList.add(String.valueOf(value)); + } + + if (!strValueList.isEmpty()) { + if (strValueList.size() <= dbMinInListLength) { + for (int idx = 0; idx < strValueList.size(); idx++) { + if (searchField.getSearchType() == SearchField.SEARCH_TYPE.FULL) { + query.setParameter(searchField.getClientFieldName() + "_" + idx, strValueList.get(idx).trim().toLowerCase()); + } else { + query.setParameter(searchField.getClientFieldName() + "_" + idx, "%" + strValueList.get(idx).trim().toLowerCase() + "%"); + } + } + } else { + query.setParameter(searchField.getClientFieldName(), strValueList); + } + } + } else if (searchField.getDataType() == SearchField.DATA_TYPE.INTEGER) { + Integer paramVal = restErrorUtil.parseInt(searchCriteria.getParam(searchField.getClientFieldName()), + "Invalid value for " + searchField.getClientFieldName(), MessageEnums.INVALID_INPUT_DATA, null, searchField.getClientFieldName()); + + Number intFieldValue = paramVal != null ? (Number) paramVal : null; + + if (intFieldValue != null) { + query.setParameter(searchField.getClientFieldName(), intFieldValue); + } + } else if (searchField.getDataType() == SearchField.DATA_TYPE.STRING) { + String strFieldValue = searchCriteria.getParam(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 = restErrorUtil.parseBoolean(searchCriteria.getParam(searchField.getClientFieldName()), + "Invalid value for " + searchField.getClientFieldName(), MessageEnums.INVALID_INPUT_DATA, null, searchField.getClientFieldName()); + + if (boolFieldValue != null) { + query.setParameter(searchField.getClientFieldName(), boolFieldValue); + } + } else if (searchField.getDataType() == SearchField.DATA_TYPE.DATE) { + Date fieldValue = restErrorUtil.parseDate(searchCriteria.getParam(searchField.getClientFieldName()), + "Invalid value for " + searchField.getClientFieldName(), MessageEnums.INVALID_INPUT_DATA, null, searchField.getClientFieldName(), null); + + if (fieldValue != null) { + query.setParameter(searchField.getClientFieldName(), fieldValue); + } + } + } + } + + private StringBuilder buildWhereClause(SearchFilter searchCriteria, List searchFields) { + return buildWhereClause(searchCriteria, searchFields, false); + } + + private StringBuilder buildWhereClause(SearchFilter searchCriteria, List searchFields, boolean excludeWhereKeyword) { + StringBuilder whereClause = new StringBuilder(excludeWhereKeyword ? "" : "WHERE 1 = 1 "); + List joinTableList = new ArrayList<>(); + + for (SearchField searchField : searchFields) { + int startWhereLen = whereClause.length(); + + if (searchField.getFieldName() == null && searchField.getCustomCondition() == null) { + continue; + } + + Object[] multiValue = searchCriteria.getMultiValueParam(searchField.getClientFieldName()); + boolean isMultiValue = multiValue != null && multiValue.length > 0; + + if (searchField.getDataType() == SearchField.DATA_TYPE.INT_LIST || (isMultiValue && searchField.getDataType() == SearchField.DATA_TYPE.INTEGER)) { + List intValueList = new ArrayList<>(); + + if (isMultiValue) { + for (Object value : multiValue) { + if (value instanceof Integer || value instanceof Long) { + intValueList.add((Number) value); + } else if (value != null) { + intValueList.add(restErrorUtil.parseInt(value.toString(), "Invalid value for " + searchField.getClientFieldName(), MessageEnums.INVALID_INPUT_DATA, null, searchField.getClientFieldName())); + } + } + } else { + String paramVal = searchCriteria.getParam(searchField.getClientFieldName()); + + if (paramVal != null) { + intValueList.add(restErrorUtil.parseInt(paramVal, "Invalid value for " + searchField.getClientFieldName(), MessageEnums.INVALID_INPUT_DATA, null, searchField.getClientFieldName())); + } + } + + if (!intValueList.isEmpty()) { + if (searchField.getCustomCondition() == null) { + if (intValueList.size() <= dbMinInListLength) { + 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()).append("_").append(count); + } + + if (intValueList.size() > 1) { + whereClause.append(" ) "); + } + } else { + whereClause.append(" and ") + .append(searchField.getFieldName()) + .append(" in ") + .append(" (:").append(searchField.getClientFieldName()).append(")"); + } + } else { + whereClause.append(" and ").append(searchField.getCustomCondition()); + } + } + } else if (searchField.getDataType() == SearchField.DATA_TYPE.STR_LIST || (isMultiValue && searchField.getDataType() == SearchField.DATA_TYPE.STRING)) { + List strValueList = new ArrayList<>(); + + for (Object value : multiValue) { + strValueList.add(String.valueOf(value)); + } + + if (!strValueList.isEmpty()) { + if (searchField.getCustomCondition() == null) { + if (strValueList.size() <= dbMinInListLength) { + whereClause.append(" and "); + + if (strValueList.size() > 1) { + whereClause.append(" ( "); + } + + for (int count = 0; count < strValueList.size(); count++) { + if (count > 0) { + whereClause.append(" or "); + } + + whereClause.append("LOWER(").append(searchField.getFieldName()).append(")") + .append(getSqlOperator(searchField.getSearchType())) + .append(":").append(searchField.getClientFieldName()).append("_").append(count); + } + + if (strValueList.size() > 1) { + whereClause.append(" ) "); + } + } else { + whereClause.append(" and ") + .append(searchField.getFieldName()) + .append(" in ") + .append(" (:").append(searchField.getClientFieldName()).append(")"); + } + } else { + whereClause.append(" and ").append(searchField.getCustomCondition()); + } + } + } else if (searchField.getDataType() == SearchField.DATA_TYPE.INTEGER) { + Integer paramVal = restErrorUtil.parseInt(searchCriteria.getParam(searchField.getClientFieldName()), + "Invalid value for " + searchField.getClientFieldName(), MessageEnums.INVALID_INPUT_DATA, null, searchField.getClientFieldName()); + + Number intFieldValue = paramVal != null ? (Number) paramVal : null; + + if (intFieldValue != null) { + if (searchField.getCustomCondition() == null) { + whereClause.append(" and ") + .append(searchField.getFieldName()) + .append(getSqlOperator(searchField.getSearchType())) + .append(":").append(searchField.getClientFieldName()); + } else { + whereClause.append(" and ").append(searchField.getCustomCondition()); + } + } + } else if (searchField.getDataType() == SearchField.DATA_TYPE.STRING) { + String strFieldValue = searchCriteria.getParam(searchField.getClientFieldName()); + + if (strFieldValue != null) { + if (searchField.getCustomCondition() == null) { + whereClause.append(" and ").append("LOWER(").append(searchField.getFieldName()).append(")") + .append(getSqlOperator(searchField.getSearchType())) + .append(":").append(searchField.getClientFieldName()); + } else { + whereClause.append(" and ").append(searchField.getCustomCondition()); + } + } + } else if (searchField.getDataType() == SearchField.DATA_TYPE.BOOLEAN) { + Boolean boolFieldValue = restErrorUtil.parseBoolean(searchCriteria.getParam(searchField.getClientFieldName()), + "Invalid value for " + searchField.getClientFieldName(), MessageEnums.INVALID_INPUT_DATA, null, searchField.getClientFieldName()); + + if (boolFieldValue != null) { + if (searchField.getCustomCondition() == null) { + whereClause.append(" and ") + .append(searchField.getFieldName()) + .append(getSqlOperator(searchField.getSearchType())) + .append(":").append(searchField.getClientFieldName()); + } else { + whereClause.append(" and ").append(searchField.getCustomCondition()); + } + } + } else if (searchField.getDataType() == SearchField.DATA_TYPE.DATE) { + Date fieldValue = restErrorUtil.parseDate(searchCriteria.getParam(searchField.getClientFieldName()), + "Invalid value for " + searchField.getClientFieldName(), MessageEnums.INVALID_INPUT_DATA, null, searchField.getClientFieldName(), null); + + if (fieldValue != null) { + if (searchField.getCustomCondition() == null) { + whereClause.append(" and ").append(searchField.getFieldName()) + .append(getSqlOperator(searchField.getSearchType())) + .append(":").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 (String joinTable : joinTableList) { + whereClause.insert(0, ", " + joinTable + " "); + } + + return whereClause; + } + + private String getSortType(SearchFilter searchCriteria) { + String ret = null; + String sortType = searchCriteria.getSortType(); + + if (!stringUtil.isEmpty(sortType)) { + if ("asc".equalsIgnoreCase(sortType) || "desc".equalsIgnoreCase(sortType)) { + ret = sortType; + } else { + logger.error("Invalid sortType. sortType={}", sortType); + } + } + return ret; - } - - /** - * @param request - * @param paramName - * @return - */ - public String[] getParamMultiValues(HttpServletRequest request, String paramName) { - String[] values = request.getParameterValues(paramName); - - if (values == null || values.length == 0) { - values = request.getParameterValues(paramName + "[]"); - } - - return values; - } + } } diff --git a/security-admin/src/main/java/org/apache/ranger/common/RangerServicePoliciesCache.java b/security-admin/src/main/java/org/apache/ranger/common/RangerServicePoliciesCache.java index df27611a1d..a4be8f6191 100644 --- a/security-admin/src/main/java/org/apache/ranger/common/RangerServicePoliciesCache.java +++ b/security-admin/src/main/java/org/apache/ranger/common/RangerServicePoliciesCache.java @@ -25,7 +25,6 @@ import org.apache.ranger.authorization.utils.JsonUtils; import org.apache.ranger.plugin.model.RangerPolicy; import org.apache.ranger.plugin.store.ServiceStore; - import org.apache.ranger.plugin.util.RangerPolicyDeltaUtil; import org.apache.ranger.plugin.util.ServicePolicies; import org.slf4j.Logger; @@ -36,7 +35,6 @@ import java.io.FileWriter; import java.io.Writer; import java.util.ArrayList; -import java.util.Comparator; import java.util.Date; import java.util.HashMap; import java.util.List; @@ -47,133 +45,134 @@ import java.util.concurrent.locks.ReentrantLock; public class RangerServicePoliciesCache { - private static final Logger LOG = LoggerFactory.getLogger(RangerServicePoliciesCache.class); + private static final Logger LOG = LoggerFactory.getLogger(RangerServicePoliciesCache.class); - private static final int MAX_WAIT_TIME_FOR_UPDATE = 10; + private static final int MAX_WAIT_TIME_FOR_UPDATE = 10; - public static volatile RangerServicePoliciesCache sInstance = null; + public static volatile RangerServicePoliciesCache sInstance; - private final int waitTimeInSeconds; - private final boolean dedupStrings; - private final Map servicePoliciesMap = new HashMap<>(); + private final int waitTimeInSeconds; + private final boolean dedupStrings; + private final Map servicePoliciesMap = new HashMap<>(); - public static RangerServicePoliciesCache getInstance() { - if (sInstance == null) { - synchronized (RangerServicePoliciesCache.class) { - if (sInstance == null) { - sInstance = new RangerServicePoliciesCache(); - } - } - } - return sInstance; - } + private RangerServicePoliciesCache() { + RangerAdminConfig config = RangerAdminConfig.getInstance(); - private RangerServicePoliciesCache() { - RangerAdminConfig config = RangerAdminConfig.getInstance(); + waitTimeInSeconds = config.getInt("ranger.admin.policy.download.cache.max.waittime.for.update", MAX_WAIT_TIME_FOR_UPDATE); + dedupStrings = config.getBoolean("ranger.admin.policy.dedup.strings", Boolean.TRUE); + } - waitTimeInSeconds = config.getInt("ranger.admin.policy.download.cache.max.waittime.for.update", MAX_WAIT_TIME_FOR_UPDATE); - dedupStrings = config.getBoolean("ranger.admin.policy.dedup.strings", Boolean.TRUE); - } + public static RangerServicePoliciesCache getInstance() { + RangerServicePoliciesCache me = sInstance; - public void dump() { - final Set serviceNames; + if (me == null) { + synchronized (RangerServicePoliciesCache.class) { + me = sInstance; - synchronized (this) { - serviceNames = servicePoliciesMap.keySet(); - } + if (me == null) { + me = new RangerServicePoliciesCache(); + sInstance = me; + } + } + } - if (CollectionUtils.isNotEmpty(serviceNames)) { + return me; + } - for (String serviceName : serviceNames) { - final ServicePoliciesWrapper cachedServicePoliciesWrapper; + public void dump() { + final Set serviceNames; - synchronized (this) { - cachedServicePoliciesWrapper = servicePoliciesMap.get(serviceName); - } - LOG.debug("serviceName:" + serviceName + ", Cached-MetaData:" + cachedServicePoliciesWrapper); + synchronized (this) { + serviceNames = servicePoliciesMap.keySet(); + } - } - } - } + if (CollectionUtils.isNotEmpty(serviceNames)) { + for (String serviceName : serviceNames) { + final ServicePoliciesWrapper cachedServicePoliciesWrapper; - public ServicePolicies getServicePolicies(String serviceName, Long serviceId, Long lastKnownVersion, boolean needsBackwardCompatibility, ServiceStore serviceStore) throws Exception { + synchronized (this) { + cachedServicePoliciesWrapper = servicePoliciesMap.get(serviceName); + } - if (LOG.isDebugEnabled()) { - LOG.debug("==> RangerServicePoliciesCache.getServicePolicies(" + serviceName + ", " + serviceId + ", " + lastKnownVersion + ", " + needsBackwardCompatibility + ")"); - } + LOG.debug("serviceName:{}, Cached-MetaData:{}", serviceName, cachedServicePoliciesWrapper); + } + } + } + + public ServicePolicies getServicePolicies(String serviceName, Long serviceId, Long lastKnownVersion, boolean needsBackwardCompatibility, ServiceStore serviceStore) throws Exception { + LOG.debug("==> RangerServicePoliciesCache.getServicePolicies({}, {}, {}, {})", serviceName, serviceId, lastKnownVersion, needsBackwardCompatibility); + + ServicePolicies ret = null; + + if (StringUtils.isNotBlank(serviceName) && serviceId != null) { + ServicePoliciesWrapper servicePoliciesWrapper; + + synchronized (this) { + servicePoliciesWrapper = servicePoliciesMap.get(serviceName); - ServicePolicies ret = null; + if (servicePoliciesWrapper != null) { + if (!serviceId.equals(servicePoliciesWrapper.getServiceId())) { + if (LOG.isDebugEnabled()) { + LOG.debug("Service [{}] changed service-id from {} to {}", serviceName, servicePoliciesWrapper.getServiceId(), serviceId); + LOG.debug("Recreating servicePoliciesWrapper for serviceName [{}]", serviceName); + } - if (StringUtils.isNotBlank(serviceName) && serviceId != null) { + servicePoliciesMap.remove(serviceName); - ServicePoliciesWrapper servicePoliciesWrapper; + servicePoliciesWrapper = null; + } + } - synchronized (this) { - servicePoliciesWrapper = servicePoliciesMap.get(serviceName); + if (servicePoliciesWrapper == null) { + servicePoliciesWrapper = new ServicePoliciesWrapper(serviceId); - if (servicePoliciesWrapper != null) { - if (!serviceId.equals(servicePoliciesWrapper.getServiceId())) { - if (LOG.isDebugEnabled()) { - LOG.debug("Service [" + serviceName + "] changed service-id from " + servicePoliciesWrapper.getServiceId() - + " to " + serviceId); - LOG.debug("Recreating servicePoliciesWrapper for serviceName [" + serviceName + "]"); - } - servicePoliciesMap.remove(serviceName); - servicePoliciesWrapper = null; - } - } + servicePoliciesMap.put(serviceName, servicePoliciesWrapper); + } + } - if (servicePoliciesWrapper == null) { - servicePoliciesWrapper = new ServicePoliciesWrapper(serviceId); - servicePoliciesMap.put(serviceName, servicePoliciesWrapper); - } - } + if (serviceStore != null) { + ret = servicePoliciesWrapper.getLatestOrCached(serviceName, serviceStore, lastKnownVersion, needsBackwardCompatibility); + } else { + LOG.error("getServicePolicies({}): failed to get latest policies as service-store is null! Returning cached servicePolicies!", serviceName); - if (serviceStore != null) { - ret = servicePoliciesWrapper.getLatestOrCached(serviceName, serviceStore, lastKnownVersion, needsBackwardCompatibility); - } else { - LOG.error("getServicePolicies(" + serviceName + "): failed to get latest policies as service-store is null! Returning cached servicePolicies!"); - ret = servicePoliciesWrapper.getServicePolicies(); - } - } else { - LOG.error("getServicePolicies() failed to get policies as serviceName is null or blank and/or serviceId is null!"); - } + ret = servicePoliciesWrapper.getServicePolicies(); + } + } else { + LOG.error("getServicePolicies() failed to get policies as serviceName is null or blank and/or serviceId is null!"); + } - if (LOG.isDebugEnabled()) { - LOG.debug("<== RangerServicePoliciesCache.getServicePolicies(" + serviceName + ", " + serviceId + ", " + lastKnownVersion + ", " + needsBackwardCompatibility + "): ret:[" + ret + "]"); - } + LOG.debug("<== RangerServicePoliciesCache.getServicePolicies({}, {}, {}, {}): ret:[{}]", serviceName, serviceId, lastKnownVersion, needsBackwardCompatibility, ret); - return ret; - } + return ret; + } /** * Reset policy cache using serviceName if provided. * If serviceName is empty, reset everything. + * * @param serviceName * @return true if was able to reset policy cache, false otherwise */ public boolean resetCache(final String serviceName) { - if (LOG.isDebugEnabled()) { - LOG.debug("==> RangerServicePoliciesCache.resetCache({})", serviceName); - } + LOG.debug("==> RangerServicePoliciesCache.resetCache({})", serviceName); boolean ret = false; + synchronized (this) { if (!servicePoliciesMap.isEmpty()) { if (StringUtils.isBlank(serviceName)) { servicePoliciesMap.clear(); - if (LOG.isDebugEnabled()) { - LOG.debug("RangerServicePoliciesCache.resetCache(): Removed policy caching for all services."); - } + + LOG.debug("RangerServicePoliciesCache.resetCache(): Removed policy caching for all services."); + ret = true; } else { ServicePoliciesWrapper removedServicePoliciesWrapper = servicePoliciesMap.remove(serviceName.trim()); // returns null if key not found + ret = removedServicePoliciesWrapper != null; if (ret) { - if (LOG.isDebugEnabled()) { - LOG.debug("RangerServicePoliciesCache.resetCache(): Removed policy caching for [{}] service.", serviceName); - } + LOG.debug("RangerServicePoliciesCache.resetCache(): Removed policy caching for [{}] service.", serviceName); } else { LOG.warn("RangerServicePoliciesCache.resetCache(): Caching for [{}] service not found, hence reset is skipped.", serviceName); } @@ -183,403 +182,376 @@ public boolean resetCache(final String serviceName) { } } - if (LOG.isDebugEnabled()) { - LOG.debug("<== RangerServicePoliciesCache.resetCache(): ret={}", ret); - } + LOG.debug("<== RangerServicePoliciesCache.resetCache(): ret={}", ret); return ret; } - public void saveToCache(ServicePolicies policies) { - if(LOG.isDebugEnabled()) { - LOG.debug("==> RangerServicePoliciesCache(serviceName=" + policies.getServiceName() + ").saveToCache()"); - } - if (policies != null) { - RangerAdminConfig config = RangerAdminConfig.getInstance(); - boolean doSaveToDisk = config.getBoolean("ranger.admin.policy.save.to.disk", false); - int maxVersionsToSaveToDisk = config.getInt("ranger.admin.policy.max.versions.to.save.to.disk", 1); - - if (doSaveToDisk) { - File cacheFile = null; - - String cacheDir = config.get("ranger.admin.policy.cache.dir"); - if (cacheDir != null) { - String appId = policies.getServiceDef().getName(); - String serviceName = policies.getServiceName(); - String cacheFileName = String.format("%s_%s.json", appId, serviceName); - - cacheFileName = cacheFileName.replace(File.separatorChar, '_'); - cacheFileName = cacheFileName.replace(File.pathSeparatorChar, '_'); - cacheFileName = cacheFileName + "_" + policies.getPolicyVersion(); - - // Create the cacheDir if it doesn't already exist - File cacheDirTmp = new File(cacheDir); - if (cacheDirTmp.exists()) { - cacheFile = new File(cacheDir + File.separator + cacheFileName); - } else { - try { - cacheDirTmp.mkdirs(); - cacheFile = new File(cacheDir + File.separator + cacheFileName); - } catch (SecurityException ex) { - LOG.error("Cannot create cache directory", ex); - } - } - } - - if (cacheFile != null) { - try (Writer writer = new FileWriter(cacheFile)) { + public void saveToCache(ServicePolicies policies) { + LOG.debug("==> RangerServicePoliciesCache(serviceName={}).saveToCache()", ((policies != null) ? policies.getServiceName() : "null")); + + if (policies != null) { + RangerAdminConfig config = RangerAdminConfig.getInstance(); + boolean doSaveToDisk = config.getBoolean("ranger.admin.policy.save.to.disk", false); + int maxVersionsToSaveToDisk = config.getInt("ranger.admin.policy.max.versions.to.save.to.disk", 1); + + if (doSaveToDisk) { + File cacheFile = null; + String cacheDir = config.get("ranger.admin.policy.cache.dir"); + + if (cacheDir != null) { + String appId = policies.getServiceDef().getName(); + String serviceName = policies.getServiceName(); + String cacheFileName = String.format("%s_%s.json", appId, serviceName); + + cacheFileName = cacheFileName.replace(File.separatorChar, '_'); + cacheFileName = cacheFileName.replace(File.pathSeparatorChar, '_'); + cacheFileName = cacheFileName + "_" + policies.getPolicyVersion(); + + // Create the cacheDir if it doesn't already exist + File cacheDirTmp = new File(cacheDir); + + if (cacheDirTmp.exists()) { + cacheFile = new File(cacheDir + File.separator + cacheFileName); + } else { + try { + cacheDirTmp.mkdirs(); + + cacheFile = new File(cacheDir + File.separator + cacheFileName); + } catch (SecurityException ex) { + LOG.error("Cannot create cache directory", ex); + } + } + } + + if (cacheFile != null) { + try (Writer writer = new FileWriter(cacheFile)) { JsonUtils.objectToWriter(writer, policies); - } catch (Exception excp) { - LOG.error("failed to save policies to cache file '" + cacheFile.getAbsolutePath() + "'", excp); - } - String serviceDefName = policies.getServiceDef().getName(); - String serviceName = policies.getServiceName(); - - File parentFile = cacheFile.getParentFile(); - FileFilter logFileFilter = (file) -> file.getName().matches(serviceDefName +"_.+json_.+"); - File[] filesInParent = parentFile.listFiles(logFileFilter); - List policyVersions = new ArrayList<>(); - if (filesInParent != null && filesInParent.length > 0) { - for (File f : filesInParent) { - String fileName = f.getName(); - // Extract the part after json_ - int policyVersionIdx = fileName.lastIndexOf("json_"); - String policyVersionStr = fileName.substring(policyVersionIdx + 5); - Long policyVersion = Long.valueOf(policyVersionStr); - policyVersions.add(policyVersion); - } - } else { - LOG.info("No files matching '" + serviceDefName + "_.+json_*' found"); - } - if (!policyVersions.isEmpty()) { - policyVersions.sort(new Comparator() { - @Override - public int compare(Long o1, Long o2) { - if (o1.equals(o2)) return 0; - return o1 < o2 ? -1 : 1; - } - }); - } - - if (policyVersions.size() > maxVersionsToSaveToDisk) { - String fileName = serviceDefName + "_" + serviceName + ".json_" + Long.toString(policyVersions.get(0)); - String pathName = parentFile.getAbsolutePath() + File.separator + fileName; - File toDelete = new File(pathName); - if (toDelete.exists()) { - //LOG.info("Deleting file :[" + pathName + "]"); - boolean isDeleted = toDelete.delete(); - //LOG.info("file :[" + pathName + "] is deleted"); - } else { - LOG.info("File: " + pathName + " does not exist!"); - } - } - } - } - } else { - LOG.error("ServicePolicies is null object!!"); - } - - if(LOG.isDebugEnabled()) { - LOG.debug("<== RangerServicePoliciesCache(serviceName=" + policies.getServiceName() + ").saveToCache()"); - } - } - - private class ServicePoliciesWrapper { - final Long serviceId; - ServicePolicies servicePolicies; - Date updateTime = null; - long longestDbLoadTimeInMs = -1; - final ReentrantLock lock = new ReentrantLock(); - - ServicePolicyDeltasCache deltaCache; - - class ServicePolicyDeltasCache { - final long fromVersion; - final ServicePolicies servicePolicyDeltas; - - ServicePolicyDeltasCache(final long fromVersion, ServicePolicies servicePolicyDeltas) { - this.fromVersion = fromVersion; - this.servicePolicyDeltas = servicePolicyDeltas; - } - ServicePolicies getServicePolicyDeltasFromVersion(long fromVersion) { - return this.fromVersion == fromVersion ? this.servicePolicyDeltas : null; - } - } - - ServicePoliciesWrapper(Long serviceId) { - this.serviceId = serviceId; - servicePolicies = null; - } - - Long getServiceId() { return serviceId; } - - ServicePolicies getServicePolicies() { - return servicePolicies; - } - - Date getUpdateTime() { - return updateTime; - } - - ServicePolicies getLatestOrCached(String serviceName, ServiceStore serviceStore, Long lastKnownVersion, boolean needsBackwardCompatibility) throws Exception { - if (LOG.isDebugEnabled()) { - LOG.debug("==> RangerServicePoliciesCache.getLatestOrCached(lastKnownVersion=" + lastKnownVersion + ", " + needsBackwardCompatibility + ")"); - } - ServicePolicies ret = null; - boolean lockResult = false; - boolean doSaveToCache = false; - - try { - final boolean isCacheReloadedByDQEvent; - - lockResult = lock.tryLock(waitTimeInSeconds, TimeUnit.SECONDS); - - if (lockResult) { - isCacheReloadedByDQEvent = getLatest(serviceName, serviceStore, lastKnownVersion); - - if (this.servicePolicies != null) { - if (isCacheReloadedByDQEvent) { - if (LOG.isDebugEnabled()) { - LOG.debug("ServicePolicies cache was completely loaded from database because of a disqualifying event - such as service-definition change!"); - } - } - if (!lastKnownVersion.equals(servicePolicies.getPolicyVersion()) || isCacheReloadedByDQEvent) { - doSaveToCache = true; - } - - if (needsBackwardCompatibility || isCacheReloadedByDQEvent - || lastKnownVersion == -1L || lastKnownVersion.equals(servicePolicies.getPolicyVersion())) { - // Looking for all policies, or Some disqualifying change encountered - if (LOG.isDebugEnabled()) { - LOG.debug("All policies were requested, returning cached ServicePolicies"); - } - ret = this.servicePolicies; - } else { - boolean isDeltaCacheReinitialized = false; - ServicePolicies servicePoliciesForDeltas = this.deltaCache != null ? this.deltaCache.getServicePolicyDeltasFromVersion(lastKnownVersion) : null; - - if (servicePoliciesForDeltas == null) { - servicePoliciesForDeltas = serviceStore.getServicePolicyDeltas(serviceName, lastKnownVersion, servicePolicies.getPolicyVersion()); - isDeltaCacheReinitialized = true; - } - if (servicePoliciesForDeltas != null && servicePoliciesForDeltas.getPolicyDeltas() != null) { - if (LOG.isDebugEnabled()) { - LOG.debug("Deltas were requested. Returning deltas from lastKnownVersion:[" + lastKnownVersion + "]"); - } - if (isDeltaCacheReinitialized) { - this.deltaCache = new ServicePolicyDeltasCache(lastKnownVersion, servicePoliciesForDeltas); - } - ret = servicePoliciesForDeltas; - } else { - LOG.warn("Deltas were requested for service:[" + serviceName + "], but could not get them!! lastKnownVersion:[" + lastKnownVersion + "]; Returning cached ServicePolicies:[" + (servicePolicies != null ? servicePolicies.getPolicyVersion() : -1L) + "]"); - - this.deltaCache = null; - ret = this.servicePolicies; - } - } - } else { - LOG.error("ServicePolicies object is null!"); - } - } else { - LOG.error("Could not get lock in [" + waitTimeInSeconds + "] seconds, returning cached ServicePolicies and wait Queue Length:[" +lock.getQueueLength() + "], servicePolicies version:[" + (servicePolicies != null ? servicePolicies.getPolicyVersion() : -1L) + "]"); - ret = this.servicePolicies; - doSaveToCache = true; - } - } catch (InterruptedException exception) { - LOG.error("getLatestOrCached:lock got interrupted..", exception); - } finally { - // Dump cached policies to disk - if (doSaveToCache) { - saveToCache(this.servicePolicies); - } - if (lockResult) { - lock.unlock(); - } - } - if (LOG.isTraceEnabled()) { - LOG.trace("RangerServicePoliciesCache.getLatestOrCached - Returns ServicePolicies:[" + ret +"]"); - } - - if (LOG.isDebugEnabled()) { - LOG.debug("<== RangerServicePoliciesCache.getLatestOrCached(lastKnownVersion=" + lastKnownVersion + ", " + needsBackwardCompatibility + ") : " + ret); - } - return ret; - } - - boolean getLatest(String serviceName, ServiceStore serviceStore, Long lastKnownVersion) throws Exception { - if (LOG.isDebugEnabled()) { - LOG.debug("==> ServicePoliciesWrapper.getLatest(serviceName=" + serviceName + ", lastKnownVersion=" + lastKnownVersion + ")"); - } - - final Long servicePolicyVersionInDb = serviceStore.getServicePolicyVersion(serviceName); - final Long cachedServicePoliciesVersion = servicePolicies != null ? servicePolicies.getPolicyVersion() : -1L; - - if (LOG.isDebugEnabled()) { - LOG.debug("ServicePolicies version in cache[" + cachedServicePoliciesVersion + "], ServicePolicies version in database[" + servicePolicyVersionInDb + "]"); - } - - boolean isCacheReloadedByDQEvent = false; - - if (servicePolicyVersionInDb == null || !servicePolicyVersionInDb.equals(cachedServicePoliciesVersion)) { - - if (LOG.isDebugEnabled()) { - LOG.debug("loading servicePolicies from database"); - } - - final long startTimeMs = System.currentTimeMillis(); - final ServicePolicies servicePoliciesFromDb = serviceStore.getServicePolicyDeltasOrPolicies(serviceName, cachedServicePoliciesVersion); - final long dbLoadTime = System.currentTimeMillis() - startTimeMs; - - if (dbLoadTime > longestDbLoadTimeInMs) { - longestDbLoadTimeInMs = dbLoadTime; - } - - updateTime = new Date(); - - if (servicePoliciesFromDb != null) { - if (LOG.isDebugEnabled()) { - LOG.debug("loading servicePolicies from database and it took:" + TimeUnit.MILLISECONDS.toSeconds(dbLoadTime) + " seconds"); - } - - if (dedupStrings) { - servicePoliciesFromDb.dedupStrings(); - } - - if (LOG.isDebugEnabled()) { - LOG.debug("Successfully loaded ServicePolicies from database: ServicePolicies:[" + servicePoliciesFromDb + "]"); - } - if (servicePolicies == null) { - if (LOG.isDebugEnabled()) { - LOG.debug("Initializing ServicePolicies cache for the first time"); - } - servicePolicies = servicePoliciesFromDb; - } else if (servicePoliciesFromDb.getPolicyDeltas() == null) { - // service-policies are loaded because service/service-def changed - if (LOG.isDebugEnabled()) { - LOG.debug("Complete set of policies are loaded from database, because of some disqualifying event"); - } - servicePolicies = servicePoliciesFromDb; - isCacheReloadedByDQEvent = true; - } else { // Previously cached service policies are still valid - no service/service-def change - // Rebuild policies cache from original policies and deltas - if (LOG.isDebugEnabled()) { - LOG.debug("Retrieved policy-deltas from database. These will be applied on top of ServicePolicy version:[" + cachedServicePoliciesVersion +"], policy-deltas:[" + servicePoliciesFromDb.getPolicyDeltas() + "]"); - } - - final List policies = servicePolicies.getPolicies() == null ? new ArrayList<>() : servicePolicies.getPolicies(); - final List newPolicies = RangerPolicyDeltaUtil.applyDeltas(policies, servicePoliciesFromDb.getPolicyDeltas(), servicePolicies.getServiceDef().getName()); - - servicePolicies.setPolicies(newPolicies); - servicePolicies.setPolicyVersion(servicePoliciesFromDb.getPolicyVersion()); - - checkCacheSanity(serviceName, serviceStore, false); - - // Rebuild tag-policies from original tag-policies and deltas - if (servicePoliciesFromDb.getTagPolicies() != null) { - String tagServiceName = servicePoliciesFromDb.getTagPolicies().getServiceName(); - if (LOG.isDebugEnabled()) { - LOG.debug("This service has associated tag service:[" + tagServiceName + "]. Will compute tagPolicies from corresponding policy-deltas"); - } - - final List tagPolicies = (servicePolicies.getTagPolicies() == null || CollectionUtils.isEmpty(servicePolicies.getTagPolicies().getPolicies())) ? new ArrayList<>() : servicePolicies.getTagPolicies().getPolicies(); - final List newTagPolicies = RangerPolicyDeltaUtil.applyDeltas(tagPolicies, servicePoliciesFromDb.getPolicyDeltas(), servicePoliciesFromDb.getTagPolicies().getServiceDef().getName()); - - servicePolicies.getTagPolicies().setPolicies(newTagPolicies); - servicePolicies.getTagPolicies().setPolicyVersion(servicePoliciesFromDb.getTagPolicies().getPolicyVersion()); - - checkCacheSanity(servicePoliciesFromDb.getTagPolicies().getServiceName(), serviceStore, true); - - } else { - if (LOG.isDebugEnabled()) { - LOG.debug("This service has no associated tag service"); - } - } - } - pruneUnusedAttributes(); - this.deltaCache = null; - } else { - LOG.error("Could not get policies from database, from-version:[" + cachedServicePoliciesVersion + ")"); - } - if (LOG.isDebugEnabled()) { - LOG.debug("ServicePolicies old-version:[" + cachedServicePoliciesVersion + "], new-version:[" + servicePolicies.getPolicyVersion() + "]"); - } - } else { - if (LOG.isDebugEnabled()) { - LOG.debug("ServicePolicies Cache already has the latest version, version:[" + servicePolicies.getPolicyVersion() + "]"); - } - } - - if (LOG.isTraceEnabled()) { - LOG.trace("Latest Cached ServicePolicies:[" + servicePolicies +"]"); - } - - if (LOG.isDebugEnabled()) { - LOG.debug("<== ServicePoliciesWrapper.getLatest(serviceName=" + serviceName + ", lastKnownVersion=" + lastKnownVersion + ") : " + isCacheReloadedByDQEvent); - } - return isCacheReloadedByDQEvent; - } - - private void checkCacheSanity(String serviceName, ServiceStore serviceStore, boolean isTagService) { - final boolean result; - Long dbPolicyVersion = serviceStore.getServicePolicyVersion(serviceName); - Long cachedPolicyVersion = isTagService ? servicePolicies.getTagPolicies().getPolicyVersion() : servicePolicies.getPolicyVersion(); - - result = Objects.equals(dbPolicyVersion, cachedPolicyVersion); - - if (!result && cachedPolicyVersion != null && dbPolicyVersion != null && cachedPolicyVersion < dbPolicyVersion) { - LOG.info("checkCacheSanity(serviceName=" + serviceName + "): policy cache has a different version than one in the database. However, changes from " + cachedPolicyVersion + " to " + dbPolicyVersion + " will be downloaded in the next download. policyVersionInDB=" + dbPolicyVersion + ", policyVersionInCache=" + cachedPolicyVersion); - } - } - - private void pruneUnusedAttributes() { - if (servicePolicies != null) { - pruneUnusedPolicyAttributes(servicePolicies.getPolicies()); - if (servicePolicies.getTagPolicies() != null) { - pruneUnusedPolicyAttributes(servicePolicies.getTagPolicies().getPolicies()); - } - } - } - - private void pruneUnusedPolicyAttributes(List policies) { - - // Null out attributes not required by plug-ins - if (CollectionUtils.isNotEmpty(policies)) { - for (RangerPolicy policy : policies) { - policy.setCreatedBy(null); - policy.setCreateTime(null); - policy.setUpdatedBy(null); - policy.setUpdateTime(null); - // policy.setGuid(null); /* this is used by import policy */ - // policy.setName(null); /* this is used by GUI in policy list page */ - // policy.setDescription(null); /* this is used by export policy */ - policy.setResourceSignature(null); - policy.setOptions(null); - } - } - } - - StringBuilder toString(StringBuilder sb) { - sb.append("RangerServicePoliciesWrapper={"); - - sb.append("updateTime=").append(updateTime) - .append(", longestDbLoadTimeInMs=").append(longestDbLoadTimeInMs) - .append(", Service-Version:").append(servicePolicies != null ? servicePolicies.getPolicyVersion() : "null") - .append(", Number-Of-Policies:").append(servicePolicies != null && servicePolicies.getPolicies() != null ? servicePolicies.getPolicies().size() : 0) - .append(", Number-Of-Policy-Deltas:").append(servicePolicies != null && servicePolicies.getPolicyDeltas() != null ? servicePolicies.getPolicyDeltas().size() : 0); - - sb.append("} "); - - return sb; - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - - toString(sb); - - return sb.toString(); - } - } -} + } catch (Exception excp) { + LOG.error("failed to save policies to cache file '{}'", cacheFile.getAbsolutePath(), excp); + } + + String serviceDefName = policies.getServiceDef().getName(); + String serviceName = policies.getServiceName(); + File parentFile = cacheFile.getParentFile(); + FileFilter logFileFilter = (file) -> file.getName().matches(serviceDefName + "_.+json_.+"); + File[] filesInParent = parentFile.listFiles(logFileFilter); + List policyVersions = new ArrayList<>(); + + if (filesInParent != null && filesInParent.length > 0) { + for (File f : filesInParent) { + String fileName = f.getName(); + // Extract the part after json_ + int policyVersionIdx = fileName.lastIndexOf("json_"); + String policyVersionStr = fileName.substring(policyVersionIdx + 5); + Long policyVersion = Long.valueOf(policyVersionStr); + + policyVersions.add(policyVersion); + } + } else { + LOG.info("No files matching '{}_.+json_*' found", serviceDefName); + } + + if (!policyVersions.isEmpty()) { + policyVersions.sort((o1, o2) -> { + if (o1.equals(o2)) { + return 0; + } + + return o1 < o2 ? -1 : 1; + }); + } + + if (policyVersions.size() > maxVersionsToSaveToDisk) { + String fileName = serviceDefName + "_" + serviceName + ".json_" + policyVersions.get(0); + String pathName = parentFile.getAbsolutePath() + File.separator + fileName; + File toDelete = new File(pathName); + + if (toDelete.exists()) { + //LOG.info("Deleting file :[" + pathName + "]"); + boolean isDeleted = toDelete.delete(); + //LOG.info("file :[" + pathName + "] is deleted"); + } else { + LOG.info("File: {} does not exist!", pathName); + } + } + } + } + } else { + LOG.error("ServicePolicies is null object!!"); + } + + LOG.debug("<== RangerServicePoliciesCache(serviceName={}).saveToCache()", policies.getServiceName()); + } + + private class ServicePoliciesWrapper { + final Long serviceId; + final ReentrantLock lock = new ReentrantLock(); + ServicePolicies servicePolicies; + Date updateTime; + long longestDbLoadTimeInMs = -1; + ServicePolicyDeltasCache deltaCache; + + ServicePoliciesWrapper(Long serviceId) { + this.serviceId = serviceId; + servicePolicies = null; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + + toString(sb); + + return sb.toString(); + } + + Long getServiceId() { + return serviceId; + } + + ServicePolicies getServicePolicies() { + return servicePolicies; + } + + Date getUpdateTime() { + return updateTime; + } + + ServicePolicies getLatestOrCached(String serviceName, ServiceStore serviceStore, Long lastKnownVersion, boolean needsBackwardCompatibility) throws Exception { + LOG.debug("==> RangerServicePoliciesCache.getLatestOrCached(lastKnownVersion={}, {})", lastKnownVersion, needsBackwardCompatibility); + + ServicePolicies ret = null; + boolean lockResult = false; + boolean doSaveToCache = false; + + try { + final boolean isCacheReloadedByDQEvent; + + lockResult = lock.tryLock(waitTimeInSeconds, TimeUnit.SECONDS); + + if (lockResult) { + isCacheReloadedByDQEvent = getLatest(serviceName, serviceStore, lastKnownVersion); + + if (this.servicePolicies != null) { + if (isCacheReloadedByDQEvent) { + LOG.debug("ServicePolicies cache was completely loaded from database because of a disqualifying event - such as service-definition change!"); + } + if (!lastKnownVersion.equals(servicePolicies.getPolicyVersion()) || isCacheReloadedByDQEvent) { + doSaveToCache = true; + } + + if (needsBackwardCompatibility || isCacheReloadedByDQEvent || lastKnownVersion == -1L || lastKnownVersion.equals(servicePolicies.getPolicyVersion())) { + // Looking for all policies, or Some disqualifying change encountered + LOG.debug("All policies were requested, returning cached ServicePolicies"); + + ret = this.servicePolicies; + } else { + boolean isDeltaCacheReinitialized = false; + ServicePolicies servicePoliciesForDeltas = this.deltaCache != null ? this.deltaCache.getServicePolicyDeltasFromVersion(lastKnownVersion) : null; + + if (servicePoliciesForDeltas == null) { + servicePoliciesForDeltas = serviceStore.getServicePolicyDeltas(serviceName, lastKnownVersion, servicePolicies.getPolicyVersion()); + isDeltaCacheReinitialized = true; + } + + if (servicePoliciesForDeltas != null && servicePoliciesForDeltas.getPolicyDeltas() != null) { + LOG.debug("Deltas were requested. Returning deltas from lastKnownVersion:[{}]", lastKnownVersion); + + if (isDeltaCacheReinitialized) { + this.deltaCache = new ServicePolicyDeltasCache(lastKnownVersion, servicePoliciesForDeltas); + } + + ret = servicePoliciesForDeltas; + } else { + LOG.warn("Deltas were requested for service:[{}], but could not get them!! lastKnownVersion:[{}]; Returning cached ServicePolicies:[{}]", serviceName, lastKnownVersion, servicePolicies != null ? servicePolicies.getPolicyVersion() : -1L); + + this.deltaCache = null; + ret = this.servicePolicies; + } + } + } else { + LOG.error("ServicePolicies object is null!"); + } + } else { + LOG.error("Could not get lock in [{}] seconds, returning cached ServicePolicies and wait Queue Length:[{}], servicePolicies version:[{}]", waitTimeInSeconds, lock.getQueueLength(), servicePolicies != null ? servicePolicies.getPolicyVersion() : -1L); + + ret = this.servicePolicies; + doSaveToCache = true; + } + } catch (InterruptedException exception) { + LOG.error("getLatestOrCached:lock got interrupted..", exception); + } finally { + // Dump cached policies to disk + if (doSaveToCache) { + saveToCache(this.servicePolicies); + } + + if (lockResult) { + lock.unlock(); + } + } + + LOG.trace("RangerServicePoliciesCache.getLatestOrCached - Returns ServicePolicies:[{}]", ret); + LOG.debug("<== RangerServicePoliciesCache.getLatestOrCached(lastKnownVersion={}, {}) : {}", lastKnownVersion, needsBackwardCompatibility, ret); + + return ret; + } + + boolean getLatest(String serviceName, ServiceStore serviceStore, Long lastKnownVersion) throws Exception { + LOG.debug("==> ServicePoliciesWrapper.getLatest(serviceName={}, lastKnownVersion={})", serviceName, lastKnownVersion); + + final Long servicePolicyVersionInDb = serviceStore.getServicePolicyVersion(serviceName); + final Long cachedServicePoliciesVersion = servicePolicies != null ? servicePolicies.getPolicyVersion() : -1L; + + LOG.debug("ServicePolicies version in cache[{}], ServicePolicies version in database[{}]", cachedServicePoliciesVersion, servicePolicyVersionInDb); + + boolean isCacheReloadedByDQEvent = false; + + if (servicePolicyVersionInDb == null || !servicePolicyVersionInDb.equals(cachedServicePoliciesVersion)) { + LOG.debug("loading servicePolicies from database"); + + final long startTimeMs = System.currentTimeMillis(); + final ServicePolicies servicePoliciesFromDb = serviceStore.getServicePolicyDeltasOrPolicies(serviceName, cachedServicePoliciesVersion); + final long dbLoadTime = System.currentTimeMillis() - startTimeMs; + + if (dbLoadTime > longestDbLoadTimeInMs) { + longestDbLoadTimeInMs = dbLoadTime; + } + + updateTime = new Date(); + + if (servicePoliciesFromDb != null) { + LOG.debug("loading servicePolicies from database and it took:{} seconds", TimeUnit.MILLISECONDS.toSeconds(dbLoadTime)); + + if (dedupStrings) { + servicePoliciesFromDb.dedupStrings(); + } + + LOG.debug("Successfully loaded ServicePolicies from database: ServicePolicies:[{}]", servicePoliciesFromDb); + + if (servicePolicies == null) { + LOG.debug("Initializing ServicePolicies cache for the first time"); + + servicePolicies = servicePoliciesFromDb; + } else if (servicePoliciesFromDb.getPolicyDeltas() == null) { + // service-policies are loaded because service/service-def changed + LOG.debug("Complete set of policies are loaded from database, because of some disqualifying event"); + + servicePolicies = servicePoliciesFromDb; + isCacheReloadedByDQEvent = true; + } else { // Previously cached service policies are still valid - no service/service-def change + // Rebuild policies cache from original policies and deltas + LOG.debug("Retrieved policy-deltas from database. These will be applied on top of ServicePolicy version:[{}], policy-deltas:[{}]", cachedServicePoliciesVersion, servicePoliciesFromDb.getPolicyDeltas()); + + final List policies = servicePolicies.getPolicies() == null ? new ArrayList<>() : servicePolicies.getPolicies(); + final List newPolicies = RangerPolicyDeltaUtil.applyDeltas(policies, servicePoliciesFromDb.getPolicyDeltas(), servicePolicies.getServiceDef().getName()); + + servicePolicies.setPolicies(newPolicies); + servicePolicies.setPolicyVersion(servicePoliciesFromDb.getPolicyVersion()); + + checkCacheSanity(serviceName, serviceStore, false); + + // Rebuild tag-policies from original tag-policies and deltas + if (servicePoliciesFromDb.getTagPolicies() != null) { + String tagServiceName = servicePoliciesFromDb.getTagPolicies().getServiceName(); + + LOG.debug("This service has associated tag service:[{}]. Will compute tagPolicies from corresponding policy-deltas", tagServiceName); + + final List tagPolicies = (servicePolicies.getTagPolicies() == null || CollectionUtils.isEmpty(servicePolicies.getTagPolicies().getPolicies())) ? new ArrayList<>() : servicePolicies.getTagPolicies().getPolicies(); + final List newTagPolicies = RangerPolicyDeltaUtil.applyDeltas(tagPolicies, servicePoliciesFromDb.getPolicyDeltas(), servicePoliciesFromDb.getTagPolicies().getServiceDef().getName()); + + servicePolicies.getTagPolicies().setPolicies(newTagPolicies); + servicePolicies.getTagPolicies().setPolicyVersion(servicePoliciesFromDb.getTagPolicies().getPolicyVersion()); + + checkCacheSanity(servicePoliciesFromDb.getTagPolicies().getServiceName(), serviceStore, true); + } else { + LOG.debug("This service has no associated tag service"); + } + } + + pruneUnusedAttributes(); + + this.deltaCache = null; + } else { + LOG.error("Could not get policies from database, from-version:[{})", cachedServicePoliciesVersion); + } + + LOG.debug("ServicePolicies old-version:[{}], new-version:[{}]", cachedServicePoliciesVersion, servicePolicies.getPolicyVersion()); + } else { + LOG.debug("ServicePolicies Cache already has the latest version, version:[{}]", servicePolicies.getPolicyVersion()); + } + + LOG.trace("Latest Cached ServicePolicies:[{}]", servicePolicies); + LOG.debug("<== ServicePoliciesWrapper.getLatest(serviceName={}, lastKnownVersion={}) : {}", serviceName, lastKnownVersion, isCacheReloadedByDQEvent); + + return isCacheReloadedByDQEvent; + } + + StringBuilder toString(StringBuilder sb) { + sb.append("RangerServicePoliciesWrapper={"); + + sb.append("updateTime=").append(updateTime) + .append(", longestDbLoadTimeInMs=").append(longestDbLoadTimeInMs) + .append(", Service-Version:").append(servicePolicies != null ? servicePolicies.getPolicyVersion() : "null") + .append(", Number-Of-Policies:").append(servicePolicies != null && servicePolicies.getPolicies() != null ? servicePolicies.getPolicies().size() : 0) + .append(", Number-Of-Policy-Deltas:").append(servicePolicies != null && servicePolicies.getPolicyDeltas() != null ? servicePolicies.getPolicyDeltas().size() : 0); + + sb.append("} "); + + return sb; + } + + private void checkCacheSanity(String serviceName, ServiceStore serviceStore, boolean isTagService) { + Long dbPolicyVersion = serviceStore.getServicePolicyVersion(serviceName); + Long cachedPolicyVersion = isTagService ? servicePolicies.getTagPolicies().getPolicyVersion() : servicePolicies.getPolicyVersion(); + boolean result = Objects.equals(dbPolicyVersion, cachedPolicyVersion); + + if (!result && cachedPolicyVersion != null && dbPolicyVersion != null && cachedPolicyVersion < dbPolicyVersion) { + LOG.info("checkCacheSanity(serviceName={}): policy cache has a different version than one in the database. However, changes from {} to {} will be downloaded in the next download. policyVersionInDB={}, policyVersionInCache={}", serviceName, cachedPolicyVersion, dbPolicyVersion, dbPolicyVersion, cachedPolicyVersion); + } + } + + private void pruneUnusedAttributes() { + if (servicePolicies != null) { + pruneUnusedPolicyAttributes(servicePolicies.getPolicies()); + + if (servicePolicies.getTagPolicies() != null) { + pruneUnusedPolicyAttributes(servicePolicies.getTagPolicies().getPolicies()); + } + } + } + + private void pruneUnusedPolicyAttributes(List policies) { + // Null out attributes not required by plug-ins + if (CollectionUtils.isNotEmpty(policies)) { + for (RangerPolicy policy : policies) { + policy.setCreatedBy(null); + policy.setCreateTime(null); + policy.setUpdatedBy(null); + policy.setUpdateTime(null); + // policy.setGuid(null); /* this is used by import policy */ + // policy.setName(null); /* this is used by GUI in policy list page */ + // policy.setDescription(null); /* this is used by export policy */ + policy.setResourceSignature(null); + policy.setOptions(null); + } + } + } + + class ServicePolicyDeltasCache { + final long fromVersion; + final ServicePolicies servicePolicyDeltas; + + ServicePolicyDeltasCache(final long fromVersion, ServicePolicies servicePolicyDeltas) { + this.fromVersion = fromVersion; + this.servicePolicyDeltas = servicePolicyDeltas; + } + + ServicePolicies getServicePolicyDeltasFromVersion(long fromVersion) { + return this.fromVersion == fromVersion ? this.servicePolicyDeltas : null; + } + } + } +} diff --git a/security-admin/src/main/java/org/apache/ranger/common/RangerServiceTagsCache.java b/security-admin/src/main/java/org/apache/ranger/common/RangerServiceTagsCache.java index ec0ff7083a..f759ec335d 100644 --- a/security-admin/src/main/java/org/apache/ranger/common/RangerServiceTagsCache.java +++ b/security-admin/src/main/java/org/apache/ranger/common/RangerServiceTagsCache.java @@ -24,7 +24,6 @@ import org.apache.ranger.authorization.hadoop.config.RangerAdminConfig; import org.apache.ranger.biz.TagDBStore; import org.apache.ranger.plugin.store.TagStore; - import org.apache.ranger.plugin.util.RangerServiceTagsDeltaUtil; import org.apache.ranger.plugin.util.ServiceTags; import org.slf4j.Logger; @@ -38,157 +37,153 @@ import java.util.concurrent.locks.ReentrantLock; public class RangerServiceTagsCache { - private static final Logger LOG = LoggerFactory.getLogger(RangerServiceTagsCache.class); - - private static final int MAX_WAIT_TIME_FOR_UPDATE = 10; - - private static volatile RangerServiceTagsCache sInstance = null; - - private final boolean useServiceTagsCache; - private final int waitTimeInSeconds; - private final boolean dedupStrings; - - private final Map serviceTagsMap = new HashMap<>(); - - public static RangerServiceTagsCache getInstance() { - if (sInstance == null) { - synchronized (RangerServiceTagsCache.class) { - if (sInstance == null) { - sInstance = new RangerServiceTagsCache(); - } - } - } - return sInstance; - } - - private RangerServiceTagsCache() { - RangerAdminConfig config = RangerAdminConfig.getInstance(); - - useServiceTagsCache = config.getBoolean("ranger.admin.tag.download.usecache", true); - waitTimeInSeconds = config.getInt("ranger.admin.tag.download.cache.max.waittime.for.update", MAX_WAIT_TIME_FOR_UPDATE); - dedupStrings = config.getBoolean("ranger.admin.tag.dedup.strings", Boolean.TRUE); - } - - public void dump() { - - if (useServiceTagsCache) { - final Set serviceNames; - - synchronized (this) { - serviceNames = serviceTagsMap.keySet(); - } - - if (CollectionUtils.isNotEmpty(serviceNames)) { - ServiceTagsWrapper cachedServiceTagsWrapper; - - for (String serviceName : serviceNames) { - synchronized (this) { - cachedServiceTagsWrapper = serviceTagsMap.get(serviceName); - } - LOG.debug("serviceName:" + serviceName + ", Cached-MetaData:" + cachedServiceTagsWrapper); - } - } - } - } - - public ServiceTags getServiceTags(String serviceName, Long serviceId, Long lastKnownVersion, boolean needsBackwardCompatibility, TagStore tagStore) throws Exception { - - if (LOG.isDebugEnabled()) { - LOG.debug("==> RangerServiceTagsCache.getServiceTags(" + serviceName + ", " + serviceId + ", " + lastKnownVersion + ", " + needsBackwardCompatibility + ")"); - } - - ServiceTags ret = null; - - if (StringUtils.isNotBlank(serviceName) && serviceId != null) { - - if (LOG.isDebugEnabled()) { - LOG.debug("useServiceTagsCache=" + useServiceTagsCache); - } - - if (!useServiceTagsCache) { - if (tagStore != null) { - try { - ret = tagStore.getServiceTags(serviceName, -1L); - - if (ret != null && dedupStrings) { - ret.dedupStrings(); - } - } catch (Exception exception) { - LOG.error("getServiceTags(" + serviceName + "): failed to get latest tags from tag-store", exception); - } - } else { - LOG.error("getServiceTags(" + serviceName + "): failed to get latest tags as tag-store is null!"); - } - } else { - ServiceTagsWrapper serviceTagsWrapper; - - synchronized (this) { - serviceTagsWrapper = serviceTagsMap.get(serviceName); - - if (serviceTagsWrapper != null) { - if (!serviceId.equals(serviceTagsWrapper.getServiceId())) { - if (LOG.isDebugEnabled()) { - LOG.debug("Service [" + serviceName + "] changed service-id from " + serviceTagsWrapper.getServiceId() - + " to " + serviceId); - LOG.debug("Recreating serviceTagsWrapper for serviceName [" + serviceName + "]"); - } - serviceTagsMap.remove(serviceName); - serviceTagsWrapper = null; - } - } - if (serviceTagsWrapper == null) { - serviceTagsWrapper = new ServiceTagsWrapper(serviceId); - serviceTagsMap.put(serviceName, serviceTagsWrapper); - } - } - - if (tagStore != null) { - ret = serviceTagsWrapper.getLatestOrCached(serviceName, tagStore, lastKnownVersion, needsBackwardCompatibility); - } else { - LOG.error("getServiceTags(" + serviceName + "): failed to get latest tags as tag-store is null!"); - ret = serviceTagsWrapper.getServiceTags(); - } - - } - } else { - LOG.error("getServiceTags() failed to get tags as serviceName is null or blank and/or serviceId is null!"); - } - - if (LOG.isDebugEnabled()) { - LOG.debug("<== RangerServiceTagsCache.getServiceTags(" + serviceName + ", " + serviceId + ", " + lastKnownVersion + ", " + needsBackwardCompatibility + "): count=" + ((ret == null || ret.getTags() == null) ? 0 : ret.getTags().size())); - } - - return ret; - } + private static final Logger LOG = LoggerFactory.getLogger(RangerServiceTagsCache.class); + + private static final int MAX_WAIT_TIME_FOR_UPDATE = 10; + + private static volatile RangerServiceTagsCache sInstance; + + private final boolean useServiceTagsCache; + private final int waitTimeInSeconds; + private final boolean dedupStrings; + + private final Map serviceTagsMap = new HashMap<>(); + + private RangerServiceTagsCache() { + RangerAdminConfig config = RangerAdminConfig.getInstance(); + + useServiceTagsCache = config.getBoolean("ranger.admin.tag.download.usecache", true); + waitTimeInSeconds = config.getInt("ranger.admin.tag.download.cache.max.waittime.for.update", MAX_WAIT_TIME_FOR_UPDATE); + dedupStrings = config.getBoolean("ranger.admin.tag.dedup.strings", Boolean.TRUE); + } + + public static RangerServiceTagsCache getInstance() { + RangerServiceTagsCache me = sInstance; + + if (me == null) { + synchronized (RangerServiceTagsCache.class) { + me = sInstance; + + if (me == null) { + me = new RangerServiceTagsCache(); + sInstance = me; + } + } + } + + return me; + } + + public void dump() { + if (useServiceTagsCache) { + final Set serviceNames; + + synchronized (this) { + serviceNames = serviceTagsMap.keySet(); + } + + if (CollectionUtils.isNotEmpty(serviceNames)) { + ServiceTagsWrapper cachedServiceTagsWrapper; + + for (String serviceName : serviceNames) { + synchronized (this) { + cachedServiceTagsWrapper = serviceTagsMap.get(serviceName); + } + + LOG.debug("serviceName:{}, Cached-MetaData:{}", serviceName, cachedServiceTagsWrapper); + } + } + } + } + + public ServiceTags getServiceTags(String serviceName, Long serviceId, Long lastKnownVersion, boolean needsBackwardCompatibility, TagStore tagStore) throws Exception { + LOG.debug("==> RangerServiceTagsCache.getServiceTags({}, {}, {}, {})", serviceName, serviceId, lastKnownVersion, needsBackwardCompatibility); + + ServiceTags ret = null; + + if (StringUtils.isNotBlank(serviceName) && serviceId != null) { + LOG.debug("useServiceTagsCache={}", useServiceTagsCache); + + if (!useServiceTagsCache) { + if (tagStore != null) { + try { + ret = tagStore.getServiceTags(serviceName, -1L); + + if (ret != null && dedupStrings) { + ret.dedupStrings(); + } + } catch (Exception exception) { + LOG.error("getServiceTags({}): failed to get latest tags from tag-store", serviceName, exception); + } + } else { + LOG.error("getServiceTags({}): failed to get latest tags as tag-store is null!", serviceName); + } + } else { + ServiceTagsWrapper serviceTagsWrapper; + + synchronized (this) { + serviceTagsWrapper = serviceTagsMap.get(serviceName); + + if (serviceTagsWrapper != null) { + if (!serviceId.equals(serviceTagsWrapper.getServiceId())) { + LOG.debug("Service [{}] changed service-id from {} to {}", serviceName, serviceTagsWrapper.getServiceId(), serviceId); + LOG.debug("Recreating serviceTagsWrapper for serviceName [{}]", serviceName); + + serviceTagsMap.remove(serviceName); + serviceTagsWrapper = null; + } + } + if (serviceTagsWrapper == null) { + serviceTagsWrapper = new ServiceTagsWrapper(serviceId); + + serviceTagsMap.put(serviceName, serviceTagsWrapper); + } + } + + if (tagStore != null) { + ret = serviceTagsWrapper.getLatestOrCached(serviceName, tagStore, lastKnownVersion, needsBackwardCompatibility); + } else { + LOG.error("getServiceTags({}): failed to get latest tags as tag-store is null!", serviceName); + + ret = serviceTagsWrapper.getServiceTags(); + } + } + } else { + LOG.error("getServiceTags() failed to get tags as serviceName is null or blank and/or serviceId is null!"); + } + + LOG.debug("<== RangerServiceTagsCache.getServiceTags({}, {}, {}, {}): count={}", serviceName, serviceId, lastKnownVersion, needsBackwardCompatibility, (ret == null || ret.getTags() == null) ? 0 : ret.getTags().size()); + + return ret; + } /** * Reset service tag cache using serviceName if provided. * If serviceName is empty, reset everything. + * * @param serviceName * @return true if was able to reset service tag cache, false otherwise */ public boolean resetCache(final String serviceName) { - if (LOG.isDebugEnabled()) { - LOG.debug("==> RangerServiceTagsCache.resetCache({})", serviceName); - } + LOG.debug("==> RangerServiceTagsCache.resetCache({})", serviceName); boolean ret = false; + synchronized (this) { if (!serviceTagsMap.isEmpty()) { if (StringUtils.isBlank(serviceName)) { serviceTagsMap.clear(); - if (LOG.isDebugEnabled()) { - LOG.debug("RangerServiceTagsCache.resetCache(): Removed policy caching for all services."); - } + + LOG.debug("RangerServiceTagsCache.resetCache(): Removed policy caching for all services."); + ret = true; } else { ServiceTagsWrapper removedServicePoliciesWrapper = serviceTagsMap.remove(serviceName.trim()); // returns null if key not found + ret = removedServicePoliciesWrapper != null; if (ret) { - if (LOG.isDebugEnabled()) { - LOG.debug("RangerServiceTagsCache.resetCache(): Removed policy caching for [{}] service.", serviceName); - } + LOG.debug("RangerServiceTagsCache.resetCache(): Removed policy caching for [{}] service.", serviceName); } else { LOG.warn("RangerServiceTagsCache.resetCache(): Caching for [{}] service not found, hence reset is skipped.", serviceName); } @@ -198,233 +193,210 @@ public boolean resetCache(final String serviceName) { } } - if (LOG.isDebugEnabled()) { - LOG.debug("<== RangerServiceTagsCache.resetCache(): ret={}", ret); - } + LOG.debug("<== RangerServiceTagsCache.resetCache(): ret={}", ret); return ret; } - private class ServiceTagsWrapper { - final Long serviceId; - ServiceTags serviceTags; - Date updateTime = null; - long longestDbLoadTimeInMs = -1; - - ServiceTagsDeltasCache deltaCache; - - class ServiceTagsDeltasCache { - final long fromVersion; - final ServiceTags serviceTagsDelta; - - ServiceTagsDeltasCache(final long fromVersion, ServiceTags serviceTagsDelta) { - this.fromVersion = fromVersion; - this.serviceTagsDelta = serviceTagsDelta; - } - ServiceTags getServiceTagsDeltaFromVersion(long fromVersion) { - return this.fromVersion == fromVersion ? this.serviceTagsDelta : null; - } - } - ReentrantLock lock = new ReentrantLock(); - - ServiceTagsWrapper(Long serviceId) { - this.serviceId = serviceId; - serviceTags = null; - } - - Long getServiceId() { return serviceId; } - - ServiceTags getServiceTags() { - return serviceTags; - } - - Date getUpdateTime() { - return updateTime; - } - - ServiceTags getLatestOrCached(String serviceName, TagStore tagStore, Long lastKnownVersion, boolean needsBackwardCompatibility) throws Exception { - if (LOG.isDebugEnabled()) { - LOG.debug("==> RangerServiceTagsCache.getLatestOrCached(lastKnownVersion=" + lastKnownVersion + ", " + needsBackwardCompatibility + ")"); - } - ServiceTags ret = null; - boolean lockResult = false; - - try { - final boolean isCacheCompletelyLoaded; - - lockResult = lock.tryLock(waitTimeInSeconds, TimeUnit.SECONDS); - if (lockResult) { - - isCacheCompletelyLoaded = getLatest(serviceName, tagStore); - - if (isCacheCompletelyLoaded) { - if (LOG.isDebugEnabled()) { - LOG.debug("ServiceTags cache was completely loaded from database "); - } - } - if (needsBackwardCompatibility || isCacheCompletelyLoaded - || lastKnownVersion == -1L || lastKnownVersion.equals(serviceTags.getTagVersion())) { - // Looking for all tags, or Some disqualifying change encountered - if (LOG.isDebugEnabled()) { - LOG.debug("Need to return all cached ServiceTags: [needsBackwardCompatibility:" + needsBackwardCompatibility + ", isCacheCompletelyLoaded:" + isCacheCompletelyLoaded + ", lastKnownVersion:" + lastKnownVersion + ", serviceTagsVersion:" + serviceTags.getTagVersion() + "]"); - } - ret = this.serviceTags; - } else { - boolean isDeltaCacheReinitialized = false; - ServiceTags serviceTagsDelta = this.deltaCache != null ? this.deltaCache.getServiceTagsDeltaFromVersion(lastKnownVersion) : null; - - if (serviceTagsDelta == null) { - serviceTagsDelta = tagStore.getServiceTagsDelta(serviceName, lastKnownVersion); - isDeltaCacheReinitialized = true; - } - if (serviceTagsDelta != null) { - if (LOG.isDebugEnabled()) { - LOG.debug("Deltas were requested. Returning deltas from lastKnownVersion:[" + lastKnownVersion + "]"); - } - if (isDeltaCacheReinitialized) { - this.deltaCache = new ServiceTagsDeltasCache(lastKnownVersion, serviceTagsDelta); - } - ret = serviceTagsDelta; - } else { - LOG.warn("Deltas were requested, but could not get them!! lastKnownVersion:[" + lastKnownVersion + "]; Returning cached ServiceTags:[" + (serviceTags != null ? serviceTags.getTagVersion() : -1L) + "]"); - - this.deltaCache = null; - ret = this.serviceTags; - } - } - } else { - if (LOG.isDebugEnabled()) { - LOG.debug("Could not get lock in [" + waitTimeInSeconds + "] seconds, returning cached ServiceTags"); - } - ret = this.serviceTags; - } - } catch (InterruptedException exception) { - LOG.error("getLatestOrCached:lock got interrupted..", exception); - } finally { - if (lockResult) { - lock.unlock(); - } - } - if (LOG.isDebugEnabled()) { - LOG.debug("<== RangerServiceTagsCache.getLatestOrCached(lastKnownVersion=" + lastKnownVersion + ", " + needsBackwardCompatibility + "): " + ret); - } - - return ret; - } - - boolean getLatest(String serviceName, TagStore tagStore) throws Exception { - if (LOG.isDebugEnabled()) { - LOG.debug("==> ServiceTagsWrapper.getLatest(" + serviceName + ")"); - } - - boolean isCacheCompletelyLoaded = false; - - final Long cachedServiceTagsVersion = serviceTags != null ? serviceTags.getTagVersion() : -1L; - - if (LOG.isDebugEnabled()) { - LOG.debug("Found ServiceTags in-cache : " + (serviceTags != null)); - } - - Long tagVersionInDb = tagStore.getTagVersion(serviceName); - - if (serviceTags == null || tagVersionInDb == null || !tagVersionInDb.equals(cachedServiceTagsVersion)) { - if (LOG.isDebugEnabled()) { - LOG.debug("loading serviceTags from db ... cachedServiceTagsVersion=" + cachedServiceTagsVersion + ", tagVersionInDb=" + tagVersionInDb); - } - - long startTimeMs = System.currentTimeMillis(); - - ServiceTags serviceTagsFromDb = tagStore.getServiceTags(serviceName, cachedServiceTagsVersion); - - long dbLoadTime = System.currentTimeMillis() - startTimeMs; - - if (dbLoadTime > longestDbLoadTimeInMs) { - longestDbLoadTimeInMs = dbLoadTime; - } - updateTime = new Date(); - - if (serviceTagsFromDb != null) { - if (LOG.isDebugEnabled()) { - LOG.debug("loading serviceTags from database and it took:" + TimeUnit.MILLISECONDS.toSeconds(dbLoadTime) + " seconds"); - } - - if (dedupStrings) { - serviceTagsFromDb.dedupStrings(); - } - - if (serviceTags == null) { - if (LOG.isDebugEnabled()) { - LOG.debug("Initializing ServiceTags cache for the first time"); - } - - this.serviceTags = serviceTagsFromDb; - this.deltaCache = null; - pruneUnusedAttributes(); - isCacheCompletelyLoaded = true; - } else if (!serviceTagsFromDb.getIsDelta()) { - // service-tags are loaded because of some disqualifying event - if (LOG.isDebugEnabled()) { - LOG.debug("Complete set of tag are loaded from database, because of some disqualifying event or because tag-delta is not supported"); - } - - this.serviceTags = serviceTagsFromDb; - this.deltaCache = null; - pruneUnusedAttributes(); - isCacheCompletelyLoaded = true; - } else { // Previously cached service tags are still valid - no disqualifying change - // Rebuild tags cache from original tags and deltas - if (LOG.isDebugEnabled()) { - LOG.debug("Retrieved tag-deltas from database. These will be applied on top of ServiceTags version:[" + cachedServiceTagsVersion + "], tag-deltas:[" + serviceTagsFromDb.getTagVersion() + "]"); - } - - boolean supportsTagsDedeup = TagDBStore.isSupportsTagsDedup(); - this.serviceTags = RangerServiceTagsDeltaUtil.applyDelta(serviceTags, serviceTagsFromDb, supportsTagsDedeup); - this.deltaCache = new ServiceTagsDeltasCache(cachedServiceTagsVersion, serviceTagsFromDb); - } - } else { - LOG.error("Could not get tags from database, from-version:[" + cachedServiceTagsVersion + ")"); - } - if (LOG.isDebugEnabled()) { - LOG.debug("ServiceTags old-version:[" + cachedServiceTagsVersion + "], new-version:[" + serviceTags.getTagVersion() + "]"); - } - } else { - if (LOG.isDebugEnabled()) { - LOG.debug("ServiceTags Cache already has the latest version, version:[" + cachedServiceTagsVersion + "]"); - } - } - - if (LOG.isDebugEnabled()) { - LOG.debug("<== ServiceTagsWrapper.getLatest(" + serviceName + "): " + isCacheCompletelyLoaded); - } - - return isCacheCompletelyLoaded; - } - - private void pruneUnusedAttributes() { - RangerServiceTagsDeltaUtil.pruneUnusedAttributes(this.serviceTags); - } - - StringBuilder toString(StringBuilder sb) { - sb.append("RangerServiceTagsWrapper={"); - - sb.append("updateTime=").append(updateTime) - .append(", longestDbLoadTimeInMs=").append(longestDbLoadTimeInMs) - .append(", Service-Version:").append(serviceTags != null ? serviceTags.getTagVersion() : "null") - .append(", Number-Of-Tags:").append(serviceTags != null ? serviceTags.getTags().size() : 0); - - sb.append("} "); - - return sb; - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - - toString(sb); - - return sb.toString(); - } - } -} + private class ServiceTagsWrapper { + final Long serviceId; + ServiceTags serviceTags; + Date updateTime; + long longestDbLoadTimeInMs = -1; + ServiceTagsDeltasCache deltaCache; + ReentrantLock lock = new ReentrantLock(); + + ServiceTagsWrapper(Long serviceId) { + this.serviceId = serviceId; + serviceTags = null; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + + toString(sb); + + return sb.toString(); + } + + Long getServiceId() { + return serviceId; + } + + ServiceTags getServiceTags() { + return serviceTags; + } + + Date getUpdateTime() { + return updateTime; + } + + ServiceTags getLatestOrCached(String serviceName, TagStore tagStore, Long lastKnownVersion, boolean needsBackwardCompatibility) throws Exception { + LOG.debug("==> RangerServiceTagsCache.getLatestOrCached(lastKnownVersion={}, {})", lastKnownVersion, needsBackwardCompatibility); + + ServiceTags ret = null; + boolean lockResult = false; + + try { + final boolean isCacheCompletelyLoaded; + + lockResult = lock.tryLock(waitTimeInSeconds, TimeUnit.SECONDS); + + if (lockResult) { + isCacheCompletelyLoaded = getLatest(serviceName, tagStore); + + if (isCacheCompletelyLoaded) { + LOG.debug("ServiceTags cache was completely loaded from database "); + } + + if (needsBackwardCompatibility || isCacheCompletelyLoaded || lastKnownVersion == -1L || lastKnownVersion.equals(serviceTags.getTagVersion())) { + // Looking for all tags, or Some disqualifying change encountered + LOG.debug("Need to return all cached ServiceTags: [needsBackwardCompatibility:{}, isCacheCompletelyLoaded:{}, lastKnownVersion:{}, serviceTagsVersion:{}]", needsBackwardCompatibility, isCacheCompletelyLoaded, lastKnownVersion, serviceTags.getTagVersion()); + + ret = this.serviceTags; + } else { + boolean isDeltaCacheReinitialized = false; + ServiceTags serviceTagsDelta = this.deltaCache != null ? this.deltaCache.getServiceTagsDeltaFromVersion(lastKnownVersion) : null; + + if (serviceTagsDelta == null) { + serviceTagsDelta = tagStore.getServiceTagsDelta(serviceName, lastKnownVersion); + isDeltaCacheReinitialized = true; + } + if (serviceTagsDelta != null) { + LOG.debug("Deltas were requested. Returning deltas from lastKnownVersion:[{}]", lastKnownVersion); + + if (isDeltaCacheReinitialized) { + this.deltaCache = new ServiceTagsDeltasCache(lastKnownVersion, serviceTagsDelta); + } + + ret = serviceTagsDelta; + } else { + LOG.warn("Deltas were requested, but could not get them!! lastKnownVersion:[{}]; Returning cached ServiceTags:[{}]", lastKnownVersion, serviceTags != null ? serviceTags.getTagVersion() : -1L); + + this.deltaCache = null; + ret = this.serviceTags; + } + } + } else { + LOG.debug("Could not get lock in [{}] seconds, returning cached ServiceTags", waitTimeInSeconds); + + ret = this.serviceTags; + } + } catch (InterruptedException exception) { + LOG.error("getLatestOrCached:lock got interrupted..", exception); + } finally { + if (lockResult) { + lock.unlock(); + } + } + + LOG.debug("<== RangerServiceTagsCache.getLatestOrCached(lastKnownVersion={}, {}): {}", lastKnownVersion, needsBackwardCompatibility, ret); + + return ret; + } + + boolean getLatest(String serviceName, TagStore tagStore) throws Exception { + LOG.debug("==> ServiceTagsWrapper.getLatest({})", serviceName); + + boolean isCacheCompletelyLoaded = false; + final Long cachedServiceTagsVersion = serviceTags != null ? serviceTags.getTagVersion() : -1L; + + LOG.debug("Found ServiceTags in-cache : {}", serviceTags != null); + + Long tagVersionInDb = tagStore.getTagVersion(serviceName); + + if (serviceTags == null || tagVersionInDb == null || !tagVersionInDb.equals(cachedServiceTagsVersion)) { + LOG.debug("loading serviceTags from db ... cachedServiceTagsVersion={}, tagVersionInDb={}", cachedServiceTagsVersion, tagVersionInDb); + + long startTimeMs = System.currentTimeMillis(); + ServiceTags serviceTagsFromDb = tagStore.getServiceTags(serviceName, cachedServiceTagsVersion); + long dbLoadTime = System.currentTimeMillis() - startTimeMs; + + if (dbLoadTime > longestDbLoadTimeInMs) { + longestDbLoadTimeInMs = dbLoadTime; + } + updateTime = new Date(); + + if (serviceTagsFromDb != null) { + LOG.debug("loading serviceTags from database and it took:{} seconds", TimeUnit.MILLISECONDS.toSeconds(dbLoadTime)); + + if (dedupStrings) { + serviceTagsFromDb.dedupStrings(); + } + + if (serviceTags == null) { + LOG.debug("Initializing ServiceTags cache for the first time"); + + this.serviceTags = serviceTagsFromDb; + this.deltaCache = null; + + pruneUnusedAttributes(); + + isCacheCompletelyLoaded = true; + } else if (!serviceTagsFromDb.getIsDelta()) { + // service-tags are loaded because of some disqualifying event + LOG.debug("Complete set of tag are loaded from database, because of some disqualifying event or because tag-delta is not supported"); + + this.serviceTags = serviceTagsFromDb; + this.deltaCache = null; + + pruneUnusedAttributes(); + + isCacheCompletelyLoaded = true; + } else { // Previously cached service tags are still valid - no disqualifying change + // Rebuild tags cache from original tags and deltas + LOG.debug("Retrieved tag-deltas from database. These will be applied on top of ServiceTags version:[{}], tag-deltas:[{}]", cachedServiceTagsVersion, serviceTagsFromDb.getTagVersion()); + + boolean supportsTagsDedeup = TagDBStore.isSupportsTagsDedup(); + + this.serviceTags = RangerServiceTagsDeltaUtil.applyDelta(serviceTags, serviceTagsFromDb, supportsTagsDedeup); + this.deltaCache = new ServiceTagsDeltasCache(cachedServiceTagsVersion, serviceTagsFromDb); + } + } else { + LOG.error("Could not get tags from database, from-version:[{})", cachedServiceTagsVersion); + } + + LOG.debug("ServiceTags old-version:[{}], new-version:[{}]", cachedServiceTagsVersion, serviceTags.getTagVersion()); + } else { + LOG.debug("ServiceTags Cache already has the latest version, version:[{}]", cachedServiceTagsVersion); + } + + LOG.debug("<== ServiceTagsWrapper.getLatest({}): {}", serviceName, isCacheCompletelyLoaded); + + return isCacheCompletelyLoaded; + } + + StringBuilder toString(StringBuilder sb) { + sb.append("RangerServiceTagsWrapper={"); + + sb.append("updateTime=").append(updateTime) + .append(", longestDbLoadTimeInMs=").append(longestDbLoadTimeInMs) + .append(", Service-Version:").append(serviceTags != null ? serviceTags.getTagVersion() : "null") + .append(", Number-Of-Tags:").append(serviceTags != null ? serviceTags.getTags().size() : 0); + + sb.append("} "); + + return sb; + } + + private void pruneUnusedAttributes() { + RangerServiceTagsDeltaUtil.pruneUnusedAttributes(this.serviceTags); + } + + class ServiceTagsDeltasCache { + final long fromVersion; + final ServiceTags serviceTagsDelta; + + ServiceTagsDeltasCache(final long fromVersion, ServiceTags serviceTagsDelta) { + this.fromVersion = fromVersion; + this.serviceTagsDelta = serviceTagsDelta; + } + + ServiceTags getServiceTagsDeltaFromVersion(long fromVersion) { + return this.fromVersion == fromVersion ? this.serviceTagsDelta : null; + } + } + } +} diff --git a/security-admin/src/main/java/org/apache/ranger/common/RangerUserStoreCache.java b/security-admin/src/main/java/org/apache/ranger/common/RangerUserStoreCache.java index d4fa304196..1b1c1bfc95 100644 --- a/security-admin/src/main/java/org/apache/ranger/common/RangerUserStoreCache.java +++ b/security-admin/src/main/java/org/apache/ranger/common/RangerUserStoreCache.java @@ -27,104 +27,106 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.util.*; +import java.util.Map; +import java.util.Objects; +import java.util.Set; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.ReentrantLock; public class RangerUserStoreCache { - private static final Logger LOG = LoggerFactory.getLogger(RangerUserStoreCache.class); - - private static final int MAX_WAIT_TIME_FOR_UPDATE = 10; - - public static volatile RangerUserStoreCache sInstance = null; - - private final int waitTimeInSeconds; - private final boolean dedupStrings; - private final ReentrantLock lock = new ReentrantLock(); - private RangerUserStore rangerUserStore; - - public static RangerUserStoreCache getInstance() { - if (sInstance == null) { - synchronized (RangerUserStoreCache.class) { - if (sInstance == null) { - sInstance = new RangerUserStoreCache(); - } - } - } - return sInstance; - } - - private RangerUserStoreCache() { - RangerAdminConfig config = RangerAdminConfig.getInstance(); - - this.waitTimeInSeconds = config.getInt("ranger.admin.userstore.download.cache.max.waittime.for.update", MAX_WAIT_TIME_FOR_UPDATE); - this.dedupStrings = config.getBoolean("ranger.admin.userstore.dedup.strings", Boolean.TRUE); - this.rangerUserStore = new RangerUserStore(); - } - - public RangerUserStore getRangerUserStore() { - return this.rangerUserStore; - } - - public RangerUserStore getLatestRangerUserStoreOrCached(XUserMgr xUserMgr) throws Exception { - if (LOG.isDebugEnabled()) { - LOG.debug("==> RangerUserStoreCache.getLatestRangerUserStoreOrCached()"); - } - - RangerUserStore ret = null; - boolean lockResult = false; - - try { - lockResult = lock.tryLock(waitTimeInSeconds, TimeUnit.SECONDS); - - if (lockResult) { - Long cachedUserStoreVersion = rangerUserStore.getUserStoreVersion(); - Long dbUserStoreVersion = xUserMgr.getUserStoreVersion(); - - if (!Objects.equals(cachedUserStoreVersion, dbUserStoreVersion)) { - LOG.info("RangerUserStoreCache refreshing from version " + cachedUserStoreVersion + " to " + dbUserStoreVersion); - final long startTimeMs = System.currentTimeMillis(); - final Set rangerUsersInDB = xUserMgr.getUsers(); - final Set rangerGroupsInDB = xUserMgr.getGroups(); - final Map> userGroups = xUserMgr.getUserGroups(); - final long dbLoadTime = System.currentTimeMillis() - startTimeMs; - - if (LOG.isDebugEnabled()) { - LOG.debug("No. of users from DB = " + rangerUsersInDB.size() + " and no. of groups from DB = " + rangerGroupsInDB.size()); - LOG.debug("No. of userGroupMappings = " + userGroups.size()); - LOG.debug("loading Users from database and it took:" + TimeUnit.MILLISECONDS.toSeconds(dbLoadTime) + " seconds"); - } - - RangerUserStore rangerUserStore = new RangerUserStore(dbUserStoreVersion, rangerUsersInDB, rangerGroupsInDB, userGroups); - - if (dedupStrings) { - rangerUserStore.dedupStrings(); - } - - this.rangerUserStore = rangerUserStore; - - LOG.info("RangerUserStoreCache refreshed from version " + cachedUserStoreVersion + " to " + dbUserStoreVersion + ": users=" + rangerUsersInDB.size() + ", groups=" + rangerGroupsInDB.size() + ", userGroupMappings=" + userGroups.size()); - } - } else { - if (LOG.isDebugEnabled()) { - LOG.debug("Could not get lock in [" + waitTimeInSeconds + "] seconds, returning cached RangerUserStore"); - } - } - } catch (InterruptedException exception) { - LOG.error("RangerUserStoreCache.getLatestRangerUserStoreOrCached:lock got interrupted..", exception); - } finally { - ret = rangerUserStore; - - if (lockResult) { - lock.unlock(); - } - } - - if (LOG.isDebugEnabled()) { - LOG.debug("<== RangerUserStoreCache.getLatestRangerUserStoreOrCached(): ret=" + ret); - } - - return ret; - } -} + private static final Logger LOG = LoggerFactory.getLogger(RangerUserStoreCache.class); + + private static final int MAX_WAIT_TIME_FOR_UPDATE = 10; + + public static volatile RangerUserStoreCache sInstance; + + private final int waitTimeInSeconds; + private final boolean dedupStrings; + private final ReentrantLock lock = new ReentrantLock(); + private RangerUserStore rangerUserStore; + + private RangerUserStoreCache() { + RangerAdminConfig config = RangerAdminConfig.getInstance(); + + this.waitTimeInSeconds = config.getInt("ranger.admin.userstore.download.cache.max.waittime.for.update", MAX_WAIT_TIME_FOR_UPDATE); + this.dedupStrings = config.getBoolean("ranger.admin.userstore.dedup.strings", Boolean.TRUE); + this.rangerUserStore = new RangerUserStore(); + } + + public static RangerUserStoreCache getInstance() { + RangerUserStoreCache me = sInstance; + + if (me == null) { + synchronized (RangerUserStoreCache.class) { + me = sInstance; + + if (me == null) { + me = new RangerUserStoreCache(); + sInstance = me; + } + } + } + + return me; + } + + public RangerUserStore getRangerUserStore() { + return this.rangerUserStore; + } + + public RangerUserStore getLatestRangerUserStoreOrCached(XUserMgr xUserMgr) { + LOG.debug("==> RangerUserStoreCache.getLatestRangerUserStoreOrCached()"); + + RangerUserStore ret; + boolean lockResult = false; + try { + lockResult = lock.tryLock(waitTimeInSeconds, TimeUnit.SECONDS); + + if (lockResult) { + Long cachedUserStoreVersion = rangerUserStore.getUserStoreVersion(); + Long dbUserStoreVersion = xUserMgr.getUserStoreVersion(); + + if (!Objects.equals(cachedUserStoreVersion, dbUserStoreVersion)) { + LOG.info("RangerUserStoreCache refreshing from version {} to {}", cachedUserStoreVersion, dbUserStoreVersion); + + final long startTimeMs = System.currentTimeMillis(); + final Set rangerUsersInDB = xUserMgr.getUsers(); + final Set rangerGroupsInDB = xUserMgr.getGroups(); + final Map> userGroups = xUserMgr.getUserGroups(); + final long dbLoadTime = System.currentTimeMillis() - startTimeMs; + + if (LOG.isDebugEnabled()) { + LOG.debug("No. of users from DB = {} and no. of groups from DB = {}", rangerUsersInDB.size(), rangerGroupsInDB.size()); + LOG.debug("No. of userGroupMappings = {}", userGroups.size()); + LOG.debug("loading Users from database and it took:{} seconds", TimeUnit.MILLISECONDS.toSeconds(dbLoadTime)); + } + + RangerUserStore rangerUserStore = new RangerUserStore(dbUserStoreVersion, rangerUsersInDB, rangerGroupsInDB, userGroups); + + if (dedupStrings) { + rangerUserStore.dedupStrings(); + } + + this.rangerUserStore = rangerUserStore; + + LOG.info("RangerUserStoreCache refreshed from version {} to {}: users={}, groups={}, userGroupMappings={}", cachedUserStoreVersion, dbUserStoreVersion, rangerUsersInDB.size(), rangerGroupsInDB.size(), userGroups.size()); + } + } else { + LOG.debug("Could not get lock in [{}] seconds, returning cached RangerUserStore", waitTimeInSeconds); + } + } catch (InterruptedException exception) { + LOG.error("RangerUserStoreCache.getLatestRangerUserStoreOrCached:lock got interrupted..", exception); + } finally { + ret = rangerUserStore; + + if (lockResult) { + lock.unlock(); + } + } + + LOG.debug("<== RangerUserStoreCache.getLatestRangerUserStoreOrCached(): ret={}", ret); + + return ret; + } +} diff --git a/security-admin/src/main/java/org/apache/ranger/common/RangerValidatorFactory.java b/security-admin/src/main/java/org/apache/ranger/common/RangerValidatorFactory.java index 50640f0710..3b5ed8e3ae 100644 --- a/security-admin/src/main/java/org/apache/ranger/common/RangerValidatorFactory.java +++ b/security-admin/src/main/java/org/apache/ranger/common/RangerValidatorFactory.java @@ -20,10 +20,10 @@ package org.apache.ranger.common; import org.apache.ranger.plugin.model.validation.RangerPolicyValidator; +import org.apache.ranger.plugin.model.validation.RangerRoleValidator; import org.apache.ranger.plugin.model.validation.RangerSecurityZoneValidator; import org.apache.ranger.plugin.model.validation.RangerServiceDefValidator; import org.apache.ranger.plugin.model.validation.RangerServiceValidator; -import org.apache.ranger.plugin.model.validation.RangerRoleValidator; import org.apache.ranger.plugin.store.RoleStore; import org.apache.ranger.plugin.store.SecurityZoneStore; import org.apache.ranger.plugin.store.ServiceStore; @@ -33,23 +33,23 @@ @Service @Scope("singleton") public class RangerValidatorFactory { - public RangerServiceValidator getServiceValidator(ServiceStore store) { - return new RangerServiceValidator(store); - } + public RangerServiceValidator getServiceValidator(ServiceStore store) { + return new RangerServiceValidator(store); + } - public RangerPolicyValidator getPolicyValidator(ServiceStore store) { - return new RangerPolicyValidator(store); - } + public RangerPolicyValidator getPolicyValidator(ServiceStore store) { + return new RangerPolicyValidator(store); + } - public RangerServiceDefValidator getServiceDefValidator(ServiceStore store) { - return new RangerServiceDefValidator(store); - } + public RangerServiceDefValidator getServiceDefValidator(ServiceStore store) { + return new RangerServiceDefValidator(store); + } - public RangerSecurityZoneValidator getSecurityZoneValidator(ServiceStore store, SecurityZoneStore securityZoneStore) { - return new RangerSecurityZoneValidator(store, securityZoneStore); + public RangerSecurityZoneValidator getSecurityZoneValidator(ServiceStore store, SecurityZoneStore securityZoneStore) { + return new RangerSecurityZoneValidator(store, securityZoneStore); } - public RangerRoleValidator getRangerRoleValidator(RoleStore roleStore) { - return new RangerRoleValidator(roleStore); - } + public RangerRoleValidator getRangerRoleValidator(RoleStore roleStore) { + return new RangerRoleValidator(roleStore); + } } 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 index 228b4b4195..e98660ac29 100644 --- a/security-admin/src/main/java/org/apache/ranger/common/RequestContext.java +++ b/security-admin/src/main/java/org/apache/ranger/common/RequestContext.java @@ -17,145 +17,138 @@ * under the License. */ - package org.apache.ranger.common; +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 = RangerCommonEnums.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 + "]"; - } - + private static final long serialVersionUID = -7083383106845193385L; + + private String ipAddress; + private String userAgent; + private String requestURL; + private String serverRequestId; + private int deviceType = RangerCommonEnums.DEVICE_UNKNOWN; + private boolean isSync = true; + private long startTime = System.currentTimeMillis(); + private int clientTimeOffsetInMinute; + + /** + * @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 + "]"; + } } 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 index 026e03dbc3..03c2b2ca17 100644 --- a/security-admin/src/main/java/org/apache/ranger/common/SearchCriteria.java +++ b/security-admin/src/main/java/org/apache/ranger/common/SearchCriteria.java @@ -17,189 +17,180 @@ * under the License. */ - /** +/** * */ package org.apache.ranger.common; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Set; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - - public class SearchCriteria { - Logger logger = LoggerFactory.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 paramList = new HashMap(); - Set nullParamList = new HashSet(); - Set notNullParamList = new HashSet(); - - List searchGroups = new ArrayList(); - - public SearchCriteria() { } - - public SearchCriteria(String paramName, Object paramValue) { - addParam(paramName, paramValue); - } - - /** - * @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 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 getNullParamList() { - return nullParamList; - } - - /** - * @return the notNullParamList - */ - public Set getNotNullParamList() { - return notNullParamList; - } - - /** - * @return the searchGroups - */ - public List getSearchGroups() { - return searchGroups; - } - - /** - * @return the isDistinct - */ - public boolean isDistinct() { - return isDistinct; - } - - /** - * @param isDistinct - * the isDistinct to set - */ - public void setDistinct(boolean isDistinct) { - -// int dbFlavor = RangerBizUtil.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; - } - + Logger logger = LoggerFactory.getLogger(SearchCriteria.class); + + int startIndex; + int maxRows = Integer.MAX_VALUE; + String sortBy; + String sortType; + boolean getCount = true; + Number ownerId; + boolean familyOnly; + boolean getChildren; + boolean isDistinct; + HashMap paramList = new HashMap<>(); + Set nullParamList = new HashSet<>(); + Set notNullParamList = new HashSet<>(); + List searchGroups = new ArrayList<>(); + + public SearchCriteria() {} + + public SearchCriteria(String paramName, Object paramValue) { + addParam(paramName, paramValue); + } + + /** + * @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 getParamList() { + return paramList; + } + + /** + * @param name + * @param value + */ + 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 getNullParamList() { + return nullParamList; + } + + /** + * @return the notNullParamList + */ + public Set getNotNullParamList() { + return notNullParamList; + } + + /** + * @return the searchGroups + */ + public List getSearchGroups() { + return searchGroups; + } + + /** + * @return the isDistinct + */ + public boolean isDistinct() { + return isDistinct; + } + + /** + * @param isDistinct the isDistinct to set + */ + public void setDistinct(boolean isDistinct) { +// int dbFlavor = RangerBizUtil.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; + } } 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 index e51acc0660..52e57033ca 100644 --- a/security-admin/src/main/java/org/apache/ranger/common/SearchField.java +++ b/security-admin/src/main/java/org/apache/ranger/common/SearchField.java @@ -17,7 +17,7 @@ * under the License. */ - /** +/** * */ package org.apache.ranger.common; @@ -26,206 +26,193 @@ 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, NOT_EQUALS - }; - - 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 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; - } + private final String clientFieldName; + private final SEARCH_TYPE searchType; + + private String fieldName; + private DATA_TYPE dataType; + private String regEx; + private String enumName; + private int maxValue; + private List 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; + } + + public static 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; + } + + public static SearchField createLong(String clientFieldName, String fieldName) { + return new SearchField(clientFieldName, fieldName, DATA_TYPE.INTEGER, SEARCH_TYPE.FULL); + } + + public static 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; + } public String getRegEx() { return regEx; } - /** - * @param enumName - * the enumName to set - */ - public void setEnumName(String enumName) { - this.enumName = enumName; - } + /** + * @param regEx the regEx to set + */ + public void setRegEx(String regEx) { + this.regEx = regEx; + } public String getEnumName() { return enumName; } - /** - * @param maxValue - * the maxValue to set - */ - public void setMaxValue(int maxValue) { - this.maxValue = maxValue; - } + /** + * @param enumName the enumName to set + */ + public void setEnumName(String enumName) { + this.enumName = enumName; + } public int getMaxValue() { return maxValue; } - /** - * @return the joinTables - */ - public List getJoinTables() { - return joinTables; - } - - /** - * @param joinTables - * the joinTables to set - */ - public void setJoinTables(List 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(); - } - - 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; - } - public void setCustomCondition(String conditions) { - customCondition=conditions; - } + /** + * @param maxValue the maxValue to set + */ + public void setMaxValue(int maxValue) { + this.maxValue = maxValue; + } + + /** + * @return the joinTables + */ + public List getJoinTables() { + return joinTables; + } + + /** + * @param joinTables the joinTables to set + */ + public void setJoinTables(List 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<>(); + } + + for (String table : joinTables.split(",")) { + 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; + } + + public void setCustomCondition(String conditions) { + customCondition = conditions; + } + + 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, NOT_EQUALS + } } 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 index 78df09e6b3..1c741e47d9 100644 --- a/security-admin/src/main/java/org/apache/ranger/common/SearchGroup.java +++ b/security-admin/src/main/java/org/apache/ranger/common/SearchGroup.java @@ -17,124 +17,134 @@ * under the License. */ - /** +/** * */ package org.apache.ranger.common; +import javax.persistence.Query; + 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 values = new ArrayList(); - List searchGroups = new ArrayList(); - - /** - * @param condition - */ - public SearchGroup(CONDITION condition) { - this.condition = condition; - } - - public String getWhereClause(String prefix) { - if (values == null || values.isEmpty() || searchGroups == null || searchGroups.isEmpty()) { - return ""; - } - - int count = -1; - int innerCount = 0; - StringBuilder whereClause = new StringBuilder("("); - for (SearchValue value : values) { - count++; - if (count > 0) { - if (CONDITION.AND.equals(condition)) { - 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.AND.equals(condition)) { - 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.isEmpty()) - || (searchGroups == null || searchGroups.isEmpty())) { - 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); - } - } + CONDITION condition; + List values = new ArrayList<>(); + List searchGroups = new ArrayList<>(); + + /** + * @param condition + */ + public SearchGroup(CONDITION condition) { + this.condition = condition; + } + + public String getWhereClause(String prefix) { + if (values == null || values.isEmpty() || searchGroups == null || searchGroups.isEmpty()) { + return ""; + } + + int count = -1; + int innerCount = 0; + StringBuilder whereClause = new StringBuilder("("); + + for (SearchValue value : values) { + count++; + + if (count > 0) { + if (CONDITION.AND.equals(condition)) { + 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()).append("_").append(prefix).append("_").append(count).append("_").append(innerCount); + + innerCount++; + } + whereClause.append(") "); + } else { + whereClause.append(searchField.getFieldName()) + .append(" = :").append(searchField.getClientFieldName()).append("_").append(prefix).append("_").append(count); + } + } + + for (SearchGroup searchGroup : searchGroups) { + count++; + + if (count > 0) { + if (CONDITION.AND.equals(condition)) { + 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.isEmpty()) || (searchGroups == null || searchGroups.isEmpty())) { + 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); + } + } + + public enum CONDITION { + AND, OR + } } 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 index 8da2b47b60..75eac3cdb1 100644 --- a/security-admin/src/main/java/org/apache/ranger/common/SearchUtil.java +++ b/security-admin/src/main/java/org/apache/ranger/common/SearchUtil.java @@ -17,771 +17,681 @@ * under the License. */ - /** +/** * */ package org.apache.ranger.common; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import javax.persistence.EntityManager; +import javax.persistence.Query; +import javax.servlet.http.HttpServletRequest; + 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; +@Component +public class SearchUtil { + static final Logger logger = LoggerFactory.getLogger(SearchUtil.class); -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; + @Autowired + RESTErrorUtil restErrorUtil; + @Autowired + RangerConfigUtil configUtil; -@Component -public class SearchUtil { - final static Logger logger = LoggerFactory.getLogger(SearchUtil.class); - - @Autowired - RESTErrorUtil restErrorUtil; - - @Autowired - RangerConfigUtil configUtil; - - // @Autowired - // AKADomainObjectSecurityHandler securityHandler; - - @Autowired - StringUtil stringUtil; - - int minInListLength = 20; - String defaultDateFormat="MM/dd/yyyy"; - - public SearchUtil() { - minInListLength = PropertiesUtil.getIntProperty("ranger.db.min_inlist", minInListLength); - defaultDateFormat = PropertiesUtil.getProperty("ranger.ui.defaultDateformat", defaultDateFormat); - } - - /** - * @param request - * @param sortFields - * @return - */ - public SearchCriteria extractCommonCriterias(HttpServletRequest request, - List sortFields) { - SearchCriteria searchCriteria = new SearchCriteria(); - - int startIndex = restErrorUtil.parseInt( - request.getParameter("startIndex"), 0, - "Invalid value for parameter startIndex", - MessageEnums.INVALID_INPUT_DATA, null, "startIndex"); - startIndex = startIndex < 0 ? 0 : 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 multiValues = extractLongList(request, searchCriteria, - paramName, userFriendlyParamName, paramName); - if (multiValues != null && !multiValues.isEmpty()) { - 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 String extractRoleString(HttpServletRequest request, - SearchCriteria searchCriteria, String paramName, - String userFriendlyParamName, String regEx) { - String value = extractString(request, searchCriteria, paramName, userFriendlyParamName, regEx); - if(!RangerConstants.VALID_USER_ROLE_LIST.contains(value)) { - restErrorUtil.validateString(value, regEx, "Invalid value for " - + userFriendlyParamName, - MessageEnums.INVALID_INPUT_DATA, null, paramName); - } - return value; - } - - public List extractEnum(HttpServletRequest request, - SearchCriteria searchCriteria, String paramName, - String userFriendlyParamName, String listName, int maxValue) { - - ArrayList valueList = new ArrayList(); - 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 == null ? Integer.valueOf(-1) : value, 0, maxValue, - "Invalid value for " + userFriendlyParamName, null, - paramName); - valueList.add(value); - } - if (!valueList.isEmpty()) { - 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 extractStringList(HttpServletRequest request, - SearchCriteria searchCriteria, String paramName, - String userFriendlyParamName, String listName, - String[] validValues, String regEx) { - ArrayList valueList = new ArrayList(); - 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 extractLongList(HttpServletRequest request, - SearchCriteria searchCriteria, String paramName, - String userFriendlyParamName, String listName) { - ArrayList valueList = new ArrayList(); - 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 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 ("asc".equalsIgnoreCase(sortType) - || "desc".equalsIgnoreCase(sortType)) { - 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 searchFields) { - return buildWhereClause(searchCriteria, searchFields, false, false); - } - - @SuppressWarnings("unchecked") - protected StringBuilder buildWhereClause(SearchCriteria searchCriteria, - List searchFields, boolean isNativeQuery, - boolean excludeWhereKeyword) { - - Map paramList = searchCriteria.getParamList(); - - StringBuilder whereClause = new StringBuilder(excludeWhereKeyword ? "" - : "WHERE 1 = 1 "); - - List joinTableList = new ArrayList(); - - 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 intValueList = null; - if (paramValue != null - && (paramValue instanceof Integer || paramValue instanceof Long)) { - intValueList = new ArrayList(); - intValueList.add((Number) paramValue); - } else { - intValueList = (Collection) paramValue; - } - - if (intValueList != null && !intValueList.isEmpty()) { - 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(" (:").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()); - } - } - 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(getSqlOperator(searchField.getSearchType())) - .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(")") - .append(getSqlOperator(searchField.getSearchType())) - .append(":").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(getSqlOperator(searchField.getSearchType())) - .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()) - .append(getSqlOperator(searchField.getSearchType())) - .append(":").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 searchFields) { - - Map 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())) { //NOPMD - // Already addressed while building where clause - } else if (searchField.getDataType() == SearchField.DATA_TYPE.INT_LIST - || isListValue - && searchField.getDataType() == SearchField.DATA_TYPE.INTEGER) { - Collection intValueList = null; - if (paramValue != null - && (paramValue instanceof Integer || paramValue instanceof Long)) { - intValueList = new ArrayList(); - intValueList.add((Number) paramValue); - } else { - intValueList = (Collection) paramValue; - } - - if (intValueList != null && !intValueList.isEmpty() - && 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 searchFields, - 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 List extractIntList(HttpServletRequest request, - SearchCriteria searchCriteria, String paramName, - String userFriendlyParamName, String listName) { - ArrayList valueList = new ArrayList(); - 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; - } - - public String getSqlOperator(SearchField.SEARCH_TYPE searchType) { - final String ret; - - switch (searchType) { - case PARTIAL: - ret = " like "; - break; - - case LESS_THAN: - ret = " < "; - break; - - case LESS_EQUAL_THAN: - ret = " <= "; - break; - - case GREATER_THAN: - ret = " > "; - break; - - case GREATER_EQUAL_THAN: - ret = " >= "; - break; - - case NOT_EQUALS: - ret = " != "; - break; - - case FULL: - default: - ret = " = "; - break; - } - - return ret; - } + // @Autowired + // AKADomainObjectSecurityHandler securityHandler; + + @Autowired + StringUtil stringUtil; + + int minInListLength = 20; + String defaultDateFormat = "MM/dd/yyyy"; + + public SearchUtil() { + minInListLength = PropertiesUtil.getIntProperty("ranger.db.min_inlist", minInListLength); + defaultDateFormat = PropertiesUtil.getProperty("ranger.ui.defaultDateformat", defaultDateFormat); + } + + /** + * @param request + * @param sortFields + * @return + */ + public SearchCriteria extractCommonCriterias(HttpServletRequest request, List sortFields) { + SearchCriteria searchCriteria = new SearchCriteria(); + int startIndex = restErrorUtil.parseInt(request.getParameter("startIndex"), 0, "Invalid value for parameter startIndex", MessageEnums.INVALID_INPUT_DATA, null, "startIndex"); + + startIndex = startIndex < 0 ? 0 : 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 multiValues = extractLongList(request, searchCriteria, paramName, userFriendlyParamName, paramName); + + if (multiValues != null && !multiValues.isEmpty()) { + 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) { + if (dateFormat == null || dateFormat.isEmpty()) { + dateFormat = defaultDateFormat; + } + + Date 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 String extractRoleString(HttpServletRequest request, SearchCriteria searchCriteria, String paramName, String userFriendlyParamName, String regEx) { + String value = extractString(request, searchCriteria, paramName, userFriendlyParamName, regEx); + + if (!RangerConstants.VALID_USER_ROLE_LIST.contains(value)) { + restErrorUtil.validateString(value, regEx, "Invalid value for " + userFriendlyParamName, MessageEnums.INVALID_INPUT_DATA, null, paramName); + } + + return value; + } + + public List extractEnum(HttpServletRequest request, SearchCriteria searchCriteria, String paramName, String userFriendlyParamName, String listName, int maxValue) { + ArrayList valueList = new ArrayList<>(); + 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 == null ? Integer.valueOf(-1) : value, 0, maxValue, "Invalid value for " + userFriendlyParamName, null, paramName); + + valueList.add(value); + } + + if (!valueList.isEmpty()) { + searchCriteria.getParamList().put(listName, valueList); + } + + return valueList; + } + + public List extractStringList(HttpServletRequest request, SearchCriteria searchCriteria, String paramName, String userFriendlyParamName, String listName, String[] validValues, String regEx) { + ArrayList valueList = new ArrayList<>(); + 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 extractLongList(HttpServletRequest request, SearchCriteria searchCriteria, String paramName, String userFriendlyParamName, String listName) { + ArrayList valueList = new ArrayList<>(); + 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 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 ("asc".equalsIgnoreCase(sortType) || "desc".equalsIgnoreCase(sortType)) { + querySortType = sortType; + } else { + logger.error("Invalid sortType. sortType={}", sortType); + } + } + + // Override the sortType using the final value + searchCriteria.setSortType(querySortType.toLowerCase()); + + return " ORDER BY " + querySortBy + " " + querySortType; + } + + return null; + } + + public Query createSearchQuery(EntityManager em, String queryStr, String sortClause, SearchCriteria searchCriteria, List searchFields, 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 List extractIntList(HttpServletRequest request, SearchCriteria searchCriteria, String paramName, String userFriendlyParamName, String listName) { + ArrayList valueList = new ArrayList<>(); + 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; + } + + public String getSqlOperator(SearchField.SEARCH_TYPE searchType) { + final String ret; + + switch (searchType) { + case PARTIAL: + ret = " like "; + break; + + case LESS_THAN: + ret = " < "; + break; + + case LESS_EQUAL_THAN: + ret = " <= "; + break; + + case GREATER_THAN: + ret = " > "; + break; + + case GREATER_EQUAL_THAN: + ret = " >= "; + break; + + case NOT_EQUALS: + ret = " != "; + break; + + case FULL: + default: + ret = " = "; + break; + } + + return ret; + } + + protected StringBuilder buildWhereClause(SearchCriteria searchCriteria, List searchFields) { + return buildWhereClause(searchCriteria, searchFields, false, false); + } + + @SuppressWarnings("unchecked") + protected StringBuilder buildWhereClause(SearchCriteria searchCriteria, List searchFields, boolean isNativeQuery, boolean excludeWhereKeyword) { + Map paramList = searchCriteria.getParamList(); + StringBuilder whereClause = new StringBuilder(excludeWhereKeyword ? "" : "WHERE 1 = 1 "); + List joinTableList = new ArrayList<>(); + 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 = paramValue instanceof Collection; + + 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 intValueList; + + if ((paramValue instanceof Integer || paramValue instanceof Long)) { + intValueList = new ArrayList<>(); + + intValueList.add((Number) paramValue); + } else { + intValueList = (Collection) paramValue; + } + + if (!intValueList.isEmpty()) { + 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()).append("_").append(count); + } + + if (intValueList.size() > 1) { + whereClause.append(" ) "); + } + } else { + whereClause.append(" and ") + .append(searchField.getFieldName()) + .append(" in ") + .append(" (:").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).isEmpty()) { + whereClause.append(" and ") + .append(searchField.getFieldName()) + .append(" in :") + .append(searchField.getClientFieldName()); + } + } 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(getSqlOperator(searchField.getSearchType())) + .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(")") + .append(getSqlOperator(searchField.getSearchType())) + .append(":").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(getSqlOperator(searchField.getSearchType())) + .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()) + .append(getSqlOperator(searchField.getSearchType())) + .append(":").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 searchFields) { + Map 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 = paramValue instanceof Collection; + + if (searchCriteria.getNullParamList().contains(searchField.getClientFieldName()) || searchCriteria.getNotNullParamList().contains(searchField.getClientFieldName())) { //NOPMD + // Already addressed while building where clause + } else if (searchField.getDataType() == SearchField.DATA_TYPE.INT_LIST || isListValue && searchField.getDataType() == SearchField.DATA_TYPE.INTEGER) { + Collection intValueList; + + if ((paramValue instanceof Integer || paramValue instanceof Long)) { + intValueList = new ArrayList<>(); + + intValueList.add((Number) paramValue); + } else { + intValueList = (Collection) paramValue; + } + + if (!intValueList.isEmpty() && intValueList.size() <= minInListLength) { + int count = -1; + + for (Number value : intValueList) { + count++; + + query.setParameter(searchField.getClientFieldName() + "_" + count, value); + } + } else if (intValueList.size() > 1) { + query.setParameter(searchField.getClientFieldName(), intValueList); + } + } else if (searchField.getDataType() == SearchField.DATA_TYPE.STR_LIST) { + if (paramValue != null && !((Collection) paramValue).isEmpty()) { + 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 + } + + /** + * @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; + } } 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 index a02255796a..8763c4e774 100644 --- a/security-admin/src/main/java/org/apache/ranger/common/SearchValue.java +++ b/security-admin/src/main/java/org/apache/ranger/common/SearchValue.java @@ -17,63 +17,59 @@ * under the License. */ - /** +/** * */ package org.apache.ranger.common; -import java.util.List; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.util.List; + /** - * * */ public class SearchValue { static final Logger logger = LoggerFactory.getLogger(SearchValue.class); SearchField searchField; - Object value = null; - List valueList = null; - boolean isNull = false; + Object value; + List valueList; + boolean isNull; - /** + /** * @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; - } + 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 valueList; } /** * @return the searchField */ public SearchField getSearchField() { - return searchField; + return searchField; } - - - public boolean isList() { - return valueList != null && valueList.size() > 1; + return valueList != null && valueList.size() > 1; } - } diff --git a/security-admin/src/main/java/org/apache/ranger/common/ServiceGdsInfoCache.java b/security-admin/src/main/java/org/apache/ranger/common/ServiceGdsInfoCache.java index 3393156680..4084591862 100644 --- a/security-admin/src/main/java/org/apache/ranger/common/ServiceGdsInfoCache.java +++ b/security-admin/src/main/java/org/apache/ranger/common/ServiceGdsInfoCache.java @@ -27,7 +27,12 @@ import org.apache.ranger.plugin.store.ServiceStore; import org.apache.ranger.plugin.util.SearchFilter; import org.apache.ranger.plugin.util.ServiceGdsInfo; -import org.apache.ranger.service.*; +import org.apache.ranger.service.RangerGdsDataShareInDatasetService; +import org.apache.ranger.service.RangerGdsDataShareService; +import org.apache.ranger.service.RangerGdsDatasetInProjectService; +import org.apache.ranger.service.RangerGdsDatasetService; +import org.apache.ranger.service.RangerGdsProjectService; +import org.apache.ranger.service.RangerGdsSharedResourceService; import org.apache.ranger.util.RangerAdminCache; import org.apache.ranger.view.RangerGdsVList; import org.slf4j.Logger; @@ -38,6 +43,7 @@ import org.springframework.transaction.PlatformTransactionManager; import javax.annotation.PostConstruct; + import java.util.ArrayList; import java.util.Date; import java.util.List; @@ -85,7 +91,6 @@ public void init() { setLoader(new ServiceGdsInfoLoader(txManager)); } - private class ServiceGdsInfoLoader extends RangerDBValueLoader { public ServiceGdsInfoLoader(PlatformTransactionManager txManager) { super(txManager); @@ -253,7 +258,7 @@ private List getPolicies(List policyIds) { ret.add(policy); } } catch (Exception excp) { - LOG.error("getPolicies(): failed to get policy with id=" + policyId, excp); + LOG.error("getPolicies(): failed to get policy with id={}", policyId, excp); } } } diff --git a/security-admin/src/main/java/org/apache/ranger/common/ServiceUtil.java b/security-admin/src/main/java/org/apache/ranger/common/ServiceUtil.java index 37ae3f6a25..8ce4741fe2 100644 --- a/security-admin/src/main/java/org/apache/ranger/common/ServiceUtil.java +++ b/security-admin/src/main/java/org/apache/ranger/common/ServiceUtil.java @@ -19,23 +19,6 @@ package org.apache.ranger.common; -import java.security.cert.X509Certificate; -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 java.util.Map.Entry; - -import javax.naming.InvalidNameException; -import javax.naming.ldap.LdapName; -import javax.naming.ldap.Rdn; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.ws.rs.PathParam; -import javax.ws.rs.WebApplicationException; - import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang.StringUtils; import org.apache.ranger.authorization.utils.StringUtil; @@ -45,7 +28,10 @@ import org.apache.ranger.entity.XXUser; import org.apache.ranger.plugin.model.RangerBaseModelObject; import org.apache.ranger.plugin.model.RangerPolicy; +import org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyItem; import org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyItemAccess; +import org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyItemCondition; +import org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyResource; import org.apache.ranger.plugin.model.RangerService; import org.apache.ranger.plugin.store.EmbeddedServiceDefsUtil; import org.apache.ranger.plugin.util.GrantRevokeRequest; @@ -66,809 +52,454 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; +import javax.naming.InvalidNameException; +import javax.naming.ldap.LdapName; +import javax.naming.ldap.Rdn; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.PathParam; +import javax.ws.rs.WebApplicationException; + +import java.security.cert.X509Certificate; +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 java.util.Map.Entry; + @Component public class ServiceUtil { - static final Logger LOG = LoggerFactory.getLogger(ServiceUtil.class); - private static final String REGEX_PREFIX_STR = "regex:"; - private static final int REGEX_PREFIX_STR_LENGTH = REGEX_PREFIX_STR.length(); - - static Map mapServiceTypeToAssetType = new HashMap(); - static Map mapAccessTypeToPermType = new HashMap(); - static String version; - - @Autowired - JSONUtil jsonUtil; - - @Autowired - RangerDaoManager xaDaoMgr; - - @Autowired - RESTErrorUtil restErrorUtil; - - @Autowired - ServiceDBStore svcStore; - - static { - mapServiceTypeToAssetType.put(EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_HDFS_NAME, Integer.valueOf(RangerCommonEnums.ASSET_HDFS)); - mapServiceTypeToAssetType.put(EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_HBASE_NAME, Integer.valueOf(RangerCommonEnums.ASSET_HBASE)); - mapServiceTypeToAssetType.put(EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_HIVE_NAME, Integer.valueOf(RangerCommonEnums.ASSET_HIVE)); - mapServiceTypeToAssetType.put(EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_KNOX_NAME, Integer.valueOf(RangerCommonEnums.ASSET_KNOX)); - mapServiceTypeToAssetType.put(EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_STORM_NAME, Integer.valueOf(RangerCommonEnums.ASSET_STORM)); - - mapAccessTypeToPermType.put("Unknown", 0); - mapAccessTypeToPermType.put("Reset", 1); - mapAccessTypeToPermType.put("read", 2); - mapAccessTypeToPermType.put("write", 3); - mapAccessTypeToPermType.put("create", 4); - mapAccessTypeToPermType.put("delete", 5); - mapAccessTypeToPermType.put("admin", 6); - mapAccessTypeToPermType.put("Obfuscate", 7); - mapAccessTypeToPermType.put("Mask", 8); - mapAccessTypeToPermType.put("execute", 9); - mapAccessTypeToPermType.put("select", 10); - mapAccessTypeToPermType.put("update", 11); - mapAccessTypeToPermType.put("drop", 12); - mapAccessTypeToPermType.put("alter", 13); - mapAccessTypeToPermType.put("index", 14); - mapAccessTypeToPermType.put("lock", 15); - mapAccessTypeToPermType.put("all", 16); - mapAccessTypeToPermType.put("allow", 17); - mapAccessTypeToPermType.put("submitTopology", 18); - mapAccessTypeToPermType.put("fileUpload", 19); - mapAccessTypeToPermType.put("getNimbusConf", 20); - mapAccessTypeToPermType.put("getClusterInfo", 21); - mapAccessTypeToPermType.put("fileDownload", 22); - mapAccessTypeToPermType.put("killTopology", 23); - mapAccessTypeToPermType.put("rebalance", 24); - mapAccessTypeToPermType.put("activate", 25); - mapAccessTypeToPermType.put("deactivate", 26); - mapAccessTypeToPermType.put("getTopologyConf", 27); - mapAccessTypeToPermType.put("getTopology", 28); - mapAccessTypeToPermType.put("getUserTopology", 29); - mapAccessTypeToPermType.put("getTopologyInfo", 30); - mapAccessTypeToPermType.put("uploadNewCredentials", 31); - mapAccessTypeToPermType.put("repladmin", 32); - mapAccessTypeToPermType.put("serviceadmin", 33); - mapAccessTypeToPermType.put("tempudfadmin", 34); - mapAccessTypeToPermType.put("idempotent_write", 35); - mapAccessTypeToPermType.put("describe_configs", 36); - mapAccessTypeToPermType.put("alter_configs", 37); - mapAccessTypeToPermType.put("cluster_action", 38); - - version = "0"; - } - - public RangerService getServiceByName(@PathParam("name") String name) { - if(LOG.isDebugEnabled()) { - LOG.debug("==> ServiceUtil.getServiceByName(" + name + ")"); - } - - RangerService ret = null; - - try { - ret = svcStore.getServiceByName(name); - } catch(WebApplicationException excp) { - throw excp; - } catch(Throwable excp) { - LOG.error("getServiceByName(" + name + ") failed", excp); - - throw restErrorUtil.createRESTException(excp.getMessage()); - } - - if(ret == null) { - throw restErrorUtil.createRESTException(HttpServletResponse.SC_NOT_FOUND, RangerServiceNotFoundException.buildExceptionMsg(name), true); - } - - if(LOG.isDebugEnabled()) { - LOG.debug("<== ServiceUtil.getServiceByName(" + name + "): " + ret); - } - - return ret; - } - - public RangerService toRangerService(VXAsset asset) { - if(asset == null) { - return null; - } - - RangerService ret = new RangerService(); - - dataObjectToRangerObject(asset, ret); - - ret.setType(toServiceType(asset.getAssetType())); - ret.setName(asset.getName()); - ret.setDescription(asset.getDescription()); - ret.setIsEnabled(asset.getActiveStatus() == RangerCommonEnums.STATUS_ENABLED); - ret.setConfigs(jsonUtil.jsonToMap(asset.getConfig())); - - return ret; - } - - public VXAsset toVXAsset(RangerService service) { - if(service == null || toAssetType(service.getType()) == null) { - return null; - } - - VXAsset ret = new VXAsset(); - - rangerObjectToDataObject(service, ret); - - ret.setAssetType(toAssetType(service.getType())); - ret.setName(service.getName()); - ret.setDescription(service.getDescription()); - ret.setActiveStatus(service.getIsEnabled() ? RangerCommonEnums.STATUS_ENABLED : RangerCommonEnums.STATUS_DISABLED); - ret.setConfig(jsonUtil.readMapToString(service.getConfigs())); - - return ret; - } - - public VXRepository toVXRepository(RangerService service){ - if(service == null || toAssetType(service.getType()) == null) { - return null; - } - - VXRepository ret = new VXRepository(); - - rangerObjectToDataObject(service,ret); - - ret.setRepositoryType(service.getType()); - ret.setName(service.getName()); - ret.setDescription(service.getDescription()); - ret.setIsActive(service.getIsEnabled()); - ret.setConfig(jsonUtil.readMapToString(service.getConfigs())); - ret.setVersion(Long.toString(service.getVersion())); - - return ret; - } - - public RangerPolicy toRangerPolicy(VXResource resource, RangerService service) { - if(resource == null) { - return null; - } - - RangerPolicy ret = new RangerPolicy(); - - dataObjectToRangerObject(resource, ret); - - if(service != null) { - ret.setService(service.getName()); - } else { - ret.setService(resource.getAssetName()); - } - - ret.setName(StringUtils.trim(resource.getPolicyName())); - ret.setDescription(resource.getDescription()); - ret.setIsEnabled(resource.getResourceStatus() == RangerCommonEnums.STATUS_ENABLED); - ret.setIsAuditEnabled(resource.getAuditList() != null && !resource.getAuditList().isEmpty()); - - Boolean isPathRecursive = resource.getIsRecursive() == RangerCommonEnums.BOOL_TRUE; - Boolean isTableExcludes = resource.getTableType() == RangerCommonEnums.POLICY_EXCLUSION; - Boolean isColumnExcludes = resource.getColumnType() == RangerCommonEnums.POLICY_EXCLUSION; - - toRangerResourceList(resource.getName(), "path", Boolean.FALSE, isPathRecursive, ret); - toRangerResourceList(resource.getTables(), "table", isTableExcludes, Boolean.FALSE, ret); - toRangerResourceList(resource.getColumnFamilies(), "column-family", Boolean.FALSE, Boolean.FALSE, ret); - toRangerResourceList(resource.getColumns(), "column", isColumnExcludes, Boolean.FALSE, ret); - toRangerResourceList(resource.getDatabases(), "database", Boolean.FALSE, Boolean.FALSE, ret); - toRangerResourceList(resource.getUdfs(), "udf", Boolean.FALSE, Boolean.FALSE, ret); - toRangerResourceList(resource.getTopologies(), "topology", Boolean.FALSE, Boolean.FALSE, ret); - toRangerResourceList(resource.getServices(), "service", Boolean.FALSE, Boolean.FALSE, ret); - toRangerResourceList(resource.getHiveServices(), "hiveservice", Boolean.FALSE, Boolean.FALSE, ret); - - HashMap> sortedPermMap = new HashMap>(); - - // re-group the list with permGroup as the key - if (resource.getPermMapList() != null) { - for(VXPermMap permMap : resource.getPermMapList()) { - String permGrp = permMap.getPermGroup(); - List sortedList = sortedPermMap.get(permGrp); - - if(sortedList == null) { - sortedList = new ArrayList(); - sortedPermMap.put(permGrp, sortedList); - } - - sortedList.add(permMap); - } - } - - Integer assetType = getAssetType(service,ret.getService()); - - for (Entry> entry : sortedPermMap.entrySet()) { - List userList = new ArrayList(); - List groupList = new ArrayList(); - List accessList = new ArrayList(); - String ipAddress = null; - - RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem(); - - for(VXPermMap permMap : entry.getValue()) { - if(permMap.getPermFor() == AppConstants.XA_PERM_FOR_USER) { - String userName = getUserName(permMap); - - if (! userList.contains(userName)) { - userList.add(userName); - } - } else if(permMap.getPermFor() == AppConstants.XA_PERM_FOR_GROUP) { - String groupName = getGroupName(permMap); - - if (! groupList.contains(groupName)) { - groupList.add(groupName); - } - } - - String accessType = toAccessType(permMap.getPermType()); - - if(StringUtils.equalsIgnoreCase(accessType, "Admin")) { - policyItem.setDelegateAdmin(Boolean.TRUE); - if ( assetType != null && assetType == RangerCommonEnums.ASSET_HBASE) { - accessList.add(new RangerPolicyItemAccess(accessType)); - } - } else { - accessList.add(new RangerPolicyItemAccess(accessType)); - } - - ipAddress = permMap.getIpAddress(); - } - - policyItem.setUsers(userList); - policyItem.setGroups(groupList); - policyItem.setAccesses(accessList); - - if(ipAddress != null && !ipAddress.isEmpty()) { - RangerPolicy.RangerPolicyItemCondition ipCondition = new RangerPolicy.RangerPolicyItemCondition("ipaddress", Collections.singletonList(ipAddress)); - - policyItem.addCondition(ipCondition); - } - - ret.addPolicyItem(policyItem); - } - - return ret; - } - - public VXResource toVXResource(RangerPolicy policy, RangerService service) { - if(policy == null || service == null || toAssetType(service.getType()) == null) { - return null; - } - - VXResource ret = new VXResource(); - - rangerObjectToDataObject(policy, ret); - - ret.setAssetName(policy.getService()); - ret.setAssetId(service.getId()); - ret.setAssetType(toAssetType(service.getType())); - ret.setPolicyName(policy.getName()); - ret.setDescription(policy.getDescription()); - ret.setGuid(policy.getGuid()); - ret.setResourceStatus(policy.getIsEnabled() ? RangerCommonEnums.STATUS_ENABLED : RangerCommonEnums.STATUS_DISABLED); - - List auditList = null; - if(policy.getIsAuditEnabled()) { - VXAuditMap auditMap = new VXAuditMap(); - - auditMap.setResourceId(policy.getId()); - auditMap.setAuditType(AppConstants.XA_AUDIT_TYPE_ALL); - - auditList = new ArrayList(); - auditList.add(auditMap); - } - ret.setAuditList(auditList); - - for(Map.Entry e : policy.getResources().entrySet()) { - RangerPolicy.RangerPolicyResource res = e.getValue(); - String resType = e.getKey(); - String resString = getResourceString(res.getValues()); - - if("path".equalsIgnoreCase(resType)) { - ret.setName(resString); - ret.setIsRecursive(Boolean.TRUE.equals(res.getIsRecursive()) ? RangerCommonEnums.BOOL_TRUE : RangerCommonEnums.BOOL_FALSE); - } else if("table".equalsIgnoreCase(resType)) { - ret.setTables(resString); - ret.setTableType(Boolean.TRUE.equals(res.getIsExcludes()) ? RangerCommonEnums.POLICY_EXCLUSION : RangerCommonEnums.POLICY_INCLUSION); - } else if("column-family".equalsIgnoreCase(resType)) { - ret.setColumnFamilies(resString); - } else if("column".equalsIgnoreCase(resType)) { - ret.setColumns(resString); - ret.setColumnType(Boolean.TRUE.equals(res.getIsExcludes()) ? RangerCommonEnums.POLICY_EXCLUSION : RangerCommonEnums.POLICY_INCLUSION); - } else if("database".equalsIgnoreCase(resType)) { - ret.setDatabases(resString); - } else if("udf".equalsIgnoreCase(resType)) { - ret.setUdfs(resString); - } else if("topology".equalsIgnoreCase(resType)) { - ret.setTopologies(resString); - } else if("service".equalsIgnoreCase(resType)) { - ret.setServices(resString); - } else if(resType.equalsIgnoreCase("hiveservice")) { - ret.setHiveServices(resString); - } - } - updateResourceName(ret); - - List permMapList = getVXPermMapList(policy); - - ret.setPermMapList(permMapList); - - return ret; - } - - public VXAsset publicObjecttoVXAsset(VXRepository vXRepository) { - VXAsset ret = new VXAsset(); - publicDataObjectTovXDataObject(vXRepository,ret); - - Integer assetType = toAssetType(vXRepository.getRepositoryType()); - - ret.setAssetType(assetType == null ? -1 : assetType.intValue()); - ret.setName(vXRepository.getName()); - ret.setDescription(vXRepository.getDescription()); - ret.setActiveStatus(vXRepository.getIsActive() ? RangerCommonEnums.STATUS_ENABLED : RangerCommonEnums.STATUS_DISABLED); - ret.setConfig(vXRepository.getConfig()); - return ret; - } - - public VXRepository vXAssetToPublicObject(VXAsset asset) { - VXRepository ret = new VXRepository(); - vXDataObjectToPublicDataObject(ret,asset); - - ret.setRepositoryType(toServiceType(asset.getAssetType())); - ret.setName(asset.getName()); - ret.setDescription(asset.getDescription()); - ret.setIsActive(asset.getActiveStatus() == RangerCommonEnums.STATUS_ENABLED ? true : false); - ret.setConfig(asset.getConfig()); - ret.setVersion(version); - - return ret; - } - - private void toRangerResourceList(String resourceString, String resourceType, Boolean isExcludes, Boolean isRecursive, RangerPolicy policy) { - if(StringUtils.isNotBlank(resourceString)) { - RangerPolicy.RangerPolicyResource resource = policy.getResources().get(resourceType); - - if(resource == null) { - resource = new RangerPolicy.RangerPolicyResource(); - resource.setIsExcludes(isExcludes); - resource.setIsRecursive(isRecursive); - - policy.setResource(resourceType, resource); - } - - for (String val : resourceString.split(",")) { - resource.addValue(val); - } - } - } - - private static String toServiceType(int assetType) { - String ret = null; - - for(Map.Entry e : mapServiceTypeToAssetType.entrySet()) { - if(e.getValue().intValue() == assetType) { - ret = e.getKey(); - - break; - } - } - - return ret; - } - - private static Integer toAssetType(String serviceType) { - Integer ret = null; - - if(serviceType != null) { - ret = mapServiceTypeToAssetType.get(serviceType.toLowerCase()); - } - - return ret; - } - - public static String toAccessType(int permType) { - String ret = null; - - for(Map.Entry e : mapAccessTypeToPermType.entrySet()) { - if(e.getValue().intValue() == permType) { - ret = e.getKey(); - - break; - } - } - - return ret; - } - - private static Integer toPermType(String accessType) { - Integer ret = null; - - for(Map.Entry e : mapAccessTypeToPermType.entrySet()) { - if(e.getKey().equalsIgnoreCase(accessType)) { - ret = e.getValue(); - - break; - } - } - - return ret == null ? 0 : ret; - } - - private RangerBaseModelObject dataObjectToRangerObject(VXDataObject dataObject,RangerBaseModelObject rangerObject) { - RangerBaseModelObject ret = rangerObject; - - ret.setId(dataObject.getId()); - ret.setCreateTime(dataObject.getCreateDate()); - ret.setUpdateTime(dataObject.getUpdateDate()); - ret.setCreatedBy(dataObject.getOwner()); - ret.setUpdatedBy(dataObject.getUpdatedBy()); - - return ret; - } - - private VXDataObject rangerObjectToDataObject(RangerBaseModelObject rangerObject, VXDataObject dataObject) { - VXDataObject ret = dataObject; - - ret.setId(rangerObject.getId()); - ret.setCreateDate(rangerObject.getCreateTime()); - ret.setUpdateDate(rangerObject.getUpdateTime()); - ret.setOwner(rangerObject.getCreatedBy()); - ret.setUpdatedBy(rangerObject.getUpdatedBy()); - - return ret; - } - - private String toVxPolicyIncExc(int policyIncExc) { - String ret = ""; - - switch(policyIncExc) { - case 0: - ret = "Inclusion"; - break; - case 1: - ret = "Exclusion"; - break; - } - return ret; - } - - private void updateResourceName(VXPolicy policy) { - if(policy == null || toAssetType(policy.getRepositoryType()) == null) { - return; - } - - String resourceName = getResourceName(toAssetType(policy.getRepositoryType()), - policy.getResourceName(), - policy.getTables(), - policy.getColumnFamilies(), - policy.getColumns(), - policy.getDatabases(), - policy.getTopologies(), - policy.getServices()); - - policy.setResourceName(resourceName); - } - - private void updateResourceName(VXResource resource) { - if(resource == null) { - return; - } - - String resourceName = getResourceName(resource.getAssetType(), - resource.getName(), - resource.getTables(), - resource.getColumnFamilies(), - resource.getColumns(), - resource.getDatabases(), - resource.getTopologies(), - resource.getServices()); - - resource.setName(resourceName); - } - - private String getResourceName(int assetType, String paths, String tables, String columnFamilies, String columns, String databases, String topologies, String services) { - StringBuilder sb = new StringBuilder(); - - switch(assetType) { - case RangerCommonEnums.ASSET_HDFS: - paths = emptyIfNull(paths); - - sb.append(paths); - break; - - case RangerCommonEnums.ASSET_HBASE: - { - tables = emptyIfNull(tables); - columnFamilies = emptyIfNull(columnFamilies); - columns = emptyIfNull(columns); - - for(String column : columns.split(",")) { - for(String columnFamily : columnFamilies.split(",")) { - for(String table : tables.split(",")) { - if(sb.length() > 0) { - sb.append(","); - } - - sb.append("/").append(table).append("/").append(columnFamily).append("/").append(column); - } - } - } - } - break; - - case RangerCommonEnums.ASSET_HIVE: - { - databases = emptyIfNull(databases); - tables = emptyIfNull(tables); - columns = emptyIfNull(columns); - - for(String column : columns.split(",")) { - for(String table : tables.split(",")) { - for(String database : databases.split(",")) { - if(sb.length() > 0) { - sb.append(","); - } - - sb.append("/").append(database).append("/").append(table).append("/").append(column); - } - } - } - } - break; - - case RangerCommonEnums.ASSET_KNOX: - { - topologies = emptyIfNull(topologies); - services = emptyIfNull(services); - - for(String service : services.split(",")) { - for(String topology : topologies.split(",")) { - if(sb.length() > 0) { - sb.append(","); - } - - sb.append("/").append(topology).append("/").append(service); - } - } - } - break; - - case RangerCommonEnums.ASSET_STORM: - topologies = emptyIfNull(topologies); - - sb.append(topologies); - break; - } - - return sb.toString(); - } - - private String emptyIfNull(String str) { - return str == null ? "" : str; - } - - private String getResourceString(List values) { - String ret = null; - - if(values != null) { - for(String value : values) { - if(ret == null) { - ret = value; - } else if(value != null) { - ret += ("," + value); - } - } - } - - return ret; - } - - private String getUserName(VXPermMap permMap) { - String userName = permMap.getUserName(); - - if(userName == null || userName.isEmpty()) { - Long userId = permMap.getUserId(); - - if(userId != null) { - XXUser xxUser = xaDaoMgr.getXXUser().getById(userId); - - if(xxUser != null) { - userName = xxUser.getName(); - } - } - } - - return userName; - } - - private String getGroupName(VXPermMap permMap) { - String groupName = permMap.getGroupName(); - - if(groupName == null || groupName.isEmpty()) { - Long groupId = permMap.getGroupId(); - - if(groupId != null) { - XXGroup xxGroup = xaDaoMgr.getXXGroup().getById(groupId); - - if(xxGroup != null) { - groupName = xxGroup.getName(); - } - } - } - - return groupName; - - } - - private Long getUserId(String userName) { - Long userId = null; - - if(userName != null) { - XXUser xxUser = xaDaoMgr.getXXUser().findByUserName(userName); - - if(xxUser != null) { - userId = xxUser.getId(); - } - } - - return userId; - } - - private Long getGroupId(String groupName) { - Long groupId = null; - - if(groupName != null) { - XXGroup xxGroup = xaDaoMgr.getXXGroup().findByGroupName(groupName); - - if(xxGroup != null) { - groupId = xxGroup.getId(); - } - } - - return groupId; - } - - public SearchCriteria getMappedSearchParams(HttpServletRequest request, - SearchCriteria searchCriteria) { - - Object typeObj = searchCriteria.getParamValue("type"); - Object statusObj = searchCriteria.getParamValue("status"); - - ArrayList statusList = new ArrayList(); - if (statusObj == null) { - statusList.add(RangerCommonEnums.STATUS_DISABLED); - statusList.add(RangerCommonEnums.STATUS_ENABLED); - } else { - Boolean status = restErrorUtil.parseBoolean( - request.getParameter("status"), "Invalid value for " - + "status", MessageEnums.INVALID_INPUT_DATA, null, - "status"); - int statusEnum = (status == null || 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 rangerServiceListToPublicObjectList(List serviceList) { - - List repoList = new ArrayList(); - for (RangerService service : serviceList) { - VXRepository vXRepo = toVXRepository(service); - - if(vXRepo != null) { - repoList.add(vXRepo); - } - } - VXRepositoryList vXRepositoryList = new VXRepositoryList(repoList); - return vXRepositoryList; - } - - - private VXDataObject vXDataObjectToPublicDataObject(VXDataObject publicDataObject, VXDataObject vXdataObject) { - - VXDataObject ret = publicDataObject; - - ret.setId(vXdataObject.getId()); - ret.setCreateDate(vXdataObject.getCreateDate()); - ret.setUpdateDate(vXdataObject.getUpdateDate()); - ret.setOwner(vXdataObject.getOwner()); - ret.setUpdatedBy(vXdataObject.getUpdatedBy()); - - return ret; - } - - protected VXDataObject publicDataObjectTovXDataObject(VXDataObject publicDataObject,VXDataObject vXDataObject) { - - VXDataObject ret = vXDataObject; - - ret.setId(publicDataObject.getId()); - ret.setCreateDate(publicDataObject.getCreateDate()); - ret.setUpdateDate(publicDataObject.getUpdateDate()); - ret.setOwner(publicDataObject.getOwner()); - ret.setUpdatedBy(publicDataObject.getUpdatedBy()); - - return ret; - } - - - public VXPolicy toVXPolicy(RangerPolicy policy, RangerService service) { - if(policy == null || service == null || toAssetType(service.getType()) == null) { - return null; - } - - VXPolicy ret = new VXPolicy(); - - rangerObjectToDataObject(policy, ret); - - ret.setPolicyName(StringUtils.trim(policy.getName())); - ret.setDescription(policy.getDescription()); - ret.setRepositoryName(policy.getService()); - ret.setIsEnabled(policy.getIsEnabled() ? true : false); - ret.setRepositoryType(service.getType()); - ret.setIsAuditEnabled(policy.getIsAuditEnabled()); - if (policy.getVersion() != null ) { - ret.setVersion(policy.getVersion().toString()); - } else { - ret.setVersion(version); - } - - for(Map.Entry e : policy.getResources().entrySet()) { - RangerPolicy.RangerPolicyResource res = e.getValue(); - String resType = e.getKey(); - String resString = getResourceString(res.getValues()); - - if("path".equalsIgnoreCase(resType)) { - ret.setResourceName(resString); - ret.setIsRecursive(Boolean.TRUE.equals(res.getIsRecursive()) ? true : false); - } else if("table".equalsIgnoreCase(resType)) { - ret.setTables(resString); - ret.setTableType(Boolean.TRUE.equals(res.getIsExcludes()) ? toVxPolicyIncExc(RangerCommonEnums.POLICY_EXCLUSION):toVxPolicyIncExc(RangerCommonEnums.POLICY_INCLUSION)); - } else if("column-family".equalsIgnoreCase(resType)) { - ret.setColumnFamilies(resString); - } else if("column".equalsIgnoreCase(resType)) { - ret.setColumns(resString); - ret.setColumnType(Boolean.TRUE.equals(res.getIsExcludes()) ? toVxPolicyIncExc(RangerCommonEnums.POLICY_EXCLUSION):toVxPolicyIncExc(RangerCommonEnums.POLICY_INCLUSION)); - } else if("database".equalsIgnoreCase(resType)) { - ret.setDatabases(resString); - } else if("udf".equalsIgnoreCase(resType)) { - ret.setUdfs(resString); - } else if("topology".equalsIgnoreCase(resType)) { - ret.setTopologies(resString); - } else if("service".equalsIgnoreCase(resType)) { - ret.setServices(resString); - } else if(resType.equalsIgnoreCase("hiveservice")) { - ret.setHiveServices(resString); - } - } - updateResourceName(ret); - - List vXPermMapList = getVXPermMapList(policy); - - List vXPermObjList = mapPermMapToPermObj(vXPermMapList); - - ret.setPermMapList(vXPermObjList); - - return ret; - } - - - public List getVXPermMapList(RangerPolicy policy) { - - List permMapList = new ArrayList(); - - int permGroup = 0; - for(RangerPolicy.RangerPolicyItem policyItem : policy.getPolicyItems()) { - String ipAddress = null; - - for (RangerPolicy.RangerPolicyItemCondition condition : policyItem.getConditions()) { + static final Logger LOG = LoggerFactory.getLogger(ServiceUtil.class); + + private static final String REGEX_PREFIX_STR = "regex:"; + private static final int REGEX_PREFIX_STR_LENGTH = REGEX_PREFIX_STR.length(); + + static Map mapServiceTypeToAssetType = new HashMap<>(); + static Map mapAccessTypeToPermType = new HashMap<>(); + static String version; + + @Autowired + JSONUtil jsonUtil; + + @Autowired + RangerDaoManager xaDaoMgr; + + @Autowired + RESTErrorUtil restErrorUtil; + + @Autowired + ServiceDBStore svcStore; + + public static String toAccessType(int permType) { + String ret = null; + + for (Map.Entry e : mapAccessTypeToPermType.entrySet()) { + if (e.getValue() == permType) { + ret = e.getKey(); + + break; + } + } + + return ret; + } + + public RangerService getServiceByName(@PathParam("name") String name) { + LOG.debug("==> ServiceUtil.getServiceByName({})", name); + + RangerService ret; + + try { + ret = svcStore.getServiceByName(name); + } catch (WebApplicationException excp) { + throw excp; + } catch (Throwable excp) { + LOG.error("getServiceByName({}) failed", name, excp); + + throw restErrorUtil.createRESTException(excp.getMessage()); + } + + if (ret == null) { + throw restErrorUtil.createRESTException(HttpServletResponse.SC_NOT_FOUND, RangerServiceNotFoundException.buildExceptionMsg(name), true); + } + + LOG.debug("<== ServiceUtil.getServiceByName({}): {}", name, ret); + + return ret; + } + + public RangerService toRangerService(VXAsset asset) { + if (asset == null) { + return null; + } + + RangerService ret = new RangerService(); + + dataObjectToRangerObject(asset, ret); + + ret.setType(toServiceType(asset.getAssetType())); + ret.setName(asset.getName()); + ret.setDescription(asset.getDescription()); + ret.setIsEnabled(asset.getActiveStatus() == RangerCommonEnums.STATUS_ENABLED); + ret.setConfigs(jsonUtil.jsonToMap(asset.getConfig())); + + return ret; + } + + public VXAsset toVXAsset(RangerService service) { + if (service == null || toAssetType(service.getType()) == null) { + return null; + } + + VXAsset ret = new VXAsset(); + + rangerObjectToDataObject(service, ret); + + ret.setAssetType(toAssetType(service.getType())); + ret.setName(service.getName()); + ret.setDescription(service.getDescription()); + ret.setActiveStatus(service.getIsEnabled() ? RangerCommonEnums.STATUS_ENABLED : RangerCommonEnums.STATUS_DISABLED); + ret.setConfig(jsonUtil.readMapToString(service.getConfigs())); + + return ret; + } + + public VXRepository toVXRepository(RangerService service) { + if (service == null || toAssetType(service.getType()) == null) { + return null; + } + + VXRepository ret = new VXRepository(); + + rangerObjectToDataObject(service, ret); + + ret.setRepositoryType(service.getType()); + ret.setName(service.getName()); + ret.setDescription(service.getDescription()); + ret.setIsActive(service.getIsEnabled()); + ret.setConfig(jsonUtil.readMapToString(service.getConfigs())); + ret.setVersion(Long.toString(service.getVersion())); + + return ret; + } + + public RangerPolicy toRangerPolicy(VXResource resource, RangerService service) { + if (resource == null) { + return null; + } + + RangerPolicy ret = new RangerPolicy(); + + dataObjectToRangerObject(resource, ret); + + if (service != null) { + ret.setService(service.getName()); + } else { + ret.setService(resource.getAssetName()); + } + + ret.setName(StringUtils.trim(resource.getPolicyName())); + ret.setDescription(resource.getDescription()); + ret.setIsEnabled(resource.getResourceStatus() == RangerCommonEnums.STATUS_ENABLED); + ret.setIsAuditEnabled(resource.getAuditList() != null && !resource.getAuditList().isEmpty()); + + Boolean isPathRecursive = resource.getIsRecursive() == RangerCommonEnums.BOOL_TRUE; + Boolean isTableExcludes = resource.getTableType() == RangerCommonEnums.POLICY_EXCLUSION; + Boolean isColumnExcludes = resource.getColumnType() == RangerCommonEnums.POLICY_EXCLUSION; + + toRangerResourceList(resource.getName(), "path", Boolean.FALSE, isPathRecursive, ret); + toRangerResourceList(resource.getTables(), "table", isTableExcludes, Boolean.FALSE, ret); + toRangerResourceList(resource.getColumnFamilies(), "column-family", Boolean.FALSE, Boolean.FALSE, ret); + toRangerResourceList(resource.getColumns(), "column", isColumnExcludes, Boolean.FALSE, ret); + toRangerResourceList(resource.getDatabases(), "database", Boolean.FALSE, Boolean.FALSE, ret); + toRangerResourceList(resource.getUdfs(), "udf", Boolean.FALSE, Boolean.FALSE, ret); + toRangerResourceList(resource.getTopologies(), "topology", Boolean.FALSE, Boolean.FALSE, ret); + toRangerResourceList(resource.getServices(), "service", Boolean.FALSE, Boolean.FALSE, ret); + toRangerResourceList(resource.getHiveServices(), "hiveservice", Boolean.FALSE, Boolean.FALSE, ret); + + HashMap> sortedPermMap = new HashMap<>(); + + // re-group the list with permGroup as the key + if (resource.getPermMapList() != null) { + for (VXPermMap permMap : resource.getPermMapList()) { + String permGrp = permMap.getPermGroup(); + List sortedList = sortedPermMap.computeIfAbsent(permGrp, k -> new ArrayList<>()); + + sortedList.add(permMap); + } + } + + Integer assetType = getAssetType(service, ret.getService()); + + for (Entry> entry : sortedPermMap.entrySet()) { + List userList = new ArrayList<>(); + List groupList = new ArrayList<>(); + List accessList = new ArrayList<>(); + String ipAddress = null; + RangerPolicyItem policyItem = new RangerPolicyItem(); + + for (VXPermMap permMap : entry.getValue()) { + if (permMap.getPermFor() == AppConstants.XA_PERM_FOR_USER) { + String userName = getUserName(permMap); + + if (!userList.contains(userName)) { + userList.add(userName); + } + } else if (permMap.getPermFor() == AppConstants.XA_PERM_FOR_GROUP) { + String groupName = getGroupName(permMap); + + if (!groupList.contains(groupName)) { + groupList.add(groupName); + } + } + + String accessType = toAccessType(permMap.getPermType()); + + if (StringUtils.equalsIgnoreCase(accessType, "Admin")) { + policyItem.setDelegateAdmin(Boolean.TRUE); + + if (assetType != null && assetType == RangerCommonEnums.ASSET_HBASE) { + accessList.add(new RangerPolicyItemAccess(accessType)); + } + } else { + accessList.add(new RangerPolicyItemAccess(accessType)); + } + + ipAddress = permMap.getIpAddress(); + } + + policyItem.setUsers(userList); + policyItem.setGroups(groupList); + policyItem.setAccesses(accessList); + + if (ipAddress != null && !ipAddress.isEmpty()) { + RangerPolicyItemCondition ipCondition = new RangerPolicyItemCondition("ipaddress", Collections.singletonList(ipAddress)); + + policyItem.addCondition(ipCondition); + } + + ret.addPolicyItem(policyItem); + } + + return ret; + } + + public VXResource toVXResource(RangerPolicy policy, RangerService service) { + if (policy == null || service == null || toAssetType(service.getType()) == null) { + return null; + } + + VXResource ret = new VXResource(); + + rangerObjectToDataObject(policy, ret); + + ret.setAssetName(policy.getService()); + ret.setAssetId(service.getId()); + ret.setAssetType(toAssetType(service.getType())); + ret.setPolicyName(policy.getName()); + ret.setDescription(policy.getDescription()); + ret.setGuid(policy.getGuid()); + ret.setResourceStatus(policy.getIsEnabled() ? RangerCommonEnums.STATUS_ENABLED : RangerCommonEnums.STATUS_DISABLED); + + List auditList = null; + + if (policy.getIsAuditEnabled()) { + VXAuditMap auditMap = new VXAuditMap(); + + auditMap.setResourceId(policy.getId()); + auditMap.setAuditType(AppConstants.XA_AUDIT_TYPE_ALL); + + auditList = new ArrayList<>(); + + auditList.add(auditMap); + } + + ret.setAuditList(auditList); + + for (Map.Entry e : policy.getResources().entrySet()) { + RangerPolicyResource res = e.getValue(); + String resType = e.getKey(); + String resString = getResourceString(res.getValues()); + + if ("path".equalsIgnoreCase(resType)) { + ret.setName(resString); + ret.setIsRecursive(Boolean.TRUE.equals(res.getIsRecursive()) ? RangerCommonEnums.BOOL_TRUE : RangerCommonEnums.BOOL_FALSE); + } else if ("table".equalsIgnoreCase(resType)) { + ret.setTables(resString); + ret.setTableType(Boolean.TRUE.equals(res.getIsExcludes()) ? RangerCommonEnums.POLICY_EXCLUSION : RangerCommonEnums.POLICY_INCLUSION); + } else if ("column-family".equalsIgnoreCase(resType)) { + ret.setColumnFamilies(resString); + } else if ("column".equalsIgnoreCase(resType)) { + ret.setColumns(resString); + ret.setColumnType(Boolean.TRUE.equals(res.getIsExcludes()) ? RangerCommonEnums.POLICY_EXCLUSION : RangerCommonEnums.POLICY_INCLUSION); + } else if ("database".equalsIgnoreCase(resType)) { + ret.setDatabases(resString); + } else if ("udf".equalsIgnoreCase(resType)) { + ret.setUdfs(resString); + } else if ("topology".equalsIgnoreCase(resType)) { + ret.setTopologies(resString); + } else if ("service".equalsIgnoreCase(resType)) { + ret.setServices(resString); + } else if (resType.equalsIgnoreCase("hiveservice")) { + ret.setHiveServices(resString); + } + } + + updateResourceName(ret); + + List permMapList = getVXPermMapList(policy); + + ret.setPermMapList(permMapList); + + return ret; + } + + public VXAsset publicObjecttoVXAsset(VXRepository vXRepository) { + VXAsset ret = new VXAsset(); + + publicDataObjectTovXDataObject(vXRepository, ret); + + Integer assetType = toAssetType(vXRepository.getRepositoryType()); + + ret.setAssetType(assetType == null ? -1 : assetType); + ret.setName(vXRepository.getName()); + ret.setDescription(vXRepository.getDescription()); + ret.setActiveStatus(vXRepository.getIsActive() ? RangerCommonEnums.STATUS_ENABLED : RangerCommonEnums.STATUS_DISABLED); + ret.setConfig(vXRepository.getConfig()); + + return ret; + } + + public VXRepository vXAssetToPublicObject(VXAsset asset) { + VXRepository ret = new VXRepository(); + + vXDataObjectToPublicDataObject(ret, asset); + + ret.setRepositoryType(toServiceType(asset.getAssetType())); + ret.setName(asset.getName()); + ret.setDescription(asset.getDescription()); + ret.setIsActive(asset.getActiveStatus() == RangerCommonEnums.STATUS_ENABLED); + ret.setConfig(asset.getConfig()); + ret.setVersion(version); + + return ret; + } + + public SearchCriteria getMappedSearchParams(HttpServletRequest request, SearchCriteria searchCriteria) { + Object typeObj = searchCriteria.getParamValue("type"); + Object statusObj = searchCriteria.getParamValue("status"); + ArrayList statusList = new ArrayList<>(); + + if (statusObj == null) { + statusList.add(RangerCommonEnums.STATUS_DISABLED); + statusList.add(RangerCommonEnums.STATUS_ENABLED); + } else { + Boolean status = restErrorUtil.parseBoolean(request.getParameter("status"), "Invalid value for status", MessageEnums.INVALID_INPUT_DATA, null, "status"); + int statusEnum = (status == null || !status) ? 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 rangerServiceListToPublicObjectList(List serviceList) { + List repoList = new ArrayList<>(); + + for (RangerService service : serviceList) { + VXRepository vXRepo = toVXRepository(service); + + if (vXRepo != null) { + repoList.add(vXRepo); + } + } + + return new VXRepositoryList(repoList); + } + + public VXPolicy toVXPolicy(RangerPolicy policy, RangerService service) { + if (policy == null || service == null || toAssetType(service.getType()) == null) { + return null; + } + + VXPolicy ret = new VXPolicy(); + + rangerObjectToDataObject(policy, ret); + + ret.setPolicyName(StringUtils.trim(policy.getName())); + ret.setDescription(policy.getDescription()); + ret.setRepositoryName(policy.getService()); + ret.setIsEnabled(policy.getIsEnabled()); + ret.setRepositoryType(service.getType()); + ret.setIsAuditEnabled(policy.getIsAuditEnabled()); + + if (policy.getVersion() != null) { + ret.setVersion(policy.getVersion().toString()); + } else { + ret.setVersion(version); + } + + for (Map.Entry e : policy.getResources().entrySet()) { + RangerPolicyResource res = e.getValue(); + String resType = e.getKey(); + String resString = getResourceString(res.getValues()); + + if ("path".equalsIgnoreCase(resType)) { + ret.setResourceName(resString); + ret.setIsRecursive(Boolean.TRUE.equals(res.getIsRecursive())); + } else if ("table".equalsIgnoreCase(resType)) { + ret.setTables(resString); + ret.setTableType(Boolean.TRUE.equals(res.getIsExcludes()) ? toVxPolicyIncExc(RangerCommonEnums.POLICY_EXCLUSION) : toVxPolicyIncExc(RangerCommonEnums.POLICY_INCLUSION)); + } else if ("column-family".equalsIgnoreCase(resType)) { + ret.setColumnFamilies(resString); + } else if ("column".equalsIgnoreCase(resType)) { + ret.setColumns(resString); + ret.setColumnType(Boolean.TRUE.equals(res.getIsExcludes()) ? toVxPolicyIncExc(RangerCommonEnums.POLICY_EXCLUSION) : toVxPolicyIncExc(RangerCommonEnums.POLICY_INCLUSION)); + } else if ("database".equalsIgnoreCase(resType)) { + ret.setDatabases(resString); + } else if ("udf".equalsIgnoreCase(resType)) { + ret.setUdfs(resString); + } else if ("topology".equalsIgnoreCase(resType)) { + ret.setTopologies(resString); + } else if ("service".equalsIgnoreCase(resType)) { + ret.setServices(resString); + } else if (resType.equalsIgnoreCase("hiveservice")) { + ret.setHiveServices(resString); + } + } + + updateResourceName(ret); + + List vXPermMapList = getVXPermMapList(policy); + List vXPermObjList = mapPermMapToPermObj(vXPermMapList); + + ret.setPermMapList(vXPermObjList); + + return ret; + } + + public List getVXPermMapList(RangerPolicy policy) { + List permMapList = new ArrayList<>(); + int permGroup = 0; + + for (RangerPolicyItem policyItem : policy.getPolicyItems()) { + String ipAddress = null; + + for (RangerPolicyItemCondition condition : policyItem.getConditions()) { if ("ipaddress".equalsIgnoreCase(condition.getType())) { List values = condition.getValues(); + if (CollectionUtils.isNotEmpty(values)) { // TODO changes this to properly deal with collection for now just returning 1st item ipAddress = values.get(0); @@ -880,750 +511,1142 @@ public List getVXPermMapList(RangerPolicy policy) { } } - for(String userName : policyItem.getUsers()) { - for(RangerPolicyItemAccess access : policyItem.getAccesses()) { - if(! access.getIsAllowed()) { - continue; - } - - VXPermMap permMap = new VXPermMap(); - - permMap.setPermFor(AppConstants.XA_PERM_FOR_USER); - permMap.setPermGroup(Integer.valueOf(permGroup).toString()); - permMap.setUserName(userName); - permMap.setUserId(getUserId(userName)); - permMap.setPermType(toPermType(access.getType())); - permMap.setIpAddress(ipAddress); - - permMapList.add(permMap); - } - - if(policyItem.getDelegateAdmin()) { - VXPermMap permMap = new VXPermMap(); - - permMap.setPermFor(AppConstants.XA_PERM_FOR_USER); - permMap.setPermGroup(Integer.valueOf(permGroup).toString()); - permMap.setUserName(userName); - permMap.setUserId(getUserId(userName)); - permMap.setPermType(toPermType("Admin")); - permMap.setIpAddress(ipAddress); - - permMapList.add(permMap); - } - } - permGroup++; - - for(String groupName : policyItem.getGroups()) { - for(RangerPolicyItemAccess access : policyItem.getAccesses()) { - if(! access.getIsAllowed()) { - continue; - } - - VXPermMap permMap = new VXPermMap(); - - permMap.setPermFor(AppConstants.XA_PERM_FOR_GROUP); - permMap.setPermGroup(Integer.valueOf(permGroup).toString()); - permMap.setGroupName(groupName); - permMap.setGroupId(getGroupId(groupName)); - permMap.setPermType(toPermType(access.getType())); - permMap.setIpAddress(ipAddress); - - permMapList.add(permMap); - } - - if(policyItem.getDelegateAdmin()) { - VXPermMap permMap = new VXPermMap(); - - permMap.setPermFor(AppConstants.XA_PERM_FOR_GROUP); - permMap.setPermGroup(Integer.valueOf(permGroup).toString()); - permMap.setGroupName(groupName); - permMap.setGroupId(getGroupId(groupName)); - permMap.setPermType(toPermType("Admin")); - permMap.setIpAddress(ipAddress); - - permMapList.add(permMap); - } - } - permGroup++; - } - return permMapList; + for (String userName : policyItem.getUsers()) { + for (RangerPolicyItemAccess access : policyItem.getAccesses()) { + if (!access.getIsAllowed()) { + continue; + } + + VXPermMap permMap = new VXPermMap(); + + permMap.setPermFor(AppConstants.XA_PERM_FOR_USER); + permMap.setPermGroup(Integer.valueOf(permGroup).toString()); + permMap.setUserName(userName); + permMap.setUserId(getUserId(userName)); + permMap.setPermType(toPermType(access.getType())); + permMap.setIpAddress(ipAddress); + + permMapList.add(permMap); + } + + if (policyItem.getDelegateAdmin()) { + VXPermMap permMap = new VXPermMap(); + + permMap.setPermFor(AppConstants.XA_PERM_FOR_USER); + permMap.setPermGroup(Integer.valueOf(permGroup).toString()); + permMap.setUserName(userName); + permMap.setUserId(getUserId(userName)); + permMap.setPermType(toPermType("Admin")); + permMap.setIpAddress(ipAddress); + + permMapList.add(permMap); + } + } + + permGroup++; + + for (String groupName : policyItem.getGroups()) { + for (RangerPolicyItemAccess access : policyItem.getAccesses()) { + if (!access.getIsAllowed()) { + continue; + } + + VXPermMap permMap = new VXPermMap(); + + permMap.setPermFor(AppConstants.XA_PERM_FOR_GROUP); + permMap.setPermGroup(Integer.valueOf(permGroup).toString()); + permMap.setGroupName(groupName); + permMap.setGroupId(getGroupId(groupName)); + permMap.setPermType(toPermType(access.getType())); + permMap.setIpAddress(ipAddress); + + permMapList.add(permMap); + } + + if (policyItem.getDelegateAdmin()) { + VXPermMap permMap = new VXPermMap(); + + permMap.setPermFor(AppConstants.XA_PERM_FOR_GROUP); + permMap.setPermGroup(Integer.valueOf(permGroup).toString()); + permMap.setGroupName(groupName); + permMap.setGroupId(getGroupId(groupName)); + permMap.setPermType(toPermType("Admin")); + permMap.setIpAddress(ipAddress); + + permMapList.add(permMap); + } + } + + permGroup++; + } + + return permMapList; + } + + public List mapPermMapToPermObj(List permMapList) { + List permObjList = new ArrayList<>(); + HashMap> sortedPemMap = new HashMap<>(); + + if (permMapList != null) { + for (VXPermMap vXPermMap : permMapList) { + String permGrp = vXPermMap.getPermGroup(); + List sortedList = sortedPemMap.computeIfAbsent(permGrp, k -> new ArrayList<>()); + + sortedList.add(vXPermMap); + } + } + + for (Entry> entry : sortedPemMap.entrySet()) { + VXPermObj vXPermObj = new VXPermObj(); + List userList = new ArrayList<>(); + List groupList = new ArrayList<>(); + List permList = new ArrayList<>(); + String ipAddress = ""; + List 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(); + } + + vXPermObj.setUserList(userList); + vXPermObj.setGroupList(groupList); + vXPermObj.setPermList(permList); + vXPermObj.setIpAddress(ipAddress); + + permObjList.add(vXPermObj); + } + + return permObjList; + } + + public RangerPolicy toRangerPolicy(VXPolicy vXPolicy, RangerService service) { + if (vXPolicy == null || service == null || toAssetType(service.getType()) == null) { + return null; + } + + RangerPolicy ret = new RangerPolicy(); + + ret = (RangerPolicy) dataObjectToRangerObject(vXPolicy, ret); + + ret.setService(service.getName()); + ret.setName(StringUtils.trim(vXPolicy.getPolicyName())); + ret.setDescription(vXPolicy.getDescription()); + ret.setIsEnabled(vXPolicy.getIsEnabled()); + ret.setIsAuditEnabled(vXPolicy.getIsAuditEnabled()); + + Integer assetType = toAssetType(service.getType()); + Boolean isRecursive = Boolean.FALSE; + + if (assetType == RangerCommonEnums.ASSET_HDFS && vXPolicy.getIsRecursive() != null) { + isRecursive = vXPolicy.getIsRecursive(); + } + + Boolean isTableExcludes = Boolean.FALSE; + + if (vXPolicy.getTableType() != null) { + isTableExcludes = vXPolicy.getTableType().equals(RangerCommonEnums.getLabelFor_PolicyType(RangerCommonEnums.POLICY_EXCLUSION)); + } + + Boolean isColumnExcludes = Boolean.FALSE; + + if (vXPolicy.getColumnType() != null) { + isColumnExcludes = vXPolicy.getColumnType().equals(RangerCommonEnums.getLabelFor_PolicyType(RangerCommonEnums.POLICY_EXCLUSION)); + } + + if (assetType == RangerCommonEnums.ASSET_HDFS && vXPolicy.getResourceName() != null) { + toRangerResourceList(vXPolicy.getResourceName(), "path", Boolean.FALSE, isRecursive, ret); + } + + if (vXPolicy.getTables() != null) { + toRangerResourceList(vXPolicy.getTables(), "table", isTableExcludes, isRecursive, ret); + } + + if (vXPolicy.getColumnFamilies() != null) { + toRangerResourceList(vXPolicy.getColumnFamilies(), "column-family", Boolean.FALSE, isRecursive, ret); + } + + if (vXPolicy.getColumns() != null) { + toRangerResourceList(vXPolicy.getColumns(), "column", isColumnExcludes, isRecursive, ret); + } + + if (vXPolicy.getDatabases() != null) { + toRangerResourceList(vXPolicy.getDatabases(), "database", Boolean.FALSE, isRecursive, ret); + } + + if (vXPolicy.getUdfs() != null) { + toRangerResourceList(vXPolicy.getUdfs(), "udf", Boolean.FALSE, isRecursive, ret); + } + + if (vXPolicy.getTopologies() != null) { + toRangerResourceList(vXPolicy.getTopologies(), "topology", Boolean.FALSE, isRecursive, ret); + } + + if (vXPolicy.getServices() != null) { + toRangerResourceList(vXPolicy.getServices(), "service", Boolean.FALSE, isRecursive, ret); + } + + if (vXPolicy.getHiveServices() != null) { + toRangerResourceList(vXPolicy.getHiveServices(), "hiveservice", Boolean.FALSE, isRecursive, ret); + } + + if (vXPolicy.getPermMapList() != null) { + List vXPermObjList = vXPolicy.getPermMapList(); + + for (VXPermObj vXPermObj : vXPermObjList) { + List userList = new ArrayList<>(); + List groupList = new ArrayList<>(); + List accessList = new ArrayList<>(); + String ipAddress = null; + boolean delegatedAdmin = false; + + if (vXPermObj.getUserList() != null) { + for (String user : vXPermObj.getUserList()) { + if (user.contains(getUserName(user))) { + userList.add(user); + } + } + } + + if (vXPermObj.getGroupList() != null) { + for (String group : vXPermObj.getGroupList()) { + if (group.contains(getGroupName(group))) { + groupList.add(group); + } + } + } + + if (vXPermObj.getPermList() != null) { + for (String perm : vXPermObj.getPermList()) { + if (AppConstants.getEnumFor_XAPermType(perm) != 0) { + if ("Admin".equalsIgnoreCase(perm)) { + delegatedAdmin = true; + + if (assetType != RangerCommonEnums.ASSET_HBASE) { + continue; + } + } + + accessList.add(new RangerPolicyItemAccess(perm)); + } + } + } + + if (vXPermObj.getIpAddress() != null) { + ipAddress = vXPermObj.getIpAddress(); + } + + RangerPolicyItem policyItem = new RangerPolicyItem(); + + policyItem.setUsers(userList); + policyItem.setGroups(groupList); + policyItem.setAccesses(accessList); + + if (delegatedAdmin) { + policyItem.setDelegateAdmin(Boolean.TRUE); + } else { + policyItem.setDelegateAdmin(Boolean.FALSE); + } + + if (ipAddress != null && !ipAddress.isEmpty()) { + RangerPolicyItemCondition ipCondition = new RangerPolicyItemCondition("ipaddress", Collections.singletonList(ipAddress)); + + policyItem.addCondition(ipCondition); + } + + ret.addPolicyItem(policyItem); + } + } + + return ret; + } + + public VXPolicyList rangerPolicyListToPublic(List rangerPolicyList, SearchFilter filter) { + RangerService service; + List vXPolicyList = new ArrayList<>(); + VXPolicyList vXPolicyListObj = new VXPolicyList(new ArrayList<>()); + + if (CollectionUtils.isNotEmpty(rangerPolicyList)) { + int totalCount = rangerPolicyList.size(); + int startIndex = filter.getStartIndex(); + int pageSize = filter.getMaxRows(); + int toIndex = Math.min(startIndex + pageSize, totalCount); + String sortType = filter.getSortType(); + String sortBy = filter.getSortBy(); + + for (int i = startIndex; i < toIndex; i++) { + RangerPolicy policy = rangerPolicyList.get(i); + + try { + service = svcStore.getServiceByName(policy.getService()); + } catch (Exception excp) { + throw restErrorUtil.createRESTException(HttpServletResponse.SC_BAD_REQUEST, excp.getMessage(), true); + } + + if (service == null) { + throw restErrorUtil.createRESTException(HttpServletResponse.SC_NOT_FOUND, RangerServiceNotFoundException.buildExceptionMsg(policy.getService()), true); + } + + VXPolicy vXPolicy = toVXPolicy(policy, service); + + if (vXPolicy != null) { + vXPolicyList.add(vXPolicy); + } + } + + vXPolicyListObj = new VXPolicyList(vXPolicyList); + + vXPolicyListObj.setPageSize(pageSize); + vXPolicyListObj.setResultSize(vXPolicyList.size()); + vXPolicyListObj.setStartIndex(startIndex); + vXPolicyListObj.setTotalCount(totalCount); + vXPolicyListObj.setSortBy(sortBy); + vXPolicyListObj.setSortType(sortType); + } + + return vXPolicyListObj; + } + + public GrantRevokeRequest toGrantRevokeRequest(VXPolicy vXPolicy) { + String serviceType; + RangerService service; + GrantRevokeRequest ret = new GrantRevokeRequest(); + + if (vXPolicy != null) { + String serviceName = vXPolicy.getRepositoryName(); + + try { + service = svcStore.getServiceByName(serviceName); + } catch (Exception e) { + LOG.error("{} No Service Found for ServiceName: {}", HttpServletResponse.SC_BAD_REQUEST, serviceName); + + throw restErrorUtil.createRESTException(HttpServletResponse.SC_BAD_REQUEST, e.getMessage() + serviceName, true); + } + + if (service != null) { + serviceType = service.getType(); + } else { + LOG.error("{} No Service Found for ServiceName {}", HttpServletResponse.SC_BAD_REQUEST, serviceName); + + throw restErrorUtil.createRESTException(HttpServletResponse.SC_BAD_REQUEST, "No Service Found for ServiceName" + serviceName, true); + } + + if (vXPolicy.getGrantor() != null) { + ret.setGrantor(vXPolicy.getGrantor()); + } + + ret.setEnableAudit(Boolean.TRUE); + ret.setIsRecursive(Boolean.FALSE); + ret.setReplaceExistingPermissions(toBooleanReplacePerm(vXPolicy.isReplacePerm())); + + Integer assetType = toAssetType(serviceType); + + if (assetType == RangerCommonEnums.ASSET_HIVE) { + String database = StringUtils.isEmpty(vXPolicy.getDatabases()) ? "*" : vXPolicy.getDatabases(); + String table = getTableOrUdf(vXPolicy); + String column = StringUtils.isEmpty(vXPolicy.getColumns()) ? "*" : vXPolicy.getColumns(); + Map mapResource = new HashMap<>(); + + mapResource.put("database", database); + mapResource.put("table", table); + mapResource.put("column", column); + + ret.setResource(mapResource); + } else if (assetType == RangerCommonEnums.ASSET_HBASE) { + String tableName = vXPolicy.getTables(); + String colFamily = vXPolicy.getColumnFamilies(); + String qualifier = vXPolicy.getColumns(); + Map mapResource = new HashMap<>(); + + tableName = StringUtil.isEmpty(tableName) ? "*" : tableName; + colFamily = StringUtil.isEmpty(colFamily) ? "*" : colFamily; + qualifier = StringUtil.isEmpty(qualifier) ? "*" : qualifier; + + mapResource.put("table", tableName); + mapResource.put("column-family", colFamily); + mapResource.put("column", qualifier); + + ret.setResource(mapResource); + } + + List vXPermObjList = vXPolicy.getPermMapList(); + + if (vXPermObjList != null) { + for (VXPermObj vXPermObj : vXPermObjList) { + boolean delegatedAdmin = false; + + if (vXPermObj.getUserList() != null) { + for (String user : vXPermObj.getUserList()) { + if (user.contains(getUserName(user))) { + ret.getUsers().add(user); + } + } + } + + if (vXPermObj.getGroupList() != null) { + for (String group : vXPermObj.getGroupList()) { + if (group.contains(getGroupName(group))) { + ret.getGroups().add(group); + } + } + } + + if (vXPermObj.getPermList() != null) { + for (String perm : vXPermObj.getPermList()) { + if (AppConstants.getEnumFor_XAPermType(perm) != 0) { + if ("Admin".equalsIgnoreCase(perm)) { + delegatedAdmin = true; + + if (assetType != null && assetType != RangerCommonEnums.ASSET_HBASE) { + continue; + } + } + + ret.getAccessTypes().add(perm); + } + } + } + + if (delegatedAdmin) { + ret.setDelegateAdmin(Boolean.TRUE); + } else { + ret.setDelegateAdmin(Boolean.FALSE); + } + } + } + } + return ret; + } + + public boolean isValidateHttpsAuthentication(String serviceName, HttpServletRequest request) { + boolean isValidAuthentication = false; + boolean httpEnabled = PropertiesUtil.getBooleanProperty("ranger.service.http.enabled", true); + X509Certificate[] certchain = (X509Certificate[]) request.getAttribute("javax.servlet.request.X509Certificate"); + String ipAddress = request.getHeader("X-FORWARDED-FOR"); + boolean isSecure = request.isSecure(); + + if (ipAddress == null) { + ipAddress = request.getRemoteAddr(); + } + + if (serviceName == null || serviceName.isEmpty()) { + LOG.error("ServiceName not provided"); + + throw restErrorUtil.createRESTException("Unauthorized access.", MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY); + } + + RangerService service; + + try { + service = svcStore.getServiceByName(serviceName); + } catch (Exception e) { + LOG.error("Requested Service not found. serviceName={}", serviceName); + + throw restErrorUtil.createRESTException("Service:" + serviceName + " not found", MessageEnums.DATA_NOT_FOUND); + } + + if (service == null) { + LOG.error("Requested Service not found. serviceName={}", serviceName); + + throw restErrorUtil.createRESTException(HttpServletResponse.SC_NOT_FOUND, RangerServiceNotFoundException.buildExceptionMsg(serviceName), false); + } + + if (!service.getIsEnabled()) { + LOG.error("Requested Service is disabled. serviceName={}", serviceName); + + throw restErrorUtil.createRESTException("Unauthorized access.", MessageEnums.OPER_NOT_ALLOWED_FOR_STATE); + } + + if (!httpEnabled) { + if (!isSecure) { + LOG.error("Unauthorized access. Only https is allowed. serviceName={}", serviceName); + + throw restErrorUtil.createRESTException("Unauthorized access -" + " only https allowed", MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY); + } + + if (certchain == null || certchain.length == 0) { + LOG.error("Unauthorized access. Unable to get client certificate. serviceName={}", serviceName); + + throw restErrorUtil.createRESTException("Unauthorized access - unable to get client certificate", MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY); + } + + // Check if common name is found in service config + Map configMap = service.getConfigs(); + String cnFromConfig = configMap.get("commonNameForCertificate"); + + if (cnFromConfig == null || cnFromConfig.trim().isEmpty()) { + LOG.error("Unauthorized access. No common name for certificate set. Please check your service config"); + + throw restErrorUtil.createRESTException("Unauthorized access. No common name for certificate set. Please check your service config", MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY); + } + + String cnFromConfigForTest = cnFromConfig; + boolean isRegEx = cnFromConfig.toLowerCase().startsWith(REGEX_PREFIX_STR); + + if (isRegEx) { + cnFromConfigForTest = cnFromConfig.substring(REGEX_PREFIX_STR_LENGTH); + } + + // Perform SAN validation + try { + Collection> subjectAltNames = certchain[0].getSubjectAlternativeNames(); + + if (subjectAltNames != null) { + for (List sanItem : subjectAltNames) { + if (sanItem.size() == 2) { + Integer sanType = (Integer) sanItem.get(0); + String sanValue = (String) sanItem.get(1); + + if ((sanType == 2 || sanType == 7) && (matchNames(sanValue, cnFromConfigForTest, isRegEx))) { + LOG.debug("Client Cert verification successful, matched SAN:{}", sanValue); + + isValidAuthentication = true; + break; + } + } + } + } + } catch (Throwable e) { + LOG.error("Unauthorized access. Error getting SAN from certificate", e); + + throw restErrorUtil.createRESTException("Unauthorized access - Error getting SAN from client certificate", MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY); + } + + // Perform common name validation only if SAN validation did not succeed + if (!isValidAuthentication) { + 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 ("CN".equalsIgnoreCase(rdn.getType())) { + commonName = rdn.getValue() + ""; + break; + } + } + + if (commonName == null) { + LOG.error("Unauthorized access. CName is null. serviceName={}", serviceName); + + throw restErrorUtil.createRESTException("Unauthorized access - Unable to find Common Name from [" + dn + "]", MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY); + } + } catch (InvalidNameException e) { + LOG.error("Invalid Common Name. CName={}, serviceName={}", commonName, serviceName, e); + + throw restErrorUtil.createRESTException("Unauthorized access - Invalid Common Name", MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY); + } + } + + if (commonName != null) { + if (matchNames(commonName, cnFromConfigForTest, isRegEx)) { + LOG.debug("Client Cert verification successful, matched CN {} with {}, wildcard match = {}", commonName, cnFromConfigForTest, isRegEx); + + isValidAuthentication = true; + } + + if (!isValidAuthentication) { + LOG.error("Unauthorized access. expected [{}], found [{}], serviceName={}", cnFromConfigForTest, commonName, serviceName); + + throw restErrorUtil.createRESTException("Unauthorized access. expected [" + cnFromConfigForTest + "], found [" + commonName + "]", MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY); + } + } + } + } else { + isValidAuthentication = true; + } + + return isValidAuthentication; + } + + public boolean isValidService(String serviceName, HttpServletRequest request) { + boolean isValid = true; + + if (serviceName == null || serviceName.isEmpty()) { + LOG.error("ServiceName not provided"); + + throw restErrorUtil.createRESTException("Unauthorized access.", MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY); + } + + RangerService service; + + try { + if (null != request.getAttribute("downloadPolicy") && StringUtils.equalsIgnoreCase(request.getAttribute("downloadPolicy").toString(), "secure")) { + service = svcStore.getServiceByNameForDP(serviceName); + } else { + service = svcStore.getServiceByName(serviceName); + } + } catch (Exception e) { + LOG.error("Requested Service not found. serviceName={}", serviceName); + + throw restErrorUtil.createRESTException("Service:" + serviceName + " not found", MessageEnums.DATA_NOT_FOUND); + } + + if (service == null) { + LOG.error("Requested Service not found. serviceName={}", serviceName); + + throw restErrorUtil.createRESTException(HttpServletResponse.SC_NOT_FOUND, RangerServiceNotFoundException.buildExceptionMsg(serviceName), false); + } + + if (!service.getIsEnabled()) { + LOG.error("Requested Service is disabled. serviceName={}", serviceName); + + throw restErrorUtil.createRESTException("Unauthorized access.", MessageEnums.OPER_NOT_ALLOWED_FOR_STATE); + } + + return isValid; + } + + public List getMatchingPoliciesForResource(HttpServletRequest request, List policyLists) { + List policies = new ArrayList<>(); + final String serviceTypeForTag = EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_TAG_NAME; + + if (request != null) { + String resource = request.getParameter(SearchFilter.POL_RESOURCE); + String serviceType = request.getParameter(SearchFilter.SERVICE_TYPE); + + if (!StringUtil.isEmpty(resource) && !StringUtil.isEmpty(serviceType)) { + List resourceList; + Map rangerPolicyResourceMap; + RangerPolicyResource rangerPolicyResource; + + for (RangerPolicy rangerPolicy : policyLists) { + if (rangerPolicy != null) { + if (serviceTypeForTag.equals(rangerPolicy.getServiceType())) { + policies.add(rangerPolicy); + } else { + rangerPolicyResourceMap = rangerPolicy.getResources(); + + if (rangerPolicyResourceMap != null) { + if (rangerPolicyResourceMap.containsKey("path")) { + rangerPolicyResource = rangerPolicyResourceMap.get("path"); + + if (rangerPolicyResource != null) { + resourceList = rangerPolicyResource.getValues(); + + if (CollectionUtils.isNotEmpty(resourceList) && resourceList.contains(resource)) { + policies.add(rangerPolicy); + } + } + } else if (rangerPolicyResourceMap.containsKey("database")) { + rangerPolicyResource = rangerPolicyResourceMap.get("database"); + + if (rangerPolicyResource != null) { + resourceList = rangerPolicyResource.getValues(); + + if (CollectionUtils.isNotEmpty(resourceList) && resourceList.contains(resource)) { + policies.add(rangerPolicy); + } + } + } + } + } + } + } + + policyLists.clear(); + + if (CollectionUtils.isNotEmpty(policies)) { + policyLists.addAll(policies); + } + } + } + + return policyLists; + } + + protected VXDataObject publicDataObjectTovXDataObject(VXDataObject publicDataObject, VXDataObject vXDataObject) { + VXDataObject ret = vXDataObject; + + ret.setId(publicDataObject.getId()); + ret.setCreateDate(publicDataObject.getCreateDate()); + ret.setUpdateDate(publicDataObject.getUpdateDate()); + ret.setOwner(publicDataObject.getOwner()); + ret.setUpdatedBy(publicDataObject.getUpdatedBy()); + + return ret; + } + + private void toRangerResourceList(String resourceString, String resourceType, Boolean isExcludes, Boolean isRecursive, RangerPolicy policy) { + if (StringUtils.isNotBlank(resourceString)) { + RangerPolicyResource resource = policy.getResources().get(resourceType); + + if (resource == null) { + resource = new RangerPolicyResource(); + + resource.setIsExcludes(isExcludes); + resource.setIsRecursive(isRecursive); + + policy.setResource(resourceType, resource); + } + + for (String val : resourceString.split(",")) { + resource.addValue(val); + } + } + } + + private static String toServiceType(int assetType) { + String ret = null; + + for (Map.Entry e : mapServiceTypeToAssetType.entrySet()) { + if (e.getValue() == assetType) { + ret = e.getKey(); + + break; + } + } + + return ret; + } + + private static Integer toAssetType(String serviceType) { + Integer ret = null; + + if (serviceType != null) { + ret = mapServiceTypeToAssetType.get(serviceType.toLowerCase()); + } + + return ret; + } + + private static Integer toPermType(String accessType) { + Integer ret = null; + + for (Map.Entry e : mapAccessTypeToPermType.entrySet()) { + if (e.getKey().equalsIgnoreCase(accessType)) { + ret = e.getValue(); + + break; + } + } + + return ret == null ? 0 : ret; + } + + private RangerBaseModelObject dataObjectToRangerObject(VXDataObject dataObject, RangerBaseModelObject rangerObject) { + RangerBaseModelObject ret = rangerObject; + + ret.setId(dataObject.getId()); + ret.setCreateTime(dataObject.getCreateDate()); + ret.setUpdateTime(dataObject.getUpdateDate()); + ret.setCreatedBy(dataObject.getOwner()); + ret.setUpdatedBy(dataObject.getUpdatedBy()); + + return ret; + } + + private VXDataObject rangerObjectToDataObject(RangerBaseModelObject rangerObject, VXDataObject dataObject) { + VXDataObject ret = dataObject; + + ret.setId(rangerObject.getId()); + ret.setCreateDate(rangerObject.getCreateTime()); + ret.setUpdateDate(rangerObject.getUpdateTime()); + ret.setOwner(rangerObject.getCreatedBy()); + ret.setUpdatedBy(rangerObject.getUpdatedBy()); + + return ret; + } + + private String toVxPolicyIncExc(int policyIncExc) { + String ret = ""; + + switch (policyIncExc) { + case 0: + ret = "Inclusion"; + break; + case 1: + ret = "Exclusion"; + break; + } + return ret; + } + + private void updateResourceName(VXPolicy policy) { + if (policy == null || toAssetType(policy.getRepositoryType()) == null) { + return; + } + + String resourceName = getResourceName(toAssetType(policy.getRepositoryType()), + policy.getResourceName(), + policy.getTables(), + policy.getColumnFamilies(), + policy.getColumns(), + policy.getDatabases(), + policy.getTopologies(), + policy.getServices()); + + policy.setResourceName(resourceName); + } + + private void updateResourceName(VXResource resource) { + if (resource == null) { + return; + } + + String resourceName = getResourceName(resource.getAssetType(), + resource.getName(), + resource.getTables(), + resource.getColumnFamilies(), + resource.getColumns(), + resource.getDatabases(), + resource.getTopologies(), + resource.getServices()); + + resource.setName(resourceName); + } + + private String getResourceName(int assetType, String paths, String tables, String columnFamilies, String columns, String databases, String topologies, String services) { + StringBuilder sb = new StringBuilder(); + + switch (assetType) { + case RangerCommonEnums.ASSET_HDFS: + paths = emptyIfNull(paths); + + sb.append(paths); + break; + + case RangerCommonEnums.ASSET_HBASE: { + tables = emptyIfNull(tables); + columnFamilies = emptyIfNull(columnFamilies); + columns = emptyIfNull(columns); + + for (String column : columns.split(",")) { + for (String columnFamily : columnFamilies.split(",")) { + for (String table : tables.split(",")) { + if (sb.length() > 0) { + sb.append(","); + } + + sb.append("/").append(table).append("/").append(columnFamily).append("/").append(column); + } + } + } + } + break; + + case RangerCommonEnums.ASSET_HIVE: { + databases = emptyIfNull(databases); + tables = emptyIfNull(tables); + columns = emptyIfNull(columns); + + for (String column : columns.split(",")) { + for (String table : tables.split(",")) { + for (String database : databases.split(",")) { + if (sb.length() > 0) { + sb.append(","); + } + + sb.append("/").append(database).append("/").append(table).append("/").append(column); + } + } + } + } + break; + + case RangerCommonEnums.ASSET_KNOX: { + topologies = emptyIfNull(topologies); + services = emptyIfNull(services); + + for (String service : services.split(",")) { + for (String topology : topologies.split(",")) { + if (sb.length() > 0) { + sb.append(","); + } + + sb.append("/").append(topology).append("/").append(service); + } + } + } + break; + + case RangerCommonEnums.ASSET_STORM: + topologies = emptyIfNull(topologies); + + sb.append(topologies); + break; + } + + return sb.toString(); + } + + private String emptyIfNull(String str) { + return str == null ? "" : str; + } + + private String getResourceString(List values) { + String ret = null; + + if (values != null) { + for (String value : values) { + if (ret == null) { + ret = value; + } else if (value != null) { + ret += ("," + value); + } + } + } + + return ret; + } + + private String getUserName(VXPermMap permMap) { + String userName = permMap.getUserName(); + + if (userName == null || userName.isEmpty()) { + Long userId = permMap.getUserId(); + + if (userId != null) { + XXUser xxUser = xaDaoMgr.getXXUser().getById(userId); + + if (xxUser != null) { + userName = xxUser.getName(); + } + } + } + + return userName; + } + + private String getGroupName(VXPermMap permMap) { + String groupName = permMap.getGroupName(); + + if (groupName == null || groupName.isEmpty()) { + Long groupId = permMap.getGroupId(); + + if (groupId != null) { + XXGroup xxGroup = xaDaoMgr.getXXGroup().getById(groupId); + + if (xxGroup != null) { + groupName = xxGroup.getName(); + } + } + } + + return groupName; + } + + private Long getUserId(String userName) { + Long userId = null; + + if (userName != null) { + XXUser xxUser = xaDaoMgr.getXXUser().findByUserName(userName); + + if (xxUser != null) { + userId = xxUser.getId(); + } + } + + return userId; + } + + private Long getGroupId(String groupName) { + Long groupId = null; + + if (groupName != null) { + XXGroup xxGroup = xaDaoMgr.getXXGroup().findByGroupName(groupName); + + if (xxGroup != null) { + groupId = xxGroup.getId(); + } + } + + return groupId; + } + + private VXDataObject vXDataObjectToPublicDataObject(VXDataObject publicDataObject, VXDataObject vXdataObject) { + VXDataObject ret = publicDataObject; + + ret.setId(vXdataObject.getId()); + ret.setCreateDate(vXdataObject.getCreateDate()); + ret.setUpdateDate(vXdataObject.getUpdateDate()); + ret.setOwner(vXdataObject.getOwner()); + ret.setUpdatedBy(vXdataObject.getUpdatedBy()); + + return ret; + } + + private String getUserName(String userName) { + if (userName == null || userName.isEmpty()) { + XXUser xxUser = xaDaoMgr.getXXUser().findByUserName(userName); + + if (xxUser != null) { + userName = xxUser.getName(); + } + } + return userName; + } + + private String getGroupName(String groupName) { + if (groupName == null || groupName.isEmpty()) { + XXGroup xxGroup = xaDaoMgr.getXXGroup().findByGroupName(groupName); + + if (xxGroup != null) { + groupName = xxGroup.getName(); + } + } + + return groupName; + } + + private String getTableOrUdf(VXPolicy vXPolicy) { + String ret = null; + String table = vXPolicy.getTables(); + String udf = vXPolicy.getUdfs(); + + if (!StringUtils.isEmpty(table)) { + ret = table; + } else if (!StringUtils.isEmpty(udf)) { + ret = udf; + } + + return ret; + } + + private boolean matchNames(String target, String source, boolean wildcardMatch) { + boolean matched = false; + + if (target != null && source != null) { + String[] names = (wildcardMatch ? new String[] {source} : source.split(",")); + + for (String n : names) { + if (wildcardMatch) { + LOG.debug("Wildcard Matching [{}] with [{}]", target, n); + + if (wildcardMatch(target, n)) { + LOG.debug("Matched target: {} with {}", target, n); + + matched = true; + break; + } + } else { + LOG.debug("Matching [{}] with [{}]", target, n); + + if (target.equalsIgnoreCase(n)) { + LOG.debug("Matched target:{} with {}", target, n); + + matched = true; + break; + } + } + } + } else { + LOG.debug("source=[{}],target=[{}], returning false.", source, target); + } + + return matched; + } + + private boolean wildcardMatch(String target, String source) { + boolean matched = false; + + if (target != null && source != null) { + try { + matched = target.matches(source); + } catch (Throwable e) { + LOG.error("Error doing wildcard match..", e); + } + } else { + LOG.debug("source=[{}],target=[{}], returning false.", source, target); + } + + return matched; + } + + private Boolean toBooleanReplacePerm(boolean isReplacePermission) { + Boolean ret; + + if (isReplacePermission) { + ret = Boolean.TRUE; + } else { + ret = Boolean.FALSE; + } + + return ret; + } + + private Integer getAssetType(RangerService service, String serviceName) { + if (service == null || StringUtils.isEmpty(service.getType())) { + try { + service = svcStore.getServiceByName(serviceName); + } catch (Exception e) { + LOG.info("{} No Service Found for ServiceName:{}", HttpServletResponse.SC_BAD_REQUEST, serviceName); + + throw restErrorUtil.createRESTException(HttpServletResponse.SC_BAD_REQUEST, e.getMessage() + serviceName, true); + } + } + + String serviceType = service != null ? service.getType() : null; + + return toAssetType(serviceType); + } + + static { + mapServiceTypeToAssetType.put(EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_HDFS_NAME, RangerCommonEnums.ASSET_HDFS); + mapServiceTypeToAssetType.put(EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_HBASE_NAME, RangerCommonEnums.ASSET_HBASE); + mapServiceTypeToAssetType.put(EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_HIVE_NAME, RangerCommonEnums.ASSET_HIVE); + mapServiceTypeToAssetType.put(EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_KNOX_NAME, RangerCommonEnums.ASSET_KNOX); + mapServiceTypeToAssetType.put(EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_STORM_NAME, RangerCommonEnums.ASSET_STORM); + + mapAccessTypeToPermType.put("Unknown", 0); + mapAccessTypeToPermType.put("Reset", 1); + mapAccessTypeToPermType.put("read", 2); + mapAccessTypeToPermType.put("write", 3); + mapAccessTypeToPermType.put("create", 4); + mapAccessTypeToPermType.put("delete", 5); + mapAccessTypeToPermType.put("admin", 6); + mapAccessTypeToPermType.put("Obfuscate", 7); + mapAccessTypeToPermType.put("Mask", 8); + mapAccessTypeToPermType.put("execute", 9); + mapAccessTypeToPermType.put("select", 10); + mapAccessTypeToPermType.put("update", 11); + mapAccessTypeToPermType.put("drop", 12); + mapAccessTypeToPermType.put("alter", 13); + mapAccessTypeToPermType.put("index", 14); + mapAccessTypeToPermType.put("lock", 15); + mapAccessTypeToPermType.put("all", 16); + mapAccessTypeToPermType.put("allow", 17); + mapAccessTypeToPermType.put("submitTopology", 18); + mapAccessTypeToPermType.put("fileUpload", 19); + mapAccessTypeToPermType.put("getNimbusConf", 20); + mapAccessTypeToPermType.put("getClusterInfo", 21); + mapAccessTypeToPermType.put("fileDownload", 22); + mapAccessTypeToPermType.put("killTopology", 23); + mapAccessTypeToPermType.put("rebalance", 24); + mapAccessTypeToPermType.put("activate", 25); + mapAccessTypeToPermType.put("deactivate", 26); + mapAccessTypeToPermType.put("getTopologyConf", 27); + mapAccessTypeToPermType.put("getTopology", 28); + mapAccessTypeToPermType.put("getUserTopology", 29); + mapAccessTypeToPermType.put("getTopologyInfo", 30); + mapAccessTypeToPermType.put("uploadNewCredentials", 31); + mapAccessTypeToPermType.put("repladmin", 32); + mapAccessTypeToPermType.put("serviceadmin", 33); + mapAccessTypeToPermType.put("tempudfadmin", 34); + mapAccessTypeToPermType.put("idempotent_write", 35); + mapAccessTypeToPermType.put("describe_configs", 36); + mapAccessTypeToPermType.put("alter_configs", 37); + mapAccessTypeToPermType.put("cluster_action", 38); + + version = "0"; } - - - public List mapPermMapToPermObj(List permMapList) { - - List permObjList = new ArrayList(); - HashMap> sortedPemMap = new HashMap>(); - - if (permMapList != null) { - for (VXPermMap vXPermMap : permMapList) { - - String permGrp = vXPermMap.getPermGroup(); - List sortedList = sortedPemMap.get(permGrp); - if (sortedList == null) { - sortedList = new ArrayList(); - sortedPemMap.put(permGrp, sortedList); - } - sortedList.add(vXPermMap); - } - } - - for (Entry> entry : sortedPemMap.entrySet()) { - VXPermObj vXPermObj = new VXPermObj(); - List userList = new ArrayList(); - List groupList = new ArrayList(); - List permList = new ArrayList(); - String ipAddress = ""; - - List 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(); - } - vXPermObj.setUserList(userList); - vXPermObj.setGroupList(groupList); - vXPermObj.setPermList(permList); - vXPermObj.setIpAddress(ipAddress); - - permObjList.add(vXPermObj); - } - return permObjList; - } - - - public RangerPolicy toRangerPolicy(VXPolicy vXPolicy, RangerService service ) { - if(vXPolicy == null || service == null || toAssetType(service.getType()) == null) { - return null; - } - - RangerPolicy ret = new RangerPolicy(); - - ret = (RangerPolicy) dataObjectToRangerObject(vXPolicy, ret); - - ret.setService(service.getName()); - ret.setName(StringUtils.trim(vXPolicy.getPolicyName())); - ret.setDescription(vXPolicy.getDescription()); - ret.setIsEnabled(vXPolicy.getIsEnabled() == true); - ret.setIsAuditEnabled(vXPolicy.getIsAuditEnabled()); - - Integer assetType = toAssetType(service.getType()); - - Boolean isRecursive = Boolean.FALSE; - if (assetType == RangerCommonEnums.ASSET_HDFS && vXPolicy.getIsRecursive() != null) { - isRecursive = vXPolicy.getIsRecursive(); - } - - Boolean isTableExcludes = Boolean.FALSE; - if ( vXPolicy.getTableType() != null) { - isTableExcludes = vXPolicy.getTableType().equals(RangerCommonEnums.getLabelFor_PolicyType(RangerCommonEnums.POLICY_EXCLUSION)); - } - - Boolean isColumnExcludes = Boolean.FALSE; - if ( vXPolicy.getColumnType() != null) { - isColumnExcludes = vXPolicy.getColumnType().equals(RangerCommonEnums.getLabelFor_PolicyType(RangerCommonEnums.POLICY_EXCLUSION)); - } - - if (assetType == RangerCommonEnums.ASSET_HDFS && vXPolicy.getResourceName() != null ) { - toRangerResourceList(vXPolicy.getResourceName(), "path", Boolean.FALSE, isRecursive, ret); - } - - if (vXPolicy.getTables() != null) { - toRangerResourceList(vXPolicy.getTables(), "table", isTableExcludes, isRecursive, ret); - } - - if (vXPolicy.getColumnFamilies() != null) { - toRangerResourceList(vXPolicy.getColumnFamilies(), "column-family", Boolean.FALSE, isRecursive, ret); - } - - if (vXPolicy.getColumns() != null) { - toRangerResourceList(vXPolicy.getColumns(), "column", isColumnExcludes, isRecursive, ret); - } - - if (vXPolicy.getDatabases() != null) { - toRangerResourceList(vXPolicy.getDatabases(), "database", Boolean.FALSE, isRecursive, ret); - } - - if (vXPolicy.getUdfs() != null) { - toRangerResourceList(vXPolicy.getUdfs(), "udf", Boolean.FALSE, isRecursive, ret); - } - - if (vXPolicy.getTopologies() != null) { - toRangerResourceList(vXPolicy.getTopologies(), "topology", Boolean.FALSE, isRecursive, ret); - } - - if (vXPolicy.getServices() != null) { - toRangerResourceList(vXPolicy.getServices(), "service", Boolean.FALSE, isRecursive, ret); - } - - if (vXPolicy.getHiveServices() != null) { - toRangerResourceList(vXPolicy.getHiveServices(), "hiveservice", Boolean.FALSE, isRecursive, ret); - } - - if ( vXPolicy.getPermMapList() != null) { - List vXPermObjList = vXPolicy.getPermMapList(); - - for(VXPermObj vXPermObj : vXPermObjList ) { - List userList = new ArrayList(); - List groupList = new ArrayList(); - List accessList = new ArrayList(); - String ipAddress = null; - boolean delegatedAdmin = false; - - if (vXPermObj.getUserList() != null) { - for (String user : vXPermObj.getUserList() ) { - if ( user.contains(getUserName(user))) { - userList.add(user); - } - } - } - - if (vXPermObj.getGroupList() != null) { - for (String group : vXPermObj.getGroupList()) { - if ( group.contains(getGroupName(group))) { - groupList.add(group); - } - } - } - - if (vXPermObj.getPermList() != null) { - for (String perm : vXPermObj.getPermList()) { - if ( AppConstants.getEnumFor_XAPermType(perm) != 0 ) { - if ("Admin".equalsIgnoreCase(perm)) { - delegatedAdmin=true; - if (assetType != RangerCommonEnums.ASSET_HBASE) { - continue; - } - } - accessList.add(new RangerPolicyItemAccess(perm)); - } - } - } - - if (vXPermObj.getIpAddress() != null ) { - ipAddress = vXPermObj.getIpAddress(); - } - - RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem(); - - policyItem.setUsers(userList); - policyItem.setGroups(groupList); - policyItem.setAccesses(accessList); - - if (delegatedAdmin) { - policyItem.setDelegateAdmin(Boolean.TRUE); - } else { - policyItem.setDelegateAdmin(Boolean.FALSE); - } - - if(ipAddress != null && !ipAddress.isEmpty()) { - RangerPolicy.RangerPolicyItemCondition ipCondition = new RangerPolicy.RangerPolicyItemCondition("ipaddress", Collections.singletonList(ipAddress)); - - policyItem.addCondition(ipCondition); - } - - ret.addPolicyItem(policyItem); - } - } - - return ret; - } - - private String getUserName(String userName) { - if(userName == null || userName.isEmpty()) { - - XXUser xxUser = xaDaoMgr.getXXUser().findByUserName(userName); - - if(xxUser != null) { - userName = xxUser.getName(); - } - } - return userName; - } - - - private String getGroupName(String groupName) { - - if(groupName == null || groupName.isEmpty()) { - XXGroup xxGroup = xaDaoMgr.getXXGroup().findByGroupName(groupName); - - if(xxGroup != null) { - groupName = xxGroup.getName(); - } - } - return groupName; - } - - - public VXPolicyList rangerPolicyListToPublic(List rangerPolicyList,SearchFilter filter) { - - RangerService service = null; - List vXPolicyList = new ArrayList(); - - VXPolicyList vXPolicyListObj = new VXPolicyList(new ArrayList()); - if(CollectionUtils.isNotEmpty(rangerPolicyList)) { - int totalCount = rangerPolicyList.size(); - int startIndex = filter.getStartIndex(); - int pageSize = filter.getMaxRows(); - int toIndex = Math.min(startIndex + pageSize, totalCount); - String sortType = filter.getSortType(); - String sortBy = filter.getSortBy(); - for(int i = startIndex; i < toIndex; i++) { - RangerPolicy policy =rangerPolicyList.get(i); - try { - service = svcStore.getServiceByName(policy.getService()); - } catch(Exception excp) { - throw restErrorUtil.createRESTException(HttpServletResponse.SC_BAD_REQUEST, excp.getMessage(), true); - } - if(service == null) { - throw restErrorUtil.createRESTException(HttpServletResponse.SC_NOT_FOUND, RangerServiceNotFoundException.buildExceptionMsg(policy.getService()), true); - } - VXPolicy vXPolicy = toVXPolicy(policy,service); - if(vXPolicy != null) { - vXPolicyList.add(vXPolicy); - } - } - vXPolicyListObj = new VXPolicyList(vXPolicyList); - vXPolicyListObj.setPageSize(pageSize); - vXPolicyListObj.setResultSize(vXPolicyList.size()); - vXPolicyListObj.setStartIndex(startIndex); - vXPolicyListObj.setTotalCount(totalCount); - vXPolicyListObj.setSortBy(sortBy); - vXPolicyListObj.setSortType(sortType); - } - return vXPolicyListObj; - } - - - public GrantRevokeRequest toGrantRevokeRequest(VXPolicy vXPolicy) { - String serviceType = null; - RangerService service = null; - GrantRevokeRequest ret = new GrantRevokeRequest(); - - if ( vXPolicy != null) { - String serviceName = vXPolicy.getRepositoryName(); - try { - service = svcStore.getServiceByName(serviceName); - } catch (Exception e) { - LOG.error( HttpServletResponse.SC_BAD_REQUEST + "No Service Found for ServiceName:" + serviceName ); - throw restErrorUtil.createRESTException(HttpServletResponse.SC_BAD_REQUEST, e.getMessage() + serviceName, true); - } - - if ( service != null) { - serviceType = service.getType(); - } else { - LOG.error( HttpServletResponse.SC_BAD_REQUEST + "No Service Found for ServiceName" + serviceName ); - throw restErrorUtil.createRESTException(HttpServletResponse.SC_BAD_REQUEST, "No Service Found for ServiceName" + serviceName, true); - } - - if (vXPolicy.getGrantor() != null) { - ret.setGrantor(vXPolicy.getGrantor()); - } - ret.setEnableAudit(Boolean.TRUE); - - ret.setIsRecursive(Boolean.FALSE); - - ret.setReplaceExistingPermissions(toBooleanReplacePerm(vXPolicy.isReplacePerm())); - - Integer assetType = toAssetType(serviceType); - - if (assetType == RangerCommonEnums.ASSET_HIVE) { - - String database = StringUtils.isEmpty(vXPolicy.getDatabases()) ? "*" : vXPolicy.getDatabases(); - String table = getTableOrUdf(vXPolicy); - String column = StringUtils.isEmpty(vXPolicy.getColumns()) ? "*" : vXPolicy.getColumns(); - - Map mapResource = new HashMap(); - mapResource.put("database", database); - mapResource.put("table", table); - mapResource.put("column", column); - ret.setResource(mapResource); - } - else if ( assetType == RangerCommonEnums.ASSET_HBASE) { - - String tableName = vXPolicy.getTables(); - tableName = StringUtil.isEmpty(tableName) ? "*" : tableName; - - String colFamily = vXPolicy.getColumnFamilies(); - colFamily = StringUtil.isEmpty(colFamily) ? "*": colFamily; - - String qualifier = vXPolicy.getColumns(); - qualifier = StringUtil.isEmpty(qualifier) ? "*" : qualifier; - - Map mapResource = new HashMap(); - mapResource.put("table", tableName); - mapResource.put("column-family", colFamily); - mapResource.put("column", qualifier); - ret.setResource(mapResource); - - } - - List vXPermObjList = vXPolicy.getPermMapList(); - - if (vXPermObjList != null) { - for(VXPermObj vXPermObj : vXPermObjList ) { - boolean delegatedAdmin = false; - - if (vXPermObj.getUserList() != null ) { - for (String user : vXPermObj.getUserList() ) { - if ( user.contains(getUserName(user))) { - ret.getUsers().add(user); - } - } - } - - if (vXPermObj.getGroupList() != null) { - for (String group : vXPermObj.getGroupList()) { - if ( group.contains(getGroupName(group))) { - ret.getGroups().add(group); - } - } - } - - if(vXPermObj.getPermList() != null) { - for (String perm : vXPermObj.getPermList()) { - if ( AppConstants.getEnumFor_XAPermType(perm) != 0 ) { - if ("Admin".equalsIgnoreCase(perm)) { - delegatedAdmin=true; - if (assetType!=null && assetType.intValue() != RangerCommonEnums.ASSET_HBASE) { - continue; - } - } - ret.getAccessTypes().add(perm); - } - } - } - - if (delegatedAdmin) { - ret.setDelegateAdmin(Boolean.TRUE); - } else { - ret.setDelegateAdmin(Boolean.FALSE); - } - } - - } - } - return ret; - - } - - private String getTableOrUdf(VXPolicy vXPolicy) { - String ret = null; - String table = vXPolicy.getTables(); - String udf = vXPolicy.getUdfs(); - - if (!StringUtils.isEmpty(table)) { - ret = table; - } else if (!StringUtils.isEmpty(udf)) { - ret = udf; - } - return ret; - } - - - public boolean isValidateHttpsAuthentication( String serviceName, HttpServletRequest request) { - boolean isValidAuthentication=false; - boolean httpEnabled = PropertiesUtil.getBooleanProperty("ranger.service.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(); - - if (serviceName == null || serviceName.isEmpty()) { - LOG.error("ServiceName not provided"); - throw restErrorUtil.createRESTException("Unauthorized access.", - MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY); - } - - RangerService service = null; - try { - service = svcStore.getServiceByName(serviceName); - } catch (Exception e) { - LOG.error("Requested Service not found. serviceName=" + serviceName); - throw restErrorUtil.createRESTException("Service:" + serviceName + " not found", - MessageEnums.DATA_NOT_FOUND); - } - if(service==null){ - LOG.error("Requested Service not found. serviceName=" + serviceName); - throw restErrorUtil.createRESTException(HttpServletResponse.SC_NOT_FOUND, RangerServiceNotFoundException.buildExceptionMsg(serviceName), - false); - } - if(!service.getIsEnabled()){ - LOG.error("Requested Service is disabled. serviceName=" + serviceName); - throw restErrorUtil.createRESTException("Unauthorized access.", - MessageEnums.OPER_NOT_ALLOWED_FOR_STATE); - } - if (!httpEnabled) { - if (!isSecure) { - LOG.error("Unauthorized access. Only https is allowed. serviceName=" + serviceName); - throw restErrorUtil.createRESTException("Unauthorized access -" - + " only https allowed", - MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY); - } - if (certchain == null || certchain.length == 0) { - LOG.error("Unauthorized access. Unable to get client certificate. serviceName=" + serviceName); - throw restErrorUtil.createRESTException("Unauthorized access -" - + " unable to get client certificate", - MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY); - } - - // Check if common name is found in service config - Map configMap = service.getConfigs(); - String cnFromConfig = configMap.get("commonNameForCertificate"); - if (cnFromConfig == null || "".equals(cnFromConfig.trim())) { - LOG.error("Unauthorized access. No common name for certificate set. Please check your service config"); - throw restErrorUtil.createRESTException("Unauthorized access. No common name for certificate set. Please check your service config", - MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY); - } - - - String cnFromConfigForTest = cnFromConfig; - boolean isRegEx = cnFromConfig.toLowerCase().startsWith(REGEX_PREFIX_STR); - if (isRegEx) { - cnFromConfigForTest = cnFromConfig.substring(REGEX_PREFIX_STR_LENGTH); - } - - // Perform SAN validation - try { - Collection> subjectAltNames = certchain[0].getSubjectAlternativeNames(); - if (subjectAltNames != null) { - for (List sanItem : subjectAltNames) { - if (sanItem.size() == 2) { - Integer sanType = (Integer) sanItem.get(0); - String sanValue = (String) sanItem.get(1); - if ( (sanType == 2 || sanType == 7) && (matchNames(sanValue, cnFromConfigForTest,isRegEx)) ) { - if (LOG.isDebugEnabled()) LOG.debug("Client Cert verification successful, matched SAN:" + sanValue); - isValidAuthentication=true; - break; - } - } - } - } - } catch (Throwable e) { - LOG.error("Unauthorized access. Error getting SAN from certificate", e); - throw restErrorUtil.createRESTException("Unauthorized access - Error getting SAN from client certificate", MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY); - } - - // Perform common name validation only if SAN validation did not succeed - if (!isValidAuthentication) { - 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 ("CN".equalsIgnoreCase(rdn.getType())) { - commonName = rdn.getValue() + ""; - break; - } - } - if (commonName == null) { - LOG.error("Unauthorized access. CName is null. serviceName=" + serviceName); - throw restErrorUtil.createRESTException( - "Unauthorized access - Unable to find Common Name from [" - + dn + "]", - MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY); - } - } catch (InvalidNameException e) { - LOG.error("Invalid Common Name. CName=" + commonName + ", serviceName=" + serviceName, e); - throw restErrorUtil.createRESTException( - "Unauthorized access - Invalid Common Name", - MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY); - } - } - if (commonName != null) { - if (matchNames(commonName, cnFromConfigForTest,isRegEx)) { - if (LOG.isDebugEnabled()) LOG.debug("Client Cert verification successful, matched CN " + commonName + " with " + cnFromConfigForTest + ", wildcard match = " + isRegEx); - isValidAuthentication=true; - } - - if (!isValidAuthentication) { - LOG.error("Unauthorized access. expected [" + cnFromConfigForTest + "], found [" - + commonName + "], serviceName=" + serviceName); - throw restErrorUtil.createRESTException( - "Unauthorized access. expected [" + cnFromConfigForTest - + "], found [" + commonName + "]", - MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY); - } - } - } - } else { - isValidAuthentication = true; - } - return isValidAuthentication; - } - - public boolean isValidService(String serviceName, HttpServletRequest request){ - boolean isValid = true; - if (serviceName == null || serviceName.isEmpty()) { - LOG.error("ServiceName not provided"); - isValid = false; - throw restErrorUtil.createRESTException("Unauthorized access.", - MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY); - } - - RangerService service = null; - try { - if(null != request.getAttribute("downloadPolicy") && StringUtils.equalsIgnoreCase(request.getAttribute("downloadPolicy").toString(), "secure")){ - service = svcStore.getServiceByNameForDP(serviceName); - }else{ - service = svcStore.getServiceByName(serviceName); - } - } catch (Exception e) { - isValid = false; - LOG.error("Requested Service not found. serviceName=" + serviceName); - throw restErrorUtil.createRESTException("Service:" + serviceName + " not found", - MessageEnums.DATA_NOT_FOUND); - } - if(service==null){ - isValid = false; - LOG.error("Requested Service not found. serviceName=" + serviceName); - throw restErrorUtil.createRESTException(HttpServletResponse.SC_NOT_FOUND, RangerServiceNotFoundException.buildExceptionMsg(serviceName), - false); - } - if(!service.getIsEnabled()){ - isValid = false; - LOG.error("Requested Service is disabled. serviceName=" + serviceName); - throw restErrorUtil.createRESTException("Unauthorized access.", - MessageEnums.OPER_NOT_ALLOWED_FOR_STATE); - } - return isValid; - } - - private boolean matchNames(String target, String source, boolean wildcardMatch) { - boolean matched = false; - if(target != null && source != null) { - String names[] = (wildcardMatch ? new String[] { source } : source.split(",")); - for (String n:names) { - - if (wildcardMatch) { - if(LOG.isDebugEnabled()) LOG.debug("Wildcard Matching [" + target + "] with [" + n + "]"); - if (wildcardMatch(target,n)) { - if(LOG.isDebugEnabled()) LOG.debug("Matched target:" + target + " with " + n); - matched = true; - break; - } - } else { - if(LOG.isDebugEnabled()) LOG.debug("Matching [" + target + "] with [" + n + "]"); - if (target.equalsIgnoreCase(n)) { - if(LOG.isDebugEnabled()) LOG.debug("Matched target:" + target + " with " + n); - matched = true; - break; - } - } - } - } else { - if(LOG.isDebugEnabled()) LOG.debug("source=[" + source + "],target=[" + target +"], returning false."); - } - return matched; - } - - private boolean wildcardMatch(String target, String source) { - boolean matched = false; - if(target != null && source != null) { - try { - matched = target.matches(source); - } catch (Throwable e) { - LOG.error("Error doing wildcard match..", e); - } - } else { - if(LOG.isDebugEnabled()) LOG.debug("source=[" + source + "],target=[" + target +"], returning false."); - } - return matched; - } - - - private Boolean toBooleanReplacePerm(boolean isReplacePermission) { - - Boolean ret; - - if (isReplacePermission) { - ret = Boolean.TRUE; - } else { - ret = Boolean.FALSE; - } - return ret; - } - - private Integer getAssetType(RangerService service, String serviceName) { - if(service == null || StringUtils.isEmpty(service.getType())) { - try { - service = svcStore.getServiceByName(serviceName); - } catch (Exception e) { - LOG.info( HttpServletResponse.SC_BAD_REQUEST + "No Service Found for ServiceName:" + serviceName ); - throw restErrorUtil.createRESTException(HttpServletResponse.SC_BAD_REQUEST, e.getMessage() + serviceName, true); - } - } - - String serviceType = service != null ? service.getType() : null; - - Integer assetType = toAssetType(serviceType); - - return assetType; - } - - public List getMatchingPoliciesForResource(HttpServletRequest request, - List policyLists) { - List policies = new ArrayList(); - final String serviceTypeForTag = EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_TAG_NAME; - if (request != null) { - String resource = request.getParameter(SearchFilter.POL_RESOURCE); - String serviceType = request.getParameter(SearchFilter.SERVICE_TYPE); - if (!StringUtil.isEmpty(resource) && !StringUtil.isEmpty(serviceType)) { - List resourceList = null; - Map rangerPolicyResourceMap = null; - RangerPolicy.RangerPolicyResource rangerPolicyResource = null; - for (RangerPolicy rangerPolicy : policyLists) { - if (rangerPolicy != null) { - if(serviceTypeForTag.equals(rangerPolicy.getServiceType())) { - policies.add(rangerPolicy); - }else { - rangerPolicyResourceMap = rangerPolicy.getResources(); - if (rangerPolicyResourceMap != null) { - if (rangerPolicyResourceMap.containsKey("path")) { - rangerPolicyResource = rangerPolicyResourceMap.get("path"); - if (rangerPolicyResource != null) { - resourceList = rangerPolicyResource.getValues(); - if (CollectionUtils.isNotEmpty(resourceList) && resourceList.contains(resource)) { - policies.add(rangerPolicy); - } - } - } else if (rangerPolicyResourceMap.containsKey("database")) { - rangerPolicyResource = rangerPolicyResourceMap.get("database"); - if (rangerPolicyResource != null) { - resourceList = rangerPolicyResource.getValues(); - if (CollectionUtils.isNotEmpty(resourceList) && resourceList.contains(resource)) { - policies.add(rangerPolicy); - } - } - } - } - } - } - } - policyLists.clear(); - if (CollectionUtils.isNotEmpty(policies)) { - policyLists.addAll(policies); - } - } - } - return policyLists; - } } - 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 index abdfc16ab4..8b2640e6f7 100644 --- a/security-admin/src/main/java/org/apache/ranger/common/SortField.java +++ b/security-admin/src/main/java/org/apache/ranger/common/SortField.java @@ -17,33 +17,28 @@ * under the License. */ - /** +/** * */ package org.apache.ranger.common; /** - * * */ public class SortField { - public enum SORT_ORDER { - ASC, DESC - }; - - String paramName; - String fieldName; - boolean isDefault = false; + String paramName; + String fieldName; + boolean isDefault; SORT_ORDER defaultOrder = SORT_ORDER.ASC; /** - * @param string - * @param string2 + * @param paramName + * @param fieldName */ public SortField(String paramName, String fieldName) { - this.paramName = paramName; - this.fieldName = fieldName; - isDefault = false; + this.paramName = paramName; + this.fieldName = fieldName; + isDefault = false; } /** @@ -51,41 +46,34 @@ public SortField(String paramName, String fieldName) { * @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; + 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 paramName; } - - /** * @return the fieldName */ public String getFieldName() { - return fieldName; + return fieldName; } - - /** * @return the isDefault */ public boolean isDefault() { - return isDefault; + return isDefault; } - - /** * @return the defaultOrder */ @@ -93,7 +81,7 @@ public SORT_ORDER getDefaultOrder() { return defaultOrder; } - - - + public enum SORT_ORDER { + ASC, DESC + } } 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 index 275c883c54..b86c6ce8da 100644 --- a/security-admin/src/main/java/org/apache/ranger/common/StringUtil.java +++ b/security-admin/src/main/java/org/apache/ranger/common/StringUtil.java @@ -17,7 +17,11 @@ * under the License. */ - package org.apache.ranger.common; +package org.apache.ranger.common; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; import java.io.Serializable; import java.io.UnsupportedEncodingException; @@ -28,234 +32,242 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.stereotype.Component; - @Component public class StringUtil implements Serializable { - private static final Logger logger = LoggerFactory.getLogger(StringUtil.class); + private static final Logger logger = LoggerFactory.getLogger(StringUtil.class); - static final public String VALIDATION_CRED = "(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z]).{8,}"; + private static final long serialVersionUID = -2102399594424760213L; - static final public String VALIDATION_NAME = "^([A-Za-z0-9_]|[\u00C0-\u017F])([a-zA-Z0-9\\s_. -@]|[\u00C0-\u017F])+$"; - static final public String VALIDATION_TEXT = "[a-zA-Z0-9\\ \"!@#$%^&*()-_=+;:'"|~`<>?/{}\\.\\,\\-\\?<>\\x00-\\x7F\\p{L}-]*"; - static final public String VALIDATION_LOGINID = "^([A-Za-z0-9_]|[\u00C0-\u017F])([a-z0-9,._\\-+/@= ]|[\u00C0-\u017F])+$"; + public static final String VALIDATION_CRED = "(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z]).{8,}"; + public static final String VALIDATION_NAME = "^([A-Za-z0-9_]|[\u00C0-\u017F])([a-zA-Z0-9\\s_. -@]|[\u00C0-\u017F])+$"; + public static final String VALIDATION_TEXT = "[a-zA-Z0-9\\ \"!@#$%^&*()-_=+;:'"|~`<>?/{}\\.\\,\\-\\?<>\\x00-\\x7F\\p{L}-]*"; + public static final String VALIDATION_LOGINID = "^([A-Za-z0-9_]|[\u00C0-\u017F])([a-z0-9,._\\-+/@= ]|[\u00C0-\u017F])+$"; + public static final String VALIDATION_ALPHA = "[a-z,A-Z]*"; + public static final String VALIDATION_IP_ADDRESS = "[\\d\\.\\%\\:]*"; + public static final String WILDCARD_ASTERISK = "*"; - 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 compiledRegEx = new HashMap<>(); + + String[] invalidNames; + + public StringUtil() { + // Default constructor + invalidNames = PropertiesUtil.getPropertyStringList("xa.names.invalid"); + } - static HashMap compiledRegEx = new HashMap(); + public static String trim(String str) { + return str != null ? str.trim() : null; + } - String[] invalidNames = null; + public static String getUTFEncodedString(String username) throws UnsupportedEncodingException { + return URLEncoder.encode(username, StandardCharsets.UTF_8.toString()); + } - /** + /** + * Checks if the string is null or empty string. * + * @param str + * @return true if it is empty string or 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) || WILDCARD_ASTERISK.equals(str); - } - - 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(); - StringBuilder result = new StringBuilder(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(); - boolean checkPassword = password.matches(VALIDATION_CRED); - if (!checkPassword) { - 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) { - boolean ret = false; - - if (expression != null && inputStr != null) { - Pattern pattern = compiledRegEx.get(expression); - - if (pattern == null) { - pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE); - compiledRegEx.put(expression, pattern); - } - - Matcher matcher = pattern.matcher(inputStr); - ret = matcher.matches(); - } - - return ret; - } - - 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 (String splitValue : splitValues) { - String str = splitValue.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 name - * @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.isEmpty()) { - 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; - } - - public static String getUTFEncodedString(String username) throws UnsupportedEncodingException { - return URLEncoder.encode(username, StandardCharsets.UTF_8.toString()); - } + public boolean isEmpty(String str) { + return str == null || str.trim().isEmpty(); + } + + public boolean isEmptyOrWildcardAsterisk(String str) { + return isEmpty(str) || WILDCARD_ASTERISK.equals(str); + } + + 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(); + + StringBuilder result = new StringBuilder(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(); + + boolean checkPassword = password.matches(VALIDATION_CRED); + + if (!checkPassword) { + 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) { + boolean ret = false; + + if (expression != null && inputStr != null) { + Pattern pattern = compiledRegEx.get(expression); + + if (pattern == null) { + pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE); + compiledRegEx.put(expression, pattern); + } + + Matcher matcher = pattern.matcher(inputStr); + ret = matcher.matches(); + } + + return ret; + } + + 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 (String splitValue : splitValues) { + String str = splitValue.trim(); + + if (!str.isEmpty()) { + c++; + + returnValues[c] = str; + } + } + + return returnValues; + } else { + return new String[0]; + } + } + + /** + * @param name + * @return + */ + public boolean isValidName(String name) { + if (name == null || name.trim().isEmpty()) { + 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) { + return list == null || list.isEmpty(); + } + + /** + * Returns a valid user name from the passed string + * + * @param str + * @return + */ + public String getValidUserName(String str) { + return str.contains("/") ? + str.substring(0, str.indexOf("/")) + : str.contains("@") ? + str.substring(0, str.indexOf("@")) + : str; + } } 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 index bc1aea3094..0e39bec5b4 100644 --- a/security-admin/src/main/java/org/apache/ranger/common/TimedEventUtil.java +++ b/security-admin/src/main/java/org/apache/ranger/common/TimedEventUtil.java @@ -17,54 +17,45 @@ * under the License. */ - package org.apache.ranger.common; +package org.apache.ranger.common; + +import org.springframework.stereotype.Component; import java.util.concurrent.Callable; import java.util.concurrent.TimeUnit; -import org.springframework.stereotype.Component; - @Component -public class TimedEventUtil{ - - public static void runWithTimeout(final Runnable runnable, long timeout, TimeUnit timeUnit) throws Exception { - timedTask(new Callable() { - @Override - public Object call() throws Exception { - runnable.run(); - return null; - } - }, timeout, timeUnit); - } - - public static T timedTask(Callable callableObj, long timeout, - TimeUnit timeUnit) throws Exception{ - - return callableObj.call(); - - /* - final ExecutorService executor = Executors.newSingleThreadExecutor(); - final Future 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 +public class TimedEventUtil { + public static void runWithTimeout(final Runnable runnable, long timeout, TimeUnit timeUnit) throws Exception { + timedTask(() -> { + runnable.run(); + + return null; + }, timeout, timeUnit); + } + + public static T timedTask(Callable callableObj, long timeout, TimeUnit timeUnit) throws Exception { + return callableObj.call(); + /* + final ExecutorService executor = Executors.newSingleThreadExecutor(); + final Future 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); + } + } + */ + } +} diff --git a/security-admin/src/main/java/org/apache/ranger/common/TimedExecutor.java b/security-admin/src/main/java/org/apache/ranger/common/TimedExecutor.java index 6ff9f0deb2..86e9206a62 100755 --- a/security-admin/src/main/java/org/apache/ranger/common/TimedExecutor.java +++ b/security-admin/src/main/java/org/apache/ranger/common/TimedExecutor.java @@ -19,6 +19,18 @@ package org.apache.ranger.common; +import org.apache.commons.lang3.StringUtils; +import org.apache.hadoop.thirdparty.com.google.common.util.concurrent.ThreadFactoryBuilder; +import org.apache.ranger.plugin.client.HadoopException; +import org.apache.ranger.plugin.service.RangerDefaultService; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Service; + +import javax.annotation.PostConstruct; + import java.lang.Thread.UncaughtExceptionHandler; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; @@ -33,146 +45,132 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; -import javax.annotation.PostConstruct; - -import org.apache.commons.lang3.StringUtils; -import org.apache.hadoop.thirdparty.com.google.common.util.concurrent.ThreadFactoryBuilder; -import org.apache.ranger.plugin.client.HadoopException; -import org.apache.ranger.plugin.service.RangerDefaultService; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Scope; -import org.springframework.stereotype.Service; - - @Service @Scope("singleton") public class TimedExecutor { + private static final Logger LOG = LoggerFactory.getLogger(TimedExecutor.class); + + @Autowired + TimedExecutorConfigurator configurator; + + ExecutorService executorService; + + public TimedExecutor() { + } + + public T timedTask(Callable callable, long time, TimeUnit unit) throws Exception { + try { + Future future = executorService.submit(callable); + + if (LOG.isDebugEnabled()) { + if (future.isCancelled()) { + LOG.debug("Got back a future that was cancelled already for callable[{}]!", callable); + } + } + + try { + return future.get(time, unit); + } catch (CancellationException | ExecutionException | InterruptedException e) { + LOG.debug("TimedExecutor: Caught exception[{}] for callable[{}]: detail[{}]. Re-throwing...", e.getClass().getName(), callable, e.getMessage()); + + if (StringUtils.contains(e.getMessage(), RangerDefaultService.ERROR_MSG_VALIDATE_CONFIG_NOT_IMPLEMENTED)) { + throw e; + } else { + throw generateHadoopException(e); + } + } catch (TimeoutException e) { + LOG.debug("TimedExecutor: Timed out waiting for callable[{}] to finish. Cancelling the task.", callable); + + boolean interruptRunningTask = true; + + future.cancel(interruptRunningTask); + + throw e; + } + } catch (RejectedExecutionException e) { + LOG.debug("Executor rejected callable[{}], due to resource exhaustion. Rethrowing exception...", callable); + + throw e; + } + } + + @PostConstruct + void initialize() { + initialize(configurator); + } + + // Not designed for public access - only for testability + void initialize(TimedExecutorConfigurator configurator) { + final ThreadFactory threadFactory = new ThreadFactoryBuilder() + .setDaemon(true) + .setNameFormat("timed-executor-pool-%d") + .setUncaughtExceptionHandler(new LocalUncaughtExceptionHandler()) + .build(); + + final BlockingQueue blockingQueue = new ArrayBlockingQueue<>(configurator.getBlockingQueueSize()); + + executorService = new LocalThreadPoolExecutor(configurator.getCoreThreadPoolSize(), configurator.getMaxThreadPoolSize(), + configurator.getKeepAliveTime(), configurator.getKeepAliveTimeUnit(), + blockingQueue, threadFactory); + } + + /** + * Not designed for public access. Non-private only for testability. Expected to be called by tests to do proper cleanup. + */ + void shutdown() { + executorService.shutdownNow(); + } + + private HadoopException generateHadoopException(Exception e) { + String msgDesc = "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 ranger_admin.log for more info. "; + HadoopException hpe = new HadoopException(e.getMessage(), e); + hpe.generateResponseDataMap(false, hpe.getMessage(e), msgDesc, null, null); + return hpe; + } + + static class LocalUncaughtExceptionHandler implements UncaughtExceptionHandler { + @Override + public void uncaughtException(Thread t, Throwable e) { + LOG.warn("TimedExecutor: Uncaught exception hanlder received exception[{}] in thread[{}]", t.getClass().getName(), t.getName(), e); + } + } + + static class LocalThreadPoolExecutor extends ThreadPoolExecutor { + private final ThreadLocal startNanoTime = new ThreadLocal<>(); + + public LocalThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue workQueue, ThreadFactory threadFactory) { + super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory); + } + + @Override + protected void beforeExecute(Thread t, Runnable r) { + if (LOG.isDebugEnabled()) { + LOG.debug("TimedExecutor: Starting execution of a task."); + startNanoTime.set(System.nanoTime()); + } + + super.beforeExecute(t, r); + } + + @Override + protected void afterExecute(Runnable r, Throwable t) { + super.afterExecute(r, t); + + if (LOG.isDebugEnabled()) { + long duration = System.nanoTime() - startNanoTime.get(); + + LOG.debug("TimedExecutor: Done execution of task. Duration[{} ms].", duration / 1000000); + } + } + + @Override + protected void terminated() { + super.terminated(); - private static final Logger LOG = LoggerFactory.getLogger(TimedExecutor.class); - - @Autowired - TimedExecutorConfigurator _configurator; - - ExecutorService _executorService; - - public TimedExecutor() { - } - - @PostConstruct - void initialize() { - initialize(_configurator); - } - - // Not designed for public access - only for testability - void initialize(TimedExecutorConfigurator configurator) { - final ThreadFactory _ThreadFactory = new ThreadFactoryBuilder() - .setDaemon(true) - .setNameFormat("timed-executor-pool-%d") - .setUncaughtExceptionHandler(new LocalUncaughtExceptionHandler()) - .build(); - - final BlockingQueue blockingQueue = new ArrayBlockingQueue<>(configurator.getBlockingQueueSize()); - - _executorService = new LocalThreadPoolExecutor(configurator.getCoreThreadPoolSize(), configurator.getMaxThreadPoolSize(), - configurator.getKeepAliveTime(), configurator.getKeepAliveTimeUnit(), - blockingQueue, _ThreadFactory); - } - - public T timedTask(Callable callable, long time, TimeUnit unit) throws Exception{ - try { - Future future = _executorService.submit(callable); - if (LOG.isDebugEnabled()) { - if (future.isCancelled()) { - LOG.debug("Got back a future that was cancelled already for callable[" + callable + "]!"); - } - } - try { - T result = future.get(time, unit); - return result; - } catch (CancellationException | ExecutionException | InterruptedException e) { - if (LOG.isDebugEnabled()) { - LOG.debug(String.format("TimedExecutor: Caught exception[%s] for callable[%s]: detail[%s]. Re-throwing...", e.getClass().getName(), callable, e.getMessage())); - } - - if (StringUtils.contains(e.getMessage(), RangerDefaultService.ERROR_MSG_VALIDATE_CONFIG_NOT_IMPLEMENTED)) { - throw e; - } else { - throw generateHadoopException(e); - } - } catch (TimeoutException e) { - if (LOG.isDebugEnabled()) { - LOG.debug(String.format("TimedExecutor: Timed out waiting for callable[%s] to finish. Cancelling the task.", callable)); - } - boolean interruptRunningTask = true; - future.cancel(interruptRunningTask); - throw e; - } - } catch (RejectedExecutionException e) { - if (LOG.isDebugEnabled()) { - LOG.debug("Executor rejected callable[" + callable + "], due to resource exhaustion. Rethrowing exception..."); - } - throw e; - } - } - - /** - * Not designed for public access. Non-private only for testability. Expected to be called by tests to do proper cleanup. - */ - void shutdown() { - _executorService.shutdownNow(); - } - - private HadoopException generateHadoopException( Exception e) { - String msgDesc = "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 ranger_admin.log for more info. "; - HadoopException hpe = new HadoopException(e.getMessage(), e); - hpe.generateResponseDataMap(false, hpe.getMessage(e), msgDesc, null, null); - return hpe; - } - - static class LocalUncaughtExceptionHandler implements UncaughtExceptionHandler { - - @Override - public void uncaughtException(Thread t, Throwable e) { - String message = String.format("TimedExecutor: Uncaught exception hanlder received exception[%s] in thread[%s]", t.getClass().getName(), t.getName()); - LOG.warn(message, e); - } - } - - static class LocalThreadPoolExecutor extends ThreadPoolExecutor { - - private ThreadLocal startNanoTime = new ThreadLocal(); - - public LocalThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue workQueue, ThreadFactory threadFactory) { - super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory); - } - - @Override - protected void beforeExecute(Thread t, Runnable r) { - if (LOG.isDebugEnabled()) { - LOG.debug("TimedExecutor: Starting execution of a task."); - startNanoTime.set(System.nanoTime()); - } - super.beforeExecute(t, r); - } - - @Override - protected void afterExecute(Runnable r, Throwable t) { - super.afterExecute(r, t); - if (LOG.isDebugEnabled()) { - long duration = System.nanoTime() - startNanoTime.get(); - LOG.debug("TimedExecutor: Done execution of task. Duration[" + duration/1000000 + " ms]."); - } - } - - @Override - protected void terminated() { - super.terminated(); - LOG.info("TimedExecutor: thread pool has terminated"); - } - } -} \ No newline at end of file + LOG.info("TimedExecutor: thread pool has terminated"); + } + } +} diff --git a/security-admin/src/main/java/org/apache/ranger/common/TimedExecutorConfigurator.java b/security-admin/src/main/java/org/apache/ranger/common/TimedExecutorConfigurator.java index 66602973bf..547af3b770 100644 --- a/security-admin/src/main/java/org/apache/ranger/common/TimedExecutorConfigurator.java +++ b/security-admin/src/main/java/org/apache/ranger/common/TimedExecutorConfigurator.java @@ -19,75 +19,80 @@ package org.apache.ranger.common; -import java.util.concurrent.TimeUnit; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Service; import javax.annotation.PostConstruct; -import org.springframework.context.annotation.Scope; -import org.springframework.stereotype.Service; +import java.util.concurrent.TimeUnit; @Service @Scope("singleton") public class TimedExecutorConfigurator { + // these two are important and hence are user configurable. + static final String PROPERTY_MAX_THREAD_POOL_SIZE = "ranger.timed.executor.max.threadpool.size"; + static final String PROPERTY_QUEUE_SIZE = "ranger.timed.executor.queue.size"; + // We need these default-defaults since default-site.xml file isn't inside the jar, i.e. file itself may be missing or values in it might be messed up! :( + static final int DEFAULT_MAX_THREAD_POOL_SIZE = 10; + private static final int DEFAULT_BLOCKING_QUEUE_SIZE = 100; + + private int maxThreadPoolSize; + private int blockingQueueSize; + private final TimeUnit keepAliveTimeUnit = TimeUnit.SECONDS; + + public TimedExecutorConfigurator() { + } + + /** + * Provided mostly only testability. + * + * @param maxThreadPoolSize + * @param blockingQueueSize + */ + public TimedExecutorConfigurator(int maxThreadPoolSize, int blockingQueueSize) { + this.maxThreadPoolSize = maxThreadPoolSize; + this.blockingQueueSize = blockingQueueSize; + } + + public int getCoreThreadPoolSize() { + // The following is hard-coded for now and can be exposed if there is a pressing need. + return 1; + } + + public int getMaxThreadPoolSize() { + return maxThreadPoolSize; + } + + public long getKeepAliveTime() { + // The following is hard-coded for now and can be exposed if there is a pressing need. + return 10; + } + + public TimeUnit getKeepAliveTimeUnit() { + return keepAliveTimeUnit; + } + + public int getBlockingQueueSize() { + return blockingQueueSize; + } + + // Infrequently used class (once per lifetime of policy manager) hence, values read from property file aren't cached. + @PostConstruct + void initialize() { + Integer value = PropertiesUtil.getIntProperty(PROPERTY_MAX_THREAD_POOL_SIZE); + + if (value == null) { + maxThreadPoolSize = DEFAULT_MAX_THREAD_POOL_SIZE; + } else { + maxThreadPoolSize = value; + } + + value = PropertiesUtil.getIntProperty(PROPERTY_QUEUE_SIZE); - // these two are important and hence are user configurable. - static final String Property_MaxThreadPoolSize = "ranger.timed.executor.max.threadpool.size"; - static final String Property_QueueSize = "ranger.timed.executor.queue.size"; - // We need these default-defaults since default-site.xml file isn't inside the jar, i.e. file itself may be missing or values in it might be messed up! :( - static final int _DefaultMaxThreadPoolSize = 10; - static final private int _DefaultBlockingQueueSize = 100; - - - private int _maxThreadPoolSize; - private int _blockingQueueSize; - // The following are hard-coded for now and can be exposed if there is a pressing need. - private int _coreThreadPoolSize = 1; - private long _keepAliveTime = 10; - private TimeUnit _keepAliveTimeUnit = TimeUnit.SECONDS; - - public TimedExecutorConfigurator() { - } - - // Infrequently used class (once per lifetime of policy manager) hence, values read from property file aren't cached. - @PostConstruct - void initialize() { - Integer value = PropertiesUtil.getIntProperty(Property_MaxThreadPoolSize); - if (value == null) { - _maxThreadPoolSize = _DefaultMaxThreadPoolSize; - } else { - _maxThreadPoolSize = value; - } - - value = PropertiesUtil.getIntProperty(Property_QueueSize); - if (value == null) { - _blockingQueueSize = _DefaultBlockingQueueSize; - } else { - _blockingQueueSize = value; - } - } - /** - * Provided mostly only testability. - * @param maxThreadPoolSize - * @param blockingQueueSize - */ - public TimedExecutorConfigurator(int maxThreadPoolSize, int blockingQueueSize) { - _maxThreadPoolSize = maxThreadPoolSize; - _blockingQueueSize = blockingQueueSize; - } - - public int getCoreThreadPoolSize() { - return _coreThreadPoolSize; - } - public int getMaxThreadPoolSize() { - return _maxThreadPoolSize; - } - public long getKeepAliveTime() { - return _keepAliveTime; - } - public TimeUnit getKeepAliveTimeUnit() { - return _keepAliveTimeUnit; - } - public int getBlockingQueueSize() { - return _blockingQueueSize; - } + if (value == null) { + blockingQueueSize = DEFAULT_BLOCKING_QUEUE_SIZE; + } else { + blockingQueueSize = value; + } + } } 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 index 6decee33b8..6957595fc1 100644 --- a/security-admin/src/main/java/org/apache/ranger/common/UserSessionBase.java +++ b/security-admin/src/main/java/org/apache/ranger/common/UserSessionBase.java @@ -17,58 +17,64 @@ * under the License. */ - package org.apache.ranger.common; +package org.apache.ranger.common; + +import org.apache.ranger.entity.XXAuthSession; +import org.apache.ranger.entity.XXPortalUser; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CopyOnWriteArraySet; -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; + int clientTimeOffsetInMinute; + private boolean userAdmin; + private boolean userAuditAdmin; + private boolean auditKeyAdmin; + private boolean keyAdmin; + private int authProvider = RangerConstants.USER_APP; + private List userRoleList = new ArrayList<>(); + private RangerUserPermission rangerUserPermission; + private Boolean isSSOEnabled; + private Boolean isSpnegoEnabled; + + 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; + } - private static final long serialVersionUID = 1L; - - XXPortalUser xXPortalUser; - XXAuthSession xXAuthSession; - private boolean userAdmin; - private boolean userAuditAdmin = false; - private boolean auditKeyAdmin = false; - private boolean keyAdmin = false; - private int authProvider = RangerConstants.USER_APP; - private List userRoleList = new ArrayList(); - private RangerUserPermission rangerUserPermission; - int clientTimeOffsetInMinute = 0; - private Boolean isSSOEnabled; - private Boolean isSpnegoEnabled = false; - - 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 boolean isAuditUserAdmin() { return userAuditAdmin; } @@ -77,52 +83,49 @@ public void setAuditUserAdmin(boolean userAuditAdmin) { this.userAuditAdmin = userAuditAdmin; } - public void setUserAdmin(boolean userAdmin) { - this.userAdmin = userAdmin; - } + public XXPortalUser getXXPortalUser() { + return xXPortalUser; + } - public XXPortalUser getXXPortalUser() { - return xXPortalUser; - } + public void setXXPortalUser(XXPortalUser gjUser) { + this.xXPortalUser = gjUser; + } - public void setXXAuthSession(XXAuthSession gjAuthSession) { - this.xXAuthSession = gjAuthSession; - } + public void setXXAuthSession(XXAuthSession gjAuthSession) { + this.xXAuthSession = gjAuthSession; + } - public void setXXPortalUser(XXPortalUser gjUser) { - this.xXPortalUser = gjUser; - } + public List getUserRoleList() { + return this.userRoleList; + } - public void setAuthProvider(int userSource) { - this.authProvider = userSource; - } + public void setUserRoleList(List strRoleList) { + this.userRoleList = strRoleList; + } - public void setUserRoleList(List strRoleList) { - this.userRoleList = strRoleList; - } - public List getUserRoleList() { - return this.userRoleList; - } + public int getAuthProvider() { + return this.authProvider; + } - public int getAuthProvider() { - return this.authProvider; - } + public void setAuthProvider(int userSource) { + this.authProvider = userSource; + } - public int getClientTimeOffsetInMinute() { - return clientTimeOffsetInMinute; - } + public int getClientTimeOffsetInMinute() { + return clientTimeOffsetInMinute; + } - public void setClientTimeOffsetInMinute(int clientTimeOffsetInMinute) { - this.clientTimeOffsetInMinute = clientTimeOffsetInMinute; - } + public void setClientTimeOffsetInMinute(int clientTimeOffsetInMinute) { + this.clientTimeOffsetInMinute = clientTimeOffsetInMinute; + } - public boolean isKeyAdmin() { - return keyAdmin; - } + public boolean isKeyAdmin() { + return keyAdmin; + } - public void setKeyAdmin(boolean keyAdmin) { - this.keyAdmin = keyAdmin; - } + public void setKeyAdmin(boolean keyAdmin) { + this.keyAdmin = keyAdmin; + } public boolean isAuditKeyAdmin() { return auditKeyAdmin; @@ -131,69 +134,69 @@ public boolean isAuditKeyAdmin() { public void setAuditKeyAdmin(boolean auditKeyAdmin) { this.auditKeyAdmin = auditKeyAdmin; } - /** - * @return the rangerUserPermission - */ - public RangerUserPermission getRangerUserPermission() { - return rangerUserPermission; - } - - /** - * @param rangerUserPermission the rangerUserPermission to set - */ - public void setRangerUserPermission(RangerUserPermission rangerUserPermission) { - this.rangerUserPermission = rangerUserPermission; - } - - - - public Boolean isSSOEnabled() { - return isSSOEnabled; - } - - public void setSSOEnabled(Boolean isSSOEnabled) { - this.isSSOEnabled = isSSOEnabled; - } - - public Boolean isSpnegoEnabled() { - return isSpnegoEnabled; - } - - public void setSpnegoEnabled(Boolean isSpnegoEnabled) { - this.isSpnegoEnabled = isSpnegoEnabled; - } - - public static class RangerUserPermission implements Serializable { - private static final long serialVersionUID = 1L; - - protected CopyOnWriteArraySet userPermissions; - protected Long lastUpdatedTime; - - /** - * @return the userPermissions - */ - public CopyOnWriteArraySet getUserPermissions() { - return userPermissions; - } - /** - * @param userPermissions the userPermissions to set - */ - public void setUserPermissions(CopyOnWriteArraySet userPermissions) { - this.userPermissions = userPermissions; - } - /** - * @return the lastUpdatedTime - */ - public Long getLastUpdatedTime() { - return lastUpdatedTime; - } - /** - * @param lastUpdatedTime the lastUpdatedTime to set - */ - public void setLastUpdatedTime(Long lastUpdatedTime) { - this.lastUpdatedTime = lastUpdatedTime; - } - - } + /** + * @return the rangerUserPermission + */ + public RangerUserPermission getRangerUserPermission() { + return rangerUserPermission; + } + + /** + * @param rangerUserPermission the rangerUserPermission to set + */ + public void setRangerUserPermission(RangerUserPermission rangerUserPermission) { + this.rangerUserPermission = rangerUserPermission; + } + + public Boolean isSSOEnabled() { + return isSSOEnabled; + } + + public void setSSOEnabled(Boolean isSSOEnabled) { + this.isSSOEnabled = isSSOEnabled; + } + + public Boolean isSpnegoEnabled() { + return isSpnegoEnabled; + } + + public void setSpnegoEnabled(Boolean isSpnegoEnabled) { + this.isSpnegoEnabled = isSpnegoEnabled; + } + + public static class RangerUserPermission implements Serializable { + private static final long serialVersionUID = 1L; + + protected CopyOnWriteArraySet userPermissions; + protected Long lastUpdatedTime; + + /** + * @return the userPermissions + */ + public CopyOnWriteArraySet getUserPermissions() { + return userPermissions; + } + + /** + * @param userPermissions the userPermissions to set + */ + public void setUserPermissions(CopyOnWriteArraySet userPermissions) { + this.userPermissions = userPermissions; + } + + /** + * @return the lastUpdatedTime + */ + public Long getLastUpdatedTime() { + return lastUpdatedTime; + } + + /** + * @param lastUpdatedTime the lastUpdatedTime to set + */ + public void setLastUpdatedTime(Long lastUpdatedTime) { + this.lastUpdatedTime = lastUpdatedTime; + } + } } diff --git a/security-admin/src/main/java/org/apache/ranger/common/XMLPropertiesUtil.java b/security-admin/src/main/java/org/apache/ranger/common/XMLPropertiesUtil.java index 9c609dbd12..1671ecedaf 100644 --- a/security-admin/src/main/java/org/apache/ranger/common/XMLPropertiesUtil.java +++ b/security-admin/src/main/java/org/apache/ranger/common/XMLPropertiesUtil.java @@ -19,22 +19,18 @@ package org.apache.ranger.common; -import java.io.IOException; -import java.io.InputStream; -import java.util.Properties; - import org.apache.ranger.plugin.util.XMLUtils; import org.springframework.util.DefaultPropertiesPersister; -public class XMLPropertiesUtil extends DefaultPropertiesPersister { +import java.io.InputStream; +import java.util.Properties; - public XMLPropertiesUtil() { - } +public class XMLPropertiesUtil extends DefaultPropertiesPersister { + public XMLPropertiesUtil() { + } - @Override - public void loadFromXml(Properties properties, InputStream inputStream) - throws IOException { + @Override + public void loadFromXml(Properties properties, InputStream inputStream) { XMLUtils.loadConfig(inputStream, properties); - } - + } } diff --git a/security-admin/src/main/java/org/apache/ranger/common/annotation/RangerAnnotationClassName.java b/security-admin/src/main/java/org/apache/ranger/common/annotation/RangerAnnotationClassName.java index eead684f8f..0c18e73d82 100644 --- a/security-admin/src/main/java/org/apache/ranger/common/annotation/RangerAnnotationClassName.java +++ b/security-admin/src/main/java/org/apache/ranger/common/annotation/RangerAnnotationClassName.java @@ -17,7 +17,7 @@ * under the License. */ - /** +/** * */ package org.apache.ranger.common.annotation; @@ -25,8 +25,7 @@ import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; - @Retention(RetentionPolicy.RUNTIME) public @interface RangerAnnotationClassName { - public Class class_name(); + Class class_name(); } diff --git a/security-admin/src/main/java/org/apache/ranger/common/annotation/RangerAnnotationJSMgrName.java b/security-admin/src/main/java/org/apache/ranger/common/annotation/RangerAnnotationJSMgrName.java index 7354a7754c..a2017d4851 100644 --- a/security-admin/src/main/java/org/apache/ranger/common/annotation/RangerAnnotationJSMgrName.java +++ b/security-admin/src/main/java/org/apache/ranger/common/annotation/RangerAnnotationJSMgrName.java @@ -17,7 +17,7 @@ * under the License. */ - /** +/** * */ package org.apache.ranger.common.annotation; @@ -26,10 +26,9 @@ import java.lang.annotation.RetentionPolicy; /** - * * */ @Retention(RetentionPolicy.RUNTIME) public @interface RangerAnnotationJSMgrName { - public String value(); + String value(); } diff --git a/security-admin/src/main/java/org/apache/ranger/common/annotation/RangerAnnotationRestAPI.java b/security-admin/src/main/java/org/apache/ranger/common/annotation/RangerAnnotationRestAPI.java index 25eccfe78b..0d6f53d343 100644 --- a/security-admin/src/main/java/org/apache/ranger/common/annotation/RangerAnnotationRestAPI.java +++ b/security-admin/src/main/java/org/apache/ranger/common/annotation/RangerAnnotationRestAPI.java @@ -17,7 +17,7 @@ * under the License. */ - /** +/** * */ package org.apache.ranger.common.annotation; @@ -27,11 +27,12 @@ /** * Annotating the REST APIs - * */ @Retention(RetentionPolicy.RUNTIME) public @interface RangerAnnotationRestAPI { - public String api_name() default ""; - public boolean updates_generic_objects() default false; - public String updates_classes() default ""; + String api_name() default ""; + + boolean updates_generic_objects() default false; + + String updates_classes() default ""; } 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 index 7f9e36f19f..2204fe455f 100644 --- 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 @@ -17,9 +17,22 @@ * under the License. */ - package org.apache.ranger.common.db; +package org.apache.ranger.common.db; +import org.apache.commons.lang3.StringUtils; +import org.apache.ranger.authorization.hadoop.config.RangerAdminConfig; +import org.apache.ranger.biz.RangerBizUtil; +import org.apache.ranger.common.AppConstants; +import org.apache.ranger.db.RangerDaoManager; +import org.apache.ranger.db.RangerDaoManagerBase; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import javax.persistence.EntityManager; +import javax.persistence.NoResultException; +import javax.persistence.Query; +import javax.persistence.Table; +import javax.persistence.TypedQuery; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; @@ -29,356 +42,352 @@ import java.util.ArrayList; import java.util.List; -import javax.persistence.EntityManager; -import javax.persistence.NoResultException; -import javax.persistence.Query; -import javax.persistence.Table; -import javax.persistence.TypedQuery; +public abstract class BaseDao { + private static final Logger logger = LoggerFactory.getLogger(BaseDao.class); -import org.apache.commons.lang3.StringUtils; -import org.apache.ranger.authorization.hadoop.config.RangerAdminConfig; -import org.apache.ranger.biz.RangerBizUtil; -import org.apache.ranger.common.AppConstants; -import org.apache.ranger.db.RangerDaoManager; -import org.apache.ranger.db.RangerDaoManagerBase; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; + private static final String PROP_BATCH_DELETE_BATCH_SIZE = "ranger.admin.dao.batch.delete.batch.size"; + private static final int DEFAULT_BATCH_DELETE_BATCH_SIZE = 1000; + private static final String NOT_AVAILABLE = "Not Available"; + private static final String GDS_TABLES = "x_gds_"; + private static int BATCH_DELETE_BATCH_SIZE; -public abstract class BaseDao { - private static final Logger logger = LoggerFactory.getLogger(BaseDao.class); - private static final String PROP_BATCH_DELETE_BATCH_SIZE = "ranger.admin.dao.batch.delete.batch.size"; - private static final int DEFAULT_BATCH_DELETE_BATCH_SIZE = 1000; - private static int BATCH_DELETE_BATCH_SIZE; - private static final String NOT_AVAILABLE = "Not Available"; - private static final String GDS_TABLES = "x_gds_"; - - static { - try { - BATCH_DELETE_BATCH_SIZE = RangerAdminConfig.getInstance().getInt(PROP_BATCH_DELETE_BATCH_SIZE, DEFAULT_BATCH_DELETE_BATCH_SIZE); - - if (BATCH_DELETE_BATCH_SIZE > DEFAULT_BATCH_DELETE_BATCH_SIZE) { - logger.warn("Configuration {}={}, which is larger than default value {}", PROP_BATCH_DELETE_BATCH_SIZE, BATCH_DELETE_BATCH_SIZE, DEFAULT_BATCH_DELETE_BATCH_SIZE); - } - } catch(Exception e) { - // When we get the Number format exception due to the invalid value entered into the config file. - BATCH_DELETE_BATCH_SIZE = DEFAULT_BATCH_DELETE_BATCH_SIZE; - } - - logger.info(PROP_BATCH_DELETE_BATCH_SIZE + "=" + BATCH_DELETE_BATCH_SIZE); - } - - protected RangerDaoManager daoManager; - - EntityManager em; - - protected Class tClass; - - public BaseDao(RangerDaoManagerBase daoManager) { - this.daoManager = (RangerDaoManager) daoManager; - this.init(daoManager.getEntityManager()); - } - - public BaseDao(RangerDaoManagerBase daoManager, String persistenceContextUnit) { - this.daoManager = (RangerDaoManager) 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) ((ParameterizedType) type).getRawType(); - } else { - this.tClass = (Class) type; - } - } - - public EntityManager getEntityManager() { - return this.em; - } - - public T create(T obj) { - T ret = null; - - em.persist(obj); - if (!RangerBizUtil.isBulkMode()) { - em.flush(); - } - ret = obj; - return ret; - } - - public List batchCreate(List obj) { - List ret = null; - - for (int n = 0; n < obj.size(); ++n) { - em.persist(obj.get(n)); - if (!RangerBizUtil.isBulkMode() && (n % RangerBizUtil.BATCH_PERSIST_SIZE == 0)) { - em.flush(); - } - } - if (!RangerBizUtil.isBulkMode()) { - em.flush(); - } - - ret = obj; - return ret; - } - - public void batchDeleteByIds(String namedQuery, List ids, String paramName) { - if (BATCH_DELETE_BATCH_SIZE <= 0) { - getEntityManager() - .createNamedQuery(namedQuery, tClass) - .setParameter(paramName, ids).executeUpdate(); - } else { - for (int fromIndex = 0; fromIndex < ids.size(); fromIndex += BATCH_DELETE_BATCH_SIZE) { - int toIndex = fromIndex + BATCH_DELETE_BATCH_SIZE; - - if (toIndex > ids.size()) { - toIndex = ids.size(); - } - - if (logger.isDebugEnabled()) { - logger.debug("batchDeleteByIds({}, idCount={}): deleting fromIndex={}, toIndex={}", namedQuery, ids.size(), fromIndex, toIndex); - } - - List subList = ids.subList(fromIndex, toIndex); - - getEntityManager() - .createNamedQuery(namedQuery, tClass) - .setParameter(paramName, subList).executeUpdate(); - } - } - } - - public T update(T obj) { - em.merge(obj); - if (!RangerBizUtil.isBulkMode()) { - em.flush(); - } - return obj; - } - - public boolean remove(Long id) { - return remove(getById(id)); - } - - public boolean remove(T obj) { - if (obj == null) { - return true; - } - if (!em.contains(obj)) { - obj = em.merge(obj); - } - em.remove(obj); - if (!RangerBizUtil.isBulkMode()) { - em.flush(); - } - return true; - } - - public void flush() { - em.flush(); - } - - public void clear() { - em.clear(); - } - public T create(T obj, boolean flush) { - T ret = null; - em.persist(obj); - if(flush) { - em.flush(); - } - ret = obj; - return ret; - } - - public T update(T obj, boolean flush) { - em.merge(obj); - if(flush) { - em.flush(); - } - return obj; - } - - public boolean remove(T obj, boolean flush) { - if (obj == null) { - return true; - } - em.remove(obj); - if(flush) { - 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 findByNamedQuery(String namedQuery, String paramName, - Object refId) { - List ret = new ArrayList(); - - if (namedQuery == null) { - return ret; - } - try { - TypedQuery qry = em.createNamedQuery(namedQuery, tClass); - qry.setParameter(paramName, refId); - ret = qry.getResultList(); - } catch (NoResultException e) { - // ignore - } - return ret; - } - - public List findByParentId(Long parentId) { - String namedQuery = tClass.getSimpleName() + ".findByParentId"; - return findByNamedQuery(namedQuery, "parentId", parentId); - } - - - public List executeQueryInSecurityContext(Class clazz, Query query) { - return executeQueryInSecurityContext(clazz, query, true); - } - - @SuppressWarnings("unchecked") - public List executeQueryInSecurityContext(Class clazz, Query query, - boolean userPrefFilter) { - // boolean filterEnabled = false; - List rtrnList = null; - // filterEnabled = enableVisiblityFilters(clazz, userPrefFilter); - - rtrnList = query.getResultList(); - - return rtrnList; - } - - public List getIds(Query query) { - return (List) query.getResultList(); - } - - public Long executeCountQueryInSecurityContext(Class clazz, Query query) { //NOPMD - return (Long) query.getSingleResult(); - } - - public List getAll() { - List ret = null; - TypedQuery qry = em.createQuery( - "SELECT t FROM " + tClass.getSimpleName() + " t", tClass); - ret = qry.getResultList(); - return ret; - } - - public Long getAllCount() { - Long ret = null; - TypedQuery qry = em.createQuery( - "SELECT count(t) FROM " + tClass.getSimpleName() + " t", - Long.class); - ret = qry.getSingleResult(); - return ret; - } - - public void updateSequence(String seqName, long nextValue) { - if(RangerBizUtil.getDBFlavor() == AppConstants.DB_FLAVOR_ORACLE) { - String[] queries = { - "ALTER SEQUENCE " + seqName + " INCREMENT BY " + (nextValue - 1), - "select " + seqName + ".nextval from dual", - "ALTER SEQUENCE " + seqName + " INCREMENT BY 1 NOCACHE NOCYCLE" - }; - - for(String query : queries) { - getEntityManager().createNativeQuery(query).executeUpdate(); - } - } else if(RangerBizUtil.getDBFlavor() == AppConstants.DB_FLAVOR_POSTGRES) { - String query = "SELECT setval('" + seqName + "', " + nextValue + ")"; - - getEntityManager().createNativeQuery(query).getSingleResult(); - } - - } - - public void setIdentityInsert(boolean identityInsert) { - if (RangerBizUtil.getDBFlavor() != AppConstants.DB_FLAVOR_SQLSERVER) { - logger.debug("Ignoring BaseDao.setIdentityInsert(). This should be executed if DB flavor is sqlserver."); - return; - } - - EntityManager entityMgr = getEntityManager(); - - String identityInsertStr; - if (identityInsert) { - identityInsertStr = "ON"; - } else { - identityInsertStr = "OFF"; - } - - Table table = tClass.getAnnotation(Table.class); - - if(table == null) { - throw new NullPointerException("Required annotation `Table` not found"); - } - - String tableName = table.name(); - - try (PreparedStatement st = entityMgr.unwrap(Connection.class).prepareStatement("SET IDENTITY_INSERT ? ?" )) { - st.setString(1, tableName); - st.setString(2, identityInsertStr); - st.execute(); - } catch (SQLException e) { - logger.error("Error while settion identity_insert " + identityInsertStr, e); - } - } - - public void updateUserIDReference(String paramName,long oldID) { - Table table = tClass.getAnnotation(Table.class); - if(table != null) { - String tableName = table.name(); - String updatedValue = tableName.contains(GDS_TABLES) ? "1" : "null"; - String query = "update " + tableName + " set " + paramName+"=" + updatedValue + " where " +paramName+"=" + oldID; - - int count=getEntityManager().createNativeQuery(query).executeUpdate(); - if(count>0){ - logger.warn(count + " records updated in table '" + tableName + "' with: set " + paramName + "="+ updatedValue + " where " + paramName + "=" + oldID); - } - }else{ - logger.warn("Required annotation `Table` not found"); - } - } - - public String getDBVersion() { - String dbVersion = NOT_AVAILABLE; - int dbFlavor = RangerBizUtil.getDBFlavor(); - String query = RangerBizUtil.getDBVersionQuery(dbFlavor); - - if (StringUtils.isNotBlank(query)) { - try { - dbVersion = (String) getEntityManager().createNativeQuery(query).getSingleResult(); - } catch (Exception ex) { - logger.error("Error occurred while fetching the DB version.", ex); - } - } - - return dbVersion; - } + protected RangerDaoManager daoManager; + protected Class tClass; + EntityManager em; + + public BaseDao(RangerDaoManagerBase daoManager) { + this.daoManager = (RangerDaoManager) daoManager; + + this.init(daoManager.getEntityManager()); + } + + public BaseDao(RangerDaoManagerBase daoManager, String persistenceContextUnit) { + this.daoManager = (RangerDaoManager) daoManager; + + EntityManager em = this.daoManager.getEntityManager(persistenceContextUnit); + + this.init(em); + } + + public EntityManager getEntityManager() { + return this.em; + } + + public T create(T obj) { + T ret; + + em.persist(obj); + + if (!RangerBizUtil.isBulkMode()) { + em.flush(); + } + + ret = obj; + + return ret; + } + + public List batchCreate(List obj) { + List ret; + + for (int n = 0; n < obj.size(); ++n) { + em.persist(obj.get(n)); + + if (!RangerBizUtil.isBulkMode() && (n % RangerBizUtil.BATCH_PERSIST_SIZE == 0)) { + em.flush(); + } + } + + if (!RangerBizUtil.isBulkMode()) { + em.flush(); + } + + ret = obj; + + return ret; + } + + public void batchDeleteByIds(String namedQuery, List ids, String paramName) { + if (BATCH_DELETE_BATCH_SIZE <= 0) { + getEntityManager().createNamedQuery(namedQuery, tClass).setParameter(paramName, ids).executeUpdate(); + } else { + for (int fromIndex = 0; fromIndex < ids.size(); fromIndex += BATCH_DELETE_BATCH_SIZE) { + int toIndex = fromIndex + BATCH_DELETE_BATCH_SIZE; + + if (toIndex > ids.size()) { + toIndex = ids.size(); + } + + logger.debug("batchDeleteByIds({}, idCount={}): deleting fromIndex={}, toIndex={}", namedQuery, ids.size(), fromIndex, toIndex); + + List subList = ids.subList(fromIndex, toIndex); + + getEntityManager().createNamedQuery(namedQuery, tClass).setParameter(paramName, subList).executeUpdate(); + } + } + } + + public T update(T obj) { + em.merge(obj); + + if (!RangerBizUtil.isBulkMode()) { + em.flush(); + } + + return obj; + } + + public boolean remove(Long id) { + return remove(getById(id)); + } + + public boolean remove(T obj) { + if (obj == null) { + return true; + } + + if (!em.contains(obj)) { + obj = em.merge(obj); + } + + em.remove(obj); + + if (!RangerBizUtil.isBulkMode()) { + em.flush(); + } + + return true; + } + + public void flush() { + em.flush(); + } + + public void clear() { + em.clear(); + } + + public T create(T obj, boolean flush) { + T ret; + + em.persist(obj); + + if (flush) { + em.flush(); + } + + ret = obj; + + return ret; + } + + public T update(T obj, boolean flush) { + em.merge(obj); + + if (flush) { + em.flush(); + } + + return obj; + } + + public boolean remove(T obj, boolean flush) { + if (obj == null) { + return true; + } + + em.remove(obj); + + if (flush) { + em.flush(); + } + + return true; + } + + public T getById(Long id) { + if (id == null) { + return null; + } + + T ret; + + try { + ret = em.find(tClass, id); + } catch (NoResultException e) { + return null; + } + + return ret; + } + + public List findByNamedQuery(String namedQuery, String paramName, Object refId) { + List ret = new ArrayList<>(); + + if (namedQuery == null) { + return ret; + } + + try { + TypedQuery qry = em.createNamedQuery(namedQuery, tClass); + + qry.setParameter(paramName, refId); + + ret = qry.getResultList(); + } catch (NoResultException e) { + // ignore + } + + return ret; + } + + public List findByParentId(Long parentId) { + String namedQuery = tClass.getSimpleName() + ".findByParentId"; + + return findByNamedQuery(namedQuery, "parentId", parentId); + } + + public List executeQueryInSecurityContext(Class clazz, Query query) { + return executeQueryInSecurityContext(clazz, query, true); + } + + @SuppressWarnings("unchecked") + public List executeQueryInSecurityContext(Class clazz, Query query, boolean userPrefFilter) { + // boolean filterEnabled = false; + // filterEnabled = enableVisiblityFilters(clazz, userPrefFilter); + + return (List) query.getResultList(); + } + + public List getIds(Query query) { + return (List) query.getResultList(); + } + + public Long executeCountQueryInSecurityContext(Class clazz, Query query) { //NOPMD + return (Long) query.getSingleResult(); + } + + public List getAll() { + TypedQuery qry = em.createQuery("SELECT t FROM " + tClass.getSimpleName() + " t", tClass); + + return qry.getResultList(); + } + + public Long getAllCount() { + TypedQuery qry = em.createQuery("SELECT count(t) FROM " + tClass.getSimpleName() + " t", Long.class); + + return qry.getSingleResult(); + } + + public void updateSequence(String seqName, long nextValue) { + if (RangerBizUtil.getDBFlavor() == AppConstants.DB_FLAVOR_ORACLE) { + String[] queries = { + "ALTER SEQUENCE " + seqName + " INCREMENT BY " + (nextValue - 1), + "select " + seqName + ".nextval from dual", + "ALTER SEQUENCE " + seqName + " INCREMENT BY 1 NOCACHE NOCYCLE" + }; + + for (String query : queries) { + getEntityManager().createNativeQuery(query).executeUpdate(); + } + } else if (RangerBizUtil.getDBFlavor() == AppConstants.DB_FLAVOR_POSTGRES) { + String query = "SELECT setval('" + seqName + "', " + nextValue + ")"; + + getEntityManager().createNativeQuery(query).getSingleResult(); + } + } + + public void setIdentityInsert(boolean identityInsert) { + if (RangerBizUtil.getDBFlavor() != AppConstants.DB_FLAVOR_SQLSERVER) { + logger.debug("Ignoring BaseDao.setIdentityInsert(). This should be executed if DB flavor is sqlserver."); + return; + } + + EntityManager entityMgr = getEntityManager(); + + String identityInsertStr; + if (identityInsert) { + identityInsertStr = "ON"; + } else { + identityInsertStr = "OFF"; + } + + Table table = tClass.getAnnotation(Table.class); + + if (table == null) { + throw new NullPointerException("Required annotation `Table` not found"); + } + + String tableName = table.name(); + + try (PreparedStatement st = entityMgr.unwrap(Connection.class).prepareStatement("SET IDENTITY_INSERT ? ?")) { + st.setString(1, tableName); + st.setString(2, identityInsertStr); + st.execute(); + } catch (SQLException e) { + logger.error("Error while settion identity_insert {}", identityInsertStr, e); + } + } + + public void updateUserIDReference(String paramName, long oldID) { + Table table = tClass.getAnnotation(Table.class); + + if (table != null) { + String tableName = table.name(); + String updatedValue = tableName.contains(GDS_TABLES) ? "1" : "null"; + String query = "update " + tableName + " set " + paramName + "=" + updatedValue + " where " + paramName + "=" + oldID; + int count = getEntityManager().createNativeQuery(query).executeUpdate(); + + if (count > 0) { + logger.warn("{} records updated in table '{}' with: set {}={} where {}={}", count, tableName, paramName, updatedValue, paramName, oldID); + } + } else { + logger.warn("Required annotation `Table` not found"); + } + } + + public String getDBVersion() { + String dbVersion = NOT_AVAILABLE; + int dbFlavor = RangerBizUtil.getDBFlavor(); + String query = RangerBizUtil.getDBVersionQuery(dbFlavor); + + if (StringUtils.isNotBlank(query)) { + try { + dbVersion = (String) getEntityManager().createNativeQuery(query).getSingleResult(); + } catch (Exception ex) { + logger.error("Error occurred while fetching the DB version.", ex); + } + } + + return dbVersion; + } + + @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) ((ParameterizedType) type).getRawType(); + } else { + this.tClass = (Class) type; + } + } + + static { + try { + BATCH_DELETE_BATCH_SIZE = RangerAdminConfig.getInstance().getInt(PROP_BATCH_DELETE_BATCH_SIZE, DEFAULT_BATCH_DELETE_BATCH_SIZE); + + if (BATCH_DELETE_BATCH_SIZE > DEFAULT_BATCH_DELETE_BATCH_SIZE) { + logger.warn("Configuration {}={}, which is larger than default value {}", PROP_BATCH_DELETE_BATCH_SIZE, BATCH_DELETE_BATCH_SIZE, DEFAULT_BATCH_DELETE_BATCH_SIZE); + } + } catch (Exception e) { + // When we get the Number format exception due to the invalid value entered into the config file. + BATCH_DELETE_BATCH_SIZE = DEFAULT_BATCH_DELETE_BATCH_SIZE; + } + + logger.info(PROP_BATCH_DELETE_BATCH_SIZE + "=" + BATCH_DELETE_BATCH_SIZE); + } } 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 index 0d83e77fbe..42f08e70d7 100644 --- 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 @@ -17,10 +17,7 @@ * under the License. */ - package org.apache.ranger.common.db; - -import javax.persistence.PrePersist; -import javax.persistence.PreUpdate; +package org.apache.ranger.common.db; import org.apache.ranger.common.DateUtil; import org.apache.ranger.common.UserSessionBase; @@ -30,82 +27,77 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import javax.persistence.PrePersist; +import javax.persistence.PreUpdate; + public class JPABeanCallbacks { - private static final Logger logger = LoggerFactory.getLogger(JPABeanCallbacks.class); - - @PrePersist - void onPrePersist(Object o) { - try { - if (o != null && o instanceof XXDBBase) { - XXDBBase entity = (XXDBBase) o; - - entity.setUpdateTime(DateUtil.getUTCDate()); - if (entity.getAddedByUserId() == null || entity.getAddedByUserId() == 0) { - - if (logger.isDebugEnabled()) { - logger.debug("AddedByUserId is null or 0 and hence getting it from userSession for " + entity.getId()); - } - RangerSecurityContext context = RangerContextHolder - .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("User session not found for this request. Identity of originator of this change cannot be recorded"); - } - } - } else { - if (logger.isDebugEnabled()) { - logger.debug("Security context not found for this request. Identity of originator of this change cannot be recorded"); - } - } - } - } - } 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 + private static final Logger logger = LoggerFactory.getLogger(JPABeanCallbacks.class); + + @PrePersist + void onPrePersist(Object o) { + try { + if (o instanceof XXDBBase) { + XXDBBase entity = (XXDBBase) o; + + entity.setUpdateTime(DateUtil.getUTCDate()); + if (entity.getAddedByUserId() == null || entity.getAddedByUserId() == 0) { + logger.debug("AddedByUserId is null or 0 and hence getting it from userSession for {}", entity.getId()); + + RangerSecurityContext context = RangerContextHolder.getSecurityContext(); + + if (context != null) { + UserSessionBase userSession = context.getUserSession(); + + if (userSession != null) { + entity.setAddedByUserId(userSession.getUserId()); + entity.setUpdatedByUserId(userSession.getUserId()); + } else { + logger.debug("User session not found for this request. Identity of originator of this change cannot be recorded"); + } + } else { + logger.debug("Security context not found for this request. Identity of originator of this change cannot be recorded"); + } + } + } + } 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 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) { + // } +} diff --git a/security-admin/src/main/java/org/apache/ranger/common/db/RangerTransactionSynchronizationAdapter.java b/security-admin/src/main/java/org/apache/ranger/common/db/RangerTransactionSynchronizationAdapter.java index 293cbfa01b..dfb922784c 100644 --- a/security-admin/src/main/java/org/apache/ranger/common/db/RangerTransactionSynchronizationAdapter.java +++ b/security-admin/src/main/java/org/apache/ranger/common/db/RangerTransactionSynchronizationAdapter.java @@ -19,31 +19,32 @@ package org.apache.ranger.common.db; -import java.util.ArrayList; -import java.util.List; - import org.apache.commons.collections.CollectionUtils; - import org.apache.ranger.service.RangerTransactionService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; - 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.TransactionSystemException; -import org.springframework.transaction.support.TransactionCallback; import org.springframework.transaction.support.TransactionSynchronizationAdapter; import org.springframework.transaction.support.TransactionSynchronizationManager; import org.springframework.transaction.support.TransactionTemplate; import javax.persistence.OptimisticLockException; +import java.util.ArrayList; +import java.util.List; + @Component public class RangerTransactionSynchronizationAdapter extends TransactionSynchronizationAdapter { + private static final Logger LOG = LoggerFactory.getLogger(RangerTransactionSynchronizationAdapter.class); + + private static final ThreadLocal> RUNNABLES = new ThreadLocal<>(); + private static final ThreadLocal> RUNNABLES_ASYNC = new ThreadLocal<>(); + private static final ThreadLocal> RUNNABLES_AFTER_COMMIT = new ThreadLocal<>(); @Autowired @Qualifier(value = "transactionManager") @@ -52,51 +53,35 @@ public class RangerTransactionSynchronizationAdapter extends TransactionSynchron @Autowired RangerTransactionService transactionService; - private static final Logger LOG = LoggerFactory.getLogger(RangerTransactionSynchronizationAdapter.class); - - private static final ThreadLocal> RUNNABLES = new ThreadLocal<>(); - private static final ThreadLocal> RUNNABLES_ASYNC = new ThreadLocal<>(); - private static final ThreadLocal> RUNNABLES_AFTER_COMMIT = new ThreadLocal<>(); - public void executeOnTransactionCompletion(Runnable runnable) { - if (LOG.isDebugEnabled()) { - LOG.debug("Submitting new runnable {" + runnable + "} to run after completion"); - } + LOG.debug("Submitting new runnable {{}} to run after completion", runnable); addRunnable(runnable, RUNNABLES); } public void executeAsyncOnTransactionComplete(Runnable runnable) { - if (LOG.isDebugEnabled()) { - LOG.debug("Submitting new runnable {" + runnable + "} to run async after completion"); - } + LOG.debug("Submitting new runnable {{}} to run async after completion", runnable); addRunnable(runnable, RUNNABLES_ASYNC); } public void executeOnTransactionCommit(Runnable runnable) { - if (LOG.isDebugEnabled()) { - LOG.debug("Submitting new runnable {" + runnable + "} to run after transaction is committed"); - } + LOG.debug("Submitting new runnable {{}} to run after transaction is committed", runnable); addRunnable(runnable, RUNNABLES_AFTER_COMMIT); } @Override public void afterCompletion(int status) { - if (LOG.isDebugEnabled()) { - LOG.debug("==> RangerTransactionSynchronizationAdapter.afterCompletion(status=" + (status == STATUS_COMMITTED ? "COMMITTED" : "ROLLED_BACK") + ")"); - } + LOG.debug("==> RangerTransactionSynchronizationAdapter.afterCompletion(status={})", status == STATUS_COMMITTED ? "COMMITTED" : "ROLLED_BACK"); - final boolean isParentTransactionCommitted = status == STATUS_COMMITTED; + final boolean isParentTransactionCommitted = status == STATUS_COMMITTED; + List runnablesAfterCommit = RUNNABLES_AFTER_COMMIT.get(); + List runnables = RUNNABLES.get(); + List asyncRunnables = RUNNABLES_ASYNC.get(); - List runnablesAfterCommit = RUNNABLES_AFTER_COMMIT.get(); RUNNABLES_AFTER_COMMIT.remove(); - - List runnables = RUNNABLES.get(); RUNNABLES.remove(); - - List asyncRunnables = RUNNABLES_ASYNC.get(); RUNNABLES_ASYNC.remove(); if (asyncRunnables != null) { @@ -113,9 +98,7 @@ public void afterCompletion(int status) { // Run other tasks scheduled to run after transaction completes runRunnables(runnables, false); - if (LOG.isDebugEnabled()) { - LOG.debug("<== RangerTransactionSynchronizationAdapter.afterCompletion(status=" + (status == STATUS_COMMITTED ? "COMMITTED" : "ROLLED_BACK") + ")"); - } + LOG.debug("<== RangerTransactionSynchronizationAdapter.afterCompletion(status={})", status == STATUS_COMMITTED ? "COMMITTED" : "ROLLED_BACK"); } private void addRunnable(Runnable runnable, ThreadLocal> threadRunnables) { @@ -131,7 +114,7 @@ private void addRunnable(Runnable runnable, ThreadLocal> threadRu TransactionSynchronizationAdapter */ if (!registerSynchronization()) { - LOG.info("Transaction synchronization is NOT ACTIVE. Executing right now runnable {" + runnable + "}"); + LOG.info("Transaction synchronization is NOT ACTIVE. Executing right now runnable {{}}", runnable); runnable.run(); @@ -142,6 +125,7 @@ private void addRunnable(Runnable runnable, ThreadLocal> threadRu if (runnables == null) { runnables = new ArrayList<>(); + threadRunnables.set(runnables); } @@ -160,85 +144,75 @@ private boolean registerSynchronization() { TransactionSynchronizationManager.registerSynchronization(this); } } + return ret; } private void runRunnables(final List runnables, final boolean isParentTransactionCommitted) { - if (LOG.isDebugEnabled()) { - LOG.debug("==> RangerTransactionSynchronizationAdapter.runRunnables()"); - } + LOG.debug("==> RangerTransactionSynchronizationAdapter.runRunnables()"); if (CollectionUtils.isNotEmpty(runnables)) { - if (LOG.isDebugEnabled()) { - LOG.debug("Executing {" + runnables.size() + "} runnables"); - } + LOG.debug("Executing {{}} runnables", runnables.size()); + for (Runnable runnable : runnables) { boolean isThisTransactionCommitted = false; + do { try { //Create new transaction TransactionTemplate txTemplate = new TransactionTemplate(txManager); + txTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); - Object result = txTemplate.execute(new TransactionCallback() { - public Object doInTransaction(TransactionStatus status) { - Object result = null; - if (LOG.isDebugEnabled()) { - LOG.debug("Executing runnable {" + runnable + "}"); - } - try { - runnable.run(); - result = runnable; - if (LOG.isDebugEnabled()) { - LOG.debug("executed runnable " + runnable); - } - } catch (OptimisticLockException optimisticLockException) { - if (LOG.isDebugEnabled()) { - LOG.debug("Failed to execute runnable " + runnable + "because of OpmimisticLockException"); - } - } catch (Throwable e) { - if (LOG.isDebugEnabled()) { - LOG.debug("Failed to execute runnable " + runnable, e); - } - } - return result; + Object result = txTemplate.execute(status -> { + Object result1 = null; + + LOG.debug("Executing runnable {{}}", runnable); + + try { + runnable.run(); + + result1 = runnable; + + LOG.debug("executed runnable {}", runnable); + } catch (OptimisticLockException optimisticLockException) { + LOG.debug("Failed to execute runnable {}because of OpmimisticLockException", runnable); + } catch (Throwable e) { + LOG.debug("Failed to execute runnable {}", runnable, e); } + + return result1; }); isThisTransactionCommitted = result == runnable; + if (isParentTransactionCommitted) { if (!isThisTransactionCommitted) { - LOG.info("Failed to commit runnable:[" + runnable + "]. Will retry!"); + LOG.info("Failed to commit runnable:[{}]. Will retry!", runnable); } else { - if (LOG.isDebugEnabled()) { - LOG.debug("Committed runnable:[" + runnable + "]."); - } + LOG.debug("Committed runnable:[{}].", runnable); } } - } catch (OptimisticLockException optimisticLockException) { if (LOG.isDebugEnabled()) { - LOG.debug("Failed to commit TransactionService transaction for runnable:[" + runnable + "]"); + LOG.debug("Failed to commit TransactionService transaction for runnable:[{}]", runnable); } } catch (TransactionSystemException tse) { if (LOG.isDebugEnabled()) { - LOG.debug("Failed to commit TransactionService transaction, exception:[" + tse + "]"); + LOG.debug("Failed to commit TransactionService transaction, exception:[{}]", String.valueOf(tse)); } - } catch (Throwable e){ + } catch (Throwable e) { if (LOG.isDebugEnabled()) { - LOG.debug("Failed to commit TransactionService transaction, throwable:[" + e + "]"); + LOG.debug("Failed to commit TransactionService transaction, throwable:[{}]", String.valueOf(e)); } } - } while (isParentTransactionCommitted && !isThisTransactionCommitted); + } + while (isParentTransactionCommitted && !isThisTransactionCommitted); } } else { - if (LOG.isDebugEnabled()) { - LOG.debug("No runnables to execute"); - } + LOG.debug("No runnables to execute"); } - if (LOG.isDebugEnabled()) { - LOG.debug("<== RangerTransactionSynchronizationAdapter.runRunnables()"); - } + LOG.debug("<== RangerTransactionSynchronizationAdapter.runRunnables()"); } -} \ No newline at end of file +} 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 index 64bf2c43c7..49b65f8df9 100644 --- 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 @@ -17,88 +17,85 @@ * under the License. */ - package org.apache.ranger.common.view; - -import java.util.List; +package org.apache.ranger.common.view; import org.apache.ranger.common.RangerCommonEnums; +import java.util.List; public class VEnum extends ViewBaseBean implements java.io.Serializable { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; - /** - * Name of the enum - */ - protected String enumName; - /** - * List of elements for this enum - */ - protected List elementList; + /** + * Name of the enum + */ + protected String enumName; + /** + * List of elements for this enum + */ + protected List elementList; - /** - * Default constructor. This will set all the attributes to default value. - */ - public VEnum() { - } + /** + * Default constructor. This will set all the attributes to default value. + */ + public VEnum() { + } - /** - * This method sets the value to the member attribute enumName. You - * cannot set null to the attribute. - * - * @param enumName - * Value to set member attribute enumName - */ - public void setEnumName(String enumName) { - this.enumName = enumName; - } + /** + * Returns the value for the member attribute enumName + * + * @return String - value of member attribute enumName. + */ + public String getEnumName() { + return this.enumName; + } - /** - * Returns the value for the member attribute enumName - * - * @return String - value of member attribute enumName. - */ - public String getEnumName() { - return this.enumName; - } + /** + * This method sets the value to the member attribute enumName. You + * cannot set null to the attribute. + * + * @param enumName Value to set member attribute enumName + */ + public void setEnumName(String enumName) { + this.enumName = enumName; + } - /** - * This method sets the value to the member attribute elementList. - * You cannot set null to the attribute. - * - * @param elementList - * Value to set member attribute elementList - */ - public void setElementList(List elementList) { - this.elementList = elementList; - } + /** + * Returns the value for the member attribute elementList + * + * @return List - value of member attribute + * elementList. + */ + public List getElementList() { + return this.elementList; + } - /** - * Returns the value for the member attribute elementList - * - * @return List - value of member attribute - * elementList. - */ - public List getElementList() { - return this.elementList; - } + /** + * This method sets the value to the member attribute elementList. + * You cannot set null to the attribute. + * + * @param elementList Value to set member attribute elementList + */ + public void setElementList(List elementList) { + this.elementList = elementList; + } - @Override - public int getMyClassType() { - return RangerCommonEnums.CLASS_TYPE_ENUM; - } + @Override + public int getMyClassType() { + return RangerCommonEnums.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; - } + /** + * 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; + } } 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 index 359746592a..08a65c4470 100644 --- 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 @@ -17,147 +17,148 @@ * under the License. */ - package org.apache.ranger.common.view; +package org.apache.ranger.common.view; import org.apache.ranger.common.RangerCommonEnums; 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 elementName. - * You cannot set null to the attribute. - * @param elementName Value to set member attribute elementName - */ - 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 enumName. - * You cannot set null to the attribute. - * @param enumName Value to set member attribute enumName - */ - public void setEnumName( String enumName ) { - this.enumName = enumName; - } - - - - /** - * This method sets the value to the member attribute elementValue. - * You cannot set null to the attribute. - * @param elementValue Value to set member attribute elementValue - */ - public void setElementValue( int elementValue ) { - this.elementValue = elementValue; - } - - /** - * Returns the value for the member attribute elementValue - * @return int - value of member attribute elementValue. - */ - public int getElementValue( ) { - return this.elementValue; - } - - /** - * This method sets the value to the member attribute elementLabel. - * You cannot set null to the attribute. - * @param elementLabel Value to set member attribute elementLabel - */ - public void setElementLabel( String elementLabel ) { - this.elementLabel = elementLabel; - } - - /** - * Returns the value for the member attribute elementLabel - * @return String - value of member attribute elementLabel. - */ - public String getElementLabel( ) { - return this.elementLabel; - } - - /** - * This method sets the value to the member attribute rbKey. - * You cannot set null to the attribute. - * @param rbKey Value to set member attribute rbKey - */ - public void setRbKey( String rbKey ) { - this.rbKey = rbKey; - } - - - - @Override - public int getMyClassType( ) { - return RangerCommonEnums.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; - } + 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() { + } + + /** + * @return the elementName + */ + public String getElementName() { + return elementName; + } + + /** + * This method sets the value to the member attribute elementName. + * You cannot set null to the attribute. + * + * @param elementName Value to set member attribute elementName + */ + public void setElementName(String elementName) { + this.elementName = elementName; + } + + /** + * @return the enumName + */ + public String getEnumName() { + return enumName; + } + + /** + * This method sets the value to the member attribute enumName. + * You cannot set null to the attribute. + * + * @param enumName Value to set member attribute enumName + */ + public void setEnumName(String enumName) { + this.enumName = enumName; + } + + /** + * @return the rbKey + */ + public String getRbKey() { + return rbKey; + } + + /** + * This method sets the value to the member attribute rbKey. + * You cannot set null to the attribute. + * + * @param rbKey Value to set member attribute rbKey + */ + public void setRbKey(String rbKey) { + this.rbKey = rbKey; + } + + /** + * Returns the value for the member attribute elementValue + * + * @return int - value of member attribute elementValue. + */ + public int getElementValue() { + return this.elementValue; + } + + /** + * This method sets the value to the member attribute elementValue. + * You cannot set null to the attribute. + * + * @param elementValue Value to set member attribute elementValue + */ + public void setElementValue(int elementValue) { + this.elementValue = elementValue; + } + + /** + * Returns the value for the member attribute elementLabel + * + * @return String - value of member attribute elementLabel. + */ + public String getElementLabel() { + return this.elementLabel; + } + + /** + * This method sets the value to the member attribute elementLabel. + * You cannot set null to the attribute. + * + * @param elementLabel Value to set member attribute elementLabel + */ + public void setElementLabel(String elementLabel) { + this.elementLabel = elementLabel; + } + + @Override + public int getMyClassType() { + return RangerCommonEnums.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; + } } 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 index 6a622bb0f5..b2ac9e8a6b 100644 --- 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 @@ -17,32 +17,29 @@ * under the License. */ - package org.apache.ranger.common.view; - +package org.apache.ranger.common.view; import java.util.List; - -public abstract class VList extends ViewBaseBean implements - java.io.Serializable { +public abstract class VList extends ViewBaseBean implements java.io.Serializable { private static final long serialVersionUID = 1L; /** * Start index for the result */ - protected int startIndex; + protected int startIndex; /** * Page size used for the result */ - protected int pageSize; + protected int pageSize; /** * Total records in the database for the given search conditions */ - protected long totalCount; + protected long totalCount; /** * Number of rows returned for the search condition */ - protected int resultSize; + protected int resultSize; /** * Sort type. Either desc or asc */ @@ -63,115 +60,114 @@ public VList() { /** * Initialize with existing list * - * @param size + * @param objectList */ 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; + 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(); + public abstract int getListSize(); - abstract public List getList(); + public abstract List getList(); + + public int getStartIndex() { + return startIndex; + } /** * This method sets the value to the member attribute startIndex. You * cannot set null to the attribute. * - * @param startIndex - * Value to set member attribute startIndex + * @param startIndex Value to set member attribute startIndex */ public void setStartIndex(int startIndex) { - this.startIndex = startIndex; + this.startIndex = startIndex; } - public int getStartIndex() { return startIndex; } + public int getPageSize() { + return pageSize; + } /** * This method sets the value to the member attribute pageSize. You * cannot set null to the attribute. * - * @param pageSize - * Value to set member attribute pageSize + * @param pageSize Value to set member attribute pageSize */ public void setPageSize(int pageSize) { - this.pageSize = pageSize; + this.pageSize = pageSize; + } + + public long getTotalCount() { + return totalCount; } - public int getPageSize() { return pageSize; } /** * This method sets the value to the member attribute totalCount. You * cannot set null to the attribute. * - * @param totalCount - * Value to set member attribute totalCount + * @param totalCount Value to set member attribute totalCount */ public void setTotalCount(long totalCount) { - this.totalCount = totalCount; + this.totalCount = totalCount; } - public long getTotalCount() { return totalCount; } - + /** + * Returns the value for the member attribute resultSize + * + * @return int - value of member attribute resultSize. + */ + public int getResultSize() { + return getListSize(); + } /** * This method sets the value to the member attribute resultSize. You * cannot set null to the attribute. * - * @param resultSize - * Value to set member attribute resultSize + * @param resultSize Value to set member attribute resultSize */ public void setResultSize(int resultSize) { - this.resultSize = resultSize; + this.resultSize = resultSize; } - /** - * Returns the value for the member attribute resultSize - * - * @return int - value of member attribute resultSize. - */ - public int getResultSize() { - return getListSize(); + public String getSortType() { + return sortType; } /** * This method sets the value to the member attribute sortType. You * cannot set null to the attribute. * - * @param sortType - * Value to set member attribute sortType + * @param sortType Value to set member attribute sortType */ public void setSortType(String sortType) { - this.sortType = sortType; + this.sortType = sortType; } - public String getSortType() { return sortType; } + public String getSortBy() { + return sortBy; + } /** * This method sets the value to the member attribute sortBy. You * cannot set null to the attribute. * - * @param sortBy - * Value to set member attribute sortBy + * @param sortBy Value to set member attribute sortBy */ public void setSortBy(String sortBy) { - this.sortBy = sortBy; + this.sortBy = sortBy; } - public String getSortBy() { return sortBy; } - - - - - - /* * (non-Javadoc) @@ -180,11 +176,10 @@ public void setSortBy(String sortBy) { */ @Override public String toString() { - return "VList [startIndex=" + startIndex + ", pageSize=" - + pageSize + ", totalCount=" + totalCount - + ", resultSize=" + resultSize + ", sortType=" - + sortType + ", sortBy=" + sortBy + ", queryTimeMS=" - + queryTimeMS + "]"; + return "VList [startIndex=" + startIndex + ", pageSize=" + + pageSize + ", totalCount=" + totalCount + + ", resultSize=" + resultSize + ", sortType=" + + sortType + ", sortBy=" + sortBy + ", queryTimeMS=" + + queryTimeMS + "]"; } - } 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 index b28ce664a6..5c637363f3 100644 --- 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 @@ -17,169 +17,169 @@ * under the License. */ - package org.apache.ranger.common.view; - -import java.io.Serializable; -import java.lang.reflect.Field; -import java.util.Collection; -import java.util.Objects; +package org.apache.ranger.common.view; import org.apache.ranger.common.AppConstants; import org.apache.ranger.entity.XXAsset; import org.apache.ranger.plugin.util.JsonUtilsV2; import org.apache.ranger.util.RangerEnumUtil; -public class VTrxLogAttr extends ViewBaseBean implements Serializable{ - private static final long serialVersionUID = 1L; - - private final String attribName; - private final String attribUserFriendlyName; - private final boolean isEnum; - private final boolean isObjName; - - public VTrxLogAttr(String attribName, String attribUserFriendlyName) { - this(attribName, attribUserFriendlyName, false, false); - } - - public VTrxLogAttr(String attribName, String attribUserFriendlyName, boolean isEnum) { - this(attribName, attribUserFriendlyName, isEnum, false); - } - - public VTrxLogAttr(String attribName, String attribUserFriendlyName, boolean isEnum, boolean isObjName) { - super(); - - this.attribName = attribName; - this.attribUserFriendlyName = attribUserFriendlyName; - this.isEnum = isEnum; - this.isObjName = isObjName; - } - - /** - * @return the attribName - */ - public String getAttribName() { - return attribName; - } - - /** - * @return the attribUserFriendlyName - */ - public String getAttribUserFriendlyName() { - return attribUserFriendlyName; - } - - /** - * @return the isEnum - */ - public boolean isEnum() { - return isEnum; - } - - /** - * @return the isObjName - */ - public boolean isObjName() { - return isObjName; - } - - @Override - public int getMyClassType( ) { - return AppConstants.CLASS_TYPE_XA_TRANSACTION_LOG_ATTRIBUTE; - } - - public String getAttrValue(Object obj, RangerEnumUtil xaEnumUtil) { - String ret = null; - - if (obj != null) { - Field field = getField(obj); - - if (field != null) { - ret = getFieldValue(obj, field, xaEnumUtil); - } - } - - return ret; - } - - @Override - public String toString(){ - String str = "VTrxLogAttr={"; - str += super.toString(); - str += "attribName={" + attribName + "} "; - str += "attribUserFriendlyName={" + attribUserFriendlyName + "} "; - str += "isEnum={" + isEnum + "} "; - str += "isObjName={" + isObjName + "} "; - str += "}"; - return str; - } - - private Field getField(Object obj) { - Field field = null; - - try { - field = obj.getClass().getDeclaredField(attribName); - } catch (NoSuchFieldException excp) { - try { - field = obj.getClass().getSuperclass().getDeclaredField(attribName); - } catch (NoSuchFieldException excp1) { - // ignore - } - } - - if (field != null && !field.isAccessible()) { - field.setAccessible(true); - } - - return field; - } - - private String getFieldValue(Object obj, Field field, RangerEnumUtil xaEnumUtil) { - String ret = null; - Object val = null; - - try { - val = field.get(obj); - } catch (IllegalArgumentException | IllegalAccessException excp) { - // ignore - } - - if (isEnum) { - String enumName = XXAsset.getEnumName(field.getName()); - int enumValue = -1; - - if (val == null) { - enumValue = 0; - } else if (val instanceof Number) { - enumValue = ((Number) val).intValue(); - } else { - try { - enumValue = Integer.parseInt(val.toString()); - } catch (Exception excp) { - // ignore - } - } - - if (enumValue == -1) { // val is not a number - ret = val.toString(); - } else { - ret = xaEnumUtil.getLabel(enumName, enumValue); - } - } else if (val != null) { - if (val instanceof String) { - ret = (String) val; - } else if (val instanceof Collection && ((Collection) val).isEmpty()) { - ret = null; - } else if (val instanceof Serializable) { - try { - ret = JsonUtilsV2.objToJson((Serializable) val); - } catch (Exception excp) { - // ignore - } - } else { - ret = Objects.toString(val); - } - } - - return ret; - } +import java.io.Serializable; +import java.lang.reflect.Field; +import java.util.Collection; +import java.util.Objects; + +public class VTrxLogAttr extends ViewBaseBean implements Serializable { + private static final long serialVersionUID = 1L; + + private final String attribName; + private final String attribUserFriendlyName; + private final boolean isEnum; + private final boolean isObjName; + + public VTrxLogAttr(String attribName, String attribUserFriendlyName) { + this(attribName, attribUserFriendlyName, false, false); + } + + public VTrxLogAttr(String attribName, String attribUserFriendlyName, boolean isEnum) { + this(attribName, attribUserFriendlyName, isEnum, false); + } + + public VTrxLogAttr(String attribName, String attribUserFriendlyName, boolean isEnum, boolean isObjName) { + super(); + + this.attribName = attribName; + this.attribUserFriendlyName = attribUserFriendlyName; + this.isEnum = isEnum; + this.isObjName = isObjName; + } + + /** + * @return the attribName + */ + public String getAttribName() { + return attribName; + } + + /** + * @return the attribUserFriendlyName + */ + public String getAttribUserFriendlyName() { + return attribUserFriendlyName; + } + + /** + * @return the isEnum + */ + public boolean isEnum() { + return isEnum; + } + + /** + * @return the isObjName + */ + public boolean isObjName() { + return isObjName; + } + + @Override + public int getMyClassType() { + return AppConstants.CLASS_TYPE_XA_TRANSACTION_LOG_ATTRIBUTE; + } + + public String getAttrValue(Object obj, RangerEnumUtil xaEnumUtil) { + String ret = null; + + if (obj != null) { + Field field = getField(obj); + + if (field != null) { + ret = getFieldValue(obj, field, xaEnumUtil); + } + } + + return ret; + } + + @Override + public String toString() { + String str = "VTrxLogAttr={"; + str += super.toString(); + str += "attribName={" + attribName + "} "; + str += "attribUserFriendlyName={" + attribUserFriendlyName + "} "; + str += "isEnum={" + isEnum + "} "; + str += "isObjName={" + isObjName + "} "; + str += "}"; + return str; + } + + private Field getField(Object obj) { + Field field = null; + + try { + field = obj.getClass().getDeclaredField(attribName); + } catch (NoSuchFieldException excp) { + try { + field = obj.getClass().getSuperclass().getDeclaredField(attribName); + } catch (NoSuchFieldException excp1) { + // ignore + } + } + + if (field != null && !field.isAccessible()) { + field.setAccessible(true); + } + + return field; + } + + private String getFieldValue(Object obj, Field field, RangerEnumUtil xaEnumUtil) { + String ret = null; + Object val = null; + + try { + val = field.get(obj); + } catch (IllegalArgumentException | IllegalAccessException excp) { + // ignore + } + + if (isEnum) { + String enumName = XXAsset.getEnumName(field.getName()); + int enumValue = -1; + + if (val == null) { + enumValue = 0; + } else if (val instanceof Number) { + enumValue = ((Number) val).intValue(); + } else { + try { + enumValue = Integer.parseInt(val.toString()); + } catch (Exception excp) { + // ignore + } + } + + if (enumValue == -1) { // val is not a number + ret = val.toString(); + } else { + ret = xaEnumUtil.getLabel(enumName, enumValue); + } + } else if (val != null) { + if (val instanceof String) { + ret = (String) val; + } else if (val instanceof Collection && ((Collection) val).isEmpty()) { + ret = null; + } else if (val instanceof Serializable) { + try { + ret = JsonUtilsV2.objToJson((Serializable) val); + } catch (Exception excp) { + // ignore + } + } else { + ret = Objects.toString(val); + } + } + + return ret; + } } 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 index f6b9bd6f66..4667a5eb74 100644 --- 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 @@ -17,36 +17,35 @@ * under the License. */ - package org.apache.ranger.common.view; +package org.apache.ranger.common.view; +import com.fasterxml.jackson.annotation.JsonIgnore; import org.apache.ranger.common.RangerCommonEnums; import org.apache.ranger.entity.XXDBBase; -import com.fasterxml.jackson.annotation.JsonIgnore; public class ViewBaseBean implements java.io.Serializable { private static final long serialVersionUID = 1L; @JsonIgnore - private XXDBBase mObj = null; + private XXDBBase mObj; /** * @return the gjObj */ @JsonIgnore public XXDBBase getMObj() { - return mObj; + return mObj; } /** - * @param gjObj - * the gjObj to set + * @param gjObj the gjObj to set */ public void setMObj(XXDBBase gjObj) { - this.mObj = gjObj; + this.mObj = gjObj; } @JsonIgnore public int getMyClassType() { - return RangerCommonEnums.CLASS_TYPE_NONE; + return RangerCommonEnums.CLASS_TYPE_NONE; } } From ddcde419d118246f9be5c07d78e4572711843779 Mon Sep 17 00:00:00 2001 From: Madhan Neethiraj Date: Tue, 7 Jan 2025 11:13:11 -0800 Subject: [PATCH 10/15] RANGER-5061: checkstyle compliance updates - security-admin org.apache.ranger.common - fix for unittest failure --- .../src/main/java/org/apache/ranger/common/UserSessionBase.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 index 6957595fc1..17644b790a 100644 --- a/security-admin/src/main/java/org/apache/ranger/common/UserSessionBase.java +++ b/security-admin/src/main/java/org/apache/ranger/common/UserSessionBase.java @@ -41,7 +41,7 @@ public class UserSessionBase implements Serializable { private List userRoleList = new ArrayList<>(); private RangerUserPermission rangerUserPermission; private Boolean isSSOEnabled; - private Boolean isSpnegoEnabled; + private Boolean isSpnegoEnabled = Boolean.FALSE; public Long getUserId() { if (xXPortalUser != null) { From b1ca7fbc53a952d7d048e6f02a439f14560d72c2 Mon Sep 17 00:00:00 2001 From: PradeeP AgrawaL Date: Wed, 8 Jan 2025 00:53:02 +0530 Subject: [PATCH 11/15] RANGER-5061: checkstyle compliance updates - security-admin modules (#495) - org.apache.ranger.view - org.apache.ranger.validation - org.apache.ranger.solr - org.apache.ranger.json - org.apache.ranger.metrics - org.apache.ranger.patch - org.apache.ranger.security --- dev-support/checkstyle-suppressions.xml | 49 + .../javax/ws/rs/core/NoContentException.java | 7 +- .../apache/ranger/AccessAuditsService.java | 136 +- .../java/org/apache/ranger/json/Folder.java | 36 +- .../ranger/json/JsonDateSerializer.java | 27 +- .../metrics/RangerAdminMetricsWrapper.java | 18 +- .../ranger/metrics/RangerMetricsFetcher.java | 80 +- .../source/RangerAdminMetricsSourceBase.java | 15 +- ...ngerAdminMetricsSourceContextEnricher.java | 6 +- ...angerAdminMetricsSourceDenyConditions.java | 6 +- ...RangerAdminMetricsSourcePolicyMasking.java | 6 +- ...dminMetricsSourcePolicyResourceAccess.java | 7 +- ...rAdminMetricsSourcePolicyRowFiltering.java | 6 +- .../RangerAdminMetricsSourceService.java | 6 +- .../RangerAdminMetricsSourceUserGroup.java | 6 +- .../org/apache/ranger/patch/BaseLoader.java | 268 +-- ...SecurityZonePersmissionToAdmin_J10026.java | 362 +-- ...AtlasForClassificationResource_J10047.java | 137 +- ...iceDefForPolicyConditionUpdate_J10060.java | 145 +- ...efUpdateForDefaultAuditFilters_J10049.java | 284 ++- ...ateForResourceSpecificAccesses_J10012.java | 104 +- .../PatchForAtlasAdminAudits_J10043.java | 78 +- ...lasResourceAndAccessTypeUpdate_J10016.java | 645 +++--- .../PatchForAtlasServiceDefUpdate_J10013.java | 480 ++-- ...EntityLabelAndBusinessMetadata_J10034.java | 231 +- .../PatchForAtlasToAddTypeRead_J10040.java | 155 +- .../PatchForDefaultAuidtFilters_J10050.java | 248 +- ...tchForExternalUserStatusUpdate_J10056.java | 142 +- ...tchForHBaseDefaultPolicyUpdate_J10045.java | 228 +- .../PatchForHBaseServiceDefUpdate_J10035.java | 125 +- .../PatchForHiveServiceDefUpdate_J10006.java | 363 +-- .../PatchForHiveServiceDefUpdate_J10007.java | 407 ++-- .../PatchForHiveServiceDefUpdate_J10009.java | 386 ++-- .../PatchForHiveServiceDefUpdate_J10010.java | 351 +-- .../PatchForHiveServiceDefUpdate_J10017.java | 349 +-- .../PatchForHiveServiceDefUpdate_J10027.java | 418 ++-- .../PatchForHiveServiceDefUpdate_J10030.java | 337 +-- .../PatchForKafkaServiceDefUpdate_J10015.java | 403 ++-- .../PatchForKafkaServiceDefUpdate_J10025.java | 875 +++---- .../PatchForKafkaServiceDefUpdate_J10033.java | 970 ++++---- ...orMigratingOldRegimePolicyJson_J10046.java | 851 +++---- ...MigratingRangerServiceResource_J10037.java | 280 ++- ...chForNifiResourceUpdateExclude_J10011.java | 184 +- ...hForOzoneDefaultPoliciesUpdate_J10044.java | 187 +- ...ForOzoneServiceDefConfigUpdate_J10051.java | 381 ++-- .../PatchForOzoneServiceDefUpdate_J10041.java | 592 ++--- ...tchForPrestoToSupportPresto333_J10038.java | 237 +- .../PatchForServiceVersionInfo_J10004.java | 188 +- ...ForSolrSvcDefAndPoliciesUpdate_J10055.java | 841 +++---- .../PatchForSyncSourceUpdate_J10054.java | 155 +- .../PatchForTagServiceDefUpdate_J10008.java | 341 +-- .../PatchForTagServiceDefUpdate_J10028.java | 559 ++--- .../PatchForTrinoSvcDefUpdate_J10062.java | 217 +- ...atingAtlasSvcDefAndTagPolicies_J10063.java | 416 ++-- .../PatchForUpdatingPolicyJson_J10019.java | 2012 ++++++++--------- .../PatchForUpdatingTagsJson_J10020.java | 214 +- .../patch/PatchForXGlobalState_J10036.java | 131 +- ...ntAuditPermissionToKeyRoleUser_J10014.java | 195 +- .../ranger/patch/PatchMigration_J10002.java | 1008 +++++---- .../patch/PatchPasswordEncryption_J10001.java | 144 +- .../patch/PatchPermissionModel_J10003.java | 348 +-- ...eSql_057_ForUpdateToUniqueGUID_J10052.java | 302 +-- ...dateToUniqueResoureceSignature_J10053.java | 368 +-- .../PatchSetAccessTypeCategory_J10061.java | 39 +- .../PatchTagModulePermission_J10005.java | 204 +- .../patch/cliutil/ChangePasswordUtil.java | 575 ++--- .../patch/cliutil/ChangeUserNameUtil.java | 69 +- .../patch/cliutil/DbToSolrMigrationUtil.java | 937 ++++---- .../ranger/patch/cliutil/MetricUtil.java | 954 ++++---- .../cliutil/RoleBasedUserSearchUtil.java | 492 ++-- .../patch/cliutil/TrxLogV2MigrationUtil.java | 127 +- .../UpdateUserAndGroupNamesInJson.java | 841 +++---- .../security/context/RangerAPIList.java | 457 ++-- .../security/context/RangerAPIMapping.java | 1123 +++++---- .../context/RangerAdminOpContext.java | 31 +- .../security/context/RangerContextHolder.java | 54 +- .../context/RangerPreAuthSecurityHandler.java | 199 +- .../context/RangerSecurityContext.java | 13 +- .../ranger/security/handler/Permission.java | 52 +- .../handler/RangerAuthenticationProvider.java | 1300 +++++------ .../handler/RangerCustomPasswordEncoder.java | 76 +- .../RangerDomainObjectSecurityHandler.java | 133 +- .../listener/RangerHttpSessionListener.java | 40 +- .../listener/SpringEventListener.java | 136 +- .../standalone/StandaloneSecurityHandler.java | 63 +- .../CustomLogoutSuccessHandler.java | 69 +- .../RangerAuthFailureHandler.java | 122 +- .../RangerAuthSuccessHandler.java | 208 +- .../RangerAuthenticationEntryPoint.java | 187 +- ...ngerSessionFixationProtectionStrategy.java | 10 +- .../web/filter/MyRememberMeFilter.java | 61 +- .../filter/RangerCSRFPreventionFilter.java | 403 ++-- .../web/filter/RangerJwtAuthFilter.java | 64 +- .../web/filter/RangerJwtAuthWrapper.java | 49 +- .../filter/RangerKRBAuthenticationFilter.java | 1324 +++++------ .../security/web/filter/RangerKrbFilter.java | 1183 +++++----- .../security/web/filter/RangerMDCFilter.java | 42 +- .../filter/RangerSSOAuthenticationFilter.java | 1100 ++++----- .../RangerSecurityContextFormationFilter.java | 273 +-- ...rUsernamePasswordAuthenticationFilter.java | 20 +- .../web/filter/SSOAuthentication.java | 67 +- .../filter/SSOAuthenticationProperties.java | 14 +- .../service/AbstractBaseResourceService.java | 8 +- .../ranger/solr/SolrAccessAuditsService.java | 489 ++-- .../java/org/apache/ranger/solr/SolrMgr.java | 211 +- .../java/org/apache/ranger/solr/SolrUtil.java | 481 ++-- .../ranger/solr/krb/AbstractKerberosUser.java | 88 +- .../solr/krb/InMemoryJAASConfiguration.java | 164 +- .../ranger/solr/krb/KerberosAction.java | 23 +- .../solr/krb/KerberosJAASConfigUser.java | 26 +- .../apache/ranger/solr/krb/KerberosUser.java | 4 +- .../RangerGdsValidationDBProvider.java | 27 +- .../RangerGdsValidationDataProvider.java | 3 +- .../ranger/validation/RangerGdsValidator.java | 140 +- .../ranger/view/RangerExportPolicyList.java | 23 +- .../ranger/view/RangerExportRoleList.java | 23 +- .../apache/ranger/view/RangerGdsVList.java | 342 +-- .../ranger/view/RangerPluginInfoList.java | 63 +- .../apache/ranger/view/RangerPolicyList.java | 69 +- .../apache/ranger/view/RangerRoleList.java | 17 +- .../ranger/view/RangerSecurityZoneList.java | 66 +- .../ranger/view/RangerServiceDefList.java | 63 +- .../apache/ranger/view/RangerServiceList.java | 63 +- .../RangerServiceResourceWithTagsList.java | 54 +- .../org/apache/ranger/view/VXAccessAudit.java | 1336 +++++------ .../apache/ranger/view/VXAccessAuditList.java | 41 +- .../java/org/apache/ranger/view/VXAsset.java | 330 ++- .../org/apache/ranger/view/VXAssetList.java | 41 +- .../org/apache/ranger/view/VXAuditMap.java | 238 +- .../apache/ranger/view/VXAuditMapList.java | 41 +- .../org/apache/ranger/view/VXAuditRecord.java | 429 ++-- .../apache/ranger/view/VXAuditRecordList.java | 75 +- .../org/apache/ranger/view/VXAuthSession.java | 876 ++++--- .../apache/ranger/view/VXAuthSessionList.java | 41 +- .../apache/ranger/view/VXCredentialStore.java | 130 +- .../ranger/view/VXCredentialStoreList.java | 41 +- .../org/apache/ranger/view/VXDataObject.java | 292 ++- .../ranger/view/VXFileSyncSourceInfo.java | 184 +- .../java/org/apache/ranger/view/VXGroup.java | 391 ++-- .../org/apache/ranger/view/VXGroupGroup.java | 170 +- .../apache/ranger/view/VXGroupGroupList.java | 41 +- .../org/apache/ranger/view/VXGroupList.java | 41 +- .../apache/ranger/view/VXGroupPermission.java | 229 +- .../ranger/view/VXGroupPermissionList.java | 79 +- .../org/apache/ranger/view/VXGroupUser.java | 170 +- .../apache/ranger/view/VXGroupUserInfo.java | 59 +- .../apache/ranger/view/VXGroupUserList.java | 41 +- .../java/org/apache/ranger/view/VXKmsKey.java | 407 ++-- .../org/apache/ranger/view/VXKmsKeyList.java | 41 +- .../ranger/view/VXLdapSyncSourceInfo.java | 285 ++- .../java/org/apache/ranger/view/VXLong.java | 92 +- .../org/apache/ranger/view/VXMessage.java | 280 ++- .../view/VXMetricAuditDetailsCount.java | 214 +- .../ranger/view/VXMetricContextEnricher.java | 89 +- .../ranger/view/VXMetricPolicyCount.java | 86 +- .../VXMetricPolicyWithServiceNameCount.java | 82 +- .../ranger/view/VXMetricServiceCount.java | 84 +- .../ranger/view/VXMetricServiceNameCount.java | 82 +- .../ranger/view/VXMetricUserGroupCount.java | 177 +- .../org/apache/ranger/view/VXModuleDef.java | 298 +-- .../apache/ranger/view/VXModuleDefList.java | 80 +- .../ranger/view/VXModulePermission.java | 82 +- .../ranger/view/VXModulePermissionList.java | 67 +- .../apache/ranger/view/VXPasswordChange.java | 324 ++- .../org/apache/ranger/view/VXPermMap.java | 580 +++-- .../org/apache/ranger/view/VXPermMapList.java | 41 +- .../org/apache/ranger/view/VXPermObj.java | 204 +- .../org/apache/ranger/view/VXPermObjList.java | 82 +- .../java/org/apache/ranger/view/VXPolicy.java | 1128 +++++---- .../ranger/view/VXPolicyExportAudit.java | 509 +++-- .../ranger/view/VXPolicyExportAuditList.java | 41 +- .../org/apache/ranger/view/VXPolicyLabel.java | 52 +- .../apache/ranger/view/VXPolicyLabelList.java | 73 +- .../org/apache/ranger/view/VXPolicyList.java | 82 +- .../org/apache/ranger/view/VXPortalUser.java | 704 +++--- .../apache/ranger/view/VXPortalUserList.java | 41 +- .../org/apache/ranger/view/VXRepository.java | 354 ++- .../apache/ranger/view/VXRepositoryList.java | 82 +- .../org/apache/ranger/view/VXResource.java | 1269 ++++++----- .../apache/ranger/view/VXResourceList.java | 41 +- .../org/apache/ranger/view/VXResponse.java | 264 ++- .../java/org/apache/ranger/view/VXString.java | 92 +- .../org/apache/ranger/view/VXStringList.java | 41 +- .../java/org/apache/ranger/view/VXTrxLog.java | 668 +++--- .../org/apache/ranger/view/VXTrxLogList.java | 44 +- .../org/apache/ranger/view/VXTrxLogV2.java | 702 +++--- .../apache/ranger/view/VXTrxLogV2List.java | 18 +- .../apache/ranger/view/VXUgsyncAuditInfo.java | 244 +- .../ranger/view/VXUgsyncAuditInfoList.java | 36 +- .../ranger/view/VXUnixSyncSourceInfo.java | 244 +- .../java/org/apache/ranger/view/VXUser.java | 620 ++--- .../apache/ranger/view/VXUserGroupInfo.java | 59 +- .../org/apache/ranger/view/VXUserList.java | 41 +- .../apache/ranger/view/VXUserPermission.java | 255 +-- .../ranger/view/VXUserPermissionList.java | 79 +- 195 files changed, 26299 insertions(+), 25088 deletions(-) diff --git a/dev-support/checkstyle-suppressions.xml b/dev-support/checkstyle-suppressions.xml index b68cfc108a..9856e3ca8c 100644 --- a/dev-support/checkstyle-suppressions.xml +++ b/dev-support/checkstyle-suppressions.xml @@ -36,4 +36,53 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/security-admin/src/main/java/javax/ws/rs/core/NoContentException.java b/security-admin/src/main/java/javax/ws/rs/core/NoContentException.java index b9366122d5..2a85d5877e 100644 --- a/security-admin/src/main/java/javax/ws/rs/core/NoContentException.java +++ b/security-admin/src/main/java/javax/ws/rs/core/NoContentException.java @@ -1,4 +1,3 @@ - /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -7,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + *

+ * http://www.apache.org/licenses/LICENSE-2.0 + *

* Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. diff --git a/security-admin/src/main/java/org/apache/ranger/AccessAuditsService.java b/security-admin/src/main/java/org/apache/ranger/AccessAuditsService.java index de1feed55c..9b3a7a3764 100644 --- a/security-admin/src/main/java/org/apache/ranger/AccessAuditsService.java +++ b/security-admin/src/main/java/org/apache/ranger/AccessAuditsService.java @@ -30,83 +30,60 @@ import org.apache.ranger.plugin.store.EmbeddedServiceDefsUtil; import org.springframework.beans.factory.annotation.Autowired; -import java.util.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.List; +import java.util.Map; public class AccessAuditsService { - protected List sortFields = new ArrayList(); - protected List searchFields; + protected List sortFields = new ArrayList<>(); + protected List searchFields = new ArrayList<>(); + @Autowired - protected - RESTErrorUtil restErrorUtil; + protected RESTErrorUtil restErrorUtil; + @Autowired - protected - RangerDaoManager daoManager; + protected RangerDaoManager daoManager; public AccessAuditsService() { - searchFields = new ArrayList(); - searchFields.add(new SearchField("id", "id", - SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.FULL)); - searchFields.add(new SearchField("accessType", "access", - SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.FULL)); - searchFields.add(new SearchField("aclEnforcer", "enforcer", - SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.FULL)); - searchFields.add(new SearchField("agentId", "agent", - SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.FULL)); - searchFields.add(new SearchField("repoName", "repo", - SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.FULL)); - searchFields.add(new SearchField("sessionId", "sess", - SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.FULL)); - searchFields.add(new SearchField("requestUser", "reqUser", - SearchField.DATA_TYPE.STR_LIST, SearchField.SEARCH_TYPE.FULL)); - searchFields.add(new SearchField("excludeUser", "exlUser", - SearchField.DATA_TYPE.STR_LIST, SearchField.SEARCH_TYPE.FULL)); - searchFields.add(new SearchField("requestData", "reqData", SearchField.DATA_TYPE.STRING, - SearchField.SEARCH_TYPE.PARTIAL)); - searchFields.add(new SearchField("resourcePath", "resource", SearchField.DATA_TYPE.STRING, - SearchField.SEARCH_TYPE.PARTIAL)); - searchFields.add(new SearchField("clientIP", "cliIP", - SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.FULL)); - - searchFields.add(new SearchField("auditType", "logType", - SearchField.DATA_TYPE.INTEGER, SearchField.SEARCH_TYPE.FULL)); - searchFields.add(new SearchField("accessResult", "result", - SearchField.DATA_TYPE.INTEGER, SearchField.SEARCH_TYPE.FULL)); + searchFields.add(new SearchField("id", "id", SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.FULL)); + searchFields.add(new SearchField("accessType", "access", SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.FULL)); + searchFields.add(new SearchField("aclEnforcer", "enforcer", SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.FULL)); + searchFields.add(new SearchField("agentId", "agent", SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.FULL)); + searchFields.add(new SearchField("repoName", "repo", SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.FULL)); + searchFields.add(new SearchField("sessionId", "sess", SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.FULL)); + searchFields.add(new SearchField("requestUser", "reqUser", SearchField.DATA_TYPE.STR_LIST, SearchField.SEARCH_TYPE.FULL)); + searchFields.add(new SearchField("excludeUser", "exlUser", SearchField.DATA_TYPE.STR_LIST, SearchField.SEARCH_TYPE.FULL)); + searchFields.add(new SearchField("requestData", "reqData", SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.PARTIAL)); + searchFields.add(new SearchField("resourcePath", "resource", SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.PARTIAL)); + searchFields.add(new SearchField("clientIP", "cliIP", SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.FULL)); + + searchFields.add(new SearchField("auditType", "logType", SearchField.DATA_TYPE.INTEGER, SearchField.SEARCH_TYPE.FULL)); + searchFields.add(new SearchField("accessResult", "result", 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", "policy", - SearchField.DATA_TYPE.INTEGER, SearchField.SEARCH_TYPE.FULL)); - searchFields.add(new SearchField("repoType", "repoType", - SearchField.DATA_TYPE.INTEGER, SearchField.SEARCH_TYPE.FULL)); + searchFields.add(new SearchField("policyId", "policy", SearchField.DATA_TYPE.INTEGER, SearchField.SEARCH_TYPE.FULL)); + searchFields.add(new SearchField("repoType", "repoType", SearchField.DATA_TYPE.INTEGER, SearchField.SEARCH_TYPE.FULL)); /* Note; search fields starting with '-' denotes exclude conditions, * it should be handled manually if audit destination does not support the same. * solr support this way while cloudwatch does not. */ - searchFields.add(new SearchField("-repoType", "-repoType", - SearchField.DATA_TYPE.INTEGER, SearchField.SEARCH_TYPE.FULL)); - searchFields.add(new SearchField("-requestUser", "-reqUser", - SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.FULL)); - searchFields.add(new SearchField("resourceType", "resType", - SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.FULL)); - searchFields.add(new SearchField("reason", "reason", - SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.FULL)); - searchFields.add(new SearchField("action", "action", - SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.FULL)); - - searchFields.add(new SearchField("startDate", "evtTime", - SearchField.DATA_TYPE.DATE, SearchField.SEARCH_TYPE.GREATER_EQUAL_THAN)); - searchFields.add(new SearchField("endDate", "evtTime", SearchField.DATA_TYPE.DATE, - SearchField.SEARCH_TYPE.LESS_EQUAL_THAN)); + searchFields.add(new SearchField("-repoType", "-repoType", SearchField.DATA_TYPE.INTEGER, SearchField.SEARCH_TYPE.FULL)); + searchFields.add(new SearchField("-requestUser", "-reqUser", SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.FULL)); + searchFields.add(new SearchField("resourceType", "resType", SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.FULL)); + searchFields.add(new SearchField("reason", "reason", SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.FULL)); + searchFields.add(new SearchField("action", "action", SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.FULL)); + + searchFields.add(new SearchField("startDate", "evtTime", SearchField.DATA_TYPE.DATE, SearchField.SEARCH_TYPE.GREATER_EQUAL_THAN)); + searchFields.add(new SearchField("endDate", "evtTime", SearchField.DATA_TYPE.DATE, SearchField.SEARCH_TYPE.LESS_EQUAL_THAN)); searchFields.add(new SearchField("tags", "tags", SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.PARTIAL)); - searchFields.add(new SearchField("cluster", "cluster", - SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.FULL)); - searchFields.add(new SearchField("zoneName", "zoneName", - SearchField.DATA_TYPE.STR_LIST, SearchField.SEARCH_TYPE.FULL)); - searchFields.add(new SearchField("agentHost", "agentHost", - SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.PARTIAL)); - - sortFields.add(new SortField("eventTime", "evtTime", true, - SortField.SORT_ORDER.DESC)); + searchFields.add(new SearchField("cluster", "cluster", SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.FULL)); + searchFields.add(new SearchField("zoneName", "zoneName", SearchField.DATA_TYPE.STR_LIST, SearchField.SEARCH_TYPE.FULL)); + searchFields.add(new SearchField("agentHost", "agentHost", SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.PARTIAL)); + + sortFields.add(new SortField("eventTime", "evtTime", true, SortField.SORT_ORDER.DESC)); sortFields.add(new SortField("policyId", "policy", false, SORT_ORDER.ASC)); sortFields.add(new SortField("requestUser", "reqUser", false, SORT_ORDER.ASC)); sortFields.add(new SortField("resourceType", "resType", false, SORT_ORDER.ASC)); @@ -120,13 +97,16 @@ public AccessAuditsService() { protected void updateUserExclusion(Map paramList) { String val = (String) paramList.get("excludeServiceUser"); - if (val != null && Boolean.valueOf(val.trim())) { + if (val != null && Boolean.parseBoolean(val.trim())) { // add param to negate requestUsers which will be added as filter query List excludeUsersList = getExcludeUsersList(); + if (CollectionUtils.isNotEmpty(excludeUsersList)) { Object oldUserExclusions = paramList.get("-requestUser"); - if (oldUserExclusions instanceof Collection && (!((Collection)oldUserExclusions).isEmpty())) { - excludeUsersList.addAll((Collection)oldUserExclusions); + + if (oldUserExclusions instanceof Collection && (!((Collection) oldUserExclusions).isEmpty())) { + excludeUsersList.addAll((Collection) oldUserExclusions); + paramList.put("-requestUser", excludeUsersList); } else { paramList.put("-requestUser", excludeUsersList); @@ -137,32 +117,38 @@ protected void updateUserExclusion(Map paramList) { private List getExcludeUsersList() { //for excluding serviceUsers using existing property in ranger-admin-site - List excludeUsersList = new ArrayList(getServiceUserList()); + List excludeUsersList = new ArrayList<>(getServiceUserList()); //for excluding additional users using new property in ranger-admin-site - String additionalExcludeUsers = PropertiesUtil.getProperty("ranger.accesslogs.exclude.users.list"); - List additionalExcludeUsersList = null; + String additionalExcludeUsers = PropertiesUtil.getProperty("ranger.accesslogs.exclude.users.list"); + List additionalExcludeUsersList; + if (StringUtils.isNotBlank(additionalExcludeUsers)) { additionalExcludeUsersList = new ArrayList<>(Arrays.asList(StringUtils.split(additionalExcludeUsers, ","))); + for (String serviceUser : additionalExcludeUsersList) { if (StringUtils.isNotBlank(serviceUser) && !excludeUsersList.contains(serviceUser.trim())) { excludeUsersList.add(serviceUser); } } } + return excludeUsersList; } private List getServiceUserList() { - String components = EmbeddedServiceDefsUtil.DEFAULT_BOOTSTRAP_SERVICEDEF_LIST; - List serviceUsersList = new ArrayList(); - List componentNames = Arrays.asList(StringUtils.split(components,",")); - for(String componentName : componentNames) { - String serviceUser = PropertiesUtil.getProperty("ranger.plugins."+componentName+".serviceuser"); - if(StringUtils.isNotBlank(serviceUser)) { + String components = EmbeddedServiceDefsUtil.DEFAULT_BOOTSTRAP_SERVICEDEF_LIST; + List serviceUsersList = new ArrayList<>(); + String[] componentNames = StringUtils.split(components, ","); + + for (String componentName : componentNames) { + String serviceUser = PropertiesUtil.getProperty("ranger.plugins." + componentName + ".serviceuser"); + + if (StringUtils.isNotBlank(serviceUser)) { serviceUsersList.add(serviceUser); } } + return serviceUsersList; } } diff --git a/security-admin/src/main/java/org/apache/ranger/json/Folder.java b/security-admin/src/main/java/org/apache/ranger/json/Folder.java index 2717b3350d..b1e628ebd0 100644 --- a/security-admin/src/main/java/org/apache/ranger/json/Folder.java +++ b/security-admin/src/main/java/org/apache/ranger/json/Folder.java @@ -17,27 +17,27 @@ * under the License. */ - package org.apache.ranger.json; +package org.apache.ranger.json; import java.util.List; public class Folder { + String name; + List folders; - String name; - List folders; - - - public String getName() { - return name; - } - public void setName(String name) { - this.name = name; - } - public List getFolders() { - return folders; - } - public void setFolders(List folders) { - this.folders = folders; - } - + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public List getFolders() { + return folders; + } + + public void setFolders(List folders) { + this.folders = folders; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/json/JsonDateSerializer.java b/security-admin/src/main/java/org/apache/ranger/json/JsonDateSerializer.java index 0317deb4c6..103b2f4121 100644 --- a/security-admin/src/main/java/org/apache/ranger/json/JsonDateSerializer.java +++ b/security-admin/src/main/java/org/apache/ranger/json/JsonDateSerializer.java @@ -17,34 +17,29 @@ * under the License. */ - package org.apache.ranger.json; - -import java.io.IOException; -import java.text.SimpleDateFormat; -import java.util.Date; +package org.apache.ranger.json; import com.fasterxml.jackson.core.JsonGenerator; -import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.SerializerProvider; import org.springframework.stereotype.Component; +import java.io.IOException; +import java.text.SimpleDateFormat; +import java.util.Date; + /** * 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 { + private static final String DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss'Z'"; - private static final String DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss'Z'"; - @Override - public void serialize(Date date, JsonGenerator gen, - SerializerProvider provider) throws IOException, - JsonProcessingException { - - String formattedDate = new SimpleDateFormat(DATE_FORMAT).format(date); - gen.writeString(formattedDate); - } + @Override + public void serialize(Date date, JsonGenerator gen, SerializerProvider provider) throws IOException { + String formattedDate = new SimpleDateFormat(DATE_FORMAT).format(date); + gen.writeString(formattedDate); + } } diff --git a/security-admin/src/main/java/org/apache/ranger/metrics/RangerAdminMetricsWrapper.java b/security-admin/src/main/java/org/apache/ranger/metrics/RangerAdminMetricsWrapper.java index b1f1dc8b9f..7fe5f1b7c0 100644 --- a/security-admin/src/main/java/org/apache/ranger/metrics/RangerAdminMetricsWrapper.java +++ b/security-admin/src/main/java/org/apache/ranger/metrics/RangerAdminMetricsWrapper.java @@ -19,13 +19,6 @@ package org.apache.ranger.metrics; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Map; - -import javax.annotation.PostConstruct; - import org.apache.ranger.metrics.source.RangerAdminMetricsSourceContextEnricher; import org.apache.ranger.metrics.source.RangerAdminMetricsSourceDenyConditions; import org.apache.ranger.metrics.source.RangerAdminMetricsSourcePolicyMasking; @@ -39,9 +32,17 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; +import javax.annotation.PostConstruct; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; + @Component public class RangerAdminMetricsWrapper { - private static final Logger LOG = LoggerFactory.getLogger(RangerAdminMetricsWrapper.class); + private static final Logger LOG= LoggerFactory.getLogger(RangerAdminMetricsWrapper.class); + private static final String context = "admin"; private final RangerMetricsSystemWrapper rangerMetricsSystemWrapper = new RangerMetricsSystemWrapper(); @@ -70,6 +71,7 @@ public class RangerAdminMetricsWrapper { @PostConstruct public void init() { LOG.info("===>> RangerAdminMetricsWrapper.init()"); + try { //Source List sourceWrappers = new ArrayList<>(); diff --git a/security-admin/src/main/java/org/apache/ranger/metrics/RangerMetricsFetcher.java b/security-admin/src/main/java/org/apache/ranger/metrics/RangerMetricsFetcher.java index 867b70e91c..975f4e07de 100644 --- a/security-admin/src/main/java/org/apache/ranger/metrics/RangerMetricsFetcher.java +++ b/security-admin/src/main/java/org/apache/ranger/metrics/RangerMetricsFetcher.java @@ -19,10 +19,6 @@ package org.apache.ranger.metrics; -import java.util.HashMap; -import java.util.Map; -import java.util.Objects; - import org.apache.ranger.biz.ServiceDBStore; import org.apache.ranger.biz.XUserMgr; import org.apache.ranger.common.RangerConstants; @@ -34,6 +30,11 @@ import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; +import java.util.HashMap; +import java.util.Map; + +import static java.util.Objects.requireNonNull; + @Service @Transactional(propagation = Propagation.REQUIRES_NEW) public class RangerMetricsFetcher { @@ -51,72 +52,99 @@ public class RangerMetricsFetcher { public Long getGroupCount() { return groupService.getAllGroupCount(); } + public Map getUserMetrics() { + Map ret = new HashMap<>(); + long total = 0L; - Map ret = new HashMap<>(); - long total = 0l; for (Map.Entry entry : xUserMgr.getUserCountByRole().entrySet()) { String role = entry.getKey(); switch (role) { - case RangerConstants.ROLE_SYS_ADMIN: ret.put("SysAdmin", entry.getValue()); break; - case RangerConstants.ROLE_ADMIN_AUDITOR: ret.put("AdminAuditor", entry.getValue()); break; - case RangerConstants.ROLE_KEY_ADMIN: ret.put("KeyAdmin", entry.getValue()); break; - case RangerConstants.ROLE_KEY_ADMIN_AUDITOR: ret.put("KeyAdminAuditor", entry.getValue()); break; - case RangerConstants.ROLE_USER: ret.put("User", entry.getValue()); break; - default: LOG.warn("===>> RangerMetricsFetcher.getUserMetrics(): invalid role [{}] type.", role);break; + case RangerConstants.ROLE_SYS_ADMIN: + ret.put("SysAdmin", entry.getValue()); + break; + case RangerConstants.ROLE_ADMIN_AUDITOR: + ret.put("AdminAuditor", entry.getValue()); + break; + case RangerConstants.ROLE_KEY_ADMIN: + ret.put("KeyAdmin", entry.getValue()); + break; + case RangerConstants.ROLE_KEY_ADMIN_AUDITOR: + ret.put("KeyAdminAuditor", entry.getValue()); + break; + case RangerConstants.ROLE_USER: + ret.put("User", entry.getValue()); + break; + default: + LOG.warn("===>> RangerMetricsFetcher.getUserMetrics(): invalid role [{}] type.", role); + break; } - total += entry.getValue().longValue(); + + total += entry.getValue(); } + ret.put("Total", total); return ret; } public Map getRangerServiceMetrics() { - Map ret = new HashMap<>(); - long total = 0l; + Map ret = new HashMap<>(); + long total = 0L; + for (Map.Entry entry : svcStore.getServiceCountByType().entrySet()) { ret.put(entry.getKey(), entry.getValue()); - total += entry.getValue().longValue(); + + total += entry.getValue(); } + ret.put("Total", total); return ret; } public Map getPolicyMetrics(Integer policyType) { - Objects.requireNonNull(policyType, "Policy type must not be null to get policy metrics."); + requireNonNull(policyType, "Policy type must not be null to get policy metrics."); + + Map ret = new HashMap<>(); + long total = 0L; - Map ret = new HashMap<>(); - long total = 0l; for (Map.Entry entry : svcStore.getPolicyCountByTypeAndServiceType(policyType).entrySet()) { ret.put(entry.getKey(), entry.getValue()); - total += entry.getValue().longValue(); + + total += entry.getValue(); } + ret.put("Total", total); return ret; } public Map getDenyConditionsMetrics() { - Map ret = new HashMap<>(); - long total = 0l; + Map ret = new HashMap<>(); + long total = 0L; + for (Map.Entry entry : svcStore.getPolicyCountByDenyConditionsAndServiceDef().entrySet()) { ret.put(entry.getKey(), entry.getValue()); - total += entry.getValue().longValue(); + + total += entry.getValue(); } + ret.put("Total", total); return ret; } public Map getContextEnrichersMetrics() { - Map ret = new HashMap<>(); - long total = 0l; + Map ret = new HashMap<>(); + long total = 0L; + for (String serviceDef : svcStore.findAllServiceDefNamesHavingContextEnrichers()) { - ret.put(serviceDef, 1l); + ret.put(serviceDef, 1L); + total++; } + ret.put("Total", total); return ret; diff --git a/security-admin/src/main/java/org/apache/ranger/metrics/source/RangerAdminMetricsSourceBase.java b/security-admin/src/main/java/org/apache/ranger/metrics/source/RangerAdminMetricsSourceBase.java index effa98c0f3..1b790403c5 100644 --- a/security-admin/src/main/java/org/apache/ranger/metrics/source/RangerAdminMetricsSourceBase.java +++ b/security-admin/src/main/java/org/apache/ranger/metrics/source/RangerAdminMetricsSourceBase.java @@ -17,11 +17,7 @@ * under the License. */ -package org.apache.ranger.metrics.source; - -import java.util.HashMap; -import java.util.Map; -import java.util.Objects; +package org.apache.ranger.metrics.source; import org.apache.hadoop.metrics2.MetricsCollector; import org.apache.hadoop.metrics2.MetricsRecordBuilder; @@ -29,6 +25,10 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; + public abstract class RangerAdminMetricsSourceBase extends RangerMetricsSource { private static final Logger LOG = LoggerFactory.getLogger(RangerAdminMetricsSourceBase.class); @@ -44,10 +44,9 @@ public RangerAdminMetricsSourceBase(String context, String record) { @Override protected void update(MetricsCollector collector, boolean all) { - MetricsRecordBuilder builder = collector.addRecord(this.record) - .setContext(this.context); + MetricsRecordBuilder builder = collector.addRecord(this.record).setContext(this.context); - for (String key: metricsMap.keySet() ) { + for (String key : metricsMap.keySet()) { builder.addGauge(new RangerMetricsInfo(key, ""), metricsMap.get(key)); } } diff --git a/security-admin/src/main/java/org/apache/ranger/metrics/source/RangerAdminMetricsSourceContextEnricher.java b/security-admin/src/main/java/org/apache/ranger/metrics/source/RangerAdminMetricsSourceContextEnricher.java index 69d54d64b9..d90ce6fc32 100644 --- a/security-admin/src/main/java/org/apache/ranger/metrics/source/RangerAdminMetricsSourceContextEnricher.java +++ b/security-admin/src/main/java/org/apache/ranger/metrics/source/RangerAdminMetricsSourceContextEnricher.java @@ -19,15 +19,14 @@ package org.apache.ranger.metrics.source; -import java.util.Map; - import org.apache.ranger.metrics.RangerMetricsFetcher; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; +import java.util.Map; + @Component public class RangerAdminMetricsSourceContextEnricher extends RangerAdminMetricsSourceBase { - @Autowired private RangerMetricsFetcher rangerMetricsFetcher; @@ -38,6 +37,7 @@ public RangerAdminMetricsSourceContextEnricher() { @Override protected void refresh() { Map contextEnrichersMetrics = rangerMetricsFetcher.getContextEnrichersMetrics(); + addMetricEntries("ContextEnricherCount", contextEnrichersMetrics); } } diff --git a/security-admin/src/main/java/org/apache/ranger/metrics/source/RangerAdminMetricsSourceDenyConditions.java b/security-admin/src/main/java/org/apache/ranger/metrics/source/RangerAdminMetricsSourceDenyConditions.java index 22095f2f78..4314f3df52 100644 --- a/security-admin/src/main/java/org/apache/ranger/metrics/source/RangerAdminMetricsSourceDenyConditions.java +++ b/security-admin/src/main/java/org/apache/ranger/metrics/source/RangerAdminMetricsSourceDenyConditions.java @@ -19,15 +19,14 @@ package org.apache.ranger.metrics.source; -import java.util.Map; - import org.apache.ranger.metrics.RangerMetricsFetcher; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; +import java.util.Map; + @Component public class RangerAdminMetricsSourceDenyConditions extends RangerAdminMetricsSourceBase { - @Autowired private RangerMetricsFetcher rangerMetricsFetcher; @@ -38,6 +37,7 @@ public RangerAdminMetricsSourceDenyConditions() { @Override protected void refresh() { Map denyConditionsMetrics = rangerMetricsFetcher.getDenyConditionsMetrics(); + addMetricEntries("DenyConditionCount", denyConditionsMetrics); } } diff --git a/security-admin/src/main/java/org/apache/ranger/metrics/source/RangerAdminMetricsSourcePolicyMasking.java b/security-admin/src/main/java/org/apache/ranger/metrics/source/RangerAdminMetricsSourcePolicyMasking.java index 7df64c6f16..958c8ce686 100644 --- a/security-admin/src/main/java/org/apache/ranger/metrics/source/RangerAdminMetricsSourcePolicyMasking.java +++ b/security-admin/src/main/java/org/apache/ranger/metrics/source/RangerAdminMetricsSourcePolicyMasking.java @@ -19,16 +19,15 @@ package org.apache.ranger.metrics.source; -import java.util.Map; - import org.apache.ranger.metrics.RangerMetricsFetcher; import org.apache.ranger.plugin.model.RangerPolicy; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; +import java.util.Map; + @Component public class RangerAdminMetricsSourcePolicyMasking extends RangerAdminMetricsSourceBase { - @Autowired private RangerMetricsFetcher rangerMetricsFetcher; @@ -39,6 +38,7 @@ public RangerAdminMetricsSourcePolicyMasking() { @Override protected void refresh() { Map maskingPolicyMetrics = rangerMetricsFetcher.getPolicyMetrics(RangerPolicy.POLICY_TYPE_DATAMASK); + addMetricEntries("MaskingCount", maskingPolicyMetrics); } } diff --git a/security-admin/src/main/java/org/apache/ranger/metrics/source/RangerAdminMetricsSourcePolicyResourceAccess.java b/security-admin/src/main/java/org/apache/ranger/metrics/source/RangerAdminMetricsSourcePolicyResourceAccess.java index 4a777f86d2..7d66a0189f 100644 --- a/security-admin/src/main/java/org/apache/ranger/metrics/source/RangerAdminMetricsSourcePolicyResourceAccess.java +++ b/security-admin/src/main/java/org/apache/ranger/metrics/source/RangerAdminMetricsSourcePolicyResourceAccess.java @@ -19,16 +19,15 @@ package org.apache.ranger.metrics.source; -import java.util.Map; - import org.apache.ranger.metrics.RangerMetricsFetcher; import org.apache.ranger.plugin.model.RangerPolicy; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; +import java.util.Map; + @Component public class RangerAdminMetricsSourcePolicyResourceAccess extends RangerAdminMetricsSourceBase { - @Autowired private RangerMetricsFetcher rangerMetricsFetcher; @@ -39,7 +38,7 @@ public RangerAdminMetricsSourcePolicyResourceAccess() { @Override protected void refresh() { Map accessPolicyMetrics = rangerMetricsFetcher.getPolicyMetrics(RangerPolicy.POLICY_TYPE_ACCESS); + addMetricEntries("ResourceAccessCount", accessPolicyMetrics); } - } diff --git a/security-admin/src/main/java/org/apache/ranger/metrics/source/RangerAdminMetricsSourcePolicyRowFiltering.java b/security-admin/src/main/java/org/apache/ranger/metrics/source/RangerAdminMetricsSourcePolicyRowFiltering.java index af6eb502a3..9e2b0409c2 100644 --- a/security-admin/src/main/java/org/apache/ranger/metrics/source/RangerAdminMetricsSourcePolicyRowFiltering.java +++ b/security-admin/src/main/java/org/apache/ranger/metrics/source/RangerAdminMetricsSourcePolicyRowFiltering.java @@ -19,16 +19,15 @@ package org.apache.ranger.metrics.source; -import java.util.Map; - import org.apache.ranger.metrics.RangerMetricsFetcher; import org.apache.ranger.plugin.model.RangerPolicy; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; +import java.util.Map; + @Component public class RangerAdminMetricsSourcePolicyRowFiltering extends RangerAdminMetricsSourceBase { - @Autowired private RangerMetricsFetcher rangerMetricsFetcher; @@ -39,6 +38,7 @@ public RangerAdminMetricsSourcePolicyRowFiltering() { @Override protected void refresh() { Map rowFilteringPolicyMetrics = rangerMetricsFetcher.getPolicyMetrics(RangerPolicy.POLICY_TYPE_ROWFILTER); + addMetricEntries("RowFilteringCount", rowFilteringPolicyMetrics); } } diff --git a/security-admin/src/main/java/org/apache/ranger/metrics/source/RangerAdminMetricsSourceService.java b/security-admin/src/main/java/org/apache/ranger/metrics/source/RangerAdminMetricsSourceService.java index 23750e672f..724897e276 100644 --- a/security-admin/src/main/java/org/apache/ranger/metrics/source/RangerAdminMetricsSourceService.java +++ b/security-admin/src/main/java/org/apache/ranger/metrics/source/RangerAdminMetricsSourceService.java @@ -19,15 +19,14 @@ package org.apache.ranger.metrics.source; -import java.util.Map; - import org.apache.ranger.metrics.RangerMetricsFetcher; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; +import java.util.Map; + @Component public class RangerAdminMetricsSourceService extends RangerAdminMetricsSourceBase { - @Autowired private RangerMetricsFetcher rangerMetricsFetcher; @@ -38,6 +37,7 @@ public RangerAdminMetricsSourceService() { @Override protected void refresh() { Map serviceMetrics = rangerMetricsFetcher.getRangerServiceMetrics(); + addMetricEntries("ServiceCount", serviceMetrics); } } diff --git a/security-admin/src/main/java/org/apache/ranger/metrics/source/RangerAdminMetricsSourceUserGroup.java b/security-admin/src/main/java/org/apache/ranger/metrics/source/RangerAdminMetricsSourceUserGroup.java index 2ed6f9db6b..d2d3b98317 100644 --- a/security-admin/src/main/java/org/apache/ranger/metrics/source/RangerAdminMetricsSourceUserGroup.java +++ b/security-admin/src/main/java/org/apache/ranger/metrics/source/RangerAdminMetricsSourceUserGroup.java @@ -19,17 +19,17 @@ package org.apache.ranger.metrics.source; -import java.util.Map; - import org.apache.ranger.metrics.RangerMetricsFetcher; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; +import java.util.Map; + @Component public class RangerAdminMetricsSourceUserGroup extends RangerAdminMetricsSourceBase { - @Autowired private RangerMetricsFetcher rangerMetricsFetcher; + public RangerAdminMetricsSourceUserGroup() { super("admin", "UserGroup"); } diff --git a/security-admin/src/main/java/org/apache/ranger/patch/BaseLoader.java b/security-admin/src/main/java/org/apache/ranger/patch/BaseLoader.java index 9b52e4a7d6..456f2b8036 100644 --- a/security-admin/src/main/java/org/apache/ranger/patch/BaseLoader.java +++ b/security-admin/src/main/java/org/apache/ranger/patch/BaseLoader.java @@ -17,13 +17,11 @@ * under the License. */ - /** +/** * */ package org.apache.ranger.patch; -import java.text.DecimalFormat; - import org.apache.ranger.authorization.hadoop.config.RangerAdminConfig; import org.apache.ranger.common.DateUtil; import org.apache.ranger.util.CLIUtil; @@ -32,176 +30,190 @@ import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; +import java.text.DecimalFormat; + /** - * * */ public abstract class BaseLoader { - private static final Logger logger = LoggerFactory.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"); + private static final Logger logger = LoggerFactory.getLogger(BaseLoader.class); + protected final RangerAdminConfig config; + long startTime = DateUtil.getUTCDate().getTime(); + long lastTime = startTime; + int countSoFar; + int countFromLastTime; + boolean moreToProcess = true; + boolean firstCall = true; + int batchSize = -1; + DecimalFormat twoDForm = new DecimalFormat("#.00"); + public BaseLoader() { this.config = RangerAdminConfig.getInstance(); } public void init(int batchSize) throws Exception { - this.batchSize = batchSize; - CLIUtil cliUtil = (CLIUtil) CLIUtil.getBean(CLIUtil.class); - cliUtil.authenticate(); + this.batchSize = batchSize; + + CLIUtil cliUtil = (CLIUtil) CLIUtil.getBean(CLIUtil.class); + + cliUtil.authenticate(); } public void init() throws Exception { - init(-1); + init(-1); } - abstract public void printStats(); + public abstract void printStats(); public abstract void execLoad(); public void onExit() { - logger.info("onExit()"); + logger.info("onExit()"); } /** * @return the moreToProcess */ public boolean isMoreToProcess() { - return moreToProcess; + return moreToProcess; } /** - * @param moreToProcess - * the moreToProcess to set + * @param moreToProcess the moreToProcess to set */ public void setMoreToProcess(boolean moreToProcess) { - this.moreToProcess = 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(); - } - - } + 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={} for {}", formatTimeTaken(endTime - startTime), 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(); - + 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 = (double)(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; - } + countSoFar = lineCount; - 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; + long currTime = DateUtil.getUTCDate().getTime(); + String retStr = formatTimeTaken(currTime - startTime); + + if (currTime - startTime > 0 && countSoFar > 0) { + double rateSoFar = (double) (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; } protected void print(int count, String message) { - if (count > 0) { - logger.info(message.trim() + " : " + count); - } + if (count > 0) { + logger.info("{} : {}", message.trim(), count); + } + } + + 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; } } diff --git a/security-admin/src/main/java/org/apache/ranger/patch/PatchAssignSecurityZonePersmissionToAdmin_J10026.java b/security-admin/src/main/java/org/apache/ranger/patch/PatchAssignSecurityZonePersmissionToAdmin_J10026.java index a0b406bdb5..842ffead83 100644 --- a/security-admin/src/main/java/org/apache/ranger/patch/PatchAssignSecurityZonePersmissionToAdmin_J10026.java +++ b/security-admin/src/main/java/org/apache/ranger/patch/PatchAssignSecurityZonePersmissionToAdmin_J10026.java @@ -17,16 +17,6 @@ package org.apache.ranger.patch; -import java.io.IOException; -import java.nio.charset.Charset; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; - import org.apache.commons.lang.StringUtils; import org.apache.ranger.biz.XUserMgr; import org.apache.ranger.common.RangerConstants; @@ -41,163 +31,203 @@ import org.springframework.stereotype.Component; import org.springframework.util.CollectionUtils; +import java.io.IOException; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + @Component public class PatchAssignSecurityZonePersmissionToAdmin_J10026 extends BaseLoader { + private static final Logger logger = LoggerFactory.getLogger(PatchAssignSecurityZonePersmissionToAdmin_J10026.class); + + private static final Charset ENCODING = StandardCharsets.UTF_8; + private static boolean grantAllUsers; + private static String usersListFileName; + + @Autowired + RangerDaoManager daoManager; + + @Autowired + XUserMgr xUserMgr; + + @Autowired + XPortalUserService xPortalUserService; + + public static void main(String[] args) { + logger.info("main()"); + + try { + if (args != null && args.length > 0) { + if (StringUtils.equalsIgnoreCase("ALL", args[0])) { + grantAllUsers = true; + } else if (!StringUtils.isEmpty(args[0])) { + usersListFileName = args[0]; + } + } + + PatchAssignSecurityZonePersmissionToAdmin_J10026 loader = (PatchAssignSecurityZonePersmissionToAdmin_J10026) CLIUtil.getBean(PatchAssignSecurityZonePersmissionToAdmin_J10026.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); + } + } + + @Override + public void init() throws Exception { + // Do Nothing + } + + @Override + public void printStats() { + // Do Nothing + } + + @Override + public void execLoad() { + logger.info("==> PatchAssignSecurityZonePersmissionToAdmin_J10026.execLoad() started"); + assignSecurityZonePermissionToExistingAdminUsers(); + logger.info("<== PatchAssignSecurityZonePersmissionToAdmin_J10026.execLoad() completed"); + } + + private void assignSecurityZonePermissionToExistingAdminUsers() { + Long userCount = daoManager.getXXPortalUser().getAllCount(); + Long patchModeMaxLimit = 500L; + int countUserPermissionUpdated; + List xXPortalUsers; + + try { + if (userCount != null && userCount > 0) { + List loginIdList = readUserNamesFromFile(usersListFileName); + + if (!CollectionUtils.isEmpty(loginIdList)) { + xXPortalUsers = new ArrayList<>(); + + XXPortalUser xXPortalUser; - private static final Logger logger = LoggerFactory.getLogger(PatchAssignSecurityZonePersmissionToAdmin_J10026.class); - - @Autowired - RangerDaoManager daoManager; - - @Autowired - XUserMgr xUserMgr; - - @Autowired - XPortalUserService xPortalUserService; - - private static boolean grantAllUsers=false; - private static String usersListFileName=null; - private final static Charset ENCODING = StandardCharsets.UTF_8; - public static void main(String[] args) { - logger.info("main()"); - try { - if(args!=null && args.length>0){ - if(StringUtils.equalsIgnoreCase("ALL", args[0])){ - grantAllUsers=true; - }else if(!StringUtils.isEmpty(args[0])){ - usersListFileName=args[0]; - } - } - PatchAssignSecurityZonePersmissionToAdmin_J10026 loader = (PatchAssignSecurityZonePersmissionToAdmin_J10026) CLIUtil - .getBean(PatchAssignSecurityZonePersmissionToAdmin_J10026.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); - } - } - - - @Override - public void init() throws Exception { - // Do Nothing - } - - @Override - public void printStats() { - // Do Nothing - } - - @Override - public void execLoad() { - logger.info("==> PatchAssignSecurityZonePersmissionToAdmin_J10026.execLoad() started"); - assignSecurityZonePermissionToExistingAdminUsers(); - logger.info("<== PatchAssignSecurityZonePersmissionToAdmin_J10026.execLoad() completed"); - - } - - private void assignSecurityZonePermissionToExistingAdminUsers() { - int countUserPermissionUpdated = 0; - Long userCount=daoManager.getXXPortalUser().getAllCount(); - List xXPortalUsers=null; - Long patchModeMaxLimit=Long.valueOf(500L); - try{ - if (userCount!=null && userCount>0){ - List loginIdList=readUserNamesFromFile(usersListFileName); - if(!CollectionUtils.isEmpty(loginIdList)){ - xXPortalUsers=new ArrayList(); - XXPortalUser xXPortalUser=null; - for(String loginId:loginIdList){ - try{ - xXPortalUser=daoManager.getXXPortalUser().findByLoginId(loginId); - if(xXPortalUser!=null){ - xXPortalUsers.add(xXPortalUser); - }else{ - logger.info("User "+loginId+" doesn't exist!"); - } - }catch(Exception ex){ - } - } - countUserPermissionUpdated=assignPermissions(xXPortalUsers); - logger.info("Security Zone Permissions assigned to "+countUserPermissionUpdated + " of total "+loginIdList.size()); - } else { - xXPortalUsers=daoManager.getXXPortalUser().findByRole(RangerConstants.ROLE_SYS_ADMIN); - if(!CollectionUtils.isEmpty(xXPortalUsers)){ - countUserPermissionUpdated=assignPermissions(xXPortalUsers); - logger.info("Security Zone Permissions assigned to users having role:"+RangerConstants.ROLE_SYS_ADMIN+". Processed:"+countUserPermissionUpdated + " of total "+xXPortalUsers.size()); - } - xXPortalUsers=daoManager.getXXPortalUser().findByRole(RangerConstants.ROLE_ADMIN_AUDITOR); - if(!CollectionUtils.isEmpty(xXPortalUsers)){ - countUserPermissionUpdated=assignPermissions(xXPortalUsers); - logger.info("Security Zone Permissions assigned to users having role:"+RangerConstants.ROLE_ADMIN_AUDITOR+". Processed:"+countUserPermissionUpdated + " of total "+xXPortalUsers.size()); - } - //if total no. of users are more than 500 then process ADMIN and KEY_ADMIN users only to avoid timeout - if(userCount.compareTo(Long.valueOf(patchModeMaxLimit))<0 || grantAllUsers){ - xXPortalUsers=daoManager.getXXPortalUser().findByRole(RangerConstants.ROLE_USER); - if(!CollectionUtils.isEmpty(xXPortalUsers)){ - countUserPermissionUpdated=assignPermissions(xXPortalUsers); - logger.info("Security Zone Permissions assigned to "+countUserPermissionUpdated + " of total "+xXPortalUsers.size()); - } - logger.info("Please execute this patch separately with argument 'ALL' to assign permission to remaining users "); - System.out.println("Please execute this patch separately with argument 'ALL' to assign module permissions to remaining users!!"); - } - } - } - }catch(Exception ex){ - } - } - - private int assignPermissions(List xXPortalUsers) { - HashMap moduleNameId = xUserMgr.getAllModuleNameAndIdMap(); - int countUserPermissionUpdated = 0; - if (!CollectionUtils.isEmpty(xXPortalUsers)) { - for (XXPortalUser xPortalUser : xXPortalUsers) { - try { - if (xPortalUser != null) { - VXPortalUser vPortalUser = xPortalUserService.populateViewBean(xPortalUser); - if (vPortalUser != null) { - vPortalUser.setUserRoleList(daoManager.getXXPortalUserRole() - .findXPortalUserRolebyXPortalUserId(vPortalUser.getId())); - xUserMgr.createOrUpdateUserPermisson(vPortalUser, - moduleNameId.get(RangerConstants.MODULE_SECURITY_ZONE), false); - countUserPermissionUpdated += 1; - logger.info("Security Zone Permission assigned/updated to Admin Role, UserId [" - + xPortalUser.getId() + "]"); - } - } - } catch (Exception ex) { - logger.error("Error while assigning security zone permission for admin users", ex); - System.exit(1); - } - } - } - return countUserPermissionUpdated; - } - - private List readUserNamesFromFile(String aFileName) throws IOException { - List userNames=new ArrayList(); - if(!StringUtils.isEmpty(aFileName)){ - Path path = Paths.get(aFileName); - if (Files.exists(path) && Files.isRegularFile(path)) { - List fileContents=Files.readAllLines(path, ENCODING); - if(fileContents!=null && !fileContents.isEmpty()){ - for(String line:fileContents){ - if(!StringUtils.isEmpty(line) && !userNames.contains(line)){ - try{ - userNames.add(line.trim()); - }catch(Exception ex){ - } - } - } - } - } - } - return userNames; - } + for (String loginId : loginIdList) { + try { + xXPortalUser = daoManager.getXXPortalUser().findByLoginId(loginId); + + if (xXPortalUser != null) { + xXPortalUsers.add(xXPortalUser); + } else { + logger.info("User {} doesn't exist!", loginId); + } + } catch (Exception ex) { + // ignore + } + } + + countUserPermissionUpdated = assignPermissions(xXPortalUsers); + + logger.info("Security Zone Permissions assigned to {} of total {}", countUserPermissionUpdated, loginIdList.size()); + } else { + xXPortalUsers = daoManager.getXXPortalUser().findByRole(RangerConstants.ROLE_SYS_ADMIN); + + if (!CollectionUtils.isEmpty(xXPortalUsers)) { + countUserPermissionUpdated = assignPermissions(xXPortalUsers); + + logger.info("Security Zone Permissions assigned to users having role:{}. Processed:{} of total {}", RangerConstants.ROLE_SYS_ADMIN, countUserPermissionUpdated, xXPortalUsers.size()); + } + + xXPortalUsers = daoManager.getXXPortalUser().findByRole(RangerConstants.ROLE_ADMIN_AUDITOR); + + if (!CollectionUtils.isEmpty(xXPortalUsers)) { + countUserPermissionUpdated = assignPermissions(xXPortalUsers); + + logger.info("Security Zone Permissions assigned to users having role:{}. Processed:{} of total {}", RangerConstants.ROLE_SYS_ADMIN, countUserPermissionUpdated, xXPortalUsers.size()); + } + + //if total no. of users are more than 500 then process ADMIN and KEY_ADMIN users only to avoid timeout + if (userCount.compareTo(patchModeMaxLimit) < 0 || grantAllUsers) { + xXPortalUsers = daoManager.getXXPortalUser().findByRole(RangerConstants.ROLE_USER); + + if (!CollectionUtils.isEmpty(xXPortalUsers)) { + countUserPermissionUpdated = assignPermissions(xXPortalUsers); + + logger.info("Security Zone Permissions assigned to {} of total {}", countUserPermissionUpdated, xXPortalUsers.size()); + } + + logger.info("Please execute this patch separately with argument 'ALL' to assign permission to remaining users "); + System.out.println("Please execute this patch separately with argument 'ALL' to assign module permissions to remaining users!!"); + } + } + } + } catch (Exception ex) { + // ignore + } + } + + private int assignPermissions(List xXPortalUsers) { + HashMap moduleNameId = xUserMgr.getAllModuleNameAndIdMap(); + int countUserPermissionUpdated = 0; + + if (!CollectionUtils.isEmpty(xXPortalUsers)) { + for (XXPortalUser xPortalUser : xXPortalUsers) { + try { + if (xPortalUser != null) { + VXPortalUser vPortalUser = xPortalUserService.populateViewBean(xPortalUser); + + if (vPortalUser != null) { + vPortalUser.setUserRoleList(daoManager.getXXPortalUserRole().findXPortalUserRolebyXPortalUserId(vPortalUser.getId())); + + xUserMgr.createOrUpdateUserPermisson(vPortalUser, moduleNameId.get(RangerConstants.MODULE_SECURITY_ZONE), false); + + countUserPermissionUpdated += 1; + + logger.info("Security Zone Permission assigned/updated to Admin Role, UserId [{}]", xPortalUser.getId()); + } + } + } catch (Exception ex) { + logger.error("Error while assigning security zone permission for admin users", ex); + + System.exit(1); + } + } + } + + return countUserPermissionUpdated; + } + + private List readUserNamesFromFile(String aFileName) throws IOException { + List userNames = new ArrayList<>(); + + if (!StringUtils.isEmpty(aFileName)) { + Path path = Paths.get(aFileName); + + if (Files.exists(path) && Files.isRegularFile(path)) { + List fileContents = Files.readAllLines(path, ENCODING); + + if (fileContents != null && !fileContents.isEmpty()) { + for (String line : fileContents) { + if (!StringUtils.isEmpty(line) && !userNames.contains(line)) { + try { + userNames.add(line.trim()); + } catch (Exception ex) { + // ignore + } + } + } + } + } + } + + return userNames; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/patch/PatchAtlasForClassificationResource_J10047.java b/security-admin/src/main/java/org/apache/ranger/patch/PatchAtlasForClassificationResource_J10047.java index a6e39d82b7..6386f5442d 100644 --- a/security-admin/src/main/java/org/apache/ranger/patch/PatchAtlasForClassificationResource_J10047.java +++ b/security-admin/src/main/java/org/apache/ranger/patch/PatchAtlasForClassificationResource_J10047.java @@ -19,12 +19,6 @@ package org.apache.ranger.patch; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.ListIterator; -import java.util.List; -import java.util.Map; -import java.util.Date; import org.apache.ranger.biz.ServiceDBStore; import org.apache.ranger.common.RangerValidatorFactory; import org.apache.ranger.db.RangerDaoManager; @@ -42,35 +36,31 @@ import org.apache.ranger.plugin.util.SearchFilter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.stereotype.Component; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Date; +import java.util.List; +import java.util.ListIterator; +import java.util.Map; + import static org.apache.ranger.plugin.store.EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_ATLAS_NAME; @Component public class PatchAtlasForClassificationResource_J10047 extends BaseLoader { - - private static final Logger logger = LoggerFactory.getLogger(PatchAtlasForClassificationResource_J10047.class); - - private static final List ATLAS_RESOURCES = new ArrayList<>( - Arrays.asList( "classification")); - - private static final List ATLAS_ACCESS_TYPES = new ArrayList<>( - Arrays.asList("entity-remove-classification", "entity-add-classification", "entity-update-classification")); - - private static final List ATLAS_RESOURCE_ENTITY = new ArrayList<>( - Arrays.asList("entity-type", "entity-classification", "entity")); + private static final List ATLAS_RESOURCES = new ArrayList<>(Collections.singletonList("classification")); + private static final List ATLAS_ACCESS_TYPES = new ArrayList<>(Arrays.asList("entity-remove-classification", "entity-add-classification", "entity-update-classification")); + private static final List ATLAS_RESOURCE_ENTITY = new ArrayList<>(Arrays.asList("entity-type", "entity-classification", "entity")); + private static final List TYPES = new ArrayList<>(Arrays.asList("type", "entity-type", "entity-classification", "relationship-type", "end-one-entity-type", "end-one-entity-classification", "end-two-entity-type", "end-two-entity-classification", "entity-business-metadata")); private static final String ENTITY_CLASSIFICATION = "entity-classification"; - - private static final String CLASSIFICATION = "classification"; - - private static final String ENTITY = "entity"; - - private static final List TYPES = new ArrayList<>( - Arrays.asList("type", "entity-type", "entity-classification", "relationship-type", "end-one-entity-type", - "end-one-entity-classification","end-two-entity-type","end-two-entity-classification","entity-business-metadata")); + private static final String CLASSIFICATION = "classification"; + private static final String ENTITY = "entity"; @Autowired RangerDaoManager daoMgr; @@ -84,20 +74,24 @@ public class PatchAtlasForClassificationResource_J10047 extends BaseLoader { @Autowired ServiceDBStore svcStore; - public static void main(String[] args) { logger.info("main()"); + try { - PatchAtlasForClassificationResource_J10047 loader = (PatchAtlasForClassificationResource_J10047) org.apache.ranger.util.CLIUtil - .getBean(PatchAtlasForClassificationResource_J10047.class); + PatchAtlasForClassificationResource_J10047 loader = (PatchAtlasForClassificationResource_J10047) org.apache.ranger.util.CLIUtil.getBean(PatchAtlasForClassificationResource_J10047.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); } } @@ -107,9 +101,15 @@ public void init() throws Exception { // Do Nothing } + @Override + public void printStats() { + logger.info("PatchAtlasForClassificationResource_J10047 Logs"); + } + @Override public void execLoad() { logger.info("==> PatchAtlasForClassificationResource_J10047.execLoad()"); + try { addResourceClassificationsInServiceDef(); createAdditionalPolicyWithClassificationForExistingEntityClassificationPolicy(); @@ -117,53 +117,49 @@ public void execLoad() { e.printStackTrace(); throw new RuntimeException("Error while updating " + EMBEDDED_SERVICEDEF_ATLAS_NAME + " service-def"); } - logger.info("<== PatchAtlasForClassificationResource_J10047.execLoad()"); - } - @Override - public void printStats() { - logger.info("PatchAtlasForClassificationResource_J10047 Logs"); + logger.info("<== PatchAtlasForClassificationResource_J10047.execLoad()"); } private void addResourceClassificationsInServiceDef() throws Exception { - RangerServiceDef ret = null; - RangerServiceDef embeddedAtlasServiceDef = null; - XXServiceDef xXServiceDefObj = null; - RangerServiceDef dbAtlasServiceDef = null; + RangerServiceDef embeddedAtlasServiceDef = EmbeddedServiceDefsUtil.instance().getEmbeddedServiceDef(EMBEDDED_SERVICEDEF_ATLAS_NAME); - - embeddedAtlasServiceDef = EmbeddedServiceDefsUtil.instance().getEmbeddedServiceDef(EMBEDDED_SERVICEDEF_ATLAS_NAME); if (embeddedAtlasServiceDef != null) { - xXServiceDefObj = daoMgr.getXXServiceDef().findByName(EMBEDDED_SERVICEDEF_ATLAS_NAME); + XXServiceDef xXServiceDefObj = daoMgr.getXXServiceDef().findByName(EMBEDDED_SERVICEDEF_ATLAS_NAME); + if (xXServiceDefObj == null) { - logger.info(" service-def for "+ EMBEDDED_SERVICEDEF_ATLAS_NAME+" not found. No patching is needed"); + logger.info("service-def for {} not found. No patching is needed", EMBEDDED_SERVICEDEF_ATLAS_NAME); + return; } - dbAtlasServiceDef = svcDBStore.getServiceDefByName(EMBEDDED_SERVICEDEF_ATLAS_NAME); + RangerServiceDef dbAtlasServiceDef = svcDBStore.getServiceDefByName(EMBEDDED_SERVICEDEF_ATLAS_NAME); updateResourceInServiceDef(embeddedAtlasServiceDef, dbAtlasServiceDef); updateTypeResourceWithIgnoreCase(dbAtlasServiceDef.getResources()); removeEntityResourceAccessTypeRestrictions(dbAtlasServiceDef.getResources()); RangerServiceDefValidator validator = validatorFactory.getServiceDefValidator(svcStore); + validator.validate(dbAtlasServiceDef, RangerValidator.Action.UPDATE); - ret = svcStore.updateServiceDef(dbAtlasServiceDef); + + RangerServiceDef ret = svcStore.updateServiceDef(dbAtlasServiceDef); + if (ret == null) { - logger.error("Error while updating "+EMBEDDED_SERVICEDEF_ATLAS_NAME+" service-def"); + logger.error("Error while updating {} service-def", EMBEDDED_SERVICEDEF_ATLAS_NAME); + throw new RuntimeException("Error while updating " + EMBEDDED_SERVICEDEF_ATLAS_NAME + " service-def"); } } } private void updateResourceInServiceDef(RangerServiceDef embeddedAtlasServiceDef, RangerServiceDef dbAtlasServiceDef) { - List embeddedAtlasResourceDefs; - List embeddedAtlasAccessTypes; - embeddedAtlasResourceDefs = embeddedAtlasServiceDef.getResources(); - embeddedAtlasAccessTypes = embeddedAtlasServiceDef.getAccessTypes(); + List embeddedAtlasResourceDefs = embeddedAtlasServiceDef.getResources(); + List embeddedAtlasAccessTypes = embeddedAtlasServiceDef.getAccessTypes(); if (!checkResourcePresent(dbAtlasServiceDef.getResources()) && checkResourcePresent(embeddedAtlasResourceDefs)) { dbAtlasServiceDef.setResources(embeddedAtlasResourceDefs); + if (checkAccessPresent(embeddedAtlasAccessTypes)) { dbAtlasServiceDef.setAccessTypes(embeddedAtlasAccessTypes); } @@ -174,23 +170,27 @@ private void updateResourceInServiceDef(RangerServiceDef embeddedAtlasServiceDef private boolean checkResourcePresent(List resourceDefs) { boolean ret = false; + for (RangerServiceDef.RangerResourceDef resourceDef : resourceDefs) { if (ATLAS_RESOURCES.contains(resourceDef.getName())) { ret = true; break; } } + return ret; } private boolean checkAccessPresent(List embeddedAtlasAccessTypes) { boolean ret = false; + for (RangerServiceDef.RangerAccessTypeDef accessDef : embeddedAtlasAccessTypes) { if (ATLAS_ACCESS_TYPES.contains(accessDef.getName())) { ret = true; break; } } + return ret; } @@ -211,32 +211,30 @@ private void removeEntityResourceAccessTypeRestrictions(List xxServices = daoMgr.getXXService().findByServiceDefId(xServiceDefId); + Long xServiceDefId = xXServiceDefObj.getId(); + List xxServices = daoMgr.getXXService().findByServiceDefId(xServiceDefId); for (XXService xxService : xxServices) { - List servicePolicies = svcStore.getServicePolicies(xxService.getId(), new SearchFilter()); for (RangerPolicy policy : servicePolicies) { - - if(!isEntityResource(policy.getResources())){ + if (!isEntityResource(policy.getResources())) { continue; } - List policyItems = policy.getPolicyItems(); + List policyItems = policy.getPolicyItems(); List denypolicyItems = policy.getDenyPolicyItems(); - boolean policyItemCheck = checkAndFilterNonClassificationAccessTypeFromPolicy(policyItems); - boolean denyPolicyItemCheck = checkAndFilterNonClassificationAccessTypeFromPolicy(denypolicyItems); + boolean policyItemCheck = checkAndFilterNonClassificationAccessTypeFromPolicy(policyItems); + boolean denyPolicyItemCheck = checkAndFilterNonClassificationAccessTypeFromPolicy(denypolicyItems); if (policyItemCheck || denyPolicyItemCheck) { policy.setName(policy.getName() + " - " + CLASSIFICATION); @@ -246,6 +244,7 @@ private void createAdditionalPolicyWithClassificationForExistingEntityClassifica RangerPolicyResource resource = xPolResMap.get(ENTITY_CLASSIFICATION); xPolResMap.put(CLASSIFICATION, resource); + policy.setResources(xPolResMap); policy.setVersion(1L); @@ -255,24 +254,26 @@ private void createAdditionalPolicyWithClassificationForExistingEntityClassifica policy.setUpdateTime(new Date()); svcStore.createPolicy(policy); + logger.info("New Additional policy created"); } } } + logger.info("<== createAdditionalPolicyWithClassificationForExistingPolicy"); } private boolean isEntityResource(Map xPolResMap) { boolean ret = true; - if (xPolResMap != null && xPolResMap.size() == ATLAS_RESOURCE_ENTITY.size()){ + if (xPolResMap != null && xPolResMap.size() == ATLAS_RESOURCE_ENTITY.size()) { for (String resourceName : ATLAS_RESOURCE_ENTITY) { if (xPolResMap.get(resourceName) == null) { ret = false; break; } } - }else{ + } else { ret = false; } @@ -280,24 +281,25 @@ private boolean isEntityResource(Map xPolResMap) { } private boolean checkAndFilterNonClassificationAccessTypeFromPolicy(List policyItems) { - - ListIterator policyItemListIterator = policyItems.listIterator(); - boolean isClassificationAccessTypeExist = false; + ListIterator policyItemListIterator = policyItems.listIterator(); + boolean isClassificationAccessTypeExist = false; while (policyItemListIterator.hasNext()) { - RangerPolicyItem policyItem = policyItemListIterator.next(); + RangerPolicyItem policyItem = policyItemListIterator.next(); ListIterator itemAccessListIterator = policyItem.getAccesses().listIterator(); + boolean accessPresent = false; - boolean accessPresent = false; while (itemAccessListIterator.hasNext()) { RangerPolicyItemAccess access = itemAccessListIterator.next(); + if (!ATLAS_ACCESS_TYPES.contains(access.getType())) { itemAccessListIterator.remove(); } else { - accessPresent = true; + accessPresent = true; isClassificationAccessTypeExist = true; } } + if (!accessPresent) { policyItemListIterator.remove(); } @@ -305,5 +307,4 @@ private boolean checkAndFilterNonClassificationAccessTypeFromPolicy(List PatchForAllServiceDefForPolicyConditionUpdate_J10060.execLoad()"); - try { - updateAllServiceDef(); - } catch (Exception e) { - logger.error("Error whille PatchForAllServiceDefForPolicyConditionUpdate_J10060()data.", e); - } - logger.info("<== PatchForAllServiceDefForPolicyConditionUpdate_J10060.execLoad()"); - } + @Override + public void init() throws Exception { + // Do Nothing + } - @Override - public void printStats() { - logger.info("PatchForAllServiceDefForPolicyConditionUpdate_J10060 data "); - } + @Override + public void printStats() { + logger.info("PatchForAllServiceDefForPolicyConditionUpdate_J10060 data "); + } - private void updateAllServiceDef() { + @Override + public void execLoad() { + logger.info("==> PatchForAllServiceDefForPolicyConditionUpdate_J10060.execLoad()"); + try { + updateAllServiceDef(); + } catch (Exception e) { + logger.error("Error whille PatchForAllServiceDefForPolicyConditionUpdate_J10060()data.", e); + } + logger.info("<== PatchForAllServiceDefForPolicyConditionUpdate_J10060.execLoad()"); + } - try { - List allServiceDefs = svcStore.getServiceDefs(new SearchFilter()); + private void updateAllServiceDef() { + try { + List allServiceDefs = svcStore.getServiceDefs(new SearchFilter()); - if (CollectionUtils.isNotEmpty(allServiceDefs)) { - for (RangerServiceDef serviceDef : allServiceDefs) { - if(CollectionUtils.isNotEmpty(serviceDef.getPolicyConditions())) { - Map uiHintPreVal = new HashMap<>(); - List updatedPolicyCondition = new ArrayList<>(); - RangerServiceDef embeddedTagServiceDef=EmbeddedServiceDefsUtil.instance().getEmbeddedServiceDef(serviceDef.getName()); + if (CollectionUtils.isNotEmpty(allServiceDefs)) { + for (RangerServiceDef serviceDef : allServiceDefs) { + if (CollectionUtils.isNotEmpty(serviceDef.getPolicyConditions())) { + Map uiHintPreVal = new HashMap<>(); + List updatedPolicyCondition = new ArrayList<>(); + RangerServiceDef embeddedTagServiceDef = EmbeddedServiceDefsUtil.instance().getEmbeddedServiceDef(serviceDef.getName()); - List policyConditionsOld = embeddedTagServiceDef.getPolicyConditions(); - for(RangerPolicyConditionDef policyConditionOld : policyConditionsOld) { - uiHintPreVal.put(policyConditionOld.getItemId(), policyConditionOld.getUiHint()); - } + List policyConditionsOld = embeddedTagServiceDef.getPolicyConditions(); + for (RangerPolicyConditionDef policyConditionOld : policyConditionsOld) { + uiHintPreVal.put(policyConditionOld.getItemId(), policyConditionOld.getUiHint()); + } - List policyConditionsNew = serviceDef.getPolicyConditions(); - for (RangerPolicyConditionDef policyConditionNew : policyConditionsNew) { - if(StringUtils.isNotEmpty(uiHintPreVal.get(policyConditionNew.getItemId()))) { - policyConditionNew.setUiHint(uiHintPreVal.get(policyConditionNew.getItemId())); - } - updatedPolicyCondition.add(policyConditionNew); - } + List policyConditionsNew = serviceDef.getPolicyConditions(); + for (RangerPolicyConditionDef policyConditionNew : policyConditionsNew) { + if (StringUtils.isNotEmpty(uiHintPreVal.get(policyConditionNew.getItemId()))) { + policyConditionNew.setUiHint(uiHintPreVal.get(policyConditionNew.getItemId())); + } + updatedPolicyCondition.add(policyConditionNew); + } - serviceDef.setPolicyConditions(updatedPolicyCondition); - svcStore.updateServiceDef(serviceDef); - } - } - } - }catch (Exception e) { - logger.error("Error while patching service-def for policy condition:", e); - } - } -} \ No newline at end of file + serviceDef.setPolicyConditions(updatedPolicyCondition); + svcStore.updateServiceDef(serviceDef); + } + } + } + } catch (Exception e) { + logger.error("Error while patching service-def for policy condition:", e); + } + } +} diff --git a/security-admin/src/main/java/org/apache/ranger/patch/PatchForAllServiceDefUpdateForDefaultAuditFilters_J10049.java b/security-admin/src/main/java/org/apache/ranger/patch/PatchForAllServiceDefUpdateForDefaultAuditFilters_J10049.java index ca26f35682..ad8fd1c658 100644 --- a/security-admin/src/main/java/org/apache/ranger/patch/PatchForAllServiceDefUpdateForDefaultAuditFilters_J10049.java +++ b/security-admin/src/main/java/org/apache/ranger/patch/PatchForAllServiceDefUpdateForDefaultAuditFilters_J10049.java @@ -17,8 +17,6 @@ package org.apache.ranger.patch; -import java.util.List; - import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang.StringUtils; import org.apache.ranger.biz.ServiceDBStore; @@ -37,151 +35,141 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; +import java.util.List; + @Component public class PatchForAllServiceDefUpdateForDefaultAuditFilters_J10049 extends BaseLoader { - private static final Logger logger = LoggerFactory - .getLogger(PatchForAllServiceDefUpdateForDefaultAuditFilters_J10049.class); - - @Autowired - RangerDaoManager daoMgr; - - @Autowired - ServiceDBStore svcDBStore; - - @Autowired - RangerServiceDefService serviceDefService; - - @Autowired - StringUtil stringUtil; - - public static void main(String[] args) { - try { - PatchForAllServiceDefUpdateForDefaultAuditFilters_J10049 loader = (PatchForAllServiceDefUpdateForDefaultAuditFilters_J10049) CLIUtil - .getBean(PatchForAllServiceDefUpdateForDefaultAuditFilters_J10049.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); - } - } - - @Override - public void init() throws Exception { - // Do Nothing - } - - @Override - public void execLoad() { - logger.info("==> PatchForAllServiceDefUpdateForDefaultAuditFilters_J10049.execLoad()"); - try { - updateAllServiceDef(); - } catch (Exception e) { - logger.error("Error in PatchForAllServiceDefUpdateForDefaultAuditFilters_J10049.execLoad()", e); - } - logger.info("<== PatchForAllServiceDefUpdateForDefaultAuditFilters_J10049.execLoad()"); - } - - @Override - public void printStats() { - logger.info("adding default audit-filters to all service-defs"); - } - - private void updateAllServiceDef() throws Exception { - if(logger.isDebugEnabled()) { - logger.debug("==> PatchForAllServiceDefUpdateForDefaultAuditFilters_J10049.updateAllServiceDef()"); - } - List allXXServiceDefs; - allXXServiceDefs = daoMgr.getXXServiceDef().getAll(); - - if (CollectionUtils.isNotEmpty(allXXServiceDefs)) { - logger.info("Found " + allXXServiceDefs.size() + " services-defs"); - for (XXServiceDef xxServiceDef : allXXServiceDefs) { - - String serviceDefName = xxServiceDef.getName(); - - try { - RangerServiceConfigDef defualtAuditFiltersSvcConfDef = getDefaultAuditFiltersByServiceDef(serviceDefName); - - if (defualtAuditFiltersSvcConfDef == null) { - logger.info("No default audit-filter available for service-def " + serviceDefName + ". Skipped"); - continue; - } - - RangerServiceDef serviceDef = svcDBStore.getServiceDefByName(serviceDefName); - - if (serviceDef != null) { - List svcConfDefList = serviceDef.getConfigs(); - boolean defaultAuditFiltresFound = false; - for (RangerServiceConfigDef svcConfDef : svcConfDefList) { - if (StringUtils.equals(svcConfDef.getName(), ServiceDBStore.RANGER_PLUGIN_AUDIT_FILTERS)) { - defaultAuditFiltresFound = true; - break; - } - } - if (!defaultAuditFiltresFound) { - logger.info("adding default audit-filter for service-def:[" + serviceDefName + "]"); - int sortOrder = serviceDef.getConfigs().size() - 1; - addDefaultAuditFilterConfig(defualtAuditFiltersSvcConfDef, xxServiceDef, sortOrder); - logger.info("Completed adding default audit-filter for service-def:[" + serviceDefName + "]"); - }else { - logger.info("default audit-filter already available for service-def " + serviceDefName + ". Skipped"); - } - - }else { - logger.info("No service-def:[" + serviceDefName + "] found"); - } - - } catch (Exception e) { - logger.error("Error while adding default audit-filter service-def:[" + serviceDefName + "]", e); - } - } - }else { - logger.info("No service-def found"); - } - if(logger.isDebugEnabled()) { - logger.debug("<== PatchForAllServiceDefUpdateForDefaultAuditFilters_J10049.updateAllServiceDef()"); - } - } - - private RangerServiceConfigDef getDefaultAuditFiltersByServiceDef(String serviceDefName) throws Exception { - if(logger.isDebugEnabled()) { - logger.debug("==> PatchForAllServiceDefUpdateForDefaultAuditFilters_J10049.getDefaultAuditFiltersByServiceDef() for serviceDefName:["+serviceDefName+ "]"); - } - RangerServiceConfigDef ret = null; - RangerServiceDef embeddedAtlasServiceDef = null; - embeddedAtlasServiceDef = EmbeddedServiceDefsUtil.instance().getEmbeddedServiceDef(serviceDefName); - - List svcConfDefList = embeddedAtlasServiceDef.getConfigs(); - for (RangerServiceConfigDef svcConfDef : svcConfDefList) { - if (StringUtils.equals(svcConfDef.getName(), ServiceDBStore.RANGER_PLUGIN_AUDIT_FILTERS)) { - ret = svcConfDef; - break; - } - } - - if(logger.isDebugEnabled()) { - logger.debug("<== PatchForAllServiceDefUpdateForDefaultAuditFilters_J10049.getDefaultAuditFiltersByServiceDef() for serviceDefName:["+serviceDefName+"] ret : "+ret); - } - return ret; - } - - private void addDefaultAuditFilterConfig(RangerServiceConfigDef config, XXServiceDef createdSvcDef, int sortOrder) { - if(logger.isDebugEnabled()) { - logger.debug("==> PatchForAllServiceDefUpdateForDefaultAuditFilters_J10049.addDefaultAuditFilterConfig() for config:["+config+"] sortOrder: "+sortOrder ); - } - XXServiceConfigDefDao xxServiceConfigDao = daoMgr.getXXServiceConfigDef(); - XXServiceConfigDef xConfig = new XXServiceConfigDef(); - xConfig = serviceDefService.populateRangerServiceConfigDefToXX(config, xConfig, createdSvcDef, - RangerServiceDefService.OPERATION_CREATE_CONTEXT); - xConfig.setOrder(sortOrder); - xConfig = xxServiceConfigDao.create(xConfig); - if(logger.isDebugEnabled()) { - logger.debug("<== PatchForAllServiceDefUpdateForDefaultAuditFilters_J10049.addDefaultAuditFilterConfig() for config:["+config+"] sortOrder: "+sortOrder); - } - } -} \ No newline at end of file + private static final Logger logger = LoggerFactory.getLogger(PatchForAllServiceDefUpdateForDefaultAuditFilters_J10049.class); + + @Autowired + RangerDaoManager daoMgr; + + @Autowired + ServiceDBStore svcDBStore; + + @Autowired + RangerServiceDefService serviceDefService; + + @Autowired + StringUtil stringUtil; + + public static void main(String[] args) { + try { + PatchForAllServiceDefUpdateForDefaultAuditFilters_J10049 loader = (PatchForAllServiceDefUpdateForDefaultAuditFilters_J10049) CLIUtil.getBean(PatchForAllServiceDefUpdateForDefaultAuditFilters_J10049.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); + } + } + + @Override + public void init() throws Exception { + // Do Nothing + } + + @Override + public void printStats() { + logger.info("adding default audit-filters to all service-defs"); + } + + @Override + public void execLoad() { + logger.info("==> PatchForAllServiceDefUpdateForDefaultAuditFilters_J10049.execLoad()"); + try { + updateAllServiceDef(); + } catch (Exception e) { + logger.error("Error in PatchForAllServiceDefUpdateForDefaultAuditFilters_J10049.execLoad()", e); + } + logger.info("<== PatchForAllServiceDefUpdateForDefaultAuditFilters_J10049.execLoad()"); + } + + private void updateAllServiceDef() { + logger.debug("==> PatchForAllServiceDefUpdateForDefaultAuditFilters_J10049.updateAllServiceDef()"); + List allXXServiceDefs; + allXXServiceDefs = daoMgr.getXXServiceDef().getAll(); + + if (CollectionUtils.isNotEmpty(allXXServiceDefs)) { + logger.info("Found {} services-defs", allXXServiceDefs.size()); + for (XXServiceDef xxServiceDef : allXXServiceDefs) { + String serviceDefName = xxServiceDef.getName(); + + try { + RangerServiceConfigDef defualtAuditFiltersSvcConfDef = getDefaultAuditFiltersByServiceDef(serviceDefName); + + if (defualtAuditFiltersSvcConfDef == null) { + logger.info("No default audit-filter available for service-def {} Skipped", serviceDefName); + continue; + } + + RangerServiceDef serviceDef = svcDBStore.getServiceDefByName(serviceDefName); + + if (serviceDef != null) { + List svcConfDefList = serviceDef.getConfigs(); + boolean defaultAuditFiltresFound = false; + for (RangerServiceConfigDef svcConfDef : svcConfDefList) { + if (StringUtils.equals(svcConfDef.getName(), ServiceDBStore.RANGER_PLUGIN_AUDIT_FILTERS)) { + defaultAuditFiltresFound = true; + break; + } + } + if (!defaultAuditFiltresFound) { + logger.info("adding default audit-filter for service-def:[{}]", serviceDefName); + int sortOrder = serviceDef.getConfigs().size() - 1; + addDefaultAuditFilterConfig(defualtAuditFiltersSvcConfDef, xxServiceDef, sortOrder); + logger.info("Completed adding default audit-filter for service-def:[{}]", serviceDefName); + } else { + logger.info("default audit-filter already available for service-def [{}] skipped", serviceDefName); + } + } else { + logger.info("No service-def:[{}] found", serviceDefName); + } + } catch (Exception e) { + logger.error("Error while adding default audit-filter service-def:[{}]", serviceDefName, e); + } + } + } else { + logger.info("No service-def found"); + } + logger.debug("<== PatchForAllServiceDefUpdateForDefaultAuditFilters_J10049.updateAllServiceDef()"); + } + + private RangerServiceConfigDef getDefaultAuditFiltersByServiceDef(String serviceDefName) throws Exception { + logger.debug("==> PatchForAllServiceDefUpdateForDefaultAuditFilters_J10049.getDefaultAuditFiltersByServiceDef() for serviceDefName:[{}]", serviceDefName); + + RangerServiceConfigDef ret = null; + RangerServiceDef embeddedAtlasServiceDef = EmbeddedServiceDefsUtil.instance().getEmbeddedServiceDef(serviceDefName); + List svcConfDefList = embeddedAtlasServiceDef.getConfigs(); + + for (RangerServiceConfigDef svcConfDef : svcConfDefList) { + if (StringUtils.equals(svcConfDef.getName(), ServiceDBStore.RANGER_PLUGIN_AUDIT_FILTERS)) { + ret = svcConfDef; + break; + } + } + + logger.debug("<== PatchForAllServiceDefUpdateForDefaultAuditFilters_J10049.getDefaultAuditFiltersByServiceDef() for serviceDefName:[{}] ret : {}", serviceDefName, ret); + + return ret; + } + + private void addDefaultAuditFilterConfig(RangerServiceConfigDef config, XXServiceDef createdSvcDef, int sortOrder) { + logger.debug("==> PatchForAllServiceDefUpdateForDefaultAuditFilters_J10049.addDefaultAuditFilterConfig() for config:[{}] sortOrder: {}", config, sortOrder); + + XXServiceConfigDefDao xxServiceConfigDao = daoMgr.getXXServiceConfigDef(); + XXServiceConfigDef xConfig = new XXServiceConfigDef(); + + xConfig = serviceDefService.populateRangerServiceConfigDefToXX(config, xConfig, createdSvcDef, RangerServiceDefService.OPERATION_CREATE_CONTEXT); + + xConfig.setOrder(sortOrder); + + xxServiceConfigDao.create(xConfig); + + logger.debug("<== PatchForAllServiceDefUpdateForDefaultAuditFilters_J10049.addDefaultAuditFilterConfig() for config:[{}] sortOrder: {}", config, sortOrder); + } +} diff --git a/security-admin/src/main/java/org/apache/ranger/patch/PatchForAllServiceDefUpdateForResourceSpecificAccesses_J10012.java b/security-admin/src/main/java/org/apache/ranger/patch/PatchForAllServiceDefUpdateForResourceSpecificAccesses_J10012.java index e783d71319..23348bc147 100644 --- a/security-admin/src/main/java/org/apache/ranger/patch/PatchForAllServiceDefUpdateForResourceSpecificAccesses_J10012.java +++ b/security-admin/src/main/java/org/apache/ranger/patch/PatchForAllServiceDefUpdateForResourceSpecificAccesses_J10012.java @@ -25,6 +25,7 @@ import org.apache.ranger.common.RangerValidatorFactory; import org.apache.ranger.common.StringUtil; import org.apache.ranger.db.RangerDaoManager; +import org.apache.ranger.entity.XXServiceDef; import org.apache.ranger.plugin.model.RangerServiceDef; import org.apache.ranger.plugin.model.validation.RangerServiceDefHelper; import org.apache.ranger.service.RangerPolicyService; @@ -35,7 +36,6 @@ import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; -import org.apache.ranger.entity.XXServiceDef; import java.util.List; import java.util.Map; @@ -76,16 +76,22 @@ public class PatchForAllServiceDefUpdateForResourceSpecificAccesses_J10012 exten public static void main(String[] args) { logger.info("main()"); + try { PatchForAllServiceDefUpdateForResourceSpecificAccesses_J10012 loader = (PatchForAllServiceDefUpdateForResourceSpecificAccesses_J10012) CLIUtil.getBean(PatchForAllServiceDefUpdateForResourceSpecificAccesses_J10012.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); } } @@ -95,80 +101,82 @@ public void init() throws Exception { // Do Nothing } + @Override + public void printStats() { + logger.info("PatchForAllServiceDefUpdateForResourceSpecificAccesses_J10012 data "); + } + @Override public void execLoad() { logger.info("==> PatchForAllServiceDefUpdateForResourceSpecificAccesses_J10012.execLoad()"); + try { updateAllServiceDef(); } catch (Exception e) { logger.error("Error in PatchForAllServiceDefUpdateForResourceSpecificAccesses_J10012.execLoad()", e); } - logger.info("<== PatchForAllServiceDefUpdateForResourceSpecificAccesses_J10012.execLoad()"); - } - @Override - public void printStats() { - logger.info("PatchForAllServiceDefUpdateForResourceSpecificAccesses_J10012 data "); + logger.info("<== PatchForAllServiceDefUpdateForResourceSpecificAccesses_J10012.execLoad()"); } - private void updateAllServiceDef() { + private void updateAllServiceDef() { + List allXXServiceDefs = daoMgr.getXXServiceDef().getAll(); - List allXXServiceDefs; - allXXServiceDefs = daoMgr.getXXServiceDef().getAll(); + if (CollectionUtils.isNotEmpty(allXXServiceDefs)) { + for (XXServiceDef xxServiceDef : allXXServiceDefs) { + String serviceDefName = xxServiceDef.getName(); - if (CollectionUtils.isNotEmpty(allXXServiceDefs)) { + try { + String jsonStrPreUpdate = xxServiceDef.getDefOptions(); + Map serviceDefOptionsPreUpdate = jsonUtil.jsonToMap(jsonStrPreUpdate); + String valueBeforeUpdate = serviceDefOptionsPreUpdate.get(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES); + RangerServiceDef serviceDef = svcDBStore.getServiceDefByName(serviceDefName); - for (XXServiceDef xxServiceDef : allXXServiceDefs) { + if (serviceDef != null) { + logger.info("Started patching service-def:[{}]", serviceDefName); - String serviceDefName = xxServiceDef.getName(); + RangerServiceDefHelper defHelper = new RangerServiceDefHelper(serviceDef, false); - try { - String jsonStrPreUpdate = xxServiceDef.getDefOptions(); - Map serviceDefOptionsPreUpdate = jsonUtil.jsonToMap(jsonStrPreUpdate); - String valueBeforeUpdate = serviceDefOptionsPreUpdate.get(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES); + defHelper.patchServiceDefWithDefaultValues(); - RangerServiceDef serviceDef = svcDBStore.getServiceDefByName(serviceDefName); + svcStore.updateServiceDef(serviceDef); - if (serviceDef != null) { - logger.info("Started patching service-def:[" + serviceDefName + "]"); + XXServiceDef dbServiceDef = daoMgr.getXXServiceDef().findByName(serviceDefName); - RangerServiceDefHelper defHelper = new RangerServiceDefHelper(serviceDef, false); - defHelper.patchServiceDefWithDefaultValues(); + if (dbServiceDef != null) { + String jsonStrPostUpdate = dbServiceDef.getDefOptions(); + Map serviceDefOptionsPostUpdate = jsonUtil.jsonToMap(jsonStrPostUpdate); + String valueAfterUpdate = serviceDefOptionsPostUpdate.get(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES); - svcStore.updateServiceDef(serviceDef); + if (!StringUtils.equals(valueBeforeUpdate, valueAfterUpdate)) { + if (StringUtils.isEmpty(valueBeforeUpdate)) { + serviceDefOptionsPostUpdate.remove(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES); + } else { + serviceDefOptionsPostUpdate.put(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES, valueBeforeUpdate); + } - XXServiceDef dbServiceDef = daoMgr.getXXServiceDef().findByName(serviceDefName); + dbServiceDef.setDefOptions(mapToJsonString(serviceDefOptionsPostUpdate)); - if (dbServiceDef != null) { - String jsonStrPostUpdate = dbServiceDef.getDefOptions(); - Map serviceDefOptionsPostUpdate = jsonUtil.jsonToMap(jsonStrPostUpdate); - String valueAfterUpdate = serviceDefOptionsPostUpdate.get(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES); + daoMgr.getXXServiceDef().update(dbServiceDef); + } + } - if (!StringUtils.equals(valueBeforeUpdate, valueAfterUpdate)) { - if (StringUtils.isEmpty(valueBeforeUpdate)) { - serviceDefOptionsPostUpdate.remove(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES); - } else { - serviceDefOptionsPostUpdate.put(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES, valueBeforeUpdate); - } - dbServiceDef.setDefOptions(mapToJsonString(serviceDefOptionsPostUpdate)); - daoMgr.getXXServiceDef().update(dbServiceDef); - } - } - logger.info("Completed patching service-def:[" + serviceDefName + "]"); - } - } catch (Exception e) { - logger.error("Error while patching service-def:[" + serviceDefName + "]", e); - } - } - } - } + logger.info("Completed patching service-def:[{}]", serviceDefName); + } + } catch (Exception e) { + logger.error("Error while patching service-def:[{}]", serviceDefName, e); + } + } + } + } - private String mapToJsonString(Map map) throws Exception { + private String mapToJsonString(Map map) { String ret = null; - if(map != null) { + + if (map != null) { ret = jsonUtil.readMapToString(map); } + return ret; } } - diff --git a/security-admin/src/main/java/org/apache/ranger/patch/PatchForAtlasAdminAudits_J10043.java b/security-admin/src/main/java/org/apache/ranger/patch/PatchForAtlasAdminAudits_J10043.java index 00d147ccfb..2dce33e50c 100644 --- a/security-admin/src/main/java/org/apache/ranger/patch/PatchForAtlasAdminAudits_J10043.java +++ b/security-admin/src/main/java/org/apache/ranger/patch/PatchForAtlasAdminAudits_J10043.java @@ -17,9 +17,6 @@ package org.apache.ranger.patch; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; import org.apache.ranger.biz.ServiceDBStore; import org.apache.ranger.common.RangerValidatorFactory; import org.apache.ranger.db.RangerDaoManager; @@ -35,14 +32,16 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + @Component public class PatchForAtlasAdminAudits_J10043 extends BaseLoader { private static final Logger logger = LoggerFactory.getLogger(PatchForAtlasAdminAudits_J10043.class); - private static final List ATLAS_RESOURCES = new ArrayList<>( - Arrays.asList("atlas-service")); - private static final List ATLAS_ACCESS_TYPES = new ArrayList<>( - Arrays.asList("admin-audits")); + private static final List ATLAS_RESOURCES = new ArrayList<>(Collections.singletonList("atlas-service")); + private static final List ATLAS_ACCESS_TYPES = new ArrayList<>(Collections.singletonList("admin-audits")); @Autowired RangerDaoManager daoMgr; @@ -58,17 +57,22 @@ public class PatchForAtlasAdminAudits_J10043 extends BaseLoader { public static void main(String[] args) { logger.info("main()"); + try { - PatchForAtlasAdminAudits_J10043 loader = (PatchForAtlasAdminAudits_J10043) CLIUtil - .getBean(PatchForAtlasAdminAudits_J10043.class); + PatchForAtlasAdminAudits_J10043 loader = (PatchForAtlasAdminAudits_J10043) CLIUtil.getBean(PatchForAtlasAdminAudits_J10043.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); } } @@ -78,84 +82,86 @@ public void init() throws Exception { // Do Nothing } + @Override + public void printStats() { + logger.info("PatchForAtlasAdminAudits_J10043 Logs"); + } + @Override public void execLoad() { logger.info("==> PatchForAtlasAdminAudits_J10043.execLoad()"); + try { addAdminAuditsPermissionInServiceDef(); } catch (Exception e) { - throw new RuntimeException( - "Error while updating " + EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_ATLAS_NAME + " service-def"); + throw new RuntimeException("Error while updating " + EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_ATLAS_NAME + " service-def"); } - logger.info("<== PatchForAtlasAdminAudits_J10043.execLoad()"); - } - @Override - public void printStats() { - logger.info("PatchForAtlasAdminAudits_J10043 Logs"); + logger.info("<== PatchForAtlasAdminAudits_J10043.execLoad()"); } private void addAdminAuditsPermissionInServiceDef() throws Exception { - RangerServiceDef ret = null; - RangerServiceDef embeddedAtlasServiceDef = null; - XXServiceDef xXServiceDefObj = null; - RangerServiceDef dbAtlasServiceDef = null; - List embeddedAtlasResourceDefs = null; - List embeddedAtlasAccessTypes = null; - - embeddedAtlasServiceDef = EmbeddedServiceDefsUtil.instance() - .getEmbeddedServiceDef(EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_ATLAS_NAME); + RangerServiceDef embeddedAtlasServiceDef = EmbeddedServiceDefsUtil.instance().getEmbeddedServiceDef(EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_ATLAS_NAME); + if (embeddedAtlasServiceDef != null) { - xXServiceDefObj = daoMgr.getXXServiceDef() - .findByName(EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_ATLAS_NAME); + XXServiceDef xXServiceDefObj = daoMgr.getXXServiceDef().findByName(EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_ATLAS_NAME); + if (xXServiceDefObj == null) { - logger.info(xXServiceDefObj + ": service-def not found. No patching is needed"); + logger.info("{}: service-def not found. No patching is needed", xXServiceDefObj); + return; } - dbAtlasServiceDef = svcDBStore.getServiceDefByName(EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_ATLAS_NAME); + RangerServiceDef dbAtlasServiceDef = svcDBStore.getServiceDefByName(EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_ATLAS_NAME); - embeddedAtlasResourceDefs = embeddedAtlasServiceDef.getResources(); - embeddedAtlasAccessTypes = embeddedAtlasServiceDef.getAccessTypes(); + List embeddedAtlasResourceDefs = embeddedAtlasServiceDef.getResources(); + List embeddedAtlasAccessTypes = embeddedAtlasServiceDef.getAccessTypes(); if (checkResourcePresent(embeddedAtlasResourceDefs)) { dbAtlasServiceDef.setResources(embeddedAtlasResourceDefs); + if (checkAccessPresent(embeddedAtlasAccessTypes)) { dbAtlasServiceDef.setAccessTypes(embeddedAtlasAccessTypes); } } RangerServiceDefValidator validator = validatorFactory.getServiceDefValidator(svcStore); + validator.validate(dbAtlasServiceDef, Action.UPDATE); - ret = svcStore.updateServiceDef(dbAtlasServiceDef); + + RangerServiceDef ret = svcStore.updateServiceDef(dbAtlasServiceDef); + if (ret == null) { - logger.error("Error while updating " + EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_ATLAS_NAME - + " service-def"); - throw new RuntimeException("Error while updating " - + EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_ATLAS_NAME + " service-def"); + logger.error("Error while updating {} service-def", EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_ATLAS_NAME); + + throw new RuntimeException("Error while updating " + EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_ATLAS_NAME + " service-def"); } } } private boolean checkResourcePresent(List resourceDefs) { boolean ret = false; + for (RangerServiceDef.RangerResourceDef resourceDef : resourceDefs) { if (ATLAS_RESOURCES.contains(resourceDef.getName())) { ret = true; break; } } + return ret; } private boolean checkAccessPresent(List embeddedAtlasAccessTypes) { boolean ret = false; + for (RangerServiceDef.RangerAccessTypeDef accessDef : embeddedAtlasAccessTypes) { if (ATLAS_ACCESS_TYPES.contains(accessDef.getName())) { ret = true; break; } } + return ret; } } diff --git a/security-admin/src/main/java/org/apache/ranger/patch/PatchForAtlasResourceAndAccessTypeUpdate_J10016.java b/security-admin/src/main/java/org/apache/ranger/patch/PatchForAtlasResourceAndAccessTypeUpdate_J10016.java index 4afd53722a..7308a449e9 100644 --- a/security-admin/src/main/java/org/apache/ranger/patch/PatchForAtlasResourceAndAccessTypeUpdate_J10016.java +++ b/security-admin/src/main/java/org/apache/ranger/patch/PatchForAtlasResourceAndAccessTypeUpdate_J10016.java @@ -18,10 +18,6 @@ package org.apache.ranger.patch; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - import org.apache.commons.lang.StringUtils; import org.apache.ranger.biz.ServiceDBStore; import org.apache.ranger.common.GUIDUtil; @@ -55,307 +51,346 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + @Component public class PatchForAtlasResourceAndAccessTypeUpdate_J10016 extends BaseLoader { - private static final Logger logger = LoggerFactory.getLogger(PatchForAtlasResourceAndAccessTypeUpdate_J10016.class); - private static final String RESOURCE_DEF_NAME = "all - relationship-type, end-one-entity-type, end-one-entity-classification, end-one-entity, end-two-entity-type, end-two-entity-classification, end-two-entity"; - private static final List ATLAS_RESOURCES = new ArrayList<>( - Arrays.asList("relationship-type", "end-one-entity-type", "end-one-entity-classification", "end-one-entity", - "end-two-entity-type", "end-two-entity-classification", "end-two-entity")); - private static final List ATLAS_ACCESS_TYPES = new ArrayList<>( - Arrays.asList("add-relationship", "update-relationship", "remove-relationship")); - private static final String LOGIN_ID_ADMIN = "admin"; - private static final String GROUP_PUBLIC = "public"; - - @Autowired - RangerDaoManager daoMgr; - - @Autowired - ServiceDBStore svcDBStore; - - @Autowired - GUIDUtil guidUtil; - - @Autowired - JSONUtil jsonUtil; - - @Autowired - StringUtil stringUtil; - - @Autowired - RangerValidatorFactory validatorFactory; - - @Autowired - ServiceDBStore svcStore; - - @Autowired - RangerPolicyService policyService; - - public static void main(String[] args) { - logger.info("main()"); - try { - PatchForAtlasResourceAndAccessTypeUpdate_J10016 loader = (PatchForAtlasResourceAndAccessTypeUpdate_J10016) CLIUtil - .getBean(PatchForAtlasResourceAndAccessTypeUpdate_J10016.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); - } - } - - @Override - public void init() throws Exception { - // Do Nothing - } - - @Override - public void execLoad() { - logger.info("==> PatchForAtlasResourceAndAccessTypeUpdate.execLoad()"); - try { - updateAtlasResourceAndAccessType(); - } catch (Exception e) { - logger.error("Error whille updateAtlasResourceAndAccessType()data.", e); - } - logger.info("<== PatchForAtlasResourceAndAccessTypeUpdate.execLoad()"); - } - - @Override - public void printStats() { - logger.info("AtlasResourceAndAccessTypeUpdate data "); - } - - private void updateAtlasResourceAndAccessType() { - RangerServiceDef ret = null; - RangerServiceDef embeddedAtlasServiceDef = null; - XXServiceDef xXServiceDefObj = null; - RangerServiceDef dbAtlasServiceDef = null; - List embeddedAtlasResourceDefs = null; - List embeddedAtlasAccessTypes = null; - - try { - embeddedAtlasServiceDef = EmbeddedServiceDefsUtil.instance() - .getEmbeddedServiceDef(EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_ATLAS_NAME); - if (embeddedAtlasServiceDef != null) { - xXServiceDefObj = daoMgr.getXXServiceDef() - .findByName(EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_ATLAS_NAME); - if (xXServiceDefObj == null) { - logger.info(xXServiceDefObj + ": service-def not found. No patching is needed"); - return; - } - - dbAtlasServiceDef = svcDBStore - .getServiceDefByName(EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_ATLAS_NAME); - embeddedAtlasResourceDefs = embeddedAtlasServiceDef.getResources(); - embeddedAtlasAccessTypes = embeddedAtlasServiceDef.getAccessTypes(); - if (checkResourcePresent(embeddedAtlasResourceDefs)) { - dbAtlasServiceDef.setResources(embeddedAtlasResourceDefs); - if (checkAccessPresent(embeddedAtlasAccessTypes)) { - dbAtlasServiceDef.setAccessTypes(embeddedAtlasAccessTypes); - } - } - - RangerServiceDefValidator validator = validatorFactory.getServiceDefValidator(svcStore); - validator.validate(dbAtlasServiceDef, Action.UPDATE); - ret = svcStore.updateServiceDef(dbAtlasServiceDef); - if (ret == null) { - logger.error("Error while updating " + EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_ATLAS_NAME - + " service-def"); - throw new RuntimeException("Error while updating " - + EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_ATLAS_NAME + " service-def"); - } else { - createDefaultPolicyToExistingService(); - updatePolicyForRelationshipType(); - } - } - } catch (Exception e) { - logger.error("Error while updating " + EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_ATLAS_NAME + " service-def",e); - } - - } - - private void createDefaultPolicyToExistingService() { - logger.info("==> createDefaultPolicyToExistingService "); - XXPortalUser xxPortalUser = daoMgr.getXXPortalUser().findByLoginId(LOGIN_ID_ADMIN); - Long currentUserId = xxPortalUser.getId(); - - XXServiceDef xXServiceDefObj = daoMgr.getXXServiceDef() - .findByName(EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_ATLAS_NAME); - if (xXServiceDefObj == null) { - logger.debug("ServiceDef not fount with name :" + EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_ATLAS_NAME); - return; - } - Long xServiceDefId = xXServiceDefObj.getId(); - List xxServices = daoMgr.getXXService().findByServiceDefId(xServiceDefId); - for (XXService xxService : xxServices) { - List xxPolicies = daoMgr.getXXPolicy().findByServiceId(xxService.getId()); - Boolean isPolicyPresent = true; - for (XXPolicy xxPolicy : xxPolicies) { - if (!xxPolicy.getName().equalsIgnoreCase(RESOURCE_DEF_NAME)) { - isPolicyPresent = false; - } else { - isPolicyPresent = true; - break; - } - } - if (!isPolicyPresent) { - XXPolicy xxPolicy = new XXPolicy(); - xxPolicy.setName(RESOURCE_DEF_NAME); - xxPolicy.setDescription(RESOURCE_DEF_NAME); - xxPolicy.setService(xxService.getId()); - xxPolicy.setPolicyPriority(RangerPolicy.POLICY_PRIORITY_NORMAL); - xxPolicy.setIsAuditEnabled(Boolean.TRUE); - xxPolicy.setIsEnabled(Boolean.TRUE); - xxPolicy.setPolicyType(RangerPolicy.POLICY_TYPE_ACCESS); - xxPolicy.setGuid(guidUtil.genGUID()); - xxPolicy.setAddedByUserId(currentUserId); - xxPolicy.setUpdatedByUserId(currentUserId); - RangerPolicy rangerPolicy = new RangerPolicy(); - RangerPolicyResourceSignature resourceSignature = new RangerPolicyResourceSignature(rangerPolicy); - xxPolicy.setResourceSignature(resourceSignature.getSignature()); - xxPolicy.setZoneId(1L); - XXPolicy createdPolicy = daoMgr.getXXPolicy().create(xxPolicy); - - XXPolicyItem xxPolicyItem = new XXPolicyItem(); - xxPolicyItem.setIsEnabled(Boolean.TRUE); - xxPolicyItem.setDelegateAdmin(Boolean.TRUE); - xxPolicyItem.setItemType(0); - xxPolicyItem.setOrder(0); - xxPolicyItem.setAddedByUserId(currentUserId); - xxPolicyItem.setUpdatedByUserId(currentUserId); - xxPolicyItem.setPolicyId(createdPolicy.getId()); - XXPolicyItem createdXXPolicyItem = daoMgr.getXXPolicyItem().create(xxPolicyItem); - - List accessTypes = Arrays.asList("add-relationship", "update-relationship", - "remove-relationship"); - for (int i = 0; i < accessTypes.size(); i++) { - XXAccessTypeDef xAccTypeDef = daoMgr.getXXAccessTypeDef().findByNameAndServiceId(accessTypes.get(i), - xxPolicy.getService()); - if (xAccTypeDef == null) { - throw new RuntimeException(accessTypes.get(i) + ": is not a valid access-type. policy='" - + xxPolicy.getName() + "' service='" + xxPolicy.getService() + "'"); - } - XXPolicyItemAccess xPolItemAcc = new XXPolicyItemAccess(); - xPolItemAcc.setIsAllowed(Boolean.TRUE); - xPolItemAcc.setType(xAccTypeDef.getId()); - xPolItemAcc.setOrder(i); - xPolItemAcc.setAddedByUserId(currentUserId); - xPolItemAcc.setUpdatedByUserId(currentUserId); - xPolItemAcc.setPolicyitemid(createdXXPolicyItem.getId()); - daoMgr.getXXPolicyItemAccess().create(xPolItemAcc); - } - - List groups = Arrays.asList(GROUP_PUBLIC); - for (int i = 0; i < groups.size(); i++) { - String group = groups.get(i); - if (StringUtils.isBlank(group)) { - continue; - } - XXGroup xGrp = daoMgr.getXXGroup().findByGroupName(group); - if (xGrp == null) { - throw new RuntimeException(group + ": group does not exist. policy='" + xxPolicy.getName() - + "' service='" + xxPolicy.getService() + "' group='" + group + "'"); - } - XXPolicyItemGroupPerm xGrpPerm = new XXPolicyItemGroupPerm(); - xGrpPerm.setGroupId(xGrp.getId()); - xGrpPerm.setPolicyItemId(createdXXPolicyItem.getId()); - xGrpPerm.setOrder(i); - xGrpPerm.setAddedByUserId(currentUserId); - xGrpPerm.setUpdatedByUserId(currentUserId); - daoMgr.getXXPolicyItemGroupPerm().create(xGrpPerm); - } - - for (int i = 0; i < ATLAS_RESOURCES.size(); i++) { - XXResourceDef xResDef = daoMgr.getXXResourceDef().findByNameAndPolicyId(ATLAS_RESOURCES.get(i), - createdPolicy.getId()); - if (xResDef == null) { - throw new RuntimeException(ATLAS_RESOURCES.get(i) + ": is not a valid resource-type. policy='" - + createdPolicy.getName() + "' service='" + createdPolicy.getService() + "'"); - } - XXPolicyResource xPolRes = new XXPolicyResource(); - - xPolRes.setAddedByUserId(currentUserId); - xPolRes.setUpdatedByUserId(currentUserId); - xPolRes.setIsExcludes(Boolean.FALSE); - xPolRes.setIsRecursive(Boolean.FALSE); - xPolRes.setPolicyId(createdPolicy.getId()); - xPolRes.setResDefId(xResDef.getId()); - xPolRes = daoMgr.getXXPolicyResource().create(xPolRes); - - XXPolicyResourceMap xPolResMap = new XXPolicyResourceMap(); - xPolResMap.setResourceId(xPolRes.getId()); - xPolResMap.setValue("*"); - xPolResMap.setOrder(i); - xPolResMap.setAddedByUserId(currentUserId); - xPolResMap.setUpdatedByUserId(currentUserId); - daoMgr.getXXPolicyResourceMap().create(xPolResMap); - } - logger.info("Creating policy for service id : " + xxService.getId()); - } - } - logger.info("<== createDefaultPolicyToExistingService "); - } - - private boolean checkResourcePresent(List resourceDefs) { - boolean ret = false; - for (RangerServiceDef.RangerResourceDef resourceDef : resourceDefs) { - if (ATLAS_RESOURCES.contains(resourceDef.getName())) { - ret = true; - break; - } - } - return ret; - } - - private boolean checkAccessPresent(List embeddedAtlasAccessTypes) { - boolean ret = false; - for (RangerServiceDef.RangerAccessTypeDef accessDef : embeddedAtlasAccessTypes) { - if (ATLAS_ACCESS_TYPES.contains(accessDef.getName())) { - ret = true; - break; - } - } - return ret; - } - - private void updatePolicyForRelationshipType() { - logger.info("===> updatePolicyForRelationshipType "); - XXPortalUser xxPortalUser = daoMgr.getXXPortalUser().findByLoginId(LOGIN_ID_ADMIN); - Long currentUserId = xxPortalUser.getId(); - XXServiceDef xXServiceDefObj = daoMgr.getXXServiceDef() - .findByName(EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_ATLAS_NAME); - if (xXServiceDefObj == null) { - logger.debug( - "xXServiceDefObj not found with name : " + EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_ATLAS_NAME); - return; - } - Long xServiceDefId = xXServiceDefObj.getId(); - XXResourceDef xxResourceDef = daoMgr.getXXResourceDef().findByNameAndServiceDefId(RESOURCE_DEF_NAME, - xServiceDefId); - List policyResources = daoMgr.getXXPolicyResource().findByResDefId(xxResourceDef.getId()); - for (XXPolicyResource xxPolicyResource : policyResources) { - XXPolicy xxPolicy = daoMgr.getXXPolicy().getById(xxPolicyResource.getPolicyid()); - List xxPolicyItems = daoMgr.getXXPolicyItem().findByPolicyId(xxPolicy.getId()); - for (XXPolicyItem xxPolicyItem : xxPolicyItems) { - XXGroup xxGroup = daoMgr.getXXGroup().findByGroupName(GROUP_PUBLIC); - if (xxGroup == null) { - logger.error("Group name 'public' not found in database"); - return; - } - Long publicGroupId = xxGroup.getId(); - XXPolicyItemGroupPerm xxPolicyItemGroupPerm = new XXPolicyItemGroupPerm(); - xxPolicyItemGroupPerm.setPolicyItemId(xxPolicyItem.getId()); - xxPolicyItemGroupPerm.setGroupId(publicGroupId); - xxPolicyItemGroupPerm.setOrder(0); - xxPolicyItemGroupPerm.setAddedByUserId(currentUserId); - xxPolicyItemGroupPerm.setUpdatedByUserId(currentUserId); - daoMgr.getXXPolicyItemGroupPerm().create(xxPolicyItemGroupPerm); - } - } - logger.info("<=== updatePolicyForRelationshipType "); - } + private static final Logger logger = LoggerFactory.getLogger(PatchForAtlasResourceAndAccessTypeUpdate_J10016.class); + + private static final String RESOURCE_DEF_NAME = "all - relationship-type, end-one-entity-type, end-one-entity-classification, end-one-entity, end-two-entity-type, end-two-entity-classification, end-two-entity"; + private static final List ATLAS_RESOURCES = new ArrayList<>(Arrays.asList("relationship-type", "end-one-entity-type", "end-one-entity-classification", "end-one-entity", "end-two-entity-type", "end-two-entity-classification", "end-two-entity")); + private static final List ATLAS_ACCESS_TYPES = new ArrayList<>(Arrays.asList("add-relationship", "update-relationship", "remove-relationship")); + private static final String LOGIN_ID_ADMIN = "admin"; + private static final String GROUP_PUBLIC = "public"; + + @Autowired + RangerDaoManager daoMgr; + + @Autowired + ServiceDBStore svcDBStore; + + @Autowired + GUIDUtil guidUtil; + + @Autowired + JSONUtil jsonUtil; + + @Autowired + StringUtil stringUtil; + + @Autowired + RangerValidatorFactory validatorFactory; + + @Autowired + ServiceDBStore svcStore; + + @Autowired + RangerPolicyService policyService; + + public static void main(String[] args) { + logger.info("main()"); + + try { + PatchForAtlasResourceAndAccessTypeUpdate_J10016 loader = (PatchForAtlasResourceAndAccessTypeUpdate_J10016) CLIUtil.getBean(PatchForAtlasResourceAndAccessTypeUpdate_J10016.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); + } + } + + @Override + public void init() throws Exception { + // Do Nothing + } + + @Override + public void printStats() { + logger.info("AtlasResourceAndAccessTypeUpdate data "); + } + + @Override + public void execLoad() { + logger.info("==> PatchForAtlasResourceAndAccessTypeUpdate.execLoad()"); + + try { + updateAtlasResourceAndAccessType(); + } catch (Exception e) { + logger.error("Error while updateAtlasResourceAndAccessType()data.", e); + } + + logger.info("<== PatchForAtlasResourceAndAccessTypeUpdate.execLoad()"); + } + + private void updateAtlasResourceAndAccessType() { + try { + RangerServiceDef embeddedAtlasServiceDef = EmbeddedServiceDefsUtil.instance().getEmbeddedServiceDef(EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_ATLAS_NAME); + + if (embeddedAtlasServiceDef != null) { + XXServiceDef xXServiceDefObj = daoMgr.getXXServiceDef().findByName(EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_ATLAS_NAME); + + if (xXServiceDefObj == null) { + logger.info("service-def not found. No patching is needed"); + return; + } + + RangerServiceDef dbAtlasServiceDef = svcDBStore.getServiceDefByName(EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_ATLAS_NAME); + List embeddedAtlasResourceDefs = embeddedAtlasServiceDef.getResources(); + List embeddedAtlasAccessTypes = embeddedAtlasServiceDef.getAccessTypes(); + + if (checkResourcePresent(embeddedAtlasResourceDefs)) { + dbAtlasServiceDef.setResources(embeddedAtlasResourceDefs); + + if (checkAccessPresent(embeddedAtlasAccessTypes)) { + dbAtlasServiceDef.setAccessTypes(embeddedAtlasAccessTypes); + } + } + + RangerServiceDefValidator validator = validatorFactory.getServiceDefValidator(svcStore); + + validator.validate(dbAtlasServiceDef, Action.UPDATE); + + RangerServiceDef ret = svcStore.updateServiceDef(dbAtlasServiceDef); + + if (ret == null) { + logger.error("Error while updating {} service-def", EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_ATLAS_NAME); + + throw new RuntimeException("Error while updating " + EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_ATLAS_NAME + " service-def"); + } else { + createDefaultPolicyToExistingService(); + updatePolicyForRelationshipType(); + } + } + } catch (Exception e) { + logger.error("Error while updating {} service-def", EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_ATLAS_NAME, e); + } + } + + private void createDefaultPolicyToExistingService() { + logger.info("==> createDefaultPolicyToExistingService "); + + XXPortalUser xxPortalUser = daoMgr.getXXPortalUser().findByLoginId(LOGIN_ID_ADMIN); + Long currentUserId = xxPortalUser.getId(); + XXServiceDef xXServiceDefObj = daoMgr.getXXServiceDef().findByName(EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_ATLAS_NAME); + + if (xXServiceDefObj == null) { + logger.debug("ServiceDef not fount with name :{}", EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_ATLAS_NAME); + + return; + } + + Long xServiceDefId = xXServiceDefObj.getId(); + List xxServices = daoMgr.getXXService().findByServiceDefId(xServiceDefId); + + for (XXService xxService : xxServices) { + List xxPolicies = daoMgr.getXXPolicy().findByServiceId(xxService.getId()); + boolean isPolicyPresent = true; + + for (XXPolicy xxPolicy : xxPolicies) { + if (!xxPolicy.getName().equalsIgnoreCase(RESOURCE_DEF_NAME)) { + isPolicyPresent = false; + } else { + isPolicyPresent = true; + break; + } + } + + if (!isPolicyPresent) { + XXPolicy xxPolicy = new XXPolicy(); + + xxPolicy.setName(RESOURCE_DEF_NAME); + xxPolicy.setDescription(RESOURCE_DEF_NAME); + xxPolicy.setService(xxService.getId()); + xxPolicy.setPolicyPriority(RangerPolicy.POLICY_PRIORITY_NORMAL); + xxPolicy.setIsAuditEnabled(Boolean.TRUE); + xxPolicy.setIsEnabled(Boolean.TRUE); + xxPolicy.setPolicyType(RangerPolicy.POLICY_TYPE_ACCESS); + xxPolicy.setGuid(guidUtil.genGUID()); + xxPolicy.setAddedByUserId(currentUserId); + xxPolicy.setUpdatedByUserId(currentUserId); + + RangerPolicy rangerPolicy = new RangerPolicy(); + RangerPolicyResourceSignature resourceSignature = new RangerPolicyResourceSignature(rangerPolicy); + + xxPolicy.setResourceSignature(resourceSignature.getSignature()); + xxPolicy.setZoneId(1L); + XXPolicy createdPolicy = daoMgr.getXXPolicy().create(xxPolicy); + + XXPolicyItem xxPolicyItem = new XXPolicyItem(); + + xxPolicyItem.setIsEnabled(Boolean.TRUE); + xxPolicyItem.setDelegateAdmin(Boolean.TRUE); + xxPolicyItem.setItemType(0); + xxPolicyItem.setOrder(0); + xxPolicyItem.setAddedByUserId(currentUserId); + xxPolicyItem.setUpdatedByUserId(currentUserId); + xxPolicyItem.setPolicyId(createdPolicy.getId()); + + XXPolicyItem createdXXPolicyItem = daoMgr.getXXPolicyItem().create(xxPolicyItem); + List accessTypes = Arrays.asList("add-relationship", "update-relationship", "remove-relationship"); + + for (int i = 0; i < accessTypes.size(); i++) { + XXAccessTypeDef xAccTypeDef = daoMgr.getXXAccessTypeDef().findByNameAndServiceId(accessTypes.get(i), xxPolicy.getService()); + + if (xAccTypeDef == null) { + throw new RuntimeException(accessTypes.get(i) + ": is not a valid access-type. policy='" + xxPolicy.getName() + "' service='" + xxPolicy.getService() + "'"); + } + + XXPolicyItemAccess xPolItemAcc = new XXPolicyItemAccess(); + + xPolItemAcc.setIsAllowed(Boolean.TRUE); + xPolItemAcc.setType(xAccTypeDef.getId()); + xPolItemAcc.setOrder(i); + xPolItemAcc.setAddedByUserId(currentUserId); + xPolItemAcc.setUpdatedByUserId(currentUserId); + xPolItemAcc.setPolicyitemid(createdXXPolicyItem.getId()); + + daoMgr.getXXPolicyItemAccess().create(xPolItemAcc); + } + + List groups = Collections.singletonList(GROUP_PUBLIC); + + for (int i = 0; i < groups.size(); i++) { + String group = groups.get(i); + + if (StringUtils.isBlank(group)) { + continue; + } + + XXGroup xGrp = daoMgr.getXXGroup().findByGroupName(group); + + if (xGrp == null) { + throw new RuntimeException(group + ": group does not exist. policy='" + xxPolicy.getName() + "' service='" + xxPolicy.getService() + "' group='" + group + "'"); + } + + XXPolicyItemGroupPerm xGrpPerm = new XXPolicyItemGroupPerm(); + + xGrpPerm.setGroupId(xGrp.getId()); + xGrpPerm.setPolicyItemId(createdXXPolicyItem.getId()); + xGrpPerm.setOrder(i); + xGrpPerm.setAddedByUserId(currentUserId); + xGrpPerm.setUpdatedByUserId(currentUserId); + + daoMgr.getXXPolicyItemGroupPerm().create(xGrpPerm); + } + + for (int i = 0; i < ATLAS_RESOURCES.size(); i++) { + XXResourceDef xResDef = daoMgr.getXXResourceDef().findByNameAndPolicyId(ATLAS_RESOURCES.get(i), createdPolicy.getId()); + + if (xResDef == null) { + throw new RuntimeException(ATLAS_RESOURCES.get(i) + ": is not a valid resource-type. policy='" + createdPolicy.getName() + "' service='" + createdPolicy.getService() + "'"); + } + + XXPolicyResource xPolRes = new XXPolicyResource(); + + xPolRes.setAddedByUserId(currentUserId); + xPolRes.setUpdatedByUserId(currentUserId); + xPolRes.setIsExcludes(Boolean.FALSE); + xPolRes.setIsRecursive(Boolean.FALSE); + xPolRes.setPolicyId(createdPolicy.getId()); + xPolRes.setResDefId(xResDef.getId()); + + xPolRes = daoMgr.getXXPolicyResource().create(xPolRes); + + XXPolicyResourceMap xPolResMap = new XXPolicyResourceMap(); + + xPolResMap.setResourceId(xPolRes.getId()); + xPolResMap.setValue("*"); + xPolResMap.setOrder(i); + xPolResMap.setAddedByUserId(currentUserId); + xPolResMap.setUpdatedByUserId(currentUserId); + + daoMgr.getXXPolicyResourceMap().create(xPolResMap); + } + + logger.info("Creating policy for service id : {}", xxService.getId()); + } + } + + logger.info("<== createDefaultPolicyToExistingService "); + } + + private boolean checkResourcePresent(List resourceDefs) { + boolean ret = false; + + for (RangerServiceDef.RangerResourceDef resourceDef : resourceDefs) { + if (ATLAS_RESOURCES.contains(resourceDef.getName())) { + ret = true; + break; + } + } + + return ret; + } + + private boolean checkAccessPresent(List embeddedAtlasAccessTypes) { + boolean ret = false; + + for (RangerServiceDef.RangerAccessTypeDef accessDef : embeddedAtlasAccessTypes) { + if (ATLAS_ACCESS_TYPES.contains(accessDef.getName())) { + ret = true; + break; + } + } + + return ret; + } + + private void updatePolicyForRelationshipType() { + logger.info("===> updatePolicyForRelationshipType "); + + XXPortalUser xxPortalUser = daoMgr.getXXPortalUser().findByLoginId(LOGIN_ID_ADMIN); + Long currentUserId = xxPortalUser.getId(); + XXServiceDef xXServiceDefObj = daoMgr.getXXServiceDef().findByName(EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_ATLAS_NAME); + + if (xXServiceDefObj == null) { + logger.debug("xXServiceDefObj not found with name : {}", EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_ATLAS_NAME); + + return; + } + + Long xServiceDefId = xXServiceDefObj.getId(); + XXResourceDef xxResourceDef = daoMgr.getXXResourceDef().findByNameAndServiceDefId(RESOURCE_DEF_NAME, xServiceDefId); + List policyResources = daoMgr.getXXPolicyResource().findByResDefId(xxResourceDef.getId()); + + for (XXPolicyResource xxPolicyResource : policyResources) { + XXPolicy xxPolicy = daoMgr.getXXPolicy().getById(xxPolicyResource.getPolicyid()); + List xxPolicyItems = daoMgr.getXXPolicyItem().findByPolicyId(xxPolicy.getId()); + + for (XXPolicyItem xxPolicyItem : xxPolicyItems) { + XXGroup xxGroup = daoMgr.getXXGroup().findByGroupName(GROUP_PUBLIC); + + if (xxGroup == null) { + logger.error("Group name 'public' not found in database"); + return; + } + + Long publicGroupId = xxGroup.getId(); + XXPolicyItemGroupPerm xxPolicyItemGroupPerm = new XXPolicyItemGroupPerm(); + + xxPolicyItemGroupPerm.setPolicyItemId(xxPolicyItem.getId()); + xxPolicyItemGroupPerm.setGroupId(publicGroupId); + xxPolicyItemGroupPerm.setOrder(0); + xxPolicyItemGroupPerm.setAddedByUserId(currentUserId); + xxPolicyItemGroupPerm.setUpdatedByUserId(currentUserId); + + daoMgr.getXXPolicyItemGroupPerm().create(xxPolicyItemGroupPerm); + } + } + + logger.info("<=== updatePolicyForRelationshipType "); + } } diff --git a/security-admin/src/main/java/org/apache/ranger/patch/PatchForAtlasServiceDefUpdate_J10013.java b/security-admin/src/main/java/org/apache/ranger/patch/PatchForAtlasServiceDefUpdate_J10013.java index 36d24c6050..49ef45195c 100644 --- a/security-admin/src/main/java/org/apache/ranger/patch/PatchForAtlasServiceDefUpdate_J10013.java +++ b/security-admin/src/main/java/org/apache/ranger/patch/PatchForAtlasServiceDefUpdate_J10013.java @@ -17,13 +17,6 @@ package org.apache.ranger.patch; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.HashSet; -import java.util.List; -import java.util.Objects; -import java.util.Set; import org.apache.commons.collections.CollectionUtils; import org.apache.ranger.biz.ServiceDBStore; import org.apache.ranger.common.RangerValidatorFactory; @@ -46,222 +39,267 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.HashSet; +import java.util.List; +import java.util.Objects; +import java.util.Set; + @Component public class PatchForAtlasServiceDefUpdate_J10013 extends BaseLoader { - private static final Logger LOG = LoggerFactory.getLogger(PatchForAtlasServiceDefUpdate_J10013.class); - private static final int MAX_ACCESS_TYPES_IN_SERVICE_DEF = 1000; - @Autowired - RangerDaoManager daoMgr; - - @Autowired - ServiceDBStore svcDBStore; - - @Autowired - RangerServiceService svcService; - - @Autowired - RangerValidatorFactory validatorFactory; - - public static void main(String[] args) { - LOG.info("main()"); - try { - PatchForAtlasServiceDefUpdate_J10013 loader = (PatchForAtlasServiceDefUpdate_J10013) CLIUtil.getBean(PatchForAtlasServiceDefUpdate_J10013.class); - loader.init(); - while (loader.isMoreToProcess()) { - loader.load(); - } - LOG.info("Load complete. Exiting!!!"); - System.exit(0); - } catch (Exception e) { - LOG.error("Error loading", e); - System.exit(1); - } - } - - @Override - public void init() throws Exception { - } - - @Override - public void execLoad() { - LOG.info("==> PatchForAtlasServiceDefUpdate.execLoad()"); - try { - updateAtlasServiceDef(); - } catch (Exception e) { - LOG.error("Error whille updateAtlasServiceDef()data.", e); + private static final Logger LOG = LoggerFactory.getLogger(PatchForAtlasServiceDefUpdate_J10013.class); + + private static final int MAX_ACCESS_TYPES_IN_SERVICE_DEF = 1000; + + @Autowired + RangerDaoManager daoMgr; + + @Autowired + ServiceDBStore svcDBStore; + + @Autowired + RangerServiceService svcService; + + @Autowired + RangerValidatorFactory validatorFactory; + + public static void main(String[] args) { + LOG.info("main()"); + + try { + PatchForAtlasServiceDefUpdate_J10013 loader = (PatchForAtlasServiceDefUpdate_J10013) CLIUtil.getBean(PatchForAtlasServiceDefUpdate_J10013.class); + + loader.init(); + + while (loader.isMoreToProcess()) { + loader.load(); + } + + LOG.info("Load complete. Exiting!!!"); + + System.exit(0); + } catch (Exception e) { + LOG.error("Error loading", e); + + System.exit(1); + } + } + + @Override + public void init() throws Exception { + } + + @Override + public void printStats() { + LOG.info("PatchForAtlasServiceDefUpdate data "); + } + + @Override + public void execLoad() { + LOG.info("==> PatchForAtlasServiceDefUpdate.execLoad()"); + + try { + updateAtlasServiceDef(); + } catch (Exception e) { + LOG.error("Error whille updateAtlasServiceDef()data.", e); + System.exit(1); - } - LOG.info("<== PatchForAtlasServiceDefUpdate.execLoad()"); - } - - @Override - public void printStats() { - LOG.info("PatchForAtlasServiceDefUpdate data "); - } - - private void updateAtlasServiceDef() throws Exception{ - String serviceDefName=EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_ATLAS_NAME; - XXServiceDefDao serviceDefDao = daoMgr.getXXServiceDef(); - XXServiceDef serviceDef = serviceDefDao.findByName(serviceDefName); - // if service-def named 'atlas' does not exist then no need to process this patch further. - if(serviceDef == null) { - LOG.info(serviceDefName + ": service-def not found. No patching is needed"); - return; - } - // if older atlas service-def doesn't exist then no need to process this patch further. - if(!checkIfHasOlderServiceDef(serviceDef)) { - LOG.info("Older version of "+serviceDefName + " service-def not found. No patching is needed"); - return; - } - String suffix = null; - for (int i = 1; true; i++) { - suffix = ".v" + i; - if (serviceDefDao.findByName(serviceDefName + suffix) == null) { - break; - } - } - String serviceDefNewName = serviceDefName + suffix; - LOG.info("Renaming service-def " + serviceDefName + " as " + serviceDefNewName); - RangerServiceDef dbAtlasServiceDef = svcDBStore.getServiceDefByName(EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_ATLAS_NAME); - if (EmbeddedServiceDefsUtil.instance().getTagServiceDefId() != -1) { - RangerServiceDef dbTagServiceDef; - try { - dbTagServiceDef = svcDBStore.getServiceDef(EmbeddedServiceDefsUtil.instance().getTagServiceDefId()); - if(dbTagServiceDef!=null) { - String prefix = serviceDefName + AbstractServiceStore.COMPONENT_ACCESSTYPE_SEPARATOR; - String newPrefix = serviceDefNewName + AbstractServiceStore.COMPONENT_ACCESSTYPE_SEPARATOR; - - List svcDefAccessTypes = dbAtlasServiceDef.getAccessTypes(); - List tagDefAccessTypes = dbTagServiceDef.getAccessTypes(); - long itemIdOffset = serviceDef.getId() * (MAX_ACCESS_TYPES_IN_SERVICE_DEF + 1); - - boolean updateNeeded = updateTagAccessTypeDefs(svcDefAccessTypes, tagDefAccessTypes, itemIdOffset, prefix,newPrefix); - if(updateNeeded) { - svcDBStore.updateServiceDef(dbTagServiceDef); - } - } - } catch (Exception e) { - LOG.error("updateAtlasServiceDef:" + serviceDef.getName() + "): could not find TAG ServiceDef.. ", e); - } - } - serviceDef.setName(serviceDefNewName); - serviceDef.setDisplayName(serviceDefNewName); - serviceDefDao.update(serviceDef); - LOG.info("Renamed service-def " + serviceDefName + " as " + serviceDefNewName); - XXServiceDao serviceDao = daoMgr.getXXService(); - List services = serviceDao.findByServiceDefId(serviceDef.getId()); - if (CollectionUtils.isNotEmpty(services)) { - for (XXService service : services) { - String serviceName = service.getName(); - String serviceNewName = serviceName + suffix; - LOG.info("Renaming service " + serviceName + " as " + serviceNewName); - if (serviceDao.findIdByName(serviceNewName) != null) { - LOG.warn("Another service named " + serviceNewName + " already exists. Not renaming " + serviceName); - continue; - } - service.setName(serviceNewName); - service.setDisplayName(serviceNewName); - serviceDao.update(service); - LOG.info("Renamed service " + serviceName + " as " + serviceNewName); - } - } - } - - /* - * This method shall check whether atlas service def resources and access types - * are matching with older service def resources and access types or not. - * returns true if all resources and access types matches with older service def - * resources and access types. - */ - private boolean checkIfHasOlderServiceDef(XXServiceDef serviceDef) { - boolean result = true; - Set atlasResources = new HashSet<>(Arrays.asList("entity", "type", "operation", "taxonomy", "term")); - XXResourceDefDao resourceDefDao=daoMgr.getXXResourceDef(); - List xxResourceDefs = resourceDefDao.findByServiceDefId(serviceDef.getId()); - for (XXResourceDef xxResourceDef : xxResourceDefs) { - if(! atlasResources.contains(xxResourceDef.getName())) { - result = false; - break; - } - } - if(result){ - Set atlasAccessTypes = new HashSet<>(Arrays.asList("read", "create", "update", "delete", "all")); - XXAccessTypeDefDao accessTypeDefDao=daoMgr.getXXAccessTypeDef(); - List xxAccessTypeDefs = accessTypeDefDao.findByServiceDefId(serviceDef.getId()); - for (XXAccessTypeDef xxAccessTypeDef : xxAccessTypeDefs) { - if(! atlasAccessTypes.contains(xxAccessTypeDef.getName())) { - result = false; - break; - } - } - } - return result; - } - - private boolean updateTagAccessTypeDefs(List svcDefAccessTypes, - List tagDefAccessTypes, long itemIdOffset, String prefix,String newPrefix) { - List toUpdate = new ArrayList<>(); - for (RangerServiceDef.RangerAccessTypeDef tagAccessType : tagDefAccessTypes) { - if (tagAccessType.getName().startsWith(prefix)) { - long svcAccessTypeItemId = tagAccessType.getItemId() - itemIdOffset; - RangerServiceDef.RangerAccessTypeDef svcAccessType = findAccessTypeDef(svcAccessTypeItemId,svcDefAccessTypes); - if (svcAccessType != null) { - if (updateTagAccessTypeDef(tagAccessType, svcAccessType, newPrefix)) { - toUpdate.add(tagAccessType); - } - } - } - } - boolean updateNeeded = false; - if (CollectionUtils.isNotEmpty(toUpdate)) { - updateNeeded = true; - } - return updateNeeded; - } - - private RangerServiceDef.RangerAccessTypeDef findAccessTypeDef(long itemId, List accessTypeDefs) { - RangerServiceDef.RangerAccessTypeDef ret = null; - for (RangerServiceDef.RangerAccessTypeDef accessTypeDef : accessTypeDefs) { - if (itemId == accessTypeDef.getItemId()) { - ret = accessTypeDef; - break; - } - } - return ret; - } - - private boolean updateTagAccessTypeDef(RangerServiceDef.RangerAccessTypeDef tagAccessType, RangerServiceDef.RangerAccessTypeDef svcAccessType, String newPrefix) { - boolean isUpdated = false; - if (!Objects.equals(tagAccessType.getName().substring(newPrefix.length()), svcAccessType.getName())) { - isUpdated = true; - } else { - Collection tagImpliedGrants = tagAccessType.getImpliedGrants(); - Collection svcImpliedGrants = svcAccessType.getImpliedGrants(); - int tagImpliedGrantsLen = tagImpliedGrants == null ? 0 : tagImpliedGrants.size(); - int svcImpliedGrantsLen = svcImpliedGrants == null ? 0 : svcImpliedGrants.size(); - if (tagImpliedGrantsLen != svcImpliedGrantsLen) { - isUpdated = true; - } else if (tagImpliedGrantsLen > 0) { - for (String svcImpliedGrant : svcImpliedGrants) { - if (!tagImpliedGrants.contains(newPrefix + svcImpliedGrant)) { - isUpdated = true; - break; - } - } - } - } - if (isUpdated) { - tagAccessType.setName(newPrefix + svcAccessType.getName()); - tagAccessType.setLabel(svcAccessType.getLabel()); - tagAccessType.setRbKeyLabel(svcAccessType.getRbKeyLabel()); - tagAccessType.setImpliedGrants(new HashSet()); - if (CollectionUtils.isNotEmpty(svcAccessType.getImpliedGrants())) { - for (String svcImpliedGrant : svcAccessType.getImpliedGrants()) { - tagAccessType.getImpliedGrants().add(newPrefix + svcImpliedGrant); - } - } - } - return isUpdated; - } + } + + LOG.info("<== PatchForAtlasServiceDefUpdate.execLoad()"); + } + + private void updateAtlasServiceDef() throws Exception { + String serviceDefName = EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_ATLAS_NAME; + XXServiceDefDao serviceDefDao = daoMgr.getXXServiceDef(); + XXServiceDef serviceDef = serviceDefDao.findByName(serviceDefName); + + // if service-def named 'atlas' does not exist then no need to process this patch further. + if (serviceDef == null) { + LOG.info("Service-def {} not found. No patching is needed", serviceDefName); + return; + } + + // if older atlas service-def doesn't exist then no need to process this patch further. + if (!checkIfHasOlderServiceDef(serviceDef)) { + LOG.info("Older version of {} service-def not found. No patching is needed", serviceDefName); + + return; + } + + String suffix; + + for (int i = 1; true; i++) { + suffix = ".v" + i; + + if (serviceDefDao.findByName(serviceDefName + suffix) == null) { + break; + } + } + + String serviceDefNewName = serviceDefName + suffix; + + LOG.info("Renaming service-def {} as {}", serviceDefName, serviceDefNewName); + + RangerServiceDef dbAtlasServiceDef = svcDBStore.getServiceDefByName(EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_ATLAS_NAME); + + if (EmbeddedServiceDefsUtil.instance().getTagServiceDefId() != -1) { + try { + RangerServiceDef dbTagServiceDef = svcDBStore.getServiceDef(EmbeddedServiceDefsUtil.instance().getTagServiceDefId()); + + if (dbTagServiceDef != null) { + String prefix = serviceDefName + AbstractServiceStore.COMPONENT_ACCESSTYPE_SEPARATOR; + String newPrefix = serviceDefNewName + AbstractServiceStore.COMPONENT_ACCESSTYPE_SEPARATOR; + + List svcDefAccessTypes = dbAtlasServiceDef.getAccessTypes(); + List tagDefAccessTypes = dbTagServiceDef.getAccessTypes(); + long itemIdOffset = serviceDef.getId() * (MAX_ACCESS_TYPES_IN_SERVICE_DEF + 1); + boolean updateNeeded = updateTagAccessTypeDefs(svcDefAccessTypes, tagDefAccessTypes, itemIdOffset, prefix, newPrefix); + + if (updateNeeded) { + svcDBStore.updateServiceDef(dbTagServiceDef); + } + } + } catch (Exception e) { + LOG.error("updateAtlasServiceDef:{}: could not find TAG ServiceDef.. ", serviceDef.getName(), e); + } + } + + serviceDef.setName(serviceDefNewName); + serviceDef.setDisplayName(serviceDefNewName); + serviceDefDao.update(serviceDef); + + LOG.info("Renamed service-def {} as {}", serviceDefName, serviceDefNewName); + + XXServiceDao serviceDao = daoMgr.getXXService(); + List services = serviceDao.findByServiceDefId(serviceDef.getId()); + + if (CollectionUtils.isNotEmpty(services)) { + for (XXService service : services) { + String serviceName = service.getName(); + String serviceNewName = serviceName + suffix; + + LOG.info("Renaming service {} as {}", serviceName, serviceNewName); + + if (serviceDao.findIdByName(serviceNewName) != null) { + LOG.warn("Another service named {} already exists. Not renaming {}", serviceNewName, serviceName); + continue; + } + + service.setName(serviceNewName); + service.setDisplayName(serviceNewName); + serviceDao.update(service); + + LOG.info("Renamed service {} as {}", serviceName, serviceNewName); + } + } + } + + /* + * This method shall check whether atlas service def resources and access types + * are matching with older service def resources and access types or not. + * returns true if all resources and access types matches with older service def + * resources and access types. + */ + private boolean checkIfHasOlderServiceDef(XXServiceDef serviceDef) { + boolean result = true; + Set atlasResources = new HashSet<>(Arrays.asList("entity", "type", "operation", "taxonomy", "term")); + XXResourceDefDao resourceDefDao = daoMgr.getXXResourceDef(); + List xxResourceDefs = resourceDefDao.findByServiceDefId(serviceDef.getId()); + + for (XXResourceDef xxResourceDef : xxResourceDefs) { + if (!atlasResources.contains(xxResourceDef.getName())) { + result = false; + break; + } + } + + if (result) { + Set atlasAccessTypes = new HashSet<>(Arrays.asList("read", "create", "update", "delete", "all")); + XXAccessTypeDefDao accessTypeDefDao = daoMgr.getXXAccessTypeDef(); + List xxAccessTypeDefs = accessTypeDefDao.findByServiceDefId(serviceDef.getId()); + + for (XXAccessTypeDef xxAccessTypeDef : xxAccessTypeDefs) { + if (!atlasAccessTypes.contains(xxAccessTypeDef.getName())) { + result = false; + break; + } + } + } + + return result; + } + + private boolean updateTagAccessTypeDefs(List svcDefAccessTypes, List tagDefAccessTypes, long itemIdOffset, String prefix, String newPrefix) { + List toUpdate = new ArrayList<>(); + + for (RangerServiceDef.RangerAccessTypeDef tagAccessType : tagDefAccessTypes) { + if (tagAccessType.getName().startsWith(prefix)) { + long svcAccessTypeItemId = tagAccessType.getItemId() - itemIdOffset; + RangerServiceDef.RangerAccessTypeDef svcAccessType = findAccessTypeDef(svcAccessTypeItemId, svcDefAccessTypes); + + if (svcAccessType != null) { + if (updateTagAccessTypeDef(tagAccessType, svcAccessType, newPrefix)) { + toUpdate.add(tagAccessType); + } + } + } + } + + return CollectionUtils.isNotEmpty(toUpdate); + } + + private RangerServiceDef.RangerAccessTypeDef findAccessTypeDef(long itemId, List accessTypeDefs) { + RangerServiceDef.RangerAccessTypeDef ret = null; + + for (RangerServiceDef.RangerAccessTypeDef accessTypeDef : accessTypeDefs) { + if (itemId == accessTypeDef.getItemId()) { + ret = accessTypeDef; + break; + } + } + + return ret; + } + + private boolean updateTagAccessTypeDef(RangerServiceDef.RangerAccessTypeDef tagAccessType, RangerServiceDef.RangerAccessTypeDef svcAccessType, String newPrefix) { + boolean isUpdated = false; + + if (!Objects.equals(tagAccessType.getName().substring(newPrefix.length()), svcAccessType.getName())) { + isUpdated = true; + } else { + Collection tagImpliedGrants = tagAccessType.getImpliedGrants(); + Collection svcImpliedGrants = svcAccessType.getImpliedGrants(); + int tagImpliedGrantsLen = tagImpliedGrants == null ? 0 : tagImpliedGrants.size(); + int svcImpliedGrantsLen = svcImpliedGrants == null ? 0 : svcImpliedGrants.size(); + + if (tagImpliedGrantsLen != svcImpliedGrantsLen) { + isUpdated = true; + } else if (tagImpliedGrantsLen > 0) { + for (String svcImpliedGrant : svcImpliedGrants) { + if (!tagImpliedGrants.contains(newPrefix + svcImpliedGrant)) { + isUpdated = true; + break; + } + } + } + } + + if (isUpdated) { + tagAccessType.setName(newPrefix + svcAccessType.getName()); + tagAccessType.setLabel(svcAccessType.getLabel()); + tagAccessType.setRbKeyLabel(svcAccessType.getRbKeyLabel()); + tagAccessType.setImpliedGrants(new HashSet<>()); + + if (CollectionUtils.isNotEmpty(svcAccessType.getImpliedGrants())) { + for (String svcImpliedGrant : svcAccessType.getImpliedGrants()) { + tagAccessType.getImpliedGrants().add(newPrefix + svcImpliedGrant); + } + } + } + return isUpdated; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/patch/PatchForAtlasToAddEntityLabelAndBusinessMetadata_J10034.java b/security-admin/src/main/java/org/apache/ranger/patch/PatchForAtlasToAddEntityLabelAndBusinessMetadata_J10034.java index e356131f59..ca57f4417c 100644 --- a/security-admin/src/main/java/org/apache/ranger/patch/PatchForAtlasToAddEntityLabelAndBusinessMetadata_J10034.java +++ b/security-admin/src/main/java/org/apache/ranger/patch/PatchForAtlasToAddEntityLabelAndBusinessMetadata_J10034.java @@ -18,11 +18,6 @@ package org.apache.ranger.patch; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; import org.apache.ranger.biz.ServiceDBStore; import org.apache.ranger.common.GUIDUtil; import org.apache.ranger.common.JSONUtil; @@ -53,24 +48,27 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + @Component public class PatchForAtlasToAddEntityLabelAndBusinessMetadata_J10034 extends BaseLoader { private static final Logger logger = LoggerFactory.getLogger(PatchForAtlasToAddEntityLabelAndBusinessMetadata_J10034.class); - private static final String RESOURCE_DEF_ENTITY_LABEL = "all - entity-type, entity-classification, entity, entity-label"; + private static final String RESOURCE_DEF_ENTITY_LABEL = "all - entity-type, entity-classification, entity, entity-label"; private static final String RESOURCE_DEF_ENTITY_BUSINESS_METADATA = "all - entity-type, entity-classification, entity, entity-business-metadata"; - private static final List ATLAS_RESOURCES = new ArrayList<>( - Arrays.asList("entity-label", "entity-business-metadata")); - private static final List ATLAS_ACCESS_TYPES = new ArrayList<>( - Arrays.asList("admin-purge", "entity-add-label", "entity-remove-label", "entity-update-business-metadata")); + private static final List ATLAS_RESOURCES = new ArrayList<>(Arrays.asList("entity-label", "entity-business-metadata")); + private static final List ATLAS_ACCESS_TYPES = new ArrayList<>(Arrays.asList("admin-purge", "entity-add-label", "entity-remove-label", "entity-update-business-metadata")); - private static final List ATLAS_RESOURCE_LABEL = new ArrayList<>( - Arrays.asList("entity-type", "entity-classification", "entity", "entity-label")); - private static final List ATLAS_RESOURCE_BUSINESS_METADATA = new ArrayList<>( - Arrays.asList("entity-type", "entity-classification", "entity", "entity-business-metadata")); - private static final String LOGIN_ID_ADMIN = "admin"; - private static final String GROUP_PUBLIC = "public"; + private static final List ATLAS_RESOURCE_LABEL = new ArrayList<>(Arrays.asList("entity-type", "entity-classification", "entity", "entity-label")); + private static final List ATLAS_RESOURCE_BUSINESS_METADATA = new ArrayList<>(Arrays.asList("entity-type", "entity-classification", "entity", "entity-business-metadata")); + private static final String LOGIN_ID_ADMIN = "admin"; + private static final String GROUP_PUBLIC = "public"; @Autowired RangerDaoManager daoMgr; @@ -98,17 +96,22 @@ public class PatchForAtlasToAddEntityLabelAndBusinessMetadata_J10034 extends Bas public static void main(String[] args) { logger.info("main()"); + try { - PatchForAtlasToAddEntityLabelAndBusinessMetadata_J10034 loader = (PatchForAtlasToAddEntityLabelAndBusinessMetadata_J10034) CLIUtil - .getBean(PatchForAtlasToAddEntityLabelAndBusinessMetadata_J10034.class); + PatchForAtlasToAddEntityLabelAndBusinessMetadata_J10034 loader = (PatchForAtlasToAddEntityLabelAndBusinessMetadata_J10034) CLIUtil.getBean(PatchForAtlasToAddEntityLabelAndBusinessMetadata_J10034.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); } } @@ -118,172 +121,191 @@ public void init() throws Exception { // Do Nothing } + @Override + public void printStats() { + logger.info("PatchForAtlasToAddEntityLabelAndBusinessMetadata Logs"); + } + @Override public void execLoad() { logger.info("==> PatchForAtlasToAddEntityLabelAndBusinessMetadata.execLoad()"); + try { addResourceEntityLabelAndEntityBusinessMetadataInServiceDef(); createDefaultPolicyForEntityLabelAndEntityBusinessMetadata(); } catch (Exception e) { - throw new RuntimeException( - "Error while updating " + EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_ATLAS_NAME + " service-def"); + throw new RuntimeException("Error while updating " + EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_ATLAS_NAME + " service-def"); } - logger.info("<== PatchForAtlasToAddEntityLabelAndBusinessMetadata.execLoad()"); - } - @Override - public void printStats() { - logger.info("PatchForAtlasToAddEntityLabelAndBusinessMetadata Logs"); + logger.info("<== PatchForAtlasToAddEntityLabelAndBusinessMetadata.execLoad()"); } private void addResourceEntityLabelAndEntityBusinessMetadataInServiceDef() throws Exception { - RangerServiceDef ret = null; - RangerServiceDef embeddedAtlasServiceDef = null; - XXServiceDef xXServiceDefObj = null; - RangerServiceDef dbAtlasServiceDef = null; - List embeddedAtlasResourceDefs = null; - List embeddedAtlasAccessTypes = null; - - embeddedAtlasServiceDef = EmbeddedServiceDefsUtil.instance() - .getEmbeddedServiceDef(EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_ATLAS_NAME); + RangerServiceDef embeddedAtlasServiceDef = EmbeddedServiceDefsUtil.instance().getEmbeddedServiceDef(EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_ATLAS_NAME); + if (embeddedAtlasServiceDef != null) { - xXServiceDefObj = daoMgr.getXXServiceDef() - .findByName(EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_ATLAS_NAME); + XXServiceDef xXServiceDefObj = daoMgr.getXXServiceDef().findByName(EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_ATLAS_NAME); + if (xXServiceDefObj == null) { - logger.info(xXServiceDefObj + ": service-def not found. No patching is needed"); + logger.info("{} service-def not found. No patching is needed", EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_ATLAS_NAME); + return; } - dbAtlasServiceDef = svcDBStore.getServiceDefByName(EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_ATLAS_NAME); + RangerServiceDef dbAtlasServiceDef = svcDBStore.getServiceDefByName(EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_ATLAS_NAME); + List embeddedAtlasResourceDefs = embeddedAtlasServiceDef.getResources(); + List embeddedAtlasAccessTypes = embeddedAtlasServiceDef.getAccessTypes(); - embeddedAtlasResourceDefs = embeddedAtlasServiceDef.getResources(); - embeddedAtlasAccessTypes = embeddedAtlasServiceDef.getAccessTypes(); if (checkResourcePresent(embeddedAtlasResourceDefs)) { dbAtlasServiceDef.setResources(embeddedAtlasResourceDefs); + if (checkAccessPresent(embeddedAtlasAccessTypes)) { dbAtlasServiceDef.setAccessTypes(embeddedAtlasAccessTypes); } } RangerServiceDefValidator validator = validatorFactory.getServiceDefValidator(svcStore); + validator.validate(dbAtlasServiceDef, Action.UPDATE); - ret = svcStore.updateServiceDef(dbAtlasServiceDef); + + RangerServiceDef ret = svcStore.updateServiceDef(dbAtlasServiceDef); + if (ret == null) { - logger.error("Error while updating " + EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_ATLAS_NAME - + " service-def"); - throw new RuntimeException("Error while updating " - + EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_ATLAS_NAME + " service-def"); + logger.error("Error while updating {} service-def", EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_ATLAS_NAME); + + throw new RuntimeException("Error while updating " + EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_ATLAS_NAME + " service-def"); } } } private boolean checkResourcePresent(List resourceDefs) { boolean ret = false; + for (RangerServiceDef.RangerResourceDef resourceDef : resourceDefs) { if (ATLAS_RESOURCES.contains(resourceDef.getName())) { ret = true; break; } } + return ret; } private boolean checkAccessPresent(List embeddedAtlasAccessTypes) { boolean ret = false; + for (RangerServiceDef.RangerAccessTypeDef accessDef : embeddedAtlasAccessTypes) { if (ATLAS_ACCESS_TYPES.contains(accessDef.getName())) { ret = true; break; } } + return ret; } private void createDefaultPolicyForEntityLabelAndEntityBusinessMetadata() throws Exception { logger.info("==> createDefaultPolicyForEntityLabelAndEntityBusinessMetadata "); - XXServiceDef xXServiceDefObj = daoMgr.getXXServiceDef() - .findByName(EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_ATLAS_NAME); + + XXServiceDef xXServiceDefObj = daoMgr.getXXServiceDef().findByName(EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_ATLAS_NAME); + if (xXServiceDefObj == null) { - logger.debug("ServiceDef not found with name :" + EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_ATLAS_NAME); + logger.debug("ServiceDef not found with name :{}", EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_ATLAS_NAME); + return; } - Long xServiceDefId = xXServiceDefObj.getId(); - List xxServices = daoMgr.getXXService().findByServiceDefId(xServiceDefId); + + Long xServiceDefId = xXServiceDefObj.getId(); + List xxServices = daoMgr.getXXService().findByServiceDefId(xServiceDefId); + for (XXService xxService : xxServices) { - List xxPolicies = daoMgr.getXXPolicy().findByServiceId(xxService.getId()); - Boolean isEntityLabelPolicyPresent = false; - Boolean isEntityBusinessMetadataPolicyPresent = false; + List xxPolicies = daoMgr.getXXPolicy().findByServiceId(xxService.getId()); + boolean isEntityLabelPolicyPresent = false; + boolean isEntityBusinessMetadataPolicyPresent = false; + for (XXPolicy xxPolicy : xxPolicies) { if (xxPolicy.getName().equalsIgnoreCase(RESOURCE_DEF_ENTITY_LABEL)) { isEntityLabelPolicyPresent = true; } + if (xxPolicy.getName().equalsIgnoreCase(RESOURCE_DEF_ENTITY_BUSINESS_METADATA)) { isEntityBusinessMetadataPolicyPresent = true; } + if (isEntityLabelPolicyPresent && isEntityBusinessMetadataPolicyPresent) { break; } } if (!isEntityLabelPolicyPresent) { - List accessTypesLabel = Arrays.asList("entity-add-label", "entity-remove-label"); - List accessTypesReadEntity = Arrays.asList("entity-read"); - createDefaultRangerPolicy(xServiceDefId, xxService, RESOURCE_DEF_ENTITY_LABEL, accessTypesLabel, - accessTypesReadEntity, ATLAS_RESOURCE_LABEL); + List accessTypesLabel = Arrays.asList("entity-add-label", "entity-remove-label"); + List accessTypesReadEntity = Collections.singletonList("entity-read"); + + createDefaultRangerPolicy(xServiceDefId, xxService, RESOURCE_DEF_ENTITY_LABEL, accessTypesLabel, accessTypesReadEntity, ATLAS_RESOURCE_LABEL); } if (!isEntityBusinessMetadataPolicyPresent) { - List accessTypesBusinessMetadata = Arrays.asList("entity-update-business-metadata"); - List accessTypesReadEntity = Arrays.asList("entity-read"); - createDefaultRangerPolicy(xServiceDefId, xxService, RESOURCE_DEF_ENTITY_BUSINESS_METADATA, accessTypesBusinessMetadata, - accessTypesReadEntity, ATLAS_RESOURCE_BUSINESS_METADATA); - } + List accessTypesBusinessMetadata = Collections.singletonList("entity-update-business-metadata"); + List accessTypesReadEntity = Collections.singletonList("entity-read"); + createDefaultRangerPolicy(xServiceDefId, xxService, RESOURCE_DEF_ENTITY_BUSINESS_METADATA, accessTypesBusinessMetadata, accessTypesReadEntity, ATLAS_RESOURCE_BUSINESS_METADATA); + } } + logger.info("<== createDefaultPolicyForEntityLabelAndEntityBusinessMetadata "); } - private RangerPolicy createDefaultRangerPolicy(Long xServiceDefId, XXService xxService, String policyName, - List accessTypesLableOrBusinessMetadata, List accessTypesReadEntity, List resources) - throws Exception { - RangerPolicy rangerPolicy = getRangerPolicyObject(xxService.getName(), policyName); + private RangerPolicy createDefaultRangerPolicy(Long xServiceDefId, XXService xxService, String policyName, List accessTypesLableOrBusinessMetadata, List accessTypesReadEntity, List resources) throws Exception { + RangerPolicy rangerPolicy = getRangerPolicyObject(xxService.getName(), policyName); + RangerPolicyItem rangerPolicyItemLabelOrBusinessMetadata = new RangerPolicyItem(); + List accessesLabelOrBusinessMetadata = getRangerPolicyItemAccessList(accessTypesLableOrBusinessMetadata, xxService, rangerPolicy.getName()); - RangerPolicyItem rangerPolicyItemLabelOrBusinessMetadata = new RangerPolicyItem(); - List accessesLabelOrBusinessMetadata = getRangerPolicyItemAccessList( - accessTypesLableOrBusinessMetadata, xxService, rangerPolicy.getName()); rangerPolicyItemLabelOrBusinessMetadata.setDelegateAdmin(Boolean.TRUE); rangerPolicyItemLabelOrBusinessMetadata.setAccesses(accessesLabelOrBusinessMetadata); + List usersOfPolicyItem1 = getDefaultPolicyUsers(xxService); + rangerPolicyItemLabelOrBusinessMetadata.setUsers(usersOfPolicyItem1); - RangerPolicyItem rangerPolicyItemReadEntity = new RangerPolicyItem(); - List accessesReadEntity = getRangerPolicyItemAccessList(accessTypesReadEntity, - xxService, rangerPolicy.getName()); + RangerPolicyItem rangerPolicyItemReadEntity = new RangerPolicyItem(); + List accessesReadEntity = getRangerPolicyItemAccessList(accessTypesReadEntity, xxService, rangerPolicy.getName()); + rangerPolicyItemReadEntity.setDelegateAdmin(Boolean.FALSE); rangerPolicyItemReadEntity.setAccesses(accessesReadEntity); - List usersOfPolicyItem2 = new ArrayList(); + + List usersOfPolicyItem2 = new ArrayList<>(); + usersOfPolicyItem2.add("rangertagsync"); - List groups = Arrays.asList(GROUP_PUBLIC); + + List groups = Collections.singletonList(GROUP_PUBLIC); + rangerPolicyItemReadEntity.setGroups(groups); rangerPolicyItemReadEntity.setUsers(usersOfPolicyItem2); - List rangerPolicyItems = new ArrayList(); + List rangerPolicyItems = new ArrayList<>(); + rangerPolicyItems.add(rangerPolicyItemLabelOrBusinessMetadata); rangerPolicyItems.add(rangerPolicyItemReadEntity); + rangerPolicy.setPolicyItems(rangerPolicyItems); - Map xPolResMap = getRangerPolicyResourceMap(resources, xServiceDefId, - xxService.getName(), rangerPolicy.getName()); + + Map xPolResMap = getRangerPolicyResourceMap(resources, xServiceDefId, xxService.getName(), rangerPolicy.getName()); + rangerPolicy.setResources(xPolResMap); - logger.info("Creating policy for service id : " + xxService.getId()); + + logger.info("Creating policy for service id : {}", xxService.getId()); + RangerPolicy createdRangerPolicy = svcDBStore.createPolicy(rangerPolicy); + if (createdRangerPolicy != null) { - logger.info("Policy created : " + createdRangerPolicy.getName()); + logger.info("Policy created : {}", createdRangerPolicy.getName()); } + return createdRangerPolicy; } private RangerPolicy getRangerPolicyObject(String serviceName, String policyName) { - RangerPolicy rangerPolicy = new RangerPolicy(); + RangerPolicy rangerPolicy = new RangerPolicy(); RangerPolicyResourceSignature resourceSignature = new RangerPolicyResourceSignature(rangerPolicy); rangerPolicy.setName(policyName); @@ -297,58 +319,67 @@ private RangerPolicy getRangerPolicyObject(String serviceName, String policyName rangerPolicy.setResourceSignature(resourceSignature.getSignature()); rangerPolicy.setZoneName(""); rangerPolicy.setUpdatedBy(LOGIN_ID_ADMIN); + return rangerPolicy; } - private List getRangerPolicyItemAccessList(List accessTypesLabel, - XXService xxService, String policyName) { - List accessesLabel = new ArrayList(); - for (int i = 0; i < accessTypesLabel.size(); i++) { - XXAccessTypeDef xAccTypeDef = daoMgr.getXXAccessTypeDef().findByNameAndServiceId(accessTypesLabel.get(i), - xxService.getId()); + private List getRangerPolicyItemAccessList(List accessTypesLabel, XXService xxService, String policyName) { + List accessesLabel = new ArrayList<>(); + + for (String s : accessTypesLabel) { + XXAccessTypeDef xAccTypeDef = daoMgr.getXXAccessTypeDef().findByNameAndServiceId(s, xxService.getId()); + if (xAccTypeDef == null) { - throw new RuntimeException(accessTypesLabel.get(i) + ": is not a valid access-type. policy='" - + policyName + "' service='" + xxService.getName() + "'"); + throw new RuntimeException(s + ": is not a valid access-type. policy='" + policyName + "' service='" + xxService.getName() + "'"); } + RangerPolicyItemAccess xPolItemAcc = new RangerPolicyItemAccess(); + xPolItemAcc.setIsAllowed(Boolean.TRUE); xPolItemAcc.setType(xAccTypeDef.getName()); + accessesLabel.add(xPolItemAcc); } + return accessesLabel; } private List getDefaultPolicyUsers(XXService xxService) { - XXPortalUser xxServiceCreator = daoMgr.getXXPortalUser().getById(xxService.getAddedByUserId()); - XXServiceConfigMap cfgMap = daoMgr.getXXServiceConfigMap().findByServiceNameAndConfigKey(xxService.getName(), - "username"); - XXPortalUser xxServiceCfgUser = daoMgr.getXXPortalUser().findByLoginId(cfgMap.getConfigvalue()); - List users = new ArrayList(); + XXPortalUser xxServiceCreator = daoMgr.getXXPortalUser().getById(xxService.getAddedByUserId()); + XXServiceConfigMap cfgMap = daoMgr.getXXServiceConfigMap().findByServiceNameAndConfigKey(xxService.getName(), "username"); + XXPortalUser xxServiceCfgUser = daoMgr.getXXPortalUser().findByLoginId(cfgMap.getConfigvalue()); + List users = new ArrayList<>(); + if (xxServiceCreator != null) { users.add(xxServiceCreator.getLoginId()); } + if (xxServiceCfgUser != null) { users.add(xxServiceCfgUser.getLoginId()); } + return users; } - private Map getRangerPolicyResourceMap(List resources, Long serviceDefId, - String serviceName, String policyName) { - Map xPolResMap = new HashMap(); - for (int i = 0; i < resources.size(); i++) { - XXResourceDef xResDef = daoMgr.getXXResourceDef().findByNameAndServiceDefId(resources.get(i), serviceDefId); + private Map getRangerPolicyResourceMap(List resources, Long serviceDefId, String serviceName, String policyName) { + Map xPolResMap = new HashMap<>(); + + for (String resource : resources) { + XXResourceDef xResDef = daoMgr.getXXResourceDef().findByNameAndServiceDefId(resource, serviceDefId); + if (xResDef == null) { - throw new RuntimeException(resources.get(i) + ": is not a valid resource-type. policy='" + policyName - + "' service='" + serviceName + "'"); + throw new RuntimeException(resource + ": is not a valid resource-type. policy='" + policyName + "' service='" + serviceName + "'"); } + RangerPolicyResource xPolRes = new RangerPolicyResource(); xPolRes.setIsExcludes(Boolean.FALSE); xPolRes.setIsRecursive(Boolean.FALSE); xPolRes.setValue("*"); + xPolResMap.put(xResDef.getName(), xPolRes); } + return xPolResMap; } } diff --git a/security-admin/src/main/java/org/apache/ranger/patch/PatchForAtlasToAddTypeRead_J10040.java b/security-admin/src/main/java/org/apache/ranger/patch/PatchForAtlasToAddTypeRead_J10040.java index 6d09f595b5..bef3426b35 100644 --- a/security-admin/src/main/java/org/apache/ranger/patch/PatchForAtlasToAddTypeRead_J10040.java +++ b/security-admin/src/main/java/org/apache/ranger/patch/PatchForAtlasToAddTypeRead_J10040.java @@ -17,44 +17,41 @@ package org.apache.ranger.patch; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - import org.apache.ranger.biz.ServiceDBStore; import org.apache.ranger.common.RangerValidatorFactory; import org.apache.ranger.db.RangerDaoManager; +import org.apache.ranger.entity.XXPolicy; +import org.apache.ranger.entity.XXService; import org.apache.ranger.entity.XXServiceDef; +import org.apache.ranger.plugin.model.RangerPolicy; +import org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyItem; +import org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyItemAccess; import org.apache.ranger.plugin.model.RangerServiceDef; import org.apache.ranger.plugin.model.RangerServiceDef.RangerAccessTypeDef; import org.apache.ranger.plugin.model.validation.RangerServiceDefValidator; import org.apache.ranger.plugin.model.validation.RangerValidator.Action; import org.apache.ranger.plugin.store.EmbeddedServiceDefsUtil; import org.apache.ranger.util.CLIUtil; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; -import org.apache.ranger.entity.XXPolicy; -import org.apache.ranger.entity.XXService; -import org.apache.ranger.plugin.model.RangerPolicy; -import org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyItem; -import org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyItemAccess; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; @Component public class PatchForAtlasToAddTypeRead_J10040 extends org.apache.ranger.patch.BaseLoader { private static final Logger logger = LoggerFactory.getLogger(PatchForAtlasToAddTypeRead_J10040.class); - private static final List ATLAS_RESOURCES = new ArrayList<>( - Arrays.asList("type")); - private static final List ATLAS_ACCESS_TYPES = new ArrayList<>( - Arrays.asList("type-read")); + private static final List ATLAS_RESOURCES = new ArrayList<>(Collections.singletonList("type")); + private static final List ATLAS_ACCESS_TYPES = new ArrayList<>(Collections.singletonList("type-read")); - private static final String GROUP_PUBLIC = "public"; - private static final String TYPE_READ = "type-read"; + private static final String GROUP_PUBLIC = "public"; + private static final String TYPE_READ = "type-read"; private static final String ALL_TYPE_RESOURCE_DEF_NAME = "all - type-category, type"; - @Autowired RangerDaoManager daoMgr; @@ -69,17 +66,22 @@ public class PatchForAtlasToAddTypeRead_J10040 extends org.apache.ranger.patch.B public static void main(String[] args) { logger.info("main()"); + try { - PatchForAtlasToAddTypeRead_J10040 loader = (PatchForAtlasToAddTypeRead_J10040) CLIUtil - .getBean(PatchForAtlasToAddTypeRead_J10040.class); + PatchForAtlasToAddTypeRead_J10040 loader = (PatchForAtlasToAddTypeRead_J10040) CLIUtil.getBean(PatchForAtlasToAddTypeRead_J10040.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); } } @@ -89,153 +91,154 @@ public void init() throws Exception { // Do Nothing } + @Override + public void printStats() { + logger.info("PatchForAtlasToAddTypeRead_J10040 Logs"); + } + @Override public void execLoad() { logger.info("==> PatchForAtlasToAddTypeRead_J10040.execLoad()"); + try { addTypeReadPermissionInServiceDef(); updateDefaultPolicyForType(); } catch (Exception e) { - throw new RuntimeException( - "Error while updating " + EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_ATLAS_NAME + " service-def", e); + throw new RuntimeException("Error while updating " + EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_ATLAS_NAME + " service-def", e); } + logger.info("<== PatchForAtlasToAddTypeRead_J10040.execLoad()"); } - @Override - public void printStats() { - logger.info("PatchForAtlasToAddTypeRead_J10040 Logs"); + boolean checkIfTypeReadPermissionSet(RangerPolicyItem item) { + boolean ret = false; + + for (RangerPolicyItemAccess itemAccess : item.getAccesses()) { + if (ATLAS_ACCESS_TYPES.contains(itemAccess.getType())) { + ret = true; + break; + } + } + + return ret; } private void addTypeReadPermissionInServiceDef() throws Exception { - logger.debug("==>> addTypeReadPermissionInServiceDef"); - RangerServiceDef ret = null; - RangerServiceDef embeddedAtlasServiceDef = null; - XXServiceDef xXServiceDefObj = null; - RangerServiceDef dbAtlasServiceDef = null; - List embeddedAtlasResourceDefs = null; - List embeddedAtlasAccessTypes = null; - - embeddedAtlasServiceDef = EmbeddedServiceDefsUtil.instance() - .getEmbeddedServiceDef(EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_ATLAS_NAME); + + RangerServiceDef embeddedAtlasServiceDef = EmbeddedServiceDefsUtil.instance().getEmbeddedServiceDef(EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_ATLAS_NAME); + if (embeddedAtlasServiceDef != null) { - xXServiceDefObj = daoMgr.getXXServiceDef() - .findByName(EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_ATLAS_NAME); + XXServiceDef xXServiceDefObj = daoMgr.getXXServiceDef().findByName(EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_ATLAS_NAME); + if (xXServiceDefObj == null) { - logger.info(xXServiceDefObj + ": service-def not found. No patching is needed"); + logger.info("{} service-def not found. No patching is needed", xXServiceDefObj); + return; } - dbAtlasServiceDef = svcDBStore.getServiceDefByName(EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_ATLAS_NAME); - - embeddedAtlasResourceDefs = embeddedAtlasServiceDef.getResources(); - embeddedAtlasAccessTypes = embeddedAtlasServiceDef.getAccessTypes(); + RangerServiceDef dbAtlasServiceDef = svcDBStore.getServiceDefByName(EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_ATLAS_NAME); + List embeddedAtlasResourceDefs = embeddedAtlasServiceDef.getResources(); + List embeddedAtlasAccessTypes = embeddedAtlasServiceDef.getAccessTypes(); if (checkResourcePresent(embeddedAtlasResourceDefs)) { dbAtlasServiceDef.setResources(embeddedAtlasResourceDefs); + if (checkAccessPresent(embeddedAtlasAccessTypes)) { dbAtlasServiceDef.setAccessTypes(embeddedAtlasAccessTypes); } } RangerServiceDefValidator validator = validatorFactory.getServiceDefValidator(svcStore); + validator.validate(dbAtlasServiceDef, Action.UPDATE); - ret = svcStore.updateServiceDef(dbAtlasServiceDef); + + RangerServiceDef ret = svcStore.updateServiceDef(dbAtlasServiceDef); + if (ret == null) { - logger.error("Error while updating " + EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_ATLAS_NAME - + " service-def"); - throw new RuntimeException("Error while updating " - + EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_ATLAS_NAME + " service-def"); + logger.error("Error while updating {} service-def", EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_ATLAS_NAME); + + throw new RuntimeException("Error while updating " + EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_ATLAS_NAME + " service-def"); } } + logger.debug("<<== addTypeReadPermissionInServiceDef"); } private boolean checkResourcePresent(List resourceDefs) { boolean ret = false; + for (RangerServiceDef.RangerResourceDef resourceDef : resourceDefs) { if (ATLAS_RESOURCES.contains(resourceDef.getName())) { ret = true; break; } } + return ret; } private boolean checkAccessPresent(List embeddedAtlasAccessTypes) { boolean ret = false; + for (RangerServiceDef.RangerAccessTypeDef accessDef : embeddedAtlasAccessTypes) { if (ATLAS_ACCESS_TYPES.contains(accessDef.getName())) { ret = true; break; } } + return ret; } private void updateDefaultPolicyForType() throws Exception { logger.info("==> updateDefaultPolicyForType() "); - XXServiceDef xXServiceDefObj = daoMgr.getXXServiceDef() - .findByName(EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_ATLAS_NAME); + XXServiceDef xXServiceDefObj = daoMgr.getXXServiceDef().findByName(EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_ATLAS_NAME); + if (xXServiceDefObj == null) { - logger.debug("ServiceDef not found with name :" + EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_ATLAS_NAME); + logger.debug("ServiceDef not found with name :{}", EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_ATLAS_NAME); + return; } - Long xServiceDefId = xXServiceDefObj.getId(); - List xxServices = daoMgr.getXXService().findByServiceDefId(xServiceDefId); + + Long xServiceDefId = xXServiceDefObj.getId(); + List xxServices = daoMgr.getXXService().findByServiceDefId(xServiceDefId); for (XXService xxService : xxServices) { List xxPolicies = daoMgr.getXXPolicy().findByServiceId(xxService.getId()); for (XXPolicy xxPolicy : xxPolicies) { if (xxPolicy.getName().equalsIgnoreCase(ALL_TYPE_RESOURCE_DEF_NAME)) { - RangerPolicy rPolicy = svcDBStore.getPolicy(xxPolicy.getId()); for (RangerPolicyItem item : rPolicy.getPolicyItems()) { if (!checkIfTypeReadPermissionSet(item)) { List itemAccesses = item.getAccesses(); + itemAccesses.add(getTypeReadPolicyItemAccesses()); + item.setAccesses(itemAccesses); } } RangerPolicyItem rangerPolicyItemReadType = new RangerPolicyItem(); + rangerPolicyItemReadType.setDelegateAdmin(Boolean.FALSE); - rangerPolicyItemReadType.setAccesses(Arrays.asList(getTypeReadPolicyItemAccesses())); - rangerPolicyItemReadType.setGroups(Arrays.asList(GROUP_PUBLIC)); + rangerPolicyItemReadType.setAccesses(Collections.singletonList(getTypeReadPolicyItemAccesses())); + rangerPolicyItemReadType.setGroups(Collections.singletonList(GROUP_PUBLIC)); rPolicy.addPolicyItem(rangerPolicyItemReadType); svcDBStore.updatePolicy(rPolicy); } - } - } + logger.info("<== updateDefaultPolicyForType() "); } private RangerPolicyItemAccess getTypeReadPolicyItemAccesses() { - - RangerPolicyItemAccess policyItemAccess = new RangerPolicyItemAccess(); - policyItemAccess.setType(TYPE_READ); - policyItemAccess.setIsAllowed(true); - - return policyItemAccess; - } - - boolean checkIfTypeReadPermissionSet(RangerPolicyItem item) { - boolean ret = false; - for (RangerPolicyItemAccess itemAccess : item.getAccesses()) { - if (ATLAS_ACCESS_TYPES.contains(itemAccess.getType())) { - ret = true; - break; - } - } - return ret; + return new RangerPolicyItemAccess(TYPE_READ, true); } - -} \ No newline at end of file +} diff --git a/security-admin/src/main/java/org/apache/ranger/patch/PatchForDefaultAuidtFilters_J10050.java b/security-admin/src/main/java/org/apache/ranger/patch/PatchForDefaultAuidtFilters_J10050.java index bd6da1de12..9b430ef397 100644 --- a/security-admin/src/main/java/org/apache/ranger/patch/PatchForDefaultAuidtFilters_J10050.java +++ b/security-admin/src/main/java/org/apache/ranger/patch/PatchForDefaultAuidtFilters_J10050.java @@ -17,10 +17,6 @@ package org.apache.ranger.patch; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang.StringUtils; import org.apache.ranger.biz.ServiceDBStore; @@ -37,124 +33,132 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + @Component public class PatchForDefaultAuidtFilters_J10050 extends BaseLoader { + private static final Logger logger = LoggerFactory.getLogger(PatchForDefaultAuidtFilters_J10050.class); + + @Autowired + RangerDaoManager daoMgr; + + @Autowired + ServiceDBStore svcStore; + + @Autowired + RangerAuditFields rangerAuditFields; + + public static void main(String[] args) { + logger.info("main()"); + + try { + PatchForDefaultAuidtFilters_J10050 loader = (PatchForDefaultAuidtFilters_J10050) CLIUtil.getBean(PatchForDefaultAuidtFilters_J10050.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); + } + } + + @Override + public void init() throws Exception { + // Do Nothing + } + + @Override + public void printStats() { + logger.info("adding default audit-filters to all services"); + } + + @Override + public void execLoad() { + logger.info("==> PatchForDefaultAuidtFilters.execLoad()"); + + try { + addDefaultAuditFilters(); + } catch (Exception e) { + logger.error("Error while PatchForDefaultAuidtFilters", e); + + System.exit(1); + } + + logger.info("<== PatchForDefaultAuidtFilters.execLoad()"); + } + + private void addDefaultAuditFilters() throws Exception { + logger.debug("==> PatchForDefaultAuidtFilters_J10050.addDefaultAuditFilters()"); + + List xxServiceList = daoMgr.getXXService().getAll(); + + if (CollectionUtils.isNotEmpty(xxServiceList)) { + logger.info("Found {} services", xxServiceList.size()); + + Map defaultAuditFiltersMap = new HashMap<>(); + + for (XXService xservice : xxServiceList) { + RangerService rangerService = svcStore.getServiceByName(xservice.getName()); + + if (rangerService != null && !rangerService.getConfigs().containsKey(ServiceDBStore.RANGER_PLUGIN_AUDIT_FILTERS)) { + if (!defaultAuditFiltersMap.containsKey(rangerService.getType())) { + List svcConfDefList = daoMgr.getXXServiceConfigDef().findByServiceDefName(rangerService.getType()); + + for (XXServiceConfigDef svcConfDef : svcConfDefList) { + if (StringUtils.equals(svcConfDef.getName(), ServiceDBStore.RANGER_PLUGIN_AUDIT_FILTERS)) { + defaultAuditFiltersMap.put(rangerService.getType(), svcConfDef.getDefaultvalue()); + } + } + } + + if (defaultAuditFiltersMap.get(rangerService.getType()) != null) { + Map configs = rangerService.getConfigs(); + + if (!configs.containsKey(ServiceDBStore.RANGER_PLUGIN_AUDIT_FILTERS)) { + logger.info("adding default audit-filter to service {}", rangerService.getName()); + + addDefaultAuditFilterConfig(xservice, defaultAuditFiltersMap.get(rangerService.getType())); + } + } else { + logger.info("No default audit-filter available for service {}. Skipped", rangerService.getName()); + } + } + } + } + + logger.info("<== PatchForDefaultAuidtFilters_J10050.addDefaultAuditFilters()"); + } + + private void addDefaultAuditFilterConfig(XXService xservice, String defaultValue) { + logger.debug("==> PatchForDefaultAuidtFilters_J10050.addDefaultAuditFilterConfig() for service (id={})", xservice.getId()); + + try { + XXServiceConfigMapDao xConfMapDao = daoMgr.getXXServiceConfigMap(); + XXServiceConfigMap xConfMap = new XXServiceConfigMap(); + + xConfMap = rangerAuditFields.populateAuditFields(xConfMap, xservice); + + xConfMap.setServiceId(xservice.getId()); + xConfMap.setConfigkey(ServiceDBStore.RANGER_PLUGIN_AUDIT_FILTERS); + xConfMap.setConfigvalue(defaultValue); + + xConfMapDao.create(xConfMap); + } catch (Exception e) { + logger.error("default audit filters addition for service (id={}) failed!!", xservice.getId()); + + throw e; + } - private static final Logger logger = LoggerFactory.getLogger(PatchForDefaultAuidtFilters_J10050.class); - - @Autowired - RangerDaoManager daoMgr; - - @Autowired - ServiceDBStore svcStore; - - @Autowired - RangerAuditFields rangerAuditFields; - - public static void main(String[] args) { - - logger.info("main()"); - try { - PatchForDefaultAuidtFilters_J10050 loader = (PatchForDefaultAuidtFilters_J10050) CLIUtil - .getBean(PatchForDefaultAuidtFilters_J10050.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); - } - } - - @Override - public void init() throws Exception { - // Do Nothing - } - - @Override - public void printStats() { - logger.info("adding default audit-filters to all services"); - - } - - @Override - public void execLoad() { - logger.info("==> PatchForDefaultAuidtFilters.execLoad()"); - - try { - addDefaultAuditFilters(); - } catch (Exception e) { - logger.error("Error while PatchForDefaultAuidtFilters", e); - System.exit(1); - } - logger.info("<== PatchForDefaultAuidtFilters.execLoad()"); - } - - private void addDefaultAuditFilters() throws Exception { - logger.debug("==> PatchForDefaultAuidtFilters_J10050.addDefaultAuditFilters()"); - - Map defaultAuditFiltersMap = null; - - List xxServiceList = daoMgr.getXXService().getAll(); - - if (CollectionUtils.isNotEmpty(xxServiceList)) { - logger.info("Found " + xxServiceList.size() + " services"); - defaultAuditFiltersMap = new HashMap(); - - for (XXService xservice : xxServiceList) { - RangerService rangerService = svcStore.getServiceByName(xservice.getName()); - if (rangerService != null && !rangerService.getConfigs().containsKey(ServiceDBStore.RANGER_PLUGIN_AUDIT_FILTERS)) { - - if (!defaultAuditFiltersMap.containsKey(rangerService.getType())) { - List svcConfDefList = daoMgr.getXXServiceConfigDef() - .findByServiceDefName(rangerService.getType()); - for(XXServiceConfigDef svcConfDef : svcConfDefList) { - if(StringUtils.equals(svcConfDef.getName(),ServiceDBStore.RANGER_PLUGIN_AUDIT_FILTERS)) { - defaultAuditFiltersMap.put(rangerService.getType(), svcConfDef.getDefaultvalue()); - continue; - } - } - } - - if (defaultAuditFiltersMap.get(rangerService.getType()) != null) { - Map configs = rangerService.getConfigs(); - if (!configs.containsKey(ServiceDBStore.RANGER_PLUGIN_AUDIT_FILTERS)) { - logger.info("adding default audit-filter to service " + rangerService.getName()); - addDefaultAuditFilterConfig(xservice, defaultAuditFiltersMap.get(rangerService.getType())); - } - }else { - logger.info("No default audit-filter available for service " + rangerService.getName() + ". Skipped"); - } - } - } - } - - logger.info("<== PatchForDefaultAuidtFilters_J10050.addDefaultAuditFilters()"); - } - - private void addDefaultAuditFilterConfig(XXService xservice, String defaultValue) { - if (logger.isDebugEnabled()) { - logger.debug("==> PatchForDefaultAuidtFilters_J10050.addDefaultAuditFilterConfig() for service (id=" - + xservice.getId() + ")"); - } - try { - XXServiceConfigMapDao xConfMapDao = daoMgr.getXXServiceConfigMap(); - XXServiceConfigMap xConfMap = new XXServiceConfigMap(); - xConfMap = (XXServiceConfigMap) rangerAuditFields.populateAuditFields(xConfMap, xservice); - xConfMap.setServiceId(xservice.getId()); - xConfMap.setConfigkey(ServiceDBStore.RANGER_PLUGIN_AUDIT_FILTERS); - xConfMap.setConfigvalue(defaultValue); - xConfMapDao.create(xConfMap); - } catch (Exception e) { - logger.error("default audit filters addition for service (id=" + xservice.getId() + ") failed!!"); - throw e; - } - if (logger.isDebugEnabled()) { - logger.debug("<== PatchForDefaultAuidtFilters_J10050.addDefaultAuditFilterConfig()"); - } - } - -} \ No newline at end of file + logger.debug("<== PatchForDefaultAuidtFilters_J10050.addDefaultAuditFilterConfig()"); + } +} diff --git a/security-admin/src/main/java/org/apache/ranger/patch/PatchForExternalUserStatusUpdate_J10056.java b/security-admin/src/main/java/org/apache/ranger/patch/PatchForExternalUserStatusUpdate_J10056.java index f4a122b38e..23c2c8988a 100644 --- a/security-admin/src/main/java/org/apache/ranger/patch/PatchForExternalUserStatusUpdate_J10056.java +++ b/security-admin/src/main/java/org/apache/ranger/patch/PatchForExternalUserStatusUpdate_J10056.java @@ -17,8 +17,6 @@ package org.apache.ranger.patch; -import java.util.List; - import org.apache.commons.collections.CollectionUtils; import org.apache.ranger.common.RangerCommonEnums; import org.apache.ranger.db.RangerDaoManager; @@ -32,77 +30,81 @@ 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 java.util.List; + @Component public class PatchForExternalUserStatusUpdate_J10056 extends BaseLoader { + private static final Logger logger = LoggerFactory.getLogger(PatchForExternalUserStatusUpdate_J10056.class); + + @Autowired + @Qualifier(value = "transactionManager") + PlatformTransactionManager txManager; + + @Autowired + private RangerDaoManager daoManager; + + public static void main(String[] args) { + try { + PatchForExternalUserStatusUpdate_J10056 loader = (PatchForExternalUserStatusUpdate_J10056) CLIUtil.getBean(PatchForExternalUserStatusUpdate_J10056.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); + } + } + + @Override + public void init() throws Exception { + // Do Nothing + } + + @Override + public void printStats() { + // TODO Auto-generated method stub + } + + @Override + public void execLoad() { + updateExternalUserStatus(); + } + + private void updateExternalUserStatus() { + XXPortalUserDao dao = this.daoManager.getXXPortalUser(); + List xXPortalUsers = dao.findByUserSourceAndStatus(RangerCommonEnums.USER_EXTERNAL, RangerCommonEnums.ACT_STATUS_DISABLED); + + if (CollectionUtils.isNotEmpty(xXPortalUsers)) { + for (XXPortalUser xxPortalUser : xXPortalUsers) { + if (xxPortalUser != null) { + xxPortalUser.setStatus(RangerCommonEnums.ACT_STATUS_ACTIVE); + + TransactionTemplate txTemplate = new TransactionTemplate(txManager); + + txTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + + try { + txTemplate.execute(status -> { + dao.update(xxPortalUser, true); - private static final Logger logger = LoggerFactory.getLogger(PatchForExternalUserStatusUpdate_J10056.class); - - @Autowired - private RangerDaoManager daoManager; - - @Autowired - @Qualifier(value = "transactionManager") - PlatformTransactionManager txManager; - - public static void main(String[] args) { - try { - PatchForExternalUserStatusUpdate_J10056 loader = (PatchForExternalUserStatusUpdate_J10056) CLIUtil - .getBean(PatchForExternalUserStatusUpdate_J10056.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); - } - } - - @Override - public void init() throws Exception { - // Do Nothing - } - - @Override - public void printStats() { - // TODO Auto-generated method stub - } - - @Override - public void execLoad() { - updateExternalUserStatus(); - } - - private void updateExternalUserStatus() { - XXPortalUserDao dao = this.daoManager.getXXPortalUser(); - List xXPortalUsers = dao.findByUserSourceAndStatus(RangerCommonEnums.USER_EXTERNAL,RangerCommonEnums.ACT_STATUS_DISABLED); - - if(CollectionUtils.isNotEmpty(xXPortalUsers)) { - for (XXPortalUser xxPortalUser : xXPortalUsers) { - if (xxPortalUser != null) { - xxPortalUser.setStatus(RangerCommonEnums.ACT_STATUS_ACTIVE); - TransactionTemplate txTemplate = new TransactionTemplate(txManager); - txTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); - try { - txTemplate.execute(new TransactionCallback() { - @Override - public Object doInTransaction(TransactionStatus status) { - dao.update(xxPortalUser, true); - return null; - } - }); - } catch (Throwable ex) { - logger.error("updateExternalUserStatus(): Failed to update DB for user: " + xxPortalUser.getLoginId() + " ", ex); - throw new RuntimeException(ex); - } - } - } - } - } + return null; + }); + } catch (Throwable ex) { + logger.error("updateExternalUserStatus(): Failed to update DB for user: {}", xxPortalUser.getLoginId(), ex); + throw new RuntimeException(ex); + } + } + } + } + } } diff --git a/security-admin/src/main/java/org/apache/ranger/patch/PatchForHBaseDefaultPolicyUpdate_J10045.java b/security-admin/src/main/java/org/apache/ranger/patch/PatchForHBaseDefaultPolicyUpdate_J10045.java index 623e981942..e4c3a9efbe 100644 --- a/security-admin/src/main/java/org/apache/ranger/patch/PatchForHBaseDefaultPolicyUpdate_J10045.java +++ b/security-admin/src/main/java/org/apache/ranger/patch/PatchForHBaseDefaultPolicyUpdate_J10045.java @@ -18,6 +18,7 @@ package org.apache.ranger.patch; import org.apache.commons.collections.CollectionUtils; +import org.apache.commons.lang.StringUtils; import org.apache.ranger.biz.ServiceDBStore; import org.apache.ranger.db.RangerDaoManager; import org.apache.ranger.entity.XXService; @@ -27,7 +28,6 @@ import org.apache.ranger.plugin.store.EmbeddedServiceDefsUtil; import org.apache.ranger.plugin.util.SearchFilter; import org.apache.ranger.util.CLIUtil; -import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -39,107 +39,127 @@ @Component public class PatchForHBaseDefaultPolicyUpdate_J10045 extends BaseLoader { - private static final Logger logger = LoggerFactory.getLogger(PatchForHBaseDefaultPolicyUpdate_J10045.class); - public static final String SERVICE_CONFIG_USER_NAME_PARAM = "username"; - public static final String DEFAULT_HBASE_USER_NAME = "hbase"; - public static final String DEFAULT_HBASE_POLICY_NAME = "all - table, column-family, column"; - - @Autowired - RangerDaoManager daoMgr; - - @Autowired - ServiceDBStore svcDBStore; - - public static void main(String[] args) { - logger.info("main()"); - try { - PatchForHBaseDefaultPolicyUpdate_J10045 loader = (PatchForHBaseDefaultPolicyUpdate_J10045) CLIUtil.getBean(PatchForHBaseDefaultPolicyUpdate_J10045.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); - } - } - - @Override - public void printStats() { - logger.info("PatchForHBaseDefaultPolicyUpdate data "); - } - - @Override - public void execLoad() { - logger.info("==> PatchForHBaseDefaultPolicyUpdate.execLoad()"); - try { - if (!updateHBaseDefaultPolicy()) { - logger.error("Failed to apply the patch."); - System.exit(1); - } - } catch (Exception e) { - logger.error("Error while updateHBaseDefaultPolicy()data.", e); - System.exit(1); - } - logger.info("<== PatchForHBaseDefaultPolicyUpdate.execLoad()"); - } - - @Override - public void init() throws Exception { - // Do Nothing - } - - private boolean updateHBaseDefaultPolicy() throws Exception { - RangerServiceDef embeddedHBaseServiceDef; - - embeddedHBaseServiceDef = EmbeddedServiceDefsUtil.instance().getEmbeddedServiceDef(EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_HBASE_NAME); - - if (embeddedHBaseServiceDef != null) { - List dbServices = daoMgr.getXXService().findByServiceDefId(embeddedHBaseServiceDef.getId()); - if (CollectionUtils.isNotEmpty(dbServices)) { - SearchFilter filter = new SearchFilter(); - - for(XXService dbService : dbServices) { - RangerService service = svcDBStore.getServiceByName(dbService.getName()); - if (service != null) { - String userName = service.getConfigs().get(SERVICE_CONFIG_USER_NAME_PARAM); - if (StringUtils.isEmpty(userName)) { - userName = DEFAULT_HBASE_USER_NAME; - } - updateDefaultHBasePolicy(svcDBStore.getServicePolicies(dbService.getId(), filter), userName); - } else { - logger.error("Cannot get RangerService with name:[" + dbService.getName() + "]"); - } - } - } - } else { - logger.error("The embedded HBase service-definition does not exist."); - return false; - } - return true; - } - - private void updateDefaultHBasePolicy(List policies, String userName) throws Exception{ - if (CollectionUtils.isNotEmpty(policies)) { - for (RangerPolicy policy : policies) { - if (policy.getName().equals(DEFAULT_HBASE_POLICY_NAME)) { - RangerPolicy.RangerPolicyItem policyItemForHBase = new RangerPolicy.RangerPolicyItem(); - policyItemForHBase.setUsers(Collections.singletonList(userName)); - List accesses = new ArrayList<>(); - accesses.add(new RangerPolicy.RangerPolicyItemAccess("read", true)); - accesses.add(new RangerPolicy.RangerPolicyItemAccess("write", true)); - accesses.add(new RangerPolicy.RangerPolicyItemAccess("create", true)); - accesses.add(new RangerPolicy.RangerPolicyItemAccess("admin", true)); - accesses.add(new RangerPolicy.RangerPolicyItemAccess("execute", true)); - policyItemForHBase.setAccesses(accesses); - policyItemForHBase.setDelegateAdmin(true); - policy.addPolicyItem(policyItemForHBase); - svcDBStore.updatePolicy(policy); - break; - } - } - } - } + private static final Logger logger = LoggerFactory.getLogger(PatchForHBaseDefaultPolicyUpdate_J10045.class); + + public static final String SERVICE_CONFIG_USER_NAME_PARAM = "username"; + public static final String DEFAULT_HBASE_USER_NAME = "hbase"; + public static final String DEFAULT_HBASE_POLICY_NAME = "all - table, column-family, column"; + @Autowired + RangerDaoManager daoMgr; + + @Autowired + ServiceDBStore svcDBStore; + + public static void main(String[] args) { + logger.info("main()"); + + try { + PatchForHBaseDefaultPolicyUpdate_J10045 loader = (PatchForHBaseDefaultPolicyUpdate_J10045) CLIUtil.getBean(PatchForHBaseDefaultPolicyUpdate_J10045.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); + } + } + + @Override + public void init() throws Exception { + // Do Nothing + } + + @Override + public void printStats() { + logger.info("PatchForHBaseDefaultPolicyUpdate data "); + } + + @Override + public void execLoad() { + logger.info("==> PatchForHBaseDefaultPolicyUpdate.execLoad()"); + + try { + if (!updateHBaseDefaultPolicy()) { + logger.error("Failed to apply the patch."); + System.exit(1); + } + } catch (Exception e) { + logger.error("Error while updateHBaseDefaultPolicy()data.", e); + + System.exit(1); + } + + logger.info("<== PatchForHBaseDefaultPolicyUpdate.execLoad()"); + } + + private boolean updateHBaseDefaultPolicy() throws Exception { + RangerServiceDef embeddedHBaseServiceDef = EmbeddedServiceDefsUtil.instance().getEmbeddedServiceDef(EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_HBASE_NAME); + + if (embeddedHBaseServiceDef != null) { + List dbServices = daoMgr.getXXService().findByServiceDefId(embeddedHBaseServiceDef.getId()); + + if (CollectionUtils.isNotEmpty(dbServices)) { + SearchFilter filter = new SearchFilter(); + + for (XXService dbService : dbServices) { + RangerService service = svcDBStore.getServiceByName(dbService.getName()); + + if (service != null) { + String userName = service.getConfigs().get(SERVICE_CONFIG_USER_NAME_PARAM); + + if (StringUtils.isEmpty(userName)) { + userName = DEFAULT_HBASE_USER_NAME; + } + + updateDefaultHBasePolicy(svcDBStore.getServicePolicies(dbService.getId(), filter), userName); + } else { + logger.error("Cannot get RangerService with name:[{}]", dbService.getName()); + } + } + } + } else { + logger.error("The embedded HBase service-definition does not exist."); + + return false; + } + + return true; + } + + private void updateDefaultHBasePolicy(List policies, String userName) throws Exception { + if (CollectionUtils.isNotEmpty(policies)) { + for (RangerPolicy policy : policies) { + if (policy.getName().equals(DEFAULT_HBASE_POLICY_NAME)) { + RangerPolicy.RangerPolicyItem policyItemForHBase = new RangerPolicy.RangerPolicyItem(); + + policyItemForHBase.setUsers(Collections.singletonList(userName)); + + List accesses = new ArrayList<>(); + + accesses.add(new RangerPolicy.RangerPolicyItemAccess("read", true)); + accesses.add(new RangerPolicy.RangerPolicyItemAccess("write", true)); + accesses.add(new RangerPolicy.RangerPolicyItemAccess("create", true)); + accesses.add(new RangerPolicy.RangerPolicyItemAccess("admin", true)); + accesses.add(new RangerPolicy.RangerPolicyItemAccess("execute", true)); + + policyItemForHBase.setAccesses(accesses); + policyItemForHBase.setDelegateAdmin(true); + + policy.addPolicyItem(policyItemForHBase); + + svcDBStore.updatePolicy(policy); + + break; + } + } + } + } } diff --git a/security-admin/src/main/java/org/apache/ranger/patch/PatchForHBaseServiceDefUpdate_J10035.java b/security-admin/src/main/java/org/apache/ranger/patch/PatchForHBaseServiceDefUpdate_J10035.java index ecda77a4e2..7f9b2a6e94 100644 --- a/security-admin/src/main/java/org/apache/ranger/patch/PatchForHBaseServiceDefUpdate_J10035.java +++ b/security-admin/src/main/java/org/apache/ranger/patch/PatchForHBaseServiceDefUpdate_J10035.java @@ -45,8 +45,9 @@ @Component public class PatchForHBaseServiceDefUpdate_J10035 extends BaseLoader { private static final Logger logger = LoggerFactory.getLogger(PatchForHBaseServiceDefUpdate_J10035.class); + public static final String SERVICEDBSTORE_SERVICEDEFBYNAME_HBASE_NAME = "hbase"; - public static final String REFRESH_ACCESS_TYPE_NAME = "execute"; + public static final String REFRESH_ACCESS_TYPE_NAME = "execute"; @Autowired RangerDaoManager daoMgr; @@ -80,20 +81,31 @@ public class PatchForHBaseServiceDefUpdate_J10035 extends BaseLoader { public static void main(String[] args) { logger.info("main()"); + try { PatchForHBaseServiceDefUpdate_J10035 loader = (PatchForHBaseServiceDefUpdate_J10035) CLIUtil.getBean(PatchForHBaseServiceDefUpdate_J10035.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); } } + @Override + public void init() throws Exception { + // Do Nothing + } + @Override public void printStats() { logger.info("PatchForHBaseServiceDefUpdate data "); @@ -102,48 +114,73 @@ public void printStats() { @Override public void execLoad() { logger.info("==> PatchForHBaseServiceDefUpdate.execLoad()"); + try { if (!updateHBaseServiceDef()) { logger.error("Failed to apply the patch."); + System.exit(1); } } catch (Exception e) { logger.error("Error while PatchForHBaseServiceDefUpdate()data.", e); + System.exit(1); } + logger.info("<== PatchForHBaseServiceDefUpdate.execLoad()"); } - @Override - public void init() throws Exception { - // Do Nothing + protected Map jsonStringToMap(String jsonStr) { + Map ret = null; + + if (!StringUtils.isEmpty(jsonStr)) { + try { + ret = jsonUtil.jsonToMap(jsonStr); + } catch (Exception ex) { + // fallback to earlier format: "name1=value1;name2=value2" + for (String optionString : jsonStr.split(";")) { + if (StringUtils.isEmpty(optionString)) { + continue; + } + + String[] nvArr = optionString.split("="); + String name = nvArr.length > 0 ? nvArr[0].trim() : null; + String value = nvArr.length > 1 ? nvArr[1].trim() : null; + + if (StringUtils.isEmpty(name)) { + continue; + } + + if (ret == null) { + ret = new HashMap<>(); + } + + ret.put(name, value); + } + } + } + + return ret; } private boolean updateHBaseServiceDef() throws Exception { - RangerServiceDef ret; - RangerServiceDef embeddedHBasServiceDef; - RangerServiceDef dbHBaseServiceDef; - List embeddedHBaseAccessTypes; - XXServiceDef xXServiceDefObj; - - embeddedHBasServiceDef = EmbeddedServiceDefsUtil.instance().getEmbeddedServiceDef(SERVICEDBSTORE_SERVICEDEFBYNAME_HBASE_NAME); + RangerServiceDef embeddedHBasServiceDef = EmbeddedServiceDefsUtil.instance().getEmbeddedServiceDef(SERVICEDBSTORE_SERVICEDEFBYNAME_HBASE_NAME); if (embeddedHBasServiceDef != null) { - xXServiceDefObj = daoMgr.getXXServiceDef().findByName(SERVICEDBSTORE_SERVICEDEFBYNAME_HBASE_NAME); - Map serviceDefOptionsPreUpdate; - String jsonPreUpdate; + XXServiceDef xXServiceDefObj = daoMgr.getXXServiceDef().findByName(SERVICEDBSTORE_SERVICEDEFBYNAME_HBASE_NAME); - if (xXServiceDefObj != null) { - jsonPreUpdate = xXServiceDefObj.getDefOptions(); - serviceDefOptionsPreUpdate = jsonStringToMap(jsonPreUpdate); - } else { + if (xXServiceDefObj == null) { logger.error("HBase service-definition does not exist in the Ranger DAO. No patching is needed!!"); + return true; } - dbHBaseServiceDef = svcDBStore.getServiceDefByName(SERVICEDBSTORE_SERVICEDEFBYNAME_HBASE_NAME); + + String jsonPreUpdate = xXServiceDefObj.getDefOptions(); + Map serviceDefOptionsPreUpdate = jsonStringToMap(jsonPreUpdate); + RangerServiceDef dbHBaseServiceDef = svcDBStore.getServiceDefByName(SERVICEDBSTORE_SERVICEDEFBYNAME_HBASE_NAME); if (dbHBaseServiceDef != null) { - embeddedHBaseAccessTypes = embeddedHBasServiceDef.getAccessTypes(); + List embeddedHBaseAccessTypes = embeddedHBasServiceDef.getAccessTypes(); if (embeddedHBaseAccessTypes != null) { if (checkNewHBaseAccessTypesPresent(embeddedHBaseAccessTypes)) { @@ -154,89 +191,79 @@ private boolean updateHBaseServiceDef() throws Exception { } } else { logger.error("HBase service-definition does not exist in the db store."); + return false; } + RangerServiceDefValidator validator = validatorFactory.getServiceDefValidator(svcStore); + validator.validate(dbHBaseServiceDef, RangerValidator.Action.UPDATE); - ret = svcStore.updateServiceDef(dbHBaseServiceDef); + RangerServiceDef ret = svcStore.updateServiceDef(dbHBaseServiceDef); + if (ret == null) { throw new RuntimeException("Error while updating " + SERVICEDBSTORE_SERVICEDEFBYNAME_HBASE_NAME + " service-def"); } + xXServiceDefObj = daoMgr.getXXServiceDef().findByName(SERVICEDBSTORE_SERVICEDEFBYNAME_HBASE_NAME); + if (xXServiceDefObj != null) { - String jsonStrPostUpdate = xXServiceDefObj.getDefOptions(); + String jsonStrPostUpdate = xXServiceDefObj.getDefOptions(); Map serviceDefOptionsPostUpdate = jsonStringToMap(jsonStrPostUpdate); + if (serviceDefOptionsPostUpdate != null && serviceDefOptionsPostUpdate.containsKey(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES)) { if (serviceDefOptionsPreUpdate == null || !serviceDefOptionsPreUpdate.containsKey(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES)) { String preUpdateValue = serviceDefOptionsPreUpdate == null ? null : serviceDefOptionsPreUpdate.get(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES); + if (preUpdateValue == null) { serviceDefOptionsPostUpdate.remove(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES); } else { serviceDefOptionsPostUpdate.put(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES, preUpdateValue); } + xXServiceDefObj.setDefOptions(mapToJsonString(serviceDefOptionsPostUpdate)); + daoMgr.getXXServiceDef().update(xXServiceDefObj); } } } else { logger.error("HBase service-definition does not exist in the Ranger DAO."); + return false; } } else { logger.error("The embedded HBase service-definition does not exist."); + return false; } + return true; } private static boolean checkNewHBaseAccessTypesPresent(List accessTypeDefs) { boolean ret = false; + for (RangerServiceDef.RangerAccessTypeDef accessTypeDef : accessTypeDefs) { if (REFRESH_ACCESS_TYPE_NAME.equals(accessTypeDef.getName())) { ret = true; break; } } + return ret; } private String mapToJsonString(Map map) { String ret = null; + if (map != null) { try { ret = jsonUtil.readMapToString(map); } catch (Exception ex) { - logger.warn("mapToJsonString() failed to convert map: " + map, ex); + logger.warn("mapToJsonString() failed to convert map: {}", map, ex); } } - return ret; - } - protected Map jsonStringToMap(String jsonStr) { - Map ret = null; - if (!StringUtils.isEmpty(jsonStr)) { - try { - ret = jsonUtil.jsonToMap(jsonStr); - } catch (Exception ex) { - // fallback to earlier format: "name1=value1;name2=value2" - for (String optionString : jsonStr.split(";")) { - if (StringUtils.isEmpty(optionString)) { - continue; - } - String[] nvArr = optionString.split("="); - String name = (nvArr != null && nvArr.length > 0) ? nvArr[0].trim() : null; - String value = (nvArr != null && nvArr.length > 1) ? nvArr[1].trim() : null; - if (StringUtils.isEmpty(name)) { - continue; - } - if (ret == null) { - ret = new HashMap(); - } - ret.put(name, value); - } - } - } return ret; } } diff --git a/security-admin/src/main/java/org/apache/ranger/patch/PatchForHiveServiceDefUpdate_J10006.java b/security-admin/src/main/java/org/apache/ranger/patch/PatchForHiveServiceDefUpdate_J10006.java index a723604ea4..998a82722a 100644 --- a/security-admin/src/main/java/org/apache/ranger/patch/PatchForHiveServiceDefUpdate_J10006.java +++ b/security-admin/src/main/java/org/apache/ranger/patch/PatchForHiveServiceDefUpdate_J10006.java @@ -18,13 +18,13 @@ package org.apache.ranger.patch; import org.apache.commons.lang.StringUtils; -import org.apache.ranger.entity.XXServiceDef; import org.apache.ranger.biz.RangerBizUtil; import org.apache.ranger.biz.ServiceDBStore; import org.apache.ranger.common.JSONUtil; import org.apache.ranger.common.RangerValidatorFactory; import org.apache.ranger.common.StringUtil; import org.apache.ranger.db.RangerDaoManager; +import org.apache.ranger.entity.XXServiceDef; import org.apache.ranger.plugin.model.RangerServiceDef; import org.apache.ranger.plugin.model.RangerServiceDef.RangerDataMaskDef; import org.apache.ranger.plugin.model.RangerServiceDef.RangerRowFilterDef; @@ -45,172 +45,195 @@ @Component public class PatchForHiveServiceDefUpdate_J10006 extends BaseLoader { - private static final Logger logger = LoggerFactory.getLogger(PatchForHiveServiceDefUpdate_J10006.class); - public static final String SERVICEDBSTORE_SERVICEDEFBYNAME_HIVE_NAME = "hive"; - @Autowired - RangerDaoManager daoMgr; - - @Autowired - ServiceDBStore svcDBStore; - - @Autowired - JSONUtil jsonUtil; - - @Autowired - RangerPolicyService policyService; - - @Autowired - StringUtil stringUtil; - - @Autowired - XPolicyService xPolService; - - @Autowired - XPermMapService xPermMapService; - - @Autowired - RangerBizUtil bizUtil; - - @Autowired - RangerValidatorFactory validatorFactory; - - @Autowired - ServiceDBStore svcStore; - - public static void main(String[] args) { - logger.info("main()"); - try { - PatchForHiveServiceDefUpdate_J10006 loader = (PatchForHiveServiceDefUpdate_J10006) CLIUtil.getBean(PatchForHiveServiceDefUpdate_J10006.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); - } - } - - @Override - public void init() throws Exception { - // Do Nothing - } - - @Override - public void execLoad() { - logger.info("==> PatchForHiveServiceDefUpdate.execLoad()"); - try { - updateHiveServiceDef(); - } catch (Exception e) { - logger.error("Error whille updateHiveServiceDef()data.", e); - } - logger.info("<== PatchForHiveServiceDefUpdate.execLoad()"); - } - - @Override - public void printStats() { - logger.info("PatchForHiveServiceDefUpdate data "); - } - - private void updateHiveServiceDef(){ - RangerServiceDef ret = null; - RangerServiceDef embeddedHiveServiceDef = null; - RangerServiceDef dbHiveServiceDef = null; - RangerDataMaskDef dataMaskDef = null; - RangerRowFilterDef rowFilterDef = null; - XXServiceDef xXServiceDefObj = null; - try{ - embeddedHiveServiceDef=EmbeddedServiceDefsUtil.instance().getEmbeddedServiceDef(SERVICEDBSTORE_SERVICEDEFBYNAME_HIVE_NAME); - if(embeddedHiveServiceDef!=null){ - xXServiceDefObj = daoMgr.getXXServiceDef().findByName(SERVICEDBSTORE_SERVICEDEFBYNAME_HIVE_NAME); - Map serviceDefOptionsPreUpdate=null; - String jsonStrPreUpdate=null; - if(xXServiceDefObj!=null) { - jsonStrPreUpdate=xXServiceDefObj.getDefOptions(); - serviceDefOptionsPreUpdate=jsonStringToMap(jsonStrPreUpdate); - xXServiceDefObj=null; - } - dataMaskDef= embeddedHiveServiceDef.getDataMaskDef(); - rowFilterDef= embeddedHiveServiceDef.getRowFilterDef(); - - dbHiveServiceDef=svcDBStore.getServiceDefByName(SERVICEDBSTORE_SERVICEDEFBYNAME_HIVE_NAME); - - if(dbHiveServiceDef!=null){ - if(dataMaskDef!=null){ - dbHiveServiceDef.setDataMaskDef(dataMaskDef); - } - if(rowFilterDef!=null){ - dbHiveServiceDef.setRowFilterDef(rowFilterDef); - } - RangerServiceDefValidator validator = validatorFactory.getServiceDefValidator(svcStore); - validator.validate(dbHiveServiceDef, Action.UPDATE); - - ret = svcStore.updateServiceDef(dbHiveServiceDef); - if(ret==null){ - logger.error("Error while updating "+SERVICEDBSTORE_SERVICEDEFBYNAME_HIVE_NAME+"service-def"); - System.exit(1); - } - xXServiceDefObj = daoMgr.getXXServiceDef().findByName(SERVICEDBSTORE_SERVICEDEFBYNAME_HIVE_NAME); - if(xXServiceDefObj!=null) { - String jsonStrPostUpdate=xXServiceDefObj.getDefOptions(); - Map serviceDefOptionsPostUpdate=jsonStringToMap(jsonStrPostUpdate); - if (serviceDefOptionsPostUpdate != null && serviceDefOptionsPostUpdate.containsKey(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES)) { - if(serviceDefOptionsPreUpdate == null || !serviceDefOptionsPreUpdate.containsKey(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES)) { - String preUpdateValue = serviceDefOptionsPreUpdate == null ? null : serviceDefOptionsPreUpdate.get(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES); - if (preUpdateValue == null) { - serviceDefOptionsPostUpdate.remove(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES); - } else { - serviceDefOptionsPostUpdate.put(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES, preUpdateValue); - } - xXServiceDefObj.setDefOptions(mapToJsonString(serviceDefOptionsPostUpdate)); - daoMgr.getXXServiceDef().update(xXServiceDefObj); - } - } - } - } - } - }catch(Exception e) - { - logger.error("Error while updating "+SERVICEDBSTORE_SERVICEDEFBYNAME_HIVE_NAME+"service-def", e); - } - } - private String mapToJsonString(Map map) { - String ret = null; - if(map != null) { - try { - ret = jsonUtil.readMapToString(map); - } catch(Exception excp) { - logger.warn("mapToJsonString() failed to convert map: " + map, excp); - } - } - return ret; - } - protected Map jsonStringToMap(String jsonStr) { - Map ret = null; - if(!StringUtils.isEmpty(jsonStr)) { - try { - ret = jsonUtil.jsonToMap(jsonStr); - } catch(Exception excp) { - // fallback to earlier format: "name1=value1;name2=value2" - for(String optionString : jsonStr.split(";")) { - if(StringUtils.isEmpty(optionString)) { - continue; - } - String[] nvArr = optionString.split("="); - String name = (nvArr != null && nvArr.length > 0) ? nvArr[0].trim() : null; - String value = (nvArr != null && nvArr.length > 1) ? nvArr[1].trim() : null; - if(StringUtils.isEmpty(name)) { - continue; - } - if(ret == null) { - ret = new HashMap(); - } - ret.put(name, value); - } - } - } - return ret; - } -} \ No newline at end of file + private static final Logger logger = LoggerFactory.getLogger(PatchForHiveServiceDefUpdate_J10006.class); + + public static final String SERVICEDBSTORE_SERVICEDEFBYNAME_HIVE_NAME = "hive"; + + @Autowired + RangerDaoManager daoMgr; + + @Autowired + ServiceDBStore svcDBStore; + + @Autowired + JSONUtil jsonUtil; + + @Autowired + RangerPolicyService policyService; + + @Autowired + StringUtil stringUtil; + + @Autowired + XPolicyService xPolService; + + @Autowired + XPermMapService xPermMapService; + + @Autowired + RangerBizUtil bizUtil; + + @Autowired + RangerValidatorFactory validatorFactory; + + @Autowired + ServiceDBStore svcStore; + + public static void main(String[] args) { + logger.info("main()"); + + try { + PatchForHiveServiceDefUpdate_J10006 loader = (PatchForHiveServiceDefUpdate_J10006) CLIUtil.getBean(PatchForHiveServiceDefUpdate_J10006.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); + } + } + + @Override + public void init() throws Exception { + // Do Nothing + } + + @Override + public void printStats() { + logger.info("PatchForHiveServiceDefUpdate data "); + } + + @Override + public void execLoad() { + logger.info("==> PatchForHiveServiceDefUpdate.execLoad()"); + + try { + updateHiveServiceDef(); + } catch (Exception e) { + logger.error("Error whille updateHiveServiceDef()data.", e); + } + + logger.info("<== PatchForHiveServiceDefUpdate.execLoad()"); + } + + protected Map jsonStringToMap(String jsonStr) { + Map ret = null; + + if (!StringUtils.isEmpty(jsonStr)) { + try { + ret = jsonUtil.jsonToMap(jsonStr); + } catch (Exception excp) { + // fallback to earlier format: "name1=value1;name2=value2" + for (String optionString : jsonStr.split(";")) { + if (StringUtils.isEmpty(optionString)) { + continue; + } + + String[] nvArr = optionString.split("="); + String name = nvArr.length > 0 ? nvArr[0].trim() : null; + String value = nvArr.length > 1 ? nvArr[1].trim() : null; + + if (StringUtils.isEmpty(name)) { + continue; + } + + if (ret == null) { + ret = new HashMap<>(); + } + + ret.put(name, value); + } + } + } + return ret; + } + + private void updateHiveServiceDef() { + try { + RangerServiceDef embeddedHiveServiceDef = EmbeddedServiceDefsUtil.instance().getEmbeddedServiceDef(SERVICEDBSTORE_SERVICEDEFBYNAME_HIVE_NAME); + + if (embeddedHiveServiceDef != null) { + XXServiceDef xXServiceDefObj = daoMgr.getXXServiceDef().findByName(SERVICEDBSTORE_SERVICEDEFBYNAME_HIVE_NAME); + Map serviceDefOptionsPreUpdate = null; + + if (xXServiceDefObj != null) { + String jsonStrPreUpdate = xXServiceDefObj.getDefOptions(); + + serviceDefOptionsPreUpdate = jsonStringToMap(jsonStrPreUpdate); + } + + RangerServiceDef dbHiveServiceDef = svcDBStore.getServiceDefByName(SERVICEDBSTORE_SERVICEDEFBYNAME_HIVE_NAME); + RangerDataMaskDef dataMaskDef = embeddedHiveServiceDef.getDataMaskDef(); + RangerRowFilterDef rowFilterDef = embeddedHiveServiceDef.getRowFilterDef(); + + if (dbHiveServiceDef != null) { + if (dataMaskDef != null) { + dbHiveServiceDef.setDataMaskDef(dataMaskDef); + } + + if (rowFilterDef != null) { + dbHiveServiceDef.setRowFilterDef(rowFilterDef); + } + + RangerServiceDefValidator validator = validatorFactory.getServiceDefValidator(svcStore); + + validator.validate(dbHiveServiceDef, Action.UPDATE); + + RangerServiceDef ret = svcStore.updateServiceDef(dbHiveServiceDef); + + if (ret == null) { + logger.error("Error while updating {} service-def", SERVICEDBSTORE_SERVICEDEFBYNAME_HIVE_NAME); + + System.exit(1); + } + + xXServiceDefObj = daoMgr.getXXServiceDef().findByName(SERVICEDBSTORE_SERVICEDEFBYNAME_HIVE_NAME); + + if (xXServiceDefObj != null) { + String jsonStrPostUpdate = xXServiceDefObj.getDefOptions(); + Map serviceDefOptionsPostUpdate = jsonStringToMap(jsonStrPostUpdate); + + if (serviceDefOptionsPostUpdate != null && serviceDefOptionsPostUpdate.containsKey(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES)) { + if (serviceDefOptionsPreUpdate == null || !serviceDefOptionsPreUpdate.containsKey(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES)) { + String preUpdateValue = serviceDefOptionsPreUpdate == null ? null : serviceDefOptionsPreUpdate.get(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES); + + if (preUpdateValue == null) { + serviceDefOptionsPostUpdate.remove(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES); + } else { + serviceDefOptionsPostUpdate.put(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES, preUpdateValue); + } + + xXServiceDefObj.setDefOptions(mapToJsonString(serviceDefOptionsPostUpdate)); + + daoMgr.getXXServiceDef().update(xXServiceDefObj); + } + } + } + } + } + } catch (Exception e) { + logger.error("Error while updating {} service-def", SERVICEDBSTORE_SERVICEDEFBYNAME_HIVE_NAME, e); + } + } + + private String mapToJsonString(Map map) { + String ret = null; + + if (map != null) { + try { + ret = jsonUtil.readMapToString(map); + } catch (Exception excp) { + logger.warn("mapToJsonString() failed to convert map: {}", map, excp); + } + } + + return ret; + } +} diff --git a/security-admin/src/main/java/org/apache/ranger/patch/PatchForHiveServiceDefUpdate_J10007.java b/security-admin/src/main/java/org/apache/ranger/patch/PatchForHiveServiceDefUpdate_J10007.java index ae2303c19f..7157435f16 100644 --- a/security-admin/src/main/java/org/apache/ranger/patch/PatchForHiveServiceDefUpdate_J10007.java +++ b/security-admin/src/main/java/org/apache/ranger/patch/PatchForHiveServiceDefUpdate_J10007.java @@ -24,6 +24,7 @@ import org.apache.ranger.common.RangerValidatorFactory; import org.apache.ranger.common.StringUtil; import org.apache.ranger.db.RangerDaoManager; +import org.apache.ranger.entity.XXServiceDef; import org.apache.ranger.plugin.model.RangerServiceDef; import org.apache.ranger.plugin.model.validation.RangerServiceDefValidator; import org.apache.ranger.plugin.model.validation.RangerValidator.Action; @@ -36,201 +37,223 @@ import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; -import org.apache.ranger.entity.XXServiceDef; + import java.util.HashMap; import java.util.List; import java.util.Map; @Component public class PatchForHiveServiceDefUpdate_J10007 extends BaseLoader { - private static final Logger logger = LoggerFactory.getLogger(PatchForHiveServiceDefUpdate_J10007.class); - public static final String SERVICEDBSTORE_SERVICEDEFBYNAME_HIVE_NAME = "hive"; - public static final String URL_RESOURCE_NAME ="url"; - - @Autowired - RangerDaoManager daoMgr; - - @Autowired - ServiceDBStore svcDBStore; - - @Autowired - JSONUtil jsonUtil; - - @Autowired - RangerPolicyService policyService; - - @Autowired - StringUtil stringUtil; - - @Autowired - XPolicyService xPolService; - - @Autowired - XPermMapService xPermMapService; - - @Autowired - RangerBizUtil bizUtil; - - @Autowired - RangerValidatorFactory validatorFactory; - - @Autowired - ServiceDBStore svcStore; - - public static void main(String[] args) { - logger.info("main()"); - try { - PatchForHiveServiceDefUpdate_J10007 loader = (PatchForHiveServiceDefUpdate_J10007) CLIUtil.getBean(PatchForHiveServiceDefUpdate_J10007.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); - } - } - - @Override - public void init() throws Exception { - // Do Nothing - } - - @Override - public void execLoad() { - logger.info("==> PatchForHiveServiceDefUpdate.execLoad()"); - try { - updateHiveServiceDef(); - } catch (Exception e) { - logger.error("Error whille updateHiveServiceDef()data.", e); - } - logger.info("<== PatchForHiveServiceDefUpdate.execLoad()"); - } - - @Override - public void printStats() { - logger.info("PatchForHiveServiceDefUpdate data "); - } - - private void updateHiveServiceDef(){ - RangerServiceDef ret = null; - RangerServiceDef embeddedHiveServiceDef = null; - RangerServiceDef dbHiveServiceDef = null; - List embeddedHiveResourceDefs = null; - List embeddedHiveAccessTypes = null; - XXServiceDef xXServiceDefObj = null; - try{ - embeddedHiveServiceDef=EmbeddedServiceDefsUtil.instance().getEmbeddedServiceDef(SERVICEDBSTORE_SERVICEDEFBYNAME_HIVE_NAME); - if(embeddedHiveServiceDef!=null){ - - xXServiceDefObj = daoMgr.getXXServiceDef().findByName(SERVICEDBSTORE_SERVICEDEFBYNAME_HIVE_NAME); - Map serviceDefOptionsPreUpdate=null; - String jsonStrPreUpdate=null; - if(xXServiceDefObj!=null) { - jsonStrPreUpdate=xXServiceDefObj.getDefOptions(); - serviceDefOptionsPreUpdate=jsonStringToMap(jsonStrPreUpdate); - xXServiceDefObj=null; - } - dbHiveServiceDef=svcDBStore.getServiceDefByName(SERVICEDBSTORE_SERVICEDEFBYNAME_HIVE_NAME); - - if(dbHiveServiceDef!=null){ - embeddedHiveResourceDefs = embeddedHiveServiceDef.getResources(); - embeddedHiveAccessTypes = embeddedHiveServiceDef.getAccessTypes(); - - if (checkURLresourcePresent(embeddedHiveResourceDefs)) { - // This is to check if URL def is added to the resource definition, if so update the resource def and accessType def - if (embeddedHiveResourceDefs != null) { - dbHiveServiceDef.setResources(embeddedHiveResourceDefs); - } - if (embeddedHiveAccessTypes != null) { - if(!embeddedHiveAccessTypes.toString().equalsIgnoreCase(dbHiveServiceDef.getAccessTypes().toString())) { - dbHiveServiceDef.setAccessTypes(embeddedHiveAccessTypes); - } - } - } - - RangerServiceDefValidator validator = validatorFactory.getServiceDefValidator(svcStore); - validator.validate(dbHiveServiceDef, Action.UPDATE); - - ret = svcStore.updateServiceDef(dbHiveServiceDef); - if(ret==null){ - logger.error("Error while updating "+SERVICEDBSTORE_SERVICEDEFBYNAME_HIVE_NAME+"service-def"); - throw new RuntimeException("Error while updating "+SERVICEDBSTORE_SERVICEDEFBYNAME_HIVE_NAME+"service-def"); - } - xXServiceDefObj = daoMgr.getXXServiceDef().findByName(SERVICEDBSTORE_SERVICEDEFBYNAME_HIVE_NAME); - if(xXServiceDefObj!=null) { - String jsonStrPostUpdate=xXServiceDefObj.getDefOptions(); - Map serviceDefOptionsPostUpdate=jsonStringToMap(jsonStrPostUpdate); - if (serviceDefOptionsPostUpdate != null && serviceDefOptionsPostUpdate.containsKey(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES)) { - if(serviceDefOptionsPreUpdate == null || !serviceDefOptionsPreUpdate.containsKey(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES)) { - String preUpdateValue = serviceDefOptionsPreUpdate == null ? null : serviceDefOptionsPreUpdate.get(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES); - if (preUpdateValue == null) { - serviceDefOptionsPostUpdate.remove(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES); - } else { - serviceDefOptionsPostUpdate.put(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES, preUpdateValue); - } - xXServiceDefObj.setDefOptions(mapToJsonString(serviceDefOptionsPostUpdate)); - daoMgr.getXXServiceDef().update(xXServiceDefObj); - } - } - } - } - } - }catch(Exception e) - { - logger.error("Error while updating "+SERVICEDBSTORE_SERVICEDEFBYNAME_HIVE_NAME+"service-def", e); - } - } - - private boolean checkURLresourcePresent(List resourceDefs) { - boolean ret = false; - for(RangerServiceDef.RangerResourceDef resourceDef : resourceDefs) { - if ( URL_RESOURCE_NAME.equals(resourceDef.getName()) ) { - ret = true ; - break; - } - } - return ret; - } - - private String mapToJsonString(Map map) { - String ret = null; - if(map != null) { - try { - ret = jsonUtil.readMapToString(map); - } catch(Exception excp) { - logger.warn("mapToJsonString() failed to convert map: " + map, excp); - } - } - return ret; - } - - protected Map jsonStringToMap(String jsonStr) { - Map ret = null; - if(!StringUtils.isEmpty(jsonStr)) { - try { - ret = jsonUtil.jsonToMap(jsonStr); - } catch(Exception excp) { - // fallback to earlier format: "name1=value1;name2=value2" - for(String optionString : jsonStr.split(";")) { - if(StringUtils.isEmpty(optionString)) { - continue; - } - String[] nvArr = optionString.split("="); - String name = (nvArr != null && nvArr.length > 0) ? nvArr[0].trim() : null; - String value = (nvArr != null && nvArr.length > 1) ? nvArr[1].trim() : null; - if(StringUtils.isEmpty(name)) { - continue; - } - if(ret == null) { - ret = new HashMap(); - } - ret.put(name, value); - } - } - } - return ret; - } -} \ No newline at end of file + private static final Logger logger = LoggerFactory.getLogger(PatchForHiveServiceDefUpdate_J10007.class); + + public static final String SERVICEDBSTORE_SERVICEDEFBYNAME_HIVE_NAME = "hive"; + public static final String URL_RESOURCE_NAME = "url"; + + @Autowired + RangerDaoManager daoMgr; + + @Autowired + ServiceDBStore svcDBStore; + + @Autowired + JSONUtil jsonUtil; + + @Autowired + RangerPolicyService policyService; + + @Autowired + StringUtil stringUtil; + + @Autowired + XPolicyService xPolService; + + @Autowired + XPermMapService xPermMapService; + + @Autowired + RangerBizUtil bizUtil; + + @Autowired + RangerValidatorFactory validatorFactory; + + @Autowired + ServiceDBStore svcStore; + + public static void main(String[] args) { + logger.info("main()"); + + try { + PatchForHiveServiceDefUpdate_J10007 loader = (PatchForHiveServiceDefUpdate_J10007) CLIUtil.getBean(PatchForHiveServiceDefUpdate_J10007.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); + } + } + + @Override + public void init() throws Exception { + // Do Nothing + } + + @Override + public void printStats() { + logger.info("PatchForHiveServiceDefUpdate data "); + } + + @Override + public void execLoad() { + logger.info("==> PatchForHiveServiceDefUpdate.execLoad()"); + + try { + updateHiveServiceDef(); + } catch (Exception e) { + logger.error("Error whille updateHiveServiceDef()data.", e); + } + + logger.info("<== PatchForHiveServiceDefUpdate.execLoad()"); + } + + protected Map jsonStringToMap(String jsonStr) { + Map ret = null; + + if (!StringUtils.isEmpty(jsonStr)) { + try { + ret = jsonUtil.jsonToMap(jsonStr); + } catch (Exception excp) { + // fallback to earlier format: "name1=value1;name2=value2" + for (String optionString : jsonStr.split(";")) { + if (StringUtils.isEmpty(optionString)) { + continue; + } + + String[] nvArr = optionString.split("="); + String name = nvArr.length > 0 ? nvArr[0].trim() : null; + String value = nvArr.length > 1 ? nvArr[1].trim() : null; + + if (StringUtils.isEmpty(name)) { + continue; + } + + if (ret == null) { + ret = new HashMap<>(); + } + + ret.put(name, value); + } + } + } + return ret; + } + + private void updateHiveServiceDef() { + try { + RangerServiceDef embeddedHiveServiceDef = EmbeddedServiceDefsUtil.instance().getEmbeddedServiceDef(SERVICEDBSTORE_SERVICEDEFBYNAME_HIVE_NAME); + + if (embeddedHiveServiceDef != null) { + XXServiceDef xXServiceDefObj = daoMgr.getXXServiceDef().findByName(SERVICEDBSTORE_SERVICEDEFBYNAME_HIVE_NAME); + Map serviceDefOptionsPreUpdate = null; + String jsonStrPreUpdate; + + if (xXServiceDefObj != null) { + jsonStrPreUpdate = xXServiceDefObj.getDefOptions(); + serviceDefOptionsPreUpdate = jsonStringToMap(jsonStrPreUpdate); + } + + RangerServiceDef dbHiveServiceDef = svcDBStore.getServiceDefByName(SERVICEDBSTORE_SERVICEDEFBYNAME_HIVE_NAME); + + if (dbHiveServiceDef != null) { + List embeddedHiveResourceDefs = embeddedHiveServiceDef.getResources(); + List embeddedHiveAccessTypes = embeddedHiveServiceDef.getAccessTypes(); + + if (checkURLresourcePresent(embeddedHiveResourceDefs)) { + // This is to check if URL def is added to the resource definition, if so update the resource def and accessType def + if (embeddedHiveResourceDefs != null) { + dbHiveServiceDef.setResources(embeddedHiveResourceDefs); + } + + if (embeddedHiveAccessTypes != null) { + if (!embeddedHiveAccessTypes.toString().equalsIgnoreCase(dbHiveServiceDef.getAccessTypes().toString())) { + dbHiveServiceDef.setAccessTypes(embeddedHiveAccessTypes); + } + } + } + + RangerServiceDefValidator validator = validatorFactory.getServiceDefValidator(svcStore); + + validator.validate(dbHiveServiceDef, Action.UPDATE); + + RangerServiceDef ret = svcStore.updateServiceDef(dbHiveServiceDef); + + if (ret == null) { + logger.error("Error while updating {} service-def", SERVICEDBSTORE_SERVICEDEFBYNAME_HIVE_NAME); + + throw new RuntimeException("Error while updating " + SERVICEDBSTORE_SERVICEDEFBYNAME_HIVE_NAME + "service-def"); + } + + xXServiceDefObj = daoMgr.getXXServiceDef().findByName(SERVICEDBSTORE_SERVICEDEFBYNAME_HIVE_NAME); + + if (xXServiceDefObj != null) { + String jsonStrPostUpdate = xXServiceDefObj.getDefOptions(); + Map serviceDefOptionsPostUpdate = jsonStringToMap(jsonStrPostUpdate); + + if (serviceDefOptionsPostUpdate != null && serviceDefOptionsPostUpdate.containsKey(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES)) { + if (serviceDefOptionsPreUpdate == null || !serviceDefOptionsPreUpdate.containsKey(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES)) { + String preUpdateValue = serviceDefOptionsPreUpdate == null ? null : serviceDefOptionsPreUpdate.get(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES); + + if (preUpdateValue == null) { + serviceDefOptionsPostUpdate.remove(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES); + } else { + serviceDefOptionsPostUpdate.put(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES, preUpdateValue); + } + + xXServiceDefObj.setDefOptions(mapToJsonString(serviceDefOptionsPostUpdate)); + + daoMgr.getXXServiceDef().update(xXServiceDefObj); + } + } + } + } + } + } catch (Exception e) { + logger.error("Error while updating {} service-def", SERVICEDBSTORE_SERVICEDEFBYNAME_HIVE_NAME, e); + } + } + + private boolean checkURLresourcePresent(List resourceDefs) { + boolean ret = false; + + for (RangerServiceDef.RangerResourceDef resourceDef : resourceDefs) { + if (URL_RESOURCE_NAME.equals(resourceDef.getName())) { + ret = true; + break; + } + } + + return ret; + } + + private String mapToJsonString(Map map) { + String ret = null; + + if (map != null) { + try { + ret = jsonUtil.readMapToString(map); + } catch (Exception excp) { + logger.warn("mapToJsonString() failed to convert map: {}", map, excp); + } + } + + return ret; + } +} diff --git a/security-admin/src/main/java/org/apache/ranger/patch/PatchForHiveServiceDefUpdate_J10009.java b/security-admin/src/main/java/org/apache/ranger/patch/PatchForHiveServiceDefUpdate_J10009.java index 949da3a712..b234a79299 100644 --- a/security-admin/src/main/java/org/apache/ranger/patch/PatchForHiveServiceDefUpdate_J10009.java +++ b/security-admin/src/main/java/org/apache/ranger/patch/PatchForHiveServiceDefUpdate_J10009.java @@ -44,184 +44,208 @@ @Component public class PatchForHiveServiceDefUpdate_J10009 extends BaseLoader { - private static final Logger logger = LoggerFactory.getLogger(PatchForHiveServiceDefUpdate_J10009.class); - public static final String SERVICEDBSTORE_SERVICEDEFBYNAME_HIVE_NAME = "hive"; - public static final String URL_RESOURCE_NAME ="url"; - - @Autowired - RangerDaoManager daoMgr; - - @Autowired - ServiceDBStore svcDBStore; - - @Autowired - JSONUtil jsonUtil; - - @Autowired - RangerPolicyService policyService; - - @Autowired - StringUtil stringUtil; - - @Autowired - XPolicyService xPolService; - - @Autowired - XPermMapService xPermMapService; - - @Autowired - RangerBizUtil bizUtil; - - @Autowired - RangerValidatorFactory validatorFactory; - - @Autowired - ServiceDBStore svcStore; - - public static void main(String[] args) { - logger.info("main()"); - try { - PatchForHiveServiceDefUpdate_J10009 loader = (PatchForHiveServiceDefUpdate_J10009) CLIUtil.getBean(PatchForHiveServiceDefUpdate_J10009.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); - } - } - - @Override - public void init() throws Exception { - // Do Nothing - } - - @Override - public void execLoad() { - logger.info("==> PatchForHiveServiceDefUpdate.execLoad()"); - try { - updateHiveServiceDef(); - } catch (Exception e) { - logger.error("Error whille updateHiveServiceDef()data.", e); - } - logger.info("<== PatchForHiveServiceDefUpdate.execLoad()"); - } - - @Override - public void printStats() { - logger.info("PatchForHiveServiceDefUpdate data "); - } - - private void updateHiveServiceDef(){ - RangerServiceDef ret = null; - RangerServiceDef embeddedHiveServiceDef = null; - RangerServiceDef dbHiveServiceDef = null; - List embeddedHiveAccessTypes = null; - XXServiceDef xXServiceDefObj = null; - try{ - embeddedHiveServiceDef=EmbeddedServiceDefsUtil.instance().getEmbeddedServiceDef(SERVICEDBSTORE_SERVICEDEFBYNAME_HIVE_NAME); - if(embeddedHiveServiceDef!=null){ - - xXServiceDefObj = daoMgr.getXXServiceDef().findByName(SERVICEDBSTORE_SERVICEDEFBYNAME_HIVE_NAME); - Map serviceDefOptionsPreUpdate=null; - String jsonStrPreUpdate=null; - if(xXServiceDefObj!=null) { - jsonStrPreUpdate=xXServiceDefObj.getDefOptions(); - serviceDefOptionsPreUpdate=jsonStringToMap(jsonStrPreUpdate); - xXServiceDefObj=null; - } - dbHiveServiceDef=svcDBStore.getServiceDefByName(SERVICEDBSTORE_SERVICEDEFBYNAME_HIVE_NAME); - - if(dbHiveServiceDef!=null){ - embeddedHiveAccessTypes = embeddedHiveServiceDef.getAccessTypes(); - if (checkHiveAccessType(embeddedHiveAccessTypes)) { - // This is to check if HiveServiceDef AccessType has the new AccessType and if Present update the dbHiveServiceDef along with new Admin accessType. - dbHiveServiceDef.setAccessTypes(embeddedHiveAccessTypes); - } - - RangerServiceDefValidator validator = validatorFactory.getServiceDefValidator(svcStore); - validator.validate(dbHiveServiceDef, Action.UPDATE); - - ret = svcStore.updateServiceDef(dbHiveServiceDef); - if(ret==null){ - logger.error("Error while updating "+SERVICEDBSTORE_SERVICEDEFBYNAME_HIVE_NAME+"service-def"); - throw new RuntimeException("Error while updating "+SERVICEDBSTORE_SERVICEDEFBYNAME_HIVE_NAME+"service-def"); - } - xXServiceDefObj = daoMgr.getXXServiceDef().findByName(SERVICEDBSTORE_SERVICEDEFBYNAME_HIVE_NAME); - if(xXServiceDefObj!=null) { - String jsonStrPostUpdate=xXServiceDefObj.getDefOptions(); - Map serviceDefOptionsPostUpdate=jsonStringToMap(jsonStrPostUpdate); - if (serviceDefOptionsPostUpdate != null && serviceDefOptionsPostUpdate.containsKey(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES)) { - if(serviceDefOptionsPreUpdate == null || !serviceDefOptionsPreUpdate.containsKey(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES)) { - String preUpdateValue = serviceDefOptionsPreUpdate == null ? null : serviceDefOptionsPreUpdate.get(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES); - if (preUpdateValue == null) { - serviceDefOptionsPostUpdate.remove(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES); - } else { - serviceDefOptionsPostUpdate.put(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES, preUpdateValue); - } - xXServiceDefObj.setDefOptions(mapToJsonString(serviceDefOptionsPostUpdate)); - daoMgr.getXXServiceDef().update(xXServiceDefObj); - } - } - } - } - } - }catch(Exception e) - { - logger.error("Error while updating "+SERVICEDBSTORE_SERVICEDEFBYNAME_HIVE_NAME+"service-def", e); - } - } - - private boolean checkHiveAccessType(List embeddedHiveAccessTypes) { - boolean ret = false; - for (RangerServiceDef.RangerAccessTypeDef embeddedHiveAccessType : embeddedHiveAccessTypes) { - if ( embeddedHiveAccessType.getName().equals("repladmin") ) { - ret = true; - break; - } - } - return ret; - } - - private String mapToJsonString(Map map) { - String ret = null; - if(map != null) { - try { - ret = jsonUtil.readMapToString(map); - } catch(Exception excp) { - logger.warn("mapToJsonString() failed to convert map: " + map, excp); - } - } - return ret; - } - - protected Map jsonStringToMap(String jsonStr) { - Map ret = null; - if(!StringUtils.isEmpty(jsonStr)) { - try { - ret = jsonUtil.jsonToMap(jsonStr); - } catch(Exception excp) { - // fallback to earlier format: "name1=value1;name2=value2" - for(String optionString : jsonStr.split(";")) { - if(StringUtils.isEmpty(optionString)) { - continue; - } - String[] nvArr = optionString.split("="); - String name = (nvArr != null && nvArr.length > 0) ? nvArr[0].trim() : null; - String value = (nvArr != null && nvArr.length > 1) ? nvArr[1].trim() : null; - if(StringUtils.isEmpty(name)) { - continue; - } - if(ret == null) { - ret = new HashMap(); - } - ret.put(name, value); - } - } - } - return ret; - } -} \ No newline at end of file + private static final Logger logger = LoggerFactory.getLogger(PatchForHiveServiceDefUpdate_J10009.class); + + public static final String SERVICEDBSTORE_SERVICEDEFBYNAME_HIVE_NAME = "hive"; + public static final String URL_RESOURCE_NAME = "url"; + + @Autowired + RangerDaoManager daoMgr; + + @Autowired + ServiceDBStore svcDBStore; + + @Autowired + JSONUtil jsonUtil; + + @Autowired + RangerPolicyService policyService; + + @Autowired + StringUtil stringUtil; + + @Autowired + XPolicyService xPolService; + + @Autowired + XPermMapService xPermMapService; + + @Autowired + RangerBizUtil bizUtil; + + @Autowired + RangerValidatorFactory validatorFactory; + + @Autowired + ServiceDBStore svcStore; + + public static void main(String[] args) { + logger.info("main()"); + + try { + PatchForHiveServiceDefUpdate_J10009 loader = (PatchForHiveServiceDefUpdate_J10009) CLIUtil.getBean(PatchForHiveServiceDefUpdate_J10009.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); + } + } + + @Override + public void init() throws Exception { + // Do Nothing + } + + @Override + public void printStats() { + logger.info("PatchForHiveServiceDefUpdate data "); + } + + @Override + public void execLoad() { + logger.info("==> PatchForHiveServiceDefUpdate.execLoad()"); + + try { + updateHiveServiceDef(); + } catch (Exception e) { + logger.error("Error whille updateHiveServiceDef()data.", e); + } + + logger.info("<== PatchForHiveServiceDefUpdate.execLoad()"); + } + + protected Map jsonStringToMap(String jsonStr) { + Map ret = null; + + if (!StringUtils.isEmpty(jsonStr)) { + try { + ret = jsonUtil.jsonToMap(jsonStr); + } catch (Exception excp) { + // fallback to earlier format: "name1=value1;name2=value2" + for (String optionString : jsonStr.split(";")) { + if (StringUtils.isEmpty(optionString)) { + continue; + } + + String[] nvArr = optionString.split("="); + String name = nvArr.length > 0 ? nvArr[0].trim() : null; + String value = nvArr.length > 1 ? nvArr[1].trim() : null; + + if (StringUtils.isEmpty(name)) { + continue; + } + + if (ret == null) { + ret = new HashMap<>(); + } + + ret.put(name, value); + } + } + } + + return ret; + } + + private void updateHiveServiceDef() { + try { + RangerServiceDef embeddedHiveServiceDef = EmbeddedServiceDefsUtil.instance().getEmbeddedServiceDef(SERVICEDBSTORE_SERVICEDEFBYNAME_HIVE_NAME); + + if (embeddedHiveServiceDef != null) { + XXServiceDef xXServiceDefObj = daoMgr.getXXServiceDef().findByName(SERVICEDBSTORE_SERVICEDEFBYNAME_HIVE_NAME); + Map serviceDefOptionsPreUpdate = null; + String jsonStrPreUpdate; + + if (xXServiceDefObj != null) { + jsonStrPreUpdate = xXServiceDefObj.getDefOptions(); + serviceDefOptionsPreUpdate = jsonStringToMap(jsonStrPreUpdate); + } + + RangerServiceDef dbHiveServiceDef = svcDBStore.getServiceDefByName(SERVICEDBSTORE_SERVICEDEFBYNAME_HIVE_NAME); + + if (dbHiveServiceDef != null) { + List embeddedHiveAccessTypes = embeddedHiveServiceDef.getAccessTypes(); + + if (checkHiveAccessType(embeddedHiveAccessTypes)) { + // This is to check if HiveServiceDef AccessType has the new AccessType and if Present update the dbHiveServiceDef along with new Admin accessType. + dbHiveServiceDef.setAccessTypes(embeddedHiveAccessTypes); + } + + RangerServiceDefValidator validator = validatorFactory.getServiceDefValidator(svcStore); + + validator.validate(dbHiveServiceDef, Action.UPDATE); + + RangerServiceDef ret = svcStore.updateServiceDef(dbHiveServiceDef); + + if (ret == null) { + logger.error("Error while updating {} service-def", SERVICEDBSTORE_SERVICEDEFBYNAME_HIVE_NAME); + + throw new RuntimeException("Error while updating " + SERVICEDBSTORE_SERVICEDEFBYNAME_HIVE_NAME + "service-def"); + } + + xXServiceDefObj = daoMgr.getXXServiceDef().findByName(SERVICEDBSTORE_SERVICEDEFBYNAME_HIVE_NAME); + + if (xXServiceDefObj != null) { + String jsonStrPostUpdate = xXServiceDefObj.getDefOptions(); + Map serviceDefOptionsPostUpdate = jsonStringToMap(jsonStrPostUpdate); + + if (serviceDefOptionsPostUpdate != null && serviceDefOptionsPostUpdate.containsKey(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES)) { + if (serviceDefOptionsPreUpdate == null || !serviceDefOptionsPreUpdate.containsKey(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES)) { + String preUpdateValue = serviceDefOptionsPreUpdate == null ? null : serviceDefOptionsPreUpdate.get(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES); + + if (preUpdateValue == null) { + serviceDefOptionsPostUpdate.remove(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES); + } else { + serviceDefOptionsPostUpdate.put(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES, preUpdateValue); + } + + xXServiceDefObj.setDefOptions(mapToJsonString(serviceDefOptionsPostUpdate)); + + daoMgr.getXXServiceDef().update(xXServiceDefObj); + } + } + } + } + } + } catch (Exception e) { + logger.error("Error while updating {} service-def", SERVICEDBSTORE_SERVICEDEFBYNAME_HIVE_NAME, e); + } + } + + private boolean checkHiveAccessType(List embeddedHiveAccessTypes) { + boolean ret = false; + + for (RangerServiceDef.RangerAccessTypeDef embeddedHiveAccessType : embeddedHiveAccessTypes) { + if (embeddedHiveAccessType.getName().equals("repladmin")) { + ret = true; + break; + } + } + + return ret; + } + + private String mapToJsonString(Map map) { + String ret = null; + + if (map != null) { + try { + ret = jsonUtil.readMapToString(map); + } catch (Exception excp) { + logger.warn("mapToJsonString() failed to convert map: {}", map, excp); + } + } + + return ret; + } +} diff --git a/security-admin/src/main/java/org/apache/ranger/patch/PatchForHiveServiceDefUpdate_J10010.java b/security-admin/src/main/java/org/apache/ranger/patch/PatchForHiveServiceDefUpdate_J10010.java index c3c605090d..013cb60c47 100644 --- a/security-admin/src/main/java/org/apache/ranger/patch/PatchForHiveServiceDefUpdate_J10010.java +++ b/security-admin/src/main/java/org/apache/ranger/patch/PatchForHiveServiceDefUpdate_J10010.java @@ -24,6 +24,7 @@ import org.apache.ranger.common.RangerValidatorFactory; import org.apache.ranger.common.StringUtil; import org.apache.ranger.db.RangerDaoManager; +import org.apache.ranger.entity.XXServiceDef; import org.apache.ranger.plugin.model.RangerServiceDef; import org.apache.ranger.plugin.model.validation.RangerServiceDefValidator; import org.apache.ranger.plugin.model.validation.RangerValidator.Action; @@ -36,179 +37,191 @@ import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; -import org.apache.ranger.entity.XXServiceDef; import java.util.List; import java.util.Map; @Component public class PatchForHiveServiceDefUpdate_J10010 extends BaseLoader { - private static final Logger logger = LoggerFactory.getLogger(PatchForHiveServiceDefUpdate_J10010.class); - public static final String SERVICEDBSTORE_SERVICEDEFBYNAME_HIVE_NAME = "hive"; - public static final String HIVE_SERVICE_RESOURCE_NAME ="hiveservice"; - - @Autowired - RangerDaoManager daoMgr; - - @Autowired - ServiceDBStore svcDBStore; - - @Autowired - JSONUtil jsonUtil; - - @Autowired - RangerPolicyService policyService; - - @Autowired - StringUtil stringUtil; - - @Autowired - XPolicyService xPolService; - - @Autowired - XPermMapService xPermMapService; - - @Autowired - RangerBizUtil bizUtil; - - @Autowired - RangerValidatorFactory validatorFactory; - - @Autowired - ServiceDBStore svcStore; - - public static void main(String[] args) { - logger.info("main()"); - try { - PatchForHiveServiceDefUpdate_J10010 loader = (PatchForHiveServiceDefUpdate_J10010) CLIUtil.getBean(PatchForHiveServiceDefUpdate_J10010.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); - } - } - - @Override - public void init() throws Exception { - // Do Nothing - } - - @Override - public void execLoad() { - logger.info("==> PatchForHiveServiceDefUpdateForResourceSpecificAccesses.execLoad()"); - try { - updateHiveServiceDef(); - } catch (Exception e) { - logger.error("Error whille updateHiveServiceDef()data.", e); - } - logger.info("<== PatchForHiveServiceDefUpdateForResourceSpecificAccesses.execLoad()"); - } - - @Override - public void printStats() { - logger.info("PatchForHiveServiceDefUpdateForResourceSpecificAccesses data "); - } - - private void updateHiveServiceDef(){ - RangerServiceDef embeddedHiveServiceDef = null; - RangerServiceDef dbHiveServiceDef = null; - XXServiceDef xXServiceDefObj = null; - try{ - embeddedHiveServiceDef = EmbeddedServiceDefsUtil.instance().getEmbeddedServiceDef(SERVICEDBSTORE_SERVICEDEFBYNAME_HIVE_NAME); - - if (embeddedHiveServiceDef != null) { - xXServiceDefObj = daoMgr.getXXServiceDef().findByName(SERVICEDBSTORE_SERVICEDEFBYNAME_HIVE_NAME); - if (xXServiceDefObj == null) { - logger.error("Service def for " + SERVICEDBSTORE_SERVICEDEFBYNAME_HIVE_NAME + " is not found!!"); - return; - } - - String jsonStrPreUpdate = xXServiceDefObj.getDefOptions(); - Map serviceDefOptionsPreUpdate = jsonUtil.jsonToMap(jsonStrPreUpdate); - String valueBeforeUpdate = serviceDefOptionsPreUpdate.get(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES); - - dbHiveServiceDef = svcDBStore.getServiceDefByName(SERVICEDBSTORE_SERVICEDEFBYNAME_HIVE_NAME); - - if(dbHiveServiceDef != null) { - boolean isServiceDefUpdated = updateServiceDef(dbHiveServiceDef, embeddedHiveServiceDef); - - if (isServiceDefUpdated) { - xXServiceDefObj = daoMgr.getXXServiceDef().findByName(SERVICEDBSTORE_SERVICEDEFBYNAME_HIVE_NAME); - - if (xXServiceDefObj != null) { - String jsonStrPostUpdate = xXServiceDefObj.getDefOptions(); - Map serviceDefOptionsPostUpdate = jsonUtil.jsonToMap(jsonStrPostUpdate); - String valueAfterUpdate = serviceDefOptionsPostUpdate.get(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES); - - if (!StringUtils.equals(valueBeforeUpdate, valueAfterUpdate)) { - if (StringUtils.isEmpty(valueBeforeUpdate)) { - serviceDefOptionsPostUpdate.remove(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES); - } else { - serviceDefOptionsPostUpdate.put(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES, valueBeforeUpdate); - } - xXServiceDefObj.setDefOptions(mapToJsonString(serviceDefOptionsPostUpdate)); - daoMgr.getXXServiceDef().update(xXServiceDefObj); - } - } - } - } - } - } catch(Exception e) { - logger.error("Error while updating "+SERVICEDBSTORE_SERVICEDEFBYNAME_HIVE_NAME+"service-def", e); - } - } - - private boolean updateServiceDef(RangerServiceDef serviceDef, RangerServiceDef embeddedHiveServiceDef ) throws Exception { - boolean ret = false; - - List embeddedHiveResourceDefs = null; - List embeddedHiveAccessTypes = null; - - embeddedHiveResourceDefs = embeddedHiveServiceDef.getResources(); - embeddedHiveAccessTypes = embeddedHiveServiceDef.getAccessTypes(); - - if (checkHiveServiceresourcePresent(embeddedHiveResourceDefs)) { - // This is to check if HIVESERVICE def is added to the resource definition, if so update the resource def and accessType def - if (embeddedHiveResourceDefs != null) { - serviceDef.setResources(embeddedHiveResourceDefs); - } - if (embeddedHiveAccessTypes != null) { - if(!embeddedHiveAccessTypes.toString().equalsIgnoreCase(serviceDef.getAccessTypes().toString())) { - serviceDef.setAccessTypes(embeddedHiveAccessTypes); - } - } - ret = true; - } - - RangerServiceDefValidator validator = validatorFactory.getServiceDefValidator(svcStore); - validator.validate(serviceDef, Action.UPDATE); - svcStore.updateServiceDef(serviceDef); - - return ret; - } - - private boolean checkHiveServiceresourcePresent(List resourceDefs) { - boolean ret = false; - for(RangerServiceDef.RangerResourceDef resourceDef : resourceDefs) { - if (HIVE_SERVICE_RESOURCE_NAME.equals(resourceDef.getName()) ) { - ret = true ; - break; - } - } - return ret; - } - - private String mapToJsonString(Map map) throws Exception { - String ret = null; - if(map != null) { - ret = jsonUtil.readMapToString(map); - } - return ret; - } -} + private static final Logger logger = LoggerFactory.getLogger(PatchForHiveServiceDefUpdate_J10010.class); + + public static final String SERVICEDBSTORE_SERVICEDEFBYNAME_HIVE_NAME = "hive"; + public static final String HIVE_SERVICE_RESOURCE_NAME = "hiveservice"; + + @Autowired + RangerDaoManager daoMgr; + + @Autowired + ServiceDBStore svcDBStore; + + @Autowired + JSONUtil jsonUtil; + + @Autowired + RangerPolicyService policyService; + + @Autowired + StringUtil stringUtil; + + @Autowired + XPolicyService xPolService; + + @Autowired + XPermMapService xPermMapService; + + @Autowired + RangerBizUtil bizUtil; + + @Autowired + RangerValidatorFactory validatorFactory; + + @Autowired + ServiceDBStore svcStore; + + public static void main(String[] args) { + logger.info("main()"); + + try { + PatchForHiveServiceDefUpdate_J10010 loader = (PatchForHiveServiceDefUpdate_J10010) CLIUtil.getBean(PatchForHiveServiceDefUpdate_J10010.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); + } + } + + @Override + public void init() throws Exception { + // Do Nothing + } + + @Override + public void printStats() { + logger.info("PatchForHiveServiceDefUpdateForResourceSpecificAccesses data "); + } + + @Override + public void execLoad() { + logger.info("==> PatchForHiveServiceDefUpdateForResourceSpecificAccesses.execLoad()"); + + try { + updateHiveServiceDef(); + } catch (Exception e) { + logger.error("Error whille updateHiveServiceDef()data.", e); + } + logger.info("<== PatchForHiveServiceDefUpdateForResourceSpecificAccesses.execLoad()"); + } + + private void updateHiveServiceDef() { + try { + RangerServiceDef embeddedHiveServiceDef = EmbeddedServiceDefsUtil.instance().getEmbeddedServiceDef(SERVICEDBSTORE_SERVICEDEFBYNAME_HIVE_NAME); + + if (embeddedHiveServiceDef != null) { + XXServiceDef xXServiceDefObj = daoMgr.getXXServiceDef().findByName(SERVICEDBSTORE_SERVICEDEFBYNAME_HIVE_NAME); + + if (xXServiceDefObj == null) { + logger.error("Service def for {} is not found!!", SERVICEDBSTORE_SERVICEDEFBYNAME_HIVE_NAME); + + return; + } + + String jsonStrPreUpdate = xXServiceDefObj.getDefOptions(); + Map serviceDefOptionsPreUpdate = jsonUtil.jsonToMap(jsonStrPreUpdate); + String valueBeforeUpdate = serviceDefOptionsPreUpdate.get(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES); + RangerServiceDef dbHiveServiceDef = svcDBStore.getServiceDefByName(SERVICEDBSTORE_SERVICEDEFBYNAME_HIVE_NAME); + + if (dbHiveServiceDef != null) { + boolean isServiceDefUpdated = updateServiceDef(dbHiveServiceDef, embeddedHiveServiceDef); + + if (isServiceDefUpdated) { + xXServiceDefObj = daoMgr.getXXServiceDef().findByName(SERVICEDBSTORE_SERVICEDEFBYNAME_HIVE_NAME); + + if (xXServiceDefObj != null) { + String jsonStrPostUpdate = xXServiceDefObj.getDefOptions(); + Map serviceDefOptionsPostUpdate = jsonUtil.jsonToMap(jsonStrPostUpdate); + String valueAfterUpdate = serviceDefOptionsPostUpdate.get(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES); + + if (!StringUtils.equals(valueBeforeUpdate, valueAfterUpdate)) { + if (StringUtils.isEmpty(valueBeforeUpdate)) { + serviceDefOptionsPostUpdate.remove(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES); + } else { + serviceDefOptionsPostUpdate.put(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES, valueBeforeUpdate); + } + + xXServiceDefObj.setDefOptions(mapToJsonString(serviceDefOptionsPostUpdate)); + + daoMgr.getXXServiceDef().update(xXServiceDefObj); + } + } + } + } + } + } catch (Exception e) { + logger.error("Error while updating {} service-def", SERVICEDBSTORE_SERVICEDEFBYNAME_HIVE_NAME, e); + } + } + + private boolean updateServiceDef(RangerServiceDef serviceDef, RangerServiceDef embeddedHiveServiceDef) throws Exception { + boolean ret = false; + + List embeddedHiveResourceDefs = embeddedHiveServiceDef.getResources(); + List embeddedHiveAccessTypes = embeddedHiveServiceDef.getAccessTypes(); + + if (checkHiveServiceresourcePresent(embeddedHiveResourceDefs)) { + // This is to check if HIVESERVICE def is added to the resource definition, if so update the resource def and accessType def + if (embeddedHiveResourceDefs != null) { + serviceDef.setResources(embeddedHiveResourceDefs); + } + + if (embeddedHiveAccessTypes != null) { + if (!embeddedHiveAccessTypes.toString().equalsIgnoreCase(serviceDef.getAccessTypes().toString())) { + serviceDef.setAccessTypes(embeddedHiveAccessTypes); + } + } + + ret = true; + } + + RangerServiceDefValidator validator = validatorFactory.getServiceDefValidator(svcStore); + + validator.validate(serviceDef, Action.UPDATE); + + svcStore.updateServiceDef(serviceDef); + + return ret; + } + + private boolean checkHiveServiceresourcePresent(List resourceDefs) { + boolean ret = false; + + for (RangerServiceDef.RangerResourceDef resourceDef : resourceDefs) { + if (HIVE_SERVICE_RESOURCE_NAME.equals(resourceDef.getName())) { + ret = true; + break; + } + } + + return ret; + } + + private String mapToJsonString(Map map) { + String ret = null; + + if (map != null) { + ret = jsonUtil.readMapToString(map); + } + + return ret; + } +} diff --git a/security-admin/src/main/java/org/apache/ranger/patch/PatchForHiveServiceDefUpdate_J10017.java b/security-admin/src/main/java/org/apache/ranger/patch/PatchForHiveServiceDefUpdate_J10017.java index 4b1a67867e..fca40b511f 100644 --- a/security-admin/src/main/java/org/apache/ranger/patch/PatchForHiveServiceDefUpdate_J10017.java +++ b/security-admin/src/main/java/org/apache/ranger/patch/PatchForHiveServiceDefUpdate_J10017.java @@ -43,172 +43,185 @@ @Component public class PatchForHiveServiceDefUpdate_J10017 extends BaseLoader { - private static final Logger logger = LoggerFactory.getLogger(PatchForHiveServiceDefUpdate_J10017.class); - public static final String SERVICEDBSTORE_SERVICEDEFBYNAME_HIVE_NAME = "hive"; - public static final String HIVE_GLOBAL_RESOURCE_NAME ="global"; - - @Autowired - RangerDaoManager daoMgr; - - @Autowired - ServiceDBStore svcDBStore; - - @Autowired - JSONUtil jsonUtil; - - @Autowired - RangerPolicyService policyService; - - @Autowired - StringUtil stringUtil; - - @Autowired - XPolicyService xPolService; - - @Autowired - XPermMapService xPermMapService; - - @Autowired - RangerBizUtil bizUtil; - - @Autowired - RangerValidatorFactory validatorFactory; - - @Autowired - ServiceDBStore svcStore; - - public static void main(String[] args) { - logger.info("main()"); - try { - PatchForHiveServiceDefUpdate_J10017 loader = (PatchForHiveServiceDefUpdate_J10017) CLIUtil.getBean(PatchForHiveServiceDefUpdate_J10017.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); - } - } - - @Override - public void init() throws Exception { - // Do Nothing - } - - @Override - public void execLoad() { - logger.info("==> PatchForHiveServiceDefUpdateForResourceSpecificAccesses.execLoad()"); - try { - updateHiveServiceDef(); - } catch (Exception e) { - logger.error("Error whille updateHiveServiceDef()data.", e); - } - logger.info("<== PatchForHiveServiceDefUpdateForResourceSpecificAccesses.execLoad()"); - } - - @Override - public void printStats() { - logger.info("PatchForHiveServiceDefUpdateForResourceSpecificAccesses data "); - } - - private void updateHiveServiceDef(){ - RangerServiceDef embeddedHiveServiceDef = null; - RangerServiceDef dbHiveServiceDef = null; - XXServiceDef xXServiceDefObj = null; - try{ - embeddedHiveServiceDef = EmbeddedServiceDefsUtil.instance().getEmbeddedServiceDef(SERVICEDBSTORE_SERVICEDEFBYNAME_HIVE_NAME); - - if (embeddedHiveServiceDef != null) { - xXServiceDefObj = daoMgr.getXXServiceDef().findByName(SERVICEDBSTORE_SERVICEDEFBYNAME_HIVE_NAME); - if (xXServiceDefObj == null) { - logger.error("Service def for " + SERVICEDBSTORE_SERVICEDEFBYNAME_HIVE_NAME + " is not found!!"); - return; - } - - String jsonStrPreUpdate = xXServiceDefObj.getDefOptions(); - Map serviceDefOptionsPreUpdate = jsonUtil.jsonToMap(jsonStrPreUpdate); - String valueBeforeUpdate = serviceDefOptionsPreUpdate.get(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES); - - dbHiveServiceDef = svcDBStore.getServiceDefByName(SERVICEDBSTORE_SERVICEDEFBYNAME_HIVE_NAME); - - if(dbHiveServiceDef != null) { - boolean isServiceDefUpdated = updateServiceDef(dbHiveServiceDef, embeddedHiveServiceDef); - - if (isServiceDefUpdated) { - xXServiceDefObj = daoMgr.getXXServiceDef().findByName(SERVICEDBSTORE_SERVICEDEFBYNAME_HIVE_NAME); - - if (xXServiceDefObj != null) { - String jsonStrPostUpdate = xXServiceDefObj.getDefOptions(); - Map serviceDefOptionsPostUpdate = jsonUtil.jsonToMap(jsonStrPostUpdate); - String valueAfterUpdate = serviceDefOptionsPostUpdate.get(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES); - - if (!StringUtils.equals(valueBeforeUpdate, valueAfterUpdate)) { - if (StringUtils.isEmpty(valueBeforeUpdate)) { - serviceDefOptionsPostUpdate.remove(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES); - } else { - serviceDefOptionsPostUpdate.put(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES, valueBeforeUpdate); - } - xXServiceDefObj.setDefOptions(mapToJsonString(serviceDefOptionsPostUpdate)); - daoMgr.getXXServiceDef().update(xXServiceDefObj); - } - } - } - } - } - } catch(Exception e) { - logger.error("Error while updating "+SERVICEDBSTORE_SERVICEDEFBYNAME_HIVE_NAME+"service-def", e); - } - } - - private boolean updateServiceDef(RangerServiceDef serviceDef, RangerServiceDef embeddedHiveServiceDef ) throws Exception { - boolean ret = false; - - List embeddedHiveResourceDefs = null; - List embeddedHiveAccessTypes = null; - - embeddedHiveResourceDefs = embeddedHiveServiceDef.getResources(); - embeddedHiveAccessTypes = embeddedHiveServiceDef.getAccessTypes(); - - if (checkHiveGlobalresourcePresent(embeddedHiveResourceDefs)) { - // This is to check if HIVESERVICE def is added to the resource definition, if so update the resource def and accessType def - if (embeddedHiveResourceDefs != null) { - serviceDef.setResources(embeddedHiveResourceDefs); - } - if (embeddedHiveAccessTypes != null) { - if(!embeddedHiveAccessTypes.toString().equalsIgnoreCase(serviceDef.getAccessTypes().toString())) { - serviceDef.setAccessTypes(embeddedHiveAccessTypes); - } - } - ret = true; - } - - RangerServiceDefValidator validator = validatorFactory.getServiceDefValidator(svcStore); - validator.validate(serviceDef, Action.UPDATE); - svcStore.updateServiceDef(serviceDef); - - return ret; - } - - private boolean checkHiveGlobalresourcePresent(List resourceDefs) { - boolean ret = false; - for(RangerServiceDef.RangerResourceDef resourceDef : resourceDefs) { - if (HIVE_GLOBAL_RESOURCE_NAME.equals(resourceDef.getName()) ) { - ret = true ; - break; - } - } - return ret; - } - - private String mapToJsonString(Map map) throws Exception { - String ret = null; - if(map != null) { - ret = jsonUtil.readMapToString(map); - } - return ret; - } -} + private static final Logger logger = LoggerFactory.getLogger(PatchForHiveServiceDefUpdate_J10017.class); + + public static final String SERVICEDBSTORE_SERVICEDEFBYNAME_HIVE_NAME = "hive"; + public static final String HIVE_GLOBAL_RESOURCE_NAME = "global"; + + @Autowired + RangerDaoManager daoMgr; + + @Autowired + ServiceDBStore svcDBStore; + + @Autowired + JSONUtil jsonUtil; + + @Autowired + RangerPolicyService policyService; + + @Autowired + StringUtil stringUtil; + + @Autowired + XPolicyService xPolService; + + @Autowired + XPermMapService xPermMapService; + + @Autowired + RangerBizUtil bizUtil; + + @Autowired + RangerValidatorFactory validatorFactory; + + @Autowired + ServiceDBStore svcStore; + + public static void main(String[] args) { + logger.info("main()"); + + try { + PatchForHiveServiceDefUpdate_J10017 loader = (PatchForHiveServiceDefUpdate_J10017) CLIUtil.getBean(PatchForHiveServiceDefUpdate_J10017.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); + } + } + + @Override + public void init() throws Exception { + // Do Nothing + } + + @Override + public void printStats() { + logger.info("PatchForHiveServiceDefUpdateForResourceSpecificAccesses data "); + } + + @Override + public void execLoad() { + logger.info("==> PatchForHiveServiceDefUpdateForResourceSpecificAccesses.execLoad()"); + + try { + updateHiveServiceDef(); + } catch (Exception e) { + logger.error("Error whille updateHiveServiceDef()data.", e); + } + + logger.info("<== PatchForHiveServiceDefUpdateForResourceSpecificAccesses.execLoad()"); + } + private void updateHiveServiceDef() { + try { + RangerServiceDef embeddedHiveServiceDef = EmbeddedServiceDefsUtil.instance().getEmbeddedServiceDef(SERVICEDBSTORE_SERVICEDEFBYNAME_HIVE_NAME); + + if (embeddedHiveServiceDef != null) { + XXServiceDef xXServiceDefObj = daoMgr.getXXServiceDef().findByName(SERVICEDBSTORE_SERVICEDEFBYNAME_HIVE_NAME); + + if (xXServiceDefObj == null) { + logger.error("Service def for {} is not found!!", SERVICEDBSTORE_SERVICEDEFBYNAME_HIVE_NAME); + + return; + } + + String jsonStrPreUpdate = xXServiceDefObj.getDefOptions(); + Map serviceDefOptionsPreUpdate = jsonUtil.jsonToMap(jsonStrPreUpdate); + String valueBeforeUpdate = serviceDefOptionsPreUpdate.get(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES); + + RangerServiceDef dbHiveServiceDef = svcDBStore.getServiceDefByName(SERVICEDBSTORE_SERVICEDEFBYNAME_HIVE_NAME); + + if (dbHiveServiceDef != null) { + boolean isServiceDefUpdated = updateServiceDef(dbHiveServiceDef, embeddedHiveServiceDef); + + if (isServiceDefUpdated) { + xXServiceDefObj = daoMgr.getXXServiceDef().findByName(SERVICEDBSTORE_SERVICEDEFBYNAME_HIVE_NAME); + + if (xXServiceDefObj != null) { + String jsonStrPostUpdate = xXServiceDefObj.getDefOptions(); + Map serviceDefOptionsPostUpdate = jsonUtil.jsonToMap(jsonStrPostUpdate); + String valueAfterUpdate = serviceDefOptionsPostUpdate.get(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES); + + if (!StringUtils.equals(valueBeforeUpdate, valueAfterUpdate)) { + if (StringUtils.isEmpty(valueBeforeUpdate)) { + serviceDefOptionsPostUpdate.remove(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES); + } else { + serviceDefOptionsPostUpdate.put(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES, valueBeforeUpdate); + } + + xXServiceDefObj.setDefOptions(mapToJsonString(serviceDefOptionsPostUpdate)); + + daoMgr.getXXServiceDef().update(xXServiceDefObj); + } + } + } + } + } + } catch (Exception e) { + logger.error("Error while updating {} service-def", SERVICEDBSTORE_SERVICEDEFBYNAME_HIVE_NAME, e); + } + } + + private boolean updateServiceDef(RangerServiceDef serviceDef, RangerServiceDef embeddedHiveServiceDef) throws Exception { + boolean ret = false; + List embeddedHiveResourceDefs = embeddedHiveServiceDef.getResources(); + List embeddedHiveAccessTypes = embeddedHiveServiceDef.getAccessTypes(); + + if (checkHiveGlobalresourcePresent(embeddedHiveResourceDefs)) { + // This is to check if HIVESERVICE def is added to the resource definition, if so update the resource def and accessType def + if (embeddedHiveResourceDefs != null) { + serviceDef.setResources(embeddedHiveResourceDefs); + } + + if (embeddedHiveAccessTypes != null) { + if (!embeddedHiveAccessTypes.toString().equalsIgnoreCase(serviceDef.getAccessTypes().toString())) { + serviceDef.setAccessTypes(embeddedHiveAccessTypes); + } + } + + ret = true; + } + + RangerServiceDefValidator validator = validatorFactory.getServiceDefValidator(svcStore); + + validator.validate(serviceDef, Action.UPDATE); + + svcStore.updateServiceDef(serviceDef); + + return ret; + } + + private boolean checkHiveGlobalresourcePresent(List resourceDefs) { + boolean ret = false; + + for (RangerServiceDef.RangerResourceDef resourceDef : resourceDefs) { + if (HIVE_GLOBAL_RESOURCE_NAME.equals(resourceDef.getName())) { + ret = true; + break; + } + } + + return ret; + } + + private String mapToJsonString(Map map) { + String ret = null; + + if (map != null) { + ret = jsonUtil.readMapToString(map); + } + + return ret; + } +} diff --git a/security-admin/src/main/java/org/apache/ranger/patch/PatchForHiveServiceDefUpdate_J10027.java b/security-admin/src/main/java/org/apache/ranger/patch/PatchForHiveServiceDefUpdate_J10027.java index 24cf14fa18..0865d53b76 100644 --- a/security-admin/src/main/java/org/apache/ranger/patch/PatchForHiveServiceDefUpdate_J10027.java +++ b/security-admin/src/main/java/org/apache/ranger/patch/PatchForHiveServiceDefUpdate_J10027.java @@ -44,199 +44,227 @@ @Component public class PatchForHiveServiceDefUpdate_J10027 extends BaseLoader { - private static final Logger logger = LoggerFactory.getLogger(PatchForHiveServiceDefUpdate_J10027.class); - public static final String SERVICEDBSTORE_SERVICEDEFBYNAME_HIVE_NAME = "hive"; - public static final String REFRESH_ACCESS_TYPE_NAME = "refresh"; - - @Autowired - RangerDaoManager daoMgr; - - @Autowired - ServiceDBStore svcDBStore; - - @Autowired - JSONUtil jsonUtil; - - @Autowired - RangerPolicyService policyService; - - @Autowired - StringUtil stringUtil; - - @Autowired - XPolicyService xPolService; - - @Autowired - XPermMapService xPermMapService; - - @Autowired - RangerBizUtil bizUtil; - - @Autowired - RangerValidatorFactory validatorFactory; - - @Autowired - ServiceDBStore svcStore; - - public static void main(String[] args) { - logger.info("main()"); - try { - PatchForHiveServiceDefUpdate_J10027 loader = (PatchForHiveServiceDefUpdate_J10027) CLIUtil.getBean(PatchForHiveServiceDefUpdate_J10027.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); - } - } - - @Override - public void printStats() { - logger.info("PatchForHiveServiceDefUpdate data "); - } - - @Override - public void execLoad() { - logger.info("==> PatchForHiveServiceDefUpdate.execLoad()"); - try { - if (!updateHiveServiceDef()) { - logger.error("Failed to apply the patch."); - System.exit(1); - } - } catch (Exception e) { - logger.error("Error while updateHiveServiceDef()data.", e); - System.exit(1); - } - logger.info("<== PatchForHiveServiceDefUpdate.execLoad()"); - } - - @Override - public void init() throws Exception { - // Do Nothing - } - - private boolean updateHiveServiceDef() throws Exception { - RangerServiceDef ret; - RangerServiceDef embeddedHiveServiceDef; - RangerServiceDef dbHiveServiceDef; - List embeddedHiveAccessTypes; - XXServiceDef xXServiceDefObj; - - embeddedHiveServiceDef = EmbeddedServiceDefsUtil.instance().getEmbeddedServiceDef(SERVICEDBSTORE_SERVICEDEFBYNAME_HIVE_NAME); - - if (embeddedHiveServiceDef != null) { - xXServiceDefObj = daoMgr.getXXServiceDef().findByName(SERVICEDBSTORE_SERVICEDEFBYNAME_HIVE_NAME); - Map serviceDefOptionsPreUpdate; - String jsonPreUpdate; - - if (xXServiceDefObj != null) { - jsonPreUpdate = xXServiceDefObj.getDefOptions(); - serviceDefOptionsPreUpdate = jsonStringToMap(jsonPreUpdate); - } else { - logger.error("Hive service-definition does not exist in the Ranger DAO. No patching is needed!!"); - return true; - } - dbHiveServiceDef = svcDBStore.getServiceDefByName(SERVICEDBSTORE_SERVICEDEFBYNAME_HIVE_NAME); - - if (dbHiveServiceDef != null) { - embeddedHiveAccessTypes = embeddedHiveServiceDef.getAccessTypes(); - - if (embeddedHiveAccessTypes != null) { - if (checkNewHiveAccessTypesPresent(embeddedHiveAccessTypes)) { - if (!embeddedHiveAccessTypes.toString().equalsIgnoreCase(dbHiveServiceDef.getAccessTypes().toString())) { - dbHiveServiceDef.setAccessTypes(embeddedHiveAccessTypes); - } - } - } - } else { - logger.error("Hive service-definition does not exist in the db store."); - return false; - } - RangerServiceDefValidator validator = validatorFactory.getServiceDefValidator(svcStore); - validator.validate(dbHiveServiceDef, RangerValidator.Action.UPDATE); - - ret = svcStore.updateServiceDef(dbHiveServiceDef); - if (ret == null) { - throw new RuntimeException("Error while updating " + SERVICEDBSTORE_SERVICEDEFBYNAME_HIVE_NAME + " service-def"); - } - xXServiceDefObj = daoMgr.getXXServiceDef().findByName(SERVICEDBSTORE_SERVICEDEFBYNAME_HIVE_NAME); - if (xXServiceDefObj != null) { - String jsonStrPostUpdate = xXServiceDefObj.getDefOptions(); - Map serviceDefOptionsPostUpdate = jsonStringToMap(jsonStrPostUpdate); - if (serviceDefOptionsPostUpdate != null && serviceDefOptionsPostUpdate.containsKey(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES)) { - if (serviceDefOptionsPreUpdate == null || !serviceDefOptionsPreUpdate.containsKey(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES)) { - String preUpdateValue = serviceDefOptionsPreUpdate == null ? null : serviceDefOptionsPreUpdate.get(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES); - if (preUpdateValue == null) { - serviceDefOptionsPostUpdate.remove(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES); - } else { - serviceDefOptionsPostUpdate.put(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES, preUpdateValue); - } - xXServiceDefObj.setDefOptions(mapToJsonString(serviceDefOptionsPostUpdate)); - daoMgr.getXXServiceDef().update(xXServiceDefObj); - } - } - } else { - logger.error("Hive service-definition does not exist in the Ranger DAO."); - return false; - } - } else { - logger.error("The embedded Hive service-definition does not exist."); - return false; - } - return true; - } - - private static boolean checkNewHiveAccessTypesPresent(List accessTypeDefs) { - boolean ret = false; - for (RangerServiceDef.RangerAccessTypeDef accessTypeDef : accessTypeDefs) { - if (REFRESH_ACCESS_TYPE_NAME.equals(accessTypeDef.getName())) { - ret = true; - break; - } - } - return ret; - } - - private String mapToJsonString(Map map) { - String ret = null; - if (map != null) { - try { - ret = jsonUtil.readMapToString(map); - } catch (Exception ex) { - logger.warn("mapToJsonString() failed to convert map: " + map, ex); - } - } - return ret; - } - - protected Map jsonStringToMap(String jsonStr) { - Map ret = null; - if (!StringUtils.isEmpty(jsonStr)) { - try { - ret = jsonUtil.jsonToMap(jsonStr); - } catch (Exception ex) { - // fallback to earlier format: "name1=value1;name2=value2" - for (String optionString : jsonStr.split(";")) { - if (StringUtils.isEmpty(optionString)) { - continue; - } - String[] nvArr = optionString.split("="); - String name = (nvArr != null && nvArr.length > 0) ? nvArr[0].trim() : null; - String value = (nvArr != null && nvArr.length > 1) ? nvArr[1].trim() : null; - if (StringUtils.isEmpty(name)) { - continue; - } - if (ret == null) { - ret = new HashMap(); - } - ret.put(name, value); - } - } - } - return ret; - } + private static final Logger logger = LoggerFactory.getLogger(PatchForHiveServiceDefUpdate_J10027.class); + + public static final String SERVICEDBSTORE_SERVICEDEFBYNAME_HIVE_NAME = "hive"; + public static final String REFRESH_ACCESS_TYPE_NAME = "refresh"; + + @Autowired + RangerDaoManager daoMgr; + + @Autowired + ServiceDBStore svcDBStore; + + @Autowired + JSONUtil jsonUtil; + + @Autowired + RangerPolicyService policyService; + + @Autowired + StringUtil stringUtil; + + @Autowired + XPolicyService xPolService; + + @Autowired + XPermMapService xPermMapService; + + @Autowired + RangerBizUtil bizUtil; + + @Autowired + RangerValidatorFactory validatorFactory; + + @Autowired + ServiceDBStore svcStore; + + public static void main(String[] args) { + logger.info("main()"); + + try { + PatchForHiveServiceDefUpdate_J10027 loader = (PatchForHiveServiceDefUpdate_J10027) CLIUtil.getBean(PatchForHiveServiceDefUpdate_J10027.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); + } + } + + @Override + public void init() throws Exception { + // Do Nothing + } + + @Override + public void printStats() { + logger.info("PatchForHiveServiceDefUpdate data "); + } + + @Override + public void execLoad() { + logger.info("==> PatchForHiveServiceDefUpdate.execLoad()"); + try { + if (!updateHiveServiceDef()) { + logger.error("Failed to apply the patch."); + + System.exit(1); + } + } catch (Exception e) { + logger.error("Error while updateHiveServiceDef()data.", e); + + System.exit(1); + } + + logger.info("<== PatchForHiveServiceDefUpdate.execLoad()"); + } + + protected Map jsonStringToMap(String jsonStr) { + Map ret = null; + + if (!StringUtils.isEmpty(jsonStr)) { + try { + ret = jsonUtil.jsonToMap(jsonStr); + } catch (Exception ex) { + // fallback to earlier format: "name1=value1;name2=value2" + for (String optionString : jsonStr.split(";")) { + if (StringUtils.isEmpty(optionString)) { + continue; + } + + String[] nvArr = optionString.split("="); + String name = nvArr.length > 0 ? nvArr[0].trim() : null; + String value = nvArr.length > 1 ? nvArr[1].trim() : null; + + if (StringUtils.isEmpty(name)) { + continue; + } + + if (ret == null) { + ret = new HashMap<>(); + } + + ret.put(name, value); + } + } + } + return ret; + } + + private boolean updateHiveServiceDef() throws Exception { + RangerServiceDef embeddedHiveServiceDef = EmbeddedServiceDefsUtil.instance().getEmbeddedServiceDef(SERVICEDBSTORE_SERVICEDEFBYNAME_HIVE_NAME); + + if (embeddedHiveServiceDef != null) { + XXServiceDef xXServiceDefObj = daoMgr.getXXServiceDef().findByName(SERVICEDBSTORE_SERVICEDEFBYNAME_HIVE_NAME); + Map serviceDefOptionsPreUpdate; + String jsonPreUpdate; + + if (xXServiceDefObj != null) { + jsonPreUpdate = xXServiceDefObj.getDefOptions(); + serviceDefOptionsPreUpdate = jsonStringToMap(jsonPreUpdate); + } else { + logger.error("Hive service-definition does not exist in the Ranger DAO. No patching is needed!!"); + + return true; + } + + RangerServiceDef dbHiveServiceDef = svcDBStore.getServiceDefByName(SERVICEDBSTORE_SERVICEDEFBYNAME_HIVE_NAME); + + if (dbHiveServiceDef != null) { + List embeddedHiveAccessTypes = embeddedHiveServiceDef.getAccessTypes(); + + if (embeddedHiveAccessTypes != null) { + if (checkNewHiveAccessTypesPresent(embeddedHiveAccessTypes)) { + if (!embeddedHiveAccessTypes.toString().equalsIgnoreCase(dbHiveServiceDef.getAccessTypes().toString())) { + dbHiveServiceDef.setAccessTypes(embeddedHiveAccessTypes); + } + } + } + } else { + logger.error("Hive service-definition does not exist in the db store."); + + return false; + } + + RangerServiceDefValidator validator = validatorFactory.getServiceDefValidator(svcStore); + + validator.validate(dbHiveServiceDef, RangerValidator.Action.UPDATE); + + RangerServiceDef ret = svcStore.updateServiceDef(dbHiveServiceDef); + + if (ret == null) { + throw new RuntimeException("Error while updating " + SERVICEDBSTORE_SERVICEDEFBYNAME_HIVE_NAME + " service-def"); + } + + xXServiceDefObj = daoMgr.getXXServiceDef().findByName(SERVICEDBSTORE_SERVICEDEFBYNAME_HIVE_NAME); + + if (xXServiceDefObj != null) { + String jsonStrPostUpdate = xXServiceDefObj.getDefOptions(); + Map serviceDefOptionsPostUpdate = jsonStringToMap(jsonStrPostUpdate); + + if (serviceDefOptionsPostUpdate != null && serviceDefOptionsPostUpdate.containsKey(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES)) { + if (serviceDefOptionsPreUpdate == null || !serviceDefOptionsPreUpdate.containsKey(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES)) { + String preUpdateValue = serviceDefOptionsPreUpdate == null ? null : serviceDefOptionsPreUpdate.get(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES); + + if (preUpdateValue == null) { + serviceDefOptionsPostUpdate.remove(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES); + } else { + serviceDefOptionsPostUpdate.put(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES, preUpdateValue); + } + + xXServiceDefObj.setDefOptions(mapToJsonString(serviceDefOptionsPostUpdate)); + + daoMgr.getXXServiceDef().update(xXServiceDefObj); + } + } + } else { + logger.error("Hive service-definition does not exist in the Ranger DAO."); + + return false; + } + } else { + logger.error("The embedded Hive service-definition does not exist."); + + return false; + } + + return true; + } + + private static boolean checkNewHiveAccessTypesPresent(List accessTypeDefs) { + boolean ret = false; + + for (RangerServiceDef.RangerAccessTypeDef accessTypeDef : accessTypeDefs) { + if (REFRESH_ACCESS_TYPE_NAME.equals(accessTypeDef.getName())) { + ret = true; + break; + } + } + + return ret; + } + + private String mapToJsonString(Map map) { + String ret = null; + + if (map != null) { + try { + ret = jsonUtil.readMapToString(map); + } catch (Exception ex) { + logger.warn("mapToJsonString() failed to convert map: {}", map, ex); + } + } + + return ret; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/patch/PatchForHiveServiceDefUpdate_J10030.java b/security-admin/src/main/java/org/apache/ranger/patch/PatchForHiveServiceDefUpdate_J10030.java index 1b9106211a..c7273bb3df 100644 --- a/security-admin/src/main/java/org/apache/ranger/patch/PatchForHiveServiceDefUpdate_J10030.java +++ b/security-admin/src/main/java/org/apache/ranger/patch/PatchForHiveServiceDefUpdate_J10030.java @@ -43,166 +43,179 @@ @Component public class PatchForHiveServiceDefUpdate_J10030 extends BaseLoader { - private static final Logger logger = LoggerFactory.getLogger(PatchForHiveServiceDefUpdate_J10030.class); - public static final String SERVICEDBSTORE_SERVICEDEFBYNAME_HIVE_NAME = "hive"; - public static final String HIVE_URL_MATCHER ="RangerURLResourceMatcher"; - - @Autowired - RangerDaoManager daoMgr; - - @Autowired - ServiceDBStore svcDBStore; - - @Autowired - JSONUtil jsonUtil; - - @Autowired - RangerPolicyService policyService; - - @Autowired - StringUtil stringUtil; - - @Autowired - XPolicyService xPolService; - - @Autowired - XPermMapService xPermMapService; - - @Autowired - RangerBizUtil bizUtil; - - @Autowired - RangerValidatorFactory validatorFactory; - - @Autowired - ServiceDBStore svcStore; - - public static void main(String[] args) { - logger.info("main()"); - try { - PatchForHiveServiceDefUpdate_J10030 loader = (PatchForHiveServiceDefUpdate_J10030) CLIUtil.getBean(PatchForHiveServiceDefUpdate_J10030.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); - } - } - - @Override - public void init() throws Exception { - // Do Nothing - } - - @Override - public void execLoad() { - logger.info("==> PatchForHiveServiceDefUpdateForURLTypeResourceUpdate.execLoad()"); - try { - updateHiveServiceDef(); - } catch (Exception e) { - logger.error("Error whille updateHiveServiceDef()data.", e); - } - logger.info("<== PatchForHiveServiceDefUpdateForURLTypeResourceUpdate.execLoad()"); - } - - @Override - public void printStats() { - logger.info("PatchForHiveServiceDefUpdateForURLTypeResourceUpdate data "); - } - - private void updateHiveServiceDef(){ - RangerServiceDef embeddedHiveServiceDef = null; - RangerServiceDef dbHiveServiceDef = null; - XXServiceDef xXServiceDefObj = null; - try{ - embeddedHiveServiceDef = EmbeddedServiceDefsUtil.instance().getEmbeddedServiceDef(SERVICEDBSTORE_SERVICEDEFBYNAME_HIVE_NAME); - - if (embeddedHiveServiceDef != null) { - xXServiceDefObj = daoMgr.getXXServiceDef().findByName(SERVICEDBSTORE_SERVICEDEFBYNAME_HIVE_NAME); - if (xXServiceDefObj == null) { - logger.error("Service def for " + SERVICEDBSTORE_SERVICEDEFBYNAME_HIVE_NAME + " is not found!!"); - return; - } - - String jsonStrPreUpdate = xXServiceDefObj.getDefOptions(); - Map serviceDefOptionsPreUpdate = jsonUtil.jsonToMap(jsonStrPreUpdate); - String valueBeforeUpdate = serviceDefOptionsPreUpdate.get(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES); - - dbHiveServiceDef = svcDBStore.getServiceDefByName(SERVICEDBSTORE_SERVICEDEFBYNAME_HIVE_NAME); - - if(dbHiveServiceDef != null) { - boolean isServiceDefUpdated = updateServiceDef(dbHiveServiceDef, embeddedHiveServiceDef); - - if (isServiceDefUpdated) { - xXServiceDefObj = daoMgr.getXXServiceDef().findByName(SERVICEDBSTORE_SERVICEDEFBYNAME_HIVE_NAME); - - if (xXServiceDefObj != null) { - String jsonStrPostUpdate = xXServiceDefObj.getDefOptions(); - Map serviceDefOptionsPostUpdate = jsonUtil.jsonToMap(jsonStrPostUpdate); - String valueAfterUpdate = serviceDefOptionsPostUpdate.get(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES); - - if (!StringUtils.equals(valueBeforeUpdate, valueAfterUpdate)) { - if (StringUtils.isEmpty(valueBeforeUpdate)) { - serviceDefOptionsPostUpdate.remove(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES); - } else { - serviceDefOptionsPostUpdate.put(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES, valueBeforeUpdate); - } - xXServiceDefObj.setDefOptions(mapToJsonString(serviceDefOptionsPostUpdate)); - daoMgr.getXXServiceDef().update(xXServiceDefObj); - } - } - } - } - } - } catch(Exception e) { - logger.error("Error while updating "+SERVICEDBSTORE_SERVICEDEFBYNAME_HIVE_NAME+"service-def", e); - } - } - - private boolean updateServiceDef(RangerServiceDef serviceDef, RangerServiceDef embeddedHiveServiceDef ) throws Exception { - boolean ret = false; - - List embeddedHiveResourceDefs = null; - - embeddedHiveResourceDefs = embeddedHiveServiceDef.getResources(); - - if (checkHiveURLResourceMatcherPresent(embeddedHiveResourceDefs)) { - // This is to check if URL resource matcher is added to the resource definition, if so update the resource def - if (embeddedHiveResourceDefs != null) { - serviceDef.setResources(embeddedHiveResourceDefs); - } - ret = true; - } - - RangerServiceDefValidator validator = validatorFactory.getServiceDefValidator(svcStore); - validator.validate(serviceDef, Action.UPDATE); - svcStore.updateServiceDef(serviceDef); - - return ret; - } - - private boolean checkHiveURLResourceMatcherPresent(List resourceDefs) { - boolean ret = false; - for(RangerServiceDef.RangerResourceDef resourceDef : resourceDefs) { - String urlResourceMatcher = resourceDef.getMatcher(); - if (StringUtils.isNotEmpty(urlResourceMatcher) && urlResourceMatcher.endsWith(HIVE_URL_MATCHER) ) { - ret = true ; - break; - } - } - return ret; - } - - private String mapToJsonString(Map map) throws Exception { - String ret = null; - if(map != null) { - ret = jsonUtil.readMapToString(map); - } - return ret; - } -} + private static final Logger logger = LoggerFactory.getLogger(PatchForHiveServiceDefUpdate_J10030.class); + + public static final String SERVICEDBSTORE_SERVICEDEFBYNAME_HIVE_NAME = "hive"; + public static final String HIVE_URL_MATCHER = "RangerURLResourceMatcher"; + + @Autowired + RangerDaoManager daoMgr; + + @Autowired + ServiceDBStore svcDBStore; + + @Autowired + JSONUtil jsonUtil; + + @Autowired + RangerPolicyService policyService; + + @Autowired + StringUtil stringUtil; + + @Autowired + XPolicyService xPolService; + + @Autowired + XPermMapService xPermMapService; + + @Autowired + RangerBizUtil bizUtil; + + @Autowired + RangerValidatorFactory validatorFactory; + + @Autowired + ServiceDBStore svcStore; + + public static void main(String[] args) { + logger.info("main()"); + + try { + PatchForHiveServiceDefUpdate_J10030 loader = (PatchForHiveServiceDefUpdate_J10030) CLIUtil.getBean(PatchForHiveServiceDefUpdate_J10030.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); + } + } + + @Override + public void init() throws Exception { + // Do Nothing + } + + @Override + public void printStats() { + logger.info("PatchForHiveServiceDefUpdateForURLTypeResourceUpdate data "); + } + + @Override + public void execLoad() { + logger.info("==> PatchForHiveServiceDefUpdateForURLTypeResourceUpdate.execLoad()"); + + try { + updateHiveServiceDef(); + } catch (Exception e) { + logger.error("Error whille updateHiveServiceDef()data.", e); + } + + logger.info("<== PatchForHiveServiceDefUpdateForURLTypeResourceUpdate.execLoad()"); + } + + private void updateHiveServiceDef() { + try { + RangerServiceDef embeddedHiveServiceDef = EmbeddedServiceDefsUtil.instance().getEmbeddedServiceDef(SERVICEDBSTORE_SERVICEDEFBYNAME_HIVE_NAME); + if (embeddedHiveServiceDef != null) { + XXServiceDef xXServiceDefObj = daoMgr.getXXServiceDef().findByName(SERVICEDBSTORE_SERVICEDEFBYNAME_HIVE_NAME); + + if (xXServiceDefObj == null) { + logger.error("Service def for {} is not found!!", SERVICEDBSTORE_SERVICEDEFBYNAME_HIVE_NAME); + + return; + } + + String jsonStrPreUpdate = xXServiceDefObj.getDefOptions(); + Map serviceDefOptionsPreUpdate = jsonUtil.jsonToMap(jsonStrPreUpdate); + String valueBeforeUpdate = serviceDefOptionsPreUpdate.get(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES); + + RangerServiceDef dbHiveServiceDef = svcDBStore.getServiceDefByName(SERVICEDBSTORE_SERVICEDEFBYNAME_HIVE_NAME); + + if (dbHiveServiceDef != null) { + boolean isServiceDefUpdated = updateServiceDef(dbHiveServiceDef, embeddedHiveServiceDef); + + if (isServiceDefUpdated) { + xXServiceDefObj = daoMgr.getXXServiceDef().findByName(SERVICEDBSTORE_SERVICEDEFBYNAME_HIVE_NAME); + + if (xXServiceDefObj != null) { + String jsonStrPostUpdate = xXServiceDefObj.getDefOptions(); + Map serviceDefOptionsPostUpdate = jsonUtil.jsonToMap(jsonStrPostUpdate); + String valueAfterUpdate = serviceDefOptionsPostUpdate.get(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES); + + if (!StringUtils.equals(valueBeforeUpdate, valueAfterUpdate)) { + if (StringUtils.isEmpty(valueBeforeUpdate)) { + serviceDefOptionsPostUpdate.remove(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES); + } else { + serviceDefOptionsPostUpdate.put(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES, valueBeforeUpdate); + } + + xXServiceDefObj.setDefOptions(mapToJsonString(serviceDefOptionsPostUpdate)); + + daoMgr.getXXServiceDef().update(xXServiceDefObj); + } + } + } + } + } + } catch (Exception e) { + logger.error("Error while updating {} service-def", SERVICEDBSTORE_SERVICEDEFBYNAME_HIVE_NAME, e); + } + } + + private boolean updateServiceDef(RangerServiceDef serviceDef, RangerServiceDef embeddedHiveServiceDef) throws Exception { + boolean ret = false; + List embeddedHiveResourceDefs = embeddedHiveServiceDef.getResources(); + + if (checkHiveURLResourceMatcherPresent(embeddedHiveResourceDefs)) { + // This is to check if URL resource matcher is added to the resource definition, if so update the resource def + if (embeddedHiveResourceDefs != null) { + serviceDef.setResources(embeddedHiveResourceDefs); + } + + ret = true; + } + + RangerServiceDefValidator validator = validatorFactory.getServiceDefValidator(svcStore); + + validator.validate(serviceDef, Action.UPDATE); + + svcStore.updateServiceDef(serviceDef); + + return ret; + } + + private boolean checkHiveURLResourceMatcherPresent(List resourceDefs) { + boolean ret = false; + + for (RangerServiceDef.RangerResourceDef resourceDef : resourceDefs) { + String urlResourceMatcher = resourceDef.getMatcher(); + + if (StringUtils.isNotEmpty(urlResourceMatcher) && urlResourceMatcher.endsWith(HIVE_URL_MATCHER)) { + ret = true; + break; + } + } + + return ret; + } + + private String mapToJsonString(Map map) { + String ret = null; + + if (map != null) { + ret = jsonUtil.readMapToString(map); + } + return ret; + } +} diff --git a/security-admin/src/main/java/org/apache/ranger/patch/PatchForKafkaServiceDefUpdate_J10015.java b/security-admin/src/main/java/org/apache/ranger/patch/PatchForKafkaServiceDefUpdate_J10015.java index cce09e5379..60d021278b 100644 --- a/security-admin/src/main/java/org/apache/ranger/patch/PatchForKafkaServiceDefUpdate_J10015.java +++ b/security-admin/src/main/java/org/apache/ranger/patch/PatchForKafkaServiceDefUpdate_J10015.java @@ -44,194 +44,215 @@ @Component public class PatchForKafkaServiceDefUpdate_J10015 extends BaseLoader { - private static final Logger logger = LoggerFactory.getLogger(PatchForKafkaServiceDefUpdate_J10015.class); - public static final String SERVICEDBSTORE_SERVICEDEFBYNAME_KAFKA_NAME = "kafka"; - public static final String TRANSACTIONALID_RESOURCE_NAME ="transactionalid"; - - @Autowired - RangerDaoManager daoMgr; - - @Autowired - ServiceDBStore svcDBStore; - - @Autowired - JSONUtil jsonUtil; - - @Autowired - RangerPolicyService policyService; - - @Autowired - StringUtil stringUtil; - - @Autowired - XPolicyService xPolService; - - @Autowired - XPermMapService xPermMapService; - - @Autowired - RangerBizUtil bizUtil; - - @Autowired - RangerValidatorFactory validatorFactory; - - @Autowired - ServiceDBStore svcStore; - - public static void main(String[] args) { - logger.info("main()"); - try { - PatchForKafkaServiceDefUpdate_J10015 loader = (PatchForKafkaServiceDefUpdate_J10015) CLIUtil.getBean(PatchForKafkaServiceDefUpdate_J10015.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); - } - } - - @Override - public void init() throws Exception { - // Do Nothing - } - - @Override - public void execLoad() { - logger.info("==> PatchForKafkaServiceDefUpdate_J10015.execLoad()"); - try { - updateHiveServiceDef(); - } catch (Exception e) { - logger.error("Error while applying PatchForKafkaServiceDefUpdate_J10015...", e); - } - logger.info("<== PatchForKafkaServiceDefUpdate_J10015.execLoad()"); - } - - @Override - public void printStats() { - logger.info("PatchForKafkaServiceDefUpdate_J10015 "); - } - - private void updateHiveServiceDef(){ - RangerServiceDef ret = null; - RangerServiceDef embeddedKafkaServiceDef = null; - RangerServiceDef dbKafkaServiceDef = null; - List embeddedKafkaResourceDefs = null; - List embeddedKafkaAccessTypes = null; - XXServiceDef xXServiceDefObj = null; - try{ - embeddedKafkaServiceDef=EmbeddedServiceDefsUtil.instance().getEmbeddedServiceDef(SERVICEDBSTORE_SERVICEDEFBYNAME_KAFKA_NAME); - if(embeddedKafkaServiceDef!=null){ - - xXServiceDefObj = daoMgr.getXXServiceDef().findByName(SERVICEDBSTORE_SERVICEDEFBYNAME_KAFKA_NAME); - Map serviceDefOptionsPreUpdate=null; - String jsonStrPreUpdate=null; - if(xXServiceDefObj!=null) { - jsonStrPreUpdate=xXServiceDefObj.getDefOptions(); - serviceDefOptionsPreUpdate=jsonStringToMap(jsonStrPreUpdate); - xXServiceDefObj=null; - } - dbKafkaServiceDef=svcDBStore.getServiceDefByName(SERVICEDBSTORE_SERVICEDEFBYNAME_KAFKA_NAME); - - if(dbKafkaServiceDef!=null){ - embeddedKafkaResourceDefs = embeddedKafkaServiceDef.getResources(); - embeddedKafkaAccessTypes = embeddedKafkaServiceDef.getAccessTypes(); - - if (checkNewKafkaresourcePresent(embeddedKafkaResourceDefs)) { - // This is to check if URL def is added to the resource definition, if so update the resource def and accessType def - if (embeddedKafkaResourceDefs != null) { - dbKafkaServiceDef.setResources(embeddedKafkaResourceDefs); - } - if (embeddedKafkaAccessTypes != null) { - if(!embeddedKafkaAccessTypes.toString().equalsIgnoreCase(dbKafkaServiceDef.getAccessTypes().toString())) { - dbKafkaServiceDef.setAccessTypes(embeddedKafkaAccessTypes); - } - } - } - - RangerServiceDefValidator validator = validatorFactory.getServiceDefValidator(svcStore); - validator.validate(dbKafkaServiceDef, Action.UPDATE); - - ret = svcStore.updateServiceDef(dbKafkaServiceDef); - if(ret==null){ - logger.error("Error while updating "+SERVICEDBSTORE_SERVICEDEFBYNAME_KAFKA_NAME+"service-def"); - throw new RuntimeException("Error while updating "+SERVICEDBSTORE_SERVICEDEFBYNAME_KAFKA_NAME+"service-def"); - } - xXServiceDefObj = daoMgr.getXXServiceDef().findByName(SERVICEDBSTORE_SERVICEDEFBYNAME_KAFKA_NAME); - if(xXServiceDefObj!=null) { - String jsonStrPostUpdate=xXServiceDefObj.getDefOptions(); - Map serviceDefOptionsPostUpdate=jsonStringToMap(jsonStrPostUpdate); - if (serviceDefOptionsPostUpdate != null && serviceDefOptionsPostUpdate.containsKey(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES)) { - if(serviceDefOptionsPreUpdate == null || !serviceDefOptionsPreUpdate.containsKey(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES)) { - String preUpdateValue = serviceDefOptionsPreUpdate == null ? null : serviceDefOptionsPreUpdate.get(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES); - if (preUpdateValue == null) { - serviceDefOptionsPostUpdate.remove(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES); - } else { - serviceDefOptionsPostUpdate.put(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES, preUpdateValue); - } - xXServiceDefObj.setDefOptions(mapToJsonString(serviceDefOptionsPostUpdate)); - daoMgr.getXXServiceDef().update(xXServiceDefObj); - } - } - } - } - } - }catch(Exception e) - { - logger.error("Error while updating "+SERVICEDBSTORE_SERVICEDEFBYNAME_KAFKA_NAME+"service-def", e); - } - } - - private boolean checkNewKafkaresourcePresent(List resourceDefs) { - boolean ret = false; - for(RangerServiceDef.RangerResourceDef resourceDef : resourceDefs) { - if (TRANSACTIONALID_RESOURCE_NAME.equals(resourceDef.getName()) ) { - ret = true ; - break; - } - } - return ret; - } - - private String mapToJsonString(Map map) { - String ret = null; - if(map != null) { - try { - ret = jsonUtil.readMapToString(map); - } catch(Exception excp) { - logger.warn("mapToJsonString() failed to convert map: " + map, excp); - } - } - return ret; - } - - protected Map jsonStringToMap(String jsonStr) { - Map ret = null; - if(!StringUtils.isEmpty(jsonStr)) { - try { - ret = jsonUtil.jsonToMap(jsonStr); - } catch(Exception excp) { - // fallback to earlier format: "name1=value1;name2=value2" - for(String optionString : jsonStr.split(";")) { - if(StringUtils.isEmpty(optionString)) { - continue; - } - String[] nvArr = optionString.split("="); - String name = (nvArr != null && nvArr.length > 0) ? nvArr[0].trim() : null; - String value = (nvArr != null && nvArr.length > 1) ? nvArr[1].trim() : null; - if(StringUtils.isEmpty(name)) { - continue; - } - if(ret == null) { - ret = new HashMap(); - } - ret.put(name, value); - } - } - } - return ret; - } -} \ No newline at end of file + private static final Logger logger = LoggerFactory.getLogger(PatchForKafkaServiceDefUpdate_J10015.class); + + public static final String SERVICEDBSTORE_SERVICEDEFBYNAME_KAFKA_NAME = "kafka"; + public static final String TRANSACTIONALID_RESOURCE_NAME = "transactionalid"; + + @Autowired + RangerDaoManager daoMgr; + + @Autowired + ServiceDBStore svcDBStore; + + @Autowired + JSONUtil jsonUtil; + + @Autowired + RangerPolicyService policyService; + + @Autowired + StringUtil stringUtil; + + @Autowired + XPolicyService xPolService; + + @Autowired + XPermMapService xPermMapService; + + @Autowired + RangerBizUtil bizUtil; + + @Autowired + RangerValidatorFactory validatorFactory; + + @Autowired + ServiceDBStore svcStore; + + public static void main(String[] args) { + logger.info("main()"); + + try { + PatchForKafkaServiceDefUpdate_J10015 loader = (PatchForKafkaServiceDefUpdate_J10015) CLIUtil.getBean(PatchForKafkaServiceDefUpdate_J10015.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); + } + } + + @Override + public void init() throws Exception { + // Do Nothing + } + + @Override + public void printStats() { + logger.info("PatchForKafkaServiceDefUpdate_J10015 "); + } + + @Override + public void execLoad() { + logger.info("==> PatchForKafkaServiceDefUpdate_J10015.execLoad()"); + + try { + updateHiveServiceDef(); + } catch (Exception e) { + logger.error("Error while applying PatchForKafkaServiceDefUpdate_J10015...", e); + } + + logger.info("<== PatchForKafkaServiceDefUpdate_J10015.execLoad()"); + } + + protected Map jsonStringToMap(String jsonStr) { + Map ret = null; + + if (!StringUtils.isEmpty(jsonStr)) { + try { + ret = jsonUtil.jsonToMap(jsonStr); + } catch (Exception excp) { + // fallback to earlier format: "name1=value1;name2=value2" + for (String optionString : jsonStr.split(";")) { + if (StringUtils.isEmpty(optionString)) { + continue; + } + + String[] nvArr = optionString.split("="); + String name = nvArr.length > 0 ? nvArr[0].trim() : null; + String value = nvArr.length > 1 ? nvArr[1].trim() : null; + + if (StringUtils.isEmpty(name)) { + continue; + } + + if (ret == null) { + ret = new HashMap<>(); + } + + ret.put(name, value); + } + } + } + return ret; + } + + private void updateHiveServiceDef() { + try { + RangerServiceDef embeddedKafkaServiceDef = EmbeddedServiceDefsUtil.instance().getEmbeddedServiceDef(SERVICEDBSTORE_SERVICEDEFBYNAME_KAFKA_NAME); + + if (embeddedKafkaServiceDef != null) { + XXServiceDef xXServiceDefObj = daoMgr.getXXServiceDef().findByName(SERVICEDBSTORE_SERVICEDEFBYNAME_KAFKA_NAME); + Map serviceDefOptionsPreUpdate = null; + + if (xXServiceDefObj != null) { + String jsonStrPreUpdate = xXServiceDefObj.getDefOptions(); + + serviceDefOptionsPreUpdate = jsonStringToMap(jsonStrPreUpdate); + } + + RangerServiceDef dbKafkaServiceDef = svcDBStore.getServiceDefByName(SERVICEDBSTORE_SERVICEDEFBYNAME_KAFKA_NAME); + + if (dbKafkaServiceDef != null) { + List embeddedKafkaResourceDefs = embeddedKafkaServiceDef.getResources(); + List embeddedKafkaAccessTypes = embeddedKafkaServiceDef.getAccessTypes(); + + if (checkNewKafkaresourcePresent(embeddedKafkaResourceDefs)) { + // This is to check if URL def is added to the resource definition, if so update the resource def and accessType def + if (embeddedKafkaResourceDefs != null) { + dbKafkaServiceDef.setResources(embeddedKafkaResourceDefs); + } + + if (embeddedKafkaAccessTypes != null) { + if (!embeddedKafkaAccessTypes.toString().equalsIgnoreCase(dbKafkaServiceDef.getAccessTypes().toString())) { + dbKafkaServiceDef.setAccessTypes(embeddedKafkaAccessTypes); + } + } + } + + RangerServiceDefValidator validator = validatorFactory.getServiceDefValidator(svcStore); + + validator.validate(dbKafkaServiceDef, Action.UPDATE); + + RangerServiceDef ret = svcStore.updateServiceDef(dbKafkaServiceDef); + + if (ret == null) { + logger.error("Error while updating {} service-def", SERVICEDBSTORE_SERVICEDEFBYNAME_KAFKA_NAME); + + throw new RuntimeException("Error while updating " + SERVICEDBSTORE_SERVICEDEFBYNAME_KAFKA_NAME + "service-def"); + } + + xXServiceDefObj = daoMgr.getXXServiceDef().findByName(SERVICEDBSTORE_SERVICEDEFBYNAME_KAFKA_NAME); + if (xXServiceDefObj != null) { + String jsonStrPostUpdate = xXServiceDefObj.getDefOptions(); + Map serviceDefOptionsPostUpdate = jsonStringToMap(jsonStrPostUpdate); + + if (serviceDefOptionsPostUpdate != null && serviceDefOptionsPostUpdate.containsKey(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES)) { + if (serviceDefOptionsPreUpdate == null || !serviceDefOptionsPreUpdate.containsKey(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES)) { + String preUpdateValue = serviceDefOptionsPreUpdate == null ? null : serviceDefOptionsPreUpdate.get(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES); + + if (preUpdateValue == null) { + serviceDefOptionsPostUpdate.remove(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES); + } else { + serviceDefOptionsPostUpdate.put(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES, preUpdateValue); + } + + xXServiceDefObj.setDefOptions(mapToJsonString(serviceDefOptionsPostUpdate)); + + daoMgr.getXXServiceDef().update(xXServiceDefObj); + } + } + } + } + } + } catch (Exception e) { + logger.error("Error while updating {} service-def", SERVICEDBSTORE_SERVICEDEFBYNAME_KAFKA_NAME, e); + } + } + + private boolean checkNewKafkaresourcePresent(List resourceDefs) { + boolean ret = false; + + for (RangerServiceDef.RangerResourceDef resourceDef : resourceDefs) { + if (TRANSACTIONALID_RESOURCE_NAME.equals(resourceDef.getName())) { + ret = true; + break; + } + } + + return ret; + } + + private String mapToJsonString(Map map) { + String ret = null; + + if (map != null) { + try { + ret = jsonUtil.readMapToString(map); + } catch (Exception excp) { + logger.warn("mapToJsonString() failed to convert map: {}", map, excp); + } + } + + return ret; + } +} diff --git a/security-admin/src/main/java/org/apache/ranger/patch/PatchForKafkaServiceDefUpdate_J10025.java b/security-admin/src/main/java/org/apache/ranger/patch/PatchForKafkaServiceDefUpdate_J10025.java index 62847d725c..4f6bdff1ab 100644 --- a/security-admin/src/main/java/org/apache/ranger/patch/PatchForKafkaServiceDefUpdate_J10025.java +++ b/security-admin/src/main/java/org/apache/ranger/patch/PatchForKafkaServiceDefUpdate_J10025.java @@ -56,8 +56,6 @@ 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 java.util.ArrayList; @@ -69,412 +67,467 @@ @Component public class PatchForKafkaServiceDefUpdate_J10025 extends BaseLoader { - private static final Logger logger = LoggerFactory.getLogger(PatchForKafkaServiceDefUpdate_J10025.class); - private static final List POLICY_NAMES = new ArrayList<>(Arrays.asList("all - cluster", "all - delegationtoken")); - private static final String LOGIN_ID_ADMIN = "admin"; - private static final String KAFKA_RESOURCE_CLUSTER = "cluster"; - private static final String KAFKA_RESOURCE_DELEGATIONTOKEN = "delegationtoken"; - - private static final List DEFAULT_POLICY_USERS = new ArrayList<>(Arrays.asList("kafka","rangerlookup")); - - - public static final String SERVICEDBSTORE_SERVICEDEFBYNAME_KAFKA_NAME = "kafka"; - public static final String CLUSTER_RESOURCE_NAME ="cluster"; - - - @Autowired - RangerDaoManager daoMgr; - - @Autowired - ServiceDBStore svcDBStore; - - @Autowired - JSONUtil jsonUtil; - - @Autowired - RangerPolicyService policyService; - - @Autowired - StringUtil stringUtil; - - @Autowired - GUIDUtil guidUtil; - - @Autowired - XPolicyService xPolService; - - @Autowired - XPermMapService xPermMapService; - - @Autowired - RangerBizUtil bizUtil; - - @Autowired - RangerValidatorFactory validatorFactory; - - @Autowired - ServiceDBStore svcStore; - - @Autowired - XUserMgr xUserMgr; - - @Autowired - @Qualifier(value = "transactionManager") - PlatformTransactionManager txManager; - - public static void main(String[] args) { - logger.info("main()"); - try { - PatchForKafkaServiceDefUpdate_J10025 loader = (PatchForKafkaServiceDefUpdate_J10025) CLIUtil.getBean(PatchForKafkaServiceDefUpdate_J10025.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); - } - } - - @Override - public void init() throws Exception { - // Do Nothing - } - - @Override - public void execLoad() { - logger.info("==> PatchForKafkaServiceDefUpdate_J10025.execLoad()"); - try { - updateKafkaServiceDef(); - } catch (Exception e) { - logger.error("Error while applying PatchForKafkaServiceDefUpdate_J10025...", e); - } - logger.info("<== PatchForKafkaServiceDefUpdate_J10025.execLoad()"); - } - - @Override - public void printStats() { - logger.info("PatchForKafkaServiceDefUpdate_J10025 "); - } - - private void updateKafkaServiceDef(){ - RangerServiceDef ret = null; - RangerServiceDef embeddedKafkaServiceDef = null; - RangerServiceDef dbKafkaServiceDef = null; - List embeddedKafkaResourceDefs = null; - List embeddedKafkaAccessTypes = null; - XXServiceDef xXServiceDefObj = null; - try{ - embeddedKafkaServiceDef=EmbeddedServiceDefsUtil.instance().getEmbeddedServiceDef(SERVICEDBSTORE_SERVICEDEFBYNAME_KAFKA_NAME); - if(embeddedKafkaServiceDef!=null){ - - xXServiceDefObj = daoMgr.getXXServiceDef().findByName(SERVICEDBSTORE_SERVICEDEFBYNAME_KAFKA_NAME); - Map serviceDefOptionsPreUpdate=null; - String jsonStrPreUpdate=null; - if(xXServiceDefObj!=null) { - jsonStrPreUpdate=xXServiceDefObj.getDefOptions(); - serviceDefOptionsPreUpdate=jsonStringToMap(jsonStrPreUpdate); - xXServiceDefObj=null; - } - dbKafkaServiceDef=svcDBStore.getServiceDefByName(SERVICEDBSTORE_SERVICEDEFBYNAME_KAFKA_NAME); - - if(dbKafkaServiceDef!=null){ - embeddedKafkaResourceDefs = embeddedKafkaServiceDef.getResources(); - embeddedKafkaAccessTypes = embeddedKafkaServiceDef.getAccessTypes(); - - if (checkNewKafkaresourcePresent(embeddedKafkaResourceDefs)) { - // This is to check if CLUSTER resource is added to the resource definition, if so update the resource def and accessType def - if (embeddedKafkaResourceDefs != null) { - dbKafkaServiceDef.setResources(embeddedKafkaResourceDefs); - } - if (embeddedKafkaAccessTypes != null) { - if(!embeddedKafkaAccessTypes.toString().equalsIgnoreCase(dbKafkaServiceDef.getAccessTypes().toString())) { - dbKafkaServiceDef.setAccessTypes(embeddedKafkaAccessTypes); - } - } - } - - RangerServiceDefValidator validator = validatorFactory.getServiceDefValidator(svcStore); - validator.validate(dbKafkaServiceDef, Action.UPDATE); - - ret = svcStore.updateServiceDef(dbKafkaServiceDef); - if(ret==null){ - logger.error("Error while updating "+SERVICEDBSTORE_SERVICEDEFBYNAME_KAFKA_NAME+"service-def"); - throw new RuntimeException("Error while updating "+SERVICEDBSTORE_SERVICEDEFBYNAME_KAFKA_NAME+"service-def"); - } - xXServiceDefObj = daoMgr.getXXServiceDef().findByName(SERVICEDBSTORE_SERVICEDEFBYNAME_KAFKA_NAME); - if(xXServiceDefObj!=null) { - String jsonStrPostUpdate=xXServiceDefObj.getDefOptions(); - Map serviceDefOptionsPostUpdate=jsonStringToMap(jsonStrPostUpdate); - if (serviceDefOptionsPostUpdate != null && serviceDefOptionsPostUpdate.containsKey(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES)) { - if(serviceDefOptionsPreUpdate == null || !serviceDefOptionsPreUpdate.containsKey(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES)) { - String preUpdateValue = serviceDefOptionsPreUpdate == null ? null : serviceDefOptionsPreUpdate.get(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES); - if (preUpdateValue == null) { - serviceDefOptionsPostUpdate.remove(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES); - } else { - serviceDefOptionsPostUpdate.put(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES, preUpdateValue); - } - xXServiceDefObj.setDefOptions(mapToJsonString(serviceDefOptionsPostUpdate)); - daoMgr.getXXServiceDef().update(xXServiceDefObj); - } - } - createDefaultPolicyForNewResources(); - } - } - } - }catch(Exception e) - { - logger.error("Error while updating "+SERVICEDBSTORE_SERVICEDEFBYNAME_KAFKA_NAME+"service-def", e); - } - } - - private boolean checkNewKafkaresourcePresent(List resourceDefs) { - boolean ret = false; - for(RangerServiceDef.RangerResourceDef resourceDef : resourceDefs) { - if (CLUSTER_RESOURCE_NAME.equals(resourceDef.getName()) ) { - ret = true ; - break; - } - } - return ret; - } - - private String mapToJsonString(Map map) { - String ret = null; - if(map != null) { - try { - ret = jsonUtil.readMapToString(map); - } catch(Exception excp) { - logger.warn("mapToJsonString() failed to convert map: " + map, excp); - } - } - return ret; - } - - protected Map jsonStringToMap(String jsonStr) { - Map ret = null; - if(!StringUtils.isEmpty(jsonStr)) { - try { - ret = jsonUtil.jsonToMap(jsonStr); - } catch(Exception excp) { - // fallback to earlier format: "name1=value1;name2=value2" - for(String optionString : jsonStr.split(";")) { - if(StringUtils.isEmpty(optionString)) { - continue; - } - String[] nvArr = optionString.split("="); - String name = (nvArr != null && nvArr.length > 0) ? nvArr[0].trim() : null; - String value = (nvArr != null && nvArr.length > 1) ? nvArr[1].trim() : null; - if(StringUtils.isEmpty(name)) { - continue; - } - if(ret == null) { - ret = new HashMap(); - } - ret.put(name, value); - } - } - } - return ret; - } - - private void createDefaultPolicyForNewResources() { - logger.info("==> createDefaultPolicyForNewResources "); - XXPortalUser xxPortalUser = daoMgr.getXXPortalUser().findByLoginId(LOGIN_ID_ADMIN); - Long currentUserId = xxPortalUser.getId(); - - XXServiceDef xXServiceDefObj = daoMgr.getXXServiceDef() - .findByName(EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_KAFKA_NAME); - if (xXServiceDefObj == null) { - logger.debug("ServiceDef not fount with name :" + EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_KAFKA_NAME); - return; - } - - Long xServiceDefId = xXServiceDefObj.getId(); - List xxServices = daoMgr.getXXService().findByServiceDefId(xServiceDefId); - - for (XXService xxService : xxServices) { - int resourceMapOrder = 0; - for (String newResource : POLICY_NAMES) { - XXPolicy xxPolicy = new XXPolicy(); - xxPolicy.setName(newResource); - xxPolicy.setDescription(newResource); - xxPolicy.setService(xxService.getId()); - xxPolicy.setPolicyPriority(RangerPolicy.POLICY_PRIORITY_NORMAL); - xxPolicy.setIsAuditEnabled(Boolean.TRUE); - xxPolicy.setIsEnabled(Boolean.TRUE); - xxPolicy.setPolicyType(RangerPolicy.POLICY_TYPE_ACCESS); - xxPolicy.setGuid(guidUtil.genGUID()); - xxPolicy.setAddedByUserId(currentUserId); - xxPolicy.setUpdatedByUserId(currentUserId); - RangerPolicy rangerPolicy = getRangerPolicy(newResource,xxPortalUser,xxService); - xxPolicy.setPolicyText(JsonUtils.objectToJson(rangerPolicy)); - xxPolicy.setResourceSignature(rangerPolicy.getResourceSignature()); - xxPolicy.setZoneId(1L); - XXPolicy createdPolicy = daoMgr.getXXPolicy().create(xxPolicy); - - XXPolicyItem xxPolicyItem = new XXPolicyItem(); - xxPolicyItem.setIsEnabled(Boolean.TRUE); - xxPolicyItem.setDelegateAdmin(Boolean.TRUE); - xxPolicyItem.setItemType(0); - xxPolicyItem.setOrder(0); - xxPolicyItem.setAddedByUserId(currentUserId); - xxPolicyItem.setUpdatedByUserId(currentUserId); - xxPolicyItem.setPolicyId(createdPolicy.getId()); - XXPolicyItem createdXXPolicyItem = daoMgr.getXXPolicyItem().create(xxPolicyItem); - - List accessTypes = getAccessTypes(); - for (int i = 0; i < accessTypes.size(); i++) { - XXAccessTypeDef xAccTypeDef = daoMgr.getXXAccessTypeDef().findByNameAndServiceId(accessTypes.get(i), - xxPolicy.getService()); - if (xAccTypeDef == null) { - throw new RuntimeException(accessTypes.get(i) + ": is not a valid access-type. policy='" - + xxPolicy.getName() + "' service='" + xxPolicy.getService() + "'"); - } - XXPolicyItemAccess xPolItemAcc = new XXPolicyItemAccess(); - xPolItemAcc.setIsAllowed(Boolean.TRUE); - xPolItemAcc.setType(xAccTypeDef.getId()); - xPolItemAcc.setOrder(i); - xPolItemAcc.setAddedByUserId(currentUserId); - xPolItemAcc.setUpdatedByUserId(currentUserId); - xPolItemAcc.setPolicyitemid(createdXXPolicyItem.getId()); - daoMgr.getXXPolicyItemAccess().create(xPolItemAcc); - } - - for (int i = 0; i < DEFAULT_POLICY_USERS.size(); i++) { - String user = DEFAULT_POLICY_USERS.get(i); - if (StringUtils.isBlank(user)) { - continue; - } - XXUser xxUser = daoMgr.getXXUser().findByUserName(user); - if (null == xxUser) { - TransactionTemplate txTemplate = new TransactionTemplate(txManager); - txTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); - try { - txTemplate.execute(new TransactionCallback() { - @Override - public Object doInTransaction(TransactionStatus status) { - xUserMgr.createServiceConfigUserSynchronously(user); - return null; - } - }); - } catch (Exception exception) { - logger.error("Cannot create ServiceConfigUser(" + user + ")", exception); - } - } - xxUser = daoMgr.getXXUser().findByUserName(user); - if (null == xxUser) { - throw new RuntimeException(user + ": user does not exist. policy='" + xxPolicy.getName() - + "' service='" + xxPolicy.getService() + "' user='" + user + "'"); - } - XXPolicyItemUserPerm xUserPerm = new XXPolicyItemUserPerm(); - xUserPerm.setUserId(xxUser.getId()); - xUserPerm.setPolicyItemId(createdXXPolicyItem.getId()); - xUserPerm.setOrder(i); - xUserPerm.setAddedByUserId(currentUserId); - xUserPerm.setUpdatedByUserId(currentUserId); - daoMgr.getXXPolicyItemUserPerm().create(xUserPerm); - } - - String policyResourceName = KAFKA_RESOURCE_CLUSTER; - if ("all - delegationtoken".equals(newResource)) { - policyResourceName = KAFKA_RESOURCE_DELEGATIONTOKEN; - } - XXResourceDef xResDef = daoMgr.getXXResourceDef().findByNameAndPolicyId(policyResourceName, - createdPolicy.getId()); - if (xResDef == null) { - throw new RuntimeException(policyResourceName + ": is not a valid resource-type. policy='" - + createdPolicy.getName() + "' service='" + createdPolicy.getService() + "'"); - } - - XXPolicyResource xPolRes = new XXPolicyResource(); - - xPolRes.setAddedByUserId(currentUserId); - xPolRes.setUpdatedByUserId(currentUserId); - xPolRes.setIsExcludes(Boolean.FALSE); - xPolRes.setIsRecursive(Boolean.FALSE); - xPolRes.setPolicyId(createdPolicy.getId()); - xPolRes.setResDefId(xResDef.getId()); - xPolRes = daoMgr.getXXPolicyResource().create(xPolRes); - - XXPolicyResourceMap xPolResMap = new XXPolicyResourceMap(); - xPolResMap.setResourceId(xPolRes.getId()); - xPolResMap.setValue("*"); - xPolResMap.setOrder(resourceMapOrder); - xPolResMap.setAddedByUserId(currentUserId); - xPolResMap.setUpdatedByUserId(currentUserId); - daoMgr.getXXPolicyResourceMap().create(xPolResMap); - resourceMapOrder++; - logger.info("Creating policy for service id : " + xxService.getId()); - } - } - logger.info("<== createDefaultPolicyForNewResources "); - } - - - private RangerPolicy getRangerPolicy(String newResource, XXPortalUser xxPortalUser, XXService xxService) { - RangerPolicy policy = new RangerPolicy(); - - List accesses = getPolicyItemAccesses(); - List users = new ArrayList<>(DEFAULT_POLICY_USERS); - List groups = new ArrayList<>(); - List conditions = new ArrayList<>(); - List policyItems = new ArrayList<>(); - RangerPolicy.RangerPolicyItem rangerPolicyItem = new RangerPolicy.RangerPolicyItem(); - rangerPolicyItem.setAccesses(accesses); - rangerPolicyItem.setConditions(conditions); - rangerPolicyItem.setGroups(groups); - rangerPolicyItem.setUsers(users); - rangerPolicyItem.setDelegateAdmin(false); - - policyItems.add(rangerPolicyItem); - - Map policyResource = new HashMap<>(); - RangerPolicy.RangerPolicyResource rangerPolicyResource = new RangerPolicy.RangerPolicyResource(); - rangerPolicyResource.setIsExcludes(false); - rangerPolicyResource.setIsRecursive(false); - rangerPolicyResource.setValue("*"); - String policyResourceName = KAFKA_RESOURCE_CLUSTER; - if ("all - delegationtoken".equals(newResource)) { - policyResourceName = KAFKA_RESOURCE_DELEGATIONTOKEN; - } - policyResource.put(policyResourceName, rangerPolicyResource); - policy.setCreateTime(new Date()); - policy.setDescription(newResource); - policy.setIsEnabled(true); - policy.setName(newResource); - policy.setCreatedBy(xxPortalUser.getLoginId()); - policy.setUpdatedBy(xxPortalUser.getLoginId()); - policy.setUpdateTime(new Date()); - policy.setService(xxService.getName()); - policy.setIsAuditEnabled(true); - policy.setPolicyItems(policyItems); - policy.setResources(policyResource); - policy.setPolicyType(0); - policy.setId(0L); - policy.setGuid(""); - policy.setPolicyLabels(new ArrayList<>()); - policy.setVersion(1L); - RangerPolicyResourceSignature resourceSignature = new RangerPolicyResourceSignature(policy); - policy.setResourceSignature(resourceSignature.getSignature()); - return policy; - } - - private List getAccessTypes() { - List accessTypes = Arrays.asList("create", "delete", "configure", "alter_configs", "describe", "describe_configs", "consume", "publish", "kafka_admin", "idempotent_write"); - return accessTypes; - } - - private ArrayList getPolicyItemAccesses() { - ArrayList rangerPolicyItemAccesses = new ArrayList<>(); - for(String type:getAccessTypes()) { - RangerPolicy.RangerPolicyItemAccess policyItemAccess = new RangerPolicy.RangerPolicyItemAccess(); - policyItemAccess.setType(type); - policyItemAccess.setIsAllowed(true); - rangerPolicyItemAccesses.add(policyItemAccess); - } - return rangerPolicyItemAccesses; - } -} \ No newline at end of file + private static final Logger logger = LoggerFactory.getLogger(PatchForKafkaServiceDefUpdate_J10025.class); + + public static final String SERVICEDBSTORE_SERVICEDEFBYNAME_KAFKA_NAME = "kafka"; + public static final String CLUSTER_RESOURCE_NAME = "cluster"; + + private static final List POLICY_NAMES = new ArrayList<>(Arrays.asList("all - cluster", "all - delegationtoken")); + private static final String LOGIN_ID_ADMIN = "admin"; + private static final String KAFKA_RESOURCE_CLUSTER = "cluster"; + private static final String KAFKA_RESOURCE_DELEGATIONTOKEN = "delegationtoken"; + private static final List DEFAULT_POLICY_USERS = new ArrayList<>(Arrays.asList("kafka", "rangerlookup")); + + @Autowired + RangerDaoManager daoMgr; + + @Autowired + ServiceDBStore svcDBStore; + + @Autowired + JSONUtil jsonUtil; + + @Autowired + RangerPolicyService policyService; + + @Autowired + StringUtil stringUtil; + + @Autowired + GUIDUtil guidUtil; + + @Autowired + XPolicyService xPolService; + + @Autowired + XPermMapService xPermMapService; + + @Autowired + RangerBizUtil bizUtil; + + @Autowired + RangerValidatorFactory validatorFactory; + + @Autowired + ServiceDBStore svcStore; + + @Autowired + XUserMgr xUserMgr; + + @Autowired + @Qualifier(value = "transactionManager") + PlatformTransactionManager txManager; + + public static void main(String[] args) { + logger.info("main()"); + + try { + PatchForKafkaServiceDefUpdate_J10025 loader = (PatchForKafkaServiceDefUpdate_J10025) CLIUtil.getBean(PatchForKafkaServiceDefUpdate_J10025.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); + } + } + + @Override + public void init() throws Exception { + // Do Nothing + } + + @Override + public void printStats() { + logger.info("PatchForKafkaServiceDefUpdate_J10025 "); + } + + @Override + public void execLoad() { + logger.info("==> PatchForKafkaServiceDefUpdate_J10025.execLoad()"); + + try { + updateKafkaServiceDef(); + } catch (Exception e) { + logger.error("Error while applying PatchForKafkaServiceDefUpdate_J10025...", e); + } + + logger.info("<== PatchForKafkaServiceDefUpdate_J10025.execLoad()"); + } + + protected Map jsonStringToMap(String jsonStr) { + Map ret = null; + + if (!StringUtils.isEmpty(jsonStr)) { + try { + ret = jsonUtil.jsonToMap(jsonStr); + } catch (Exception excp) { + // fallback to earlier format: "name1=value1;name2=value2" + for (String optionString : jsonStr.split(";")) { + if (StringUtils.isEmpty(optionString)) { + continue; + } + + String[] nvArr = optionString.split("="); + String name = nvArr.length > 0 ? nvArr[0].trim() : null; + String value = nvArr.length > 1 ? nvArr[1].trim() : null; + + if (StringUtils.isEmpty(name)) { + continue; + } + + if (ret == null) { + ret = new HashMap<>(); + } + + ret.put(name, value); + } + } + } + return ret; + } + + private void updateKafkaServiceDef() { + try { + RangerServiceDef embeddedKafkaServiceDef = EmbeddedServiceDefsUtil.instance().getEmbeddedServiceDef(SERVICEDBSTORE_SERVICEDEFBYNAME_KAFKA_NAME); + + if (embeddedKafkaServiceDef != null) { + XXServiceDef xXServiceDefObj = daoMgr.getXXServiceDef().findByName(SERVICEDBSTORE_SERVICEDEFBYNAME_KAFKA_NAME); + Map serviceDefOptionsPreUpdate = null; + + if (xXServiceDefObj != null) { + String jsonStrPreUpdate = xXServiceDefObj.getDefOptions(); + + serviceDefOptionsPreUpdate = jsonStringToMap(jsonStrPreUpdate); + } + + RangerServiceDef dbKafkaServiceDef = svcDBStore.getServiceDefByName(SERVICEDBSTORE_SERVICEDEFBYNAME_KAFKA_NAME); + + if (dbKafkaServiceDef != null) { + List embeddedKafkaResourceDefs = embeddedKafkaServiceDef.getResources(); + List embeddedKafkaAccessTypes = embeddedKafkaServiceDef.getAccessTypes(); + + if (checkNewKafkaresourcePresent(embeddedKafkaResourceDefs)) { + // This is to check if CLUSTER resource is added to the resource definition, if so update the resource def and accessType def + if (embeddedKafkaResourceDefs != null) { + dbKafkaServiceDef.setResources(embeddedKafkaResourceDefs); + } + + if (embeddedKafkaAccessTypes != null) { + if (!embeddedKafkaAccessTypes.toString().equalsIgnoreCase(dbKafkaServiceDef.getAccessTypes().toString())) { + dbKafkaServiceDef.setAccessTypes(embeddedKafkaAccessTypes); + } + } + } + + RangerServiceDefValidator validator = validatorFactory.getServiceDefValidator(svcStore); + + validator.validate(dbKafkaServiceDef, Action.UPDATE); + + RangerServiceDef ret = svcStore.updateServiceDef(dbKafkaServiceDef); + + if (ret == null) { + logger.error("Error while updating {} service-def", SERVICEDBSTORE_SERVICEDEFBYNAME_KAFKA_NAME); + + throw new RuntimeException("Error while updating " + SERVICEDBSTORE_SERVICEDEFBYNAME_KAFKA_NAME + "service-def"); + } + + xXServiceDefObj = daoMgr.getXXServiceDef().findByName(SERVICEDBSTORE_SERVICEDEFBYNAME_KAFKA_NAME); + + if (xXServiceDefObj != null) { + String jsonStrPostUpdate = xXServiceDefObj.getDefOptions(); + Map serviceDefOptionsPostUpdate = jsonStringToMap(jsonStrPostUpdate); + + if (serviceDefOptionsPostUpdate != null && serviceDefOptionsPostUpdate.containsKey(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES)) { + if (serviceDefOptionsPreUpdate == null || !serviceDefOptionsPreUpdate.containsKey(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES)) { + String preUpdateValue = serviceDefOptionsPreUpdate == null ? null : serviceDefOptionsPreUpdate.get(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES); + + if (preUpdateValue == null) { + serviceDefOptionsPostUpdate.remove(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES); + } else { + serviceDefOptionsPostUpdate.put(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES, preUpdateValue); + } + + xXServiceDefObj.setDefOptions(mapToJsonString(serviceDefOptionsPostUpdate)); + + daoMgr.getXXServiceDef().update(xXServiceDefObj); + } + } + + createDefaultPolicyForNewResources(); + } + } + } + } catch (Exception e) { + logger.error("Error while updating {} service-def", SERVICEDBSTORE_SERVICEDEFBYNAME_KAFKA_NAME, e); + } + } + + private boolean checkNewKafkaresourcePresent(List resourceDefs) { + boolean ret = false; + + for (RangerServiceDef.RangerResourceDef resourceDef : resourceDefs) { + if (CLUSTER_RESOURCE_NAME.equals(resourceDef.getName())) { + ret = true; + break; + } + } + + return ret; + } + + private String mapToJsonString(Map map) { + String ret = null; + + if (map != null) { + try { + ret = jsonUtil.readMapToString(map); + } catch (Exception excp) { + logger.warn("mapToJsonString() failed to convert map: {}", map, excp); + } + } + + return ret; + } + + private void createDefaultPolicyForNewResources() { + logger.info("==> createDefaultPolicyForNewResources "); + + XXPortalUser xxPortalUser = daoMgr.getXXPortalUser().findByLoginId(LOGIN_ID_ADMIN); + Long currentUserId = xxPortalUser.getId(); + XXServiceDef xXServiceDefObj = daoMgr.getXXServiceDef().findByName(EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_KAFKA_NAME); + + if (xXServiceDefObj == null) { + logger.debug("ServiceDef not fount with name :{}", EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_KAFKA_NAME); + + return; + } + + Long xServiceDefId = xXServiceDefObj.getId(); + List xxServices = daoMgr.getXXService().findByServiceDefId(xServiceDefId); + + for (XXService xxService : xxServices) { + int resourceMapOrder = 0; + + for (String newResource : POLICY_NAMES) { + XXPolicy xxPolicy = new XXPolicy(); + + xxPolicy.setName(newResource); + xxPolicy.setDescription(newResource); + xxPolicy.setService(xxService.getId()); + xxPolicy.setPolicyPriority(RangerPolicy.POLICY_PRIORITY_NORMAL); + xxPolicy.setIsAuditEnabled(Boolean.TRUE); + xxPolicy.setIsEnabled(Boolean.TRUE); + xxPolicy.setPolicyType(RangerPolicy.POLICY_TYPE_ACCESS); + xxPolicy.setGuid(guidUtil.genGUID()); + xxPolicy.setAddedByUserId(currentUserId); + xxPolicy.setUpdatedByUserId(currentUserId); + + RangerPolicy rangerPolicy = getRangerPolicy(newResource, xxPortalUser, xxService); + + xxPolicy.setPolicyText(JsonUtils.objectToJson(rangerPolicy)); + xxPolicy.setResourceSignature(rangerPolicy.getResourceSignature()); + xxPolicy.setZoneId(1L); + + XXPolicy createdPolicy = daoMgr.getXXPolicy().create(xxPolicy); + + XXPolicyItem xxPolicyItem = new XXPolicyItem(); + + xxPolicyItem.setIsEnabled(Boolean.TRUE); + xxPolicyItem.setDelegateAdmin(Boolean.TRUE); + xxPolicyItem.setItemType(0); + xxPolicyItem.setOrder(0); + xxPolicyItem.setAddedByUserId(currentUserId); + xxPolicyItem.setUpdatedByUserId(currentUserId); + xxPolicyItem.setPolicyId(createdPolicy.getId()); + + XXPolicyItem createdXXPolicyItem = daoMgr.getXXPolicyItem().create(xxPolicyItem); + List accessTypes = getAccessTypes(); + + for (int i = 0; i < accessTypes.size(); i++) { + XXAccessTypeDef xAccTypeDef = daoMgr.getXXAccessTypeDef().findByNameAndServiceId(accessTypes.get(i), xxPolicy.getService()); + + if (xAccTypeDef == null) { + throw new RuntimeException(accessTypes.get(i) + ": is not a valid access-type. policy='" + xxPolicy.getName() + "' service='" + xxPolicy.getService() + "'"); + } + + XXPolicyItemAccess xPolItemAcc = new XXPolicyItemAccess(); + + xPolItemAcc.setIsAllowed(Boolean.TRUE); + xPolItemAcc.setType(xAccTypeDef.getId()); + xPolItemAcc.setOrder(i); + xPolItemAcc.setAddedByUserId(currentUserId); + xPolItemAcc.setUpdatedByUserId(currentUserId); + xPolItemAcc.setPolicyitemid(createdXXPolicyItem.getId()); + + daoMgr.getXXPolicyItemAccess().create(xPolItemAcc); + } + + for (int i = 0; i < DEFAULT_POLICY_USERS.size(); i++) { + String user = DEFAULT_POLICY_USERS.get(i); + + if (StringUtils.isBlank(user)) { + continue; + } + + XXUser xxUser = daoMgr.getXXUser().findByUserName(user); + + if (null == xxUser) { + TransactionTemplate txTemplate = new TransactionTemplate(txManager); + + txTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + + try { + txTemplate.execute(status -> { + xUserMgr.createServiceConfigUserSynchronously(user); + + return null; + }); + } catch (Exception exception) { + logger.error("Cannot create ServiceConfigUser({})", user, exception); + } + } + + xxUser = daoMgr.getXXUser().findByUserName(user); + + if (null == xxUser) { + throw new RuntimeException(user + ": user does not exist. policy='" + xxPolicy.getName() + "' service='" + xxPolicy.getService() + "' user='" + user + "'"); + } + + XXPolicyItemUserPerm xUserPerm = new XXPolicyItemUserPerm(); + + xUserPerm.setUserId(xxUser.getId()); + xUserPerm.setPolicyItemId(createdXXPolicyItem.getId()); + xUserPerm.setOrder(i); + xUserPerm.setAddedByUserId(currentUserId); + xUserPerm.setUpdatedByUserId(currentUserId); + + daoMgr.getXXPolicyItemUserPerm().create(xUserPerm); + } + + String policyResourceName = KAFKA_RESOURCE_CLUSTER; + + if ("all - delegationtoken".equals(newResource)) { + policyResourceName = KAFKA_RESOURCE_DELEGATIONTOKEN; + } + + XXResourceDef xResDef = daoMgr.getXXResourceDef().findByNameAndPolicyId(policyResourceName, createdPolicy.getId()); + + if (xResDef == null) { + throw new RuntimeException(policyResourceName + ": is not a valid resource-type. policy='" + createdPolicy.getName() + "' service='" + createdPolicy.getService() + "'"); + } + + XXPolicyResource xPolRes = new XXPolicyResource(); + + xPolRes.setAddedByUserId(currentUserId); + xPolRes.setUpdatedByUserId(currentUserId); + xPolRes.setIsExcludes(Boolean.FALSE); + xPolRes.setIsRecursive(Boolean.FALSE); + xPolRes.setPolicyId(createdPolicy.getId()); + xPolRes.setResDefId(xResDef.getId()); + + xPolRes = daoMgr.getXXPolicyResource().create(xPolRes); + + XXPolicyResourceMap xPolResMap = new XXPolicyResourceMap(); + + xPolResMap.setResourceId(xPolRes.getId()); + xPolResMap.setValue("*"); + xPolResMap.setOrder(resourceMapOrder); + xPolResMap.setAddedByUserId(currentUserId); + xPolResMap.setUpdatedByUserId(currentUserId); + + daoMgr.getXXPolicyResourceMap().create(xPolResMap); + + resourceMapOrder++; + + logger.info("Creating policy for service id : {}", xxService.getId()); + } + } + + logger.info("<== createDefaultPolicyForNewResources "); + } + + private RangerPolicy getRangerPolicy(String newResource, XXPortalUser xxPortalUser, XXService xxService) { + List accesses = getPolicyItemAccesses(); + List users = new ArrayList<>(DEFAULT_POLICY_USERS); + List groups = new ArrayList<>(); + List conditions = new ArrayList<>(); + List policyItems = new ArrayList<>(); + RangerPolicy.RangerPolicyItem rangerPolicyItem = new RangerPolicy.RangerPolicyItem(); + + rangerPolicyItem.setAccesses(accesses); + rangerPolicyItem.setConditions(conditions); + rangerPolicyItem.setGroups(groups); + rangerPolicyItem.setUsers(users); + rangerPolicyItem.setDelegateAdmin(false); + + policyItems.add(rangerPolicyItem); + + Map policyResource = new HashMap<>(); + RangerPolicy.RangerPolicyResource rangerPolicyResource = new RangerPolicy.RangerPolicyResource(); + + rangerPolicyResource.setIsExcludes(false); + rangerPolicyResource.setIsRecursive(false); + rangerPolicyResource.setValue("*"); + + String policyResourceName = KAFKA_RESOURCE_CLUSTER; + + if ("all - delegationtoken".equals(newResource)) { + policyResourceName = KAFKA_RESOURCE_DELEGATIONTOKEN; + } + + policyResource.put(policyResourceName, rangerPolicyResource); + + RangerPolicy policy = new RangerPolicy(); + + policy.setCreateTime(new Date()); + policy.setDescription(newResource); + policy.setIsEnabled(true); + policy.setName(newResource); + policy.setCreatedBy(xxPortalUser.getLoginId()); + policy.setUpdatedBy(xxPortalUser.getLoginId()); + policy.setUpdateTime(new Date()); + policy.setService(xxService.getName()); + policy.setIsAuditEnabled(true); + policy.setPolicyItems(policyItems); + policy.setResources(policyResource); + policy.setPolicyType(0); + policy.setId(0L); + policy.setGuid(""); + policy.setPolicyLabels(new ArrayList<>()); + policy.setVersion(1L); + + RangerPolicyResourceSignature resourceSignature = new RangerPolicyResourceSignature(policy); + + policy.setResourceSignature(resourceSignature.getSignature()); + + return policy; + } + + private List getAccessTypes() { + return Arrays.asList("create", "delete", "configure", "alter_configs", "describe", "describe_configs", "consume", "publish", "kafka_admin", "idempotent_write"); + } + + private ArrayList getPolicyItemAccesses() { + ArrayList rangerPolicyItemAccesses = new ArrayList<>(); + + for (String type : getAccessTypes()) { + RangerPolicy.RangerPolicyItemAccess policyItemAccess = new RangerPolicy.RangerPolicyItemAccess(); + + policyItemAccess.setType(type); + policyItemAccess.setIsAllowed(true); + + rangerPolicyItemAccesses.add(policyItemAccess); + } + + return rangerPolicyItemAccesses; + } +} diff --git a/security-admin/src/main/java/org/apache/ranger/patch/PatchForKafkaServiceDefUpdate_J10033.java b/security-admin/src/main/java/org/apache/ranger/patch/PatchForKafkaServiceDefUpdate_J10033.java index e78c666db0..c6645e83ca 100644 --- a/security-admin/src/main/java/org/apache/ranger/patch/PatchForKafkaServiceDefUpdate_J10033.java +++ b/security-admin/src/main/java/org/apache/ranger/patch/PatchForKafkaServiceDefUpdate_J10033.java @@ -28,7 +28,20 @@ import org.apache.ranger.common.RangerValidatorFactory; import org.apache.ranger.common.StringUtil; import org.apache.ranger.db.RangerDaoManager; -import org.apache.ranger.entity.*; +import org.apache.ranger.entity.XXAccessTypeDef; +import org.apache.ranger.entity.XXGroup; +import org.apache.ranger.entity.XXPolicy; +import org.apache.ranger.entity.XXPolicyItem; +import org.apache.ranger.entity.XXPolicyItemAccess; +import org.apache.ranger.entity.XXPolicyItemGroupPerm; +import org.apache.ranger.entity.XXPolicyItemUserPerm; +import org.apache.ranger.entity.XXPolicyResource; +import org.apache.ranger.entity.XXPolicyResourceMap; +import org.apache.ranger.entity.XXPortalUser; +import org.apache.ranger.entity.XXResourceDef; +import org.apache.ranger.entity.XXService; +import org.apache.ranger.entity.XXServiceDef; +import org.apache.ranger.entity.XXUser; import org.apache.ranger.plugin.model.RangerPolicy; import org.apache.ranger.plugin.model.RangerPolicyResourceSignature; import org.apache.ranger.plugin.model.RangerServiceDef; @@ -46,12 +59,11 @@ 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 java.util.ArrayList; import java.util.Arrays; +import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.List; @@ -59,458 +71,502 @@ @Component public class PatchForKafkaServiceDefUpdate_J10033 extends BaseLoader { - private static final Logger logger = LoggerFactory.getLogger(PatchForKafkaServiceDefUpdate_J10033.class); - private static final String POLICY_NAME = "all - consumergroup"; - private static final String LOGIN_ID_ADMIN = "admin"; - - private static final List DEFAULT_POLICY_USERS = new ArrayList<>(Arrays.asList("kafka","rangerlookup")); - private static final List DEFAULT_POLICY_GROUP = new ArrayList<>(Arrays.asList("public")); - - public static final String SERVICEDBSTORE_SERVICEDEFBYNAME_KAFKA_NAME = "kafka"; - public static final String CONSUMERGROUP_RESOURCE_NAME = "consumergroup"; - - - @Autowired - RangerDaoManager daoMgr; - - @Autowired - ServiceDBStore svcDBStore; - - @Autowired - JSONUtil jsonUtil; - - @Autowired - RangerPolicyService policyService; - - @Autowired - StringUtil stringUtil; - - @Autowired - GUIDUtil guidUtil; - - @Autowired - XPolicyService xPolService; - - @Autowired - XPermMapService xPermMapService; - - @Autowired - RangerBizUtil bizUtil; - - @Autowired - RangerValidatorFactory validatorFactory; - - @Autowired - ServiceDBStore svcStore; - - @Autowired - XUserMgr xUserMgr; - - @Autowired - @Qualifier(value = "transactionManager") - PlatformTransactionManager txManager; - - public static void main(String[] args) { - logger.info("main()"); - try { - PatchForKafkaServiceDefUpdate_J10033 loader = (PatchForKafkaServiceDefUpdate_J10033) CLIUtil.getBean(PatchForKafkaServiceDefUpdate_J10033.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); - } - } - - @Override - public void init() throws Exception { - // Do Nothing - } - - @Override - public void execLoad() { - logger.info("==> PatchForKafkaServiceDefUpdate_J10033.execLoad()"); - try { - updateKafkaServiceDef(); - } catch (Exception e) { - logger.error("Error while applying PatchForKafkaServiceDefUpdate_J10033...", e); - } - logger.info("<== PatchForKafkaServiceDefUpdate_J10033.execLoad()"); - } - - @Override - public void printStats() { - logger.info("PatchForKafkaServiceDefUpdate_J10033 "); - } - - private void updateKafkaServiceDef(){ - RangerServiceDef ret = null; - RangerServiceDef embeddedKafkaServiceDef = null; - RangerServiceDef dbKafkaServiceDef = null; - List embeddedKafkaResourceDefs = null; - List embeddedKafkaAccessTypes = null; - XXServiceDef xXServiceDefObj = null; - try{ - embeddedKafkaServiceDef=EmbeddedServiceDefsUtil.instance().getEmbeddedServiceDef(SERVICEDBSTORE_SERVICEDEFBYNAME_KAFKA_NAME); - if(embeddedKafkaServiceDef!=null){ - - xXServiceDefObj = daoMgr.getXXServiceDef().findByName(SERVICEDBSTORE_SERVICEDEFBYNAME_KAFKA_NAME); - Map serviceDefOptionsPreUpdate=null; - String jsonStrPreUpdate=null; - if(xXServiceDefObj!=null) { - jsonStrPreUpdate=xXServiceDefObj.getDefOptions(); - serviceDefOptionsPreUpdate=jsonStringToMap(jsonStrPreUpdate); - xXServiceDefObj=null; - } - dbKafkaServiceDef=svcDBStore.getServiceDefByName(SERVICEDBSTORE_SERVICEDEFBYNAME_KAFKA_NAME); - - if(dbKafkaServiceDef!=null){ - embeddedKafkaResourceDefs = embeddedKafkaServiceDef.getResources(); - embeddedKafkaAccessTypes = embeddedKafkaServiceDef.getAccessTypes(); - - if (checkNewKafkaresourcePresent(embeddedKafkaResourceDefs)) { - // This is to check if CONSUMERGROUP resource is added to the resource definition, if so update the resource def and accessType def - if (embeddedKafkaResourceDefs != null) { - dbKafkaServiceDef.setResources(embeddedKafkaResourceDefs); - } - if (embeddedKafkaAccessTypes != null) { - if(!embeddedKafkaAccessTypes.toString().equalsIgnoreCase(dbKafkaServiceDef.getAccessTypes().toString())) { - dbKafkaServiceDef.setAccessTypes(embeddedKafkaAccessTypes); - } - } - } - - RangerServiceDefValidator validator = validatorFactory.getServiceDefValidator(svcStore); - validator.validate(dbKafkaServiceDef, Action.UPDATE); - - ret = svcStore.updateServiceDef(dbKafkaServiceDef); - if(ret==null){ - logger.error("Error while updating "+SERVICEDBSTORE_SERVICEDEFBYNAME_KAFKA_NAME+"service-def"); - throw new RuntimeException("Error while updating "+SERVICEDBSTORE_SERVICEDEFBYNAME_KAFKA_NAME+"service-def"); - } - xXServiceDefObj = daoMgr.getXXServiceDef().findByName(SERVICEDBSTORE_SERVICEDEFBYNAME_KAFKA_NAME); - if(xXServiceDefObj!=null) { - String jsonStrPostUpdate=xXServiceDefObj.getDefOptions(); - Map serviceDefOptionsPostUpdate=jsonStringToMap(jsonStrPostUpdate); - if (serviceDefOptionsPostUpdate != null && serviceDefOptionsPostUpdate.containsKey(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES)) { - if(serviceDefOptionsPreUpdate == null || !serviceDefOptionsPreUpdate.containsKey(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES)) { - String preUpdateValue = serviceDefOptionsPreUpdate == null ? null : serviceDefOptionsPreUpdate.get(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES); - if (preUpdateValue == null) { - serviceDefOptionsPostUpdate.remove(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES); - } else { - serviceDefOptionsPostUpdate.put(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES, preUpdateValue); - } - xXServiceDefObj.setDefOptions(mapToJsonString(serviceDefOptionsPostUpdate)); - daoMgr.getXXServiceDef().update(xXServiceDefObj); - } - } - createDefaultPolicyForNewResources(); - } - } - } - }catch(Exception e) - { - logger.error("Error while updating "+SERVICEDBSTORE_SERVICEDEFBYNAME_KAFKA_NAME+"service-def", e); - } - } - - private boolean checkNewKafkaresourcePresent(List resourceDefs) { - boolean ret = false; - for(RangerServiceDef.RangerResourceDef resourceDef : resourceDefs) { - if (CONSUMERGROUP_RESOURCE_NAME.equals(resourceDef.getName()) ) { - ret = true ; - break; - } - } - return ret; - } - - private String mapToJsonString(Map map) { - String ret = null; - if(map != null) { - try { - ret = jsonUtil.readMapToString(map); - } catch(Exception excp) { - logger.warn("mapToJsonString() failed to convert map: " + map, excp); - } - } - return ret; - } - - protected Map jsonStringToMap(String jsonStr) { - Map ret = null; - if(!StringUtils.isEmpty(jsonStr)) { - try { - ret = jsonUtil.jsonToMap(jsonStr); - } catch(Exception excp) { - // fallback to earlier format: "name1=value1;name2=value2" - for(String optionString : jsonStr.split(";")) { - if(StringUtils.isEmpty(optionString)) { - continue; - } - String[] nvArr = optionString.split("="); - String name = (nvArr != null && nvArr.length > 0) ? nvArr[0].trim() : null; - String value = (nvArr != null && nvArr.length > 1) ? nvArr[1].trim() : null; - if(StringUtils.isEmpty(name)) { - continue; - } - if(ret == null) { - ret = new HashMap(); - } - ret.put(name, value); - } - } - } - return ret; - } - - private void createDefaultPolicyForNewResources() { - logger.info("==> createDefaultPolicyForNewResources "); - XXPortalUser xxPortalUser = daoMgr.getXXPortalUser().findByLoginId(LOGIN_ID_ADMIN); - Long currentUserId = xxPortalUser.getId(); - - XXServiceDef xXServiceDefObj = daoMgr.getXXServiceDef() - .findByName(EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_KAFKA_NAME); - if (xXServiceDefObj == null) { - logger.debug("ServiceDef not fount with name :" + EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_KAFKA_NAME); - return; - } - - Long xServiceDefId = xXServiceDefObj.getId(); - List xxServices = daoMgr.getXXService().findByServiceDefId(xServiceDefId); - - for (XXService xxService : xxServices) { - int resourceMapOrder = 0; - XXPolicy xxPolicy = new XXPolicy(); - xxPolicy.setName(POLICY_NAME); - xxPolicy.setDescription(POLICY_NAME); - xxPolicy.setService(xxService.getId()); - xxPolicy.setPolicyPriority(RangerPolicy.POLICY_PRIORITY_NORMAL); - xxPolicy.setIsAuditEnabled(Boolean.TRUE); - xxPolicy.setIsEnabled(Boolean.TRUE); - xxPolicy.setPolicyType(RangerPolicy.POLICY_TYPE_ACCESS); - xxPolicy.setGuid(guidUtil.genGUID()); - xxPolicy.setAddedByUserId(currentUserId); - xxPolicy.setUpdatedByUserId(currentUserId); - RangerPolicy rangerPolicy = getRangerPolicy(POLICY_NAME,xxPortalUser,xxService); - xxPolicy.setPolicyText(JsonUtils.objectToJson(rangerPolicy)); - xxPolicy.setResourceSignature(rangerPolicy.getResourceSignature()); - xxPolicy.setZoneId(1L); - boolean policyExist = false; - try { - List rangerpolicies = svcDBStore.getPoliciesByResourceSignature(xxService.getName(), - rangerPolicy.getResourceSignature(), true); - if (CollectionUtils.isNotEmpty(rangerpolicies)) { - for (RangerPolicy rPolicy : rangerpolicies) { - if (rangerPolicy != null) { - if (logger.isDebugEnabled()) { - logger.debug("print Policy: " + rPolicy); - logger.debug("policy found with resource " + rPolicy.getResources() - + " and ResourceSignature " + rPolicy.getResourceSignature() - + " service name : " + rPolicy.getService()); - } - - if (rPolicy.getResourceSignature().equalsIgnoreCase(rangerPolicy.getResourceSignature())) { - policyExist = true; - } - - } - } - } - } catch (Exception ex) { - logger.error(" Error while getting policy using Resource Signature, Servie Name and policy enabled flag" + ex); - } - - if(!policyExist) { - XXPolicy createdPolicy = daoMgr.getXXPolicy().create(xxPolicy); - - XXPolicyItem xxPolicyItem = new XXPolicyItem(); - xxPolicyItem.setIsEnabled(Boolean.TRUE); - xxPolicyItem.setDelegateAdmin(Boolean.TRUE); - xxPolicyItem.setItemType(0); - xxPolicyItem.setOrder(0); - xxPolicyItem.setAddedByUserId(currentUserId); - xxPolicyItem.setUpdatedByUserId(currentUserId); - xxPolicyItem.setPolicyId(createdPolicy.getId()); - XXPolicyItem createdXXPolicyItem = daoMgr.getXXPolicyItem().create(xxPolicyItem); - - List accessTypes = getAccessTypes(); - for (int i = 0; i < accessTypes.size(); i++) { - XXAccessTypeDef xAccTypeDef = daoMgr.getXXAccessTypeDef().findByNameAndServiceId(accessTypes.get(i), - xxPolicy.getService()); - if (xAccTypeDef == null) { - throw new RuntimeException(accessTypes.get(i) + ": is not a valid access-type. policy='" - + xxPolicy.getName() + "' service='" + xxPolicy.getService() + "'"); - } - XXPolicyItemAccess xPolItemAcc = new XXPolicyItemAccess(); - xPolItemAcc.setIsAllowed(Boolean.TRUE); - xPolItemAcc.setType(xAccTypeDef.getId()); - xPolItemAcc.setOrder(i); - xPolItemAcc.setAddedByUserId(currentUserId); - xPolItemAcc.setUpdatedByUserId(currentUserId); - xPolItemAcc.setPolicyitemid(createdXXPolicyItem.getId()); - daoMgr.getXXPolicyItemAccess().create(xPolItemAcc); - } - - for (int i = 0; i < DEFAULT_POLICY_USERS.size(); i++) { - String user = DEFAULT_POLICY_USERS.get(i); - if (StringUtils.isBlank(user)) { - continue; - } - XXUser xxUser = daoMgr.getXXUser().findByUserName(user); - Long userId = null; - if (xxUser == null) { - if (null == xxUser) { - logger.info(user +" user is not found, adding user: "+user); - TransactionTemplate txTemplate = new TransactionTemplate(txManager); - txTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); - try { - txTemplate.execute(new TransactionCallback() { - @Override - public Object doInTransaction(TransactionStatus status) { - xUserMgr.createServiceConfigUserSynchronously(user); - return null; - } - }); - } catch(Exception exception) { - logger.error("Cannot create ServiceConfigUser(" + user + ")", exception); - } - } - - xxUser = daoMgr.getXXUser().findByUserName(user); - if (xxUser == null) { - throw new RuntimeException(user + ": user does not exist. policy='" + xxPolicy.getName() - + "' service='" + xxPolicy.getService() + "' user='" + user + "'"); - } - } - userId = xxUser.getId(); - - XXPolicyItemUserPerm xUserPerm = new XXPolicyItemUserPerm(); - xUserPerm.setUserId(userId); - xUserPerm.setPolicyItemId(createdXXPolicyItem.getId()); - xUserPerm.setOrder(i); - xUserPerm.setAddedByUserId(currentUserId); - xUserPerm.setUpdatedByUserId(currentUserId); - daoMgr.getXXPolicyItemUserPerm().create(xUserPerm); - } - - for (int i = 0; i < DEFAULT_POLICY_GROUP.size(); i++) { - String group = DEFAULT_POLICY_GROUP.get(i); - if (StringUtils.isBlank(group)) { - continue; - } - XXGroup xxGroup = daoMgr.getXXGroup().findByGroupName(group); - if (xxGroup == null) { - throw new RuntimeException(group + ": group does not exist. policy='" + xxPolicy.getName() - + "' service='" + xxPolicy.getService() + "' group='" + group + "'"); - } - XXPolicyItemGroupPerm xGroupPerm = new XXPolicyItemGroupPerm(); - xGroupPerm.setGroupId(xxGroup.getId()); - xGroupPerm.setPolicyItemId(createdXXPolicyItem.getId()); - xGroupPerm.setOrder(i); - xGroupPerm.setAddedByUserId(currentUserId); - xGroupPerm.setUpdatedByUserId(currentUserId); - daoMgr.getXXPolicyItemGroupPerm().create(xGroupPerm); - } - - - String policyResourceName = CONSUMERGROUP_RESOURCE_NAME; - - XXResourceDef xResDef = daoMgr.getXXResourceDef().findByNameAndPolicyId(policyResourceName, - createdPolicy.getId()); - if (xResDef == null) { - throw new RuntimeException(policyResourceName + ": is not a valid resource-type. policy='" - + createdPolicy.getName() + "' service='" + createdPolicy.getService() + "'"); - } - - XXPolicyResource xPolRes = new XXPolicyResource(); - - xPolRes.setAddedByUserId(currentUserId); - xPolRes.setUpdatedByUserId(currentUserId); - xPolRes.setIsExcludes(Boolean.FALSE); - xPolRes.setIsRecursive(Boolean.FALSE); - xPolRes.setPolicyId(createdPolicy.getId()); - xPolRes.setResDefId(xResDef.getId()); - xPolRes = daoMgr.getXXPolicyResource().create(xPolRes); - - XXPolicyResourceMap xPolResMap = new XXPolicyResourceMap(); - xPolResMap.setResourceId(xPolRes.getId()); - xPolResMap.setValue("*"); - xPolResMap.setOrder(resourceMapOrder); - xPolResMap.setAddedByUserId(currentUserId); - xPolResMap.setUpdatedByUserId(currentUserId); - daoMgr.getXXPolicyResourceMap().create(xPolResMap); - resourceMapOrder++; - logger.info("Creating policy for service id : " + xxService.getId()); - } - logger.info("<== createDefaultPolicyForNewResources "); - } - - } - - - private RangerPolicy getRangerPolicy(String newResource, XXPortalUser xxPortalUser, XXService xxService) { - RangerPolicy policy = new RangerPolicy(); - - List accesses = getPolicyItemAccesses(); - List users = new ArrayList<>(DEFAULT_POLICY_USERS); - List groups = new ArrayList<>(DEFAULT_POLICY_GROUP); - List conditions = new ArrayList<>(); - List policyItems = new ArrayList<>(); - RangerPolicy.RangerPolicyItem rangerPolicyItem = new RangerPolicy.RangerPolicyItem(); - rangerPolicyItem.setAccesses(accesses); - rangerPolicyItem.setConditions(conditions); - rangerPolicyItem.setGroups(groups); - rangerPolicyItem.setUsers(users); - rangerPolicyItem.setDelegateAdmin(false); - - policyItems.add(rangerPolicyItem); - - Map policyResource = new HashMap<>(); - RangerPolicy.RangerPolicyResource rangerPolicyResource = new RangerPolicy.RangerPolicyResource(); - rangerPolicyResource.setIsExcludes(false); - rangerPolicyResource.setIsRecursive(false); - rangerPolicyResource.setValue("*"); - String policyResourceName = CONSUMERGROUP_RESOURCE_NAME; - policyResource.put(policyResourceName, rangerPolicyResource); - policy.setCreateTime(new Date()); - policy.setDescription(newResource); - policy.setIsEnabled(true); - policy.setName(newResource); - policy.setCreatedBy(xxPortalUser.getLoginId()); - policy.setUpdatedBy(xxPortalUser.getLoginId()); - policy.setUpdateTime(new Date()); - policy.setService(xxService.getName()); - policy.setIsAuditEnabled(true); - policy.setPolicyItems(policyItems); - policy.setResources(policyResource); - policy.setPolicyType(0); - policy.setId(0L); - policy.setGuid(""); - policy.setPolicyLabels(new ArrayList<>()); - policy.setVersion(1L); - RangerPolicyResourceSignature resourceSignature = new RangerPolicyResourceSignature(policy); - policy.setResourceSignature(resourceSignature.getSignature()); - return policy; - } - - private List getAccessTypes() { - List accessTypes = Arrays.asList("consume", "describe", "delete"); - return accessTypes; - } - - private ArrayList getPolicyItemAccesses() { - ArrayList rangerPolicyItemAccesses = new ArrayList<>(); - for(String type:getAccessTypes()) { - RangerPolicy.RangerPolicyItemAccess policyItemAccess = new RangerPolicy.RangerPolicyItemAccess(); - policyItemAccess.setType(type); - policyItemAccess.setIsAllowed(true); - rangerPolicyItemAccesses.add(policyItemAccess); - } - return rangerPolicyItemAccesses; - } + private static final Logger logger = LoggerFactory.getLogger(PatchForKafkaServiceDefUpdate_J10033.class); + + public static final String SERVICEDBSTORE_SERVICEDEFBYNAME_KAFKA_NAME = "kafka"; + public static final String CONSUMERGROUP_RESOURCE_NAME = "consumergroup"; + + private static final String POLICY_NAME = "all - consumergroup"; + private static final String LOGIN_ID_ADMIN = "admin"; + private static final List DEFAULT_POLICY_USERS = new ArrayList<>(Arrays.asList("kafka", "rangerlookup")); + private static final List DEFAULT_POLICY_GROUP = new ArrayList<>(Collections.singletonList("public")); + + @Autowired + RangerDaoManager daoMgr; + + @Autowired + ServiceDBStore svcDBStore; + + @Autowired + JSONUtil jsonUtil; + + @Autowired + RangerPolicyService policyService; + + @Autowired + StringUtil stringUtil; + + @Autowired + GUIDUtil guidUtil; + + @Autowired + XPolicyService xPolService; + + @Autowired + XPermMapService xPermMapService; + + @Autowired + RangerBizUtil bizUtil; + + @Autowired + RangerValidatorFactory validatorFactory; + + @Autowired + ServiceDBStore svcStore; + + @Autowired + XUserMgr xUserMgr; + + @Autowired + @Qualifier(value = "transactionManager") + PlatformTransactionManager txManager; + + public static void main(String[] args) { + logger.info("main()"); + + try { + PatchForKafkaServiceDefUpdate_J10033 loader = (PatchForKafkaServiceDefUpdate_J10033) CLIUtil.getBean(PatchForKafkaServiceDefUpdate_J10033.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); + } + } + + @Override + public void init() throws Exception { + // Do Nothing + } + + @Override + public void printStats() { + logger.info("PatchForKafkaServiceDefUpdate_J10033 "); + } + + @Override + public void execLoad() { + logger.info("==> PatchForKafkaServiceDefUpdate_J10033.execLoad()"); + + try { + updateKafkaServiceDef(); + } catch (Exception e) { + logger.error("Error while applying PatchForKafkaServiceDefUpdate_J10033...", e); + } + + logger.info("<== PatchForKafkaServiceDefUpdate_J10033.execLoad()"); + } + + protected Map jsonStringToMap(String jsonStr) { + Map ret = null; + + if (!StringUtils.isEmpty(jsonStr)) { + try { + ret = jsonUtil.jsonToMap(jsonStr); + } catch (Exception excp) { + // fallback to earlier format: "name1=value1;name2=value2" + for (String optionString : jsonStr.split(";")) { + if (StringUtils.isEmpty(optionString)) { + continue; + } + + String[] nvArr = optionString.split("="); + String name = nvArr.length > 0 ? nvArr[0].trim() : null; + String value = nvArr.length > 1 ? nvArr[1].trim() : null; + + if (StringUtils.isEmpty(name)) { + continue; + } + + if (ret == null) { + ret = new HashMap<>(); + } + + ret.put(name, value); + } + } + } + return ret; + } + + private void updateKafkaServiceDef() { + try { + RangerServiceDef embeddedKafkaServiceDef = EmbeddedServiceDefsUtil.instance().getEmbeddedServiceDef(SERVICEDBSTORE_SERVICEDEFBYNAME_KAFKA_NAME); + + if (embeddedKafkaServiceDef != null) { + XXServiceDef xXServiceDefObj = daoMgr.getXXServiceDef().findByName(SERVICEDBSTORE_SERVICEDEFBYNAME_KAFKA_NAME); + Map serviceDefOptionsPreUpdate = null; + + if (xXServiceDefObj != null) { + String jsonStrPreUpdate = xXServiceDefObj.getDefOptions(); + + serviceDefOptionsPreUpdate = jsonStringToMap(jsonStrPreUpdate); + } + + RangerServiceDef dbKafkaServiceDef = svcDBStore.getServiceDefByName(SERVICEDBSTORE_SERVICEDEFBYNAME_KAFKA_NAME); + + if (dbKafkaServiceDef != null) { + List embeddedKafkaResourceDefs = embeddedKafkaServiceDef.getResources(); + List embeddedKafkaAccessTypes = embeddedKafkaServiceDef.getAccessTypes(); + + if (checkNewKafkaresourcePresent(embeddedKafkaResourceDefs)) { + // This is to check if CONSUMERGROUP resource is added to the resource definition, if so update the resource def and accessType def + if (embeddedKafkaResourceDefs != null) { + dbKafkaServiceDef.setResources(embeddedKafkaResourceDefs); + } + + if (embeddedKafkaAccessTypes != null) { + if (!embeddedKafkaAccessTypes.toString().equalsIgnoreCase(dbKafkaServiceDef.getAccessTypes().toString())) { + dbKafkaServiceDef.setAccessTypes(embeddedKafkaAccessTypes); + } + } + } + + RangerServiceDefValidator validator = validatorFactory.getServiceDefValidator(svcStore); + + validator.validate(dbKafkaServiceDef, Action.UPDATE); + + RangerServiceDef ret = svcStore.updateServiceDef(dbKafkaServiceDef); + + if (ret == null) { + logger.error("Error while updating {} service-def", SERVICEDBSTORE_SERVICEDEFBYNAME_KAFKA_NAME); + + throw new RuntimeException("Error while updating " + SERVICEDBSTORE_SERVICEDEFBYNAME_KAFKA_NAME + "service-def"); + } + + xXServiceDefObj = daoMgr.getXXServiceDef().findByName(SERVICEDBSTORE_SERVICEDEFBYNAME_KAFKA_NAME); + + if (xXServiceDefObj != null) { + String jsonStrPostUpdate = xXServiceDefObj.getDefOptions(); + Map serviceDefOptionsPostUpdate = jsonStringToMap(jsonStrPostUpdate); + + if (serviceDefOptionsPostUpdate != null && serviceDefOptionsPostUpdate.containsKey(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES)) { + if (serviceDefOptionsPreUpdate == null || !serviceDefOptionsPreUpdate.containsKey(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES)) { + String preUpdateValue = serviceDefOptionsPreUpdate == null ? null : serviceDefOptionsPreUpdate.get(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES); + + if (preUpdateValue == null) { + serviceDefOptionsPostUpdate.remove(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES); + } else { + serviceDefOptionsPostUpdate.put(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES, preUpdateValue); + } + + xXServiceDefObj.setDefOptions(mapToJsonString(serviceDefOptionsPostUpdate)); + + daoMgr.getXXServiceDef().update(xXServiceDefObj); + } + } + + createDefaultPolicyForNewResources(); + } + } + } + } catch (Exception e) { + logger.error("Error while updating {} service-def", SERVICEDBSTORE_SERVICEDEFBYNAME_KAFKA_NAME, e); + } + } + + private boolean checkNewKafkaresourcePresent(List resourceDefs) { + boolean ret = false; + + for (RangerServiceDef.RangerResourceDef resourceDef : resourceDefs) { + if (CONSUMERGROUP_RESOURCE_NAME.equals(resourceDef.getName())) { + ret = true; + break; + } + } + + return ret; + } + + private String mapToJsonString(Map map) { + String ret = null; + + if (map != null) { + try { + ret = jsonUtil.readMapToString(map); + } catch (Exception excp) { + logger.warn("mapToJsonString() failed to convert map: {}", map, excp); + } + } + + return ret; + } + + private void createDefaultPolicyForNewResources() { + logger.info("==> createDefaultPolicyForNewResources "); + + XXPortalUser xxPortalUser = daoMgr.getXXPortalUser().findByLoginId(LOGIN_ID_ADMIN); + Long currentUserId = xxPortalUser.getId(); + XXServiceDef xXServiceDefObj = daoMgr.getXXServiceDef().findByName(EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_KAFKA_NAME); + + if (xXServiceDefObj == null) { + logger.debug("ServiceDef not fount with name :{}", EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_KAFKA_NAME); + + return; + } + + Long xServiceDefId = xXServiceDefObj.getId(); + List xxServices = daoMgr.getXXService().findByServiceDefId(xServiceDefId); + + for (XXService xxService : xxServices) { + int resourceMapOrder = 0; + XXPolicy xxPolicy = new XXPolicy(); + + xxPolicy.setName(POLICY_NAME); + xxPolicy.setDescription(POLICY_NAME); + xxPolicy.setService(xxService.getId()); + xxPolicy.setPolicyPriority(RangerPolicy.POLICY_PRIORITY_NORMAL); + xxPolicy.setIsAuditEnabled(Boolean.TRUE); + xxPolicy.setIsEnabled(Boolean.TRUE); + xxPolicy.setPolicyType(RangerPolicy.POLICY_TYPE_ACCESS); + xxPolicy.setGuid(guidUtil.genGUID()); + xxPolicy.setAddedByUserId(currentUserId); + xxPolicy.setUpdatedByUserId(currentUserId); + + RangerPolicy rangerPolicy = getRangerPolicy(POLICY_NAME, xxPortalUser, xxService); + + xxPolicy.setPolicyText(JsonUtils.objectToJson(rangerPolicy)); + xxPolicy.setResourceSignature(rangerPolicy.getResourceSignature()); + xxPolicy.setZoneId(1L); + + boolean policyExist = false; + + try { + List rangerpolicies = svcDBStore.getPoliciesByResourceSignature(xxService.getName(), rangerPolicy.getResourceSignature(), true); + + if (CollectionUtils.isNotEmpty(rangerpolicies)) { + for (RangerPolicy rPolicy : rangerpolicies) { + if (rPolicy != null) { + logger.debug("print Policy: {}", rPolicy); + logger.debug("policy found with resource {} and ResourceSignature {} service name:{}", rPolicy.getResources(), rPolicy.getResourceSignature(), rPolicy.getService()); + + if (rPolicy.getResourceSignature().equalsIgnoreCase(rangerPolicy.getResourceSignature())) { + policyExist = true; + } + } + } + } + } catch (Exception ex) { + logger.error(" Error while getting policy using Resource Signature, Service Name and policy enabled flag", ex); + } + + if (!policyExist) { + XXPolicy createdPolicy = daoMgr.getXXPolicy().create(xxPolicy); + + XXPolicyItem xxPolicyItem = new XXPolicyItem(); + xxPolicyItem.setIsEnabled(Boolean.TRUE); + xxPolicyItem.setDelegateAdmin(Boolean.TRUE); + xxPolicyItem.setItemType(0); + xxPolicyItem.setOrder(0); + xxPolicyItem.setAddedByUserId(currentUserId); + xxPolicyItem.setUpdatedByUserId(currentUserId); + xxPolicyItem.setPolicyId(createdPolicy.getId()); + XXPolicyItem createdXXPolicyItem = daoMgr.getXXPolicyItem().create(xxPolicyItem); + + List accessTypes = getAccessTypes(); + + for (int i = 0; i < accessTypes.size(); i++) { + XXAccessTypeDef xAccTypeDef = daoMgr.getXXAccessTypeDef().findByNameAndServiceId(accessTypes.get(i), xxPolicy.getService()); + + if (xAccTypeDef == null) { + throw new RuntimeException(accessTypes.get(i) + ": is not a valid access-type. policy='" + xxPolicy.getName() + "' service='" + xxPolicy.getService() + "'"); + } + + XXPolicyItemAccess xPolItemAcc = new XXPolicyItemAccess(); + + xPolItemAcc.setIsAllowed(Boolean.TRUE); + xPolItemAcc.setType(xAccTypeDef.getId()); + xPolItemAcc.setOrder(i); + xPolItemAcc.setAddedByUserId(currentUserId); + xPolItemAcc.setUpdatedByUserId(currentUserId); + xPolItemAcc.setPolicyitemid(createdXXPolicyItem.getId()); + + daoMgr.getXXPolicyItemAccess().create(xPolItemAcc); + } + + for (int i = 0; i < DEFAULT_POLICY_USERS.size(); i++) { + String user = DEFAULT_POLICY_USERS.get(i); + + if (StringUtils.isBlank(user)) { + continue; + } + + XXUser xxUser = daoMgr.getXXUser().findByUserName(user); + + if (xxUser == null) { + logger.info("{} user is not found, adding user: {}", user, user); + + TransactionTemplate txTemplate = new TransactionTemplate(txManager); + + txTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + + try { + txTemplate.execute(status -> { + xUserMgr.createServiceConfigUserSynchronously(user); + + return null; + }); + } catch (Exception exception) { + logger.error("Cannot create ServiceConfigUser({})", user, exception); + } + + xxUser = daoMgr.getXXUser().findByUserName(user); + + if (xxUser == null) { + throw new RuntimeException(user + ": user does not exist. policy='" + xxPolicy.getName() + "' service='" + xxPolicy.getService() + "' user='" + user + "'"); + } + } + + Long userId = xxUser.getId(); + + XXPolicyItemUserPerm xUserPerm = new XXPolicyItemUserPerm(); + + xUserPerm.setUserId(userId); + xUserPerm.setPolicyItemId(createdXXPolicyItem.getId()); + xUserPerm.setOrder(i); + xUserPerm.setAddedByUserId(currentUserId); + xUserPerm.setUpdatedByUserId(currentUserId); + + daoMgr.getXXPolicyItemUserPerm().create(xUserPerm); + } + + for (int i = 0; i < DEFAULT_POLICY_GROUP.size(); i++) { + String group = DEFAULT_POLICY_GROUP.get(i); + + if (StringUtils.isBlank(group)) { + continue; + } + + XXGroup xxGroup = daoMgr.getXXGroup().findByGroupName(group); + + if (xxGroup == null) { + throw new RuntimeException(group + ": group does not exist. policy='" + xxPolicy.getName() + "' service='" + xxPolicy.getService() + "' group='" + group + "'"); + } + + XXPolicyItemGroupPerm xGroupPerm = new XXPolicyItemGroupPerm(); + + xGroupPerm.setGroupId(xxGroup.getId()); + xGroupPerm.setPolicyItemId(createdXXPolicyItem.getId()); + xGroupPerm.setOrder(i); + xGroupPerm.setAddedByUserId(currentUserId); + xGroupPerm.setUpdatedByUserId(currentUserId); + + daoMgr.getXXPolicyItemGroupPerm().create(xGroupPerm); + } + + String policyResourceName = CONSUMERGROUP_RESOURCE_NAME; + XXResourceDef xResDef = daoMgr.getXXResourceDef().findByNameAndPolicyId(policyResourceName, createdPolicy.getId()); + + if (xResDef == null) { + throw new RuntimeException(policyResourceName + ": is not a valid resource-type. policy='" + createdPolicy.getName() + "' service='" + createdPolicy.getService() + "'"); + } + + XXPolicyResource xPolRes = new XXPolicyResource(); + + xPolRes.setAddedByUserId(currentUserId); + xPolRes.setUpdatedByUserId(currentUserId); + xPolRes.setIsExcludes(Boolean.FALSE); + xPolRes.setIsRecursive(Boolean.FALSE); + xPolRes.setPolicyId(createdPolicy.getId()); + xPolRes.setResDefId(xResDef.getId()); + + xPolRes = daoMgr.getXXPolicyResource().create(xPolRes); + + XXPolicyResourceMap xPolResMap = new XXPolicyResourceMap(); + + xPolResMap.setResourceId(xPolRes.getId()); + xPolResMap.setValue("*"); + xPolResMap.setOrder(resourceMapOrder); + xPolResMap.setAddedByUserId(currentUserId); + xPolResMap.setUpdatedByUserId(currentUserId); + + daoMgr.getXXPolicyResourceMap().create(xPolResMap); + + resourceMapOrder++; + + logger.info("Creating policy for service id : {}", xxService.getId()); + } + + logger.info("<== createDefaultPolicyForNewResources "); + } + } + + private RangerPolicy getRangerPolicy(String newResource, XXPortalUser xxPortalUser, XXService xxService) { + List accesses = getPolicyItemAccesses(); + List users = new ArrayList<>(DEFAULT_POLICY_USERS); + List groups = new ArrayList<>(DEFAULT_POLICY_GROUP); + List conditions = new ArrayList<>(); + List policyItems = new ArrayList<>(); + RangerPolicy.RangerPolicyItem rangerPolicyItem = new RangerPolicy.RangerPolicyItem(); + + rangerPolicyItem.setAccesses(accesses); + rangerPolicyItem.setConditions(conditions); + rangerPolicyItem.setGroups(groups); + rangerPolicyItem.setUsers(users); + rangerPolicyItem.setDelegateAdmin(false); + + policyItems.add(rangerPolicyItem); + + Map policyResource = new HashMap<>(); + RangerPolicy.RangerPolicyResource rangerPolicyResource = new RangerPolicy.RangerPolicyResource(); + + rangerPolicyResource.setIsExcludes(false); + rangerPolicyResource.setIsRecursive(false); + rangerPolicyResource.setValue("*"); + + policyResource.put(CONSUMERGROUP_RESOURCE_NAME, rangerPolicyResource); + + RangerPolicy policy = new RangerPolicy(); + + policy.setCreateTime(new Date()); + policy.setDescription(newResource); + policy.setIsEnabled(true); + policy.setName(newResource); + policy.setCreatedBy(xxPortalUser.getLoginId()); + policy.setUpdatedBy(xxPortalUser.getLoginId()); + policy.setUpdateTime(new Date()); + policy.setService(xxService.getName()); + policy.setIsAuditEnabled(true); + policy.setPolicyItems(policyItems); + policy.setResources(policyResource); + policy.setPolicyType(0); + policy.setId(0L); + policy.setGuid(""); + policy.setPolicyLabels(new ArrayList<>()); + policy.setVersion(1L); + + RangerPolicyResourceSignature resourceSignature = new RangerPolicyResourceSignature(policy); + + policy.setResourceSignature(resourceSignature.getSignature()); + + return policy; + } + + private List getAccessTypes() { + return Arrays.asList("consume", "describe", "delete"); + } + + private ArrayList getPolicyItemAccesses() { + ArrayList rangerPolicyItemAccesses = new ArrayList<>(); + + for (String type : getAccessTypes()) { + RangerPolicy.RangerPolicyItemAccess policyItemAccess = new RangerPolicy.RangerPolicyItemAccess(); + + policyItemAccess.setType(type); + policyItemAccess.setIsAllowed(true); + + rangerPolicyItemAccesses.add(policyItemAccess); + } + + return rangerPolicyItemAccesses; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/patch/PatchForMigratingOldRegimePolicyJson_J10046.java b/security-admin/src/main/java/org/apache/ranger/patch/PatchForMigratingOldRegimePolicyJson_J10046.java index 4dfe72aed3..6465327272 100644 --- a/security-admin/src/main/java/org/apache/ranger/patch/PatchForMigratingOldRegimePolicyJson_J10046.java +++ b/security-admin/src/main/java/org/apache/ranger/patch/PatchForMigratingOldRegimePolicyJson_J10046.java @@ -6,7 +6,7 @@ * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -17,12 +17,6 @@ package org.apache.ranger.patch; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.MapUtils; import org.apache.commons.lang.StringUtils; @@ -69,490 +63,517 @@ 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 java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + /** * Consolidates Ranger policy details into a JSON string and stores it into a * column in x_policy table After running this patch Ranger policy can be * completely read/saved into x_policy table and some related Ref tables (which * maintain ID->String mapping for each policy). - * */ @Component public class PatchForMigratingOldRegimePolicyJson_J10046 extends BaseLoader { - private static final Logger logger = LoggerFactory.getLogger(PatchForMigratingOldRegimePolicyJson_J10046.class); - - @Autowired - RangerDaoManager daoMgr; - - @Autowired - ServiceDBStore svcStore; - - @Autowired - @Qualifier(value = "transactionManager") - PlatformTransactionManager txManager; - - @Autowired - PolicyRefUpdater policyRefUpdater; - - @Autowired - XUserMgr xUserMgr; - - private final Map groupIdMap = new HashMap<>(); - private final Map userIdMap = new HashMap<>(); - private final Map> resourceNameIdMap = new HashMap<>(); - private final Map> accessTypeIdMap = new HashMap<>(); - private final Map> conditionNameIdMap = new HashMap<>(); - private final Map> dataMaskTypeIdMap = new HashMap<>(); - - public static void main(String[] args) { - logger.info("main()"); - try { - PatchForMigratingOldRegimePolicyJson_J10046 loader = (PatchForMigratingOldRegimePolicyJson_J10046) CLIUtil.getBean(PatchForMigratingOldRegimePolicyJson_J10046.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); - } - } - - @Override - public void init() throws Exception { - // Do Nothing - } - - @Override - public void execLoad() { - logger.info("==> PatchForMigratingOldRegimePolicyJson.execLoad()"); - - try { - migrateRangerPolicyTableWithPolicyJson(); - } catch (Exception e) { - logger.error("Error while PatchForMigratingOldRegimePolicyJson()", e); - System.exit(1); - } - - logger.info("<== PatchForMigratingOldRegimePolicyJson.execLoad()"); - } - - @Override - public void printStats() { - logger.info("Migrating OldRegimePolicyJson data "); - } - - private void migrateRangerPolicyTableWithPolicyJson() throws Exception { - logger.info("==> updateRangerPolicyTableWithPolicyJson() "); - List xxPolicyList = daoMgr.getXXPolicy().getAllByPolicyItem(); - if (CollectionUtils.isNotEmpty(xxPolicyList)) { - for (XXPolicy xxPolicy : xxPolicyList) { - logger.info("XXPolicy : " + xxPolicy); - RangerPolicy policy = svcStore.getPolicy(xxPolicy.getId()); - if (policy != null) { - TransactionTemplate txTemplate = new TransactionTemplate(txManager); - RangerService service = svcStore.getServiceByName(policy.getService()); - PolicyUpdaterThread updaterThread = new PolicyUpdaterThread(txTemplate, service, policy); - updaterThread.setDaemon(true); - updaterThread.start(); - updaterThread.join(); - String errorMsg = updaterThread.getErrorMsg(); - if (StringUtils.isNotEmpty(errorMsg)) { - throw new Exception(errorMsg); - } - } - } - } else { - logger.info("no old XXPolicyItems found "); - } - logger.info("<== updateRangerPolicyTableWithPolicyJson() "); - } - public Boolean cleanupOldRefTables(RangerPolicy policy) { - final Long policyId = policy == null ? null : policy.getId(); - - if (policyId == null) { - return false; - } - logger.info("==> cleanupOldRefTables() "); - daoMgr.getXXPolicyItemGroupPerm().deleteByPolicyId(policyId); - daoMgr.getXXPolicyItemUserPerm().deleteByPolicyId(policyId); - daoMgr.getXXPolicyItemAccess().deleteByPolicyId(policyId); - daoMgr.getXXPolicyItemCondition().deleteByPolicyId(policyId); - daoMgr.getXXPolicyItemDataMaskInfo().deleteByPolicyId(policyId); - daoMgr.getXXPolicyItemRowFilterInfo().deleteByPolicyId(policyId); - daoMgr.getXXPolicyItem().deleteByPolicyId(policyId); - daoMgr.getXXPolicyResourceMap().deleteByPolicyId(policyId); - daoMgr.getXXPolicyResource().deleteByPolicyId(policyId); - logger.info("<== cleanupOldRefTables() "); - return true; - } - - private class PolicyUpdaterThread extends Thread { - final TransactionTemplate txTemplate; - final RangerService service; - final RangerPolicy policy; - String errorMsg; - - PolicyUpdaterThread(TransactionTemplate txTemplate, final RangerService service, final RangerPolicy policy) { - this.txTemplate = txTemplate; - this.service = service; - this.policy = policy; - this.errorMsg = null; - } - - public String getErrorMsg() { - return errorMsg; - } - - @Override - public void run() { - errorMsg = txTemplate.execute(new TransactionCallback() { - @Override - public String doInTransaction(TransactionStatus status) { - String ret = null; - try { - policyRefUpdater.cleanupRefTables(policy); - portPolicy(service.getType(), policy); - cleanupOldRefTables(policy); - } catch (Throwable e) { - logger.error("PortPolicy failed for policy:[" + policy + "]", e); - ret = e.toString(); - } - return ret; - } - }); - } - } - - private void portPolicy(String serviceType, RangerPolicy policy) throws Exception { - logger.info("==> portPolicy(id=" + policy.getId() + ")"); - - String policyText = JsonUtils.objectToJson(policy); - - if (StringUtils.isEmpty(policyText)) { - throw new Exception("Failed to convert policy to json string. Policy: [id=" + policy.getId() + "; name=" + policy.getName() + "; serviceType=" + serviceType + "]"); - } - - XXPolicyDao policyDao = daoMgr.getXXPolicy(); - XXPolicy dbBean = policyDao.getById(policy.getId()); - - dbBean.setPolicyText(policyText); - - policyDao.update(dbBean); - - try { - Set accesses = new HashSet<>(); - Set users = new HashSet<>(); - Set groups = new HashSet<>(); - Set conditions = new HashSet<>(); - Set dataMasks = new HashSet<>(); - - buildLists(policy.getPolicyItems(), accesses, conditions, users, groups); - buildLists(policy.getDenyPolicyItems(), accesses, conditions, users, groups); - buildLists(policy.getAllowExceptions(), accesses, conditions, users, groups); - buildLists(policy.getDenyExceptions(), accesses, conditions, users, groups); - buildLists(policy.getDataMaskPolicyItems(), accesses, conditions, users, groups); - buildLists(policy.getRowFilterPolicyItems(), accesses, conditions, users, groups); - - buildList(policy.getDataMaskPolicyItems(), dataMasks); - - addResourceDefRef(serviceType, policy); - addUserNameRef(policy.getId(), users); - addGroupNameRef(policy.getId(), groups); - addAccessDefRef(serviceType, policy.getId(), accesses); - addPolicyConditionDefRef(serviceType, policy.getId(), conditions); - addDataMaskDefRef(serviceType, policy.getId(), dataMasks); - } catch (Exception e) { - logger.error("portPoliry(id=" + policy.getId() +") failed!!"); - logger.error("Offending policy:" + policyText); - throw e; - } - - logger.info("<== portPolicy(id=" + policy.getId() + ")"); - } - - private void addResourceDefRef(String serviceType, RangerPolicy policy) throws Exception { - logger.info("==> addResourceDefRef(id=" + policy.getId() + ")"); - - Map serviceDefResourceNameIDMap = resourceNameIdMap.get(serviceType); - - if (serviceDefResourceNameIDMap == null) { - serviceDefResourceNameIDMap = new HashMap<>(); - - resourceNameIdMap.put(serviceType, serviceDefResourceNameIDMap); - - XXServiceDef dbServiceDef = daoMgr.getXXServiceDef().findByName(serviceType); - if (dbServiceDef != null) { - for (XXResourceDef resourceDef : daoMgr.getXXResourceDef().findByServiceDefId(dbServiceDef.getId())) { - serviceDefResourceNameIDMap.put(resourceDef.getName(), resourceDef.getId()); - } - } - } - - Map policyResources = policy.getResources(); - - if (MapUtils.isNotEmpty(policyResources)) { - XXPolicyRefResourceDao policyRefResourceDao = daoMgr.getXXPolicyRefResource(); - Set resourceNames = policyResources.keySet(); - - for (String resourceName : resourceNames) { - Long resourceDefId = serviceDefResourceNameIDMap.get(resourceName); - - if (resourceDefId == null) { - throw new Exception(resourceName + ": unknown resource in policy [id=" + policy.getId() + "; name=" + policy.getName() + "; serviceType=" + serviceType + "]. Known resources: " + serviceDefResourceNameIDMap.keySet()); - } - - // insert policy-id, resourceDefId, resourceName into Ref table - XXPolicyRefResource policyRefResource = new XXPolicyRefResource(); - - policyRefResource.setPolicyId(policy.getId()); - policyRefResource.setResourceDefId(resourceDefId); - policyRefResource.setResourceName(resourceName); + private static final Logger logger = LoggerFactory.getLogger(PatchForMigratingOldRegimePolicyJson_J10046.class); + + private final Map groupIdMap = new HashMap<>(); + private final Map userIdMap = new HashMap<>(); + private final Map> resourceNameIdMap = new HashMap<>(); + private final Map> accessTypeIdMap = new HashMap<>(); + private final Map> conditionNameIdMap = new HashMap<>(); + private final Map> dataMaskTypeIdMap = new HashMap<>(); + + @Autowired + RangerDaoManager daoMgr; + + @Autowired + ServiceDBStore svcStore; + + @Autowired + @Qualifier(value = "transactionManager") + PlatformTransactionManager txManager; + + @Autowired + PolicyRefUpdater policyRefUpdater; + + @Autowired + XUserMgr xUserMgr; + + public static void main(String[] args) { + logger.info("main()"); + + try { + PatchForMigratingOldRegimePolicyJson_J10046 loader = (PatchForMigratingOldRegimePolicyJson_J10046) CLIUtil.getBean(PatchForMigratingOldRegimePolicyJson_J10046.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); + } + } + + @Override + public void init() throws Exception { + // Do Nothing + } + + @Override + public void printStats() { + logger.info("Migrating OldRegimePolicyJson data "); + } + + @Override + public void execLoad() { + logger.info("==> PatchForMigratingOldRegimePolicyJson.execLoad()"); + + try { + migrateRangerPolicyTableWithPolicyJson(); + } catch (Exception e) { + logger.error("Error while PatchForMigratingOldRegimePolicyJson()", e); + + System.exit(1); + } + + logger.info("<== PatchForMigratingOldRegimePolicyJson.execLoad()"); + } + + public Boolean cleanupOldRefTables(RangerPolicy policy) { + final Long policyId = policy == null ? null : policy.getId(); + + if (policyId == null) { + return false; + } + + logger.info("==> cleanupOldRefTables() "); + + daoMgr.getXXPolicyItemGroupPerm().deleteByPolicyId(policyId); + daoMgr.getXXPolicyItemUserPerm().deleteByPolicyId(policyId); + daoMgr.getXXPolicyItemAccess().deleteByPolicyId(policyId); + daoMgr.getXXPolicyItemCondition().deleteByPolicyId(policyId); + daoMgr.getXXPolicyItemDataMaskInfo().deleteByPolicyId(policyId); + daoMgr.getXXPolicyItemRowFilterInfo().deleteByPolicyId(policyId); + daoMgr.getXXPolicyItem().deleteByPolicyId(policyId); + daoMgr.getXXPolicyResourceMap().deleteByPolicyId(policyId); + daoMgr.getXXPolicyResource().deleteByPolicyId(policyId); + + logger.info("<== cleanupOldRefTables() "); + + return true; + } + + private void migrateRangerPolicyTableWithPolicyJson() throws Exception { + logger.info("==> updateRangerPolicyTableWithPolicyJson() "); + + List xxPolicyList = daoMgr.getXXPolicy().getAllByPolicyItem(); + + if (CollectionUtils.isNotEmpty(xxPolicyList)) { + for (XXPolicy xxPolicy : xxPolicyList) { + logger.info("XXPolicy : {}", xxPolicy); + + RangerPolicy policy = svcStore.getPolicy(xxPolicy.getId()); + + if (policy != null) { + TransactionTemplate txTemplate = new TransactionTemplate(txManager); + RangerService service = svcStore.getServiceByName(policy.getService()); + PolicyUpdaterThread updaterThread = new PolicyUpdaterThread(txTemplate, service, policy); + + updaterThread.setDaemon(true); + updaterThread.start(); + updaterThread.join(); + + String errorMsg = updaterThread.getErrorMsg(); + + if (StringUtils.isNotEmpty(errorMsg)) { + throw new Exception(errorMsg); + } + } + } + } else { + logger.info("no old XXPolicyItems found "); + } + + logger.info("<== updateRangerPolicyTableWithPolicyJson() "); + } + + private void portPolicy(String serviceType, RangerPolicy policy) throws Exception { + logger.info("==> portPolicy(id={})", policy.getId()); + + String policyText = JsonUtils.objectToJson(policy); + + if (StringUtils.isEmpty(policyText)) { + throw new Exception("Failed to convert policy to json string. Policy: [id=" + policy.getId() + "; name=" + policy.getName() + "; serviceType=" + serviceType + "]"); + } + + XXPolicyDao policyDao = daoMgr.getXXPolicy(); + XXPolicy dbBean = policyDao.getById(policy.getId()); + + dbBean.setPolicyText(policyText); + + policyDao.update(dbBean); + + try { + Set accesses = new HashSet<>(); + Set users = new HashSet<>(); + Set groups = new HashSet<>(); + Set conditions = new HashSet<>(); + Set dataMasks = new HashSet<>(); + + buildLists(policy.getPolicyItems(), accesses, conditions, users, groups); + buildLists(policy.getDenyPolicyItems(), accesses, conditions, users, groups); + buildLists(policy.getAllowExceptions(), accesses, conditions, users, groups); + buildLists(policy.getDenyExceptions(), accesses, conditions, users, groups); + buildLists(policy.getDataMaskPolicyItems(), accesses, conditions, users, groups); + buildLists(policy.getRowFilterPolicyItems(), accesses, conditions, users, groups); + + buildList(policy.getDataMaskPolicyItems(), dataMasks); + + addResourceDefRef(serviceType, policy); + addUserNameRef(policy.getId(), users); + addGroupNameRef(policy.getId(), groups); + addAccessDefRef(serviceType, policy.getId(), accesses); + addPolicyConditionDefRef(serviceType, policy.getId(), conditions); + addDataMaskDefRef(serviceType, policy.getId(), dataMasks); + } catch (Exception e) { + logger.error("portPolicy(id={}) failed!!", policy.getId()); + logger.error("Offending policy:{}", policyText); + + throw e; + } + + logger.info("<== portPolicy(id={}})", policy.getId()); + } + + private void addResourceDefRef(String serviceType, RangerPolicy policy) throws Exception { + logger.info("==> addResourceDefRef(id={}})", policy.getId()); + + Map serviceDefResourceNameIDMap = resourceNameIdMap.get(serviceType); + + if (serviceDefResourceNameIDMap == null) { + serviceDefResourceNameIDMap = new HashMap<>(); + + resourceNameIdMap.put(serviceType, serviceDefResourceNameIDMap); + + XXServiceDef dbServiceDef = daoMgr.getXXServiceDef().findByName(serviceType); + + if (dbServiceDef != null) { + for (XXResourceDef resourceDef : daoMgr.getXXResourceDef().findByServiceDefId(dbServiceDef.getId())) { + serviceDefResourceNameIDMap.put(resourceDef.getName(), resourceDef.getId()); + } + } + } + + Map policyResources = policy.getResources(); + + if (MapUtils.isNotEmpty(policyResources)) { + XXPolicyRefResourceDao policyRefResourceDao = daoMgr.getXXPolicyRefResource(); + Set resourceNames = policyResources.keySet(); + + for (String resourceName : resourceNames) { + Long resourceDefId = serviceDefResourceNameIDMap.get(resourceName); + + if (resourceDefId == null) { + throw new Exception(resourceName + ": unknown resource in policy [id=" + policy.getId() + "; name=" + policy.getName() + "; serviceType=" + serviceType + "]. Known resources: " + serviceDefResourceNameIDMap.keySet()); + } + + // insert policy-id, resourceDefId, resourceName into Ref table + XXPolicyRefResource policyRefResource = new XXPolicyRefResource(); + + policyRefResource.setPolicyId(policy.getId()); + policyRefResource.setResourceDefId(resourceDefId); + policyRefResource.setResourceName(resourceName); + + policyRefResourceDao.create(policyRefResource); + } + } + + logger.info("<== addResourceDefRef(id={})", policy.getId()); + } + + private void addUserNameRef(Long policyId, Set users) throws Exception { + logger.info("==> addUserNameRef(id={})", policyId); + + XXPolicyRefUserDao policyRefUserDao = daoMgr.getXXPolicyRefUser(); + XXUserDao userDao = daoMgr.getXXUser(); + + // insert policy-id, userName into Ref table + for (String user : users) { + Long userId = userIdMap.get(user); + + if (userId == null) { + XXUser userObject = userDao.findByUserName(user); + + if (userObject == null) { + logger.info("user is not found, adding user: {}", user); + + TransactionTemplate txTemplate = new TransactionTemplate(txManager); + + txTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + + try { + txTemplate.execute(status -> { + xUserMgr.createServiceConfigUserSynchronously(user); + + return null; + }); + } catch (Exception exception) { + logger.error("Cannot create ServiceConfigUser({})", user, exception); + } + + userObject = userDao.findByUserName(user); + + if (userObject == null) { + throw new Exception(user + ": unknown user in policy [id=" + policyId + "]"); + } + } + + userId = userObject.getId(); + + logger.info("userId:{}", userId); + + userIdMap.put(user, userId); + } - policyRefResourceDao.create(policyRefResource); - } - } + XXPolicyRefUser policyRefUser = new XXPolicyRefUser(); - logger.info("<== addResourceDefRef(id=" + policy.getId() + ")"); - } + policyRefUser.setPolicyId(policyId); + policyRefUser.setUserName(user); + policyRefUser.setUserId(userId); - private void addUserNameRef(Long policyId, Set users) throws Exception { - logger.info("==> addUserNameRef(id=" + policyId + ")"); + policyRefUserDao.create(policyRefUser); + } - XXPolicyRefUserDao policyRefUserDao = daoMgr.getXXPolicyRefUser(); - XXUserDao userDao = daoMgr.getXXUser(); + logger.info("<== addUserNameRef(id={})", policyId); + } - // insert policy-id, userName into Ref table - for (String user : users) { - Long userId = userIdMap.get(user); + private void addGroupNameRef(Long policyId, Set groups) throws Exception { + logger.info("==> addGroupNameRef(id={})", policyId); - if (userId == null) { - XXUser userObject = userDao.findByUserName(user); + // insert policy-id, groupName into Ref table + XXPolicyRefGroupDao policyRefGroupDao = daoMgr.getXXPolicyRefGroup(); + XXGroupDao groupDao = daoMgr.getXXGroup(); - if (userObject == null) { - logger.info(user +" user is not found, adding user: "+user); - TransactionTemplate txTemplate = new TransactionTemplate(txManager); - txTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); - try { - txTemplate.execute(new TransactionCallback() { - @Override - public Object doInTransaction(TransactionStatus status) { - xUserMgr.createServiceConfigUserSynchronously(user); - return null; - } - }); - } catch(Exception exception) { - logger.error("Cannot create ServiceConfigUser(" + user + ")", exception); - } - userObject = userDao.findByUserName(user); - if (userObject == null) { - throw new Exception(user + ": unknown user in policy [id=" + policyId + "]"); - } - } + for (String group : groups) { + Long groupId = groupIdMap.get(group); - userId = userObject.getId(); - logger.info("userId:"+userId); + if (groupId == null) { + XXGroup groupObject = groupDao.findByGroupName(group); - userIdMap.put(user, userId); - } + if (groupObject == null) { + throw new Exception(group + ": unknown group in policy [id=" + policyId + "]"); + } - XXPolicyRefUser policyRefUser = new XXPolicyRefUser(); + groupId = groupObject.getId(); - policyRefUser.setPolicyId(policyId); - policyRefUser.setUserName(user); - policyRefUser.setUserId(userId); + groupIdMap.put(group, groupId); + } - policyRefUserDao.create(policyRefUser); - } + XXPolicyRefGroup policyRefGroup = new XXPolicyRefGroup(); - logger.info("<== addUserNameRef(id=" + policyId + ")"); - } + policyRefGroup.setPolicyId(policyId); + policyRefGroup.setGroupName(group); + policyRefGroup.setGroupId(groupId); - private void addGroupNameRef(Long policyId, Set groups) throws Exception { - logger.info("==> addGroupNameRef(id=" + policyId + ")"); + policyRefGroupDao.create(policyRefGroup); + } - // insert policy-id, groupName into Ref table - XXPolicyRefGroupDao policyRefGroupDao = daoMgr.getXXPolicyRefGroup(); - XXGroupDao groupDao = daoMgr.getXXGroup(); + logger.info("<== addGroupNameRef(id={})", policyId); + } - for (String group : groups) { - Long groupId = groupIdMap.get(group); + private void addAccessDefRef(String serviceType, Long policyId, Set accesses) throws Exception { + logger.info("==> addAccessDefRef(id={})", policyId); + // insert policy-id, accessName into Ref table - if (groupId == null) { - XXGroup groupObject = groupDao.findByGroupName(group); + Map serviceDefAccessTypeIDMap = accessTypeIdMap.get(serviceType); - if (groupObject == null) { - throw new Exception(group + ": unknown group in policy [id=" + policyId + "]"); - } + if (serviceDefAccessTypeIDMap == null) { + serviceDefAccessTypeIDMap = new HashMap<>(); - groupId = groupObject.getId(); + accessTypeIdMap.put(serviceType, serviceDefAccessTypeIDMap); - groupIdMap.put(group, groupId); - } + XXServiceDef dbServiceDef = daoMgr.getXXServiceDef().findByName(serviceType); - XXPolicyRefGroup policyRefGroup = new XXPolicyRefGroup(); + if (dbServiceDef != null) { + for (XXAccessTypeDef accessTypeDef : daoMgr.getXXAccessTypeDef().findByServiceDefId(dbServiceDef.getId())) { + serviceDefAccessTypeIDMap.put(accessTypeDef.getName(), accessTypeDef.getId()); + } + } + } - policyRefGroup.setPolicyId(policyId); - policyRefGroup.setGroupName(group); - policyRefGroup.setGroupId(groupId); + XXPolicyRefAccessTypeDao policyRefAccessTypeDao = daoMgr.getXXPolicyRefAccessType(); - policyRefGroupDao.create(policyRefGroup); - } + for (String access : accesses) { + Long accessTypeDefId = serviceDefAccessTypeIDMap.get(access); - logger.info("<== addGroupNameRef(id=" + policyId + ")"); + if (accessTypeDefId == null) { + throw new Exception(access + ": unknown accessType in policy [id=" + policyId + "; serviceType=" + serviceType + "]. Known accessTypes: " + serviceDefAccessTypeIDMap.keySet()); + } - } + XXPolicyRefAccessType policyRefAccessType = new XXPolicyRefAccessType(); - private void addAccessDefRef(String serviceType, Long policyId, Set accesses) throws Exception { - logger.info("==> addAccessDefRef(id=" + policyId + ")"); - // insert policy-id, accessName into Ref table + policyRefAccessType.setPolicyId(policyId); + policyRefAccessType.setAccessTypeName(access); + policyRefAccessType.setAccessDefId(accessTypeDefId); - Map serviceDefAccessTypeIDMap = accessTypeIdMap.get(serviceType); + policyRefAccessTypeDao.create(policyRefAccessType); + } - if (serviceDefAccessTypeIDMap == null) { - serviceDefAccessTypeIDMap = new HashMap<>(); + logger.info("<== addAccessDefRef(id={}})", policyId); + } - accessTypeIdMap.put(serviceType, serviceDefAccessTypeIDMap); + private void addPolicyConditionDefRef(String serviceType, Long policyId, Set conditions) throws Exception { + logger.info("==> addPolicyConditionDefRef(id={})", policyId); + // insert policy-id, conditionName into Ref table - XXServiceDef dbServiceDef = daoMgr.getXXServiceDef().findByName(serviceType); - if (dbServiceDef != null) { - for (XXAccessTypeDef accessTypeDef : daoMgr.getXXAccessTypeDef().findByServiceDefId(dbServiceDef.getId())) { - serviceDefAccessTypeIDMap.put(accessTypeDef.getName(), accessTypeDef.getId()); - } - } - } + Map serviceDefConditionNameIDMap = conditionNameIdMap.get(serviceType); - XXPolicyRefAccessTypeDao policyRefAccessTypeDao = daoMgr.getXXPolicyRefAccessType(); + if (serviceDefConditionNameIDMap == null) { + serviceDefConditionNameIDMap = new HashMap<>(); - for (String access : accesses) { - Long accessTypeDefId = serviceDefAccessTypeIDMap.get(access); + conditionNameIdMap.put(serviceType, serviceDefConditionNameIDMap); - if (accessTypeDefId == null) { - throw new Exception(access + ": unknown accessType in policy [id=" + policyId + "; serviceType=" + serviceType + "]. Known accessTypes: " + serviceDefAccessTypeIDMap.keySet()); - } + XXServiceDef dbServiceDef = daoMgr.getXXServiceDef().findByName(serviceType); - XXPolicyRefAccessType policyRefAccessType = new XXPolicyRefAccessType(); + if (dbServiceDef != null) { + for (XXPolicyConditionDef conditionDef : daoMgr.getXXPolicyConditionDef().findByServiceDefId(dbServiceDef.getId())) { + serviceDefConditionNameIDMap.put(conditionDef.getName(), conditionDef.getId()); + } + } + } - policyRefAccessType.setPolicyId(policyId); - policyRefAccessType.setAccessTypeName(access); - policyRefAccessType.setAccessDefId(accessTypeDefId); + XXPolicyRefConditionDao policyRefConditionDao = daoMgr.getXXPolicyRefCondition(); - policyRefAccessTypeDao.create(policyRefAccessType); - } + for (String condition : conditions) { + Long conditionDefId = serviceDefConditionNameIDMap.get(condition); - logger.info("<== addAccessDefRef(id=" + policyId + ")"); - } + if (conditionDefId == null) { + throw new Exception(condition + ": unknown condition in policy [id=" + policyId + "; serviceType=" + serviceType + "]. Known conditions are: " + serviceDefConditionNameIDMap.keySet()); + } - private void addPolicyConditionDefRef(String serviceType, Long policyId, Set conditions) throws Exception { - logger.info("==> addPolicyConditionDefRef(id=" + policyId + ")"); - // insert policy-id, conditionName into Ref table + XXPolicyRefCondition policyRefCondition = new XXPolicyRefCondition(); - Map serviceDefConditionNameIDMap = conditionNameIdMap.get(serviceType); + policyRefCondition.setPolicyId(policyId); + policyRefCondition.setConditionName(condition); + policyRefCondition.setConditionDefId(conditionDefId); - if (serviceDefConditionNameIDMap == null) { - serviceDefConditionNameIDMap = new HashMap<>(); + policyRefConditionDao.create(policyRefCondition); + } - conditionNameIdMap.put(serviceType, serviceDefConditionNameIDMap); + logger.info("<== addPolicyConditionDefRef(id={})", policyId); + } - XXServiceDef dbServiceDef = daoMgr.getXXServiceDef().findByName(serviceType); - if (dbServiceDef != null) { - for (XXPolicyConditionDef conditionDef : daoMgr.getXXPolicyConditionDef().findByServiceDefId(dbServiceDef.getId())) { - serviceDefConditionNameIDMap.put(conditionDef.getName(), conditionDef.getId()); - } - } - } + private void addDataMaskDefRef(String serviceType, Long policyId, Set datamasks) throws Exception { + logger.info("==> addDataMaskDefRef(id={})", policyId); - XXPolicyRefConditionDao policyRefConditionDao = daoMgr.getXXPolicyRefCondition(); + // insert policy-id, datamaskName into Ref table - for (String condition : conditions) { - Long conditionDefId = serviceDefConditionNameIDMap.get(condition); + Map serviceDefDataMaskTypeIDMap = dataMaskTypeIdMap.get(serviceType); - if (conditionDefId == null) { - throw new Exception(condition + ": unknown condition in policy [id=" + policyId + "; serviceType=" + serviceType + "]. Known conditions are: " + serviceDefConditionNameIDMap.keySet()); - } + if (serviceDefDataMaskTypeIDMap == null) { + serviceDefDataMaskTypeIDMap = new HashMap<>(); - XXPolicyRefCondition policyRefCondition = new XXPolicyRefCondition(); + dataMaskTypeIdMap.put(serviceType, serviceDefDataMaskTypeIDMap); - policyRefCondition.setPolicyId(policyId); - policyRefCondition.setConditionName(condition); - policyRefCondition.setConditionDefId(conditionDefId); + XXServiceDef dbServiceDef = daoMgr.getXXServiceDef().findByName(serviceType); - policyRefConditionDao.create(policyRefCondition); - } + if (dbServiceDef != null) { + for (XXDataMaskTypeDef dataMaskTypeDef : daoMgr.getXXDataMaskTypeDef().findByServiceDefId(dbServiceDef.getId())) { + serviceDefDataMaskTypeIDMap.put(dataMaskTypeDef.getName(), dataMaskTypeDef.getId()); + } + } + } - logger.info("<== addPolicyConditionDefRef(id=" + policyId + ")"); - } + XXPolicyRefDataMaskTypeDao policyRefDataMaskTypeDao = daoMgr.getXXPolicyRefDataMaskType(); - private void addDataMaskDefRef(String serviceType, Long policyId, Set datamasks) throws Exception { - logger.info("==> addDataMaskDefRef(id=" + policyId + ")"); + for (String datamask : datamasks) { + Long dataMaskTypeId = serviceDefDataMaskTypeIDMap.get(datamask); - // insert policy-id, datamaskName into Ref table + if (dataMaskTypeId == null) { + throw new Exception(datamask + ": unknown dataMaskType in policy [id=" + policyId + "; serviceType=" + serviceType + "]. Known dataMaskTypes " + serviceDefDataMaskTypeIDMap.keySet()); + } - Map serviceDefDataMaskTypeIDMap = dataMaskTypeIdMap.get(serviceType); + XXPolicyRefDataMaskType policyRefDataMaskType = new XXPolicyRefDataMaskType(); - if (serviceDefDataMaskTypeIDMap == null) { - serviceDefDataMaskTypeIDMap = new HashMap<>(); + policyRefDataMaskType.setPolicyId(policyId); + policyRefDataMaskType.setDataMaskTypeName(datamask); + policyRefDataMaskType.setDataMaskDefId(dataMaskTypeId); - dataMaskTypeIdMap.put(serviceType, serviceDefDataMaskTypeIDMap); + policyRefDataMaskTypeDao.create(policyRefDataMaskType); + } - XXServiceDef dbServiceDef = daoMgr.getXXServiceDef().findByName(serviceType); - if (dbServiceDef != null) { - for (XXDataMaskTypeDef dataMaskTypeDef : daoMgr.getXXDataMaskTypeDef().findByServiceDefId(dbServiceDef.getId())) { - serviceDefDataMaskTypeIDMap.put(dataMaskTypeDef.getName(), dataMaskTypeDef.getId()); - } - } - } + logger.info("<== addDataMaskDefRef(id={})", policyId); + } - XXPolicyRefDataMaskTypeDao policyRefDataMaskTypeDao = daoMgr.getXXPolicyRefDataMaskType(); + private void buildLists(List policyItems, Set accesses, Set conditions, Set users, Set groups) { + for (RangerPolicyItem item : policyItems) { + for (RangerPolicyItemAccess policyAccess : item.getAccesses()) { + accesses.add(policyAccess.getType()); + } - for (String datamask : datamasks) { - Long dataMaskTypeId = serviceDefDataMaskTypeIDMap.get(datamask); + for (RangerPolicyItemCondition policyCondition : item.getConditions()) { + conditions.add(policyCondition.getType()); + } - if (dataMaskTypeId == null) { - throw new Exception(datamask + ": unknown dataMaskType in policy [id=" + policyId + "; serviceType=" + serviceType + "]. Known dataMaskTypes " + serviceDefDataMaskTypeIDMap.keySet()); - } + users.addAll(item.getUsers()); + groups.addAll(item.getGroups()); + } + } - XXPolicyRefDataMaskType policyRefDataMaskType = new XXPolicyRefDataMaskType(); + private void buildList(List dataMaskPolicyItems, Set dataMasks) { + for (RangerDataMaskPolicyItem datMaskPolicyItem : dataMaskPolicyItems) { + dataMasks.add(datMaskPolicyItem.getDataMaskInfo().getDataMaskType()); + } + } - policyRefDataMaskType.setPolicyId(policyId); - policyRefDataMaskType.setDataMaskTypeName(datamask); - policyRefDataMaskType.setDataMaskDefId(dataMaskTypeId); + private class PolicyUpdaterThread extends Thread { + final TransactionTemplate txTemplate; + final RangerService service; + final RangerPolicy policy; + String errorMsg; - policyRefDataMaskTypeDao.create(policyRefDataMaskType); - } + PolicyUpdaterThread(TransactionTemplate txTemplate, final RangerService service, final RangerPolicy policy) { + this.txTemplate = txTemplate; + this.service = service; + this.policy = policy; + this.errorMsg = null; + } - logger.info("<== addDataMaskDefRef(id=" + policyId + ")"); + public String getErrorMsg() { + return errorMsg; + } - } + @Override + public void run() { + errorMsg = txTemplate.execute(status -> { + String ret = null; - private void buildLists(List policyItems, Set accesses, Set conditions, Set users, Set groups) { - for (RangerPolicyItem item : policyItems) { - for (RangerPolicyItemAccess policyAccess : item.getAccesses()) { - accesses.add(policyAccess.getType()); - } + try { + policyRefUpdater.cleanupRefTables(policy); - for (RangerPolicyItemCondition policyCondition : item.getConditions()) { - conditions.add(policyCondition.getType()); - } + portPolicy(service.getType(), policy); - users.addAll(item.getUsers()); - groups.addAll(item.getGroups()); - } - } + cleanupOldRefTables(policy); + } catch (Throwable e) { + logger.error("PortPolicy failed for policy:[{}]", policy, e); - private void buildList(List dataMaskPolicyItems, Set dataMasks) { - for (RangerDataMaskPolicyItem datMaskPolicyItem : dataMaskPolicyItems) { - dataMasks.add(datMaskPolicyItem.getDataMaskInfo().getDataMaskType()); - } - } + ret = e.toString(); + } + return ret; + }); + } + } } diff --git a/security-admin/src/main/java/org/apache/ranger/patch/PatchForMigratingRangerServiceResource_J10037.java b/security-admin/src/main/java/org/apache/ranger/patch/PatchForMigratingRangerServiceResource_J10037.java index f78fb8d8c0..0e84333a79 100644 --- a/security-admin/src/main/java/org/apache/ranger/patch/PatchForMigratingRangerServiceResource_J10037.java +++ b/security-admin/src/main/java/org/apache/ranger/patch/PatchForMigratingRangerServiceResource_J10037.java @@ -6,7 +6,7 @@ * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -25,8 +25,6 @@ package org.apache.ranger.patch; -import java.util.List; - import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang.StringUtils; import org.apache.ranger.db.RangerDaoManager; @@ -43,161 +41,157 @@ 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 java.util.List; + @Component public class PatchForMigratingRangerServiceResource_J10037 extends BaseLoader { + private static final Logger logger = LoggerFactory.getLogger(PatchForMigratingRangerServiceResource_J10037.class); + + @Autowired + RangerDaoManager daoMgr; + + @Autowired + @Qualifier(value = "transactionManager") + PlatformTransactionManager txManager; + + @Autowired + RangerServiceResourceService serviceResourceService; + + public static void main(String[] args) { + logger.info("main() starts"); + + try { + PatchForMigratingRangerServiceResource_J10037 loader = (PatchForMigratingRangerServiceResource_J10037) CLIUtil.getBean(PatchForMigratingRangerServiceResource_J10037.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); + } + } + + @Override + public void init() throws Exception { + // Do Nothing + } + + @Override + public void printStats() { + logger.info(" Updating Ranger Service Resource signature "); + } + + @Override + public void execLoad() { + logger.info("==> PatchForMigratingRangerServiceResource.execLoad()"); + + try { + updateRangerServiceResourceSignature(); + } catch (Exception e) { + logger.error("Error while updateRangerServiceResourceSignature()", e); + + System.exit(1); + } - private static final Logger logger = LoggerFactory.getLogger(PatchForMigratingRangerServiceResource_J10037.class); + logger.info("<== PatchForMigratingRangerServiceResource.execLoad()"); + } - @Autowired - RangerDaoManager daoMgr; + private void updateRangerServiceResourceSignature() throws Exception { + logger.info("==> updateRangerServiceResourceSignature() start "); - @Autowired - @Qualifier(value = "transactionManager") - PlatformTransactionManager txManager; + List allServices = daoMgr.getXXService().getAll(); - @Autowired - RangerServiceResourceService serviceResourceService; + if (CollectionUtils.isNotEmpty(allServices)) { + for (XXService xService : allServices) { + logger.info("processing ranger service: {}", xService); - public static void main(String[] args) { - logger.info("main() starts"); - try { - PatchForMigratingRangerServiceResource_J10037 loader = (PatchForMigratingRangerServiceResource_J10037) CLIUtil - .getBean(PatchForMigratingRangerServiceResource_J10037.class); + List serviceResourceGuids = daoMgr.getXXServiceResource().findServiceResourceGuidsInServiceId(xService.getId()); - loader.init(); + if (CollectionUtils.isNotEmpty(serviceResourceGuids)) { + TransactionTemplate txTemplate = new TransactionTemplate(txManager); - while (loader.isMoreToProcess()) { - loader.load(); - } + int chunkSize = 1000; // hardcoded + int numOfChunks = (serviceResourceGuids.size() / chunkSize) + 1; - logger.info("Load complete. Exiting!!!"); + for (int chunkIndex = 0; chunkIndex < numOfChunks; chunkIndex++) { + List chunk = serviceResourceGuids.subList(chunkIndex * chunkSize, (chunkIndex == numOfChunks - 1 ? serviceResourceGuids.size() : (chunkIndex + 1) * chunkSize)); + ServiceResourceUpdaterThread updaterThread = new ServiceResourceUpdaterThread(txTemplate, chunk); + String errorMsg = runThread(updaterThread); - System.exit(0); - } catch (Exception e) { - logger.error("Error loading", e); - System.exit(1); - } - } + if (StringUtils.isNotEmpty(errorMsg)) { + throw new Exception(errorMsg); + } + } + } else { + logger.info("No Ranger service resource found for service : {}", xService.getDisplayName()); + } + } + } else { + logger.info("No Ranger service found"); + } - @Override - public void init() throws Exception { - // Do Nothing - } + logger.info("<== updateRangerServiceResourceSgnature() end"); + } - @Override - public void execLoad() { - logger.info("==> PatchForMigratingRangerServiceResource.execLoad()"); + private String runThread(ServiceResourceUpdaterThread updaterThread) throws Exception { + updaterThread.setDaemon(true); + updaterThread.start(); + updaterThread.join(); - try { - updateRangerServiceResourceSignature(); - } catch (Exception e) { - logger.error("Error while updateRangerServiceResourceSignature()", e); - System.exit(1); - } - - logger.info("<== PatchForMigratingRangerServiceResource.execLoad()"); - } - - @Override - public void printStats() { - logger.info(" Updating Ranger Service Resource signature "); - } - - private void updateRangerServiceResourceSignature() throws Exception { - logger.info("==> updateRangerServiceResourceSignature() start "); - - List allServices = daoMgr.getXXService().getAll(); - - if (CollectionUtils.isNotEmpty(allServices)) { - - for (XXService xService : allServices) { - logger.info("processing ranger service: " + xService); - - List serviceResourceGuids = daoMgr.getXXServiceResource().findServiceResourceGuidsInServiceId(xService.getId()); - - if (CollectionUtils.isNotEmpty(serviceResourceGuids)) { - - TransactionTemplate txTemplate = new TransactionTemplate(txManager); - - int chunkSize = 1000; // hardcoded - int numOfChunks = (serviceResourceGuids.size() / chunkSize) + 1; - - for (int chunkIndex = 0; chunkIndex < numOfChunks; chunkIndex++) { - List chunk = serviceResourceGuids.subList(chunkIndex * chunkSize, (chunkIndex == numOfChunks -1 ? serviceResourceGuids.size() : (chunkIndex + 1) * chunkSize)); - - ServiceResourceUpdaterThread updaterThread = new ServiceResourceUpdaterThread(txTemplate, chunk); - - String errorMsg = runThread(updaterThread); - - if (StringUtils.isNotEmpty(errorMsg)) { - throw new Exception(errorMsg); - } - } - } else { - logger.info("No Ranger service resource found for service : " + xService.getDisplayName()); - } - } - } else { - logger.info("No Ranger service found"); - } - - logger.info("<== updateRangerServiceResourceSgnature() end"); - } - - private String runThread(ServiceResourceUpdaterThread updaterThread) throws Exception { - updaterThread.setDaemon(true); - updaterThread.start(); - updaterThread.join(); - return updaterThread.getErrorMsg(); - } - - private class ServiceResourceUpdaterThread extends Thread { - final TransactionTemplate txTemplate; - final List entityGuids; - String errorMsg; - - ServiceResourceUpdaterThread(TransactionTemplate txTemplate, final List entityGuids) { - this.txTemplate = txTemplate; - this.entityGuids = entityGuids; - this.errorMsg = null; - } - - public String getErrorMsg() { - return errorMsg; - } - - @Override - public void run() { - txTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); - - errorMsg = txTemplate.execute(new TransactionCallback() { - @Override - public String doInTransaction(TransactionStatus status) { - String ret = null; - try { - if (CollectionUtils.isNotEmpty(entityGuids)) { - for (String entityGuid : entityGuids) { - XXServiceResource entityObject = daoMgr.getXXServiceResource().findByGuid(entityGuid); - RangerServiceResource viewObject = serviceResourceService.getPopulatedViewObject(entityObject); - RangerServiceResourceSignature serializer = new RangerServiceResourceSignature(viewObject); - - entityObject.setResourceSignature(serializer.getSignature()); - - daoMgr.getXXServiceResource().update(entityObject); - } - } - } catch (Throwable e) { - logger.error("signature update failed :[rangerServiceResource=" + entityGuids + "]", e); - ret = e.toString(); - } - return ret; - } - }); - } - } + return updaterThread.getErrorMsg(); + } + + private class ServiceResourceUpdaterThread extends Thread { + final TransactionTemplate txTemplate; + final List entityGuids; + String errorMsg; + ServiceResourceUpdaterThread(TransactionTemplate txTemplate, final List entityGuids) { + this.txTemplate = txTemplate; + this.entityGuids = entityGuids; + this.errorMsg = null; + } + + public String getErrorMsg() { + return errorMsg; + } + + @Override + public void run() { + txTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + + errorMsg = txTemplate.execute(status -> { + String ret = null; + try { + if (CollectionUtils.isNotEmpty(entityGuids)) { + for (String entityGuid : entityGuids) { + XXServiceResource entityObject = daoMgr.getXXServiceResource().findByGuid(entityGuid); + RangerServiceResource viewObject = serviceResourceService.getPopulatedViewObject(entityObject); + RangerServiceResourceSignature serializer = new RangerServiceResourceSignature(viewObject); + + entityObject.setResourceSignature(serializer.getSignature()); + + daoMgr.getXXServiceResource().update(entityObject); + } + } + } catch (Throwable e) { + logger.error("signature update failed :[rangerServiceResource={}", entityGuids, e); + + ret = e.toString(); + } + + return ret; + }); + } + } } diff --git a/security-admin/src/main/java/org/apache/ranger/patch/PatchForNifiResourceUpdateExclude_J10011.java b/security-admin/src/main/java/org/apache/ranger/patch/PatchForNifiResourceUpdateExclude_J10011.java index ff35a8c0f0..cd381c5075 100644 --- a/security-admin/src/main/java/org/apache/ranger/patch/PatchForNifiResourceUpdateExclude_J10011.java +++ b/security-admin/src/main/java/org/apache/ranger/patch/PatchForNifiResourceUpdateExclude_J10011.java @@ -18,7 +18,6 @@ package org.apache.ranger.patch; -import java.util.List; import org.apache.commons.collections.CollectionUtils; import org.apache.ranger.biz.ServiceDBStore; import org.apache.ranger.common.JSONUtil; @@ -40,110 +39,125 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; +import java.util.List; + /** * Disables the Nifi plugin's exclude toggle in Ranger UI. * After running this patch user wont be able to add exclude resource policies in NIFI. */ @Component public class PatchForNifiResourceUpdateExclude_J10011 extends BaseLoader { - private static final Logger logger = LoggerFactory.getLogger(PatchForNifiResourceUpdateExclude_J10011.class); - @Autowired - RangerDaoManager daoMgr; + private static final Logger logger = LoggerFactory.getLogger(PatchForNifiResourceUpdateExclude_J10011.class); - @Autowired - ServiceDBStore svcDBStore; + @Autowired + RangerDaoManager daoMgr; - @Autowired - JSONUtil jsonUtil; + @Autowired + ServiceDBStore svcDBStore; - @Autowired - StringUtil stringUtil; + @Autowired + JSONUtil jsonUtil; - @Autowired - RangerValidatorFactory validatorFactory; + @Autowired + StringUtil stringUtil; - @Autowired - ServiceDBStore svcStore; + @Autowired + RangerValidatorFactory validatorFactory; - @Autowired - RangerPolicyService policyService; + @Autowired + ServiceDBStore svcStore; - public static void main(String[] args) { - logger.info("main()"); - try { - PatchForNifiResourceUpdateExclude_J10011 loader = (PatchForNifiResourceUpdateExclude_J10011) CLIUtil.getBean(PatchForNifiResourceUpdateExclude_J10011.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); - } - } + @Autowired + RangerPolicyService policyService; - @Override - public void init() throws Exception { - // Do Nothing - } + public static void main(String[] args) { + logger.info("main()"); - @Override - public void execLoad() { - logger.info("==> PatchForNifiResourceUpdateExclude.execLoad()"); - try { - updateNifiServiceDef(); - } catch (Exception e) { - logger.error("Error whille updateNifiServiceDef()data.", e); - } - logger.info("<== PatchForNifiResourceUpdateExclude.execLoad()"); - } + try { + PatchForNifiResourceUpdateExclude_J10011 loader = (PatchForNifiResourceUpdateExclude_J10011) CLIUtil.getBean(PatchForNifiResourceUpdateExclude_J10011.class); + + loader.init(); + + while (loader.isMoreToProcess()) { + loader.load(); + } + + logger.info("Load complete. Exiting!!!"); - @Override - public void printStats() { - logger.info("updateNifiServiceDef data "); + System.exit(0); + } catch (Exception e) { + logger.error("Error loading", e); + + System.exit(1); + } + } + + @Override + public void init() throws Exception { + // Do Nothing + } + + @Override + public void printStats() { + logger.info("updateNifiServiceDef data "); + } + + @Override + public void execLoad() { + logger.info("==> PatchForNifiResourceUpdateExclude.execLoad()"); + + try { + updateNifiServiceDef(); + } catch (Exception e) { + logger.error("Error whille updateNifiServiceDef()data.", e); } - private void updateNifiServiceDef(){ - RangerServiceDef ret = null; - RangerServiceDef dbNifiServiceDef = null; - try { - dbNifiServiceDef = svcDBStore.getServiceDefByName(EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_NIFI_NAME); - if (dbNifiServiceDef != null) { - List rRDefList = null; - rRDefList = dbNifiServiceDef.getResources(); - if (CollectionUtils.isNotEmpty(rRDefList)) { - for (RangerResourceDef rRDef : rRDefList) { - - if (rRDef.getExcludesSupported()) { - rRDef.setExcludesSupported(false); - } - - XXResourceDef sdf=daoMgr.getXXResourceDef().findByNameAndServiceDefId(rRDef.getName(), dbNifiServiceDef.getId()); - long ResourceDefId=sdf.getId(); - List RangerPolicyResourceList=daoMgr.getXXPolicyResource().findByResDefId(ResourceDefId); - if (CollectionUtils.isNotEmpty(RangerPolicyResourceList)){ - for(XXPolicyResource RangerPolicyResource : RangerPolicyResourceList){ - if(RangerPolicyResource.getIsexcludes()){ - RangerPolicy rPolicy=svcDBStore.getPolicy(RangerPolicyResource.getPolicyid()); - rPolicy.setIsEnabled(false); - svcStore.updatePolicy(rPolicy); - } - } - } - } - } - RangerServiceDefValidator validator = validatorFactory.getServiceDefValidator(svcStore); - validator.validate(dbNifiServiceDef, Action.UPDATE); - ret = svcStore.updateServiceDef(dbNifiServiceDef); + logger.info("<== PatchForNifiResourceUpdateExclude.execLoad()"); + } + + private void updateNifiServiceDef() { + try { + RangerServiceDef dbNifiServiceDef = svcDBStore.getServiceDefByName(EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_NIFI_NAME); + + if (dbNifiServiceDef != null) { + List rRDefList = dbNifiServiceDef.getResources(); + + if (CollectionUtils.isNotEmpty(rRDefList)) { + for (RangerResourceDef rRDef : rRDefList) { + if (rRDef.getExcludesSupported()) { + rRDef.setExcludesSupported(false); } - if (ret == null) { - logger.error("Error while updating " + EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_NIFI_NAME+ "service-def"); + + XXResourceDef sdf = daoMgr.getXXResourceDef().findByNameAndServiceDefId(rRDef.getName(), dbNifiServiceDef.getId()); + long resourceDefId = sdf.getId(); + List rangerPolicyResourceList = daoMgr.getXXPolicyResource().findByResDefId(resourceDefId); + + if (CollectionUtils.isNotEmpty(rangerPolicyResourceList)) { + for (XXPolicyResource rangerPolicyResource : rangerPolicyResourceList) { + if (rangerPolicyResource.getIsexcludes()) { + RangerPolicy rPolicy = svcDBStore.getPolicy(rangerPolicyResource.getPolicyid()); + + rPolicy.setIsEnabled(false); + + svcStore.updatePolicy(rPolicy); + } + } } - } catch (Exception e) { - logger.error("Error while updating " + EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_NIFI_NAME + "service-def", e); + } } - } + RangerServiceDefValidator validator = validatorFactory.getServiceDefValidator(svcStore); + + validator.validate(dbNifiServiceDef, Action.UPDATE); + + RangerServiceDef ret = svcStore.updateServiceDef(dbNifiServiceDef); + + if (ret == null) { + logger.error("Error while updating {} service-def", EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_NIFI_NAME); + } + } + } catch (Exception e) { + logger.error("Error while updating {} service-def", EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_NIFI_NAME, e); + } + } } diff --git a/security-admin/src/main/java/org/apache/ranger/patch/PatchForOzoneDefaultPoliciesUpdate_J10044.java b/security-admin/src/main/java/org/apache/ranger/patch/PatchForOzoneDefaultPoliciesUpdate_J10044.java index 99a80caf8e..8b2e8a4c7d 100644 --- a/security-admin/src/main/java/org/apache/ranger/patch/PatchForOzoneDefaultPoliciesUpdate_J10044.java +++ b/security-admin/src/main/java/org/apache/ranger/patch/PatchForOzoneDefaultPoliciesUpdate_J10044.java @@ -37,89 +37,106 @@ @Component public class PatchForOzoneDefaultPoliciesUpdate_J10044 extends BaseLoader { - private static final Logger logger = LoggerFactory.getLogger(PatchForOzoneDefaultPoliciesUpdate_J10044.class); - public static final String ACCESS_TYPE_ALL = "all"; - - @Autowired - RangerDaoManager daoMgr; - - @Autowired - ServiceDBStore svcDBStore; - - public static void main(String[] args) { - logger.info("main()"); - try { - PatchForOzoneDefaultPoliciesUpdate_J10044 loader = (PatchForOzoneDefaultPoliciesUpdate_J10044) CLIUtil.getBean(PatchForOzoneDefaultPoliciesUpdate_J10044.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); - } - } - - @Override - public void printStats() { - logger.info("PatchForOzoneDefaultPoliciesUpdate data "); - } - - @Override - public void execLoad() { - logger.info("==> PatchForOzoneDefaultPoliciesUpdate.execLoad()"); - try { - if (!updateOzoneDefaultPolicies()) { - logger.error("Failed to apply the patch."); - System.exit(1); - } - } catch (Exception e) { - logger.error("Error while updateOzoneDefaultPolicies()data.", e); - System.exit(1); - } - logger.info("<== PatchForOzoneDefaultPoliciesUpdate.execLoad()"); - } - - @Override - public void init() throws Exception { - // Do Nothing - } - - private boolean updateOzoneDefaultPolicies() throws Exception { - RangerServiceDef embeddedOzoneServiceDef; - - embeddedOzoneServiceDef = EmbeddedServiceDefsUtil.instance().getEmbeddedServiceDef(EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_OZONE_NAME); - - if (embeddedOzoneServiceDef != null) { - List dbServices = daoMgr.getXXService().findByServiceDefId(embeddedOzoneServiceDef.getId()); - if (CollectionUtils.isNotEmpty(dbServices)) { - for(XXService dbService : dbServices) { - SearchFilter filter = new SearchFilter(); - filter.setParam(SearchFilter.SERVICE_NAME, dbService.getName()); - updateDefaultOzonePolicies(svcDBStore.getServicePolicies(dbService.getId(), filter)); - } - } - } else { - logger.error("The embedded Ozone service-definition does not exist."); - return false; - } - return true; - } - - private void updateDefaultOzonePolicies(List policies) throws Exception{ - if (CollectionUtils.isNotEmpty(policies)) { - for (RangerPolicy policy : policies) { - if (policy.getName().startsWith("all")) { - RangerPolicy.RangerPolicyItem policyItemOwner = new RangerPolicy.RangerPolicyItem(); - policyItemOwner.setUsers(Collections.singletonList(RangerPolicyEngine.RESOURCE_OWNER)); - policyItemOwner.setAccesses(Collections.singletonList(new RangerPolicy.RangerPolicyItemAccess(ACCESS_TYPE_ALL))); - policyItemOwner.setDelegateAdmin(true); - policy.addPolicyItem(policyItemOwner); - } - svcDBStore.updatePolicy(policy); - } - } - } + private static final Logger logger = LoggerFactory.getLogger(PatchForOzoneDefaultPoliciesUpdate_J10044.class); + + public static final String ACCESS_TYPE_ALL = "all"; + + @Autowired + RangerDaoManager daoMgr; + + @Autowired + ServiceDBStore svcDBStore; + + public static void main(String[] args) { + logger.info("main()"); + + try { + PatchForOzoneDefaultPoliciesUpdate_J10044 loader = (PatchForOzoneDefaultPoliciesUpdate_J10044) CLIUtil.getBean(PatchForOzoneDefaultPoliciesUpdate_J10044.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); + } + } + + @Override + public void init() throws Exception { + // Do Nothing + } + + @Override + public void printStats() { + logger.info("PatchForOzoneDefaultPoliciesUpdate data "); + } + + @Override + public void execLoad() { + logger.info("==> PatchForOzoneDefaultPoliciesUpdate.execLoad()"); + + try { + if (!updateOzoneDefaultPolicies()) { + logger.error("Failed to apply the patch."); + + System.exit(1); + } + } catch (Exception e) { + logger.error("Error while updateOzoneDefaultPolicies()data.", e); + + System.exit(1); + } + + logger.info("<== PatchForOzoneDefaultPoliciesUpdate.execLoad()"); + } + + private boolean updateOzoneDefaultPolicies() throws Exception { + RangerServiceDef embeddedOzoneServiceDef = EmbeddedServiceDefsUtil.instance().getEmbeddedServiceDef(EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_OZONE_NAME); + + if (embeddedOzoneServiceDef != null) { + List dbServices = daoMgr.getXXService().findByServiceDefId(embeddedOzoneServiceDef.getId()); + + if (CollectionUtils.isNotEmpty(dbServices)) { + for (XXService dbService : dbServices) { + SearchFilter filter = new SearchFilter(); + + filter.setParam(SearchFilter.SERVICE_NAME, dbService.getName()); + + updateDefaultOzonePolicies(svcDBStore.getServicePolicies(dbService.getId(), filter)); + } + } + } else { + logger.error("The embedded Ozone service-definition does not exist."); + + return false; + } + + return true; + } + + private void updateDefaultOzonePolicies(List policies) throws Exception { + if (CollectionUtils.isNotEmpty(policies)) { + for (RangerPolicy policy : policies) { + if (policy.getName().startsWith("all")) { + RangerPolicy.RangerPolicyItem policyItemOwner = new RangerPolicy.RangerPolicyItem(); + + policyItemOwner.setUsers(Collections.singletonList(RangerPolicyEngine.RESOURCE_OWNER)); + policyItemOwner.setAccesses(Collections.singletonList(new RangerPolicy.RangerPolicyItemAccess(ACCESS_TYPE_ALL))); + policyItemOwner.setDelegateAdmin(true); + + policy.addPolicyItem(policyItemOwner); + } + + svcDBStore.updatePolicy(policy); + } + } + } } diff --git a/security-admin/src/main/java/org/apache/ranger/patch/PatchForOzoneServiceDefConfigUpdate_J10051.java b/security-admin/src/main/java/org/apache/ranger/patch/PatchForOzoneServiceDefConfigUpdate_J10051.java index 3f08bc7617..c0fb990d83 100644 --- a/security-admin/src/main/java/org/apache/ranger/patch/PatchForOzoneServiceDefConfigUpdate_J10051.java +++ b/security-admin/src/main/java/org/apache/ranger/patch/PatchForOzoneServiceDefConfigUpdate_J10051.java @@ -44,183 +44,206 @@ @Component public class PatchForOzoneServiceDefConfigUpdate_J10051 extends BaseLoader { - private static final Logger logger = LoggerFactory.getLogger(PatchForOzoneServiceDefConfigUpdate_J10051.class); - - @Autowired - RangerDaoManager daoMgr; - - @Autowired - ServiceDBStore svcDBStore; - - @Autowired - JSONUtil jsonUtil; - - @Autowired - RangerPolicyService policyService; - - @Autowired - StringUtil stringUtil; - - @Autowired - XPolicyService xPolService; - - @Autowired - XPermMapService xPermMapService; - - @Autowired - RangerBizUtil bizUtil; - - @Autowired - RangerValidatorFactory validatorFactory; - - public static void main(String[] args) { - logger.info("main()"); - try { - PatchForOzoneServiceDefConfigUpdate_J10051 loader = (PatchForOzoneServiceDefConfigUpdate_J10051) CLIUtil.getBean(PatchForOzoneServiceDefConfigUpdate_J10051.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); - } - } - - @Override - public void printStats() { - logger.info("PatchForOzoneServiceDefConfigUpdate data "); - } - - @Override - public void execLoad() { - logger.info("==> PatchForOzoneServiceDefConfigUpdate.execLoad()"); - try { - if (!updateOzoneServiceDef()) { - logger.error("Failed to apply the patch."); - System.exit(1); - } - } catch (Exception e) { - logger.error("Error while updateOzoneServiceDef()data.", e); - System.exit(1); - } - logger.info("<== PatchForOzoneServiceDefConfigUpdate.execLoad()"); - } - - @Override - public void init() throws Exception { - // Do Nothing - } - - private boolean updateOzoneServiceDef() throws Exception { - RangerServiceDef ret; - RangerServiceDef embeddedOzoneServiceDef; - RangerServiceDef dbOzoneServiceDef; - List embeddedOzoneConfigDefs; - XXServiceDef xXServiceDefObj; - - embeddedOzoneServiceDef = EmbeddedServiceDefsUtil.instance().getEmbeddedServiceDef(EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_OZONE_NAME); - - if (embeddedOzoneServiceDef != null) { - xXServiceDefObj = daoMgr.getXXServiceDef().findByName(EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_OZONE_NAME); - Map serviceDefOptionsPreUpdate; - String jsonPreUpdate; - - if (xXServiceDefObj != null) { - jsonPreUpdate = xXServiceDefObj.getDefOptions(); - serviceDefOptionsPreUpdate = jsonStringToMap(jsonPreUpdate); - } else { - logger.error("Ozone service-definition does not exist in the Ranger DAO. No patching is needed!!"); - return true; - } - dbOzoneServiceDef = svcDBStore.getServiceDefByName(EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_OZONE_NAME); - - if (dbOzoneServiceDef != null) { - // Update old Ozone configs - embeddedOzoneConfigDefs = embeddedOzoneServiceDef.getConfigs(); - for (RangerServiceDef.RangerServiceConfigDef configDef : embeddedOzoneConfigDefs) { - if (StringUtils.equalsIgnoreCase(configDef.getName(), "hadoop.security.authorization")) { - configDef.setMandatory(false); - break; - } - } - dbOzoneServiceDef.setConfigs(embeddedOzoneConfigDefs); - } else { - logger.error("Ozone service-definition does not exist in the db store."); - return false; - } - RangerServiceDefValidator validator = validatorFactory.getServiceDefValidator(svcDBStore); - validator.validate(dbOzoneServiceDef, RangerValidator.Action.UPDATE); - - ret = svcDBStore.updateServiceDef(dbOzoneServiceDef); - if (ret == null) { - throw new RuntimeException("Error while updating " + EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_OZONE_NAME + " service-def"); - } - xXServiceDefObj = daoMgr.getXXServiceDef().findByName(EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_OZONE_NAME); - if (xXServiceDefObj != null) { - String jsonStrPostUpdate = xXServiceDefObj.getDefOptions(); - Map serviceDefOptionsPostUpdate = jsonStringToMap(jsonStrPostUpdate); - if (serviceDefOptionsPostUpdate != null && serviceDefOptionsPostUpdate.containsKey(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES)) { - if (serviceDefOptionsPreUpdate == null || !serviceDefOptionsPreUpdate.containsKey(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES)) { - String preUpdateValue = serviceDefOptionsPreUpdate == null ? null : serviceDefOptionsPreUpdate.get(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES); - if (preUpdateValue == null) { - serviceDefOptionsPostUpdate.remove(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES); - } else { - serviceDefOptionsPostUpdate.put(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES, preUpdateValue); - } - xXServiceDefObj.setDefOptions(mapToJsonString(serviceDefOptionsPostUpdate)); - daoMgr.getXXServiceDef().update(xXServiceDefObj); - } - } - } else { - logger.error("Ozone service-definition does not exist in the Ranger DAO."); - return false; - } - } else { - logger.error("The embedded Ozone service-definition does not exist."); - return false; - } - return true; - } - - private String mapToJsonString(Map map) { - String ret = null; - if (map != null) { - try { - ret = jsonUtil.readMapToString(map); - } catch (Exception ex) { - logger.warn("mapToJsonString() failed to convert map: " + map, ex); - } - } - return ret; - } - - protected Map jsonStringToMap(String jsonStr) { - Map ret = null; - if (!StringUtils.isEmpty(jsonStr)) { - try { - ret = jsonUtil.jsonToMap(jsonStr); - } catch (Exception ex) { - // fallback to earlier format: "name1=value1;name2=value2" - for (String optionString : jsonStr.split(";")) { - if (StringUtils.isEmpty(optionString)) { - continue; - } - String[] nvArr = optionString.split("="); - String name = (nvArr != null && nvArr.length > 0) ? nvArr[0].trim() : null; - String value = (nvArr != null && nvArr.length > 1) ? nvArr[1].trim() : null; - if (StringUtils.isEmpty(name)) { - continue; - } - if (ret == null) { - ret = new HashMap(); - } - ret.put(name, value); - } - } - } - return ret; - } + private static final Logger logger = LoggerFactory.getLogger(PatchForOzoneServiceDefConfigUpdate_J10051.class); + + @Autowired + RangerDaoManager daoMgr; + + @Autowired + ServiceDBStore svcDBStore; + + @Autowired + JSONUtil jsonUtil; + + @Autowired + RangerPolicyService policyService; + + @Autowired + StringUtil stringUtil; + + @Autowired + XPolicyService xPolService; + + @Autowired + XPermMapService xPermMapService; + + @Autowired + RangerBizUtil bizUtil; + + @Autowired + RangerValidatorFactory validatorFactory; + + public static void main(String[] args) { + logger.info("main()"); + + try { + PatchForOzoneServiceDefConfigUpdate_J10051 loader = (PatchForOzoneServiceDefConfigUpdate_J10051) CLIUtil.getBean(PatchForOzoneServiceDefConfigUpdate_J10051.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); + } + } + + @Override + public void init() throws Exception { + // Do Nothing + } + + @Override + public void printStats() { + logger.info("PatchForOzoneServiceDefConfigUpdate data "); + } + + @Override + public void execLoad() { + logger.info("==> PatchForOzoneServiceDefConfigUpdate.execLoad()"); + + try { + if (!updateOzoneServiceDef()) { + logger.error("Failed to apply the patch."); + + System.exit(1); + } + } catch (Exception e) { + logger.error("Error while updateOzoneServiceDef()data.", e); + + System.exit(1); + } + + logger.info("<== PatchForOzoneServiceDefConfigUpdate.execLoad()"); + } + + protected Map jsonStringToMap(String jsonStr) { + Map ret = null; + + if (!StringUtils.isEmpty(jsonStr)) { + try { + ret = jsonUtil.jsonToMap(jsonStr); + } catch (Exception ex) { + // fallback to earlier format: "name1=value1;name2=value2" + for (String optionString : jsonStr.split(";")) { + if (StringUtils.isEmpty(optionString)) { + continue; + } + + String[] nvArr = optionString.split("="); + String name = nvArr.length > 0 ? nvArr[0].trim() : null; + String value = nvArr.length > 1 ? nvArr[1].trim() : null; + + if (StringUtils.isEmpty(name)) { + continue; + } + + if (ret == null) { + ret = new HashMap<>(); + } + + ret.put(name, value); + } + } + } + return ret; + } + + private boolean updateOzoneServiceDef() throws Exception { + RangerServiceDef embeddedOzoneServiceDef = EmbeddedServiceDefsUtil.instance().getEmbeddedServiceDef(EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_OZONE_NAME); + + if (embeddedOzoneServiceDef != null) { + XXServiceDef xXServiceDefObj = daoMgr.getXXServiceDef().findByName(EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_OZONE_NAME); + + if (xXServiceDefObj == null) { + logger.error("Ozone service-definition does not exist in the Ranger DAO. No patching is needed!!"); + return true; + } + + String jsonPreUpdate = xXServiceDefObj.getDefOptions(); + Map serviceDefOptionsPreUpdate = jsonStringToMap(jsonPreUpdate); + RangerServiceDef dbOzoneServiceDef = svcDBStore.getServiceDefByName(EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_OZONE_NAME); + + if (dbOzoneServiceDef != null) { + // Update old Ozone configs + List embeddedOzoneConfigDefs = embeddedOzoneServiceDef.getConfigs(); + + for (RangerServiceDef.RangerServiceConfigDef configDef : embeddedOzoneConfigDefs) { + if (StringUtils.equalsIgnoreCase(configDef.getName(), "hadoop.security.authorization")) { + configDef.setMandatory(false); + break; + } + } + + dbOzoneServiceDef.setConfigs(embeddedOzoneConfigDefs); + } else { + logger.error("Ozone service-definition does not exist in the db store."); + + return false; + } + RangerServiceDefValidator validator = validatorFactory.getServiceDefValidator(svcDBStore); + + validator.validate(dbOzoneServiceDef, RangerValidator.Action.UPDATE); + + RangerServiceDef ret = svcDBStore.updateServiceDef(dbOzoneServiceDef); + + if (ret == null) { + throw new RuntimeException("Error while updating " + EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_OZONE_NAME + " service-def"); + } + + xXServiceDefObj = daoMgr.getXXServiceDef().findByName(EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_OZONE_NAME); + + if (xXServiceDefObj != null) { + String jsonStrPostUpdate = xXServiceDefObj.getDefOptions(); + Map serviceDefOptionsPostUpdate = jsonStringToMap(jsonStrPostUpdate); + + if (serviceDefOptionsPostUpdate != null && serviceDefOptionsPostUpdate.containsKey(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES)) { + if (serviceDefOptionsPreUpdate == null || !serviceDefOptionsPreUpdate.containsKey(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES)) { + String preUpdateValue = serviceDefOptionsPreUpdate == null ? null : serviceDefOptionsPreUpdate.get(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES); + + if (preUpdateValue == null) { + serviceDefOptionsPostUpdate.remove(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES); + } else { + serviceDefOptionsPostUpdate.put(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES, preUpdateValue); + } + + xXServiceDefObj.setDefOptions(mapToJsonString(serviceDefOptionsPostUpdate)); + + daoMgr.getXXServiceDef().update(xXServiceDefObj); + } + } + } else { + logger.error("Ozone service-definition does not exist in the Ranger DAO."); + + return false; + } + } else { + logger.error("The embedded Ozone service-definition does not exist."); + + return false; + } + + return true; + } + + private String mapToJsonString(Map map) { + String ret = null; + + if (map != null) { + try { + ret = jsonUtil.readMapToString(map); + } catch (Exception ex) { + logger.warn("mapToJsonString() failed to convert map: {}", map, ex); + } + } + + return ret; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/patch/PatchForOzoneServiceDefUpdate_J10041.java b/security-admin/src/main/java/org/apache/ranger/patch/PatchForOzoneServiceDefUpdate_J10041.java index 2e8f182129..b55b51c3c0 100644 --- a/security-admin/src/main/java/org/apache/ranger/patch/PatchForOzoneServiceDefUpdate_J10041.java +++ b/security-admin/src/main/java/org/apache/ranger/patch/PatchForOzoneServiceDefUpdate_J10041.java @@ -43,288 +43,324 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; -import java.util.List; import java.util.ArrayList; -import java.util.Map; import java.util.Arrays; import java.util.HashMap; +import java.util.List; +import java.util.Map; @Component public class PatchForOzoneServiceDefUpdate_J10041 extends BaseLoader { - private static final Logger logger = LoggerFactory.getLogger(PatchForOzoneServiceDefUpdate_J10041.class); - private static final List OZONE_CONFIGS = new ArrayList<>( - Arrays.asList("dfs.datanode.kerberos.principal", "dfs.namenode.kerberos.principal", "dfs.secondary.namenode.kerberos.principal", "commonNameForCertificate")); - private static final String OZONE_RESOURCE_VOLUME = "volume"; - private static final String OZONE_RESOURCE_KEY = "key"; - private static final String ACCESS_TYPE_READ_ACL = "read_acl"; - private static final String ACCESS_TYPE_WRITE_ACL = "write_acl"; - - @Autowired - RangerDaoManager daoMgr; - - @Autowired - ServiceDBStore svcDBStore; - - @Autowired - JSONUtil jsonUtil; - - @Autowired - RangerPolicyService policyService; - - @Autowired - StringUtil stringUtil; - - @Autowired - XPolicyService xPolService; - - @Autowired - XPermMapService xPermMapService; - - @Autowired - RangerBizUtil bizUtil; - - @Autowired - RangerValidatorFactory validatorFactory; - - public static void main(String[] args) { - logger.info("main()"); - try { - PatchForOzoneServiceDefUpdate_J10041 loader = (PatchForOzoneServiceDefUpdate_J10041) CLIUtil.getBean(PatchForOzoneServiceDefUpdate_J10041.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); - } - } - - @Override - public void printStats() { - logger.info("PatchForOzoneServiceDefUpdate data "); - } - - @Override - public void execLoad() { - logger.info("==> PatchForOzoneServiceDefUpdate.execLoad()"); - try { - if (!updateOzoneServiceDef()) { - logger.error("Failed to apply the patch."); - System.exit(1); - } - } catch (Exception e) { - logger.error("Error while updateOzoneServiceDef()data.", e); - System.exit(1); - } - logger.info("<== PatchForOzoneServiceDefUpdate.execLoad()"); - } - - @Override - public void init() throws Exception { - // Do Nothing - } - - private boolean updateOzoneServiceDef() throws Exception { - RangerServiceDef ret; - RangerServiceDef embeddedOzoneServiceDef; - RangerServiceDef dbOzoneServiceDef; - List embeddedOzoneConfigDefs; - List embeddedOzoneResourceDefs; - List embeddedOzoneAccessTypes; - XXServiceDef xXServiceDefObj; - - embeddedOzoneServiceDef = EmbeddedServiceDefsUtil.instance().getEmbeddedServiceDef(EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_OZONE_NAME); - - if (embeddedOzoneServiceDef != null) { - xXServiceDefObj = daoMgr.getXXServiceDef().findByName(EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_OZONE_NAME); - Map serviceDefOptionsPreUpdate; - String jsonPreUpdate; - - if (xXServiceDefObj != null) { - jsonPreUpdate = xXServiceDefObj.getDefOptions(); - serviceDefOptionsPreUpdate = jsonStringToMap(jsonPreUpdate); - } else { - logger.error("Ozone service-definition does not exist in the Ranger DAO. No patching is needed!!"); - return true; - } - dbOzoneServiceDef = svcDBStore.getServiceDefByName(EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_OZONE_NAME); - - if (dbOzoneServiceDef != null) { - // Remove old Ozone configs - embeddedOzoneConfigDefs = embeddedOzoneServiceDef.getConfigs(); - if (checkNotConfigPresent(embeddedOzoneConfigDefs)) { - dbOzoneServiceDef.setConfigs(embeddedOzoneConfigDefs); - } - - // Update volume resource with recursive flag false and key resource with recursive flag true - embeddedOzoneResourceDefs = embeddedOzoneServiceDef.getResources(); - if (checkVolKeyResUpdate(embeddedOzoneResourceDefs)) { - dbOzoneServiceDef.setResources(embeddedOzoneResourceDefs); - } - - // Add new access types - embeddedOzoneAccessTypes = embeddedOzoneServiceDef.getAccessTypes(); - - if (embeddedOzoneAccessTypes != null) { - if (checkAccessTypesPresent(embeddedOzoneAccessTypes)) { - if (!embeddedOzoneAccessTypes.toString().equalsIgnoreCase(dbOzoneServiceDef.getAccessTypes().toString())) { - dbOzoneServiceDef.setAccessTypes(embeddedOzoneAccessTypes); - } - } - } - } else { - logger.error("Ozone service-definition does not exist in the db store."); - return false; - } - RangerServiceDefValidator validator = validatorFactory.getServiceDefValidator(svcDBStore); - validator.validate(dbOzoneServiceDef, RangerValidator.Action.UPDATE); - - ret = svcDBStore.updateServiceDef(dbOzoneServiceDef); - if (ret == null) { - throw new RuntimeException("Error while updating " + EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_OZONE_NAME + " service-def"); - } - xXServiceDefObj = daoMgr.getXXServiceDef().findByName(EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_OZONE_NAME); - if (xXServiceDefObj != null) { - String jsonStrPostUpdate = xXServiceDefObj.getDefOptions(); - Map serviceDefOptionsPostUpdate = jsonStringToMap(jsonStrPostUpdate); - if (serviceDefOptionsPostUpdate != null && serviceDefOptionsPostUpdate.containsKey(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES)) { - if (serviceDefOptionsPreUpdate == null || !serviceDefOptionsPreUpdate.containsKey(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES)) { - String preUpdateValue = serviceDefOptionsPreUpdate == null ? null : serviceDefOptionsPreUpdate.get(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES); - if (preUpdateValue == null) { - serviceDefOptionsPostUpdate.remove(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES); - } else { - serviceDefOptionsPostUpdate.put(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES, preUpdateValue); - } - xXServiceDefObj.setDefOptions(mapToJsonString(serviceDefOptionsPostUpdate)); - daoMgr.getXXServiceDef().update(xXServiceDefObj); - } - } - } else { - logger.error("Ozone service-definition does not exist in the Ranger DAO."); - return false; - } - List dbServices = daoMgr.getXXService().findByServiceDefId(embeddedOzoneServiceDef.getId()); - if (CollectionUtils.isNotEmpty(dbServices)) { - for(XXService dbService : dbServices) { - SearchFilter filter = new SearchFilter(); - filter.setParam(SearchFilter.SERVICE_NAME, dbService.getName()); - updateExisitngOzonePolicies(svcDBStore.getServicePolicies(dbService.getId(), filter)); - } - } - } else { - logger.error("The embedded Ozone service-definition does not exist."); - return false; - } - return true; - } - - private boolean checkNotConfigPresent(List configDefs) { - boolean ret = false; - List configNames = new ArrayList<>(); - for (RangerServiceDef.RangerServiceConfigDef configDef : configDefs) { - configNames.add(configDef.getName()); - } - for (String delConfig : OZONE_CONFIGS) { - if (!configNames.contains(delConfig)) { - ret = true; - break; - } - } - return ret; - } - - private boolean checkVolKeyResUpdate(List embeddedOzoneResDefs) { - boolean ret = false; - for (RangerServiceDef.RangerResourceDef resDef : embeddedOzoneResDefs) { - if ((resDef.getName().equals(OZONE_RESOURCE_VOLUME) && (!resDef.getRecursiveSupported() || resDef.getExcludesSupported())) || - (resDef.getName().equals(OZONE_RESOURCE_KEY) && resDef.getRecursiveSupported())) { - ret = true; - break; - } - } - return ret; - } - - private boolean checkAccessTypesPresent(List embeddedOzoneAccessTypes) { - boolean ret = false; - for (RangerServiceDef.RangerAccessTypeDef accessDef : embeddedOzoneAccessTypes) { - if (ACCESS_TYPE_READ_ACL.equals(accessDef.getName()) || ACCESS_TYPE_WRITE_ACL.equals(accessDef.getName())) { - ret = true; - break; - } - } - return ret; - } - - private void updateExisitngOzonePolicies(List policies) throws Exception{ - if (CollectionUtils.isNotEmpty(policies)) { - for (RangerPolicy policy : policies) { - List policyItems = policy.getPolicyItems(); - if (CollectionUtils.isNotEmpty(policyItems)) { - for (RangerPolicy.RangerPolicyItem policyItem : policyItems) { - // Add new access types - policyItem.addAccess(new RangerPolicy.RangerPolicyItemAccess("read_acl")); - policyItem.addAccess(new RangerPolicy.RangerPolicyItemAccess("write_acl")); - } - } - Map policyResources = policy.getResources(); - if (MapUtils.isNotEmpty(policyResources)) { - if (policyResources.containsKey(OZONE_RESOURCE_VOLUME)) { - // Set recursive flag as false for volume resource - policyResources.get(OZONE_RESOURCE_VOLUME).setIsRecursive(false); - // Set exclude support flag as true for volume resource - policyResources.get(OZONE_RESOURCE_VOLUME).setIsExcludes(false); - } - if (policyResources.containsKey(OZONE_RESOURCE_KEY)) { - // Set is recursive flag as true for volume resource - policyResources.get(OZONE_RESOURCE_KEY).setIsRecursive(true); - } - } - svcDBStore.updatePolicy(policy); - } - } - } - - - private String mapToJsonString(Map map) { - String ret = null; - if (map != null) { - try { - ret = jsonUtil.readMapToString(map); - } catch (Exception ex) { - logger.warn("mapToJsonString() failed to convert map: " + map, ex); - } - } - return ret; - } - - protected Map jsonStringToMap(String jsonStr) { - Map ret = null; - if (!StringUtils.isEmpty(jsonStr)) { - try { - ret = jsonUtil.jsonToMap(jsonStr); - } catch (Exception ex) { - // fallback to earlier format: "name1=value1;name2=value2" - for (String optionString : jsonStr.split(";")) { - if (StringUtils.isEmpty(optionString)) { - continue; - } - String[] nvArr = optionString.split("="); - String name = (nvArr != null && nvArr.length > 0) ? nvArr[0].trim() : null; - String value = (nvArr != null && nvArr.length > 1) ? nvArr[1].trim() : null; - if (StringUtils.isEmpty(name)) { - continue; - } - if (ret == null) { - ret = new HashMap(); - } - ret.put(name, value); - } - } - } - return ret; - } + private static final Logger logger = LoggerFactory.getLogger(PatchForOzoneServiceDefUpdate_J10041.class); + + private static final List OZONE_CONFIGS = new ArrayList<>(Arrays.asList("dfs.datanode.kerberos.principal", "dfs.namenode.kerberos.principal", "dfs.secondary.namenode.kerberos.principal", "commonNameForCertificate")); + private static final String OZONE_RESOURCE_VOLUME = "volume"; + private static final String OZONE_RESOURCE_KEY = "key"; + private static final String ACCESS_TYPE_READ_ACL = "read_acl"; + private static final String ACCESS_TYPE_WRITE_ACL = "write_acl"; + + @Autowired + RangerDaoManager daoMgr; + + @Autowired + ServiceDBStore svcDBStore; + + @Autowired + JSONUtil jsonUtil; + + @Autowired + RangerPolicyService policyService; + + @Autowired + StringUtil stringUtil; + + @Autowired + XPolicyService xPolService; + + @Autowired + XPermMapService xPermMapService; + + @Autowired + RangerBizUtil bizUtil; + + @Autowired + RangerValidatorFactory validatorFactory; + + public static void main(String[] args) { + logger.info("main()"); + + try { + PatchForOzoneServiceDefUpdate_J10041 loader = (PatchForOzoneServiceDefUpdate_J10041) CLIUtil.getBean(PatchForOzoneServiceDefUpdate_J10041.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); + } + } + + @Override + public void init() throws Exception { + // Do Nothing + } + + @Override + public void printStats() { + logger.info("PatchForOzoneServiceDefUpdate data "); + } + + @Override + public void execLoad() { + logger.info("==> PatchForOzoneServiceDefUpdate.execLoad()"); + + try { + if (!updateOzoneServiceDef()) { + logger.error("Failed to apply the patch."); + + System.exit(1); + } + } catch (Exception e) { + logger.error("Error while updateOzoneServiceDef()data.", e); + + System.exit(1); + } + + logger.info("<== PatchForOzoneServiceDefUpdate.execLoad()"); + } + + protected Map jsonStringToMap(String jsonStr) { + Map ret = null; + + if (!StringUtils.isEmpty(jsonStr)) { + try { + ret = jsonUtil.jsonToMap(jsonStr); + } catch (Exception ex) { + // fallback to earlier format: "name1=value1;name2=value2" + for (String optionString : jsonStr.split(";")) { + if (StringUtils.isEmpty(optionString)) { + continue; + } + + String[] nvArr = optionString.split("="); + String name = nvArr.length > 0 ? nvArr[0].trim() : null; + String value = nvArr.length > 1 ? nvArr[1].trim() : null; + + if (StringUtils.isEmpty(name)) { + continue; + } + + if (ret == null) { + ret = new HashMap<>(); + } + + ret.put(name, value); + } + } + } + + return ret; + } + + private boolean updateOzoneServiceDef() throws Exception { + RangerServiceDef embeddedOzoneServiceDef = EmbeddedServiceDefsUtil.instance().getEmbeddedServiceDef(EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_OZONE_NAME); + + if (embeddedOzoneServiceDef != null) { + XXServiceDef xXServiceDefObj = daoMgr.getXXServiceDef().findByName(EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_OZONE_NAME); + + if (xXServiceDefObj == null) { + logger.error("Ozone service-definition does not exist in the Ranger DAO. No patching is needed!!"); + return true; + } + + String jsonPreUpdate = xXServiceDefObj.getDefOptions(); + Map serviceDefOptionsPreUpdate = jsonStringToMap(jsonPreUpdate); + RangerServiceDef dbOzoneServiceDef = svcDBStore.getServiceDefByName(EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_OZONE_NAME); + + if (dbOzoneServiceDef != null) { + // Remove old Ozone configs + List embeddedOzoneConfigDefs = embeddedOzoneServiceDef.getConfigs(); + + if (checkNotConfigPresent(embeddedOzoneConfigDefs)) { + dbOzoneServiceDef.setConfigs(embeddedOzoneConfigDefs); + } + + // Update volume resource with recursive flag false and key resource with recursive flag true + List embeddedOzoneResourceDefs = embeddedOzoneServiceDef.getResources(); + + if (checkVolKeyResUpdate(embeddedOzoneResourceDefs)) { + dbOzoneServiceDef.setResources(embeddedOzoneResourceDefs); + } + + // Add new access types + List embeddedOzoneAccessTypes = embeddedOzoneServiceDef.getAccessTypes(); + + if (embeddedOzoneAccessTypes != null) { + if (checkAccessTypesPresent(embeddedOzoneAccessTypes)) { + if (!embeddedOzoneAccessTypes.toString().equalsIgnoreCase(dbOzoneServiceDef.getAccessTypes().toString())) { + dbOzoneServiceDef.setAccessTypes(embeddedOzoneAccessTypes); + } + } + } + } else { + logger.error("Ozone service-definition does not exist in the db store."); + + return false; + } + + RangerServiceDefValidator validator = validatorFactory.getServiceDefValidator(svcDBStore); + + validator.validate(dbOzoneServiceDef, RangerValidator.Action.UPDATE); + + RangerServiceDef ret = svcDBStore.updateServiceDef(dbOzoneServiceDef); + + if (ret == null) { + throw new RuntimeException("Error while updating " + EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_OZONE_NAME + " service-def"); + } + + xXServiceDefObj = daoMgr.getXXServiceDef().findByName(EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_OZONE_NAME); + + if (xXServiceDefObj != null) { + String jsonStrPostUpdate = xXServiceDefObj.getDefOptions(); + Map serviceDefOptionsPostUpdate = jsonStringToMap(jsonStrPostUpdate); + + if (serviceDefOptionsPostUpdate != null && serviceDefOptionsPostUpdate.containsKey(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES)) { + if (serviceDefOptionsPreUpdate == null || !serviceDefOptionsPreUpdate.containsKey(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES)) { + String preUpdateValue = serviceDefOptionsPreUpdate == null ? null : serviceDefOptionsPreUpdate.get(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES); + + if (preUpdateValue == null) { + serviceDefOptionsPostUpdate.remove(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES); + } else { + serviceDefOptionsPostUpdate.put(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES, preUpdateValue); + } + + xXServiceDefObj.setDefOptions(mapToJsonString(serviceDefOptionsPostUpdate)); + + daoMgr.getXXServiceDef().update(xXServiceDefObj); + } + } + } else { + logger.error("Ozone service-definition does not exist in the Ranger DAO."); + + return false; + } + List dbServices = daoMgr.getXXService().findByServiceDefId(embeddedOzoneServiceDef.getId()); + + if (CollectionUtils.isNotEmpty(dbServices)) { + for (XXService dbService : dbServices) { + SearchFilter filter = new SearchFilter(); + + filter.setParam(SearchFilter.SERVICE_NAME, dbService.getName()); + + updateExisitngOzonePolicies(svcDBStore.getServicePolicies(dbService.getId(), filter)); + } + } + } else { + logger.error("The embedded Ozone service-definition does not exist."); + + return false; + } + + return true; + } + + private boolean checkNotConfigPresent(List configDefs) { + boolean ret = false; + List configNames = new ArrayList<>(); + + for (RangerServiceDef.RangerServiceConfigDef configDef : configDefs) { + configNames.add(configDef.getName()); + } + + for (String delConfig : OZONE_CONFIGS) { + if (!configNames.contains(delConfig)) { + ret = true; + break; + } + } + + return ret; + } + + private boolean checkVolKeyResUpdate(List embeddedOzoneResDefs) { + boolean ret = false; + + for (RangerServiceDef.RangerResourceDef resDef : embeddedOzoneResDefs) { + if ((resDef.getName().equals(OZONE_RESOURCE_VOLUME) && (!resDef.getRecursiveSupported() || resDef.getExcludesSupported())) || (resDef.getName().equals(OZONE_RESOURCE_KEY) && resDef.getRecursiveSupported())) { + ret = true; + break; + } + } + + return ret; + } + + private boolean checkAccessTypesPresent(List embeddedOzoneAccessTypes) { + boolean ret = false; + + for (RangerServiceDef.RangerAccessTypeDef accessDef : embeddedOzoneAccessTypes) { + if (ACCESS_TYPE_READ_ACL.equals(accessDef.getName()) || ACCESS_TYPE_WRITE_ACL.equals(accessDef.getName())) { + ret = true; + break; + } + } + + return ret; + } + + private void updateExisitngOzonePolicies(List policies) throws Exception { + if (CollectionUtils.isNotEmpty(policies)) { + for (RangerPolicy policy : policies) { + List policyItems = policy.getPolicyItems(); + + if (CollectionUtils.isNotEmpty(policyItems)) { + for (RangerPolicy.RangerPolicyItem policyItem : policyItems) { + // Add new access types + policyItem.addAccess(new RangerPolicy.RangerPolicyItemAccess("read_acl")); + policyItem.addAccess(new RangerPolicy.RangerPolicyItemAccess("write_acl")); + } + } + + Map policyResources = policy.getResources(); + + if (MapUtils.isNotEmpty(policyResources)) { + if (policyResources.containsKey(OZONE_RESOURCE_VOLUME)) { + // Set recursive flag as false for volume resource + policyResources.get(OZONE_RESOURCE_VOLUME).setIsRecursive(false); + // Set exclude support flag as true for volume resource + policyResources.get(OZONE_RESOURCE_VOLUME).setIsExcludes(false); + } + + if (policyResources.containsKey(OZONE_RESOURCE_KEY)) { + // Set is recursive flag as true for volume resource + policyResources.get(OZONE_RESOURCE_KEY).setIsRecursive(true); + } + } + + svcDBStore.updatePolicy(policy); + } + } + } + + private String mapToJsonString(Map map) { + String ret = null; + + if (map != null) { + try { + ret = jsonUtil.readMapToString(map); + } catch (Exception ex) { + logger.warn("mapToJsonString() failed to convert map: {}", map, ex); + } + } + + return ret; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/patch/PatchForPrestoToSupportPresto333_J10038.java b/security-admin/src/main/java/org/apache/ranger/patch/PatchForPrestoToSupportPresto333_J10038.java index 4247ed7af1..7d4c549723 100644 --- a/security-admin/src/main/java/org/apache/ranger/patch/PatchForPrestoToSupportPresto333_J10038.java +++ b/security-admin/src/main/java/org/apache/ranger/patch/PatchForPrestoToSupportPresto333_J10038.java @@ -43,139 +43,142 @@ @Component public class PatchForPrestoToSupportPresto333_J10038 extends BaseLoader { - private static final Logger logger = LoggerFactory.getLogger(PatchForPrestoToSupportPresto333_J10038.class); + private static final Logger logger = LoggerFactory.getLogger(PatchForPrestoToSupportPresto333_J10038.class); - private static final List PRESTO_RESOURCES = new ArrayList<>( - Arrays.asList("function", "procedure", "prestouser", "systemproperty", "sessionproperty")); + private static final List PRESTO_RESOURCES = new ArrayList<>(Arrays.asList("function", "procedure", "prestouser", "systemproperty", "sessionproperty")); - private static final List PRESTO_ACCESS_TYPES = new ArrayList<>( - Arrays.asList("grant", "revoke", "show", "impersonate", "execute", "delete")); + private static final List PRESTO_ACCESS_TYPES = new ArrayList<>(Arrays.asList("grant", "revoke", "show", "impersonate", "execute", "delete")); - @Autowired - RangerDaoManager daoMgr; + @Autowired + RangerDaoManager daoMgr; - @Autowired - ServiceDBStore svcDBStore; + @Autowired + ServiceDBStore svcDBStore; - @Autowired - GUIDUtil guidUtil; + @Autowired + GUIDUtil guidUtil; - @Autowired - JSONUtil jsonUtil; + @Autowired + JSONUtil jsonUtil; - @Autowired - StringUtil stringUtil; + @Autowired + StringUtil stringUtil; - @Autowired - RangerValidatorFactory validatorFactory; + @Autowired + RangerValidatorFactory validatorFactory; - @Autowired - ServiceDBStore svcStore; + @Autowired + ServiceDBStore svcStore; - @Autowired - RangerPolicyService policyService; + @Autowired + RangerPolicyService policyService; - public static void main(String[] args) { - logger.info("main()"); - try { - PatchForPrestoToSupportPresto333_J10038 loader = (PatchForPrestoToSupportPresto333_J10038) CLIUtil - .getBean(PatchForPrestoToSupportPresto333_J10038.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); + public static void main(String[] args) { + logger.info("main()"); + + try { + PatchForPrestoToSupportPresto333_J10038 loader = (PatchForPrestoToSupportPresto333_J10038) CLIUtil.getBean(PatchForPrestoToSupportPresto333_J10038.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); + } } - } - - @Override - public void init() throws Exception { - // Do Nothing - } - - @Override - public void execLoad() { - logger.info("==> PatchForPrestoToSupportPresto333.execLoad()"); - try { - addPresto333Support(); - } catch (Exception e) { - throw new RuntimeException( - "Error while updating " + EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_PRESTO_NAME + " service-def"); + + @Override + public void init() throws Exception { + // Do Nothing } - logger.info("<== PatchForPrestoToSupportPresto333.execLoad()"); - } - - @Override - public void printStats() { - logger.info("PatchForPrestoToSupportPresto333 Logs"); - } - - private void addPresto333Support() throws Exception { - RangerServiceDef ret = null; - RangerServiceDef embeddedPrestoServiceDef = null; - XXServiceDef xXServiceDefObj = null; - RangerServiceDef dbPrestoServiceDef = null; - List embeddedPrestoResourceDefs = null; - List embeddedPrestoAccessTypes = null; - - embeddedPrestoServiceDef = EmbeddedServiceDefsUtil.instance() - .getEmbeddedServiceDef(EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_PRESTO_NAME); - - if (embeddedPrestoServiceDef != null) { - xXServiceDefObj = daoMgr.getXXServiceDef() - .findByName(EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_PRESTO_NAME); - if (xXServiceDefObj == null) { - logger.info(xXServiceDefObj + ": service-def not found. No patching is needed"); - return; - } - - dbPrestoServiceDef = svcDBStore.getServiceDefByName(EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_PRESTO_NAME); - - embeddedPrestoResourceDefs = embeddedPrestoServiceDef.getResources(); - embeddedPrestoAccessTypes = embeddedPrestoServiceDef.getAccessTypes(); - if (checkResourcePresent(PRESTO_RESOURCES, embeddedPrestoResourceDefs)) { - dbPrestoServiceDef.setResources(embeddedPrestoResourceDefs); - if (checkAccessPresent(PRESTO_ACCESS_TYPES, embeddedPrestoAccessTypes)) { - dbPrestoServiceDef.setAccessTypes(embeddedPrestoAccessTypes); + + @Override + public void printStats() { + logger.info("PatchForPrestoToSupportPresto333 Logs"); + } + + @Override + public void execLoad() { + logger.info("==> PatchForPrestoToSupportPresto333.execLoad()"); + + try { + addPresto333Support(); + } catch (Exception e) { + throw new RuntimeException("Error while updating " + EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_PRESTO_NAME + " service-def"); } - } - - RangerServiceDefValidator validator = validatorFactory.getServiceDefValidator(svcStore); - validator.validate(dbPrestoServiceDef, RangerValidator.Action.UPDATE); - ret = svcStore.updateServiceDef(dbPrestoServiceDef); - if (ret == null) { - logger.error("Error while updating " + EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_PRESTO_NAME - + " service-def"); - throw new RuntimeException("Error while updating " - + EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_PRESTO_NAME + " service-def"); - } + logger.info("<== PatchForPrestoToSupportPresto333.execLoad()"); + } + + private void addPresto333Support() throws Exception { + RangerServiceDef embeddedPrestoServiceDef = EmbeddedServiceDefsUtil.instance().getEmbeddedServiceDef(EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_PRESTO_NAME); + + if (embeddedPrestoServiceDef != null) { + XXServiceDef xXServiceDefObj = daoMgr.getXXServiceDef().findByName(EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_PRESTO_NAME); + + if (xXServiceDefObj == null) { + logger.info("service-def not found. No patching is needed"); + + return; + } + + RangerServiceDef dbPrestoServiceDef = svcDBStore.getServiceDefByName(EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_PRESTO_NAME); + List embeddedPrestoResourceDefs = embeddedPrestoServiceDef.getResources(); + List embeddedPrestoAccessTypes = embeddedPrestoServiceDef.getAccessTypes(); + + if (checkResourcePresent(PRESTO_RESOURCES, embeddedPrestoResourceDefs)) { + dbPrestoServiceDef.setResources(embeddedPrestoResourceDefs); + + if (checkAccessPresent(PRESTO_ACCESS_TYPES, embeddedPrestoAccessTypes)) { + dbPrestoServiceDef.setAccessTypes(embeddedPrestoAccessTypes); + } + } + + RangerServiceDefValidator validator = validatorFactory.getServiceDefValidator(svcStore); + + validator.validate(dbPrestoServiceDef, RangerValidator.Action.UPDATE); + + RangerServiceDef ret = svcStore.updateServiceDef(dbPrestoServiceDef); + + if (ret == null) { + logger.error("Error while updating {} service-def", EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_PRESTO_NAME); + + throw new RuntimeException("Error while updating " + EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_PRESTO_NAME + " service-def"); + } + } } - } - - private boolean checkResourcePresent(List resources, List resourceDefs) { - boolean ret = false; - for (RangerServiceDef.RangerResourceDef resourceDef : resourceDefs) { - if (resources.contains(resourceDef.getName())) { - ret = true; - break; - } + + private boolean checkResourcePresent(List resources, List resourceDefs) { + boolean ret = false; + + for (RangerServiceDef.RangerResourceDef resourceDef : resourceDefs) { + if (resources.contains(resourceDef.getName())) { + ret = true; + break; + } + } + + return ret; } - return ret; - } - - private boolean checkAccessPresent(List accesses, List embeddedAtlasAccessTypes) { - boolean ret = false; - for (RangerServiceDef.RangerAccessTypeDef accessDef : embeddedAtlasAccessTypes) { - if (accesses.contains(accessDef.getName())) { - ret = true; - break; - } + + private boolean checkAccessPresent(List accesses, List embeddedAtlasAccessTypes) { + boolean ret = false; + + for (RangerServiceDef.RangerAccessTypeDef accessDef : embeddedAtlasAccessTypes) { + if (accesses.contains(accessDef.getName())) { + ret = true; + break; + } + } + + return ret; } - return ret; - } } diff --git a/security-admin/src/main/java/org/apache/ranger/patch/PatchForServiceVersionInfo_J10004.java b/security-admin/src/main/java/org/apache/ranger/patch/PatchForServiceVersionInfo_J10004.java index 9bd15b0fc6..a04915237c 100644 --- a/security-admin/src/main/java/org/apache/ranger/patch/PatchForServiceVersionInfo_J10004.java +++ b/security-admin/src/main/java/org/apache/ranger/patch/PatchForServiceVersionInfo_J10004.java @@ -17,107 +17,113 @@ package org.apache.ranger.patch; -import java.util.Date; -import java.util.List; import org.apache.ranger.db.RangerDaoManager; import org.apache.ranger.entity.XXService; import org.apache.ranger.entity.XXServiceVersionInfo; - import org.apache.ranger.util.CLIUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; +import java.util.Date; +import java.util.List; + @Component public class PatchForServiceVersionInfo_J10004 extends BaseLoader { - private static final Logger logger = LoggerFactory - .getLogger(PatchForServiceVersionInfo_J10004.class); - - @Autowired - RangerDaoManager daoManager; - - public static void main(String[] args) { - logger.info("main()"); - try { - PatchForServiceVersionInfo_J10004 loader = (PatchForServiceVersionInfo_J10004) CLIUtil - .getBean(PatchForServiceVersionInfo_J10004.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); - } - } - - @Override - public void init() throws Exception { - // Do Nothing - } - - @Override - public void execLoad() { - logger.info("==> ServiceVersionInfoPatch.execLoad()"); - copyVersionsFromServiceToServiceVersionInfo(); - logger.info("<== ServiceVersionInfoPatch.execLoad()"); - } - - public void copyVersionsFromServiceToServiceVersionInfo() { - List allServices = daoManager.getXXService().getAll(); - Date now = new Date(); - - for (XXService xService : allServices) { - - boolean needToCreateServiceVersionInfo = false; - XXServiceVersionInfo serviceVersionInfoDbObj = daoManager.getXXServiceVersionInfo().findByServiceId(xService.getId()); - - if (serviceVersionInfoDbObj == null) { - needToCreateServiceVersionInfo = true; - serviceVersionInfoDbObj = new XXServiceVersionInfo(); - serviceVersionInfoDbObj.setServiceId(xService.getId()); - } - serviceVersionInfoDbObj.setPolicyVersion(xService.getPolicyVersion() == null ? 1L : xService.getPolicyVersion()); - serviceVersionInfoDbObj.setTagVersion(xService.getTagVersion()); - serviceVersionInfoDbObj.setPolicyUpdateTime(xService.getPolicyUpdateTime()); - serviceVersionInfoDbObj.setTagUpdateTime(xService.getTagUpdateTime()); - - if (needToCreateServiceVersionInfo) { - daoManager.getXXServiceVersionInfo().create(serviceVersionInfoDbObj); - logger.info("Created serviceVesionInfo for serviceName [" + xService.getName() + "]"); - } else { - daoManager.getXXServiceVersionInfo().update(serviceVersionInfoDbObj); - logger.info("Updated serviceVesionInfo for serviceName [" + xService.getName() + "]"); - } - - // Consider this scenario: - // 1. ranger-admin is upgraded to use versions from x_service_version_info table; - // 2. there are updates to policies and/or tags; - // 3. no plug-ins download service-policies; - // 4. upgrade is rolled back, for ranger-admin to use versions from x_service table; - // 5. Now plug-in downloads service-policies. - // In this scenario, plug-ins will miss the policy/tag updates down in step 2. To ensure that - // plug-ins get updated policies/tags, we increment versions in x_service table when x_service_version_info - // table is updated in this patch. This may cause one potentially unnecessary download to plugin in case - // step 2 above did not take place, but it is safer. - - xService.setPolicyVersion(xService.getPolicyVersion() == null ? 2L : xService.getPolicyVersion() + 1); - xService.setTagVersion(xService.getTagVersion() + 1); - - xService.setPolicyUpdateTime(now); - xService.setTagUpdateTime(now); - - daoManager.getXXService().update(xService); - logger.info("Incremented policy and tag versions for serviceName [" + xService.getName() + "]"); - } - } - - @Override - public void printStats() { - } + private static final Logger logger = LoggerFactory.getLogger(PatchForServiceVersionInfo_J10004.class); + + @Autowired + RangerDaoManager daoManager; + + public static void main(String[] args) { + logger.info("main()"); + try { + PatchForServiceVersionInfo_J10004 loader = (PatchForServiceVersionInfo_J10004) CLIUtil.getBean(PatchForServiceVersionInfo_J10004.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); + } + } + + @Override + public void init() throws Exception { + // Do Nothing + } + + @Override + public void printStats() { + } + + @Override + public void execLoad() { + logger.info("==> ServiceVersionInfoPatch.execLoad()"); + + copyVersionsFromServiceToServiceVersionInfo(); + + logger.info("<== ServiceVersionInfoPatch.execLoad()"); + } + + public void copyVersionsFromServiceToServiceVersionInfo() { + List allServices = daoManager.getXXService().getAll(); + Date now = new Date(); + + for (XXService xService : allServices) { + boolean needToCreateServiceVersionInfo = false; + XXServiceVersionInfo serviceVersionInfoDbObj = daoManager.getXXServiceVersionInfo().findByServiceId(xService.getId()); + + if (serviceVersionInfoDbObj == null) { + needToCreateServiceVersionInfo = true; + serviceVersionInfoDbObj = new XXServiceVersionInfo(); + + serviceVersionInfoDbObj.setServiceId(xService.getId()); + } + + serviceVersionInfoDbObj.setPolicyVersion(xService.getPolicyVersion() == null ? 1L : xService.getPolicyVersion()); + serviceVersionInfoDbObj.setTagVersion(xService.getTagVersion()); + serviceVersionInfoDbObj.setPolicyUpdateTime(xService.getPolicyUpdateTime()); + serviceVersionInfoDbObj.setTagUpdateTime(xService.getTagUpdateTime()); + + if (needToCreateServiceVersionInfo) { + daoManager.getXXServiceVersionInfo().create(serviceVersionInfoDbObj); + + logger.info("Created serviceVesionInfo for serviceName [{}]", xService.getName()); + } else { + daoManager.getXXServiceVersionInfo().update(serviceVersionInfoDbObj); + + logger.info("Updated serviceVesionInfo for serviceName [{}]", xService.getName()); + } + + // Consider this scenario: + // 1. ranger-admin is upgraded to use versions from x_service_version_info table; + // 2. there are updates to policies and/or tags; + // 3. no plug-ins download service-policies; + // 4. upgrade is rolled back, for ranger-admin to use versions from x_service table; + // 5. Now plug-in downloads service-policies. + // In this scenario, plug-ins will miss the policy/tag updates down in step 2. To ensure that + // plug-ins get updated policies/tags, we increment versions in x_service table when x_service_version_info + // table is updated in this patch. This may cause one potentially unnecessary download to plugin in case + // step 2 above did not take place, but it is safer. + + xService.setPolicyVersion(xService.getPolicyVersion() == null ? 2L : xService.getPolicyVersion() + 1); + xService.setTagVersion(xService.getTagVersion() + 1); + xService.setPolicyUpdateTime(now); + xService.setTagUpdateTime(now); + + daoManager.getXXService().update(xService); + logger.info("Incremented policy and tag versions for serviceName [{}]", xService.getName()); + } + } } diff --git a/security-admin/src/main/java/org/apache/ranger/patch/PatchForSolrSvcDefAndPoliciesUpdate_J10055.java b/security-admin/src/main/java/org/apache/ranger/patch/PatchForSolrSvcDefAndPoliciesUpdate_J10055.java index e6c6954a40..9d9fd9cdd5 100644 --- a/security-admin/src/main/java/org/apache/ranger/patch/PatchForSolrSvcDefAndPoliciesUpdate_J10055.java +++ b/security-admin/src/main/java/org/apache/ranger/patch/PatchForSolrSvcDefAndPoliciesUpdate_J10055.java @@ -18,14 +18,6 @@ */ package org.apache.ranger.patch; -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.commons.collections.CollectionUtils; import org.apache.commons.collections.MapUtils; import org.apache.commons.lang.StringUtils; @@ -60,35 +52,42 @@ 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 java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + @Component public class PatchForSolrSvcDefAndPoliciesUpdate_J10055 extends BaseLoader { - private static final Logger logger = LoggerFactory.getLogger(PatchForSolrSvcDefAndPoliciesUpdate_J10055.class); + private static final Logger logger = LoggerFactory.getLogger(PatchForSolrSvcDefAndPoliciesUpdate_J10055.class); + private static final String ACCESS_TYPE_UPDATE = "update"; private static final String ACCESS_TYPE_QUERY = "query"; private static final String ACCESS_TYPE_ADMIN = "solr_admin"; private static final String ACCESS_TYPE_OTHERS = "others"; //TAG type solr:permissions - private static final String ACCESS_TYPE_UPDATE_TAG = "solr:update"; - private static final String ACCESS_TYPE_QUERY_TAG = "solr:query"; - private static final String ACCESS_TYPE_ADMIN_TAG = "solr:solr_admin"; - private static final String ACCESS_TYPE_OTHERS_TAG = "solr:others"; - private enum NEW_RESOURCE { admin, config, schema } - + private static final String ACCESS_TYPE_UPDATE_TAG = "solr:update"; + private static final String ACCESS_TYPE_QUERY_TAG = "solr:query"; + private static final String ACCESS_TYPE_ADMIN_TAG = "solr:solr_admin"; + private static final String ACCESS_TYPE_OTHERS_TAG = "solr:others"; private static final String SVC_ACCESS_TYPE_CONFIG_SUFFIX = "accessTypes"; + private static final String SOLR_SVC_DEF_NAME = EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_SOLR_NAME; - private static final String SOLR_SVC_DEF_NAME = EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_SOLR_NAME; - private static RangerServiceDef embeddedSolrServiceDef = null; + @Autowired + ServiceDBStore svcDBStore; @Autowired - private RangerDaoManager daoMgr; + @Qualifier(value = "transactionManager") + PlatformTransactionManager txManager; @Autowired - ServiceDBStore svcDBStore; + private RangerDaoManager daoMgr; @Autowired private SecurityZoneDBStore secZoneDBStore; @@ -96,22 +95,24 @@ private enum NEW_RESOURCE { admin, config, schema } @Autowired private RangerValidatorFactory validatorFactory; - @Autowired - @Qualifier(value = "transactionManager") - PlatformTransactionManager txManager; - public static void main(String[] args) { logger.info("main()"); + try { PatchForSolrSvcDefAndPoliciesUpdate_J10055 loader = (PatchForSolrSvcDefAndPoliciesUpdate_J10055) CLIUtil.getBean(PatchForSolrSvcDefAndPoliciesUpdate_J10055.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); } } @@ -129,304 +130,354 @@ public void printStats() { @Override public void execLoad() { logger.info("==> PatchForSolrSvcDefAndPoliciesUpdate_J10055.execLoad()"); + try { - embeddedSolrServiceDef = EmbeddedServiceDefsUtil.instance().getEmbeddedServiceDef(SOLR_SVC_DEF_NAME); - if(embeddedSolrServiceDef == null) { + RangerServiceDef embeddedSolrServiceDef = EmbeddedServiceDefsUtil.instance().getEmbeddedServiceDef(SOLR_SVC_DEF_NAME); + + if (embeddedSolrServiceDef == null) { logger.error("The embedded Solr service-definition does not exist."); + System.exit(1); } - TransactionTemplate txTemplate = new TransactionTemplate(txManager); - txTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); - try { - txTemplate.execute(new TransactionCallback() { - @Override - public Object doInTransaction(TransactionStatus status) { - if (updateSolrSvcDef() == null) { - throw new RuntimeException("Error while updating " + SOLR_SVC_DEF_NAME + " service-def"); - } - return null; - } - }); - } catch (Throwable ex) { - logger.error("Error while updating " + SOLR_SVC_DEF_NAME + " service-def"); - throw new RuntimeException("Error while updating " + SOLR_SVC_DEF_NAME + " service-def"); - } - - final Long resTypeSvcDefId = embeddedSolrServiceDef.getId(); - final Long tagSvcDefId = EmbeddedServiceDefsUtil.instance().getTagServiceDefId(); - updateExistingRangerResPolicy(resTypeSvcDefId); - updateExistingRangerTagPolicies(tagSvcDefId); - - deleteOldAccessTypeRefs(resTypeSvcDefId); - deleteOldAccessTypeRefs(tagSvcDefId); + TransactionTemplate txTemplate = new TransactionTemplate(txManager); + + txTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + + try { + txTemplate.execute(status -> { + if (updateSolrSvcDef() == null) { + throw new RuntimeException("Error while updating " + SOLR_SVC_DEF_NAME + " service-def"); + } + + return null; + }); + } catch (Throwable ex) { + logger.error("Error while updating {} service-def", SOLR_SVC_DEF_NAME); + + throw new RuntimeException("Error while updating " + SOLR_SVC_DEF_NAME + " service-def"); + } + + final Long resTypeSvcDefId = embeddedSolrServiceDef.getId(); + final Long tagSvcDefId = EmbeddedServiceDefsUtil.instance().getTagServiceDefId(); + + updateExistingRangerResPolicy(resTypeSvcDefId); + updateExistingRangerTagPolicies(tagSvcDefId); + + deleteOldAccessTypeRefs(resTypeSvcDefId); + deleteOldAccessTypeRefs(tagSvcDefId); } catch (Exception e) { - logger.error("Error whille executing PatchForSolrSvcDefAndPoliciesUpdate_J10055, Error - ", e); + logger.error("Error while executing PatchForSolrSvcDefAndPoliciesUpdate_J10055, Error - ", e); + + System.exit(1); + } + + try { + // For RANGER-3725 - Update atlas default audit filter + updateDefaultAuditFilter(EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_ATLAS_NAME); + } catch (Throwable t) { + logger.error("Failed to update atlas default audit filter - ", t); + System.exit(1); } - try { - // For RANGER-3725 - Update atlas default audit filter - updateDefaultAuditFilter(EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_ATLAS_NAME); - } catch (Throwable t) { - logger.error("Failed to update atlas default audit filter - ", t); - System.exit(1); - } + logger.info("<== PatchForSolrSvcDefAndPoliciesUpdate_J10055.execLoad()"); + } + + private void updateExistingRangerResPolicy(Long svcDefId) throws Exception { + logger.info("<== PatchForSolrSvcDefAndPoliciesUpdate_J10055.updateExistingRangerResPolicy(...)"); + + List dbServices = daoMgr.getXXService().findByServiceDefId(svcDefId); + + if (CollectionUtils.isNotEmpty(dbServices)) { + for (XXService dbService : dbServices) { + SearchFilter filter = new SearchFilter(); + + filter.setParam(SearchFilter.SERVICE_NAME, dbService.getName()); + filter.setParam(SearchFilter.FETCH_ZONE_UNZONE_POLICIES, "true"); + + updateResPolicies(svcDBStore.getServicePolicies(dbService.getId(), filter)); + updateZoneResourceMapping(dbService); + updateServiceConfig(dbService); + } + } + logger.info("<== PatchForSolrSvcDefAndPoliciesUpdate_J10055.updateExistingRangerResPolicy(...)"); + } + + private void updateZoneResourceMapping(final XXService solrDBSvc) throws Exception { + logger.info("==> PatchForSolrSvcDefAndPoliciesUpdate_J10055.updateZoneResourceMapping(...)"); + + // Update Zone Resource Mapping For Solr Services + final String svcName = solrDBSvc.getName(); + SearchFilter filter = new SearchFilter(); + + filter.setParam(SearchFilter.SERVICE_NAME, svcName); + + List secZoneList = this.secZoneDBStore.getSecurityZones(filter); + long index = 1; + + for (RangerSecurityZone secZone : secZoneList) { + logger.info("updateZoneResourceMapping() processing: [{}/{}]", index, secZoneList.size()); + + TransactionTemplate txTemplate = new TransactionTemplate(txManager); + + txTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + + try { + txTemplate.execute(status -> { + try { + updateZone(secZone, svcName); + } catch (Exception e) { + throw new RuntimeException(e); + } + + return null; + }); + } catch (Throwable ex) { + logger.error("updateZoneResourceMapping(): Failed to update zone: {}", secZone.getName(), ex); + throw new RuntimeException(ex); + } + + index++; + } + + logger.info("<== PatchForSolrSvcDefAndPoliciesUpdate_J10055.updateZoneResourceMapping(...)"); + } + + private void updateZone(RangerSecurityZone secZone, String svcName) throws Exception { + RangerSecurityZoneService secZoneSvc = secZone.getServices().get(svcName); // get secZoneSvc only for this svcName + List>> solrZoneSvcResourcesMapList = secZoneSvc.getResources(); + final Set>> updatedResMapSet = new HashSet<>(); + + for (HashMap> existingResMap : solrZoneSvcResourcesMapList) { + boolean isAllResource = false; + + for (Map.Entry> resNameValueListMap : existingResMap.entrySet()) { + updatedResMapSet.add(existingResMap); + + final List resourceValueList = resNameValueListMap.getValue(); + + if (CollectionUtils.isNotEmpty(resourceValueList) && resourceValueList.contains("*")) { + updatedResMapSet.clear(); + updatedResMapSet.add(existingResMap); + + isAllResource = true; + break; + } else { + HashMap> updatedResMap = new HashMap<>(); + + updatedResMap.put(NEW_RESOURCE.schema.name(), resourceValueList); + + updatedResMapSet.add(updatedResMap); + } + } + + if (isAllResource) { + final List allResVal = Collections.singletonList("*"); + + for (NEW_RESOURCE newRes : NEW_RESOURCE.values()) { + HashMap> updatedResMap = new HashMap<>(); + + updatedResMap.put(newRes.name(), allResVal); + + updatedResMapSet.add(updatedResMap); + } + + secZoneSvc.setResources(new ArrayList<>(updatedResMapSet)); + break; + } + + secZoneSvc.setResources(new ArrayList<>(updatedResMapSet)); + } + + this.secZoneDBStore.updateSecurityZoneById(secZone); + } + + private void updateExistingRangerTagPolicies(Long svcDefId) throws Exception { + List dbServices = daoMgr.getXXService().findByServiceDefId(svcDefId); + + if (CollectionUtils.isNotEmpty(dbServices)) { + for (XXService dbService : dbServices) { + SearchFilter filter = new SearchFilter(); + + filter.setParam(SearchFilter.SERVICE_NAME, dbService.getName()); + + updateTagPolicies(svcDBStore.getServicePolicies(dbService.getId(), filter)); + } + } + } + + private void updateTagPolicies(List tagServicePolicies) { + if (CollectionUtils.isNotEmpty(tagServicePolicies)) { + long index = 1; + + for (RangerPolicy exPolicy : tagServicePolicies) { + logger.info("updateTagPolicies() processing: [{}/{}]", index, tagServicePolicies.size()); + + TransactionTemplate txTemplate = new TransactionTemplate(txManager); + + txTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + + try { + txTemplate.execute(status -> { + updateTagPolicyItemAccess(exPolicy.getPolicyItems()); + updateTagPolicyItemAccess(exPolicy.getAllowExceptions()); + updateTagPolicyItemAccess(exPolicy.getDenyPolicyItems()); + updateTagPolicyItemAccess(exPolicy.getDenyExceptions()); + + try { + svcDBStore.updatePolicy(exPolicy); + } catch (Exception e) { + throw new RuntimeException(e); + } + + return null; + }); + } catch (Throwable ex) { + logger.error("updateTagPolicies(): Failed to update policy:{}", exPolicy.getName(), ex); + + throw new RuntimeException(ex); + } + + index++; + } + } + } + + private void updateResPolicies(List policies) { + if (CollectionUtils.isNotEmpty(policies)) { + long index = 1; + + for (RangerPolicy exPolicy : policies) { + logger.info("updateResPolicies() processing: [{}/{}]", index, policies.size()); + + TransactionTemplate txTemplate = new TransactionTemplate(txManager); + + txTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); - logger.info("<== PatchForSolrSvcDefAndPoliciesUpdate_J10055.execLoad()"); + try { + txTemplate.execute(status -> { + createOrUpdatePolicy(exPolicy); + + return null; + }); + } catch (Throwable ex) { + logger.error("updateResPolicies(): Failed to create/update policy:{}", exPolicy.getName(), ex); + + throw new RuntimeException(ex); + } + + index++; + } + } } - private void updateExistingRangerResPolicy(Long svcDefId) throws Exception { - logger.info("<== PatchForSolrSvcDefAndPoliciesUpdate_J10055.updateExistingRangerResPolicy(...)"); - List dbServices = daoMgr.getXXService().findByServiceDefId(svcDefId); - if (CollectionUtils.isNotEmpty(dbServices)) { - for (XXService dbService : dbServices) { - SearchFilter filter = new SearchFilter(); - filter.setParam(SearchFilter.SERVICE_NAME, dbService.getName()); - filter.setParam(SearchFilter.FETCH_ZONE_UNZONE_POLICIES, "true"); - updateResPolicies(svcDBStore.getServicePolicies(dbService.getId(), filter)); - updateZoneResourceMapping(dbService); - updateServiceConfig(dbService); - } - } - logger.info("<== PatchForSolrSvcDefAndPoliciesUpdate_J10055.updateExistingRangerResPolicy(...)"); - } - - private void updateZoneResourceMapping(final XXService solrDBSvc) throws Exception { - logger.info("==> PatchForSolrSvcDefAndPoliciesUpdate_J10055.updateZoneResourceMapping(...)"); - // Update Zone Resource Mapping For Solr Services - final String svcName = solrDBSvc.getName(); - SearchFilter filter = new SearchFilter(); - filter.setParam(SearchFilter.SERVICE_NAME, svcName); - List secZoneList = this.secZoneDBStore.getSecurityZones(filter); - long index = 1; - for (RangerSecurityZone secZone : secZoneList) { - logger.info("updateZoneResourceMapping() processing: [" + index + "/" + secZoneList.size() + "]"); - TransactionTemplate txTemplate = new TransactionTemplate(txManager); - txTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); - try { - txTemplate.execute(new TransactionCallback() { - @Override - public Object doInTransaction(TransactionStatus status) { - try { - updateZone(secZone, svcName); - } catch (Exception e) { - throw new RuntimeException(e); - } - return null; - } - }); - } catch (Throwable ex) { - logger.error("updateZoneResourceMapping(): Failed to update zone: " + secZone.getName() + " ", ex); - throw new RuntimeException(ex); - } - index++; - } - logger.info("<== PatchForSolrSvcDefAndPoliciesUpdate_J10055.updateZoneResourceMapping(...)"); - } - - private void updateZone(RangerSecurityZone secZone, String svcName) throws Exception { - RangerSecurityZoneService secZoneSvc = secZone.getServices().get(svcName);// get secZoneSvc only for this svcName - List>> solrZoneSvcResourcesMapList = secZoneSvc.getResources(); - - final Set>> updatedResMapSet = new HashSet>>(); - for (HashMap> existingResMap : solrZoneSvcResourcesMapList) { - boolean isAllResource = false; // * - for (Map.Entry> resNameValueListMap : existingResMap.entrySet()) { - - updatedResMapSet.add(existingResMap); - final List resourceValueList = resNameValueListMap.getValue(); - - if (CollectionUtils.isNotEmpty(resourceValueList) && resourceValueList.indexOf("*") >= 0) { - updatedResMapSet.clear(); - updatedResMapSet.add(existingResMap); - isAllResource = true; - break; - } else { - HashMap> updatedResMap = new HashMap>(); - updatedResMap.put(NEW_RESOURCE.schema.name(), resourceValueList); - updatedResMapSet.add(updatedResMap); - } - } - - if (isAllResource) { - final List allResVal = Arrays.asList("*"); - for (NEW_RESOURCE newRes : NEW_RESOURCE.values()) { - HashMap> updatedResMap = new HashMap>(); - updatedResMap.put(newRes.name(), allResVal); - updatedResMapSet.add(updatedResMap); - } - secZoneSvc.setResources(new ArrayList>>(updatedResMapSet)); - break; - } - secZoneSvc.setResources(new ArrayList>>(updatedResMapSet)); - } - this.secZoneDBStore.updateSecurityZoneById(secZone); - } - - private void updateExistingRangerTagPolicies(Long svcDefId) throws Exception { - List dbServices = daoMgr.getXXService().findByServiceDefId(svcDefId); - if (CollectionUtils.isNotEmpty(dbServices)) { - for (XXService dbService : dbServices) { - SearchFilter filter = new SearchFilter(); - filter.setParam(SearchFilter.SERVICE_NAME, dbService.getName()); - updateTagPolicies(svcDBStore.getServicePolicies(dbService.getId(), filter)); - } - } - } - - private void updateTagPolicies(List tagServicePolicies) { - if (CollectionUtils.isNotEmpty(tagServicePolicies)) { - long index = 1; - for (RangerPolicy exPolicy : tagServicePolicies) { - logger.info("updateTagPolicies() processing: [" + index + "/" + tagServicePolicies.size() + "]"); - TransactionTemplate txTemplate = new TransactionTemplate(txManager); - txTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); - try { - txTemplate.execute(new TransactionCallback() { - @Override - public Object doInTransaction(TransactionStatus status) { - updateTagPolicyItemAccess(exPolicy.getPolicyItems()); - updateTagPolicyItemAccess(exPolicy.getAllowExceptions()); - updateTagPolicyItemAccess(exPolicy.getDenyPolicyItems()); - updateTagPolicyItemAccess(exPolicy.getDenyExceptions()); - try { - svcDBStore.updatePolicy(exPolicy); - } catch (Exception e) { - throw new RuntimeException(e); - } - return null; - } - }); - } catch (Throwable ex) { - logger.error("updateTagPolicies(): Failed to update policy: " + exPolicy.getName() + " ", ex); - throw new RuntimeException(ex); - } - index++; - } - } - } - - private void updateResPolicies(List policies) { - if (CollectionUtils.isNotEmpty(policies)) { - long index = 1; - for (RangerPolicy exPolicy : policies) { - logger.info("updateResPolicies() processing: [" + index + "/" + policies.size() + "]"); - TransactionTemplate txTemplate = new TransactionTemplate(txManager); - txTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); - try { - txTemplate.execute(new TransactionCallback() { - @Override - public Object doInTransaction(TransactionStatus status) { - createOrUpdatePolicy(exPolicy); - return null; - } - }); - } catch (Throwable ex) { - logger.error("updateResPolicies(): Failed to create/update policy: " + exPolicy.getName() + " ", ex); - throw new RuntimeException(ex); - } - index++; - } - } - } - - private void createOrUpdatePolicy(RangerPolicy exPolicy) { - // Filter policy items which are eligible for admin,config and schema resources - final List filteredAllowPolciyItems = filterPolicyItemsForAdminPermission(exPolicy.getPolicyItems()); - final List filteredAllowExcpPolItems = filterPolicyItemsForAdminPermission(exPolicy.getAllowExceptions()); - final List filteredDenyPolItems = filterPolicyItemsForAdminPermission(exPolicy.getDenyPolicyItems()); - final List filteredDenyExcpPolItems = filterPolicyItemsForAdminPermission(exPolicy.getDenyExceptions()); - - // check if there is a need to create additional policies with - // admin/config/schema resource(s) - final boolean splitPolicy = (filteredAllowPolciyItems.size() > 0 || filteredAllowExcpPolItems.size() > 0 || filteredDenyPolItems.size() > 0 || filteredDenyExcpPolItems.size() > 0); - if (splitPolicy) { - RangerPolicy newPolicyForNewResource = new RangerPolicy(); - newPolicyForNewResource.setService(exPolicy.getService()); - newPolicyForNewResource.setServiceType(exPolicy.getServiceType()); - newPolicyForNewResource.setPolicyPriority(exPolicy.getPolicyPriority()); - - RangerPolicyResource newRes = new RangerPolicyResource(); - boolean isAllResources = false; - // Only one entry expected - for (Map.Entry entry : exPolicy.getResources().entrySet()) { - RangerPolicyResource exPolRes = entry.getValue(); - newRes.setIsExcludes(exPolRes.getIsExcludes()); - newRes.setIsRecursive(exPolRes.getIsRecursive()); - newRes.setValues(exPolRes.getValues()); - if (CollectionUtils.isNotEmpty(exPolRes.getValues()) && exPolRes.getValues().indexOf("*") >= 0) { - isAllResources = true; - } - } - - newPolicyForNewResource.setPolicyItems(filteredAllowPolciyItems); - newPolicyForNewResource.setAllowExceptions(filteredAllowExcpPolItems); - newPolicyForNewResource.setDenyPolicyItems(filteredDenyPolItems); - newPolicyForNewResource.setDenyExceptions(filteredDenyExcpPolItems); - newPolicyForNewResource.setOptions(exPolicy.getOptions()); - newPolicyForNewResource.setValiditySchedules(exPolicy.getValiditySchedules()); - newPolicyForNewResource.setPolicyLabels(exPolicy.getPolicyLabels()); - newPolicyForNewResource.setConditions(exPolicy.getConditions()); - newPolicyForNewResource.setIsDenyAllElse(exPolicy.getIsDenyAllElse()); - newPolicyForNewResource.setZoneName(exPolicy.getZoneName()); - newPolicyForNewResource.setIsEnabled(exPolicy.getIsEnabled()); - newPolicyForNewResource.setIsAuditEnabled(exPolicy.getIsAuditEnabled()); - newPolicyForNewResource.setPolicyType(exPolicy.getPolicyType()); - - try { - if (isAllResources) { - for (NEW_RESOURCE resType : NEW_RESOURCE.values()) { - createNewPolicy(resType.name(), newPolicyForNewResource, newRes, exPolicy.getName()); - } - } else { - createNewPolicy(NEW_RESOURCE.schema.name(), newPolicyForNewResource, newRes, exPolicy.getName()); - } - - } catch (Exception e) { - throw new RuntimeException(e); - } - } - try { - // update policy items - updateResPolicyItemAccess(exPolicy.getPolicyItems()); - updateResPolicyItemAccess(exPolicy.getAllowExceptions()); - updateResPolicyItemAccess(exPolicy.getDenyPolicyItems()); - updateResPolicyItemAccess(exPolicy.getDenyExceptions()); - this.svcDBStore.updatePolicy(exPolicy); - } catch (Exception e) { - throw new RuntimeException(e); - } - } + private void createOrUpdatePolicy(RangerPolicy exPolicy) { + // Filter policy items which are eligible for admin,config and schema resources + final List filteredAllowPolciyItems = filterPolicyItemsForAdminPermission(exPolicy.getPolicyItems()); + final List filteredAllowExcpPolItems = filterPolicyItemsForAdminPermission(exPolicy.getAllowExceptions()); + final List filteredDenyPolItems = filterPolicyItemsForAdminPermission(exPolicy.getDenyPolicyItems()); + final List filteredDenyExcpPolItems = filterPolicyItemsForAdminPermission(exPolicy.getDenyExceptions()); + + // check if there is a need to create additional policies with + // admin/config/schema resource(s) + final boolean splitPolicy = (!filteredAllowPolciyItems.isEmpty() || !filteredAllowExcpPolItems.isEmpty() || !filteredDenyPolItems.isEmpty() || !filteredDenyExcpPolItems.isEmpty()); + + if (splitPolicy) { + RangerPolicy newPolicyForNewResource = new RangerPolicy(); + + newPolicyForNewResource.setService(exPolicy.getService()); + newPolicyForNewResource.setServiceType(exPolicy.getServiceType()); + newPolicyForNewResource.setPolicyPriority(exPolicy.getPolicyPriority()); + + RangerPolicyResource newRes = new RangerPolicyResource(); + boolean isAllResources = false; + + // Only one entry expected + for (Map.Entry entry : exPolicy.getResources().entrySet()) { + RangerPolicyResource exPolRes = entry.getValue(); + + newRes.setIsExcludes(exPolRes.getIsExcludes()); + newRes.setIsRecursive(exPolRes.getIsRecursive()); + newRes.setValues(exPolRes.getValues()); + + if (CollectionUtils.isNotEmpty(exPolRes.getValues()) && exPolRes.getValues().contains("*")) { + isAllResources = true; + } + } + + newPolicyForNewResource.setPolicyItems(filteredAllowPolciyItems); + newPolicyForNewResource.setAllowExceptions(filteredAllowExcpPolItems); + newPolicyForNewResource.setDenyPolicyItems(filteredDenyPolItems); + newPolicyForNewResource.setDenyExceptions(filteredDenyExcpPolItems); + newPolicyForNewResource.setOptions(exPolicy.getOptions()); + newPolicyForNewResource.setValiditySchedules(exPolicy.getValiditySchedules()); + newPolicyForNewResource.setPolicyLabels(exPolicy.getPolicyLabels()); + newPolicyForNewResource.setConditions(exPolicy.getConditions()); + newPolicyForNewResource.setIsDenyAllElse(exPolicy.getIsDenyAllElse()); + newPolicyForNewResource.setZoneName(exPolicy.getZoneName()); + newPolicyForNewResource.setIsEnabled(exPolicy.getIsEnabled()); + newPolicyForNewResource.setIsAuditEnabled(exPolicy.getIsAuditEnabled()); + newPolicyForNewResource.setPolicyType(exPolicy.getPolicyType()); + + try { + if (isAllResources) { + for (NEW_RESOURCE resType : NEW_RESOURCE.values()) { + createNewPolicy(resType.name(), newPolicyForNewResource, newRes, exPolicy.getName()); + } + } else { + createNewPolicy(NEW_RESOURCE.schema.name(), newPolicyForNewResource, newRes, exPolicy.getName()); + } + } catch (Exception e) { + throw new RuntimeException(e); + } + } + try { + // update policy items + updateResPolicyItemAccess(exPolicy.getPolicyItems()); + updateResPolicyItemAccess(exPolicy.getAllowExceptions()); + updateResPolicyItemAccess(exPolicy.getDenyPolicyItems()); + updateResPolicyItemAccess(exPolicy.getDenyExceptions()); + + this.svcDBStore.updatePolicy(exPolicy); + } catch (Exception e) { + throw new RuntimeException(e); + } + } private void createNewPolicy(final String resType, final RangerPolicy newPolicy, final RangerPolicyResource newRes, final String exPolicyName) throws Exception { final String newPolicyName = resType + " - '" + exPolicyName + "'"; + newPolicy.setName(newPolicyName); newPolicy.setDescription(newPolicyName); - final Map resForNewPol = new HashMap(); + final Map resForNewPol = new HashMap<>(); + resForNewPol.put(resType, newRes); + newPolicy.setResources(resForNewPol); newPolicy.setResourceSignature(null); newPolicy.setGuid(null); - if (logger.isDebugEnabled()) { - logger.debug("newPolicy:"+newPolicy); - } + + logger.debug("newPolicy:{}", newPolicy); + this.svcDBStore.createPolicy(newPolicy); } private void updateResPolicyItemAccess(List policyItems) { - Set newRangerPolicyItemAccess = new HashSet(); if (CollectionUtils.isNotEmpty(policyItems)) { for (RangerPolicyItem exPolicyItem : policyItems) { if (exPolicyItem != null) { List exPolicyItemAccessList = exPolicyItem.getAccesses(); + if (CollectionUtils.isNotEmpty(exPolicyItemAccessList)) { - newRangerPolicyItemAccess = new HashSet(); + Set newRangerPolicyItemAccess = new HashSet<>(); + for (RangerPolicyItemAccess aPolicyItemAccess : exPolicyItemAccessList) { if (aPolicyItemAccess != null) { final String accessType = aPolicyItemAccess.getType(); final Boolean isAllowed = aPolicyItemAccess.getIsAllowed(); + if (ACCESS_TYPE_ADMIN.equalsIgnoreCase(accessType)) { newRangerPolicyItemAccess.add(new RangerPolicyItemAccess(ACCESS_TYPE_QUERY, isAllowed)); newRangerPolicyItemAccess.add(new RangerPolicyItemAccess(ACCESS_TYPE_UPDATE, isAllowed)); @@ -440,7 +491,8 @@ private void updateResPolicyItemAccess(List policyItems) { } } } - exPolicyItem.setAccesses(new ArrayList(newRangerPolicyItemAccess)); + + exPolicyItem.setAccesses(new ArrayList<>(newRangerPolicyItemAccess)); } } } @@ -448,18 +500,21 @@ private void updateResPolicyItemAccess(List policyItems) { } private void updateTagPolicyItemAccess(List policyItems) { - List newPolicyItems = new ArrayList(); - Set newRangerPolicyItemAccess = new HashSet(); + List newPolicyItems = new ArrayList<>(); + if (CollectionUtils.isNotEmpty(policyItems)) { for (RangerPolicyItem exPolicyItem : policyItems) { if (exPolicyItem != null) { List exPolicyItemAccessList = exPolicyItem.getAccesses(); + if (CollectionUtils.isNotEmpty(exPolicyItemAccessList)) { - newRangerPolicyItemAccess = new HashSet(); + Set newRangerPolicyItemAccess = new HashSet<>(); + for (RangerPolicyItemAccess aPolicyItemAccess : exPolicyItemAccessList) { if (aPolicyItemAccess != null) { final String accessType = aPolicyItemAccess.getType(); final Boolean isAllowed = aPolicyItemAccess.getIsAllowed(); + if (ACCESS_TYPE_ADMIN_TAG.equalsIgnoreCase(accessType)) { newRangerPolicyItemAccess.add(new RangerPolicyItemAccess(ACCESS_TYPE_QUERY_TAG, isAllowed)); newRangerPolicyItemAccess.add(new RangerPolicyItemAccess(ACCESS_TYPE_UPDATE_TAG, isAllowed)); @@ -474,7 +529,9 @@ private void updateTagPolicyItemAccess(List policyItems) { } } } - exPolicyItem.setAccesses(new ArrayList(newRangerPolicyItemAccess)); + + exPolicyItem.setAccesses(new ArrayList<>(newRangerPolicyItemAccess)); + newPolicyItems.add(exPolicyItem); } } @@ -484,141 +541,167 @@ private void updateTagPolicyItemAccess(List policyItems) { private List filterPolicyItemsForAdminPermission(List policyItems) { // Add only those policy items who's access permission list contains 'solr_admin' permission - List filteredPolicyItems = new ArrayList(); - Set newRangerPolicyItemAccess = new HashSet(); + List filteredPolicyItems = new ArrayList<>(); + Set newRangerPolicyItemAccess = new HashSet<>(); + policyItems.forEach(exPolicyItem -> exPolicyItem.getAccesses().forEach(polItemAcc -> { if (ACCESS_TYPE_ADMIN.equalsIgnoreCase(polItemAcc.getType())) { newRangerPolicyItemAccess.add(new RangerPolicyItemAccess(ACCESS_TYPE_QUERY, polItemAcc.getIsAllowed())); newRangerPolicyItemAccess.add(new RangerPolicyItemAccess(ACCESS_TYPE_UPDATE, polItemAcc.getIsAllowed())); - RangerPolicyItem newPolicyItem = new RangerPolicyItem(new ArrayList(newRangerPolicyItemAccess), exPolicyItem.getUsers(), exPolicyItem.getGroups(), - exPolicyItem.getRoles(), exPolicyItem.getConditions(), exPolicyItem.getDelegateAdmin()); + + RangerPolicyItem newPolicyItem = new RangerPolicyItem(new ArrayList<>(newRangerPolicyItemAccess), exPolicyItem.getUsers(), exPolicyItem.getGroups(), exPolicyItem.getRoles(), exPolicyItem.getConditions(), exPolicyItem.getDelegateAdmin()); + filteredPolicyItems.add(newPolicyItem); } })); + return filteredPolicyItems; } private RangerServiceDef updateSolrSvcDef() { logger.info("==> PatchForSolrSvcDefAndPoliciesUpdate_J10055.updateSolrSvcDef()"); - RangerServiceDef ret = null; - RangerServiceDef embeddedSolrServiceDef = null; - XXServiceDef xXServiceDefObj = null; - RangerServiceDef dbSolrServiceDef = null; - List embeddedSolrResourceDefs = null; + + RangerServiceDef ret = null; + try { - embeddedSolrServiceDef = EmbeddedServiceDefsUtil.instance().getEmbeddedServiceDef(SOLR_SVC_DEF_NAME); + RangerServiceDef embeddedSolrServiceDef = EmbeddedServiceDefsUtil.instance().getEmbeddedServiceDef(SOLR_SVC_DEF_NAME); + if (embeddedSolrServiceDef != null) { - xXServiceDefObj = daoMgr.getXXServiceDef().findByName(SOLR_SVC_DEF_NAME); + XXServiceDef xXServiceDefObj = daoMgr.getXXServiceDef().findByName(SOLR_SVC_DEF_NAME); + if (xXServiceDefObj == null) { - logger.info(xXServiceDefObj + ": service-def not found. No patching is needed"); + logger.info(" service-def not found. No patching is needed"); + System.exit(0); } - embeddedSolrResourceDefs = embeddedSolrServiceDef.getResources(); // ResourcesType - dbSolrServiceDef = this.svcDBStore.getServiceDefByName(SOLR_SVC_DEF_NAME); + List embeddedSolrResourceDefs = embeddedSolrServiceDef.getResources(); // ResourcesType + RangerServiceDef dbSolrServiceDef = this.svcDBStore.getServiceDefByName(SOLR_SVC_DEF_NAME); + dbSolrServiceDef.setResources(embeddedSolrResourceDefs); RangerServiceDefValidator validator = validatorFactory.getServiceDefValidator(this.svcDBStore); + validator.validate(dbSolrServiceDef, Action.UPDATE); + ret = this.svcDBStore.updateServiceDef(dbSolrServiceDef); } } catch (Exception e) { - logger.error("Error while updating " + SOLR_SVC_DEF_NAME + " service-def", e); + logger.error("Error while updating {} service-def", SOLR_SVC_DEF_NAME, e); + throw new RuntimeException(e); } + logger.info("<== PatchForSolrSvcDefAndPoliciesUpdate_J10055.updateSolrSvcDef()"); + return ret; } private void deleteOldAccessTypeRefs(Long svcDefId) { - logger.info("==> PatchForSolrSvcDefAndPoliciesUpdate_J10055.deleteOldAccessTypeRefs(" + svcDefId + ")"); + logger.info("==> PatchForSolrSvcDefAndPoliciesUpdate_J10055.deleteOldAccessTypeRefs({})", svcDefId); List solrAccessDefTypes = daoMgr.getXXAccessTypeDef().findByServiceDefId(svcDefId); XXAccessTypeDefDao accessTypeDefDao = daoMgr.getXXAccessTypeDef(); XXAccessTypeDefGrantsDao xxAccessTypeDefGrantsDao = daoMgr.getXXAccessTypeDefGrants(); + for (XXAccessTypeDef xXAccessTypeDef : solrAccessDefTypes) { if (xXAccessTypeDef != null) { final String accessTypeName = xXAccessTypeDef.getName(); final Long id = xXAccessTypeDef.getId(); // atd_id in x_access_type_def_grants tbl + // remove solr_admin refs from implied grants refs tbl for (XXAccessTypeDefGrants xXAccessTypeDefGrants : xxAccessTypeDefGrantsDao.findByATDId(id)) { if (xXAccessTypeDefGrants != null) { xxAccessTypeDefGrantsDao.remove(xXAccessTypeDefGrants.getId()); } } + // remove no longer supported accessTyeDef's (others,solr_admin, solr:others, solr:solr_admin) - if (ACCESS_TYPE_ADMIN.equalsIgnoreCase(accessTypeName) || ACCESS_TYPE_OTHERS.equalsIgnoreCase(accessTypeName) || ACCESS_TYPE_OTHERS_TAG.equalsIgnoreCase(accessTypeName) - || ACCESS_TYPE_ADMIN_TAG.equalsIgnoreCase(accessTypeName)) { + if (ACCESS_TYPE_ADMIN.equalsIgnoreCase(accessTypeName) || ACCESS_TYPE_OTHERS.equalsIgnoreCase(accessTypeName) || ACCESS_TYPE_OTHERS_TAG.equalsIgnoreCase(accessTypeName) || ACCESS_TYPE_ADMIN_TAG.equalsIgnoreCase(accessTypeName)) { accessTypeDefDao.remove(xXAccessTypeDef.getId()); } } } - logger.info("<== PatchForSolrSvcDefAndPoliciesUpdate_J10055.deleteOldAccessTypeRefs(" + svcDefId + ")"); + + logger.info("<== PatchForSolrSvcDefAndPoliciesUpdate_J10055.deleteOldAccessTypeRefs({})", svcDefId); + } + + private void updateServiceConfig(final XXService dbService) throws Exception { + logger.info("==> PatchForSolrSvcDefAndPoliciesUpdate_J10055.updateServiceConfig()"); + + final RangerService rangerSvc = this.svcDBStore.getService(dbService.getId()); + final Map configMap = rangerSvc != null ? rangerSvc.getConfigs() : null; + + if (MapUtils.isNotEmpty(configMap)) { + for (final Map.Entry entry : configMap.entrySet()) { + final String configKey = entry.getKey(); + final String configValue = entry.getValue(); + Set accessTypeSet = new HashSet<>(); + + if (StringUtils.endsWith(configKey, SVC_ACCESS_TYPE_CONFIG_SUFFIX) && StringUtils.isNotEmpty(configValue)) { + final String[] accessTypeArray = configValue.split(","); + + for (String access : accessTypeArray) { + if (!ACCESS_TYPE_OTHERS.equalsIgnoreCase(access) && !ACCESS_TYPE_ADMIN.equalsIgnoreCase(access)) { + accessTypeSet.add(access); + } else { + if (ACCESS_TYPE_ADMIN.equalsIgnoreCase(access)) { + accessTypeSet.add(ACCESS_TYPE_QUERY); + accessTypeSet.add(ACCESS_TYPE_UPDATE); + } else if (ACCESS_TYPE_OTHERS.equalsIgnoreCase(access)) { + accessTypeSet.add(ACCESS_TYPE_QUERY); + } + } + } + + configMap.put(configKey, StringUtils.join(accessTypeSet, ",")); + } + } + + rangerSvc.setConfigs(configMap); + + this.svcDBStore.updateService(rangerSvc, null); + } + + logger.info("<== PatchForSolrSvcDefAndPoliciesUpdate_J10055.updateServiceConfig()"); + } + + private void updateDefaultAuditFilter(final String svcDefName) throws Exception { + logger.info("==> PatchForSolrSvcDefAndPoliciesUpdate_J10055.updateAtlasDefaultAuditFilter()"); + + final RangerServiceDef embeddedAtlasServiceDef = EmbeddedServiceDefsUtil.instance().getEmbeddedServiceDef(svcDefName); + final List embdSvcConfDefList = embeddedAtlasServiceDef != null ? embeddedAtlasServiceDef.getConfigs() : new ArrayList<>(); + String embdAuditFilterStr = StringUtils.EMPTY; + + if (CollectionUtils.isNotEmpty(embdSvcConfDefList)) { + for (RangerServiceConfigDef embdSvcConfDef : embdSvcConfDefList) { + if (StringUtils.equals(embdSvcConfDef.getName(), ServiceDBStore.RANGER_PLUGIN_AUDIT_FILTERS)) { + embdAuditFilterStr = embdSvcConfDef.getDefaultValue(); // new audit filter str + break; + } + } + } + + if (StringUtils.isNotEmpty(embdAuditFilterStr)) { + final RangerServiceDef serviceDbDef = this.svcDBStore.getServiceDefByName(svcDefName); + + for (RangerServiceConfigDef dbSvcDefConfig : serviceDbDef.getConfigs()) { + if (dbSvcDefConfig != null && StringUtils.equals(dbSvcDefConfig.getName(), ServiceDBStore.RANGER_PLUGIN_AUDIT_FILTERS)) { + final String dbAuditFilterStr = dbSvcDefConfig.getDefaultValue(); + + if (!StringUtils.equalsIgnoreCase(dbAuditFilterStr, embdAuditFilterStr)) { + dbSvcDefConfig.setDefaultValue(embdAuditFilterStr); + + this.svcDBStore.updateServiceDef(serviceDbDef); + + logger.info("Updated {} service default audit filter.", serviceDbDef.getName()); + } + break; + } + } + } + + logger.info("<== PatchForSolrSvcDefAndPoliciesUpdate_J10055.updateAtlasDefaultAuditFilter()"); } - private void updateServiceConfig(final XXService dbService) throws Exception { - logger.info("==> PatchForSolrSvcDefAndPoliciesUpdate_J10055.updateServiceConfig()"); - final RangerService rangerSvc = this.svcDBStore.getService(dbService.getId()); - final Map configMap = rangerSvc != null ? rangerSvc.getConfigs() : null; - Set accessTypeSet = new HashSet(); - - if (MapUtils.isNotEmpty(configMap)) { - for (final Map.Entry entry : configMap.entrySet()) { - final String configKey = entry.getKey(); - final String configValue = entry.getValue(); - accessTypeSet = new HashSet(); - if (StringUtils.endsWith(configKey, SVC_ACCESS_TYPE_CONFIG_SUFFIX) && StringUtils.isNotEmpty(configValue)) { - final String[] accessTypeArray = configValue.split(","); - for (String access : accessTypeArray) { - if (!ACCESS_TYPE_OTHERS.equalsIgnoreCase(access) && !ACCESS_TYPE_ADMIN.equalsIgnoreCase(access)) { - accessTypeSet.add(access); - } else { - if (ACCESS_TYPE_ADMIN.equalsIgnoreCase(access)) { - accessTypeSet.add(ACCESS_TYPE_QUERY); - accessTypeSet.add(ACCESS_TYPE_UPDATE); - } else if (ACCESS_TYPE_OTHERS.equalsIgnoreCase(access)) { - accessTypeSet.add(ACCESS_TYPE_QUERY); - } - } - } - configMap.put(configKey, StringUtils.join(accessTypeSet, ",")); - } - } - rangerSvc.setConfigs(configMap); - this.svcDBStore.updateService(rangerSvc, null); - } - logger.info("<== PatchForSolrSvcDefAndPoliciesUpdate_J10055.updateServiceConfig()"); - } - - private void updateDefaultAuditFilter(final String svcDefName) throws Exception { - logger.info("==> PatchForSolrSvcDefAndPoliciesUpdate_J10055.updateAtlasDefaultAuditFilter()"); - final RangerServiceDef embeddedAtlasServiceDef = EmbeddedServiceDefsUtil.instance() - .getEmbeddedServiceDef(svcDefName); - final List embdSvcConfDefList = embeddedAtlasServiceDef != null ? embeddedAtlasServiceDef.getConfigs() : new ArrayList(); - String embdAuditFilterStr = StringUtils.EMPTY; - - if (CollectionUtils.isNotEmpty(embdSvcConfDefList)) { - for (RangerServiceConfigDef embdSvcConfDef : embdSvcConfDefList) { - if (StringUtils.equals(embdSvcConfDef.getName(), ServiceDBStore.RANGER_PLUGIN_AUDIT_FILTERS)) { - embdAuditFilterStr = embdSvcConfDef.getDefaultValue(); // new audit filter str - break; - } - } - } - - if (StringUtils.isNotEmpty(embdAuditFilterStr)) { - final RangerServiceDef serviceDbDef = this.svcDBStore.getServiceDefByName(svcDefName); - for (RangerServiceConfigDef dbSvcDefConfig : serviceDbDef.getConfigs()) { - if (dbSvcDefConfig != null && StringUtils.equals(dbSvcDefConfig.getName(), ServiceDBStore.RANGER_PLUGIN_AUDIT_FILTERS)) { - final String dbAuditFilterStr = dbSvcDefConfig.getDefaultValue(); - if (!StringUtils.equalsIgnoreCase(dbAuditFilterStr, embdAuditFilterStr)) { - dbSvcDefConfig.setDefaultValue(embdAuditFilterStr); - this.svcDBStore.updateServiceDef(serviceDbDef); - logger.info("Updated " + serviceDbDef.getName() + " service default audit filter."); - } - break; - } - } - } - logger.info("<== PatchForSolrSvcDefAndPoliciesUpdate_J10055.updateAtlasDefaultAuditFilter()"); - } -} \ No newline at end of file + private enum NEW_RESOURCE { admin, config, schema} +} diff --git a/security-admin/src/main/java/org/apache/ranger/patch/PatchForSyncSourceUpdate_J10054.java b/security-admin/src/main/java/org/apache/ranger/patch/PatchForSyncSourceUpdate_J10054.java index df29a57ff0..2697ce86f0 100644 --- a/security-admin/src/main/java/org/apache/ranger/patch/PatchForSyncSourceUpdate_J10054.java +++ b/security-admin/src/main/java/org/apache/ranger/patch/PatchForSyncSourceUpdate_J10054.java @@ -32,15 +32,14 @@ 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 java.util.List; import java.util.Map; @Component -public class PatchForSyncSourceUpdate_J10054 extends BaseLoader{ +public class PatchForSyncSourceUpdate_J10054 extends BaseLoader { + private static final Logger logger = LoggerFactory.getLogger(PatchForSyncSourceUpdate_J10054.class); @Autowired RangerDaoManager daoManager; @@ -49,130 +48,146 @@ public class PatchForSyncSourceUpdate_J10054 extends BaseLoader{ @Qualifier(value = "transactionManager") PlatformTransactionManager txManager; - private static final Logger logger = LoggerFactory.getLogger(PatchForSyncSourceUpdate_J10054.class); + public static void main(String[] args) { + logger.info("main()"); + + try { + PatchForSyncSourceUpdate_J10054 loader = (PatchForSyncSourceUpdate_J10054) CLIUtil.getBean(PatchForSyncSourceUpdate_J10054.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); + } + } @Override public void init() throws Exception {/* Do Nothing */} + @Override + public void printStats() { + logger.info("PatchForSyncSourceUpdate data"); + } + @Override public void execLoad() { logger.info("==> PatchForSyncSourceUpdate.execLoad()"); + try { if (!updateSyncSourceForUsers() || !updateSyncSourceForGroups()) { logger.error("Failed to apply the patch."); + System.exit(1); } } catch (Exception e) { logger.error("Error while PatchForSyncSourceUpdate()data.", e); - System.exit(1); - } - logger.info("<== PatchForSyncSourceUpdate.execLoad()"); - } - - @Override - public void printStats() { logger.info("PatchForSyncSourceUpdate data"); } - public static void main(String[] args) { - logger.info("main()"); - try { - PatchForSyncSourceUpdate_J10054 loader = (PatchForSyncSourceUpdate_J10054) CLIUtil.getBean(PatchForSyncSourceUpdate_J10054.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); } + + logger.info("<== PatchForSyncSourceUpdate.execLoad()"); } - public boolean updateSyncSourceForUsers(){ + public boolean updateSyncSourceForUsers() { List users = daoManager.getXXUser().getAll(); - for( XXUser xUser: users) { + + for (XXUser xUser : users) { String syncSource = xUser.getSyncSource(); String otherAttributes = xUser.getOtherAttributes(); - if (StringUtils.isNotEmpty(otherAttributes) && StringUtils.isEmpty(syncSource)){ + + if (StringUtils.isNotEmpty(otherAttributes) && StringUtils.isEmpty(syncSource)) { syncSource = (String) JsonUtils.jsonToObject(otherAttributes, Map.class).get(UgsyncCommonConstants.SYNC_SOURCE); + xUser.setSyncSource(syncSource); TransactionTemplate txTemplate = new TransactionTemplate(txManager); + txTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); String finalSyncSource = syncSource; + try { - txTemplate.execute(new TransactionCallback() { - @Override - public Object doInTransaction(TransactionStatus status) { - if (StringUtils.isNotEmpty(finalSyncSource)) { - XXPortalUser xXPortalUser = daoManager.getXXPortalUser().findByLoginId(xUser.getName()); - if (xXPortalUser != null && xXPortalUser.getUserSource() == 0){ - /* updating the user source to external for users which had some sync source prior to upgrade - but the user source was marked internal to due bugs which were fixed later. - See RANGER-3297 for more info - */ - xXPortalUser.setUserSource(1); - daoManager.getXXPortalUser().update(xXPortalUser); - if (logger.isDebugEnabled()) { - logger.debug("USER: Name: " + xUser.getName() + " userSource changed to External"); - } - } - } - daoManager.getXXUser().update(xUser); - if (logger.isDebugEnabled()) { - logger.debug("USER: Name: " + xUser.getName() + " syncSource updated to " + finalSyncSource); + txTemplate.execute(status -> { + if (StringUtils.isNotEmpty(finalSyncSource)) { + XXPortalUser xXPortalUser = daoManager.getXXPortalUser().findByLoginId(xUser.getName()); + if (xXPortalUser != null && xXPortalUser.getUserSource() == 0) { + /* updating the user source to external for users which had some sync source prior to upgrade + but the user source was marked internal to due bugs which were fixed later. + See RANGER-3297 for more info + */ + xXPortalUser.setUserSource(1); + + daoManager.getXXPortalUser().update(xXPortalUser); + + logger.debug("USER: Name: {} userSource changed to External", xUser.getName()); } - return null; } + + daoManager.getXXUser().update(xUser); + + logger.debug("USER: Name: {} syncSource updated to {}", xUser.getName(), finalSyncSource); + + return null; }); } catch (Throwable ex) { - logger.error("updateSyncSourceForUsers(): Failed to update DB for user: " + xUser.getName() + " ", ex); + logger.error("updateSyncSourceForUsers(): Failed to update DB for user: {}", xUser.getName(), ex); + throw new RuntimeException(ex); } - } else if (logger.isDebugEnabled()) { - logger.debug("Skipping syncSource update for user: " + xUser.getName() ); + } else { + logger.debug("Skipping syncSource update for user: {}", xUser.getName()); } } return true; } - public boolean updateSyncSourceForGroups(){ - List groups = daoManager.getXXGroup().getAll(); - for( XXGroup xGroup: groups) { + public boolean updateSyncSourceForGroups() { + List groups = daoManager.getXXGroup().getAll(); + + for (XXGroup xGroup : groups) { String syncSource = xGroup.getSyncSource(); String otherAttributes = xGroup.getOtherAttributes(); - if (StringUtils.isNotEmpty(otherAttributes) && StringUtils.isEmpty(syncSource)){ + + if (StringUtils.isNotEmpty(otherAttributes) && StringUtils.isEmpty(syncSource)) { syncSource = (String) JsonUtils.jsonToObject(otherAttributes, Map.class).get(UgsyncCommonConstants.SYNC_SOURCE); - if (StringUtils.isNotEmpty(syncSource) && xGroup.getGroupSource() == 0){ + + if (StringUtils.isNotEmpty(syncSource) && xGroup.getGroupSource() == 0) { xGroup.setGroupSource(1); - if (logger.isDebugEnabled()) { - logger.debug("GROUP: Name: " + xGroup.getName() + " groupSource changed to External"); - } + logger.debug("GROUP: Name: {} groupSource changed to External", xGroup.getName()); } + xGroup.setSyncSource(syncSource); - if (logger.isDebugEnabled()) { - logger.debug("GROUP: Name: " + xGroup.getName() + " syncSource updated to " + syncSource); - } + + logger.debug("GROUP: Name: {} syncSource updated to {}", xGroup.getName(), syncSource); TransactionTemplate txTemplate = new TransactionTemplate(txManager); + txTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + try { - txTemplate.execute(new TransactionCallback() { - @Override - public Object doInTransaction(TransactionStatus status) { - daoManager.getXXGroup().update(xGroup); - return null; - } + txTemplate.execute(status -> { + daoManager.getXXGroup().update(xGroup); + return null; }); } catch (Throwable ex) { - logger.error("updateSyncSourceForGroups(): Failed to update DB for group: " + xGroup.getName() + " ", ex); + logger.error("updateSyncSourceForGroups(): Failed to update DB for group: {}", xGroup.getName(), ex); + throw new RuntimeException(ex); } - } else if (logger.isDebugEnabled()) { - logger.debug("Skipping syncSource update for group: " + xGroup.getName() ); + } else { + logger.debug("Skipping syncSource update for group: {}", xGroup.getName()); } } + return true; } } diff --git a/security-admin/src/main/java/org/apache/ranger/patch/PatchForTagServiceDefUpdate_J10008.java b/security-admin/src/main/java/org/apache/ranger/patch/PatchForTagServiceDefUpdate_J10008.java index 8276050ac3..185e4e4a1e 100644 --- a/security-admin/src/main/java/org/apache/ranger/patch/PatchForTagServiceDefUpdate_J10008.java +++ b/security-admin/src/main/java/org/apache/ranger/patch/PatchForTagServiceDefUpdate_J10008.java @@ -24,6 +24,7 @@ import org.apache.ranger.common.RangerValidatorFactory; import org.apache.ranger.common.StringUtil; import org.apache.ranger.db.RangerDaoManager; +import org.apache.ranger.entity.XXServiceDef; import org.apache.ranger.plugin.model.RangerServiceDef; import org.apache.ranger.plugin.model.validation.RangerServiceDefValidator; import org.apache.ranger.plugin.model.validation.RangerValidator.Action; @@ -36,168 +37,190 @@ import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; -import org.apache.ranger.entity.XXServiceDef; + import java.util.List; import java.util.Map; @Component public class PatchForTagServiceDefUpdate_J10008 extends BaseLoader { - private static final Logger logger = LoggerFactory.getLogger(PatchForTagServiceDefUpdate_J10008.class); - public static final String SERVICEDBSTORE_SERVICEDEFBYNAME_TAG_NAME = "tag"; - public static final String SCRIPT_POLICY_CONDITION_NAME = "expression"; - - @Autowired - RangerDaoManager daoMgr; - - @Autowired - ServiceDBStore svcDBStore; - - @Autowired - JSONUtil jsonUtil; - - @Autowired - RangerPolicyService policyService; - - @Autowired - StringUtil stringUtil; - - @Autowired - XPolicyService xPolService; - - @Autowired - XPermMapService xPermMapService; - - @Autowired - RangerBizUtil bizUtil; - - @Autowired - RangerValidatorFactory validatorFactory; - - @Autowired - ServiceDBStore svcStore; - - public static void main(String[] args) { - logger.info("main()"); - try { - PatchForTagServiceDefUpdate_J10008 loader = (PatchForTagServiceDefUpdate_J10008) CLIUtil.getBean(PatchForTagServiceDefUpdate_J10008.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); - } - } - - @Override - public void init() throws Exception { - // Do Nothing - } - - @Override - public void execLoad() { - logger.info("==> PatchForTagServiceDefUpdate.execLoad()"); - try { - updateTagServiceDef(); - } catch (Exception e) { - logger.error("Error whille updateTagServiceDef()data.", e); - } - logger.info("<== PatchForTagServiceDefUpdate.execLoad()"); - } - - @Override - public void printStats() { - logger.info("PatchForTagServiceDefUpdate data "); - } - - private void updateTagServiceDef(){ - RangerServiceDef embeddedTagServiceDef = null; - RangerServiceDef dbTagServiceDef = null; - List embeddedTagPolicyConditionDefs = null; - XXServiceDef xXServiceDefObj = null; - try{ - embeddedTagServiceDef=EmbeddedServiceDefsUtil.instance().getEmbeddedServiceDef(SERVICEDBSTORE_SERVICEDEFBYNAME_TAG_NAME); - if(embeddedTagServiceDef!=null){ - embeddedTagPolicyConditionDefs = embeddedTagServiceDef.getPolicyConditions(); - if (embeddedTagPolicyConditionDefs == null) { - logger.error("Policy Conditions are empyt in tag service def json"); - return; - } - - if (checkScriptPolicyCondPresent(embeddedTagPolicyConditionDefs) == false) { - logger.error(SCRIPT_POLICY_CONDITION_NAME + "policy condition not found!!"); - return; - } - - xXServiceDefObj = daoMgr.getXXServiceDef().findByName(SERVICEDBSTORE_SERVICEDEFBYNAME_TAG_NAME); - if (xXServiceDefObj == null) { - logger.error("Service def for " + SERVICEDBSTORE_SERVICEDEFBYNAME_TAG_NAME + " is not found!!"); - return; - } - - Map serviceDefOptionsPreUpdate=null; - String jsonStrPreUpdate=null; - jsonStrPreUpdate=xXServiceDefObj.getDefOptions(); - if (!StringUtils.isEmpty(jsonStrPreUpdate)) { - serviceDefOptionsPreUpdate=jsonUtil.jsonToMap(jsonStrPreUpdate); - } - xXServiceDefObj=null; - dbTagServiceDef=svcDBStore.getServiceDefByName(SERVICEDBSTORE_SERVICEDEFBYNAME_TAG_NAME); - - if(dbTagServiceDef!=null){ - dbTagServiceDef.setPolicyConditions(embeddedTagPolicyConditionDefs); - RangerServiceDefValidator validator = validatorFactory.getServiceDefValidator(svcStore); - validator.validate(dbTagServiceDef, Action.UPDATE); - - svcStore.updateServiceDef(dbTagServiceDef); - - xXServiceDefObj = daoMgr.getXXServiceDef().findByName(SERVICEDBSTORE_SERVICEDEFBYNAME_TAG_NAME); - if(xXServiceDefObj!=null) { - String jsonStrPostUpdate=xXServiceDefObj.getDefOptions(); - Map serviceDefOptionsPostUpdate = null; - if (!StringUtils.isEmpty(jsonStrPostUpdate)) { - serviceDefOptionsPostUpdate =jsonUtil.jsonToMap(jsonStrPostUpdate); - } - if (serviceDefOptionsPostUpdate != null && serviceDefOptionsPostUpdate.containsKey(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES)) { - if(serviceDefOptionsPreUpdate == null || !serviceDefOptionsPreUpdate.containsKey(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES)) { - String preUpdateValue = serviceDefOptionsPreUpdate == null ? null : serviceDefOptionsPreUpdate.get(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES); - if (preUpdateValue == null) { - serviceDefOptionsPostUpdate.remove(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES); - } else { - serviceDefOptionsPostUpdate.put(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES, preUpdateValue); - } - xXServiceDefObj.setDefOptions(mapToJsonString(serviceDefOptionsPostUpdate)); - daoMgr.getXXServiceDef().update(xXServiceDefObj); - } - } - } - } - } - }catch(Exception e) - { - logger.error("Error while updating "+SERVICEDBSTORE_SERVICEDEFBYNAME_TAG_NAME+"service-def", e); - } - } - - private boolean checkScriptPolicyCondPresent(List policyCondDefs) { - boolean ret = false; - for(RangerServiceDef.RangerPolicyConditionDef policyCondDef : policyCondDefs) { - if ( SCRIPT_POLICY_CONDITION_NAME.equals(policyCondDef.getName()) ) { - ret = true ; - break; - } - } - return ret; - } - - private String mapToJsonString(Map map) throws Exception{ - String ret = null; - if(map != null) { - ret = jsonUtil.readMapToString(map); - } - return ret; - } + private static final Logger logger = LoggerFactory.getLogger(PatchForTagServiceDefUpdate_J10008.class); + + public static final String SERVICEDBSTORE_SERVICEDEFBYNAME_TAG_NAME = "tag"; + public static final String SCRIPT_POLICY_CONDITION_NAME = "expression"; + + @Autowired + RangerDaoManager daoMgr; + + @Autowired + ServiceDBStore svcDBStore; + + @Autowired + JSONUtil jsonUtil; + + @Autowired + RangerPolicyService policyService; + + @Autowired + StringUtil stringUtil; + + @Autowired + XPolicyService xPolService; + + @Autowired + XPermMapService xPermMapService; + + @Autowired + RangerBizUtil bizUtil; + + @Autowired + RangerValidatorFactory validatorFactory; + + @Autowired + ServiceDBStore svcStore; + + public static void main(String[] args) { + logger.info("main()"); + + try { + PatchForTagServiceDefUpdate_J10008 loader = (PatchForTagServiceDefUpdate_J10008) CLIUtil.getBean(PatchForTagServiceDefUpdate_J10008.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); + } + } + + @Override + public void init() throws Exception { + // Do Nothing + } + + @Override + public void printStats() { + logger.info("PatchForTagServiceDefUpdate data "); + } + + @Override + public void execLoad() { + logger.info("==> PatchForTagServiceDefUpdate.execLoad()"); + + try { + updateTagServiceDef(); + } catch (Exception e) { + logger.error("Error whille updateTagServiceDef()data.", e); + } + + logger.info("<== PatchForTagServiceDefUpdate.execLoad()"); + } + + private void updateTagServiceDef() { + try { + RangerServiceDef embeddedTagServiceDef = EmbeddedServiceDefsUtil.instance().getEmbeddedServiceDef(SERVICEDBSTORE_SERVICEDEFBYNAME_TAG_NAME); + + if (embeddedTagServiceDef != null) { + List embeddedTagPolicyConditionDefs = embeddedTagServiceDef.getPolicyConditions(); + + if (embeddedTagPolicyConditionDefs == null) { + logger.error("Policy Conditions are empyt in tag service def json"); + + return; + } + + if (!checkScriptPolicyCondPresent(embeddedTagPolicyConditionDefs)) { + logger.error("{} policy condition not found!!", SCRIPT_POLICY_CONDITION_NAME); + + return; + } + + XXServiceDef xXServiceDefObj = daoMgr.getXXServiceDef().findByName(SERVICEDBSTORE_SERVICEDEFBYNAME_TAG_NAME); + + if (xXServiceDefObj == null) { + logger.error("Service def for {} is not found!!", SERVICEDBSTORE_SERVICEDEFBYNAME_TAG_NAME); + return; + } + + Map serviceDefOptionsPreUpdate = null; + String jsonStrPreUpdate = xXServiceDefObj.getDefOptions(); + + if (!StringUtils.isEmpty(jsonStrPreUpdate)) { + serviceDefOptionsPreUpdate = jsonUtil.jsonToMap(jsonStrPreUpdate); + } + + RangerServiceDef dbTagServiceDef = svcDBStore.getServiceDefByName(SERVICEDBSTORE_SERVICEDEFBYNAME_TAG_NAME); + + if (dbTagServiceDef != null) { + dbTagServiceDef.setPolicyConditions(embeddedTagPolicyConditionDefs); + + RangerServiceDefValidator validator = validatorFactory.getServiceDefValidator(svcStore); + + validator.validate(dbTagServiceDef, Action.UPDATE); + + svcStore.updateServiceDef(dbTagServiceDef); + + xXServiceDefObj = daoMgr.getXXServiceDef().findByName(SERVICEDBSTORE_SERVICEDEFBYNAME_TAG_NAME); + + if (xXServiceDefObj != null) { + String jsonStrPostUpdate = xXServiceDefObj.getDefOptions(); + Map serviceDefOptionsPostUpdate = null; + + if (!StringUtils.isEmpty(jsonStrPostUpdate)) { + serviceDefOptionsPostUpdate = jsonUtil.jsonToMap(jsonStrPostUpdate); + } + + if (serviceDefOptionsPostUpdate != null && serviceDefOptionsPostUpdate.containsKey(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES)) { + if (serviceDefOptionsPreUpdate == null || !serviceDefOptionsPreUpdate.containsKey(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES)) { + String preUpdateValue = serviceDefOptionsPreUpdate == null ? null : serviceDefOptionsPreUpdate.get(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES); + + if (preUpdateValue == null) { + serviceDefOptionsPostUpdate.remove(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES); + } else { + serviceDefOptionsPostUpdate.put(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES, preUpdateValue); + } + + xXServiceDefObj.setDefOptions(mapToJsonString(serviceDefOptionsPostUpdate)); + + daoMgr.getXXServiceDef().update(xXServiceDefObj); + } + } + } + } + } + } catch (Exception e) { + logger.error("Error while updating {} service-def", SERVICEDBSTORE_SERVICEDEFBYNAME_TAG_NAME, e); + } + } + + private boolean checkScriptPolicyCondPresent(List policyCondDefs) { + boolean ret = false; + + for (RangerServiceDef.RangerPolicyConditionDef policyCondDef : policyCondDefs) { + if (SCRIPT_POLICY_CONDITION_NAME.equals(policyCondDef.getName())) { + ret = true; + + break; + } + } + + return ret; + } + + private String mapToJsonString(Map map) { + String ret = null; + + if (map != null) { + ret = jsonUtil.readMapToString(map); + } + + return ret; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/patch/PatchForTagServiceDefUpdate_J10028.java b/security-admin/src/main/java/org/apache/ranger/patch/PatchForTagServiceDefUpdate_J10028.java index 072831bf8f..27c568863a 100644 --- a/security-admin/src/main/java/org/apache/ranger/patch/PatchForTagServiceDefUpdate_J10028.java +++ b/security-admin/src/main/java/org/apache/ranger/patch/PatchForTagServiceDefUpdate_J10028.java @@ -45,272 +45,295 @@ @Component public class PatchForTagServiceDefUpdate_J10028 extends BaseLoader { - private static final Logger logger = LoggerFactory.getLogger(PatchForTagServiceDefUpdate_J10028.class); - private static final String SERVICEDBSTORE_SERVICEDEFBYNAME_TAG_NAME = "tag"; - - @Autowired - RangerDaoManager daoMgr; - - @Autowired - ServiceDBStore svcDBStore; - - @Autowired - JSONUtil jsonUtil; - - @Autowired - RangerPolicyService policyService; - - @Autowired - StringUtil stringUtil; - - @Autowired - XPolicyService xPolService; - - @Autowired - XPermMapService xPermMapService; - - @Autowired - RangerBizUtil bizUtil; - - @Autowired - RangerValidatorFactory validatorFactory; - - @Autowired - ServiceDBStore svcStore; - - public static void main(String[] args) { - logger.info("main()"); - try { - PatchForTagServiceDefUpdate_J10028 loader = (PatchForTagServiceDefUpdate_J10028) CLIUtil.getBean(PatchForTagServiceDefUpdate_J10028.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); - } - } - - @Override - public void printStats() { - logger.info("PatchForTagServiceDefUpdate data "); - } - - @Override - public void execLoad() { - logger.info("==> PatchForTagServiceDefUpdate.execLoad()"); - try { - if (!updateTagServiceDef()) { - logger.error("Failed to apply the patch."); - System.exit(1); - } - } catch (Exception e) { - logger.error("Error while updateTagServiceDef()data.", e); - System.exit(1); - } - logger.info("<== PatchForTagServiceDefUpdate.execLoad()"); - } - - @Override - public void init() throws Exception { - // Do Nothing - } - - private boolean updateTagServiceDef() throws Exception { - RangerServiceDef ret; - RangerServiceDef embeddedTagServiceDef; - RangerServiceDef dbTagServiceDef; - XXServiceDef xXServiceDefObj; - - embeddedTagServiceDef = EmbeddedServiceDefsUtil.instance().getEmbeddedServiceDef(SERVICEDBSTORE_SERVICEDEFBYNAME_TAG_NAME); - - if (embeddedTagServiceDef != null) { - xXServiceDefObj = daoMgr.getXXServiceDef().findByName(SERVICEDBSTORE_SERVICEDEFBYNAME_TAG_NAME); - Map serviceDefOptionsPreUpdate; - String jsonPreUpdate; - - if (xXServiceDefObj != null) { - jsonPreUpdate = xXServiceDefObj.getDefOptions(); - serviceDefOptionsPreUpdate = jsonStringToMap(jsonPreUpdate); - } else { - logger.error("Tag service-definition does not exist in the Ranger DAO. No patching is needed"); - return true; - } - dbTagServiceDef = svcDBStore.getServiceDefByName(SERVICEDBSTORE_SERVICEDEFBYNAME_TAG_NAME); - - boolean isTagServiceUpdated; - if (dbTagServiceDef != null) { - isTagServiceUpdated = updateResourceInTagServiceDef(dbTagServiceDef); - } else { - logger.error("Tag service-definition does not exist in the db store."); - return false; - } - if (isTagServiceUpdated) { - ret = svcStore.updateServiceDef(dbTagServiceDef); - if (ret == null) { - throw new RuntimeException("Error while updating " + SERVICEDBSTORE_SERVICEDEFBYNAME_TAG_NAME + " service-def"); - } - xXServiceDefObj = daoMgr.getXXServiceDef().findByName(SERVICEDBSTORE_SERVICEDEFBYNAME_TAG_NAME); - if (xXServiceDefObj != null) { - String jsonStrPostUpdate = xXServiceDefObj.getDefOptions(); - Map serviceDefOptionsPostUpdate = jsonStringToMap(jsonStrPostUpdate); - if (serviceDefOptionsPostUpdate != null && serviceDefOptionsPostUpdate.containsKey(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES)) { - if (serviceDefOptionsPreUpdate == null || !serviceDefOptionsPreUpdate.containsKey(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES)) { - String preUpdateValue = serviceDefOptionsPreUpdate == null ? null : serviceDefOptionsPreUpdate.get(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES); - if (preUpdateValue == null) { - serviceDefOptionsPostUpdate.remove(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES); - } else { - serviceDefOptionsPostUpdate.put(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES, preUpdateValue); - } - xXServiceDefObj.setDefOptions(mapToJsonString(serviceDefOptionsPostUpdate)); - daoMgr.getXXServiceDef().update(xXServiceDefObj); - } - } - } else { - logger.error("Tag service-definition does not exist in the Ranger DAO."); - return false; - } - } - } else { - logger.error("The embedded Tag service-definition does not exist."); - return false; - } - return true; - } - - private String mapToJsonString(Map map) { - String ret = null; - if (map != null) { - try { - ret = jsonUtil.readMapToString(map); - } catch (Exception ex) { - logger.warn("mapToJsonString() failed to convert map: " + map, ex); - } - } - return ret; - } - - private Map jsonStringToMap(String jsonStr) { - Map ret = null; - if (!StringUtils.isEmpty(jsonStr)) { - try { - ret = jsonUtil.jsonToMap(jsonStr); - } catch (Exception ex) { - // fallback to earlier format: "name1=value1;name2=value2" - for (String optionString : jsonStr.split(";")) { - if (StringUtils.isEmpty(optionString)) { - continue; - } - String[] nvArr = optionString.split("="); - String name = (nvArr.length > 0) ? nvArr[0].trim() : null; - String value = (nvArr.length > 1) ? nvArr[1].trim() : null; - if (StringUtils.isEmpty(name)) { - continue; - } - if (ret == null) { - ret = new HashMap<>(); - } - ret.put(name, value); - } - } - } - return ret; - } - - private boolean updateResourceInTagServiceDef(RangerServiceDef tagServiceDef) { - if (logger.isDebugEnabled()) { - logger.debug("==> PatchForTagServiceDefUpdate_J10028.updateResourceInTagServiceDef(" + tagServiceDef + ")"); - } - boolean ret = false; - - final RangerServiceDef.RangerResourceDef accessPolicyTagResource = getResourceDefForTagResource(tagServiceDef.getResources()); - - if (accessPolicyTagResource != null) { - - RangerServiceDef.RangerDataMaskDef dataMaskDef = tagServiceDef.getDataMaskDef(); - - if (dataMaskDef != null) { - if (CollectionUtils.isNotEmpty(dataMaskDef.getAccessTypes())) { - addOrUpdateResourceDefForTagResource(dataMaskDef.getResources(), accessPolicyTagResource); - ret = true; - } else { - if (CollectionUtils.isNotEmpty(dataMaskDef.getResources())) { - dataMaskDef.setResources(null); - ret = true; - } - } - } - - RangerServiceDef.RangerRowFilterDef rowFilterDef = tagServiceDef.getRowFilterDef(); - - if (rowFilterDef != null) { - boolean autopropagateRowfilterdefToTag = config.getBoolean(AbstractServiceStore.AUTOPROPAGATE_ROWFILTERDEF_TO_TAG_PROP, AbstractServiceStore.AUTOPROPAGATE_ROWFILTERDEF_TO_TAG_PROP_DEFAULT); - if (autopropagateRowfilterdefToTag) { - if (CollectionUtils.isNotEmpty(rowFilterDef.getAccessTypes())) { - addOrUpdateResourceDefForTagResource(rowFilterDef.getResources(), accessPolicyTagResource); - ret = true; - } else { - if (CollectionUtils.isNotEmpty(rowFilterDef.getResources())) { - rowFilterDef.setResources(null); - ret = true; - } - } - } - } - } else { - logger.warn("Resource with name :[" + RangerServiceTag.TAG_RESOURCE_NAME + "] not found in tag-service-definition!!"); - } - - if (logger.isDebugEnabled()) { - logger.debug("<== PatchForTagServiceDefUpdate_J10028.updateResourceInTagServiceDef(" + tagServiceDef + ") : " + ret); - } - - return ret; - } - - private RangerServiceDef.RangerResourceDef getResourceDefForTagResource(List resourceDefs) { - - RangerServiceDef.RangerResourceDef ret = null; - - if (CollectionUtils.isNotEmpty(resourceDefs)) { - for (RangerServiceDef.RangerResourceDef resourceDef : resourceDefs) { - if (resourceDef.getName().equals(RangerServiceTag.TAG_RESOURCE_NAME)) { - ret = resourceDef; - break; - } - } - } - - return ret; - } - - private void addOrUpdateResourceDefForTagResource(List resourceDefs, RangerServiceDef.RangerResourceDef tagResourceDef) { - - RangerServiceDef.RangerResourceDef tagResourceDefInResourceDefs = getResourceDefForTagResource(resourceDefs); - - if (tagResourceDefInResourceDefs == null) { - resourceDefs.add(tagResourceDef); - } else { - tagResourceDefInResourceDefs.setDescription(tagResourceDef.getDescription()); - tagResourceDefInResourceDefs.setLabel(tagResourceDef.getLabel()); - tagResourceDefInResourceDefs.setValidationMessage(tagResourceDef.getValidationMessage()); - tagResourceDefInResourceDefs.setValidationRegEx(tagResourceDef.getValidationRegEx()); - tagResourceDefInResourceDefs.setRbKeyDescription(tagResourceDef.getRbKeyDescription()); - tagResourceDefInResourceDefs.setRbKeyLabel(tagResourceDef.getRbKeyLabel()); - tagResourceDefInResourceDefs.setRbKeyValidationMessage(tagResourceDef.getRbKeyValidationMessage()); - tagResourceDefInResourceDefs.setUiHint(tagResourceDef.getUiHint()); - tagResourceDefInResourceDefs.setMatcher(tagResourceDef.getMatcher()); - tagResourceDefInResourceDefs.setMatcherOptions(tagResourceDef.getMatcherOptions()); - tagResourceDefInResourceDefs.setLookupSupported(tagResourceDef.getLookupSupported()); - tagResourceDefInResourceDefs.setExcludesSupported(tagResourceDef.getExcludesSupported()); - tagResourceDefInResourceDefs.setRecursiveSupported(tagResourceDef.getRecursiveSupported()); - tagResourceDefInResourceDefs.setMandatory(tagResourceDef.getMandatory()); - tagResourceDefInResourceDefs.setLevel(tagResourceDef.getLevel()); - tagResourceDefInResourceDefs.setIsValidLeaf(tagResourceDef.getIsValidLeaf()); - tagResourceDefInResourceDefs.setParent(tagResourceDef.getParent()); - } - } + private static final Logger logger = LoggerFactory.getLogger(PatchForTagServiceDefUpdate_J10028.class); + + private static final String SERVICEDBSTORE_SERVICEDEFBYNAME_TAG_NAME = "tag"; + + @Autowired + RangerDaoManager daoMgr; + + @Autowired + ServiceDBStore svcDBStore; + + @Autowired + JSONUtil jsonUtil; + + @Autowired + RangerPolicyService policyService; + + @Autowired + StringUtil stringUtil; + + @Autowired + XPolicyService xPolService; + + @Autowired + XPermMapService xPermMapService; + + @Autowired + RangerBizUtil bizUtil; + + @Autowired + RangerValidatorFactory validatorFactory; + + @Autowired + ServiceDBStore svcStore; + + public static void main(String[] args) { + logger.info("main()"); + + try { + PatchForTagServiceDefUpdate_J10028 loader = (PatchForTagServiceDefUpdate_J10028) CLIUtil.getBean(PatchForTagServiceDefUpdate_J10028.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); + } + } + + @Override + public void init() throws Exception { + // Do Nothing + } + + @Override + public void printStats() { + logger.info("PatchForTagServiceDefUpdate data "); + } + + @Override + public void execLoad() { + logger.info("==> PatchForTagServiceDefUpdate.execLoad()"); + + try { + if (!updateTagServiceDef()) { + logger.error("Failed to apply the patch."); + + System.exit(1); + } + } catch (Exception e) { + logger.error("Error while updateTagServiceDef()data.", e); + + System.exit(1); + } + + logger.info("<== PatchForTagServiceDefUpdate.execLoad()"); + } + + private boolean updateTagServiceDef() throws Exception { + RangerServiceDef embeddedTagServiceDef = EmbeddedServiceDefsUtil.instance().getEmbeddedServiceDef(SERVICEDBSTORE_SERVICEDEFBYNAME_TAG_NAME); + + if (embeddedTagServiceDef != null) { + XXServiceDef xXServiceDefObj = daoMgr.getXXServiceDef().findByName(SERVICEDBSTORE_SERVICEDEFBYNAME_TAG_NAME); + + if (xXServiceDefObj == null) { + logger.error("Tag service-definition does not exist in the Ranger DAO. No patching is needed"); + return true; + } + + String jsonPreUpdate = xXServiceDefObj.getDefOptions(); + Map serviceDefOptionsPreUpdate = jsonStringToMap(jsonPreUpdate); + RangerServiceDef dbTagServiceDef = svcDBStore.getServiceDefByName(SERVICEDBSTORE_SERVICEDEFBYNAME_TAG_NAME); + boolean isTagServiceUpdated; + + if (dbTagServiceDef != null) { + isTagServiceUpdated = updateResourceInTagServiceDef(dbTagServiceDef); + } else { + logger.error("Tag service-definition does not exist in the db store."); + + return false; + } + + if (isTagServiceUpdated) { + RangerServiceDef ret = svcStore.updateServiceDef(dbTagServiceDef); + + if (ret == null) { + throw new RuntimeException("Error while updating " + SERVICEDBSTORE_SERVICEDEFBYNAME_TAG_NAME + " service-def"); + } + + xXServiceDefObj = daoMgr.getXXServiceDef().findByName(SERVICEDBSTORE_SERVICEDEFBYNAME_TAG_NAME); + + if (xXServiceDefObj != null) { + String jsonStrPostUpdate = xXServiceDefObj.getDefOptions(); + Map serviceDefOptionsPostUpdate = jsonStringToMap(jsonStrPostUpdate); + + if (serviceDefOptionsPostUpdate != null && serviceDefOptionsPostUpdate.containsKey(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES)) { + if (serviceDefOptionsPreUpdate == null || !serviceDefOptionsPreUpdate.containsKey(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES)) { + String preUpdateValue = serviceDefOptionsPreUpdate == null ? null : serviceDefOptionsPreUpdate.get(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES); + + if (preUpdateValue == null) { + serviceDefOptionsPostUpdate.remove(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES); + } else { + serviceDefOptionsPostUpdate.put(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES, preUpdateValue); + } + + xXServiceDefObj.setDefOptions(mapToJsonString(serviceDefOptionsPostUpdate)); + + daoMgr.getXXServiceDef().update(xXServiceDefObj); + } + } + } else { + logger.error("Tag service-definition does not exist in the Ranger DAO."); + + return false; + } + } + } else { + logger.error("The embedded Tag service-definition does not exist."); + + return false; + } + + return true; + } + + private String mapToJsonString(Map map) { + String ret = null; + + if (map != null) { + try { + ret = jsonUtil.readMapToString(map); + } catch (Exception ex) { + logger.warn("mapToJsonString() failed to convert map: {}", map, ex); + } + } + + return ret; + } + + private Map jsonStringToMap(String jsonStr) { + Map ret = null; + + if (!StringUtils.isEmpty(jsonStr)) { + try { + ret = jsonUtil.jsonToMap(jsonStr); + } catch (Exception ex) { + // fallback to earlier format: "name1=value1;name2=value2" + for (String optionString : jsonStr.split(";")) { + if (StringUtils.isEmpty(optionString)) { + continue; + } + + String[] nvArr = optionString.split("="); + String name = (nvArr.length > 0) ? nvArr[0].trim() : null; + String value = (nvArr.length > 1) ? nvArr[1].trim() : null; + + if (StringUtils.isEmpty(name)) { + continue; + } + + if (ret == null) { + ret = new HashMap<>(); + } + + ret.put(name, value); + } + } + } + + return ret; + } + + private boolean updateResourceInTagServiceDef(RangerServiceDef tagServiceDef) { + logger.debug("==> PatchForTagServiceDefUpdate_J10028.updateResourceInTagServiceDef({})", tagServiceDef); + + boolean ret = false; + final RangerServiceDef.RangerResourceDef accessPolicyTagResource = getResourceDefForTagResource(tagServiceDef.getResources()); + + if (accessPolicyTagResource != null) { + RangerServiceDef.RangerDataMaskDef dataMaskDef = tagServiceDef.getDataMaskDef(); + + if (dataMaskDef != null) { + if (CollectionUtils.isNotEmpty(dataMaskDef.getAccessTypes())) { + addOrUpdateResourceDefForTagResource(dataMaskDef.getResources(), accessPolicyTagResource); + + ret = true; + } else { + if (CollectionUtils.isNotEmpty(dataMaskDef.getResources())) { + dataMaskDef.setResources(null); + + ret = true; + } + } + } + + RangerServiceDef.RangerRowFilterDef rowFilterDef = tagServiceDef.getRowFilterDef(); + + if (rowFilterDef != null) { + boolean autopropagateRowfilterdefToTag = config.getBoolean(AbstractServiceStore.AUTOPROPAGATE_ROWFILTERDEF_TO_TAG_PROP, AbstractServiceStore.AUTOPROPAGATE_ROWFILTERDEF_TO_TAG_PROP_DEFAULT); + + if (autopropagateRowfilterdefToTag) { + if (CollectionUtils.isNotEmpty(rowFilterDef.getAccessTypes())) { + addOrUpdateResourceDefForTagResource(rowFilterDef.getResources(), accessPolicyTagResource); + + ret = true; + } else { + if (CollectionUtils.isNotEmpty(rowFilterDef.getResources())) { + rowFilterDef.setResources(null); + + ret = true; + } + } + } + } + } else { + logger.warn("Resource with name :[{}] not found in tag-service-definition!!", RangerServiceTag.TAG_RESOURCE_NAME); + } + + logger.debug("<== PatchForTagServiceDefUpdate_J10028.updateResourceInTagServiceDef({}) : {}", tagServiceDef, ret); + + return ret; + } + + private RangerServiceDef.RangerResourceDef getResourceDefForTagResource(List resourceDefs) { + RangerServiceDef.RangerResourceDef ret = null; + + if (CollectionUtils.isNotEmpty(resourceDefs)) { + for (RangerServiceDef.RangerResourceDef resourceDef : resourceDefs) { + if (resourceDef.getName().equals(RangerServiceTag.TAG_RESOURCE_NAME)) { + ret = resourceDef; + + break; + } + } + } + + return ret; + } + + private void addOrUpdateResourceDefForTagResource(List resourceDefs, RangerServiceDef.RangerResourceDef tagResourceDef) { + RangerServiceDef.RangerResourceDef tagResourceDefInResourceDefs = getResourceDefForTagResource(resourceDefs); + + if (tagResourceDefInResourceDefs == null) { + resourceDefs.add(tagResourceDef); + } else { + tagResourceDefInResourceDefs.setDescription(tagResourceDef.getDescription()); + tagResourceDefInResourceDefs.setLabel(tagResourceDef.getLabel()); + tagResourceDefInResourceDefs.setValidationMessage(tagResourceDef.getValidationMessage()); + tagResourceDefInResourceDefs.setValidationRegEx(tagResourceDef.getValidationRegEx()); + tagResourceDefInResourceDefs.setRbKeyDescription(tagResourceDef.getRbKeyDescription()); + tagResourceDefInResourceDefs.setRbKeyLabel(tagResourceDef.getRbKeyLabel()); + tagResourceDefInResourceDefs.setRbKeyValidationMessage(tagResourceDef.getRbKeyValidationMessage()); + tagResourceDefInResourceDefs.setUiHint(tagResourceDef.getUiHint()); + tagResourceDefInResourceDefs.setMatcher(tagResourceDef.getMatcher()); + tagResourceDefInResourceDefs.setMatcherOptions(tagResourceDef.getMatcherOptions()); + tagResourceDefInResourceDefs.setLookupSupported(tagResourceDef.getLookupSupported()); + tagResourceDefInResourceDefs.setExcludesSupported(tagResourceDef.getExcludesSupported()); + tagResourceDefInResourceDefs.setRecursiveSupported(tagResourceDef.getRecursiveSupported()); + tagResourceDefInResourceDefs.setMandatory(tagResourceDef.getMandatory()); + tagResourceDefInResourceDefs.setLevel(tagResourceDef.getLevel()); + tagResourceDefInResourceDefs.setIsValidLeaf(tagResourceDef.getIsValidLeaf()); + tagResourceDefInResourceDefs.setParent(tagResourceDef.getParent()); + } + } } diff --git a/security-admin/src/main/java/org/apache/ranger/patch/PatchForTrinoSvcDefUpdate_J10062.java b/security-admin/src/main/java/org/apache/ranger/patch/PatchForTrinoSvcDefUpdate_J10062.java index 57d55f50c0..6a88d81750 100644 --- a/security-admin/src/main/java/org/apache/ranger/patch/PatchForTrinoSvcDefUpdate_J10062.java +++ b/security-admin/src/main/java/org/apache/ranger/patch/PatchForTrinoSvcDefUpdate_J10062.java @@ -37,8 +37,6 @@ 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 java.util.ArrayList; @@ -48,53 +46,66 @@ @Component public class PatchForTrinoSvcDefUpdate_J10062 extends BaseLoader { - public static final String LOGIN_ID_ADMIN = "admin"; - public static final String WILDCARD_ASTERISK = "*"; - public static final String POlICY_NAME_FOR_ALL_SYSINFO = "all - sysinfo"; - public static final String POlICY_NAME_FOR_ALL_CATALOG_SCHEMA_FUNCTION = "all - catalog, schema, schemafunction"; - public static final String POlICY_NAME_FOR_ALL_QUERY = "all - queryid"; - public static final String POlICY_NAME_FOR_ALL_ROLE = "all - role"; - public static final String RESOURCE_SYSINFO = "sysinfo"; - public static final String RESOURCE_CATALOG = "catalog"; - public static final String RESOURCE_SCHEMA = "schema"; - public static final String RESOURCE_QUERYID = "queryid"; - public static final String RESOURCE_ROLE = "role"; - public static final String RESOURCE_SCHEMAFUNCTION = "schemafunction"; - public static final String ACCESS_TYPE_READ_SYSINFO = "read_sysinfo"; - public static final String ACCESS_TYPE_WRITE_SYSINFO = "write_sysinfo"; - public static final String ACCESS_TYPE_CREATE = "create"; - public static final String ACCESS_TYPE_DROP = "drop"; - public static final String ACCESS_TYPE_SHOW = "show"; - public static final String ACCESS_TYPE_GRANT = "grant"; - public static final String ACCESS_TYPE_REVOKE = "revoke"; - public static final String ACCESS_TYPE_EXECUTE = "execute"; - public static final String ACCESS_TYPE_SELECT = "select"; private static final Logger logger = Logger.getLogger(PatchForTrinoSvcDefUpdate_J10062.class); + + public static final String LOGIN_ID_ADMIN = "admin"; + public static final String WILDCARD_ASTERISK = "*"; + public static final String POlICY_NAME_FOR_ALL_SYSINFO = "all - sysinfo"; + public static final String POlICY_NAME_FOR_ALL_CATALOG_SCHEMA_FUNCTION = "all - catalog, schema, schemafunction"; + public static final String POlICY_NAME_FOR_ALL_QUERY = "all - queryid"; + public static final String POlICY_NAME_FOR_ALL_ROLE = "all - role"; + public static final String RESOURCE_SYSINFO = "sysinfo"; + public static final String RESOURCE_CATALOG = "catalog"; + public static final String RESOURCE_SCHEMA = "schema"; + public static final String RESOURCE_QUERYID = "queryid"; + public static final String RESOURCE_ROLE = "role"; + public static final String RESOURCE_SCHEMAFUNCTION = "schemafunction"; + public static final String ACCESS_TYPE_READ_SYSINFO = "read_sysinfo"; + public static final String ACCESS_TYPE_WRITE_SYSINFO = "write_sysinfo"; + public static final String ACCESS_TYPE_CREATE = "create"; + public static final String ACCESS_TYPE_DROP = "drop"; + public static final String ACCESS_TYPE_SHOW = "show"; + public static final String ACCESS_TYPE_GRANT = "grant"; + public static final String ACCESS_TYPE_REVOKE = "revoke"; + public static final String ACCESS_TYPE_EXECUTE = "execute"; + public static final String ACCESS_TYPE_SELECT = "select"; + private static final String TRINO_SVC_DEF_NAME = EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_TRINO_NAME; + @Autowired - GUIDUtil guidUtil; + GUIDUtil guidUtil; + @Autowired - ServiceDBStore svcDBStore; + ServiceDBStore svcDBStore; + @Autowired @Qualifier(value = "transactionManager") PlatformTransactionManager txManager; + @Autowired - private RangerDaoManager daoMgr; + private RangerDaoManager daoMgr; + @Autowired private RangerValidatorFactory validatorFactory; public static void main(String[] args) { logger.info("main()"); + try { PatchForTrinoSvcDefUpdate_J10062 loader = (PatchForTrinoSvcDefUpdate_J10062) CLIUtil.getBean(PatchForTrinoSvcDefUpdate_J10062.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); } } @@ -112,83 +123,104 @@ public void printStats() { @Override public void execLoad() { logger.info("==> PatchForTrinoSvcDefUpdate_J10062.execLoad()"); + try { TransactionTemplate txTemplate = new TransactionTemplate(txManager); + txTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + try { - txTemplate.execute(new TransactionCallback() { - @Override - public Object doInTransaction(TransactionStatus status) { - RangerServiceDef dbRangerServiceDef = null; - RangerServiceDef embeddedTrinoServiceDef = null; - try { - embeddedTrinoServiceDef = EmbeddedServiceDefsUtil.instance().getEmbeddedServiceDef(TRINO_SVC_DEF_NAME); - } catch (Exception ex) { - logger.error("Error while loading service-def: " + TRINO_SVC_DEF_NAME, ex); - } - if (embeddedTrinoServiceDef == null) { - logger.error("The embedded Trino service-definition does not exist."); + txTemplate.execute(status -> { + RangerServiceDef dbRangerServiceDef = null; + RangerServiceDef embeddedTrinoServiceDef = null; + + try { + embeddedTrinoServiceDef = EmbeddedServiceDefsUtil.instance().getEmbeddedServiceDef(TRINO_SVC_DEF_NAME); + } catch (Exception ex) { + logger.error("Error while loading service-def:" + TRINO_SVC_DEF_NAME, ex); + } + + if (embeddedTrinoServiceDef == null) { + logger.error("The embedded Trino service-definition does not exist."); + + throw new RuntimeException("Error while updating " + TRINO_SVC_DEF_NAME + " service-def"); + } + + try { + dbRangerServiceDef = svcDBStore.getServiceDefByName(TRINO_SVC_DEF_NAME); + } catch (Exception e) { + logger.error("The Trino service-definition does not exist in ranger db."); + } finally { + if (dbRangerServiceDef == null) { + logger.error("The Trino service-definition does not exist."); + throw new RuntimeException("Error while updating " + TRINO_SVC_DEF_NAME + " service-def"); } - if (embeddedTrinoServiceDef != null) { - try { - dbRangerServiceDef = svcDBStore.getServiceDefByName(TRINO_SVC_DEF_NAME); - } catch (Exception e) { - logger.error("The Trino service-definition does not exist in ranger db."); - } finally { - if (dbRangerServiceDef == null) { - logger.error("The Trino service-definition does not exist."); - throw new RuntimeException("Error while updating " + TRINO_SVC_DEF_NAME + " service-def"); - } - } - } - dbRangerServiceDef = updateTrinoSvcDef(embeddedTrinoServiceDef, dbRangerServiceDef); - if (dbRangerServiceDef != null) { - try { - createDefaultPolicies(dbRangerServiceDef); - } catch (Exception e) { - logger.error("Error while creating default ranger policies for " + TRINO_SVC_DEF_NAME + " service-def"); - throw new RuntimeException("Error while creating default ranger policies for " + TRINO_SVC_DEF_NAME + " service-def"); - } - } else { - logger.error("Error while updating " + TRINO_SVC_DEF_NAME + " service-def"); - throw new RuntimeException("Error while updating " + TRINO_SVC_DEF_NAME + " service-def"); + } + + dbRangerServiceDef = updateTrinoSvcDef(embeddedTrinoServiceDef, dbRangerServiceDef); + + if (dbRangerServiceDef != null) { + try { + createDefaultPolicies(dbRangerServiceDef); + } catch (Exception e) { + logger.error("Error while creating default ranger policies for " + TRINO_SVC_DEF_NAME + " service-def"); + + throw new RuntimeException("Error while creating default ranger policies for " + TRINO_SVC_DEF_NAME + " service-def"); } - return null; + } else { + logger.error("Error while updating " + TRINO_SVC_DEF_NAME + " service-def"); + + throw new RuntimeException("Error while updating " + TRINO_SVC_DEF_NAME + " service-def"); } + + return null; }); } catch (Throwable ex) { logger.error("Error while updating " + TRINO_SVC_DEF_NAME + " service-def"); + throw new RuntimeException(ex.getMessage()); } } catch (Exception e) { logger.error("Error while executing PatchForTrinoSvcDefUpdate_J10062, Error - ", e); + throw new RuntimeException(e.getMessage()); } + logger.info("<== PatchForTrinoSvcDefUpdate_J10062.execLoad()"); } private RangerServiceDef updateTrinoSvcDef(RangerServiceDef embeddedTrinoServiceDef, RangerServiceDef dbRangerServiceDef) { logger.info("==> PatchForTrinoSvcDefUpdate_J10062.updateTrinoSvcDef()"); - RangerServiceDef ret = null; + + RangerServiceDef ret; + try { dbRangerServiceDef.setResources(embeddedTrinoServiceDef.getResources()); dbRangerServiceDef.setAccessTypes(embeddedTrinoServiceDef.getAccessTypes()); dbRangerServiceDef.setConfigs(embeddedTrinoServiceDef.getConfigs()); + RangerServiceDefValidator validator = validatorFactory.getServiceDefValidator(this.svcDBStore); + validator.validate(dbRangerServiceDef, Action.UPDATE); + ret = this.svcDBStore.updateServiceDef(dbRangerServiceDef); + logger.info(TRINO_SVC_DEF_NAME + " service-def has been updated"); } catch (Exception e) { logger.error("Error while updating" + TRINO_SVC_DEF_NAME + " service-def", e); + throw new RuntimeException(e); } + logger.info("<== PatchForTrinoSvcDefUpdate_J10062.updateTrinoSvcDef()"); + return ret; } private void createDefaultPolicies(RangerServiceDef dbRangerServiceDef) throws Exception { List dbServices = daoMgr.getXXService().findByServiceDefId(dbRangerServiceDef.getId()); + if (CollectionUtils.isNotEmpty(dbServices)) { for (XXService dbService : dbServices) { addDefaultPolicies(dbService.getName(), null); @@ -198,57 +230,81 @@ private void createDefaultPolicies(RangerServiceDef dbRangerServiceDef) throws E private void addDefaultPolicies(String serviceName, String zoneName) throws Exception { logger.info("===> addDefaultPolicies ServiceName : " + serviceName + " ZoneName : " + zoneName); + List resources = new ArrayList<>(); + resources.add(RESOURCE_SYSINFO); - RangerPolicy allSysInfoPolicy = getPolicy(serviceName, zoneName, POlICY_NAME_FOR_ALL_SYSINFO, resources); - List policies = svcDBStore.getPoliciesByResourceSignature(serviceName, allSysInfoPolicy.getResourceSignature(), true); + + RangerPolicy allSysInfoPolicy = getPolicy(serviceName, zoneName, POlICY_NAME_FOR_ALL_SYSINFO, resources); + List policies = svcDBStore.getPoliciesByResourceSignature(serviceName, allSysInfoPolicy.getResourceSignature(), true); + if (CollectionUtils.isEmpty(policies)) { logger.info("No policy found with resource sysinfo = * creating new policy"); + svcDBStore.createPolicy(allSysInfoPolicy); } resources.clear(); policies.clear(); + resources.add(RESOURCE_CATALOG); resources.add(RESOURCE_SCHEMA); resources.add(RESOURCE_SCHEMAFUNCTION); + RangerPolicy allCatalogSchemaFunctionPolicy = getPolicy(serviceName, zoneName, POlICY_NAME_FOR_ALL_CATALOG_SCHEMA_FUNCTION, resources); + policies = svcDBStore.getPoliciesByResourceSignature(serviceName, allCatalogSchemaFunctionPolicy.getResourceSignature(), true); + if (CollectionUtils.isEmpty(policies)) { logger.info("No policy found with resource catalog, schema, schemafunction = *; creating new policy"); + svcDBStore.createPolicy(allCatalogSchemaFunctionPolicy); } resources.clear(); policies.clear(); + resources.add(RESOURCE_QUERYID); + RangerPolicy allQueryIdPolicy = getPolicy(serviceName, zoneName, POlICY_NAME_FOR_ALL_QUERY, resources); + policies = svcDBStore.getPoliciesByResourceSignature(serviceName, allQueryIdPolicy.getResourceSignature(), true); + if (CollectionUtils.isEmpty(policies)) { logger.info("No policy found with resource queryId = *; creating new policy"); + svcDBStore.createPolicy(allQueryIdPolicy); } resources.clear(); policies.clear(); + resources.add(RESOURCE_ROLE); + RangerPolicy allRolePolicy = getPolicy(serviceName, zoneName, POlICY_NAME_FOR_ALL_ROLE, resources); + policies = svcDBStore.getPoliciesByResourceSignature(serviceName, allRolePolicy.getResourceSignature(), true); + if (CollectionUtils.isEmpty(policies)) { logger.info("No policy found with resource role = *; creating new policy"); + svcDBStore.createPolicy(allRolePolicy); } + logger.info("<=== addDefaultPolicies"); } private RangerPolicy getPolicy(String serviceName, String zoneName, String policyName, List resources) { logger.info("===> getPolicy "); - RangerPolicy policy; + Map policyResources = new HashMap<>(); + for (String resource : resources) { policyResources.put(resource, new RangerPolicy.RangerPolicyResource(WILDCARD_ASTERISK)); } - policy = new RangerPolicy(); + + RangerPolicy policy = new RangerPolicy(); + policy.setService(serviceName); policy.setName(policyName); policy.setDescription("Policy for " + policyName); @@ -258,31 +314,38 @@ private RangerPolicy getPolicy(String serviceName, String zoneName, String polic policy.setPolicyType(RangerPolicy.POLICY_TYPE_ACCESS); policy.setGuid(guidUtil.genGUID()); policy.setZoneName(zoneName); + List policyItems = new ArrayList<>(); + policyItems.add(getPolicyItem(policyName, "trino", true)); policyItems.add(getPolicyItem("select", "rangerlookup", false)); + policy.setPolicyItems(policyItems); policy.setResourceSignature(new RangerPolicyResourceSignature(policy).getSignature()); - if (logger.isDebugEnabled()) { - logger.debug("===> getPolicy policy ResourceSignature " + policy.getResourceSignature()); - logger.debug("===> getPolicy policy : " + policy); - } + + logger.debug("===> getPolicy policy ResourceSignature " + policy.getResourceSignature()); + logger.debug("===> getPolicy policy : " + policy); logger.info("<=== getPolicy "); + return policy; } private RangerPolicy.RangerPolicyItem getPolicyItem(String policyName, String user, boolean delegateAdmin) { RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem(); - policyItem.setUsers(new ArrayList() {{ - add(user); - }}); + List users = new ArrayList<>(); + + users.add(user); + + policyItem.setUsers(users); policyItem.setAccesses(getAccessList(policyName)); policyItem.setDelegateAdmin(delegateAdmin); + return policyItem; } private List getAccessList(String policyName) { - List accessList = new ArrayList(); + List accessList = new ArrayList<>(); + switch (policyName) { case POlICY_NAME_FOR_ALL_SYSINFO: accessList.add(new RangerPolicy.RangerPolicyItemAccess(ACCESS_TYPE_READ_SYSINFO)); @@ -309,7 +372,7 @@ private List getAccessList(String policyNam accessList.add(new RangerPolicy.RangerPolicyItemAccess(ACCESS_TYPE_SELECT)); break; } + return accessList; } - -} \ No newline at end of file +} diff --git a/security-admin/src/main/java/org/apache/ranger/patch/PatchForUpdatingAtlasSvcDefAndTagPolicies_J10063.java b/security-admin/src/main/java/org/apache/ranger/patch/PatchForUpdatingAtlasSvcDefAndTagPolicies_J10063.java index ce18040006..89899fa59b 100644 --- a/security-admin/src/main/java/org/apache/ranger/patch/PatchForUpdatingAtlasSvcDefAndTagPolicies_J10063.java +++ b/security-admin/src/main/java/org/apache/ranger/patch/PatchForUpdatingAtlasSvcDefAndTagPolicies_J10063.java @@ -17,11 +17,6 @@ package org.apache.ranger.patch; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang.StringUtils; import org.apache.ranger.biz.ServiceDBStore; @@ -42,195 +37,230 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + @Component public class PatchForUpdatingAtlasSvcDefAndTagPolicies_J10063 extends BaseLoader { - private static final Logger logger = LoggerFactory - .getLogger(PatchForUpdatingAtlasSvcDefAndTagPolicies_J10063.class); - - @Autowired - RangerDaoManager daoMgr; - - @Autowired - JSONUtil jsonUtil; - - @Autowired - StringUtil stringUtil; - - @Autowired - ServiceDBStore svcStore; - - public static void main(String[] args) { - logger.info("main()"); - try { - PatchForUpdatingAtlasSvcDefAndTagPolicies_J10063 loader = (PatchForUpdatingAtlasSvcDefAndTagPolicies_J10063) CLIUtil - .getBean(PatchForUpdatingAtlasSvcDefAndTagPolicies_J10063.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); - } - } - - @Override - public void printStats() { - logger.info("PatchForUpdatingAtlasSvcDefAndTagPolicies_J10063 data "); - } - - @Override - public void execLoad() { - logger.info("==> PatchForUpdatingAtlasSvcDefAndTagPolicies_J10063.execLoad()"); - try { - if (updateAtlasServiceDef()) { - disableAtlasAccessForTagPolicies(); - } - } catch (Exception e) { - logger.error("Error while updateTagServiceDef()data.", e); - System.exit(1); - } - logger.info("<== PatchForUpdatingAtlasSvcDefAndTagPolicies_J10063.execLoad()"); - } - - @Override - public void init() throws Exception { - // Do Nothing - } - - private boolean updateAtlasServiceDef() throws Exception { - logger.info("==> PatchForUpdatingAtlasSvcDefAndTagPolicies_J10063.updateAtlasServiceDef()"); - RangerServiceDef embeddedAtlasServiceDef; - XXServiceDef xXServiceDefObj; - - embeddedAtlasServiceDef = EmbeddedServiceDefsUtil.instance() - .getEmbeddedServiceDef(EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_ATLAS_NAME); - - if (embeddedAtlasServiceDef != null) { - xXServiceDefObj = daoMgr.getXXServiceDef().findByName(EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_ATLAS_NAME); - - if (xXServiceDefObj != null) { - String jsonStrUpdate = xXServiceDefObj.getDefOptions(); - Map serviceDefOptionsUpdate = jsonStringToMap(jsonStrUpdate); - if (serviceDefOptionsUpdate == null) { - serviceDefOptionsUpdate = new HashMap<>(); - } - serviceDefOptionsUpdate.put(RangerServiceDef.OPTION_ENABLE_TAG_BASED_POLICIES, "false"); - xXServiceDefObj.setDefOptions(mapToJsonString(serviceDefOptionsUpdate)); - daoMgr.getXXServiceDef().update(xXServiceDefObj); - } else { - logger.error("Atlas service-definition does not exist in the Ranger DAO."); - return false; - } - } else { - logger.error("The embedded Atlas service-definition does not exist."); - return false; - } - logger.info("<== PatchForUpdatingAtlasSvcDefAndTagPolicies_J10063.updateAtlasServiceDef()"); - return true; - } - - private void disableAtlasAccessForTagPolicies() throws Exception { - logger.info("==> PatchForUpdatingAtlasSvcDefAndTagPolicies_J10063.disableAtlasAccessForTagPolicies()"); - RangerServiceDef embeddedTagServiceDef = EmbeddedServiceDefsUtil.instance() - .getEmbeddedServiceDef(EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_TAG_NAME); - if (embeddedTagServiceDef != null) { - List xxPolicies = daoMgr.getXXPolicy().findByServiceDefId(embeddedTagServiceDef.getId()); - if (CollectionUtils.isNotEmpty(xxPolicies)) { - for (XXPolicy xxPolicy : xxPolicies) { - RangerPolicy rPolicy = svcStore.getPolicy(xxPolicy.getId()); - if (CollectionUtils.isNotEmpty(rPolicy.getPolicyItems()) || CollectionUtils.isNotEmpty(rPolicy.getAllowExceptions()) - || CollectionUtils.isNotEmpty(rPolicy.getDenyPolicyItems()) || CollectionUtils.isNotEmpty(rPolicy.getDenyExceptions())) { - updateAccessTypeForTagPolicies(rPolicy.getPolicyItems()); - updateAccessTypeForTagPolicies(rPolicy.getAllowExceptions()); - updateAccessTypeForTagPolicies(rPolicy.getDenyPolicyItems()); - updateAccessTypeForTagPolicies(rPolicy.getDenyExceptions()); - svcStore.updatePolicy(rPolicy); - } - } - } - } else { - logger.error("The embedded Tag service-definition does not exist."); - } - - // delete XXAccessTypeDef records of tagDef where name startWith Atlas - List xxAccessTypes = daoMgr.getXXAccessTypeDef().findByServiceDefId(embeddedTagServiceDef.getId()); - for (XXAccessTypeDef xAccess : xxAccessTypes) { - if (xAccess != null && xAccess.getName().startsWith(EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_ATLAS_NAME)) { - svcStore.deleteXXAccessTypeDef(xAccess); - } - } - logger.info("<== PatchForUpdatingAtlasSvcDefAndTagPolicies_J10063.disableAtlasAccessForTagPolicies()"); - } - - private void updateAccessTypeForTagPolicies(List policyItems) throws Exception { - logger.info("==> PatchForDisableAccessTypeForTagPolicies_J10063.updateAccessTypeForTagPolicies() "+policyItems); - if (CollectionUtils.isEmpty(policyItems)) { - logger.info("==> PatchForDisableAccessTypeForTagPolicies_J10063.updateAccessTypeForTagPolicies() policy items collection was null/empty"); - } else { - List removePolicyItem = new ArrayList(); - for (RangerPolicyItem policyItem : policyItems) { - if (policyItem != null && policyItem.getAccesses() != null) { - List accessesToRemove = new ArrayList(); - for (RangerPolicyItemAccess access : policyItem.getAccesses()) { - if (access != null) { - String[] svcDefAccType = access.getType().split(":"); - String serviceDefName = svcDefAccType.length > 0 ? svcDefAccType[0] : null; - if (serviceDefName != null && serviceDefName.equals(EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_ATLAS_NAME)) { - accessesToRemove.add(access); - } - } - } - policyItem.getAccesses().removeAll(accessesToRemove); - } - if(policyItem != null && CollectionUtils.isEmpty(policyItem.getAccesses())) { - removePolicyItem.add(policyItem); - } - } - policyItems.removeAll(removePolicyItem); - } - logger.info("<== PatchForDisableAccessTypeForTagPolicies_J10063.updateAccessTypeForTagPolicies() "+policyItems); - } - - private String mapToJsonString(Map map) { - String ret = null; - if (map != null) { - try { - ret = jsonUtil.readMapToString(map); - } catch (Exception ex) { - logger.warn("mapToJsonString() failed to convert map: " + map, ex); - } - } - return ret; - } - - private Map jsonStringToMap(String jsonStr) { - Map ret = null; - if (!StringUtils.isEmpty(jsonStr)) { - try { - ret = jsonUtil.jsonToMap(jsonStr); - } catch (Exception ex) { - // fallback to earlier format: "name1=value1;name2=value2" - for (String optionString : jsonStr.split(";")) { - if (StringUtils.isEmpty(optionString)) { - continue; - } - String[] nvArr = optionString.split("="); - String name = (nvArr.length > 0) ? nvArr[0].trim() : null; - String value = (nvArr.length > 1) ? nvArr[1].trim() : null; - if (StringUtils.isEmpty(name)) { - continue; - } - if (ret == null) { - ret = new HashMap<>(); - } - ret.put(name, value); - } - } - } - return ret; - } + private static final Logger logger = LoggerFactory.getLogger(PatchForUpdatingAtlasSvcDefAndTagPolicies_J10063.class); + + @Autowired + RangerDaoManager daoMgr; + + @Autowired + JSONUtil jsonUtil; + + @Autowired + StringUtil stringUtil; + + @Autowired + ServiceDBStore svcStore; + + public static void main(String[] args) { + logger.info("main()"); + + try { + PatchForUpdatingAtlasSvcDefAndTagPolicies_J10063 loader = (PatchForUpdatingAtlasSvcDefAndTagPolicies_J10063) CLIUtil.getBean(PatchForUpdatingAtlasSvcDefAndTagPolicies_J10063.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); + } + } + + @Override + public void init() throws Exception { + // Do Nothing + } + + @Override + public void printStats() { + logger.info("PatchForUpdatingAtlasSvcDefAndTagPolicies_J10063 data "); + } + + @Override + public void execLoad() { + logger.info("==> PatchForUpdatingAtlasSvcDefAndTagPolicies_J10063.execLoad()"); + + try { + if (updateAtlasServiceDef()) { + disableAtlasAccessForTagPolicies(); + } + } catch (Exception e) { + logger.error("Error while updateTagServiceDef()data.", e); + + System.exit(1); + } + + logger.info("<== PatchForUpdatingAtlasSvcDefAndTagPolicies_J10063.execLoad()"); + } + + private boolean updateAtlasServiceDef() throws Exception { + logger.info("==> PatchForUpdatingAtlasSvcDefAndTagPolicies_J10063.updateAtlasServiceDef()"); + + RangerServiceDef embeddedAtlasServiceDef = EmbeddedServiceDefsUtil.instance().getEmbeddedServiceDef(EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_ATLAS_NAME); + + if (embeddedAtlasServiceDef != null) { + XXServiceDef xXServiceDefObj = daoMgr.getXXServiceDef().findByName(EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_ATLAS_NAME); + + if (xXServiceDefObj != null) { + String jsonStrUpdate = xXServiceDefObj.getDefOptions(); + Map serviceDefOptionsUpdate = jsonStringToMap(jsonStrUpdate); + + if (serviceDefOptionsUpdate == null) { + serviceDefOptionsUpdate = new HashMap<>(); + } + + serviceDefOptionsUpdate.put(RangerServiceDef.OPTION_ENABLE_TAG_BASED_POLICIES, "false"); + + xXServiceDefObj.setDefOptions(mapToJsonString(serviceDefOptionsUpdate)); + + daoMgr.getXXServiceDef().update(xXServiceDefObj); + } else { + logger.error("Atlas service-definition does not exist in the Ranger DAO."); + return false; + } + } else { + logger.error("The embedded Atlas service-definition does not exist."); + + return false; + } + + logger.info("<== PatchForUpdatingAtlasSvcDefAndTagPolicies_J10063.updateAtlasServiceDef()"); + + return true; + } + + private void disableAtlasAccessForTagPolicies() throws Exception { + logger.info("==> PatchForUpdatingAtlasSvcDefAndTagPolicies_J10063.disableAtlasAccessForTagPolicies()"); + + RangerServiceDef embeddedTagServiceDef = EmbeddedServiceDefsUtil.instance().getEmbeddedServiceDef(EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_TAG_NAME); + + if (embeddedTagServiceDef != null) { + List xxPolicies = daoMgr.getXXPolicy().findByServiceDefId(embeddedTagServiceDef.getId()); + + if (CollectionUtils.isNotEmpty(xxPolicies)) { + for (XXPolicy xxPolicy : xxPolicies) { + RangerPolicy rPolicy = svcStore.getPolicy(xxPolicy.getId()); + + if (CollectionUtils.isNotEmpty(rPolicy.getPolicyItems()) || CollectionUtils.isNotEmpty(rPolicy.getAllowExceptions()) || CollectionUtils.isNotEmpty(rPolicy.getDenyPolicyItems()) || CollectionUtils.isNotEmpty(rPolicy.getDenyExceptions())) { + updateAccessTypeForTagPolicies(rPolicy.getPolicyItems()); + updateAccessTypeForTagPolicies(rPolicy.getAllowExceptions()); + updateAccessTypeForTagPolicies(rPolicy.getDenyPolicyItems()); + updateAccessTypeForTagPolicies(rPolicy.getDenyExceptions()); + + svcStore.updatePolicy(rPolicy); + } + } + } + } else { + logger.error("The embedded Tag service-definition does not exist."); + } + + // delete XXAccessTypeDef records of tagDef where name startWith Atlas + List xxAccessTypes = daoMgr.getXXAccessTypeDef().findByServiceDefId(embeddedTagServiceDef.getId()); + + for (XXAccessTypeDef xAccess : xxAccessTypes) { + if (xAccess != null && xAccess.getName().startsWith(EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_ATLAS_NAME)) { + svcStore.deleteXXAccessTypeDef(xAccess); + } + } + + logger.info("<== PatchForUpdatingAtlasSvcDefAndTagPolicies_J10063.disableAtlasAccessForTagPolicies()"); + } + + private void updateAccessTypeForTagPolicies(List policyItems) throws Exception { + logger.info("==> PatchForDisableAccessTypeForTagPolicies_J10063.updateAccessTypeForTagPolicies() {}", policyItems); + + if (CollectionUtils.isEmpty(policyItems)) { + logger.info("==> PatchForDisableAccessTypeForTagPolicies_J10063.updateAccessTypeForTagPolicies() policy items collection was null/empty"); + } else { + List removePolicyItem = new ArrayList<>(); + + for (RangerPolicyItem policyItem : policyItems) { + if (policyItem != null && policyItem.getAccesses() != null) { + List accessesToRemove = new ArrayList<>(); + + for (RangerPolicyItemAccess access : policyItem.getAccesses()) { + if (access != null) { + String[] svcDefAccType = access.getType().split(":"); + String serviceDefName = svcDefAccType.length > 0 ? svcDefAccType[0] : null; + + if (serviceDefName != null && serviceDefName.equals(EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_ATLAS_NAME)) { + accessesToRemove.add(access); + } + } + } + + policyItem.getAccesses().removeAll(accessesToRemove); + } + + if (policyItem != null && CollectionUtils.isEmpty(policyItem.getAccesses())) { + removePolicyItem.add(policyItem); + } + } + + policyItems.removeAll(removePolicyItem); + } + + logger.info("<== PatchForDisableAccessTypeForTagPolicies_J10063.updateAccessTypeForTagPolicies() {}", policyItems); + } + + private String mapToJsonString(Map map) { + String ret = null; + + if (map != null) { + try { + ret = jsonUtil.readMapToString(map); + } catch (Exception ex) { + logger.warn("mapToJsonString() failed to convert map: {}", map, ex); + } + } + + return ret; + } + + private Map jsonStringToMap(String jsonStr) { + Map ret = null; + + if (!StringUtils.isEmpty(jsonStr)) { + try { + ret = jsonUtil.jsonToMap(jsonStr); + } catch (Exception ex) { + // fallback to earlier format: "name1=value1;name2=value2" + for (String optionString : jsonStr.split(";")) { + if (StringUtils.isEmpty(optionString)) { + continue; + } + + String[] nvArr = optionString.split("="); + String name = (nvArr.length > 0) ? nvArr[0].trim() : null; + String value = (nvArr.length > 1) ? nvArr[1].trim() : null; + + if (StringUtils.isEmpty(name)) { + continue; + } + + if (ret == null) { + ret = new HashMap<>(); + } + ret.put(name, value); + } + } + } + return ret; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/patch/PatchForUpdatingPolicyJson_J10019.java b/security-admin/src/main/java/org/apache/ranger/patch/PatchForUpdatingPolicyJson_J10019.java index 8c288dcaca..a2c8af0fd5 100644 --- a/security-admin/src/main/java/org/apache/ranger/patch/PatchForUpdatingPolicyJson_J10019.java +++ b/security-admin/src/main/java/org/apache/ranger/patch/PatchForUpdatingPolicyJson_J10019.java @@ -6,7 +6,7 @@ * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -17,14 +17,6 @@ package org.apache.ranger.patch; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.ListIterator; -import java.util.Map; -import java.util.Set; - import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.MapUtils; import org.apache.commons.lang.StringUtils; @@ -94,618 +86,595 @@ 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 java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.ListIterator; +import java.util.Map; +import java.util.Set; + /** * Consolidates Ranger policy details into a JSON string and stores it into a * column in x_policy table After running this patch Ranger policy can be * completely read/saved into x_policy table and some related Ref tables (which * maintain ID->String mapping for each policy). - * */ @Component public class PatchForUpdatingPolicyJson_J10019 extends BaseLoader { - private static final Logger logger = LoggerFactory.getLogger(PatchForUpdatingPolicyJson_J10019.class); + private static final Logger logger = LoggerFactory.getLogger(PatchForUpdatingPolicyJson_J10019.class); + + private final Map groupIdMap = new HashMap<>(); + private final Map userIdMap = new HashMap<>(); + private final Map> resourceNameIdMap = new HashMap<>(); + private final Map> accessTypeIdMap = new HashMap<>(); + private final Map> conditionNameIdMap = new HashMap<>(); + private final Map> dataMaskTypeIdMap = new HashMap<>(); + + @Autowired + RangerDaoManager daoMgr; + + @Autowired + ServiceDBStore svcStore; + + @Autowired + @Qualifier(value = "transactionManager") + PlatformTransactionManager txManager; + + @Autowired + PolicyRefUpdater policyRefUpdater; + + @Autowired + XUserMgr xUserMgr; + + @Autowired + RangerDataHistService dataHistService; + + public static void main(String[] args) { + logger.info("main()"); + + try { + PatchForUpdatingPolicyJson_J10019 loader = (PatchForUpdatingPolicyJson_J10019) CLIUtil.getBean(PatchForUpdatingPolicyJson_J10019.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); + } + } + + @Override + public void init() throws Exception { + // Do Nothing + } + + @Override + public void printStats() { + logger.info("updateRangerPolicyTableWithPolicyJson data "); + } + + @Override + public void execLoad() { + logger.info("==> PatchForUpdatingPolicyJson.execLoad()"); + + try { + updateRangerPolicyTableWithPolicyJson(); + } catch (Exception e) { + logger.error("Error while updateRangerPolicyTableWithPolicyJson()", e); + + System.exit(1); + } + + logger.info("<== PatchForUpdatingPolicyJson.execLoad()"); + } + + private void updateRangerPolicyTableWithPolicyJson() throws Exception { + logger.info("==> updateRangerPolicyTableWithPolicyJson() "); + + List allServices = svcStore.getServices(new SearchFilter()); + + if (CollectionUtils.isNotEmpty(allServices)) { + for (RangerService service : allServices) { + XXService dbService = daoMgr.getXXService().getById(service.getId()); + + logger.info("==> Port Policies of service(name={})", dbService.getName()); + + RangerPolicyRetriever policyRetriever = new RangerPolicyRetriever(daoMgr, txManager); + + List policies = policyRetriever.getServicePolicies(dbService); + + if (CollectionUtils.isNotEmpty(policies)) { + TransactionTemplate txTemplate = new TransactionTemplate(txManager); + + for (RangerPolicy policy : policies) { + XXPolicy xPolicy = daoMgr.getXXPolicy().getById(policy.getId()); + if (xPolicy != null && StringUtil.isEmpty(xPolicy.getPolicyText())) { + PolicyUpdaterThread updaterThread = new PolicyUpdaterThread(txTemplate, service, policy); + + updaterThread.setDaemon(true); + updaterThread.start(); + updaterThread.join(); + + String errorMsg = updaterThread.getErrorMsg(); + + if (StringUtils.isNotEmpty(errorMsg)) { + throw new Exception(errorMsg); + } + } + } + } + } + } + + logger.info("<== updateRangerPolicyTableWithPolicyJson() "); + } + + private void portPolicy(String serviceType, RangerPolicy policy) throws Exception { + logger.info("==> portPolicy(id={})", policy.getId()); + + String policyText = JsonUtils.objectToJson(policy); + + if (StringUtils.isEmpty(policyText)) { + throw new Exception("Failed to convert policy to json string. Policy: [id=" + policy.getId() + "; name=" + policy.getName() + "; serviceType=" + serviceType + "]"); + } + + XXPolicyDao policyDao = daoMgr.getXXPolicy(); + XXPolicy dbBean = policyDao.getById(policy.getId()); + + dbBean.setPolicyText(policyText); + + policyDao.update(dbBean); + + try { + Set accesses = new HashSet<>(); + Set users = new HashSet<>(); + Set groups = new HashSet<>(); + Set conditions = new HashSet<>(); + Set dataMasks = new HashSet<>(); + + buildLists(policy.getPolicyItems(), accesses, conditions, users, groups); + buildLists(policy.getDenyPolicyItems(), accesses, conditions, users, groups); + buildLists(policy.getAllowExceptions(), accesses, conditions, users, groups); + buildLists(policy.getDenyExceptions(), accesses, conditions, users, groups); + buildLists(policy.getDataMaskPolicyItems(), accesses, conditions, users, groups); + buildLists(policy.getRowFilterPolicyItems(), accesses, conditions, users, groups); + + buildList(policy.getDataMaskPolicyItems(), dataMasks); + + addResourceDefRef(serviceType, policy); + addUserNameRef(policy.getId(), users); + addGroupNameRef(policy.getId(), groups); + addAccessDefRef(serviceType, policy.getId(), accesses); + addPolicyConditionDefRef(serviceType, policy.getId(), conditions); + addDataMaskDefRef(serviceType, policy.getId(), dataMasks); + + dataHistService.createObjectDataHistory(policy, RangerDataHistService.ACTION_UPDATE); + } catch (Exception e) { + logger.error("portPolicy(id={}) failed!!", policy.getId()); + logger.error("Offending policy:{}", policyText); + + throw e; + } + + logger.info("<== portPolicy(id={})", policy.getId()); + } + + private void addResourceDefRef(String serviceType, RangerPolicy policy) throws Exception { + logger.info("==> addResourceDefRef(id={})", policy.getId()); + + Map serviceDefResourceNameIDMap = resourceNameIdMap.get(serviceType); + + if (serviceDefResourceNameIDMap == null) { + serviceDefResourceNameIDMap = new HashMap<>(); + + resourceNameIdMap.put(serviceType, serviceDefResourceNameIDMap); + + XXServiceDef dbServiceDef = daoMgr.getXXServiceDef().findByName(serviceType); - @Autowired - RangerDaoManager daoMgr; + if (dbServiceDef != null) { + for (XXResourceDef resourceDef : daoMgr.getXXResourceDef().findByServiceDefId(dbServiceDef.getId())) { + serviceDefResourceNameIDMap.put(resourceDef.getName(), resourceDef.getId()); + } + } + } + + Map policyResources = policy.getResources(); + + if (MapUtils.isNotEmpty(policyResources)) { + XXPolicyRefResourceDao policyRefResourceDao = daoMgr.getXXPolicyRefResource(); + Set resourceNames = policyResources.keySet(); + + for (String resourceName : resourceNames) { + Long resourceDefId = serviceDefResourceNameIDMap.get(resourceName); + + if (resourceDefId == null) { + throw new Exception(resourceName + ": unknown resource in policy [id=" + policy.getId() + "; name=" + policy.getName() + "; serviceType=" + serviceType + "]. Known resources: " + serviceDefResourceNameIDMap.keySet()); + } + + // insert policy-id, resourceDefId, resourceName into Ref table + XXPolicyRefResource policyRefResource = new XXPolicyRefResource(); + + policyRefResource.setPolicyId(policy.getId()); + policyRefResource.setResourceDefId(resourceDefId); + policyRefResource.setResourceName(resourceName); + + policyRefResourceDao.create(policyRefResource); + } + } + + logger.info("<== addResourceDefRef(id={})", policy.getId()); + } + + private void addUserNameRef(Long policyId, Set users) throws Exception { + logger.info("==> addUserNameRef(id={})", policyId); + + XXPolicyRefUserDao policyRefUserDao = daoMgr.getXXPolicyRefUser(); + XXUserDao userDao = daoMgr.getXXUser(); + + // insert policy-id, userName into Ref table + for (String user : users) { + Long userId = userIdMap.get(user); + + if (userId == null) { + XXUser userObject = userDao.findByUserName(user); + + if (userObject == null) { + logger.info("user is not found, adding user: {}", user); + + TransactionTemplate txTemplate = new TransactionTemplate(txManager); + + txTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + + try { + txTemplate.execute(status -> { + xUserMgr.createServiceConfigUserSynchronously(user); + + return null; + }); + } catch (Exception exception) { + logger.error("Cannot create ServiceConfigUser({})", user, exception); + } + + userObject = userDao.findByUserName(user); + + if (userObject == null) { + throw new Exception(user + ": unknown user in policy [id=" + policyId + "]"); + } + } + + userId = userObject.getId(); + + logger.info("userId:{}", userId); + + userIdMap.put(user, userId); + } + + XXPolicyRefUser policyRefUser = new XXPolicyRefUser(); + + policyRefUser.setPolicyId(policyId); + policyRefUser.setUserName(user); + policyRefUser.setUserId(userId); + + policyRefUserDao.create(policyRefUser); + } + + logger.info("<== addUserNameRef(id={})", policyId); + } + + private void addGroupNameRef(Long policyId, Set groups) throws Exception { + logger.info("==> addGroupNameRef(id={})", policyId); + + // insert policy-id, groupName into Ref table + XXPolicyRefGroupDao policyRefGroupDao = daoMgr.getXXPolicyRefGroup(); + XXGroupDao groupDao = daoMgr.getXXGroup(); - @Autowired - ServiceDBStore svcStore; + for (String group : groups) { + Long groupId = groupIdMap.get(group); - @Autowired - @Qualifier(value = "transactionManager") - PlatformTransactionManager txManager; + if (groupId == null) { + XXGroup groupObject = groupDao.findByGroupName(group); - @Autowired - PolicyRefUpdater policyRefUpdater; + if (groupObject == null) { + throw new Exception(group + ": unknown group in policy [id=" + policyId + "]"); + } + + groupId = groupObject.getId(); + + groupIdMap.put(group, groupId); + } + + XXPolicyRefGroup policyRefGroup = new XXPolicyRefGroup(); + + policyRefGroup.setPolicyId(policyId); + policyRefGroup.setGroupName(group); + policyRefGroup.setGroupId(groupId); + + policyRefGroupDao.create(policyRefGroup); + } + + logger.info("<== addGroupNameRef(id={})", policyId); + } + + private void addAccessDefRef(String serviceType, Long policyId, Set accesses) throws Exception { + logger.info("==> addAccessDefRef(id={})", policyId); + // insert policy-id, accessName into Ref table - @Autowired - XUserMgr xUserMgr; + Map serviceDefAccessTypeIDMap = accessTypeIdMap.get(serviceType); - @Autowired - RangerDataHistService dataHistService; + if (serviceDefAccessTypeIDMap == null) { + serviceDefAccessTypeIDMap = new HashMap<>(); - private final Map groupIdMap = new HashMap<>(); - private final Map userIdMap = new HashMap<>(); - private final Map> resourceNameIdMap = new HashMap<>(); - private final Map> accessTypeIdMap = new HashMap<>(); - private final Map> conditionNameIdMap = new HashMap<>(); - private final Map> dataMaskTypeIdMap = new HashMap<>(); - - public static void main(String[] args) { - logger.info("main()"); - try { - PatchForUpdatingPolicyJson_J10019 loader = (PatchForUpdatingPolicyJson_J10019) CLIUtil.getBean(PatchForUpdatingPolicyJson_J10019.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); - } - } - - @Override - public void init() throws Exception { - // Do Nothing - } - - @Override - public void execLoad() { - logger.info("==> PatchForUpdatingPolicyJson.execLoad()"); - - try { - updateRangerPolicyTableWithPolicyJson(); - } catch (Exception e) { - logger.error("Error while updateRangerPolicyTableWithPolicyJson()", e); - System.exit(1); - } - - logger.info("<== PatchForUpdatingPolicyJson.execLoad()"); - } - - @Override - public void printStats() { - logger.info("updateRangerPolicyTableWithPolicyJson data "); - } - - private void updateRangerPolicyTableWithPolicyJson() throws Exception { - logger.info("==> updateRangerPolicyTableWithPolicyJson() "); - - List allServices = svcStore.getServices(new SearchFilter()); - - if (CollectionUtils.isNotEmpty(allServices)) { - for (RangerService service : allServices) { - XXService dbService = daoMgr.getXXService().getById(service.getId()); - - logger.info("==> Port Policies of service(name=" + dbService.getName() + ")"); - - RangerPolicyRetriever policyRetriever = new RangerPolicyRetriever(daoMgr, txManager); - - List policies = policyRetriever.getServicePolicies(dbService); - - if (CollectionUtils.isNotEmpty(policies)) { - TransactionTemplate txTemplate = new TransactionTemplate(txManager); - - for (RangerPolicy policy : policies) { - XXPolicy xPolicy = daoMgr.getXXPolicy().getById(policy.getId()); - if (xPolicy != null && StringUtil.isEmpty(xPolicy.getPolicyText())) { - - PolicyUpdaterThread updaterThread = new PolicyUpdaterThread(txTemplate, service, policy); - updaterThread.setDaemon(true); - updaterThread.start(); - updaterThread.join(); - - String errorMsg = updaterThread.getErrorMsg(); - if (StringUtils.isNotEmpty(errorMsg)) { - throw new Exception(errorMsg); - } - } - } - } - } - } - - logger.info("<== updateRangerPolicyTableWithPolicyJson() "); - } - - private class PolicyUpdaterThread extends Thread { - final TransactionTemplate txTemplate; - final RangerService service; - final RangerPolicy policy; - String errorMsg; - - PolicyUpdaterThread(TransactionTemplate txTemplate, final RangerService service, final RangerPolicy policy) { - this.txTemplate = txTemplate; - this.service = service; - this.policy = policy; - this.errorMsg = null; - } - - public String getErrorMsg() { - return errorMsg; - } - - @Override - public void run() { - errorMsg = txTemplate.execute(new TransactionCallback() { - @Override - public String doInTransaction(TransactionStatus status) { - String ret = null; - try { - policyRefUpdater.cleanupRefTables(policy); - portPolicy(service.getType(), policy); - } catch (Throwable e) { - logger.error("PortPolicy failed for policy:[" + policy + "]", e); - ret = e.toString(); - } - return ret; - } - }); - } - } - - private void portPolicy(String serviceType, RangerPolicy policy) throws Exception { - logger.info("==> portPolicy(id=" + policy.getId() + ")"); - - String policyText = JsonUtils.objectToJson(policy); - - if (StringUtils.isEmpty(policyText)) { - throw new Exception("Failed to convert policy to json string. Policy: [id=" + policy.getId() + "; name=" + policy.getName() + "; serviceType=" + serviceType + "]"); - } - - XXPolicyDao policyDao = daoMgr.getXXPolicy(); - XXPolicy dbBean = policyDao.getById(policy.getId()); - - dbBean.setPolicyText(policyText); - - policyDao.update(dbBean); - - try { - Set accesses = new HashSet<>(); - Set users = new HashSet<>(); - Set groups = new HashSet<>(); - Set conditions = new HashSet<>(); - Set dataMasks = new HashSet<>(); - - buildLists(policy.getPolicyItems(), accesses, conditions, users, groups); - buildLists(policy.getDenyPolicyItems(), accesses, conditions, users, groups); - buildLists(policy.getAllowExceptions(), accesses, conditions, users, groups); - buildLists(policy.getDenyExceptions(), accesses, conditions, users, groups); - buildLists(policy.getDataMaskPolicyItems(), accesses, conditions, users, groups); - buildLists(policy.getRowFilterPolicyItems(), accesses, conditions, users, groups); - - buildList(policy.getDataMaskPolicyItems(), dataMasks); - - addResourceDefRef(serviceType, policy); - addUserNameRef(policy.getId(), users); - addGroupNameRef(policy.getId(), groups); - addAccessDefRef(serviceType, policy.getId(), accesses); - addPolicyConditionDefRef(serviceType, policy.getId(), conditions); - addDataMaskDefRef(serviceType, policy.getId(), dataMasks); - dataHistService.createObjectDataHistory(policy, RangerDataHistService.ACTION_UPDATE); - } catch (Exception e) { - logger.error("portPoliry(id=" + policy.getId() +") failed!!"); - logger.error("Offending policy:" + policyText); - throw e; - } - - logger.info("<== portPolicy(id=" + policy.getId() + ")"); - } - - private void addResourceDefRef(String serviceType, RangerPolicy policy) throws Exception { - logger.info("==> addResourceDefRef(id=" + policy.getId() + ")"); - - Map serviceDefResourceNameIDMap = resourceNameIdMap.get(serviceType); - - if (serviceDefResourceNameIDMap == null) { - serviceDefResourceNameIDMap = new HashMap<>(); - - resourceNameIdMap.put(serviceType, serviceDefResourceNameIDMap); - - XXServiceDef dbServiceDef = daoMgr.getXXServiceDef().findByName(serviceType); - if (dbServiceDef != null) { - for (XXResourceDef resourceDef : daoMgr.getXXResourceDef().findByServiceDefId(dbServiceDef.getId())) { - serviceDefResourceNameIDMap.put(resourceDef.getName(), resourceDef.getId()); - } - } - } - - Map policyResources = policy.getResources(); - - if (MapUtils.isNotEmpty(policyResources)) { - XXPolicyRefResourceDao policyRefResourceDao = daoMgr.getXXPolicyRefResource(); - Set resourceNames = policyResources.keySet(); - - for (String resourceName : resourceNames) { - Long resourceDefId = serviceDefResourceNameIDMap.get(resourceName); - - if (resourceDefId == null) { - throw new Exception(resourceName + ": unknown resource in policy [id=" + policy.getId() + "; name=" + policy.getName() + "; serviceType=" + serviceType + "]. Known resources: " + serviceDefResourceNameIDMap.keySet()); - } - - // insert policy-id, resourceDefId, resourceName into Ref table - XXPolicyRefResource policyRefResource = new XXPolicyRefResource(); - - policyRefResource.setPolicyId(policy.getId()); - policyRefResource.setResourceDefId(resourceDefId); - policyRefResource.setResourceName(resourceName); + accessTypeIdMap.put(serviceType, serviceDefAccessTypeIDMap); - policyRefResourceDao.create(policyRefResource); - } - } + XXServiceDef dbServiceDef = daoMgr.getXXServiceDef().findByName(serviceType); - logger.info("<== addResourceDefRef(id=" + policy.getId() + ")"); - } + if (dbServiceDef != null) { + for (XXAccessTypeDef accessTypeDef : daoMgr.getXXAccessTypeDef().findByServiceDefId(dbServiceDef.getId())) { + serviceDefAccessTypeIDMap.put(accessTypeDef.getName(), accessTypeDef.getId()); + } + } + } - private void addUserNameRef(Long policyId, Set users) throws Exception { - logger.info("==> addUserNameRef(id=" + policyId + ")"); + XXPolicyRefAccessTypeDao policyRefAccessTypeDao = daoMgr.getXXPolicyRefAccessType(); - XXPolicyRefUserDao policyRefUserDao = daoMgr.getXXPolicyRefUser(); - XXUserDao userDao = daoMgr.getXXUser(); + for (String access : accesses) { + Long accessTypeDefId = serviceDefAccessTypeIDMap.get(access); - // insert policy-id, userName into Ref table - for (String user : users) { - Long userId = userIdMap.get(user); + if (accessTypeDefId == null) { + throw new Exception(access + ": unknown accessType in policy [id=" + policyId + "; serviceType=" + serviceType + "]. Known accessTypes: " + serviceDefAccessTypeIDMap.keySet()); + } - if (userId == null) { - XXUser userObject = userDao.findByUserName(user); + XXPolicyRefAccessType policyRefAccessType = new XXPolicyRefAccessType(); - if (userObject == null) { - logger.info(user +" user is not found, adding user: "+user); - TransactionTemplate txTemplate = new TransactionTemplate(txManager); - txTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); - try { - txTemplate.execute(new TransactionCallback() { - @Override - public Object doInTransaction(TransactionStatus status) { - xUserMgr.createServiceConfigUserSynchronously(user); - return null; - } - }); - } catch(Exception exception) { - logger.error("Cannot create ServiceConfigUser(" + user + ")", exception); - } - userObject = userDao.findByUserName(user); - if (userObject == null) { - throw new Exception(user + ": unknown user in policy [id=" + policyId + "]"); - } - } + policyRefAccessType.setPolicyId(policyId); + policyRefAccessType.setAccessTypeName(access); + policyRefAccessType.setAccessDefId(accessTypeDefId); - userId = userObject.getId(); - logger.info("userId:"+userId); + policyRefAccessTypeDao.create(policyRefAccessType); + } - userIdMap.put(user, userId); - } + logger.info("<== addAccessDefRef(id={})", policyId); + } - XXPolicyRefUser policyRefUser = new XXPolicyRefUser(); + private void addPolicyConditionDefRef(String serviceType, Long policyId, Set conditions) throws Exception { + logger.info("==> addPolicyConditionDefRef(id={})", policyId); + // insert policy-id, conditionName into Ref table - policyRefUser.setPolicyId(policyId); - policyRefUser.setUserName(user); - policyRefUser.setUserId(userId); + Map serviceDefConditionNameIDMap = conditionNameIdMap.get(serviceType); - policyRefUserDao.create(policyRefUser); - } + if (serviceDefConditionNameIDMap == null) { + serviceDefConditionNameIDMap = new HashMap<>(); - logger.info("<== addUserNameRef(id=" + policyId + ")"); - } + conditionNameIdMap.put(serviceType, serviceDefConditionNameIDMap); - private void addGroupNameRef(Long policyId, Set groups) throws Exception { - logger.info("==> addGroupNameRef(id=" + policyId + ")"); + XXServiceDef dbServiceDef = daoMgr.getXXServiceDef().findByName(serviceType); - // insert policy-id, groupName into Ref table - XXPolicyRefGroupDao policyRefGroupDao = daoMgr.getXXPolicyRefGroup(); - XXGroupDao groupDao = daoMgr.getXXGroup(); + if (dbServiceDef != null) { + for (XXPolicyConditionDef conditionDef : daoMgr.getXXPolicyConditionDef().findByServiceDefId(dbServiceDef.getId())) { + serviceDefConditionNameIDMap.put(conditionDef.getName(), conditionDef.getId()); + } + } + } - for (String group : groups) { - Long groupId = groupIdMap.get(group); + XXPolicyRefConditionDao policyRefConditionDao = daoMgr.getXXPolicyRefCondition(); - if (groupId == null) { - XXGroup groupObject = groupDao.findByGroupName(group); + for (String condition : conditions) { + Long conditionDefId = serviceDefConditionNameIDMap.get(condition); - if (groupObject == null) { - throw new Exception(group + ": unknown group in policy [id=" + policyId + "]"); - } + if (conditionDefId == null) { + throw new Exception(condition + ": unknown condition in policy [id=" + policyId + "; serviceType=" + serviceType + "]. Known conditions are: " + serviceDefConditionNameIDMap.keySet()); + } + + XXPolicyRefCondition policyRefCondition = new XXPolicyRefCondition(); - groupId = groupObject.getId(); + policyRefCondition.setPolicyId(policyId); + policyRefCondition.setConditionName(condition); + policyRefCondition.setConditionDefId(conditionDefId); - groupIdMap.put(group, groupId); - } + policyRefConditionDao.create(policyRefCondition); + } - XXPolicyRefGroup policyRefGroup = new XXPolicyRefGroup(); + logger.info("<== addPolicyConditionDefRef(id={})", policyId); + } - policyRefGroup.setPolicyId(policyId); - policyRefGroup.setGroupName(group); - policyRefGroup.setGroupId(groupId); + private void addDataMaskDefRef(String serviceType, Long policyId, Set datamasks) throws Exception { + logger.info("==> addDataMaskDefRef(id={})", policyId); - policyRefGroupDao.create(policyRefGroup); - } + // insert policy-id, datamaskName into Ref table - logger.info("<== addGroupNameRef(id=" + policyId + ")"); + Map serviceDefDataMaskTypeIDMap = dataMaskTypeIdMap.get(serviceType); - } + if (serviceDefDataMaskTypeIDMap == null) { + serviceDefDataMaskTypeIDMap = new HashMap<>(); - private void addAccessDefRef(String serviceType, Long policyId, Set accesses) throws Exception { - logger.info("==> addAccessDefRef(id=" + policyId + ")"); - // insert policy-id, accessName into Ref table + dataMaskTypeIdMap.put(serviceType, serviceDefDataMaskTypeIDMap); - Map serviceDefAccessTypeIDMap = accessTypeIdMap.get(serviceType); + XXServiceDef dbServiceDef = daoMgr.getXXServiceDef().findByName(serviceType); + + if (dbServiceDef != null) { + for (XXDataMaskTypeDef dataMaskTypeDef : daoMgr.getXXDataMaskTypeDef().findByServiceDefId(dbServiceDef.getId())) { + serviceDefDataMaskTypeIDMap.put(dataMaskTypeDef.getName(), dataMaskTypeDef.getId()); + } + } + } - if (serviceDefAccessTypeIDMap == null) { - serviceDefAccessTypeIDMap = new HashMap<>(); + XXPolicyRefDataMaskTypeDao policyRefDataMaskTypeDao = daoMgr.getXXPolicyRefDataMaskType(); - accessTypeIdMap.put(serviceType, serviceDefAccessTypeIDMap); + for (String datamask : datamasks) { + Long dataMaskTypeId = serviceDefDataMaskTypeIDMap.get(datamask); - XXServiceDef dbServiceDef = daoMgr.getXXServiceDef().findByName(serviceType); - if (dbServiceDef != null) { - for (XXAccessTypeDef accessTypeDef : daoMgr.getXXAccessTypeDef().findByServiceDefId(dbServiceDef.getId())) { - serviceDefAccessTypeIDMap.put(accessTypeDef.getName(), accessTypeDef.getId()); - } - } - } + if (dataMaskTypeId == null) { + throw new Exception(datamask + ": unknown dataMaskType in policy [id=" + policyId + "; serviceType=" + serviceType + "]. Known dataMaskTypes " + serviceDefDataMaskTypeIDMap.keySet()); + } - XXPolicyRefAccessTypeDao policyRefAccessTypeDao = daoMgr.getXXPolicyRefAccessType(); + XXPolicyRefDataMaskType policyRefDataMaskType = new XXPolicyRefDataMaskType(); - for (String access : accesses) { - Long accessTypeDefId = serviceDefAccessTypeIDMap.get(access); + policyRefDataMaskType.setPolicyId(policyId); + policyRefDataMaskType.setDataMaskTypeName(datamask); + policyRefDataMaskType.setDataMaskDefId(dataMaskTypeId); - if (accessTypeDefId == null) { - throw new Exception(access + ": unknown accessType in policy [id=" + policyId + "; serviceType=" + serviceType + "]. Known accessTypes: " + serviceDefAccessTypeIDMap.keySet()); - } + policyRefDataMaskTypeDao.create(policyRefDataMaskType); + } - XXPolicyRefAccessType policyRefAccessType = new XXPolicyRefAccessType(); + logger.info("<== addDataMaskDefRef(id={})", policyId); + } - policyRefAccessType.setPolicyId(policyId); - policyRefAccessType.setAccessTypeName(access); - policyRefAccessType.setAccessDefId(accessTypeDefId); + private void buildLists(List policyItems, Set accesses, Set conditions, Set users, Set groups) { + for (RangerPolicyItem item : policyItems) { + for (RangerPolicyItemAccess policyAccess : item.getAccesses()) { + accesses.add(policyAccess.getType()); + } - policyRefAccessTypeDao.create(policyRefAccessType); - } + for (RangerPolicyItemCondition policyCondition : item.getConditions()) { + conditions.add(policyCondition.getType()); + } - logger.info("<== addAccessDefRef(id=" + policyId + ")"); - } + users.addAll(item.getUsers()); + groups.addAll(item.getGroups()); + } + } - private void addPolicyConditionDefRef(String serviceType, Long policyId, Set conditions) throws Exception { - logger.info("==> addPolicyConditionDefRef(id=" + policyId + ")"); - // insert policy-id, conditionName into Ref table + private void buildList(List dataMaskPolicyItems, Set dataMasks) { + for (RangerDataMaskPolicyItem datMaskPolicyItem : dataMaskPolicyItems) { + dataMasks.add(datMaskPolicyItem.getDataMaskInfo().getDataMaskType()); + } + } - Map serviceDefConditionNameIDMap = conditionNameIdMap.get(serviceType); + private static class RangerPolicyRetriever { + static final Logger LOG = LoggerFactory.getLogger(RangerPolicyRetriever.class); + static final Logger PERF_LOG = RangerPerfTracer.getPerfLogger("db.RangerPolicyRetriever"); - if (serviceDefConditionNameIDMap == null) { - serviceDefConditionNameIDMap = new HashMap<>(); + private final RangerDaoManager daoMgr; + private final LookupCache lookupCache = new LookupCache(); + private final TransactionTemplate txTemplate; - conditionNameIdMap.put(serviceType, serviceDefConditionNameIDMap); + RangerPolicyRetriever(RangerDaoManager daoMgr, PlatformTransactionManager txManager) { + this.daoMgr = daoMgr; - XXServiceDef dbServiceDef = daoMgr.getXXServiceDef().findByName(serviceType); - if (dbServiceDef != null) { - for (XXPolicyConditionDef conditionDef : daoMgr.getXXPolicyConditionDef().findByServiceDefId(dbServiceDef.getId())) { - serviceDefConditionNameIDMap.put(conditionDef.getName(), conditionDef.getId()); - } - } - } + if (txManager != null) { + this.txTemplate = new TransactionTemplate(txManager); - XXPolicyRefConditionDao policyRefConditionDao = daoMgr.getXXPolicyRefCondition(); + this.txTemplate.setReadOnly(true); + } else { + this.txTemplate = null; + } + } - for (String condition : conditions) { - Long conditionDefId = serviceDefConditionNameIDMap.get(condition); + static List asList(XXPolicy policy) { + List ret = new ArrayList<>(); - if (conditionDefId == null) { - throw new Exception(condition + ": unknown condition in policy [id=" + policyId + "; serviceType=" + serviceType + "]. Known conditions are: " + serviceDefConditionNameIDMap.keySet()); - } + if (policy != null) { + ret.add(policy); + } - XXPolicyRefCondition policyRefCondition = new XXPolicyRefCondition(); + return ret; + } - policyRefCondition.setPolicyId(policyId); - policyRefCondition.setConditionName(condition); - policyRefCondition.setConditionDefId(conditionDefId); + public List getServicePolicies(final XXService xService) throws InterruptedException { + String serviceName = xService == null ? null : xService.getName(); + Long serviceId = xService == null ? null : xService.getId(); - policyRefConditionDao.create(policyRefCondition); - } + LOG.debug("==> RangerPolicyRetriever.getServicePolicies(serviceName={}, serviceId={}", serviceName, serviceId); - logger.info("<== addPolicyConditionDefRef(id=" + policyId + ")"); - } + List ret = null; + RangerPerfTracer perf = null; - private void addDataMaskDefRef(String serviceType, Long policyId, Set datamasks) throws Exception { - logger.info("==> addDataMaskDefRef(id=" + policyId + ")"); + if (RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { + perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "RangerPolicyRetriever.getServicePolicies(serviceName=" + serviceName + ",serviceId=" + serviceId + ")"); + } - // insert policy-id, datamaskName into Ref table + if (xService != null) { + if (txTemplate == null) { + LOG.debug("Transaction Manager is null; Retrieving policies in the existing transaction"); - Map serviceDefDataMaskTypeIDMap = dataMaskTypeIdMap.get(serviceType); + RetrieverContext ctx = new RetrieverContext(xService); - if (serviceDefDataMaskTypeIDMap == null) { - serviceDefDataMaskTypeIDMap = new HashMap<>(); + ret = ctx.getAllPolicies(); + } else { + LOG.debug("Retrieving policies in a new, read-only transaction"); - dataMaskTypeIdMap.put(serviceType, serviceDefDataMaskTypeIDMap); + PolicyLoaderThread t = new PolicyLoaderThread(txTemplate, xService); + t.start(); + t.join(); - XXServiceDef dbServiceDef = daoMgr.getXXServiceDef().findByName(serviceType); - if (dbServiceDef != null) { - for (XXDataMaskTypeDef dataMaskTypeDef : daoMgr.getXXDataMaskTypeDef().findByServiceDefId(dbServiceDef.getId())) { - serviceDefDataMaskTypeIDMap.put(dataMaskTypeDef.getName(), dataMaskTypeDef.getId()); - } - } - } + ret = t.getPolicies(); + } + } else { + LOG.debug("RangerPolicyRetriever.getServicePolicies(xService={}): invalid parameter", xService); + } - XXPolicyRefDataMaskTypeDao policyRefDataMaskTypeDao = daoMgr.getXXPolicyRefDataMaskType(); + RangerPerfTracer.log(perf); - for (String datamask : datamasks) { - Long dataMaskTypeId = serviceDefDataMaskTypeIDMap.get(datamask); + LOG.debug("<== RangerPolicyRetriever.getServicePolicies(serviceName={}, serviceId={}): policyCount={}", (ret == null ? 0 : ret.size()), serviceName, serviceId); - if (dataMaskTypeId == null) { - throw new Exception(datamask + ": unknown dataMaskType in policy [id=" + policyId + "; serviceType=" + serviceType + "]. Known dataMaskTypes " + serviceDefDataMaskTypeIDMap.keySet()); - } + return ret; + } - XXPolicyRefDataMaskType policyRefDataMaskType = new XXPolicyRefDataMaskType(); + private class PolicyLoaderThread extends Thread { + final TransactionTemplate txTemplate; + final XXService xService; + List policies; - policyRefDataMaskType.setPolicyId(policyId); - policyRefDataMaskType.setDataMaskTypeName(datamask); - policyRefDataMaskType.setDataMaskDefId(dataMaskTypeId); + PolicyLoaderThread(TransactionTemplate txTemplate, final XXService xService) { + this.txTemplate = txTemplate; + this.xService = xService; + } - policyRefDataMaskTypeDao.create(policyRefDataMaskType); - } + public List getPolicies() { + return policies; + } - logger.info("<== addDataMaskDefRef(id=" + policyId + ")"); + @Override + public void run() { + txTemplate.setReadOnly(true); + policies = txTemplate.execute(status -> { + RetrieverContext ctx = new RetrieverContext(xService); - } + return ctx.getAllPolicies(); + }); + } + } + + class LookupCache { + final Map userNames = new HashMap<>(); + final Map userScreenNames = new HashMap<>(); + final Map groupNames = new HashMap<>(); + final Map accessTypes = new HashMap<>(); + final Map conditions = new HashMap<>(); + final Map resourceDefs = new HashMap<>(); + final Map dataMasks = new HashMap<>(); + final Map policyLabels = new HashMap<>(); + + String getUserName(Long userId) { + String ret = null; - private void buildLists(List policyItems, Set accesses, Set conditions, Set users, Set groups) { - for (RangerPolicyItem item : policyItems) { - for (RangerPolicyItemAccess policyAccess : item.getAccesses()) { - accesses.add(policyAccess.getType()); - } + if (userId != null) { + ret = userNames.get(userId); - for (RangerPolicyItemCondition policyCondition : item.getConditions()) { - conditions.add(policyCondition.getType()); - } + if (ret == null) { + XXUser user = daoMgr.getXXUser().getById(userId); - users.addAll(item.getUsers()); - groups.addAll(item.getGroups()); - } - } + if (user != null) { + ret = user.getName(); // Name is `loginId` - private void buildList(List dataMaskPolicyItems, Set dataMasks) { - for (RangerDataMaskPolicyItem datMaskPolicyItem : dataMaskPolicyItems) { - dataMasks.add(datMaskPolicyItem.getDataMaskInfo().getDataMaskType()); - } - } + userNames.put(userId, ret); + } + } + } - static private class RangerPolicyRetriever { - static final Logger LOG = LoggerFactory.getLogger(RangerPolicyRetriever.class); - static final Logger PERF_LOG = RangerPerfTracer.getPerfLogger("db.RangerPolicyRetriever"); - - private final RangerDaoManager daoMgr; - private final LookupCache lookupCache = new LookupCache(); - - private final PlatformTransactionManager txManager; - private final TransactionTemplate txTemplate; - - RangerPolicyRetriever(RangerDaoManager daoMgr, PlatformTransactionManager txManager) { - this.daoMgr = daoMgr; - this.txManager = txManager; - - if (this.txManager != null) { - this.txTemplate = new TransactionTemplate(this.txManager); - - this.txTemplate.setReadOnly(true); - } else { - this.txTemplate = null; - } - } - - private class PolicyLoaderThread extends Thread { - final TransactionTemplate txTemplate; - final XXService xService; - List policies; - - PolicyLoaderThread(TransactionTemplate txTemplate, final XXService xService) { - this.txTemplate = txTemplate; - this.xService = xService; - } - - public List getPolicies() { - return policies; - } - - @Override - public void run() { - txTemplate.setReadOnly(true); - policies = txTemplate.execute(new TransactionCallback>() { - @Override - public List doInTransaction(TransactionStatus status) { - RetrieverContext ctx = new RetrieverContext(xService); - return ctx.getAllPolicies(); - } - }); - } - } - - public List getServicePolicies(final XXService xService) throws InterruptedException { - String serviceName = xService == null ? null : xService.getName(); - Long serviceId = xService == null ? null : xService.getId(); - - if (LOG.isDebugEnabled()) { - LOG.debug("==> RangerPolicyRetriever.getServicePolicies(serviceName=" + serviceName + ", serviceId=" + serviceId + ")"); - } - - List ret = null; - RangerPerfTracer perf = null; - - if (RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { - perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "RangerPolicyRetriever.getServicePolicies(serviceName=" + serviceName + ",serviceId=" + serviceId + ")"); - } - - if (xService != null) { - if (txTemplate == null) { - if (LOG.isDebugEnabled()) { - LOG.debug("Transaction Manager is null; Retrieving policies in the existing transaction"); - } - - RetrieverContext ctx = new RetrieverContext(xService); - - ret = ctx.getAllPolicies(); - } else { - if (LOG.isDebugEnabled()) { - LOG.debug("Retrieving policies in a new, read-only transaction"); - } - - PolicyLoaderThread t = new PolicyLoaderThread(txTemplate, xService); - t.start(); - t.join(); - ret = t.getPolicies(); - } - } else { - if (LOG.isDebugEnabled()) { - LOG.debug("RangerPolicyRetriever.getServicePolicies(xService=" + xService + "): invalid parameter"); - } - } - - RangerPerfTracer.log(perf); - - if (LOG.isDebugEnabled()) { - LOG.debug("<== RangerPolicyRetriever.getServicePolicies(serviceName=" + serviceName + ", serviceId=" + serviceId + "): policyCount=" + (ret == null ? 0 : ret.size())); - } - - return ret; - } - - class LookupCache { - final Map userNames = new HashMap(); - final Map userScreenNames = new HashMap(); - final Map groupNames = new HashMap(); - final Map accessTypes = new HashMap(); - final Map conditions = new HashMap(); - final Map resourceDefs = new HashMap(); - final Map dataMasks = new HashMap(); - final Map policyLabels = new HashMap(); - - String getUserName(Long userId) { - String ret = null; - - if (userId != null) { - ret = userNames.get(userId); - - if (ret == null) { - XXUser user = daoMgr.getXXUser().getById(userId); - - if (user != null) { - ret = user.getName(); // Name is `loginId` - - userNames.put(userId, ret); - } - } - } - - return ret; - } + return ret; + } String getPolicyLabelName(Long policyLabelId) { String ret = null; @@ -727,542 +696,569 @@ String getPolicyLabelName(Long policyLabelId) { return ret; } - String getUserScreenName(Long userId) { - String ret = null; + String getUserScreenName(Long userId) { + String ret = null; + + if (userId != null) { + ret = userScreenNames.get(userId); + + if (ret == null) { + XXPortalUser user = daoMgr.getXXPortalUser().getById(userId); + + if (user != null) { + ret = user.getPublicScreenName(); + + if (StringUtil.isEmpty(ret)) { + ret = user.getFirstName(); + + if (StringUtil.isEmpty(ret)) { + ret = user.getLoginId(); + } else { + if (!StringUtil.isEmpty(user.getLastName())) { + ret += (" " + user.getLastName()); + } + } + } + + if (ret != null) { + userScreenNames.put(userId, ret); + } + } + } + } + + return ret; + } + + String getGroupName(Long groupId) { + String ret = null; + + if (groupId != null) { + ret = groupNames.get(groupId); - if (userId != null) { - ret = userScreenNames.get(userId); + if (ret == null) { + XXGroup group = daoMgr.getXXGroup().getById(groupId); + + if (group != null) { + ret = group.getName(); + + groupNames.put(groupId, ret); + } + } + } - if (ret == null) { - XXPortalUser user = daoMgr.getXXPortalUser().getById(userId); + return ret; + } - if (user != null) { - ret = user.getPublicScreenName(); + String getAccessType(Long accessTypeId) { + String ret = null; - if (StringUtil.isEmpty(ret)) { - ret = user.getFirstName(); + if (accessTypeId != null) { + ret = accessTypes.get(accessTypeId); - if (StringUtil.isEmpty(ret)) { - ret = user.getLoginId(); - } else { - if (!StringUtil.isEmpty(user.getLastName())) { - ret += (" " + user.getLastName()); - } - } - } + if (ret == null) { + XXAccessTypeDef xAccessType = daoMgr.getXXAccessTypeDef().getById(accessTypeId); - if (ret != null) { - userScreenNames.put(userId, ret); - } - } - } - } + if (xAccessType != null) { + ret = xAccessType.getName(); - return ret; - } + accessTypes.put(accessTypeId, ret); + } else { + LOG.warn("getAccessType(): Can't find name for accessTypeId {}. This will cause Ranger policy migration to fail. Please check if all service-defs are migrated correctly!", accessTypeId); + } + } + } - String getGroupName(Long groupId) { - String ret = null; + return ret; + } - if (groupId != null) { - ret = groupNames.get(groupId); + String getConditionType(Long conditionDefId) { + String ret = null; - if (ret == null) { - XXGroup group = daoMgr.getXXGroup().getById(groupId); + if (conditionDefId != null) { + ret = conditions.get(conditionDefId); - if (group != null) { - ret = group.getName(); + if (ret == null) { + XXPolicyConditionDef xPolicyConditionDef = daoMgr.getXXPolicyConditionDef().getById(conditionDefId); - groupNames.put(groupId, ret); - } - } - } + if (xPolicyConditionDef != null) { + ret = xPolicyConditionDef.getName(); - return ret; - } + conditions.put(conditionDefId, ret); + } + } + } - String getAccessType(Long accessTypeId) { - String ret = null; + return ret; + } - if (accessTypeId != null) { - ret = accessTypes.get(accessTypeId); + String getResourceName(Long resourceDefId) { + String ret = null; - if (ret == null) { - XXAccessTypeDef xAccessType = daoMgr.getXXAccessTypeDef().getById(accessTypeId); + if (resourceDefId != null) { + ret = resourceDefs.get(resourceDefId); - if (xAccessType != null) { - ret = xAccessType.getName(); + if (ret == null) { + XXResourceDef xResourceDef = daoMgr.getXXResourceDef().getById(resourceDefId); - accessTypes.put(accessTypeId, ret); - } else { - LOG.warn("getAccessType(): Canot find name for accessTypeId " + accessTypeId + ". This will cause Ranger policy migration to fail. Please check if all service-defs are migrated correctly!"); - } - } - } + if (xResourceDef != null) { + ret = xResourceDef.getName(); - return ret; - } + resourceDefs.put(resourceDefId, ret); + } + } + } - String getConditionType(Long conditionDefId) { - String ret = null; + return ret; + } - if (conditionDefId != null) { - ret = conditions.get(conditionDefId); + String getDataMaskName(Long dataMaskDefId) { + String ret = null; - if (ret == null) { - XXPolicyConditionDef xPolicyConditionDef = daoMgr.getXXPolicyConditionDef() - .getById(conditionDefId); + if (dataMaskDefId != null) { + ret = dataMasks.get(dataMaskDefId); - if (xPolicyConditionDef != null) { - ret = xPolicyConditionDef.getName(); + if (ret == null) { + XXDataMaskTypeDef xDataMaskDef = daoMgr.getXXDataMaskTypeDef().getById(dataMaskDefId); - conditions.put(conditionDefId, ret); - } - } - } + if (xDataMaskDef != null) { + ret = xDataMaskDef.getName(); - return ret; - } + dataMasks.put(dataMaskDefId, ret); + } + } + } - String getResourceName(Long resourceDefId) { - String ret = null; + return ret; + } + } + + class RetrieverContext { + final XXService service; + final ListIterator iterPolicy; + final ListIterator iterResources; + final ListIterator iterResourceMaps; + final ListIterator iterPolicyItems; + final ListIterator iterUserPerms; + final ListIterator iterGroupPerms; + final ListIterator iterAccesses; + final ListIterator iterConditions; + final ListIterator iterDataMaskInfos; + final ListIterator iterRowFilterInfos; + final ListIterator iterPolicyLabels; - if (resourceDefId != null) { - ret = resourceDefs.get(resourceDefId); + RetrieverContext(XXService xService) { + Long serviceId = xService == null ? null : xService.getId(); + List xPolicies = daoMgr.getXXPolicy().findByServiceId(serviceId); + + this.service = xService; + this.iterPolicy = xPolicies.listIterator(); + + List xResources = daoMgr.getXXPolicyResource().findByServiceId(serviceId); + List xResourceMaps = daoMgr.getXXPolicyResourceMap().findByServiceId(serviceId); + List xPolicyItems = daoMgr.getXXPolicyItem().findByServiceId(serviceId); + List xUserPerms = daoMgr.getXXPolicyItemUserPerm().findByServiceId(serviceId); + List xGroupPerms = daoMgr.getXXPolicyItemGroupPerm().findByServiceId(serviceId); + List xAccesses = daoMgr.getXXPolicyItemAccess().findByServiceId(serviceId); + List xConditions = daoMgr.getXXPolicyItemCondition().findByServiceId(serviceId); + List xDataMaskInfos = daoMgr.getXXPolicyItemDataMaskInfo().findByServiceId(serviceId); + List xRowFilterInfos = daoMgr.getXXPolicyItemRowFilterInfo().findByServiceId(serviceId); + List xPolicyLabelMap = daoMgr.getXXPolicyLabelMap().findByServiceId(serviceId); - if (ret == null) { - XXResourceDef xResourceDef = daoMgr.getXXResourceDef().getById(resourceDefId); + this.iterResources = xResources.listIterator(); + this.iterResourceMaps = xResourceMaps.listIterator(); + this.iterPolicyItems = xPolicyItems.listIterator(); + this.iterUserPerms = xUserPerms.listIterator(); + this.iterGroupPerms = xGroupPerms.listIterator(); + this.iterAccesses = xAccesses.listIterator(); + this.iterConditions = xConditions.listIterator(); + this.iterDataMaskInfos = xDataMaskInfos.listIterator(); + this.iterRowFilterInfos = xRowFilterInfos.listIterator(); + this.iterPolicyLabels = xPolicyLabelMap.listIterator(); + } - if (xResourceDef != null) { - ret = xResourceDef.getName(); + RetrieverContext(XXPolicy xPolicy, XXService xService) { + Long policyId = xPolicy == null ? null : xPolicy.getId(); + List xPolicies = asList(xPolicy); + + this.service = xService; + this.iterPolicy = xPolicies.listIterator(); + + List xResources = daoMgr.getXXPolicyResource().findByPolicyId(policyId); + List xResourceMaps = daoMgr.getXXPolicyResourceMap().findByPolicyId(policyId); + List xPolicyItems = daoMgr.getXXPolicyItem().findByPolicyId(policyId); + List xUserPerms = daoMgr.getXXPolicyItemUserPerm().findByPolicyId(policyId); + List xGroupPerms = daoMgr.getXXPolicyItemGroupPerm().findByPolicyId(policyId); + List xAccesses = daoMgr.getXXPolicyItemAccess().findByPolicyId(policyId); + List xConditions = daoMgr.getXXPolicyItemCondition().findByPolicyId(policyId); + List xDataMaskInfos = daoMgr.getXXPolicyItemDataMaskInfo().findByPolicyId(policyId); + List xRowFilterInfos = daoMgr.getXXPolicyItemRowFilterInfo().findByPolicyId(policyId); + List xPolicyLabelMap = daoMgr.getXXPolicyLabelMap().findByPolicyId(policyId); - resourceDefs.put(resourceDefId, ret); - } - } - } + this.iterResources = xResources.listIterator(); + this.iterResourceMaps = xResourceMaps.listIterator(); + this.iterPolicyItems = xPolicyItems.listIterator(); + this.iterUserPerms = xUserPerms.listIterator(); + this.iterGroupPerms = xGroupPerms.listIterator(); + this.iterAccesses = xAccesses.listIterator(); + this.iterConditions = xConditions.listIterator(); + this.iterDataMaskInfos = xDataMaskInfos.listIterator(); + this.iterRowFilterInfos = xRowFilterInfos.listIterator(); + this.iterPolicyLabels = xPolicyLabelMap.listIterator(); + } - return ret; - } + RangerPolicy getNextPolicy() { + RangerPolicy ret = null; + + if (iterPolicy.hasNext()) { + XXPolicy xPolicy = iterPolicy.next(); + + if (xPolicy != null) { + ret = new RangerPolicy(); + + ret.setId(xPolicy.getId()); + ret.setGuid(xPolicy.getGuid()); + ret.setIsEnabled(xPolicy.getIsEnabled()); + ret.setCreatedBy(lookupCache.getUserScreenName(xPolicy.getAddedByUserId())); + ret.setUpdatedBy(lookupCache.getUserScreenName(xPolicy.getUpdatedByUserId())); + ret.setCreateTime(xPolicy.getCreateTime()); + ret.setUpdateTime(xPolicy.getUpdateTime()); + ret.setVersion(xPolicy.getVersion()); + ret.setService(service == null ? null : service.getName()); + ret.setName(StringUtils.trim(xPolicy.getName())); + ret.setPolicyType(xPolicy.getPolicyType() == null ? RangerPolicy.POLICY_TYPE_ACCESS : xPolicy.getPolicyType()); + ret.setDescription(xPolicy.getDescription()); + ret.setResourceSignature(xPolicy.getResourceSignature()); + ret.setIsAuditEnabled(xPolicy.getIsAuditEnabled()); + ret.setPolicyPriority(xPolicy.getPolicyPriority()); + + Map mapOfOptions = JsonUtils.jsonToMapStringString(xPolicy.getOptions()); + + if (MapUtils.isNotEmpty(mapOfOptions)) { + String validitySchedulesStr = mapOfOptions.get(RangerPolicyService.OPTION_POLICY_VALIDITY_SCHEDULES); + + if (StringUtils.isNotEmpty(validitySchedulesStr)) { + List validitySchedules = JsonUtils.jsonToRangerValiditySchedule(validitySchedulesStr); + + ret.setValiditySchedules(validitySchedules); + } + } - String getDataMaskName(Long dataMaskDefId) { - String ret = null; + getPolicyLabels(ret); + getResource(ret); + getPolicyItems(ret); + } + } - if (dataMaskDefId != null) { - ret = dataMasks.get(dataMaskDefId); + return ret; + } - if (ret == null) { - XXDataMaskTypeDef xDataMaskDef = daoMgr.getXXDataMaskTypeDef().getById(dataMaskDefId); + List getAllPolicies() { + List ret = new ArrayList<>(); - if (xDataMaskDef != null) { - ret = xDataMaskDef.getName(); + while (iterPolicy.hasNext()) { + RangerPolicy policy = getNextPolicy(); - dataMasks.put(dataMaskDefId, ret); - } - } - } + if (policy != null) { + ret.add(policy); + } + } - return ret; - } - } + if (!hasProcessedAll()) { + LOG.warn("getAllPolicies(): perhaps one or more policies got updated during retrieval. Falling back to secondary method"); - static List asList(XXPolicy policy) { - List ret = new ArrayList(); + ret = getAllPoliciesBySecondary(); + } - if (policy != null) { - ret.add(policy); - } + return ret; + } - return ret; - } + List getAllPoliciesBySecondary() { + List ret = null; - class RetrieverContext { - final XXService service; - final ListIterator iterPolicy; - final ListIterator iterResources; - final ListIterator iterResourceMaps; - final ListIterator iterPolicyItems; - final ListIterator iterUserPerms; - final ListIterator iterGroupPerms; - final ListIterator iterAccesses; - final ListIterator iterConditions; - final ListIterator iterDataMaskInfos; - final ListIterator iterRowFilterInfos; - final ListIterator iterPolicyLabels; + if (service != null) { + List xPolicies = daoMgr.getXXPolicy().findByServiceId(service.getId()); - RetrieverContext(XXService xService) { - Long serviceId = xService == null ? null : xService.getId(); - List xPolicies = daoMgr.getXXPolicy().findByServiceId(serviceId); - - this.service = xService; - this.iterPolicy = xPolicies.listIterator(); - - List xResources = daoMgr.getXXPolicyResource().findByServiceId(serviceId); - List xResourceMaps = daoMgr.getXXPolicyResourceMap().findByServiceId(serviceId); - List xPolicyItems = daoMgr.getXXPolicyItem().findByServiceId(serviceId); - List xUserPerms = daoMgr.getXXPolicyItemUserPerm().findByServiceId(serviceId); - List xGroupPerms = daoMgr.getXXPolicyItemGroupPerm().findByServiceId(serviceId); - List xAccesses = daoMgr.getXXPolicyItemAccess().findByServiceId(serviceId); - List xConditions = daoMgr.getXXPolicyItemCondition().findByServiceId(serviceId); - List xDataMaskInfos = daoMgr.getXXPolicyItemDataMaskInfo().findByServiceId(serviceId); - List xRowFilterInfos = daoMgr.getXXPolicyItemRowFilterInfo().findByServiceId(serviceId); - List xPolicyLabelMap = daoMgr.getXXPolicyLabelMap().findByServiceId(serviceId); + if (CollectionUtils.isNotEmpty(xPolicies)) { + ret = new ArrayList<>(xPolicies.size()); - this.iterResources = xResources.listIterator(); - this.iterResourceMaps = xResourceMaps.listIterator(); - this.iterPolicyItems = xPolicyItems.listIterator(); - this.iterUserPerms = xUserPerms.listIterator(); - this.iterGroupPerms = xGroupPerms.listIterator(); - this.iterAccesses = xAccesses.listIterator(); - this.iterConditions = xConditions.listIterator(); - this.iterDataMaskInfos = xDataMaskInfos.listIterator(); - this.iterRowFilterInfos = xRowFilterInfos.listIterator(); - this.iterPolicyLabels = xPolicyLabelMap.listIterator(); - } - - RetrieverContext(XXPolicy xPolicy, XXService xService) { - Long policyId = xPolicy == null ? null : xPolicy.getId(); - List xPolicies = asList(xPolicy); - - this.service = xService; - this.iterPolicy = xPolicies.listIterator(); - - List xResources = daoMgr.getXXPolicyResource().findByPolicyId(policyId); - List xResourceMaps = daoMgr.getXXPolicyResourceMap().findByPolicyId(policyId); - List xPolicyItems = daoMgr.getXXPolicyItem().findByPolicyId(policyId); - List xUserPerms = daoMgr.getXXPolicyItemUserPerm().findByPolicyId(policyId); - List xGroupPerms = daoMgr.getXXPolicyItemGroupPerm().findByPolicyId(policyId); - List xAccesses = daoMgr.getXXPolicyItemAccess().findByPolicyId(policyId); - List xConditions = daoMgr.getXXPolicyItemCondition().findByPolicyId(policyId); - List xDataMaskInfos = daoMgr.getXXPolicyItemDataMaskInfo().findByPolicyId(policyId); - List xRowFilterInfos = daoMgr.getXXPolicyItemRowFilterInfo().findByPolicyId(policyId); - List xPolicyLabelMap = daoMgr.getXXPolicyLabelMap().findByPolicyId(policyId); + for (XXPolicy xPolicy : xPolicies) { + RetrieverContext ctx = new RetrieverContext(xPolicy, service); + RangerPolicy policy = ctx.getNextPolicy(); - this.iterResources = xResources.listIterator(); - this.iterResourceMaps = xResourceMaps.listIterator(); - this.iterPolicyItems = xPolicyItems.listIterator(); - this.iterUserPerms = xUserPerms.listIterator(); - this.iterGroupPerms = xGroupPerms.listIterator(); - this.iterAccesses = xAccesses.listIterator(); - this.iterConditions = xConditions.listIterator(); - this.iterDataMaskInfos = xDataMaskInfos.listIterator(); - this.iterRowFilterInfos = xRowFilterInfos.listIterator(); - this.iterPolicyLabels = xPolicyLabelMap.listIterator(); - } - - RangerPolicy getNextPolicy() { - RangerPolicy ret = null; - - if (iterPolicy.hasNext()) { - XXPolicy xPolicy = iterPolicy.next(); - - if (xPolicy != null) { - ret = new RangerPolicy(); - - ret.setId(xPolicy.getId()); - ret.setGuid(xPolicy.getGuid()); - ret.setIsEnabled(xPolicy.getIsEnabled()); - ret.setCreatedBy(lookupCache.getUserScreenName(xPolicy.getAddedByUserId())); - ret.setUpdatedBy(lookupCache.getUserScreenName(xPolicy.getUpdatedByUserId())); - ret.setCreateTime(xPolicy.getCreateTime()); - ret.setUpdateTime(xPolicy.getUpdateTime()); - ret.setVersion(xPolicy.getVersion()); - ret.setService(service == null ? null : service.getName()); - ret.setName(StringUtils.trim(xPolicy.getName())); - ret.setPolicyType(xPolicy.getPolicyType() == null ? RangerPolicy.POLICY_TYPE_ACCESS : xPolicy.getPolicyType()); - ret.setDescription(xPolicy.getDescription()); - ret.setResourceSignature(xPolicy.getResourceSignature()); - ret.setIsAuditEnabled(xPolicy.getIsAuditEnabled()); - ret.setPolicyPriority(xPolicy.getPolicyPriority()); - - Map mapOfOptions = JsonUtils.jsonToMapStringString(xPolicy.getOptions()); - - if (MapUtils.isNotEmpty(mapOfOptions)) { - String validitySchedulesStr = mapOfOptions.get(RangerPolicyService.OPTION_POLICY_VALIDITY_SCHEDULES); - - if (StringUtils.isNotEmpty(validitySchedulesStr)) { - List validitySchedules = JsonUtils.jsonToRangerValiditySchedule(validitySchedulesStr); - - ret.setValiditySchedules(validitySchedules); - } - } - - getPolicyLabels(ret); - getResource(ret); - getPolicyItems(ret); - } - } - - return ret; - } + if (policy != null) { + ret.add(policy); + } + } + } + } + + return ret; + } private void getPolicyLabels(RangerPolicy ret) { - List xPolicyLabels = new ArrayList(); + List xPolicyLabels = new ArrayList<>(); + while (iterPolicyLabels.hasNext()) { XXPolicyLabelMap xPolicyLabel = iterPolicyLabels.next(); + if (xPolicyLabel.getPolicyId().equals(ret.getId())) { String policyLabel = lookupCache.getPolicyLabelName(xPolicyLabel.getPolicyLabelId()); + if (policyLabel != null) { xPolicyLabels.add(policyLabel); } + ret.setPolicyLabels(xPolicyLabels); } else { if (iterPolicyLabels.hasPrevious()) { iterPolicyLabels.previous(); } + + break; + } + } + } + + private boolean hasProcessedAll() { + boolean moreToProcess = iterPolicy.hasNext() || iterResources.hasNext() || iterResourceMaps.hasNext() || iterPolicyItems.hasNext() || iterUserPerms.hasNext() || iterGroupPerms.hasNext() || iterAccesses.hasNext() || iterConditions.hasNext() || iterDataMaskInfos.hasNext() || iterRowFilterInfos.hasNext() || iterPolicyLabels.hasNext(); + + return !moreToProcess; + } + + private void getResource(RangerPolicy policy) { + while (iterResources.hasNext()) { + XXPolicyResource xResource = iterResources.next(); + + if (xResource.getPolicyid().equals(policy.getId())) { + RangerPolicyResource resource = new RangerPolicyResource(); + + resource.setIsExcludes(xResource.getIsexcludes()); + resource.setIsRecursive(xResource.getIsrecursive()); + + while (iterResourceMaps.hasNext()) { + XXPolicyResourceMap xResourceMap = iterResourceMaps.next(); + + if (xResourceMap.getResourceid().equals(xResource.getId())) { + resource.addValue(xResourceMap.getValue()); + } else { + if (iterResourceMaps.hasPrevious()) { + iterResourceMaps.previous(); + } + + break; + } + } + + policy.setResource(lookupCache.getResourceName(xResource.getResdefid()), resource); + } else if (xResource.getPolicyid().compareTo(policy.getId()) > 0) { + if (iterResources.hasPrevious()) { + iterResources.previous(); + } + + break; + } + } + } + + private void getPolicyItems(RangerPolicy policy) { + while (iterPolicyItems.hasNext()) { + XXPolicyItem xPolicyItem = iterPolicyItems.next(); + + if (xPolicyItem.getPolicyid().equals(policy.getId())) { + final RangerPolicyItem policyItem; + final RangerDataMaskPolicyItem dataMaskPolicyItem; + final RangerRowFilterPolicyItem rowFilterPolicyItem; + + if (xPolicyItem.getItemType() == RangerPolicyItemEvaluator.POLICY_ITEM_TYPE_DATAMASK) { + dataMaskPolicyItem = new RangerDataMaskPolicyItem(); + rowFilterPolicyItem = null; + policyItem = dataMaskPolicyItem; + } else if (xPolicyItem.getItemType() == RangerPolicyItemEvaluator.POLICY_ITEM_TYPE_ROWFILTER) { + dataMaskPolicyItem = null; + rowFilterPolicyItem = new RangerRowFilterPolicyItem(); + policyItem = rowFilterPolicyItem; + } else { + dataMaskPolicyItem = null; + rowFilterPolicyItem = null; + policyItem = new RangerPolicyItem(); + } + + while (iterAccesses.hasNext()) { + XXPolicyItemAccess xAccess = iterAccesses.next(); + + if (xAccess.getPolicyitemid().equals(xPolicyItem.getId())) { + policyItem.addAccess(new RangerPolicyItemAccess(lookupCache.getAccessType(xAccess.getType()), xAccess.getIsallowed())); + } else { + if (iterAccesses.hasPrevious()) { + iterAccesses.previous(); + } + + break; + } + } + + while (iterUserPerms.hasNext()) { + XXPolicyItemUserPerm xUserPerm = iterUserPerms.next(); + + if (xUserPerm.getPolicyitemid().equals(xPolicyItem.getId())) { + String userName = lookupCache.getUserName(xUserPerm.getUserid()); + + if (userName != null) { + policyItem.addUser(userName); + } + } else { + if (iterUserPerms.hasPrevious()) { + iterUserPerms.previous(); + } + + break; + } + } + + while (iterGroupPerms.hasNext()) { + XXPolicyItemGroupPerm xGroupPerm = iterGroupPerms.next(); + + if (xGroupPerm.getPolicyitemid().equals(xPolicyItem.getId())) { + String groupName = lookupCache.getGroupName(xGroupPerm.getGroupid()); + + if (groupName != null) { + policyItem.addGroup(groupName); + } + } else { + if (iterGroupPerms.hasPrevious()) { + iterGroupPerms.previous(); + } + + break; + } + } + + RangerPolicyItemCondition condition = null; + Long prevConditionType = null; + + while (iterConditions.hasNext()) { + XXPolicyItemCondition xCondition = iterConditions.next(); + + if (xCondition.getPolicyitemid().equals(xPolicyItem.getId())) { + if (!xCondition.getType().equals(prevConditionType)) { + condition = new RangerPolicyItemCondition(); + + condition.setType(lookupCache.getConditionType(xCondition.getType())); + condition.addValue(xCondition.getValue()); + + policyItem.addCondition(condition); + + prevConditionType = xCondition.getType(); + } else { + condition.addValue(xCondition.getValue()); + } + } else { + if (iterConditions.hasPrevious()) { + iterConditions.previous(); + } + + break; + } + } + + policyItem.setDelegateAdmin(xPolicyItem.getDelegateAdmin()); + + if (dataMaskPolicyItem != null) { + while (iterDataMaskInfos.hasNext()) { + XXPolicyItemDataMaskInfo xDataMaskInfo = iterDataMaskInfos.next(); + + if (xDataMaskInfo.getPolicyItemId().equals(xPolicyItem.getId())) { + dataMaskPolicyItem.setDataMaskInfo(new RangerPolicyItemDataMaskInfo(lookupCache.getDataMaskName(xDataMaskInfo.getType()), xDataMaskInfo.getConditionExpr(), xDataMaskInfo.getValueExpr())); + } else { + if (iterDataMaskInfos.hasPrevious()) { + iterDataMaskInfos.previous(); + } + + break; + } + } + } + + if (rowFilterPolicyItem != null) { + while (iterRowFilterInfos.hasNext()) { + XXPolicyItemRowFilterInfo xRowFilterInfo = iterRowFilterInfos.next(); + + if (xRowFilterInfo.getPolicyItemId().equals(xPolicyItem.getId())) { + rowFilterPolicyItem.setRowFilterInfo(new RangerPolicyItemRowFilterInfo(xRowFilterInfo.getFilterExpr())); + } else { + if (iterRowFilterInfos.hasPrevious()) { + iterRowFilterInfos.previous(); + } + + break; + } + } + } + + int itemType = xPolicyItem.getItemType() == null ? RangerPolicyItemEvaluator.POLICY_ITEM_TYPE_ALLOW : xPolicyItem.getItemType(); + + if (itemType == RangerPolicyItemEvaluator.POLICY_ITEM_TYPE_ALLOW) { + policy.addPolicyItem(policyItem); + } else if (itemType == RangerPolicyItemEvaluator.POLICY_ITEM_TYPE_DENY) { + policy.addDenyPolicyItem(policyItem); + } else if (itemType == RangerPolicyItemEvaluator.POLICY_ITEM_TYPE_ALLOW_EXCEPTIONS) { + policy.addAllowException(policyItem); + } else if (itemType == RangerPolicyItemEvaluator.POLICY_ITEM_TYPE_DENY_EXCEPTIONS) { + policy.addDenyPolicyItem(policyItem); + } else if (itemType == RangerPolicyItemEvaluator.POLICY_ITEM_TYPE_DATAMASK) { + policy.addDataMaskPolicyItem(dataMaskPolicyItem); + } else if (itemType == RangerPolicyItemEvaluator.POLICY_ITEM_TYPE_ROWFILTER) { + policy.addRowFilterPolicyItem(rowFilterPolicyItem); + } else { // unknown itemType + LOG.warn("RangerPolicyRetriever.getPolicy(policyId={}): ignoring unknown policyItemType {}", policy.getId(), itemType); + } + } else if (xPolicyItem.getPolicyid().compareTo(policy.getId()) > 0) { + if (iterPolicyItems.hasPrevious()) { + iterPolicyItems.previous(); + } + break; } } } + } + } + + private class PolicyUpdaterThread extends Thread { + final TransactionTemplate txTemplate; + final RangerService service; + final RangerPolicy policy; + String errorMsg; + + PolicyUpdaterThread(TransactionTemplate txTemplate, final RangerService service, final RangerPolicy policy) { + this.txTemplate = txTemplate; + this.service = service; + this.policy = policy; + this.errorMsg = null; + } + + public String getErrorMsg() { + return errorMsg; + } + + @Override + public void run() { + errorMsg = txTemplate.execute(status -> { + String ret = null; - List getAllPolicies() { - List ret = new ArrayList(); + try { + policyRefUpdater.cleanupRefTables(policy); - while (iterPolicy.hasNext()) { - RangerPolicy policy = getNextPolicy(); + portPolicy(service.getType(), policy); + } catch (Throwable e) { + logger.error("PortPolicy failed for policy:[{}]", policy, e); - if (policy != null) { - ret.add(policy); - } - } - - if (!hasProcessedAll()) { - LOG.warn("getAllPolicies(): perhaps one or more policies got updated during retrieval. Falling back to secondary method"); + ret = e.toString(); + } - ret = getAllPoliciesBySecondary(); - } - - return ret; - } - - List getAllPoliciesBySecondary() { - List ret = null; - - if (service != null) { - List xPolicies = daoMgr.getXXPolicy().findByServiceId(service.getId()); - - if (CollectionUtils.isNotEmpty(xPolicies)) { - ret = new ArrayList(xPolicies.size()); - - for (XXPolicy xPolicy : xPolicies) { - RetrieverContext ctx = new RetrieverContext(xPolicy, service); - - RangerPolicy policy = ctx.getNextPolicy(); - - if (policy != null) { - ret.add(policy); - } - } - } - } - - return ret; - } - - private boolean hasProcessedAll() { - boolean moreToProcess = iterPolicy.hasNext() || iterResources.hasNext() || iterResourceMaps.hasNext() - || iterPolicyItems.hasNext() || iterUserPerms.hasNext() || iterGroupPerms.hasNext() - || iterAccesses.hasNext() || iterConditions.hasNext() || iterDataMaskInfos.hasNext() - || iterRowFilterInfos.hasNext() || iterPolicyLabels.hasNext(); - - return !moreToProcess; - } - - private void getResource(RangerPolicy policy) { - while (iterResources.hasNext()) { - XXPolicyResource xResource = iterResources.next(); - - if (xResource.getPolicyid().equals(policy.getId())) { - RangerPolicyResource resource = new RangerPolicyResource(); - - resource.setIsExcludes(xResource.getIsexcludes()); - resource.setIsRecursive(xResource.getIsrecursive()); - - while (iterResourceMaps.hasNext()) { - XXPolicyResourceMap xResourceMap = iterResourceMaps.next(); - - if (xResourceMap.getResourceid().equals(xResource.getId())) { - resource.addValue(xResourceMap.getValue()); - } else { - if (iterResourceMaps.hasPrevious()) { - iterResourceMaps.previous(); - } - - break; - } - } - - policy.setResource(lookupCache.getResourceName(xResource.getResdefid()), resource); - } else if (xResource.getPolicyid().compareTo(policy.getId()) > 0) { - if (iterResources.hasPrevious()) { - iterResources.previous(); - } - - break; - } - } - } - - private void getPolicyItems(RangerPolicy policy) { - while (iterPolicyItems.hasNext()) { - XXPolicyItem xPolicyItem = iterPolicyItems.next(); - - if (xPolicyItem.getPolicyid().equals(policy.getId())) { - final RangerPolicyItem policyItem; - final RangerDataMaskPolicyItem dataMaskPolicyItem; - final RangerRowFilterPolicyItem rowFilterPolicyItem; - - if (xPolicyItem.getItemType() == RangerPolicyItemEvaluator.POLICY_ITEM_TYPE_DATAMASK) { - dataMaskPolicyItem = new RangerDataMaskPolicyItem(); - rowFilterPolicyItem = null; - policyItem = dataMaskPolicyItem; - } else if (xPolicyItem.getItemType() == RangerPolicyItemEvaluator.POLICY_ITEM_TYPE_ROWFILTER) { - dataMaskPolicyItem = null; - rowFilterPolicyItem = new RangerRowFilterPolicyItem(); - policyItem = rowFilterPolicyItem; - } else { - dataMaskPolicyItem = null; - rowFilterPolicyItem = null; - policyItem = new RangerPolicyItem(); - } - - while (iterAccesses.hasNext()) { - XXPolicyItemAccess xAccess = iterAccesses.next(); - - if (xAccess.getPolicyitemid().equals(xPolicyItem.getId())) { - policyItem.addAccess(new RangerPolicyItemAccess(lookupCache.getAccessType(xAccess.getType()), xAccess.getIsallowed())); - } else { - if (iterAccesses.hasPrevious()) { - iterAccesses.previous(); - } - - break; - } - } - - while (iterUserPerms.hasNext()) { - XXPolicyItemUserPerm xUserPerm = iterUserPerms.next(); - - if (xUserPerm.getPolicyitemid().equals(xPolicyItem.getId())) { - String userName = lookupCache.getUserName(xUserPerm.getUserid()); - - if (userName != null) { - policyItem.addUser(userName); - } - } else { - if (iterUserPerms.hasPrevious()) { - iterUserPerms.previous(); - } - - break; - } - } - - while (iterGroupPerms.hasNext()) { - XXPolicyItemGroupPerm xGroupPerm = iterGroupPerms.next(); - - if (xGroupPerm.getPolicyitemid().equals(xPolicyItem.getId())) { - String groupName = lookupCache.getGroupName(xGroupPerm.getGroupid()); - - if (groupName != null) { - policyItem.addGroup(groupName); - } - } else { - if (iterGroupPerms.hasPrevious()) { - iterGroupPerms.previous(); - } - - break; - } - } - - RangerPolicyItemCondition condition = null; - Long prevConditionType = null; - - while (iterConditions.hasNext()) { - XXPolicyItemCondition xCondition = iterConditions.next(); - - if (xCondition.getPolicyitemid().equals(xPolicyItem.getId())) { - if (!xCondition.getType().equals(prevConditionType)) { - condition = new RangerPolicyItemCondition(); - - condition.setType(lookupCache.getConditionType(xCondition.getType())); - condition.addValue(xCondition.getValue()); - - policyItem.addCondition(condition); - - prevConditionType = xCondition.getType(); - } else { - condition.addValue(xCondition.getValue()); - } - } else { - if (iterConditions.hasPrevious()) { - iterConditions.previous(); - } - - break; - } - } - - policyItem.setDelegateAdmin(xPolicyItem.getDelegateAdmin()); - - if (dataMaskPolicyItem != null) { - while (iterDataMaskInfos.hasNext()) { - XXPolicyItemDataMaskInfo xDataMaskInfo = iterDataMaskInfos.next(); - - if (xDataMaskInfo.getPolicyItemId().equals(xPolicyItem.getId())) { - dataMaskPolicyItem.setDataMaskInfo(new RangerPolicyItemDataMaskInfo(lookupCache.getDataMaskName(xDataMaskInfo.getType()), xDataMaskInfo.getConditionExpr(), xDataMaskInfo.getValueExpr())); - } else { - if (iterDataMaskInfos.hasPrevious()) { - iterDataMaskInfos.previous(); - } - - break; - } - } - } - - if (rowFilterPolicyItem != null) { - while (iterRowFilterInfos.hasNext()) { - XXPolicyItemRowFilterInfo xRowFilterInfo = iterRowFilterInfos.next(); - - if (xRowFilterInfo.getPolicyItemId().equals(xPolicyItem.getId())) { - rowFilterPolicyItem.setRowFilterInfo(new RangerPolicyItemRowFilterInfo(xRowFilterInfo.getFilterExpr())); - } else { - if (iterRowFilterInfos.hasPrevious()) { - iterRowFilterInfos.previous(); - } - - break; - } - } - } - - int itemType = xPolicyItem.getItemType() == null ? RangerPolicyItemEvaluator.POLICY_ITEM_TYPE_ALLOW : xPolicyItem.getItemType(); - - if (itemType == RangerPolicyItemEvaluator.POLICY_ITEM_TYPE_ALLOW) { - policy.addPolicyItem(policyItem); - } else if (itemType == RangerPolicyItemEvaluator.POLICY_ITEM_TYPE_DENY) { - policy.addDenyPolicyItem(policyItem); - } else if (itemType == RangerPolicyItemEvaluator.POLICY_ITEM_TYPE_ALLOW_EXCEPTIONS) { - policy.addAllowException(policyItem); - } else if (itemType == RangerPolicyItemEvaluator.POLICY_ITEM_TYPE_DENY_EXCEPTIONS) { - policy.addDenyPolicyItem(policyItem); - } else if (itemType == RangerPolicyItemEvaluator.POLICY_ITEM_TYPE_DATAMASK) { - policy.addDataMaskPolicyItem(dataMaskPolicyItem); - } else if (itemType == RangerPolicyItemEvaluator.POLICY_ITEM_TYPE_ROWFILTER) { - policy.addRowFilterPolicyItem(rowFilterPolicyItem); - } else { // unknown itemType - LOG.warn("RangerPolicyRetriever.getPolicy(policyId=" + policy.getId() + "): ignoring unknown policyItemType " + itemType); - } - } else if (xPolicyItem.getPolicyid().compareTo(policy.getId()) > 0) { - if (iterPolicyItems.hasPrevious()) { - iterPolicyItems.previous(); - } - - break; - } - } - } - } - } + return ret; + }); + } + } } diff --git a/security-admin/src/main/java/org/apache/ranger/patch/PatchForUpdatingTagsJson_J10020.java b/security-admin/src/main/java/org/apache/ranger/patch/PatchForUpdatingTagsJson_J10020.java index 584f09d716..ed14f2c47f 100644 --- a/security-admin/src/main/java/org/apache/ranger/patch/PatchForUpdatingTagsJson_J10020.java +++ b/security-admin/src/main/java/org/apache/ranger/patch/PatchForUpdatingTagsJson_J10020.java @@ -6,7 +6,7 @@ * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -25,12 +25,6 @@ package org.apache.ranger.patch; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.ListIterator; -import java.util.Map; - import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.MapUtils; import org.apache.commons.lang.StringUtils; @@ -69,13 +63,16 @@ import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Component; import org.springframework.transaction.PlatformTransactionManager; -import org.springframework.transaction.TransactionStatus; -import org.springframework.transaction.support.TransactionCallback; import org.springframework.transaction.support.TransactionTemplate; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.ListIterator; +import java.util.Map; + @Component public class PatchForUpdatingTagsJson_J10020 extends BaseLoader { - private static final Logger logger = LoggerFactory.getLogger(PatchForUpdatingTagsJson_J10020.class); @Autowired @@ -102,9 +99,9 @@ public class PatchForUpdatingTagsJson_J10020 extends BaseLoader { public static void main(String[] args) { logger.info("main()"); + try { - PatchForUpdatingTagsJson_J10020 loader = (PatchForUpdatingTagsJson_J10020) CLIUtil - .getBean(PatchForUpdatingTagsJson_J10020.class); + PatchForUpdatingTagsJson_J10020 loader = (PatchForUpdatingTagsJson_J10020) CLIUtil.getBean(PatchForUpdatingTagsJson_J10020.class); loader.init(); @@ -117,6 +114,7 @@ public static void main(String[] args) { System.exit(0); } catch (Exception e) { logger.error("Error loading", e); + System.exit(1); } } @@ -126,6 +124,11 @@ public void init() throws Exception { // Do Nothing } + @Override + public void printStats() { + logger.info("Update Ranger Tags Tables with Json data "); + } + @Override public void execLoad() { logger.info("==> PatchForUpdatingTagsJson.execLoad()"); @@ -134,17 +137,13 @@ public void execLoad() { updateRangerTagsTablesWithTagsJson(); } catch (Exception e) { logger.error("Error while UpdateRangerTagsTablesWithTagsJson()", e); + System.exit(1); } logger.info("<== PatchForUpdatingTagsJson.execLoad()"); } - @Override - public void printStats() { - logger.info("Update Ranger Tags Tables with Json data "); - } - private void updateRangerTagsTablesWithTagsJson() throws Exception { logger.info("==> updateRangerTagsTablesWithTagsJson() "); @@ -165,16 +164,16 @@ private void updateRangerTagsTablesWithTagsJson() throws Exception { XXServiceResourceDao serviceResourceDao = daoMgr.getXXServiceResource(); if (MapUtils.isNotEmpty(tagDefs)) { - logger.info("==> Port " + tagDefs.size() + " Tag Definitions for service(name=" + dbService.getName() + ")"); + logger.info("==> Port {} Tag Definitions for service(name={})", tagDefs.size(), dbService.getName()); for (Map.Entry entry : tagDefs.entrySet()) { - RangerTagDef tagDef = entry.getValue(); - XXTagDef xTagDef = tagDefDao.getById(tagDef.getId()); + RangerTagDef tagDef = entry.getValue(); + XXTagDef xTagDef = tagDefDao.getById(tagDef.getId()); if (xTagDef != null && StringUtils.isEmpty(xTagDef.getTagAttrDefs())) { - TagsUpdaterThread updaterThread = new TagsUpdaterThread(txTemplate, null, null, tagDef); - String errorMsg = runThread(updaterThread); + String errorMsg = runThread(updaterThread); + if (StringUtils.isNotEmpty(errorMsg)) { throw new Exception(errorMsg); } @@ -183,15 +182,16 @@ private void updateRangerTagsTablesWithTagsJson() throws Exception { } if (MapUtils.isNotEmpty(tags)) { - logger.info("==> Port " + tags.size() + " Tags for service(name=" + dbService.getName() + ")"); + logger.info("==> Port {} Tags for service(name={})", tags.size(), dbService.getName()); for (Map.Entry entry : tags.entrySet()) { - RangerTag tag = entry.getValue(); - XXTag xTag = tagDao.getById(tag.getId()); + RangerTag tag = entry.getValue(); + XXTag xTag = tagDao.getById(tag.getId()); if (xTag != null && StringUtils.isEmpty(xTag.getTagAttrs())) { TagsUpdaterThread updaterThread = new TagsUpdaterThread(txTemplate, null, tag, null); - String errorMsg = runThread(updaterThread); + String errorMsg = runThread(updaterThread); + if (StringUtils.isNotEmpty(errorMsg)) { throw new Exception(errorMsg); } @@ -200,15 +200,15 @@ private void updateRangerTagsTablesWithTagsJson() throws Exception { } if (CollectionUtils.isNotEmpty(serviceResources)) { - logger.info("==> Port " + serviceResources.size() + " Service Resources for service(name=" + dbService.getName() + ")"); + logger.info("==> Port {} Service Resources for service(name={})", serviceResources.size(), dbService.getName()); for (RangerServiceResource serviceResource : serviceResources) { - XXServiceResource xServiceResource = serviceResourceDao.getById(serviceResource.getId()); if (xServiceResource != null && StringUtils.isEmpty(xServiceResource.getServiceResourceElements())) { TagsUpdaterThread updaterThread = new TagsUpdaterThread(txTemplate, serviceResource, null, null); - String errorMsg = runThread(updaterThread); + String errorMsg = runThread(updaterThread); + if (StringUtils.isNotEmpty(errorMsg)) { throw new Exception(errorMsg); } @@ -225,22 +225,37 @@ private String runThread(TagsUpdaterThread updaterThread) throws Exception { updaterThread.setDaemon(true); updaterThread.start(); updaterThread.join(); + return updaterThread.getErrorMsg(); } + private void portTagDef(RangerTagDef tagDef) { + tagDefService.update(tagDef); + } + + private void portTag(RangerTag tag) { + tagService.update(tag); + } + + private void portServiceResource(RangerServiceResource serviceResource) throws Exception { + serviceResourceService.update(serviceResource); + + tagStore.refreshServiceResource(serviceResource.getId()); + } + private class TagsUpdaterThread extends Thread { final TransactionTemplate txTemplate; final RangerServiceResource serviceResource; final RangerTag tag; final RangerTagDef tagDef; - String errorMsg; + String errorMsg; TagsUpdaterThread(TransactionTemplate txTemplate, final RangerServiceResource serviceResource, final RangerTag tag, final RangerTagDef tagDef) { - this.txTemplate = txTemplate; - this.serviceResource = serviceResource; - this.tag = tag; - this.tagDef = tagDef; - this.errorMsg = null; + this.txTemplate = txTemplate; + this.serviceResource = serviceResource; + this.tag = tag; + this.tagDef = tagDef; + this.errorMsg = null; } public String getErrorMsg() { @@ -249,50 +264,38 @@ public String getErrorMsg() { @Override public void run() { - errorMsg = txTemplate.execute(new TransactionCallback() { - @Override - public String doInTransaction(TransactionStatus status) { - String ret = null; - try { - if (serviceResource != null) { - portServiceResource(serviceResource); - } - if (tag != null) { - portTag(tag); - } - if (tagDef != null) { - portTagDef(tagDef); - } - } catch (Throwable e) { - logger.error("Port failed :[serviceResource=" + serviceResource + ", tag=" + tag + ", tagDef=" + tagDef +"]", e); - ret = e.toString(); + errorMsg = txTemplate.execute(status -> { + String ret = null; + + try { + if (serviceResource != null) { + portServiceResource(serviceResource); } - return ret; + + if (tag != null) { + portTag(tag); + } + + if (tagDef != null) { + portTagDef(tagDef); + } + } catch (Throwable e) { + logger.error("Port failed :[serviceResource={}, tag={}, tagDef={}]", serviceResource, tag, tagDef, e); + + ret = e.toString(); } + + return ret; }); } } - private void portTagDef(RangerTagDef tagDef) { - tagDefService.update(tagDef); - } - private void portTag(RangerTag tag) { - tagService.update(tag); - } - - private void portServiceResource(RangerServiceResource serviceResource) throws Exception { - serviceResourceService.update(serviceResource); - tagStore.refreshServiceResource(serviceResource.getId()); - } - - private class RangerTagDBRetriever { - final Logger LOG = LoggerFactory.getLogger(RangerTagDBRetriever.class); + private static class RangerTagDBRetriever { + Logger logger = LoggerFactory.getLogger(RangerTagDBRetriever.class); private final RangerDaoManager daoMgr; private final XXService xService; private final RangerTagDBRetriever.LookupCache lookupCache; - private final PlatformTransactionManager txManager; - private final TransactionTemplate txTemplate; private List serviceResources; private Map tagDefs; private Map tags; @@ -301,35 +304,31 @@ private class RangerTagDBRetriever { this.daoMgr = daoMgr; this.xService = xService; this.lookupCache = new RangerTagDBRetriever.LookupCache(); - this.txManager = txManager; - if (this.txManager != null) { - this.txTemplate = new TransactionTemplate(this.txManager); - this.txTemplate.setReadOnly(true); + TransactionTemplate txTemplate; + + if (txManager != null) { + txTemplate = new TransactionTemplate(txManager); + txTemplate.setReadOnly(true); } else { - this.txTemplate = null; + txTemplate = null; } if (this.daoMgr != null && this.xService != null) { - if (this.txTemplate == null) { - if (LOG.isDebugEnabled()) { - LOG.debug("Load Tags in the same thread and using an existing transaction"); - } + if (txTemplate == null) { + logger.debug("Load Tags in the same thread and using an existing transaction"); if (!initializeTagCache(xService)) { - LOG.error("Failed to get tags for service:[" + xService.getName() + "] in the same thread and using an existing transaction"); + logger.error("Failed to get tags for service:[{}}] in the same thread and using an existing transaction", xService.getName()); } } else { - if (LOG.isDebugEnabled()) { - LOG.debug("Load Tags in a separate thread and using a new transaction"); - } + logger.debug("Load Tags in a separate thread and using a new transaction"); RangerTagDBRetriever.TagLoaderThread t = new RangerTagDBRetriever.TagLoaderThread(txTemplate, xService); t.setDaemon(true); t.start(); t.join(); } - } } @@ -346,17 +345,15 @@ Map getTags() { } private boolean initializeTagCache(XXService xService) { - boolean ret; - RangerTagDBRetriever.TagRetrieverServiceResourceContext serviceResourceContext = new RangerTagDBRetriever.TagRetrieverServiceResourceContext(xService); - RangerTagDBRetriever.TagRetrieverTagDefContext tagDefContext = new RangerTagDBRetriever.TagRetrieverTagDefContext(xService); - RangerTagDBRetriever.TagRetrieverTagContext tagContext = new RangerTagDBRetriever.TagRetrieverTagContext(xService); + RangerTagDBRetriever.TagRetrieverServiceResourceContext serviceResourceContext = new RangerTagDBRetriever.TagRetrieverServiceResourceContext(xService); + RangerTagDBRetriever.TagRetrieverTagDefContext tagDefContext = new RangerTagDBRetriever.TagRetrieverTagDefContext(xService); + RangerTagDBRetriever.TagRetrieverTagContext tagContext = new RangerTagDBRetriever.TagRetrieverTagContext(xService); serviceResources = serviceResourceContext.getAllServiceResources(); tagDefs = tagDefContext.getAllTagDefs(); tags = tagContext.getAllTags(); - ret = true; - return ret; + return true; } private List asList(T obj) { @@ -440,22 +437,17 @@ private class TagLoaderThread extends Thread { @Override public void run() { txTemplate.setReadOnly(true); - Boolean result = txTemplate.execute(new TransactionCallback() { - @Override - public Boolean doInTransaction(TransactionStatus status) { - boolean ret = initializeTagCache(xService); - - if (!ret) { - status.setRollbackOnly(); - LOG.error("Failed to get tags for service:[" + xService.getName() + "] in a new transaction"); - } - return ret; + Boolean result = txTemplate.execute(status -> { + boolean ret = initializeTagCache(xService); + + if (!ret) { + status.setRollbackOnly(); + logger.error("Failed to get tags for service:[{}] in a new transaction", xService.getName()); } + return ret; }); - if (LOG.isDebugEnabled()) { - LOG.debug("transaction result:[" + result +"]"); - } + logger.debug("transaction result:[{}]", result); } } @@ -475,7 +467,6 @@ private class TagRetrieverServiceResourceContext { this.iterServiceResource = xServiceResources.listIterator(); this.iterServiceResourceElement = xServiceResourceElements.listIterator(); this.iterServiceResourceElementValue = xServiceResourceElementValues.listIterator(); - } TagRetrieverServiceResourceContext(XXServiceResource xServiceResource, XXService xService) { @@ -502,7 +493,7 @@ List getAllServiceResources() { } if (!hasProcessedAll()) { - LOG.warn("getAllServiceResources(): perhaps one or more serviceResources got updated during retrieval. Using fallback ... "); + logger.warn("getAllServiceResources(): perhaps one or more serviceResources got updated during retrieval. Using fallback ... "); ret = getServiceResourcesBySecondary(); } @@ -573,9 +564,7 @@ void getServiceResourceElements(RangerServiceResource serviceResource) { } boolean hasProcessedAll() { - boolean moreToProcess = iterServiceResource.hasNext() - || iterServiceResourceElement.hasNext() - || iterServiceResourceElementValue.hasNext(); + boolean moreToProcess = iterServiceResource.hasNext() || iterServiceResourceElement.hasNext() || iterServiceResourceElementValue.hasNext(); return !moreToProcess; } @@ -609,7 +598,6 @@ private class TagRetrieverTagDefContext { final ListIterator iterTagDef; final ListIterator iterTagAttributeDef; - TagRetrieverTagDefContext(XXService xService) { Long serviceId = xService == null ? null : xService.getId(); List xTagDefs = daoMgr.getXXTagDef().findByServiceId(serviceId); @@ -642,7 +630,7 @@ Map getAllTagDefs() { } if (!hasProcessedAllTagDefs()) { - LOG.warn("getAllTagDefs(): perhaps one or more tag-definitions got updated during retrieval. Using fallback ... "); + logger.warn("getAllTagDefs(): perhaps one or more tag-definitions got updated during retrieval. Using fallback ... "); ret = getTagDefsBySecondary(); } @@ -732,7 +720,6 @@ private class TagRetrieverTagContext { final ListIterator iterTag; final ListIterator iterTagAttribute; - TagRetrieverTagContext(XXService xService) { Long serviceId = xService == null ? null : xService.getId(); List xTags = daoMgr.getXXTag().findByServiceId(serviceId); @@ -741,7 +728,6 @@ private class TagRetrieverTagContext { this.service = xService; this.iterTag = xTags.listIterator(); this.iterTagAttribute = xTagAttributes.listIterator(); - } TagRetrieverTagContext(XXTag xTag, XXService xService) { @@ -754,7 +740,6 @@ private class TagRetrieverTagContext { this.iterTagAttribute = xTagAttributes.listIterator(); } - Map getAllTags() { Map ret = new HashMap<>(); @@ -767,7 +752,7 @@ Map getAllTags() { } if (!hasProcessedAllTags()) { - LOG.warn("getAllTags(): perhaps one or more tags got updated during retrieval. Using fallback ... "); + logger.warn("getAllTags(): perhaps one or more tags got updated during retrieval. Using fallback ... "); ret = getTagsBySecondary(); } @@ -825,7 +810,7 @@ void getTagAttributes(RangerTag tag) { XXTagAttribute xTagAttribute = iterTagAttribute.next(); if (xTagAttribute.getTagId().equals(tag.getId())) { - String attributeName = xTagAttribute.getName(); + String attributeName = xTagAttribute.getName(); String attributeValue = xTagAttribute.getValue(); if (tag.getAttributes() == null) { @@ -873,4 +858,3 @@ Map getTagsBySecondary() { } } } - diff --git a/security-admin/src/main/java/org/apache/ranger/patch/PatchForXGlobalState_J10036.java b/security-admin/src/main/java/org/apache/ranger/patch/PatchForXGlobalState_J10036.java index 8690d7a55e..8eda85f3ea 100644 --- a/security-admin/src/main/java/org/apache/ranger/patch/PatchForXGlobalState_J10036.java +++ b/security-admin/src/main/java/org/apache/ranger/patch/PatchForXGlobalState_J10036.java @@ -32,67 +32,74 @@ @Component public class PatchForXGlobalState_J10036 extends BaseLoader { - private static final Logger logger = LoggerFactory - .getLogger(PatchForXGlobalState_J10036.class); - - @Autowired - RangerDaoManager daoManager; - - public static void main(String[] args) { - logger.info("main()"); - try { - PatchForXGlobalState_J10036 loader = (PatchForXGlobalState_J10036) CLIUtil - .getBean(PatchForXGlobalState_J10036.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); - } - } - - @Override - public void init() throws Exception { - // Do Nothing - } - - @Override - public void execLoad() { - logger.info("==> ServiceVersionInfoPatch.execLoad()"); - updateRangerRoleVersionToVersion(); - logger.info("<== ServiceVersionInfoPatch.execLoad()"); - } - - public void updateRangerRoleVersionToVersion() { - XXGlobalState globalState = daoManager.getXXGlobalState().findByStateName("RangerRole"); - if (globalState != null) { - logger.info("Updating globalstate with id = " + globalState.getId()); - - if(StringUtils.isNotEmpty(globalState.getAppData())) { - Map appDataVersionJson = null; - appDataVersionJson = JsonUtils.jsonToObject(globalState.getAppData(), Map.class); - if (MapUtils.isNotEmpty(appDataVersionJson)) { - logger.info("Updating globalstate appdata version for = " + appDataVersionJson); - String roleVersion = appDataVersionJson.get("RangerRoleVersion"); - if (StringUtils.isNotEmpty(roleVersion)) { - appDataVersionJson.put("Version", roleVersion); - appDataVersionJson.remove("RangerRoleVersion"); - globalState.setAppData(JsonUtils.objectToJson(appDataVersionJson)); - daoManager.getXXGlobalState().update(globalState); - } - } - } - - } - } - - @Override - public void printStats() { - } + private static final Logger logger = LoggerFactory.getLogger(PatchForXGlobalState_J10036.class); + @Autowired + RangerDaoManager daoManager; + + public static void main(String[] args) { + logger.info("main()"); + try { + PatchForXGlobalState_J10036 loader = (PatchForXGlobalState_J10036) CLIUtil.getBean(PatchForXGlobalState_J10036.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); + } + } + + @Override + public void init() throws Exception { + // Do Nothing + } + + @Override + public void printStats() { + } + + @Override + public void execLoad() { + logger.info("==> ServiceVersionInfoPatch.execLoad()"); + + updateRangerRoleVersionToVersion(); + + logger.info("<== ServiceVersionInfoPatch.execLoad()"); + } + + public void updateRangerRoleVersionToVersion() { + XXGlobalState globalState = daoManager.getXXGlobalState().findByStateName("RangerRole"); + + if (globalState != null) { + logger.info("Updating globalstate with id = {}", globalState.getId()); + + if (StringUtils.isNotEmpty(globalState.getAppData())) { + Map appDataVersionJson = JsonUtils.jsonToObject(globalState.getAppData(), Map.class); + + if (MapUtils.isNotEmpty(appDataVersionJson)) { + logger.info("Updating globalstate appdata version for = {}", appDataVersionJson); + + String roleVersion = appDataVersionJson.get("RangerRoleVersion"); + + if (StringUtils.isNotEmpty(roleVersion)) { + appDataVersionJson.put("Version", roleVersion); + appDataVersionJson.remove("RangerRoleVersion"); + + globalState.setAppData(JsonUtils.objectToJson(appDataVersionJson)); + + daoManager.getXXGlobalState().update(globalState); + } + } + } + } + } } diff --git a/security-admin/src/main/java/org/apache/ranger/patch/PatchGrantAuditPermissionToKeyRoleUser_J10014.java b/security-admin/src/main/java/org/apache/ranger/patch/PatchGrantAuditPermissionToKeyRoleUser_J10014.java index b1275031e8..b6329b4de7 100644 --- a/security-admin/src/main/java/org/apache/ranger/patch/PatchGrantAuditPermissionToKeyRoleUser_J10014.java +++ b/security-admin/src/main/java/org/apache/ranger/patch/PatchGrantAuditPermissionToKeyRoleUser_J10014.java @@ -17,127 +17,128 @@ package org.apache.ranger.patch; -import java.util.List; import org.apache.commons.collections.CollectionUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.apache.ranger.biz.XUserMgr; +import org.apache.ranger.common.RangerConstants; import org.apache.ranger.db.RangerDaoManager; import org.apache.ranger.entity.XXModuleDef; import org.apache.ranger.entity.XXPortalUser; import org.apache.ranger.service.XPortalUserService; -import org.apache.ranger.biz.XUserMgr; -import org.apache.ranger.common.RangerConstants; import org.apache.ranger.util.CLIUtil; import org.apache.ranger.view.VXPortalUser; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; +import java.util.List; + @Component public class PatchGrantAuditPermissionToKeyRoleUser_J10014 extends BaseLoader { - private static final Logger logger = LoggerFactory - .getLogger(PatchGrantAuditPermissionToKeyRoleUser_J10014.class); + private static final Logger logger = LoggerFactory.getLogger(PatchGrantAuditPermissionToKeyRoleUser_J10014.class); - @Autowired - XUserMgr xUserMgr; + @Autowired + XUserMgr xUserMgr; - @Autowired - XPortalUserService xPortalUserService; + @Autowired + XPortalUserService xPortalUserService; - @Autowired - RangerDaoManager daoManager; + @Autowired + RangerDaoManager daoManager; - public static void main(String[] args) { - logger.info("main()"); - try { - PatchGrantAuditPermissionToKeyRoleUser_J10014 loader = (PatchGrantAuditPermissionToKeyRoleUser_J10014) CLIUtil - .getBean(PatchGrantAuditPermissionToKeyRoleUser_J10014.class); + public static void main(String[] args) { + logger.info("main()"); - 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); - } - } + try { + PatchGrantAuditPermissionToKeyRoleUser_J10014 loader = (PatchGrantAuditPermissionToKeyRoleUser_J10014) CLIUtil.getBean(PatchGrantAuditPermissionToKeyRoleUser_J10014.class); - @Override - public void init() throws Exception { - // Do Nothing - } + loader.init(); - @Override - public void execLoad() { - logger.info("==>Starting : PatchGrantAuditPermissionToKeyRoleUser.execLoad()"); - assignAuditAndUserGroupPermissionToKeyAdminRoleUser(); + while (loader.isMoreToProcess()) { + loader.load(); + } - logger.info("<==Completed : PatchGrantAuditPermissionToKeyRoleUser.execLoad()"); + logger.info("Load complete. Exiting!!!"); + + System.exit(0); + } catch (Exception e) { + logger.error("Error loading", e); + + System.exit(1); } + } - private void assignAuditAndUserGroupPermissionToKeyAdminRoleUser() { - try { - int countUserPermissionUpdated = 0; - XXModuleDef xAuditModDef = daoManager.getXXModuleDef() - .findByModuleName(RangerConstants.MODULE_AUDIT); - XXModuleDef xUserGrpModDef = daoManager.getXXModuleDef() - .findByModuleName(RangerConstants.MODULE_USER_GROUPS); - logger.warn("Audit Module Object : " + xAuditModDef); - logger.warn("USer Group Module Object : " + xUserGrpModDef); - if (xAuditModDef == null && xUserGrpModDef == null) { - logger.warn("Audit Module and User Group module not found"); - return; - } - List allKeyAdminUsers = daoManager.getXXPortalUser() - .findByRole(RangerConstants.ROLE_KEY_ADMIN); - if (!CollectionUtils.isEmpty(allKeyAdminUsers)) { - for (XXPortalUser xPortalUser : allKeyAdminUsers) { - boolean isUserUpdated = false; - VXPortalUser vPortalUser = xPortalUserService - .populateViewBean(xPortalUser); - if (vPortalUser != null) { - vPortalUser.setUserRoleList(daoManager - .getXXPortalUserRole() - .findXPortalUserRolebyXPortalUserId( - vPortalUser.getId())); - if (xAuditModDef != null) { - xUserMgr.createOrUpdateUserPermisson(vPortalUser, - xAuditModDef.getId(), true); - isUserUpdated = true; - logger.info("Added '" + xAuditModDef.getModule() - + "' permission to user '" - + xPortalUser.getLoginId() + "'"); - } - if (xUserGrpModDef != null) { - xUserMgr.createOrUpdateUserPermisson(vPortalUser, - xUserGrpModDef.getId(), true); - isUserUpdated = true; - logger.info("Added '" + xUserGrpModDef.getModule() - + "' permission to user '" - + xPortalUser.getLoginId() + "'"); - } - if (isUserUpdated) { - countUserPermissionUpdated += 1; - } - - } - } - - logger.info(countUserPermissionUpdated - + " permissions were assigned"); - } else { - logger.info("There are no user with Key Admin role"); + @Override + public void init() throws Exception { + // Do Nothing + } + + @Override + public void printStats() { + } + + @Override + public void execLoad() { + logger.info("==>Starting : PatchGrantAuditPermissionToKeyRoleUser.execLoad()"); + + assignAuditAndUserGroupPermissionToKeyAdminRoleUser(); + + logger.info("<==Completed : PatchGrantAuditPermissionToKeyRoleUser.execLoad()"); + } + + private void assignAuditAndUserGroupPermissionToKeyAdminRoleUser() { + try { + int countUserPermissionUpdated = 0; + XXModuleDef xAuditModDef = daoManager.getXXModuleDef().findByModuleName(RangerConstants.MODULE_AUDIT); + XXModuleDef xUserGrpModDef = daoManager.getXXModuleDef().findByModuleName(RangerConstants.MODULE_USER_GROUPS); + + logger.warn("Audit Module Object : {}", xAuditModDef); + logger.warn("USer Group Module Object : {}", xUserGrpModDef); + + if (xAuditModDef == null && xUserGrpModDef == null) { + logger.warn("Audit Module and User Group module not found"); + + return; + } + + List allKeyAdminUsers = daoManager.getXXPortalUser().findByRole(RangerConstants.ROLE_KEY_ADMIN); + + if (!CollectionUtils.isEmpty(allKeyAdminUsers)) { + for (XXPortalUser xPortalUser : allKeyAdminUsers) { + boolean isUserUpdated = false; + VXPortalUser vPortalUser = xPortalUserService.populateViewBean(xPortalUser); + + if (vPortalUser != null) { + vPortalUser.setUserRoleList(daoManager.getXXPortalUserRole().findXPortalUserRolebyXPortalUserId(vPortalUser.getId())); + + if (xAuditModDef != null) { + xUserMgr.createOrUpdateUserPermisson(vPortalUser, xAuditModDef.getId(), true); + + isUserUpdated = true; + + logger.info("Added {} permission to user {}", xAuditModDef.getModule(), xPortalUser.getLoginId()); } - } catch (Exception ex) { - logger.error("Error while granting Audit and User group permission ",ex); - } - } + if (xUserGrpModDef != null) { + xUserMgr.createOrUpdateUserPermisson(vPortalUser, xUserGrpModDef.getId(), true); + + isUserUpdated = true; + logger.info("Added {} permission to user {}", xUserGrpModDef.getModule(), xPortalUser.getLoginId()); + } + + if (isUserUpdated) { + countUserPermissionUpdated += 1; + } + } + } - @Override - public void printStats() { + logger.info("{} permissions were assigned", countUserPermissionUpdated); + } else { + logger.info("There are no user with Key Admin role"); + } + } catch (Exception ex) { + logger.error("Error while granting Audit and User group permission ", ex); } -} \ No newline at end of file + } +} diff --git a/security-admin/src/main/java/org/apache/ranger/patch/PatchMigration_J10002.java b/security-admin/src/main/java/org/apache/ranger/patch/PatchMigration_J10002.java index 72b0b6e405..92473eb9eb 100644 --- a/security-admin/src/main/java/org/apache/ranger/patch/PatchMigration_J10002.java +++ b/security-admin/src/main/java/org/apache/ranger/patch/PatchMigration_J10002.java @@ -17,15 +17,6 @@ package org.apache.ranger.patch; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; - import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang.StringUtils; import org.apache.ranger.biz.RangerBizUtil; @@ -48,10 +39,10 @@ import org.apache.ranger.entity.XXServiceDef; import org.apache.ranger.entity.XXUser; import org.apache.ranger.plugin.model.RangerPolicy; -import org.apache.ranger.plugin.model.RangerService; import org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyItem; import org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyItemAccess; import org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyResource; +import org.apache.ranger.plugin.model.RangerService; import org.apache.ranger.plugin.store.EmbeddedServiceDefsUtil; import org.apache.ranger.service.RangerPolicyService; import org.apache.ranger.service.XPermMapService; @@ -63,506 +54,533 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + @Component public class PatchMigration_J10002 extends BaseLoader { - private static final Logger logger = LoggerFactory.getLogger(PatchMigration_J10002.class); - - @Autowired - RangerDaoManager daoMgr; - - @Autowired - ServiceDBStore svcDBStore; - - @Autowired - JSONUtil jsonUtil; - - @Autowired - RangerPolicyService policyService; - - @Autowired - StringUtil stringUtil; - - @Autowired - XPolicyService xPolService; - - @Autowired - XPermMapService xPermMapService; - - @Autowired - RangerBizUtil bizUtil; - - private static int policyCounter = 0; - private static int serviceCounter = 0; - - static Set unsupportedLegacyPermTypes = new HashSet(); - - static { - unsupportedLegacyPermTypes.add("Unknown"); - unsupportedLegacyPermTypes.add("Reset"); - unsupportedLegacyPermTypes.add("Obfuscate"); - unsupportedLegacyPermTypes.add("Mask"); - } - - public static void main(String[] args) { - logger.info("main()"); - try { - PatchMigration_J10002 loader = (PatchMigration_J10002) CLIUtil.getBean(PatchMigration_J10002.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); - } - } - - @Override - public void init() throws Exception { - // Do Nothing - } - - @Override - public void execLoad() { - logger.info("==> MigrationPatch.execLoad()"); - try { - migrateServicesToNewSchema(); - migratePoliciesToNewSchema(); - updateSequences(); - } catch (Exception e) { - logger.error("Error whille migrating data.", e); - } - logger.info("<== MigrationPatch.execLoad()"); - } - - @Override - public void printStats() { - logger.info("Total Number of migrated repositories/services: " + serviceCounter); - logger.info("Total Number of migrated resources/policies: " + policyCounter); - } - - public void migrateServicesToNewSchema() throws Exception { - logger.info("==> MigrationPatch.migrateServicesToNewSchema()"); - - try { - List repoList = daoMgr.getXXAsset().getAll(); - - if (repoList.isEmpty()) { - return; - } - if (!repoList.isEmpty()) { - EmbeddedServiceDefsUtil.instance().init(svcDBStore); - } - - svcDBStore.setPopulateExistingBaseFields(true); - for (XXAsset xAsset : repoList) { - - if (xAsset.getActiveStatus() == AppConstants.STATUS_DELETED) { - continue; - } - - RangerService existing = svcDBStore.getServiceByName(xAsset.getName()); - if (existing != null) { - logger.info("Repository/Service already exists. Ignoring migration of repo: " + xAsset.getName()); - continue; - } - - RangerService service = new RangerService(); - service = mapXAssetToService(service, xAsset); - - service = svcDBStore.createService(service); - - serviceCounter++; - logger.info("New Service created. ServiceName: " + service.getName()); - } - svcDBStore.setPopulateExistingBaseFields(false); - } catch (Exception e) { - throw new Exception("Error while migrating data to new Plugin Schema.", e); - } - logger.info("<== MigrationPatch.migrateServicesToNewSchema()"); - } - - public void migratePoliciesToNewSchema() throws Exception { - logger.info("==> MigrationPatch.migratePoliciesToNewSchema()"); - - try { - List resList = daoMgr.getXXResource().getAll(); - if (resList.isEmpty()) { - return; - } - - svcDBStore.setPopulateExistingBaseFields(true); - for (XXResource xRes : resList) { - - if (xRes.getResourceStatus() == AppConstants.STATUS_DELETED) { - continue; - } - - XXAsset xAsset = daoMgr.getXXAsset().getById(xRes.getAssetId()); - if (xAsset == null) { - logger.error("No Repository found for policyName: " + xRes.getPolicyName()); - continue; - } - - RangerService service = svcDBStore.getServiceByName(xAsset.getName()); - - if (service == null) { - logger.error("No Service found for policy. Ignoring migration of such policy, policyName: " - + xRes.getPolicyName()); - continue; - } - - XXPolicy existing = daoMgr.getXXPolicy().findByNameAndServiceId(xRes.getPolicyName(), service.getId()); - if (existing != null) { - logger.info("Policy already exists. Ignoring migration of policy: " + existing.getName()); - continue; - } - - RangerPolicy policy = new RangerPolicy(); - policy = mapXResourceToPolicy(policy, xRes, service); - - if(policy != null) { - policy = svcDBStore.createPolicy(policy); - - policyCounter++; - logger.info("New policy created. policyName: " + policy.getName()); - } - } - svcDBStore.setPopulateExistingBaseFields(false); - } catch (Exception e) { - throw new Exception("Error while migrating data to new Plugin Schema.", e); - } - logger.info("<== MigrationPatch.migratePoliciesToNewSchema()"); - } - - private RangerService mapXAssetToService(RangerService service, XXAsset xAsset) throws Exception { - - String type = ""; - String name = xAsset.getName(); - String description = xAsset.getDescription(); - Map configs = null; - - int typeInt = xAsset.getAssetType(); - XXServiceDef serviceDef = daoMgr.getXXServiceDef().findByName(AppConstants.getLabelFor_AssetType(typeInt).toLowerCase()); - - if (serviceDef == null) { - throw new Exception("No ServiceDefinition found for repository: " + name); - } - type = serviceDef.getName(); - configs = jsonUtil.jsonToMap(xAsset.getConfig()); - - List mandatoryConfigs = daoMgr.getXXServiceConfigDef().findByServiceDefName(type); - for (XXServiceConfigDef serviceConf : mandatoryConfigs) { - if (serviceConf.getIsMandatory()) { - if (!stringUtil.isEmpty(configs.get(serviceConf.getName()))) { - continue; - } - String dataType = serviceConf.getType(); - String defaultValue = serviceConf.getDefaultvalue(); - - if (stringUtil.isEmpty(defaultValue)) { - defaultValue = getDefaultValueForDataType(dataType); - } - configs.put(serviceConf.getName(), defaultValue); - } - } - - service.setType(type); - service.setName(name); - service.setDescription(description); - service.setConfigs(configs); - - service.setCreateTime(xAsset.getCreateTime()); - service.setUpdateTime(xAsset.getUpdateTime()); - - XXPortalUser createdByUser = daoMgr.getXXPortalUser().getById(xAsset.getAddedByUserId()); - XXPortalUser updByUser = daoMgr.getXXPortalUser().getById(xAsset.getUpdatedByUserId()); - - if (createdByUser != null) { - service.setCreatedBy(createdByUser.getLoginId()); - } - if (updByUser != null) { - service.setUpdatedBy(updByUser.getLoginId()); - } - service.setId(xAsset.getId()); - - return service; - } - - private String getDefaultValueForDataType(String dataType) { - - String defaultValue = ""; - switch (dataType) { - case "int": - defaultValue = "0"; - break; - case "string": - defaultValue = "unknown"; - break; - case "bool": - defaultValue = "false"; - break; - case "enum": - defaultValue = "0"; - break; - case "password": - defaultValue = "password"; - break; - default: - break; - } - return defaultValue; - } - - private RangerPolicy mapXResourceToPolicy(RangerPolicy policy, XXResource xRes, RangerService service) { - String serviceName = service.getName(); - String serviceType = service.getType(); - String name = xRes.getPolicyName(); - String description = xRes.getDescription(); - Boolean isAuditEnabled = true; - Boolean isEnabled = true; - Map resources = new HashMap(); - List policyItems = new ArrayList(); - - XXServiceDef svcDef = daoMgr.getXXServiceDef().findByName(serviceType); - - if(svcDef == null) { - logger.error(serviceType + ": service-def not found. Skipping policy '" + name + "'"); - - return null; - } - - List auditMapList = daoMgr.getXXAuditMap().findByResourceId(xRes.getId()); - if (stringUtil.isEmpty(auditMapList)) { - isAuditEnabled = false; - } - if (xRes.getResourceStatus() == AppConstants.STATUS_DISABLED) { - isEnabled = false; - } - - Boolean isPathRecursive = xRes.getIsRecursive() == RangerCommonEnums.BOOL_TRUE; - Boolean isTableExcludes = xRes.getTableType() == RangerCommonEnums.POLICY_EXCLUSION; - Boolean isColumnExcludes = xRes.getColumnType() == RangerCommonEnums.POLICY_EXCLUSION; - - if (StringUtils.equalsIgnoreCase(serviceType, "hdfs")) { - toRangerResourceList(xRes.getName(), "path", Boolean.FALSE, isPathRecursive, resources); - } else if (StringUtils.equalsIgnoreCase(serviceType, "hbase")) { - toRangerResourceList(xRes.getTables(), "table", isTableExcludes, Boolean.FALSE, resources); - toRangerResourceList(xRes.getColumnFamilies(), "column-family", Boolean.FALSE, Boolean.FALSE, resources); - toRangerResourceList(xRes.getColumns(), "column", isColumnExcludes, Boolean.FALSE, resources); - } else if (StringUtils.equalsIgnoreCase(serviceType, "hive")) { - toRangerResourceList(xRes.getDatabases(), "database", Boolean.FALSE, Boolean.FALSE, resources); - toRangerResourceList(xRes.getTables(), "table", isTableExcludes, Boolean.FALSE, resources); - toRangerResourceList(xRes.getColumns(), "column", isColumnExcludes, Boolean.FALSE, resources); - toRangerResourceList(xRes.getUdfs(), "udf", Boolean.FALSE, Boolean.FALSE, resources); - } else if (StringUtils.equalsIgnoreCase(serviceType, "knox")) { - toRangerResourceList(xRes.getTopologies(), "topology", Boolean.FALSE, Boolean.FALSE, resources); - toRangerResourceList(xRes.getServices(), "service", Boolean.FALSE, Boolean.FALSE, resources); - } else if (StringUtils.equalsIgnoreCase(serviceType, "storm")) { - toRangerResourceList(xRes.getTopologies(), "topology", Boolean.FALSE, Boolean.FALSE, resources); - } - - policyItems = getPolicyItemListForRes(xRes, svcDef); - - policy.setService(serviceName); - policy.setName(name); - policy.setDescription(description); - policy.setIsAuditEnabled(isAuditEnabled); - policy.setIsEnabled(isEnabled); - policy.setResources(resources); - policy.setPolicyItems(policyItems); - - policy.setCreateTime(xRes.getCreateTime()); - policy.setUpdateTime(xRes.getUpdateTime()); - - XXPortalUser createdByUser = daoMgr.getXXPortalUser().getById(xRes.getAddedByUserId()); - XXPortalUser updByUser = daoMgr.getXXPortalUser().getById(xRes.getUpdatedByUserId()); - - if (createdByUser != null) { - policy.setCreatedBy(createdByUser.getLoginId()); - } - if (updByUser != null) { - policy.setUpdatedBy(updByUser.getLoginId()); - } - - policy.setId(xRes.getId()); - - return policy; - } - - private Map toRangerResourceList(String resourceString, String resourceType, Boolean isExcludes, Boolean isRecursive, Map resources) { - Map ret = resources == null ? new HashMap() : resources; - - if(StringUtils.isNotBlank(resourceString)) { - RangerPolicy.RangerPolicyResource resource = ret.get(resourceType); - - if(resource == null) { - resource = new RangerPolicy.RangerPolicyResource(); - resource.setIsExcludes(isExcludes); - resource.setIsRecursive(isRecursive); - - ret.put(resourceType, resource); - } - - Collections.addAll(resource.getValues(), resourceString.split(",")); - } - - return ret; - } - - private List getPolicyItemListForRes(XXResource xRes, XXServiceDef svcDef) { - List policyItems = new ArrayList(); - - SearchCriteria sc = new SearchCriteria(); - - sc.addParam("resourceId", xRes.getId()); - List permMapList = xPermMapService.searchXPermMaps(sc).getVXPermMaps(); - - HashMap> sortedPermMap = new HashMap>(); - - // re-group the list with permGroup as the key - if (permMapList != null) { - for(VXPermMap permMap : permMapList) { - String permGrp = permMap.getPermGroup(); - List sortedList = sortedPermMap.get(permGrp); - - if(sortedList == null) { - sortedList = new ArrayList(); - sortedPermMap.put(permGrp, sortedList); - } - - sortedList.add(permMap); - } - } - - for (Entry> entry : sortedPermMap.entrySet()) { - List userList = new ArrayList(); - List groupList = new ArrayList(); - List accessList = new ArrayList(); - String ipAddress = null; - - RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem(); - - for(VXPermMap permMap : entry.getValue()) { - if(permMap.getPermFor() == AppConstants.XA_PERM_FOR_USER) { - String userName = getUserName(permMap); - - if (! userList.contains(userName)) { - userList.add(userName); - } - } else if(permMap.getPermFor() == AppConstants.XA_PERM_FOR_GROUP) { - String groupName = getGroupName(permMap); - - if (! groupList.contains(groupName)) { - groupList.add(groupName); - } - } + private static final Logger logger = LoggerFactory.getLogger(PatchMigration_J10002.class); + + static Set unsupportedLegacyPermTypes = new HashSet<>(); + + private static int policyCounter; + private static int serviceCounter; + + @Autowired + RangerDaoManager daoMgr; + + @Autowired + ServiceDBStore svcDBStore; + + @Autowired + JSONUtil jsonUtil; + + @Autowired + RangerPolicyService policyService; + + @Autowired + StringUtil stringUtil; + + @Autowired + XPolicyService xPolService; + + @Autowired + XPermMapService xPermMapService; + + @Autowired + RangerBizUtil bizUtil; + + public static void main(String[] args) { + logger.info("main()"); + + try { + PatchMigration_J10002 loader = (PatchMigration_J10002) CLIUtil.getBean(PatchMigration_J10002.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); + } + } + + @Override + public void init() throws Exception { + // Do Nothing + } + + @Override + public void printStats() { + logger.info("Total Number of migrated repositories/services: {}", serviceCounter); + logger.info("Total Number of migrated resources/policies: {}", policyCounter); + } + + @Override + public void execLoad() { + logger.info("==> MigrationPatch.execLoad()"); + + try { + migrateServicesToNewSchema(); + migratePoliciesToNewSchema(); + updateSequences(); + } catch (Exception e) { + logger.error("Error while migrating data.", e); + } + + logger.info("<== MigrationPatch.execLoad()"); + } + + public void migrateServicesToNewSchema() throws Exception { + logger.info("==> MigrationPatch.migrateServicesToNewSchema()"); + + try { + List repoList = daoMgr.getXXAsset().getAll(); + + if (repoList.isEmpty()) { + return; + } + + EmbeddedServiceDefsUtil.instance().init(svcDBStore); + + svcDBStore.setPopulateExistingBaseFields(true); + + for (XXAsset xAsset : repoList) { + if (xAsset.getActiveStatus() == AppConstants.STATUS_DELETED) { + continue; + } + + RangerService existing = svcDBStore.getServiceByName(xAsset.getName()); + + if (existing != null) { + logger.info("Repository/Service already exists. Ignoring migration of repo: {}", xAsset.getName()); + continue; + } + + RangerService service = new RangerService(); + + service = mapXAssetToService(service, xAsset); + service = svcDBStore.createService(service); + + serviceCounter++; + + logger.info("New Service created. ServiceName: {}", service.getName()); + } + svcDBStore.setPopulateExistingBaseFields(false); + } catch (Exception e) { + throw new Exception("Error while migrating data to new Plugin Schema.", e); + } + + logger.info("<== MigrationPatch.migrateServicesToNewSchema()"); + } + + public void migratePoliciesToNewSchema() throws Exception { + logger.info("==> MigrationPatch.migratePoliciesToNewSchema()"); + + try { + List resList = daoMgr.getXXResource().getAll(); + + if (resList.isEmpty()) { + return; + } + + svcDBStore.setPopulateExistingBaseFields(true); + + for (XXResource xRes : resList) { + if (xRes.getResourceStatus() == AppConstants.STATUS_DELETED) { + continue; + } + + XXAsset xAsset = daoMgr.getXXAsset().getById(xRes.getAssetId()); + + if (xAsset == null) { + logger.error("No Repository found for policyName: {}", xRes.getPolicyName()); + continue; + } + + RangerService service = svcDBStore.getServiceByName(xAsset.getName()); + + if (service == null) { + logger.error("No Service found for policy. Ignoring migration of such policy, policyName: {}", xRes.getPolicyName()); + continue; + } + + XXPolicy existing = daoMgr.getXXPolicy().findByNameAndServiceId(xRes.getPolicyName(), service.getId()); + + if (existing != null) { + logger.info("Policy already exists. Ignoring migration of policy: {}", existing.getName()); + continue; + } + + RangerPolicy policy = new RangerPolicy(); + + policy = mapXResourceToPolicy(policy, xRes, service); + + if (policy != null) { + policy = svcDBStore.createPolicy(policy); + + policyCounter++; + + logger.info("New policy created. policyName: {}", policy.getName()); + } + } + + svcDBStore.setPopulateExistingBaseFields(false); + } catch (Exception e) { + throw new Exception("Error while migrating data to new Plugin Schema.", e); + } + + logger.info("<== MigrationPatch.migratePoliciesToNewSchema()"); + } + + private RangerService mapXAssetToService(RangerService service, XXAsset xAsset) throws Exception { + String name = xAsset.getName(); + String description = xAsset.getDescription(); + int typeInt = xAsset.getAssetType(); + XXServiceDef serviceDef = daoMgr.getXXServiceDef().findByName(AppConstants.getLabelFor_AssetType(typeInt).toLowerCase()); + + if (serviceDef == null) { + throw new Exception("No ServiceDefinition found for repository: " + name); + } + + String type = serviceDef.getName(); + Map configs = jsonUtil.jsonToMap(xAsset.getConfig()); + List mandatoryConfigs = daoMgr.getXXServiceConfigDef().findByServiceDefName(type); + + for (XXServiceConfigDef serviceConf : mandatoryConfigs) { + if (serviceConf.getIsMandatory()) { + if (!stringUtil.isEmpty(configs.get(serviceConf.getName()))) { + continue; + } + + String dataType = serviceConf.getType(); + String defaultValue = serviceConf.getDefaultvalue(); + + if (stringUtil.isEmpty(defaultValue)) { + defaultValue = getDefaultValueForDataType(dataType); + } + + configs.put(serviceConf.getName(), defaultValue); + } + } + + service.setType(type); + service.setName(name); + service.setDescription(description); + service.setConfigs(configs); + service.setCreateTime(xAsset.getCreateTime()); + service.setUpdateTime(xAsset.getUpdateTime()); + + XXPortalUser createdByUser = daoMgr.getXXPortalUser().getById(xAsset.getAddedByUserId()); + XXPortalUser updByUser = daoMgr.getXXPortalUser().getById(xAsset.getUpdatedByUserId()); + + if (createdByUser != null) { + service.setCreatedBy(createdByUser.getLoginId()); + } + + if (updByUser != null) { + service.setUpdatedBy(updByUser.getLoginId()); + } + + service.setId(xAsset.getId()); + + return service; + } + + private String getDefaultValueForDataType(String dataType) { + String defaultValue = ""; + + switch (dataType) { + case "int": + defaultValue = "0"; + break; + case "string": + defaultValue = "unknown"; + break; + case "bool": + defaultValue = "false"; + break; + case "enum": + defaultValue = "0"; + break; + case "password": + defaultValue = "password"; + break; + default: + break; + } + + return defaultValue; + } + + private RangerPolicy mapXResourceToPolicy(RangerPolicy policy, XXResource xRes, RangerService service) { + String serviceName = service.getName(); + String serviceType = service.getType(); + String name = xRes.getPolicyName(); + String description = xRes.getDescription(); + boolean isAuditEnabled = true; + boolean isEnabled = true; + XXServiceDef svcDef = daoMgr.getXXServiceDef().findByName(serviceType); + + if (svcDef == null) { + logger.error("{} service-def not found. Skipping policy {}", serviceType, name); + + return null; + } + + List auditMapList = daoMgr.getXXAuditMap().findByResourceId(xRes.getId()); + + if (stringUtil.isEmpty(auditMapList)) { + isAuditEnabled = false; + } + + if (xRes.getResourceStatus() == AppConstants.STATUS_DISABLED) { + isEnabled = false; + } + + Boolean isPathRecursive = xRes.getIsRecursive() == RangerCommonEnums.BOOL_TRUE; + Boolean isTableExcludes = xRes.getTableType() == RangerCommonEnums.POLICY_EXCLUSION; + Boolean isColumnExcludes = xRes.getColumnType() == RangerCommonEnums.POLICY_EXCLUSION; + + Map resources = new HashMap<>(); + + if (StringUtils.equalsIgnoreCase(serviceType, "hdfs")) { + toRangerResourceList(xRes.getName(), "path", Boolean.FALSE, isPathRecursive, resources); + } else if (StringUtils.equalsIgnoreCase(serviceType, "hbase")) { + toRangerResourceList(xRes.getTables(), "table", isTableExcludes, Boolean.FALSE, resources); + toRangerResourceList(xRes.getColumnFamilies(), "column-family", Boolean.FALSE, Boolean.FALSE, resources); + toRangerResourceList(xRes.getColumns(), "column", isColumnExcludes, Boolean.FALSE, resources); + } else if (StringUtils.equalsIgnoreCase(serviceType, "hive")) { + toRangerResourceList(xRes.getDatabases(), "database", Boolean.FALSE, Boolean.FALSE, resources); + toRangerResourceList(xRes.getTables(), "table", isTableExcludes, Boolean.FALSE, resources); + toRangerResourceList(xRes.getColumns(), "column", isColumnExcludes, Boolean.FALSE, resources); + toRangerResourceList(xRes.getUdfs(), "udf", Boolean.FALSE, Boolean.FALSE, resources); + } else if (StringUtils.equalsIgnoreCase(serviceType, "knox")) { + toRangerResourceList(xRes.getTopologies(), "topology", Boolean.FALSE, Boolean.FALSE, resources); + toRangerResourceList(xRes.getServices(), "service", Boolean.FALSE, Boolean.FALSE, resources); + } else if (StringUtils.equalsIgnoreCase(serviceType, "storm")) { + toRangerResourceList(xRes.getTopologies(), "topology", Boolean.FALSE, Boolean.FALSE, resources); + } + + List policyItems = getPolicyItemListForRes(xRes, svcDef); + + policy.setService(serviceName); + policy.setName(name); + policy.setDescription(description); + policy.setIsAuditEnabled(isAuditEnabled); + policy.setIsEnabled(isEnabled); + policy.setResources(resources); + policy.setPolicyItems(policyItems); + policy.setCreateTime(xRes.getCreateTime()); + policy.setUpdateTime(xRes.getUpdateTime()); + + XXPortalUser createdByUser = daoMgr.getXXPortalUser().getById(xRes.getAddedByUserId()); + XXPortalUser updByUser = daoMgr.getXXPortalUser().getById(xRes.getUpdatedByUserId()); + + if (createdByUser != null) { + policy.setCreatedBy(createdByUser.getLoginId()); + } + + if (updByUser != null) { + policy.setUpdatedBy(updByUser.getLoginId()); + } + + policy.setId(xRes.getId()); + + return policy; + } + + private Map toRangerResourceList(String resourceString, String resourceType, Boolean isExcludes, Boolean isRecursive, Map resources) { + Map ret = resources == null ? new HashMap<>() : resources; + + if (StringUtils.isNotBlank(resourceString)) { + RangerPolicy.RangerPolicyResource resource = ret.get(resourceType); + + if (resource == null) { + resource = new RangerPolicy.RangerPolicyResource(); + + resource.setIsExcludes(isExcludes); + resource.setIsRecursive(isRecursive); + + ret.put(resourceType, resource); + } + + Collections.addAll(resource.getValues(), resourceString.split(",")); + } + + return ret; + } + + private List getPolicyItemListForRes(XXResource xRes, XXServiceDef svcDef) { + List policyItems = new ArrayList<>(); + SearchCriteria sc = new SearchCriteria(); + + sc.addParam("resourceId", xRes.getId()); + + List permMapList = xPermMapService.searchXPermMaps(sc).getVXPermMaps(); + + HashMap> sortedPermMap = new HashMap<>(); + + // re-group the list with permGroup as the key + if (permMapList != null) { + for (VXPermMap permMap : permMapList) { + String permGrp = permMap.getPermGroup(); + List sortedList = sortedPermMap.computeIfAbsent(permGrp, k -> new ArrayList<>()); + + sortedList.add(permMap); + } + } + + for (Entry> entry : sortedPermMap.entrySet()) { + List userList = new ArrayList<>(); + List groupList = new ArrayList<>(); + List accessList = new ArrayList<>(); + String ipAddress = null; + RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem(); + + for (VXPermMap permMap : entry.getValue()) { + if (permMap.getPermFor() == AppConstants.XA_PERM_FOR_USER) { + String userName = getUserName(permMap); + + if (!userList.contains(userName)) { + userList.add(userName); + } + } else if (permMap.getPermFor() == AppConstants.XA_PERM_FOR_GROUP) { + String groupName = getGroupName(permMap); + + if (!groupList.contains(groupName)) { + groupList.add(groupName); + } + } + + String accessType = ServiceUtil.toAccessType(permMap.getPermType()); + + if (StringUtils.isBlank(accessType) || unsupportedLegacyPermTypes.contains(accessType)) { + logger.info("{}: is not a valid access-type, ignoring access-type for policy: {}", accessType, xRes.getPolicyName()); + + continue; + } + + if (StringUtils.equalsIgnoreCase(accessType, "Admin")) { + policyItem.setDelegateAdmin(Boolean.TRUE); + + if (svcDef.getId() == EmbeddedServiceDefsUtil.instance().getHBaseServiceDefId()) { + addAccessType(accessType, accessList); + } + } else { + addAccessType(accessType, accessList); + } + + ipAddress = permMap.getIpAddress(); + } + + if (CollectionUtils.isEmpty(accessList)) { + logger.info("no access specified. ignoring policyItem for policy: {}", xRes.getPolicyName()); + + continue; + } + + if (CollectionUtils.isEmpty(userList) && CollectionUtils.isEmpty(groupList)) { + logger.info("no user or group specified. ignoring policyItem for policy: {}", xRes.getPolicyName()); + + continue; + } + + policyItem.setUsers(userList); + policyItem.setGroups(groupList); + policyItem.setAccesses(accessList); + + if (ipAddress != null && !ipAddress.isEmpty()) { + XXPolicyConditionDef policyCond = daoMgr.getXXPolicyConditionDef().findByServiceDefIdAndName(svcDef.getId(), "ip-range"); + + if (policyCond != null) { + RangerPolicy.RangerPolicyItemCondition ipCondition = new RangerPolicy.RangerPolicyItemCondition("ip-range", Collections.singletonList(ipAddress)); + + policyItem.addCondition(ipCondition); + } + } + + policyItems.add(policyItem); + } + + return policyItems; + } + + private void addAccessType(String accessType, List accessList) { + boolean alreadyExists = false; - String accessType = ServiceUtil.toAccessType(permMap.getPermType()); - if(StringUtils.isBlank(accessType) || unsupportedLegacyPermTypes.contains(accessType)) { - logger.info(accessType + ": is not a valid access-type, ignoring accesstype for policy: " + xRes.getPolicyName()); - continue; - } + for (RangerPolicyItemAccess access : accessList) { + if (StringUtils.equalsIgnoreCase(accessType, access.getType())) { + alreadyExists = true; - if(StringUtils.equalsIgnoreCase(accessType, "Admin")) { - policyItem.setDelegateAdmin(Boolean.TRUE); - if ( svcDef.getId() == EmbeddedServiceDefsUtil.instance().getHBaseServiceDefId()) { - addAccessType(accessType, accessList); - } - } else { - addAccessType(accessType, accessList); - } + break; + } + } - ipAddress = permMap.getIpAddress(); - } + if (!alreadyExists) { + accessList.add(new RangerPolicyItemAccess(accessType)); + } + } - if(CollectionUtils.isEmpty(accessList)) { - logger.info("no access specified. ignoring policyItem for policy: " + xRes.getPolicyName()); - continue; - } + private void updateSequences() { + daoMgr.getXXServiceDef().updateSequence(); + daoMgr.getXXService().updateSequence(); + daoMgr.getXXPolicy().updateSequence(); + } - if(CollectionUtils.isEmpty(userList) && CollectionUtils.isEmpty(groupList)) { - logger.info("no user or group specified. ignoring policyItem for policy: " + xRes.getPolicyName()); - continue; - } + private String getUserName(VXPermMap permMap) { + String userName = permMap.getUserName(); - policyItem.setUsers(userList); - policyItem.setGroups(groupList); - policyItem.setAccesses(accessList); + if (userName == null || userName.isEmpty()) { + Long userId = permMap.getUserId(); - if(ipAddress != null && !ipAddress.isEmpty()) { - XXPolicyConditionDef policyCond = daoMgr.getXXPolicyConditionDef().findByServiceDefIdAndName(svcDef.getId(), "ip-range"); + if (userId != null) { + XXUser xxUser = daoMgr.getXXUser().getById(userId); - if(policyCond != null) { - RangerPolicy.RangerPolicyItemCondition ipCondition = new RangerPolicy.RangerPolicyItemCondition("ip-range", Collections.singletonList(ipAddress)); + if (xxUser != null) { + userName = xxUser.getName(); + } + } + } - policyItem.addCondition(ipCondition); - } - } + return userName; + } - policyItems.add(policyItem); - } + private String getGroupName(VXPermMap permMap) { + String groupName = permMap.getGroupName(); - return policyItems; - } + if (groupName == null || groupName.isEmpty()) { + Long groupId = permMap.getGroupId(); - private void addAccessType(String accessType, List accessList) { - boolean alreadyExists = false; + if (groupId != null) { + XXGroup xxGroup = daoMgr.getXXGroup().getById(groupId); - for(RangerPolicyItemAccess access : accessList) { - if(StringUtils.equalsIgnoreCase(accessType, access.getType())) { - alreadyExists = true; + if (xxGroup != null) { + groupName = xxGroup.getName(); + } + } + } - break; - } - } - - if(!alreadyExists) { - accessList.add(new RangerPolicyItemAccess(accessType)); - } - } - - private void updateSequences() { - daoMgr.getXXServiceDef().updateSequence(); - daoMgr.getXXService().updateSequence(); - daoMgr.getXXPolicy().updateSequence(); - } - - private String getUserName(VXPermMap permMap) { - String userName = permMap.getUserName(); - - if(userName == null || userName.isEmpty()) { - Long userId = permMap.getUserId(); - - if(userId != null) { - XXUser xxUser = daoMgr.getXXUser().getById(userId); - - if(xxUser != null) { - userName = xxUser.getName(); - } - } - } - - return userName; - } - - private String getGroupName(VXPermMap permMap) { - String groupName = permMap.getGroupName(); - - if(groupName == null || groupName.isEmpty()) { - Long groupId = permMap.getGroupId(); - - if(groupId != null) { - XXGroup xxGroup = daoMgr.getXXGroup().getById(groupId); - - if(xxGroup != null) { - groupName = xxGroup.getName(); - } - } - } + return groupName; + } - return groupName; - } + static { + unsupportedLegacyPermTypes.add("Unknown"); + unsupportedLegacyPermTypes.add("Reset"); + unsupportedLegacyPermTypes.add("Obfuscate"); + unsupportedLegacyPermTypes.add("Mask"); + } } diff --git a/security-admin/src/main/java/org/apache/ranger/patch/PatchPasswordEncryption_J10001.java b/security-admin/src/main/java/org/apache/ranger/patch/PatchPasswordEncryption_J10001.java index 1da16e52d3..1d1936f8e4 100644 --- a/security-admin/src/main/java/org/apache/ranger/patch/PatchPasswordEncryption_J10001.java +++ b/security-admin/src/main/java/org/apache/ranger/patch/PatchPasswordEncryption_J10001.java @@ -16,8 +16,6 @@ */ package org.apache.ranger.patch; -import java.util.List; - import org.apache.ranger.common.StringUtil; import org.apache.ranger.db.RangerDaoManager; import org.apache.ranger.entity.XXAsset; @@ -28,73 +26,83 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; +import java.util.List; + @Component public class PatchPasswordEncryption_J10001 extends BaseLoader { - private static final Logger logger = LoggerFactory.getLogger(PatchPasswordEncryption_J10001.class); - int lineCount = 0; - - @Autowired - RangerDaoManager 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 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); - } - } + private static final Logger logger = LoggerFactory.getLogger(PatchPasswordEncryption_J10001.class); + + int lineCount; + + @Autowired + RangerDaoManager xaDaoManager; + + @Autowired + StringUtil stringUtil; + + @Autowired + XAssetService xAssetService; + + public PatchPasswordEncryption_J10001() { + } + + 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); + } + } + + @Override + public void printStats() { + logger.info("Time taken so far:{}, moreToProcess={}", timeTakenSoFar(lineCount), isMoreToProcess()); + + print(lineCount, "Processed lines"); + } + + @Override + public void execLoad() { + encryptLookupUserPassword(); + } + + private void encryptLookupUserPassword() { + List xAssetList = xaDaoManager.getXXAsset().getAll(); + String oldConfig; + String newConfig; + + for (XXAsset xAsset : xAssetList) { + oldConfig = xAsset.getConfig(); + newConfig = null; + + 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 : "); + } + } } diff --git a/security-admin/src/main/java/org/apache/ranger/patch/PatchPermissionModel_J10003.java b/security-admin/src/main/java/org/apache/ranger/patch/PatchPermissionModel_J10003.java index 25f2db9baf..18a6c87db0 100644 --- a/security-admin/src/main/java/org/apache/ranger/patch/PatchPermissionModel_J10003.java +++ b/security-admin/src/main/java/org/apache/ranger/patch/PatchPermissionModel_J10003.java @@ -17,20 +17,12 @@ package org.apache.ranger.patch; -import java.io.IOException; -import java.nio.charset.Charset; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.ArrayList; -import java.util.List; import org.apache.commons.lang.StringUtils; +import org.apache.ranger.biz.XUserMgr; +import org.apache.ranger.common.RangerConstants; import org.apache.ranger.db.RangerDaoManager; import org.apache.ranger.entity.XXPortalUser; import org.apache.ranger.service.XPortalUserService; -import org.apache.ranger.biz.XUserMgr; -import org.apache.ranger.common.RangerConstants; import org.apache.ranger.util.CLIUtil; import org.apache.ranger.view.VXPortalUser; import org.slf4j.Logger; @@ -39,153 +31,195 @@ import org.springframework.stereotype.Component; import org.springframework.util.CollectionUtils; +import java.io.IOException; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.List; + @Component public class PatchPermissionModel_J10003 extends BaseLoader { - private static final Logger logger = LoggerFactory - .getLogger(PatchPermissionModel_J10003.class); - - @Autowired - XUserMgr xUserMgr; - - @Autowired - XPortalUserService xPortalUserService; - - @Autowired - RangerDaoManager daoManager; - - private static boolean grantAllUsers=false; - private static String usersListFileName=null; - private final static Charset ENCODING = StandardCharsets.UTF_8; - public static void main(String[] args) { - logger.info("main()"); - try { - if(args!=null && args.length>0){ - if(StringUtils.equalsIgnoreCase("ALL", args[0])){ - grantAllUsers=true; - }else if(!StringUtils.isEmpty(args[0])){ - usersListFileName=args[0]; - } - } - PatchPermissionModel_J10003 loader = (PatchPermissionModel_J10003) CLIUtil - .getBean(PatchPermissionModel_J10003.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); - } - } - - @Override - public void init() throws Exception { - // Do Nothing - } - - @Override - public void execLoad() { - logger.info("==> PermissionPatch.execLoad()"); - assignPermissionToExistingUsers(); - logger.info("<== PermissionPatch.execLoad()"); - } - - public void assignPermissionToExistingUsers() { - int countUserPermissionUpdated = 0; - Long userCount=daoManager.getXXPortalUser().getAllCount(); - List xXPortalUsers=null; - Long patchModeMaxLimit=Long.valueOf(500L); - try{ - if (userCount!=null && userCount>0){ - List loginIdList=readUserNamesFromFile(usersListFileName); - if(!CollectionUtils.isEmpty(loginIdList)){ - xXPortalUsers=new ArrayList(); - XXPortalUser xXPortalUser=null; - for(String loginId:loginIdList){ - try{ - xXPortalUser=daoManager.getXXPortalUser().findByLoginId(loginId); - if(xXPortalUser!=null){ - xXPortalUsers.add(xXPortalUser); - }else{ - logger.info("User "+loginId+" doesn't exist!"); - } - }catch(Exception ex){ - } - } - countUserPermissionUpdated=assignPermissions(xXPortalUsers); - logger.info("Permissions assigned to "+countUserPermissionUpdated + " of "+loginIdList.size()); - }else if(userCount.compareTo(Long.valueOf(patchModeMaxLimit))<0 || grantAllUsers){ - xXPortalUsers=daoManager.getXXPortalUser().findAllXPortalUser(); - if(!CollectionUtils.isEmpty(xXPortalUsers)){ - countUserPermissionUpdated=assignPermissions(xXPortalUsers); - logger.info("Permissions assigned to "+countUserPermissionUpdated + " of "+xXPortalUsers.size()); - } - }else{ - //if total no. of users are more than 500 then process ADMIN and KEY_ADMIN users only to avoid timeout - xXPortalUsers=daoManager.getXXPortalUser().findByRole(RangerConstants.ROLE_SYS_ADMIN); - if(!CollectionUtils.isEmpty(xXPortalUsers)){ - countUserPermissionUpdated=assignPermissions(xXPortalUsers); - logger.info("Permissions assigned to users having role:"+RangerConstants.ROLE_SYS_ADMIN+". Processed:"+countUserPermissionUpdated + " of total "+xXPortalUsers.size()); - } - xXPortalUsers=daoManager.getXXPortalUser().findByRole(RangerConstants.ROLE_KEY_ADMIN); - if(!CollectionUtils.isEmpty(xXPortalUsers)){ - countUserPermissionUpdated=assignPermissions(xXPortalUsers); - logger.info("Permissions assigned to users having role:"+RangerConstants.ROLE_KEY_ADMIN+". Processed:"+countUserPermissionUpdated + " of total "+xXPortalUsers.size()); - } - logger.info("Please execute this patch separately with argument 'ALL' to assign permission to remaining users "); - System.out.println("Please execute this patch separately with argument 'ALL' to assign module permissions to remaining users!!"); - } - } - }catch(Exception ex){ - } - } - - @Override - public void printStats() { - } - - private int assignPermissions(List xXPortalUsers){ - int countUserPermissionUpdated = 0; - if(!CollectionUtils.isEmpty(xXPortalUsers)){ - for (XXPortalUser xPortalUser : xXPortalUsers) { - try{ - if(xPortalUser!=null){ - VXPortalUser vPortalUser = xPortalUserService.populateViewBean(xPortalUser); - if(vPortalUser!=null){ - vPortalUser.setUserRoleList(daoManager.getXXPortalUserRole().findXPortalUserRolebyXPortalUserId(vPortalUser.getId())); - xUserMgr.assignPermissionToUser(vPortalUser, false); - countUserPermissionUpdated += 1; - logger.info("Permissions assigned/updated on base of User's Role, UserId [" + xPortalUser.getId() + "]"); - } - } - }catch(Exception ex){ - } - } - } - return countUserPermissionUpdated; - } - - private List readUserNamesFromFile(String aFileName) throws IOException { - List userNames=new ArrayList(); - if(!StringUtils.isEmpty(aFileName)){ - Path path = Paths.get(aFileName); - if (Files.exists(path) && Files.isRegularFile(path)) { - List fileContents=Files.readAllLines(path, ENCODING); - if(fileContents!=null && !fileContents.isEmpty()){ - for(String line:fileContents){ - if(!StringUtils.isEmpty(line) && !userNames.contains(line)){ - try{ - userNames.add(line.trim()); - }catch(Exception ex){ - } - } - } - } - } - } - return userNames; - } + private static final Logger logger = LoggerFactory.getLogger(PatchPermissionModel_J10003.class); + + private static final Charset ENCODING = StandardCharsets.UTF_8; + + private static boolean grantAllUsers; + private static String usersListFileName; + + @Autowired + XUserMgr xUserMgr; + + @Autowired + XPortalUserService xPortalUserService; + + @Autowired + RangerDaoManager daoManager; + + public static void main(String[] args) { + logger.info("main()"); + + try { + if (args != null && args.length > 0) { + if (StringUtils.equalsIgnoreCase("ALL", args[0])) { + grantAllUsers = true; + } else if (!StringUtils.isEmpty(args[0])) { + usersListFileName = args[0]; + } + } + + PatchPermissionModel_J10003 loader = (PatchPermissionModel_J10003) CLIUtil.getBean(PatchPermissionModel_J10003.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); + } + } + + @Override + public void init() throws Exception { + // Do Nothing + } + + @Override + public void printStats() { + } + + @Override + public void execLoad() { + logger.info("==> PermissionPatch.execLoad()"); + + assignPermissionToExistingUsers(); + + logger.info("<== PermissionPatch.execLoad()"); + } + + public void assignPermissionToExistingUsers() { + Long userCount = daoManager.getXXPortalUser().getAllCount(); + Long patchModeMaxLimit = 500L; + + try { + if (userCount != null && userCount > 0) { + List loginIdList = readUserNamesFromFile(usersListFileName); + + if (!CollectionUtils.isEmpty(loginIdList)) { + List xXPortalUsers = new ArrayList<>(); + + for (String loginId : loginIdList) { + try { + XXPortalUser xXPortalUser = daoManager.getXXPortalUser().findByLoginId(loginId); + + if (xXPortalUser != null) { + xXPortalUsers.add(xXPortalUser); + } else { + logger.info("User {} doesn't exist!", loginId); + } + } catch (Exception ex) { + // ignore + } + } + + int countUserPermissionUpdated = assignPermissions(xXPortalUsers); + + logger.info("Permissions assigned to {} of {}", countUserPermissionUpdated, loginIdList.size()); + } else if (userCount.compareTo(patchModeMaxLimit) < 0 || grantAllUsers) { + List xXPortalUsers = daoManager.getXXPortalUser().findAllXPortalUser(); + + if (!CollectionUtils.isEmpty(xXPortalUsers)) { + int countUserPermissionUpdated = assignPermissions(xXPortalUsers); + + logger.info("Permissions assigned to {} of {}", countUserPermissionUpdated, xXPortalUsers.size()); + } + } else { + //if total no. of users are more than 500 then process ADMIN and KEY_ADMIN users only to avoid timeout + List xXPortalUsers = daoManager.getXXPortalUser().findByRole(RangerConstants.ROLE_SYS_ADMIN); + + if (!CollectionUtils.isEmpty(xXPortalUsers)) { + int countUserPermissionUpdated = assignPermissions(xXPortalUsers); + + logger.info("Permissions assigned to users having role:{}. Processed:{} of total {}", RangerConstants.ROLE_SYS_ADMIN, countUserPermissionUpdated, xXPortalUsers.size()); + } + + xXPortalUsers = daoManager.getXXPortalUser().findByRole(RangerConstants.ROLE_KEY_ADMIN); + + if (!CollectionUtils.isEmpty(xXPortalUsers)) { + int countUserPermissionUpdated = assignPermissions(xXPortalUsers); + + logger.info("Permissions assigned to users having role:{}. Processed:{} of total {}", RangerConstants.ROLE_SYS_ADMIN, countUserPermissionUpdated, xXPortalUsers.size()); + } + + logger.info("Please execute this patch separately with argument 'ALL' to assign permission to remaining users "); + System.out.println("Please execute this patch separately with argument 'ALL' to assign module permissions to remaining users!!"); + } + } + } catch (Exception ex) { + // ignore + } + } + + private int assignPermissions(List xXPortalUsers) { + int countUserPermissionUpdated = 0; + + if (!CollectionUtils.isEmpty(xXPortalUsers)) { + for (XXPortalUser xPortalUser : xXPortalUsers) { + try { + if (xPortalUser != null) { + VXPortalUser vPortalUser = xPortalUserService.populateViewBean(xPortalUser); + + if (vPortalUser != null) { + vPortalUser.setUserRoleList(daoManager.getXXPortalUserRole().findXPortalUserRolebyXPortalUserId(vPortalUser.getId())); + + xUserMgr.assignPermissionToUser(vPortalUser, false); + + countUserPermissionUpdated += 1; + + logger.info("Permissions assigned/updated on base of User's Role, UserId [{}]", xPortalUser.getId()); + } + } + } catch (Exception ex) { + // ignore + } + } + } + + return countUserPermissionUpdated; + } + + private List readUserNamesFromFile(String aFileName) throws IOException { + List userNames = new ArrayList<>(); + + if (!StringUtils.isEmpty(aFileName)) { + Path path = Paths.get(aFileName); + + if (Files.exists(path) && Files.isRegularFile(path)) { + List fileContents = Files.readAllLines(path, ENCODING); + + if (fileContents != null && !fileContents.isEmpty()) { + for (String line : fileContents) { + if (!StringUtils.isEmpty(line) && !userNames.contains(line)) { + try { + userNames.add(line.trim()); + } catch (Exception ex) { + // ignore + } + } + } + } + } + } + + return userNames; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/patch/PatchPreSql_057_ForUpdateToUniqueGUID_J10052.java b/security-admin/src/main/java/org/apache/ranger/patch/PatchPreSql_057_ForUpdateToUniqueGUID_J10052.java index 2c59390098..33c72f58ac 100644 --- a/security-admin/src/main/java/org/apache/ranger/patch/PatchPreSql_057_ForUpdateToUniqueGUID_J10052.java +++ b/security-admin/src/main/java/org/apache/ranger/patch/PatchPreSql_057_ForUpdateToUniqueGUID_J10052.java @@ -6,7 +6,7 @@ * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -17,8 +17,6 @@ package org.apache.ranger.patch; -import java.util.List; - import org.apache.commons.collections.CollectionUtils; import org.apache.ranger.authorization.utils.JsonUtils; import org.apache.ranger.biz.ServiceDBStore; @@ -36,153 +34,161 @@ import org.springframework.stereotype.Component; import org.springframework.transaction.PlatformTransactionManager; +import java.util.List; + /** * This patch will regenerate new GUID and update policies which has duplicate GUID for every service. - * */ @Component public class PatchPreSql_057_ForUpdateToUniqueGUID_J10052 extends BaseLoader { - private static final Logger logger = LoggerFactory.getLogger(PatchPreSql_057_ForUpdateToUniqueGUID_J10052.class); - - @Autowired - RangerDaoManager daoMgr; - - @Autowired - ServiceDBStore svcStore; - - @Autowired - GUIDUtil guidUtil; - - @Autowired - @Qualifier(value = "transactionManager") - PlatformTransactionManager txManager; - - - public static void main(String[] args) { - logger.info("main()"); - try { - PatchPreSql_057_ForUpdateToUniqueGUID_J10052 loader = (PatchPreSql_057_ForUpdateToUniqueGUID_J10052) CLIUtil.getBean(PatchPreSql_057_ForUpdateToUniqueGUID_J10052.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); - } - } - - @Override - public void init() throws Exception { - // Do Nothing - } - - @Override - public void execLoad() { - - try { - logger.info("==> updatePolicyGUIDToUniqueValue()"); - updatePolicyGUIDToUniqueValue(); - } catch (Exception e) { - logger.error("Error while updatePolicyGUIDToUniqueValue()", e); - System.exit(1); - } - - logger.info("<== updatePolicyGUIDToUniqueValue.execLoad()"); - } - - @Override - public void printStats() { - logger.info("runnig updatePolicyGUIDToUniqueValue "); - } - - private void updatePolicyGUIDToUniqueValue() throws Exception { - logger.info("==> updatePolicyGUIDToUniqueValue() "); - - List allXXZones = null; - List allXXService = null; - - allXXZones = daoMgr.getXXSecurityZoneDao().getAll(); - allXXService = daoMgr.getXXService().getAll(); - - if (CollectionUtils.isNotEmpty(allXXZones) && CollectionUtils.isNotEmpty(allXXService)) { - logger.info("Total number of zones " + allXXZones.size() +", service :" +allXXService.size()); - for (XXSecurityZone xSecurityZone : allXXZones) { - for (XXService xService : allXXService) { - logger.info("serching duplicate guid policies for service :" + xService.getName() + " zone : " - + xSecurityZone.getName()); - List duplicateGuidList = daoMgr.getXXPolicy() - .findDuplicateGUIDByServiceIdAndZoneId(xService.getId(), xSecurityZone.getId()); - if (CollectionUtils.isNotEmpty(duplicateGuidList)) { - logger.info("Total number of duplicate GUIDs :" + duplicateGuidList.size() + " for service :" - + xService.getName() + " and zone :" + xSecurityZone.getName()); - for (String guid : duplicateGuidList) { - List xxPolicyList = daoMgr.getXXPolicy().findPolicyByGUIDAndServiceIdAndZoneId( - guid, xService.getId(), xSecurityZone.getId()); - boolean isFirstElement = false; - if (CollectionUtils.isNotEmpty(xxPolicyList)) { - isFirstElement = true; - for (XXPolicy xxPolicy : xxPolicyList) { - if (isFirstElement) { - isFirstElement = false; - continue; - } - RangerPolicy policy = getPolicy(xxPolicy); - if (policy != null) { - guid = guidUtil.genGUID(); - xxPolicy.setGuid(guid); - policy.setGuid(guid); - xxPolicy.setPolicyText(JsonUtils.objectToJson(policy)); - - daoMgr.getXXPolicy().update(xxPolicy); - } - } - } else { - logger.info("No policy found with guid:" + guid); - } - } - } else { - logger.info("No duplicate GUID found in policy for Service :" + xService.getName() + ", Zone : " - + xSecurityZone.getName()); - } - } - } - } else { - logger.info("No zone or service found"); - } - } - - private RangerPolicy getPolicy(final XXPolicy xPolicy) { - final RangerPolicy ret; - - if (xPolicy != null) { - String policyText = xPolicy.getPolicyText(); - if (logger.isDebugEnabled()) { - logger.debug("Ranger Policy text:[" + policyText + "]"); - } - ret = JsonUtils.jsonToObject(policyText, RangerPolicy.class); - - if (ret != null) { - ret.setId(xPolicy.getId()); - ret.setGuid(xPolicy.getGuid()); - ret.setCreateTime(xPolicy.getCreateTime()); - ret.setUpdateTime(xPolicy.getUpdateTime()); - ret.setVersion(xPolicy.getVersion()); - ret.setPolicyType(xPolicy.getPolicyType() == null ? RangerPolicy.POLICY_TYPE_ACCESS : xPolicy.getPolicyType()); - XXSecurityZone xSecurityZone = daoMgr.getXXSecurityZoneDao().findByZoneId(xPolicy.getZoneId()); - if (xSecurityZone != null) { - ret.setZoneName(xSecurityZone.getName()); - } - } - } else { - ret = null; - } - return ret; - } -} \ No newline at end of file + private static final Logger logger = LoggerFactory.getLogger(PatchPreSql_057_ForUpdateToUniqueGUID_J10052.class); + + @Autowired + RangerDaoManager daoMgr; + + @Autowired + ServiceDBStore svcStore; + + @Autowired + GUIDUtil guidUtil; + + @Autowired + @Qualifier(value = "transactionManager") + PlatformTransactionManager txManager; + + public static void main(String[] args) { + logger.info("main()"); + + try { + PatchPreSql_057_ForUpdateToUniqueGUID_J10052 loader = (PatchPreSql_057_ForUpdateToUniqueGUID_J10052) CLIUtil.getBean(PatchPreSql_057_ForUpdateToUniqueGUID_J10052.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); + } + } + + @Override + public void init() throws Exception { + // Do Nothing + } + + @Override + public void printStats() { + logger.info("runnig updatePolicyGUIDToUniqueValue "); + } + + @Override + public void execLoad() { + logger.info("==> updatePolicyGUIDToUniqueValue()"); + + try { + updatePolicyGUIDToUniqueValue(); + } catch (Exception e) { + logger.error("Error while updatePolicyGUIDToUniqueValue()", e); + + System.exit(1); + } + + logger.info("<== updatePolicyGUIDToUniqueValue.execLoad()"); + } + + private void updatePolicyGUIDToUniqueValue() { + logger.info("==> updatePolicyGUIDToUniqueValue() "); + + List allXXZones = daoMgr.getXXSecurityZoneDao().getAll(); + List allXXService = daoMgr.getXXService().getAll(); + + if (CollectionUtils.isNotEmpty(allXXZones) && CollectionUtils.isNotEmpty(allXXService)) { + logger.info("Total number of zones {}, services :{}", allXXZones.size(), allXXService.size()); + + for (XXSecurityZone xSecurityZone : allXXZones) { + for (XXService xService : allXXService) { + logger.info("serching duplicate guid policies for service :{} zone:{}", xService.getName(), xSecurityZone.getName()); + + List duplicateGuidList = daoMgr.getXXPolicy().findDuplicateGUIDByServiceIdAndZoneId(xService.getId(), xSecurityZone.getId()); + + if (CollectionUtils.isNotEmpty(duplicateGuidList)) { + logger.info("Total number of duplicate GUIDs:{} for service:{} and zone:{}", duplicateGuidList.size(), xService.getName(), xSecurityZone.getName()); + + for (String guid : duplicateGuidList) { + List xxPolicyList = daoMgr.getXXPolicy().findPolicyByGUIDAndServiceIdAndZoneId(guid, xService.getId(), xSecurityZone.getId()); + + if (CollectionUtils.isNotEmpty(xxPolicyList)) { + boolean isFirstElement = true; + + for (XXPolicy xxPolicy : xxPolicyList) { + if (isFirstElement) { + isFirstElement = false; + continue; + } + + RangerPolicy policy = getPolicy(xxPolicy); + + if (policy != null) { + guid = guidUtil.genGUID(); + + xxPolicy.setGuid(guid); + + policy.setGuid(guid); + + xxPolicy.setPolicyText(JsonUtils.objectToJson(policy)); + + daoMgr.getXXPolicy().update(xxPolicy); + } + } + } else { + logger.info("No policy found with guid:{}", guid); + } + } + } else { + logger.info("No duplicate GUID found in policy for Service :{}, Zone:{}", xService.getName(), xSecurityZone.getName()); + } + } + } + } else { + logger.info("No zone or service found"); + } + } + + private RangerPolicy getPolicy(final XXPolicy xPolicy) { + final RangerPolicy ret; + + if (xPolicy != null) { + String policyText = xPolicy.getPolicyText(); + + logger.debug("Ranger Policy text:[{}]", policyText); + + ret = JsonUtils.jsonToObject(policyText, RangerPolicy.class); + + if (ret != null) { + ret.setId(xPolicy.getId()); + ret.setGuid(xPolicy.getGuid()); + ret.setCreateTime(xPolicy.getCreateTime()); + ret.setUpdateTime(xPolicy.getUpdateTime()); + ret.setVersion(xPolicy.getVersion()); + ret.setPolicyType(xPolicy.getPolicyType() == null ? RangerPolicy.POLICY_TYPE_ACCESS : xPolicy.getPolicyType()); + + XXSecurityZone xSecurityZone = daoMgr.getXXSecurityZoneDao().findByZoneId(xPolicy.getZoneId()); + + if (xSecurityZone != null) { + ret.setZoneName(xSecurityZone.getName()); + } + } + } else { + ret = null; + } + + return ret; + } +} diff --git a/security-admin/src/main/java/org/apache/ranger/patch/PatchPreSql_058_ForUpdateToUniqueResoureceSignature_J10053.java b/security-admin/src/main/java/org/apache/ranger/patch/PatchPreSql_058_ForUpdateToUniqueResoureceSignature_J10053.java index d93c123f95..4ca27766e3 100644 --- a/security-admin/src/main/java/org/apache/ranger/patch/PatchPreSql_058_ForUpdateToUniqueResoureceSignature_J10053.java +++ b/security-admin/src/main/java/org/apache/ranger/patch/PatchPreSql_058_ForUpdateToUniqueResoureceSignature_J10053.java @@ -6,7 +6,7 @@ * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -17,10 +17,6 @@ package org.apache.ranger.patch; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - import org.apache.commons.collections.CollectionUtils; import org.apache.ranger.authorization.utils.JsonUtils; import org.apache.ranger.biz.ServiceDBStore; @@ -40,177 +36,203 @@ import org.springframework.stereotype.Component; import org.springframework.transaction.PlatformTransactionManager; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + /** * This patch will re-calculate and update policy resource_signature for all disabled Ranger Policies. - * */ @Component public class PatchPreSql_058_ForUpdateToUniqueResoureceSignature_J10053 extends BaseLoader { - private static final Logger logger = LoggerFactory.getLogger(PatchPreSql_058_ForUpdateToUniqueResoureceSignature_J10053.class); - - @Autowired - RangerDaoManager daoMgr; - - @Autowired - ServiceDBStore svcStore; - - @Autowired - RangerFactory factory; - - @Autowired - @Qualifier(value = "transactionManager") - PlatformTransactionManager txManager; - - private final Boolean isPolicyEnabled = false; - - public static void main(String[] args) { - logger.info("main()"); - try { - PatchPreSql_058_ForUpdateToUniqueResoureceSignature_J10053 loader = (PatchPreSql_058_ForUpdateToUniqueResoureceSignature_J10053) CLIUtil.getBean(PatchPreSql_058_ForUpdateToUniqueResoureceSignature_J10053.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); - } - } - - @Override - public void init() throws Exception { - // Do Nothing - } - - @Override - public void execLoad() { - logger.info("==> PatchPreSql_058_ForUpdateToUniqueResoureceSignature_J10053.execLoad()"); - - try { - updateDisabledPolicyResourceSignature(); - removeDuplicateResourceSignaturesPolicies(); - } catch (Exception e) { - logger.error("Error while PatchPreSql_058_ForUpdateToUniqueResoureceSignature_J10053()", e); - System.exit(1); - } - - logger.info("<== PatchPreSql_058_ForUpdateToUniqueResoureceSignature_J10053.execLoad()"); - } - - @Override - public void printStats() { - logger.info("Updating resource_signature of disabled Policy"); - } - - private void updateDisabledPolicyResourceSignature() throws Exception { - logger.info("==> updateDisabledPolicyResourceSignature() "); - - List xxPolicyList = daoMgr.getXXPolicy().findByPolicyStatus(isPolicyEnabled); - - logger.info("Total number of disabled policies :[" + xxPolicyList.size() + "]"); - - if (CollectionUtils.isNotEmpty(xxPolicyList)) { - for (XXPolicy xxPolicy : xxPolicyList) { - RangerPolicy policy = getPolicy(xxPolicy); - if (policy != null) { - policy.setResourceSignature(null); - xxPolicy.setResourceSignature(null); - RangerPolicyResourceSignature policySignature = factory.createPolicyResourceSignature(policy); - String signature = policySignature.getSignature(); - policy.setResourceSignature(signature); - xxPolicy.setPolicyText(JsonUtils.objectToJson(policy)); - xxPolicy.setResourceSignature(signature); - if (logger.isDebugEnabled()) { - logger.debug("Ranger text after update:[" + xxPolicy.getPolicyText() + "]"); - } - daoMgr.getXXPolicy().update(xxPolicy); - } else { - logger.info("RangerPolicy object cannot be created from xxPolicy: ["+ xxPolicy + "]"); - } - } - } - - logger.info("<== updateDisabledPolicyResourceSignature() "); - } - - private void removeDuplicateResourceSignaturesPolicies() throws Exception { - logger.info("==> removeDuplicateResourceSignaturesPolicies() "); - Map duplicateEntries = daoMgr.getXXPolicy().findDuplicatePoliciesByServiceAndResourceSignature(); - if (duplicateEntries != null && duplicateEntries.size() > 0) { - logger.info("Total number of possible duplicate policies:" + duplicateEntries.size()); - for (Map.Entry entry : duplicateEntries.entrySet()) { - logger.info("Duplicate policy Entry - {ResourceSignature:" + entry.getKey() + ", ServiceId:" + entry.getValue() + "}"); - List xxPolicyList = daoMgr.getXXPolicy().findByServiceIdAndResourceSignature(entry.getValue(), entry.getKey()); - if (CollectionUtils.isNotEmpty(xxPolicyList) && xxPolicyList.size() > 1) { - Iterator duplicatePolicies = xxPolicyList.iterator(); - duplicatePolicies.next(); - while (duplicatePolicies.hasNext()) { - XXPolicy xxPolicy = duplicatePolicies.next(); - if (xxPolicy != null) { - logger.info("Attempting to Remove duplicate policy:{" + xxPolicy.getId() + ":" + xxPolicy.getName() + "}"); - if (cleanupRefTables(xxPolicy.getId())) { - daoMgr.getXXPolicy().remove(xxPolicy.getId()); - } - } - } - } - } - } else { - logger.info("no duplicate Policy found"); - } - logger.info("<== removeDuplicateResourceSignaturesPolicies() "); - } - - private Boolean cleanupRefTables(Long policyId) { - if (policyId == null) { - return false; - } - daoMgr.getXXPolicyRefResource().deleteByPolicyId(policyId); - daoMgr.getXXPolicyRefRole().deleteByPolicyId(policyId); - daoMgr.getXXPolicyRefGroup().deleteByPolicyId(policyId); - daoMgr.getXXPolicyRefUser().deleteByPolicyId(policyId); - daoMgr.getXXPolicyRefAccessType().deleteByPolicyId(policyId); - daoMgr.getXXPolicyRefCondition().deleteByPolicyId(policyId); - daoMgr.getXXPolicyRefDataMaskType().deleteByPolicyId(policyId); - XXPolicyLabelMapDao policyLabelMapDao = daoMgr.getXXPolicyLabelMap(); - List xxPolicyLabelMaps = policyLabelMapDao.findByPolicyId(policyId); - for (XXPolicyLabelMap xxPolicyLabelMap : xxPolicyLabelMaps) { - policyLabelMapDao.remove(xxPolicyLabelMap); - } - return true; - } - - private RangerPolicy getPolicy(final XXPolicy xPolicy) { - final RangerPolicy ret; - - if (xPolicy != null) { - String policyText = xPolicy.getPolicyText(); - if (logger.isDebugEnabled()) { - logger.debug("Ranger Policy text:[" + policyText + "]"); - } - ret = JsonUtils.jsonToObject(policyText, RangerPolicy.class); - - if (ret != null) { - ret.setId(xPolicy.getId()); - ret.setGuid(xPolicy.getGuid()); - ret.setCreateTime(xPolicy.getCreateTime()); - ret.setUpdateTime(xPolicy.getUpdateTime()); - ret.setVersion(xPolicy.getVersion()); - ret.setPolicyType(xPolicy.getPolicyType() == null ? RangerPolicy.POLICY_TYPE_ACCESS : xPolicy.getPolicyType()); - XXSecurityZone xSecurityZone = daoMgr.getXXSecurityZoneDao().findByZoneId(xPolicy.getZoneId()); - if (xSecurityZone != null) { - ret.setZoneName(xSecurityZone.getName()); - } - } - } else { - ret = null; - } - return ret; - } + private static final Logger logger = LoggerFactory.getLogger(PatchPreSql_058_ForUpdateToUniqueResoureceSignature_J10053.class); + + @Autowired + RangerDaoManager daoMgr; + + @Autowired + ServiceDBStore svcStore; + + @Autowired + RangerFactory factory; + + @Autowired + @Qualifier(value = "transactionManager") + PlatformTransactionManager txManager; + + public static void main(String[] args) { + logger.info("main()"); + + try { + PatchPreSql_058_ForUpdateToUniqueResoureceSignature_J10053 loader = (PatchPreSql_058_ForUpdateToUniqueResoureceSignature_J10053) CLIUtil.getBean(PatchPreSql_058_ForUpdateToUniqueResoureceSignature_J10053.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); + } + } + + @Override + public void init() throws Exception { + // Do Nothing + } + + @Override + public void printStats() { + logger.info("Updating resource_signature of disabled Policy"); + } + + @Override + public void execLoad() { + logger.info("==> PatchPreSql_058_ForUpdateToUniqueResoureceSignature_J10053.execLoad()"); + + try { + updateDisabledPolicyResourceSignature(); + removeDuplicateResourceSignaturesPolicies(); + } catch (Exception e) { + logger.error("Error while PatchPreSql_058_ForUpdateToUniqueResoureceSignature_J10053()", e); + + System.exit(1); + } + + logger.info("<== PatchPreSql_058_ForUpdateToUniqueResoureceSignature_J10053.execLoad()"); + } + + private void updateDisabledPolicyResourceSignature() { + logger.info("==> updateDisabledPolicyResourceSignature() "); + + Boolean isPolicyEnabled = false; + List xxPolicyList = daoMgr.getXXPolicy().findByPolicyStatus(isPolicyEnabled); + + logger.info("Total number of disabled policies :[{}]", xxPolicyList.size()); + + if (CollectionUtils.isNotEmpty(xxPolicyList)) { + for (XXPolicy xxPolicy : xxPolicyList) { + RangerPolicy policy = getPolicy(xxPolicy); + + if (policy != null) { + policy.setResourceSignature(null); + xxPolicy.setResourceSignature(null); + + RangerPolicyResourceSignature policySignature = factory.createPolicyResourceSignature(policy); + String signature = policySignature.getSignature(); + + policy.setResourceSignature(signature); + + xxPolicy.setPolicyText(JsonUtils.objectToJson(policy)); + xxPolicy.setResourceSignature(signature); + + logger.debug("Ranger text after update:[{}]", xxPolicy.getPolicyText()); + + daoMgr.getXXPolicy().update(xxPolicy); + } else { + logger.info("RangerPolicy object cannot be created from xxPolicy: [{}]", xxPolicy); + } + } + } + + logger.info("<== updateDisabledPolicyResourceSignature() "); + } + + private void removeDuplicateResourceSignaturesPolicies() { + logger.info("==> removeDuplicateResourceSignaturesPolicies() "); + + Map duplicateEntries = daoMgr.getXXPolicy().findDuplicatePoliciesByServiceAndResourceSignature(); + + if (duplicateEntries != null && !duplicateEntries.isEmpty()) { + logger.info("Total number of possible duplicate policies:{}", duplicateEntries.size()); + + for (Map.Entry entry : duplicateEntries.entrySet()) { + logger.info("Duplicate policy Entry - {ResourceSignature:{}, ServiceId:{}}", entry.getKey(), entry.getValue()); + + List xxPolicyList = daoMgr.getXXPolicy().findByServiceIdAndResourceSignature(entry.getValue(), entry.getKey()); + + if (CollectionUtils.isNotEmpty(xxPolicyList) && xxPolicyList.size() > 1) { + Iterator duplicatePolicies = xxPolicyList.iterator(); + + duplicatePolicies.next(); + + while (duplicatePolicies.hasNext()) { + XXPolicy xxPolicy = duplicatePolicies.next(); + + if (xxPolicy != null) { + logger.info("Attempting to Remove duplicate policy:{{}:{}}", xxPolicy.getId(), xxPolicy.getName()); + + if (cleanupRefTables(xxPolicy.getId())) { + daoMgr.getXXPolicy().remove(xxPolicy.getId()); + } + } + } + } + } + } else { + logger.info("no duplicate Policy found"); + } + + logger.info("<== removeDuplicateResourceSignaturesPolicies() "); + } + + private Boolean cleanupRefTables(Long policyId) { + if (policyId == null) { + return false; + } + + daoMgr.getXXPolicyRefResource().deleteByPolicyId(policyId); + daoMgr.getXXPolicyRefRole().deleteByPolicyId(policyId); + daoMgr.getXXPolicyRefGroup().deleteByPolicyId(policyId); + daoMgr.getXXPolicyRefUser().deleteByPolicyId(policyId); + daoMgr.getXXPolicyRefAccessType().deleteByPolicyId(policyId); + daoMgr.getXXPolicyRefCondition().deleteByPolicyId(policyId); + daoMgr.getXXPolicyRefDataMaskType().deleteByPolicyId(policyId); + + XXPolicyLabelMapDao policyLabelMapDao = daoMgr.getXXPolicyLabelMap(); + List xxPolicyLabelMaps = policyLabelMapDao.findByPolicyId(policyId); + + for (XXPolicyLabelMap xxPolicyLabelMap : xxPolicyLabelMaps) { + policyLabelMapDao.remove(xxPolicyLabelMap); + } + + return true; + } + + private RangerPolicy getPolicy(final XXPolicy xPolicy) { + final RangerPolicy ret; + + if (xPolicy != null) { + String policyText = xPolicy.getPolicyText(); + + logger.debug("Ranger Policy text:[{}]", policyText); + + ret = JsonUtils.jsonToObject(policyText, RangerPolicy.class); + + if (ret != null) { + ret.setId(xPolicy.getId()); + ret.setGuid(xPolicy.getGuid()); + ret.setCreateTime(xPolicy.getCreateTime()); + ret.setUpdateTime(xPolicy.getUpdateTime()); + ret.setVersion(xPolicy.getVersion()); + ret.setPolicyType(xPolicy.getPolicyType() == null ? RangerPolicy.POLICY_TYPE_ACCESS : xPolicy.getPolicyType()); + + XXSecurityZone xSecurityZone = daoMgr.getXXSecurityZoneDao().findByZoneId(xPolicy.getZoneId()); + + if (xSecurityZone != null) { + ret.setZoneName(xSecurityZone.getName()); + } + } + } else { + ret = null; + } + + return ret; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/patch/PatchSetAccessTypeCategory_J10061.java b/security-admin/src/main/java/org/apache/ranger/patch/PatchSetAccessTypeCategory_J10061.java index 2915ace273..54a3424c1a 100644 --- a/security-admin/src/main/java/org/apache/ranger/patch/PatchSetAccessTypeCategory_J10061.java +++ b/security-admin/src/main/java/org/apache/ranger/patch/PatchSetAccessTypeCategory_J10061.java @@ -38,7 +38,7 @@ import java.util.Map; @Component -public class PatchSetAccessTypeCategory_J10061 extends BaseLoader{ +public class PatchSetAccessTypeCategory_J10061 extends BaseLoader { private static final Logger logger = LoggerFactory.getLogger(PatchSetAccessTypeCategory_J10061.class); @Autowired @@ -71,6 +71,11 @@ public void init() throws Exception { // Do Nothing } + @Override + public void printStats() { + logger.info("PatchSetAccessTypeCategory_J10061"); + } + @Override public void execLoad() { logger.info("==> PatchSetAccessTypeCategory_J10061.execLoad()"); @@ -84,11 +89,6 @@ public void execLoad() { logger.info("<== PatchSetAccessTypeCategory_J10061.execLoad()"); } - @Override - public void printStats() { - logger.info("PatchSetAccessTypeCategory_J10061"); - } - private void updateAllServiceDef() throws Exception { logger.info("==> PatchSetAccessTypeCategory_J10061.updateAllServiceDef()"); @@ -96,31 +96,30 @@ private void updateAllServiceDef() throws Exception { Map> embeddedCategories = new HashMap<>(); for (RangerServiceDef serviceDef : serviceDefs) { - if (StringUtils.equals(serviceDef.getName(), EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_TAG_NAME) || - StringUtils.equals(serviceDef.getName(), EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_GDS_NAME)) { + if (StringUtils.equals(serviceDef.getName(), EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_TAG_NAME) || StringUtils.equals(serviceDef.getName(), EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_GDS_NAME)) { continue; } - logger.info("Updating access-type categories for service-def:[" + serviceDef.getName() + "]"); + logger.info("Updating access-type categories for service-def:[{}]", serviceDef.getName()); if (CollectionUtils.isEmpty(serviceDef.getAccessTypes())) { - logger.info("No access-types found in service-def:[" + serviceDef.getName() + "]"); + logger.info("No access-types found in service-def:[{}}]", serviceDef.getName()); continue; } - RangerServiceDef embeddedServiceDef = null; + RangerServiceDef embeddedServiceDef; try { embeddedServiceDef = EmbeddedServiceDefsUtil.instance().getEmbeddedServiceDef(serviceDef.getName()); if (embeddedServiceDef == null) { - logger.info("No embedded service-def found for:[" + serviceDef.getName() + "]. Access type category will not be updated"); + logger.info("No embedded service-def found for:[{}]. Access type category will not be updated", serviceDef.getName()); continue; } } catch (Exception e) { - logger.info("Failed to load embedded service-def for:[" + serviceDef.getName() + "]. Access type category will not be updated", e); + logger.info("Failed to load embedded service-def for:[{}]. Access type category will not be updated", serviceDef.getName(), e); continue; } @@ -137,7 +136,7 @@ private void updateAllServiceDef() throws Exception { AccessTypeCategory category = accessTypeCategories.get(accessTypeDef.getName()); if (category == null) { - logger.info("Category not found for access-type:[" + accessTypeDef.getName() + "] in embedded service-def:[" + serviceDef.getName() + "]. Will not be updated"); + logger.info("Category not found for access-type:[{}] in embedded service-def:[{}]. Will not be updated", accessTypeDef.getName(), serviceDef.getName()); continue; } @@ -147,13 +146,13 @@ private void updateAllServiceDef() throws Exception { svcStore.updateServiceDef(serviceDef); - logger.info("Updated access-type categories for service-def:[" + serviceDef.getName() + "]"); + logger.info("Updated access-type categories for service-def:[{}]", serviceDef.getName()); } RangerServiceDef tagServiceDef = svcStore.getServiceDefByName(EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_TAG_NAME); if (tagServiceDef != null && CollectionUtils.isNotEmpty(tagServiceDef.getAccessTypes())) { - logger.info("Updating access-type categories for service-def:[" + tagServiceDef.getName() + "]"); + logger.info("Updating access-type categories for service-def:[{}]", tagServiceDef.getName()); for (RangerAccessTypeDef accessTypeDef : tagServiceDef.getAccessTypes()) { String[] svcDefAccType = accessTypeDef.getName().split(":"); @@ -161,7 +160,7 @@ private void updateAllServiceDef() throws Exception { String accessTypeName = svcDefAccType.length > 1 ? svcDefAccType[1] : null; if (StringUtils.isBlank(serviceDefName) || StringUtils.isBlank(accessTypeName)) { - logger.warn("Invalid access-type:[" + accessTypeDef.getName() + "] found in tag service-def. Access type category will not be updated"); + logger.warn("Invalid access-type:[{}] found in tag service-def. Access type category will not be updated", accessTypeDef.getName()); continue; } @@ -169,7 +168,7 @@ private void updateAllServiceDef() throws Exception { Map accessTypeCategories = embeddedCategories.get(serviceDefName); if (accessTypeCategories == null) { - logger.warn("No embedded service-def found for:[" + serviceDefName + "]. Access type category will not be updated in tag service-def"); + logger.warn("No embedded service-def found for:[{}]. Access type category will not be updated in tag service-def", serviceDefName); continue; } @@ -177,7 +176,7 @@ private void updateAllServiceDef() throws Exception { AccessTypeCategory category = accessTypeCategories.get(accessTypeName); if (category == null) { - logger.warn("Category not found for access-type:[" + accessTypeName + "] in embedded service-def:[" + serviceDefName + "]. Access type category will not be updated in tag service-def"); + logger.warn("Category not found for access-type:[{}] in embedded service-def:[{}]. Access type category will not be updated in tag service-def", accessTypeName, serviceDefName); continue; } @@ -187,7 +186,7 @@ private void updateAllServiceDef() throws Exception { svcStore.updateServiceDef(tagServiceDef); - logger.info("Updated access-type categories for service-def:[" + tagServiceDef.getName() + "]"); + logger.info("Updated access-type categories for service-def:[{}]", tagServiceDef.getName()); } logger.info("<== PatchSetAccessTypeCategory_J10061.updateAllServiceDef()"); diff --git a/security-admin/src/main/java/org/apache/ranger/patch/PatchTagModulePermission_J10005.java b/security-admin/src/main/java/org/apache/ranger/patch/PatchTagModulePermission_J10005.java index a4dba5bb9e..2654054a76 100644 --- a/security-admin/src/main/java/org/apache/ranger/patch/PatchTagModulePermission_J10005.java +++ b/security-admin/src/main/java/org/apache/ranger/patch/PatchTagModulePermission_J10005.java @@ -17,16 +17,15 @@ package org.apache.ranger.patch; -import java.util.List; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang.StringUtils; +import org.apache.ranger.biz.XUserMgr; +import org.apache.ranger.common.RangerConstants; import org.apache.ranger.db.RangerDaoManager; import org.apache.ranger.entity.XXModuleDef; import org.apache.ranger.entity.XXPolicy; import org.apache.ranger.entity.XXPortalUser; import org.apache.ranger.service.XPortalUserService; -import org.apache.ranger.biz.XUserMgr; -import org.apache.ranger.common.RangerConstants; import org.apache.ranger.util.CLIUtil; import org.apache.ranger.view.VXPortalUser; import org.slf4j.Logger; @@ -34,96 +33,115 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; +import java.util.List; + @Component public class PatchTagModulePermission_J10005 extends BaseLoader { - private static final Logger logger = LoggerFactory - .getLogger(PatchTagModulePermission_J10005.class); - - @Autowired - XUserMgr xUserMgr; - - @Autowired - XPortalUserService xPortalUserService; - - @Autowired - RangerDaoManager daoManager; - - public static void main(String[] args) { - logger.info("main()"); - try { - PatchTagModulePermission_J10005 loader = (PatchTagModulePermission_J10005) CLIUtil - .getBean(PatchTagModulePermission_J10005.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); - } - } - - @Override - public void init() throws Exception { - // Do Nothing - } - - @Override - public void execLoad() { - logger.info("==> PermissionPatch.execLoad()"); - assignPermissionOnTagModuleToAdminUsers(); - trimPolicyName(); - logger.info("<== PermissionPatch.execLoad()"); - } - - public void assignPermissionOnTagModuleToAdminUsers() { - int countUserPermissionUpdated = 0; - XXModuleDef xModDef = daoManager.getXXModuleDef().findByModuleName(RangerConstants.MODULE_TAG_BASED_POLICIES); - if(xModDef==null){ - return; - } - List allAdminUsers = daoManager.getXXPortalUser().findByRole(RangerConstants.ROLE_SYS_ADMIN); - if(!CollectionUtils.isEmpty(allAdminUsers)){ - for (XXPortalUser xPortalUser : allAdminUsers) { - VXPortalUser vPortalUser = xPortalUserService.populateViewBean(xPortalUser); - if(vPortalUser!=null){ - vPortalUser.setUserRoleList(daoManager.getXXPortalUserRole().findXPortalUserRolebyXPortalUserId(vPortalUser.getId())); - xUserMgr.createOrUpdateUserPermisson(vPortalUser,xModDef.getId(), false); - countUserPermissionUpdated += 1; - logger.info("Added '" + xModDef.getModule() + "' permission to user '" + xPortalUser.getLoginId() + "'"); - } - } - } - logger.info(countUserPermissionUpdated + " permissions were assigned"); - } - - @Override - public void printStats() { - } - - private void trimPolicyName(){ - List policies=daoManager.getXXPolicy().getAll(); - if(!CollectionUtils.isEmpty(policies)){ - String policyName=null; - for(XXPolicy xXPolicy:policies){ - try{ - if(xXPolicy!=null){ - policyName=xXPolicy.getName(); - if(!StringUtils.isEmpty(policyName)){ - if(policyName.startsWith(" ") || policyName.endsWith(" ")){ - xXPolicy.setName(StringUtils.trim(policyName)); - daoManager.getXXPolicy().update(xXPolicy); - } - } - } - }catch(Exception ex){ - logger.info("Error during policy update:"+xXPolicy.toString()); - logger.error("", ex); - } - } - } - } + private static final Logger logger = LoggerFactory.getLogger(PatchTagModulePermission_J10005.class); + + @Autowired + XUserMgr xUserMgr; + + @Autowired + XPortalUserService xPortalUserService; + + @Autowired + RangerDaoManager daoManager; + + public static void main(String[] args) { + logger.info("main()"); + + try { + PatchTagModulePermission_J10005 loader = (PatchTagModulePermission_J10005) CLIUtil.getBean(PatchTagModulePermission_J10005.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); + } + } + + @Override + public void init() throws Exception { + // Do Nothing + } + + @Override + public void printStats() { + } + + @Override + public void execLoad() { + logger.info("==> PermissionPatch.execLoad()"); + + assignPermissionOnTagModuleToAdminUsers(); + + trimPolicyName(); + + logger.info("<== PermissionPatch.execLoad()"); + } + + public void assignPermissionOnTagModuleToAdminUsers() { + int countUserPermissionUpdated = 0; + XXModuleDef xModDef = daoManager.getXXModuleDef().findByModuleName(RangerConstants.MODULE_TAG_BASED_POLICIES); + + if (xModDef == null) { + return; + } + + List allAdminUsers = daoManager.getXXPortalUser().findByRole(RangerConstants.ROLE_SYS_ADMIN); + + if (!CollectionUtils.isEmpty(allAdminUsers)) { + for (XXPortalUser xPortalUser : allAdminUsers) { + VXPortalUser vPortalUser = xPortalUserService.populateViewBean(xPortalUser); + + if (vPortalUser != null) { + vPortalUser.setUserRoleList(daoManager.getXXPortalUserRole().findXPortalUserRolebyXPortalUserId(vPortalUser.getId())); + + xUserMgr.createOrUpdateUserPermisson(vPortalUser, xModDef.getId(), false); + + countUserPermissionUpdated += 1; + + logger.info("Added {} permission to user {}", xModDef.getModule(), xPortalUser.getLoginId()); + } + } + } + + logger.info("{} permissions were assigned", countUserPermissionUpdated); + } + + private void trimPolicyName() { + List policies = daoManager.getXXPolicy().getAll(); + + if (!CollectionUtils.isEmpty(policies)) { + for (XXPolicy xXPolicy : policies) { + try { + if (xXPolicy != null) { + String policyName = xXPolicy.getName(); + + if (!StringUtils.isEmpty(policyName)) { + if (policyName.startsWith(" ") || policyName.endsWith(" ")) { + xXPolicy.setName(StringUtils.trim(policyName)); + + daoManager.getXXPolicy().update(xXPolicy); + } + } + } + } catch (Exception ex) { + logger.info("Error during policy update:{}", xXPolicy); + + logger.error("", ex); + } + } + } + } } diff --git a/security-admin/src/main/java/org/apache/ranger/patch/cliutil/ChangePasswordUtil.java b/security-admin/src/main/java/org/apache/ranger/patch/cliutil/ChangePasswordUtil.java index 536ad0fc60..21c654aaca 100644 --- a/security-admin/src/main/java/org/apache/ranger/patch/cliutil/ChangePasswordUtil.java +++ b/security-admin/src/main/java/org/apache/ranger/patch/cliutil/ChangePasswordUtil.java @@ -7,7 +7,7 @@ Licensed to the Apache Software Foundation (ASF) under one or more (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at - http://www.apache.org/licenses/LICENSE-2.0 + http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, @@ -18,6 +18,7 @@ Licensed to the Apache Software Foundation (ASF) under one or more package org.apache.ranger.patch.cliutil; +import org.apache.commons.lang.StringUtils; import org.apache.ranger.biz.UserMgr; import org.apache.ranger.common.MessageEnums; import org.apache.ranger.common.RESTErrorUtil; @@ -26,7 +27,6 @@ Licensed to the Apache Software Foundation (ASF) under one or more import org.apache.ranger.entity.XXPortalUser; import org.apache.ranger.patch.BaseLoader; import org.apache.ranger.util.CLIUtil; -import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -34,264 +34,317 @@ Licensed to the Apache Software Foundation (ASF) under one or more @Component public class ChangePasswordUtil extends BaseLoader { - private static final Logger logger = LoggerFactory.getLogger(ChangePasswordUtil.class); - - @Autowired - RangerDaoManager daoMgr; - - @Autowired - UserMgr userMgr; - - @Autowired - RESTErrorUtil restErrorUtil; - - public static String userLoginId; - public static String currentPassword; - public static String newPassword; - public static boolean defaultPwdChangeRequest = false; - public static String[] userPwdArgs; - - public static void main(String[] args) { - logger.info("main()"); - try { - ChangePasswordUtil loader = (ChangePasswordUtil) CLIUtil.getBean(ChangePasswordUtil.class); - loader.init(); - userPwdArgs=args; - if (args.length > 4) { - if ("-default".equalsIgnoreCase(args[args.length-1])) { - defaultPwdChangeRequest = true; - } - while (loader.isMoreToProcess()) { - loader.load(); - } - logger.info("Load complete. Exiting!!!"); - System.exit(0); - } else if (args.length == 3 || args.length == 4) { - userLoginId = args[0]; - currentPassword = args[1]; - newPassword = args[2]; - if (args.length == 4) { - if ("-default".equalsIgnoreCase(args[3])) { - defaultPwdChangeRequest = true; - } - } - if (StringUtils.isEmpty(userLoginId)) { - System.out.println("Invalid login ID. Exiting!!!"); - logger.info("Invalid login ID. Exiting!!!"); - System.exit(1); - } - if (StringUtils.isEmpty(currentPassword)) { - System.out.println("Invalid current password. Exiting!!!"); - logger.info("Invalid current password. Exiting!!!"); - System.exit(1); - } - if (StringUtils.isEmpty(newPassword)) { - System.out.println("Invalid new password. Exiting!!!"); - logger.info("Invalid new password. Exiting!!!"); - System.exit(1); - } - while (loader.isMoreToProcess()) { - loader.load(); - } - logger.info("Load complete. Exiting!!!"); - System.exit(0); - } else { - System.out.println( - "ChangePasswordUtil: Incorrect Arguments \n Usage: \n "); - logger.error( - "ChangePasswordUtil: Incorrect Arguments \n Usage: \n "); - System.exit(1); - } - } catch (Exception e) { - logger.error("Error loading", e); - System.exit(1); - } - } - - @Override - public void init() throws Exception { - } - - @Override - public void printStats() { - } - - @Override - public void execLoad() { - logger.info("==> ChangePasswordUtil.execLoad()"); - if(userPwdArgs.length>4) { - updateMultiplePasswords(); - }else { - updateAdminPassword(); - } - logger.info("<== ChangePasswordUtil.execLoad()"); - } - - public void updateAdminPassword() { - XXPortalUser xPortalUser = daoMgr.getXXPortalUser().findByLoginId(userLoginId); - if (xPortalUser != null) { - String dbPassword = xPortalUser.getPassword(); - String currentEncryptedPassword = null; - String md5EncryptedPassword = null; - try { - if (config.isFipsEnabled()) { - if (defaultPwdChangeRequest) { - md5EncryptedPassword = userMgr.encryptWithOlderAlgo(userLoginId, currentPassword); - if (md5EncryptedPassword.equals(dbPassword)) { - validatePassword(newPassword); - userMgr.updatePasswordInSHA256(userLoginId, newPassword, true); - logger.info("User '" + userLoginId + "' Password updated sucessfully."); - } else { - System.out.println( - "Skipping default password change request as provided password doesn't match with existing password."); - logger.error( - "Skipping default password change request as provided password doesn't match with existing password."); - System.exit(2); - } - } else if (userMgr.isPasswordValid(userLoginId, dbPassword, currentPassword)) { - validatePassword(newPassword); - userMgr.updatePasswordInSHA256(userLoginId, newPassword, true); - logger.info("User '" + userLoginId + "' Password updated sucessfully."); - } - } else { - currentEncryptedPassword = userMgr.encrypt(userLoginId, currentPassword); - if (currentEncryptedPassword.equals(dbPassword)) { - validatePassword(newPassword); - userMgr.updatePasswordInSHA256(userLoginId, newPassword, true); - logger.info("User '" + userLoginId + "' Password updated sucessfully."); - } else if (!currentEncryptedPassword.equals(dbPassword) && defaultPwdChangeRequest) { - logger.info("current encryped password is not equal to dbpassword , trying with md5 now"); - md5EncryptedPassword = userMgr.encryptWithOlderAlgo(userLoginId, currentPassword); - if (md5EncryptedPassword.equals(dbPassword)) { - validatePassword(newPassword); - userMgr.updatePasswordInSHA256(userLoginId, newPassword, true); - logger.info("User '" + userLoginId + "' Password updated sucessfully."); - } else { - System.out.println( - "Skipping default password change request as provided password doesn't match with existing password."); - logger.error( - "Skipping default password change request as provided password doesn't match with existing password."); - System.exit(2); - } - } else { - System.out.println("Invalid user password"); - logger.error("Invalid user password"); - System.exit(1); - } - } - } catch (Exception e) { - logger.error("Update Admin Password failure. Detail: \n", e); - System.exit(1); - } - } else { - System.out.println("User does not exist in DB!!"); - logger.error("User does not exist in DB"); - System.exit(1); - } - } - - public void updateMultiplePasswords() { - for (int i=0; i 4) { + if ("-default".equalsIgnoreCase(args[args.length - 1])) { + defaultPwdChangeRequest = true; + } + + while (loader.isMoreToProcess()) { + loader.load(); + } + + logger.info("Load complete. Exiting!!!"); + + System.exit(0); + } else if (args.length == 3 || args.length == 4) { + userLoginId = args[0]; + currentPassword = args[1]; + newPassword = args[2]; + + if (args.length == 4) { + if ("-default".equalsIgnoreCase(args[3])) { + defaultPwdChangeRequest = true; + } + } + + if (StringUtils.isEmpty(userLoginId)) { + System.out.println("Invalid login ID. Exiting!!!"); + logger.info("Invalid login ID. Exiting!!!"); + + System.exit(1); + } + + if (StringUtils.isEmpty(currentPassword)) { + System.out.println("Invalid current password. Exiting!!!"); + logger.info("Invalid current password. Exiting!!!"); + + System.exit(1); + } + + if (StringUtils.isEmpty(newPassword)) { + System.out.println("Invalid new password. Exiting!!!"); + logger.info("Invalid new password. Exiting!!!"); + + System.exit(1); + } + + while (loader.isMoreToProcess()) { + loader.load(); + } + + logger.info("Load complete. Exiting!!!"); + + System.exit(0); + } else { + System.out.println("ChangePasswordUtil: Incorrect Arguments \n Usage: \n "); + logger.error("ChangePasswordUtil: Incorrect Arguments \n Usage: \n "); + + System.exit(1); + } + } catch (Exception e) { + logger.error("Error loading", e); + + System.exit(1); + } + } + + @Override + public void init() throws Exception { + } + + @Override + public void printStats() { + } + + @Override + public void execLoad() { + logger.info("==> ChangePasswordUtil.execLoad()"); + + if (userPwdArgs.length > 4) { + updateMultiplePasswords(); + } else { + updateAdminPassword(); + } + + logger.info("<== ChangePasswordUtil.execLoad()"); + } + + public void updateAdminPassword() { + XXPortalUser xPortalUser = daoMgr.getXXPortalUser().findByLoginId(userLoginId); + + if (xPortalUser != null) { + String currentEncryptedPassword; + String md5EncryptedPassword; + String dbPassword = xPortalUser.getPassword(); + + try { + if (config.isFipsEnabled()) { + if (defaultPwdChangeRequest) { + md5EncryptedPassword = userMgr.encryptWithOlderAlgo(userLoginId, currentPassword); + + if (md5EncryptedPassword.equals(dbPassword)) { + validatePassword(newPassword); + userMgr.updatePasswordInSHA256(userLoginId, newPassword, true); + + logger.info("User '{}' Password updated sucessfully.", userLoginId); + } else { + System.out.println("Skipping default password change request as provided password doesn't match with existing password."); + logger.error("Skipping default password change request as provided password doesn't match with existing password."); + + System.exit(2); + } + } else if (userMgr.isPasswordValid(userLoginId, dbPassword, currentPassword)) { + validatePassword(newPassword); + userMgr.updatePasswordInSHA256(userLoginId, newPassword, true); + + logger.info("User '{}' Password updated sucessfully.", userLoginId); + } + } else { + currentEncryptedPassword = userMgr.encrypt(userLoginId, currentPassword); + if (currentEncryptedPassword.equals(dbPassword)) { + validatePassword(newPassword); + userMgr.updatePasswordInSHA256(userLoginId, newPassword, true); + + logger.info("User '{}' Password updated sucessfully.", userLoginId); + } else if (defaultPwdChangeRequest) { + logger.info("current encryped password is not equal to dbpassword , trying with md5 now"); + + md5EncryptedPassword = userMgr.encryptWithOlderAlgo(userLoginId, currentPassword); + + if (md5EncryptedPassword.equals(dbPassword)) { + validatePassword(newPassword); + userMgr.updatePasswordInSHA256(userLoginId, newPassword, true); + + logger.info("User '{}' Password updated sucessfully.", userLoginId); + } else { + System.out.println("Skipping default password change request as provided password doesn't match with existing password."); + logger.error("Skipping default password change request as provided password doesn't match with existing password."); + + System.exit(2); + } + } else { + System.out.println("Invalid user password"); + logger.error("Invalid user password"); + + System.exit(1); + } + } + } catch (Exception e) { + logger.error("Update Admin Password failure. Detail: \n", e); + + System.exit(1); + } + } else { + System.out.println("User does not exist in DB!!"); + logger.error("User does not exist in DB"); + + System.exit(1); + } + } + + public void updateMultiplePasswords() { + for (int i = 0; i < userPwdArgs.length; i += 3) { + if ("-default".equalsIgnoreCase(userPwdArgs[i])) { + continue; + } + + String userLoginIdTemp = userPwdArgs[i]; + String currentPasswordTemp = userPwdArgs[i + 1]; + String newPasswordTemp = userPwdArgs[i + 2]; + + if (StringUtils.isEmpty(userLoginIdTemp)) { + System.out.println("Invalid login ID. Exiting!!!"); + logger.info("Invalid login ID. Exiting!!!"); + + System.exit(1); + } + + if (StringUtils.isEmpty(currentPasswordTemp)) { + System.out.println("Invalid current password. Exiting!!!"); + logger.info("Invalid current password. Exiting!!!"); + + System.exit(1); + } + if (StringUtils.isEmpty(newPasswordTemp)) { + System.out.println("Invalid new password. Exiting!!!"); + logger.info("Invalid new password. Exiting!!!"); + + System.exit(1); + } + + XXPortalUser xPortalUser = daoMgr.getXXPortalUser().findByLoginId(userLoginIdTemp); + + if (xPortalUser != null) { + String currentEncryptedPassword; + String md5EncryptedPassword; + String dbPassword = xPortalUser.getPassword(); + + try { + if (config.isFipsEnabled()) { + if (defaultPwdChangeRequest) { + currentEncryptedPassword = userMgr.encryptWithOlderAlgo(userLoginIdTemp, currentPasswordTemp); + + if (currentEncryptedPassword.equals(dbPassword)) { + validatePassword(newPasswordTemp); + userMgr.updatePasswordInSHA256(userLoginIdTemp, newPasswordTemp, true); + + logger.info("User '{}' Password updated successfully.", userLoginIdTemp); + } else { + System.out.println("Skipping default password change request as provided password doesn't match with existing password."); + logger.error("Skipping default password change request as provided password doesn't match with existing password."); + + System.exit(2); + } + } else if (userMgr.isPasswordValid(userLoginIdTemp, dbPassword, currentPasswordTemp)) { + validatePassword(newPasswordTemp); + userMgr.updatePasswordInSHA256(userLoginIdTemp, newPasswordTemp, true); + + logger.info("User '{}' Password updated successfully.", userLoginIdTemp); + } + } else { + currentEncryptedPassword = userMgr.encrypt(userLoginIdTemp, currentPasswordTemp); + + if (currentEncryptedPassword.equals(dbPassword)) { + validatePassword(newPasswordTemp); + userMgr.updatePasswordInSHA256(userLoginIdTemp, newPasswordTemp, true); + + logger.info("User '{}' Password updated successfully.", userLoginIdTemp); + } else if (defaultPwdChangeRequest) { + logger.info("current encryped password is not equal to dbpassword , trying with md5 now"); + + md5EncryptedPassword = userMgr.encryptWithOlderAlgo(userLoginIdTemp, currentPasswordTemp); + + if (md5EncryptedPassword.equals(dbPassword)) { + validatePassword(newPasswordTemp); + userMgr.updatePasswordInSHA256(userLoginIdTemp, newPasswordTemp, true); + + logger.info("User '{}' Password updated successfully.", userLoginIdTemp); + } else { + System.out.println("Skipping default password change request as provided password doesn't match with existing password."); + logger.error("Skipping default password change request as provided password doesn't match with existing password."); + + System.exit(2); + } + } else { + System.out.println("Invalid user password"); + logger.error("Invalid user password"); + + System.exit(1); + break; + } + } + } catch (Exception e) { + logger.error("Update Admin Password failure. Detail: \n", e); + + System.exit(1); + break; + } + } else { + System.out.println("User does not exist in DB!!"); + logger.error("User does not exist in DB"); + + System.exit(1); + break; + } + } + } + + private void validatePassword(String newPassword) { + boolean checkPassword; + + if (newPassword != null) { + checkPassword = newPassword.trim().matches(StringUtil.VALIDATION_CRED); + + if (!checkPassword) { + String msg = "Password should be minimum 8 characters, at least one uppercase letter, one lowercase letter and one numeric."; + + logger.error(msg); + System.out.println(msg); + + throw restErrorUtil.createRESTException("serverMsg.changePasswordValidatePassword", MessageEnums.INVALID_PASSWORD, null, msg, null); + } + } else { + logger.error("validatePassword(). Password cannot be blank/null."); + System.out.println("validatePassword(). Password cannot be blank/null."); + throw restErrorUtil.createRESTException("serverMsg.changePasswordValidatePassword", MessageEnums.INVALID_PASSWORD, null, "Password cannot be blank/null", null); + } + } } diff --git a/security-admin/src/main/java/org/apache/ranger/patch/cliutil/ChangeUserNameUtil.java b/security-admin/src/main/java/org/apache/ranger/patch/cliutil/ChangeUserNameUtil.java index 4be81d69c9..8cdb41b937 100644 --- a/security-admin/src/main/java/org/apache/ranger/patch/cliutil/ChangeUserNameUtil.java +++ b/security-admin/src/main/java/org/apache/ranger/patch/cliutil/ChangeUserNameUtil.java @@ -18,12 +18,12 @@ Licensed to the Apache Software Foundation (ASF) under one or more package org.apache.ranger.patch.cliutil; +import org.apache.commons.lang.StringUtils; import org.apache.ranger.biz.UserMgr; import org.apache.ranger.db.RangerDaoManager; import org.apache.ranger.entity.XXPortalUser; import org.apache.ranger.patch.BaseLoader; import org.apache.ranger.util.CLIUtil; -import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -33,53 +33,66 @@ Licensed to the Apache Software Foundation (ASF) under one or more public class ChangeUserNameUtil extends BaseLoader { private static final Logger logger = LoggerFactory.getLogger(ChangeUserNameUtil.class); + public static String userLoginId; + public static String currentPassword; + public static String newUserName; + @Autowired RangerDaoManager daoMgr; @Autowired UserMgr userMgr; - public static String userLoginId; - public static String currentPassword; - public static String newUserName; - public static void main(String[] args) { logger.info("main()"); + try { ChangeUserNameUtil loader = (ChangeUserNameUtil) CLIUtil.getBean(ChangeUserNameUtil.class); + loader.init(); + if (args.length == 3) { - userLoginId = args[0]; + userLoginId = args[0]; currentPassword = args[1]; - newUserName = args[2]; - if(StringUtils.isEmpty(userLoginId)){ + newUserName = args[2]; + + if (StringUtils.isEmpty(userLoginId)) { System.out.println("Invalid login ID. Exiting!!!"); logger.info("Invalid login ID. Exiting!!!"); + System.exit(1); } - if(StringUtils.isEmpty(currentPassword)){ + + if (StringUtils.isEmpty(currentPassword)) { System.out.println("Invalid current password. Exiting!!!"); logger.info("Invalid current password. Exiting!!!"); + System.exit(1); } - if(StringUtils.isEmpty(newUserName)){ + + if (StringUtils.isEmpty(newUserName)) { System.out.println("Invalid new user name. Exiting!!!"); logger.info("Invalid new user name. Exiting!!!"); + System.exit(1); } + while (loader.isMoreToProcess()) { loader.load(); } + logger.info("Load complete. Exiting!!!"); + System.exit(0); - }else{ + } else { System.out.println("ChangeUserNameUtil: Incorrect Arguments \n Usage: \n "); logger.error("ChangeUserNameUtil: Incorrect Arguments \n Usage: \n "); + System.exit(1); } - } - catch (Exception e) { + } catch (Exception e) { logger.error("Error loading", e); + System.exit(1); } } @@ -95,7 +108,9 @@ public void printStats() { @Override public void execLoad() { logger.info("==> ChangeUserNameUtil.execLoad()"); + updateUserName(); + logger.info("<== ChangeUserNameUtil.execLoad()"); } @@ -104,30 +119,36 @@ public void updateUserName() { if (daoMgr.getXXPortalUser().findByLoginId(newUserName) != null) { System.out.println("New user name already exist in DB!"); logger.error("New user name already exist in DB"); + System.exit(1); } - XXPortalUser xPortalUser=daoMgr.getXXPortalUser().findByLoginId(userLoginId); - if (xPortalUser!=null){ - String dbPassword=xPortalUser.getPassword(); - String currentEncryptedPassword=null; + + XXPortalUser xPortalUser = daoMgr.getXXPortalUser().findByLoginId(userLoginId); + + if (xPortalUser != null) { + String currentEncryptedPassword; + String dbPassword = xPortalUser.getPassword(); + try { - currentEncryptedPassword=userMgr.encrypt(userLoginId, currentPassword); - if (currentEncryptedPassword.equals(dbPassword)){ + currentEncryptedPassword = userMgr.encrypt(userLoginId, currentPassword); + + if (currentEncryptedPassword.equals(dbPassword)) { userMgr.updateOldUserName(userLoginId, newUserName, currentPassword); - logger.info("User Name '"+userLoginId+"' updated to '"+newUserName+"' sucessfully."); - } - else{ + + logger.info("User Name '{}' updated to '{}' sucessfully.", userLoginId, newUserName); + } else { System.out.println("Invalid user password"); logger.error("Invalid user password"); + System.exit(1); } } catch (Exception e) { e.printStackTrace(); } - } - else{ + } else { System.out.println("User does not exist in DB!!"); logger.error("User does not exist in DB"); + System.exit(1); } } diff --git a/security-admin/src/main/java/org/apache/ranger/patch/cliutil/DbToSolrMigrationUtil.java b/security-admin/src/main/java/org/apache/ranger/patch/cliutil/DbToSolrMigrationUtil.java index de76002d1c..8da901d591 100644 --- a/security-admin/src/main/java/org/apache/ranger/patch/cliutil/DbToSolrMigrationUtil.java +++ b/security-admin/src/main/java/org/apache/ranger/patch/cliutil/DbToSolrMigrationUtil.java @@ -17,18 +17,12 @@ package org.apache.ranger.patch.cliutil; -import java.io.IOException; -import java.nio.charset.Charset; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.ArrayList; -import java.util.List; -import java.util.Properties; -import java.util.UUID; -import java.util.Arrays; - +import org.apache.ranger.audit.utils.InMemoryJAASConfiguration; +import org.apache.ranger.authorization.utils.StringUtil; +import org.apache.ranger.biz.RangerBizUtil; +import org.apache.ranger.common.AppConstants; +import org.apache.ranger.common.DateUtil; +import org.apache.ranger.common.PropertiesUtil; import org.apache.ranger.db.RangerDaoManager; import org.apache.ranger.entity.XXAccessAudit; import org.apache.ranger.entity.XXAccessAuditBase; @@ -36,12 +30,6 @@ import org.apache.ranger.entity.XXAccessAuditV5; import org.apache.ranger.patch.BaseLoader; import org.apache.ranger.solr.SolrAccessAuditsService; -import org.apache.ranger.audit.utils.InMemoryJAASConfiguration; -import org.apache.ranger.authorization.utils.StringUtil; -import org.apache.ranger.biz.RangerBizUtil; -import org.apache.ranger.common.AppConstants; -import org.apache.ranger.common.DateUtil; -import org.apache.ranger.common.PropertiesUtil; import org.apache.ranger.util.CLIUtil; import org.apache.solr.client.solrj.SolrClient; import org.apache.solr.client.solrj.impl.BinaryRequestWriter; @@ -61,416 +49,509 @@ import javax.security.auth.login.Configuration; +import java.io.IOException; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Properties; +import java.util.UUID; + @Component public class DbToSolrMigrationUtil extends BaseLoader { - private static final Logger logger = LoggerFactory.getLogger(DbToSolrMigrationUtil.class); - private final static String CHECK_FILE_NAME = "migration_check_file.txt"; - private final static Charset ENCODING = StandardCharsets.UTF_8; - - public static SolrClient solrClient = null; - public final static String SOLR_URLS_PROP = "ranger.audit.solr.urls"; - public final static String SOLR_ZK_HOSTS = "ranger.audit.solr.zookeepers"; - public final static String SOLR_COLLECTION_NAME = "ranger.audit.solr.collection.name"; - public final static String PROP_JAVA_SECURITY_AUTH_LOGIN_CONFIG = "java.security.auth.login.config"; - public final static String DEFAULT_COLLECTION_NAME = "ranger_audits"; - - @Autowired - RangerDaoManager daoManager; - @Autowired - SolrAccessAuditsService solrAccessAuditsService; - - public static void main(String[] args) throws Exception { - logger.info("main()"); - logger.info("Note: If migrating to Secure Solr, make sure SolrClient JAAS Properites are configured in ranger-admin-site.xml"); - try { - DbToSolrMigrationUtil loader = (DbToSolrMigrationUtil) CLIUtil - .getBean(DbToSolrMigrationUtil.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); - } finally { - if (solrClient != null) { - solrClient.close(); - } - } - } - - @Override - public void init() throws Exception { - logger.info("==> DbToSolrMigrationUtil.init() Start."); - solrClient = createSolrClient(); - logger.info("<== DbToSolrMigrationUtil.init() End."); - } - - @Override - public void execLoad() { - logger.info("==> DbToSolrMigrationUtil.execLoad() Start."); - migrateAuditDbLogsToSolr(); - logger.info("<== DbToSolrMigrationUtil.execLoad() End."); - } - - public void migrateAuditDbLogsToSolr() { - System.out.println("Migration process is started.."); - long maxXXAccessAuditID = daoManager.getXXAccessAudit().getMaxIdOfXXAccessAudit(); - if(maxXXAccessAuditID==0){ - logger.info("Access Audit log does not exist."); - System.out.println("Access Audit log does not exist in db."); - return; - } - long maxMigratedID=0; - try { - maxMigratedID = readMigrationStatusFile(CHECK_FILE_NAME); - } catch (IOException ex) { - logger.error("Failed to read migration status from file " + CHECK_FILE_NAME, ex); - } - logger.info("ID of the last available audit log: "+ maxXXAccessAuditID); - if(maxMigratedID > 0) { - logger.info("ID of the last migrated audit log: "+ maxMigratedID); - } - if(maxMigratedID>=maxXXAccessAuditID){ - logger.info("No more DB Audit logs to migrate. Last migrated audit log ID: " + maxMigratedID); - System.out.println("No more DB Audit logs to migrate. Last migrated audit log ID: " + maxMigratedID); - return; - } - String db_flavor=AppConstants.getLabelFor_DatabaseFlavor(RangerBizUtil.getDBFlavor()); - logger.info("DB flavor: " + db_flavor); - List columnList=daoManager.getXXAccessAudit().getColumnNames(db_flavor); - int auditTableVersion=4; - if(columnList!=null){ - if(columnList.contains("tags")){ - auditTableVersion=6; - }else if(columnList.contains("seq_num") && columnList.contains("event_count") && columnList.contains("event_dur_ms")){ - auditTableVersion=5; - } - } - logger.info("Columns Name:"+columnList); - long maxRowsPerBatch=10000; - //To ceil the actual division result i.e noOfBatches=maxXXAccessAuditID/maxRowsPerBatch - long noOfBatches=((maxXXAccessAuditID-maxMigratedID)+maxRowsPerBatch-1)/maxRowsPerBatch; - long rangeStart=maxMigratedID; - long rangeEnd=maxXXAccessAuditID-maxMigratedID<=maxRowsPerBatch ? maxXXAccessAuditID : rangeStart+maxRowsPerBatch; - long startTimeInMS=0; - long timeTaken=0; - long lastMigratedID=0; - long totalMigratedLogs=0; - for(long index=1;index<=noOfBatches;index++){ - logger.info("Batch "+ index+" of total "+noOfBatches); - System.out.println("Processing batch "+ index+" of total "+noOfBatches); - startTimeInMS=System.currentTimeMillis(); - //rangeStart and rangeEnd both exclusive, if we add +1 in maxRange - if(auditTableVersion==4){ - List xXAccessAuditV4List=daoManager.getXXAccessAudit().getByIdRangeV4(rangeStart,rangeEnd+1); - if(!CollectionUtils.isEmpty(xXAccessAuditV4List)){ - for(XXAccessAuditV4 xXAccessAudit:xXAccessAuditV4List){ - if(xXAccessAudit!=null){ - try { - send2solr(xXAccessAudit); - lastMigratedID=xXAccessAudit.getId(); - totalMigratedLogs++; - } catch (Throwable e) { - logger.error("Error while writing audit log id '"+xXAccessAudit.getId()+"' to Solr.", e); - writeMigrationStatusFile(lastMigratedID,CHECK_FILE_NAME); - logger.info("Stopping migration process!"); - System.out.println("Error while writing audit log id '"+xXAccessAudit.getId()+"' to Solr."); - System.out.println("Migration process failed, Please refer ranger_db_patch.log file."); - return; - } - } - } - } - }else if(auditTableVersion==5){ - List xXAccessAuditV5List=daoManager.getXXAccessAudit().getByIdRangeV5(rangeStart,rangeEnd+1); - if(!CollectionUtils.isEmpty(xXAccessAuditV5List)){ - for(XXAccessAuditV5 xXAccessAudit:xXAccessAuditV5List){ - if(xXAccessAudit!=null){ - try { - send2solr(xXAccessAudit); - lastMigratedID=xXAccessAudit.getId(); - totalMigratedLogs++; - } catch (Throwable e) { - logger.error("Error while writing audit log id '"+xXAccessAudit.getId()+"' to Solr.", e); - writeMigrationStatusFile(lastMigratedID,CHECK_FILE_NAME); - logger.info("Stopping migration process!"); - System.out.println("Error while writing audit log id '"+xXAccessAudit.getId()+"' to Solr."); - System.out.println("Migration process failed, Please refer ranger_db_patch.log file."); - return; - } - } - } - } - } - else if(auditTableVersion==6){ - List xXAccessAuditV6List=daoManager.getXXAccessAudit().getByIdRangeV6(rangeStart,rangeEnd+1); - if(!CollectionUtils.isEmpty(xXAccessAuditV6List)){ - for(XXAccessAudit xXAccessAudit:xXAccessAuditV6List){ - if(xXAccessAudit!=null){ - try { - send2solr(xXAccessAudit); - lastMigratedID=xXAccessAudit.getId(); - totalMigratedLogs++; - } catch (Throwable e) { - logger.error("Error while writing audit log id '"+xXAccessAudit.getId()+"' to Solr.", e); - writeMigrationStatusFile(lastMigratedID,CHECK_FILE_NAME); - logger.info("Stopping migration process!"); - System.out.println("Error while writing audit log id '"+xXAccessAudit.getId()+"' to Solr."); - System.out.println("Migration process failed, Please refer ranger_db_patch.log file."); - return; - } - } - } - } - } - timeTaken=(System.currentTimeMillis()-startTimeInMS); - logger.info("Batch #" + index + ": time taken:"+timeTaken+" ms"); - if(rangeEnd0){ - System.out.println("Total Number of Migrated Audit logs:"+totalMigratedLogs); - logger.info("Total Number of Migrated Audit logs:"+totalMigratedLogs); - } - if(solrClient!=null){ - try { - solrClient.close(); - } catch (IOException e) { - logger.error("Error while closing solr connection", e); - }finally{ - solrClient=null; - } - } - System.out.println("Migration process finished!!"); - } - - public void send2solr(XXAccessAuditV4 xXAccessAudit) throws Throwable { - SolrInputDocument document = new SolrInputDocument(); - toSolrDocument(xXAccessAudit,document); - UpdateResponse response = solrClient.add(document); - if (response.getStatus() != 0) { - logger.info("Response=" + response.toString() + ", status= " - + response.getStatus() + ", event=" + xXAccessAudit.toString()); - throw new Exception("Failed to send audit event ID=" + xXAccessAudit.getId()); - } - } - - public void send2solr(XXAccessAuditV5 xXAccessAudit) throws Throwable { - SolrInputDocument document = new SolrInputDocument(); - toSolrDocument(xXAccessAudit,document); - UpdateResponse response = solrClient.add(document); - if (response.getStatus() != 0) { - logger.info("Response=" + response.toString() + ", status= " - + response.getStatus() + ", event=" + xXAccessAudit.toString()); - throw new Exception("Failed to send audit event ID=" + xXAccessAudit.getId()); - } - } - - public void send2solr(XXAccessAudit xXAccessAudit) throws Throwable { - SolrInputDocument document = new SolrInputDocument(); - toSolrDocument(xXAccessAudit,document); - UpdateResponse response = solrClient.add(document); - if (response.getStatus() != 0) { - logger.info("Response=" + response.toString() + ", status= " - + response.getStatus() + ", event=" + xXAccessAudit.toString()); - throw new Exception("Failed to send audit event ID=" + xXAccessAudit.getId()); - } - } - - private void toSolrDocument(XXAccessAuditBase xXAccessAudit, SolrInputDocument document) { - // add v4 fields - document.addField("id", xXAccessAudit.getId()); - document.addField("access", xXAccessAudit.getAccessType()); - document.addField("enforcer", xXAccessAudit.getAclEnforcer()); - document.addField("agent", xXAccessAudit.getAgentId()); - document.addField("repo", xXAccessAudit.getRepoName()); - document.addField("sess", xXAccessAudit.getSessionId()); - document.addField("reqUser", xXAccessAudit.getRequestUser()); - document.addField("reqData", xXAccessAudit.getRequestData()); - document.addField("resource", xXAccessAudit.getResourcePath()); - document.addField("cliIP", xXAccessAudit.getClientIP()); - document.addField("logType", "RangerAudit"); - document.addField("result", xXAccessAudit.getAccessResult()); - document.addField("policy", xXAccessAudit.getPolicyId()); - document.addField("repoType", xXAccessAudit.getRepoType()); - document.addField("resType", xXAccessAudit.getResourceType()); - document.addField("reason", xXAccessAudit.getResultReason()); - document.addField("action", xXAccessAudit.getAction()); - document.addField("evtTime", DateUtil.getLocalDateForUTCDate(xXAccessAudit.getEventTime())); - SolrInputField idField = document.getField("id"); - boolean uidIsString = true; - if( idField == null) { - Object uid = null; - if(uidIsString) { - uid = UUID.randomUUID().toString(); - } - document.setField("id", uid); - } - } - - private void toSolrDocument(XXAccessAuditV5 xXAccessAudit, SolrInputDocument document) { - toSolrDocument((XXAccessAuditBase)xXAccessAudit, document); - // add v5 fields - document.addField("seq_num", xXAccessAudit.getSequenceNumber()); - document.addField("event_count", xXAccessAudit.getEventCount()); - document.addField("event_dur_ms", xXAccessAudit.getEventDuration()); - } - - private void toSolrDocument(XXAccessAudit xXAccessAudit,SolrInputDocument document) { - toSolrDocument((XXAccessAuditBase)xXAccessAudit, document); - // add v6 fields - document.addField("seq_num", xXAccessAudit.getSequenceNumber()); - document.addField("event_count", xXAccessAudit.getEventCount()); - document.addField("event_dur_ms", xXAccessAudit.getEventDuration()); - document.addField("tags", xXAccessAudit.getTags()); - } - private Long readMigrationStatusFile(String aFileName) throws IOException { - Long migratedDbID=0L; - Path path = Paths.get(aFileName); - if (Files.exists(path) && Files.isRegularFile(path)) { - List fileContents=Files.readAllLines(path, ENCODING); - if(fileContents!=null && fileContents.size()>=1){ - String line=fileContents.get(fileContents.size()-1).trim(); - if(!StringUtil.isEmpty(line)){ - try{ - migratedDbID=Long.parseLong(line); - }catch(Exception ex){ - } - } - } - } - return migratedDbID; - } - - private void writeMigrationStatusFile(Long DbID, String aFileName) { - try{ - Path path = Paths.get(aFileName); - List fileContents=new ArrayList(); - fileContents.add(String.valueOf(DbID)); - Files.write(path, fileContents, ENCODING); - }catch(IOException ex){ - logger.error("Failed to update migration status to file " + CHECK_FILE_NAME, ex); - }catch(Exception ex){ - logger.error("Error while updating migration status to file " + CHECK_FILE_NAME, ex); - } - } - @Override - public void printStats() { - } - - private SolrClient createSolrClient() throws Exception { - SolrClient solrClient = null; - - registerSolrClientJAAS(); - String zkHosts = PropertiesUtil - .getProperty(SOLR_ZK_HOSTS); - if (zkHosts == null) { - zkHosts = PropertiesUtil - .getProperty("ranger.audit.solr.zookeeper"); - } - if (zkHosts == null) { - zkHosts = PropertiesUtil - .getProperty("ranger.solr.zookeeper"); - } - - String solrURL = PropertiesUtil - .getProperty(SOLR_URLS_PROP); - if (solrURL == null) { - // Try with url - solrURL = PropertiesUtil - .getProperty("ranger.audit.solr.url"); - } - if (solrURL == null) { - // Let's try older property name - solrURL = PropertiesUtil - .getProperty("ranger.solr.url"); - } - - if (zkHosts != null && !"".equals(zkHosts.trim()) - && !"none".equalsIgnoreCase(zkHosts.trim())) { - zkHosts = zkHosts.trim(); - String collectionName = PropertiesUtil - .getProperty(SOLR_COLLECTION_NAME); - if (collectionName == null - || "none".equalsIgnoreCase(collectionName)) { - collectionName = DEFAULT_COLLECTION_NAME; - } - - logger.info("Solr zkHosts=" + zkHosts - + ", collectionName=" + collectionName); - // Instantiate - try (Krb5HttpClientBuilder krbBuild = new Krb5HttpClientBuilder()) { - SolrHttpClientBuilder kb = krbBuild.getBuilder(); - HttpClientUtil.setHttpClientBuilder(kb); - final List zkhosts = new ArrayList(Arrays.asList(zkHosts.split(","))); - CloudSolrClient solrCloudClient = new CloudSolrClient.Builder(zkhosts, null).build(); - solrCloudClient.setDefaultCollection(collectionName); - return solrCloudClient; - } catch (Exception e) { - logger.error( - "Can't connect to Solr server. ZooKeepers=" - + zkHosts + ", collection=" - + collectionName, e); - throw e; - } - } else { - if (solrURL == null || solrURL.isEmpty() - || "none".equalsIgnoreCase(solrURL)) { - logger.error("Solr ZKHosts and URL for Audit are empty. Please set property " - + SOLR_ZK_HOSTS - + " or " - + SOLR_URLS_PROP); - } else { - try (Krb5HttpClientBuilder krbBuild = new Krb5HttpClientBuilder()) { - SolrHttpClientBuilder kb = krbBuild.getBuilder(); - HttpClientUtil.setHttpClientBuilder(kb); - HttpSolrClient.Builder builder = new HttpSolrClient.Builder(); - builder.withBaseSolrUrl(solrURL); - builder.allowCompression(true); - builder.withConnectionTimeout(1000); - HttpSolrClient httpSolrClient = builder.build(); - httpSolrClient.setRequestWriter(new BinaryRequestWriter()); - solrClient = httpSolrClient; - } catch (Exception e) { - logger.error( - "Can't connect to Solr server. URL=" - + solrURL, e); - throw e; - } - } - } - return solrClient; - } - - private void registerSolrClientJAAS() { - logger.info("==> createSolrClient.registerSolrClientJAAS()" ); - Properties props = PropertiesUtil.getProps(); - try { - // SolrJ requires "java.security.auth.login.config" property to be set to identify itself that it is kerberized. So using a dummy property for it - // Acutal solrclient JAAS configs are read from the ranger-admin-site.xml in ranger admin config folder and set by InMemoryJAASConfiguration - // Refer InMemoryJAASConfiguration doc for JAAS Configuration - if ( System.getProperty(PROP_JAVA_SECURITY_AUTH_LOGIN_CONFIG) == null ) { - System.setProperty(PROP_JAVA_SECURITY_AUTH_LOGIN_CONFIG, "/dev/null"); - } - logger.info("Loading SolrClient JAAS config from Ranger audit config if present..."); - - Configuration conf = InMemoryJAASConfiguration.init(props); - - if (conf != null) { - Configuration.setConfiguration(conf); - } - } catch (Exception e) { - logger.error("ERROR: Unable to load SolrClient JAAS config from ranger admin config file. Audit migration to Secure Solr will fail...",e); - } - logger.info("<==createSolrClient.registerSolrClientJAAS()" ); - } + private static final Logger logger = LoggerFactory.getLogger(DbToSolrMigrationUtil.class); + + public static final String SOLR_URLS_PROP = "ranger.audit.solr.urls"; + public static final String SOLR_ZK_HOSTS = "ranger.audit.solr.zookeepers"; + public static final String SOLR_COLLECTION_NAME = "ranger.audit.solr.collection.name"; + public static final String PROP_JAVA_SECURITY_AUTH_LOGIN_CONFIG = "java.security.auth.login.config"; + public static final String DEFAULT_COLLECTION_NAME = "ranger_audits"; + + private static final String CHECK_FILE_NAME = "migration_check_file.txt"; + private static final Charset ENCODING = StandardCharsets.UTF_8; + + public static SolrClient solrClient; + + @Autowired + RangerDaoManager daoManager; + + @Autowired + SolrAccessAuditsService solrAccessAuditsService; + + public static void main(String[] args) throws Exception { + logger.info("main()"); + logger.info("Note: If migrating to Secure Solr, make sure SolrClient JAAS Properites are configured in ranger-admin-site.xml"); + + try { + DbToSolrMigrationUtil loader = (DbToSolrMigrationUtil) CLIUtil.getBean(DbToSolrMigrationUtil.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); + } finally { + if (solrClient != null) { + solrClient.close(); + } + } + } + + @Override + public void init() throws Exception { + logger.info("==> DbToSolrMigrationUtil.init() Start."); + + solrClient = createSolrClient(); + + logger.info("<== DbToSolrMigrationUtil.init() End."); + } + + @Override + public void printStats() { + } + + @Override + public void execLoad() { + logger.info("==> DbToSolrMigrationUtil.execLoad() Start."); + + migrateAuditDbLogsToSolr(); + + logger.info("<== DbToSolrMigrationUtil.execLoad() End."); + } + + public void migrateAuditDbLogsToSolr() { + System.out.println("Migration process is started.."); + + long maxXXAccessAuditID = daoManager.getXXAccessAudit().getMaxIdOfXXAccessAudit(); + + if (maxXXAccessAuditID == 0) { + logger.info("Access Audit log does not exist."); + System.out.println("Access Audit log does not exist in db."); + + return; + } + + long maxMigratedID = 0; + + try { + maxMigratedID = readMigrationStatusFile(CHECK_FILE_NAME); + } catch (IOException ex) { + logger.error("Failed to read migration status from file {}", CHECK_FILE_NAME, ex); + } + + logger.info("ID of the last available audit log: {}", maxXXAccessAuditID); + + if (maxMigratedID > 0) { + logger.info("ID of the last migrated audit log: {}", maxMigratedID); + } + + if (maxMigratedID >= maxXXAccessAuditID) { + logger.info("No more DB Audit logs to migrate. Last migrated audit log ID: {}", maxMigratedID); + System.out.println("No more DB Audit logs to migrate. Last migrated audit log ID: " + maxMigratedID); + + return; + } + + String dbFlavor = AppConstants.getLabelFor_DatabaseFlavor(RangerBizUtil.getDBFlavor()); + + logger.info("DB flavor: {}", dbFlavor); + + List columnList = daoManager.getXXAccessAudit().getColumnNames(dbFlavor); + int auditTableVersion = 4; + + if (columnList != null) { + if (columnList.contains("tags")) { + auditTableVersion = 6; + } else if (columnList.contains("seq_num") && columnList.contains("event_count") && columnList.contains("event_dur_ms")) { + auditTableVersion = 5; + } + } + + logger.info("Columns Name:{}", columnList); + + long maxRowsPerBatch = 10000; + //To ceil the actual division result i.e noOfBatches=maxXXAccessAuditID/maxRowsPerBatch + long noOfBatches = ((maxXXAccessAuditID - maxMigratedID) + maxRowsPerBatch - 1) / maxRowsPerBatch; + long rangeStart = maxMigratedID; + long rangeEnd = maxXXAccessAuditID - maxMigratedID <= maxRowsPerBatch ? maxXXAccessAuditID : rangeStart + maxRowsPerBatch; + long startTimeInMS; + long timeTaken; + long lastMigratedID = 0; + long totalMigratedLogs = 0; + + for (long index = 1; index <= noOfBatches; index++) { + logger.info("Batch {} of total {}", index, noOfBatches); + System.out.println("Processing batch " + index + " of total " + noOfBatches); + + startTimeInMS = System.currentTimeMillis(); + + //rangeStart and rangeEnd both exclusive, if we add +1 in maxRange + if (auditTableVersion == 4) { + List xXAccessAuditV4List = daoManager.getXXAccessAudit().getByIdRangeV4(rangeStart, rangeEnd + 1); + + if (!CollectionUtils.isEmpty(xXAccessAuditV4List)) { + for (XXAccessAuditV4 xXAccessAudit : xXAccessAuditV4List) { + if (xXAccessAudit != null) { + try { + send2solr(xXAccessAudit); + + lastMigratedID = xXAccessAudit.getId(); + + totalMigratedLogs++; + } catch (Throwable e) { + logger.error("Error while writing audit log id '{}' to Solr.", xXAccessAudit.getId(), e); + + writeMigrationStatusFile(lastMigratedID, CHECK_FILE_NAME); + logger.info("Stopping migration process!"); + + System.out.println("Error while writing audit log id '" + xXAccessAudit.getId() + "' to Solr."); + System.out.println("Migration process failed, Please refer ranger_db_patch.log file."); + + return; + } + } + } + } + } else if (auditTableVersion == 5) { + List xXAccessAuditV5List = daoManager.getXXAccessAudit().getByIdRangeV5(rangeStart, rangeEnd + 1); + + if (!CollectionUtils.isEmpty(xXAccessAuditV5List)) { + for (XXAccessAuditV5 xXAccessAudit : xXAccessAuditV5List) { + if (xXAccessAudit != null) { + try { + send2solr(xXAccessAudit); + + lastMigratedID = xXAccessAudit.getId(); + + totalMigratedLogs++; + } catch (Throwable e) { + logger.error("Error while writing audit log id '{}' to Solr.", xXAccessAudit.getId(), e); + + writeMigrationStatusFile(lastMigratedID, CHECK_FILE_NAME); + + logger.info("Stopping migration process!"); + System.out.println("Error while writing audit log id '" + xXAccessAudit.getId() + "' to Solr."); + System.out.println("Migration process failed, Please refer ranger_db_patch.log file."); + + return; + } + } + } + } + } else if (auditTableVersion == 6) { + List xXAccessAuditV6List = daoManager.getXXAccessAudit().getByIdRangeV6(rangeStart, rangeEnd + 1); + + if (!CollectionUtils.isEmpty(xXAccessAuditV6List)) { + for (XXAccessAudit xXAccessAudit : xXAccessAuditV6List) { + if (xXAccessAudit != null) { + try { + send2solr(xXAccessAudit); + + lastMigratedID = xXAccessAudit.getId(); + + totalMigratedLogs++; + } catch (Throwable e) { + logger.error("Error while writing audit log id '{}' to Solr.", xXAccessAudit.getId(), e); + + writeMigrationStatusFile(lastMigratedID, CHECK_FILE_NAME); + + logger.info("Stopping migration process!"); + System.out.println("Error while writing audit log id '" + xXAccessAudit.getId() + "' to Solr."); + System.out.println("Migration process failed, Please refer ranger_db_patch.log file."); + + return; + } + } + } + } + } + + timeTaken = (System.currentTimeMillis() - startTimeInMS); + + logger.info("Batch #{}: time taken:{} ms", index, timeTaken); + + if (rangeEnd < maxXXAccessAuditID) { + writeMigrationStatusFile(rangeEnd, CHECK_FILE_NAME); + } else { + writeMigrationStatusFile(maxXXAccessAuditID, CHECK_FILE_NAME); + } + + rangeStart = rangeEnd; + rangeEnd = rangeEnd + maxRowsPerBatch; + } + + if (totalMigratedLogs > 0) { + System.out.println("Total Number of Migrated Audit logs:" + totalMigratedLogs); + logger.info("Total Number of Migrated Audit logs:{}", totalMigratedLogs); + } + + if (solrClient != null) { + try { + solrClient.close(); + } catch (IOException e) { + logger.error("Error while closing solr connection", e); + } finally { + solrClient = null; + } + } + System.out.println("Migration process finished!!"); + } + + public void send2solr(XXAccessAuditV4 xXAccessAudit) throws Throwable { + SolrInputDocument document = new SolrInputDocument(); + + toSolrDocument(xXAccessAudit, document); + + UpdateResponse response = solrClient.add(document); + + if (response.getStatus() != 0) { + logger.info("Response={}, status= {}, event={}", response, response.getStatus(), xXAccessAudit); + + throw new Exception("Failed to send audit event ID=" + xXAccessAudit.getId()); + } + } + + public void send2solr(XXAccessAuditV5 xXAccessAudit) throws Throwable { + SolrInputDocument document = new SolrInputDocument(); + + toSolrDocument(xXAccessAudit, document); + + UpdateResponse response = solrClient.add(document); + + if (response.getStatus() != 0) { + logger.info("Response={}, status= {}, event={}", response, response.getStatus(), xXAccessAudit); + + throw new Exception("Failed to send audit event ID=" + xXAccessAudit.getId()); + } + } + + public void send2solr(XXAccessAudit xXAccessAudit) throws Throwable { + SolrInputDocument document = new SolrInputDocument(); + + toSolrDocument(xXAccessAudit, document); + + UpdateResponse response = solrClient.add(document); + + if (response.getStatus() != 0) { + logger.info("Response={}, status= {}, event={}", response, response.getStatus(), xXAccessAudit); + + throw new Exception("Failed to send audit event ID=" + xXAccessAudit.getId()); + } + } + + private void toSolrDocument(XXAccessAuditBase xXAccessAudit, SolrInputDocument document) { + // add v4 fields + document.addField("id", xXAccessAudit.getId()); + document.addField("access", xXAccessAudit.getAccessType()); + document.addField("enforcer", xXAccessAudit.getAclEnforcer()); + document.addField("agent", xXAccessAudit.getAgentId()); + document.addField("repo", xXAccessAudit.getRepoName()); + document.addField("sess", xXAccessAudit.getSessionId()); + document.addField("reqUser", xXAccessAudit.getRequestUser()); + document.addField("reqData", xXAccessAudit.getRequestData()); + document.addField("resource", xXAccessAudit.getResourcePath()); + document.addField("cliIP", xXAccessAudit.getClientIP()); + document.addField("logType", "RangerAudit"); + document.addField("result", xXAccessAudit.getAccessResult()); + document.addField("policy", xXAccessAudit.getPolicyId()); + document.addField("repoType", xXAccessAudit.getRepoType()); + document.addField("resType", xXAccessAudit.getResourceType()); + document.addField("reason", xXAccessAudit.getResultReason()); + document.addField("action", xXAccessAudit.getAction()); + document.addField("evtTime", DateUtil.getLocalDateForUTCDate(xXAccessAudit.getEventTime())); + + SolrInputField idField = document.getField("id"); + boolean uidIsString = true; + + if (idField == null) { + Object uid = null; + + if (uidIsString) { + uid = UUID.randomUUID().toString(); + } + + document.setField("id", uid); + } + } + + private void toSolrDocument(XXAccessAuditV5 xXAccessAudit, SolrInputDocument document) { + toSolrDocument((XXAccessAuditBase) xXAccessAudit, document); + + // add v5 fields + document.addField("seq_num", xXAccessAudit.getSequenceNumber()); + document.addField("event_count", xXAccessAudit.getEventCount()); + document.addField("event_dur_ms", xXAccessAudit.getEventDuration()); + } + + private void toSolrDocument(XXAccessAudit xXAccessAudit, SolrInputDocument document) { + toSolrDocument((XXAccessAuditBase) xXAccessAudit, document); + + // add v6 fields + document.addField("seq_num", xXAccessAudit.getSequenceNumber()); + document.addField("event_count", xXAccessAudit.getEventCount()); + document.addField("event_dur_ms", xXAccessAudit.getEventDuration()); + document.addField("tags", xXAccessAudit.getTags()); + } + + private Long readMigrationStatusFile(String aFileName) throws IOException { + long migratedDbID = 0L; + Path path = Paths.get(aFileName); + + if (Files.exists(path) && Files.isRegularFile(path)) { + List fileContents = Files.readAllLines(path, ENCODING); + + if (fileContents != null && fileContents.size() >= 1) { + String line = fileContents.get(fileContents.size() - 1).trim(); + if (!StringUtil.isEmpty(line)) { + try { + migratedDbID = Long.parseLong(line); + } catch (Exception ex) { + // ignore + } + } + } + } + + return migratedDbID; + } + + private void writeMigrationStatusFile(Long dbId, String aFileName) { + try { + Path path = Paths.get(aFileName); + List fileContents = new ArrayList<>(); + + fileContents.add(String.valueOf(dbId)); + + Files.write(path, fileContents, ENCODING); + } catch (IOException ex) { + logger.error("Failed to update migration status to file {}", CHECK_FILE_NAME, ex); + } catch (Exception ex) { + logger.error("Error while updating migration status to file {}", CHECK_FILE_NAME, ex); + } + } + + private SolrClient createSolrClient() throws Exception { + SolrClient solrClient = null; + + registerSolrClientJAAS(); + + String zkHosts = PropertiesUtil.getProperty(SOLR_ZK_HOSTS); + + if (zkHosts == null) { + zkHosts = PropertiesUtil.getProperty("ranger.audit.solr.zookeeper"); + + if (zkHosts == null) { + zkHosts = PropertiesUtil.getProperty("ranger.solr.zookeeper"); + } + } + + String solrURL = PropertiesUtil.getProperty(SOLR_URLS_PROP); + + if (solrURL == null) { + // Try with url + solrURL = PropertiesUtil.getProperty("ranger.audit.solr.url"); + + if (solrURL == null) { + // Let's try older property name + solrURL = PropertiesUtil.getProperty("ranger.solr.url"); + } + } + + if (zkHosts != null && !"".equals(zkHosts.trim()) && !"none".equalsIgnoreCase(zkHosts.trim())) { + zkHosts = zkHosts.trim(); + + String collectionName = PropertiesUtil.getProperty(SOLR_COLLECTION_NAME); + + if (collectionName == null || "none".equalsIgnoreCase(collectionName)) { + collectionName = DEFAULT_COLLECTION_NAME; + } + + logger.info("Solr zkHosts={}, collectionName={}", zkHosts, collectionName); + + // Instantiate + try (Krb5HttpClientBuilder krbBuild = new Krb5HttpClientBuilder()) { + SolrHttpClientBuilder kb = krbBuild.getBuilder(); + + HttpClientUtil.setHttpClientBuilder(kb); + + final List zkhosts = new ArrayList(Arrays.asList(zkHosts.split(","))); + CloudSolrClient solrCloudClient = new CloudSolrClient.Builder(zkhosts, null).build(); + + solrCloudClient.setDefaultCollection(collectionName); + + return solrCloudClient; + } catch (Exception e) { + logger.error("Can't connect to Solr server. ZooKeepers={}, collection={}", zkHosts, collectionName, e); + + throw e; + } + } else { + if (solrURL == null || solrURL.isEmpty() || "none".equalsIgnoreCase(solrURL)) { + logger.error("Solr ZKHosts and URL for Audit are empty. Please set property {} or {}", SOLR_ZK_HOSTS, SOLR_URLS_PROP); + } else { + try (Krb5HttpClientBuilder krbBuild = new Krb5HttpClientBuilder()) { + SolrHttpClientBuilder kb = krbBuild.getBuilder(); + + HttpClientUtil.setHttpClientBuilder(kb); + + HttpSolrClient.Builder builder = new HttpSolrClient.Builder(); + + builder.withBaseSolrUrl(solrURL); + builder.allowCompression(true); + builder.withConnectionTimeout(1000); + + HttpSolrClient httpSolrClient = builder.build(); + + httpSolrClient.setRequestWriter(new BinaryRequestWriter()); + + solrClient = httpSolrClient; + } catch (Exception e) { + logger.error("Can't connect to Solr server. URL={}", solrURL, e); + + throw e; + } + } + } + + return solrClient; + } + + private void registerSolrClientJAAS() { + logger.info("==> createSolrClient.registerSolrClientJAAS()"); + + Properties props = PropertiesUtil.getProps(); + + try { + // SolrJ requires "java.security.auth.login.config" property to be set to identify itself that it is kerberized. So using a dummy property for it + // Acutal solrclient JAAS configs are read from the ranger-admin-site.xml in ranger admin config folder and set by InMemoryJAASConfiguration + // Refer InMemoryJAASConfiguration doc for JAAS Configuration + if (System.getProperty(PROP_JAVA_SECURITY_AUTH_LOGIN_CONFIG) == null) { + System.setProperty(PROP_JAVA_SECURITY_AUTH_LOGIN_CONFIG, "/dev/null"); + } + + logger.info("Loading SolrClient JAAS config from Ranger audit config if present..."); + + Configuration conf = InMemoryJAASConfiguration.init(props); + + if (conf != null) { + Configuration.setConfiguration(conf); + } + } catch (Exception e) { + logger.error("ERROR: Unable to load SolrClient JAAS config from ranger admin config file. Audit migration to Secure Solr will fail...", e); + } + + logger.info("<==createSolrClient.registerSolrClientJAAS()"); + } } diff --git a/security-admin/src/main/java/org/apache/ranger/patch/cliutil/MetricUtil.java b/security-admin/src/main/java/org/apache/ranger/patch/cliutil/MetricUtil.java index ef6c64da52..92dacca142 100644 --- a/security-admin/src/main/java/org/apache/ranger/patch/cliutil/MetricUtil.java +++ b/security-admin/src/main/java/org/apache/ranger/patch/cliutil/MetricUtil.java @@ -16,22 +16,14 @@ */ package org.apache.ranger.patch.cliutil; -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Date; - -import org.apache.ranger.authorization.utils.JsonUtils; -import org.apache.ranger.common.DateUtil; import org.apache.commons.lang.StringUtils; import org.apache.ranger.audit.provider.MiscUtil; +import org.apache.ranger.authorization.utils.JsonUtils; import org.apache.ranger.biz.AssetMgr; import org.apache.ranger.biz.RangerBizUtil; import org.apache.ranger.biz.ServiceDBStore; import org.apache.ranger.biz.XUserMgr; +import org.apache.ranger.common.DateUtil; import org.apache.ranger.common.MessageEnums; import org.apache.ranger.common.RESTErrorUtil; import org.apache.ranger.common.RangerConstants; @@ -48,10 +40,10 @@ import org.apache.ranger.util.RestUtil; import org.apache.ranger.view.VXAccessAuditList; import org.apache.ranger.view.VXGroupList; -import org.apache.ranger.view.VXMetricContextEnricher; import org.apache.ranger.view.VXMetricAuditDetailsCount; -import org.apache.ranger.view.VXMetricServiceCount; +import org.apache.ranger.view.VXMetricContextEnricher; import org.apache.ranger.view.VXMetricPolicyCount; +import org.apache.ranger.view.VXMetricServiceCount; import org.apache.ranger.view.VXMetricUserGroupCount; import org.apache.ranger.view.VXUserList; import org.slf4j.Logger; @@ -59,443 +51,525 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + @Component -public class MetricUtil extends BaseLoader { - - private static final Logger logger = LoggerFactory.getLogger(MetricUtil.class); - - public static String metricType; - - @Autowired - XUserMgr xUserMgr; - - @Autowired - AssetMgr assetMgr; - - @Autowired - ServiceDBStore svcStore; - - @Autowired - RangerBizUtil xaBizUtil; - - @Autowired - RESTErrorUtil restErrorUtil; - - public static void main(String[] args) { - /* LOG4J2: TODO - logger.getRootLogger().setLevel(Level.OFF); - */ - logger.info("MetricUtil : main()"); - try { - MetricUtil loader = (MetricUtil) CLIUtil.getBean(MetricUtil.class); - loader.init(); - if (args.length != 2) { - System.out.println("type: Incorrect Arguments usage : -type policies | audits | usergroup | services | database | contextenrichers | denyconditions"); - } else { - if (!("-type".equalsIgnoreCase(args[0])) || !("policies".equalsIgnoreCase(args[1]) || "audits".equalsIgnoreCase(args[1]) || "usergroup".equalsIgnoreCase(args[1]) || "services".equalsIgnoreCase(args[1]) || "database".equalsIgnoreCase(args[1]) || "contextenrichers".equalsIgnoreCase(args[1]) || "denyconditions".equalsIgnoreCase(args[1]))) { - System.out.println("type: Incorrect Arguments usage : -type policies | audits | usergroup | services | database | contextenrichers | denyconditions"); - } else { - metricType = args[1]; - if (logger.isDebugEnabled()) { - logger.debug("Metric Type : " + metricType); - } - } - } - while (loader.isMoreToProcess()) { - loader.load(); - } - logger.info("Load complete. Exiting!!!"); - System.exit(0); - } catch (Exception e) { - logger.error("Error loading", e); - System.exit(1); - } - } - - @Override - public void init() throws Exception { - logger.info("==> MetricUtil.init()"); - } - - @Override - public void execLoad() { - logger.info("==> MetricUtil.execLoad()"); - metricCalculation(metricType); - logger.info("<== MetricUtil.execLoad()"); - } - - @Override - public void printStats() { - } - - private void metricCalculation(String caseValue) { - logger.info("Metric Type : " + caseValue); - try { - SearchCriteria searchCriteria = new SearchCriteria(); - searchCriteria.setStartIndex(0); - searchCriteria.setMaxRows(100); - searchCriteria.setGetCount(true); - searchCriteria.setSortType("asc"); - - switch (caseValue.toLowerCase()) { - case "usergroup": - try { - VXGroupList vxGroupList = xUserMgr.searchXGroups(searchCriteria); - - long groupCount = vxGroupList.getTotalCount(); - - ArrayList userAdminRoleCount = new ArrayList(); +public class MetricUtil extends BaseLoader { + private static final Logger logger = LoggerFactory.getLogger(MetricUtil.class); + + public static String metricType; + + @Autowired + XUserMgr xUserMgr; + + @Autowired + AssetMgr assetMgr; + + @Autowired + ServiceDBStore svcStore; + + @Autowired + RangerBizUtil xaBizUtil; + + @Autowired + RESTErrorUtil restErrorUtil; + + public static void main(String[] args) { + logger.info("MetricUtil : main()"); + + try { + MetricUtil loader = (MetricUtil) CLIUtil.getBean(MetricUtil.class); + + loader.init(); + if (args.length != 2) { + System.out.println("type: Incorrect Arguments usage : -type policies | audits | usergroup | services | database | contextenrichers | denyconditions"); + } else { + if (!("-type".equalsIgnoreCase(args[0])) || !("policies".equalsIgnoreCase(args[1]) || "audits".equalsIgnoreCase(args[1]) || "usergroup".equalsIgnoreCase(args[1]) || "services".equalsIgnoreCase(args[1]) || "database".equalsIgnoreCase(args[1]) || "contextenrichers".equalsIgnoreCase(args[1]) || "denyconditions".equalsIgnoreCase(args[1]))) { + System.out.println("type: Incorrect Arguments usage : -type policies | audits | usergroup | services | database | contextenrichers | denyconditions"); + } else { + metricType = args[1]; + + logger.debug("Metric Type : {}", metricType); + } + } + + while (loader.isMoreToProcess()) { + loader.load(); + } + + logger.info("Load complete. Exiting!!!"); + + System.exit(0); + } catch (Exception e) { + logger.error("Error loading", e); + + System.exit(1); + } + } + + @Override + public void init() throws Exception { + logger.info("==> MetricUtil.init()"); + } + + @Override + public void printStats() { + } + + @Override + public void execLoad() { + logger.info("==> MetricUtil.execLoad()"); + + metricCalculation(metricType); + + logger.info("<== MetricUtil.execLoad()"); + } + + private void metricCalculation(String caseValue) { + logger.info("Metric Type : {}", caseValue); + + try { + SearchCriteria searchCriteria = new SearchCriteria(); + + searchCriteria.setStartIndex(0); + searchCriteria.setMaxRows(100); + searchCriteria.setGetCount(true); + searchCriteria.setSortType("asc"); + + switch (caseValue.toLowerCase()) { + case "usergroup": + try { + VXGroupList vxGroupList = xUserMgr.searchXGroups(searchCriteria); + long groupCount = vxGroupList.getTotalCount(); + ArrayList userAdminRoleCount = new ArrayList<>(); + userAdminRoleCount.add(RangerConstants.ROLE_SYS_ADMIN); + long userSysAdminCount = getUserCountBasedOnUserRole(userAdminRoleCount); - ArrayList userAdminAuditorRoleCount = new ArrayList(); + ArrayList userAdminAuditorRoleCount = new ArrayList<>(); + userAdminAuditorRoleCount.add(RangerConstants.ROLE_ADMIN_AUDITOR); + long userSysAdminAuditorCount = getUserCountBasedOnUserRole(userAdminAuditorRoleCount); - ArrayList userRoleListKeyRoleAdmin = new ArrayList(); - userRoleListKeyRoleAdmin.add(RangerConstants.ROLE_KEY_ADMIN); - long userKeyAdminCount = getUserCountBasedOnUserRole(userRoleListKeyRoleAdmin); + ArrayList userRoleListKeyRoleAdmin = new ArrayList<>(); + + userRoleListKeyRoleAdmin.add(RangerConstants.ROLE_KEY_ADMIN); + + long userKeyAdminCount = getUserCountBasedOnUserRole(userRoleListKeyRoleAdmin); + + ArrayList userRoleListKeyadminAduitorRole = new ArrayList<>(); - ArrayList userRoleListKeyadminAduitorRole = new ArrayList(); userRoleListKeyadminAduitorRole.add(RangerConstants.ROLE_KEY_ADMIN_AUDITOR); + long userKeyadminAuditorCount = getUserCountBasedOnUserRole(userRoleListKeyadminAduitorRole); - ArrayList userRoleListUser = new ArrayList(); - userRoleListUser.add(RangerConstants.ROLE_USER); - long userRoleCount = getUserCountBasedOnUserRole(userRoleListUser); - - long userTotalCount = userSysAdminCount + userKeyAdminCount + userRoleCount + userKeyadminAuditorCount + userSysAdminAuditorCount; - - VXMetricUserGroupCount metricUserGroupCount = new VXMetricUserGroupCount(); - metricUserGroupCount.setUserCountOfUserRole(userRoleCount); - metricUserGroupCount.setUserCountOfKeyAdminRole(userKeyAdminCount); - metricUserGroupCount.setUserCountOfSysAdminRole(userSysAdminCount); - metricUserGroupCount.setUserCountOfKeyadminAuditorRole(userKeyadminAuditorCount); - metricUserGroupCount.setUserCountOfSysAdminAuditorRole(userSysAdminAuditorCount); - metricUserGroupCount.setUserTotalCount(userTotalCount); - metricUserGroupCount.setGroupCount(groupCount); - final String jsonUserGroupCount = JsonUtils.objectToJson(metricUserGroupCount); - System.out.println(jsonUserGroupCount); - } catch (Exception e) { - logger.error("Error calculating Metric for usergroup : " + e.getMessage()); - } - break; - case "audits": - try{ - int clientTimeOffsetInMinute = RestUtil.getClientTimeOffset(); - String defaultDateFormat="MM/dd/yyyy"; - DateFormat formatter = new SimpleDateFormat(defaultDateFormat); - - VXMetricAuditDetailsCount auditObj = new VXMetricAuditDetailsCount(); - DateUtil dateUtilTwoDays = new DateUtil(); - Date startDateUtilTwoDays = dateUtilTwoDays.getDateFromNow(-2); - Date dStart2 = restErrorUtil.parseDate(formatter.format(startDateUtilTwoDays), - "Invalid value for startDate", - MessageEnums.INVALID_INPUT_DATA, null, "startDate", defaultDateFormat); - - Date endDateTwoDays = MiscUtil.getUTCDate(); - Date dEnd2 = restErrorUtil.parseDate(formatter.format(endDateTwoDays), - "Invalid value for endDate", - MessageEnums.INVALID_INPUT_DATA, null, "endDate", defaultDateFormat); - dEnd2 = dateUtilTwoDays.getDateFromGivenDate(dEnd2, 0, 23, 59, 59); - dEnd2 = dateUtilTwoDays.addTimeOffset(dEnd2, clientTimeOffsetInMinute); - VXMetricServiceCount deniedCountObj = getAuditsCount(0,dStart2,dEnd2); - auditObj.setDenialEventsCountTwoDays(deniedCountObj); - - VXMetricServiceCount allowedCountObj = getAuditsCount(1,dStart2,dEnd2); - auditObj.setAccessEventsCountTwoDays(allowedCountObj); - - long totalAuditsCountTwoDays = deniedCountObj.getTotalCount() + allowedCountObj.getTotalCount(); - auditObj.setSolrIndexCountTwoDays(totalAuditsCountTwoDays); - - DateUtil dateUtilWeek = new DateUtil(); - Date startDateUtilWeek = dateUtilWeek.getDateFromNow(-7); - Date dStart7 = restErrorUtil.parseDate(formatter.format(startDateUtilWeek), - "Invalid value for startDate", - MessageEnums.INVALID_INPUT_DATA, null, "startDate", defaultDateFormat); - - Date endDateWeek = MiscUtil.getUTCDate(); - DateUtil dateUtilweek = new DateUtil(); - Date dEnd7 = restErrorUtil.parseDate(formatter.format(endDateWeek), - "Invalid value for endDate", - MessageEnums.INVALID_INPUT_DATA, null, "endDate", defaultDateFormat); - dEnd7 = dateUtilweek.getDateFromGivenDate(dEnd7,0, 23, 59, 59 ); - dEnd7 = dateUtilweek.addTimeOffset(dEnd7, clientTimeOffsetInMinute); - VXMetricServiceCount deniedCountObjWeek = getAuditsCount(0,dStart7,dEnd7); - auditObj.setDenialEventsCountWeek(deniedCountObjWeek); - - VXMetricServiceCount allowedCountObjWeek = getAuditsCount(1,dStart7,dEnd7); - auditObj.setAccessEventsCountWeek(allowedCountObjWeek); - - long totalAuditsCountWeek = deniedCountObjWeek.getTotalCount() + allowedCountObjWeek.getTotalCount(); - auditObj.setSolrIndexCountWeek(totalAuditsCountWeek); - - final String jsonAudit = JsonUtils.objectToJson(auditObj); - System.out.println(jsonAudit); - }catch (Exception e) { - logger.error("Error calculating Metric for audits : "+e.getMessage()); - } - break; - case "services" : - try { - SearchFilter serviceFilter = new SearchFilter(); - serviceFilter.setMaxRows(200); - serviceFilter.setStartIndex(0); - serviceFilter.setGetCount(true); - serviceFilter.setSortBy("serviceId"); - serviceFilter.setSortType("asc"); - VXMetricServiceCount vXMetricServiceCount = new VXMetricServiceCount(); - PList paginatedSvcs = svcStore.getPaginatedServices(serviceFilter); - long totalServiceCount = paginatedSvcs.getTotalCount(); - List rangerServiceList = paginatedSvcs.getList(); - Map services = new HashMap(); - for (Object rangerService : rangerServiceList) { - RangerService RangerServiceObj = (RangerService) rangerService; - String serviceName = RangerServiceObj.getType(); - if (!(services.containsKey(serviceName))) { - serviceFilter.setParam("serviceType", serviceName); - PList paginatedSvcscount = svcStore.getPaginatedServices(serviceFilter); - services.put(serviceName, paginatedSvcscount.getTotalCount()); - } - } - vXMetricServiceCount.setServiceBasedCountList(services); - vXMetricServiceCount.setTotalCount(totalServiceCount); - final String jsonServices = JsonUtils.objectToJson(vXMetricServiceCount); - System.out.println(jsonServices); - } catch (Exception e) { - logger.error("Error calculating Metric for services : " + e.getMessage()); - } - break; - case "policies" : - try { - SearchFilter policyFilter = new SearchFilter(); - policyFilter.setMaxRows(200); - policyFilter.setStartIndex(0); - policyFilter.setGetCount(true); - policyFilter.setSortBy("serviceId"); - policyFilter.setSortType("asc"); - VXMetricPolicyCount vXMetricPolicyCount = new VXMetricPolicyCount(); - PList paginatedSvcsList = svcStore.getPaginatedPolicies(policyFilter); - vXMetricPolicyCount.setTotalCount(paginatedSvcsList.getTotalCount()); - Map servicesWithPolicy = new HashMap(); - for (int k = 2; k >= 0; k--) { - String policyType = String.valueOf(k); - VXMetricServiceCount vXMetricServiceCount = getVXMetricServiceCount(policyType); - if (k == 2) { - servicesWithPolicy.put("rowFilteringPolicies", vXMetricServiceCount); } - else if (k == 1) { - servicesWithPolicy.put("maskingPolicies", vXMetricServiceCount); } - else if (k == 0) { - servicesWithPolicy.put("resourceAccessPolicies", vXMetricServiceCount);} - } - boolean tagFlag = false; - if (tagFlag == false) { - policyFilter.setParam("serviceType", "tag"); - PList policiestype = svcStore.getPaginatedPolicies(policyFilter); - Map tagMap = new HashMap(); - long tagCount = policiestype.getTotalCount(); - tagMap.put("tag", tagCount); - VXMetricServiceCount vXMetricServiceCount = new VXMetricServiceCount(); - vXMetricServiceCount.setServiceBasedCountList(tagMap); - vXMetricServiceCount.setTotalCount(tagCount); - servicesWithPolicy.put("tagAccessPolicies", vXMetricServiceCount); - tagFlag = true; - } - vXMetricPolicyCount.setPolicyCountList(servicesWithPolicy); - final String jsonPolicies = JsonUtils.objectToJson(vXMetricPolicyCount); - System.out.println(jsonPolicies); - } catch (Exception e) { - logger.error("Error calculating Metric for policies : " + e.getMessage()); - } - break; - case "database" : - try { - int dbFlavor = RangerBizUtil.getDBFlavor(); - String dbFlavourType = RangerBizUtil.getDBFlavorType(dbFlavor); - String dbDetail = dbFlavourType + " " + xaBizUtil.getDBVersion(); - String jsonDBDetail = JsonUtils.objectToJson(dbDetail); - - logger.info("jsonDBDetail:" + jsonDBDetail); - } catch (Exception e) { - logger.error("Error calculating Metric for database : " + e.getMessage()); - } - break; - case "contextenrichers": - try { - SearchFilter filter = new SearchFilter(); - filter.setStartIndex(0); - VXMetricContextEnricher serviceWithContextEnrichers = new VXMetricContextEnricher(); - PList paginatedSvcDefs = svcStore.getPaginatedServiceDefs(filter); - List repoTypeList = paginatedSvcDefs.getList(); - if (repoTypeList != null) { - for (RangerServiceDef repoType : repoTypeList) { - RangerServiceDef rangerServiceDefObj = (RangerServiceDef) repoType; - String name = rangerServiceDefObj.getName(); - List contextEnrichers = rangerServiceDefObj.getContextEnrichers(); - if (contextEnrichers != null && !contextEnrichers.isEmpty()) { - serviceWithContextEnrichers.setServiceName(name); - serviceWithContextEnrichers.setTotalCount(contextEnrichers.size()); - } - } - } - final String jsonContextEnrichers = JsonUtils.objectToJson(serviceWithContextEnrichers); - System.out.println(jsonContextEnrichers); - } catch (Exception e) { - logger.error("Error calculating Metric for contextenrichers : " + e.getMessage()); - } - break; - case "denyconditions": - try { - SearchFilter policyFilter1 = new SearchFilter(); - policyFilter1.setMaxRows(200); - policyFilter1.setStartIndex(0); - policyFilter1.setGetCount(true); - policyFilter1.setSortBy("serviceId"); - policyFilter1.setSortType("asc"); - - int denyCount = 0; - Map denyconditionsonMap = new HashMap(); - PList paginatedSvcDefs = svcStore.getPaginatedServiceDefs(policyFilter1); - if (paginatedSvcDefs != null) { - List rangerServiceDefs = paginatedSvcDefs.getList(); - if (rangerServiceDefs != null && !rangerServiceDefs.isEmpty()) { - for (RangerServiceDef rangerServiceDef : rangerServiceDefs) { - if (rangerServiceDef != null) { - String serviceDef = rangerServiceDef.getName(); - if (!StringUtils.isEmpty(serviceDef)) { - policyFilter1.setParam("serviceType", serviceDef); - policyFilter1.setParam("denyCondition", "true"); - PList policiesList = svcStore.getPaginatedPolicies(policyFilter1); - if (policiesList != null && policiesList.getListSize() > 0) { - int policyListCount = policiesList.getListSize(); - if (policyListCount > 0 && policiesList.getList() != null) { - List policies = policiesList.getList(); - for (RangerPolicy policy : policies) { - if (policy != null) { - List policyItem = policy.getDenyPolicyItems(); - if (policyItem != null && !policyItem.isEmpty()) { - if (denyconditionsonMap.get(serviceDef) != null) { - denyCount = denyconditionsonMap.get(serviceDef) + denyCount + policyItem.size(); - } else { - denyCount = denyCount + policyItem.size(); - } - } - List policyItemExclude = policy.getDenyExceptions(); - if (policyItemExclude != null && !policyItemExclude.isEmpty()) { - if (denyconditionsonMap.get(serviceDef) != null) { - denyCount = denyconditionsonMap.get(serviceDef) + denyCount + policyItemExclude.size(); - } else { - denyCount = denyCount + policyItemExclude.size(); - } - } - } - } - } - } - policyFilter1.removeParam("serviceType"); - } - denyconditionsonMap.put(serviceDef, denyCount); - denyCount = 0; - } - } - } - } - String jsonContextDenyCondtionOn = JsonUtils.objectToJson(denyconditionsonMap); - System.out.println(jsonContextDenyCondtionOn); - } catch (Exception e) { - logger.error("Error calculating Metric for denyconditions : " + e.getMessage()); - } - break; - default: - System.out.println("type: Incorrect Arguments usage : -type policies | audits | usergroup | services | database | contextenrichers | denyconditions"); - logger.info("Please enter the valid arguments for Metric Calculation"); - break; - } - } catch(Exception e) { - logger.error("Error calculating Metric : "+e.getMessage()); - } - } - - private VXMetricServiceCount getVXMetricServiceCount(String policyType) - throws Exception { - SearchFilter policyFilter1 = new SearchFilter(); - policyFilter1.setMaxRows(200); - policyFilter1.setStartIndex(0); - policyFilter1.setGetCount(true); - policyFilter1.setSortBy("serviceId"); - policyFilter1.setSortType("asc"); - policyFilter1.setParam("policyType", policyType); - PList policies = svcStore.getPaginatedPolicies(policyFilter1); - PList paginatedSvcsSevice = svcStore.getPaginatedServices(policyFilter1); - - List rangerServiceList = paginatedSvcsSevice.getList(); - - Map servicesforPolicyType = new HashMap(); - long tagCount = 0; - for (Object rangerService : rangerServiceList) { - RangerService rangerServiceObj = (RangerService) rangerService; - String serviceName = rangerServiceObj.getType(); - if (!(servicesforPolicyType.containsKey(serviceName))) { - policyFilter1.setParam("serviceType", serviceName); - PList policiestype = svcStore.getPaginatedPolicies(policyFilter1); - long count = policiestype.getTotalCount(); - if (count != 0) { - if (!"tag".equalsIgnoreCase(serviceName)) { - servicesforPolicyType.put(serviceName, count); - } else { - tagCount = count; - } - } - } - } - VXMetricServiceCount vXMetricServiceCount = new VXMetricServiceCount(); - vXMetricServiceCount.setServiceBasedCountList(servicesforPolicyType); - long totalCountOfPolicyType = policies.getTotalCount() - tagCount; - vXMetricServiceCount.setTotalCount(totalCountOfPolicyType); - return vXMetricServiceCount; - } - - private VXMetricServiceCount getAuditsCount(int accessResult, - Date startDate, Date endDate) throws Exception { - long totalCountOfAudits = 0; - SearchFilter filter = new SearchFilter(); - filter.setStartIndex(0); - Map servicesRepoType = new HashMap(); - VXMetricServiceCount vXMetricServiceCount = new VXMetricServiceCount(); - PList paginatedSvcDefs = svcStore.getPaginatedServiceDefs(filter); - Iterable repoTypeGet = paginatedSvcDefs.getList(); - for (Object repo : repoTypeGet) { - RangerServiceDef rangerServiceDefObj = (RangerServiceDef) repo; - long id = rangerServiceDefObj.getId(); - String serviceRepoName = rangerServiceDefObj.getName(); - SearchCriteria searchCriteriaWithType = new SearchCriteria(); - searchCriteriaWithType.getParamList().put("repoType", id); - searchCriteriaWithType.getParamList().put("accessResult", accessResult); - searchCriteriaWithType.addParam("startDate", startDate); - searchCriteriaWithType.addParam("endDate", endDate); - searchCriteriaWithType.setMaxRows(0); - searchCriteriaWithType.setGetCount(true); - VXAccessAuditList vXAccessAuditListwithType = assetMgr.getAccessLogs(searchCriteriaWithType); - long toltalCountOfRepo = vXAccessAuditListwithType.getTotalCount(); - if (toltalCountOfRepo != 0) { - servicesRepoType.put(serviceRepoName, toltalCountOfRepo); - totalCountOfAudits += toltalCountOfRepo; - } - } - vXMetricServiceCount.setServiceBasedCountList(servicesRepoType); - vXMetricServiceCount.setTotalCount(totalCountOfAudits); - return vXMetricServiceCount; - } - - private Long getUserCountBasedOnUserRole(@SuppressWarnings("rawtypes") List userRoleList) { - SearchCriteria searchCriteria = new SearchCriteria(); - searchCriteria.setStartIndex(0); - searchCriteria.setMaxRows(100); - searchCriteria.setGetCount(true); - searchCriteria.setSortType("asc"); - searchCriteria.addParam("userRoleList", userRoleList); - VXUserList VXUserListKeyAdmin = xUserMgr.searchXUsers(searchCriteria); - long userCount = VXUserListKeyAdmin.getTotalCount(); - return userCount; - } + ArrayList userRoleListUser = new ArrayList<>(); + + userRoleListUser.add(RangerConstants.ROLE_USER); + + long userRoleCount = getUserCountBasedOnUserRole(userRoleListUser); + long userTotalCount = userSysAdminCount + userKeyAdminCount + userRoleCount + userKeyadminAuditorCount + userSysAdminAuditorCount; + VXMetricUserGroupCount metricUserGroupCount = new VXMetricUserGroupCount(); + + metricUserGroupCount.setUserCountOfUserRole(userRoleCount); + metricUserGroupCount.setUserCountOfKeyAdminRole(userKeyAdminCount); + metricUserGroupCount.setUserCountOfSysAdminRole(userSysAdminCount); + metricUserGroupCount.setUserCountOfKeyadminAuditorRole(userKeyadminAuditorCount); + metricUserGroupCount.setUserCountOfSysAdminAuditorRole(userSysAdminAuditorCount); + metricUserGroupCount.setUserTotalCount(userTotalCount); + metricUserGroupCount.setGroupCount(groupCount); + + final String jsonUserGroupCount = JsonUtils.objectToJson(metricUserGroupCount); + + System.out.println(jsonUserGroupCount); + } catch (Exception e) { + logger.error("Error calculating Metric for usergroup : {}", e.getMessage()); + } + break; + case "audits": + try { + int clientTimeOffsetInMinute = RestUtil.getClientTimeOffset(); + String defaultDateFormat = "MM/dd/yyyy"; + DateFormat formatter = new SimpleDateFormat(defaultDateFormat); + VXMetricAuditDetailsCount auditObj = new VXMetricAuditDetailsCount(); + DateUtil dateUtilTwoDays = new DateUtil(); + Date startDateUtilTwoDays = dateUtilTwoDays.getDateFromNow(-2); + Date dStart2 = restErrorUtil.parseDate(formatter.format(startDateUtilTwoDays), "Invalid value for startDate", MessageEnums.INVALID_INPUT_DATA, null, "startDate", defaultDateFormat); + Date endDateTwoDays = MiscUtil.getUTCDate(); + Date dEnd2 = restErrorUtil.parseDate(formatter.format(endDateTwoDays), "Invalid value for endDate", MessageEnums.INVALID_INPUT_DATA, null, "endDate", defaultDateFormat); + + dEnd2 = dateUtilTwoDays.getDateFromGivenDate(dEnd2, 0, 23, 59, 59); + dEnd2 = dateUtilTwoDays.addTimeOffset(dEnd2, clientTimeOffsetInMinute); + + VXMetricServiceCount deniedCountObj = getAuditsCount(0, dStart2, dEnd2); + + auditObj.setDenialEventsCountTwoDays(deniedCountObj); + + VXMetricServiceCount allowedCountObj = getAuditsCount(1, dStart2, dEnd2); + + auditObj.setAccessEventsCountTwoDays(allowedCountObj); + + long totalAuditsCountTwoDays = deniedCountObj.getTotalCount() + allowedCountObj.getTotalCount(); + + auditObj.setSolrIndexCountTwoDays(totalAuditsCountTwoDays); + + DateUtil dateUtilWeek = new DateUtil(); + Date startDateUtilWeek = dateUtilWeek.getDateFromNow(-7); + Date dStart7 = restErrorUtil.parseDate(formatter.format(startDateUtilWeek), "Invalid value for startDate", MessageEnums.INVALID_INPUT_DATA, null, "startDate", defaultDateFormat); + Date endDateWeek = MiscUtil.getUTCDate(); + DateUtil dateUtilweek = new DateUtil(); + Date dEnd7 = restErrorUtil.parseDate(formatter.format(endDateWeek), "Invalid value for endDate", MessageEnums.INVALID_INPUT_DATA, null, "endDate", defaultDateFormat); + + dEnd7 = dateUtilweek.getDateFromGivenDate(dEnd7, 0, 23, 59, 59); + dEnd7 = dateUtilweek.addTimeOffset(dEnd7, clientTimeOffsetInMinute); + + VXMetricServiceCount deniedCountObjWeek = getAuditsCount(0, dStart7, dEnd7); + + auditObj.setDenialEventsCountWeek(deniedCountObjWeek); + + VXMetricServiceCount allowedCountObjWeek = getAuditsCount(1, dStart7, dEnd7); + + auditObj.setAccessEventsCountWeek(allowedCountObjWeek); + + long totalAuditsCountWeek = deniedCountObjWeek.getTotalCount() + allowedCountObjWeek.getTotalCount(); + + auditObj.setSolrIndexCountWeek(totalAuditsCountWeek); + + final String jsonAudit = JsonUtils.objectToJson(auditObj); + + System.out.println(jsonAudit); + } catch (Exception e) { + logger.error("Error calculating Metric for audits : {}", e.getMessage()); + } + break; + case "services": + try { + SearchFilter serviceFilter = new SearchFilter(); + + serviceFilter.setMaxRows(200); + serviceFilter.setStartIndex(0); + serviceFilter.setGetCount(true); + serviceFilter.setSortBy("serviceId"); + serviceFilter.setSortType("asc"); + + VXMetricServiceCount vXMetricServiceCount = new VXMetricServiceCount(); + PList paginatedSvcs = svcStore.getPaginatedServices(serviceFilter); + long totalServiceCount = paginatedSvcs.getTotalCount(); + List rangerServiceList = paginatedSvcs.getList(); + Map services = new HashMap<>(); + + for (RangerService rangerService : rangerServiceList) { + String serviceName = rangerService.getType(); + + if (!(services.containsKey(serviceName))) { + serviceFilter.setParam("serviceType", serviceName); + + PList paginatedSvcscount = svcStore.getPaginatedServices(serviceFilter); + + services.put(serviceName, paginatedSvcscount.getTotalCount()); + } + } + + vXMetricServiceCount.setServiceBasedCountList(services); + vXMetricServiceCount.setTotalCount(totalServiceCount); + + final String jsonServices = JsonUtils.objectToJson(vXMetricServiceCount); + + System.out.println(jsonServices); + } catch (Exception e) { + logger.error("Error calculating Metric for services : {}", e.getMessage()); + } + break; + case "policies": + try { + SearchFilter policyFilter = new SearchFilter(); + + policyFilter.setMaxRows(200); + policyFilter.setStartIndex(0); + policyFilter.setGetCount(true); + policyFilter.setSortBy("serviceId"); + policyFilter.setSortType("asc"); + + VXMetricPolicyCount vXMetricPolicyCount = new VXMetricPolicyCount(); + PList paginatedSvcsList = svcStore.getPaginatedPolicies(policyFilter); + + vXMetricPolicyCount.setTotalCount(paginatedSvcsList.getTotalCount()); + + Map servicesWithPolicy = new HashMap<>(); + + for (int k = 2; k >= 0; k--) { + String policyType = String.valueOf(k); + VXMetricServiceCount vXMetricServiceCount = getVXMetricServiceCount(policyType); + + if (k == 2) { + servicesWithPolicy.put("rowFilteringPolicies", vXMetricServiceCount); + } else if (k == 1) { + servicesWithPolicy.put("maskingPolicies", vXMetricServiceCount); + } else if (k == 0) { + servicesWithPolicy.put("resourceAccessPolicies", vXMetricServiceCount); + } + } + + boolean tagFlag = false; + + if (!tagFlag) { + policyFilter.setParam("serviceType", "tag"); + + PList policiestype = svcStore.getPaginatedPolicies(policyFilter); + Map tagMap = new HashMap<>(); + long tagCount = policiestype.getTotalCount(); + + tagMap.put("tag", tagCount); + + VXMetricServiceCount vXMetricServiceCount = new VXMetricServiceCount(); + + vXMetricServiceCount.setServiceBasedCountList(tagMap); + vXMetricServiceCount.setTotalCount(tagCount); + servicesWithPolicy.put("tagAccessPolicies", vXMetricServiceCount); + + tagFlag = true; + } + + vXMetricPolicyCount.setPolicyCountList(servicesWithPolicy); + + final String jsonPolicies = JsonUtils.objectToJson(vXMetricPolicyCount); + + System.out.println(jsonPolicies); + } catch (Exception e) { + logger.error("Error calculating Metric for policies : {}", e.getMessage()); + } + break; + case "database": + try { + int dbFlavor = RangerBizUtil.getDBFlavor(); + String dbFlavourType = RangerBizUtil.getDBFlavorType(dbFlavor); + String dbDetail = dbFlavourType + " " + xaBizUtil.getDBVersion(); + String jsonDBDetail = JsonUtils.objectToJson(dbDetail); + + logger.info("jsonDBDetail:{}", jsonDBDetail); + } catch (Exception e) { + logger.error("Error calculating Metric for database : {}", e.getMessage()); + } + break; + case "contextenrichers": + try { + SearchFilter filter = new SearchFilter(); + + filter.setStartIndex(0); + + VXMetricContextEnricher serviceWithContextEnrichers = new VXMetricContextEnricher(); + PList paginatedSvcDefs = svcStore.getPaginatedServiceDefs(filter); + List repoTypeList = paginatedSvcDefs.getList(); + + if (repoTypeList != null) { + for (RangerServiceDef repoType : repoTypeList) { + String name = repoType.getName(); + List contextEnrichers = repoType.getContextEnrichers(); + + if (contextEnrichers != null && !contextEnrichers.isEmpty()) { + serviceWithContextEnrichers.setServiceName(name); + serviceWithContextEnrichers.setTotalCount(contextEnrichers.size()); + } + } + } + + final String jsonContextEnrichers = JsonUtils.objectToJson(serviceWithContextEnrichers); + + System.out.println(jsonContextEnrichers); + } catch (Exception e) { + logger.error("Error calculating Metric for contextenrichers : {}", e.getMessage()); + } + break; + case "denyconditions": + try { + SearchFilter policyFilter1 = new SearchFilter(); + + policyFilter1.setMaxRows(200); + policyFilter1.setStartIndex(0); + policyFilter1.setGetCount(true); + policyFilter1.setSortBy("serviceId"); + policyFilter1.setSortType("asc"); + + int denyCount = 0; + Map denyconditionsonMap = new HashMap<>(); + PList paginatedSvcDefs = svcStore.getPaginatedServiceDefs(policyFilter1); + + if (paginatedSvcDefs != null) { + List rangerServiceDefs = paginatedSvcDefs.getList(); + + if (rangerServiceDefs != null && !rangerServiceDefs.isEmpty()) { + for (RangerServiceDef rangerServiceDef : rangerServiceDefs) { + if (rangerServiceDef != null) { + String serviceDef = rangerServiceDef.getName(); + + if (!StringUtils.isEmpty(serviceDef)) { + policyFilter1.setParam("serviceType", serviceDef); + policyFilter1.setParam("denyCondition", "true"); + + PList policiesList = svcStore.getPaginatedPolicies(policyFilter1); + + if (policiesList != null && policiesList.getListSize() > 0) { + int policyListCount = policiesList.getListSize(); + + if (policyListCount > 0 && policiesList.getList() != null) { + List policies = policiesList.getList(); + + for (RangerPolicy policy : policies) { + if (policy != null) { + List policyItem = policy.getDenyPolicyItems(); + + if (policyItem != null && !policyItem.isEmpty()) { + if (denyconditionsonMap.get(serviceDef) != null) { + denyCount = denyconditionsonMap.get(serviceDef) + denyCount + policyItem.size(); + } else { + denyCount = denyCount + policyItem.size(); + } + } + + List policyItemExclude = policy.getDenyExceptions(); + if (policyItemExclude != null && !policyItemExclude.isEmpty()) { + if (denyconditionsonMap.get(serviceDef) != null) { + denyCount = denyconditionsonMap.get(serviceDef) + denyCount + policyItemExclude.size(); + } else { + denyCount = denyCount + policyItemExclude.size(); + } + } + } + } + } + } + + policyFilter1.removeParam("serviceType"); + } + + denyconditionsonMap.put(serviceDef, denyCount); + + denyCount = 0; + } + } + } + } + + String jsonContextDenyCondtionOn = JsonUtils.objectToJson(denyconditionsonMap); + System.out.println(jsonContextDenyCondtionOn); + } catch (Exception e) { + logger.error("Error calculating Metric for denyconditions : {}", e.getMessage()); + } + break; + default: + System.out.println("type: Incorrect Arguments usage : -type policies | audits | usergroup | services | database | contextenrichers | denyconditions"); + logger.info("Please enter the valid arguments for Metric Calculation"); + break; + } + } catch (Exception e) { + logger.error("Error calculating Metric : {}", e.getMessage()); + } + } + + private VXMetricServiceCount getVXMetricServiceCount(String policyType) throws Exception { + SearchFilter policyFilter1 = new SearchFilter(); + + policyFilter1.setMaxRows(200); + policyFilter1.setStartIndex(0); + policyFilter1.setGetCount(true); + policyFilter1.setSortBy("serviceId"); + policyFilter1.setSortType("asc"); + policyFilter1.setParam("policyType", policyType); + + PList policies = svcStore.getPaginatedPolicies(policyFilter1); + PList paginatedSvcsSevice = svcStore.getPaginatedServices(policyFilter1); + List rangerServiceList = paginatedSvcsSevice.getList(); + Map servicesforPolicyType = new HashMap<>(); + long tagCount = 0; + + for (RangerService rangerService : rangerServiceList) { + String serviceName = rangerService.getType(); + + if (!(servicesforPolicyType.containsKey(serviceName))) { + policyFilter1.setParam("serviceType", serviceName); + + PList policiestype = svcStore.getPaginatedPolicies(policyFilter1); + long count = policiestype.getTotalCount(); + + if (count != 0) { + if (!"tag".equalsIgnoreCase(serviceName)) { + servicesforPolicyType.put(serviceName, count); + } else { + tagCount = count; + } + } + } + } + + VXMetricServiceCount vXMetricServiceCount = new VXMetricServiceCount(); + + vXMetricServiceCount.setServiceBasedCountList(servicesforPolicyType); + + long totalCountOfPolicyType = policies.getTotalCount() - tagCount; + + vXMetricServiceCount.setTotalCount(totalCountOfPolicyType); + + return vXMetricServiceCount; + } + + private VXMetricServiceCount getAuditsCount(int accessResult, Date startDate, Date endDate) throws Exception { + long totalCountOfAudits = 0; + SearchFilter filter = new SearchFilter(); + + filter.setStartIndex(0); + + Map servicesRepoType = new HashMap<>(); + VXMetricServiceCount vXMetricServiceCount = new VXMetricServiceCount(); + PList paginatedSvcDefs = svcStore.getPaginatedServiceDefs(filter); + Iterable repoTypeGet = paginatedSvcDefs.getList(); + + for (RangerServiceDef repo : repoTypeGet) { + long id = repo.getId(); + String serviceRepoName = repo.getName(); + SearchCriteria searchCriteriaWithType = new SearchCriteria(); + + searchCriteriaWithType.getParamList().put("repoType", id); + searchCriteriaWithType.getParamList().put("accessResult", accessResult); + searchCriteriaWithType.addParam("startDate", startDate); + searchCriteriaWithType.addParam("endDate", endDate); + searchCriteriaWithType.setMaxRows(0); + searchCriteriaWithType.setGetCount(true); + + VXAccessAuditList vXAccessAuditListwithType = assetMgr.getAccessLogs(searchCriteriaWithType); + long toltalCountOfRepo = vXAccessAuditListwithType.getTotalCount(); + + if (toltalCountOfRepo != 0) { + servicesRepoType.put(serviceRepoName, toltalCountOfRepo); + + totalCountOfAudits += toltalCountOfRepo; + } + } + + vXMetricServiceCount.setServiceBasedCountList(servicesRepoType); + vXMetricServiceCount.setTotalCount(totalCountOfAudits); + + return vXMetricServiceCount; + } + + private Long getUserCountBasedOnUserRole(@SuppressWarnings("rawtypes") List userRoleList) { + SearchCriteria searchCriteria = new SearchCriteria(); + + searchCriteria.setStartIndex(0); + searchCriteria.setMaxRows(100); + searchCriteria.setGetCount(true); + searchCriteria.setSortType("asc"); + searchCriteria.addParam("userRoleList", userRoleList); + + VXUserList vxUserListKeyAdmin = xUserMgr.searchXUsers(searchCriteria); + + return vxUserListKeyAdmin.getTotalCount(); + } } diff --git a/security-admin/src/main/java/org/apache/ranger/patch/cliutil/RoleBasedUserSearchUtil.java b/security-admin/src/main/java/org/apache/ranger/patch/cliutil/RoleBasedUserSearchUtil.java index ae793e2c9a..587e1c7453 100644 --- a/security-admin/src/main/java/org/apache/ranger/patch/cliutil/RoleBasedUserSearchUtil.java +++ b/security-admin/src/main/java/org/apache/ranger/patch/cliutil/RoleBasedUserSearchUtil.java @@ -19,20 +19,14 @@ package org.apache.ranger.patch.cliutil; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; - import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.MapUtils; +import org.apache.commons.lang.StringUtils; import org.apache.ranger.biz.UserMgr; import org.apache.ranger.biz.XUserMgr; import org.apache.ranger.common.RangerConstants; import org.apache.ranger.db.RangerDaoManager; import org.apache.ranger.entity.XXPortalUser; -import org.apache.commons.lang.StringUtils; import org.apache.ranger.patch.BaseLoader; import org.apache.ranger.service.XUserService; import org.apache.ranger.util.CLIUtil; @@ -42,254 +36,308 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; + @Component public class RoleBasedUserSearchUtil extends BaseLoader { + private static final Logger logger = LoggerFactory.getLogger(RoleBasedUserSearchUtil.class); - private static final Logger logger = LoggerFactory.getLogger(RoleBasedUserSearchUtil.class); - @Autowired - XUserService xUserService; + public static Boolean checkRole = true; + public static String userLoginId = ""; + public static String currentPassword = ""; + public static String userRole = ""; - @Autowired - RangerDaoManager daoMgr; + @Autowired + XUserService xUserService; - @Autowired - UserMgr userMgr; + @Autowired + RangerDaoManager daoMgr; - @Autowired - XUserMgr xUserMgr; + @Autowired + UserMgr userMgr; - public static Boolean checkRole = true; - public static String userLoginId = ""; - public static String currentPassword = ""; - public static String userRole = ""; + @Autowired + XUserMgr xUserMgr; - public static void main(String[] args) { - logger.info("RoleBaseUserSearchUtil : main()"); - try { - RoleBasedUserSearchUtil loader = (RoleBasedUserSearchUtil) CLIUtil.getBean(RoleBasedUserSearchUtil.class); - loader.init(); - if (args.length == 3 || args.length == 2) { - userLoginId = args[0]; - currentPassword = args[1]; - if (args.length == 3) { - userRole = args[2]; - if (!StringUtils.isBlank(userRole)) { - userRole = userRole.toUpperCase(); - if (!RangerConstants.VALID_USER_ROLE_LIST.contains(userRole)) { - System.out.println("Invalid UserRole. Exiting!!!"); - logger.info("Invalid UserRole. Exiting!!!"); - System.exit(1); - } else { - checkRole = false; - } - } - } - if (StringUtils.isBlank(userLoginId)) { - System.out.println("Invalid login ID. Exiting!!!"); - logger.info("Invalid login ID. Exiting!!!"); - System.exit(1); - } - if (StringUtils.isBlank(currentPassword)) { - System.out.println("Invalid current password. Exiting!!!"); - logger.info("Invalid current password. Exiting!!!"); - System.exit(1); - } - while (loader.isMoreToProcess()) { - loader.load(); - } - logger.info("Load complete. Exiting!!!"); - System.exit(0); - } else { - System.out.println("RoleBaseUserSearchUtil: Incorrect Arguments \n Usage: \n "); - logger.error("RoleBaseUserSearchUtil: Incorrect Arguments \n Usage: \n "); - System.exit(1); - } - } catch (Exception e) { - logger.error("Error loading", e); - System.exit(1); + public static void main(String[] args) { + logger.info("RoleBaseUserSearchUtil : main()"); + + try { + RoleBasedUserSearchUtil loader = (RoleBasedUserSearchUtil) CLIUtil.getBean(RoleBasedUserSearchUtil.class); + + loader.init(); + + if (args.length == 3 || args.length == 2) { + userLoginId = args[0]; + currentPassword = args[1]; + + if (args.length == 3) { + userRole = args[2]; + + if (!StringUtils.isBlank(userRole)) { + userRole = userRole.toUpperCase(); + + if (!RangerConstants.VALID_USER_ROLE_LIST.contains(userRole)) { + System.out.println("Invalid UserRole. Exiting!!!"); + logger.info("Invalid UserRole. Exiting!!!"); + + System.exit(1); + } else { + checkRole = false; + } + } + } + + if (StringUtils.isBlank(userLoginId)) { + System.out.println("Invalid login ID. Exiting!!!"); + logger.info("Invalid login ID. Exiting!!!"); + + System.exit(1); + } + + if (StringUtils.isBlank(currentPassword)) { + System.out.println("Invalid current password. Exiting!!!"); + logger.info("Invalid current password. Exiting!!!"); + + System.exit(1); + } + + while (loader.isMoreToProcess()) { + loader.load(); + } + + logger.info("Load complete. Exiting!!!"); + + System.exit(0); + } else { + System.out.println("RoleBaseUserSearchUtil: Incorrect Arguments \n Usage: \n "); + logger.error("RoleBaseUserSearchUtil: Incorrect Arguments \n Usage: \n "); + + System.exit(1); } - } + } catch (Exception e) { + logger.error("Error loading", e); - @Override - public void init() throws Exception { - logger.info("==> RoleBaseUserSearchUtil.init()"); + System.exit(1); } + } - @Override - public void printStats() { - } + @Override + public void init() throws Exception { + logger.info("==> RoleBaseUserSearchUtil.init()"); + } - @Override - public void execLoad() { - logger.info("==> RoleBaseUserSearchUtil.execLoad()"); - validateUserAndFetchUserList(); - logger.info("<== RoleBaseUserSearchUtil.execLoad()"); - } + @Override + public void printStats() { + } - public void getUsersBasedOnRole(List userRoleList) { - try { - if (!CollectionUtils.isEmpty(userRoleList) && userRoleList != null) { - Map roleSysAdminMap = new HashMap(); - Map roleAdminAuditorMap = new HashMap(); - Map roleKeyAdminMap = new HashMap(); - Map roleKeyAdminAuditorMap = new HashMap(); - Map roleUserMap = new HashMap(); - for (String userRole : userRoleList) { - List listXXPortalUser = daoMgr.getXXPortalUser().findByRole(userRole); - if (listXXPortalUser != null && !CollectionUtils.isEmpty(listXXPortalUser)) { - if (userRole.equalsIgnoreCase(RangerConstants.ROLE_SYS_ADMIN)) { - for (XXPortalUser xXPortalUser : listXXPortalUser) { - roleSysAdminMap.put(xXPortalUser.getLoginId(),userRole); - } - } else if (userRole.equalsIgnoreCase(RangerConstants.ROLE_ADMIN_AUDITOR)) { - for (XXPortalUser xXPortalUser : listXXPortalUser) { - roleAdminAuditorMap.put(xXPortalUser.getLoginId(),userRole); - } - } else if (userRole.equalsIgnoreCase(RangerConstants.ROLE_KEY_ADMIN)) { - for (XXPortalUser xXPortalUser : listXXPortalUser) { - roleKeyAdminMap.put(xXPortalUser.getLoginId(),userRole); - } - } else if (userRole.equalsIgnoreCase(RangerConstants.ROLE_KEY_ADMIN_AUDITOR)) { - for (XXPortalUser xXPortalUser : listXXPortalUser) { - roleKeyAdminAuditorMap.put(xXPortalUser.getLoginId(),userRole); - } - } else if (userRole.equalsIgnoreCase(RangerConstants.ROLE_USER)) { - for (XXPortalUser xXPortalUser : listXXPortalUser) { - roleUserMap.put(xXPortalUser.getLoginId(),userRole); - } - } - } - } - if (MapUtils.isEmpty(roleSysAdminMap) && MapUtils.isEmpty(roleKeyAdminMap) && MapUtils.isEmpty(roleUserMap) && MapUtils.isEmpty(roleAdminAuditorMap) && MapUtils.isEmpty(roleKeyAdminAuditorMap)) { - System.out.println("users with given user role are not there"); - logger.error("users with given user role are not there"); - System.exit(1); - } else { - if (!MapUtils.isEmpty(roleSysAdminMap)) { - for(Entry entry : roleSysAdminMap.entrySet()){ - System.out.println(entry.getValue() + " : " + entry.getKey()); - } - } - if (!MapUtils.isEmpty(roleKeyAdminMap)) { - for(Entry entry : roleKeyAdminMap.entrySet()){ - System.out.println(entry.getValue() + " : " + entry.getKey()); - } - } - if (!MapUtils.isEmpty(roleUserMap)) { - for(Entry entry : roleUserMap.entrySet()){ - System.out.println(entry.getValue() + " : " + entry.getKey()); + @Override + public void execLoad() { + logger.info("==> RoleBaseUserSearchUtil.execLoad()"); + + validateUserAndFetchUserList(); + + logger.info("<== RoleBaseUserSearchUtil.execLoad()"); + } + + public void getUsersBasedOnRole(List userRoleList) { + try { + if (!CollectionUtils.isEmpty(userRoleList)) { + Map roleSysAdminMap = new HashMap<>(); + Map roleAdminAuditorMap = new HashMap<>(); + Map roleKeyAdminMap = new HashMap<>(); + Map roleKeyAdminAuditorMap = new HashMap<>(); + Map roleUserMap = new HashMap<>(); + + for (String userRole : userRoleList) { + List listXXPortalUser = daoMgr.getXXPortalUser().findByRole(userRole); + + if (listXXPortalUser != null && !CollectionUtils.isEmpty(listXXPortalUser)) { + if (userRole.equalsIgnoreCase(RangerConstants.ROLE_SYS_ADMIN)) { + for (XXPortalUser xXPortalUser : listXXPortalUser) { + roleSysAdminMap.put(xXPortalUser.getLoginId(), userRole); + } + } else if (userRole.equalsIgnoreCase(RangerConstants.ROLE_ADMIN_AUDITOR)) { + for (XXPortalUser xXPortalUser : listXXPortalUser) { + roleAdminAuditorMap.put(xXPortalUser.getLoginId(), userRole); + } + } else if (userRole.equalsIgnoreCase(RangerConstants.ROLE_KEY_ADMIN)) { + for (XXPortalUser xXPortalUser : listXXPortalUser) { + roleKeyAdminMap.put(xXPortalUser.getLoginId(), userRole); + } + } else if (userRole.equalsIgnoreCase(RangerConstants.ROLE_KEY_ADMIN_AUDITOR)) { + for (XXPortalUser xXPortalUser : listXXPortalUser) { + roleKeyAdminAuditorMap.put(xXPortalUser.getLoginId(), userRole); + } + } else if (userRole.equalsIgnoreCase(RangerConstants.ROLE_USER)) { + for (XXPortalUser xXPortalUser : listXXPortalUser) { + roleUserMap.put(xXPortalUser.getLoginId(), userRole); } } - if (!MapUtils.isEmpty(roleAdminAuditorMap)) { - for(Entry entry : roleAdminAuditorMap.entrySet()){ - System.out.println(entry.getValue() + " : " + entry.getKey()); - } - } - if (!MapUtils.isEmpty(roleKeyAdminAuditorMap)) { - for(Entry entry : roleKeyAdminAuditorMap.entrySet()){ - System.out.println(entry.getValue() + " : " + entry.getKey()); - } - } - if (userRoleList.contains(RangerConstants.ROLE_SYS_ADMIN)) { - System.out.println("ROLE_SYS_ADMIN Total Count : " + roleSysAdminMap.size()); + } + } + + if (MapUtils.isEmpty(roleSysAdminMap) && MapUtils.isEmpty(roleKeyAdminMap) && MapUtils.isEmpty(roleUserMap) && MapUtils.isEmpty(roleAdminAuditorMap) && MapUtils.isEmpty(roleKeyAdminAuditorMap)) { + System.out.println("users with given user role are not there"); + logger.error("users with given user role are not there"); + + System.exit(1); + } else { + if (!MapUtils.isEmpty(roleSysAdminMap)) { + for (Entry entry : roleSysAdminMap.entrySet()) { + System.out.println(entry.getValue() + " : " + entry.getKey()); } - if (userRoleList.contains(RangerConstants.ROLE_KEY_ADMIN)) { - System.out.println("ROLE_KEY_ADMIN Total Count : " + roleKeyAdminMap.size()); + } + + if (!MapUtils.isEmpty(roleKeyAdminMap)) { + for (Entry entry : roleKeyAdminMap.entrySet()) { + System.out.println(entry.getValue() + " : " + entry.getKey()); } - if (userRoleList.contains(RangerConstants.ROLE_USER)) { - System.out.println("ROLE_USER Total Count : " + roleUserMap.size()); + } + + if (!MapUtils.isEmpty(roleUserMap)) { + for (Entry entry : roleUserMap.entrySet()) { + System.out.println(entry.getValue() + " : " + entry.getKey()); } - if (userRoleList.contains(RangerConstants.ROLE_ADMIN_AUDITOR)) { - System.out.println("ROLE_ADMIN_AUDITOR Total Count : " + roleAdminAuditorMap.size()); + } + + if (!MapUtils.isEmpty(roleAdminAuditorMap)) { + for (Entry entry : roleAdminAuditorMap.entrySet()) { + System.out.println(entry.getValue() + " : " + entry.getKey()); } - if (userRoleList.contains(RangerConstants.ROLE_KEY_ADMIN_AUDITOR)) { - System.out.println("ROLE_KEY_ADMIN_AUDITOR Total Count : " + roleKeyAdminAuditorMap.size()); + } + + if (!MapUtils.isEmpty(roleKeyAdminAuditorMap)) { + for (Entry entry : roleKeyAdminAuditorMap.entrySet()) { + System.out.println(entry.getValue() + " : " + entry.getKey()); } + } - int total = roleSysAdminMap.size() + roleKeyAdminMap.size() + roleUserMap.size() + roleAdminAuditorMap.size() + roleKeyAdminAuditorMap.size(); - System.out.println("Total Count : " + total); + if (userRoleList.contains(RangerConstants.ROLE_SYS_ADMIN)) { + System.out.println("ROLE_SYS_ADMIN Total Count : " + roleSysAdminMap.size()); } - } - - } catch (Exception e) { - logger.error("Error getting User's List with the mentioned role: "+ e.getMessage()); - } + + if (userRoleList.contains(RangerConstants.ROLE_KEY_ADMIN)) { + System.out.println("ROLE_KEY_ADMIN Total Count : " + roleKeyAdminMap.size()); + } + + if (userRoleList.contains(RangerConstants.ROLE_USER)) { + System.out.println("ROLE_USER Total Count : " + roleUserMap.size()); + } + + if (userRoleList.contains(RangerConstants.ROLE_ADMIN_AUDITOR)) { + System.out.println("ROLE_ADMIN_AUDITOR Total Count : " + roleAdminAuditorMap.size()); + } + + if (userRoleList.contains(RangerConstants.ROLE_KEY_ADMIN_AUDITOR)) { + System.out.println("ROLE_KEY_ADMIN_AUDITOR Total Count : " + roleKeyAdminAuditorMap.size()); + } + + int total = roleSysAdminMap.size() + roleKeyAdminMap.size() + roleUserMap.size() + roleAdminAuditorMap.size() + roleKeyAdminAuditorMap.size(); + + System.out.println("Total Count : " + total); + } + } + } catch (Exception e) { + logger.error("Error getting User's List with the mentioned role: {}", e.getMessage()); } + } + + public void validateUserAndFetchUserList() { + userLoginId = userLoginId.toLowerCase(); + + XXPortalUser xxPortalUser = daoMgr.getXXPortalUser().findByLoginId(userLoginId); + boolean isUserAuthorized = false; + + if (xxPortalUser != null) { + String currentEncryptedPassword; + String dbPassword = xxPortalUser.getPassword(); + + try { + currentEncryptedPassword = userMgr.encrypt(userLoginId, currentPassword); + + if (currentEncryptedPassword != null && currentEncryptedPassword.equals(dbPassword)) { + VXUser vxUser = xUserService.getXUserByUserName(xxPortalUser.getLoginId()); + + if (vxUser != null) { + List existingRole = (List) vxUser.getUserRoleList(); + List permissionList = daoMgr.getXXModuleDef().findAccessibleModulesByUserId(xxPortalUser.getId(), vxUser.getId()); + + if (permissionList != null && permissionList.contains(RangerConstants.MODULE_USER_GROUPS) && !CollectionUtils.isEmpty(existingRole) && !StringUtils.isBlank(existingRole.get(0))) { + List userRoleList = new ArrayList<>(); + + if (existingRole.get(0).equalsIgnoreCase(RangerConstants.ROLE_USER)) { + userRoleList.add(RangerConstants.ROLE_USER); - public void validateUserAndFetchUserList() { - userLoginId = userLoginId.toLowerCase(); - XXPortalUser xxPortalUser = daoMgr.getXXPortalUser().findByLoginId(userLoginId); - Boolean isUserAuthorized = false; - if (xxPortalUser != null) { - String dbPassword = xxPortalUser.getPassword(); - String currentEncryptedPassword = null; - try { - currentEncryptedPassword = userMgr.encrypt(userLoginId,currentPassword); - if (currentEncryptedPassword != null && currentEncryptedPassword.equals(dbPassword)) { - VXUser vxUser = xUserService.getXUserByUserName(xxPortalUser.getLoginId()); - if (vxUser != null) { - List existingRole = (List) vxUser.getUserRoleList(); - List permissionList = daoMgr.getXXModuleDef().findAccessibleModulesByUserId(xxPortalUser.getId(), vxUser.getId()); - if (permissionList != null && permissionList.contains(RangerConstants.MODULE_USER_GROUPS) && !CollectionUtils.isEmpty(existingRole) && !StringUtils.isBlank(existingRole.get(0))) { - List userRoleList = new ArrayList(); - if (existingRole.get(0).equalsIgnoreCase(RangerConstants.ROLE_USER)) { - userRoleList.add(RangerConstants.ROLE_USER); - if (checkRole) { - getUsersBasedOnRole(userRoleList); - } else if (existingRole.get(0).equalsIgnoreCase(userRole) || userRole.equalsIgnoreCase(RangerConstants.ROLE_USER)) { - getUsersBasedOnRole(userRoleList); - } else { - isUserAuthorized = true; - } - } else if (existingRole.get(0).equalsIgnoreCase(RangerConstants.ROLE_SYS_ADMIN) || existingRole.get(0).equalsIgnoreCase(RangerConstants.ROLE_ADMIN_AUDITOR)) { - if (checkRole) { - userRoleList.add(RangerConstants.ROLE_SYS_ADMIN); - userRoleList.add(RangerConstants.ROLE_ADMIN_AUDITOR); - userRoleList.add(RangerConstants.ROLE_USER); - getUsersBasedOnRole(userRoleList); - } else if (existingRole.get(0).equalsIgnoreCase(userRole) || userRole.equalsIgnoreCase(RangerConstants.ROLE_USER) || userRole.equalsIgnoreCase(RangerConstants.ROLE_ADMIN_AUDITOR) || userRole.equalsIgnoreCase(RangerConstants.ROLE_SYS_ADMIN)) { - userRoleList.add(userRole); - getUsersBasedOnRole(userRoleList); - }else { - isUserAuthorized = true; - } - } else if (existingRole.get(0).equalsIgnoreCase(RangerConstants.ROLE_KEY_ADMIN) || existingRole.get(0).equalsIgnoreCase(RangerConstants.ROLE_KEY_ADMIN_AUDITOR) || userRole.equalsIgnoreCase(RangerConstants.ROLE_USER)) { - if (checkRole) { - userRoleList.add(RangerConstants.ROLE_KEY_ADMIN); - userRoleList.add(RangerConstants.ROLE_KEY_ADMIN_AUDITOR); - userRoleList.add(RangerConstants.ROLE_USER); - getUsersBasedOnRole(userRoleList); - } else if (existingRole.get(0).equalsIgnoreCase(userRole) || userRole.equalsIgnoreCase(RangerConstants.ROLE_USER) || userRole.equalsIgnoreCase(RangerConstants.ROLE_KEY_ADMIN) || userRole.equalsIgnoreCase(RangerConstants.ROLE_KEY_ADMIN_AUDITOR)) { - userRoleList.add(userRole); - getUsersBasedOnRole(userRoleList); - } else { - isUserAuthorized = true; - } + if (checkRole) { + getUsersBasedOnRole(userRoleList); + } else if (existingRole.get(0).equalsIgnoreCase(userRole) || userRole.equalsIgnoreCase(RangerConstants.ROLE_USER)) { + getUsersBasedOnRole(userRoleList); + } else { + isUserAuthorized = true; } - if (isUserAuthorized == true) { - System.out.println("user is not authorized to fetch this list"); - logger.error("user is not authorized to fetch this list"); - System.exit(1); + } else if (existingRole.get(0).equalsIgnoreCase(RangerConstants.ROLE_SYS_ADMIN) || existingRole.get(0).equalsIgnoreCase(RangerConstants.ROLE_ADMIN_AUDITOR)) { + if (checkRole) { + userRoleList.add(RangerConstants.ROLE_SYS_ADMIN); + userRoleList.add(RangerConstants.ROLE_ADMIN_AUDITOR); + userRoleList.add(RangerConstants.ROLE_USER); + + getUsersBasedOnRole(userRoleList); + } else if (existingRole.get(0).equalsIgnoreCase(userRole) || userRole.equalsIgnoreCase(RangerConstants.ROLE_USER) || userRole.equalsIgnoreCase(RangerConstants.ROLE_ADMIN_AUDITOR) || userRole.equalsIgnoreCase(RangerConstants.ROLE_SYS_ADMIN)) { + userRoleList.add(userRole); + + getUsersBasedOnRole(userRoleList); + } else { + isUserAuthorized = true; } - } else { - System.out.println("user permission denied"); - logger.error("user permission denied"); + } else if (existingRole.get(0).equalsIgnoreCase(RangerConstants.ROLE_KEY_ADMIN) || existingRole.get(0).equalsIgnoreCase(RangerConstants.ROLE_KEY_ADMIN_AUDITOR) || userRole.equalsIgnoreCase(RangerConstants.ROLE_USER)) { + if (checkRole) { + userRoleList.add(RangerConstants.ROLE_KEY_ADMIN); + userRoleList.add(RangerConstants.ROLE_KEY_ADMIN_AUDITOR); + userRoleList.add(RangerConstants.ROLE_USER); + + getUsersBasedOnRole(userRoleList); + } else if (existingRole.get(0).equalsIgnoreCase(userRole) || userRole.equalsIgnoreCase(RangerConstants.ROLE_USER) || userRole.equalsIgnoreCase(RangerConstants.ROLE_KEY_ADMIN) || userRole.equalsIgnoreCase(RangerConstants.ROLE_KEY_ADMIN_AUDITOR)) { + userRoleList.add(userRole); + + getUsersBasedOnRole(userRoleList); + } else { + isUserAuthorized = true; + } + } + if (isUserAuthorized) { + System.out.println("user is not authorized to fetch this list"); + logger.error("user is not authorized to fetch this list"); + System.exit(1); } + } else { + System.out.println("user permission denied"); + logger.error("user permission denied"); + + System.exit(1); } - } else { - System.out.println("Invalid user password"); - logger.error("Invalid user password"); - System.exit(1); } - } catch (Exception e) { - logger.error("Getting User's List with the mentioned role failure. Detail: \n",e); + } else { + System.out.println("Invalid user password"); + logger.error("Invalid user password"); + System.exit(1); } - } else { - System.out.println("User does not exist in DB!!"); - logger.error("User does not exist in DB"); + } catch (Exception e) { + logger.error("Getting User's List with the mentioned role failure. Detail: \n", e); + System.exit(1); } + } else { + System.out.println("User does not exist in DB!!"); + logger.error("User does not exist in DB"); + + System.exit(1); } -} \ No newline at end of file + } +} diff --git a/security-admin/src/main/java/org/apache/ranger/patch/cliutil/TrxLogV2MigrationUtil.java b/security-admin/src/main/java/org/apache/ranger/patch/cliutil/TrxLogV2MigrationUtil.java index bb8ba0b0b9..be582199a7 100644 --- a/security-admin/src/main/java/org/apache/ranger/patch/cliutil/TrxLogV2MigrationUtil.java +++ b/security-admin/src/main/java/org/apache/ranger/patch/cliutil/TrxLogV2MigrationUtil.java @@ -16,17 +16,6 @@ */ package org.apache.ranger.patch.cliutil; -import java.sql.Timestamp; -import java.text.SimpleDateFormat; -import java.time.LocalDate; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Date; -import java.util.Iterator; -import java.util.List; -import java.util.concurrent.atomic.AtomicLong; -import java.util.concurrent.atomic.AtomicReference; - import org.apache.commons.collections.CollectionUtils; import org.apache.ranger.db.RangerDaoManager; import org.apache.ranger.entity.XXTrxLog; @@ -47,15 +36,22 @@ import org.springframework.transaction.support.TransactionCallback; import org.springframework.transaction.support.TransactionTemplate; +import java.sql.Timestamp; +import java.text.SimpleDateFormat; +import java.time.LocalDate; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Date; +import java.util.Iterator; +import java.util.List; +import java.util.concurrent.atomic.AtomicLong; +import java.util.concurrent.atomic.AtomicReference; + @Component public class TrxLogV2MigrationUtil extends BaseLoader { private static final Logger logger = LoggerFactory.getLogger(TrxLogV2MigrationUtil.class); - private final Stats stats; - private TransactionTemplate txTemplate; - private Iterator trxIdIter = Collections.emptyIterator(); - private int commitBatchSize = 25; - + private final Stats stats; @Autowired RangerDaoManager daoMgr; @@ -64,11 +60,16 @@ public class TrxLogV2MigrationUtil extends BaseLoader { @Qualifier(value = "transactionManager") PlatformTransactionManager txManager; + private TransactionTemplate txTemplate; + private Iterator trxIdIter = Collections.emptyIterator(); + private int commitBatchSize = 25; + + public TrxLogV2MigrationUtil() { + this.stats = new Stats(); + } public static void main(String[] args) { - if (logger.isDebugEnabled()) { - logger.info("TrxLogV2MigrationUtil: main()"); - } + logger.info("TrxLogV2MigrationUtil: main()"); try { TrxLogV2MigrationUtil loader = (TrxLogV2MigrationUtil) CLIUtil.getBean(TrxLogV2MigrationUtil.class); @@ -89,10 +90,6 @@ public static void main(String[] args) { } } - public TrxLogV2MigrationUtil() { - this.stats = new Stats(); - } - @Override public void init() throws Exception { txTemplate = new TransactionTemplate(txManager); @@ -100,6 +97,11 @@ public void init() throws Exception { txTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); } + @Override + public void printStats() { + stats.logStats(); + } + @Override public void execLoad() { logger.info("==> TrxLogV2MigrationUtil.execLoad()"); @@ -113,11 +115,6 @@ public void execLoad() { logger.info("<== TrxLogV2MigrationUtil.execLoad(): migration completed. Transaction counts(total: {}, migrated: {}, already-migrated: {}, failed: {})", stats.totalCount, stats.migratedCount, stats.alreadyMigratedCount, stats.failedCount); } - @Override - public void printStats() { - stats.logStats(); - } - private void migrateTrxLogs() throws Exception { logger.info("==> TrxLogV2MigrationUtil.migrateTrxLogs()"); @@ -135,10 +132,7 @@ private void migrateTrxLogs() throws Exception { Date startDate = Timestamp.valueOf(LocalDate.now().minusDays(trxRetentionDays).atStartOfDay()); Date endDate = Timestamp.valueOf(LocalDate.now().atTime(23, 59, 59, 999999999)); - uniqueTrxIdList = daoMgr.getEntityManager().createNamedQuery("XXTrxLog.findDistinctTrxIdsByTimeInterval", String.class) - .setParameter("startDate", startDate) - .setParameter("endDate", endDate) - .getResultList(); + uniqueTrxIdList = daoMgr.getEntityManager().createNamedQuery("XXTrxLog.findDistinctTrxIdsByTimeInterval", String.class).setParameter("startDate", startDate).setParameter("endDate", endDate).getResultList(); } trxIdIter = uniqueTrxIdList.iterator(); @@ -165,16 +159,12 @@ private void migrateTrxLogs() throws Exception { } private void migrateTrxLog(String trxId) { - if (logger.isDebugEnabled()) { - logger.debug("==> TrxLogV2MigrationUtil.createTransactionLogByTrxId()"); - } + logger.debug("==> TrxLogV2MigrationUtil.createTransactionLogByTrxId()"); List trxLogsV2 = daoMgr.getXXTrxLogV2().findByTransactionId(trxId); if (CollectionUtils.isNotEmpty(trxLogsV2)) { - if (logger.isDebugEnabled()) { - logger.debug("transaction({}): already migrated to v2", trxId); - } + logger.debug("transaction({}): already migrated to v2", trxId); stats.incrAlreadyMigratedCount(); } else { @@ -191,23 +181,17 @@ private void migrateTrxLog(String trxId) { createTrxLog(firstTrxLog, objChangeInfo); - if (logger.isDebugEnabled()) { - logger.debug("transaction({}): migrated {} v1 records", trxId, v1TrxLogs.size()); - } + logger.debug("transaction({}): migrated {} v1 records", trxId, v1TrxLogs.size()); stats.incrMigratedCount(firstTrxLog.getId(), firstTrxLog.getCreateTime()); } else { - if (logger.isDebugEnabled()) { - logger.debug("transaction({}): no v1 records found", trxId); - } + logger.debug("transaction({}): no v1 records found", trxId); stats.incrFailedCount(); } } - if (logger.isDebugEnabled()) { - logger.debug("<== TrxLogV2MigrationUtil.createTransactionLogByTrxId()"); - } + logger.debug("<== TrxLogV2MigrationUtil.createTransactionLogByTrxId()"); } private List getV1TrxLogs(String trxId) { @@ -302,8 +286,7 @@ private static VXTrxLog toVXTrxLog(XXTrxLog trxLog) { } private static XXTrxLogV2 toDBObject(VXTrxLogV2 vObj) { - XXTrxLogV2 ret = new XXTrxLogV2(vObj.getObjectClassType(), vObj.getObjectId(), vObj.getObjectName(), - vObj.getParentObjectClassType(), vObj.getParentObjectId(), vObj.getParentObjectName(), vObj.getAction()); + XXTrxLogV2 ret = new XXTrxLogV2(vObj.getObjectClassType(), vObj.getObjectId(), vObj.getObjectName(), vObj.getParentObjectClassType(), vObj.getParentObjectId(), vObj.getParentObjectName(), vObj.getAction()); ret.setCreateTime(vObj.getCreateDate()); ret.setChangeInfo(toJson(vObj.getChangeInfo())); @@ -333,33 +316,15 @@ private static long toLong(Object obj) { return obj instanceof Long ? ((Number) obj).longValue() : 0L; } - class LogMigrationThread extends Thread { - @Override - public void run() { - List trxIds = new ArrayList<>(commitBatchSize); - - for (fetchNextBatch(trxIds); !trxIds.isEmpty(); fetchNextBatch(trxIds)) { - txTemplate.execute((TransactionCallback) status -> { - for (String trxId : trxIds) { - migrateTrxLog(trxId); - } - - return null; - }); - } - } - } - public static class Stats { - private long totalCount; private final AtomicLong migratedCount = new AtomicLong(); private final AtomicLong failedCount = new AtomicLong(); private final AtomicLong alreadyMigratedCount = new AtomicLong(); private final AtomicLong processedCount = new AtomicLong(); private final AtomicReference lastTrxId = new AtomicReference<>(); private final AtomicReference lastTrxDate = new AtomicReference<>(); - private final ThreadLocal dateFormatter = ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyy/MM/dd HH:mm:ss Z")); + private long totalCount; public void incrMigratedCount(Long trxId, Date trxDate) { migratedCount.incrementAndGet(); @@ -381,19 +346,35 @@ public void incrAlreadyMigratedCount() { incrProcessedCount(); } + public void logStats() { + logger.info("PROGRESS: {} of {} transactions processed. Last migrated transaction(id={}, time={}). Counts(migrated: {}, failed: {}, already-migrated: {})", processedCount.get(), totalCount, lastTrxId.get(), toString(lastTrxDate.get()), migratedCount.get(), failedCount.get(), alreadyMigratedCount.get()); + } + private void incrProcessedCount() { if (processedCount.incrementAndGet() % 1000 == 0) { logStats(); } } - public void logStats() { - logger.info("PROGRESS: {} of {} transactions processed. Last migrated transaction(id={}, time={}). Counts(migrated: {}, failed: {}, already-migrated: {})", - processedCount.get(), totalCount, lastTrxId.get(), toString(lastTrxDate.get()), migratedCount.get(), failedCount.get(), alreadyMigratedCount.get()); - } - private String toString(Date date) { return date != null ? dateFormatter.get().format(date) : null; } } + + class LogMigrationThread extends Thread { + @Override + public void run() { + List trxIds = new ArrayList<>(commitBatchSize); + + for (fetchNextBatch(trxIds); !trxIds.isEmpty(); fetchNextBatch(trxIds)) { + txTemplate.execute((TransactionCallback) status -> { + for (String trxId : trxIds) { + migrateTrxLog(trxId); + } + + return null; + }); + } + } + } } diff --git a/security-admin/src/main/java/org/apache/ranger/patch/cliutil/UpdateUserAndGroupNamesInJson.java b/security-admin/src/main/java/org/apache/ranger/patch/cliutil/UpdateUserAndGroupNamesInJson.java index 781404c4ad..813084e72c 100644 --- a/security-admin/src/main/java/org/apache/ranger/patch/cliutil/UpdateUserAndGroupNamesInJson.java +++ b/security-admin/src/main/java/org/apache/ranger/patch/cliutil/UpdateUserAndGroupNamesInJson.java @@ -6,7 +6,7 @@ * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -17,10 +17,6 @@ package org.apache.ranger.patch.cliutil; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang.StringUtils; import org.apache.ranger.authorization.utils.JsonUtils; @@ -49,408 +45,451 @@ import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Component; import org.springframework.transaction.PlatformTransactionManager; -import org.springframework.transaction.TransactionStatus; -import org.springframework.transaction.support.TransactionCallback; import org.springframework.transaction.support.TransactionTemplate; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + /** - * Update Ranger policy JSON string with actual user/group name value after + * Update Ranger policy JSON string with actual user/group name value after * user/group name case is converted via usersync. * This patch shall also update the user/group names in security zone schema. */ @Component public class UpdateUserAndGroupNamesInJson extends BaseLoader { - private static final Logger logger = LoggerFactory.getLogger(UpdateUserAndGroupNamesInJson.class); - - @Autowired - RangerDaoManager daoMgr; - - @Autowired - ServiceDBStore svcStore; - - @Autowired - @Qualifier(value = "transactionManager") - PlatformTransactionManager txManager; - - @Autowired - PolicyRefUpdater policyRefUpdater; - - @Autowired - RangerSearchUtil searchUtil; - - @Autowired - SecurityZoneDBStore securityZoneStore; - - public static void main(String[] args) { - logger.info("main()"); - try { - UpdateUserAndGroupNamesInJson loader = (UpdateUserAndGroupNamesInJson) CLIUtil.getBean(UpdateUserAndGroupNamesInJson.class); - loader.init(); - while (loader.isMoreToProcess()) { - loader.load(); - } - logger.info("Load complete. Exiting!!!"); - System.exit(0); - } catch (Exception e) { - logger.error("Error loading UpdateUserAndGroupNamesInJson Utility", e); - System.exit(1); - } - } - - @Override - public void init() throws Exception { - - } - - @Override - public void execLoad() { - logger.info("==> UpdateUserAndGroupNamesInJson.execLoad()"); - try { - RangerPolicyRetriever policyRetriever = new RangerPolicyRetriever(daoMgr, txManager); - Map usersInDB = policyRetriever.getAllUsers(); - Map groupsInDB = policyRetriever.getAllGroups(); - updateUserAndGroupNamesInPolicyJson(policyRetriever, usersInDB, groupsInDB); - updateRangerSecurityZoneJson(usersInDB, groupsInDB); - } catch (Exception e) { - logger.error("Error while UpdateUserAndGroupNamesInJson()", e); - System.exit(1); - } - logger.info("<== UpdateUserAndGroupNamesInJson.execLoad()"); - } - - @Override - public void printStats() { - logger.info("UpdateUserAndGroupNamesInJson data "); - } - - //Update user and group name in policy json - private void updateUserAndGroupNamesInPolicyJson(RangerPolicyRetriever policyRetriever, Map usersInDB, Map groupsInDB) throws Exception { - logger.info("==> updateUserAndGroupNamesInPolicyJson() "); - List allServices = svcStore.getServices(new SearchFilter()); - if (CollectionUtils.isNotEmpty(allServices)) { - for (RangerService service : allServices) { - XXService dbService = daoMgr.getXXService().getById(service.getId()); - TransactionTemplate txTemplate = new TransactionTemplate(txManager); - logger.info("==> Update Policies of service(name=" + dbService.getName() + ")"); - List policies = policyRetriever.getServicePolicies(dbService); - if (CollectionUtils.isNotEmpty(policies)) { - for (XXPolicy xPolicy : policies) { - if (xPolicy != null && !StringUtil.isEmpty(xPolicy.getPolicyText())) { - //logger.info("existingPolicyText:" + xPolicy.getPolicyText()); - RangerPolicy rangerPolicy = JsonUtils.jsonToObject(xPolicy.getPolicyText(), RangerPolicy.class); - - updatePolicyItemUsersAndGroups(rangerPolicy.getPolicyItems(), usersInDB, groupsInDB); - updatePolicyItemUsersAndGroups(rangerPolicy.getDenyPolicyItems(), usersInDB, groupsInDB); - updatePolicyItemUsersAndGroups(rangerPolicy.getAllowExceptions(), usersInDB, groupsInDB); - updatePolicyItemUsersAndGroups(rangerPolicy.getDenyExceptions(), usersInDB, groupsInDB); - updatePolicyItemUsersAndGroups(rangerPolicy.getDataMaskPolicyItems(), usersInDB, groupsInDB); - updatePolicyItemUsersAndGroups(rangerPolicy.getRowFilterPolicyItems(), usersInDB, groupsInDB); - - String updatedPolicyText = JsonUtils.objectToJson(rangerPolicy); - xPolicy.setPolicyText(updatedPolicyText); - //logger.info("updatedPolicyText:" + updatedPolicyText); - PolicyUpdaterThread updaterThread = new PolicyUpdaterThread(txTemplate, xPolicy); - updaterThread.setDaemon(true); - updaterThread.start(); - updaterThread.join(); - - String errorMsg = updaterThread.getErrorMsg(); - if (StringUtils.isNotEmpty(errorMsg)) { - throw new Exception(errorMsg); - } - } - } - } - } - } - logger.info("<== updateUserAndGroupNamesInPolicyJson() "); - } - - private void updatePolicyItemUsersAndGroups(List policyItems, Map usersInDB, Map groupsInDB) throws Exception { - for (RangerPolicyItem rangerPolicyItem : policyItems) { - List policyJsonUsers = rangerPolicyItem.getUsers(); - for (int i = 0; i < policyJsonUsers.size(); i++) { - if (usersInDB.containsKey(policyJsonUsers.get(i).toLowerCase())) { - policyJsonUsers.set(i, usersInDB.get(policyJsonUsers.get(i).toLowerCase())); - } - } - List policyJsonGroups = rangerPolicyItem.getGroups(); - for (int i = 0; i < policyJsonGroups.size(); i++) { - if (groupsInDB.containsKey(policyJsonGroups.get(i).toLowerCase())) { - policyJsonGroups.set(i, groupsInDB.get(policyJsonGroups.get(i).toLowerCase())); - } - } - } - } - - //Update user and group name in security json - private void updateRangerSecurityZoneJson(Map usersInDB, Map groupsInDB) { - SearchFilter filter = new SearchFilter(); - try { - List securityZones = securityZoneStore.getSecurityZones(filter); - TransactionTemplate txTemplate = new TransactionTemplate(txManager); - for (RangerSecurityZone securityZone : securityZones) { - updateRangerSecurityZoneUsersAndGroups(securityZone.getAdminUserGroups(), groupsInDB); - updateRangerSecurityZoneUsersAndGroups(securityZone.getAdminUsers(), usersInDB); - updateRangerSecurityZoneUsersAndGroups(securityZone.getAuditUserGroups(), groupsInDB); - updateRangerSecurityZoneUsersAndGroups(securityZone.getAuditUsers(), usersInDB); - - SecurityZoneUpdaterThread updaterThread = new SecurityZoneUpdaterThread(txTemplate, securityZone); - updaterThread.setDaemon(true); - updaterThread.start(); - updaterThread.join(); - - String errorMsg = updaterThread.getErrorMsg(); - if (StringUtils.isNotEmpty(errorMsg)) { - throw new Exception(errorMsg); - } - } - } catch (Exception ex) { - logger.error("Error in updateRangerSecurityZoneJson()", ex); - } - } - - private List updateRangerSecurityZoneUsersAndGroups(List userOrGroups, Map usersOrGroupsInDB) throws Exception { - for (int i = 0; i < userOrGroups.size(); i++) { - if (usersOrGroupsInDB.containsKey(userOrGroups.get(i).toLowerCase())) { - userOrGroups.set(i, usersOrGroupsInDB.get(userOrGroups.get(i).toLowerCase())); - } - } - return userOrGroups; - } - - private class PolicyUpdaterThread extends Thread { - final TransactionTemplate txTemplate; - final XXPolicy policy; - String errorMsg; - - PolicyUpdaterThread(TransactionTemplate txTemplate, final XXPolicy policy) { - this.txTemplate = txTemplate; - this.policy = policy; - this.errorMsg = null; - } - - public String getErrorMsg() { - return errorMsg; - } - - @Override - public void run() { - errorMsg = txTemplate.execute(new TransactionCallback() { - @Override - public String doInTransaction(TransactionStatus status) { - String ret = null; - try { - updatePolicyJson(policy); - } catch (Throwable e) { - logger.error("updatePolicyJson failed for policy:[" + policy + "]", e); - ret = e.toString(); - } - return ret; - } - }); - } - } - - private class SecurityZoneUpdaterThread extends Thread { - final TransactionTemplate txTemplate; - RangerSecurityZone rangerSecurityZone; - String errorMsg; - - SecurityZoneUpdaterThread(TransactionTemplate txTemplate, RangerSecurityZone rangerSecurityZone) { - this.txTemplate = txTemplate; - this.errorMsg = null; - this.rangerSecurityZone = rangerSecurityZone; - } - - public String getErrorMsg() { - return errorMsg; - } - - @Override - public void run() { - errorMsg = txTemplate.execute(new TransactionCallback() { - @Override - public String doInTransaction(TransactionStatus status) { - String ret = null; - try { - updateSecurityZone(rangerSecurityZone); - } catch (Throwable e) { - logger.error("updateSecurityZone failed for zone:[" + rangerSecurityZone.getId() + "]", e); - ret = e.toString(); - } - return ret; - } - }); - } - } - - private void updatePolicyJson(XXPolicy policy) throws Exception { - logger.info("==> updatePolicyJson(id=" + policy.getId() + ")"); - XXPolicyDao policyDao = daoMgr.getXXPolicy(); - policyDao.update(policy); - logger.info("<== updatePolicyJson(id=" + policy.getId() + ")"); - } - - private void updateSecurityZone(RangerSecurityZone rangerSecurityZone) throws Exception { - logger.info("==> updateSecurityZone(id=" + rangerSecurityZone.getId() + ")"); - securityZoneStore.updateSecurityZoneById(rangerSecurityZone); - logger.info("<== updateSecurityZone(id=" + rangerSecurityZone.getId() + ")"); - } - - static private class RangerPolicyRetriever { - static final Logger LOG = LoggerFactory.getLogger(RangerPolicyRetriever.class); - static final Logger PERF_LOG = RangerPerfTracer.getPerfLogger("db.RangerPolicyRetriever"); - private final RangerDaoManager daoMgr; - private final PlatformTransactionManager txManager; - private final TransactionTemplate txTemplate; - - RangerPolicyRetriever(RangerDaoManager daoMgr, PlatformTransactionManager txManager) { - this.daoMgr = daoMgr; - this.txManager = txManager; - if (this.txManager != null) { - this.txTemplate = new TransactionTemplate(this.txManager); - this.txTemplate.setReadOnly(true); - } else { - this.txTemplate = null; - } - } - - private class PolicyLoaderThread extends Thread { - final TransactionTemplate txTemplate; - final XXService xService; - List policies; - - PolicyLoaderThread(TransactionTemplate txTemplate, final XXService xService) { - this.txTemplate = txTemplate; - this.xService = xService; - } - - public List getPolicies() { - return policies; - } - - @Override - public void run() { - txTemplate.setReadOnly(true); - policies = txTemplate.execute(new TransactionCallback>() { - @Override - public List doInTransaction(TransactionStatus status) { - RetrieverContext ctx = new RetrieverContext(xService); - return ctx.getAllPolicies(); - } - }); - } - } - - public List getServicePolicies(final XXService xService) throws InterruptedException { - String serviceName = xService == null ? null : xService.getName(); - Long serviceId = xService == null ? null : xService.getId(); - if (LOG.isDebugEnabled()) { - LOG.debug("==> RangerPolicyRetriever.getServicePolicies(serviceName=" + serviceName + ", serviceId=" + serviceId + ")"); - } - List ret = null; - RangerPerfTracer perf = null; - if (RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { - perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "RangerPolicyRetriever.getServicePolicies(serviceName=" + serviceName + ",serviceId=" + serviceId + ")"); - } - - if (xService != null) { - if (txTemplate == null) { - if (LOG.isDebugEnabled()) { - LOG.debug("Transaction Manager is null; Retrieving policies in the existing transaction"); - } - RetrieverContext ctx = new RetrieverContext(xService); - ret = ctx.getAllPolicies(); - } else { - if (LOG.isDebugEnabled()) { - LOG.debug("Retrieving policies in a new, read-only transaction"); - } - PolicyLoaderThread t = new PolicyLoaderThread(txTemplate, xService); - t.start(); - t.join(); - ret = t.getPolicies(); - } - } else { - if (LOG.isDebugEnabled()) { - LOG.debug("RangerPolicyRetriever.getServicePolicies(xService=" + xService + "): invalid parameter"); - } - } - RangerPerfTracer.log(perf); - if (LOG.isDebugEnabled()) { - LOG.debug("<== RangerPolicyRetriever.getServicePolicies(serviceName=" + serviceName + ", serviceId=" + serviceId + "): policyCount=" + (ret == null ? 0 : ret.size())); - } - return ret; - } - - public Map getAllUsers() throws InterruptedException { - if (LOG.isDebugEnabled()) { - LOG.debug("==> RangerPolicyRetriever.getAllUsers()"); - } - Map ret = null; - RangerPerfTracer perf = null; - if (RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { - perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "RangerPolicyRetriever.getAllUsers()"); - } - if (LOG.isDebugEnabled()) { - LOG.debug("Transaction Manager is null; Retrieving users in the existing transaction"); - } - RetrieverContext ctx = new RetrieverContext(null); - ret = ctx.getAllUsersMap(); - RangerPerfTracer.log(perf); - if (LOG.isDebugEnabled()) { - LOG.debug("<== RangerPolicyRetriever.getAllUsers(): userCount=" + (ret == null ? 0 : ret.size())); - } - return ret; - } - - public Map getAllGroups() throws InterruptedException { - if (LOG.isDebugEnabled()) { - LOG.debug("==> RangerPolicyRetriever.getAllGroups()"); - } - Map ret = null; - RangerPerfTracer perf = null; - if (RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { - perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "RangerPolicyRetriever.getAllGroups()"); - } - if (LOG.isDebugEnabled()) { - LOG.debug("Transaction Manager is null; Retrieving groups in the existing transaction"); - } - RetrieverContext ctx = new RetrieverContext(null); - ret = ctx.getAllGroupsMap(); - RangerPerfTracer.log(perf); - if (LOG.isDebugEnabled()) { - LOG.debug("<== RangerPolicyRetriever.getAllGroups(): groupCount=" + (ret == null ? 0 : ret.size())); - } - return ret; - } - - class RetrieverContext { - final XXService service; - RetrieverContext(XXService xService) { - this.service = xService; - } - List getAllPolicies() { - Long serviceId = service == null ? 0 : service.getId(); - List xPolicies = daoMgr.getXXPolicy().findByServiceId(serviceId); - return xPolicies; - } - Map getAllUsersMap() { - List xXusers = daoMgr.getXXUser().getAll(); - Map usersMap = new HashMap(); - for (XXUser xxUser : xXusers) { - usersMap.put(xxUser.getName().toLowerCase(), xxUser.getName()); - } - return usersMap; - } - Map getAllGroupsMap() { - List xXgroups = daoMgr.getXXGroup().getAll(); - Map groupsMap = new HashMap(); - for (XXGroup xxGroup : xXgroups) { - groupsMap.put(xxGroup.getName().toLowerCase(), xxGroup.getName()); - } - return groupsMap; - } - } - } + private static final Logger logger = LoggerFactory.getLogger(UpdateUserAndGroupNamesInJson.class); + + @Autowired + RangerDaoManager daoMgr; + + @Autowired + ServiceDBStore svcStore; + + @Autowired + @Qualifier(value = "transactionManager") + PlatformTransactionManager txManager; + + @Autowired + PolicyRefUpdater policyRefUpdater; + + @Autowired + RangerSearchUtil searchUtil; + + @Autowired + SecurityZoneDBStore securityZoneStore; + + public static void main(String[] args) { + logger.info("main()"); + try { + UpdateUserAndGroupNamesInJson loader = (UpdateUserAndGroupNamesInJson) CLIUtil.getBean(UpdateUserAndGroupNamesInJson.class); + + loader.init(); + + while (loader.isMoreToProcess()) { + loader.load(); + } + + logger.info("Load complete. Exiting!!!"); + + System.exit(0); + } catch (Exception e) { + logger.error("Error loading UpdateUserAndGroupNamesInJson Utility", e); + + System.exit(1); + } + } + + @Override + public void init() throws Exception { + } + + @Override + public void printStats() { + logger.info("UpdateUserAndGroupNamesInJson data "); + } + + @Override + public void execLoad() { + logger.info("==> UpdateUserAndGroupNamesInJson.execLoad()"); + try { + RangerPolicyRetriever policyRetriever = new RangerPolicyRetriever(daoMgr, txManager); + Map usersInDB = policyRetriever.getAllUsers(); + Map groupsInDB = policyRetriever.getAllGroups(); + + updateUserAndGroupNamesInPolicyJson(policyRetriever, usersInDB, groupsInDB); + + updateRangerSecurityZoneJson(usersInDB, groupsInDB); + } catch (Exception e) { + logger.error("Error while UpdateUserAndGroupNamesInJson()", e); + + System.exit(1); + } + logger.info("<== UpdateUserAndGroupNamesInJson.execLoad()"); + } + + //Update user and group name in policy json + private void updateUserAndGroupNamesInPolicyJson(RangerPolicyRetriever policyRetriever, Map usersInDB, Map groupsInDB) throws Exception { + logger.info("==> updateUserAndGroupNamesInPolicyJson() "); + + List allServices = svcStore.getServices(new SearchFilter()); + + if (CollectionUtils.isNotEmpty(allServices)) { + for (RangerService service : allServices) { + XXService dbService = daoMgr.getXXService().getById(service.getId()); + TransactionTemplate txTemplate = new TransactionTemplate(txManager); + + logger.info("==> Update Policies of service(name={})", dbService.getName()); + + List policies = policyRetriever.getServicePolicies(dbService); + + if (CollectionUtils.isNotEmpty(policies)) { + for (XXPolicy xPolicy : policies) { + if (xPolicy != null && !StringUtil.isEmpty(xPolicy.getPolicyText())) { + //logger.info("existingPolicyText:" + xPolicy.getPolicyText()); + + RangerPolicy rangerPolicy = JsonUtils.jsonToObject(xPolicy.getPolicyText(), RangerPolicy.class); + + updatePolicyItemUsersAndGroups(rangerPolicy.getPolicyItems(), usersInDB, groupsInDB); + updatePolicyItemUsersAndGroups(rangerPolicy.getDenyPolicyItems(), usersInDB, groupsInDB); + updatePolicyItemUsersAndGroups(rangerPolicy.getAllowExceptions(), usersInDB, groupsInDB); + updatePolicyItemUsersAndGroups(rangerPolicy.getDenyExceptions(), usersInDB, groupsInDB); + updatePolicyItemUsersAndGroups(rangerPolicy.getDataMaskPolicyItems(), usersInDB, groupsInDB); + updatePolicyItemUsersAndGroups(rangerPolicy.getRowFilterPolicyItems(), usersInDB, groupsInDB); + + String updatedPolicyText = JsonUtils.objectToJson(rangerPolicy); + + xPolicy.setPolicyText(updatedPolicyText); + + //logger.info("updatedPolicyText:" + updatedPolicyText); + + PolicyUpdaterThread updaterThread = new PolicyUpdaterThread(txTemplate, xPolicy); + + updaterThread.setDaemon(true); + updaterThread.start(); + updaterThread.join(); + + String errorMsg = updaterThread.getErrorMsg(); + + if (StringUtils.isNotEmpty(errorMsg)) { + throw new Exception(errorMsg); + } + } + } + } + } + } + + logger.info("<== updateUserAndGroupNamesInPolicyJson() "); + } + + private void updatePolicyItemUsersAndGroups(List policyItems, Map usersInDB, Map groupsInDB) { + for (RangerPolicyItem rangerPolicyItem : policyItems) { + List policyJsonUsers = rangerPolicyItem.getUsers(); + + for (int i = 0; i < policyJsonUsers.size(); i++) { + if (usersInDB.containsKey(policyJsonUsers.get(i).toLowerCase())) { + policyJsonUsers.set(i, usersInDB.get(policyJsonUsers.get(i).toLowerCase())); + } + } + + List policyJsonGroups = rangerPolicyItem.getGroups(); + + for (int i = 0; i < policyJsonGroups.size(); i++) { + if (groupsInDB.containsKey(policyJsonGroups.get(i).toLowerCase())) { + policyJsonGroups.set(i, groupsInDB.get(policyJsonGroups.get(i).toLowerCase())); + } + } + } + } + + //Update user and group name in security json + private void updateRangerSecurityZoneJson(Map usersInDB, Map groupsInDB) { + SearchFilter filter = new SearchFilter(); + + try { + List securityZones = securityZoneStore.getSecurityZones(filter); + TransactionTemplate txTemplate = new TransactionTemplate(txManager); + + for (RangerSecurityZone securityZone : securityZones) { + updateRangerSecurityZoneUsersAndGroups(securityZone.getAdminUserGroups(), groupsInDB); + updateRangerSecurityZoneUsersAndGroups(securityZone.getAdminUsers(), usersInDB); + updateRangerSecurityZoneUsersAndGroups(securityZone.getAuditUserGroups(), groupsInDB); + updateRangerSecurityZoneUsersAndGroups(securityZone.getAuditUsers(), usersInDB); + + SecurityZoneUpdaterThread updaterThread = new SecurityZoneUpdaterThread(txTemplate, securityZone); + + updaterThread.setDaemon(true); + updaterThread.start(); + updaterThread.join(); + + String errorMsg = updaterThread.getErrorMsg(); + + if (StringUtils.isNotEmpty(errorMsg)) { + throw new Exception(errorMsg); + } + } + } catch (Exception ex) { + logger.error("Error in updateRangerSecurityZoneJson()", ex); + } + } + + private List updateRangerSecurityZoneUsersAndGroups(List userOrGroups, Map usersOrGroupsInDB) { + for (int i = 0; i < userOrGroups.size(); i++) { + if (usersOrGroupsInDB.containsKey(userOrGroups.get(i).toLowerCase())) { + userOrGroups.set(i, usersOrGroupsInDB.get(userOrGroups.get(i).toLowerCase())); + } + } + + return userOrGroups; + } + + private void updatePolicyJson(XXPolicy policy) { + logger.info("==> updatePolicyJson(id={})", policy.getId()); + + XXPolicyDao policyDao = daoMgr.getXXPolicy(); + + policyDao.update(policy); + + logger.info("<== updatePolicyJson(id={})", policy.getId()); + } + + private void updateSecurityZone(RangerSecurityZone rangerSecurityZone) throws Exception { + logger.info("==> updateSecurityZone(id={})", rangerSecurityZone.getId()); + + securityZoneStore.updateSecurityZoneById(rangerSecurityZone); + + logger.info("<== updateSecurityZone(id={})", rangerSecurityZone.getId()); + } + + private static class RangerPolicyRetriever { + static final Logger LOG = LoggerFactory.getLogger(RangerPolicyRetriever.class); + static final Logger PERF_LOG = RangerPerfTracer.getPerfLogger("db.RangerPolicyRetriever"); + + private final RangerDaoManager daoMgr; + private final TransactionTemplate txTemplate; + + RangerPolicyRetriever(RangerDaoManager daoMgr, PlatformTransactionManager txManager) { + this.daoMgr = daoMgr; + + if (txManager != null) { + this.txTemplate = new TransactionTemplate(txManager); + + this.txTemplate.setReadOnly(true); + } else { + this.txTemplate = null; + } + } + + public List getServicePolicies(final XXService xService) throws InterruptedException { + String serviceName = xService == null ? null : xService.getName(); + Long serviceId = xService == null ? null : xService.getId(); + + LOG.debug("==> RangerPolicyRetriever.getServicePolicies(serviceName={}, serviceId={})", serviceName, serviceId); + + List ret = null; + RangerPerfTracer perf = null; + + if (RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { + perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "RangerPolicyRetriever.getServicePolicies(serviceName=" + serviceName + ",serviceId=" + serviceId + ")"); + } + + if (xService != null) { + if (txTemplate == null) { + LOG.debug("Transaction Manager is null; Retrieving policies in the existing transaction"); + + RetrieverContext ctx = new RetrieverContext(xService); + + ret = ctx.getAllPolicies(); + } else { + LOG.debug("Retrieving policies in a new, read-only transaction"); + + PolicyLoaderThread t = new PolicyLoaderThread(txTemplate, xService); + + t.start(); + t.join(); + + ret = t.getPolicies(); + } + } else { + LOG.debug("RangerPolicyRetriever.getServicePolicies(xService={}): invalid parameter", xService); + } + + RangerPerfTracer.log(perf); + + LOG.debug("<== RangerPolicyRetriever.getServicePolicies(serviceName={}, serviceId={}): policyCount={}", serviceName, serviceId, ret == null ? 0 : ret.size()); + + return ret; + } + + public Map getAllUsers() { + LOG.debug("==> RangerPolicyRetriever.getAllUsers()"); + + RangerPerfTracer perf = null; + + if (RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { + perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "RangerPolicyRetriever.getAllUsers()"); + } + + LOG.debug("Transaction Manager is null; Retrieving users in the existing transaction"); + + RetrieverContext ctx = new RetrieverContext(null); + Map ret = ctx.getAllUsersMap(); + + RangerPerfTracer.log(perf); + + LOG.debug("<== RangerPolicyRetriever.getAllUsers(): userCount={}", ret == null ? 0 : ret.size()); + + return ret; + } + + public Map getAllGroups() { + LOG.debug("==> RangerPolicyRetriever.getAllGroups()"); + + RangerPerfTracer perf = null; + + if (RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { + perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "RangerPolicyRetriever.getAllGroups()"); + } + + LOG.debug("Transaction Manager is null; Retrieving groups in the existing transaction"); + + RetrieverContext ctx = new RetrieverContext(null); + Map ret = ctx.getAllGroupsMap(); + + RangerPerfTracer.log(perf); + + LOG.debug("<== RangerPolicyRetriever.getAllGroups(): groupCount={}", ret == null ? 0 : ret.size()); + + return ret; + } + + private class PolicyLoaderThread extends Thread { + final TransactionTemplate txTemplate; + final XXService xService; + List policies; + + PolicyLoaderThread(TransactionTemplate txTemplate, final XXService xService) { + this.txTemplate = txTemplate; + this.xService = xService; + } + + public List getPolicies() { + return policies; + } + + @Override + public void run() { + txTemplate.setReadOnly(true); + + policies = txTemplate.execute(status -> { + RetrieverContext ctx = new RetrieverContext(xService); + + return ctx.getAllPolicies(); + }); + } + } + + class RetrieverContext { + final XXService service; + + RetrieverContext(XXService xService) { + this.service = xService; + } + + List getAllPolicies() { + Long serviceId = service == null ? 0 : service.getId(); + + return daoMgr.getXXPolicy().findByServiceId(serviceId); + } + + Map getAllUsersMap() { + List xXusers = daoMgr.getXXUser().getAll(); + Map usersMap = new HashMap<>(); + + for (XXUser xxUser : xXusers) { + usersMap.put(xxUser.getName().toLowerCase(), xxUser.getName()); + } + + return usersMap; + } + + Map getAllGroupsMap() { + List xXgroups = daoMgr.getXXGroup().getAll(); + Map groupsMap = new HashMap<>(); + + for (XXGroup xxGroup : xXgroups) { + groupsMap.put(xxGroup.getName().toLowerCase(), xxGroup.getName()); + } + + return groupsMap; + } + } + } + + private class PolicyUpdaterThread extends Thread { + final TransactionTemplate txTemplate; + final XXPolicy policy; + String errorMsg; + + PolicyUpdaterThread(TransactionTemplate txTemplate, final XXPolicy policy) { + this.txTemplate = txTemplate; + this.policy = policy; + this.errorMsg = null; + } + + public String getErrorMsg() { + return errorMsg; + } + + @Override + public void run() { + errorMsg = txTemplate.execute(status -> { + String ret = null; + + try { + updatePolicyJson(policy); + } catch (Throwable e) { + logger.error("updatePolicyJson failed for policy:[{}]", policy, e); + + ret = e.toString(); + } + + return ret; + }); + } + } + + private class SecurityZoneUpdaterThread extends Thread { + final TransactionTemplate txTemplate; + RangerSecurityZone rangerSecurityZone; + String errorMsg; + + SecurityZoneUpdaterThread(TransactionTemplate txTemplate, RangerSecurityZone rangerSecurityZone) { + this.txTemplate = txTemplate; + this.errorMsg = null; + this.rangerSecurityZone = rangerSecurityZone; + } + + public String getErrorMsg() { + return errorMsg; + } + + @Override + public void run() { + errorMsg = txTemplate.execute(status -> { + String ret = null; + + try { + updateSecurityZone(rangerSecurityZone); + } catch (Throwable e) { + logger.error("updateSecurityZone failed for zone:[{}]", rangerSecurityZone.getId(), e); + + ret = e.toString(); + } + + return ret; + }); + } + } } diff --git a/security-admin/src/main/java/org/apache/ranger/security/context/RangerAPIList.java b/security-admin/src/main/java/org/apache/ranger/security/context/RangerAPIList.java index 509ed58f46..08fccdb7ef 100755 --- a/security-admin/src/main/java/org/apache/ranger/security/context/RangerAPIList.java +++ b/security-admin/src/main/java/org/apache/ranger/security/context/RangerAPIList.java @@ -21,244 +21,247 @@ * This Class needs to be updated when writing new API in any of the REST. */ public class RangerAPIList { + /** + * List of APIs for AssetREST + */ + public static final String GET_X_ASSET = "AssetREST.getXAsset"; + public static final String CREATE_X_ASSET = "AssetREST.createXAsset"; + public static final String UPDATE_X_ASSET = "AssetREST.updateXAsset"; + public static final String DELETE_X_ASSET = "AssetREST.deleteXAsset"; + public static final String TEST_CONFIG = "AssetREST.testConfig"; + public static final String SEARCH_X_ASSETS = "AssetREST.searchXAssets"; + public static final String COUNT_X_ASSETS = "AssetREST.countXAssets"; + public static final String GET_X_RESOURCE = "AssetREST.getXResource"; + public static final String CREATE_X_RESOURCE = "AssetREST.createXResource"; + public static final String UPDATE_X_RESOURCE = "AssetREST.updateXResource"; + public static final String DELETE_X_RESOURCE = "AssetREST.deleteXResource"; + public static final String SEARCH_X_RESOURCES = "AssetREST.searchXResources"; + public static final String COUNT_X_RESOURCES = "AssetREST.countXResources"; + public static final String GET_X_CRED_STORE = "AssetREST.getXCredentialStore"; + public static final String CREATE_X_CRED_STORE = "AssetREST.createXCredentialStore"; + public static final String UPDATE_X_CRED_STORE = "AssetREST.updateXCredentialStore"; + public static final String DELETE_X_CRED_STORE = "AssetREST.deleteXCredentialStore"; + public static final String SEARCH_X_CRED_STORE = "AssetREST.searchXCredentialStores"; + public static final String COUNT_X_CRED_STORE = "AssetREST.countXCredentialStores"; + public static final String GET_X_RESOURCE_FILE = "AssetREST.getXResourceFile"; + public static final String GET_RESOURCE_JSON = "AssetREST.getResourceJSON"; + public static final String SEARCH_X_POLICY_EXPORT_AUDITS = "AssetREST.searchXPolicyExportAudits"; + public static final String GET_REPORT_LOGS = "AssetREST.getReportLogs"; + public static final String GET_TRANSACTION_REPORT = "AssetREST.getTransactionReport"; + public static final String GET_ACCESS_LOGS = "AssetREST.getAccessLogs"; + public static final String GRANT_PERMISSION = "AssetREST.grantPermission"; + public static final String REVOKE_PERMISSION = "AssetREST.revokePermission"; + public static final String GET_UGSYNC_AUDITS = "AssetREST.getUgsyncAudits"; + public static final String GET_UGSYNC_AUDITS_BY_SYNCSOURCE = "AssetREST.getUgsyncAuditsBySyncSource"; - /** - * List of APIs for AssetREST - */ - public static final String GET_X_ASSET = "AssetREST.getXAsset"; - public static final String CREATE_X_ASSET = "AssetREST.createXAsset"; - public static final String UPDATE_X_ASSET = "AssetREST.updateXAsset"; - public static final String DELETE_X_ASSET = "AssetREST.deleteXAsset"; - public static final String TEST_CONFIG = "AssetREST.testConfig"; - public static final String SEARCH_X_ASSETS = "AssetREST.searchXAssets"; - public static final String COUNT_X_ASSETS = "AssetREST.countXAssets"; - public static final String GET_X_RESOURCE = "AssetREST.getXResource"; - public static final String CREATE_X_RESOURCE = "AssetREST.createXResource"; - public static final String UPDATE_X_RESOURCE = "AssetREST.updateXResource"; - public static final String DELETE_X_RESOURCE = "AssetREST.deleteXResource"; - public static final String SEARCH_X_RESOURCES = "AssetREST.searchXResources"; - public static final String COUNT_X_RESOURCES = "AssetREST.countXResources"; - public static final String GET_X_CRED_STORE = "AssetREST.getXCredentialStore"; - public static final String CREATE_X_CRED_STORE = "AssetREST.createXCredentialStore"; - public static final String UPDATE_X_CRED_STORE = "AssetREST.updateXCredentialStore"; - public static final String DELETE_X_CRED_STORE = "AssetREST.deleteXCredentialStore"; - public static final String SEARCH_X_CRED_STORE = "AssetREST.searchXCredentialStores"; - public static final String COUNT_X_CRED_STORE = "AssetREST.countXCredentialStores"; - public static final String GET_X_RESOURCE_FILE = "AssetREST.getXResourceFile"; - public static final String GET_RESOURCE_JSON = "AssetREST.getResourceJSON"; - public static final String SEARCH_X_POLICY_EXPORT_AUDITS = "AssetREST.searchXPolicyExportAudits"; - public static final String GET_REPORT_LOGS = "AssetREST.getReportLogs"; - public static final String GET_TRANSACTION_REPORT = "AssetREST.getTransactionReport"; - public static final String GET_ACCESS_LOGS = "AssetREST.getAccessLogs"; - public static final String GRANT_PERMISSION = "AssetREST.grantPermission"; - public static final String REVOKE_PERMISSION = "AssetREST.revokePermission"; - public static final String GET_UGSYNC_AUDITS = "AssetREST.getUgsyncAudits"; - public static final String GET_UGSYNC_AUDITS_BY_SYNCSOURCE = "AssetREST.getUgsyncAuditsBySyncSource"; + /** + * List of APIs for ServiceREST + */ + public static final String CREATE_SERVICE_DEF = "ServiceREST.createServiceDef"; + public static final String UPDATE_SERVICE_DEF = "ServiceREST.updateServiceDef"; + public static final String DELETE_SERVICE_DEF = "ServiceREST.deleteServiceDef"; + public static final String GET_SERVICE_DEF = "ServiceREST.getServiceDef"; + public static final String GET_SERVICE_DEF_BY_NAME = "ServiceREST.getServiceDefByName"; + public static final String GET_SERVICE_DEFS = "ServiceREST.getServiceDefs"; + public static final String CREATE_SERVICE = "ServiceREST.createService"; + public static final String UPDATE_SERVICE = "ServiceREST.updateService"; + public static final String DELETE_SERVICE = "ServiceREST.deleteService"; + public static final String GET_SERVICE = "ServiceREST.getService"; + public static final String GET_SERVICE_BY_NAME = "ServiceREST.getServiceByName"; + public static final String GET_SERVICES = "ServiceREST.getServices"; + public static final String COUNT_SERVICES = "ServiceREST.countServices"; + public static final String VALIDATE_CONFIG = "ServiceREST.validateConfig"; + public static final String LOOKUP_RESOURCE = "ServiceREST.lookupResource"; + public static final String GRANT_ACCESS = "ServiceREST.grantAccess"; + public static final String REVOKE_ACCESS = "ServiceREST.revokeAccess"; + public static final String CREATE_POLICY = "ServiceREST.createPolicy"; + public static final String UPDATE_POLICY = "ServiceREST.updatePolicy"; + public static final String DELETE_POLICY = "ServiceREST.deletePolicy"; + public static final String GET_POLICY = "ServiceREST.getPolicy"; + public static final String GET_POLICIES = "ServiceREST.getPolicies"; + public static final String COUNT_POLICIES = "ServiceREST.countPolicies"; + public static final String GET_SERVICE_POLICIES = "ServiceREST.getServicePolicies"; + public static final String GET_SERVICE_POLICIES_BY_NAME = "ServiceREST.getServicePoliciesByName"; + public static final String GET_SERVICE_POLICIES_IF_UPDATED = "ServiceREST.getServicePoliciesIfUpdated"; + public static final String GET_POLICY_FROM_EVENT_TIME = "ServiceREST.getPolicyFromEventTime"; + public static final String GET_POLICY_VERSION_LIST = "ServiceREST.getPolicyVersionList"; + public static final String GET_POLICY_FOR_VERSION_NO = "ServiceREST.getPolicyForVersionNumber"; + public static final String GET_PLUGINS_INFO = "ServiceREST.getPluginsInfo"; + public static final String GET_METRICS_BY_TYPE = "ServiceREST.getMetricByType"; + public static final String DELETE_CLUSTER_SERVICES = "ServiceREST.deleteClusterServices"; - /** - * List of APIs for ServiceREST - */ - public static final String CREATE_SERVICE_DEF = "ServiceREST.createServiceDef"; - public static final String UPDATE_SERVICE_DEF = "ServiceREST.updateServiceDef"; - public static final String DELETE_SERVICE_DEF = "ServiceREST.deleteServiceDef"; - public static final String GET_SERVICE_DEF = "ServiceREST.getServiceDef"; - public static final String GET_SERVICE_DEF_BY_NAME = "ServiceREST.getServiceDefByName"; - public static final String GET_SERVICE_DEFS = "ServiceREST.getServiceDefs"; - public static final String CREATE_SERVICE = "ServiceREST.createService"; - public static final String UPDATE_SERVICE = "ServiceREST.updateService"; - public static final String DELETE_SERVICE = "ServiceREST.deleteService"; - public static final String GET_SERVICE = "ServiceREST.getService"; - public static final String GET_SERVICE_BY_NAME = "ServiceREST.getServiceByName"; - public static final String GET_SERVICES = "ServiceREST.getServices"; - public static final String COUNT_SERVICES = "ServiceREST.countServices"; - public static final String VALIDATE_CONFIG = "ServiceREST.validateConfig"; - public static final String LOOKUP_RESOURCE = "ServiceREST.lookupResource"; - public static final String GRANT_ACCESS = "ServiceREST.grantAccess"; - public static final String REVOKE_ACCESS = "ServiceREST.revokeAccess"; - public static final String CREATE_POLICY = "ServiceREST.createPolicy"; - public static final String UPDATE_POLICY = "ServiceREST.updatePolicy"; - public static final String DELETE_POLICY = "ServiceREST.deletePolicy"; - public static final String GET_POLICY = "ServiceREST.getPolicy"; - public static final String GET_POLICIES = "ServiceREST.getPolicies"; - public static final String COUNT_POLICIES = "ServiceREST.countPolicies"; - public static final String GET_SERVICE_POLICIES = "ServiceREST.getServicePolicies"; - public static final String GET_SERVICE_POLICIES_BY_NAME = "ServiceREST.getServicePoliciesByName"; - public static final String GET_SERVICE_POLICIES_IF_UPDATED = "ServiceREST.getServicePoliciesIfUpdated"; - public static final String GET_POLICY_FROM_EVENT_TIME = "ServiceREST.getPolicyFromEventTime"; - public static final String GET_POLICY_VERSION_LIST = "ServiceREST.getPolicyVersionList"; - public static final String GET_POLICY_FOR_VERSION_NO = "ServiceREST.getPolicyForVersionNumber"; - public static final String GET_PLUGINS_INFO = "ServiceREST.getPluginsInfo"; - public static final String GET_METRICS_BY_TYPE = "ServiceREST.getMetricByType"; - public static final String DELETE_CLUSTER_SERVICES = "ServiceREST.deleteClusterServices"; + /** + * List of APIs for UserREST + */ + public static final String SEARCH_USERS = "UserREST.searchUsers"; + public static final String GET_USER_PROFILE_FOR_USER = "UserREST.getUserProfileForUser"; + public static final String CREATE = "UserREST.create"; + public static final String CREATE_DEFAULT_ACCOUNT_USER = "UserREST.createDefaultAccountUser"; + public static final String UPDATE = "UserREST.update"; + public static final String SET_USER_ROLES = "UserREST.setUserRoles"; + public static final String DEACTIVATE_USER = "UserREST.deactivateUser"; + public static final String GET_USER_PROFILE = "UserREST.getUserProfile"; + public static final String CHANGE_PASSWORD = "UserREST.changePassword"; + public static final String CHANGE_EMAIL_ADDRESS = "UserREST.changeEmailAddress"; - /** - * List of APIs for UserREST - */ - public static final String SEARCH_USERS = "UserREST.searchUsers"; - public static final String GET_USER_PROFILE_FOR_USER = "UserREST.getUserProfileForUser"; - public static final String CREATE = "UserREST.create"; - public static final String CREATE_DEFAULT_ACCOUNT_USER = "UserREST.createDefaultAccountUser"; - public static final String UPDATE = "UserREST.update"; - public static final String SET_USER_ROLES = "UserREST.setUserRoles"; - public static final String DEACTIVATE_USER = "UserREST.deactivateUser"; - public static final String GET_USER_PROFILE = "UserREST.getUserProfile"; - public static final String CHANGE_PASSWORD = "UserREST.changePassword"; - public static final String CHANGE_EMAIL_ADDRESS = "UserREST.changeEmailAddress"; + /** + * List of APIs for XAuditREST + */ + public static final String GET_X_TRX_LOG = "XAuditREST.getXTrxLog"; + public static final String CREATE_X_TRX_LOG = "XAuditREST.createXTrxLog"; + public static final String UPDATE_X_TRX_LOG = "XAuditREST.updateXTrxLog"; + public static final String DELETE_X_TRX_LOG = "XAuditREST.deleteXTrxLog"; + public static final String SEARCH_X_TRX_LOG = "XAuditREST.searchXTrxLogs"; + public static final String COUNT_X_TRX_LOGS = "XAuditREST.countXTrxLogs"; + public static final String SEARCH_X_ACCESS_AUDITS = "XAuditREST.searchXAccessAudits"; + public static final String COUNT_X_ACCESS_AUDITS = "XAuditREST.countXAccessAudits"; - /** - * List of APIs for XAuditREST - */ - public static final String GET_X_TRX_LOG = "XAuditREST.getXTrxLog"; - public static final String CREATE_X_TRX_LOG = "XAuditREST.createXTrxLog"; - public static final String UPDATE_X_TRX_LOG = "XAuditREST.updateXTrxLog"; - public static final String DELETE_X_TRX_LOG = "XAuditREST.deleteXTrxLog"; - public static final String SEARCH_X_TRX_LOG = "XAuditREST.searchXTrxLogs"; - public static final String COUNT_X_TRX_LOGS = "XAuditREST.countXTrxLogs"; - public static final String SEARCH_X_ACCESS_AUDITS = "XAuditREST.searchXAccessAudits"; - public static final String COUNT_X_ACCESS_AUDITS = "XAuditREST.countXAccessAudits"; + /** + * List of APIs for XKeyREST + */ + public static final String SEARCH_KEYS = "XKeyREST.searchKeys"; + public static final String ROLLOVER_KEYS = "XKeyREST.rolloverKey"; + public static final String DELETE_KEY = "XKeyREST.deleteKey"; + public static final String CREATE_KEY = "XKeyREST.createKey"; + public static final String GET_KEY = "XKeyREST.getKey"; - /** - * List of APIs for XKeyREST - */ - public static final String SEARCH_KEYS = "XKeyREST.searchKeys"; - public static final String ROLLOVER_KEYS = "XKeyREST.rolloverKey"; - public static final String DELETE_KEY = "XKeyREST.deleteKey"; - public static final String CREATE_KEY = "XKeyREST.createKey"; - public static final String GET_KEY = "XKeyREST.getKey"; + /** + * List of APIs for XUserREST + */ + public static final String GET_X_GROUP = "XUserREST.getXGroup"; + public static final String SECURE_GET_X_GROUP = "XUserREST.secureGetXGroup"; + public static final String CREATE_X_GROUP = "XUserREST.createXGroup"; + public static final String SECURE_CREATE_X_GROUP = "XUserREST.secureCreateXGroup"; + public static final String UPDATE_X_GROUP = "XUserREST.updateXGroup"; + public static final String SECURE_UPDATE_X_GROUP = "XUserREST.secureUpdateXGroup"; + public static final String MODIFY_GROUPS_VISIBILITY = "XUserREST.modifyGroupsVisibility"; + public static final String DELETE_X_GROUP = "XUserREST.deleteXGroup"; + public static final String SEARCH_X_GROUPS = "XUserREST.searchXGroups"; + public static final String COUNT_X_GROUPS = "XUserREST.countXGroups"; + public static final String GET_X_USER = "XUserREST.getXUser"; + public static final String SECURE_GET_X_USER = "XUserREST.secureGetXUser"; + public static final String CREATE_X_USER = "XUserREST.createXUser"; + public static final String CREATE_X_USER_GROUP_FROM_MAP = "XUserREST.createXUserGroupFromMap"; + public static final String SECURE_CREATE_X_USER = "XUserREST.secureCreateXUser"; + public static final String UPDATE_X_USER = "XUserREST.updateXUser"; + public static final String SECURE_UPDATE_X_USER = "XUserREST.secureUpdateXUser"; + public static final String MODIFY_USER_VISIBILITY = "XUserREST.modifyUserVisibility"; + public static final String DELETE_X_USER = "XUserREST.deleteXUser"; + public static final String SEARCH_X_USERS = "XUserREST.searchXUsers"; + public static final String GET_USERS_LOOKUP = "XUserREST.getUsersLookup"; + public static final String GET_GROUPS_LOOKUP = "XUserREST.getGroupsLookup"; + public static final String GET_PRINCIPALS_LOOKUP = "XUserREST.getPrincipalsLookup"; + public static final String COUNT_X_USERS = "XUserREST.countXUsers"; + public static final String GET_X_GROUP_USER = "XUserREST.getXGroupUser"; + public static final String CREATE_X_GROUP_USER = "XUserREST.createXGroupUser"; + public static final String UPDATE_X_GROUP_USER = "XUserREST.updateXGroupUser"; + public static final String DELETE_X_GROUP_USER = "XUserREST.deleteXGroupUser"; + public static final String SEARCH_X_GROUP_USERS = "XUserREST.searchXGroupUsers"; + public static final String GET_X_GROUP_USERS_BY_GROUP_NAME = "XUserREST.getXGroupUsersByGroupName"; + public static final String COUNT_X_GROUP_USERS = "XUserREST.countXGroupUsers"; + public static final String GET_X_PERM_MAP = "XUserREST.getXPermMap"; + public static final String CREATE_X_PERM_MAP = "XUserREST.createXPermMap"; + public static final String UPDATE_X_PERM_MAP = "XUserREST.updateXPermMap"; + public static final String DELETE_X_PERM_MAP = "XUserREST.deleteXPermMap"; + public static final String SEARCH_X_PERM_MAPS = "XUserREST.searchXPermMaps"; + public static final String COUNT_X_PERM_MAPS = "XUserREST.countXPermMaps"; + public static final String GET_X_AUDIT_MAP = "XUserREST.getXAuditMap"; + public static final String CREATE_X_AUDIT_MAP = "XUserREST.createXAuditMap"; + public static final String UPDATE_X_AUDIT_MAP = "XUserREST.updateXAuditMap"; + public static final String DELETE_X_AUDIT_MAP = "XUserREST.deleteXAuditMap"; + public static final String SEARCH_X_AUDIT_MAPS = "XUserREST.searchXAuditMaps"; + public static final String COUNT_X_AUDIT_MAPS = "XUserREST.countXAuditMaps"; + public static final String GET_X_USER_BY_USER_NAME = "XUserREST.getXUserByUserName"; + public static final String GET_X_GROUP_BY_GROUP_NAME = "XUserREST.getXGroupByGroupName"; + public static final String DELETE_X_USER_BY_USER_NAME = "XUserREST.deleteXUserByUserName"; + public static final String DELETE_X_GROUP_BY_GROUP_NAME = "XUserREST.deleteXGroupByGroupName"; + public static final String DELETE_X_GROUP_AND_X_USER = "XUserREST.deleteXGroupAndXUser"; + public static final String GET_X_USER_GROUPS = "XUserREST.getXUserGroups"; + public static final String GET_X_GROUP_USERS = "XUserREST.getXGroupUsers"; + public static final String GET_AUTH_SESSIONS = "XUserREST.getAuthSessions"; + public static final String GET_AUTH_SESSION = "XUserREST.getAuthSession"; + public static final String CREATE_X_MODULE_DEF_PERMISSION = "XUserREST.createXModuleDefPermission"; + public static final String GET_X_MODULE_DEF_PERMISSION = "XUserREST.getXModuleDefPermission"; + public static final String UPDATE_X_MODULE_DEF_PERMISSION = "XUserREST.updateXModuleDefPermission"; + public static final String DELETE_X_MODULE_DEF_PERMISSION = "XUserREST.deleteXModuleDefPermission"; + public static final String SEARCH_X_MODULE_DEF = "XUserREST.searchXModuleDef"; + public static final String COUNT_X_MODULE_DEF = "XUserREST.countXModuleDef"; + public static final String CREATE_X_USER_PERMISSION = "XUserREST.createXUserPermission"; + public static final String GET_X_USER_PERMISSION = "XUserREST.getXUserPermission"; + public static final String UPDATE_X_USER_PERMISSION = "XUserREST.updateXUserPermission"; + public static final String DELETE_X_USER_PERMISSION = "XUserREST.deleteXUserPermission"; + public static final String SEARCH_X_USER_PERMISSION = "XUserREST.searchXUserPermission"; + public static final String COUNT_X_USER_PERMISSION = "XUserREST.countXUserPermission"; + public static final String CREATE_X_GROUP_PERMISSION = "XUserREST.createXGroupPermission"; + public static final String GET_X_GROUP_PERMISSION = "XUserREST.getXGroupPermission"; + public static final String UPDATE_X_GROUP_PERMISSION = "XUserREST.updateXGroupPermission"; + public static final String DELETE_X_GROUP_PERMISSION = "XUserREST.deleteXGroupPermission"; + public static final String SEARCH_X_GROUP_PERMISSION = "XUserREST.searchXGroupPermission"; + public static final String COUNT_X_GROUP_PERMISSION = "XUserREST.countXGroupPermission"; + public static final String MODIFY_USER_ACTIVE_STATUS = "XUserREST.modifyUserActiveStatus"; + public static final String SET_USER_ROLES_BY_ID = "XUserREST.setUserRolesByID"; + public static final String SET_USER_ROLES_BY_NAME = "XUserREST.setUserRolesByName"; + public static final String GET_USER_ROLES_BY_ID = "XUserREST.getUserRolesByID"; + public static final String GET_USER_ROLES_BY_NAME = "XUserREST.getUserRolesByName"; + public static final String FORCE_DELETE_EXTERNAL_USERS = "XUserREST.forceDeleteExternalUsers"; + public static final String FORCE_DELETE_EXTERNAL_GROUPS = "XUserREST.forceDeleteExternalGroups"; - /** - * List of APIs for XUserREST - */ - public static final String GET_X_GROUP = "XUserREST.getXGroup"; - public static final String SECURE_GET_X_GROUP = "XUserREST.secureGetXGroup"; - public static final String CREATE_X_GROUP = "XUserREST.createXGroup"; - public static final String SECURE_CREATE_X_GROUP = "XUserREST.secureCreateXGroup"; - public static final String UPDATE_X_GROUP = "XUserREST.updateXGroup"; - public static final String SECURE_UPDATE_X_GROUP = "XUserREST.secureUpdateXGroup"; - public static final String MODIFY_GROUPS_VISIBILITY = "XUserREST.modifyGroupsVisibility"; - public static final String DELETE_X_GROUP = "XUserREST.deleteXGroup"; - public static final String SEARCH_X_GROUPS = "XUserREST.searchXGroups"; - public static final String COUNT_X_GROUPS = "XUserREST.countXGroups"; - public static final String GET_X_USER = "XUserREST.getXUser"; - public static final String SECURE_GET_X_USER = "XUserREST.secureGetXUser"; - public static final String CREATE_X_USER = "XUserREST.createXUser"; - public static final String CREATE_X_USER_GROUP_FROM_MAP = "XUserREST.createXUserGroupFromMap"; - public static final String SECURE_CREATE_X_USER = "XUserREST.secureCreateXUser"; - public static final String UPDATE_X_USER = "XUserREST.updateXUser"; - public static final String SECURE_UPDATE_X_USER = "XUserREST.secureUpdateXUser"; - public static final String MODIFY_USER_VISIBILITY = "XUserREST.modifyUserVisibility"; - public static final String DELETE_X_USER = "XUserREST.deleteXUser"; - public static final String SEARCH_X_USERS = "XUserREST.searchXUsers"; - public static final String GET_USERS_LOOKUP = "XUserREST.getUsersLookup"; - public static final String GET_GROUPS_LOOKUP = "XUserREST.getGroupsLookup"; - public static final String GET_PRINCIPALS_LOOKUP = "XUserREST.getPrincipalsLookup"; - public static final String COUNT_X_USERS = "XUserREST.countXUsers"; - public static final String GET_X_GROUP_USER = "XUserREST.getXGroupUser"; - public static final String CREATE_X_GROUP_USER = "XUserREST.createXGroupUser"; - public static final String UPDATE_X_GROUP_USER = "XUserREST.updateXGroupUser"; - public static final String DELETE_X_GROUP_USER = "XUserREST.deleteXGroupUser"; - public static final String SEARCH_X_GROUP_USERS = "XUserREST.searchXGroupUsers"; - public static final String GET_X_GROUP_USERS_BY_GROUP_NAME = "XUserREST.getXGroupUsersByGroupName"; - public static final String COUNT_X_GROUP_USERS = "XUserREST.countXGroupUsers"; - public static final String GET_X_PERM_MAP = "XUserREST.getXPermMap"; - public static final String CREATE_X_PERM_MAP = "XUserREST.createXPermMap"; - public static final String UPDATE_X_PERM_MAP = "XUserREST.updateXPermMap"; - public static final String DELETE_X_PERM_MAP = "XUserREST.deleteXPermMap"; - public static final String SEARCH_X_PERM_MAPS = "XUserREST.searchXPermMaps"; - public static final String COUNT_X_PERM_MAPS = "XUserREST.countXPermMaps"; - public static final String GET_X_AUDIT_MAP = "XUserREST.getXAuditMap"; - public static final String CREATE_X_AUDIT_MAP = "XUserREST.createXAuditMap"; - public static final String UPDATE_X_AUDIT_MAP = "XUserREST.updateXAuditMap"; - public static final String DELETE_X_AUDIT_MAP = "XUserREST.deleteXAuditMap"; - public static final String SEARCH_X_AUDIT_MAPS = "XUserREST.searchXAuditMaps"; - public static final String COUNT_X_AUDIT_MAPS = "XUserREST.countXAuditMaps"; - public static final String GET_X_USER_BY_USER_NAME = "XUserREST.getXUserByUserName"; - public static final String GET_X_GROUP_BY_GROUP_NAME = "XUserREST.getXGroupByGroupName"; - public static final String DELETE_X_USER_BY_USER_NAME = "XUserREST.deleteXUserByUserName"; - public static final String DELETE_X_GROUP_BY_GROUP_NAME = "XUserREST.deleteXGroupByGroupName"; - public static final String DELETE_X_GROUP_AND_X_USER = "XUserREST.deleteXGroupAndXUser"; - public static final String GET_X_USER_GROUPS = "XUserREST.getXUserGroups"; - public static final String GET_X_GROUP_USERS = "XUserREST.getXGroupUsers"; - public static final String GET_AUTH_SESSIONS = "XUserREST.getAuthSessions"; - public static final String GET_AUTH_SESSION = "XUserREST.getAuthSession"; - public static final String CREATE_X_MODULE_DEF_PERMISSION = "XUserREST.createXModuleDefPermission"; - public static final String GET_X_MODULE_DEF_PERMISSION = "XUserREST.getXModuleDefPermission"; - public static final String UPDATE_X_MODULE_DEF_PERMISSION = "XUserREST.updateXModuleDefPermission"; - public static final String DELETE_X_MODULE_DEF_PERMISSION = "XUserREST.deleteXModuleDefPermission"; - public static final String SEARCH_X_MODULE_DEF = "XUserREST.searchXModuleDef"; - public static final String COUNT_X_MODULE_DEF = "XUserREST.countXModuleDef"; - public static final String CREATE_X_USER_PERMISSION = "XUserREST.createXUserPermission"; - public static final String GET_X_USER_PERMISSION = "XUserREST.getXUserPermission"; - public static final String UPDATE_X_USER_PERMISSION = "XUserREST.updateXUserPermission"; - public static final String DELETE_X_USER_PERMISSION = "XUserREST.deleteXUserPermission"; - public static final String SEARCH_X_USER_PERMISSION = "XUserREST.searchXUserPermission"; - public static final String COUNT_X_USER_PERMISSION = "XUserREST.countXUserPermission"; - public static final String CREATE_X_GROUP_PERMISSION = "XUserREST.createXGroupPermission"; - public static final String GET_X_GROUP_PERMISSION = "XUserREST.getXGroupPermission"; - public static final String UPDATE_X_GROUP_PERMISSION = "XUserREST.updateXGroupPermission"; - public static final String DELETE_X_GROUP_PERMISSION = "XUserREST.deleteXGroupPermission"; - public static final String SEARCH_X_GROUP_PERMISSION = "XUserREST.searchXGroupPermission"; - public static final String COUNT_X_GROUP_PERMISSION = "XUserREST.countXGroupPermission"; - public static final String MODIFY_USER_ACTIVE_STATUS = "XUserREST.modifyUserActiveStatus"; - public static final String SET_USER_ROLES_BY_ID="XUserREST.setUserRolesByID"; - public static final String SET_USER_ROLES_BY_NAME="XUserREST.setUserRolesByName"; - public static final String GET_USER_ROLES_BY_ID="XUserREST.getUserRolesByID"; - public static final String GET_USER_ROLES_BY_NAME="XUserREST.getUserRolesByName"; - public static final String FORCE_DELETE_EXTERNAL_USERS = "XUserREST.forceDeleteExternalUsers"; - public static final String FORCE_DELETE_EXTERNAL_GROUPS = "XUserREST.forceDeleteExternalGroups"; + /** + * List of APIs for DataShareREST + */ + public static final String GET_DATASET_SUMMARY = "GdsREST.getDatasetSummary"; + public static final String CREATE_DATASET = "GdsREST.createDataset"; + public static final String UPDATE_DATASET = "GdsREST.updateDataset"; + public static final String DELETE_DATASET = "GdsREST.deleteDataset"; + public static final String GET_DATASET = "GdsREST.getDataset"; + public static final String SEARCH_DATASETS = "GdsREST.searchDatasets"; + public static final String LIST_DATASET_NAMES = "GdsREST.listDatasetNames"; + public static final String DATASET_POLICY = "GdsREST.datasetPolicy"; - /** - * List of APIs for DataShareREST - */ - public static final String GET_DATASET_SUMMARY = "GdsREST.getDatasetSummary"; - public static final String CREATE_DATASET = "GdsREST.createDataset"; - public static final String UPDATE_DATASET = "GdsREST.updateDataset"; - public static final String DELETE_DATASET = "GdsREST.deleteDataset"; - public static final String GET_DATASET = "GdsREST.getDataset"; - public static final String SEARCH_DATASETS = "GdsREST.searchDatasets"; - public static final String LIST_DATASET_NAMES = "GdsREST.listDatasetNames"; - public static final String DATASET_POLICY = "GdsREST.datasetPolicy"; + public static final String CREATE_PROJECT = "GdsREST.createProject"; + public static final String UPDATE_PROJECT = "GdsREST.updateProject"; + public static final String DELETE_PROJECT = "GdsREST.deleteProject"; + public static final String GET_PROJECT = "GdsREST.getProject"; + public static final String SEARCH_PROJECTS = "GdsREST.searchProjects"; + public static final String LIST_PROJECT_NAMES = "GdsREST.listProjectNames"; + public static final String PROJECT_POLICY = "GdsREST.projectPolicy"; - public static final String CREATE_PROJECT = "GdsREST.createProject"; - public static final String UPDATE_PROJECT = "GdsREST.updateProject"; - public static final String DELETE_PROJECT = "GdsREST.deleteProject"; - public static final String GET_PROJECT = "GdsREST.getProject"; - public static final String SEARCH_PROJECTS = "GdsREST.searchProjects"; - public static final String LIST_PROJECT_NAMES = "GdsREST.listProjectNames"; - public static final String PROJECT_POLICY = "GdsREST.projectPolicy"; + public static final String CREATE_DATA_SHARE = "GdsREST.createDataShare"; + public static final String UPDATE_DATA_SHARE = "GdsREST.updateDataShare"; + public static final String DELETE_DATA_SHARE = "GdsREST.deleteDataShare"; + public static final String GET_DATA_SHARE = "GdsREST.getDataShare"; + public static final String SEARCH_DATA_SHARES = "GdsREST.searchDataShares"; + public static final String GET_DATA_SHARE_SUMMARY = "GdsREST.getDataShareSummary"; - public static final String CREATE_DATA_SHARE = "GdsREST.createDataShare"; - public static final String UPDATE_DATA_SHARE = "GdsREST.updateDataShare"; - public static final String DELETE_DATA_SHARE = "GdsREST.deleteDataShare"; - public static final String GET_DATA_SHARE = "GdsREST.getDataShare"; - public static final String SEARCH_DATA_SHARES = "GdsREST.searchDataShares"; - public static final String GET_DATA_SHARE_SUMMARY = "GdsREST.getDataShareSummary"; + public static final String ADD_SHARED_RESOURCE = "GdsREST.addSharedResource"; + public static final String ADD_SHARED_RESOURCES = "GdsREST.addSharedResources"; + public static final String UPDATE_SHARED_RESOURCE = "GdsREST.updateSharedResource"; + public static final String REMOVE_SHARED_RESOURCE = "GdsREST.removeSharedResource"; + public static final String REMOVE_SHARED_RESOURCES = "GdsREST.removeSharedResources"; + public static final String GET_SHARED_RESOURCE = "GdsREST.getSharedResource"; + public static final String SEARCH_SHARED_RESOURCES = "GdsREST.searchSharedResources"; - public static final String ADD_SHARED_RESOURCE = "GdsREST.addSharedResource"; - public static final String ADD_SHARED_RESOURCES = "GdsREST.addSharedResources"; - public static final String UPDATE_SHARED_RESOURCE = "GdsREST.updateSharedResource"; - public static final String REMOVE_SHARED_RESOURCE = "GdsREST.removeSharedResource"; - public static final String REMOVE_SHARED_RESOURCES = "GdsREST.removeSharedResources"; - public static final String GET_SHARED_RESOURCE = "GdsREST.getSharedResource"; - public static final String SEARCH_SHARED_RESOURCES = "GdsREST.searchSharedResources"; + public static final String ADD_DATASHARE_IN_DATASET = "GdsREST.addDataShareInDataset"; + public static final String UPDATE_DATASHARE_IN_DATASET = "GdsREST.updateDataShareInDataset"; + public static final String REMOVE_DATASHARE_IN_DATASET = "GdsREST.removeDataShareInDataset"; + public static final String GET_DATASHARE_IN_DATASET = "GdsREST.getDataShareInDataset"; + public static final String SEARCH_DATASHARE_IN_DATASET = "GdsREST.searchDataShareInDataset"; + public static final String SEARCH_DATASHARE_IN_DATASET_SUMMARY = "GdsREST.getDshInDsSummary"; - public static final String ADD_DATASHARE_IN_DATASET = "GdsREST.addDataShareInDataset"; - public static final String UPDATE_DATASHARE_IN_DATASET = "GdsREST.updateDataShareInDataset"; - public static final String REMOVE_DATASHARE_IN_DATASET = "GdsREST.removeDataShareInDataset"; - public static final String GET_DATASHARE_IN_DATASET = "GdsREST.getDataShareInDataset"; - public static final String SEARCH_DATASHARE_IN_DATASET = "GdsREST.searchDataShareInDataset"; - public static final String SEARCH_DATASHARE_IN_DATASET_SUMMARY = "GdsREST.getDshInDsSummary"; + public static final String ADD_DATASET_IN_PROJECT = "GdsREST.addDatasetInProject"; + public static final String UPDATE_DATASET_IN_PROJECT = "GdsREST.updateDatasetInProject"; + public static final String REMOVE_DATASET_IN_PROJECT = "GdsREST.removeDatasetInProject"; + public static final String GET_DATASET_IN_PROJECT = "GdsREST.getDatasetInProject"; + public static final String SEARCH_DATASET_IN_PROJECT = "GdsREST.searchDatasetInProject"; + public static final String GET_DATASET_GRANTS = "GdsREST.getDataSetGrants"; + public static final String UPDATE_DATASET_GRANTS = "GdsREST.updateDataSetGrants"; - public static final String ADD_DATASET_IN_PROJECT = "GdsREST.addDatasetInProject"; - public static final String UPDATE_DATASET_IN_PROJECT = "GdsREST.updateDatasetInProject"; - public static final String REMOVE_DATASET_IN_PROJECT = "GdsREST.removeDatasetInProject"; - public static final String GET_DATASET_IN_PROJECT = "GdsREST.getDatasetInProject"; - public static final String SEARCH_DATASET_IN_PROJECT = "GdsREST.searchDatasetInProject"; - public static final String GET_DATASET_GRANTS = "GdsREST.getDataSetGrants"; - public static final String UPDATE_DATASET_GRANTS = "GdsREST.updateDataSetGrants"; + /** + * List of APIs for PublicAPIsv2 + */ + public static final String GET_SERVICE_HEADERS = "PublicAPIsv2.getServiceHeaders"; - /** - * List of APIs for PublicAPIsv2 - */ - public static final String GET_SERVICE_HEADERS = "PublicAPIsv2.getServiceHeaders"; + private RangerAPIList() { + //To block instantiation + } } diff --git a/security-admin/src/main/java/org/apache/ranger/security/context/RangerAPIMapping.java b/security-admin/src/main/java/org/apache/ranger/security/context/RangerAPIMapping.java index 89bd01425c..1159207204 100644 --- a/security-admin/src/main/java/org/apache/ranger/security/context/RangerAPIMapping.java +++ b/security-admin/src/main/java/org/apache/ranger/security/context/RangerAPIMapping.java @@ -16,581 +16,564 @@ */ package org.apache.ranger.security.context; +import org.apache.commons.collections.CollectionUtils; +import org.springframework.stereotype.Component; + import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; -import org.apache.commons.collections.CollectionUtils; -import org.springframework.stereotype.Component; - @Component public class RangerAPIMapping { - - /** - * @NOTE While adding new tab here, please don't forget to update the function: - * org.apache.ranger.security.context.RangerAPIMapping.getAvailableUITabs() - */ - public static final String TAB_RESOURCE_BASED_POLICIES = "Resource Based Policies"; - public static final String TAB_AUDIT = "Audit"; - public static final String TAB_USERS_GROUPS = "Users/Groups"; - public static final String TAB_PERMISSIONS = "Permissions"; - public static final String TAB_KEY_MANAGER = "Key Manager"; - public static final String TAB_TAG_BASED_POLICIES = "Tag Based Policies"; - public static final String TAB_REPORTS = "Reports"; - public static final String TAB_GDS = "Governed Data Sharing"; - private static HashMap> rangerAPIMappingWithUI = null; - private static Set tabList = new HashSet(); - private static Map> mapApiToTabs = null; - - public RangerAPIMapping() { - init(); - } - - private void init() { - if (rangerAPIMappingWithUI == null) { - rangerAPIMappingWithUI = new HashMap>(); - } - if (mapApiToTabs == null) { - mapApiToTabs = new HashMap>(); - } - - mapResourceBasedPoliciesWithAPIs(); - mapAuditWithAPIs(); - mapUGWithAPIs(); - mapPermissionsWithAPIs(); - mapKeyManagerWithAPIs(); - mapTagBasedPoliciesWithAPIs(); - mapReportsWithAPIs(); - mapGDSWithAPIs(); - - if (CollectionUtils.isEmpty(tabList)) { - populateAvailableUITabs(); - } - - } - - private void populateAvailableUITabs() { - tabList = new HashSet(); - tabList.add(TAB_RESOURCE_BASED_POLICIES); - tabList.add(TAB_TAG_BASED_POLICIES); - tabList.add(TAB_AUDIT); - tabList.add(TAB_REPORTS); - tabList.add(TAB_KEY_MANAGER); - tabList.add(TAB_PERMISSIONS); - tabList.add(TAB_USERS_GROUPS); - tabList.add(TAB_GDS); - } - - private void mapReportsWithAPIs() { - Set apiAssociatedWithReports = new HashSet(); - - apiAssociatedWithReports.add(RangerAPIList.COUNT_X_ASSETS); - apiAssociatedWithReports.add(RangerAPIList.GET_X_ASSET); - apiAssociatedWithReports.add(RangerAPIList.SEARCH_X_ASSETS); - - apiAssociatedWithReports.add(RangerAPIList.COUNT_SERVICES); - apiAssociatedWithReports.add(RangerAPIList.GET_POLICY_FOR_VERSION_NO); - apiAssociatedWithReports.add(RangerAPIList.GET_POLICY_FROM_EVENT_TIME); - apiAssociatedWithReports.add(RangerAPIList.GET_POLICY_VERSION_LIST); - apiAssociatedWithReports.add(RangerAPIList.GET_SERVICE); - apiAssociatedWithReports.add(RangerAPIList.GET_SERVICE_BY_NAME); - apiAssociatedWithReports.add(RangerAPIList.GET_SERVICE_DEF); - apiAssociatedWithReports.add(RangerAPIList.GET_SERVICE_DEF_BY_NAME); - apiAssociatedWithReports.add(RangerAPIList.GET_SERVICE_DEFS); - apiAssociatedWithReports.add(RangerAPIList.GET_SERVICES); - apiAssociatedWithReports.add(RangerAPIList.GET_SERVICE_HEADERS); - apiAssociatedWithReports.add(RangerAPIList.LOOKUP_RESOURCE); - - apiAssociatedWithReports.add(RangerAPIList.GET_USER_PROFILE_FOR_USER); - apiAssociatedWithReports.add(RangerAPIList.SEARCH_USERS); - - apiAssociatedWithReports.add(RangerAPIList.COUNT_X_AUDIT_MAPS); - apiAssociatedWithReports.add(RangerAPIList.COUNT_X_GROUPS); - apiAssociatedWithReports.add(RangerAPIList.COUNT_X_GROUP_USERS); - apiAssociatedWithReports.add(RangerAPIList.COUNT_X_PERM_MAPS); - apiAssociatedWithReports.add(RangerAPIList.COUNT_X_USERS); - apiAssociatedWithReports.add(RangerAPIList.GET_X_AUDIT_MAP); - apiAssociatedWithReports.add(RangerAPIList.GET_X_GROUP); - apiAssociatedWithReports.add(RangerAPIList.GET_X_GROUP_BY_GROUP_NAME); - apiAssociatedWithReports.add(RangerAPIList.GET_X_GROUP_USER); - apiAssociatedWithReports.add(RangerAPIList.GET_X_GROUP_USERS); - apiAssociatedWithReports.add(RangerAPIList.GET_X_PERM_MAP); - apiAssociatedWithReports.add(RangerAPIList.GET_X_USER); - apiAssociatedWithReports.add(RangerAPIList.GET_X_USER_BY_USER_NAME); - apiAssociatedWithReports.add(RangerAPIList.GET_X_USER_GROUPS); - apiAssociatedWithReports.add(RangerAPIList.SEARCH_X_AUDIT_MAPS); - apiAssociatedWithReports.add(RangerAPIList.SEARCH_X_GROUPS); - apiAssociatedWithReports.add(RangerAPIList.SEARCH_X_GROUP_USERS); - apiAssociatedWithReports.add(RangerAPIList.SEARCH_X_PERM_MAPS); - apiAssociatedWithReports.add(RangerAPIList.SEARCH_X_USERS); - apiAssociatedWithReports.add(RangerAPIList.SECURE_GET_X_GROUP); - apiAssociatedWithReports.add(RangerAPIList.SECURE_GET_X_USER); - - rangerAPIMappingWithUI.put(TAB_REPORTS, apiAssociatedWithReports); - - for (String api : apiAssociatedWithReports) { - if (mapApiToTabs.get(api) == null) { - mapApiToTabs.put(api, new HashSet()); - } - mapApiToTabs.get(api).add(TAB_REPORTS); - } - } - - private void mapTagBasedPoliciesWithAPIs() { - Set apiAssociatedWithTagBasedPolicy = new HashSet(); - - apiAssociatedWithTagBasedPolicy.add(RangerAPIList.COUNT_X_ASSETS); - apiAssociatedWithTagBasedPolicy.add(RangerAPIList.CREATE_X_ASSET); - apiAssociatedWithTagBasedPolicy.add(RangerAPIList.DELETE_X_ASSET); - apiAssociatedWithTagBasedPolicy.add(RangerAPIList.GET_X_ASSET); - apiAssociatedWithTagBasedPolicy.add(RangerAPIList.SEARCH_X_ASSETS); - apiAssociatedWithTagBasedPolicy.add(RangerAPIList.TEST_CONFIG); - apiAssociatedWithTagBasedPolicy.add(RangerAPIList.UPDATE_X_ASSET); - - apiAssociatedWithTagBasedPolicy.add(RangerAPIList.COUNT_SERVICES); - apiAssociatedWithTagBasedPolicy.add(RangerAPIList.CREATE_SERVICE); - apiAssociatedWithTagBasedPolicy.add(RangerAPIList.CREATE_SERVICE_DEF); - apiAssociatedWithTagBasedPolicy.add(RangerAPIList.DELETE_SERVICE); - apiAssociatedWithTagBasedPolicy.add(RangerAPIList.DELETE_SERVICE_DEF); - apiAssociatedWithTagBasedPolicy.add(RangerAPIList.GET_POLICY_FOR_VERSION_NO); - apiAssociatedWithTagBasedPolicy.add(RangerAPIList.GET_POLICY_FROM_EVENT_TIME); - apiAssociatedWithTagBasedPolicy.add(RangerAPIList.GET_POLICY_VERSION_LIST); - apiAssociatedWithTagBasedPolicy.add(RangerAPIList.GET_SERVICE); - apiAssociatedWithTagBasedPolicy.add(RangerAPIList.GET_SERVICE_BY_NAME); - apiAssociatedWithTagBasedPolicy.add(RangerAPIList.GET_SERVICE_DEF); - apiAssociatedWithTagBasedPolicy.add(RangerAPIList.GET_SERVICE_DEF_BY_NAME); - apiAssociatedWithTagBasedPolicy.add(RangerAPIList.GET_SERVICE_DEFS); - apiAssociatedWithTagBasedPolicy.add(RangerAPIList.GET_SERVICES); - apiAssociatedWithTagBasedPolicy.add(RangerAPIList.GET_SERVICE_HEADERS); - apiAssociatedWithTagBasedPolicy.add(RangerAPIList.LOOKUP_RESOURCE); - apiAssociatedWithTagBasedPolicy.add(RangerAPIList.UPDATE_SERVICE); - apiAssociatedWithTagBasedPolicy.add(RangerAPIList.UPDATE_SERVICE_DEF); - apiAssociatedWithTagBasedPolicy.add(RangerAPIList.VALIDATE_CONFIG); - - apiAssociatedWithTagBasedPolicy.add(RangerAPIList.GET_USER_PROFILE_FOR_USER); - apiAssociatedWithTagBasedPolicy.add(RangerAPIList.SEARCH_USERS); - - apiAssociatedWithTagBasedPolicy.add(RangerAPIList.COUNT_X_AUDIT_MAPS); - apiAssociatedWithTagBasedPolicy.add(RangerAPIList.COUNT_X_GROUPS); - apiAssociatedWithTagBasedPolicy.add(RangerAPIList.COUNT_X_GROUP_USERS); - apiAssociatedWithTagBasedPolicy.add(RangerAPIList.COUNT_X_PERM_MAPS); - apiAssociatedWithTagBasedPolicy.add(RangerAPIList.COUNT_X_USERS); - apiAssociatedWithTagBasedPolicy.add(RangerAPIList.CREATE_X_AUDIT_MAP); - apiAssociatedWithTagBasedPolicy.add(RangerAPIList.CREATE_X_PERM_MAP); - apiAssociatedWithTagBasedPolicy.add(RangerAPIList.DELETE_X_AUDIT_MAP); - apiAssociatedWithTagBasedPolicy.add(RangerAPIList.DELETE_X_PERM_MAP); - apiAssociatedWithTagBasedPolicy.add(RangerAPIList.GET_X_AUDIT_MAP); - apiAssociatedWithTagBasedPolicy.add(RangerAPIList.GET_X_GROUP); - apiAssociatedWithTagBasedPolicy.add(RangerAPIList.GET_X_GROUP_BY_GROUP_NAME); - apiAssociatedWithTagBasedPolicy.add(RangerAPIList.GET_X_GROUP_USER); - apiAssociatedWithTagBasedPolicy.add(RangerAPIList.GET_X_GROUP_USERS); - apiAssociatedWithTagBasedPolicy.add(RangerAPIList.GET_X_PERM_MAP); - apiAssociatedWithTagBasedPolicy.add(RangerAPIList.GET_X_USER); - apiAssociatedWithTagBasedPolicy.add(RangerAPIList.GET_X_USER_BY_USER_NAME); - apiAssociatedWithTagBasedPolicy.add(RangerAPIList.GET_X_USER_GROUPS); - apiAssociatedWithTagBasedPolicy.add(RangerAPIList.MODIFY_GROUPS_VISIBILITY); - apiAssociatedWithTagBasedPolicy.add(RangerAPIList.MODIFY_USER_ACTIVE_STATUS); - apiAssociatedWithTagBasedPolicy.add(RangerAPIList.MODIFY_USER_VISIBILITY); - apiAssociatedWithTagBasedPolicy.add(RangerAPIList.SEARCH_X_AUDIT_MAPS); - apiAssociatedWithTagBasedPolicy.add(RangerAPIList.SEARCH_X_GROUPS); - apiAssociatedWithTagBasedPolicy.add(RangerAPIList.SEARCH_X_GROUP_USERS); - apiAssociatedWithTagBasedPolicy.add(RangerAPIList.SEARCH_X_PERM_MAPS); - apiAssociatedWithTagBasedPolicy.add(RangerAPIList.SEARCH_X_USERS); - apiAssociatedWithTagBasedPolicy.add(RangerAPIList.SECURE_GET_X_GROUP); - apiAssociatedWithTagBasedPolicy.add(RangerAPIList.SECURE_GET_X_USER); - apiAssociatedWithTagBasedPolicy.add(RangerAPIList.UPDATE_X_AUDIT_MAP); - apiAssociatedWithTagBasedPolicy.add(RangerAPIList.UPDATE_X_PERM_MAP); - - apiAssociatedWithTagBasedPolicy.add(RangerAPIList.CREATE); - apiAssociatedWithTagBasedPolicy.add(RangerAPIList.CREATE_DEFAULT_ACCOUNT_USER); - apiAssociatedWithTagBasedPolicy.add(RangerAPIList.UPDATE); - apiAssociatedWithTagBasedPolicy.add(RangerAPIList.SET_USER_ROLES); - apiAssociatedWithTagBasedPolicy.add(RangerAPIList.DEACTIVATE_USER); - - rangerAPIMappingWithUI.put(TAB_TAG_BASED_POLICIES, apiAssociatedWithTagBasedPolicy); - - for (String api : apiAssociatedWithTagBasedPolicy) { - if (mapApiToTabs.get(api) == null) { - mapApiToTabs.put(api, new HashSet()); - } - mapApiToTabs.get(api).add(TAB_TAG_BASED_POLICIES); - } - } - - private void mapKeyManagerWithAPIs() { - - Set apiAssociatedWithKeyManager = new HashSet(); - - apiAssociatedWithKeyManager.add(RangerAPIList.COUNT_X_ASSETS); - apiAssociatedWithKeyManager.add(RangerAPIList.CREATE_X_ASSET); - apiAssociatedWithKeyManager.add(RangerAPIList.DELETE_X_ASSET); - apiAssociatedWithKeyManager.add(RangerAPIList.GET_X_ASSET); - apiAssociatedWithKeyManager.add(RangerAPIList.SEARCH_X_ASSETS); - apiAssociatedWithKeyManager.add(RangerAPIList.TEST_CONFIG); - apiAssociatedWithKeyManager.add(RangerAPIList.UPDATE_X_ASSET); - - apiAssociatedWithKeyManager.add(RangerAPIList.COUNT_SERVICES); - apiAssociatedWithKeyManager.add(RangerAPIList.CREATE_SERVICE); - apiAssociatedWithKeyManager.add(RangerAPIList.CREATE_SERVICE_DEF); - apiAssociatedWithKeyManager.add(RangerAPIList.DELETE_SERVICE); - apiAssociatedWithKeyManager.add(RangerAPIList.DELETE_SERVICE_DEF); - apiAssociatedWithKeyManager.add(RangerAPIList.GET_POLICY_FOR_VERSION_NO); - apiAssociatedWithKeyManager.add(RangerAPIList.GET_POLICY_FROM_EVENT_TIME); - apiAssociatedWithKeyManager.add(RangerAPIList.GET_POLICY_VERSION_LIST); - apiAssociatedWithKeyManager.add(RangerAPIList.GET_SERVICE); - apiAssociatedWithKeyManager.add(RangerAPIList.GET_SERVICE_BY_NAME); - apiAssociatedWithKeyManager.add(RangerAPIList.GET_SERVICE_DEF); - apiAssociatedWithKeyManager.add(RangerAPIList.GET_SERVICE_DEF_BY_NAME); - apiAssociatedWithKeyManager.add(RangerAPIList.GET_SERVICE_DEFS); - apiAssociatedWithKeyManager.add(RangerAPIList.GET_SERVICES); - apiAssociatedWithKeyManager.add(RangerAPIList.GET_SERVICE_HEADERS); - apiAssociatedWithKeyManager.add(RangerAPIList.LOOKUP_RESOURCE); - apiAssociatedWithKeyManager.add(RangerAPIList.UPDATE_SERVICE); - apiAssociatedWithKeyManager.add(RangerAPIList.UPDATE_SERVICE_DEF); - apiAssociatedWithKeyManager.add(RangerAPIList.VALIDATE_CONFIG); - - apiAssociatedWithKeyManager.add(RangerAPIList.CREATE_KEY); - apiAssociatedWithKeyManager.add(RangerAPIList.DELETE_KEY); - apiAssociatedWithKeyManager.add(RangerAPIList.GET_KEY); - apiAssociatedWithKeyManager.add(RangerAPIList.ROLLOVER_KEYS); - apiAssociatedWithKeyManager.add(RangerAPIList.SEARCH_KEYS); - - rangerAPIMappingWithUI.put(TAB_KEY_MANAGER, apiAssociatedWithKeyManager); - - for (String api : apiAssociatedWithKeyManager) { - if (mapApiToTabs.get(api) == null) { - mapApiToTabs.put(api, new HashSet()); - } - mapApiToTabs.get(api).add(TAB_KEY_MANAGER); - } - } - - private void mapPermissionsWithAPIs() { - - Set apiAssociatedWithPermissions = new HashSet(); - - apiAssociatedWithPermissions.add(RangerAPIList.COUNT_X_GROUP_PERMISSION); - apiAssociatedWithPermissions.add(RangerAPIList.COUNT_X_MODULE_DEF); - apiAssociatedWithPermissions.add(RangerAPIList.COUNT_X_USER_PERMISSION); - apiAssociatedWithPermissions.add(RangerAPIList.CREATE_X_GROUP_PERMISSION); - apiAssociatedWithPermissions.add(RangerAPIList.CREATE_X_MODULE_DEF_PERMISSION); - apiAssociatedWithPermissions.add(RangerAPIList.CREATE_X_USER_PERMISSION); - apiAssociatedWithPermissions.add(RangerAPIList.DELETE_X_GROUP_PERMISSION); - apiAssociatedWithPermissions.add(RangerAPIList.DELETE_X_MODULE_DEF_PERMISSION); - apiAssociatedWithPermissions.add(RangerAPIList.DELETE_X_USER_PERMISSION); - apiAssociatedWithPermissions.add(RangerAPIList.GET_X_GROUP_PERMISSION); - apiAssociatedWithPermissions.add(RangerAPIList.GET_X_MODULE_DEF_PERMISSION); - apiAssociatedWithPermissions.add(RangerAPIList.GET_X_USER_PERMISSION); - apiAssociatedWithPermissions.add(RangerAPIList.SEARCH_X_GROUP_PERMISSION); - apiAssociatedWithPermissions.add(RangerAPIList.SEARCH_X_MODULE_DEF); - apiAssociatedWithPermissions.add(RangerAPIList.SEARCH_X_USER_PERMISSION); - apiAssociatedWithPermissions.add(RangerAPIList.UPDATE_X_GROUP_PERMISSION); - apiAssociatedWithPermissions.add(RangerAPIList.UPDATE_X_MODULE_DEF_PERMISSION); - apiAssociatedWithPermissions.add(RangerAPIList.UPDATE_X_USER_PERMISSION); - - rangerAPIMappingWithUI.put(TAB_PERMISSIONS, apiAssociatedWithPermissions); - - for (String api : apiAssociatedWithPermissions) { - if (mapApiToTabs.get(api) == null) { - mapApiToTabs.put(api, new HashSet()); - } - mapApiToTabs.get(api).add(TAB_PERMISSIONS); - } - } - - private void mapUGWithAPIs() { - Set apiAssociatedWithUserAndGroups = new HashSet(); - - apiAssociatedWithUserAndGroups.add(RangerAPIList.GET_USER_PROFILE_FOR_USER); - apiAssociatedWithUserAndGroups.add(RangerAPIList.SEARCH_USERS); - - apiAssociatedWithUserAndGroups.add(RangerAPIList.COUNT_X_AUDIT_MAPS); - apiAssociatedWithUserAndGroups.add(RangerAPIList.COUNT_X_GROUPS); - apiAssociatedWithUserAndGroups.add(RangerAPIList.COUNT_X_GROUP_USERS); - apiAssociatedWithUserAndGroups.add(RangerAPIList.COUNT_X_PERM_MAPS); - apiAssociatedWithUserAndGroups.add(RangerAPIList.COUNT_X_USERS); - apiAssociatedWithUserAndGroups.add(RangerAPIList.CREATE_X_AUDIT_MAP); - apiAssociatedWithUserAndGroups.add(RangerAPIList.CREATE_X_PERM_MAP); - apiAssociatedWithUserAndGroups.add(RangerAPIList.DELETE_X_AUDIT_MAP); - apiAssociatedWithUserAndGroups.add(RangerAPIList.DELETE_X_PERM_MAP); - apiAssociatedWithUserAndGroups.add(RangerAPIList.GET_X_AUDIT_MAP); - apiAssociatedWithUserAndGroups.add(RangerAPIList.GET_X_GROUP); - apiAssociatedWithUserAndGroups.add(RangerAPIList.GET_X_GROUP_BY_GROUP_NAME); - apiAssociatedWithUserAndGroups.add(RangerAPIList.GET_X_GROUP_USER); - apiAssociatedWithUserAndGroups.add(RangerAPIList.GET_X_GROUP_USERS); - apiAssociatedWithUserAndGroups.add(RangerAPIList.GET_X_PERM_MAP); - apiAssociatedWithUserAndGroups.add(RangerAPIList.GET_X_USER); - apiAssociatedWithUserAndGroups.add(RangerAPIList.GET_X_USER_BY_USER_NAME); - apiAssociatedWithUserAndGroups.add(RangerAPIList.GET_X_USER_GROUPS); - apiAssociatedWithUserAndGroups.add(RangerAPIList.MODIFY_GROUPS_VISIBILITY); - apiAssociatedWithUserAndGroups.add(RangerAPIList.MODIFY_USER_ACTIVE_STATUS); - apiAssociatedWithUserAndGroups.add(RangerAPIList.MODIFY_USER_VISIBILITY); - apiAssociatedWithUserAndGroups.add(RangerAPIList.SEARCH_X_AUDIT_MAPS); - apiAssociatedWithUserAndGroups.add(RangerAPIList.SEARCH_X_GROUPS); - apiAssociatedWithUserAndGroups.add(RangerAPIList.SEARCH_X_GROUP_USERS); - apiAssociatedWithUserAndGroups.add(RangerAPIList.SEARCH_X_PERM_MAPS); - apiAssociatedWithUserAndGroups.add(RangerAPIList.SEARCH_X_USERS); - apiAssociatedWithUserAndGroups.add(RangerAPIList.SECURE_GET_X_GROUP); - apiAssociatedWithUserAndGroups.add(RangerAPIList.SECURE_GET_X_USER); - apiAssociatedWithUserAndGroups.add(RangerAPIList.UPDATE_X_AUDIT_MAP); - apiAssociatedWithUserAndGroups.add(RangerAPIList.UPDATE_X_PERM_MAP); - - apiAssociatedWithUserAndGroups.add(RangerAPIList.CREATE); - apiAssociatedWithUserAndGroups.add(RangerAPIList.CREATE_DEFAULT_ACCOUNT_USER); - apiAssociatedWithUserAndGroups.add(RangerAPIList.UPDATE); - apiAssociatedWithUserAndGroups.add(RangerAPIList.SET_USER_ROLES); - apiAssociatedWithUserAndGroups.add(RangerAPIList.DEACTIVATE_USER); - apiAssociatedWithUserAndGroups.add(RangerAPIList.SET_USER_ROLES_BY_ID); - apiAssociatedWithUserAndGroups.add(RangerAPIList.SET_USER_ROLES_BY_NAME); - apiAssociatedWithUserAndGroups.add(RangerAPIList.GET_USER_ROLES_BY_ID); - apiAssociatedWithUserAndGroups.add(RangerAPIList.GET_USER_ROLES_BY_NAME); - - rangerAPIMappingWithUI.put(TAB_USERS_GROUPS, apiAssociatedWithUserAndGroups); - - for (String api : apiAssociatedWithUserAndGroups) { - if (mapApiToTabs.get(api) == null) { - mapApiToTabs.put(api, new HashSet()); - } - mapApiToTabs.get(api).add(TAB_USERS_GROUPS); - } - } - - private void mapAuditWithAPIs() { - - Set apiAssociatedWithAudit = new HashSet(); - - apiAssociatedWithAudit.add(RangerAPIList.COUNT_X_ASSETS); - apiAssociatedWithAudit.add(RangerAPIList.GET_X_ASSET); - apiAssociatedWithAudit.add(RangerAPIList.SEARCH_X_ASSETS); - - apiAssociatedWithAudit.add(RangerAPIList.COUNT_SERVICES); - apiAssociatedWithAudit.add(RangerAPIList.GET_POLICY_FOR_VERSION_NO); - apiAssociatedWithAudit.add(RangerAPIList.GET_POLICY_FROM_EVENT_TIME); - apiAssociatedWithAudit.add(RangerAPIList.GET_POLICY_VERSION_LIST); - apiAssociatedWithAudit.add(RangerAPIList.GET_PLUGINS_INFO); - apiAssociatedWithAudit.add(RangerAPIList.GET_SERVICE); - apiAssociatedWithAudit.add(RangerAPIList.GET_SERVICE_BY_NAME); - apiAssociatedWithAudit.add(RangerAPIList.GET_SERVICE_DEF); - apiAssociatedWithAudit.add(RangerAPIList.GET_SERVICE_DEF_BY_NAME); - apiAssociatedWithAudit.add(RangerAPIList.GET_SERVICE_DEFS); - apiAssociatedWithAudit.add(RangerAPIList.GET_SERVICES); - apiAssociatedWithAudit.add(RangerAPIList.GET_SERVICE_HEADERS); - apiAssociatedWithAudit.add(RangerAPIList.LOOKUP_RESOURCE); - - apiAssociatedWithAudit.add(RangerAPIList.GET_USER_PROFILE_FOR_USER); - apiAssociatedWithAudit.add(RangerAPIList.SEARCH_USERS); - - apiAssociatedWithAudit.add(RangerAPIList.COUNT_X_AUDIT_MAPS); - apiAssociatedWithAudit.add(RangerAPIList.COUNT_X_GROUPS); - apiAssociatedWithAudit.add(RangerAPIList.COUNT_X_GROUP_USERS); - apiAssociatedWithAudit.add(RangerAPIList.COUNT_X_PERM_MAPS); - apiAssociatedWithAudit.add(RangerAPIList.COUNT_X_USERS); - apiAssociatedWithAudit.add(RangerAPIList.GET_X_AUDIT_MAP); - apiAssociatedWithAudit.add(RangerAPIList.GET_X_GROUP); - apiAssociatedWithAudit.add(RangerAPIList.GET_X_GROUP_BY_GROUP_NAME); - apiAssociatedWithAudit.add(RangerAPIList.GET_X_GROUP_USER); - apiAssociatedWithAudit.add(RangerAPIList.GET_X_GROUP_USERS); - apiAssociatedWithAudit.add(RangerAPIList.GET_X_PERM_MAP); - apiAssociatedWithAudit.add(RangerAPIList.GET_X_USER); - apiAssociatedWithAudit.add(RangerAPIList.GET_X_USER_BY_USER_NAME); - apiAssociatedWithAudit.add(RangerAPIList.GET_X_USER_GROUPS); - apiAssociatedWithAudit.add(RangerAPIList.SEARCH_X_AUDIT_MAPS); - apiAssociatedWithAudit.add(RangerAPIList.SEARCH_X_GROUPS); - apiAssociatedWithAudit.add(RangerAPIList.SEARCH_X_GROUP_USERS); - apiAssociatedWithAudit.add(RangerAPIList.SEARCH_X_PERM_MAPS); - apiAssociatedWithAudit.add(RangerAPIList.SEARCH_X_USERS); - apiAssociatedWithAudit.add(RangerAPIList.SECURE_GET_X_GROUP); - apiAssociatedWithAudit.add(RangerAPIList.SECURE_GET_X_USER); - - apiAssociatedWithAudit.add(RangerAPIList.GET_X_TRX_LOG); - apiAssociatedWithAudit.add(RangerAPIList.CREATE_X_TRX_LOG); - apiAssociatedWithAudit.add(RangerAPIList.UPDATE_X_TRX_LOG); - apiAssociatedWithAudit.add(RangerAPIList.DELETE_X_TRX_LOG); - apiAssociatedWithAudit.add(RangerAPIList.SEARCH_X_TRX_LOG); - apiAssociatedWithAudit.add(RangerAPIList.COUNT_X_TRX_LOGS); - apiAssociatedWithAudit.add(RangerAPIList.SEARCH_X_ACCESS_AUDITS); - apiAssociatedWithAudit.add(RangerAPIList.COUNT_X_ACCESS_AUDITS); - apiAssociatedWithAudit.add(RangerAPIList.SEARCH_X_POLICY_EXPORT_AUDITS); - apiAssociatedWithAudit.add(RangerAPIList.GET_REPORT_LOGS); - apiAssociatedWithAudit.add(RangerAPIList.GET_TRANSACTION_REPORT); - apiAssociatedWithAudit.add(RangerAPIList.GET_ACCESS_LOGS); - apiAssociatedWithAudit.add(RangerAPIList.GET_AUTH_SESSION); - apiAssociatedWithAudit.add(RangerAPIList.GET_AUTH_SESSIONS); - - rangerAPIMappingWithUI.put(TAB_AUDIT, apiAssociatedWithAudit); - - for (String api : apiAssociatedWithAudit) { - if (mapApiToTabs.get(api) == null) { - mapApiToTabs.put(api, new HashSet()); - } - mapApiToTabs.get(api).add(TAB_AUDIT); - } - } - - private void mapResourceBasedPoliciesWithAPIs() { - Set apiAssociatedWithRBPolicies = new HashSet(); - - apiAssociatedWithRBPolicies.add(RangerAPIList.COUNT_X_ASSETS); - apiAssociatedWithRBPolicies.add(RangerAPIList.CREATE_X_ASSET); - apiAssociatedWithRBPolicies.add(RangerAPIList.DELETE_X_ASSET); - apiAssociatedWithRBPolicies.add(RangerAPIList.GET_X_ASSET); - apiAssociatedWithRBPolicies.add(RangerAPIList.SEARCH_X_ASSETS); - apiAssociatedWithRBPolicies.add(RangerAPIList.TEST_CONFIG); - apiAssociatedWithRBPolicies.add(RangerAPIList.UPDATE_X_ASSET); - - apiAssociatedWithRBPolicies.add(RangerAPIList.COUNT_SERVICES); - apiAssociatedWithRBPolicies.add(RangerAPIList.CREATE_SERVICE); - apiAssociatedWithRBPolicies.add(RangerAPIList.CREATE_SERVICE_DEF); - apiAssociatedWithRBPolicies.add(RangerAPIList.DELETE_SERVICE); - apiAssociatedWithRBPolicies.add(RangerAPIList.DELETE_SERVICE_DEF); - apiAssociatedWithRBPolicies.add(RangerAPIList.GET_POLICY_FOR_VERSION_NO); - apiAssociatedWithRBPolicies.add(RangerAPIList.GET_POLICY_FROM_EVENT_TIME); - apiAssociatedWithRBPolicies.add(RangerAPIList.GET_POLICY_VERSION_LIST); - apiAssociatedWithRBPolicies.add(RangerAPIList.GET_SERVICE); - apiAssociatedWithRBPolicies.add(RangerAPIList.GET_SERVICE_BY_NAME); - apiAssociatedWithRBPolicies.add(RangerAPIList.GET_SERVICE_DEF); - apiAssociatedWithRBPolicies.add(RangerAPIList.GET_SERVICE_DEF_BY_NAME); - apiAssociatedWithRBPolicies.add(RangerAPIList.GET_SERVICE_DEFS); - apiAssociatedWithRBPolicies.add(RangerAPIList.GET_SERVICES); - apiAssociatedWithRBPolicies.add(RangerAPIList.GET_SERVICE_HEADERS); - apiAssociatedWithRBPolicies.add(RangerAPIList.LOOKUP_RESOURCE); - apiAssociatedWithRBPolicies.add(RangerAPIList.UPDATE_SERVICE); - apiAssociatedWithRBPolicies.add(RangerAPIList.UPDATE_SERVICE_DEF); - apiAssociatedWithRBPolicies.add(RangerAPIList.VALIDATE_CONFIG); - - apiAssociatedWithRBPolicies.add(RangerAPIList.GET_USER_PROFILE_FOR_USER); - apiAssociatedWithRBPolicies.add(RangerAPIList.SEARCH_USERS); - - apiAssociatedWithRBPolicies.add(RangerAPIList.COUNT_X_AUDIT_MAPS); - apiAssociatedWithRBPolicies.add(RangerAPIList.COUNT_X_GROUPS); - apiAssociatedWithRBPolicies.add(RangerAPIList.COUNT_X_GROUP_USERS); - apiAssociatedWithRBPolicies.add(RangerAPIList.COUNT_X_PERM_MAPS); - apiAssociatedWithRBPolicies.add(RangerAPIList.COUNT_X_USERS); - apiAssociatedWithRBPolicies.add(RangerAPIList.CREATE_X_AUDIT_MAP); - apiAssociatedWithRBPolicies.add(RangerAPIList.CREATE_X_PERM_MAP); - apiAssociatedWithRBPolicies.add(RangerAPIList.DELETE_X_AUDIT_MAP); - apiAssociatedWithRBPolicies.add(RangerAPIList.DELETE_X_PERM_MAP); - apiAssociatedWithRBPolicies.add(RangerAPIList.GET_X_AUDIT_MAP); - apiAssociatedWithRBPolicies.add(RangerAPIList.GET_X_GROUP); - apiAssociatedWithRBPolicies.add(RangerAPIList.GET_X_GROUP_BY_GROUP_NAME); - apiAssociatedWithRBPolicies.add(RangerAPIList.GET_X_GROUP_USER); - apiAssociatedWithRBPolicies.add(RangerAPIList.GET_X_GROUP_USERS); - apiAssociatedWithRBPolicies.add(RangerAPIList.GET_X_PERM_MAP); - apiAssociatedWithRBPolicies.add(RangerAPIList.GET_X_USER); - apiAssociatedWithRBPolicies.add(RangerAPIList.GET_X_USER_BY_USER_NAME); - apiAssociatedWithRBPolicies.add(RangerAPIList.GET_X_USER_GROUPS); - apiAssociatedWithRBPolicies.add(RangerAPIList.MODIFY_GROUPS_VISIBILITY); - apiAssociatedWithRBPolicies.add(RangerAPIList.MODIFY_USER_ACTIVE_STATUS); - apiAssociatedWithRBPolicies.add(RangerAPIList.MODIFY_USER_VISIBILITY); - apiAssociatedWithRBPolicies.add(RangerAPIList.SEARCH_X_AUDIT_MAPS); - apiAssociatedWithRBPolicies.add(RangerAPIList.SEARCH_X_GROUPS); - apiAssociatedWithRBPolicies.add(RangerAPIList.SEARCH_X_GROUP_USERS); - apiAssociatedWithRBPolicies.add(RangerAPIList.SEARCH_X_PERM_MAPS); - apiAssociatedWithRBPolicies.add(RangerAPIList.SEARCH_X_USERS); - apiAssociatedWithRBPolicies.add(RangerAPIList.SECURE_GET_X_GROUP); - apiAssociatedWithRBPolicies.add(RangerAPIList.SECURE_GET_X_USER); - apiAssociatedWithRBPolicies.add(RangerAPIList.UPDATE_X_AUDIT_MAP); - apiAssociatedWithRBPolicies.add(RangerAPIList.UPDATE_X_PERM_MAP); - - apiAssociatedWithRBPolicies.add(RangerAPIList.CREATE); - apiAssociatedWithRBPolicies.add(RangerAPIList.CREATE_DEFAULT_ACCOUNT_USER); - apiAssociatedWithRBPolicies.add(RangerAPIList.UPDATE); - apiAssociatedWithRBPolicies.add(RangerAPIList.SET_USER_ROLES); - apiAssociatedWithRBPolicies.add(RangerAPIList.DEACTIVATE_USER); - - rangerAPIMappingWithUI.put(TAB_RESOURCE_BASED_POLICIES, apiAssociatedWithRBPolicies); - - for (String api : apiAssociatedWithRBPolicies) { - if (mapApiToTabs.get(api) == null) { - mapApiToTabs.put(api, new HashSet()); - } - mapApiToTabs.get(api).add(TAB_RESOURCE_BASED_POLICIES); - } - } - - private void mapGDSWithAPIs() { - Set apiAssociatedWithGDS = new HashSet(); - - apiAssociatedWithGDS.add(RangerAPIList.GET_DATASET_SUMMARY); - apiAssociatedWithGDS.add(RangerAPIList.CREATE_DATASET); - apiAssociatedWithGDS.add(RangerAPIList.UPDATE_DATASET); - apiAssociatedWithGDS.add(RangerAPIList.DELETE_DATASET); - apiAssociatedWithGDS.add(RangerAPIList.GET_DATASET); - apiAssociatedWithGDS.add(RangerAPIList.SEARCH_DATASETS); - apiAssociatedWithGDS.add(RangerAPIList.LIST_DATASET_NAMES); - apiAssociatedWithGDS.add(RangerAPIList.DATASET_POLICY); - - apiAssociatedWithGDS.add(RangerAPIList.CREATE_PROJECT); - apiAssociatedWithGDS.add(RangerAPIList.UPDATE_PROJECT); - apiAssociatedWithGDS.add(RangerAPIList.DELETE_PROJECT); - apiAssociatedWithGDS.add(RangerAPIList.GET_PROJECT); - apiAssociatedWithGDS.add(RangerAPIList.SEARCH_PROJECTS); - apiAssociatedWithGDS.add(RangerAPIList.LIST_PROJECT_NAMES); - apiAssociatedWithGDS.add(RangerAPIList.PROJECT_POLICY); - - apiAssociatedWithGDS.add(RangerAPIList.CREATE_DATA_SHARE); - apiAssociatedWithGDS.add(RangerAPIList.UPDATE_DATA_SHARE); - apiAssociatedWithGDS.add(RangerAPIList.DELETE_DATA_SHARE); - apiAssociatedWithGDS.add(RangerAPIList.GET_DATA_SHARE); - apiAssociatedWithGDS.add(RangerAPIList.SEARCH_DATA_SHARES); - apiAssociatedWithGDS.add(RangerAPIList.GET_DATA_SHARE_SUMMARY); - - apiAssociatedWithGDS.add(RangerAPIList.ADD_SHARED_RESOURCE); - apiAssociatedWithGDS.add(RangerAPIList.ADD_SHARED_RESOURCES); - apiAssociatedWithGDS.add(RangerAPIList.UPDATE_SHARED_RESOURCE); - apiAssociatedWithGDS.add(RangerAPIList.REMOVE_SHARED_RESOURCE); - apiAssociatedWithGDS.add(RangerAPIList.REMOVE_SHARED_RESOURCES); - apiAssociatedWithGDS.add(RangerAPIList.GET_SHARED_RESOURCE); - apiAssociatedWithGDS.add(RangerAPIList.SEARCH_SHARED_RESOURCES); - - apiAssociatedWithGDS.add(RangerAPIList.ADD_DATASHARE_IN_DATASET); - apiAssociatedWithGDS.add(RangerAPIList.UPDATE_DATASHARE_IN_DATASET); - apiAssociatedWithGDS.add(RangerAPIList.REMOVE_DATASHARE_IN_DATASET); - apiAssociatedWithGDS.add(RangerAPIList.GET_DATASHARE_IN_DATASET); - apiAssociatedWithGDS.add(RangerAPIList.SEARCH_DATASHARE_IN_DATASET); - apiAssociatedWithGDS.add(RangerAPIList.SEARCH_DATASHARE_IN_DATASET_SUMMARY); - - apiAssociatedWithGDS.add(RangerAPIList.ADD_DATASET_IN_PROJECT); - apiAssociatedWithGDS.add(RangerAPIList.UPDATE_DATASET_IN_PROJECT); - apiAssociatedWithGDS.add(RangerAPIList.REMOVE_DATASET_IN_PROJECT); - apiAssociatedWithGDS.add(RangerAPIList.GET_DATASET_IN_PROJECT); - apiAssociatedWithGDS.add(RangerAPIList.SEARCH_DATASET_IN_PROJECT); - - apiAssociatedWithGDS.add(RangerAPIList.GET_DATASET_GRANTS); - apiAssociatedWithGDS.add(RangerAPIList.UPDATE_DATASET_GRANTS); - apiAssociatedWithGDS.add(RangerAPIList.GET_SERVICE_HEADERS); - - rangerAPIMappingWithUI.put(TAB_GDS, apiAssociatedWithGDS); - - for (String api : apiAssociatedWithGDS) { - if (mapApiToTabs.get(api) == null) { - mapApiToTabs.put(api, new HashSet()); - } - mapApiToTabs.get(api).add(TAB_GDS); - } - } - - - - // * Utility methods starts from here, to retrieve API-UItab mapping information * - - public Set getAvailableUITabs() { - if (CollectionUtils.isEmpty(tabList)) { - populateAvailableUITabs(); - } - return tabList; - } - - /** - * @param apiName - * @return - * - * @Note: apiName being passed to this function should strictly follow this format: {ClassName}.{apiMethodName} and also API should be listed into - * RangerAPIList and should be mapped properly with UI tabs in the current class. - */ - public Set getAssociatedTabsWithAPI(String apiName) { - Set associatedTabs = mapApiToTabs.get(apiName); - return associatedTabs; - } + /** + * @NOTE While adding new tab here, please don't forget to update the function: + * org.apache.ranger.security.context.RangerAPIMapping.getAvailableUITabs() + */ + public static final String TAB_RESOURCE_BASED_POLICIES = "Resource Based Policies"; + public static final String TAB_AUDIT = "Audit"; + public static final String TAB_USERS_GROUPS = "Users/Groups"; + public static final String TAB_PERMISSIONS = "Permissions"; + public static final String TAB_KEY_MANAGER = "Key Manager"; + public static final String TAB_TAG_BASED_POLICIES = "Tag Based Policies"; + public static final String TAB_REPORTS = "Reports"; + public static final String TAB_GDS = "Governed Data Sharing"; + private static HashMap> rangerAPIMappingWithUI; + private static Set tabList = new HashSet<>(); + private static Map> mapApiToTabs; + + public RangerAPIMapping() { + init(); + } + + public Set getAvailableUITabs() { + if (CollectionUtils.isEmpty(tabList)) { + populateAvailableUITabs(); + } + return tabList; + } + + /** + * @param apiName + * @return + * @Note: apiName being passed to this function should strictly follow this format: {ClassName}.{apiMethodName} and also API should be listed into + * RangerAPIList and should be mapped properly with UI tabs in the current class. + */ + public Set getAssociatedTabsWithAPI(String apiName) { + return mapApiToTabs.get(apiName); + } + + private void init() { + if (rangerAPIMappingWithUI == null) { + rangerAPIMappingWithUI = new HashMap<>(); + } + if (mapApiToTabs == null) { + mapApiToTabs = new HashMap<>(); + } + + mapResourceBasedPoliciesWithAPIs(); + mapAuditWithAPIs(); + mapUGWithAPIs(); + mapPermissionsWithAPIs(); + mapKeyManagerWithAPIs(); + mapTagBasedPoliciesWithAPIs(); + mapReportsWithAPIs(); + mapGDSWithAPIs(); + + if (CollectionUtils.isEmpty(tabList)) { + populateAvailableUITabs(); + } + } + + private void populateAvailableUITabs() { + tabList = new HashSet<>(); + tabList.add(TAB_RESOURCE_BASED_POLICIES); + tabList.add(TAB_TAG_BASED_POLICIES); + tabList.add(TAB_AUDIT); + tabList.add(TAB_REPORTS); + tabList.add(TAB_KEY_MANAGER); + tabList.add(TAB_PERMISSIONS); + tabList.add(TAB_USERS_GROUPS); + tabList.add(TAB_GDS); + } + + private void mapReportsWithAPIs() { + Set apiAssociatedWithReports = new HashSet<>(); + + apiAssociatedWithReports.add(RangerAPIList.COUNT_X_ASSETS); + apiAssociatedWithReports.add(RangerAPIList.GET_X_ASSET); + apiAssociatedWithReports.add(RangerAPIList.SEARCH_X_ASSETS); + + apiAssociatedWithReports.add(RangerAPIList.COUNT_SERVICES); + apiAssociatedWithReports.add(RangerAPIList.GET_POLICY_FOR_VERSION_NO); + apiAssociatedWithReports.add(RangerAPIList.GET_POLICY_FROM_EVENT_TIME); + apiAssociatedWithReports.add(RangerAPIList.GET_POLICY_VERSION_LIST); + apiAssociatedWithReports.add(RangerAPIList.GET_SERVICE); + apiAssociatedWithReports.add(RangerAPIList.GET_SERVICE_BY_NAME); + apiAssociatedWithReports.add(RangerAPIList.GET_SERVICE_DEF); + apiAssociatedWithReports.add(RangerAPIList.GET_SERVICE_DEF_BY_NAME); + apiAssociatedWithReports.add(RangerAPIList.GET_SERVICE_DEFS); + apiAssociatedWithReports.add(RangerAPIList.GET_SERVICES); + apiAssociatedWithReports.add(RangerAPIList.GET_SERVICE_HEADERS); + apiAssociatedWithReports.add(RangerAPIList.LOOKUP_RESOURCE); + + apiAssociatedWithReports.add(RangerAPIList.GET_USER_PROFILE_FOR_USER); + apiAssociatedWithReports.add(RangerAPIList.SEARCH_USERS); + + apiAssociatedWithReports.add(RangerAPIList.COUNT_X_AUDIT_MAPS); + apiAssociatedWithReports.add(RangerAPIList.COUNT_X_GROUPS); + apiAssociatedWithReports.add(RangerAPIList.COUNT_X_GROUP_USERS); + apiAssociatedWithReports.add(RangerAPIList.COUNT_X_PERM_MAPS); + apiAssociatedWithReports.add(RangerAPIList.COUNT_X_USERS); + apiAssociatedWithReports.add(RangerAPIList.GET_X_AUDIT_MAP); + apiAssociatedWithReports.add(RangerAPIList.GET_X_GROUP); + apiAssociatedWithReports.add(RangerAPIList.GET_X_GROUP_BY_GROUP_NAME); + apiAssociatedWithReports.add(RangerAPIList.GET_X_GROUP_USER); + apiAssociatedWithReports.add(RangerAPIList.GET_X_GROUP_USERS); + apiAssociatedWithReports.add(RangerAPIList.GET_X_PERM_MAP); + apiAssociatedWithReports.add(RangerAPIList.GET_X_USER); + apiAssociatedWithReports.add(RangerAPIList.GET_X_USER_BY_USER_NAME); + apiAssociatedWithReports.add(RangerAPIList.GET_X_USER_GROUPS); + apiAssociatedWithReports.add(RangerAPIList.SEARCH_X_AUDIT_MAPS); + apiAssociatedWithReports.add(RangerAPIList.SEARCH_X_GROUPS); + apiAssociatedWithReports.add(RangerAPIList.SEARCH_X_GROUP_USERS); + apiAssociatedWithReports.add(RangerAPIList.SEARCH_X_PERM_MAPS); + apiAssociatedWithReports.add(RangerAPIList.SEARCH_X_USERS); + apiAssociatedWithReports.add(RangerAPIList.SECURE_GET_X_GROUP); + apiAssociatedWithReports.add(RangerAPIList.SECURE_GET_X_USER); + + rangerAPIMappingWithUI.put(TAB_REPORTS, apiAssociatedWithReports); + + for (String api : apiAssociatedWithReports) { + Set tabs = mapApiToTabs.computeIfAbsent(api, k -> new HashSet<>()); + + tabs.add(TAB_REPORTS); + } + } + + private void mapTagBasedPoliciesWithAPIs() { + Set apiAssociatedWithTagBasedPolicy = new HashSet<>(); + + apiAssociatedWithTagBasedPolicy.add(RangerAPIList.COUNT_X_ASSETS); + apiAssociatedWithTagBasedPolicy.add(RangerAPIList.CREATE_X_ASSET); + apiAssociatedWithTagBasedPolicy.add(RangerAPIList.DELETE_X_ASSET); + apiAssociatedWithTagBasedPolicy.add(RangerAPIList.GET_X_ASSET); + apiAssociatedWithTagBasedPolicy.add(RangerAPIList.SEARCH_X_ASSETS); + apiAssociatedWithTagBasedPolicy.add(RangerAPIList.TEST_CONFIG); + apiAssociatedWithTagBasedPolicy.add(RangerAPIList.UPDATE_X_ASSET); + + apiAssociatedWithTagBasedPolicy.add(RangerAPIList.COUNT_SERVICES); + apiAssociatedWithTagBasedPolicy.add(RangerAPIList.CREATE_SERVICE); + apiAssociatedWithTagBasedPolicy.add(RangerAPIList.CREATE_SERVICE_DEF); + apiAssociatedWithTagBasedPolicy.add(RangerAPIList.DELETE_SERVICE); + apiAssociatedWithTagBasedPolicy.add(RangerAPIList.DELETE_SERVICE_DEF); + apiAssociatedWithTagBasedPolicy.add(RangerAPIList.GET_POLICY_FOR_VERSION_NO); + apiAssociatedWithTagBasedPolicy.add(RangerAPIList.GET_POLICY_FROM_EVENT_TIME); + apiAssociatedWithTagBasedPolicy.add(RangerAPIList.GET_POLICY_VERSION_LIST); + apiAssociatedWithTagBasedPolicy.add(RangerAPIList.GET_SERVICE); + apiAssociatedWithTagBasedPolicy.add(RangerAPIList.GET_SERVICE_BY_NAME); + apiAssociatedWithTagBasedPolicy.add(RangerAPIList.GET_SERVICE_DEF); + apiAssociatedWithTagBasedPolicy.add(RangerAPIList.GET_SERVICE_DEF_BY_NAME); + apiAssociatedWithTagBasedPolicy.add(RangerAPIList.GET_SERVICE_DEFS); + apiAssociatedWithTagBasedPolicy.add(RangerAPIList.GET_SERVICES); + apiAssociatedWithTagBasedPolicy.add(RangerAPIList.GET_SERVICE_HEADERS); + apiAssociatedWithTagBasedPolicy.add(RangerAPIList.LOOKUP_RESOURCE); + apiAssociatedWithTagBasedPolicy.add(RangerAPIList.UPDATE_SERVICE); + apiAssociatedWithTagBasedPolicy.add(RangerAPIList.UPDATE_SERVICE_DEF); + apiAssociatedWithTagBasedPolicy.add(RangerAPIList.VALIDATE_CONFIG); + + apiAssociatedWithTagBasedPolicy.add(RangerAPIList.GET_USER_PROFILE_FOR_USER); + apiAssociatedWithTagBasedPolicy.add(RangerAPIList.SEARCH_USERS); + + apiAssociatedWithTagBasedPolicy.add(RangerAPIList.COUNT_X_AUDIT_MAPS); + apiAssociatedWithTagBasedPolicy.add(RangerAPIList.COUNT_X_GROUPS); + apiAssociatedWithTagBasedPolicy.add(RangerAPIList.COUNT_X_GROUP_USERS); + apiAssociatedWithTagBasedPolicy.add(RangerAPIList.COUNT_X_PERM_MAPS); + apiAssociatedWithTagBasedPolicy.add(RangerAPIList.COUNT_X_USERS); + apiAssociatedWithTagBasedPolicy.add(RangerAPIList.CREATE_X_AUDIT_MAP); + apiAssociatedWithTagBasedPolicy.add(RangerAPIList.CREATE_X_PERM_MAP); + apiAssociatedWithTagBasedPolicy.add(RangerAPIList.DELETE_X_AUDIT_MAP); + apiAssociatedWithTagBasedPolicy.add(RangerAPIList.DELETE_X_PERM_MAP); + apiAssociatedWithTagBasedPolicy.add(RangerAPIList.GET_X_AUDIT_MAP); + apiAssociatedWithTagBasedPolicy.add(RangerAPIList.GET_X_GROUP); + apiAssociatedWithTagBasedPolicy.add(RangerAPIList.GET_X_GROUP_BY_GROUP_NAME); + apiAssociatedWithTagBasedPolicy.add(RangerAPIList.GET_X_GROUP_USER); + apiAssociatedWithTagBasedPolicy.add(RangerAPIList.GET_X_GROUP_USERS); + apiAssociatedWithTagBasedPolicy.add(RangerAPIList.GET_X_PERM_MAP); + apiAssociatedWithTagBasedPolicy.add(RangerAPIList.GET_X_USER); + apiAssociatedWithTagBasedPolicy.add(RangerAPIList.GET_X_USER_BY_USER_NAME); + apiAssociatedWithTagBasedPolicy.add(RangerAPIList.GET_X_USER_GROUPS); + apiAssociatedWithTagBasedPolicy.add(RangerAPIList.MODIFY_GROUPS_VISIBILITY); + apiAssociatedWithTagBasedPolicy.add(RangerAPIList.MODIFY_USER_ACTIVE_STATUS); + apiAssociatedWithTagBasedPolicy.add(RangerAPIList.MODIFY_USER_VISIBILITY); + apiAssociatedWithTagBasedPolicy.add(RangerAPIList.SEARCH_X_AUDIT_MAPS); + apiAssociatedWithTagBasedPolicy.add(RangerAPIList.SEARCH_X_GROUPS); + apiAssociatedWithTagBasedPolicy.add(RangerAPIList.SEARCH_X_GROUP_USERS); + apiAssociatedWithTagBasedPolicy.add(RangerAPIList.SEARCH_X_PERM_MAPS); + apiAssociatedWithTagBasedPolicy.add(RangerAPIList.SEARCH_X_USERS); + apiAssociatedWithTagBasedPolicy.add(RangerAPIList.SECURE_GET_X_GROUP); + apiAssociatedWithTagBasedPolicy.add(RangerAPIList.SECURE_GET_X_USER); + apiAssociatedWithTagBasedPolicy.add(RangerAPIList.UPDATE_X_AUDIT_MAP); + apiAssociatedWithTagBasedPolicy.add(RangerAPIList.UPDATE_X_PERM_MAP); + + apiAssociatedWithTagBasedPolicy.add(RangerAPIList.CREATE); + apiAssociatedWithTagBasedPolicy.add(RangerAPIList.CREATE_DEFAULT_ACCOUNT_USER); + apiAssociatedWithTagBasedPolicy.add(RangerAPIList.UPDATE); + apiAssociatedWithTagBasedPolicy.add(RangerAPIList.SET_USER_ROLES); + apiAssociatedWithTagBasedPolicy.add(RangerAPIList.DEACTIVATE_USER); + + rangerAPIMappingWithUI.put(TAB_TAG_BASED_POLICIES, apiAssociatedWithTagBasedPolicy); + + for (String api : apiAssociatedWithTagBasedPolicy) { + Set tabs = mapApiToTabs.computeIfAbsent(api, k -> new HashSet<>()); + + tabs.add(TAB_TAG_BASED_POLICIES); + } + } + + private void mapKeyManagerWithAPIs() { + Set apiAssociatedWithKeyManager = new HashSet<>(); + + apiAssociatedWithKeyManager.add(RangerAPIList.COUNT_X_ASSETS); + apiAssociatedWithKeyManager.add(RangerAPIList.CREATE_X_ASSET); + apiAssociatedWithKeyManager.add(RangerAPIList.DELETE_X_ASSET); + apiAssociatedWithKeyManager.add(RangerAPIList.GET_X_ASSET); + apiAssociatedWithKeyManager.add(RangerAPIList.SEARCH_X_ASSETS); + apiAssociatedWithKeyManager.add(RangerAPIList.TEST_CONFIG); + apiAssociatedWithKeyManager.add(RangerAPIList.UPDATE_X_ASSET); + + apiAssociatedWithKeyManager.add(RangerAPIList.COUNT_SERVICES); + apiAssociatedWithKeyManager.add(RangerAPIList.CREATE_SERVICE); + apiAssociatedWithKeyManager.add(RangerAPIList.CREATE_SERVICE_DEF); + apiAssociatedWithKeyManager.add(RangerAPIList.DELETE_SERVICE); + apiAssociatedWithKeyManager.add(RangerAPIList.DELETE_SERVICE_DEF); + apiAssociatedWithKeyManager.add(RangerAPIList.GET_POLICY_FOR_VERSION_NO); + apiAssociatedWithKeyManager.add(RangerAPIList.GET_POLICY_FROM_EVENT_TIME); + apiAssociatedWithKeyManager.add(RangerAPIList.GET_POLICY_VERSION_LIST); + apiAssociatedWithKeyManager.add(RangerAPIList.GET_SERVICE); + apiAssociatedWithKeyManager.add(RangerAPIList.GET_SERVICE_BY_NAME); + apiAssociatedWithKeyManager.add(RangerAPIList.GET_SERVICE_DEF); + apiAssociatedWithKeyManager.add(RangerAPIList.GET_SERVICE_DEF_BY_NAME); + apiAssociatedWithKeyManager.add(RangerAPIList.GET_SERVICE_DEFS); + apiAssociatedWithKeyManager.add(RangerAPIList.GET_SERVICES); + apiAssociatedWithKeyManager.add(RangerAPIList.GET_SERVICE_HEADERS); + apiAssociatedWithKeyManager.add(RangerAPIList.LOOKUP_RESOURCE); + apiAssociatedWithKeyManager.add(RangerAPIList.UPDATE_SERVICE); + apiAssociatedWithKeyManager.add(RangerAPIList.UPDATE_SERVICE_DEF); + apiAssociatedWithKeyManager.add(RangerAPIList.VALIDATE_CONFIG); + + apiAssociatedWithKeyManager.add(RangerAPIList.CREATE_KEY); + apiAssociatedWithKeyManager.add(RangerAPIList.DELETE_KEY); + apiAssociatedWithKeyManager.add(RangerAPIList.GET_KEY); + apiAssociatedWithKeyManager.add(RangerAPIList.ROLLOVER_KEYS); + apiAssociatedWithKeyManager.add(RangerAPIList.SEARCH_KEYS); + + rangerAPIMappingWithUI.put(TAB_KEY_MANAGER, apiAssociatedWithKeyManager); + + for (String api : apiAssociatedWithKeyManager) { + Set tabs = mapApiToTabs.computeIfAbsent(api, k -> new HashSet<>()); + + tabs.add(TAB_KEY_MANAGER); + } + } + + private void mapPermissionsWithAPIs() { + Set apiAssociatedWithPermissions = new HashSet<>(); + + apiAssociatedWithPermissions.add(RangerAPIList.COUNT_X_GROUP_PERMISSION); + apiAssociatedWithPermissions.add(RangerAPIList.COUNT_X_MODULE_DEF); + apiAssociatedWithPermissions.add(RangerAPIList.COUNT_X_USER_PERMISSION); + apiAssociatedWithPermissions.add(RangerAPIList.CREATE_X_GROUP_PERMISSION); + apiAssociatedWithPermissions.add(RangerAPIList.CREATE_X_MODULE_DEF_PERMISSION); + apiAssociatedWithPermissions.add(RangerAPIList.CREATE_X_USER_PERMISSION); + apiAssociatedWithPermissions.add(RangerAPIList.DELETE_X_GROUP_PERMISSION); + apiAssociatedWithPermissions.add(RangerAPIList.DELETE_X_MODULE_DEF_PERMISSION); + apiAssociatedWithPermissions.add(RangerAPIList.DELETE_X_USER_PERMISSION); + apiAssociatedWithPermissions.add(RangerAPIList.GET_X_GROUP_PERMISSION); + apiAssociatedWithPermissions.add(RangerAPIList.GET_X_MODULE_DEF_PERMISSION); + apiAssociatedWithPermissions.add(RangerAPIList.GET_X_USER_PERMISSION); + apiAssociatedWithPermissions.add(RangerAPIList.SEARCH_X_GROUP_PERMISSION); + apiAssociatedWithPermissions.add(RangerAPIList.SEARCH_X_MODULE_DEF); + apiAssociatedWithPermissions.add(RangerAPIList.SEARCH_X_USER_PERMISSION); + apiAssociatedWithPermissions.add(RangerAPIList.UPDATE_X_GROUP_PERMISSION); + apiAssociatedWithPermissions.add(RangerAPIList.UPDATE_X_MODULE_DEF_PERMISSION); + apiAssociatedWithPermissions.add(RangerAPIList.UPDATE_X_USER_PERMISSION); + + rangerAPIMappingWithUI.put(TAB_PERMISSIONS, apiAssociatedWithPermissions); + + for (String api : apiAssociatedWithPermissions) { + Set tabs = mapApiToTabs.computeIfAbsent(api, k -> new HashSet<>()); + + tabs.add(TAB_PERMISSIONS); + } + } + + private void mapUGWithAPIs() { + Set apiAssociatedWithUserAndGroups = new HashSet<>(); + + apiAssociatedWithUserAndGroups.add(RangerAPIList.GET_USER_PROFILE_FOR_USER); + apiAssociatedWithUserAndGroups.add(RangerAPIList.SEARCH_USERS); + + apiAssociatedWithUserAndGroups.add(RangerAPIList.COUNT_X_AUDIT_MAPS); + apiAssociatedWithUserAndGroups.add(RangerAPIList.COUNT_X_GROUPS); + apiAssociatedWithUserAndGroups.add(RangerAPIList.COUNT_X_GROUP_USERS); + apiAssociatedWithUserAndGroups.add(RangerAPIList.COUNT_X_PERM_MAPS); + apiAssociatedWithUserAndGroups.add(RangerAPIList.COUNT_X_USERS); + apiAssociatedWithUserAndGroups.add(RangerAPIList.CREATE_X_AUDIT_MAP); + apiAssociatedWithUserAndGroups.add(RangerAPIList.CREATE_X_PERM_MAP); + apiAssociatedWithUserAndGroups.add(RangerAPIList.DELETE_X_AUDIT_MAP); + apiAssociatedWithUserAndGroups.add(RangerAPIList.DELETE_X_PERM_MAP); + apiAssociatedWithUserAndGroups.add(RangerAPIList.GET_X_AUDIT_MAP); + apiAssociatedWithUserAndGroups.add(RangerAPIList.GET_X_GROUP); + apiAssociatedWithUserAndGroups.add(RangerAPIList.GET_X_GROUP_BY_GROUP_NAME); + apiAssociatedWithUserAndGroups.add(RangerAPIList.GET_X_GROUP_USER); + apiAssociatedWithUserAndGroups.add(RangerAPIList.GET_X_GROUP_USERS); + apiAssociatedWithUserAndGroups.add(RangerAPIList.GET_X_PERM_MAP); + apiAssociatedWithUserAndGroups.add(RangerAPIList.GET_X_USER); + apiAssociatedWithUserAndGroups.add(RangerAPIList.GET_X_USER_BY_USER_NAME); + apiAssociatedWithUserAndGroups.add(RangerAPIList.GET_X_USER_GROUPS); + apiAssociatedWithUserAndGroups.add(RangerAPIList.MODIFY_GROUPS_VISIBILITY); + apiAssociatedWithUserAndGroups.add(RangerAPIList.MODIFY_USER_ACTIVE_STATUS); + apiAssociatedWithUserAndGroups.add(RangerAPIList.MODIFY_USER_VISIBILITY); + apiAssociatedWithUserAndGroups.add(RangerAPIList.SEARCH_X_AUDIT_MAPS); + apiAssociatedWithUserAndGroups.add(RangerAPIList.SEARCH_X_GROUPS); + apiAssociatedWithUserAndGroups.add(RangerAPIList.SEARCH_X_GROUP_USERS); + apiAssociatedWithUserAndGroups.add(RangerAPIList.SEARCH_X_PERM_MAPS); + apiAssociatedWithUserAndGroups.add(RangerAPIList.SEARCH_X_USERS); + apiAssociatedWithUserAndGroups.add(RangerAPIList.SECURE_GET_X_GROUP); + apiAssociatedWithUserAndGroups.add(RangerAPIList.SECURE_GET_X_USER); + apiAssociatedWithUserAndGroups.add(RangerAPIList.UPDATE_X_AUDIT_MAP); + apiAssociatedWithUserAndGroups.add(RangerAPIList.UPDATE_X_PERM_MAP); + + apiAssociatedWithUserAndGroups.add(RangerAPIList.CREATE); + apiAssociatedWithUserAndGroups.add(RangerAPIList.CREATE_DEFAULT_ACCOUNT_USER); + apiAssociatedWithUserAndGroups.add(RangerAPIList.UPDATE); + apiAssociatedWithUserAndGroups.add(RangerAPIList.SET_USER_ROLES); + apiAssociatedWithUserAndGroups.add(RangerAPIList.DEACTIVATE_USER); + apiAssociatedWithUserAndGroups.add(RangerAPIList.SET_USER_ROLES_BY_ID); + apiAssociatedWithUserAndGroups.add(RangerAPIList.SET_USER_ROLES_BY_NAME); + apiAssociatedWithUserAndGroups.add(RangerAPIList.GET_USER_ROLES_BY_ID); + apiAssociatedWithUserAndGroups.add(RangerAPIList.GET_USER_ROLES_BY_NAME); + + rangerAPIMappingWithUI.put(TAB_USERS_GROUPS, apiAssociatedWithUserAndGroups); + + for (String api : apiAssociatedWithUserAndGroups) { + Set tabs = mapApiToTabs.computeIfAbsent(api, k -> new HashSet<>()); + + tabs.add(TAB_USERS_GROUPS); + } + } + + private void mapAuditWithAPIs() { + Set apiAssociatedWithAudit = new HashSet<>(); + + apiAssociatedWithAudit.add(RangerAPIList.COUNT_X_ASSETS); + apiAssociatedWithAudit.add(RangerAPIList.GET_X_ASSET); + apiAssociatedWithAudit.add(RangerAPIList.SEARCH_X_ASSETS); + + apiAssociatedWithAudit.add(RangerAPIList.COUNT_SERVICES); + apiAssociatedWithAudit.add(RangerAPIList.GET_POLICY_FOR_VERSION_NO); + apiAssociatedWithAudit.add(RangerAPIList.GET_POLICY_FROM_EVENT_TIME); + apiAssociatedWithAudit.add(RangerAPIList.GET_POLICY_VERSION_LIST); + apiAssociatedWithAudit.add(RangerAPIList.GET_PLUGINS_INFO); + apiAssociatedWithAudit.add(RangerAPIList.GET_SERVICE); + apiAssociatedWithAudit.add(RangerAPIList.GET_SERVICE_BY_NAME); + apiAssociatedWithAudit.add(RangerAPIList.GET_SERVICE_DEF); + apiAssociatedWithAudit.add(RangerAPIList.GET_SERVICE_DEF_BY_NAME); + apiAssociatedWithAudit.add(RangerAPIList.GET_SERVICE_DEFS); + apiAssociatedWithAudit.add(RangerAPIList.GET_SERVICES); + apiAssociatedWithAudit.add(RangerAPIList.GET_SERVICE_HEADERS); + apiAssociatedWithAudit.add(RangerAPIList.LOOKUP_RESOURCE); + + apiAssociatedWithAudit.add(RangerAPIList.GET_USER_PROFILE_FOR_USER); + apiAssociatedWithAudit.add(RangerAPIList.SEARCH_USERS); + + apiAssociatedWithAudit.add(RangerAPIList.COUNT_X_AUDIT_MAPS); + apiAssociatedWithAudit.add(RangerAPIList.COUNT_X_GROUPS); + apiAssociatedWithAudit.add(RangerAPIList.COUNT_X_GROUP_USERS); + apiAssociatedWithAudit.add(RangerAPIList.COUNT_X_PERM_MAPS); + apiAssociatedWithAudit.add(RangerAPIList.COUNT_X_USERS); + apiAssociatedWithAudit.add(RangerAPIList.GET_X_AUDIT_MAP); + apiAssociatedWithAudit.add(RangerAPIList.GET_X_GROUP); + apiAssociatedWithAudit.add(RangerAPIList.GET_X_GROUP_BY_GROUP_NAME); + apiAssociatedWithAudit.add(RangerAPIList.GET_X_GROUP_USER); + apiAssociatedWithAudit.add(RangerAPIList.GET_X_GROUP_USERS); + apiAssociatedWithAudit.add(RangerAPIList.GET_X_PERM_MAP); + apiAssociatedWithAudit.add(RangerAPIList.GET_X_USER); + apiAssociatedWithAudit.add(RangerAPIList.GET_X_USER_BY_USER_NAME); + apiAssociatedWithAudit.add(RangerAPIList.GET_X_USER_GROUPS); + apiAssociatedWithAudit.add(RangerAPIList.SEARCH_X_AUDIT_MAPS); + apiAssociatedWithAudit.add(RangerAPIList.SEARCH_X_GROUPS); + apiAssociatedWithAudit.add(RangerAPIList.SEARCH_X_GROUP_USERS); + apiAssociatedWithAudit.add(RangerAPIList.SEARCH_X_PERM_MAPS); + apiAssociatedWithAudit.add(RangerAPIList.SEARCH_X_USERS); + apiAssociatedWithAudit.add(RangerAPIList.SECURE_GET_X_GROUP); + apiAssociatedWithAudit.add(RangerAPIList.SECURE_GET_X_USER); + + apiAssociatedWithAudit.add(RangerAPIList.GET_X_TRX_LOG); + apiAssociatedWithAudit.add(RangerAPIList.CREATE_X_TRX_LOG); + apiAssociatedWithAudit.add(RangerAPIList.UPDATE_X_TRX_LOG); + apiAssociatedWithAudit.add(RangerAPIList.DELETE_X_TRX_LOG); + apiAssociatedWithAudit.add(RangerAPIList.SEARCH_X_TRX_LOG); + apiAssociatedWithAudit.add(RangerAPIList.COUNT_X_TRX_LOGS); + apiAssociatedWithAudit.add(RangerAPIList.SEARCH_X_ACCESS_AUDITS); + apiAssociatedWithAudit.add(RangerAPIList.COUNT_X_ACCESS_AUDITS); + apiAssociatedWithAudit.add(RangerAPIList.SEARCH_X_POLICY_EXPORT_AUDITS); + apiAssociatedWithAudit.add(RangerAPIList.GET_REPORT_LOGS); + apiAssociatedWithAudit.add(RangerAPIList.GET_TRANSACTION_REPORT); + apiAssociatedWithAudit.add(RangerAPIList.GET_ACCESS_LOGS); + apiAssociatedWithAudit.add(RangerAPIList.GET_AUTH_SESSION); + apiAssociatedWithAudit.add(RangerAPIList.GET_AUTH_SESSIONS); + + rangerAPIMappingWithUI.put(TAB_AUDIT, apiAssociatedWithAudit); + + for (String api : apiAssociatedWithAudit) { + Set tabs = mapApiToTabs.computeIfAbsent(api, k -> new HashSet<>()); + + tabs.add(TAB_AUDIT); + } + } + + // * Utility methods starts from here, to retrieve API-UItab mapping information * + + private void mapResourceBasedPoliciesWithAPIs() { + Set apiAssociatedWithRBPolicies = new HashSet<>(); + + apiAssociatedWithRBPolicies.add(RangerAPIList.COUNT_X_ASSETS); + apiAssociatedWithRBPolicies.add(RangerAPIList.CREATE_X_ASSET); + apiAssociatedWithRBPolicies.add(RangerAPIList.DELETE_X_ASSET); + apiAssociatedWithRBPolicies.add(RangerAPIList.GET_X_ASSET); + apiAssociatedWithRBPolicies.add(RangerAPIList.SEARCH_X_ASSETS); + apiAssociatedWithRBPolicies.add(RangerAPIList.TEST_CONFIG); + apiAssociatedWithRBPolicies.add(RangerAPIList.UPDATE_X_ASSET); + + apiAssociatedWithRBPolicies.add(RangerAPIList.COUNT_SERVICES); + apiAssociatedWithRBPolicies.add(RangerAPIList.CREATE_SERVICE); + apiAssociatedWithRBPolicies.add(RangerAPIList.CREATE_SERVICE_DEF); + apiAssociatedWithRBPolicies.add(RangerAPIList.DELETE_SERVICE); + apiAssociatedWithRBPolicies.add(RangerAPIList.DELETE_SERVICE_DEF); + apiAssociatedWithRBPolicies.add(RangerAPIList.GET_POLICY_FOR_VERSION_NO); + apiAssociatedWithRBPolicies.add(RangerAPIList.GET_POLICY_FROM_EVENT_TIME); + apiAssociatedWithRBPolicies.add(RangerAPIList.GET_POLICY_VERSION_LIST); + apiAssociatedWithRBPolicies.add(RangerAPIList.GET_SERVICE); + apiAssociatedWithRBPolicies.add(RangerAPIList.GET_SERVICE_BY_NAME); + apiAssociatedWithRBPolicies.add(RangerAPIList.GET_SERVICE_DEF); + apiAssociatedWithRBPolicies.add(RangerAPIList.GET_SERVICE_DEF_BY_NAME); + apiAssociatedWithRBPolicies.add(RangerAPIList.GET_SERVICE_DEFS); + apiAssociatedWithRBPolicies.add(RangerAPIList.GET_SERVICES); + apiAssociatedWithRBPolicies.add(RangerAPIList.GET_SERVICE_HEADERS); + apiAssociatedWithRBPolicies.add(RangerAPIList.LOOKUP_RESOURCE); + apiAssociatedWithRBPolicies.add(RangerAPIList.UPDATE_SERVICE); + apiAssociatedWithRBPolicies.add(RangerAPIList.UPDATE_SERVICE_DEF); + apiAssociatedWithRBPolicies.add(RangerAPIList.VALIDATE_CONFIG); + + apiAssociatedWithRBPolicies.add(RangerAPIList.GET_USER_PROFILE_FOR_USER); + apiAssociatedWithRBPolicies.add(RangerAPIList.SEARCH_USERS); + + apiAssociatedWithRBPolicies.add(RangerAPIList.COUNT_X_AUDIT_MAPS); + apiAssociatedWithRBPolicies.add(RangerAPIList.COUNT_X_GROUPS); + apiAssociatedWithRBPolicies.add(RangerAPIList.COUNT_X_GROUP_USERS); + apiAssociatedWithRBPolicies.add(RangerAPIList.COUNT_X_PERM_MAPS); + apiAssociatedWithRBPolicies.add(RangerAPIList.COUNT_X_USERS); + apiAssociatedWithRBPolicies.add(RangerAPIList.CREATE_X_AUDIT_MAP); + apiAssociatedWithRBPolicies.add(RangerAPIList.CREATE_X_PERM_MAP); + apiAssociatedWithRBPolicies.add(RangerAPIList.DELETE_X_AUDIT_MAP); + apiAssociatedWithRBPolicies.add(RangerAPIList.DELETE_X_PERM_MAP); + apiAssociatedWithRBPolicies.add(RangerAPIList.GET_X_AUDIT_MAP); + apiAssociatedWithRBPolicies.add(RangerAPIList.GET_X_GROUP); + apiAssociatedWithRBPolicies.add(RangerAPIList.GET_X_GROUP_BY_GROUP_NAME); + apiAssociatedWithRBPolicies.add(RangerAPIList.GET_X_GROUP_USER); + apiAssociatedWithRBPolicies.add(RangerAPIList.GET_X_GROUP_USERS); + apiAssociatedWithRBPolicies.add(RangerAPIList.GET_X_PERM_MAP); + apiAssociatedWithRBPolicies.add(RangerAPIList.GET_X_USER); + apiAssociatedWithRBPolicies.add(RangerAPIList.GET_X_USER_BY_USER_NAME); + apiAssociatedWithRBPolicies.add(RangerAPIList.GET_X_USER_GROUPS); + apiAssociatedWithRBPolicies.add(RangerAPIList.MODIFY_GROUPS_VISIBILITY); + apiAssociatedWithRBPolicies.add(RangerAPIList.MODIFY_USER_ACTIVE_STATUS); + apiAssociatedWithRBPolicies.add(RangerAPIList.MODIFY_USER_VISIBILITY); + apiAssociatedWithRBPolicies.add(RangerAPIList.SEARCH_X_AUDIT_MAPS); + apiAssociatedWithRBPolicies.add(RangerAPIList.SEARCH_X_GROUPS); + apiAssociatedWithRBPolicies.add(RangerAPIList.SEARCH_X_GROUP_USERS); + apiAssociatedWithRBPolicies.add(RangerAPIList.SEARCH_X_PERM_MAPS); + apiAssociatedWithRBPolicies.add(RangerAPIList.SEARCH_X_USERS); + apiAssociatedWithRBPolicies.add(RangerAPIList.SECURE_GET_X_GROUP); + apiAssociatedWithRBPolicies.add(RangerAPIList.SECURE_GET_X_USER); + apiAssociatedWithRBPolicies.add(RangerAPIList.UPDATE_X_AUDIT_MAP); + apiAssociatedWithRBPolicies.add(RangerAPIList.UPDATE_X_PERM_MAP); + + apiAssociatedWithRBPolicies.add(RangerAPIList.CREATE); + apiAssociatedWithRBPolicies.add(RangerAPIList.CREATE_DEFAULT_ACCOUNT_USER); + apiAssociatedWithRBPolicies.add(RangerAPIList.UPDATE); + apiAssociatedWithRBPolicies.add(RangerAPIList.SET_USER_ROLES); + apiAssociatedWithRBPolicies.add(RangerAPIList.DEACTIVATE_USER); + + rangerAPIMappingWithUI.put(TAB_RESOURCE_BASED_POLICIES, apiAssociatedWithRBPolicies); + + for (String api : apiAssociatedWithRBPolicies) { + Set tabs = mapApiToTabs.computeIfAbsent(api, k -> new HashSet<>()); + + tabs.add(TAB_RESOURCE_BASED_POLICIES); + } + } + + private void mapGDSWithAPIs() { + Set apiAssociatedWithGDS = new HashSet<>(); + + apiAssociatedWithGDS.add(RangerAPIList.GET_DATASET_SUMMARY); + apiAssociatedWithGDS.add(RangerAPIList.CREATE_DATASET); + apiAssociatedWithGDS.add(RangerAPIList.UPDATE_DATASET); + apiAssociatedWithGDS.add(RangerAPIList.DELETE_DATASET); + apiAssociatedWithGDS.add(RangerAPIList.GET_DATASET); + apiAssociatedWithGDS.add(RangerAPIList.SEARCH_DATASETS); + apiAssociatedWithGDS.add(RangerAPIList.LIST_DATASET_NAMES); + apiAssociatedWithGDS.add(RangerAPIList.DATASET_POLICY); + + apiAssociatedWithGDS.add(RangerAPIList.CREATE_PROJECT); + apiAssociatedWithGDS.add(RangerAPIList.UPDATE_PROJECT); + apiAssociatedWithGDS.add(RangerAPIList.DELETE_PROJECT); + apiAssociatedWithGDS.add(RangerAPIList.GET_PROJECT); + apiAssociatedWithGDS.add(RangerAPIList.SEARCH_PROJECTS); + apiAssociatedWithGDS.add(RangerAPIList.LIST_PROJECT_NAMES); + apiAssociatedWithGDS.add(RangerAPIList.PROJECT_POLICY); + + apiAssociatedWithGDS.add(RangerAPIList.CREATE_DATA_SHARE); + apiAssociatedWithGDS.add(RangerAPIList.UPDATE_DATA_SHARE); + apiAssociatedWithGDS.add(RangerAPIList.DELETE_DATA_SHARE); + apiAssociatedWithGDS.add(RangerAPIList.GET_DATA_SHARE); + apiAssociatedWithGDS.add(RangerAPIList.SEARCH_DATA_SHARES); + apiAssociatedWithGDS.add(RangerAPIList.GET_DATA_SHARE_SUMMARY); + + apiAssociatedWithGDS.add(RangerAPIList.ADD_SHARED_RESOURCE); + apiAssociatedWithGDS.add(RangerAPIList.ADD_SHARED_RESOURCES); + apiAssociatedWithGDS.add(RangerAPIList.UPDATE_SHARED_RESOURCE); + apiAssociatedWithGDS.add(RangerAPIList.REMOVE_SHARED_RESOURCE); + apiAssociatedWithGDS.add(RangerAPIList.REMOVE_SHARED_RESOURCES); + apiAssociatedWithGDS.add(RangerAPIList.GET_SHARED_RESOURCE); + apiAssociatedWithGDS.add(RangerAPIList.SEARCH_SHARED_RESOURCES); + + apiAssociatedWithGDS.add(RangerAPIList.ADD_DATASHARE_IN_DATASET); + apiAssociatedWithGDS.add(RangerAPIList.UPDATE_DATASHARE_IN_DATASET); + apiAssociatedWithGDS.add(RangerAPIList.REMOVE_DATASHARE_IN_DATASET); + apiAssociatedWithGDS.add(RangerAPIList.GET_DATASHARE_IN_DATASET); + apiAssociatedWithGDS.add(RangerAPIList.SEARCH_DATASHARE_IN_DATASET); + apiAssociatedWithGDS.add(RangerAPIList.SEARCH_DATASHARE_IN_DATASET_SUMMARY); + + apiAssociatedWithGDS.add(RangerAPIList.ADD_DATASET_IN_PROJECT); + apiAssociatedWithGDS.add(RangerAPIList.UPDATE_DATASET_IN_PROJECT); + apiAssociatedWithGDS.add(RangerAPIList.REMOVE_DATASET_IN_PROJECT); + apiAssociatedWithGDS.add(RangerAPIList.GET_DATASET_IN_PROJECT); + apiAssociatedWithGDS.add(RangerAPIList.SEARCH_DATASET_IN_PROJECT); + + apiAssociatedWithGDS.add(RangerAPIList.GET_DATASET_GRANTS); + apiAssociatedWithGDS.add(RangerAPIList.UPDATE_DATASET_GRANTS); + apiAssociatedWithGDS.add(RangerAPIList.GET_SERVICE_HEADERS); + + rangerAPIMappingWithUI.put(TAB_GDS, apiAssociatedWithGDS); + + for (String api : apiAssociatedWithGDS) { + Set tabs = mapApiToTabs.computeIfAbsent(api, k -> new HashSet<>()); + + tabs.add(TAB_GDS); + } + } } diff --git a/security-admin/src/main/java/org/apache/ranger/security/context/RangerAdminOpContext.java b/security-admin/src/main/java/org/apache/ranger/security/context/RangerAdminOpContext.java index c1d13ac1e4..56bacee281 100644 --- a/security-admin/src/main/java/org/apache/ranger/security/context/RangerAdminOpContext.java +++ b/security-admin/src/main/java/org/apache/ranger/security/context/RangerAdminOpContext.java @@ -22,23 +22,24 @@ import java.io.Serializable; public class RangerAdminOpContext implements Serializable { - private static final long serialVersionUID = 1L; - private boolean bulkModeContext = false; - private Boolean createPrincipalsIfAbsent = null; + private static final long serialVersionUID = 1L; - public boolean isBulkModeContext() { - return bulkModeContext; - } + private boolean bulkModeContext; + private Boolean createPrincipalsIfAbsent; - public void setBulkModeContext(boolean bulkMode) { - this.bulkModeContext = bulkMode; - } + public boolean isBulkModeContext() { + return bulkModeContext; + } - public Boolean getCreatePrincipalsIfAbsent() { - return createPrincipalsIfAbsent; - } + public void setBulkModeContext(boolean bulkMode) { + this.bulkModeContext = bulkMode; + } - public void setCreatePrincipalsIfAbsent(Boolean createPrincipalsIfAbsent) { - this.createPrincipalsIfAbsent = createPrincipalsIfAbsent; - } + public Boolean getCreatePrincipalsIfAbsent() { + return createPrincipalsIfAbsent; + } + + public void setCreatePrincipalsIfAbsent(Boolean createPrincipalsIfAbsent) { + this.createPrincipalsIfAbsent = createPrincipalsIfAbsent; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/security/context/RangerContextHolder.java b/security-admin/src/main/java/org/apache/ranger/security/context/RangerContextHolder.java index d54eb556f9..f7722c883f 100644 --- a/security-admin/src/main/java/org/apache/ranger/security/context/RangerContextHolder.java +++ b/security-admin/src/main/java/org/apache/ranger/security/context/RangerContextHolder.java @@ -17,54 +17,52 @@ * under the License. */ - /** +/** * */ package org.apache.ranger.security.context; public class RangerContextHolder { + private static final ThreadLocal securityContextThreadLocal = new ThreadLocal<>(); - private static final ThreadLocal securityContextThreadLocal = new ThreadLocal(); - - private static final ThreadLocal operationContextThreadLocal = new ThreadLocal(); + private static final ThreadLocal operationContextThreadLocal = new ThreadLocal<>(); private RangerContextHolder() { - } - public static RangerSecurityContext getSecurityContext(){ - return securityContextThreadLocal.get(); + public static RangerSecurityContext getSecurityContext() { + return securityContextThreadLocal.get(); } - public static void setSecurityContext(RangerSecurityContext context){ - securityContextThreadLocal.set(context); + public static void setSecurityContext(RangerSecurityContext context) { + securityContextThreadLocal.set(context); } - public static void resetSecurityContext(){ - securityContextThreadLocal.remove(); + public static void resetSecurityContext() { + securityContextThreadLocal.remove(); } - public static RangerAdminOpContext getOpContext() { - return operationContextThreadLocal.get(); - } + public static RangerAdminOpContext getOpContext() { + return operationContextThreadLocal.get(); + } - public static RangerAdminOpContext getOrCreateOpContext() { - RangerAdminOpContext ret = operationContextThreadLocal.get(); + public static void setOpContext(RangerAdminOpContext context) { + operationContextThreadLocal.set(context); + } - if (ret == null) { - ret = new RangerAdminOpContext(); + public static RangerAdminOpContext getOrCreateOpContext() { + RangerAdminOpContext ret = operationContextThreadLocal.get(); - operationContextThreadLocal.set(ret); - } + if (ret == null) { + ret = new RangerAdminOpContext(); - return ret; - } + operationContextThreadLocal.set(ret); + } - public static void setOpContext(RangerAdminOpContext context) { - operationContextThreadLocal.set(context); - } + return ret; + } - public static void resetOpContext() { - operationContextThreadLocal.remove(); - } + public static void resetOpContext() { + operationContextThreadLocal.remove(); + } } diff --git a/security-admin/src/main/java/org/apache/ranger/security/context/RangerPreAuthSecurityHandler.java b/security-admin/src/main/java/org/apache/ranger/security/context/RangerPreAuthSecurityHandler.java index 80511c6918..518016efd3 100644 --- a/security-admin/src/main/java/org/apache/ranger/security/context/RangerPreAuthSecurityHandler.java +++ b/security-admin/src/main/java/org/apache/ranger/security/context/RangerPreAuthSecurityHandler.java @@ -19,11 +19,6 @@ package org.apache.ranger.security.context; -import java.util.Set; -import java.util.concurrent.CopyOnWriteArraySet; - -import javax.servlet.http.HttpServletResponse; - import org.apache.commons.collections.CollectionUtils; import org.apache.ranger.biz.SessionMgr; import org.apache.ranger.common.ContextUtil; @@ -36,102 +31,126 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; +import javax.servlet.http.HttpServletResponse; + +import java.util.Set; +import java.util.concurrent.CopyOnWriteArraySet; + @Component("rangerPreAuthSecurityHandler") public class RangerPreAuthSecurityHandler { - Logger logger = LoggerFactory.getLogger(RangerPreAuthSecurityHandler.class); - - @Autowired - RangerDaoManager daoManager; - - @Autowired - RESTErrorUtil restErrorUtil; - - @Autowired - RangerAPIMapping rangerAPIMapping; - - @Autowired - SessionMgr sessionMgr; - - public boolean isAPIAccessible(String methodName) throws Exception { - - if (methodName == null) { - return false; - } - - UserSessionBase userSession = ContextUtil.getCurrentUserSession(); - if (userSession == null) { - logger.warn("WARNING: UserSession found null. Some non-authorized user might be trying to access the API."); - return false; - } - - if (userSession.isUserAdmin()) { - if (logger.isDebugEnabled()) { - logger.debug("WARNING: Logged in user is System Admin, System Admin is allowed to access all the tabs except Key Manager." - + "Reason for returning true is, In few cases system admin needs to have access on Key Manager tabs as well."); - } - return true; - } - - Set associatedTabs = rangerAPIMapping.getAssociatedTabsWithAPI(methodName); - if (CollectionUtils.isEmpty(associatedTabs)) { - return true; - } - if(associatedTabs.contains(RangerAPIMapping.TAB_PERMISSIONS) && userSession.isAuditUserAdmin()){ - return true; + Logger logger = LoggerFactory.getLogger(RangerPreAuthSecurityHandler.class); + + @Autowired + RangerDaoManager daoManager; + + @Autowired + RESTErrorUtil restErrorUtil; + + @Autowired + RangerAPIMapping rangerAPIMapping; + + @Autowired + SessionMgr sessionMgr; + + public boolean isAPIAccessible(String methodName) { + if (methodName == null) { + return false; + } + + UserSessionBase userSession = ContextUtil.getCurrentUserSession(); + + if (userSession == null) { + logger.warn("WARNING: UserSession found null. Some non-authorized user might be trying to access the API."); + + return false; + } + + if (userSession.isUserAdmin()) { + logger.debug("WARNING: Logged in user is System Admin, System Admin is allowed to access all the tabs except Key Manager. Reason for returning true is, In few cases system admin needs to have access on Key Manager tabs as well."); + + return true; + } + + Set associatedTabs = rangerAPIMapping.getAssociatedTabsWithAPI(methodName); + + if (CollectionUtils.isEmpty(associatedTabs)) { + return true; + } + + if (associatedTabs.contains(RangerAPIMapping.TAB_PERMISSIONS) && userSession.isAuditUserAdmin()) { + return true; + } + + return isAPIAccessible(associatedTabs); + } + + public boolean isAPIAccessible(Set associatedTabs) { + UserSessionBase userSession = ContextUtil.getCurrentUserSession(); + + if (userSession != null) { + sessionMgr.refreshPermissionsIfNeeded(userSession); + + if (userSession.getRangerUserPermission() != null) { + CopyOnWriteArraySet accessibleModules = userSession.getRangerUserPermission().getUserPermissions(); + + if (CollectionUtils.containsAny(accessibleModules, associatedTabs)) { + return true; } - return isAPIAccessible(associatedTabs); - } - - public boolean isAPIAccessible(Set associatedTabs) throws Exception { - - UserSessionBase userSession = ContextUtil.getCurrentUserSession(); - if (userSession != null) { - sessionMgr.refreshPermissionsIfNeeded(userSession); - if (userSession.getRangerUserPermission() != null) { - CopyOnWriteArraySet accessibleModules = userSession.getRangerUserPermission().getUserPermissions(); - if (CollectionUtils.containsAny(accessibleModules, associatedTabs)) { - return true; - } - } - } - VXResponse gjResponse = new VXResponse(); + } + } + + VXResponse gjResponse = new VXResponse(); + gjResponse.setStatusCode(HttpServletResponse.SC_FORBIDDEN); gjResponse.setMsgDesc("User is not allowed to access the API"); + throw restErrorUtil.generateRESTException(gjResponse); - } - - public boolean isAPISpnegoAccessible(){ - UserSessionBase userSession = ContextUtil.getCurrentUserSession(); - if (userSession != null && (userSession.isSpnegoEnabled() || userSession.isUserAdmin() || userSession.isAuditUserAdmin())) { - return true; - }else if(userSession != null && (userSession.isUserAdmin() || userSession.isKeyAdmin() || userSession.isAuditKeyAdmin())){ - return true; - } + } + + public boolean isAPISpnegoAccessible() { + UserSessionBase userSession = ContextUtil.getCurrentUserSession(); + + if (userSession != null && (userSession.isSpnegoEnabled() || userSession.isUserAdmin() || userSession.isAuditUserAdmin())) { + return true; + } else if (userSession != null && (userSession.isUserAdmin() || userSession.isKeyAdmin() || userSession.isAuditKeyAdmin())) { + return true; + } + VXResponse gjResponse = new VXResponse(); + gjResponse.setStatusCode(HttpServletResponse.SC_FORBIDDEN); gjResponse.setMsgDesc("User is not allowed to access the API"); + + throw restErrorUtil.generateRESTException(gjResponse); + } + + public boolean isAdminOrKeyAdminRole() { + UserSessionBase userSession = ContextUtil.getCurrentUserSession(); + + if (userSession != null && (userSession.isKeyAdmin() || userSession.isUserAdmin())) { + return true; + } + + VXResponse gjResponse = new VXResponse(); + + gjResponse.setStatusCode(HttpServletResponse.SC_FORBIDDEN); // assert user is authenticated. + gjResponse.setMsgDesc("User is not allowed to access the API"); + throw restErrorUtil.generateRESTException(gjResponse); - } - - public boolean isAdminOrKeyAdminRole(){ - UserSessionBase userSession = ContextUtil.getCurrentUserSession(); - if (userSession != null && (userSession.isKeyAdmin() || userSession.isUserAdmin())) { - return true; - } - VXResponse gjResponse = new VXResponse(); + } + + public boolean isAdminRole() { + UserSessionBase userSession = ContextUtil.getCurrentUserSession(); + + if (userSession != null && userSession.isUserAdmin()) { + return true; + } + + VXResponse gjResponse = new VXResponse(); + gjResponse.setStatusCode(HttpServletResponse.SC_FORBIDDEN); // assert user is authenticated. gjResponse.setMsgDesc("User is not allowed to access the API"); + throw restErrorUtil.generateRESTException(gjResponse); - } - - public boolean isAdminRole(){ - UserSessionBase userSession = ContextUtil.getCurrentUserSession(); - if (userSession != null && userSession.isUserAdmin()) { - return true; - } - VXResponse gjResponse = new VXResponse(); - gjResponse.setStatusCode(HttpServletResponse.SC_FORBIDDEN); // assert user is authenticated. - gjResponse.setMsgDesc("User is not allowed to access the API"); - throw restErrorUtil.generateRESTException(gjResponse); - } + } } diff --git a/security-admin/src/main/java/org/apache/ranger/security/context/RangerSecurityContext.java b/security-admin/src/main/java/org/apache/ranger/security/context/RangerSecurityContext.java index 1cf1ac539a..a1624fda11 100644 --- a/security-admin/src/main/java/org/apache/ranger/security/context/RangerSecurityContext.java +++ b/security-admin/src/main/java/org/apache/ranger/security/context/RangerSecurityContext.java @@ -17,20 +17,21 @@ * under the License. */ - /** +/** * */ package org.apache.ranger.security.context; -import java.io.Serializable; - import org.apache.ranger.common.RequestContext; import org.apache.ranger.common.UserSessionBase; -public class RangerSecurityContext implements Serializable{ +import java.io.Serializable; + +public class RangerSecurityContext implements Serializable { private static final long serialVersionUID = 1L; + private UserSessionBase userSession; - private RequestContext requestContext; + private RequestContext requestContext; public UserSessionBase getUserSession() { return userSession; @@ -53,6 +54,4 @@ public RequestContext getRequestContext() { public void setRequestContext(RequestContext requestContext) { this.requestContext = requestContext; } - - } diff --git a/security-admin/src/main/java/org/apache/ranger/security/handler/Permission.java b/security-admin/src/main/java/org/apache/ranger/security/handler/Permission.java index effa7398fb..67bf99f9c4 100644 --- a/security-admin/src/main/java/org/apache/ranger/security/handler/Permission.java +++ b/security-admin/src/main/java/org/apache/ranger/security/handler/Permission.java @@ -17,37 +17,41 @@ * under the License. */ - package org.apache.ranger.security.handler; +package org.apache.ranger.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 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"; + private Permission() { + //To block instantiation + } - public enum permissionType { - CREATE, READ, UPDATE, DELETE - }; + public static PermissionType getPermission(Object in) { + String permString = in.toString(); - public static permissionType getPermisson(Object in) { - String permString = in.toString(); + if (CREATE_PERMISSION.equals(permString)) { + return PermissionType.CREATE; + } - if (CREATE_PERMISSION.equals(permString)) { - return permissionType.CREATE; - } + if (READ_PERMISSION.equals(permString)) { + return PermissionType.READ; + } - if (READ_PERMISSION.equals(permString)) { - return permissionType.READ; - } + if (UPDATE_PERMISSION.equals(permString)) { + return PermissionType.UPDATE; + } - if (UPDATE_PERMISSION.equals(permString)) { - return permissionType.UPDATE; - } + if (DELETE_PERMISSION.equals(permString)) { + return PermissionType.DELETE; + } - if (DELETE_PERMISSION.equals(permString)) { - return permissionType.DELETE; - } + return null; + } - return null; - } + public enum PermissionType { + CREATE, READ, UPDATE, DELETE + } } diff --git a/security-admin/src/main/java/org/apache/ranger/security/handler/RangerAuthenticationProvider.java b/security-admin/src/main/java/org/apache/ranger/security/handler/RangerAuthenticationProvider.java index 8d3a523ab8..884a03d05c 100644 --- a/security-admin/src/main/java/org/apache/ranger/security/handler/RangerAuthenticationProvider.java +++ b/security-admin/src/main/java/org/apache/ranger/security/handler/RangerAuthenticationProvider.java @@ -19,31 +19,25 @@ package org.apache.ranger.security.handler; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; -import java.util.Map; -import java.util.HashMap; - -import javax.security.auth.login.AppConfigurationEntry; -import javax.security.auth.login.AppConfigurationEntry.LoginModuleControlFlag; -import javax.security.auth.login.Configuration; - import org.apache.ranger.authentication.unix.jaas.RoleUserAuthorityGranter; import org.apache.ranger.authorization.hadoop.config.RangerAdminConfig; import org.apache.ranger.authorization.utils.StringUtil; +import org.apache.ranger.biz.SessionMgr; +import org.apache.ranger.biz.UserMgr; import org.apache.ranger.common.PropertiesUtil; import org.apache.ranger.util.Pbkdf2PasswordEncoderCust; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.support.MessageSourceAccessor; import org.springframework.ldap.core.support.DefaultTlsDirContextAuthenticationStrategy; import org.springframework.ldap.core.support.LdapContextSource; import org.springframework.security.authentication.AuthenticationProvider; -import org.springframework.security.authentication.AuthenticationServiceException; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.LockedException; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.authentication.dao.DaoAuthenticationProvider; import org.springframework.security.authentication.jaas.DefaultJaasAuthenticationProvider; import org.springframework.security.authentication.jaas.memory.InMemoryConfiguration; import org.springframework.security.core.Authentication; @@ -58,639 +52,667 @@ import org.springframework.security.ldap.authentication.LdapAuthenticationProvider; import org.springframework.security.ldap.authentication.LdapAuthenticator; import org.springframework.security.ldap.authentication.ad.ActiveDirectoryLdapAuthenticationProvider; -import org.springframework.security.ldap.userdetails.DefaultLdapAuthoritiesPopulator; import org.springframework.security.ldap.search.FilterBasedLdapUserSearch; +import org.springframework.security.ldap.userdetails.DefaultLdapAuthoritiesPopulator; import org.springframework.security.provisioning.JdbcUserDetailsManager; -import org.springframework.security.authentication.dao.DaoAuthenticationProvider; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.apache.ranger.biz.UserMgr; -import org.apache.ranger.biz.SessionMgr; +import javax.security.auth.login.AppConfigurationEntry; +import javax.security.auth.login.AppConfigurationEntry.LoginModuleControlFlag; +import javax.security.auth.login.Configuration; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; public class RangerAuthenticationProvider implements AuthenticationProvider { + private static final Logger logger = LoggerFactory.getLogger(RangerAuthenticationProvider.class); + + private final boolean isFipsEnabled; + + protected MessageSourceAccessor messages = SpringSecurityMessageSource.getAccessor(); + + @Autowired + UserMgr userMgr; + + @Autowired + SessionMgr sessionMgr; + + @Autowired + @Qualifier("userService") + private JdbcUserDetailsManager userDetailsService; + + private String rangerAuthenticationMethod; + private LdapAuthenticator authenticator; + private boolean ssoEnabled; + + public RangerAuthenticationProvider() { + this.isFipsEnabled = RangerAdminConfig.getInstance().isFipsEnabled(); + } + + @Override + public Authentication authenticate(Authentication authentication) throws AuthenticationException { + if (isSsoEnabled()) { + if (authentication != null) { + authentication = getSSOAuthentication(authentication); + + if (authentication != null && authentication.isAuthenticated()) { + return authentication; + } + } + } else { + String sha256PasswordUpdateDisable = PropertiesUtil.getProperty("ranger.sha256Password.update.disable", "false"); + + if (rangerAuthenticationMethod == null) { + rangerAuthenticationMethod = "NONE"; + } + + if (authentication != null) { + if ("LDAP".equalsIgnoreCase(rangerAuthenticationMethod)) { + authentication = getLdapAuthentication(authentication); + + if (authentication != null && authentication.isAuthenticated()) { + return authentication; + } else { + authentication = getLdapBindAuthentication(authentication); + + if (authentication != null && authentication.isAuthenticated()) { + return authentication; + } + } + } else if ("ACTIVE_DIRECTORY".equalsIgnoreCase(rangerAuthenticationMethod)) { + authentication = getADBindAuthentication(authentication); + + if (authentication != null && authentication.isAuthenticated()) { + return authentication; + } else { + authentication = getADAuthentication(authentication); + + if (authentication != null && authentication.isAuthenticated()) { + return authentication; + } + } + } else if ("UNIX".equalsIgnoreCase(rangerAuthenticationMethod)) { + boolean isPAMAuthEnabled = PropertiesUtil.getBooleanProperty("ranger.pam.authentication.enabled", false); + + authentication = (isPAMAuthEnabled ? getPamAuthentication(authentication) : getUnixAuthentication(authentication)); + + if (authentication != null && authentication.isAuthenticated()) { + return authentication; + } + } else if ("PAM".equalsIgnoreCase(rangerAuthenticationMethod)) { + authentication = getPamAuthentication(authentication); + + if (authentication != null && authentication.isAuthenticated()) { + return authentication; + } + } + + // Following are JDBC + if (authentication != null && authentication.getName() != null && sessionMgr.isLoginIdLocked(authentication.getName())) { + logger.debug("Failed to authenticate since user account is locked"); + + throw new LockedException(messages.getMessage("AbstractUserDetailsAuthenticationProvider.locked", "User account is locked")); + } + + if (this.isFipsEnabled) { + try { + authentication = getJDBCAuthentication(authentication, ""); + } catch (Exception e) { + logger.error("JDBC Authentication failure: ", e); + throw e; + } + + return authentication; + } + + String encoder = "SHA256"; + + try { + authentication = getJDBCAuthentication(authentication, encoder); + } catch (Exception e) { + logger.debug("JDBC Authentication failure: ", e); + } + + if (authentication != null && authentication.isAuthenticated()) { + return authentication; + } + + if (authentication != null && !authentication.isAuthenticated()) { + logger.info("Authentication with SHA-256 failed. Now trying with MD5."); + + encoder = "MD5"; + + String userName = authentication.getName(); + String userPassword = null; + + if (authentication.getCredentials() != null) { + userPassword = authentication.getCredentials().toString(); + } + + try { + authentication = getJDBCAuthentication(authentication, encoder); + } catch (Exception e) { + throw e; + } + + if (authentication != null && authentication.isAuthenticated()) { + if ("false".equalsIgnoreCase(sha256PasswordUpdateDisable)) { + userMgr.updatePasswordInSHA256(userName, userPassword, false); + } + } + + return authentication; + } + + return authentication; + } + } + + return authentication; + } + + @Override + public boolean supports(Class authentication) { + return authentication.equals(UsernamePasswordAuthenticationToken.class); + } + + public Authentication getADAuthentication(Authentication authentication) { + try { + String rangerADURL = PropertiesUtil.getProperty("ranger.ldap.ad.url", ""); + String rangerADDomain = PropertiesUtil.getProperty("ranger.ldap.ad.domain", ""); + String rangerLdapDefaultRole = PropertiesUtil.getProperty("ranger.ldap.default.role", "ROLE_USER"); + String rangerLdapUserSearchFilter = PropertiesUtil.getProperty("ranger.ldap.ad.user.searchfilter", "(sAMAccountName={0})"); + + ActiveDirectoryLdapAuthenticationProvider adAuthenticationProvider = new ActiveDirectoryLdapAuthenticationProvider(rangerADDomain, rangerADURL); + + adAuthenticationProvider.setConvertSubErrorCodesToExceptions(true); + adAuthenticationProvider.setUseAuthenticationRequestCredentials(true); + adAuthenticationProvider.setSearchFilter(rangerLdapUserSearchFilter); + + // Grab the user-name and password out of the authentication object. + String userName = authentication.getName(); + String userPassword = ""; + + if (authentication.getCredentials() != null) { + userPassword = authentication.getCredentials().toString(); + } + + // getting user authenticated + if (userName != null && userPassword != null && !userName.trim().isEmpty() && !userPassword.trim().isEmpty()) { + final List grantedAuths = new ArrayList<>(); + + grantedAuths.add(new SimpleGrantedAuthority(rangerLdapDefaultRole)); + + final UserDetails principal = new User(userName, userPassword, grantedAuths); + final Authentication finalAuthentication = new UsernamePasswordAuthenticationToken(principal, userPassword, grantedAuths); + + authentication = adAuthenticationProvider.authenticate(finalAuthentication); + } + + return authentication; + } catch (Exception e) { + logger.error("AD Authentication Failed:", e); + } + + return authentication; + } + + public Authentication getPamAuthentication(Authentication authentication) { + try { + String rangerLdapDefaultRole = PropertiesUtil.getProperty("ranger.ldap.default.role", "ROLE_USER"); + DefaultJaasAuthenticationProvider jaasAuthenticationProvider = new DefaultJaasAuthenticationProvider(); + String loginModuleName = "org.apache.ranger.authentication.unix.jaas.PamLoginModule"; + LoginModuleControlFlag controlFlag = LoginModuleControlFlag.REQUIRED; + Map options = PropertiesUtil.getPropertiesMap(); + + if (!options.containsKey("ranger.pam.service")) { + options.put("ranger.pam.service", "ranger-admin"); + } + + AppConfigurationEntry appConfigurationEntry = new AppConfigurationEntry(loginModuleName, controlFlag, options); + AppConfigurationEntry[] appConfigurationEntries = new AppConfigurationEntry[] {appConfigurationEntry}; + Map appConfigurationEntriesOptions = new HashMap<>(); + + appConfigurationEntriesOptions.put("SPRINGSECURITY", appConfigurationEntries); + + Configuration configuration = new InMemoryConfiguration(appConfigurationEntriesOptions); + + jaasAuthenticationProvider.setConfiguration(configuration); + + RoleUserAuthorityGranter authorityGranter = new RoleUserAuthorityGranter(); + RoleUserAuthorityGranter[] authorityGranters = new RoleUserAuthorityGranter[] {authorityGranter}; + + jaasAuthenticationProvider.setAuthorityGranters(authorityGranters); + jaasAuthenticationProvider.afterPropertiesSet(); + + String userName = authentication.getName(); + String userPassword = ""; + + if (authentication.getCredentials() != null) { + userPassword = authentication.getCredentials().toString(); + } + + // getting user authenticated + if (userName != null && userPassword != null && !userName.trim().isEmpty() && !userPassword.trim().isEmpty()) { + final List grantedAuths = new ArrayList<>(); + + grantedAuths.add(new SimpleGrantedAuthority(rangerLdapDefaultRole)); + + final UserDetails principal = new User(userName, userPassword, grantedAuths); + final Authentication finalAuthentication = new UsernamePasswordAuthenticationToken(principal, userPassword, grantedAuths); + + authentication = jaasAuthenticationProvider.authenticate(finalAuthentication); + authentication = getAuthenticationWithGrantedAuthority(authentication); + } + + return authentication; + } catch (Exception e) { + logger.debug("Pam Authentication Failed:", e); + } + + return authentication; + } + + public Authentication getUnixAuthentication(Authentication authentication) { + try { + String rangerLdapDefaultRole = PropertiesUtil.getProperty("ranger.ldap.default.role", "ROLE_USER"); + DefaultJaasAuthenticationProvider jaasAuthenticationProvider = new DefaultJaasAuthenticationProvider(); + String loginModuleName = "org.apache.ranger.authentication.unix.jaas.RemoteUnixLoginModule"; + LoginModuleControlFlag controlFlag = LoginModuleControlFlag.REQUIRED; + Map options = PropertiesUtil.getPropertiesMap(); + AppConfigurationEntry appConfigurationEntry = new AppConfigurationEntry(loginModuleName, controlFlag, options); + AppConfigurationEntry[] appConfigurationEntries = new AppConfigurationEntry[] {appConfigurationEntry}; + Map appConfigurationEntriesOptions = new HashMap<>(); + + appConfigurationEntriesOptions.put("SPRINGSECURITY", appConfigurationEntries); + + Configuration configuration = new InMemoryConfiguration(appConfigurationEntriesOptions); + + jaasAuthenticationProvider.setConfiguration(configuration); + + RoleUserAuthorityGranter authorityGranter = new RoleUserAuthorityGranter(); + RoleUserAuthorityGranter[] authorityGranters = new RoleUserAuthorityGranter[] {authorityGranter}; + + jaasAuthenticationProvider.setAuthorityGranters(authorityGranters); + jaasAuthenticationProvider.afterPropertiesSet(); + + String userName = authentication.getName(); + String userPassword = ""; + + if (authentication.getCredentials() != null) { + userPassword = authentication.getCredentials().toString(); + } + + // getting user authenticated + if (userName != null && userPassword != null && !userName.trim().isEmpty() && !userPassword.trim().isEmpty()) { + final List grantedAuths = new ArrayList<>(); + + grantedAuths.add(new SimpleGrantedAuthority(rangerLdapDefaultRole)); + + final UserDetails principal = new User(userName, userPassword, grantedAuths); + final Authentication finalAuthentication = new UsernamePasswordAuthenticationToken(principal, userPassword, grantedAuths); + + authentication = jaasAuthenticationProvider.authenticate(finalAuthentication); + authentication = getAuthenticationWithGrantedAuthority(authentication); + } + + return authentication; + } catch (Exception e) { + logger.debug("Unix Authentication Failed:", e); + } + + return authentication; + } + + public String getRangerAuthenticationMethod() { + return rangerAuthenticationMethod; + } + + public void setRangerAuthenticationMethod(String rangerAuthenticationMethod) { + this.rangerAuthenticationMethod = rangerAuthenticationMethod; + } + + public LdapAuthenticator getAuthenticator() { + return authenticator; + } + + public void setAuthenticator(LdapAuthenticator authenticator) { + this.authenticator = authenticator; + } + + public Authentication getAuthenticationWithGrantedAuthority(Authentication authentication) { + UsernamePasswordAuthenticationToken result; + + if (authentication != null && authentication.isAuthenticated()) { + final List grantedAuths = getAuthorities(authentication.getName()); + final UserDetails userDetails = new User(authentication.getName(), authentication.getCredentials().toString(), grantedAuths); + + result = new UsernamePasswordAuthenticationToken(userDetails, authentication.getCredentials(), grantedAuths); + result.setDetails(authentication.getDetails()); + + return result; + } + + return authentication; + } + + /** + * @return the ssoEnabled + */ + public boolean isSsoEnabled() { + return ssoEnabled; + } + + /** + * @param ssoEnabled the ssoEnabled to set + */ + public void setSsoEnabled(boolean ssoEnabled) { + this.ssoEnabled = ssoEnabled; + } + + private Authentication getLdapAuthentication(Authentication authentication) { + try { + // getting ldap settings + String rangerLdapURL = PropertiesUtil.getProperty("ranger.ldap.url", ""); + String rangerLdapUserDNPattern = PropertiesUtil.getProperty("ranger.ldap.user.dnpattern", ""); + String rangerLdapGroupSearchBase = PropertiesUtil.getProperty("ranger.ldap.group.searchbase", ""); + String rangerLdapGroupSearchFilter = PropertiesUtil.getProperty("ranger.ldap.group.searchfilter", ""); + String rangerLdapGroupRoleAttribute = PropertiesUtil.getProperty("ranger.ldap.group.roleattribute", ""); + String rangerLdapDefaultRole = PropertiesUtil.getProperty("ranger.ldap.default.role", "ROLE_USER"); + boolean rangerIsStartTlsEnabled = Boolean.parseBoolean(PropertiesUtil.getProperty("ranger.ldap.starttls", "false")); + + // taking the user-name and password from the authentication + // object. + String userName = authentication.getName(); + String userPassword = ""; + + if (authentication.getCredentials() != null) { + userPassword = authentication.getCredentials().toString(); + } + + // populating LDAP context source with LDAP URL and user-DN-pattern + LdapContextSource ldapContextSource = new DefaultSpringSecurityContextSource(rangerLdapURL); + + if (rangerIsStartTlsEnabled) { + ldapContextSource.setPooled(false); + ldapContextSource.setAuthenticationStrategy(new DefaultTlsDirContextAuthenticationStrategy()); + } + + ldapContextSource.setCacheEnvironmentProperties(false); + ldapContextSource.setAnonymousReadOnly(true); + + // Creating BindAuthenticator using Ldap Context Source. + BindAuthenticator bindAuthenticator = new BindAuthenticator(ldapContextSource); + //String[] userDnPatterns = new String[] { rangerLdapUserDNPattern }; + String[] userDnPatterns = rangerLdapUserDNPattern.split(";"); + + bindAuthenticator.setUserDnPatterns(userDnPatterns); + + LdapAuthenticationProvider ldapAuthenticationProvider; + + if (!StringUtil.isEmpty(rangerLdapGroupSearchBase) && !StringUtil.isEmpty(rangerLdapGroupSearchFilter)) { + // Creating LDAP authorities populator using Ldap context source and + // Ldap group search base. + // populating LDAP authorities populator with group search + // base,group role attribute, group search filter. + DefaultLdapAuthoritiesPopulator defaultLdapAuthoritiesPopulator = new DefaultLdapAuthoritiesPopulator(ldapContextSource, rangerLdapGroupSearchBase); + defaultLdapAuthoritiesPopulator.setGroupRoleAttribute(rangerLdapGroupRoleAttribute); + defaultLdapAuthoritiesPopulator.setGroupSearchFilter(rangerLdapGroupSearchFilter); + defaultLdapAuthoritiesPopulator.setIgnorePartialResultException(true); + + // Creating Ldap authentication provider using BindAuthenticator and Ldap authentication populator + ldapAuthenticationProvider = new LdapAuthenticationProvider(bindAuthenticator, defaultLdapAuthoritiesPopulator); + } else { + ldapAuthenticationProvider = new LdapAuthenticationProvider(bindAuthenticator); + } + + // getting user authenticated + if (userName != null && userPassword != null && !userName.trim().isEmpty() && !userPassword.trim().isEmpty()) { + final List grantedAuths = new ArrayList<>(); + + grantedAuths.add(new SimpleGrantedAuthority(rangerLdapDefaultRole)); + + final UserDetails principal = new User(userName, userPassword, grantedAuths); + + final Authentication finalAuthentication = new UsernamePasswordAuthenticationToken(principal, userPassword, grantedAuths); + + authentication = ldapAuthenticationProvider.authenticate(finalAuthentication); + authentication = getAuthenticationWithGrantedAuthority(authentication); + } + + return authentication; + } catch (Exception e) { + logger.error("LDAP Authentication Failed:", e); + } + + return authentication; + } + + private Authentication getADBindAuthentication(Authentication authentication) { + try { + String rangerADURL = PropertiesUtil.getProperty("ranger.ldap.ad.url", ""); + String rangerLdapADBase = PropertiesUtil.getProperty("ranger.ldap.ad.base.dn", ""); + String rangerADBindDN = PropertiesUtil.getProperty("ranger.ldap.ad.bind.dn", ""); + String rangerADBindPassword = PropertiesUtil.getProperty("ranger.ldap.ad.bind.password", ""); + String rangerLdapDefaultRole = PropertiesUtil.getProperty("ranger.ldap.default.role", "ROLE_USER"); + String rangerLdapReferral = PropertiesUtil.getProperty("ranger.ldap.ad.referral", "follow"); + String rangerLdapUserSearchFilter = PropertiesUtil.getProperty("ranger.ldap.ad.user.searchfilter", "(sAMAccountName={0})"); + boolean rangerIsStartTlsEnabled = Boolean.parseBoolean(PropertiesUtil.getProperty("ranger.ldap.starttls", "false")); + String userName = authentication.getName(); + String userPassword = ""; + + if (authentication.getCredentials() != null) { + userPassword = authentication.getCredentials().toString(); + } + + LdapContextSource ldapContextSource = new DefaultSpringSecurityContextSource(rangerADURL); + + ldapContextSource.setUserDn(rangerADBindDN); + ldapContextSource.setPassword(rangerADBindPassword); + ldapContextSource.setReferral(rangerLdapReferral); + ldapContextSource.setCacheEnvironmentProperties(true); + ldapContextSource.setAnonymousReadOnly(false); + ldapContextSource.setPooled(true); + + if (rangerIsStartTlsEnabled) { + ldapContextSource.setPooled(false); + ldapContextSource.setAuthenticationStrategy(new DefaultTlsDirContextAuthenticationStrategy()); + } + + ldapContextSource.afterPropertiesSet(); + + //String searchFilter="(sAMAccountName={0})"; + if (rangerLdapUserSearchFilter == null || rangerLdapUserSearchFilter.trim().isEmpty()) { + rangerLdapUserSearchFilter = "(sAMAccountName={0})"; + } + + FilterBasedLdapUserSearch userSearch = new FilterBasedLdapUserSearch(rangerLdapADBase, rangerLdapUserSearchFilter, ldapContextSource); + + userSearch.setSearchSubtree(true); + + BindAuthenticator bindAuthenticator = new BindAuthenticator(ldapContextSource); + + bindAuthenticator.setUserSearch(userSearch); + bindAuthenticator.afterPropertiesSet(); + + LdapAuthenticationProvider ldapAuthenticationProvider = new LdapAuthenticationProvider(bindAuthenticator); + + if (userName != null && userPassword != null && !userName.trim().isEmpty() && !userPassword.trim().isEmpty()) { + final List grantedAuths = new ArrayList<>(); + + grantedAuths.add(new SimpleGrantedAuthority(rangerLdapDefaultRole)); + + final UserDetails principal = new User(userName, userPassword, grantedAuths); + final Authentication finalAuthentication = new UsernamePasswordAuthenticationToken(principal, userPassword, grantedAuths); + + authentication = ldapAuthenticationProvider.authenticate(finalAuthentication); + authentication = getAuthenticationWithGrantedAuthority(authentication); + } + + return authentication; + } catch (Exception e) { + logger.error("AD bind Authentication Failed:", e); + } + + return authentication; + } + + private Authentication getLdapBindAuthentication(Authentication authentication) { + try { + String rangerLdapURL = PropertiesUtil.getProperty("ranger.ldap.url", ""); + String rangerLdapUserDNPattern = PropertiesUtil.getProperty("ranger.ldap.user.dnpattern", ""); + String rangerLdapGroupSearchBase = PropertiesUtil.getProperty("ranger.ldap.group.searchbase", ""); + String rangerLdapGroupSearchFilter = PropertiesUtil.getProperty("ranger.ldap.group.searchfilter", ""); + String rangerLdapGroupRoleAttribute = PropertiesUtil.getProperty("ranger.ldap.group.roleattribute", ""); + String rangerLdapDefaultRole = PropertiesUtil.getProperty("ranger.ldap.default.role", "ROLE_USER"); + String rangerLdapBase = PropertiesUtil.getProperty("ranger.ldap.base.dn", ""); + String rangerLdapBindDN = PropertiesUtil.getProperty("ranger.ldap.bind.dn", ""); + String rangerLdapBindPassword = PropertiesUtil.getProperty("ranger.ldap.bind.password", ""); + String rangerLdapReferral = PropertiesUtil.getProperty("ranger.ldap.referral", "follow"); + String rangerLdapUserSearchFilter = PropertiesUtil.getProperty("ranger.ldap.user.searchfilter", "(uid={0})"); + boolean rangerIsStartTlsEnabled = Boolean.parseBoolean(PropertiesUtil.getProperty("ranger.ldap.starttls", "false")); + String userName = authentication.getName(); + String userPassword = ""; + + if (authentication.getCredentials() != null) { + userPassword = authentication.getCredentials().toString(); + } + + LdapContextSource ldapContextSource = new DefaultSpringSecurityContextSource(rangerLdapURL); + + ldapContextSource.setUserDn(rangerLdapBindDN); + ldapContextSource.setPassword(rangerLdapBindPassword); + ldapContextSource.setReferral(rangerLdapReferral); + ldapContextSource.setCacheEnvironmentProperties(false); + ldapContextSource.setAnonymousReadOnly(false); + ldapContextSource.setPooled(true); + + if (rangerIsStartTlsEnabled) { + ldapContextSource.setPooled(false); + ldapContextSource.setAuthenticationStrategy(new DefaultTlsDirContextAuthenticationStrategy()); + } + + ldapContextSource.afterPropertiesSet(); + + DefaultLdapAuthoritiesPopulator defaultLdapAuthoritiesPopulator = new DefaultLdapAuthoritiesPopulator(ldapContextSource, rangerLdapGroupSearchBase); + + defaultLdapAuthoritiesPopulator.setGroupRoleAttribute(rangerLdapGroupRoleAttribute); + defaultLdapAuthoritiesPopulator.setGroupSearchFilter(rangerLdapGroupSearchFilter); + defaultLdapAuthoritiesPopulator.setIgnorePartialResultException(true); + + //String searchFilter="(uid={0})"; + if (rangerLdapUserSearchFilter == null || rangerLdapUserSearchFilter.trim().isEmpty()) { + rangerLdapUserSearchFilter = "(uid={0})"; + } + + FilterBasedLdapUserSearch userSearch = new FilterBasedLdapUserSearch(rangerLdapBase, rangerLdapUserSearchFilter, ldapContextSource); + + userSearch.setSearchSubtree(true); + + BindAuthenticator bindAuthenticator = new BindAuthenticator(ldapContextSource); + + bindAuthenticator.setUserSearch(userSearch); + + String[] userDnPatterns = new String[] {rangerLdapUserDNPattern}; + + bindAuthenticator.setUserDnPatterns(userDnPatterns); + bindAuthenticator.afterPropertiesSet(); + + LdapAuthenticationProvider ldapAuthenticationProvider = new LdapAuthenticationProvider(bindAuthenticator, defaultLdapAuthoritiesPopulator); + + if (userName != null && userPassword != null && !userName.trim().isEmpty() && !userPassword.trim().isEmpty()) { + final List grantedAuths = new ArrayList<>(); + + grantedAuths.add(new SimpleGrantedAuthority(rangerLdapDefaultRole)); + + final UserDetails principal = new User(userName, userPassword, grantedAuths); + final Authentication finalAuthentication = new UsernamePasswordAuthenticationToken(principal, userPassword, grantedAuths); + + authentication = ldapAuthenticationProvider.authenticate(finalAuthentication); + authentication = getAuthenticationWithGrantedAuthority(authentication); + } + + return authentication; + } catch (Exception e) { + logger.error("LDAP bind Authentication Failed:", e); + } + + return authentication; + } + + private Authentication getJDBCAuthentication(Authentication authentication, String encoder) throws AuthenticationException { + try { + DaoAuthenticationProvider authenticator = new DaoAuthenticationProvider(); + + authenticator.setUserDetailsService(userDetailsService); + + if (this.isFipsEnabled) { + if (authentication != null && authentication.getCredentials() != null && !authentication.isAuthenticated()) { + Pbkdf2PasswordEncoderCust passwordEncoder = new Pbkdf2PasswordEncoderCust(authentication.getName()); + + passwordEncoder.setEncodeHashAsBase64(true); + authenticator.setPasswordEncoder(passwordEncoder); + } + } else { + if ("SHA256".equalsIgnoreCase(encoder) && authentication != null) { + authenticator.setPasswordEncoder(new RangerCustomPasswordEncoder(authentication.getName(), "SHA-256")); + } else if ("MD5".equalsIgnoreCase(encoder) && authentication != null) { + authenticator.setPasswordEncoder(new RangerCustomPasswordEncoder(authentication.getName(), "MD5")); + } + } + + String userName = ""; + String userPassword = ""; + + if (authentication != null) { + userName = authentication.getName(); + + if (authentication.getCredentials() != null) { + userPassword = authentication.getCredentials().toString(); + } + } + + String rangerLdapDefaultRole = PropertiesUtil.getProperty("ranger.ldap.default.role", "ROLE_USER"); + + if (userName != null && userPassword != null && !userName.trim().isEmpty() && !userPassword.trim().isEmpty()) { + final List grantedAuths = new ArrayList<>(); + + grantedAuths.add(new SimpleGrantedAuthority(rangerLdapDefaultRole)); + + final UserDetails principal = new User(userName, userPassword, grantedAuths); + final Authentication finalAuthentication = new UsernamePasswordAuthenticationToken(principal, userPassword, grantedAuths); + + authentication = authenticator.authenticate(finalAuthentication); + + return authentication; + } else { + if (authentication != null && !authentication.isAuthenticated()) { + throw new BadCredentialsException("Bad credentials"); + } + } + } catch (Exception e) { + throw e; + } catch (Throwable t) { + throw new BadCredentialsException("Bad credentials", t); + } + + return authentication; + } + + private List getAuthorities(String username) { + Collection roleList = userMgr.getRolesByLoginId(username); + final List grantedAuths = new ArrayList<>(); + + for (String role : roleList) { + grantedAuths.add(new SimpleGrantedAuthority(role)); + } + + return grantedAuths; + } - @Autowired - @Qualifier("userService") - private JdbcUserDetailsManager userDetailsService; - - @Autowired - UserMgr userMgr; - - @Autowired - SessionMgr sessionMgr; - - private static final Logger logger = LoggerFactory.getLogger(RangerAuthenticationProvider.class); - - private String rangerAuthenticationMethod; - - private LdapAuthenticator authenticator; - - private boolean ssoEnabled = false; - private final boolean isFipsEnabled; - protected MessageSourceAccessor messages = SpringSecurityMessageSource.getAccessor(); - - public RangerAuthenticationProvider() { - this.isFipsEnabled = RangerAdminConfig.getInstance().isFipsEnabled(); - - } - - @Override - public Authentication authenticate(Authentication authentication) - throws AuthenticationException { - if (isSsoEnabled()) { - if (authentication != null) { - authentication = getSSOAuthentication(authentication); - if (authentication != null && authentication.isAuthenticated()) { - return authentication; - } - } - } else { - String sha256PasswordUpdateDisable = PropertiesUtil.getProperty("ranger.sha256Password.update.disable", "false"); - if (rangerAuthenticationMethod==null) { - rangerAuthenticationMethod="NONE"; - } - if (authentication != null && rangerAuthenticationMethod != null) { - if ("LDAP".equalsIgnoreCase(rangerAuthenticationMethod)) { - authentication = getLdapAuthentication(authentication); - if (authentication!=null && authentication.isAuthenticated()) { - return authentication; - } else { - authentication=getLdapBindAuthentication(authentication); - if (authentication != null && authentication.isAuthenticated()) { - return authentication; - } - } - } - if ("ACTIVE_DIRECTORY".equalsIgnoreCase(rangerAuthenticationMethod)) { - authentication = getADBindAuthentication(authentication); - if (authentication != null && authentication.isAuthenticated()) { - return authentication; - } else { - authentication = getADAuthentication(authentication); - if (authentication != null && authentication.isAuthenticated()) { - return authentication; - } - } - } - if ("UNIX".equalsIgnoreCase(rangerAuthenticationMethod)) { - boolean isPAMAuthEnabled = PropertiesUtil.getBooleanProperty("ranger.pam.authentication.enabled", false); - authentication= (isPAMAuthEnabled ? getPamAuthentication(authentication) : getUnixAuthentication(authentication)); - if (authentication != null && authentication.isAuthenticated()) { - return authentication; - } - } - if ("PAM".equalsIgnoreCase(rangerAuthenticationMethod)) { - authentication = getPamAuthentication(authentication); - if (authentication != null && authentication.isAuthenticated()) { - return authentication; - } - } - - // Following are JDBC - if (authentication != null && authentication.getName() != null && sessionMgr.isLoginIdLocked(authentication.getName())) { - logger.debug("Failed to authenticate since user account is locked"); - - throw new LockedException(messages.getMessage("AbstractUserDetailsAuthenticationProvider.locked", "User account is locked")); - } - - if (this.isFipsEnabled) { - try { - authentication = getJDBCAuthentication(authentication,""); - } catch (Exception e) { - logger.error("JDBC Authentication failure: ", e); - throw e; - } - return authentication; - } - String encoder="SHA256"; - try { - authentication = getJDBCAuthentication(authentication,encoder); - } catch (Exception e) { - logger.debug("JDBC Authentication failure: ", e); - } - if (authentication !=null && authentication.isAuthenticated()) { - return authentication; - } - if (authentication != null && !authentication.isAuthenticated()) { - logger.info("Authentication with SHA-256 failed. Now trying with MD5."); - encoder="MD5"; - String userName = authentication.getName(); - String userPassword = null; - if (authentication.getCredentials() != null) { - userPassword = authentication.getCredentials().toString(); - } - try { - authentication = getJDBCAuthentication(authentication,encoder); - } catch (Exception e) { - throw e; - } - if (authentication != null && authentication.isAuthenticated()) { - if ("false".equalsIgnoreCase(sha256PasswordUpdateDisable)) { - userMgr.updatePasswordInSHA256(userName,userPassword,false); - } - return authentication; - }else{ - return authentication; - } - } - return authentication; - } - } - return authentication; - } - - private Authentication getLdapAuthentication(Authentication authentication) { - - try { - // getting ldap settings - String rangerLdapURL = PropertiesUtil.getProperty( - "ranger.ldap.url", ""); - String rangerLdapUserDNPattern = PropertiesUtil.getProperty( - "ranger.ldap.user.dnpattern", ""); - String rangerLdapGroupSearchBase = PropertiesUtil.getProperty( - "ranger.ldap.group.searchbase", ""); - String rangerLdapGroupSearchFilter = PropertiesUtil.getProperty( - "ranger.ldap.group.searchfilter", ""); - String rangerLdapGroupRoleAttribute = PropertiesUtil.getProperty( - "ranger.ldap.group.roleattribute", ""); - String rangerLdapDefaultRole = PropertiesUtil.getProperty( - "ranger.ldap.default.role", "ROLE_USER"); - boolean rangerIsStartTlsEnabled = Boolean.valueOf(PropertiesUtil.getProperty( - "ranger.ldap.starttls", "false")); - - // taking the user-name and password from the authentication - // object. - String userName = authentication.getName(); - String userPassword = ""; - if (authentication.getCredentials() != null) { - userPassword = authentication.getCredentials().toString(); - } - - // populating LDAP context source with LDAP URL and user-DN-pattern - LdapContextSource ldapContextSource = new DefaultSpringSecurityContextSource( - rangerLdapURL); - if (rangerIsStartTlsEnabled) { - ldapContextSource.setPooled(false); - ldapContextSource.setAuthenticationStrategy(new DefaultTlsDirContextAuthenticationStrategy()); - } - - ldapContextSource.setCacheEnvironmentProperties(false); - ldapContextSource.setAnonymousReadOnly(true); - - // Creating BindAuthenticator using Ldap Context Source. - BindAuthenticator bindAuthenticator = new BindAuthenticator( - ldapContextSource); - //String[] userDnPatterns = new String[] { rangerLdapUserDNPattern }; - String[] userDnPatterns = rangerLdapUserDNPattern.split(";"); - bindAuthenticator.setUserDnPatterns(userDnPatterns); - - LdapAuthenticationProvider ldapAuthenticationProvider = null; - - if (!StringUtil.isEmpty(rangerLdapGroupSearchBase) && !StringUtil.isEmpty(rangerLdapGroupSearchFilter)) { - // Creating LDAP authorities populator using Ldap context source and - // Ldap group search base. - // populating LDAP authorities populator with group search - // base,group role attribute, group search filter. - DefaultLdapAuthoritiesPopulator defaultLdapAuthoritiesPopulator = new DefaultLdapAuthoritiesPopulator( - ldapContextSource, rangerLdapGroupSearchBase); - defaultLdapAuthoritiesPopulator.setGroupRoleAttribute(rangerLdapGroupRoleAttribute); - defaultLdapAuthoritiesPopulator.setGroupSearchFilter(rangerLdapGroupSearchFilter); - defaultLdapAuthoritiesPopulator.setIgnorePartialResultException(true); - - // Creating Ldap authentication provider using BindAuthenticator and Ldap authentication populator - ldapAuthenticationProvider = new LdapAuthenticationProvider( - bindAuthenticator, defaultLdapAuthoritiesPopulator); - } else { - ldapAuthenticationProvider = new LdapAuthenticationProvider(bindAuthenticator); - } - - // getting user authenticated - if (userName != null && userPassword != null - && !userName.trim().isEmpty() - && !userPassword.trim().isEmpty()) { - final List grantedAuths = new ArrayList<>(); - grantedAuths.add(new SimpleGrantedAuthority( - rangerLdapDefaultRole)); - - final UserDetails principal = new User(userName, userPassword, - grantedAuths); - - final Authentication finalAuthentication = new UsernamePasswordAuthenticationToken( - principal, userPassword, grantedAuths); - - authentication = ldapAuthenticationProvider - .authenticate(finalAuthentication); - authentication=getAuthenticationWithGrantedAuthority(authentication); - return authentication; - } else { - return authentication; - } - } catch (Exception e) { - logger.error("LDAP Authentication Failed:", e); - } - return authentication; - } - - public Authentication getADAuthentication(Authentication authentication) { - try{ - String rangerADURL = PropertiesUtil.getProperty("ranger.ldap.ad.url", - ""); - String rangerADDomain = PropertiesUtil.getProperty( - "ranger.ldap.ad.domain", ""); - String rangerLdapDefaultRole = PropertiesUtil.getProperty( - "ranger.ldap.default.role", "ROLE_USER"); - String rangerLdapUserSearchFilter = PropertiesUtil.getProperty( - "ranger.ldap.ad.user.searchfilter", "(sAMAccountName={0})"); - - ActiveDirectoryLdapAuthenticationProvider adAuthenticationProvider = new ActiveDirectoryLdapAuthenticationProvider( - rangerADDomain, rangerADURL); - adAuthenticationProvider.setConvertSubErrorCodesToExceptions(true); - adAuthenticationProvider.setUseAuthenticationRequestCredentials(true); - adAuthenticationProvider.setSearchFilter(rangerLdapUserSearchFilter); - - // Grab the user-name and password out of the authentication object. - String userName = authentication.getName(); - String userPassword = ""; - if (authentication.getCredentials() != null) { - userPassword = authentication.getCredentials().toString(); - } - - // getting user authenticated - if (userName != null && userPassword != null - && !userName.trim().isEmpty() && !userPassword.trim().isEmpty()) { - final List grantedAuths = new ArrayList<>(); - grantedAuths.add(new SimpleGrantedAuthority(rangerLdapDefaultRole)); - final UserDetails principal = new User(userName, userPassword, - grantedAuths); - final Authentication finalAuthentication = new UsernamePasswordAuthenticationToken( - principal, userPassword, grantedAuths); - authentication = adAuthenticationProvider - .authenticate(finalAuthentication); - return authentication; - } else { - return authentication; - } - }catch (Exception e) { - logger.error("AD Authentication Failed:", e); - } - return authentication; - } - - public Authentication getPamAuthentication(Authentication authentication) { - try { - String rangerLdapDefaultRole = PropertiesUtil.getProperty( - "ranger.ldap.default.role", "ROLE_USER"); - DefaultJaasAuthenticationProvider jaasAuthenticationProvider = new DefaultJaasAuthenticationProvider(); - String loginModuleName = "org.apache.ranger.authentication.unix.jaas.PamLoginModule"; - LoginModuleControlFlag controlFlag = LoginModuleControlFlag.REQUIRED; - Map options = PropertiesUtil.getPropertiesMap(); - - if (!options.containsKey("ranger.pam.service")) - options.put("ranger.pam.service", "ranger-admin"); - - AppConfigurationEntry appConfigurationEntry = new AppConfigurationEntry( - loginModuleName, controlFlag, options); - AppConfigurationEntry[] appConfigurationEntries = new AppConfigurationEntry[] { appConfigurationEntry }; - Map appConfigurationEntriesOptions = new HashMap(); - appConfigurationEntriesOptions.put("SPRINGSECURITY", - appConfigurationEntries); - Configuration configuration = new InMemoryConfiguration( - appConfigurationEntriesOptions); - jaasAuthenticationProvider.setConfiguration(configuration); - RoleUserAuthorityGranter authorityGranter = new RoleUserAuthorityGranter(); - RoleUserAuthorityGranter[] authorityGranters = new RoleUserAuthorityGranter[] { authorityGranter }; - jaasAuthenticationProvider.setAuthorityGranters(authorityGranters); - jaasAuthenticationProvider.afterPropertiesSet(); - String userName = authentication.getName(); - String userPassword = ""; - if (authentication.getCredentials() != null) { - userPassword = authentication.getCredentials().toString(); - } - - // getting user authenticated - if (userName != null && userPassword != null - && !userName.trim().isEmpty() - && !userPassword.trim().isEmpty()) { - final List grantedAuths = new ArrayList<>(); - grantedAuths.add(new SimpleGrantedAuthority( - rangerLdapDefaultRole)); - final UserDetails principal = new User(userName, userPassword, - grantedAuths); - final Authentication finalAuthentication = new UsernamePasswordAuthenticationToken( - principal, userPassword, grantedAuths); - authentication = jaasAuthenticationProvider - .authenticate(finalAuthentication); - authentication=getAuthenticationWithGrantedAuthority(authentication); - return authentication; - } else { - return authentication; - } - } catch (Exception e) { - logger.debug("Pam Authentication Failed:", e); - } - return authentication; - } - - public Authentication getUnixAuthentication(Authentication authentication) { - - try { - String rangerLdapDefaultRole = PropertiesUtil.getProperty( - "ranger.ldap.default.role", "ROLE_USER"); - DefaultJaasAuthenticationProvider jaasAuthenticationProvider = new DefaultJaasAuthenticationProvider(); - String loginModuleName = "org.apache.ranger.authentication.unix.jaas.RemoteUnixLoginModule"; - LoginModuleControlFlag controlFlag = LoginModuleControlFlag.REQUIRED; - Map options = PropertiesUtil.getPropertiesMap(); - AppConfigurationEntry appConfigurationEntry = new AppConfigurationEntry( - loginModuleName, controlFlag, options); - AppConfigurationEntry[] appConfigurationEntries = new AppConfigurationEntry[] { appConfigurationEntry }; - Map appConfigurationEntriesOptions = new HashMap(); - appConfigurationEntriesOptions.put("SPRINGSECURITY", - appConfigurationEntries); - Configuration configuration = new InMemoryConfiguration( - appConfigurationEntriesOptions); - jaasAuthenticationProvider.setConfiguration(configuration); - RoleUserAuthorityGranter authorityGranter = new RoleUserAuthorityGranter(); - RoleUserAuthorityGranter[] authorityGranters = new RoleUserAuthorityGranter[] { authorityGranter }; - jaasAuthenticationProvider.setAuthorityGranters(authorityGranters); - jaasAuthenticationProvider.afterPropertiesSet(); - String userName = authentication.getName(); - String userPassword = ""; - if (authentication.getCredentials() != null) { - userPassword = authentication.getCredentials().toString(); - } - - // getting user authenticated - if (userName != null && userPassword != null - && !userName.trim().isEmpty() - && !userPassword.trim().isEmpty()) { - final List grantedAuths = new ArrayList<>(); - grantedAuths.add(new SimpleGrantedAuthority( - rangerLdapDefaultRole)); - final UserDetails principal = new User(userName, userPassword, - grantedAuths); - final Authentication finalAuthentication = new UsernamePasswordAuthenticationToken( - principal, userPassword, grantedAuths); - authentication = jaasAuthenticationProvider - .authenticate(finalAuthentication); - authentication=getAuthenticationWithGrantedAuthority(authentication); - return authentication; - } else { - return authentication; - } - } catch (Exception e) { - logger.debug("Unix Authentication Failed:", e); - } - - return authentication; - } - - @Override - public boolean supports(Class authentication) { - return authentication.equals(UsernamePasswordAuthenticationToken.class); - } - - public String getRangerAuthenticationMethod() { - return rangerAuthenticationMethod; - } - - public void setRangerAuthenticationMethod(String rangerAuthenticationMethod) { - this.rangerAuthenticationMethod = rangerAuthenticationMethod; - } - - public LdapAuthenticator getAuthenticator() { - return authenticator; - } - - public void setAuthenticator(LdapAuthenticator authenticator) { - this.authenticator = authenticator; - } - - private Authentication getADBindAuthentication(Authentication authentication) { - try { - String rangerADURL = PropertiesUtil.getProperty("ranger.ldap.ad.url", ""); - String rangerLdapADBase = PropertiesUtil.getProperty("ranger.ldap.ad.base.dn", ""); - String rangerADBindDN = PropertiesUtil.getProperty("ranger.ldap.ad.bind.dn", ""); - String rangerADBindPassword = PropertiesUtil.getProperty("ranger.ldap.ad.bind.password", ""); - String rangerLdapDefaultRole = PropertiesUtil.getProperty("ranger.ldap.default.role", "ROLE_USER"); - String rangerLdapReferral = PropertiesUtil.getProperty("ranger.ldap.ad.referral", "follow"); - String rangerLdapUserSearchFilter = PropertiesUtil.getProperty("ranger.ldap.ad.user.searchfilter", "(sAMAccountName={0})"); - boolean rangerIsStartTlsEnabled = Boolean.valueOf(PropertiesUtil.getProperty( - "ranger.ldap.starttls", "false")); - String userName = authentication.getName(); - String userPassword = ""; - if (authentication.getCredentials() != null) { - userPassword = authentication.getCredentials().toString(); - } - - LdapContextSource ldapContextSource = new DefaultSpringSecurityContextSource(rangerADURL); - ldapContextSource.setUserDn(rangerADBindDN); - ldapContextSource.setPassword(rangerADBindPassword); - ldapContextSource.setReferral(rangerLdapReferral); - ldapContextSource.setCacheEnvironmentProperties(true); - ldapContextSource.setAnonymousReadOnly(false); - ldapContextSource.setPooled(true); - if (rangerIsStartTlsEnabled) { - ldapContextSource.setPooled(false); - ldapContextSource.setAuthenticationStrategy(new DefaultTlsDirContextAuthenticationStrategy()); - } - ldapContextSource.afterPropertiesSet(); - - //String searchFilter="(sAMAccountName={0})"; - if (rangerLdapUserSearchFilter==null || rangerLdapUserSearchFilter.trim().isEmpty()) { - rangerLdapUserSearchFilter="(sAMAccountName={0})"; - } - FilterBasedLdapUserSearch userSearch=new FilterBasedLdapUserSearch(rangerLdapADBase, rangerLdapUserSearchFilter,ldapContextSource); - userSearch.setSearchSubtree(true); - - BindAuthenticator bindAuthenticator = new BindAuthenticator(ldapContextSource); - bindAuthenticator.setUserSearch(userSearch); - bindAuthenticator.afterPropertiesSet(); - - LdapAuthenticationProvider ldapAuthenticationProvider = new LdapAuthenticationProvider(bindAuthenticator); - - if (userName != null && userPassword != null && !userName.trim().isEmpty() && !userPassword.trim().isEmpty()) { - final List grantedAuths = new ArrayList<>(); - grantedAuths.add(new SimpleGrantedAuthority(rangerLdapDefaultRole)); - final UserDetails principal = new User(userName, userPassword,grantedAuths); - final Authentication finalAuthentication = new UsernamePasswordAuthenticationToken(principal, userPassword, grantedAuths); - - authentication = ldapAuthenticationProvider.authenticate(finalAuthentication); - authentication=getAuthenticationWithGrantedAuthority(authentication); - return authentication; - } else { - return authentication; - } - } catch (Exception e) { - logger.error("AD bind Authentication Failed:", e); - } - return authentication; - } - - private Authentication getLdapBindAuthentication(Authentication authentication) { - try { - String rangerLdapURL = PropertiesUtil.getProperty("ranger.ldap.url", ""); - String rangerLdapUserDNPattern = PropertiesUtil.getProperty("ranger.ldap.user.dnpattern", ""); - String rangerLdapGroupSearchBase = PropertiesUtil.getProperty("ranger.ldap.group.searchbase", ""); - String rangerLdapGroupSearchFilter = PropertiesUtil.getProperty("ranger.ldap.group.searchfilter", ""); - String rangerLdapGroupRoleAttribute = PropertiesUtil.getProperty("ranger.ldap.group.roleattribute", ""); - String rangerLdapDefaultRole = PropertiesUtil.getProperty("ranger.ldap.default.role", "ROLE_USER"); - String rangerLdapBase = PropertiesUtil.getProperty("ranger.ldap.base.dn", ""); - String rangerLdapBindDN = PropertiesUtil.getProperty("ranger.ldap.bind.dn", ""); - String rangerLdapBindPassword = PropertiesUtil.getProperty("ranger.ldap.bind.password", ""); - String rangerLdapReferral = PropertiesUtil.getProperty("ranger.ldap.referral", "follow"); - String rangerLdapUserSearchFilter = PropertiesUtil.getProperty("ranger.ldap.user.searchfilter", "(uid={0})"); - boolean rangerIsStartTlsEnabled = Boolean.valueOf(PropertiesUtil.getProperty( - "ranger.ldap.starttls", "false")); - String userName = authentication.getName(); - String userPassword = ""; - if (authentication.getCredentials() != null) { - userPassword = authentication.getCredentials().toString(); - } - - LdapContextSource ldapContextSource = new DefaultSpringSecurityContextSource(rangerLdapURL); - ldapContextSource.setUserDn(rangerLdapBindDN); - ldapContextSource.setPassword(rangerLdapBindPassword); - ldapContextSource.setReferral(rangerLdapReferral); - ldapContextSource.setCacheEnvironmentProperties(false); - ldapContextSource.setAnonymousReadOnly(false); - ldapContextSource.setPooled(true); - if (rangerIsStartTlsEnabled) { - ldapContextSource.setPooled(false); - ldapContextSource.setAuthenticationStrategy(new DefaultTlsDirContextAuthenticationStrategy()); - } - ldapContextSource.afterPropertiesSet(); - - DefaultLdapAuthoritiesPopulator defaultLdapAuthoritiesPopulator = new DefaultLdapAuthoritiesPopulator(ldapContextSource, rangerLdapGroupSearchBase); - defaultLdapAuthoritiesPopulator.setGroupRoleAttribute(rangerLdapGroupRoleAttribute); - defaultLdapAuthoritiesPopulator.setGroupSearchFilter(rangerLdapGroupSearchFilter); - defaultLdapAuthoritiesPopulator.setIgnorePartialResultException(true); - - //String searchFilter="(uid={0})"; - if (rangerLdapUserSearchFilter==null||rangerLdapUserSearchFilter.trim().isEmpty()) { - rangerLdapUserSearchFilter="(uid={0})"; - } - FilterBasedLdapUserSearch userSearch=new FilterBasedLdapUserSearch(rangerLdapBase, rangerLdapUserSearchFilter,ldapContextSource); - userSearch.setSearchSubtree(true); - - BindAuthenticator bindAuthenticator = new BindAuthenticator(ldapContextSource); - bindAuthenticator.setUserSearch(userSearch); - String[] userDnPatterns = new String[] { rangerLdapUserDNPattern }; - bindAuthenticator.setUserDnPatterns(userDnPatterns); - bindAuthenticator.afterPropertiesSet(); - - LdapAuthenticationProvider ldapAuthenticationProvider = new LdapAuthenticationProvider(bindAuthenticator,defaultLdapAuthoritiesPopulator); - - if (userName != null && userPassword != null && !userName.trim().isEmpty()&& !userPassword.trim().isEmpty()) { - final List grantedAuths = new ArrayList<>(); - grantedAuths.add(new SimpleGrantedAuthority(rangerLdapDefaultRole)); - final UserDetails principal = new User(userName, userPassword,grantedAuths); - final Authentication finalAuthentication = new UsernamePasswordAuthenticationToken(principal, userPassword, grantedAuths); - - authentication = ldapAuthenticationProvider.authenticate(finalAuthentication); - authentication=getAuthenticationWithGrantedAuthority(authentication); - return authentication; - } else { - return authentication; - } - } catch (Exception e) { - logger.error("LDAP bind Authentication Failed:", e); - } - return authentication; - } - - private Authentication getJDBCAuthentication(Authentication authentication,String encoder) throws AuthenticationException{ - try { - DaoAuthenticationProvider authenticator = new DaoAuthenticationProvider(); - authenticator.setUserDetailsService(userDetailsService); - if (this.isFipsEnabled) { - if (authentication != null && authentication.getCredentials() != null && !authentication.isAuthenticated()) { - Pbkdf2PasswordEncoderCust passwordEncoder = new Pbkdf2PasswordEncoderCust(authentication.getName()); - passwordEncoder.setEncodeHashAsBase64(true); - authenticator.setPasswordEncoder(passwordEncoder); - } - } else { - if (encoder != null && "SHA256".equalsIgnoreCase(encoder) && authentication != null) { - authenticator.setPasswordEncoder(new RangerCustomPasswordEncoder(authentication.getName(),"SHA-256")); - - } else if (encoder != null && "MD5".equalsIgnoreCase(encoder) && authentication != null) { - authenticator.setPasswordEncoder(new RangerCustomPasswordEncoder(authentication.getName(),"MD5")); - } - } - - String userName =""; - String userPassword = ""; - if (authentication!=null) { - userName = authentication.getName(); - if (authentication.getCredentials() != null) { - userPassword = authentication.getCredentials().toString(); - } - } - - String rangerLdapDefaultRole = PropertiesUtil.getProperty("ranger.ldap.default.role", "ROLE_USER"); - if (userName != null && userPassword != null && !userName.trim().isEmpty()&& !userPassword.trim().isEmpty()) { - final List grantedAuths = new ArrayList<>(); - grantedAuths.add(new SimpleGrantedAuthority(rangerLdapDefaultRole)); - final UserDetails principal = new User(userName, userPassword,grantedAuths); - final Authentication finalAuthentication = new UsernamePasswordAuthenticationToken(principal, userPassword, grantedAuths); - authentication= authenticator.authenticate(finalAuthentication); - return authentication; - } else { - if (authentication !=null && !authentication.isAuthenticated()) { - throw new BadCredentialsException("Bad credentials"); - } - } - } catch (BadCredentialsException e) { - throw e; - }catch (AuthenticationServiceException e) { - throw e; - }catch (AuthenticationException e) { - throw e; - }catch (Exception e) { - throw e; - } catch (Throwable t) { - throw new BadCredentialsException("Bad credentials", t); - } - return authentication; - } - - private List getAuthorities(String username) { - Collection roleList=userMgr.getRolesByLoginId(username); - final List grantedAuths = new ArrayList<>(); - for (String role : roleList) { - grantedAuths.add(new SimpleGrantedAuthority(role)); - } - return grantedAuths; - } - - public Authentication getAuthenticationWithGrantedAuthority(Authentication authentication){ - UsernamePasswordAuthenticationToken result = null; - if (authentication != null && authentication.isAuthenticated()) { - final List grantedAuths=getAuthorities(authentication.getName().toString()); - final UserDetails userDetails = new User(authentication.getName().toString(), authentication.getCredentials().toString(),grantedAuths); - result = new UsernamePasswordAuthenticationToken(userDetails,authentication.getCredentials(),grantedAuths); - result.setDetails(authentication.getDetails()); - return result; - } - return authentication; - } - - private Authentication getSSOAuthentication(Authentication authentication) throws AuthenticationException{ - return authentication; - } - - /** - * @return the ssoEnabled - */ - public boolean isSsoEnabled() { - return ssoEnabled; - } - - /** - * @param ssoEnabled the ssoEnabled to set - */ - public void setSsoEnabled(boolean ssoEnabled) { - this.ssoEnabled = ssoEnabled; - } + private Authentication getSSOAuthentication(Authentication authentication) throws AuthenticationException { + return authentication; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/security/handler/RangerCustomPasswordEncoder.java b/security-admin/src/main/java/org/apache/ranger/security/handler/RangerCustomPasswordEncoder.java index fadea9bcb1..1c2854b3bb 100644 --- a/security-admin/src/main/java/org/apache/ranger/security/handler/RangerCustomPasswordEncoder.java +++ b/security-admin/src/main/java/org/apache/ranger/security/handler/RangerCustomPasswordEncoder.java @@ -19,54 +19,52 @@ package org.apache.ranger.security.handler; -import java.io.UnsupportedEncodingException; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; - import org.springframework.security.crypto.codec.Hex; import org.springframework.security.crypto.password.PasswordEncoder; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; + public class RangerCustomPasswordEncoder implements PasswordEncoder { + private final String salt; + private final String algorithm; - private final String salt; - private final String algorithm; + public RangerCustomPasswordEncoder(String salt, String algorithm) { + this.salt = salt; + this.algorithm = algorithm; + } - public RangerCustomPasswordEncoder(String salt, String algorithm) { - this.salt = salt; - this.algorithm = algorithm; - } + @Override + public String encode(CharSequence rawPassword) { + try { + String saltedPassword = mergeTextAndSalt(rawPassword, this.salt, false); + MessageDigest digest = MessageDigest.getInstance(this.algorithm); - @Override - public String encode(CharSequence rawPassword) { - try { - String saltedPassword = mergeTextAndSalt(rawPassword, this.salt, false); - MessageDigest digest = MessageDigest.getInstance(this.algorithm); - return new String(Hex.encode(digest.digest(saltedPassword.getBytes("UTF-8")))); - } catch (UnsupportedEncodingException e) { - throw new RuntimeException("UTF-8 not supported"); - } catch (NoSuchAlgorithmException e) { - throw new RuntimeException("Algorithm " + algorithm + " not supported"); - } - } + return new String(Hex.encode(digest.digest(saltedPassword.getBytes(StandardCharsets.UTF_8)))); + } catch (NoSuchAlgorithmException e) { + throw new RuntimeException("Algorithm " + algorithm + " not supported"); + } + } - @Override - public boolean matches(CharSequence rawPassword, String encodedPassword) { - return this.encode(rawPassword).equals(encodedPassword); - } + @Override + public boolean matches(CharSequence rawPassword, String encodedPassword) { + return this.encode(rawPassword).equals(encodedPassword); + } - private String mergeTextAndSalt(CharSequence text, Object salt, boolean strict) { - if (text == null) { - text = ""; - } + private String mergeTextAndSalt(CharSequence text, Object salt, boolean strict) { + if (text == null) { + text = ""; + } - if ((strict) && (salt != null) && ((salt.toString().lastIndexOf("{") != -1) || (salt.toString().lastIndexOf("}") != -1))) { - throw new IllegalArgumentException("Cannot use { or } in salt.toString()"); - } + if ((strict) && (salt != null) && ((salt.toString().lastIndexOf("{") != -1) || (salt.toString().lastIndexOf("}") != -1))) { + throw new IllegalArgumentException("Cannot use { or } in salt.toString()"); + } - if ((salt == null) || ("".equals(salt))) { - return text.toString(); - } - return text + "{" + salt.toString() + "}"; - } + if ((salt == null) || ("".equals(salt))) { + return text.toString(); + } -} \ No newline at end of file + return text + "{" + salt + "}"; + } +} diff --git a/security-admin/src/main/java/org/apache/ranger/security/handler/RangerDomainObjectSecurityHandler.java b/security-admin/src/main/java/org/apache/ranger/security/handler/RangerDomainObjectSecurityHandler.java index 08b0f74e9a..df75c7a84e 100644 --- a/security-admin/src/main/java/org/apache/ranger/security/handler/RangerDomainObjectSecurityHandler.java +++ b/security-admin/src/main/java/org/apache/ranger/security/handler/RangerDomainObjectSecurityHandler.java @@ -17,14 +17,12 @@ * under the License. */ - package org.apache.ranger.security.handler; +package org.apache.ranger.security.handler; /** * */ -import java.io.Serializable; - import org.apache.ranger.biz.RangerBizUtil; import org.apache.ranger.common.ContextUtil; import org.apache.ranger.common.PropertiesUtil; @@ -36,78 +34,67 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; +import java.io.Serializable; + @Component public class RangerDomainObjectSecurityHandler { + private static final Logger logger = LoggerFactory.getLogger(RangerDomainObjectSecurityHandler.class); + + @Autowired + public RangerDaoManager daoManager; + + @Autowired + RangerBizUtil msBizUtil; + + boolean checkParentObject; + + public RangerDomainObjectSecurityHandler() { + checkParentObject = PropertiesUtil.getBooleanProperty("xa.db.access.filter.check.parentobject", checkParentObject); + } + + /** + * @return the daoManager + */ + public RangerDaoManager getDaoManager() { + return daoManager; + } + + public 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 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("Exception targetType:{}, targetId:{}", targetType, targetId, e); + } + + return false; + } + + public boolean hasAccess(Class targetClass, Serializable targetId, Permission.PermissionType permission) { + try { + Class gjClazz = targetClass.asSubclass(XXDBBase.class); + XXDBBase base = getDaoManager().getEntityManager().find(gjClazz, targetId); + + return hasAccess(base, permission); + } catch (Exception e) { + logger.error("Exception targetType:{}, targetId:{}", targetClass, targetId, e); + } + + return false; + } - private static final Logger logger = LoggerFactory - .getLogger(RangerDomainObjectSecurityHandler.class); - - @Autowired - public RangerDaoManager daoManager; - - @Autowired - RangerBizUtil msBizUtil; - - boolean checkParentObject = false; - - public RangerDomainObjectSecurityHandler() { - checkParentObject = PropertiesUtil.getBooleanProperty( - "xa.db.access.filter.check.parentobject", checkParentObject); - } - - /** - * @return the daoManager - */ - public RangerDaoManager getDaoManager() { - return daoManager; - } - - public 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 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 targetClass, - Serializable targetId, Permission.permissionType permission) { - try { - Class 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; - } + public boolean hasModeratorPermission() { + UserSessionBase sess = ContextUtil.getCurrentUserSession(); + return sess != null && sess.isUserAdmin(); + } } diff --git a/security-admin/src/main/java/org/apache/ranger/security/listener/RangerHttpSessionListener.java b/security-admin/src/main/java/org/apache/ranger/security/listener/RangerHttpSessionListener.java index 04edf66528..a13b16a99e 100644 --- a/security-admin/src/main/java/org/apache/ranger/security/listener/RangerHttpSessionListener.java +++ b/security-admin/src/main/java/org/apache/ranger/security/listener/RangerHttpSessionListener.java @@ -19,30 +19,28 @@ package org.apache.ranger.security.listener; -import java.util.concurrent.CopyOnWriteArrayList; - import javax.servlet.http.HttpSession; import javax.servlet.http.HttpSessionEvent; import javax.servlet.http.HttpSessionListener; -public class RangerHttpSessionListener implements HttpSessionListener { - - private static CopyOnWriteArrayList listOfSession = new CopyOnWriteArrayList(); - - @Override - public void sessionCreated(HttpSessionEvent event) { - listOfSession.add(event.getSession()); - } - - @Override - public void sessionDestroyed(HttpSessionEvent event) { - if (!listOfSession.isEmpty()) { - listOfSession.remove(event.getSession()); - } - } - - public static CopyOnWriteArrayList getActiveSessionOnServer() { - return listOfSession; - } +import java.util.concurrent.CopyOnWriteArrayList; +public class RangerHttpSessionListener implements HttpSessionListener { + private static final CopyOnWriteArrayList listOfSession = new CopyOnWriteArrayList<>(); + + public static CopyOnWriteArrayList getActiveSessionOnServer() { + return listOfSession; + } + + @Override + public void sessionCreated(HttpSessionEvent event) { + listOfSession.add(event.getSession()); + } + + @Override + public void sessionDestroyed(HttpSessionEvent event) { + if (!listOfSession.isEmpty()) { + listOfSession.remove(event.getSession()); + } + } } diff --git a/security-admin/src/main/java/org/apache/ranger/security/listener/SpringEventListener.java b/security-admin/src/main/java/org/apache/ranger/security/listener/SpringEventListener.java index c07fc5a5a4..88d28987e4 100644 --- a/security-admin/src/main/java/org/apache/ranger/security/listener/SpringEventListener.java +++ b/security-admin/src/main/java/org/apache/ranger/security/listener/SpringEventListener.java @@ -17,9 +17,8 @@ * under the License. */ - package org.apache.ranger.security.listener; +package org.apache.ranger.security.listener; -import java.util.Calendar; import org.apache.ranger.biz.SessionMgr; import org.apache.ranger.entity.XXAuthSession; import org.slf4j.Logger; @@ -29,17 +28,16 @@ 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.authentication.event.AuthenticationFailureLockedEvent; +import org.springframework.security.authentication.event.AuthenticationSuccessEvent; import org.springframework.security.core.Authentication; import org.springframework.security.web.authentication.WebAuthenticationDetails; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; +import java.util.Calendar; -public class SpringEventListener implements - ApplicationListener { - +public class SpringEventListener implements ApplicationListener { private static final Logger logger = LoggerFactory.getLogger(SpringEventListener.class); @Autowired @@ -47,92 +45,74 @@ public class SpringEventListener implements @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 AuthenticationFailureLockedEvent) { - process((AuthenticationFailureLockedEvent) event); - } else if (event instanceof AuthenticationFailureDisabledEvent) { - process((AuthenticationFailureDisabledEvent) event); - } - // igonre all other events - - } catch (Exception e) { - logger.error("Exception in Spring Event Listener.", e); - } + try { + if (event instanceof AuthenticationSuccessEvent) { + process((AuthenticationSuccessEvent) event); + } else if (event instanceof AuthenticationFailureBadCredentialsEvent) { + process((AuthenticationFailureBadCredentialsEvent) event); + } else if (event instanceof AuthenticationFailureLockedEvent) { + process((AuthenticationFailureLockedEvent) event); + } else if (event instanceof AuthenticationFailureDisabledEvent) { + process((AuthenticationFailureDisabledEvent) event); + } + // 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() : ""; - - Calendar cal = Calendar.getInstance(); - logger.info("Login Successful:" + auth.getName() + " | Ip Address:" - + remoteAddress + " | sessionId=" + sessionId + " | Epoch=" +cal.getTimeInMillis() ); - - // success logins are processed further in - // AKASecurityContextFormationFilter + Authentication auth = authSuccessEvent.getAuthentication(); + WebAuthenticationDetails details = (WebAuthenticationDetails) auth.getDetails(); + String remoteAddress = details != null ? details.getRemoteAddress() : ""; + String sessionId = details != null ? details.getSessionId() : ""; + + Calendar cal = Calendar.getInstance(); + + logger.info("Login Successful:{} | Ip Address:{} sessionId={} | Epoch={}", auth.getName(), remoteAddress, sessionId, cal.getTimeInMillis()); + // 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() : ""; - String userAgent = getUserAgent(); - - 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, userAgent); + 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() : ""; + String userAgent = getUserAgent(); + + logger.info("Login Unsuccessful:{} | Ip Address:{} | Bad Credentials", auth.getName(), remoteAddress); + + sessionMgr.processFailureLogin(XXAuthSession.AUTH_STATUS_WRONG_PASSWORD, XXAuthSession.AUTH_TYPE_PASSWORD, auth.getName(), remoteAddress, sessionId, userAgent); } protected void process(AuthenticationFailureLockedEvent authFailEvent) { - Authentication auth = authFailEvent.getAuthentication(); - WebAuthenticationDetails details = (WebAuthenticationDetails) auth.getDetails(); - String remoteAddress = details != null ? details.getRemoteAddress() : ""; - String sessionId = details != null ? details.getSessionId() : ""; - String userAgent = getUserAgent(); + Authentication auth = authFailEvent.getAuthentication(); + WebAuthenticationDetails details = (WebAuthenticationDetails) auth.getDetails(); + String remoteAddress = details != null ? details.getRemoteAddress() : ""; + String sessionId = details != null ? details.getSessionId() : ""; + String userAgent = getUserAgent(); - logger.info("Login Unsuccessful:" + auth.getName() + " | Ip Address:" + remoteAddress + " | User account is locked"); + logger.info("Login Unsuccessful:{} | Ip Address:{} | User account is locked", auth.getName(), remoteAddress); - sessionMgr.processFailureLogin(XXAuthSession.AUTH_STATUS_LOCKED, XXAuthSession.AUTH_TYPE_PASSWORD, - auth.getName(), remoteAddress, sessionId, userAgent); - } + sessionMgr.processFailureLogin(XXAuthSession.AUTH_STATUS_LOCKED, XXAuthSession.AUTH_TYPE_PASSWORD, auth.getName(), remoteAddress, sessionId, userAgent); + } 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() : ""; - String userAgent = getUserAgent(); + Authentication auth = authFailEvent.getAuthentication(); + WebAuthenticationDetails details = (WebAuthenticationDetails) auth.getDetails(); + String remoteAddress = details != null ? details.getRemoteAddress() : ""; + String sessionId = details != null ? details.getSessionId() : ""; + String userAgent = getUserAgent(); - logger.info("Login Unsuccessful:" + auth.getName() + " | Ip Address:" - + remoteAddress + " | User Disabled"); - - sessionMgr.processFailureLogin(XXAuthSession.AUTH_STATUS_DISABLED, - XXAuthSession.AUTH_TYPE_PASSWORD, auth.getName(), - remoteAddress, sessionId, userAgent); + logger.info("Login Unsuccessful:{} | Ip Address:{} | User Disabled", auth.getName(), remoteAddress); + sessionMgr.processFailureLogin(XXAuthSession.AUTH_STATUS_DISABLED, XXAuthSession.AUTH_TYPE_PASSWORD, auth.getName(), remoteAddress, sessionId, userAgent); } - protected String getUserAgent() { - ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); - String userAgent = attributes.getRequest().getHeader("User-Agent"); - return userAgent; - } + protected String getUserAgent() { + ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); + + return attributes.getRequest().getHeader("User-Agent"); + } } diff --git a/security-admin/src/main/java/org/apache/ranger/security/standalone/StandaloneSecurityHandler.java b/security-admin/src/main/java/org/apache/ranger/security/standalone/StandaloneSecurityHandler.java index 377b1a3b5d..8b22c6d070 100644 --- a/security-admin/src/main/java/org/apache/ranger/security/standalone/StandaloneSecurityHandler.java +++ b/security-admin/src/main/java/org/apache/ranger/security/standalone/StandaloneSecurityHandler.java @@ -17,15 +17,11 @@ * under the License. */ - /** +/** * */ package org.apache.ranger.security.standalone; -import java.net.InetAddress; -import java.util.ArrayList; -import java.util.Collection; - import org.apache.ranger.biz.SessionMgr; import org.apache.ranger.common.RangerConstants; import org.apache.ranger.entity.XXAuthSession; @@ -40,39 +36,42 @@ import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Component; +import java.net.InetAddress; +import java.util.ArrayList; +import java.util.Collection; + @Component public class StandaloneSecurityHandler { - public static final String AUTH_MANAGER_BEAN_NAME = "authenticationManager"; - public static final String ACCESS_DECISION_MANAGER_BEAN_NAME = "customAccessDecisionManager"; + 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); - @Autowired - SessionMgr sessionMgr; + // [3] Check User Access + AffirmativeBased accessDecisionManager = (AffirmativeBased) context.getBean(ACCESS_DECISION_MANAGER_BEAN_NAME); + Collection list = new ArrayList<>(); + SecurityConfig config = new SecurityConfig(RangerConstants.ROLE_SYS_ADMIN); - public void login(String userName, String password, - ApplicationContext context) throws Exception { - // [1] Create AUTH Token - Authentication token = new UsernamePasswordAuthenticationToken( - userName, password); + list.add(config); - // [2] Authenticate User - AuthenticationManager am = (AuthenticationManager) context - .getBean(AUTH_MANAGER_BEAN_NAME); - token = am.authenticate(token); + accessDecisionManager.decide(token, null, list); - // [3] Check User Access - AffirmativeBased accessDecisionManager = (AffirmativeBased) context - .getBean(ACCESS_DECISION_MANAGER_BEAN_NAME); - Collection list = new ArrayList(); - SecurityConfig config = new SecurityConfig(RangerConstants.ROLE_SYS_ADMIN); - list.add(config); - accessDecisionManager.decide(token, null, list); + // [4] set token in spring context + SecurityContextHolder.getContext().setAuthentication(token); - // [4] set token in spring context - SecurityContextHolder.getContext().setAuthentication(token); + // [5] Process Success login + InetAddress thisIp = InetAddress.getLocalHost(); - // [5] Process Success login - InetAddress thisIp = InetAddress.getLocalHost(); - sessionMgr.processStandaloneSuccessLogin( - XXAuthSession.AUTH_TYPE_PASSWORD, thisIp.getHostAddress()); - } + sessionMgr.processStandaloneSuccessLogin(XXAuthSession.AUTH_TYPE_PASSWORD, thisIp.getHostAddress()); + } } diff --git a/security-admin/src/main/java/org/apache/ranger/security/web/authentication/CustomLogoutSuccessHandler.java b/security-admin/src/main/java/org/apache/ranger/security/web/authentication/CustomLogoutSuccessHandler.java index 0fb9b12a80..91f6cb3ad2 100644 --- a/security-admin/src/main/java/org/apache/ranger/security/web/authentication/CustomLogoutSuccessHandler.java +++ b/security-admin/src/main/java/org/apache/ranger/security/web/authentication/CustomLogoutSuccessHandler.java @@ -17,13 +17,7 @@ * under the License. */ - package org.apache.ranger.security.web.authentication; - -import java.io.IOException; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +package org.apache.ranger.security.web.authentication; import org.apache.ranger.common.JSONUtil; import org.apache.ranger.view.VXResponse; @@ -32,39 +26,40 @@ import org.springframework.security.web.authentication.logout.LogoutSuccessHandler; import org.springframework.security.web.authentication.logout.SimpleUrlLogoutSuccessHandler; -public class CustomLogoutSuccessHandler extends SimpleUrlLogoutSuccessHandler - implements LogoutSuccessHandler { +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import java.io.IOException; + +public class CustomLogoutSuccessHandler extends SimpleUrlLogoutSuccessHandler implements LogoutSuccessHandler { + @Autowired + JSONUtil jsonUtil; + + @Override + public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException { + request.getServletContext().removeAttribute(request.getRequestedSessionId()); + + response.setContentType("application/json;charset=UTF-8"); + response.setHeader("Cache-Control", "no-cache"); + response.setHeader("X-Frame-Options", "DENY"); - @Autowired - JSONUtil jsonUtil; + try { + VXResponse vXResponse = new VXResponse(); - @Override - public void onLogoutSuccess(HttpServletRequest request, - HttpServletResponse response, Authentication authentication) - throws IOException, ServletException { + vXResponse.setStatusCode(HttpServletResponse.SC_OK); + vXResponse.setMsgDesc("Logout Successful"); - request.getServletContext().removeAttribute(request.getRequestedSessionId()); - - response.setContentType("application/json;charset=UTF-8"); - response.setHeader("Cache-Control", "no-cache"); - response.setHeader("X-Frame-Options", "DENY"); - String jsonStr = ""; - try { - VXResponse vXResponse = new VXResponse(); - vXResponse.setStatusCode(HttpServletResponse.SC_OK); - vXResponse.setMsgDesc("Logout Successful"); - jsonStr = jsonUtil.writeObjectAsString(vXResponse); + String 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"); - } - } + 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"); + } + } } diff --git a/security-admin/src/main/java/org/apache/ranger/security/web/authentication/RangerAuthFailureHandler.java b/security-admin/src/main/java/org/apache/ranger/security/web/authentication/RangerAuthFailureHandler.java index 99d8363d96..312d9dc683 100644 --- a/security-admin/src/main/java/org/apache/ranger/security/web/authentication/RangerAuthFailureHandler.java +++ b/security-admin/src/main/java/org/apache/ranger/security/web/authentication/RangerAuthFailureHandler.java @@ -17,17 +17,11 @@ * under the License. */ - /** +/** * */ package org.apache.ranger.security.web.authentication; -import java.io.IOException; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - import org.apache.ranger.common.JSONUtil; import org.apache.ranger.common.PropertiesUtil; import org.apache.ranger.util.CLIUtil; @@ -38,24 +32,28 @@ import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.authentication.ExceptionMappingAuthenticationFailureHandler; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import java.io.IOException; + /** - * * */ -public class RangerAuthFailureHandler extends -ExceptionMappingAuthenticationFailureHandler { +public class RangerAuthFailureHandler extends ExceptionMappingAuthenticationFailureHandler { private static final Logger LOG = LoggerFactory.getLogger(RangerAuthFailureHandler.class); - String ajaxLoginfailurePage = null; + String ajaxLoginfailurePage; @Autowired JSONUtil jsonUtil; public RangerAuthFailureHandler() { - super(); - if (ajaxLoginfailurePage == null) { - ajaxLoginfailurePage = PropertiesUtil.getProperty("ranger.ajax.auth.failure.page", "/ajax_failure.jsp"); - } + super(); + + if (ajaxLoginfailurePage == null) { + ajaxLoginfailurePage = PropertiesUtil.getProperty("ranger.ajax.auth.failure.page", "/ajax_failure.jsp"); + } } /* @@ -68,52 +66,52 @@ public RangerAuthFailureHandler() { * 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 (LOG.isDebugEnabled()) { - LOG.debug("commence() X-Requested-With=" + ajaxRequestHeader); - } - - response.setContentType("application/json;charset=UTF-8"); - response.setHeader("Cache-Control", "no-cache"); - response.setHeader("X-Frame-Options", "DENY"); - String jsonResp = ""; - try { - String msg = exception.getMessage(); - VXResponse vXResponse = new VXResponse(); - if (msg != null && !msg.isEmpty()) { - if (CLIUtil.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials",request).equalsIgnoreCase(msg)) { - vXResponse.setStatusCode(HttpServletResponse.SC_UNAUTHORIZED); - vXResponse.setMsgDesc("The username or password you entered is incorrect."); - LOG.info("Error Message : " + msg); - } else if (msg.contains("Could not get JDBC Connection; nested exception is java.sql.SQLException: Connections could not be acquired from the underlying database!")) { - vXResponse.setStatusCode(HttpServletResponse.SC_UNAUTHORIZED); - vXResponse.setMsgDesc("Unable to connect to DB."); - } else if (msg.contains("Communications link failure")) { - vXResponse.setStatusCode(HttpServletResponse.SC_UNAUTHORIZED); - vXResponse.setMsgDesc("Unable to connect to DB."); - } else if (CLIUtil.getMessage("AbstractUserDetailsAuthenticationProvider.disabled",request).equalsIgnoreCase(msg)) { - vXResponse.setStatusCode(HttpServletResponse.SC_UNAUTHORIZED); - vXResponse.setMsgDesc("The username or password you entered is disabled."); - } else if (CLIUtil.getMessage("AbstractUserDetailsAuthenticationProvider.locked",request).equalsIgnoreCase(msg)) { - vXResponse.setStatusCode(HttpServletResponse.SC_UNAUTHORIZED); - vXResponse.setMsgDesc("The user account is locked."); - } - } - jsonResp = jsonUtil.writeObjectAsString(vXResponse); - response.getWriter().write(jsonResp); - response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); - } catch (IOException e) { - LOG.info("Error while writing JSON in HttpServletResponse"); - } - - if (ajaxRequestHeader != null && "XMLHttpRequest".equalsIgnoreCase(ajaxRequestHeader)) { - if (LOG.isDebugEnabled()) { - LOG.debug("Sending login failed response : " + jsonResp); - } - } - } + public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) { + String ajaxRequestHeader = request.getHeader("X-Requested-With"); + + LOG.debug("commence() X-Requested-With={}", ajaxRequestHeader); + + response.setContentType("application/json;charset=UTF-8"); + response.setHeader("Cache-Control", "no-cache"); + response.setHeader("X-Frame-Options", "DENY"); + + String jsonResp = ""; + + try { + String msg = exception.getMessage(); + VXResponse vXResponse = new VXResponse(); + if (msg != null && !msg.isEmpty()) { + if (CLIUtil.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", request).equalsIgnoreCase(msg)) { + vXResponse.setStatusCode(HttpServletResponse.SC_UNAUTHORIZED); + vXResponse.setMsgDesc("The username or password you entered is incorrect."); + + LOG.info("Error Message : {}", msg); + } else if (msg.contains("Could not get JDBC Connection; nested exception is java.sql.SQLException: Connections could not be acquired from the underlying database!")) { + vXResponse.setStatusCode(HttpServletResponse.SC_UNAUTHORIZED); + vXResponse.setMsgDesc("Unable to connect to DB."); + } else if (msg.contains("Communications link failure")) { + vXResponse.setStatusCode(HttpServletResponse.SC_UNAUTHORIZED); + vXResponse.setMsgDesc("Unable to connect to DB."); + } else if (CLIUtil.getMessage("AbstractUserDetailsAuthenticationProvider.disabled", request).equalsIgnoreCase(msg)) { + vXResponse.setStatusCode(HttpServletResponse.SC_UNAUTHORIZED); + vXResponse.setMsgDesc("The username or password you entered is disabled."); + } else if (CLIUtil.getMessage("AbstractUserDetailsAuthenticationProvider.locked", request).equalsIgnoreCase(msg)) { + vXResponse.setStatusCode(HttpServletResponse.SC_UNAUTHORIZED); + vXResponse.setMsgDesc("The user account is locked."); + } + } + + jsonResp = jsonUtil.writeObjectAsString(vXResponse); + + response.getWriter().write(jsonResp); + response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); + } catch (IOException e) { + LOG.info("Error while writing JSON in HttpServletResponse"); + } + + if ("XMLHttpRequest".equalsIgnoreCase(ajaxRequestHeader)) { + LOG.debug("Sending login failed response : {}", jsonResp); + } + } } diff --git a/security-admin/src/main/java/org/apache/ranger/security/web/authentication/RangerAuthSuccessHandler.java b/security-admin/src/main/java/org/apache/ranger/security/web/authentication/RangerAuthSuccessHandler.java index 890c334223..84812b360c 100644 --- a/security-admin/src/main/java/org/apache/ranger/security/web/authentication/RangerAuthSuccessHandler.java +++ b/security-admin/src/main/java/org/apache/ranger/security/web/authentication/RangerAuthSuccessHandler.java @@ -17,17 +17,11 @@ * under the License. */ - /** +/** * */ package org.apache.ranger.security.web.authentication; -import java.io.IOException; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - import org.apache.ranger.biz.SessionMgr; import org.apache.ranger.biz.XUserMgr; import org.apache.ranger.common.JSONUtil; @@ -41,15 +35,18 @@ import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler; import org.springframework.security.web.authentication.WebAuthenticationDetails; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import java.io.IOException; + /** - * * */ -public class RangerAuthSuccessHandler extends -SavedRequestAwareAuthenticationSuccessHandler { +public class RangerAuthSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler { private static final Logger LOG = LoggerFactory.getLogger(RangerAuthSuccessHandler.class); - String ajaxLoginSuccessPage = null; + String ajaxLoginSuccessPage; @Autowired SessionMgr sessionMgr; @@ -57,14 +54,15 @@ public class RangerAuthSuccessHandler extends @Autowired JSONUtil jsonUtil; - @Autowired - XUserMgr xUserMgr; + @Autowired + XUserMgr xUserMgr; public RangerAuthSuccessHandler() { - super(); - if (ajaxLoginSuccessPage == null) { - ajaxLoginSuccessPage = PropertiesUtil.getProperty("ranger.ajax.auth.success.page", "/ajax_success.html"); - } + super(); + + if (ajaxLoginSuccessPage == null) { + ajaxLoginSuccessPage = PropertiesUtil.getProperty("ranger.ajax.auth.success.page", "/ajax_success.html"); + } } /* @@ -77,95 +75,91 @@ public RangerAuthSuccessHandler() { * org.springframework.security.core.Authentication) */ @Override - public void onAuthenticationSuccess(HttpServletRequest request, - HttpServletResponse response, Authentication authentication) - throws ServletException, IOException { - - RangerSessionFixationProtectionStrategy rangerSessionFixationProtectionStrategy=new RangerSessionFixationProtectionStrategy(); - rangerSessionFixationProtectionStrategy.onAuthentication(authentication, request, response); - WebAuthenticationDetails details = (WebAuthenticationDetails) authentication - .getDetails(); - String remoteAddress = details != null ? details.getRemoteAddress() - : ""; - String sessionId = details != null ? details.getSessionId() : ""; - String userAgent = request.getHeader("User-Agent"); - - boolean isValidUser = sessionMgr.isValidXAUser(authentication.getName()); - String rangerAuthenticationMethod=PropertiesUtil.getProperty("ranger.authentication.method","NONE"); - if(!isValidUser && !"NONE".equalsIgnoreCase(rangerAuthenticationMethod)){ - xUserMgr.createServiceConfigUser(authentication.getName()); - isValidUser = sessionMgr.isValidXAUser(authentication.getName()); - } - - response.setContentType("application/json;charset=UTF-8"); - response.setHeader("Cache-Control", "no-cache"); - response.setHeader("X-Frame-Options", "DENY"); - VXResponse vXResponse = new VXResponse(); - - if(!isValidUser) { - sessionMgr.processFailureLogin( - XXAuthSession.AUTH_STATUS_USER_NOT_FOUND, - XXAuthSession.AUTH_TYPE_PASSWORD, authentication.getName(), - remoteAddress, sessionId, userAgent); - authentication.setAuthenticated(false); - - vXResponse.setStatusCode(HttpServletResponse.SC_PRECONDITION_FAILED); - vXResponse.setMsgDesc("Auth Succeeded but user is not synced yet or federated-user for " + authentication.getName()); - - response.setStatus(HttpServletResponse.SC_PRECONDITION_FAILED); - response.getWriter().write(jsonUtil.writeObjectAsString(vXResponse)); - - // response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED); - LOG.info("Auth Succeeded but user is not synced yet for " - + authentication.getName()); - - } else { - - String ajaxRequestHeader = request.getHeader("X-Requested-With"); - if (LOG.isDebugEnabled()) { - LOG.debug("commence() X-Requested-With=" + ajaxRequestHeader); - } - if (ajaxRequestHeader != null && "XMLHttpRequest".equalsIgnoreCase(ajaxRequestHeader)) { - // 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) { - LOG.info("Error while writing JSON in HttpServletResponse"); - } - if (LOG.isDebugEnabled()) { - LOG.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) { - LOG.info("Error while writing JSON in HttpServletResponse"); - } - if (LOG.isDebugEnabled()) { - LOG.debug("Sending login success response : " + jsonResp); - } - } - } - } + public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException { + RangerSessionFixationProtectionStrategy rangerSessionFixationProtectionStrategy = new RangerSessionFixationProtectionStrategy(); + + rangerSessionFixationProtectionStrategy.onAuthentication(authentication, request, response); + + WebAuthenticationDetails details = (WebAuthenticationDetails) authentication.getDetails(); + String remoteAddress = details != null ? details.getRemoteAddress() : ""; + String sessionId = details != null ? details.getSessionId() : ""; + String userAgent = request.getHeader("User-Agent"); + + boolean isValidUser = sessionMgr.isValidXAUser(authentication.getName()); + String rangerAuthenticationMethod = PropertiesUtil.getProperty("ranger.authentication.method", "NONE"); + + if (!isValidUser && !"NONE".equalsIgnoreCase(rangerAuthenticationMethod)) { + xUserMgr.createServiceConfigUser(authentication.getName()); + + isValidUser = sessionMgr.isValidXAUser(authentication.getName()); + } + response.setContentType("application/json;charset=UTF-8"); + response.setHeader("Cache-Control", "no-cache"); + response.setHeader("X-Frame-Options", "DENY"); + + VXResponse vXResponse = new VXResponse(); + + if (!isValidUser) { + sessionMgr.processFailureLogin(XXAuthSession.AUTH_STATUS_USER_NOT_FOUND, XXAuthSession.AUTH_TYPE_PASSWORD, authentication.getName(), remoteAddress, sessionId, userAgent); + authentication.setAuthenticated(false); + + vXResponse.setStatusCode(HttpServletResponse.SC_PRECONDITION_FAILED); + vXResponse.setMsgDesc("Auth Succeeded but user is not synced yet or federated-user for " + authentication.getName()); + + response.setStatus(HttpServletResponse.SC_PRECONDITION_FAILED); + response.getWriter().write(jsonUtil.writeObjectAsString(vXResponse)); + + // response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED); + LOG.info("Auth Succeeded but user is not synced yet for {}", authentication.getName()); + } else { + String ajaxRequestHeader = request.getHeader("X-Requested-With"); + + LOG.debug("commence() X-Requested-With={}", ajaxRequestHeader); + + if ("XMLHttpRequest".equalsIgnoreCase(ajaxRequestHeader)) { + // 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) { + LOG.info("Error while writing JSON in HttpServletResponse"); + } + + LOG.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) { + LOG.info("Error while writing JSON in HttpServletResponse"); + } + LOG.debug("Sending login success response : {}", jsonResp); + } + } + } } diff --git a/security-admin/src/main/java/org/apache/ranger/security/web/authentication/RangerAuthenticationEntryPoint.java b/security-admin/src/main/java/org/apache/ranger/security/web/authentication/RangerAuthenticationEntryPoint.java index 34963d1af9..cf29bb97bc 100644 --- a/security-admin/src/main/java/org/apache/ranger/security/web/authentication/RangerAuthenticationEntryPoint.java +++ b/security-admin/src/main/java/org/apache/ranger/security/web/authentication/RangerAuthenticationEntryPoint.java @@ -22,12 +22,6 @@ */ package org.apache.ranger.security.web.authentication; -import java.io.IOException; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - import org.apache.ranger.biz.SessionMgr; import org.apache.ranger.common.JSONUtil; import org.apache.ranger.common.PropertiesUtil; @@ -40,103 +34,94 @@ import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import java.io.IOException; + /** - * * */ -public class RangerAuthenticationEntryPoint extends - LoginUrlAuthenticationEntryPoint { - public static final int SC_AUTHENTICATION_TIMEOUT = 419; - - private static final Logger logger = LoggerFactory - .getLogger(RangerAuthenticationEntryPoint.class); - static int ajaxReturnCode = -1; - - @Autowired - RangerConfigUtil configUtil; - - @Autowired - JSONUtil jsonUtil; - - @Autowired - SessionMgr sessionMgr; - - public RangerAuthenticationEntryPoint(String loginFormUrl) { - super(loginFormUrl); - if (logger.isDebugEnabled()) { - logger.debug("AjaxAwareAuthenticationEntryPoint(): constructor"); - } - - if (ajaxReturnCode < 0) { - ajaxReturnCode = PropertiesUtil.getIntProperty( - "ranger.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"); - response.setHeader("X-Frame-Options", "DENY"); - if (logger.isDebugEnabled()) { - logger.debug("commence() X-Requested-With=" + ajaxRequestHeader); - } - - String requestURI = (request.getRequestURI() != null) ? request - .getRequestURI() : ""; - String servletPath = PropertiesUtil.getProperty( - "ranger.servlet.mapping.url.pattern", "service"); - if (logger.isDebugEnabled()) { - logger.debug("===> RangerAuthenticationEntryPoint.commence() servletPath["+servletPath+"] requestURI ["+requestURI+"]"); - } - if ("XMLHttpRequest".equals(ajaxRequestHeader)) { - try { - - VXResponse vXResponse = new VXResponse(); - - vXResponse.setStatusCode(SC_AUTHENTICATION_TIMEOUT); - vXResponse.setMsgDesc("Session Timeout"); - - response.setStatus(SC_AUTHENTICATION_TIMEOUT); - response.getWriter().write( - jsonUtil.writeObjectAsString(vXResponse)); - } catch (IOException e) { - logger.info("Error while writing JSON in HttpServletResponse"); - } - return; - } else { - 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 - && "XMLHttpRequest".equalsIgnoreCase(ajaxRequestHeader)) { - if (logger.isDebugEnabled()) { - logger.debug("commence() AJAX request. Authentication required. Returning " - + ajaxReturnCode + ". URL=" + request.getRequestURI()); - } - response.sendError(ajaxReturnCode, ""); - } else if (!(requestURI.contains(servletPath))) { - if(requestURI.contains(RestUtil.LOCAL_LOGIN_URL)){ - if (request.getSession() != null){ - request.getSession().setAttribute("locallogin","true"); - request.getServletContext().setAttribute(request.getSession().getId(), "locallogin"); - } - } - super.commence(request, response, authException); - } - } +public class RangerAuthenticationEntryPoint extends LoginUrlAuthenticationEntryPoint { + private static final Logger logger = LoggerFactory.getLogger(RangerAuthenticationEntryPoint.class); + + public static final int SC_AUTHENTICATION_TIMEOUT = 419; + static int ajaxReturnCode = -1; + + @Autowired + RangerConfigUtil configUtil; + + @Autowired + JSONUtil jsonUtil; + + @Autowired + SessionMgr sessionMgr; + + public RangerAuthenticationEntryPoint(String loginFormUrl) { + super(loginFormUrl); + + logger.debug("AjaxAwareAuthenticationEntryPoint(): constructor"); + + if (ajaxReturnCode < 0) { + ajaxReturnCode = PropertiesUtil.getIntProperty("ranger.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"); + + response.setHeader("X-Frame-Options", "DENY"); + + logger.debug("commence() X-Requested-With={}", ajaxRequestHeader); + + String requestURI = (request.getRequestURI() != null) ? request.getRequestURI() : ""; + String servletPath = PropertiesUtil.getProperty("ranger.servlet.mapping.url.pattern", "service"); + + logger.debug("===> RangerAuthenticationEntryPoint.commence() servletPath[{}] requestURI [{}]", servletPath, requestURI); + + if ("XMLHttpRequest".equals(ajaxRequestHeader)) { + try { + VXResponse vXResponse = new VXResponse(); + + vXResponse.setStatusCode(SC_AUTHENTICATION_TIMEOUT); + vXResponse.setMsgDesc("Session Timeout"); + + response.setStatus(SC_AUTHENTICATION_TIMEOUT); + response.getWriter().write(jsonUtil.writeObjectAsString(vXResponse)); + } catch (IOException e) { + logger.info("Error while writing JSON in HttpServletResponse"); + } + + return; + } else { + 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 ("XMLHttpRequest".equalsIgnoreCase(ajaxRequestHeader)) { + logger.debug("commence() AJAX request. Authentication required. Returning {}, URL={}", ajaxReturnCode, request.getRequestURI()); + + response.sendError(ajaxReturnCode, ""); + } else if (!(requestURI.contains(servletPath))) { + if (requestURI.contains(RestUtil.LOCAL_LOGIN_URL)) { + if (request.getSession() != null) { + request.getSession().setAttribute("locallogin", "true"); + request.getServletContext().setAttribute(request.getSession().getId(), "locallogin"); + } + } + super.commence(request, response, authException); + } + } } diff --git a/security-admin/src/main/java/org/apache/ranger/security/web/authentication/RangerSessionFixationProtectionStrategy.java b/security-admin/src/main/java/org/apache/ranger/security/web/authentication/RangerSessionFixationProtectionStrategy.java index 1db24659d2..750892e04e 100644 --- a/security-admin/src/main/java/org/apache/ranger/security/web/authentication/RangerSessionFixationProtectionStrategy.java +++ b/security-admin/src/main/java/org/apache/ranger/security/web/authentication/RangerSessionFixationProtectionStrategy.java @@ -19,15 +19,15 @@ package org.apache.ranger.security.web.authentication; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; import org.springframework.security.core.Authentication; import org.springframework.security.web.authentication.session.SessionFixationProtectionStrategy; -public class RangerSessionFixationProtectionStrategy extends SessionFixationProtectionStrategy { +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +public class RangerSessionFixationProtectionStrategy extends SessionFixationProtectionStrategy { @Override - public void onAuthentication(Authentication authentication, HttpServletRequest request, HttpServletResponse response){ - super.onAuthentication(authentication, request, response); + public void onAuthentication(Authentication authentication, HttpServletRequest request, HttpServletResponse response) { + super.onAuthentication(authentication, request, response); } } diff --git a/security-admin/src/main/java/org/apache/ranger/security/web/filter/MyRememberMeFilter.java b/security-admin/src/main/java/org/apache/ranger/security/web/filter/MyRememberMeFilter.java index 1bd10f9658..c5b8678187 100644 --- a/security-admin/src/main/java/org/apache/ranger/security/web/filter/MyRememberMeFilter.java +++ b/security-admin/src/main/java/org/apache/ranger/security/web/filter/MyRememberMeFilter.java @@ -17,12 +17,18 @@ * under the License. */ - /** +/** * */ package org.apache.ranger.security.web.filter; -import java.io.IOException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.AuthenticationException; +import org.springframework.security.web.authentication.RememberMeServices; +import org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationFilter; import javax.servlet.FilterChain; import javax.servlet.ServletException; @@ -31,26 +37,18 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.security.authentication.AuthenticationManager; -import org.springframework.security.core.Authentication; -import org.springframework.security.core.AuthenticationException; -import org.springframework.security.web.authentication.RememberMeServices; -import org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationFilter; +import java.io.IOException; /** - * * */ @SuppressWarnings("deprecation") public class MyRememberMeFilter extends RememberMeAuthenticationFilter { + private static final Logger LOG = LoggerFactory.getLogger(MyRememberMeFilter.class); public MyRememberMeFilter(AuthenticationManager authenticationManager, RememberMeServices rememberMeServices) { - super(authenticationManager, rememberMeServices); - } - - private static final Logger LOG = LoggerFactory.getLogger(MyRememberMeFilter.class); + super(authenticationManager, rememberMeServices); + } /* * (non-Javadoc) @@ -60,11 +58,12 @@ public MyRememberMeFilter(AuthenticationManager authenticationManager, RememberM * javax.servlet.ServletResponse, javax.servlet.FilterChain) */ @Override - public void doFilter(ServletRequest arg0, ServletResponse arg1, - FilterChain arg2) throws IOException, ServletException { - HttpServletResponse res = (HttpServletResponse)arg1; - res.setHeader("X-Frame-Options", "DENY" ); - super.doFilter(arg0, res, arg2); + public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2) throws IOException, ServletException { + HttpServletResponse res = (HttpServletResponse) arg1; + + res.setHeader("X-Frame-Options", "DENY"); + + super.doFilter(arg0, res, arg2); } /* @@ -77,11 +76,12 @@ public void doFilter(ServletRequest arg0, ServletResponse arg1, * org.springframework.security.core.Authentication) */ @Override - protected void onSuccessfulAuthentication(HttpServletRequest request, - HttpServletResponse response, Authentication authResult) { - response.setHeader("X-Frame-Options", "DENY" ); - super.onSuccessfulAuthentication(request, response, authResult); - LOG.info("onSuccessfulAuthentication() authResult=" + authResult); + protected void onSuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, Authentication authResult) { + response.setHeader("X-Frame-Options", "DENY"); + + super.onSuccessfulAuthentication(request, response, authResult); + + LOG.info("onSuccessfulAuthentication() authResult={}", authResult); } /* @@ -94,12 +94,11 @@ protected void onSuccessfulAuthentication(HttpServletRequest request, * org.springframework.security.core.AuthenticationException) */ @Override - protected void onUnsuccessfulAuthentication(HttpServletRequest request, - HttpServletResponse response, AuthenticationException failed) { - LOG.error("Authentication failure. failed=" + failed, - new Throwable()); - response.setHeader("X-Frame-Options", "DENY" ); - super.onUnsuccessfulAuthentication(request, response, failed); - } + protected void onUnsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) { + LOG.error("Authentication failure. failed={}", failed, new Throwable()); + + response.setHeader("X-Frame-Options", "DENY"); + super.onUnsuccessfulAuthentication(request, response, failed); + } } diff --git a/security-admin/src/main/java/org/apache/ranger/security/web/filter/RangerCSRFPreventionFilter.java b/security-admin/src/main/java/org/apache/ranger/security/web/filter/RangerCSRFPreventionFilter.java index 7cc7f5e63f..41bbb2969f 100644 --- a/security-admin/src/main/java/org/apache/ranger/security/web/filter/RangerCSRFPreventionFilter.java +++ b/security-admin/src/main/java/org/apache/ranger/security/web/filter/RangerCSRFPreventionFilter.java @@ -19,10 +19,11 @@ package org.apache.ranger.security.web.filter; -import java.io.IOException; -import java.util.Collections; -import java.util.HashSet; -import java.util.Set; +import org.apache.commons.lang.StringUtils; +import org.apache.ranger.common.PropertiesUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; @@ -33,217 +34,209 @@ import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; -import org.apache.commons.lang.StringUtils; -import org.apache.ranger.common.PropertiesUtil; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import java.io.IOException; +import java.util.Collections; +import java.util.HashSet; +import java.util.Set; public class RangerCSRFPreventionFilter implements Filter { - - private static final Logger LOG = LoggerFactory.getLogger(RangerCSRFPreventionFilter.class); - - public static final String BROWSER_USER_AGENT_PARAM = "ranger.rest-csrf.browser-useragents-regex"; - public static final String BROWSER_USER_AGENTS_DEFAULT = "Mozilla,Opera,Chrome"; - public static final String CUSTOM_METHODS_TO_IGNORE_PARAM = "ranger.rest-csrf.methods-to-ignore"; - public static final String METHODS_TO_IGNORE_DEFAULT = "GET,OPTIONS,HEAD,TRACE"; - public static final String CUSTOM_HEADER_PARAM = "ranger.rest-csrf.custom-header"; - public static final String HEADER_DEFAULT = "X-XSRF-HEADER"; - public static final String HEADER_USER_AGENT = "User-Agent"; - public static final String CSRF_TOKEN = "_csrfToken"; - private static final boolean IS_CSRF_ENABLED = PropertiesUtil.getBooleanProperty("ranger.rest-csrf.enabled", true); - - private String headerName = HEADER_DEFAULT; - private Set methodsToIgnore = null; - private String[] browserUserAgents; - - public RangerCSRFPreventionFilter() { - try { - if (IS_CSRF_ENABLED){ - init(null); - } - } catch (Exception e) { - LOG.error("Error while initializing Filter : "+e.getMessage()); - } - } - - public void init(FilterConfig filterConfig) throws ServletException { - String customHeader = PropertiesUtil.getProperty(CUSTOM_HEADER_PARAM, HEADER_DEFAULT); - if (customHeader != null) { - headerName = customHeader; - } - - String customMethodsToIgnore = PropertiesUtil.getProperty(CUSTOM_METHODS_TO_IGNORE_PARAM, METHODS_TO_IGNORE_DEFAULT); + private static final Logger LOG = LoggerFactory.getLogger(RangerCSRFPreventionFilter.class); + + public static final String BROWSER_USER_AGENT_PARAM = "ranger.rest-csrf.browser-useragents-regex"; + public static final String BROWSER_USER_AGENTS_DEFAULT = "Mozilla,Opera,Chrome"; + public static final String CUSTOM_METHODS_TO_IGNORE_PARAM = "ranger.rest-csrf.methods-to-ignore"; + public static final String METHODS_TO_IGNORE_DEFAULT = "GET,OPTIONS,HEAD,TRACE"; + public static final String CUSTOM_HEADER_PARAM = "ranger.rest-csrf.custom-header"; + public static final String HEADER_DEFAULT = "X-XSRF-HEADER"; + public static final String HEADER_USER_AGENT = "User-Agent"; + public static final String CSRF_TOKEN = "_csrfToken"; + + private static final boolean IS_CSRF_ENABLED = PropertiesUtil.getBooleanProperty("ranger.rest-csrf.enabled", true); + + private String headerName = HEADER_DEFAULT; + private Set methodsToIgnore; + private String[] browserUserAgents; + + public RangerCSRFPreventionFilter() { + try { + if (IS_CSRF_ENABLED) { + init(null); + } + } catch (Exception e) { + LOG.error("Error while initializing Filter : {}", e.getMessage()); + } + } + + public void init(FilterConfig filterConfig) throws ServletException { + String customHeader = PropertiesUtil.getProperty(CUSTOM_HEADER_PARAM, HEADER_DEFAULT); + + if (customHeader != null) { + headerName = customHeader; + } + + String customMethodsToIgnore = PropertiesUtil.getProperty(CUSTOM_METHODS_TO_IGNORE_PARAM, METHODS_TO_IGNORE_DEFAULT); + if (customMethodsToIgnore != null) { - parseMethodsToIgnore(customMethodsToIgnore); + parseMethodsToIgnore(customMethodsToIgnore); } else { - parseMethodsToIgnore(METHODS_TO_IGNORE_DEFAULT); + parseMethodsToIgnore(METHODS_TO_IGNORE_DEFAULT); } + String agents = PropertiesUtil.getProperty(BROWSER_USER_AGENT_PARAM, BROWSER_USER_AGENTS_DEFAULT); + if (agents == null) { - agents = BROWSER_USER_AGENTS_DEFAULT; + agents = BROWSER_USER_AGENTS_DEFAULT; } + parseBrowserUserAgents(agents); + LOG.info("Adding cross-site request forgery (CSRF) protection"); - } - - void parseMethodsToIgnore(String mti) { + } + + public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { + if (IS_CSRF_ENABLED) { + final HttpServletRequest httpRequest = (HttpServletRequest) request; + final HttpServletResponse httpResponse = (HttpServletResponse) response; + boolean spnegoEnabled = httpRequest.getAttribute("spnegoEnabled") != null && Boolean.parseBoolean(String.valueOf(httpRequest.getAttribute("spnegoEnabled"))); + boolean trustedProxyEnabled = httpRequest.getAttribute("trustedProxyEnabled") != null && Boolean.parseBoolean(String.valueOf(httpRequest.getAttribute("trustedProxyEnabled"))); + + handleHttpInteraction(new ServletFilterHttpInteraction(httpRequest, httpResponse, chain), spnegoEnabled, trustedProxyEnabled); + } else { + chain.doFilter(request, response); + } + } + + public void destroy() { + } + + public void handleHttpInteraction(HttpInteraction httpInteraction, boolean spnegoEnabled, boolean trustedProxyEnabled) throws IOException, ServletException { + HttpSession session = ((ServletFilterHttpInteraction) httpInteraction).getSession(); + String clientCsrfToken = httpInteraction.getHeader(headerName); + String actualCsrfToken = StringUtils.EMPTY; + + if (session != null) { + actualCsrfToken = (String) session.getAttribute(CSRF_TOKEN); + } else { + LOG.debug("Session is null"); + } + + LOG.debug("actualCsrfToken = {}, clientCsrfToken = {}, trustedProxy = {}, for {}", actualCsrfToken, clientCsrfToken, trustedProxyEnabled, ((ServletFilterHttpInteraction) httpInteraction).httpRequest.getRequestURI()); + + /* When the request is from Knox, then spnegoEnabled and trustedProxyEnabled are true. + * In this case Knox inserts XSRF header with proper value for POST & PUT requests and hence proceed with authentication filter + */ + if ((spnegoEnabled && trustedProxyEnabled) || clientCsrfToken != null && clientCsrfToken.equals(actualCsrfToken) || !isBrowser(httpInteraction.getHeader(HEADER_USER_AGENT)) || methodsToIgnore.contains(httpInteraction.getMethod())) { + httpInteraction.proceed(); + } else { + LOG.error("Missing header or invalid Header value for CSRF Vulnerability Protection"); + + httpInteraction.sendError(HttpServletResponse.SC_BAD_REQUEST, "Missing header or invalid Header value for CSRF Vulnerability Protection"); + } + } + + protected boolean isBrowser(String userAgent) { + boolean isWeb = false; + + if (browserUserAgents != null && browserUserAgents.length > 0 && userAgent != null) { + for (String ua : browserUserAgents) { + if (userAgent.toLowerCase().startsWith(ua.toLowerCase())) { + isWeb = true; + break; + } + } + } + + return isWeb; + } + + void parseMethodsToIgnore(String mti) { String[] methods = mti.split(","); - methodsToIgnore = new HashSet(); + + methodsToIgnore = new HashSet<>(); + Collections.addAll(methodsToIgnore, methods); - } - - void parseBrowserUserAgents(String userAgents) { - browserUserAgents = userAgents.split(","); - } - - protected boolean isBrowser(String userAgent) { - boolean isWeb = false; - if (browserUserAgents != null && browserUserAgents.length > 0 && userAgent != null) { - for (String ua : browserUserAgents) { - if (userAgent.toLowerCase().startsWith(ua.toLowerCase())) { - isWeb = true; - break; - } - } - } - return isWeb; - } - - public interface HttpInteraction { - /** - * Returns the value of a header. - * - * @param header - * name of header - * @return value of header - */ - String getHeader(String header); - - /** - * Returns the method. - * - * @return method - */ - String getMethod(); - - /** - * Called by the filter after it decides that the request may proceed. - * - * @throws IOException - * if there is an I/O error - * @throws ServletException - * if the implementation relies on the servlet API and a - * servlet API call has failed - */ - void proceed() throws IOException, ServletException; - - /** - * Called by the filter after it decides that the request is a potential - * CSRF attack and therefore must be rejected. - * - * @param code - * status code to send - * @param message - * response message - * @throws IOException - * if there is an I/O error - */ - void sendError(int code, String message) throws IOException; - } - - public void handleHttpInteraction(HttpInteraction httpInteraction, boolean spnegoEnabled, boolean trustedProxyEnabled) - throws IOException, ServletException { - - HttpSession session = ((ServletFilterHttpInteraction) httpInteraction).getSession(); - String clientCsrfToken = httpInteraction.getHeader(headerName); - String actualCsrfToken = StringUtils.EMPTY; - - if (session != null) { - actualCsrfToken = (String) session.getAttribute(CSRF_TOKEN); - } else { - if (LOG.isDebugEnabled()) { - LOG.debug("Session is null"); - } - } - - if (LOG.isDebugEnabled()) { - LOG.debug("actualCsrfToken = " + actualCsrfToken + " clientCsrfToken = " + clientCsrfToken + - "trustedProxy = " + trustedProxyEnabled + " for " + ((ServletFilterHttpInteraction) httpInteraction).httpRequest.getRequestURI()); - } - /* When the request is from Knox, then spnegoEnabled and trustedProxyEnabled are true. - * In this case Knox inserts XSRF header with proper value for POST & PUT requests and hence proceed with authentication filter - */ - if ((spnegoEnabled && trustedProxyEnabled) || clientCsrfToken != null && clientCsrfToken.equals(actualCsrfToken) - || !isBrowser(httpInteraction.getHeader(HEADER_USER_AGENT)) - || methodsToIgnore.contains(httpInteraction.getMethod())) { - httpInteraction.proceed(); - }else { - LOG.error("Missing header or invalid Header value for CSRF Vulnerability Protection"); - httpInteraction.sendError(HttpServletResponse.SC_BAD_REQUEST,"Missing header or invalid Header value for CSRF Vulnerability Protection"); - } - } - - public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { - if (IS_CSRF_ENABLED) { - final HttpServletRequest httpRequest = (HttpServletRequest)request; - final HttpServletResponse httpResponse = (HttpServletResponse)response; - Boolean spnegoEnabled = httpRequest.getAttribute("spnegoEnabled") != null ? Boolean.valueOf(String.valueOf(httpRequest.getAttribute("spnegoEnabled"))) : false; - Boolean trustedProxyEnabled = httpRequest.getAttribute("trustedProxyEnabled") != null ? Boolean.valueOf(String.valueOf(httpRequest.getAttribute("trustedProxyEnabled"))) : false; - handleHttpInteraction(new ServletFilterHttpInteraction(httpRequest, httpResponse, chain), spnegoEnabled, trustedProxyEnabled); - }else{ - chain.doFilter(request, response); - } - } - - public void destroy() { - } - - private static final class ServletFilterHttpInteraction implements - HttpInteraction { - - private final FilterChain chain; - private final HttpServletRequest httpRequest; - private final HttpServletResponse httpResponse; - - /** - * Creates a new ServletFilterHttpInteraction. - * - * @param httpRequest - * request to process - * @param httpResponse - * response to process - * @param chain - * filter chain to forward to if HTTP interaction is allowed - */ - public ServletFilterHttpInteraction(HttpServletRequest httpRequest, - HttpServletResponse httpResponse, FilterChain chain) { - this.httpRequest = httpRequest; - this.httpResponse = httpResponse; - this.chain = chain; - } - - @Override - public String getHeader(String header) { - return httpRequest.getHeader(header); - } - - @Override - public String getMethod() { - return httpRequest.getMethod(); - } - - @Override - public void proceed() throws IOException, ServletException { - chain.doFilter(httpRequest, httpResponse); - } - - public HttpSession getSession() { - return httpRequest.getSession(); - } - - @Override - public void sendError(int code, String message) throws IOException { - httpResponse.sendError(code, message); - } - } + } + + void parseBrowserUserAgents(String userAgents) { + browserUserAgents = userAgents.split(","); + } + + public interface HttpInteraction { + /** + * Returns the value of a header. + * + * @param header name of header + * @return value of header + */ + String getHeader(String header); + + /** + * Returns the method. + * + * @return method + */ + String getMethod(); + + /** + * Called by the filter after it decides that the request may proceed. + * + * @throws IOException if there is an I/O error + * @throws ServletException if the implementation relies on the servlet API and a + * servlet API call has failed + */ + void proceed() throws IOException, ServletException; + + /** + * Called by the filter after it decides that the request is a potential + * CSRF attack and therefore must be rejected. + * + * @param code status code to send + * @param message response message + * @throws IOException if there is an I/O error + */ + void sendError(int code, String message) throws IOException; + } + + private static final class ServletFilterHttpInteraction implements HttpInteraction { + private final FilterChain chain; + private final HttpServletRequest httpRequest; + private final HttpServletResponse httpResponse; + + /** + * Creates a new ServletFilterHttpInteraction. + * + * @param httpRequest request to process + * @param httpResponse response to process + * @param chain filter chain to forward to if HTTP interaction is allowed + */ + public ServletFilterHttpInteraction(HttpServletRequest httpRequest, HttpServletResponse httpResponse, FilterChain chain) { + this.httpRequest = httpRequest; + this.httpResponse = httpResponse; + this.chain = chain; + } + + @Override + public String getHeader(String header) { + return httpRequest.getHeader(header); + } + + @Override + public String getMethod() { + return httpRequest.getMethod(); + } + + @Override + public void proceed() throws IOException, ServletException { + chain.doFilter(httpRequest, httpResponse); + } + + @Override + public void sendError(int code, String message) throws IOException { + httpResponse.sendError(code, message); + } + + public HttpSession getSession() { + return httpRequest.getSession(); + } + } } diff --git a/security-admin/src/main/java/org/apache/ranger/security/web/filter/RangerJwtAuthFilter.java b/security-admin/src/main/java/org/apache/ranger/security/web/filter/RangerJwtAuthFilter.java index f14adaaa8d..b10238b51f 100644 --- a/security-admin/src/main/java/org/apache/ranger/security/web/filter/RangerJwtAuthFilter.java +++ b/security-admin/src/main/java/org/apache/ranger/security/web/filter/RangerJwtAuthFilter.java @@ -18,20 +18,6 @@ */ package org.apache.ranger.security.web.filter; -import java.io.IOException; -import java.util.Arrays; -import java.util.List; -import java.util.Properties; - -import javax.annotation.PostConstruct; -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.HttpServletRequest; - import org.apache.log4j.Logger; import org.apache.ranger.authz.handler.RangerAuth; import org.apache.ranger.authz.handler.jwt.RangerDefaultJwtAuthHandler; @@ -49,17 +35,30 @@ import org.springframework.security.web.authentication.WebAuthenticationDetails; import org.springframework.stereotype.Component; +import javax.annotation.PostConstruct; +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.HttpServletRequest; + +import java.io.IOException; +import java.util.Collections; +import java.util.List; +import java.util.Properties; + @Lazy(true) @Component public class RangerJwtAuthFilter extends RangerDefaultJwtAuthHandler implements Filter { - private static final Logger LOG = Logger.getLogger(RangerJwtAuthFilter.class); + private static final Logger LOG = Logger.getLogger(RangerJwtAuthFilter.class); + private static final String DEFAULT_RANGER_ROLE = "ROLE_USER"; @PostConstruct public void initialize() { - if (LOG.isDebugEnabled()) { - LOG.debug("===>>> RangerJwtAuthFilter.initialize()"); - } + LOG.debug("===>>> RangerJwtAuthFilter.initialize()"); /** * If this filter is configured in spring security. The @@ -67,12 +66,11 @@ public void initialize() { * DelegatingFilterProxy} does not invoke init method (like Servlet container). */ try { - Properties config = new Properties(); + Properties config = new Properties(); config.setProperty(RangerJwtAuthHandler.KEY_PROVIDER_URL, PropertiesUtil.getProperty(RangerSSOAuthenticationFilter.JWT_AUTH_PROVIDER_URL)); config.setProperty(RangerJwtAuthHandler.KEY_JWT_PUBLIC_KEY, PropertiesUtil.getProperty(RangerSSOAuthenticationFilter.JWT_PUBLIC_KEY, "")); - config.setProperty(RangerJwtAuthHandler.KEY_JWT_COOKIE_NAME, - PropertiesUtil.getProperty(RangerSSOAuthenticationFilter.JWT_COOKIE_NAME, RangerSSOAuthenticationFilter.JWT_COOKIE_NAME_DEFAULT)); + config.setProperty(RangerJwtAuthHandler.KEY_JWT_COOKIE_NAME, PropertiesUtil.getProperty(RangerSSOAuthenticationFilter.JWT_COOKIE_NAME, RangerSSOAuthenticationFilter.JWT_COOKIE_NAME_DEFAULT)); config.setProperty(RangerJwtAuthHandler.KEY_JWT_AUDIENCES, PropertiesUtil.getProperty(RangerSSOAuthenticationFilter.JWT_AUDIENCES, "")); super.initialize(config); @@ -80,9 +78,7 @@ public void initialize() { LOG.error("Failed to initialize Ranger Admin JWT Auth Filter.", e); } - if (LOG.isDebugEnabled()) { - LOG.debug("<<<=== RangerJwtAuthFilter.initialize()"); - } + LOG.debug("<<<=== RangerJwtAuthFilter.initialize()"); } @Override @@ -92,25 +88,25 @@ public void init(FilterConfig filterConfig) throws ServletException { @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { - if (LOG.isDebugEnabled()) { - LOG.debug("===>>> RangerJwtAuthFilter.doFilter()"); - } + LOG.debug("===>>> RangerJwtAuthFilter.doFilter()"); HttpServletRequest httpServletRequest = (HttpServletRequest) request; - - RangerAuth rangerAuth = authenticate(httpServletRequest); + RangerAuth rangerAuth = authenticate(httpServletRequest); if (rangerAuth != null) { - final List grantedAuths = Arrays.asList(new SimpleGrantedAuthority(DEFAULT_RANGER_ROLE)); - final UserDetails principal = new User(rangerAuth.getUserName(), "", grantedAuths); - final Authentication finalAuthentication = new UsernamePasswordAuthenticationToken(principal, "", grantedAuths); - final WebAuthenticationDetails webDetails = new WebAuthenticationDetails(httpServletRequest); - ((AbstractAuthenticationToken) finalAuthentication).setDetails(webDetails); + final List grantedAuths = Collections.singletonList(new SimpleGrantedAuthority(DEFAULT_RANGER_ROLE)); + final UserDetails principal = new User(rangerAuth.getUserName(), "", grantedAuths); + final AbstractAuthenticationToken finalAuthentication = new UsernamePasswordAuthenticationToken(principal, "", grantedAuths); + final WebAuthenticationDetails webDetails = new WebAuthenticationDetails(httpServletRequest); + + finalAuthentication.setDetails(webDetails); + SecurityContextHolder.getContext().setAuthentication(finalAuthentication); } // Log final status of request. Authentication auth = SecurityContextHolder.getContext().getAuthentication(); + if (auth != null) { if (LOG.isDebugEnabled()) { LOG.debug("<<<=== RangerJwtAuthFilter.doFilter() - user=[" + auth.getPrincipal() + "], isUserAuthenticated? [" + auth.isAuthenticated() + "]"); diff --git a/security-admin/src/main/java/org/apache/ranger/security/web/filter/RangerJwtAuthWrapper.java b/security-admin/src/main/java/org/apache/ranger/security/web/filter/RangerJwtAuthWrapper.java index ac69bde26c..38f4ff721c 100644 --- a/security-admin/src/main/java/org/apache/ranger/security/web/filter/RangerJwtAuthWrapper.java +++ b/security-admin/src/main/java/org/apache/ranger/security/web/filter/RangerJwtAuthWrapper.java @@ -18,16 +18,6 @@ */ package org.apache.ranger.security.web.filter; -import java.io.IOException; - -import javax.annotation.PostConstruct; -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.commons.lang.StringUtils; import org.apache.log4j.Logger; import org.apache.ranger.common.PropertiesUtil; @@ -41,17 +31,27 @@ import org.springframework.stereotype.Component; import org.springframework.web.filter.GenericFilterBean; +import javax.annotation.PostConstruct; +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 java.io.IOException; + @Lazy(true) @Component public class RangerJwtAuthWrapper extends GenericFilterBean { private static final Logger LOG = Logger.getLogger(RangerJwtAuthWrapper.class); - private String[] browserUserAgents = new String[] {""}; //Initialize with empty - @Lazy(true) @Autowired RangerJwtAuthFilter rangerJwtAuthFilter; + private String[] browserUserAgents = new String[] {""}; //Initialize with empty + @PostConstruct public void initialize() { //FIXME: Browser agents should be common across ALL filters. @@ -83,29 +83,20 @@ public void doFilter(ServletRequest request, ServletResponse response, FilterCha if (!isRequestAuthenticated()) { String userAgent = ((HttpServletRequest) request).getHeader("User-Agent"); + if (isBrowserAgent(userAgent)) { - if (LOG.isDebugEnabled()) { - LOG.debug("Redirecting to login page as request does not have valid JWT auth details."); - } + LOG.debug("Redirecting to login page as request does not have valid JWT auth details."); + ((HttpServletResponse) response).sendRedirect("/login.jsp"); } } } else { - if (LOG.isDebugEnabled()) { - LOG.debug("===>> RangerJwtAuthWrapper.doFilter() - Skipping JWT auth."); - } + LOG.debug("===>> RangerJwtAuthWrapper.doFilter() - Skipping JWT auth."); } filterChain.doFilter(request, response); // proceed with filter chain - if (LOG.isDebugEnabled()) { - LOG.debug("<<<=== RangerJwtAuthWrapper.doFilter()"); - } - } - - private boolean isRequestAuthenticated() { - Authentication auth = SecurityContextHolder.getContext().getAuthentication(); - return auth != null && auth.isAuthenticated(); + LOG.debug("<<<=== RangerJwtAuthWrapper.doFilter()"); } protected boolean isBrowserAgent(String userAgent) { @@ -122,4 +113,10 @@ protected boolean isBrowserAgent(String userAgent) { return isBrowserAgent; } + + private boolean isRequestAuthenticated() { + Authentication auth = SecurityContextHolder.getContext().getAuthentication(); + + return auth != null && auth.isAuthenticated(); + } } diff --git a/security-admin/src/main/java/org/apache/ranger/security/web/filter/RangerKRBAuthenticationFilter.java b/security-admin/src/main/java/org/apache/ranger/security/web/filter/RangerKRBAuthenticationFilter.java index db55e408d9..1a9410188f 100644 --- a/security-admin/src/main/java/org/apache/ranger/security/web/filter/RangerKRBAuthenticationFilter.java +++ b/security-admin/src/main/java/org/apache/ranger/security/web/filter/RangerKRBAuthenticationFilter.java @@ -19,45 +19,14 @@ package org.apache.ranger.security.web.filter; -import java.io.IOException; -import java.io.InputStream; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Enumeration; -import java.util.EventListener; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.Collections; - -import javax.servlet.Filter; -import javax.servlet.FilterChain; -import javax.servlet.FilterConfig; -import javax.servlet.FilterRegistration; -import javax.servlet.RequestDispatcher; -import javax.servlet.Servlet; -import javax.servlet.ServletContext; -import javax.servlet.ServletException; -import javax.servlet.ServletRegistration; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; -import javax.servlet.SessionCookieConfig; -import javax.servlet.SessionTrackingMode; -import javax.servlet.FilterRegistration.Dynamic; -import javax.servlet.descriptor.JspConfigDescriptor; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; - import org.apache.commons.collections.iterators.IteratorEnumeration; +import org.apache.commons.lang.StringUtils; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.security.SaslRpcServer; +import org.apache.hadoop.security.SecureClientLogin; import org.apache.hadoop.security.UserGroupInformation; import org.apache.hadoop.security.authentication.server.AuthenticationToken; +import org.apache.hadoop.security.authentication.util.KerberosName; import org.apache.hadoop.security.authorize.AuthorizationException; import org.apache.hadoop.security.authorize.ProxyUsers; import org.apache.hadoop.util.HttpExceptionUtils; @@ -76,627 +45,678 @@ import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; -import org.apache.commons.lang.StringUtils; -import org.apache.hadoop.security.SecureClientLogin; -import org.apache.hadoop.security.authentication.util.KerberosName; import org.springframework.security.web.authentication.WebAuthenticationDetails; +import javax.servlet.Filter; +import javax.servlet.FilterChain; +import javax.servlet.FilterConfig; +import javax.servlet.FilterRegistration; +import javax.servlet.FilterRegistration.Dynamic; +import javax.servlet.RequestDispatcher; +import javax.servlet.Servlet; +import javax.servlet.ServletContext; +import javax.servlet.ServletException; +import javax.servlet.ServletRegistration; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import javax.servlet.SessionCookieConfig; +import javax.servlet.SessionTrackingMode; +import javax.servlet.descriptor.JspConfigDescriptor; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; + +import java.io.IOException; +import java.io.InputStream; +import java.net.URL; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.Enumeration; +import java.util.EventListener; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + public class RangerKRBAuthenticationFilter extends RangerKrbFilter { - private static final Logger LOG = LoggerFactory.getLogger(RangerKRBAuthenticationFilter.class); - - @Autowired - UserMgr userMgr; - - @Autowired - RESTErrorUtil restErrorUtil; - - static final String NAME_RULES = "hadoop.security.auth_to_local"; - static final String TOKEN_VALID = "ranger.admin.kerberos.token.valid.seconds"; - static final String COOKIE_DOMAIN = "ranger.admin.kerberos.cookie.domain"; - static final String COOKIE_PATH = "ranger.admin.kerberos.cookie.path"; - static final String PRINCIPAL = "ranger.spnego.kerberos.principal"; - static final String KEYTAB = "ranger.spnego.kerberos.keytab"; - static final String NAME_RULES_PARAM = "kerberos.name.rules"; - static final String TOKEN_VALID_PARAM = "token.validity"; - static final String COOKIE_DOMAIN_PARAM = "cookie.domain"; - static final String COOKIE_PATH_PARAM = "cookie.path"; - static final String PRINCIPAL_PARAM = "kerberos.principal"; - static final String KEYTAB_PARAM = "kerberos.keytab"; - static final String AUTH_TYPE = "type"; - static final String RANGER_AUTH_TYPE = "hadoop.security.authentication"; - static final String AUTH_COOKIE_NAME = "hadoop.auth"; - static final String HOST_NAME = "ranger.service.host"; - static final String ALLOW_TRUSTED_PROXY = "ranger.authentication.allow.trustedproxy"; - static final String PROXY_PREFIX = "ranger.proxyuser."; - static final String RULES_MECHANISM = "hadoop.security.rules.mechanism"; - static final String RULES_MECHANISM_PARAM = "kerberos.name.rules.mechanism"; - - private static final String KERBEROS_TYPE = "kerberos"; - private static final String S_USER = "suser"; - private String originalUrlQueryParam = "originalUrl"; - public static final String LOGOUT_URL = "/logout"; - - public RangerKRBAuthenticationFilter() { - try { - init(null); - } catch (ServletException e) { - LOG.error("Error while initializing Filter : "+e.getMessage()); - } - } - - @Override - public void init(FilterConfig conf) throws ServletException { - final FilterConfig globalConf = conf; - final Map params = new HashMap(); - params.put(AUTH_TYPE, PropertiesUtil.getProperty(RANGER_AUTH_TYPE, "simple")); - params.put(NAME_RULES_PARAM, PropertiesUtil.getProperty(NAME_RULES, "DEFAULT")); - params.put(TOKEN_VALID_PARAM, PropertiesUtil.getProperty(TOKEN_VALID,"30")); - params.put(COOKIE_DOMAIN_PARAM, PropertiesUtil.getProperty(COOKIE_DOMAIN, PropertiesUtil.getProperty(HOST_NAME, "localhost"))); - params.put(COOKIE_PATH_PARAM, PropertiesUtil.getProperty(COOKIE_PATH, "/")); - params.put(ALLOW_TRUSTED_PROXY, PropertiesUtil.getProperty(ALLOW_TRUSTED_PROXY, "false")); - params.put(RULES_MECHANISM_PARAM, PropertiesUtil.getProperty(RULES_MECHANISM, "hadoop")); - try { - params.put(PRINCIPAL_PARAM, SecureClientLogin.getPrincipal(PropertiesUtil.getProperty(PRINCIPAL,""), PropertiesUtil.getProperty(HOST_NAME))); - } catch (IOException ignored) { + private static final Logger LOG = LoggerFactory.getLogger(RangerKRBAuthenticationFilter.class); + + public static final String LOGOUT_URL = "/logout"; + + static final String NAME_RULES = "hadoop.security.auth_to_local"; + static final String TOKEN_VALID = "ranger.admin.kerberos.token.valid.seconds"; + static final String COOKIE_DOMAIN = "ranger.admin.kerberos.cookie.domain"; + static final String COOKIE_PATH = "ranger.admin.kerberos.cookie.path"; + static final String PRINCIPAL = "ranger.spnego.kerberos.principal"; + static final String KEYTAB = "ranger.spnego.kerberos.keytab"; + static final String NAME_RULES_PARAM = "kerberos.name.rules"; + static final String TOKEN_VALID_PARAM = "token.validity"; + static final String COOKIE_DOMAIN_PARAM = "cookie.domain"; + static final String COOKIE_PATH_PARAM = "cookie.path"; + static final String PRINCIPAL_PARAM = "kerberos.principal"; + static final String KEYTAB_PARAM = "kerberos.keytab"; + static final String AUTH_TYPE = "type"; + static final String RANGER_AUTH_TYPE = "hadoop.security.authentication"; + static final String AUTH_COOKIE_NAME = "hadoop.auth"; + static final String HOST_NAME = "ranger.service.host"; + static final String ALLOW_TRUSTED_PROXY = "ranger.authentication.allow.trustedproxy"; + static final String PROXY_PREFIX = "ranger.proxyuser."; + static final String RULES_MECHANISM = "hadoop.security.rules.mechanism"; + static final String RULES_MECHANISM_PARAM = "kerberos.name.rules.mechanism"; + + private static final String KERBEROS_TYPE = "kerberos"; + private static final String S_USER = "suser"; + + protected static ServletContext noContext = new ServletContext() { + @Override + public String getContextPath() { + return null; + } + + @Override + public ServletContext getContext(String uripath) { + return null; + } + + @Override + public int getMajorVersion() { + return 0; + } + + @Override + public int getMinorVersion() { + return 0; + } + + @Override + public int getEffectiveMajorVersion() { + return 0; + } + + @Override + public int getEffectiveMinorVersion() { + return 0; + } + + @Override + public String getMimeType(String file) { + return null; + } + + @Override + public Set getResourcePaths(String path) { + return null; + } + + @Override + public URL getResource(String path) { + return null; + } + + @Override + public InputStream getResourceAsStream(String path) { + return null; + } + + @Override + public RequestDispatcher getRequestDispatcher(String path) { + return null; + } + + @Override + public RequestDispatcher getNamedDispatcher(String name) { + return null; + } + + @Override + public Servlet getServlet(String name) { + return null; + } + + @Override + public Enumeration getServlets() { + return null; + } + + @Override + public Enumeration getServletNames() { + return null; + } + + @Override + public void log(String msg) { + } + + @Override + public void log(Exception exception, String msg) { + } + + @Override + public void log(String message, Throwable throwable) { + } + + @Override + public String getRealPath(String path) { + return null; + } + + @Override + public String getServerInfo() { + return null; + } + + @Override + public String getInitParameter(String name) { + return null; + } + + @Override + public Enumeration getInitParameterNames() { + return null; + } + + @Override + public boolean setInitParameter(String name, String value) { + return false; + } + + @Override + public Object getAttribute(String name) { + return null; + } + + @Override + public Enumeration getAttributeNames() { + return null; + } + + @Override + public void setAttribute(String name, Object object) { + } + + @Override + public void removeAttribute(String name) { + } + + @Override + public String getServletContextName() { + return null; + } + + @Override + public ServletRegistration.Dynamic addServlet(String servletName, String className) { + return null; + } + + @Override + public ServletRegistration.Dynamic addServlet(String servletName, Servlet servlet) { + return null; + } + + @Override + public ServletRegistration.Dynamic addServlet(String servletName, Class servletClass) { + return null; + } + + @Override + public T createServlet(Class clazz) { + return null; + } + + @Override + public ServletRegistration getServletRegistration(String servletName) { + return null; + } + + @Override + public Map getServletRegistrations() { + return null; + } + + @Override + public Dynamic addFilter(String filterName, String className) { + return null; + } + + @Override + public Dynamic addFilter(String filterName, Filter filter) { + return null; + } + + @Override + public Dynamic addFilter(String filterName, Class filterClass) { + return null; + } + + @Override + public T createFilter(Class clazz) { + return null; + } + + @Override + public FilterRegistration getFilterRegistration(String filterName) { + return null; + } + + @Override + public Map getFilterRegistrations() { + return null; + } + + @Override + public SessionCookieConfig getSessionCookieConfig() { + return null; + } + + @Override + public void setSessionTrackingModes(Set sessionTrackingModes) { + } + + @Override + public Set getDefaultSessionTrackingModes() { + return null; + } + + @Override + public Set getEffectiveSessionTrackingModes() { + return null; + } + + @Override + public void addListener(String className) { + } + + @Override + public void addListener(T t) { + } + + @Override + public void addListener(Class listenerClass) { + } + + @Override + public T createListener(Class clazz) { + return null; + } + + @Override + public JspConfigDescriptor getJspConfigDescriptor() { + return null; + } + + @Override + public ClassLoader getClassLoader() { + return null; + } + + @Override + public void declareRoles(String... roleNames) { + } + + @Override + public String getVirtualServerName() { + return null; + } + }; + + private final String originalUrlQueryParam = "originalUrl"; + + @Autowired + UserMgr userMgr; + + @Autowired + RESTErrorUtil restErrorUtil; + + public RangerKRBAuthenticationFilter() { + try { + init(null); + } catch (ServletException e) { + LOG.error("Error while initializing Filter : {}", e.getMessage()); + } + } + + @Override + public void init(FilterConfig conf) throws ServletException { + final FilterConfig globalConf = conf; + final Map params = new HashMap<>(); + + params.put(AUTH_TYPE, PropertiesUtil.getProperty(RANGER_AUTH_TYPE, "simple")); + params.put(NAME_RULES_PARAM, PropertiesUtil.getProperty(NAME_RULES, "DEFAULT")); + params.put(TOKEN_VALID_PARAM, PropertiesUtil.getProperty(TOKEN_VALID, "30")); + params.put(COOKIE_DOMAIN_PARAM, PropertiesUtil.getProperty(COOKIE_DOMAIN, PropertiesUtil.getProperty(HOST_NAME, "localhost"))); + params.put(COOKIE_PATH_PARAM, PropertiesUtil.getProperty(COOKIE_PATH, "/")); + params.put(ALLOW_TRUSTED_PROXY, PropertiesUtil.getProperty(ALLOW_TRUSTED_PROXY, "false")); + params.put(RULES_MECHANISM_PARAM, PropertiesUtil.getProperty(RULES_MECHANISM, "hadoop")); + + try { + params.put(PRINCIPAL_PARAM, SecureClientLogin.getPrincipal(PropertiesUtil.getProperty(PRINCIPAL, ""), PropertiesUtil.getProperty(HOST_NAME))); + } catch (IOException ignored) { // do nothing - } - params.put(KEYTAB_PARAM, PropertiesUtil.getProperty(KEYTAB,"")); - - FilterConfig myConf = new FilterConfig() { - @Override - public ServletContext getServletContext() { - if (globalConf != null) { - return globalConf.getServletContext(); - } else { - return noContext; - } - } - - @SuppressWarnings("unchecked") - @Override - public Enumeration getInitParameterNames() { - return new IteratorEnumeration(params.keySet().iterator()); - } - - @Override - public String getInitParameter(String param) { - return params.get(param); - } - - @Override - public String getFilterName() { - return "KerberosFilter"; - } - }; - super.init(myConf); - Configuration conf1 = this.getProxyuserConfiguration(); - ProxyUsers.refreshSuperUserGroupsConfiguration(conf1, PROXY_PREFIX); - } - - protected Configuration getProxyuserConfiguration() { - Configuration conf = new Configuration(false); - Map propertiesMap = PropertiesUtil.getPropertiesMap(); - for (String key : propertiesMap.keySet()) { - if (!key.startsWith(PROXY_PREFIX)) { - continue; - } - conf.set(key, propertiesMap.get(key)); - } - return conf; - } - - @Override - protected void doFilter(FilterChain filterChain, - HttpServletRequest request, HttpServletResponse response) - throws IOException, ServletException { - String authType = PropertiesUtil.getProperty(RANGER_AUTH_TYPE); - String userName = null; - boolean checkCookie = response.containsHeader("Set-Cookie"); - boolean allowTrustedProxy = PropertiesUtil.getBooleanProperty(ALLOW_TRUSTED_PROXY, false); - if(checkCookie){ - Collection authUserName = response.getHeaders("Set-Cookie"); - if(authUserName != null){ - Iterator i = authUserName.iterator(); - while(i.hasNext()){ - String cookie = i.next(); - if(!StringUtils.isEmpty(cookie)){ - if(cookie.toLowerCase().startsWith(AUTH_COOKIE_NAME.toLowerCase()) && cookie.contains("u=")){ - String[] split = cookie.split(";"); - if(split != null){ - for(String s : split){ - if(!StringUtils.isEmpty(s) && s.toLowerCase().startsWith(AUTH_COOKIE_NAME.toLowerCase())){ - int ustr = s.indexOf("u="); - if(ustr != -1){ - int andStr = s.indexOf("&", ustr); - if(andStr != -1){ - try{ - userName = s.substring(ustr+2, andStr); - }catch(Exception e){ - userName = null; - } - } - } - } - } - } - } - } - } - } - } - String sessionUserName = request.getParameter(S_USER); - String pathInfo = request.getPathInfo(); - if(!StringUtils.isEmpty(sessionUserName) && "keyadmin".equalsIgnoreCase(sessionUserName) && !StringUtils.isEmpty(pathInfo) && pathInfo.contains("public/v2/api/service")){ - LOG.info("Session will be created by : "+sessionUserName); - userName = sessionUserName; - } - - if(LOG.isDebugEnabled()) { - LOG.debug("Remote user from request = " + request.getRemoteUser()); - } - - if((isSpnegoEnable(authType) && (!StringUtils.isEmpty(userName)))){ - Authentication existingAuth = SecurityContextHolder.getContext().getAuthentication(); - if(existingAuth == null || !existingAuth.isAuthenticated()){ - //--------------------------- To Create Ranger Session -------------------------------------- - String rangerLdapDefaultRole = PropertiesUtil.getProperty("ranger.ldap.default.role", "ROLE_USER"); - if(LOG.isDebugEnabled()) { - LOG.debug("Http headers: " + Collections.list(request.getHeaderNames()).toString()); - } - String doAsUser = request.getParameter("doAs"); - - if (allowTrustedProxy && doAsUser != null && !doAsUser.isEmpty()) { - if(LOG.isDebugEnabled()) { - LOG.debug("userPrincipal from request = " + request.getUserPrincipal() + " request paramerters = " + request.getParameterMap().keySet()); - } - AuthenticationToken authToken = (AuthenticationToken)request.getUserPrincipal(); - if(authToken != null && authToken != AuthenticationToken.ANONYMOUS) { - if(LOG.isDebugEnabled()) { - LOG.debug("remote user from authtoken = " + authToken.getUserName()); - } - UserGroupInformation ugi = UserGroupInformation.createRemoteUser(authToken.getUserName(), SaslRpcServer.AuthMethod.KERBEROS); - if(ugi != null) { - ugi = UserGroupInformation.createProxyUser(doAsUser, ugi); - if(LOG.isDebugEnabled()) { - LOG.debug("Real user from UGI = " + ugi.getRealUser().getShortUserName()); - } - - try { - ProxyUsers.authorize(ugi, request.getRemoteAddr()); - } catch (AuthorizationException ex) { - HttpExceptionUtils.createServletExceptionResponse(response, 403, ex); - if(LOG.isDebugEnabled()) { - LOG.debug("Authentication exception: " + ex.getMessage(), ex); - } else { - LOG.warn("Authentication exception: " + ex.getMessage()); - } - return; - } - final List grantedAuths = new ArrayList<>(); - grantedAuths.add(new SimpleGrantedAuthority(rangerLdapDefaultRole)); - final UserDetails principal = new User(doAsUser, "", grantedAuths); - Authentication authentication = new UsernamePasswordAuthenticationToken(principal, "", grantedAuths); - WebAuthenticationDetails webDetails = new WebAuthenticationDetails(request); - ((AbstractAuthenticationToken) authentication).setDetails(webDetails); - authentication = getGrantedAuthority(authentication); - SecurityContextHolder.getContext().setAuthentication(authentication); - request.setAttribute("spnegoEnabled", true); - request.setAttribute("trustedProxyEnabled", true); - LOG.info("Logged into Ranger as doAsUser = " + doAsUser + ", by authenticatedUser=" + authToken.getUserName()); - } - - } - - }else { - //if we get the userName from the token then log into ranger using the same user - final List grantedAuths = new ArrayList<>(); - grantedAuths.add(new SimpleGrantedAuthority(rangerLdapDefaultRole)); - final UserDetails principal = new User(userName, "", grantedAuths); - final Authentication finalAuthentication = new UsernamePasswordAuthenticationToken(principal, "", grantedAuths); - WebAuthenticationDetails webDetails = new WebAuthenticationDetails(request); - ((AbstractAuthenticationToken) finalAuthentication).setDetails(webDetails); - Authentication authentication = getGrantedAuthority(finalAuthentication); - if (authentication != null && authentication.isAuthenticated()) { - if (request.getParameterMap().containsKey("doAs")) { - if (!response.isCommitted()) { - if (LOG.isDebugEnabled()) { - LOG.debug("Request contains unsupported parameter, doAs."); - } - request.setAttribute("spnegoenabled", false); - response.sendError(HttpServletResponse.SC_FORBIDDEN, "Missing authentication token."); - } - } - if (request.getParameterMap().containsKey("user.name")) { - if (!response.isCommitted()) { - if (LOG.isDebugEnabled()) { - LOG.debug("Request contains an unsupported parameter user.name"); - } - request.setAttribute("spnegoenabled", false); - response.sendError(HttpServletResponse.SC_FORBIDDEN, "Missing authentication token."); - } else { - LOG.info("Response seems to be already committed for user.name."); - } - } - } - SecurityContextHolder.getContext().setAuthentication(authentication); - request.setAttribute("spnegoEnabled", true); - if(LOG.isDebugEnabled()) { - LOG.debug("Logged into Ranger as = " + userName); - } - } - filterChain.doFilter(request, response); - }else{ - try{ - super.doFilter(filterChain, request, response); - }catch(Exception e){ - throw restErrorUtil.createRESTException("RangerKRBAuthenticationFilter Failed : "+e.getMessage()); - } - } - }else{ - filterChain.doFilter(request, response); - } - } - - @Override - public void doFilter(ServletRequest request, ServletResponse response, - FilterChain filterChain) throws IOException, ServletException { - String authtype = PropertiesUtil.getProperty(RANGER_AUTH_TYPE); - HttpServletRequest httpRequest = (HttpServletRequest)request; - Authentication existingAuth = SecurityContextHolder.getContext().getAuthentication(); - if(isSpnegoEnable(authtype) && (existingAuth == null || !existingAuth.isAuthenticated())){ - KerberosName.setRules(PropertiesUtil.getProperty(NAME_RULES, "DEFAULT")); - if (LOG.isDebugEnabled()) { - String userName = null; - LOG.debug("isSpnegoEnable = " + isSpnegoEnable(authtype) + " userName = " + userName + " request URL = " + getRequestURL(httpRequest)); - if (existingAuth!=null) { - LOG.debug("isAuthenticated: " + existingAuth.isAuthenticated()); - } - } - try{ - if (StringUtils.equals(httpRequest.getParameter("action"), RestUtil.TIMEOUT_ACTION)) { - handleTimeoutRequest(httpRequest, (HttpServletResponse) response); - } else { - super.doFilter(request, response, filterChain); - } - }catch(Exception e){ - throw restErrorUtil.createRESTException("RangerKRBAuthenticationFilter Failed : "+e.getMessage()); - } - } else { - String action = httpRequest.getParameter("action"); - String doAsUser = request.getParameter("doAs"); - if(LOG.isDebugEnabled()) { - LOG.debug("RangerKRBAuthenticationFilter: request URL = " + httpRequest.getRequestURI()); - } - - boolean allowTrustedProxy = PropertiesUtil.getBooleanProperty(ALLOW_TRUSTED_PROXY, false); - - if(isSpnegoEnable(authtype) && allowTrustedProxy && StringUtils.isNotEmpty(doAsUser) - && existingAuth != null && existingAuth.isAuthenticated()) { - request.setAttribute("spnegoEnabled", true); - request.setAttribute("trustedProxyEnabled", true); - } - - if (allowTrustedProxy && StringUtils.isNotEmpty(doAsUser) && existingAuth != null && existingAuth.isAuthenticated() - && StringUtils.equals(action, RestUtil.TIMEOUT_ACTION)) { - HttpServletResponse httpResponse = (HttpServletResponse) response; - handleTimeoutRequest(httpRequest, httpResponse); - } else { - filterChain.doFilter(request, response); - } - } - } - - private void handleTimeoutRequest(HttpServletRequest httpRequest, HttpServletResponse httpResponse) throws IOException{ - String xForwardedURL = RestUtil.constructForwardableURL(httpRequest); - if (LOG.isDebugEnabled()) { - LOG.debug("xForwardedURL = " + xForwardedURL); - } - String logoutUrl = xForwardedURL; - logoutUrl = StringUtils.replace(logoutUrl, httpRequest.getRequestURI(), LOGOUT_URL); - if (LOG.isDebugEnabled()) { - LOG.debug("logoutUrl value is " + logoutUrl); - } - String redirectUrl = RestUtil.constructRedirectURL(httpRequest, logoutUrl, xForwardedURL, originalUrlQueryParam); - - if (LOG.isDebugEnabled()) { - LOG.debug("Redirect URL = " + redirectUrl); - LOG.debug("session id = " + httpRequest.getRequestedSessionId()); - } - - HttpSession httpSession = httpRequest.getSession(false); - if (httpSession != null) { - httpSession.invalidate(); - } - httpResponse.setHeader("Content-Type", "application/x-http-headers"); - httpResponse.sendRedirect(redirectUrl); - } - - private boolean isSpnegoEnable(String authType){ - String principal = PropertiesUtil.getProperty(PRINCIPAL); - String keytabPath = PropertiesUtil.getProperty(KEYTAB); - return ((!StringUtils.isEmpty(authType)) && KERBEROS_TYPE.equalsIgnoreCase(authType) && SecureClientLogin.isKerberosCredentialExists(principal, keytabPath)); - } - - private Authentication getGrantedAuthority(Authentication authentication) { - UsernamePasswordAuthenticationToken result=null; - if(authentication!=null && authentication.isAuthenticated()){ - final List grantedAuths=getAuthorities(authentication.getName().toString()); - final UserDetails userDetails = new User(authentication.getName().toString(), authentication.getCredentials().toString(),grantedAuths); - result = new UsernamePasswordAuthenticationToken(userDetails,authentication.getCredentials(),grantedAuths); - result.setDetails(authentication.getDetails()); - return result; - } - return authentication; - } - - private List getAuthorities(String username) { - Collection roleList=userMgr.getRolesByLoginId(username); - final List grantedAuths = new ArrayList<>(); - for(String role:roleList){ - grantedAuths.add(new SimpleGrantedAuthority(role)); - } - return grantedAuths; - } - - protected static ServletContext noContext = new ServletContext() { - - @Override - public void setSessionTrackingModes( - Set sessionTrackingModes) { - } - - @Override - public boolean setInitParameter(String name, String value) { - return false; - } - - @Override - public void setAttribute(String name, Object object) { - } - - @Override - public void removeAttribute(String name) { - } - - @Override - public void log(String message, Throwable throwable) { - } - - @Override - public void log(Exception exception, String msg) { - } - - @Override - public void log(String msg) { - } - - @Override - public String getVirtualServerName() { - return null; - } - - @Override - public SessionCookieConfig getSessionCookieConfig() { - return null; - } - - @Override - public Enumeration getServlets() { - return null; - } - - @Override - public Map getServletRegistrations() { - return null; - } - - @Override - public ServletRegistration getServletRegistration(String servletName) { - return null; - } - - @Override - public Enumeration getServletNames() { - return null; - } - - @Override - public String getServletContextName() { - return null; - } - - @Override - public Servlet getServlet(String name) throws ServletException { - return null; - } - - @Override - public String getServerInfo() { - return null; - } - - @Override - public Set getResourcePaths(String path) { - return null; - } - - @Override - public InputStream getResourceAsStream(String path) { - return null; - } - - @Override - public URL getResource(String path) throws MalformedURLException { - return null; - } - - @Override - public RequestDispatcher getRequestDispatcher(String path) { - return null; - } - - @Override - public String getRealPath(String path) { - return null; - } - - @Override - public RequestDispatcher getNamedDispatcher(String name) { - return null; - } - - @Override - public int getMinorVersion() { - return 0; - } - - @Override - public String getMimeType(String file) { - return null; - } - - @Override - public int getMajorVersion() { - return 0; - } - - @Override - public JspConfigDescriptor getJspConfigDescriptor() { - return null; - } - - @Override - public Enumeration getInitParameterNames() { - return null; - } - - @Override - public String getInitParameter(String name) { - return null; - } - - @Override - public Map getFilterRegistrations() { - return null; - } - - @Override - public FilterRegistration getFilterRegistration(String filterName) { - return null; - } - - @Override - public Set getEffectiveSessionTrackingModes() { - return null; - } - - @Override - public int getEffectiveMinorVersion() { - return 0; - } - - @Override - public int getEffectiveMajorVersion() { - return 0; - } - - @Override - public Set getDefaultSessionTrackingModes() { - return null; - } - - @Override - public String getContextPath() { - return null; - } - - @Override - public ServletContext getContext(String uripath) { - return null; - } - - @Override - public ClassLoader getClassLoader() { - return null; - } - - @Override - public Enumeration getAttributeNames() { - return null; - } - - @Override - public Object getAttribute(String name) { - return null; - } - - @Override - public void declareRoles(String... roleNames) { - } - - @Override - public T createServlet(Class clazz) - throws ServletException { - return null; - } - - @Override - public T createListener(Class clazz) - throws ServletException { - return null; - } - - @Override - public T createFilter(Class clazz) - throws ServletException { - return null; - } - - @Override - public ServletRegistration.Dynamic addServlet( - String servletName, Class servletClass) { - return null; - } - - @Override - public ServletRegistration.Dynamic addServlet( - String servletName, Servlet servlet) { - return null; - } - - @Override - public ServletRegistration.Dynamic addServlet( - String servletName, String className) { - return null; - } - - @Override - public void addListener(Class listenerClass) { - } - - @Override - public void addListener(T t) { - } - - @Override - public void addListener(String className) { - } - - @Override - public Dynamic addFilter(String filterName, - Class filterClass) { - return null; - } - - @Override - public Dynamic addFilter(String filterName, Filter filter) { - return null; - } - - @Override - public Dynamic addFilter(String filterName, String className) { - return null; - } - }; + } + + params.put(KEYTAB_PARAM, PropertiesUtil.getProperty(KEYTAB, "")); + + FilterConfig myConf = new FilterConfig() { + @Override + public String getFilterName() { + return "KerberosFilter"; + } + + @Override + public ServletContext getServletContext() { + if (globalConf != null) { + return globalConf.getServletContext(); + } else { + return noContext; + } + } + + @Override + public String getInitParameter(String param) { + return params.get(param); + } + + @SuppressWarnings("unchecked") + @Override + public Enumeration getInitParameterNames() { + return new IteratorEnumeration(params.keySet().iterator()); + } + }; + + super.init(myConf); + + Configuration conf1 = this.getProxyuserConfiguration(); + + ProxyUsers.refreshSuperUserGroupsConfiguration(conf1, PROXY_PREFIX); + } + + @Override + public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException { + String authtype = PropertiesUtil.getProperty(RANGER_AUTH_TYPE); + HttpServletRequest httpRequest = (HttpServletRequest) request; + Authentication existingAuth = SecurityContextHolder.getContext().getAuthentication(); + + if (isSpnegoEnable(authtype) && (existingAuth == null || !existingAuth.isAuthenticated())) { + KerberosName.setRules(PropertiesUtil.getProperty(NAME_RULES, "DEFAULT")); + + String userName = null; + + LOG.debug("isSpnegoEnable = {}, userName = {}, request URL = {}", isSpnegoEnable(authtype), userName, getRequestURL(httpRequest)); + + if (existingAuth != null) { + LOG.debug("isAuthenticated: {}", existingAuth.isAuthenticated()); + } + + try { + if (StringUtils.equals(httpRequest.getParameter("action"), RestUtil.TIMEOUT_ACTION)) { + handleTimeoutRequest(httpRequest, (HttpServletResponse) response); + } else { + super.doFilter(request, response, filterChain); + } + } catch (Exception e) { + throw restErrorUtil.createRESTException("RangerKRBAuthenticationFilter Failed : " + e.getMessage()); + } + } else { + String action = httpRequest.getParameter("action"); + String doAsUser = request.getParameter("doAs"); + + LOG.debug("RangerKRBAuthenticationFilter: request URL = {}", httpRequest.getRequestURI()); + + boolean allowTrustedProxy = PropertiesUtil.getBooleanProperty(ALLOW_TRUSTED_PROXY, false); + + if (isSpnegoEnable(authtype) && allowTrustedProxy && StringUtils.isNotEmpty(doAsUser) && existingAuth != null && existingAuth.isAuthenticated()) { + request.setAttribute("spnegoEnabled", true); + request.setAttribute("trustedProxyEnabled", true); + } + + if (allowTrustedProxy && StringUtils.isNotEmpty(doAsUser) && existingAuth != null && existingAuth.isAuthenticated() && StringUtils.equals(action, RestUtil.TIMEOUT_ACTION)) { + HttpServletResponse httpResponse = (HttpServletResponse) response; + + handleTimeoutRequest(httpRequest, httpResponse); + } else { + filterChain.doFilter(request, response); + } + } + } + + @Override + protected void doFilter(FilterChain filterChain, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { + String authType = PropertiesUtil.getProperty(RANGER_AUTH_TYPE); + String userName = null; + boolean checkCookie = response.containsHeader("Set-Cookie"); + boolean allowTrustedProxy = PropertiesUtil.getBooleanProperty(ALLOW_TRUSTED_PROXY, false); + + if (checkCookie) { + Collection authUserName = response.getHeaders("Set-Cookie"); + + if (authUserName != null) { + for (String cookie : authUserName) { + if (!StringUtils.isEmpty(cookie)) { + if (cookie.toLowerCase().startsWith(AUTH_COOKIE_NAME.toLowerCase()) && cookie.contains("u=")) { + String[] split = cookie.split(";"); + + for (String s : split) { + if (!StringUtils.isEmpty(s) && s.toLowerCase().startsWith(AUTH_COOKIE_NAME.toLowerCase())) { + int ustr = s.indexOf("u="); + + if (ustr != -1) { + int andStr = s.indexOf("&", ustr); + + if (andStr != -1) { + try { + userName = s.substring(ustr + 2, andStr); + } catch (Exception e) { + userName = null; + } + } + } + } + } + } + } + } + } + } + + String sessionUserName = request.getParameter(S_USER); + String pathInfo = request.getPathInfo(); + + if (!StringUtils.isEmpty(sessionUserName) && "keyadmin".equalsIgnoreCase(sessionUserName) && !StringUtils.isEmpty(pathInfo) && pathInfo.contains("public/v2/api/service")) { + LOG.info("Session will be created by : {}", sessionUserName); + + userName = sessionUserName; + } + + LOG.debug("Remote user from request = {}", request.getRemoteUser()); + + if ((isSpnegoEnable(authType) && (!StringUtils.isEmpty(userName)))) { + Authentication existingAuth = SecurityContextHolder.getContext().getAuthentication(); + + if (existingAuth == null || !existingAuth.isAuthenticated()) { + //--------------------------- To Create Ranger Session -------------------------------------- + String rangerLdapDefaultRole = PropertiesUtil.getProperty("ranger.ldap.default.role", "ROLE_USER"); + + LOG.debug("Http headers: {}", Collections.list(request.getHeaderNames())); + + String doAsUser = request.getParameter("doAs"); + + if (allowTrustedProxy && doAsUser != null && !doAsUser.isEmpty()) { + LOG.debug("userPrincipal from request = {} request parameters = {}", request.getUserPrincipal(), request.getParameterMap().keySet()); + + AuthenticationToken authToken = (AuthenticationToken) request.getUserPrincipal(); + + if (authToken != null && authToken != AuthenticationToken.ANONYMOUS) { + LOG.debug("remote user from authtoken = {}", authToken.getUserName()); + + UserGroupInformation ugi = UserGroupInformation.createRemoteUser(authToken.getUserName(), SaslRpcServer.AuthMethod.KERBEROS); + + if (ugi != null) { + ugi = UserGroupInformation.createProxyUser(doAsUser, ugi); + + LOG.debug("Real user from UGI = {}", ugi.getRealUser().getShortUserName()); + + try { + ProxyUsers.authorize(ugi, request.getRemoteAddr()); + } catch (AuthorizationException ex) { + HttpExceptionUtils.createServletExceptionResponse(response, 403, ex); + + if (LOG.isDebugEnabled()) { + LOG.debug("Authentication exception: {}", ex.getMessage(), ex); + } else { + LOG.warn("Authentication exception: {}", ex.getMessage()); + } + + return; + } + + final List grantedAuths = new ArrayList<>(); + + grantedAuths.add(new SimpleGrantedAuthority(rangerLdapDefaultRole)); + + final UserDetails principal = new User(doAsUser, "", grantedAuths); + Authentication authentication = new UsernamePasswordAuthenticationToken(principal, "", grantedAuths); + WebAuthenticationDetails webDetails = new WebAuthenticationDetails(request); + + ((AbstractAuthenticationToken) authentication).setDetails(webDetails); + + authentication = getGrantedAuthority(authentication); + + SecurityContextHolder.getContext().setAuthentication(authentication); + + request.setAttribute("spnegoEnabled", true); + request.setAttribute("trustedProxyEnabled", true); + + LOG.info("Logged into Ranger as doAsUser = {}, by authenticatedUser = {}", doAsUser, authToken.getUserName()); + } + } + } else { + //if we get the userName from the token then log into ranger using the same user + final List grantedAuths = new ArrayList<>(); + + grantedAuths.add(new SimpleGrantedAuthority(rangerLdapDefaultRole)); + + final UserDetails principal = new User(userName, "", grantedAuths); + final AbstractAuthenticationToken finalAuthentication = new UsernamePasswordAuthenticationToken(principal, "", grantedAuths); + WebAuthenticationDetails webDetails = new WebAuthenticationDetails(request); + + finalAuthentication.setDetails(webDetails); + + Authentication authentication = getGrantedAuthority(finalAuthentication); + + if (authentication != null && authentication.isAuthenticated()) { + if (request.getParameterMap().containsKey("doAs")) { + if (!response.isCommitted()) { + LOG.debug("Request contains unsupported parameter, doAs."); + + request.setAttribute("spnegoenabled", false); + response.sendError(HttpServletResponse.SC_FORBIDDEN, "Missing authentication token."); + } + } + if (request.getParameterMap().containsKey("user.name")) { + if (!response.isCommitted()) { + LOG.debug("Request contains an unsupported parameter user.name"); + + request.setAttribute("spnegoenabled", false); + response.sendError(HttpServletResponse.SC_FORBIDDEN, "Missing authentication token."); + } else { + LOG.info("Response seems to be already committed for user.name."); + } + } + } + + SecurityContextHolder.getContext().setAuthentication(authentication); + + request.setAttribute("spnegoEnabled", true); + + LOG.debug("Logged into Ranger as = {}", userName); + } + filterChain.doFilter(request, response); + } else { + try { + super.doFilter(filterChain, request, response); + } catch (Exception e) { + throw restErrorUtil.createRESTException("RangerKRBAuthenticationFilter Failed : " + e.getMessage()); + } + } + } else { + filterChain.doFilter(request, response); + } + } + + protected Configuration getProxyuserConfiguration() { + Configuration conf = new Configuration(false); + Map propertiesMap = PropertiesUtil.getPropertiesMap(); + + for (String key : propertiesMap.keySet()) { + if (!key.startsWith(PROXY_PREFIX)) { + continue; + } + + conf.set(key, propertiesMap.get(key)); + } + + return conf; + } + + private void handleTimeoutRequest(HttpServletRequest httpRequest, HttpServletResponse httpResponse) throws IOException { + String xForwardedURL = RestUtil.constructForwardableURL(httpRequest); + + LOG.debug("xForwardedURL = {}", xForwardedURL); + + String logoutUrl = xForwardedURL; + + logoutUrl = StringUtils.replace(logoutUrl, httpRequest.getRequestURI(), LOGOUT_URL); + + LOG.debug("logoutUrl value is {}", logoutUrl); + + String redirectUrl = RestUtil.constructRedirectURL(httpRequest, logoutUrl, xForwardedURL, originalUrlQueryParam); + + LOG.debug("Redirect URL = {}", redirectUrl); + LOG.debug("session id = {}", httpRequest.getRequestedSessionId()); + + HttpSession httpSession = httpRequest.getSession(false); + + if (httpSession != null) { + httpSession.invalidate(); + } + + httpResponse.setHeader("Content-Type", "application/x-http-headers"); + httpResponse.sendRedirect(redirectUrl); + } + + private boolean isSpnegoEnable(String authType) { + String principal = PropertiesUtil.getProperty(PRINCIPAL); + String keytabPath = PropertiesUtil.getProperty(KEYTAB); + + return ((!StringUtils.isEmpty(authType)) && KERBEROS_TYPE.equalsIgnoreCase(authType) && SecureClientLogin.isKerberosCredentialExists(principal, keytabPath)); + } + + private Authentication getGrantedAuthority(Authentication authentication) { + UsernamePasswordAuthenticationToken result; + + if (authentication != null && authentication.isAuthenticated()) { + final List grantedAuths = getAuthorities(authentication.getName()); + final UserDetails userDetails = new User(authentication.getName(), authentication.getCredentials().toString(), grantedAuths); + + result = new UsernamePasswordAuthenticationToken(userDetails, authentication.getCredentials(), grantedAuths); + + result.setDetails(authentication.getDetails()); + + return result; + } + + return authentication; + } + + private List getAuthorities(String username) { + Collection roleList = userMgr.getRolesByLoginId(username); + final List grantedAuths = new ArrayList<>(); + + for (String role : roleList) { + grantedAuths.add(new SimpleGrantedAuthority(role)); + } + return grantedAuths; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/security/web/filter/RangerKrbFilter.java b/security-admin/src/main/java/org/apache/ranger/security/web/filter/RangerKrbFilter.java index 3c370d1730..a9fde78cf9 100644 --- a/security-admin/src/main/java/org/apache/ranger/security/web/filter/RangerKrbFilter.java +++ b/security-admin/src/main/java/org/apache/ranger/security/web/filter/RangerKrbFilter.java @@ -2,9 +2,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + *

+ * http://www.apache.org/licenses/LICENSE-2.0 + *

* Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -23,7 +23,12 @@ import org.apache.hadoop.security.authentication.server.AuthenticationToken; import org.apache.hadoop.security.authentication.server.KerberosAuthenticationHandler; import org.apache.hadoop.security.authentication.server.PseudoAuthenticationHandler; -import org.apache.hadoop.security.authentication.util.*; +import org.apache.hadoop.security.authentication.util.FileSignerSecretProvider; +import org.apache.hadoop.security.authentication.util.RandomSignerSecretProvider; +import org.apache.hadoop.security.authentication.util.Signer; +import org.apache.hadoop.security.authentication.util.SignerException; +import org.apache.hadoop.security.authentication.util.SignerSecretProvider; +import org.apache.hadoop.security.authentication.util.ZKSignerSecretProvider; import org.apache.ranger.common.PropertiesUtil; import org.apache.ranger.plugin.util.RangerCommonConstants; import org.slf4j.Logger; @@ -45,621 +50,635 @@ import java.io.IOException; import java.security.Principal; import java.text.SimpleDateFormat; -import java.util.*; +import java.util.Collection; +import java.util.Date; +import java.util.Enumeration; +import java.util.Properties; +import java.util.TimeZone; import static org.apache.hadoop.thirdparty.com.google.common.io.ByteStreams.skipFully; - @InterfaceAudience.Private @InterfaceStability.Unstable public class RangerKrbFilter implements Filter { - private static final Logger LOG = LoggerFactory.getLogger(RangerKrbFilter.class); - /** - * Constant for the property that specifies the configuration prefix. - */ - public static final String CONFIG_PREFIX = "config.prefix"; - - /** - * Constant for the property that specifies the authentication handler to use. - */ - public static final String AUTH_TYPE = "type"; - - /** - * Constant for the property that specifies the secret to use for signing the HTTP Cookies. - */ - public static final String SIGNATURE_SECRET = "signature.secret"; - - public static final String SIGNATURE_SECRET_FILE = SIGNATURE_SECRET + ".file"; - - /** - * Constant for the configuration property that indicates the validity of the generated token. - */ - public static final String AUTH_TOKEN_VALIDITY = "token.validity"; - - /** - * Constant for the configuration property that indicates the domain to use in the HTTP cookie. - */ - public static final String COOKIE_DOMAIN = "cookie.domain"; - - /** - * Constant for the configuration property that indicates the path to use in the HTTP cookie. - */ - public static final String COOKIE_PATH = "cookie.path"; - - /** - * Constant for the configuration property that indicates the name of the - * SignerSecretProvider class to use. - * Possible values are: "string", "random", "zookeeper", or a classname. - * If not specified, the "string" implementation will be used with - * SIGNATURE_SECRET; and if that's not specified, the "random" implementation - * will be used. - */ - public static final String SIGNER_SECRET_PROVIDER = - "signer.secret.provider"; - - /** - * Constant for the ServletContext attribute that can be used for providing a - * custom implementation of the SignerSecretProvider. Note that the class - * should already be initialized. If not specified, SIGNER_SECRET_PROVIDER - * will be used. - */ - public static final String SIGNER_SECRET_PROVIDER_ATTRIBUTE = - "signer.secret.provider.object"; - - private static final String BROWSER_USER_AGENT_PARAM = "ranger.krb.browser-useragents-regex"; - - static final String ALLOW_TRUSTED_PROXY = "ranger.authentication.allow.trustedproxy"; - - private static final String supportKerberosAuthForBrowserLoginConfig = "ranger.allow.kerberos.auth.login.browser"; - - private String[] browserUserAgents; - - private Properties config; - private Signer signer; - private SignerSecretProvider secretProvider; - private AuthenticationHandler authHandler; - private long validity; - private String cookieDomain; - private String cookiePath; - private String cookieName; - private boolean isKerberosEnabled; - private boolean supportKerberosAuthForBrowserLogin; - - /** - *

Initializes the authentication filter and signer secret provider.

- * It instantiates and initializes the specified {@link - * AuthenticationHandler}. - * - * @param filterConfig filter configuration. - * - * @throws ServletException thrown if the filter or the authentication handler could not be initialized properly. - */ - @Override - public void init(FilterConfig filterConfig) throws ServletException { - String configPrefix = filterConfig.getInitParameter(CONFIG_PREFIX); - configPrefix = (configPrefix != null) ? configPrefix + "." : ""; - config = getConfiguration(configPrefix, filterConfig); - String authHandlerName = config.getProperty(AUTH_TYPE, null); - String authHandlerClassName; - if (authHandlerName == null) { - throw new ServletException("Authentication type must be specified: " + - PseudoAuthenticationHandler.TYPE + "|" + - KerberosAuthenticationHandler.TYPE + "|"); - } - if(StringUtils.equalsIgnoreCase(authHandlerName, PseudoAuthenticationHandler.TYPE)){ - authHandlerClassName = PseudoAuthenticationHandler.class.getName(); - }else if(StringUtils.equalsIgnoreCase(authHandlerName, KerberosAuthenticationHandler.TYPE)){ - authHandlerClassName = KerberosAuthenticationHandler.class.getName(); - } else { - authHandlerClassName = authHandlerName; - } + /** + * Constant for the property that specifies the configuration prefix. + */ + public static final String CONFIG_PREFIX = "config.prefix"; + /** + * Constant for the property that specifies the authentication handler to use. + */ + public static final String AUTH_TYPE = "type"; + /** + * Constant for the property that specifies the secret to use for signing the HTTP Cookies. + */ + public static final String SIGNATURE_SECRET = "signature.secret"; + public static final String SIGNATURE_SECRET_FILE = SIGNATURE_SECRET + ".file"; + /** + * Constant for the configuration property that indicates the validity of the generated token. + */ + public static final String AUTH_TOKEN_VALIDITY = "token.validity"; + /** + * Constant for the configuration property that indicates the domain to use in the HTTP cookie. + */ + public static final String COOKIE_DOMAIN = "cookie.domain"; + /** + * Constant for the configuration property that indicates the path to use in the HTTP cookie. + */ + public static final String COOKIE_PATH = "cookie.path"; + /** + * Constant for the configuration property that indicates the name of the + * SignerSecretProvider class to use. + * Possible values are: "string", "random", "zookeeper", or a classname. + * If not specified, the "string" implementation will be used with + * SIGNATURE_SECRET; and if that's not specified, the "random" implementation + * will be used. + */ + public static final String SIGNER_SECRET_PROVIDER = "signer.secret.provider"; + /** + * Constant for the ServletContext attribute that can be used for providing a + * custom implementation of the SignerSecretProvider. Note that the class + * should already be initialized. If not specified, SIGNER_SECRET_PROVIDER + * will be used. + */ + public static final String SIGNER_SECRET_PROVIDER_ATTRIBUTE = "signer.secret.provider.object"; + static final String ALLOW_TRUSTED_PROXY = "ranger.authentication.allow.trustedproxy"; + private static final String BROWSER_USER_AGENT_PARAM = "ranger.krb.browser-useragents-regex"; + private static final String supportKerberosAuthForBrowserLoginConfig = "ranger.allow.kerberos.auth.login.browser"; + + private String[] browserUserAgents; + private Properties config; + private Signer signer; + private SignerSecretProvider secretProvider; + private AuthenticationHandler authHandler; + private long validity; + private String cookieDomain; + private String cookiePath; + private String cookieName; + private boolean isKerberosEnabled; + private boolean supportKerberosAuthForBrowserLogin; + + public static SignerSecretProvider constructSecretProvider(ServletContext ctx, Properties config, boolean disallowFallbackToRandomSecretProvider) throws Exception { + long validity = Long.parseLong(config.getProperty(AUTH_TOKEN_VALIDITY, "36000")) * 1000; + String name = config.getProperty(SIGNER_SECRET_PROVIDER); + + if (StringUtils.isEmpty(name)) { + if (!disallowFallbackToRandomSecretProvider) { + name = "random"; + } else { + name = "file"; + } + } + + SignerSecretProvider provider; + + switch (name) { + case "file": + provider = new FileSignerSecretProvider(); + + try { + provider.init(config, ctx, validity); + } catch (Exception e) { + if (!disallowFallbackToRandomSecretProvider) { + LOG.info("Unable to initialize FileSignerSecretProvider, falling back to use random secrets."); - validity = Long.parseLong(config.getProperty(AUTH_TOKEN_VALIDITY, "36000")) - * 1000; //10 hours - initializeSecretProvider(filterConfig); - - initializeAuthHandler(authHandlerClassName, filterConfig); - - cookieDomain = config.getProperty(COOKIE_DOMAIN, null); - cookiePath = config.getProperty(COOKIE_PATH, null); - cookieName = config.getProperty(RangerCommonConstants.PROP_COOKIE_NAME, RangerCommonConstants.DEFAULT_COOKIE_NAME); - isKerberosEnabled = (PropertiesUtil.getProperty("hadoop.security.authentication", "simple").equalsIgnoreCase("kerberos")); - supportKerberosAuthForBrowserLogin = PropertiesUtil.getBooleanProperty(supportKerberosAuthForBrowserLoginConfig, false); - } - - protected void initializeAuthHandler(String authHandlerClassName, FilterConfig filterConfig) - throws ServletException { - try { - Class klass = Thread.currentThread().getContextClassLoader().loadClass(authHandlerClassName); - authHandler = (AuthenticationHandler) klass.newInstance(); - authHandler.init(config); - } catch (ClassNotFoundException | InstantiationException | - IllegalAccessException ex) { - throw new ServletException(ex); + provider = new RandomSignerSecretProvider(); + + provider.init(config, ctx, validity); + } else { + throw e; + } + } + break; + case "random": + provider = new RandomSignerSecretProvider(); + + provider.init(config, ctx, validity); + break; + case "zookeeper": + provider = new ZKSignerSecretProvider(); + + provider.init(config, ctx, validity); + break; + default: + provider = (SignerSecretProvider) Thread.currentThread().getContextClassLoader().loadClass(name).newInstance(); + + provider.init(config, ctx, validity); + break; + } + + return provider; } - } - - protected void initializeSecretProvider(FilterConfig filterConfig) - throws ServletException { - secretProvider = (SignerSecretProvider) filterConfig.getServletContext(). - getAttribute(SIGNER_SECRET_PROVIDER_ATTRIBUTE); - if (secretProvider == null) { - // As tomcat cannot specify the provider object in the configuration. - // It'll go into this path - try { - secretProvider = constructSecretProvider( - filterConfig.getServletContext(), - config, false); - } catch (Exception ex) { - throw new ServletException(ex); - } + + /** + * Creates the Hadoop authentication HTTP cookie. + * + * @param token authentication token for the cookie. + * @param expires UNIX timestamp that indicates the expire date of the + * cookie. It has no effect if its value < 0. + *

+ * XXX the following code duplicate some logic in Jetty / Servlet API, + * because of the fact that Hadoop is stuck at servlet 2.5 and jetty 6 + * right now. + */ + public static void createAuthCookie(HttpServletResponse resp, String token, String domain, String path, long expires, boolean isSecure) { + StringBuilder sb = new StringBuilder(AuthenticatedURL.AUTH_COOKIE).append("="); + + if (token != null && !token.isEmpty()) { + sb.append("\"").append(token).append("\""); + } + + if (StringUtils.isNotEmpty(path)) { + sb.append("; Path=").append(path); + } + + if (StringUtils.isNotEmpty(domain)) { + sb.append("; Domain=").append(domain); + } + + if (expires >= 0) { + Date date = new Date(expires); + SimpleDateFormat df = new SimpleDateFormat("EEE, " + "dd-MMM-yyyy HH:mm:ss zzz"); + + df.setTimeZone(TimeZone.getTimeZone("GMT")); + + sb.append("; Expires=").append(df.format(date)); + } + + if (isSecure) { + sb.append("; Secure"); + } + + sb.append("; HttpOnly"); + resp.addHeader("Set-Cookie", sb.toString()); } - signer = new Signer(secretProvider); - } - - public static SignerSecretProvider constructSecretProvider( - ServletContext ctx, Properties config, - boolean disallowFallbackToRandomSecretProvider) throws Exception { - long validity = Long.parseLong(config.getProperty(AUTH_TOKEN_VALIDITY, - "36000")) * 1000; - - String name = config.getProperty(SIGNER_SECRET_PROVIDER); - if (StringUtils.isEmpty(name)) { - if (!disallowFallbackToRandomSecretProvider) { - name = "random"; - } else { - name = "file"; - } - } - - SignerSecretProvider provider; - if ("file".equals(name)) { - provider = new FileSignerSecretProvider(); - try { - provider.init(config, ctx, validity); - } catch (Exception e) { - if (!disallowFallbackToRandomSecretProvider) { - LOG.info("Unable to initialize FileSignerSecretProvider, " + - "falling back to use random secrets."); - provider = new RandomSignerSecretProvider(); - provider.init(config, ctx, validity); + + /** + *

Initializes the authentication filter and signer secret provider.

+ * It instantiates and initializes the specified {@link + * AuthenticationHandler}. + * + * @param filterConfig filter configuration. + * @throws ServletException thrown if the filter or the authentication handler could not be initialized properly. + */ + @Override + public void init(FilterConfig filterConfig) throws ServletException { + String configPrefix = filterConfig.getInitParameter(CONFIG_PREFIX); + + configPrefix = (configPrefix != null) ? configPrefix + "." : ""; + config = getConfiguration(configPrefix, filterConfig); + + String authHandlerName = config.getProperty(AUTH_TYPE, null); + String authHandlerClassName; + + if (authHandlerName == null) { + throw new ServletException("Authentication type must be specified: " + PseudoAuthenticationHandler.TYPE + "|" + KerberosAuthenticationHandler.TYPE + "|"); + } + + if (StringUtils.equalsIgnoreCase(authHandlerName, PseudoAuthenticationHandler.TYPE)) { + authHandlerClassName = PseudoAuthenticationHandler.class.getName(); + } else if (StringUtils.equalsIgnoreCase(authHandlerName, KerberosAuthenticationHandler.TYPE)) { + authHandlerClassName = KerberosAuthenticationHandler.class.getName(); } else { - throw e; + authHandlerClassName = authHandlerName; } - } - } else if ("random".equals(name)) { - provider = new RandomSignerSecretProvider(); - provider.init(config, ctx, validity); - } else if ("zookeeper".equals(name)) { - provider = new ZKSignerSecretProvider(); - provider.init(config, ctx, validity); - } else { - provider = (SignerSecretProvider) Thread.currentThread(). - getContextClassLoader().loadClass(name).newInstance(); - provider.init(config, ctx, validity); + + validity = Long.parseLong(config.getProperty(AUTH_TOKEN_VALIDITY, "36000")) * 1000; //10 hours + + initializeSecretProvider(filterConfig); + initializeAuthHandler(authHandlerClassName, filterConfig); + + cookieDomain = config.getProperty(COOKIE_DOMAIN, null); + cookiePath = config.getProperty(COOKIE_PATH, null); + cookieName = config.getProperty(RangerCommonConstants.PROP_COOKIE_NAME, RangerCommonConstants.DEFAULT_COOKIE_NAME); + isKerberosEnabled = (PropertiesUtil.getProperty("hadoop.security.authentication", "simple").equalsIgnoreCase("kerberos")); + supportKerberosAuthForBrowserLogin = PropertiesUtil.getBooleanProperty(supportKerberosAuthForBrowserLoginConfig, false); } - return provider; - } - - /** - * Returns the configuration properties of the {@link RangerKrbFilter} - * without the prefix. The returned properties are the same that the - * {@link #getConfiguration(String, FilterConfig)} method returned. - * - * @return the configuration properties. - */ - protected Properties getConfiguration() { - return config; - } - - /** - * Returns the authentication handler being used. - * - * @return the authentication handler being used. - */ - protected AuthenticationHandler getAuthenticationHandler() { - return authHandler; - } - - /** - * Returns if a random secret is being used. - * - * @return if a random secret is being used. - */ - protected boolean isRandomSecret() { - return secretProvider != null && secretProvider.getClass() == RandomSignerSecretProvider.class; - } - - /** - * Returns if a custom implementation of a SignerSecretProvider is being used. - * - * @return if a custom implementation of a SignerSecretProvider is being used. - */ - protected boolean isCustomSignerSecretProvider() { - Class clazz = secretProvider != null ? secretProvider.getClass() : null; - return clazz != FileSignerSecretProvider.class && clazz != - RandomSignerSecretProvider.class && clazz != ZKSignerSecretProvider - .class; - } - - /** - * Returns the validity time of the generated tokens. - * - * @return the validity time of the generated tokens, in seconds. - */ - protected long getValidity() { - return validity / 1000; - } - - /** - * Returns the cookie domain to use for the HTTP cookie. - * - * @return the cookie domain to use for the HTTP cookie. - */ - protected String getCookieDomain() { - return cookieDomain; - } - - /** - * Returns the cookie path to use for the HTTP cookie. - * - * @return the cookie path to use for the HTTP cookie. - */ - protected String getCookiePath() { - return cookiePath; - } - - /** - * Destroys the filter. - *

- * It invokes the {@link AuthenticationHandler#destroy()} method to release any resources it may hold. - */ - @Override - public void destroy() { - if (authHandler != null) { - authHandler.destroy(); - authHandler = null; + + /** + * If the request has a valid authentication token it allows the request to continue to the target resource, + * otherwise it triggers an authentication sequence using the configured {@link AuthenticationHandler}. + * + * @param request the request object. + * @param response the response object. + * @param filterChain the filter chain object. + * @throws IOException thrown if an IO error occurred. + * @throws ServletException thrown if a processing error occurred. + */ + @Override + public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException { + boolean unauthorizedResponse = true; + int errCode = HttpServletResponse.SC_UNAUTHORIZED; + AuthenticationException authenticationEx = null; + HttpServletRequest httpRequest = (HttpServletRequest) request; + HttpServletResponse httpResponse = (HttpServletResponse) response; + boolean isHttps = "https".equals(httpRequest.getScheme()); + boolean allowTrustedProxy = PropertiesUtil.getBooleanProperty(ALLOW_TRUSTED_PROXY, false); + long contentLength = httpRequest.getContentLength(); + + try { + boolean newToken = false; + AuthenticationToken token; + + try { + token = getToken(httpRequest); + } catch (AuthenticationException ex) { + ex.printStackTrace(); + + LOG.warn("AuthenticationToken ignored: {}", ex.getMessage()); + + // will be sent back in a 401 unless filter authenticates + authenticationEx = ex; + token = null; + } + + if (authHandler.managementOperation(token, httpRequest, httpResponse)) { + if (token == null) { + if (LOG.isDebugEnabled()) { + LOG.debug("Request [{}] triggering authentication", getRequestURL(httpRequest)); + } + + token = authHandler.authenticate(httpRequest, httpResponse); + + if (token != null && token.getExpires() != 0 && token != AuthenticationToken.ANONYMOUS) { + token.setExpires(System.currentTimeMillis() + getValidity() * 1000); + } + + newToken = true; + } + if (token != null) { + unauthorizedResponse = false; + + if (LOG.isDebugEnabled()) { + LOG.debug("Request [{}] user [{}] authenticated", getRequestURL(httpRequest), token.getUserName()); + } + + final AuthenticationToken authToken = token; + + httpRequest = new HttpServletRequestWrapper(httpRequest) { + @Override + public String getAuthType() { + return authToken.getType(); + } + + @Override + public String getRemoteUser() { + return authToken.getUserName(); + } + + @Override + public Principal getUserPrincipal() { + return (authToken != AuthenticationToken.ANONYMOUS) ? authToken : null; + } + }; + + if ((newToken || allowTrustedProxy) && !token.isExpired() && token != AuthenticationToken.ANONYMOUS) { + String signedToken = signer.sign(token.toString()); + + createAuthCookie(httpResponse, signedToken, getCookieDomain(), getCookiePath(), token.getExpires(), isHttps); + } + + doFilter(filterChain, httpRequest, httpResponse); + } + } else { + unauthorizedResponse = false; + } + } catch (AuthenticationException ex) { + // exception from the filter itself is fatal + ex.printStackTrace(); + + errCode = HttpServletResponse.SC_FORBIDDEN; + authenticationEx = ex; + + LOG.warn("Authentication exception: {}", ex.getMessage(), ex); + } + + if (unauthorizedResponse) { + String doAsUser = request.getParameter("doAs"); + + if (!httpResponse.isCommitted()) { + LOG.debug("create auth cookie"); + + createAuthCookie(httpResponse, "", getCookieDomain(), getCookiePath(), 0, isHttps); + + // If response code is 401. Then WWW-Authenticate Header should be + // present.. reset to 403 if not found.. + if ((errCode == HttpServletResponse.SC_UNAUTHORIZED) && (!httpResponse.containsHeader(KerberosAuthenticator.WWW_AUTHENTICATE) && !isKerberosEnabled && !supportKerberosAuthForBrowserLogin)) { + errCode = HttpServletResponse.SC_FORBIDDEN; + } + + if (authenticationEx == null) { + String agents = PropertiesUtil.getProperty(BROWSER_USER_AGENT_PARAM, RangerCSRFPreventionFilter.BROWSER_USER_AGENTS_DEFAULT); + + if (agents == null) { + agents = RangerCSRFPreventionFilter.BROWSER_USER_AGENTS_DEFAULT; + } + + parseBrowserUserAgents(agents); + + if (isBrowser(httpRequest.getHeader(RangerCSRFPreventionFilter.HEADER_USER_AGENT)) && (!allowTrustedProxy || StringUtils.isEmpty(doAsUser)) && !supportKerberosAuthForBrowserLogin) { + ((HttpServletResponse) response).setHeader(KerberosAuthenticator.WWW_AUTHENTICATE, ""); + + filterChain.doFilter(request, response); + } else { + if (isKerberosEnabled && isBrowser(httpRequest.getHeader(RangerCSRFPreventionFilter.HEADER_USER_AGENT)) && supportKerberosAuthForBrowserLogin) { + LOG.debug("Kerberos and ticket based browser login is enabled setting header to authenticate ticket based login for user."); + + ((HttpServletResponse) response).setHeader(KerberosAuthenticator.WWW_AUTHENTICATE, KerberosAuthenticator.NEGOTIATE); + } + + if (allowTrustedProxy) { + String expectHeader = httpRequest.getHeader("Expect"); + + LOG.debug("expect header in request = {}", expectHeader); + LOG.debug("http response code = {}", httpResponse.getStatus()); + + if (expectHeader != null && expectHeader.startsWith("100")) { + LOG.debug("skipping 100 continue!!"); + + if (contentLength <= 0) { + contentLength = Integer.MAX_VALUE; + + try { + LOG.debug("Skipping content length of {}", contentLength); + + skipFully(request.getInputStream(), contentLength); + } catch (EOFException ex) { + LOG.info(ex.getMessage()); + } + } + } + } + + boolean chk = true; + Collection headerNames = httpResponse.getHeaderNames(); + + LOG.debug("response header names = {}", headerNames); + + for (String headerName : headerNames) { + String value = httpResponse.getHeader(headerName); + + if ("Set-Cookie".equalsIgnoreCase(headerName) && value.startsWith(cookieName)) { + chk = false; + break; + } + } + + String authHeader = httpRequest.getHeader("Authorization"); + + if (authHeader == null && chk) { + filterChain.doFilter(request, response); + } else if (authHeader != null && authHeader.startsWith("Basic")) { + filterChain.doFilter(request, response); + } + } + } else { + httpResponse.sendError(errCode, authenticationEx.getMessage()); + } + } + } } - } - - /** - * Returns the filtered configuration (only properties starting with the specified prefix). The property keys - * are also trimmed from the prefix. The returned {@link Properties} object is used to initialized the - * {@link AuthenticationHandler}. - *

- * This method can be overriden by subclasses to obtain the configuration from other configuration source than - * the web.xml file. - * - * @param configPrefix configuration prefix to use for extracting configuration properties. - * @param filterConfig filter configuration object - * - * @return the configuration to be used with the {@link AuthenticationHandler} instance. - * - * @throws ServletException thrown if the configuration could not be created. - */ - protected Properties getConfiguration(String configPrefix, FilterConfig filterConfig) throws ServletException { - Properties props = new Properties(); - if(filterConfig != null){ - Enumeration names = filterConfig.getInitParameterNames(); - if(names != null){ - while (names.hasMoreElements()) { - String name = (String) names.nextElement(); - if (name != null && configPrefix != null && name.startsWith(configPrefix)) { - String value = filterConfig.getInitParameter(name); - props.put(name.substring(configPrefix.length()), value); - } - } - } + + /** + * Destroys the filter. + *

+ * It invokes the {@link AuthenticationHandler#destroy()} method to release any resources it may hold. + */ + @Override + public void destroy() { + if (authHandler != null) { + authHandler.destroy(); + + authHandler = null; + } } - return props; - } - - /** - * Returns the full URL of the request including the query string. - *

- * Used as a convenience method for logging purposes. - * - * @param request the request object. - * - * @return the full URL of the request including the query string. - */ - protected String getRequestURL(HttpServletRequest request) { - StringBuffer sb = request.getRequestURL(); - if (request.getQueryString() != null) { - sb.append("?").append(request.getQueryString()); + + protected void initializeAuthHandler(String authHandlerClassName, FilterConfig filterConfig) throws ServletException { + try { + Class klass = Thread.currentThread().getContextClassLoader().loadClass(authHandlerClassName); + + authHandler = (AuthenticationHandler) klass.newInstance(); + + authHandler.init(config); + } catch (ClassNotFoundException | InstantiationException | IllegalAccessException ex) { + throw new ServletException(ex); + } } - return sb.toString(); - } - - /** - * Returns the {@link AuthenticationToken} for the request. - *

- * It looks at the received HTTP cookies and extracts the value of the {@link AuthenticatedURL#AUTH_COOKIE} - * if present. It verifies the signature and if correct it creates the {@link AuthenticationToken} and returns - * it. - *

- * If this method returns null the filter will invoke the configured {@link AuthenticationHandler} - * to perform user authentication. - * - * @param request request object. - * - * @return the Authentication token if the request is authenticated, null otherwise. - * - * @throws IOException thrown if an IO error occurred. - * @throws AuthenticationException thrown if the token is invalid or if it has expired. - */ - protected AuthenticationToken getToken(HttpServletRequest request) throws IOException, AuthenticationException { - AuthenticationToken token = null; - String tokenStr = null; - Cookie[] cookies = request.getCookies(); - if (cookies != null) { - for (Cookie cookie : cookies) { - if (AuthenticatedURL.AUTH_COOKIE.equals(cookie.getName())) { - tokenStr = cookie.getValue(); - try { - tokenStr = signer.verifyAndExtract(tokenStr); - } catch (SignerException ex) { - throw new AuthenticationException(ex); - } - break; + + protected void initializeSecretProvider(FilterConfig filterConfig) throws ServletException { + secretProvider = (SignerSecretProvider) filterConfig.getServletContext().getAttribute(SIGNER_SECRET_PROVIDER_ATTRIBUTE); + + if (secretProvider == null) { + // As tomcat cannot specify the provider object in the configuration. + // It'll go into this path + try { + secretProvider = constructSecretProvider(filterConfig.getServletContext(), config, false); + } catch (Exception ex) { + throw new ServletException(ex); + } } - } + + signer = new Signer(secretProvider); } - if (tokenStr != null) { - token = AuthenticationToken.parse(tokenStr); - if(token != null){ - if (!token.getType().equals(authHandler.getType())) { - throw new AuthenticationException("Invalid AuthenticationToken type"); - } - if (token.isExpired()) { - throw new AuthenticationException("AuthenticationToken expired"); - } - } + + /** + * Returns the configuration properties of the {@link RangerKrbFilter} + * without the prefix. The returned properties are the same that the + * {@link #getConfiguration(String, FilterConfig)} method returned. + * + * @return the configuration properties. + */ + protected Properties getConfiguration() { + return config; } - return token; - } - - /** - * If the request has a valid authentication token it allows the request to continue to the target resource, - * otherwise it triggers an authentication sequence using the configured {@link AuthenticationHandler}. - * - * @param request the request object. - * @param response the response object. - * @param filterChain the filter chain object. - * - * @throws IOException thrown if an IO error occurred. - * @throws ServletException thrown if a processing error occurred. - */ - @Override - public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) - throws IOException, ServletException { - boolean unauthorizedResponse = true; - int errCode = HttpServletResponse.SC_UNAUTHORIZED; - AuthenticationException authenticationEx = null; - HttpServletRequest httpRequest = (HttpServletRequest) request; - HttpServletResponse httpResponse = (HttpServletResponse) response; - boolean isHttps = "https".equals(httpRequest.getScheme()); - boolean allowTrustedProxy = PropertiesUtil.getBooleanProperty(ALLOW_TRUSTED_PROXY, false); - long contentLength = httpRequest.getContentLength(); - - try { - boolean newToken = false; - AuthenticationToken token; - try { - token = getToken(httpRequest); - } - catch (AuthenticationException ex) { - ex.printStackTrace(); - LOG.warn("AuthenticationToken ignored: " + ex.getMessage()); - // will be sent back in a 401 unless filter authenticates - authenticationEx = ex; - token = null; - } - - if (authHandler.managementOperation(token, httpRequest, httpResponse)) { - if (token == null) { - if (LOG.isDebugEnabled()) { - LOG.debug("Request [{}] triggering authentication", getRequestURL(httpRequest)); - } - token = authHandler.authenticate(httpRequest, httpResponse); - if (token != null && token.getExpires() != 0 && - token != AuthenticationToken.ANONYMOUS) { - token.setExpires(System.currentTimeMillis() + getValidity() * 1000); - } - newToken = true; - } - if (token != null) { - unauthorizedResponse = false; - if (LOG.isDebugEnabled()) { - LOG.debug("Request [{}] user [{}] authenticated", getRequestURL(httpRequest), token.getUserName()); - } - final AuthenticationToken authToken = token; - httpRequest = new HttpServletRequestWrapper(httpRequest) { - - @Override - public String getAuthType() { - return authToken.getType(); - } - @Override - public String getRemoteUser() { - return authToken.getUserName(); - } + /** + * Returns the authentication handler being used. + * + * @return the authentication handler being used. + */ + protected AuthenticationHandler getAuthenticationHandler() { + return authHandler; + } + + /** + * Returns if a random secret is being used. + * + * @return if a random secret is being used. + */ + protected boolean isRandomSecret() { + return secretProvider != null && secretProvider.getClass() == RandomSignerSecretProvider.class; + } + + /** + * Returns if a custom implementation of a SignerSecretProvider is being used. + * + * @return if a custom implementation of a SignerSecretProvider is being used. + */ + protected boolean isCustomSignerSecretProvider() { + Class clazz = secretProvider != null ? secretProvider.getClass() : null; + + return clazz != FileSignerSecretProvider.class && clazz != RandomSignerSecretProvider.class && clazz != ZKSignerSecretProvider.class; + } - @Override - public Principal getUserPrincipal() { - return (authToken != AuthenticationToken.ANONYMOUS) ? authToken : null; + /** + * Returns the validity time of the generated tokens. + * + * @return the validity time of the generated tokens, in seconds. + */ + protected long getValidity() { + return validity / 1000; + } + + /** + * Returns the cookie domain to use for the HTTP cookie. + * + * @return the cookie domain to use for the HTTP cookie. + */ + protected String getCookieDomain() { + return cookieDomain; + } + + /** + * Returns the cookie path to use for the HTTP cookie. + * + * @return the cookie path to use for the HTTP cookie. + */ + protected String getCookiePath() { + return cookiePath; + } + + /** + * Returns the filtered configuration (only properties starting with the specified prefix). The property keys + * are also trimmed from the prefix. The returned {@link Properties} object is used to initialized the + * {@link AuthenticationHandler}. + *

+ * This method can be overriden by subclasses to obtain the configuration from other configuration source than + * the web.xml file. + * + * @param configPrefix configuration prefix to use for extracting configuration properties. + * @param filterConfig filter configuration object + * @return the configuration to be used with the {@link AuthenticationHandler} instance. + * @throws ServletException thrown if the configuration could not be created. + */ + protected Properties getConfiguration(String configPrefix, FilterConfig filterConfig) throws ServletException { + Properties props = new Properties(); + + if (filterConfig != null) { + Enumeration names = filterConfig.getInitParameterNames(); + + if (names != null) { + while (names.hasMoreElements()) { + String name = (String) names.nextElement(); + + if (name != null && configPrefix != null && name.startsWith(configPrefix)) { + String value = filterConfig.getInitParameter(name); + + props.put(name.substring(configPrefix.length()), value); + } + } } - }; - if ((newToken || allowTrustedProxy) && !token.isExpired() && token != AuthenticationToken.ANONYMOUS) { - String signedToken = signer.sign(token.toString()); - createAuthCookie(httpResponse, signedToken, getCookieDomain(), - getCookiePath(), token.getExpires(), isHttps); - } - doFilter(filterChain, httpRequest, httpResponse); } - } else { - unauthorizedResponse = false; - } - } catch (AuthenticationException ex) { - // exception from the filter itself is fatal - ex.printStackTrace(); - errCode = HttpServletResponse.SC_FORBIDDEN; - authenticationEx = ex; - LOG.warn("Authentication exception: " + ex.getMessage(), ex); + + return props; } - if (unauthorizedResponse) { - String doAsUser = request.getParameter("doAs"); - if (!httpResponse.isCommitted()) { - if (LOG.isDebugEnabled()) { - LOG.debug("create auth cookie"); - } - createAuthCookie(httpResponse, "", getCookieDomain(), - getCookiePath(), 0, isHttps); - // If response code is 401. Then WWW-Authenticate Header should be - // present.. reset to 403 if not found.. - if ((errCode == HttpServletResponse.SC_UNAUTHORIZED) - && (!httpResponse.containsHeader( - KerberosAuthenticator.WWW_AUTHENTICATE) && !isKerberosEnabled && !supportKerberosAuthForBrowserLogin)) { - errCode = HttpServletResponse.SC_FORBIDDEN; + + /** + * Returns the full URL of the request including the query string. + *

+ * Used as a convenience method for logging purposes. + * + * @param request the request object. + * @return the full URL of the request including the query string. + */ + protected String getRequestURL(HttpServletRequest request) throws IOException { + StringBuffer sb = request.getRequestURL(); + + if (request.getQueryString() != null) { + sb.append("?").append(request.getQueryString()); } - if (authenticationEx == null) { - String agents = PropertiesUtil.getProperty(BROWSER_USER_AGENT_PARAM, RangerCSRFPreventionFilter.BROWSER_USER_AGENTS_DEFAULT); - if (agents == null) { - agents = RangerCSRFPreventionFilter.BROWSER_USER_AGENTS_DEFAULT; - } - parseBrowserUserAgents(agents); - if(isBrowser(httpRequest.getHeader(RangerCSRFPreventionFilter.HEADER_USER_AGENT)) && - (!allowTrustedProxy || (allowTrustedProxy && StringUtils.isEmpty(doAsUser))) && !supportKerberosAuthForBrowserLogin){ - ((HttpServletResponse)response).setHeader(KerberosAuthenticator.WWW_AUTHENTICATE, ""); - filterChain.doFilter(request, response); - }else{ - if (isKerberosEnabled && isBrowser(httpRequest.getHeader(RangerCSRFPreventionFilter.HEADER_USER_AGENT)) && supportKerberosAuthForBrowserLogin) { - if (LOG.isDebugEnabled()) { - LOG.debug("Kerberos and ticket based browser login is enabled setting header to authenticate ticket based login for user."); - } - ((HttpServletResponse) response).setHeader(KerberosAuthenticator.WWW_AUTHENTICATE, KerberosAuthenticator.NEGOTIATE); - } - if (allowTrustedProxy) { - String expectHeader = httpRequest.getHeader("Expect"); - if (LOG.isDebugEnabled()) { - LOG.debug("expect header in request = " + expectHeader); - LOG.debug("http response code = " + httpResponse.getStatus()); - } - if (expectHeader != null && expectHeader.startsWith("100")) { - if (LOG.isDebugEnabled()) { - LOG.debug("skipping 100 continue!!"); - } - if (contentLength <= 0) { - Integer maxContentLen = Integer.MAX_VALUE; - contentLength = maxContentLen.longValue(); + + return sb.toString(); + } + + /** + * Returns the {@link AuthenticationToken} for the request. + *

+ * It looks at the received HTTP cookies and extracts the value of the {@link AuthenticatedURL#AUTH_COOKIE} + * if present. It verifies the signature and if correct it creates the {@link AuthenticationToken} and returns + * it. + *

+ * If this method returns null the filter will invoke the configured {@link AuthenticationHandler} + * to perform user authentication. + * + * @param request request object. + * @return the Authentication token if the request is authenticated, null otherwise. + * @throws IOException thrown if an IO error occurred. + * @throws AuthenticationException thrown if the token is invalid or if it has expired. + */ + protected AuthenticationToken getToken(HttpServletRequest request) throws IOException, AuthenticationException { + AuthenticationToken token = null; + String tokenStr = null; + Cookie[] cookies = request.getCookies(); + + if (cookies != null) { + for (Cookie cookie : cookies) { + if (AuthenticatedURL.AUTH_COOKIE.equals(cookie.getName())) { + tokenStr = cookie.getValue(); + try { - if (LOG.isDebugEnabled()) { - LOG.debug("Skipping content length of " + contentLength); - } - skipFully(request.getInputStream(), contentLength); - } catch (EOFException ex) { - LOG.info(ex.getMessage()); + tokenStr = signer.verifyAndExtract(tokenStr); + } catch (SignerException ex) { + throw new AuthenticationException(ex); } - } + + break; } - } - boolean chk = true; - Collection headerNames = httpResponse.getHeaderNames(); - if (LOG.isDebugEnabled()) { - LOG.debug("reponse header names = " + headerNames); - } - for(String headerName : headerNames){ - String value = httpResponse.getHeader(headerName); - if("Set-Cookie".equalsIgnoreCase(headerName) && value.startsWith(cookieName)){ - chk = false; - break; + } + } + if (tokenStr != null) { + token = AuthenticationToken.parse(tokenStr); + + if (token != null) { + if (!token.getType().equals(authHandler.getType())) { + throw new AuthenticationException("Invalid AuthenticationToken type"); } - } - String authHeader = httpRequest.getHeader("Authorization"); - if(authHeader == null && chk){ - filterChain.doFilter(request, response); - }else if(authHeader != null && authHeader.startsWith("Basic")){ - filterChain.doFilter(request, response); - } - } - } else { - httpResponse.sendError(errCode, authenticationEx.getMessage()); + + if (token.isExpired()) { + throw new AuthenticationException("AuthenticationToken expired"); + } + } } - } - } - } - - /** - * Delegates call to the servlet filter chain. Sub-classes my override this - * method to perform pre and post tasks. - */ - protected void doFilter(FilterChain filterChain, HttpServletRequest request, - HttpServletResponse response) throws IOException, ServletException { - filterChain.doFilter(request, response); - } - - /** - * Creates the Hadoop authentication HTTP cookie. - * - * @param token authentication token for the cookie. - * @param expires UNIX timestamp that indicates the expire date of the - * cookie. It has no effect if its value < 0. - * - * XXX the following code duplicate some logic in Jetty / Servlet API, - * because of the fact that Hadoop is stuck at servlet 2.5 and jetty 6 - * right now. - */ - public static void createAuthCookie(HttpServletResponse resp, String token, - String domain, String path, long expires, - boolean isSecure) { - StringBuilder sb = new StringBuilder(AuthenticatedURL.AUTH_COOKIE) - .append("="); - if (token != null && token.length() > 0) { - sb.append("\"").append(token).append("\""); - } - if (StringUtils.isNotEmpty(path)) { - sb.append("; Path=").append(path); + return token; } - if (StringUtils.isNotEmpty(domain)) { - sb.append("; Domain=").append(domain); + /** + * Delegates call to the servlet filter chain. Sub-classes my override this + * method to perform pre and post tasks. + */ + protected void doFilter(FilterChain filterChain, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { + filterChain.doFilter(request, response); } - if (expires >= 0) { - Date date = new Date(expires); - SimpleDateFormat df = new SimpleDateFormat("EEE, " + - "dd-MMM-yyyy HH:mm:ss zzz"); - df.setTimeZone(TimeZone.getTimeZone("GMT")); - sb.append("; Expires=").append(df.format(date)); - } + protected boolean isBrowser(String userAgent) { + boolean isWeb = false; + + if (browserUserAgents != null && browserUserAgents.length > 0 && userAgent != null) { + for (String ua : browserUserAgents) { + if (userAgent.toLowerCase().startsWith(ua.toLowerCase())) { + isWeb = true; + break; + } + } + } - if (isSecure) { - sb.append("; Secure"); + return isWeb; } - sb.append("; HttpOnly"); - resp.addHeader("Set-Cookie", sb.toString()); - } - - void parseBrowserUserAgents(String userAgents) { - browserUserAgents = userAgents.split(","); - } - - protected boolean isBrowser(String userAgent) { - boolean isWeb = false; - if (browserUserAgents != null && browserUserAgents.length > 0 && userAgent != null) { - for (String ua : browserUserAgents) { - if (userAgent.toLowerCase().startsWith(ua.toLowerCase())) { - isWeb = true; - break; - } - } - } - return isWeb; - } + void parseBrowserUserAgents(String userAgents) { + browserUserAgents = userAgents.split(","); + } } - diff --git a/security-admin/src/main/java/org/apache/ranger/security/web/filter/RangerMDCFilter.java b/security-admin/src/main/java/org/apache/ranger/security/web/filter/RangerMDCFilter.java index 46ecd94912..40013dca57 100644 --- a/security-admin/src/main/java/org/apache/ranger/security/web/filter/RangerMDCFilter.java +++ b/security-admin/src/main/java/org/apache/ranger/security/web/filter/RangerMDCFilter.java @@ -19,7 +19,11 @@ package org.apache.ranger.security.web.filter; -import java.io.IOException; +import org.apache.ranger.common.PropertiesUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.slf4j.MDC; + import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; @@ -27,10 +31,8 @@ import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; -import org.apache.ranger.common.PropertiesUtil; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.slf4j.MDC; + +import java.io.IOException; /** * RangerMDCFilter filter that captures the HTTP request and insert request-id @@ -40,8 +42,8 @@ public class RangerMDCFilter implements Filter { private static final Logger log = LoggerFactory.getLogger(RangerMDCFilter.class); - public static final String DEFAULT_MDC_KEY = "REQUEST_ID"; - public static final String DEFAULT_REQUEST_ID_HEADER_NAME = "request-id"; + public static final String DEFAULT_MDC_KEY = "REQUEST_ID"; + public static final String DEFAULT_REQUEST_ID_HEADER_NAME = "request-id"; private static final boolean DEFAULT_MDC_FILTER_ENABLED = false; private static final String PROP_MDC_FILTER_MDC_KEY = "ranger.admin.mdc-filter.mdcKey"; private static final String PROP_MDC_FILTER_REQUEST_ID_HEADER_NAME = "ranger.admin.mdc-filter.requestHeader.name"; @@ -51,12 +53,9 @@ public class RangerMDCFilter implements Filter { private String requestHeaderName = DEFAULT_REQUEST_ID_HEADER_NAME; private boolean mdcFilterEnabled = DEFAULT_MDC_FILTER_ENABLED; - @Override public void init(FilterConfig config) throws ServletException { - if (log.isDebugEnabled()) { - log.debug("==> RangerMDCFilter.initialize()"); - } + log.debug("==> RangerMDCFilter.initialize()"); mdcFilterEnabled = PropertiesUtil.getBooleanProperty(PROP_MDC_FILTER_ENABLED, DEFAULT_MDC_FILTER_ENABLED); @@ -64,25 +63,20 @@ public void init(FilterConfig config) throws ServletException { requestHeaderName = PropertiesUtil.getProperty(PROP_MDC_FILTER_REQUEST_ID_HEADER_NAME, DEFAULT_REQUEST_ID_HEADER_NAME); mdcKey = PropertiesUtil.getProperty(PROP_MDC_FILTER_MDC_KEY, DEFAULT_MDC_KEY); - log.info(PROP_MDC_FILTER_REQUEST_ID_HEADER_NAME + "=" + requestHeaderName); - log.info(PROP_MDC_FILTER_MDC_KEY + "=" + mdcKey); + log.info("{} = {}", PROP_MDC_FILTER_REQUEST_ID_HEADER_NAME, requestHeaderName); + log.info("{} = {}", PROP_MDC_FILTER_MDC_KEY, mdcKey); } - log.info(PROP_MDC_FILTER_ENABLED + "=" + mdcFilterEnabled); - - if (log.isDebugEnabled()) { - log.debug("<== RangerMDCFilter.initialize()"); - } + log.info("{} = {}", PROP_MDC_FILTER_ENABLED, mdcFilterEnabled); + log.debug("<== RangerMDCFilter.initialize()"); } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { - if (log.isDebugEnabled()) { - log.debug("==> RangerMDCFilter.doFilter()"); - } + log.debug("==> RangerMDCFilter.doFilter()"); if (mdcFilterEnabled) { - HttpServletRequest httpRequest = (HttpServletRequest)request; + HttpServletRequest httpRequest = (HttpServletRequest) request; String requestId = httpRequest.getHeader(requestHeaderName); if (requestId != null) { @@ -98,9 +92,7 @@ public void doFilter(ServletRequest request, ServletResponse response, FilterCha chain.doFilter(request, response); } - if (log.isDebugEnabled()) { - log.debug("<== RangerMDCFilter.doFilter()"); - } + log.debug("<== RangerMDCFilter.doFilter()"); } @Override diff --git a/security-admin/src/main/java/org/apache/ranger/security/web/filter/RangerSSOAuthenticationFilter.java b/security-admin/src/main/java/org/apache/ranger/security/web/filter/RangerSSOAuthenticationFilter.java index e59bf3f7e6..23498094c5 100644 --- a/security-admin/src/main/java/org/apache/ranger/security/web/filter/RangerSSOAuthenticationFilter.java +++ b/security-admin/src/main/java/org/apache/ranger/security/web/filter/RangerSSOAuthenticationFilter.java @@ -20,12 +20,18 @@ package org.apache.ranger.security.web.filter; import com.google.inject.Inject; -import com.nimbusds.jose.JOSEException; import com.nimbusds.jose.JWSObject; import com.nimbusds.jose.JWSVerifier; import com.nimbusds.jose.crypto.RSASSAVerifier; import com.nimbusds.jwt.SignedJWT; - +import org.apache.commons.lang.StringUtils; +import org.apache.ranger.biz.UserMgr; +import org.apache.ranger.common.PropertiesUtil; +import org.apache.ranger.common.RangerConstants; +import org.apache.ranger.common.UserSessionBase; +import org.apache.ranger.security.context.RangerContextHolder; +import org.apache.ranger.security.context.RangerSecurityContext; +import org.apache.ranger.security.handler.RangerAuthenticationProvider; import org.apache.ranger.util.RestUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -40,14 +46,24 @@ import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.web.authentication.WebAuthenticationDetails; -import javax.servlet.*; +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.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import java.io.ByteArrayInputStream; import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.nio.charset.StandardCharsets; import java.security.PublicKey; import java.security.cert.CertificateException; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; import java.security.interfaces.RSAPublicKey; import java.text.ParseException; import java.util.ArrayList; @@ -56,547 +72,513 @@ import java.util.Date; import java.util.List; -import org.apache.commons.lang.StringUtils; -import org.apache.ranger.biz.UserMgr; -import org.apache.ranger.common.PropertiesUtil; -import org.apache.ranger.common.RangerConstants; -import org.apache.ranger.common.UserSessionBase; -import org.apache.ranger.security.context.RangerContextHolder; -import org.apache.ranger.security.context.RangerSecurityContext; -import org.apache.ranger.security.handler.RangerAuthenticationProvider; - -import java.io.ByteArrayInputStream; -import java.io.UnsupportedEncodingException; -import java.security.cert.CertificateFactory; -import java.security.cert.X509Certificate; - public class RangerSSOAuthenticationFilter implements Filter { - private static final Logger LOG = LoggerFactory.getLogger(RangerSSOAuthenticationFilter.class); - - public static final String BROWSER_USERAGENT = "ranger.sso.browser.useragent"; - public static final String JWT_AUTH_PROVIDER_URL = "ranger.sso.providerurl"; - public static final String JWT_PUBLIC_KEY = "ranger.sso.publicKey"; - public static final String JWT_COOKIE_NAME = "ranger.sso.cookiename"; - public static final String JWT_AUDIENCES = "ranger.sso.audiences"; - public static final String JWT_ORIGINAL_URL_QUERY_PARAM = "ranger.sso.query.param.originalurl"; - public static final String JWT_COOKIE_NAME_DEFAULT = "hadoop-jwt"; - public static final String JWT_ORIGINAL_URL_QUERY_PARAM_DEFAULT = "originalUrl"; - /** + private static final Logger LOG = LoggerFactory.getLogger(RangerSSOAuthenticationFilter.class); + + public static final String BROWSER_USERAGENT = "ranger.sso.browser.useragent"; + public static final String JWT_AUTH_PROVIDER_URL = "ranger.sso.providerurl"; + public static final String JWT_PUBLIC_KEY = "ranger.sso.publicKey"; + public static final String JWT_COOKIE_NAME = "ranger.sso.cookiename"; + public static final String JWT_AUDIENCES = "ranger.sso.audiences"; + public static final String JWT_ORIGINAL_URL_QUERY_PARAM = "ranger.sso.query.param.originalurl"; + public static final String JWT_COOKIE_NAME_DEFAULT = "hadoop-jwt"; + public static final String JWT_ORIGINAL_URL_QUERY_PARAM_DEFAULT = "originalUrl"; + /** * If specified, this configuration property refers to the signature algorithm which a received * token must match. Otherwise, the default value "RS256" is used */ - public static final String JWT_EXPECTED_SIGALG = "ranger.sso.expected.sigalg"; - public static final String JWT_DEFAULT_SIGALG = "RS256"; - - public static final String DEFAULT_BROWSER_USERAGENT = "ranger.default.browser-useragents"; - - - private SSOAuthenticationProperties jwtProperties; - - private String originalUrlQueryParam = "originalUrl"; - private String authenticationProviderUrl = null; - private RSAPublicKey publicKey = null; - private String cookieName = "hadoop-jwt"; - - @Autowired - UserMgr userMgr; - - @Inject - public RangerSSOAuthenticationFilter(){ - jwtProperties = getJwtProperties(); - loadJwtProperties(); - } - - public RangerSSOAuthenticationFilter( - SSOAuthenticationProperties jwtProperties){ - this.jwtProperties = jwtProperties; - loadJwtProperties(); - } - - @Override - public void init(FilterConfig filterConfig) throws ServletException { - } - - /* - * doFilter of RangerSSOAuthenticationFilter is the first in the filter list so in this it check for the request - * if the request is from browser, doesn't contain local login and sso is enabled then it process the request against knox sso - * else if it's ssoenable and the request is with local login string then it show's the appropriate msg - * else if ssoenable is false then it contiunes with further filters as it was before sso - */ - @Override - public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)throws IOException, ServletException { - - HttpServletRequest httpRequest = (HttpServletRequest)servletRequest; - - String xForwardedURL = RestUtil.constructForwardableURL(httpRequest); - - if (httpRequest.getRequestedSessionId() != null && !httpRequest.isRequestedSessionIdValid()){ - synchronized(httpRequest.getServletContext()){ - if(httpRequest.getServletContext().getAttribute(httpRequest.getRequestedSessionId()) != null && "locallogin".equals(httpRequest.getServletContext().getAttribute(httpRequest.getRequestedSessionId()).toString())){ - httpRequest.getSession().setAttribute("locallogin","true"); - httpRequest.getServletContext().removeAttribute(httpRequest.getRequestedSessionId()); - } - } - } - - RangerSecurityContext context = RangerContextHolder.getSecurityContext(); - UserSessionBase session = context != null ? context.getUserSession() : null; - boolean ssoEnabled = session != null ? session.isSSOEnabled() : PropertiesUtil.getBooleanProperty("ranger.sso.enabled", false); - - String userAgent = httpRequest.getHeader("User-Agent"); - if(httpRequest.getSession() != null){ - if(httpRequest.getSession().getAttribute("locallogin") != null){ - servletRequest.setAttribute("ssoEnabled", false); - filterChain.doFilter(servletRequest, servletResponse); - return; - } - } - //If sso is enable and request is not for local login and is from browser then it will go inside and try for knox sso authentication - if (ssoEnabled && !httpRequest.getRequestURI().contains(RestUtil.LOCAL_LOGIN_URL)) { - //if jwt properties are loaded and is current not authenticated then it will go for sso authentication - //Note : Need to remove !isAuthenticated() after knoxsso solve the bug from cross-origin script - if (jwtProperties != null && !isAuthenticated()) { - HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; - String serializedJWT = getJWTFromCookie(httpRequest); - // if we get the hadoop-jwt token from the cookies then will process it further - if (serializedJWT != null) { - SignedJWT jwtToken = null; - try { - jwtToken = SignedJWT.parse(serializedJWT); - boolean valid = validateToken(jwtToken); - //if the public key provide is correct and also token is not expired the process token - if (valid) { - String userName = jwtToken.getJWTClaimsSet().getSubject(); - LOG.info("SSO login user : "+userName); - - String rangerLdapDefaultRole = PropertiesUtil.getProperty("ranger.ldap.default.role", "ROLE_USER"); - //if we get the userName from the token then log into ranger using the same user - if (userName != null && !userName.trim().isEmpty()) { - final List grantedAuths = new ArrayList<>(); - grantedAuths.add(new SimpleGrantedAuthority(rangerLdapDefaultRole)); - final UserDetails principal = new User(userName, "",grantedAuths); - final Authentication finalAuthentication = new UsernamePasswordAuthenticationToken(principal, "", grantedAuths); - WebAuthenticationDetails webDetails = new WebAuthenticationDetails(httpRequest); - ((AbstractAuthenticationToken) finalAuthentication).setDetails(webDetails); - RangerAuthenticationProvider authenticationProvider = new RangerAuthenticationProvider(); - authenticationProvider.setSsoEnabled(ssoEnabled); - Authentication authentication = authenticationProvider.authenticate(finalAuthentication); - authentication = getGrantedAuthority(authentication); - SecurityContextHolder.getContext().setAuthentication(authentication); - } - - filterChain.doFilter(servletRequest,httpServletResponse); - } - // if the token is not valid then redirect to knox sso - else { - if (isWebUserAgent(userAgent)) { - String ssourl = null; - String ajaxRequestHeader = httpRequest.getHeader("X-Requested-With"); - if ("XMLHttpRequest".equals(ajaxRequestHeader)) { - ssourl = constructLoginURLForApi(httpRequest, xForwardedURL); - if (LOG.isDebugEnabled()) { - LOG.debug("ajaxRequestHeader redirectUrl = " + ssourl); - } - httpServletResponse.setHeader("X-Frame-Options", "DENY"); - httpServletResponse.setStatus(RangerConstants.SC_AUTHENTICATION_TIMEOUT); - httpServletResponse.setHeader("X-Rngr-Redirect-Url", ssourl); - } else { - ssourl = RestUtil.constructRedirectURL(httpRequest, authenticationProviderUrl, xForwardedURL, originalUrlQueryParam); - if (LOG.isDebugEnabled()) { - LOG.debug("SSO URL = " + ssourl); - } - httpServletResponse.sendRedirect(ssourl); - } - } else { - filterChain.doFilter(servletRequest,httpServletResponse); - } - } - } catch (ParseException e) { - LOG.warn("Unable to parse the JWT token", e); - } - } - // if the jwt token is not available then redirect it to knox sso - else { - if (isWebUserAgent(userAgent)) { - String ssourl = null; - String ajaxRequestHeader = httpRequest.getHeader("X-Requested-With"); - if ("XMLHttpRequest".equals(ajaxRequestHeader)) { - ssourl = constructLoginURLForApi(httpRequest, xForwardedURL); - if (LOG.isDebugEnabled()) { - LOG.debug("ajaxRequestHeader redirectUrl = " + ssourl); - } - httpServletResponse.setHeader("X-Frame-Options", "DENY"); - httpServletResponse.setStatus(RangerConstants.SC_AUTHENTICATION_TIMEOUT); - httpServletResponse.setHeader("X-Rngr-Redirect-Url", ssourl); - } else { - ssourl = RestUtil.constructRedirectURL(httpRequest, authenticationProviderUrl, xForwardedURL, originalUrlQueryParam); - if (LOG.isDebugEnabled()) { - LOG.debug("SSO URL = " + ssourl); - } - httpServletResponse.sendRedirect(ssourl); - } - } else { - filterChain.doFilter(servletRequest,httpServletResponse); - } - } - } - //if property is not loaded or is already authenticated then proceed further with next filter - else { - filterChain.doFilter(servletRequest, servletResponse); - } - } else if(ssoEnabled && ((HttpServletRequest) servletRequest).getRequestURI().contains(RestUtil.LOCAL_LOGIN_URL) && isWebUserAgent(userAgent) && isAuthenticated()){ - //If already there's an active session with sso and user want's to switch to local login(i.e without sso) then it won't be navigated to local login - // In this scenario the user has to use separate browser - String url = ((HttpServletRequest) servletRequest).getRequestURI().replace(RestUtil.LOCAL_LOGIN_URL+"/", ""); - url = url.replace(RestUtil.LOCAL_LOGIN_URL, ""); - LOG.warn("There is an active session and if you want local login to ranger, try this on a separate browser"); - ((HttpServletResponse)servletResponse).sendRedirect(url); - } else if (!ssoEnabled && ((HttpServletRequest) servletRequest).getRequestURI().contains(RestUtil.LOCAL_LOGIN_URL) && !isAuthenticated() && - ( isWebUserAgent(userAgent) || isBrowserAgent(userAgent))) { - // if sso is not enabled and request has locallogin then need to redirect user to the login page. - String url = ((HttpServletRequest) servletRequest).getRequestURI().replace(RestUtil.LOCAL_LOGIN_URL+"/", ""); - url = url.replace(RestUtil.LOCAL_LOGIN_URL, "login.jsp"); - // invalidating session - if (LOG.isDebugEnabled()) { - LOG.debug("Request does not have any authentication and contains local login url redirecting to login page."); - } - ((HttpServletRequest) servletRequest).getSession().invalidate(); - - ((HttpServletResponse)servletResponse).sendRedirect(url); - } - //if sso is not enable or the request is not from browser then proceed further with next filter - else { - filterChain.doFilter(servletRequest, servletResponse); - } - } - - private Authentication getGrantedAuthority(Authentication authentication) { - UsernamePasswordAuthenticationToken result=null; - if(authentication!=null && authentication.isAuthenticated()){ - final List grantedAuths=getAuthorities(authentication.getName().toString()); - final UserDetails userDetails = new User(authentication.getName().toString(), authentication.getCredentials().toString(),grantedAuths); - result = new UsernamePasswordAuthenticationToken(userDetails,authentication.getCredentials(),grantedAuths); - result.setDetails(authentication.getDetails()); - return result; - } - return authentication; - } - - private List getAuthorities(String username) { - Collection roleList=userMgr.getRolesByLoginId(username); - final List grantedAuths = new ArrayList<>(); - for(String role:roleList){ - grantedAuths.add(new SimpleGrantedAuthority(role)); - } - return grantedAuths; - } - - private boolean isWebUserAgent(String userAgent) { - boolean isWeb = false; - if (jwtProperties != null) { - String userAgentList[] = jwtProperties.getUserAgentList(); - if(userAgentList != null && userAgentList.length > 0){ - for(String ua : userAgentList){ - if(userAgent.toLowerCase().startsWith(ua.toLowerCase())){ - isWeb = true; - break; - } - } - } - } - return isWeb; - } - - private void loadJwtProperties() { - if (jwtProperties != null) { - authenticationProviderUrl = jwtProperties.getAuthenticationProviderUrl(); - publicKey = jwtProperties.getPublicKey(); - cookieName = jwtProperties.getCookieName(); - originalUrlQueryParam = jwtProperties.getOriginalUrlQueryParam(); - } - } - - /** - * Do not try to validate JWT if user already authenticated via other - * provider - * - * @return true, if JWT validation required - */ - private boolean isAuthenticated() { - Authentication existingAuth = SecurityContextHolder.getContext().getAuthentication(); - return !(!(existingAuth != null && existingAuth.isAuthenticated()) || existingAuth instanceof SSOAuthentication); - } - - /** - * Encapsulate the acquisition of the JWT token from HTTP cookies within the - * request. - * - * @param req - * servlet request to get the JWT token from - * @return serialized JWT token - */ - protected String getJWTFromCookie(HttpServletRequest req) { - String serializedJWT = null; - Cookie[] cookies = req.getCookies(); - if (cookies != null) { - for (Cookie cookie : cookies) { - if (cookieName != null && cookieName.equals(cookie.getName())) { - if (LOG.isDebugEnabled()) { - LOG.debug(cookieName + " cookie has been found and is being processed"); - } - serializedJWT = cookie.getValue(); - break; - } - } - } - return serializedJWT; - } - - /** - * This method provides a single method for validating the JWT for use in - * request processing. It provides for the override of specific aspects of - * this implementation through submethods used within but also allows for - * the override of the entire token validation algorithm. - * - * @param jwtToken - * the token to validate - * @return true if valid - */ - protected boolean validateToken(SignedJWT jwtToken) { - boolean sigValid = validateSignature(jwtToken); - if (!sigValid) { - LOG.warn("Signature of JWT token could not be verified. Please check the public key"); - return false; - } - - boolean expValid = validateExpiration(jwtToken); - if (!expValid) { - LOG.warn("Expiration time validation of JWT token failed."); - return false; - } - - boolean audiencesValid = validateAudiences(jwtToken); - if (!audiencesValid) { - LOG.warn("Audience validation of JWT token failed."); - return false; + public static final String JWT_EXPECTED_SIGALG = "ranger.sso.expected.sigalg"; + public static final String JWT_DEFAULT_SIGALG = "RS256"; + public static final String DEFAULT_BROWSER_USERAGENT = "ranger.default.browser-useragents"; + + private final SSOAuthenticationProperties jwtProperties; + + @Autowired + UserMgr userMgr; + + private String originalUrlQueryParam = "originalUrl"; + private String authenticationProviderUrl; + private RSAPublicKey publicKey; + private String cookieName = "hadoop-jwt"; + + @Inject + public RangerSSOAuthenticationFilter() { + jwtProperties = getJwtProperties(); + + loadJwtProperties(); + } + + public RangerSSOAuthenticationFilter(SSOAuthenticationProperties jwtProperties) { + this.jwtProperties = jwtProperties; + + loadJwtProperties(); + } + + public static RSAPublicKey parseRSAPublicKey(String pem) throws CertificateException, UnsupportedEncodingException, ServletException { + String pemHeader = "-----BEGIN CERTIFICATE-----\n"; + String pemFooter = "\n-----END CERTIFICATE-----"; + String fullPem = pemHeader + pem + pemFooter; + PublicKey key; + + try { + CertificateFactory fact = CertificateFactory.getInstance("X.509"); + ByteArrayInputStream is = new ByteArrayInputStream(fullPem.getBytes(StandardCharsets.UTF_8)); + X509Certificate cer = (X509Certificate) fact.generateCertificate(is); + + key = cer.getPublicKey(); + } catch (CertificateException ce) { + String message; + + if (pem.startsWith(pemHeader)) { + message = "CertificateException - be sure not to include PEM header and footer in the PEM configuration element."; + } else { + message = "CertificateException - PEM may be corrupt"; + } + + throw new ServletException(message, ce); + } + return (RSAPublicKey) key; + } + + @Override + public void init(FilterConfig filterConfig) throws ServletException { + } + + /* + * doFilter of RangerSSOAuthenticationFilter is the first in the filter list so in this it check for the request + * if the request is from browser, doesn't contain local login and sso is enabled then it process the request against knox sso + * else if it's ssoenable and the request is with local login string then it show's the appropriate msg + * else if ssoenable is false then it contiunes with further filters as it was before sso + */ + @Override + public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { + HttpServletRequest httpRequest = (HttpServletRequest) servletRequest; + String xForwardedURL = RestUtil.constructForwardableURL(httpRequest); + + if (httpRequest.getRequestedSessionId() != null && !httpRequest.isRequestedSessionIdValid()) { + synchronized (httpRequest.getServletContext()) { + if (httpRequest.getServletContext().getAttribute(httpRequest.getRequestedSessionId()) != null && "locallogin".equals(httpRequest.getServletContext().getAttribute(httpRequest.getRequestedSessionId()).toString())) { + httpRequest.getSession().setAttribute("locallogin", "true"); + httpRequest.getServletContext().removeAttribute(httpRequest.getRequestedSessionId()); + } + } + } + + RangerSecurityContext context = RangerContextHolder.getSecurityContext(); + UserSessionBase session = context != null ? context.getUserSession() : null; + boolean ssoEnabled = session != null ? session.isSSOEnabled() : PropertiesUtil.getBooleanProperty("ranger.sso.enabled", false); + String userAgent = httpRequest.getHeader("User-Agent"); + + if (httpRequest.getSession() != null) { + if (httpRequest.getSession().getAttribute("locallogin") != null) { + servletRequest.setAttribute("ssoEnabled", false); + + filterChain.doFilter(servletRequest, servletResponse); + + return; + } + } + + //If sso is enable and request is not for local login and is from browser then it will go inside and try for knox sso authentication + if (ssoEnabled && !httpRequest.getRequestURI().contains(RestUtil.LOCAL_LOGIN_URL)) { + //if jwt properties are loaded and is current not authenticated then it will go for sso authentication + //Note : Need to remove !isAuthenticated() after knoxsso solve the bug from cross-origin script + if (jwtProperties != null && !isAuthenticated()) { + HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; + String serializedJWT = getJWTFromCookie(httpRequest); + + // if we get the hadoop-jwt token from the cookies then will process it further + if (serializedJWT != null) { + SignedJWT jwtToken; + + try { + jwtToken = SignedJWT.parse(serializedJWT); + + boolean valid = validateToken(jwtToken); + + //if the public key provide is correct and also token is not expired the process token + if (valid) { + String userName = jwtToken.getJWTClaimsSet().getSubject(); + + LOG.info("SSO login user : {}", userName); + + String rangerLdapDefaultRole = PropertiesUtil.getProperty("ranger.ldap.default.role", "ROLE_USER"); + + //if we get the userName from the token then log into ranger using the same user + if (userName != null && !userName.trim().isEmpty()) { + final List grantedAuths = new ArrayList<>(); + + grantedAuths.add(new SimpleGrantedAuthority(rangerLdapDefaultRole)); + + final UserDetails principal = new User(userName, "", grantedAuths); + final AbstractAuthenticationToken finalAuthentication = new UsernamePasswordAuthenticationToken(principal, "", grantedAuths); + WebAuthenticationDetails webDetails = new WebAuthenticationDetails(httpRequest); + + finalAuthentication.setDetails(webDetails); + + RangerAuthenticationProvider authenticationProvider = new RangerAuthenticationProvider(); + + authenticationProvider.setSsoEnabled(ssoEnabled); + + Authentication authentication = authenticationProvider.authenticate(finalAuthentication); + + authentication = getGrantedAuthority(authentication); + + SecurityContextHolder.getContext().setAuthentication(authentication); + } + + filterChain.doFilter(servletRequest, httpServletResponse); + } + // if the token is not valid then redirect to knox sso + else { + if (isWebUserAgent(userAgent)) { + String ssourl; + String ajaxRequestHeader = httpRequest.getHeader("X-Requested-With"); + + if ("XMLHttpRequest".equals(ajaxRequestHeader)) { + ssourl = constructLoginURLForApi(httpRequest, xForwardedURL); + + LOG.debug("ajaxRequestHeader redirectUrl = {}", ssourl); + + httpServletResponse.setHeader("X-Frame-Options", "DENY"); + httpServletResponse.setStatus(RangerConstants.SC_AUTHENTICATION_TIMEOUT); + httpServletResponse.setHeader("X-Rngr-Redirect-Url", ssourl); + } else { + ssourl = RestUtil.constructRedirectURL(httpRequest, authenticationProviderUrl, xForwardedURL, originalUrlQueryParam); + + LOG.debug("SSO URL = {}", ssourl); + + httpServletResponse.sendRedirect(ssourl); + } + } else { + filterChain.doFilter(servletRequest, httpServletResponse); + } + } + } catch (ParseException e) { + LOG.warn("Unable to parse the JWT token", e); + } + } + // if the jwt token is not available then redirect it to knox sso + else { + if (isWebUserAgent(userAgent)) { + String ssourl; + String ajaxRequestHeader = httpRequest.getHeader("X-Requested-With"); + + if ("XMLHttpRequest".equals(ajaxRequestHeader)) { + ssourl = constructLoginURLForApi(httpRequest, xForwardedURL); + + LOG.debug("ajaxRequestHeader redirectUrl = {}", ssourl); + + httpServletResponse.setHeader("X-Frame-Options", "DENY"); + httpServletResponse.setStatus(RangerConstants.SC_AUTHENTICATION_TIMEOUT); + httpServletResponse.setHeader("X-Rngr-Redirect-Url", ssourl); + } else { + ssourl = RestUtil.constructRedirectURL(httpRequest, authenticationProviderUrl, xForwardedURL, originalUrlQueryParam); + + LOG.debug("SSO URL = {}", ssourl); + + httpServletResponse.sendRedirect(ssourl); + } + } else { + filterChain.doFilter(servletRequest, httpServletResponse); + } + } + } + //if property is not loaded or is already authenticated then proceed further with next filter + else { + filterChain.doFilter(servletRequest, servletResponse); + } + } else if (ssoEnabled && ((HttpServletRequest) servletRequest).getRequestURI().contains(RestUtil.LOCAL_LOGIN_URL) && isWebUserAgent(userAgent) && isAuthenticated()) { + //If already there's an active session with sso and user want's to switch to local login(i.e without sso) then it won't be navigated to local login + // In this scenario the user has to use separate browser + String url = ((HttpServletRequest) servletRequest).getRequestURI().replace(RestUtil.LOCAL_LOGIN_URL + "/", ""); + + url = url.replace(RestUtil.LOCAL_LOGIN_URL, ""); + + LOG.warn("There is an active session and if you want local login to ranger, try this on a separate browser"); + + ((HttpServletResponse) servletResponse).sendRedirect(url); + } else if (!ssoEnabled && ((HttpServletRequest) servletRequest).getRequestURI().contains(RestUtil.LOCAL_LOGIN_URL) && !isAuthenticated() && (isWebUserAgent(userAgent) || isBrowserAgent(userAgent))) { + // if sso is not enabled and request has locallogin then need to redirect user to the login page. + String url = ((HttpServletRequest) servletRequest).getRequestURI().replace(RestUtil.LOCAL_LOGIN_URL + "/", ""); + + url = url.replace(RestUtil.LOCAL_LOGIN_URL, "login.jsp"); + + // invalidating session + LOG.debug("Request does not have any authentication and contains local login url redirecting to login page."); + + ((HttpServletRequest) servletRequest).getSession().invalidate(); + + ((HttpServletResponse) servletResponse).sendRedirect(url); + } else { //if sso is not enable or the request is not from browser then proceed further with next filter + filterChain.doFilter(servletRequest, servletResponse); } + } + + @Override + public void destroy() { + } + + public SSOAuthenticationProperties getJwtProperties() { + String providerUrl = PropertiesUtil.getProperty(JWT_AUTH_PROVIDER_URL); + + if (providerUrl != null && PropertiesUtil.getBooleanProperty("ranger.sso.enabled", false)) { + SSOAuthenticationProperties jwtProperties = new SSOAuthenticationProperties(); + String publicKeyPath = PropertiesUtil.getProperty(JWT_PUBLIC_KEY); + + if (publicKeyPath == null) { + LOG.error("Public key pem not specified for SSO auth provider {}. SSO auth will be disabled.", providerUrl); + + return null; + } + + jwtProperties.setAuthenticationProviderUrl(providerUrl); + jwtProperties.setCookieName(PropertiesUtil.getProperty(JWT_COOKIE_NAME, JWT_COOKIE_NAME_DEFAULT)); + jwtProperties.setOriginalUrlQueryParam(PropertiesUtil.getProperty(JWT_ORIGINAL_URL_QUERY_PARAM, JWT_ORIGINAL_URL_QUERY_PARAM_DEFAULT)); + + String defaultUserAgent = PropertiesUtil.getProperty(DEFAULT_BROWSER_USERAGENT); + String userAgent = PropertiesUtil.getProperty(BROWSER_USERAGENT); + + if (userAgent != null && !userAgent.isEmpty()) { + jwtProperties.setUserAgentList(userAgent.split(",")); + } else if (defaultUserAgent != null && !defaultUserAgent.isEmpty()) { + userAgent = defaultUserAgent; + + jwtProperties.setUserAgentList(userAgent.split(",")); + } + + String audiences = PropertiesUtil.getProperty(JWT_AUDIENCES); - return true; - } - - /** - * Verify the signature of the JWT token in this method. This method depends - * on the public key that was established during init based upon the - * provisioned public key. Override this method in subclasses in order to - * customize the signature verification behavior. - * - * @param jwtToken - * the token that contains the signature to be validated - * @return valid true if signature verifies successfully; false otherwise - */ - protected boolean validateSignature(SignedJWT jwtToken) { - boolean valid = false; - if (JWSObject.State.SIGNED == jwtToken.getState()) { - if (LOG.isDebugEnabled()) { - LOG.debug("SSO token is in a SIGNED state"); - } - if (jwtToken.getSignature() != null) { - if (LOG.isDebugEnabled()) { - LOG.debug("SSO token signature is not null"); - } - try { - JWSVerifier verifier = new RSASSAVerifier(publicKey); - if (jwtToken.verify(verifier)) { - valid = true; - if (LOG.isDebugEnabled()) { - LOG.debug("SSO token has been successfully verified"); - } - } else { - LOG.warn("SSO signature verification failed.Please check the public key"); - } - } catch (JOSEException je) { - LOG.warn("Error while validating signature", je); - }catch(Exception e){ - LOG.warn("Error while validating signature", e); - } - } - - // Now check that the signature algorithm was as expected - if (valid) { - String receivedSigAlg = jwtToken.getHeader().getAlgorithm().getName(); - if (!receivedSigAlg.equals(jwtProperties.getExpectedSigAlg())) { - valid = false; - } - } - } - return valid; - } - - /** - * Validate that the expiration time of the JWT token has not been violated. - * If it has then throw an AuthenticationException. Override this method in - * subclasses in order to customize the expiration validation behavior. - * - * @param jwtToken - * the token that contains the expiration date to validate - * @return valid true if the token has not expired; false otherwise - */ - protected boolean validateExpiration(SignedJWT jwtToken) { - boolean valid = false; - try { - Date expires = jwtToken.getJWTClaimsSet().getExpirationTime(); - if (expires == null || new Date().before(expires)) { - if (LOG.isDebugEnabled()) { - LOG.debug("SSO token expiration date has been " + "successfully validated"); - } - valid = true; - } else { - LOG.warn("SSO expiration date validation failed."); - } - } catch (ParseException pe) { - LOG.warn("SSO expiration date validation failed.", pe); - } - return valid; - } - - protected boolean validateAudiences(SignedJWT jwtToken) { - boolean valid = false; - - if (jwtProperties.getAudiences().isEmpty()) { - // if there were no expected audiences configured then just - // consider any audience acceptable - valid = true; - } else { - try { - List tokenAudienceList = jwtToken.getJWTClaimsSet().getAudience(); - // if any of the configured audiences is found then consider it acceptable - if (tokenAudienceList != null) { - for (String aud : tokenAudienceList) { - if (jwtProperties.getAudiences().contains(aud)) { - LOG.debug("Audience claim has been validated."); - valid = true; - break; - } - } - } - } catch (ParseException pe) { - LOG.warn("Audience validation failed.", pe); - } - } - - return valid; - } - - @Override - public void destroy() { - } - - public SSOAuthenticationProperties getJwtProperties() { - String providerUrl = PropertiesUtil.getProperty(JWT_AUTH_PROVIDER_URL); - if (providerUrl != null && PropertiesUtil.getBooleanProperty("ranger.sso.enabled", false)) { - SSOAuthenticationProperties jwtProperties = new SSOAuthenticationProperties(); - String publicKeyPath = PropertiesUtil.getProperty(JWT_PUBLIC_KEY); - if (publicKeyPath == null) { - LOG.error("Public key pem not specified for SSO auth provider {}. SSO auth will be disabled.",providerUrl); - return null; - } - jwtProperties.setAuthenticationProviderUrl(providerUrl); - jwtProperties.setCookieName(PropertiesUtil.getProperty(JWT_COOKIE_NAME, JWT_COOKIE_NAME_DEFAULT)); - jwtProperties.setOriginalUrlQueryParam(PropertiesUtil.getProperty(JWT_ORIGINAL_URL_QUERY_PARAM, JWT_ORIGINAL_URL_QUERY_PARAM_DEFAULT)); - String defaultUserAgent = PropertiesUtil.getProperty(DEFAULT_BROWSER_USERAGENT); - String userAgent = PropertiesUtil.getProperty(BROWSER_USERAGENT); - if (userAgent != null && !userAgent.isEmpty()) { - jwtProperties.setUserAgentList(userAgent.split(",")); - } else if (defaultUserAgent != null && !defaultUserAgent.isEmpty()) { - userAgent = defaultUserAgent; - jwtProperties.setUserAgentList(userAgent.split(",")); - } - String audiences = PropertiesUtil.getProperty(JWT_AUDIENCES); if (audiences != null && !audiences.isEmpty()) { jwtProperties.setAudiences(Arrays.asList(audiences.split(","))); } + jwtProperties.setExpectedSigAlg(PropertiesUtil.getProperty(JWT_EXPECTED_SIGALG, JWT_DEFAULT_SIGALG)); - try { - RSAPublicKey publicKey = parseRSAPublicKey(publicKeyPath); - jwtProperties.setPublicKey(publicKey); - } catch (IOException e) { - LOG.error("Unable to read public certificate file. JWT auth will be disabled.",e); - } catch (CertificateException e) { - LOG.error("Unable to parse public certificate file. JWT auth will be disabled.",e); - } catch (ServletException e) { - LOG.error("ServletException while processing the properties",e); - } - return jwtProperties; - } else { - return null; - } - } - - /* - * public static RSAPublicKey getPublicKeyFromFile(String filePath) throws - * IOException, CertificateException { - * FileUtils.readFileToString(new File(filePath)); - * getPublicKeyFromString(pemString); } - */ - - public static RSAPublicKey parseRSAPublicKey(String pem) - throws CertificateException, UnsupportedEncodingException, - ServletException { - String PEM_HEADER = "-----BEGIN CERTIFICATE-----\n"; - String PEM_FOOTER = "\n-----END CERTIFICATE-----"; - String fullPem = PEM_HEADER + pem + PEM_FOOTER; - PublicKey key = null; - try { - CertificateFactory fact = CertificateFactory.getInstance("X.509"); - ByteArrayInputStream is = new ByteArrayInputStream(fullPem.getBytes("UTF8")); - X509Certificate cer = (X509Certificate) fact.generateCertificate(is); - key = cer.getPublicKey(); - } catch (CertificateException ce) { - String message = null; - if (pem.startsWith(PEM_HEADER)) { - message = "CertificateException - be sure not to include PEM header " + "and footer in the PEM configuration element."; - } else { - message = "CertificateException - PEM may be corrupt"; - } - throw new ServletException(message, ce); - } catch (UnsupportedEncodingException uee) { - throw new ServletException(uee); - } - return (RSAPublicKey) key; - } - /** - * Create the redirect URL to be used for authentication of the user in the absence - * of a JWT token within the incoming request. - * - * @param request - * for getting the original request URL - * @return url to use as login url for redirect - */ - protected String constructLoginURLForApi(HttpServletRequest request, String xForwardedURL) { - String delimiter = "?"; - if (authenticationProviderUrl.contains("?")) { - delimiter = "&"; + + try { + RSAPublicKey publicKey = parseRSAPublicKey(publicKeyPath); + + jwtProperties.setPublicKey(publicKey); + } catch (IOException e) { + LOG.error("Unable to read public certificate file. JWT auth will be disabled.", e); + } catch (CertificateException e) { + LOG.error("Unable to parse public certificate file. JWT auth will be disabled.", e); + } catch (ServletException e) { + LOG.error("ServletException while processing the properties", e); + } + + return jwtProperties; + } else { + return null; + } + } + + /** + * Encapsulate the acquisition of the JWT token from HTTP cookies within the + * request. + * + * @param req servlet request to get the JWT token from + * @return serialized JWT token + */ + protected String getJWTFromCookie(HttpServletRequest req) { + String serializedJWT = null; + Cookie[] cookies = req.getCookies(); + + if (cookies != null) { + for (Cookie cookie : cookies) { + if (cookieName != null && cookieName.equals(cookie.getName())) { + LOG.debug("{} cookie has been found and is being processed", cookieName); + + serializedJWT = cookie.getValue(); + break; + } + } + } + + return serializedJWT; + } + + /** + * This method provides a single method for validating the JWT for use in + * request processing. It provides for the override of specific aspects of + * this implementation through submethods used within but also allows for + * the override of the entire token validation algorithm. + * + * @param jwtToken the token to validate + * @return true if valid + */ + protected boolean validateToken(SignedJWT jwtToken) { + boolean sigValid = validateSignature(jwtToken); + + if (!sigValid) { + LOG.warn("Signature of JWT token could not be verified. Please check the public key"); + + return false; + } + + boolean expValid = validateExpiration(jwtToken); + + if (!expValid) { + LOG.warn("Expiration time validation of JWT token failed."); + + return false; + } + + boolean audiencesValid = validateAudiences(jwtToken); + + if (!audiencesValid) { + LOG.warn("Audience validation of JWT token failed."); + + return false; + } + + return true; + } + + /** + * Verify the signature of the JWT token in this method. This method depends + * on the public key that was established during init based upon the + * provisioned public key. Override this method in subclasses in order to + * customize the signature verification behavior. + * + * @param jwtToken the token that contains the signature to be validated + * @return valid true if signature verifies successfully; false otherwise + */ + protected boolean validateSignature(SignedJWT jwtToken) { + boolean valid = false; + + if (JWSObject.State.SIGNED == jwtToken.getState()) { + LOG.debug("SSO token is in a SIGNED state"); + + if (jwtToken.getSignature() != null) { + LOG.debug("SSO token signature is not null"); + + try { + JWSVerifier verifier = new RSASSAVerifier(publicKey); + + if (jwtToken.verify(verifier)) { + valid = true; + + LOG.debug("SSO token has been successfully verified"); + } else { + LOG.warn("SSO signature verification failed.Please check the public key"); + } + } catch (Exception e) { + LOG.warn("Error while validating signature", e); } - String loginURL = authenticationProviderUrl + delimiter + originalUrlQueryParam + "="; - if (StringUtils.trimToNull(xForwardedURL) != null) { - loginURL += xForwardedURL; - } else { - loginURL += request.getRequestURL(); + } + + // Now check that the signature algorithm was as expected + if (valid) { + String receivedSigAlg = jwtToken.getHeader().getAlgorithm().getName(); + + if (!receivedSigAlg.equals(jwtProperties.getExpectedSigAlg())) { + valid = false; } - if (StringUtils.isNotEmpty(request.getRequestURI()) && request.getRequestURI().length() > 1) { - loginURL = loginURL.replace(request.getRequestURI(), "/"); + } + } + + return valid; + } + + /** + * Validate that the expiration time of the JWT token has not been violated. + * If it has then throw an AuthenticationException. Override this method in + * subclasses in order to customize the expiration validation behavior. + * + * @param jwtToken the token that contains the expiration date to validate + * @return valid true if the token has not expired; false otherwise + */ + protected boolean validateExpiration(SignedJWT jwtToken) { + boolean valid = false; + + try { + Date expires = jwtToken.getJWTClaimsSet().getExpirationTime(); + + if (expires == null || new Date().before(expires)) { + LOG.debug("SSO token expiration date has been successfully validated"); + + valid = true; + } else { + LOG.warn("SSO expiration date validation failed."); + } + } catch (ParseException pe) { + LOG.warn("SSO expiration date validation failed.", pe); + } + + return valid; + } + + protected boolean validateAudiences(SignedJWT jwtToken) { + boolean valid = false; + + if (jwtProperties.getAudiences().isEmpty()) { + // if there were no expected audiences configured then just + // consider any audience acceptable + valid = true; + } else { + try { + List tokenAudienceList = jwtToken.getJWTClaimsSet().getAudience(); + + // if any of the configured audiences is found then consider it acceptable + if (tokenAudienceList != null) { + for (String aud : tokenAudienceList) { + if (jwtProperties.getAudiences().contains(aud)) { + LOG.debug("Audience claim has been validated."); + + valid = true; + + break; + } + } } - return loginURL; + } catch (ParseException pe) { + LOG.warn("Audience validation failed.", pe); + } + } + + return valid; + } + + /** + * Create the redirect URL to be used for authentication of the user in the absence + * of a JWT token within the incoming request. + * + * @param request for getting the original request URL + * @return url to use as login url for redirect + */ + protected String constructLoginURLForApi(HttpServletRequest request, String xForwardedURL) { + String delimiter = "?"; + + if (authenticationProviderUrl.contains("?")) { + delimiter = "&"; } + String loginURL = authenticationProviderUrl + delimiter + originalUrlQueryParam + "="; + + if (StringUtils.trimToNull(xForwardedURL) != null) { + loginURL += xForwardedURL; + } else { + loginURL += request.getRequestURL(); + } + + if (StringUtils.isNotEmpty(request.getRequestURI()) && request.getRequestURI().length() > 1) { + loginURL = loginURL.replace(request.getRequestURI(), "/"); + } + + return loginURL; + } protected boolean isBrowserAgent(String userAgent) { - boolean isWeb = false; - String agents = PropertiesUtil.getProperty("ranger.krb.browser-useragents-regex", RangerCSRFPreventionFilter.BROWSER_USER_AGENTS_DEFAULT); + boolean isWeb = false; + String agents = PropertiesUtil.getProperty("ranger.krb.browser-useragents-regex", RangerCSRFPreventionFilter.BROWSER_USER_AGENTS_DEFAULT); + if (agents == null) { agents = RangerCSRFPreventionFilter.BROWSER_USER_AGENTS_DEFAULT; } + String[] browserUserAgents = agents.split(","); + if (browserUserAgents.length > 0 && userAgent != null) { for (String ua : browserUserAgents) { if (userAgent.toLowerCase().startsWith(ua.toLowerCase())) { @@ -605,7 +587,79 @@ protected boolean isBrowserAgent(String userAgent) { } } } + + return isWeb; + } + + private Authentication getGrantedAuthority(Authentication authentication) { + if (authentication != null && authentication.isAuthenticated()) { + final List grantedAuths = getAuthorities(authentication.getName()); + final UserDetails userDetails = new User(authentication.getName(), authentication.getCredentials().toString(), grantedAuths); + UsernamePasswordAuthenticationToken result = new UsernamePasswordAuthenticationToken(userDetails, authentication.getCredentials(), grantedAuths); + + result.setDetails(authentication.getDetails()); + + return result; + } + + return authentication; + } + + private List getAuthorities(String username) { + Collection roleList = userMgr.getRolesByLoginId(username); + final List grantedAuths = new ArrayList<>(); + + for (String role : roleList) { + grantedAuths.add(new SimpleGrantedAuthority(role)); + } + + return grantedAuths; + } + + /* + * public static RSAPublicKey getPublicKeyFromFile(String filePath) throws + * IOException, CertificateException { + * FileUtils.readFileToString(new File(filePath)); + * getPublicKeyFromString(pemString); } + */ + + private boolean isWebUserAgent(String userAgent) { + boolean isWeb = false; + + if (jwtProperties != null) { + String[] userAgentList = jwtProperties.getUserAgentList(); + + if (userAgentList != null) { + for (String ua : userAgentList) { + if (userAgent.toLowerCase().startsWith(ua.toLowerCase())) { + isWeb = true; + break; + } + } + } + } + return isWeb; } + private void loadJwtProperties() { + if (jwtProperties != null) { + authenticationProviderUrl = jwtProperties.getAuthenticationProviderUrl(); + publicKey = jwtProperties.getPublicKey(); + cookieName = jwtProperties.getCookieName(); + originalUrlQueryParam = jwtProperties.getOriginalUrlQueryParam(); + } + } + + /** + * Do not try to validate JWT if user already authenticated via other + * provider + * + * @return true, if JWT validation required + */ + private boolean isAuthenticated() { + Authentication existingAuth = SecurityContextHolder.getContext().getAuthentication(); + + return !(!(existingAuth != null && existingAuth.isAuthenticated()) || existingAuth instanceof SSOAuthentication); + } } diff --git a/security-admin/src/main/java/org/apache/ranger/security/web/filter/RangerSecurityContextFormationFilter.java b/security-admin/src/main/java/org/apache/ranger/security/web/filter/RangerSecurityContextFormationFilter.java index 71d7af0d11..9951960e52 100644 --- a/security-admin/src/main/java/org/apache/ranger/security/web/filter/RangerSecurityContextFormationFilter.java +++ b/security-admin/src/main/java/org/apache/ranger/security/web/filter/RangerSecurityContextFormationFilter.java @@ -17,21 +17,11 @@ * under the License. */ - /** +/** * */ package org.apache.ranger.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 javax.servlet.http.HttpSession; - import org.apache.ranger.biz.SessionMgr; import org.apache.ranger.biz.XUserMgr; import org.apache.ranger.common.GUIDUtil; @@ -49,135 +39,146 @@ import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.web.filter.GenericFilterBean; -public class RangerSecurityContextFormationFilter extends GenericFilterBean { +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 javax.servlet.http.HttpSession; - public static final String AKA_SC_SESSION_KEY = "AKA_SECURITY_CONTEXT"; - public static final String USER_AGENT = "User-Agent"; +import java.io.IOException; + +public class RangerSecurityContextFormationFilter extends GenericFilterBean { + public static final String AKA_SC_SESSION_KEY = "AKA_SECURITY_CONTEXT"; + public static final String USER_AGENT = "User-Agent"; - @Autowired - SessionMgr sessionMgr; + @Autowired + SessionMgr sessionMgr; - @Autowired - HTTPUtil httpUtil; + @Autowired + HTTPUtil httpUtil; - @Autowired + @Autowired XUserMgr xUserMgr; - @Autowired - GUIDUtil guidUtil; - - String testIP = null; - - public RangerSecurityContextFormationFilter() { - 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)) { - HttpServletRequest httpRequest = (HttpServletRequest) request; - HttpSession httpSession = httpRequest.getSession(false); - - // [1]get the context from session - RangerSecurityContext context = null; - if(httpSession!=null){ - context=(RangerSecurityContext) httpSession.getAttribute(AKA_SC_SESSION_KEY); - } - int clientTimeOffset = 0; - if (context == null) { - context = new RangerSecurityContext(); - httpSession.setAttribute(AKA_SC_SESSION_KEY, context); - } - String userAgent = httpRequest.getHeader(USER_AGENT); - 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.genGUID()); - requestContext.setRequestURL(httpRequest.getRequestURI()); - - requestContext.setClientTimeOffsetInMinute(clientTimeOffset); - context.setRequestContext(requestContext); - - RangerContextHolder.setSecurityContext(context); - int authType = getAuthType(httpRequest); - UserSessionBase userSession = sessionMgr.processSuccessLogin( - authType, userAgent, httpRequest); - - if (userSession != null) { - if (userSession.getClientTimeOffsetInMinute() == 0) { - userSession.setClientTimeOffsetInMinute(clientTimeOffset); - } - } - - context.setUserSession(userSession); - } - - setupAdminOpContext(request); - - HttpServletResponse res = (HttpServletResponse)response; - res.setHeader("Cache-Control", "no-cache, no-store, max-age=0, must-revalidate"); - res.setHeader("X-Frame-Options", "DENY" ); - res.setHeader("X-XSS-Protection", "1; mode=block"); - res.setHeader("Strict-Transport-Security", "max-age=31536000; includeSubDomains; preload"); - res.setHeader("Content-Security-Policy", "default-src 'none'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; connect-src 'self'; img-src 'self' data:; style-src 'self' 'unsafe-inline';font-src 'self'"); - res.setHeader("X-Permitted-Cross-Domain-Policies", "none"); - chain.doFilter(request, res); - - } finally { - // [4]remove context from thread-local - RangerContextHolder.resetSecurityContext(); - RangerContextHolder.resetOpContext(); - } - } - - private void setupAdminOpContext(ServletRequest request) { - Object attrCreatePrincipalsIfAbsent = request.getParameter("createPrincipalsIfAbsent"); - - if (attrCreatePrincipalsIfAbsent != null) { - RangerContextHolder.getOrCreateOpContext().setCreatePrincipalsIfAbsent(Boolean.parseBoolean(attrCreatePrincipalsIfAbsent.toString())); - } - } - - private int getAuthType(HttpServletRequest request) { - int authType; - Object ssoEnabledObj = request.getAttribute("ssoEnabled"); - Boolean ssoEnabled = ssoEnabledObj != null ? Boolean.valueOf(String.valueOf(ssoEnabledObj)) : PropertiesUtil.getBooleanProperty("ranger.sso.enabled", false); - - if (ssoEnabled) { - authType = XXAuthSession.AUTH_TYPE_SSO; - } else if (request.getAttribute("spnegoEnabled") != null && Boolean.valueOf(String.valueOf(request.getAttribute("spnegoEnabled")))){ - if (request.getAttribute("trustedProxyEnabled") != null && Boolean.valueOf(String.valueOf(request.getAttribute("trustedProxyEnabled")))) { - if (logger.isDebugEnabled()) { - logger.debug("Setting auth type as trusted proxy"); - } - authType = XXAuthSession.AUTH_TYPE_TRUSTED_PROXY; - } else { - authType = XXAuthSession.AUTH_TYPE_KERBEROS; - } - } else { - authType = XXAuthSession.AUTH_TYPE_PASSWORD; - } - return authType; - } + @Autowired + GUIDUtil guidUtil; + + String testIP; + + public RangerSecurityContextFormationFilter() { + 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)) { + HttpServletRequest httpRequest = (HttpServletRequest) request; + HttpSession httpSession = httpRequest.getSession(false); + + // [1]get the context from session + RangerSecurityContext context = null; + + if (httpSession != null) { + context = (RangerSecurityContext) httpSession.getAttribute(AKA_SC_SESSION_KEY); + } + + if (context == null) { + context = new RangerSecurityContext(); + + httpSession.setAttribute(AKA_SC_SESSION_KEY, context); + } + + String userAgent = httpRequest.getHeader(USER_AGENT); + int 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.genGUID()); + requestContext.setRequestURL(httpRequest.getRequestURI()); + requestContext.setClientTimeOffsetInMinute(clientTimeOffset); + + context.setRequestContext(requestContext); + + RangerContextHolder.setSecurityContext(context); + + int authType = getAuthType(httpRequest); + UserSessionBase userSession = sessionMgr.processSuccessLogin(authType, userAgent, httpRequest); + + if (userSession != null) { + if (userSession.getClientTimeOffsetInMinute() == 0) { + userSession.setClientTimeOffsetInMinute(clientTimeOffset); + } + } + + context.setUserSession(userSession); + } + + setupAdminOpContext(request); + + HttpServletResponse res = (HttpServletResponse) response; + + res.setHeader("Cache-Control", "no-cache, no-store, max-age=0, must-revalidate"); + res.setHeader("X-Frame-Options", "DENY"); + res.setHeader("X-XSS-Protection", "1; mode=block"); + res.setHeader("Strict-Transport-Security", "max-age=31536000; includeSubDomains; preload"); + res.setHeader("Content-Security-Policy", "default-src 'none'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; connect-src 'self'; img-src 'self' data:; style-src 'self' 'unsafe-inline';font-src 'self'"); + res.setHeader("X-Permitted-Cross-Domain-Policies", "none"); + + chain.doFilter(request, res); + } finally { + // [4]remove context from thread-local + RangerContextHolder.resetSecurityContext(); + RangerContextHolder.resetOpContext(); + } + } + + private void setupAdminOpContext(ServletRequest request) { + Object attrCreatePrincipalsIfAbsent = request.getParameter("createPrincipalsIfAbsent"); + + if (attrCreatePrincipalsIfAbsent != null) { + RangerContextHolder.getOrCreateOpContext().setCreatePrincipalsIfAbsent(Boolean.parseBoolean(attrCreatePrincipalsIfAbsent.toString())); + } + } + + private int getAuthType(HttpServletRequest request) { + int authType; + Object ssoEnabledObj = request.getAttribute("ssoEnabled"); + boolean ssoEnabled = ssoEnabledObj != null ? Boolean.parseBoolean(String.valueOf(ssoEnabledObj)) : PropertiesUtil.getBooleanProperty("ranger.sso.enabled", false); + + if (ssoEnabled) { + authType = XXAuthSession.AUTH_TYPE_SSO; + } else if (request.getAttribute("spnegoEnabled") != null && Boolean.parseBoolean(String.valueOf(request.getAttribute("spnegoEnabled")))) { + if (request.getAttribute("trustedProxyEnabled") != null && Boolean.parseBoolean(String.valueOf(request.getAttribute("trustedProxyEnabled")))) { + logger.debug("Setting auth type as trusted proxy"); + + authType = XXAuthSession.AUTH_TYPE_TRUSTED_PROXY; + } else { + authType = XXAuthSession.AUTH_TYPE_KERBEROS; + } + } else { + authType = XXAuthSession.AUTH_TYPE_PASSWORD; + } + + return authType; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/security/web/filter/RangerUsernamePasswordAuthenticationFilter.java b/security-admin/src/main/java/org/apache/ranger/security/web/filter/RangerUsernamePasswordAuthenticationFilter.java index c08e14f805..b3b5207425 100644 --- a/security-admin/src/main/java/org/apache/ranger/security/web/filter/RangerUsernamePasswordAuthenticationFilter.java +++ b/security-admin/src/main/java/org/apache/ranger/security/web/filter/RangerUsernamePasswordAuthenticationFilter.java @@ -17,7 +17,7 @@ * under the License. */ - /** +/** * */ package org.apache.ranger.security.web.filter; @@ -27,11 +27,8 @@ import org.springframework.security.web.authentication.RememberMeServices; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; -public class RangerUsernamePasswordAuthenticationFilter extends - UsernamePasswordAuthenticationFilter { - - private static final Logger LOG = LoggerFactory - .getLogger(RangerUsernamePasswordAuthenticationFilter.class); +public class RangerUsernamePasswordAuthenticationFilter extends UsernamePasswordAuthenticationFilter { + private static final Logger LOG = LoggerFactory.getLogger(RangerUsernamePasswordAuthenticationFilter.class); /* * (non-Javadoc) @@ -43,11 +40,10 @@ public class RangerUsernamePasswordAuthenticationFilter extends */ @Override public void setRememberMeServices(RememberMeServices rememberMeServices) { - if (LOG.isDebugEnabled()) { - LOG.debug("setRememberMeServices() enter: rememberMeServices=" - + rememberMeServices.toString()); - } - super.setRememberMeServices(rememberMeServices); - } + if (LOG.isDebugEnabled()) { + LOG.debug("setRememberMeServices() enter: rememberMeServices={}", rememberMeServices.toString()); + } + super.setRememberMeServices(rememberMeServices); + } } diff --git a/security-admin/src/main/java/org/apache/ranger/security/web/filter/SSOAuthentication.java b/security-admin/src/main/java/org/apache/ranger/security/web/filter/SSOAuthentication.java index 61f19f4783..696a55ff97 100644 --- a/security-admin/src/main/java/org/apache/ranger/security/web/filter/SSOAuthentication.java +++ b/security-admin/src/main/java/org/apache/ranger/security/web/filter/SSOAuthentication.java @@ -29,46 +29,45 @@ * Internal token which describes JWT authentication */ public class SSOAuthentication implements Authentication { + private final SignedJWT token; + private boolean authenticated; - private SignedJWT token; - private boolean authenticated = false; + public SSOAuthentication(SignedJWT token) { + this.token = token; + } - public SSOAuthentication(SignedJWT token) { - this.token = token; - } + @Override + public String getName() { + return null; + } - @Override - public SignedJWT getCredentials() { - return token; - } + @Override + public Collection getAuthorities() { + return null; + } - @Override - public Object getDetails() { - return null; - } + @Override + public SignedJWT getCredentials() { + return token; + } - @Override - public boolean isAuthenticated() { - return authenticated; - } + @Override + public Object getDetails() { + return null; + } - @Override - public void setAuthenticated(boolean authenticated) throws IllegalArgumentException { - this.authenticated = authenticated; - } + @Override + public Object getPrincipal() { + return null; + } - @Override - public String getName() { - return null; - } + @Override + public boolean isAuthenticated() { + return authenticated; + } - @Override - public Collection getAuthorities() { - return null; - } - - @Override - public Object getPrincipal() { - return null; - } + @Override + public void setAuthenticated(boolean authenticated) throws IllegalArgumentException { + this.authenticated = authenticated; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/security/web/filter/SSOAuthenticationProperties.java b/security-admin/src/main/java/org/apache/ranger/security/web/filter/SSOAuthenticationProperties.java index f9d1a408e6..088850a994 100644 --- a/security-admin/src/main/java/org/apache/ranger/security/web/filter/SSOAuthenticationProperties.java +++ b/security-admin/src/main/java/org/apache/ranger/security/web/filter/SSOAuthenticationProperties.java @@ -24,14 +24,13 @@ import java.util.List; public class SSOAuthenticationProperties { - - private String authenticationProviderUrl; + private String authenticationProviderUrl; private RSAPublicKey publicKey; - private String cookieName = "hadoop-jwt"; - private String originalUrlQueryParam; - private String[] userAgentList; - private List audiences = Collections.emptyList(); - private String expectedSigAlg; + private String cookieName = "hadoop-jwt"; + private String originalUrlQueryParam; + private String[] userAgentList; + private List audiences = Collections.emptyList(); + private String expectedSigAlg; public String getAuthenticationProviderUrl() { return authenticationProviderUrl; @@ -95,4 +94,3 @@ public void setExpectedSigAlg(String expectedSigAlg) { this.expectedSigAlg = expectedSigAlg; } } - diff --git a/security-admin/src/main/java/org/apache/ranger/service/AbstractBaseResourceService.java b/security-admin/src/main/java/org/apache/ranger/service/AbstractBaseResourceService.java index d2ddbd0e76..020e1dff51 100644 --- a/security-admin/src/main/java/org/apache/ranger/service/AbstractBaseResourceService.java +++ b/security-admin/src/main/java/org/apache/ranger/service/AbstractBaseResourceService.java @@ -255,7 +255,7 @@ public V createResource(V viewBaseBean) { // object security if (!objectSecurityHandler.hasAccess(resource, - Permission.permissionType.CREATE)) { + Permission.PermissionType.CREATE)) { throw restErrorUtil.create403RESTException(getResourceName() + " access denied. classType=" + resource.getMyClassType() + ", className=" + resource.getClass().getName() @@ -304,7 +304,7 @@ public V readResource(Long id) { private V readResource(T resource) { // object security if (!objectSecurityHandler.hasAccess(resource, - Permission.permissionType.READ)) { + Permission.PermissionType.READ)) { throw restErrorUtil.create403RESTException(getResourceName() + " access denied. classType=" + resource.getMyClassType() @@ -352,7 +352,7 @@ public V updateResource(V viewBaseBean) { // object security if (!objectSecurityHandler.hasAccess(resource, - Permission.permissionType.UPDATE)) { + Permission.PermissionType.UPDATE)) { throw restErrorUtil.create403RESTException(getResourceName() + " access denied. classType=" + resource.getMyClassType() + ", className=" + resource.getClass().getName() @@ -393,7 +393,7 @@ public boolean deleteResource(Long id) { // object security if (!objectSecurityHandler.hasAccess(resource, - Permission.permissionType.DELETE)) { + Permission.PermissionType.DELETE)) { // throw 401 logger.debug("OBJECT SECURITY"); } diff --git a/security-admin/src/main/java/org/apache/ranger/solr/SolrAccessAuditsService.java b/security-admin/src/main/java/org/apache/ranger/solr/SolrAccessAuditsService.java index 861f5db97d..f3d6fde874 100644 --- a/security-admin/src/main/java/org/apache/ranger/solr/SolrAccessAuditsService.java +++ b/security-admin/src/main/java/org/apache/ranger/solr/SolrAccessAuditsService.java @@ -19,10 +19,6 @@ package org.apache.ranger.solr; -import java.io.UnsupportedEncodingException; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; import org.apache.ranger.AccessAuditsService; import org.apache.ranger.audit.provider.MiscUtil; import org.apache.ranger.common.MessageEnums; @@ -30,10 +26,10 @@ import org.apache.ranger.common.SearchCriteria; import org.apache.ranger.entity.XXService; import org.apache.ranger.entity.XXServiceDef; +import org.apache.ranger.plugin.util.JsonUtilsV2; import org.apache.ranger.view.VXAccessAudit; import org.apache.ranger.view.VXAccessAuditList; import org.apache.ranger.view.VXLong; -import org.apache.ranger.plugin.util.JsonUtilsV2; import org.apache.solr.client.solrj.SolrClient; import org.apache.solr.client.solrj.response.QueryResponse; import org.apache.solr.common.SolrDocument; @@ -44,237 +40,264 @@ import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Service; +import java.io.UnsupportedEncodingException; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + @Service @Scope("singleton") public class SolrAccessAuditsService extends AccessAuditsService { - private static final Logger LOGGER = LoggerFactory.getLogger(SolrAccessAuditsService.class); - - @Autowired - SolrMgr solrMgr; - - @Autowired - SolrUtil solrUtil; - - public VXAccessAuditList searchXAccessAudits(SearchCriteria searchCriteria) { - - // Make call to Solr - SolrClient solrClient = solrMgr.getSolrClient(); - final boolean hiveQueryVisibility = PropertiesUtil.getBooleanProperty("ranger.audit.hive.query.visibility", true); - if (solrClient == null) { - LOGGER.warn("Solr client is null, so not running the query."); - throw restErrorUtil.createRESTException( - "Error connecting to search engine", - MessageEnums.ERROR_SYSTEM); - } - List xAccessAuditList = new ArrayList(); - - Map paramList = searchCriteria.getParamList(); - - Object eventIdObj = paramList.get("eventId"); - if (eventIdObj != null) { - paramList.put("id", eventIdObj.toString()); - } - - updateUserExclusion(paramList); - - QueryResponse response = solrUtil.searchResources(searchCriteria, - searchFields, sortFields, solrClient); - SolrDocumentList docs = response.getResults(); - for (int i = 0; i < docs.size(); i++) { - SolrDocument doc = docs.get(i); - VXAccessAudit vXAccessAudit = populateViewBean(doc); - if (vXAccessAudit != null) { - if (!hiveQueryVisibility && "hive".equalsIgnoreCase(vXAccessAudit.getServiceType())) { - vXAccessAudit.setRequestData(null); - } - else if("hive".equalsIgnoreCase(vXAccessAudit.getServiceType()) && ("grant".equalsIgnoreCase(vXAccessAudit.getAccessType()) || "revoke".equalsIgnoreCase(vXAccessAudit.getAccessType()))){ - try { - if (vXAccessAudit.getRequestData() != null) { - vXAccessAudit.setRequestData(java.net.URLDecoder.decode(vXAccessAudit.getRequestData(), "UTF-8")); - } else { - LOGGER.warn("Error in request data of audit from solr. AuditData: " + vXAccessAudit.toString()); - } - } catch (UnsupportedEncodingException e) { - LOGGER.warn("Error while encoding request data"); - } - } + private static final Logger LOGGER = LoggerFactory.getLogger(SolrAccessAuditsService.class); + + @Autowired + SolrMgr solrMgr; + + @Autowired + SolrUtil solrUtil; + + public VXAccessAuditList searchXAccessAudits(SearchCriteria searchCriteria) { + // Make call to Solr + SolrClient solrClient = solrMgr.getSolrClient(); + final boolean hiveQueryVisibility = PropertiesUtil.getBooleanProperty("ranger.audit.hive.query.visibility", true); + + if (solrClient == null) { + LOGGER.warn("Solr client is null, so not running the query."); + + throw restErrorUtil.createRESTException("Error connecting to search engine", MessageEnums.ERROR_SYSTEM); + } + + List xAccessAuditList = new ArrayList<>(); + Map paramList = searchCriteria.getParamList(); + Object eventIdObj = paramList.get("eventId"); + + if (eventIdObj != null) { + paramList.put("id", eventIdObj.toString()); + } + + updateUserExclusion(paramList); + + QueryResponse response = solrUtil.searchResources(searchCriteria, searchFields, sortFields, solrClient); + SolrDocumentList docs = response.getResults(); + + for (SolrDocument doc : docs) { + VXAccessAudit vXAccessAudit = populateViewBean(doc); + + if (vXAccessAudit != null) { + if (!hiveQueryVisibility && "hive".equalsIgnoreCase(vXAccessAudit.getServiceType())) { + vXAccessAudit.setRequestData(null); + } else if ("hive".equalsIgnoreCase(vXAccessAudit.getServiceType()) && ("grant".equalsIgnoreCase(vXAccessAudit.getAccessType()) || "revoke".equalsIgnoreCase(vXAccessAudit.getAccessType()))) { + try { + if (vXAccessAudit.getRequestData() != null) { + vXAccessAudit.setRequestData(java.net.URLDecoder.decode(vXAccessAudit.getRequestData(), "UTF-8")); + } else { + LOGGER.warn("Error in request data of audit from solr. AuditData: {}", vXAccessAudit); } - xAccessAuditList.add(vXAccessAudit); - } - - VXAccessAuditList returnList = new VXAccessAuditList(); - returnList.setPageSize(searchCriteria.getMaxRows()); - returnList.setResultSize(docs.size()); - returnList.setTotalCount((int) docs.getNumFound()); - returnList.setStartIndex((int) docs.getStart()); - returnList.setVXAccessAudits(xAccessAuditList); - return returnList; - } - - /** - * @param doc - * @return - */ - private VXAccessAudit populateViewBean(SolrDocument doc) { - VXAccessAudit accessAudit = new VXAccessAudit(); - - Object value = null; - if(LOGGER.isDebugEnabled()) { - LOGGER.debug("doc=" + doc.toString()); - } - - value = doc.getFieldValue("id"); - if (value != null) { - // TODO: Converting ID to hashcode for now - accessAudit.setId((long) value.hashCode()); - accessAudit.setEventId(value.toString()); - } - - value = doc.getFieldValue("cluster"); - if (value != null) { - accessAudit.setClusterName(value.toString()); - } - - value = doc.getFieldValue("zoneName"); - if (value != null) { - accessAudit.setZoneName(value.toString()); - } - - value = doc.getFieldValue("agentHost"); - if (value != null) { - accessAudit.setAgentHost(value.toString()); - } - - value = doc.getFieldValue("policyVersion"); - if (value != null) { - accessAudit.setPolicyVersion(MiscUtil.toLong(value)); - } - - value = doc.getFieldValue("access"); - if (value != null) { - accessAudit.setAccessType(value.toString()); - } - - value = doc.getFieldValue("enforcer"); - if (value != null) { - accessAudit.setAclEnforcer(value.toString()); - } - value = doc.getFieldValue("agent"); - if (value != null) { - accessAudit.setAgentId(value.toString()); - } - value = doc.getFieldValue("repo"); - if (value != null) { - accessAudit.setRepoName(value.toString()); - XXService xxService = daoManager.getXXService().findByName(accessAudit.getRepoName()); - - if(xxService != null) { - accessAudit.setRepoDisplayName(xxService.getDisplayName()); - } - } - value = doc.getFieldValue("sess"); - if (value != null) { - accessAudit.setSessionId(value.toString()); - } - value = doc.getFieldValue("reqUser"); - if (value != null) { - accessAudit.setRequestUser(value.toString()); - } - value = doc.getFieldValue("reqData"); - if (value != null) { - accessAudit.setRequestData(value.toString()); - } - value = doc.getFieldValue("resource"); - if (value != null) { - accessAudit.setResourcePath(value.toString()); - } - value = doc.getFieldValue("cliIP"); - if (value != null) { - accessAudit.setClientIP(value.toString()); - } - value = doc.getFieldValue("logType"); - //if (value != null) { - // TODO: Need to see what logType maps to in UI -// accessAudit.setAuditType(solrUtil.toInt(value)); - //} - value = doc.getFieldValue("result"); - if (value != null) { - accessAudit.setAccessResult(MiscUtil.toInt(value)); - } - value = doc.getFieldValue("policy"); - if (value != null) { - accessAudit.setPolicyId(MiscUtil.toLong(value)); - } - value = doc.getFieldValue("repoType"); - if (value != null) { - accessAudit.setRepoType(MiscUtil.toInt(value)); - XXServiceDef xServiceDef = daoManager.getXXServiceDef().getById((long) accessAudit.getRepoType()); - if (xServiceDef != null) { - accessAudit.setServiceType(xServiceDef.getName()); - accessAudit.setServiceTypeDisplayName(xServiceDef.getDisplayName()); - } - } - value = doc.getFieldValue("resType"); - if (value != null) { - accessAudit.setResourceType(value.toString()); - } - value = doc.getFieldValue("reason"); - if (value != null) { - accessAudit.setResultReason(value.toString()); - } - value = doc.getFieldValue("action"); - if (value != null) { - accessAudit.setAction(value.toString()); - } - value = doc.getFieldValue("evtTime"); - if (value != null) { - accessAudit.setEventTime(MiscUtil.toLocalDate(value)); - } - value = doc.getFieldValue("seq_num"); - if (value != null) { - accessAudit.setSequenceNumber(MiscUtil.toLong(value)); - } - value = doc.getFieldValue("event_count"); - if (value != null) { - accessAudit.setEventCount(MiscUtil.toLong(value)); - } - value = doc.getFieldValue("event_dur_ms"); - if (value != null) { - accessAudit.setEventDuration(MiscUtil.toLong(value)); - } - value = doc.getFieldValue("tags"); - if (value != null) { - accessAudit.setTags(value.toString()); - } - value = doc.getFieldValue("datasets"); - if (value != null) { - try { - accessAudit.setDatasets(JsonUtilsV2.nonSerializableObjToJson(value)); - } catch (Exception e) { - LOGGER.warn("Failed to convert datasets to json", e); - } - } - value = doc.getFieldValue("projects"); - if (value != null) { - try { - accessAudit.setProjects(JsonUtilsV2.nonSerializableObjToJson(value)); - } catch (Exception e) { - LOGGER.warn("Failed to convert projects to json", e); - } - } - return accessAudit; - } - - /** - * @param searchCriteria - * @return - */ - public VXLong getXAccessAuditSearchCount(SearchCriteria searchCriteria) { - long count = 100; - - VXLong vXLong = new VXLong(); - vXLong.setValue(count); - return vXLong; - } + } catch (UnsupportedEncodingException e) { + LOGGER.warn("Error while encoding request data"); + } + } + } + + xAccessAuditList.add(vXAccessAudit); + } + + VXAccessAuditList returnList = new VXAccessAuditList(); + + returnList.setPageSize(searchCriteria.getMaxRows()); + returnList.setResultSize(docs.size()); + returnList.setTotalCount((int) docs.getNumFound()); + returnList.setStartIndex((int) docs.getStart()); + returnList.setVXAccessAudits(xAccessAuditList); + + return returnList; + } + + /** + * @param searchCriteria + * @return + */ + public VXLong getXAccessAuditSearchCount(SearchCriteria searchCriteria) { + long count = 100; + VXLong vXLong = new VXLong(); + + vXLong.setValue(count); + + return vXLong; + } + + /** + * @param doc + * @return + */ + private VXAccessAudit populateViewBean(SolrDocument doc) { + LOGGER.debug("doc={}", doc); + + VXAccessAudit accessAudit = new VXAccessAudit(); + + Object value = doc.getFieldValue("id"); + if (value != null) { + // TODO: Converting ID to hashcode for now + accessAudit.setId((long) value.hashCode()); + accessAudit.setEventId(value.toString()); + } + + value = doc.getFieldValue("cluster"); + if (value != null) { + accessAudit.setClusterName(value.toString()); + } + + value = doc.getFieldValue("zoneName"); + if (value != null) { + accessAudit.setZoneName(value.toString()); + } + + value = doc.getFieldValue("agentHost"); + if (value != null) { + accessAudit.setAgentHost(value.toString()); + } + + value = doc.getFieldValue("policyVersion"); + if (value != null) { + accessAudit.setPolicyVersion(MiscUtil.toLong(value)); + } + + value = doc.getFieldValue("access"); + if (value != null) { + accessAudit.setAccessType(value.toString()); + } + + value = doc.getFieldValue("enforcer"); + if (value != null) { + accessAudit.setAclEnforcer(value.toString()); + } + + value = doc.getFieldValue("agent"); + if (value != null) { + accessAudit.setAgentId(value.toString()); + } + + value = doc.getFieldValue("repo"); + if (value != null) { + accessAudit.setRepoName(value.toString()); + XXService xxService = daoManager.getXXService().findByName(accessAudit.getRepoName()); + + if (xxService != null) { + accessAudit.setRepoDisplayName(xxService.getDisplayName()); + } + } + + value = doc.getFieldValue("sess"); + if (value != null) { + accessAudit.setSessionId(value.toString()); + } + + value = doc.getFieldValue("reqUser"); + if (value != null) { + accessAudit.setRequestUser(value.toString()); + } + + value = doc.getFieldValue("reqData"); + if (value != null) { + accessAudit.setRequestData(value.toString()); + } + + value = doc.getFieldValue("resource"); + if (value != null) { + accessAudit.setResourcePath(value.toString()); + } + + value = doc.getFieldValue("cliIP"); + if (value != null) { + accessAudit.setClientIP(value.toString()); + } + + value = doc.getFieldValue("logType"); + //if (value != null) { + // TODO: Need to see what logType maps to in UI + // accessAudit.setAuditType(solrUtil.toInt(value)); + //} + + value = doc.getFieldValue("result"); + if (value != null) { + accessAudit.setAccessResult(MiscUtil.toInt(value)); + } + + value = doc.getFieldValue("policy"); + if (value != null) { + accessAudit.setPolicyId(MiscUtil.toLong(value)); + } + + value = doc.getFieldValue("repoType"); + if (value != null) { + accessAudit.setRepoType(MiscUtil.toInt(value)); + + XXServiceDef xServiceDef = daoManager.getXXServiceDef().getById((long) accessAudit.getRepoType()); + + if (xServiceDef != null) { + accessAudit.setServiceType(xServiceDef.getName()); + accessAudit.setServiceTypeDisplayName(xServiceDef.getDisplayName()); + } + } + + value = doc.getFieldValue("resType"); + if (value != null) { + accessAudit.setResourceType(value.toString()); + } + + value = doc.getFieldValue("reason"); + if (value != null) { + accessAudit.setResultReason(value.toString()); + } + + value = doc.getFieldValue("action"); + if (value != null) { + accessAudit.setAction(value.toString()); + } + + value = doc.getFieldValue("evtTime"); + if (value != null) { + accessAudit.setEventTime(MiscUtil.toLocalDate(value)); + } + + value = doc.getFieldValue("seq_num"); + if (value != null) { + accessAudit.setSequenceNumber(MiscUtil.toLong(value)); + } + + value = doc.getFieldValue("event_count"); + if (value != null) { + accessAudit.setEventCount(MiscUtil.toLong(value)); + } + + value = doc.getFieldValue("event_dur_ms"); + if (value != null) { + accessAudit.setEventDuration(MiscUtil.toLong(value)); + } + + value = doc.getFieldValue("tags"); + if (value != null) { + accessAudit.setTags(value.toString()); + } + + value = doc.getFieldValue("datasets"); + if (value != null) { + try { + accessAudit.setDatasets(JsonUtilsV2.nonSerializableObjToJson(value)); + } catch (Exception e) { + LOGGER.warn("Failed to convert datasets to json", e); + } + } + + value = doc.getFieldValue("projects"); + if (value != null) { + try { + accessAudit.setProjects(JsonUtilsV2.nonSerializableObjToJson(value)); + } catch (Exception e) { + LOGGER.warn("Failed to convert projects to json", e); + } + } + return accessAudit; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/solr/SolrMgr.java b/security-admin/src/main/java/org/apache/ranger/solr/SolrMgr.java index b3aea129ea..76d7cd50c1 100644 --- a/security-admin/src/main/java/org/apache/ranger/solr/SolrMgr.java +++ b/security-admin/src/main/java/org/apache/ranger/solr/SolrMgr.java @@ -19,10 +19,6 @@ package org.apache.ranger.solr; -import java.io.IOException; -import java.security.PrivilegedExceptionAction; -import java.util.*; - import org.apache.ranger.biz.RangerBizUtil; import org.apache.ranger.common.PropertiesUtil; import org.apache.ranger.solr.krb.InMemoryJAASConfiguration; @@ -46,45 +42,114 @@ import javax.annotation.PreDestroy; import javax.security.auth.login.LoginException; +import java.io.IOException; +import java.security.PrivilegedExceptionAction; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Date; +import java.util.List; +import java.util.Optional; +import java.util.Properties; + /** * This class initializes Solr - * */ @Component public class SolrMgr { - private static final Logger logger = LoggerFactory.getLogger(SolrMgr.class); - @Autowired - RangerBizUtil rangerBizUtil; + public static final String DEFAULT_COLLECTION_NAME = "ranger_audits"; - static final Object lock = new Object(); + static final Object lock = new Object(); + static final String SOLR_URLS_PROP = "ranger.audit.solr.urls"; + static final String SOLR_ZK_HOSTS = "ranger.audit.solr.zookeepers"; + static final String SOLR_COLLECTION_NAME = "ranger.audit.solr.collection.name"; + static final String PROP_JAVA_SECURITY_AUTH_LOGIN_CONFIG = "java.security.auth.login.config"; - SolrClient solrClient = null; - Date lastConnectTime = null; - volatile boolean initDone = false; - private volatile KerberosUser kerberosUser = null; + @Autowired + RangerBizUtil rangerBizUtil; - final static String SOLR_URLS_PROP = "ranger.audit.solr.urls"; - final static String SOLR_ZK_HOSTS = "ranger.audit.solr.zookeepers"; - final static String SOLR_COLLECTION_NAME = "ranger.audit.solr.collection.name"; - final static String PROP_JAVA_SECURITY_AUTH_LOGIN_CONFIG = "java.security.auth.login.config"; + SolrClient solrClient; + Date lastConnectTime; - public static final String DEFAULT_COLLECTION_NAME = "ranger_audits"; + volatile boolean initDone; + private volatile KerberosUser kerberosUser; public SolrMgr() { init(); } - void connect() { + public SolrClient getSolrClient() { + SolrClient me = solrClient; + + if (me != null) { + return me; + } else { + synchronized (this) { + me = connect(); + } + } + + return me; + } + + @PreDestroy + public void stop() { + logger.info("SolrMgr.stop() called.."); + + if (solrClient != null) { + try { + solrClient.close(); + } catch (IOException ioe) { + logger.error("Error while stopping solr!", ioe); + } finally { + solrClient = null; + } + } + + if (kerberosUser != null) { + try { + kerberosUser.logout(); + } catch (LoginException excp) { + logger.error("Error logging out keytab user", excp); + } finally { + kerberosUser = null; + } + } + } + + public QueryResponse queryToSolr(final QueryRequest req) throws Exception { + final QueryResponse ret; + + try { + final PrivilegedExceptionAction action = () -> req.process(solrClient); + + if (kerberosUser != null) { + // execute the privileged action as the given keytab user + final KerberosAction kerberosAction = new KerberosAction<>(kerberosUser, action, logger); + + ret = kerberosAction.execute(); + } else { + ret = action.run(); + } + } catch (Exception e) { + throw e; + } + + return ret; + } + + SolrClient connect() { if (!initDone) { synchronized (lock) { if (!initDone) { if ("solr".equalsIgnoreCase(rangerBizUtil.getAuditDBType())) { String zkHosts = PropertiesUtil.getProperty(SOLR_ZK_HOSTS); + if (zkHosts == null) { zkHosts = PropertiesUtil.getProperty("ranger.audit.solr.zookeeper"); } + if (zkHosts == null) { zkHosts = PropertiesUtil.getProperty("ranger.solr.zookeeper"); } @@ -95,137 +160,95 @@ void connect() { // Try with url solrURL = PropertiesUtil.getProperty("ranger.audit.solr.url"); } + if (solrURL == null) { // Let's try older property name solrURL = PropertiesUtil.getProperty("ranger.solr.url"); } - if (zkHosts != null && !"".equals(zkHosts.trim()) && !"none".equalsIgnoreCase(zkHosts.trim())) { + if (zkHosts != null && !zkHosts.trim().isEmpty() && !"none".equalsIgnoreCase(zkHosts.trim())) { zkHosts = zkHosts.trim(); + String collectionName = PropertiesUtil.getProperty(SOLR_COLLECTION_NAME); + if (collectionName == null || "none".equalsIgnoreCase(collectionName)) { collectionName = DEFAULT_COLLECTION_NAME; } - logger.info("Solr zkHosts=" + zkHosts + ", collectionName=" + collectionName); + logger.info("Solr zkHosts={}, collectionName={}", zkHosts, collectionName); try (Krb5HttpClientBuilder krbBuild = new Krb5HttpClientBuilder()) { // Instantiate - SolrHttpClientBuilder kb = krbBuild.getBuilder(); + SolrHttpClientBuilder kb = krbBuild.getBuilder(); + HttpClientUtil.setHttpClientBuilder(kb); - final List zkhosts = new ArrayList(Arrays.asList(zkHosts.split(","))); + + final List zkhosts = new ArrayList<>(Arrays.asList(zkHosts.split(","))); CloudSolrClient solrCloudClient = new CloudSolrClient.Builder(zkhosts, Optional.empty()).build(); + solrCloudClient.setDefaultCollection(collectionName); + solrClient = solrCloudClient; } catch (Throwable t) { - logger.error("Can't connect to Solr server. ZooKeepers=" + zkHosts + ", collection=" + collectionName, t); + logger.error("Can't connect to Solr server. ZooKeepers={}, collection={}", zkHosts, collectionName, t); } - } else { if (solrURL == null || solrURL.isEmpty() || "none".equalsIgnoreCase(solrURL)) { - logger.error("Solr ZKHosts and URL for Audit are empty. Please set property " + SOLR_ZK_HOSTS + " or " + SOLR_URLS_PROP); + logger.error("Solr ZKHosts and URL for Audit are empty. Please set property {} or {}", SOLR_ZK_HOSTS, SOLR_URLS_PROP); } else { try (Krb5HttpClientBuilder krbBuild = new Krb5HttpClientBuilder()) { - SolrHttpClientBuilder kb = krbBuild.getBuilder(); + SolrHttpClientBuilder kb = krbBuild.getBuilder(); + HttpClientUtil.setHttpClientBuilder(kb); + HttpSolrClient.Builder builder = new HttpSolrClient.Builder(); + builder.withBaseSolrUrl(solrURL); builder.allowCompression(true); builder.withConnectionTimeout(1000); + HttpSolrClient httpSolrClient = builder.build(); httpSolrClient.setRequestWriter(new BinaryRequestWriter()); + solrClient = httpSolrClient; initDone = true; } catch (Throwable t) { - logger.error("Can't connect to Solr server. URL=" + solrURL, t); + logger.error("Can't connect to Solr server. URL={}", solrURL, t); } } } } - } } } + + return solrClient; } private void init() { logger.info("==>SolrMgr.init()"); + Properties props = PropertiesUtil.getProps(); + try { // SolrJ requires "java.security.auth.login.config" property to be set to identify itself that it is kerberized. So using a dummy property for it // Acutal solrclient JAAS configs are read from the ranger-admin-site.xml in ranger admin config folder and set by InMemoryJAASConfiguration // Refer InMemoryJAASConfiguration doc for JAAS Configuration - if (System.getProperty(PROP_JAVA_SECURITY_AUTH_LOGIN_CONFIG) == null) { - System.setProperty(PROP_JAVA_SECURITY_AUTH_LOGIN_CONFIG, "/dev/null"); - } - logger.info("Loading SolrClient JAAS config from Ranger audit config if present..."); - InMemoryJAASConfiguration conf = InMemoryJAASConfiguration.init(props); - - KerberosUser kerberosUser = new KerberosJAASConfigUser("Client", conf); - - if (kerberosUser.getPrincipal() != null) { - this.kerberosUser = kerberosUser; - } - } catch (Exception e) { - logger.error("ERROR: Unable to load SolrClient JAAS config from ranger admin config file. Audit to Kerberized Solr will fail...", e); - } - logger.info("<==SolrMgr.init()"); - } - - public SolrClient getSolrClient() { - if (solrClient != null) { - return solrClient; - } else { - synchronized (this) { - connect(); - } - } - return solrClient; - } - - @PreDestroy - public void stop() { - logger.info("SolrMgr.stop() called.."); - - if (solrClient != null) { - try { - solrClient.close(); - } catch (IOException ioe) { - logger.error("Error while stopping solr!", ioe); - } finally { - solrClient = null; - } - } - - if (kerberosUser != null) { - try { - kerberosUser.logout(); - } catch (LoginException excp) { - logger.error("Error logging out keytab user", excp); - } finally { - kerberosUser = null; + if (System.getProperty(PROP_JAVA_SECURITY_AUTH_LOGIN_CONFIG) == null) { + System.setProperty(PROP_JAVA_SECURITY_AUTH_LOGIN_CONFIG, "/dev/null"); } - } - } - public QueryResponse queryToSolr(final QueryRequest req) throws Exception { - final QueryResponse ret; + logger.info("Loading SolrClient JAAS config from Ranger audit config if present..."); - try { - final PrivilegedExceptionAction action = () -> req.process(solrClient); + InMemoryJAASConfiguration conf = InMemoryJAASConfiguration.init(props); + KerberosUser kerberosUser = new KerberosJAASConfigUser("Client", conf); - if (kerberosUser != null) { - // execute the privileged action as the given keytab user - final KerberosAction kerberosAction = new KerberosAction(kerberosUser, action, logger); - - ret = (QueryResponse) kerberosAction.execute(); - } else { - ret = action.run(); + if (kerberosUser.getPrincipal() != null) { + this.kerberosUser = kerberosUser; } } catch (Exception e) { - throw e; + logger.error("ERROR: Unable to load SolrClient JAAS config from ranger admin config file. Audit to Kerberized Solr will fail...", e); } - - return ret; + logger.info("<==SolrMgr.init()"); } } diff --git a/security-admin/src/main/java/org/apache/ranger/solr/SolrUtil.java b/security-admin/src/main/java/org/apache/ranger/solr/SolrUtil.java index a5823364f5..714fa2cc44 100644 --- a/security-admin/src/main/java/org/apache/ranger/solr/SolrUtil.java +++ b/security-admin/src/main/java/org/apache/ranger/solr/SolrUtil.java @@ -19,20 +19,14 @@ package org.apache.ranger.solr; -import java.text.SimpleDateFormat; -import java.util.Collection; -import java.util.Date; -import java.util.List; -import java.util.TimeZone; - import org.apache.ranger.common.MessageEnums; import org.apache.ranger.common.PropertiesUtil; import org.apache.ranger.common.RESTErrorUtil; import org.apache.ranger.common.SearchCriteria; import org.apache.ranger.common.SearchField; +import org.apache.ranger.common.SearchField.SEARCH_TYPE; import org.apache.ranger.common.SortField; import org.apache.ranger.common.StringUtil; -import org.apache.ranger.common.SearchField.SEARCH_TYPE; import org.apache.solr.client.solrj.SolrClient; import org.apache.solr.client.solrj.SolrQuery; import org.apache.solr.client.solrj.SolrQuery.ORDER; @@ -45,33 +39,40 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; +import java.text.SimpleDateFormat; +import java.util.Collection; +import java.util.Date; +import java.util.List; +import java.util.TimeZone; + @Component public class SolrUtil { - private static final Logger logger = LoggerFactory.getLogger(SolrUtil.class); + private static final Logger logger = LoggerFactory.getLogger(SolrUtil.class); + + @Autowired + RESTErrorUtil restErrorUtil; - @Autowired - RESTErrorUtil restErrorUtil; + @Autowired + StringUtil stringUtil; - @Autowired - StringUtil stringUtil; + @Autowired + SolrMgr solrMgr; - @Autowired - SolrMgr solrMgr; + SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); - SimpleDateFormat dateFormat = new SimpleDateFormat( - "yyyy-MM-dd'T'HH:mm:ss'Z'"); + public SolrUtil() { + String timeZone = PropertiesUtil.getProperty("xa.solr.timezone"); - public SolrUtil() { - String timeZone = PropertiesUtil.getProperty("xa.solr.timezone"); - if (timeZone != null) { - logger.info("Setting timezone to " + timeZone); - try { - dateFormat.setTimeZone(TimeZone.getTimeZone(timeZone)); - } catch (Throwable t) { - logger.error("Error setting timezone. TimeZone = " + timeZone); - } - } - } + if (timeZone != null) { + logger.info("Setting timezone to {}", timeZone); + + try { + dateFormat.setTimeZone(TimeZone.getTimeZone(timeZone)); + } catch (Throwable t) { + logger.error("Error setting timezone. TimeZone = {}", timeZone); + } + } + } public QueryResponse runQuery(SolrClient solrClient, SolrQuery solrQuery) throws Throwable { if (solrQuery != null) { @@ -79,6 +80,7 @@ public QueryResponse runQuery(SolrClient solrClient, SolrQuery solrQuery) throws QueryRequest req = new QueryRequest(solrQuery, METHOD.POST); String username = PropertiesUtil.getProperty("ranger.solr.audit.user"); String password = PropertiesUtil.getProperty("ranger.solr.audit.user.password"); + if (username != null && password != null) { req.setBasicAuthCredentials(username, password); } @@ -89,218 +91,225 @@ public QueryResponse runQuery(SolrClient solrClient, SolrQuery solrQuery) throws throw e; } } + return null; } - public QueryResponse searchResources(SearchCriteria searchCriteria, - List searchFields, List sortFieldList, - SolrClient solrClient) { - SolrQuery query = new SolrQuery(); - query.setQuery("*:*"); - if (searchCriteria.getParamList() != null) { - // For now assuming there is only date field where range query will - // be done. If we there are more than one, then we should create a - // hashmap for each field name - Date fromDate = null; - Date toDate = null; - String dateFieldName = null; - - for (SearchField searchField : searchFields) { - Object paramValue = searchCriteria.getParamValue(searchField.getClientFieldName()); - if (paramValue == null || paramValue.toString().isEmpty()) { - continue; - } - String fieldName = searchField.getFieldName(); - if (paramValue instanceof Collection) { - String fq = orList(fieldName, (Collection) paramValue); - if (fq != null) { - query.addFilterQuery(fq); - } - } else if (searchField.getDataType() == SearchField.DATA_TYPE.DATE) { - if (!(paramValue instanceof Date)) { - logger.error("Search field is not a Java Date Object, paramValue = " + paramValue); - } else { - if (searchField.getSearchType() == SEARCH_TYPE.GREATER_EQUAL_THAN - || searchField.getSearchType() == SEARCH_TYPE.GREATER_THAN) { - fromDate = (Date) paramValue; - dateFieldName = fieldName; - } else if (searchField.getSearchType() == SEARCH_TYPE.LESS_EQUAL_THAN - || searchField.getSearchType() == SEARCH_TYPE.LESS_THAN) { - toDate = (Date) paramValue; - dateFieldName = fieldName; - } - } - } else if (searchField.getSearchType() == SEARCH_TYPE.GREATER_EQUAL_THAN - || searchField.getSearchType() == SEARCH_TYPE.GREATER_THAN - || searchField.getSearchType() == SEARCH_TYPE.LESS_EQUAL_THAN - || searchField.getSearchType() == SEARCH_TYPE.LESS_THAN) { //NOPMD - // TODO: Need to handle range here - } else { - String fq = setField(fieldName, paramValue); - - if (searchField.getSearchType() == SEARCH_TYPE.PARTIAL) { - fq = setFieldForPartialSearch(fieldName, paramValue); - } - - if (fq != null) { - query.addFilterQuery(fq); - } - } - } - if (fromDate != null || toDate != null) { - String fq = setDateRange(dateFieldName, fromDate, toDate); - if (fq != null) { - query.addFilterQuery(fq); - } - } - } - - setSortClause(searchCriteria, sortFieldList, query); - query.setStart(searchCriteria.getStartIndex()); - query.setRows(searchCriteria.getMaxRows()); - - // Fields to get - // query.setFields("myClassType", "id", "score", "globalId"); - if (logger.isDebugEnabled()) { - logger.debug("SOLR QUERY = " + query); + public QueryResponse searchResources(SearchCriteria searchCriteria, List searchFields, List sortFieldList, SolrClient solrClient) { + SolrQuery query = new SolrQuery(); + + query.setQuery("*:*"); + + if (searchCriteria.getParamList() != null) { + // For now assuming there is only date field where range query will + // be done. If we there are more than one, then we should create a + // hashmap for each field name + Date fromDate = null; + Date toDate = null; + String dateFieldName = null; + + for (SearchField searchField : searchFields) { + Object paramValue = searchCriteria.getParamValue(searchField.getClientFieldName()); + + if (paramValue == null || paramValue.toString().isEmpty()) { + continue; + } + + String fieldName = searchField.getFieldName(); + + if (paramValue instanceof Collection) { + String fq = orList(fieldName, (Collection) paramValue); + + if (fq != null) { + query.addFilterQuery(fq); + } + } else if (searchField.getDataType() == SearchField.DATA_TYPE.DATE) { + if (!(paramValue instanceof Date)) { + logger.error("Search field is not a Java Date Object, paramValue = {}", paramValue); + } else { + if (searchField.getSearchType() == SEARCH_TYPE.GREATER_EQUAL_THAN || searchField.getSearchType() == SEARCH_TYPE.GREATER_THAN) { + fromDate = (Date) paramValue; + dateFieldName = fieldName; + } else if (searchField.getSearchType() == SEARCH_TYPE.LESS_EQUAL_THAN || searchField.getSearchType() == SEARCH_TYPE.LESS_THAN) { + toDate = (Date) paramValue; + dateFieldName = fieldName; + } + } + } else if (searchField.getSearchType() == SEARCH_TYPE.GREATER_EQUAL_THAN || searchField.getSearchType() == SEARCH_TYPE.GREATER_THAN || searchField.getSearchType() == SEARCH_TYPE.LESS_EQUAL_THAN || searchField.getSearchType() == SEARCH_TYPE.LESS_THAN) { //NOPMD + // TODO: Need to handle range here + } else { + String fq = setField(fieldName, paramValue); + + if (searchField.getSearchType() == SEARCH_TYPE.PARTIAL) { + fq = setFieldForPartialSearch(fieldName, paramValue); + } + + if (fq != null) { + query.addFilterQuery(fq); + } + } + } + + if (fromDate != null || toDate != null) { + String fq = setDateRange(dateFieldName, fromDate, toDate); + + if (fq != null) { + query.addFilterQuery(fq); + } + } + } + + setSortClause(searchCriteria, sortFieldList, query); + + query.setStart(searchCriteria.getStartIndex()); + query.setRows(searchCriteria.getMaxRows()); + + // Fields to get + // query.setFields("myClassType", "id", "score", "globalId"); + logger.debug("SOLR QUERY = {}", query); + + QueryResponse response = null; + + try { + response = runQuery(solrClient, query); + } catch (Throwable e) { + logger.error("Error running solr query. Query = {}, response = {}", query, response); + + throw restErrorUtil.createRESTException("Error running solr query, please check solr configs. " + e.getMessage(), MessageEnums.ERROR_SYSTEM); + } + + if (response == null || response.getStatus() != 0) { + logger.error("Error running solr query. Query = {}, response = {}", query, response); + + throw restErrorUtil.createRESTException("Unable to connect to Audit store !!", MessageEnums.ERROR_SYSTEM); + } + + return response; + } + + public String setField(String fieldName, Object value) { + if (value == null || value.toString().trim().isEmpty()) { + return null; + } + + return fieldName + ":" + ClientUtils.escapeQueryChars(value.toString().trim().toLowerCase()); + } + + public String setDateRange(String fieldName, Date fromDate, Date toDate) { + String fromStr = "*"; + String toStr = "NOW"; + + if (fromDate != null) { + fromStr = dateFormat.format(fromDate); + } + + if (toDate != null) { + toStr = dateFormat.format(toDate); + } + + return fieldName + ":[" + fromStr + " TO " + toStr + "]"; + } + + public String orList(String fieldName, Collection valueList) { + if (valueList == null || valueList.isEmpty()) { + return null; + } + + String expr = ""; + int count = -1; + + for (Object value : valueList) { + count++; + + if (count > 0) { + expr += " OR "; + } + + expr += fieldName + ":" + ClientUtils.escapeQueryChars(value.toString().toLowerCase()); + } + + if (valueList.isEmpty()) { + return expr; + } else { + return "(" + expr + ")"; + } + } + + public String andList(String fieldName, Collection valueList) { + if (valueList == null || valueList.isEmpty()) { + return null; + } + + String expr = ""; + int count = -1; + + for (Object value : valueList) { + count++; + + if (count > 0) { + expr += " AND "; + } + + expr += fieldName + ":" + ClientUtils.escapeQueryChars(value.toString().toLowerCase()); + } + + if (valueList.isEmpty()) { + return expr; + } else { + return "(" + expr + ")"; + } + } + + public void setSortClause(SearchCriteria searchCriteria, List sortFields, SolrQuery query) { + // TODO: We are supporting single sort field only for now + 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; } - QueryResponse response = null; - try { - response = runQuery(solrClient, query); - } catch (Throwable e) { - logger.error("Error running solr query. Query = " + query - + ", response = " + response); - throw restErrorUtil.createRESTException( - "Error running solr query, please check solr configs. " - + e.getMessage(), MessageEnums.ERROR_SYSTEM); - } - if (response == null || response.getStatus() != 0) { - logger.error("Error running solr query. Query = " + query - + ", response = " + response); - throw restErrorUtil.createRESTException( - "Unable to connect to Audit store !!", - MessageEnums.ERROR_SYSTEM); - } - return response; - } - - private String setFieldForPartialSearch(String fieldName, Object value) { - if (value == null || value.toString().trim().length() == 0) { - return null; - } - return fieldName + ":*" + ClientUtils.escapeQueryChars(value.toString().trim().toLowerCase()) + "*"; - } - - public String setField(String fieldName, Object value) { - if (value == null || value.toString().trim().length() == 0) { - return null; - } - return fieldName - + ":" - + ClientUtils.escapeQueryChars(value.toString().trim() - .toLowerCase()); - } - - public String setDateRange(String fieldName, Date fromDate, Date toDate) { - String fromStr = "*"; - String toStr = "NOW"; - if (fromDate != null) { - fromStr = dateFormat.format(fromDate); - } - if (toDate != null) { - toStr = dateFormat.format(toDate); - } - return fieldName + ":[" + fromStr + " TO " + toStr + "]"; - } - - public String orList(String fieldName, Collection valueList) { - if (valueList == null || valueList.isEmpty()) { - return null; - } - String expr = ""; - int count = -1; - for (Object value : valueList) { - count++; - if (count > 0) { - expr += " OR "; - } - expr += fieldName - + ":" - + ClientUtils.escapeQueryChars(value.toString() - .toLowerCase()); - } - if (valueList.isEmpty()) { - return expr; - } else { - return "(" + expr + ")"; - } - - } - - public String andList(String fieldName, Collection valueList) { - if (valueList == null || valueList.isEmpty()) { - return null; - } - String expr = ""; - int count = -1; - for (Object value : valueList) { - count++; - if (count > 0) { - expr += " AND "; - } - expr += fieldName - + ":" - + ClientUtils.escapeQueryChars(value.toString() - .toLowerCase()); - } - if (valueList.isEmpty()) { - return expr; - } else { - return "(" + expr + ")"; - } - } - - public void setSortClause(SearchCriteria searchCriteria, - List sortFields, SolrQuery query) { - - // TODO: We are supporting single sort field only for now - 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(); - ORDER order = ORDER.asc; - if (sortType != null && "desc".equalsIgnoreCase(sortType)) { - order = ORDER.desc; - - } - query.addSort(querySortBy, order); - } - } + } + } + + if (querySortBy != null) { + // Add sort type + String sortType = searchCriteria.getSortType(); + ORDER order = ORDER.asc; + + if ("desc".equalsIgnoreCase(sortType)) { + order = ORDER.desc; + } + query.addSort(querySortBy, order); + } + } + + private String setFieldForPartialSearch(String fieldName, Object value) { + if (value == null || value.toString().trim().isEmpty()) { + return null; + } + + return fieldName + ":*" + ClientUtils.escapeQueryChars(value.toString().trim().toLowerCase()) + "*"; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/solr/krb/AbstractKerberosUser.java b/security-admin/src/main/java/org/apache/ranger/solr/krb/AbstractKerberosUser.java index 4831f76956..f4bfb5b3f9 100644 --- a/security-admin/src/main/java/org/apache/ranger/solr/krb/AbstractKerberosUser.java +++ b/security-admin/src/main/java/org/apache/ranger/solr/krb/AbstractKerberosUser.java @@ -27,6 +27,7 @@ import javax.security.auth.kerberos.KerberosTicket; import javax.security.auth.login.LoginContext; import javax.security.auth.login.LoginException; + import java.security.PrivilegedAction; import java.security.PrivilegedActionException; import java.security.PrivilegedExceptionAction; @@ -36,11 +37,9 @@ import java.util.concurrent.atomic.AtomicBoolean; public abstract class AbstractKerberosUser implements KerberosUser { - private static final Logger LOG = LoggerFactory.getLogger(AbstractKerberosUser.class); static final String DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss'Z'"; - /** * Percentage of the ticket window to use before we renew the TGT. */ @@ -48,7 +47,7 @@ public abstract class AbstractKerberosUser implements KerberosUser { protected final AtomicBoolean loggedIn = new AtomicBoolean(false); - protected Subject subject; + protected Subject subject; protected LoginContext loginContext; public AbstractKerberosUser() { @@ -68,29 +67,30 @@ public synchronized void login() throws LoginException { try { // If it's the first time ever calling login then we need to initialize a new context if (loginContext == null) { - if (LOG.isDebugEnabled()) { - LOG.debug("Initializing new login context..."); - } + LOG.debug("Initializing new login context..."); + if (this.subject == null) { // only create a new subject if a current one does not exist // other classes may be referencing an existing subject and replacing it may break functionality of those other classes after relogin this.subject = new Subject(); } + this.loginContext = createLoginContext(subject); } loginContext.login(); loggedIn.set(true); - LOG.info("Successful login for {}", new Object[]{getPrincipal()}); + + LOG.info("Successful login for {}", getPrincipal()); } catch (LoginException le) { LoginException loginException = new LoginException("Unable to login with " + getPrincipal() + " due to: " + le.getMessage()); + loginException.setStackTrace(le.getStackTrace()); + throw loginException; } } - protected abstract LoginContext createLoginContext(final Subject subject) throws LoginException; - /** * Performs a logout of the current user. * @@ -105,11 +105,12 @@ public synchronized void logout() throws LoginException { try { loginContext.logout(); loggedIn.set(false); - LOG.info("Successful logout for {}", new Object[]{getPrincipal()}); + + LOG.info("Successful logout for {}", getPrincipal()); loginContext = null; } catch (LoginException e) { - LOG.warn("Logout failed due to: " + e.getMessage()); + LOG.warn("Logout failed due to: {}", e.getMessage()); throw e; } } @@ -141,8 +142,7 @@ public T doAs(final PrivilegedAction action) throws IllegalStateException * @throws PrivilegedActionException if an exception is thrown from the action */ @Override - public T doAs(final PrivilegedExceptionAction action) - throws IllegalStateException, PrivilegedActionException { + public T doAs(final PrivilegedExceptionAction action) throws IllegalStateException, PrivilegedActionException { if (!isLoggedIn()) { throw new IllegalStateException("Must login before executing actions"); } @@ -158,25 +158,40 @@ public T doAs(final PrivilegedExceptionAction action) @Override public synchronized boolean checkTGTAndRelogin() throws LoginException { final KerberosTicket tgt = getTGT(); + if (tgt == null) { - if (LOG.isDebugEnabled()) { - LOG.debug("TGT was not found"); - } + LOG.debug("TGT was not found"); } if (tgt != null && System.currentTimeMillis() < getRefreshTime(tgt)) { - if (LOG.isDebugEnabled()) { - LOG.debug("TGT was found, but has not reached expiration window"); - } + LOG.debug("TGT was found, but has not reached expiration window"); + return false; } - LOG.info("Performing relogin for {}", new Object[]{getPrincipal()}); + LOG.info("Performing relogin for {}", getPrincipal()); + logout(); login(); + return true; } + /** + * @return true if this user is currently logged in, false otherwise + */ + @Override + public boolean isLoggedIn() { + return loggedIn.get(); + } + + @Override + public String toString() { + return "KerberosUser{" + "principal='" + getPrincipal() + '\'' + ", loggedIn=" + loggedIn + '}'; + } + + protected abstract LoginContext createLoginContext(Subject subject) throws LoginException; + /** * Get the Kerberos TGT. * @@ -206,9 +221,8 @@ private boolean isTGSPrincipal(final KerberosPrincipal principal) { } if (principal.getName().equals("krbtgt/" + principal.getRealm() + "@" + principal.getRealm())) { - if (LOG.isTraceEnabled()) { - LOG.trace("Found TGT principal: " + principal.getName()); - } + LOG.trace("Found TGT principal: {}", principal.getName()); + return true; } @@ -217,33 +231,17 @@ private boolean isTGSPrincipal(final KerberosPrincipal principal) { private long getRefreshTime(final KerberosTicket tgt) { long start = tgt.getStartTime().getTime(); - long end = tgt.getEndTime().getTime(); + long end = tgt.getEndTime().getTime(); if (LOG.isTraceEnabled()) { final SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT); - final String startDate = dateFormat.format(new Date(start)); - final String endDate = dateFormat.format(new Date(end)); - LOG.trace("TGT valid starting at: " + startDate); - LOG.trace("TGT expires at: " + endDate); + final String startDate = dateFormat.format(new Date(start)); + final String endDate = dateFormat.format(new Date(end)); + + LOG.trace("TGT valid starting at: {}", startDate); + LOG.trace("TGT expires at: {}", endDate); } return start + (long) ((end - start) * TICKET_RENEW_WINDOW); } - - /** - * @return true if this user is currently logged in, false otherwise - */ - @Override - public boolean isLoggedIn() { - return loggedIn.get(); - } - - @Override - public String toString() { - return "KerberosUser{" + - "principal='" + getPrincipal() + '\'' + - ", loggedIn=" + loggedIn + - '}'; - } } - diff --git a/security-admin/src/main/java/org/apache/ranger/solr/krb/InMemoryJAASConfiguration.java b/security-admin/src/main/java/org/apache/ranger/solr/krb/InMemoryJAASConfiguration.java index 46bf6c1ce1..d438974831 100644 --- a/security-admin/src/main/java/org/apache/ranger/solr/krb/InMemoryJAASConfiguration.java +++ b/security-admin/src/main/java/org/apache/ranger/solr/krb/InMemoryJAASConfiguration.java @@ -6,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + *

+ * http://www.apache.org/licenses/LICENSE-2.0 + *

* Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -23,6 +23,9 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import javax.security.auth.login.AppConfigurationEntry; +import javax.security.auth.login.Configuration; + import java.io.File; import java.io.FileInputStream; import java.io.IOException; @@ -37,9 +40,6 @@ import java.util.StringTokenizer; import java.util.TreeSet; -import javax.security.auth.login.AppConfigurationEntry; -import javax.security.auth.login.Configuration; - /** * InMemoryJAASConfiguration * @@ -55,7 +55,6 @@ * xasecure.audit.jaas.KafkaClient.option.serviceName = kafka * xasecure.audit.jaas.KafkaClient.option.keyTab = /etc/security/keytabs/kafka_client.keytab * xasecure.audit.jaas.KafkaClient.option.principal = kafka-client-1@EXAMPLE.COM - * xasecure.audit.jaas.MyClient.0.loginModuleName = com.sun.security.auth.module.Krb5LoginModule * xasecure.audit.jaas.MyClient.0.loginModuleControlFlag = required * xasecure.audit.jaas.MyClient.0.option.useKeyTab = true @@ -71,7 +70,6 @@ * xasecure.audit.jaas.MyClient.1.option.serviceName = kafka * xasecure.audit.jaas.MyClient.1.option.keyTab = /etc/security/keytabs/kafka_client.keytab * xasecure.audit.jaas.MyClient.1.option.principal = kafka-client-1@EXAMPLE.COM - * This will set the JAAS configuration - equivalent to the jaas.conf file entries: * KafkaClient { * com.sun.security.auth.module.Krb5LoginModule required @@ -116,24 +114,25 @@ */ public final class InMemoryJAASConfiguration extends Configuration { - private static final Logger LOG = LoggerFactory.getLogger(InMemoryJAASConfiguration.class); - public static final String JAAS_CONFIG_PREFIX_PARAM = "xasecure.audit.jaas."; public static final String JAAS_CONFIG_LOGIN_MODULE_NAME_PARAM = "loginModuleName"; public static final String JAAS_CONFIG_LOGIN_MODULE_CONTROL_FLAG_PARAM = "loginModuleControlFlag"; public static final String JAAS_CONFIG_LOGIN_OPTIONS_PREFIX = "option"; public static final String JAAS_PRINCIPAL_PROP = "principal"; - private final Configuration parent; private final Map> applicationConfigEntryMap = new HashMap<>(); + private InMemoryJAASConfiguration(Properties prop) { + parent = Configuration.getConfiguration(); + + initialize(prop); + } + public static InMemoryJAASConfiguration init(String propFile) throws Exception { - if (LOG.isDebugEnabled()) { - LOG.debug("==> InMemoryJAASConfiguration.init( {} ) ", propFile); - } + LOG.debug("==> InMemoryJAASConfiguration.init( {} ) ", propFile); - InMemoryJAASConfiguration ret = null; + InMemoryJAASConfiguration ret; InputStream in = null; try { @@ -165,21 +164,17 @@ public static InMemoryJAASConfiguration init(String propFile) throws Exception { } } - if (LOG.isDebugEnabled()) { - LOG.debug("<== InMemoryJAASConfiguration.init( {} ) ", propFile); - } + LOG.debug("<== InMemoryJAASConfiguration.init( {} ) ", propFile); return ret; } public static void init(org.apache.commons.configuration2.Configuration configuration) throws Exception { - if (LOG.isDebugEnabled()) { - LOG.debug("==> InMemoryJAASConfiguration.init()"); - } + LOG.debug("==> InMemoryJAASConfiguration.init()"); if (configuration != null && !configuration.isEmpty()) { - Properties properties = new Properties(); - Iterator iterator = configuration.getKeys(); + Properties properties = new Properties(); + Iterator iterator = configuration.getKeys(); while (iterator.hasNext()) { String key = iterator.next(); properties.put(key, configuration.getProperty(key)); @@ -189,36 +184,26 @@ public static void init(org.apache.commons.configuration2.Configuration configur throw new Exception("Failed to load JAAS application properties: configuration NULL or empty!"); } - if (LOG.isDebugEnabled()) { - LOG.debug("<== InMemoryJAASConfiguration.init()"); - } + LOG.debug("<== InMemoryJAASConfiguration.init()"); } public static InMemoryJAASConfiguration init(Properties properties) throws Exception { - if (LOG.isDebugEnabled()) { - LOG.debug("==> InMemoryJAASConfiguration.init()"); - } + LOG.debug("==> InMemoryJAASConfiguration.init()"); InMemoryJAASConfiguration ret = null; - if (properties != null && MapUtils.isNotEmpty(properties)) { + if (MapUtils.isNotEmpty(properties)) { ret = new InMemoryJAASConfiguration(properties); } else { throw new Exception("Failed to load JAAS application properties: properties NULL or empty!"); } - - if (LOG.isDebugEnabled()) { - LOG.debug("<== InMemoryJAASConfiguration.init()"); - } - + LOG.debug("<== InMemoryJAASConfiguration.init()"); return ret; } @Override public AppConfigurationEntry[] getAppConfigurationEntry(String name) { - if (LOG.isDebugEnabled()) { - LOG.debug("==> InMemoryJAASConfiguration.getAppConfigurationEntry( {} )", name); - } + LOG.debug("==> InMemoryJAASConfiguration.getAppConfigurationEntry( {} )", name); AppConfigurationEntry[] ret = null; @@ -229,33 +214,22 @@ public AppConfigurationEntry[] getAppConfigurationEntry(String name) { if (ret == null || ret.length == 0) { List retList = applicationConfigEntryMap.get(name); - if (retList != null && retList.size() > 0) { + if (retList != null && !retList.isEmpty()) { ret = retList.toArray(new AppConfigurationEntry[retList.size()]); } } - - if (LOG.isDebugEnabled()) { - LOG.debug("<== InMemoryJAASConfiguration.getAppConfigurationEntry( {} ) : {}", name, toString(ret)); - } + LOG.debug("<== InMemoryJAASConfiguration.getAppConfigurationEntry( {} ) : {}", name, toString(ret)); return ret; } - private InMemoryJAASConfiguration(Properties prop) { - parent = Configuration.getConfiguration(); - - initialize(prop); - } - private void initialize(Properties properties) { - if (LOG.isDebugEnabled()) { - LOG.debug("==> InMemoryJAASConfiguration.initialize()"); - } + LOG.debug("==> InMemoryJAASConfiguration.initialize()"); int prefixLen = JAAS_CONFIG_PREFIX_PARAM.length(); Map> jaasClients = new HashMap<>(); - for(String key : properties.stringPropertyNames()) { + for (String key : properties.stringPropertyNames()) { if (key.startsWith(JAAS_CONFIG_PREFIX_PARAM)) { String jaasKey = key.substring(prefixLen); StringTokenizer tokenizer = new StringTokenizer(jaasKey, "."); @@ -263,40 +237,29 @@ private void initialize(Properties properties) { if (tokenCount > 0) { String clientId = tokenizer.nextToken(); - SortedSet indexList = jaasClients.get(clientId); - - if (indexList == null) { - indexList = new TreeSet<>(); - - jaasClients.put(clientId, indexList); - } + SortedSet indexList = jaasClients.computeIfAbsent(clientId, k -> new TreeSet<>()); String indexStr = tokenizer.nextToken(); - int indexId = isNumeric(indexStr) ? Integer.parseInt(indexStr) : -1; - Integer clientIdIndex = Integer.valueOf(indexId); + Integer clientIdIndex = isNumeric(indexStr) ? Integer.parseInt(indexStr) : -1; - if (!indexList.contains(clientIdIndex)) { - indexList.add(clientIdIndex); - } + indexList.add(clientIdIndex); } } } - for(String jaasClient : jaasClients.keySet()) { - for(Integer index : jaasClients.get(jaasClient)) { + for (String jaasClient : jaasClients.keySet()) { + for (Integer index : jaasClients.get(jaasClient)) { String keyPrefix = JAAS_CONFIG_PREFIX_PARAM + jaasClient + "."; if (index > -1) { - keyPrefix = keyPrefix + String.valueOf(index) + "."; + keyPrefix = keyPrefix + index + "."; } String keyParam = keyPrefix + JAAS_CONFIG_LOGIN_MODULE_NAME_PARAM; String loginModuleName = properties.getProperty(keyParam); if (loginModuleName == null) { - LOG.error("Unable to add JAAS configuration for " - + "client [" + jaasClient + "] as it is missing param [" + keyParam + "]." - + " Skipping JAAS config for [" + jaasClient + "]"); + LOG.error("Unable to add JAAS configuration for client [{}}] as it is missing param [{}]. Skipping JAAS config for [{}]", jaasClient, keyParam, jaasClient); continue; } else { loginModuleName = loginModuleName.trim(); @@ -306,29 +269,32 @@ private void initialize(Properties properties) { String controlFlag = properties.getProperty(keyParam); - AppConfigurationEntry.LoginModuleControlFlag loginControlFlag = null; + AppConfigurationEntry.LoginModuleControlFlag loginControlFlag; if (controlFlag != null) { controlFlag = controlFlag.trim().toLowerCase(); - if (controlFlag.equals("optional")) { - loginControlFlag = AppConfigurationEntry.LoginModuleControlFlag.OPTIONAL; - } else if (controlFlag.equals("requisite")) { - loginControlFlag = AppConfigurationEntry.LoginModuleControlFlag.REQUISITE; - } else if (controlFlag.equals("sufficient")) { - loginControlFlag = AppConfigurationEntry.LoginModuleControlFlag.SUFFICIENT; - } else if (controlFlag.equals("required")) { - loginControlFlag = AppConfigurationEntry.LoginModuleControlFlag.REQUIRED; - } else { - String validValues = "optional|requisite|sufficient|required"; - LOG.warn("Unknown JAAS configuration value for (" + keyParam - + ") = [" + controlFlag + "], valid value are [" + validValues - + "] using the default value, REQUIRED"); - loginControlFlag = AppConfigurationEntry.LoginModuleControlFlag.REQUIRED; + switch (controlFlag) { + case "optional": + loginControlFlag = AppConfigurationEntry.LoginModuleControlFlag.OPTIONAL; + break; + case "requisite": + loginControlFlag = AppConfigurationEntry.LoginModuleControlFlag.REQUISITE; + break; + case "sufficient": + loginControlFlag = AppConfigurationEntry.LoginModuleControlFlag.SUFFICIENT; + break; + case "required": + loginControlFlag = AppConfigurationEntry.LoginModuleControlFlag.REQUIRED; + break; + default: + String validValues = "optional|requisite|sufficient|required"; + LOG.warn("Unknown JAAS configuration value for ({}) = [{}], valid value are [{}] using the default value, REQUIRED", keyParam, controlFlag, validValues); + loginControlFlag = AppConfigurationEntry.LoginModuleControlFlag.REQUIRED; + break; } } else { - LOG.warn("Unable to find JAAS configuration (" - + keyParam + "); using the default value, REQUIRED"); + LOG.warn("Unable to find JAAS configuration ({}); using the default value, REQUIRED", keyParam); loginControlFlag = AppConfigurationEntry.LoginModuleControlFlag.REQUIRED; } @@ -336,7 +302,7 @@ private void initialize(Properties properties) { String optionPrefix = keyPrefix + JAAS_CONFIG_LOGIN_OPTIONS_PREFIX + "."; int optionPrefixLen = optionPrefix.length(); - for(String key : properties.stringPropertyNames()) { + for (String key : properties.stringPropertyNames()) { if (key.startsWith(optionPrefix)) { String optionKey = key.substring(optionPrefixLen); String optionVal = properties.getProperty(key); @@ -349,8 +315,7 @@ private void initialize(Properties properties) { optionVal = SecurityUtil.getServerPrincipal(optionVal, (String) null); } } catch (IOException e) { - LOG.warn("Failed to build serverPrincipal. Using provided value:[" - + optionVal + "]"); + LOG.warn("Failed to build serverPrincipal. Using provided value:[{}]", optionVal); } } @@ -376,21 +341,13 @@ private void initialize(Properties properties) { LOG.debug(sb.toString()); } - List retList = applicationConfigEntryMap.get(jaasClient); - - if (retList == null) { - retList = new ArrayList<>(); - - applicationConfigEntryMap.put(jaasClient, retList); - } + List retList = applicationConfigEntryMap.computeIfAbsent(jaasClient, k -> new ArrayList<>()); retList.add(entry); } } - if (LOG.isDebugEnabled()) { - LOG.debug("<== InMemoryJAASConfiguration.initialize()"); - } + LOG.debug("<== InMemoryJAASConfiguration.initialize()"); } private static boolean isNumeric(String str) { @@ -403,10 +360,7 @@ private String toString(AppConfigurationEntry[] entries) { sb.append('['); if (entries != null) { for (AppConfigurationEntry entry : entries) { - sb.append("{ loginModuleName=").append(entry.getLoginModuleName()) - .append(", controlFlag=").append(entry.getControlFlag()) - .append(", options=").append(entry.getOptions()) - .append("}"); + sb.append("{ loginModuleName=").append(entry.getLoginModuleName()).append(", controlFlag=").append(entry.getControlFlag()).append(", options=").append(entry.getOptions()).append("}"); } } sb.append(']'); diff --git a/security-admin/src/main/java/org/apache/ranger/solr/krb/KerberosAction.java b/security-admin/src/main/java/org/apache/ranger/solr/krb/KerberosAction.java index 23abe1fe22..9ed1d44840 100644 --- a/security-admin/src/main/java/org/apache/ranger/solr/krb/KerberosAction.java +++ b/security-admin/src/main/java/org/apache/ranger/solr/krb/KerberosAction.java @@ -23,6 +23,7 @@ import org.slf4j.Logger; import javax.security.auth.login.LoginException; + import java.security.PrivilegedActionException; import java.security.PrivilegedExceptionAction; @@ -30,17 +31,15 @@ * Helper class for processors to perform an action as a KerberosUser. */ public class KerberosAction { - - private final KerberosUser kerberosUser; + private final KerberosUser kerberosUser; private final PrivilegedExceptionAction action; - private final Logger logger; + private final Logger logger; - public KerberosAction(final KerberosUser kerberosUser, - final PrivilegedExceptionAction action, - final Logger logger) { + public KerberosAction(final KerberosUser kerberosUser, final PrivilegedExceptionAction action, final Logger logger) { this.kerberosUser = kerberosUser; - this.action = action; - this.logger = logger; + this.action = action; + this.logger = logger; + Validate.notNull(this.kerberosUser); Validate.notNull(this.action); Validate.notNull(this.logger); @@ -48,11 +47,15 @@ public KerberosAction(final KerberosUser kerberosUser, public T execute() throws Exception { T result; + // lazily login the first time the processor executes if (!kerberosUser.isLoggedIn()) { try { kerberosUser.login(); - if (logger != null) logger.info("Successful login for " + kerberosUser.getPrincipal()); + + if (logger != null) { + logger.info("Successful login for {}", kerberosUser.getPrincipal()); + } } catch (LoginException e) { throw new Exception("Login failed due to: " + e.getMessage(), e); } @@ -77,12 +80,14 @@ public T execute() throws Exception { try { kerberosUser.logout(); kerberosUser.login(); + result = kerberosUser.doAs(action); } catch (Exception e) { throw new Exception("Retrying privileged action failed due to: " + e.getMessage(), e); } } catch (PrivilegedActionException pae) { final Exception cause = pae.getException(); + throw new Exception("Privileged action failed due to: " + cause.getMessage(), cause); } diff --git a/security-admin/src/main/java/org/apache/ranger/solr/krb/KerberosJAASConfigUser.java b/security-admin/src/main/java/org/apache/ranger/solr/krb/KerberosJAASConfigUser.java index 115404e49b..c170ab728d 100644 --- a/security-admin/src/main/java/org/apache/ranger/solr/krb/KerberosJAASConfigUser.java +++ b/security-admin/src/main/java/org/apache/ranger/solr/krb/KerberosJAASConfigUser.java @@ -30,8 +30,7 @@ /** * Used to authenticate and execute actions when Kerberos is enabled and a keytab is being used. - * - * */ + */ public class KerberosJAASConfigUser extends AbstractKerberosUser { private static final Logger LOG = LoggerFactory.getLogger(KerberosJAASConfigUser.class); @@ -43,20 +42,19 @@ public KerberosJAASConfigUser(final String configName, final Configuration confi this.config = config; } - @Override public String getPrincipal() { String ret = null; AppConfigurationEntry[] entries = config.getAppConfigurationEntry(configName); if (entries != null) { - for (AppConfigurationEntry entry : entries) { - if (entry.getOptions().containsKey(InMemoryJAASConfiguration.JAAS_PRINCIPAL_PROP)) { - ret = (String) entry.getOptions().get(InMemoryJAASConfiguration.JAAS_PRINCIPAL_PROP); + for (AppConfigurationEntry entry : entries) { + if (entry.getOptions().containsKey(InMemoryJAASConfiguration.JAAS_PRINCIPAL_PROP)) { + ret = (String) entry.getOptions().get(InMemoryJAASConfiguration.JAAS_PRINCIPAL_PROP); - break; - } - } + break; + } + } } return ret; @@ -64,15 +62,9 @@ public String getPrincipal() { @Override protected LoginContext createLoginContext(Subject subject) throws LoginException { - if (LOG.isDebugEnabled()) { - LOG.debug("==> KerberosJAASConfigUser.createLoginContext()"); - } - - if (LOG.isDebugEnabled()) { - LOG.debug("<== KerberosJAASConfigUser.createLoginContext(), Subject: " + subject); - } + LOG.debug("==> KerberosJAASConfigUser.createLoginContext()"); + LOG.debug("<== KerberosJAASConfigUser.createLoginContext(), Subject: {}", subject); return new LoginContext(configName, subject, null, config); } } - diff --git a/security-admin/src/main/java/org/apache/ranger/solr/krb/KerberosUser.java b/security-admin/src/main/java/org/apache/ranger/solr/krb/KerberosUser.java index 411847183c..7b652682c4 100644 --- a/security-admin/src/main/java/org/apache/ranger/solr/krb/KerberosUser.java +++ b/security-admin/src/main/java/org/apache/ranger/solr/krb/KerberosUser.java @@ -20,6 +20,7 @@ package org.apache.ranger.solr.krb; import javax.security.auth.login.LoginException; + import java.security.PrivilegedAction; import java.security.PrivilegedActionException; import java.security.PrivilegedExceptionAction; @@ -28,7 +29,6 @@ * A keytab-based user that can login/logout and perform actions as the given user. */ public interface KerberosUser { - /** * Performs a login for the given user. * @@ -82,6 +82,4 @@ T doAs(PrivilegedExceptionAction action) * @return the principal for this user */ String getPrincipal(); - } - diff --git a/security-admin/src/main/java/org/apache/ranger/validation/RangerGdsValidationDBProvider.java b/security-admin/src/main/java/org/apache/ranger/validation/RangerGdsValidationDBProvider.java index 43e73f919a..f282cea032 100644 --- a/security-admin/src/main/java/org/apache/ranger/validation/RangerGdsValidationDBProvider.java +++ b/security-admin/src/main/java/org/apache/ranger/validation/RangerGdsValidationDBProvider.java @@ -25,7 +25,14 @@ import org.apache.ranger.biz.XUserMgr; import org.apache.ranger.common.RangerRoleCache; import org.apache.ranger.db.RangerDaoManager; -import org.apache.ranger.entity.*; +import org.apache.ranger.entity.XXGdsDataShare; +import org.apache.ranger.entity.XXGdsDataset; +import org.apache.ranger.entity.XXGdsProject; +import org.apache.ranger.entity.XXGroup; +import org.apache.ranger.entity.XXRole; +import org.apache.ranger.entity.XXSecurityZone; +import org.apache.ranger.entity.XXService; +import org.apache.ranger.entity.XXUser; import org.apache.ranger.plugin.model.RangerGds.RangerDataShare; import org.apache.ranger.plugin.model.RangerGds.RangerDataset; import org.apache.ranger.plugin.model.RangerGds.RangerProject; @@ -47,8 +54,8 @@ import java.util.Collection; import java.util.HashSet; import java.util.List; -import java.util.Set; import java.util.Map; +import java.util.Set; import static org.apache.ranger.db.XXGlobalStateDao.RANGER_GLOBAL_STATE_NAME_ROLE; @@ -87,7 +94,6 @@ public class RangerGdsValidationDBProvider extends RangerGdsValidationDataProvid RangerRolesUtil rolesUtil; - public RangerGdsValidationDBProvider() { } @@ -152,7 +158,6 @@ public boolean isServiceAdmin(String name) { RangerService service = xService != null ? svcService.getPopulatedViewObject(xService) : null; return service != null && bizUtil.isUserServiceAdmin(service, bizUtil.getCurrentUserLoginId()); - } public boolean isZoneAdmin(String zoneName) { @@ -201,9 +206,8 @@ public Set getAccessTypes(String serviceName) { public Set getMaskTypes(String serviceName) { List maskTypes = daoMgr.getXXDataMaskTypeDef().getNamesByServiceName(serviceName); - Set ret = new HashSet<>(maskTypes); - return ret; + return new HashSet<>(maskTypes); } public RangerDataset getDataset(Long id) { @@ -253,15 +257,11 @@ public RangerDataShare getDataShare(Long id) { } public Long getSharedResourceId(Long dataShareId, String name) { - Long ret = daoMgr.getXXGdsSharedResource().getIdByDataShareIdAndName(dataShareId, name); - - return ret; + return daoMgr.getXXGdsSharedResource().getIdByDataShareIdAndName(dataShareId, name); } public Long getSharedResourceId(Long dataShareId, RangerPolicyResourceSignature signature) { - Long ret = daoMgr.getXXGdsSharedResource().getIdByDataShareIdAndResourceSignature(dataShareId, signature.getSignature()); - - return ret; + return daoMgr.getXXGdsSharedResource().getIdByDataShareIdAndResourceSignature(dataShareId, signature.getSignature()); } private RangerRolesUtil initGetRolesUtil() { @@ -279,7 +279,8 @@ private RangerRolesUtil initGetRolesUtil() { RangerRoles roles = RangerRoleCache.getInstance().getLatestRangerRoleOrCached(SERVICE_NAME_FOR_ROLES, rolesStore, lastKnownVersion, currentVersion); if (roles != null) { - this.rolesUtil = ret = new RangerRolesUtil(roles); + ret = new RangerRolesUtil(roles); + this.rolesUtil = new RangerRolesUtil(roles); } } catch (Exception excp) { LOG.warn("failed to get roles from store", excp); diff --git a/security-admin/src/main/java/org/apache/ranger/validation/RangerGdsValidationDataProvider.java b/security-admin/src/main/java/org/apache/ranger/validation/RangerGdsValidationDataProvider.java index f8efaa677b..fa495ec03e 100644 --- a/security-admin/src/main/java/org/apache/ranger/validation/RangerGdsValidationDataProvider.java +++ b/security-admin/src/main/java/org/apache/ranger/validation/RangerGdsValidationDataProvider.java @@ -17,11 +17,10 @@ package org.apache.ranger.validation; - -import org.apache.ranger.plugin.model.RangerPolicyResourceSignature; import org.apache.ranger.plugin.model.RangerGds.RangerDataShare; import org.apache.ranger.plugin.model.RangerGds.RangerDataset; import org.apache.ranger.plugin.model.RangerGds.RangerProject; +import org.apache.ranger.plugin.model.RangerPolicyResourceSignature; import java.util.Collection; import java.util.Set; diff --git a/security-admin/src/main/java/org/apache/ranger/validation/RangerGdsValidator.java b/security-admin/src/main/java/org/apache/ranger/validation/RangerGdsValidator.java index 4ee7b97abd..068eba2fc4 100755 --- a/security-admin/src/main/java/org/apache/ranger/validation/RangerGdsValidator.java +++ b/security-admin/src/main/java/org/apache/ranger/validation/RangerGdsValidator.java @@ -27,10 +27,10 @@ import org.apache.ranger.plugin.model.RangerGds; import org.apache.ranger.plugin.model.RangerGds.GdsPermission; import org.apache.ranger.plugin.model.RangerGds.GdsShareStatus; -import org.apache.ranger.plugin.model.RangerGds.RangerDataShareInDataset; import org.apache.ranger.plugin.model.RangerGds.RangerDataShare; -import org.apache.ranger.plugin.model.RangerGds.RangerDatasetInProject; +import org.apache.ranger.plugin.model.RangerGds.RangerDataShareInDataset; import org.apache.ranger.plugin.model.RangerGds.RangerDataset; +import org.apache.ranger.plugin.model.RangerGds.RangerDatasetInProject; import org.apache.ranger.plugin.model.RangerGds.RangerGdsMaskInfo; import org.apache.ranger.plugin.model.RangerGds.RangerGdsObjectACL; import org.apache.ranger.plugin.model.RangerGds.RangerProject; @@ -47,17 +47,17 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; -import java.util.*; - +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; @Component public class RangerGdsValidator { + public static final Integer GDS_ENTITIES_NAME_MAX_LENGTH = 512; private static final Logger LOG = LoggerFactory.getLogger(RangerGdsValidator.class); - private final RangerGdsValidationDataProvider dataProvider; - - public static final Integer GDS_ENTITIES_NAME_MAX_LENGTH = 512; - @Autowired RESTErrorUtil restErrorUtil; @@ -357,7 +357,7 @@ public void validateUpdate(RangerSharedResource resource, RangerSharedResource e } if (result.isSuccess()) { - Long existingSharedResourceNameId = dataProvider.getSharedResourceId(resource.getDataShareId(),new RangerPolicyResourceSignature(resource)); + Long existingSharedResourceNameId = dataProvider.getSharedResourceId(resource.getDataShareId(), new RangerPolicyResourceSignature(resource)); if (existingSharedResourceNameId != null && !existingSharedResourceNameId.equals(existing.getId())) { result.addValidationFailure(new ValidationFailureDetails(ValidationErrorCode.GDS_VALIDATION_ERR_SHARED_RESOURCE_CONFLICT, "resource", resource.getResource(), dataShare.getName())); @@ -414,25 +414,24 @@ public void validateCreate(RangerDataShareInDataset dshid) { } if (dataShare != null && dataset != null && !dataProvider.isAdminUser()) { - switch (dshid.getStatus()) { case GRANTED: case DENIED: validateAdmin(dataProvider.getCurrentUserLoginId(), "dataShare", dataShare.getName(), dataShare.getAcl(), result); - break; + break; case ACTIVE: validateAdmin(dataProvider.getCurrentUserLoginId(), "dataShare", dataShare.getName(), dataShare.getAcl(), result); validateAdmin(dataProvider.getCurrentUserLoginId(), "dataset", dataset.getName(), dataset.getAcl(), result); - break; + break; case REQUESTED: validateAdmin(dataProvider.getCurrentUserLoginId(), "dataset", dataset.getName(), dataset.getAcl(), result); - break; + break; case NONE: default: - break; + break; } } @@ -489,12 +488,9 @@ public void validateUpdate(RangerDataShareInDataset dshid, RangerDataShareInData validateAdmin(dataProvider.getCurrentUserLoginId(), "dataset", dataset.getName(), dataset.getAcl(), result); } - if (!requireDataShareAdmin && !requireDatasetAdmin){ // must be either a dataShare admin or a dataset admin - String userName = dataProvider.getCurrentUserLoginId(); - boolean isAllowed = isAdmin(userName, dataShare.getAcl()) || - dataProvider.isServiceAdmin(dataShare.getService()) || - dataProvider.isZoneAdmin(dataShare.getZone()) || - isAdmin(userName, dataset.getAcl()); + if (!requireDataShareAdmin && !requireDatasetAdmin) { // must be either a dataShare admin or a dataset admin + String userName = dataProvider.getCurrentUserLoginId(); + boolean isAllowed = isAdmin(userName, dataShare.getAcl()) || dataProvider.isServiceAdmin(dataShare.getService()) || dataProvider.isZoneAdmin(dataShare.getZone()) || isAdmin(userName, dataset.getAcl()); if (!isAllowed) { result.addValidationFailure(new ValidationFailureDetails(ValidationErrorCode.GDS_VALIDATION_ERR_INVALID_STATUS_CHANGE, "status", existing.getStatus(), dshid.getStatus())); @@ -531,11 +527,8 @@ public void validateDelete(Long dshidId, RangerDataShareInDataset existing) { } if (dataShare != null && dataset != null && !dataProvider.isAdminUser()) { // must be either a dataset admin or a dataShare admin - String userName = dataProvider.getCurrentUserLoginId(); - boolean isAllowed = isAdmin(userName, dataShare.getAcl()) || - dataProvider.isServiceAdmin(dataShare.getService()) || - dataProvider.isZoneAdmin(dataShare.getZone()) || - isAdmin(userName, dataset.getAcl()); + String userName = dataProvider.getCurrentUserLoginId(); + boolean isAllowed = isAdmin(userName, dataShare.getAcl()) || dataProvider.isServiceAdmin(dataShare.getService()) || dataProvider.isZoneAdmin(dataShare.getZone()) || isAdmin(userName, dataset.getAcl()); if (!isAllowed) { result.addValidationFailure(new ValidationFailureDetails(ValidationErrorCode.GDS_VALIDATION_ERR_NOT_ADMIN, null, userName, "dataShareInDataset", "dataShare (name=" + dataShare.getName() + ") or dataset (name=" + dataset.getName() + ")")); @@ -570,17 +563,17 @@ public void validateCreate(RangerDatasetInProject dip) { case GRANTED: case DENIED: validateAdmin(dataProvider.getCurrentUserLoginId(), "dataset", dataset.getName(), dataset.getAcl(), result); - break; + break; case ACTIVE: validateAdmin(dataProvider.getCurrentUserLoginId(), "dataset", dataset.getName(), dataset.getAcl(), result); validateAdmin(dataProvider.getCurrentUserLoginId(), "project", project.getName(), project.getAcl(), result); - break; + break; case NONE: case REQUESTED: default: - break; + break; } } @@ -594,7 +587,7 @@ public void validateCreate(RangerDatasetInProject dip) { public void validateUpdate(RangerDatasetInProject dip, RangerDatasetInProject existing) { LOG.debug("==> validateUpdate(dip={}, existing={})", dip, existing); - ValidationResult result = new ValidationResult(); + ValidationResult result = new ValidationResult(); if (existing == null) { result.addValidationFailure(new ValidationFailureDetails(ValidationErrorCode.GDS_VALIDATION_ERR_DATASET_IN_PROJECT_ID_NOT_FOUND, "id", dip.getId())); @@ -635,7 +628,7 @@ public void validateUpdate(RangerDatasetInProject dip, RangerDatasetInProject ex validateAdmin(dataProvider.getCurrentUserLoginId(), "project", project.getName(), project.getAcl(), result); } - if (!requireDatasetAdmin && !requireProjectAdmin){ // must be either a dataset admin or a project admin + if (!requireDatasetAdmin && !requireProjectAdmin) { // must be either a dataset admin or a project admin String userName = dataProvider.getCurrentUserLoginId(); boolean isAllowed = isAdmin(userName, dataset.getAcl()) || isAdmin(userName, project.getAcl()); @@ -696,7 +689,7 @@ public void validateCreateOrUpdate(RangerPolicy policy) { return; } - ValidationResult result = new ValidationResult(); + ValidationResult result = new ValidationResult(); List policyItems = policy.getPolicyItems(); validatePolicyItems(policyItems, result); @@ -756,7 +749,7 @@ public boolean hasPermission(RangerGdsObjectACL acl, GdsPermission permission) { if (!ret && acl.getGroups() != null) { ret = isAllowed(acl.getGroups().get(RangerConstants.GROUP_PUBLIC), permission); - if(!ret) { + if (!ret) { Set userGroups = dataProvider.getGroupsForUser(userName); for (String userGroup : userGroups) { @@ -868,10 +861,10 @@ private void validatePolicyItems(List policyItems, ValidationR continue; } - boolean hasNoPrincipals = CollectionUtils.isEmpty(policyItem.getUsers()) && CollectionUtils.isEmpty(policyItem.getGroups()) && CollectionUtils.isEmpty(policyItem.getRoles()); - boolean hasInvalidUsers = policyItem.getUsers() != null && policyItem.getUsers().stream().anyMatch(StringUtils::isBlank); + boolean hasNoPrincipals = CollectionUtils.isEmpty(policyItem.getUsers()) && CollectionUtils.isEmpty(policyItem.getGroups()) && CollectionUtils.isEmpty(policyItem.getRoles()); + boolean hasInvalidUsers = policyItem.getUsers() != null && policyItem.getUsers().stream().anyMatch(StringUtils::isBlank); boolean hasInvalidGroups = policyItem.getGroups() != null && policyItem.getGroups().stream().anyMatch(StringUtils::isBlank); - boolean hasInvalidRoles = policyItem.getRoles() != null && policyItem.getRoles().stream().anyMatch(StringUtils::isBlank); + boolean hasInvalidRoles = policyItem.getRoles() != null && policyItem.getRoles().stream().anyMatch(StringUtils::isBlank); if (hasNoPrincipals || hasInvalidUsers || hasInvalidGroups || hasInvalidRoles) { addValidationFailure(result, ValidationErrorCode.POLICY_VALIDATION_ERR_MISSING_USER_AND_GROUPS); @@ -1032,7 +1025,7 @@ private boolean isAdmin(String userName, RangerGdsObjectACL acl) { } if (!ret && MapUtils.isNotEmpty(acl.getRoles())) { - Set userRoles = dataProvider.getRolesForUser(userName); + Set userRoles = dataProvider.getRolesForUser(userName); if (userRoles != null) { for (String userRole : userRoles) { @@ -1055,47 +1048,36 @@ private boolean isAllowed(GdsPermission hasPermission, GdsPermission accessPermi switch (accessPermission) { case ADMIN: ret = hasPermission == GdsPermission.ADMIN; - break; + break; case POLICY_ADMIN: - ret = hasPermission == GdsPermission.POLICY_ADMIN || - hasPermission == GdsPermission.ADMIN; - break; + ret = hasPermission == GdsPermission.POLICY_ADMIN || hasPermission == GdsPermission.ADMIN; + break; case AUDIT: - ret = hasPermission == GdsPermission.AUDIT || - hasPermission == GdsPermission.POLICY_ADMIN || - hasPermission == GdsPermission.ADMIN; - break; + ret = hasPermission == GdsPermission.AUDIT || hasPermission == GdsPermission.POLICY_ADMIN || hasPermission == GdsPermission.ADMIN; + break; case VIEW: - ret = hasPermission == GdsPermission.VIEW || - hasPermission == GdsPermission.AUDIT || - hasPermission == GdsPermission.POLICY_ADMIN || - hasPermission == GdsPermission.ADMIN; - break; + ret = hasPermission == GdsPermission.VIEW || hasPermission == GdsPermission.AUDIT || hasPermission == GdsPermission.POLICY_ADMIN || hasPermission == GdsPermission.ADMIN; + break; case LIST: - ret = hasPermission == GdsPermission.LIST || - hasPermission == GdsPermission.VIEW || - hasPermission == GdsPermission.AUDIT || - hasPermission == GdsPermission.POLICY_ADMIN || - hasPermission == GdsPermission.ADMIN; - break; + ret = hasPermission == GdsPermission.LIST || hasPermission == GdsPermission.VIEW || hasPermission == GdsPermission.AUDIT || hasPermission == GdsPermission.POLICY_ADMIN || hasPermission == GdsPermission.ADMIN; + break; case NONE: ret = false; - break; + break; default: ret = false; - break; + break; } return ret; } - private GdsPermission getHigherPrivilegePermission(GdsPermission permission1, GdsPermission permission2) { GdsPermission ret = permission1; @@ -1116,10 +1098,7 @@ private static boolean needsSharedObjectAdmin(GdsShareStatus existing, GdsShareS switch (existing) { case NONE: case REQUESTED: - ret = (updated == GdsShareStatus.GRANTED) || - (updated == GdsShareStatus.DENIED) || - (updated == GdsShareStatus.ACTIVE); // implicit approval - + ret = (updated == GdsShareStatus.GRANTED) || (updated == GdsShareStatus.DENIED) || (updated == GdsShareStatus.ACTIVE); // implicit approval break; case GRANTED: @@ -1127,16 +1106,13 @@ private static boolean needsSharedObjectAdmin(GdsShareStatus existing, GdsShareS break; case DENIED: - ret = (updated == GdsShareStatus.GRANTED) || - (updated == GdsShareStatus.ACTIVE); // implicit approval + ret = (updated == GdsShareStatus.GRANTED) || (updated == GdsShareStatus.ACTIVE); // implicit approval break; case ACTIVE: - ret = (updated == GdsShareStatus.GRANTED) || - (updated == GdsShareStatus.DENIED); + ret = (updated == GdsShareStatus.GRANTED) || (updated == GdsShareStatus.DENIED); break; } - } return ret; @@ -1151,28 +1127,22 @@ private static boolean needsReceivingObjectAdmin(GdsShareStatus existing, GdsSha if (!Objects.equals(existing, updated)) { switch (existing) { case NONE: - ret = (updated == GdsShareStatus.REQUESTED) || - (updated == GdsShareStatus.ACTIVE); - break; + ret = (updated == GdsShareStatus.REQUESTED) || (updated == GdsShareStatus.ACTIVE); + break; case REQUESTED: - ret = (updated == GdsShareStatus.NONE) || - (updated == GdsShareStatus.ACTIVE); - break; + ret = (updated == GdsShareStatus.NONE) || (updated == GdsShareStatus.ACTIVE); + break; case GRANTED: case DENIED: - ret = (updated == GdsShareStatus.NONE) || - (updated == GdsShareStatus.REQUESTED) || - (updated == GdsShareStatus.ACTIVE); - break; + ret = (updated == GdsShareStatus.NONE) || (updated == GdsShareStatus.REQUESTED) || (updated == GdsShareStatus.ACTIVE); + break; case ACTIVE: - ret = (updated == GdsShareStatus.NONE) || - (updated == GdsShareStatus.REQUESTED); - break; + ret = (updated == GdsShareStatus.NONE) || (updated == GdsShareStatus.REQUESTED); + break; } - } return ret; @@ -1184,13 +1154,17 @@ public class ValidationResult { private ValidationResult() { } - public boolean isSuccess() { return validationFailures.isEmpty(); } + public boolean isSuccess() { + return validationFailures.isEmpty(); + } public void addValidationFailure(ValidationFailureDetails validationFailure) { validationFailures.add(validationFailure); } - public List getValidationFailures() { return validationFailures; } + public List getValidationFailures() { + return validationFailures; + } public void throwRESTException() { throw restErrorUtil.createRESTException(validationFailures.toString(), MessageEnums.INVALID_INPUT_DATA); diff --git a/security-admin/src/main/java/org/apache/ranger/view/RangerExportPolicyList.java b/security-admin/src/main/java/org/apache/ranger/view/RangerExportPolicyList.java index cd2e4033ab..e1933e32ac 100644 --- a/security-admin/src/main/java/org/apache/ranger/view/RangerExportPolicyList.java +++ b/security-admin/src/main/java/org/apache/ranger/view/RangerExportPolicyList.java @@ -17,26 +17,25 @@ package org.apache.ranger.view; -import java.util.LinkedHashMap; -import java.util.Map; - import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; import com.fasterxml.jackson.annotation.JsonInclude; +import java.util.LinkedHashMap; +import java.util.Map; + @JsonAutoDetect(getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE, fieldVisibility = Visibility.ANY) @JsonInclude(JsonInclude.Include.NON_NULL) public class RangerExportPolicyList extends RangerPolicyList implements java.io.Serializable { - private static final long serialVersionUID = 1L; - - Map metaDataInfo = new LinkedHashMap(); + private static final long serialVersionUID = 1L; - public Map getMetaDataInfo() { - return metaDataInfo; - } + Map metaDataInfo = new LinkedHashMap<>(); - public void setMetaDataInfo(Map metaDataInfo) { - this.metaDataInfo = metaDataInfo; - } + public Map getMetaDataInfo() { + return metaDataInfo; + } + public void setMetaDataInfo(Map metaDataInfo) { + this.metaDataInfo = metaDataInfo; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/view/RangerExportRoleList.java b/security-admin/src/main/java/org/apache/ranger/view/RangerExportRoleList.java index c6cc697988..b1681d8903 100644 --- a/security-admin/src/main/java/org/apache/ranger/view/RangerExportRoleList.java +++ b/security-admin/src/main/java/org/apache/ranger/view/RangerExportRoleList.java @@ -17,26 +17,25 @@ package org.apache.ranger.view; -import java.util.LinkedHashMap; -import java.util.Map; - import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; import com.fasterxml.jackson.annotation.JsonInclude; +import java.util.LinkedHashMap; +import java.util.Map; + @JsonAutoDetect(getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE, fieldVisibility = Visibility.ANY) @JsonInclude(JsonInclude.Include.NON_NULL) public class RangerExportRoleList extends RangerRoleList implements java.io.Serializable { - private static final long serialVersionUID = 1L; - - Map metaDataInfo = new LinkedHashMap(); + private static final long serialVersionUID = 1L; - public Map getMetaDataInfo() { - return metaDataInfo; - } + Map metaDataInfo = new LinkedHashMap<>(); - public void setMetaDataInfo(Map metaDataInfo) { - this.metaDataInfo = metaDataInfo; - } + public Map getMetaDataInfo() { + return metaDataInfo; + } + public void setMetaDataInfo(Map metaDataInfo) { + this.metaDataInfo = metaDataInfo; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/view/RangerGdsVList.java b/security-admin/src/main/java/org/apache/ranger/view/RangerGdsVList.java index 754797b9a5..52eb84d8b6 100644 --- a/security-admin/src/main/java/org/apache/ranger/view/RangerGdsVList.java +++ b/security-admin/src/main/java/org/apache/ranger/view/RangerGdsVList.java @@ -17,6 +17,9 @@ package org.apache.ranger.view; +import com.fasterxml.jackson.annotation.JsonAutoDetect; +import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; +import com.fasterxml.jackson.annotation.JsonInclude; import org.apache.ranger.common.view.VList; import org.apache.ranger.plugin.model.RangerGds.RangerDataShare; import org.apache.ranger.plugin.model.RangerGds.RangerDataShareInDataset; @@ -24,171 +27,192 @@ import org.apache.ranger.plugin.model.RangerGds.RangerDatasetInProject; import org.apache.ranger.plugin.model.RangerGds.RangerProject; import org.apache.ranger.plugin.model.RangerGds.RangerSharedResource; -import com.fasterxml.jackson.annotation.JsonAutoDetect; -import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; -import com.fasterxml.jackson.annotation.JsonInclude; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; + import java.util.ArrayList; import java.util.List; public class RangerGdsVList { - - @JsonAutoDetect(getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE, fieldVisibility = Visibility.ANY) - @JsonInclude(JsonInclude.Include.NON_NULL) - @XmlRootElement - @XmlAccessorType(XmlAccessType.FIELD) - public static class RangerDatasetList extends VList { - private static final long serialVersionUID = 1L; - - List list = new ArrayList<>(); - - public RangerDatasetList() { - super(); - } - - public RangerDatasetList(List objList) { - super(objList); - - this.list = objList; - } - - @Override - public int getListSize() { return list != null ? list.size() : 0; } - - @Override - public List getList() { return list; } - } - - @JsonAutoDetect(getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE, fieldVisibility = Visibility.ANY) - @JsonInclude(JsonInclude.Include.NON_NULL) - @XmlRootElement - @XmlAccessorType(XmlAccessType.FIELD) - public static class RangerProjectList extends VList { - private static final long serialVersionUID = 1L; - - List list = new ArrayList<>(); - - public RangerProjectList() { - super(); - } - - public RangerProjectList(List objList) { - super(objList); - - this.list = objList; - } - - @Override - public int getListSize() { return list != null ? list.size() : 0; } - - @Override - public List getList() { return list; } - } - - @JsonAutoDetect(getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE, fieldVisibility = Visibility.ANY) - @JsonInclude(JsonInclude.Include.NON_NULL) - @XmlRootElement - @XmlAccessorType(XmlAccessType.FIELD) - public static class RangerDataShareList extends VList { - private static final long serialVersionUID = 1L; - - List list = new ArrayList<>(); - - public RangerDataShareList() { - super(); - } - - public RangerDataShareList(List objList) { - super(objList); - - this.list = objList; - } - - @Override - public int getListSize() { return list != null ? list.size() : 0; } - - @Override - public List getList() { return list; } - } - - @JsonAutoDetect(getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE, fieldVisibility = Visibility.ANY) - @JsonInclude(JsonInclude.Include.NON_NULL) - @XmlRootElement - @XmlAccessorType(XmlAccessType.FIELD) - public static class RangerSharedResourceList extends VList { - private static final long serialVersionUID = 1L; - - List list = new ArrayList<>(); - - public RangerSharedResourceList() { - super(); - } - - public RangerSharedResourceList(List objList) { - super(objList); - - this.list = objList; - } - - @Override - public int getListSize() { return list != null ? list.size() : 0; } - - @Override - public List getList() { return list; } - } - - @JsonAutoDetect(getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE, fieldVisibility = Visibility.ANY) - @JsonInclude(JsonInclude.Include.NON_NULL) - @XmlRootElement - @XmlAccessorType(XmlAccessType.FIELD) - public static class RangerDataShareInDatasetList extends VList { - private static final long serialVersionUID = 1L; - - List list = new ArrayList<>(); - - public RangerDataShareInDatasetList() { - super(); - } - - public RangerDataShareInDatasetList(List objList) { - super(objList); - - this.list = objList; - } - - @Override - public int getListSize() { return list != null ? list.size() : 0; } - - @Override - public List getList() { return list; } - } - - @JsonAutoDetect(getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE, fieldVisibility = Visibility.ANY) - @JsonInclude(JsonInclude.Include.NON_NULL) - @XmlRootElement - @XmlAccessorType(XmlAccessType.FIELD) - public static class RangerDatasetInProjectList extends VList { - private static final long serialVersionUID = 1L; - - List list = new ArrayList<>(); - - public RangerDatasetInProjectList() { - super(); - } - - public RangerDatasetInProjectList(List objList) { - super(objList); - - this.list = objList; - } - - @Override - public int getListSize() { return list != null ? list.size() : 0; } - - @Override - public List getList() { return list; } - } + @JsonAutoDetect(getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE, fieldVisibility = Visibility.ANY) + @JsonInclude(JsonInclude.Include.NON_NULL) + @XmlRootElement + @XmlAccessorType(XmlAccessType.FIELD) + public static class RangerDatasetList extends VList { + private static final long serialVersionUID = 1L; + + List list = new ArrayList<>(); + + public RangerDatasetList() { + super(); + } + + public RangerDatasetList(List objList) { + super(objList); + + this.list = objList; + } + + @Override + public int getListSize() { + return list != null ? list.size() : 0; + } + + @Override + public List getList() { + return list; + } + } + + @JsonAutoDetect(getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE, fieldVisibility = Visibility.ANY) + @JsonInclude(JsonInclude.Include.NON_NULL) + @XmlRootElement + @XmlAccessorType(XmlAccessType.FIELD) + public static class RangerProjectList extends VList { + private static final long serialVersionUID = 1L; + + List list = new ArrayList<>(); + + public RangerProjectList() { + super(); + } + + public RangerProjectList(List objList) { + super(objList); + + this.list = objList; + } + + @Override + public int getListSize() { + return list != null ? list.size() : 0; + } + + @Override + public List getList() { + return list; + } + } + + @JsonAutoDetect(getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE, fieldVisibility = Visibility.ANY) + @JsonInclude(JsonInclude.Include.NON_NULL) + @XmlRootElement + @XmlAccessorType(XmlAccessType.FIELD) + public static class RangerDataShareList extends VList { + private static final long serialVersionUID = 1L; + + List list = new ArrayList<>(); + + public RangerDataShareList() { + super(); + } + + public RangerDataShareList(List objList) { + super(objList); + + this.list = objList; + } + + @Override + public int getListSize() { + return list != null ? list.size() : 0; + } + + @Override + public List getList() { + return list; + } + } + + @JsonAutoDetect(getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE, fieldVisibility = Visibility.ANY) + @JsonInclude(JsonInclude.Include.NON_NULL) + @XmlRootElement + @XmlAccessorType(XmlAccessType.FIELD) + public static class RangerSharedResourceList extends VList { + private static final long serialVersionUID = 1L; + + List list = new ArrayList<>(); + + public RangerSharedResourceList() { + super(); + } + + public RangerSharedResourceList(List objList) { + super(objList); + + this.list = objList; + } + + @Override + public int getListSize() { + return list != null ? list.size() : 0; + } + + @Override + public List getList() { + return list; + } + } + + @JsonAutoDetect(getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE, fieldVisibility = Visibility.ANY) + @JsonInclude(JsonInclude.Include.NON_NULL) + @XmlRootElement + @XmlAccessorType(XmlAccessType.FIELD) + public static class RangerDataShareInDatasetList extends VList { + private static final long serialVersionUID = 1L; + + List list = new ArrayList<>(); + + public RangerDataShareInDatasetList() { + super(); + } + + public RangerDataShareInDatasetList(List objList) { + super(objList); + + this.list = objList; + } + + @Override + public int getListSize() { + return list != null ? list.size() : 0; + } + + @Override + public List getList() { + return list; + } + } + + @JsonAutoDetect(getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE, fieldVisibility = Visibility.ANY) + @JsonInclude(JsonInclude.Include.NON_NULL) + @XmlRootElement + @XmlAccessorType(XmlAccessType.FIELD) + public static class RangerDatasetInProjectList extends VList { + private static final long serialVersionUID = 1L; + + List list = new ArrayList<>(); + + public RangerDatasetInProjectList() { + super(); + } + + public RangerDatasetInProjectList(List objList) { + super(objList); + + this.list = objList; + } + + @Override + public int getListSize() { + return list != null ? list.size() : 0; + } + + @Override + public List getList() { + return list; + } + } } diff --git a/security-admin/src/main/java/org/apache/ranger/view/RangerPluginInfoList.java b/security-admin/src/main/java/org/apache/ranger/view/RangerPluginInfoList.java index 8ddfa159df..d33a69d4d8 100644 --- a/security-admin/src/main/java/org/apache/ranger/view/RangerPluginInfoList.java +++ b/security-admin/src/main/java/org/apache/ranger/view/RangerPluginInfoList.java @@ -17,50 +17,49 @@ package org.apache.ranger.view; -import java.util.ArrayList; -import java.util.List; - -import org.apache.ranger.common.view.VList; -import org.apache.ranger.plugin.model.RangerPluginInfo; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; import com.fasterxml.jackson.annotation.JsonInclude; +import org.apache.ranger.common.view.VList; +import org.apache.ranger.plugin.model.RangerPluginInfo; + +import java.util.ArrayList; +import java.util.List; @JsonAutoDetect(getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE, fieldVisibility = Visibility.ANY) @JsonInclude(JsonInclude.Include.NON_NULL) public class RangerPluginInfoList extends VList { - private static final long serialVersionUID = 1L; - - List pluginInfoList = new ArrayList(); + private static final long serialVersionUID = 1L; - public RangerPluginInfoList() { - super(); - } + List pluginInfoList = new ArrayList<>(); - public RangerPluginInfoList(List objList) { - super(objList); - this.pluginInfoList = objList; - } + public RangerPluginInfoList() { + super(); + } - public List getPluginInfoList() { - return pluginInfoList; - } + public RangerPluginInfoList(List objList) { + super(objList); + this.pluginInfoList = objList; + } - public void setPluginInfoList(List pluginInfoList) { - this.pluginInfoList = pluginInfoList; - } + public List getPluginInfoList() { + return pluginInfoList; + } - @Override - public int getListSize() { - if (pluginInfoList != null) { - return pluginInfoList.size(); - } - return 0; - } + public void setPluginInfoList(List pluginInfoList) { + this.pluginInfoList = pluginInfoList; + } - @Override - public List getList() { - return pluginInfoList; - } + @Override + public int getListSize() { + if (pluginInfoList != null) { + return pluginInfoList.size(); + } + return 0; + } + @Override + public List getList() { + return pluginInfoList; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/view/RangerPolicyList.java b/security-admin/src/main/java/org/apache/ranger/view/RangerPolicyList.java index a1099f291a..399ac4da49 100644 --- a/security-admin/src/main/java/org/apache/ranger/view/RangerPolicyList.java +++ b/security-admin/src/main/java/org/apache/ranger/view/RangerPolicyList.java @@ -17,54 +17,53 @@ package org.apache.ranger.view; -import java.util.ArrayList; -import java.util.List; - -import org.apache.ranger.common.view.VList; -import org.apache.ranger.plugin.model.RangerPolicy; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; import com.fasterxml.jackson.annotation.JsonInclude; +import org.apache.ranger.common.view.VList; +import org.apache.ranger.plugin.model.RangerPolicy; + +import java.util.ArrayList; +import java.util.List; @JsonAutoDetect(getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE, fieldVisibility = Visibility.ANY) @JsonInclude(JsonInclude.Include.NON_NULL) public class RangerPolicyList extends VList { - private static final long serialVersionUID = 1L; - - List policies = new ArrayList(); + private static final long serialVersionUID = 1L; - public RangerPolicyList() { - super(); - } + List policies = new ArrayList<>(); - public RangerPolicyList(List objList) { - super(objList); - this.policies = objList; - } + public RangerPolicyList() { + super(); + } - public List getPolicies() { - return policies; - } + public RangerPolicyList(List objList) { + super(objList); + this.policies = objList; + } - public void setPolicies(List policies) { - this.policies = policies; - } + public List getPolicies() { + return policies; + } - public void setGenericPolicies(List policies) { - this.policies = (List) policies; - } + public void setPolicies(List policies) { + this.policies = policies; + } - @Override - public int getListSize() { - if (policies != null) { - return policies.size(); - } - return 0; - } + public void setGenericPolicies(List policies) { + this.policies = (List) policies; + } - @Override - public List getList() { - return policies; - } + @Override + public int getListSize() { + if (policies != null) { + return policies.size(); + } + return 0; + } + @Override + public List getList() { + return policies; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/view/RangerRoleList.java b/security-admin/src/main/java/org/apache/ranger/view/RangerRoleList.java index cde3b5bb4a..e8b587ddab 100644 --- a/security-admin/src/main/java/org/apache/ranger/view/RangerRoleList.java +++ b/security-admin/src/main/java/org/apache/ranger/view/RangerRoleList.java @@ -17,22 +17,21 @@ package org.apache.ranger.view; -import java.util.ArrayList; -import java.util.List; - -import org.apache.ranger.common.view.VList; -import org.apache.ranger.plugin.model.RangerRole; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; import com.fasterxml.jackson.annotation.JsonInclude; +import org.apache.ranger.common.view.VList; +import org.apache.ranger.plugin.model.RangerRole; + +import java.util.ArrayList; +import java.util.List; @JsonAutoDetect(getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE, fieldVisibility = Visibility.ANY) @JsonInclude(JsonInclude.Include.NON_NULL) -public class RangerRoleList extends VList{ - +public class RangerRoleList extends VList { private static final long serialVersionUID = 1L; - List roles = new ArrayList(); + List roles = new ArrayList<>(); public RangerRoleList() { super(); @@ -67,6 +66,4 @@ public int getListSize() { public List getList() { return roles; } - } - diff --git a/security-admin/src/main/java/org/apache/ranger/view/RangerSecurityZoneList.java b/security-admin/src/main/java/org/apache/ranger/view/RangerSecurityZoneList.java index c8165680ea..97d61d7611 100644 --- a/security-admin/src/main/java/org/apache/ranger/view/RangerSecurityZoneList.java +++ b/security-admin/src/main/java/org/apache/ranger/view/RangerSecurityZoneList.java @@ -17,51 +17,49 @@ package org.apache.ranger.view; -import java.util.ArrayList; -import java.util.List; - -import org.apache.ranger.common.view.VList; -import org.apache.ranger.plugin.model.RangerSecurityZone; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; import com.fasterxml.jackson.annotation.JsonInclude; +import org.apache.ranger.common.view.VList; +import org.apache.ranger.plugin.model.RangerSecurityZone; + +import java.util.ArrayList; +import java.util.List; @JsonAutoDetect(getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE, fieldVisibility = Visibility.ANY) @JsonInclude(JsonInclude.Include.NON_NULL) -public class RangerSecurityZoneList extends VList{ - - private static final long serialVersionUID = 1L; - - List securityZones = new ArrayList(); +public class RangerSecurityZoneList extends VList { + private static final long serialVersionUID = 1L; - public RangerSecurityZoneList() { - super(); - } + List securityZones = new ArrayList<>(); - public RangerSecurityZoneList(List objList) { - super(objList); - this.securityZones = objList; - } + public RangerSecurityZoneList() { + super(); + } - public List getSecurityZones() { - return securityZones; - } + public RangerSecurityZoneList(List objList) { + super(objList); + this.securityZones = objList; + } - public void setSecurityZoneList(List securityZones) { - this.securityZones = securityZones; - } + public List getSecurityZones() { + return securityZones; + } - @Override - public int getListSize() { - if (securityZones != null) { - return securityZones.size(); - } - return 0; - } + public void setSecurityZoneList(List securityZones) { + this.securityZones = securityZones; + } - @Override - public List getList() { - return securityZones; - } + @Override + public int getListSize() { + if (securityZones != null) { + return securityZones.size(); + } + return 0; + } + @Override + public List getList() { + return securityZones; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/view/RangerServiceDefList.java b/security-admin/src/main/java/org/apache/ranger/view/RangerServiceDefList.java index 6bb3f9254f..7f5211dd77 100644 --- a/security-admin/src/main/java/org/apache/ranger/view/RangerServiceDefList.java +++ b/security-admin/src/main/java/org/apache/ranger/view/RangerServiceDefList.java @@ -17,50 +17,49 @@ package org.apache.ranger.view; -import java.util.ArrayList; -import java.util.List; - -import org.apache.ranger.common.view.VList; -import org.apache.ranger.plugin.model.RangerServiceDef; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; import com.fasterxml.jackson.annotation.JsonInclude; +import org.apache.ranger.common.view.VList; +import org.apache.ranger.plugin.model.RangerServiceDef; + +import java.util.ArrayList; +import java.util.List; @JsonAutoDetect(getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE, fieldVisibility = Visibility.ANY) @JsonInclude(JsonInclude.Include.NON_NULL) public class RangerServiceDefList extends VList { - private static final long serialVersionUID = 1L; - - List serviceDefs = new ArrayList(); + private static final long serialVersionUID = 1L; - public RangerServiceDefList() { - super(); - } + List serviceDefs = new ArrayList<>(); - public RangerServiceDefList(List objList) { - super(objList); - this.serviceDefs = objList; - } + public RangerServiceDefList() { + super(); + } - public List getServiceDefs() { - return serviceDefs; - } + public RangerServiceDefList(List objList) { + super(objList); + this.serviceDefs = objList; + } - public void setServiceDefs(List serviceDefs) { - this.serviceDefs = serviceDefs; - } + public List getServiceDefs() { + return serviceDefs; + } - @Override - public int getListSize() { - if (serviceDefs != null) { - return serviceDefs.size(); - } - return 0; - } + public void setServiceDefs(List serviceDefs) { + this.serviceDefs = serviceDefs; + } - @Override - public List getList() { - return serviceDefs; - } + @Override + public int getListSize() { + if (serviceDefs != null) { + return serviceDefs.size(); + } + return 0; + } + @Override + public List getList() { + return serviceDefs; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/view/RangerServiceList.java b/security-admin/src/main/java/org/apache/ranger/view/RangerServiceList.java index 065667df33..215b16eb14 100644 --- a/security-admin/src/main/java/org/apache/ranger/view/RangerServiceList.java +++ b/security-admin/src/main/java/org/apache/ranger/view/RangerServiceList.java @@ -17,50 +17,49 @@ package org.apache.ranger.view; -import java.util.ArrayList; -import java.util.List; - -import org.apache.ranger.common.view.VList; -import org.apache.ranger.plugin.model.RangerService; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; import com.fasterxml.jackson.annotation.JsonInclude; +import org.apache.ranger.common.view.VList; +import org.apache.ranger.plugin.model.RangerService; + +import java.util.ArrayList; +import java.util.List; @JsonAutoDetect(getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE, fieldVisibility = Visibility.ANY) @JsonInclude(JsonInclude.Include.NON_NULL) public class RangerServiceList extends VList { - private static final long serialVersionUID = 1L; - - List services = new ArrayList(); + private static final long serialVersionUID = 1L; - public RangerServiceList() { - super(); - } + List services = new ArrayList<>(); - public RangerServiceList(List objList) { - super(objList); - this.services = objList; - } + public RangerServiceList() { + super(); + } - public List getServices() { - return services; - } + public RangerServiceList(List objList) { + super(objList); + this.services = objList; + } - public void setServices(List services) { - this.services = services; - } + public List getServices() { + return services; + } - @Override - public int getListSize() { - if (services != null) { - return services.size(); - } - return 0; - } + public void setServices(List services) { + this.services = services; + } - @Override - public List getList() { - return services; - } + @Override + public int getListSize() { + if (services != null) { + return services.size(); + } + return 0; + } + @Override + public List getList() { + return services; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/view/RangerServiceResourceWithTagsList.java b/security-admin/src/main/java/org/apache/ranger/view/RangerServiceResourceWithTagsList.java index cb9efe2ccc..5fc864fcef 100644 --- a/security-admin/src/main/java/org/apache/ranger/view/RangerServiceResourceWithTagsList.java +++ b/security-admin/src/main/java/org/apache/ranger/view/RangerServiceResourceWithTagsList.java @@ -17,46 +17,46 @@ package org.apache.ranger.view; -import java.util.List; - -import org.apache.ranger.common.view.VList; -import org.apache.ranger.plugin.model.RangerServiceResourceWithTags; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; import com.fasterxml.jackson.annotation.JsonInclude; +import org.apache.ranger.common.view.VList; +import org.apache.ranger.plugin.model.RangerServiceResourceWithTags; + +import java.util.List; @JsonAutoDetect(getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE, fieldVisibility = Visibility.ANY) @JsonInclude(JsonInclude.Include.NON_NULL) public class RangerServiceResourceWithTagsList extends VList { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; - List resourceList; + List resourceList; - public RangerServiceResourceWithTagsList() { - super(); - } + public RangerServiceResourceWithTagsList() { + super(); + } - public RangerServiceResourceWithTagsList(List objList) { - super(objList); + public RangerServiceResourceWithTagsList(List objList) { + super(objList); - this.resourceList = objList; - } + this.resourceList = objList; + } - public List getResourceList() { - return resourceList; - } + public List getResourceList() { + return resourceList; + } - public void setResourceList(List resourceList) { - this.resourceList = resourceList; - } + public void setResourceList(List resourceList) { + this.resourceList = resourceList; + } - @Override - public int getListSize() { - return (resourceList != null) ? resourceList.size() : 0; - } + @Override + public int getListSize() { + return (resourceList != null) ? resourceList.size() : 0; + } - @Override - public List getList() { - return resourceList; - } + @Override + public List getList() { + return resourceList; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/view/VXAccessAudit.java b/security-admin/src/main/java/org/apache/ranger/view/VXAccessAudit.java index ea2a781449..49a4f8d39d 100644 --- a/security-admin/src/main/java/org/apache/ranger/view/VXAccessAudit.java +++ b/security-admin/src/main/java/org/apache/ranger/view/VXAccessAudit.java @@ -17,684 +17,684 @@ * under the License. */ - package org.apache.ranger.view; +package org.apache.ranger.view; /** * Access Audit - * */ -import java.util.Date; - -import org.apache.ranger.common.AppConstants; -import org.apache.ranger.common.DateUtil; -import org.apache.ranger.common.RangerConstants; -import org.apache.ranger.json.JsonDateSerializer; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.databind.annotation.JsonSerialize; +import org.apache.ranger.common.AppConstants; +import org.apache.ranger.common.DateUtil; +import org.apache.ranger.common.RangerConstants; +import org.apache.ranger.json.JsonDateSerializer; + +import java.util.Date; -@JsonAutoDetect(getterVisibility=Visibility.NONE, setterVisibility=Visibility.NONE, fieldVisibility=Visibility.ANY) +@JsonAutoDetect(getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE, fieldVisibility = Visibility.ANY) @JsonInclude(JsonInclude.Include.NON_NULL) -@JsonIgnoreProperties(ignoreUnknown=true) +@JsonIgnoreProperties(ignoreUnknown = true) 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 = RangerConstants.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 Display Name - */ - protected String repoDisplayName; - /** - * Repository Type - */ - protected int repoType; - /** - * Service Type ~~ repoType - */ - protected String serviceType; - /** - * Service Type Display Name - */ - protected String serviceTypeDisplayName; - /** - * 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; - - protected long sequenceNumber; - - protected long eventCount; - - //event duration in ms - protected long eventDuration; - - protected String tags; - - protected String datasets; - - protected String projects; - - protected String clusterName; - - // Security Zone - protected String zoneName; - // Host Name - protected String agentHost; - - // Policy Version - - protected Long policyVersion; - - // Event ID - protected String eventId; - - //Zoned Event Time - protected String zonedEventTime; - - /** - * Default constructor. This will set all the attributes to default value. - */ - public VXAccessAudit ( ) { - accessResult = RangerConstants.ACCESS_RESULT_DENIED; - } - - /** - * This method sets the value to the member attribute auditType. - * You cannot set null to the attribute. - * @param auditType Value to set member attribute auditType - */ - public void setAuditType( int auditType ) { - this.auditType = auditType; - } - - /** - * Returns the value for the member attribute auditType - * @return int - value of member attribute auditType. - */ - public int getAuditType( ) { - return this.auditType; - } - - /** - * This method sets the value to the member attribute accessResult. - * You cannot set null to the attribute. - * @param accessResult Value to set member attribute accessResult - */ - public void setAccessResult( int accessResult ) { - this.accessResult = accessResult; - } - - /** - * Returns the value for the member attribute accessResult - * @return int - value of member attribute accessResult. - */ - public int getAccessResult( ) { - return this.accessResult; - } - - /** - * This method sets the value to the member attribute accessType. - * You cannot set null to the attribute. - * @param accessType Value to set member attribute accessType - */ - public void setAccessType( String accessType ) { - this.accessType = accessType; - } - - /** - * Returns the value for the member attribute accessType - * @return String - value of member attribute accessType. - */ - public String getAccessType( ) { - return this.accessType; - } - - /** - * This method sets the value to the member attribute aclEnforcer. - * You cannot set null to the attribute. - * @param aclEnforcer Value to set member attribute aclEnforcer - */ - public void setAclEnforcer( String aclEnforcer ) { - this.aclEnforcer = aclEnforcer; - } - - /** - * Returns the value for the member attribute aclEnforcer - * @return String - value of member attribute aclEnforcer. - */ - public String getAclEnforcer( ) { - return this.aclEnforcer; - } - - /** - * This method sets the value to the member attribute agentId. - * You cannot set null to the attribute. - * @param agentId Value to set member attribute agentId - */ - public void setAgentId( String agentId ) { - this.agentId = agentId; - } - - /** - * Returns the value for the member attribute agentId - * @return String - value of member attribute agentId. - */ - public String getAgentId( ) { - return this.agentId; - } - - /** - * This method sets the value to the member attribute clientIP. - * You cannot set null to the attribute. - * @param clientIP Value to set member attribute clientIP - */ - public void setClientIP( String clientIP ) { - this.clientIP = clientIP; - } - - /** - * Returns the value for the member attribute clientIP - * @return String - value of member attribute clientIP. - */ - public String getClientIP( ) { - return this.clientIP; - } - - /** - * This method sets the value to the member attribute clientType. - * You cannot set null to the attribute. - * @param clientType Value to set member attribute clientType - */ - public void setClientType( String clientType ) { - this.clientType = clientType; - } - - /** - * Returns the value for the member attribute clientType - * @return String - value of member attribute clientType. - */ - public String getClientType( ) { - return this.clientType; - } - - /** - * This method sets the value to the member attribute policyId. - * You cannot set null to the attribute. - * @param policyId Value to set member attribute policyId - */ - public void setPolicyId( long policyId ) { - this.policyId = policyId; - } - - /** - * Returns the value for the member attribute policyId - * @return long - value of member attribute policyId. - */ - public long getPolicyId( ) { - return this.policyId; - } - - /** - * This method sets the value to the member attribute repoName. - * You cannot set null to the attribute. - * @param repoName Value to set member attribute repoName - */ - public void setRepoName( String repoName ) { - this.repoName = repoName; - } - - /** - * Returns the value for the member attribute repoName - * @return String - value of member attribute repoName. - */ - public String getRepoName( ) { - return this.repoName; - } - - /** - * This method sets the value to the member attribute repoDisplayName. - * You cannot set null to the attribute. - * @param repoDisplayName Value to set member attribute repoDisplayName - */ - public void setRepoDisplayName(String repoDisplayName) { - this.repoDisplayName = repoDisplayName; - } - - /** - * Returns the value for the member attribute repoDisplayName - * @return String - value of member attribute repoDisplayName. - */ - public String getRepoDisplayName() { - return repoDisplayName; - } - - /** - * This method sets the value to the member attribute repoType. - * You cannot set null to the attribute. - * @param repoType Value to set member attribute repoType - */ - public void setRepoType( int repoType ) { - this.repoType = repoType; - } - - /** - * Returns the value for the member attribute repoType - * @return int - value of member attribute repoType. - */ - public int getRepoType( ) { - return this.repoType; - } - - /** - * @return the serviceType - */ - public String getServiceType() { - return serviceType; - } - - /** - * @param serviceType the serviceType to set - */ - public void setServiceType(String serviceType) { - this.serviceType = serviceType; - } - - /** - * @return the serviceTypeDisplayName - */ - public String getServiceTypeDisplayName() { - return serviceTypeDisplayName; - } - - /** - * @param serviceTypeDisplayName the serviceTypeDisplayName to set - */ - public void setServiceTypeDisplayName(String serviceTypeDisplayName) { - this.serviceTypeDisplayName = serviceTypeDisplayName; - } - - /** - * This method sets the value to the member attribute resultReason. - * You cannot set null to the attribute. - * @param resultReason Value to set member attribute resultReason - */ - public void setResultReason( String resultReason ) { - this.resultReason = resultReason; - } - - /** - * Returns the value for the member attribute resultReason - * @return String - value of member attribute resultReason. - */ - public String getResultReason( ) { - return this.resultReason; - } - - /** - * This method sets the value to the member attribute sessionId. - * You cannot set null to the attribute. - * @param sessionId Value to set member attribute sessionId - */ - public void setSessionId( String sessionId ) { - this.sessionId = sessionId; - } - - /** - * Returns the value for the member attribute sessionId - * @return String - value of member attribute sessionId. - */ - public String getSessionId( ) { - return this.sessionId; - } - - /** - * This method sets the value to the member attribute eventTime. - * You cannot set null to the attribute. - * @param eventTime Value to set member attribute eventTime - */ - public void setEventTime( Date eventTime ) { - this.eventTime = eventTime; - } - - /** - * Returns the value for the member attribute eventTime - * @return Date - value of member attribute eventTime. - */ - public Date getEventTime( ) { - return this.eventTime; - } - - /** - * This method sets the value to the member attribute requestUser. - * You cannot set null to the attribute. - * @param requestUser Value to set member attribute requestUser - */ - public void setRequestUser( String requestUser ) { - this.requestUser = requestUser; - } - - /** - * Returns the value for the member attribute requestUser - * @return String - value of member attribute requestUser. - */ - public String getRequestUser( ) { - return this.requestUser; - } - - /** - * This method sets the value to the member attribute action. - * You cannot set null to the attribute. - * @param action Value to set member attribute action - */ - public void setAction( String action ) { - this.action = action; - } - - /** - * Returns the value for the member attribute action - * @return String - value of member attribute action. - */ - public String getAction( ) { - return this.action; - } - - /** - * This method sets the value to the member attribute requestData. - * You cannot set null to the attribute. - * @param requestData Value to set member attribute requestData - */ - public void setRequestData( String requestData ) { - this.requestData = requestData; - } - - /** - * Returns the value for the member attribute requestData - * @return String - value of member attribute requestData. - */ - public String getRequestData( ) { - return this.requestData; - } - - /** - * This method sets the value to the member attribute resourcePath. - * You cannot set null to the attribute. - * @param resourcePath Value to set member attribute resourcePath - */ - public void setResourcePath( String resourcePath ) { - this.resourcePath = resourcePath; - } - - /** - * Returns the value for the member attribute resourcePath - * @return String - value of member attribute resourcePath. - */ - public String getResourcePath( ) { - return this.resourcePath; - } - - /** - * This method sets the value to the member attribute resourceType. - * You cannot set null to the attribute. - * @param resourceType Value to set member attribute resourceType - */ - public void setResourceType( String resourceType ) { - this.resourceType = resourceType; - } - - /** - * Returns the value for the member attribute resourceType - * @return String - value of member attribute resourceType. - */ - public String getResourceType( ) { - return this.resourceType; - } - - public long getSequenceNumber() { - return sequenceNumber; - } - - public void setSequenceNumber(long sequenceNumber) { - this.sequenceNumber = sequenceNumber; - } - - public long getEventCount() { - return eventCount; - } - - public void setEventCount(long eventCount) { - this.eventCount = eventCount; - } - - public long getEventDuration() { - return eventDuration; - } - - public void setEventDuration(long eventDuration) { - this.eventDuration = eventDuration; - } - - /** - * @return the tags - */ - public String getTags() { - return tags; - } - - /** - * @param tags - * the tags to set - */ - public void setTags(String tags) { - this.tags = tags; - } - - public String getDatasets() { - return datasets; - } - - public void setDatasets(String datasets) { - this.datasets = datasets; - } - - public String getProjects() { - return projects; - } - - public void setProjects(String projects) { - this.projects = projects; - } - - - /** - * @return the clusterName - */ - public String getClusterName() { - return clusterName; - } - /** - * @param clusterName - * the clusterName to set - */ - public void setClusterName(String clusterName) { - this.clusterName = clusterName; - } - - @Override - public int getMyClassType( ) { - return AppConstants.CLASS_TYPE_XA_ACCESS_AUDIT; - } - - /** - * @return the zoneName - */ - public String getZoneName() { - return zoneName; - } - /** - * @param zoneName - * the zoneName to set - */ - public void setZoneName(String zoneName) { - this.zoneName = zoneName; - } - - public String getAgentHost() { - return agentHost; - } - - public void setAgentHost(String agentHost) { - this.agentHost = agentHost; - } - - /** - * @return the policyVersion - */ - public Long getPolicyVersion() { - return policyVersion; - } - /** - * @param policyVersion - * the policyVersion to set - */ - public void setPolicyVersion(Long policyVersion) { - this.policyVersion = policyVersion; - } - - public String getEventId() { - return eventId; - } - - public void setEventId(String eventId) { - this.eventId = eventId; - } - - /** - * Returns the value for the member attribute zonedEventTime - * @return Date - value of member attribute zonedEventTime. - */ - public String getZonedEventTime( ) { - return this.zonedEventTime; - } - - /** - * This method sets the value to the member attribute zonedEventTime. - * You cannot set null to the attribute. - * @param zonedEventTime Value to set member attribute zonedEventTime - */ - public void setZonedEventTime( String zonedEventTime ) { - this.zonedEventTime = zonedEventTime; - } - - /** - * 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 += "policyVersion={" + policyVersion + "} "; - str += "repoName={" + repoName + "} "; - str += "repoDisplayName={" + repoDisplayName + "} "; - str += "repoType={" + repoType + "} "; - str += "serviceType={" + serviceType + "} "; - str += "serviceTypeDisplayName={" + serviceTypeDisplayName + "} "; - 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 += "sequenceNumber={" + sequenceNumber + "}"; - str += "eventCount={" + eventCount + "}"; - str += "eventDuration={" + eventDuration + "}"; - str += "tags={" + tags + "}"; - str += "datasets={" + datasets + "}"; - str += "projects={" + projects + "}"; - str += "clusterName={" + clusterName + "}"; - str += "zoneName={" + zoneName + "}"; - str += "agentHost={" + agentHost + "}"; - str += "eventId={" + eventId + "}"; - str += "zonedEventTime={" + zonedEventTime + "} "; - str += "}"; - return str; - } + private static final long serialVersionUID = 1L; + + /** + * Repository Type + */ + protected int auditType; + /** + * Access Result + * This attribute is of type enum CommonEnums::AccessResult + */ + protected int accessResult = RangerConstants.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 Display Name + */ + protected String repoDisplayName; + /** + * Repository Type + */ + protected int repoType; + /** + * Service Type ~~ repoType + */ + protected String serviceType; + /** + * Service Type Display Name + */ + protected String serviceTypeDisplayName; + /** + * 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; + + protected long sequenceNumber; + + protected long eventCount; + + //event duration in ms + protected long eventDuration; + + protected String tags; + + protected String datasets; + + protected String projects; + + protected String clusterName; + + // Security Zone + protected String zoneName; + // Host Name + protected String agentHost; + + // Policy Version + + protected Long policyVersion; + + // Event ID + protected String eventId; + + //Zoned Event Time + protected String zonedEventTime; + + /** + * Default constructor. This will set all the attributes to default value. + */ + public VXAccessAudit() { + accessResult = RangerConstants.ACCESS_RESULT_DENIED; + } + + /** + * Returns the value for the member attribute auditType + * @return int - value of member attribute auditType. + */ + public int getAuditType() { + return this.auditType; + } + + /** + * This method sets the value to the member attribute auditType. + * You cannot set null to the attribute. + * @param auditType Value to set member attribute auditType + */ + public void setAuditType(int auditType) { + this.auditType = auditType; + } + + /** + * Returns the value for the member attribute accessResult + * @return int - value of member attribute accessResult. + */ + public int getAccessResult() { + return this.accessResult; + } + + /** + * This method sets the value to the member attribute accessResult. + * You cannot set null to the attribute. + * @param accessResult Value to set member attribute accessResult + */ + public void setAccessResult(int accessResult) { + this.accessResult = accessResult; + } + + /** + * Returns the value for the member attribute accessType + * @return String - value of member attribute accessType. + */ + public String getAccessType() { + return this.accessType; + } + + /** + * This method sets the value to the member attribute accessType. + * You cannot set null to the attribute. + * @param accessType Value to set member attribute accessType + */ + public void setAccessType(String accessType) { + this.accessType = accessType; + } + + /** + * Returns the value for the member attribute aclEnforcer + * @return String - value of member attribute aclEnforcer. + */ + public String getAclEnforcer() { + return this.aclEnforcer; + } + + /** + * This method sets the value to the member attribute aclEnforcer. + * You cannot set null to the attribute. + * @param aclEnforcer Value to set member attribute aclEnforcer + */ + public void setAclEnforcer(String aclEnforcer) { + this.aclEnforcer = aclEnforcer; + } + + /** + * Returns the value for the member attribute agentId + * @return String - value of member attribute agentId. + */ + public String getAgentId() { + return this.agentId; + } + + /** + * This method sets the value to the member attribute agentId. + * You cannot set null to the attribute. + * @param agentId Value to set member attribute agentId + */ + public void setAgentId(String agentId) { + this.agentId = agentId; + } + + /** + * Returns the value for the member attribute clientIP + * @return String - value of member attribute clientIP. + */ + public String getClientIP() { + return this.clientIP; + } + + /** + * This method sets the value to the member attribute clientIP. + * You cannot set null to the attribute. + * @param clientIP Value to set member attribute clientIP + */ + public void setClientIP(String clientIP) { + this.clientIP = clientIP; + } + + /** + * Returns the value for the member attribute clientType + * @return String - value of member attribute clientType. + */ + public String getClientType() { + return this.clientType; + } + + /** + * This method sets the value to the member attribute clientType. + * You cannot set null to the attribute. + * @param clientType Value to set member attribute clientType + */ + public void setClientType(String clientType) { + this.clientType = clientType; + } + + /** + * Returns the value for the member attribute policyId + * @return long - value of member attribute policyId. + */ + public long getPolicyId() { + return this.policyId; + } + + /** + * This method sets the value to the member attribute policyId. + * You cannot set null to the attribute. + * @param policyId Value to set member attribute policyId + */ + public void setPolicyId(long policyId) { + this.policyId = policyId; + } + + /** + * Returns the value for the member attribute repoName + * @return String - value of member attribute repoName. + */ + public String getRepoName() { + return this.repoName; + } + + /** + * This method sets the value to the member attribute repoName. + * You cannot set null to the attribute. + * @param repoName Value to set member attribute repoName + */ + public void setRepoName(String repoName) { + this.repoName = repoName; + } + + /** + * Returns the value for the member attribute repoDisplayName + * @return String - value of member attribute repoDisplayName. + */ + public String getRepoDisplayName() { + return repoDisplayName; + } + + /** + * This method sets the value to the member attribute repoDisplayName. + * You cannot set null to the attribute. + * @param repoDisplayName Value to set member attribute repoDisplayName + */ + public void setRepoDisplayName(String repoDisplayName) { + this.repoDisplayName = repoDisplayName; + } + + /** + * Returns the value for the member attribute repoType + * @return int - value of member attribute repoType. + */ + public int getRepoType() { + return this.repoType; + } + + /** + * This method sets the value to the member attribute repoType. + * You cannot set null to the attribute. + * @param repoType Value to set member attribute repoType + */ + public void setRepoType(int repoType) { + this.repoType = repoType; + } + + /** + * @return the serviceType + */ + public String getServiceType() { + return serviceType; + } + + /** + * @param serviceType the serviceType to set + */ + public void setServiceType(String serviceType) { + this.serviceType = serviceType; + } + + /** + * @return the serviceTypeDisplayName + */ + public String getServiceTypeDisplayName() { + return serviceTypeDisplayName; + } + + /** + * @param serviceTypeDisplayName the serviceTypeDisplayName to set + */ + public void setServiceTypeDisplayName(String serviceTypeDisplayName) { + this.serviceTypeDisplayName = serviceTypeDisplayName; + } + + /** + * Returns the value for the member attribute resultReason + * @return String - value of member attribute resultReason. + */ + public String getResultReason() { + return this.resultReason; + } + + /** + * This method sets the value to the member attribute resultReason. + * You cannot set null to the attribute. + * @param resultReason Value to set member attribute resultReason + */ + public void setResultReason(String resultReason) { + this.resultReason = resultReason; + } + + /** + * Returns the value for the member attribute sessionId + * @return String - value of member attribute sessionId. + */ + public String getSessionId() { + return this.sessionId; + } + + /** + * This method sets the value to the member attribute sessionId. + * You cannot set null to the attribute. + * @param sessionId Value to set member attribute sessionId + */ + public void setSessionId(String sessionId) { + this.sessionId = sessionId; + } + + /** + * Returns the value for the member attribute eventTime + * @return Date - value of member attribute eventTime. + */ + public Date getEventTime() { + return this.eventTime; + } + + /** + * This method sets the value to the member attribute eventTime. + * You cannot set null to the attribute. + * @param eventTime Value to set member attribute eventTime + */ + public void setEventTime(Date eventTime) { + this.eventTime = eventTime; + } + + /** + * Returns the value for the member attribute requestUser + * @return String - value of member attribute requestUser. + */ + public String getRequestUser() { + return this.requestUser; + } + + /** + * This method sets the value to the member attribute requestUser. + * You cannot set null to the attribute. + * @param requestUser Value to set member attribute requestUser + */ + public void setRequestUser(String requestUser) { + this.requestUser = requestUser; + } + + /** + * Returns the value for the member attribute action + * @return String - value of member attribute action. + */ + public String getAction() { + return this.action; + } + + /** + * This method sets the value to the member attribute action. + * You cannot set null to the attribute. + * @param action Value to set member attribute action + */ + public void setAction(String action) { + this.action = action; + } + + /** + * Returns the value for the member attribute requestData + * @return String - value of member attribute requestData. + */ + public String getRequestData() { + return this.requestData; + } + + /** + * This method sets the value to the member attribute requestData. + * You cannot set null to the attribute. + * @param requestData Value to set member attribute requestData + */ + public void setRequestData(String requestData) { + this.requestData = requestData; + } + + /** + * Returns the value for the member attribute resourcePath + * @return String - value of member attribute resourcePath. + */ + public String getResourcePath() { + return this.resourcePath; + } + + /** + * This method sets the value to the member attribute resourcePath. + * You cannot set null to the attribute. + * @param resourcePath Value to set member attribute resourcePath + */ + public void setResourcePath(String resourcePath) { + this.resourcePath = resourcePath; + } + + /** + * Returns the value for the member attribute resourceType + * @return String - value of member attribute resourceType. + */ + public String getResourceType() { + return this.resourceType; + } + + /** + * This method sets the value to the member attribute resourceType. + * You cannot set null to the attribute. + * @param resourceType Value to set member attribute resourceType + */ + public void setResourceType(String resourceType) { + this.resourceType = resourceType; + } + + public long getSequenceNumber() { + return sequenceNumber; + } + + public void setSequenceNumber(long sequenceNumber) { + this.sequenceNumber = sequenceNumber; + } + + public long getEventCount() { + return eventCount; + } + + public void setEventCount(long eventCount) { + this.eventCount = eventCount; + } + + public long getEventDuration() { + return eventDuration; + } + + public void setEventDuration(long eventDuration) { + this.eventDuration = eventDuration; + } + + /** + * @return the tags + */ + public String getTags() { + return tags; + } + + /** + * @param tags + * the tags to set + */ + public void setTags(String tags) { + this.tags = tags; + } + + public String getDatasets() { + return datasets; + } + + public void setDatasets(String datasets) { + this.datasets = datasets; + } + + public String getProjects() { + return projects; + } + + public void setProjects(String projects) { + this.projects = projects; + } + + /** + * @return the clusterName + */ + public String getClusterName() { + return clusterName; + } + + /** + * @param clusterName + * the clusterName to set + */ + public void setClusterName(String clusterName) { + this.clusterName = clusterName; + } + + @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 += "policyVersion={" + policyVersion + "} "; + str += "repoName={" + repoName + "} "; + str += "repoDisplayName={" + repoDisplayName + "} "; + str += "repoType={" + repoType + "} "; + str += "serviceType={" + serviceType + "} "; + str += "serviceTypeDisplayName={" + serviceTypeDisplayName + "} "; + 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 += "sequenceNumber={" + sequenceNumber + "}"; + str += "eventCount={" + eventCount + "}"; + str += "eventDuration={" + eventDuration + "}"; + str += "tags={" + tags + "}"; + str += "datasets={" + datasets + "}"; + str += "projects={" + projects + "}"; + str += "clusterName={" + clusterName + "}"; + str += "zoneName={" + zoneName + "}"; + str += "agentHost={" + agentHost + "}"; + str += "eventId={" + eventId + "}"; + str += "zonedEventTime={" + zonedEventTime + "} "; + str += "}"; + return str; + } + + /** + * @return the zoneName + */ + public String getZoneName() { + return zoneName; + } + + /** + * @param zoneName + * the zoneName to set + */ + public void setZoneName(String zoneName) { + this.zoneName = zoneName; + } + + public String getAgentHost() { + return agentHost; + } + + public void setAgentHost(String agentHost) { + this.agentHost = agentHost; + } + + /** + * @return the policyVersion + */ + public Long getPolicyVersion() { + return policyVersion; + } + + /** + * @param policyVersion + * the policyVersion to set + */ + public void setPolicyVersion(Long policyVersion) { + this.policyVersion = policyVersion; + } + + public String getEventId() { + return eventId; + } + + public void setEventId(String eventId) { + this.eventId = eventId; + } + + /** + * Returns the value for the member attribute zonedEventTime + * @return Date - value of member attribute zonedEventTime. + */ + public String getZonedEventTime() { + return this.zonedEventTime; + } + + /** + * This method sets the value to the member attribute zonedEventTime. + * You cannot set null to the attribute. + * @param zonedEventTime Value to set member attribute zonedEventTime + */ + public void setZonedEventTime(String zonedEventTime) { + this.zonedEventTime = zonedEventTime; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/view/VXAccessAuditList.java b/security-admin/src/main/java/org/apache/ranger/view/VXAccessAuditList.java index 5fc7b0c1fa..73a005e8a5 100644 --- a/security-admin/src/main/java/org/apache/ranger/view/VXAccessAuditList.java +++ b/security-admin/src/main/java/org/apache/ranger/view/VXAccessAuditList.java @@ -17,35 +17,35 @@ * under the License. */ - package org.apache.ranger.view; +package org.apache.ranger.view; /** * List wrapper class for VXAccessAudit - * */ -import java.util.ArrayList; -import java.util.List; - -import org.apache.ranger.common.view.VList; -import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import org.apache.ranger.common.view.VList; + +import java.util.ArrayList; +import java.util.List; -@JsonAutoDetect(getterVisibility=Visibility.NONE, setterVisibility=Visibility.NONE, fieldVisibility=Visibility.ANY) +@JsonAutoDetect(getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE, fieldVisibility = Visibility.ANY) @JsonInclude(JsonInclude.Include.NON_NULL) public class VXAccessAuditList extends VList { - private static final long serialVersionUID = 1L; - List vXAccessAudits = new ArrayList(); + private static final long serialVersionUID = 1L; + + List vXAccessAudits = new ArrayList<>(); public VXAccessAuditList() { - super(); + super(); } public VXAccessAuditList(List objList) { - super(objList); - this.vXAccessAudits = objList; + super(objList); + this.vXAccessAudits = objList; } /** @@ -53,7 +53,7 @@ public VXAccessAuditList(List objList) { */ @JsonProperty("vXAccessAudits") public List getVXAccessAudits() { - return vXAccessAudits; + return vXAccessAudits; } /** @@ -62,20 +62,19 @@ public List getVXAccessAudits() { */ @JsonProperty("vXAccessAudits") public void setVXAccessAudits(List vXAccessAudits) { - this.vXAccessAudits = vXAccessAudits; + this.vXAccessAudits = vXAccessAudits; } @Override public int getListSize() { - if (vXAccessAudits != null) { - return vXAccessAudits.size(); - } - return 0; + if (vXAccessAudits != null) { + return vXAccessAudits.size(); + } + return 0; } @Override public List getList() { - return vXAccessAudits; + return vXAccessAudits; } - } diff --git a/security-admin/src/main/java/org/apache/ranger/view/VXAsset.java b/security-admin/src/main/java/org/apache/ranger/view/VXAsset.java index 12ad069262..66be77ff84 100644 --- a/security-admin/src/main/java/org/apache/ranger/view/VXAsset.java +++ b/security-admin/src/main/java/org/apache/ranger/view/VXAsset.java @@ -17,182 +17,180 @@ * under the License. */ - package org.apache.ranger.view; +package org.apache.ranger.view; /** * Asset - * */ -import org.apache.ranger.common.AppConstants; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; +import org.apache.ranger.common.AppConstants; -@JsonAutoDetect(getterVisibility=Visibility.NONE, setterVisibility=Visibility.NONE, fieldVisibility=Visibility.ANY) +@JsonAutoDetect(getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE, fieldVisibility = Visibility.ANY) @JsonInclude(JsonInclude.Include.NON_NULL) -@JsonIgnoreProperties(ignoreUnknown=true) +@JsonIgnoreProperties(ignoreUnknown = true) 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 name. - * You cannot set null to the attribute. - * @param name Value to set member attribute name - */ - public void setName( String name ) { - this.name = name; - } - - /** - * Returns the value for the member attribute name - * @return String - value of member attribute name. - */ - public String getName( ) { - return this.name; - } - - /** - * This method sets the value to the member attribute description. - * You cannot set null to the attribute. - * @param description Value to set member attribute description - */ - public void setDescription( String description ) { - this.description = description; - } - - /** - * Returns the value for the member attribute description - * @return String - value of member attribute description. - */ - public String getDescription( ) { - return this.description; - } - - /** - * This method sets the value to the member attribute activeStatus. - * You cannot set null to the attribute. - * @param activeStatus Value to set member attribute activeStatus - */ - public void setActiveStatus( int activeStatus ) { - this.activeStatus = activeStatus; - } - - /** - * Returns the value for the member attribute activeStatus - * @return int - value of member attribute activeStatus. - */ - public int getActiveStatus( ) { - return this.activeStatus; - } - - /** - * This method sets the value to the member attribute assetType. - * You cannot set null to the attribute. - * @param assetType Value to set member attribute assetType - */ - public void setAssetType( int assetType ) { - this.assetType = assetType; - } - - /** - * Returns the value for the member attribute assetType - * @return int - value of member attribute assetType. - */ - public int getAssetType( ) { - return this.assetType; - } - - /** - * This method sets the value to the member attribute config. - * You cannot set null to the attribute. - * @param config Value to set member attribute config - */ - public void setConfig( String config ) { - this.config = config; - } - - /** - * Returns the value for the member attribute config - * @return String - value of member attribute config. - */ - public String getConfig( ) { - return this.config; - } - - /** - * This method sets the value to the member attribute supportNative. - * You cannot set null to the attribute. - * @param supportNative Value to set member attribute supportNative - */ - public void setSupportNative( boolean supportNative ) { - this.supportNative = supportNative; - } - - /** - * Returns the value for the member attribute supportNative - * @return boolean - value of member attribute supportNative. - */ - 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; - } + 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; + + /** + * Default constructor. This will set all the attributes to default value. + */ + public VXAsset() { + activeStatus = 0; + assetType = AppConstants.ASSET_UNKNOWN; + } + + /** + * Returns the value for the member attribute name + * @return String - value of member attribute name. + */ + public String getName() { + return this.name; + } + + /** + * This method sets the value to the member attribute name. + * You cannot set null to the attribute. + * @param name Value to set member attribute name + */ + public void setName(String name) { + this.name = name; + } + + /** + * Returns the value for the member attribute description + * @return String - value of member attribute description. + */ + public String getDescription() { + return this.description; + } + + /** + * This method sets the value to the member attribute description. + * You cannot set null to the attribute. + * @param description Value to set member attribute description + */ + public void setDescription(String description) { + this.description = description; + } + + /** + * Returns the value for the member attribute activeStatus + * @return int - value of member attribute activeStatus. + */ + public int getActiveStatus() { + return this.activeStatus; + } + + /** + * This method sets the value to the member attribute activeStatus. + * You cannot set null to the attribute. + * @param activeStatus Value to set member attribute activeStatus + */ + public void setActiveStatus(int activeStatus) { + this.activeStatus = activeStatus; + } + + /** + * Returns the value for the member attribute assetType + * @return int - value of member attribute assetType. + */ + public int getAssetType() { + return this.assetType; + } + + /** + * This method sets the value to the member attribute assetType. + * You cannot set null to the attribute. + * @param assetType Value to set member attribute assetType + */ + public void setAssetType(int assetType) { + this.assetType = assetType; + } + + /** + * Returns the value for the member attribute config + * @return String - value of member attribute config. + */ + public String getConfig() { + return this.config; + } + + /** + * This method sets the value to the member attribute config. + * You cannot set null to the attribute. + * @param config Value to set member attribute config + */ + public void setConfig(String config) { + this.config = config; + } + + /** + * Returns the value for the member attribute supportNative + * @return boolean - value of member attribute supportNative. + */ + public boolean isSupportNative() { + return this.supportNative; + } + + /** + * This method sets the value to the member attribute supportNative. + * You cannot set null to the attribute. + * @param supportNative Value to set member attribute supportNative + */ + public void setSupportNative(boolean supportNative) { + this.supportNative = 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; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/view/VXAssetList.java b/security-admin/src/main/java/org/apache/ranger/view/VXAssetList.java index 0c5817b37e..7752f04a10 100644 --- a/security-admin/src/main/java/org/apache/ranger/view/VXAssetList.java +++ b/security-admin/src/main/java/org/apache/ranger/view/VXAssetList.java @@ -17,35 +17,35 @@ * under the License. */ - package org.apache.ranger.view; +package org.apache.ranger.view; /** * List wrapper class for VXAsset - * */ -import java.util.ArrayList; -import java.util.List; - -import org.apache.ranger.common.view.VList; -import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import org.apache.ranger.common.view.VList; + +import java.util.ArrayList; +import java.util.List; -@JsonAutoDetect(getterVisibility=Visibility.NONE, setterVisibility=Visibility.NONE, fieldVisibility=Visibility.ANY) +@JsonAutoDetect(getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE, fieldVisibility = Visibility.ANY) @JsonInclude(JsonInclude.Include.NON_NULL) public class VXAssetList extends VList { - private static final long serialVersionUID = 1L; - List vXAssets = new ArrayList(); + private static final long serialVersionUID = 1L; + + List vXAssets = new ArrayList<>(); public VXAssetList() { - super(); + super(); } public VXAssetList(List objList) { - super(objList); - this.vXAssets = objList; + super(objList); + this.vXAssets = objList; } /** @@ -53,7 +53,7 @@ public VXAssetList(List objList) { */ @JsonProperty("vXAssets") public List getVXAssets() { - return vXAssets; + return vXAssets; } /** @@ -62,20 +62,19 @@ public List getVXAssets() { */ @JsonProperty("vXAssets") public void setVXAssets(List vXAssets) { - this.vXAssets = vXAssets; + this.vXAssets = vXAssets; } @Override public int getListSize() { - if (vXAssets != null) { - return vXAssets.size(); - } - return 0; + if (vXAssets != null) { + return vXAssets.size(); + } + return 0; } @Override public List getList() { - return vXAssets; + return vXAssets; } - } diff --git a/security-admin/src/main/java/org/apache/ranger/view/VXAuditMap.java b/security-admin/src/main/java/org/apache/ranger/view/VXAuditMap.java index d421b1eb10..9ff501b65e 100644 --- a/security-admin/src/main/java/org/apache/ranger/view/VXAuditMap.java +++ b/security-admin/src/main/java/org/apache/ranger/view/VXAuditMap.java @@ -17,136 +17,134 @@ * under the License. */ - package org.apache.ranger.view; +package org.apache.ranger.view; /** * Audi map - * */ -import org.apache.ranger.common.AppConstants; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; +import org.apache.ranger.common.AppConstants; -@JsonAutoDetect(getterVisibility=Visibility.NONE, setterVisibility=Visibility.NONE, fieldVisibility=Visibility.ANY) +@JsonAutoDetect(getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE, fieldVisibility = Visibility.ANY) @JsonInclude(JsonInclude.Include.NON_NULL) -@JsonIgnoreProperties(ignoreUnknown=true) +@JsonIgnoreProperties(ignoreUnknown = true) 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 resourceId. - * You cannot set null to the attribute. - * @param resourceId Value to set member attribute resourceId - */ - public void setResourceId( Long resourceId ) { - this.resourceId = resourceId; - } - - /** - * Returns the value for the member attribute resourceId - * @return Long - value of member attribute resourceId. - */ - public Long getResourceId( ) { - return this.resourceId; - } - - /** - * This method sets the value to the member attribute groupId. - * You cannot set null to the attribute. - * @param groupId Value to set member attribute groupId - */ - public void setGroupId( Long groupId ) { - this.groupId = groupId; - } - - /** - * Returns the value for the member attribute groupId - * @return Long - value of member attribute groupId. - */ - public Long getGroupId( ) { - return this.groupId; - } - - /** - * This method sets the value to the member attribute userId. - * You cannot set null to the attribute. - * @param userId Value to set member attribute userId - */ - public void setUserId( Long userId ) { - this.userId = userId; - } - - /** - * Returns the value for the member attribute userId - * @return Long - value of member attribute userId. - */ - public Long getUserId( ) { - return this.userId; - } - - /** - * This method sets the value to the member attribute auditType. - * You cannot set null to the attribute. - * @param auditType Value to set member attribute auditType - */ - public void setAuditType( int auditType ) { - this.auditType = auditType; - } - - /** - * Returns the value for the member attribute auditType - * @return int - value of member attribute auditType. - */ - 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; - } + 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; + } + + /** + * Returns the value for the member attribute resourceId + * @return Long - value of member attribute resourceId. + */ + public Long getResourceId() { + return this.resourceId; + } + + /** + * This method sets the value to the member attribute resourceId. + * You cannot set null to the attribute. + * @param resourceId Value to set member attribute resourceId + */ + public void setResourceId(Long resourceId) { + this.resourceId = resourceId; + } + + /** + * Returns the value for the member attribute groupId + * @return Long - value of member attribute groupId. + */ + public Long getGroupId() { + return this.groupId; + } + + /** + * This method sets the value to the member attribute groupId. + * You cannot set null to the attribute. + * @param groupId Value to set member attribute groupId + */ + public void setGroupId(Long groupId) { + this.groupId = groupId; + } + + /** + * Returns the value for the member attribute userId + * @return Long - value of member attribute userId. + */ + public Long getUserId() { + return this.userId; + } + + /** + * This method sets the value to the member attribute userId. + * You cannot set null to the attribute. + * @param userId Value to set member attribute userId + */ + public void setUserId(Long userId) { + this.userId = userId; + } + + /** + * Returns the value for the member attribute auditType + * @return int - value of member attribute auditType. + */ + public int getAuditType() { + return this.auditType; + } + + /** + * This method sets the value to the member attribute auditType. + * You cannot set null to the attribute. + * @param auditType Value to set member attribute auditType + */ + public void setAuditType(int auditType) { + this.auditType = 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; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/view/VXAuditMapList.java b/security-admin/src/main/java/org/apache/ranger/view/VXAuditMapList.java index a8fd942c49..e945d3a802 100644 --- a/security-admin/src/main/java/org/apache/ranger/view/VXAuditMapList.java +++ b/security-admin/src/main/java/org/apache/ranger/view/VXAuditMapList.java @@ -17,35 +17,35 @@ * under the License. */ - package org.apache.ranger.view; +package org.apache.ranger.view; /** * List wrapper class for VXAuditMap - * */ -import java.util.ArrayList; -import java.util.List; - -import org.apache.ranger.common.view.VList; -import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import org.apache.ranger.common.view.VList; + +import java.util.ArrayList; +import java.util.List; -@JsonAutoDetect(getterVisibility=Visibility.NONE, setterVisibility=Visibility.NONE, fieldVisibility=Visibility.ANY) +@JsonAutoDetect(getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE, fieldVisibility = Visibility.ANY) @JsonInclude(JsonInclude.Include.NON_NULL) public class VXAuditMapList extends VList { - private static final long serialVersionUID = 1L; - List vXAuditMaps = new ArrayList(); + private static final long serialVersionUID = 1L; + + List vXAuditMaps = new ArrayList<>(); public VXAuditMapList() { - super(); + super(); } public VXAuditMapList(List objList) { - super(objList); - this.vXAuditMaps = objList; + super(objList); + this.vXAuditMaps = objList; } /** @@ -53,7 +53,7 @@ public VXAuditMapList(List objList) { */ @JsonProperty("vXAuditMaps") public List getVXAuditMaps() { - return vXAuditMaps; + return vXAuditMaps; } /** @@ -62,20 +62,19 @@ public List getVXAuditMaps() { */ @JsonProperty("vXAuditMaps") public void setVXAuditMaps(List vXAuditMaps) { - this.vXAuditMaps = vXAuditMaps; + this.vXAuditMaps = vXAuditMaps; } @Override public int getListSize() { - if (vXAuditMaps != null) { - return vXAuditMaps.size(); - } - return 0; + if (vXAuditMaps != null) { + return vXAuditMaps.size(); + } + return 0; } @Override public List getList() { - return vXAuditMaps; + return vXAuditMaps; } - } diff --git a/security-admin/src/main/java/org/apache/ranger/view/VXAuditRecord.java b/security-admin/src/main/java/org/apache/ranger/view/VXAuditRecord.java index b62032b90e..a585d82288 100644 --- a/security-admin/src/main/java/org/apache/ranger/view/VXAuditRecord.java +++ b/security-admin/src/main/java/org/apache/ranger/view/VXAuditRecord.java @@ -17,219 +17,232 @@ * under the License. */ - package org.apache.ranger.view; +package org.apache.ranger.view; -import java.util.Date; - -import org.apache.ranger.common.AppConstants; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; import com.fasterxml.jackson.annotation.JsonInclude; +import org.apache.ranger.common.AppConstants; -@JsonAutoDetect(getterVisibility=Visibility.NONE, setterVisibility=Visibility.NONE, fieldVisibility=Visibility.ANY) +import java.util.Date; + +@JsonAutoDetect(getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE, fieldVisibility = Visibility.ANY) @JsonInclude(JsonInclude.Include.NON_NULL) 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 date - * @return Date - value of member attribute date. - */ - public Date getDate() { - return date; - } - - /** - * This method sets the value to the member attribute date. - * You cannot set null to the attribute. - * @param date Value to set member attribute date - */ - public void setDate(Date date) { - this.date = date; - } - - /** - * Returns the value for the member attribute resource - * @return String - value of member attribute resource. - */ - public String getResource() { - return resource; - } - - /** - * This method sets the value to the member attribute resource. - * You cannot set null to the attribute. - * @param resource Value to set member attribute resource - */ - public void setResource(String resource) { - this.resource = resource; - } - - /** - * Returns the value for the member attribute action - * @return String - value of member attribute action. - */ - public String getAction() { - return action; - } - - /** - * This method sets the value to the member attribute action. - * You cannot set null to the attribute. - * @param action Value to set member attribute action - */ - public void setAction(String action) { - this.action = action; - } - - /** - * Returns the value for the member attribute result - * @return String - value of member attribute result. - */ - public String getResult() { - return result; - } - - /** - * This method sets the value to the member attribute result. - * You cannot set null to the attribute. - * @param result Value to set member attribute result - */ - public void setResult(String result) { - this.result = result; - } - - /** - * Returns the value for the member attribute user - * @return String - value of member attribute user. - */ - public String getUser() { - return user; - } - - /** - * This method sets the value to the member attribute user. - * You cannot set null to the attribute. - * @param user Value to set member attribute user - */ - public void setUser(String user) { - this.user = user; - } - - public String getEnforcer() { - return enforcer; - } - - /** - * This method sets the value to the member attribute enforcer. - * You cannot set null to the attribute. - * @param enforcer Value to set member attribute enforcer - */ - public void setEnforcer(String enforcer) { - this.enforcer = enforcer; - } - - /** - * Returns the value for the member attribute resourceType - * @return int - value of member attribute resourceType. - */ - public int getResourceType( ) { - return this.resourceType; - } - - /** - * This method sets the value to the member attribute resourceType. - * You cannot set null to the attribute. - * @param resourceType Value to set member attribute resourceType - */ - public void setResourceType( int resourceType ) { - this.resourceType = resourceType; - } - - /** - * Returns the value for the member attribute assetType - * @return int - value of member attribute assetType. - */ - public int getAssetType() { - return assetType; - } - - /** - * This method sets the value to the member attribute assetType. - * You cannot set null to the attribute. - * @param assetType Value to set member attribute assetType - */ - 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; - } - + /** + * 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 date + * + * @return Date - value of member attribute date. + */ + public Date getDate() { + return date; + } + + /** + * This method sets the value to the member attribute date. + * You cannot set null to the attribute. + * + * @param date Value to set member attribute date + */ + public void setDate(Date date) { + this.date = date; + } + + /** + * Returns the value for the member attribute resource + * + * @return String - value of member attribute resource. + */ + public String getResource() { + return resource; + } + + /** + * This method sets the value to the member attribute resource. + * You cannot set null to the attribute. + * + * @param resource Value to set member attribute resource + */ + public void setResource(String resource) { + this.resource = resource; + } + + /** + * Returns the value for the member attribute action + * + * @return String - value of member attribute action. + */ + public String getAction() { + return action; + } + + /** + * This method sets the value to the member attribute action. + * You cannot set null to the attribute. + * + * @param action Value to set member attribute action + */ + public void setAction(String action) { + this.action = action; + } + + /** + * Returns the value for the member attribute result + * + * @return String - value of member attribute result. + */ + public String getResult() { + return result; + } + + /** + * This method sets the value to the member attribute result. + * You cannot set null to the attribute. + * + * @param result Value to set member attribute result + */ + public void setResult(String result) { + this.result = result; + } + + /** + * Returns the value for the member attribute user + * + * @return String - value of member attribute user. + */ + public String getUser() { + return user; + } + + /** + * This method sets the value to the member attribute user. + * You cannot set null to the attribute. + * + * @param user Value to set member attribute user + */ + public void setUser(String user) { + this.user = user; + } + + public String getEnforcer() { + return enforcer; + } + + /** + * This method sets the value to the member attribute enforcer. + * You cannot set null to the attribute. + * + * @param enforcer Value to set member attribute enforcer + */ + public void setEnforcer(String enforcer) { + this.enforcer = enforcer; + } + + /** + * Returns the value for the member attribute resourceType + * + * @return int - value of member attribute resourceType. + */ + public int getResourceType() { + return this.resourceType; + } + + /** + * This method sets the value to the member attribute resourceType. + * You cannot set null to the attribute. + * + * @param resourceType Value to set member attribute resourceType + */ + public void setResourceType(int resourceType) { + this.resourceType = resourceType; + } + + /** + * Returns the value for the member attribute assetType + * + * @return int - value of member attribute assetType. + */ + public int getAssetType() { + return assetType; + } + + /** + * This method sets the value to the member attribute assetType. + * You cannot set null to the attribute. + * + * @param assetType Value to set member attribute assetType + */ + 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; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/view/VXAuditRecordList.java b/security-admin/src/main/java/org/apache/ranger/view/VXAuditRecordList.java index b2c7899cf0..efe8b116d4 100644 --- a/security-admin/src/main/java/org/apache/ranger/view/VXAuditRecordList.java +++ b/security-admin/src/main/java/org/apache/ranger/view/VXAuditRecordList.java @@ -17,50 +17,47 @@ * under the License. */ - package org.apache.ranger.view; +package org.apache.ranger.view; -import java.util.ArrayList; -import java.util.List; - -import org.apache.ranger.common.view.VList; -import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import org.apache.ranger.common.view.VList; + +import java.util.ArrayList; +import java.util.List; -@JsonAutoDetect(getterVisibility=Visibility.NONE, setterVisibility=Visibility.NONE, fieldVisibility=Visibility.ANY) +@JsonAutoDetect(getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE, fieldVisibility = Visibility.ANY) @JsonInclude(JsonInclude.Include.NON_NULL) public class VXAuditRecordList extends VList { - - /** - * - */ - private static final long serialVersionUID = 1L; - List vXAuditRecords = new ArrayList(); - - @JsonProperty("vXAuditRecords") - public List getvAudits() { - return vXAuditRecords; - } - - @JsonProperty("vXAuditRecords") - public void setvAudits(List 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; - } + private static final long serialVersionUID = 1L; + + List vXAuditRecords = new ArrayList<>(); + + public VXAuditRecordList() { + super(); + } + + @JsonProperty("vXAuditRecords") + public List getvAudits() { + return vXAuditRecords; + } + + @JsonProperty("vXAuditRecords") + public void setvAudits(List vXAuditRecords) { + this.vXAuditRecords = vXAuditRecords; + } + + @Override + public int getListSize() { + // TODO Auto-generated method stub + return 0; + } + + @Override + public List getList() { + // TODO Auto-generated method stub + return null; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/view/VXAuthSession.java b/security-admin/src/main/java/org/apache/ranger/view/VXAuthSession.java index 7170b04d5f..c91ba5ccfa 100644 --- a/security-admin/src/main/java/org/apache/ranger/view/VXAuthSession.java +++ b/security-admin/src/main/java/org/apache/ranger/view/VXAuthSession.java @@ -17,455 +17,453 @@ * under the License. */ - package org.apache.ranger.view; +package org.apache.ranger.view; /** * Authentication sessions - * */ -import java.util.Date; - -import org.apache.ranger.common.AppConstants; -import org.apache.ranger.json.JsonDateSerializer; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.databind.annotation.JsonSerialize; +import org.apache.ranger.common.AppConstants; +import org.apache.ranger.json.JsonDateSerializer; + +import java.util.Date; -@JsonAutoDetect(getterVisibility=Visibility.NONE, setterVisibility=Visibility.NONE, fieldVisibility=Visibility.ANY) +@JsonAutoDetect(getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE, fieldVisibility = Visibility.ANY) @JsonInclude(JsonInclude.Include.NON_NULL) -@JsonIgnoreProperties(ignoreUnknown=true) +@JsonIgnoreProperties(ignoreUnknown = true) 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; - /** - * 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 loginId. - * You cannot set null to the attribute. - * @param loginId Value to set member attribute loginId - */ - public void setLoginId( String loginId ) { - this.loginId = loginId; - } - - /** - * Returns the value for the member attribute loginId - * @return String - value of member attribute loginId. - */ - public String getLoginId( ) { - return this.loginId; - } - - /** - * This method sets the value to the member attribute userId. - * You cannot set null to the attribute. - * @param userId Value to set member attribute userId - */ - public void setUserId( Long userId ) { - this.userId = userId; - } - - /** - * Returns the value for the member attribute userId - * @return Long - value of member attribute userId. - */ - public Long getUserId( ) { - return this.userId; - } - - /** - * This method sets the value to the member attribute emailAddress. - * You cannot set null to the attribute. - * @param emailAddress Value to set member attribute emailAddress - */ - public void setEmailAddress( String emailAddress ) { - this.emailAddress = emailAddress; - } - - /** - * Returns the value for the member attribute emailAddress - * @return String - value of member attribute emailAddress. - */ - public String getEmailAddress( ) { - return this.emailAddress; - } - - /** - * This method sets the value to the member attribute isTestUser. - * You cannot set null to the attribute. - * @param isTestUser Value to set member attribute isTestUser - */ - public void setIsTestUser( boolean isTestUser ) { - this.isTestUser = isTestUser; - } - - /** - * Returns the value for the member attribute isTestUser - * @return boolean - value of member attribute isTestUser. - */ - public boolean isIsTestUser( ) { - return this.isTestUser; - } - - /** - * This method sets the value to the member attribute firstName. - * You cannot set null to the attribute. - * @param firstName Value to set member attribute firstName - */ - public void setFirstName( String firstName ) { - this.firstName = firstName; - } - - /** - * Returns the value for the member attribute firstName - * @return String - value of member attribute firstName. - */ - public String getFirstName( ) { - return this.firstName; - } - - /** - * This method sets the value to the member attribute lastName. - * You cannot set null to the attribute. - * @param lastName Value to set member attribute lastName - */ - public void setLastName( String lastName ) { - this.lastName = lastName; - } - - /** - * Returns the value for the member attribute lastName - * @return String - value of member attribute lastName. - */ - public String getLastName( ) { - return this.lastName; - } - - /** - * This method sets the value to the member attribute publicScreenName. - * You cannot set null to the attribute. - * @param publicScreenName Value to set member attribute publicScreenName - */ - public void setPublicScreenName( String publicScreenName ) { - this.publicScreenName = publicScreenName; - } - - /** - * Returns the value for the member attribute publicScreenName - * @return String - value of member attribute publicScreenName. - */ - public String getPublicScreenName( ) { - return this.publicScreenName; - } - - /** - * This method sets the value to the member attribute familyScreenName. - * You cannot set null to the attribute. - * @param familyScreenName Value to set member attribute familyScreenName - */ - public void setFamilyScreenName( String familyScreenName ) { - this.familyScreenName = familyScreenName; - } - - /** - * Returns the value for the member attribute familyScreenName - * @return String - value of member attribute familyScreenName. - */ - public String getFamilyScreenName( ) { - return this.familyScreenName; - } - - /** - * This method sets the value to the member attribute authTime. - * You cannot set null to the attribute. - * @param authTime Value to set member attribute authTime - */ - public void setAuthTime( Date authTime ) { - this.authTime = authTime; - } - - /** - * Returns the value for the member attribute authTime - * @return Date - value of member attribute authTime. - */ - public Date getAuthTime( ) { - return this.authTime; - } - - /** - * This method sets the value to the member attribute authStatus. - * You cannot set null to the attribute. - * @param authStatus Value to set member attribute authStatus - */ - public void setAuthStatus( int authStatus ) { - this.authStatus = authStatus; - } - - /** - * Returns the value for the member attribute authStatus - * @return int - value of member attribute authStatus. - */ - public int getAuthStatus( ) { - return this.authStatus; - } - - /** - * This method sets the value to the member attribute authType. - * You cannot set null to the attribute. - * @param authType Value to set member attribute authType - */ - public void setAuthType( int authType ) { - this.authType = authType; - } - - /** - * Returns the value for the member attribute authType - * @return int - value of member attribute authType. - */ - public int getAuthType( ) { - return this.authType; - } - - /** - * This method sets the value to the member attribute authProvider. - * You cannot set null to the attribute. - * @param authProvider Value to set member attribute authProvider - */ - public void setAuthProvider( int authProvider ) { - this.authProvider = authProvider; - } - - /** - * Returns the value for the member attribute authProvider - * @return int - value of member attribute authProvider. - */ - public int getAuthProvider( ) { - return this.authProvider; - } - - /** - * This method sets the value to the member attribute deviceType. - * You cannot set null to the attribute. - * @param deviceType Value to set member attribute deviceType - */ - public void setDeviceType( int deviceType ) { - this.deviceType = deviceType; - } - - /** - * Returns the value for the member attribute deviceType - * @return int - value of member attribute deviceType. - */ - public int getDeviceType( ) { - return this.deviceType; - } - - /** - * This method sets the value to the member attribute requestIP. - * You cannot set null to the attribute. - * @param requestIP Value to set member attribute requestIP - */ - public void setRequestIP( String requestIP ) { - this.requestIP = requestIP; - } - - /** - * Returns the value for the member attribute requestIP - * @return String - value of member attribute requestIP. - */ - public String getRequestIP( ) { - return this.requestIP; - } - - /** - * This method sets the value to the member attribute cityName. - * You cannot set null to the attribute. - * @param cityName Value to set member attribute cityName - */ - public void setCityName( String cityName ) { - this.cityName = cityName; - } - - /** - * Returns the value for the member attribute cityName - * @return String - value of member attribute cityName. - */ - public String getCityName( ) { - return this.cityName; - } - - /** - * This method sets the value to the member attribute stateName. - * You cannot set null to the attribute. - * @param stateName Value to set member attribute stateName - */ - public void setStateName( String stateName ) { - this.stateName = stateName; - } - - /** - * Returns the value for the member attribute stateName - * @return String - value of member attribute stateName. - */ - public String getStateName( ) { - return this.stateName; - } - - /** - * This method sets the value to the member attribute countryName. - * You cannot set null to the attribute. - * @param countryName Value to set member attribute countryName - */ - public void setCountryName( String countryName ) { - this.countryName = countryName; - } - - /** - * Returns the value for the member attribute countryName - * @return String - value of member attribute countryName. - */ - public String getCountryName( ) { - return this.countryName; - } - - /** - * This method sets the value to the member attribute requestUserAgent. - * You cannot set null to the attribute. - * @param requestUserAgent Value to set member attribute requestUserAgent - */ - public void setRequestUserAgent( String requestUserAgent ) { - this.requestUserAgent = requestUserAgent; - } - - /** - * Returns the value for the member attribute requestUserAgent - * @return String - value of member attribute requestUserAgent. - */ - 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 += "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; - } + 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; + /** + * 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; + /** + * 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; + } + + /** + * Returns the value for the member attribute loginId + * @return String - value of member attribute loginId. + */ + public String getLoginId() { + return this.loginId; + } + + /** + * This method sets the value to the member attribute loginId. + * You cannot set null to the attribute. + * @param loginId Value to set member attribute loginId + */ + public void setLoginId(String loginId) { + this.loginId = loginId; + } + + /** + * Returns the value for the member attribute userId + * @return Long - value of member attribute userId. + */ + public Long getUserId() { + return this.userId; + } + + /** + * This method sets the value to the member attribute userId. + * You cannot set null to the attribute. + * @param userId Value to set member attribute userId + */ + public void setUserId(Long userId) { + this.userId = userId; + } + + /** + * Returns the value for the member attribute emailAddress + * @return String - value of member attribute emailAddress. + */ + public String getEmailAddress() { + return this.emailAddress; + } + + /** + * This method sets the value to the member attribute emailAddress. + * You cannot set null to the attribute. + * @param emailAddress Value to set member attribute emailAddress + */ + public void setEmailAddress(String emailAddress) { + this.emailAddress = emailAddress; + } + + /** + * Returns the value for the member attribute isTestUser + * @return boolean - value of member attribute isTestUser. + */ + public boolean isIsTestUser() { + return this.isTestUser; + } + + /** + * This method sets the value to the member attribute isTestUser. + * You cannot set null to the attribute. + * @param isTestUser Value to set member attribute isTestUser + */ + public void setIsTestUser(boolean isTestUser) { + this.isTestUser = isTestUser; + } + + /** + * Returns the value for the member attribute firstName + * @return String - value of member attribute firstName. + */ + public String getFirstName() { + return this.firstName; + } + + /** + * This method sets the value to the member attribute firstName. + * You cannot set null to the attribute. + * @param firstName Value to set member attribute firstName + */ + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + /** + * Returns the value for the member attribute lastName + * @return String - value of member attribute lastName. + */ + public String getLastName() { + return this.lastName; + } + + /** + * This method sets the value to the member attribute lastName. + * You cannot set null to the attribute. + * @param lastName Value to set member attribute lastName + */ + public void setLastName(String lastName) { + this.lastName = lastName; + } + + /** + * Returns the value for the member attribute publicScreenName + * @return String - value of member attribute publicScreenName. + */ + public String getPublicScreenName() { + return this.publicScreenName; + } + + /** + * This method sets the value to the member attribute publicScreenName. + * You cannot set null to the attribute. + * @param publicScreenName Value to set member attribute publicScreenName + */ + public void setPublicScreenName(String publicScreenName) { + this.publicScreenName = publicScreenName; + } + + /** + * Returns the value for the member attribute familyScreenName + * @return String - value of member attribute familyScreenName. + */ + public String getFamilyScreenName() { + return this.familyScreenName; + } + + /** + * This method sets the value to the member attribute familyScreenName. + * You cannot set null to the attribute. + * @param familyScreenName Value to set member attribute familyScreenName + */ + public void setFamilyScreenName(String familyScreenName) { + this.familyScreenName = familyScreenName; + } + + /** + * Returns the value for the member attribute authTime + * @return Date - value of member attribute authTime. + */ + public Date getAuthTime() { + return this.authTime; + } + + /** + * This method sets the value to the member attribute authTime. + * You cannot set null to the attribute. + * @param authTime Value to set member attribute authTime + */ + public void setAuthTime(Date authTime) { + this.authTime = authTime; + } + + /** + * Returns the value for the member attribute authStatus + * @return int - value of member attribute authStatus. + */ + public int getAuthStatus() { + return this.authStatus; + } + + /** + * This method sets the value to the member attribute authStatus. + * You cannot set null to the attribute. + * @param authStatus Value to set member attribute authStatus + */ + public void setAuthStatus(int authStatus) { + this.authStatus = authStatus; + } + + /** + * Returns the value for the member attribute authType + * @return int - value of member attribute authType. + */ + public int getAuthType() { + return this.authType; + } + + /** + * This method sets the value to the member attribute authType. + * You cannot set null to the attribute. + * @param authType Value to set member attribute authType + */ + public void setAuthType(int authType) { + this.authType = authType; + } + + /** + * Returns the value for the member attribute authProvider + * @return int - value of member attribute authProvider. + */ + public int getAuthProvider() { + return this.authProvider; + } + + /** + * This method sets the value to the member attribute authProvider. + * You cannot set null to the attribute. + * @param authProvider Value to set member attribute authProvider + */ + public void setAuthProvider(int authProvider) { + this.authProvider = authProvider; + } + + /** + * Returns the value for the member attribute deviceType + * @return int - value of member attribute deviceType. + */ + public int getDeviceType() { + return this.deviceType; + } + + /** + * This method sets the value to the member attribute deviceType. + * You cannot set null to the attribute. + * @param deviceType Value to set member attribute deviceType + */ + public void setDeviceType(int deviceType) { + this.deviceType = deviceType; + } + + /** + * Returns the value for the member attribute requestIP + * @return String - value of member attribute requestIP. + */ + public String getRequestIP() { + return this.requestIP; + } + + /** + * This method sets the value to the member attribute requestIP. + * You cannot set null to the attribute. + * @param requestIP Value to set member attribute requestIP + */ + public void setRequestIP(String requestIP) { + this.requestIP = requestIP; + } + + /** + * Returns the value for the member attribute cityName + * @return String - value of member attribute cityName. + */ + public String getCityName() { + return this.cityName; + } + + /** + * This method sets the value to the member attribute cityName. + * You cannot set null to the attribute. + * @param cityName Value to set member attribute cityName + */ + public void setCityName(String cityName) { + this.cityName = cityName; + } + + /** + * Returns the value for the member attribute stateName + * @return String - value of member attribute stateName. + */ + public String getStateName() { + return this.stateName; + } + + /** + * This method sets the value to the member attribute stateName. + * You cannot set null to the attribute. + * @param stateName Value to set member attribute stateName + */ + public void setStateName(String stateName) { + this.stateName = stateName; + } + + /** + * Returns the value for the member attribute countryName + * @return String - value of member attribute countryName. + */ + public String getCountryName() { + return this.countryName; + } + + /** + * This method sets the value to the member attribute countryName. + * You cannot set null to the attribute. + * @param countryName Value to set member attribute countryName + */ + public void setCountryName(String countryName) { + this.countryName = countryName; + } + + /** + * Returns the value for the member attribute requestUserAgent + * @return String - value of member attribute requestUserAgent. + */ + public String getRequestUserAgent() { + return this.requestUserAgent; + } + + /** + * This method sets the value to the member attribute requestUserAgent. + * You cannot set null to the attribute. + * @param requestUserAgent Value to set member attribute requestUserAgent + */ + public void setRequestUserAgent(String requestUserAgent) { + this.requestUserAgent = 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 += "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; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/view/VXAuthSessionList.java b/security-admin/src/main/java/org/apache/ranger/view/VXAuthSessionList.java index 61fe3f0617..d2ef2eae5d 100644 --- a/security-admin/src/main/java/org/apache/ranger/view/VXAuthSessionList.java +++ b/security-admin/src/main/java/org/apache/ranger/view/VXAuthSessionList.java @@ -17,35 +17,35 @@ * under the License. */ - package org.apache.ranger.view; +package org.apache.ranger.view; /** * List wrapper class for VXAuthSession - * */ -import java.util.ArrayList; -import java.util.List; - -import org.apache.ranger.common.view.VList; -import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import org.apache.ranger.common.view.VList; + +import java.util.ArrayList; +import java.util.List; -@JsonAutoDetect(getterVisibility=Visibility.NONE, setterVisibility=Visibility.NONE, fieldVisibility=Visibility.ANY) +@JsonAutoDetect(getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE, fieldVisibility = Visibility.ANY) @JsonInclude(JsonInclude.Include.NON_NULL) public class VXAuthSessionList extends VList { - private static final long serialVersionUID = 1L; - List vXAuthSessions = new ArrayList(); + private static final long serialVersionUID = 1L; + + List vXAuthSessions = new ArrayList<>(); public VXAuthSessionList() { - super(); + super(); } public VXAuthSessionList(List objList) { - super(objList); - this.vXAuthSessions = objList; + super(objList); + this.vXAuthSessions = objList; } /** @@ -53,7 +53,7 @@ public VXAuthSessionList(List objList) { */ @JsonProperty("vXAuthSessions") public List getVXAuthSessions() { - return vXAuthSessions; + return vXAuthSessions; } /** @@ -62,20 +62,19 @@ public List getVXAuthSessions() { */ @JsonProperty("vXAuthSessions") public void setVXAuthSessions(List vXAuthSessions) { - this.vXAuthSessions = vXAuthSessions; + this.vXAuthSessions = vXAuthSessions; } @Override public int getListSize() { - if (vXAuthSessions != null) { - return vXAuthSessions.size(); - } - return 0; + if (vXAuthSessions != null) { + return vXAuthSessions.size(); + } + return 0; } @Override public List getList() { - return vXAuthSessions; + return vXAuthSessions; } - } diff --git a/security-admin/src/main/java/org/apache/ranger/view/VXCredentialStore.java b/security-admin/src/main/java/org/apache/ranger/view/VXCredentialStore.java index a3d87957f0..7e75ff0efe 100644 --- a/security-admin/src/main/java/org/apache/ranger/view/VXCredentialStore.java +++ b/security-admin/src/main/java/org/apache/ranger/view/VXCredentialStore.java @@ -17,90 +17,88 @@ * under the License. */ - package org.apache.ranger.view; +package org.apache.ranger.view; /** * Credential Store - */ -import org.apache.ranger.common.AppConstants; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; +import org.apache.ranger.common.AppConstants; -@JsonAutoDetect(getterVisibility=Visibility.NONE, setterVisibility=Visibility.NONE, fieldVisibility=Visibility.ANY) +@JsonAutoDetect(getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE, fieldVisibility = Visibility.ANY) @JsonInclude(JsonInclude.Include.NON_NULL) -@JsonIgnoreProperties(ignoreUnknown=true) +@JsonIgnoreProperties(ignoreUnknown = true) public class VXCredentialStore extends VXDataObject implements java.io.Serializable { - private static final long serialVersionUID = 1L; - + private static final long serialVersionUID = 1L; - /** - * Name - */ - protected String name; - /** - * Description - */ - protected String description; + /** + * Name + */ + protected String name; + /** + * Description + */ + protected String description; - /** - * Default constructor. This will set all the attributes to default value. - */ - public VXCredentialStore ( ) { - } + /** + * Default constructor. This will set all the attributes to default value. + */ + public VXCredentialStore() { + } - /** - * This method sets the value to the member attribute name. - * You cannot set null to the attribute. - * @param name Value to set member attribute name - */ - public void setName( String name ) { - this.name = name; - } + /** + * Returns the value for the member attribute name + * @return String - value of member attribute name. + */ + public String getName() { + return this.name; + } - /** - * Returns the value for the member attribute name - * @return String - value of member attribute name. - */ - public String getName( ) { - return this.name; - } + /** + * This method sets the value to the member attribute name. + * You cannot set null to the attribute. + * @param name Value to set member attribute name + */ + public void setName(String name) { + this.name = name; + } - /** - * This method sets the value to the member attribute description. - * You cannot set null to the attribute. - * @param description Value to set member attribute description - */ - public void setDescription( String description ) { - this.description = description; - } + /** + * Returns the value for the member attribute description + * @return String - value of member attribute description. + */ + public String getDescription() { + return this.description; + } - /** - * Returns the value for the member attribute description - * @return String - value of member attribute description. - */ - public String getDescription( ) { - return this.description; - } + /** + * This method sets the value to the member attribute description. + * You cannot set null to the attribute. + * @param description Value to set member attribute description + */ + public void setDescription(String description) { + this.description = description; + } - @Override - public int getMyClassType( ) { - return AppConstants.CLASS_TYPE_XA_CRED_STORE; - } + @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; - } + /** + * 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; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/view/VXCredentialStoreList.java b/security-admin/src/main/java/org/apache/ranger/view/VXCredentialStoreList.java index 82c75cce64..44fb8ef21e 100644 --- a/security-admin/src/main/java/org/apache/ranger/view/VXCredentialStoreList.java +++ b/security-admin/src/main/java/org/apache/ranger/view/VXCredentialStoreList.java @@ -17,35 +17,35 @@ * under the License. */ - package org.apache.ranger.view; +package org.apache.ranger.view; /** * List wrapper class for VXCredentialStore - */ -import java.util.ArrayList; -import java.util.List; - -import org.apache.ranger.common.view.VList; -import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import org.apache.ranger.common.view.VList; + +import java.util.ArrayList; +import java.util.List; -@JsonAutoDetect(getterVisibility=Visibility.NONE, setterVisibility=Visibility.NONE, fieldVisibility=Visibility.ANY) +@JsonAutoDetect(getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE, fieldVisibility = Visibility.ANY) @JsonInclude(JsonInclude.Include.NON_NULL) public class VXCredentialStoreList extends VList { - private static final long serialVersionUID = 1L; - List vXCredentialStores = new ArrayList(); + private static final long serialVersionUID = 1L; + + List vXCredentialStores = new ArrayList<>(); public VXCredentialStoreList() { - super(); + super(); } public VXCredentialStoreList(List objList) { - super(objList); - this.vXCredentialStores = objList; + super(objList); + this.vXCredentialStores = objList; } /** @@ -53,7 +53,7 @@ public VXCredentialStoreList(List objList) { */ @JsonProperty("vXCredentialStores") public List getVXCredentialStores() { - return vXCredentialStores; + return vXCredentialStores; } /** @@ -62,20 +62,19 @@ public List getVXCredentialStores() { */ @JsonProperty("vXCredentialStores") public void setVXCredentialStores(List vXCredentialStores) { - this.vXCredentialStores = vXCredentialStores; + this.vXCredentialStores = vXCredentialStores; } @Override public int getListSize() { - if (vXCredentialStores != null) { - return vXCredentialStores.size(); - } - return 0; + if (vXCredentialStores != null) { + return vXCredentialStores.size(); + } + return 0; } @Override public List getList() { - return vXCredentialStores; + return vXCredentialStores; } - } diff --git a/security-admin/src/main/java/org/apache/ranger/view/VXDataObject.java b/security-admin/src/main/java/org/apache/ranger/view/VXDataObject.java index 8585d7d510..d03c11fd76 100644 --- a/security-admin/src/main/java/org/apache/ranger/view/VXDataObject.java +++ b/security-admin/src/main/java/org/apache/ranger/view/VXDataObject.java @@ -17,163 +17,161 @@ * under the License. */ - package org.apache.ranger.view; +package org.apache.ranger.view; /** * Base object class - * */ -import java.util.Date; - -import org.apache.ranger.common.AppConstants; -import org.apache.ranger.common.view.ViewBaseBean; -import org.apache.ranger.json.JsonDateSerializer; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.databind.annotation.JsonSerialize; +import org.apache.ranger.common.AppConstants; +import org.apache.ranger.common.view.ViewBaseBean; +import org.apache.ranger.json.JsonDateSerializer; + +import java.util.Date; -@JsonAutoDetect(getterVisibility=Visibility.NONE, setterVisibility=Visibility.NONE, fieldVisibility=Visibility.ANY) +@JsonAutoDetect(getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE, fieldVisibility = Visibility.ANY) @JsonInclude(JsonInclude.Include.NON_NULL) -@JsonIgnoreProperties(ignoreUnknown=true) +@JsonIgnoreProperties(ignoreUnknown = true) 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 id. - * You cannot set null to the attribute. - * @param id Value to set member attribute id - */ - public void setId( Long id ) { - this.id = id; - } - - /** - * Returns the value for the member attribute id - * @return Long - value of member attribute id. - */ - public Long getId( ) { - return this.id; - } - - /** - * This method sets the value to the member attribute createDate. - * You cannot set null to the attribute. - * @param createDate Value to set member attribute createDate - */ - public void setCreateDate( Date createDate ) { - this.createDate = createDate; - } - - /** - * Returns the value for the member attribute createDate - * @return Date - value of member attribute createDate. - */ - public Date getCreateDate( ) { - return this.createDate; - } - - /** - * This method sets the value to the member attribute updateDate. - * You cannot set null to the attribute. - * @param updateDate Value to set member attribute updateDate - */ - public void setUpdateDate( Date updateDate ) { - this.updateDate = updateDate; - } - - /** - * Returns the value for the member attribute updateDate - * @return Date - value of member attribute updateDate. - */ - public Date getUpdateDate( ) { - return this.updateDate; - } - - /** - * This method sets the value to the member attribute owner. - * You cannot set null to the attribute. - * @param owner Value to set member attribute owner - */ - public void setOwner( String owner ) { - this.owner = owner; - } - - /** - * Returns the value for the member attribute owner - * @return String - value of member attribute owner. - */ - public String getOwner( ) { - return this.owner; - } - - /** - * This method sets the value to the member attribute updatedBy. - * You cannot set null to the attribute. - * @param updatedBy Value to set member attribute updatedBy - */ - public void setUpdatedBy( String updatedBy ) { - this.updatedBy = updatedBy; - } - - /** - * Returns the value for the member attribute updatedBy - * @return String - value of member attribute updatedBy. - */ - 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; - } + 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() { + } + + /** + * Returns the value for the member attribute id + * @return Long - value of member attribute id. + */ + public Long getId() { + return this.id; + } + + /** + * This method sets the value to the member attribute id. + * You cannot set null to the attribute. + * @param id Value to set member attribute id + */ + public void setId(Long id) { + this.id = id; + } + + /** + * Returns the value for the member attribute createDate + * @return Date - value of member attribute createDate. + */ + public Date getCreateDate() { + return this.createDate; + } + + /** + * This method sets the value to the member attribute createDate. + * You cannot set null to the attribute. + * @param createDate Value to set member attribute createDate + */ + public void setCreateDate(Date createDate) { + this.createDate = createDate; + } + + /** + * Returns the value for the member attribute updateDate + * @return Date - value of member attribute updateDate. + */ + public Date getUpdateDate() { + return this.updateDate; + } + + /** + * This method sets the value to the member attribute updateDate. + * You cannot set null to the attribute. + * @param updateDate Value to set member attribute updateDate + */ + public void setUpdateDate(Date updateDate) { + this.updateDate = updateDate; + } + + /** + * Returns the value for the member attribute owner + * @return String - value of member attribute owner. + */ + public String getOwner() { + return this.owner; + } + + /** + * This method sets the value to the member attribute owner. + * You cannot set null to the attribute. + * @param owner Value to set member attribute owner + */ + public void setOwner(String owner) { + this.owner = owner; + } + + /** + * Returns the value for the member attribute updatedBy + * @return String - value of member attribute updatedBy. + */ + public String getUpdatedBy() { + return this.updatedBy; + } + + /** + * This method sets the value to the member attribute updatedBy. + * You cannot set null to the attribute. + * @param updatedBy Value to set member attribute updatedBy + */ + public void setUpdatedBy(String updatedBy) { + this.updatedBy = 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; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/view/VXFileSyncSourceInfo.java b/security-admin/src/main/java/org/apache/ranger/view/VXFileSyncSourceInfo.java index 0aa52a690c..3bc7dc12fd 100644 --- a/security-admin/src/main/java/org/apache/ranger/view/VXFileSyncSourceInfo.java +++ b/security-admin/src/main/java/org/apache/ranger/view/VXFileSyncSourceInfo.java @@ -17,11 +17,10 @@ * under the License. */ - package org.apache.ranger.view; +package org.apache.ranger.view; /** * UserGroupInfo - * */ import com.fasterxml.jackson.annotation.JsonAutoDetect; @@ -29,96 +28,95 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; -@JsonAutoDetect(getterVisibility=Visibility.NONE, setterVisibility=Visibility.NONE, fieldVisibility=Visibility.ANY) +@JsonAutoDetect(getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE, fieldVisibility = Visibility.ANY) @JsonInclude(JsonInclude.Include.NON_NULL) -@JsonIgnoreProperties(ignoreUnknown=true) -public class VXFileSyncSourceInfo implements java.io.Serializable { - - private static final long serialVersionUID = 1L; - - private String fileName; - private String syncTime; - private String lastModified; - private long totalUsersSynced; - private long totalGroupsSynced; - private long totalUsersDeleted; - private long totalGroupsDeleted; - - public VXFileSyncSourceInfo() { - } - - public String getFileName() { - return fileName; - } - - public void setFileName(String fileName) { - this.fileName = fileName; - } - - public String getSyncTime() { - return syncTime; - } - - public void setSyncTime(String syncTime) { - this.syncTime = syncTime; - } - - public String getLastModified() { - return lastModified; - } - - public void setLastModified(String lastModified) { - this.lastModified = lastModified; - } - - public long getTotalUsersSynced() { - return totalUsersSynced; - } - - public void setTotalUsersSynced(long totalUsersSynced) { - this.totalUsersSynced = totalUsersSynced; - } - - public long getTotalGroupsSynced() { - return totalGroupsSynced; - } - - public void setTotalGroupsSynced(long totalGroupsSynced) { - this.totalGroupsSynced = totalGroupsSynced; - } - - public long getTotalUsersDeleted() { - return totalUsersDeleted; - } - - public void setTotalUsersDeleted(long totalUsersDeleted) { - this.totalUsersDeleted = totalUsersDeleted; - } - - public long getTotalGroupsDeleted() { - return totalGroupsDeleted; - } - - public void setTotalGroupsDeleted(long totalGroupsDeleted) { - this.totalGroupsDeleted = totalGroupsDeleted; - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - toString(sb); - return sb.toString(); - } - - public StringBuilder toString(StringBuilder sb) { - sb.append("{\"fileName\":\"").append(fileName); - sb.append("\", \"syncTime\":\"").append(syncTime); - sb.append("\", \"lastModified\":\"").append(lastModified); - sb.append("\", \"totalUsersSynced\":\"").append(totalUsersSynced); - sb.append("\", \"totalGroupsSynced\":\"").append(totalGroupsSynced); - sb.append("\", \"totalUsersDeleted\":\"").append(totalUsersDeleted); - sb.append("\", \"totalGroupsDeleted\":\"").append(totalGroupsDeleted); - sb.append("\"}"); - return sb; - } +@JsonIgnoreProperties(ignoreUnknown = true) +public class VXFileSyncSourceInfo implements java.io.Serializable { + private static final long serialVersionUID = 1L; + + private String fileName; + private String syncTime; + private String lastModified; + private long totalUsersSynced; + private long totalGroupsSynced; + private long totalUsersDeleted; + private long totalGroupsDeleted; + + public VXFileSyncSourceInfo() { + } + + public String getFileName() { + return fileName; + } + + public void setFileName(String fileName) { + this.fileName = fileName; + } + + public String getSyncTime() { + return syncTime; + } + + public void setSyncTime(String syncTime) { + this.syncTime = syncTime; + } + + public String getLastModified() { + return lastModified; + } + + public void setLastModified(String lastModified) { + this.lastModified = lastModified; + } + + public long getTotalUsersSynced() { + return totalUsersSynced; + } + + public void setTotalUsersSynced(long totalUsersSynced) { + this.totalUsersSynced = totalUsersSynced; + } + + public long getTotalGroupsSynced() { + return totalGroupsSynced; + } + + public void setTotalGroupsSynced(long totalGroupsSynced) { + this.totalGroupsSynced = totalGroupsSynced; + } + + public long getTotalUsersDeleted() { + return totalUsersDeleted; + } + + public void setTotalUsersDeleted(long totalUsersDeleted) { + this.totalUsersDeleted = totalUsersDeleted; + } + + public long getTotalGroupsDeleted() { + return totalGroupsDeleted; + } + + public void setTotalGroupsDeleted(long totalGroupsDeleted) { + this.totalGroupsDeleted = totalGroupsDeleted; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + toString(sb); + return sb.toString(); + } + + public StringBuilder toString(StringBuilder sb) { + sb.append("{\"fileName\":\"").append(fileName); + sb.append("\", \"syncTime\":\"").append(syncTime); + sb.append("\", \"lastModified\":\"").append(lastModified); + sb.append("\", \"totalUsersSynced\":\"").append(totalUsersSynced); + sb.append("\", \"totalGroupsSynced\":\"").append(totalGroupsSynced); + sb.append("\", \"totalUsersDeleted\":\"").append(totalUsersDeleted); + sb.append("\", \"totalGroupsDeleted\":\"").append(totalGroupsDeleted); + sb.append("\"}"); + return sb; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/view/VXGroup.java b/security-admin/src/main/java/org/apache/ranger/view/VXGroup.java index 12531e4b82..3873688f34 100644 --- a/security-admin/src/main/java/org/apache/ranger/view/VXGroup.java +++ b/security-admin/src/main/java/org/apache/ranger/view/VXGroup.java @@ -17,213 +17,210 @@ * under the License. */ - package org.apache.ranger.view; +package org.apache.ranger.view; /** * Group - * */ -import org.apache.ranger.common.AppConstants; -import org.apache.ranger.common.RangerCommonEnums; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; +import org.apache.ranger.common.AppConstants; +import org.apache.ranger.common.RangerCommonEnums; -@JsonAutoDetect(getterVisibility=Visibility.NONE, setterVisibility=Visibility.NONE, fieldVisibility=Visibility.ANY) +@JsonAutoDetect(getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE, fieldVisibility = Visibility.ANY) @JsonInclude(JsonInclude.Include.NON_NULL) -@JsonIgnoreProperties(ignoreUnknown=true) +@JsonIgnoreProperties(ignoreUnknown = true) 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 = RangerCommonEnums.GROUP_INTERNAL; - /** - * Id of the credential store - */ - protected Long credStoreId; - - /** - * Group visibility - */ - protected Integer isVisible; - - /** - * Additional store attributes. - * - */ - protected String otherAttributes; - - /** - * Sync Source Attribute - * */ - protected String syncSource; - - /** - * Default constructor. This will set all the attributes to default value. - */ - public VXGroup ( ) { - groupType = AppConstants.XA_GROUP_UNKNOWN; - isVisible = RangerCommonEnums.IS_VISIBLE; - } - - /** - * This method sets the value to the member attribute name. - * You cannot set null to the attribute. - * @param name Value to set member attribute name - */ - public void setName( String name ) { - this.name = name; - } - - /** - * Returns the value for the member attribute name - * @return String - value of member attribute name. - */ - public String getName( ) { - return this.name; - } - - /** - * This method sets the value to the member attribute description. - * You cannot set null to the attribute. - * @param description Value to set member attribute description - */ - public void setDescription( String description ) { - this.description = description; - } - - /** - * Returns the value for the member attribute description - * @return String - value of member attribute description. - */ - public String getDescription( ) { - return this.description; - } - - /** - * This method sets the value to the member attribute groupType. - * You cannot set null to the attribute. - * @param groupType Value to set member attribute groupType - */ - public void setGroupType( int groupType ) { - this.groupType = groupType; - } - - /** - * Returns the value for the member attribute groupType - * @return int - value of member attribute groupType. - */ - public int getGroupType( ) { - return this.groupType; - } - - /** - * This method sets the value to the member attribute credStoreId. - * You cannot set null to the attribute. - * @param credStoreId Value to set member attribute credStoreId - */ - public void setCredStoreId( Long credStoreId ) { - this.credStoreId = credStoreId; - } - - /** - * Returns the value for the member attribute credStoreId - * @return Long - value of member attribute credStoreId. - */ - public Long getCredStoreId( ) { - return this.credStoreId; - } - - /** - * @return the isVisible - */ - public Integer getIsVisible() { - return isVisible; - } - - /** - * @param isVisible the isVisible to set - */ - public void setIsVisible(Integer isVisible) { - this.isVisible = isVisible; - } - - @Override - public int getMyClassType( ) { - return AppConstants.CLASS_TYPE_XA_GROUP; - } - - - - - public int getGroupSource() { - return groupSource; - } - - public void setGroupSource(int groupSource) { - this.groupSource = groupSource; - } - - /** - * @return {@link String} - additional attributes. - */ - public String getOtherAttributes() { - return otherAttributes; - } - - /** - * This method sets additional attributes. - * @param otherAttributes - */ - public void setOtherAttributes(final String otherAttributes) { - this.otherAttributes = otherAttributes; - } - - /** - * This method sets sync source attribute. - * @param syncSource - */ - public void setSyncSource(String syncSource) { - this.syncSource = syncSource; - } - - /** - * @return {@link String} sync source attribute - */ - public String getSyncSource() { return syncSource; } - - /** - * 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 += "isVisible={" + isVisible + "} "; - str += "groupSrc={" + groupSource + "} "; - str += "otherAttributes={" + otherAttributes + "} "; - str += "syncSource={" + syncSource + "} "; - str += "}"; - return str; - } + 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 = RangerCommonEnums.GROUP_INTERNAL; + /** + * Id of the credential store + */ + protected Long credStoreId; + + /** + * Group visibility + */ + protected Integer isVisible; + + /** + * Additional store attributes. + * + */ + protected String otherAttributes; + + /** + * Sync Source Attribute + * */ + protected String syncSource; + + /** + * Default constructor. This will set all the attributes to default value. + */ + public VXGroup() { + groupType = AppConstants.XA_GROUP_UNKNOWN; + isVisible = RangerCommonEnums.IS_VISIBLE; + } + + /** + * Returns the value for the member attribute name + * @return String - value of member attribute name. + */ + public String getName() { + return this.name; + } + + /** + * This method sets the value to the member attribute name. + * You cannot set null to the attribute. + * @param name Value to set member attribute name + */ + public void setName(String name) { + this.name = name; + } + + /** + * Returns the value for the member attribute description + * @return String - value of member attribute description. + */ + public String getDescription() { + return this.description; + } + + /** + * This method sets the value to the member attribute description. + * You cannot set null to the attribute. + * @param description Value to set member attribute description + */ + public void setDescription(String description) { + this.description = description; + } + + /** + * Returns the value for the member attribute groupType + * @return int - value of member attribute groupType. + */ + public int getGroupType() { + return this.groupType; + } + + /** + * This method sets the value to the member attribute groupType. + * You cannot set null to the attribute. + * @param groupType Value to set member attribute groupType + */ + public void setGroupType(int groupType) { + this.groupType = groupType; + } + + /** + * Returns the value for the member attribute credStoreId + * @return Long - value of member attribute credStoreId. + */ + public Long getCredStoreId() { + return this.credStoreId; + } + + /** + * This method sets the value to the member attribute credStoreId. + * You cannot set null to the attribute. + * @param credStoreId Value to set member attribute credStoreId + */ + public void setCredStoreId(Long credStoreId) { + this.credStoreId = credStoreId; + } + + /** + * @return the isVisible + */ + public Integer getIsVisible() { + return isVisible; + } + + /** + * @param isVisible the isVisible to set + */ + public void setIsVisible(Integer isVisible) { + this.isVisible = isVisible; + } + + @Override + public int getMyClassType() { + return AppConstants.CLASS_TYPE_XA_GROUP; + } + + /** + * 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 += "isVisible={" + isVisible + "} "; + str += "groupSrc={" + groupSource + "} "; + str += "otherAttributes={" + otherAttributes + "} "; + str += "syncSource={" + syncSource + "} "; + str += "}"; + return str; + } + + public int getGroupSource() { + return groupSource; + } + + public void setGroupSource(int groupSource) { + this.groupSource = groupSource; + } + + /** + * @return {@link String} - additional attributes. + */ + public String getOtherAttributes() { + return otherAttributes; + } + + /** + * This method sets additional attributes. + * @param otherAttributes + */ + public void setOtherAttributes(final String otherAttributes) { + this.otherAttributes = otherAttributes; + } + + /** + * @return {@link String} sync source attribute + */ + public String getSyncSource() { + return syncSource; + } + + /** + * This method sets sync source attribute. + * @param syncSource + */ + public void setSyncSource(String syncSource) { + this.syncSource = syncSource; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/view/VXGroupGroup.java b/security-admin/src/main/java/org/apache/ranger/view/VXGroupGroup.java index f3728fdc67..ea53e65909 100644 --- a/security-admin/src/main/java/org/apache/ranger/view/VXGroupGroup.java +++ b/security-admin/src/main/java/org/apache/ranger/view/VXGroupGroup.java @@ -17,112 +17,110 @@ * under the License. */ - package org.apache.ranger.view; +package org.apache.ranger.view; /** * Group of groups - * */ -import org.apache.ranger.common.AppConstants; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; +import org.apache.ranger.common.AppConstants; -@JsonAutoDetect(getterVisibility=Visibility.NONE, setterVisibility=Visibility.NONE, fieldVisibility=Visibility.ANY) +@JsonAutoDetect(getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE, fieldVisibility = Visibility.ANY) @JsonInclude(JsonInclude.Include.NON_NULL) -@JsonIgnoreProperties(ignoreUnknown=true) +@JsonIgnoreProperties(ignoreUnknown = true) public class VXGroupGroup extends VXDataObject implements java.io.Serializable { - private static final long serialVersionUID = 1L; - + 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; + /** + * 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 ( ) { - } + /** + * Default constructor. This will set all the attributes to default value. + */ + public VXGroupGroup() { + } - /** - * This method sets the value to the member attribute name. - * You cannot set null to the attribute. - * @param name Value to set member attribute name - */ - public void setName( String name ) { - this.name = name; - } + /** + * Returns the value for the member attribute name + * @return String - value of member attribute name. + */ + public String getName() { + return this.name; + } - /** - * Returns the value for the member attribute name - * @return String - value of member attribute name. - */ - public String getName( ) { - return this.name; - } + /** + * This method sets the value to the member attribute name. + * You cannot set null to the attribute. + * @param name Value to set member attribute name + */ + public void setName(String name) { + this.name = name; + } - /** - * This method sets the value to the member attribute parentGroupId. - * You cannot set null to the attribute. - * @param parentGroupId Value to set member attribute parentGroupId - */ - public void setParentGroupId( Long parentGroupId ) { - this.parentGroupId = parentGroupId; - } + /** + * Returns the value for the member attribute parentGroupId + * @return Long - value of member attribute parentGroupId. + */ + public Long getParentGroupId() { + return this.parentGroupId; + } - /** - * Returns the value for the member attribute parentGroupId - * @return Long - value of member attribute parentGroupId. - */ - public Long getParentGroupId( ) { - return this.parentGroupId; - } + /** + * This method sets the value to the member attribute parentGroupId. + * You cannot set null to the attribute. + * @param parentGroupId Value to set member attribute parentGroupId + */ + public void setParentGroupId(Long parentGroupId) { + this.parentGroupId = parentGroupId; + } - /** - * This method sets the value to the member attribute groupId. - * You cannot set null to the attribute. - * @param groupId Value to set member attribute groupId - */ - public void setGroupId( Long groupId ) { - this.groupId = groupId; - } + /** + * Returns the value for the member attribute groupId + * @return Long - value of member attribute groupId. + */ + public Long getGroupId() { + return this.groupId; + } - /** - * Returns the value for the member attribute groupId - * @return Long - value of member attribute groupId. - */ - public Long getGroupId( ) { - return this.groupId; - } + /** + * This method sets the value to the member attribute groupId. + * You cannot set null to the attribute. + * @param groupId Value to set member attribute groupId + */ + public void setGroupId(Long groupId) { + this.groupId = groupId; + } - @Override - public int getMyClassType( ) { - return AppConstants.CLASS_TYPE_XA_GROUP_GROUP; - } + @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; - } + /** + * 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; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/view/VXGroupGroupList.java b/security-admin/src/main/java/org/apache/ranger/view/VXGroupGroupList.java index 52254a10cb..3a642b6f1c 100644 --- a/security-admin/src/main/java/org/apache/ranger/view/VXGroupGroupList.java +++ b/security-admin/src/main/java/org/apache/ranger/view/VXGroupGroupList.java @@ -17,35 +17,35 @@ * under the License. */ - package org.apache.ranger.view; +package org.apache.ranger.view; /** * List wrapper class for VXGroupGroup - * */ -import java.util.ArrayList; -import java.util.List; - -import org.apache.ranger.common.view.VList; -import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import org.apache.ranger.common.view.VList; + +import java.util.ArrayList; +import java.util.List; -@JsonAutoDetect(getterVisibility=Visibility.NONE, setterVisibility=Visibility.NONE, fieldVisibility=Visibility.ANY) +@JsonAutoDetect(getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE, fieldVisibility = Visibility.ANY) @JsonInclude(JsonInclude.Include.NON_NULL) public class VXGroupGroupList extends VList { - private static final long serialVersionUID = 1L; - List vXGroupGroups = new ArrayList(); + private static final long serialVersionUID = 1L; + + List vXGroupGroups = new ArrayList<>(); public VXGroupGroupList() { - super(); + super(); } public VXGroupGroupList(List objList) { - super(objList); - this.vXGroupGroups = objList; + super(objList); + this.vXGroupGroups = objList; } /** @@ -53,7 +53,7 @@ public VXGroupGroupList(List objList) { */ @JsonProperty("vXGroupGroups") public List getVXGroupGroups() { - return vXGroupGroups; + return vXGroupGroups; } /** @@ -62,20 +62,19 @@ public List getVXGroupGroups() { */ @JsonProperty("vXGroupGroups") public void setVXGroupGroups(List vXGroupGroups) { - this.vXGroupGroups = vXGroupGroups; + this.vXGroupGroups = vXGroupGroups; } @Override public int getListSize() { - if (vXGroupGroups != null) { - return vXGroupGroups.size(); - } - return 0; + if (vXGroupGroups != null) { + return vXGroupGroups.size(); + } + return 0; } @Override public List getList() { - return vXGroupGroups; + return vXGroupGroups; } - } diff --git a/security-admin/src/main/java/org/apache/ranger/view/VXGroupList.java b/security-admin/src/main/java/org/apache/ranger/view/VXGroupList.java index cf13ac6728..f4bbc3e105 100644 --- a/security-admin/src/main/java/org/apache/ranger/view/VXGroupList.java +++ b/security-admin/src/main/java/org/apache/ranger/view/VXGroupList.java @@ -17,35 +17,35 @@ * under the License. */ - package org.apache.ranger.view; +package org.apache.ranger.view; /** * List wrapper class for VXGroup - * */ -import java.util.ArrayList; -import java.util.List; - -import org.apache.ranger.common.view.VList; -import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import org.apache.ranger.common.view.VList; + +import java.util.ArrayList; +import java.util.List; -@JsonAutoDetect(getterVisibility=Visibility.NONE, setterVisibility=Visibility.NONE, fieldVisibility=Visibility.ANY) +@JsonAutoDetect(getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE, fieldVisibility = Visibility.ANY) @JsonInclude(JsonInclude.Include.NON_NULL) public class VXGroupList extends VList { - private static final long serialVersionUID = 1L; - List vXGroups = new ArrayList(); + private static final long serialVersionUID = 1L; + + List vXGroups = new ArrayList<>(); public VXGroupList() { - super(); + super(); } public VXGroupList(List objList) { - super(objList); - this.vXGroups = objList; + super(objList); + this.vXGroups = objList; } /** @@ -53,7 +53,7 @@ public VXGroupList(List objList) { */ @JsonProperty("vXGroups") public List getVXGroups() { - return vXGroups; + return vXGroups; } /** @@ -62,20 +62,19 @@ public List getVXGroups() { */ @JsonProperty("vXGroups") public void setVXGroups(List vXGroups) { - this.vXGroups = vXGroups; + this.vXGroups = vXGroups; } @Override public int getListSize() { - if (vXGroups != null) { - return vXGroups.size(); - } - return 0; + if (vXGroups != null) { + return vXGroups.size(); + } + return 0; } @Override public List getList() { - return vXGroups; + return vXGroups; } - } diff --git a/security-admin/src/main/java/org/apache/ranger/view/VXGroupPermission.java b/security-admin/src/main/java/org/apache/ranger/view/VXGroupPermission.java index c54587e704..3662ecb1bd 100644 --- a/security-admin/src/main/java/org/apache/ranger/view/VXGroupPermission.java +++ b/security-admin/src/main/java/org/apache/ranger/view/VXGroupPermission.java @@ -17,126 +17,123 @@ package org.apache.ranger.view; -import org.apache.ranger.common.AppConstants; import com.fasterxml.jackson.annotation.JsonAutoDetect; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; +import org.apache.ranger.common.AppConstants; -@JsonAutoDetect(getterVisibility=Visibility.NONE, setterVisibility=Visibility.NONE, fieldVisibility=Visibility.ANY) +@JsonAutoDetect(getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE, fieldVisibility = Visibility.ANY) @JsonInclude(JsonInclude.Include.NON_NULL) -@JsonIgnoreProperties(ignoreUnknown=true) +@JsonIgnoreProperties(ignoreUnknown = true) public class VXGroupPermission extends VXDataObject implements java.io.Serializable { - - private static final long serialVersionUID = 1L; - - - protected Long groupId; - protected Long moduleId; - protected Integer isAllowed; - protected String moduleName; - - protected String groupName; - - public VXGroupPermission() { - // TODO Auto-generated constructor stub - } - - /** - * @return the id - */ - public Long getId() { - return id; - } - - /** - * @param id the id to set - */ - public void setId(Long id) { - this.id = id; - } - - /** - * @return the groupId - */ - public Long getGroupId() { - return groupId; - } - - /** - * @param groupId the groupId to set - */ - public void setGroupId(Long groupId) { - this.groupId = groupId; - } - - /** - * @return the groupName - */ - public String getGroupName() { - return groupName; - } - - /** - * @param groupName the groupName to set - */ - public void setGroupName(String groupName) { - this.groupName = groupName; - } - - /** - * @return the moduleId - */ - public Long getModuleId() { - return moduleId; - } - - /** - * @param moduleId the moduleId to set - */ - public void setModuleId(Long moduleId) { - this.moduleId = moduleId; - } - - /** - * @return the isAllowed - */ - public Integer getIsAllowed() { - return isAllowed; - } - - /** - * @param isAllowed the isAllowed to set - */ - public void setIsAllowed(Integer isAllowed) { - this.isAllowed = isAllowed; - } - - public String getModuleName() { - return moduleName; - } - - public void setModuleName(String moduleName) { - this.moduleName = moduleName; - } - - @Override - public int getMyClassType() { - return AppConstants.CLASS_TYPE_RANGER_GROUP_PERMISSION; - } - - @Override - public String toString() { - - String str = "VXGroupPermission={"; - str += super.toString(); - str += "id={" + id + "} "; - str += "groupId={" + groupId + "} "; - str += "moduleId={" + moduleId + "} "; - str += "isAllowed={" + isAllowed + "} "; - str += "moduleName={" + moduleName + "} "; - str += "}"; - - return str; - } + private static final long serialVersionUID = 1L; + + protected Long groupId; + protected Long moduleId; + protected Integer isAllowed; + protected String moduleName; + + protected String groupName; + + public VXGroupPermission() { + // TODO Auto-generated constructor stub + } + + /** + * @return the id + */ + public Long getId() { + return id; + } + + /** + * @param id the id to set + */ + public void setId(Long id) { + this.id = id; + } + + @Override + public int getMyClassType() { + return AppConstants.CLASS_TYPE_RANGER_GROUP_PERMISSION; + } + + @Override + public String toString() { + String str = "VXGroupPermission={"; + str += super.toString(); + str += "id={" + id + "} "; + str += "groupId={" + groupId + "} "; + str += "moduleId={" + moduleId + "} "; + str += "isAllowed={" + isAllowed + "} "; + str += "moduleName={" + moduleName + "} "; + str += "}"; + + return str; + } + + /** + * @return the groupId + */ + public Long getGroupId() { + return groupId; + } + + /** + * @param groupId the groupId to set + */ + public void setGroupId(Long groupId) { + this.groupId = groupId; + } + + /** + * @return the groupName + */ + public String getGroupName() { + return groupName; + } + + /** + * @param groupName the groupName to set + */ + public void setGroupName(String groupName) { + this.groupName = groupName; + } + + /** + * @return the moduleId + */ + public Long getModuleId() { + return moduleId; + } + + /** + * @param moduleId the moduleId to set + */ + public void setModuleId(Long moduleId) { + this.moduleId = moduleId; + } + + /** + * @return the isAllowed + */ + public Integer getIsAllowed() { + return isAllowed; + } + + /** + * @param isAllowed the isAllowed to set + */ + public void setIsAllowed(Integer isAllowed) { + this.isAllowed = isAllowed; + } + + public String getModuleName() { + return moduleName; + } + + public void setModuleName(String moduleName) { + this.moduleName = moduleName; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/view/VXGroupPermissionList.java b/security-admin/src/main/java/org/apache/ranger/view/VXGroupPermissionList.java index ef5aa8e530..686ecb2103 100644 --- a/security-admin/src/main/java/org/apache/ranger/view/VXGroupPermissionList.java +++ b/security-admin/src/main/java/org/apache/ranger/view/VXGroupPermissionList.java @@ -17,58 +17,57 @@ package org.apache.ranger.view; -import java.util.ArrayList; -import java.util.List; - -import org.apache.ranger.common.view.VList; -import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import org.apache.ranger.common.view.VList; + +import java.util.ArrayList; +import java.util.List; @JsonAutoDetect(getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE, fieldVisibility = Visibility.ANY) @JsonInclude(JsonInclude.Include.NON_NULL) public class VXGroupPermissionList extends VList { + private static final long serialVersionUID = 1L; - private static final long serialVersionUID = 1L; - - List vXGroupPermission = new ArrayList(); + List vXGroupPermission = new ArrayList<>(); - public VXGroupPermissionList() { - super(); - } + public VXGroupPermissionList() { + super(); + } - public VXGroupPermissionList(List objList) { - super(objList); - this.vXGroupPermission = objList; - } + public VXGroupPermissionList(List objList) { + super(objList); + this.vXGroupPermission = objList; + } - /** - * @return the vXGroupPermission - */ - @JsonProperty("vXGroupPermission") - public List getvXGroupPermission() { - return vXGroupPermission; - } + /** + * @return the vXGroupPermission + */ + @JsonProperty("vXGroupPermission") + public List getvXGroupPermission() { + return vXGroupPermission; + } - /** - * @param vXGroupPermission the vXGroupPermission to set - */ - @JsonProperty("vXGroupPermission") - public void setvXGroupPermission(List vXGroupPermission) { - this.vXGroupPermission = vXGroupPermission; - } + /** + * @param vXGroupPermission the vXGroupPermission to set + */ + @JsonProperty("vXGroupPermission") + public void setvXGroupPermission(List vXGroupPermission) { + this.vXGroupPermission = vXGroupPermission; + } - @Override - public int getListSize() { - if (vXGroupPermission != null) { - return vXGroupPermission.size(); - } - return 0; - } + @Override + public int getListSize() { + if (vXGroupPermission != null) { + return vXGroupPermission.size(); + } + return 0; + } - @Override - public List getList() { - return vXGroupPermission; - } + @Override + public List getList() { + return vXGroupPermission; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/view/VXGroupUser.java b/security-admin/src/main/java/org/apache/ranger/view/VXGroupUser.java index 373c2ee81f..07d066e545 100644 --- a/security-admin/src/main/java/org/apache/ranger/view/VXGroupUser.java +++ b/security-admin/src/main/java/org/apache/ranger/view/VXGroupUser.java @@ -17,112 +17,110 @@ * under the License. */ - package org.apache.ranger.view; +package org.apache.ranger.view; /** * Group of users - * */ -import org.apache.ranger.common.AppConstants; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; +import org.apache.ranger.common.AppConstants; -@JsonAutoDetect(getterVisibility=Visibility.NONE, setterVisibility=Visibility.NONE, fieldVisibility=Visibility.ANY) +@JsonAutoDetect(getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE, fieldVisibility = Visibility.ANY) @JsonInclude(JsonInclude.Include.NON_NULL) -@JsonIgnoreProperties(ignoreUnknown=true) +@JsonIgnoreProperties(ignoreUnknown = true) public class VXGroupUser extends VXDataObject implements java.io.Serializable { - private static final long serialVersionUID = 1L; - + private static final long serialVersionUID = 1L; - /** - * Name - */ - protected String name; - /** - * Id of the group - */ - protected Long parentGroupId; - /** - * Id of the user - */ - protected Long userId; + /** + * 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 ( ) { - } + /** + * Default constructor. This will set all the attributes to default value. + */ + public VXGroupUser() { + } - /** - * This method sets the value to the member attribute name. - * You cannot set null to the attribute. - * @param name Value to set member attribute name - */ - public void setName( String name ) { - this.name = name; - } + /** + * Returns the value for the member attribute name + * @return String - value of member attribute name. + */ + public String getName() { + return this.name; + } - /** - * Returns the value for the member attribute name - * @return String - value of member attribute name. - */ - public String getName( ) { - return this.name; - } + /** + * This method sets the value to the member attribute name. + * You cannot set null to the attribute. + * @param name Value to set member attribute name + */ + public void setName(String name) { + this.name = name; + } - /** - * This method sets the value to the member attribute parentGroupId. - * You cannot set null to the attribute. - * @param parentGroupId Value to set member attribute parentGroupId - */ - public void setParentGroupId( Long parentGroupId ) { - this.parentGroupId = parentGroupId; - } + /** + * Returns the value for the member attribute parentGroupId + * @return Long - value of member attribute parentGroupId. + */ + public Long getParentGroupId() { + return this.parentGroupId; + } - /** - * Returns the value for the member attribute parentGroupId - * @return Long - value of member attribute parentGroupId. - */ - public Long getParentGroupId( ) { - return this.parentGroupId; - } + /** + * This method sets the value to the member attribute parentGroupId. + * You cannot set null to the attribute. + * @param parentGroupId Value to set member attribute parentGroupId + */ + public void setParentGroupId(Long parentGroupId) { + this.parentGroupId = parentGroupId; + } - /** - * This method sets the value to the member attribute userId. - * You cannot set null to the attribute. - * @param userId Value to set member attribute userId - */ - public void setUserId( Long userId ) { - this.userId = userId; - } + /** + * Returns the value for the member attribute userId + * @return Long - value of member attribute userId. + */ + public Long getUserId() { + return this.userId; + } - /** - * Returns the value for the member attribute userId - * @return Long - value of member attribute userId. - */ - public Long getUserId( ) { - return this.userId; - } + /** + * This method sets the value to the member attribute userId. + * You cannot set null to the attribute. + * @param userId Value to set member attribute userId + */ + public void setUserId(Long userId) { + this.userId = userId; + } - @Override - public int getMyClassType( ) { - return AppConstants.CLASS_TYPE_XA_GROUP_USER; - } + @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; - } + /** + * 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; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/view/VXGroupUserInfo.java b/security-admin/src/main/java/org/apache/ranger/view/VXGroupUserInfo.java index 7e945283ea..860ab7deeb 100644 --- a/security-admin/src/main/java/org/apache/ranger/view/VXGroupUserInfo.java +++ b/security-admin/src/main/java/org/apache/ranger/view/VXGroupUserInfo.java @@ -17,47 +17,44 @@ * under the License. */ - package org.apache.ranger.view; +package org.apache.ranger.view; /** * UserGroupInfo - * */ -import java.util.List; - import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; -@JsonAutoDetect(getterVisibility=Visibility.NONE, setterVisibility=Visibility.NONE, fieldVisibility=Visibility.ANY) +import java.util.List; + +@JsonAutoDetect(getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE, fieldVisibility = Visibility.ANY) @JsonInclude(JsonInclude.Include.NON_NULL) -@JsonIgnoreProperties(ignoreUnknown=true) -public class VXGroupUserInfo extends VXDataObject implements java.io.Serializable { - - private static final long serialVersionUID = 1L; - - VXGroup xgroupInfo; - List xuserInfo; - - public VXGroupUserInfo ( ) { - } - - public VXGroup getXgroupInfo() { - return xgroupInfo; - } - - public void setXgroupInfo(VXGroup xgroupInfo) { - this.xgroupInfo = xgroupInfo; - } - - public List getXuserInfo() { - return xuserInfo; - } - - public void setXuserInfo(List xuserInfo) { - this.xuserInfo = xuserInfo; - } +@JsonIgnoreProperties(ignoreUnknown = true) +public class VXGroupUserInfo extends VXDataObject implements java.io.Serializable { + private static final long serialVersionUID = 1L; + + VXGroup xgroupInfo; + List xuserInfo; + + public VXGroupUserInfo() { + } + + public VXGroup getXgroupInfo() { + return xgroupInfo; + } + + public void setXgroupInfo(VXGroup xgroupInfo) { + this.xgroupInfo = xgroupInfo; + } + + public List getXuserInfo() { + return xuserInfo; + } + public void setXuserInfo(List xuserInfo) { + this.xuserInfo = xuserInfo; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/view/VXGroupUserList.java b/security-admin/src/main/java/org/apache/ranger/view/VXGroupUserList.java index 38a0949071..203857125a 100644 --- a/security-admin/src/main/java/org/apache/ranger/view/VXGroupUserList.java +++ b/security-admin/src/main/java/org/apache/ranger/view/VXGroupUserList.java @@ -17,35 +17,35 @@ * under the License. */ - package org.apache.ranger.view; +package org.apache.ranger.view; /** * List wrapper class for VXGroupUser - * */ -import java.util.ArrayList; -import java.util.List; - -import org.apache.ranger.common.view.VList; -import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import org.apache.ranger.common.view.VList; + +import java.util.ArrayList; +import java.util.List; -@JsonAutoDetect(getterVisibility=Visibility.NONE, setterVisibility=Visibility.NONE, fieldVisibility=Visibility.ANY) +@JsonAutoDetect(getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE, fieldVisibility = Visibility.ANY) @JsonInclude(JsonInclude.Include.NON_NULL) public class VXGroupUserList extends VList { - private static final long serialVersionUID = 1L; - List vXGroupUsers = new ArrayList(); + private static final long serialVersionUID = 1L; + + List vXGroupUsers = new ArrayList<>(); public VXGroupUserList() { - super(); + super(); } public VXGroupUserList(List objList) { - super(objList); - this.vXGroupUsers = objList; + super(objList); + this.vXGroupUsers = objList; } /** @@ -53,7 +53,7 @@ public VXGroupUserList(List objList) { */ @JsonProperty("vXGroupUsers") public List getVXGroupUsers() { - return vXGroupUsers; + return vXGroupUsers; } /** @@ -62,20 +62,19 @@ public List getVXGroupUsers() { */ @JsonProperty("vXGroupUsers") public void setVXGroupUsers(List vXGroupUsers) { - this.vXGroupUsers = vXGroupUsers; + this.vXGroupUsers = vXGroupUsers; } @Override public int getListSize() { - if (vXGroupUsers != null) { - return vXGroupUsers.size(); - } - return 0; + if (vXGroupUsers != null) { + return vXGroupUsers.size(); + } + return 0; } @Override public List getList() { - return vXGroupUsers; + return vXGroupUsers; } - } diff --git a/security-admin/src/main/java/org/apache/ranger/view/VXKmsKey.java b/security-admin/src/main/java/org/apache/ranger/view/VXKmsKey.java index 4f843c1044..a9937c14cb 100755 --- a/security-admin/src/main/java/org/apache/ranger/view/VXKmsKey.java +++ b/security-admin/src/main/java/org/apache/ranger/view/VXKmsKey.java @@ -17,220 +17,219 @@ * under the License. */ - package org.apache.ranger.view; +package org.apache.ranger.view; /** * Key - * */ -import java.util.Map; - -import org.apache.ranger.common.AppConstants; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; +import org.apache.ranger.common.AppConstants; + +import java.util.Map; -@JsonAutoDetect(getterVisibility=Visibility.NONE, setterVisibility=Visibility.NONE, fieldVisibility=Visibility.ANY) +@JsonAutoDetect(getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE, fieldVisibility = Visibility.ANY) @JsonInclude(JsonInclude.Include.NON_NULL) -@JsonIgnoreProperties(ignoreUnknown=true) +@JsonIgnoreProperties(ignoreUnknown = true) public class VXKmsKey extends VXDataObject implements java.io.Serializable { - private static final long serialVersionUID = 1L; - - /** - * Name - */ - protected String name; - /** - * Cipher - */ - protected String cipher; - /** - * Length - */ - protected int length; - /** - * Description - */ - protected String description; - /** - * Version - */ - protected int versions; - /** - * Material - */ - protected String material; - /** - * Version Name - */ - protected String versionName; - - /** - * Key Created Date - */ - protected Long created; - - /** - * Attributes - */ - protected Map attributes; - - /** - * Default constructor. This will set all the attributes to default value. - */ - public VXKmsKey ( ) { - } - - /** - * @return the name - */ - public String getName() { - return name; - } - - /** - * @param name the name to set - */ - public void setName(String name) { - this.name = name; - } - - /** - * @return the cipher - */ - public String getCipher() { - return cipher; - } - - /** - * @param cipher the cipher to set - */ - public void setCipher(String cipher) { - this.cipher = cipher; - } - - /** - * @return the length - */ - public int getLength() { - return length; - } - - /** - * @param length the length to set - */ - public void setLength(int length) { - this.length = length; - } - - /** - * @return the description - */ - public String getDescription() { - return description; - } - - /** - * @param description the description to set - */ - public void setDescription(String description) { - this.description = description; - } - - /** - * @return the version - */ - public int getVersions() { - return versions; - } - - /** - * @param version the version to set - */ - public void setVersions(int versions) { - this.versions = versions; - } - - /** - * @return the material - */ - public String getMaterial() { - return material; - } - - /** - * @param material the material to set - */ - public void setMaterial(String material) { - this.material = material; - } - - /** - * @return the versionName - */ - public String getVersionName() { - return versionName; - } - - /** - * @param versionName the versionName to set - */ - public void setVersionName(String versionName) { - this.versionName = versionName; - } - - /** - * @return the created - */ - public Long getCreated() { - return created; - } - - /** - * @param created the created to set - */ - public void setCreated(Long created) { - this.created = created; - } - - /** - * @return the attributes - */ - public Map getAttributes() { - return attributes; - } - - /** - * @param attributes the attributes to set - */ - public void setAttributes(Map attributes) { - this.attributes = attributes; - } - - @Override - public int getMyClassType( ) { - return AppConstants.CLASS_TYPE_XA_KMS_KEY; - } - - /** - * This return the bean content in string format - * @return formatedStr - */ - public String toString( ) { - String str = "VXUser={"; - str += super.toString(); - str += "name={" + name + "} "; - str += "cipher={" + cipher + "} "; - str += "length={" + length + "} "; - str += "description={" + description + "} "; - str += "atrribute={" + attributes + "} "; - str += "created={" + created.toString() + "} "; - str += "version={" + versions + "} "; - str += "material={" + material + "} "; - str += "versionName={" + versionName + "} "; - str += "}"; - return str; - } + private static final long serialVersionUID = 1L; + + /** + * Name + */ + protected String name; + /** + * Cipher + */ + protected String cipher; + /** + * Length + */ + protected int length; + /** + * Description + */ + protected String description; + /** + * Version + */ + protected int versions; + /** + * Material + */ + protected String material; + /** + * Version Name + */ + protected String versionName; + + /** + * Key Created Date + */ + protected Long created; + + /** + * Attributes + */ + protected Map attributes; + + /** + * Default constructor. This will set all the attributes to default value. + */ + public VXKmsKey() { + } + + /** + * @return the name + */ + public String getName() { + return name; + } + + /** + * @param name the name to set + */ + public void setName(String name) { + this.name = name; + } + + /** + * @return the cipher + */ + public String getCipher() { + return cipher; + } + + /** + * @param cipher the cipher to set + */ + public void setCipher(String cipher) { + this.cipher = cipher; + } + + /** + * @return the length + */ + public int getLength() { + return length; + } + + /** + * @param length the length to set + */ + public void setLength(int length) { + this.length = length; + } + + /** + * @return the description + */ + public String getDescription() { + return description; + } + + /** + * @param description the description to set + */ + public void setDescription(String description) { + this.description = description; + } + + /** + * @return the version + */ + public int getVersions() { + return versions; + } + + /** + * @param version the version to set + */ + public void setVersions(int versions) { + this.versions = versions; + } + + /** + * @return the material + */ + public String getMaterial() { + return material; + } + + /** + * @param material the material to set + */ + public void setMaterial(String material) { + this.material = material; + } + + /** + * @return the versionName + */ + public String getVersionName() { + return versionName; + } + + /** + * @param versionName the versionName to set + */ + public void setVersionName(String versionName) { + this.versionName = versionName; + } + + /** + * @return the created + */ + public Long getCreated() { + return created; + } + + /** + * @param created the created to set + */ + public void setCreated(Long created) { + this.created = created; + } + + /** + * @return the attributes + */ + public Map getAttributes() { + return attributes; + } + + /** + * @param attributes the attributes to set + */ + public void setAttributes(Map attributes) { + this.attributes = attributes; + } + + @Override + public int getMyClassType() { + return AppConstants.CLASS_TYPE_XA_KMS_KEY; + } + + /** + * This return the bean content in string format + * @return formatedStr + */ + public String toString() { + String str = "VXUser={"; + str += super.toString(); + str += "name={" + name + "} "; + str += "cipher={" + cipher + "} "; + str += "length={" + length + "} "; + str += "description={" + description + "} "; + str += "atrribute={" + attributes + "} "; + str += "created={" + created.toString() + "} "; + str += "version={" + versions + "} "; + str += "material={" + material + "} "; + str += "versionName={" + versionName + "} "; + str += "}"; + return str; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/view/VXKmsKeyList.java b/security-admin/src/main/java/org/apache/ranger/view/VXKmsKeyList.java index 95d804e86f..65e73549cc 100644 --- a/security-admin/src/main/java/org/apache/ranger/view/VXKmsKeyList.java +++ b/security-admin/src/main/java/org/apache/ranger/view/VXKmsKeyList.java @@ -17,35 +17,35 @@ * under the License. */ - package org.apache.ranger.view; +package org.apache.ranger.view; /** * List wrapper class for VXKey - * */ -import java.util.ArrayList; -import java.util.List; - -import org.apache.ranger.common.view.VList; -import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import org.apache.ranger.common.view.VList; + +import java.util.ArrayList; +import java.util.List; -@JsonAutoDetect(getterVisibility=Visibility.NONE, setterVisibility=Visibility.NONE, fieldVisibility=Visibility.ANY) +@JsonAutoDetect(getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE, fieldVisibility = Visibility.ANY) @JsonInclude(JsonInclude.Include.NON_NULL) public class VXKmsKeyList extends VList { - private static final long serialVersionUID = 1L; - List vXKeys = new ArrayList(); + private static final long serialVersionUID = 1L; + + List vXKeys = new ArrayList<>(); public VXKmsKeyList() { - super(); + super(); } public VXKmsKeyList(List objList) { - super(objList); - this.vXKeys = objList; + super(objList); + this.vXKeys = objList; } /** @@ -53,7 +53,7 @@ public VXKmsKeyList(List objList) { */ @JsonProperty("vXKeys") public List getVXKeys() { - return vXKeys; + return vXKeys; } /** @@ -62,20 +62,19 @@ public List getVXKeys() { */ @JsonProperty("vXKeys") public void setVXKeys(List vXKeys) { - this.vXKeys = vXKeys; + this.vXKeys = vXKeys; } @Override public int getListSize() { - if (vXKeys != null) { - return vXKeys.size(); - } - return 0; + if (vXKeys != null) { + return vXKeys.size(); + } + return 0; } @Override public List getList() { - return vXKeys; + return vXKeys; } - } diff --git a/security-admin/src/main/java/org/apache/ranger/view/VXLdapSyncSourceInfo.java b/security-admin/src/main/java/org/apache/ranger/view/VXLdapSyncSourceInfo.java index 8ce523fe28..0f82ba0a12 100644 --- a/security-admin/src/main/java/org/apache/ranger/view/VXLdapSyncSourceInfo.java +++ b/security-admin/src/main/java/org/apache/ranger/view/VXLdapSyncSourceInfo.java @@ -17,11 +17,10 @@ * under the License. */ - package org.apache.ranger.view; +package org.apache.ranger.view; /** * UserGroupInfo - * */ import com.fasterxml.jackson.annotation.JsonAutoDetect; @@ -29,147 +28,145 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; -@JsonAutoDetect(getterVisibility=Visibility.NONE, setterVisibility=Visibility.NONE, fieldVisibility=Visibility.ANY) +@JsonAutoDetect(getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE, fieldVisibility = Visibility.ANY) @JsonInclude(JsonInclude.Include.NON_NULL) -@JsonIgnoreProperties(ignoreUnknown=true) -public class VXLdapSyncSourceInfo implements java.io.Serializable { - - private static final long serialVersionUID = 1L; - - private String ldapUrl; - private String incrementalSycn; - private String groupSearchFirstEnabled; - private String groupSearchEnabled; - private String userSearchEnabled; - private String userSearchFilter; - private String groupSearchFilter; - private String groupHierarchyLevel; - private long totalUsersSynced; - private long totalGroupsSynced; - private long totalUsersDeleted; - private long totalGroupsDeleted; - - public VXLdapSyncSourceInfo() { - } - - public String getLdapUrl() { - return ldapUrl; - } - - public void setLdapUrl(String ldapUrl) { - this.ldapUrl = ldapUrl; - } - - public String isIncrementalSycn() { - return incrementalSycn; - } - - public void setIncrementalSycn(String incrementalSycn) { - this.incrementalSycn = incrementalSycn; - } - - public String getUserSearchFilter() { - return userSearchFilter; - } - - public void setUserSearchFilter(String userSearchFilter) { - this.userSearchFilter = userSearchFilter; - } - - public String getGroupSearchFilter() { - return groupSearchFilter; - } - - public void setGroupSearchFilter(String groupSearchFilter) { - this.groupSearchFilter = groupSearchFilter; - } - - public String getGroupHierarchyLevel() { - return groupHierarchyLevel; - } - - public void setGroupHierarchyLevel(String groupHierarchyLevel) { - this.groupHierarchyLevel = groupHierarchyLevel; - } - - public long getTotalUsersSynced() { - return totalUsersSynced; - } - - public void setTotalUsersSynced(long totalUsersSynced) { - this.totalUsersSynced = totalUsersSynced; - } - - public long getTotalGroupsSynced() { - return totalGroupsSynced; - } - - public void setTotalGroupsSynced(long totalGroupsSynced) { - this.totalGroupsSynced = totalGroupsSynced; - } - - public String getGroupSearchFirstEnabled() { - return groupSearchFirstEnabled; - } - - public void setGroupSearchFirstEnabled(String groupSearchFirstEnabled) { - this.groupSearchFirstEnabled = groupSearchFirstEnabled; - } - - public String getGroupSearchEnabled() { - return groupSearchEnabled; - } - - public void setGroupSearchEnabled(String groupSearchEnabled) { - this.groupSearchEnabled = groupSearchEnabled; - } - - public String getUserSearchEnabled() { - return userSearchEnabled; - } - - public void setUserSearchEnabled(String userSearchEnabled) { - this.userSearchEnabled = userSearchEnabled; - } - - public long getTotalUsersDeleted() { - return totalUsersDeleted; - } - - public void setTotalUsersDeleted(long totalUsersDeleted) { - this.totalUsersDeleted = totalUsersDeleted; - } - - public long getTotalGroupsDeleted() { - return totalGroupsDeleted; - } - - public void setTotalGroupsDeleted(long totalGroupsDeleted) { - this.totalGroupsDeleted = totalGroupsDeleted; - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - toString(sb); - return sb.toString(); - } - - public StringBuilder toString(StringBuilder sb) { - sb.append("{\"ldapUrl\":\"").append(ldapUrl); - sb.append("\", \"isIncrementalSync\":\"").append(incrementalSycn); - sb.append("\", \"userSearchEnabled\":\"").append(userSearchEnabled); - sb.append("\", \"groupSearchEnabled\":\"").append(groupSearchEnabled); - sb.append("\", \"groupSearchFirstEnabled\":\"").append(groupSearchFirstEnabled); - sb.append("\", \"userSearchFilter\":\"").append(userSearchFilter); - sb.append("\", \"groupSearchFilter\":\"").append(groupSearchFilter); - sb.append("\", \"groupHierarchyLevel\":\"").append(groupHierarchyLevel); - sb.append("\", \"totalUsersSynced\":\"").append(totalUsersSynced); - sb.append("\", \"totalGroupsSynced\":\"").append(totalGroupsSynced); - sb.append("\", \"totalUsersDeleted\":\"").append(totalUsersDeleted); - sb.append("\", \"totalGroupsDeleted\":\"").append(totalGroupsDeleted); - sb.append("\"}"); - return sb; - } - +@JsonIgnoreProperties(ignoreUnknown = true) +public class VXLdapSyncSourceInfo implements java.io.Serializable { + private static final long serialVersionUID = 1L; + + private String ldapUrl; + private String incrementalSycn; + private String groupSearchFirstEnabled; + private String groupSearchEnabled; + private String userSearchEnabled; + private String userSearchFilter; + private String groupSearchFilter; + private String groupHierarchyLevel; + private long totalUsersSynced; + private long totalGroupsSynced; + private long totalUsersDeleted; + private long totalGroupsDeleted; + + public VXLdapSyncSourceInfo() { + } + + public String getLdapUrl() { + return ldapUrl; + } + + public void setLdapUrl(String ldapUrl) { + this.ldapUrl = ldapUrl; + } + + public String isIncrementalSycn() { + return incrementalSycn; + } + + public void setIncrementalSycn(String incrementalSycn) { + this.incrementalSycn = incrementalSycn; + } + + public String getUserSearchFilter() { + return userSearchFilter; + } + + public void setUserSearchFilter(String userSearchFilter) { + this.userSearchFilter = userSearchFilter; + } + + public String getGroupSearchFilter() { + return groupSearchFilter; + } + + public void setGroupSearchFilter(String groupSearchFilter) { + this.groupSearchFilter = groupSearchFilter; + } + + public String getGroupHierarchyLevel() { + return groupHierarchyLevel; + } + + public void setGroupHierarchyLevel(String groupHierarchyLevel) { + this.groupHierarchyLevel = groupHierarchyLevel; + } + + public long getTotalUsersSynced() { + return totalUsersSynced; + } + + public void setTotalUsersSynced(long totalUsersSynced) { + this.totalUsersSynced = totalUsersSynced; + } + + public long getTotalGroupsSynced() { + return totalGroupsSynced; + } + + public void setTotalGroupsSynced(long totalGroupsSynced) { + this.totalGroupsSynced = totalGroupsSynced; + } + + public String getGroupSearchFirstEnabled() { + return groupSearchFirstEnabled; + } + + public void setGroupSearchFirstEnabled(String groupSearchFirstEnabled) { + this.groupSearchFirstEnabled = groupSearchFirstEnabled; + } + + public String getGroupSearchEnabled() { + return groupSearchEnabled; + } + + public void setGroupSearchEnabled(String groupSearchEnabled) { + this.groupSearchEnabled = groupSearchEnabled; + } + + public String getUserSearchEnabled() { + return userSearchEnabled; + } + + public void setUserSearchEnabled(String userSearchEnabled) { + this.userSearchEnabled = userSearchEnabled; + } + + public long getTotalUsersDeleted() { + return totalUsersDeleted; + } + + public void setTotalUsersDeleted(long totalUsersDeleted) { + this.totalUsersDeleted = totalUsersDeleted; + } + + public long getTotalGroupsDeleted() { + return totalGroupsDeleted; + } + + public void setTotalGroupsDeleted(long totalGroupsDeleted) { + this.totalGroupsDeleted = totalGroupsDeleted; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + toString(sb); + return sb.toString(); + } + + public StringBuilder toString(StringBuilder sb) { + sb.append("{\"ldapUrl\":\"").append(ldapUrl); + sb.append("\", \"isIncrementalSync\":\"").append(incrementalSycn); + sb.append("\", \"userSearchEnabled\":\"").append(userSearchEnabled); + sb.append("\", \"groupSearchEnabled\":\"").append(groupSearchEnabled); + sb.append("\", \"groupSearchFirstEnabled\":\"").append(groupSearchFirstEnabled); + sb.append("\", \"userSearchFilter\":\"").append(userSearchFilter); + sb.append("\", \"groupSearchFilter\":\"").append(groupSearchFilter); + sb.append("\", \"groupHierarchyLevel\":\"").append(groupHierarchyLevel); + sb.append("\", \"totalUsersSynced\":\"").append(totalUsersSynced); + sb.append("\", \"totalGroupsSynced\":\"").append(totalGroupsSynced); + sb.append("\", \"totalUsersDeleted\":\"").append(totalUsersDeleted); + sb.append("\", \"totalGroupsDeleted\":\"").append(totalGroupsDeleted); + sb.append("\"}"); + return sb; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/view/VXLong.java b/security-admin/src/main/java/org/apache/ranger/view/VXLong.java index 26cc797499..d3c70439e9 100644 --- a/security-admin/src/main/java/org/apache/ranger/view/VXLong.java +++ b/security-admin/src/main/java/org/apache/ranger/view/VXLong.java @@ -17,69 +17,67 @@ * under the License. */ - package org.apache.ranger.view; +package org.apache.ranger.view; /** * Long - * */ -import org.apache.ranger.common.AppConstants; -import org.apache.ranger.common.view.ViewBaseBean; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; +import org.apache.ranger.common.AppConstants; +import org.apache.ranger.common.view.ViewBaseBean; -@JsonAutoDetect(getterVisibility=Visibility.NONE, setterVisibility=Visibility.NONE, fieldVisibility=Visibility.ANY) +@JsonAutoDetect(getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE, fieldVisibility = Visibility.ANY) @JsonInclude(JsonInclude.Include.NON_NULL) -@JsonIgnoreProperties(ignoreUnknown=true) +@JsonIgnoreProperties(ignoreUnknown = true) public class VXLong extends ViewBaseBean implements java.io.Serializable { - private static final long serialVersionUID = 1L; - + private static final long serialVersionUID = 1L; - /** - * Value - */ - protected long value; + /** + * Value + */ + protected long value; - /** - * Default constructor. This will set all the attributes to default value. - */ - public VXLong ( ) { - } + /** + * Default constructor. This will set all the attributes to default value. + */ + public VXLong() { + } - /** - * This method sets the value to the member attribute value. - * You cannot set null to the attribute. - * @param value Value to set member attribute value - */ - public void setValue( long value ) { - this.value = value; - } + /** + * Returns the value for the member attribute value + * @return long - value of member attribute value. + */ + public long getValue() { + return this.value; + } - /** - * Returns the value for the member attribute value - * @return long - value of member attribute value. - */ - public long getValue( ) { - return this.value; - } + /** + * This method sets the value to the member attribute value. + * You cannot set null to the attribute. + * @param value Value to set member attribute value + */ + public void setValue(long value) { + this.value = value; + } - @Override - public int getMyClassType( ) { - return AppConstants.CLASS_TYPE_LONG; - } + @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; - } + /** + * 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; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/view/VXMessage.java b/security-admin/src/main/java/org/apache/ranger/view/VXMessage.java index c02ad51b89..7c0eb2dadc 100644 --- a/security-admin/src/main/java/org/apache/ranger/view/VXMessage.java +++ b/security-admin/src/main/java/org/apache/ranger/view/VXMessage.java @@ -17,157 +17,155 @@ * under the License. */ - package org.apache.ranger.view; +package org.apache.ranger.view; /** * Message class - * */ -import org.apache.ranger.common.AppConstants; -import org.apache.ranger.common.view.ViewBaseBean; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; +import org.apache.ranger.common.AppConstants; +import org.apache.ranger.common.view.ViewBaseBean; -@JsonAutoDetect(getterVisibility=Visibility.NONE, setterVisibility=Visibility.NONE, fieldVisibility=Visibility.ANY) +@JsonAutoDetect(getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE, fieldVisibility = Visibility.ANY) @JsonInclude(JsonInclude.Include.NON_NULL) -@JsonIgnoreProperties(ignoreUnknown=true) +@JsonIgnoreProperties(ignoreUnknown = true) 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 name. - * You cannot set null to the attribute. - * @param name Value to set member attribute name - */ - public void setName( String name ) { - this.name = name; - } - - /** - * Returns the value for the member attribute name - * @return String - value of member attribute name. - */ - public String getName( ) { - return this.name; - } - - /** - * This method sets the value to the member attribute rbKey. - * You cannot set null to the attribute. - * @param rbKey Value to set member attribute rbKey - */ - public void setRbKey( String rbKey ) { - this.rbKey = rbKey; - } - - /** - * Returns the value for the member attribute rbKey - * @return String - value of member attribute rbKey. - */ - public String getRbKey( ) { - return this.rbKey; - } - - /** - * This method sets the value to the member attribute message. - * You cannot set null to the attribute. - * @param message Value to set member attribute message - */ - public void setMessage( String message ) { - this.message = message; - } - - /** - * Returns the value for the member attribute message - * @return String - value of member attribute message. - */ - public String getMessage( ) { - return this.message; - } - - /** - * This method sets the value to the member attribute objectId. - * You cannot set null to the attribute. - * @param objectId Value to set member attribute objectId - */ - public void setObjectId( Long objectId ) { - this.objectId = objectId; - } - - /** - * Returns the value for the member attribute objectId - * @return Long - value of member attribute objectId. - */ - public Long getObjectId( ) { - return this.objectId; - } - - /** - * This method sets the value to the member attribute fieldName. - * You cannot set null to the attribute. - * @param fieldName Value to set member attribute fieldName - */ - public void setFieldName( String fieldName ) { - this.fieldName = fieldName; - } - - /** - * Returns the value for the member attribute fieldName - * @return String - value of member attribute fieldName. - */ - 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; - } + 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() { + } + + /** + * Returns the value for the member attribute name + * @return String - value of member attribute name. + */ + public String getName() { + return this.name; + } + + /** + * This method sets the value to the member attribute name. + * You cannot set null to the attribute. + * @param name Value to set member attribute name + */ + public void setName(String name) { + this.name = name; + } + + /** + * Returns the value for the member attribute rbKey + * @return String - value of member attribute rbKey. + */ + public String getRbKey() { + return this.rbKey; + } + + /** + * This method sets the value to the member attribute rbKey. + * You cannot set null to the attribute. + * @param rbKey Value to set member attribute rbKey + */ + public void setRbKey(String rbKey) { + this.rbKey = rbKey; + } + + /** + * Returns the value for the member attribute message + * @return String - value of member attribute message. + */ + public String getMessage() { + return this.message; + } + + /** + * This method sets the value to the member attribute message. + * You cannot set null to the attribute. + * @param message Value to set member attribute message + */ + public void setMessage(String message) { + this.message = message; + } + + /** + * Returns the value for the member attribute objectId + * @return Long - value of member attribute objectId. + */ + public Long getObjectId() { + return this.objectId; + } + + /** + * This method sets the value to the member attribute objectId. + * You cannot set null to the attribute. + * @param objectId Value to set member attribute objectId + */ + public void setObjectId(Long objectId) { + this.objectId = objectId; + } + + /** + * Returns the value for the member attribute fieldName + * @return String - value of member attribute fieldName. + */ + public String getFieldName() { + return this.fieldName; + } + + /** + * This method sets the value to the member attribute fieldName. + * You cannot set null to the attribute. + * @param fieldName Value to set member attribute fieldName + */ + public void setFieldName(String fieldName) { + this.fieldName = 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; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/view/VXMetricAuditDetailsCount.java b/security-admin/src/main/java/org/apache/ranger/view/VXMetricAuditDetailsCount.java index 01410dc975..66f4ea7418 100644 --- a/security-admin/src/main/java/org/apache/ranger/view/VXMetricAuditDetailsCount.java +++ b/security-admin/src/main/java/org/apache/ranger/view/VXMetricAuditDetailsCount.java @@ -20,107 +20,119 @@ import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; import com.fasterxml.jackson.annotation.JsonInclude; -@JsonAutoDetect(getterVisibility=Visibility.NONE, setterVisibility=Visibility.NONE, fieldVisibility=Visibility.ANY) +@JsonAutoDetect(getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE, fieldVisibility = Visibility.ANY) @JsonInclude(JsonInclude.Include.NON_NULL) public class VXMetricAuditDetailsCount implements java.io.Serializable { - private static final long serialVersionUID = 1L; - - protected Long solrIndexCountTwoDays; - protected VXMetricServiceCount accessEventsCountTwoDays; - protected VXMetricServiceCount denialEventsCountTwoDays; - protected Long solrIndexCountWeek; - protected VXMetricServiceCount accessEventsCountWeek; - protected VXMetricServiceCount denialEventsCountWeek; - /** - * Default constructor. This will set all the attributes to default value. - */ - public VXMetricAuditDetailsCount() { - } - /** - * @return the solrIndexCountTwoDays - */ - public Long getSolrIndexCountTwoDays() { - return solrIndexCountTwoDays; - } - /** - * @param solrIndexCountTwoDays the solrIndexCountTwoDays to set - */ - public void setSolrIndexCountTwoDays(Long solrIndexCountTwoDays) { - this.solrIndexCountTwoDays = solrIndexCountTwoDays; - } - /** - * @return the accessEventsCountTwoDays - */ - public VXMetricServiceCount getAccessEventsCountTwoDays() { - return accessEventsCountTwoDays; - } - /** - * @param accessEventsCountTwoDays the accessEventsCountTwoDays to set - */ - public void setAccessEventsCountTwoDays( - VXMetricServiceCount accessEventsCountTwoDays) { - this.accessEventsCountTwoDays = accessEventsCountTwoDays; - } - /** - * @return the denialEventsCountTwoDays - */ - public VXMetricServiceCount getDenialEventsCountTwoDays() { - return denialEventsCountTwoDays; - } - /** - * @param denialEventsCountTwoDays the denialEventsCountTwoDays to set - */ - public void setDenialEventsCountTwoDays( - VXMetricServiceCount denialEventsCountTwoDays) { - this.denialEventsCountTwoDays = denialEventsCountTwoDays; - } - /** - * @return the solrIndexCountWeek - */ - public Long getSolrIndexCountWeek() { - return solrIndexCountWeek; - } - /** - * @param solrIndexCountWeek the solrIndexCountWeek to set - */ - public void setSolrIndexCountWeek(Long solrIndexCountWeek) { - this.solrIndexCountWeek = solrIndexCountWeek; - } - /** - * @return the accessEventsCountWeek - */ - public VXMetricServiceCount getAccessEventsCountWeek() { - return accessEventsCountWeek; - } - /** - * @param accessEventsCountWeek the accessEventsCountWeek to set - */ - public void setAccessEventsCountWeek(VXMetricServiceCount accessEventsCountWeek) { - this.accessEventsCountWeek = accessEventsCountWeek; - } - /** - * @return the denialEventsCountWeek - */ - public VXMetricServiceCount getDenialEventsCountWeek() { - return denialEventsCountWeek; - } - /** - * @param denialEventsCountWeek the denialEventsCountWeek to set - */ - public void setDenialEventsCountWeek(VXMetricServiceCount denialEventsCountWeek) { - this.denialEventsCountWeek = denialEventsCountWeek; - } - /* (non-Javadoc) - * @see java.lang.Object#toString() - */ - @Override - public String toString() { - return "VXMetricAuditDetailsCount [solrIndexCountTwoDays=" - + solrIndexCountTwoDays + ", accessEventsCountTwoDays=" - + accessEventsCountTwoDays + ", denialEventsCountTwoDays=" - + denialEventsCountTwoDays + ", solrIndexCountWeek=" - + solrIndexCountWeek + ", accessEventsCountWeek=" - + accessEventsCountWeek + ", denialEventsCountWeek=" - + denialEventsCountWeek + "]"; - } + private static final long serialVersionUID = 1L; + + protected Long solrIndexCountTwoDays; + protected VXMetricServiceCount accessEventsCountTwoDays; + protected VXMetricServiceCount denialEventsCountTwoDays; + protected Long solrIndexCountWeek; + protected VXMetricServiceCount accessEventsCountWeek; + protected VXMetricServiceCount denialEventsCountWeek; + + /** + * Default constructor. This will set all the attributes to default value. + */ + public VXMetricAuditDetailsCount() { + } + + /** + * @return the solrIndexCountTwoDays + */ + public Long getSolrIndexCountTwoDays() { + return solrIndexCountTwoDays; + } + + /** + * @param solrIndexCountTwoDays the solrIndexCountTwoDays to set + */ + public void setSolrIndexCountTwoDays(Long solrIndexCountTwoDays) { + this.solrIndexCountTwoDays = solrIndexCountTwoDays; + } + + /** + * @return the accessEventsCountTwoDays + */ + public VXMetricServiceCount getAccessEventsCountTwoDays() { + return accessEventsCountTwoDays; + } + + /** + * @param accessEventsCountTwoDays the accessEventsCountTwoDays to set + */ + public void setAccessEventsCountTwoDays(VXMetricServiceCount accessEventsCountTwoDays) { + this.accessEventsCountTwoDays = accessEventsCountTwoDays; + } + + /** + * @return the denialEventsCountTwoDays + */ + public VXMetricServiceCount getDenialEventsCountTwoDays() { + return denialEventsCountTwoDays; + } + + /** + * @param denialEventsCountTwoDays the denialEventsCountTwoDays to set + */ + public void setDenialEventsCountTwoDays(VXMetricServiceCount denialEventsCountTwoDays) { + this.denialEventsCountTwoDays = denialEventsCountTwoDays; + } + + /** + * @return the solrIndexCountWeek + */ + public Long getSolrIndexCountWeek() { + return solrIndexCountWeek; + } + + /** + * @param solrIndexCountWeek the solrIndexCountWeek to set + */ + public void setSolrIndexCountWeek(Long solrIndexCountWeek) { + this.solrIndexCountWeek = solrIndexCountWeek; + } + + /** + * @return the accessEventsCountWeek + */ + public VXMetricServiceCount getAccessEventsCountWeek() { + return accessEventsCountWeek; + } + + /** + * @param accessEventsCountWeek the accessEventsCountWeek to set + */ + public void setAccessEventsCountWeek(VXMetricServiceCount accessEventsCountWeek) { + this.accessEventsCountWeek = accessEventsCountWeek; + } + + /** + * @return the denialEventsCountWeek + */ + public VXMetricServiceCount getDenialEventsCountWeek() { + return denialEventsCountWeek; + } + + /** + * @param denialEventsCountWeek the denialEventsCountWeek to set + */ + public void setDenialEventsCountWeek(VXMetricServiceCount denialEventsCountWeek) { + this.denialEventsCountWeek = denialEventsCountWeek; + } + + /* (non-Javadoc) + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + return "VXMetricAuditDetailsCount [solrIndexCountTwoDays=" + + solrIndexCountTwoDays + ", accessEventsCountTwoDays=" + + accessEventsCountTwoDays + ", denialEventsCountTwoDays=" + + denialEventsCountTwoDays + ", solrIndexCountWeek=" + + solrIndexCountWeek + ", accessEventsCountWeek=" + + accessEventsCountWeek + ", denialEventsCountWeek=" + + denialEventsCountWeek + "]"; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/view/VXMetricContextEnricher.java b/security-admin/src/main/java/org/apache/ranger/view/VXMetricContextEnricher.java index 1677ad0f21..bf391877da 100644 --- a/security-admin/src/main/java/org/apache/ranger/view/VXMetricContextEnricher.java +++ b/security-admin/src/main/java/org/apache/ranger/view/VXMetricContextEnricher.java @@ -17,50 +17,51 @@ package org.apache.ranger.view; public class VXMetricContextEnricher implements java.io.Serializable { - private static final long serialVersionUID = 1L; - - String serviceName; - int totalCount; - - /** - * Default constructor. This will set all the attributes to default value. - */ - public VXMetricContextEnricher() { - } - - /** - * @return the serviceName - */ - public String getServiceName() { - return serviceName; - } - /** - * @param serviceName the serviceName to set - */ - public void setServiceName(String serviceName) { - this.serviceName = serviceName; - } - /** - * @return the totalCount - */ - public int getTotalCount() { - return totalCount; - } - /** - * @param totalCount the totalCount to set - */ - public void setTotalCount(int totalCount) { - this.totalCount = totalCount; - } + private static final long serialVersionUID = 1L; - @Override - public String toString() { - String str = "VXMeticContextEnricher=["; - str += "serviceName={" + serviceName + "},"; - str += "totalCount={" + totalCount +"} "; - str += "]"; - return str; - } - + String serviceName; + int totalCount; + /** + * Default constructor. This will set all the attributes to default value. + */ + public VXMetricContextEnricher() { + } + + /** + * @return the serviceName + */ + public String getServiceName() { + return serviceName; + } + + /** + * @param serviceName the serviceName to set + */ + public void setServiceName(String serviceName) { + this.serviceName = serviceName; + } + + /** + * @return the totalCount + */ + public int getTotalCount() { + return totalCount; + } + + /** + * @param totalCount the totalCount to set + */ + public void setTotalCount(int totalCount) { + this.totalCount = totalCount; + } + + @Override + public String toString() { + String str = "VXMeticContextEnricher=["; + str += "serviceName={" + serviceName + "},"; + str += "totalCount={" + totalCount + "} "; + str += "]"; + return str; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/view/VXMetricPolicyCount.java b/security-admin/src/main/java/org/apache/ranger/view/VXMetricPolicyCount.java index a27dd092bc..f0305b2ab1 100644 --- a/security-admin/src/main/java/org/apache/ranger/view/VXMetricPolicyCount.java +++ b/security-admin/src/main/java/org/apache/ranger/view/VXMetricPolicyCount.java @@ -16,59 +16,57 @@ */ package org.apache.ranger.view; -import java.util.HashMap; -import java.util.Map; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; import com.fasterxml.jackson.annotation.JsonInclude; -@JsonAutoDetect(getterVisibility=Visibility.NONE, setterVisibility=Visibility.NONE, fieldVisibility=Visibility.ANY) +import java.util.HashMap; +import java.util.Map; + +@JsonAutoDetect(getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE, fieldVisibility = Visibility.ANY) @JsonInclude(JsonInclude.Include.NON_NULL) public class VXMetricPolicyCount implements java.io.Serializable { - private static final long serialVersionUID = 1L; - - protected Map policyCountList = new HashMap(); - protected long totalCount; - - /** - * Default constructor. This will set all the attributes to default value. - */ - public VXMetricPolicyCount() { - } + private static final long serialVersionUID = 1L; + + protected Map policyCountList = new HashMap<>(); + protected long totalCount; + + /** + * Default constructor. This will set all the attributes to default value. + */ + public VXMetricPolicyCount() { + } - /** - * @return the policyCountList - */ - public Map getPolicyCountList() { - return policyCountList; - } + /** + * @return the policyCountList + */ + public Map getPolicyCountList() { + return policyCountList; + } - /** - * @param policyCountList the policyCountList to set - */ - public void setPolicyCountList(Map policyCountList) { - this.policyCountList = policyCountList; - } + /** + * @param policyCountList the policyCountList to set + */ + public void setPolicyCountList(Map policyCountList) { + this.policyCountList = policyCountList; + } - /** - * @return the totalCount - */ - public long getTotalCount() { - return totalCount; - } + /** + * @return the totalCount + */ + public long getTotalCount() { + return totalCount; + } - /** - * @param totalCount the totalCount to set - */ - public void setTotalCount(long totalCount) { - this.totalCount = totalCount; - } + /** + * @param totalCount the totalCount to set + */ + public void setTotalCount(long totalCount) { + this.totalCount = totalCount; + } - @Override - public String toString() { - return "VXMetricPolicyCount={totalCount=" - + totalCount +", vXMetricServiceCount=[" - + policyCountList.toString() - + "]}"; - } + @Override + public String toString() { + return "VXMetricPolicyCount={totalCount=" + totalCount + ", vXMetricServiceCount=[" + policyCountList.toString() + "]}"; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/view/VXMetricPolicyWithServiceNameCount.java b/security-admin/src/main/java/org/apache/ranger/view/VXMetricPolicyWithServiceNameCount.java index 0b9b306fff..eba29fc211 100644 --- a/security-admin/src/main/java/org/apache/ranger/view/VXMetricPolicyWithServiceNameCount.java +++ b/security-admin/src/main/java/org/apache/ranger/view/VXMetricPolicyWithServiceNameCount.java @@ -16,59 +16,57 @@ */ package org.apache.ranger.view; -import java.util.HashMap; -import java.util.Map; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; import com.fasterxml.jackson.annotation.JsonInclude; -@JsonAutoDetect(getterVisibility=Visibility.NONE, setterVisibility=Visibility.NONE, fieldVisibility=Visibility.ANY) +import java.util.HashMap; +import java.util.Map; + +@JsonAutoDetect(getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE, fieldVisibility = Visibility.ANY) @JsonInclude(JsonInclude.Include.NON_NULL) public class VXMetricPolicyWithServiceNameCount implements java.io.Serializable { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; - protected Map policyCountList = new HashMap(); - protected long totalCount; + protected Map policyCountList = new HashMap<>(); + protected long totalCount; - /** - * Default constructor. This will set all the attributes to default value. - */ - public VXMetricPolicyWithServiceNameCount() { - } + /** + * Default constructor. This will set all the attributes to default value. + */ + public VXMetricPolicyWithServiceNameCount() { + } - /** - * @return the policyCountList - */ - public Map getPolicyCountList() { - return policyCountList; - } + /** + * @return the policyCountList + */ + public Map getPolicyCountList() { + return policyCountList; + } - /** - * @param policyCountList the policyCountList to set - */ - public void setPolicyCountList(Map policyCountList) { - this.policyCountList = policyCountList; - } + /** + * @param policyCountList the policyCountList to set + */ + public void setPolicyCountList(Map policyCountList) { + this.policyCountList = policyCountList; + } - /** - * @return the totalCount - */ - public long getTotalCount() { - return totalCount; - } + /** + * @return the totalCount + */ + public long getTotalCount() { + return totalCount; + } - /** - * @param totalCount the totalCount to set - */ - public void setTotalCount(long totalCount) { - this.totalCount = totalCount; - } + /** + * @param totalCount the totalCount to set + */ + public void setTotalCount(long totalCount) { + this.totalCount = totalCount; + } - @Override - public String toString() { - return "VXMetricPolicyWithServiceNameCount={totalCount=" - + totalCount +", VXMetricPolicyWithServiceNameCount=[" - + policyCountList.toString() - + "]}"; - } + @Override + public String toString() { + return "VXMetricPolicyWithServiceNameCount={totalCount=" + totalCount + ", VXMetricPolicyWithServiceNameCount=[" + policyCountList.toString() + "]}"; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/view/VXMetricServiceCount.java b/security-admin/src/main/java/org/apache/ranger/view/VXMetricServiceCount.java index 04a23ae9ab..ec624cafba 100644 --- a/security-admin/src/main/java/org/apache/ranger/view/VXMetricServiceCount.java +++ b/security-admin/src/main/java/org/apache/ranger/view/VXMetricServiceCount.java @@ -16,57 +16,57 @@ */ package org.apache.ranger.view; -import java.util.HashMap; -import java.util.Map; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; import com.fasterxml.jackson.annotation.JsonInclude; -@JsonAutoDetect(getterVisibility=Visibility.NONE, setterVisibility=Visibility.NONE, fieldVisibility=Visibility.ANY) +import java.util.HashMap; +import java.util.Map; + +@JsonAutoDetect(getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE, fieldVisibility = Visibility.ANY) @JsonInclude(JsonInclude.Include.NON_NULL) public class VXMetricServiceCount implements java.io.Serializable { - private static final long serialVersionUID = 1L; - - protected Map serviceBasedCountList = new HashMap(); - protected Long totalCount; - - /** - * Default constructor. This will set all the attributes to default value. - */ - public VXMetricServiceCount() { - } + private static final long serialVersionUID = 1L; + + protected Map serviceBasedCountList = new HashMap<>(); + protected Long totalCount; + + /** + * Default constructor. This will set all the attributes to default value. + */ + public VXMetricServiceCount() { + } - /** - * @return the serviceBasedCountList - */ - public Map getServiceBasedCountList() { - return serviceBasedCountList; - } + /** + * @return the serviceBasedCountList + */ + public Map getServiceBasedCountList() { + return serviceBasedCountList; + } - /** - * @param serviceBasedCountList the serviceBasedCountList to set - */ - public void setServiceBasedCountList(Map serviceBasedCountList) { - this.serviceBasedCountList = serviceBasedCountList; - } + /** + * @param serviceBasedCountList the serviceBasedCountList to set + */ + public void setServiceBasedCountList(Map serviceBasedCountList) { + this.serviceBasedCountList = serviceBasedCountList; + } - /** - * @return the totalCount - */ - public Long getTotalCount() { - return totalCount; - } + /** + * @return the totalCount + */ + public Long getTotalCount() { + return totalCount; + } - /** - * @param totalCount the totalCount to set - */ - public void setTotalCount(Long totalCount) { - this.totalCount = totalCount; - } + /** + * @param totalCount the totalCount to set + */ + public void setTotalCount(Long totalCount) { + this.totalCount = totalCount; + } - @Override - public String toString() { - return "VXMetricServiceCount={total_count=" + totalCount +", services=" - + serviceBasedCountList +"}"; - } + @Override + public String toString() { + return "VXMetricServiceCount={total_count=" + totalCount + ", services=" + serviceBasedCountList + "}"; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/view/VXMetricServiceNameCount.java b/security-admin/src/main/java/org/apache/ranger/view/VXMetricServiceNameCount.java index 07f06170d3..b1b4d0cbca 100644 --- a/security-admin/src/main/java/org/apache/ranger/view/VXMetricServiceNameCount.java +++ b/security-admin/src/main/java/org/apache/ranger/view/VXMetricServiceNameCount.java @@ -16,58 +16,58 @@ */ package org.apache.ranger.view; -import java.util.HashMap; -import java.util.Map; - import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; import com.fasterxml.jackson.annotation.JsonInclude; -@JsonAutoDetect(getterVisibility=Visibility.NONE, setterVisibility=Visibility.NONE, fieldVisibility=Visibility.ANY) +import java.util.HashMap; +import java.util.Map; + +@JsonAutoDetect(getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE, fieldVisibility = Visibility.ANY) @JsonInclude(JsonInclude.Include.NON_NULL) public class VXMetricServiceNameCount implements java.io.Serializable { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; - protected Map> serviceBasedCountList = new HashMap>(); - protected Long totalCount; + protected Map> serviceBasedCountList = new HashMap<>(); + protected Long totalCount; - /** - * Default constructor. This will set all the attributes to default value. - */ - public VXMetricServiceNameCount() { - } + /** + * Default constructor. This will set all the attributes to default value. + */ + public VXMetricServiceNameCount() { + } - /** - * @return the serviceBasedCountList - */ - public Map> getServiceBasedCountList() { - return serviceBasedCountList; - } + /** + * @return the serviceBasedCountList + */ + public Map> getServiceBasedCountList() { + return serviceBasedCountList; + } - /** - * @param servicesforPolicyType the serviceBasedCountList to set - */ - public void setServiceBasedCountList(Map> servicesforPolicyType) { - this.serviceBasedCountList = servicesforPolicyType; - } + /** + * @param servicesforPolicyType the serviceBasedCountList to set + */ + public void setServiceBasedCountList(Map> servicesforPolicyType) { + this.serviceBasedCountList = servicesforPolicyType; + } - /** - * @return the totalCount - */ - public Long getTotalCount() { - return totalCount; - } + /** + * @return the totalCount + */ + public Long getTotalCount() { + return totalCount; + } - /** - * @param totalCount the totalCount to set - */ - public void setTotalCount(Long totalCount) { - this.totalCount = totalCount; - } + /** + * @param totalCount the totalCount to set + */ + public void setTotalCount(Long totalCount) { + this.totalCount = totalCount; + } - @Override - public String toString() { - return "VXMetricServiceNameCount={total_count=" + totalCount +", services=" - + serviceBasedCountList +"}"; - } + @Override + public String toString() { + return "VXMetricServiceNameCount={total_count=" + totalCount + ", services=" + + serviceBasedCountList + "}"; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/view/VXMetricUserGroupCount.java b/security-admin/src/main/java/org/apache/ranger/view/VXMetricUserGroupCount.java index eb62833084..6678bb88fd 100644 --- a/security-admin/src/main/java/org/apache/ranger/view/VXMetricUserGroupCount.java +++ b/security-admin/src/main/java/org/apache/ranger/view/VXMetricUserGroupCount.java @@ -20,104 +20,119 @@ import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; import com.fasterxml.jackson.annotation.JsonInclude; -@JsonAutoDetect(getterVisibility=Visibility.NONE, setterVisibility=Visibility.NONE, fieldVisibility=Visibility.ANY) +@JsonAutoDetect(getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE, fieldVisibility = Visibility.ANY) @JsonInclude(JsonInclude.Include.NON_NULL) public class VXMetricUserGroupCount implements java.io.Serializable { - private static final long serialVersionUID = 1L; - - protected Long groupCount; - protected Long userCountOfUserRole; - protected Long userCountOfKeyAdminRole; - protected Long userCountOfSysAdminRole; + private static final long serialVersionUID = 1L; + + protected Long groupCount; + protected Long userCountOfUserRole; + protected Long userCountOfKeyAdminRole; + protected Long userCountOfSysAdminRole; protected Long userCountOfKeyadminAuditorRole; protected Long userCountOfSysAdminAuditorRole; - protected Long userTotalCount; - /** - * Default constructor. This will set all the attributes to default value. - */ - public VXMetricUserGroupCount() { - } + protected Long userTotalCount; + + /** + * Default constructor. This will set all the attributes to default value. + */ + public VXMetricUserGroupCount() { + } + public Long getUserCountOfKeyadminAuditorRole() { - return userCountOfKeyadminAuditorRole; + return userCountOfKeyadminAuditorRole; } + public void setUserCountOfKeyadminAuditorRole(Long userCountOfKeyadminAuditorRole) { - this.userCountOfKeyadminAuditorRole = userCountOfKeyadminAuditorRole; + this.userCountOfKeyadminAuditorRole = userCountOfKeyadminAuditorRole; } + public Long getUserCountOfSysAdminAuditorRole() { - return userCountOfSysAdminAuditorRole; + return userCountOfSysAdminAuditorRole; } + public void setUserCountOfSysAdminAuditorRole(Long userCountOfSysAdminAuditorRole) { - this.userCountOfSysAdminAuditorRole = userCountOfSysAdminAuditorRole; - } - /** - * @return the groupCount - */ - public Long getGroupCount() { - return groupCount; - } - /** - * @param groupCount the groupCount to set - */ - public void setGroupCount(Long groupCount) { - this.groupCount = groupCount; - } - - /** - * @return the userCountOfUserRole - */ - public Long getUserCountOfUserRole() { - return userCountOfUserRole; - } - /** - * @param userCountOfUserRole the userCountOfUserRole to set - */ - public void setUserCountOfUserRole(Long userCountOfUserRole) { - this.userCountOfUserRole = userCountOfUserRole; - } - /** - * @return the userCountOfKeyAdminRole - */ - public Long getUserCountOfKeyAdminRole() { - return userCountOfKeyAdminRole; - } - /** - * @param userCountOfKeyAdminRole the userKeyAdminRoleCount to set - */ - public void setUserCountOfKeyAdminRole(Long userCountOfKeyAdminRole) { - this.userCountOfKeyAdminRole = userCountOfKeyAdminRole; - } - /** - * @return the userCountOfSysAdminRole - */ - public Long getUserCountOfSysAdminRole() { - return userCountOfSysAdminRole; - } - /** - * @param userCountOfSysAdminRole the userCountOfSysAdminRole to set - */ - public void setUserCountOfSysAdminRole(Long userCountOfSysAdminRole) { - this.userCountOfSysAdminRole = userCountOfSysAdminRole; - } + this.userCountOfSysAdminAuditorRole = userCountOfSysAdminAuditorRole; + } + + /** + * @return the groupCount + */ + public Long getGroupCount() { + return groupCount; + } + + /** + * @param groupCount the groupCount to set + */ + public void setGroupCount(Long groupCount) { + this.groupCount = groupCount; + } + + /** + * @return the userCountOfUserRole + */ + public Long getUserCountOfUserRole() { + return userCountOfUserRole; + } + + /** + * @param userCountOfUserRole the userCountOfUserRole to set + */ + public void setUserCountOfUserRole(Long userCountOfUserRole) { + this.userCountOfUserRole = userCountOfUserRole; + } + + /** + * @return the userCountOfKeyAdminRole + */ + public Long getUserCountOfKeyAdminRole() { + return userCountOfKeyAdminRole; + } + + /** + * @param userCountOfKeyAdminRole the userKeyAdminRoleCount to set + */ + public void setUserCountOfKeyAdminRole(Long userCountOfKeyAdminRole) { + this.userCountOfKeyAdminRole = userCountOfKeyAdminRole; + } + + /** + * @return the userCountOfSysAdminRole + */ + public Long getUserCountOfSysAdminRole() { + return userCountOfSysAdminRole; + } + + /** + * @param userCountOfSysAdminRole the userCountOfSysAdminRole to set + */ + public void setUserCountOfSysAdminRole(Long userCountOfSysAdminRole) { + this.userCountOfSysAdminRole = userCountOfSysAdminRole; + } + /** * @return the userTotalCount */ public Long getUserTotalCount() { - return userTotalCount; + return userTotalCount; } + /** * @param userTotalCount the userTotalCount to set - */ + */ public void setUserTotalCount(Long userTotalCount) { - this.userTotalCount = userTotalCount; - } - @Override - public String toString() { - return "VXMetricUserGroupCount [groupCount=" + groupCount - + ", userCountOfUserRole=" + userCountOfUserRole - + ", userCountOfKeyAdminRole=" + userCountOfKeyAdminRole - + ", userCountOfSysAdminRole=" + userCountOfSysAdminRole - + ", userCountOfKeyadminAuditorRole=" + userCountOfKeyadminAuditorRole - + ", userCountOfSysAdminAuditorRole=" + userCountOfSysAdminAuditorRole - + ", userTotalCount=" + userTotalCount+ "]"; - } + this.userTotalCount = userTotalCount; + } + + @Override + public String toString() { + return "VXMetricUserGroupCount [groupCount=" + groupCount + + ", userCountOfUserRole=" + userCountOfUserRole + + ", userCountOfKeyAdminRole=" + userCountOfKeyAdminRole + + ", userCountOfSysAdminRole=" + userCountOfSysAdminRole + + ", userCountOfKeyadminAuditorRole=" + userCountOfKeyadminAuditorRole + + ", userCountOfSysAdminAuditorRole=" + userCountOfSysAdminAuditorRole + + ", userTotalCount=" + userTotalCount + "]"; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/view/VXModuleDef.java b/security-admin/src/main/java/org/apache/ranger/view/VXModuleDef.java index c25e9214be..71dbc2aec7 100644 --- a/security-admin/src/main/java/org/apache/ranger/view/VXModuleDef.java +++ b/security-admin/src/main/java/org/apache/ranger/view/VXModuleDef.java @@ -17,154 +17,168 @@ package org.apache.ranger.view; -import java.util.Date; -import java.util.List; - import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; -@JsonAutoDetect(getterVisibility=Visibility.NONE, setterVisibility=Visibility.NONE, fieldVisibility=Visibility.ANY) +import java.util.Date; +import java.util.List; + +@JsonAutoDetect(getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE, fieldVisibility = Visibility.ANY) @JsonInclude(JsonInclude.Include.NON_NULL) -@JsonIgnoreProperties(ignoreUnknown=true) +@JsonIgnoreProperties(ignoreUnknown = true) public class VXModuleDef extends VXDataObject implements java.io.Serializable { + private static final long serialVersionUID = 1L; + + protected Date createTime; + protected Date updateTime; + protected Long addedById; + protected Long updatedById; + protected String module; + protected String url; + + protected List userPermList; + protected List groupPermList; + + /** + * @return the userPermList + */ + public List getUserPermList() { + return userPermList; + } + + /** + * @param userPermList the userPermList to set + */ + public void setUserPermList(List userPermList) { + this.userPermList = userPermList; + } + + /** + * @return the groupPermList + */ + public List getGroupPermList() { + return groupPermList; + } + + /** + * @param groupPermList the groupPermList to set + */ + public void setGroupPermList(List groupPermList) { + this.groupPermList = groupPermList; + } + + /** + * @return the createTime + */ + public Date getCreateTime() { + return createTime; + } + + /** + * @return the id + */ + public Long getId() { + return id; + } + + /** + * @param createTime the createTime to set + */ + public void setCreateTime(Date createTime) { + this.createTime = createTime; + } + + /** + * @param id the id to set + */ + public void setId(Long id) { + this.id = id; + } + + /** + * @return the updateTime + */ + public Date getUpdateTime() { + return updateTime; + } + + /** + * @param updateTime the updateTime to set + */ + public void setUpdateTime(Date updateTime) { + this.updateTime = updateTime; + } + + /** + * @return the addedById + */ + public Long getAddedById() { + return addedById; + } + + /** + * @param addedById the addedById to set + */ + public void setAddedById(Long addedById) { + this.addedById = addedById; + } + + /** + * @return the updatedById + */ + public Long getUpdatedById() { + return updatedById; + } + + /** + * @param updatedById the updatedById to set + */ + public void setUpdatedById(Long updatedById) { + this.updatedById = updatedById; + } + + /** + * @return the module + */ + public String getModule() { + return module; + } + + /** + * @param module the module to set + */ + public void setModule(String module) { + this.module = module; + } + + /** + * @return the url + */ + public String getUrl() { + return url; + } + + /** + * @param url the url to set + */ + public void setUrl(String url) { + this.url = url; + } - private static final long serialVersionUID = 1L; - - - protected Date createTime; - protected Date updateTime; - protected Long addedById; - protected Long updatedById; - protected String module; - protected String url; - - protected List userPermList; - protected List groupPermList; - - /** - * @return the userPermList - */ - public List getUserPermList() { - return userPermList; - } - /** - * @param userPermList the userPermList to set - */ - public void setUserPermList(List userPermList) { - this.userPermList = userPermList; - } - /** - * @return the groupPermList - */ - public List getGroupPermList() { - return groupPermList; - } - /** - * @param groupPermList the groupPermList to set - */ - public void setGroupPermList(List groupPermList) { - this.groupPermList = groupPermList; - } - /** - * @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 addedById - */ - public Long getAddedById() { - return addedById; - } - /** - * @param addedById the addedById to set - */ - public void setAddedById(Long addedById) { - this.addedById = addedById; - } - /** - * @return the updatedById - */ - public Long getUpdatedById() { - return updatedById; - } - /** - * @param updatedById the updatedById to set - */ - public void setUpdatedById(Long updatedById) { - this.updatedById = updatedById; - } - /** - * @return the module - */ - public String getModule() { - return module; - } - /** - * @param module the module to set - */ - public void setModule(String module) { - this.module = module; - } - /** - * @return the url - */ - public String getUrl() { - return url; - } - /** - * @param url the url to set - */ - public void setUrl(String url) { - this.url = url; - } - - @Override - public String toString() { - - String str = "VXModuleDef={"; - str += super.toString(); - str += "id={" + id + "} "; - str += "createTime={" + createTime + "} "; - str += "updateTime={" + updateTime + "} "; - str += "addedById={" + addedById + "} "; - str += "updatedById={" + updatedById + "} "; - str += "module={" + module + "} "; - str += "url={" + url + "} "; - str += "}"; - return str; - } + @Override + public String toString() { + String str = "VXModuleDef={"; + str += super.toString(); + str += "id={" + id + "} "; + str += "createTime={" + createTime + "} "; + str += "updateTime={" + updateTime + "} "; + str += "addedById={" + addedById + "} "; + str += "updatedById={" + updatedById + "} "; + str += "module={" + module + "} "; + str += "url={" + url + "} "; + str += "}"; + return str; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/view/VXModuleDefList.java b/security-admin/src/main/java/org/apache/ranger/view/VXModuleDefList.java index 3ca1742ec5..67ec1c19d8 100644 --- a/security-admin/src/main/java/org/apache/ranger/view/VXModuleDefList.java +++ b/security-admin/src/main/java/org/apache/ranger/view/VXModuleDefList.java @@ -17,59 +17,57 @@ package org.apache.ranger.view; -import java.util.ArrayList; -import java.util.List; - -import org.apache.ranger.common.view.VList; -import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import org.apache.ranger.common.view.VList; + +import java.util.ArrayList; +import java.util.List; @JsonAutoDetect(getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE, fieldVisibility = Visibility.ANY) @JsonInclude(JsonInclude.Include.NON_NULL) public class VXModuleDefList extends VList { + private static final long serialVersionUID = 1L; - private static final long serialVersionUID = 1L; - - List vXModuleDef = new ArrayList(); - - public VXModuleDefList() { - super(); - } + List vXModuleDef = new ArrayList<>(); - public VXModuleDefList(List objList) { - super(objList); - this.vXModuleDef = objList; - } + public VXModuleDefList() { + super(); + } - /** - * @return the vXModuleDef - */ - @JsonProperty("vXModuleDef") - public List getvXModuleDef() { - return vXModuleDef; - } + public VXModuleDefList(List objList) { + super(objList); + this.vXModuleDef = objList; + } - /** - * @param vXModuleDef the vXModuleDef to set - */ - @JsonProperty("vXModuleDef") - public void setvXModuleDef(List vXModuleDef) { - this.vXModuleDef = vXModuleDef; - } + /** + * @return the vXModuleDef + */ + @JsonProperty("vXModuleDef") + public List getvXModuleDef() { + return vXModuleDef; + } - @Override - public int getListSize() { - if (vXModuleDef != null) { - return vXModuleDef.size(); - } - return 0; - } + /** + * @param vXModuleDef the vXModuleDef to set + */ + @JsonProperty("vXModuleDef") + public void setvXModuleDef(List vXModuleDef) { + this.vXModuleDef = vXModuleDef; + } - @Override - public List getList() { - return vXModuleDef; - } + @Override + public int getListSize() { + if (vXModuleDef != null) { + return vXModuleDef.size(); + } + return 0; + } + @Override + public List getList() { + return vXModuleDef; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/view/VXModulePermission.java b/security-admin/src/main/java/org/apache/ranger/view/VXModulePermission.java index f011e23f1f..599ad45f3a 100644 --- a/security-admin/src/main/java/org/apache/ranger/view/VXModulePermission.java +++ b/security-admin/src/main/java/org/apache/ranger/view/VXModulePermission.java @@ -17,53 +17,57 @@ package org.apache.ranger.view; -import java.io.Serializable; -import java.util.ArrayList; -import java.util.List; - import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; -@JsonAutoDetect(getterVisibility=Visibility.NONE, setterVisibility=Visibility.NONE, fieldVisibility=Visibility.ANY) +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; + +@JsonAutoDetect(getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE, fieldVisibility = Visibility.ANY) @JsonInclude(JsonInclude.Include.NON_NULL) -@JsonIgnoreProperties(ignoreUnknown=true) +@JsonIgnoreProperties(ignoreUnknown = true) public class VXModulePermission extends VXDataObject implements Serializable { + private static final long serialVersionUID = 1L; + protected String module; + protected List userNameList = new ArrayList<>(); + protected List groupNameList = new ArrayList<>(); + + public String getModule() { + return module; + } + + public void setModule(String module) { + this.module = module; + } + + public List getUserNameList() { + return userNameList; + } + + public void setUserNameList(List userNameList) { + this.userNameList = userNameList; + } - private static final long serialVersionUID = 1L; - protected String module; - protected List userNameList = new ArrayList(); - protected List groupNameList = new ArrayList(); + public List getGroupNameList() { + return groupNameList; + } - public String getModule() { - return module; - } - public void setModule(String module) { - this.module = module; - } - public List getUserNameList() { - return userNameList; - } - public void setUserNameList(List userNameList) { - this.userNameList = userNameList; - } - public List getGroupNameList() { - return groupNameList; - } - public void setGroupNameList(List groupNameList) { - this.groupNameList = groupNameList; - } + public void setGroupNameList(List groupNameList) { + this.groupNameList = groupNameList; + } - @Override - public String toString() { - String str = "VXModulePermission={"; - str += super.toString(); - str += "id={" + id + "} "; - str += "module={" + module + " } "; - str += "userNameList={" + userNameList + " } "; - str += "groupNameList={" + groupNameList + " } "; - str += "}"; - return str; - } + @Override + public String toString() { + String str = "VXModulePermission={"; + str += super.toString(); + str += "id={" + id + "} "; + str += "module={" + module + " } "; + str += "userNameList={" + userNameList + " } "; + str += "groupNameList={" + groupNameList + " } "; + str += "}"; + return str; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/view/VXModulePermissionList.java b/security-admin/src/main/java/org/apache/ranger/view/VXModulePermissionList.java index 2b43c43312..36290ff89d 100644 --- a/security-admin/src/main/java/org/apache/ranger/view/VXModulePermissionList.java +++ b/security-admin/src/main/java/org/apache/ranger/view/VXModulePermissionList.java @@ -17,52 +17,51 @@ package org.apache.ranger.view; -import java.util.ArrayList; -import java.util.List; - -import org.apache.ranger.common.view.VList; -import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import org.apache.ranger.common.view.VList; + +import java.util.ArrayList; +import java.util.List; @JsonAutoDetect(getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE, fieldVisibility = Visibility.ANY) @JsonInclude(JsonInclude.Include.NON_NULL) public class VXModulePermissionList extends VList { + private static final long serialVersionUID = 1L; - private static final long serialVersionUID = 1L; - - List vXModulePermissionList = new ArrayList(); + List vXModulePermissionList = new ArrayList<>(); - public VXModulePermissionList() { - super(); - } + public VXModulePermissionList() { + super(); + } - public VXModulePermissionList(List objList) { - super(objList); - this.vXModulePermissionList = objList; - } + public VXModulePermissionList(List objList) { + super(objList); + this.vXModulePermissionList = objList; + } - @JsonProperty("vXModulePermissionList") - public List getvXModulePermissionList() { - return vXModulePermissionList; - } + @JsonProperty("vXModulePermissionList") + public List getvXModulePermissionList() { + return vXModulePermissionList; + } - @JsonProperty("vXModulePermissionList") - public void setvXModulePermissionList(List vXModulePermissionList) { - this.vXModulePermissionList = vXModulePermissionList; - } + @JsonProperty("vXModulePermissionList") + public void setvXModulePermissionList(List vXModulePermissionList) { + this.vXModulePermissionList = vXModulePermissionList; + } - @Override - public int getListSize() { - if(vXModulePermissionList != null) { - return vXModulePermissionList.size(); - } - return 0; - } + @Override + public int getListSize() { + if (vXModulePermissionList != null) { + return vXModulePermissionList.size(); + } + return 0; + } - @Override - public List getList() { - return vXModulePermissionList; - } + @Override + public List getList() { + return vXModulePermissionList; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/view/VXPasswordChange.java b/security-admin/src/main/java/org/apache/ranger/view/VXPasswordChange.java index d3d3b86fb7..38e621246a 100644 --- a/security-admin/src/main/java/org/apache/ranger/view/VXPasswordChange.java +++ b/security-admin/src/main/java/org/apache/ranger/view/VXPasswordChange.java @@ -17,179 +17,177 @@ * under the License. */ - package org.apache.ranger.view; +package org.apache.ranger.view; /** * Change password structure - * */ -import org.apache.ranger.common.AppConstants; -import org.apache.ranger.common.view.ViewBaseBean; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; +import org.apache.ranger.common.AppConstants; +import org.apache.ranger.common.view.ViewBaseBean; -@JsonAutoDetect(getterVisibility=Visibility.NONE, setterVisibility=Visibility.NONE, fieldVisibility=Visibility.ANY) +@JsonAutoDetect(getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE, fieldVisibility = Visibility.ANY) @JsonInclude(JsonInclude.Include.NON_NULL) -@JsonIgnoreProperties(ignoreUnknown=true) +@JsonIgnoreProperties(ignoreUnknown = true) 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 id. - * You cannot set null to the attribute. - * @param id Value to set member attribute id - */ - public void setId( Long id ) { - this.id = id; - } - - /** - * Returns the value for the member attribute id - * @return Long - value of member attribute id. - */ - public Long getId( ) { - return this.id; - } - - /** - * This method sets the value to the member attribute loginId. - * You cannot set null to the attribute. - * @param loginId Value to set member attribute loginId - */ - public void setLoginId( String loginId ) { - this.loginId = loginId; - } - - /** - * Returns the value for the member attribute loginId - * @return String - value of member attribute loginId. - */ - public String getLoginId( ) { - return this.loginId; - } - - /** - * This method sets the value to the member attribute emailAddress. - * You cannot set null to the attribute. - * @param emailAddress Value to set member attribute emailAddress - */ - public void setEmailAddress( String emailAddress ) { - this.emailAddress = emailAddress; - } - - /** - * Returns the value for the member attribute emailAddress - * @return String - value of member attribute emailAddress. - */ - public String getEmailAddress( ) { - return this.emailAddress; - } - - /** - * This method sets the value to the member attribute resetCode. - * You cannot set null to the attribute. - * @param resetCode Value to set member attribute resetCode - */ - public void setResetCode( String resetCode ) { - this.resetCode = resetCode; - } - - /** - * Returns the value for the member attribute resetCode - * @return String - value of member attribute resetCode. - */ - public String getResetCode( ) { - return this.resetCode; - } - - /** - * This method sets the value to the member attribute oldPassword. - * You cannot set null to the attribute. - * @param oldPassword Value to set member attribute oldPassword - */ - public void setOldPassword( String oldPassword ) { - this.oldPassword = oldPassword; - } - - /** - * Returns the value for the member attribute oldPassword - * @return String - value of member attribute oldPassword. - */ - public String getOldPassword( ) { - return this.oldPassword; - } - - /** - * This method sets the value to the member attribute updPassword. - * You cannot set null to the attribute. - * @param updPassword Value to set member attribute updPassword - */ - public void setUpdPassword( String updPassword ) { - this.updPassword = updPassword; - } - - /** - * Returns the value for the member attribute updPassword - * @return String - value of member attribute updPassword. - */ - 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 += "isOldPasswordNull={" + (oldPassword == null) + "} "; - str += "isUpdPasswordNull={" + (updPassword == null) + "}"; - str += "}"; - return str; - } + 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() { + } + + /** + * Returns the value for the member attribute id + * @return Long - value of member attribute id. + */ + public Long getId() { + return this.id; + } + + /** + * This method sets the value to the member attribute id. + * You cannot set null to the attribute. + * @param id Value to set member attribute id + */ + public void setId(Long id) { + this.id = id; + } + + /** + * Returns the value for the member attribute loginId + * @return String - value of member attribute loginId. + */ + public String getLoginId() { + return this.loginId; + } + + /** + * This method sets the value to the member attribute loginId. + * You cannot set null to the attribute. + * @param loginId Value to set member attribute loginId + */ + public void setLoginId(String loginId) { + this.loginId = loginId; + } + + /** + * Returns the value for the member attribute emailAddress + * @return String - value of member attribute emailAddress. + */ + public String getEmailAddress() { + return this.emailAddress; + } + + /** + * This method sets the value to the member attribute emailAddress. + * You cannot set null to the attribute. + * @param emailAddress Value to set member attribute emailAddress + */ + public void setEmailAddress(String emailAddress) { + this.emailAddress = emailAddress; + } + + /** + * Returns the value for the member attribute resetCode + * @return String - value of member attribute resetCode. + */ + public String getResetCode() { + return this.resetCode; + } + + /** + * This method sets the value to the member attribute resetCode. + * You cannot set null to the attribute. + * @param resetCode Value to set member attribute resetCode + */ + public void setResetCode(String resetCode) { + this.resetCode = resetCode; + } + + /** + * Returns the value for the member attribute oldPassword + * @return String - value of member attribute oldPassword. + */ + public String getOldPassword() { + return this.oldPassword; + } + + /** + * This method sets the value to the member attribute oldPassword. + * You cannot set null to the attribute. + * @param oldPassword Value to set member attribute oldPassword + */ + public void setOldPassword(String oldPassword) { + this.oldPassword = oldPassword; + } + + /** + * Returns the value for the member attribute updPassword + * @return String - value of member attribute updPassword. + */ + public String getUpdPassword() { + return this.updPassword; + } + + /** + * This method sets the value to the member attribute updPassword. + * You cannot set null to the attribute. + * @param updPassword Value to set member attribute updPassword + */ + public void setUpdPassword(String updPassword) { + this.updPassword = 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 += "isOldPasswordNull={" + (oldPassword == null) + "} "; + str += "isUpdPasswordNull={" + (updPassword == null) + "}"; + str += "}"; + return str; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/view/VXPermMap.java b/security-admin/src/main/java/org/apache/ranger/view/VXPermMap.java index 323f3b4a6a..9b1cb4fbb9 100644 --- a/security-admin/src/main/java/org/apache/ranger/view/VXPermMap.java +++ b/security-admin/src/main/java/org/apache/ranger/view/VXPermMap.java @@ -17,307 +17,305 @@ * under the License. */ - package org.apache.ranger.view; +package org.apache.ranger.view; /** * Permission map - * */ -import org.apache.ranger.common.AppConstants; -import org.apache.ranger.common.RangerConstants; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; +import org.apache.ranger.common.AppConstants; +import org.apache.ranger.common.RangerConstants; -@JsonAutoDetect(getterVisibility=Visibility.NONE, setterVisibility=Visibility.NONE, fieldVisibility=Visibility.ANY) +@JsonAutoDetect(getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE, fieldVisibility = Visibility.ANY) @JsonInclude(JsonInclude.Include.NON_NULL) -@JsonIgnoreProperties(ignoreUnknown=true) +@JsonIgnoreProperties(ignoreUnknown = true) 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 = RangerConstants.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 = RangerConstants.BOOL_NONE; - } - - /** - * This method sets the value to the member attribute permGroup. - * You cannot set null to the attribute. - * @param permGroup Value to set member attribute permGroup - */ - public void setPermGroup( String permGroup ) { - this.permGroup = permGroup; - } - - /** - * Returns the value for the member attribute permGroup - * @return String - value of member attribute permGroup. - */ - public String getPermGroup( ) { - return this.permGroup; - } - - /** - * This method sets the value to the member attribute resourceId. - * You cannot set null to the attribute. - * @param resourceId Value to set member attribute resourceId - */ - public void setResourceId( Long resourceId ) { - this.resourceId = resourceId; - } - - /** - * Returns the value for the member attribute resourceId - * @return Long - value of member attribute resourceId. - */ - public Long getResourceId( ) { - return this.resourceId; - } - - /** - * This method sets the value to the member attribute groupId. - * You cannot set null to the attribute. - * @param groupId Value to set member attribute groupId - */ - public void setGroupId( Long groupId ) { - this.groupId = groupId; - } - - /** - * Returns the value for the member attribute groupId - * @return Long - value of member attribute groupId. - */ - public Long getGroupId( ) { - return this.groupId; - } - - /** - * This method sets the value to the member attribute userId. - * You cannot set null to the attribute. - * @param userId Value to set member attribute userId - */ - public void setUserId( Long userId ) { - this.userId = userId; - } - - /** - * Returns the value for the member attribute userId - * @return Long - value of member attribute userId. - */ - public Long getUserId( ) { - return this.userId; - } - - /** - * This method sets the value to the member attribute permFor. - * You cannot set null to the attribute. - * @param permFor Value to set member attribute permFor - */ - public void setPermFor( int permFor ) { - this.permFor = permFor; - } - - /** - * Returns the value for the member attribute permFor - * @return int - value of member attribute permFor. - */ - public int getPermFor( ) { - return this.permFor; - } - - /** - * This method sets the value to the member attribute permType. - * You cannot set null to the attribute. - * @param permType Value to set member attribute permType - */ - public void setPermType( int permType ) { - this.permType = permType; - } - - /** - * Returns the value for the member attribute permType - * @return int - value of member attribute permType. - */ - public int getPermType( ) { - return this.permType; - } - - /** - * This method sets the value to the member attribute grantOrRevoke. - * You cannot set null to the attribute. - * @param grantOrRevoke Value to set member attribute grantOrRevoke - */ - public void setGrantOrRevoke( boolean grantOrRevoke ) { - this.grantOrRevoke = grantOrRevoke; - } - - /** - * Returns the value for the member attribute grantOrRevoke - * @return boolean - value of member attribute grantOrRevoke. - */ - public boolean isGrantOrRevoke( ) { - return this.grantOrRevoke; - } - - /** - * This method sets the value to the member attribute groupName. - * You cannot set null to the attribute. - * @param groupName Value to set member attribute groupName - */ - public void setGroupName( String groupName ) { - this.groupName = groupName; - } - - /** - * Returns the value for the member attribute groupName - * @return String - value of member attribute groupName. - */ - public String getGroupName( ) { - return this.groupName; - } - - /** - * This method sets the value to the member attribute userName. - * You cannot set null to the attribute. - * @param userName Value to set member attribute userName - */ - public void setUserName( String userName ) { - this.userName = userName; - } - - /** - * Returns the value for the member attribute userName - * @return String - value of member attribute userName. - */ - public String getUserName( ) { - return this.userName; - } - - /** - * This method sets the value to the member attribute isRecursive. - * You cannot set null to the attribute. - * @param isRecursive Value to set member attribute isRecursive - */ - public void setIsRecursive( int isRecursive ) { - this.isRecursive = isRecursive; - } - - /** - * Returns the value for the member attribute isRecursive - * @return int - value of member attribute isRecursive. - */ - public int getIsRecursive( ) { - return this.isRecursive; - } - - /** - * This method sets the value to the member attribute isWildCard. - * You cannot set null to the attribute. - * @param isWildCard Value to set member attribute isWildCard - */ - public void setIsWildCard( boolean isWildCard ) { - this.isWildCard = isWildCard; - } - - /** - * Returns the value for the member attribute isWildCard - * @return boolean - value of member attribute isWildCard. - */ - 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; - } + 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 = RangerConstants.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 = RangerConstants.BOOL_NONE; + } + + /** + * Returns the value for the member attribute permGroup + * @return String - value of member attribute permGroup. + */ + public String getPermGroup() { + return this.permGroup; + } + + /** + * This method sets the value to the member attribute permGroup. + * You cannot set null to the attribute. + * @param permGroup Value to set member attribute permGroup + */ + public void setPermGroup(String permGroup) { + this.permGroup = permGroup; + } + + /** + * Returns the value for the member attribute resourceId + * @return Long - value of member attribute resourceId. + */ + public Long getResourceId() { + return this.resourceId; + } + + /** + * This method sets the value to the member attribute resourceId. + * You cannot set null to the attribute. + * @param resourceId Value to set member attribute resourceId + */ + public void setResourceId(Long resourceId) { + this.resourceId = resourceId; + } + + /** + * Returns the value for the member attribute groupId + * @return Long - value of member attribute groupId. + */ + public Long getGroupId() { + return this.groupId; + } + + /** + * This method sets the value to the member attribute groupId. + * You cannot set null to the attribute. + * @param groupId Value to set member attribute groupId + */ + public void setGroupId(Long groupId) { + this.groupId = groupId; + } + + /** + * Returns the value for the member attribute userId + * @return Long - value of member attribute userId. + */ + public Long getUserId() { + return this.userId; + } + + /** + * This method sets the value to the member attribute userId. + * You cannot set null to the attribute. + * @param userId Value to set member attribute userId + */ + public void setUserId(Long userId) { + this.userId = userId; + } + + /** + * Returns the value for the member attribute permFor + * @return int - value of member attribute permFor. + */ + public int getPermFor() { + return this.permFor; + } + + /** + * This method sets the value to the member attribute permFor. + * You cannot set null to the attribute. + * @param permFor Value to set member attribute permFor + */ + public void setPermFor(int permFor) { + this.permFor = permFor; + } + + /** + * Returns the value for the member attribute permType + * @return int - value of member attribute permType. + */ + public int getPermType() { + return this.permType; + } + + /** + * This method sets the value to the member attribute permType. + * You cannot set null to the attribute. + * @param permType Value to set member attribute permType + */ + public void setPermType(int permType) { + this.permType = permType; + } + + /** + * Returns the value for the member attribute grantOrRevoke + * @return boolean - value of member attribute grantOrRevoke. + */ + public boolean isGrantOrRevoke() { + return this.grantOrRevoke; + } + + /** + * This method sets the value to the member attribute grantOrRevoke. + * You cannot set null to the attribute. + * @param grantOrRevoke Value to set member attribute grantOrRevoke + */ + public void setGrantOrRevoke(boolean grantOrRevoke) { + this.grantOrRevoke = grantOrRevoke; + } + + /** + * Returns the value for the member attribute groupName + * @return String - value of member attribute groupName. + */ + public String getGroupName() { + return this.groupName; + } + + /** + * This method sets the value to the member attribute groupName. + * You cannot set null to the attribute. + * @param groupName Value to set member attribute groupName + */ + public void setGroupName(String groupName) { + this.groupName = groupName; + } + + /** + * Returns the value for the member attribute userName + * @return String - value of member attribute userName. + */ + public String getUserName() { + return this.userName; + } + + /** + * This method sets the value to the member attribute userName. + * You cannot set null to the attribute. + * @param userName Value to set member attribute userName + */ + public void setUserName(String userName) { + this.userName = userName; + } + + /** + * Returns the value for the member attribute isRecursive + * @return int - value of member attribute isRecursive. + */ + public int getIsRecursive() { + return this.isRecursive; + } + + /** + * This method sets the value to the member attribute isRecursive. + * You cannot set null to the attribute. + * @param isRecursive Value to set member attribute isRecursive + */ + public void setIsRecursive(int isRecursive) { + this.isRecursive = isRecursive; + } + + /** + * Returns the value for the member attribute isWildCard + * @return boolean - value of member attribute isWildCard. + */ + public boolean isIsWildCard() { + return this.isWildCard; + } + + /** + * This method sets the value to the member attribute isWildCard. + * You cannot set null to the attribute. + * @param isWildCard Value to set member attribute isWildCard + */ + public void setIsWildCard(boolean isWildCard) { + this.isWildCard = 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; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/view/VXPermMapList.java b/security-admin/src/main/java/org/apache/ranger/view/VXPermMapList.java index 42c3a9d97d..e43f2e345e 100644 --- a/security-admin/src/main/java/org/apache/ranger/view/VXPermMapList.java +++ b/security-admin/src/main/java/org/apache/ranger/view/VXPermMapList.java @@ -17,35 +17,35 @@ * under the License. */ - package org.apache.ranger.view; +package org.apache.ranger.view; /** * List wrapper class for VXPermMap - * */ -import java.util.ArrayList; -import java.util.List; - -import org.apache.ranger.common.view.VList; -import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import org.apache.ranger.common.view.VList; + +import java.util.ArrayList; +import java.util.List; -@JsonAutoDetect(getterVisibility=Visibility.NONE, setterVisibility=Visibility.NONE, fieldVisibility=Visibility.ANY) +@JsonAutoDetect(getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE, fieldVisibility = Visibility.ANY) @JsonInclude(JsonInclude.Include.NON_NULL) public class VXPermMapList extends VList { - private static final long serialVersionUID = 1L; - List vXPermMaps = new ArrayList(); + private static final long serialVersionUID = 1L; + + List vXPermMaps = new ArrayList<>(); public VXPermMapList() { - super(); + super(); } public VXPermMapList(List objList) { - super(objList); - this.vXPermMaps = objList; + super(objList); + this.vXPermMaps = objList; } /** @@ -53,7 +53,7 @@ public VXPermMapList(List objList) { */ @JsonProperty("vXPermMaps") public List getVXPermMaps() { - return vXPermMaps; + return vXPermMaps; } /** @@ -62,20 +62,19 @@ public List getVXPermMaps() { */ @JsonProperty("vXPermMaps") public void setVXPermMaps(List vXPermMaps) { - this.vXPermMaps = vXPermMaps; + this.vXPermMaps = vXPermMaps; } @Override public int getListSize() { - if (vXPermMaps != null) { - return vXPermMaps.size(); - } - return 0; + if (vXPermMaps != null) { + return vXPermMaps.size(); + } + return 0; } @Override public List getList() { - return vXPermMaps; + return vXPermMaps; } - } diff --git a/security-admin/src/main/java/org/apache/ranger/view/VXPermObj.java b/security-admin/src/main/java/org/apache/ranger/view/VXPermObj.java index 222b4d7f75..1c371bc32d 100644 --- a/security-admin/src/main/java/org/apache/ranger/view/VXPermObj.java +++ b/security-admin/src/main/java/org/apache/ranger/view/VXPermObj.java @@ -17,123 +17,117 @@ * under the License. */ - package org.apache.ranger.view; - +package org.apache.ranger.view; /** * Permission map */ -import java.util.List; - import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; +import java.util.List; + @JsonAutoDetect(getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE, fieldVisibility = Visibility.ANY) @JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) public class VXPermObj implements java.io.Serializable { - private static final long serialVersionUID = 1L; - - /** - * List of userName - */ - protected List userList; - /** - * List of groupName - */ - protected List groupList; - /** - * List of permission - */ - protected List 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 getUserList() { - return userList; - } - - /** - * @param userList - * the userList to set - */ - public void setUserList(List userList) { - this.userList = userList; - } - - /** - * @return the groupList - */ - public List getGroupList() { - return groupList; - } - - /** - * @param groupList - * the groupList to set - */ - public void setGroupList(List groupList) { - this.groupList = groupList; - } - - /** - * @return the permList - */ - public List getPermList() { - return permList; - } - - /** - * @param permList - * the permList to set - */ - public void setPermList(List 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; - } + private static final long serialVersionUID = 1L; + + /** + * List of userName + */ + protected List userList; + /** + * List of groupName + */ + protected List groupList; + /** + * List of permission + */ + protected List 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 getUserList() { + return userList; + } + + /** + * @param userList the userList to set + */ + public void setUserList(List userList) { + this.userList = userList; + } + + /** + * @return the groupList + */ + public List getGroupList() { + return groupList; + } + + /** + * @param groupList the groupList to set + */ + public void setGroupList(List groupList) { + this.groupList = groupList; + } + + /** + * @return the permList + */ + public List getPermList() { + return permList; + } + + /** + * @param permList the permList to set + */ + public void setPermList(List 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; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/view/VXPermObjList.java b/security-admin/src/main/java/org/apache/ranger/view/VXPermObjList.java index f8ee58fc9c..95976e1a0d 100644 --- a/security-admin/src/main/java/org/apache/ranger/view/VXPermObjList.java +++ b/security-admin/src/main/java/org/apache/ranger/view/VXPermObjList.java @@ -17,65 +17,63 @@ * under the License. */ - package org.apache.ranger.view; - +package org.apache.ranger.view; /** * List wrapper class for VXPermObj */ -import java.util.ArrayList; -import java.util.List; - -import org.apache.ranger.common.view.VList; -import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import org.apache.ranger.common.view.VList; + +import java.util.ArrayList; +import java.util.List; @JsonAutoDetect(getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE, fieldVisibility = Visibility.ANY) @JsonInclude(JsonInclude.Include.NON_NULL) public class VXPermObjList extends VList { - private static final long serialVersionUID = 1L; - List vXPermObjs = new ArrayList(); + private static final long serialVersionUID = 1L; - public VXPermObjList() { - super(); - } + List vXPermObjs = new ArrayList<>(); - public VXPermObjList(List objList) { - super(objList); - this.vXPermObjs = objList; - } + public VXPermObjList() { + super(); + } - /** - * @return the vXPermObjs - */ - @JsonProperty("vXPermObjs") - public List getVXPermObjs() { - return vXPermObjs; - } + public VXPermObjList(List objList) { + super(objList); + this.vXPermObjs = objList; + } - /** - * @param vXPermObjs - * the vXPermObjs to set - */ - @JsonProperty("vXPermObjs") - public void setVXPermObjs(List vXPermObjs) { - this.vXPermObjs = vXPermObjs; - } + /** + * @return the vXPermObjs + */ + @JsonProperty("vXPermObjs") + public List getVXPermObjs() { + return vXPermObjs; + } - @Override - public int getListSize() { - if (vXPermObjs != null) { - return vXPermObjs.size(); - } - return 0; - } + /** + * @param vXPermObjs the vXPermObjs to set + */ + @JsonProperty("vXPermObjs") + public void setVXPermObjs(List vXPermObjs) { + this.vXPermObjs = vXPermObjs; + } - @Override - public List getList() { - return vXPermObjs; - } + @Override + public int getListSize() { + if (vXPermObjs != null) { + return vXPermObjs.size(); + } + return 0; + } + @Override + public List getList() { + return vXPermObjs; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/view/VXPolicy.java b/security-admin/src/main/java/org/apache/ranger/view/VXPolicy.java index 918b1031dc..e21fe0469e 100644 --- a/security-admin/src/main/java/org/apache/ranger/view/VXPolicy.java +++ b/security-admin/src/main/java/org/apache/ranger/view/VXPolicy.java @@ -17,593 +17,571 @@ * under the License. */ - package org.apache.ranger.view; - +package org.apache.ranger.view; /** * Policy */ -import java.util.List; - -import org.apache.ranger.common.AppConstants; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; +import org.apache.ranger.common.AppConstants; + +import java.util.List; @JsonAutoDetect(getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE, fieldVisibility = Visibility.ANY) @JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) 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 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 ColumnType - */ - protected String columnType; - /** - * Topologoies - */ - protected String topologies; - /** - * Services - */ - protected String services; - /** - * Hive Services - */ - protected String hiveservices; - - /** - * 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; - - protected String policyLabel; - - /** - * Default constructor. This will set all the attributes to default value. - */ - public VXPolicy() { - isRecursive = false; - replacePerm=false; - } - - /** - * Returns the value for the member attribute policyName - * - * @return String - value of member attribute policyName. - */ - public String getPolicyName() { - return policyName; - } - - /** - * This method sets the value to the member attribute policyName. You - * cannot set null to the attribute. - * - * @param policyName - * Value to set member attribute policyName - */ - public void setPolicyName(String policyName) { - this.policyName = policyName; - } - - /** - * This method sets the value to the member attribute resourceName. - * You cannot set null to the attribute. - * - * @param name - * Value to set member attribute resourceName - */ - public void setResourceName(String resourceName) { - this.resourceName = resourceName; - } - - /** - * Returns the value for the member attribute resourceName - * - * @return String - value of member attribute resourceName. - */ - public String getResourceName() { - return this.resourceName; - } - - /** - * This method sets the value to the member attribute description. - * You cannot set null to the attribute. - * - * @param description - * Value to set member attribute description - */ - public void setDescription(String description) { - this.description = description; - } - - /** - * Returns the value for the member attribute description - * - * @return String - value of member attribute description. - */ - public String getDescription() { - return this.description; - } - - /** - * This method sets the value to the member attribute assetName. You - * cannot set null to the attribute. - * - * @param assetName - * Value to set member attribute assetName - */ - public void setRepositoryName(String repositoryName) { - this.repositoryName = repositoryName; - } - - /** - * Returns the value for the member attribute repositoryName - * - * @return String - value of member attribute repositoryName. - */ - public String getRepositoryName() { - return this.repositoryName; - } - - /** - * This method sets the value to the member attribute assetType. You - * cannot set null to the attribute. - * - * @param assetType - * Value to set member attribute assetType - */ - public void setRepositoryType(String repositoryType) { - this.repositoryType = repositoryType; - } - - /** - * Returns the value for the member attribute repositoryType - * - * @return String - value of member attribute repositoryType. - */ - public String getRepositoryType() { - return this.repositoryType; - } - - /** - * This method sets the value to the member attribute permMapList. - * You cannot set null to the attribute. - * - * @param permMapList - * Value to set member attribute permMapList - */ - public void setPermMapList(List permMapList) { - this.permMapList = permMapList; - } - - /** - * Returns the value for the member attribute userPermList - * - * @return List - value of member attribute permMapList. - */ - public List getPermMapList() { - return this.permMapList; - } - - /** - * This method sets the value to the member attribute tables. You - * cannot set null to the attribute. - * - * @param tables - * Value to set member attribute tables - */ - public void setTables(String tables) { - this.tables = tables; - } - - /** - * Returns the value for the member attribute tables - * - * @return String - value of member attribute tables. - */ - public String getTables() { - return this.tables; - } - - /** - * This method sets the value to the member attribute columnFamilies. - * You cannot set null to the attribute. - * - * @param columnFamilies - * Value to set member attribute columnFamilies - */ - public void setColumnFamilies(String columnFamilies) { - this.columnFamilies = columnFamilies; - } - - /** - * Returns the value for the member attribute columnFamilies - * - * @return String - value of member attribute columnFamilies. - */ - public String getColumnFamilies() { - return this.columnFamilies; - } - - /** - * This method sets the value to the member attribute columns. You - * cannot set null to the attribute. - * - * @param columns - * Value to set member attribute columns - */ - public void setColumns(String columns) { - this.columns = columns; - } - - /** - * Returns the value for the member attribute columns - * - * @return String - value of member attribute columns. - */ - public String getColumns() { - return this.columns; - } - - /** - * This method sets the value to the member attribute databases. You - * cannot set null to the attribute. - * - * @param databases - * Value to set member attribute databases - */ - public void setDatabases(String databases) { - this.databases = databases; - } - - /** - * Returns the value for the member attribute databases - * - * @return String - value of member attribute databases. - */ - public String getDatabases() { - return this.databases; - } - - /** - * This method sets the value to the member attribute udfs. You - * cannot set null to the attribute. - * - * @param udfs - * Value to set member attribute udfs - */ - public void setUdfs(String udfs) { - this.udfs = udfs; - } - - /** - * Returns the value for the member attribute udfs - * - * @return String - value of member attribute udfs. - */ - public String getUdfs() { - return this.udfs; - } - - /** - * Returns the value for the member attribute tableType - * - * @return String - value of member attribute tableType. - */ - public String getTableType() { - return tableType; - } - - /** - * This method sets the value to the member attribute tableType. You - * cannot set null to the attribute. - * - * @param tableType - * Value to set member attribute tableType - */ - public void setTableType(String tableType) { - this.tableType = tableType; - } - - /** - * Returns the value for the member attribute columnType - * - * @return String - value of member attribute columnType. - */ - public String getColumnType() { - return columnType; - } - - /** - * This method sets the value to the member attribute columnType. You - * cannot set null to the attribute. - * - * @param columnType - * Value to set member attribute columnType - */ - public void setColumnType(String columnType) { - this.columnType = columnType; - } - - /** - * Returns the value for the member attribute topologies - * - * @return String - value of member attribute topologies. - */ - public String getTopologies() { - return topologies; - } - - /** - * This method sets the value to the member attribute topologies. You - * cannot set null to the attribute. - * - * @param topologies - * Value to set member attribute topologies - */ - public void setTopologies(String topologies) { - this.topologies = topologies; - } - - /** - * Returns the value for the member attribute services - * - * @return String - value of member attribute services. - */ - public String getServices() { - return services; - } - - /** - * This method sets the value to the member attribute services. You - * cannot set null to the attribute. - * - * @param services - * Value to set member attribute services - */ - public void setServices(String services) { - this.services = services; - } - - /** - * Returns the value for the member attribute hiveservices - * - * @return String - value of member attribute hiveservices. - */ - public String getHiveServices() { - return hiveservices; - } - - /** - * This method sets the value to the member attribute hiveservices. You - * cannot set null to the attribute. - * - * @param hiveservices - * Value to set member attribute hiveservices - */ - public void setHiveServices(String hiveservices) { - this.hiveservices = hiveservices; - } - - /** - * This method sets the value to the member attribute resourceStatus. - * You cannot set null to the attribute. - * - * @param isEnabled - * Value to set member attribute isEnable - */ - public void setIsEnabled(boolean isEnabled) { - this.isEnabled = isEnabled; - } - - /** - * Returns the value for the member attribute isEnable - * - * @return boolean - value of member attribute isEnable. - */ - public boolean getIsEnabled() { - return this.isEnabled; - } - - /** - * This method sets the value to the member attribute isRecursive. - * You cannot set null to the attribute. - * - * @param isRecursive - * Value to set member attribute isRecursive - */ - public void setIsRecursive(Boolean isRecursive) { - this.isRecursive = isRecursive; - } - - /** - * Returns the value for the member attribute isRecursive - * - * @return boolean - value of member attribute isRecursive. - */ - public Boolean getIsRecursive() { - return this.isRecursive; - } - - /** - * This method sets the value to the member attribute isAuditEnabled. - * You cannot set null to the attribute. - * - * @param isAuditEnabled - * Value to set member attribute isAuditEnabled - */ - public void setIsAuditEnabled(boolean isAuditEnabled) { - this.isAuditEnabled = isAuditEnabled; - } - - /** - * Returns the value for the member attribute isAuditEnabled - * - * @return boolean - value of member attribute isAuditEnabled. - */ - public boolean getIsAuditEnabled() { - return this.isAuditEnabled; - } - - /** - * Returns the value for the member attribute version - * - * @return String - value of member attribute version. - */ - public String getVersion() { - return version; - } - - /** - * This method sets the value to the member attribute version. You - * cannot set null to the attribute. - * - * @param version - * Value to set member attribute version - */ - 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; - } - - public String getPolicyLabel() { - return policyLabel; - } - - public void setPolicyLabel(String policyLabel) { - this.policyLabel = policyLabel; - } - - @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 += "policyLabel={" + policyLabel + "} "; - 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(Boolean.FALSE); - } + 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 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 ColumnType + */ + protected String columnType; + /** + * Topologoies + */ + protected String topologies; + /** + * Services + */ + protected String services; + /** + * Hive Services + */ + protected String hiveservices; + + /** + * 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; + + protected String policyLabel; + + /** + * Default constructor. This will set all the attributes to default value. + */ + public VXPolicy() { + isRecursive = false; + replacePerm = false; + } + + /** + * Returns the value for the member attribute policyName + * + * @return String - value of member attribute policyName. + */ + public String getPolicyName() { + return policyName; + } + + /** + * This method sets the value to the member attribute policyName. You + * cannot set null to the attribute. + * + * @param policyName Value to set member attribute policyName + */ + public void setPolicyName(String policyName) { + this.policyName = policyName; + } + + /** + * Returns the value for the member attribute resourceName + * + * @return String - value of member attribute resourceName. + */ + public String getResourceName() { + return this.resourceName; + } + + /** + * This method sets the value to the member attribute resourceName. + * You cannot set null to the attribute. + * + * @param name Value to set member attribute resourceName + */ + public void setResourceName(String resourceName) { + this.resourceName = resourceName; + } + + /** + * Returns the value for the member attribute description + * + * @return String - value of member attribute description. + */ + public String getDescription() { + return this.description; + } + + /** + * This method sets the value to the member attribute description. + * You cannot set null to the attribute. + * + * @param description Value to set member attribute description + */ + public void setDescription(String description) { + this.description = description; + } + + /** + * Returns the value for the member attribute repositoryName + * + * @return String - value of member attribute repositoryName. + */ + public String getRepositoryName() { + return this.repositoryName; + } + + /** + * This method sets the value to the member attribute assetName. You + * cannot set null to the attribute. + * + * @param assetName Value to set member attribute assetName + */ + public void setRepositoryName(String repositoryName) { + this.repositoryName = repositoryName; + } + + /** + * Returns the value for the member attribute repositoryType + * + * @return String - value of member attribute repositoryType. + */ + public String getRepositoryType() { + return this.repositoryType; + } + + /** + * This method sets the value to the member attribute assetType. You + * cannot set null to the attribute. + * + * @param assetType Value to set member attribute assetType + */ + public void setRepositoryType(String repositoryType) { + this.repositoryType = repositoryType; + } + + /** + * Returns the value for the member attribute userPermList + * + * @return List - value of member attribute permMapList. + */ + public List getPermMapList() { + return this.permMapList; + } + + /** + * This method sets the value to the member attribute permMapList. + * You cannot set null to the attribute. + * + * @param permMapList Value to set member attribute permMapList + */ + public void setPermMapList(List permMapList) { + this.permMapList = permMapList; + } + + /** + * Returns the value for the member attribute tables + * + * @return String - value of member attribute tables. + */ + public String getTables() { + return this.tables; + } + + /** + * This method sets the value to the member attribute tables. You + * cannot set null to the attribute. + * + * @param tables Value to set member attribute tables + */ + public void setTables(String tables) { + this.tables = tables; + } + + /** + * Returns the value for the member attribute columnFamilies + * + * @return String - value of member attribute columnFamilies. + */ + public String getColumnFamilies() { + return this.columnFamilies; + } + + /** + * This method sets the value to the member attribute columnFamilies. + * You cannot set null to the attribute. + * + * @param columnFamilies Value to set member attribute columnFamilies + */ + public void setColumnFamilies(String columnFamilies) { + this.columnFamilies = columnFamilies; + } + + /** + * Returns the value for the member attribute columns + * + * @return String - value of member attribute columns. + */ + public String getColumns() { + return this.columns; + } + + /** + * This method sets the value to the member attribute columns. You + * cannot set null to the attribute. + * + * @param columns Value to set member attribute columns + */ + public void setColumns(String columns) { + this.columns = columns; + } + + /** + * Returns the value for the member attribute databases + * + * @return String - value of member attribute databases. + */ + public String getDatabases() { + return this.databases; + } + + /** + * This method sets the value to the member attribute databases. You + * cannot set null to the attribute. + * + * @param databases Value to set member attribute databases + */ + public void setDatabases(String databases) { + this.databases = databases; + } + + /** + * Returns the value for the member attribute udfs + * + * @return String - value of member attribute udfs. + */ + public String getUdfs() { + return this.udfs; + } + + /** + * This method sets the value to the member attribute udfs. You + * cannot set null to the attribute. + * + * @param udfs Value to set member attribute udfs + */ + public void setUdfs(String udfs) { + this.udfs = udfs; + } + + /** + * Returns the value for the member attribute tableType + * + * @return String - value of member attribute tableType. + */ + public String getTableType() { + return tableType; + } + + /** + * This method sets the value to the member attribute tableType. You + * cannot set null to the attribute. + * + * @param tableType Value to set member attribute tableType + */ + public void setTableType(String tableType) { + this.tableType = tableType; + } + + /** + * Returns the value for the member attribute columnType + * + * @return String - value of member attribute columnType. + */ + public String getColumnType() { + return columnType; + } + + /** + * This method sets the value to the member attribute columnType. You + * cannot set null to the attribute. + * + * @param columnType Value to set member attribute columnType + */ + public void setColumnType(String columnType) { + this.columnType = columnType; + } + + /** + * Returns the value for the member attribute topologies + * + * @return String - value of member attribute topologies. + */ + public String getTopologies() { + return topologies; + } + + /** + * This method sets the value to the member attribute topologies. You + * cannot set null to the attribute. + * + * @param topologies Value to set member attribute topologies + */ + public void setTopologies(String topologies) { + this.topologies = topologies; + } + + /** + * Returns the value for the member attribute services + * + * @return String - value of member attribute services. + */ + public String getServices() { + return services; + } + + /** + * This method sets the value to the member attribute services. You + * cannot set null to the attribute. + * + * @param services Value to set member attribute services + */ + public void setServices(String services) { + this.services = services; + } + + /** + * Returns the value for the member attribute hiveservices + * + * @return String - value of member attribute hiveservices. + */ + public String getHiveServices() { + return hiveservices; + } + + /** + * This method sets the value to the member attribute hiveservices. You + * cannot set null to the attribute. + * + * @param hiveservices Value to set member attribute hiveservices + */ + public void setHiveServices(String hiveservices) { + this.hiveservices = hiveservices; + } + + /** + * Returns the value for the member attribute isEnable + * + * @return boolean - value of member attribute isEnable. + */ + public boolean getIsEnabled() { + return this.isEnabled; + } + + /** + * This method sets the value to the member attribute resourceStatus. + * You cannot set null to the attribute. + * + * @param isEnabled Value to set member attribute isEnable + */ + public void setIsEnabled(boolean isEnabled) { + this.isEnabled = isEnabled; + } + + /** + * Returns the value for the member attribute isRecursive + * + * @return boolean - value of member attribute isRecursive. + */ + public Boolean getIsRecursive() { + return this.isRecursive; + } + + /** + * This method sets the value to the member attribute isRecursive. + * You cannot set null to the attribute. + * + * @param isRecursive Value to set member attribute isRecursive + */ + public void setIsRecursive(Boolean isRecursive) { + this.isRecursive = isRecursive; + } + + /** + * Returns the value for the member attribute isAuditEnabled + * + * @return boolean - value of member attribute isAuditEnabled. + */ + public boolean getIsAuditEnabled() { + return this.isAuditEnabled; + } + + /** + * This method sets the value to the member attribute isAuditEnabled. + * You cannot set null to the attribute. + * + * @param isAuditEnabled Value to set member attribute isAuditEnabled + */ + public void setIsAuditEnabled(boolean isAuditEnabled) { + this.isAuditEnabled = isAuditEnabled; + } + + /** + * Returns the value for the member attribute version + * + * @return String - value of member attribute version. + */ + public String getVersion() { + return version; + } + + /** + * This method sets the value to the member attribute version. You + * cannot set null to the attribute. + * + * @param version Value to set member attribute version + */ + 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; + } + + public String getPolicyLabel() { + return policyLabel; + } + + public void setPolicyLabel(String policyLabel) { + this.policyLabel = policyLabel; + } + + @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 += "policyLabel={" + policyLabel + "} "; + 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(Boolean.FALSE); + } } diff --git a/security-admin/src/main/java/org/apache/ranger/view/VXPolicyExportAudit.java b/security-admin/src/main/java/org/apache/ranger/view/VXPolicyExportAudit.java index 571361d39a..dfb7b9423d 100644 --- a/security-admin/src/main/java/org/apache/ranger/view/VXPolicyExportAudit.java +++ b/security-admin/src/main/java/org/apache/ranger/view/VXPolicyExportAudit.java @@ -17,272 +17,269 @@ * under the License. */ - package org.apache.ranger.view; +package org.apache.ranger.view; /** * Audit Log for Policy Export - * */ -import java.util.Date; - -import org.apache.ranger.common.AppConstants; -import org.apache.ranger.json.JsonDateSerializer; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.databind.annotation.JsonSerialize; +import org.apache.ranger.common.AppConstants; +import org.apache.ranger.json.JsonDateSerializer; + +import java.util.Date; -@JsonAutoDetect(getterVisibility=Visibility.NONE, setterVisibility=Visibility.NONE, fieldVisibility=Visibility.ANY) +@JsonAutoDetect(getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE, fieldVisibility = Visibility.ANY) @JsonInclude(JsonInclude.Include.NON_NULL) -@JsonIgnoreProperties(ignoreUnknown=true) +@JsonIgnoreProperties(ignoreUnknown = true) 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; - /** - * Repository Display Name - */ - protected String repositoryDisplayName; - /** - * JSON of the policies exported - */ - protected String exportedJson; - /** - * HTTP Response Code - */ - protected int httpRetCode; - - protected String syncStatus; - - protected String clusterName; - - protected String zoneName; - - protected Long policyVersion; - - /** - * Default constructor. This will set all the attributes to default value. - */ - public VXPolicyExportAudit ( ) { - } - - /** - * This method sets the value to the member attribute clientIP. - * You cannot set null to the attribute. - * @param clientIP Value to set member attribute clientIP - */ - public void setClientIP( String clientIP ) { - this.clientIP = clientIP; - } - - /** - * Returns the value for the member attribute clientIP - * @return String - value of member attribute clientIP. - */ - public String getClientIP( ) { - return this.clientIP; - } - - /** - * This method sets the value to the member attribute agentId. - * You cannot set null to the attribute. - * @param agentId Value to set member attribute agentId - */ - public void setAgentId( String agentId ) { - this.agentId = agentId; - } - - /** - * Returns the value for the member attribute agentId - * @return String - value of member attribute agentId. - */ - public String getAgentId( ) { - return this.agentId; - } - - /** - * This method sets the value to the member attribute requestedEpoch. - * You cannot set null to the attribute. - * @param requestedEpoch Value to set member attribute requestedEpoch - */ - public void setRequestedEpoch( Long requestedEpoch ) { - this.requestedEpoch = requestedEpoch; - } - - /** - * Returns the value for the member attribute requestedEpoch - * @return Long - value of member attribute requestedEpoch. - */ - public Long getRequestedEpoch( ) { - return this.requestedEpoch; - } - - /** - * This method sets the value to the member attribute lastUpdated. - * You cannot set null to the attribute. - * @param lastUpdated Value to set member attribute lastUpdated - */ - public void setLastUpdated( Date lastUpdated ) { - this.lastUpdated = lastUpdated; - } - - /** - * Returns the value for the member attribute lastUpdated - * @return Date - value of member attribute lastUpdated. - */ - public Date getLastUpdated( ) { - return this.lastUpdated; - } - - /** - * This method sets the value to the member attribute repositoryName. - * You cannot set null to the attribute. - * @param repositoryName Value to set member attribute repositoryName - */ - public void setRepositoryName( String repositoryName ) { - this.repositoryName = repositoryName; - } - - /** - * Returns the value for the member attribute repositoryName - * @return String - value of member attribute repositoryName. - */ - public String getRepositoryName( ) { - return this.repositoryName; - } - - /** - * This method sets the value to the member attribute repositoryDisplayName. - * You cannot set null to the attribute. - * @param repositoryDisplayName Value to set member attribute repositoryDisplayName - */ - public void setRepositoryDisplayName(String repositoryDisplayName) { - this.repositoryDisplayName = repositoryDisplayName; - } - - /** - * Returns the value for the member attribute repositoryDisplayName - * @return String - value of member attribute repositoryDisplayName. - */ - public String getRepositoryDisplayName() { - return repositoryDisplayName; - } - - /** - * This method sets the value to the member attribute exportedJson. - * You cannot set null to the attribute. - * @param exportedJson Value to set member attribute exportedJson - */ - public void setExportedJson( String exportedJson ) { - this.exportedJson = exportedJson; - } - - /** - * Returns the value for the member attribute exportedJson - * @return String - value of member attribute exportedJson. - */ - public String getExportedJson( ) { - return this.exportedJson; - } - - /** - * This method sets the value to the member attribute httpRetCode. - * You cannot set null to the attribute. - * @param httpRetCode Value to set member attribute httpRetCode - */ - public void setHttpRetCode( int httpRetCode ) { - this.httpRetCode = httpRetCode; - } - - /** - * Returns the value for the member attribute httpRetCode - * @return int - value of member attribute httpRetCode. - */ - public int getHttpRetCode( ) { - return this.httpRetCode; - } - - - public String getSyncStatus() { - return syncStatus; - } - - public void setSyncStatus(String syncStatus) { - this.syncStatus = syncStatus; - } - - public String getClusterName() { - return clusterName; - } - - public void setClusterName(String clusterName) { - this.clusterName = clusterName; - } - - public String getZoneName() { - return zoneName; - } - - public void setZoneName(String zoneName) { - this.zoneName = zoneName; - } - - public Long getPolicyVersion() { - return policyVersion; - } - - public void setPolicyVersion(Long policyVersion) { - this.policyVersion = policyVersion; - } - - @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 += "repositoryDisplayName={" + repositoryDisplayName + "} "; - str += "exportedJson={" + exportedJson + "} "; - str += "httpRetCode={" + httpRetCode + "} "; - str += "syncStatus={" + syncStatus + "} "; - str += "clusterName={" + clusterName + "} "; - str += "zoneName={" + zoneName + "}"; - str += "policyVersion={" + policyVersion + "}"; - str += "}"; - return str; - } + 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; + /** + * Repository Display Name + */ + protected String repositoryDisplayName; + /** + * JSON of the policies exported + */ + protected String exportedJson; + /** + * HTTP Response Code + */ + protected int httpRetCode; + + protected String syncStatus; + + protected String clusterName; + + protected String zoneName; + + protected Long policyVersion; + + /** + * Default constructor. This will set all the attributes to default value. + */ + public VXPolicyExportAudit() { + } + + /** + * Returns the value for the member attribute clientIP + * @return String - value of member attribute clientIP. + */ + public String getClientIP() { + return this.clientIP; + } + + /** + * This method sets the value to the member attribute clientIP. + * You cannot set null to the attribute. + * @param clientIP Value to set member attribute clientIP + */ + public void setClientIP(String clientIP) { + this.clientIP = clientIP; + } + + /** + * Returns the value for the member attribute agentId + * @return String - value of member attribute agentId. + */ + public String getAgentId() { + return this.agentId; + } + + /** + * This method sets the value to the member attribute agentId. + * You cannot set null to the attribute. + * @param agentId Value to set member attribute agentId + */ + public void setAgentId(String agentId) { + this.agentId = agentId; + } + + /** + * Returns the value for the member attribute requestedEpoch + * @return Long - value of member attribute requestedEpoch. + */ + public Long getRequestedEpoch() { + return this.requestedEpoch; + } + + /** + * This method sets the value to the member attribute requestedEpoch. + * You cannot set null to the attribute. + * @param requestedEpoch Value to set member attribute requestedEpoch + */ + public void setRequestedEpoch(Long requestedEpoch) { + this.requestedEpoch = requestedEpoch; + } + + /** + * Returns the value for the member attribute lastUpdated + * @return Date - value of member attribute lastUpdated. + */ + public Date getLastUpdated() { + return this.lastUpdated; + } + + /** + * This method sets the value to the member attribute lastUpdated. + * You cannot set null to the attribute. + * @param lastUpdated Value to set member attribute lastUpdated + */ + public void setLastUpdated(Date lastUpdated) { + this.lastUpdated = lastUpdated; + } + + /** + * Returns the value for the member attribute repositoryName + * @return String - value of member attribute repositoryName. + */ + public String getRepositoryName() { + return this.repositoryName; + } + + /** + * This method sets the value to the member attribute repositoryName. + * You cannot set null to the attribute. + * @param repositoryName Value to set member attribute repositoryName + */ + public void setRepositoryName(String repositoryName) { + this.repositoryName = repositoryName; + } + + /** + * Returns the value for the member attribute repositoryDisplayName + * @return String - value of member attribute repositoryDisplayName. + */ + public String getRepositoryDisplayName() { + return repositoryDisplayName; + } + + /** + * This method sets the value to the member attribute repositoryDisplayName. + * You cannot set null to the attribute. + * @param repositoryDisplayName Value to set member attribute repositoryDisplayName + */ + public void setRepositoryDisplayName(String repositoryDisplayName) { + this.repositoryDisplayName = repositoryDisplayName; + } + + /** + * Returns the value for the member attribute exportedJson + * @return String - value of member attribute exportedJson. + */ + public String getExportedJson() { + return this.exportedJson; + } + + /** + * This method sets the value to the member attribute exportedJson. + * You cannot set null to the attribute. + * @param exportedJson Value to set member attribute exportedJson + */ + public void setExportedJson(String exportedJson) { + this.exportedJson = exportedJson; + } + + /** + * Returns the value for the member attribute httpRetCode + * @return int - value of member attribute httpRetCode. + */ + public int getHttpRetCode() { + return this.httpRetCode; + } + + /** + * This method sets the value to the member attribute httpRetCode. + * You cannot set null to the attribute. + * @param httpRetCode Value to set member attribute httpRetCode + */ + public void setHttpRetCode(int httpRetCode) { + this.httpRetCode = httpRetCode; + } + + public String getSyncStatus() { + return syncStatus; + } + + public void setSyncStatus(String syncStatus) { + this.syncStatus = syncStatus; + } + + public String getClusterName() { + return clusterName; + } + + public void setClusterName(String clusterName) { + this.clusterName = clusterName; + } + + public String getZoneName() { + return zoneName; + } + + public void setZoneName(String zoneName) { + this.zoneName = zoneName; + } + + public Long getPolicyVersion() { + return policyVersion; + } + + public void setPolicyVersion(Long policyVersion) { + this.policyVersion = policyVersion; + } + + @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 += "repositoryDisplayName={" + repositoryDisplayName + "} "; + str += "exportedJson={" + exportedJson + "} "; + str += "httpRetCode={" + httpRetCode + "} "; + str += "syncStatus={" + syncStatus + "} "; + str += "clusterName={" + clusterName + "} "; + str += "zoneName={" + zoneName + "}"; + str += "policyVersion={" + policyVersion + "}"; + str += "}"; + return str; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/view/VXPolicyExportAuditList.java b/security-admin/src/main/java/org/apache/ranger/view/VXPolicyExportAuditList.java index 951ea2e1f8..f4238828a2 100644 --- a/security-admin/src/main/java/org/apache/ranger/view/VXPolicyExportAuditList.java +++ b/security-admin/src/main/java/org/apache/ranger/view/VXPolicyExportAuditList.java @@ -17,35 +17,35 @@ * under the License. */ - package org.apache.ranger.view; +package org.apache.ranger.view; /** * List wrapper class for VXPolicyExportAudit - * */ -import java.util.ArrayList; -import java.util.List; - -import org.apache.ranger.common.view.VList; -import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import org.apache.ranger.common.view.VList; + +import java.util.ArrayList; +import java.util.List; -@JsonAutoDetect(getterVisibility=Visibility.NONE, setterVisibility=Visibility.NONE, fieldVisibility=Visibility.ANY) +@JsonAutoDetect(getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE, fieldVisibility = Visibility.ANY) @JsonInclude(JsonInclude.Include.NON_NULL) public class VXPolicyExportAuditList extends VList { - private static final long serialVersionUID = 1L; - List vXPolicyExportAudits = new ArrayList(); + private static final long serialVersionUID = 1L; + + List vXPolicyExportAudits = new ArrayList<>(); public VXPolicyExportAuditList() { - super(); + super(); } public VXPolicyExportAuditList(List objList) { - super(objList); - this.vXPolicyExportAudits = objList; + super(objList); + this.vXPolicyExportAudits = objList; } /** @@ -53,7 +53,7 @@ public VXPolicyExportAuditList(List objList) { */ @JsonProperty("vXPolicyExportAudits") public List getVXPolicyExportAudits() { - return vXPolicyExportAudits; + return vXPolicyExportAudits; } /** @@ -62,20 +62,19 @@ public List getVXPolicyExportAudits() { */ @JsonProperty("vXPolicyExportAudits") public void setVXPolicyExportAudits(List vXPolicyExportAudits) { - this.vXPolicyExportAudits = vXPolicyExportAudits; + this.vXPolicyExportAudits = vXPolicyExportAudits; } @Override public int getListSize() { - if (vXPolicyExportAudits != null) { - return vXPolicyExportAudits.size(); - } - return 0; + if (vXPolicyExportAudits != null) { + return vXPolicyExportAudits.size(); + } + return 0; } @Override public List getList() { - return vXPolicyExportAudits; + return vXPolicyExportAudits; } - } diff --git a/security-admin/src/main/java/org/apache/ranger/view/VXPolicyLabel.java b/security-admin/src/main/java/org/apache/ranger/view/VXPolicyLabel.java index 0a1cd377ca..53356c36a6 100644 --- a/security-admin/src/main/java/org/apache/ranger/view/VXPolicyLabel.java +++ b/security-admin/src/main/java/org/apache/ranger/view/VXPolicyLabel.java @@ -23,7 +23,6 @@ * Policy */ - import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; @@ -33,35 +32,34 @@ @JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) public class VXPolicyLabel extends VXDataObject implements java.io.Serializable { - private static final long serialVersionUID = 1L; - - protected String policyLabel; + private static final long serialVersionUID = 1L; - /** - * Default constructor. This will set all the attributes to default value. - */ - public VXPolicyLabel() { - } + protected String policyLabel; - public String getPolicyLabel() { - return policyLabel; - } + /** + * Default constructor. This will set all the attributes to default value. + */ + public VXPolicyLabel() { + } - public void setPolicyLabel(String policyLabel) { - this.policyLabel = policyLabel; - } + public String getPolicyLabel() { + return policyLabel; + } - /** - * This return the bean content in string format - * - * @return formatedStr - */ - public String toString() { - String str = "VXPolicyLabel={"; - str += super.toString(); - str += "policyLabel={" + policyLabel + "} "; - str += "}"; - return str; - } + public void setPolicyLabel(String policyLabel) { + this.policyLabel = policyLabel; + } + /** + * This return the bean content in string format + * + * @return formatedStr + */ + public String toString() { + String str = "VXPolicyLabel={"; + str += super.toString(); + str += "policyLabel={" + policyLabel + "} "; + str += "}"; + return str; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/view/VXPolicyLabelList.java b/security-admin/src/main/java/org/apache/ranger/view/VXPolicyLabelList.java index 48fd49a588..0ded9a4feb 100644 --- a/security-admin/src/main/java/org/apache/ranger/view/VXPolicyLabelList.java +++ b/security-admin/src/main/java/org/apache/ranger/view/VXPolicyLabelList.java @@ -17,61 +17,60 @@ * under the License. */ - package org.apache.ranger.view; - +package org.apache.ranger.view; /** * List wrapper class for VXPolicy */ -import java.util.ArrayList; -import java.util.List; - -import org.apache.ranger.common.view.VList; -import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import org.apache.ranger.common.view.VList; + +import java.util.ArrayList; +import java.util.List; @JsonAutoDetect(getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE, fieldVisibility = Visibility.ANY) @JsonInclude(JsonInclude.Include.NON_NULL) public class VXPolicyLabelList extends VList { - private static final long serialVersionUID = 1L; - List vxPolicyLabels = new ArrayList(); + private static final long serialVersionUID = 1L; - public VXPolicyLabelList() { - super(); - } + List vxPolicyLabels = new ArrayList<>(); - public VXPolicyLabelList(List objList) { - super(objList); - this.vxPolicyLabels = objList; - } + public VXPolicyLabelList() { + super(); + } - /** - * @return the VXPolicyLabels - */ - @JsonProperty("vxPolicyLabels") - public List getVXPolicyLabels() { - return vxPolicyLabels; - } + public VXPolicyLabelList(List objList) { + super(objList); + this.vxPolicyLabels = objList; + } - @JsonProperty("vxPolicyLabels") - public void setVXPolicyLabels(List vxPolicyLabels) { - this.vxPolicyLabels = vxPolicyLabels; - } + /** + * @return the VXPolicyLabels + */ + @JsonProperty("vxPolicyLabels") + public List getVXPolicyLabels() { + return vxPolicyLabels; + } - @Override - public int getListSize() { - if (vxPolicyLabels != null) { - return vxPolicyLabels.size(); - } - return 0; - } + @JsonProperty("vxPolicyLabels") + public void setVXPolicyLabels(List vxPolicyLabels) { + this.vxPolicyLabels = vxPolicyLabels; + } - @Override - public List getList() { - return vxPolicyLabels; + @Override + public int getListSize() { + if (vxPolicyLabels != null) { + return vxPolicyLabels.size(); } + return 0; + } + @Override + public List getList() { + return vxPolicyLabels; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/view/VXPolicyList.java b/security-admin/src/main/java/org/apache/ranger/view/VXPolicyList.java index f45516c273..0bec68c718 100644 --- a/security-admin/src/main/java/org/apache/ranger/view/VXPolicyList.java +++ b/security-admin/src/main/java/org/apache/ranger/view/VXPolicyList.java @@ -17,65 +17,63 @@ * under the License. */ - package org.apache.ranger.view; - +package org.apache.ranger.view; /** * List wrapper class for VXPolicy */ -import java.util.ArrayList; -import java.util.List; - -import org.apache.ranger.common.view.VList; -import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import org.apache.ranger.common.view.VList; + +import java.util.ArrayList; +import java.util.List; @JsonAutoDetect(getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE, fieldVisibility = Visibility.ANY) @JsonInclude(JsonInclude.Include.NON_NULL) public class VXPolicyList extends VList { - private static final long serialVersionUID = 1L; - List vXPolicies = new ArrayList(); + private static final long serialVersionUID = 1L; - public VXPolicyList() { - super(); - } + List vXPolicies = new ArrayList<>(); - public VXPolicyList(List objList) { - super(objList); - this.vXPolicies = objList; - } + public VXPolicyList() { + super(); + } - /** - * @return the vXPolicies - */ - @JsonProperty("vXPolicies") - public List getVXPolicies() { - return vXPolicies; - } + public VXPolicyList(List objList) { + super(objList); + this.vXPolicies = objList; + } - /** - * @param vXPolicies - * the vXPolicies to set - */ - @JsonProperty("vXPolicies") - public void setVXPolicies(List vXPolicies) { - this.vXPolicies = vXPolicies; - } + /** + * @return the vXPolicies + */ + @JsonProperty("vXPolicies") + public List getVXPolicies() { + return vXPolicies; + } - @Override - public int getListSize() { - if (vXPolicies != null) { - return vXPolicies.size(); - } - return 0; - } + /** + * @param vXPolicies the vXPolicies to set + */ + @JsonProperty("vXPolicies") + public void setVXPolicies(List vXPolicies) { + this.vXPolicies = vXPolicies; + } - @Override - public List getList() { - return vXPolicies; - } + @Override + public int getListSize() { + if (vXPolicies != null) { + return vXPolicies.size(); + } + return 0; + } + @Override + public List getList() { + return vXPolicies; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/view/VXPortalUser.java b/security-admin/src/main/java/org/apache/ranger/view/VXPortalUser.java index 27bae7e8a8..c9ceeb0c44 100644 --- a/security-admin/src/main/java/org/apache/ranger/view/VXPortalUser.java +++ b/security-admin/src/main/java/org/apache/ranger/view/VXPortalUser.java @@ -17,356 +17,372 @@ * under the License. */ - package org.apache.ranger.view; +package org.apache.ranger.view; -import java.util.Collection; -import java.util.List; -import java.util.Map; - -import org.apache.ranger.common.AppConstants; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; +import org.apache.ranger.common.AppConstants; + +import java.util.Collection; +import java.util.List; +import java.util.Map; -@JsonAutoDetect(getterVisibility=Visibility.NONE, setterVisibility=Visibility.NONE, fieldVisibility=Visibility.ANY) +@JsonAutoDetect(getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE, fieldVisibility = Visibility.ANY) @JsonInclude(JsonInclude.Include.NON_NULL) -@JsonIgnoreProperties(ignoreUnknown=true) +@JsonIgnoreProperties(ignoreUnknown = true) 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 userRoleList; - protected Collection groupIdList; - protected List userPermList; - protected List groupPermissions; - - - /** - * Additional store attributes. - * - */ - protected String otherAttributes; - - /** - * sync Source Attribute. - * - */ - protected String syncSource; - - /** - * Configuration properties. - * - */ - protected Map configProperties; - - /** - * 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 loginId. - * You cannot set null to the attribute. - * @param loginId Value to set member attribute loginId - */ - public void setLoginId( String loginId ) { - this.loginId = loginId; - } - - /** - * Returns the value for the member attribute loginId - * @return String - value of member attribute loginId. - */ - public String getLoginId( ) { - return this.loginId; - } - - /** - * This method sets the value to the member attribute password. - * You cannot set null to the attribute. - * @param password Value to set member attribute password - */ - public void setPassword( String password ) { - this.password = password; - } - - /** - * Returns the value for the member attribute password - * @return String - value of member attribute password. - */ - public String getPassword( ) { - return this.password; - } - - /** - * This method sets the value to the member attribute status. - * You cannot set null to the attribute. - * @param status Value to set member attribute status - */ - public void setStatus( int status ) { - this.status = status; - } - - /** - * Returns the value for the member attribute status - * @return int - value of member attribute status. - */ - public int getStatus( ) { - return this.status; - } - - /** - * This method sets the value to the member attribute emailAddress. - * You cannot set null to the attribute. - * @param emailAddress Value to set member attribute emailAddress - */ - public void setEmailAddress( String emailAddress ) { - this.emailAddress = emailAddress; - } - - /** - * Returns the value for the member attribute emailAddress - * @return String - value of member attribute emailAddress. - */ - public String getEmailAddress( ) { - return this.emailAddress; - } - - /** - * This method sets the value to the member attribute firstName. - * You cannot set null to the attribute. - * @param firstName Value to set member attribute firstName - */ - public void setFirstName( String firstName ) { - this.firstName = firstName; - } - - /** - * Returns the value for the member attribute firstName - * @return String - value of member attribute firstName. - */ - public String getFirstName( ) { - return this.firstName; - } - - /** - * This method sets the value to the member attribute lastName. - * You cannot set null to the attribute. - * @param lastName Value to set member attribute lastName - */ - public void setLastName( String lastName ) { - this.lastName = lastName; - } - - /** - * Returns the value for the member attribute lastName - * @return String - value of member attribute lastName. - */ - public String getLastName( ) { - return this.lastName; - } - - /** - * This method sets the value to the member attribute publicScreenName. - * You cannot set null to the attribute. - * @param publicScreenName Value to set member attribute publicScreenName - */ - public void setPublicScreenName( String publicScreenName ) { - this.publicScreenName = publicScreenName; - } - - /** - * Returns the value for the member attribute publicScreenName - * @return String - value of member attribute publicScreenName. - */ - public String getPublicScreenName( ) { - return this.publicScreenName; - } - - /** - * This method sets the value to the member attribute userSource. - * You cannot set null to the attribute. - * @param userSource Value to set member attribute userSource - */ - public void setUserSource( int userSource ) { - this.userSource = userSource; - } - - /** - * Returns the value for the member attribute userSource - * @return int - value of member attribute userSource. - */ - public int getUserSource( ) { - return this.userSource; - } - - /** - * This method sets the value to the member attribute notes. - * You cannot set null to the attribute. - * @param notes Value to set member attribute notes - */ - public void setNotes( String notes ) { - this.notes = notes; - } - - /** - * Returns the value for the member attribute notes - * @return String - value of member attribute notes. - */ - public String getNotes( ) { - return this.notes; - } - - /** - * This method sets the value to the member attribute userRoleList. - * You cannot set null to the attribute. - * @param userRoleList Value to set member attribute userRoleList - */ - public void setUserRoleList( Collection userRoleList ) { - this.userRoleList = userRoleList; - } - - /** - * Returns the value for the member attribute userRoleList - * @return Collection - value of member attribute userRoleList. - */ - public Collection getUserRoleList( ) { - return this.userRoleList; - } - - @Override - public int getMyClassType( ) { - return AppConstants.CLASS_TYPE_USER_PROFILE; - } - - public Collection getGroupIdList() { - return groupIdList; - } - - public void setGroupIdList(Collection groupIdList) { - this.groupIdList = groupIdList; - } - - - public List getUserPermList() { - return userPermList; - } - - public void setUserPermList(List userPermList) { - this.userPermList = userPermList; - } - - public List getGroupPermissions() { - return groupPermissions; - } - - public void setGroupPermissions(List groupPermissions) { - this.groupPermissions = groupPermissions; - } - - - /** - * @return {@link String} - additional attributes. - */ - public String getOtherAttributes() { - return otherAttributes; - } - - /** - * This method sets additional attributes. - * @param otherAttributes - */ - public void setOtherAttributes(final String otherAttributes) { - this.otherAttributes = otherAttributes; - } - - public Map getConfigProperties() { - return configProperties; - } - - public void setConfigProperties(Map configProperties) { - this.configProperties = configProperties; - } - - /** - * @return {@link String} - sync Source attribute. - */ - public String getSyncSource() { - return syncSource; - } - - /** - * This method sets sync Source attribute. - * @param syncSource - */ - public void setSyncSource(final String syncSource) { - this.syncSource = syncSource; - } - - /** - * This return the bean content in string format - * @return formatedStr - */ - public String toString( ) { - String str = "VXPortalUser={"; - str += super.toString(); - str += "loginId={" + loginId + "} "; - 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 += "otherAttributes={" + otherAttributes + "} "; - str += "syncSource={" + syncSource + "} "; - str += "}"; - return str; - } + 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 userRoleList; + protected Collection groupIdList; + protected List userPermList; + protected List groupPermissions; + + /** + * Additional store attributes. + */ + protected String otherAttributes; + + /** + * sync Source Attribute. + */ + protected String syncSource; + + /** + * Configuration properties. + */ + protected Map configProperties; + + /** + * Default constructor. This will set all the attributes to default value. + */ + public VXPortalUser() { + status = 0; + userSource = 0; + } + + /** + * Returns the value for the member attribute loginId + * + * @return String - value of member attribute loginId. + */ + public String getLoginId() { + return this.loginId; + } + + /** + * This method sets the value to the member attribute loginId. + * You cannot set null to the attribute. + * + * @param loginId Value to set member attribute loginId + */ + public void setLoginId(String loginId) { + this.loginId = loginId; + } + + /** + * Returns the value for the member attribute password + * + * @return String - value of member attribute password. + */ + public String getPassword() { + return this.password; + } + + /** + * This method sets the value to the member attribute password. + * You cannot set null to the attribute. + * + * @param password Value to set member attribute password + */ + public void setPassword(String password) { + this.password = password; + } + + /** + * Returns the value for the member attribute status + * + * @return int - value of member attribute status. + */ + public int getStatus() { + return this.status; + } + + /** + * This method sets the value to the member attribute status. + * You cannot set null to the attribute. + * + * @param status Value to set member attribute status + */ + public void setStatus(int status) { + this.status = status; + } + + /** + * Returns the value for the member attribute emailAddress + * + * @return String - value of member attribute emailAddress. + */ + public String getEmailAddress() { + return this.emailAddress; + } + + /** + * This method sets the value to the member attribute emailAddress. + * You cannot set null to the attribute. + * + * @param emailAddress Value to set member attribute emailAddress + */ + public void setEmailAddress(String emailAddress) { + this.emailAddress = emailAddress; + } + + /** + * Returns the value for the member attribute firstName + * + * @return String - value of member attribute firstName. + */ + public String getFirstName() { + return this.firstName; + } + + /** + * This method sets the value to the member attribute firstName. + * You cannot set null to the attribute. + * + * @param firstName Value to set member attribute firstName + */ + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + /** + * Returns the value for the member attribute lastName + * + * @return String - value of member attribute lastName. + */ + public String getLastName() { + return this.lastName; + } + + /** + * This method sets the value to the member attribute lastName. + * You cannot set null to the attribute. + * + * @param lastName Value to set member attribute lastName + */ + public void setLastName(String lastName) { + this.lastName = lastName; + } + + /** + * Returns the value for the member attribute publicScreenName + * + * @return String - value of member attribute publicScreenName. + */ + public String getPublicScreenName() { + return this.publicScreenName; + } + + /** + * This method sets the value to the member attribute publicScreenName. + * You cannot set null to the attribute. + * + * @param publicScreenName Value to set member attribute publicScreenName + */ + public void setPublicScreenName(String publicScreenName) { + this.publicScreenName = publicScreenName; + } + + /** + * Returns the value for the member attribute userSource + * + * @return int - value of member attribute userSource. + */ + public int getUserSource() { + return this.userSource; + } + + /** + * This method sets the value to the member attribute userSource. + * You cannot set null to the attribute. + * + * @param userSource Value to set member attribute userSource + */ + public void setUserSource(int userSource) { + this.userSource = userSource; + } + + /** + * Returns the value for the member attribute notes + * + * @return String - value of member attribute notes. + */ + public String getNotes() { + return this.notes; + } + + /** + * This method sets the value to the member attribute notes. + * You cannot set null to the attribute. + * + * @param notes Value to set member attribute notes + */ + public void setNotes(String notes) { + this.notes = notes; + } + + /** + * Returns the value for the member attribute userRoleList + * + * @return Collection - value of member attribute userRoleList. + */ + public Collection getUserRoleList() { + return this.userRoleList; + } + + /** + * This method sets the value to the member attribute userRoleList. + * You cannot set null to the attribute. + * + * @param userRoleList Value to set member attribute userRoleList + */ + public void setUserRoleList(Collection userRoleList) { + this.userRoleList = 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 += "status={" + status + "} "; + str += "emailAddress={" + emailAddress + "} "; + str += "firstName={" + firstName + "} "; + str += "lastName={" + lastName + "} "; + str += "publicScreenName={" + publicScreenName + "} "; + str += "userSource={" + userSource + "} "; + str += "notes={" + notes + "} "; + str += "userRoleList={" + userRoleList + "} "; + str += "otherAttributes={" + otherAttributes + "} "; + str += "syncSource={" + syncSource + "} "; + str += "}"; + return str; + } + + public Collection getGroupIdList() { + return groupIdList; + } + + public void setGroupIdList(Collection groupIdList) { + this.groupIdList = groupIdList; + } + + public List getUserPermList() { + return userPermList; + } + + public void setUserPermList(List userPermList) { + this.userPermList = userPermList; + } + + public List getGroupPermissions() { + return groupPermissions; + } + + public void setGroupPermissions(List groupPermissions) { + this.groupPermissions = groupPermissions; + } + + /** + * @return {@link String} - additional attributes. + */ + public String getOtherAttributes() { + return otherAttributes; + } + + /** + * This method sets additional attributes. + * + * @param otherAttributes + */ + public void setOtherAttributes(final String otherAttributes) { + this.otherAttributes = otherAttributes; + } + + public Map getConfigProperties() { + return configProperties; + } + + public void setConfigProperties(Map configProperties) { + this.configProperties = configProperties; + } + + /** + * @return {@link String} - sync Source attribute. + */ + public String getSyncSource() { + return syncSource; + } + + /** + * This method sets sync Source attribute. + * + * @param syncSource + */ + public void setSyncSource(final String syncSource) { + this.syncSource = syncSource; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/view/VXPortalUserList.java b/security-admin/src/main/java/org/apache/ranger/view/VXPortalUserList.java index b17a597998..e7861a2a46 100644 --- a/security-admin/src/main/java/org/apache/ranger/view/VXPortalUserList.java +++ b/security-admin/src/main/java/org/apache/ranger/view/VXPortalUserList.java @@ -17,35 +17,35 @@ * under the License. */ - package org.apache.ranger.view; +package org.apache.ranger.view; /** * List wrapper class for VXPortalUser - * */ -import java.util.ArrayList; -import java.util.List; - -import org.apache.ranger.common.view.VList; -import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import org.apache.ranger.common.view.VList; + +import java.util.ArrayList; +import java.util.List; -@JsonAutoDetect(getterVisibility=Visibility.NONE, setterVisibility=Visibility.NONE, fieldVisibility=Visibility.ANY) +@JsonAutoDetect(getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE, fieldVisibility = Visibility.ANY) @JsonInclude(JsonInclude.Include.NON_NULL) public class VXPortalUserList extends VList { - private static final long serialVersionUID = 1L; - List vXPortalUsers = new ArrayList(); + private static final long serialVersionUID = 1L; + + List vXPortalUsers = new ArrayList<>(); public VXPortalUserList() { - super(); + super(); } public VXPortalUserList(List objList) { - super(objList); - this.vXPortalUsers = objList; + super(objList); + this.vXPortalUsers = objList; } /** @@ -53,7 +53,7 @@ public VXPortalUserList(List objList) { */ @JsonProperty("vXPortalUsers") public List getVXPortalUsers() { - return vXPortalUsers; + return vXPortalUsers; } /** @@ -62,20 +62,19 @@ public List getVXPortalUsers() { */ @JsonProperty("vXPortalUsers") public void setVXPortalUsers(List vXPortalUsers) { - this.vXPortalUsers = vXPortalUsers; + this.vXPortalUsers = vXPortalUsers; } @Override public int getListSize() { - if (vXPortalUsers != null) { - return vXPortalUsers.size(); - } - return 0; + if (vXPortalUsers != null) { + return vXPortalUsers.size(); + } + return 0; } @Override public List getList() { - return vXPortalUsers; + return vXPortalUsers; } - } diff --git a/security-admin/src/main/java/org/apache/ranger/view/VXRepository.java b/security-admin/src/main/java/org/apache/ranger/view/VXRepository.java index 071b1af0e3..e4f8a00cd6 100644 --- a/security-admin/src/main/java/org/apache/ranger/view/VXRepository.java +++ b/security-admin/src/main/java/org/apache/ranger/view/VXRepository.java @@ -17,199 +17,191 @@ * under the License. */ - package org.apache.ranger.view; - +package org.apache.ranger.view; /** * Repository */ -import org.apache.ranger.common.AppConstants; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; +import org.apache.ranger.common.AppConstants; @JsonAutoDetect(getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE, fieldVisibility = Visibility.ANY) @JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) 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 name. You - * cannot set null to the attribute. - * - * @param name - * Value to set member attribute name - */ - public void setName(String name) { - this.name = name; - } - - /** - * Returns the value for the member attribute name - * - * @return String - value of member attribute name. - */ - public String getName() { - return this.name; - } - - /** - * This method sets the value to the member attribute description. - * You cannot set null to the attribute. - * - * @param description - * Value to set member attribute description - */ - public void setDescription(String description) { - this.description = description; - } - - /** - * Returns the value for the member attribute description - * - * @return String - value of member attribute description. - */ - public String getDescription() { - return this.description; - } - - /** - * This method sets the value to the member attribute repositoryType. - * You cannot set null to the attribute. - * - * @param repositoryType - * Value to set member attribute repositoryType - */ - public void setRepositoryType(String repositoryType) { - this.repositoryType = repositoryType; - } - - /** - * Returns the value for the member attribute repositoryType - * - * @return String - value of member attribute repositoryType. - */ - public String getRepositoryType() { - return this.repositoryType; - } - - /** - * This method sets the value to the member attribute config. You - * cannot set null to the attribute. - * - * @param config - * Value to set member attribute config - */ - public void setConfig(String config) { - this.config = config; - } - - /** - * Returns the value for the member attribute config - * - * @return String - value of member attribute config. - */ - public String getConfig() { - return this.config; - } - - /** - * This method sets the value to the member attribute isActive. You - * cannot set null to the attribute. - * - * @param isActive - * Value to set member attribute isActive - */ - public void setIsActive(boolean isActive) { - this.isActive = isActive; - } - - /** - * Returns the value for the member attribute isActive - * - * @return boolean - value of member attribute isActive. - */ - public boolean getIsActive() { - return this.isActive; - } - - /** - * Returns the value for the member attribute version - * - * @return String - value of member attribute version. - */ - public String getVersion() { - return version; - } - - /** - * This method sets the value to the member attribute version. You - * cannot set null to the attribute. - * - * @param version - * Value to set member attribute version - */ - 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; - } + 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 = ""; + } + + /** + * Returns the value for the member attribute name + * + * @return String - value of member attribute name. + */ + public String getName() { + return this.name; + } + + /** + * This method sets the value to the member attribute name. You + * cannot set null to the attribute. + * + * @param name Value to set member attribute name + */ + public void setName(String name) { + this.name = name; + } + + /** + * Returns the value for the member attribute description + * + * @return String - value of member attribute description. + */ + public String getDescription() { + return this.description; + } + + /** + * This method sets the value to the member attribute description. + * You cannot set null to the attribute. + * + * @param description Value to set member attribute description + */ + public void setDescription(String description) { + this.description = description; + } + + /** + * Returns the value for the member attribute repositoryType + * + * @return String - value of member attribute repositoryType. + */ + public String getRepositoryType() { + return this.repositoryType; + } + + /** + * This method sets the value to the member attribute repositoryType. + * You cannot set null to the attribute. + * + * @param repositoryType Value to set member attribute repositoryType + */ + public void setRepositoryType(String repositoryType) { + this.repositoryType = repositoryType; + } + + /** + * Returns the value for the member attribute config + * + * @return String - value of member attribute config. + */ + public String getConfig() { + return this.config; + } + + /** + * This method sets the value to the member attribute config. You + * cannot set null to the attribute. + * + * @param config Value to set member attribute config + */ + public void setConfig(String config) { + this.config = config; + } + + /** + * Returns the value for the member attribute isActive + * + * @return boolean - value of member attribute isActive. + */ + public boolean getIsActive() { + return this.isActive; + } + + /** + * This method sets the value to the member attribute isActive. You + * cannot set null to the attribute. + * + * @param isActive Value to set member attribute isActive + */ + public void setIsActive(boolean isActive) { + this.isActive = isActive; + } + + /** + * Returns the value for the member attribute version + * + * @return String - value of member attribute version. + */ + public String getVersion() { + return version; + } + + /** + * This method sets the value to the member attribute version. You + * cannot set null to the attribute. + * + * @param version Value to set member attribute version + */ + 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; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/view/VXRepositoryList.java b/security-admin/src/main/java/org/apache/ranger/view/VXRepositoryList.java index 6e1b3af215..bb7230cad9 100644 --- a/security-admin/src/main/java/org/apache/ranger/view/VXRepositoryList.java +++ b/security-admin/src/main/java/org/apache/ranger/view/VXRepositoryList.java @@ -17,65 +17,63 @@ * under the License. */ - package org.apache.ranger.view; - +package org.apache.ranger.view; /** * List wrapper class for VXRepository */ -import java.util.ArrayList; -import java.util.List; - -import org.apache.ranger.common.view.VList; -import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import org.apache.ranger.common.view.VList; + +import java.util.ArrayList; +import java.util.List; @JsonAutoDetect(getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE, fieldVisibility = Visibility.ANY) @JsonInclude(JsonInclude.Include.NON_NULL) public class VXRepositoryList extends VList { - private static final long serialVersionUID = 1L; - List vXRepositories = new ArrayList(); + private static final long serialVersionUID = 1L; - public VXRepositoryList() { - super(); - } + List vXRepositories = new ArrayList<>(); - public VXRepositoryList(List objList) { - super(objList); - this.vXRepositories = objList; - } + public VXRepositoryList() { + super(); + } - /** - * @return the vXRepositories - */ - @JsonProperty("vXRepositories") - public List getVXRepositories() { - return vXRepositories; - } + public VXRepositoryList(List objList) { + super(objList); + this.vXRepositories = objList; + } - /** - * @param vXRepositories - * the vXRepositories to set - */ - @JsonProperty("vXRepositories") - public void setVXRepositories(List vXRepositories) { - this.vXRepositories = vXRepositories; - } + /** + * @return the vXRepositories + */ + @JsonProperty("vXRepositories") + public List getVXRepositories() { + return vXRepositories; + } - @Override - public int getListSize() { - if (vXRepositories != null) { - return vXRepositories.size(); - } - return 0; - } + /** + * @param vXRepositories the vXRepositories to set + */ + @JsonProperty("vXRepositories") + public void setVXRepositories(List vXRepositories) { + this.vXRepositories = vXRepositories; + } - @Override - public List getList() { - return vXRepositories; - } + @Override + public int getListSize() { + if (vXRepositories != null) { + return vXRepositories.size(); + } + return 0; + } + @Override + public List getList() { + return vXRepositories; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/view/VXResource.java b/security-admin/src/main/java/org/apache/ranger/view/VXResource.java index 146984cd2a..eb8b5f2142 100644 --- a/security-admin/src/main/java/org/apache/ranger/view/VXResource.java +++ b/security-admin/src/main/java/org/apache/ranger/view/VXResource.java @@ -17,652 +17,649 @@ * under the License. */ - package org.apache.ranger.view; +package org.apache.ranger.view; /** * Resource - * */ -import java.util.List; - -import org.apache.ranger.common.AppConstants; -import org.apache.ranger.common.RangerConstants; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; +import org.apache.ranger.common.AppConstants; +import org.apache.ranger.common.RangerConstants; + +import java.util.List; -@JsonAutoDetect(getterVisibility=Visibility.NONE, setterVisibility=Visibility.NONE, fieldVisibility=Visibility.ANY) +@JsonAutoDetect(getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE, fieldVisibility = Visibility.ANY) @JsonInclude(JsonInclude.Include.NON_NULL) -@JsonIgnoreProperties(ignoreUnknown=true) +@JsonIgnoreProperties(ignoreUnknown = true) 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 = RangerConstants.BOOL_FALSE; - /** - * List of permissions maps - */ - protected List permMapList; - /** - * List of audits - */ - protected List auditList; - /** - * Is recursive - * This attribute is of type enum CommonEnums::BooleanValue - */ - protected int isRecursive = RangerConstants.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 = RangerConstants.BOOL_NONE; - /** - * Topologoies - */ - protected String topologies; - /** - * Services - */ - protected String services; - - /** - * Hive Services - */ - protected String hiveServices; - - /** - * guid - */ - protected String guid; - - /** - * Default constructor. This will set all the attributes to default value. - */ - public VXResource ( ) { - resourceType = AppConstants.RESOURCE_PATH; - isEncrypt = RangerConstants.BOOL_FALSE; - isRecursive = RangerConstants.BOOL_NONE; - checkParentPermission = RangerConstants.BOOL_NONE; - } - - /** - * This method sets the value to the member attribute name. - * You cannot set null to the attribute. - * @param name Value to set member attribute name - */ - public void setName( String name ) { - this.name = name; - } - - /** - * Returns the value for the member attribute name - * @return String - value of member attribute name. - */ - 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 description. - * You cannot set null to the attribute. - * @param description Value to set member attribute description - */ - public void setDescription( String description ) { - this.description = description; - } - - /** - * Returns the value for the member attribute description - * @return String - value of member attribute description. - */ - public String getDescription( ) { - return this.description; - } - - /** - * This method sets the value to the member attribute resourceType. - * You cannot set null to the attribute. - * @param resourceType Value to set member attribute resourceType - */ - public void setResourceType( int resourceType ) { - this.resourceType = resourceType; - } - - /** - * Returns the value for the member attribute resourceType - * @return int - value of member attribute resourceType. - */ - public int getResourceType( ) { - return this.resourceType; - } - - /** - * This method sets the value to the member attribute assetId. - * You cannot set null to the attribute. - * @param assetId Value to set member attribute assetId - */ - public void setAssetId( Long assetId ) { - this.assetId = assetId; - } - - /** - * Returns the value for the member attribute assetId - * @return Long - value of member attribute assetId. - */ - public Long getAssetId( ) { - return this.assetId; - } - - /** - * This method sets the value to the member attribute parentId. - * You cannot set null to the attribute. - * @param parentId Value to set member attribute parentId - */ - public void setParentId( Long parentId ) { - this.parentId = parentId; - } - - /** - * Returns the value for the member attribute parentId - * @return Long - value of member attribute parentId. - */ - public Long getParentId( ) { - return this.parentId; - } - - /** - * This method sets the value to the member attribute parentPath. - * You cannot set null to the attribute. - * @param parentPath Value to set member attribute parentPath - */ - public void setParentPath( String parentPath ) { - this.parentPath = parentPath; - } - - /** - * Returns the value for the member attribute parentPath - * @return String - value of member attribute parentPath. - */ - public String getParentPath( ) { - return this.parentPath; - } - - /** - * This method sets the value to the member attribute isEncrypt. - * You cannot set null to the attribute. - * @param isEncrypt Value to set member attribute isEncrypt - */ - public void setIsEncrypt( int isEncrypt ) { - this.isEncrypt = isEncrypt; - } - - /** - * Returns the value for the member attribute isEncrypt - * @return int - value of member attribute isEncrypt. - */ - public int getIsEncrypt( ) { - return this.isEncrypt; - } - - /** - * This method sets the value to the member attribute permMapList. - * You cannot set null to the attribute. - * @param permMapList Value to set member attribute permMapList - */ - public void setPermMapList( List permMapList ) { - this.permMapList = permMapList; - } - - /** - * Returns the value for the member attribute permMapList - * @return List - value of member attribute permMapList. - */ - public List getPermMapList( ) { - return this.permMapList; - } - - /** - * This method sets the value to the member attribute auditList. - * You cannot set null to the attribute. - * @param auditList Value to set member attribute auditList - */ - public void setAuditList( List auditList ) { - this.auditList = auditList; - } - - /** - * Returns the value for the member attribute auditList - * @return List - value of member attribute auditList. - */ - public List getAuditList( ) { - return this.auditList; - } - - /** - * This method sets the value to the member attribute isRecursive. - * You cannot set null to the attribute. - * @param isRecursive Value to set member attribute isRecursive - */ - public void setIsRecursive( int isRecursive ) { - this.isRecursive = isRecursive; - } - - /** - * Returns the value for the member attribute isRecursive - * @return int - value of member attribute isRecursive. - */ - public int getIsRecursive( ) { - return this.isRecursive; - } - - /** - * This method sets the value to the member attribute resourceGroup. - * You cannot set null to the attribute. - * @param resourceGroup Value to set member attribute resourceGroup - */ - public void setResourceGroup( String resourceGroup ) { - this.resourceGroup = resourceGroup; - } - - /** - * Returns the value for the member attribute resourceGroup - * @return String - value of member attribute resourceGroup. - */ - public String getResourceGroup( ) { - return this.resourceGroup; - } - - /** - * This method sets the value to the member attribute databases. - * You cannot set null to the attribute. - * @param databases Value to set member attribute databases - */ - public void setDatabases( String databases ) { - this.databases = databases; - } - - /** - * Returns the value for the member attribute databases - * @return String - value of member attribute databases. - */ - public String getDatabases( ) { - return this.databases; - } - - /** - * This method sets the value to the member attribute tables. - * You cannot set null to the attribute. - * @param tables Value to set member attribute tables - */ - public void setTables( String tables ) { - this.tables = tables; - } - - /** - * Returns the value for the member attribute tables - * @return String - value of member attribute tables. - */ - public String getTables( ) { - return this.tables; - } - - /** - * This method sets the value to the member attribute columnFamilies. - * You cannot set null to the attribute. - * @param columnFamilies Value to set member attribute columnFamilies - */ - public void setColumnFamilies( String columnFamilies ) { - this.columnFamilies = columnFamilies; - } - - /** - * Returns the value for the member attribute columnFamilies - * @return String - value of member attribute columnFamilies. - */ - public String getColumnFamilies( ) { - return this.columnFamilies; - } - - /** - * This method sets the value to the member attribute columns. - * You cannot set null to the attribute. - * @param columns Value to set member attribute columns - */ - public void setColumns( String columns ) { - this.columns = columns; - } - - /** - * Returns the value for the member attribute columns - * @return String - value of member attribute columns. - */ - public String getColumns( ) { - return this.columns; - } - - /** - * This method sets the value to the member attribute udfs. - * You cannot set null to the attribute. - * @param udfs Value to set member attribute udfs - */ - public void setUdfs( String udfs ) { - this.udfs = udfs; - } - - /** - * Returns the value for the member attribute udfs - * @return String - value of member attribute udfs. - */ - public String getUdfs( ) { - return this.udfs; - } - - /** - * This method sets the value to the member attribute assetName. - * You cannot set null to the attribute. - * @param assetName Value to set member attribute assetName - */ - public void setAssetName( String assetName ) { - this.assetName = assetName; - } - - /** - * Returns the value for the member attribute assetName - * @return String - value of member attribute assetName. - */ - public String getAssetName( ) { - return this.assetName; - } - - /** - * This method sets the value to the member attribute assetType. - * You cannot set null to the attribute. - * @param assetType Value to set member attribute assetType - */ - public void setAssetType( int assetType ) { - this.assetType = assetType; - } - - /** - * Returns the value for the member attribute assetType - * @return int - value of member attribute assetType. - */ - public int getAssetType( ) { - return this.assetType; - } - - /** - * This method sets the value to the member attribute resourceStatus. - * You cannot set null to the attribute. - * @param resourceStatus Value to set member attribute resourceStatus - */ - public void setResourceStatus( int resourceStatus ) { - this.resourceStatus = resourceStatus; - } - - /** - * Returns the value for the member attribute resourceStatus - * @return int - value of member attribute resourceStatus. - */ - public int getResourceStatus( ) { - return this.resourceStatus; - } - - /** - * This method sets the value to the member attribute tableType. - * You cannot set null to the attribute. - * @param tableType Value to set member attribute tableType - */ - public void setTableType( int tableType ) { - this.tableType = tableType; - } - - /** - * Returns the value for the member attribute tableType - * @return int - value of member attribute tableType. - */ - public int getTableType( ) { - return this.tableType; - } - - /** - * This method sets the value to the member attribute columnType. - * You cannot set null to the attribute. - * @param columnType Value to set member attribute columnType - */ - public void setColumnType( int columnType ) { - this.columnType = columnType; - } - - /** - * Returns the value for the member attribute columnType - * @return int - value of member attribute columnType. - */ - public int getColumnType( ) { - return this.columnType; - } - - /** - * Returns the value for the member attribute topologies - * - * @return String - value of member attribute topologies. - */ - public String getTopologies() { - return topologies; - } - - /** - * This method sets the value to the member attribute topologies. You - * cannot set null to the attribute. - * - * @param topologies - * Value to set member attribute topologies - */ - public void setTopologies(String topologies) { - this.topologies = topologies; - } - - /** - * Returns the value for the member attribute services - * - * @return String - value of member attribute services. - */ - public String getServices() { - return services; - } - - /** - * This method sets the value to the member attribute services. You - * cannot set null to the attribute. - * - * @param services - * Value to set member attribute services - */ - public void setServices(String services) { - this.services = services; - } - - - /** - * This method sets the value to the member attribute hiveservices. You - * cannot set null to the attribute. - * - * @param hiveServices - * Value to set member attribute hiveservices - */ - public void setHiveServices(String hiveServices) { - this.hiveServices = hiveServices; - } - - /** - * Returns the value for the member attribute hiveservices - * - * @return String - value of member attribute hiveservices. - */ - public String getHiveServices() { - return hiveServices; - } - - /** - * This method sets the value to the member attribute checkParentPermission. - * You cannot set null to the attribute. - * @param checkParentPermission Value to set member attribute checkParentPermission - */ - public void setCheckParentPermission( int checkParentPermission ) { - this.checkParentPermission = checkParentPermission; - } - - /** - * Returns the value for the member attribute checkParentPermission - * @return int - value of member attribute checkParentPermission. - */ - public int getCheckParentPermission( ) { - return this.checkParentPermission; - } - - @Override - public int getMyClassType( ) { - return AppConstants.CLASS_TYPE_XA_RESOURCE; - } - - /** - * Returns the value for the member attribute guid - * - * @return String - value of member attribute guid. - */ - public String getGuid() { - return guid; - } - - /** - * This method sets the value to the member attribute guid. You - * cannot set null to the attribute. - * - * @param guid - Value to set member attribute guid - */ - public void setGuid(String guid) { - this.guid = guid; - } - - /** - * This return the bean content in string format - * @return formatedStr - */ - public String toString( ) { - String str = "VXResource={"; - str += super.toString(); - str += "name={" + name + "} "; - str += "guid={" + guid + "} "; - 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; - } + 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 = RangerConstants.BOOL_FALSE; + /** + * List of permissions maps + */ + protected List permMapList; + /** + * List of audits + */ + protected List auditList; + /** + * Is recursive + * This attribute is of type enum CommonEnums::BooleanValue + */ + protected int isRecursive = RangerConstants.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 = RangerConstants.BOOL_NONE; + /** + * Topologoies + */ + protected String topologies; + /** + * Services + */ + protected String services; + + /** + * Hive Services + */ + protected String hiveServices; + + /** + * guid + */ + protected String guid; + + /** + * Default constructor. This will set all the attributes to default value. + */ + public VXResource() { + resourceType = AppConstants.RESOURCE_PATH; + isEncrypt = RangerConstants.BOOL_FALSE; + isRecursive = RangerConstants.BOOL_NONE; + checkParentPermission = RangerConstants.BOOL_NONE; + } + + /** + * Returns the value for the member attribute name + * @return String - value of member attribute name. + */ + public String getName() { + return this.name; + } + + /** + * This method sets the value to the member attribute name. + * You cannot set null to the attribute. + * @param name Value to set member attribute name + */ + 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 description + * @return String - value of member attribute description. + */ + public String getDescription() { + return this.description; + } + + /** + * This method sets the value to the member attribute description. + * You cannot set null to the attribute. + * @param description Value to set member attribute description + */ + public void setDescription(String description) { + this.description = description; + } + + /** + * Returns the value for the member attribute resourceType + * @return int - value of member attribute resourceType. + */ + public int getResourceType() { + return this.resourceType; + } + + /** + * This method sets the value to the member attribute resourceType. + * You cannot set null to the attribute. + * @param resourceType Value to set member attribute resourceType + */ + public void setResourceType(int resourceType) { + this.resourceType = resourceType; + } + + /** + * Returns the value for the member attribute assetId + * @return Long - value of member attribute assetId. + */ + public Long getAssetId() { + return this.assetId; + } + + /** + * This method sets the value to the member attribute assetId. + * You cannot set null to the attribute. + * @param assetId Value to set member attribute assetId + */ + public void setAssetId(Long assetId) { + this.assetId = assetId; + } + + /** + * Returns the value for the member attribute parentId + * @return Long - value of member attribute parentId. + */ + public Long getParentId() { + return this.parentId; + } + + /** + * This method sets the value to the member attribute parentId. + * You cannot set null to the attribute. + * @param parentId Value to set member attribute parentId + */ + public void setParentId(Long parentId) { + this.parentId = parentId; + } + + /** + * Returns the value for the member attribute parentPath + * @return String - value of member attribute parentPath. + */ + public String getParentPath() { + return this.parentPath; + } + + /** + * This method sets the value to the member attribute parentPath. + * You cannot set null to the attribute. + * @param parentPath Value to set member attribute parentPath + */ + public void setParentPath(String parentPath) { + this.parentPath = parentPath; + } + + /** + * Returns the value for the member attribute isEncrypt + * @return int - value of member attribute isEncrypt. + */ + public int getIsEncrypt() { + return this.isEncrypt; + } + + /** + * This method sets the value to the member attribute isEncrypt. + * You cannot set null to the attribute. + * @param isEncrypt Value to set member attribute isEncrypt + */ + public void setIsEncrypt(int isEncrypt) { + this.isEncrypt = isEncrypt; + } + + /** + * Returns the value for the member attribute permMapList + * @return List - value of member attribute permMapList. + */ + public List getPermMapList() { + return this.permMapList; + } + + /** + * This method sets the value to the member attribute permMapList. + * You cannot set null to the attribute. + * @param permMapList Value to set member attribute permMapList + */ + public void setPermMapList(List permMapList) { + this.permMapList = permMapList; + } + + /** + * Returns the value for the member attribute auditList + * @return List - value of member attribute auditList. + */ + public List getAuditList() { + return this.auditList; + } + + /** + * This method sets the value to the member attribute auditList. + * You cannot set null to the attribute. + * @param auditList Value to set member attribute auditList + */ + public void setAuditList(List auditList) { + this.auditList = auditList; + } + + /** + * Returns the value for the member attribute isRecursive + * @return int - value of member attribute isRecursive. + */ + public int getIsRecursive() { + return this.isRecursive; + } + + /** + * This method sets the value to the member attribute isRecursive. + * You cannot set null to the attribute. + * @param isRecursive Value to set member attribute isRecursive + */ + public void setIsRecursive(int isRecursive) { + this.isRecursive = isRecursive; + } + + /** + * Returns the value for the member attribute resourceGroup + * @return String - value of member attribute resourceGroup. + */ + public String getResourceGroup() { + return this.resourceGroup; + } + + /** + * This method sets the value to the member attribute resourceGroup. + * You cannot set null to the attribute. + * @param resourceGroup Value to set member attribute resourceGroup + */ + public void setResourceGroup(String resourceGroup) { + this.resourceGroup = resourceGroup; + } + + /** + * Returns the value for the member attribute databases + * @return String - value of member attribute databases. + */ + public String getDatabases() { + return this.databases; + } + + /** + * This method sets the value to the member attribute databases. + * You cannot set null to the attribute. + * @param databases Value to set member attribute databases + */ + public void setDatabases(String databases) { + this.databases = databases; + } + + /** + * Returns the value for the member attribute tables + * @return String - value of member attribute tables. + */ + public String getTables() { + return this.tables; + } + + /** + * This method sets the value to the member attribute tables. + * You cannot set null to the attribute. + * @param tables Value to set member attribute tables + */ + public void setTables(String tables) { + this.tables = tables; + } + + /** + * Returns the value for the member attribute columnFamilies + * @return String - value of member attribute columnFamilies. + */ + public String getColumnFamilies() { + return this.columnFamilies; + } + + /** + * This method sets the value to the member attribute columnFamilies. + * You cannot set null to the attribute. + * @param columnFamilies Value to set member attribute columnFamilies + */ + public void setColumnFamilies(String columnFamilies) { + this.columnFamilies = columnFamilies; + } + + /** + * Returns the value for the member attribute columns + * @return String - value of member attribute columns. + */ + public String getColumns() { + return this.columns; + } + + /** + * This method sets the value to the member attribute columns. + * You cannot set null to the attribute. + * @param columns Value to set member attribute columns + */ + public void setColumns(String columns) { + this.columns = columns; + } + + /** + * Returns the value for the member attribute udfs + * @return String - value of member attribute udfs. + */ + public String getUdfs() { + return this.udfs; + } + + /** + * This method sets the value to the member attribute udfs. + * You cannot set null to the attribute. + * @param udfs Value to set member attribute udfs + */ + public void setUdfs(String udfs) { + this.udfs = udfs; + } + + /** + * Returns the value for the member attribute assetName + * @return String - value of member attribute assetName. + */ + public String getAssetName() { + return this.assetName; + } + + /** + * This method sets the value to the member attribute assetName. + * You cannot set null to the attribute. + * @param assetName Value to set member attribute assetName + */ + public void setAssetName(String assetName) { + this.assetName = assetName; + } + + /** + * Returns the value for the member attribute assetType + * @return int - value of member attribute assetType. + */ + public int getAssetType() { + return this.assetType; + } + + /** + * This method sets the value to the member attribute assetType. + * You cannot set null to the attribute. + * @param assetType Value to set member attribute assetType + */ + public void setAssetType(int assetType) { + this.assetType = assetType; + } + + /** + * Returns the value for the member attribute resourceStatus + * @return int - value of member attribute resourceStatus. + */ + public int getResourceStatus() { + return this.resourceStatus; + } + + /** + * This method sets the value to the member attribute resourceStatus. + * You cannot set null to the attribute. + * @param resourceStatus Value to set member attribute resourceStatus + */ + public void setResourceStatus(int resourceStatus) { + this.resourceStatus = resourceStatus; + } + + /** + * Returns the value for the member attribute tableType + * @return int - value of member attribute tableType. + */ + public int getTableType() { + return this.tableType; + } + + /** + * This method sets the value to the member attribute tableType. + * You cannot set null to the attribute. + * @param tableType Value to set member attribute tableType + */ + public void setTableType(int tableType) { + this.tableType = tableType; + } + + /** + * Returns the value for the member attribute columnType + * @return int - value of member attribute columnType. + */ + public int getColumnType() { + return this.columnType; + } + + /** + * This method sets the value to the member attribute columnType. + * You cannot set null to the attribute. + * @param columnType Value to set member attribute columnType + */ + public void setColumnType(int columnType) { + this.columnType = columnType; + } + + /** + * Returns the value for the member attribute topologies + * + * @return String - value of member attribute topologies. + */ + public String getTopologies() { + return topologies; + } + + /** + * This method sets the value to the member attribute topologies. You + * cannot set null to the attribute. + * + * @param topologies + * Value to set member attribute topologies + */ + public void setTopologies(String topologies) { + this.topologies = topologies; + } + + /** + * Returns the value for the member attribute services + * + * @return String - value of member attribute services. + */ + public String getServices() { + return services; + } + + /** + * This method sets the value to the member attribute services. You + * cannot set null to the attribute. + * + * @param services + * Value to set member attribute services + */ + public void setServices(String services) { + this.services = services; + } + + /** + * Returns the value for the member attribute hiveservices + * + * @return String - value of member attribute hiveservices. + */ + public String getHiveServices() { + return hiveServices; + } + + /** + * This method sets the value to the member attribute hiveservices. You + * cannot set null to the attribute. + * + * @param hiveServices + * Value to set member attribute hiveservices + */ + public void setHiveServices(String hiveServices) { + this.hiveServices = hiveServices; + } + + /** + * Returns the value for the member attribute checkParentPermission + * @return int - value of member attribute checkParentPermission. + */ + public int getCheckParentPermission() { + return this.checkParentPermission; + } + + /** + * This method sets the value to the member attribute checkParentPermission. + * You cannot set null to the attribute. + * @param checkParentPermission Value to set member attribute checkParentPermission + */ + public void setCheckParentPermission(int checkParentPermission) { + this.checkParentPermission = 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 += "guid={" + guid + "} "; + 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; + } + + /** + * Returns the value for the member attribute guid + * + * @return String - value of member attribute guid. + */ + public String getGuid() { + return guid; + } + + /** + * This method sets the value to the member attribute guid. You + * cannot set null to the attribute. + * + * @param guid - Value to set member attribute guid + */ + public void setGuid(String guid) { + this.guid = guid; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/view/VXResourceList.java b/security-admin/src/main/java/org/apache/ranger/view/VXResourceList.java index c933eefe6f..6a472e20f4 100644 --- a/security-admin/src/main/java/org/apache/ranger/view/VXResourceList.java +++ b/security-admin/src/main/java/org/apache/ranger/view/VXResourceList.java @@ -17,35 +17,35 @@ * under the License. */ - package org.apache.ranger.view; +package org.apache.ranger.view; /** * List wrapper class for VXResource - * */ -import java.util.ArrayList; -import java.util.List; - -import org.apache.ranger.common.view.VList; -import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import org.apache.ranger.common.view.VList; + +import java.util.ArrayList; +import java.util.List; -@JsonAutoDetect(getterVisibility=Visibility.NONE, setterVisibility=Visibility.NONE, fieldVisibility=Visibility.ANY) +@JsonAutoDetect(getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE, fieldVisibility = Visibility.ANY) @JsonInclude(JsonInclude.Include.NON_NULL) public class VXResourceList extends VList { - private static final long serialVersionUID = 1L; - List vXResources = new ArrayList(); + private static final long serialVersionUID = 1L; + + List vXResources = new ArrayList<>(); public VXResourceList() { - super(); + super(); } public VXResourceList(List objList) { - super(objList); - this.vXResources = objList; + super(objList); + this.vXResources = objList; } /** @@ -53,7 +53,7 @@ public VXResourceList(List objList) { */ @JsonProperty("vXResources") public List getVXResources() { - return vXResources; + return vXResources; } /** @@ -62,20 +62,19 @@ public List getVXResources() { */ @JsonProperty("vXResources") public void setVXResources(List vXResources) { - this.vXResources = vXResources; + this.vXResources = vXResources; } @Override public int getListSize() { - if (vXResources != null) { - return vXResources.size(); - } - return 0; + if (vXResources != null) { + return vXResources.size(); + } + return 0; } @Override public List getList() { - return vXResources; + return vXResources; } - } diff --git a/security-admin/src/main/java/org/apache/ranger/view/VXResponse.java b/security-admin/src/main/java/org/apache/ranger/view/VXResponse.java index abcf72a6ee..3190c61138 100644 --- a/security-admin/src/main/java/org/apache/ranger/view/VXResponse.java +++ b/security-admin/src/main/java/org/apache/ranger/view/VXResponse.java @@ -17,150 +17,146 @@ * under the License. */ - package org.apache.ranger.view; +package org.apache.ranger.view; /** * Response - * */ -import java.util.List; - -import org.apache.ranger.common.AppConstants; -import org.apache.ranger.common.view.ViewBaseBean; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; +import org.apache.ranger.common.AppConstants; +import org.apache.ranger.common.view.ViewBaseBean; + +import java.util.List; -@JsonAutoDetect(getterVisibility=Visibility.NONE, setterVisibility=Visibility.NONE, fieldVisibility=Visibility.ANY) +@JsonAutoDetect(getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE, fieldVisibility = Visibility.ANY) @JsonInclude(JsonInclude.Include.NON_NULL) -@JsonIgnoreProperties(ignoreUnknown=true) +@JsonIgnoreProperties(ignoreUnknown = true) 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 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 statusCode. - * You cannot set null to the attribute. - * @param statusCode Value to set member attribute statusCode - */ - public void setStatusCode( int statusCode ) { - this.statusCode = statusCode; - } - - /** - * Returns the value for the member attribute statusCode - * @return int - value of member attribute statusCode. - */ - public int getStatusCode( ) { - return this.statusCode; - } - - /** - * This method sets the value to the member attribute msgDesc. - * You cannot set null to the attribute. - * @param msgDesc Value to set member attribute msgDesc - */ - public void setMsgDesc( String msgDesc ) { - this.msgDesc = msgDesc; - } - - /** - * Returns the value for the member attribute msgDesc - * @return String - value of member attribute msgDesc. - */ - public String getMsgDesc( ) { - return this.msgDesc; - } - - /** - * This method sets the value to the member attribute messageList. - * You cannot set null to the attribute. - * @param messageList Value to set member attribute messageList - */ - public void setMessageList( List messageList ) { - this.messageList = messageList; - } - - /** - * Returns the value for the member attribute messageList - * @return List - value of member attribute messageList. - */ - public List 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; - } + /** + * STATUS_SUCCESS is an element of enum ResponseStatus. Its value is "STATUS_SUCCESS". + */ + public static final int STATUS_SUCCESS = 0; + + /** + * Enum values for ResponseStatus + */ + /** + * 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; + private static final long serialVersionUID = 1L; + /** + * Status code + * This attribute is of type enum XResponse::ResponseStatus + */ + protected int statusCode; + /** + * Message description + */ + protected String msgDesc; + /** + * List of messages + */ + protected List messageList; + + /** + * Default constructor. This will set all the attributes to default value. + */ + public VXResponse() { + statusCode = 0; + } + + /** + * Returns the value for the member attribute statusCode + * @return int - value of member attribute statusCode. + */ + public int getStatusCode() { + return this.statusCode; + } + + /** + * This method sets the value to the member attribute statusCode. + * You cannot set null to the attribute. + * @param statusCode Value to set member attribute statusCode + */ + public void setStatusCode(int statusCode) { + this.statusCode = statusCode; + } + + /** + * Returns the value for the member attribute msgDesc + * @return String - value of member attribute msgDesc. + */ + public String getMsgDesc() { + return this.msgDesc; + } + + /** + * This method sets the value to the member attribute msgDesc. + * You cannot set null to the attribute. + * @param msgDesc Value to set member attribute msgDesc + */ + public void setMsgDesc(String msgDesc) { + this.msgDesc = msgDesc; + } + + /** + * Returns the value for the member attribute messageList + * @return List - value of member attribute messageList. + */ + public List getMessageList() { + return this.messageList; + } + + /** + * This method sets the value to the member attribute messageList. + * You cannot set null to the attribute. + * @param messageList Value to set member attribute messageList + */ + public void setMessageList(List messageList) { + this.messageList = 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; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/view/VXString.java b/security-admin/src/main/java/org/apache/ranger/view/VXString.java index e88134ecd6..8b66c860d9 100644 --- a/security-admin/src/main/java/org/apache/ranger/view/VXString.java +++ b/security-admin/src/main/java/org/apache/ranger/view/VXString.java @@ -17,69 +17,67 @@ * under the License. */ - package org.apache.ranger.view; +package org.apache.ranger.view; /** * String - * */ -import org.apache.ranger.common.AppConstants; -import org.apache.ranger.common.view.ViewBaseBean; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; +import org.apache.ranger.common.AppConstants; +import org.apache.ranger.common.view.ViewBaseBean; -@JsonAutoDetect(getterVisibility=Visibility.NONE, setterVisibility=Visibility.NONE, fieldVisibility=Visibility.ANY) +@JsonAutoDetect(getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE, fieldVisibility = Visibility.ANY) @JsonInclude(JsonInclude.Include.NON_NULL) -@JsonIgnoreProperties(ignoreUnknown=true) +@JsonIgnoreProperties(ignoreUnknown = true) public class VXString extends ViewBaseBean implements java.io.Serializable { - private static final long serialVersionUID = 1L; - + private static final long serialVersionUID = 1L; - /** - * Value - */ - protected String value; + /** + * Value + */ + protected String value; - /** - * Default constructor. This will set all the attributes to default value. - */ - public VXString ( ) { - } + /** + * Default constructor. This will set all the attributes to default value. + */ + public VXString() { + } - /** - * This method sets the value to the member attribute value. - * You cannot set null to the attribute. - * @param value Value to set member attribute value - */ - public void setValue( String value ) { - this.value = value; - } + /** + * Returns the value for the member attribute value + * @return String - value of member attribute value. + */ + public String getValue() { + return this.value; + } - /** - * Returns the value for the member attribute value - * @return String - value of member attribute value. - */ - public String getValue( ) { - return this.value; - } + /** + * This method sets the value to the member attribute value. + * You cannot set null to the attribute. + * @param value Value to set member attribute value + */ + public void setValue(String value) { + this.value = value; + } - @Override - public int getMyClassType( ) { - return AppConstants.CLASS_TYPE_STRING; - } + @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; - } + /** + * 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; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/view/VXStringList.java b/security-admin/src/main/java/org/apache/ranger/view/VXStringList.java index 81b40830cc..277caa1195 100644 --- a/security-admin/src/main/java/org/apache/ranger/view/VXStringList.java +++ b/security-admin/src/main/java/org/apache/ranger/view/VXStringList.java @@ -17,35 +17,35 @@ * under the License. */ - package org.apache.ranger.view; +package org.apache.ranger.view; /** * List wrapper class for VXString - * */ -import java.util.ArrayList; -import java.util.List; - -import org.apache.ranger.common.view.VList; -import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import org.apache.ranger.common.view.VList; + +import java.util.ArrayList; +import java.util.List; -@JsonAutoDetect(getterVisibility=Visibility.NONE, setterVisibility=Visibility.NONE, fieldVisibility=Visibility.ANY) +@JsonAutoDetect(getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE, fieldVisibility = Visibility.ANY) @JsonInclude(JsonInclude.Include.NON_NULL) public class VXStringList extends VList { - private static final long serialVersionUID = 1L; - List vXStrings = new ArrayList(); + private static final long serialVersionUID = 1L; + + List vXStrings = new ArrayList<>(); public VXStringList() { - super(); + super(); } public VXStringList(List objList) { - super(objList); - this.vXStrings = objList; + super(objList); + this.vXStrings = objList; } /** @@ -53,7 +53,7 @@ public VXStringList(List objList) { */ @JsonProperty("vXStrings") public List getVXStrings() { - return vXStrings; + return vXStrings; } /** @@ -62,20 +62,19 @@ public List getVXStrings() { */ @JsonProperty("vXStrings") public void setVXStrings(List vXStrings) { - this.vXStrings = vXStrings; + this.vXStrings = vXStrings; } @Override public int getListSize() { - if (vXStrings != null) { - return vXStrings.size(); - } - return 0; + if (vXStrings != null) { + return vXStrings.size(); + } + return 0; } @Override public List getList() { - return vXStrings; + return vXStrings; } - } diff --git a/security-admin/src/main/java/org/apache/ranger/view/VXTrxLog.java b/security-admin/src/main/java/org/apache/ranger/view/VXTrxLog.java index 087b4179c5..b5b127f845 100644 --- a/security-admin/src/main/java/org/apache/ranger/view/VXTrxLog.java +++ b/security-admin/src/main/java/org/apache/ranger/view/VXTrxLog.java @@ -17,351 +17,349 @@ * under the License. */ - package org.apache.ranger.view; +package org.apache.ranger.view; /** * Logging table for all DB create and update queries - * */ -import org.apache.ranger.common.RangerConstants; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; +import org.apache.ranger.common.RangerConstants; -@JsonAutoDetect(getterVisibility=Visibility.NONE, setterVisibility=Visibility.NONE, fieldVisibility=Visibility.ANY) +@JsonAutoDetect(getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE, fieldVisibility = Visibility.ANY) @JsonInclude(JsonInclude.Include.NON_NULL) -@JsonIgnoreProperties(ignoreUnknown=true) +@JsonIgnoreProperties(ignoreUnknown = true) 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 = RangerConstants.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 = RangerConstants.CLASS_TYPE_NONE; - } - - /** - * This method sets the value to the member attribute objectClassType. - * You cannot set null to the attribute. - * @param objectClassType Value to set member attribute objectClassType - */ - public void setObjectClassType( int objectClassType ) { - this.objectClassType = objectClassType; - } - - /** - * Returns the value for the member attribute objectClassType - * @return int - value of member attribute objectClassType. - */ - public int getObjectClassType( ) { - return this.objectClassType; - } - - /** - * This method sets the value to the member attribute objectId. - * You cannot set null to the attribute. - * @param objectId Value to set member attribute objectId - */ - public void setObjectId( Long objectId ) { - this.objectId = objectId; - } - - /** - * Returns the value for the member attribute objectId - * @return Long - value of member attribute objectId. - */ - public Long getObjectId( ) { - return this.objectId; - } - - /** - * This method sets the value to the member attribute parentObjectId. - * You cannot set null to the attribute. - * @param parentObjectId Value to set member attribute parentObjectId - */ - public void setParentObjectId( Long parentObjectId ) { - this.parentObjectId = parentObjectId; - } - - /** - * Returns the value for the member attribute parentObjectId - * @return Long - value of member attribute parentObjectId. - */ - public Long getParentObjectId( ) { - return this.parentObjectId; - } - - /** - * This method sets the value to the member attribute parentObjectClassType. - * You cannot set null to the attribute. - * @param parentObjectClassType Value to set member attribute parentObjectClassType - */ - public void setParentObjectClassType( int parentObjectClassType ) { - this.parentObjectClassType = parentObjectClassType; - } - - /** - * Returns the value for the member attribute parentObjectClassType - * @return int - value of member attribute parentObjectClassType. - */ - public int getParentObjectClassType( ) { - return this.parentObjectClassType; - } - - /** - * This method sets the value to the member attribute parentObjectName. - * You cannot set null to the attribute. - * @param parentObjectName Value to set member attribute parentObjectName - */ - public void setParentObjectName( String parentObjectName ) { - this.parentObjectName = parentObjectName; - } - - /** - * Returns the value for the member attribute parentObjectName - * @return String - value of member attribute parentObjectName. - */ - public String getParentObjectName( ) { - return this.parentObjectName; - } - - /** - * This method sets the value to the member attribute objectName. - * You cannot set null to the attribute. - * @param objectName Value to set member attribute objectName - */ - public void setObjectName( String objectName ) { - this.objectName = objectName; - } - - /** - * Returns the value for the member attribute objectName - * @return String - value of member attribute objectName. - */ - public String getObjectName( ) { - return this.objectName; - } - - /** - * This method sets the value to the member attribute attributeName. - * You cannot set null to the attribute. - * @param attributeName Value to set member attribute attributeName - */ - public void setAttributeName( String attributeName ) { - this.attributeName = attributeName; - } - - /** - * Returns the value for the member attribute attributeName - * @return String - value of member attribute attributeName. - */ - public String getAttributeName( ) { - return this.attributeName; - } - - /** - * This method sets the value to the member attribute previousValue. - * You cannot set null to the attribute. - * @param previousValue Value to set member attribute previousValue - */ - public void setPreviousValue( String previousValue ) { - this.previousValue = previousValue; - } - - /** - * Returns the value for the member attribute previousValue - * @return String - value of member attribute previousValue. - */ - public String getPreviousValue( ) { - return this.previousValue; - } - - /** - * This method sets the value to the member attribute newValue. - * You cannot set null to the attribute. - * @param newValue Value to set member attribute newValue - */ - public void setNewValue( String newValue ) { - this.newValue = newValue; - } - - /** - * Returns the value for the member attribute newValue - * @return String - value of member attribute newValue. - */ - public String getNewValue( ) { - return this.newValue; - } - - /** - * This method sets the value to the member attribute transactionId. - * You cannot set null to the attribute. - * @param transactionId Value to set member attribute transactionId - */ - public void setTransactionId( String transactionId ) { - this.transactionId = transactionId; - } - - /** - * Returns the value for the member attribute transactionId - * @return String - value of member attribute transactionId. - */ - public String getTransactionId( ) { - return this.transactionId; - } - - /** - * This method sets the value to the member attribute action. - * You cannot set null to the attribute. - * @param action Value to set member attribute action - */ - public void setAction( String action ) { - this.action = action; - } - - /** - * Returns the value for the member attribute action - * @return String - value of member attribute action. - */ - public String getAction( ) { - return this.action; - } - - /** - * This method sets the value to the member attribute sessionId. - * You cannot set null to the attribute. - * @param sessionId Value to set member attribute sessionId - */ - public void setSessionId( String sessionId ) { - this.sessionId = sessionId; - } - - /** - * Returns the value for the member attribute sessionId - * @return String - value of member attribute sessionId. - */ - public String getSessionId( ) { - return this.sessionId; - } - - /** - * This method sets the value to the member attribute requestId. - * You cannot set null to the attribute. - * @param requestId Value to set member attribute requestId - */ - public void setRequestId( String requestId ) { - this.requestId = requestId; - } - - /** - * Returns the value for the member attribute requestId - * @return String - value of member attribute requestId. - */ - public String getRequestId( ) { - return this.requestId; - } - - /** - * This method sets the value to the member attribute sessionType. - * You cannot set null to the attribute. - * @param sessionType Value to set member attribute sessionType - */ - public void setSessionType( String sessionType ) { - this.sessionType = sessionType; - } - - /** - * Returns the value for the member attribute sessionType - * @return String - value of member attribute sessionType. - */ - 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; - } + 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 = RangerConstants.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 = RangerConstants.CLASS_TYPE_NONE; + } + + /** + * Returns the value for the member attribute objectClassType + * @return int - value of member attribute objectClassType. + */ + public int getObjectClassType() { + return this.objectClassType; + } + + /** + * This method sets the value to the member attribute objectClassType. + * You cannot set null to the attribute. + * @param objectClassType Value to set member attribute objectClassType + */ + public void setObjectClassType(int objectClassType) { + this.objectClassType = objectClassType; + } + + /** + * Returns the value for the member attribute objectId + * @return Long - value of member attribute objectId. + */ + public Long getObjectId() { + return this.objectId; + } + + /** + * This method sets the value to the member attribute objectId. + * You cannot set null to the attribute. + * @param objectId Value to set member attribute objectId + */ + public void setObjectId(Long objectId) { + this.objectId = objectId; + } + + /** + * Returns the value for the member attribute parentObjectId + * @return Long - value of member attribute parentObjectId. + */ + public Long getParentObjectId() { + return this.parentObjectId; + } + + /** + * This method sets the value to the member attribute parentObjectId. + * You cannot set null to the attribute. + * @param parentObjectId Value to set member attribute parentObjectId + */ + public void setParentObjectId(Long parentObjectId) { + this.parentObjectId = parentObjectId; + } + + /** + * Returns the value for the member attribute parentObjectClassType + * @return int - value of member attribute parentObjectClassType. + */ + public int getParentObjectClassType() { + return this.parentObjectClassType; + } + + /** + * This method sets the value to the member attribute parentObjectClassType. + * You cannot set null to the attribute. + * @param parentObjectClassType Value to set member attribute parentObjectClassType + */ + public void setParentObjectClassType(int parentObjectClassType) { + this.parentObjectClassType = parentObjectClassType; + } + + /** + * Returns the value for the member attribute parentObjectName + * @return String - value of member attribute parentObjectName. + */ + public String getParentObjectName() { + return this.parentObjectName; + } + + /** + * This method sets the value to the member attribute parentObjectName. + * You cannot set null to the attribute. + * @param parentObjectName Value to set member attribute parentObjectName + */ + public void setParentObjectName(String parentObjectName) { + this.parentObjectName = parentObjectName; + } + + /** + * Returns the value for the member attribute objectName + * @return String - value of member attribute objectName. + */ + public String getObjectName() { + return this.objectName; + } + + /** + * This method sets the value to the member attribute objectName. + * You cannot set null to the attribute. + * @param objectName Value to set member attribute objectName + */ + public void setObjectName(String objectName) { + this.objectName = objectName; + } + + /** + * Returns the value for the member attribute attributeName + * @return String - value of member attribute attributeName. + */ + public String getAttributeName() { + return this.attributeName; + } + + /** + * This method sets the value to the member attribute attributeName. + * You cannot set null to the attribute. + * @param attributeName Value to set member attribute attributeName + */ + public void setAttributeName(String attributeName) { + this.attributeName = attributeName; + } + + /** + * Returns the value for the member attribute previousValue + * @return String - value of member attribute previousValue. + */ + public String getPreviousValue() { + return this.previousValue; + } + + /** + * This method sets the value to the member attribute previousValue. + * You cannot set null to the attribute. + * @param previousValue Value to set member attribute previousValue + */ + public void setPreviousValue(String previousValue) { + this.previousValue = previousValue; + } + + /** + * Returns the value for the member attribute newValue + * @return String - value of member attribute newValue. + */ + public String getNewValue() { + return this.newValue; + } + + /** + * This method sets the value to the member attribute newValue. + * You cannot set null to the attribute. + * @param newValue Value to set member attribute newValue + */ + public void setNewValue(String newValue) { + this.newValue = newValue; + } + + /** + * Returns the value for the member attribute transactionId + * @return String - value of member attribute transactionId. + */ + public String getTransactionId() { + return this.transactionId; + } + + /** + * This method sets the value to the member attribute transactionId. + * You cannot set null to the attribute. + * @param transactionId Value to set member attribute transactionId + */ + public void setTransactionId(String transactionId) { + this.transactionId = transactionId; + } + + /** + * Returns the value for the member attribute action + * @return String - value of member attribute action. + */ + public String getAction() { + return this.action; + } + + /** + * This method sets the value to the member attribute action. + * You cannot set null to the attribute. + * @param action Value to set member attribute action + */ + public void setAction(String action) { + this.action = action; + } + + /** + * Returns the value for the member attribute sessionId + * @return String - value of member attribute sessionId. + */ + public String getSessionId() { + return this.sessionId; + } + + /** + * This method sets the value to the member attribute sessionId. + * You cannot set null to the attribute. + * @param sessionId Value to set member attribute sessionId + */ + public void setSessionId(String sessionId) { + this.sessionId = sessionId; + } + + /** + * Returns the value for the member attribute requestId + * @return String - value of member attribute requestId. + */ + public String getRequestId() { + return this.requestId; + } + + /** + * This method sets the value to the member attribute requestId. + * You cannot set null to the attribute. + * @param requestId Value to set member attribute requestId + */ + public void setRequestId(String requestId) { + this.requestId = requestId; + } + + /** + * Returns the value for the member attribute sessionType + * @return String - value of member attribute sessionType. + */ + public String getSessionType() { + return this.sessionType; + } + + /** + * This method sets the value to the member attribute sessionType. + * You cannot set null to the attribute. + * @param sessionType Value to set member attribute sessionType + */ + public void setSessionType(String sessionType) { + this.sessionType = 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; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/view/VXTrxLogList.java b/security-admin/src/main/java/org/apache/ranger/view/VXTrxLogList.java index 600e29b399..c3c66a5a54 100644 --- a/security-admin/src/main/java/org/apache/ranger/view/VXTrxLogList.java +++ b/security-admin/src/main/java/org/apache/ranger/view/VXTrxLogList.java @@ -17,31 +17,31 @@ * under the License. */ - package org.apache.ranger.view; +package org.apache.ranger.view; -import java.util.ArrayList; -import java.util.List; - - -import org.apache.ranger.common.view.VList; -import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import org.apache.ranger.common.view.VList; + +import java.util.ArrayList; +import java.util.List; -@JsonAutoDetect(getterVisibility=Visibility.NONE, setterVisibility=Visibility.NONE, fieldVisibility=Visibility.ANY) +@JsonAutoDetect(getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE, fieldVisibility = Visibility.ANY) @JsonInclude(JsonInclude.Include.NON_NULL) public class VXTrxLogList extends VList { - private static final long serialVersionUID = 1L; - List vXTrxLogs = new ArrayList(); + private static final long serialVersionUID = 1L; + + List vXTrxLogs = new ArrayList<>(); public VXTrxLogList() { - super(); + super(); } public VXTrxLogList(List objList) { - super(objList); - this.vXTrxLogs = objList; + super(objList); + this.vXTrxLogs = objList; } /** @@ -49,29 +49,27 @@ public VXTrxLogList(List objList) { */ @JsonProperty("vXTrxLogs") public List getVXTrxLogs() { - return vXTrxLogs; + return vXTrxLogs; } /** - * @param vXTrxLogs - * the vXTrxLogs to set + * @param vXTrxLogs the vXTrxLogs to set */ @JsonProperty("vXTrxLogs") public void setVXTrxLogs(List vXTrxLogs) { - this.vXTrxLogs = vXTrxLogs; + this.vXTrxLogs = vXTrxLogs; } @Override public int getListSize() { - if (vXTrxLogs != null) { - return vXTrxLogs.size(); - } - return 0; + if (vXTrxLogs != null) { + return vXTrxLogs.size(); + } + return 0; } @Override public List getList() { - return vXTrxLogs; + return vXTrxLogs; } - } diff --git a/security-admin/src/main/java/org/apache/ranger/view/VXTrxLogV2.java b/security-admin/src/main/java/org/apache/ranger/view/VXTrxLogV2.java index a60134b120..0514eb8e2f 100644 --- a/security-admin/src/main/java/org/apache/ranger/view/VXTrxLogV2.java +++ b/security-admin/src/main/java/org/apache/ranger/view/VXTrxLogV2.java @@ -19,368 +19,368 @@ package org.apache.ranger.view; -import org.apache.commons.lang3.StringUtils; -import org.apache.ranger.common.RangerConstants; -import org.apache.ranger.json.JsonDateSerializer; -import org.apache.ranger.plugin.util.JsonUtilsV2; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.databind.annotation.JsonSerialize; +import org.apache.commons.lang3.StringUtils; +import org.apache.ranger.common.RangerConstants; +import org.apache.ranger.json.JsonDateSerializer; +import org.apache.ranger.plugin.util.JsonUtilsV2; import java.io.Serializable; import java.util.ArrayList; import java.util.Date; import java.util.List; -@JsonAutoDetect(getterVisibility=Visibility.NONE, setterVisibility=Visibility.NONE, fieldVisibility=Visibility.ANY) +@JsonAutoDetect(getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE, fieldVisibility = Visibility.ANY) @JsonInclude(JsonInclude.Include.NON_NULL) -@JsonIgnoreProperties(ignoreUnknown=true) +@JsonIgnoreProperties(ignoreUnknown = true) public class VXTrxLogV2 implements java.io.Serializable { - private static final long serialVersionUID = 1L; - - protected Long id; - @JsonSerialize(using=JsonDateSerializer.class) - protected Date createDate; - protected String createdBy; - protected int objectClassType = RangerConstants.CLASS_TYPE_NONE; - protected Long objectId; - protected String objectName; - protected int parentObjectClassType; - protected Long parentObjectId; - protected String parentObjectName; - protected String action; - protected ObjectChangeInfo changeInfo; - protected String requestId; - protected String transactionId; - protected String sessionId; - protected String sessionType; - - /** - * Default constructor. This will set all the attributes to default value. - */ - public VXTrxLogV2( ) { - } - - public VXTrxLogV2(VXTrxLog trxLog) { - if (trxLog != null) { - this.id = trxLog.getId(); - this.createDate = trxLog.getCreateDate(); - this.createdBy = trxLog.getOwner(); - this.objectClassType = trxLog.getObjectClassType(); - this.objectId = trxLog.getObjectId(); - this.objectName = trxLog.getObjectName(); - this.parentObjectClassType = trxLog.getParentObjectClassType(); - this.parentObjectId = trxLog.getParentObjectId(); - this.parentObjectName = trxLog.getParentObjectName(); - this.action = trxLog.getAction(); - this.requestId = trxLog.getRequestId(); - this.transactionId = trxLog.getTransactionId(); - this.sessionId = trxLog.getSessionId(); - this.sessionType = trxLog.getSessionType(); - - if (StringUtils.isNotBlank(trxLog.getAttributeName())) { - this.changeInfo = new ObjectChangeInfo(); - - this.changeInfo.addAttribute(new AttributeChangeInfo(trxLog.getAttributeName(), trxLog.getPreviousValue(), trxLog.getNewValue())); - } else { - this.changeInfo = null; - } - } - } - - public void setId(Long id) { - this.id = id; - } - - public Long getId( ) { - return id; - } - - public void setCreateDate(Date createDate) { - this.createDate = createDate; - } - - public Date getCreateDate() { - return createDate; - } - - public void setCreatedBy(String createdBy) { - this.createdBy = createdBy; - } - - public String getCreatedBy() { - return createdBy; - } - - public void setObjectClassType(int objectClassType) { - this.objectClassType = objectClassType; - } - - public int getObjectClassType() { - return this.objectClassType; - } - - public void setObjectId(Long objectId) { - this.objectId = objectId; - } - - public Long getObjectId() { - return this.objectId; - } - - public void setObjectName(String objectName) { - this.objectName = objectName; - } - - public String getObjectName() { - return this.objectName; - } - - public void setParentObjectClassType(int parentObjectClassType) { - this.parentObjectClassType = parentObjectClassType; - } - - public int getParentObjectClassType() { - return this.parentObjectClassType; - } - - public void setParentObjectId(Long parentObjectId) { - this.parentObjectId = parentObjectId; - } - - public Long getParentObjectId() { - return this.parentObjectId; - } - - public void setParentObjectName(String parentObjectName) { - this.parentObjectName = parentObjectName; - } - - public String getParentObjectName() { - return this.parentObjectName; - } - - public void setAction(String action) { - this.action = action; - } - - public String getAction() { - return this.action; - } - - public void setChangeInfo(ObjectChangeInfo changeInfo) { - this.changeInfo = changeInfo; - } - - public ObjectChangeInfo getChangeInfo() { - return this.changeInfo; - } - - public void setRequestId(String requestId) { - this.requestId = requestId; - } - - public String getRequestId() { - return this.requestId; - } - - public void setTransactionId(String transactionId) { - this.transactionId = transactionId; - } - - public String getTransactionId() { - return this.transactionId; - } - - public void setSessionId(String sessionId) { - this.sessionId = sessionId; - } - - public String getSessionId() { - return this.sessionId; - } - - public void setSessionType(String sessionType) { - this.sessionType = sessionType; - } - - public String getSessionType() { - return this.sessionType; - } - - @Override - public String toString( ) { - return toString(new StringBuilder()).toString(); - } - - public static VXTrxLog toVXTrxLog(VXTrxLogV2 trxLogV2) { - VXTrxLog ret = new VXTrxLog(); - - if (trxLogV2 != null) { - ret.setId(trxLogV2.getId()); - ret.setCreateDate(trxLogV2.getCreateDate()); - ret.setUpdateDate(trxLogV2.getCreateDate()); - ret.setOwner(trxLogV2.getCreatedBy()); - ret.setUpdatedBy(trxLogV2.getCreatedBy()); - ret.setObjectClassType(trxLogV2.getObjectClassType()); - ret.setObjectId(trxLogV2.getObjectId()); - ret.setObjectName(trxLogV2.getObjectName()); - ret.setParentObjectClassType(trxLogV2.getParentObjectClassType()); - ret.setParentObjectId((trxLogV2.getParentObjectId())); - ret.setParentObjectName(trxLogV2.getParentObjectName()); - ret.setAction(trxLogV2.getAction()); - ret.setRequestId(trxLogV2.getRequestId()); - ret.setTransactionId(trxLogV2.getTransactionId()); - ret.setSessionId(trxLogV2.getSessionId()); - ret.setSessionType(trxLogV2.getSessionType()); - } - - return ret; - } - - public StringBuilder toString(StringBuilder sb) { - sb.append("VXTrxLogV2={") - .append("id={").append(id).append("} ") - .append("createDate={").append(createDate).append("} ") - .append("createdBy={").append(createdBy).append("} ") - .append("objectClassType={").append(objectClassType).append("} ") - .append("objectId={").append(objectId).append("} ") - .append("objectName={").append(objectName).append("} ") - .append("parentObjectId={").append(parentObjectId).append("} ") - .append("parentObjectClassType={").append(parentObjectClassType).append("} ") - .append("parentObjectName={").append(parentObjectName).append("} ") - .append("action={").append(action).append("} ") - .append("changeInfo={"); - - if (changeInfo != null) { - changeInfo.toString(sb); - } - - sb.append("} ") - .append("requestId={").append(requestId).append("} ") - .append("transactionId={").append(transactionId).append("} ") - .append("sessionId={").append(sessionId).append("} ") - .append("sessionType={").append(sessionType).append("} ") - .append("}"); - - return sb; - } - - @JsonAutoDetect(getterVisibility=Visibility.NONE, setterVisibility=Visibility.NONE, fieldVisibility=Visibility.ANY) - @JsonInclude(JsonInclude.Include.NON_NULL) - @JsonIgnoreProperties(ignoreUnknown=true) - public static class ObjectChangeInfo implements Serializable { - private static final long serialVersionUID = 1L; - - private List attributes; - - public List getAttributes() { - return attributes; - } - - public void setAttributes(List attributes) { - this.attributes = attributes; - } - - public void addAttribute(AttributeChangeInfo changeInfo) { - if (attributes == null) { - attributes = new ArrayList<>(); - } - - attributes.add(changeInfo); - } - - public void addAttribute(String attributeName, String oldValue, String newValue) { - addAttribute(new AttributeChangeInfo(attributeName, oldValue, newValue)); - } - - @JsonIgnore - public String toJson() { - try { - return JsonUtilsV2.objToJson(this); - } catch (Exception e) { - // TODO: log error - return null; - } - } - - @Override - public String toString( ) { - return toString(new StringBuilder()).toString(); - } - - public StringBuilder toString(StringBuilder sb) { - sb.append("{ attributes=["); - - if (attributes != null) { - for (AttributeChangeInfo changeInfo : attributes) { - changeInfo.toString(sb); - } - } - - sb.append("] }"); - - return sb; - } - } - - @JsonAutoDetect(getterVisibility=Visibility.NONE, setterVisibility=Visibility.NONE, fieldVisibility=Visibility.ANY) - @JsonInclude(JsonInclude.Include.NON_NULL) - @JsonIgnoreProperties(ignoreUnknown=true) - public static class AttributeChangeInfo implements Serializable { - private static final long serialVersionUID = 1L; - - private String attributeName; - private String oldValue; - private String newValue; - - public AttributeChangeInfo() { } - - public AttributeChangeInfo(String attributeName, String oldValue, String newValue) { - this.attributeName = attributeName; - this.oldValue = oldValue; - this.newValue = newValue; - } - - public String getAttributeName() { - return attributeName; - } - - public void setAttributeName(String attributeName) { - this.attributeName = attributeName; - } - - public String getOldValue() { - return oldValue; - } - - public void setOldValue(String oldValue) { - this.oldValue = oldValue; - } - - public String getNewValue() { - return newValue; - } - - public void setNewValue(String newValue) { - this.newValue = newValue; - } - - @Override - public String toString( ) { - return toString(new StringBuilder()).toString(); - } - - public StringBuilder toString(StringBuilder sb) { - sb.append("{ attributeName={").append(attributeName).append("} ") - .append("oldValue={").append(oldValue).append("} ") - .append("newValue={").append(newValue).append("} ") - .append("}"); - - return sb; - } - } + private static final long serialVersionUID = 1L; + + protected Long id; + @JsonSerialize(using = JsonDateSerializer.class) + protected Date createDate; + protected String createdBy; + protected int objectClassType = RangerConstants.CLASS_TYPE_NONE; + protected Long objectId; + protected String objectName; + protected int parentObjectClassType; + protected Long parentObjectId; + protected String parentObjectName; + protected String action; + protected ObjectChangeInfo changeInfo; + protected String requestId; + protected String transactionId; + protected String sessionId; + protected String sessionType; + + /** + * Default constructor. This will set all the attributes to default value. + */ + public VXTrxLogV2() { + } + + public VXTrxLogV2(VXTrxLog trxLog) { + if (trxLog != null) { + this.id = trxLog.getId(); + this.createDate = trxLog.getCreateDate(); + this.createdBy = trxLog.getOwner(); + this.objectClassType = trxLog.getObjectClassType(); + this.objectId = trxLog.getObjectId(); + this.objectName = trxLog.getObjectName(); + this.parentObjectClassType = trxLog.getParentObjectClassType(); + this.parentObjectId = trxLog.getParentObjectId(); + this.parentObjectName = trxLog.getParentObjectName(); + this.action = trxLog.getAction(); + this.requestId = trxLog.getRequestId(); + this.transactionId = trxLog.getTransactionId(); + this.sessionId = trxLog.getSessionId(); + this.sessionType = trxLog.getSessionType(); + + if (StringUtils.isNotBlank(trxLog.getAttributeName())) { + this.changeInfo = new ObjectChangeInfo(); + + this.changeInfo.addAttribute(new AttributeChangeInfo(trxLog.getAttributeName(), trxLog.getPreviousValue(), trxLog.getNewValue())); + } else { + this.changeInfo = null; + } + } + } + + public static VXTrxLog toVXTrxLog(VXTrxLogV2 trxLogV2) { + VXTrxLog ret = new VXTrxLog(); + + if (trxLogV2 != null) { + ret.setId(trxLogV2.getId()); + ret.setCreateDate(trxLogV2.getCreateDate()); + ret.setUpdateDate(trxLogV2.getCreateDate()); + ret.setOwner(trxLogV2.getCreatedBy()); + ret.setUpdatedBy(trxLogV2.getCreatedBy()); + ret.setObjectClassType(trxLogV2.getObjectClassType()); + ret.setObjectId(trxLogV2.getObjectId()); + ret.setObjectName(trxLogV2.getObjectName()); + ret.setParentObjectClassType(trxLogV2.getParentObjectClassType()); + ret.setParentObjectId((trxLogV2.getParentObjectId())); + ret.setParentObjectName(trxLogV2.getParentObjectName()); + ret.setAction(trxLogV2.getAction()); + ret.setRequestId(trxLogV2.getRequestId()); + ret.setTransactionId(trxLogV2.getTransactionId()); + ret.setSessionId(trxLogV2.getSessionId()); + ret.setSessionType(trxLogV2.getSessionType()); + } + + return ret; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public Date getCreateDate() { + return createDate; + } + + public void setCreateDate(Date createDate) { + this.createDate = createDate; + } + + public String getCreatedBy() { + return createdBy; + } + + public void setCreatedBy(String createdBy) { + this.createdBy = createdBy; + } + + public int getObjectClassType() { + return this.objectClassType; + } + + public void setObjectClassType(int objectClassType) { + this.objectClassType = objectClassType; + } + + public Long getObjectId() { + return this.objectId; + } + + public void setObjectId(Long objectId) { + this.objectId = objectId; + } + + public String getObjectName() { + return this.objectName; + } + + public void setObjectName(String objectName) { + this.objectName = objectName; + } + + public int getParentObjectClassType() { + return this.parentObjectClassType; + } + + public void setParentObjectClassType(int parentObjectClassType) { + this.parentObjectClassType = parentObjectClassType; + } + + public Long getParentObjectId() { + return this.parentObjectId; + } + + public void setParentObjectId(Long parentObjectId) { + this.parentObjectId = parentObjectId; + } + + public String getParentObjectName() { + return this.parentObjectName; + } + + public void setParentObjectName(String parentObjectName) { + this.parentObjectName = parentObjectName; + } + + public String getAction() { + return this.action; + } + + public void setAction(String action) { + this.action = action; + } + + public ObjectChangeInfo getChangeInfo() { + return this.changeInfo; + } + + public void setChangeInfo(ObjectChangeInfo changeInfo) { + this.changeInfo = changeInfo; + } + + public String getRequestId() { + return this.requestId; + } + + public void setRequestId(String requestId) { + this.requestId = requestId; + } + + public String getTransactionId() { + return this.transactionId; + } + + public void setTransactionId(String transactionId) { + this.transactionId = transactionId; + } + + public String getSessionId() { + return this.sessionId; + } + + public void setSessionId(String sessionId) { + this.sessionId = sessionId; + } + + public String getSessionType() { + return this.sessionType; + } + + public void setSessionType(String sessionType) { + this.sessionType = sessionType; + } + + @Override + public String toString() { + return toString(new StringBuilder()).toString(); + } + + public StringBuilder toString(StringBuilder sb) { + sb.append("VXTrxLogV2={") + .append("id={").append(id).append("} ") + .append("createDate={").append(createDate).append("} ") + .append("createdBy={").append(createdBy).append("} ") + .append("objectClassType={").append(objectClassType).append("} ") + .append("objectId={").append(objectId).append("} ") + .append("objectName={").append(objectName).append("} ") + .append("parentObjectId={").append(parentObjectId).append("} ") + .append("parentObjectClassType={").append(parentObjectClassType).append("} ") + .append("parentObjectName={").append(parentObjectName).append("} ") + .append("action={").append(action).append("} ") + .append("changeInfo={"); + + if (changeInfo != null) { + changeInfo.toString(sb); + } + + sb.append("} ") + .append("requestId={").append(requestId).append("} ") + .append("transactionId={").append(transactionId).append("} ") + .append("sessionId={").append(sessionId).append("} ") + .append("sessionType={").append(sessionType).append("} ") + .append("}"); + + return sb; + } + + @JsonAutoDetect(getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE, fieldVisibility = Visibility.ANY) + @JsonInclude(JsonInclude.Include.NON_NULL) + @JsonIgnoreProperties(ignoreUnknown = true) + public static class ObjectChangeInfo implements Serializable { + private static final long serialVersionUID = 1L; + + private List attributes; + + public List getAttributes() { + return attributes; + } + + public void setAttributes(List attributes) { + this.attributes = attributes; + } + + public void addAttribute(AttributeChangeInfo changeInfo) { + if (attributes == null) { + attributes = new ArrayList<>(); + } + + attributes.add(changeInfo); + } + + public void addAttribute(String attributeName, String oldValue, String newValue) { + addAttribute(new AttributeChangeInfo(attributeName, oldValue, newValue)); + } + + @JsonIgnore + public String toJson() { + try { + return JsonUtilsV2.objToJson(this); + } catch (Exception e) { + // TODO: log error + return null; + } + } + + @Override + public String toString() { + return toString(new StringBuilder()).toString(); + } + + public StringBuilder toString(StringBuilder sb) { + sb.append("{ attributes=["); + + if (attributes != null) { + for (AttributeChangeInfo changeInfo : attributes) { + changeInfo.toString(sb); + } + } + + sb.append("] }"); + + return sb; + } + } + + @JsonAutoDetect(getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE, fieldVisibility = Visibility.ANY) + @JsonInclude(JsonInclude.Include.NON_NULL) + @JsonIgnoreProperties(ignoreUnknown = true) + public static class AttributeChangeInfo implements Serializable { + private static final long serialVersionUID = 1L; + + private String attributeName; + private String oldValue; + private String newValue; + + public AttributeChangeInfo() {} + + public AttributeChangeInfo(String attributeName, String oldValue, String newValue) { + this.attributeName = attributeName; + this.oldValue = oldValue; + this.newValue = newValue; + } + + public String getAttributeName() { + return attributeName; + } + + public void setAttributeName(String attributeName) { + this.attributeName = attributeName; + } + + public String getOldValue() { + return oldValue; + } + + public void setOldValue(String oldValue) { + this.oldValue = oldValue; + } + + public String getNewValue() { + return newValue; + } + + public void setNewValue(String newValue) { + this.newValue = newValue; + } + + @Override + public String toString() { + return toString(new StringBuilder()).toString(); + } + + public StringBuilder toString(StringBuilder sb) { + sb.append("{ attributeName={").append(attributeName).append("} ") + .append("oldValue={").append(oldValue).append("} ") + .append("newValue={").append(newValue).append("} ") + .append("}"); + + return sb; + } + } } diff --git a/security-admin/src/main/java/org/apache/ranger/view/VXTrxLogV2List.java b/security-admin/src/main/java/org/apache/ranger/view/VXTrxLogV2List.java index 6fa55b606c..dcb489649c 100644 --- a/security-admin/src/main/java/org/apache/ranger/view/VXTrxLogV2List.java +++ b/security-admin/src/main/java/org/apache/ranger/view/VXTrxLogV2List.java @@ -19,19 +19,19 @@ package org.apache.ranger.view; -import org.apache.ranger.common.view.VList; -import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import org.apache.ranger.common.view.VList; import java.util.ArrayList; import java.util.List; -@JsonAutoDetect(getterVisibility=Visibility.NONE, setterVisibility=Visibility.NONE, fieldVisibility=Visibility.ANY) +@JsonAutoDetect(getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE, fieldVisibility = Visibility.ANY) @JsonInclude(JsonInclude.Include.NON_NULL) public class VXTrxLogV2List extends VList { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; List vXTrxLogs = new ArrayList<>(); public VXTrxLogV2List() { @@ -52,8 +52,7 @@ public List getVXTrxLogs() { } /** - * @param vXTrxLogs - * the vXTrxLogs to set + * @param vXTrxLogs the vXTrxLogs to set */ @JsonProperty("vXTrxLogs") public void setVXTrxLogs(List vXTrxLogs) { @@ -62,9 +61,9 @@ public void setVXTrxLogs(List vXTrxLogs) { @Override public int getListSize() { - if (vXTrxLogs != null) { - return vXTrxLogs.size(); - } + if (vXTrxLogs != null) { + return vXTrxLogs.size(); + } return 0; } @@ -72,5 +71,4 @@ public int getListSize() { public List getList() { return vXTrxLogs; } - } diff --git a/security-admin/src/main/java/org/apache/ranger/view/VXUgsyncAuditInfo.java b/security-admin/src/main/java/org/apache/ranger/view/VXUgsyncAuditInfo.java index bac53ef9c2..fc714bfc6f 100644 --- a/security-admin/src/main/java/org/apache/ranger/view/VXUgsyncAuditInfo.java +++ b/security-admin/src/main/java/org/apache/ranger/view/VXUgsyncAuditInfo.java @@ -17,142 +17,140 @@ * under the License. */ - package org.apache.ranger.view; +package org.apache.ranger.view; /** * UserGroupInfo - * */ -import org.apache.ranger.json.JsonDateSerializer; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.databind.annotation.JsonSerialize; +import org.apache.ranger.json.JsonDateSerializer; import java.util.Date; import java.util.HashMap; import java.util.Map; -@JsonAutoDetect(getterVisibility=Visibility.NONE, setterVisibility=Visibility.NONE, fieldVisibility=Visibility.ANY) +@JsonAutoDetect(getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE, fieldVisibility = Visibility.ANY) @JsonInclude(JsonInclude.Include.NON_NULL) -@JsonIgnoreProperties(ignoreUnknown=true) -public class VXUgsyncAuditInfo extends VXDataObject implements java.io.Serializable { - - private static final long serialVersionUID = 1L; - - @JsonSerialize(using=JsonDateSerializer.class) - private Date eventTime; - - private String userName; - private Long noOfNewUsers; - private Long noOfNewGroups; - private Long noOfModifiedUsers; - private Long noOfModifiedGroups; - private String syncSource; - private String sessionId; - private Map syncSourceInfo; - private VXLdapSyncSourceInfo ldapSyncSourceInfo; - private VXFileSyncSourceInfo fileSyncSourceInfo; - private VXUnixSyncSourceInfo unixSyncSourceInfo; - - public VXUgsyncAuditInfo() { - } - - public Date getEventTime() { - return eventTime; - } - - public void setEventTime(Date eventTime) { - this.eventTime = eventTime; - } - - public String getUserName() { - return userName; - } - - public void setUserName(String userName) { - this.userName = userName; - } - - public Long getNoOfNewUsers() { - return noOfNewUsers; - } - - public void setNoOfNewUsers(Long noOfUsers) { - this.noOfNewUsers = noOfUsers; - } - - public Long getNoOfModifiedUsers() { - return noOfModifiedUsers; - } - - public void setNoOfModifiedUsers(Long noOfModifiedUsers) { - this.noOfModifiedUsers = noOfModifiedUsers; - } - - public Long getNoOfNewGroups() { - return noOfNewGroups; - } - - public void setNoOfNewGroups(Long noOfNewGroups) { - this.noOfNewGroups = noOfNewGroups; - } - - public Long getNoOfModifiedGroups() { - return noOfModifiedGroups; - } - - public void setNoOfModifiedGroups(Long noOfModifiedGroups) { - this.noOfModifiedGroups = noOfModifiedGroups; - } - - public String getSyncSource() { - return syncSource; - } - - public void setSyncSource(String syncSource) { - this.syncSource = syncSource; - } - - public VXLdapSyncSourceInfo getLdapSyncSourceInfo() { - return ldapSyncSourceInfo; - } - - public void setLdapSyncSourceInfo(VXLdapSyncSourceInfo ldapSyncSourceInfo) { - this.ldapSyncSourceInfo = ldapSyncSourceInfo; - } - - public VXFileSyncSourceInfo getFileSyncSourceInfo() { - return fileSyncSourceInfo; - } - - public void setFileSyncSourceInfo(VXFileSyncSourceInfo fileSyncSourceInfo) { - this.fileSyncSourceInfo = fileSyncSourceInfo; - } - - public VXUnixSyncSourceInfo getUnixSyncSourceInfo() { - return unixSyncSourceInfo; - } - - public void setUnixSyncSourceInfo(VXUnixSyncSourceInfo unixSyncSourceInfo) { - this.unixSyncSourceInfo = unixSyncSourceInfo; - } - - public String getSessionId() { - return sessionId; - } - - public void setSessionId(String sessionId) { - this.sessionId = sessionId; - } - - public Map getSyncSourceInfo() { - return syncSourceInfo; - } - - public void setSyncSourceInfo(Map syncSourceInfo) { - this.syncSourceInfo = syncSourceInfo == null ? new HashMap() :syncSourceInfo; - } +@JsonIgnoreProperties(ignoreUnknown = true) +public class VXUgsyncAuditInfo extends VXDataObject implements java.io.Serializable { + private static final long serialVersionUID = 1L; + + @JsonSerialize(using = JsonDateSerializer.class) + private Date eventTime; + + private String userName; + private Long noOfNewUsers; + private Long noOfNewGroups; + private Long noOfModifiedUsers; + private Long noOfModifiedGroups; + private String syncSource; + private String sessionId; + private Map syncSourceInfo; + private VXLdapSyncSourceInfo ldapSyncSourceInfo; + private VXFileSyncSourceInfo fileSyncSourceInfo; + private VXUnixSyncSourceInfo unixSyncSourceInfo; + + public VXUgsyncAuditInfo() { + } + + public Date getEventTime() { + return eventTime; + } + + public void setEventTime(Date eventTime) { + this.eventTime = eventTime; + } + + public String getUserName() { + return userName; + } + + public void setUserName(String userName) { + this.userName = userName; + } + + public Long getNoOfNewUsers() { + return noOfNewUsers; + } + + public void setNoOfNewUsers(Long noOfUsers) { + this.noOfNewUsers = noOfUsers; + } + + public Long getNoOfModifiedUsers() { + return noOfModifiedUsers; + } + + public void setNoOfModifiedUsers(Long noOfModifiedUsers) { + this.noOfModifiedUsers = noOfModifiedUsers; + } + + public Long getNoOfNewGroups() { + return noOfNewGroups; + } + + public void setNoOfNewGroups(Long noOfNewGroups) { + this.noOfNewGroups = noOfNewGroups; + } + + public Long getNoOfModifiedGroups() { + return noOfModifiedGroups; + } + + public void setNoOfModifiedGroups(Long noOfModifiedGroups) { + this.noOfModifiedGroups = noOfModifiedGroups; + } + + public String getSyncSource() { + return syncSource; + } + + public void setSyncSource(String syncSource) { + this.syncSource = syncSource; + } + + public VXLdapSyncSourceInfo getLdapSyncSourceInfo() { + return ldapSyncSourceInfo; + } + + public void setLdapSyncSourceInfo(VXLdapSyncSourceInfo ldapSyncSourceInfo) { + this.ldapSyncSourceInfo = ldapSyncSourceInfo; + } + + public VXFileSyncSourceInfo getFileSyncSourceInfo() { + return fileSyncSourceInfo; + } + + public void setFileSyncSourceInfo(VXFileSyncSourceInfo fileSyncSourceInfo) { + this.fileSyncSourceInfo = fileSyncSourceInfo; + } + + public VXUnixSyncSourceInfo getUnixSyncSourceInfo() { + return unixSyncSourceInfo; + } + + public void setUnixSyncSourceInfo(VXUnixSyncSourceInfo unixSyncSourceInfo) { + this.unixSyncSourceInfo = unixSyncSourceInfo; + } + + public String getSessionId() { + return sessionId; + } + + public void setSessionId(String sessionId) { + this.sessionId = sessionId; + } + + public Map getSyncSourceInfo() { + return syncSourceInfo; + } + + public void setSyncSourceInfo(Map syncSourceInfo) { + this.syncSourceInfo = syncSourceInfo == null ? new HashMap<>() : syncSourceInfo; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/view/VXUgsyncAuditInfoList.java b/security-admin/src/main/java/org/apache/ranger/view/VXUgsyncAuditInfoList.java index 22192085d4..51b9688c0d 100644 --- a/security-admin/src/main/java/org/apache/ranger/view/VXUgsyncAuditInfoList.java +++ b/security-admin/src/main/java/org/apache/ranger/view/VXUgsyncAuditInfoList.java @@ -17,36 +17,35 @@ * under the License. */ - package org.apache.ranger.view; +package org.apache.ranger.view; /** * List wrapper class for VXAccessAudit - * */ -import org.apache.ranger.common.view.VList; - -import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import org.apache.ranger.common.view.VList; import java.util.ArrayList; import java.util.List; -@JsonAutoDetect(getterVisibility=Visibility.NONE, setterVisibility=Visibility.NONE, fieldVisibility=Visibility.ANY) +@JsonAutoDetect(getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE, fieldVisibility = Visibility.ANY) @JsonInclude(JsonInclude.Include.NON_NULL) public class VXUgsyncAuditInfoList extends VList { - private static final long serialVersionUID = 1L; - List vxUgsyncAuditInfoList = new ArrayList(); + private static final long serialVersionUID = 1L; + + List vxUgsyncAuditInfoList = new ArrayList<>(); public VXUgsyncAuditInfoList() { - super(); + super(); } public VXUgsyncAuditInfoList(List objList) { - super(objList); - this.vxUgsyncAuditInfoList = objList; + super(objList); + this.vxUgsyncAuditInfoList = objList; } /** @@ -54,7 +53,7 @@ public VXUgsyncAuditInfoList(List objList) { */ @JsonProperty("vxUgsyncAuditInfoList") public List getVxUgsyncAuditInfoList() { - return vxUgsyncAuditInfoList; + return vxUgsyncAuditInfoList; } /** @@ -63,20 +62,19 @@ public List getVxUgsyncAuditInfoList() { */ @JsonProperty("vxUgsyncAuditInfoList") public void setVxUgsyncAuditInfoList(List vxUgsyncAuditInfoList) { - this.vxUgsyncAuditInfoList = vxUgsyncAuditInfoList; + this.vxUgsyncAuditInfoList = vxUgsyncAuditInfoList; } @Override public int getListSize() { - if (vxUgsyncAuditInfoList != null) { - return vxUgsyncAuditInfoList.size(); - } - return 0; + if (vxUgsyncAuditInfoList != null) { + return vxUgsyncAuditInfoList.size(); + } + return 0; } @Override public List getList() { - return vxUgsyncAuditInfoList; + return vxUgsyncAuditInfoList; } - } diff --git a/security-admin/src/main/java/org/apache/ranger/view/VXUnixSyncSourceInfo.java b/security-admin/src/main/java/org/apache/ranger/view/VXUnixSyncSourceInfo.java index 9313921039..d0c31dd20d 100644 --- a/security-admin/src/main/java/org/apache/ranger/view/VXUnixSyncSourceInfo.java +++ b/security-admin/src/main/java/org/apache/ranger/view/VXUnixSyncSourceInfo.java @@ -17,11 +17,10 @@ * under the License. */ - package org.apache.ranger.view; +package org.apache.ranger.view; /** * UserGroupInfo - * */ import com.fasterxml.jackson.annotation.JsonAutoDetect; @@ -29,126 +28,125 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; -@JsonAutoDetect(getterVisibility=Visibility.NONE, setterVisibility=Visibility.NONE, fieldVisibility=Visibility.ANY) +@JsonAutoDetect(getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE, fieldVisibility = Visibility.ANY) @JsonInclude(JsonInclude.Include.NON_NULL) -@JsonIgnoreProperties(ignoreUnknown=true) -public class VXUnixSyncSourceInfo implements java.io.Serializable { - - private static final long serialVersionUID = 1L; - - private String unixBackend; - private String fileName; - private String syncTime; - private String lastModified; - private String minUserId; - private String minGroupId; - private long totalUsersSynced; - private long totalGroupsSynced; - private long totalUsersDeleted; - private long totalGroupsDeleted; - - public VXUnixSyncSourceInfo() { - } - - public String getFileName() { - return fileName; - } - - public void setFileName(String fileName) { - this.fileName = fileName; - } - - public String getSyncTime() { - return syncTime; - } - - public void setSyncTime(String syncTime) { - this.syncTime = syncTime; - } - - public String getLastModified() { - return lastModified; - } - - public void setLastModified(String lastModified) { - this.lastModified = lastModified; - } - - public String getUnixBackend() { - return unixBackend; - } - - public void setUnixBackend(String unixBackend) { - this.unixBackend = unixBackend; - } - - public String getMinUserId() { - return minUserId; - } - - public void setMinUserId(String minUserId) { - this.minUserId = minUserId; - } - - public String getMinGroupId() { - return minGroupId; - } - - public void setMinGroupId(String minGroupId) { - this.minGroupId = minGroupId; - } - - public long getTotalUsersSynced() { - return totalUsersSynced; - } - - public void setTotalUsersSynced(long totalUsersSynced) { - this.totalUsersSynced = totalUsersSynced; - } - - public long getTotalGroupsSynced() { - return totalGroupsSynced; - } - - public void setTotalGroupsSynced(long totalGroupsSynced) { - this.totalGroupsSynced = totalGroupsSynced; - } - - public long getTotalUsersDeleted() { - return totalUsersDeleted; - } - - public void setTotalUsersDeleted(long totalUsersDeleted) { - this.totalUsersDeleted = totalUsersDeleted; - } - - public long getTotalGroupsDeleted() { - return totalGroupsDeleted; - } - - public void setTotalGroupsDeleted(long totalGroupsDeleted) { - this.totalGroupsDeleted = totalGroupsDeleted; - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - toString(sb); - return sb.toString(); - } - - public StringBuilder toString(StringBuilder sb) { - sb.append("{\"unixBackend\":\"").append(unixBackend); - sb.append("\", \"fileName\":\"").append(fileName); - sb.append("\", \"syncTime\":\"").append(syncTime); - sb.append("\", \"lastModified\":\"").append(lastModified); - sb.append("\", \"minUserId\":\"").append(minUserId); - sb.append("\", \"minGroupId\":\"").append(minGroupId); - sb.append("\", \"totalUsersSynced\":\"").append(totalUsersSynced); - sb.append("\", \"totalGroupsSynced\":\"").append(totalGroupsSynced); - sb.append("\", \"totalUsersDeleted\":\"").append(totalUsersDeleted); - sb.append("\", \"totalGroupsDeleted\":\"").append(totalGroupsDeleted); - sb.append("\"}"); - return sb; - } +@JsonIgnoreProperties(ignoreUnknown = true) +public class VXUnixSyncSourceInfo implements java.io.Serializable { + private static final long serialVersionUID = 1L; + + private String unixBackend; + private String fileName; + private String syncTime; + private String lastModified; + private String minUserId; + private String minGroupId; + private long totalUsersSynced; + private long totalGroupsSynced; + private long totalUsersDeleted; + private long totalGroupsDeleted; + + public VXUnixSyncSourceInfo() { + } + + public String getFileName() { + return fileName; + } + + public void setFileName(String fileName) { + this.fileName = fileName; + } + + public String getSyncTime() { + return syncTime; + } + + public void setSyncTime(String syncTime) { + this.syncTime = syncTime; + } + + public String getLastModified() { + return lastModified; + } + + public void setLastModified(String lastModified) { + this.lastModified = lastModified; + } + + public String getUnixBackend() { + return unixBackend; + } + + public void setUnixBackend(String unixBackend) { + this.unixBackend = unixBackend; + } + + public String getMinUserId() { + return minUserId; + } + + public void setMinUserId(String minUserId) { + this.minUserId = minUserId; + } + + public String getMinGroupId() { + return minGroupId; + } + + public void setMinGroupId(String minGroupId) { + this.minGroupId = minGroupId; + } + + public long getTotalUsersSynced() { + return totalUsersSynced; + } + + public void setTotalUsersSynced(long totalUsersSynced) { + this.totalUsersSynced = totalUsersSynced; + } + + public long getTotalGroupsSynced() { + return totalGroupsSynced; + } + + public void setTotalGroupsSynced(long totalGroupsSynced) { + this.totalGroupsSynced = totalGroupsSynced; + } + + public long getTotalUsersDeleted() { + return totalUsersDeleted; + } + + public void setTotalUsersDeleted(long totalUsersDeleted) { + this.totalUsersDeleted = totalUsersDeleted; + } + + public long getTotalGroupsDeleted() { + return totalGroupsDeleted; + } + + public void setTotalGroupsDeleted(long totalGroupsDeleted) { + this.totalGroupsDeleted = totalGroupsDeleted; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + toString(sb); + return sb.toString(); + } + + public StringBuilder toString(StringBuilder sb) { + sb.append("{\"unixBackend\":\"").append(unixBackend); + sb.append("\", \"fileName\":\"").append(fileName); + sb.append("\", \"syncTime\":\"").append(syncTime); + sb.append("\", \"lastModified\":\"").append(lastModified); + sb.append("\", \"minUserId\":\"").append(minUserId); + sb.append("\", \"minGroupId\":\"").append(minGroupId); + sb.append("\", \"totalUsersSynced\":\"").append(totalUsersSynced); + sb.append("\", \"totalGroupsSynced\":\"").append(totalGroupsSynced); + sb.append("\", \"totalUsersDeleted\":\"").append(totalUsersDeleted); + sb.append("\", \"totalGroupsDeleted\":\"").append(totalGroupsDeleted); + sb.append("\"}"); + return sb; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/view/VXUser.java b/security-admin/src/main/java/org/apache/ranger/view/VXUser.java index da02265023..9899898042 100644 --- a/security-admin/src/main/java/org/apache/ranger/view/VXUser.java +++ b/security-admin/src/main/java/org/apache/ranger/view/VXUser.java @@ -17,327 +17,327 @@ * under the License. */ - package org.apache.ranger.view; +package org.apache.ranger.view; /** * User - * */ -import java.util.Collection; - -import org.apache.ranger.common.AppConstants; -import org.apache.ranger.common.RangerCommonEnums; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; +import org.apache.ranger.common.AppConstants; +import org.apache.ranger.common.RangerCommonEnums; + +import java.util.Collection; -@JsonAutoDetect(getterVisibility=Visibility.NONE, setterVisibility=Visibility.NONE, fieldVisibility=Visibility.ANY) +@JsonAutoDetect(getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE, fieldVisibility = Visibility.ANY) @JsonInclude(JsonInclude.Include.NON_NULL) -@JsonIgnoreProperties(ignoreUnknown=true) +@JsonIgnoreProperties(ignoreUnknown = true) 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 groupIdList; - protected Collection groupNameList; - - protected int status; - protected Integer isVisible; - protected int userSource; - /** - * List of roles for this user - */ - protected Collection userRoleList; - - /** - * Additional store attributes. - * - */ - protected String otherAttributes; - - /** - * Sync Source - */ - protected String syncSource; - - /** - * Default constructor. This will set all the attributes to default value. - */ - public VXUser ( ) { - isVisible = RangerCommonEnums.IS_VISIBLE; - } - - /** - * This method sets the value to the member attribute name. - * You cannot set null to the attribute. - * @param name Value to set member attribute name - */ - public void setName( String name ) { - this.name = name; - } - - /** - * Returns the value for the member attribute name - * @return String - value of member attribute name. - */ - public String getName( ) { - return this.name; - } - - /** - * This method sets the value to the member attribute firstName. - * You cannot set null to the attribute. - * @param firstName Value to set member attribute firstName - */ - public void setFirstName( String firstName ) { - this.firstName = firstName; - } - - /** - * Returns the value for the member attribute firstName - * @return String - value of member attribute firstName. - */ - public String getFirstName( ) { - return this.firstName; - } - - /** - * This method sets the value to the member attribute lastName. - * You cannot set null to the attribute. - * @param lastName Value to set member attribute lastName - */ - public void setLastName( String lastName ) { - this.lastName = lastName; - } - - /** - * Returns the value for the member attribute lastName - * @return String - value of member attribute lastName. - */ - public String getLastName( ) { - return this.lastName; - } - - /** - * This method sets the value to the member attribute emailAddress. - * You cannot set null to the attribute. - * @param emailAddress Value to set member attribute emailAddress - */ - public void setEmailAddress( String emailAddress ) { - this.emailAddress = emailAddress; - } - - /** - * Returns the value for the member attribute emailAddress - * @return String - value of member attribute emailAddress. - */ - public String getEmailAddress( ) { - return this.emailAddress; - } - - /** - * This method sets the value to the member attribute password. - * You cannot set null to the attribute. - * @param password Value to set member attribute password - */ - public void setPassword( String password ) { - this.password = password; - } - - /** - * Returns the value for the member attribute password - * @return String - value of member attribute password. - */ - public String getPassword( ) { - return this.password; - } - - /** - * This method sets the value to the member attribute description. - * You cannot set null to the attribute. - * @param description Value to set member attribute description - */ - public void setDescription( String description ) { - this.description = description; - } - - /** - * Returns the value for the member attribute description - * @return String - value of member attribute description. - */ - public String getDescription( ) { - return this.description; - } - - /** - * This method sets the value to the member attribute credStoreId. - * You cannot set null to the attribute. - * @param credStoreId Value to set member attribute credStoreId - */ - public void setCredStoreId( Long credStoreId ) { - this.credStoreId = credStoreId; - } - - /** - * Returns the value for the member attribute credStoreId - * @return Long - value of member attribute credStoreId. - */ - public Long getCredStoreId( ) { - return this.credStoreId; - } - - /** - * This method sets the value to the member attribute groupIdList. - * You cannot set null to the attribute. - * @param groupIdList Value to set member attribute groupIdList - */ - public void setGroupIdList( Collection groupIdList ) { - this.groupIdList = groupIdList; - } - - /** - * Returns the value for the member attribute groupIdList - * @return Collection - value of member attribute groupIdList. - */ - public Collection getGroupIdList( ) { - return this.groupIdList; - } - - @Override - public int getMyClassType( ) { - return AppConstants.CLASS_TYPE_XA_USER; - } - - - public int getStatus() { - return status; - } - - public void setStatus(Integer status) { - this.status = status; - } - - public Integer getIsVisible() { - return isVisible; - } - - public void setIsVisible(Integer isVisible) { - this.isVisible = isVisible; - } - - public int getUserSource() { - return userSource; - } - - public void setUserSource(int userSource) { - this.userSource = userSource; - } - - /** - * This method sets the value to the member attribute userRoleList. - * You cannot set null to the attribute. - * @param userRoleList Value to set member attribute userRoleList - */ - public void setUserRoleList( Collection userRoleList ) { - this.userRoleList = userRoleList; - } - - /** - * Returns the value for the member attribute userRoleList - * @return Collection - value of member attribute userRoleList. - */ - public Collection getUserRoleList( ) { - return this.userRoleList; - } - - - public Collection getGroupNameList() { - return groupNameList; - } - - public void setGroupNameList(Collection groupNameList) { - this.groupNameList = groupNameList; - } - - /** - * @return {@link String} - additional attributes. - */ - public String getOtherAttributes() { - return otherAttributes; - } - - /** - * This method sets additional attributes. - * @param otherAttributes - */ - public void setOtherAttributes(final String otherAttributes) { - this.otherAttributes = otherAttributes; - } - - /** - * @return {@link String} - sync Source. - */ - public String getSyncSource() { return syncSource; } - - /** - * This method sets additional attributes. - * @param syncSource - */ - public void setSyncSource(String syncSource) { this.syncSource = syncSource; } - - /** - * 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 += "description={" + description + "} "; - str += "credStoreId={" + credStoreId + "} "; - str += "isVisible={" + isVisible + "} "; - str += "groupIdList={" + groupIdList + "} "; - str += "groupNameList={" + groupNameList + "} "; + 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 groupIdList; + protected Collection groupNameList; + + protected int status; + protected Integer isVisible; + protected int userSource; + /** + * List of roles for this user + */ + protected Collection userRoleList; + + /** + * Additional store attributes. + * + */ + protected String otherAttributes; + + /** + * Sync Source + */ + protected String syncSource; + + /** + * Default constructor. This will set all the attributes to default value. + */ + public VXUser() { + isVisible = RangerCommonEnums.IS_VISIBLE; + } + + /** + * Returns the value for the member attribute name + * @return String - value of member attribute name. + */ + public String getName() { + return this.name; + } + + /** + * This method sets the value to the member attribute name. + * You cannot set null to the attribute. + * @param name Value to set member attribute name + */ + public void setName(String name) { + this.name = name; + } + + /** + * Returns the value for the member attribute firstName + * @return String - value of member attribute firstName. + */ + public String getFirstName() { + return this.firstName; + } + + /** + * This method sets the value to the member attribute firstName. + * You cannot set null to the attribute. + * @param firstName Value to set member attribute firstName + */ + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + /** + * Returns the value for the member attribute lastName + * @return String - value of member attribute lastName. + */ + public String getLastName() { + return this.lastName; + } + + /** + * This method sets the value to the member attribute lastName. + * You cannot set null to the attribute. + * @param lastName Value to set member attribute lastName + */ + public void setLastName(String lastName) { + this.lastName = lastName; + } + + /** + * Returns the value for the member attribute emailAddress + * @return String - value of member attribute emailAddress. + */ + public String getEmailAddress() { + return this.emailAddress; + } + + /** + * This method sets the value to the member attribute emailAddress. + * You cannot set null to the attribute. + * @param emailAddress Value to set member attribute emailAddress + */ + public void setEmailAddress(String emailAddress) { + this.emailAddress = emailAddress; + } + + /** + * Returns the value for the member attribute password + * @return String - value of member attribute password. + */ + public String getPassword() { + return this.password; + } + + /** + * This method sets the value to the member attribute password. + * You cannot set null to the attribute. + * @param password Value to set member attribute password + */ + public void setPassword(String password) { + this.password = password; + } + + /** + * Returns the value for the member attribute description + * @return String - value of member attribute description. + */ + public String getDescription() { + return this.description; + } + + /** + * This method sets the value to the member attribute description. + * You cannot set null to the attribute. + * @param description Value to set member attribute description + */ + public void setDescription(String description) { + this.description = description; + } + + /** + * Returns the value for the member attribute credStoreId + * @return Long - value of member attribute credStoreId. + */ + public Long getCredStoreId() { + return this.credStoreId; + } + + /** + * This method sets the value to the member attribute credStoreId. + * You cannot set null to the attribute. + * @param credStoreId Value to set member attribute credStoreId + */ + public void setCredStoreId(Long credStoreId) { + this.credStoreId = credStoreId; + } + + /** + * Returns the value for the member attribute groupIdList + * @return Collection - value of member attribute groupIdList. + */ + public Collection getGroupIdList() { + return this.groupIdList; + } + + /** + * This method sets the value to the member attribute groupIdList. + * You cannot set null to the attribute. + * @param groupIdList Value to set member attribute groupIdList + */ + public void setGroupIdList(Collection groupIdList) { + this.groupIdList = groupIdList; + } + + @Override + public int getMyClassType() { + return AppConstants.CLASS_TYPE_XA_USER; + } + + /** + * 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 += "description={" + description + "} "; + str += "credStoreId={" + credStoreId + "} "; + str += "isVisible={" + isVisible + "} "; + str += "groupIdList={" + groupIdList + "} "; + str += "groupNameList={" + groupNameList + "} "; str += "roleList={" + userRoleList + "} "; - str += "otherAttributes={" + otherAttributes + "} "; - str += "syncSource={" + syncSource + "} "; - str += "}"; - return str; - } + str += "otherAttributes={" + otherAttributes + "} "; + str += "syncSource={" + syncSource + "} "; + str += "}"; + return str; + } + + public int getStatus() { + return status; + } + + public void setStatus(Integer status) { + this.status = status; + } + + public Integer getIsVisible() { + return isVisible; + } + + public void setIsVisible(Integer isVisible) { + this.isVisible = isVisible; + } + + public int getUserSource() { + return userSource; + } + + public void setUserSource(int userSource) { + this.userSource = userSource; + } + + /** + * Returns the value for the member attribute userRoleList + * @return Collection - value of member attribute userRoleList. + */ + public Collection getUserRoleList() { + return this.userRoleList; + } + + /** + * This method sets the value to the member attribute userRoleList. + * You cannot set null to the attribute. + * @param userRoleList Value to set member attribute userRoleList + */ + public void setUserRoleList(Collection userRoleList) { + this.userRoleList = userRoleList; + } + + public Collection getGroupNameList() { + return groupNameList; + } + + public void setGroupNameList(Collection groupNameList) { + this.groupNameList = groupNameList; + } + + /** + * @return {@link String} - additional attributes. + */ + public String getOtherAttributes() { + return otherAttributes; + } + + /** + * This method sets additional attributes. + * @param otherAttributes + */ + public void setOtherAttributes(final String otherAttributes) { + this.otherAttributes = otherAttributes; + } + + /** + * @return {@link String} - sync Source. + */ + public String getSyncSource() { + return syncSource; + } + + /** + * This method sets additional attributes. + * @param syncSource + */ + public void setSyncSource(String syncSource) { + this.syncSource = syncSource; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/view/VXUserGroupInfo.java b/security-admin/src/main/java/org/apache/ranger/view/VXUserGroupInfo.java index ec67981fe9..d265b625ba 100644 --- a/security-admin/src/main/java/org/apache/ranger/view/VXUserGroupInfo.java +++ b/security-admin/src/main/java/org/apache/ranger/view/VXUserGroupInfo.java @@ -17,47 +17,44 @@ * under the License. */ - package org.apache.ranger.view; +package org.apache.ranger.view; /** * UserGroupInfo - * */ -import java.util.List; - import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; -@JsonAutoDetect(getterVisibility=Visibility.NONE, setterVisibility=Visibility.NONE, fieldVisibility=Visibility.ANY) +import java.util.List; + +@JsonAutoDetect(getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE, fieldVisibility = Visibility.ANY) @JsonInclude(JsonInclude.Include.NON_NULL) -@JsonIgnoreProperties(ignoreUnknown=true) -public class VXUserGroupInfo extends VXDataObject implements java.io.Serializable { - - private static final long serialVersionUID = 1L; - - VXUser xuserInfo; - List xgroupInfo; - - public VXUserGroupInfo ( ) { - } - - public VXUser getXuserInfo() { - return xuserInfo; - } - - public void setXuserInfo(VXUser xuserInfo) { - this.xuserInfo = xuserInfo; - } - - public List getXgroupInfo() { - return xgroupInfo; - } - - public void setXgroupInfo(List xgroupInfo) { - this.xgroupInfo = xgroupInfo; - } +@JsonIgnoreProperties(ignoreUnknown = true) +public class VXUserGroupInfo extends VXDataObject implements java.io.Serializable { + private static final long serialVersionUID = 1L; + + VXUser xuserInfo; + List xgroupInfo; + + public VXUserGroupInfo() { + } + + public VXUser getXuserInfo() { + return xuserInfo; + } + + public void setXuserInfo(VXUser xuserInfo) { + this.xuserInfo = xuserInfo; + } + + public List getXgroupInfo() { + return xgroupInfo; + } + public void setXgroupInfo(List xgroupInfo) { + this.xgroupInfo = xgroupInfo; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/view/VXUserList.java b/security-admin/src/main/java/org/apache/ranger/view/VXUserList.java index b1fbdfaed2..b24c006898 100644 --- a/security-admin/src/main/java/org/apache/ranger/view/VXUserList.java +++ b/security-admin/src/main/java/org/apache/ranger/view/VXUserList.java @@ -17,35 +17,35 @@ * under the License. */ - package org.apache.ranger.view; +package org.apache.ranger.view; /** * List wrapper class for VXUser - * */ -import java.util.ArrayList; -import java.util.List; - -import org.apache.ranger.common.view.VList; -import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import org.apache.ranger.common.view.VList; + +import java.util.ArrayList; +import java.util.List; -@JsonAutoDetect(getterVisibility=Visibility.NONE, setterVisibility=Visibility.NONE, fieldVisibility=Visibility.ANY) +@JsonAutoDetect(getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE, fieldVisibility = Visibility.ANY) @JsonInclude(JsonInclude.Include.NON_NULL) public class VXUserList extends VList { - private static final long serialVersionUID = 1L; - List vXUsers = new ArrayList(); + private static final long serialVersionUID = 1L; + + List vXUsers = new ArrayList<>(); public VXUserList() { - super(); + super(); } public VXUserList(List objList) { - super(objList); - this.vXUsers = objList; + super(objList); + this.vXUsers = objList; } /** @@ -53,7 +53,7 @@ public VXUserList(List objList) { */ @JsonProperty("vXUsers") public List getVXUsers() { - return vXUsers; + return vXUsers; } /** @@ -62,20 +62,19 @@ public List getVXUsers() { */ @JsonProperty("vXUsers") public void setVXUsers(List vXUsers) { - this.vXUsers = vXUsers; + this.vXUsers = vXUsers; } @Override public int getListSize() { - if (vXUsers != null) { - return vXUsers.size(); - } - return 0; + if (vXUsers != null) { + return vXUsers.size(); + } + return 0; } @Override public List getList() { - return vXUsers; + return vXUsers; } - } diff --git a/security-admin/src/main/java/org/apache/ranger/view/VXUserPermission.java b/security-admin/src/main/java/org/apache/ranger/view/VXUserPermission.java index 61b5f24a79..e584814bf9 100644 --- a/security-admin/src/main/java/org/apache/ranger/view/VXUserPermission.java +++ b/security-admin/src/main/java/org/apache/ranger/view/VXUserPermission.java @@ -17,145 +17,132 @@ package org.apache.ranger.view; -import org.apache.ranger.common.AppConstants; import com.fasterxml.jackson.annotation.JsonAutoDetect; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; +import org.apache.ranger.common.AppConstants; @JsonAutoDetect(getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE, fieldVisibility = Visibility.ANY) @JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) -public class VXUserPermission extends VXDataObject implements - java.io.Serializable { - - private static final long serialVersionUID = 1L; - - - protected Long userId; - protected Long moduleId; - protected Integer isAllowed; - protected String userName; - protected String moduleName; - protected String loginId; - - - - public VXUserPermission() { - // TODO Auto-generated constructor stub - } - - - /** - * @return the id - */ - public Long getId() { - return id; - } - - /** - * @param id - * the id to set - */ - public void setId(Long id) { - this.id = id; - } - - /** - * @return the userId - */ - public Long getUserId() { - return userId; - } - - /** - * @param userId - * the userId to set - */ - public void setUserId(Long userId) { - this.userId = userId; - } - - /** - * @return the moduleId - */ - public Long getModuleId() { - return moduleId; - } - - /** - * @param moduleId - * the moduleId to set - */ - public void setModuleId(Long moduleId) { - this.moduleId = moduleId; - } - - /** - * @return the isAllowed - */ - public Integer getIsAllowed() { - return isAllowed; - } - - /** - * @param isAllowed - * the isAllowed to set - */ - public void setIsAllowed(Integer isAllowed) { - this.isAllowed = isAllowed; - } - - /** - * @return the userName - */ - public String getUserName() { - return userName; - } - - /** - * @param userName the userName to set - */ - public void setUserName(String userName) { - this.userName = userName; - } - - public String getModuleName() { - return moduleName; - } - - public void setModuleName(String moduleName) { - this.moduleName = moduleName; - } - - public String getLoginId() { - return loginId; - } - - - public void setLoginId(String loginId) { - this.loginId = loginId; - } - - - @Override - public int getMyClassType() { - return AppConstants.CLASS_TYPE_RANGER_USER_PERMISSION; - } - - @Override - public String toString() { - - String str = "VXUserPermission={"; - str += super.toString(); - str += "id={" + id + "} "; - str += "userId={" + userId + "} "; - str += "moduleId={" + moduleId + "} "; - str += "isAllowed={" + isAllowed + "} "; - str += "moduleName={" + moduleName + "} "; - str += "loginId={" + loginId + "} "; - str += "}"; - - return str; - } +public class VXUserPermission extends VXDataObject implements java.io.Serializable { + private static final long serialVersionUID = 1L; + + protected Long userId; + protected Long moduleId; + protected Integer isAllowed; + protected String userName; + protected String moduleName; + protected String loginId; + + public VXUserPermission() { + // TODO Auto-generated constructor stub + } + + /** + * @return the id + */ + public Long getId() { + return id; + } + + /** + * @param id the id to set + */ + public void setId(Long id) { + this.id = id; + } + + @Override + public int getMyClassType() { + return AppConstants.CLASS_TYPE_RANGER_USER_PERMISSION; + } + + @Override + public String toString() { + String str = "VXUserPermission={"; + str += super.toString(); + str += "id={" + id + "} "; + str += "userId={" + userId + "} "; + str += "moduleId={" + moduleId + "} "; + str += "isAllowed={" + isAllowed + "} "; + str += "moduleName={" + moduleName + "} "; + str += "loginId={" + loginId + "} "; + str += "}"; + + return str; + } + + /** + * @return the userId + */ + public Long getUserId() { + return userId; + } + + /** + * @param userId the userId to set + */ + public void setUserId(Long userId) { + this.userId = userId; + } + + /** + * @return the moduleId + */ + public Long getModuleId() { + return moduleId; + } + + /** + * @param moduleId the moduleId to set + */ + public void setModuleId(Long moduleId) { + this.moduleId = moduleId; + } + + /** + * @return the isAllowed + */ + public Integer getIsAllowed() { + return isAllowed; + } + + /** + * @param isAllowed the isAllowed to set + */ + public void setIsAllowed(Integer isAllowed) { + this.isAllowed = isAllowed; + } + + /** + * @return the userName + */ + public String getUserName() { + return userName; + } + + /** + * @param userName the userName to set + */ + public void setUserName(String userName) { + this.userName = userName; + } + + public String getModuleName() { + return moduleName; + } + + public void setModuleName(String moduleName) { + this.moduleName = moduleName; + } + + public String getLoginId() { + return loginId; + } + + public void setLoginId(String loginId) { + this.loginId = loginId; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/view/VXUserPermissionList.java b/security-admin/src/main/java/org/apache/ranger/view/VXUserPermissionList.java index a72cb01380..0d37b12463 100644 --- a/security-admin/src/main/java/org/apache/ranger/view/VXUserPermissionList.java +++ b/security-admin/src/main/java/org/apache/ranger/view/VXUserPermissionList.java @@ -17,58 +17,57 @@ package org.apache.ranger.view; -import java.util.ArrayList; -import java.util.List; - -import org.apache.ranger.common.view.VList; -import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import org.apache.ranger.common.view.VList; + +import java.util.ArrayList; +import java.util.List; @JsonAutoDetect(getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE, fieldVisibility = Visibility.ANY) @JsonInclude(JsonInclude.Include.NON_NULL) public class VXUserPermissionList extends VList { + private static final long serialVersionUID = 1L; - private static final long serialVersionUID = 1L; - - List vXUserPermission = new ArrayList(); + List vXUserPermission = new ArrayList<>(); - public VXUserPermissionList() { - super(); - } + public VXUserPermissionList() { + super(); + } - public VXUserPermissionList(List objList) { - super(objList); - this.vXUserPermission = objList; - } + public VXUserPermissionList(List objList) { + super(objList); + this.vXUserPermission = objList; + } - /** - * @return the vXModuleDef - */ - @JsonProperty("vXUserPermission") - public List getvXModuleDef() { - return vXUserPermission; - } + /** + * @return the vXModuleDef + */ + @JsonProperty("vXUserPermission") + public List getvXModuleDef() { + return vXUserPermission; + } - /** - * @param vXModuleDef the vXModuleDef to set - */ - @JsonProperty("vXUserPermission") - public void setvXModuleDef(List vXModuleDef) { - this.vXUserPermission = vXModuleDef; - } + /** + * @param vXModuleDef the vXModuleDef to set + */ + @JsonProperty("vXUserPermission") + public void setvXModuleDef(List vXModuleDef) { + this.vXUserPermission = vXModuleDef; + } - @Override - public int getListSize() { - if (vXUserPermission != null) { - return vXUserPermission.size(); - } - return 0; - } + @Override + public int getListSize() { + if (vXUserPermission != null) { + return vXUserPermission.size(); + } + return 0; + } - @Override - public List getList() { - return vXUserPermission; - } + @Override + public List getList() { + return vXUserPermission; + } } From 942b3ce1ba11f84233edc7d609d62b7ed2121388 Mon Sep 17 00:00:00 2001 From: PradeeP AgrawaL Date: Sat, 11 Jan 2025 11:17:35 +0530 Subject: [PATCH 12/15] RANGER-5061: checkstyle compliance updates - security-admin org.apache.ranger.service (#503) --- .../AbstractAuditedResourceService.java | 396 ++--- .../service/AbstractBaseResourceService.java | 1490 ++++++++--------- .../ranger/service/AuthSessionService.java | 266 ++- .../ranger/service/PublicAPIServiceBase.java | 35 +- .../ranger/service/RangerAuditFields.java | 28 +- .../service/RangerAuditedModelService.java | 404 ++--- .../service/RangerBaseModelService.java | 847 +++++----- .../ranger/service/RangerDataHistService.java | 239 ++- .../service/RangerGdsBaseModelService.java | 18 +- .../RangerGdsDataShareInDatasetService.java | 162 +- .../service/RangerGdsDataShareService.java | 189 +-- .../RangerGdsDatasetInProjectService.java | 146 +- .../service/RangerGdsDatasetService.java | 123 +- .../service/RangerGdsProjectService.java | 101 +- .../RangerGdsSharedResourceService.java | 175 +- .../service/RangerPluginInfoService.java | 521 +++--- .../service/RangerPolicyLabelsService.java | 57 +- .../ranger/service/RangerPolicyService.java | 70 +- .../service/RangerPolicyServiceBase.java | 455 +++-- .../RangerPolicyWithAssignedIdService.java | 74 +- .../ranger/service/RangerRoleService.java | 127 +- .../ranger/service/RangerRoleServiceBase.java | 42 +- .../RangerSecurityZoneServiceBase.java | 63 +- .../RangerSecurityZoneServiceService.java | 243 ++- .../service/RangerServiceDefService.java | 141 +- .../service/RangerServiceDefServiceBase.java | 1490 +++++++++-------- ...RangerServiceDefWithAssignedIdService.java | 47 +- .../service/RangerServiceResourceService.java | 80 +- .../RangerServiceResourceServiceBase.java | 121 +- .../RangerServiceResourceWithTagsService.java | 123 +- ...gerServiceResourceWithTagsServiceBase.java | 59 +- .../ranger/service/RangerServiceService.java | 311 ++-- .../service/RangerServiceServiceBase.java | 293 ++-- .../RangerServiceWithAssignedIdService.java | 80 +- .../ranger/service/RangerTagDefService.java | 145 +- .../service/RangerTagDefServiceBase.java | 212 +-- .../service/RangerTagResourceMapService.java | 248 ++- .../RangerTagResourceMapServiceBase.java | 64 +- .../ranger/service/RangerTagService.java | 253 ++- .../ranger/service/RangerTagServiceBase.java | 224 ++- .../service/RangerTransactionService.java | 73 +- .../ranger/service/RangerTrxLogV2Service.java | 452 +++-- .../apache/ranger/service/UserService.java | 554 +++--- .../ranger/service/UserServiceBase.java | 65 +- .../ranger/service/XAccessAuditService.java | 379 ++--- .../service/XAccessAuditServiceBase.java | 155 +- .../apache/ranger/service/XAssetService.java | 385 +++-- .../ranger/service/XAssetServiceBase.java | 123 +- .../ranger/service/XAuditMapService.java | 142 +- .../ranger/service/XAuditMapServiceBase.java | 122 +- .../service/XCredentialStoreService.java | 24 +- .../service/XCredentialStoreServiceBase.java | 79 +- .../ranger/service/XGroupGroupService.java | 24 +- .../service/XGroupGroupServiceBase.java | 83 +- .../service/XGroupPermissionService.java | 160 +- .../service/XGroupPermissionServiceBase.java | 77 +- .../apache/ranger/service/XGroupService.java | 266 +-- .../ranger/service/XGroupServiceBase.java | 169 +- .../ranger/service/XGroupUserService.java | 401 +++-- .../ranger/service/XGroupUserServiceBase.java | 147 +- .../ranger/service/XModuleDefService.java | 327 ++-- .../ranger/service/XModuleDefServiceBase.java | 111 +- .../ranger/service/XPermMapService.java | 235 +-- .../ranger/service/XPermMapServiceBase.java | 197 ++- .../service/XPolicyExportAuditService.java | 55 +- .../XPolicyExportAuditServiceBase.java | 121 +- .../apache/ranger/service/XPolicyService.java | 1393 ++++++++------- .../ranger/service/XPortalUserService.java | 318 ++-- .../service/XPortalUserServiceBase.java | 130 +- .../ranger/service/XRepositoryService.java | 183 +- .../ranger/service/XResourceService.java | 719 ++++---- .../ranger/service/XResourceServiceBase.java | 231 ++- .../service/XUgsyncAuditInfoService.java | 223 ++- .../service/XUgsyncAuditInfoServiceBase.java | 66 +- .../service/XUserPermissionService.java | 157 +- .../service/XUserPermissionServiceBase.java | 183 +- .../apache/ranger/service/XUserService.java | 483 +++--- .../ranger/service/XUserServiceBase.java | 179 +- .../service/filter/RangerRESTAPIFilter.java | 459 +++-- 79 files changed, 9665 insertions(+), 10147 deletions(-) diff --git a/security-admin/src/main/java/org/apache/ranger/service/AbstractAuditedResourceService.java b/security-admin/src/main/java/org/apache/ranger/service/AbstractAuditedResourceService.java index b39b83293c..fdda33f335 100644 --- a/security-admin/src/main/java/org/apache/ranger/service/AbstractAuditedResourceService.java +++ b/security-admin/src/main/java/org/apache/ranger/service/AbstractAuditedResourceService.java @@ -17,7 +17,7 @@ * under the License. */ - package org.apache.ranger.service; +package org.apache.ranger.service; import org.apache.commons.lang3.StringUtils; import org.apache.ranger.common.JSONUtil; @@ -35,203 +35,211 @@ import org.springframework.beans.factory.annotation.Autowired; import javax.annotation.PostConstruct; -import java.util.*; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; import static org.apache.ranger.service.RangerBaseModelService.OPERATION_CREATE_CONTEXT; import static org.apache.ranger.service.RangerBaseModelService.OPERATION_DELETE_CONTEXT; import static org.apache.ranger.service.RangerBaseModelService.OPERATION_UPDATE_CONTEXT; public abstract class AbstractAuditedResourceService extends AbstractBaseResourceService { - protected static final Logger logger = LoggerFactory.getLogger(AbstractAuditedResourceService.class); - - @Autowired - JSONUtil jsonUtil; - - @Autowired - RangerEnumUtil xaEnumUtil; - - protected final Map trxLogAttrs = new HashMap<>(); - protected final String hiddenPasswordString; - private final int classType; - private final int parentClassType; - private final List objNameAttrs = new ArrayList<>(); - - protected AbstractAuditedResourceService(int classType) { - this(classType, -1); - } - - protected AbstractAuditedResourceService(int classType, int parentClassType) { - this.classType = classType; - this.parentClassType = parentClassType; - this.hiddenPasswordString = PropertiesUtil.getProperty("ranger.password.hidden", "*****"); - } - - @PostConstruct - public void init() { - for (VTrxLogAttr vTrxLog : trxLogAttrs.values()) { - if (vTrxLog.isObjName()) { - objNameAttrs.add(vTrxLog); - } - } - - if (objNameAttrs.isEmpty()) { - objNameAttrs.add(new VTrxLogAttr("name", "Name", false, true)); - } - } - - public void createTransactionLog(XXTrxLogV2 trxLog) { - bizUtil.createTrxLog(Collections.singletonList(trxLog)); - } - - public void createTransactionLog(XXTrxLogV2 trxLog, String attrName, String oldValue, String newValue) { - try { - ObjectChangeInfo objChangeInfo = new ObjectChangeInfo(); - if("Password".equalsIgnoreCase(attrName)) { - oldValue = hiddenPasswordString; - newValue = hiddenPasswordString; - } - - objChangeInfo.addAttribute(attrName, oldValue, newValue); - - trxLog.setChangeInfo(JsonUtilsV2.objToJson(objChangeInfo)); - } catch (Exception excp) { - logger.warn("failed to convert attribute change info to json"); - } - - bizUtil.createTrxLog(Collections.singletonList(trxLog)); - } - - public void createTransactionLog(V obj, V oldObj, int action, Long userId) { - List trxLogList = getTransactionLog(obj, oldObj, action); - - if (trxLogList != null) { - for (XXTrxLogV2 trxLog : trxLogList) { - trxLog.setAddedByUserId(userId); - } - - bizUtil.createTrxLog(trxLogList); - } - - createTransactionLog(obj, null, action); - } - - public void createTransactionLog(V obj, V oldObj, int action) { - List trxLogList = getTransactionLog(obj, oldObj, action); - - if (trxLogList != null) { - bizUtil.createTrxLog(trxLogList); - } - } - - public List getTransactionLog(V obj, V oldObj, int action) { - if (obj == null || (action == OPERATION_UPDATE_CONTEXT && oldObj == null)) { - return null; - } - - List trxLogList = new ArrayList<>(); - - try { - ObjectChangeInfo objChangeInfo = new ObjectChangeInfo(); - - for (VTrxLogAttr trxLog : trxLogAttrs.values()) { - processFieldToCreateTrxLog(trxLog, obj, oldObj, action, objChangeInfo); - } - - if(objChangeInfo.getAttributes() != null && objChangeInfo.getAttributes().size() > 0) { - for(AttributeChangeInfo changeInfo : objChangeInfo.getAttributes()) { - if("Password".equalsIgnoreCase(changeInfo.getAttributeName())) { - changeInfo.setNewValue(hiddenPasswordString); - changeInfo.setOldValue(hiddenPasswordString); - } - } - trxLogList.add(new XXTrxLogV2(classType, obj.getId(), getObjectName(obj), getParentObjectType(obj, oldObj), getParentObjectId(obj, oldObj), getParentObjectName(obj, oldObj), toActionString(action), JsonUtilsV2.objToJson(objChangeInfo))); - } - } catch (Exception e) { - logger.warn("failed to get transaction log for object: type=" + obj.getClass().getName() + ", id=" + obj.getId(), e); - } - - return trxLogList; - } - - public String getObjectName(V obj) { - String ret = null; - - for (VTrxLogAttr attr : objNameAttrs) { - ret = attr.getAttrValue(obj, xaEnumUtil); - - if (StringUtils.isNotBlank(ret)) { - break; - } - } - - return ret; - } - - public int getParentObjectType(V obj, V oldObj) { - return parentClassType; - } - - public String getParentObjectName(V obj, V oldObj) { - return null; - } - - public Long getParentObjectId(V obj, V oldObj) { - return null; - } - - public boolean skipTrxLogForAttribute(V obj, V oldObj, VTrxLogAttr trxLogAttr) { - return false; - } - - public String getTrxLogAttrValue(V obj, VTrxLogAttr trxLogAttr) { - return trxLogAttr.getAttrValue(obj, xaEnumUtil); - } - - private void processFieldToCreateTrxLog(VTrxLogAttr trxLogAttr, V obj, V oldObj, int action, ObjectChangeInfo objChangeInfo) { - if (skipTrxLogForAttribute(obj, oldObj, trxLogAttr)) { - return; - } - - String value = getTrxLogAttrValue(obj, trxLogAttr); - - if ((action == OPERATION_CREATE_CONTEXT || action == OPERATION_DELETE_CONTEXT) && StringUtils.isBlank(value)) { - return; - } - - final String prevValue; - final String newValue; - - if (action == OPERATION_CREATE_CONTEXT) { - prevValue = null; - newValue = value; - } else if (action == OPERATION_DELETE_CONTEXT) { - prevValue = value; - newValue = null; - } else if (action == OPERATION_UPDATE_CONTEXT) { - prevValue = getTrxLogAttrValue(oldObj, trxLogAttr); - newValue = value; - } else { - prevValue = null; - newValue = null; - } - - if ((StringUtils.isEmpty(prevValue) && StringUtils.isEmpty(newValue)) || StringUtils.equals(prevValue, newValue)) { - return; - } - - objChangeInfo.addAttribute(trxLogAttr.getAttribUserFriendlyName(), prevValue, newValue); - } - - private String toActionString(int action) { - switch (action) { - case OPERATION_CREATE_CONTEXT: - return "create"; - case OPERATION_UPDATE_CONTEXT: - return "update"; - case OPERATION_DELETE_CONTEXT: - return "delete"; - } - - return "unknown"; - } + protected static final Logger logger = LoggerFactory.getLogger(AbstractAuditedResourceService.class); + + protected final Map trxLogAttrs = new HashMap<>(); + protected final String hiddenPasswordString; + + private final int classType; + private final int parentClassType; + private final List objNameAttrs = new ArrayList<>(); + + @Autowired + JSONUtil jsonUtil; + + @Autowired + RangerEnumUtil xaEnumUtil; + + protected AbstractAuditedResourceService(int classType) { + this(classType, -1); + } + + protected AbstractAuditedResourceService(int classType, int parentClassType) { + this.classType = classType; + this.parentClassType = parentClassType; + this.hiddenPasswordString = PropertiesUtil.getProperty("ranger.password.hidden", "*****"); + } + + @PostConstruct + public void init() { + for (VTrxLogAttr vTrxLog : trxLogAttrs.values()) { + if (vTrxLog.isObjName()) { + objNameAttrs.add(vTrxLog); + } + } + + if (objNameAttrs.isEmpty()) { + objNameAttrs.add(new VTrxLogAttr("name", "Name", false, true)); + } + } + + public void createTransactionLog(XXTrxLogV2 trxLog) { + bizUtil.createTrxLog(Collections.singletonList(trxLog)); + } + + public void createTransactionLog(XXTrxLogV2 trxLog, String attrName, String oldValue, String newValue) { + try { + ObjectChangeInfo objChangeInfo = new ObjectChangeInfo(); + + if ("Password".equalsIgnoreCase(attrName)) { + oldValue = hiddenPasswordString; + newValue = hiddenPasswordString; + } + + objChangeInfo.addAttribute(attrName, oldValue, newValue); + + trxLog.setChangeInfo(JsonUtilsV2.objToJson(objChangeInfo)); + } catch (Exception excp) { + logger.warn("failed to convert attribute change info to json"); + } + + bizUtil.createTrxLog(Collections.singletonList(trxLog)); + } + + public void createTransactionLog(V obj, V oldObj, int action, Long userId) { + List trxLogList = getTransactionLog(obj, oldObj, action); + + if (trxLogList != null) { + for (XXTrxLogV2 trxLog : trxLogList) { + trxLog.setAddedByUserId(userId); + } + + bizUtil.createTrxLog(trxLogList); + } + + createTransactionLog(obj, null, action); + } + + public void createTransactionLog(V obj, V oldObj, int action) { + List trxLogList = getTransactionLog(obj, oldObj, action); + + if (trxLogList != null) { + bizUtil.createTrxLog(trxLogList); + } + } + + public List getTransactionLog(V obj, V oldObj, int action) { + if (obj == null || (action == OPERATION_UPDATE_CONTEXT && oldObj == null)) { + return null; + } + + List trxLogList = new ArrayList<>(); + + try { + ObjectChangeInfo objChangeInfo = new ObjectChangeInfo(); + + for (VTrxLogAttr trxLog : trxLogAttrs.values()) { + processFieldToCreateTrxLog(trxLog, obj, oldObj, action, objChangeInfo); + } + + if (objChangeInfo.getAttributes() != null && !objChangeInfo.getAttributes().isEmpty()) { + for (AttributeChangeInfo changeInfo : objChangeInfo.getAttributes()) { + if ("Password".equalsIgnoreCase(changeInfo.getAttributeName())) { + changeInfo.setNewValue(hiddenPasswordString); + changeInfo.setOldValue(hiddenPasswordString); + } + } + + trxLogList.add(new XXTrxLogV2(classType, obj.getId(), getObjectName(obj), getParentObjectType(obj, oldObj), getParentObjectId(obj, oldObj), getParentObjectName(obj, oldObj), toActionString(action), JsonUtilsV2.objToJson(objChangeInfo))); + } + } catch (Exception e) { + logger.warn("failed to get transaction log for object: type={}, id={}", obj.getClass().getName(), obj.getId(), e); + } + + return trxLogList; + } + + public String getObjectName(V obj) { + String ret = null; + + for (VTrxLogAttr attr : objNameAttrs) { + ret = attr.getAttrValue(obj, xaEnumUtil); + + if (StringUtils.isNotBlank(ret)) { + break; + } + } + + return ret; + } + + public int getParentObjectType(V obj, V oldObj) { + return parentClassType; + } + + public String getParentObjectName(V obj, V oldObj) { + return null; + } + + public Long getParentObjectId(V obj, V oldObj) { + return null; + } + + public boolean skipTrxLogForAttribute(V obj, V oldObj, VTrxLogAttr trxLogAttr) { + return false; + } + + public String getTrxLogAttrValue(V obj, VTrxLogAttr trxLogAttr) { + return trxLogAttr.getAttrValue(obj, xaEnumUtil); + } + + private void processFieldToCreateTrxLog(VTrxLogAttr trxLogAttr, V obj, V oldObj, int action, ObjectChangeInfo objChangeInfo) { + if (skipTrxLogForAttribute(obj, oldObj, trxLogAttr)) { + return; + } + + String value = getTrxLogAttrValue(obj, trxLogAttr); + + if ((action == OPERATION_CREATE_CONTEXT || action == OPERATION_DELETE_CONTEXT) && StringUtils.isBlank(value)) { + return; + } + + final String prevValue; + final String newValue; + + if (action == OPERATION_CREATE_CONTEXT) { + prevValue = null; + newValue = value; + } else if (action == OPERATION_DELETE_CONTEXT) { + prevValue = value; + newValue = null; + } else if (action == OPERATION_UPDATE_CONTEXT) { + prevValue = getTrxLogAttrValue(oldObj, trxLogAttr); + newValue = value; + } else { + prevValue = null; + newValue = null; + } + + if ((StringUtils.isEmpty(prevValue) && StringUtils.isEmpty(newValue)) || StringUtils.equals(prevValue, newValue)) { + return; + } + + objChangeInfo.addAttribute(trxLogAttr.getAttribUserFriendlyName(), prevValue, newValue); + } + + private String toActionString(int action) { + switch (action) { + case OPERATION_CREATE_CONTEXT: + return "create"; + case OPERATION_UPDATE_CONTEXT: + return "update"; + case OPERATION_DELETE_CONTEXT: + return "delete"; + } + + return "unknown"; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/service/AbstractBaseResourceService.java b/security-admin/src/main/java/org/apache/ranger/service/AbstractBaseResourceService.java index 020e1dff51..4b6c78a612 100644 --- a/security-admin/src/main/java/org/apache/ranger/service/AbstractBaseResourceService.java +++ b/security-admin/src/main/java/org/apache/ranger/service/AbstractBaseResourceService.java @@ -17,27 +17,7 @@ * under the License. */ - package org.apache.ranger.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 javax.servlet.http.HttpServletResponse; +package org.apache.ranger.service; import org.apache.ranger.biz.RangerBizUtil; import org.apache.ranger.common.ContextUtil; @@ -66,776 +46,708 @@ import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; +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 javax.servlet.http.HttpServletResponse; + +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 static org.apache.ranger.service.RangerBaseModelService.OPERATION_CREATE_CONTEXT; import static org.apache.ranger.service.RangerBaseModelService.OPERATION_UPDATE_CONTEXT; public abstract class AbstractBaseResourceService { - protected static final Logger logger = LoggerFactory.getLogger(AbstractBaseResourceService.class); - - protected static final Map, String> tEntityValueMap = new HashMap<>(); - - protected final Class tEntityClass; - protected final Class tViewClass; - protected final String className; - protected final String viewClassName; - protected final String countQueryStr; - protected final String queryStr; - protected final String distinctCountQueryStr; - protected final String distinctQueryStr; - - public final List sortFields = new ArrayList<>(); - public final List searchFields = new ArrayList<>(); - - static { - tEntityValueMap.put(XXAuthSession.class, "Auth Session"); - tEntityValueMap.put(XXDBBase.class, "Base"); - } - - @Autowired - BaseDao entityDao; - - @Autowired - StringUtil stringUtil; - - @Autowired - protected RangerDaoManager daoManager; - - @Autowired - protected SearchUtil searchUtil; - - @Autowired - protected RESTErrorUtil restErrorUtil; - - @Autowired - RangerDomainObjectSecurityHandler objectSecurityHandler; - - @Autowired - RangerBizUtil bizUtil; - - @Autowired - RangerConfigUtil 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); - - 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("org.apache.ranger.entity.M")){ - // return className.substring(14); - // } - // return className; - } - - protected BaseDao getDao() { - if (entityDao == null) { - throw new NullPointerException("entityDao is not injected by Spring!"); - } - 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; - } - - /** - * constructor - */ - @SuppressWarnings("unchecked") - public AbstractBaseResourceService() { - - Class klass = getClass(); - ParameterizedType genericSuperclass = (ParameterizedType) klass - .getGenericSuperclass(); - TypeVariable> var[] = klass.getTypeParameters(); - - if (genericSuperclass.getActualTypeArguments()[0] instanceof Class) { - tEntityClass = (Class) genericSuperclass - .getActualTypeArguments()[0]; - tViewClass = (Class) genericSuperclass.getActualTypeArguments()[1]; - } else if (var.length > 0) { - tEntityClass = (Class) var[0].getBounds()[0]; - tViewClass = (Class) var[1].getBounds()[0]; - } else { - tEntityClass = null; - tViewClass = null; - - logger.error("Cannot find class for template", new Throwable()); - } - if (tEntityClass != null) { - className = tEntityClass.getName(); - } else { - className = null; - } - - if (tViewClass != null) { - viewClassName = tViewClass.getName(); - } else { - viewClassName = null; - } - - // Get total count of the rows which meet the search criteria - countQueryStr = "SELECT COUNT(obj) FROM " + className - + " obj "; - queryStr = "SELECT obj FROM " + className + " obj "; - - distinctCountQueryStr = "SELECT COUNT(distinct obj.id) FROM " - + className + " obj "; - distinctQueryStr = "SELECT distinct obj FROM " + className + " obj "; - sortFields.add(new SortField("id", "obj.id",true,SORT_ORDER.ASC)); - } - - // ---------------------------------------------------------------------------------- - // 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()); - } - - 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 404 with DATA_NOT_FOUND as the error message - throw restErrorUtil.createRESTException(getResourceName() - + " not found", MessageEnums.DATA_NOT_FOUND, id, null, - "preRead: " + id + " not found.",HttpServletResponse.SC_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 - 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); - return mapEntityToViewBean(viewBean, resource); - } - - 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() - && !"null".equalsIgnoreCase(tUser.getPublicScreenName().trim())) { - viewBean.setOwner(tUser.getPublicScreenName()); - } else { - if (tUser.getFirstName() != null - && !tUser.getFirstName().trim().isEmpty() - && !"null".equalsIgnoreCase(tUser.getFirstName().trim())) { - if (tUser.getLastName() != null - && !tUser.getLastName().trim().isEmpty() - && !"null".equalsIgnoreCase(tUser.getLastName().trim())) { - 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() - && !"null".equalsIgnoreCase(tUser.getPublicScreenName().trim())) { - viewBean.setUpdatedBy(tUser.getPublicScreenName()); - } else { - if (tUser.getFirstName() != null - && !tUser.getFirstName().trim().isEmpty() - && !"null".equalsIgnoreCase(tUser.getFirstName().trim())) { - if (tUser.getLastName() != null - && !tUser.getLastName().trim().isEmpty() - && !"null".equalsIgnoreCase(tUser.getLastName().trim())) { - 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 searchFieldList, - boolean isCountQuery) { -// EntityManager em = entityDao != null ? entityDao.getEntityManager() : daoManager.getEntityManager(); - EntityManager em = getDao().getEntityManager(); - - Query query = searchUtil.createSearchQuery(em, searchString, sortString, - searchCriteria, searchFieldList, false, - isCountQuery); - return query; - } - - protected long getCountForSearchQuery(SearchCriteria searchCriteria, - List 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 searchFieldList) { - long count = getCountForSearchQuery(searchCriteria, searchFieldList); - - VXLong vXLong = new VXLong(); - vXLong.setValue(count); - return vXLong; - } - - protected List searchResources(SearchCriteria searchCriteria, - List searchFieldList, List 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 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 searchFieldList) { - EntityManager em = getDao().getEntityManager(); - CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder(); - CriteriaQuery criteria = criteriaBuilder.createQuery(Long.class); - - Root from = criteria.from(tEntityClass); - Expression 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 countQuery = em.createQuery(criteria); - long count = getDao().executeCountQueryInSecurityContext(tEntityClass, - countQuery); - - VXLong vXLong = new VXLong(); - vXLong.setValue(count); - return vXLong; - } - - protected List searchResourcesUsingCriteria( - SearchCriteria searchCriteria, List searchFieldList, - List sortFieldList, VList vList) { - // boolean filterEnabled = getDao().enableVisiblityFilters(tClass, - // true); - - EntityManager em = getDao().getEntityManager(); - CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder(); - CriteriaQuery criteria = criteriaBuilder.createQuery(); - Root 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 countExpression = criteriaBuilder.count(from - .get("id")); - criteria.select(countExpression); - TypedQuery 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 typedQuery = em.createQuery(criteria); - searchUtil.updateQueryPageSize(typedQuery, searchCriteria); - - List 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 paramList, - List searchFields, CriteriaBuilder cb, - Root from) { - Predicate userConditions = cb.conjunction(); - - for (SearchField searchField : searchFields) { - if (paramList.containsKey(searchField.getClientFieldName())) { - Path 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 tableFieldWithLowerExpr = cb - .lower(tableField.as(String.class)); - - if (searchField.getSearchType() == SearchField.SEARCH_TYPE.FULL) { - Expression literal = cb.lower(cb - .literal(strFieldValue)); - userConditions = cb.and(userConditions, - cb.equal(tableFieldWithLowerExpr, literal)); - } else { - Expression 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 intValueList = (Collection) 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 from, SearchCriteria sc) { - return null; - } - - public void setSortClause(SearchCriteria searchCriteria, - List sortFields, CriteriaBuilder criteriaBuilder, - CriteriaQuery criteria, Root 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 && "desc".equalsIgnoreCase(sortType)) { - criteria.orderBy(criteriaBuilder.desc(from.get(sortByField))); - } else { - criteria.orderBy(criteriaBuilder.asc(from.get(sortByField))); - } - - } - } - - public Map convertVListToVMap(List vObjList) { - Map ret = new HashMap(); - if (vObjList == null) { - return ret; - } - for (V vObj : vObjList) { - ret.put(vObj.getId(), vObj); - } - return ret; - } + protected static final Logger logger = LoggerFactory.getLogger(AbstractBaseResourceService.class); + + protected static final Map, String> tEntityValueMap = new HashMap<>(); + + public final List sortFields = new ArrayList<>(); + public final List searchFields = new ArrayList<>(); + + protected final Class tEntityClass; + protected final Class tViewClass; + protected final String className; + protected final String viewClassName; + protected final String countQueryStr; + protected final String queryStr; + protected final String distinctCountQueryStr; + protected final String distinctQueryStr; + + @Autowired + protected RangerDaoManager daoManager; + + @Autowired + protected SearchUtil searchUtil; + + @Autowired + protected RESTErrorUtil restErrorUtil; + + @Autowired + BaseDao entityDao; + + @Autowired + StringUtil stringUtil; + + @Autowired + RangerDomainObjectSecurityHandler objectSecurityHandler; + + @Autowired + RangerBizUtil bizUtil; + + @Autowired + RangerConfigUtil msConfigUtil; + + @SuppressWarnings("unchecked") + public AbstractBaseResourceService() { + Class klass = getClass(); + ParameterizedType genericSuperclass = (ParameterizedType) klass.getGenericSuperclass(); + TypeVariable>[] var = klass.getTypeParameters(); + + if (genericSuperclass.getActualTypeArguments()[0] instanceof Class) { + tEntityClass = (Class) genericSuperclass.getActualTypeArguments()[0]; + tViewClass = (Class) genericSuperclass.getActualTypeArguments()[1]; + } else if (var.length > 0) { + tEntityClass = (Class) var[0].getBounds()[0]; + tViewClass = (Class) var[1].getBounds()[0]; + } else { + tEntityClass = null; + tViewClass = null; + + logger.error("Cannot find class for template", new Throwable()); + } + + if (tEntityClass != null) { + className = tEntityClass.getName(); + } else { + className = null; + } + + if (tViewClass != null) { + viewClassName = tViewClass.getName(); + } else { + viewClassName = null; + } + + // Get total count of the rows which meet the search criteria + countQueryStr = "SELECT COUNT(obj) FROM " + className + " obj "; + queryStr = "SELECT obj FROM " + className + " obj "; + distinctCountQueryStr = "SELECT COUNT(distinct obj.id) FROM " + className + " obj "; + distinctQueryStr = "SELECT distinct obj FROM " + className + " obj "; + + sortFields.add(new SortField("id", "obj.id", true, SORT_ORDER.ASC)); + } + + 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()); + } + + resource = getDao().create(resource); + + return postCreate(resource); + } + + public V readResource(Long id) { + // T resource = preRead(id); + + T resource = getDao().getById(id); + + if (resource == null) { + // Returns code 404 with DATA_NOT_FOUND as the error message + throw restErrorUtil.createRESTException(getResourceName() + " not found", MessageEnums.DATA_NOT_FOUND, id, null, "preRead: " + id + " not found.", HttpServletResponse.SC_NOT_FOUND); + } + + return readResource(resource); + } + + 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); + + return postUpdate(resource); + } + + public boolean deleteResource(Long id) { + boolean result; + 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 + try { + result = getDao().remove(resource); + } catch (Exception e) { + logger.error("Error deleting {} => Id = {}", getResourceName(), 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; + } + + // ---------------------------------------------------------------------------------- + // mapping view bean attributes + // ---------------------------------------------------------------------------------- + public V populateViewBean(T resource) { + V viewBean = createViewObject(); + + populateViewBean(resource, viewBean); + + return mapEntityToViewBean(viewBean, resource); + } + + public VXLong getSearchCount(SearchCriteria searchCriteria, List searchFieldList) { + long count = getCountForSearchQuery(searchCriteria, searchFieldList); + VXLong vXLong = new VXLong(); + + vXLong.setValue(count); + + return vXLong; + } + + // -------------Criteria Usage-------------------- + // ----------------------------------------------- + public VXLong getSearchCountUsingCriteria(SearchCriteria searchCriteria, List searchFieldList) { + EntityManager em = getDao().getEntityManager(); + CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder(); + CriteriaQuery criteria = criteriaBuilder.createQuery(Long.class); + Root from = criteria.from(tEntityClass); + Expression 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 countQuery = em.createQuery(criteria); + long count = getDao().executeCountQueryInSecurityContext(tEntityClass, countQuery); + VXLong vXLong = new VXLong(); + + vXLong.setValue(count); + + return vXLong; + } + + public void setSortClause(SearchCriteria searchCriteria, List sortFields, CriteriaBuilder criteriaBuilder, CriteriaQuery criteria, Root 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 ("desc".equalsIgnoreCase(sortType)) { + criteria.orderBy(criteriaBuilder.desc(from.get(sortByField))); + } else { + criteria.orderBy(criteriaBuilder.asc(from.get(sortByField))); + } + } + } + + public Map convertVListToVMap(List vObjList) { + Map ret = new HashMap<>(); + + if (vObjList == null) { + return ret; + } + + for (V vObj : vObjList) { + ret.put(vObj.getId(), vObj); + } + + return ret; + } + + // ---------------------------------------------------------------------------------- + // Create Operation + // ---------------------------------------------------------------------------------- + + protected abstract void validateForCreate(V viewBaseBean); + + protected abstract void validateForUpdate(V viewBaseBean, T t); + + protected abstract T mapViewToEntityBean(V viewBean, T t, int operationContext); + + protected abstract V mapEntityToViewBean(V viewBean, T t); + + protected String getResourceName() { + String resourceName = tEntityValueMap.get(tEntityClass); + + if (resourceName == null || resourceName.isEmpty()) { + resourceName = "Object"; + } + + return resourceName; + } + + // ---------------------------------------------------------------------------------- + // Read Operation + // ---------------------------------------------------------------------------------- + + protected BaseDao getDao() { + if (entityDao == null) { + throw new NullPointerException("entityDao is not injected by Spring!"); + } + + 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; + } + + /** + * 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()); + } + + // ---------------------------------------------------------------------------------- + // Update Operation + // ---------------------------------------------------------------------------------- + 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; + } + + protected V postCreate(T resource) { + return populateViewBean(resource); + } + + protected T preRead(Long id) { + return null; + } + + protected V postRead(T resource) { + return populateViewBean(resource); + } + + /** + * 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); + } + + protected V postUpdate(T resource) { + return populateViewBean(resource); + } + + // ---------------------------------------------------------------------------------- + // 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 {} id={}", getResourceName(), id); + } + + return resource; + } + + protected void postDelete(T resource) { + } + + // ---------------------------------------------------------------------------------- + // Validation + // ---------------------------------------------------------------------------------- + protected void validateGenericAttributes(V viewBaseBean) { + } + + // ---------------------------------------------------------------------------------- + // Search Operation + // ---------------------------------------------------------------------------------- + + 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() && !"null".equalsIgnoreCase(tUser.getPublicScreenName().trim())) { + viewBean.setOwner(tUser.getPublicScreenName()); + } else { + if (tUser.getFirstName() != null && !tUser.getFirstName().trim().isEmpty() && !"null".equalsIgnoreCase(tUser.getFirstName().trim())) { + if (tUser.getLastName() != null && !tUser.getLastName().trim().isEmpty() && !"null".equalsIgnoreCase(tUser.getLastName().trim())) { + 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() && !"null".equalsIgnoreCase(tUser.getPublicScreenName().trim())) { + viewBean.setUpdatedBy(tUser.getPublicScreenName()); + } else { + if (tUser.getFirstName() != null && !tUser.getFirstName().trim().isEmpty() && !"null".equalsIgnoreCase(tUser.getFirstName().trim())) { + if (tUser.getLastName() != null && !tUser.getLastName().trim().isEmpty() && !"null".equalsIgnoreCase(tUser.getLastName().trim())) { + viewBean.setUpdatedBy(tUser.getFirstName() + " " + tUser.getLastName()); + } else { + viewBean.setUpdatedBy(tUser.getFirstName()); + } + } else { + viewBean.setUpdatedBy(tUser.getLoginId()); + } + } + } + } + } + + protected Query createQuery(String searchString, String sortString, SearchCriteria searchCriteria, List searchFieldList, boolean isCountQuery) { + EntityManager em = getDao().getEntityManager(); + + return searchUtil.createSearchQuery(em, searchString, sortString, searchCriteria, searchFieldList, false, isCountQuery); + } + + protected long getCountForSearchQuery(SearchCriteria searchCriteria, List 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; + } + + protected List searchResources(SearchCriteria searchCriteria, List searchFieldList, List 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 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; + } + + protected List searchResourcesUsingCriteria(SearchCriteria searchCriteria, List searchFieldList, List sortFieldList, VList vList) { + EntityManager em = getDao().getEntityManager(); + CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder(); + CriteriaQuery criteria = criteriaBuilder.createQuery(); + Root 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 countExpression = criteriaBuilder.count(from.get("id")); + + criteria.select(countExpression); + + TypedQuery 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 typedQuery = em.createQuery(criteria); + + searchUtil.updateQueryPageSize(typedQuery, searchCriteria); + + List 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); + } + + return resultList; + } + + protected Predicate buildUserConditions(Map paramList, List searchFields, CriteriaBuilder cb, Root from) { + Predicate userConditions = cb.conjunction(); + + for (SearchField searchField : searchFields) { + if (paramList.containsKey(searchField.getClientFieldName())) { + Path tableField; + 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 tableFieldWithLowerExpr = cb.lower(tableField.as(String.class)); + + if (searchField.getSearchType() == SearchField.SEARCH_TYPE.FULL) { + Expression literal = cb.lower(cb.literal(strFieldValue)); + + userConditions = cb.and(userConditions, cb.equal(tableFieldWithLowerExpr, literal)); + } else { + Expression 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 intValueList = (Collection) 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)); + } + } + } + } + + return userConditions; + } + + protected Predicate buildResourceSpecificConditions(CriteriaBuilder criteriaBuilder, Root from, SearchCriteria sc) { + return null; + } + + /** + * @param resource + * @return + */ + 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); + } + + return postRead(resource); + } + + static { + tEntityValueMap.put(XXAuthSession.class, "Auth Session"); + tEntityValueMap.put(XXDBBase.class, "Base"); + } } diff --git a/security-admin/src/main/java/org/apache/ranger/service/AuthSessionService.java b/security-admin/src/main/java/org/apache/ranger/service/AuthSessionService.java index 25ca9fbe32..1718717eac 100644 --- a/security-admin/src/main/java/org/apache/ranger/service/AuthSessionService.java +++ b/security-admin/src/main/java/org/apache/ranger/service/AuthSessionService.java @@ -17,10 +17,7 @@ * under the License. */ - package org.apache.ranger.service; - -import java.util.ArrayList; -import java.util.List; +package org.apache.ranger.service; import org.apache.ranger.common.RangerConstants; import org.apache.ranger.common.SearchCriteria; @@ -34,157 +31,116 @@ import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Service; +import java.util.ArrayList; +import java.util.List; + @Service @Scope("singleton") -public class AuthSessionService extends - AbstractBaseResourceService { - - public static final String NAME = "AuthSession"; - - public static final List AUTH_SESSION_SORT_FLDS = new ArrayList(); - 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 AUTH_SESSION_SEARCH_FLDS = new ArrayList(); - 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", RangerConstants.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; - } - - /* - * (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.setId(resource.getId()); - viewObj.setRequestIP(resource.getRequestIP()); - - viewObj.setRequestUserAgent(resource.getRequestUserAgent()); - - if (resource.getUserId() != null) { - viewObj.setUserId(resource.getUserId()); - - XXPortalUser gjUser = daoManager.getXXPortalUser().getById(resource.getUserId()); - if (gjUser != null) { - viewObj.setEmailAddress(gjUser.getEmailAddress()); - viewObj.setFamilyScreenName(gjUser.getLastName()); - viewObj.setFirstName(gjUser.getFirstName()); - viewObj.setLastName(gjUser.getLastName()); - viewObj.setPublicScreenName(gjUser.getPublicScreenName()); - } - } - - return viewObj; - } - - /** - * @param searchCriteria - * @return - */ - public VXAuthSessionList search(SearchCriteria searchCriteria) { - VXAuthSessionList returnList = new VXAuthSessionList(); - List viewList = new ArrayList(); - - List 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; - } +public class AuthSessionService extends AbstractBaseResourceService { + public static final String NAME = "AuthSession"; + + public static final List AUTH_SESSION_SORT_FLDS = new ArrayList<>(); + public static final List AUTH_SESSION_SEARCH_FLDS = new ArrayList<>(); + + /** + * @param searchCriteria + * @return + */ + public VXAuthSessionList search(SearchCriteria searchCriteria) { + VXAuthSessionList returnList = new VXAuthSessionList(); + List viewList = new ArrayList<>(); + + List 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; + } + + @Override + protected void validateForCreate(VXAuthSession vXAuthSession) { + logger.error("This method is not required and shouldn't be called.", new Throwable().fillInStackTrace()); + } + + @Override + protected void validateForUpdate(VXAuthSession vXAuthSession, XXAuthSession mObj) { + logger.error("This method is not required and shouldn't be called.", new Throwable().fillInStackTrace()); + } + + @Override + protected XXAuthSession mapViewToEntityBean(VXAuthSession vXAuthSession, XXAuthSession t, int operationContext) { + logger.error("This method is not required and shouldn't be called.", new Throwable().fillInStackTrace()); + + return null; + } + + @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.setId(resource.getId()); + viewObj.setRequestIP(resource.getRequestIP()); + viewObj.setRequestUserAgent(resource.getRequestUserAgent()); + + if (resource.getUserId() != null) { + viewObj.setUserId(resource.getUserId()); + + XXPortalUser gjUser = daoManager.getXXPortalUser().getById(resource.getUserId()); + if (gjUser != null) { + viewObj.setEmailAddress(gjUser.getEmailAddress()); + viewObj.setFamilyScreenName(gjUser.getLastName()); + viewObj.setFirstName(gjUser.getFirstName()); + viewObj.setLastName(gjUser.getLastName()); + viewObj.setPublicScreenName(gjUser.getPublicScreenName()); + } + } + + return viewObj; + } + + @Override + protected String getResourceName() { + return NAME; + } + + @Override + protected XXAuthSession createEntityObject() { + return new XXAuthSession(); + } + + @Override + protected VXAuthSession createViewObject() { + return new VXAuthSession(); + } + + 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)); + } + + 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", RangerConstants.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)); + } } diff --git a/security-admin/src/main/java/org/apache/ranger/service/PublicAPIServiceBase.java b/security-admin/src/main/java/org/apache/ranger/service/PublicAPIServiceBase.java index ad79a2a7ac..e94f278480 100644 --- a/security-admin/src/main/java/org/apache/ranger/service/PublicAPIServiceBase.java +++ b/security-admin/src/main/java/org/apache/ranger/service/PublicAPIServiceBase.java @@ -17,29 +17,28 @@ * under the License. */ - package org.apache.ranger.service; +package org.apache.ranger.service; import org.apache.ranger.view.VXDataObject; public abstract class PublicAPIServiceBase { + 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()); - 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; - } + 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; - } + 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; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/service/RangerAuditFields.java b/security-admin/src/main/java/org/apache/ranger/service/RangerAuditFields.java index fe1883dd17..91fd15afba 100644 --- a/security-admin/src/main/java/org/apache/ranger/service/RangerAuditFields.java +++ b/security-admin/src/main/java/org/apache/ranger/service/RangerAuditFields.java @@ -24,21 +24,21 @@ @Component public class RangerAuditFields { + public T populateAuditFields(T xObj, PARENT parentObj) { + xObj.setCreateTime(parentObj.getCreateTime()); + xObj.setUpdateTime(parentObj.getUpdateTime()); + xObj.setAddedByUserId(parentObj.getAddedByUserId()); + xObj.setUpdatedByUserId(parentObj.getUpdatedByUserId()); - public T populateAuditFields(T xObj, PARENT parentObj) { - xObj.setCreateTime(parentObj.getCreateTime()); - xObj.setUpdateTime(parentObj.getUpdateTime()); - xObj.setAddedByUserId(parentObj.getAddedByUserId()); - xObj.setUpdatedByUserId(parentObj.getUpdatedByUserId()); - return xObj; - } + return xObj; + } - public T populateAuditFieldsForCreate(T xObj) { - xObj.setCreateTime(DateUtil.getUTCDate()); - xObj.setUpdateTime(DateUtil.getUTCDate()); - xObj.setAddedByUserId(ContextUtil.getCurrentUserId()); - xObj.setUpdatedByUserId(ContextUtil.getCurrentUserId()); - return xObj; - } + public T populateAuditFieldsForCreate(T xObj) { + xObj.setCreateTime(DateUtil.getUTCDate()); + xObj.setUpdateTime(DateUtil.getUTCDate()); + xObj.setAddedByUserId(ContextUtil.getCurrentUserId()); + xObj.setUpdatedByUserId(ContextUtil.getCurrentUserId()); + return xObj; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/service/RangerAuditedModelService.java b/security-admin/src/main/java/org/apache/ranger/service/RangerAuditedModelService.java index dfecf720fd..edf514b1fe 100755 --- a/security-admin/src/main/java/org/apache/ranger/service/RangerAuditedModelService.java +++ b/security-admin/src/main/java/org/apache/ranger/service/RangerAuditedModelService.java @@ -31,213 +31,219 @@ import org.springframework.beans.factory.annotation.Autowired; import javax.annotation.PostConstruct; -import java.util.*; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; public abstract class RangerAuditedModelService extends RangerBaseModelService { - private static final Logger LOG = LoggerFactory.getLogger(RangerAuditedModelService.class); + private static final Logger LOG = LoggerFactory.getLogger(RangerAuditedModelService.class); + + protected final Map trxLogAttrs = new HashMap<>(); + protected final String hiddenPasswordString; + + private final int classType; + private final int parentClassType; + private final List objNameAttrs = new ArrayList<>(); + + @Autowired + RangerDataHistService dataHistService; + + @Autowired + RangerEnumUtil xaEnumUtil; + + protected RangerAuditedModelService(int classType) { + this(classType, 0); + } + + protected RangerAuditedModelService(int classType, int parentClassType) { + super(); + + this.classType = classType; + this.parentClassType = parentClassType; + this.hiddenPasswordString = PropertiesUtil.getProperty("ranger.password.hidden", "*****"); + + LOG.debug("RangerAuditedModelService({}, {})", this.classType, this.parentClassType); + } + + @PostConstruct + public void init() { + for (VTrxLogAttr vTrxLog : trxLogAttrs.values()) { + if (vTrxLog.isObjName()) { + objNameAttrs.add(vTrxLog); + } + } - @Autowired - RangerDataHistService dataHistService; + if (objNameAttrs.isEmpty()) { + objNameAttrs.add(new VTrxLogAttr("name", "Name", false, true)); + } + } - @Autowired - RangerEnumUtil xaEnumUtil; - private final int classType; - private final int parentClassType; - private final List objNameAttrs = new ArrayList<>(); - - protected final Map trxLogAttrs = new HashMap<>(); - protected final String hiddenPasswordString; - - protected RangerAuditedModelService(int classType) { - this(classType, 0); - } - - protected RangerAuditedModelService(int classType, int parentClassType) { - super(); - - this.classType = classType; - this.parentClassType = parentClassType; - this.hiddenPasswordString = PropertiesUtil.getProperty("ranger.password.hidden", "*****"); - - LOG.debug("RangerAuditedModelService({}, {})", this.classType, this.parentClassType); - } - - @PostConstruct - public void init() { - for (VTrxLogAttr vTrxLog : trxLogAttrs.values()) { - if (vTrxLog.isObjName()) { - objNameAttrs.add(vTrxLog); - } - } - - if (objNameAttrs.isEmpty()) { - objNameAttrs.add(new VTrxLogAttr("name", "Name", false, true)); - } - } + public void onObjectChange(V current, V former, int action) { + switch (action) { + case RangerServiceService.OPERATION_CREATE_CONTEXT: + dataHistService.createObjectDataHistory(current, RangerDataHistService.ACTION_CREATE); + break; - public void onObjectChange(V current, V former, int action) { - switch (action) { - case RangerServiceService.OPERATION_CREATE_CONTEXT: - dataHistService.createObjectDataHistory(current, RangerDataHistService.ACTION_CREATE); - break; + case RangerServiceService.OPERATION_UPDATE_CONTEXT: + dataHistService.createObjectDataHistory(current, RangerDataHistService.ACTION_UPDATE); + break; - case RangerServiceService.OPERATION_UPDATE_CONTEXT: - dataHistService.createObjectDataHistory(current, RangerDataHistService.ACTION_UPDATE); - break; + case RangerServiceService.OPERATION_DELETE_CONTEXT: + if (current == null) { + current = former; + } - case RangerServiceService.OPERATION_DELETE_CONTEXT: - if (current == null) { - current = former; - } + dataHistService.createObjectDataHistory(current, RangerDataHistService.ACTION_DELETE); + break; + } - dataHistService.createObjectDataHistory(current, RangerDataHistService.ACTION_DELETE); - break; - } + if (current != null && (former != null || action != OPERATION_UPDATE_CONTEXT) && action != 0) { + createTransactionLog(current, former, action); + } + } - if (current != null && (former != null || action != OPERATION_UPDATE_CONTEXT) && action != 0) { - createTransactionLog(current, former, action); - } - } + public void createTransactionLog(XXTrxLogV2 trxLog, String attrName, String oldValue, String newValue) { + try { + ObjectChangeInfo objChangeInfo = new ObjectChangeInfo(); - public void createTransactionLog(XXTrxLogV2 trxLog, String attrName, String oldValue, String newValue) { - try { - ObjectChangeInfo objChangeInfo = new ObjectChangeInfo(); - - objChangeInfo.addAttribute(attrName, oldValue, newValue); - - trxLog.setChangeInfo(JsonUtilsV2.objToJson(objChangeInfo)); - } catch (Exception excp) { - LOG.warn("failed to convert attribute change info to json"); - } - - bizUtil.createTrxLog(Collections.singletonList(trxLog)); - } - - public void createTransactionLog(XXTrxLogV2 trxLog) { - bizUtil.createTrxLog(Collections.singletonList(trxLog)); - } - - public void createTransactionLog(V obj, V oldObj, int action) { - List trxLogs = getTransactionLogs(obj, oldObj, action); - - if (trxLogs != null) { - bizUtil.createTrxLog(trxLogs); - } - } - - private List getTransactionLogs(V obj, V oldObj, int action) { - if (obj == null || (action == OPERATION_UPDATE_CONTEXT && oldObj == null)) { - return null; - } - - List ret = new ArrayList<>(); - - try { - ObjectChangeInfo objChangeInfo = new ObjectChangeInfo(); - - for (VTrxLogAttr trxLog : trxLogAttrs.values()) { - processFieldToCreateTrxLog(trxLog, obj, oldObj, action, objChangeInfo); - } - - if(objChangeInfo.getAttributes() != null && objChangeInfo.getAttributes().size() > 0) { - ret.add(new XXTrxLogV2(classType, obj.getId(), getObjectName(obj), getParentObjectType(obj, oldObj), getParentObjectId(obj, oldObj), getParentObjectName(obj, oldObj), toActionString(action), JsonUtilsV2.objToJson(objChangeInfo))); - } - } catch (Exception excp) { - LOG.warn("failed to get transaction log for object: type=" + obj.getClass().getName() + ", id=" + obj.getId(), excp); - } - - return ret; - } - - public int getParentObjectType(V obj, V oldObj) { - return parentClassType; - } - - public String getParentObjectName(V obj, V oldObj) { - return null; - } - - public Long getParentObjectId(V obj, V oldObj) { - return null; - } - - public boolean skipTrxLogForAttribute(V obj, V oldObj, VTrxLogAttr trxLogAttr) { - return false; - } - - public String getTrxLogAttrValue(V obj, VTrxLogAttr trxLogAttr) { - return trxLogAttr.getAttrValue(obj, xaEnumUtil); - } - - private String getObjectName(V obj) { - String ret = null; - - for (VTrxLogAttr attr : objNameAttrs) { - ret = attr.getAttrValue(obj, xaEnumUtil); - - if (StringUtils.isNotBlank(ret)) { - break; - } - } - - return ret; - } - - private void processFieldToCreateTrxLog(VTrxLogAttr trxLogAttr, V obj, V oldObj, int action, ObjectChangeInfo objChangeInfo) { - if (skipTrxLogForAttribute(obj, oldObj, trxLogAttr)) { - return; - } - - String value = getTrxLogAttrValue(obj, trxLogAttr); - - if ((action == OPERATION_CREATE_CONTEXT || action == OPERATION_DELETE_CONTEXT) && StringUtils.isBlank(value)) { - return; - } - - final String prevValue; - final String newValue; - - if (action == OPERATION_CREATE_CONTEXT) { - prevValue = null; - newValue = value; - } else if (action == OPERATION_DELETE_CONTEXT) { - prevValue = value; - newValue = null; - } else if (action == OPERATION_UPDATE_CONTEXT) { - prevValue = getTrxLogAttrValue(oldObj, trxLogAttr); - newValue = value; - } else if (action == OPERATION_IMPORT_CREATE_CONTEXT) { - prevValue = null; - newValue = value; - } else if (action == OPERATION_IMPORT_DELETE_CONTEXT) { - prevValue = value; - newValue = null; - } else { - prevValue = null; - newValue = null; - } - - if (StringUtils.equals(prevValue, newValue) || (StringUtils.isEmpty(prevValue) && StringUtils.isEmpty(newValue))) { - return; - } - - objChangeInfo.addAttribute(trxLogAttr.getAttribUserFriendlyName(), prevValue, newValue); - } - - private String toActionString(int action) { - switch (action) { - case OPERATION_CREATE_CONTEXT: - return "create"; - case OPERATION_UPDATE_CONTEXT: - return "update"; - case OPERATION_DELETE_CONTEXT: - return "delete"; - case OPERATION_IMPORT_CREATE_CONTEXT: - return "Import Create"; - case OPERATION_IMPORT_DELETE_CONTEXT: - return "Import Delete"; - } - - return "unknown"; - } + objChangeInfo.addAttribute(attrName, oldValue, newValue); + + trxLog.setChangeInfo(JsonUtilsV2.objToJson(objChangeInfo)); + } catch (Exception excp) { + LOG.warn("failed to convert attribute change info to json"); + } + + bizUtil.createTrxLog(Collections.singletonList(trxLog)); + } + + public void createTransactionLog(XXTrxLogV2 trxLog) { + bizUtil.createTrxLog(Collections.singletonList(trxLog)); + } + + public void createTransactionLog(V obj, V oldObj, int action) { + List trxLogs = getTransactionLogs(obj, oldObj, action); + + if (trxLogs != null) { + bizUtil.createTrxLog(trxLogs); + } + } + + public int getParentObjectType(V obj, V oldObj) { + return parentClassType; + } + + public String getParentObjectName(V obj, V oldObj) { + return null; + } + + public Long getParentObjectId(V obj, V oldObj) { + return null; + } + + public boolean skipTrxLogForAttribute(V obj, V oldObj, VTrxLogAttr trxLogAttr) { + return false; + } + + public String getTrxLogAttrValue(V obj, VTrxLogAttr trxLogAttr) { + return trxLogAttr.getAttrValue(obj, xaEnumUtil); + } + + private List getTransactionLogs(V obj, V oldObj, int action) { + if (obj == null || (action == OPERATION_UPDATE_CONTEXT && oldObj == null)) { + return null; + } + + List ret = new ArrayList<>(); + + try { + ObjectChangeInfo objChangeInfo = new ObjectChangeInfo(); + + for (VTrxLogAttr trxLog : trxLogAttrs.values()) { + processFieldToCreateTrxLog(trxLog, obj, oldObj, action, objChangeInfo); + } + + if (objChangeInfo.getAttributes() != null && !objChangeInfo.getAttributes().isEmpty()) { + ret.add(new XXTrxLogV2(classType, obj.getId(), getObjectName(obj), getParentObjectType(obj, oldObj), getParentObjectId(obj, oldObj), getParentObjectName(obj, oldObj), toActionString(action), JsonUtilsV2.objToJson(objChangeInfo))); + } + } catch (Exception excp) { + LOG.warn("failed to get transaction log for object: type={}, id={}", obj.getClass().getName(), obj.getId(), excp); + } + + return ret; + } + + private String getObjectName(V obj) { + String ret = null; + + for (VTrxLogAttr attr : objNameAttrs) { + ret = attr.getAttrValue(obj, xaEnumUtil); + + if (StringUtils.isNotBlank(ret)) { + break; + } + } + + return ret; + } + + private void processFieldToCreateTrxLog(VTrxLogAttr trxLogAttr, V obj, V oldObj, int action, ObjectChangeInfo objChangeInfo) { + if (skipTrxLogForAttribute(obj, oldObj, trxLogAttr)) { + return; + } + + String value = getTrxLogAttrValue(obj, trxLogAttr); + + if ((action == OPERATION_CREATE_CONTEXT || action == OPERATION_DELETE_CONTEXT) && StringUtils.isBlank(value)) { + return; + } + + final String prevValue; + final String newValue; + + if (action == OPERATION_CREATE_CONTEXT) { + prevValue = null; + newValue = value; + } else if (action == OPERATION_DELETE_CONTEXT) { + prevValue = value; + newValue = null; + } else if (action == OPERATION_UPDATE_CONTEXT) { + prevValue = getTrxLogAttrValue(oldObj, trxLogAttr); + newValue = value; + } else if (action == OPERATION_IMPORT_CREATE_CONTEXT) { + prevValue = null; + newValue = value; + } else if (action == OPERATION_IMPORT_DELETE_CONTEXT) { + prevValue = value; + newValue = null; + } else { + prevValue = null; + newValue = null; + } + + if (StringUtils.equals(prevValue, newValue) || (StringUtils.isEmpty(prevValue) && StringUtils.isEmpty(newValue))) { + return; + } + + objChangeInfo.addAttribute(trxLogAttr.getAttribUserFriendlyName(), prevValue, newValue); + } + + private String toActionString(int action) { + switch (action) { + case OPERATION_CREATE_CONTEXT: + return "create"; + case OPERATION_UPDATE_CONTEXT: + return "update"; + case OPERATION_DELETE_CONTEXT: + return "delete"; + case OPERATION_IMPORT_CREATE_CONTEXT: + return "Import Create"; + case OPERATION_IMPORT_DELETE_CONTEXT: + return "Import Delete"; + } + + return "unknown"; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/service/RangerBaseModelService.java b/security-admin/src/main/java/org/apache/ranger/service/RangerBaseModelService.java index 26f76578e5..0484979d74 100755 --- a/security-admin/src/main/java/org/apache/ranger/service/RangerBaseModelService.java +++ b/security-admin/src/main/java/org/apache/ranger/service/RangerBaseModelService.java @@ -17,15 +17,6 @@ package org.apache.ranger.service; -import java.lang.reflect.ParameterizedType; -import java.lang.reflect.TypeVariable; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import javax.persistence.EntityManager; -import javax.persistence.Query; - import org.apache.ranger.biz.RangerBizUtil; import org.apache.ranger.common.ContextUtil; import org.apache.ranger.common.DateUtil; @@ -51,452 +42,424 @@ import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; +import javax.persistence.EntityManager; +import javax.persistence.Query; + +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.TypeVariable; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + public abstract class RangerBaseModelService { - private static final Logger LOG = LoggerFactory.getLogger(RangerBaseModelService.class); - - public static final int OPERATION_CREATE_CONTEXT = 1; - public static final int OPERATION_UPDATE_CONTEXT = 2; - public static final int OPERATION_DELETE_CONTEXT = 3; - public static final int OPERATION_IMPORT_CREATE_CONTEXT = 4; - public static final int OPERATION_IMPORT_DELETE_CONTEXT = 5; - - - @Autowired - protected RangerDaoManager daoMgr; - - @Autowired - protected StringUtil stringUtil; - - @Autowired - protected RESTErrorUtil restErrorUtil; - - @Autowired - protected RangerSearchUtil searchUtil; - - @Autowired - protected BaseDao entityDao; - - @Autowired - RangerBizUtil bizUtil; - - public final List sortFields = new ArrayList<>(); - public final List searchFields = new ArrayList<>(); - protected final Class tEntityClass; - protected final Class tViewClass; - protected final String tClassName; - protected final String countQueryStr; - protected final String distinctCountQueryStr; - protected final String queryStr; - protected final String distinctQueryStr; - private Boolean populateExistingBaseFields; - - @SuppressWarnings("unchecked") - public RangerBaseModelService() { - Class klass = getClass(); - ParameterizedType genericSuperclass = (ParameterizedType) klass.getGenericSuperclass(); - TypeVariable> var[] = klass.getTypeParameters(); - - if (genericSuperclass.getActualTypeArguments()[0] instanceof Class) { - tEntityClass = (Class) genericSuperclass.getActualTypeArguments()[0]; - tViewClass = (Class) genericSuperclass.getActualTypeArguments()[1]; - } else if (var.length > 0) { - tEntityClass = (Class) var[0].getBounds()[0]; - tViewClass = (Class) var[1].getBounds()[0]; - } else { - LOG.error("Cannot find class for template", new Throwable()); - - tEntityClass = null; - tViewClass = null; - } - - tClassName = (tEntityClass != null) ? tEntityClass.getName() : "XXDBBase"; - - populateExistingBaseFields = false; - - countQueryStr = "SELECT COUNT(obj) FROM " + tClassName + " obj "; - distinctCountQueryStr = "SELECT COUNT(distinct obj.id) FROM " + tClassName + " obj "; - queryStr = "SELECT obj FROM " + tClassName + " obj "; - distinctQueryStr = "SELECT DISTINCT obj FROM " + tClassName + " obj "; - } - - protected abstract T mapViewToEntityBean(V viewBean, T t, - int OPERATION_CONTEXT); - - protected abstract V mapEntityToViewBean(V viewBean, T t); - - protected T createEntityObject() { - try { - return tEntityClass.newInstance(); - } catch (Throwable e) { - LOG.error("Error instantiating entity class. tEntityClass=" - + tEntityClass.toString(), e); - } - return null; - } - - protected V createViewObject() { - try { - return tViewClass.newInstance(); - } catch (Throwable e) { - LOG.error("Error instantiating view class. tViewClass=" - + tViewClass.toString(), e); - } - return null; - } - - protected BaseDao getDao() { - if (entityDao == null) { - throw new NullPointerException("entityDao is not injected by Spring!"); - } - return entityDao; - } - - protected V populateViewBean(T entityObj) { - V vObj = createViewObject(); - vObj.setId(entityObj.getId()); - vObj.setCreateTime(entityObj.getCreateTime()); - vObj.setUpdateTime(entityObj.getUpdateTime()); - vObj.setCreatedBy(getUserScreenName(entityObj.getAddedByUserId())); - vObj.setUpdatedBy(getUserScreenName(entityObj.getUpdatedByUserId())); - - return mapEntityToViewBean(vObj, entityObj); - } - - protected T populateEntityBeanForCreate(T entityObj, V vObj) { - if (!populateExistingBaseFields) { - entityObj.setCreateTime(DateUtil.getUTCDate()); - entityObj.setUpdateTime(entityObj.getCreateTime()); - entityObj.setAddedByUserId(ContextUtil.getCurrentUserId()); - entityObj.setUpdatedByUserId(entityObj.getAddedByUserId()); - } else { - XXPortalUser createdByUser = daoMgr.getXXPortalUser().findByLoginId(vObj.getCreatedBy()); - XXPortalUser updByUser = daoMgr.getXXPortalUser().findByLoginId(vObj.getUpdatedBy()); - - entityObj.setId(vObj.getId()); - entityObj.setCreateTime(vObj.getCreateTime() != null ? vObj.getCreateTime() : DateUtil.getUTCDate()); - entityObj.setUpdateTime(vObj.getUpdateTime() != null ? vObj.getUpdateTime() : DateUtil.getUTCDate()); - entityObj.setAddedByUserId(createdByUser != null ? createdByUser.getId() : ContextUtil.getCurrentUserId()); - entityObj.setUpdatedByUserId(updByUser != null ? updByUser.getId() : ContextUtil.getCurrentUserId()); - } - - return mapViewToEntityBean(vObj, entityObj, OPERATION_CREATE_CONTEXT); - } - - protected T populateEntityBeanForUpdate(T entityObj, V vObj) { - if (entityObj == null) { - throw restErrorUtil.createRESTException( - "No Object found to update.", - MessageEnums.DATA_NOT_FOUND); - } - - T ret = mapViewToEntityBean(vObj, entityObj, OPERATION_UPDATE_CONTEXT); - - if (ret.getCreateTime() == null) { - ret.setCreateTime(DateUtil.getUTCDate()); - } - - if (ret.getAddedByUserId() == null) { - ret.setAddedByUserId(ContextUtil.getCurrentUserId()); - } - - if(!populateExistingBaseFields) { - ret.setUpdateTime(DateUtil.getUTCDate()); - ret.setUpdatedByUserId(ContextUtil.getCurrentUserId()); - } - - return ret; - } - - protected abstract void validateForCreate(V vObj); - - protected abstract void validateForUpdate(V vObj, T entityObj); - - public T preCreate(V vObj) { - validateForCreate(vObj); - - T entityObj = createEntityObject(); - - return populateEntityBeanForCreate(entityObj, vObj); - } - - public V postCreate(T xObj) { - return populateViewBean(xObj); - } - - public V create(V vObj) { - T resource = preCreate(vObj); - resource = getDao().create(resource); - vObj = postCreate(resource); - return vObj; - } - - public V create(V vObj, boolean flush) { - T resource = preCreate(vObj); - resource = getDao().create(resource, flush); - vObj = postCreate(resource); - return vObj; - } - - public V read(Long id) { - T resource = getDao().getById(id); - if (resource == null) { - throw restErrorUtil.createRESTException(tViewClass.getName() - + " :Data Not Found for given Id", - MessageEnums.DATA_NOT_FOUND, id, null, - "readResource : No Object found with given id."); - } - return populateViewBean(resource); - } - - public V update(V viewBaseBean) { - T resource = preUpdate(viewBaseBean); - resource = getDao().update(resource); - V viewBean = postUpdate(resource); - return viewBean; - } - - public V postUpdate(T resource) { - return populateViewBean(resource); - } - - public T preUpdate(V viewBaseBean) { - T resource = getDao().getById(viewBaseBean.getId()); - if (resource == null) { - throw restErrorUtil.createRESTException(tEntityClass.getSimpleName() - + " not found", MessageEnums.DATA_NOT_FOUND, - viewBaseBean.getId(), null, "preUpdate: id not found."); - } - validateForUpdate(viewBaseBean, resource); - return populateEntityBeanForUpdate(resource, viewBaseBean); - } - - public boolean delete(V vObj) { - boolean result = false; - Long id = vObj.getId(); - T resource = preDelete(id); - if (resource == null) { - throw restErrorUtil.createRESTException( - tEntityClass.getSimpleName() + " not found", - MessageEnums.DATA_NOT_FOUND, id, null, - tEntityClass.getSimpleName() + ":" + id); - } - try { - result = getDao().remove(resource); - } catch (Exception e) { - LOG.error("Error deleting " + tEntityClass.getSimpleName() - + ". Id=" + id, e); - - throw restErrorUtil.createRESTException( - tEntityClass.getSimpleName() + " can't be deleted", - MessageEnums.OPER_NOT_ALLOWED_FOR_STATE, id, null, "" + id - + ", error=" + e.getMessage()); - } - return result; - } - - public boolean delete(V vObj, boolean flush) { - boolean result = false; - Long id = vObj.getId(); - T resource = preDelete(id); - if (resource == null) { - throw restErrorUtil.createRESTException( - tEntityClass.getSimpleName() + " not found", - MessageEnums.DATA_NOT_FOUND, id, null, - tEntityClass.getSimpleName() + ":" + id); - } - try { - result = getDao().remove(resource); - } catch (Exception e) { - LOG.error("Error deleting " + tEntityClass.getSimpleName() - + ". Id=" + id, e); - - throw restErrorUtil.createRESTException( - tEntityClass.getSimpleName() + " can't be deleted", - MessageEnums.OPER_NOT_ALLOWED_FOR_STATE, id, null, "" + id - + ", error=" + e.getMessage()); - } - return result; - } - - protected T preDelete(Long id) { - T resource = getDao().getById(id); - if (resource == null) { - // Return without error - LOG.info("Delete ignored for non-existent Object, id=" + id); - } - return resource; - } - - public Boolean getPopulateExistingBaseFields() { - return populateExistingBaseFields; - } - - public void setPopulateExistingBaseFields(Boolean populateExistingBaseFields) { - this.populateExistingBaseFields = populateExistingBaseFields; - } - - /* - * Search Operations - * - */ - - public List searchResources(SearchFilter searchCriteria, - List searchFieldList, List 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(); - } - } - - String sortClause = searchUtil.constructSortClause(searchCriteria, sortFieldList); - String q = searchCriteria.isDistinct() ? distinctQueryStr : queryStr; - Query query = createQuery(q, sortClause, searchCriteria, searchFieldList, false); - List resultList = getDao().executeQueryInSecurityContext(tEntityClass, query); - - if (vList != null) { - vList.setResultSize(resultList.size()); - vList.setPageSize(query.getMaxResults()); - vList.setSortBy(searchCriteria.getSortBy()); - vList.setSortType(searchCriteria.getSortType()); - vList.setStartIndex(query.getFirstResult()); - vList.setTotalCount(count); - } - return resultList; - } - - protected List searchRangerObjects(SearchFilter searchCriteria, List searchFieldList, List sortFieldList, PList pList) { - - // 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(); - } - } - - String sortClause = searchUtil.constructSortClause(searchCriteria, sortFieldList); - - String q = queryStr; - Query query = createQuery(q, sortClause, searchCriteria, searchFieldList, false); - - List resultList = getDao().executeQueryInSecurityContext(tEntityClass, query); - - if (pList != null) { - pList.setResultSize(resultList.size()); - pList.setPageSize(query.getMaxResults()); - pList.setSortBy(searchCriteria.getSortBy()); - pList.setSortType(searchCriteria.getSortType()); - pList.setStartIndex(query.getFirstResult()); - pList.setTotalCount(count); - } - return resultList; - } - - //If not efficient we need to review this and add jpa_named queries to get the count - public long getCountForSearchQuery(SearchFilter searchCriteria, List searchFieldList) { - String q = searchCriteria.isDistinct() ? distinctCountQueryStr : countQueryStr; - Query query = createQuery(q, null, searchCriteria, searchFieldList, true); - Long count = getDao().executeCountQueryInSecurityContext(tEntityClass, query); - - return (count == null) ? 0 : count.longValue(); - } - - protected Query createQuery(String searchString, String sortString, SearchFilter searchCriteria, - List searchFieldList, boolean isCountQuery) { - - EntityManager em = getDao().getEntityManager(); - Query query = searchUtil.createSearchQuery(em, searchString, sortString, searchCriteria, - searchFieldList, false, isCountQuery); - return query; - } - - protected String getUserScreenName(Long userId) { - String ret = null; - - XXPortalUser xPortalUser = userId == null ? null : daoMgr.getXXPortalUser().getById(userId); - - if(xPortalUser != null) { - ret = xPortalUser.getPublicScreenName(); - - if (stringUtil.isEmpty(ret)) { - ret = xPortalUser.getFirstName(); - - if(stringUtil.isEmpty(ret)) { - ret = xPortalUser.getLoginId(); - } else { - if(!stringUtil.isEmpty(xPortalUser.getLastName())) { - ret += (" " + xPortalUser.getLastName()); - } - } - } - } - - return ret; - } - - protected String getUserName(Long userId) { - String ret = null; - - XXPortalUser xPortalUser = userId == null ? null : daoMgr.getXXPortalUser().getById(userId); - - if(xPortalUser != null) { - ret = xPortalUser.getLoginId(); - } - - return ret; - } - - protected String getGroupName(Long groupId) { - String ret = null; - - XXGroup xGroup = groupId == null ? null : daoMgr.getXXGroup().getById(groupId); + private static final Logger LOG = LoggerFactory.getLogger(RangerBaseModelService.class); + + public static final int OPERATION_CREATE_CONTEXT = 1; + public static final int OPERATION_UPDATE_CONTEXT = 2; + public static final int OPERATION_DELETE_CONTEXT = 3; + public static final int OPERATION_IMPORT_CREATE_CONTEXT = 4; + public static final int OPERATION_IMPORT_DELETE_CONTEXT = 5; + + public final List sortFields = new ArrayList<>(); + public final List searchFields = new ArrayList<>(); + + protected final Class tEntityClass; + protected final Class tViewClass; + protected final String tClassName; + protected final String countQueryStr; + protected final String distinctCountQueryStr; + protected final String queryStr; + protected final String distinctQueryStr; + + @Autowired + protected RangerDaoManager daoMgr; + + @Autowired + protected StringUtil stringUtil; + + @Autowired + protected RESTErrorUtil restErrorUtil; + + @Autowired + protected RangerSearchUtil searchUtil; + + @Autowired + protected BaseDao entityDao; + + @Autowired + RangerBizUtil bizUtil; + + private Boolean populateExistingBaseFields; + + @SuppressWarnings("unchecked") + public RangerBaseModelService() { + Class klass = getClass(); + ParameterizedType genericSuperclass = (ParameterizedType) klass.getGenericSuperclass(); + TypeVariable>[] var = klass.getTypeParameters(); + + if (genericSuperclass.getActualTypeArguments()[0] instanceof Class) { + tEntityClass = (Class) genericSuperclass.getActualTypeArguments()[0]; + tViewClass = (Class) genericSuperclass.getActualTypeArguments()[1]; + } else if (var.length > 0) { + tEntityClass = (Class) var[0].getBounds()[0]; + tViewClass = (Class) var[1].getBounds()[0]; + } else { + LOG.error("Cannot find class for template", new Throwable()); + + tEntityClass = null; + tViewClass = null; + } + + tClassName = (tEntityClass != null) ? tEntityClass.getName() : "XXDBBase"; + populateExistingBaseFields = false; + countQueryStr = "SELECT COUNT(obj) FROM " + tClassName + " obj "; + distinctCountQueryStr = "SELECT COUNT(distinct obj.id) FROM " + tClassName + " obj "; + queryStr = "SELECT obj FROM " + tClassName + " obj "; + distinctQueryStr = "SELECT DISTINCT obj FROM " + tClassName + " obj "; + } + + public T preCreate(V vObj) { + validateForCreate(vObj); + + T entityObj = createEntityObject(); + + return populateEntityBeanForCreate(entityObj, vObj); + } + + public V postCreate(T xObj) { + return populateViewBean(xObj); + } + + public V create(V vObj) { + T resource = preCreate(vObj); + + resource = getDao().create(resource); + vObj = postCreate(resource); + + return vObj; + } + + public V create(V vObj, boolean flush) { + T resource = preCreate(vObj); + + resource = getDao().create(resource, flush); + vObj = postCreate(resource); + + return vObj; + } + + public V read(Long id) { + T resource = getDao().getById(id); + + if (resource == null) { + throw restErrorUtil.createRESTException(tViewClass.getName() + " :Data Not Found for given Id", MessageEnums.DATA_NOT_FOUND, id, null, "readResource : No Object found with given id."); + } + + return populateViewBean(resource); + } + + public V update(V viewBaseBean) { + T resource = preUpdate(viewBaseBean); + + resource = getDao().update(resource); + + return postUpdate(resource); + } + + public V postUpdate(T resource) { + return populateViewBean(resource); + } + + public T preUpdate(V viewBaseBean) { + T resource = getDao().getById(viewBaseBean.getId()); + + if (resource == null) { + throw restErrorUtil.createRESTException(tEntityClass.getSimpleName() + " not found", MessageEnums.DATA_NOT_FOUND, viewBaseBean.getId(), null, "preUpdate: id not found."); + } + + validateForUpdate(viewBaseBean, resource); + + return populateEntityBeanForUpdate(resource, viewBaseBean); + } + + public boolean delete(V vObj) { + boolean result; + Long id = vObj.getId(); + T resource = preDelete(id); + + if (resource == null) { + throw restErrorUtil.createRESTException(tEntityClass.getSimpleName() + " not found", MessageEnums.DATA_NOT_FOUND, id, null, tEntityClass.getSimpleName() + ":" + id); + } + + try { + result = getDao().remove(resource); + } catch (Exception e) { + LOG.error("Error deleting {}. Id={}", tEntityClass.getSimpleName(), id, e); + + throw restErrorUtil.createRESTException(tEntityClass.getSimpleName() + " can't be deleted", MessageEnums.OPER_NOT_ALLOWED_FOR_STATE, id, null, id + ", error=" + e.getMessage()); + } + + return result; + } + + public boolean delete(V vObj, boolean flush) { + boolean result; + Long id = vObj.getId(); + T resource = preDelete(id); + + if (resource == null) { + throw restErrorUtil.createRESTException(tEntityClass.getSimpleName() + " not found", MessageEnums.DATA_NOT_FOUND, id, null, tEntityClass.getSimpleName() + ":" + id); + } + + try { + result = getDao().remove(resource); + } catch (Exception e) { + LOG.error("Error deleting {}. Id={}", tEntityClass.getSimpleName(), id, e); + + throw restErrorUtil.createRESTException(tEntityClass.getSimpleName() + " can't be deleted", MessageEnums.OPER_NOT_ALLOWED_FOR_STATE, id, null, id + ", error=" + e.getMessage()); + } + + return result; + } + + public Boolean getPopulateExistingBaseFields() { + return populateExistingBaseFields; + } + + public void setPopulateExistingBaseFields(Boolean populateExistingBaseFields) { + this.populateExistingBaseFields = populateExistingBaseFields; + } + + public List searchResources(SearchFilter searchCriteria, List searchFieldList, List 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(); + } + } + + String sortClause = searchUtil.constructSortClause(searchCriteria, sortFieldList); + String q = searchCriteria.isDistinct() ? distinctQueryStr : queryStr; + Query query = createQuery(q, sortClause, searchCriteria, searchFieldList, false); + List resultList = getDao().executeQueryInSecurityContext(tEntityClass, query); + + if (vList != null) { + vList.setResultSize(resultList.size()); + vList.setPageSize(query.getMaxResults()); + vList.setSortBy(searchCriteria.getSortBy()); + vList.setSortType(searchCriteria.getSortType()); + vList.setStartIndex(query.getFirstResult()); + vList.setTotalCount(count); + } + + return resultList; + } + + //If not efficient we need to review this and add jpa_named queries to get the count + public long getCountForSearchQuery(SearchFilter searchCriteria, List searchFieldList) { + String q = searchCriteria.isDistinct() ? distinctCountQueryStr : countQueryStr; + Query query = createQuery(q, null, searchCriteria, searchFieldList, true); + Long count = getDao().executeCountQueryInSecurityContext(tEntityClass, query); + + return (count == null) ? 0 : count; + } + + protected abstract T mapViewToEntityBean(V viewBean, T t, int operationContext); + + protected abstract V mapEntityToViewBean(V viewBean, T t); + + protected T createEntityObject() { + try { + return tEntityClass.newInstance(); + } catch (Throwable e) { + LOG.error("Error instantiating entity class. tEntityClass={}", tEntityClass.toString(), e); + } + + return null; + } + + protected V createViewObject() { + try { + return tViewClass.newInstance(); + } catch (Throwable e) { + LOG.error("Error instantiating view class. tViewClass={}", tViewClass.toString(), e); + } + + return null; + } + + protected BaseDao getDao() { + if (entityDao == null) { + throw new NullPointerException("entityDao is not injected by Spring!"); + } + + return entityDao; + } + + protected V populateViewBean(T entityObj) { + V vObj = createViewObject(); + + vObj.setId(entityObj.getId()); + vObj.setCreateTime(entityObj.getCreateTime()); + vObj.setUpdateTime(entityObj.getUpdateTime()); + vObj.setCreatedBy(getUserScreenName(entityObj.getAddedByUserId())); + vObj.setUpdatedBy(getUserScreenName(entityObj.getUpdatedByUserId())); + + return mapEntityToViewBean(vObj, entityObj); + } + + protected T populateEntityBeanForCreate(T entityObj, V vObj) { + if (!populateExistingBaseFields) { + entityObj.setCreateTime(DateUtil.getUTCDate()); + entityObj.setUpdateTime(entityObj.getCreateTime()); + entityObj.setAddedByUserId(ContextUtil.getCurrentUserId()); + entityObj.setUpdatedByUserId(entityObj.getAddedByUserId()); + } else { + XXPortalUser createdByUser = daoMgr.getXXPortalUser().findByLoginId(vObj.getCreatedBy()); + XXPortalUser updByUser = daoMgr.getXXPortalUser().findByLoginId(vObj.getUpdatedBy()); + + entityObj.setId(vObj.getId()); + entityObj.setCreateTime(vObj.getCreateTime() != null ? vObj.getCreateTime() : DateUtil.getUTCDate()); + entityObj.setUpdateTime(vObj.getUpdateTime() != null ? vObj.getUpdateTime() : DateUtil.getUTCDate()); + entityObj.setAddedByUserId(createdByUser != null ? createdByUser.getId() : ContextUtil.getCurrentUserId()); + entityObj.setUpdatedByUserId(updByUser != null ? updByUser.getId() : ContextUtil.getCurrentUserId()); + } + + return mapViewToEntityBean(vObj, entityObj, OPERATION_CREATE_CONTEXT); + } + + protected T populateEntityBeanForUpdate(T entityObj, V vObj) { + if (entityObj == null) { + throw restErrorUtil.createRESTException("No Object found to update.", MessageEnums.DATA_NOT_FOUND); + } + + T ret = mapViewToEntityBean(vObj, entityObj, OPERATION_UPDATE_CONTEXT); + + if (ret.getCreateTime() == null) { + ret.setCreateTime(DateUtil.getUTCDate()); + } + + if (ret.getAddedByUserId() == null) { + ret.setAddedByUserId(ContextUtil.getCurrentUserId()); + } + + if (!populateExistingBaseFields) { + ret.setUpdateTime(DateUtil.getUTCDate()); + ret.setUpdatedByUserId(ContextUtil.getCurrentUserId()); + } + + return ret; + } + + protected abstract void validateForCreate(V vObj); + + /* + * Search Operations + * + */ + + protected abstract void validateForUpdate(V vObj, T entityObj); + + protected T preDelete(Long id) { + T resource = getDao().getById(id); + + if (resource == null) { + // Return without error + LOG.info("Delete ignored for non-existent Object, id={}", id); + } + + return resource; + } + + protected List searchRangerObjects(SearchFilter searchCriteria, List searchFieldList, List sortFieldList, PList pList) { + // 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(); + } + } + + String sortClause = searchUtil.constructSortClause(searchCriteria, sortFieldList); + String q = queryStr; + Query query = createQuery(q, sortClause, searchCriteria, searchFieldList, false); + List resultList = getDao().executeQueryInSecurityContext(tEntityClass, query); + + if (pList != null) { + pList.setResultSize(resultList.size()); + pList.setPageSize(query.getMaxResults()); + pList.setSortBy(searchCriteria.getSortBy()); + pList.setSortType(searchCriteria.getSortType()); + pList.setStartIndex(query.getFirstResult()); + pList.setTotalCount(count); + } + + return resultList; + } + + protected Query createQuery(String searchString, String sortString, SearchFilter searchCriteria, List searchFieldList, boolean isCountQuery) { + EntityManager em = getDao().getEntityManager(); + + return searchUtil.createSearchQuery(em, searchString, sortString, searchCriteria, searchFieldList, false, isCountQuery); + } + + protected String getUserScreenName(Long userId) { + String ret = null; + XXPortalUser xPortalUser = userId == null ? null : daoMgr.getXXPortalUser().getById(userId); - if(xGroup != null) { - ret = xGroup.getName(); - } + if (xPortalUser != null) { + ret = xPortalUser.getPublicScreenName(); - return ret; - } + if (stringUtil.isEmpty(ret)) { + ret = xPortalUser.getFirstName(); - protected String getAccessTypeName(Long accessTypeDefId) { - String ret = null; + if (stringUtil.isEmpty(ret)) { + ret = xPortalUser.getLoginId(); + } else { + if (!stringUtil.isEmpty(xPortalUser.getLastName())) { + ret += (" " + xPortalUser.getLastName()); + } + } + } + } - XXAccessTypeDef accessTypeDef = accessTypeDefId == null ? null : daoMgr.getXXAccessTypeDef().getById(accessTypeDefId); + return ret; + } - if(accessTypeDef != null) { - ret = accessTypeDef.getName(); - } + protected String getUserName(Long userId) { + XXPortalUser xPortalUser = userId == null ? null : daoMgr.getXXPortalUser().getById(userId); - return ret; - } + return xPortalUser != null ? xPortalUser.getLoginId() : null; + } - protected String getConditionName(Long conditionDefId) { - String ret = null; + protected String getGroupName(Long groupId) { + XXGroup xGroup = groupId == null ? null : daoMgr.getXXGroup().getById(groupId); - XXPolicyConditionDef conditionDef = conditionDefId == null ? null : daoMgr.getXXPolicyConditionDef().getById(conditionDefId); + return xGroup != null ? xGroup.getName() : null; + } - if(conditionDef != null) { - ret = conditionDef.getName(); - } + protected String getAccessTypeName(Long accessTypeDefId) { + XXAccessTypeDef accessTypeDef = accessTypeDefId == null ? null : daoMgr.getXXAccessTypeDef().getById(accessTypeDefId); - return ret; - } + return accessTypeDef != null ? accessTypeDef.getName() : null; + } - protected String getResourceName(Long resourceDefId) { - String ret = null; + protected String getConditionName(Long conditionDefId) { + XXPolicyConditionDef conditionDef = conditionDefId == null ? null : daoMgr.getXXPolicyConditionDef().getById(conditionDefId); - XXResourceDef resourceDef = resourceDefId == null ? null : daoMgr.getXXResourceDef().getById(resourceDefId); + return conditionDef != null ? conditionDef.getName() : null; + } - if(resourceDef != null) { - ret = resourceDef.getName(); - } + protected String getResourceName(Long resourceDefId) { + XXResourceDef resourceDef = resourceDefId == null ? null : daoMgr.getXXResourceDef().getById(resourceDefId); - return ret; - } + return resourceDef != null ? resourceDef.getName() : null; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/service/RangerDataHistService.java b/security-admin/src/main/java/org/apache/ranger/service/RangerDataHistService.java index 38edcea120..1ca1018ad0 100644 --- a/security-admin/src/main/java/org/apache/ranger/service/RangerDataHistService.java +++ b/security-admin/src/main/java/org/apache/ranger/service/RangerDataHistService.java @@ -17,8 +17,6 @@ package org.apache.ranger.service; -import java.util.Date; - import org.apache.ranger.common.AppConstants; import org.apache.ranger.common.DateUtil; import org.apache.ranger.common.JSONUtil; @@ -27,136 +25,135 @@ import org.apache.ranger.db.RangerDaoManager; import org.apache.ranger.entity.XXDataHist; import org.apache.ranger.plugin.model.RangerBaseModelObject; -import org.apache.ranger.plugin.model.RangerPolicy; -import org.apache.ranger.plugin.model.RangerService; -import org.apache.ranger.plugin.model.RangerServiceDef; +import org.apache.ranger.plugin.model.RangerGds.RangerDataShare; +import org.apache.ranger.plugin.model.RangerGds.RangerDataShareInDataset; import org.apache.ranger.plugin.model.RangerGds.RangerDataset; import org.apache.ranger.plugin.model.RangerGds.RangerDatasetInProject; -import org.apache.ranger.plugin.model.RangerGds.RangerDataShare; import org.apache.ranger.plugin.model.RangerGds.RangerProject; -import org.apache.ranger.plugin.model.RangerGds.RangerDataShareInDataset; import org.apache.ranger.plugin.model.RangerGds.RangerSharedResource; +import org.apache.ranger.plugin.model.RangerPolicy; +import org.apache.ranger.plugin.model.RangerService; +import org.apache.ranger.plugin.model.RangerServiceDef; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Service; +import java.util.Date; + @Service @Scope("singleton") public class RangerDataHistService { + public static final String ACTION_CREATE = "Create"; + public static final String ACTION_UPDATE = "Update"; + public static final String ACTION_DELETE = "Delete"; + + @Autowired + RESTErrorUtil restErrorUtil; + + @Autowired + RangerDaoManager daoMgr; + + @Autowired + JSONUtil jsonUtil; + + public void createObjectDataHistory(RangerBaseModelObject baseModelObj, String action) { + if (baseModelObj == null || action == null) { + throw restErrorUtil.createRESTException("Error while creating DataHistory. " + "Object or Action can not be null.", MessageEnums.DATA_NOT_FOUND); + } + + Integer classType = null; + String objectName = null; + String content = null; + Long objectId = baseModelObj.getId(); + String objectGuid = baseModelObj.getGuid(); + Date currentDate = DateUtil.getUTCDate(); + XXDataHist xDataHist = new XXDataHist(); + + xDataHist.setObjectId(baseModelObj.getId()); + xDataHist.setObjectGuid(objectGuid); + xDataHist.setCreateTime(currentDate); + xDataHist.setAction(action); + xDataHist.setVersion(baseModelObj.getVersion()); + xDataHist.setUpdateTime(currentDate); + xDataHist.setFromTime(currentDate); + + if (baseModelObj instanceof RangerServiceDef) { + RangerServiceDef serviceDef = (RangerServiceDef) baseModelObj; + + objectName = serviceDef.getName(); + classType = AppConstants.CLASS_TYPE_XA_SERVICE_DEF; + content = jsonUtil.writeObjectAsString(serviceDef); + } else if (baseModelObj instanceof RangerService) { + RangerService service = (RangerService) baseModelObj; + + objectName = service.getName(); + classType = AppConstants.CLASS_TYPE_XA_SERVICE; + content = jsonUtil.writeObjectAsString(service); + } else if (baseModelObj instanceof RangerPolicy) { + RangerPolicy policy = (RangerPolicy) baseModelObj; + + objectName = policy.getName(); + classType = AppConstants.CLASS_TYPE_RANGER_POLICY; + + policy.setServiceType(policy.getServiceType()); + + content = jsonUtil.writeObjectAsString(policy); + } else if (baseModelObj instanceof RangerDataset) { + RangerDataset dataset = (RangerDataset) baseModelObj; + + objectName = dataset.getName(); + classType = AppConstants.CLASS_TYPE_GDS_DATASET; + content = jsonUtil.writeObjectAsString(dataset); + } else if (baseModelObj instanceof RangerProject) { + RangerProject project = (RangerProject) baseModelObj; + + objectName = project.getName(); + classType = AppConstants.CLASS_TYPE_GDS_PROJECT; + content = jsonUtil.writeObjectAsString(project); + } else if (baseModelObj instanceof RangerDataShare) { + RangerDataShare dataShare = (RangerDataShare) baseModelObj; + + objectName = dataShare.getName(); + classType = AppConstants.CLASS_TYPE_GDS_DATA_SHARE; + content = jsonUtil.writeObjectAsString(dataShare); + } else if (baseModelObj instanceof RangerSharedResource) { + RangerSharedResource sharedResource = (RangerSharedResource) baseModelObj; + + objectName = sharedResource.getName(); + classType = AppConstants.CLASS_TYPE_GDS_SHARED_RESOURCE; + content = jsonUtil.writeObjectAsString(sharedResource); + } else if (baseModelObj instanceof RangerDataShareInDataset) { + RangerDataShareInDataset dataShareInDataset = (RangerDataShareInDataset) baseModelObj; + + objectName = dataShareInDataset.getGuid(); + classType = AppConstants.CLASS_TYPE_GDS_DATA_SHARE_IN_DATASET; + content = jsonUtil.writeObjectAsString(dataShareInDataset); + } else if (baseModelObj instanceof RangerDatasetInProject) { + RangerDatasetInProject datasetInProject = (RangerDatasetInProject) baseModelObj; + + objectName = datasetInProject.getGuid(); + classType = AppConstants.CLASS_TYPE_GDS_DATASET_IN_PROJECT; + content = jsonUtil.writeObjectAsString(datasetInProject); + } + + xDataHist.setObjectClassType(classType); + xDataHist.setObjectName(objectName); + xDataHist.setContent(content); + + daoMgr.getXXDataHist().create(xDataHist); + + if (ACTION_UPDATE.equalsIgnoreCase(action) || ACTION_DELETE.equalsIgnoreCase(action)) { + XXDataHist prevHist = daoMgr.getXXDataHist().findLatestByObjectClassTypeAndObjectId(classType, objectId); + + if (prevHist == null) { + throw restErrorUtil.createRESTException("Error updating DataHistory Object. ObjectName: " + objectName, MessageEnums.DATA_NOT_UPDATABLE); + } - @Autowired - RESTErrorUtil restErrorUtil; - - @Autowired - RangerDaoManager daoMgr; - - @Autowired - JSONUtil jsonUtil; - - public static final String ACTION_CREATE = "Create"; - public static final String ACTION_UPDATE = "Update"; - public static final String ACTION_DELETE = "Delete"; - - public void createObjectDataHistory(RangerBaseModelObject baseModelObj, String action) { - if(baseModelObj == null || action == null) { - throw restErrorUtil - .createRESTException("Error while creating DataHistory. " - + "Object or Action can not be null.", - MessageEnums.DATA_NOT_FOUND); - } - - - Integer classType = null; - String objectName = null; - String content = null; - - Long objectId = baseModelObj.getId(); - String objectGuid = baseModelObj.getGuid(); - Date currentDate = DateUtil.getUTCDate(); - - XXDataHist xDataHist = new XXDataHist(); - - xDataHist.setObjectId(baseModelObj.getId()); - xDataHist.setObjectGuid(objectGuid); - xDataHist.setCreateTime(currentDate); - xDataHist.setAction(action); - xDataHist.setVersion(baseModelObj.getVersion()); - xDataHist.setUpdateTime(currentDate); - xDataHist.setFromTime(currentDate); - - if(baseModelObj instanceof RangerServiceDef) { - RangerServiceDef serviceDef = (RangerServiceDef) baseModelObj; - objectName = serviceDef.getName(); - classType = AppConstants.CLASS_TYPE_XA_SERVICE_DEF; - content = jsonUtil.writeObjectAsString(serviceDef); - } else if(baseModelObj instanceof RangerService) { - RangerService service = (RangerService) baseModelObj; - objectName = service.getName(); - classType = AppConstants.CLASS_TYPE_XA_SERVICE; - content = jsonUtil.writeObjectAsString(service); - } else if(baseModelObj instanceof RangerPolicy) { - RangerPolicy policy = (RangerPolicy) baseModelObj; - objectName = policy.getName(); - classType = AppConstants.CLASS_TYPE_RANGER_POLICY; - policy.setServiceType(policy.getServiceType()); - content = jsonUtil.writeObjectAsString(policy); - } else if (baseModelObj instanceof RangerDataset) { - RangerDataset dataset = (RangerDataset) baseModelObj; - - objectName = dataset.getName(); - classType = AppConstants.CLASS_TYPE_GDS_DATASET; - content = jsonUtil.writeObjectAsString(dataset); - } else if (baseModelObj instanceof RangerProject) { - RangerProject project = (RangerProject) baseModelObj; - - objectName = project.getName(); - classType = AppConstants.CLASS_TYPE_GDS_PROJECT; - content = jsonUtil.writeObjectAsString(project); - } else if (baseModelObj instanceof RangerDataShare) { - RangerDataShare dataShare = (RangerDataShare) baseModelObj; - - objectName = dataShare.getName(); - classType = AppConstants.CLASS_TYPE_GDS_DATA_SHARE; - content = jsonUtil.writeObjectAsString(dataShare); - } else if (baseModelObj instanceof RangerSharedResource) { - RangerSharedResource sharedResource = (RangerSharedResource) baseModelObj; - - objectName = sharedResource.getName(); - classType = AppConstants.CLASS_TYPE_GDS_SHARED_RESOURCE; - content = jsonUtil.writeObjectAsString(sharedResource); - } else if (baseModelObj instanceof RangerDataShareInDataset) { - RangerDataShareInDataset dataShareInDataset = (RangerDataShareInDataset) baseModelObj; - - objectName = dataShareInDataset.getGuid(); - classType = AppConstants.CLASS_TYPE_GDS_DATA_SHARE_IN_DATASET; - content = jsonUtil.writeObjectAsString(dataShareInDataset); - } else if (baseModelObj instanceof RangerDatasetInProject) { - RangerDatasetInProject datasetInProject = (RangerDatasetInProject) baseModelObj; - - objectName = datasetInProject.getGuid(); - classType = AppConstants.CLASS_TYPE_GDS_DATASET_IN_PROJECT; - content = jsonUtil.writeObjectAsString(datasetInProject); - } - - xDataHist.setObjectClassType(classType); - xDataHist.setObjectName(objectName); - xDataHist.setContent(content); - xDataHist = daoMgr.getXXDataHist().create(xDataHist); - - if (ACTION_UPDATE.equalsIgnoreCase(action) || ACTION_DELETE.equalsIgnoreCase(action)) { - XXDataHist prevHist = daoMgr.getXXDataHist().findLatestByObjectClassTypeAndObjectId(classType, objectId); - - if(prevHist == null) { - throw restErrorUtil.createRESTException( - "Error updating DataHistory Object. ObjectName: " - + objectName, MessageEnums.DATA_NOT_UPDATABLE); - } - - prevHist.setUpdateTime(currentDate); - prevHist.setToTime(currentDate); - prevHist.setObjectName(objectName); - prevHist = daoMgr.getXXDataHist().update(prevHist); - } - } + prevHist.setUpdateTime(currentDate); + prevHist.setToTime(currentDate); + prevHist.setObjectName(objectName); + daoMgr.getXXDataHist().update(prevHist); + } + } } diff --git a/security-admin/src/main/java/org/apache/ranger/service/RangerGdsBaseModelService.java b/security-admin/src/main/java/org/apache/ranger/service/RangerGdsBaseModelService.java index d94aab013c..f0f4bec221 100644 --- a/security-admin/src/main/java/org/apache/ranger/service/RangerGdsBaseModelService.java +++ b/security-admin/src/main/java/org/apache/ranger/service/RangerGdsBaseModelService.java @@ -29,24 +29,22 @@ import java.util.List; public abstract class RangerGdsBaseModelService extends RangerAuditedModelService { - protected RangerGdsBaseModelService(int classType) { super(classType, -1); } - protected RangerGdsBaseModelService(int classType, int parentClassType) { super(classType, parentClassType); - searchFields.add(new SearchField(SearchFilter.GUID, "obj.guid", SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.FULL)); - searchFields.add(new SearchField(SearchFilter.IS_ENABLED, "obj.isEnabled", SearchField.DATA_TYPE.BOOLEAN, SearchField.SEARCH_TYPE.FULL)); - searchFields.add(new SearchField(SearchFilter.CREATE_TIME_START, "obj.createTime", SearchField.DATA_TYPE.DATE, SearchField.SEARCH_TYPE.GREATER_EQUAL_THAN)); - searchFields.add(new SearchField(SearchFilter.CREATE_TIME_END, "obj.createTime", SearchField.DATA_TYPE.DATE, SearchField.SEARCH_TYPE.LESS_EQUAL_THAN)); - searchFields.add(new SearchField(SearchFilter.UPDATE_TIME_START, "obj.updateTime", SearchField.DATA_TYPE.DATE, SearchField.SEARCH_TYPE.GREATER_EQUAL_THAN)); - searchFields.add(new SearchField(SearchFilter.UPDATE_TIME_END, "obj.createTime", SearchField.DATA_TYPE.DATE, SearchField.SEARCH_TYPE.LESS_EQUAL_THAN)); + searchFields.add(new SearchField(SearchFilter.GUID, "obj.guid", SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.FULL)); + searchFields.add(new SearchField(SearchFilter.IS_ENABLED, "obj.isEnabled", SearchField.DATA_TYPE.BOOLEAN, SearchField.SEARCH_TYPE.FULL)); + searchFields.add(new SearchField(SearchFilter.CREATE_TIME_START, "obj.createTime", SearchField.DATA_TYPE.DATE, SearchField.SEARCH_TYPE.GREATER_EQUAL_THAN)); + searchFields.add(new SearchField(SearchFilter.CREATE_TIME_END, "obj.createTime", SearchField.DATA_TYPE.DATE, SearchField.SEARCH_TYPE.LESS_EQUAL_THAN)); + searchFields.add(new SearchField(SearchFilter.UPDATE_TIME_START, "obj.updateTime", SearchField.DATA_TYPE.DATE, SearchField.SEARCH_TYPE.GREATER_EQUAL_THAN)); + searchFields.add(new SearchField(SearchFilter.UPDATE_TIME_END, "obj.createTime", SearchField.DATA_TYPE.DATE, SearchField.SEARCH_TYPE.LESS_EQUAL_THAN)); - trxLogAttrs.put("description", new VTrxLogAttr("description", "Description")); - trxLogAttrs.put("options", new VTrxLogAttr("options", "Options")); + trxLogAttrs.put("description", new VTrxLogAttr("description", "Description")); + trxLogAttrs.put("options", new VTrxLogAttr("options", "Options")); trxLogAttrs.put("additionalInfo", new VTrxLogAttr("additionalInfo", "Additional info")); } diff --git a/security-admin/src/main/java/org/apache/ranger/service/RangerGdsDataShareInDatasetService.java b/security-admin/src/main/java/org/apache/ranger/service/RangerGdsDataShareInDatasetService.java index 866c742caa..cfe623eaeb 100644 --- a/security-admin/src/main/java/org/apache/ranger/service/RangerGdsDataShareInDatasetService.java +++ b/security-admin/src/main/java/org/apache/ranger/service/RangerGdsDataShareInDatasetService.java @@ -17,7 +17,6 @@ package org.apache.ranger.service; - import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang.StringUtils; import org.apache.ranger.authorization.utils.JsonUtils; @@ -61,36 +60,36 @@ public class RangerGdsDataShareInDatasetService extends RangerGdsBaseModelServic public RangerGdsDataShareInDatasetService() { super(AppConstants.CLASS_TYPE_GDS_DATA_SHARE_IN_DATASET, AppConstants.CLASS_TYPE_GDS_DATASET); - searchFields.add(new SearchField(SearchFilter.DATA_SHARE_IN_DATASET_ID, "obj.id", SearchField.DATA_TYPE.INTEGER, SearchField.SEARCH_TYPE.FULL)); - searchFields.add(new SearchField(SearchFilter.DATA_SHARE_ID, "obj.dataShareId", SearchField.DATA_TYPE.INTEGER, SearchField.SEARCH_TYPE.FULL)); - searchFields.add(new SearchField(SearchFilter.DATA_SHARE_NAME, "dsh.name", SearchField.DATA_TYPE.INTEGER, SearchField.SEARCH_TYPE.FULL, "XXGdsDataShare dsh", "obj.dataShareId = dsh.id")); - searchFields.add(new SearchField(SearchFilter.DATA_SHARE_NAME_PARTIAL, "dsh.name", SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.PARTIAL, "XXGdsDataShare dsh", "obj.dataShareId = dsh.id")); - searchFields.add(new SearchField(SearchFilter.SERVICE_ID, "dsh.serviceId", SearchField.DATA_TYPE.INTEGER, SearchField.SEARCH_TYPE.FULL, "XXGdsDataShare dsh", "obj.dataShareId = dsh.id")); - searchFields.add(new SearchField(SearchFilter.SERVICE_NAME, "s.name", SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.FULL, "XXGdsDataShare dsh, XXService s", "obj.dataShareId = dsh.id and dsh.serviceId = s.id")); - searchFields.add(new SearchField(SearchFilter.SERVICE_NAME_PARTIAL, "s.name", SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.PARTIAL, "XXGdsDataShare dsh, XXService s", "obj.dataShareId = dsh.id and dsh.serviceId = s.id")); - searchFields.add(new SearchField(SearchFilter.ZONE_ID, "dsh.zoneId", SearchField.DATA_TYPE.INTEGER, SearchField.SEARCH_TYPE.FULL, "XXGdsDataShare dsh, XXSecurityZone z", "obj.dataShareId = dsh.id")); - searchFields.add(new SearchField(SearchFilter.ZONE_NAME, "z.name", SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.FULL, "XXGdsDataShare dsh, XXSecurityZone z", "obj.dataShareId = dsh.id and dsh.zoneId = z.id")); - searchFields.add(new SearchField(SearchFilter.ZONE_NAME_PARTIAL, "z.name", SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.PARTIAL, "XXGdsDataShare dsh, XXSecurityZone z", "obj.dataShareId = dsh.id and dsh.zoneId = z.id")); - searchFields.add(new SearchField(SearchFilter.DATASET_ID, "obj.datasetId", SearchField.DATA_TYPE.INTEGER, SearchField.SEARCH_TYPE.FULL)); - searchFields.add(new SearchField(SearchFilter.DATASET_NAME, "d.name", SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.FULL, "XXGdsDataset d", "obj.datasetId = d.id")); - searchFields.add(new SearchField(SearchFilter.DATASET_NAME_PARTIAL, "d.name", SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.PARTIAL, "XXGdsDataset d", "obj.datasetId = d.id")); - searchFields.add(new SearchField(SearchFilter.PROJECT_ID, "dip.projectId", SearchField.DATA_TYPE.INTEGER, SearchField.SEARCH_TYPE.FULL, "XXGdsDataset d, XXGdsDatasetInProject dip", "obj.datasetId = d.id and d.id = dip.datasetId")); - searchFields.add(new SearchField(SearchFilter.PROJECT_NAME, "p.name", SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.FULL, "XXGdsDataset d, XXGdsDatasetInProject dip, XXGdsProject p", "obj.datasetId = d.id and d.id = dip.datasetId and dip.projectId = p.id")); - searchFields.add(new SearchField(SearchFilter.PROJECT_NAME_PARTIAL, "p.name", SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.PARTIAL, "XXGdsDataset d, XXGdsDatasetInProject dip, XXGdsProject p", "obj.datasetId = d.id and d.id = dip.datasetId and dip.projectId = p.id")); - searchFields.add(new SearchField(SearchFilter.APPROVER, "obj.approverId", SearchField.DATA_TYPE.INTEGER, SearchField.SEARCH_TYPE.FULL)); - searchFields.add(new SearchField(SearchFilter.CREATED_BY, "obj.addedByUserId",SearchField.DATA_TYPE.INTEGER, SearchField.SEARCH_TYPE.FULL)); - searchFields.add(new SearchField(SearchFilter.SHARE_STATUS, "obj.status", SearchField.DATA_TYPE.INTEGER, SearchField.SEARCH_TYPE.FULL)); - - sortFields.add(new SortField(SearchFilter.CREATE_TIME, "obj.createTime")); - sortFields.add(new SortField(SearchFilter.UPDATE_TIME, "obj.updateTime")); + searchFields.add(new SearchField(SearchFilter.DATA_SHARE_IN_DATASET_ID, "obj.id", SearchField.DATA_TYPE.INTEGER, SearchField.SEARCH_TYPE.FULL)); + searchFields.add(new SearchField(SearchFilter.DATA_SHARE_ID, "obj.dataShareId", SearchField.DATA_TYPE.INTEGER, SearchField.SEARCH_TYPE.FULL)); + searchFields.add(new SearchField(SearchFilter.DATA_SHARE_NAME, "dsh.name", SearchField.DATA_TYPE.INTEGER, SearchField.SEARCH_TYPE.FULL, "XXGdsDataShare dsh", "obj.dataShareId = dsh.id")); + searchFields.add(new SearchField(SearchFilter.DATA_SHARE_NAME_PARTIAL, "dsh.name", SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.PARTIAL, "XXGdsDataShare dsh", "obj.dataShareId = dsh.id")); + searchFields.add(new SearchField(SearchFilter.SERVICE_ID, "dsh.serviceId", SearchField.DATA_TYPE.INTEGER, SearchField.SEARCH_TYPE.FULL, "XXGdsDataShare dsh", "obj.dataShareId = dsh.id")); + searchFields.add(new SearchField(SearchFilter.SERVICE_NAME, "s.name", SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.FULL, "XXGdsDataShare dsh, XXService s", "obj.dataShareId = dsh.id and dsh.serviceId = s.id")); + searchFields.add(new SearchField(SearchFilter.SERVICE_NAME_PARTIAL, "s.name", SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.PARTIAL, "XXGdsDataShare dsh, XXService s", "obj.dataShareId = dsh.id and dsh.serviceId = s.id")); + searchFields.add(new SearchField(SearchFilter.ZONE_ID, "dsh.zoneId", SearchField.DATA_TYPE.INTEGER, SearchField.SEARCH_TYPE.FULL, "XXGdsDataShare dsh, XXSecurityZone z", "obj.dataShareId = dsh.id")); + searchFields.add(new SearchField(SearchFilter.ZONE_NAME, "z.name", SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.FULL, "XXGdsDataShare dsh, XXSecurityZone z", "obj.dataShareId = dsh.id and dsh.zoneId = z.id")); + searchFields.add(new SearchField(SearchFilter.ZONE_NAME_PARTIAL, "z.name", SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.PARTIAL, "XXGdsDataShare dsh, XXSecurityZone z", "obj.dataShareId = dsh.id and dsh.zoneId = z.id")); + searchFields.add(new SearchField(SearchFilter.DATASET_ID, "obj.datasetId", SearchField.DATA_TYPE.INTEGER, SearchField.SEARCH_TYPE.FULL)); + searchFields.add(new SearchField(SearchFilter.DATASET_NAME, "d.name", SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.FULL, "XXGdsDataset d", "obj.datasetId = d.id")); + searchFields.add(new SearchField(SearchFilter.DATASET_NAME_PARTIAL, "d.name", SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.PARTIAL, "XXGdsDataset d", "obj.datasetId = d.id")); + searchFields.add(new SearchField(SearchFilter.PROJECT_ID, "dip.projectId", SearchField.DATA_TYPE.INTEGER, SearchField.SEARCH_TYPE.FULL, "XXGdsDataset d, XXGdsDatasetInProject dip", "obj.datasetId = d.id and d.id = dip.datasetId")); + searchFields.add(new SearchField(SearchFilter.PROJECT_NAME, "p.name", SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.FULL, "XXGdsDataset d, XXGdsDatasetInProject dip, XXGdsProject p", "obj.datasetId = d.id and d.id = dip.datasetId and dip.projectId = p.id")); + searchFields.add(new SearchField(SearchFilter.PROJECT_NAME_PARTIAL, "p.name", SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.PARTIAL, "XXGdsDataset d, XXGdsDatasetInProject dip, XXGdsProject p", "obj.datasetId = d.id and d.id = dip.datasetId and dip.projectId = p.id")); + searchFields.add(new SearchField(SearchFilter.APPROVER, "obj.approverId", SearchField.DATA_TYPE.INTEGER, SearchField.SEARCH_TYPE.FULL)); + searchFields.add(new SearchField(SearchFilter.CREATED_BY, "obj.addedByUserId", SearchField.DATA_TYPE.INTEGER, SearchField.SEARCH_TYPE.FULL)); + searchFields.add(new SearchField(SearchFilter.SHARE_STATUS, "obj.status", SearchField.DATA_TYPE.INTEGER, SearchField.SEARCH_TYPE.FULL)); + + sortFields.add(new SortField(SearchFilter.CREATE_TIME, "obj.createTime")); + sortFields.add(new SortField(SearchFilter.UPDATE_TIME, "obj.updateTime")); sortFields.add(new SortField(SearchFilter.DATA_SHARE_IN_DATASET_ID, "obj.id", true, SortField.SORT_ORDER.ASC)); - trxLogAttrs.put("dataShareId", new VTrxLogAttr("dataShareId", "DataShare ID")); - trxLogAttrs.put("datasetId", new VTrxLogAttr("datasetId", "Dataset ID")); - trxLogAttrs.put("status", new VTrxLogAttr("status", "Status", true)); + trxLogAttrs.put("dataShareId", new VTrxLogAttr("dataShareId", "DataShare ID")); + trxLogAttrs.put("datasetId", new VTrxLogAttr("datasetId", "Dataset ID")); + trxLogAttrs.put("status", new VTrxLogAttr("status", "Status", true)); trxLogAttrs.put("validitySchedule", new VTrxLogAttr("validitySchedule", "Validity Schedule")); - trxLogAttrs.put("profiles", new VTrxLogAttr("profiles", "Profiles")); - trxLogAttrs.put("approver", new VTrxLogAttr("approver", "Approver")); + trxLogAttrs.put("profiles", new VTrxLogAttr("profiles", "Profiles")); + trxLogAttrs.put("approver", new VTrxLogAttr("approver", "Approver")); } @Override @@ -112,26 +111,53 @@ public RangerDataShareInDataset postUpdate(XXGdsDataShareInDataset xObj) { } @Override - public XXGdsDataShareInDataset preDelete(Long id) { - // Update ServiceVersionInfo for each service in the zone - XXGdsDataShareInDataset ret = super.preDelete(id); + protected XXGdsDataShareInDataset mapViewToEntityBean(RangerDataShareInDataset vObj, XXGdsDataShareInDataset xObj, int operationContext) { + XXGdsDataShare xDataShare = daoMgr.getXXGdsDataShare().getById(vObj.getDataShareId()); - // TODO: + if (xDataShare == null) { + throw restErrorUtil.createRESTException("No data share found with ID: " + vObj.getDataShareId(), MessageEnums.INVALID_INPUT_DATA); + } - return ret; - } + XXGdsDataset xDataset = daoMgr.getXXGdsDataset().getById(vObj.getDatasetId()); - @Override - public String getParentObjectName(RangerDataShareInDataset obj, RangerDataShareInDataset oldObj) { - Long datasetId = obj != null ? obj.getDatasetId() : null; - XXGdsDataset dataset = datasetId != null ? daoMgr.getXXGdsDataset().getById(datasetId) : null; + if (xDataset == null) { + throw restErrorUtil.createRESTException("No dataset found with ID: " + vObj.getDatasetId(), MessageEnums.INVALID_INPUT_DATA); + } - return dataset != null ? dataset.getName() : null; + xObj.setGuid(vObj.getGuid()); + xObj.setIsEnabled(vObj.getIsEnabled()); + xObj.setDescription(vObj.getDescription()); + xObj.setDataShareId(vObj.getDataShareId()); + xObj.setDatasetId(vObj.getDatasetId()); + xObj.setStatus((short) vObj.getStatus().ordinal()); + xObj.setValidityPeriod(JsonUtils.objectToJson(vObj.getValiditySchedule())); + xObj.setProfiles(JsonUtils.objectToJson(vObj.getProfiles())); + xObj.setOptions(JsonUtils.mapToJson(vObj.getOptions())); + xObj.setAdditionalInfo(JsonUtils.mapToJson(vObj.getAdditionalInfo())); + + final XXPortalUser user = xxPortalUserDao.findByLoginId(vObj.getApprover()); + + xObj.setApproverId(user == null ? null : user.getId()); + + return xObj; } @Override - public Long getParentObjectId(RangerDataShareInDataset obj, RangerDataShareInDataset oldObj) { - return obj != null ? obj.getDatasetId() : null; + protected RangerDataShareInDataset mapEntityToViewBean(RangerDataShareInDataset vObj, XXGdsDataShareInDataset xObj) { + vObj.setGuid(xObj.getGuid()); + vObj.setIsEnabled(xObj.getIsEnabled()); + vObj.setVersion(xObj.getVersion()); + vObj.setDescription(xObj.getDescription()); + vObj.setDataShareId(xObj.getDataShareId()); + vObj.setDatasetId(xObj.getDatasetId()); + vObj.setStatus(toShareStatus(xObj.getStatus())); + vObj.setValiditySchedule(JsonUtils.jsonToObject(xObj.getValidityPeriod(), RangerValiditySchedule.class)); + vObj.setProfiles(JsonUtils.jsonToSetString(xObj.getProfiles())); + vObj.setOptions(JsonUtils.jsonToMapStringString(xObj.getOptions())); + vObj.setAdditionalInfo(JsonUtils.jsonToMapStringString(xObj.getAdditionalInfo())); + vObj.setApprover(getUserName(xObj.getApproverId())); + + return vObj; } @Override @@ -237,52 +263,26 @@ protected void validateForUpdate(RangerDataShareInDataset vObj, XXGdsDataShareIn } @Override - protected XXGdsDataShareInDataset mapViewToEntityBean(RangerDataShareInDataset vObj, XXGdsDataShareInDataset xObj, int OPERATION_CONTEXT) { - XXGdsDataShare xDataShare = daoMgr.getXXGdsDataShare().getById(vObj.getDataShareId()); - - if (xDataShare == null) { - throw restErrorUtil.createRESTException("No data share found with ID: " + vObj.getDataShareId(), MessageEnums.INVALID_INPUT_DATA); - } - - XXGdsDataset xDataset = daoMgr.getXXGdsDataset().getById(vObj.getDatasetId()); + public XXGdsDataShareInDataset preDelete(Long id) { + // Update ServiceVersionInfo for each service in the zone + XXGdsDataShareInDataset ret = super.preDelete(id); - if (xDataset == null) { - throw restErrorUtil.createRESTException("No dataset found with ID: " + vObj.getDatasetId(), MessageEnums.INVALID_INPUT_DATA); - } + // TODO: - xObj.setGuid(vObj.getGuid()); - xObj.setIsEnabled(vObj.getIsEnabled()); - xObj.setDescription(vObj.getDescription()); - xObj.setDataShareId(vObj.getDataShareId()); - xObj.setDatasetId(vObj.getDatasetId()); - xObj.setStatus((short) vObj.getStatus().ordinal()); - xObj.setValidityPeriod(JsonUtils.objectToJson(vObj.getValiditySchedule())); - xObj.setProfiles(JsonUtils.objectToJson(vObj.getProfiles())); - xObj.setOptions(JsonUtils.mapToJson(vObj.getOptions())); - xObj.setAdditionalInfo(JsonUtils.mapToJson(vObj.getAdditionalInfo())); + return ret; + } - final XXPortalUser user = xxPortalUserDao.findByLoginId(vObj.getApprover()); - xObj.setApproverId(user == null? null : user.getId()); + @Override + public String getParentObjectName(RangerDataShareInDataset obj, RangerDataShareInDataset oldObj) { + Long datasetId = obj != null ? obj.getDatasetId() : null; + XXGdsDataset dataset = datasetId != null ? daoMgr.getXXGdsDataset().getById(datasetId) : null; - return xObj; + return dataset != null ? dataset.getName() : null; } @Override - protected RangerDataShareInDataset mapEntityToViewBean(RangerDataShareInDataset vObj, XXGdsDataShareInDataset xObj) { - vObj.setGuid(xObj.getGuid()); - vObj.setIsEnabled(xObj.getIsEnabled()); - vObj.setVersion(xObj.getVersion()); - vObj.setDescription(xObj.getDescription()); - vObj.setDataShareId(xObj.getDataShareId()); - vObj.setDatasetId(xObj.getDatasetId()); - vObj.setStatus(toShareStatus(xObj.getStatus())); - vObj.setValiditySchedule(JsonUtils.jsonToObject(xObj.getValidityPeriod(), RangerValiditySchedule.class)); - vObj.setProfiles(JsonUtils.jsonToSetString(xObj.getProfiles())); - vObj.setOptions(JsonUtils.jsonToMapStringString(xObj.getOptions())); - vObj.setAdditionalInfo(JsonUtils.jsonToMapStringString(xObj.getAdditionalInfo())); - vObj.setApprover(getUserName(xObj.getApproverId())); - - return vObj; + public Long getParentObjectId(RangerDataShareInDataset obj, RangerDataShareInDataset oldObj) { + return obj != null ? obj.getDatasetId() : null; } public RangerDataShareInDataset getPopulatedViewObject(XXGdsDataShareInDataset xObj) { @@ -292,7 +292,7 @@ public RangerDataShareInDataset getPopulatedViewObject(XXGdsDataShareInDataset x public RangerDataShareInDatasetList searchDataShareInDatasets(SearchFilter filter) { LOG.debug("==> searchDataShareInDatasets({})", filter); - RangerDataShareInDatasetList ret = new RangerDataShareInDatasetList(); + RangerDataShareInDatasetList ret = new RangerDataShareInDatasetList(); List datasets = super.searchResources(filter, searchFields, sortFields, ret); if (datasets != null) { diff --git a/security-admin/src/main/java/org/apache/ranger/service/RangerGdsDataShareService.java b/security-admin/src/main/java/org/apache/ranger/service/RangerGdsDataShareService.java index 861b624aa3..153edfa146 100755 --- a/security-admin/src/main/java/org/apache/ranger/service/RangerGdsDataShareService.java +++ b/security-admin/src/main/java/org/apache/ranger/service/RangerGdsDataShareService.java @@ -17,7 +17,6 @@ package org.apache.ranger.service; - import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang.StringUtils; import org.apache.ranger.authorization.utils.JsonUtils; @@ -57,36 +56,35 @@ public class RangerGdsDataShareService extends RangerGdsBaseModelService sortFields = new ArrayList<>(); + private final List searchFields = new ArrayList<>(); + + @Autowired + RangerSearchUtil searchUtil; + + @Autowired + RangerBizUtil bizUtil; + + @Autowired + JSONUtil jsonUtil; + + @Autowired + RangerDaoManager daoManager; + + RangerPluginInfoService() { + searchFields.add(new SearchField(SearchFilter.SERVICE_NAME, "obj.serviceName", SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.FULL)); + searchFields.add(new SearchField(SearchFilter.PLUGIN_HOST_NAME, "obj.hostName", SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.FULL)); + searchFields.add(new SearchField(SearchFilter.PLUGIN_APP_TYPE, "obj.appType", SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.FULL)); + searchFields.add(new SearchField(SearchFilter.PLUGIN_IP_ADDRESS, "obj.ipAddress", SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.FULL)); + + sortFields.add(new SortField(SearchFilter.SERVICE_NAME, "obj.serviceName", true, SortField.SORT_ORDER.ASC)); + sortFields.add(new SortField(SearchFilter.PLUGIN_HOST_NAME, "obj.hostName", true, SortField.SORT_ORDER.ASC)); + sortFields.add(new SortField(SearchFilter.PLUGIN_APP_TYPE, "obj.appType", true, SortField.SORT_ORDER.ASC)); + } + + public List getSearchFields() { + return searchFields; + } + + public List getSortFields() { + return sortFields; + } + + public PList searchRangerPluginInfo(SearchFilter searchFilter) { + PList retList = new PList<>(); + List objList = new ArrayList<>(); + + List servicesWithTagService = daoManager.getXXService().getAllServicesWithTagService(); + String serviceTypeToSearch = searchFilter.getParam(SearchFilter.SERVICE_TYPE); + String clusterNameToSearch = searchFilter.getParam(SearchFilter.CLUSTER_NAME); + + // Rebuild searchFilter without serviceType + if (StringUtils.isNotBlank(serviceTypeToSearch)) { + searchFilter.removeParam(SearchFilter.SERVICE_TYPE); + } + + List xObjList = searchRangerObjects(searchFilter, searchFields, sortFields, retList); + + List objectsList = null; + + if (CollectionUtils.isNotEmpty(xObjList)) { + objectsList = daoManager.getXXServiceVersionInfo().getAllWithServiceNames(); + } + + for (XXPluginInfo xObj : xObjList) { + XXServiceVersionInfo xxServiceVersionInfo = null; + boolean hasAssociatedTagService = false; + + if (CollectionUtils.isNotEmpty(objectsList)) { + for (Object[] objects : objectsList) { + if (objects.length == 2) { + if (xObj.getServiceName().equals(objects[1])) { + if (objects[0] instanceof XXServiceVersionInfo) { + xxServiceVersionInfo = (XXServiceVersionInfo) objects[0]; + + for (XXService service : servicesWithTagService) { + if (service.getName().equals(xObj.getServiceName())) { + hasAssociatedTagService = true; + break; + } + } + } else { + LOG.warn("Expected first object to be XXServiceVersionInfo, got {}", objects[0]); + } + break; + } + } else { + LOG.warn("Expected 2 objects in the list returned by getAllWithServiceNames(), received {}", objects.length); + } + } + } - private static final Logger LOG = LoggerFactory.getLogger(RangerPluginInfoService.class); + RangerPluginInfo obj = populateViewObjectWithServiceVersionInfo(xObj, xxServiceVersionInfo, hasAssociatedTagService); - @Autowired - RangerSearchUtil searchUtil; + if (StringUtils.isBlank(serviceTypeToSearch) || StringUtils.equals(serviceTypeToSearch, obj.getServiceType())) { + objList.add(obj); + } - @Autowired - RangerBizUtil bizUtil; + if (StringUtils.isNotBlank(clusterNameToSearch)) { + Map infoMap = obj.getInfo(); + Set> infoSet = infoMap.entrySet(); - @Autowired - JSONUtil jsonUtil; + for (Map.Entry info : infoSet) { + if (StringUtils.equals(info.getKey(), SearchFilter.CLUSTER_NAME)) { + if (!StringUtils.equals(info.getValue(), clusterNameToSearch)) { + objList.remove(obj); + } + break; + } + } + } + } - @Autowired - RangerDaoManager daoManager; + retList.setList(objList); - private List sortFields = new ArrayList(); - private List searchFields = new ArrayList(); + return retList; + } - RangerPluginInfoService() { + public RangerPluginInfo populateViewObject(XXPluginInfo xObj) { + RangerPluginInfo ret = new RangerPluginInfo(); - searchFields.add(new SearchField(SearchFilter.SERVICE_NAME, "obj.serviceName", SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.FULL)); - searchFields.add(new SearchField(SearchFilter.PLUGIN_HOST_NAME, "obj.hostName", SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.FULL)); - searchFields.add(new SearchField(SearchFilter.PLUGIN_APP_TYPE, "obj.appType", SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.FULL)); - searchFields.add(new SearchField(SearchFilter.PLUGIN_IP_ADDRESS, "obj.ipAddress", SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.FULL)); + ret.setId(xObj.getId()); + ret.setCreateTime(xObj.getCreateTime()); + ret.setUpdateTime(xObj.getUpdateTime()); + ret.setServiceName(xObj.getServiceName()); - sortFields.add(new SortField(SearchFilter.SERVICE_NAME, "obj.serviceName", true, SortField.SORT_ORDER.ASC)); - sortFields.add(new SortField(SearchFilter.PLUGIN_HOST_NAME, "obj.hostName", true, SortField.SORT_ORDER.ASC)); - sortFields.add(new SortField(SearchFilter.PLUGIN_APP_TYPE, "obj.appType", true, SortField.SORT_ORDER.ASC)); + String serviceType = daoManager.getXXServiceDef().findServiceDefTypeByServiceName(ret.getServiceName()); - } + if (StringUtils.isNotBlank(serviceType)) { + ret.setServiceType(serviceType); + } - public List getSearchFields() { - return searchFields; - } + ret.setHostName(xObj.getHostName()); + ret.setAppType(xObj.getAppType()); + ret.setIpAddress(xObj.getIpAddress()); + ret.setInfo(jsonStringToMap(xObj.getInfo(), null, false)); - public List getSortFields() { - return sortFields; - } + return ret; + } - public PList searchRangerPluginInfo(SearchFilter searchFilter) { - PList retList = new PList(); - List objList = new ArrayList(); + public XXPluginInfo populateDBObject(RangerPluginInfo modelObj) { + XXPluginInfo ret = new XXPluginInfo(); - List servicesWithTagService = daoManager.getXXService().getAllServicesWithTagService(); + ret.setId(modelObj.getId()); + ret.setCreateTime(modelObj.getCreateTime()); + ret.setUpdateTime(modelObj.getUpdateTime()); + ret.setServiceName(modelObj.getServiceName()); + ret.setHostName(modelObj.getHostName()); + ret.setAppType(modelObj.getAppType()); + ret.setIpAddress(modelObj.getIpAddress()); + ret.setInfo(mapToJsonString(modelObj.getInfo())); - // Rebuild searchFilter without serviceType + return ret; + } - String serviceTypeToSearch = searchFilter.getParam(SearchFilter.SERVICE_TYPE); - if (StringUtils.isNotBlank(serviceTypeToSearch)) { - searchFilter.removeParam(SearchFilter.SERVICE_TYPE); - } - String clusterNameToSearch = searchFilter.getParam(SearchFilter.CLUSTER_NAME); - - List xObjList = searchRangerObjects(searchFilter, searchFields, sortFields, retList); - - List objectsList = null; - if (CollectionUtils.isNotEmpty(xObjList)) { - objectsList = daoManager.getXXServiceVersionInfo().getAllWithServiceNames(); - } - - for (XXPluginInfo xObj : xObjList) { - XXServiceVersionInfo xxServiceVersionInfo = null; - boolean hasAssociatedTagService = false; - - if (CollectionUtils.isNotEmpty(objectsList)) { - for (Object[] objects : objectsList) { - if (objects.length == 2) { - if (xObj.getServiceName().equals(objects[1])) { - if (objects[0] instanceof XXServiceVersionInfo) { - xxServiceVersionInfo = (XXServiceVersionInfo) objects[0]; - for (XXService service : servicesWithTagService) { - if (service.getName().equals(xObj.getServiceName())) { - hasAssociatedTagService = true; - break; - } - } - } else { - LOG.warn("Expected first object to be XXServiceVersionInfo, got " + objects[0]); - } - break; - } - } else { - LOG.warn("Expected 2 objects in the list returned by getAllWithServiceNames(), received " + objects.length); - } - } - } - - RangerPluginInfo obj = populateViewObjectWithServiceVersionInfo(xObj, xxServiceVersionInfo, hasAssociatedTagService); - - if (StringUtils.isBlank(serviceTypeToSearch) || StringUtils.equals(serviceTypeToSearch, obj.getServiceType())) { - objList.add(obj); - } + private RangerPluginInfo populateViewObjectWithServiceVersionInfo(XXPluginInfo xObj, XXServiceVersionInfo xxServiceVersionInfo, boolean hasAssociatedTagService) { + RangerPluginInfo ret = new RangerPluginInfo(); + + ret.setId(xObj.getId()); + ret.setCreateTime(xObj.getCreateTime()); + ret.setUpdateTime(xObj.getUpdateTime()); + ret.setServiceName(xObj.getServiceName()); + + String serviceDefName = daoManager.getXXServiceDef().findServiceDefTypeByServiceName(ret.getServiceName()); + + if (StringUtils.isNotBlank(serviceDefName)) { + ret.setServiceType(serviceDefName); + + XXServiceDef xxServiceDef = daoManager.getXXServiceDef().findByName(serviceDefName); + + ret.setServiceTypeDisplayName(xxServiceDef.getDisplayName()); + } + + ret.setHostName(xObj.getHostName()); + ret.setAppType(xObj.getAppType()); + ret.setIpAddress(xObj.getIpAddress()); + ret.setInfo(jsonStringToMap(xObj.getInfo(), xxServiceVersionInfo, hasAssociatedTagService)); + + XXService xxService = daoManager.getXXService().findByName(ret.getServiceName()); + + if (xxService != null) { + ret.setServiceDisplayName(xxService.getDisplayName()); + } + + return ret; + } + + private List searchRangerObjects(SearchFilter searchCriteria, List searchFieldList, List sortFieldList, PList pList) { + // 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(); + } + } + + String sortClause = searchUtil.constructSortClause(searchCriteria, sortFieldList); + String queryStr = "SELECT obj FROM " + XXPluginInfo.class.getName() + " obj "; + Query query = createQuery(queryStr, sortClause, searchCriteria, searchFieldList, false); + List resultList = daoManager.getXXPluginInfo().executeQueryInSecurityContext(XXPluginInfo.class, query); + + if (pList != null) { + pList.setResultSize(resultList.size()); + pList.setPageSize(query.getMaxResults()); + pList.setSortBy(searchCriteria.getSortBy()); + pList.setSortType(searchCriteria.getSortType()); + pList.setStartIndex(query.getFirstResult()); + pList.setTotalCount(count); + } + + return resultList; + } + + private Query createQuery(String searchString, String sortString, SearchFilter searchCriteria, List searchFieldList, boolean isCountQuery) { + EntityManager em = daoManager.getEntityManager(); + + return searchUtil.createSearchQuery(em, searchString, sortString, searchCriteria, searchFieldList, false, isCountQuery); + } + + private long getCountForSearchQuery(SearchFilter searchCriteria, List searchFieldList) { + String countQueryStr = "SELECT COUNT(obj) FROM " + XXPluginInfo.class.getName() + " obj "; + Query query = createQuery(countQueryStr, null, searchCriteria, searchFieldList, true); + Long count = daoManager.getXXPluginInfo().executeCountQueryInSecurityContext(XXPluginInfo.class, query); + + if (count == null) { + return 0; + } + + return count; + } + + private String mapToJsonString(Map map) { + String ret = null; + + if (map != null) { + try { + ret = jsonUtil.readMapToString(map); + } catch (Exception excp) { + LOG.error("Failed to convert map to JSON string: {}", map, excp); + } + } + + return ret; + } + + private Map jsonStringToMap(String jsonStr, XXServiceVersionInfo xxServiceVersionInfo, boolean hasAssociatedTagService) { + Map ret = null; - if (StringUtils.isNotBlank(clusterNameToSearch)) { - Map infoMap = obj.getInfo(); - Set> infoSet = infoMap.entrySet(); - for (Map.Entry info : infoSet) { - if (StringUtils.equals(info.getKey(), SearchFilter.CLUSTER_NAME)) { - if (!StringUtils.equals(info.getValue(), clusterNameToSearch)) { - objList.remove(obj); - } - break; - } - } - } - } - - retList.setList(objList); - - return retList; - } - - public RangerPluginInfo populateViewObject(XXPluginInfo xObj) { - RangerPluginInfo ret = new RangerPluginInfo(); - ret.setId(xObj.getId()); - ret.setCreateTime(xObj.getCreateTime()); - ret.setUpdateTime(xObj.getUpdateTime()); - ret.setServiceName(xObj.getServiceName()); - - String serviceType = daoManager.getXXServiceDef().findServiceDefTypeByServiceName(ret.getServiceName()); - if (StringUtils.isNotBlank(serviceType)) { - ret.setServiceType(serviceType); + try { + ret = jsonUtil.jsonToMap(jsonStr); + + if (xxServiceVersionInfo != null) { + Long latestPolicyVersion = xxServiceVersionInfo.getPolicyVersion(); + Date lastPolicyUpdateTime = xxServiceVersionInfo.getPolicyUpdateTime(); + Long latestTagVersion = xxServiceVersionInfo.getTagVersion(); + Date lastTagUpdateTime = xxServiceVersionInfo.getTagUpdateTime(); + Long latestGdsVersion = xxServiceVersionInfo.getGdsVersion(); + Date lastGdsUpdateTime = xxServiceVersionInfo.getGdsUpdateTime(); + + ret.put(RangerPluginInfo.RANGER_ADMIN_LATEST_POLICY_VERSION, Long.toString(latestPolicyVersion)); + ret.put(RangerPluginInfo.RANGER_ADMIN_LAST_POLICY_UPDATE_TIME, Long.toString(lastPolicyUpdateTime.getTime())); + ret.put(RangerPluginInfo.RANGER_ADMIN_LATEST_GDS_VERSION, Long.toString(latestGdsVersion)); + ret.put(RangerPluginInfo.RANGER_ADMIN_LAST_GDS_UPDATE_TIME, Long.toString(lastGdsUpdateTime.getTime())); + + if (hasAssociatedTagService) { + ret.put(RangerPluginInfo.RANGER_ADMIN_LATEST_TAG_VERSION, Long.toString(latestTagVersion)); + ret.put(RangerPluginInfo.RANGER_ADMIN_LAST_TAG_UPDATE_TIME, Long.toString(lastTagUpdateTime.getTime())); + } else { + ret.remove(RangerPluginInfo.RANGER_ADMIN_LATEST_TAG_VERSION); + ret.remove(RangerPluginInfo.RANGER_ADMIN_LAST_TAG_UPDATE_TIME); } - ret.setHostName(xObj.getHostName()); - ret.setAppType(xObj.getAppType()); - ret.setIpAddress(xObj.getIpAddress()); - ret.setInfo(jsonStringToMap(xObj.getInfo(), null, false)); - return ret; - } - - public XXPluginInfo populateDBObject(RangerPluginInfo modelObj) { - XXPluginInfo ret = new XXPluginInfo(); - ret.setId(modelObj.getId()); - ret.setCreateTime(modelObj.getCreateTime()); - ret.setUpdateTime(modelObj.getUpdateTime()); - ret.setServiceName(modelObj.getServiceName()); - ret.setHostName(modelObj.getHostName()); - ret.setAppType(modelObj.getAppType()); - ret.setIpAddress(modelObj.getIpAddress()); - ret.setInfo(mapToJsonString(modelObj.getInfo())); - return ret; - } - - private RangerPluginInfo populateViewObjectWithServiceVersionInfo(XXPluginInfo xObj, XXServiceVersionInfo xxServiceVersionInfo, boolean hasAssociatedTagService) { - RangerPluginInfo ret = new RangerPluginInfo(); - ret.setId(xObj.getId()); - ret.setCreateTime(xObj.getCreateTime()); - ret.setUpdateTime(xObj.getUpdateTime()); - ret.setServiceName(xObj.getServiceName()); - - String serviceDefName = daoManager.getXXServiceDef().findServiceDefTypeByServiceName(ret.getServiceName()); - if (StringUtils.isNotBlank(serviceDefName)) { - ret.setServiceType(serviceDefName); - XXServiceDef xxServiceDef = daoManager.getXXServiceDef().findByName(serviceDefName); - - ret.setServiceTypeDisplayName(xxServiceDef.getDisplayName()); - } - ret.setHostName(xObj.getHostName()); - ret.setAppType(xObj.getAppType()); - ret.setIpAddress(xObj.getIpAddress()); - ret.setInfo(jsonStringToMap(xObj.getInfo(), xxServiceVersionInfo, hasAssociatedTagService)); - - XXService xxService = daoManager.getXXService().findByName(ret.getServiceName()); - if (xxService != null) { - ret.setServiceDisplayName(xxService.getDisplayName()); - } - return ret; - } - - private List searchRangerObjects(SearchFilter searchCriteria, List searchFieldList, List sortFieldList, PList pList) { - - // 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(); - } - } - - String sortClause = searchUtil.constructSortClause(searchCriteria, sortFieldList); - - String queryStr = "SELECT obj FROM " + XXPluginInfo.class.getName() + " obj "; - Query query = createQuery(queryStr, sortClause, searchCriteria, searchFieldList, false); - - List resultList = daoManager.getXXPluginInfo().executeQueryInSecurityContext(XXPluginInfo.class, query); - - if (pList != null) { - pList.setResultSize(resultList.size()); - pList.setPageSize(query.getMaxResults()); - pList.setSortBy(searchCriteria.getSortBy()); - pList.setSortType(searchCriteria.getSortType()); - pList.setStartIndex(query.getFirstResult()); - pList.setTotalCount(count); - } - return resultList; - } - - private Query createQuery(String searchString, String sortString, SearchFilter searchCriteria, - List searchFieldList, boolean isCountQuery) { - - EntityManager em = daoManager.getEntityManager(); - return searchUtil.createSearchQuery(em, searchString, sortString, searchCriteria, - searchFieldList, false, isCountQuery); - } - - private long getCountForSearchQuery(SearchFilter searchCriteria, List searchFieldList) { - - String countQueryStr = "SELECT COUNT(obj) FROM " + XXPluginInfo.class.getName() + " obj "; - - Query query = createQuery(countQueryStr, null, searchCriteria, searchFieldList, true); - Long count = daoManager.getXXPluginInfo().executeCountQueryInSecurityContext(XXPluginInfo.class, query); - - if (count == null) { - return 0; - } - return count; - } - - private String mapToJsonString(Map map) { - String ret = null; - - if(map != null) { - try { - ret = jsonUtil.readMapToString(map); - } catch(Exception excp) { - LOG.error("Failed to convert map to JSON string: '" + map + "'", excp); - } - } - - return ret; - } - - private Map jsonStringToMap(String jsonStr, XXServiceVersionInfo xxServiceVersionInfo, boolean hasAssociatedTagService) { - - Map ret = null; - - try { - ret = jsonUtil.jsonToMap(jsonStr); - - if (xxServiceVersionInfo != null) { - Long latestPolicyVersion = xxServiceVersionInfo.getPolicyVersion(); - Date lastPolicyUpdateTime = xxServiceVersionInfo.getPolicyUpdateTime(); - Long latestTagVersion = xxServiceVersionInfo.getTagVersion(); - Date lastTagUpdateTime = xxServiceVersionInfo.getTagUpdateTime(); - Long latestGdsVersion = xxServiceVersionInfo.getGdsVersion(); - Date lastGdsUpdateTime = xxServiceVersionInfo.getGdsUpdateTime(); - - ret.put(RangerPluginInfo.RANGER_ADMIN_LATEST_POLICY_VERSION, Long.toString(latestPolicyVersion)); - ret.put(RangerPluginInfo.RANGER_ADMIN_LAST_POLICY_UPDATE_TIME, Long.toString(lastPolicyUpdateTime.getTime())); - ret.put(RangerPluginInfo.RANGER_ADMIN_LATEST_GDS_VERSION, Long.toString(latestGdsVersion)); - ret.put(RangerPluginInfo.RANGER_ADMIN_LAST_GDS_UPDATE_TIME, Long.toString(lastGdsUpdateTime.getTime())); - if (hasAssociatedTagService) { - ret.put(RangerPluginInfo.RANGER_ADMIN_LATEST_TAG_VERSION, Long.toString(latestTagVersion)); - ret.put(RangerPluginInfo.RANGER_ADMIN_LAST_TAG_UPDATE_TIME, Long.toString(lastTagUpdateTime.getTime())); - } else { - ret.remove(RangerPluginInfo.RANGER_ADMIN_LATEST_TAG_VERSION); - ret.remove(RangerPluginInfo.RANGER_ADMIN_LAST_TAG_UPDATE_TIME); - } - } - } - catch(Exception excp) { - LOG.error("Failed to convert JSON string to Map: '" + jsonStr + "'", excp); - } - - return ret; - } -} \ No newline at end of file + } + } catch (Exception excp) { + LOG.error("Failed to convert JSON string to Map: {}", jsonStr, excp); + } + + return ret; + } +} diff --git a/security-admin/src/main/java/org/apache/ranger/service/RangerPolicyLabelsService.java b/security-admin/src/main/java/org/apache/ranger/service/RangerPolicyLabelsService.java index ece9997e75..e9e21a8cba 100644 --- a/security-admin/src/main/java/org/apache/ranger/service/RangerPolicyLabelsService.java +++ b/security-admin/src/main/java/org/apache/ranger/service/RangerPolicyLabelsService.java @@ -31,41 +31,36 @@ @Service @Scope("singleton") -public class RangerPolicyLabelsService - extends RangerBaseModelService { +public class RangerPolicyLabelsService extends RangerBaseModelService { + @Autowired + RangerAuditFields rangerAuditFields; - @Autowired - RangerAuditFields rangerAuditFields; + public RangerPolicyLabelsService() { + super(); - public RangerPolicyLabelsService() { - super(); - searchFields.add( - new SearchField(SearchFilter.POLICY_LABEL, "obj.policyLabel", DATA_TYPE.STRING, SEARCH_TYPE.PARTIAL)); - sortFields.add(new SortField(SearchFilter.POLICY_LABEL_ID, "obj.id", true, SORT_ORDER.ASC)); - } + searchFields.add(new SearchField(SearchFilter.POLICY_LABEL, "obj.policyLabel", DATA_TYPE.STRING, SEARCH_TYPE.PARTIAL)); + sortFields.add(new SortField(SearchFilter.POLICY_LABEL_ID, "obj.id", true, SORT_ORDER.ASC)); + } - @Override - protected T mapViewToEntityBean(V viewBean, T t, int OPERATION_CONTEXT) { - // TODO Auto-generated method stub - return null; - } + @Override + protected T mapViewToEntityBean(V viewBean, T t, int operationContext) { + // TODO Auto-generated method stub + return null; + } - @Override - protected V mapEntityToViewBean(V viewBean, T t) { - // TODO Auto-generated method stub - return null; - } + @Override + protected V mapEntityToViewBean(V viewBean, T t) { + // TODO Auto-generated method stub + return null; + } - @Override - protected void validateForCreate(V vObj) { - // TODO Auto-generated method stub - - } - - @Override - protected void validateForUpdate(V vObj, T entityObj) { - // TODO Auto-generated method stub - - } + @Override + protected void validateForCreate(V vObj) { + // TODO Auto-generated method stub + } + @Override + protected void validateForUpdate(V vObj, T entityObj) { + // TODO Auto-generated method stub + } } diff --git a/security-admin/src/main/java/org/apache/ranger/service/RangerPolicyService.java b/security-admin/src/main/java/org/apache/ranger/service/RangerPolicyService.java index a0381da8bc..193face94f 100644 --- a/security-admin/src/main/java/org/apache/ranger/service/RangerPolicyService.java +++ b/security-admin/src/main/java/org/apache/ranger/service/RangerPolicyService.java @@ -17,7 +17,6 @@ package org.apache.ranger.service; - import org.apache.ranger.biz.RangerPolicyRetriever; import org.apache.ranger.entity.XXPolicy; import org.apache.ranger.plugin.model.RangerPolicy; @@ -27,39 +26,38 @@ @Service @Scope("singleton") public class RangerPolicyService extends RangerPolicyServiceBase { - - public RangerPolicyService() { - super(); - } - - @Override - protected XXPolicy mapViewToEntityBean(RangerPolicy vObj, XXPolicy xObj, int OPERATION_CONTEXT) { - return super.mapViewToEntityBean(vObj, xObj, OPERATION_CONTEXT); - } - - @Override - protected RangerPolicy mapEntityToViewBean(RangerPolicy vObj, XXPolicy xObj) { - return super.mapEntityToViewBean(vObj, xObj); - } - - @Override - protected void validateForCreate(RangerPolicy vObj) { - // TODO Auto-generated method stub - } - - @Override - protected void validateForUpdate(RangerPolicy vObj, XXPolicy entityObj) { - // TODO Auto-generated method stub - } - - @Override - protected RangerPolicy populateViewBean(XXPolicy xPolicy) { - RangerPolicyRetriever retriever = new RangerPolicyRetriever(daoMgr); - - return retriever.getPolicy(xPolicy); - } - - public RangerPolicy getPopulatedViewObject(XXPolicy xPolicy) { - return this.populateViewBean(xPolicy); - } + public RangerPolicyService() { + super(); + } + + public RangerPolicy getPopulatedViewObject(XXPolicy xPolicy) { + return this.populateViewBean(xPolicy); + } + + @Override + protected XXPolicy mapViewToEntityBean(RangerPolicy vObj, XXPolicy xObj, int operationContext) { + return super.mapViewToEntityBean(vObj, xObj, operationContext); + } + + @Override + protected RangerPolicy mapEntityToViewBean(RangerPolicy vObj, XXPolicy xObj) { + return super.mapEntityToViewBean(vObj, xObj); + } + + @Override + protected RangerPolicy populateViewBean(XXPolicy xPolicy) { + RangerPolicyRetriever retriever = new RangerPolicyRetriever(daoMgr); + + return retriever.getPolicy(xPolicy); + } + + @Override + protected void validateForCreate(RangerPolicy vObj) { + // TODO Auto-generated method stub + } + + @Override + protected void validateForUpdate(RangerPolicy vObj, XXPolicy entityObj) { + // TODO Auto-generated method stub + } } diff --git a/security-admin/src/main/java/org/apache/ranger/service/RangerPolicyServiceBase.java b/security-admin/src/main/java/org/apache/ranger/service/RangerPolicyServiceBase.java index 7d5727a766..03ec978acd 100755 --- a/security-admin/src/main/java/org/apache/ranger/service/RangerPolicyServiceBase.java +++ b/security-admin/src/main/java/org/apache/ranger/service/RangerPolicyServiceBase.java @@ -20,15 +20,20 @@ import org.apache.commons.collections.MapUtils; import org.apache.commons.lang.StringUtils; import org.apache.ranger.authorization.utils.JsonUtils; -import org.apache.ranger.common.*; +import org.apache.ranger.common.AppConstants; +import org.apache.ranger.common.GUIDUtil; +import org.apache.ranger.common.MessageEnums; +import org.apache.ranger.common.SearchField; import org.apache.ranger.common.SearchField.DATA_TYPE; import org.apache.ranger.common.SearchField.SEARCH_TYPE; +import org.apache.ranger.common.SortField; import org.apache.ranger.common.SortField.SORT_ORDER; import org.apache.ranger.common.view.VTrxLogAttr; import org.apache.ranger.entity.XXPolicyBase; import org.apache.ranger.entity.XXSecurityZone; import org.apache.ranger.entity.XXService; import org.apache.ranger.entity.XXServiceDef; +import org.apache.ranger.plugin.model.RangerBaseModelObject; import org.apache.ranger.plugin.model.RangerPolicy; import org.apache.ranger.plugin.model.RangerSecurityZone; import org.apache.ranger.plugin.util.SearchFilter; @@ -37,236 +42,228 @@ import java.util.Map; public abstract class RangerPolicyServiceBase extends RangerAuditedModelService { - public static final String OPTION_POLICY_VALIDITY_SCHEDULES = "POLICY_VALIDITY_SCHEDULES"; @Autowired - GUIDUtil guidUtil; - - public RangerPolicyServiceBase() { - super(AppConstants.CLASS_TYPE_RANGER_POLICY, AppConstants.CLASS_TYPE_XA_SERVICE); - - searchFields.add(new SearchField(SearchFilter.SERVICE_TYPE, "xSvcDef.name", DATA_TYPE.STRING, SEARCH_TYPE.FULL, - "XXServiceDef xSvcDef, XXService xSvc", "xSvc.type = xSvcDef.id and xSvc.id = obj.service")); - searchFields.add(new SearchField(SearchFilter.SERVICE_TYPE_ID, "xSvc.type", DATA_TYPE.INTEGER, - SEARCH_TYPE.FULL, "XXService xSvc", "xSvc.id = obj.service")); - searchFields.add(new SearchField(SearchFilter.SERVICE_NAME, "xSvc.name", DATA_TYPE.STRING, SEARCH_TYPE.FULL, - "XXService xSvc", "xSvc.id = obj.service")); - searchFields.add(new SearchField(SearchFilter.SERVICE_ID, "xSvc.id", DATA_TYPE.INTEGER, SEARCH_TYPE.FULL, - "XXService xSvc", "xSvc.id = obj.service")); - searchFields - .add(new SearchField(SearchFilter.IS_ENABLED, "obj.isEnabled", DATA_TYPE.BOOLEAN, SEARCH_TYPE.FULL)); - //might need updation - /*searchFields.add(new SearchField(SearchFilter.IS_RECURSIVE,"xPolRes.isRecursive",DATA_TYPE.BOOLEAN,SEARCH_TYPE.FULL, - "XXPolicyResource xPolRes","obj.id=xPolRes.policyId"));*/ - searchFields.add(new SearchField(SearchFilter.POLICY_ID, "obj.id", DATA_TYPE.INTEGER, SEARCH_TYPE.FULL)); - searchFields.add(new SearchField(SearchFilter.POLICY_NAME, "obj.name", DATA_TYPE.STRING, SEARCH_TYPE.FULL)); - searchFields.add(new SearchField(SearchFilter.GUID, "obj.guid", DATA_TYPE.STRING, SEARCH_TYPE.FULL)); - searchFields.add(new SearchField(SearchFilter.USER, "xUser.name", DATA_TYPE.STRING, SEARCH_TYPE.FULL, - "XXUser xUser, XXPolicyRefUser refUser", "obj.id = refUser.policyId " - + "and xUser.id = refUser.userId")); - searchFields.add(new SearchField(SearchFilter.GROUP, "xGrp.name", DATA_TYPE.STRING, SEARCH_TYPE.FULL, - "XXGroup xGrp , XXPolicyRefGroup refGroup", "obj.id = refGroup.policyId " - + "and xGrp.id = refGroup.groupId")); - searchFields.add(new SearchField(SearchFilter.ROLE, "xRole.name", DATA_TYPE.STRING, SEARCH_TYPE.FULL, - "XXRole xRole , XXPolicyRefRole refRole", "obj.id = refRole.policyId " - + "and xRole.id = refRole.roleId")); - //might need updation - /*searchFields.add(new SearchField(SearchFilter.POL_RESOURCE, "resMap.value", DATA_TYPE.STRING, - SEARCH_TYPE.PARTIAL, "XXPolicyResourceMap resMap, XXPolicyResource polRes", - "resMap.resourceId = polRes.id and polRes.policyId = obj.id")); - /*searchFields.add(new SearchField(SearchFilter.POLICY_LABELS_PARTIAL, "obj.label_name", DATA_TYPE.STRING, - SEARCH_TYPE.PARTIAL));*/ - searchFields.add(new SearchField(SearchFilter.POLICY_NAME_PARTIAL, "obj.name", DATA_TYPE.STRING, - SEARCH_TYPE.PARTIAL)); - searchFields.add(new SearchField(SearchFilter.POLICY_TYPE, "obj.policyType", DATA_TYPE.INTEGER, SEARCH_TYPE.FULL)); - searchFields.add(new SearchField(SearchFilter.ZONE_NAME, "xZone.name", DATA_TYPE.STRING, SEARCH_TYPE.FULL, - "XXSecurityZone xZone", "xZone.id = obj.zoneId")); - searchFields.add(new SearchField(SearchFilter.ZONE_ID, "xZone.id", DATA_TYPE.INTEGER, SEARCH_TYPE.FULL, - "XXSecurityZone xZone", "xZone.id = obj.zoneId")); - - sortFields.add(new SortField(SearchFilter.CREATE_TIME, "obj.createTime")); - sortFields.add(new SortField(SearchFilter.UPDATE_TIME, "obj.updateTime")); - sortFields.add(new SortField(SearchFilter.POLICY_ID, "obj.id", true, SORT_ORDER.ASC)); - sortFields.add(new SortField(SearchFilter.POLICY_NAME, "obj.name")); - - trxLogAttrs.put("name", new VTrxLogAttr("name", "Policy Name", false, true)); - trxLogAttrs.put("description", new VTrxLogAttr("description", "Policy Description")); - trxLogAttrs.put("isEnabled", new VTrxLogAttr("isEnabled", "Policy Status")); - trxLogAttrs.put("resources", new VTrxLogAttr("resources", "Policy Resources")); - trxLogAttrs.put("additionalResources", new VTrxLogAttr("additionalResources", "Policy Additional Resources")); - trxLogAttrs.put("conditions", new VTrxLogAttr("conditions", "Policy Conditions")); - trxLogAttrs.put("policyItems", new VTrxLogAttr("policyItems", "Policy Items")); - trxLogAttrs.put("denyPolicyItems", new VTrxLogAttr("denyPolicyItems", "DenyPolicy Items")); - trxLogAttrs.put("allowExceptions", new VTrxLogAttr("allowExceptions", "Allow Exceptions")); - trxLogAttrs.put("denyExceptions", new VTrxLogAttr("denyExceptions", "Deny Exceptions")); - trxLogAttrs.put("dataMaskPolicyItems", new VTrxLogAttr("dataMaskPolicyItems", "Masked Policy Items")); - trxLogAttrs.put("rowFilterPolicyItems", new VTrxLogAttr("rowFilterPolicyItems", "Row level filter Policy Items")); - trxLogAttrs.put("isAuditEnabled", new VTrxLogAttr("isAuditEnabled", "Audit Status")); - trxLogAttrs.put("policyLabels", new VTrxLogAttr("policyLabels", "Policy Labels")); - trxLogAttrs.put("validitySchedules", new VTrxLogAttr("validitySchedules", "Validity Schedules")); - trxLogAttrs.put("policyPriority", new VTrxLogAttr("policyPriority", "Priority")); - trxLogAttrs.put("zoneName", new VTrxLogAttr("zoneName", "Zone Name")); - trxLogAttrs.put("isDenyAllElse", new VTrxLogAttr("isDenyAllElse", "Deny All Other Accesses")); - } - - @Override - public String getParentObjectName(V obj, V oldObj) { - return obj != null ? obj.getService() : null; - } - - @Override - public Long getParentObjectId(V obj, V oldObj) { - String serviceName = obj != null ? obj.getService() : null; - XXService service = serviceName != null ? daoMgr.getXXService().findByName(obj.getService()) : null; - - return service != null ? service.getId() : null; - } - - @Override - public boolean skipTrxLogForAttribute(V obj, V oldObj, VTrxLogAttr trxLogAttr) { - final boolean ret; - - int policyType = (obj == null || obj.getPolicyType() == null) ? RangerPolicy.POLICY_TYPE_ACCESS : obj.getPolicyType(); - - switch (trxLogAttr.getAttribName()) { - case "dataMaskPolicyItems": - ret = policyType != RangerPolicy.POLICY_TYPE_DATAMASK; - break; - - case "rowFilterPolicyItems": - ret = policyType != RangerPolicy.POLICY_TYPE_ROWFILTER; - break; - - case "policyItems": - case "allowExceptions": - case "denyPolicyItems": - case "denyExceptions": - case "isDenyAllElse": + GUIDUtil guidUtil; + + public RangerPolicyServiceBase() { + super(AppConstants.CLASS_TYPE_RANGER_POLICY, AppConstants.CLASS_TYPE_XA_SERVICE); + + searchFields.add(new SearchField(SearchFilter.SERVICE_TYPE, "xSvcDef.name", DATA_TYPE.STRING, SEARCH_TYPE.FULL, "XXServiceDef xSvcDef, XXService xSvc", "xSvc.type = xSvcDef.id and xSvc.id = obj.service")); + searchFields.add(new SearchField(SearchFilter.SERVICE_TYPE_ID, "xSvc.type", DATA_TYPE.INTEGER, SEARCH_TYPE.FULL, "XXService xSvc", "xSvc.id = obj.service")); + searchFields.add(new SearchField(SearchFilter.SERVICE_NAME, "xSvc.name", DATA_TYPE.STRING, SEARCH_TYPE.FULL, "XXService xSvc", "xSvc.id = obj.service")); + searchFields.add(new SearchField(SearchFilter.SERVICE_ID, "xSvc.id", DATA_TYPE.INTEGER, SEARCH_TYPE.FULL, "XXService xSvc", "xSvc.id = obj.service")); + searchFields.add(new SearchField(SearchFilter.IS_ENABLED, "obj.isEnabled", DATA_TYPE.BOOLEAN, SEARCH_TYPE.FULL)); + searchFields.add(new SearchField(SearchFilter.POLICY_ID, "obj.id", DATA_TYPE.INTEGER, SEARCH_TYPE.FULL)); + searchFields.add(new SearchField(SearchFilter.POLICY_NAME, "obj.name", DATA_TYPE.STRING, SEARCH_TYPE.FULL)); + searchFields.add(new SearchField(SearchFilter.GUID, "obj.guid", DATA_TYPE.STRING, SEARCH_TYPE.FULL)); + searchFields.add(new SearchField(SearchFilter.USER, "xUser.name", DATA_TYPE.STRING, SEARCH_TYPE.FULL, "XXUser xUser, XXPolicyRefUser refUser", "obj.id = refUser.policyId and xUser.id = refUser.userId")); + searchFields.add(new SearchField(SearchFilter.GROUP, "xGrp.name", DATA_TYPE.STRING, SEARCH_TYPE.FULL, "XXGroup xGrp , XXPolicyRefGroup refGroup", "obj.id = refGroup.policyId and xGrp.id = refGroup.groupId")); + searchFields.add(new SearchField(SearchFilter.ROLE, "xRole.name", DATA_TYPE.STRING, SEARCH_TYPE.FULL, "XXRole xRole , XXPolicyRefRole refRole", "obj.id = refRole.policyId and xRole.id = refRole.roleId")); + searchFields.add(new SearchField(SearchFilter.POLICY_NAME_PARTIAL, "obj.name", DATA_TYPE.STRING, SEARCH_TYPE.PARTIAL)); + searchFields.add(new SearchField(SearchFilter.POLICY_TYPE, "obj.policyType", DATA_TYPE.INTEGER, SEARCH_TYPE.FULL)); + searchFields.add(new SearchField(SearchFilter.ZONE_NAME, "xZone.name", DATA_TYPE.STRING, SEARCH_TYPE.FULL, "XXSecurityZone xZone", "xZone.id = obj.zoneId")); + searchFields.add(new SearchField(SearchFilter.ZONE_ID, "xZone.id", DATA_TYPE.INTEGER, SEARCH_TYPE.FULL, "XXSecurityZone xZone", "xZone.id = obj.zoneId")); + + sortFields.add(new SortField(SearchFilter.CREATE_TIME, "obj.createTime")); + sortFields.add(new SortField(SearchFilter.UPDATE_TIME, "obj.updateTime")); + sortFields.add(new SortField(SearchFilter.POLICY_ID, "obj.id", true, SORT_ORDER.ASC)); + sortFields.add(new SortField(SearchFilter.POLICY_NAME, "obj.name")); + + trxLogAttrs.put("name", new VTrxLogAttr("name", "Policy Name", false, true)); + trxLogAttrs.put("description", new VTrxLogAttr("description", "Policy Description")); + trxLogAttrs.put("isEnabled", new VTrxLogAttr("isEnabled", "Policy Status")); + trxLogAttrs.put("resources", new VTrxLogAttr("resources", "Policy Resources")); + trxLogAttrs.put("additionalResources", new VTrxLogAttr("additionalResources", "Policy Additional Resources")); + trxLogAttrs.put("conditions", new VTrxLogAttr("conditions", "Policy Conditions")); + trxLogAttrs.put("policyItems", new VTrxLogAttr("policyItems", "Policy Items")); + trxLogAttrs.put("denyPolicyItems", new VTrxLogAttr("denyPolicyItems", "DenyPolicy Items")); + trxLogAttrs.put("allowExceptions", new VTrxLogAttr("allowExceptions", "Allow Exceptions")); + trxLogAttrs.put("denyExceptions", new VTrxLogAttr("denyExceptions", "Deny Exceptions")); + trxLogAttrs.put("dataMaskPolicyItems", new VTrxLogAttr("dataMaskPolicyItems", "Masked Policy Items")); + trxLogAttrs.put("rowFilterPolicyItems", new VTrxLogAttr("rowFilterPolicyItems", "Row level filter Policy Items")); + trxLogAttrs.put("isAuditEnabled", new VTrxLogAttr("isAuditEnabled", "Audit Status")); + trxLogAttrs.put("policyLabels", new VTrxLogAttr("policyLabels", "Policy Labels")); + trxLogAttrs.put("validitySchedules", new VTrxLogAttr("validitySchedules", "Validity Schedules")); + trxLogAttrs.put("policyPriority", new VTrxLogAttr("policyPriority", "Priority")); + trxLogAttrs.put("zoneName", new VTrxLogAttr("zoneName", "Zone Name")); + trxLogAttrs.put("isDenyAllElse", new VTrxLogAttr("isDenyAllElse", "Deny All Other Accesses")); + } + + @Override + public String getParentObjectName(V obj, V oldObj) { + return obj != null ? obj.getService() : null; + } + + @Override + public Long getParentObjectId(V obj, V oldObj) { + String serviceName = obj != null ? obj.getService() : null; + XXService service = serviceName != null ? daoMgr.getXXService().findByName(obj.getService()) : null; + + return service != null ? service.getId() : null; + } + + @Override + public boolean skipTrxLogForAttribute(V obj, V oldObj, VTrxLogAttr trxLogAttr) { + final boolean ret; + + int policyType = (obj == null || obj.getPolicyType() == null) ? RangerPolicy.POLICY_TYPE_ACCESS : obj.getPolicyType(); + + switch (trxLogAttr.getAttribName()) { + case "dataMaskPolicyItems": + ret = policyType != RangerPolicy.POLICY_TYPE_DATAMASK; + break; + + case "rowFilterPolicyItems": + ret = policyType != RangerPolicy.POLICY_TYPE_ROWFILTER; + break; + + case "policyItems": + case "allowExceptions": + case "denyPolicyItems": + case "denyExceptions": + case "isDenyAllElse": ret = policyType != RangerPolicy.POLICY_TYPE_ACCESS; - break; - - default: - ret = false; - break; - } - - return ret; - } - - @Override - protected T mapViewToEntityBean(V vObj, T xObj, int OPERATION_CONTEXT) { - XXService xService = daoMgr.getXXService().findByName(vObj.getService()); - if (xService == null) { - throw restErrorUtil.createRESTException("No corresponding service found for policyName: " + vObj.getName() - + "Service Not Found : " + vObj.getService(), MessageEnums.INVALID_INPUT_DATA); - } - Long zoneId = convertZoneNameToZoneId(vObj.getZoneName(), vObj); - xObj.setZoneId(zoneId); - - XXServiceDef xServiceDef = daoMgr.getXXServiceDef().getById(xService.getType()); - if (xServiceDef != null) { - vObj.setServiceType(xServiceDef.getName()); - } - - String guid = vObj.getGuid(); - if (StringUtils.isEmpty(guid)) { - guid = guidUtil.genGUID(); - vObj.setGuid(guid); - } - Integer policyPriority = vObj.getPolicyPriority(); - if (policyPriority == null) { - policyPriority = RangerPolicy.POLICY_PRIORITY_NORMAL; - vObj.setPolicyPriority(policyPriority); - } - Integer policyType = vObj.getPolicyType(); - if (policyType == null) { - policyType = RangerPolicy.POLICY_TYPE_ACCESS; - vObj.setPolicyType(policyType); - } - - xObj.setGuid(guid); - xObj.setVersion(vObj.getVersion()); - xObj.setService(xService.getId()); - xObj.setName(StringUtils.trim(vObj.getName())); - xObj.setPolicyType(policyType); - xObj.setPolicyPriority(policyPriority); - xObj.setDescription(vObj.getDescription()); - xObj.setResourceSignature(vObj.getResourceSignature()); - xObj.setIsAuditEnabled(vObj.getIsAuditEnabled()); - xObj.setIsEnabled(vObj.getIsEnabled()); - - String validitySchedules = JsonUtils.listToJson(vObj.getValiditySchedules()); - Map options = vObj.getOptions(); - - if (StringUtils.isNotBlank(validitySchedules)) { - options = vObj.getUpdatableMap(options); - options.put(OPTION_POLICY_VALIDITY_SCHEDULES, validitySchedules); - } else if (MapUtils.isNotEmpty(options)) { - options.remove(OPTION_POLICY_VALIDITY_SCHEDULES); - } - - xObj.setOptions(JsonUtils.mapToJson(options)); - - xObj.setPolicyText(JsonUtils.objectToJson(vObj)); - - return xObj; - } - - @Override - protected V mapEntityToViewBean(V vObj, T xObj) { - XXService xService = daoMgr.getXXService().getById(xObj.getService()); - XXServiceDef xServiceDef = daoMgr.getXXServiceDef().getById(xService.getType()); - vObj.setGuid(xObj.getGuid()); - vObj.setVersion(xObj.getVersion()); - vObj.setService(xService.getName()); - vObj.setServiceType(xServiceDef.getName()); - vObj.setName(StringUtils.trim(xObj.getName())); - vObj.setPolicyType(xObj.getPolicyType() == null ? RangerPolicy.POLICY_TYPE_ACCESS : xObj.getPolicyType()); - vObj.setPolicyPriority(xObj.getPolicyPriority() == null ? RangerPolicy.POLICY_PRIORITY_NORMAL : xObj.getPolicyPriority()); - vObj.setDescription(xObj.getDescription()); - vObj.setResourceSignature(xObj.getResourceSignature()); - vObj.setIsEnabled(xObj.getIsEnabled()); - vObj.setIsAuditEnabled(xObj.getIsAuditEnabled()); - String zoneName = convertZoneIdToZoneName(xObj.getZoneId(), vObj); - vObj.setZoneName(zoneName); - - String policyText = xObj.getPolicyText(); - - RangerPolicy ret = JsonUtils.jsonToObject(policyText, RangerPolicy.class); - - if (ret != null) { - vObj.setOptions(ret.getOptions()); - vObj.setValiditySchedules(ret.getValiditySchedules()); - vObj.setPolicyLabels(ret.getPolicyLabels()); - } - - return vObj; - } - - private Long convertZoneNameToZoneId(String zoneName, V vObj) { - if (StringUtils.isEmpty(zoneName)) return RangerSecurityZone.RANGER_UNZONED_SECURITY_ZONE_ID; - XXSecurityZone zone = daoMgr.getXXSecurityZoneDao().findByZoneName(zoneName); - if (zone == null) { - throw restErrorUtil.createRESTException("No corresponding zone found for policyName: " + vObj.getName() - + "Zone Not Found : " + zoneName, MessageEnums.INVALID_INPUT_DATA); - } - return zone.getId(); - } - - private String convertZoneIdToZoneName(Long zoneId, V vObj) { - if (zoneId == null) { - throw restErrorUtil.createRESTException("No corresponding zone found for policyName: " + vObj.getName() - + "Zone Not Found : " + zoneId, MessageEnums.INVALID_INPUT_DATA); - } - if (zoneId.equals(RangerSecurityZone.RANGER_UNZONED_SECURITY_ZONE_ID)) { - return StringUtils.EMPTY; - } - XXSecurityZone zone = daoMgr.getXXSecurityZoneDao().findByZoneId(zoneId); - if (zone == null) { - throw restErrorUtil.createRESTException("No corresponding zone found for policyName: " + vObj.getName() - + "Zone Not Found : " + zoneId, MessageEnums.INVALID_INPUT_DATA); - } - return zone.getName(); - } + break; + + default: + ret = false; + break; + } + + return ret; + } + + @Override + protected T mapViewToEntityBean(V vObj, T xObj, int operationContext) { + XXService xService = daoMgr.getXXService().findByName(vObj.getService()); + + if (xService == null) { + throw restErrorUtil.createRESTException("No corresponding service found for policyName: " + vObj.getName() + "Service Not Found : " + vObj.getService(), MessageEnums.INVALID_INPUT_DATA); + } + + Long zoneId = convertZoneNameToZoneId(vObj.getZoneName(), vObj); + + xObj.setZoneId(zoneId); + + XXServiceDef xServiceDef = daoMgr.getXXServiceDef().getById(xService.getType()); + + if (xServiceDef != null) { + vObj.setServiceType(xServiceDef.getName()); + } + + String guid = vObj.getGuid(); + + if (StringUtils.isEmpty(guid)) { + guid = guidUtil.genGUID(); + vObj.setGuid(guid); + } + + Integer policyPriority = vObj.getPolicyPriority(); + + if (policyPriority == null) { + policyPriority = RangerPolicy.POLICY_PRIORITY_NORMAL; + vObj.setPolicyPriority(policyPriority); + } + + Integer policyType = vObj.getPolicyType(); + + if (policyType == null) { + policyType = RangerPolicy.POLICY_TYPE_ACCESS; + vObj.setPolicyType(policyType); + } + + xObj.setGuid(guid); + xObj.setVersion(vObj.getVersion()); + xObj.setService(xService.getId()); + xObj.setName(StringUtils.trim(vObj.getName())); + xObj.setPolicyType(policyType); + xObj.setPolicyPriority(policyPriority); + xObj.setDescription(vObj.getDescription()); + xObj.setResourceSignature(vObj.getResourceSignature()); + xObj.setIsAuditEnabled(vObj.getIsAuditEnabled()); + xObj.setIsEnabled(vObj.getIsEnabled()); + + String validitySchedules = JsonUtils.listToJson(vObj.getValiditySchedules()); + Map options = vObj.getOptions(); + + if (StringUtils.isNotBlank(validitySchedules)) { + options = RangerBaseModelObject.getUpdatableMap(options); + options.put(OPTION_POLICY_VALIDITY_SCHEDULES, validitySchedules); + } else if (MapUtils.isNotEmpty(options)) { + options.remove(OPTION_POLICY_VALIDITY_SCHEDULES); + } + + xObj.setOptions(JsonUtils.mapToJson(options)); + xObj.setPolicyText(JsonUtils.objectToJson(vObj)); + + return xObj; + } + + @Override + protected V mapEntityToViewBean(V vObj, T xObj) { + XXService xService = daoMgr.getXXService().getById(xObj.getService()); + XXServiceDef xServiceDef = daoMgr.getXXServiceDef().getById(xService.getType()); + + vObj.setGuid(xObj.getGuid()); + vObj.setVersion(xObj.getVersion()); + vObj.setService(xService.getName()); + vObj.setServiceType(xServiceDef.getName()); + vObj.setName(StringUtils.trim(xObj.getName())); + vObj.setPolicyType(xObj.getPolicyType() == null ? RangerPolicy.POLICY_TYPE_ACCESS : xObj.getPolicyType()); + vObj.setPolicyPriority(xObj.getPolicyPriority() == null ? RangerPolicy.POLICY_PRIORITY_NORMAL : xObj.getPolicyPriority()); + vObj.setDescription(xObj.getDescription()); + vObj.setResourceSignature(xObj.getResourceSignature()); + vObj.setIsEnabled(xObj.getIsEnabled()); + vObj.setIsAuditEnabled(xObj.getIsAuditEnabled()); + + String zoneName = convertZoneIdToZoneName(xObj.getZoneId(), vObj); + + vObj.setZoneName(zoneName); + + String policyText = xObj.getPolicyText(); + + RangerPolicy ret = JsonUtils.jsonToObject(policyText, RangerPolicy.class); + + if (ret != null) { + vObj.setOptions(ret.getOptions()); + vObj.setValiditySchedules(ret.getValiditySchedules()); + vObj.setPolicyLabels(ret.getPolicyLabels()); + } + + return vObj; + } + + private Long convertZoneNameToZoneId(String zoneName, V vObj) { + if (StringUtils.isEmpty(zoneName)) { + return RangerSecurityZone.RANGER_UNZONED_SECURITY_ZONE_ID; + } + + XXSecurityZone zone = daoMgr.getXXSecurityZoneDao().findByZoneName(zoneName); + + if (zone == null) { + throw restErrorUtil.createRESTException("No corresponding zone found for policyName: " + vObj.getName() + "Zone Not Found : " + zoneName, MessageEnums.INVALID_INPUT_DATA); + } + + return zone.getId(); + } + + private String convertZoneIdToZoneName(Long zoneId, V vObj) { + if (zoneId == null) { + throw restErrorUtil.createRESTException("No corresponding zone found for policyName: " + vObj.getName() + "Zone Not Found : " + zoneId, MessageEnums.INVALID_INPUT_DATA); + } + + if (zoneId.equals(RangerSecurityZone.RANGER_UNZONED_SECURITY_ZONE_ID)) { + return StringUtils.EMPTY; + } + + XXSecurityZone zone = daoMgr.getXXSecurityZoneDao().findByZoneId(zoneId); + + if (zone == null) { + throw restErrorUtil.createRESTException("No corresponding zone found for policyName: " + vObj.getName() + "Zone Not Found : " + zoneId, MessageEnums.INVALID_INPUT_DATA); + } + + return zone.getName(); + } } diff --git a/security-admin/src/main/java/org/apache/ranger/service/RangerPolicyWithAssignedIdService.java b/security-admin/src/main/java/org/apache/ranger/service/RangerPolicyWithAssignedIdService.java index 540a29eb24..2e61df41dd 100644 --- a/security-admin/src/main/java/org/apache/ranger/service/RangerPolicyWithAssignedIdService.java +++ b/security-admin/src/main/java/org/apache/ranger/service/RangerPolicyWithAssignedIdService.java @@ -17,7 +17,6 @@ package org.apache.ranger.service; - import org.apache.ranger.biz.RangerPolicyRetriever; import org.apache.ranger.common.JSONUtil; import org.apache.ranger.entity.XXPolicyWithAssignedId; @@ -27,44 +26,37 @@ @Service public class RangerPolicyWithAssignedIdService extends RangerPolicyServiceBase { - - @Autowired - JSONUtil jsonUtil; - - @Override - protected XXPolicyWithAssignedId mapViewToEntityBean(RangerPolicy vObj, XXPolicyWithAssignedId xObj, - int OPERATION_CONTEXT) { - return super.mapViewToEntityBean(vObj, xObj, OPERATION_CONTEXT); - } - - @Override - protected RangerPolicy mapEntityToViewBean(RangerPolicy vObj, XXPolicyWithAssignedId xObj) { - return super.mapEntityToViewBean(vObj, xObj); - } - - @Override - protected void validateForCreate(RangerPolicy vObj) { - // TODO Auto-generated method stub - - } - - @Override - protected void validateForUpdate(RangerPolicy vObj, XXPolicyWithAssignedId entityObj) { - // TODO Auto-generated method stub - - } - - @Override - protected RangerPolicy populateViewBean(XXPolicyWithAssignedId xPolicy) { - RangerPolicyRetriever retriever = new RangerPolicyRetriever(daoMgr); - - RangerPolicy vPolicy = retriever.getPolicy(xPolicy.getId()); - - return vPolicy; - } - - public RangerPolicy getPopulatedViewObject(XXPolicyWithAssignedId xPolicy) { - return this.populateViewBean(xPolicy); - } - + @Autowired + JSONUtil jsonUtil; + + public RangerPolicy getPopulatedViewObject(XXPolicyWithAssignedId xPolicy) { + return this.populateViewBean(xPolicy); + } + + @Override + protected XXPolicyWithAssignedId mapViewToEntityBean(RangerPolicy vObj, XXPolicyWithAssignedId xObj, int operationContext) { + return super.mapViewToEntityBean(vObj, xObj, operationContext); + } + + @Override + protected RangerPolicy mapEntityToViewBean(RangerPolicy vObj, XXPolicyWithAssignedId xObj) { + return super.mapEntityToViewBean(vObj, xObj); + } + + @Override + protected RangerPolicy populateViewBean(XXPolicyWithAssignedId xPolicy) { + RangerPolicyRetriever retriever = new RangerPolicyRetriever(daoMgr); + + return retriever.getPolicy(xPolicy.getId()); + } + + @Override + protected void validateForCreate(RangerPolicy vObj) { + // TODO Auto-generated method stub + } + + @Override + protected void validateForUpdate(RangerPolicy vObj, XXPolicyWithAssignedId entityObj) { + // TODO Auto-generated method stub + } } diff --git a/security-admin/src/main/java/org/apache/ranger/service/RangerRoleService.java b/security-admin/src/main/java/org/apache/ranger/service/RangerRoleService.java index eb8ed8bfad..bc91560850 100644 --- a/security-admin/src/main/java/org/apache/ranger/service/RangerRoleService.java +++ b/security-admin/src/main/java/org/apache/ranger/service/RangerRoleService.java @@ -17,11 +17,6 @@ package org.apache.ranger.service; - -import java.util.HashSet; -import java.util.List; -import java.util.Set; - import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang.StringUtils; import org.apache.ranger.authorization.utils.JsonUtils; @@ -38,16 +33,43 @@ import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Service; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + @Service @Scope("singleton") public class RangerRoleService extends RangerRoleServiceBase { - private static final Logger logger = LoggerFactory.getLogger(RangerRoleService.class); public RangerRoleService() { super(); } + public void updatePolicyVersions(Long roleId) { + logger.debug("==> updatePolicyVersions(roleId={})", roleId); + // Get all roles which include this role because change to this affects all these roles + Set containingRoles = getContainingRoles(roleId); + + logger.debug("All containing Roles for roleId:[{}] are [{}]", roleId, containingRoles); + + updatePolicyVersions(containingRoles); + + logger.debug("<== updatePolicyVersions(roleId={})", roleId); + } + + public void updateRoleVersions(Long roleId) { + logger.debug("==> updateRoleVersions(roleId={})", roleId); + // Get all roles which include this role because change to this affects all these roles + Set containingRoles = getContainingRoles(roleId); + + logger.debug("All containing Roles for roleId:[{}] are [{}]", roleId, containingRoles); + + updateRoleVersions(containingRoles); + + logger.debug("<== updateRoleVersions(roleId={})", roleId); + } + @Override protected void validateForCreate(RangerRole vObj) { } @@ -57,25 +79,26 @@ protected void validateForUpdate(RangerRole vObj, XXRole entityObj) { } @Override - protected XXRole mapViewToEntityBean(RangerRole rangerRole, XXRole xxRole, int OPERATION_CONTEXT) { - XXRole ret = super.mapViewToEntityBean(rangerRole, xxRole, OPERATION_CONTEXT); + protected XXRole mapViewToEntityBean(RangerRole rangerRole, XXRole xxRole, int operationContext) { + XXRole ret = super.mapViewToEntityBean(rangerRole, xxRole, operationContext); + ret.setRoleText(JsonUtils.objectToJson(rangerRole)); + return ret; } + @Override protected RangerRole mapEntityToViewBean(RangerRole rangerRole, XXRole xxRole) { RangerRole ret = super.mapEntityToViewBean(rangerRole, xxRole); if (StringUtils.isNotEmpty(xxRole.getRoleText())) { - if (logger.isDebugEnabled()) { - logger.debug("roleText=" + xxRole.getRoleText()); - } + logger.debug("roleText={}", xxRole.getRoleText()); + RangerRole roleFromJsonData = JsonUtils.jsonToObject(xxRole.getRoleText(), RangerRole.class); if (roleFromJsonData != null) { - if (logger.isDebugEnabled()) { - logger.debug("Role object built from JSON :[" + roleFromJsonData +"]"); - } + logger.debug("Role object built from JSON :[{}]", roleFromJsonData); + ret.setOptions(roleFromJsonData.getOptions()); ret.setUsers(roleFromJsonData.getUsers()); ret.setGroups(roleFromJsonData.getGroups()); @@ -83,30 +106,12 @@ protected RangerRole mapEntityToViewBean(RangerRole rangerRole, XXRole xxRole) { ret.setCreatedByUser(roleFromJsonData.getCreatedByUser()); } } else { - logger.info("Empty string representing jsonData in [" + xxRole + "]!!"); + logger.info("Empty string representing jsonData in [{}]!!", xxRole); } return ret; } - public void updatePolicyVersions(Long roleId) { - if (logger.isDebugEnabled()) { - logger.debug("==> updatePolicyVersions(roleId=" + roleId + ")"); - } - // Get all roles which include this role because change to this affects all these roles - Set containingRoles = getContainingRoles(roleId); - - if (logger.isDebugEnabled()) { - logger.debug("All containing Roles for roleId:[" + roleId +"] are [" + containingRoles + "]"); - } - - updatePolicyVersions(containingRoles); - - if (logger.isDebugEnabled()) { - logger.debug("<== updatePolicyVersions(roleId=" + roleId + ")"); - } - } - private Set getContainingRoles(Long roleId) { Set ret = new HashSet<>(); @@ -115,28 +120,9 @@ private Set getContainingRoles(Long roleId) { return ret; } - public void updateRoleVersions(Long roleId) { - if (logger.isDebugEnabled()) { - logger.debug("==> updateRoleVersions(roleId=" + roleId + ")"); - } - // Get all roles which include this role because change to this affects all these roles - Set containingRoles = getContainingRoles(roleId); - - if (logger.isDebugEnabled()) { - logger.debug("All containing Roles for roleId:[" + roleId +"] are [" + containingRoles + "]"); - } - - updateRoleVersions(containingRoles); - - if (logger.isDebugEnabled()) { - logger.debug("<== updateRoleVersions(roleId=" + roleId + ")"); - } - } - private void addContainingRoles(Long roleId, Set allRoles) { - if (logger.isDebugEnabled()) { - logger.debug("==> addContainingRoles(roleId=" + roleId + ")"); - } + logger.debug("==> addContainingRoles(roleId={})", roleId); + if (!allRoles.contains(roleId)) { allRoles.add(roleId); @@ -146,15 +132,12 @@ private void addContainingRoles(Long roleId, Set allRoles) { addContainingRoles(role, allRoles); } } - if (logger.isDebugEnabled()) { - logger.debug("<== addContainingRoles(roleId=" + roleId + ")"); - } + + logger.debug("<== addContainingRoles(roleId={})", roleId); } private void updatePolicyVersions(Set roleIds) { - if (logger.isDebugEnabled()) { - logger.debug("==> updatePolicyVersions(roleIds=" + roleIds + ")"); - } + logger.debug("==> updatePolicyVersions(roleIds={})", roleIds); if (CollectionUtils.isNotEmpty(roleIds)) { Set allAffectedServiceIds = new HashSet<>(); @@ -172,31 +155,32 @@ private void updatePolicyVersions(Set roleIds) { } } - if (logger.isDebugEnabled()) { - logger.debug("<== updatePolicyVersions(roleIds=" + roleIds + ")"); - } + logger.debug("<== updatePolicyVersions(roleIds={})", roleIds); } private void updateRoleVersions(Set roleIds) { - if (logger.isDebugEnabled()) { - logger.debug("==> updatePolicyVersions(roleIds=" + roleIds + ")"); - } + logger.debug("==> updatePolicyVersions(roleIds={})", roleIds); if (CollectionUtils.isNotEmpty(roleIds)) { Set allAffectedServiceIds = new HashSet<>(); for (Long roleId : roleIds) { List affectedServiceIds = daoMgr.getXXPolicy().findServiceIdsByRoleId(roleId); + allAffectedServiceIds.addAll(affectedServiceIds); } XXServiceDao serviceDao = daoMgr.getXXService(); + if (CollectionUtils.isNotEmpty(allAffectedServiceIds)) { for (final Long serviceId : allAffectedServiceIds) { Runnable serviceVersionUpdater = new ServiceDBStore.ServiceVersionUpdater(daoMgr, serviceId, ServiceDBStore.VERSION_TYPE.ROLE_VERSION, null, RangerPolicyDelta.CHANGE_TYPE_ROLE_UPDATE, null); + daoMgr.getRangerTransactionSynchronizationAdapter().executeOnTransactionCommit(serviceVersionUpdater); + XXService serviceDbObj = serviceDao.getById(serviceId); boolean isTagService = serviceDbObj.getType() == EmbeddedServiceDefsUtil.instance().getTagServiceDefId(); + if (isTagService) { updateRoleVersionOfAllServicesRefferingTag(daoMgr, serviceDao, serviceId); } @@ -204,20 +188,19 @@ private void updateRoleVersions(Set roleIds) { } } - if (logger.isDebugEnabled()) { - logger.debug("<== updatePolicyVersions(roleIds=" + roleIds + ")"); - } + logger.debug("<== updatePolicyVersions(roleIds={})", roleIds); } private void updateRoleVersionOfAllServicesRefferingTag(RangerDaoManager daoManager, XXServiceDao serviceDao, Long serviceId) { List referringServices = serviceDao.findByTagServiceId(serviceId); - if(CollectionUtils.isNotEmpty(referringServices)) { - for(XXService referringService : referringServices) { + + if (CollectionUtils.isNotEmpty(referringServices)) { + for (XXService referringService : referringServices) { final Long referringServiceId = referringService.getId(); Runnable roleVersionUpdater = new ServiceDBStore.ServiceVersionUpdater(daoManager, referringServiceId, ServiceDBStore.VERSION_TYPE.ROLE_VERSION, null, RangerPolicyDelta.CHANGE_TYPE_ROLE_UPDATE, null); + daoMgr.getRangerTransactionSynchronizationAdapter().executeOnTransactionCommit(roleVersionUpdater); } } } } - diff --git a/security-admin/src/main/java/org/apache/ranger/service/RangerRoleServiceBase.java b/security-admin/src/main/java/org/apache/ranger/service/RangerRoleServiceBase.java index 22867cbe5a..e5832850ce 100644 --- a/security-admin/src/main/java/org/apache/ranger/service/RangerRoleServiceBase.java +++ b/security-admin/src/main/java/org/apache/ranger/service/RangerRoleServiceBase.java @@ -30,52 +30,45 @@ import java.util.Map; public abstract class RangerRoleServiceBase extends RangerAuditedModelService { - public RangerRoleServiceBase() { super(AppConstants.CLASS_TYPE_RANGER_ROLE); searchFields.add(new SearchField(SearchFilter.ROLE_ID, "obj.id", SearchField.DATA_TYPE.INTEGER, SearchField.SEARCH_TYPE.FULL)); searchFields.add(new SearchField(SearchFilter.ROLE_NAME, "obj.name", SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.FULL)); - searchFields.add(new SearchField(SearchFilter.GROUP_NAME, "xXRoleRefGroup.groupName", - SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.FULL, "XXRoleRefGroup xXRoleRefGroup", - "xXRoleRefGroup.roleId = obj.id")); - searchFields.add(new SearchField(SearchFilter.USER_NAME, "xXRoleRefUser.userName", SearchField.DATA_TYPE.STRING, - SearchField.SEARCH_TYPE.FULL, "XXRoleRefUser xXRoleRefUser", "xXRoleRefUser.roleId = obj.id")); - searchFields.add(new SearchField(SearchFilter.ROLE_NAME_PARTIAL, "obj.name", SearchField.DATA_TYPE.STRING, - SearchField.SEARCH_TYPE.PARTIAL)); - searchFields.add(new SearchField(SearchFilter.GROUP_NAME_PARTIAL, "xXRoleRefGroup.groupName", - SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.PARTIAL, "XXRoleRefGroup xXRoleRefGroup", - "xXRoleRefGroup.roleId = obj.id")); - searchFields.add(new SearchField(SearchFilter.USER_NAME_PARTIAL, "xXRoleRefUser.userName", - SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.PARTIAL, "XXRoleRefUser xXRoleRefUser", - "xXRoleRefUser.roleId = obj.id")); + searchFields.add(new SearchField(SearchFilter.GROUP_NAME, "xXRoleRefGroup.groupName", SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.FULL, "XXRoleRefGroup xXRoleRefGroup", "xXRoleRefGroup.roleId = obj.id")); + searchFields.add(new SearchField(SearchFilter.USER_NAME, "xXRoleRefUser.userName", SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.FULL, "XXRoleRefUser xXRoleRefUser", "xXRoleRefUser.roleId = obj.id")); + searchFields.add(new SearchField(SearchFilter.ROLE_NAME_PARTIAL, "obj.name", SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.PARTIAL)); + searchFields.add(new SearchField(SearchFilter.GROUP_NAME_PARTIAL, "xXRoleRefGroup.groupName", SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.PARTIAL, "XXRoleRefGroup xXRoleRefGroup", "xXRoleRefGroup.roleId = obj.id")); + searchFields.add(new SearchField(SearchFilter.USER_NAME_PARTIAL, "xXRoleRefUser.userName", SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.PARTIAL, "XXRoleRefUser xXRoleRefUser", "xXRoleRefUser.roleId = obj.id")); sortFields.add(new SortField(SearchFilter.CREATE_TIME, "obj.createTime")); sortFields.add(new SortField(SearchFilter.UPDATE_TIME, "obj.updateTime")); sortFields.add(new SortField(SearchFilter.ROLE_ID, "obj.id", true, SortField.SORT_ORDER.ASC)); sortFields.add(new SortField(SearchFilter.ROLE_NAME, "obj.name")); - trxLogAttrs.put("name", new VTrxLogAttr("name", "Role Name", false, true)); - trxLogAttrs.put("description", new VTrxLogAttr("description", "Role Description")); - trxLogAttrs.put("options", new VTrxLogAttr("options", "Options")); - trxLogAttrs.put("users", new VTrxLogAttr("users", "Users")); - trxLogAttrs.put("adminUsers", new VTrxLogAttr("adminUsers", "Admin Users")); - trxLogAttrs.put("groups", new VTrxLogAttr("groups", "Groups")); - trxLogAttrs.put("adminGroups", new VTrxLogAttr("adminGroups", "Admin Groups")); - trxLogAttrs.put("roles", new VTrxLogAttr("roles", "Roles")); - trxLogAttrs.put("adminRoles", new VTrxLogAttr("adminRoles", "Admin Roles")); + trxLogAttrs.put("name", new VTrxLogAttr("name", "Role Name", false, true)); + trxLogAttrs.put("description", new VTrxLogAttr("description", "Role Description")); + trxLogAttrs.put("options", new VTrxLogAttr("options", "Options")); + trxLogAttrs.put("users", new VTrxLogAttr("users", "Users")); + trxLogAttrs.put("adminUsers", new VTrxLogAttr("adminUsers", "Admin Users")); + trxLogAttrs.put("groups", new VTrxLogAttr("groups", "Groups")); + trxLogAttrs.put("adminGroups", new VTrxLogAttr("adminGroups", "Admin Groups")); + trxLogAttrs.put("roles", new VTrxLogAttr("roles", "Roles")); + trxLogAttrs.put("adminRoles", new VTrxLogAttr("adminRoles", "Admin Roles")); trxLogAttrs.put("createdByUser", new VTrxLogAttr("createdByUser", "Created By User")); } @Override - protected T mapViewToEntityBean(V vObj, T xObj, int OPERATION_CONTEXT) { + protected T mapViewToEntityBean(V vObj, T xObj, int operationContext) { xObj.setName(vObj.getName()); xObj.setDescription(vObj.getDescription()); Map options = vObj.getOptions(); + if (options == null) { options = new HashMap<>(); } + xObj.setOptions(JsonUtils.mapToJson(options)); return xObj; @@ -89,4 +82,3 @@ protected V mapEntityToViewBean(V vObj, T xObj) { return vObj; } } - diff --git a/security-admin/src/main/java/org/apache/ranger/service/RangerSecurityZoneServiceBase.java b/security-admin/src/main/java/org/apache/ranger/service/RangerSecurityZoneServiceBase.java index 272914db02..da5a5e4d3b 100644 --- a/security-admin/src/main/java/org/apache/ranger/service/RangerSecurityZoneServiceBase.java +++ b/security-admin/src/main/java/org/apache/ranger/service/RangerSecurityZoneServiceBase.java @@ -26,11 +26,9 @@ import org.apache.ranger.plugin.model.RangerSecurityZone; import org.apache.ranger.plugin.util.SearchFilter; - public abstract class RangerSecurityZoneServiceBase extends RangerAuditedModelService { - - public RangerSecurityZoneServiceBase() { - super(AppConstants.CLASS_TYPE_RANGER_SECURITY_ZONE); + public RangerSecurityZoneServiceBase() { + super(AppConstants.CLASS_TYPE_RANGER_SECURITY_ZONE); searchFields.add(new SearchField(SearchFilter.ZONE_ID, "obj.id", SearchField.DATA_TYPE.INTEGER, SearchField.SEARCH_TYPE.FULL)); searchFields.add(new SearchField(SearchFilter.ZONE_NAME, "obj.name", SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.FULL)); @@ -40,33 +38,36 @@ public RangerSecurityZoneServiceBase() { sortFields.add(new SortField(SearchFilter.ZONE_ID, "obj.id", true, SortField.SORT_ORDER.ASC)); sortFields.add(new SortField(SearchFilter.ZONE_NAME, "obj.name")); - trxLogAttrs.put("name", new VTrxLogAttr("name", "Zone Name", false, true)); - trxLogAttrs.put("services", new VTrxLogAttr("services", "Zone Services")); - trxLogAttrs.put("adminUsers", new VTrxLogAttr("adminUsers", "Zone Admin Users")); - trxLogAttrs.put("adminUserGroups", new VTrxLogAttr("adminUserGroups", "Zone Admin User Groups")); - trxLogAttrs.put("auditUsers", new VTrxLogAttr("auditUsers", "Zone Audit Users")); - trxLogAttrs.put("auditUserGroups", new VTrxLogAttr("auditUserGroups", "Zone Audit User Groups")); - trxLogAttrs.put("adminRoles", new VTrxLogAttr("adminRoles", "Zone Admin Roles")); - trxLogAttrs.put("auditRoles", new VTrxLogAttr("auditRoles", "Zone Audit Roles")); - trxLogAttrs.put("description", new VTrxLogAttr("description", "Zone Description")); - trxLogAttrs.put("tagServices", new VTrxLogAttr("tagServices", "Zone Tag Services")); - } + trxLogAttrs.put("name", new VTrxLogAttr("name", "Zone Name", false, true)); + trxLogAttrs.put("services", new VTrxLogAttr("services", "Zone Services")); + trxLogAttrs.put("adminUsers", new VTrxLogAttr("adminUsers", "Zone Admin Users")); + trxLogAttrs.put("adminUserGroups", new VTrxLogAttr("adminUserGroups", "Zone Admin User Groups")); + trxLogAttrs.put("auditUsers", new VTrxLogAttr("auditUsers", "Zone Audit Users")); + trxLogAttrs.put("auditUserGroups", new VTrxLogAttr("auditUserGroups", "Zone Audit User Groups")); + trxLogAttrs.put("adminRoles", new VTrxLogAttr("adminRoles", "Zone Admin Roles")); + trxLogAttrs.put("auditRoles", new VTrxLogAttr("auditRoles", "Zone Audit Roles")); + trxLogAttrs.put("description", new VTrxLogAttr("description", "Zone Description")); + trxLogAttrs.put("tagServices", new VTrxLogAttr("tagServices", "Zone Tag Services")); + } + + @Override + protected T mapViewToEntityBean(V vObj, T xObj, int operationContext) { + xObj.setName(vObj.getName()); + xObj.setDescription(vObj.getDescription()); + + return xObj; + } + + @Override + protected V mapEntityToViewBean(V vObj, T xObj) { + if (xObj.getId().equals(RangerSecurityZone.RANGER_UNZONED_SECURITY_ZONE_ID)) { + vObj.setName(StringUtils.EMPTY); + } else { + vObj.setName(xObj.getName()); + } - @Override - protected T mapViewToEntityBean(V vObj, T xObj, int OPERATION_CONTEXT) { - xObj.setName(vObj.getName()); - xObj.setDescription(vObj.getDescription()); - return xObj; - } + vObj.setDescription(xObj.getDescription()); - @Override - protected V mapEntityToViewBean(V vObj, T xObj) { - if (xObj.getId().equals(RangerSecurityZone.RANGER_UNZONED_SECURITY_ZONE_ID)) { - vObj.setName(StringUtils.EMPTY); - } else { - vObj.setName(xObj.getName()); - } - vObj.setDescription(xObj.getDescription()); - return vObj; - } + return vObj; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/service/RangerSecurityZoneServiceService.java b/security-admin/src/main/java/org/apache/ranger/service/RangerSecurityZoneServiceService.java index 12aed36b64..18d7bf90ea 100755 --- a/security-admin/src/main/java/org/apache/ranger/service/RangerSecurityZoneServiceService.java +++ b/security-admin/src/main/java/org/apache/ranger/service/RangerSecurityZoneServiceService.java @@ -17,22 +17,11 @@ package org.apache.ranger.service; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang.StringUtils; import org.apache.ranger.authorization.hadoop.config.RangerAdminConfig; -import org.apache.ranger.authorization.utils.StringUtil; import org.apache.ranger.authorization.utils.JsonUtils; +import org.apache.ranger.authorization.utils.StringUtil; import org.apache.ranger.biz.GdsDBStore; import org.apache.ranger.biz.ServiceDBStore; import org.apache.ranger.common.view.VTrxLogAttr; @@ -51,22 +40,31 @@ import javax.annotation.PostConstruct; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + @Service @Scope("singleton") public class RangerSecurityZoneServiceService extends RangerSecurityZoneServiceBase { - @Autowired - ServiceDBStore serviceDBStore; - - @Autowired - GdsDBStore gdsStore; + private static final Logger logger = LoggerFactory.getLogger(RangerSecurityZoneServiceService.class); - boolean compressJsonData = false; + private final Map> serviceNamesInZones = new HashMap<>(); + private final Map> tagServiceNamesInZones = new HashMap<>(); - private static final Logger logger = LoggerFactory.getLogger(RangerSecurityZoneServiceService.class); + @Autowired + ServiceDBStore serviceDBStore; - private Map> serviceNamesInZones = new HashMap<>(); - private Map> tagServiceNamesInZones = new HashMap<>(); + @Autowired + GdsDBStore gdsStore; + boolean compressJsonData; public RangerSecurityZoneServiceService() { super(); @@ -74,9 +72,7 @@ public RangerSecurityZoneServiceService() { @PostConstruct public void initService() { - if (logger.isDebugEnabled()) { - logger.debug("==> RangerSecurityZoneServiceService.initService()"); - } + logger.debug("==> RangerSecurityZoneServiceService.initService()"); RangerAdminConfig config = RangerAdminConfig.getInstance(); @@ -84,94 +80,16 @@ public void initService() { logger.info("ranger.admin.store.security.zone.compress.json_data={}", compressJsonData); - if (logger.isDebugEnabled()) { - logger.debug("<== RangerSecurityZoneServiceService.initService()"); - } - } - - @Override - protected void validateForCreate(RangerSecurityZone vObj) { - } - - @Override - protected void validateForUpdate(RangerSecurityZone vObj, XXSecurityZone entityObj) { - // Cache service-names in existing zone object - RangerSecurityZone existingZone = new RangerSecurityZone(); - existingZone = mapEntityToViewBean(existingZone, entityObj); - serviceNamesInZones.put(entityObj.getId(), existingZone.getServices().keySet()); - tagServiceNamesInZones.put(entityObj.getId(), new HashSet<>(existingZone.getTagServices())); - } - - @Override - protected XXSecurityZone mapViewToEntityBean(RangerSecurityZone securityZone, XXSecurityZone xxSecurityZone, int OPERATION_CONTEXT) { - XXSecurityZone ret = super.mapViewToEntityBean(securityZone, xxSecurityZone, OPERATION_CONTEXT); - - String json = JsonUtils.objectToJson(securityZone); - - if (StringUtils.isNotEmpty(json) && compressJsonData) { - try { - ret.setJsonData(null); - ret.setGzJsonData(StringUtil.gzipCompress(json)); - } catch (IOException excp) { - logger.error("mapViewToEntityBean(): json compression failed (length="+json.length()+"). Will save uncompressed json", excp); - - ret.setJsonData(json); - ret.setGzJsonData(null); - } - } else { - ret.setJsonData(json); - ret.setGzJsonData(null); - } - - return ret; - } - @Override - protected RangerSecurityZone mapEntityToViewBean(RangerSecurityZone securityZone, XXSecurityZone xxSecurityZone) { - RangerSecurityZone ret = super.mapEntityToViewBean(securityZone, xxSecurityZone); - byte[] gzJson = xxSecurityZone.getGzJsonData(); - String json; - - if (gzJson != null) { - try { - json = StringUtil.gzipDecompress(gzJson); - } catch (IOException excp) { - json = xxSecurityZone.getJsonData(); - - logger.error("mapEntityToViewBean(): decompression of x_security_zone.gz_jsonData failed (length={}). Will use contents of x_security_zone.jsonData (length={})", gzJson.length, (json != null ? json.length() : 0), excp); - } - } else { - json = xxSecurityZone.getJsonData(); - } - - if (StringUtils.isNotEmpty(json)) { - RangerSecurityZone zoneFromJsonData = JsonUtils.jsonToObject(json, RangerSecurityZone.class); - - if (zoneFromJsonData != null) { - ret.setName(zoneFromJsonData.getName()); - ret.setServices(zoneFromJsonData.getServices()); - ret.setAdminUsers(zoneFromJsonData.getAdminUsers()); - ret.setAdminUserGroups(zoneFromJsonData.getAdminUserGroups()); - ret.setAdminRoles(zoneFromJsonData.getAdminRoles()); - ret.setAuditUsers(zoneFromJsonData.getAuditUsers()); - ret.setAuditUserGroups(zoneFromJsonData.getAuditUserGroups()); - ret.setAuditRoles(zoneFromJsonData.getAuditRoles()); - ret.setTagServices(zoneFromJsonData.getTagServices()); - } - } else { - logger.info("Empty string representing jsonData in [" + xxSecurityZone + "]!!"); - } - - return ret; + logger.debug("<== RangerSecurityZoneServiceService.initService()"); } @Override public RangerSecurityZone postCreate(XXSecurityZone xObj) { // Ensure to update ServiceVersionInfo for each service in the zone - RangerSecurityZone ret = super.postCreate(xObj); - Set serviceNames = ret.getServices().keySet(); - - List tagServiceNames = ret.getTagServices(); + RangerSecurityZone ret = super.postCreate(xObj); + Set serviceNames = ret.getServices().keySet(); + List tagServiceNames = ret.getTagServices(); // Create default zone policies try { @@ -181,25 +99,25 @@ public RangerSecurityZone postCreate(XXSecurityZone xObj) { serviceDBStore.createZoneDefaultPolicies(tagServiceNames, ret); updateServiceInfos(tagServiceNames); } catch (Exception exception) { - logger.error("postCreate processing failed for security-zone:[" + ret + "]", exception); + logger.error("postCreate processing failed for security-zone:[{}]", ret, exception); ret = null; } return ret; } - @Override + @Override public RangerSecurityZone postUpdate(XXSecurityZone xObj) { // Update ServiceVersionInfo for all affected services RangerSecurityZone ret = super.postUpdate(xObj); - Set oldServiceNames = new HashSet(serviceNamesInZones.remove(xObj.getId())); + Set oldServiceNames = new HashSet<>(serviceNamesInZones.remove(xObj.getId())); Set updatedServiceNames = ret.getServices().keySet(); - Set oldTagServiceNames = new HashSet(tagServiceNamesInZones.remove(xObj.getId())); - Set updatedTagServiceNames = new HashSet(ret.getTagServices()); + Set oldTagServiceNames = new HashSet<>(tagServiceNamesInZones.remove(xObj.getId())); + Set updatedTagServiceNames = new HashSet<>(ret.getTagServices()); - Collection newServiceNames = CollectionUtils.subtract(updatedServiceNames, oldServiceNames); + Collection newServiceNames = CollectionUtils.subtract(updatedServiceNames, oldServiceNames); Collection deletedServiceNames = CollectionUtils.subtract(oldServiceNames, updatedServiceNames); Collection deletedTagServiceNames = CollectionUtils.subtract(oldTagServiceNames, updatedTagServiceNames); @@ -215,16 +133,31 @@ public RangerSecurityZone postUpdate(XXSecurityZone xObj) { oldServiceNames.addAll(updatedServiceNames); updateServiceInfos(oldServiceNames); } catch (Exception exception) { - logger.error("postUpdate processing failed for security-zone:[" + ret + "]", exception); + logger.error("postUpdate processing failed for security-zone:[{}]", ret, exception); + ret = null; } + return ret; } + @Override + protected void validateForCreate(RangerSecurityZone vObj) { + } + + @Override + protected void validateForUpdate(RangerSecurityZone vObj, XXSecurityZone entityObj) { + // Cache service-names in existing zone object + RangerSecurityZone existingZone = new RangerSecurityZone(); + existingZone = mapEntityToViewBean(existingZone, entityObj); + serviceNamesInZones.put(entityObj.getId(), existingZone.getServices().keySet()); + tagServiceNamesInZones.put(entityObj.getId(), new HashSet<>(existingZone.getTagServices())); + } + @Override public XXSecurityZone preDelete(Long id) { // Update ServiceVersionInfo for each service in the zone - XXSecurityZone ret = super.preDelete(id); + XXSecurityZone ret = super.preDelete(id); RangerSecurityZone viewObject = new RangerSecurityZone(); viewObject = mapEntityToViewBean(viewObject, ret); Set allServiceNames = new HashSet<>(viewObject.getTagServices()); @@ -237,7 +170,7 @@ public XXSecurityZone preDelete(Long id) { gdsStore.deleteAllGdsObjectsForSecurityZone(id); updateServiceInfos(allServiceNames); } catch (Exception exception) { - logger.error("preDelete processing failed for security-zone:[" + viewObject + "]", exception); + logger.error("preDelete processing failed for security-zone:[{}]", viewObject, exception); ret = null; } @@ -256,8 +189,11 @@ public String getTrxLogAttrValue(RangerSecurityZone obj, VTrxLogAttr trxLogAttr) RangerSecurityZoneService service = entry.getValue(); int resourceCount = service != null && service.getResources() != null ? service.getResources().size() : 0; RangerSecurityZoneService serviceSummary = new RangerSecurityZoneService(); - - serviceSummary.getResources().add((new HashMap>() {{ put("resourceCount", Collections.singletonList(Integer.toString(resourceCount))); }})); + serviceSummary.getResources().add((new HashMap>() { + { + put("resourceCount", Collections.singletonList(Integer.toString(resourceCount))); + } + })); servicesSummary.put(serviceName, serviceSummary); } @@ -278,8 +214,70 @@ public String getTrxLogAttrValue(RangerSecurityZone obj, VTrxLogAttr trxLogAttr) return ret; } + @Override + protected XXSecurityZone mapViewToEntityBean(RangerSecurityZone securityZone, XXSecurityZone xxSecurityZone, int operationContext) { + XXSecurityZone ret = super.mapViewToEntityBean(securityZone, xxSecurityZone, operationContext); + String json = JsonUtils.objectToJson(securityZone); + + if (StringUtils.isNotEmpty(json) && compressJsonData) { + try { + ret.setJsonData(null); + ret.setGzJsonData(StringUtil.gzipCompress(json)); + } catch (IOException excp) { + logger.error("mapViewToEntityBean(): json compression failed (length={}). Will save uncompressed json", json.length(), excp); + + ret.setJsonData(json); + ret.setGzJsonData(null); + } + } else { + ret.setJsonData(json); + ret.setGzJsonData(null); + } + + return ret; + } + + @Override + protected RangerSecurityZone mapEntityToViewBean(RangerSecurityZone securityZone, XXSecurityZone xxSecurityZone) { + RangerSecurityZone ret = super.mapEntityToViewBean(securityZone, xxSecurityZone); + byte[] gzJson = xxSecurityZone.getGzJsonData(); + String json; + + if (gzJson != null) { + try { + json = StringUtil.gzipDecompress(gzJson); + } catch (IOException excp) { + json = xxSecurityZone.getJsonData(); + + logger.error("mapEntityToViewBean(): decompression of x_security_zone.gz_jsonData failed (length={}). Will use contents of x_security_zone.jsonData (length={})", gzJson.length, (json != null ? json.length() : 0), excp); + } + } else { + json = xxSecurityZone.getJsonData(); + } + + if (StringUtils.isNotEmpty(json)) { + RangerSecurityZone zoneFromJsonData = JsonUtils.jsonToObject(json, RangerSecurityZone.class); + + if (zoneFromJsonData != null) { + ret.setName(zoneFromJsonData.getName()); + ret.setServices(zoneFromJsonData.getServices()); + ret.setAdminUsers(zoneFromJsonData.getAdminUsers()); + ret.setAdminUserGroups(zoneFromJsonData.getAdminUserGroups()); + ret.setAdminRoles(zoneFromJsonData.getAdminRoles()); + ret.setAuditUsers(zoneFromJsonData.getAuditUsers()); + ret.setAuditUserGroups(zoneFromJsonData.getAuditUserGroups()); + ret.setAuditRoles(zoneFromJsonData.getAuditRoles()); + ret.setTagServices(zoneFromJsonData.getTagServices()); + } + } else { + logger.info("Empty string representing jsonData in [{}]!!", xxSecurityZone); + } + + return ret; + } + private void updateServiceInfos(Collection services) { - if(CollectionUtils.isEmpty(services)) { + if (CollectionUtils.isEmpty(services)) { return; } @@ -289,15 +287,14 @@ private void updateServiceInfos(Collection services) { serviceVersionInfos.add(daoMgr.getXXServiceVersionInfo().findByServiceName(serviceName)); } - for(XXServiceVersionInfo serviceVersionInfo : serviceVersionInfos) { - final RangerDaoManager finaldaoManager = daoMgr; - final Long finalServiceId = serviceVersionInfo.getServiceId(); - final ServiceDBStore.VERSION_TYPE versionType = ServiceDBStore.VERSION_TYPE.POLICY_VERSION; + for (XXServiceVersionInfo serviceVersionInfo : serviceVersionInfos) { + final RangerDaoManager finaldaoManager = daoMgr; + final Long finalServiceId = serviceVersionInfo.getServiceId(); + final ServiceDBStore.VERSION_TYPE versionType = ServiceDBStore.VERSION_TYPE.POLICY_VERSION; Runnable serviceVersionUpdater = new ServiceDBStore.ServiceVersionUpdater(finaldaoManager, finalServiceId, versionType, null, RangerPolicyDelta.CHANGE_TYPE_SERVICE_CHANGE, null); daoMgr.getRangerTransactionSynchronizationAdapter().executeOnTransactionCommit(serviceVersionUpdater); } - } } diff --git a/security-admin/src/main/java/org/apache/ranger/service/RangerServiceDefService.java b/security-admin/src/main/java/org/apache/ranger/service/RangerServiceDefService.java index 3fb3dea408..6966c44d84 100644 --- a/security-admin/src/main/java/org/apache/ranger/service/RangerServiceDefService.java +++ b/security-admin/src/main/java/org/apache/ranger/service/RangerServiceDefService.java @@ -17,10 +17,6 @@ package org.apache.ranger.service; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - import org.apache.commons.lang.StringUtils; import org.apache.ranger.authorization.hadoop.config.RangerAdminConfig; import org.apache.ranger.entity.XXServiceDef; @@ -29,73 +25,80 @@ import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Service; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; @Service @Scope("singleton") public class RangerServiceDefService extends RangerServiceDefServiceBase { - private final RangerAdminConfig config; - - public RangerServiceDefService() { - super(); - - this.config = RangerAdminConfig.getInstance(); - } - - @Override - protected void validateForCreate(RangerServiceDef vObj) { - - } - - @Override - protected void validateForUpdate(RangerServiceDef vObj, XXServiceDef entityObj) { - - } - - @Override - protected XXServiceDef mapViewToEntityBean(RangerServiceDef vObj, XXServiceDef xObj, int OPERATION_CONTEXT) { - return super.mapViewToEntityBean(vObj, xObj, OPERATION_CONTEXT); - } - - @Override - protected RangerServiceDef mapEntityToViewBean(RangerServiceDef vObj, XXServiceDef xObj) { - RangerServiceDef ret = super.mapEntityToViewBean(vObj, xObj); - - Map serviceDefOptions = ret.getOptions(); - - if (serviceDefOptions.get(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES) == null) { - boolean enableDenyAndExceptionsInPoliciesHiddenOption = config.getBoolean("ranger.servicedef.enableDenyAndExceptionsInPolicies", true); - if (enableDenyAndExceptionsInPoliciesHiddenOption || StringUtils.equalsIgnoreCase(ret.getName(), EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_TAG_NAME)) { - serviceDefOptions.put(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES, "true"); - } else { - serviceDefOptions.put(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES, "false"); - } - ret.setOptions(serviceDefOptions); - } - - if (serviceDefOptions.get(RangerServiceDef.OPTION_ENABLE_TAG_BASED_POLICIES) == null) { - boolean enableTagBasedPoliciesHiddenOption = config.getBoolean("ranger.servicedef.enableTagBasedPolicies", true); - if (enableTagBasedPoliciesHiddenOption) { - serviceDefOptions.put(RangerServiceDef.OPTION_ENABLE_TAG_BASED_POLICIES, "true"); - } else { - serviceDefOptions.put(RangerServiceDef.OPTION_ENABLE_TAG_BASED_POLICIES, "false"); - } - ret.setOptions(serviceDefOptions); - } - return ret; - } - - public List getAllServiceDefs() { - List xxServiceDefList = getDao().getAll(); - List serviceDefList = new ArrayList(); - - for (XXServiceDef xxServiceDef : xxServiceDefList) { - RangerServiceDef serviceDef = populateViewBean(xxServiceDef); - serviceDefList.add(serviceDef); - } - return serviceDefList; - } - - public RangerServiceDef getPopulatedViewObject(XXServiceDef xServiceDef) { - return this.populateViewBean(xServiceDef); - } + private final RangerAdminConfig config; + + public RangerServiceDefService() { + super(); + + this.config = RangerAdminConfig.getInstance(); + } + + public List getAllServiceDefs() { + List xxServiceDefList = getDao().getAll(); + List serviceDefList = new ArrayList<>(); + + for (XXServiceDef xxServiceDef : xxServiceDefList) { + RangerServiceDef serviceDef = populateViewBean(xxServiceDef); + + serviceDefList.add(serviceDef); + } + + return serviceDefList; + } + + public RangerServiceDef getPopulatedViewObject(XXServiceDef xServiceDef) { + return this.populateViewBean(xServiceDef); + } + + @Override + protected void validateForCreate(RangerServiceDef vObj) { + } + + @Override + protected void validateForUpdate(RangerServiceDef vObj, XXServiceDef entityObj) { + } + + @Override + protected XXServiceDef mapViewToEntityBean(RangerServiceDef vObj, XXServiceDef xObj, int operationContext) { + return super.mapViewToEntityBean(vObj, xObj, operationContext); + } + + @Override + protected RangerServiceDef mapEntityToViewBean(RangerServiceDef vObj, XXServiceDef xObj) { + RangerServiceDef ret = super.mapEntityToViewBean(vObj, xObj); + Map serviceDefOptions = ret.getOptions(); + + if (serviceDefOptions.get(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES) == null) { + boolean enableDenyAndExceptionsInPoliciesHiddenOption = config.getBoolean("ranger.servicedef.enableDenyAndExceptionsInPolicies", true); + + if (enableDenyAndExceptionsInPoliciesHiddenOption || StringUtils.equalsIgnoreCase(ret.getName(), EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_TAG_NAME)) { + serviceDefOptions.put(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES, "true"); + } else { + serviceDefOptions.put(RangerServiceDef.OPTION_ENABLE_DENY_AND_EXCEPTIONS_IN_POLICIES, "false"); + } + + ret.setOptions(serviceDefOptions); + } + + if (serviceDefOptions.get(RangerServiceDef.OPTION_ENABLE_TAG_BASED_POLICIES) == null) { + boolean enableTagBasedPoliciesHiddenOption = config.getBoolean("ranger.servicedef.enableTagBasedPolicies", true); + + if (enableTagBasedPoliciesHiddenOption) { + serviceDefOptions.put(RangerServiceDef.OPTION_ENABLE_TAG_BASED_POLICIES, "true"); + } else { + serviceDefOptions.put(RangerServiceDef.OPTION_ENABLE_TAG_BASED_POLICIES, "false"); + } + + ret.setOptions(serviceDefOptions); + } + + return ret; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/service/RangerServiceDefServiceBase.java b/security-admin/src/main/java/org/apache/ranger/service/RangerServiceDefServiceBase.java index a0ba463e47..9e082977f4 100644 --- a/security-admin/src/main/java/org/apache/ranger/service/RangerServiceDefServiceBase.java +++ b/security-admin/src/main/java/org/apache/ranger/service/RangerServiceDefServiceBase.java @@ -17,14 +17,6 @@ package org.apache.ranger.service; -import java.io.Serializable; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - import org.apache.commons.collections.MapUtils; import org.apache.commons.lang.StringUtils; import org.apache.ranger.common.AppConstants; @@ -33,10 +25,19 @@ import org.apache.ranger.common.MessageEnums; import org.apache.ranger.common.PropertiesUtil; import org.apache.ranger.common.SearchField; -import org.apache.ranger.common.SortField; import org.apache.ranger.common.SearchField.DATA_TYPE; import org.apache.ranger.common.SearchField.SEARCH_TYPE; -import org.apache.ranger.entity.*; +import org.apache.ranger.common.SortField; +import org.apache.ranger.entity.XXAccessTypeDef; +import org.apache.ranger.entity.XXContextEnricherDef; +import org.apache.ranger.entity.XXDataMaskTypeDef; +import org.apache.ranger.entity.XXEnumDef; +import org.apache.ranger.entity.XXEnumElementDef; +import org.apache.ranger.entity.XXPolicyConditionDef; +import org.apache.ranger.entity.XXResourceDef; +import org.apache.ranger.entity.XXServiceConfigDef; +import org.apache.ranger.entity.XXServiceDef; +import org.apache.ranger.entity.XXServiceDefBase; import org.apache.ranger.plugin.model.RangerServiceDef; import org.apache.ranger.plugin.model.RangerServiceDef.RangerAccessTypeDef; import org.apache.ranger.plugin.model.RangerServiceDef.RangerAccessTypeDef.AccessTypeCategory; @@ -56,728 +57,779 @@ import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; +import java.io.Serializable; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + import static org.apache.ranger.plugin.util.ServiceDefUtil.IMPLICIT_CONDITION_EXPRESSION_EVALUATOR; -public abstract class RangerServiceDefServiceBase - extends RangerBaseModelService { - private static final Logger LOG = LoggerFactory.getLogger(RangerServiceDefServiceBase.class); - - private static final String OPTION_RESOURCE_ACCESS_TYPE_RESTRICTIONS = "__accessTypeRestrictions"; - private static final String OPTION_RESOURCE_IS_VALID_LEAF = "__isValidLeaf"; - public static final String PROP_ENABLE_IMPLICIT_CONDITION_EXPRESSION = "ranger.servicedef.enableImplicitConditionExpression"; - - @Autowired - RangerAuditFields rangerAuditFields; - - @Autowired - JSONUtil jsonUtil; - - @Autowired - GUIDUtil guidUtil; - - public RangerServiceDefServiceBase() { - super(); - - searchFields.add(new SearchField(SearchFilter.SERVICE_TYPE, "obj.name", DATA_TYPE.STRING, SEARCH_TYPE.FULL)); - searchFields.add(new SearchField(SearchFilter.SERVICE_TYPE_DISPLAY_NAME, "obj.displayName", DATA_TYPE.STRING, SEARCH_TYPE.FULL)); - searchFields.add(new SearchField(SearchFilter.SERVICE_TYPE_ID, "obj.id", DATA_TYPE.INTEGER, SEARCH_TYPE.FULL)); - searchFields.add(new SearchField(SearchFilter.IS_ENABLED, "obj.isEnabled", DATA_TYPE.BOOLEAN, SEARCH_TYPE.FULL)); - - sortFields.add(new SortField(SearchFilter.CREATE_TIME, "obj.createTime")); - sortFields.add(new SortField(SearchFilter.UPDATE_TIME, "obj.updateTime")); - sortFields.add(new SortField(SearchFilter.SERVICE_TYPE_ID, "obj.id")); - sortFields.add(new SortField(SearchFilter.SERVICE_TYPE, "obj.name")); - sortFields.add(new SortField(SearchFilter.SERVICE_TYPE_DISPLAY_NAME, "obj.displayName")); - } - - @Override - protected V populateViewBean(T xServiceDef) { - V serviceDef = super.populateViewBean((T) xServiceDef); - Long serviceDefId = xServiceDef.getId(); - - List xConfigs = daoMgr.getXXServiceConfigDef().findByServiceDefId(serviceDefId); - if (!stringUtil.isEmpty(xConfigs)) { - List configs = new ArrayList(); - for (XXServiceConfigDef xConfig : xConfigs) { - RangerServiceConfigDef config = populateXXToRangerServiceConfigDef(xConfig); - configs.add(config); - } - serviceDef.setConfigs(configs); - } - - List xResources = daoMgr.getXXResourceDef().findByServiceDefId(serviceDefId); - if (!stringUtil.isEmpty(xResources)) { - List resources = new ArrayList(); - for (XXResourceDef xResource : xResources) { - RangerResourceDef resource = populateXXToRangerResourceDef(xResource); - resources.add(resource); - } - serviceDef.setResources(resources); - } - - List xAccessTypes = daoMgr.getXXAccessTypeDef().findByServiceDefId(serviceDefId); - Map> impliedGrants = daoMgr.getXXAccessTypeDefGrants().findImpliedGrantsByServiceDefId(serviceDefId); - if (!stringUtil.isEmpty(xAccessTypes)) { - List accessTypes = new ArrayList(); - for (XXAccessTypeDef xAtd : xAccessTypes) { - RangerAccessTypeDef accessType = populateXXToRangerAccessTypeDef(xAtd, impliedGrants.get(xAtd.getName())); - accessTypes.add(accessType); - } - serviceDef.setAccessTypes(accessTypes); - } - - serviceDef.setMarkerAccessTypes(ServiceDefUtil.getMarkerAccessTypes(serviceDef.getAccessTypes())); - - List xPolicyConditions = daoMgr.getXXPolicyConditionDef() - .findByServiceDefId(serviceDefId); - if (!stringUtil.isEmpty(xPolicyConditions)) { - List policyConditions = new ArrayList(); - for (XXPolicyConditionDef xPolicyCondDef : xPolicyConditions) { - RangerPolicyConditionDef policyCondition = populateXXToRangerPolicyConditionDef(xPolicyCondDef); - policyConditions.add(policyCondition); - } - serviceDef.setPolicyConditions(policyConditions); - } - - List xContextEnrichers = daoMgr.getXXContextEnricherDef() - .findByServiceDefId(serviceDefId); - if (!stringUtil.isEmpty(xContextEnrichers)) { - List contextEnrichers = new ArrayList(); - for (XXContextEnricherDef xContextEnricherDef : xContextEnrichers) { - RangerContextEnricherDef contextEnricher = populateXXToRangerContextEnricherDef(xContextEnricherDef); - contextEnrichers.add(contextEnricher); - } - serviceDef.setContextEnrichers(contextEnrichers); - } - - List xEnumList = daoMgr.getXXEnumDef().findByServiceDefId(serviceDefId); - if (!stringUtil.isEmpty(xEnumList)) { - List enums = new ArrayList(); - for (XXEnumDef xEnum : xEnumList) { - RangerEnumDef vEnum = populateXXToRangerEnumDef(xEnum); - enums.add(vEnum); - } - serviceDef.setEnums(enums); - } - - RangerDataMaskDef dataMaskDef = new RangerDataMaskDef(); - RangerRowFilterDef rowFilterDef = new RangerRowFilterDef(); - - List xDataMaskTypes = daoMgr.getXXDataMaskTypeDef().findByServiceDefId(serviceDefId); - if (!stringUtil.isEmpty(xDataMaskTypes)) { - List dataMaskTypes = new ArrayList(); - for (XXDataMaskTypeDef xDataMaskType : xDataMaskTypes) { - RangerDataMaskTypeDef dataMaskType = populateXXToRangerDataMaskTypeDef(xDataMaskType); - dataMaskTypes.add(dataMaskType); - } - - dataMaskDef.setMaskTypes(dataMaskTypes); - } - - if (!stringUtil.isEmpty(xResources)) { - for (XXResourceDef xResource : xResources) { - if (StringUtils.isNotEmpty(xResource.getDataMaskOptions())) { - RangerResourceDef dataMaskResource = jsonToObject(xResource.getDataMaskOptions(), RangerResourceDef.class); - - dataMaskDef.getResources().add(dataMaskResource); - } - - if (StringUtils.isNotEmpty(xResource.getRowFilterOptions())) { - RangerResourceDef resource = jsonToObject(xResource.getRowFilterOptions(), RangerResourceDef.class); - - rowFilterDef.getResources().add(resource); - } - } - } - - if (!stringUtil.isEmpty(xAccessTypes)) { - for (XXAccessTypeDef xAtd : xAccessTypes) { - if(StringUtils.isNotEmpty(xAtd.getDataMaskOptions())) { - RangerAccessTypeDef dataMaskAccessType = jsonToObject(xAtd.getDataMaskOptions(), RangerAccessTypeDef.class); - - dataMaskDef.getAccessTypes().add(dataMaskAccessType); - } - - if(StringUtils.isNotEmpty(xAtd.getRowFilterOptions())) { - RangerAccessTypeDef accessType = jsonToObject(xAtd.getRowFilterOptions(), RangerAccessTypeDef.class); - - rowFilterDef.getAccessTypes().add(accessType); - } - } - } - serviceDef.setDataMaskDef(dataMaskDef); - serviceDef.setRowFilterDef(rowFilterDef); - - addImplicitConditionExpressionIfNeeded(serviceDef); - - ServiceDefUtil.normalize(serviceDef); - - return serviceDef; - } - - @Override - protected T mapViewToEntityBean(V vObj, T xObj, int operationContext) { - - String guid = (StringUtils.isEmpty(vObj.getGuid())) ? guidUtil.genGUID() : vObj.getGuid(); - - xObj.setGuid(guid); - xObj.setName(vObj.getName()); - xObj.setDisplayName(vObj.getDisplayName()); - xObj.setImplclassname(vObj.getImplClass()); - xObj.setLabel(vObj.getLabel()); - xObj.setDescription(vObj.getDescription()); - xObj.setRbkeylabel(vObj.getRbKeyLabel()); - xObj.setRbkeydescription(vObj.getRbKeyDescription()); - xObj.setIsEnabled(vObj.getIsEnabled()); - - xObj.setDefOptions(mapToJsonString(vObj.getOptions())); - - return xObj; - } - - @Override - protected V mapEntityToViewBean(V vObj, T xObj) { - vObj.setGuid(xObj.getGuid()); - vObj.setVersion(xObj.getVersion()); - vObj.setName(xObj.getName()); - vObj.setImplClass(xObj.getImplclassname()); - vObj.setLabel(xObj.getLabel()); - vObj.setDescription(xObj.getDescription()); - vObj.setOptions(jsonStringToMap(xObj.getDefOptions())); - vObj.setRbKeyLabel(xObj.getRbkeylabel()); - vObj.setRbKeyDescription(xObj.getRbkeydescription()); - vObj.setIsEnabled(xObj.getIsEnabled()); - vObj.setDisplayName(xObj.getDisplayName()); - return vObj; - } - - public XXServiceConfigDef populateRangerServiceConfigDefToXX(RangerServiceConfigDef vObj, XXServiceConfigDef xObj, - XXServiceDef serviceDef, int operationContext) { - if(serviceDef == null) { - LOG.error("RangerServiceDefServiceBase.populateRangerServiceConfigDefToXX, serviceDef can not be null"); - throw restErrorUtil.createRESTException("RangerServiceDef cannot be null.", MessageEnums.DATA_NOT_FOUND); - } - - xObj = rangerAuditFields.populateAuditFields(xObj, serviceDef); - xObj.setDefid(serviceDef.getId()); - xObj.setItemId(vObj.getItemId()); - xObj.setName(vObj.getName()); - xObj.setType(vObj.getType()); - xObj.setSubtype(vObj.getSubType()); - xObj.setIsMandatory(vObj.getMandatory()); - xObj.setDefaultvalue(vObj.getDefaultValue()); - xObj.setValidationRegEx(vObj.getValidationRegEx()); - xObj.setValidationMessage(vObj.getValidationMessage()); - xObj.setUiHint(vObj.getUiHint()); - xObj.setLabel(vObj.getLabel()); - xObj.setDescription(vObj.getDescription()); - xObj.setRbkeylabel(vObj.getRbKeyLabel()); - xObj.setRbkeydescription(vObj.getRbKeyDescription()); - xObj.setRbKeyValidationMessage(vObj.getRbKeyValidationMessage()); - xObj.setOrder(AppConstants.DEFAULT_SORT_ORDER); - return xObj; - } - - public RangerServiceConfigDef populateXXToRangerServiceConfigDef(XXServiceConfigDef xObj) { - RangerServiceConfigDef vObj = new RangerServiceConfigDef(); - vObj.setItemId(xObj.getItemId()); - vObj.setName(xObj.getName()); - vObj.setType(xObj.getType()); - vObj.setSubType(xObj.getSubtype()); - vObj.setMandatory(xObj.getIsMandatory()); - vObj.setDefaultValue(xObj.getDefaultvalue()); - vObj.setValidationRegEx(xObj.getValidationRegEx()); - vObj.setValidationMessage(xObj.getValidationMessage()); - vObj.setUiHint(xObj.getUiHint()); - vObj.setLabel(xObj.getLabel()); - vObj.setDescription(xObj.getDescription()); - vObj.setRbKeyLabel(xObj.getRbkeylabel()); - vObj.setRbKeyDescription(xObj.getRbkeydescription()); - vObj.setRbKeyValidationMessage(xObj.getRbKeyValidationMessage()); - return vObj; - } - - public XXResourceDef populateRangerResourceDefToXX(RangerResourceDef vObj, XXResourceDef xObj, - XXServiceDef serviceDef, int operationContext) { - if(serviceDef == null) { - LOG.error("RangerServiceDefServiceBase.populateRangerResourceDefToXX, serviceDef can not be null"); - throw restErrorUtil.createRESTException("RangerServiceDef cannot be null.", MessageEnums.DATA_NOT_FOUND); - } - - xObj = rangerAuditFields.populateAuditFields(xObj, serviceDef); - xObj.setDefid(serviceDef.getId()); - xObj.setItemId(vObj.getItemId()); - xObj.setName(vObj.getName()); - xObj.setType(vObj.getType()); - xObj.setLevel(vObj.getLevel()); - xObj.setMandatory(vObj.getMandatory()); - xObj.setLookupsupported(vObj.getLookupSupported()); - xObj.setRecursivesupported(vObj.getRecursiveSupported()); - xObj.setExcludessupported(vObj.getExcludesSupported()); - xObj.setMatcher(vObj.getMatcher()); - - String accessTypeRestrictions = objectToJson((HashSet)vObj.getAccessTypeRestrictions()); - String isValidLeaf = objectToJson(vObj.getIsValidLeaf()); - Map matcherOptions = vObj.getMatcherOptions(); - - if (StringUtils.isNotBlank(accessTypeRestrictions)) { - matcherOptions.put(OPTION_RESOURCE_ACCESS_TYPE_RESTRICTIONS, accessTypeRestrictions); - } else { - matcherOptions.remove(OPTION_RESOURCE_ACCESS_TYPE_RESTRICTIONS); - } - - if (StringUtils.isNotBlank(isValidLeaf)) { - matcherOptions.put(OPTION_RESOURCE_IS_VALID_LEAF, isValidLeaf); - } else { - matcherOptions.remove(OPTION_RESOURCE_IS_VALID_LEAF); - } +public abstract class RangerServiceDefServiceBase extends RangerBaseModelService { + private static final Logger LOG = LoggerFactory.getLogger(RangerServiceDefServiceBase.class); + + public static final String PROP_ENABLE_IMPLICIT_CONDITION_EXPRESSION = "ranger.servicedef.enableImplicitConditionExpression"; + + private static final String OPTION_RESOURCE_ACCESS_TYPE_RESTRICTIONS = "__accessTypeRestrictions"; + private static final String OPTION_RESOURCE_IS_VALID_LEAF = "__isValidLeaf"; + + @Autowired + RangerAuditFields rangerAuditFields; + + @Autowired + JSONUtil jsonUtil; + + @Autowired + GUIDUtil guidUtil; + + public RangerServiceDefServiceBase() { + super(); + + searchFields.add(new SearchField(SearchFilter.SERVICE_TYPE, "obj.name", DATA_TYPE.STRING, SEARCH_TYPE.FULL)); + searchFields.add(new SearchField(SearchFilter.SERVICE_TYPE_DISPLAY_NAME, "obj.displayName", DATA_TYPE.STRING, SEARCH_TYPE.FULL)); + searchFields.add(new SearchField(SearchFilter.SERVICE_TYPE_ID, "obj.id", DATA_TYPE.INTEGER, SEARCH_TYPE.FULL)); + searchFields.add(new SearchField(SearchFilter.IS_ENABLED, "obj.isEnabled", DATA_TYPE.BOOLEAN, SEARCH_TYPE.FULL)); + + sortFields.add(new SortField(SearchFilter.CREATE_TIME, "obj.createTime")); + sortFields.add(new SortField(SearchFilter.UPDATE_TIME, "obj.updateTime")); + sortFields.add(new SortField(SearchFilter.SERVICE_TYPE_ID, "obj.id")); + sortFields.add(new SortField(SearchFilter.SERVICE_TYPE, "obj.name")); + sortFields.add(new SortField(SearchFilter.SERVICE_TYPE_DISPLAY_NAME, "obj.displayName")); + } + + public XXServiceConfigDef populateRangerServiceConfigDefToXX(RangerServiceConfigDef vObj, XXServiceConfigDef xObj, XXServiceDef serviceDef, int operationContext) { + if (serviceDef == null) { + LOG.error("RangerServiceDefServiceBase.populateRangerServiceConfigDefToXX, serviceDef can not be null"); + + throw restErrorUtil.createRESTException("RangerServiceDef cannot be null.", MessageEnums.DATA_NOT_FOUND); + } + + xObj = rangerAuditFields.populateAuditFields(xObj, serviceDef); + + xObj.setDefid(serviceDef.getId()); + xObj.setItemId(vObj.getItemId()); + xObj.setName(vObj.getName()); + xObj.setType(vObj.getType()); + xObj.setSubtype(vObj.getSubType()); + xObj.setIsMandatory(vObj.getMandatory()); + xObj.setDefaultvalue(vObj.getDefaultValue()); + xObj.setValidationRegEx(vObj.getValidationRegEx()); + xObj.setValidationMessage(vObj.getValidationMessage()); + xObj.setUiHint(vObj.getUiHint()); + xObj.setLabel(vObj.getLabel()); + xObj.setDescription(vObj.getDescription()); + xObj.setRbkeylabel(vObj.getRbKeyLabel()); + xObj.setRbkeydescription(vObj.getRbKeyDescription()); + xObj.setRbKeyValidationMessage(vObj.getRbKeyValidationMessage()); + xObj.setOrder(AppConstants.DEFAULT_SORT_ORDER); + + return xObj; + } + + public RangerServiceConfigDef populateXXToRangerServiceConfigDef(XXServiceConfigDef xObj) { + RangerServiceConfigDef vObj = new RangerServiceConfigDef(); + + vObj.setItemId(xObj.getItemId()); + vObj.setName(xObj.getName()); + vObj.setType(xObj.getType()); + vObj.setSubType(xObj.getSubtype()); + vObj.setMandatory(xObj.getIsMandatory()); + vObj.setDefaultValue(xObj.getDefaultvalue()); + vObj.setValidationRegEx(xObj.getValidationRegEx()); + vObj.setValidationMessage(xObj.getValidationMessage()); + vObj.setUiHint(xObj.getUiHint()); + vObj.setLabel(xObj.getLabel()); + vObj.setDescription(xObj.getDescription()); + vObj.setRbKeyLabel(xObj.getRbkeylabel()); + vObj.setRbKeyDescription(xObj.getRbkeydescription()); + vObj.setRbKeyValidationMessage(xObj.getRbKeyValidationMessage()); + + return vObj; + } + + public XXResourceDef populateRangerResourceDefToXX(RangerResourceDef vObj, XXResourceDef xObj, XXServiceDef serviceDef, int operationContext) { + if (serviceDef == null) { + LOG.error("RangerServiceDefServiceBase.populateRangerResourceDefToXX, serviceDef can not be null"); + + throw restErrorUtil.createRESTException("RangerServiceDef cannot be null.", MessageEnums.DATA_NOT_FOUND); + } + + xObj = rangerAuditFields.populateAuditFields(xObj, serviceDef); + + xObj.setDefid(serviceDef.getId()); + xObj.setItemId(vObj.getItemId()); + xObj.setName(vObj.getName()); + xObj.setType(vObj.getType()); + xObj.setLevel(vObj.getLevel()); + xObj.setMandatory(vObj.getMandatory()); + xObj.setLookupsupported(vObj.getLookupSupported()); + xObj.setRecursivesupported(vObj.getRecursiveSupported()); + xObj.setExcludessupported(vObj.getExcludesSupported()); + xObj.setMatcher(vObj.getMatcher()); + + String accessTypeRestrictions = objectToJson((HashSet) vObj.getAccessTypeRestrictions()); + String isValidLeaf = objectToJson(vObj.getIsValidLeaf()); + Map matcherOptions = vObj.getMatcherOptions(); + + if (StringUtils.isNotBlank(accessTypeRestrictions)) { + matcherOptions.put(OPTION_RESOURCE_ACCESS_TYPE_RESTRICTIONS, accessTypeRestrictions); + } else { + matcherOptions.remove(OPTION_RESOURCE_ACCESS_TYPE_RESTRICTIONS); + } + + if (StringUtils.isNotBlank(isValidLeaf)) { + matcherOptions.put(OPTION_RESOURCE_IS_VALID_LEAF, isValidLeaf); + } else { + matcherOptions.remove(OPTION_RESOURCE_IS_VALID_LEAF); + } xObj.setMatcheroptions(mapToJsonString(matcherOptions)); + xObj.setValidationRegEx(vObj.getValidationRegEx()); + xObj.setValidationMessage(vObj.getValidationMessage()); + xObj.setUiHint(vObj.getUiHint()); + xObj.setLabel(vObj.getLabel()); + xObj.setDescription(vObj.getDescription()); + xObj.setRbkeylabel(vObj.getRbKeyLabel()); + xObj.setRbkeydescription(vObj.getRbKeyDescription()); + xObj.setRbKeyValidationMessage(vObj.getRbKeyValidationMessage()); + xObj.setOrder(AppConstants.DEFAULT_SORT_ORDER); + + return xObj; + } + + public RangerResourceDef populateXXToRangerResourceDef(XXResourceDef xObj) { + RangerResourceDef vObj = new RangerResourceDef(); + + vObj.setItemId(xObj.getItemId()); + vObj.setName(xObj.getName()); + vObj.setType(xObj.getType()); + vObj.setLevel(xObj.getLevel()); + vObj.setMandatory(xObj.getMandatory()); + vObj.setLookupSupported(xObj.getLookupsupported()); + vObj.setRecursiveSupported(xObj.getRecursivesupported()); + vObj.setExcludesSupported(xObj.getExcludessupported()); + vObj.setMatcher(xObj.getMatcher()); + + Map matcherOptions = jsonStringToMap(xObj.getMatcheroptions()); + + if (MapUtils.isNotEmpty(matcherOptions)) { + String optionAccessTypeRestrictions = matcherOptions.remove(OPTION_RESOURCE_ACCESS_TYPE_RESTRICTIONS); + String optionIsValidLeaf = matcherOptions.remove(OPTION_RESOURCE_IS_VALID_LEAF); + + if (StringUtils.isNotBlank(optionAccessTypeRestrictions)) { + Set accessTypeRestrictions = new HashSet<>(); + + accessTypeRestrictions = jsonToObject(optionAccessTypeRestrictions, accessTypeRestrictions.getClass()); + + vObj.setAccessTypeRestrictions(accessTypeRestrictions); + } + + if (StringUtils.isNotBlank(optionIsValidLeaf)) { + Boolean isValidLeaf = jsonToObject(optionIsValidLeaf, Boolean.class); + + vObj.setIsValidLeaf(isValidLeaf); + } + } + + vObj.setMatcherOptions(matcherOptions); + vObj.setValidationRegEx(xObj.getValidationRegEx()); + vObj.setValidationMessage(xObj.getValidationMessage()); + vObj.setUiHint(xObj.getUiHint()); + vObj.setLabel(xObj.getLabel()); + vObj.setDescription(xObj.getDescription()); + vObj.setRbKeyLabel(xObj.getRbkeylabel()); + vObj.setRbKeyDescription(xObj.getRbkeydescription()); + vObj.setRbKeyValidationMessage(xObj.getRbKeyValidationMessage()); + + XXResourceDef parent = daoMgr.getXXResourceDef().getById(xObj.getParent()); + String parentName = (parent != null) ? parent.getName() : null; + + vObj.setParent(parentName); + + return vObj; + } + + public XXAccessTypeDef populateRangerAccessTypeDefToXX(RangerAccessTypeDef vObj, XXAccessTypeDef xObj, XXServiceDef serviceDef, int operationContext) { + if (serviceDef == null) { + LOG.error("RangerServiceDefServiceBase.populateRangerAccessTypeDefToXX, serviceDef can not be null"); + + throw restErrorUtil.createRESTException("RangerServiceDef cannot be null.", MessageEnums.DATA_NOT_FOUND); + } + + xObj = rangerAuditFields.populateAuditFields(xObj, serviceDef); + + xObj.setDefid(serviceDef.getId()); + xObj.setItemId(vObj.getItemId()); + xObj.setName(vObj.getName()); + xObj.setLabel(vObj.getLabel()); + xObj.setRbkeylabel(vObj.getRbKeyLabel()); + xObj.setOrder(AppConstants.DEFAULT_SORT_ORDER); + + if (vObj.getCategory() != null) { + xObj.setCategory((short) vObj.getCategory().ordinal()); + } + + return xObj; + } + + public RangerAccessTypeDef populateXXToRangerAccessTypeDef(XXAccessTypeDef xObj) { + List impliedGrants = daoMgr.getXXAccessTypeDefGrants().findImpliedGrantsByATDId(xObj.getId()); + + return populateXXToRangerAccessTypeDef(xObj, impliedGrants); + } + + public RangerAccessTypeDef populateXXToRangerAccessTypeDef(XXAccessTypeDef xObj, List impliedGrants) { + RangerAccessTypeDef vObj = new RangerAccessTypeDef(); + + if (impliedGrants == null) { + impliedGrants = new ArrayList<>(); + } + + vObj.setItemId(xObj.getItemId()); + vObj.setName(xObj.getName()); + vObj.setLabel(xObj.getLabel()); + vObj.setRbKeyLabel(xObj.getRbkeylabel()); + vObj.setImpliedGrants(impliedGrants); + + if (xObj.getCategory() != null) { + vObj.setCategory(toAccessTypeCategory(xObj.getCategory())); + } + + return vObj; + } + + public XXPolicyConditionDef populateRangerPolicyConditionDefToXX(RangerPolicyConditionDef vObj, XXPolicyConditionDef xObj, XXServiceDef serviceDef, int operationContext) { + if (serviceDef == null) { + LOG.error("RangerServiceDefServiceBase.populateRangerPolicyConditionDefToXX, serviceDef can not be null"); + + throw restErrorUtil.createRESTException("RangerServiceDef cannot be null.", MessageEnums.DATA_NOT_FOUND); + } + + xObj = rangerAuditFields.populateAuditFields(xObj, serviceDef); + + xObj.setDefid(serviceDef.getId()); + xObj.setItemId(vObj.getItemId()); + xObj.setName(vObj.getName()); + xObj.setEvaluator(vObj.getEvaluator()); + xObj.setEvaluatoroptions(mapToJsonString(vObj.getEvaluatorOptions())); + xObj.setValidationRegEx(vObj.getValidationRegEx()); + xObj.setValidationMessage(vObj.getValidationMessage()); + xObj.setUiHint(vObj.getUiHint()); + xObj.setLabel(vObj.getLabel()); + xObj.setDescription(vObj.getDescription()); + xObj.setRbkeylabel(vObj.getRbKeyLabel()); + xObj.setRbkeydescription(vObj.getRbKeyDescription()); + xObj.setRbKeyValidationMessage(vObj.getRbKeyValidationMessage()); + xObj.setOrder(AppConstants.DEFAULT_SORT_ORDER); + + return xObj; + } + + public RangerPolicyConditionDef populateXXToRangerPolicyConditionDef(XXPolicyConditionDef xObj) { + RangerPolicyConditionDef vObj = new RangerPolicyConditionDef(); + + vObj.setItemId(xObj.getItemId()); + vObj.setName(xObj.getName()); + vObj.setEvaluator(xObj.getEvaluator()); + vObj.setEvaluatorOptions(jsonStringToMap(xObj.getEvaluatoroptions())); + vObj.setValidationRegEx(xObj.getValidationRegEx()); + vObj.setValidationMessage(xObj.getValidationMessage()); + vObj.setUiHint(xObj.getUiHint()); + vObj.setLabel(xObj.getLabel()); + vObj.setDescription(xObj.getDescription()); + vObj.setRbKeyLabel(xObj.getRbkeylabel()); + vObj.setRbKeyDescription(xObj.getRbkeydescription()); + vObj.setRbKeyValidationMessage(xObj.getRbKeyValidationMessage()); + + return vObj; + } + + public XXContextEnricherDef populateRangerContextEnricherDefToXX(RangerContextEnricherDef vObj, XXContextEnricherDef xObj, XXServiceDef serviceDef, int operationContext) { + if (serviceDef == null) { + LOG.error("RangerServiceDefServiceBase.populateRangerContextEnricherDefToXX, serviceDef can not be null"); + throw restErrorUtil.createRESTException("RangerServiceDef cannot be null.", MessageEnums.DATA_NOT_FOUND); + } + + xObj = rangerAuditFields.populateAuditFields(xObj, serviceDef); + + xObj.setDefid(serviceDef.getId()); + xObj.setItemId(vObj.getItemId()); + xObj.setName(vObj.getName()); + xObj.setEnricher(vObj.getEnricher()); + xObj.setEnricherOptions(mapToJsonString(vObj.getEnricherOptions())); + xObj.setOrder(AppConstants.DEFAULT_SORT_ORDER); + + return xObj; + } + + public RangerContextEnricherDef populateXXToRangerContextEnricherDef(XXContextEnricherDef xObj) { + RangerContextEnricherDef vObj = new RangerContextEnricherDef(); + + vObj.setItemId(xObj.getItemId()); + vObj.setName(xObj.getName()); + vObj.setEnricher(xObj.getEnricher()); + vObj.setEnricherOptions(jsonStringToMap(xObj.getEnricherOptions())); + + return vObj; + } + + public XXEnumDef populateRangerEnumDefToXX(RangerEnumDef vObj, XXEnumDef xObj, XXServiceDef serviceDef, int operationContext) { + if (serviceDef == null) { + LOG.error("RangerServiceDefServiceBase.populateRangerEnumDefToXX, serviceDef can not be null"); + + throw restErrorUtil.createRESTException("RangerServiceDef cannot be null.", MessageEnums.DATA_NOT_FOUND); + } + + xObj = rangerAuditFields.populateAuditFields(xObj, serviceDef); + + xObj.setDefid(serviceDef.getId()); + xObj.setItemId(vObj.getItemId()); + xObj.setName(vObj.getName()); + xObj.setDefaultindex(vObj.getDefaultIndex()); + + return xObj; + } + + public RangerEnumDef populateXXToRangerEnumDef(XXEnumDef xObj) { + RangerEnumDef vObj = new RangerEnumDef(); + + vObj.setItemId(xObj.getItemId()); + vObj.setName(xObj.getName()); + vObj.setDefaultIndex(xObj.getDefaultindex()); + + List xElements = daoMgr.getXXEnumElementDef().findByEnumDefId(xObj.getId()); + List elements = new ArrayList<>(); + + for (XXEnumElementDef xEle : xElements) { + RangerEnumElementDef element = populateXXToRangerEnumElementDef(xEle); + + elements.add(element); + } + + vObj.setElements(elements); + + return vObj; + } + + public XXEnumElementDef populateRangerEnumElementDefToXX(RangerEnumElementDef vObj, XXEnumElementDef xObj, XXEnumDef enumDef, int operationContext) { + if (enumDef == null) { + LOG.error("RangerServiceDefServiceBase.populateRangerEnumElementDefToXX, enumDef can not be null"); + + throw restErrorUtil.createRESTException("enumDef cannot be null.", MessageEnums.DATA_NOT_FOUND); + } + + xObj = rangerAuditFields.populateAuditFields(xObj, enumDef); + + xObj.setEnumdefid(enumDef.getId()); + xObj.setItemId(vObj.getItemId()); + xObj.setName(vObj.getName()); + xObj.setLabel(vObj.getLabel()); + xObj.setRbkeylabel(vObj.getRbKeyLabel()); + xObj.setOrder(AppConstants.DEFAULT_SORT_ORDER); + + return xObj; + } + + public RangerEnumElementDef populateXXToRangerEnumElementDef(XXEnumElementDef xObj) { + RangerEnumElementDef vObj = new RangerEnumElementDef(); + + vObj.setItemId(xObj.getItemId()); + vObj.setName(xObj.getName()); + vObj.setLabel(xObj.getLabel()); + vObj.setRbKeyLabel(xObj.getRbkeylabel()); + + return vObj; + } + + public XXDataMaskTypeDef populateRangerDataMaskDefToXX(RangerDataMaskTypeDef vObj, XXDataMaskTypeDef xObj, XXServiceDef serviceDef, int operationContext) { + if (serviceDef == null) { + LOG.error("RangerServiceDefServiceBase.populateRangerDataMaskDefToXX, serviceDef can not be null"); + + throw restErrorUtil.createRESTException("RangerServiceDef cannot be null.", MessageEnums.DATA_NOT_FOUND); + } + + xObj = rangerAuditFields.populateAuditFields(xObj, serviceDef); + + xObj.setDefid(serviceDef.getId()); + xObj.setItemId(vObj.getItemId()); + xObj.setName(vObj.getName()); + xObj.setLabel(vObj.getLabel()); + xObj.setDescription(vObj.getDescription()); + xObj.setTransformer(vObj.getTransformer()); + xObj.setDataMaskOptions(mapToJsonString(vObj.getDataMaskOptions())); + xObj.setRbkeylabel(vObj.getRbKeyLabel()); + xObj.setRbKeyDescription(vObj.getRbKeyDescription()); + xObj.setOrder(AppConstants.DEFAULT_SORT_ORDER); + + return xObj; + } + + public RangerDataMaskTypeDef populateXXToRangerDataMaskTypeDef(XXDataMaskTypeDef xObj) { + RangerDataMaskTypeDef vObj = new RangerDataMaskTypeDef(); + + vObj.setItemId(xObj.getItemId()); + vObj.setName(xObj.getName()); + vObj.setLabel(xObj.getLabel()); + vObj.setDescription(xObj.getDescription()); + vObj.setTransformer(xObj.getTransformer()); + vObj.setDataMaskOptions(jsonStringToMap(xObj.getDataMaskOptions())); + vObj.setRbKeyLabel(xObj.getRbkeylabel()); + vObj.setRbKeyDescription(xObj.getRbKeyDescription()); + + return vObj; + } + + public RangerServiceDefList searchRangerServiceDefs(SearchFilter searchFilter) { + RangerServiceDefList retList = new RangerServiceDefList(); + int startIndex = searchFilter.getStartIndex(); + int pageSize = searchFilter.getMaxRows(); + String denyCondition = searchFilter.getParam(SearchFilter.FETCH_DENY_CONDITION); + + searchFilter.setStartIndex(0); + searchFilter.setMaxRows(Integer.MAX_VALUE); + + boolean isAuditPage = searchFilter.getParam("pageSource") != null; + List xSvcDefList = searchResources(searchFilter, searchFields, sortFields, retList); + List permittedServiceDefs = new ArrayList<>(); + + for (T xSvcDef : xSvcDefList) { + if ((bizUtil.hasAccess(xSvcDef, null) || (bizUtil.isAdmin() && isAuditPage)) || ("true".equals(denyCondition))) { + if (!bizUtil.isGdsServiceDef(xSvcDef)) { + permittedServiceDefs.add(xSvcDef); + } + } + } + + if (!permittedServiceDefs.isEmpty()) { + populatePageList(permittedServiceDefs, startIndex, pageSize, retList); + } + + return retList; + } + + public String objectToJson(Serializable obj) { + String ret = null; + + if (obj != null) { + try { + ret = jsonUtil.writeObjectAsString(obj); + } catch (Exception excp) { + LOG.warn("objectToJson() failed to convert object to json: {}", obj, excp); + } + } + + return ret; + } + + public DST jsonToObject(String jsonStr, Class clz) { + DST ret = null; + + if (StringUtils.isNotEmpty(jsonStr)) { + try { + ret = jsonUtil.writeJsonToJavaObject(jsonStr, clz); + } catch (Exception excp) { + LOG.warn("jsonToObject() failed to convert json to object: {}", jsonStr, excp); + } + } + + return ret; + } + + @Override + protected T mapViewToEntityBean(V vObj, T xObj, int operationContext) { + String guid = (StringUtils.isEmpty(vObj.getGuid())) ? guidUtil.genGUID() : vObj.getGuid(); + + xObj.setGuid(guid); + xObj.setName(vObj.getName()); + xObj.setDisplayName(vObj.getDisplayName()); + xObj.setImplclassname(vObj.getImplClass()); + xObj.setLabel(vObj.getLabel()); + xObj.setDescription(vObj.getDescription()); + xObj.setRbkeylabel(vObj.getRbKeyLabel()); + xObj.setRbkeydescription(vObj.getRbKeyDescription()); + xObj.setIsEnabled(vObj.getIsEnabled()); + xObj.setDefOptions(mapToJsonString(vObj.getOptions())); + + return xObj; + } + + @Override + protected V mapEntityToViewBean(V vObj, T xObj) { + vObj.setGuid(xObj.getGuid()); + vObj.setVersion(xObj.getVersion()); + vObj.setName(xObj.getName()); + vObj.setImplClass(xObj.getImplclassname()); + vObj.setLabel(xObj.getLabel()); + vObj.setDescription(xObj.getDescription()); + vObj.setOptions(jsonStringToMap(xObj.getDefOptions())); + vObj.setRbKeyLabel(xObj.getRbkeylabel()); + vObj.setRbKeyDescription(xObj.getRbkeydescription()); + vObj.setIsEnabled(xObj.getIsEnabled()); + vObj.setDisplayName(xObj.getDisplayName()); + + return vObj; + } + + @Override + protected V populateViewBean(T xServiceDef) { + V serviceDef = super.populateViewBean(xServiceDef); + Long serviceDefId = xServiceDef.getId(); + List xConfigs = daoMgr.getXXServiceConfigDef().findByServiceDefId(serviceDefId); + + if (!stringUtil.isEmpty(xConfigs)) { + List configs = new ArrayList<>(); + + for (XXServiceConfigDef xConfig : xConfigs) { + RangerServiceConfigDef config = populateXXToRangerServiceConfigDef(xConfig); + + configs.add(config); + } + + serviceDef.setConfigs(configs); + } + + List xResources = daoMgr.getXXResourceDef().findByServiceDefId(serviceDefId); + + if (!stringUtil.isEmpty(xResources)) { + List resources = new ArrayList<>(); + + for (XXResourceDef xResource : xResources) { + RangerResourceDef resource = populateXXToRangerResourceDef(xResource); + + resources.add(resource); + } + + serviceDef.setResources(resources); + } + + List xAccessTypes = daoMgr.getXXAccessTypeDef().findByServiceDefId(serviceDefId); + Map> impliedGrants = daoMgr.getXXAccessTypeDefGrants().findImpliedGrantsByServiceDefId(serviceDefId); + + if (!stringUtil.isEmpty(xAccessTypes)) { + List accessTypes = new ArrayList<>(); + + for (XXAccessTypeDef xAtd : xAccessTypes) { + RangerAccessTypeDef accessType = populateXXToRangerAccessTypeDef(xAtd, impliedGrants.get(xAtd.getName())); + + accessTypes.add(accessType); + } + + serviceDef.setAccessTypes(accessTypes); + } + + serviceDef.setMarkerAccessTypes(ServiceDefUtil.getMarkerAccessTypes(serviceDef.getAccessTypes())); + + List xPolicyConditions = daoMgr.getXXPolicyConditionDef().findByServiceDefId(serviceDefId); + + if (!stringUtil.isEmpty(xPolicyConditions)) { + List policyConditions = new ArrayList<>(); + + for (XXPolicyConditionDef xPolicyCondDef : xPolicyConditions) { + RangerPolicyConditionDef policyCondition = populateXXToRangerPolicyConditionDef(xPolicyCondDef); + + policyConditions.add(policyCondition); + } + + serviceDef.setPolicyConditions(policyConditions); + } + + List xContextEnrichers = daoMgr.getXXContextEnricherDef().findByServiceDefId(serviceDefId); + + if (!stringUtil.isEmpty(xContextEnrichers)) { + List contextEnrichers = new ArrayList<>(); + + for (XXContextEnricherDef xContextEnricherDef : xContextEnrichers) { + RangerContextEnricherDef contextEnricher = populateXXToRangerContextEnricherDef(xContextEnricherDef); + + contextEnrichers.add(contextEnricher); + } + + serviceDef.setContextEnrichers(contextEnrichers); + } + + List xEnumList = daoMgr.getXXEnumDef().findByServiceDefId(serviceDefId); + + if (!stringUtil.isEmpty(xEnumList)) { + List enums = new ArrayList<>(); + + for (XXEnumDef xEnum : xEnumList) { + RangerEnumDef vEnum = populateXXToRangerEnumDef(xEnum); + + enums.add(vEnum); + } + + serviceDef.setEnums(enums); + } + + RangerDataMaskDef dataMaskDef = new RangerDataMaskDef(); + RangerRowFilterDef rowFilterDef = new RangerRowFilterDef(); + List xDataMaskTypes = daoMgr.getXXDataMaskTypeDef().findByServiceDefId(serviceDefId); + + if (!stringUtil.isEmpty(xDataMaskTypes)) { + List dataMaskTypes = new ArrayList<>(); + + for (XXDataMaskTypeDef xDataMaskType : xDataMaskTypes) { + RangerDataMaskTypeDef dataMaskType = populateXXToRangerDataMaskTypeDef(xDataMaskType); + + dataMaskTypes.add(dataMaskType); + } + + dataMaskDef.setMaskTypes(dataMaskTypes); + } + + if (!stringUtil.isEmpty(xResources)) { + for (XXResourceDef xResource : xResources) { + if (StringUtils.isNotEmpty(xResource.getDataMaskOptions())) { + RangerResourceDef dataMaskResource = jsonToObject(xResource.getDataMaskOptions(), RangerResourceDef.class); + + dataMaskDef.getResources().add(dataMaskResource); + } + + if (StringUtils.isNotEmpty(xResource.getRowFilterOptions())) { + RangerResourceDef resource = jsonToObject(xResource.getRowFilterOptions(), RangerResourceDef.class); + + rowFilterDef.getResources().add(resource); + } + } + } + + if (!stringUtil.isEmpty(xAccessTypes)) { + for (XXAccessTypeDef xAtd : xAccessTypes) { + if (StringUtils.isNotEmpty(xAtd.getDataMaskOptions())) { + RangerAccessTypeDef dataMaskAccessType = jsonToObject(xAtd.getDataMaskOptions(), RangerAccessTypeDef.class); + + dataMaskDef.getAccessTypes().add(dataMaskAccessType); + } + + if (StringUtils.isNotEmpty(xAtd.getRowFilterOptions())) { + RangerAccessTypeDef accessType = jsonToObject(xAtd.getRowFilterOptions(), RangerAccessTypeDef.class); + + rowFilterDef.getAccessTypes().add(accessType); + } + } + } + + serviceDef.setDataMaskDef(dataMaskDef); + serviceDef.setRowFilterDef(rowFilterDef); + + addImplicitConditionExpressionIfNeeded(serviceDef); + + ServiceDefUtil.normalize(serviceDef); + + return serviceDef; + } + + protected Map jsonStringToMap(String jsonStr) { + Map ret = null; + + if (!StringUtils.isEmpty(jsonStr)) { + try { + ret = jsonUtil.jsonToMap(jsonStr); + } catch (Exception excp) { + // fallback to earlier format: "name1=value1;name2=value2" + for (String optionString : jsonStr.split(";")) { + if (StringUtils.isEmpty(optionString)) { + continue; + } + + String[] nvArr = optionString.split("="); + String name = nvArr.length > 0 ? nvArr[0].trim() : null; + String value = nvArr.length > 1 ? nvArr[1].trim() : null; + + if (StringUtils.isEmpty(name)) { + continue; + } + + if (ret == null) { + ret = new HashMap<>(); + } + + ret.put(name, value); + } + } + } + + return ret; + } + + boolean addImplicitConditionExpressionIfNeeded(RangerServiceDef serviceDef) { + boolean ret = false; + boolean implicitConditionDefault = PropertiesUtil.getBooleanProperty(PROP_ENABLE_IMPLICIT_CONDITION_EXPRESSION, true); + boolean implicitConditionEnabled = ServiceDefUtil.getBooleanValue(serviceDef.getOptions(), RangerServiceDef.OPTION_ENABLE_IMPLICIT_CONDITION_EXPRESSION, implicitConditionDefault); + + if (implicitConditionEnabled) { + boolean exists = false; + List conditionDefs = serviceDef.getPolicyConditions(); + + if (conditionDefs == null) { + conditionDefs = new ArrayList<>(); + } + + for (RangerPolicyConditionDef conditionDef : conditionDefs) { + if (StringUtils.equalsIgnoreCase(conditionDef.getEvaluator(), IMPLICIT_CONDITION_EXPRESSION_EVALUATOR)) { + exists = true; + + break; + } + } + + if (!exists) { + long maxItemId = ServiceDefUtil.getConditionsMaxItemId(conditionDefs); + + conditionDefs.add(ServiceDefUtil.createImplicitExpressionConditionDef(maxItemId + 1)); + + serviceDef.setPolicyConditions(conditionDefs); + + ret = true; + } + } + + LOG.debug("addImplicitConditionExpressionIfNeeded(serviceType={}): implicitConditionDefault={}, implicitConditionEnabled={}, conditionDefs={}, ret={}", serviceDef.getName(), implicitConditionDefault, implicitConditionEnabled, serviceDef.getPolicyConditions(), ret); - xObj.setValidationRegEx(vObj.getValidationRegEx()); - xObj.setValidationMessage(vObj.getValidationMessage()); - xObj.setUiHint(vObj.getUiHint()); - xObj.setLabel(vObj.getLabel()); - xObj.setDescription(vObj.getDescription()); - xObj.setRbkeylabel(vObj.getRbKeyLabel()); - xObj.setRbkeydescription(vObj.getRbKeyDescription()); - xObj.setRbKeyValidationMessage(vObj.getRbKeyValidationMessage()); - xObj.setOrder(AppConstants.DEFAULT_SORT_ORDER); - return xObj; - } - - public RangerResourceDef populateXXToRangerResourceDef(XXResourceDef xObj) { - RangerResourceDef vObj = new RangerResourceDef(); - vObj.setItemId(xObj.getItemId()); - vObj.setName(xObj.getName()); - vObj.setType(xObj.getType()); - vObj.setLevel(xObj.getLevel()); - vObj.setMandatory(xObj.getMandatory()); - vObj.setLookupSupported(xObj.getLookupsupported()); - vObj.setRecursiveSupported(xObj.getRecursivesupported()); - vObj.setExcludesSupported(xObj.getExcludessupported()); - vObj.setMatcher(xObj.getMatcher()); - - Map matcherOptions = jsonStringToMap(xObj.getMatcheroptions()); - - if (MapUtils.isNotEmpty(matcherOptions)) { - String optionAccessTypeRestrictions = matcherOptions.remove(OPTION_RESOURCE_ACCESS_TYPE_RESTRICTIONS); - String optionIsValidLeaf = matcherOptions.remove(OPTION_RESOURCE_IS_VALID_LEAF); - - if (StringUtils.isNotBlank(optionAccessTypeRestrictions)) { - Set accessTypeRestrictions = new HashSet<>(); - - accessTypeRestrictions = jsonToObject(optionAccessTypeRestrictions, accessTypeRestrictions.getClass()); - - vObj.setAccessTypeRestrictions(accessTypeRestrictions); - } - - if (StringUtils.isNotBlank(optionIsValidLeaf)) { - Boolean isValidLeaf = jsonToObject(optionIsValidLeaf, Boolean.class); - - vObj.setIsValidLeaf(isValidLeaf); - } - } - - vObj.setMatcherOptions(matcherOptions); - - vObj.setValidationRegEx(xObj.getValidationRegEx()); - vObj.setValidationMessage(xObj.getValidationMessage()); - vObj.setUiHint(xObj.getUiHint()); - vObj.setLabel(xObj.getLabel()); - vObj.setDescription(xObj.getDescription()); - vObj.setRbKeyLabel(xObj.getRbkeylabel()); - vObj.setRbKeyDescription(xObj.getRbkeydescription()); - vObj.setRbKeyValidationMessage(xObj.getRbKeyValidationMessage()); - - XXResourceDef parent = daoMgr.getXXResourceDef().getById(xObj.getParent()); - String parentName = (parent != null) ? parent.getName() : null; - vObj.setParent(parentName); - - return vObj; - } - - public XXAccessTypeDef populateRangerAccessTypeDefToXX(RangerAccessTypeDef vObj, XXAccessTypeDef xObj, - XXServiceDef serviceDef, int operationContext) { - if(serviceDef == null) { - LOG.error("RangerServiceDefServiceBase.populateRangerAccessTypeDefToXX, serviceDef can not be null"); - throw restErrorUtil.createRESTException("RangerServiceDef cannot be null.", MessageEnums.DATA_NOT_FOUND); - } - - xObj = rangerAuditFields.populateAuditFields(xObj, serviceDef); - xObj.setDefid(serviceDef.getId()); - xObj.setItemId(vObj.getItemId()); - xObj.setName(vObj.getName()); - xObj.setLabel(vObj.getLabel()); - xObj.setRbkeylabel(vObj.getRbKeyLabel()); - xObj.setOrder(AppConstants.DEFAULT_SORT_ORDER); - - if (vObj.getCategory() != null) { - xObj.setCategory((short) vObj.getCategory().ordinal()); - } - - return xObj; - } - - public RangerAccessTypeDef populateXXToRangerAccessTypeDef(XXAccessTypeDef xObj) { - List impliedGrants = daoMgr.getXXAccessTypeDefGrants().findImpliedGrantsByATDId(xObj.getId()); - - return populateXXToRangerAccessTypeDef(xObj, impliedGrants); - } - - public RangerAccessTypeDef populateXXToRangerAccessTypeDef(XXAccessTypeDef xObj, List impliedGrants) { - RangerAccessTypeDef vObj = new RangerAccessTypeDef(); - - if (impliedGrants == null) { - impliedGrants = new ArrayList<>(); - } - - vObj.setItemId(xObj.getItemId()); - vObj.setName(xObj.getName()); - vObj.setLabel(xObj.getLabel()); - vObj.setRbKeyLabel(xObj.getRbkeylabel()); - vObj.setImpliedGrants(impliedGrants); - - if (xObj.getCategory() != null) { - vObj.setCategory(toAccessTypeCategory(xObj.getCategory())); - } - - return vObj; - } - - public XXPolicyConditionDef populateRangerPolicyConditionDefToXX(RangerPolicyConditionDef vObj, - XXPolicyConditionDef xObj, XXServiceDef serviceDef, int operationContext) { - if(serviceDef == null) { - LOG.error("RangerServiceDefServiceBase.populateRangerPolicyConditionDefToXX, serviceDef can not be null"); - throw restErrorUtil.createRESTException("RangerServiceDef cannot be null.", MessageEnums.DATA_NOT_FOUND); - } - - xObj = rangerAuditFields.populateAuditFields(xObj, serviceDef); - xObj.setDefid(serviceDef.getId()); - xObj.setItemId(vObj.getItemId()); - xObj.setName(vObj.getName()); - xObj.setEvaluator(vObj.getEvaluator()); - xObj.setEvaluatoroptions(mapToJsonString(vObj.getEvaluatorOptions())); - xObj.setValidationRegEx(vObj.getValidationRegEx()); - xObj.setValidationMessage(vObj.getValidationMessage()); - xObj.setUiHint(vObj.getUiHint()); - xObj.setLabel(vObj.getLabel()); - xObj.setDescription(vObj.getDescription()); - xObj.setRbkeylabel(vObj.getRbKeyLabel()); - xObj.setRbkeydescription(vObj.getRbKeyDescription()); - xObj.setRbKeyValidationMessage(vObj.getRbKeyValidationMessage()); - xObj.setOrder(AppConstants.DEFAULT_SORT_ORDER); - return xObj; - } - - public RangerPolicyConditionDef populateXXToRangerPolicyConditionDef(XXPolicyConditionDef xObj) { - RangerPolicyConditionDef vObj = new RangerPolicyConditionDef(); - vObj.setItemId(xObj.getItemId()); - vObj.setName(xObj.getName()); - vObj.setEvaluator(xObj.getEvaluator()); - vObj.setEvaluatorOptions(jsonStringToMap(xObj.getEvaluatoroptions())); - vObj.setValidationRegEx(xObj.getValidationRegEx()); - vObj.setValidationMessage(xObj.getValidationMessage()); - vObj.setUiHint(xObj.getUiHint()); - vObj.setLabel(xObj.getLabel()); - vObj.setDescription(xObj.getDescription()); - vObj.setRbKeyLabel(xObj.getRbkeylabel()); - vObj.setRbKeyDescription(xObj.getRbkeydescription()); - vObj.setRbKeyValidationMessage(xObj.getRbKeyValidationMessage()); - return vObj; - } - - public XXContextEnricherDef populateRangerContextEnricherDefToXX(RangerContextEnricherDef vObj, - XXContextEnricherDef xObj, XXServiceDef serviceDef, int operationContext) { - if(serviceDef == null) { - LOG.error("RangerServiceDefServiceBase.populateRangerContextEnricherDefToXX, serviceDef can not be null"); - throw restErrorUtil.createRESTException("RangerServiceDef cannot be null.", MessageEnums.DATA_NOT_FOUND); - } - - xObj = rangerAuditFields.populateAuditFields(xObj, serviceDef); - xObj.setDefid(serviceDef.getId()); - xObj.setItemId(vObj.getItemId()); - xObj.setName(vObj.getName()); - xObj.setEnricher(vObj.getEnricher()); - xObj.setEnricherOptions(mapToJsonString(vObj.getEnricherOptions())); - xObj.setOrder(AppConstants.DEFAULT_SORT_ORDER); - return xObj; - } - - public RangerContextEnricherDef populateXXToRangerContextEnricherDef(XXContextEnricherDef xObj) { - RangerContextEnricherDef vObj = new RangerContextEnricherDef(); - vObj.setItemId(xObj.getItemId()); - vObj.setName(xObj.getName()); - vObj.setEnricher(xObj.getEnricher()); - vObj.setEnricherOptions(jsonStringToMap(xObj.getEnricherOptions())); - return vObj; - } - - public XXEnumDef populateRangerEnumDefToXX(RangerEnumDef vObj, XXEnumDef xObj, XXServiceDef serviceDef, - int operationContext) { - if(serviceDef == null) { - LOG.error("RangerServiceDefServiceBase.populateRangerEnumDefToXX, serviceDef can not be null"); - throw restErrorUtil.createRESTException("RangerServiceDef cannot be null.", MessageEnums.DATA_NOT_FOUND); - } - - xObj = rangerAuditFields.populateAuditFields(xObj, serviceDef); - xObj.setDefid(serviceDef.getId()); - xObj.setItemId(vObj.getItemId()); - xObj.setName(vObj.getName()); - xObj.setDefaultindex(vObj.getDefaultIndex()); - return xObj; - } - - public RangerEnumDef populateXXToRangerEnumDef(XXEnumDef xObj) { - RangerEnumDef vObj = new RangerEnumDef(); - vObj.setItemId(xObj.getItemId()); - vObj.setName(xObj.getName()); - vObj.setDefaultIndex(xObj.getDefaultindex()); - - List xElements = daoMgr.getXXEnumElementDef().findByEnumDefId(xObj.getId()); - List elements = new ArrayList(); - - for(XXEnumElementDef xEle : xElements) { - RangerEnumElementDef element = populateXXToRangerEnumElementDef(xEle); - elements.add(element); - } - vObj.setElements(elements); - - return vObj; - } - - public XXEnumElementDef populateRangerEnumElementDefToXX(RangerEnumElementDef vObj, XXEnumElementDef xObj, - XXEnumDef enumDef, int operationContext) { - if(enumDef == null) { - LOG.error("RangerServiceDefServiceBase.populateRangerEnumElementDefToXX, enumDef can not be null"); - throw restErrorUtil.createRESTException("enumDef cannot be null.", MessageEnums.DATA_NOT_FOUND); - } - - xObj = rangerAuditFields.populateAuditFields(xObj, enumDef); - xObj.setEnumdefid(enumDef.getId()); - xObj.setItemId(vObj.getItemId()); - xObj.setName(vObj.getName()); - xObj.setLabel(vObj.getLabel()); - xObj.setRbkeylabel(vObj.getRbKeyLabel()); - xObj.setOrder(AppConstants.DEFAULT_SORT_ORDER); - return xObj; - } - - public RangerEnumElementDef populateXXToRangerEnumElementDef(XXEnumElementDef xObj) { - RangerEnumElementDef vObj = new RangerEnumElementDef(); - vObj.setItemId(xObj.getItemId()); - vObj.setName(xObj.getName()); - vObj.setLabel(xObj.getLabel()); - vObj.setRbKeyLabel(xObj.getRbkeylabel()); - return vObj; - } - - public XXDataMaskTypeDef populateRangerDataMaskDefToXX(RangerDataMaskTypeDef vObj, XXDataMaskTypeDef xObj, - XXServiceDef serviceDef, int operationContext) { - if(serviceDef == null) { - LOG.error("RangerServiceDefServiceBase.populateRangerDataMaskDefToXX, serviceDef can not be null"); - throw restErrorUtil.createRESTException("RangerServiceDef cannot be null.", MessageEnums.DATA_NOT_FOUND); - } - - xObj = rangerAuditFields.populateAuditFields(xObj, serviceDef); - xObj.setDefid(serviceDef.getId()); - xObj.setItemId(vObj.getItemId()); - xObj.setName(vObj.getName()); - xObj.setLabel(vObj.getLabel()); - xObj.setDescription(vObj.getDescription()); - xObj.setTransformer(vObj.getTransformer()); - xObj.setDataMaskOptions(mapToJsonString(vObj.getDataMaskOptions())); - xObj.setRbkeylabel(vObj.getRbKeyLabel()); - xObj.setRbKeyDescription(vObj.getRbKeyDescription()); - xObj.setOrder(AppConstants.DEFAULT_SORT_ORDER); - return xObj; - } - - public RangerDataMaskTypeDef populateXXToRangerDataMaskTypeDef(XXDataMaskTypeDef xObj) { - RangerDataMaskTypeDef vObj = new RangerDataMaskTypeDef(); - vObj.setItemId(xObj.getItemId()); - vObj.setName(xObj.getName()); - vObj.setLabel(xObj.getLabel()); - vObj.setDescription(xObj.getDescription()); - vObj.setTransformer(xObj.getTransformer()); - vObj.setDataMaskOptions(jsonStringToMap(xObj.getDataMaskOptions())); - vObj.setRbKeyLabel(xObj.getRbkeylabel()); - vObj.setRbKeyDescription(xObj.getRbKeyDescription()); - - return vObj; - } - - public RangerServiceDefList searchRangerServiceDefs(SearchFilter searchFilter) { - RangerServiceDefList retList = new RangerServiceDefList(); - int startIndex = searchFilter.getStartIndex(); - int pageSize = searchFilter.getMaxRows(); - String denyCondition = searchFilter.getParam(SearchFilter.FETCH_DENY_CONDITION); - searchFilter.setStartIndex(0); - searchFilter.setMaxRows(Integer.MAX_VALUE); - - boolean isAuditPage=false; - if(searchFilter.getParam("pageSource")!=null){ - isAuditPage=true; - } - List xSvcDefList = searchResources(searchFilter, searchFields, sortFields, - retList); - List permittedServiceDefs = new ArrayList(); - for (T xSvcDef : xSvcDefList) { - if ((bizUtil.hasAccess(xSvcDef, null) || (bizUtil.isAdmin() && isAuditPage)) || ("true".equals(denyCondition))) { - if (!bizUtil.isGdsServiceDef(xSvcDef)) { - permittedServiceDefs.add(xSvcDef); - } - } - } - if (!permittedServiceDefs.isEmpty()) { - populatePageList(permittedServiceDefs, startIndex, pageSize, retList); - } - return retList; - - } - - - private void populatePageList(List xxObjList, int startIndex, int pageSize, - RangerServiceDefList retList) { - List onePageList = new ArrayList(); - - for (int i = startIndex; i < pageSize + startIndex && i < xxObjList.size(); i++) { - onePageList.add(populateViewBean(xxObjList.get(i))); - } - retList.setServiceDefs(onePageList); - retList.setStartIndex(startIndex); - retList.setPageSize(pageSize); - retList.setResultSize(onePageList.size()); - retList.setTotalCount(xxObjList.size()); - } - - private String mapToJsonString(Map map) { - String ret = null; - - if(map != null) { - try { - ret = jsonUtil.readMapToString(map); - } catch(Exception excp) { - LOG.warn("mapToJsonString() failed to convert map: " + map, excp); - } - } - - return ret; - } - - protected Map jsonStringToMap(String jsonStr) { - Map ret = null; - - if(!StringUtils.isEmpty(jsonStr)) { - try { - ret = jsonUtil.jsonToMap(jsonStr); - } catch(Exception excp) { - // fallback to earlier format: "name1=value1;name2=value2" - for(String optionString : jsonStr.split(";")) { - if(StringUtils.isEmpty(optionString)) { - continue; - } - - String[] nvArr = optionString.split("="); - - String name = (nvArr != null && nvArr.length > 0) ? nvArr[0].trim() : null; - String value = (nvArr != null && nvArr.length > 1) ? nvArr[1].trim() : null; - - if(StringUtils.isEmpty(name)) { - continue; - } - - if(ret == null) { - ret = new HashMap(); - } - - ret.put(name, value); - } - } - } - - return ret; - } - - public String objectToJson(Serializable obj) { - String ret = null; - - if(obj != null) { - try { - ret = jsonUtil.writeObjectAsString(obj); - } catch(Exception excp) { - LOG.warn("objectToJson() failed to convert object to json: " + obj, excp); - } - } - - return ret; - } - - public DST jsonToObject(String jsonStr, Class clz) { - DST ret = null; - - if(StringUtils.isNotEmpty(jsonStr)) { - try { - ret = jsonUtil.writeJsonToJavaObject(jsonStr, clz); - } catch(Exception excp) { - LOG.warn("jsonToObject() failed to convert json to object: " + jsonStr, excp); - } - } - - return ret; - } - - - boolean addImplicitConditionExpressionIfNeeded(RangerServiceDef serviceDef) { - boolean ret = false; - boolean implicitConditionDefault = PropertiesUtil.getBooleanProperty(PROP_ENABLE_IMPLICIT_CONDITION_EXPRESSION, true); - boolean implicitConditionEnabled = ServiceDefUtil.getBooleanValue(serviceDef.getOptions(), RangerServiceDef.OPTION_ENABLE_IMPLICIT_CONDITION_EXPRESSION, implicitConditionDefault); - - if (implicitConditionEnabled) { - boolean exists = false; - List conditionDefs = serviceDef.getPolicyConditions(); - - if (conditionDefs == null) { - conditionDefs = new ArrayList<>(); - } - - for (RangerPolicyConditionDef conditionDef : conditionDefs) { - if (StringUtils.equalsIgnoreCase(conditionDef.getEvaluator(), IMPLICIT_CONDITION_EXPRESSION_EVALUATOR)) { - exists = true; - - break; - } - } + return ret; + } - if (!exists) { - long maxItemId = ServiceDefUtil.getConditionsMaxItemId(conditionDefs); + private void populatePageList(List xxObjList, int startIndex, int pageSize, RangerServiceDefList retList) { + List onePageList = new ArrayList<>(); - conditionDefs.add(ServiceDefUtil.createImplicitExpressionConditionDef(maxItemId + 1)); + for (int i = startIndex; i < pageSize + startIndex && i < xxObjList.size(); i++) { + onePageList.add(populateViewBean(xxObjList.get(i))); + } - serviceDef.setPolicyConditions(conditionDefs); + retList.setServiceDefs(onePageList); + retList.setStartIndex(startIndex); + retList.setPageSize(pageSize); + retList.setResultSize(onePageList.size()); + retList.setTotalCount(xxObjList.size()); + } - ret = true; - } - } + private String mapToJsonString(Map map) { + String ret = null; - if (LOG.isDebugEnabled()) { - LOG.debug("addImplicitConditionExpressionIfNeeded(serviceType={}): implicitConditionDefault={}, implicitConditionEnabled={}, conditionDefs={}, ret={}", serviceDef.getName(), implicitConditionDefault, implicitConditionEnabled, serviceDef.getPolicyConditions(), ret); - } + if (map != null) { + try { + ret = jsonUtil.readMapToString(map); + } catch (Exception excp) { + LOG.warn("mapToJsonString() failed to convert map: {}", map, excp); + } + } - return ret; - } + return ret; + } - private AccessTypeCategory toAccessTypeCategory(short val) { - AccessTypeCategory ret = null; + private AccessTypeCategory toAccessTypeCategory(short val) { + AccessTypeCategory ret = null; - for (AccessTypeCategory category : AccessTypeCategory.values()) { - if (category.ordinal() == val) { - ret = category; + for (AccessTypeCategory category : AccessTypeCategory.values()) { + if (category.ordinal() == val) { + ret = category; - break; - } - } + break; + } + } - return ret; - } + return ret; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/service/RangerServiceDefWithAssignedIdService.java b/security-admin/src/main/java/org/apache/ranger/service/RangerServiceDefWithAssignedIdService.java index ef4984d6cb..7d0861b84b 100644 --- a/security-admin/src/main/java/org/apache/ranger/service/RangerServiceDefWithAssignedIdService.java +++ b/security-admin/src/main/java/org/apache/ranger/service/RangerServiceDefWithAssignedIdService.java @@ -23,30 +23,25 @@ @Service public class RangerServiceDefWithAssignedIdService extends RangerServiceDefServiceBase { - - @Override - protected XXServiceDefWithAssignedId mapViewToEntityBean(RangerServiceDef vObj, XXServiceDefWithAssignedId xObj, - int OPERATION_CONTEXT) { - return super.mapViewToEntityBean(vObj, xObj, OPERATION_CONTEXT); - } - - @Override - protected RangerServiceDef mapEntityToViewBean(RangerServiceDef vObj, XXServiceDefWithAssignedId xObj) { - return super.mapEntityToViewBean(vObj, xObj); - } - - @Override - protected void validateForCreate(RangerServiceDef vObj) { - - } - - @Override - protected void validateForUpdate(RangerServiceDef vServiceDef, XXServiceDefWithAssignedId xServiceDef) { - - } - - public RangerServiceDef getPopulatedViewObject(XXServiceDefWithAssignedId xServiceDef) { - return this.populateViewBean(xServiceDef); - } - + public RangerServiceDef getPopulatedViewObject(XXServiceDefWithAssignedId xServiceDef) { + return this.populateViewBean(xServiceDef); + } + + @Override + protected XXServiceDefWithAssignedId mapViewToEntityBean(RangerServiceDef vObj, XXServiceDefWithAssignedId xObj, int operationContext) { + return super.mapViewToEntityBean(vObj, xObj, operationContext); + } + + @Override + protected RangerServiceDef mapEntityToViewBean(RangerServiceDef vObj, XXServiceDefWithAssignedId xObj) { + return super.mapEntityToViewBean(vObj, xObj); + } + + @Override + protected void validateForCreate(RangerServiceDef vObj) { + } + + @Override + protected void validateForUpdate(RangerServiceDef vServiceDef, XXServiceDefWithAssignedId xServiceDef) { + } } diff --git a/security-admin/src/main/java/org/apache/ranger/service/RangerServiceResourceService.java b/security-admin/src/main/java/org/apache/ranger/service/RangerServiceResourceService.java index 2d1aa2e63b..8fe023e6c9 100755 --- a/security-admin/src/main/java/org/apache/ranger/service/RangerServiceResourceService.java +++ b/security-admin/src/main/java/org/apache/ranger/service/RangerServiceResourceService.java @@ -19,11 +19,6 @@ package org.apache.ranger.service; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.type.TypeReference; import org.apache.commons.collections.CollectionUtils; @@ -31,9 +26,9 @@ import org.apache.commons.lang.StringUtils; import org.apache.ranger.authorization.utils.JsonUtils; import org.apache.ranger.common.SearchField; -import org.apache.ranger.common.SortField; import org.apache.ranger.common.SearchField.DATA_TYPE; import org.apache.ranger.common.SearchField.SEARCH_TYPE; +import org.apache.ranger.common.SortField; import org.apache.ranger.entity.XXServiceResource; import org.apache.ranger.plugin.model.RangerPolicy; import org.apache.ranger.plugin.model.RangerServiceResource; @@ -43,15 +38,19 @@ import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + @Service public class RangerServiceResourceService extends RangerServiceResourceServiceBase { - private static final Logger LOG = LoggerFactory.getLogger(RangerServiceResourceService.class); - private boolean serviceUpdateNeeded = true; - public static final TypeReference subsumedDataType = new TypeReference>() {}; + public static final TypeReference> subsumedDataType = new TypeReference>() {}; + public static final TypeReference> duplicatedDataType = new TypeReference>() {}; - public static final TypeReference duplicatedDataType = new TypeReference>() {}; + private boolean serviceUpdateNeeded = true; public RangerServiceResourceService() { searchFields.add(new SearchField(SearchFilter.TAG_RESOURCE_ID, "obj.id", DATA_TYPE.INTEGER, SEARCH_TYPE.FULL)); @@ -64,23 +63,8 @@ public RangerServiceResourceService() { sortFields.add(new SortField(SearchFilter.TAG_RESOURCE_ID, "obj.id", true, SortField.SORT_ORDER.ASC)); sortFields.add(new SortField(SearchFilter.TAG_SERVICE_ID, "obj.serviceId")); - sortFields.add(new SortField(SearchFilter.CREATE_TIME, "obj.createTime")); - sortFields.add(new SortField(SearchFilter.UPDATE_TIME, "obj.updateTime")); - } - - @Override - protected void validateForCreate(RangerServiceResource vObj) { - - } - - @Override - protected void validateForUpdate(RangerServiceResource vObj, XXServiceResource entityObj) { - if (StringUtils.equals(entityObj.getGuid(), vObj.getGuid()) && - StringUtils.equals(entityObj.getResourceSignature(), vObj.getResourceSignature())) { - serviceUpdateNeeded = false; - } else { - serviceUpdateNeeded = true; - } + sortFields.add(new SortField(SearchFilter.CREATE_TIME, "obj.createTime")); + sortFields.add(new SortField(SearchFilter.UPDATE_TIME, "obj.updateTime")); } @Override @@ -94,14 +78,22 @@ public RangerServiceResource postUpdate(XXServiceResource resource) { return ret; } + @Override + protected void validateForCreate(RangerServiceResource vObj) { + } + + @Override + protected void validateForUpdate(RangerServiceResource vObj, XXServiceResource entityObj) { + serviceUpdateNeeded = !StringUtils.equals(entityObj.getGuid(), vObj.getGuid()) || !StringUtils.equals(entityObj.getResourceSignature(), vObj.getResourceSignature()); + } + public RangerServiceResource getPopulatedViewObject(XXServiceResource xObj) { return populateViewBean(xObj); } public RangerServiceResource getServiceResourceByGuid(String guid) { - RangerServiceResource ret = null; - - XXServiceResource xxServiceResource = daoMgr.getXXServiceResource().findByGuid(guid); + RangerServiceResource ret = null; + XXServiceResource xxServiceResource = daoMgr.getXXServiceResource().findByGuid(guid); if (xxServiceResource != null) { ret = populateViewBean(xxServiceResource); @@ -111,9 +103,8 @@ public RangerServiceResource getServiceResourceByGuid(String guid) { } public List getByServiceId(Long serviceId) { - List ret = new ArrayList(); - - List xxServiceResources = daoMgr.getXXServiceResource().findByServiceId(serviceId); + List ret = new ArrayList<>(); + List xxServiceResources = daoMgr.getXXServiceResource().findByServiceId(serviceId); if (CollectionUtils.isNotEmpty(xxServiceResources)) { for (XXServiceResource xxServiceResource : xxServiceResources) { @@ -127,9 +118,8 @@ public List getByServiceId(Long serviceId) { } public RangerServiceResource getByServiceAndResourceSignature(Long serviceId, String resourceSignature) { - RangerServiceResource ret = null; - - XXServiceResource xxServiceResource = daoMgr.getXXServiceResource().findByServiceAndResourceSignature(serviceId, resourceSignature); + RangerServiceResource ret = null; + XXServiceResource xxServiceResource = daoMgr.getXXServiceResource().findByServiceAndResourceSignature(serviceId, resourceSignature); if (xxServiceResource != null) { ret = populateViewBean(xxServiceResource); @@ -139,9 +129,8 @@ public RangerServiceResource getByServiceAndResourceSignature(Long serviceId, St } public List getTaggedResourcesInServiceId(Long serviceId) { - List ret = new ArrayList(); - - List xxServiceResources = daoMgr.getXXServiceResource().findByServiceId(serviceId); + List ret = new ArrayList<>(); + List xxServiceResources = daoMgr.getXXServiceResource().findByServiceId(serviceId); if (CollectionUtils.isNotEmpty(xxServiceResources)) { for (XXServiceResource xxServiceResource : xxServiceResources) { @@ -157,12 +146,14 @@ public List getTaggedResourcesInServiceId(Long serviceId) @Override protected XXServiceResource mapViewToEntityBean(RangerServiceResource serviceResource, XXServiceResource xxServiceResource, int operationContext) { XXServiceResource ret = super.mapViewToEntityBean(serviceResource, xxServiceResource, operationContext); + if (MapUtils.isNotEmpty(serviceResource.getResourceElements())) { String serviceResourceElements = JsonUtils.mapToJson(serviceResource.getResourceElements()); + if (StringUtils.isNotEmpty(serviceResourceElements)) { ret.setServiceResourceElements(serviceResourceElements); } else { - LOG.info("Empty string representing serviceResourceElements in [" + ret + "]!!"); + LOG.info("Empty string representing serviceResourceElements in [{}]!!", ret); } } @@ -172,20 +163,23 @@ protected XXServiceResource mapViewToEntityBean(RangerServiceResource serviceRes @Override protected RangerServiceResource mapEntityToViewBean(RangerServiceResource serviceResource, XXServiceResource xxServiceResource) { RangerServiceResource ret = super.mapEntityToViewBean(serviceResource, xxServiceResource); + if (StringUtils.isNotEmpty(xxServiceResource.getServiceResourceElements())) { Map serviceResourceElements = null; + try { - serviceResourceElements = (Map) JsonUtils.jsonToObject(xxServiceResource.getServiceResourceElements(), RangerServiceResourceService.subsumedDataType); + serviceResourceElements = JsonUtils.jsonToObject(xxServiceResource.getServiceResourceElements(), RangerServiceResourceService.subsumedDataType); } catch (JsonProcessingException e) { LOG.error("Error occurred while processing JSON ", e); } + if (MapUtils.isNotEmpty(serviceResourceElements)) { ret.setResourceElements(serviceResourceElements); } else { - LOG.info("Empty serviceResourceElement in [" + ret + "]!!"); + LOG.info("Empty serviceResourceElement in [{}]!!", ret); } } else { - LOG.info("Empty string representing serviceResourceElements in [" + xxServiceResource + "]!!"); + LOG.info("Empty string representing serviceResourceElements in [{}]!!", xxServiceResource); } return ret; diff --git a/security-admin/src/main/java/org/apache/ranger/service/RangerServiceResourceServiceBase.java b/security-admin/src/main/java/org/apache/ranger/service/RangerServiceResourceServiceBase.java index 69b64383c5..1f342a5070 100644 --- a/security-admin/src/main/java/org/apache/ranger/service/RangerServiceResourceServiceBase.java +++ b/security-admin/src/main/java/org/apache/ranger/service/RangerServiceResourceServiceBase.java @@ -19,11 +19,6 @@ package org.apache.ranger.service; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - import org.apache.commons.lang.StringUtils; import org.apache.ranger.common.GUIDUtil; import org.apache.ranger.common.MessageEnums; @@ -38,58 +33,83 @@ import org.apache.ranger.plugin.util.SearchFilter; import org.springframework.beans.factory.annotation.Autowired; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + public abstract class RangerServiceResourceServiceBase extends RangerBaseModelService { + @Autowired + GUIDUtil guidUtil; + + public PList searchServiceResources(SearchFilter searchFilter) { + PList retList = new PList<>(); + List resourceList = new ArrayList<>(); + List xResourceList = searchRangerObjects(searchFilter, searchFields, sortFields, retList); + + for (T xResource : xResourceList) { + V taggedRes = populateViewBean(xResource); + + resourceList.add(taggedRes); + } - @Autowired - GUIDUtil guidUtil; + retList.setList(resourceList); + retList.setResultSize(resourceList.size()); + retList.setPageSize(searchFilter.getMaxRows()); + retList.setStartIndex(searchFilter.getStartIndex()); + retList.setSortType(searchFilter.getSortType()); + retList.setSortBy(searchFilter.getSortBy()); - @Override - protected T mapViewToEntityBean(V vObj, T xObj, int operationContext) { - String guid = (StringUtils.isEmpty(vObj.getGuid())) ? guidUtil.genGUID() : vObj.getGuid(); + return retList; + } - xObj.setGuid(guid); - xObj.setVersion(vObj.getVersion()); - xObj.setIsEnabled(vObj.getIsEnabled()); - xObj.setResourceSignature(vObj.getResourceSignature()); + @Override + protected T mapViewToEntityBean(V vObj, T xObj, int operationContext) { + String guid = (StringUtils.isEmpty(vObj.getGuid())) ? guidUtil.genGUID() : vObj.getGuid(); - XXService xService = daoMgr.getXXService().findByName(vObj.getServiceName()); - if (xService == null) { - throw restErrorUtil.createRESTException("Error Populating XXServiceResource. No Service found with name: " + vObj.getServiceName(), MessageEnums.INVALID_INPUT_DATA); - } + xObj.setGuid(guid); + xObj.setVersion(vObj.getVersion()); + xObj.setIsEnabled(vObj.getIsEnabled()); + xObj.setResourceSignature(vObj.getResourceSignature()); - xObj.setServiceId(xService.getId()); + XXService xService = daoMgr.getXXService().findByName(vObj.getServiceName()); - return xObj; - } + if (xService == null) { + throw restErrorUtil.createRESTException("Error Populating XXServiceResource. No Service found with name: " + vObj.getServiceName(), MessageEnums.INVALID_INPUT_DATA); + } - @Override - protected V mapEntityToViewBean(V vObj, T xObj) { - vObj.setGuid(xObj.getGuid()); - vObj.setVersion(xObj.getVersion()); - vObj.setIsEnabled(xObj.getIsEnabled()); - vObj.setResourceSignature(xObj.getResourceSignature()); + xObj.setServiceId(xService.getId()); - XXService xService = daoMgr.getXXService().getById(xObj.getServiceId()); + return xObj; + } - vObj.setServiceName(xService.getName()); + @Override + protected V mapEntityToViewBean(V vObj, T xObj) { + vObj.setGuid(xObj.getGuid()); + vObj.setVersion(xObj.getVersion()); + vObj.setIsEnabled(xObj.getIsEnabled()); + vObj.setResourceSignature(xObj.getResourceSignature()); - Map resourceElements = getServiceResourceElements(xObj); + XXService xService = daoMgr.getXXService().getById(xObj.getServiceId()); - vObj.setResourceElements(resourceElements); + vObj.setServiceName(xService.getName()); - return vObj; - } + Map resourceElements = getServiceResourceElements(xObj); - Map getServiceResourceElements(T xObj) { - List resElementList = daoMgr.getXXServiceResourceElement().findByResourceId(xObj.getId()); - Map resourceElements = new HashMap(); + vObj.setResourceElements(resourceElements); - for (XXServiceResourceElement resElement : resElementList) { - List resValueMapList = daoMgr.getXXServiceResourceElementValue().findValuesByResElementId(resElement.getId()); + return vObj; + } - XXResourceDef xResDef = daoMgr.getXXResourceDef().getById(resElement.getResDefId()); + Map getServiceResourceElements(T xObj) { + List resElementList = daoMgr.getXXServiceResourceElement().findByResourceId(xObj.getId()); + Map resourceElements = new HashMap<>(); + + for (XXServiceResourceElement resElement : resElementList) { + List resValueMapList = daoMgr.getXXServiceResourceElementValue().findValuesByResElementId(resElement.getId()); + XXResourceDef xResDef = daoMgr.getXXResourceDef().getById(resElement.getResDefId()); + RangerPolicyResource policyRes = new RangerPolicyResource(); - RangerPolicyResource policyRes = new RangerPolicyResource(); policyRes.setIsExcludes(resElement.getIsExcludes()); policyRes.setIsRecursive(resElement.getIsRecursive()); policyRes.setValues(resValueMapList); @@ -98,25 +118,4 @@ Map getServiceResourceElements(T xObj) { } return resourceElements; } - - public PList searchServiceResources(SearchFilter searchFilter) { - PList retList = new PList(); - List resourceList = new ArrayList(); - - List xResourceList = searchRangerObjects(searchFilter, searchFields, sortFields, retList); - - for (T xResource : xResourceList) { - V taggedRes = populateViewBean(xResource); - resourceList.add(taggedRes); - } - retList.setList(resourceList); - retList.setResultSize(resourceList.size()); - retList.setPageSize(searchFilter.getMaxRows()); - retList.setStartIndex(searchFilter.getStartIndex()); - retList.setSortType(searchFilter.getSortType()); - retList.setSortBy(searchFilter.getSortBy()); - - return retList; - } - } diff --git a/security-admin/src/main/java/org/apache/ranger/service/RangerServiceResourceWithTagsService.java b/security-admin/src/main/java/org/apache/ranger/service/RangerServiceResourceWithTagsService.java index 6660c9c700..44be8dd41a 100755 --- a/security-admin/src/main/java/org/apache/ranger/service/RangerServiceResourceWithTagsService.java +++ b/security-admin/src/main/java/org/apache/ranger/service/RangerServiceResourceWithTagsService.java @@ -19,18 +19,14 @@ package org.apache.ranger.service; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - import com.fasterxml.jackson.core.JsonProcessingException; import org.apache.commons.collections.MapUtils; import org.apache.commons.lang.StringUtils; import org.apache.ranger.authorization.utils.JsonUtils; import org.apache.ranger.common.SearchField; -import org.apache.ranger.common.SortField; import org.apache.ranger.common.SearchField.DATA_TYPE; import org.apache.ranger.common.SearchField.SEARCH_TYPE; +import org.apache.ranger.common.SortField; import org.apache.ranger.entity.XXServiceResource; import org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyResource; import org.apache.ranger.plugin.model.RangerServiceResourceWithTags; @@ -40,83 +36,86 @@ import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + @Service public class RangerServiceResourceWithTagsService extends RangerServiceResourceWithTagsServiceBase { - - private static final Logger LOG = LoggerFactory.getLogger(RangerServiceResourceWithTagsService.class); - - public RangerServiceResourceWithTagsService() { - searchFields.add(new SearchField(SearchFilter.TAG_RESOURCE_ID, "obj.id", DATA_TYPE.INTEGER, SEARCH_TYPE.FULL)); - searchFields.add(new SearchField(SearchFilter.TAG_SERVICE_ID, "obj.serviceId", DATA_TYPE.INTEGER, SEARCH_TYPE.FULL)); - searchFields.add(new SearchField(SearchFilter.TAG_SERVICE_NAME, "service.name", DATA_TYPE.STRING, SEARCH_TYPE.FULL, "XXService service", "obj.serviceId = service.id")); - searchFields.add(new SearchField(SearchFilter.TAG_SERVICE_NAME_PARTIAL, "service.name", DATA_TYPE.STRING, SEARCH_TYPE.PARTIAL, "XXService service", "obj.serviceId = service.id")); - searchFields.add(new SearchField(SearchFilter.TAG_RESOURCE_GUID, "obj.guid", DATA_TYPE.STRING, SEARCH_TYPE.FULL)); - searchFields.add(new SearchField(SearchFilter.TAG_RESOURCE_SIGNATURE, "obj.resourceSignature", DATA_TYPE.STRING, SEARCH_TYPE.FULL)); - searchFields.add(new SearchField(SearchFilter.TAG_RESOURCE_IDS, "obj.id", DATA_TYPE.INT_LIST, SEARCH_TYPE.FULL)); - searchFields.add(new SearchField(SearchFilter.TAG_RESOURCE_ELEMENTS, "obj.serviceResourceElements", DATA_TYPE.STRING, SEARCH_TYPE.PARTIAL)); - searchFields.add(new SearchField(SearchFilter.TAG_NAMES, "tagDef.name", DATA_TYPE.STR_LIST, SEARCH_TYPE.FULL, "XXTagResourceMap map, XXTag tag, XXTagDef tagDef", "obj.id = map.resourceId and map.tagId = tag.id and tag.type = tagDef.id")); + private static final Logger LOG = LoggerFactory.getLogger(RangerServiceResourceWithTagsService.class); + + public RangerServiceResourceWithTagsService() { + searchFields.add(new SearchField(SearchFilter.TAG_RESOURCE_ID, "obj.id", DATA_TYPE.INTEGER, SEARCH_TYPE.FULL)); + searchFields.add(new SearchField(SearchFilter.TAG_SERVICE_ID, "obj.serviceId", DATA_TYPE.INTEGER, SEARCH_TYPE.FULL)); + searchFields.add(new SearchField(SearchFilter.TAG_SERVICE_NAME, "service.name", DATA_TYPE.STRING, SEARCH_TYPE.FULL, "XXService service", "obj.serviceId = service.id")); + searchFields.add(new SearchField(SearchFilter.TAG_SERVICE_NAME_PARTIAL, "service.name", DATA_TYPE.STRING, SEARCH_TYPE.PARTIAL, "XXService service", "obj.serviceId = service.id")); + searchFields.add(new SearchField(SearchFilter.TAG_RESOURCE_GUID, "obj.guid", DATA_TYPE.STRING, SEARCH_TYPE.FULL)); + searchFields.add(new SearchField(SearchFilter.TAG_RESOURCE_SIGNATURE, "obj.resourceSignature", DATA_TYPE.STRING, SEARCH_TYPE.FULL)); + searchFields.add(new SearchField(SearchFilter.TAG_RESOURCE_IDS, "obj.id", DATA_TYPE.INT_LIST, SEARCH_TYPE.FULL)); + searchFields.add(new SearchField(SearchFilter.TAG_RESOURCE_ELEMENTS, "obj.serviceResourceElements", DATA_TYPE.STRING, SEARCH_TYPE.PARTIAL)); + searchFields.add(new SearchField(SearchFilter.TAG_NAMES, "tagDef.name", DATA_TYPE.STR_LIST, SEARCH_TYPE.FULL, "XXTagResourceMap map, XXTag tag, XXTagDef tagDef", "obj.id = map.resourceId and map.tagId = tag.id and tag.type = tagDef.id")); sortFields.add(new SortField(SearchFilter.TAG_RESOURCE_ID, "obj.id", true, SortField.SORT_ORDER.ASC)); - sortFields.add(new SortField(SearchFilter.TAG_SERVICE_ID, "obj.serviceId")); - sortFields.add(new SortField(SearchFilter.CREATE_TIME, "obj.createTime")); - sortFields.add(new SortField(SearchFilter.UPDATE_TIME, "obj.updateTime")); + sortFields.add(new SortField(SearchFilter.TAG_SERVICE_ID, "obj.serviceId")); + sortFields.add(new SortField(SearchFilter.CREATE_TIME, "obj.createTime")); + sortFields.add(new SortField(SearchFilter.UPDATE_TIME, "obj.updateTime")); } - @Override - protected XXServiceResource mapViewToEntityBean(RangerServiceResourceWithTags viewBean, XXServiceResource t, int OPERATION_CONTEXT) { - return null; - } + public RangerServiceResourceWithTags getPopulatedViewObject(XXServiceResource xObj) { + return this.populateViewBean(xObj); + } - @Override - protected void validateForCreate(RangerServiceResourceWithTags vObj) { - } + public RangerServiceResourceWithTagsList searchServiceResourcesWithTags(SearchFilter filter) { + LOG.debug("==> searchServiceResourcesWithTags({})", filter); - @Override - protected void validateForUpdate(RangerServiceResourceWithTags vObj, XXServiceResource entityObj) { - } + RangerServiceResourceWithTagsList ret = new RangerServiceResourceWithTagsList(); + List xObjList = super.searchResources(filter, searchFields, sortFields, ret); + List resourceList = new ArrayList<>(); - public RangerServiceResourceWithTags getPopulatedViewObject(XXServiceResource xObj) { - return this.populateViewBean(xObj); - } + if (xObjList != null) { + for (XXServiceResource resource : xObjList) { + resourceList.add(getPopulatedViewObject(resource)); + } + } - public RangerServiceResourceWithTagsList searchServiceResourcesWithTags(SearchFilter filter) { - LOG.debug("==> searchServiceResourcesWithTags({})", filter); + ret.setResourceList(resourceList); - RangerServiceResourceWithTagsList ret = new RangerServiceResourceWithTagsList(); - List xObjList = super.searchResources(filter, searchFields, sortFields, ret); - List resourceList = new ArrayList<>(); + LOG.debug("<== searchServiceResourcesWithTags({}): ret={}", filter, ret); - if (xObjList != null) { - for (XXServiceResource resource:xObjList) { - resourceList.add(getPopulatedViewObject(resource)); - } - } + return ret; + } - ret.setResourceList(resourceList); + @Override + protected XXServiceResource mapViewToEntityBean(RangerServiceResourceWithTags viewBean, XXServiceResource t, int operationContext) { + return null; + } - LOG.debug("<== searchServiceResourcesWithTags({}): ret={}", filter, ret); + @Override + protected void validateForCreate(RangerServiceResourceWithTags vObj) { + } - return ret; - } + @Override + protected void validateForUpdate(RangerServiceResourceWithTags vObj, XXServiceResource entityObj) { + } - @Override + @Override protected RangerServiceResourceWithTags mapEntityToViewBean(RangerServiceResourceWithTags serviceResourceWithTags, XXServiceResource xxServiceResource) { - RangerServiceResourceWithTags ret = super.mapEntityToViewBean(serviceResourceWithTags, xxServiceResource); + RangerServiceResourceWithTags ret = super.mapEntityToViewBean(serviceResourceWithTags, xxServiceResource); if (StringUtils.isNotEmpty(xxServiceResource.getServiceResourceElements())) { - try { - Map serviceResourceElements = (Map) JsonUtils.jsonToObject(xxServiceResource.getServiceResourceElements(), RangerServiceResourceService.subsumedDataType); - - if (MapUtils.isNotEmpty(serviceResourceElements)) { - ret.setResourceElements(serviceResourceElements); - } else { - LOG.info("Empty serviceResourceElement in [" + ret + "]!!"); - } - } catch (JsonProcessingException e) { - LOG.error("Error occurred while processing json", e); - } + try { + Map serviceResourceElements = (Map) JsonUtils.jsonToObject(xxServiceResource.getServiceResourceElements(), RangerServiceResourceService.subsumedDataType); + + if (MapUtils.isNotEmpty(serviceResourceElements)) { + ret.setResourceElements(serviceResourceElements); + } else { + LOG.info("Empty serviceResourceElement in [{}]!!", ret); + } + } catch (JsonProcessingException e) { + LOG.error("Error occurred while processing json", e); + } } else { - LOG.info("Empty string representing serviceResourceElements in [" + xxServiceResource + "]!!"); + LOG.info("Empty string representing serviceResourceElements in [{}]!!", xxServiceResource); } return ret; diff --git a/security-admin/src/main/java/org/apache/ranger/service/RangerServiceResourceWithTagsServiceBase.java b/security-admin/src/main/java/org/apache/ranger/service/RangerServiceResourceWithTagsServiceBase.java index 57cd20ab36..6c52e05fe8 100755 --- a/security-admin/src/main/java/org/apache/ranger/service/RangerServiceResourceWithTagsServiceBase.java +++ b/security-admin/src/main/java/org/apache/ranger/service/RangerServiceResourceWithTagsServiceBase.java @@ -19,9 +19,6 @@ package org.apache.ranger.service; -import java.util.ArrayList; -import java.util.List; - import org.apache.ranger.authorization.utils.JsonUtils; import org.apache.ranger.entity.XXService; import org.apache.ranger.entity.XXServiceResource; @@ -29,39 +26,41 @@ import org.apache.ranger.plugin.store.PList; import org.apache.ranger.plugin.util.SearchFilter; -public abstract class RangerServiceResourceWithTagsServiceBase extends RangerBaseModelService { +import java.util.ArrayList; +import java.util.List; - @Override - protected V mapEntityToViewBean(V vObj, T xObj) { - XXService xService = daoMgr.getXXService().getById(xObj.getServiceId()); +public abstract class RangerServiceResourceWithTagsServiceBase extends RangerBaseModelService { + public PList searchServiceResources(SearchFilter searchFilter) { + PList retList = new PList(); + List resourceList = new ArrayList(); + List xResourceList = searchRangerObjects(searchFilter, searchFields, sortFields, retList); - vObj.setGuid(xObj.getGuid()); - vObj.setVersion(xObj.getVersion()); - vObj.setIsEnabled(xObj.getIsEnabled()); - vObj.setServiceName(xService.getName()); - vObj.setAssociatedTags(JsonUtils.jsonToRangerTagList(xObj.getTags())); + for (T xResource : xResourceList) { + V taggedRes = populateViewBean(xResource); - return vObj; - } + resourceList.add(taggedRes); + } - public PList searchServiceResources(SearchFilter searchFilter) { - PList retList = new PList(); - List resourceList = new ArrayList(); - List xResourceList = searchRangerObjects(searchFilter, searchFields, sortFields, retList); + retList.setList(resourceList); + retList.setResultSize(resourceList.size()); + retList.setPageSize(searchFilter.getMaxRows()); + retList.setStartIndex(searchFilter.getStartIndex()); + retList.setSortType(searchFilter.getSortType()); + retList.setSortBy(searchFilter.getSortBy()); - for (T xResource : xResourceList) { - V taggedRes = populateViewBean(xResource); + return retList; + } - resourceList.add(taggedRes); - } + @Override + protected V mapEntityToViewBean(V vObj, T xObj) { + XXService xService = daoMgr.getXXService().getById(xObj.getServiceId()); - retList.setList(resourceList); - retList.setResultSize(resourceList.size()); - retList.setPageSize(searchFilter.getMaxRows()); - retList.setStartIndex(searchFilter.getStartIndex()); - retList.setSortType(searchFilter.getSortType()); - retList.setSortBy(searchFilter.getSortBy()); + vObj.setGuid(xObj.getGuid()); + vObj.setVersion(xObj.getVersion()); + vObj.setIsEnabled(xObj.getIsEnabled()); + vObj.setServiceName(xService.getName()); + vObj.setAssociatedTags(JsonUtils.jsonToRangerTagList(xObj.getTags())); - return retList; - } + return vObj; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/service/RangerServiceService.java b/security-admin/src/main/java/org/apache/ranger/service/RangerServiceService.java index 9285ae756a..eedbb4f80e 100644 --- a/security-admin/src/main/java/org/apache/ranger/service/RangerServiceService.java +++ b/security-admin/src/main/java/org/apache/ranger/service/RangerServiceService.java @@ -17,12 +17,6 @@ package org.apache.ranger.service; -import java.util.ArrayList; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - import org.apache.commons.lang.StringUtils; import org.apache.hadoop.thirdparty.com.google.common.base.Joiner; import org.apache.ranger.biz.GdsDBStore; @@ -39,164 +33,157 @@ import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Service; +import java.util.ArrayList; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; @Service @Scope("singleton") public class RangerServiceService extends RangerServiceServiceBase { - private static final Logger LOG = LoggerFactory.getLogger(RangerServiceService.class.getName()); - - @Autowired - GdsDBStore gdsStore; - - String actionCreate; - String actionUpdate; - String actionDelete; - - public RangerServiceService() { - super(); - - actionCreate = "create"; - actionUpdate = "update"; - actionDelete = "delete"; - } - - @Override - protected XXService mapViewToEntityBean(RangerService vObj, XXService xObj, int OPERATION_CONTEXT) { - return super.mapViewToEntityBean(vObj, xObj, OPERATION_CONTEXT); - } - - @Override - protected RangerService mapEntityToViewBean(RangerService vObj, XXService xObj) { - return super.mapEntityToViewBean(vObj, xObj); - } - - @Override - protected void validateForCreate(RangerService vObj) { - // TODO Auto-generated method stub - - } - - @Override - protected void validateForUpdate(RangerService vService, XXService xService) { - - } - - @Override - protected RangerService populateViewBean(XXService xService) { - RangerService vService = super.populateViewBean(xService); - - HashMap configs = new HashMap(); - List svcConfigMapList = daoMgr.getXXServiceConfigMap() - .findByServiceId(xService.getId()); - for(XXServiceConfigMap svcConfMap : svcConfigMapList) { - String configValue = svcConfMap.getConfigvalue(); - - if(StringUtils.equalsIgnoreCase(svcConfMap.getConfigkey(), ServiceDBStore.CONFIG_KEY_PASSWORD)) { - configValue = ServiceDBStore.HIDDEN_PASSWORD_STR; - } - configs.put(svcConfMap.getConfigkey(), configValue); - } - vService.setConfigs(configs); - return vService; - } - - public RangerService getPopulatedViewObject(XXService xService) { - return this.populateViewBean(xService); - } - - public List getAllServices() { - List xxServiceList = daoMgr.getXXService().getAll(); - List serviceList = new ArrayList(); - - for(XXService xxService : xxServiceList) { - RangerService service = populateViewBean(xxService); - serviceList.add(service); - } - return serviceList; - } - - public Map getConfigsWithDecryptedPassword(RangerService service) throws Exception { - Map configs = service.getConfigs(); - - String pwd = configs.get(ServiceDBStore.CONFIG_KEY_PASSWORD); - if(!stringUtil.isEmpty(pwd) && ServiceDBStore.HIDDEN_PASSWORD_STR.equalsIgnoreCase(pwd)) { - XXServiceConfigMap pwdConfig = daoMgr.getXXServiceConfigMap().findByServiceAndConfigKey(service.getId(), - ServiceDBStore.CONFIG_KEY_PASSWORD); - - if (pwdConfig != null) { - String encryptedPwd = pwdConfig.getConfigvalue(); - if (encryptedPwd.contains(",")) { - PasswordUtils util = PasswordUtils.build(encryptedPwd); - String freeTextPasswordMetaData = Joiner.on(",").skipNulls().join(util.getCryptAlgo(), - new String(util.getEncryptKey()), new String(util.getSalt()), util.getIterationCount(), - PasswordUtils.needsIv(util.getCryptAlgo()) ? util.getIvAsString() : null); - String decryptedPwd = PasswordUtils.decryptPassword(encryptedPwd); - if (StringUtils - .equalsIgnoreCase( - freeTextPasswordMetaData + "," - + PasswordUtils - .encryptPassword(freeTextPasswordMetaData + "," + decryptedPwd), - encryptedPwd)) { - configs.put(ServiceDBStore.CONFIG_KEY_PASSWORD, encryptedPwd); // XXX: method name is - // getConfigsWithDecryptedPassword, - // then why do we store the - // encryptedPwd? - } - } else { - String decryptedPwd = PasswordUtils.decryptPassword(encryptedPwd); - if (StringUtils.equalsIgnoreCase(PasswordUtils.encryptPassword(decryptedPwd), encryptedPwd)) { - configs.put(ServiceDBStore.CONFIG_KEY_PASSWORD, encryptedPwd); // XXX: method name is - // getConfigsWithDecryptedPassword, - // then why do we store the - // encryptedPwd? - } - } - } - } - return configs; - } - - @Override - public RangerService postCreate(XXService xObj) { - XXServiceVersionInfo serviceVersionInfo = new XXServiceVersionInfo(); - - serviceVersionInfo.setServiceId(xObj.getId()); - serviceVersionInfo.setPolicyVersion(1L); - serviceVersionInfo.setTagVersion(1L); - serviceVersionInfo.setRoleVersion(1L); - serviceVersionInfo.setGdsVersion(1L); - Date now = new Date(); - serviceVersionInfo.setPolicyUpdateTime(now); - serviceVersionInfo.setTagUpdateTime(now); - serviceVersionInfo.setRoleUpdateTime(now); - serviceVersionInfo.setGdsUpdateTime(now); - - XXServiceVersionInfoDao serviceVersionInfoDao = daoMgr.getXXServiceVersionInfo(); - - XXServiceVersionInfo createdServiceVersionInfo = serviceVersionInfoDao.create(serviceVersionInfo); - - return createdServiceVersionInfo != null ? super.postCreate(xObj) : null; - } - - @Override - protected XXService preDelete(Long id) { - XXService ret = super.preDelete(id); - - if (ret != null) { - try { - gdsStore.deleteAllGdsObjectsForService(id); - } catch (Exception excp) { - LOG.error("Error deleting GDS objects for service(id={})", id, excp); - } - - XXServiceVersionInfoDao serviceVersionInfoDao = daoMgr.getXXServiceVersionInfo(); - - XXServiceVersionInfo serviceVersionInfo = serviceVersionInfoDao.findByServiceId(id); - - if (serviceVersionInfo != null) { - serviceVersionInfoDao.remove(serviceVersionInfo.getId()); - } - } - return ret; - } + private static final Logger LOG = LoggerFactory.getLogger(RangerServiceService.class.getName()); + + @Autowired + GdsDBStore gdsStore; + + String actionCreate; + String actionUpdate; + String actionDelete; + + public RangerServiceService() { + super(); + + actionCreate = "create"; + actionUpdate = "update"; + actionDelete = "delete"; + } + + public RangerService getPopulatedViewObject(XXService xService) { + return this.populateViewBean(xService); + } + + public List getAllServices() { + List xxServiceList = daoMgr.getXXService().getAll(); + List serviceList = new ArrayList<>(); + + for (XXService xxService : xxServiceList) { + RangerService service = populateViewBean(xxService); + serviceList.add(service); + } + return serviceList; + } + + public Map getConfigsWithDecryptedPassword(RangerService service) throws Exception { + Map configs = service.getConfigs(); + + String pwd = configs.get(ServiceDBStore.CONFIG_KEY_PASSWORD); + if (!stringUtil.isEmpty(pwd) && ServiceDBStore.HIDDEN_PASSWORD_STR.equalsIgnoreCase(pwd)) { + XXServiceConfigMap pwdConfig = daoMgr.getXXServiceConfigMap().findByServiceAndConfigKey(service.getId(), ServiceDBStore.CONFIG_KEY_PASSWORD); + + if (pwdConfig != null) { + String encryptedPwd = pwdConfig.getConfigvalue(); + if (encryptedPwd.contains(",")) { + PasswordUtils util = PasswordUtils.build(encryptedPwd); + String freeTextPasswordMetaData = Joiner.on(",").skipNulls().join(util.getCryptAlgo(), new String(util.getEncryptKey()), new String(util.getSalt()), util.getIterationCount(), PasswordUtils.needsIv(util.getCryptAlgo()) ? util.getIvAsString() : null); + String decryptedPwd = PasswordUtils.decryptPassword(encryptedPwd); + if (StringUtils.equalsIgnoreCase(freeTextPasswordMetaData + "," + PasswordUtils.encryptPassword(freeTextPasswordMetaData + "," + decryptedPwd), encryptedPwd)) { + configs.put(ServiceDBStore.CONFIG_KEY_PASSWORD, encryptedPwd); + // XXX: method name is getConfigsWithDecryptedPassword, then why do we store the encryptedPwd? + } + } else { + String decryptedPwd = PasswordUtils.decryptPassword(encryptedPwd); + if (StringUtils.equalsIgnoreCase(PasswordUtils.encryptPassword(decryptedPwd), encryptedPwd)) { + configs.put(ServiceDBStore.CONFIG_KEY_PASSWORD, encryptedPwd); + // XXX: method name is getConfigsWithDecryptedPassword, then why do we store the encryptedPwd? + } + } + } + } + return configs; + } + + @Override + public RangerService postCreate(XXService xObj) { + XXServiceVersionInfo serviceVersionInfo = new XXServiceVersionInfo(); + + serviceVersionInfo.setServiceId(xObj.getId()); + serviceVersionInfo.setPolicyVersion(1L); + serviceVersionInfo.setTagVersion(1L); + serviceVersionInfo.setRoleVersion(1L); + serviceVersionInfo.setGdsVersion(1L); + + Date now = new Date(); + + serviceVersionInfo.setPolicyUpdateTime(now); + serviceVersionInfo.setTagUpdateTime(now); + serviceVersionInfo.setRoleUpdateTime(now); + serviceVersionInfo.setGdsUpdateTime(now); + + XXServiceVersionInfoDao serviceVersionInfoDao = daoMgr.getXXServiceVersionInfo(); + XXServiceVersionInfo createdServiceVersionInfo = serviceVersionInfoDao.create(serviceVersionInfo); + + return createdServiceVersionInfo != null ? super.postCreate(xObj) : null; + } + + @Override + protected RangerService populateViewBean(XXService xService) { + RangerService vService = super.populateViewBean(xService); + HashMap configs = new HashMap<>(); + List svcConfigMapList = daoMgr.getXXServiceConfigMap().findByServiceId(xService.getId()); + + for (XXServiceConfigMap svcConfMap : svcConfigMapList) { + String configValue = svcConfMap.getConfigvalue(); + + if (StringUtils.equalsIgnoreCase(svcConfMap.getConfigkey(), ServiceDBStore.CONFIG_KEY_PASSWORD)) { + configValue = ServiceDBStore.HIDDEN_PASSWORD_STR; + } + + configs.put(svcConfMap.getConfigkey(), configValue); + } + + vService.setConfigs(configs); + + return vService; + } + + @Override + protected void validateForCreate(RangerService vObj) { + } + + @Override + protected void validateForUpdate(RangerService vService, XXService xService) { + } + + @Override + protected XXService preDelete(Long id) { + XXService ret = super.preDelete(id); + + if (ret != null) { + try { + gdsStore.deleteAllGdsObjectsForService(id); + } catch (Exception excp) { + LOG.error("Error deleting GDS objects for service(id={})", id, excp); + } + + XXServiceVersionInfoDao serviceVersionInfoDao = daoMgr.getXXServiceVersionInfo(); + XXServiceVersionInfo serviceVersionInfo = serviceVersionInfoDao.findByServiceId(id); + + if (serviceVersionInfo != null) { + serviceVersionInfoDao.remove(serviceVersionInfo.getId()); + } + } + + return ret; + } + + @Override + protected XXService mapViewToEntityBean(RangerService vObj, XXService xObj, int operationContext) { + return super.mapViewToEntityBean(vObj, xObj, operationContext); + } + + @Override + protected RangerService mapEntityToViewBean(RangerService vObj, XXService xObj) { + return super.mapEntityToViewBean(vObj, xObj); + } } diff --git a/security-admin/src/main/java/org/apache/ranger/service/RangerServiceServiceBase.java b/security-admin/src/main/java/org/apache/ranger/service/RangerServiceServiceBase.java index b09c726977..98857638e8 100755 --- a/security-admin/src/main/java/org/apache/ranger/service/RangerServiceServiceBase.java +++ b/security-admin/src/main/java/org/apache/ranger/service/RangerServiceServiceBase.java @@ -17,13 +17,14 @@ package org.apache.ranger.service; -import java.util.ArrayList; -import java.util.List; - import org.apache.commons.lang.StringUtils; -import org.apache.ranger.common.*; +import org.apache.ranger.common.AppConstants; +import org.apache.ranger.common.GUIDUtil; +import org.apache.ranger.common.MessageEnums; +import org.apache.ranger.common.SearchField; import org.apache.ranger.common.SearchField.DATA_TYPE; import org.apache.ranger.common.SearchField.SEARCH_TYPE; +import org.apache.ranger.common.SortField; import org.apache.ranger.common.SortField.SORT_ORDER; import org.apache.ranger.common.view.VTrxLogAttr; import org.apache.ranger.entity.XXService; @@ -35,146 +36,150 @@ import org.apache.ranger.view.RangerServiceList; import org.springframework.beans.factory.annotation.Autowired; +import java.util.ArrayList; +import java.util.List; + public abstract class RangerServiceServiceBase extends RangerAuditedModelService { - - @Autowired - GUIDUtil guidUtil; - - public RangerServiceServiceBase() { - super(AppConstants.CLASS_TYPE_XA_SERVICE, AppConstants.CLASS_TYPE_XA_SERVICE_DEF); - - trxLogAttrs.put("name", new VTrxLogAttr("name", "Service Name", false, true)); - trxLogAttrs.put("displayName", new VTrxLogAttr("displayName", "Service Display Name")); - trxLogAttrs.put("description", new VTrxLogAttr("description", "Service Description")); - trxLogAttrs.put("isEnabled", new VTrxLogAttr("isEnabled", "Service Status")); - trxLogAttrs.put("configs", new VTrxLogAttr("configs", "Connection Configurations")); - trxLogAttrs.put("tagService", new VTrxLogAttr("tagService", "Tag Service Name")); - - searchFields.add(new SearchField(SearchFilter.SERVICE_TYPE, "xSvcDef.name", DATA_TYPE.STRING, - SEARCH_TYPE.FULL, "XXServiceDef xSvcDef", "obj.type = xSvcDef.id")); - searchFields.add(new SearchField(SearchFilter.SERVICE_TYPE_ID, "obj.type", DATA_TYPE.INTEGER, SEARCH_TYPE.FULL)); - searchFields.add(new SearchField(SearchFilter.SERVICE_NAME, "obj.name", DATA_TYPE.STRING, SEARCH_TYPE.FULL)); - searchFields.add(new SearchField(SearchFilter.SERVICE_DISPLAY_NAME, "obj.displayName", DATA_TYPE.STRING, SEARCH_TYPE.FULL)); - searchFields.add(new SearchField(SearchFilter.SERVICE_NAME_PARTIAL, "obj.name", DATA_TYPE.STRING, SEARCH_TYPE.PARTIAL)); - searchFields.add(new SearchField(SearchFilter.SERVICE_DISPLAY_NAME_PARTIAL, "obj.displayName", DATA_TYPE.STRING, SEARCH_TYPE.PARTIAL)); - searchFields.add(new SearchField(SearchFilter.SERVICE_ID, "obj.id", DATA_TYPE.INTEGER, SEARCH_TYPE.FULL)); - searchFields.add(new SearchField(SearchFilter.IS_ENABLED, "obj.isEnabled", DATA_TYPE.BOOLEAN, SEARCH_TYPE.FULL)); - searchFields.add(new SearchField(SearchFilter.TAG_SERVICE_ID, "obj.tagService", DATA_TYPE.INTEGER, SEARCH_TYPE.FULL)); - searchFields.add(new SearchField(SearchFilter.TAG_SERVICE_NAME, "xTagSvc.name", DATA_TYPE.STRING, - SEARCH_TYPE.FULL, "XXServiceBase xTagSvc", "obj.tagService = xTagSvc.id")); - - sortFields.add(new SortField(SearchFilter.CREATE_TIME, "obj.createTime")); - sortFields.add(new SortField(SearchFilter.UPDATE_TIME, "obj.updateTime")); - sortFields.add(new SortField(SearchFilter.SERVICE_ID, "obj.id", true, SORT_ORDER.ASC)); - sortFields.add(new SortField(SearchFilter.SERVICE_NAME, "obj.name")); - sortFields.add(new SortField(SearchFilter.SERVICE_DISPLAY_NAME, "obj.displayName")); - } - - @Override - protected T mapViewToEntityBean(V vObj, T xObj, int OPERATION_CONTEXT) { - String guid = (StringUtils.isEmpty(vObj.getGuid())) ? guidUtil.genGUID() : vObj.getGuid(); - - xObj.setGuid(guid); - - XXServiceDef xServiceDef = daoMgr.getXXServiceDef().findByName(vObj.getType()); - - if(xServiceDef == null) { - throw restErrorUtil.createRESTException( - "No ServiceDefinition found with name :" + vObj.getType(), - MessageEnums.INVALID_INPUT_DATA); - } - - Long tagServiceId = null; - String tagServiceName = vObj.getTagService(); - if(! StringUtils.isEmpty(tagServiceName)) { - XXService xTagService = daoMgr.getXXService().findByName(tagServiceName); - - if(xTagService == null) { - throw restErrorUtil.createRESTException( - "No Service found with name :" + tagServiceName, - MessageEnums.INVALID_INPUT_DATA); - } - - tagServiceId = xTagService.getId(); - } - - xObj.setType(xServiceDef.getId()); - xObj.setName(vObj.getName()); - xObj.setDisplayName(vObj.getDisplayName()); - xObj.setTagService(tagServiceId); - if (OPERATION_CONTEXT == OPERATION_CREATE_CONTEXT) { - xObj.setTagVersion(vObj.getTagVersion()); - } - xObj.setDescription(vObj.getDescription()); - xObj.setIsEnabled(vObj.getIsEnabled()); - return xObj; - } - - @Override - protected V mapEntityToViewBean(V vObj, T xObj) { - XXServiceDef xServiceDef = daoMgr.getXXServiceDef().getById(xObj.getType()); - XXService xTagService = xObj.getTagService() != null ? daoMgr.getXXService().getById(xObj.getTagService()) : null; - vObj.setType(xServiceDef.getName()); - vObj.setGuid(xObj.getGuid()); - vObj.setVersion(xObj.getVersion()); - vObj.setName(xObj.getName()); - vObj.setDisplayName(xObj.getDisplayName()); - vObj.setDescription(xObj.getDescription()); - vObj.setTagService(xTagService != null ? xTagService.getName() : null); - XXServiceVersionInfo versionInfoObj = daoMgr.getXXServiceVersionInfo().findByServiceId(xObj.getId()); - if (versionInfoObj != null) { - vObj.setPolicyVersion(versionInfoObj.getPolicyVersion()); - vObj.setTagVersion(versionInfoObj.getTagVersion()); - vObj.setPolicyUpdateTime(versionInfoObj.getPolicyUpdateTime()); - vObj.setTagUpdateTime(versionInfoObj.getTagUpdateTime()); - } else { - vObj.setPolicyVersion(xObj.getPolicyVersion()); - vObj.setTagVersion(xObj.getTagVersion()); - vObj.setPolicyUpdateTime(xObj.getPolicyUpdateTime()); - vObj.setTagUpdateTime(xObj.getTagUpdateTime()); - } - vObj.setIsEnabled(xObj.getIsenabled()); - return vObj; - } - - public RangerServiceList searchRangerServices(SearchFilter searchFilter) { - RangerServiceList retList = new RangerServiceList(); - - int startIndex = searchFilter.getStartIndex(); - int pageSize = searchFilter.getMaxRows(); - searchFilter.setStartIndex(0); - searchFilter.setMaxRows(Integer.MAX_VALUE); - - List xSvcList = searchResources(searchFilter, searchFields, sortFields, retList); - List permittedServices = new ArrayList(); - - for (T xSvc : xSvcList) { - if(bizUtil.hasAccess(xSvc, null)){ - if (!bizUtil.isGdsService(xSvc)) { - permittedServices.add(xSvc); - } - } - } - - if(!permittedServices.isEmpty()) { - populatePageList(permittedServices, startIndex, pageSize, retList); - } - - return retList; - } - - private void populatePageList(List xxObjList, int startIndex, int pageSize, - RangerServiceList retList) { - List onePageList = new ArrayList(); - - for (int i = startIndex; i < pageSize + startIndex && i < xxObjList.size(); i++) { - onePageList.add(populateViewBean(xxObjList.get(i))); - } - retList.setServices(onePageList); - retList.setStartIndex(startIndex); - retList.setPageSize(pageSize); - retList.setResultSize(onePageList.size()); - retList.setTotalCount(xxObjList.size()); - } + @Autowired + GUIDUtil guidUtil; + + public RangerServiceServiceBase() { + super(AppConstants.CLASS_TYPE_XA_SERVICE, AppConstants.CLASS_TYPE_XA_SERVICE_DEF); + + trxLogAttrs.put("name", new VTrxLogAttr("name", "Service Name", false, true)); + trxLogAttrs.put("displayName", new VTrxLogAttr("displayName", "Service Display Name")); + trxLogAttrs.put("description", new VTrxLogAttr("description", "Service Description")); + trxLogAttrs.put("isEnabled", new VTrxLogAttr("isEnabled", "Service Status")); + trxLogAttrs.put("configs", new VTrxLogAttr("configs", "Connection Configurations")); + trxLogAttrs.put("tagService", new VTrxLogAttr("tagService", "Tag Service Name")); + + searchFields.add(new SearchField(SearchFilter.SERVICE_TYPE, "xSvcDef.name", DATA_TYPE.STRING, SEARCH_TYPE.FULL, "XXServiceDef xSvcDef", "obj.type = xSvcDef.id")); + searchFields.add(new SearchField(SearchFilter.SERVICE_TYPE_ID, "obj.type", DATA_TYPE.INTEGER, SEARCH_TYPE.FULL)); + searchFields.add(new SearchField(SearchFilter.SERVICE_NAME, "obj.name", DATA_TYPE.STRING, SEARCH_TYPE.FULL)); + searchFields.add(new SearchField(SearchFilter.SERVICE_DISPLAY_NAME, "obj.displayName", DATA_TYPE.STRING, SEARCH_TYPE.FULL)); + searchFields.add(new SearchField(SearchFilter.SERVICE_NAME_PARTIAL, "obj.name", DATA_TYPE.STRING, SEARCH_TYPE.PARTIAL)); + searchFields.add(new SearchField(SearchFilter.SERVICE_DISPLAY_NAME_PARTIAL, "obj.displayName", DATA_TYPE.STRING, SEARCH_TYPE.PARTIAL)); + searchFields.add(new SearchField(SearchFilter.SERVICE_ID, "obj.id", DATA_TYPE.INTEGER, SEARCH_TYPE.FULL)); + searchFields.add(new SearchField(SearchFilter.IS_ENABLED, "obj.isEnabled", DATA_TYPE.BOOLEAN, SEARCH_TYPE.FULL)); + searchFields.add(new SearchField(SearchFilter.TAG_SERVICE_ID, "obj.tagService", DATA_TYPE.INTEGER, SEARCH_TYPE.FULL)); + searchFields.add(new SearchField(SearchFilter.TAG_SERVICE_NAME, "xTagSvc.name", DATA_TYPE.STRING, SEARCH_TYPE.FULL, "XXServiceBase xTagSvc", "obj.tagService = xTagSvc.id")); + + sortFields.add(new SortField(SearchFilter.CREATE_TIME, "obj.createTime")); + sortFields.add(new SortField(SearchFilter.UPDATE_TIME, "obj.updateTime")); + sortFields.add(new SortField(SearchFilter.SERVICE_ID, "obj.id", true, SORT_ORDER.ASC)); + sortFields.add(new SortField(SearchFilter.SERVICE_NAME, "obj.name")); + sortFields.add(new SortField(SearchFilter.SERVICE_DISPLAY_NAME, "obj.displayName")); + } + + public RangerServiceList searchRangerServices(SearchFilter searchFilter) { + RangerServiceList retList = new RangerServiceList(); + int startIndex = searchFilter.getStartIndex(); + int pageSize = searchFilter.getMaxRows(); + + searchFilter.setStartIndex(0); + searchFilter.setMaxRows(Integer.MAX_VALUE); + + List xSvcList = searchResources(searchFilter, searchFields, sortFields, retList); + List permittedServices = new ArrayList<>(); + + for (T xSvc : xSvcList) { + if (bizUtil.hasAccess(xSvc, null)) { + if (!bizUtil.isGdsService(xSvc)) { + permittedServices.add(xSvc); + } + } + } + + if (!permittedServices.isEmpty()) { + populatePageList(permittedServices, startIndex, pageSize, retList); + } + + return retList; + } + + @Override + protected T mapViewToEntityBean(V vObj, T xObj, int operationContext) { + String guid = (StringUtils.isEmpty(vObj.getGuid())) ? guidUtil.genGUID() : vObj.getGuid(); + + xObj.setGuid(guid); + + XXServiceDef xServiceDef = daoMgr.getXXServiceDef().findByName(vObj.getType()); + + if (xServiceDef == null) { + throw restErrorUtil.createRESTException("No ServiceDefinition found with name :" + vObj.getType(), MessageEnums.INVALID_INPUT_DATA); + } + + Long tagServiceId = null; + String tagServiceName = vObj.getTagService(); + + if (!StringUtils.isEmpty(tagServiceName)) { + XXService xTagService = daoMgr.getXXService().findByName(tagServiceName); + + if (xTagService == null) { + throw restErrorUtil.createRESTException("No Service found with name :" + tagServiceName, MessageEnums.INVALID_INPUT_DATA); + } + + tagServiceId = xTagService.getId(); + } + + xObj.setType(xServiceDef.getId()); + xObj.setName(vObj.getName()); + xObj.setDisplayName(vObj.getDisplayName()); + xObj.setTagService(tagServiceId); + + if (operationContext == OPERATION_CREATE_CONTEXT) { + xObj.setTagVersion(vObj.getTagVersion()); + } + + xObj.setDescription(vObj.getDescription()); + xObj.setIsEnabled(vObj.getIsEnabled()); + + return xObj; + } + + @Override + protected V mapEntityToViewBean(V vObj, T xObj) { + XXServiceDef xServiceDef = daoMgr.getXXServiceDef().getById(xObj.getType()); + XXService xTagService = xObj.getTagService() != null ? daoMgr.getXXService().getById(xObj.getTagService()) : null; + + vObj.setType(xServiceDef.getName()); + vObj.setGuid(xObj.getGuid()); + vObj.setVersion(xObj.getVersion()); + vObj.setName(xObj.getName()); + vObj.setDisplayName(xObj.getDisplayName()); + vObj.setDescription(xObj.getDescription()); + vObj.setTagService(xTagService != null ? xTagService.getName() : null); + + XXServiceVersionInfo versionInfoObj = daoMgr.getXXServiceVersionInfo().findByServiceId(xObj.getId()); + + if (versionInfoObj != null) { + vObj.setPolicyVersion(versionInfoObj.getPolicyVersion()); + vObj.setTagVersion(versionInfoObj.getTagVersion()); + vObj.setPolicyUpdateTime(versionInfoObj.getPolicyUpdateTime()); + vObj.setTagUpdateTime(versionInfoObj.getTagUpdateTime()); + } else { + vObj.setPolicyVersion(xObj.getPolicyVersion()); + vObj.setTagVersion(xObj.getTagVersion()); + vObj.setPolicyUpdateTime(xObj.getPolicyUpdateTime()); + vObj.setTagUpdateTime(xObj.getTagUpdateTime()); + } + + vObj.setIsEnabled(xObj.getIsenabled()); + + return vObj; + } + + private void populatePageList(List xxObjList, int startIndex, int pageSize, RangerServiceList retList) { + List onePageList = new ArrayList<>(); + + for (int i = startIndex; i < pageSize + startIndex && i < xxObjList.size(); i++) { + onePageList.add(populateViewBean(xxObjList.get(i))); + } + retList.setServices(onePageList); + retList.setStartIndex(startIndex); + retList.setPageSize(pageSize); + retList.setResultSize(onePageList.size()); + retList.setTotalCount(xxObjList.size()); + } } diff --git a/security-admin/src/main/java/org/apache/ranger/service/RangerServiceWithAssignedIdService.java b/security-admin/src/main/java/org/apache/ranger/service/RangerServiceWithAssignedIdService.java index 83892bad08..de935a3137 100644 --- a/security-admin/src/main/java/org/apache/ranger/service/RangerServiceWithAssignedIdService.java +++ b/security-admin/src/main/java/org/apache/ranger/service/RangerServiceWithAssignedIdService.java @@ -17,9 +17,6 @@ package org.apache.ranger.service; -import java.util.HashMap; -import java.util.List; - import org.apache.ranger.common.JSONUtil; import org.apache.ranger.entity.XXServiceConfigMap; import org.apache.ranger.entity.XXServiceWithAssignedId; @@ -27,50 +24,49 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; +import java.util.HashMap; +import java.util.List; + @Service public class RangerServiceWithAssignedIdService extends RangerServiceServiceBase { + @Autowired + JSONUtil jsonUtil; + + public RangerService getPopulatedViewObject(XXServiceWithAssignedId xService) { + return this.populateViewBean(xService); + } + + @Override + protected XXServiceWithAssignedId mapViewToEntityBean(RangerService vObj, XXServiceWithAssignedId xObj, int operationContext) { + return super.mapViewToEntityBean(vObj, xObj, operationContext); + } + + @Override + protected RangerService mapEntityToViewBean(RangerService vObj, XXServiceWithAssignedId xObj) { + return super.mapEntityToViewBean(vObj, xObj); + } + + @Override + protected RangerService populateViewBean(XXServiceWithAssignedId xService) { + RangerService vService = super.populateViewBean(xService); + HashMap configs = new HashMap<>(); + List svcConfigMapList = daoMgr.getXXServiceConfigMap().findByServiceId(xService.getId()); - @Autowired - JSONUtil jsonUtil; + for (XXServiceConfigMap svcConfMap : svcConfigMapList) { + configs.put(svcConfMap.getConfigkey(), svcConfMap.getConfigvalue()); + } - @Override - protected XXServiceWithAssignedId mapViewToEntityBean(RangerService vObj, XXServiceWithAssignedId xObj, int OPERATION_CONTEXT) { - return super.mapViewToEntityBean(vObj, xObj, OPERATION_CONTEXT); - } + vService.setConfigs(configs); - @Override - protected RangerService mapEntityToViewBean(RangerService vObj, XXServiceWithAssignedId xObj) { - return super.mapEntityToViewBean(vObj, xObj); - } - - @Override - protected void validateForCreate(RangerService vObj) { - // TODO Auto-generated method stub - - } + return vService; + } - @Override - protected void validateForUpdate(RangerService vService, XXServiceWithAssignedId xService) { - - } - - @Override - protected RangerService populateViewBean(XXServiceWithAssignedId xService) { - RangerService vService = super.populateViewBean(xService); - - HashMap configs = new HashMap(); - List svcConfigMapList = daoMgr.getXXServiceConfigMap() - .findByServiceId(xService.getId()); - for(XXServiceConfigMap svcConfMap : svcConfigMapList) { - configs.put(svcConfMap.getConfigkey(), svcConfMap.getConfigvalue()); - } - vService.setConfigs(configs); - - return vService; - } - - public RangerService getPopulatedViewObject(XXServiceWithAssignedId xService) { - return this.populateViewBean(xService); - } + @Override + protected void validateForCreate(RangerService vObj) { + // TODO Auto-generated method stub + } + @Override + protected void validateForUpdate(RangerService vService, XXServiceWithAssignedId xService) { + } } diff --git a/security-admin/src/main/java/org/apache/ranger/service/RangerTagDefService.java b/security-admin/src/main/java/org/apache/ranger/service/RangerTagDefService.java index b9be0c0dff..6e99228c7b 100644 --- a/security-admin/src/main/java/org/apache/ranger/service/RangerTagDefService.java +++ b/security-admin/src/main/java/org/apache/ranger/service/RangerTagDefService.java @@ -19,9 +19,6 @@ package org.apache.ranger.service; -import java.util.ArrayList; -import java.util.List; - import com.fasterxml.jackson.core.JsonProcessingException; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.StringUtils; @@ -30,111 +27,111 @@ import org.apache.ranger.authorization.utils.JsonUtils; import org.apache.ranger.biz.RangerTagDBRetriever; import org.apache.ranger.common.SearchField; -import org.apache.ranger.common.SortField; import org.apache.ranger.common.SearchField.DATA_TYPE; import org.apache.ranger.common.SearchField.SEARCH_TYPE; +import org.apache.ranger.common.SortField; import org.apache.ranger.entity.XXTagDef; import org.apache.ranger.plugin.model.RangerTagDef; import org.apache.ranger.plugin.util.SearchFilter; import org.springframework.stereotype.Service; +import java.util.ArrayList; +import java.util.List; + @Service public class RangerTagDefService extends RangerTagDefServiceBase { + private static final Log logger = LogFactory.getLog(RangerTagDefService.class); + + public RangerTagDefService() { + searchFields.add(new SearchField(SearchFilter.TAG_DEF_ID, "obj.id", DATA_TYPE.INTEGER, SEARCH_TYPE.FULL)); + searchFields.add(new SearchField(SearchFilter.TAG_DEF_GUID, "obj.guid", DATA_TYPE.STRING, SEARCH_TYPE.FULL)); + searchFields.add(new SearchField(SearchFilter.TAG_TYPE, "obj.name", DATA_TYPE.STRING, SEARCH_TYPE.FULL)); + searchFields.add(new SearchField(SearchFilter.TAG_TYPE_PARTIAL, "obj.name", DATA_TYPE.STRING, SEARCH_TYPE.PARTIAL)); + searchFields.add(new SearchField(SearchFilter.TAG_SOURCE, "obj.source", DATA_TYPE.STRING, SEARCH_TYPE.FULL)); + searchFields.add(new SearchField(SearchFilter.TAG_SOURCE_PARTIAL, "obj.source", DATA_TYPE.STRING, SEARCH_TYPE.PARTIAL)); + + sortFields.add(new SortField(SearchFilter.TAG_DEF_ID, "obj.id", true, SortField.SORT_ORDER.ASC)); + sortFields.add(new SortField(SearchFilter.TAG_TYPE, "obj.name")); + sortFields.add(new SortField(SearchFilter.CREATE_TIME, "obj.createTime")); + sortFields.add(new SortField(SearchFilter.UPDATE_TIME, "obj.updateTime")); + } - private static final Log logger = LogFactory.getLog(RangerTagDefService.class); - - public RangerTagDefService() { - searchFields.add(new SearchField(SearchFilter.TAG_DEF_ID, "obj.id", DATA_TYPE.INTEGER, SEARCH_TYPE.FULL)); - searchFields.add(new SearchField(SearchFilter.TAG_DEF_GUID, "obj.guid", DATA_TYPE.STRING, SEARCH_TYPE.FULL)); - searchFields.add(new SearchField(SearchFilter.TAG_TYPE, "obj.name", DATA_TYPE.STRING, SEARCH_TYPE.FULL)); - searchFields.add(new SearchField(SearchFilter.TAG_TYPE_PARTIAL, "obj.name", DATA_TYPE.STRING, SEARCH_TYPE.PARTIAL)); - searchFields.add(new SearchField(SearchFilter.TAG_SOURCE, "obj.source", DATA_TYPE.STRING, SEARCH_TYPE.FULL)); - searchFields.add(new SearchField(SearchFilter.TAG_SOURCE_PARTIAL, "obj.source", DATA_TYPE.STRING, SEARCH_TYPE.PARTIAL)); + public RangerTagDef getPopulatedViewObject(XXTagDef xObj) { + return populateViewBean(xObj); + } - sortFields.add(new SortField(SearchFilter.TAG_DEF_ID, "obj.id", true, SortField.SORT_ORDER.ASC)); - sortFields.add(new SortField(SearchFilter.TAG_TYPE, "obj.name")); - sortFields.add(new SortField(SearchFilter.CREATE_TIME, "obj.createTime")); - sortFields.add(new SortField(SearchFilter.UPDATE_TIME, "obj.updateTime")); - } - - @Override - protected void validateForCreate(RangerTagDef vObj) { + public RangerTagDef getTagDefByGuid(String guid) { + RangerTagDef ret = null; + XXTagDef xxTagDef = daoMgr.getXXTagDef().findByGuid(guid); - } + if (xxTagDef != null) { + ret = populateViewBean(xxTagDef); + } - @Override - protected void validateForUpdate(RangerTagDef vObj, XXTagDef entityObj) { + return ret; + } - } + public RangerTagDef getTagDefByName(String name) { + RangerTagDef ret = null; + XXTagDef xxTagDef = daoMgr.getXXTagDef().findByName(name); - public RangerTagDef getPopulatedViewObject(XXTagDef xObj) { - return populateViewBean(xObj); - } + if (xxTagDef != null) { + ret = populateViewBean(xxTagDef); + } - public RangerTagDef getTagDefByGuid(String guid) { - RangerTagDef ret = null; + return ret; + } - XXTagDef xxTagDef = daoMgr.getXXTagDef().findByGuid(guid); - - if(xxTagDef != null) { - ret = populateViewBean(xxTagDef); - } + public List getTagDefsByServiceId(Long serviceId) { + List ret = new ArrayList<>(); + List xxTagDefs = daoMgr.getXXTagDef().findByServiceId(serviceId); - return ret; - } + if (CollectionUtils.isNotEmpty(xxTagDefs)) { + for (XXTagDef xxTagDef : xxTagDefs) { + RangerTagDef tagDef = populateViewBean(xxTagDef); - public RangerTagDef getTagDefByName(String name) { - RangerTagDef ret = null; + ret.add(tagDef); + } + } - XXTagDef xxTagDef = daoMgr.getXXTagDef().findByName(name); - - if(xxTagDef != null) { - ret = populateViewBean(xxTagDef); - } + return ret; + } - return ret; - } + @Override + public List getAttributeDefForTagDef(XXTagDef xtagDef) { + return new ArrayList<>(); + } - public List getTagDefsByServiceId(Long serviceId) { - List ret = new ArrayList(); + @Override + protected XXTagDef mapViewToEntityBean(RangerTagDef vObj, XXTagDef xObj, int operationContext) { + XXTagDef ret = super.mapViewToEntityBean(vObj, xObj, operationContext); - List xxTagDefs = daoMgr.getXXTagDef().findByServiceId(serviceId); - - if(CollectionUtils.isNotEmpty(xxTagDefs)) { - for(XXTagDef xxTagDef : xxTagDefs) { - RangerTagDef tagDef = populateViewBean(xxTagDef); - - ret.add(tagDef); - } - } + ret.setTagAttrDefs(JsonUtils.listToJson(vObj.getAttributeDefs())); - return ret; - } + return ret; + } @Override protected RangerTagDef mapEntityToViewBean(RangerTagDef vObj, XXTagDef xObj) { RangerTagDef ret = super.mapEntityToViewBean(vObj, xObj); - if (StringUtils.isNotEmpty(xObj.getTagAttrDefs())) { - try { - List attributeDefs = (List) JsonUtils.jsonToObject(xObj.getTagAttrDefs(), RangerTagDBRetriever.subsumedDataType); - ret.setAttributeDefs(attributeDefs); - } catch (JsonProcessingException e) { - logger.error("Error occurred while processing json", e); - } - } + + if (StringUtils.isNotEmpty(xObj.getTagAttrDefs())) { + try { + List attributeDefs = (List) JsonUtils.jsonToObject(xObj.getTagAttrDefs(), RangerTagDBRetriever.subsumedDataType); + ret.setAttributeDefs(attributeDefs); + } catch (JsonProcessingException e) { + logger.error("Error occurred while processing json", e); + } + } + return ret; } @Override - protected XXTagDef mapViewToEntityBean(RangerTagDef vObj, XXTagDef xObj, int OPERATION_CONTEXT) { - XXTagDef ret = super.mapViewToEntityBean(vObj, xObj, OPERATION_CONTEXT); - ret.setTagAttrDefs(JsonUtils.listToJson(vObj.getAttributeDefs())); - return ret; + protected void validateForCreate(RangerTagDef vObj) { } @Override - public List getAttributeDefForTagDef(XXTagDef xtagDef) { - return new ArrayList<>(); + protected void validateForUpdate(RangerTagDef vObj, XXTagDef entityObj) { } - } diff --git a/security-admin/src/main/java/org/apache/ranger/service/RangerTagDefServiceBase.java b/security-admin/src/main/java/org/apache/ranger/service/RangerTagDefServiceBase.java index 47204767ac..2f763be615 100644 --- a/security-admin/src/main/java/org/apache/ranger/service/RangerTagDefServiceBase.java +++ b/security-admin/src/main/java/org/apache/ranger/service/RangerTagDefServiceBase.java @@ -19,9 +19,6 @@ package org.apache.ranger.service; -import java.util.ArrayList; -import java.util.List; - import org.apache.commons.lang.StringUtils; import org.apache.ranger.common.GUIDUtil; import org.apache.ranger.common.RangerConfigUtil; @@ -33,106 +30,111 @@ import org.apache.ranger.plugin.util.SearchFilter; import org.springframework.beans.factory.annotation.Autowired; -public abstract class RangerTagDefServiceBase extends - RangerBaseModelService { - - @Autowired - GUIDUtil guidUtil; - - @Autowired - RangerAuditFields rangerAuditFields; - - @Autowired - RangerConfigUtil configUtil; - - @Override - protected T mapViewToEntityBean(V vObj, T xObj, int OPERATION_CONTEXT) { - String guid = (StringUtils.isEmpty(vObj.getGuid())) ? guidUtil.genGUID() : vObj.getGuid(); - - xObj.setGuid(guid); - xObj.setVersion(vObj.getVersion()); - xObj.setIsEnabled(vObj.getIsEnabled()); - xObj.setName(vObj.getName()); - xObj.setSource(vObj.getSource()); - return xObj; - } - - @Override - protected V mapEntityToViewBean(V vObj, T xObj) { - - vObj.setGuid(xObj.getGuid()); - vObj.setVersion(xObj.getVersion()); - vObj.setIsEnabled(xObj.getIsEnabled()); - vObj.setName(xObj.getName()); - vObj.setSource(xObj.getSource()); - - List attributeDefs = getAttributeDefForTagDef(xObj); - vObj.setAttributeDefs(attributeDefs); - - return vObj; - } - - public List getAttributeDefForTagDef(XXTagDef xtagDef) { - List tagAttrDefList = daoMgr.getXXTagAttributeDef().findByTagDefId(xtagDef.getId()); - List attributeDefList = new ArrayList(); - - for (XXTagAttributeDef xAttrTag : tagAttrDefList) { - RangerTagAttributeDef attrDef = populateRangerTagAttributeDef(xAttrTag); - attributeDefList.add(attrDef); - } - return attributeDefList; - } - - /** - * @param xObj - * @return - */ - public RangerTagAttributeDef populateRangerTagAttributeDef(XXTagAttributeDef xObj) { - RangerTagAttributeDef attrDef = new RangerTagAttributeDef(); - attrDef.setName(xObj.getName()); - attrDef.setType(xObj.getType()); - return attrDef; - } - - /** - * @param attrDef - * @param xTagAttrDef - * @param parentObj - * @return - */ - public XXTagAttributeDef populateXXTagAttributeDef(RangerTagAttributeDef attrDef, XXTagAttributeDef xTagAttrDef, - XXTagDef parentObj) { - - if (xTagAttrDef == null) { - xTagAttrDef = new XXTagAttributeDef(); - } - - xTagAttrDef = rangerAuditFields.populateAuditFields(xTagAttrDef, parentObj); - - xTagAttrDef.setTagDefId(parentObj.getId()); - xTagAttrDef.setName(attrDef.getName()); - xTagAttrDef.setType(attrDef.getType()); - return xTagAttrDef; - } - - public PList searchRangerTagDefs(SearchFilter searchFilter) { - PList retList = new PList(); - List tagDefList = new ArrayList(); - - List xTagDefList = searchRangerObjects(searchFilter, searchFields, sortFields, retList); - - for (T xTagDef : xTagDefList) { - V tagDef = populateViewBean(xTagDef); - tagDefList.add(tagDef); - } - - retList.setList(tagDefList); - retList.setResultSize(tagDefList.size()); - retList.setPageSize(searchFilter.getMaxRows()); - retList.setStartIndex(searchFilter.getStartIndex()); - retList.setSortType(searchFilter.getSortType()); - retList.setSortBy(searchFilter.getSortBy()); - - return retList; - } +import java.util.ArrayList; +import java.util.List; + +public abstract class RangerTagDefServiceBase extends RangerBaseModelService { + @Autowired + GUIDUtil guidUtil; + + @Autowired + RangerAuditFields rangerAuditFields; + + @Autowired + RangerConfigUtil configUtil; + + public List getAttributeDefForTagDef(XXTagDef xtagDef) { + List tagAttrDefList = daoMgr.getXXTagAttributeDef().findByTagDefId(xtagDef.getId()); + List attributeDefList = new ArrayList<>(); + + for (XXTagAttributeDef xAttrTag : tagAttrDefList) { + RangerTagAttributeDef attrDef = populateRangerTagAttributeDef(xAttrTag); + + attributeDefList.add(attrDef); + } + + return attributeDefList; + } + + /** + * @param xObj + * @return + */ + public RangerTagAttributeDef populateRangerTagAttributeDef(XXTagAttributeDef xObj) { + RangerTagAttributeDef attrDef = new RangerTagAttributeDef(); + + attrDef.setName(xObj.getName()); + attrDef.setType(xObj.getType()); + + return attrDef; + } + + /** + * @param attrDef + * @param xTagAttrDef + * @param parentObj + * @return + */ + public XXTagAttributeDef populateXXTagAttributeDef(RangerTagAttributeDef attrDef, XXTagAttributeDef xTagAttrDef, XXTagDef parentObj) { + if (xTagAttrDef == null) { + xTagAttrDef = new XXTagAttributeDef(); + } + + xTagAttrDef = rangerAuditFields.populateAuditFields(xTagAttrDef, parentObj); + + xTagAttrDef.setTagDefId(parentObj.getId()); + xTagAttrDef.setName(attrDef.getName()); + xTagAttrDef.setType(attrDef.getType()); + + return xTagAttrDef; + } + + public PList searchRangerTagDefs(SearchFilter searchFilter) { + PList retList = new PList<>(); + List tagDefList = new ArrayList<>(); + List xTagDefList = searchRangerObjects(searchFilter, searchFields, sortFields, retList); + + for (T xTagDef : xTagDefList) { + V tagDef = populateViewBean(xTagDef); + + tagDefList.add(tagDef); + } + + retList.setList(tagDefList); + retList.setResultSize(tagDefList.size()); + retList.setPageSize(searchFilter.getMaxRows()); + retList.setStartIndex(searchFilter.getStartIndex()); + retList.setSortType(searchFilter.getSortType()); + retList.setSortBy(searchFilter.getSortBy()); + + return retList; + } + + @Override + protected T mapViewToEntityBean(V vObj, T xObj, int operationContext) { + String guid = (StringUtils.isEmpty(vObj.getGuid())) ? guidUtil.genGUID() : vObj.getGuid(); + + xObj.setGuid(guid); + xObj.setVersion(vObj.getVersion()); + xObj.setIsEnabled(vObj.getIsEnabled()); + xObj.setName(vObj.getName()); + xObj.setSource(vObj.getSource()); + + return xObj; + } + + @Override + protected V mapEntityToViewBean(V vObj, T xObj) { + vObj.setGuid(xObj.getGuid()); + vObj.setVersion(xObj.getVersion()); + vObj.setIsEnabled(xObj.getIsEnabled()); + vObj.setName(xObj.getName()); + vObj.setSource(xObj.getSource()); + + List attributeDefs = getAttributeDefForTagDef(xObj); + + vObj.setAttributeDefs(attributeDefs); + + return vObj; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/service/RangerTagResourceMapService.java b/security-admin/src/main/java/org/apache/ranger/service/RangerTagResourceMapService.java index fd39a4ecb9..c58c21ae51 100755 --- a/security-admin/src/main/java/org/apache/ranger/service/RangerTagResourceMapService.java +++ b/security-admin/src/main/java/org/apache/ranger/service/RangerTagResourceMapService.java @@ -19,9 +19,6 @@ package org.apache.ranger.service; -import java.util.ArrayList; -import java.util.List; - import org.apache.commons.collections.CollectionUtils; import org.apache.ranger.common.SearchField; import org.apache.ranger.common.SearchField.DATA_TYPE; @@ -32,174 +29,163 @@ import org.apache.ranger.plugin.util.SearchFilter; import org.springframework.stereotype.Service; +import java.util.ArrayList; +import java.util.List; + @Service public class RangerTagResourceMapService extends RangerTagResourceMapServiceBase { + public RangerTagResourceMapService() { + searchFields.add(new SearchField(SearchFilter.TAG_DEF_ID, "obj.id", DATA_TYPE.INTEGER, SEARCH_TYPE.FULL)); + searchFields.add(new SearchField(SearchFilter.TAG_RESOURCE_ID, "obj.resourceId", DATA_TYPE.INTEGER, SearchField.SEARCH_TYPE.FULL)); + searchFields.add(new SearchField(SearchFilter.TAG_ID, "obj.tagId", DATA_TYPE.INTEGER, SearchField.SEARCH_TYPE.FULL)); + searchFields.add(new SearchField(SearchFilter.TAG_SERVICE_NAME, "svc.name", DATA_TYPE.STRING, SEARCH_TYPE.FULL, "XXServiceResource svcr, XXService svc", "obj.resourceId = svcr.id and svcr.serviceId = svc.id")); - public RangerTagResourceMapService() { - searchFields.add(new SearchField(SearchFilter.TAG_DEF_ID, "obj.id", DATA_TYPE.INTEGER, SEARCH_TYPE.FULL)); - searchFields.add(new SearchField(SearchFilter.TAG_RESOURCE_ID, "obj.resourceId", DATA_TYPE.INTEGER, SearchField.SEARCH_TYPE.FULL)); - searchFields.add(new SearchField(SearchFilter.TAG_ID, "obj.tagId", DATA_TYPE.INTEGER, SearchField.SEARCH_TYPE.FULL)); - searchFields.add(new SearchField(SearchFilter.TAG_SERVICE_NAME, "svc.name", DATA_TYPE.STRING, SEARCH_TYPE.FULL, "XXServiceResource svcr, XXService svc", "obj.resourceId = svcr.id and svcr.serviceId = svc.id")); - - sortFields.add(new SortField(SearchFilter.TAG_DEF_ID, "obj.id", true, SortField.SORT_ORDER.ASC)); - sortFields.add(new SortField(SearchFilter.TAG_RESOURCE_ID, "obj.resourceId")); - sortFields.add(new SortField(SearchFilter.TAG_ID, "obj.tagId")); - } - - @Override - protected void validateForCreate(RangerTagResourceMap vObj) { - - } - - @Override - protected void validateForUpdate(RangerTagResourceMap vObj, XXTagResourceMap entityObj) { - - } - - @Override - public RangerTagResourceMap postCreate(XXTagResourceMap tagResMap) { - RangerTagResourceMap ret = super.postCreate(tagResMap); + sortFields.add(new SortField(SearchFilter.TAG_DEF_ID, "obj.id", true, SortField.SORT_ORDER.ASC)); + sortFields.add(new SortField(SearchFilter.TAG_RESOURCE_ID, "obj.resourceId")); + sortFields.add(new SortField(SearchFilter.TAG_ID, "obj.tagId")); + } - daoMgr.getXXServiceVersionInfo().updateServiceVersionInfoForTagResourceMapCreate(tagResMap.getResourceId(), tagResMap.getTagId()); + @Override + public RangerTagResourceMap postCreate(XXTagResourceMap tagResMap) { + RangerTagResourceMap ret = super.postCreate(tagResMap); - return ret; - } + daoMgr.getXXServiceVersionInfo().updateServiceVersionInfoForTagResourceMapCreate(tagResMap.getResourceId(), tagResMap.getTagId()); - @Override - protected XXTagResourceMap preDelete(Long id) { - XXTagResourceMap tagResMap = super.preDelete(id); + return ret; + } - if (tagResMap != null) { - daoMgr.getXXServiceVersionInfo().updateServiceVersionInfoForTagResourceMapDelete(tagResMap.getResourceId(), tagResMap.getTagId()); - } + @Override + protected void validateForCreate(RangerTagResourceMap vObj) { + } - return tagResMap; - } + @Override + protected void validateForUpdate(RangerTagResourceMap vObj, XXTagResourceMap entityObj) { + } - public RangerTagResourceMap getPopulatedViewObject(XXTagResourceMap xObj) { - return populateViewBean(xObj); - } + @Override + protected XXTagResourceMap preDelete(Long id) { + XXTagResourceMap tagResMap = super.preDelete(id); + if (tagResMap != null) { + daoMgr.getXXServiceVersionInfo().updateServiceVersionInfoForTagResourceMapDelete(tagResMap.getResourceId(), tagResMap.getTagId()); + } - public List getByTagId(Long tagId) { - List ret = new ArrayList(); + return tagResMap; + } - List xxTagResourceMaps = daoMgr.getXXTagResourceMap().findByTagId(tagId); - - if(CollectionUtils.isNotEmpty(xxTagResourceMaps)) { - for(XXTagResourceMap xxTagResourceMap : xxTagResourceMaps) { - RangerTagResourceMap tagResourceMap = populateViewBean(xxTagResourceMap); + public RangerTagResourceMap getPopulatedViewObject(XXTagResourceMap xObj) { + return populateViewBean(xObj); + } - ret.add(tagResourceMap); - } - } + public List getByTagId(Long tagId) { + List ret = new ArrayList<>(); + List xxTagResourceMaps = daoMgr.getXXTagResourceMap().findByTagId(tagId); - return ret; - } + if (CollectionUtils.isNotEmpty(xxTagResourceMaps)) { + for (XXTagResourceMap xxTagResourceMap : xxTagResourceMaps) { + RangerTagResourceMap tagResourceMap = populateViewBean(xxTagResourceMap); - public List getByTagGuid(String tagGuid) { - List ret = new ArrayList(); + ret.add(tagResourceMap); + } + } - List xxTagResourceMaps = daoMgr.getXXTagResourceMap().findByTagGuid(tagGuid); - - if(CollectionUtils.isNotEmpty(xxTagResourceMaps)) { - for(XXTagResourceMap xxTagResourceMap : xxTagResourceMaps) { - RangerTagResourceMap tagResourceMap = populateViewBean(xxTagResourceMap); + return ret; + } - ret.add(tagResourceMap); - } - } + public List getByTagGuid(String tagGuid) { + List ret = new ArrayList<>(); + List xxTagResourceMaps = daoMgr.getXXTagResourceMap().findByTagGuid(tagGuid); - return ret; - } + if (CollectionUtils.isNotEmpty(xxTagResourceMaps)) { + for (XXTagResourceMap xxTagResourceMap : xxTagResourceMaps) { + RangerTagResourceMap tagResourceMap = populateViewBean(xxTagResourceMap); - public List getByResourceId(Long resourceId) { - List ret = new ArrayList(); + ret.add(tagResourceMap); + } + } - List xxTagResourceMaps = daoMgr.getXXTagResourceMap().findByResourceId(resourceId); - - if(CollectionUtils.isNotEmpty(xxTagResourceMaps)) { - for(XXTagResourceMap xxTagResourceMap : xxTagResourceMaps) { - RangerTagResourceMap tagResourceMap = populateViewBean(xxTagResourceMap); + return ret; + } - ret.add(tagResourceMap); - } - } + public List getByResourceId(Long resourceId) { + List ret = new ArrayList<>(); + List xxTagResourceMaps = daoMgr.getXXTagResourceMap().findByResourceId(resourceId); - return ret; - } + if (CollectionUtils.isNotEmpty(xxTagResourceMaps)) { + for (XXTagResourceMap xxTagResourceMap : xxTagResourceMaps) { + RangerTagResourceMap tagResourceMap = populateViewBean(xxTagResourceMap); - public List getTagIdsForResourceId(Long resourceId) { - List ret = daoMgr.getXXTagResourceMap().findTagIdsForResourceId(resourceId); + ret.add(tagResourceMap); + } + } - return ret; - } + return ret; + } - public List getByResourceGuid(String resourceGuid) { - List ret = new ArrayList(); + public List getTagIdsForResourceId(Long resourceId) { + return daoMgr.getXXTagResourceMap().findTagIdsForResourceId(resourceId); + } - List xxTagResourceMaps = daoMgr.getXXTagResourceMap().findByResourceGuid(resourceGuid); - - if(CollectionUtils.isNotEmpty(xxTagResourceMaps)) { - for(XXTagResourceMap xxTagResourceMap : xxTagResourceMaps) { - RangerTagResourceMap tagResourceMap = populateViewBean(xxTagResourceMap); + public List getByResourceGuid(String resourceGuid) { + List ret = new ArrayList<>(); + List xxTagResourceMaps = daoMgr.getXXTagResourceMap().findByResourceGuid(resourceGuid); - ret.add(tagResourceMap); - } - } + if (CollectionUtils.isNotEmpty(xxTagResourceMaps)) { + for (XXTagResourceMap xxTagResourceMap : xxTagResourceMaps) { + RangerTagResourceMap tagResourceMap = populateViewBean(xxTagResourceMap); - return ret; - } - - public RangerTagResourceMap getByGuid(String guid) { - RangerTagResourceMap ret = null; + ret.add(tagResourceMap); + } + } - XXTagResourceMap xxTagResourceMap = daoMgr.getXXTagResourceMap().findByGuid(guid); + return ret; + } - if(xxTagResourceMap != null) { - ret = populateViewBean(xxTagResourceMap); - } + public RangerTagResourceMap getByGuid(String guid) { + RangerTagResourceMap ret = null; + XXTagResourceMap xxTagResourceMap = daoMgr.getXXTagResourceMap().findByGuid(guid); - return ret; - } - - public RangerTagResourceMap getByTagAndResourceId(Long tagId, Long resourceId) { - RangerTagResourceMap ret = null; + if (xxTagResourceMap != null) { + ret = populateViewBean(xxTagResourceMap); + } - XXTagResourceMap xxTagResourceMap = daoMgr.getXXTagResourceMap().findByTagAndResourceId(tagId, resourceId); + return ret; + } - if(xxTagResourceMap != null) { - ret = populateViewBean(xxTagResourceMap); - } + public RangerTagResourceMap getByTagAndResourceId(Long tagId, Long resourceId) { + RangerTagResourceMap ret = null; + XXTagResourceMap xxTagResourceMap = daoMgr.getXXTagResourceMap().findByTagAndResourceId(tagId, resourceId); - return ret; - } + if (xxTagResourceMap != null) { + ret = populateViewBean(xxTagResourceMap); + } - public RangerTagResourceMap getByTagAndResourceGuid(String tagGuid, String resourceGuid) { - RangerTagResourceMap ret = null; + return ret; + } - XXTagResourceMap xxTagResourceMap = daoMgr.getXXTagResourceMap().findByTagAndResourceGuid(tagGuid, resourceGuid); + public RangerTagResourceMap getByTagAndResourceGuid(String tagGuid, String resourceGuid) { + RangerTagResourceMap ret = null; + XXTagResourceMap xxTagResourceMap = daoMgr.getXXTagResourceMap().findByTagAndResourceGuid(tagGuid, resourceGuid); - if(xxTagResourceMap != null) { - ret = populateViewBean(xxTagResourceMap); - } + if (xxTagResourceMap != null) { + ret = populateViewBean(xxTagResourceMap); + } - return ret; - } + return ret; + } - public List getTagResourceMapsByServiceId(Long serviceId) { - List ret = new ArrayList(); + public List getTagResourceMapsByServiceId(Long serviceId) { + List ret = new ArrayList<>(); + List xxTagResourceMaps = daoMgr.getXXTagResourceMap().findByServiceId(serviceId); - List xxTagResourceMaps = daoMgr.getXXTagResourceMap().findByServiceId(serviceId); - - if(CollectionUtils.isNotEmpty(xxTagResourceMaps)) { - for(XXTagResourceMap xxTagResourceMap : xxTagResourceMaps) { - RangerTagResourceMap tagResourceMap = populateViewBean(xxTagResourceMap); + if (CollectionUtils.isNotEmpty(xxTagResourceMaps)) { + for (XXTagResourceMap xxTagResourceMap : xxTagResourceMaps) { + RangerTagResourceMap tagResourceMap = populateViewBean(xxTagResourceMap); - ret.add(tagResourceMap); - } - } + ret.add(tagResourceMap); + } + } - return ret; - } + return ret; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/service/RangerTagResourceMapServiceBase.java b/security-admin/src/main/java/org/apache/ranger/service/RangerTagResourceMapServiceBase.java index 97b8150d39..e18ddffee6 100644 --- a/security-admin/src/main/java/org/apache/ranger/service/RangerTagResourceMapServiceBase.java +++ b/security-admin/src/main/java/org/apache/ranger/service/RangerTagResourceMapServiceBase.java @@ -19,9 +19,6 @@ package org.apache.ranger.service; -import java.util.ArrayList; -import java.util.List; - import org.apache.commons.lang.StringUtils; import org.apache.ranger.common.GUIDUtil; import org.apache.ranger.entity.XXTagResourceMap; @@ -30,43 +27,44 @@ import org.apache.ranger.plugin.util.SearchFilter; import org.springframework.beans.factory.annotation.Autowired; -public abstract class RangerTagResourceMapServiceBase extends RangerBaseModelService { - - @Autowired - GUIDUtil guidUtil; +import java.util.ArrayList; +import java.util.List; - @Override - protected T mapViewToEntityBean(V vObj, T xObj, int operationContext) { - String guid = (StringUtils.isEmpty(vObj.getGuid())) ? guidUtil.genGUID() : vObj.getGuid(); +public abstract class RangerTagResourceMapServiceBase extends RangerBaseModelService { + @Autowired + GUIDUtil guidUtil; - xObj.setGuid(guid); - xObj.setTagId(vObj.getTagId()); - xObj.setResourceId(vObj.getResourceId()); + public PList searchRangerTaggedResources(SearchFilter searchFilter) { + PList retList = new PList(); + List taggedResList = new ArrayList(); - return xObj; - } + List xTaggedResList = searchRangerObjects(searchFilter, searchFields, sortFields, retList); - @Override - protected V mapEntityToViewBean(V vObj, T xObj) { - vObj.setGuid(xObj.getGuid()); - vObj.setTagId(xObj.getTagId()); - vObj.setResourceId(xObj.getResourceId()); + for (T xTaggedRes : xTaggedResList) { + V taggedRes = populateViewBean(xTaggedRes); + taggedResList.add(taggedRes); + } + retList.setList(taggedResList); + return retList; + } - return vObj; - } + @Override + protected T mapViewToEntityBean(V vObj, T xObj, int operationContext) { + String guid = (StringUtils.isEmpty(vObj.getGuid())) ? guidUtil.genGUID() : vObj.getGuid(); - public PList searchRangerTaggedResources(SearchFilter searchFilter) { - PList retList = new PList(); - List taggedResList = new ArrayList(); + xObj.setGuid(guid); + xObj.setTagId(vObj.getTagId()); + xObj.setResourceId(vObj.getResourceId()); - List xTaggedResList = searchRangerObjects(searchFilter, searchFields, sortFields, retList); + return xObj; + } - for (T xTaggedRes : xTaggedResList) { - V taggedRes = populateViewBean(xTaggedRes); - taggedResList.add(taggedRes); - } - retList.setList(taggedResList); - return retList; - } + @Override + protected V mapEntityToViewBean(V vObj, T xObj) { + vObj.setGuid(xObj.getGuid()); + vObj.setTagId(xObj.getTagId()); + vObj.setResourceId(xObj.getResourceId()); + return vObj; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/service/RangerTagService.java b/security-admin/src/main/java/org/apache/ranger/service/RangerTagService.java index 89fcf28c3d..b9af5737d4 100755 --- a/security-admin/src/main/java/org/apache/ranger/service/RangerTagService.java +++ b/security-admin/src/main/java/org/apache/ranger/service/RangerTagService.java @@ -19,20 +19,15 @@ package org.apache.ranger.service; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.type.TypeReference; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang.StringUtils; import org.apache.ranger.authorization.utils.JsonUtils; import org.apache.ranger.common.SearchField; -import org.apache.ranger.common.SortField; import org.apache.ranger.common.SearchField.DATA_TYPE; import org.apache.ranger.common.SearchField.SEARCH_TYPE; +import org.apache.ranger.common.SortField; import org.apache.ranger.entity.XXServiceResource; import org.apache.ranger.entity.XXTag; import org.apache.ranger.plugin.model.RangerTag; @@ -41,173 +36,177 @@ import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; @Service public class RangerTagService extends RangerTagServiceBase { - private static final Logger logger = LoggerFactory.getLogger(RangerTagService.class); + private static final Logger logger = LoggerFactory.getLogger(RangerTagService.class); - private static final TypeReference subsumedDataType = new TypeReference>() {}; + private static final TypeReference> subsumedDataType = new TypeReference>() {}; - public RangerTagService() { - searchFields.add(new SearchField(SearchFilter.TAG_ID, "obj.id", SearchField.DATA_TYPE.INTEGER, SearchField.SEARCH_TYPE.FULL)); - searchFields.add(new SearchField(SearchFilter.TAG_DEF_ID, "obj.type", SearchField.DATA_TYPE.INTEGER, SearchField.SEARCH_TYPE.FULL)); - searchFields.add(new SearchField(SearchFilter.TAG_TYPE, "tagDef.name", DATA_TYPE.STRING, SEARCH_TYPE.FULL, "XXTagDef tagDef", "obj.type = tagDef.id")); - searchFields.add(new SearchField(SearchFilter.TAG_TYPE_PARTIAL, "tagDef.name", DATA_TYPE.STRING, SEARCH_TYPE.PARTIAL, "XXTagDef tagDef", "obj.type = tagDef.id")); - searchFields.add(new SearchField(SearchFilter.TAG_IDS, "obj.id", SearchField.DATA_TYPE.INT_LIST, SearchField.SEARCH_TYPE.FULL)); + public RangerTagService() { + searchFields.add(new SearchField(SearchFilter.TAG_ID, "obj.id", SearchField.DATA_TYPE.INTEGER, SearchField.SEARCH_TYPE.FULL)); + searchFields.add(new SearchField(SearchFilter.TAG_DEF_ID, "obj.type", SearchField.DATA_TYPE.INTEGER, SearchField.SEARCH_TYPE.FULL)); + searchFields.add(new SearchField(SearchFilter.TAG_TYPE, "tagDef.name", DATA_TYPE.STRING, SEARCH_TYPE.FULL, "XXTagDef tagDef", "obj.type = tagDef.id")); + searchFields.add(new SearchField(SearchFilter.TAG_TYPE_PARTIAL, "tagDef.name", DATA_TYPE.STRING, SEARCH_TYPE.PARTIAL, "XXTagDef tagDef", "obj.type = tagDef.id")); + searchFields.add(new SearchField(SearchFilter.TAG_IDS, "obj.id", SearchField.DATA_TYPE.INT_LIST, SearchField.SEARCH_TYPE.FULL)); - sortFields.add(new SortField(SearchFilter.TAG_ID, "obj.id", true, SortField.SORT_ORDER.ASC)); - sortFields.add(new SortField(SearchFilter.TAG_DEF_ID, "obj.type")); - sortFields.add(new SortField(SearchFilter.CREATE_TIME, "obj.createTime")); - sortFields.add(new SortField(SearchFilter.UPDATE_TIME, "obj.updateTime")); - } - - @Override - protected void validateForCreate(RangerTag vObj) { - - } + sortFields.add(new SortField(SearchFilter.TAG_ID, "obj.id", true, SortField.SORT_ORDER.ASC)); + sortFields.add(new SortField(SearchFilter.TAG_DEF_ID, "obj.type")); + sortFields.add(new SortField(SearchFilter.CREATE_TIME, "obj.createTime")); + sortFields.add(new SortField(SearchFilter.UPDATE_TIME, "obj.updateTime")); + } - @Override - protected void validateForUpdate(RangerTag vObj, XXTag entityObj) { + public RangerTag getPopulatedViewObject(XXTag xObj) { + return populateViewBean(xObj); + } - } + public RangerTag getTagByGuid(String guid) { + RangerTag ret = null; + XXTag xxTag = daoMgr.getXXTag().findByGuid(guid); - @Override - public RangerTag postCreate(XXTag tag) { - RangerTag ret = super.postCreate(tag); + if (xxTag != null) { + ret = populateViewBean(xxTag); + } - // This is not needed - on tag creation, service-version-info need not be updated. - //daoMgr.getXXServiceVersionInfo().updateServiceVersionInfoForTagUpdate(tag.getId()); + return ret; + } - return ret; - } + public List getTagsByType(String name) { + List ret = new ArrayList<>(); + List xxTags = daoMgr.getXXTag().findByName(name); - @Override - public RangerTag postUpdate(XXTag tag) { - RangerTag ret = super.postUpdate(tag); + if (CollectionUtils.isNotEmpty(xxTags)) { + for (XXTag xxTag : xxTags) { + RangerTag tag = populateViewBean(xxTag); - daoMgr.getXXServiceVersionInfo().updateServiceVersionInfoForTagUpdate(tag.getId()); + ret.add(tag); + } + } - return ret; - } + return ret; + } - @Override - protected XXTag preDelete(Long id) { - XXTag ret = super.preDelete(id); + public List getTagsForResourceId(Long resourceId) { + List ret = new ArrayList<>(); + XXServiceResource serviceResourceEntity = daoMgr.getXXServiceResource().getById(resourceId); - daoMgr.getXXServiceVersionInfo().updateServiceVersionInfoForTagUpdate(id); + if (serviceResourceEntity != null) { + String tagsText = serviceResourceEntity.getTags(); - return ret; - } + if (StringUtils.isNotEmpty(tagsText)) { + try { + ret = JsonUtils.jsonToObject(tagsText, RangerServiceResourceService.duplicatedDataType); + } catch (JsonProcessingException e) { + logger.error("Error occurred while processing json", e); + } + } + } - public RangerTag getPopulatedViewObject(XXTag xObj) { - return populateViewBean(xObj); - } + return ret; + } - public RangerTag getTagByGuid(String guid) { - RangerTag ret = null; + public List getTagsForResourceGuid(String resourceGuid) { + List ret = new ArrayList<>(); + XXServiceResource serviceResourceEntity = daoMgr.getXXServiceResource().findByGuid(resourceGuid); - XXTag xxTag = daoMgr.getXXTag().findByGuid(guid); - - if(xxTag != null) { - ret = populateViewBean(xxTag); - } + if (serviceResourceEntity != null) { + String tagsText = serviceResourceEntity.getTags(); - return ret; - } + if (StringUtils.isNotEmpty(tagsText)) { + try { + ret = JsonUtils.jsonToObject(tagsText, RangerServiceResourceService.duplicatedDataType); + } catch (JsonProcessingException e) { + logger.error("Error occurred while processing json", e); + } + } + } - public List getTagsByType(String name) { - List ret = new ArrayList(); + return ret; + } - List xxTags = daoMgr.getXXTag().findByName(name); - - if(CollectionUtils.isNotEmpty(xxTags)) { - for(XXTag xxTag : xxTags) { - RangerTag tag = populateViewBean(xxTag); + public List getTagsByServiceId(Long serviceId) { + List ret = new ArrayList<>(); + List xxTags = daoMgr.getXXTag().findByServiceId(serviceId); - ret.add(tag); - } - } + if (CollectionUtils.isNotEmpty(xxTags)) { + for (XXTag xxTag : xxTags) { + RangerTag tag = populateViewBean(xxTag); - return ret; - } + ret.add(tag); + } + } - public List getTagsForResourceId(Long resourceId) { - List ret = new ArrayList(); + return ret; + } - XXServiceResource serviceResourceEntity = daoMgr.getXXServiceResource().getById(resourceId); + @Override + public RangerTag postCreate(XXTag tag) { + RangerTag ret = super.postCreate(tag); - if (serviceResourceEntity != null) { - String tagsText = serviceResourceEntity.getTags(); - if (StringUtils.isNotEmpty(tagsText)) { - try { - ret = (List) JsonUtils.jsonToObject(tagsText, RangerServiceResourceService.duplicatedDataType); - } catch (JsonProcessingException e) { - logger.error("Error occurred while processing json", e); - } - } - } + // This is not needed - on tag creation, service-version-info need not be updated. + //daoMgr.getXXServiceVersionInfo().updateServiceVersionInfoForTagUpdate(tag.getId()); - return ret; - } + return ret; + } - public List getTagsForResourceGuid(String resourceGuid) { - List ret = new ArrayList(); + @Override + public RangerTag postUpdate(XXTag tag) { + RangerTag ret = super.postUpdate(tag); - XXServiceResource serviceResourceEntity = daoMgr.getXXServiceResource().findByGuid(resourceGuid); + daoMgr.getXXServiceVersionInfo().updateServiceVersionInfoForTagUpdate(tag.getId()); - if (serviceResourceEntity != null) { - String tagsText = serviceResourceEntity.getTags(); - if (StringUtils.isNotEmpty(tagsText)) { - try { - ret = (List) JsonUtils.jsonToObject(tagsText, RangerServiceResourceService.duplicatedDataType); - } catch (JsonProcessingException e) { - logger.error("Error occurred while processing json", e); - } - } - } + return ret; + } - return ret; - } + @Override + protected void validateForCreate(RangerTag vObj) { + } - public List getTagsByServiceId(Long serviceId) { - List ret = new ArrayList(); + @Override + protected void validateForUpdate(RangerTag vObj, XXTag entityObj) { + } - List xxTags = daoMgr.getXXTag().findByServiceId(serviceId); - - if(CollectionUtils.isNotEmpty(xxTags)) { - for(XXTag xxTag : xxTags) { - RangerTag tag = populateViewBean(xxTag); + @Override + protected XXTag preDelete(Long id) { + XXTag ret = super.preDelete(id); - ret.add(tag); - } - } + daoMgr.getXXServiceVersionInfo().updateServiceVersionInfoForTagUpdate(id); - return ret; - } + return ret; + } @Override - protected RangerTag mapEntityToViewBean(RangerTag vObj, XXTag xObj) { - RangerTag ret = super.mapEntityToViewBean(vObj, xObj); - if (StringUtils.isNotEmpty(xObj.getTagAttrs())) { - try { - Map attributes = (Map) JsonUtils.jsonToObject(xObj.getTagAttrs(), RangerTagService.subsumedDataType); - ret.setAttributes(attributes); - } catch (JsonProcessingException e) { - logger.error("Error occurred while processing json", e); - } - } - return ret; + public Map getAttributesForTag(XXTag xTag) { + return new HashMap<>(); } @Override - protected XXTag mapViewToEntityBean(RangerTag vObj, XXTag xObj, int OPERATION_CONTEXT) { - XXTag ret = super.mapViewToEntityBean(vObj, xObj, OPERATION_CONTEXT); + protected XXTag mapViewToEntityBean(RangerTag vObj, XXTag xObj, int operationContext) { + XXTag ret = super.mapViewToEntityBean(vObj, xObj, operationContext); + ret.setTagAttrs(JsonUtils.mapToJson(vObj.getAttributes())); + return ret; } @Override - public Map getAttributesForTag(XXTag xTag) { - return new HashMap<>(); + protected RangerTag mapEntityToViewBean(RangerTag vObj, XXTag xObj) { + RangerTag ret = super.mapEntityToViewBean(vObj, xObj); + + if (StringUtils.isNotEmpty(xObj.getTagAttrs())) { + try { + Map attributes = JsonUtils.jsonToObject(xObj.getTagAttrs(), RangerTagService.subsumedDataType); + + ret.setAttributes(attributes); + } catch (JsonProcessingException e) { + logger.error("Error occurred while processing json", e); + } + } + + return ret; } } diff --git a/security-admin/src/main/java/org/apache/ranger/service/RangerTagServiceBase.java b/security-admin/src/main/java/org/apache/ranger/service/RangerTagServiceBase.java index 1d35564a07..dc1b267b18 100644 --- a/security-admin/src/main/java/org/apache/ranger/service/RangerTagServiceBase.java +++ b/security-admin/src/main/java/org/apache/ranger/service/RangerTagServiceBase.java @@ -19,11 +19,6 @@ package org.apache.ranger.service; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.MapUtils; import org.apache.commons.lang.StringUtils; @@ -31,8 +26,8 @@ import org.apache.ranger.common.GUIDUtil; import org.apache.ranger.common.MessageEnums; import org.apache.ranger.common.RangerConfigUtil; -import org.apache.ranger.entity.XXTagAttribute; import org.apache.ranger.entity.XXTag; +import org.apache.ranger.entity.XXTagAttribute; import org.apache.ranger.entity.XXTagDef; import org.apache.ranger.plugin.model.RangerTag; import org.apache.ranger.plugin.model.RangerValiditySchedule; @@ -40,113 +35,116 @@ import org.apache.ranger.plugin.util.SearchFilter; import org.springframework.beans.factory.annotation.Autowired; -public abstract class RangerTagServiceBase extends - RangerBaseModelService { +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public abstract class RangerTagServiceBase extends RangerBaseModelService { + @Autowired + GUIDUtil guidUtil; + + @Autowired + RangerAuditFields rangerAuditFields; + + @Autowired + RangerConfigUtil configUtil; + + public Map getAttributesForTag(XXTag xtag) { + List tagAttrList = daoMgr.getXXTagAttribute().findByTagId(xtag.getId()); + Map ret = new HashMap<>(); + + if (CollectionUtils.isNotEmpty(tagAttrList)) { + for (XXTagAttribute tagAttr : tagAttrList) { + ret.put(tagAttr.getName(), tagAttr.getValue()); + } + } + + return ret; + } + + public PList searchRangerTags(SearchFilter searchFilter) { + PList retList = new PList<>(); + List tagList = new ArrayList<>(); + List xTagList = searchRangerObjects(searchFilter, searchFields, sortFields, retList); + + for (T xTag : xTagList) { + V tag = populateViewBean(xTag); + + tagList.add(tag); + } + + retList.setList(tagList); + retList.setResultSize(tagList.size()); + retList.setPageSize(searchFilter.getMaxRows()); + retList.setStartIndex(searchFilter.getStartIndex()); + retList.setSortType(searchFilter.getSortType()); + retList.setSortBy(searchFilter.getSortBy()); + + return retList; + } + + @Override + protected T mapViewToEntityBean(V vObj, T xObj, int operationContext) { + String guid = (StringUtils.isEmpty(vObj.getGuid())) ? guidUtil.genGUID() : vObj.getGuid(); + + XXTagDef xTagDef = daoMgr.getXXTagDef().findByName(vObj.getType()); + if (xTagDef == null) { + throw restErrorUtil.createRESTException("No TagDefinition found with name :" + vObj.getType(), MessageEnums.INVALID_INPUT_DATA); + } + + xObj.setGuid(guid); + xObj.setType(xTagDef.getId()); + xObj.setOwner(vObj.getOwner()); + + String validityPeriods = JsonUtils.listToJson(vObj.getValidityPeriods()); + Map options = vObj.getOptions(); + + if (options == null) { + options = new HashMap<>(); + } + + if (StringUtils.isNotBlank(validityPeriods)) { + options.put(RangerTag.OPTION_TAG_VALIDITY_PERIODS, validityPeriods); + } else { + options.remove(RangerTag.OPTION_TAG_VALIDITY_PERIODS); + } + + xObj.setOptions(JsonUtils.mapToJson(options)); + + return xObj; + } + + @Override + protected V mapEntityToViewBean(V vObj, T xObj) { + XXTagDef xTagDef = daoMgr.getXXTagDef().getById(xObj.getType()); + + if (xTagDef == null) { + throw restErrorUtil.createRESTException("No TagDefinition found with name :" + xObj.getType(), MessageEnums.INVALID_INPUT_DATA); + } + + vObj.setGuid(xObj.getGuid()); + vObj.setType(xTagDef.getName()); + vObj.setOwner(xObj.getOwner()); + + Map options = JsonUtils.jsonToObject(xObj.getOptions(), Map.class); + + if (MapUtils.isNotEmpty(options)) { + String optionTagValidityPeriod = (String) options.remove(RangerTag.OPTION_TAG_VALIDITY_PERIODS); + + if (StringUtils.isNotBlank(optionTagValidityPeriod)) { + List validityPeriods = JsonUtils.jsonToRangerValiditySchedule(optionTagValidityPeriod); + + vObj.setValidityPeriods(validityPeriods); + } + } + + vObj.setOptions(options); + + Map attributes = getAttributesForTag(xObj); - @Autowired - GUIDUtil guidUtil; + vObj.setAttributes(attributes); - @Autowired - RangerAuditFields rangerAuditFields; - - @Autowired - RangerConfigUtil configUtil; - - @Override - protected T mapViewToEntityBean(V vObj, T xObj, int OPERATION_CONTEXT) { - String guid = (StringUtils.isEmpty(vObj.getGuid())) ? guidUtil.genGUID() : vObj.getGuid(); - - XXTagDef xTagDef = daoMgr.getXXTagDef().findByName(vObj.getType()); - if(xTagDef == null) { - throw restErrorUtil.createRESTException( - "No TagDefinition found with name :" + vObj.getType(), - MessageEnums.INVALID_INPUT_DATA); - } - - xObj.setGuid(guid); - xObj.setType(xTagDef.getId()); - xObj.setOwner(vObj.getOwner()); - - String validityPeriods = JsonUtils.listToJson(vObj.getValidityPeriods()); - Map options = vObj.getOptions(); - - if (options == null) { - options = new HashMap<>(); - } - - if (StringUtils.isNotBlank(validityPeriods)) { - options.put(RangerTag.OPTION_TAG_VALIDITY_PERIODS, validityPeriods); - } else { - options.remove(RangerTag.OPTION_TAG_VALIDITY_PERIODS); - } - - xObj.setOptions(JsonUtils.mapToJson(options)); - return xObj; - } - - @Override - protected V mapEntityToViewBean(V vObj, T xObj) { - XXTagDef xTagDef = daoMgr.getXXTagDef().getById(xObj.getType()); - if(xTagDef == null) { - throw restErrorUtil.createRESTException( - "No TagDefinition found with name :" + xObj.getType(), - MessageEnums.INVALID_INPUT_DATA); - } - - vObj.setGuid(xObj.getGuid()); - vObj.setType(xTagDef.getName()); - vObj.setOwner(xObj.getOwner()); - - Map options = JsonUtils.jsonToObject(xObj.getOptions(), Map.class); - - if (MapUtils.isNotEmpty(options)) { - String optionTagValidityPeriod = (String)options.remove(RangerTag.OPTION_TAG_VALIDITY_PERIODS); - - if (StringUtils.isNotBlank(optionTagValidityPeriod)) { - List validityPeriods = JsonUtils.jsonToRangerValiditySchedule(optionTagValidityPeriod); - - vObj.setValidityPeriods(validityPeriods); - } - } - - vObj.setOptions(options); - - Map attributes = getAttributesForTag(xObj); - vObj.setAttributes(attributes); - - return vObj; - } - - public Map getAttributesForTag(XXTag xtag) { - List tagAttrList = daoMgr.getXXTagAttribute().findByTagId(xtag.getId()); - Map ret = new HashMap(); - - if(CollectionUtils.isNotEmpty(tagAttrList)) { - for (XXTagAttribute tagAttr : tagAttrList) { - ret.put(tagAttr.getName(), tagAttr.getValue()); - } - } - - return ret; - } - - public PList searchRangerTags(SearchFilter searchFilter) { - PList retList = new PList(); - List tagList = new ArrayList(); - - List xTagList = searchRangerObjects(searchFilter, searchFields, sortFields, retList); - - for (T xTag : xTagList) { - V tag = populateViewBean(xTag); - tagList.add(tag); - } - - retList.setList(tagList); - retList.setResultSize(tagList.size()); - retList.setPageSize(searchFilter.getMaxRows()); - retList.setStartIndex(searchFilter.getStartIndex()); - retList.setSortType(searchFilter.getSortType()); - retList.setSortBy(searchFilter.getSortBy()); - return retList; - } + return vObj; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/service/RangerTransactionService.java b/security-admin/src/main/java/org/apache/ranger/service/RangerTransactionService.java index 0e7ae7daa1..b2c826ca5d 100644 --- a/security-admin/src/main/java/org/apache/ranger/service/RangerTransactionService.java +++ b/security-admin/src/main/java/org/apache/ranger/service/RangerTransactionService.java @@ -27,12 +27,11 @@ import org.springframework.stereotype.Service; 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 javax.annotation.PostConstruct; import javax.annotation.PreDestroy; + import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; @@ -42,19 +41,20 @@ @Service public class RangerTransactionService { + private static final Logger LOG = LoggerFactory.getLogger(RangerTransactionService.class); + private static final String PROP_THREADPOOL_SIZE = "ranger.admin.transaction.service.threadpool.size"; private static final String PROP_SUMMARY_LOG_INTERVAL_SEC = "ranger.admin.transaction.service.summary.log.interval.sec"; + private final AtomicLong scheduledTaskCount = new AtomicLong(0); + private final AtomicLong executedTaskCount = new AtomicLong(0); + private final AtomicLong failedTaskCount = new AtomicLong(0); + @Autowired @Qualifier(value = "transactionManager") PlatformTransactionManager txManager; - private static final Logger LOG = LoggerFactory.getLogger(RangerTransactionService.class); - - private ScheduledExecutorService scheduler = null; - private AtomicLong scheduledTaskCount = new AtomicLong(0); - private AtomicLong executedTaskCount = new AtomicLong(0); - private AtomicLong failedTaskCount = new AtomicLong(0); + private ScheduledExecutorService scheduler; private long summaryLogIntervalMs = 5 * 60 * 1000; private long nextLogSummaryTime = System.currentTimeMillis() + summaryLogIntervalMs; @@ -77,49 +77,46 @@ public void init() { public void destroy() { try { LOG.info("attempt to shutdown RangerTransactionService"); + scheduler.shutdown(); scheduler.awaitTermination(5, TimeUnit.SECONDS); logSummary(); - } - catch (InterruptedException e) { + } catch (InterruptedException e) { LOG.error("RangerTransactionService tasks interrupted"); - } - finally { + } finally { if (!scheduler.isTerminated()) { LOG.info("cancel non-finished RangerTransactionService tasks"); } + scheduler.shutdownNow(); + LOG.info("RangerTransactionService shutdown finished"); } } public void scheduleToExecuteInOwnTransaction(final Runnable task, final long delayInMillis) { try { - scheduler.schedule(new Runnable() { - @Override - public void run() { - if (task != null) { - try { - //Create new transaction - TransactionTemplate txTemplate = new TransactionTemplate(txManager); - txTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); - - txTemplate.execute(new TransactionCallback() { - public Object doInTransaction(TransactionStatus status) { - task.run(); - return null; - } - }); - } catch (Exception e) { - failedTaskCount.getAndIncrement(); - - LOG.error("Failed to commit TransactionService transaction", e); - LOG.error("Ignoring..."); - } finally { - executedTaskCount.getAndIncrement(); - logSummaryIfNeeded(); - } + scheduler.schedule(() -> { + if (task != null) { + try { + //Create new transaction + TransactionTemplate txTemplate = new TransactionTemplate(txManager); + + txTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + + txTemplate.execute(status -> { + task.run(); + return null; + }); + } catch (Exception e) { + failedTaskCount.getAndIncrement(); + + LOG.error("Failed to commit TransactionService transaction", e); + LOG.error("Ignoring..."); + } finally { + executedTaskCount.getAndIncrement(); + logSummaryIfNeeded(); } } }, delayInMillis, MILLISECONDS); @@ -129,7 +126,7 @@ public Object doInTransaction(TransactionStatus status) { logSummaryIfNeeded(); } catch (Exception e) { LOG.error("Failed to schedule TransactionService transaction:", e); - LOG.error("Ignroing..."); + LOG.error("Ignoring..."); } } @@ -155,4 +152,4 @@ private void logSummary() { LOG.info("RangerTransactionService: tasks(scheduled={}, executed={}, failed={}, pending={})", scheduled, executed, failed, pending); } -} \ No newline at end of file +} diff --git a/security-admin/src/main/java/org/apache/ranger/service/RangerTrxLogV2Service.java b/security-admin/src/main/java/org/apache/ranger/service/RangerTrxLogV2Service.java index 3eb2a707ea..46c59ef45e 100644 --- a/security-admin/src/main/java/org/apache/ranger/service/RangerTrxLogV2Service.java +++ b/security-admin/src/main/java/org/apache/ranger/service/RangerTrxLogV2Service.java @@ -17,15 +17,14 @@ * under the License. */ - package org.apache.ranger.service; - -/** - * - */ +package org.apache.ranger.service; import org.apache.commons.lang3.StringUtils; import org.apache.ranger.authorization.utils.StringUtil; -import org.apache.ranger.common.*; +import org.apache.ranger.common.RangerSearchUtil; +import org.apache.ranger.common.SearchCriteria; +import org.apache.ranger.common.SearchField; +import org.apache.ranger.common.SortField; import org.apache.ranger.db.RangerDaoManager; import org.apache.ranger.entity.XXPortalUser; import org.apache.ranger.entity.XXTrxLogV2; @@ -41,250 +40,247 @@ import javax.persistence.EntityManager; import javax.persistence.Query; -import java.util.*; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; import java.util.stream.Collectors; @Service @Scope("singleton") public class RangerTrxLogV2Service { - private static final Logger LOG = LoggerFactory.getLogger(RangerTrxLogV2Service.class); + private static final Logger LOG = LoggerFactory.getLogger(RangerTrxLogV2Service.class); + + private final List sortFields = new ArrayList<>(); + private final List searchFields = new ArrayList<>(); + + @Autowired + RangerSearchUtil searchUtil; + + @Autowired + RangerDaoManager daoManager; + + public RangerTrxLogV2Service() { + searchFields.add(new SearchField("attributeName", "obj.changeInfo", 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)); + searchFields.add(new SearchField("objectId", "obj.objectId", SearchField.DATA_TYPE.INT_LIST, SearchField.SEARCH_TYPE.FULL)); + + sortFields.add(new SortField("id", "obj.id", true, SortField.SORT_ORDER.DESC)); + sortFields.add(new SortField("createDate", "obj.createTime", true, SortField.SORT_ORDER.DESC)); + } + + public List getSearchFields() { + return searchFields; + } + + public List getSortFields() { + return sortFields; + } + + public PList searchTrxLogs(SearchCriteria searchCriteria) { + PList ret = new PList<>(); + List resultList = searchTrxLogs(searchCriteria, ret); + Map uidNameCache = new HashMap<>(); + List objList = resultList.stream().map(xTrxLog -> toViewObject(xTrxLog, uidNameCache)).collect(Collectors.toList()); + + ret.setList(objList); + + return ret; + } + + public long getTrxLogsCount(SearchCriteria searchCriteria) { + String countQueryStr = "SELECT COUNT(obj) FROM " + XXTrxLogV2.class.getName() + " obj "; + Query query = createQuery(countQueryStr, null, searchCriteria, searchFields, true); + Long count = daoManager.getXXTrxLogV2().executeCountQueryInSecurityContext(XXTrxLogV2.class, query); + + return count == null ? 0 : count; + } + + public List findByTransactionId(String transactionId) { + final List ret; + final List trxLogsV2 = daoManager.getXXTrxLogV2().findByTransactionId(transactionId); + + if (trxLogsV2 != null && !trxLogsV2.isEmpty()) { + Map uidNameCache = new HashMap<>(); + + ret = trxLogsV2.stream().map(xTrxLog -> toViewObject(xTrxLog, uidNameCache)).collect(Collectors.toList()); + } else { + ret = Collections.emptyList(); + } + + return ret; + } + + public VXTrxLogV2 createResource(VXTrxLogV2 trxLog) { + XXTrxLogV2 dbObj = trxLog != null ? toDBObject(trxLog) : null; + XXTrxLogV2 savedObj = dbObj != null ? daoManager.getXXTrxLogV2().create(dbObj) : null; + VXTrxLogV2 ret = savedObj != null ? toViewObject(savedObj, null) : null; + + LOG.debug("createResource({}): ret={}", trxLog, ret); + + return ret; + } + + public VXTrxLogV2 readResource(Long id) { + XXTrxLogV2 dbObj = id != null ? daoManager.getXXTrxLogV2().getById(id) : null; + VXTrxLogV2 ret = dbObj != null ? toViewObject(dbObj, null) : null; + + LOG.debug("readResource({}): ret={}", id, ret); + + return ret; + } + + public VXTrxLogV2 updateResource(VXTrxLogV2 trxLog) { + XXTrxLogV2 dbObj = trxLog != null ? toDBObject(trxLog) : null; + XXTrxLogV2 savedObj = dbObj != null ? daoManager.getXXTrxLogV2().update(dbObj) : null; + VXTrxLogV2 ret = savedObj != null ? toViewObject(savedObj, null) : null; - @Autowired - RangerSearchUtil searchUtil; + LOG.debug("updateResource({}): ret={}", trxLog, ret); - @Autowired - RangerDaoManager daoManager; + return ret; + } - private final List sortFields = new ArrayList<>(); - private final List searchFields = new ArrayList<>(); + public boolean deleteResource(Long id) { + boolean ret = id != null && daoManager.getXXTrxLogV2().remove(id); - public RangerTrxLogV2Service() { - searchFields.add(new SearchField("attributeName", "obj.changeInfo", 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)); - searchFields.add(new SearchField("objectId", "obj.objectId", SearchField.DATA_TYPE.INT_LIST, SearchField.SEARCH_TYPE.FULL)); + LOG.debug("deleteResource({}): ret={}", id, ret); - sortFields.add(new SortField("id", "obj.id", true, SortField.SORT_ORDER.DESC)); - sortFields.add(new SortField("createDate", "obj.createTime", true, SortField.SORT_ORDER.DESC)); - } + return ret; + } - public List getSearchFields() { - return searchFields; - } + private List searchTrxLogs(SearchCriteria searchCriteria, PList pList) { + // Get total count of the rows which meet the search criteria + long count = -1; - public List getSortFields() { - return sortFields; - } + if (searchCriteria.isGetCount()) { + count = getTrxLogsCount(searchCriteria); - public PList searchTrxLogs(SearchCriteria searchCriteria) { - PList ret = new PList<>(); - List resultList = searchTrxLogs(searchCriteria, ret); - Map uidNameCache = new HashMap<>(); - List objList = resultList.stream().map(xTrxLog -> toViewObject(xTrxLog, uidNameCache)).collect(Collectors.toList()); + if (count == 0) { + return Collections.emptyList(); + } + } - ret.setList(objList); + String sortClause = searchUtil.constructSortClause(searchCriteria, sortFields); + String queryStr = "SELECT obj FROM " + XXTrxLogV2.class.getName() + " obj "; + Query query = createQuery(queryStr, sortClause, searchCriteria, searchFields, false); - return ret; - } + List ret = daoManager.getXXTrxLogV2().executeQueryInSecurityContext(XXTrxLogV2.class, query); - public long getTrxLogsCount(SearchCriteria searchCriteria) { - String countQueryStr = "SELECT COUNT(obj) FROM " + XXTrxLogV2.class.getName() + " obj "; - Query query = createQuery(countQueryStr, null, searchCriteria, searchFields, true); - Long count = daoManager.getXXTrxLogV2().executeCountQueryInSecurityContext(XXTrxLogV2.class, query); + if (pList != null) { + pList.setResultSize(ret.size()); + pList.setPageSize(query.getMaxResults()); + pList.setSortBy(searchCriteria.getSortBy()); + pList.setSortType(searchCriteria.getSortType()); + pList.setStartIndex(query.getFirstResult()); + pList.setTotalCount(count); + } - return count == null ? 0 : count; - } + return ret; + } - public List findByTransactionId(String transactionId) { - final List ret; - final List trxLogsV2 = daoManager.getXXTrxLogV2().findByTransactionId(transactionId); + private Query createQuery(String searchString, String sortString, SearchCriteria searchCriteria, List searchFieldList, boolean isCountQuery) { + EntityManager em = daoManager.getEntityManager(); - if (trxLogsV2 != null && !trxLogsV2.isEmpty()) { - Map uidNameCache = new HashMap<>(); + return searchUtil.createSearchQuery(em, searchString, sortString, searchCriteria, searchFieldList, false, isCountQuery); + } - ret = trxLogsV2.stream().map(xTrxLog -> toViewObject(xTrxLog, uidNameCache)).collect(Collectors.toList()); - } else { - ret = Collections.emptyList(); - } + private XXTrxLogV2 toDBObject(VXTrxLogV2 vObj) { + XXTrxLogV2 ret = new XXTrxLogV2(vObj.getObjectClassType(), vObj.getObjectId(), vObj.getObjectName(), vObj.getParentObjectClassType(), vObj.getParentObjectId(), vObj.getParentObjectName(), vObj.getAction()); - return ret; - } + ret.setChangeInfo(toJson(vObj.getChangeInfo())); + ret.setTransactionId(vObj.getTransactionId()); + ret.setAction(vObj.getAction()); + ret.setSessionId(vObj.getSessionId()); + ret.setRequestId(vObj.getRequestId()); + ret.setSessionType(vObj.getSessionType()); - public VXTrxLogV2 createResource(VXTrxLogV2 trxLog) { - XXTrxLogV2 dbObj = trxLog != null ? toDBObject(trxLog) : null; - XXTrxLogV2 savedObj = dbObj != null ? daoManager.getXXTrxLogV2().create(dbObj) : null; - VXTrxLogV2 ret = savedObj != null ? toViewObject(savedObj, null) : null; - - if (LOG.isDebugEnabled()) { - LOG.debug("createResource(" + trxLog + "): ret=" + ret); - } - - return ret; - } - - public VXTrxLogV2 readResource(Long id) { - XXTrxLogV2 dbObj = id != null ? daoManager.getXXTrxLogV2().getById(id) : null; - VXTrxLogV2 ret = dbObj != null ? toViewObject(dbObj, null) : null; - - if (LOG.isDebugEnabled()) { - LOG.debug("readResource(" + id + "): ret=" + ret); - } - - return ret; - } - - public VXTrxLogV2 updateResource(VXTrxLogV2 trxLog) { - XXTrxLogV2 dbObj = trxLog != null ? toDBObject(trxLog) : null; - XXTrxLogV2 savedObj = dbObj != null ? daoManager.getXXTrxLogV2().update(dbObj) : null; - VXTrxLogV2 ret = savedObj != null ? toViewObject(savedObj, null) : null; - - if (LOG.isDebugEnabled()) { - LOG.debug("updateResource(" + trxLog + "): ret=" + ret); - } - - return ret; - } - - public boolean deleteResource(Long id) { - boolean ret = id != null && daoManager.getXXTrxLogV2().remove(id); - - if (LOG.isDebugEnabled()) { - LOG.debug("deleteResource(" + id + "): ret=" + ret); - } - - return ret; - } - - private List searchTrxLogs(SearchCriteria searchCriteria, PList pList) { - // Get total count of the rows which meet the search criteria - long count = -1; - - if (searchCriteria.isGetCount()) { - count = getTrxLogsCount(searchCriteria); + return ret; + } + + private VXTrxLogV2 toViewObject(XXTrxLogV2 dbObj, Map userIdNameCache) { + VXTrxLogV2 ret = new VXTrxLogV2(); - if (count == 0) { - return Collections.emptyList(); - } - } + ret.setId(dbObj.getId()); + ret.setCreateDate(dbObj.getCreateTime()); + ret.setCreatedBy(toUserName(dbObj.getAddedByUserId(), userIdNameCache)); + ret.setObjectClassType(dbObj.getObjectClassType()); + ret.setObjectId(dbObj.getObjectId()); + ret.setObjectName(dbObj.getObjectName()); + ret.setParentObjectClassType(dbObj.getParentObjectClassType()); + ret.setParentObjectId(dbObj.getParentObjectId()); + ret.setParentObjectName(dbObj.getParentObjectName()); + ret.setChangeInfo(toObjectChangeInfo(dbObj.getChangeInfo())); + ret.setTransactionId(dbObj.getTransactionId()); + ret.setAction(dbObj.getAction()); + ret.setSessionId(dbObj.getSessionId()); + ret.setRequestId(dbObj.getRequestId()); + ret.setSessionType(dbObj.getSessionType()); - String sortClause = searchUtil.constructSortClause(searchCriteria, sortFields); - String queryStr = "SELECT obj FROM " + XXTrxLogV2.class.getName() + " obj "; - Query query = createQuery(queryStr, sortClause, searchCriteria, searchFields, false); - - List ret = daoManager.getXXTrxLogV2().executeQueryInSecurityContext(XXTrxLogV2.class, query); - - if (pList != null) { - pList.setResultSize(ret.size()); - pList.setPageSize(query.getMaxResults()); - pList.setSortBy(searchCriteria.getSortBy()); - pList.setSortType(searchCriteria.getSortType()); - pList.setStartIndex(query.getFirstResult()); - pList.setTotalCount(count); - } - - return ret; - } - - private Query createQuery(String searchString, String sortString, SearchCriteria searchCriteria, List searchFieldList, boolean isCountQuery) { - EntityManager em = daoManager.getEntityManager(); - - return searchUtil.createSearchQuery(em, searchString, sortString, searchCriteria, searchFieldList, false, isCountQuery); - } - - private XXTrxLogV2 toDBObject(VXTrxLogV2 vObj) { - XXTrxLogV2 ret = new XXTrxLogV2(vObj.getObjectClassType(), vObj.getObjectId(), vObj.getObjectName(), vObj.getParentObjectClassType(), vObj.getParentObjectId(), vObj.getParentObjectName(), vObj.getAction()); - - ret.setChangeInfo(toJson(vObj.getChangeInfo())); - ret.setTransactionId(vObj.getTransactionId()); - ret.setAction(vObj.getAction()); - ret.setSessionId(vObj.getSessionId()); - ret.setRequestId(vObj.getRequestId()); - ret.setSessionType(vObj.getSessionType()); - - return ret; - } - - private VXTrxLogV2 toViewObject(XXTrxLogV2 dbObj, Map userIdNameCache) { - VXTrxLogV2 ret = new VXTrxLogV2(); - - ret.setId(dbObj.getId()); - ret.setCreateDate(dbObj.getCreateTime()); - ret.setCreatedBy(toUserName(dbObj.getAddedByUserId(), userIdNameCache)); - ret.setObjectClassType(dbObj.getObjectClassType()); - ret.setObjectId(dbObj.getObjectId()); - ret.setObjectName(dbObj.getObjectName()); - ret.setParentObjectClassType(dbObj.getParentObjectClassType()); - ret.setParentObjectId(dbObj.getParentObjectId()); - ret.setParentObjectName(dbObj.getParentObjectName()); - ret.setChangeInfo(toObjectChangeInfo(dbObj.getChangeInfo())); - ret.setTransactionId(dbObj.getTransactionId()); - ret.setAction(dbObj.getAction()); - ret.setSessionId(dbObj.getSessionId()); - ret.setRequestId(dbObj.getRequestId()); - ret.setSessionType(dbObj.getSessionType()); - - return ret; - } - - private String toJson(ObjectChangeInfo changeInfo) { - String ret = null; - - try { - ret = JsonUtilsV2.objToJson(changeInfo); - } catch (Exception excp) { - // ignore - } - - return ret; - } - - private ObjectChangeInfo toObjectChangeInfo(String json) { - ObjectChangeInfo ret = null; - - try { - ret = JsonUtilsV2.jsonToObj(json, ObjectChangeInfo.class); - } catch (Exception excp) { - // ignore - } - - return ret; - } - - private String toUserName(Long userId, Map userIdNameCache) { - String ret = null; - - if(userId != null) { - ret = userIdNameCache != null ? userIdNameCache.get(userId) : null; - - if(ret == null) { - XXPortalUser user = daoManager.getXXPortalUser().findById(userId); - - if(user != null) { - ret = user.getPublicScreenName(); - - if (StringUtil.isEmpty(ret)) { - ret = user.getFirstName(); - - if(StringUtil.isEmpty(ret)) { - ret = user.getLoginId(); - } else { - if(StringUtils.isNotEmpty(user.getLastName())) { - ret += (" " + user.getLastName()); - } - } - } - - if (ret != null && userIdNameCache != null) { - userIdNameCache.put(userId, ret); - } - } - } - } - - return ret; - } + return ret; + } + + private String toJson(ObjectChangeInfo changeInfo) { + String ret = null; + + try { + ret = JsonUtilsV2.objToJson(changeInfo); + } catch (Exception excp) { + // ignore + } + + return ret; + } + + private ObjectChangeInfo toObjectChangeInfo(String json) { + ObjectChangeInfo ret = null; + + try { + ret = JsonUtilsV2.jsonToObj(json, ObjectChangeInfo.class); + } catch (Exception excp) { + // ignore + } + + return ret; + } + + private String toUserName(Long userId, Map userIdNameCache) { + String ret = null; + + if (userId != null) { + ret = userIdNameCache != null ? userIdNameCache.get(userId) : null; + + if (ret == null) { + XXPortalUser user = daoManager.getXXPortalUser().findById(userId); + + if (user != null) { + ret = user.getPublicScreenName(); + + if (StringUtil.isEmpty(ret)) { + ret = user.getFirstName(); + + if (StringUtil.isEmpty(ret)) { + ret = user.getLoginId(); + } else { + if (StringUtils.isNotEmpty(user.getLastName())) { + ret += (" " + user.getLastName()); + } + } + } + + if (ret != null && userIdNameCache != null) { + userIdNameCache.put(userId, ret); + } + } + } + } + + return ret; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/service/UserService.java b/security-admin/src/main/java/org/apache/ranger/service/UserService.java index 6a0961795c..af78e17f69 100644 --- a/security-admin/src/main/java/org/apache/ranger/service/UserService.java +++ b/security-admin/src/main/java/org/apache/ranger/service/UserService.java @@ -17,12 +17,7 @@ * under the License. */ - package org.apache.ranger.service; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.List; +package org.apache.ranger.service; import org.apache.ranger.common.ContextUtil; import org.apache.ranger.common.MessageEnums; @@ -41,290 +36,275 @@ import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Service; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.List; + @Service @Scope("singleton") public class UserService extends UserServiceBase { - private static final Logger logger = LoggerFactory.getLogger(UserService.class); - - public static final String NAME = "User"; - - @Autowired - RangerConfigUtil configUtil; - - @Autowired - XUserPermissionService xUserPermissionService; - - 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 messageList = new ArrayList(); - 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.isEmpty()) { - 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 messageList = new ArrayList(); - - 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, - RangerConstants.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.isEmpty()) { - 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 collection) { - Collection newCollection = new ArrayList(); - for (String role : collection) { - String roles[] = role.split(","); + private static final Logger logger = LoggerFactory.getLogger(UserService.class); + + public static final String NAME = "User"; + + private static UserService instance; + + @Autowired + RangerConfigUtil configUtil; + + @Autowired + XUserPermissionService xUserPermissionService; + + public UserService() { + super(); + + instance = this; + } + + public static UserService getInstance() { + if (instance == null) { + logger.error("Instance is null", new Throwable()); + } + + return instance; + } + + // 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<>()); + + 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 gjUserRoleList = daoManager.getXXPortalUserRole().findByParentId(user.getId()); + + for (XXPortalUserRole gjUserRole : gjUserRoleList) { + userProfile.getUserRoleList().add(gjUserRole.getUserRole()); + } + } + + @Override + protected void validateForCreate(VXPortalUser userProfile) { + List messageList = new ArrayList<>(); + + 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.isEmpty()) { + VXResponse gjResponse = new VXResponse(); + + gjResponse.setStatusCode(VXResponse.STATUS_ERROR); + gjResponse.setMsgDesc("Validation failure"); + gjResponse.setMessageList(messageList); + + logger.info("Validation Error in createUser() userProfile={}, error={}", userProfile, gjResponse); + + throw restErrorUtil.createRESTException(gjResponse); + } + } + + @Override + protected void validateForUpdate(VXPortalUser userProfile, XXPortalUser xXPortalUser) { + List messageList = new ArrayList<>(); + + 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, RangerConstants.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.isEmpty()) { + VXResponse gjResponse = new VXResponse(); + + gjResponse.setStatusCode(VXResponse.STATUS_ERROR); + gjResponse.setMsgDesc("Validation failure"); + gjResponse.setMessageList(messageList); + + logger.info("Validation Error in updateUser() userProfile={}, error={}", userProfile, gjResponse); + + throw restErrorUtil.createRESTException(gjResponse); + } + } + + @Override + protected XXPortalUser mapViewToEntityBean(VXPortalUser userProfile, XXPortalUser mObj, int operationContext) { + 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 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 gjUserRoleList = daoManager.getXXPortalUserRole().findByParentId(user.getId()); + + for (XXPortalUserRole gjUserRole : gjUserRoleList) { + userProfile.getUserRoleList().add(gjUserRole.getUserRole()); + } + + return userProfile; + } + + void splitUserRoleList(Collection collection) { + Collection newCollection = new ArrayList<>(); + + for (String role : collection) { + String[] roles = role.split(","); + newCollection.addAll(Arrays.asList(roles)); - } - 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 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 gjUserRoleList = daoManager.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()); - 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 gjUserRoleList = daoManager.getXXPortalUserRole().findByParentId( - user.getId()); - - for (XXPortalUserRole gjUserRole : gjUserRoleList) { - userProfile.getUserRoleList().add(gjUserRole.getUserRole()); - } - } + } + collection.clear(); + collection.addAll(newCollection); + } } diff --git a/security-admin/src/main/java/org/apache/ranger/service/UserServiceBase.java b/security-admin/src/main/java/org/apache/ranger/service/UserServiceBase.java index 597b5c2c48..e09b8d3c87 100644 --- a/security-admin/src/main/java/org/apache/ranger/service/UserServiceBase.java +++ b/security-admin/src/main/java/org/apache/ranger/service/UserServiceBase.java @@ -17,53 +17,50 @@ * under the License. */ - package org.apache.ranger.service; - -import java.util.ArrayList; -import java.util.List; +package org.apache.ranger.service; import org.apache.ranger.common.SearchCriteria; import org.apache.ranger.entity.XXPortalUser; import org.apache.ranger.view.VXPortalUser; import org.apache.ranger.view.VXPortalUserList; -public abstract class UserServiceBase - extends AbstractBaseResourceService { - public static final String NAME = "User"; +import java.util.ArrayList; +import java.util.List; - public UserServiceBase() { +public abstract class UserServiceBase extends AbstractBaseResourceService { + public static final String NAME = "User"; - } + public UserServiceBase() { + } - @Override - protected T mapViewToEntityBean(V vObj, T mObj, int OPERATION_CONTEXT) { - return mObj; - } + /** + * @param searchCriteria + * @return + */ + public VXPortalUserList searchUsers(SearchCriteria searchCriteria) { + VXPortalUserList returnList = new VXPortalUserList(); + List userList = new ArrayList<>(); + List resultList = searchResources(searchCriteria, searchFields, sortFields, returnList); - @Override - protected V mapEntityToViewBean(V vObj, T mObj) { - return vObj; - } + // Iterate over the result list and create the return list + for (T gjUser : resultList) { + VXPortalUser vUser = populateViewBean(gjUser); - /** - * @param searchCriteria - * @return - */ - public VXPortalUserList searchUsers(SearchCriteria searchCriteria) { - VXPortalUserList returnList = new VXPortalUserList(); - List userList = new ArrayList(); + userList.add(vUser); + } - List resultList = searchResources(searchCriteria, - searchFields, sortFields, returnList); + returnList.setVXPortalUsers(userList); - // Iterate over the result list and create the return list - for (T gjUser : resultList) { - VXPortalUser vUser = populateViewBean(gjUser); - userList.add(vUser); - } + return returnList; + } - returnList.setVXPortalUsers(userList); - return returnList; - } + @Override + protected T mapViewToEntityBean(V vObj, T mObj, int operationContext) { + return mObj; + } + @Override + protected V mapEntityToViewBean(V vObj, T mObj) { + return vObj; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/service/XAccessAuditService.java b/security-admin/src/main/java/org/apache/ranger/service/XAccessAuditService.java index 4cc9e0a041..f21d6749b2 100644 --- a/security-admin/src/main/java/org/apache/ranger/service/XAccessAuditService.java +++ b/security-admin/src/main/java/org/apache/ranger/service/XAccessAuditService.java @@ -17,11 +17,7 @@ * under the License. */ - package org.apache.ranger.service; - -import java.io.UnsupportedEncodingException; -import java.util.ArrayList; -import java.util.List; +package org.apache.ranger.service; import org.apache.commons.lang.StringUtils; import org.apache.ranger.authorization.hadoop.constants.RangerHadoopConstants; @@ -40,260 +36,167 @@ import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Service; +import java.io.UnsupportedEncodingException; +import java.util.ArrayList; +import java.util.List; + @Service @Scope("singleton") -public class XAccessAuditService extends XAccessAuditServiceBase{ - - public static final String NAME = "XAccessAudit"; - - public XAccessAuditService() { - 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)); - searchFields.add(new SearchField("tags", "obj.tags", DATA_TYPE.STRING, SEARCH_TYPE.PARTIAL)); - searchFields.add(new SearchField("cluster", "obj.cluster", - SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.FULL)); - searchFields.add(new SearchField("zoneName", "obj.zoneName", - SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.FULL)); - searchFields.add(new SearchField("agentHost", "obj.agentHost", - SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.PARTIAL)); - - sortFields.add(new SortField("eventTime", "obj.evtTime", true, SORT_ORDER.DESC)); - sortFields.add(new SortField("policyId", "obj.policy", false, SORT_ORDER.ASC)); - sortFields.add(new SortField("requestUser", "obj.reqUser", false, SORT_ORDER.ASC)); - sortFields.add(new SortField("resourceType", "obj.resType", false, SORT_ORDER.ASC)); - sortFields.add(new SortField("accessType", "obj.access", false, SORT_ORDER.ASC)); - sortFields.add(new SortField("action", "obj.action", false, SORT_ORDER.ASC)); - sortFields.add(new SortField("aclEnforcer", "obj.enforcer", false, SORT_ORDER.ASC)); - sortFields.add(new SortField("zoneName", "obj.zoneName", false, SORT_ORDER.ASC)); - sortFields.add(new SortField("clientIP", "obj.cliIP", false, SORT_ORDER.ASC)); -} - - 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()); - mObj.setSequenceNumber( vObj.getSequenceNumber()); - mObj.setEventCount( vObj.getEventCount()); - mObj.setEventDuration( vObj.getEventDuration()); - mObj.setTags(vObj.getTags()); - 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()); - vObj.setSequenceNumber( mObj.getSequenceNumber()); - vObj.setEventCount( mObj.getEventCount()); - vObj.setEventDuration( mObj.getEventDuration()); - vObj.setTags(mObj.getTags()); - - XXService xService = daoManager.getXXService().findByName(mObj.getRepoName()); - if (xService != null) { - vObj.setRepoDisplayName(xService.getDisplayName()); - XXServiceDef xServiceDef = daoManager.getXXServiceDef().getById(xService.getType()); - - if (xServiceDef != null) { - vObj.setServiceType(xServiceDef.getName()); - vObj.setServiceTypeDisplayName(xServiceDef.getDisplayName()); - } - } - - return vObj; - } +public class XAccessAuditService extends XAccessAuditServiceBase { + public static final String NAME = "XAccessAudit"; + + public XAccessAuditService() { + 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)); + searchFields.add(new SearchField("tags", "obj.tags", DATA_TYPE.STRING, SEARCH_TYPE.PARTIAL)); + searchFields.add(new SearchField("cluster", "obj.cluster", SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.FULL)); + searchFields.add(new SearchField("zoneName", "obj.zoneName", SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.FULL)); + searchFields.add(new SearchField("agentHost", "obj.agentHost", SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.PARTIAL)); + + sortFields.add(new SortField("eventTime", "obj.evtTime", true, SORT_ORDER.DESC)); + sortFields.add(new SortField("policyId", "obj.policy", false, SORT_ORDER.ASC)); + sortFields.add(new SortField("requestUser", "obj.reqUser", false, SORT_ORDER.ASC)); + sortFields.add(new SortField("resourceType", "obj.resType", false, SORT_ORDER.ASC)); + sortFields.add(new SortField("accessType", "obj.access", false, SORT_ORDER.ASC)); + sortFields.add(new SortField("action", "obj.action", false, SORT_ORDER.ASC)); + sortFields.add(new SortField("aclEnforcer", "obj.enforcer", false, SORT_ORDER.ASC)); + sortFields.add(new SortField("zoneName", "obj.zoneName", false, SORT_ORDER.ASC)); + sortFields.add(new SortField("clientIP", "obj.cliIP", false, SORT_ORDER.ASC)); + } - /** - * @param searchCriteria - * @return - */ - public VXAccessAuditList searchXAccessAudits(SearchCriteria searchCriteria) { - VXAccessAuditList returnList = new VXAccessAuditList(); - List xAccessAuditList = new ArrayList(); + /** + * @param searchCriteria + * @return + */ + public VXAccessAuditList searchXAccessAudits(SearchCriteria searchCriteria) { + VXAccessAuditList returnList = new VXAccessAuditList(); + List xAccessAuditList = new ArrayList<>(); + List resultList = searchResources(searchCriteria, searchFields, sortFields, returnList); + final boolean hiveQueryVisibility = PropertiesUtil.getBooleanProperty("ranger.audit.hive.query.visibility", true); - List resultList = (List) searchResources(searchCriteria, - searchFields, sortFields, returnList); - final boolean hiveQueryVisibility = PropertiesUtil.getBooleanProperty("ranger.audit.hive.query.visibility", true); // Iterate over the result list and create the return list for (XXAccessAudit gjXAccessAudit : resultList) { VXAccessAudit vXAccessAudit = populateViewBean(gjXAccessAudit); - if(vXAccessAudit != null) { - if(StringUtils.equalsIgnoreCase(vXAccessAudit.getAclEnforcer(), RangerHadoopConstants.DEFAULT_XASECURE_MODULE_ACL_NAME)) { + if (vXAccessAudit != null) { + if (StringUtils.equalsIgnoreCase(vXAccessAudit.getAclEnforcer(), RangerHadoopConstants.DEFAULT_XASECURE_MODULE_ACL_NAME)) { vXAccessAudit.setAclEnforcer(RangerHadoopConstants.DEFAULT_RANGER_MODULE_ACL_NAME); } - if (!hiveQueryVisibility && "hive".equalsIgnoreCase(vXAccessAudit.getServiceType())) { - vXAccessAudit.setRequestData(null); - } - else if("hive".equalsIgnoreCase(vXAccessAudit.getServiceType()) && ("grant".equalsIgnoreCase(vXAccessAudit.getAccessType()) || "revoke".equalsIgnoreCase(vXAccessAudit.getAccessType()))){ - try { - vXAccessAudit.setRequestData(java.net.URLDecoder.decode(vXAccessAudit.getRequestData(), "UTF-8")); - } catch (UnsupportedEncodingException e) { - logger.warn("Error while encoding request data"); - } - } + + if (!hiveQueryVisibility && "hive".equalsIgnoreCase(vXAccessAudit.getServiceType())) { + vXAccessAudit.setRequestData(null); + } else if ("hive".equalsIgnoreCase(vXAccessAudit.getServiceType()) && ("grant".equalsIgnoreCase(vXAccessAudit.getAccessType()) || "revoke".equalsIgnoreCase(vXAccessAudit.getAccessType()))) { + try { + vXAccessAudit.setRequestData(java.net.URLDecoder.decode(vXAccessAudit.getRequestData(), "UTF-8")); + } catch (UnsupportedEncodingException e) { + logger.warn("Error while encoding request data"); + } + } + xAccessAuditList.add(vXAccessAudit); } } - returnList.setVXAccessAudits(xAccessAuditList); + return returnList; } - - public VXAccessAudit populateViewBean(XXAccessAudit gjXAccessAudit) { - VXAccessAudit vXAccessAudit = new VXAccessAudit(); - return mapEntityToViewBean(vXAccessAudit, gjXAccessAudit); - } - /* - protected List searchResources(SearchCriteria searchCriteria, - List searchFieldList, List 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 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 searchFieldList) { - long count = getCountForSearchQuery(searchCriteria, searchFieldList); + protected XXAccessAudit mapViewToEntityBean(VXAccessAudit vObj, XXAccessAudit mObj, int operationContext) { + 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()); + mObj.setSequenceNumber(vObj.getSequenceNumber()); + mObj.setEventCount(vObj.getEventCount()); + mObj.setEventDuration(vObj.getEventDuration()); + mObj.setTags(vObj.getTags()); + + return mObj; + } - VXLong vXLong = new VXLong(); - vXLong.setValue(count); - return vXLong; - } + 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()); + vObj.setSequenceNumber(mObj.getSequenceNumber()); + vObj.setEventCount(mObj.getEventCount()); + vObj.setEventDuration(mObj.getEventDuration()); + vObj.setTags(mObj.getTags()); + + XXService xService = daoManager.getXXService().findByName(mObj.getRepoName()); + + if (xService != null) { + vObj.setRepoDisplayName(xService.getDisplayName()); + + XXServiceDef xServiceDef = daoManager.getXXServiceDef().getById(xService.getType()); + + if (xServiceDef != null) { + vObj.setServiceType(xServiceDef.getName()); + vObj.setServiceTypeDisplayName(xServiceDef.getDisplayName()); + } + } - protected long getCountForSearchQuery(SearchCriteria searchCriteria, - List searchFieldList) { + return vObj; + } - 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); + public VXAccessAudit populateViewBean(XXAccessAudit gjXAccessAudit) { + VXAccessAudit vXAccessAudit = new VXAccessAudit(); - // 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(); - } + return mapEntityToViewBean(vXAccessAudit, gjXAccessAudit); + } -// protected Query createQuery(String searchString, String sortString, -// SearchCriteria searchCriteria, List 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 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 + @Override + protected void validateForUpdate(VXAccessAudit viewBaseBean, XXAccessAudit t) { + // TODO Auto-generated method stub + } +} diff --git a/security-admin/src/main/java/org/apache/ranger/service/XAccessAuditServiceBase.java b/security-admin/src/main/java/org/apache/ranger/service/XAccessAuditServiceBase.java index 6dfa8c3d1b..494d9204b0 100644 --- a/security-admin/src/main/java/org/apache/ranger/service/XAccessAuditServiceBase.java +++ b/security-admin/src/main/java/org/apache/ranger/service/XAccessAuditServiceBase.java @@ -17,99 +17,94 @@ * under the License. */ - package org.apache.ranger.service; - -/** - * - */ - -import java.util.ArrayList; -import java.util.List; +package org.apache.ranger.service; import org.apache.ranger.common.SearchCriteria; import org.apache.ranger.entity.XXAccessAudit; import org.apache.ranger.view.VXAccessAudit; import org.apache.ranger.view.VXAccessAuditList; -public abstract class XAccessAuditServiceBase - extends AbstractBaseResourceService { - public static final String NAME = "XAccessAudit"; +import java.util.ArrayList; +import java.util.List; + +public abstract class XAccessAuditServiceBase extends AbstractBaseResourceService { + public static final String NAME = "XAccessAudit"; + + public XAccessAuditServiceBase() { + } - public XAccessAuditServiceBase() { + /** + * @param searchCriteria + * @return + */ + public VXAccessAuditList searchXAccessAudits(SearchCriteria searchCriteria) { + VXAccessAuditList returnList = new VXAccessAuditList(); + List xAccessAuditList = new ArrayList<>(); + List resultList = searchResources(searchCriteria, searchFields, sortFields, returnList); - } + // Iterate over the result list and create the return list + for (T gjXAccessAudit : resultList) { + VXAccessAudit vXAccessAudit = populateViewBean(gjXAccessAudit); - @Override - protected T mapViewToEntityBean(V vObj, T 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()); - mObj.setSequenceNumber( vObj.getSequenceNumber()); - mObj.setEventCount( vObj.getEventCount()); - mObj.setEventDuration( vObj.getEventDuration()); - return mObj; - } + xAccessAuditList.add(vXAccessAudit); + } - @Override - protected V mapEntityToViewBean(V vObj, T 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()); - vObj.setSequenceNumber( mObj.getSequenceNumber()); - vObj.setEventCount( mObj.getEventCount()); - vObj.setEventDuration( mObj.getEventDuration()); - return vObj; - } + returnList.setVXAccessAudits(xAccessAuditList); - /** - * @param searchCriteria - * @return - */ - public VXAccessAuditList searchXAccessAudits(SearchCriteria searchCriteria) { - VXAccessAuditList returnList = new VXAccessAuditList(); - List xAccessAuditList = new ArrayList(); + return returnList; + } - List resultList = searchResources(searchCriteria, - searchFields, sortFields, returnList); + @Override + protected T mapViewToEntityBean(V vObj, T mObj, int operationContext) { + 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()); + mObj.setSequenceNumber(vObj.getSequenceNumber()); + mObj.setEventCount(vObj.getEventCount()); + mObj.setEventDuration(vObj.getEventDuration()); - // Iterate over the result list and create the return list - for (T gjXAccessAudit : resultList) { - VXAccessAudit vXAccessAudit = populateViewBean(gjXAccessAudit); - xAccessAuditList.add(vXAccessAudit); - } + return mObj; + } - returnList.setVXAccessAudits(xAccessAuditList); - return returnList; - } + @Override + protected V mapEntityToViewBean(V vObj, T 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()); + vObj.setSequenceNumber(mObj.getSequenceNumber()); + vObj.setEventCount(mObj.getEventCount()); + vObj.setEventDuration(mObj.getEventDuration()); + return vObj; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/service/XAssetService.java b/security-admin/src/main/java/org/apache/ranger/service/XAssetService.java index e977954bfe..d14462aaca 100644 --- a/security-admin/src/main/java/org/apache/ranger/service/XAssetService.java +++ b/security-admin/src/main/java/org/apache/ranger/service/XAssetService.java @@ -17,234 +17,231 @@ * under the License. */ - package org.apache.ranger.service; - -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; -import java.util.Map.Entry; +package org.apache.ranger.service; +import com.fasterxml.jackson.core.type.TypeReference; import org.apache.ranger.common.AppConstants; import org.apache.ranger.common.MessageEnums; -import org.apache.ranger.plugin.util.JsonUtilsV2; -import org.apache.ranger.plugin.util.PasswordUtils; import org.apache.ranger.common.SearchField; import org.apache.ranger.common.SearchField.DATA_TYPE; import org.apache.ranger.common.SearchField.SEARCH_TYPE; import org.apache.ranger.entity.XXAsset; +import org.apache.ranger.plugin.util.JsonUtilsV2; +import org.apache.ranger.plugin.util.PasswordUtils; import org.apache.ranger.view.VXAsset; -import com.fasterxml.jackson.core.type.TypeReference; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Service; +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; +import java.util.Map.Entry; + @Service @Scope("singleton") public class XAssetService extends XAssetServiceBase { + public XAssetService() { + super(); + + 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)); + } + + public void validateConfig(VXAsset vObj) { + HashMap configrationMap = null; + + if (vObj.getAssetType() == AppConstants.ASSET_HDFS) { + TypeReference> typeRef = new TypeReference>() {}; + + try { + configrationMap = JsonUtilsV2.getMapper().readValue(vObj.getConfig(), typeRef); + } catch (Exception e) { + logger.error("Error in config json", e); + } + + if (configrationMap != null) { + String fsDefaultName = configrationMap.get("fs.default.name").toString(); + + if (fsDefaultName.isEmpty()) { + throw restErrorUtil.createRESTException("serverMsg.fsDefaultNameEmptyError", MessageEnums.INVALID_INPUT_DATA, null, "fs.default.name", vObj.toString()); + } + } + } + } + + public String getConfigWithEncryptedPassword(String config, boolean isForced) { + try { + if (config != null && !config.isEmpty()) { + Map configMap = jsonUtil.jsonToMap(config); + Entry passwordEntry = getPasswordEntry(configMap); + Entry isEncryptedEntry = getIsEncryptedEntry(configMap); + + if (passwordEntry != null) { + if (isEncryptedEntry == null || !"true".equalsIgnoreCase(isEncryptedEntry.getValue()) || isForced) { + String password = passwordEntry.getValue(); + String encryptPassword = PasswordUtils.encryptPassword(password); + String decryptPassword = PasswordUtils.decryptPassword(encryptPassword); + + if (decryptPassword != null && 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 configMap = jsonUtil.jsonToMap(config); + Entry passwordEntry = getPasswordEntry(configMap); + Entry isEncryptedEntry = getIsEncryptedEntry(configMap); + + if (isEncryptedEntry != null && passwordEntry != null) { + if (!stringUtil.isEmpty(isEncryptedEntry.getValue()) && "true".equalsIgnoreCase(isEncryptedEntry.getValue())) { + 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; + } + + @Override + protected void validateForCreate(VXAsset vObj) { + XXAsset xxAsset = daoManager.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().isEmpty()) { + 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 operationContext) { + XXAsset ret = null; - public XAssetService(){ - super(); - 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 = daoManager.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) { - XXAsset ret = null; if (vObj != null && mObj != null) { String oldConfig = mObj.getConfig(); - ret = super.mapViewToEntityBean(vObj, mObj, OPERATION_CONTEXT); + + ret = super.mapViewToEntityBean(vObj, mObj, operationContext); + String config = ret.getConfig(); + if (config != null && !config.isEmpty()) { - Map configMap = jsonUtil.jsonToMap(config); + Map configMap = jsonUtil.jsonToMap(config); Entry 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 oldConfigMap = jsonUtil - .jsonToMap(oldConfig); - Entry oldPasswordEntry - = getPasswordEntry(oldConfigMap); + Map oldConfigMap = jsonUtil.jsonToMap(oldConfig); + Entry oldPasswordEntry = getPasswordEntry(oldConfigMap); + if (oldPasswordEntry != null) { - configMap.put(oldPasswordEntry.getKey(), - oldPasswordEntry.getValue()); + configMap.put(oldPasswordEntry.getKey(), oldPasswordEntry.getValue()); } } } + config = jsonUtil.readMapToString(configMap); } } } + ret.setConfig(config); } - return ret; - } - - @Override - protected VXAsset mapEntityToViewBean(VXAsset vObj, XXAsset mObj) { - VXAsset ret = super.mapEntityToViewBean(vObj, mObj); - String config = ret.getConfig(); - if (config != null && !config.isEmpty()) { - Map configMap = jsonUtil.jsonToMap(config); - Entry passwordEntry = getPasswordEntry(configMap); - if (passwordEntry != null) { - configMap.put(passwordEntry.getKey(), hiddenPasswordString); - } - config = jsonUtil.readMapToString(configMap); - } - ret.setConfig(config); - return ret; - } - - private Entry getPasswordEntry(Map configMap) { - Entry entry = null; - - for(Entry e : configMap.entrySet()) { - if(e.getKey().toLowerCase().contains("password")){ - entry = e; - break; - } - } - - return entry; - } - - private Entry getIsEncryptedEntry(Map configMap){ - Entry entry = null; - for(Entry e : configMap.entrySet()) { - if(e.getKey().toLowerCase().contains("isencrypted")){ - entry = e; - break; - } - } - return entry; - } - - public void validateConfig(VXAsset vObj) { - HashMap configrationMap = null; - if (vObj.getAssetType() == AppConstants.ASSET_HDFS) { - TypeReference> typeRef = new TypeReference - >() {}; - try { - configrationMap = JsonUtilsV2.getMapper().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 String getConfigWithEncryptedPassword(String config,boolean isForced){ - try { - if (config != null && !config.isEmpty()) { - Map configMap = jsonUtil.jsonToMap(config); - Entry passwordEntry = getPasswordEntry(configMap); - Entry isEncryptedEntry = getIsEncryptedEntry(configMap); - if (passwordEntry != null){ - if(isEncryptedEntry==null || !"true".equalsIgnoreCase(isEncryptedEntry.getValue())||isForced==true){ - String password=passwordEntry.getValue(); - String encryptPassword=PasswordUtils.encryptPassword(password); - String decryptPassword=PasswordUtils.decryptPassword(encryptPassword); - if(decryptPassword != null && 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 configMap = jsonUtil.jsonToMap(config); - Entry passwordEntry = getPasswordEntry(configMap); - Entry isEncryptedEntry = getIsEncryptedEntry(configMap); - if (isEncryptedEntry!=null && passwordEntry != null){ - if (!stringUtil.isEmpty(isEncryptedEntry.getValue()) - && "true".equalsIgnoreCase(isEncryptedEntry.getValue())) { - 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; - } + + return ret; + } + + @Override + protected VXAsset mapEntityToViewBean(VXAsset vObj, XXAsset mObj) { + VXAsset ret = super.mapEntityToViewBean(vObj, mObj); + String config = ret.getConfig(); + + if (config != null && !config.isEmpty()) { + Map configMap = jsonUtil.jsonToMap(config); + Entry passwordEntry = getPasswordEntry(configMap); + + if (passwordEntry != null) { + configMap.put(passwordEntry.getKey(), hiddenPasswordString); + } + + config = jsonUtil.readMapToString(configMap); + } + + ret.setConfig(config); + + return ret; + } + + private Entry getPasswordEntry(Map configMap) { + Entry entry = null; + + for (Entry e : configMap.entrySet()) { + if (e.getKey().toLowerCase().contains("password")) { + entry = e; + break; + } + } + + return entry; + } + + private Entry getIsEncryptedEntry(Map configMap) { + Entry entry = null; + + for (Entry e : configMap.entrySet()) { + if (e.getKey().toLowerCase().contains("isencrypted")) { + entry = e; + break; + } + } + + return entry; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/service/XAssetServiceBase.java b/security-admin/src/main/java/org/apache/ranger/service/XAssetServiceBase.java index 12f2a2bad6..6b0ddf4042 100644 --- a/security-admin/src/main/java/org/apache/ranger/service/XAssetServiceBase.java +++ b/security-admin/src/main/java/org/apache/ranger/service/XAssetServiceBase.java @@ -17,14 +17,7 @@ * under the License. */ - package org.apache.ranger.service; - -/** - * - */ - -import java.util.ArrayList; -import java.util.List; +package org.apache.ranger.service; import org.apache.ranger.common.AppConstants; import org.apache.ranger.common.SearchCriteria; @@ -33,60 +26,64 @@ import org.apache.ranger.view.VXAsset; import org.apache.ranger.view.VXAssetList; -public abstract class XAssetServiceBase - extends AbstractAuditedResourceService { - public static final String NAME = "XAsset"; - - public XAssetServiceBase() { - super(AppConstants.CLASS_TYPE_XA_SERVICE, AppConstants.CLASS_TYPE_XA_SERVICE_DEF); - - trxLogAttrs.put("name", new VTrxLogAttr("name", "Repository Name", false, true)); - trxLogAttrs.put("description", new VTrxLogAttr("description", "Repository Description")); - trxLogAttrs.put("activeStatus", new VTrxLogAttr("activeStatus", "Repository Status", true)); - trxLogAttrs.put("config", new VTrxLogAttr("config", "Connection Configurations")); - } - - @Override - protected T mapViewToEntityBean(V vObj, T 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; - } - - @Override - protected V mapEntityToViewBean(V vObj, T 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 xAssetList = new ArrayList(); - - List resultList = searchResources(searchCriteria, - searchFields, sortFields, returnList); - - // Iterate over the result list and create the return list - for (T gjXAsset : resultList) { - VXAsset vXAsset = populateViewBean(gjXAsset); - xAssetList.add(vXAsset); - } - - returnList.setVXAssets(xAssetList); - return returnList; - } +import java.util.ArrayList; +import java.util.List; + +public abstract class XAssetServiceBase extends AbstractAuditedResourceService { + public static final String NAME = "XAsset"; + + public XAssetServiceBase() { + super(AppConstants.CLASS_TYPE_XA_SERVICE, AppConstants.CLASS_TYPE_XA_SERVICE_DEF); + + trxLogAttrs.put("name", new VTrxLogAttr("name", "Repository Name", false, true)); + trxLogAttrs.put("description", new VTrxLogAttr("description", "Repository Description")); + trxLogAttrs.put("activeStatus", new VTrxLogAttr("activeStatus", "Repository Status", true)); + trxLogAttrs.put("config", new VTrxLogAttr("config", "Connection Configurations")); + } + + /** + * @param searchCriteria + * @return + */ + public VXAssetList searchXAssets(SearchCriteria searchCriteria) { + VXAssetList returnList = new VXAssetList(); + List xAssetList = new ArrayList<>(); + + List resultList = searchResources(searchCriteria, searchFields, sortFields, returnList); + + // Iterate over the result list and create the return list + for (T gjXAsset : resultList) { + VXAsset vXAsset = populateViewBean(gjXAsset); + + xAssetList.add(vXAsset); + } + + returnList.setVXAssets(xAssetList); + + return returnList; + } + + @Override + protected T mapViewToEntityBean(V vObj, T mObj, int operationContext) { + 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; + } + + @Override + protected V mapEntityToViewBean(V vObj, T 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; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/service/XAuditMapService.java b/security-admin/src/main/java/org/apache/ranger/service/XAuditMapService.java index 2ca887840f..5724807ab7 100644 --- a/security-admin/src/main/java/org/apache/ranger/service/XAuditMapService.java +++ b/security-admin/src/main/java/org/apache/ranger/service/XAuditMapService.java @@ -17,8 +17,7 @@ * under the License. */ - package org.apache.ranger.service; - +package org.apache.ranger.service; import org.apache.ranger.common.SearchField; import org.apache.ranger.entity.XXAuditMap; @@ -30,74 +29,77 @@ @Service @Scope("singleton") public class XAuditMapService extends XAuditMapServiceBase { + public XAuditMapService() { + searchFields.add(new SearchField("resourceId", "obj.resourceId", 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(VXAuditMap vObj) { + // TODO Auto-generated method stub + } + + @Override + protected void validateForUpdate(VXAuditMap vObj, XXAuditMap mObj) { + // TODO Auto-generated method stub + } + + @Override + protected XXAuditMap mapViewToEntityBean(VXAuditMap vObj, XXAuditMap mObj, int operationContext) { + XXAuditMap ret = null; + + if (vObj != null && mObj != null) { + ret = super.mapViewToEntityBean(vObj, mObj, operationContext); + + if (ret.getAddedByUserId() == null || ret.getAddedByUserId() == 0) { + if (!stringUtil.isEmpty(vObj.getOwner())) { + XXPortalUser xXPortalUser = daoManager.getXXPortalUser().findByLoginId(vObj.getOwner()); + + if (xXPortalUser != null) { + ret.setAddedByUserId(xXPortalUser.getId()); + } + } + } + + if (ret.getUpdatedByUserId() == null || ret.getUpdatedByUserId() == 0) { + if (!stringUtil.isEmpty(vObj.getUpdatedBy())) { + XXPortalUser xXPortalUser = daoManager.getXXPortalUser().findByLoginId(vObj.getUpdatedBy()); + + if (xXPortalUser != null) { + ret.setUpdatedByUserId(xXPortalUser.getId()); + } + } + } + } + + return ret; + } + + @Override + protected VXAuditMap mapEntityToViewBean(VXAuditMap vObj, XXAuditMap mObj) { + VXAuditMap ret = null; + + if (mObj != null && vObj != null) { + ret = super.mapEntityToViewBean(vObj, mObj); + + if (stringUtil.isEmpty(ret.getOwner())) { + XXPortalUser xXPortalUser = daoManager.getXXPortalUser().getById(mObj.getAddedByUserId()); + + if (xXPortalUser != null) { + ret.setOwner(xXPortalUser.getLoginId()); + } + } + + if (stringUtil.isEmpty(ret.getUpdatedBy())) { + XXPortalUser xXPortalUser = daoManager.getXXPortalUser().getById(mObj.getUpdatedByUserId()); - public XAuditMapService() { - searchFields.add(new SearchField("resourceId", "obj.resourceId", - 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(VXAuditMap vObj) { - // TODO Auto-generated method stub - - } - - @Override - protected void validateForUpdate(VXAuditMap vObj, XXAuditMap mObj) { - // TODO Auto-generated method stub - - } - - @Override - protected XXAuditMap mapViewToEntityBean(VXAuditMap vObj, XXAuditMap mObj, int OPERATION_CONTEXT) { - XXAuditMap ret = null; - if(vObj!=null && mObj!=null){ - ret = super.mapViewToEntityBean(vObj, mObj, OPERATION_CONTEXT); - XXPortalUser xXPortalUser=null; - if(ret.getAddedByUserId()==null || ret.getAddedByUserId()==0){ - if(!stringUtil.isEmpty(vObj.getOwner())){ - xXPortalUser=daoManager.getXXPortalUser().findByLoginId(vObj.getOwner()); - if(xXPortalUser!=null){ - ret.setAddedByUserId(xXPortalUser.getId()); - } - } - } - if(ret.getUpdatedByUserId()==null || ret.getUpdatedByUserId()==0){ - if(!stringUtil.isEmpty(vObj.getUpdatedBy())){ - xXPortalUser= daoManager.getXXPortalUser().findByLoginId(vObj.getUpdatedBy()); - if(xXPortalUser!=null){ - ret.setUpdatedByUserId(xXPortalUser.getId()); - } - } - } - } - return ret; - } - - @Override - protected VXAuditMap mapEntityToViewBean(VXAuditMap vObj, XXAuditMap mObj) { - VXAuditMap ret = null; - if(mObj!=null && vObj!=null){ - ret = super.mapEntityToViewBean(vObj, mObj); - XXPortalUser xXPortalUser=null; - if(stringUtil.isEmpty(ret.getOwner())){ - xXPortalUser= daoManager.getXXPortalUser().getById(mObj.getAddedByUserId()); - if(xXPortalUser!=null){ - ret.setOwner(xXPortalUser.getLoginId()); - } - } - if(stringUtil.isEmpty(ret.getUpdatedBy())){ - xXPortalUser= daoManager.getXXPortalUser().getById(mObj.getUpdatedByUserId()); - if(xXPortalUser!=null){ - ret.setUpdatedBy(xXPortalUser.getLoginId()); - } - } - } - return ret; - } + if (xXPortalUser != null) { + ret.setUpdatedBy(xXPortalUser.getLoginId()); + } + } + } + return ret; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/service/XAuditMapServiceBase.java b/security-admin/src/main/java/org/apache/ranger/service/XAuditMapServiceBase.java index 2bce439bf8..13a6d58aa0 100644 --- a/security-admin/src/main/java/org/apache/ranger/service/XAuditMapServiceBase.java +++ b/security-admin/src/main/java/org/apache/ranger/service/XAuditMapServiceBase.java @@ -17,14 +17,7 @@ * under the License. */ - package org.apache.ranger.service; - -/** - * - */ - -import java.util.ArrayList; -import java.util.List; +package org.apache.ranger.service; import org.apache.ranger.common.AppConstants; import org.apache.ranger.common.SearchCriteria; @@ -33,58 +26,63 @@ import org.apache.ranger.view.VXAuditMap; import org.apache.ranger.view.VXAuditMapList; -public abstract class XAuditMapServiceBase - extends AbstractAuditedResourceService { - public static final String NAME = "XAuditMap"; - - public XAuditMapServiceBase() { - super(AppConstants.CLASS_TYPE_XA_AUDIT_MAP, AppConstants.CLASS_TYPE_XA_RESOURCE); - // 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)); - } - - @Override - protected T mapViewToEntityBean(V vObj, T mObj, int OPERATION_CONTEXT) { - mObj.setResourceId( vObj.getResourceId()); - mObj.setGroupId( vObj.getGroupId()); - mObj.setUserId( vObj.getUserId()); - mObj.setAuditType( vObj.getAuditType()); - return mObj; - } - - @Override - protected V mapEntityToViewBean(V vObj, T 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 xAuditMapList = new ArrayList(); - - List resultList = searchResources(searchCriteria, - searchFields, sortFields, returnList); - - // Iterate over the result list and create the return list - for (T gjXAuditMap : resultList) { - VXAuditMap vXAuditMap = populateViewBean(gjXAuditMap); - xAuditMapList.add(vXAuditMap); - } - - returnList.setVXAuditMaps(xAuditMapList); - return returnList; - } - - @Override - public Long getParentObjectId(V obj, V oldObj) { - return obj != null ? obj.getResourceId() : null; - } +import java.util.ArrayList; +import java.util.List; + +public abstract class XAuditMapServiceBase extends AbstractAuditedResourceService { + public static final String NAME = "XAuditMap"; + + public XAuditMapServiceBase() { + super(AppConstants.CLASS_TYPE_XA_AUDIT_MAP, AppConstants.CLASS_TYPE_XA_RESOURCE); + + //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)); + } + + /** + * @param searchCriteria + * @return + */ + public VXAuditMapList searchXAuditMaps(SearchCriteria searchCriteria) { + VXAuditMapList returnList = new VXAuditMapList(); + List xAuditMapList = new ArrayList<>(); + List resultList = searchResources(searchCriteria, searchFields, sortFields, returnList); + + // Iterate over the result list and create the return list + for (T gjXAuditMap : resultList) { + VXAuditMap vXAuditMap = populateViewBean(gjXAuditMap); + + xAuditMapList.add(vXAuditMap); + } + + returnList.setVXAuditMaps(xAuditMapList); + + return returnList; + } + + @Override + public Long getParentObjectId(V obj, V oldObj) { + return obj != null ? obj.getResourceId() : null; + } + + @Override + protected T mapViewToEntityBean(V vObj, T mObj, int operationContext) { + mObj.setResourceId(vObj.getResourceId()); + mObj.setGroupId(vObj.getGroupId()); + mObj.setUserId(vObj.getUserId()); + mObj.setAuditType(vObj.getAuditType()); + + return mObj; + } + + @Override + protected V mapEntityToViewBean(V vObj, T mObj) { + vObj.setResourceId(mObj.getResourceId()); + vObj.setGroupId(mObj.getGroupId()); + vObj.setUserId(mObj.getUserId()); + vObj.setAuditType(mObj.getAuditType()); + + return vObj; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/service/XCredentialStoreService.java b/security-admin/src/main/java/org/apache/ranger/service/XCredentialStoreService.java index c2dd320a20..bd7682a3e8 100644 --- a/security-admin/src/main/java/org/apache/ranger/service/XCredentialStoreService.java +++ b/security-admin/src/main/java/org/apache/ranger/service/XCredentialStoreService.java @@ -17,7 +17,7 @@ * under the License. */ - package org.apache.ranger.service; +package org.apache.ranger.service; import org.apache.ranger.entity.XXCredentialStore; import org.apache.ranger.view.VXCredentialStore; @@ -27,17 +27,13 @@ @Service @Scope("singleton") public class XCredentialStoreService extends XCredentialStoreServiceBase { - - @Override - protected void validateForCreate(VXCredentialStore vObj) { - // TODO Auto-generated method stub - - } - - @Override - protected void validateForUpdate(VXCredentialStore vObj, XXCredentialStore mObj) { - // TODO Auto-generated method stub - - } - + @Override + protected void validateForCreate(VXCredentialStore vObj) { + // TODO Auto-generated method stub + } + + @Override + protected void validateForUpdate(VXCredentialStore vObj, XXCredentialStore mObj) { + // TODO Auto-generated method stub + } } diff --git a/security-admin/src/main/java/org/apache/ranger/service/XCredentialStoreServiceBase.java b/security-admin/src/main/java/org/apache/ranger/service/XCredentialStoreServiceBase.java index 20274527ff..3fb93ad56b 100644 --- a/security-admin/src/main/java/org/apache/ranger/service/XCredentialStoreServiceBase.java +++ b/security-admin/src/main/java/org/apache/ranger/service/XCredentialStoreServiceBase.java @@ -17,61 +17,56 @@ * under the License. */ - package org.apache.ranger.service; - -/** - * - */ - -import java.util.ArrayList; -import java.util.List; +package org.apache.ranger.service; import org.apache.ranger.common.SearchCriteria; import org.apache.ranger.entity.XXCredentialStore; import org.apache.ranger.view.VXCredentialStore; import org.apache.ranger.view.VXCredentialStoreList; -public abstract class XCredentialStoreServiceBase - extends AbstractBaseResourceService { - public static final String NAME = "XCredentialStore"; +import java.util.ArrayList; +import java.util.List; + +public abstract class XCredentialStoreServiceBase extends AbstractBaseResourceService { + public static final String NAME = "XCredentialStore"; + + public XCredentialStoreServiceBase() { + } - public XCredentialStoreServiceBase() { + /** + * @param searchCriteria + * @return + */ + public VXCredentialStoreList searchXCredentialStores(SearchCriteria searchCriteria) { + VXCredentialStoreList returnList = new VXCredentialStoreList(); + List xCredentialStoreList = new ArrayList<>(); + List resultList = searchResources(searchCriteria, searchFields, sortFields, returnList); - } + // Iterate over the result list and create the return list + for (T gjXCredentialStore : resultList) { + VXCredentialStore vXCredentialStore = populateViewBean(gjXCredentialStore); - @Override - protected T mapViewToEntityBean(V vObj, T mObj, int OPERATION_CONTEXT) { - mObj.setName( vObj.getName()); - mObj.setDescription( vObj.getDescription()); - return mObj; - } + xCredentialStoreList.add(vXCredentialStore); + } - @Override - protected V mapEntityToViewBean(V vObj, T mObj) { - vObj.setName( mObj.getName()); - vObj.setDescription( mObj.getDescription()); - return vObj; - } + returnList.setVXCredentialStores(xCredentialStoreList); - /** - * @param searchCriteria - * @return - */ - public VXCredentialStoreList searchXCredentialStores(SearchCriteria searchCriteria) { - VXCredentialStoreList returnList = new VXCredentialStoreList(); - List xCredentialStoreList = new ArrayList(); + return returnList; + } - List resultList = searchResources(searchCriteria, - searchFields, sortFields, returnList); + @Override + protected T mapViewToEntityBean(V vObj, T mObj, int operationContext) { + mObj.setName(vObj.getName()); + mObj.setDescription(vObj.getDescription()); - // Iterate over the result list and create the return list - for (T gjXCredentialStore : resultList) { - VXCredentialStore vXCredentialStore = populateViewBean(gjXCredentialStore); - xCredentialStoreList.add(vXCredentialStore); - } + return mObj; + } - returnList.setVXCredentialStores(xCredentialStoreList); - return returnList; - } + @Override + protected V mapEntityToViewBean(V vObj, T mObj) { + vObj.setName(mObj.getName()); + vObj.setDescription(mObj.getDescription()); + return vObj; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/service/XGroupGroupService.java b/security-admin/src/main/java/org/apache/ranger/service/XGroupGroupService.java index 67f4c739a7..1ee0457929 100644 --- a/security-admin/src/main/java/org/apache/ranger/service/XGroupGroupService.java +++ b/security-admin/src/main/java/org/apache/ranger/service/XGroupGroupService.java @@ -17,7 +17,7 @@ * under the License. */ - package org.apache.ranger.service; +package org.apache.ranger.service; import org.apache.ranger.entity.XXGroupGroup; import org.apache.ranger.view.VXGroupGroup; @@ -27,17 +27,13 @@ @Service @Scope("singleton") public class XGroupGroupService extends XGroupGroupServiceBase { - - @Override - protected void validateForCreate(VXGroupGroup vObj) { - // TODO Auto-generated method stub - - } - - @Override - protected void validateForUpdate(VXGroupGroup vObj, XXGroupGroup mObj) { - // TODO Auto-generated method stub - - } - + @Override + protected void validateForCreate(VXGroupGroup vObj) { + // TODO Auto-generated method stub + } + + @Override + protected void validateForUpdate(VXGroupGroup vObj, XXGroupGroup mObj) { + // TODO Auto-generated method stub + } } diff --git a/security-admin/src/main/java/org/apache/ranger/service/XGroupGroupServiceBase.java b/security-admin/src/main/java/org/apache/ranger/service/XGroupGroupServiceBase.java index 643157fdce..5c14bc2473 100644 --- a/security-admin/src/main/java/org/apache/ranger/service/XGroupGroupServiceBase.java +++ b/security-admin/src/main/java/org/apache/ranger/service/XGroupGroupServiceBase.java @@ -17,63 +17,58 @@ * under the License. */ - package org.apache.ranger.service; - -/** - * - */ - -import java.util.ArrayList; -import java.util.List; +package org.apache.ranger.service; import org.apache.ranger.common.SearchCriteria; import org.apache.ranger.entity.XXGroupGroup; import org.apache.ranger.view.VXGroupGroup; import org.apache.ranger.view.VXGroupGroupList; -public abstract class XGroupGroupServiceBase - extends AbstractBaseResourceService { - public static final String NAME = "XGroupGroup"; +import java.util.ArrayList; +import java.util.List; + +public abstract class XGroupGroupServiceBase extends AbstractBaseResourceService { + public static final String NAME = "XGroupGroup"; + + public XGroupGroupServiceBase() { + } - public XGroupGroupServiceBase() { + /** + * @param searchCriteria + * @return + */ + public VXGroupGroupList searchXGroupGroups(SearchCriteria searchCriteria) { + VXGroupGroupList returnList = new VXGroupGroupList(); + List xGroupGroupList = new ArrayList<>(); + List resultList = searchResources(searchCriteria, searchFields, sortFields, returnList); - } + // Iterate over the result list and create the return list + for (T gjXGroupGroup : resultList) { + V vXGroupGroup = populateViewBean(gjXGroupGroup); - @Override - protected T mapViewToEntityBean(V vObj, T mObj, int OPERATION_CONTEXT) { - mObj.setName( vObj.getName()); - mObj.setParentGroupId( vObj.getParentGroupId()); - mObj.setGroupId( vObj.getGroupId()); - return mObj; - } + xGroupGroupList.add(vXGroupGroup); + } - @Override - protected V mapEntityToViewBean(V vObj, T mObj) { - vObj.setName( mObj.getName()); - vObj.setParentGroupId( mObj.getParentGroupId()); - vObj.setGroupId( mObj.getGroupId()); - return vObj; - } + returnList.setVXGroupGroups(xGroupGroupList); - /** - * @param searchCriteria - * @return - */ - public VXGroupGroupList searchXGroupGroups(SearchCriteria searchCriteria) { - VXGroupGroupList returnList = new VXGroupGroupList(); - List xGroupGroupList = new ArrayList(); + return returnList; + } - List resultList = searchResources(searchCriteria, - searchFields, sortFields, returnList); + @Override + protected T mapViewToEntityBean(V vObj, T mObj, int operationContext) { + mObj.setName(vObj.getName()); + mObj.setParentGroupId(vObj.getParentGroupId()); + mObj.setGroupId(vObj.getGroupId()); - // Iterate over the result list and create the return list - for (T gjXGroupGroup : resultList) { - V vXGroupGroup = populateViewBean(gjXGroupGroup); - xGroupGroupList.add(vXGroupGroup); - } + return mObj; + } - returnList.setVXGroupGroups(xGroupGroupList); - return returnList; - } + @Override + protected V mapEntityToViewBean(V vObj, T mObj) { + vObj.setName(mObj.getName()); + vObj.setParentGroupId(mObj.getParentGroupId()); + vObj.setGroupId(mObj.getGroupId()); + return vObj; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/service/XGroupPermissionService.java b/security-admin/src/main/java/org/apache/ranger/service/XGroupPermissionService.java index 030f8adf1e..1c1c07bdf4 100644 --- a/security-admin/src/main/java/org/apache/ranger/service/XGroupPermissionService.java +++ b/security-admin/src/main/java/org/apache/ranger/service/XGroupPermissionService.java @@ -17,11 +17,6 @@ package org.apache.ranger.service; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - import org.apache.ranger.common.MessageEnums; import org.apache.ranger.common.SearchField; import org.apache.ranger.entity.XXGroup; @@ -31,81 +26,86 @@ import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Service; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + @Service @Scope("singleton") -public class XGroupPermissionService extends XGroupPermissionServiceBase{ - - public XGroupPermissionService() { - searchFields.add(new SearchField("id", "obj.id", - SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.FULL)); - - searchFields.add(new SearchField("groupPermissionList", "obj.groupId", - SearchField.DATA_TYPE.INTEGER, SearchField.SEARCH_TYPE.FULL, - "XXModuleDef xXModuleDef", "xXModuleDef.id = obj.groupId ")); - } - - @Override - protected void validateForCreate(VXGroupPermission vObj) { - XXGroupPermission xGroupPerm = daoManager.getXXGroupPermission().findByModuleIdAndGroupId(vObj.getGroupId(), vObj.getModuleId()); - if (xGroupPerm != null) { - throw restErrorUtil.createRESTException("Group with ID [" + vObj.getGroupId() + "] " + "is already " + "assigned to the module with ID [" + vObj.getModuleId() + "]", - MessageEnums.ERROR_DUPLICATE_OBJECT); - } - } - - @Override - protected void validateForUpdate(VXGroupPermission vObj, XXGroupPermission mObj) { - XXGroupPermission xGroupPerm = daoManager.getXXGroupPermission().findByModuleIdAndGroupId(vObj.getGroupId(), vObj.getModuleId()); - if (xGroupPerm != null && !xGroupPerm.getId().equals(vObj.getId())) { - throw restErrorUtil.createRESTException("Group with ID [" + vObj.getGroupId() + "] " + "is already " + "assigned to the module with ID [" + vObj.getModuleId() + "]", - MessageEnums.ERROR_DUPLICATE_OBJECT); - } - } - - @Override - public VXGroupPermission populateViewBean(XXGroupPermission xObj) { - VXGroupPermission vObj = super.populateViewBean(xObj); - XXGroup xGroup = daoManager.getXXGroup().getById( - xObj.getGroupId()); - - if (xGroup == null) { - throw restErrorUtil.createRESTException(xGroup + " is Not Found", - MessageEnums.DATA_NOT_FOUND); - } - - vObj.setGroupName(xGroup.getName()); - return vObj; - } - - public List getPopulatedVXGroupPermissionList(List xgroupPermissionList, - Map xXGroupMap, VXModuleDef vModuleDef) { - List vXGroupPermissionList = new ArrayList(); - for (XXGroupPermission xgroupPermission : xgroupPermissionList) { - if (xXGroupMap.containsKey(xgroupPermission.getGroupId())) { - VXGroupPermission vXGrpPerm = new VXGroupPermission(); - vXGrpPerm.setId(xgroupPermission.getId()); - vXGrpPerm.setGroupId(xgroupPermission.getGroupId()); - vXGrpPerm.setModuleId(xgroupPermission.getModuleId()); - vXGrpPerm.setIsAllowed(xgroupPermission.getIsAllowed()); - vXGrpPerm.setCreateDate(xgroupPermission.getCreateTime()); - vXGrpPerm.setUpdateDate(xgroupPermission.getUpdateTime()); - vXGrpPerm.setGroupName(xXGroupMap.get(xgroupPermission.getGroupId())); - vXGrpPerm.setModuleName(vModuleDef.getModule()); - vXGroupPermissionList.add(vXGrpPerm); - } - } - return vXGroupPermissionList; - } - - @Override - public Map convertVListToVMap(List vObjList) { - Map ret = new HashMap(); - if (vObjList == null) { - return ret; - } - for (VXGroupPermission vObj : vObjList) { - ret.put(vObj.getGroupId(), vObj); - } - return ret; - } +public class XGroupPermissionService extends XGroupPermissionServiceBase { + public XGroupPermissionService() { + searchFields.add(new SearchField("id", "obj.id", SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.FULL)); + searchFields.add(new SearchField("groupPermissionList", "obj.groupId", SearchField.DATA_TYPE.INTEGER, SearchField.SEARCH_TYPE.FULL, "XXModuleDef xXModuleDef", "xXModuleDef.id = obj.groupId ")); + } + + public List getPopulatedVXGroupPermissionList(List xgroupPermissionList, Map xXGroupMap, VXModuleDef vModuleDef) { + List vXGroupPermissionList = new ArrayList<>(); + + for (XXGroupPermission xgroupPermission : xgroupPermissionList) { + if (xXGroupMap.containsKey(xgroupPermission.getGroupId())) { + VXGroupPermission vXGrpPerm = new VXGroupPermission(); + + vXGrpPerm.setId(xgroupPermission.getId()); + vXGrpPerm.setGroupId(xgroupPermission.getGroupId()); + vXGrpPerm.setModuleId(xgroupPermission.getModuleId()); + vXGrpPerm.setIsAllowed(xgroupPermission.getIsAllowed()); + vXGrpPerm.setCreateDate(xgroupPermission.getCreateTime()); + vXGrpPerm.setUpdateDate(xgroupPermission.getUpdateTime()); + vXGrpPerm.setGroupName(xXGroupMap.get(xgroupPermission.getGroupId())); + vXGrpPerm.setModuleName(vModuleDef.getModule()); + + vXGroupPermissionList.add(vXGrpPerm); + } + } + + return vXGroupPermissionList; + } + + @Override + public VXGroupPermission populateViewBean(XXGroupPermission xObj) { + VXGroupPermission vObj = super.populateViewBean(xObj); + XXGroup xGroup = daoManager.getXXGroup().getById(xObj.getGroupId()); + + if (xGroup == null) { + throw restErrorUtil.createRESTException(xGroup + " is Not Found", MessageEnums.DATA_NOT_FOUND); + } + + vObj.setGroupName(xGroup.getName()); + + return vObj; + } + + @Override + public Map convertVListToVMap(List vObjList) { + Map ret = new HashMap<>(); + + if (vObjList == null) { + return ret; + } + + for (VXGroupPermission vObj : vObjList) { + ret.put(vObj.getGroupId(), vObj); + } + + return ret; + } + + @Override + protected void validateForCreate(VXGroupPermission vObj) { + XXGroupPermission xGroupPerm = daoManager.getXXGroupPermission().findByModuleIdAndGroupId(vObj.getGroupId(), vObj.getModuleId()); + + if (xGroupPerm != null) { + throw restErrorUtil.createRESTException("Group with ID [" + vObj.getGroupId() + "] " + "is already " + "assigned to the module with ID [" + vObj.getModuleId() + "]", MessageEnums.ERROR_DUPLICATE_OBJECT); + } + } + + @Override + protected void validateForUpdate(VXGroupPermission vObj, XXGroupPermission mObj) { + XXGroupPermission xGroupPerm = daoManager.getXXGroupPermission().findByModuleIdAndGroupId(vObj.getGroupId(), vObj.getModuleId()); + + if (xGroupPerm != null && !xGroupPerm.getId().equals(vObj.getId())) { + throw restErrorUtil.createRESTException("Group with ID [" + vObj.getGroupId() + "] " + "is already " + "assigned to the module with ID [" + vObj.getModuleId() + "]", MessageEnums.ERROR_DUPLICATE_OBJECT); + } + } } diff --git a/security-admin/src/main/java/org/apache/ranger/service/XGroupPermissionServiceBase.java b/security-admin/src/main/java/org/apache/ranger/service/XGroupPermissionServiceBase.java index 0eeb0c0bfe..9418271304 100644 --- a/security-admin/src/main/java/org/apache/ranger/service/XGroupPermissionServiceBase.java +++ b/security-admin/src/main/java/org/apache/ranger/service/XGroupPermissionServiceBase.java @@ -17,57 +17,56 @@ package org.apache.ranger.service; -import java.util.ArrayList; -import java.util.List; import org.apache.ranger.common.SearchCriteria; import org.apache.ranger.entity.XXGroupPermission; import org.apache.ranger.view.VXGroupPermission; import org.apache.ranger.view.VXGroupPermissionList; -public abstract class XGroupPermissionServiceBase - extends AbstractBaseResourceService { +import java.util.ArrayList; +import java.util.List; + +public abstract class XGroupPermissionServiceBase extends AbstractBaseResourceService { + public static final String NAME = "XGroupPermission"; + + public XGroupPermissionServiceBase() { + } - public static final String NAME = "XGroupPermission"; + /** + * @param searchCriteria + * @return + */ + public VXGroupPermissionList searchXGroupPermission(SearchCriteria searchCriteria) { + VXGroupPermissionList returnList = new VXGroupPermissionList(); + List vXGroupPermissions = new ArrayList<>(); + List resultList = searchResources(searchCriteria, searchFields, sortFields, returnList); - public XGroupPermissionServiceBase() { + // Iterate over the result list and create the return list + for (T gjXUser : resultList) { + VXGroupPermission vXGroupPermission = populateViewBean(gjXUser); - } + vXGroupPermissions.add(vXGroupPermission); + } - @Override - protected T mapViewToEntityBean(V vObj, - T mObj, int OPERATION_CONTEXT) { - mObj.setGroupId(vObj.getGroupId()); - mObj.setModuleId(vObj.getModuleId()); - mObj.setIsAllowed(vObj.getIsAllowed()); - return mObj; - } + returnList.setvXGroupPermission(vXGroupPermissions); - @Override - protected V mapEntityToViewBean(V vObj, T mObj) { - vObj.setGroupId(mObj.getGroupId()); - vObj.setModuleId(mObj.getModuleId()); - vObj.setIsAllowed(mObj.getIsAllowed()); - return vObj; - } + return returnList; + } - /** - * @param searchCriteria - * @return - */ - public VXGroupPermissionList searchXGroupPermission(SearchCriteria searchCriteria) { - VXGroupPermissionList returnList = new VXGroupPermissionList(); - List vXGroupPermissions = new ArrayList(); + @Override + protected T mapViewToEntityBean(V vObj, T mObj, int operationContext) { + mObj.setGroupId(vObj.getGroupId()); + mObj.setModuleId(vObj.getModuleId()); + mObj.setIsAllowed(vObj.getIsAllowed()); - List resultList = searchResources( - searchCriteria, searchFields, sortFields, returnList); + return mObj; + } - // Iterate over the result list and create the return list - for (T gjXUser : resultList) { - VXGroupPermission vXGroupPermission = populateViewBean(gjXUser); - vXGroupPermissions.add(vXGroupPermission); - } + @Override + protected V mapEntityToViewBean(V vObj, T mObj) { + vObj.setGroupId(mObj.getGroupId()); + vObj.setModuleId(mObj.getModuleId()); + vObj.setIsAllowed(mObj.getIsAllowed()); - returnList.setvXGroupPermission(vXGroupPermissions); - return returnList; - } + return vObj; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/service/XGroupService.java b/security-admin/src/main/java/org/apache/ranger/service/XGroupService.java index 46484e706a..cccd162684 100644 --- a/security-admin/src/main/java/org/apache/ranger/service/XGroupService.java +++ b/security-admin/src/main/java/org/apache/ranger/service/XGroupService.java @@ -17,11 +17,7 @@ * under the License. */ - package org.apache.ranger.service; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; +package org.apache.ranger.service; import org.apache.ranger.common.MessageEnums; import org.apache.ranger.common.PropertiesUtil; @@ -34,142 +30,146 @@ import org.springframework.stereotype.Service; import org.springframework.util.CollectionUtils; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + @Service @Scope("singleton") public class XGroupService extends XGroupServiceBase { + private final Long createdByUserId; + + 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.INTEGER, SearchField.SEARCH_TYPE.FULL)); + searchFields.add(new SearchField("isVisible", "obj.isVisible", SearchField.DATA_TYPE.INTEGER, SearchField.SEARCH_TYPE.FULL)); + searchFields.add(new SearchField("userId", "groupUser.userId", SearchField.DATA_TYPE.INTEGER, SearchField.SEARCH_TYPE.FULL, "XXGroupUser groupUser", "obj.id = groupUser.parentGroupId")); + searchFields.add(new SearchField("syncSource", "obj.syncSource", SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.PARTIAL)); + + createdByUserId = PropertiesUtil.getLongProperty("ranger.xuser.createdByUserId", 1); + + sortFields.add(new SortField("name", "obj.name", true, SortField.SORT_ORDER.ASC)); + } + + public VXGroup getGroupByGroupName(String groupName) { + XXGroup xxGroup = daoManager.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 = daoManager.getXXGroup().findByGroupName(vxGroup.getName()); + boolean groupExists = true; + + if (xxGroup == null) { + xxGroup = new XXGroup(); + groupExists = false; + } + + xxGroup = mapViewToEntityBean(vxGroup, xxGroup, 0); + + XXPortalUser xXPortalUser = daoManager.getXXPortalUser().getById(createdByUserId); + + if (xXPortalUser != null) { + xxGroup.setAddedByUserId(createdByUserId); + xxGroup.setUpdatedByUserId(createdByUserId); + } - private final Long createdByUserId; - - 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.INTEGER, SearchField.SEARCH_TYPE.FULL)); - - searchFields.add(new SearchField("isVisible", "obj.isVisible", - SearchField.DATA_TYPE.INTEGER, SearchField.SEARCH_TYPE.FULL )); - - searchFields.add(new SearchField("userId", "groupUser.userId", - SearchField.DATA_TYPE.INTEGER, SearchField.SEARCH_TYPE.FULL, - "XXGroupUser groupUser", "obj.id = groupUser.parentGroupId")); - - searchFields.add(new SearchField("syncSource", "obj.syncSource", - SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.PARTIAL)); - - createdByUserId = PropertiesUtil.getLongProperty("ranger.xuser.createdByUserId", 1); - - sortFields.add(new SortField("name", "obj.name",true,SortField.SORT_ORDER.ASC)); - } - - @Override - protected void validateForCreate(VXGroup vObj) { - XXGroup xxGroup = daoManager.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 = daoManager.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 = daoManager.getXXGroup().findByGroupName( - vxGroup.getName()); - boolean groupExists = true; - - if (xxGroup == null) { - xxGroup = new XXGroup(); - groupExists = false; - } - - xxGroup = mapViewToEntityBean(vxGroup, xxGroup, 0); - XXPortalUser xXPortalUser = daoManager.getXXPortalUser().getById(createdByUserId); - if (xXPortalUser != null) { - xxGroup.setAddedByUserId(createdByUserId); - xxGroup.setUpdatedByUserId(createdByUserId); - } - if (groupExists) { - getDao().update(xxGroup); - } else { - getDao().create(xxGroup); - } - xxGroup = daoManager.getXXGroup().findByGroupName(vxGroup.getName()); - 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; - } - - @Override - public VXGroup populateViewBean(XXGroup xGroup) { - VXGroup vObj = super.populateViewBean(xGroup); - vObj.setIsVisible(xGroup.getIsVisible()); - return vObj; - } - - @Override - protected XXGroup mapViewToEntityBean(VXGroup vObj, XXGroup mObj, int OPERATION_CONTEXT) { - return super.mapViewToEntityBean(vObj, mObj, OPERATION_CONTEXT); - } - - @Override - protected VXGroup mapEntityToViewBean(VXGroup vObj, XXGroup mObj) { - return super.mapEntityToViewBean(vObj, mObj); + if (groupExists) { + getDao().update(xxGroup); + } else { + getDao().create(xxGroup); } - public Map getXXGroupIdXXGroupMap(){ - Map xXGroupMap=new HashMap(); - try{ - List xXGroupList=daoManager.getXXGroup().getAll(); - if(!CollectionUtils.isEmpty(xXGroupList)){ - for(XXGroup xXGroup:xXGroupList){ - xXGroupMap.put(xXGroup.getId(), xXGroup); - } - } - }catch(Exception ex){} - return xXGroupMap; + xxGroup = daoManager.getXXGroup().findByGroupName(vxGroup.getName()); + 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 Map getXXGroupIdXXGroupMap() { + Map xXGroupMap = new HashMap<>(); + + try { + List xXGroupList = daoManager.getXXGroup().getAll(); + + if (!CollectionUtils.isEmpty(xXGroupList)) { + for (XXGroup xXGroup : xXGroupList) { + xXGroupMap.put(xXGroup.getId(), xXGroup); + } + } + } catch (Exception ex) { + // ignore } - public Map getXXGroupIdNameMap() { - return daoManager.getXXGroup().getAllGroupIdNames(); - } + return xXGroupMap; + } + + public Map getXXGroupIdNameMap() { + return daoManager.getXXGroup().getAllGroupIdNames(); + } + + public Long getAllGroupCount() { + return daoManager.getXXGroup().getAllCount(); + } + + public List getGroupsByUserId(Long userId) { + return daoManager.getXXGroup().findByUserId(userId); + } + + @Override + public VXGroup populateViewBean(XXGroup xGroup) { + VXGroup vObj = super.populateViewBean(xGroup); + + vObj.setIsVisible(xGroup.getIsVisible()); + + return vObj; + } + + @Override + protected void validateForCreate(VXGroup vObj) { + XXGroup xxGroup = daoManager.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 Long getAllGroupCount() { - return daoManager.getXXGroup().getAllCount(); - } + @Override + protected XXGroup mapViewToEntityBean(VXGroup vObj, XXGroup mObj, int operationContext) { + return super.mapViewToEntityBean(vObj, mObj, operationContext); + } - public List getGroupsByUserId(Long userId) { - return daoManager.getXXGroup().findByUserId(userId); - } + @Override + protected VXGroup mapEntityToViewBean(VXGroup vObj, XXGroup mObj) { + return super.mapEntityToViewBean(vObj, mObj); + } } diff --git a/security-admin/src/main/java/org/apache/ranger/service/XGroupServiceBase.java b/security-admin/src/main/java/org/apache/ranger/service/XGroupServiceBase.java index 8577f2215c..a385457944 100644 --- a/security-admin/src/main/java/org/apache/ranger/service/XGroupServiceBase.java +++ b/security-admin/src/main/java/org/apache/ranger/service/XGroupServiceBase.java @@ -17,14 +17,7 @@ * under the License. */ - package org.apache.ranger.service; - -/** - * - */ - -import java.util.ArrayList; -import java.util.List; +package org.apache.ranger.service; import org.apache.ranger.common.AppConstants; import org.apache.ranger.common.SearchCriteria; @@ -36,81 +29,87 @@ import javax.persistence.Query; -public abstract class XGroupServiceBase - extends AbstractAuditedResourceService { - public static final String NAME = "XGroup"; - - public XGroupServiceBase() { - super(AppConstants.CLASS_TYPE_XA_GROUP); - - trxLogAttrs.put("name", new VTrxLogAttr("name", "Group Name", false, true)); - trxLogAttrs.put("description", new VTrxLogAttr("description", "Group Description")); - trxLogAttrs.put("otherAttributes", new VTrxLogAttr("otherAttributes", "Other Attributes")); - trxLogAttrs.put("syncSource", new VTrxLogAttr("syncSource", "Sync Source")); - } - - @Override - protected T mapViewToEntityBean(V vObj, T mObj, int OPERATION_CONTEXT) { - mObj.setName( vObj.getName()); - mObj.setIsVisible(vObj.getIsVisible()); - mObj.setDescription( vObj.getDescription()); - mObj.setGroupType( vObj.getGroupType()); - mObj.setCredStoreId( vObj.getCredStoreId()); - mObj.setGroupSource(vObj.getGroupSource()); - mObj.setOtherAttributes(vObj.getOtherAttributes()); - mObj.setSyncSource(vObj.getSyncSource()); - return mObj; - } - - @Override - protected V mapEntityToViewBean(V vObj, T mObj) { - vObj.setName( mObj.getName()); - vObj.setIsVisible( mObj.getIsVisible()); - vObj.setDescription( mObj.getDescription()); - vObj.setGroupType( mObj.getGroupType()); - vObj.setCredStoreId( mObj.getCredStoreId()); - vObj.setGroupSource(mObj.getGroupSource()); - vObj.setOtherAttributes(mObj.getOtherAttributes()); - vObj.setSyncSource(mObj.getSyncSource()); - return vObj; - } - - /** - * @param searchCriteria - * @return - */ - public VXGroupList searchXGroups(SearchCriteria searchCriteria) { - VXGroupList returnList = new VXGroupList(); - List xGroupList = new ArrayList(); - List resultList = searchResources(searchCriteria, searchFields, sortFields, returnList); - - // Iterate over the result list and create the return list - for (T gjXGroup : resultList) { - VXGroup vXGroup = populateViewBean(gjXGroup); - xGroupList.add(vXGroup); - } - - returnList.setVXGroups(xGroupList); - return returnList; - } - - /** - * Searches the XGroup table and gets the group ids matching the search criteria. - */ - public List searchXGroupsForIds(SearchCriteria searchCriteria){ - // construct the sort clause - String sortClause = searchUtil.constructSortClause(searchCriteria, sortFields); - - // get only the column id from the table - String q = "SELECT obj.id FROM " + className + " obj "; - - // construct the query object for retrieving the data - Query query = createQuery(q, sortClause, searchCriteria, searchFields, false); - - return getDao().getIds(query); - } - - public List getGroups() { - return daoManager.getXXGroup().getAllGroupsInfo(); - } +import java.util.ArrayList; +import java.util.List; + +public abstract class XGroupServiceBase extends AbstractAuditedResourceService { + public static final String NAME = "XGroup"; + + public XGroupServiceBase() { + super(AppConstants.CLASS_TYPE_XA_GROUP); + + trxLogAttrs.put("name", new VTrxLogAttr("name", "Group Name", false, true)); + trxLogAttrs.put("description", new VTrxLogAttr("description", "Group Description")); + trxLogAttrs.put("otherAttributes", new VTrxLogAttr("otherAttributes", "Other Attributes")); + trxLogAttrs.put("syncSource", new VTrxLogAttr("syncSource", "Sync Source")); + } + + /** + * @param searchCriteria + * @return + */ + public VXGroupList searchXGroups(SearchCriteria searchCriteria) { + VXGroupList returnList = new VXGroupList(); + List xGroupList = new ArrayList<>(); + List resultList = searchResources(searchCriteria, searchFields, sortFields, returnList); + + // Iterate over the result list and create the return list + for (T gjXGroup : resultList) { + VXGroup vXGroup = populateViewBean(gjXGroup); + + xGroupList.add(vXGroup); + } + + returnList.setVXGroups(xGroupList); + + return returnList; + } + + /** + * Searches the XGroup table and gets the group ids matching the search criteria. + */ + public List searchXGroupsForIds(SearchCriteria searchCriteria) { + // construct the sort clause + String sortClause = searchUtil.constructSortClause(searchCriteria, sortFields); + + // get only the column id from the table + String q = "SELECT obj.id FROM " + className + " obj "; + + // construct the query object for retrieving the data + Query query = createQuery(q, sortClause, searchCriteria, searchFields, false); + + return getDao().getIds(query); + } + + public List getGroups() { + return daoManager.getXXGroup().getAllGroupsInfo(); + } + + @Override + protected T mapViewToEntityBean(V vObj, T mObj, int operationContext) { + mObj.setName(vObj.getName()); + mObj.setIsVisible(vObj.getIsVisible()); + mObj.setDescription(vObj.getDescription()); + mObj.setGroupType(vObj.getGroupType()); + mObj.setCredStoreId(vObj.getCredStoreId()); + mObj.setGroupSource(vObj.getGroupSource()); + mObj.setOtherAttributes(vObj.getOtherAttributes()); + mObj.setSyncSource(vObj.getSyncSource()); + + return mObj; + } + + @Override + protected V mapEntityToViewBean(V vObj, T mObj) { + vObj.setName(mObj.getName()); + vObj.setIsVisible(mObj.getIsVisible()); + vObj.setDescription(mObj.getDescription()); + vObj.setGroupType(mObj.getGroupType()); + vObj.setCredStoreId(mObj.getCredStoreId()); + vObj.setGroupSource(mObj.getGroupSource()); + vObj.setOtherAttributes(mObj.getOtherAttributes()); + vObj.setSyncSource(mObj.getSyncSource()); + + return vObj; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/service/XGroupUserService.java b/security-admin/src/main/java/org/apache/ranger/service/XGroupUserService.java index a4d6640a5e..61b0c95ee6 100644 --- a/security-admin/src/main/java/org/apache/ranger/service/XGroupUserService.java +++ b/security-admin/src/main/java/org/apache/ranger/service/XGroupUserService.java @@ -17,10 +17,7 @@ * under the License. */ - package org.apache.ranger.service; - -import java.util.Map; -import java.util.Set; +package org.apache.ranger.service; import org.apache.commons.collections.CollectionUtils; import org.apache.ranger.common.MessageEnums; @@ -36,203 +33,205 @@ import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Service; +import java.util.Map; +import java.util.Set; + @Service @Scope("singleton") -public class XGroupUserService extends - XGroupUserServiceBase { - - private final Long createdByUserId; - - @Autowired - RangerTransactionSynchronizationAdapter transactionSynchronizationAdapter; - - - 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 = PropertiesUtil.getLongProperty("ranger.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) { - boolean groupUserMappingExists = true; - XXGroupUser xxGroupUser = daoManager.getXXGroupUser().findByGroupNameAndUserId(vxGroupUser.getName(), vxGroupUser.getUserId()); - if (xxGroupUser == null) { - xxGroupUser = new XXGroupUser(); - groupUserMappingExists = false; - } - - XXGroup xGroup = daoManager.getXXGroup().findByGroupName(vxGroupUser.getName()); - vxGroupUser.setParentGroupId(xGroup.getId()); - xxGroupUser = mapViewToEntityBean(vxGroupUser, xxGroupUser, 0); - XXPortalUser xXPortalUser = daoManager.getXXPortalUser().getById(createdByUserId); - if (xXPortalUser != null) { - xxGroupUser.setAddedByUserId(createdByUserId); - xxGroupUser.setUpdatedByUserId(createdByUserId); - } - if (groupUserMappingExists) { - xxGroupUser = getDao().update(xxGroupUser); - } else { - xxGroupUser = getDao().create(xxGroupUser); - } - vxGroupUser = postCreate(xxGroupUser); - return vxGroupUser; - } - - public void createOrDeleteXGroupUsers(GroupUserInfo groupUserInfo, Map usersFromDB) { - if (logger.isDebugEnabled()) { - logger.debug("==>> createOrDeleteXGroupUsers for " + groupUserInfo.getGroupName()); - Long mb = 1024L * 1024L; - logger.debug("==>> createOrDeleteXGroupUsers: Max memory = " + Runtime.getRuntime().maxMemory() / mb + " Free memory = " + Runtime.getRuntime().freeMemory() / mb - + " Total memory = " + Runtime.getRuntime().totalMemory() / mb); - } - String groupName = groupUserInfo.getGroupName(); - if (CollectionUtils.isEmpty(groupUserInfo.getAddUsers()) && CollectionUtils.isEmpty(groupUserInfo.getDelUsers())) { - logger.info("Group memberships for source are empty for " + groupName); - return; - } - XXGroup xxGroup = daoManager.getXXGroup().findByGroupName(groupName); - if (xxGroup == null) { - if (logger.isDebugEnabled()) { - logger.debug("createOrDeleteXGroupUsers(): groupname = " + groupName - + " doesn't exist in database. Hence ignoring group membership updates"); - } - return; - } - /* findUsersByGroupName returns all the entries from x_group_users table for a given group name and corresponding usernames from x_user table. - Return Map has username as key and XXGroupUser object as value. - */ - - Map groupUsers = daoManager.getXXGroupUser().findUsersByGroupName(groupName); - - if (CollectionUtils.isNotEmpty(groupUserInfo.getAddUsers())) { - Set addUsers = groupUserInfo.getAddUsers(); - if (logger.isDebugEnabled()) { - logger.debug("No. of new users in group" + groupName + " = " + addUsers.size()); - } - for (String username : addUsers) { - if (usersFromDB.containsKey(username)) { - // Add or update group user mapping only if the user exists in x_user table. - transactionSynchronizationAdapter.executeOnTransactionCommit(new GroupUserMappingUpdator(groupName, xxGroup.getId(), username, usersFromDB.get(username), groupUsers.get(username), false)); - } - } - } - - if (CollectionUtils.isNotEmpty(groupUserInfo.getDelUsers())) { - Set delUsers = groupUserInfo.getDelUsers(); - if (logger.isDebugEnabled()) { - logger.debug("No. of deleted users in group" + groupName + " = " + delUsers.size()); - } - - for (String username : delUsers) { - if (usersFromDB.containsKey(username)) { - // delete group user mapping only if the user exists in x_user table.. - transactionSynchronizationAdapter.executeOnTransactionCommit(new GroupUserMappingUpdator(groupName, xxGroup.getId(), username, usersFromDB.get(username), groupUsers.get(username), true)); - } - } - } - - if (logger.isDebugEnabled()) { - logger.debug("<<== createOrDeleteXGroupUsers for " + groupUserInfo.getGroupName()); - Long mb = 1024L * 1024L; - logger.debug("<<== createOrDeleteXGroupUsers: Max memory = " + Runtime.getRuntime().maxMemory() / mb + " Free memory = " + Runtime.getRuntime().freeMemory() / mb - + " Total memory = " + Runtime.getRuntime().totalMemory() / mb); - } - } - - 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; - } - - private class GroupUserMappingUpdator implements Runnable { - private String groupName; - private Long groupId; - private String userName; - private Long userId; - private XXGroupUser xxGroupUser; - private boolean isDelete; - - GroupUserMappingUpdator(String groupName, Long groupId, String userName, Long userId, XXGroupUser xxGroupUser, boolean isDelete) { - this.groupName = groupName; - this.groupId = groupId; - this.userName = userName; - this.userId = userId; - this.xxGroupUser = xxGroupUser; - this.isDelete = isDelete; - } - - @Override - public void run() { - updateGroupUserMappings(); - } - - private void updateGroupUserMappings() { - if (logger.isDebugEnabled()) { - logger.debug("==> GroupUserMappingUpdator.updateGroupUserMappings(" + groupName + ", " + userName + ")"); - } - - if (isDelete) { - if (xxGroupUser != null) { - getDao().remove(xxGroupUser.getId()); - if (logger.isDebugEnabled()) { - logger.debug("createOrDeleteXGroupUsers(): deleted group user mapping with groupname = " + groupName - + " username = " + userName); - } - } - } else { - boolean groupUserMappingExists = true; - if (xxGroupUser == null) { - xxGroupUser = new XXGroupUser(); - groupUserMappingExists = false; - } - XXPortalUser xXPortalUser = daoManager.getXXPortalUser().getById(createdByUserId); - if (xXPortalUser != null) { - xxGroupUser.setAddedByUserId(createdByUserId); - xxGroupUser.setUpdatedByUserId(createdByUserId); - } - - if (groupUserMappingExists) { - xxGroupUser = getDao().update(xxGroupUser); - } else { - VXGroupUser vXGroupUser = new VXGroupUser(); - vXGroupUser.setUserId(userId); - vXGroupUser.setName(groupName); - vXGroupUser.setParentGroupId(groupId); - xxGroupUser = mapViewToEntityBean(vXGroupUser, xxGroupUser, 0); - xxGroupUser = getDao().create(xxGroupUser); - } - if (logger.isDebugEnabled()) { - logger.debug(String.format("createOrDeleteXGroupUsers(): Create or update group user mapping with groupname = " + groupName - + " username = %s userId = %d", userName, xxGroupUser.getUserId())); - } - } - if (logger.isDebugEnabled()) { - logger.debug("<== GroupUserMappingUpdator.updateGroupUserMappings(" + groupName + ", " + userName + ")"); - } - } - } - +public class XGroupUserService extends XGroupUserServiceBase { + private final Long createdByUserId; + + @Autowired + RangerTransactionSynchronizationAdapter transactionSynchronizationAdapter; + + 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 = PropertiesUtil.getLongProperty("ranger.xuser.createdByUserId", 1); + } + + public VXGroupUser createXGroupUserWithOutLogin(VXGroupUser vxGroupUser) { + boolean groupUserMappingExists = true; + XXGroupUser xxGroupUser = daoManager.getXXGroupUser().findByGroupNameAndUserId(vxGroupUser.getName(), vxGroupUser.getUserId()); + + if (xxGroupUser == null) { + xxGroupUser = new XXGroupUser(); + groupUserMappingExists = false; + } + + XXGroup xGroup = daoManager.getXXGroup().findByGroupName(vxGroupUser.getName()); + + vxGroupUser.setParentGroupId(xGroup.getId()); + + xxGroupUser = mapViewToEntityBean(vxGroupUser, xxGroupUser, 0); + + XXPortalUser xXPortalUser = daoManager.getXXPortalUser().getById(createdByUserId); + + if (xXPortalUser != null) { + xxGroupUser.setAddedByUserId(createdByUserId); + xxGroupUser.setUpdatedByUserId(createdByUserId); + } + + if (groupUserMappingExists) { + xxGroupUser = getDao().update(xxGroupUser); + } else { + xxGroupUser = getDao().create(xxGroupUser); + } + + vxGroupUser = postCreate(xxGroupUser); + + return vxGroupUser; + } + + public void createOrDeleteXGroupUsers(GroupUserInfo groupUserInfo, Map usersFromDB) { + if (logger.isDebugEnabled()) { + logger.debug("==>> createOrDeleteXGroupUsers for {}", groupUserInfo.getGroupName()); + + Long mb = 1024L * 1024L; + + logger.debug("==>> createOrDeleteXGroupUsers: Max memory = {} Free memory = {} Total memory = {}", Runtime.getRuntime().maxMemory() / mb, Runtime.getRuntime().freeMemory() / mb, Runtime.getRuntime().totalMemory() / mb); + } + + String groupName = groupUserInfo.getGroupName(); + + if (CollectionUtils.isEmpty(groupUserInfo.getAddUsers()) && CollectionUtils.isEmpty(groupUserInfo.getDelUsers())) { + logger.info("Group memberships for source are empty for {}", groupName); + + return; + } + + XXGroup xxGroup = daoManager.getXXGroup().findByGroupName(groupName); + + if (xxGroup == null) { + logger.debug("createOrDeleteXGroupUsers(): groupName = {} doesn't exist in database. Hence ignoring group membership updates", groupName); + + return; + } + + /* findUsersByGroupName returns all the entries from x_group_users table for a given group name and corresponding usernames from x_user table. + Return Map has username as key and XXGroupUser object as value. + */ + + Map groupUsers = daoManager.getXXGroupUser().findUsersByGroupName(groupName); + + if (CollectionUtils.isNotEmpty(groupUserInfo.getAddUsers())) { + Set addUsers = groupUserInfo.getAddUsers(); + + logger.debug("No. of new users in group {} : {}", groupName, addUsers.size()); + + for (String username : addUsers) { + if (usersFromDB.containsKey(username)) { + // Add or update group user mapping only if the user exists in x_user table. + transactionSynchronizationAdapter.executeOnTransactionCommit(new GroupUserMappingUpdator(groupName, xxGroup.getId(), username, usersFromDB.get(username), groupUsers.get(username), false)); + } + } + } + + if (CollectionUtils.isNotEmpty(groupUserInfo.getDelUsers())) { + Set delUsers = groupUserInfo.getDelUsers(); + + logger.debug("No. of deleted users in group {} : {}", groupName, delUsers.size()); + + for (String username : delUsers) { + if (usersFromDB.containsKey(username)) { + // delete group user mapping only if the user exists in x_user table.. + transactionSynchronizationAdapter.executeOnTransactionCommit(new GroupUserMappingUpdator(groupName, xxGroup.getId(), username, usersFromDB.get(username), groupUsers.get(username), true)); + } + } + } + + if (logger.isDebugEnabled()) { + logger.debug("<<== createOrDeleteXGroupUsers for {}", groupUserInfo.getGroupName()); + + long mb = 1024L * 1024L; + + logger.debug("<<== createOrDeleteXGroupUsers: Max memory = {} Free memory = {} Total memory = {}", Runtime.getRuntime().maxMemory() / mb, Runtime.getRuntime().freeMemory() / mb, Runtime.getRuntime().totalMemory() / mb); + } + } + + 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."); + } + + return populateViewBean(resource); + } + + @Override + protected void validateForCreate(VXGroupUser vObj) { + } + + @Override + protected void validateForUpdate(VXGroupUser vObj, XXGroupUser mObj) { + } + + private class GroupUserMappingUpdator implements Runnable { + private final String groupName; + private final Long groupId; + private final String userName; + private final Long userId; + private final boolean isDelete; + private XXGroupUser xxGroupUser; + + GroupUserMappingUpdator(String groupName, Long groupId, String userName, Long userId, XXGroupUser xxGroupUser, boolean isDelete) { + this.groupName = groupName; + this.groupId = groupId; + this.userName = userName; + this.userId = userId; + this.xxGroupUser = xxGroupUser; + this.isDelete = isDelete; + } + + @Override + public void run() { + updateGroupUserMappings(); + } + + private void updateGroupUserMappings() { + logger.debug("==> GroupUserMappingUpdater.updateGroupUserMappings({}, {})", groupName, userName); + + if (isDelete) { + if (xxGroupUser != null) { + getDao().remove(xxGroupUser.getId()); + + logger.debug("createOrDeleteXGroupUsers(): deleted group user mapping with groupname = {} username = {}", groupName, userName); + } + } else { + boolean groupUserMappingExists = true; + + if (xxGroupUser == null) { + xxGroupUser = new XXGroupUser(); + groupUserMappingExists = false; + } + + XXPortalUser xXPortalUser = daoManager.getXXPortalUser().getById(createdByUserId); + + if (xXPortalUser != null) { + xxGroupUser.setAddedByUserId(createdByUserId); + xxGroupUser.setUpdatedByUserId(createdByUserId); + } + + if (groupUserMappingExists) { + xxGroupUser = getDao().update(xxGroupUser); + } else { + VXGroupUser vXGroupUser = new VXGroupUser(); + + vXGroupUser.setUserId(userId); + vXGroupUser.setName(groupName); + vXGroupUser.setParentGroupId(groupId); + + xxGroupUser = mapViewToEntityBean(vXGroupUser, xxGroupUser, 0); + xxGroupUser = getDao().create(xxGroupUser); + } + + logger.debug("createOrDeleteXGroupUsers(): Create or update group user mapping with groupname = {}, username = {}, userId = {}", groupName, userName, xxGroupUser.getUserId()); + } + + logger.debug("<== GroupUserMappingUpdater.updateGroupUserMappings({}, {})", groupName, userName); + } + } } diff --git a/security-admin/src/main/java/org/apache/ranger/service/XGroupUserServiceBase.java b/security-admin/src/main/java/org/apache/ranger/service/XGroupUserServiceBase.java index 3f10abfde3..6ce6b23408 100644 --- a/security-admin/src/main/java/org/apache/ranger/service/XGroupUserServiceBase.java +++ b/security-admin/src/main/java/org/apache/ranger/service/XGroupUserServiceBase.java @@ -17,14 +17,7 @@ * under the License. */ - package org.apache.ranger.service; - -/** - * - */ - -import java.util.ArrayList; -import java.util.List; +package org.apache.ranger.service; import org.apache.ranger.common.AppConstants; import org.apache.ranger.common.SearchCriteria; @@ -35,71 +28,75 @@ import org.apache.ranger.view.VXGroupUser; import org.apache.ranger.view.VXGroupUserList; -public abstract class XGroupUserServiceBase - extends AbstractAuditedResourceService { - public static final String NAME = "XGroupUser"; - - public XGroupUserServiceBase() { - super(AppConstants.CLASS_TYPE_XA_GROUP_USER, AppConstants.CLASS_TYPE_XA_GROUP); - - trxLogAttrs.put("name", new VTrxLogAttr("name", "Group Name")); - } - - @Override - protected T mapViewToEntityBean(V vObj, T mObj, int OPERATION_CONTEXT) { - mObj.setName( vObj.getName()); - mObj.setParentGroupId( vObj.getParentGroupId()); - mObj.setUserId( vObj.getUserId()); - return mObj; - } - - @Override - protected V mapEntityToViewBean(V vObj, T 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 xGroupUserList = new ArrayList(); - - List resultList = searchResources(searchCriteria, - searchFields, sortFields, returnList); - - // Iterate over the result list and create the return list - for (T gjXGroupUser : resultList) { - VXGroupUser vXGroupUser = populateViewBean(gjXGroupUser); - xGroupUserList.add(vXGroupUser); - } - - returnList.setVXGroupUsers(xGroupUserList); - return returnList; - } - - @Override - public String getObjectName(V obj) { - Long userId = obj != null ? obj.getUserId() : null; - XXUser user = userId != null ? daoManager.getXXUser().getById(userId) : null; - - return user != null ? user.getName() : null; - } - - @Override - public String getParentObjectName(V obj, V oldObj) { - Long groupId = getParentObjectId(obj, oldObj); - XXGroup group = groupId != null ? daoManager.getXXGroup().getById(groupId) : null; - - return group != null ? group.getName() : null; - } - - @Override - public Long getParentObjectId(V obj, V oldObj) { - return obj != null ? obj.getParentGroupId() : null; - } +import java.util.ArrayList; +import java.util.List; + +public abstract class XGroupUserServiceBase extends AbstractAuditedResourceService { + public static final String NAME = "XGroupUser"; + + public XGroupUserServiceBase() { + super(AppConstants.CLASS_TYPE_XA_GROUP_USER, AppConstants.CLASS_TYPE_XA_GROUP); + + trxLogAttrs.put("name", new VTrxLogAttr("name", "Group Name")); + } + + /** + * @param searchCriteria + * @return + */ + public VXGroupUserList searchXGroupUsers(SearchCriteria searchCriteria) { + VXGroupUserList returnList = new VXGroupUserList(); + List xGroupUserList = new ArrayList<>(); + List resultList = searchResources(searchCriteria, searchFields, sortFields, returnList); + + // Iterate over the result list and create the return list + for (T gjXGroupUser : resultList) { + VXGroupUser vXGroupUser = populateViewBean(gjXGroupUser); + + xGroupUserList.add(vXGroupUser); + } + + returnList.setVXGroupUsers(xGroupUserList); + + return returnList; + } + + @Override + public String getObjectName(V obj) { + Long userId = obj != null ? obj.getUserId() : null; + XXUser user = userId != null ? daoManager.getXXUser().getById(userId) : null; + + return user != null ? user.getName() : null; + } + + @Override + public String getParentObjectName(V obj, V oldObj) { + Long groupId = getParentObjectId(obj, oldObj); + XXGroup group = groupId != null ? daoManager.getXXGroup().getById(groupId) : null; + + return group != null ? group.getName() : null; + } + + @Override + public Long getParentObjectId(V obj, V oldObj) { + return obj != null ? obj.getParentGroupId() : null; + } + + @Override + protected T mapViewToEntityBean(V vObj, T mObj, int operationContext) { + mObj.setName(vObj.getName()); + mObj.setParentGroupId(vObj.getParentGroupId()); + mObj.setUserId(vObj.getUserId()); + + return mObj; + } + + @Override + protected V mapEntityToViewBean(V vObj, T mObj) { + vObj.setName(mObj.getName()); + vObj.setParentGroupId(mObj.getParentGroupId()); + vObj.setUserId(mObj.getUserId()); + + return vObj; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/service/XModuleDefService.java b/security-admin/src/main/java/org/apache/ranger/service/XModuleDefService.java index 778087902f..015ed65c08 100644 --- a/security-admin/src/main/java/org/apache/ranger/service/XModuleDefService.java +++ b/security-admin/src/main/java/org/apache/ranger/service/XModuleDefService.java @@ -17,11 +17,6 @@ package org.apache.ranger.service; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - import org.apache.ranger.common.RangerConstants; import org.apache.ranger.common.SearchCriteria; import org.apache.ranger.common.SearchField; @@ -39,163 +34,171 @@ import org.springframework.stereotype.Service; import org.springframework.util.CollectionUtils; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + @Service @Scope("singleton") -public class XModuleDefService extends - XModuleDefServiceBase { - - - @Autowired - XUserPermissionService xUserPermService; - - @Autowired - XGroupPermissionService xGrpPermService; - - @Autowired - XUserService xUserService; - - @Autowired - XGroupService xGroupService; - public XModuleDefService() { - searchFields.add(new SearchField("module", "obj.module", - SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.PARTIAL)); - searchFields - .add(new SearchField( - "userName", - "portalUser.loginId", - SearchField.DATA_TYPE.STRING, - SearchField.SEARCH_TYPE.PARTIAL, - " XXPortalUser portalUser, XXUserPermission userPermission", - "obj.id=userPermission.moduleId and portalUser.id=userPermission.userId and userPermission.isAllowed=" - + RangerConstants.IS_ALLOWED)); - searchFields - .add(new SearchField( - "groupName", - "group.name", - SearchField.DATA_TYPE.STRING, - SearchField.SEARCH_TYPE.PARTIAL, - "XXGroup group,XXGroupPermission groupModulePermission", - "obj.id=groupModulePermission.moduleId and groupModulePermission.groupId=group.id and groupModulePermission.isAllowed=" - + RangerConstants.IS_ALLOWED)); - } - - @Override - protected void validateForCreate(VXModuleDef vObj) { - - } - - @Override - protected void validateForUpdate(VXModuleDef vObj, XXModuleDef mObj) { - - } - - @Override - public VXModuleDef populateViewBean(XXModuleDef xObj) { - VXModuleDef vModuleDef = super.populateViewBean(xObj); - Map xXPortalUserIdXXUserMap = xUserService.getXXPortalUserIdXXUserNameMap(); - Map xXGroupMap = xGroupService.getXXGroupIdNameMap(); - List vXUserPermissionList = new ArrayList(); - List vXGroupPermissionList = new ArrayList(); - List xuserPermissionList = daoManager - .getXXUserPermission().findByModuleId(xObj.getId(), false); - List xgroupPermissionList = daoManager - .getXXGroupPermission().findByModuleId(xObj.getId(), false); - if(CollectionUtils.isEmpty(xXPortalUserIdXXUserMap)){ - for (XXUserPermission xUserPerm : xuserPermissionList) { - VXUserPermission vXUserPerm = xUserPermService.populateViewBean(xUserPerm); - vXUserPermissionList.add(vXUserPerm); - } - }else{ - vXUserPermissionList=xUserPermService.getPopulatedVXUserPermissionList(xuserPermissionList,xXPortalUserIdXXUserMap,vModuleDef); - } - if(CollectionUtils.isEmpty(xXGroupMap)){ - for (XXGroupPermission xGrpPerm : xgroupPermissionList) { - VXGroupPermission vXGrpPerm = xGrpPermService.populateViewBean(xGrpPerm); - vXGroupPermissionList.add(vXGrpPerm); - } - }else{ - vXGroupPermissionList=xGrpPermService.getPopulatedVXGroupPermissionList(xgroupPermissionList,xXGroupMap,vModuleDef); - } - vModuleDef.setUserPermList(vXUserPermissionList); - vModuleDef.setGroupPermList(vXGroupPermissionList); - return vModuleDef; - } - - @Override - public VXModuleDefList searchModuleDef(SearchCriteria searchCriteria) { - VXModuleDefList returnList = new VXModuleDefList(); - List vXModuleDefList = new ArrayList(); - searchCriteria.setMaxRows(Integer.MAX_VALUE); - searchCriteria.setDistinct(true); - List resultList = searchResources(searchCriteria, searchFields, sortFields, returnList); - // Filter out duplicate values retrieved from database in case of user & group permission lookup - Map matchModule = new HashMap(); - for (XXModuleDef moduleDef : resultList) { - matchModule.put(moduleDef.getId(), moduleDef); - } - List moduleDefList = new ArrayList(matchModule.values()); - - Map xXPortalUserIdXXUserMap = xUserService.getXXPortalUserIdXXUserNameMap(); - Map xXGroupMap = xGroupService.getXXGroupIdNameMap(); - - // Iterate over the result list and create the return list - for (XXModuleDef gjXModuleDef : moduleDefList) { - VXModuleDef vXModuleDef = populateViewBean(gjXModuleDef, xXPortalUserIdXXUserMap, xXGroupMap, false); - vXModuleDefList.add(vXModuleDef); - } - returnList.setTotalCount(vXModuleDefList.size()); - returnList.setvXModuleDef(vXModuleDefList); - return returnList; - } - - public VXModuleDef populateViewBean(XXModuleDef xObj, Map xXPortalUserIdXXUserMap, - Map xXGroupMap, boolean isUpdate) { - VXModuleDef vModuleDef = super.populateViewBean(xObj); - List vXUserPermissionList = new ArrayList(); - List vXGroupPermissionList = new ArrayList(); - List xuserPermissionList = daoManager.getXXUserPermission().findByModuleId(xObj.getId(),isUpdate); - List xgroupPermissionList = daoManager.getXXGroupPermission().findByModuleId(xObj.getId(),isUpdate); - if (CollectionUtils.isEmpty(xXPortalUserIdXXUserMap)) { - for (XXUserPermission xUserPerm : xuserPermissionList) { - VXUserPermission vXUserPerm = xUserPermService.populateViewBean(xUserPerm); - vXUserPermissionList.add(vXUserPerm); - } - } else { - vXUserPermissionList = xUserPermService.getPopulatedVXUserPermissionList(xuserPermissionList,xXPortalUserIdXXUserMap, vModuleDef); - } - if (CollectionUtils.isEmpty(xXGroupMap)) { - for (XXGroupPermission xGrpPerm : xgroupPermissionList) { - VXGroupPermission vXGrpPerm = xGrpPermService.populateViewBean(xGrpPerm); - vXGroupPermissionList.add(vXGrpPerm); - } - } else { - vXGroupPermissionList = xGrpPermService.getPopulatedVXGroupPermissionList(xgroupPermissionList, xXGroupMap,vModuleDef); - } - vModuleDef.setUserPermList(vXUserPermissionList); - vModuleDef.setGroupPermList(vXGroupPermissionList); - return vModuleDef; - } - - public VXModulePermissionList searchModuleDefList(SearchCriteria searchCriteria) { - VXModulePermissionList returnList = new VXModulePermissionList(); - List vXModulePermissionList = new ArrayList(); - searchCriteria.setMaxRows(Integer.MAX_VALUE); - searchCriteria.setDistinct(true); - List moduleDefList = searchResources(searchCriteria, searchFields, sortFields, returnList); - - // Iterate over the result list and create the return list - for (XXModuleDef gjXModuleDef : moduleDefList) { - VXModulePermission obj = new VXModulePermission(); - obj.setId(gjXModuleDef.getId()); - obj.setModule(gjXModuleDef.getModule()); - List userNameList = daoManager.getXXUserPermission().findModuleUsersByModuleId(gjXModuleDef.getId()); - List groupNameList = daoManager.getXXGroupPermission().findModuleGroupsByModuleId(gjXModuleDef.getId()); - obj.setUserNameList(userNameList); - obj.setGroupNameList(groupNameList); - vXModulePermissionList.add(obj); - } - returnList.setTotalCount(vXModulePermissionList.size()); - returnList.setvXModulePermissionList(vXModulePermissionList); - return returnList; - } +public class XModuleDefService extends XModuleDefServiceBase { + @Autowired + XUserPermissionService xUserPermService; + + @Autowired + XGroupPermissionService xGrpPermService; + + @Autowired + XUserService xUserService; + + @Autowired + XGroupService xGroupService; + + public XModuleDefService() { + searchFields.add(new SearchField("module", "obj.module", SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.PARTIAL)); + searchFields.add(new SearchField("userName", "portalUser.loginId", SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.PARTIAL, " XXPortalUser portalUser, XXUserPermission userPermission", "obj.id=userPermission.moduleId and portalUser.id=userPermission.userId and userPermission.isAllowed=" + RangerConstants.IS_ALLOWED)); + searchFields.add(new SearchField("groupName", "group.name", SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.PARTIAL, "XXGroup group,XXGroupPermission groupModulePermission", "obj.id=groupModulePermission.moduleId and groupModulePermission.groupId=group.id and groupModulePermission.isAllowed=" + RangerConstants.IS_ALLOWED)); + } + + @Override + public VXModuleDefList searchModuleDef(SearchCriteria searchCriteria) { + VXModuleDefList returnList = new VXModuleDefList(); + List vXModuleDefList = new ArrayList<>(); + + searchCriteria.setMaxRows(Integer.MAX_VALUE); + searchCriteria.setDistinct(true); + + List resultList = searchResources(searchCriteria, searchFields, sortFields, returnList); + + // Filter out duplicate values retrieved from database in case of user & group permission lookup + Map matchModule = new HashMap<>(); + + for (XXModuleDef moduleDef : resultList) { + matchModule.put(moduleDef.getId(), moduleDef); + } + + List moduleDefList = new ArrayList<>(matchModule.values()); + Map xXPortalUserIdXXUserMap = xUserService.getXXPortalUserIdXXUserNameMap(); + Map xXGroupMap = xGroupService.getXXGroupIdNameMap(); + + // Iterate over the result list and create the return list + for (XXModuleDef gjXModuleDef : moduleDefList) { + VXModuleDef vXModuleDef = populateViewBean(gjXModuleDef, xXPortalUserIdXXUserMap, xXGroupMap, false); + + vXModuleDefList.add(vXModuleDef); + } + + returnList.setTotalCount(vXModuleDefList.size()); + returnList.setvXModuleDef(vXModuleDefList); + + return returnList; + } + + public VXModuleDef populateViewBean(XXModuleDef xObj, Map xXPortalUserIdXXUserMap, Map xXGroupMap, boolean isUpdate) { + VXModuleDef vModuleDef = super.populateViewBean(xObj); + List vXUserPermissionList = new ArrayList<>(); + List vXGroupPermissionList = new ArrayList<>(); + List xuserPermissionList = daoManager.getXXUserPermission().findByModuleId(xObj.getId(), isUpdate); + List xgroupPermissionList = daoManager.getXXGroupPermission().findByModuleId(xObj.getId(), isUpdate); + + if (CollectionUtils.isEmpty(xXPortalUserIdXXUserMap)) { + for (XXUserPermission xUserPerm : xuserPermissionList) { + VXUserPermission vXUserPerm = xUserPermService.populateViewBean(xUserPerm); + + vXUserPermissionList.add(vXUserPerm); + } + } else { + vXUserPermissionList = xUserPermService.getPopulatedVXUserPermissionList(xuserPermissionList, xXPortalUserIdXXUserMap, vModuleDef); + } + + if (CollectionUtils.isEmpty(xXGroupMap)) { + for (XXGroupPermission xGrpPerm : xgroupPermissionList) { + VXGroupPermission vXGrpPerm = xGrpPermService.populateViewBean(xGrpPerm); + + vXGroupPermissionList.add(vXGrpPerm); + } + } else { + vXGroupPermissionList = xGrpPermService.getPopulatedVXGroupPermissionList(xgroupPermissionList, xXGroupMap, vModuleDef); + } + + vModuleDef.setUserPermList(vXUserPermissionList); + vModuleDef.setGroupPermList(vXGroupPermissionList); + + return vModuleDef; + } + + public VXModulePermissionList searchModuleDefList(SearchCriteria searchCriteria) { + VXModulePermissionList returnList = new VXModulePermissionList(); + List vXModulePermissionList = new ArrayList<>(); + + searchCriteria.setMaxRows(Integer.MAX_VALUE); + searchCriteria.setDistinct(true); + + List moduleDefList = searchResources(searchCriteria, searchFields, sortFields, returnList); + + // Iterate over the result list and create the return list + for (XXModuleDef gjXModuleDef : moduleDefList) { + VXModulePermission obj = new VXModulePermission(); + + obj.setId(gjXModuleDef.getId()); + obj.setModule(gjXModuleDef.getModule()); + + List userNameList = daoManager.getXXUserPermission().findModuleUsersByModuleId(gjXModuleDef.getId()); + List groupNameList = daoManager.getXXGroupPermission().findModuleGroupsByModuleId(gjXModuleDef.getId()); + + obj.setUserNameList(userNameList); + obj.setGroupNameList(groupNameList); + + vXModulePermissionList.add(obj); + } + + returnList.setTotalCount(vXModulePermissionList.size()); + returnList.setvXModulePermissionList(vXModulePermissionList); + + return returnList; + } + + @Override + public VXModuleDef populateViewBean(XXModuleDef xObj) { + VXModuleDef vModuleDef = super.populateViewBean(xObj); + Map xXPortalUserIdXXUserMap = xUserService.getXXPortalUserIdXXUserNameMap(); + Map xXGroupMap = xGroupService.getXXGroupIdNameMap(); + List vXUserPermissionList = new ArrayList<>(); + List vXGroupPermissionList = new ArrayList<>(); + List xuserPermissionList = daoManager.getXXUserPermission().findByModuleId(xObj.getId(), false); + List xgroupPermissionList = daoManager.getXXGroupPermission().findByModuleId(xObj.getId(), false); + + if (CollectionUtils.isEmpty(xXPortalUserIdXXUserMap)) { + for (XXUserPermission xUserPerm : xuserPermissionList) { + VXUserPermission vXUserPerm = xUserPermService.populateViewBean(xUserPerm); + + vXUserPermissionList.add(vXUserPerm); + } + } else { + vXUserPermissionList = xUserPermService.getPopulatedVXUserPermissionList(xuserPermissionList, xXPortalUserIdXXUserMap, vModuleDef); + } + + if (CollectionUtils.isEmpty(xXGroupMap)) { + for (XXGroupPermission xGrpPerm : xgroupPermissionList) { + VXGroupPermission vXGrpPerm = xGrpPermService.populateViewBean(xGrpPerm); + + vXGroupPermissionList.add(vXGrpPerm); + } + } else { + vXGroupPermissionList = xGrpPermService.getPopulatedVXGroupPermissionList(xgroupPermissionList, xXGroupMap, vModuleDef); + } + + vModuleDef.setUserPermList(vXUserPermissionList); + vModuleDef.setGroupPermList(vXGroupPermissionList); + + return vModuleDef; + } + + @Override + protected void validateForCreate(VXModuleDef vObj) { + } + + @Override + protected void validateForUpdate(VXModuleDef vObj, XXModuleDef mObj) { + } } diff --git a/security-admin/src/main/java/org/apache/ranger/service/XModuleDefServiceBase.java b/security-admin/src/main/java/org/apache/ranger/service/XModuleDefServiceBase.java index adf43586b6..c1b4339e70 100644 --- a/security-admin/src/main/java/org/apache/ranger/service/XModuleDefServiceBase.java +++ b/security-admin/src/main/java/org/apache/ranger/service/XModuleDefServiceBase.java @@ -19,62 +19,67 @@ package org.apache.ranger.service; -import java.util.ArrayList; -import java.util.List; - import org.apache.ranger.common.SearchCriteria; import org.apache.ranger.entity.XXModuleDef; import org.apache.ranger.view.VXModuleDef; import org.apache.ranger.view.VXModuleDefList; -import java.util.Map; + +import java.util.ArrayList; import java.util.HashMap; -public abstract class XModuleDefServiceBase - extends AbstractBaseResourceService { - - public static final String NAME = "XModuleDef"; - - public XModuleDefServiceBase() { - - } - - @Override - protected T mapViewToEntityBean(V vObj, T mObj, - int OPERATION_CONTEXT) { - mObj.setModule(vObj.getModule()); - mObj.setUrl(vObj.getUrl()); - return mObj; - } - - @Override - protected V mapEntityToViewBean(V vObj, T mObj) { - vObj.setModule(mObj.getModule()); - vObj.setUrl(mObj.getUrl()); - return vObj; - } - - /** - * @param searchCriteria - * @return - */ - public VXModuleDefList searchModuleDef(SearchCriteria searchCriteria) { - VXModuleDefList returnList = new VXModuleDefList(); - List vXModuleDefList = new ArrayList(); - searchCriteria.setMaxRows(Integer.MAX_VALUE); - List resultList = searchResources(searchCriteria, - searchFields, sortFields, returnList); - Map matchModule = new HashMap(); - for (T moduleDef : resultList) { - matchModule.put(moduleDef.getId(), moduleDef); - } - - List moduleDefList=new ArrayList(matchModule.values()); - // Iterate over the result list and create the return list - for (T gjXModuleDef : moduleDefList) { - VXModuleDef vXModuleDef = populateViewBean(gjXModuleDef); - vXModuleDefList.add(vXModuleDef); - } - returnList.setTotalCount(vXModuleDefList.size()); - returnList.setvXModuleDef(vXModuleDefList); - return returnList; - } +import java.util.List; +import java.util.Map; + +public abstract class XModuleDefServiceBase extends AbstractBaseResourceService { + public static final String NAME = "XModuleDef"; + + public XModuleDefServiceBase() { + } + + /** + * @param searchCriteria + * @return + */ + public VXModuleDefList searchModuleDef(SearchCriteria searchCriteria) { + VXModuleDefList returnList = new VXModuleDefList(); + List vXModuleDefList = new ArrayList<>(); + + searchCriteria.setMaxRows(Integer.MAX_VALUE); + + List resultList = searchResources(searchCriteria, searchFields, sortFields, returnList); + Map matchModule = new HashMap<>(); + + for (T moduleDef : resultList) { + matchModule.put(moduleDef.getId(), moduleDef); + } + + List moduleDefList = new ArrayList<>(matchModule.values()); + // Iterate over the result list and create the return list + + for (T gjXModuleDef : moduleDefList) { + VXModuleDef vXModuleDef = populateViewBean(gjXModuleDef); + + vXModuleDefList.add(vXModuleDef); + } + + returnList.setTotalCount(vXModuleDefList.size()); + returnList.setvXModuleDef(vXModuleDefList); + + return returnList; + } + + @Override + protected T mapViewToEntityBean(V vObj, T mObj, int operationContext) { + mObj.setModule(vObj.getModule()); + mObj.setUrl(vObj.getUrl()); + + return mObj; + } + + @Override + protected V mapEntityToViewBean(V vObj, T mObj) { + vObj.setModule(mObj.getModule()); + vObj.setUrl(mObj.getUrl()); + + return vObj; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/service/XPermMapService.java b/security-admin/src/main/java/org/apache/ranger/service/XPermMapService.java index 764135fd5f..ffbe68aa70 100644 --- a/security-admin/src/main/java/org/apache/ranger/service/XPermMapService.java +++ b/security-admin/src/main/java/org/apache/ranger/service/XPermMapService.java @@ -17,7 +17,7 @@ * under the License. */ - package org.apache.ranger.service; +package org.apache.ranger.service; import org.apache.ranger.common.AppConstants; import org.apache.ranger.common.SearchField; @@ -33,119 +33,126 @@ @Service @Scope("singleton") public class XPermMapService extends XPermMapServiceBase { + @Autowired + XGroupService xGroupService; - @Autowired - XGroupService xGroupService; - - @Autowired - XUserService xUserService; - - - 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; - } - - 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; - } - - @Override - protected XXPermMap mapViewToEntityBean(VXPermMap vObj, XXPermMap mObj, int OPERATION_CONTEXT) { - XXPermMap ret = null; - if(vObj!=null && mObj!=null){ - ret = super.mapViewToEntityBean(vObj, mObj, OPERATION_CONTEXT); - XXPortalUser xXPortalUser=null; - if(ret.getAddedByUserId()==null || ret.getAddedByUserId()==0){ - if(!stringUtil.isEmpty(vObj.getOwner())){ - xXPortalUser=daoManager.getXXPortalUser().findByLoginId(vObj.getOwner()); - if(xXPortalUser!=null){ - ret.setAddedByUserId(xXPortalUser.getId()); - } - } - } - if(ret.getUpdatedByUserId()==null || ret.getUpdatedByUserId()==0){ - if(!stringUtil.isEmpty(vObj.getUpdatedBy())){ - xXPortalUser= daoManager.getXXPortalUser().findByLoginId(vObj.getUpdatedBy()); - if(xXPortalUser!=null){ - ret.setUpdatedByUserId(xXPortalUser.getId()); - } - } - } - } - return ret; - } - - @Override - protected VXPermMap mapEntityToViewBean(VXPermMap vObj, XXPermMap mObj) { - VXPermMap ret = null; - if(mObj!=null && vObj!=null){ + @Autowired + XUserService xUserService; + + 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)); + } + + 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; + } + } + + @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 + protected void validateForCreate(VXPermMap vObj) { + // TODO Auto-generated method stub + } + + @Override + protected void validateForUpdate(VXPermMap vObj, XXPermMap mObj) { + // TODO Auto-generated method stub + } + + @Override + protected XXPermMap mapViewToEntityBean(VXPermMap vObj, XXPermMap mObj, int operationContext) { + XXPermMap ret = null; + + if (vObj != null && mObj != null) { + ret = super.mapViewToEntityBean(vObj, mObj, operationContext); + + if (ret.getAddedByUserId() == null || ret.getAddedByUserId() == 0) { + if (!stringUtil.isEmpty(vObj.getOwner())) { + XXPortalUser xXPortalUser = daoManager.getXXPortalUser().findByLoginId(vObj.getOwner()); + + if (xXPortalUser != null) { + ret.setAddedByUserId(xXPortalUser.getId()); + } + } + } + + if (ret.getUpdatedByUserId() == null || ret.getUpdatedByUserId() == 0) { + if (!stringUtil.isEmpty(vObj.getUpdatedBy())) { + XXPortalUser xXPortalUser = daoManager.getXXPortalUser().findByLoginId(vObj.getUpdatedBy()); + + if (xXPortalUser != null) { + ret.setUpdatedByUserId(xXPortalUser.getId()); + } + } + } + } + + return ret; + } + + @Override + protected VXPermMap mapEntityToViewBean(VXPermMap vObj, XXPermMap mObj) { + VXPermMap ret = null; + + if (mObj != null && vObj != null) { ret = super.mapEntityToViewBean(vObj, mObj); - XXPortalUser xXPortalUser=null; - if(stringUtil.isEmpty(ret.getOwner())){ - xXPortalUser= daoManager.getXXPortalUser().getById(mObj.getAddedByUserId()); - if(xXPortalUser!=null){ - ret.setOwner(xXPortalUser.getLoginId()); - } - } - if(stringUtil.isEmpty(ret.getUpdatedBy())){ - xXPortalUser= daoManager.getXXPortalUser().getById(mObj.getUpdatedByUserId()); - if(xXPortalUser!=null){ - ret.setUpdatedBy(xXPortalUser.getLoginId()); - } - } - } - return ret; - } + + if (stringUtil.isEmpty(ret.getOwner())) { + XXPortalUser xXPortalUser = daoManager.getXXPortalUser().getById(mObj.getAddedByUserId()); + + if (xXPortalUser != null) { + ret.setOwner(xXPortalUser.getLoginId()); + } + } + + if (stringUtil.isEmpty(ret.getUpdatedBy())) { + XXPortalUser xXPortalUser = daoManager.getXXPortalUser().getById(mObj.getUpdatedByUserId()); + + if (xXPortalUser != null) { + ret.setUpdatedBy(xXPortalUser.getLoginId()); + } + } + } + + return ret; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/service/XPermMapServiceBase.java b/security-admin/src/main/java/org/apache/ranger/service/XPermMapServiceBase.java index 2c55774bf6..38aadd9cbc 100644 --- a/security-admin/src/main/java/org/apache/ranger/service/XPermMapServiceBase.java +++ b/security-admin/src/main/java/org/apache/ranger/service/XPermMapServiceBase.java @@ -17,14 +17,7 @@ * under the License. */ - package org.apache.ranger.service; - -/** - * - */ - -import java.util.ArrayList; -import java.util.List; +package org.apache.ranger.service; import org.apache.ranger.common.AppConstants; import org.apache.ranger.common.SearchCriteria; @@ -35,96 +28,100 @@ import org.apache.ranger.view.VXPermMap; import org.apache.ranger.view.VXPermMapList; -public abstract class XPermMapServiceBase - extends AbstractAuditedResourceService { - public static final String NAME = "XPermMap"; - - public XPermMapServiceBase() { - super(AppConstants.CLASS_TYPE_XA_PERM_MAP); - - // 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")); - } - - @Override - protected T mapViewToEntityBean(V vObj, T 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; - } - - @Override - protected V mapEntityToViewBean(V vObj, T 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 xPermMapList = new ArrayList(); - - List resultList = searchResources(searchCriteria, - searchFields, sortFields, returnList); - - // Iterate over the result list and create the return list - for (T gjXPermMap : resultList) { - VXPermMap vXPermMap = populateViewBean(gjXPermMap); - xPermMapList.add(vXPermMap); - } - - returnList.setVXPermMaps(xPermMapList); - return returnList; - } - - @Override - public int getParentObjectType(V obj, V oldObj) { - return obj.getGroupId() != null ? AppConstants.CLASS_TYPE_XA_GROUP : AppConstants.CLASS_TYPE_XA_USER; - } - - @Override - public String getParentObjectName(V obj, V oldObj) { - String ret; - - if (obj.getGroupId() != null) { - XXGroup xGroup = daoManager.getXXGroup().getById(obj.getGroupId()); - - ret = xGroup != null ? xGroup.getName() : null; - } else if (obj.getUserId() != null) { - XXUser xUser = daoManager.getXXUser().getById(obj.getUserId()); - - ret = xUser != null ? xUser.getName() : null; - } else { - ret = null; - } - - return ret; - } - - @Override - public Long getParentObjectId(V obj, V oldObj) { - return obj.getGroupId() != null ? obj.getGroupId() : obj.getUserId(); - } +import java.util.ArrayList; +import java.util.List; + +public abstract class XPermMapServiceBase extends AbstractAuditedResourceService { + public static final String NAME = "XPermMap"; + + public XPermMapServiceBase() { + super(AppConstants.CLASS_TYPE_XA_PERM_MAP); + + // 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")); + } + + /** + * @param searchCriteria + * @return + */ + public VXPermMapList searchXPermMaps(SearchCriteria searchCriteria) { + VXPermMapList returnList = new VXPermMapList(); + List xPermMapList = new ArrayList<>(); + List resultList = searchResources(searchCriteria, searchFields, sortFields, returnList); + + // Iterate over the result list and create the return list + for (T gjXPermMap : resultList) { + VXPermMap vXPermMap = populateViewBean(gjXPermMap); + + xPermMapList.add(vXPermMap); + } + + returnList.setVXPermMaps(xPermMapList); + + return returnList; + } + + @Override + public int getParentObjectType(V obj, V oldObj) { + return obj.getGroupId() != null ? AppConstants.CLASS_TYPE_XA_GROUP : AppConstants.CLASS_TYPE_XA_USER; + } + + @Override + public String getParentObjectName(V obj, V oldObj) { + String ret; + + if (obj.getGroupId() != null) { + XXGroup xGroup = daoManager.getXXGroup().getById(obj.getGroupId()); + + ret = xGroup != null ? xGroup.getName() : null; + } else if (obj.getUserId() != null) { + XXUser xUser = daoManager.getXXUser().getById(obj.getUserId()); + + ret = xUser != null ? xUser.getName() : null; + } else { + ret = null; + } + + return ret; + } + + @Override + public Long getParentObjectId(V obj, V oldObj) { + return obj.getGroupId() != null ? obj.getGroupId() : obj.getUserId(); + } + + @Override + protected T mapViewToEntityBean(V vObj, T mObj, int operationContext) { + 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; + } + + @Override + protected V mapEntityToViewBean(V vObj, T 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; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/service/XPolicyExportAuditService.java b/security-admin/src/main/java/org/apache/ranger/service/XPolicyExportAuditService.java index 01c56e9e16..5796084877 100644 --- a/security-admin/src/main/java/org/apache/ranger/service/XPolicyExportAuditService.java +++ b/security-admin/src/main/java/org/apache/ranger/service/XPolicyExportAuditService.java @@ -17,7 +17,7 @@ * under the License. */ - package org.apache.ranger.service; +package org.apache.ranger.service; import org.apache.ranger.common.SearchField; import org.apache.ranger.common.SearchField.DATA_TYPE; @@ -32,36 +32,25 @@ @Service @Scope("singleton") public class XPolicyExportAuditService extends XPolicyExportAuditServiceBase { - - 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("cluster", "obj.clusterName", - SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.FULL)); - 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 - - } - + 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("cluster", "obj.clusterName", SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.FULL)); + 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 + } } diff --git a/security-admin/src/main/java/org/apache/ranger/service/XPolicyExportAuditServiceBase.java b/security-admin/src/main/java/org/apache/ranger/service/XPolicyExportAuditServiceBase.java index 275da232b9..b3fbc76e93 100644 --- a/security-admin/src/main/java/org/apache/ranger/service/XPolicyExportAuditServiceBase.java +++ b/security-admin/src/main/java/org/apache/ranger/service/XPolicyExportAuditServiceBase.java @@ -17,14 +17,7 @@ * under the License. */ - package org.apache.ranger.service; - -/** - * - */ - -import java.util.ArrayList; -import java.util.List; +package org.apache.ranger.service; import org.apache.ranger.common.MapUtil; import org.apache.ranger.common.SearchCriteria; @@ -33,69 +26,71 @@ import org.apache.ranger.view.VXPolicyExportAudit; import org.apache.ranger.view.VXPolicyExportAuditList; -public abstract class XPolicyExportAuditServiceBase - extends AbstractBaseResourceService { - public static final String NAME = "XPolicyExportAudit"; +import java.util.ArrayList; +import java.util.List; + +public abstract class XPolicyExportAuditServiceBase extends AbstractBaseResourceService { + public static final String NAME = "XPolicyExportAudit"; + + public XPolicyExportAuditServiceBase() { + } - public XPolicyExportAuditServiceBase() { + /** + * @param searchCriteria + * @return + */ + public VXPolicyExportAuditList searchXPolicyExportAudits(SearchCriteria searchCriteria) { + VXPolicyExportAuditList returnList = new VXPolicyExportAuditList(); + List xPolicyExportAuditList = new ArrayList<>(); + List resultList = searchResources(searchCriteria, searchFields, sortFields, returnList); - } + // Iterate over the result list and create the return list + for (T gjXPolicyExportAudit : resultList) { + VXPolicyExportAudit vXPolicyExportAudit = populateViewBean(gjXPolicyExportAudit); + XXService xxService = daoManager.getXXService().findByName(vXPolicyExportAudit.getRepositoryName()); - @Override - protected T mapViewToEntityBean(V vObj, T 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()); - mObj.setClusterName( vObj.getClusterName()); - mObj.setZoneName( vObj.getZoneName()); - mObj.setPolicyVersion( vObj.getPolicyVersion()); - return mObj; - } + if (xxService != null) { + vXPolicyExportAudit.setRepositoryDisplayName(xxService.getDisplayName()); + } - @Override - protected V mapEntityToViewBean(V vObj, T 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()); - vObj.setSyncStatus( MapUtil.getPolicyExportAuditSyncStatus(mObj.getHttpRetCode())); - vObj.setClusterName( mObj.getClusterName()); - vObj.setZoneName( mObj.getZoneName()); - vObj.setPolicyVersion( mObj.getPolicyVersion()); - return vObj; - } + xPolicyExportAuditList.add(vXPolicyExportAudit); + } - /** - * @param searchCriteria - * @return - */ - public VXPolicyExportAuditList searchXPolicyExportAudits(SearchCriteria searchCriteria) { - VXPolicyExportAuditList returnList = new VXPolicyExportAuditList(); - List xPolicyExportAuditList = new ArrayList(); + returnList.setVXPolicyExportAudits(xPolicyExportAuditList); - List resultList = searchResources(searchCriteria, - searchFields, sortFields, returnList); + return returnList; + } - // Iterate over the result list and create the return list - for (T gjXPolicyExportAudit : resultList) { - VXPolicyExportAudit vXPolicyExportAudit = populateViewBean(gjXPolicyExportAudit); - XXService xxService = daoManager.getXXService().findByName(vXPolicyExportAudit.getRepositoryName()); + @Override + protected T mapViewToEntityBean(V vObj, T mObj, int operationContext) { + 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()); + mObj.setClusterName(vObj.getClusterName()); + mObj.setZoneName(vObj.getZoneName()); + mObj.setPolicyVersion(vObj.getPolicyVersion()); - if (xxService != null) { - vXPolicyExportAudit.setRepositoryDisplayName(xxService.getDisplayName()); - } - xPolicyExportAuditList.add(vXPolicyExportAudit); - } + return mObj; + } - returnList.setVXPolicyExportAudits(xPolicyExportAuditList); - return returnList; - } + @Override + protected V mapEntityToViewBean(V vObj, T 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()); + vObj.setSyncStatus(MapUtil.getPolicyExportAuditSyncStatus(mObj.getHttpRetCode())); + vObj.setClusterName(mObj.getClusterName()); + vObj.setZoneName(mObj.getZoneName()); + vObj.setPolicyVersion(mObj.getPolicyVersion()); + return vObj; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/service/XPolicyService.java b/security-admin/src/main/java/org/apache/ranger/service/XPolicyService.java index a2f9dc9af2..34e4da5af2 100644 --- a/security-admin/src/main/java/org/apache/ranger/service/XPolicyService.java +++ b/security-admin/src/main/java/org/apache/ranger/service/XPolicyService.java @@ -19,15 +19,6 @@ package org.apache.ranger.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.ranger.common.AppConstants; import org.apache.ranger.common.DateUtil; @@ -57,700 +48,700 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.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 static org.apache.ranger.service.RangerBaseModelService.OPERATION_CREATE_CONTEXT; @Service public class XPolicyService extends PublicAPIServiceBase { - Logger logger = LoggerFactory.getLogger(XPolicyService.class); - - @Autowired - RESTErrorUtil restErrorUtil; - - @Autowired - StringUtil stringUtil; - - @Autowired - RangerDaoManager 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(StringUtils.trim(vXResource.getPolicyName())); - vXPolicy.setResourceName(vXResource.getName()); - vXPolicy.setDescription(vXResource.getDescription()); - vXPolicy.setRepositoryName(vXResource.getAssetName()); - vXPolicy.setRepositoryType(AppConstants - .getLabelFor_AssetType(vXResource.getAssetType())); - - - List 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(StringUtils.trim(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 == RangerBaseModelService.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 auditList = new ArrayList(); - - 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 permMapList = mapPermObjToPermList( - vXPolicy.getPermMapList(), vXPolicy); - - vXResource.setAuditList(auditList); - vXResource.setPermMapList(permMapList); - - } else if (operationContext == OPERATION_CREATE_CONTEXT) { - if (vXPolicy.getIsAuditEnabled()) { - VXAuditMap vXAuditMap = new VXAuditMap(); - vXAuditMap.setAuditType(AppConstants.XA_AUDIT_TYPE_ALL); - List auditList = new ArrayList(); - auditList.add(vXAuditMap); - - vXResource.setAuditList(auditList); - } - if (!stringUtil.isEmpty(vXPolicy.getPermMapList())) { - List 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 == 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 mapPermObjToPermList(List permObjList, - VXPolicy vXPolicy) { - - Long resId = vXPolicy.getId(); - List permMapList = new ArrayList(); - List updPermMapList = new ArrayList(); - Map newPermMap = new LinkedHashMap(); - Random rand = new Random(); - - Map prevPermMap = getPrevPermMap(resId); - - if (permObjList == null) { - permObjList = new ArrayList(); - } - 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.isEmpty()) { - updPermMapList.addAll(permMapList); - } else { - for (Entry 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 getPrevPermMap(Long resId) { - List xxPermMapList = xaDaoMgr.getXXPermMap() - .findByResourceId(resId); - - Map prevPermMap = new LinkedHashMap(); - - 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 mapPermMapToPermObj(List permMapList) { - - List permObjList = new ArrayList(); - HashMap> sortedPemMap = new HashMap>(); - - if (permMapList != null) { - for (VXPermMap vXPermMap : permMapList) { - - String permGrp = vXPermMap.getPermGroup(); - List sortedList = sortedPemMap.get(permGrp); - if (sortedList == null) { - sortedList = new ArrayList(); - sortedPemMap.put(permGrp, sortedList); - } - sortedList.add(vXPermMap); - } - } - - for (Entry> entry : sortedPemMap.entrySet()) { - VXPermObj vXPermObj = new VXPermObj(); - List userList = new ArrayList(); - List groupList = new ArrayList(); - List permList = new ArrayList(); - String ipAddress = ""; - - List 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 policyList = new ArrayList(); - for (VXResource vXAsset : vXResourceList.getVXResources()) { - VXPolicy vXRepo = mapXAToPublicObject(vXAsset); - policyList.add(vXRepo); - } - VXPolicyList vXPolicyList = new VXPolicyList(policyList); - return vXPolicyList; - } - - private List mapPermObjToPermList(List permObjList) { - - List permMapList = new ArrayList(); - 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 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 updatedPermMapList = new ArrayList(); - - SearchCriteria searchCriteria = new SearchCriteria(); - searchCriteria.addParam("resourceId", resId); - VXPermMapList currentPermMaps = xPermMapService - .searchXPermMaps(searchCriteria); - - List currentPermMapList = currentPermMaps.getVXPermMaps(); - HashMap> userPermMap = new HashMap>(); - - 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 permList = userPermMap.get(uniKey); - if (permList == null) { - permList = new ArrayList(); - userPermMap.put(uniKey, permList); - } - permList.add(""+permType); - - if (stringUtil.isEmpty(ipAddress)) { - permList.add(ipAddress); - } - - } - - List> masterKeyList = new ArrayList>(); - List proceedKeyList = new ArrayList(); - for (Entry> upMap : userPermMap.entrySet()) { - - if (proceedKeyList.contains(upMap.getKey())) { - continue; - } - - List keyList = new ArrayList(); - keyList.add(upMap.getKey()); - proceedKeyList.add(upMap.getKey()); - - for (Entry> 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 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; - } + Logger logger = LoggerFactory.getLogger(XPolicyService.class); + + private static final String uniqueKeySeparator = "_"; + + @Autowired + RESTErrorUtil restErrorUtil; + + @Autowired + StringUtil stringUtil; + + @Autowired + RangerDaoManager xaDaoMgr; + + @Autowired + XPermMapService xPermMapService; + + @Autowired + XAuditMapService xAuditMapService; + + @Autowired + XResourceService xResourceService; + + String version; + + public XPolicyService() { + version = PropertiesUtil.getProperty("maven.project.version", ""); + } + + public VXPolicy mapXAToPublicObject(VXResource vXResource) { + VXPolicy vXPolicy = new VXPolicy(); + + vXPolicy = super.mapBaseAttributesToPublicObject(vXResource, vXPolicy); + + vXPolicy.setPolicyName(StringUtils.trim(vXResource.getPolicyName())); + vXPolicy.setResourceName(vXResource.getName()); + vXPolicy.setDescription(vXResource.getDescription()); + vXPolicy.setRepositoryName(vXResource.getAssetName()); + vXPolicy.setRepositoryType(AppConstants.getLabelFor_AssetType(vXResource.getAssetType())); + + List 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 = vXResource.getResourceStatus() != AppConstants.STATUS_DISABLED && vXResource.getResourceStatus() != AppConstants.STATUS_DELETED; + + vXPolicy.setIsEnabled(enable); + + boolean auditEnable = !stringUtil.isEmpty(vXResource.getAuditList()); + + 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(StringUtils.trim(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 == RangerBaseModelService.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 auditList = new ArrayList<>(); + + 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 permMapList = mapPermObjToPermList(vXPolicy.getPermMapList(), vXPolicy); + + vXResource.setAuditList(auditList); + vXResource.setPermMapList(permMapList); + } else if (operationContext == OPERATION_CREATE_CONTEXT) { + if (vXPolicy.getIsAuditEnabled()) { + VXAuditMap vXAuditMap = new VXAuditMap(); + + vXAuditMap.setAuditType(AppConstants.XA_AUDIT_TYPE_ALL); + + List auditList = new ArrayList<>(); + + auditList.add(vXAuditMap); + + vXResource.setAuditList(auditList); + } + + if (!stringUtil.isEmpty(vXPolicy.getPermMapList())) { + List 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 == 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; + } + + public List mapPermMapToPermObj(List permMapList) { + List permObjList = new ArrayList<>(); + HashMap> sortedPemMap = new HashMap<>(); + + if (permMapList != null) { + for (VXPermMap vXPermMap : permMapList) { + String permGrp = vXPermMap.getPermGroup(); + List sortedList = sortedPemMap.computeIfAbsent(permGrp, k -> new ArrayList<>()); + + sortedList.add(vXPermMap); + } + } + + for (Entry> entry : sortedPemMap.entrySet()) { + VXPermObj vXPermObj = new VXPermObj(); + List userList = new ArrayList<>(); + List groupList = new ArrayList<>(); + List permList = new ArrayList<>(); + String ipAddress = ""; + + for (VXPermMap permMap : entry.getValue()) { + 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 policyList = new ArrayList<>(); + + for (VXResource vXAsset : vXResourceList.getVXResources()) { + VXPolicy vXRepo = mapXAToPublicObject(vXAsset); + + policyList.add(vXRepo); + } + + return new VXPolicyList(policyList); + } + + public List updatePermGroup(VXResource vXResource) { + XXResource xxResource = xaDaoMgr.getXXResource().getById(vXResource.getId()); + + if (xxResource == null) { + logger.info("Resource : {} Not Found, while updating PermGroup", vXResource.getPolicyName()); + + throw restErrorUtil.createRESTException("Resource Not found to update PermGroup", MessageEnums.DATA_NOT_FOUND); + } + + Long resId = vXResource.getId(); + List updatedPermMapList = new ArrayList<>(); + SearchCriteria searchCriteria = new SearchCriteria(); + + searchCriteria.addParam("resourceId", resId); + + VXPermMapList currentPermMaps = xPermMapService.searchXPermMaps(searchCriteria); + List currentPermMapList = currentPermMaps.getVXPermMaps(); + HashMap> userPermMap = new HashMap<>(); + + 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 permList = userPermMap.computeIfAbsent(uniKey, k -> new ArrayList<>()); + + permList.add("" + permType); + + if (stringUtil.isEmpty(ipAddress)) { + permList.add(ipAddress); + } + } + + List> masterKeyList = new ArrayList<>(); + List proceedKeyList = new ArrayList<>(); + + for (Entry> upMap : userPermMap.entrySet()) { + if (proceedKeyList.contains(upMap.getKey())) { + continue; + } + + List keyList = new ArrayList<>(); + + keyList.add(upMap.getKey()); + proceedKeyList.add(upMap.getKey()); + + for (Entry> 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 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 : {} Resource Id : {}", key, resId); + } + } + } + + return updatedPermMapList; + } + + 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; + } + + private List mapPermObjToPermList(List permObjList, VXPolicy vXPolicy) { + Long resId = vXPolicy.getId(); + List permMapList = new ArrayList<>(); + List updPermMapList = new ArrayList<>(); + Map newPermMap = new LinkedHashMap<>(); + Random rand = new Random(); + + Map prevPermMap = getPrevPermMap(resId); + + if (permObjList == null) { + permObjList = new ArrayList<>(); + } + + 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); + + String uniqueKey = resId + uniqueKeySeparator + permFor + uniqueKeySeparator + userId + uniqueKeySeparator + permType; + + newPermMap.put(uniqueKey, 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); + + String uniqueKey = resId + uniqueKeySeparator + permFor + uniqueKeySeparator + grpId + uniqueKeySeparator + permType; + + newPermMap.put(uniqueKey, vXPermMap); + } + } + } + } + + // Create Newly added permissions and Remove deleted permissions from DB + if (prevPermMap.isEmpty()) { + updPermMapList.addAll(permMapList); + } else { + for (Entry 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 getPrevPermMap(Long resId) { + List xxPermMapList = xaDaoMgr.getXXPermMap().findByResourceId(resId); + Map prevPermMap = new LinkedHashMap<>(); + + 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).append(uniqueKeySeparator); + uniqueKey.append(permFor).append(uniqueKeySeparator); + + if (userId != null) { + uniqueKey.append(userId).append(uniqueKeySeparator); + } else if (grpId != null) { + uniqueKey.append(grpId).append(uniqueKeySeparator); + } + + uniqueKey.append(permType); + + prevPermMap.put(uniqueKey.toString(), xxPermMap); + } + + return prevPermMap; + } + + private List mapPermObjToPermList(List permObjList) { + List permMapList = new ArrayList<>(); + 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; + } + + 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; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/service/XPortalUserService.java b/security-admin/src/main/java/org/apache/ranger/service/XPortalUserService.java index 9ab886e43e..3c1294e08d 100644 --- a/security-admin/src/main/java/org/apache/ranger/service/XPortalUserService.java +++ b/security-admin/src/main/java/org/apache/ranger/service/XPortalUserService.java @@ -17,7 +17,7 @@ * under the License. */ - package org.apache.ranger.service; +package org.apache.ranger.service; import org.apache.ranger.entity.XXPortalUser; import org.apache.ranger.view.VXPortalUser; @@ -26,166 +26,162 @@ @Service @Scope("singleton") -public class XPortalUserService extends - XPortalUserServiceBase { +public class XPortalUserService extends XPortalUserServiceBase { + public void updateXXPortalUserReferences(long xXPortalUserId) { + daoManager.getXXAsset().updateUserIDReference("added_by_id", xXPortalUserId); + daoManager.getXXAsset().updateUserIDReference("upd_by_id", xXPortalUserId); + daoManager.getXXAuditMap().updateUserIDReference("added_by_id", xXPortalUserId); + daoManager.getXXAuditMap().updateUserIDReference("upd_by_id", xXPortalUserId); + daoManager.getXXAuthSession().updateUserIDReference("added_by_id", xXPortalUserId); + daoManager.getXXAuthSession().updateUserIDReference("upd_by_id", xXPortalUserId); + daoManager.getXXCredentialStore().updateUserIDReference("added_by_id", xXPortalUserId); + daoManager.getXXCredentialStore().updateUserIDReference("upd_by_id", xXPortalUserId); + daoManager.getXXGroup().updateUserIDReference("added_by_id", xXPortalUserId); + daoManager.getXXGroup().updateUserIDReference("upd_by_id", xXPortalUserId); + daoManager.getXXGroupGroup().updateUserIDReference("added_by_id", xXPortalUserId); + daoManager.getXXGroupGroup().updateUserIDReference("upd_by_id", xXPortalUserId); + daoManager.getXXGroupUser().updateUserIDReference("added_by_id", xXPortalUserId); + daoManager.getXXGroupUser().updateUserIDReference("upd_by_id", xXPortalUserId); + daoManager.getXXPermMap().updateUserIDReference("added_by_id", xXPortalUserId); + daoManager.getXXPermMap().updateUserIDReference("upd_by_id", xXPortalUserId); + daoManager.getXXPolicyExportAudit().updateUserIDReference("added_by_id", xXPortalUserId); + daoManager.getXXPolicyExportAudit().updateUserIDReference("upd_by_id", xXPortalUserId); + daoManager.getXXPortalUser().updateUserIDReference("added_by_id", xXPortalUserId); + daoManager.getXXPortalUser().updateUserIDReference("upd_by_id", xXPortalUserId); + daoManager.getXXPortalUserRole().updateUserIDReference("added_by_id", xXPortalUserId); + daoManager.getXXPortalUserRole().updateUserIDReference("upd_by_id", xXPortalUserId); + daoManager.getXXResource().updateUserIDReference("added_by_id", xXPortalUserId); + daoManager.getXXResource().updateUserIDReference("upd_by_id", xXPortalUserId); + daoManager.getXXUser().updateUserIDReference("added_by_id", xXPortalUserId); + daoManager.getXXUser().updateUserIDReference("upd_by_id", xXPortalUserId); + //0.5 + daoManager.getXXServiceDef().updateUserIDReference("added_by_id", xXPortalUserId); + daoManager.getXXServiceDef().updateUserIDReference("upd_by_id", xXPortalUserId); + daoManager.getXXService().updateUserIDReference("added_by_id", xXPortalUserId); + daoManager.getXXService().updateUserIDReference("upd_by_id", xXPortalUserId); + daoManager.getXXPolicy().updateUserIDReference("added_by_id", xXPortalUserId); + daoManager.getXXPolicy().updateUserIDReference("upd_by_id", xXPortalUserId); + daoManager.getXXServiceConfigDef().updateUserIDReference("added_by_id", xXPortalUserId); + daoManager.getXXServiceConfigDef().updateUserIDReference("upd_by_id", xXPortalUserId); + daoManager.getXXResourceDef().updateUserIDReference("added_by_id", xXPortalUserId); + daoManager.getXXResourceDef().updateUserIDReference("upd_by_id", xXPortalUserId); + daoManager.getXXAccessTypeDef().updateUserIDReference("added_by_id", xXPortalUserId); + daoManager.getXXAccessTypeDef().updateUserIDReference("upd_by_id", xXPortalUserId); + daoManager.getXXAccessTypeDefGrants().updateUserIDReference("added_by_id", xXPortalUserId); + daoManager.getXXAccessTypeDefGrants().updateUserIDReference("upd_by_id", xXPortalUserId); + daoManager.getXXPolicyConditionDef().updateUserIDReference("added_by_id", xXPortalUserId); + daoManager.getXXPolicyConditionDef().updateUserIDReference("upd_by_id", xXPortalUserId); + daoManager.getXXContextEnricherDef().updateUserIDReference("added_by_id", xXPortalUserId); + daoManager.getXXContextEnricherDef().updateUserIDReference("upd_by_id", xXPortalUserId); + daoManager.getXXEnumDef().updateUserIDReference("added_by_id", xXPortalUserId); + daoManager.getXXEnumDef().updateUserIDReference("upd_by_id", xXPortalUserId); + daoManager.getXXEnumElementDef().updateUserIDReference("added_by_id", xXPortalUserId); + daoManager.getXXEnumElementDef().updateUserIDReference("upd_by_id", xXPortalUserId); + daoManager.getXXServiceConfigMap().updateUserIDReference("added_by_id", xXPortalUserId); + daoManager.getXXServiceConfigMap().updateUserIDReference("upd_by_id", xXPortalUserId); + daoManager.getXXPolicyResource().updateUserIDReference("added_by_id", xXPortalUserId); + daoManager.getXXPolicyResource().updateUserIDReference("upd_by_id", xXPortalUserId); + daoManager.getXXPolicyResourceMap().updateUserIDReference("added_by_id", xXPortalUserId); + daoManager.getXXPolicyResourceMap().updateUserIDReference("upd_by_id", xXPortalUserId); + daoManager.getXXPolicyItem().updateUserIDReference("added_by_id", xXPortalUserId); + daoManager.getXXPolicyItem().updateUserIDReference("upd_by_id", xXPortalUserId); + daoManager.getXXPolicyItemAccess().updateUserIDReference("added_by_id", xXPortalUserId); + daoManager.getXXPolicyItemAccess().updateUserIDReference("upd_by_id", xXPortalUserId); + daoManager.getXXPolicyItemCondition().updateUserIDReference("added_by_id", xXPortalUserId); + daoManager.getXXPolicyItemCondition().updateUserIDReference("upd_by_id", xXPortalUserId); + daoManager.getXXPolicyItemUserPerm().updateUserIDReference("added_by_id", xXPortalUserId); + daoManager.getXXPolicyItemUserPerm().updateUserIDReference("upd_by_id", xXPortalUserId); + daoManager.getXXPolicyItemGroupPerm().updateUserIDReference("added_by_id", xXPortalUserId); + daoManager.getXXPolicyItemGroupPerm().updateUserIDReference("upd_by_id", xXPortalUserId); + daoManager.getXXModuleDef().updateUserIDReference("added_by_id", xXPortalUserId); + daoManager.getXXModuleDef().updateUserIDReference("upd_by_id", xXPortalUserId); + daoManager.getXXUserPermission().updateUserIDReference("added_by_id", xXPortalUserId); + daoManager.getXXUserPermission().updateUserIDReference("upd_by_id", xXPortalUserId); + daoManager.getXXGroupPermission().updateUserIDReference("added_by_id", xXPortalUserId); + daoManager.getXXGroupPermission().updateUserIDReference("upd_by_id", xXPortalUserId); + //0.6 + daoManager.getXXTagDef().updateUserIDReference("added_by_id", xXPortalUserId); + daoManager.getXXTagDef().updateUserIDReference("upd_by_id", xXPortalUserId); + daoManager.getXXServiceResource().updateUserIDReference("added_by_id", xXPortalUserId); + daoManager.getXXServiceResource().updateUserIDReference("upd_by_id", xXPortalUserId); + daoManager.getXXTag().updateUserIDReference("added_by_id", xXPortalUserId); + daoManager.getXXTag().updateUserIDReference("upd_by_id", xXPortalUserId); + daoManager.getXXTagResourceMap().updateUserIDReference("added_by_id", xXPortalUserId); + daoManager.getXXTagResourceMap().updateUserIDReference("upd_by_id", xXPortalUserId); + //1.0 + daoManager.getXXDataMaskTypeDef().updateUserIDReference("added_by_id", xXPortalUserId); + daoManager.getXXDataMaskTypeDef().updateUserIDReference("upd_by_id", xXPortalUserId); + daoManager.getXXPolicyItemDataMaskInfo().updateUserIDReference("added_by_id", xXPortalUserId); + daoManager.getXXPolicyItemDataMaskInfo().updateUserIDReference("upd_by_id", xXPortalUserId); + daoManager.getXXPolicyItemRowFilterInfo().updateUserIDReference("added_by_id", xXPortalUserId); + daoManager.getXXPolicyItemRowFilterInfo().updateUserIDReference("upd_by_id", xXPortalUserId); + daoManager.getXXUgsyncAuditInfo().updateUserIDReference("added_by_id", xXPortalUserId); + daoManager.getXXUgsyncAuditInfo().updateUserIDReference("upd_by_id", xXPortalUserId); + daoManager.getXXPolicyLabels().updateUserIDReference("added_by_id", xXPortalUserId); + daoManager.getXXPolicyLabels().updateUserIDReference("upd_by_id", xXPortalUserId); + daoManager.getXXPolicyLabelMap().updateUserIDReference("added_by_id", xXPortalUserId); + daoManager.getXXPolicyLabelMap().updateUserIDReference("upd_by_id", xXPortalUserId); + daoManager.getXXPolicyRefCondition().updateUserIDReference("added_by_id", xXPortalUserId); + daoManager.getXXPolicyRefCondition().updateUserIDReference("upd_by_id", xXPortalUserId); + daoManager.getXXPolicyRefGroup().updateUserIDReference("added_by_id", xXPortalUserId); + daoManager.getXXPolicyRefGroup().updateUserIDReference("upd_by_id", xXPortalUserId); + daoManager.getXXPolicyRefDataMaskType().updateUserIDReference("added_by_id", xXPortalUserId); + daoManager.getXXPolicyRefDataMaskType().updateUserIDReference("upd_by_id", xXPortalUserId); + daoManager.getXXPolicyRefResource().updateUserIDReference("added_by_id", xXPortalUserId); + daoManager.getXXPolicyRefResource().updateUserIDReference("upd_by_id", xXPortalUserId); + daoManager.getXXPolicyRefUser().updateUserIDReference("added_by_id", xXPortalUserId); + daoManager.getXXPolicyRefUser().updateUserIDReference("upd_by_id", xXPortalUserId); + daoManager.getXXPolicyRefAccessType().updateUserIDReference("added_by_id", xXPortalUserId); + daoManager.getXXPolicyRefAccessType().updateUserIDReference("upd_by_id", xXPortalUserId); + //2.0 + //Note: skipping x_policy_change_log table as it does not have 'added_by_id' and 'upd_by_id' fields + daoManager.getXXSecurityZoneRefGroup().updateUserIDReference("added_by_id", xXPortalUserId); + daoManager.getXXSecurityZoneRefGroup().updateUserIDReference("upd_by_id", xXPortalUserId); + daoManager.getXXSecurityZoneRefUser().updateUserIDReference("added_by_id", xXPortalUserId); + daoManager.getXXSecurityZoneRefUser().updateUserIDReference("upd_by_id", xXPortalUserId); + daoManager.getXXSecurityZoneRefResource().updateUserIDReference("added_by_id", xXPortalUserId); + daoManager.getXXSecurityZoneRefResource().updateUserIDReference("upd_by_id", xXPortalUserId); + daoManager.getXXSecurityZoneRefTagService().updateUserIDReference("added_by_id", xXPortalUserId); + daoManager.getXXSecurityZoneRefTagService().updateUserIDReference("upd_by_id", xXPortalUserId); + daoManager.getXXSecurityZoneRefService().updateUserIDReference("added_by_id", xXPortalUserId); + daoManager.getXXSecurityZoneRefService().updateUserIDReference("upd_by_id", xXPortalUserId); + daoManager.getXXGlobalState().updateUserIDReference("added_by_id", xXPortalUserId); + daoManager.getXXGlobalState().updateUserIDReference("upd_by_id", xXPortalUserId); + daoManager.getXXSecurityZoneDao().updateUserIDReference("added_by_id", xXPortalUserId); + daoManager.getXXSecurityZoneDao().updateUserIDReference("upd_by_id", xXPortalUserId); + daoManager.getXXRoleRefRole().updateUserIDReference("added_by_id", xXPortalUserId); + daoManager.getXXRoleRefRole().updateUserIDReference("upd_by_id", xXPortalUserId); + daoManager.getXXRoleRefGroup().updateUserIDReference("added_by_id", xXPortalUserId); + daoManager.getXXRoleRefGroup().updateUserIDReference("upd_by_id", xXPortalUserId); + daoManager.getXXRoleRefUser().updateUserIDReference("added_by_id", xXPortalUserId); + daoManager.getXXRoleRefUser().updateUserIDReference("upd_by_id", xXPortalUserId); + daoManager.getXXPolicyRefRole().updateUserIDReference("added_by_id", xXPortalUserId); + daoManager.getXXPolicyRefRole().updateUserIDReference("upd_by_id", xXPortalUserId); + daoManager.getXXRole().updateUserIDReference("added_by_id", xXPortalUserId); + daoManager.getXXRole().updateUserIDReference("upd_by_id", xXPortalUserId); + daoManager.getXXGdsDataset().updateUserIDReference("added_by_id", xXPortalUserId); + daoManager.getXXGdsDataset().updateUserIDReference("upd_by_id", xXPortalUserId); + daoManager.getXXGdsDataShare().updateUserIDReference("added_by_id", xXPortalUserId); + daoManager.getXXGdsDataShare().updateUserIDReference("upd_by_id", xXPortalUserId); + daoManager.getXXGdsProject().updateUserIDReference("added_by_id", xXPortalUserId); + daoManager.getXXGdsProject().updateUserIDReference("upd_by_id", xXPortalUserId); + daoManager.getXXGdsSharedResource().updateUserIDReference("added_by_id", xXPortalUserId); + daoManager.getXXGdsSharedResource().updateUserIDReference("upd_by_id", xXPortalUserId); + daoManager.getXXGdsDataShareInDataset().updateUserIDReference("added_by_id", xXPortalUserId); + daoManager.getXXGdsDataShareInDataset().updateUserIDReference("upd_by_id", xXPortalUserId); + daoManager.getXXGdsDataShareInDataset().updateUserIDReference("approver_id", xXPortalUserId); + daoManager.getXXGdsDatasetInProject().updateUserIDReference("added_by_id", xXPortalUserId); + daoManager.getXXGdsDatasetInProject().updateUserIDReference("upd_by_id", xXPortalUserId); + daoManager.getXXGdsDatasetInProject().updateUserIDReference("approver_id", xXPortalUserId); + } - @Override - protected void validateForCreate(VXPortalUser vObj) { - // TODO Auto-generated method stub + @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 void updateXXPortalUserReferences(long xXPortalUserId){ - daoManager.getXXAsset().updateUserIDReference("added_by_id", xXPortalUserId); - daoManager.getXXAsset().updateUserIDReference("upd_by_id", xXPortalUserId); - daoManager.getXXAuditMap().updateUserIDReference("added_by_id", xXPortalUserId); - daoManager.getXXAuditMap().updateUserIDReference("upd_by_id", xXPortalUserId); - daoManager.getXXAuthSession().updateUserIDReference("added_by_id", xXPortalUserId); - daoManager.getXXAuthSession().updateUserIDReference("upd_by_id", xXPortalUserId); - daoManager.getXXCredentialStore().updateUserIDReference("added_by_id", xXPortalUserId); - daoManager.getXXCredentialStore().updateUserIDReference("upd_by_id", xXPortalUserId); - daoManager.getXXGroup().updateUserIDReference("added_by_id", xXPortalUserId); - daoManager.getXXGroup().updateUserIDReference("upd_by_id", xXPortalUserId); - daoManager.getXXGroupGroup().updateUserIDReference("added_by_id", xXPortalUserId); - daoManager.getXXGroupGroup().updateUserIDReference("upd_by_id", xXPortalUserId); - daoManager.getXXGroupUser().updateUserIDReference("added_by_id", xXPortalUserId); - daoManager.getXXGroupUser().updateUserIDReference("upd_by_id", xXPortalUserId); - daoManager.getXXPermMap().updateUserIDReference("added_by_id", xXPortalUserId); - daoManager.getXXPermMap().updateUserIDReference("upd_by_id", xXPortalUserId); - daoManager.getXXPolicyExportAudit().updateUserIDReference("added_by_id", xXPortalUserId); - daoManager.getXXPolicyExportAudit().updateUserIDReference("upd_by_id", xXPortalUserId); - daoManager.getXXPortalUser().updateUserIDReference("added_by_id", xXPortalUserId); - daoManager.getXXPortalUser().updateUserIDReference("upd_by_id", xXPortalUserId); - daoManager.getXXPortalUserRole().updateUserIDReference("added_by_id", xXPortalUserId); - daoManager.getXXPortalUserRole().updateUserIDReference("upd_by_id", xXPortalUserId); - daoManager.getXXResource().updateUserIDReference("added_by_id", xXPortalUserId); - daoManager.getXXResource().updateUserIDReference("upd_by_id", xXPortalUserId); - daoManager.getXXUser().updateUserIDReference("added_by_id", xXPortalUserId); - daoManager.getXXUser().updateUserIDReference("upd_by_id", xXPortalUserId); - //0.5 - daoManager.getXXServiceDef().updateUserIDReference("added_by_id", xXPortalUserId); - daoManager.getXXServiceDef().updateUserIDReference("upd_by_id", xXPortalUserId); - daoManager.getXXService().updateUserIDReference("added_by_id", xXPortalUserId); - daoManager.getXXService().updateUserIDReference("upd_by_id", xXPortalUserId); - daoManager.getXXPolicy().updateUserIDReference("added_by_id", xXPortalUserId); - daoManager.getXXPolicy().updateUserIDReference("upd_by_id", xXPortalUserId); - daoManager.getXXServiceConfigDef().updateUserIDReference("added_by_id", xXPortalUserId); - daoManager.getXXServiceConfigDef().updateUserIDReference("upd_by_id", xXPortalUserId); - daoManager.getXXResourceDef().updateUserIDReference("added_by_id", xXPortalUserId); - daoManager.getXXResourceDef().updateUserIDReference("upd_by_id", xXPortalUserId); - daoManager.getXXAccessTypeDef().updateUserIDReference("added_by_id", xXPortalUserId); - daoManager.getXXAccessTypeDef().updateUserIDReference("upd_by_id", xXPortalUserId); - daoManager.getXXAccessTypeDefGrants().updateUserIDReference("added_by_id", xXPortalUserId); - daoManager.getXXAccessTypeDefGrants().updateUserIDReference("upd_by_id", xXPortalUserId); - daoManager.getXXPolicyConditionDef().updateUserIDReference("added_by_id", xXPortalUserId); - daoManager.getXXPolicyConditionDef().updateUserIDReference("upd_by_id", xXPortalUserId); - daoManager.getXXContextEnricherDef().updateUserIDReference("added_by_id", xXPortalUserId); - daoManager.getXXContextEnricherDef().updateUserIDReference("upd_by_id", xXPortalUserId); - daoManager.getXXEnumDef().updateUserIDReference("added_by_id", xXPortalUserId); - daoManager.getXXEnumDef().updateUserIDReference("upd_by_id", xXPortalUserId); - daoManager.getXXEnumElementDef().updateUserIDReference("added_by_id", xXPortalUserId); - daoManager.getXXEnumElementDef().updateUserIDReference("upd_by_id", xXPortalUserId); - daoManager.getXXServiceConfigMap().updateUserIDReference("added_by_id", xXPortalUserId); - daoManager.getXXServiceConfigMap().updateUserIDReference("upd_by_id", xXPortalUserId); - daoManager.getXXPolicyResource().updateUserIDReference("added_by_id", xXPortalUserId); - daoManager.getXXPolicyResource().updateUserIDReference("upd_by_id", xXPortalUserId); - daoManager.getXXPolicyResourceMap().updateUserIDReference("added_by_id", xXPortalUserId); - daoManager.getXXPolicyResourceMap().updateUserIDReference("upd_by_id", xXPortalUserId); - daoManager.getXXPolicyItem().updateUserIDReference("added_by_id", xXPortalUserId); - daoManager.getXXPolicyItem().updateUserIDReference("upd_by_id", xXPortalUserId); - daoManager.getXXPolicyItemAccess().updateUserIDReference("added_by_id", xXPortalUserId); - daoManager.getXXPolicyItemAccess().updateUserIDReference("upd_by_id", xXPortalUserId); - daoManager.getXXPolicyItemCondition().updateUserIDReference("added_by_id", xXPortalUserId); - daoManager.getXXPolicyItemCondition().updateUserIDReference("upd_by_id", xXPortalUserId); - daoManager.getXXPolicyItemUserPerm().updateUserIDReference("added_by_id", xXPortalUserId); - daoManager.getXXPolicyItemUserPerm().updateUserIDReference("upd_by_id", xXPortalUserId); - daoManager.getXXPolicyItemGroupPerm().updateUserIDReference("added_by_id", xXPortalUserId); - daoManager.getXXPolicyItemGroupPerm().updateUserIDReference("upd_by_id", xXPortalUserId); - daoManager.getXXModuleDef().updateUserIDReference("added_by_id", xXPortalUserId); - daoManager.getXXModuleDef().updateUserIDReference("upd_by_id", xXPortalUserId); - daoManager.getXXUserPermission().updateUserIDReference("added_by_id", xXPortalUserId); - daoManager.getXXUserPermission().updateUserIDReference("upd_by_id", xXPortalUserId); - daoManager.getXXGroupPermission().updateUserIDReference("added_by_id", xXPortalUserId); - daoManager.getXXGroupPermission().updateUserIDReference("upd_by_id", xXPortalUserId); - //0.6 - daoManager.getXXTagDef().updateUserIDReference("added_by_id", xXPortalUserId); - daoManager.getXXTagDef().updateUserIDReference("upd_by_id", xXPortalUserId); - daoManager.getXXServiceResource().updateUserIDReference("added_by_id", xXPortalUserId); - daoManager.getXXServiceResource().updateUserIDReference("upd_by_id", xXPortalUserId); - daoManager.getXXTag().updateUserIDReference("added_by_id", xXPortalUserId); - daoManager.getXXTag().updateUserIDReference("upd_by_id", xXPortalUserId); - daoManager.getXXTagResourceMap().updateUserIDReference("added_by_id", xXPortalUserId); - daoManager.getXXTagResourceMap().updateUserIDReference("upd_by_id", xXPortalUserId); - //1.0 - daoManager.getXXDataMaskTypeDef().updateUserIDReference("added_by_id", xXPortalUserId); - daoManager.getXXDataMaskTypeDef().updateUserIDReference("upd_by_id", xXPortalUserId); - daoManager.getXXPolicyItemDataMaskInfo().updateUserIDReference("added_by_id", xXPortalUserId); - daoManager.getXXPolicyItemDataMaskInfo().updateUserIDReference("upd_by_id", xXPortalUserId); - daoManager.getXXPolicyItemRowFilterInfo().updateUserIDReference("added_by_id", xXPortalUserId); - daoManager.getXXPolicyItemRowFilterInfo().updateUserIDReference("upd_by_id", xXPortalUserId); - daoManager.getXXUgsyncAuditInfo().updateUserIDReference("added_by_id", xXPortalUserId); - daoManager.getXXUgsyncAuditInfo().updateUserIDReference("upd_by_id", xXPortalUserId); - daoManager.getXXPolicyLabels().updateUserIDReference("added_by_id", xXPortalUserId); - daoManager.getXXPolicyLabels().updateUserIDReference("upd_by_id", xXPortalUserId); - daoManager.getXXPolicyLabelMap().updateUserIDReference("added_by_id", xXPortalUserId); - daoManager.getXXPolicyLabelMap().updateUserIDReference("upd_by_id", xXPortalUserId); - daoManager.getXXPolicyRefCondition().updateUserIDReference("added_by_id", xXPortalUserId); - daoManager.getXXPolicyRefCondition().updateUserIDReference("upd_by_id", xXPortalUserId); - daoManager.getXXPolicyRefGroup().updateUserIDReference("added_by_id", xXPortalUserId); - daoManager.getXXPolicyRefGroup().updateUserIDReference("upd_by_id", xXPortalUserId); - daoManager.getXXPolicyRefDataMaskType().updateUserIDReference("added_by_id", xXPortalUserId); - daoManager.getXXPolicyRefDataMaskType().updateUserIDReference("upd_by_id", xXPortalUserId); - daoManager.getXXPolicyRefResource().updateUserIDReference("added_by_id", xXPortalUserId); - daoManager.getXXPolicyRefResource().updateUserIDReference("upd_by_id", xXPortalUserId); - daoManager.getXXPolicyRefUser().updateUserIDReference("added_by_id", xXPortalUserId); - daoManager.getXXPolicyRefUser().updateUserIDReference("upd_by_id", xXPortalUserId); - daoManager.getXXPolicyRefAccessType().updateUserIDReference("added_by_id", xXPortalUserId); - daoManager.getXXPolicyRefAccessType().updateUserIDReference("upd_by_id", xXPortalUserId); - //2.0 - //Note: skipping x_policy_change_log table as it does not have 'added_by_id' and 'upd_by_id' fields - daoManager.getXXSecurityZoneRefGroup().updateUserIDReference("added_by_id", xXPortalUserId); - daoManager.getXXSecurityZoneRefGroup().updateUserIDReference("upd_by_id", xXPortalUserId); - daoManager.getXXSecurityZoneRefUser().updateUserIDReference("added_by_id", xXPortalUserId); - daoManager.getXXSecurityZoneRefUser().updateUserIDReference("upd_by_id", xXPortalUserId); - daoManager.getXXSecurityZoneRefResource().updateUserIDReference("added_by_id", xXPortalUserId); - daoManager.getXXSecurityZoneRefResource().updateUserIDReference("upd_by_id", xXPortalUserId); - daoManager.getXXSecurityZoneRefTagService().updateUserIDReference("added_by_id", xXPortalUserId); - daoManager.getXXSecurityZoneRefTagService().updateUserIDReference("upd_by_id", xXPortalUserId); - daoManager.getXXSecurityZoneRefService().updateUserIDReference("added_by_id", xXPortalUserId); - daoManager.getXXSecurityZoneRefService().updateUserIDReference("upd_by_id", xXPortalUserId); - daoManager.getXXGlobalState().updateUserIDReference("added_by_id", xXPortalUserId); - daoManager.getXXGlobalState().updateUserIDReference("upd_by_id", xXPortalUserId); - daoManager.getXXSecurityZoneDao().updateUserIDReference("added_by_id", xXPortalUserId); - daoManager.getXXSecurityZoneDao().updateUserIDReference("upd_by_id", xXPortalUserId); - daoManager.getXXRoleRefRole().updateUserIDReference("added_by_id", xXPortalUserId); - daoManager.getXXRoleRefRole().updateUserIDReference("upd_by_id", xXPortalUserId); - daoManager.getXXRoleRefGroup().updateUserIDReference("added_by_id", xXPortalUserId); - daoManager.getXXRoleRefGroup().updateUserIDReference("upd_by_id", xXPortalUserId); - daoManager.getXXRoleRefUser().updateUserIDReference("added_by_id", xXPortalUserId); - daoManager.getXXRoleRefUser().updateUserIDReference("upd_by_id", xXPortalUserId); - daoManager.getXXPolicyRefRole().updateUserIDReference("added_by_id", xXPortalUserId); - daoManager.getXXPolicyRefRole().updateUserIDReference("upd_by_id", xXPortalUserId); - daoManager.getXXRole().updateUserIDReference("added_by_id", xXPortalUserId); - daoManager.getXXRole().updateUserIDReference("upd_by_id", xXPortalUserId); - daoManager.getXXGdsDataset().updateUserIDReference("added_by_id", xXPortalUserId); - daoManager.getXXGdsDataset().updateUserIDReference("upd_by_id", xXPortalUserId); - daoManager.getXXGdsDataShare().updateUserIDReference("added_by_id", xXPortalUserId); - daoManager.getXXGdsDataShare().updateUserIDReference("upd_by_id", xXPortalUserId); - daoManager.getXXGdsProject().updateUserIDReference("added_by_id", xXPortalUserId); - daoManager.getXXGdsProject().updateUserIDReference("upd_by_id", xXPortalUserId); - daoManager.getXXGdsSharedResource().updateUserIDReference("added_by_id", xXPortalUserId); - daoManager.getXXGdsSharedResource().updateUserIDReference("upd_by_id", xXPortalUserId); - daoManager.getXXGdsDataShareInDataset().updateUserIDReference("added_by_id", xXPortalUserId); - daoManager.getXXGdsDataShareInDataset().updateUserIDReference("upd_by_id", xXPortalUserId); - daoManager.getXXGdsDataShareInDataset().updateUserIDReference("approver_id", xXPortalUserId); - daoManager.getXXGdsDatasetInProject().updateUserIDReference("added_by_id", xXPortalUserId); - daoManager.getXXGdsDatasetInProject().updateUserIDReference("upd_by_id", xXPortalUserId); - daoManager.getXXGdsDatasetInProject().updateUserIDReference("approver_id", xXPortalUserId); - } + @Override + protected void validateForUpdate(VXPortalUser vObj, XXPortalUser mObj) { + // TODO Auto-generated method stub + } } diff --git a/security-admin/src/main/java/org/apache/ranger/service/XPortalUserServiceBase.java b/security-admin/src/main/java/org/apache/ranger/service/XPortalUserServiceBase.java index 834d76d889..3b29db937a 100644 --- a/security-admin/src/main/java/org/apache/ranger/service/XPortalUserServiceBase.java +++ b/security-admin/src/main/java/org/apache/ranger/service/XPortalUserServiceBase.java @@ -17,14 +17,7 @@ * under the License. */ - package org.apache.ranger.service; - -/** - * - */ - -import java.util.ArrayList; -import java.util.List; +package org.apache.ranger.service; import org.apache.ranger.common.AppConstants; import org.apache.ranger.common.SearchCriteria; @@ -33,72 +26,75 @@ import org.apache.ranger.view.VXPortalUser; import org.apache.ranger.view.VXPortalUserList; -public abstract class XPortalUserServiceBase - extends AbstractAuditedResourceService { - public static final String NAME = "XPortalUser"; +import java.util.ArrayList; +import java.util.List; + +public abstract class XPortalUserServiceBase extends AbstractAuditedResourceService { + public static final String NAME = "XPortalUser"; + + public XPortalUserServiceBase() { + super(AppConstants.CLASS_TYPE_USER_PROFILE); + + trxLogAttrs.put("loginId", new VTrxLogAttr("loginId", "Login ID", false, true)); + trxLogAttrs.put("status", new VTrxLogAttr("status", "Activation Status")); + trxLogAttrs.put("firstName", new VTrxLogAttr("firstName", "First Name")); + trxLogAttrs.put("lastName", new VTrxLogAttr("lastName", "Last Name")); + trxLogAttrs.put("emailAddress", new VTrxLogAttr("emailAddress", "Email Address")); + trxLogAttrs.put("publicScreenName", new VTrxLogAttr("publicScreenName", "Public Screen Name")); + } - public XPortalUserServiceBase() { - super(AppConstants.CLASS_TYPE_USER_PROFILE); + /** + * @param searchCriteria + * @return + */ + public VXPortalUserList searchXPortalUsers(SearchCriteria searchCriteria) { + VXPortalUserList returnList = new VXPortalUserList(); + List xPortalUserList = new ArrayList<>(); + List resultList = searchResources(searchCriteria, searchFields, sortFields, returnList); - trxLogAttrs.put("loginId", new VTrxLogAttr("loginId", "Login ID", false, true)); - trxLogAttrs.put("status", new VTrxLogAttr("status", "Activation Status")); - trxLogAttrs.put("firstName", new VTrxLogAttr("firstName", "First Name")); - trxLogAttrs.put("lastName", new VTrxLogAttr("lastName", "Last Name")); - trxLogAttrs.put("emailAddress", new VTrxLogAttr("emailAddress", "Email Address")); - trxLogAttrs.put("publicScreenName", new VTrxLogAttr("publicScreenName", "Public Screen Name")); - } + // Iterate over the result list and create the return list + for (T gjXPortalUser : resultList) { + VXPortalUser vXPortalUser = populateViewBean(gjXPortalUser); - @Override - protected T mapViewToEntityBean(V vObj, T 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()); - mObj.setOtherAttributes(vObj.getOtherAttributes()); - mObj.setSyncSource(vObj.getSyncSource()); - return mObj; - } + xPortalUserList.add(vXPortalUser); + } - @Override - protected V mapEntityToViewBean(V vObj, T 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()); - vObj.setOtherAttributes(mObj.getOtherAttributes()); - vObj.setSyncSource(mObj.getSyncSource()); - return vObj; - } + returnList.setVXPortalUsers(xPortalUserList); - /** - * @param searchCriteria - * @return - */ - public VXPortalUserList searchXPortalUsers(SearchCriteria searchCriteria) { - VXPortalUserList returnList = new VXPortalUserList(); - List xPortalUserList = new ArrayList(); + return returnList; + } - List resultList = searchResources(searchCriteria, - searchFields, sortFields, returnList); + @Override + protected T mapViewToEntityBean(V vObj, T mObj, int operationContext) { + 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()); + mObj.setOtherAttributes(vObj.getOtherAttributes()); + mObj.setSyncSource(vObj.getSyncSource()); - // Iterate over the result list and create the return list - for (T gjXPortalUser : resultList) { - VXPortalUser vXPortalUser = populateViewBean(gjXPortalUser); - xPortalUserList.add(vXPortalUser); - } + return mObj; + } - returnList.setVXPortalUsers(xPortalUserList); - return returnList; - } + @Override + protected V mapEntityToViewBean(V vObj, T 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()); + vObj.setOtherAttributes(mObj.getOtherAttributes()); + vObj.setSyncSource(mObj.getSyncSource()); + return vObj; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/service/XRepositoryService.java b/security-admin/src/main/java/org/apache/ranger/service/XRepositoryService.java index 58b6d72c11..5b2659cea4 100644 --- a/security-admin/src/main/java/org/apache/ranger/service/XRepositoryService.java +++ b/security-admin/src/main/java/org/apache/ranger/service/XRepositoryService.java @@ -19,11 +19,6 @@ package org.apache.ranger.service; -import java.util.ArrayList; -import java.util.List; - -import javax.servlet.http.HttpServletRequest; - import org.apache.ranger.common.AppConstants; import org.apache.ranger.common.MessageEnums; import org.apache.ranger.common.PropertiesUtil; @@ -37,96 +32,94 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; +import javax.servlet.http.HttpServletRequest; + +import java.util.ArrayList; +import java.util.List; + @Service -public class XRepositoryService extends - PublicAPIServiceBase { - - @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 == RangerCommonEnums.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()) ? RangerCommonEnums.STATUS_DISABLED - : RangerCommonEnums.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 statusList = new ArrayList(); - if (statusObj == null) { - statusList.add(RangerCommonEnums.STATUS_DISABLED); - statusList.add(RangerCommonEnums.STATUS_ENABLED); - } else { - Boolean status = restErrorUtil.parseBoolean( - request.getParameter("status"), "Invalid value for " - + "status", MessageEnums.INVALID_INPUT_DATA, null, - "status"); - int statusEnum = (status == null || 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 repoList = new ArrayList(); - for (VXAsset vXAsset : vXAssetList.getVXAssets()) { - VXRepository vXRepo = mapXAToPublicObject(vXAsset); - repoList.add(vXRepo); - } - VXRepositoryList vXRepositoryList = new VXRepositoryList(repoList); - return vXRepositoryList; - } +public class XRepositoryService extends PublicAPIServiceBase { + @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 != RangerCommonEnums.STATUS_DISABLED; + + 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()) ? RangerCommonEnums.STATUS_DISABLED : RangerCommonEnums.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 statusList = new ArrayList<>(); + + if (statusObj == null) { + statusList.add(RangerCommonEnums.STATUS_DISABLED); + statusList.add(RangerCommonEnums.STATUS_ENABLED); + } else { + Boolean status = restErrorUtil.parseBoolean(request.getParameter("status"), "Invalid value for status", MessageEnums.INVALID_INPUT_DATA, null, "status"); + int statusEnum = (status == null || !status) ? 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 repoList = new ArrayList<>(); + + for (VXAsset vXAsset : vXAssetList.getVXAssets()) { + VXRepository vXRepo = mapXAToPublicObject(vXAsset); + + repoList.add(vXRepo); + } + return new VXRepositoryList(repoList); + } } diff --git a/security-admin/src/main/java/org/apache/ranger/service/XResourceService.java b/security-admin/src/main/java/org/apache/ranger/service/XResourceService.java index db58f2f93f..9570fe5ef8 100644 --- a/security-admin/src/main/java/org/apache/ranger/service/XResourceService.java +++ b/security-admin/src/main/java/org/apache/ranger/service/XResourceService.java @@ -17,10 +17,7 @@ * under the License. */ - package org.apache.ranger.service; - -import java.util.ArrayList; -import java.util.List; +package org.apache.ranger.service; import org.apache.ranger.biz.RangerBizUtil; import org.apache.ranger.common.AppConstants; @@ -45,401 +42,329 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Service; + +import java.util.ArrayList; +import java.util.List; + @Service @Scope("singleton") -public class XResourceService extends - XResourceServiceBase { - - @Autowired - XPermMapService xPermMapService; - - @Autowired - XAuditMapService xAuditMapService; - - @Autowired - RangerBizUtil xaBizUtil; - - 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(); - if(assetId != null){ - XXAsset xAsset = daoManager.getXXAsset().getById(assetId); - if(xAsset == null){ - 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 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 != null && mObj != null) && - (!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 newAuditMapList = new ArrayList(); - List vxAuditMapList = vXResource.getAuditList(); - if (vxAuditMapList != null) { - for (VXAuditMap vxAuditMap : vxAuditMapList) { - vxAuditMap.setResourceId(resource.getId()); - vxAuditMap = xAuditMapService.createResource(vxAuditMap); - newAuditMapList.add(vxAuditMap); - } - } - - List newPermMapList = new ArrayList(); - List 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 VXResource populateViewBean(XXResource xXResource) { - VXResource vXResource = super.populateViewBean(xXResource); - populateAssetProperties(vXResource); - populatePermList(vXResource); - return vXResource; - } - - private void populateAssetProperties(VXResource vXResource) { - XXAsset xxAsset = daoManager.getXXAsset().getById( - vXResource.getAssetId()); - if (xxAsset != null) { - vXResource.setAssetName(xxAsset.getName()); - vXResource.setAssetType(xxAsset.getAssetType()); +public class XResourceService extends XResourceServiceBase { + @Autowired + XPermMapService xPermMapService; + + @Autowired + XAuditMapService xAuditMapService; + + @Autowired + RangerBizUtil xaBizUtil; + + 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")); + } + + 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; + } + + @Override + public VXResource createResource(VXResource vXResource) { + VXResource resource = super.createResource(vXResource); + List newAuditMapList = new ArrayList<>(); + List vxAuditMapList = vXResource.getAuditList(); + + if (vxAuditMapList != null) { + for (VXAuditMap vxAuditMap : vxAuditMapList) { + vxAuditMap.setResourceId(resource.getId()); + + vxAuditMap = xAuditMapService.createResource(vxAuditMap); + + newAuditMapList.add(vxAuditMap); + } + } + + List newPermMapList = new ArrayList<>(); + List vxPermMapList = vXResource.getPermMapList(); + + if (vxPermMapList != null) { + for (VXPermMap permMap : vxPermMapList) { + if (permMap.getUserId() == null && permMap.getGroupId() == null && 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 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; + } + + @Override + public VXResource populateViewBean(XXResource xXResource) { + VXResource vXResource = super.populateViewBean(xXResource); + + populateAssetProperties(vXResource); + populatePermList(vXResource); + + return vXResource; + } + + @Override + protected void validateForCreate(VXResource vObj) { + if (vObj == null) { + throw restErrorUtil.createRESTException("Policy not provided.", MessageEnums.DATA_NOT_FOUND); } - } - - private void populateAuditList(VXResource vXResource) { - - List xAuditMapList = daoManager.getXXAuditMap().findByResourceId(vXResource.getId()); - List vXAuditMapList = new ArrayList(); - - for (XXAuditMap xAuditMap : xAuditMapList) { - vXAuditMapList.add(xAuditMapService.populateViewBean(xAuditMap)); - } - vXResource.setAuditList(vXAuditMapList); - } - - private void populatePermList(VXResource vXResource) { - - List xPermMapList = daoManager.getXXPermMap().findByResourceId(vXResource.getId()); - List vXPermMapList = new ArrayList(); - - for (XXPermMap xPermMap : xPermMapList) { - vXPermMapList.add(xPermMapService.populateViewBean(xPermMap)); - } - vXResource.setPermMapList(vXPermMapList); - } - - @Override - public VXResourceList searchXResources(SearchCriteria searchCriteria) { - - VXResourceList returnList; - UserSessionBase currentUserSession = ContextUtil - .getCurrentUserSession(); - // If user is system admin - if (currentUserSession != null && 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 resultList = (List) searchResources( - searchCriteria, searchFields, sortFields, returnList); - List adminPermResourceList = new ArrayList(); - 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.isEmpty()) { - populatePageList(adminPermResourceList, startIndex, pageSize, - returnList); - } - } - if(returnList!=null && returnList.getResultSize()>0){ - for (VXResource vXResource : returnList.getVXResources()) { - populateAuditList(vXResource); - } - } - return returnList; - } - - private void populatePageList(List resourceList, - int startIndex, int pageSize, VXResourceList vxResourceList) { - List onePageList = new ArrayList(); - 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) { - XXResource ret = null; - if(vObj!=null && mObj!=null){ - ret = super.mapViewToEntityBean(vObj, mObj, OPERATION_CONTEXT); - ret.setUdfs(vObj.getUdfs()); - XXPortalUser xXPortalUser= null; - if(ret.getAddedByUserId()==null || ret.getAddedByUserId()==0){ - if(!stringUtil.isEmpty(vObj.getOwner())){ - xXPortalUser=daoManager.getXXPortalUser().findByLoginId(vObj.getOwner()); - if(xXPortalUser!=null){ - ret.setAddedByUserId(xXPortalUser.getId()); - } - } - } - if(ret.getUpdatedByUserId()==null || ret.getUpdatedByUserId()==0){ - if(!stringUtil.isEmpty(vObj.getUpdatedBy())){ - xXPortalUser= daoManager.getXXPortalUser().findByLoginId(vObj.getUpdatedBy()); - if(xXPortalUser!=null){ - ret.setUpdatedByUserId(xXPortalUser.getId()); - } - } - } - - } - return ret; - } - - @Override - protected VXResource mapEntityToViewBean(VXResource vObj, XXResource mObj) { - VXResource ret = null; - if(mObj!=null && vObj!=null){ + + Long assetId = vObj.getAssetId(); + + if (assetId != null) { + XXAsset xAsset = daoManager.getXXAsset().getById(assetId); + + if (xAsset == null) { + 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(); + + if (stringUtil.isEmpty(resourceName)) { + logger.error("Resource name not found for : {}", vObj); + + throw restErrorUtil.createRESTException("Please provide valid resources.", MessageEnums.INVALID_INPUT_DATA); + } + } + + @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 != null && mObj != null) && (!vObj.getName().equalsIgnoreCase(mObj.getName()) || vObj.getIsRecursive() != mObj.getIsRecursive() || vObj.getResourceType() != mObj.getResourceType())) { + validateForCreate(vObj); + } + } + + @Override + public VXResourceList searchXResources(SearchCriteria searchCriteria) { + VXResourceList returnList; + UserSessionBase currentUserSession = ContextUtil.getCurrentUserSession(); + + // If user is system admin + if (currentUserSession != null && 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 resultList = searchResources(searchCriteria, searchFields, sortFields, returnList); + List adminPermResourceList = new ArrayList<>(); + + 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.isEmpty()) { + populatePageList(adminPermResourceList, startIndex, pageSize, returnList); + } + } + + if (returnList != null && returnList.getResultSize() > 0) { + for (VXResource vXResource : returnList.getVXResources()) { + populateAuditList(vXResource); + } + } + + return returnList; + } + + @Override + protected XXResource mapViewToEntityBean(VXResource vObj, XXResource mObj, int operationContext) { + XXResource ret = null; + + if (vObj != null && mObj != null) { + ret = super.mapViewToEntityBean(vObj, mObj, operationContext); + + ret.setUdfs(vObj.getUdfs()); + + if (ret.getAddedByUserId() == null || ret.getAddedByUserId() == 0) { + if (!stringUtil.isEmpty(vObj.getOwner())) { + XXPortalUser xXPortalUser = daoManager.getXXPortalUser().findByLoginId(vObj.getOwner()); + + if (xXPortalUser != null) { + ret.setAddedByUserId(xXPortalUser.getId()); + } + } + } + + if (ret.getUpdatedByUserId() == null || ret.getUpdatedByUserId() == 0) { + if (!stringUtil.isEmpty(vObj.getUpdatedBy())) { + XXPortalUser xXPortalUser = daoManager.getXXPortalUser().findByLoginId(vObj.getUpdatedBy()); + + if (xXPortalUser != null) { + ret.setUpdatedByUserId(xXPortalUser.getId()); + } + } + } + } + + return ret; + } + + @Override + protected VXResource mapEntityToViewBean(VXResource vObj, XXResource mObj) { + VXResource ret = null; + + if (mObj != null && vObj != null) { ret = super.mapEntityToViewBean(vObj, mObj); - ret.setUdfs(mObj.getUdfs()); - populateAssetProperties(ret); - XXPortalUser xXPortalUser= null; - if(stringUtil.isEmpty(ret.getOwner())){ - xXPortalUser=daoManager.getXXPortalUser().getById(mObj.getAddedByUserId()); - if(xXPortalUser!=null){ - ret.setOwner(xXPortalUser.getLoginId()); - } - } - if(stringUtil.isEmpty(ret.getUpdatedBy())){ - xXPortalUser= daoManager.getXXPortalUser().getById(mObj.getUpdatedByUserId()); - if(xXPortalUser!=null){ - ret.setUpdatedBy(xXPortalUser.getLoginId()); - } - } - } - return ret; - } - - @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; - } + + ret.setUdfs(mObj.getUdfs()); + + populateAssetProperties(ret); + + if (stringUtil.isEmpty(ret.getOwner())) { + XXPortalUser xXPortalUser = daoManager.getXXPortalUser().getById(mObj.getAddedByUserId()); + + if (xXPortalUser != null) { + ret.setOwner(xXPortalUser.getLoginId()); + } + } + + if (stringUtil.isEmpty(ret.getUpdatedBy())) { + XXPortalUser xXPortalUser = daoManager.getXXPortalUser().getById(mObj.getUpdatedByUserId()); + + if (xXPortalUser != null) { + ret.setUpdatedBy(xXPortalUser.getLoginId()); + } + } + } + + return ret; + } + + private void populateAssetProperties(VXResource vXResource) { + XXAsset xxAsset = daoManager.getXXAsset().getById(vXResource.getAssetId()); + + if (xxAsset != null) { + vXResource.setAssetName(xxAsset.getName()); + vXResource.setAssetType(xxAsset.getAssetType()); + } + } + + private void populateAuditList(VXResource vXResource) { + List xAuditMapList = daoManager.getXXAuditMap().findByResourceId(vXResource.getId()); + List vXAuditMapList = new ArrayList<>(); + + for (XXAuditMap xAuditMap : xAuditMapList) { + vXAuditMapList.add(xAuditMapService.populateViewBean(xAuditMap)); + } + + vXResource.setAuditList(vXAuditMapList); + } + + private void populatePermList(VXResource vXResource) { + List xPermMapList = daoManager.getXXPermMap().findByResourceId(vXResource.getId()); + List vXPermMapList = new ArrayList<>(); + + for (XXPermMap xPermMap : xPermMapList) { + vXPermMapList.add(xPermMapService.populateViewBean(xPermMap)); + } + + vXResource.setPermMapList(vXPermMapList); + } + + private void populatePageList(List resourceList, int startIndex, int pageSize, VXResourceList vxResourceList) { + List onePageList = new ArrayList<>(); + + 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()); + } } diff --git a/security-admin/src/main/java/org/apache/ranger/service/XResourceServiceBase.java b/security-admin/src/main/java/org/apache/ranger/service/XResourceServiceBase.java index f75897fd1d..820e3b877d 100644 --- a/security-admin/src/main/java/org/apache/ranger/service/XResourceServiceBase.java +++ b/security-admin/src/main/java/org/apache/ranger/service/XResourceServiceBase.java @@ -17,14 +17,7 @@ * under the License. */ - package org.apache.ranger.service; - -/** - * - */ - -import java.util.ArrayList; -import java.util.List; +package org.apache.ranger.service; import org.apache.ranger.common.AppConstants; import org.apache.ranger.common.SearchCriteria; @@ -34,113 +27,117 @@ import org.apache.ranger.view.VXResource; import org.apache.ranger.view.VXResourceList; -public abstract class XResourceServiceBase - extends AbstractAuditedResourceService { - public static final String NAME = "XResource"; - - public XResourceServiceBase() { - super(AppConstants.CLASS_TYPE_XA_RESOURCE, AppConstants.CLASS_TYPE_XA_ASSET); - - trxLogAttrs.put("name", new VTrxLogAttr("name", "Resource Path", false, true)); - trxLogAttrs.put("description", new VTrxLogAttr("description", "Policy Description")); - 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")); - trxLogAttrs.put("tables", new VTrxLogAttr("tables", "Tables")); - trxLogAttrs.put("columnFamilies", new VTrxLogAttr("columnFamilies", "Column Families")); - trxLogAttrs.put("columns", new VTrxLogAttr("columns", "Columns")); - trxLogAttrs.put("udfs", new VTrxLogAttr("udfs", "UDF")); - 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")); - trxLogAttrs.put("topologies", new VTrxLogAttr("topologies", "Topologies")); - trxLogAttrs.put("services", new VTrxLogAttr("services", "Services")); - trxLogAttrs.put("assetType", new VTrxLogAttr("assetType", "Repository Type", true)); - } - - @Override - protected T mapViewToEntityBean(V vObj, T 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; - } - - @Override - protected V mapEntityToViewBean(V vObj, T 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 xResourceList = new ArrayList(); - - List resultList = searchResources(searchCriteria, - searchFields, sortFields, returnList); - - // Iterate over the result list and create the return list - for (T gjXResource : resultList) { - VXResource vXResource = populateViewBean(gjXResource); - xResourceList.add(vXResource); - } - - returnList.setVXResources(xResourceList); - return returnList; - } - - @Override - public String getParentObjectName(V obj, V oldObj) { - Long assetId = getParentObjectId(obj, oldObj); - XXAsset xAsset = assetId != null ? daoManager.getXXAsset().getById(assetId) : null; - - return xAsset != null ? xAsset.getName() : null; - } - - @Override - public Long getParentObjectId(V obj, V oldObj) { - return obj != null ? obj.getAssetId() : null; - } +import java.util.ArrayList; +import java.util.List; + +public abstract class XResourceServiceBase extends AbstractAuditedResourceService { + public static final String NAME = "XResource"; + + public XResourceServiceBase() { + super(AppConstants.CLASS_TYPE_XA_RESOURCE, AppConstants.CLASS_TYPE_XA_ASSET); + + trxLogAttrs.put("name", new VTrxLogAttr("name", "Resource Path", false, true)); + trxLogAttrs.put("description", new VTrxLogAttr("description", "Policy Description")); + 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")); + trxLogAttrs.put("tables", new VTrxLogAttr("tables", "Tables")); + trxLogAttrs.put("columnFamilies", new VTrxLogAttr("columnFamilies", "Column Families")); + trxLogAttrs.put("columns", new VTrxLogAttr("columns", "Columns")); + trxLogAttrs.put("udfs", new VTrxLogAttr("udfs", "UDF")); + 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")); + trxLogAttrs.put("topologies", new VTrxLogAttr("topologies", "Topologies")); + trxLogAttrs.put("services", new VTrxLogAttr("services", "Services")); + trxLogAttrs.put("assetType", new VTrxLogAttr("assetType", "Repository Type", true)); + } + + /** + * @param searchCriteria + * @return + */ + public VXResourceList searchXResources(SearchCriteria searchCriteria) { + VXResourceList returnList = new VXResourceList(); + List xResourceList = new ArrayList<>(); + List resultList = searchResources(searchCriteria, searchFields, sortFields, returnList); + + // Iterate over the result list and create the return list + for (T gjXResource : resultList) { + VXResource vXResource = populateViewBean(gjXResource); + + xResourceList.add(vXResource); + } + + returnList.setVXResources(xResourceList); + + return returnList; + } + + @Override + public String getParentObjectName(V obj, V oldObj) { + Long assetId = getParentObjectId(obj, oldObj); + XXAsset xAsset = assetId != null ? daoManager.getXXAsset().getById(assetId) : null; + + return xAsset != null ? xAsset.getName() : null; + } + + @Override + public Long getParentObjectId(V obj, V oldObj) { + return obj != null ? obj.getAssetId() : null; + } + + @Override + protected T mapViewToEntityBean(V vObj, T mObj, int operationContext) { + 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; + } + + @Override + protected V mapEntityToViewBean(V vObj, T 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; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/service/XUgsyncAuditInfoService.java b/security-admin/src/main/java/org/apache/ranger/service/XUgsyncAuditInfoService.java index 6a4f533cd9..f4960e8b42 100644 --- a/security-admin/src/main/java/org/apache/ranger/service/XUgsyncAuditInfoService.java +++ b/security-admin/src/main/java/org/apache/ranger/service/XUgsyncAuditInfoService.java @@ -17,11 +17,16 @@ * under the License. */ - package org.apache.ranger.service; +package org.apache.ranger.service; -import org.apache.ranger.common.*; +import org.apache.ranger.common.ContextUtil; +import org.apache.ranger.common.DateUtil; +import org.apache.ranger.common.JSONUtil; +import org.apache.ranger.common.SearchCriteria; +import org.apache.ranger.common.SearchField; import org.apache.ranger.common.SearchField.DATA_TYPE; import org.apache.ranger.common.SearchField.SEARCH_TYPE; +import org.apache.ranger.common.SortField; import org.apache.ranger.common.SortField.SORT_ORDER; import org.apache.ranger.entity.XXUgsyncAuditInfo; import org.apache.ranger.view.VXUgsyncAuditInfo; @@ -35,128 +40,120 @@ @Service @Scope("singleton") -public class XUgsyncAuditInfoService extends XUgsyncAuditInfoServiceBase{ - @Autowired - JSONUtil jsonUtil; - - public static final String NAME = "XUgsyncAuditInfo"; - - public XUgsyncAuditInfoService() { - sortFields.add(new SortField("eventTime", "obj.eventTime", true, SORT_ORDER.DESC)); - searchFields.add(new SearchField("userName", "obj.userName", - DATA_TYPE.STRING, SEARCH_TYPE.PARTIAL)); - searchFields.add(new SearchField("sessionId", "obj.sessionId", - DATA_TYPE.STRING, SEARCH_TYPE.PARTIAL)); - searchFields.add(new SearchField("syncSource", "obj.syncSource", - DATA_TYPE.STRING, SEARCH_TYPE.PARTIAL)); - searchFields.add(new SearchField("noOfNewUsers", "obj.noOfNewUsers", - DATA_TYPE.INTEGER, SEARCH_TYPE.FULL)); - searchFields.add(new SearchField("noOfNewGroups", "obj.noOfNewGroups", - DATA_TYPE.INTEGER, SEARCH_TYPE.FULL)); - searchFields.add(new SearchField("noOfModifiedUsers", "obj.noOfModifiedUsers", - DATA_TYPE.INTEGER, SEARCH_TYPE.FULL)); - searchFields.add(new SearchField("noOfModifiedGroups", "obj.noOfModifiedGroups", - DATA_TYPE.INTEGER, SEARCH_TYPE.FULL)); - searchFields.add(new SearchField("syncSourceInfo", "obj.syncSourceInfo", DATA_TYPE.STRING, SEARCH_TYPE.PARTIAL)); - 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)); -} +public class XUgsyncAuditInfoService extends XUgsyncAuditInfoServiceBase { + public static final String NAME = "XUgsyncAuditInfo"; + + @Autowired + JSONUtil jsonUtil; + + public XUgsyncAuditInfoService() { + sortFields.add(new SortField("eventTime", "obj.eventTime", true, SORT_ORDER.DESC)); + searchFields.add(new SearchField("userName", "obj.userName", DATA_TYPE.STRING, SEARCH_TYPE.PARTIAL)); + searchFields.add(new SearchField("sessionId", "obj.sessionId", DATA_TYPE.STRING, SEARCH_TYPE.PARTIAL)); + searchFields.add(new SearchField("syncSource", "obj.syncSource", DATA_TYPE.STRING, SEARCH_TYPE.PARTIAL)); + searchFields.add(new SearchField("noOfNewUsers", "obj.noOfNewUsers", DATA_TYPE.INTEGER, SEARCH_TYPE.FULL)); + searchFields.add(new SearchField("noOfNewGroups", "obj.noOfNewGroups", DATA_TYPE.INTEGER, SEARCH_TYPE.FULL)); + searchFields.add(new SearchField("noOfModifiedUsers", "obj.noOfModifiedUsers", DATA_TYPE.INTEGER, SEARCH_TYPE.FULL)); + searchFields.add(new SearchField("noOfModifiedGroups", "obj.noOfModifiedGroups", DATA_TYPE.INTEGER, SEARCH_TYPE.FULL)); + searchFields.add(new SearchField("syncSourceInfo", "obj.syncSourceInfo", DATA_TYPE.STRING, SEARCH_TYPE.PARTIAL)); + 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)); + } - protected XXUgsyncAuditInfo mapViewToEntityBean(VXUgsyncAuditInfo vObj, XXUgsyncAuditInfo mObj, int OPERATION_CONTEXT) { - mObj.setId(vObj.getId()); - mObj.setEventTime(vObj.getEventTime()); - mObj.setUserName(vObj.getUserName()); - mObj.setSyncSource(vObj.getSyncSource()); - mObj.setNoOfNewUsers(vObj.getNoOfNewUsers()); - mObj.setNoOfNewGroups(vObj.getNoOfNewGroups()); - mObj.setNoOfModifiedUsers(vObj.getNoOfModifiedUsers()); - mObj.setNoOfModifiedGroups(vObj.getNoOfModifiedGroups()); - mObj.setSyncSourceInfo(jsonUtil.readMapToString(vObj.getSyncSourceInfo())); - mObj.setSessionId(vObj.getSessionId()); - return mObj; - } - - protected VXUgsyncAuditInfo mapEntityToViewBean(VXUgsyncAuditInfo vObj, XXUgsyncAuditInfo mObj) { - vObj.setId(mObj.getId()); - vObj.setEventTime(mObj.getEventTime()); - vObj.setUserName(mObj.getUserName()); - vObj.setSyncSource(mObj.getSyncSource()); - vObj.setNoOfNewUsers(mObj.getNoOfNewUsers()); - vObj.setNoOfNewGroups(mObj.getNoOfNewGroups()); - vObj.setNoOfModifiedUsers(mObj.getNoOfModifiedUsers()); - vObj.setNoOfModifiedGroups(mObj.getNoOfModifiedGroups()); - String jsonString = mObj.getSyncSourceInfo(); - vObj.setSyncSourceInfo(jsonUtil.jsonToMap(jsonString)); - vObj.setSessionId( mObj.getSessionId()); - - return vObj; - } - - /** - * @param searchCriteria - * @return - */ - public VXUgsyncAuditInfoList searchXUgsyncAuditInfoList(SearchCriteria searchCriteria) { - VXUgsyncAuditInfoList returnList = new VXUgsyncAuditInfoList(); - List xUgsyncAuditInfoList = new ArrayList(); - - List resultList = (List) searchResources(searchCriteria, - searchFields, sortFields, returnList); + /** + * @param searchCriteria + * @return + */ + public VXUgsyncAuditInfoList searchXUgsyncAuditInfoList(SearchCriteria searchCriteria) { + VXUgsyncAuditInfoList returnList = new VXUgsyncAuditInfoList(); + List xUgsyncAuditInfoList = new ArrayList<>(); + List resultList = searchResources(searchCriteria, searchFields, sortFields, returnList); // Iterate over the result list and create the return list for (XXUgsyncAuditInfo gjXUgsyncAuditInfo : resultList) { VXUgsyncAuditInfo vxUgsyncAuditInfo = populateViewBean(gjXUgsyncAuditInfo); - if(vxUgsyncAuditInfo != null) { - xUgsyncAuditInfoList.add(vxUgsyncAuditInfo); + if (vxUgsyncAuditInfo != null) { + xUgsyncAuditInfoList.add(vxUgsyncAuditInfo); } } returnList.setVxUgsyncAuditInfoList(xUgsyncAuditInfoList); + return returnList; } - public VXUgsyncAuditInfoList searchXUgsyncAuditInfoBySyncSource(String syncSource) { - VXUgsyncAuditInfoList returnList = new VXUgsyncAuditInfoList(); - List xUgsyncAuditInfoList = new ArrayList(); - - List resultList = daoManager.getXXUgsyncAuditInfo().findBySyncSource(syncSource); - - // Iterate over the result list and create the return list - for (XXUgsyncAuditInfo gjXUgsyncAuditInfo : resultList) { - VXUgsyncAuditInfo vxUgsyncAuditInfo = populateViewBean(gjXUgsyncAuditInfo); - - if(vxUgsyncAuditInfo != null) { - xUgsyncAuditInfoList.add(vxUgsyncAuditInfo); - } - } - - returnList.setVxUgsyncAuditInfoList(xUgsyncAuditInfoList); - returnList.setTotalCount(xUgsyncAuditInfoList.size()); - returnList.setResultSize(xUgsyncAuditInfoList.size()); - return returnList; - } - - public VXUgsyncAuditInfo createUgsyncAuditInfo(VXUgsyncAuditInfo vxUgsyncAuditInfo) { - - Long sessionId = ContextUtil.getCurrentUserSession() != null ? ContextUtil.getCurrentUserSession().getSessionId() : null; - if (sessionId != null) { - vxUgsyncAuditInfo.setSessionId("" + sessionId); - } - vxUgsyncAuditInfo.setEventTime(DateUtil.getUTCDate()); - vxUgsyncAuditInfo.setUserName(ContextUtil.getCurrentUserLoginId()); - - // Process the sync source information - if (vxUgsyncAuditInfo.getUnixSyncSourceInfo() != null) { - vxUgsyncAuditInfo.setSyncSourceInfo(jsonUtil.jsonToMap(vxUgsyncAuditInfo.getUnixSyncSourceInfo().toString())); - } else if (vxUgsyncAuditInfo.getFileSyncSourceInfo() != null) { - vxUgsyncAuditInfo.setSyncSourceInfo(jsonUtil.jsonToMap(vxUgsyncAuditInfo.getFileSyncSourceInfo().toString())); - } else if (vxUgsyncAuditInfo.getLdapSyncSourceInfo() != null) { - vxUgsyncAuditInfo.setSyncSourceInfo(jsonUtil.jsonToMap(vxUgsyncAuditInfo.getLdapSyncSourceInfo().toString())); - } - - return createResource(vxUgsyncAuditInfo); - } + public VXUgsyncAuditInfoList searchXUgsyncAuditInfoBySyncSource(String syncSource) { + VXUgsyncAuditInfoList returnList = new VXUgsyncAuditInfoList(); + List xUgsyncAuditInfoList = new ArrayList<>(); + List resultList = daoManager.getXXUgsyncAuditInfo().findBySyncSource(syncSource); + + // Iterate over the result list and create the return list + for (XXUgsyncAuditInfo gjXUgsyncAuditInfo : resultList) { + VXUgsyncAuditInfo vxUgsyncAuditInfo = populateViewBean(gjXUgsyncAuditInfo); + + if (vxUgsyncAuditInfo != null) { + xUgsyncAuditInfoList.add(vxUgsyncAuditInfo); + } + } + + returnList.setVxUgsyncAuditInfoList(xUgsyncAuditInfoList); + returnList.setTotalCount(xUgsyncAuditInfoList.size()); + returnList.setResultSize(xUgsyncAuditInfoList.size()); + + return returnList; + } + + public VXUgsyncAuditInfo createUgsyncAuditInfo(VXUgsyncAuditInfo vxUgsyncAuditInfo) { + Long sessionId = ContextUtil.getCurrentUserSession() != null ? ContextUtil.getCurrentUserSession().getSessionId() : null; + + if (sessionId != null) { + vxUgsyncAuditInfo.setSessionId("" + sessionId); + } + + vxUgsyncAuditInfo.setEventTime(DateUtil.getUTCDate()); + vxUgsyncAuditInfo.setUserName(ContextUtil.getCurrentUserLoginId()); + + // Process the sync source information + if (vxUgsyncAuditInfo.getUnixSyncSourceInfo() != null) { + vxUgsyncAuditInfo.setSyncSourceInfo(jsonUtil.jsonToMap(vxUgsyncAuditInfo.getUnixSyncSourceInfo().toString())); + } else if (vxUgsyncAuditInfo.getFileSyncSourceInfo() != null) { + vxUgsyncAuditInfo.setSyncSourceInfo(jsonUtil.jsonToMap(vxUgsyncAuditInfo.getFileSyncSourceInfo().toString())); + } else if (vxUgsyncAuditInfo.getLdapSyncSourceInfo() != null) { + vxUgsyncAuditInfo.setSyncSourceInfo(jsonUtil.jsonToMap(vxUgsyncAuditInfo.getLdapSyncSourceInfo().toString())); + } + + return createResource(vxUgsyncAuditInfo); + } + + protected XXUgsyncAuditInfo mapViewToEntityBean(VXUgsyncAuditInfo vObj, XXUgsyncAuditInfo mObj, int operationContext) { + mObj.setId(vObj.getId()); + mObj.setEventTime(vObj.getEventTime()); + mObj.setUserName(vObj.getUserName()); + mObj.setSyncSource(vObj.getSyncSource()); + mObj.setNoOfNewUsers(vObj.getNoOfNewUsers()); + mObj.setNoOfNewGroups(vObj.getNoOfNewGroups()); + mObj.setNoOfModifiedUsers(vObj.getNoOfModifiedUsers()); + mObj.setNoOfModifiedGroups(vObj.getNoOfModifiedGroups()); + mObj.setSyncSourceInfo(jsonUtil.readMapToString(vObj.getSyncSourceInfo())); + mObj.setSessionId(vObj.getSessionId()); + + return mObj; + } + + protected VXUgsyncAuditInfo mapEntityToViewBean(VXUgsyncAuditInfo vObj, XXUgsyncAuditInfo mObj) { + vObj.setId(mObj.getId()); + vObj.setEventTime(mObj.getEventTime()); + vObj.setUserName(mObj.getUserName()); + vObj.setSyncSource(mObj.getSyncSource()); + vObj.setNoOfNewUsers(mObj.getNoOfNewUsers()); + vObj.setNoOfNewGroups(mObj.getNoOfNewGroups()); + vObj.setNoOfModifiedUsers(mObj.getNoOfModifiedUsers()); + vObj.setNoOfModifiedGroups(mObj.getNoOfModifiedGroups()); + String jsonString = mObj.getSyncSourceInfo(); + vObj.setSyncSourceInfo(jsonUtil.jsonToMap(jsonString)); + vObj.setSessionId(mObj.getSessionId()); + + return vObj; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/service/XUgsyncAuditInfoServiceBase.java b/security-admin/src/main/java/org/apache/ranger/service/XUgsyncAuditInfoServiceBase.java index 18531590fc..be793b299e 100644 --- a/security-admin/src/main/java/org/apache/ranger/service/XUgsyncAuditInfoServiceBase.java +++ b/security-admin/src/main/java/org/apache/ranger/service/XUgsyncAuditInfoServiceBase.java @@ -17,56 +17,50 @@ * under the License. */ - package org.apache.ranger.service; - -/** - * - */ +package org.apache.ranger.service; import org.apache.ranger.entity.XXUgsyncAuditInfo; import org.apache.ranger.view.VXUgsyncAuditInfo; -public abstract class XUgsyncAuditInfoServiceBase - extends AbstractBaseResourceService { - public static final String NAME = "XUgsyncAuditInfo"; - - public XUgsyncAuditInfoServiceBase() { +public abstract class XUgsyncAuditInfoServiceBase extends AbstractBaseResourceService { + public static final String NAME = "XUgsyncAuditInfo"; - } - - @Override - protected T mapViewToEntityBean(V vObj, T mObj, int OPERATION_CONTEXT) { - mObj.setEventTime(vObj.getEventTime()); - mObj.setUserName(vObj.getUserName()); - mObj.setSyncSource(vObj.getSyncSource()); - mObj.setNoOfNewGroups(vObj.getNoOfNewGroups()); - mObj.setNoOfNewUsers(vObj.getNoOfNewUsers()); - mObj.setNoOfModifiedGroups(vObj.getNoOfModifiedGroups()); - mObj.setNoOfModifiedUsers(vObj.getNoOfModifiedUsers()); - return mObj; - } - - @Override - protected V mapEntityToViewBean(V vObj, T mObj) { - vObj.setEventTime( mObj.getEventTime()); - vObj.setUserName( mObj.getUserName()); - vObj.setSyncSource( mObj.getSyncSource()); - vObj.setNoOfNewGroups(mObj.getNoOfNewGroups()); - vObj.setNoOfNewUsers(mObj.getNoOfNewUsers()); - vObj.setNoOfModifiedGroups(mObj.getNoOfModifiedGroups()); - vObj.setNoOfModifiedUsers(mObj.getNoOfModifiedUsers()); - return vObj; - } + public XUgsyncAuditInfoServiceBase() { + } @Override protected void validateForCreate(VXUgsyncAuditInfo viewBaseBean) { // TODO Auto-generated method stub - } @Override protected void validateForUpdate(VXUgsyncAuditInfo viewBaseBean, XXUgsyncAuditInfo t) { // TODO Auto-generated method stub + } + + @Override + protected T mapViewToEntityBean(V vObj, T mObj, int operationContext) { + mObj.setEventTime(vObj.getEventTime()); + mObj.setUserName(vObj.getUserName()); + mObj.setSyncSource(vObj.getSyncSource()); + mObj.setNoOfNewGroups(vObj.getNoOfNewGroups()); + mObj.setNoOfNewUsers(vObj.getNoOfNewUsers()); + mObj.setNoOfModifiedGroups(vObj.getNoOfModifiedGroups()); + mObj.setNoOfModifiedUsers(vObj.getNoOfModifiedUsers()); + + return mObj; + } + + @Override + protected V mapEntityToViewBean(V vObj, T mObj) { + vObj.setEventTime(mObj.getEventTime()); + vObj.setUserName(mObj.getUserName()); + vObj.setSyncSource(mObj.getSyncSource()); + vObj.setNoOfNewGroups(mObj.getNoOfNewGroups()); + vObj.setNoOfNewUsers(mObj.getNoOfNewUsers()); + vObj.setNoOfModifiedGroups(mObj.getNoOfModifiedGroups()); + vObj.setNoOfModifiedUsers(mObj.getNoOfModifiedUsers()); + return vObj; } } diff --git a/security-admin/src/main/java/org/apache/ranger/service/XUserPermissionService.java b/security-admin/src/main/java/org/apache/ranger/service/XUserPermissionService.java index 9042d7080b..05511c9578 100644 --- a/security-admin/src/main/java/org/apache/ranger/service/XUserPermissionService.java +++ b/security-admin/src/main/java/org/apache/ranger/service/XUserPermissionService.java @@ -17,11 +17,6 @@ package org.apache.ranger.service; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - import org.apache.ranger.common.SearchField; import org.apache.ranger.entity.XXModuleDef; import org.apache.ranger.entity.XXPortalUser; @@ -30,78 +25,84 @@ import org.apache.ranger.view.VXUserPermission; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Service; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + @Service @Scope("singleton") -public class XUserPermissionService extends XUserPermissionServiceBase{ - - public XUserPermissionService() { - searchFields.add(new SearchField("id", "obj.id", - SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.FULL)); - - searchFields.add(new SearchField("userPermissionList", "obj.userId", - SearchField.DATA_TYPE.INTEGER, SearchField.SEARCH_TYPE.FULL, - "XXModuleDef xXModuleDef", "xXModuleDef.id = obj.userId ")); - } - - @Override - protected void validateForCreate(VXUserPermission vObj) { - - } - - @Override - protected void validateForUpdate(VXUserPermission vObj, XXUserPermission mObj) { - - } - - @Override - public VXUserPermission populateViewBean(XXUserPermission xObj) { - VXUserPermission vObj = super.populateViewBean(xObj); - - XXPortalUser xPortalUser = daoManager.getXXPortalUser().getById(xObj.getUserId()); - if (xPortalUser != null) { - vObj.setUserName(xPortalUser.getLoginId()); - } - - XXModuleDef xModuleDef = daoManager.getXXModuleDef().getById(xObj.getModuleId()); - if (xModuleDef != null) { - vObj.setModuleName(xModuleDef.getModule()); - } - - return vObj; - } - - public List getPopulatedVXUserPermissionList(List xuserPermissionList, - Map xXPortalUserIdXXUserMap, VXModuleDef vModuleDef) { - List vXUserPermissionList = new ArrayList(); - Object[] xXUser = null; - for (XXUserPermission xuserPermission : xuserPermissionList) { - if (xXPortalUserIdXXUserMap.containsKey(xuserPermission.getUserId())) { - xXUser = xXPortalUserIdXXUserMap.get(xuserPermission.getUserId()); - VXUserPermission vXUserPerm = new VXUserPermission(); - vXUserPerm.setId(xuserPermission.getId()); - vXUserPerm.setUserId((Long) xXUser[1]); - vXUserPerm.setModuleId(xuserPermission.getModuleId()); - vXUserPerm.setIsAllowed(xuserPermission.getIsAllowed()); - vXUserPerm.setCreateDate(xuserPermission.getCreateTime()); - vXUserPerm.setUpdateDate(xuserPermission.getUpdateTime()); - vXUserPerm.setModuleName(vModuleDef.getModule()); - vXUserPerm.setLoginId((String) xXUser[2]); - vXUserPerm.setUserName((String) xXUser[2]); - vXUserPermissionList.add(vXUserPerm); - } - } - return vXUserPermissionList; - } - - @Override - public Map convertVListToVMap(List vObjList) { - Map ret = new HashMap(); - if (vObjList == null) { - return ret; - } - for (VXUserPermission vObj : vObjList) { - ret.put(vObj.getUserId(), vObj); - } - return ret; - } -} \ No newline at end of file +public class XUserPermissionService extends XUserPermissionServiceBase { + public XUserPermissionService() { + searchFields.add(new SearchField("id", "obj.id", SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.FULL)); + + searchFields.add(new SearchField("userPermissionList", "obj.userId", SearchField.DATA_TYPE.INTEGER, SearchField.SEARCH_TYPE.FULL, "XXModuleDef xXModuleDef", "xXModuleDef.id = obj.userId ")); + } + + public List getPopulatedVXUserPermissionList(List xuserPermissionList, Map xXPortalUserIdXXUserMap, VXModuleDef vModuleDef) { + List vXUserPermissionList = new ArrayList<>(); + + for (XXUserPermission xuserPermission : xuserPermissionList) { + if (xXPortalUserIdXXUserMap.containsKey(xuserPermission.getUserId())) { + Object[] xXUser = xXPortalUserIdXXUserMap.get(xuserPermission.getUserId()); + VXUserPermission vXUserPerm = new VXUserPermission(); + + vXUserPerm.setId(xuserPermission.getId()); + vXUserPerm.setUserId((Long) xXUser[1]); + vXUserPerm.setModuleId(xuserPermission.getModuleId()); + vXUserPerm.setIsAllowed(xuserPermission.getIsAllowed()); + vXUserPerm.setCreateDate(xuserPermission.getCreateTime()); + vXUserPerm.setUpdateDate(xuserPermission.getUpdateTime()); + vXUserPerm.setModuleName(vModuleDef.getModule()); + vXUserPerm.setLoginId((String) xXUser[2]); + vXUserPerm.setUserName((String) xXUser[2]); + + vXUserPermissionList.add(vXUserPerm); + } + } + + return vXUserPermissionList; + } + + @Override + public VXUserPermission populateViewBean(XXUserPermission xObj) { + VXUserPermission vObj = super.populateViewBean(xObj); + XXPortalUser xPortalUser = daoManager.getXXPortalUser().getById(xObj.getUserId()); + + if (xPortalUser != null) { + vObj.setUserName(xPortalUser.getLoginId()); + } + + XXModuleDef xModuleDef = daoManager.getXXModuleDef().getById(xObj.getModuleId()); + + if (xModuleDef != null) { + vObj.setModuleName(xModuleDef.getModule()); + } + + return vObj; + } + + @Override + public Map convertVListToVMap(List vObjList) { + Map ret = new HashMap<>(); + + if (vObjList == null) { + return ret; + } + + for (VXUserPermission vObj : vObjList) { + ret.put(vObj.getUserId(), vObj); + } + + return ret; + } + + @Override + protected void validateForCreate(VXUserPermission vObj) { + } + + @Override + protected void validateForUpdate(VXUserPermission vObj, XXUserPermission mObj) { + } +} diff --git a/security-admin/src/main/java/org/apache/ranger/service/XUserPermissionServiceBase.java b/security-admin/src/main/java/org/apache/ranger/service/XUserPermissionServiceBase.java index 3650b8367e..78ece0ebde 100644 --- a/security-admin/src/main/java/org/apache/ranger/service/XUserPermissionServiceBase.java +++ b/security-admin/src/main/java/org/apache/ranger/service/XUserPermissionServiceBase.java @@ -17,9 +17,6 @@ package org.apache.ranger.service; -import java.util.ArrayList; -import java.util.List; - import org.apache.ranger.common.MessageEnums; import org.apache.ranger.common.SearchCriteria; import org.apache.ranger.entity.XXPortalUser; @@ -28,96 +25,90 @@ import org.apache.ranger.view.VXUserPermission; import org.apache.ranger.view.VXUserPermissionList; -public abstract class XUserPermissionServiceBase - extends AbstractBaseResourceService { - - public static final String NAME = "XUserPermission"; - - @Override - protected T mapViewToEntityBean(V vObj, T mObj, int OPERATION_CONTEXT) { - - // Assuming that vObj.userId coming from UI/Client would be of XXUser, but in DB it should be of XXPortalUser so - // have to map XXUser.ID to XXPortalUser.ID and if portalUser does not exist then not allowing to create/update - - XXPortalUser portalUser = daoManager.getXXPortalUser().findByXUserId(vObj.getUserId()); - if (portalUser == null) { - throw restErrorUtil.createRESTException("Invalid UserId: [" + vObj.getUserId() - + "], Please make sure while create/update given userId should be of x_user", - MessageEnums.INVALID_INPUT_DATA); - } - - mObj.setUserId(portalUser.getId()); - mObj.setModuleId(vObj.getModuleId()); - mObj.setIsAllowed(vObj.getIsAllowed()); - - if (OPERATION_CONTEXT == RangerBaseModelService.OPERATION_CREATE_CONTEXT) { - validateXUserPermForCreate(mObj); - } else if (OPERATION_CONTEXT == RangerBaseModelService.OPERATION_UPDATE_CONTEXT) { - validateXUserPermForUpdate(mObj); - } - - return mObj; - } - - @Override - protected V mapEntityToViewBean(V vObj, T mObj) { - - // As XXUserPermission.userID refers to XXPortalUser.ID, But UI/Client expects XXUser.ID so have to map - // XXUserPermission.userID from XXPortalUser.ID to XXUser.ID - XXUser xUser = daoManager.getXXUser().findByPortalUserId(mObj.getUserId()); - Long userId; - if (xUser != null) { - userId = xUser.getId(); - } else { - // In this case rather throwing exception, send it as null - userId = null; - } - vObj.setUserId(userId); - vObj.setModuleId(mObj.getModuleId()); - vObj.setIsAllowed(mObj.getIsAllowed()); - return vObj; - } - - /** - * @param searchCriteria - * @return - */ - public VXUserPermissionList searchXUserPermission(SearchCriteria searchCriteria) { - VXUserPermissionList returnList = new VXUserPermissionList(); - List vXUserPermissions = new ArrayList(); - - List resultList = searchResources( - searchCriteria, searchFields, sortFields, returnList); - - // Iterate over the result list and create the return list - for (T gjXUser : resultList) { - VXUserPermission vXUserPermission = populateViewBean(gjXUser); - vXUserPermissions.add(vXUserPermission); - } - - returnList.setvXModuleDef(vXUserPermissions); - return returnList; - } - - protected void validateXUserPermForCreate(XXUserPermission mObj) { - XXUserPermission xUserPerm = daoManager.getXXUserPermission().findByModuleIdAndPortalUserId(mObj.getUserId(), - mObj.getModuleId()); - if (xUserPerm != null) { - throw restErrorUtil.createRESTException("User with ID [" + mObj.getUserId() + "] " + "is already " - + "assigned to the module with ID [" + mObj.getModuleId() + "]", - MessageEnums.ERROR_DUPLICATE_OBJECT); - } - } - - protected void validateXUserPermForUpdate(XXUserPermission mObj) { - - XXUserPermission xUserPerm = daoManager.getXXUserPermission().findByModuleIdAndPortalUserId(mObj.getUserId(), - mObj.getModuleId()); - if (xUserPerm != null && !xUserPerm.getId().equals(mObj.getId())) { - throw restErrorUtil.createRESTException("User with ID [" + mObj.getUserId() + "] " + "is already " - + "assigned to the module with ID [" + mObj.getModuleId() + "]", - MessageEnums.ERROR_DUPLICATE_OBJECT); - } - } - -} \ No newline at end of file +import java.util.ArrayList; +import java.util.List; + +public abstract class XUserPermissionServiceBase extends AbstractBaseResourceService { + public static final String NAME = "XUserPermission"; + + /** + * @param searchCriteria + * @return + */ + public VXUserPermissionList searchXUserPermission(SearchCriteria searchCriteria) { + VXUserPermissionList returnList = new VXUserPermissionList(); + List vXUserPermissions = new ArrayList<>(); + List resultList = searchResources(searchCriteria, searchFields, sortFields, returnList); + + // Iterate over the result list and create the return list + for (T gjXUser : resultList) { + VXUserPermission vXUserPermission = populateViewBean(gjXUser); + + vXUserPermissions.add(vXUserPermission); + } + + returnList.setvXModuleDef(vXUserPermissions); + + return returnList; + } + + @Override + protected T mapViewToEntityBean(V vObj, T mObj, int operationContext) { + // Assuming that vObj.userId coming from UI/Client would be of XXUser, but in DB it should be of XXPortalUser so + // have to map XXUser.ID to XXPortalUser.ID and if portalUser does not exist then not allowing to create/update + XXPortalUser portalUser = daoManager.getXXPortalUser().findByXUserId(vObj.getUserId()); + + if (portalUser == null) { + throw restErrorUtil.createRESTException("Invalid UserId: [" + vObj.getUserId() + "], Please make sure while create/update given userId should be of x_user", MessageEnums.INVALID_INPUT_DATA); + } + + mObj.setUserId(portalUser.getId()); + mObj.setModuleId(vObj.getModuleId()); + mObj.setIsAllowed(vObj.getIsAllowed()); + + if (operationContext == RangerBaseModelService.OPERATION_CREATE_CONTEXT) { + validateXUserPermForCreate(mObj); + } else if (operationContext == RangerBaseModelService.OPERATION_UPDATE_CONTEXT) { + validateXUserPermForUpdate(mObj); + } + + return mObj; + } + + @Override + protected V mapEntityToViewBean(V vObj, T mObj) { + // As XXUserPermission.userID refers to XXPortalUser.ID, But UI/Client expects XXUser.ID so have to map + // XXUserPermission.userID from XXPortalUser.ID to XXUser.ID + XXUser xUser = daoManager.getXXUser().findByPortalUserId(mObj.getUserId()); + Long userId; + + if (xUser != null) { + userId = xUser.getId(); + } else { + // In this case rather throwing exception, send it as null + userId = null; + } + + vObj.setUserId(userId); + vObj.setModuleId(mObj.getModuleId()); + vObj.setIsAllowed(mObj.getIsAllowed()); + + return vObj; + } + + protected void validateXUserPermForCreate(XXUserPermission mObj) { + XXUserPermission xUserPerm = daoManager.getXXUserPermission().findByModuleIdAndPortalUserId(mObj.getUserId(), mObj.getModuleId()); + + if (xUserPerm != null) { + throw restErrorUtil.createRESTException("User with ID [" + mObj.getUserId() + "] is already assigned to the module with ID [" + mObj.getModuleId() + "]", MessageEnums.ERROR_DUPLICATE_OBJECT); + } + } + + protected void validateXUserPermForUpdate(XXUserPermission mObj) { + XXUserPermission xUserPerm = daoManager.getXXUserPermission().findByModuleIdAndPortalUserId(mObj.getUserId(), mObj.getModuleId()); + + if (xUserPerm != null && !xUserPerm.getId().equals(mObj.getId())) { + throw restErrorUtil.createRESTException("User with ID [" + mObj.getUserId() + "] is already assigned to the module with ID [" + mObj.getModuleId() + "]", MessageEnums.ERROR_DUPLICATE_OBJECT); + } + } +} diff --git a/security-admin/src/main/java/org/apache/ranger/service/XUserService.java b/security-admin/src/main/java/org/apache/ranger/service/XUserService.java index 5053cd6a51..5a2d4ca4ed 100644 --- a/security-admin/src/main/java/org/apache/ranger/service/XUserService.java +++ b/security-admin/src/main/java/org/apache/ranger/service/XUserService.java @@ -17,14 +17,8 @@ * under the License. */ - package org.apache.ranger.service; +package org.apache.ranger.service; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; import org.apache.ranger.common.MessageEnums; import org.apache.ranger.common.PropertiesUtil; import org.apache.ranger.common.RangerCommonEnums; @@ -42,242 +36,257 @@ import org.springframework.stereotype.Service; import org.springframework.util.CollectionUtils; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + @Service @Scope("singleton") public class XUserService extends XUserServiceBase { - private final Long createdByUserId; - - String hiddenPassword; - - 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.STR_LIST, SearchField.SEARCH_TYPE.FULL, - "XXPortalUser xXPortalUser, XXPortalUserRole xXPortalUserRole", - "xXPortalUser.id=xXPortalUserRole.userId and xXPortalUser.loginId = obj.name ")); - - searchFields.add(new SearchField("isVisible", "obj.isVisible", - SearchField.DATA_TYPE.INTEGER, SearchField.SEARCH_TYPE.FULL )); - - searchFields.add(new SearchField("status", "xXPortalUser.status", - SearchField.DATA_TYPE.INTEGER, SearchField.SEARCH_TYPE.FULL, - "XXPortalUser xXPortalUser", "xXPortalUser.loginId = obj.name ")); - searchFields.add(new SearchField("userRole", "xXPortalUserRole.userRole", - SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.FULL, - "XXPortalUser xXPortalUser, XXPortalUserRole xXPortalUserRole", - "xXPortalUser.id=xXPortalUserRole.userId and xXPortalUser.loginId = obj.name ")); - - searchFields.add(new SearchField("syncSource", "obj.syncSource", - SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.PARTIAL)); - - createdByUserId = PropertiesUtil.getLongProperty("ranger.xuser.createdByUserId", 1); - - hiddenPassword = PropertiesUtil.getProperty("ranger.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(vObj.getName() + " 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().equalsIgnoreCase(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 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; - } - XXPortalUser xxPortalUser = daoManager.getXXPortalUser().findByLoginId( - vxUser.getName()); - if (xxPortalUser != null - && xxPortalUser.getUserSource() == RangerCommonEnums.USER_EXTERNAL) { + private final Long createdByUserId; + + String hiddenPassword; + + 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.STR_LIST, SearchField.SEARCH_TYPE.FULL, "XXPortalUser xXPortalUser, XXPortalUserRole xXPortalUserRole", "xXPortalUser.id=xXPortalUserRole.userId and xXPortalUser.loginId = obj.name ")); + + searchFields.add(new SearchField("isVisible", "obj.isVisible", SearchField.DATA_TYPE.INTEGER, SearchField.SEARCH_TYPE.FULL)); + + searchFields.add(new SearchField("status", "xXPortalUser.status", SearchField.DATA_TYPE.INTEGER, SearchField.SEARCH_TYPE.FULL, "XXPortalUser xXPortalUser", "xXPortalUser.loginId = obj.name ")); + searchFields.add(new SearchField("userRole", "xXPortalUserRole.userRole", SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.FULL, "XXPortalUser xXPortalUser, XXPortalUserRole xXPortalUserRole", "xXPortalUser.id=xXPortalUserRole.userId and xXPortalUser.loginId = obj.name ")); + + searchFields.add(new SearchField("syncSource", "obj.syncSource", SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.PARTIAL)); + + createdByUserId = PropertiesUtil.getLongProperty("ranger.xuser.createdByUserId", 1); + + hiddenPassword = PropertiesUtil.getProperty("ranger.password.hidden", "*****"); + + sortFields.add(new SortField("name", "obj.name", true, SortField.SORT_ORDER.ASC)); + } + + 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 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; + } + + XXPortalUser xxPortalUser = daoManager.getXXPortalUser().findByLoginId(vxUser.getName()); + + if (xxPortalUser != null && xxPortalUser.getUserSource() == RangerCommonEnums.USER_EXTERNAL) { vxUser.setIsVisible(xxUser.getIsVisible()); } - 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) { - VXUser ret = super.mapEntityToViewBean(vObj, mObj); - String userName = ret.getName(); - populateUserAttributes(userName, ret); - return ret; - } - - @Override - public VXUser populateViewBean(XXUser xUser) { - VXUser vObj = super.populateViewBean(xUser); - vObj.setIsVisible(xUser.getIsVisible()); - populateGroupList(xUser.getId(), vObj); - return vObj; - } - - private void populateGroupList(Long xUserId, VXUser vObj) { - List xGroupUserList = daoManager.getXXGroupUser() - .findByUserId(xUserId); - Set groupIdList = new LinkedHashSet(); - Set groupNameList = new LinkedHashSet(); - if (xGroupUserList != null) { - for (XXGroupUser xGroupUser : xGroupUserList) { - groupIdList.add(xGroupUser.getParentGroupId()); - groupNameList.add(xGroupUser.getName()); - } - } - List groups = new ArrayList(groupIdList); - List groupNames = new ArrayList(groupNameList); - vObj.setGroupIdList(groups); - vObj.setGroupNameList(groupNames); - } - - private void populateUserAttributes(String userName, VXUser vObj) { - if (userName != null && !userName.isEmpty()) { - List userRoleList =new ArrayList(); - XXPortalUser xXPortalUser = daoManager.getXXPortalUser().findByLoginId(userName); - if (xXPortalUser != null) { - vObj.setFirstName(xXPortalUser.getFirstName()); - vObj.setLastName(xXPortalUser.getLastName()); - vObj.setPassword(PropertiesUtil.getProperty("ranger.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 gjUserRoleList = daoManager.getXXPortalUserRole().findByParentId( - xXPortalUser.getId()); - - for (XXPortalUserRole gjUserRole : gjUserRoleList) { - userRoleList.add(gjUserRole.getUserRole()); - } - } - if(userRoleList==null || userRoleList.isEmpty()){ - userRoleList.add(RangerConstants.ROLE_USER); - } - vObj.setUserRoleList(userRoleList); - } - } - - public Map getXXPortalUserIdXXUserMap(){ - Map xXPortalUserIdXXUserMap=new HashMap(); - try{ - Map xXUserMap=new HashMap(); - List xXUserList=daoManager.getXXUser().getAll(); - if(!CollectionUtils.isEmpty(xXUserList)){ - for(XXUser xxUser:xXUserList){ - xXUserMap.put(xxUser.getName(), xxUser); - } - } - xXUserList=null; - List xXPortalUserList=daoManager.getXXPortalUser().getAll(); - if(!CollectionUtils.isEmpty(xXPortalUserList)){ - for(XXPortalUser xXPortalUser:xXPortalUserList){ - if(xXUserMap.containsKey(xXPortalUser.getLoginId())){ - xXPortalUserIdXXUserMap.put(xXPortalUser.getId(),xXUserMap.get(xXPortalUser.getLoginId())); - } - } - } - }catch(Exception ex){} - return xXPortalUserIdXXUserMap; + + 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); } - public VXUserList lookupXUsers(SearchCriteria searchCriteria, VXUserList vXUserList) { - List xUserList = new ArrayList(); - - @SuppressWarnings("unchecked") - List resultList = (List) searchResources(searchCriteria, searchFields, sortFields, vXUserList); - - for (XXUser xXUser : resultList) { - VXUser vObj = super.mapEntityToViewBean(createViewObject(), xXUser); - vObj.setIsVisible(xXUser.getIsVisible()); - xUserList.add(vObj); - } - - vXUserList.setVXUsers(xUserList); - return vXUserList; - } - - public Map getXXPortalUserIdXXUserNameMap() { - Map xXPortalUserIdXXUserMap = new HashMap(); - try { - List xxUserList = daoManager.getXXUser().getAllUserIdNames(); - if(!CollectionUtils.isEmpty(xxUserList)) { - for (Object[] obj : xxUserList) { - xXPortalUserIdXXUserMap.put((Long)obj[0], obj); - } - } - } catch (Exception ex) { - } - return xXPortalUserIdXXUserMap; - } + 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."); + } + return populateViewBean(resource); + } + + public Map getXXPortalUserIdXXUserMap() { + Map xXPortalUserIdXXUserMap = new HashMap<>(); + + try { + Map xXUserMap = new HashMap<>(); + List xXUserList = daoManager.getXXUser().getAll(); + + if (!CollectionUtils.isEmpty(xXUserList)) { + for (XXUser xxUser : xXUserList) { + xXUserMap.put(xxUser.getName(), xxUser); + } + } + + List xXPortalUserList = daoManager.getXXPortalUser().getAll(); + + if (!CollectionUtils.isEmpty(xXPortalUserList)) { + for (XXPortalUser xXPortalUser : xXPortalUserList) { + if (xXUserMap.containsKey(xXPortalUser.getLoginId())) { + xXPortalUserIdXXUserMap.put(xXPortalUser.getId(), xXUserMap.get(xXPortalUser.getLoginId())); + } + } + } + } catch (Exception ex) { + // ignored + } + + return xXPortalUserIdXXUserMap; + } + + public VXUserList lookupXUsers(SearchCriteria searchCriteria, VXUserList vXUserList) { + List xUserList = new ArrayList<>(); + List resultList = searchResources(searchCriteria, searchFields, sortFields, vXUserList); + + for (XXUser xXUser : resultList) { + VXUser vObj = super.mapEntityToViewBean(createViewObject(), xXUser); + + vObj.setIsVisible(xXUser.getIsVisible()); + + xUserList.add(vObj); + } + + vXUserList.setVXUsers(xUserList); + + return vXUserList; + } + + public Map getXXPortalUserIdXXUserNameMap() { + Map xXPortalUserIdXXUserMap = new HashMap<>(); + + try { + List xxUserList = daoManager.getXXUser().getAllUserIdNames(); + + if (!CollectionUtils.isEmpty(xxUserList)) { + for (Object[] obj : xxUserList) { + xXPortalUserIdXXUserMap.put((Long) obj[0], obj); + } + } + } catch (Exception ex) { + // ignored + } + + return xXPortalUserIdXXUserMap; + } + + @Override + public VXUser populateViewBean(XXUser xUser) { + VXUser vObj = super.populateViewBean(xUser); + + vObj.setIsVisible(xUser.getIsVisible()); + + populateGroupList(xUser.getId(), vObj); + + return vObj; + } + + @Override + protected void validateForCreate(VXUser vObj) { + XXUser xUser = daoManager.getXXUser().findByUserName(vObj.getName()); + + if (xUser != null) { + throw restErrorUtil.createRESTException(vObj.getName() + " 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().equalsIgnoreCase(mObjName.trim())) { + validateForCreate(vObj); + } + } + } + + @Override + protected VXUser mapEntityToViewBean(VXUser vObj, XXUser mObj) { + VXUser ret = super.mapEntityToViewBean(vObj, mObj); + String userName = ret.getName(); + + populateUserAttributes(userName, ret); + + return ret; + } + + private void populateGroupList(Long xUserId, VXUser vObj) { + List xGroupUserList = daoManager.getXXGroupUser().findByUserId(xUserId); + Set groupIdList = new LinkedHashSet<>(); + Set groupNameList = new LinkedHashSet<>(); + + if (xGroupUserList != null) { + for (XXGroupUser xGroupUser : xGroupUserList) { + groupIdList.add(xGroupUser.getParentGroupId()); + + groupNameList.add(xGroupUser.getName()); + } + } + List groups = new ArrayList<>(groupIdList); + List groupNames = new ArrayList<>(groupNameList); + + vObj.setGroupIdList(groups); + vObj.setGroupNameList(groupNames); + } + + private void populateUserAttributes(String userName, VXUser vObj) { + if (userName != null && !userName.isEmpty()) { + List userRoleList = new ArrayList<>(); + XXPortalUser xXPortalUser = daoManager.getXXPortalUser().findByLoginId(userName); + + if (xXPortalUser != null) { + vObj.setFirstName(xXPortalUser.getFirstName()); + vObj.setLastName(xXPortalUser.getLastName()); + vObj.setPassword(PropertiesUtil.getProperty("ranger.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 gjUserRoleList = daoManager.getXXPortalUserRole().findByParentId(xXPortalUser.getId()); + + for (XXPortalUserRole gjUserRole : gjUserRoleList) { + userRoleList.add(gjUserRole.getUserRole()); + } + } + + if (userRoleList.isEmpty()) { + userRoleList.add(RangerConstants.ROLE_USER); + } + + vObj.setUserRoleList(userRoleList); + } + } } diff --git a/security-admin/src/main/java/org/apache/ranger/service/XUserServiceBase.java b/security-admin/src/main/java/org/apache/ranger/service/XUserServiceBase.java index 1c074112f3..b5d2b5277a 100644 --- a/security-admin/src/main/java/org/apache/ranger/service/XUserServiceBase.java +++ b/security-admin/src/main/java/org/apache/ranger/service/XUserServiceBase.java @@ -17,14 +17,7 @@ * under the License. */ - package org.apache.ranger.service; - -/** - * - */ - -import java.util.ArrayList; -import java.util.List; +package org.apache.ranger.service; import org.apache.ranger.common.AppConstants; import org.apache.ranger.common.SearchCriteria; @@ -36,86 +29,92 @@ import javax.persistence.Query; -public abstract class XUserServiceBase - extends AbstractAuditedResourceService { - public static final String NAME = "XUser"; - - public XUserServiceBase() { - super(AppConstants.CLASS_TYPE_XA_USER); - - trxLogAttrs.put("name", new VTrxLogAttr("name", "Login ID", false, true)); - trxLogAttrs.put("firstName", new VTrxLogAttr("firstName", "First Name")); - trxLogAttrs.put("lastName", new VTrxLogAttr("lastName", "Last Name")); - trxLogAttrs.put("emailAddress", new VTrxLogAttr("emailAddress", "Email Address")); - trxLogAttrs.put("password", new VTrxLogAttr("password", "Password")); - trxLogAttrs.put("userRoleList", new VTrxLogAttr("userRoleList", "User Role")); - trxLogAttrs.put("otherAttributes", new VTrxLogAttr("otherAttributes", "Other Attributes")); - trxLogAttrs.put("syncSource", new VTrxLogAttr("syncSource", "Sync Source")); - } - - @SuppressWarnings("unchecked") - @Override - protected XXUser mapViewToEntityBean(VXUser vObj, XXUser mObj, int OPERATION_CONTEXT) { - mObj.setName( vObj.getName()); - mObj.setIsVisible(vObj.getIsVisible()); - mObj.setDescription( vObj.getDescription()); - mObj.setCredStoreId( vObj.getCredStoreId()); - mObj.setOtherAttributes(vObj.getOtherAttributes()); - mObj.setSyncSource(vObj.getSyncSource()); - return mObj; - } - - @SuppressWarnings("unchecked") - @Override - protected VXUser mapEntityToViewBean(VXUser vObj, XXUser mObj) { - vObj.setName( mObj.getName()); - vObj.setIsVisible(mObj.getIsVisible()); - vObj.setDescription( mObj.getDescription()); - vObj.setCredStoreId( mObj.getCredStoreId()); - vObj.setOtherAttributes(mObj.getOtherAttributes()); - vObj.setSyncSource(mObj.getSyncSource()); - return vObj; - } - - /** - * @param searchCriteria - * @return - */ - public VXUserList searchXUsers(SearchCriteria searchCriteria) { - VXUserList returnList = new VXUserList(); - List xUserList = new ArrayList(); - - @SuppressWarnings("unchecked") - List resultList = (List)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; - } - - /** - * Searches the XUser table and gets the user ids matching the search criteria. - */ - public List searchXUsersForIds(SearchCriteria searchCriteria){ - // construct the sort clause - String sortClause = searchUtil.constructSortClause(searchCriteria, sortFields); - - // get only the column id from the table - String q = "SELECT obj.id FROM " + className + " obj "; - - // construct the query object for retrieving the data - Query query = createQuery(q, sortClause, searchCriteria, searchFields, false); - - return getDao().getIds(query); - } - - public List getUsers() { - return daoManager.getXXUser().getAllUsersInfo(); - } +import java.util.ArrayList; +import java.util.List; + +public abstract class XUserServiceBase extends AbstractAuditedResourceService { + public static final String NAME = "XUser"; + + public XUserServiceBase() { + super(AppConstants.CLASS_TYPE_XA_USER); + + trxLogAttrs.put("name", new VTrxLogAttr("name", "Login ID", false, true)); + trxLogAttrs.put("firstName", new VTrxLogAttr("firstName", "First Name")); + trxLogAttrs.put("lastName", new VTrxLogAttr("lastName", "Last Name")); + trxLogAttrs.put("emailAddress", new VTrxLogAttr("emailAddress", "Email Address")); + trxLogAttrs.put("password", new VTrxLogAttr("password", "Password")); + trxLogAttrs.put("userRoleList", new VTrxLogAttr("userRoleList", "User Role")); + trxLogAttrs.put("otherAttributes", new VTrxLogAttr("otherAttributes", "Other Attributes")); + trxLogAttrs.put("syncSource", new VTrxLogAttr("syncSource", "Sync Source")); + } + + /** + * @param searchCriteria + * @return + */ + public VXUserList searchXUsers(SearchCriteria searchCriteria) { + VXUserList returnList = new VXUserList(); + List xUserList = new ArrayList<>(); + + @SuppressWarnings("unchecked") + List resultList = (List) 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; + } + + /** + * Searches the XUser table and gets the user ids matching the search criteria. + */ + public List searchXUsersForIds(SearchCriteria searchCriteria) { + // construct the sort clause + String sortClause = searchUtil.constructSortClause(searchCriteria, sortFields); + + // get only the column id from the table + String q = "SELECT obj.id FROM " + className + " obj "; + + // construct the query object for retrieving the data + Query query = createQuery(q, sortClause, searchCriteria, searchFields, false); + + return getDao().getIds(query); + } + + public List getUsers() { + return daoManager.getXXUser().getAllUsersInfo(); + } + + @SuppressWarnings("unchecked") + @Override + protected XXUser mapViewToEntityBean(VXUser vObj, XXUser mObj, int operationContext) { + mObj.setName(vObj.getName()); + mObj.setIsVisible(vObj.getIsVisible()); + mObj.setDescription(vObj.getDescription()); + mObj.setCredStoreId(vObj.getCredStoreId()); + mObj.setOtherAttributes(vObj.getOtherAttributes()); + mObj.setSyncSource(vObj.getSyncSource()); + + return mObj; + } + + @SuppressWarnings("unchecked") + @Override + protected VXUser mapEntityToViewBean(VXUser vObj, XXUser mObj) { + vObj.setName(mObj.getName()); + vObj.setIsVisible(mObj.getIsVisible()); + vObj.setDescription(mObj.getDescription()); + vObj.setCredStoreId(mObj.getCredStoreId()); + vObj.setOtherAttributes(mObj.getOtherAttributes()); + vObj.setSyncSource(mObj.getSyncSource()); + + return vObj; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/service/filter/RangerRESTAPIFilter.java b/security-admin/src/main/java/org/apache/ranger/service/filter/RangerRESTAPIFilter.java index 8d133037b3..035185aebd 100644 --- a/security-admin/src/main/java/org/apache/ranger/service/filter/RangerRESTAPIFilter.java +++ b/security-admin/src/main/java/org/apache/ranger/service/filter/RangerRESTAPIFilter.java @@ -17,15 +17,17 @@ * under the License. */ - package org.apache.ranger.service.filter; +package org.apache.ranger.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 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 org.apache.ranger.common.PropertiesUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.config.BeanDefinition; +import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider; import javax.ws.rs.DELETE; import javax.ws.rs.GET; @@ -33,232 +35,221 @@ import javax.ws.rs.PUT; import javax.ws.rs.Path; -import org.apache.ranger.common.PropertiesUtil; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -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 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; public class RangerRESTAPIFilter extends LoggingFilter { - Logger logger = LoggerFactory.getLogger(RangerRESTAPIFilter.class); - static volatile boolean initDone = false; - - boolean logStdOut = true; - HashMap regexPathMap = new HashMap(); - HashMap regexPatternMap = new HashMap(); - List regexList = new ArrayList(); - List loggedRestPathErrors = new ArrayList(); - - void init() { - if (initDone) { - return; - } - synchronized (RangerRESTAPIFilter.class) { - if (initDone) { - return; - } - - logStdOut = PropertiesUtil.getBooleanProperty( - "xa.restapi.log.enabled", false); - - // 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(); - - if ((request.getMediaType() == null || !"multipart".equals(request.getMediaType() - .getType())) - && !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 is null"); - } - if (response.getMediaType() == null - || !"image".equals(response.getMediaType().getType())) { - - response = super.filter(request, response); - } - } - - return response; - } - - private void loadPathPatterns() throws ClassNotFoundException { - String pkg = "org.apache.ranger.service"; - // List cList = findClasses(new File(dir), pkg); - @SuppressWarnings("rawtypes") - List 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 (Annotation methodAnnotation : methodAnnotations) { - if (methodAnnotation instanceof GET) { - httpMethod = "GET"; - } else if (methodAnnotation instanceof PUT) { - httpMethod = "PUT"; - } else if (methodAnnotation instanceof POST) { - httpMethod = "POST"; - } else if (methodAnnotation instanceof DELETE) { - httpMethod = "DELETE"; - } else if (methodAnnotation instanceof Path) { - servicePath = ((Path) methodAnnotation) - .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 tmpList = new ArrayList(); - 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 findClasses(String packageName) - throws ClassNotFoundException { - List classes = new ArrayList(); - - ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider( - true); - - // scanner.addIncludeFilter(new - // AnnotationTypeFilter(.class)); - - for (BeanDefinition bd : scanner.findCandidateComponents(packageName)) { - classes.add(Class.forName(bd.getBeanClassName())); - } - - return classes; - } - + Logger logger = LoggerFactory.getLogger(RangerRESTAPIFilter.class); + + static volatile boolean initDone; + + boolean logStdOut = true; + HashMap regexPathMap = new HashMap<>(); + HashMap regexPatternMap = new HashMap<>(); + List regexList = new ArrayList<>(); + List loggedRestPathErrors = new ArrayList<>(); + + /* + * (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(); + + if ((request.getMediaType() == null || !"multipart".equals(request.getMediaType().getType())) && !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 is null"); + } + + if (response.getMediaType() == null || !"image".equals(response.getMediaType().getType())) { + response = super.filter(request, response); + } + } + + return response; + } + + void init() { + if (initDone) { + return; + } + + synchronized (RangerRESTAPIFilter.class) { + if (initDone) { + return; + } + + logStdOut = PropertiesUtil.getBooleanProperty("xa.restapi.log.enabled", false); + + // 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; + } + } + + private void loadPathPatterns() throws ClassNotFoundException { + String pkg = "org.apache.ranger.service"; + + @SuppressWarnings("rawtypes") + List 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; + } + + for (Method m : klass.getMethods()) { + Annotation[] methodAnnotations = m.getAnnotations(); + String httpMethod = null; + String servicePath = null; + + for (Annotation methodAnnotation : methodAnnotations) { + if (methodAnnotation instanceof GET) { + httpMethod = "GET"; + } else if (methodAnnotation instanceof PUT) { + httpMethod = "PUT"; + } else if (methodAnnotation instanceof POST) { + httpMethod = "POST"; + } else if (methodAnnotation instanceof DELETE) { + httpMethod = "DELETE"; + } else if (methodAnnotation instanceof Path) { + servicePath = ((Path) methodAnnotation).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 = {}, fullPath = {}", regEx, fullPath); + } + + regexList.add(regEx); + regexPathMap.put(regEx, fullPath); + regexPatternMap.put(regEx, regexPattern); + + logger.info("path = {}, servicePath = {}, fullPath = {}, regEx = {}", path.value(), servicePath, fullPath, regEx); + } + } + } + + // ReOrder list + int i; + + for (i = 0; i < 10; i++) { + boolean foundMatches = false; + List tmpList = new ArrayList<>(); + + 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; + 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 {} loops", i); + } + + logger.info("Loaded {} API methods.", regexList.size()); + } + + @SuppressWarnings("rawtypes") + private List findClasses(String packageName) throws ClassNotFoundException { + List classes = new ArrayList<>(); + + ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(true); + + for (BeanDefinition bd : scanner.findCandidateComponents(packageName)) { + classes.add(Class.forName(bd.getBeanClassName())); + } + + return classes; + } } From 10cc6b54db416df385de5994c9476f370bca00ab Mon Sep 17 00:00:00 2001 From: PradeeP AgrawaL Date: Sun, 12 Jan 2025 03:04:58 +0530 Subject: [PATCH 13/15] RANGER-5061: checkstyle compliance updates - security-admin org.apache.ranger.rest (#505) --- .../org/apache/ranger/rest/AssetREST.java | 1335 ++- .../java/org/apache/ranger/rest/GdsREST.java | 849 +- .../org/apache/ranger/rest/MetricsREST.java | 68 +- .../org/apache/ranger/rest/PublicAPIs.java | 641 +- .../org/apache/ranger/rest/PublicAPIsv2.java | 1672 ++- .../apache/ranger/rest/RangerHealthREST.java | 13 +- .../java/org/apache/ranger/rest/RoleREST.java | 1362 +-- .../apache/ranger/rest/SecurityZoneREST.java | 679 +- .../org/apache/ranger/rest/ServiceREST.java | 8948 ++++++++--------- .../apache/ranger/rest/ServiceRESTUtil.java | 2142 ++-- .../ranger/rest/ServiceTagsProcessor.java | 1163 ++- .../java/org/apache/ranger/rest/TagREST.java | 905 +- .../apache/ranger/rest/TagRESTConstants.java | 48 +- .../java/org/apache/ranger/rest/UserREST.java | 605 +- .../org/apache/ranger/rest/XAuditREST.java | 267 +- .../java/org/apache/ranger/rest/XKeyREST.java | 382 +- .../org/apache/ranger/rest/XUserREST.java | 2932 +++--- .../apache/ranger/rest/TestServiceREST.java | 2 +- 18 files changed, 11766 insertions(+), 12247 deletions(-) diff --git a/security-admin/src/main/java/org/apache/ranger/rest/AssetREST.java b/security-admin/src/main/java/org/apache/ranger/rest/AssetREST.java index 065b9d33e3..46f16285c4 100644 --- a/security-admin/src/main/java/org/apache/ranger/rest/AssetREST.java +++ b/security-admin/src/main/java/org/apache/ranger/rest/AssetREST.java @@ -17,28 +17,7 @@ * under the License. */ - package org.apache.ranger.rest; - -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.ws.rs.Consumes; -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.QueryParam; -import javax.ws.rs.WebApplicationException; -import javax.ws.rs.core.Context; +package org.apache.ranger.rest; import org.apache.commons.lang.StringUtils; import org.apache.ranger.admin.client.datatype.RESTResponse; @@ -59,15 +38,27 @@ import org.apache.ranger.plugin.util.GrantRevokeRequest; import org.apache.ranger.plugin.util.SearchFilter; import org.apache.ranger.security.context.RangerAPIList; +import org.apache.ranger.service.RangerTrxLogV2Service; import org.apache.ranger.service.XAccessAuditService; import org.apache.ranger.service.XAssetService; import org.apache.ranger.service.XCredentialStoreService; import org.apache.ranger.service.XPolicyExportAuditService; import org.apache.ranger.service.XPolicyService; import org.apache.ranger.service.XResourceService; -import org.apache.ranger.service.RangerTrxLogV2Service; import org.apache.ranger.util.RestUtil; -import org.apache.ranger.view.*; +import org.apache.ranger.view.VXAccessAuditList; +import org.apache.ranger.view.VXAsset; +import org.apache.ranger.view.VXAssetList; +import org.apache.ranger.view.VXCredentialStore; +import org.apache.ranger.view.VXCredentialStoreList; +import org.apache.ranger.view.VXLong; +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.VXTrxLogList; +import org.apache.ranger.view.VXUgsyncAuditInfoList; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -77,6 +68,27 @@ import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.Consumes; +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.QueryParam; +import javax.ws.rs.WebApplicationException; +import javax.ws.rs.core.Context; + +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + import static org.apache.ranger.util.RestUtil.convertToTimeZone; @Path("assets") @@ -85,704 +97,589 @@ @RangerAnnotationJSMgrName("AssetMgr") @Transactional(propagation = Propagation.REQUIRES_NEW) public class AssetREST { - private static final Logger logger = LoggerFactory.getLogger(AssetREST.class); - - @Autowired - RangerSearchUtil searchUtil; - - @Autowired - AssetMgr assetMgr; - - @Autowired - XAssetService xAssetService; - - @Autowired - XResourceService xResourceService; - - @Autowired - XPolicyService xPolicyService; - - @Autowired - XCredentialStoreService xCredentialStoreService; - - @Autowired - RESTErrorUtil restErrorUtil; - - @Autowired - XPolicyExportAuditService xPolicyExportAudits; - - @Autowired - RangerTrxLogV2Service xTrxLogService; - - @Autowired - RangerBizUtil msBizUtil; - - @Autowired - XAccessAuditService xAccessAuditService; - - @Autowired - ServiceUtil serviceUtil; - - @Autowired - ServiceREST serviceREST; - - @Autowired - RangerDaoManager daoManager; - - @GET - @Path("/assets/{id}") - @Produces({ "application/json" }) - @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.GET_X_ASSET + "\")") - public VXAsset getXAsset(@PathParam("id") Long id) { - if(logger.isDebugEnabled()) { - logger.debug("==> AssetREST.getXAsset(" + id + ")"); - } - - RangerService service = serviceREST.getService(id); - - VXAsset ret = serviceUtil.toVXAsset(service); - - if(logger.isDebugEnabled()) { - logger.debug("<== AssetREST.getXAsset(" + id + "): " + ret); - } - - return ret; - } - - @POST - @Path("/assets") - @Consumes({ "application/json" }) - @Produces({ "application/json" }) - @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.CREATE_X_ASSET + "\")") - public VXAsset createXAsset(VXAsset vXAsset) { - if(logger.isDebugEnabled()) { - logger.debug("==> AssetREST.createXAsset(" + vXAsset + ")"); - } - - RangerService service = serviceUtil.toRangerService(vXAsset); - - RangerService createdService = serviceREST.createService(service); - - VXAsset ret = serviceUtil.toVXAsset(createdService); - - if(logger.isDebugEnabled()) { - logger.debug("<== AssetREST.createXAsset(" + vXAsset + "): " + ret); - } - - return ret; - } - - @PUT - @Path("/assets/{id}") - @Consumes({ "application/json" }) - @Produces({ "application/json" }) - @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.UPDATE_X_ASSET + "\")") - public VXAsset updateXAsset(VXAsset vXAsset) { - if(logger.isDebugEnabled()) { - logger.debug("==> AssetREST.updateXAsset(" + vXAsset + ")"); - } - - RangerService service = serviceUtil.toRangerService(vXAsset); - - RangerService updatedService = serviceREST.updateService(service, null); - - VXAsset ret = serviceUtil.toVXAsset(updatedService); - - if(logger.isDebugEnabled()) { - logger.debug("<== AssetREST.updateXAsset(" + vXAsset + "): " + ret); - } - - return ret; - } - - @DELETE - @Path("/assets/{id}") - @RangerAnnotationClassName(class_name = VXAsset.class) - @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.DELETE_X_ASSET + "\")") - public void deleteXAsset(@PathParam("id") Long id, - @Context HttpServletRequest request) { - if(logger.isDebugEnabled()) { - logger.debug("==> AssetREST.deleteXAsset(" + id + ")"); - } - - serviceREST.deleteService(id); - - if(logger.isDebugEnabled()) { - logger.debug("<== AssetREST.deleteXAsset(" + id + ")"); - } - } - - @POST - @Path("/assets/testConfig") - @Consumes({ "application/json" }) - @Produces({ "application/json" }) - @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.TEST_CONFIG + "\")") - public VXResponse configTest(VXAsset vXAsset) { - if(logger.isDebugEnabled()) { - logger.debug("==> AssetREST.configTest(" + vXAsset + ")"); - } - - RangerService service = serviceUtil.toRangerService(vXAsset); - - VXResponse ret = serviceREST.validateConfig(service); - - if(logger.isDebugEnabled()) { - logger.debug("<== AssetREST.testConfig(" + vXAsset + "): " + ret); - } - - return ret; - } - - @GET - @Path("/assets") - @Produces({ "application/json" }) - @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.SEARCH_X_ASSETS + "\")") - public VXAssetList searchXAssets(@Context HttpServletRequest request) { - if(logger.isDebugEnabled()) { - logger.debug("==> AssetREST.searchXAssets()"); - } - - VXAssetList ret = new VXAssetList(); - - SearchFilter filter = searchUtil.getSearchFilterFromLegacyRequestForRepositorySearch(request, xAssetService.sortFields); - - List services = serviceREST.getServices(filter); - - if(services != null) { - List assets = new ArrayList(); - for(RangerService service : services) { - VXAsset asset = serviceUtil.toVXAsset(service); - - if(asset != null) { - assets.add(asset); - } - } - - ret.setVXAssets(assets); - ret.setTotalCount(assets.size()); - ret.setResultSize(assets.size()); - } - - if(logger.isDebugEnabled()) { - logger.debug("<== AssetREST.searchXAssets(): count=" + ret.getListSize()); - } - - return ret; - } - - @GET - @Path("/assets/count") - @Produces({ "application/json" }) - @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.COUNT_X_ASSETS + "\")") - public VXLong countXAssets(@Context HttpServletRequest request) { - if(logger.isDebugEnabled()) { - logger.debug("==> AssetREST.countXAssets()"); - } - - SearchFilter filter = searchUtil.getSearchFilterFromLegacyRequest(request, xResourceService.sortFields); - - filter.setMaxRows(Integer.MAX_VALUE); - - List services = serviceREST.getServices(filter); - int servicesCount = 0; - - if (services != null) { - for (RangerService service : services) { - VXAsset asset = serviceUtil.toVXAsset(service); - - if (asset != null) { - servicesCount++; - } - } - } - - VXLong ret = new VXLong(); - - ret.setValue(servicesCount); - - if(logger.isDebugEnabled()) { - logger.debug("<== AssetREST.countXAssets(): " + ret); - } - - return ret; - } - - @GET - @Path("/resources/{id}") - @Produces({ "application/json" }) - public VXResource getXResource(@PathParam("id") Long id) { - if(logger.isDebugEnabled()) { - logger.debug("==> AssetREST.getXResource(" + id + ")"); - } - - RangerPolicy policy = null; - RangerService service = null; - - policy = serviceREST.getPolicy(id); - - if(policy != null) { - service = serviceREST.getServiceByName(policy.getService()); - } - - VXResource ret = serviceUtil.toVXResource(policy, service); - - if(logger.isDebugEnabled()) { - logger.debug("<== AssetREST.getXResource(" + id + "): " + ret); - } - - return ret; - } - - @POST - @Path("/resources") - @Consumes({ "application/json" }) - @Produces({ "application/json" }) - public VXResource createXResource(VXResource vXResource) { - if(logger.isDebugEnabled()) { - logger.debug("==> AssetREST.createXResource(" + vXResource + ")"); - } - - RangerService service = serviceREST.getService(vXResource.getAssetId()); - RangerPolicy policy = serviceUtil.toRangerPolicy(vXResource, service); - - RangerPolicy createdPolicy = serviceREST.createPolicy(policy, null); - - VXResource ret = serviceUtil.toVXResource(createdPolicy, service); - - if(logger.isDebugEnabled()) { - logger.debug("<== AssetREST.createXResource(" + vXResource + "): " + ret); - } - - return ret; - } - - @PUT - @Path("/resources/{id}") - @Consumes({ "application/json" }) - @Produces({ "application/json" }) - public VXResource updateXResource(VXResource vXResource , @PathParam("id") Long id) { - if(logger.isDebugEnabled()) { - logger.debug("==> AssetREST.updateXResource(" + vXResource + ")"); - } - - // if vXResource.id is specified, it should be same as the param 'id' - if (vXResource.getId() == null) { - vXResource.setId(id); - } else if(!vXResource.getId().equals(id)) { - throw restErrorUtil.createRESTException(HttpServletResponse.SC_BAD_REQUEST , "resource Id mismatch", true); - } - - RangerService service = serviceREST.getService(vXResource.getAssetId()); - RangerPolicy policy = serviceUtil.toRangerPolicy(vXResource, service); + private static final Logger logger = LoggerFactory.getLogger(AssetREST.class); + + @Autowired + RangerSearchUtil searchUtil; + + @Autowired + AssetMgr assetMgr; + + @Autowired + XAssetService xAssetService; + + @Autowired + XResourceService xResourceService; + + @Autowired + XPolicyService xPolicyService; + + @Autowired + XCredentialStoreService xCredentialStoreService; + + @Autowired + RESTErrorUtil restErrorUtil; + + @Autowired + XPolicyExportAuditService xPolicyExportAudits; + + @Autowired + RangerTrxLogV2Service xTrxLogService; + + @Autowired + RangerBizUtil msBizUtil; + + @Autowired + XAccessAuditService xAccessAuditService; + + @Autowired + ServiceUtil serviceUtil; + + @Autowired + ServiceREST serviceREST; + + @Autowired + RangerDaoManager daoManager; + + @GET + @Path("/assets/{id}") + @Produces("application/json") + @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.GET_X_ASSET + "\")") + public VXAsset getXAsset(@PathParam("id") Long id) { + logger.debug("==> AssetREST.getXAsset({})", id); + + RangerService service = serviceREST.getService(id); + VXAsset ret = serviceUtil.toVXAsset(service); + + logger.debug("<== AssetREST.getXAsset({}): {}", id, ret); + + return ret; + } + + @POST + @Path("/assets") + @Consumes("application/json") + @Produces("application/json") + @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.CREATE_X_ASSET + "\")") + public VXAsset createXAsset(VXAsset vXAsset) { + logger.debug("==> AssetREST.createXAsset({})", vXAsset); + + RangerService service = serviceUtil.toRangerService(vXAsset); + RangerService createdService = serviceREST.createService(service); + VXAsset ret = serviceUtil.toVXAsset(createdService); + + logger.debug("<== AssetREST.createXAsset({}):{}", vXAsset, ret); + + return ret; + } + + @PUT + @Path("/assets/{id}") + @Consumes("application/json") + @Produces("application/json") + @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.UPDATE_X_ASSET + "\")") + public VXAsset updateXAsset(VXAsset vXAsset) { + logger.debug("==> AssetREST.updateXAsset({})", vXAsset); + + RangerService service = serviceUtil.toRangerService(vXAsset); + RangerService updatedService = serviceREST.updateService(service, null); + VXAsset ret = serviceUtil.toVXAsset(updatedService); + + logger.debug("<== AssetREST.updateXAsset({}):{}", vXAsset, ret); + + return ret; + } + + @DELETE + @Path("/assets/{id}") + @RangerAnnotationClassName(class_name = VXAsset.class) + @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.DELETE_X_ASSET + "\")") + public void deleteXAsset(@PathParam("id") Long id, @Context HttpServletRequest request) { + logger.debug("==> AssetREST.deleteXAsset({})", id); + + serviceREST.deleteService(id); + + logger.debug("<== AssetREST.deleteXAsset({})", id); + } + + @POST + @Path("/assets/testConfig") + @Consumes("application/json") + @Produces("application/json") + @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.TEST_CONFIG + "\")") + public VXResponse configTest(VXAsset vXAsset) { + logger.debug("==> AssetREST.configTest({})", vXAsset); + + RangerService service = serviceUtil.toRangerService(vXAsset); + VXResponse ret = serviceREST.validateConfig(service); + + logger.debug("<== AssetREST.testConfig({}):{}", vXAsset, ret); + + return ret; + } + + @GET + @Path("/assets") + @Produces("application/json") + @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.SEARCH_X_ASSETS + "\")") + public VXAssetList searchXAssets(@Context HttpServletRequest request) { + logger.debug("==> AssetREST.searchXAssets()"); + + VXAssetList ret = new VXAssetList(); + SearchFilter filter = searchUtil.getSearchFilterFromLegacyRequestForRepositorySearch(request, xAssetService.sortFields); + List services = serviceREST.getServices(filter); + + if (services != null) { + List assets = new ArrayList<>(); + + for (RangerService service : services) { + VXAsset asset = serviceUtil.toVXAsset(service); + + if (asset != null) { + assets.add(asset); + } + } + + ret.setVXAssets(assets); + ret.setTotalCount(assets.size()); + ret.setResultSize(assets.size()); + } + + logger.debug("<== AssetREST.searchXAssets(): count={}", ret.getListSize()); + + return ret; + } + + @GET + @Path("/assets/count") + @Produces("application/json") + @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.COUNT_X_ASSETS + "\")") + public VXLong countXAssets(@Context HttpServletRequest request) { + logger.debug("==> AssetREST.countXAssets()"); + + SearchFilter filter = searchUtil.getSearchFilterFromLegacyRequest(request, xResourceService.sortFields); + + filter.setMaxRows(Integer.MAX_VALUE); + + List services = serviceREST.getServices(filter); + int servicesCount = 0; + + if (services != null) { + for (RangerService service : services) { + VXAsset asset = serviceUtil.toVXAsset(service); + + if (asset != null) { + servicesCount++; + } + } + } + + VXLong ret = new VXLong(); + + ret.setValue(servicesCount); + + logger.debug("<== AssetREST.countXAssets(): {}", ret); + + return ret; + } + + @GET + @Path("/resources/{id}") + @Produces("application/json") + public VXResource getXResource(@PathParam("id") Long id) { + logger.debug("==> AssetREST.getXResource({})", id); + + RangerService service = null; + RangerPolicy policy = serviceREST.getPolicy(id); + + if (policy != null) { + service = serviceREST.getServiceByName(policy.getService()); + } + + VXResource ret = serviceUtil.toVXResource(policy, service); + + logger.debug("<== AssetREST.getXResource({}): {}", id, ret); + + return ret; + } + + @POST + @Path("/resources") + @Consumes("application/json") + @Produces("application/json") + public VXResource createXResource(VXResource vXResource) { + logger.debug("==> AssetREST.createXResource({})", vXResource); + + RangerService service = serviceREST.getService(vXResource.getAssetId()); + RangerPolicy policy = serviceUtil.toRangerPolicy(vXResource, service); + RangerPolicy createdPolicy = serviceREST.createPolicy(policy, null); + VXResource ret = serviceUtil.toVXResource(createdPolicy, service); + + logger.debug("<== AssetREST.createXResource({}): {}", vXResource, ret); + + return ret; + } + + @PUT + @Path("/resources/{id}") + @Consumes("application/json") + @Produces("application/json") + public VXResource updateXResource(VXResource vXResource, @PathParam("id") Long id) { + logger.debug("==> AssetREST.updateXResource({})", vXResource); + + // if vXResource.id is specified, it should be same as the param 'id' + if (vXResource.getId() == null) { + vXResource.setId(id); + } else if (!vXResource.getId().equals(id)) { + throw restErrorUtil.createRESTException(HttpServletResponse.SC_BAD_REQUEST, "resource Id mismatch", true); + } + + RangerService service = serviceREST.getService(vXResource.getAssetId()); + RangerPolicy policy = serviceUtil.toRangerPolicy(vXResource, service); + RangerPolicy updatedPolicy = serviceREST.updatePolicy(policy, policy.getId()); + VXResource ret = serviceUtil.toVXResource(updatedPolicy, service); + + logger.debug("<== AssetREST.updateXResource({}): {}", vXResource, ret); + + return ret; + } + + @DELETE + @Path("/resources/{id}") + @RangerAnnotationClassName(class_name = VXResource.class) + public void deleteXResource(@PathParam("id") Long id, @Context HttpServletRequest request) { + logger.debug("==> AssetREST.deleteXResource({})", id); + + serviceREST.deletePolicy(id); + + logger.debug("<== AssetREST.deleteXResource({})", id); + } + + @GET + @Path("/resources") + @Produces("application/json") + public VXResourceList searchXResources(@Context HttpServletRequest request) { + logger.debug("==> AssetREST.searchXResources()"); + + VXResourceList ret = new VXResourceList(); + SearchFilter filter = searchUtil.getSearchFilterFromLegacyRequest(request, xResourceService.sortFields); + List policies = serviceREST.getPolicies(filter); + + if (policies != null) { + List resources = new ArrayList<>(); - RangerPolicy updatedPolicy = serviceREST.updatePolicy(policy, policy.getId()); - - VXResource ret = serviceUtil.toVXResource(updatedPolicy, service); + for (RangerPolicy policy : policies) { + RangerService service = serviceREST.getServiceByName(policy.getService()); + VXResource resource = serviceUtil.toVXResource(policy, service); - if(logger.isDebugEnabled()) { - logger.debug("<== AssetREST.updateXResource(" + vXResource + "): " + ret); - } + if (resource != null) { + resources.add(resource); + } + } - return ret; - } + ret.setVXResources(resources); + ret.setTotalCount(resources.size()); + ret.setResultSize(resources.size()); + } - @DELETE - @Path("/resources/{id}") - @RangerAnnotationClassName(class_name = VXResource.class) - public void deleteXResource(@PathParam("id") Long id, - @Context HttpServletRequest request) { - if(logger.isDebugEnabled()) { - logger.debug("==> AssetREST.deleteXResource(" + id + ")"); - } + logger.debug("<== AssetREST.searchXResources(): count={}", ret.getResultSize()); + + return ret; + } - serviceREST.deletePolicy(id); - - if(logger.isDebugEnabled()) { - logger.debug("<== AssetREST.deleteXResource(" + id + ")"); - } - } - - @GET - @Path("/resources") - @Produces({ "application/json" }) - public VXResourceList searchXResources(@Context HttpServletRequest request) { - if(logger.isDebugEnabled()) { - logger.debug("==> AssetREST.searchXResources()"); - } - - VXResourceList ret = new VXResourceList(); - - SearchFilter filter = searchUtil.getSearchFilterFromLegacyRequest(request, xResourceService.sortFields); - - List policies = serviceREST.getPolicies(filter); - - if(policies != null) { - List resources = new ArrayList(); - for(RangerPolicy policy : policies) { - RangerService service = serviceREST.getServiceByName(policy.getService()); - - VXResource resource = serviceUtil.toVXResource(policy, service); - - if(resource != null) { - resources.add(resource); - } - } - - ret.setVXResources(resources); - ret.setTotalCount(resources.size()); - ret.setResultSize(resources.size()); - } - - if(logger.isDebugEnabled()) { - logger.debug("<== AssetREST.searchXResources(): count=" + ret.getResultSize()); - } - - return ret; - } - - @GET - @Path("/resources/count") - @Produces({ "application/json" }) - public VXLong countXResources(@Context HttpServletRequest request) { - if(logger.isDebugEnabled()) { - logger.debug("==> AssetREST.countXResources()"); - } - - SearchFilter filter = searchUtil.getSearchFilterFromLegacyRequest(request, xResourceService.sortFields); - - filter.setMaxRows(Integer.MAX_VALUE); - - List policies = serviceREST.getPolicies(filter); - int policiesCount = 0; - - if (policies != null) { - Map services = new HashMap<>(); - - for (RangerPolicy policy : policies) { - RangerService service = services.get(policy.getService()); - - if (service == null) { - service = serviceREST.getServiceByName(policy.getService()); - - services.put(policy.getService(), service); - } - - VXResource resource = serviceUtil.toVXResource(policy, service); - - if (resource != null) { - policiesCount++; - } - } - } - - VXLong ret = new VXLong(); - - ret.setValue(policiesCount); - - if(logger.isDebugEnabled()) { - logger.debug("<== AssetREST.countXResources(): " + ret); - } - - return ret; - } - - @GET - @Path("/credstores/{id}") - @Produces({ "application/json" }) - public VXCredentialStore getXCredentialStore(@PathParam("id") Long id) { - return assetMgr.getXCredentialStore(id); - } - - @POST - @Path("/credstores") - @Consumes({ "application/json" }) - @Produces({ "application/json" }) - public VXCredentialStore createXCredentialStore( - VXCredentialStore vXCredentialStore) { - return assetMgr.createXCredentialStore(vXCredentialStore); - } - - @PUT - @Path("/credstores") - @Consumes({ "application/json" }) - @Produces({ "application/json" }) - public VXCredentialStore updateXCredentialStore( - VXCredentialStore vXCredentialStore) { - return assetMgr.updateXCredentialStore(vXCredentialStore); - } - - @DELETE - @Path("/credstores/{id}") - @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") - @RangerAnnotationClassName(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/json" }) - public VXCredentialStoreList searchXCredentialStores( - @Context HttpServletRequest request) { - SearchCriteria searchCriteria = searchUtil.extractCommonCriterias( - request, xCredentialStoreService.sortFields); - return assetMgr.searchXCredentialStores(searchCriteria); - } - - @GET - @Path("/credstores/count") - @Produces({ "application/json" }) - public VXLong countXCredentialStores(@Context HttpServletRequest request) { - SearchCriteria searchCriteria = searchUtil.extractCommonCriterias( - request, xCredentialStoreService.sortFields); - return assetMgr.getXCredentialStoreSearchCount(searchCriteria); - } - - @GET - @Path("/exportAudit") - @Produces({ "application/json" }) - @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.SEARCH_X_POLICY_EXPORT_AUDITS + "\")") - 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", null); - searchUtil.extractDate(request, searchCriteria, "endDate", - "End Date", null); - searchUtil.extractString(request, searchCriteria, "cluster", - "Cluster Name", StringUtil.VALIDATION_TEXT); - searchUtil.extractString(request, searchCriteria, "zoneName", - "Zone Name", StringUtil.VALIDATION_TEXT); - return assetMgr.searchXPolicyExportAudits(searchCriteria); - } - - @GET - @Path("/report") - @Produces({ "application/json" }) - @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.GET_REPORT_LOGS + "\")") - public VXTrxLogList getReportLogs(@Context HttpServletRequest request){ - - SearchCriteria searchCriteria = searchUtil.extractCommonCriterias( - request, xTrxLogService.getSortFields()); - searchUtil.extractInt(request, searchCriteria, "objectClassType", "audit type."); - searchUtil.extractInt(request, searchCriteria, "objectId", "Object ID"); - 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/json" }) - @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.GET_TRANSACTION_REPORT + "\")") - public VXTrxLogList getTransactionReport(@Context HttpServletRequest request, - @PathParam("transactionId") String transactionId){ - return assetMgr.getTransactionReport(transactionId); - } - - @GET - @Path("/accessAudit") - @Produces({ "application/json" }) - @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.GET_ACCESS_LOGS + "\")") - public VXAccessAuditList getAccessLogs(@Context HttpServletRequest request, @QueryParam("timeZone") String timeZone){ - SearchCriteria searchCriteria = searchUtil.extractCommonCriterias( - request, xAccessAuditService.sortFields); - searchUtil.extractString(request, searchCriteria, "accessType", - "Access Type", StringUtil.VALIDATION_TEXT); - searchUtil.extractString(request, searchCriteria, "aclEnforcer", - "Access Enforcer", StringUtil.VALIDATION_TEXT); - searchUtil.extractString(request, searchCriteria, "agentId", - "Application", StringUtil.VALIDATION_TEXT); - searchUtil.extractString(request, searchCriteria, "repoName", - "Service Name", StringUtil.VALIDATION_TEXT); - searchUtil.extractString(request, searchCriteria, "sessionId", - "Session ID", StringUtil.VALIDATION_TEXT); - searchUtil.extractStringList(request, searchCriteria, "requestUser", - "Users", "requestUser", null, StringUtil.VALIDATION_TEXT); - searchUtil.extractStringList(request, searchCriteria, "excludeUser", - "Exclude Users", "-requestUser", null, StringUtil.VALIDATION_TEXT); - searchUtil.extractString(request, searchCriteria, "requestData", - "Request Data", StringUtil.VALIDATION_TEXT); - searchUtil.extractString(request, searchCriteria, "resourcePath", - "Resource Name", StringUtil.VALIDATION_TEXT); - searchUtil.extractString(request, searchCriteria, "clientIP", - "Client IP", StringUtil.VALIDATION_TEXT); - searchUtil.extractString(request, searchCriteria, "resourceType", - "Resource Type", StringUtil.VALIDATION_TEXT); - searchUtil.extractString(request,searchCriteria,"excludeServiceUser", - "Exclude Service User",StringUtil.VALIDATION_TEXT); - - searchUtil.extractInt(request, searchCriteria, "auditType", "Audit Type"); - searchUtil.extractInt(request, searchCriteria, "accessResult", "Result"); - searchUtil.extractInt(request, searchCriteria, "assetId", "Asset ID"); - searchUtil.extractLong(request, searchCriteria, "policyId", "Policy ID"); - searchUtil.extractInt(request, searchCriteria, "repoType", "Service Type"); - - searchUtil.extractDate(request, searchCriteria, "startDate","Start Date", "MM/dd/yyyy"); - searchUtil.extractDate(request, searchCriteria, "endDate", "End Date", "MM/dd/yyyy"); - - searchUtil.extractString(request, searchCriteria, "tags", "tags", null); - searchUtil.extractString(request, searchCriteria, "cluster", "Cluster Name", StringUtil.VALIDATION_TEXT); - searchUtil.extractStringList(request, searchCriteria, "zoneName", "Zone Name List", "zoneName", null, null); - - searchUtil.extractString(request, searchCriteria, "agentHost", "Agent Host Name", StringUtil.VALIDATION_TEXT); - - searchUtil.extractString(request, searchCriteria, "eventId", "Event Id", null); - - boolean isKeyAdmin = msBizUtil.isKeyAdmin(); - boolean isAuditKeyAdmin = msBizUtil.isAuditKeyAdmin(); - XXServiceDef xxServiceDef = daoManager.getXXServiceDef().findByName(EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_KMS_NAME); - if(isKeyAdmin && xxServiceDef != null || isAuditKeyAdmin && xxServiceDef != null){ - searchCriteria.getParamList().put("repoType", xxServiceDef.getId()); - } - else if (xxServiceDef != null) { - searchCriteria.getParamList().put("-repoType", xxServiceDef.getId()); - } - VXAccessAuditList vxAccessAuditList = assetMgr.getAccessLogs(searchCriteria); - - if (timeZone != null && !StringUtils.isBlank(timeZone)) { - vxAccessAuditList.getVXAccessAudits().forEach(vxAccessAudit -> { - String zonedEventTime = convertToTimeZone(vxAccessAudit.getEventTime(), timeZone); - if (zonedEventTime == null || zonedEventTime.isEmpty()) { - throw restErrorUtil.createRESTException(HttpServletResponse.SC_BAD_REQUEST , "Passed timeZone value is invalid", true); - } - vxAccessAudit.setZonedEventTime(zonedEventTime); - }); - } else { - vxAccessAuditList.getVXAccessAudits().forEach(vxAccessAudit -> { - vxAccessAudit.setZonedEventTime(new SimpleDateFormat(RestUtil.ZONED_EVENT_TIME_FORMAT).format(vxAccessAudit.getEventTime())); - }); - } - return vxAccessAuditList; - } - - @POST - @Path("/resources/grant") - @Consumes({ "application/json" }) - @Produces({ "application/json" }) - public VXPolicy grantPermission(@Context HttpServletRequest request,VXPolicy vXPolicy) { - - RESTResponse ret = null; - - if(logger.isDebugEnabled()) { - logger.debug("==> AssetREST.grantPermission(" + vXPolicy + ")"); - } - - if ( vXPolicy != null) { - String serviceName = vXPolicy.getRepositoryName(); - GrantRevokeRequest grantRevokeRequest = serviceUtil.toGrantRevokeRequest(vXPolicy); - try { - ret = serviceREST.grantAccess(serviceName, grantRevokeRequest, request); - } catch(WebApplicationException excp) { - throw excp; - } catch (Throwable e) { - logger.error( HttpServletResponse.SC_BAD_REQUEST + "Grant Access Failed for the request " + vXPolicy, e); - throw restErrorUtil.createRESTException("Grant Access Failed for the request: " + vXPolicy + ". " + e.getMessage()); - } - } else { - logger.error( HttpServletResponse.SC_BAD_REQUEST + "Bad Request parameter"); - throw restErrorUtil.createRESTException("Bad Request parameter"); - } - - if(logger.isDebugEnabled()) { - logger.debug("<== AssetREST.grantPermission(" + ret + ")"); - } - - // TO DO Current Grant REST doesn't return a policy so returning a null value. Has to be replace with VXpolicy. - return vXPolicy; - } - - @POST - @Path("/resources/revoke") - @Consumes({ "application/json" }) - @Produces({ "application/json" }) - public VXPolicy revokePermission(@Context HttpServletRequest request,VXPolicy vXPolicy) { - - RESTResponse ret = null; - - if(logger.isDebugEnabled()) { - logger.debug("==> AssetREST.revokePermission(" + vXPolicy + ")"); - } - - if ( vXPolicy != null) { - String serviceName = vXPolicy.getRepositoryName(); - GrantRevokeRequest grantRevokeRequest = serviceUtil.toGrantRevokeRequest(vXPolicy); - try { - ret = serviceREST.revokeAccess(serviceName, grantRevokeRequest, request); - } catch(WebApplicationException excp) { - throw excp; - } catch (Throwable e) { - logger.error( HttpServletResponse.SC_BAD_REQUEST + "Revoke Access Failed for the request " + vXPolicy, e); - throw restErrorUtil.createRESTException("Revoke Access Failed for the request: " + vXPolicy + ". " + e.getMessage()); - } - } else { - logger.error( HttpServletResponse.SC_BAD_REQUEST + "Bad Request parameter"); - throw restErrorUtil.createRESTException("Bad Request parameter"); - } - - if(logger.isDebugEnabled()) { - logger.debug("<== AssetREST.revokePermission(" + ret + ")"); - } - return vXPolicy; - } - - @GET - @Path("/ugsyncAudits") - @Produces({ "application/json" }) - @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.GET_UGSYNC_AUDITS + "\")") - public VXUgsyncAuditInfoList getUgsyncAudits(@Context HttpServletRequest request){ - - SearchCriteria searchCriteria = searchUtil.extractCommonCriterias( - request, xAccessAuditService.sortFields); - searchUtil.extractString(request, searchCriteria, "userName", - "User Name", StringUtil.VALIDATION_TEXT); - searchUtil.extractString(request, searchCriteria, "sessionId", - "Session Id", StringUtil.VALIDATION_TEXT); - searchUtil.extractString(request, searchCriteria, "syncSource", - "Sync Source", StringUtil.VALIDATION_TEXT); - searchUtil.extractString(request, searchCriteria, "syncSourceInfo", - "Sync Source Info", StringUtil.VALIDATION_TEXT); - searchUtil.extractLong(request, searchCriteria, "noOfUsers", "No of Users"); - searchUtil.extractLong(request, searchCriteria, "noOfGroups", "No of Groups"); - - searchUtil.extractDate(request, searchCriteria, "startDate", - "Start Date", "MM/dd/yyyy"); - searchUtil.extractDate(request, searchCriteria, "endDate", "End Date", - "MM/dd/yyyy"); - return assetMgr.getUgsyncAudits(searchCriteria); - } - - @GET - @Path("/ugsyncAudits/{syncSource}") - @Encoded - @Produces({ "application/json" }) - @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.GET_UGSYNC_AUDITS_BY_SYNCSOURCE + "\")") - public VXUgsyncAuditInfoList getUgsyncAuditsBySyncSource(@PathParam("syncSource") String syncSource){ - VXUgsyncAuditInfoList vxUgsyncAuditInfoList = new VXUgsyncAuditInfoList(); - vxUgsyncAuditInfoList = assetMgr.getUgsyncAuditsBySyncSource(syncSource); - return vxUgsyncAuditInfoList; - } + @GET + @Path("/resources/count") + @Produces("application/json") + public VXLong countXResources(@Context HttpServletRequest request) { + logger.debug("==> AssetREST.countXResources()"); + + SearchFilter filter = searchUtil.getSearchFilterFromLegacyRequest(request, xResourceService.sortFields); + + filter.setMaxRows(Integer.MAX_VALUE); + + List policies = serviceREST.getPolicies(filter); + int policiesCount = 0; + + if (policies != null) { + Map services = new HashMap<>(); + + for (RangerPolicy policy : policies) { + RangerService service = services.get(policy.getService()); + + if (service == null) { + service = serviceREST.getServiceByName(policy.getService()); + + services.put(policy.getService(), service); + } + + VXResource resource = serviceUtil.toVXResource(policy, service); + + if (resource != null) { + policiesCount++; + } + } + } + + VXLong ret = new VXLong(); + + ret.setValue(policiesCount); + + logger.debug("<== AssetREST.countXResources(): {}", ret); + + return ret; + } + + @GET + @Path("/credstores/{id}") + @Produces("application/json") + public VXCredentialStore getXCredentialStore(@PathParam("id") Long id) { + return assetMgr.getXCredentialStore(id); + } + + @POST + @Path("/credstores") + @Consumes("application/json") + @Produces("application/json") + public VXCredentialStore createXCredentialStore(VXCredentialStore vXCredentialStore) { + return assetMgr.createXCredentialStore(vXCredentialStore); + } + + @PUT + @Path("/credstores") + @Consumes("application/json") + @Produces("application/json") + public VXCredentialStore updateXCredentialStore(VXCredentialStore vXCredentialStore) { + return assetMgr.updateXCredentialStore(vXCredentialStore); + } + + @DELETE + @Path("/credstores/{id}") + @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") + @RangerAnnotationClassName(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/json") + public VXCredentialStoreList searchXCredentialStores(@Context HttpServletRequest request) { + SearchCriteria searchCriteria = searchUtil.extractCommonCriterias(request, xCredentialStoreService.sortFields); + + return assetMgr.searchXCredentialStores(searchCriteria); + } + + @GET + @Path("/credstores/count") + @Produces("application/json") + public VXLong countXCredentialStores(@Context HttpServletRequest request) { + SearchCriteria searchCriteria = searchUtil.extractCommonCriterias(request, xCredentialStoreService.sortFields); + + return assetMgr.getXCredentialStoreSearchCount(searchCriteria); + } + + @GET + @Path("/exportAudit") + @Produces("application/json") + @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.SEARCH_X_POLICY_EXPORT_AUDITS + "\")") + 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", null); + searchUtil.extractDate(request, searchCriteria, "endDate", "End Date", null); + searchUtil.extractString(request, searchCriteria, "cluster", "Cluster Name", StringUtil.VALIDATION_TEXT); + searchUtil.extractString(request, searchCriteria, "zoneName", "Zone Name", StringUtil.VALIDATION_TEXT); + + return assetMgr.searchXPolicyExportAudits(searchCriteria); + } + + @GET + @Path("/report") + @Produces("application/json") + @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.GET_REPORT_LOGS + "\")") + public VXTrxLogList getReportLogs(@Context HttpServletRequest request) { + SearchCriteria searchCriteria = searchUtil.extractCommonCriterias(request, xTrxLogService.getSortFields()); + + searchUtil.extractInt(request, searchCriteria, "objectClassType", "audit type."); + searchUtil.extractInt(request, searchCriteria, "objectId", "Object ID"); + 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/json") + @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.GET_TRANSACTION_REPORT + "\")") + public VXTrxLogList getTransactionReport(@Context HttpServletRequest request, @PathParam("transactionId") String transactionId) { + return assetMgr.getTransactionReport(transactionId); + } + + @GET + @Path("/accessAudit") + @Produces("application/json") + @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.GET_ACCESS_LOGS + "\")") + public VXAccessAuditList getAccessLogs(@Context HttpServletRequest request, @QueryParam("timeZone") String timeZone) { + SearchCriteria searchCriteria = searchUtil.extractCommonCriterias(request, xAccessAuditService.sortFields); + + searchUtil.extractString(request, searchCriteria, "accessType", "Access Type", StringUtil.VALIDATION_TEXT); + searchUtil.extractString(request, searchCriteria, "aclEnforcer", "Access Enforcer", StringUtil.VALIDATION_TEXT); + searchUtil.extractString(request, searchCriteria, "agentId", "Application", StringUtil.VALIDATION_TEXT); + searchUtil.extractString(request, searchCriteria, "repoName", "Service Name", StringUtil.VALIDATION_TEXT); + searchUtil.extractString(request, searchCriteria, "sessionId", "Session ID", StringUtil.VALIDATION_TEXT); + searchUtil.extractStringList(request, searchCriteria, "requestUser", "Users", "requestUser", null, StringUtil.VALIDATION_TEXT); + searchUtil.extractStringList(request, searchCriteria, "excludeUser", "Exclude Users", "-requestUser", null, StringUtil.VALIDATION_TEXT); + searchUtil.extractString(request, searchCriteria, "requestData", "Request Data", StringUtil.VALIDATION_TEXT); + searchUtil.extractString(request, searchCriteria, "resourcePath", "Resource Name", StringUtil.VALIDATION_TEXT); + searchUtil.extractString(request, searchCriteria, "clientIP", "Client IP", StringUtil.VALIDATION_TEXT); + searchUtil.extractString(request, searchCriteria, "resourceType", "Resource Type", StringUtil.VALIDATION_TEXT); + searchUtil.extractString(request, searchCriteria, "excludeServiceUser", "Exclude Service User", StringUtil.VALIDATION_TEXT); + + searchUtil.extractInt(request, searchCriteria, "auditType", "Audit Type"); + searchUtil.extractInt(request, searchCriteria, "accessResult", "Result"); + searchUtil.extractInt(request, searchCriteria, "assetId", "Asset ID"); + searchUtil.extractLong(request, searchCriteria, "policyId", "Policy ID"); + searchUtil.extractInt(request, searchCriteria, "repoType", "Service Type"); + searchUtil.extractDate(request, searchCriteria, "startDate", "Start Date", "MM/dd/yyyy"); + searchUtil.extractDate(request, searchCriteria, "endDate", "End Date", "MM/dd/yyyy"); + searchUtil.extractString(request, searchCriteria, "tags", "tags", null); + searchUtil.extractString(request, searchCriteria, "cluster", "Cluster Name", StringUtil.VALIDATION_TEXT); + searchUtil.extractStringList(request, searchCriteria, "zoneName", "Zone Name List", "zoneName", null, null); + searchUtil.extractString(request, searchCriteria, "agentHost", "Agent Host Name", StringUtil.VALIDATION_TEXT); + searchUtil.extractString(request, searchCriteria, "eventId", "Event Id", null); + + boolean isKeyAdmin = msBizUtil.isKeyAdmin(); + boolean isAuditKeyAdmin = msBizUtil.isAuditKeyAdmin(); + XXServiceDef xxServiceDef = daoManager.getXXServiceDef().findByName(EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_KMS_NAME); + + if (isKeyAdmin && xxServiceDef != null || isAuditKeyAdmin && xxServiceDef != null) { + searchCriteria.getParamList().put("repoType", xxServiceDef.getId()); + } else if (xxServiceDef != null) { + searchCriteria.getParamList().put("-repoType", xxServiceDef.getId()); + } + + VXAccessAuditList vxAccessAuditList = assetMgr.getAccessLogs(searchCriteria); + + if (timeZone != null && !StringUtils.isBlank(timeZone)) { + vxAccessAuditList.getVXAccessAudits().forEach(vxAccessAudit -> { + String zonedEventTime = convertToTimeZone(vxAccessAudit.getEventTime(), timeZone); + + if (zonedEventTime == null || zonedEventTime.isEmpty()) { + throw restErrorUtil.createRESTException(HttpServletResponse.SC_BAD_REQUEST, "Passed timeZone value is invalid", true); + } + + vxAccessAudit.setZonedEventTime(zonedEventTime); + }); + } else { + vxAccessAuditList.getVXAccessAudits().forEach(vxAccessAudit -> vxAccessAudit.setZonedEventTime(new SimpleDateFormat(RestUtil.ZONED_EVENT_TIME_FORMAT).format(vxAccessAudit.getEventTime()))); + } + + return vxAccessAuditList; + } + + @POST + @Path("/resources/grant") + @Consumes("application/json") + @Produces("application/json") + public VXPolicy grantPermission(@Context HttpServletRequest request, VXPolicy vXPolicy) { + RESTResponse ret; + + logger.debug("==> AssetREST.grantPermission({})", vXPolicy); + + if (vXPolicy != null) { + String serviceName = vXPolicy.getRepositoryName(); + GrantRevokeRequest grantRevokeRequest = serviceUtil.toGrantRevokeRequest(vXPolicy); + + try { + ret = serviceREST.grantAccess(serviceName, grantRevokeRequest, request); + } catch (WebApplicationException excp) { + throw excp; + } catch (Throwable e) { + logger.error("{} Grant Access Failed for the request {}", HttpServletResponse.SC_BAD_REQUEST, vXPolicy, e); + + throw restErrorUtil.createRESTException("Grant Access Failed for the request: " + vXPolicy + ". " + e.getMessage()); + } + } else { + logger.error("{} Bad Request parameter", HttpServletResponse.SC_BAD_REQUEST); + + throw restErrorUtil.createRESTException("Bad Request parameter"); + } + + logger.debug("<== AssetREST.grantPermission({})", ret); + + // TO DO Current Grant REST doesn't return a policy so returning a null value. Has to be replace with VXpolicy. + return vXPolicy; + } + + @POST + @Path("/resources/revoke") + @Consumes("application/json") + @Produces("application/json") + public VXPolicy revokePermission(@Context HttpServletRequest request, VXPolicy vXPolicy) { + RESTResponse ret; + + logger.debug("==> AssetREST.revokePermission({})", vXPolicy); + + if (vXPolicy != null) { + String serviceName = vXPolicy.getRepositoryName(); + GrantRevokeRequest grantRevokeRequest = serviceUtil.toGrantRevokeRequest(vXPolicy); + + try { + ret = serviceREST.revokeAccess(serviceName, grantRevokeRequest, request); + } catch (WebApplicationException excp) { + throw excp; + } catch (Throwable e) { + logger.error("{} Revoke Access Failed for the request {}", HttpServletResponse.SC_BAD_REQUEST, vXPolicy, e); + + throw restErrorUtil.createRESTException("Revoke Access Failed for the request: " + vXPolicy + ". " + e.getMessage()); + } + } else { + logger.error("{} Bad Request parameter", HttpServletResponse.SC_BAD_REQUEST); + + throw restErrorUtil.createRESTException("Bad Request parameter"); + } + + logger.debug("<== AssetREST.revokePermission({})", ret); + + return vXPolicy; + } + + @GET + @Path("/ugsyncAudits") + @Produces("application/json") + @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.GET_UGSYNC_AUDITS + "\")") + public VXUgsyncAuditInfoList getUgsyncAudits(@Context HttpServletRequest request) { + SearchCriteria searchCriteria = searchUtil.extractCommonCriterias(request, xAccessAuditService.sortFields); + + searchUtil.extractString(request, searchCriteria, "userName", "User Name", StringUtil.VALIDATION_TEXT); + searchUtil.extractString(request, searchCriteria, "sessionId", "Session Id", StringUtil.VALIDATION_TEXT); + searchUtil.extractString(request, searchCriteria, "syncSource", "Sync Source", StringUtil.VALIDATION_TEXT); + searchUtil.extractString(request, searchCriteria, "syncSourceInfo", "Sync Source Info", StringUtil.VALIDATION_TEXT); + searchUtil.extractLong(request, searchCriteria, "noOfUsers", "No of Users"); + searchUtil.extractLong(request, searchCriteria, "noOfGroups", "No of Groups"); + searchUtil.extractDate(request, searchCriteria, "startDate", "Start Date", "MM/dd/yyyy"); + searchUtil.extractDate(request, searchCriteria, "endDate", "End Date", "MM/dd/yyyy"); + + return assetMgr.getUgsyncAudits(searchCriteria); + } + + @GET + @Path("/ugsyncAudits/{syncSource}") + @Encoded + @Produces("application/json") + @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.GET_UGSYNC_AUDITS_BY_SYNCSOURCE + "\")") + public VXUgsyncAuditInfoList getUgsyncAuditsBySyncSource(@PathParam("syncSource") String syncSource) { + return assetMgr.getUgsyncAuditsBySyncSource(syncSource); + } } diff --git a/security-admin/src/main/java/org/apache/ranger/rest/GdsREST.java b/security-admin/src/main/java/org/apache/ranger/rest/GdsREST.java index 87eb6ea4d0..0d3ef3d767 100755 --- a/security-admin/src/main/java/org/apache/ranger/rest/GdsREST.java +++ b/security-admin/src/main/java/org/apache/ranger/rest/GdsREST.java @@ -20,7 +20,6 @@ package org.apache.ranger.rest; import org.apache.commons.collections4.CollectionUtils; -import java.util.function.Predicate; import org.apache.commons.lang.ArrayUtils; import org.apache.commons.lang.StringUtils; import org.apache.hadoop.thirdparty.com.google.common.annotations.VisibleForTesting; @@ -34,17 +33,16 @@ import org.apache.ranger.common.RangerSearchUtil; import org.apache.ranger.common.ServiceUtil; import org.apache.ranger.plugin.model.RangerGds; -import org.apache.ranger.plugin.model.RangerGds.DatasetSummary; -import org.apache.ranger.plugin.model.RangerGds.DataShareSummary; import org.apache.ranger.plugin.model.RangerGds.DataShareInDatasetSummary; +import org.apache.ranger.plugin.model.RangerGds.DataShareSummary; +import org.apache.ranger.plugin.model.RangerGds.DatasetSummary; +import org.apache.ranger.plugin.model.RangerGds.RangerDataShare; +import org.apache.ranger.plugin.model.RangerGds.RangerDataShareInDataset; import org.apache.ranger.plugin.model.RangerGds.RangerDataset; import org.apache.ranger.plugin.model.RangerGds.RangerDatasetInProject; -import org.apache.ranger.plugin.model.RangerGds.RangerDataShareInDataset; -import org.apache.ranger.plugin.model.RangerGds.RangerDataShare; import org.apache.ranger.plugin.model.RangerGds.RangerProject; import org.apache.ranger.plugin.model.RangerGds.RangerSharedResource; import org.apache.ranger.plugin.model.RangerGrant; - import org.apache.ranger.plugin.model.RangerPluginInfo; import org.apache.ranger.plugin.model.RangerPolicy; import org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyItem; @@ -61,13 +59,12 @@ import org.apache.ranger.plugin.util.SearchFilter; import org.apache.ranger.plugin.util.ServiceGdsInfo; import org.apache.ranger.security.context.RangerAPIList; -import org.apache.ranger.service.RangerGdsDatasetInProjectService; import org.apache.ranger.service.RangerGdsDataShareInDatasetService; import org.apache.ranger.service.RangerGdsDataShareService; +import org.apache.ranger.service.RangerGdsDatasetInProjectService; import org.apache.ranger.service.RangerGdsDatasetService; import org.apache.ranger.service.RangerGdsProjectService; import org.apache.ranger.service.RangerGdsSharedResourceService; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -79,8 +76,19 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import javax.ws.rs.*; +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.DefaultValue; +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.WebApplicationException; import javax.ws.rs.core.Context; + import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; @@ -89,6 +97,7 @@ import java.util.List; import java.util.Map; import java.util.Set; +import java.util.function.Predicate; import java.util.stream.Collectors; @Path("gds") @@ -99,20 +108,15 @@ public class GdsREST { private static final Logger LOG = LoggerFactory.getLogger(GdsREST.class); private static final Logger PERF_LOG = RangerPerfTracer.getPerfLogger("rest.GdsREST"); - private final RangerAdminConfig config = RangerAdminConfig.getInstance(); - - private final int SHARED_RESOURCES_MAX_BATCH_SIZE = config.getInt("ranger.admin.rest.gds.shared.resources.max.batch.size", 100); - - private static final String PRINCIPAL_TYPE_USER = RangerPrincipal.PrincipalType.USER.name().toLowerCase(); - - private static final String PRINCIPAL_TYPE_GROUP = RangerPrincipal.PrincipalType.GROUP.name().toLowerCase(); - - private static final String PRINCIPAL_TYPE_ROLE = RangerPrincipal.PrincipalType.ROLE.name().toLowerCase(); - - private static final String DEFAULT_PRINCIPAL_TYPE = PRINCIPAL_TYPE_USER; - public static final String GDS_POLICY_EXPR_CONDITION = "expression"; + private static final String PRINCIPAL_TYPE_USER = RangerPrincipal.PrincipalType.USER.name().toLowerCase(); + private static final String PRINCIPAL_TYPE_GROUP = RangerPrincipal.PrincipalType.GROUP.name().toLowerCase(); + private static final String PRINCIPAL_TYPE_ROLE = RangerPrincipal.PrincipalType.ROLE.name().toLowerCase(); + private static final String DEFAULT_PRINCIPAL_TYPE = PRINCIPAL_TYPE_USER; + private static final RangerAdminConfig config = RangerAdminConfig.getInstance(); + private static final int SHARED_RESOURCES_MAX_BATCH_SIZE = config.getInt("ranger.admin.rest.gds.shared.resources.max.batch.size", 100); + @Autowired GdsDBStore gdsStore; @@ -152,11 +156,10 @@ public class GdsREST { @Autowired AssetMgr assetMgr; - @POST @Path("/dataset") - @Consumes({ "application/json" }) - @Produces({ "application/json" }) + @Consumes("application/json") + @Produces("application/json") @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.CREATE_DATASET + "\")") public RangerDataset createDataset(RangerDataset dataset) { LOG.debug("==> GdsREST.createDataset({})", dataset); @@ -165,14 +168,14 @@ public RangerDataset createDataset(RangerDataset dataset) { RangerPerfTracer perf = null; try { - if(RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { + if (RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "GdsREST.createDataset(datasetName=" + dataset.getName() + ")"); } ret = gdsStore.createDataset(dataset); - } catch(WebApplicationException excp) { + } catch (WebApplicationException excp) { throw excp; - } catch(Throwable excp) { + } catch (Throwable excp) { LOG.error("createDataset({}) failed", dataset, excp); throw restErrorUtil.createRESTException(excp.getMessage()); @@ -187,32 +190,37 @@ public RangerDataset createDataset(RangerDataset dataset) { @POST @Path("/dataset/{id}/resources/{serviceName}") - @Consumes({ "application/json" }) - @Produces({ "application/json" }) + @Consumes("application/json") + @Produces("application/json") @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.ADD_SHARED_RESOURCES + "\")") - public List addDatasetResources(@PathParam("id") Long datasetId, - @PathParam("serviceName") String serviceName, - @QueryParam("zoneName") @DefaultValue("") String zoneName, - List resources) { + public List addDatasetResources(@PathParam("id") Long datasetId, @PathParam("serviceName") String serviceName, @QueryParam("zoneName") @DefaultValue("") String zoneName, List resources) { LOG.debug("==> GdsREST.addDatasetResources(datasetId={} serviceName={} zoneNam={} resources={})", datasetId, serviceName, zoneName, resources); List ret = new ArrayList<>(); RangerPerfTracer perf = null; try { + if (RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { + perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "GdsREST.addDatasetResources(datasetId=" + datasetId + ")"); + } + Long serviceId = validateAndGetServiceId(serviceName); Long zoneId = validateAndGetZoneId(zoneName); Long dataShareId = getOrCreateDataShare(datasetId, serviceId, zoneId, serviceName); + // Add resources to DataShare for (RangerSharedResource resource : resources) { resource.setDataShareId(dataShareId); + RangerSharedResource rangerSharedResource = addSharedResource(resource); + ret.add(rangerSharedResource); } - } catch(WebApplicationException excp) { + } catch (WebApplicationException excp) { throw excp; - } catch(Throwable excp) { + } catch (Throwable excp) { LOG.error("GdsREST.addDatasetResources(datasetId={} serviceName={} zoneName={} resources={}) failed!", datasetId, serviceName, zoneName, resources, excp); + throw restErrorUtil.createRESTException(excp.getMessage()); } finally { RangerPerfTracer.log(perf); @@ -225,8 +233,8 @@ public List addDatasetResources(@PathParam("id") Long data @POST @Path("/dataset/{id}/datashare") - @Consumes({ "application/json" }) - @Produces({ "application/json" }) + @Consumes("application/json") + @Produces("application/json") @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.ADD_DATASHARE_IN_DATASET + "\")") public List addDataSharesInDataset(@PathParam("id") Long datasetId, List dataSharesInDataset) { LOG.debug("==> GdsREST.addDataSharesInDataset({}, {})", datasetId, dataSharesInDataset); @@ -236,7 +244,7 @@ public List addDataSharesInDataset(@PathParam("id") Lo try { if (RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { - perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "GdsREST.addDataSharesInDataset(" + datasetId + ")"); + perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "GdsREST.addDataSharesInDataset(" + datasetId + ")"); } if (CollectionUtils.isNotEmpty(dataSharesInDataset)) { @@ -252,9 +260,9 @@ public List addDataSharesInDataset(@PathParam("id") Lo } ret = gdsStore.addDataSharesInDataset(dataSharesInDataset); - } catch(WebApplicationException excp) { + } catch (WebApplicationException excp) { throw excp; - } catch(Throwable excp) { + } catch (Throwable excp) { LOG.error("addDataShareInDataset({}) failed", datasetId, excp); throw restErrorUtil.createRESTException(excp.getMessage()); @@ -269,8 +277,8 @@ public List addDataSharesInDataset(@PathParam("id") Lo @PUT @Path("/dataset/{id}") - @Consumes({ "application/json" }) - @Produces({ "application/json" }) + @Consumes("application/json") + @Produces("application/json") @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.UPDATE_DATASET + "\")") public RangerDataset updateDataset(@PathParam("id") Long datasetId, RangerDataset dataset) { LOG.debug("==> GdsREST.updateDataset({}, {})", datasetId, dataset); @@ -279,16 +287,16 @@ public RangerDataset updateDataset(@PathParam("id") Long datasetId, RangerDatase RangerPerfTracer perf = null; try { - if(RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { + if (RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "GdsREST.updateDataset(datasetId=" + datasetId + ", datasetName=" + dataset.getName() + ")"); } dataset.setId(datasetId); ret = gdsStore.updateDataset(dataset); - } catch(WebApplicationException excp) { + } catch (WebApplicationException excp) { throw excp; - } catch(Throwable excp) { + } catch (Throwable excp) { LOG.error("updateDataset({}, {}) failed", datasetId, dataset, excp); throw restErrorUtil.createRESTException(excp.getMessage()); @@ -303,7 +311,7 @@ public RangerDataset updateDataset(@PathParam("id") Long datasetId, RangerDatase @DELETE @Path("/dataset/{id}") - @Produces({ "application/json" }) + @Produces("application/json") @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.DELETE_DATASET + "\")") public void deleteDataset(@PathParam("id") Long datasetId, @Context HttpServletRequest request) { LOG.debug("==> deleteDataset({})", datasetId); @@ -311,16 +319,16 @@ public void deleteDataset(@PathParam("id") Long datasetId, @Context HttpServletR RangerPerfTracer perf = null; try { - if(RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { + if (RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "GdsREST.deleteDataset(datasetId=" + datasetId + ")"); } boolean forceDelete = Boolean.parseBoolean(request.getParameter("forceDelete")); gdsStore.deleteDataset(datasetId, forceDelete); - } catch(WebApplicationException excp) { + } catch (WebApplicationException excp) { throw excp; - } catch(Throwable excp) { + } catch (Throwable excp) { LOG.error("deleteDataset({}) failed", datasetId, excp); throw restErrorUtil.createRESTException(excp.getMessage()); @@ -333,7 +341,7 @@ public void deleteDataset(@PathParam("id") Long datasetId, @Context HttpServletR @GET @Path("/dataset/{id}") - @Produces({ "application/json" }) + @Produces("application/json") @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.GET_DATASET + "\")") public RangerDataset getDataset(@PathParam("id") Long datasetId) { LOG.debug("==> GdsREST.getDataset({})", datasetId); @@ -342,7 +350,7 @@ public RangerDataset getDataset(@PathParam("id") Long datasetId) { RangerPerfTracer perf = null; try { - if(RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { + if (RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "GdsREST.getDataset(datasetId=" + datasetId + ")"); } @@ -351,9 +359,9 @@ public RangerDataset getDataset(@PathParam("id") Long datasetId) { if (ret == null) { throw restErrorUtil.createRESTException(HttpServletResponse.SC_NOT_FOUND, "no dataset with id=" + datasetId, false); } - } catch(WebApplicationException excp) { + } catch (WebApplicationException excp) { throw excp; - } catch(Throwable excp) { + } catch (Throwable excp) { LOG.error("getDataset({}) failed", datasetId, excp); throw restErrorUtil.createRESTException(excp.getMessage()); @@ -368,7 +376,7 @@ public RangerDataset getDataset(@PathParam("id") Long datasetId) { @GET @Path("/dataset") - @Produces({ "application/json" }) + @Produces("application/json") @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.SEARCH_DATASETS + "\")") public PList searchDatasets(@Context HttpServletRequest request) { LOG.debug("==> GdsREST.searchDatasets()"); @@ -378,7 +386,7 @@ public PList searchDatasets(@Context HttpServletRequest request) SearchFilter filter = null; try { - if(RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { + if (RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "GdsREST.searchDatasets()"); } @@ -388,9 +396,9 @@ public PList searchDatasets(@Context HttpServletRequest request) searchUtil.extractStringList(request, filter, SearchFilter.DATASET_KEYWORD, "Dataset Keyword List", "datasetKeywords", null, null); ret = gdsStore.searchDatasets(filter); - } catch(WebApplicationException excp) { + } catch (WebApplicationException excp) { throw excp; - } catch(Throwable excp) { + } catch (Throwable excp) { LOG.error("searchDatasets({}) failed", filter, excp); throw restErrorUtil.createRESTException(excp.getMessage()); @@ -405,7 +413,7 @@ public PList searchDatasets(@Context HttpServletRequest request) @GET @Path("/dataset/names") - @Produces({ "application/json" }) + @Produces("application/json") @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.LIST_DATASET_NAMES + "\")") public PList listDatasetNames(@Context HttpServletRequest request) { LOG.debug("==> GdsREST.listDatasetNames()"); @@ -418,9 +426,9 @@ public PList listDatasetNames(@Context HttpServletRequest request) { filter = searchUtil.getSearchFilter(request, datasetService.sortFields); ret = gdsStore.getDatasetNames(filter); - } catch(WebApplicationException excp) { + } catch (WebApplicationException excp) { throw excp; - } catch(Throwable excp) { + } catch (Throwable excp) { LOG.error("listDatasetNames({}) failed", filter, excp); throw restErrorUtil.createRESTException(excp.getMessage()); @@ -435,7 +443,7 @@ public PList listDatasetNames(@Context HttpServletRequest request) { @GET @Path("/dataset/summary") - @Produces({ "application/json" }) + @Produces("application/json") @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.GET_DATASET_SUMMARY + "\")") public PList getDatasetSummary(@Context HttpServletRequest request) { LOG.debug("==> GdsREST.getDatasetSummary()"); @@ -465,8 +473,8 @@ public PList getDatasetSummary(@Context HttpServletRequest reque @POST @Path(("/dataset/{id}/policy")) - @Consumes({ "application/json" }) - @Produces({ "application/json" }) + @Consumes("application/json") + @Produces("application/json") @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.DATASET_POLICY + "\")") public RangerPolicy addDatasetPolicy(@PathParam("id") Long datasetId, RangerPolicy policy) { LOG.debug("==> GdsREST.addDatasetPolicy({}, {})", datasetId, policy); @@ -493,8 +501,8 @@ public RangerPolicy addDatasetPolicy(@PathParam("id") Long datasetId, RangerPoli @PUT @Path(("/dataset/{id}/policy/{policyId}")) - @Consumes({ "application/json" }) - @Produces({ "application/json" }) + @Consumes("application/json") + @Produces("application/json") @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.DATASET_POLICY + "\")") public RangerPolicy updateDatasetPolicy(@PathParam("id") Long datasetId, @PathParam("policyId") Long policyId, RangerPolicy policy) { LOG.debug("==> GdsREST.updateDatasetPolicy({}, {})", datasetId, policy); @@ -504,6 +512,7 @@ public RangerPolicy updateDatasetPolicy(@PathParam("id") Long datasetId, @PathPa try { policy.setId(policyId); + ret = gdsStore.updateDatasetPolicy(datasetId, policy); } catch (WebApplicationException excp) { throw excp; @@ -545,7 +554,7 @@ public void deleteDatasetPolicy(@PathParam("id") Long datasetId, @PathParam("pol @GET @Path(("/dataset/{id}/policy/{policyId}")) - @Produces({ "application/json" }) + @Produces("application/json") @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.DATASET_POLICY + "\")") public RangerPolicy getDatasetPolicy(@PathParam("id") Long datasetId, @PathParam("policyId") Long policyId) { LOG.debug("==> GdsREST.getDatasetPolicy({}, {})", datasetId, policyId); @@ -572,7 +581,7 @@ public RangerPolicy getDatasetPolicy(@PathParam("id") Long datasetId, @PathParam @GET @Path(("/dataset/{id}/policy")) - @Produces({ "application/json" }) + @Produces("application/json") @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.DATASET_POLICY + "\")") public List getDatasetPolicies(@PathParam("id") Long datasetId, @Context HttpServletRequest request) { LOG.debug("==> GdsREST.getDatasetPolicies({})", datasetId); @@ -599,8 +608,8 @@ public List getDatasetPolicies(@PathParam("id") Long datasetId, @C @POST @Path("/project") - @Consumes({ "application/json" }) - @Produces({ "application/json" }) + @Consumes("application/json") + @Produces("application/json") @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.CREATE_PROJECT + "\")") public RangerProject createProject(RangerProject project) { LOG.debug("==> GdsREST.createProject({})", project); @@ -609,14 +618,14 @@ public RangerProject createProject(RangerProject project) { RangerPerfTracer perf = null; try { - if(RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { + if (RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "GdsREST.createProject(projectName=" + project.getName() + ")"); } ret = gdsStore.createProject(project); - } catch(WebApplicationException excp) { + } catch (WebApplicationException excp) { throw excp; - } catch(Throwable excp) { + } catch (Throwable excp) { LOG.error("createProject({}) failed", project, excp); throw restErrorUtil.createRESTException(excp.getMessage()); @@ -631,8 +640,8 @@ public RangerProject createProject(RangerProject project) { @PUT @Path("/project/{id}") - @Consumes({ "application/json" }) - @Produces({ "application/json" }) + @Consumes("application/json") + @Produces("application/json") @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.UPDATE_PROJECT + "\")") public RangerProject updateProject(@PathParam("id") Long projectId, RangerProject project) { LOG.debug("==> GdsREST.updateProject({}, {})", projectId, project); @@ -641,16 +650,16 @@ public RangerProject updateProject(@PathParam("id") Long projectId, RangerProjec RangerPerfTracer perf = null; try { - if(RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { + if (RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "GdsREST.updateProject(projectId=" + projectId + ", projectName=" + project.getName() + ")"); } project.setId(projectId); ret = gdsStore.updateProject(project); - } catch(WebApplicationException excp) { + } catch (WebApplicationException excp) { throw excp; - } catch(Throwable excp) { + } catch (Throwable excp) { LOG.error("updateProject({}, {}) failed", projectId, project, excp); throw restErrorUtil.createRESTException(excp.getMessage()); @@ -665,7 +674,7 @@ public RangerProject updateProject(@PathParam("id") Long projectId, RangerProjec @DELETE @Path("/project/{id}") - @Produces({ "application/json" }) + @Produces("application/json") @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.DELETE_PROJECT + "\")") public void deleteProject(@PathParam("id") Long projectId, @Context HttpServletRequest request) { LOG.debug("==> deleteProject({})", projectId); @@ -673,16 +682,16 @@ public void deleteProject(@PathParam("id") Long projectId, @Context HttpServletR RangerPerfTracer perf = null; try { - if(RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { + if (RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "GdsREST.deleteProject(projectId=" + projectId + ")"); } boolean forceDelete = Boolean.parseBoolean(request.getParameter("forceDelete")); gdsStore.deleteProject(projectId, forceDelete); - } catch(WebApplicationException excp) { + } catch (WebApplicationException excp) { throw excp; - } catch(Throwable excp) { + } catch (Throwable excp) { LOG.error("deleteProject({}) failed", projectId, excp); throw restErrorUtil.createRESTException(excp.getMessage()); @@ -695,7 +704,7 @@ public void deleteProject(@PathParam("id") Long projectId, @Context HttpServletR @GET @Path("/project/{id}") - @Produces({ "application/json" }) + @Produces("application/json") @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.GET_PROJECT + "\")") public RangerProject getProject(@PathParam("id") Long projectId) { LOG.debug("==> GdsREST.getProject({})", projectId); @@ -704,7 +713,7 @@ public RangerProject getProject(@PathParam("id") Long projectId) { RangerPerfTracer perf = null; try { - if(RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { + if (RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "GdsREST.getProject(projectId=" + projectId + ")"); } @@ -713,9 +722,9 @@ public RangerProject getProject(@PathParam("id") Long projectId) { if (ret == null) { throw restErrorUtil.createRESTException(HttpServletResponse.SC_NOT_FOUND, "no project with id=" + projectId, false); } - } catch(WebApplicationException excp) { + } catch (WebApplicationException excp) { throw excp; - } catch(Throwable excp) { + } catch (Throwable excp) { LOG.error("getProject({}) failed", projectId, excp); throw restErrorUtil.createRESTException(excp.getMessage()); @@ -730,7 +739,7 @@ public RangerProject getProject(@PathParam("id") Long projectId) { @GET @Path("/project") - @Produces({ "application/json" }) + @Produces("application/json") @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.SEARCH_PROJECTS + "\")") public PList searchProjects(@Context HttpServletRequest request) { LOG.debug("==> GdsREST.searchProjects()"); @@ -743,9 +752,9 @@ public PList searchProjects(@Context HttpServletRequest request) filter = searchUtil.getSearchFilter(request, projectService.sortFields); ret = gdsStore.searchProjects(filter); - } catch(WebApplicationException excp) { + } catch (WebApplicationException excp) { throw excp; - } catch(Throwable excp) { + } catch (Throwable excp) { LOG.error("searchProjects({}) failed", filter, excp); throw restErrorUtil.createRESTException(excp.getMessage()); @@ -760,7 +769,7 @@ public PList searchProjects(@Context HttpServletRequest request) @GET @Path("/project/names") - @Produces({ "application/json" }) + @Produces("application/json") @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.LIST_PROJECT_NAMES + "\")") public PList listProjectNames(@Context HttpServletRequest request) { LOG.debug("==> GdsREST.listProjectNames()"); @@ -773,9 +782,9 @@ public PList listProjectNames(@Context HttpServletRequest request) { filter = searchUtil.getSearchFilter(request, projectService.sortFields); ret = gdsStore.getProjectNames(filter); - } catch(WebApplicationException excp) { + } catch (WebApplicationException excp) { throw excp; - } catch(Throwable excp) { + } catch (Throwable excp) { LOG.error("listProjectNames({}) failed", filter, excp); throw restErrorUtil.createRESTException(excp.getMessage()); @@ -790,8 +799,8 @@ public PList listProjectNames(@Context HttpServletRequest request) { @POST @Path(("/project/{id}/policy")) - @Consumes({ "application/json" }) - @Produces({ "application/json" }) + @Consumes("application/json") + @Produces("application/json") @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.PROJECT_POLICY + "\")") public RangerPolicy addProjectPolicy(@PathParam("id") Long projectId, RangerPolicy policy) { LOG.debug("==> GdsREST.addProjectPolicy({}, {})", projectId, policy); @@ -818,8 +827,8 @@ public RangerPolicy addProjectPolicy(@PathParam("id") Long projectId, RangerPoli @PUT @Path(("/project/{id}/policy/{policyId}")) - @Consumes({ "application/json" }) - @Produces({ "application/json" }) + @Consumes("application/json") + @Produces("application/json") @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.PROJECT_POLICY + "\")") public RangerPolicy updateProjectPolicy(@PathParam("id") Long projectId, @PathParam("policyId") Long policyId, RangerPolicy policy) { LOG.debug("==> GdsREST.updateProjectPolicy({}, {})", projectId, policy); @@ -829,6 +838,7 @@ public RangerPolicy updateProjectPolicy(@PathParam("id") Long projectId, @PathPa try { policy.setId(policyId); + ret = gdsStore.updateProjectPolicy(projectId, policy); } catch (WebApplicationException excp) { throw excp; @@ -870,7 +880,7 @@ public void deleteProjectPolicy(@PathParam("id") Long projectId, @PathParam("pol @GET @Path(("/project/{id}/policy/{policyId}")) - @Produces({ "application/json" }) + @Produces("application/json") @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.PROJECT_POLICY + "\")") public RangerPolicy getProjectPolicy(@PathParam("id") Long projectId, @PathParam("policyId") Long policyId) { LOG.debug("==> GdsREST.getProjectPolicy({}, {})", projectId, policyId); @@ -897,7 +907,7 @@ public RangerPolicy getProjectPolicy(@PathParam("id") Long projectId, @PathParam @GET @Path(("/project/{id}/policy")) - @Produces({ "application/json" }) + @Produces("application/json") @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.PROJECT_POLICY + "\")") public List getProjectPolicies(@PathParam("id") Long projectId, @Context HttpServletRequest request) { LOG.debug("==> GdsREST.getProjectPolicies({})", projectId); @@ -924,8 +934,8 @@ public List getProjectPolicies(@PathParam("id") Long projectId, @C @POST @Path("/datashare") - @Consumes({ "application/json" }) - @Produces({ "application/json" }) + @Consumes("application/json") + @Produces("application/json") @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.CREATE_DATA_SHARE + "\")") public RangerDataShare createDataShare(RangerDataShare dataShare) { LOG.debug("==> GdsREST.createDataShare({})", dataShare); @@ -934,14 +944,14 @@ public RangerDataShare createDataShare(RangerDataShare dataShare) { RangerPerfTracer perf = null; try { - if(RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { + if (RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "GdsREST.createDataShare(" + dataShare + ")"); } ret = gdsStore.createDataShare(dataShare); - } catch(WebApplicationException excp) { + } catch (WebApplicationException excp) { throw excp; - } catch(Throwable excp) { + } catch (Throwable excp) { LOG.error("createDataShare({}) failed", dataShare, excp); throw restErrorUtil.createRESTException(excp.getMessage()); @@ -956,8 +966,8 @@ public RangerDataShare createDataShare(RangerDataShare dataShare) { @PUT @Path("/datashare/{id}") - @Consumes({ "application/json" }) - @Produces({ "application/json" }) + @Consumes("application/json") + @Produces("application/json") @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.UPDATE_DATA_SHARE + "\")") public RangerDataShare updateDataShare(@PathParam("id") Long dataShareId, RangerDataShare dataShare) { LOG.debug("==> GdsREST.updateDataShare({}, {})", dataShareId, dataShare); @@ -966,16 +976,16 @@ public RangerDataShare updateDataShare(@PathParam("id") Long dataShareId, Ranger RangerPerfTracer perf = null; try { - if(RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { + if (RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "GdsREST.updateDataShare(" + dataShare + ")"); } dataShare.setId(dataShareId); ret = gdsStore.updateDataShare(dataShare); - } catch(WebApplicationException excp) { + } catch (WebApplicationException excp) { throw excp; - } catch(Throwable excp) { + } catch (Throwable excp) { LOG.error("updateDataShare({}, {}) failed", dataShareId, dataShare, excp); throw restErrorUtil.createRESTException(excp.getMessage()); @@ -990,7 +1000,7 @@ public RangerDataShare updateDataShare(@PathParam("id") Long dataShareId, Ranger @DELETE @Path("/datashare/{id}") - @Produces({ "application/json" }) + @Produces("application/json") @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.DELETE_DATA_SHARE + "\")") public void deleteDataShare(@PathParam("id") Long dataShareId, @Context HttpServletRequest request) { LOG.debug("==> GdsREST.deleteDataShare({})", dataShareId); @@ -998,17 +1008,17 @@ public void deleteDataShare(@PathParam("id") Long dataShareId, @Context HttpServ RangerPerfTracer perf = null; try { - if(RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { + if (RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "GdsREST.deleteDataShare(" + dataShareId + ")"); } - String forceDeleteStr = request.getParameter("forceDelete"); - boolean forceDelete = !StringUtils.isEmpty(forceDeleteStr) && "true".equalsIgnoreCase(forceDeleteStr); + String forceDeleteStr = request.getParameter("forceDelete"); + boolean forceDelete = !StringUtils.isEmpty(forceDeleteStr) && "true".equalsIgnoreCase(forceDeleteStr); gdsStore.deleteDataShare(dataShareId, forceDelete); - } catch(WebApplicationException excp) { + } catch (WebApplicationException excp) { throw excp; - } catch(Throwable excp) { + } catch (Throwable excp) { LOG.error("deleteDataShare({}) failed", dataShareId, excp); throw restErrorUtil.createRESTException(excp.getMessage()); @@ -1021,7 +1031,7 @@ public void deleteDataShare(@PathParam("id") Long dataShareId, @Context HttpServ @GET @Path("/datashare/{id}") - @Produces({ "application/json" }) + @Produces("application/json") @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.GET_DATA_SHARE + "\")") public RangerDataShare getDataShare(@PathParam("id") Long dataShareId) { LOG.debug("==> GdsREST.getDataShare({})", dataShareId); @@ -1030,7 +1040,7 @@ public RangerDataShare getDataShare(@PathParam("id") Long dataShareId) { RangerPerfTracer perf = null; try { - if(RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { + if (RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "GdsREST.getDataShare(" + dataShareId + ")"); } @@ -1039,9 +1049,9 @@ public RangerDataShare getDataShare(@PathParam("id") Long dataShareId) { if (ret == null) { throw restErrorUtil.createRESTException(HttpServletResponse.SC_NOT_FOUND, "no dataShare with id=" + dataShareId, false); } - } catch(WebApplicationException excp) { + } catch (WebApplicationException excp) { throw excp; - } catch(Throwable excp) { + } catch (Throwable excp) { LOG.error("getDataShare({}) failed", dataShareId, excp); throw restErrorUtil.createRESTException(excp.getMessage()); @@ -1056,7 +1066,7 @@ public RangerDataShare getDataShare(@PathParam("id") Long dataShareId) { @GET @Path("/datashare") - @Produces({ "application/json" }) + @Produces("application/json") @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.SEARCH_DATA_SHARES + "\")") public PList searchDataShares(@Context HttpServletRequest request) { LOG.debug("==> GdsREST.searchDataShares()"); @@ -1069,9 +1079,9 @@ public PList searchDataShares(@Context HttpServletRequest reque filter = searchUtil.getSearchFilter(request, dataShareService.sortFields); ret = gdsStore.searchDataShares(filter); - } catch(WebApplicationException excp) { + } catch (WebApplicationException excp) { throw excp; - } catch(Throwable excp) { + } catch (Throwable excp) { LOG.error("searchDataShares({}) failed", filter, excp); throw restErrorUtil.createRESTException(excp.getMessage()); @@ -1086,7 +1096,7 @@ public PList searchDataShares(@Context HttpServletRequest reque @GET @Path("/datashare/summary") - @Produces({ "application/json" }) + @Produces("application/json") @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.GET_DATA_SHARE_SUMMARY + "\")") public PList getDataShareSummary(@Context HttpServletRequest request) { LOG.debug("==> GdsREST.getDataShareSummary()"); @@ -1115,8 +1125,8 @@ public PList getDataShareSummary(@Context HttpServletRequest r @POST @Path("/resource") - @Consumes({ "application/json" }) - @Produces({ "application/json" }) + @Consumes("application/json") + @Produces("application/json") @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.ADD_SHARED_RESOURCE + "\")") public RangerSharedResource addSharedResource(RangerSharedResource resource) { LOG.debug("==> GdsREST.addSharedResource({})", resource); @@ -1125,16 +1135,16 @@ public RangerSharedResource addSharedResource(RangerSharedResource resource) { RangerPerfTracer perf = null; try { - if(RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { + if (RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "GdsREST.addSharedResource(" + resource + ")"); } - List sharedResources = gdsStore.addSharedResources(Arrays.asList(resource)); + List sharedResources = gdsStore.addSharedResources(Collections.singletonList(resource)); ret = CollectionUtils.isNotEmpty(sharedResources) ? sharedResources.get(0) : null; - } catch(WebApplicationException excp) { + } catch (WebApplicationException excp) { throw excp; - } catch(Throwable excp) { + } catch (Throwable excp) { LOG.error("addSharedResource({}) failed", resource, excp); throw restErrorUtil.createRESTException(excp.getMessage()); @@ -1149,8 +1159,8 @@ public RangerSharedResource addSharedResource(RangerSharedResource resource) { @POST @Path("/resources") - @Consumes({ "application/json" }) - @Produces({ "application/json" }) + @Consumes("application/json") + @Produces("application/json") @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.ADD_SHARED_RESOURCES + "\")") public List addSharedResources(List resources) { LOG.debug("==> GdsREST.addSharedResources({})", resources); @@ -1168,9 +1178,9 @@ public List addSharedResources(List } ret = gdsStore.addSharedResources(resources); - } catch(WebApplicationException excp) { + } catch (WebApplicationException excp) { throw excp; - } catch(Throwable excp) { + } catch (Throwable excp) { LOG.error("addSharedResources({}) failed", resources, excp); throw restErrorUtil.createRESTException(excp.getMessage()); @@ -1185,26 +1195,26 @@ public List addSharedResources(List @PUT @Path("/resource/{id}") - @Consumes({ "application/json" }) - @Produces({ "application/json" }) + @Consumes("application/json") + @Produces("application/json") @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.UPDATE_SHARED_RESOURCE + "\")") public RangerSharedResource updateSharedResource(@PathParam("id") Long resourceId, RangerSharedResource resource) { LOG.debug("==> GdsREST.updateSharedResource({}, {})", resourceId, resource); - RangerSharedResource ret; - RangerPerfTracer perf = null; + RangerSharedResource ret; + RangerPerfTracer perf = null; try { - if(RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { + if (RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "GdsREST.updateSharedResource(" + resource + ")"); } resource.setId(resourceId); ret = gdsStore.updateSharedResource(resource); - } catch(WebApplicationException excp) { + } catch (WebApplicationException excp) { throw excp; - } catch(Throwable excp) { + } catch (Throwable excp) { LOG.error("updateSharedResource({}, {}) failed", resourceId, resource, excp); throw restErrorUtil.createRESTException(excp.getMessage()); @@ -1219,7 +1229,7 @@ public RangerSharedResource updateSharedResource(@PathParam("id") Long resourceI @DELETE @Path("/resource/{id}") - @Produces({ "application/json" }) + @Produces("application/json") @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.REMOVE_SHARED_RESOURCE + "\")") public void removeSharedResource(@PathParam("id") Long resourceId) { LOG.debug("==> GdsREST.removeSharedResource({})", resourceId); @@ -1227,14 +1237,14 @@ public void removeSharedResource(@PathParam("id") Long resourceId) { RangerPerfTracer perf = null; try { - if(RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { + if (RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "GdsREST.removeSharedResource(" + resourceId + ")"); } - gdsStore.removeSharedResources(Arrays.asList(resourceId)); - } catch(WebApplicationException excp) { + gdsStore.removeSharedResources(Collections.singletonList(resourceId)); + } catch (WebApplicationException excp) { throw excp; - } catch(Throwable excp) { + } catch (Throwable excp) { LOG.error("removeSharedResource({}) failed", resourceId, excp); throw restErrorUtil.createRESTException(excp.getMessage()); @@ -1263,9 +1273,9 @@ public void removeSharedResources(List resourceIds) { } gdsStore.removeSharedResources(resourceIds); - } catch(WebApplicationException excp) { + } catch (WebApplicationException excp) { throw excp; - } catch(Throwable excp) { + } catch (Throwable excp) { LOG.error("removeSharedResources({}) failed", resourceIds, excp); throw restErrorUtil.createRESTException(excp.getMessage()); @@ -1278,16 +1288,16 @@ public void removeSharedResources(List resourceIds) { @GET @Path("/resource/{id}") - @Produces({ "application/json" }) + @Produces("application/json") @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.GET_SHARED_RESOURCE + "\")") public RangerSharedResource getSharedResource(@PathParam("id") Long resourceId) { LOG.debug("==> GdsREST.getSharedResource({})", resourceId); - RangerSharedResource ret; - RangerPerfTracer perf = null; + RangerSharedResource ret; + RangerPerfTracer perf = null; try { - if(RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { + if (RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "GdsREST.getSharedResource(" + resourceId + ")"); } @@ -1296,9 +1306,9 @@ public RangerSharedResource getSharedResource(@PathParam("id") Long resourceId) if (ret == null) { throw restErrorUtil.createRESTException(HttpServletResponse.SC_NOT_FOUND, "no shared-resource with id=" + resourceId, false); } - } catch(WebApplicationException excp) { + } catch (WebApplicationException excp) { throw excp; - } catch(Throwable excp) { + } catch (Throwable excp) { LOG.error("getSharedResource({}) failed", resourceId, excp); throw restErrorUtil.createRESTException(excp.getMessage()); @@ -1313,7 +1323,7 @@ public RangerSharedResource getSharedResource(@PathParam("id") Long resourceId) @GET @Path("/resource") - @Produces({ "application/json" }) + @Produces("application/json") @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.SEARCH_SHARED_RESOURCES + "\")") public PList searchSharedResources(@Context HttpServletRequest request) { LOG.debug("==> GdsREST.searchSharedResources()"); @@ -1326,9 +1336,9 @@ public PList searchSharedResources(@Context HttpServletReq filter = searchUtil.getSearchFilter(request, sharedResourceService.sortFields); ret = gdsStore.searchSharedResources(filter); - } catch(WebApplicationException excp) { + } catch (WebApplicationException excp) { throw excp; - } catch(Throwable excp) { + } catch (Throwable excp) { LOG.error("searchSharedResources({}) failed", filter, excp); throw restErrorUtil.createRESTException(excp.getMessage()); @@ -1343,8 +1353,8 @@ public PList searchSharedResources(@Context HttpServletReq @POST @Path("/datashare/dataset") - @Consumes({ "application/json" }) - @Produces({ "application/json" }) + @Consumes("application/json") + @Produces("application/json") @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.ADD_DATASHARE_IN_DATASET + "\")") public RangerDataShareInDataset addDataShareInDataset(RangerDataShareInDataset datasetData) { LOG.debug("==> GdsREST.addDataShareInDataset({})", datasetData); @@ -1353,14 +1363,14 @@ public RangerDataShareInDataset addDataShareInDataset(RangerDataShareInDataset d RangerPerfTracer perf = null; try { - if(RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { - perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "GdsREST.addDataShareInDataset(" + datasetData + ")"); + if (RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { + perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "GdsREST.addDataShareInDataset(" + datasetData + ")"); } ret = gdsStore.addDataShareInDataset(datasetData); - } catch(WebApplicationException excp) { + } catch (WebApplicationException excp) { throw excp; - } catch(Throwable excp) { + } catch (Throwable excp) { LOG.error("addDataShareInDataset({}) failed", datasetData, excp); throw restErrorUtil.createRESTException(excp.getMessage()); @@ -1375,8 +1385,8 @@ public RangerDataShareInDataset addDataShareInDataset(RangerDataShareInDataset d @PUT @Path("/datashare/dataset/{id}") - @Consumes({ "application/json" }) - @Produces({ "application/json" }) + @Consumes("application/json") + @Produces("application/json") @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.UPDATE_DATASHARE_IN_DATASET + "\")") public RangerDataShareInDataset updateDataShareInDataset(@PathParam("id") Long id, RangerDataShareInDataset dataShareInDataset) { LOG.debug("==> GdsREST.updateDataShareInDataset({}, {})", id, dataShareInDataset); @@ -1385,16 +1395,16 @@ public RangerDataShareInDataset updateDataShareInDataset(@PathParam("id") Long i RangerPerfTracer perf = null; try { - if(RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { - perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "GdsREST.updateDataShareInDataset(" + dataShareInDataset + ")"); + if (RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { + perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "GdsREST.updateDataShareInDataset(" + dataShareInDataset + ")"); } dataShareInDataset.setId(id); ret = gdsStore.updateDataShareInDataset(dataShareInDataset); - } catch(WebApplicationException excp) { + } catch (WebApplicationException excp) { throw excp; - } catch(Throwable excp) { + } catch (Throwable excp) { LOG.error("updateDataShareInDataset({}) failed", dataShareInDataset, excp); throw restErrorUtil.createRESTException(excp.getMessage()); @@ -1416,14 +1426,14 @@ public void removeDataShareInDataset(@PathParam("id") Long id) { RangerPerfTracer perf = null; try { - if(RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { - perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "GdsREST.removeDatasetData(" + id + ")"); + if (RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { + perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "GdsREST.removeDatasetData(" + id + ")"); } gdsStore.removeDataShareInDataset(id); - } catch(WebApplicationException excp) { + } catch (WebApplicationException excp) { throw excp; - } catch(Throwable excp) { + } catch (Throwable excp) { LOG.error("removeDatasetData({}) failed", id, excp); throw restErrorUtil.createRESTException(excp.getMessage()); @@ -1436,7 +1446,7 @@ public void removeDataShareInDataset(@PathParam("id") Long id) { @GET @Path("/datashare/dataset/{id}") - @Produces({ "application/json" }) + @Produces("application/json") @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.GET_DATASHARE_IN_DATASET + "\")") public RangerDataShareInDataset getDataShareInDataset(@PathParam("id") Long id) { LOG.debug("==> GdsREST.updateDataShareInDataset({})", id); @@ -1445,14 +1455,14 @@ public RangerDataShareInDataset getDataShareInDataset(@PathParam("id") Long id) RangerPerfTracer perf = null; try { - if(RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { - perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "GdsREST.getDataShareInDataset(" + id + ")"); + if (RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { + perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "GdsREST.getDataShareInDataset(" + id + ")"); } ret = gdsStore.getDataShareInDataset(id); - } catch(WebApplicationException excp) { + } catch (WebApplicationException excp) { throw excp; - } catch(Throwable excp) { + } catch (Throwable excp) { LOG.error("getDataShareInDataset({}) failed", id, excp); throw restErrorUtil.createRESTException(excp.getMessage()); @@ -1467,22 +1477,22 @@ public RangerDataShareInDataset getDataShareInDataset(@PathParam("id") Long id) @GET @Path("/datashare/dataset") - @Produces({ "application/json" }) + @Produces("application/json") @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.SEARCH_DATASHARE_IN_DATASET + "\")") public PList searchDataShareInDatasets(@Context HttpServletRequest request) { LOG.debug("==> GdsREST.searchDataShareInDatasets()"); PList ret; - RangerPerfTracer perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "GdsREST.searchDataShareInDatasets()"); - SearchFilter filter = null; + RangerPerfTracer perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "GdsREST.searchDataShareInDatasets()"); + SearchFilter filter = null; try { filter = searchUtil.getSearchFilter(request, dshidService.sortFields); ret = gdsStore.searchDataShareInDatasets(filter); - } catch(WebApplicationException excp) { + } catch (WebApplicationException excp) { throw excp; - } catch(Throwable excp) { + } catch (Throwable excp) { LOG.error("searchDataShareInDatasets({}) failed", filter, excp); throw restErrorUtil.createRESTException(excp.getMessage()); @@ -1495,56 +1505,56 @@ public PList searchDataShareInDatasets(@Context HttpSe return ret; } - @GET - @Path("/datashare/dataset/summary") - @Produces({ "application/json" }) - @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.SEARCH_DATASHARE_IN_DATASET_SUMMARY + "\")") - public PList getDshInDsSummary(@Context HttpServletRequest request) { - LOG.debug("==> GdsREST.searchDshInDsSummary()"); + @GET + @Path("/datashare/dataset/summary") + @Produces("application/json") + @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.SEARCH_DATASHARE_IN_DATASET_SUMMARY + "\")") + public PList getDshInDsSummary(@Context HttpServletRequest request) { + LOG.debug("==> GdsREST.searchDshInDsSummary()"); - PList ret; - SearchFilter filter = null; - RangerPerfTracer perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "GdsREST.getDshInDsSummary()"); + PList ret; + SearchFilter filter = null; + RangerPerfTracer perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "GdsREST.getDshInDsSummary()"); - try { - filter = searchUtil.getSearchFilter(request, dshidService.sortFields); + try { + filter = searchUtil.getSearchFilter(request, dshidService.sortFields); - ret = gdsStore.getDshInDsSummary(filter); - } catch (WebApplicationException excp) { - throw excp; - } catch (Throwable excp) { - LOG.error("getDshInDsSummary({}) failed", filter, excp); + ret = gdsStore.getDshInDsSummary(filter); + } catch (WebApplicationException excp) { + throw excp; + } catch (Throwable excp) { + LOG.error("getDshInDsSummary({}) failed", filter, excp); - throw restErrorUtil.createRESTException(excp.getMessage()); - } finally { - RangerPerfTracer.log(perf); - } + throw restErrorUtil.createRESTException(excp.getMessage()); + } finally { + RangerPerfTracer.log(perf); + } - LOG.debug("<== GdsREST.getDshInDsSummary({}): {}", filter, ret); + LOG.debug("<== GdsREST.getDshInDsSummary({}): {}", filter, ret); - return ret; - } + return ret; + } @POST @Path("/dataset/project") - @Consumes({ "application/json" }) - @Produces({ "application/json" }) + @Consumes("application/json") + @Produces("application/json") @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.ADD_DATASET_IN_PROJECT + "\")") public RangerDatasetInProject addDatasetInProject(RangerDatasetInProject projectData) { LOG.debug("==> GdsREST.addDatasetInProject({})", projectData); RangerDatasetInProject ret; - RangerPerfTracer perf = null; + RangerPerfTracer perf = null; try { - if(RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { - perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "GdsREST.addDatasetInProject(" + projectData + ")"); + if (RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { + perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "GdsREST.addDatasetInProject(" + projectData + ")"); } ret = gdsStore.addDatasetInProject(projectData); - } catch(WebApplicationException excp) { + } catch (WebApplicationException excp) { throw excp; - } catch(Throwable excp) { + } catch (Throwable excp) { LOG.error("addDatasetInProject({}) failed", projectData, excp); throw restErrorUtil.createRESTException(excp.getMessage()); @@ -1559,26 +1569,26 @@ public RangerDatasetInProject addDatasetInProject(RangerDatasetInProject project @PUT @Path("/dataset/project/{id}") - @Consumes({ "application/json" }) - @Produces({ "application/json" }) + @Consumes("application/json") + @Produces("application/json") @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.UPDATE_DATASET_IN_PROJECT + "\")") public RangerDatasetInProject updateDatasetInProject(@PathParam("id") Long id, RangerDatasetInProject dataShareInProject) { LOG.debug("==> GdsREST.updateDatasetInProject({}, {})", id, dataShareInProject); RangerDatasetInProject ret; - RangerPerfTracer perf = null; + RangerPerfTracer perf = null; try { - if(RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { - perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "GdsREST.updateDatasetInProject(" + dataShareInProject + ")"); + if (RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { + perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "GdsREST.updateDatasetInProject(" + dataShareInProject + ")"); } dataShareInProject.setId(id); ret = gdsStore.updateDatasetInProject(dataShareInProject); - } catch(WebApplicationException excp) { + } catch (WebApplicationException excp) { throw excp; - } catch(Throwable excp) { + } catch (Throwable excp) { LOG.error("updateDatasetInProject({}) failed", dataShareInProject, excp); throw restErrorUtil.createRESTException(excp.getMessage()); @@ -1600,14 +1610,14 @@ public void removeDatasetInProject(@PathParam("id") Long id) { RangerPerfTracer perf = null; try { - if(RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { - perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "GdsREST.removeProjectData(" + id + ")"); + if (RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { + perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "GdsREST.removeProjectData(" + id + ")"); } gdsStore.removeDatasetInProject(id); - } catch(WebApplicationException excp) { + } catch (WebApplicationException excp) { throw excp; - } catch(Throwable excp) { + } catch (Throwable excp) { LOG.error("removeProjectData({}) failed", id, excp); throw restErrorUtil.createRESTException(excp.getMessage()); @@ -1620,7 +1630,7 @@ public void removeDatasetInProject(@PathParam("id") Long id) { @GET @Path("/dataset/project/{id}") - @Produces({ "application/json" }) + @Produces("application/json") @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.GET_DATASET_IN_PROJECT + "\")") public RangerDatasetInProject getDatasetInProject(@PathParam("id") Long id) { LOG.debug("==> GdsREST.getDatasetInProject({})", id); @@ -1630,7 +1640,7 @@ public RangerDatasetInProject getDatasetInProject(@PathParam("id") Long id) { try { if (RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { - perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "GdsREST.getDatasetInProject(" + id + ")"); + perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "GdsREST.getDatasetInProject(" + id + ")"); } ret = gdsStore.getDatasetInProject(id); @@ -1651,7 +1661,7 @@ public RangerDatasetInProject getDatasetInProject(@PathParam("id") Long id) { @GET @Path("/dataset/project") - @Produces({ "application/json" }) + @Produces("application/json") @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.SEARCH_DATASET_IN_PROJECT + "\")") public PList searchDatasetInProjects(@Context HttpServletRequest request) { LOG.debug("==> GdsREST.searchDatasetInProjects()"); @@ -1664,9 +1674,9 @@ public PList searchDatasetInProjects(@Context HttpServle filter = searchUtil.getSearchFilter(request, dipService.sortFields); ret = gdsStore.searchDatasetInProjects(filter); - } catch(WebApplicationException excp) { + } catch (WebApplicationException excp) { throw excp; - } catch(Throwable excp) { + } catch (Throwable excp) { LOG.error("searchDatasetInProjects({}) failed", filter, excp); throw restErrorUtil.createRESTException(excp.getMessage()); @@ -1679,17 +1689,10 @@ public PList searchDatasetInProjects(@Context HttpServle return ret; } - @GET @Path("/download/{serviceName}") - @Produces({ "application/json" }) - public ServiceGdsInfo getServiceGdsInfoIfUpdated(@PathParam("serviceName") String serviceName, - @QueryParam("lastKnownGdsVersion") @DefaultValue("-1") Long lastKnownVersion, - @QueryParam("lastActivationTime") @DefaultValue("0") Long lastActivationTime, - @QueryParam("pluginId") String pluginId, - @QueryParam("clusterName") @DefaultValue("") String clusterName, - @QueryParam("pluginCapabilities") @DefaultValue("") String pluginCapabilities, - @Context HttpServletRequest request) { + @Produces("application/json") + public ServiceGdsInfo getServiceGdsInfoIfUpdated(@PathParam("serviceName") String serviceName, @QueryParam("lastKnownGdsVersion") @DefaultValue("-1") Long lastKnownVersion, @QueryParam("lastActivationTime") @DefaultValue("0") Long lastActivationTime, @QueryParam("pluginId") String pluginId, @QueryParam("clusterName") @DefaultValue("") String clusterName, @QueryParam("pluginCapabilities") @DefaultValue("") String pluginCapabilities, @Context HttpServletRequest request) { LOG.debug("==> GdsREST.getServiceGdsInfoIfUpdated(serviceName={}, lastKnownVersion={}, lastActivationTime={}, pluginId={}, clusterName={}, pluginCapabilities{})", serviceName, lastKnownVersion, lastActivationTime, pluginId, clusterName, pluginCapabilities); ServiceGdsInfo ret = null; @@ -1738,14 +1741,8 @@ public ServiceGdsInfo getServiceGdsInfoIfUpdated(@PathParam("serviceName") Strin @GET @Path("/secure/download/{serviceName}") - @Produces({ "application/json" }) - public ServiceGdsInfo getSecureServiceGdsInfoIfUpdated(@PathParam("serviceName") String serviceName, - @QueryParam("lastKnownGdsVersion") @DefaultValue("-1") Long lastKnownVersion, - @QueryParam("lastActivationTime") @DefaultValue("0") Long lastActivationTime, - @QueryParam("pluginId") String pluginId, - @QueryParam("clusterName") @DefaultValue("") String clusterName, - @QueryParam("pluginCapabilities") @DefaultValue("") String pluginCapabilities, - @Context HttpServletRequest request) { + @Produces("application/json") + public ServiceGdsInfo getSecureServiceGdsInfoIfUpdated(@PathParam("serviceName") String serviceName, @QueryParam("lastKnownGdsVersion") @DefaultValue("-1") Long lastKnownVersion, @QueryParam("lastActivationTime") @DefaultValue("0") Long lastActivationTime, @QueryParam("pluginId") String pluginId, @QueryParam("clusterName") @DefaultValue("") String clusterName, @QueryParam("pluginCapabilities") @DefaultValue("") String pluginCapabilities, @Context HttpServletRequest request) { LOG.debug("==> GdsREST.getSecureServiceGdsInfoIfUpdated(serviceName={}, lastKnownVersion={}, lastActivationTime={}, pluginId={}, clusterName={}, pluginCapabilities{})", serviceName, lastKnownVersion, lastActivationTime, pluginId, clusterName, pluginCapabilities); ServiceGdsInfo ret = null; @@ -1792,114 +1789,9 @@ public ServiceGdsInfo getSecureServiceGdsInfoIfUpdated(@PathParam("serviceName") return ret; } - private Long getOrCreateDataShare(Long datasetId, Long serviceId, Long zoneId, String serviceName) throws Exception { - LOG.debug("==> GdsREST.getOrCreateDataShare(dataSetId={} serviceId={} zoneId={} seviceName={})", datasetId); - - Long ret; - RangerDataShare rangerDataShare; - RangerDataset rangerDataset = gdsStore.getDataset(datasetId); - String dataShareName = "__dataset_" + datasetId + "__service_" + serviceId + "__zone_" + zoneId; - - SearchFilter filter = new SearchFilter(); - filter.setParam(SearchFilter.DATA_SHARE_NAME, dataShareName); - PList dataSharePList = gdsStore.searchDataShares(filter); - List dataShareList = dataSharePList.getList(); - - if (CollectionUtils.isNotEmpty(dataShareList)) { - List rangerDataShares = dataSharePList.getList(); - rangerDataShare = rangerDataShares.get(0); - ret = rangerDataShare.getId(); - } else { - //Create a DataShare - RangerDataShare dataShare = new RangerDataShare(); - dataShare.setName(dataShareName); - dataShare.setDescription(dataShareName); - dataShare.setTermsOfUse(rangerDataset.getTermsOfUse()); - dataShare.setService(serviceName); - Set accessTypes = new HashSet<>(CollectionUtils.EMPTY_COLLECTION); - dataShare.setDefaultAccessTypes(accessTypes); - rangerDataShare = gdsStore.createDataShare(dataShare); - - //Add DataShare to DataSet - List rangerDataShareInDatasets = new ArrayList<>(); - RangerDataShareInDataset rangerDataShareInDataset = new RangerDataShareInDataset(); - rangerDataShareInDataset.setDataShareId(rangerDataShare.getId()); - rangerDataShareInDataset.setDatasetId(rangerDataset.getId()); - rangerDataShareInDataset.setStatus(RangerGds.GdsShareStatus.REQUESTED); - rangerDataShareInDatasets.add(rangerDataShareInDataset); - addDataSharesInDataset(rangerDataset.getId(), rangerDataShareInDatasets); - ret = rangerDataShare.getId(); - } - - LOG.debug("<== GdsREST.getOrCreateDataShare(RangerDataShare={})", ret); - - return ret; - } - - private Long validateAndGetServiceId(String serviceName){ - Long ret; - if (serviceName == null || serviceName.isEmpty()) { - LOG.error("ServiceName not provided"); - throw restErrorUtil.createRESTException("ServiceName not provided.", - MessageEnums.INVALID_INPUT_DATA); - } - - RangerService service; - - try { - service = serviceDBStore.getServiceByName(serviceName); - ret = service.getId(); - } catch (Exception e) { - LOG.error("Requested Service not found. serviceName=" + serviceName); - throw restErrorUtil.createRESTException("Service:" + serviceName + " not found", - MessageEnums.DATA_NOT_FOUND); - } - - if(service == null){ - LOG.error("Requested Service not found. serviceName=" + serviceName); - throw restErrorUtil.createRESTException(HttpServletResponse.SC_NOT_FOUND, RangerServiceNotFoundException.buildExceptionMsg(serviceName), - false); - } - - if(!service.getIsEnabled()){ - LOG.error("Requested Service is disabled. serviceName=" + serviceName); - throw restErrorUtil.createRESTException("Unauthorized access.", - MessageEnums.OPER_NOT_ALLOWED_FOR_STATE); - } - - return ret; - } - - private Long validateAndGetZoneId(String zoneName){ - Long ret = RangerSecurityZone.RANGER_UNZONED_SECURITY_ZONE_ID; - - if (zoneName == null || zoneName.isEmpty()) { - return ret; - } - - RangerSecurityZone rangerSecurityZone = null; - - try { - rangerSecurityZone = serviceDBStore.getSecurityZone(zoneName); - ret = rangerSecurityZone.getId(); - } catch (Exception e) { - LOG.error("Requested Zone not found. ZoneName=" + zoneName); - throw restErrorUtil.createRESTException("Zone:" + zoneName + " not found", - MessageEnums.DATA_NOT_FOUND); - } - - if(rangerSecurityZone == null){ - LOG.error("Requested Zone not found. ZoneName=" + zoneName); - throw restErrorUtil.createRESTException(HttpServletResponse.SC_NOT_FOUND, RangerServiceNotFoundException.buildExceptionMsg(zoneName), - false); - } - - return ret; - } - @GET @Path("/dataset/{id}/grants") - @Produces({"application/json"}) + @Produces("application/json") @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.GET_DATASET_GRANTS + "\")") public List getDataSetGrants(@PathParam("id") Long id, @Context HttpServletRequest request) { LOG.debug("==> GdsREST.getDataSetGrants(dataSetId: {})", id); @@ -1919,13 +1811,12 @@ public List getDataSetGrants(@PathParam("id") Long id, @Context Htt if (CollectionUtils.isNotEmpty(filteredPolicyItems)) { ret = transformPolicyItemsToGrants(filteredPolicyItems); - } else { + } else { LOG.debug("getDataSetGrants(): no grants available in dataset(id={}), policy(id={}) for query {}", id, policies.get(0).getId(), request.getQueryString()); } } else { LOG.debug("getDataSetGrants(): no policy found for dataset(id={})", id); } - } catch (WebApplicationException excp) { throw excp; } catch (Throwable excp) { @@ -1942,8 +1833,8 @@ public List getDataSetGrants(@PathParam("id") Long id, @Context Htt @PUT @Path("/dataset/{id}/grant") - @Consumes({"application/json"}) - @Produces({"application/json"}) + @Consumes("application/json") + @Produces("application/json") @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.UPDATE_DATASET_GRANTS + "\")") public RangerPolicyHeader updateDataSetGrants(@PathParam("id") Long id, List rangerGrants) { LOG.debug("==> GdsREST.updateDataSetGrants(dataSetId: {}, rangerGrants: {})", id, rangerGrants); @@ -1953,15 +1844,16 @@ public RangerPolicyHeader updateDataSetGrants(@PathParam("id") Long id, List policies = gdsStore.getDatasetPolicies(id); - RangerPolicy policy = CollectionUtils.isNotEmpty(policies) ? policies.get(0) : gdsStore.addDatasetPolicy(id, new RangerPolicy()); - RangerPolicy policyWithModifiedGrants = updatePolicyWithModifiedGrants(policy, rangerGrants); + List policies = gdsStore.getDatasetPolicies(id); + RangerPolicy policy = CollectionUtils.isNotEmpty(policies) ? policies.get(0) : gdsStore.addDatasetPolicy(id, new RangerPolicy()); + RangerPolicy policyWithModifiedGrants = updatePolicyWithModifiedGrants(policy, rangerGrants); if (policyWithModifiedGrants != null) { RangerPolicy updatedPolicy = gdsStore.updateDatasetPolicy(id, policyWithModifiedGrants); + ret = rangerPolicyHeaderOf(updatedPolicy); } else { throw restErrorUtil.createRESTException(HttpServletResponse.SC_NOT_MODIFIED, "No action performed: The grant may already exist or may not be found for deletion.", false); @@ -1988,30 +1880,27 @@ List filterPolicyItemsByRequest(RangerPolicy rangerPolicy, Htt return Collections.emptyList(); } - List policyItems = rangerPolicy.getPolicyItems(); - String[] filteringPrincipals = searchUtil.getParamMultiValues(request, "principal"); - String[] filteringAccessTypes = searchUtil.getParamMultiValues(request, "accessType"); + List policyItems = rangerPolicy.getPolicyItems(); + String[] filteringPrincipals = searchUtil.getParamMultiValues(request, "principal"); + String[] filteringAccessTypes = searchUtil.getParamMultiValues(request, "accessType"); - Predicate byPrincipalPredicate = filterByPrincipalsPredicate(filteringPrincipals); + Predicate byPrincipalPredicate = filterByPrincipalsPredicate(filteringPrincipals); Predicate byAccessTypePredicate = filterByAccessTypesPredicate(filteringAccessTypes); - - List filteredPolicyItems = policyItems.stream() - .filter(byPrincipalPredicate.and(byAccessTypePredicate)) - .collect(Collectors.toList()); + List filteredPolicyItems = policyItems.stream().filter(byPrincipalPredicate.and(byAccessTypePredicate)).collect(Collectors.toList()); LOG.debug("<== GdsREST.filterPolicyItemsByRequest(rangerPolicy: {}): filteredPolicyItems= {}", rangerPolicy, filteredPolicyItems); return filteredPolicyItems; } - @VisibleForTesting - List transformPolicyItemsToGrants(List policyItems) { + @VisibleForTesting + List transformPolicyItemsToGrants(List policyItems) { LOG.debug("==> GdsREST.transformPolicyItemsToGrants(policyItems: {})", policyItems); if (CollectionUtils.isEmpty(policyItems)) { return null; } - List ret = new ArrayList<>(); + List ret = new ArrayList<>(); for (RangerPolicyItem policyItem : policyItems) { List policyItemUsers = policyItem.getUsers(); @@ -2021,19 +1910,19 @@ List transformPolicyItemsToGrants(List policyItem List policyItemAccesses = policyItem.getAccesses(); List policyItemConditions = policyItem.getConditions(); - List policyItemAccessTypes = policyItemAccesses.stream().map(x -> x.getType()).collect(Collectors.toList()); + List policyItemAccessTypes = policyItemAccesses.stream().map(RangerPolicyItemAccess::getType).collect(Collectors.toList()); List policyItemConditionValues = policyItemConditions.stream().flatMap(x -> x.getValues().stream()).collect(Collectors.toList()); if (CollectionUtils.isNotEmpty(policyItemUsers)) { - policyItemUsers.stream().forEach(x -> ret.add(new RangerGrant(new RangerPrincipal(RangerPrincipal.PrincipalType.USER, x), policyItemAccessTypes, policyItemConditionValues))); + policyItemUsers.forEach(x -> ret.add(new RangerGrant(new RangerPrincipal(RangerPrincipal.PrincipalType.USER, x), policyItemAccessTypes, policyItemConditionValues))); } if (CollectionUtils.isNotEmpty(policyItemGroups)) { - policyItemGroups.stream().forEach(x -> ret.add(new RangerGrant(new RangerPrincipal(RangerPrincipal.PrincipalType.GROUP, x), policyItemAccessTypes, policyItemConditionValues))); + policyItemGroups.forEach(x -> ret.add(new RangerGrant(new RangerPrincipal(RangerPrincipal.PrincipalType.GROUP, x), policyItemAccessTypes, policyItemConditionValues))); } if (CollectionUtils.isNotEmpty(policyItemRoles)) { - policyItemRoles.stream().forEach(x -> ret.add(new RangerGrant(new RangerPrincipal(RangerPrincipal.PrincipalType.ROLE, x), policyItemAccessTypes, policyItemConditionValues))); + policyItemRoles.forEach(x -> ret.add(new RangerGrant(new RangerPrincipal(RangerPrincipal.PrincipalType.ROLE, x), policyItemAccessTypes, policyItemConditionValues))); } } @@ -2042,38 +1931,25 @@ List transformPolicyItemsToGrants(List policyItem return ret; } - private RangerPolicyHeader rangerPolicyHeaderOf(RangerPolicy rangerPolicy) { - LOG.debug("==> GdsREST.rangerPolicyHeaderOf(rangerPolicy: {})", rangerPolicy); - - RangerPolicyHeader ret = null; - if (rangerPolicy != null) { - ret = new RangerPolicyHeader(rangerPolicy); - } - - LOG.debug("<== GdsREST.rangerPolicyHeaderOf(rangerPolicy: {}): ret= {}", rangerPolicy, ret); - return ret; - } - - @VisibleForTesting - RangerPolicy updatePolicyWithModifiedGrants(RangerPolicy policy, List rangerGrants) { + @VisibleForTesting + RangerPolicy updatePolicyWithModifiedGrants(RangerPolicy policy, List rangerGrants) { LOG.debug("==> GdsREST.updatePolicyWithModifiedGrants(policy: {}, rangerGrants: {})", policy, rangerGrants); try { - List policyItems = policy.getPolicyItems(); + List policyItems = policy.getPolicyItems(); List policyItemsToUpdate = policyItems.stream().map(this::copyOf).collect(Collectors.toList()); - - Set principalsToUpdate = rangerGrants.stream().map(RangerGrant::getPrincipal).collect(Collectors.toSet()); + Set principalsToUpdate = rangerGrants.stream().map(RangerGrant::getPrincipal).collect(Collectors.toSet()); for (RangerPrincipal principal : principalsToUpdate) { List policyItemsToRemove = new ArrayList<>(); - policyItemsToUpdate.stream() - .filter(matchesPrincipalPredicate(principal)) - .forEach(policyItem -> { - removeMatchingPrincipalFromPolicyItem(policyItem, principal); - if (isPolicyItemEmpty(policyItem)) { - policyItemsToRemove.add(policyItem); - } - - }); + + policyItemsToUpdate.stream().filter(matchesPrincipalPredicate(principal)).forEach(policyItem -> { + removeMatchingPrincipalFromPolicyItem(policyItem, principal); + + if (isPolicyItemEmpty(policyItem)) { + policyItemsToRemove.add(policyItem); + } + }); + policyItemsToUpdate.removeAll(policyItemsToRemove); } @@ -2092,18 +1968,145 @@ RangerPolicy updatePolicyWithModifiedGrants(RangerPolicy policy, List GdsREST.getOrCreateDataShare(dataSetId={} serviceId={} zoneId={} serviceName={})", datasetId, serviceId, zoneId, serviceName); + + Long ret; + RangerDataShare rangerDataShare; + RangerDataset rangerDataset = gdsStore.getDataset(datasetId); + String dataShareName = "__dataset_" + datasetId + "__service_" + serviceId + "__zone_" + zoneId; + + SearchFilter filter = new SearchFilter(); + + filter.setParam(SearchFilter.DATA_SHARE_NAME, dataShareName); + + PList dataSharePList = gdsStore.searchDataShares(filter); + List dataShareList = dataSharePList.getList(); + + if (CollectionUtils.isNotEmpty(dataShareList)) { + List rangerDataShares = dataSharePList.getList(); + + rangerDataShare = rangerDataShares.get(0); + ret = rangerDataShare.getId(); + } else { + //Create a DataShare + RangerDataShare dataShare = new RangerDataShare(); + + dataShare.setName(dataShareName); + dataShare.setDescription(dataShareName); + dataShare.setTermsOfUse(rangerDataset.getTermsOfUse()); + dataShare.setService(serviceName); + dataShare.setDefaultAccessTypes(new HashSet<>()); + + rangerDataShare = gdsStore.createDataShare(dataShare); + + //Add DataShare to DataSet + List rangerDataShareInDatasets = new ArrayList<>(); + RangerDataShareInDataset rangerDataShareInDataset = new RangerDataShareInDataset(); + + rangerDataShareInDataset.setDataShareId(rangerDataShare.getId()); + rangerDataShareInDataset.setDatasetId(rangerDataset.getId()); + rangerDataShareInDataset.setStatus(RangerGds.GdsShareStatus.REQUESTED); + rangerDataShareInDatasets.add(rangerDataShareInDataset); + + addDataSharesInDataset(rangerDataset.getId(), rangerDataShareInDatasets); + + ret = rangerDataShare.getId(); + } + + LOG.debug("<== GdsREST.getOrCreateDataShare(RangerDataShare={})", ret); + + return ret; + } + + private Long validateAndGetServiceId(String serviceName) { + Long ret; + + if (serviceName == null || serviceName.isEmpty()) { + LOG.error("ServiceName not provided"); + + throw restErrorUtil.createRESTException("ServiceName not provided.", MessageEnums.INVALID_INPUT_DATA); + } + + RangerService service; + + try { + service = serviceDBStore.getServiceByName(serviceName); + ret = service.getId(); + } catch (Exception e) { + LOG.error("Requested Service not found. serviceName={}", serviceName); + + throw restErrorUtil.createRESTException("Service:" + serviceName + " not found", MessageEnums.DATA_NOT_FOUND); + } + + if (service == null) { + LOG.error("Requested Service not found. serviceName={}", serviceName); + + throw restErrorUtil.createRESTException(HttpServletResponse.SC_NOT_FOUND, RangerServiceNotFoundException.buildExceptionMsg(serviceName), false); + } + + if (!service.getIsEnabled()) { + LOG.error("Requested Service is disabled. serviceName={}", serviceName); + + throw restErrorUtil.createRESTException("Unauthorized access.", MessageEnums.OPER_NOT_ALLOWED_FOR_STATE); + } + + return ret; + } + + private Long validateAndGetZoneId(String zoneName) { + Long ret = RangerSecurityZone.RANGER_UNZONED_SECURITY_ZONE_ID; + + if (zoneName == null || zoneName.isEmpty()) { + return ret; + } + + RangerSecurityZone rangerSecurityZone; + + try { + rangerSecurityZone = serviceDBStore.getSecurityZone(zoneName); + ret = rangerSecurityZone.getId(); + } catch (Exception e) { + LOG.error("Requested Zone not found. ZoneName={}", zoneName); + + throw restErrorUtil.createRESTException("Zone:" + zoneName + " not found", MessageEnums.DATA_NOT_FOUND); + } + + if (rangerSecurityZone == null) { + LOG.error("Requested Zone not found. ZoneName={}", zoneName); + + throw restErrorUtil.createRESTException(HttpServletResponse.SC_NOT_FOUND, RangerServiceNotFoundException.buildExceptionMsg(zoneName), false); + } + + return ret; + } + + private RangerPolicyHeader rangerPolicyHeaderOf(RangerPolicy rangerPolicy) { + LOG.debug("==> GdsREST.rangerPolicyHeaderOf(rangerPolicy: {})", rangerPolicy); + + RangerPolicyHeader ret = null; + + if (rangerPolicy != null) { + ret = new RangerPolicyHeader(rangerPolicy); + } + + LOG.debug("<== GdsREST.rangerPolicyHeaderOf(rangerPolicy: {}): ret= {}", rangerPolicy, ret); + + return ret; + } + private boolean isPolicyItemEmpty(RangerPolicyItem policyItem) { - return CollectionUtils.isEmpty(policyItem.getUsers()) && - CollectionUtils.isEmpty(policyItem.getGroups()) && - CollectionUtils.isEmpty(policyItem.getRoles()); + return CollectionUtils.isEmpty(policyItem.getUsers()) && CollectionUtils.isEmpty(policyItem.getGroups()) && CollectionUtils.isEmpty(policyItem.getRoles()); } private void removeMatchingPrincipalFromPolicyItem(RangerPolicyItem policyItem, RangerPrincipal principal) { - String principalName = principal.getName(); + String principalName = principal.getName(); PrincipalType principalType = principal.getType(); if (principalType == PrincipalType.USER && policyItem.getUsers() != null) { @@ -2122,20 +2125,16 @@ private RangerPolicyItem transformGrantToPolicyItem(RangerGrant grant) { return null; } - RangerPolicyItem policyItem = new RangerPolicyItem(); + RangerPolicyItem policyItem = new RangerPolicyItem(); + List permissions = grant.getAccessTypes(); + List conditions = grant.getConditions(); - List permissions = grant.getAccessTypes(); if (CollectionUtils.isNotEmpty(permissions)) { - policyItem.setAccesses(permissions.stream() - .map(accessType -> new RangerPolicyItemAccess(accessType, true)) - .collect(Collectors.toList())); + policyItem.setAccesses(permissions.stream().map(accessType -> new RangerPolicyItemAccess(accessType, true)).collect(Collectors.toList())); } - List conditions = grant.getConditions(); if (CollectionUtils.isNotEmpty(conditions)) { - policyItem.setConditions(conditions.stream() - .map(condition -> new RangerPolicyItemCondition(GDS_POLICY_EXPR_CONDITION, Collections.singletonList(condition))) - .collect(Collectors.toList())); + policyItem.setConditions(conditions.stream().map(condition -> new RangerPolicyItemCondition(GDS_POLICY_EXPR_CONDITION, Collections.singletonList(condition))).collect(Collectors.toList())); } switch (grant.getPrincipal().getType()) { @@ -2156,7 +2155,7 @@ private RangerPolicyItem transformGrantToPolicyItem(RangerGrant grant) { } private Predicate matchesPrincipalPredicate(RangerPrincipal principal) { - String principalName = principal.getName(); + String principalName = principal.getName(); PrincipalType principalType = principal.getType(); return policyItem -> { @@ -2182,24 +2181,21 @@ private Predicate filterByPrincipalsPredicate(String[] filteri } Map> principalCriteriaMap = new HashMap<>(); + for (String principal : filteringPrincipals) { - String[] parts = principal.split(":"); - String principalType = parts.length > 1 ? parts[0] : DEFAULT_PRINCIPAL_TYPE; - String principalName = parts.length > 1 ? parts[1] : parts[0]; + String[] parts = principal.split(":"); + String principalType = parts.length > 1 ? parts[0] : DEFAULT_PRINCIPAL_TYPE; + String principalName = parts.length > 1 ? parts[1] : parts[0]; - principalCriteriaMap - .computeIfAbsent(principalType.toLowerCase(), k -> new HashSet<>()) - .add(principalName); + principalCriteriaMap.computeIfAbsent(principalType.toLowerCase(), k -> new HashSet<>()).add(principalName); } return policyItem -> { - Set users = principalCriteriaMap.getOrDefault(PRINCIPAL_TYPE_USER, Collections.emptySet()); + Set users = principalCriteriaMap.getOrDefault(PRINCIPAL_TYPE_USER, Collections.emptySet()); Set groups = principalCriteriaMap.getOrDefault(PRINCIPAL_TYPE_GROUP, Collections.emptySet()); - Set roles = principalCriteriaMap.getOrDefault(PRINCIPAL_TYPE_ROLE, Collections.emptySet()); + Set roles = principalCriteriaMap.getOrDefault(PRINCIPAL_TYPE_ROLE, Collections.emptySet()); - return (policyItem.getUsers() != null && policyItem.getUsers().stream().anyMatch(users::contains)) || - (policyItem.getGroups() != null && policyItem.getGroups().stream().anyMatch(groups::contains)) || - (policyItem.getRoles() != null && policyItem.getRoles().stream().anyMatch(roles::contains)); + return (policyItem.getUsers() != null && policyItem.getUsers().stream().anyMatch(users::contains)) || (policyItem.getGroups() != null && policyItem.getGroups().stream().anyMatch(groups::contains)) || (policyItem.getRoles() != null && policyItem.getRoles().stream().anyMatch(roles::contains)); }; } @@ -2209,18 +2205,19 @@ private Predicate filterByAccessTypesPredicate(String[] filter } Set accessTypeSet = new HashSet<>(Arrays.asList(filteringAccessTypes)); - return policyItem -> policyItem.getAccesses().stream() - .anyMatch(access -> accessTypeSet.contains(access.getType())); + + return policyItem -> policyItem.getAccesses().stream().anyMatch(access -> accessTypeSet.contains(access.getType())); } private RangerPolicyItem copyOf(RangerPolicyItem policyItem) { RangerPolicyItem copy = new RangerPolicyItem(); + copy.setAccesses(new ArrayList<>(policyItem.getAccesses())); copy.setUsers(new ArrayList<>(policyItem.getUsers())); copy.setGroups(new ArrayList<>(policyItem.getGroups())); copy.setRoles(new ArrayList<>(policyItem.getRoles())); copy.setConditions(new ArrayList<>(policyItem.getConditions())); - copy.setDelegateAdmin(new Boolean(policyItem.getDelegateAdmin())); + copy.setDelegateAdmin(policyItem.getDelegateAdmin()); return copy; } diff --git a/security-admin/src/main/java/org/apache/ranger/rest/MetricsREST.java b/security-admin/src/main/java/org/apache/ranger/rest/MetricsREST.java index b34a795b42..c4ab05dd53 100644 --- a/security-admin/src/main/java/org/apache/ranger/rest/MetricsREST.java +++ b/security-admin/src/main/java/org/apache/ranger/rest/MetricsREST.java @@ -19,16 +19,6 @@ package org.apache.ranger.rest; -import java.lang.management.ManagementFactory; -import java.lang.management.RuntimeMXBean; -import java.util.LinkedHashMap; -import java.util.Map; - -import javax.ws.rs.GET; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; -import javax.ws.rs.core.MediaType; - import org.apache.ranger.metrics.RangerAdminMetricsWrapper; import org.apache.ranger.plugin.model.RangerMetrics; import org.apache.ranger.util.RangerMetricsUtil; @@ -40,17 +30,28 @@ import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.core.MediaType; + +import java.lang.management.ManagementFactory; +import java.lang.management.RuntimeMXBean; +import java.util.LinkedHashMap; +import java.util.Map; + @Path("metrics") @Component @Scope("request") @Transactional(propagation = Propagation.REQUIRES_NEW) public class MetricsREST { private static final Logger LOG = LoggerFactory.getLogger(MetricsREST.class); - private static final RuntimeMXBean RUNTIME = ManagementFactory.getRuntimeMXBean(); - private static final String JVM_MACHINE_ACTUAL_NAME = RUNTIME.getVmName(); - private static final String VERSION = RUNTIME.getVmVersion(); - private static final String JVM_MACHINE_REPRESENTATION_NAME = RUNTIME.getName(); - private static final String JVM_VENDOR_NAME = RUNTIME.getVmVendor(); + + private static final RuntimeMXBean RUNTIME = ManagementFactory.getRuntimeMXBean(); + private static final String JVM_MACHINE_ACTUAL_NAME = RUNTIME.getVmName(); + private static final String VERSION = RUNTIME.getVmVersion(); + private static final String JVM_MACHINE_REPRESENTATION_NAME = RUNTIME.getName(); + private static final String JVM_VENDOR_NAME = RUNTIME.getVmVendor(); @Autowired RangerMetricsUtil jvmMetricUtil; @@ -60,25 +61,23 @@ public class MetricsREST { @GET @Path("/status") - @Produces({ "application/json" }) + @Produces("application/json") public RangerMetrics getStatus() { - if (LOG.isDebugEnabled()) { - LOG.debug("==> MetricsREST.getStatus()"); - } + LOG.debug("==> MetricsREST.getStatus()"); - Map jvm = new LinkedHashMap<>(); + Map jvm = new LinkedHashMap<>(); Map vmDetails = new LinkedHashMap<>(); + vmDetails.put("JVM Machine Actual Name", JVM_MACHINE_ACTUAL_NAME); vmDetails.put("version", VERSION); vmDetails.put("JVM Machine Representation Name", JVM_MACHINE_REPRESENTATION_NAME); vmDetails.put("Up time of JVM", RUNTIME.getUptime()); vmDetails.put("JVM Vendor Name", JVM_VENDOR_NAME); vmDetails.putAll(jvmMetricUtil.getValues()); - jvm.put("jvm",vmDetails); - if (LOG.isDebugEnabled()) { - LOG.debug("<== MetricsREST.getStatus(): jvm=" + jvm); - } + jvm.put("jvm", vmDetails); + + LOG.debug("<== MetricsREST.getStatus(): jvm={}", jvm); return new RangerMetrics(jvm); } @@ -87,19 +86,18 @@ public RangerMetrics getStatus() { @Path("/prometheus") @Produces(MediaType.TEXT_PLAIN) public String getMetricsPrometheus() { - if (LOG.isDebugEnabled()) { - LOG.debug("==> MetricsREST.getMetricsPrometheus()"); - } + LOG.debug("==> MetricsREST.getMetricsPrometheus()"); + String ret = ""; + try { ret = rangerAdminMetricsWrapper.getRangerMetricsInPrometheusFormat(); } catch (Exception e) { LOG.error("MetricsREST.getMetricsPrometheus(): Exception occurred while getting metric.", e); } - if (LOG.isDebugEnabled()) { - LOG.debug("<== MetricsREST.getMetricsPrometheus(): ret=" + ret); - } + LOG.debug("<== MetricsREST.getMetricsPrometheus(): ret={}", ret); + return ret; } @@ -107,20 +105,18 @@ public String getMetricsPrometheus() { @Path("/json") @Produces(MediaType.APPLICATION_JSON) public Map> getMetricsJson() { - if (LOG.isDebugEnabled()) { - LOG.debug("==> MetricsREST.getMetricsJson()"); - } + LOG.debug("==> MetricsREST.getMetricsJson()"); Map> ret = null; + try { ret = rangerAdminMetricsWrapper.getRangerMetrics(); } catch (Exception e) { LOG.error("MetricsREST.getMetricsJson(): Exception occurred while getting metric.", e); } - if (LOG.isDebugEnabled()) { - LOG.debug("<== MetricsREST.getMetricsJson(): ret=" + ret); - } + LOG.debug("<== MetricsREST.getMetricsJson(): ret={}", ret); + return ret; } } diff --git a/security-admin/src/main/java/org/apache/ranger/rest/PublicAPIs.java b/security-admin/src/main/java/org/apache/ranger/rest/PublicAPIs.java index b7735e7155..5d11e97a4a 100644 --- a/security-admin/src/main/java/org/apache/ranger/rest/PublicAPIs.java +++ b/security-admin/src/main/java/org/apache/ranger/rest/PublicAPIs.java @@ -19,7 +19,11 @@ package org.apache.ranger.rest; -import org.apache.ranger.common.*; +import org.apache.ranger.common.MessageEnums; +import org.apache.ranger.common.RESTErrorUtil; +import org.apache.ranger.common.RangerSearchUtil; +import org.apache.ranger.common.ServiceUtil; +import org.apache.ranger.common.StringUtil; import org.apache.ranger.common.annotation.RangerAnnotationClassName; import org.apache.ranger.common.annotation.RangerAnnotationJSMgrName; import org.apache.ranger.db.RangerDaoManager; @@ -30,7 +34,13 @@ import org.apache.ranger.plugin.util.SearchFilter; import org.apache.ranger.service.RangerPolicyService; import org.apache.ranger.service.XAssetService; -import org.apache.ranger.view.*; +import org.apache.ranger.view.VXAsset; +import org.apache.ranger.view.VXLong; +import org.apache.ranger.view.VXPolicy; +import org.apache.ranger.view.VXPolicyList; +import org.apache.ranger.view.VXRepository; +import org.apache.ranger.view.VXRepositoryList; +import org.apache.ranger.view.VXResource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -42,7 +52,14 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import javax.ws.rs.*; +import javax.ws.rs.Consumes; +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 java.util.List; @@ -53,352 +70,276 @@ @RangerAnnotationJSMgrName("PublicMgr") @Transactional(propagation = Propagation.REQUIRES_NEW) public class PublicAPIs { - private static final Logger logger = LoggerFactory.getLogger(PublicAPIs.class); - - @Autowired - RangerSearchUtil searchUtil; - - @Autowired - XAssetService xAssetService; - - @Autowired - RangerPolicyService policyService; - - @Autowired - StringUtil stringUtil; - - @Autowired - ServiceUtil serviceUtil; - - @Autowired - ServiceREST serviceREST; - - @Autowired - RangerDaoManager daoMgr; - - @Autowired - RESTErrorUtil restErrorUtil; - - @Autowired - AssetREST assetREST; - - @GET - @Path("/api/repository/{id}") - @Produces({ "application/json" }) - public VXRepository getRepository(@PathParam("id") Long id) { - if(logger.isDebugEnabled()) { - logger.debug("==> PublicAPIs.getRepository(" + id + ")"); - } - - RangerService service = serviceREST.getService(id); - - VXRepository ret = serviceUtil.toVXRepository(service); - - if(logger.isDebugEnabled()) { - logger.debug("<= PublicAPIs.getRepository(" + id + ")"); - } - return ret; - } - - - @POST - @Path("/api/repository/") - @Consumes({ "application/json" }) - @Produces({ "application/json" }) - public VXRepository createRepository(VXRepository vXRepository) { - if(logger.isDebugEnabled()) { - logger.debug("==> PublicAPIs.createRepository(" + vXRepository + ")"); - } - - VXAsset vXAsset = serviceUtil.publicObjecttoVXAsset(vXRepository); - - RangerService service = serviceUtil.toRangerService(vXAsset); - - RangerService createdService = serviceREST.createService(service); - - VXAsset retvXAsset = serviceUtil.toVXAsset(createdService); - - VXRepository ret = serviceUtil.vXAssetToPublicObject(retvXAsset); - - if(logger.isDebugEnabled()) { - logger.debug("<== PublicAPIs.createRepository(" + ret + ")"); - } - - return ret; - } - - - @PUT - @Path("/api/repository/{id}") - @Consumes({ "application/json" }) - @Produces({ "application/json" }) - public VXRepository updateRepository(VXRepository vXRepository, - @PathParam("id") Long id) { - - if(logger.isDebugEnabled()) { - logger.debug("==> PublicAPIs.updateRepository(" + id + ")"); - } - - XXService existing = daoMgr.getXXService().getById(id); - if(existing == null) { - throw restErrorUtil.createRESTException("Repository not found for Id: " + id, MessageEnums.DATA_NOT_FOUND); - } - - vXRepository.setId(id); - - VXAsset vXAsset = serviceUtil.publicObjecttoVXAsset(vXRepository); - - RangerService service = serviceUtil.toRangerService(vXAsset); - service.setVersion(existing.getVersion()); - - RangerService updatedService = serviceREST.updateService(service, null); - - VXAsset retvXAsset = serviceUtil.toVXAsset(updatedService); - - VXRepository ret = serviceUtil.vXAssetToPublicObject(retvXAsset); - - if(logger.isDebugEnabled()) { - logger.debug("<== PublicAPIs.updateRepository(" + ret + ")"); - } - - return ret; - } - - - @DELETE - @Path("/api/repository/{id}") - @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") - @RangerAnnotationClassName(class_name = VXAsset.class) - public void deleteRepository(@PathParam("id") Long id, - @Context HttpServletRequest request) { - - if(logger.isDebugEnabled()) { - logger.debug("==> PublicAPIs.deleteRepository(" + id + ")"); - } - - serviceREST.deleteService(id); - - if(logger.isDebugEnabled()) { - logger.debug("<== PublicAPIs.deleteRepository(" + id + ")"); - } - } - - @GET - @Path("/api/repository/") - @Produces({ "application/json" }) - public VXRepositoryList searchRepositories( - @Context HttpServletRequest request) { - - if(logger.isDebugEnabled()) { - logger.debug("==> PublicAPIs.searchRepositories()"); - } - - SearchFilter filter = searchUtil.getSearchFilterFromLegacyRequestForRepositorySearch(request, xAssetService.sortFields); - - List serviceList = serviceREST.getServices(filter); - - VXRepositoryList ret = null; - - if (serviceList != null) { - ret = serviceUtil.rangerServiceListToPublicObjectList(serviceList); - } - - if(logger.isDebugEnabled()) { - logger.debug("<== PublicAPIs.searchRepositories(): count=" + (ret == null ? 0 : ret.getListSize())); - } - - return ret; - } - - - @GET - @Path("/api/repository/count") - @Produces({ "application/json" }) - public VXLong countRepositories(@Context HttpServletRequest request) { - - if(logger.isDebugEnabled()) { - logger.debug("==> PublicAPIs.countRepositories()"); - } - - VXLong ret = assetREST.countXAssets(request); - - if(logger.isDebugEnabled()) { - logger.debug("<== PublicAPIs.countRepositories(): count=" + ret); - } - - return ret; - } - - - - @GET - @Path("/api/policy/{id}") - @Produces({ "application/json" }) - public VXPolicy getPolicy(@PathParam("id") Long id) { - - if(logger.isDebugEnabled()) { - logger.debug("==> PublicAPIs.getPolicy() " + id); - } - - RangerPolicy policy = null; - RangerService service = null; - - policy = serviceREST.getPolicy(id); - - if(policy != null) { - service = serviceREST.getServiceByName(policy.getService()); - } - - VXPolicy ret = serviceUtil.toVXPolicy(policy, service); - - if(logger.isDebugEnabled()) { - logger.debug("<== PublicAPIs.getPolicy()" + ret); - } - - return ret; - } - - - @POST - @Path("/api/policy") - @Consumes({ "application/json" }) - @Produces({ "application/json" }) - public VXPolicy createPolicy(VXPolicy vXPolicy) { - - if(logger.isDebugEnabled()) { - logger.debug("==> PublicAPIs.createPolicy()"); - } - - if(vXPolicy == null) { - throw restErrorUtil.createRESTException(HttpServletResponse.SC_BAD_REQUEST, "Policy object is null in create policy api", false); - } - RangerService service = serviceREST.getServiceByName(vXPolicy.getRepositoryName()); - RangerPolicy policy = serviceUtil.toRangerPolicy(vXPolicy,service); - - VXPolicy ret = null; - if(policy != null) { - if(logger.isDebugEnabled()) { - logger.debug("RANGERPOLICY: " + policy.toString()); - } - - RangerPolicy createdPolicy = serviceREST.createPolicy(policy,null); - - ret = serviceUtil.toVXPolicy(createdPolicy, service); - } - - if(logger.isDebugEnabled()) { - logger.debug("<== PublicAPIs.createPolicy(" + policy + "): " + ret); - } - - return ret; - } - - @PUT - @Path("/api/policy/{id}") - @Consumes({ "application/json" }) - @Produces({ "application/json" }) - public VXPolicy updatePolicy(VXPolicy vXPolicy, @PathParam("id") Long id) { - - if(logger.isDebugEnabled()) { - logger.debug("==> PublicAPIs.updatePolicy(): " + vXPolicy ); - } - - if(vXPolicy == null) { - throw restErrorUtil.createRESTException(HttpServletResponse.SC_BAD_REQUEST, "Policy object is null in update policy api", false); - } - - XXPolicy existing = daoMgr.getXXPolicy().getById(id); - if(existing == null) { - throw restErrorUtil.createRESTException("Policy not found for Id: " + id, MessageEnums.DATA_NOT_FOUND); - } - - vXPolicy.setId(id); - - RangerService service = serviceREST.getServiceByName(vXPolicy.getRepositoryName()); - RangerPolicy policy = serviceUtil.toRangerPolicy(vXPolicy,service); - - VXPolicy ret = null; - if(policy != null) { - policy.setVersion(existing.getVersion()); - - RangerPolicy updatedPolicy = serviceREST.updatePolicy(policy, policy.getId()); - - ret = serviceUtil.toVXPolicy(updatedPolicy, service); - } - - if(logger.isDebugEnabled()) { - logger.debug("<== PublicAPIs.updatePolicy(" + policy + "): " + ret); - } - - return ret; - } - - @DELETE - @Path("/api/policy/{id}") - @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") - @RangerAnnotationClassName(class_name = VXResource.class) - public void deletePolicy(@PathParam("id") Long id, - @Context HttpServletRequest request) { - - if(logger.isDebugEnabled()) { - logger.debug("==> PublicAPIs.deletePolicy(): " + id ); - } - - serviceREST.deletePolicy(id); - - if(logger.isDebugEnabled()) { - logger.debug("<== PublicAPIs.deletePolicy(): " + id ); - } - } - - @GET - @Path("/api/policy") - @Produces({ "application/json" }) - public VXPolicyList searchPolicies(@Context HttpServletRequest request) { - - if(logger.isDebugEnabled()) { - logger.debug("==> PublicAPIs.searchPolicies(): "); - } - - SearchFilter filter = searchUtil.getSearchFilterFromLegacyRequest(request, policyService.sortFields); - // get all policies from the store; pick the page to return after applying filter - int savedStartIndex = filter.getStartIndex(); - int savedMaxRows = filter.getMaxRows(); - - filter.setStartIndex(0); - filter.setMaxRows(Integer.MAX_VALUE); - - List rangerPolicyList = serviceREST.getPolicies(filter); - - filter.setStartIndex(savedStartIndex); - filter.setMaxRows(savedMaxRows); - - VXPolicyList vXPolicyList = null; - if (rangerPolicyList != null) { - vXPolicyList = serviceUtil.rangerPolicyListToPublic(rangerPolicyList,filter); - } - if(logger.isDebugEnabled()) { - logger.debug("<== PublicAPIs.searchPolicies(): " + vXPolicyList ); - } - return vXPolicyList; - } - - @GET - @Path("/api/policy/count") - @Produces({ "application/json" }) - public VXLong countPolicies(@Context HttpServletRequest request) { - - if(logger.isDebugEnabled()) { - logger.debug("==> PublicAPIs.countPolicies(): "); - } - - VXLong ret = assetREST.countXResources(request); - - if(logger.isDebugEnabled()) { - logger.debug("<== PublicAPIs.countPolicies(): " + ret); - } - - return ret; - } + private static final Logger logger = LoggerFactory.getLogger(PublicAPIs.class); + @Autowired + RangerSearchUtil searchUtil; + + @Autowired + XAssetService xAssetService; + + @Autowired + RangerPolicyService policyService; + + @Autowired + StringUtil stringUtil; + + @Autowired + ServiceUtil serviceUtil; + + @Autowired + ServiceREST serviceREST; + + @Autowired + RangerDaoManager daoMgr; + + @Autowired + RESTErrorUtil restErrorUtil; + + @Autowired + AssetREST assetREST; + + @GET + @Path("/api/repository/{id}") + @Produces("application/json") + public VXRepository getRepository(@PathParam("id") Long id) { + logger.debug("==> PublicAPIs.getRepository({})", id); + + RangerService service = serviceREST.getService(id); + VXRepository ret = serviceUtil.toVXRepository(service); + + logger.debug("<= PublicAPIs.getRepository({})", id); + + return ret; + } + + @POST + @Path("/api/repository/") + @Consumes("application/json") + @Produces("application/json") + public VXRepository createRepository(VXRepository vXRepository) { + logger.debug("==> PublicAPIs.createRepository({})", vXRepository); + + VXAsset vXAsset = serviceUtil.publicObjecttoVXAsset(vXRepository); + RangerService service = serviceUtil.toRangerService(vXAsset); + RangerService createdService = serviceREST.createService(service); + VXAsset retvXAsset = serviceUtil.toVXAsset(createdService); + VXRepository ret = serviceUtil.vXAssetToPublicObject(retvXAsset); + + logger.debug("<== PublicAPIs.createRepository({})", ret); + + return ret; + } + + @PUT + @Path("/api/repository/{id}") + @Consumes("application/json") + @Produces("application/json") + public VXRepository updateRepository(VXRepository vXRepository, @PathParam("id") Long id) { + logger.debug("==> PublicAPIs.updateRepository({})", id); + + XXService existing = daoMgr.getXXService().getById(id); + + if (existing == null) { + throw restErrorUtil.createRESTException("Repository not found for Id: " + id, MessageEnums.DATA_NOT_FOUND); + } + + vXRepository.setId(id); + + VXAsset vXAsset = serviceUtil.publicObjecttoVXAsset(vXRepository); + RangerService service = serviceUtil.toRangerService(vXAsset); + + service.setVersion(existing.getVersion()); + + RangerService updatedService = serviceREST.updateService(service, null); + VXAsset retvXAsset = serviceUtil.toVXAsset(updatedService); + VXRepository ret = serviceUtil.vXAssetToPublicObject(retvXAsset); + + logger.debug("<== PublicAPIs.updateRepository({})", ret); + + return ret; + } + + @DELETE + @Path("/api/repository/{id}") + @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") + @RangerAnnotationClassName(class_name = VXAsset.class) + public void deleteRepository(@PathParam("id") Long id, @Context HttpServletRequest request) { + logger.debug("==> PublicAPIs.deleteRepository({})", id); + + serviceREST.deleteService(id); + + logger.debug("<== PublicAPIs.deleteRepository({})", id); + } + + @GET + @Path("/api/repository/") + @Produces("application/json") + public VXRepositoryList searchRepositories(@Context HttpServletRequest request) { + logger.debug("==> PublicAPIs.searchRepositories()"); + + SearchFilter filter = searchUtil.getSearchFilterFromLegacyRequestForRepositorySearch(request, xAssetService.sortFields); + List serviceList = serviceREST.getServices(filter); + VXRepositoryList ret = null; + + if (serviceList != null) { + ret = serviceUtil.rangerServiceListToPublicObjectList(serviceList); + } + + logger.debug("<== PublicAPIs.searchRepositories(): count={}", (ret == null ? 0 : ret.getListSize())); + + return ret; + } + + @GET + @Path("/api/repository/count") + @Produces("application/json") + public VXLong countRepositories(@Context HttpServletRequest request) { + logger.debug("==> PublicAPIs.countRepositories()"); + + VXLong ret = assetREST.countXAssets(request); + + logger.debug("<== PublicAPIs.countRepositories(): count={}", ret); + + return ret; + } + + @GET + @Path("/api/policy/{id}") + @Produces("application/json") + public VXPolicy getPolicy(@PathParam("id") Long id) { + logger.debug("==> PublicAPIs.getPolicy() {}", id); + + RangerService service = null; + RangerPolicy policy = serviceREST.getPolicy(id); + + if (policy != null) { + service = serviceREST.getServiceByName(policy.getService()); + } + + VXPolicy ret = serviceUtil.toVXPolicy(policy, service); + + logger.debug("<== PublicAPIs.getPolicy(){}", ret); + + return ret; + } + + @POST + @Path("/api/policy") + @Consumes("application/json") + @Produces("application/json") + public VXPolicy createPolicy(VXPolicy vXPolicy) { + logger.debug("==> PublicAPIs.createPolicy()"); + + if (vXPolicy == null) { + throw restErrorUtil.createRESTException(HttpServletResponse.SC_BAD_REQUEST, "Policy object is null in create policy api", false); + } + + RangerService service = serviceREST.getServiceByName(vXPolicy.getRepositoryName()); + RangerPolicy policy = serviceUtil.toRangerPolicy(vXPolicy, service); + + VXPolicy ret = null; + if (policy != null) { + logger.debug("RangerPolicy: {}", policy); + + RangerPolicy createdPolicy = serviceREST.createPolicy(policy, null); + + ret = serviceUtil.toVXPolicy(createdPolicy, service); + } + + logger.debug("<== PublicAPIs.createPolicy({}): {}", policy, ret); + + return ret; + } + + @PUT + @Path("/api/policy/{id}") + @Consumes("application/json") + @Produces("application/json") + public VXPolicy updatePolicy(VXPolicy vXPolicy, @PathParam("id") Long id) { + logger.debug("==> PublicAPIs.updatePolicy(): {}", vXPolicy); + + if (vXPolicy == null) { + throw restErrorUtil.createRESTException(HttpServletResponse.SC_BAD_REQUEST, "Policy object is null in update policy api", false); + } + + XXPolicy existing = daoMgr.getXXPolicy().getById(id); + + if (existing == null) { + throw restErrorUtil.createRESTException("Policy not found for Id: " + id, MessageEnums.DATA_NOT_FOUND); + } + + vXPolicy.setId(id); + + RangerService service = serviceREST.getServiceByName(vXPolicy.getRepositoryName()); + RangerPolicy policy = serviceUtil.toRangerPolicy(vXPolicy, service); + + VXPolicy ret = null; + if (policy != null) { + policy.setVersion(existing.getVersion()); + + RangerPolicy updatedPolicy = serviceREST.updatePolicy(policy, policy.getId()); + + ret = serviceUtil.toVXPolicy(updatedPolicy, service); + } + + logger.debug("<== PublicAPIs.updatePolicy({}):{}", policy, ret); + + return ret; + } + + @DELETE + @Path("/api/policy/{id}") + @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") + @RangerAnnotationClassName(class_name = VXResource.class) + public void deletePolicy(@PathParam("id") Long id, @Context HttpServletRequest request) { + logger.debug("==> PublicAPIs.deletePolicy(): {}", id); + + serviceREST.deletePolicy(id); + + logger.debug("<== PublicAPIs.deletePolicy(): {}", id); + } + + @GET + @Path("/api/policy") + @Produces("application/json") + public VXPolicyList searchPolicies(@Context HttpServletRequest request) { + logger.debug("==> PublicAPIs.searchPolicies(): "); + + SearchFilter filter = searchUtil.getSearchFilterFromLegacyRequest(request, policyService.sortFields); + + // get all policies from the store; pick the page to return after applying filter + int savedStartIndex = filter.getStartIndex(); + int savedMaxRows = filter.getMaxRows(); + + filter.setStartIndex(0); + filter.setMaxRows(Integer.MAX_VALUE); + + List rangerPolicyList = serviceREST.getPolicies(filter); + + filter.setStartIndex(savedStartIndex); + filter.setMaxRows(savedMaxRows); + + VXPolicyList vXPolicyList = null; + + if (rangerPolicyList != null) { + vXPolicyList = serviceUtil.rangerPolicyListToPublic(rangerPolicyList, filter); + } + + logger.debug("<== PublicAPIs.searchPolicies(): {}", vXPolicyList); + return vXPolicyList; + } + + @GET + @Path("/api/policy/count") + @Produces("application/json") + public VXLong countPolicies(@Context HttpServletRequest request) { + logger.debug("==> PublicAPIs.countPolicies(): "); + + VXLong ret = assetREST.countXResources(request); + + logger.debug("<== PublicAPIs.countPolicies(): {}", ret); + + return ret; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/rest/PublicAPIsv2.java b/security-admin/src/main/java/org/apache/ranger/rest/PublicAPIsv2.java index d9a2140998..7b1eb7fe7d 100644 --- a/security-admin/src/main/java/org/apache/ranger/rest/PublicAPIsv2.java +++ b/security-admin/src/main/java/org/apache/ranger/rest/PublicAPIsv2.java @@ -29,14 +29,14 @@ import org.apache.ranger.plugin.model.RangerRole; import org.apache.ranger.plugin.model.RangerSecurityZone; import org.apache.ranger.plugin.model.RangerSecurityZoneHeaderInfo; +import org.apache.ranger.plugin.model.RangerSecurityZoneV2; +import org.apache.ranger.plugin.model.RangerSecurityZoneV2.RangerSecurityZoneChangeRequest; +import org.apache.ranger.plugin.model.RangerSecurityZoneV2.RangerSecurityZoneResource; import org.apache.ranger.plugin.model.RangerService; import org.apache.ranger.plugin.model.RangerServiceDef; import org.apache.ranger.plugin.model.RangerServiceHeaderInfo; import org.apache.ranger.plugin.model.RangerServiceResource; import org.apache.ranger.plugin.model.RangerServiceTags; -import org.apache.ranger.plugin.model.RangerSecurityZoneV2; -import org.apache.ranger.plugin.model.RangerSecurityZoneV2.RangerSecurityZoneChangeRequest; -import org.apache.ranger.plugin.model.RangerSecurityZoneV2.RangerSecurityZoneResource; import org.apache.ranger.plugin.store.PList; import org.apache.ranger.plugin.util.GrantRevokeRoleRequest; import org.apache.ranger.plugin.util.RangerPurgeResult; @@ -66,7 +66,6 @@ import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Context; -import java.util.ArrayList; import java.util.Collection; import java.util.List; @@ -76,933 +75,868 @@ @RangerAnnotationJSMgrName("PublicMgr") @Transactional(propagation = Propagation.REQUIRES_NEW) public class PublicAPIsv2 { - private static final Logger logger = LoggerFactory.getLogger(PublicAPIsv2.class); + private static final Logger logger = LoggerFactory.getLogger(PublicAPIsv2.class); - @Autowired - ServiceREST serviceREST; + @Autowired + ServiceREST serviceREST; - @Autowired - TagREST tagREST; + @Autowired + TagREST tagREST; - @Autowired - SecurityZoneREST securityZoneRest; + @Autowired + SecurityZoneREST securityZoneRest; - @Autowired - RoleREST roleREST; + @Autowired + RoleREST roleREST; - @Autowired - RESTErrorUtil restErrorUtil; + @Autowired + RESTErrorUtil restErrorUtil; @Autowired SecurityZoneDBStore securityZoneStore; - /* - * SecurityZone Creation API - */ - @POST - @Path("/api/zones") - @Consumes({ "application/json" }) - @Produces({ "application/json" }) - public RangerSecurityZone createSecurityZone(RangerSecurityZone securityZone) { - return securityZoneRest.createSecurityZone(securityZone); - } - - /* - * SecurityZone Manipulation API - */ - @PUT - @Path("/api/zones/{id}") - @Consumes({ "application/json" }) - @Produces({ "application/json" }) - public RangerSecurityZone updateSecurityZone(@PathParam("id") Long zoneId, RangerSecurityZone securityZone) { - return securityZoneRest.updateSecurityZone(zoneId, securityZone); - } - - @DELETE - @Path("/api/zones/name/{name}") - public void deleteSecurityZone(@PathParam("name") String zoneName) { - securityZoneRest.deleteSecurityZone(zoneName); - } - - @DELETE - @Path("/api/zones/{id}") - public void deleteSecurityZone(@PathParam("id") Long zoneId) { - securityZoneRest.deleteSecurityZone(zoneId); - } - - /* - * API's to Access SecurityZones - */ - @GET - @Path("/api/zones/name/{name}") - @Produces({ "application/json" }) - public RangerSecurityZone getSecurityZone(@PathParam("name") String zoneName) { - return securityZoneRest.getSecurityZone(zoneName); - } - - @GET - @Path("/api/zones/{id}") - @Produces({ "application/json"}) - public RangerSecurityZone getSecurityZone(@PathParam("id") Long id) { - return securityZoneRest.getSecurityZone(id); - } - - @GET + /* + * SecurityZone Creation API + */ + @POST + @Path("/api/zones") + @Consumes("application/json") + @Produces("application/json") + public RangerSecurityZone createSecurityZone(RangerSecurityZone securityZone) { + return securityZoneRest.createSecurityZone(securityZone); + } + + /* + * SecurityZone Manipulation API + */ + @PUT + @Path("/api/zones/{id}") + @Consumes("application/json") + @Produces("application/json") + public RangerSecurityZone updateSecurityZone(@PathParam("id") Long zoneId, RangerSecurityZone securityZone) { + return securityZoneRest.updateSecurityZone(zoneId, securityZone); + } + + @DELETE + @Path("/api/zones/name/{name}") + public void deleteSecurityZone(@PathParam("name") String zoneName) { + securityZoneRest.deleteSecurityZone(zoneName); + } + + @DELETE + @Path("/api/zones/{id}") + public void deleteSecurityZone(@PathParam("id") Long zoneId) { + securityZoneRest.deleteSecurityZone(zoneId); + } + + /* + * API's to Access SecurityZones + */ + @GET + @Path("/api/zones/name/{name}") + @Produces("application/json") + public RangerSecurityZone getSecurityZone(@PathParam("name") String zoneName) { + return securityZoneRest.getSecurityZone(zoneName); + } + + @GET + @Path("/api/zones/{id}") + @Produces("application/json") + public RangerSecurityZone getSecurityZone(@PathParam("id") Long id) { + return securityZoneRest.getSecurityZone(id); + } + + @GET @Path("/api/zones") - @Produces({ "application/json"}) - public List getAllZones(@Context HttpServletRequest request){ - return securityZoneRest.getAllZones(request).getSecurityZones(); - } + @Produces("application/json") + public List getAllZones(@Context HttpServletRequest request) { + return securityZoneRest.getAllZones(request).getSecurityZones(); + } /** * Get {@link List} of security zone header info. * This API is authorized to every authenticated user. + * * @return {@link List} of {@link RangerSecurityZoneHeaderInfo} if present. */ @GET @Path("/api/zone-headers") - @Produces({ "application/json" }) + @Produces("application/json") public List getSecurityZoneHeaderInfoList(@Context HttpServletRequest request) { - if (logger.isDebugEnabled()) { - logger.debug("==> PublicAPIsv2.getSecurityZoneHeaderInfoList()"); - } + logger.debug("==> PublicAPIsv2.getSecurityZoneHeaderInfoList()"); List ret; + try { ret = securityZoneStore.getSecurityZoneHeaderInfoList(request); } catch (WebApplicationException excp) { throw excp; } catch (Throwable excp) { logger.error("PublicAPIsv2.getSecurityZoneHeaderInfoList() failed", excp); + throw restErrorUtil.createRESTException(excp.getMessage()); } - if (logger.isDebugEnabled()) { - logger.debug("<== PublicAPIsv2.getSecurityZoneHeaderInfoList():" + ret); - } + logger.debug("<== PublicAPIsv2.getSecurityZoneHeaderInfoList():{}", ret); + return ret; } - /** - * Get {@link List} of security zone header info. - * This API is authorized to every authenticated user. - * @param serviceId - * @param isTagService - * @return {@link List} of {@link RangerSecurityZoneHeaderInfo} if present. - */ - @GET - @Path("/api/zones/zone-headers/for-service/{serviceId}") - @Produces({ "application/json" }) - public List getSecurityZoneHeaderInfoListByServiceId(@PathParam("serviceId") Long serviceId, - @DefaultValue("false") @QueryParam("isTagService") Boolean isTagService, - @Context HttpServletRequest request) { - return securityZoneRest.getSecurityZoneHeaderInfoListByServiceId(serviceId,isTagService, request); - } + /** + * Get {@link List} of security zone header info. + * This API is authorized to every authenticated user. + * + * @param serviceId + * @param isTagService + * @return {@link List} of {@link RangerSecurityZoneHeaderInfo} if present. + */ + @GET + @Path("/api/zones/zone-headers/for-service/{serviceId}") + @Produces("application/json") + public List getSecurityZoneHeaderInfoListByServiceId(@PathParam("serviceId") Long serviceId, @DefaultValue("false") @QueryParam("isTagService") Boolean isTagService, @Context HttpServletRequest request) { + return securityZoneRest.getSecurityZoneHeaderInfoListByServiceId(serviceId, isTagService, request); + } /** * Get service header info {@link List} for given zone. * This API is authorized to every authenticated user. + * * @param zoneId * @return {@link List} of {@link RangerServiceHeaderInfo} for given zone if present. */ @GET @Path("/api/zones/{zoneId}/service-headers") - @Produces({ "application/json" }) + @Produces("application/json") public List getServiceHeaderInfoListByZoneId(@PathParam("zoneId") Long zoneId, @Context HttpServletRequest request) { - if (logger.isDebugEnabled()) { - logger.debug("==> PublicAPIsv2.getServiceHeaderInfoListByZoneId({})" + zoneId); - } + logger.debug("==> PublicAPIsv2.getServiceHeaderInfoListByZoneId({})", zoneId); List ret; + try { ret = securityZoneStore.getServiceHeaderInfoListByZoneId(zoneId, request); } catch (WebApplicationException excp) { throw excp; } catch (Throwable excp) { logger.error("PublicAPIsv2.getServiceHeaderInfoListByZoneId() failed", excp); + throw restErrorUtil.createRESTException(excp.getMessage()); } - if (logger.isDebugEnabled()) { - logger.debug("<== PublicAPIsv2.getServiceHeaderInfoListByZoneId():" + ret); + logger.debug("<== PublicAPIsv2.getServiceHeaderInfoListByZoneId():{}", ret); + return ret; + } + + @GET + @Path("/api/zone-names/{serviceName}/resource") + @Produces("application/json") + @PreAuthorize("@rangerPreAuthSecurityHandler.isAPISpnegoAccessible()") + public Collection getSecurityZoneNamesForResource(@PathParam("serviceName") String serviceName, @Context HttpServletRequest request) { + return securityZoneRest.getZoneNamesForResource(serviceName, request); + } + + @POST + @Path("/api/zones-v2") + @Consumes("application/json") + @Produces("application/json") + public RangerSecurityZoneV2 createSecurityZone(RangerSecurityZoneV2 securityZone) { + return securityZoneRest.createSecurityZone(securityZone); + } + + @PUT + @Path("/api/zones-v2/{id}") + @Consumes("application/json") + @Produces("application/json") + public RangerSecurityZoneV2 updateSecurityZone(@PathParam("id") Long zoneId, RangerSecurityZoneV2 securityZone) { + return securityZoneRest.updateSecurityZone(zoneId, securityZone); + } + + @PUT + @Path("/api/zones-v2/{id}/partial") + @Consumes("application/json") + @Produces("application/json") + public Boolean updateSecurityZone(@PathParam("id") Long zoneId, RangerSecurityZoneChangeRequest changeRequest) { + return securityZoneRest.updateSecurityZone(zoneId, changeRequest); + } + + @GET + @Path("/api/zones-v2/name/{name}") + @Produces("application/json") + public RangerSecurityZoneV2 getSecurityZoneV2(@PathParam("name") String zoneName) { + return securityZoneRest.getSecurityZoneV2(zoneName); + } + + @GET + @Path("/api/zones-v2/{id}") + @Produces("application/json") + public RangerSecurityZoneV2 getSecurityZoneV2(@PathParam("id") Long zoneId) { + return securityZoneRest.getSecurityZoneV2(zoneId); + } + + @GET + @Path("/api/zones-v2/{id}/resources/{serviceName}") + @Produces("application/json") + public PList getResources(@PathParam("id") Long zoneId, @PathParam("serviceName") String serviceName, @Context HttpServletRequest request) { + return securityZoneRest.getResources(zoneId, serviceName, request); + } + + @GET + @Path("/api/zones-v2/name/{name}/resources/{serviceName}") + @Produces("application/json") + public PList getResources(@PathParam("name") String zoneName, @PathParam("serviceName") String serviceName, @Context HttpServletRequest request) { + return securityZoneRest.getResources(zoneName, serviceName, request); + } + + @GET + @Path("/api/zones-v2") + @Produces("application/json") + public PList getAllZonesV2(@Context HttpServletRequest request) { + return securityZoneRest.getAllZonesV2(request); + } + + /* + * ServiceDef Manipulation APIs + */ + + @GET + @Path("/api/servicedef/{id}") + @Produces("application/json") + public RangerServiceDef getServiceDef(@PathParam("id") Long id) { + return serviceREST.getServiceDef(id); + } + + @GET + @Path("/api/servicedef/name/{name}") + @Produces("application/json") + public RangerServiceDef getServiceDefByName(@PathParam("name") String name) { + return serviceREST.getServiceDefByName(name); + } + + @GET + @Path("/api/servicedef/") + @Produces("application/json") + public List searchServiceDefs(@Context HttpServletRequest request) { + return serviceREST.getServiceDefs(request).getServiceDefs(); + } + + @POST + @Path("/api/servicedef/") + @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") + @Consumes("application/json") + @Produces("application/json") + public RangerServiceDef createServiceDef(RangerServiceDef serviceDef) { + return serviceREST.createServiceDef(serviceDef); + } + + @PUT + @Path("/api/servicedef/{id}") + @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") + @Consumes("application/json") + @Produces("application/json") + public RangerServiceDef updateServiceDef(RangerServiceDef serviceDef, @PathParam("id") Long id) { + // if serviceDef.id is specified, it should be same as param 'id' + if (serviceDef.getId() == null) { + serviceDef.setId(id); + } else if (!serviceDef.getId().equals(id)) { + throw restErrorUtil.createRESTException(HttpServletResponse.SC_BAD_REQUEST, "serviceDef id mismatch", true); + } + + return serviceREST.updateServiceDef(serviceDef, serviceDef.getId()); + } + + @PUT + @Path("/api/servicedef/name/{name}") + @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") + @Consumes("application/json") + @Produces("application/json") + public RangerServiceDef updateServiceDefByName(RangerServiceDef serviceDef, @PathParam("name") String name) { + // serviceDef.name is immutable + // if serviceDef.name is specified, it should be same as the param 'name' + if (serviceDef.getName() == null) { + serviceDef.setName(name); + } else if (!serviceDef.getName().equals(name)) { + throw restErrorUtil.createRESTException(HttpServletResponse.SC_BAD_REQUEST, "serviceDef name mismatch", true); + } + + // ignore serviceDef.id - if specified. Retrieve using the given name and use id from the retrieved object + RangerServiceDef existingServiceDef = getServiceDefByName(name); + + serviceDef.setId(existingServiceDef.getId()); + + if (StringUtils.isEmpty(serviceDef.getGuid())) { + serviceDef.setGuid(existingServiceDef.getGuid()); + } + + return serviceREST.updateServiceDef(serviceDef, serviceDef.getId()); + } + + /* + * Should add this back when guid is used for search and delete operations as well + @PUT + @Path("/api/servicedef/guid/{guid}") + @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") + @Produces({ "application/json" }) + public RangerServiceDef updateServiceDefByGuid(RangerServiceDef serviceDef, @PathParam("guid") String guid) { + // ignore serviceDef.id - if specified. Retrieve using the given guid and use id from the retrieved object + RangerServiceDef existingServiceDef = getServiceDefByGuid(guid); + serviceDef.setId(existingServiceDef.getId()); + if(StringUtils.isEmpty(serviceDef.getGuid())) { + serviceDef.setGuid(existingServiceDef.getGuid()); + } + + return serviceREST.updateServiceDef(serviceDef); + } + */ + + @DELETE + @Path("/api/servicedef/{id}") + @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") + public void deleteServiceDef(@PathParam("id") Long id, @Context HttpServletRequest request) { + serviceREST.deleteServiceDef(id, request); + } + + @DELETE + @Path("/api/servicedef/name/{name}") + @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") + public void deleteServiceDefByName(@PathParam("name") String name, @Context HttpServletRequest request) { + RangerServiceDef serviceDef = serviceREST.getServiceDefByName(name); + + serviceREST.deleteServiceDef(serviceDef.getId(), request); + } + + /* + * Service Manipulation APIs + */ + + @GET + @Path("/api/service/{id}") + @Produces("application/json") + @PreAuthorize("@rangerPreAuthSecurityHandler.isAPISpnegoAccessible()") + public RangerService getService(@PathParam("id") Long id) { + return serviceREST.getService(id); + } + + @GET + @Path("/api/service/name/{name}") + @Produces("application/json") + @PreAuthorize("@rangerPreAuthSecurityHandler.isAPISpnegoAccessible()") + public RangerService getServiceByName(@PathParam("name") String name) { + return serviceREST.getServiceByName(name); + } + + @GET + @Path("/api/service/") + @Produces("application/json") + @PreAuthorize("@rangerPreAuthSecurityHandler.isAPISpnegoAccessible()") + public List searchServices(@Context HttpServletRequest request) { + return serviceREST.getServices(request).getServices(); + } + + @GET + @Path("/api/service-headers") + @Produces("application/json") + @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.GET_SERVICE_HEADERS + "\")") + public List getServiceHeaders(@Context HttpServletRequest request) { + return serviceREST.getServiceHeaders(request); + } + + @POST + @Path("/api/service/") + @PreAuthorize("@rangerPreAuthSecurityHandler.isAPISpnegoAccessible()") + @Consumes("application/json") + @Produces("application/json") + public RangerService createService(RangerService service) { + return serviceREST.createService(service); + } + + @PUT + @Path("/api/service/{id}") + @PreAuthorize("@rangerPreAuthSecurityHandler.isAPISpnegoAccessible()") + @Consumes("application/json") + @Produces("application/json") + public RangerService updateService(RangerService service, @PathParam("id") Long id, @Context HttpServletRequest request) { + // if service.id is specified, it should be same as the param 'id' + if (service.getId() == null) { + service.setId(id); + } else if (!service.getId().equals(id)) { + throw restErrorUtil.createRESTException(HttpServletResponse.SC_BAD_REQUEST, "service id mismatch", true); + } + + return serviceREST.updateService(service, request); + } + + @PUT + @Path("/api/service/name/{name}") + @PreAuthorize("@rangerPreAuthSecurityHandler.isAPISpnegoAccessible()") + @Consumes("application/json") + @Produces("application/json") + public RangerService updateServiceByName(RangerService service, @PathParam("name") String name, @Context HttpServletRequest request) { + // ignore service.id - if specified. Retrieve using the given name and use id from the retrieved object + RangerService existingService = getServiceByName(name); + + service.setId(existingService.getId()); + + if (StringUtils.isEmpty(service.getGuid())) { + service.setGuid(existingService.getGuid()); + } + + if (StringUtils.isEmpty(service.getName())) { + service.setName(existingService.getName()); + } + + return serviceREST.updateService(service, request); + } + + /* + * Should add this back when guid is used for search and delete operations as well + @PUT + @Path("/api/service/guid/{guid}") + @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") + @Produces({ "application/json" }) + public RangerService updateServiceByGuid(RangerService service, @PathParam("guid") String guid) { + // ignore service.id - if specified. Retrieve using the given guid and use id from the retrieved object + RangerService existingService = getServiceByGuid(guid); + service.setId(existingService.getId()); + if(StringUtils.isEmpty(service.getGuid())) { + service.setGuid(existingService.getGuid()); } + + return serviceREST.updateService(service); + } + */ + + @DELETE + @Path("/api/service/{id}") + @PreAuthorize("@rangerPreAuthSecurityHandler.isAPISpnegoAccessible()") + public void deleteService(@PathParam("id") Long id) { + serviceREST.deleteService(id); + } + + @DELETE + @Path("/api/service/name/{name}") + @PreAuthorize("@rangerPreAuthSecurityHandler.isAPISpnegoAccessible()") + public void deleteServiceByName(@PathParam("name") String name) { + RangerService service = serviceREST.getServiceByName(name); + + serviceREST.deleteService(service.getId()); + } + + /* + * Policy Manipulation APIs + */ + + @GET + @Path("/api/policy/{id}") + @Produces("application/json") + public RangerPolicy getPolicy(@PathParam("id") Long id) { + return serviceREST.getPolicy(id); + } + + @GET + @Path("/api/policy/") + @Produces("application/json") + public List getPolicies(@Context HttpServletRequest request) { + logger.debug("==> PublicAPIsv2.getPolicies()"); + + List ret = serviceREST.getPolicies(request).getPolicies(); + boolean includeMetaAttributes = Boolean.parseBoolean(request.getParameter("includeMetaAttributes")); + + if (includeMetaAttributes) { + ret = serviceREST.getPoliciesWithMetaAttributes(ret); + } + + logger.debug("<== PublicAPIsv2.getPolicies(Request: {} Result Size: {}", request.getQueryString(), ret.size()); + return ret; } - @GET - @Path("/api/zone-names/{serviceName}/resource") - @Produces({ "application/json" }) - @PreAuthorize("@rangerPreAuthSecurityHandler.isAPISpnegoAccessible()") - public Collection getSecurityZoneNamesForResource(@PathParam("serviceName") String serviceName, @Context HttpServletRequest request) { - return securityZoneRest.getZoneNamesForResource(serviceName, request); - } - - @POST - @Path("/api/zones-v2") - @Consumes({ "application/json" }) - @Produces({ "application/json" }) - public RangerSecurityZoneV2 createSecurityZone(RangerSecurityZoneV2 securityZone) { - return securityZoneRest.createSecurityZone(securityZone); - } - - @PUT - @Path("/api/zones-v2/{id}") - @Consumes({ "application/json" }) - @Produces({ "application/json" }) - public RangerSecurityZoneV2 updateSecurityZone(@PathParam("id") Long zoneId, RangerSecurityZoneV2 securityZone) { - return securityZoneRest.updateSecurityZone(zoneId, securityZone); - } - - @PUT - @Path("/api/zones-v2/{id}/partial") - @Consumes({ "application/json" }) - @Produces({ "application/json" }) - public Boolean updateSecurityZone(@PathParam("id") Long zoneId, RangerSecurityZoneChangeRequest changeRequest) { - return securityZoneRest.updateSecurityZone(zoneId, changeRequest); - } - - @GET - @Path("/api/zones-v2/name/{name}") - @Produces({ "application/json" }) - public RangerSecurityZoneV2 getSecurityZoneV2(@PathParam("name") String zoneName) { - return securityZoneRest.getSecurityZoneV2(zoneName); - } - - @GET - @Path("/api/zones-v2/{id}") - @Produces({ "application/json" }) - public RangerSecurityZoneV2 getSecurityZoneV2(@PathParam("id") Long zoneId) { - return securityZoneRest.getSecurityZoneV2(zoneId); - } - - @GET - @Path("/api/zones-v2/{id}/resources/{serviceName}") - @Produces({ "application/json" }) - public PList getResources(@PathParam("id") Long zoneId, @PathParam("serviceName") String serviceName, @Context HttpServletRequest request) { - return securityZoneRest.getResources(zoneId, serviceName, request); - } - - @GET - @Path("/api/zones-v2/name/{name}/resources/{serviceName}") - @Produces({ "application/json" }) - public PList getResources(@PathParam("name") String zoneName, @PathParam("serviceName") String serviceName, @Context HttpServletRequest request) { - return securityZoneRest.getResources(zoneName, serviceName, request); - } - - @GET - @Path("/api/zones-v2") - @Produces({ "application/json"}) - public PList getAllZonesV2(@Context HttpServletRequest request){ - return securityZoneRest.getAllZonesV2(request); - } - - /* - * ServiceDef Manipulation APIs - */ - - @GET - @Path("/api/servicedef/{id}") - @Produces({ "application/json" }) - public RangerServiceDef getServiceDef(@PathParam("id") Long id) { - return serviceREST.getServiceDef(id); - } - - @GET - @Path("/api/servicedef/name/{name}") - @Produces({ "application/json" }) - public RangerServiceDef getServiceDefByName(@PathParam("name") String name) { - return serviceREST.getServiceDefByName(name); - } - - @GET - @Path("/api/servicedef/") - @Produces({ "application/json" }) - public List searchServiceDefs(@Context HttpServletRequest request) { - return serviceREST.getServiceDefs(request).getServiceDefs(); - } - - @POST - @Path("/api/servicedef/") - @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") - @Consumes({ "application/json" }) - @Produces({ "application/json" }) - public RangerServiceDef createServiceDef(RangerServiceDef serviceDef) { - return serviceREST.createServiceDef(serviceDef); - } - - @PUT - @Path("/api/servicedef/{id}") - @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") - @Consumes({ "application/json" }) - @Produces({ "application/json" }) - public RangerServiceDef updateServiceDef(RangerServiceDef serviceDef, @PathParam("id") Long id) { - // if serviceDef.id is specified, it should be same as param 'id' - if(serviceDef.getId() == null) { - serviceDef.setId(id); - } else if(!serviceDef.getId().equals(id)) { - throw restErrorUtil.createRESTException(HttpServletResponse.SC_BAD_REQUEST , "serviceDef id mismatch", true); - } - - return serviceREST.updateServiceDef(serviceDef, serviceDef.getId()); - } - - - @PUT - @Path("/api/servicedef/name/{name}") - @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") - @Consumes({ "application/json" }) - @Produces({ "application/json" }) - public RangerServiceDef updateServiceDefByName(RangerServiceDef serviceDef, - @PathParam("name") String name) { - // serviceDef.name is immutable - // if serviceDef.name is specified, it should be same as the param 'name' - if(serviceDef.getName() == null) { - serviceDef.setName(name); - } else if(!serviceDef.getName().equals(name)) { - throw restErrorUtil.createRESTException(HttpServletResponse.SC_BAD_REQUEST , "serviceDef name mismatch", true); - } - - // ignore serviceDef.id - if specified. Retrieve using the given name and use id from the retrieved object - RangerServiceDef existingServiceDef = getServiceDefByName(name); - serviceDef.setId(existingServiceDef.getId()); - if(StringUtils.isEmpty(serviceDef.getGuid())) { - serviceDef.setGuid(existingServiceDef.getGuid()); - } - - return serviceREST.updateServiceDef(serviceDef, serviceDef.getId()); - } - - /* - * Should add this back when guid is used for search and delete operations as well - @PUT - @Path("/api/servicedef/guid/{guid}") - @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") - @Produces({ "application/json" }) - public RangerServiceDef updateServiceDefByGuid(RangerServiceDef serviceDef, - @PathParam("guid") String guid) { - // ignore serviceDef.id - if specified. Retrieve using the given guid and use id from the retrieved object - RangerServiceDef existingServiceDef = getServiceDefByGuid(guid); - serviceDef.setId(existingServiceDef.getId()); - if(StringUtils.isEmpty(serviceDef.getGuid())) { - serviceDef.setGuid(existingServiceDef.getGuid()); - } - - return serviceREST.updateServiceDef(serviceDef); - } - */ - - - @DELETE - @Path("/api/servicedef/{id}") - @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") - public void deleteServiceDef(@PathParam("id") Long id, @Context HttpServletRequest request) { - serviceREST.deleteServiceDef(id, request); - } - - @DELETE - @Path("/api/servicedef/name/{name}") - @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") - public void deleteServiceDefByName(@PathParam("name") String name, @Context HttpServletRequest request) { - RangerServiceDef serviceDef = serviceREST.getServiceDefByName(name); - serviceREST.deleteServiceDef(serviceDef.getId(), request); - } - - /* - * Service Manipulation APIs - */ - - @GET - @Path("/api/service/{id}") - @Produces({ "application/json" }) - @PreAuthorize("@rangerPreAuthSecurityHandler.isAPISpnegoAccessible()") - public RangerService getService(@PathParam("id") Long id) { - return serviceREST.getService(id); - } - - @GET - @Path("/api/service/name/{name}") - @Produces({ "application/json" }) - @PreAuthorize("@rangerPreAuthSecurityHandler.isAPISpnegoAccessible()") - public RangerService getServiceByName(@PathParam("name") String name) { - return serviceREST.getServiceByName(name); - } - - @GET - @Path("/api/service/") - @Produces({ "application/json" }) - @PreAuthorize("@rangerPreAuthSecurityHandler.isAPISpnegoAccessible()") - public List searchServices(@Context HttpServletRequest request) { - return serviceREST.getServices(request).getServices(); - } - - @GET - @Path("/api/service-headers") - @Produces({ "application/json" }) - @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.GET_SERVICE_HEADERS + "\")") - public List getServiceHeaders(@Context HttpServletRequest request) { - return serviceREST.getServiceHeaders(request); - } - - @POST - @Path("/api/service/") - @PreAuthorize("@rangerPreAuthSecurityHandler.isAPISpnegoAccessible()") - @Consumes({ "application/json" }) - @Produces({ "application/json" }) - public RangerService createService(RangerService service) { - return serviceREST.createService(service); - } - - @PUT - @Path("/api/service/{id}") - @PreAuthorize("@rangerPreAuthSecurityHandler.isAPISpnegoAccessible()") - @Consumes({ "application/json" }) - @Produces({ "application/json" }) - public RangerService updateService(RangerService service, @PathParam("id") Long id, - @Context HttpServletRequest request) { - // if service.id is specified, it should be same as the param 'id' - if(service.getId() == null) { - service.setId(id); - } else if(!service.getId().equals(id)) { - throw restErrorUtil.createRESTException(HttpServletResponse.SC_BAD_REQUEST , "service id mismatch", true); - } - - return serviceREST.updateService(service, request); - } - - @PUT - @Path("/api/service/name/{name}") - @PreAuthorize("@rangerPreAuthSecurityHandler.isAPISpnegoAccessible()") - @Consumes({ "application/json" }) - @Produces({ "application/json" }) - public RangerService updateServiceByName(RangerService service, - @PathParam("name") String name, - @Context HttpServletRequest request) { - // ignore service.id - if specified. Retrieve using the given name and use id from the retrieved object - RangerService existingService = getServiceByName(name); - service.setId(existingService.getId()); - if(StringUtils.isEmpty(service.getGuid())) { - service.setGuid(existingService.getGuid()); - } - if (StringUtils.isEmpty(service.getName())) { - service.setName(existingService.getName()); - } - - return serviceREST.updateService(service, request); - } - - /* - * Should add this back when guid is used for search and delete operations as well - @PUT - @Path("/api/service/guid/{guid}") - @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") - @Produces({ "application/json" }) - public RangerService updateServiceByGuid(RangerService service, - @PathParam("guid") String guid) { - // ignore service.id - if specified. Retrieve using the given guid and use id from the retrieved object - RangerService existingService = getServiceByGuid(guid); - service.setId(existingService.getId()); - if(StringUtils.isEmpty(service.getGuid())) { - service.setGuid(existingService.getGuid()); - } - - return serviceREST.updateService(service); - } - */ - - @DELETE - @Path("/api/service/{id}") - @PreAuthorize("@rangerPreAuthSecurityHandler.isAPISpnegoAccessible()") - public void deleteService(@PathParam("id") Long id) { - serviceREST.deleteService(id); - } - - @DELETE - @Path("/api/service/name/{name}") - @PreAuthorize("@rangerPreAuthSecurityHandler.isAPISpnegoAccessible()") - public void deleteServiceByName(@PathParam("name") String name) { - RangerService service = serviceREST.getServiceByName(name); - serviceREST.deleteService(service.getId()); - } - - - /* - * Policy Manipulation APIs - */ - - @GET - @Path("/api/policy/{id}") - @Produces({ "application/json" }) - public RangerPolicy getPolicy(@PathParam("id") Long id) { - return serviceREST.getPolicy(id); - } - - @GET - @Path("/api/policy/") - @Produces({ "application/json" }) - public List getPolicies(@Context HttpServletRequest request) { - - List ret = new ArrayList(); - - if(logger.isDebugEnabled()) { - logger.debug("==> PublicAPIsv2.getPolicies()"); - } - - ret = serviceREST.getPolicies(request).getPolicies(); - - boolean includeMetaAttributes = Boolean.parseBoolean(request.getParameter("includeMetaAttributes")); - if (includeMetaAttributes) { - ret = serviceREST.getPoliciesWithMetaAttributes(ret); - } - if(logger.isDebugEnabled()) { - logger.debug("<== PublicAPIsv2.getPolicies(Request: " + request.getQueryString() + " Result Size: " + ret.size() ); - } - return ret; - } - - @GET - @Path("/api/service/{servicename}/policy/{policyname}") - @Produces({ "application/json" }) - public RangerPolicy getPolicyByName(@PathParam("servicename") String serviceName, - @PathParam("policyname") String policyName, - @QueryParam("zoneName") String zoneName, - @Context HttpServletRequest request) { - if(logger.isDebugEnabled()) { - logger.debug("==> PublicAPIsv2.getPolicyByName(" + serviceName + "," + policyName + "," + zoneName + ")"); - } - - RangerPolicy policy = serviceREST.getPolicyByName(serviceName, policyName, zoneName); - - if (policy == null) { - throw restErrorUtil.createRESTException(HttpServletResponse.SC_NOT_FOUND, "Not found", true); - } - - if(logger.isDebugEnabled()) { - logger.debug("<== PublicAPIsv2.getPolicyByName(" + serviceName + "," + policyName + "," + zoneName + ")" + policy); - } - return policy; - } - - @GET - @Path("/api/service/{servicename}/policy/") - @Produces({ "application/json" }) - public List searchPolicies(@PathParam("servicename") String serviceName, - @Context HttpServletRequest request) { - return serviceREST.getServicePoliciesByName(serviceName, request).getPolicies(); - } - - @GET - @Path("/api/policies/{serviceDefName}/for-resource/") - @Produces({ "application/json" }) - public List getPoliciesForResource(@PathParam("serviceDefName") String serviceDefName, - @DefaultValue("") @QueryParam("serviceName") String serviceName, - @Context HttpServletRequest request) { - return serviceREST.getPoliciesForResource(serviceDefName, serviceName, request); - } - - @GET - @Path("/api/policy/guid/{guid}") - @Produces({ "application/json" }) - public RangerPolicy getPolicyByGUIDAndServiceNameAndZoneName(@PathParam("guid") String guid, - @DefaultValue("") @QueryParam("serviceName") String serviceName, - @DefaultValue("") @QueryParam("ZoneName") String zoneName) { - if(logger.isDebugEnabled()) { - logger.debug("==> PublicAPIsv2.getPolicyByGUIDAndServiceNameAndZoneName(" + guid + "," + serviceName + "," + zoneName + ")"); - } - RangerPolicy rangerPolicy = serviceREST.getPolicyByGUIDAndServiceNameAndZoneName(guid, serviceName, zoneName); - if(logger.isDebugEnabled()) { - logger.debug("<== PublicAPIsv2.getPolicyByGUIDAndServiceNameAndZoneName(" + guid + "," + serviceName + "," + zoneName + ")"); - } - return rangerPolicy; - } - - @POST - @Path("/api/policy/") - @Consumes({ "application/json" }) - @Produces({ "application/json" }) - public RangerPolicy createPolicy(RangerPolicy policy , @Context HttpServletRequest request) { - return serviceREST.createPolicy(policy, request); - } - - @POST - @Path("/api/policy/apply/") - @Consumes({ "application/json"}) - @Produces({ "application/json"}) - public RangerPolicy applyPolicy(RangerPolicy policy, @Context HttpServletRequest request) { // new API - return serviceREST.applyPolicy(policy, request); - } - - @PUT - @Path("/api/policy/{id}") - @Consumes({ "application/json" }) - @Produces({ "application/json" }) - public RangerPolicy updatePolicy(RangerPolicy policy, @PathParam("id") Long id) { - // if policy.id is specified, it should be same as the param 'id' - if(policy.getId() == null) { - policy.setId(id); - } else if(!policy.getId().equals(id)) { - throw restErrorUtil.createRESTException(HttpServletResponse.SC_BAD_REQUEST , "policyID mismatch", true); - } - - return serviceREST.updatePolicy(policy, id); - } - - @PUT - @Path("/api/service/{servicename}/policy/{policyname}") - @Consumes({ "application/json" }) - @Produces({ "application/json" }) - public RangerPolicy updatePolicyByName(RangerPolicy policy, - @PathParam("servicename") String serviceName, - @PathParam("policyname") String policyName, - @QueryParam("zoneName") String zoneName, - @Context HttpServletRequest request) { - if (policy.getService() == null || !policy.getService().equals(serviceName)) { - throw restErrorUtil.createRESTException(HttpServletResponse.SC_BAD_REQUEST , "service name mismatch", true); - } - RangerPolicy oldPolicy = getPolicyByName(serviceName, policyName, zoneName, request); - - // ignore policy.id - if specified. Retrieve using the given serviceName+policyName and use id from the retrieved object - policy.setId(oldPolicy.getId()); - if(StringUtils.isEmpty(policy.getGuid())) { - policy.setGuid(oldPolicy.getGuid()); - } - if(StringUtils.isEmpty(policy.getName())) { - policy.setName(StringUtils.trim(oldPolicy.getName())); - } - - return serviceREST.updatePolicy(policy, policy.getId()); - } - - - /* Should add this back when guid is used for search and delete operations as well - @PUT - @Path("/api/policy/guid/{guid}") - @Produces({ "application/json" }) - public RangerPolicy updatePolicyByGuid(RangerPolicy policy, - @PathParam("guid") String guid) { - // ignore policy.guid - if specified. Retrieve using the given guid and use id from the retrieved object - RangerPolicy existingPolicy = getPolicyByGuid(name); - policy.setId(existingPolicy.getId()); - if(StringUtils.isEmpty(policy.getGuid())) { - policy.setGuid(existingPolicy.getGuid()); - } - - return serviceREST.updatePolicy(policy); - } - */ - - - @DELETE - @Path("/api/policy/{id}") - public void deletePolicy(@PathParam("id") Long id) { - serviceREST.deletePolicy(id); - } - - @DELETE - @Path("/api/policy") - public void deletePolicyByName(@QueryParam("servicename") String serviceName, - @QueryParam("policyname") String policyName, - @QueryParam("zoneName") String zoneName, - @Context HttpServletRequest request) { - if(logger.isDebugEnabled()) { - logger.debug("==> PublicAPIsv2.deletePolicyByName(" + serviceName + "," + policyName + ")"); - } - - if (serviceName == null || policyName == null) { - throw restErrorUtil.createRESTException(HttpServletResponse.SC_BAD_REQUEST , "Invalid service name or policy name", true); - } - RangerPolicy policy = getPolicyByName(serviceName, policyName, zoneName, request); - serviceREST.deletePolicy(policy.getId()); - if(logger.isDebugEnabled()) { - logger.debug("<== PublicAPIsv2.deletePolicyByName(" + serviceName + "," + policyName + ")"); - } - } - - @DELETE - @Path("/api/policy/guid/{guid}") - public void deletePolicyByGUIDAndServiceNameAndZoneName(@PathParam("guid") String guid, - @DefaultValue("") @QueryParam("serviceName") String serviceName, - @DefaultValue("") @QueryParam("zoneName") String zoneName) { - if(logger.isDebugEnabled()) { - logger.debug("==> PublicAPIsv2.deletePolicyByGUIDAndServiceNameAndZoneName(" + guid + "," + serviceName + "," + zoneName + ")"); - } - serviceREST.deletePolicyByGUIDAndServiceNameAndZoneName(guid, serviceName, zoneName); - if(logger.isDebugEnabled()) { - logger.debug("<== PublicAPIsv2.deletePolicyByGUIDAndServiceNameAndZoneName(" + guid + "," + serviceName + "," + zoneName + ")"); - } - } - - @PUT - @Path("/api/service/{serviceName}/tags") - @Consumes({ "application/json" }) - @Produces({ "application/json" }) - @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") - public void importServiceTags(@PathParam("serviceName") String serviceName, RangerServiceTags svcTags) { - if (logger.isDebugEnabled()) { - logger.debug("==> PublicAPIsv2.importServiceTags()"); - } - - // overwrite serviceName with the one given in url - if (svcTags.getServiceResources() != null) { - for (RangerServiceResource svcResource : svcTags.getServiceResources()) { - svcResource.setServiceName(serviceName); - } - } - - ServiceTags serviceTags = RangerServiceTags.toServiceTags(svcTags); - - // overwrite serviceName with the one given in url - serviceTags.setServiceName(serviceName); - - tagREST.importServiceTags(serviceTags); - - if (logger.isDebugEnabled()) { - logger.debug("<== PublicAPIsv2.importServiceTags()"); - } - } - - @GET - @Path("/api/service/{serviceName}/tags") - @Produces({ "application/json" }) - @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") - public RangerServiceTags getServiceTags(@PathParam("serviceName") String serviceName, @Context HttpServletRequest request) { - if (logger.isDebugEnabled()) { - logger.debug("==> PublicAPIsv2.getServiceTags()"); - } - - Long lastKnownVersion = -1L; - Long lastActivationTime = 0L; - String pluginId = null; - Boolean supportsTagDeltas = false; - String pluginCapabilities = ""; - ServiceTags tags = tagREST.getServiceTagsIfUpdated(serviceName, lastKnownVersion, lastActivationTime, pluginId, supportsTagDeltas, pluginCapabilities, request); - RangerServiceTags ret = RangerServiceTags.toRangerServiceTags(tags); - - if (logger.isDebugEnabled()) { - logger.debug("<== PublicAPIsv2.getServiceTags()"); - } - - return ret; - } - - - @GET - @Path("/api/plugins/info") - @Produces({ "application/json" }) - public List getPluginsInfo(@Context HttpServletRequest request) { - if (logger.isDebugEnabled()) { - logger.debug("==> PublicAPIsv2.getPluginsInfo()"); - } - - List ret = serviceREST.getPluginsInfo(request).getPluginInfoList(); - - if (logger.isDebugEnabled()) { - logger.debug("<== PublicAPIsv2.getPluginsInfo()"); - } - return ret; - } - - @DELETE - @Path("/api/server/policydeltas") - @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") - public void deletePolicyDeltas(@DefaultValue("7") @QueryParam("days") Integer olderThan, @Context HttpServletRequest request) { - if (logger.isDebugEnabled()) { - logger.debug("==> PublicAPIsv2.deletePolicyDeltas(" + olderThan + ")"); - } - - serviceREST.deletePolicyDeltas(olderThan, request); - - if (logger.isDebugEnabled()) { - logger.debug("<== PublicAPIsv2.deletePolicyDeltas(" + olderThan + ")"); - } - } - - @DELETE - @Path("/api/server/tagdeltas") - @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") - public void deleteTagDeltas(@DefaultValue("7") @QueryParam("days") Integer olderThan, @Context HttpServletRequest request) { - if (logger.isDebugEnabled()) { - logger.debug("==> PublicAPIsv2.deleteTagDeltas(" + olderThan + ")"); - } - - tagREST.deleteTagDeltas(olderThan, request); - - if (logger.isDebugEnabled()) { - logger.debug("<== PublicAPIsv2.deleteTagDeltas(" + olderThan + ")"); - } - } - - @DELETE - @Path("/api/server/purgepolicies/{serviceName}") - @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") - public void purgeEmptyPolicies(@PathParam("serviceName") String serviceName, @Context HttpServletRequest request) { - if (logger.isDebugEnabled()) { - logger.debug("==> PublicAPIsv2.purgeEmptyPolicies(" + serviceName + ")"); - } - - if (serviceName == null) { - throw restErrorUtil.createRESTException(HttpServletResponse.SC_BAD_REQUEST , "Invalid service name", true); - } - - serviceREST.purgeEmptyPolicies(serviceName, request); - - if (logger.isDebugEnabled()) { - logger.debug("<== PublicAPIsv2.purgeEmptyPolicies(" + serviceName + ")"); - } - } - - /* - * Role Creation API - */ - - @POST - @Path("/api/roles") - @Consumes({ "application/json" }) - @Produces({ "application/json" }) - public RangerRole createRole(@QueryParam("serviceName") String serviceName, RangerRole role - , @DefaultValue("false") @QueryParam("createNonExistUserGroup") Boolean createNonExistUserGroup - , @Context HttpServletRequest request) { - logger.info("==> PublicAPIsv2.createRole"); - RangerRole ret; - ret = roleREST.createRole(serviceName, role, createNonExistUserGroup); - logger.info("<== PublicAPIsv2.createRole" + ret.getName()); - return ret; - } - - /* - * Role Manipulation API - */ - @PUT - @Path("/api/roles/{id}") - @Consumes({ "application/json" }) - @Produces({ "application/json" }) - public RangerRole updateRole(@PathParam("id") Long roleId, RangerRole role - , @DefaultValue("false") @QueryParam("createNonExistUserGroup") Boolean createNonExistUserGroup - , @Context HttpServletRequest request) { - return roleREST.updateRole(roleId, role, createNonExistUserGroup); - } - - @DELETE - @Path("/api/roles/name/{name}") - public void deleteRole(@QueryParam("serviceName") String serviceName, @QueryParam("execUser") String userName, @PathParam("name") String roleName, @Context HttpServletRequest request) { - roleREST.deleteRole(serviceName, userName, roleName); - } - - @DELETE - @Path("/api/roles/{id}") - public void deleteRole(@PathParam("id") Long roleId, @Context HttpServletRequest request) { - roleREST.deleteRole(roleId); - } - - /* - * APIs to Access Roles - */ - @GET - @Path("/api/roles/name/{name}") - @Produces({ "application/json" }) - public RangerRole getRole(@QueryParam("serviceName") String serviceName, @QueryParam("execUser") String userName, @PathParam("name") String roleName, @Context HttpServletRequest request) { - return roleREST.getRole(serviceName, userName, roleName); - } - - @GET - @Path("/api/roles/{id}") - @Produces({ "application/json" }) - public RangerRole getRole(@PathParam("id") Long id, @Context HttpServletRequest request) { - return roleREST.getRole(id); - } - - @GET - @Path("/api/roles") - @Produces({ "application/json" }) - public List getAllRoles(@Context HttpServletRequest request) { - return roleREST.getAllRoles(request).getSecurityRoles(); - } - - @GET - @Path("/api/roles/names") - @Produces({ "application/json" }) - public List getAllRoleNames(@QueryParam("serviceName") String serviceName, @QueryParam("execUser") String userName, @Context HttpServletRequest request){ - return roleREST.getAllRoleNames(serviceName, userName, request); - } - - @GET - @Path("/api/roles/user/{user}") - @Produces({ "application/json" }) - public List getUserRoles(@PathParam("user") String userName, @Context HttpServletRequest request){ - return roleREST.getUserRoles(userName, request); - } - - /* - This API is used to add users and groups with/without GRANT privileges to this Role. It follows add-or-update semantics - */ - @PUT - @Path("/api/roles/{id}/addUsersAndGroups") - @Consumes({ "application/json" }) - @Produces({ "application/json" }) - public RangerRole addUsersAndGroups(@PathParam("id") Long roleId, List users, List groups, Boolean isAdmin, @Context HttpServletRequest request) { - return roleREST.addUsersAndGroups(roleId, users, groups, isAdmin); - } - - /* + @GET + @Path("/api/service/{servicename}/policy/{policyname}") + @Produces("application/json") + public RangerPolicy getPolicyByName(@PathParam("servicename") String serviceName, @PathParam("policyname") String policyName, @QueryParam("zoneName") String zoneName, @Context HttpServletRequest request) { + logger.debug("==> PublicAPIsv2.getPolicyByName({}, {}, {})", serviceName, policyName, zoneName); + + RangerPolicy policy = serviceREST.getPolicyByName(serviceName, policyName, zoneName); + + if (policy == null) { + throw restErrorUtil.createRESTException(HttpServletResponse.SC_NOT_FOUND, "Not found", true); + } + + logger.debug("<== PublicAPIsv2.getPolicyByName({}, {}, {}): {}", serviceName, policyName, zoneName, policy); + return policy; + } + + @GET + @Path("/api/service/{servicename}/policy/") + @Produces("application/json") + public List searchPolicies(@PathParam("servicename") String serviceName, @Context HttpServletRequest request) { + return serviceREST.getServicePoliciesByName(serviceName, request).getPolicies(); + } + + @GET + @Path("/api/policies/{serviceDefName}/for-resource/") + @Produces("application/json") + public List getPoliciesForResource(@PathParam("serviceDefName") String serviceDefName, @DefaultValue("") @QueryParam("serviceName") String serviceName, @Context HttpServletRequest request) { + return serviceREST.getPoliciesForResource(serviceDefName, serviceName, request); + } + + @GET + @Path("/api/policy/guid/{guid}") + @Produces("application/json") + public RangerPolicy getPolicyByGUIDAndServiceNameAndZoneName(@PathParam("guid") String guid, @DefaultValue("") @QueryParam("serviceName") String serviceName, @DefaultValue("") @QueryParam("ZoneName") String zoneName) { + logger.debug("==> PublicAPIsv2.getPolicyByGUIDAndServiceNameAndZoneName({}, {}, {})", guid, serviceName, zoneName); + + RangerPolicy rangerPolicy = serviceREST.getPolicyByGUIDAndServiceNameAndZoneName(guid, serviceName, zoneName); + + logger.debug("<== PublicAPIsv2.getPolicyByGUIDAndServiceNameAndZoneName({}, {}, {})", guid, serviceName, zoneName); + + return rangerPolicy; + } + + @POST + @Path("/api/policy/") + @Consumes("application/json") + @Produces("application/json") + public RangerPolicy createPolicy(RangerPolicy policy, @Context HttpServletRequest request) { + return serviceREST.createPolicy(policy, request); + } + + @POST + @Path("/api/policy/apply/") + @Consumes("application/json") + @Produces("application/json") + public RangerPolicy applyPolicy(RangerPolicy policy, @Context HttpServletRequest request) { // new API + return serviceREST.applyPolicy(policy, request); + } + + @PUT + @Path("/api/policy/{id}") + @Consumes("application/json") + @Produces("application/json") + public RangerPolicy updatePolicy(RangerPolicy policy, @PathParam("id") Long id) { + // if policy.id is specified, it should be same as the param 'id' + if (policy.getId() == null) { + policy.setId(id); + } else if (!policy.getId().equals(id)) { + throw restErrorUtil.createRESTException(HttpServletResponse.SC_BAD_REQUEST, "policyID mismatch", true); + } + + return serviceREST.updatePolicy(policy, id); + } + + @PUT + @Path("/api/service/{servicename}/policy/{policyname}") + @Consumes("application/json") + @Produces("application/json") + public RangerPolicy updatePolicyByName(RangerPolicy policy, @PathParam("servicename") String serviceName, @PathParam("policyname") String policyName, @QueryParam("zoneName") String zoneName, @Context HttpServletRequest request) { + if (policy.getService() == null || !policy.getService().equals(serviceName)) { + throw restErrorUtil.createRESTException(HttpServletResponse.SC_BAD_REQUEST, "service name mismatch", true); + } + + RangerPolicy oldPolicy = getPolicyByName(serviceName, policyName, zoneName, request); + + // ignore policy.id - if specified. Retrieve using the given serviceName+policyName and use id from the retrieved object + policy.setId(oldPolicy.getId()); + + if (StringUtils.isEmpty(policy.getGuid())) { + policy.setGuid(oldPolicy.getGuid()); + } + + if (StringUtils.isEmpty(policy.getName())) { + policy.setName(StringUtils.trim(oldPolicy.getName())); + } + + return serviceREST.updatePolicy(policy, policy.getId()); + } + + /* Should add this back when guid is used for search and delete operations as well + @PUT + @Path("/api/policy/guid/{guid}") + @Produces({ "application/json" }) + public RangerPolicy updatePolicyByGuid(RangerPolicy policy, @PathParam("guid") String guid) { + // ignore policy.guid - if specified. Retrieve using the given guid and use id from the retrieved object + RangerPolicy existingPolicy = getPolicyByGuid(name); + policy.setId(existingPolicy.getId()); + if(StringUtils.isEmpty(policy.getGuid())) { + policy.setGuid(existingPolicy.getGuid()); + } + + return serviceREST.updatePolicy(policy); + } + */ + + @DELETE + @Path("/api/policy/{id}") + public void deletePolicy(@PathParam("id") Long id) { + serviceREST.deletePolicy(id); + } + + @DELETE + @Path("/api/policy") + public void deletePolicyByName(@QueryParam("servicename") String serviceName, @QueryParam("policyname") String policyName, @QueryParam("zoneName") String zoneName, @Context HttpServletRequest request) { + logger.debug("==> PublicAPIsv2.deletePolicyByName({}, {})", serviceName, policyName); + + if (serviceName == null || policyName == null) { + throw restErrorUtil.createRESTException(HttpServletResponse.SC_BAD_REQUEST, "Invalid service name or policy name", true); + } + + RangerPolicy policy = getPolicyByName(serviceName, policyName, zoneName, request); + + serviceREST.deletePolicy(policy.getId()); + + logger.debug("<== PublicAPIsv2.deletePolicyByName({}, {})", serviceName, policyName); + } + + @DELETE + @Path("/api/policy/guid/{guid}") + public void deletePolicyByGUIDAndServiceNameAndZoneName(@PathParam("guid") String guid, @DefaultValue("") @QueryParam("serviceName") String serviceName, @DefaultValue("") @QueryParam("zoneName") String zoneName) { + logger.debug("==> PublicAPIsv2.deletePolicyByGUIDAndServiceNameAndZoneName({}, {}, {})", guid, serviceName, zoneName); + + serviceREST.deletePolicyByGUIDAndServiceNameAndZoneName(guid, serviceName, zoneName); + + logger.debug("<== PublicAPIsv2.deletePolicyByGUIDAndServiceNameAndZoneName({}, {}, {})", guid, serviceName, zoneName); + } + + @PUT + @Path("/api/service/{serviceName}/tags") + @Consumes("application/json") + @Produces("application/json") + @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") + public void importServiceTags(@PathParam("serviceName") String serviceName, RangerServiceTags svcTags) { + logger.debug("==> PublicAPIsv2.importServiceTags()"); + + // overwrite serviceName with the one given in url + if (svcTags.getServiceResources() != null) { + for (RangerServiceResource svcResource : svcTags.getServiceResources()) { + svcResource.setServiceName(serviceName); + } + } + + ServiceTags serviceTags = RangerServiceTags.toServiceTags(svcTags); + + // overwrite serviceName with the one given in url + serviceTags.setServiceName(serviceName); + + tagREST.importServiceTags(serviceTags); + + logger.debug("<== PublicAPIsv2.importServiceTags()"); + } + + @GET + @Path("/api/service/{serviceName}/tags") + @Produces("application/json") + @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") + public RangerServiceTags getServiceTags(@PathParam("serviceName") String serviceName, @Context HttpServletRequest request) { + logger.debug("==> PublicAPIsv2.getServiceTags()"); + + Long lastKnownVersion = -1L; + Long lastActivationTime = 0L; + String pluginId = null; + Boolean supportsTagDeltas = false; + String pluginCapabilities = ""; + ServiceTags tags = tagREST.getServiceTagsIfUpdated(serviceName, lastKnownVersion, lastActivationTime, pluginId, supportsTagDeltas, pluginCapabilities, request); + RangerServiceTags ret = RangerServiceTags.toRangerServiceTags(tags); + + logger.debug("<== PublicAPIsv2.getServiceTags()"); + + return ret; + } + + @GET + @Path("/api/plugins/info") + @Produces("application/json") + public List getPluginsInfo(@Context HttpServletRequest request) { + logger.debug("==> PublicAPIsv2.getPluginsInfo()"); + + List ret = serviceREST.getPluginsInfo(request).getPluginInfoList(); + + logger.debug("<== PublicAPIsv2.getPluginsInfo()"); + + return ret; + } + + @DELETE + @Path("/api/server/policydeltas") + @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") + public void deletePolicyDeltas(@DefaultValue("7") @QueryParam("days") Integer olderThan, @Context HttpServletRequest request) { + logger.debug("==> PublicAPIsv2.deletePolicyDeltas({})", olderThan); + + serviceREST.deletePolicyDeltas(olderThan, request); + + logger.debug("<== PublicAPIsv2.deletePolicyDeltas({})", olderThan); + } + + @DELETE + @Path("/api/server/tagdeltas") + @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") + public void deleteTagDeltas(@DefaultValue("7") @QueryParam("days") Integer olderThan, @Context HttpServletRequest request) { + logger.debug("==> PublicAPIsv2.deleteTagDeltas({})", olderThan); + + tagREST.deleteTagDeltas(olderThan, request); + + logger.debug("<== PublicAPIsv2.deleteTagDeltas({})", olderThan); + } + + @DELETE + @Path("/api/server/purgepolicies/{serviceName}") + @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") + public void purgeEmptyPolicies(@PathParam("serviceName") String serviceName, @Context HttpServletRequest request) { + logger.debug("==> PublicAPIsv2.purgeEmptyPolicies({})", serviceName); + + if (serviceName == null) { + throw restErrorUtil.createRESTException(HttpServletResponse.SC_BAD_REQUEST, "Invalid service name", true); + } + + serviceREST.purgeEmptyPolicies(serviceName, request); + + logger.debug("<== PublicAPIsv2.purgeEmptyPolicies({})", serviceName); + } + + /* + * Role Creation API + */ + + @POST + @Path("/api/roles") + @Consumes("application/json") + @Produces("application/json") + public RangerRole createRole(@QueryParam("serviceName") String serviceName, RangerRole role, @DefaultValue("false") @QueryParam("createNonExistUserGroup") Boolean createNonExistUserGroup, @Context HttpServletRequest request) { + logger.info("==> PublicAPIsv2.createRole"); + + RangerRole ret = roleREST.createRole(serviceName, role, createNonExistUserGroup); + + logger.info("<== PublicAPIsv2.createRole({})", ret.getName()); + + return ret; + } + + /* + * Role Manipulation API + */ + @PUT + @Path("/api/roles/{id}") + @Consumes("application/json") + @Produces("application/json") + public RangerRole updateRole(@PathParam("id") Long roleId, RangerRole role, @DefaultValue("false") @QueryParam("createNonExistUserGroup") Boolean createNonExistUserGroup, @Context HttpServletRequest request) { + return roleREST.updateRole(roleId, role, createNonExistUserGroup); + } + + @DELETE + @Path("/api/roles/name/{name}") + public void deleteRole(@QueryParam("serviceName") String serviceName, @QueryParam("execUser") String userName, @PathParam("name") String roleName, @Context HttpServletRequest request) { + roleREST.deleteRole(serviceName, userName, roleName); + } + + @DELETE + @Path("/api/roles/{id}") + public void deleteRole(@PathParam("id") Long roleId, @Context HttpServletRequest request) { + roleREST.deleteRole(roleId); + } + + /* + * APIs to Access Roles + */ + @GET + @Path("/api/roles/name/{name}") + @Produces("application/json") + public RangerRole getRole(@QueryParam("serviceName") String serviceName, @QueryParam("execUser") String userName, @PathParam("name") String roleName, @Context HttpServletRequest request) { + return roleREST.getRole(serviceName, userName, roleName); + } + + @GET + @Path("/api/roles/{id}") + @Produces("application/json") + public RangerRole getRole(@PathParam("id") Long id, @Context HttpServletRequest request) { + return roleREST.getRole(id); + } + + @GET + @Path("/api/roles") + @Produces("application/json") + public List getAllRoles(@Context HttpServletRequest request) { + return roleREST.getAllRoles(request).getSecurityRoles(); + } + + @GET + @Path("/api/roles/names") + @Produces("application/json") + public List getAllRoleNames(@QueryParam("serviceName") String serviceName, @QueryParam("execUser") String userName, @Context HttpServletRequest request) { + return roleREST.getAllRoleNames(serviceName, userName, request); + } + + @GET + @Path("/api/roles/user/{user}") + @Produces("application/json") + public List getUserRoles(@PathParam("user") String userName, @Context HttpServletRequest request) { + return roleREST.getUserRoles(userName, request); + } + + /* + This API is used to add users and groups with/without GRANT privileges to this Role. It follows add-or-update semantics + */ + @PUT + @Path("/api/roles/{id}/addUsersAndGroups") + @Consumes("application/json") + @Produces("application/json") + public RangerRole addUsersAndGroups(@PathParam("id") Long roleId, List users, List groups, Boolean isAdmin, @Context HttpServletRequest request) { + return roleREST.addUsersAndGroups(roleId, users, groups, isAdmin); + } + + /* This API is used to remove users and groups, without regard to their GRANT privilege, from this Role. */ - @PUT - @Path("/api/roles/{id}/removeUsersAndGroups") - @Consumes({ "application/json" }) - @Produces({ "application/json" }) - public RangerRole removeUsersAndGroups(@PathParam("id") Long roleId, List users, List groups, @Context HttpServletRequest request) { - return roleREST.removeUsersAndGroups(roleId, users, groups); - } - - /* + @PUT + @Path("/api/roles/{id}/removeUsersAndGroups") + @Consumes("application/json") + @Produces("application/json") + public RangerRole removeUsersAndGroups(@PathParam("id") Long roleId, List users, List groups, @Context HttpServletRequest request) { + return roleREST.removeUsersAndGroups(roleId, users, groups); + } + + /* This API is used to remove GRANT privilege from listed users and groups. */ - @PUT - @Path("/api/roles/{id}/removeAdminFromUsersAndGroups") - @Consumes({ "application/json" }) - @Produces({ "application/json" }) - public RangerRole removeAdminFromUsersAndGroups(@PathParam("id") Long roleId, List users, List groups, @Context HttpServletRequest request) { - return roleREST.removeAdminFromUsersAndGroups(roleId, users, groups); - } - - /* - This API is used to add users and roles with/without GRANT privileges to this Role. It follows add-or-update semantics - */ - @PUT - @Path("/api/roles/grant/{serviceName}") - @Consumes({ "application/json" }) - @Produces({ "application/json" }) - public RESTResponse grantRole(@PathParam("serviceName") String serviceName, GrantRevokeRoleRequest grantRoleRequest, @Context HttpServletRequest request) { - if(logger.isDebugEnabled()) { - logger.debug("==> PublicAPIsv2.grantRoleUsersAndRoles(" + grantRoleRequest.toString() + ")"); - } - return roleREST.grantRole(serviceName, grantRoleRequest, request); - } - - /* + @PUT + @Path("/api/roles/{id}/removeAdminFromUsersAndGroups") + @Consumes("application/json") + @Produces("application/json") + public RangerRole removeAdminFromUsersAndGroups(@PathParam("id") Long roleId, List users, List groups, @Context HttpServletRequest request) { + return roleREST.removeAdminFromUsersAndGroups(roleId, users, groups); + } + + /* + This API is used to add users and roles with/without GRANT privileges to this Role. It follows add-or-update semantics + */ + @PUT + @Path("/api/roles/grant/{serviceName}") + @Consumes("application/json") + @Produces("application/json") + public RESTResponse grantRole(@PathParam("serviceName") String serviceName, GrantRevokeRoleRequest grantRoleRequest, @Context HttpServletRequest request) { + logger.debug("==> PublicAPIsv2.grantRoleUsersAndRoles({})", grantRoleRequest); + + return roleREST.grantRole(serviceName, grantRoleRequest, request); + } + + /* This API is used to remove users and groups, without regard to their GRANT privilege, from this Role. */ - @PUT - @Path("/api/roles/revoke/{serviceName}") - @Consumes({ "application/json" }) - @Produces({ "application/json" }) - public RESTResponse revokeRoleUsersAndRoles(@PathParam("serviceName") String serviceName, GrantRevokeRoleRequest revokeRoleRequest, @Context HttpServletRequest request) { - return roleREST.revokeRole(serviceName, revokeRoleRequest, request); - } - - @DELETE - @Path("/api/server/purge/records") - @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") - public List purgeRecords(@QueryParam("type") String recordType, @DefaultValue("180") @QueryParam("retentionDays") Integer olderThan, @Context HttpServletRequest request) { - if (logger.isDebugEnabled()) { - logger.debug("==> PublicAPIsv2.purgeRecords(" + recordType + ", " + olderThan + ")"); - } - - List ret = serviceREST.purgeRecords(recordType, olderThan, request); - - if (logger.isDebugEnabled()) { - logger.debug("<== PublicAPIsv2.purgeRecords(" + recordType + ", " + olderThan + "): ret=" + ret); - } - - return ret; - } + @PUT + @Path("/api/roles/revoke/{serviceName}") + @Consumes("application/json") + @Produces("application/json") + public RESTResponse revokeRoleUsersAndRoles(@PathParam("serviceName") String serviceName, GrantRevokeRoleRequest revokeRoleRequest, @Context HttpServletRequest request) { + return roleREST.revokeRole(serviceName, revokeRoleRequest, request); + } + + @DELETE + @Path("/api/server/purge/records") + @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") + public List purgeRecords(@QueryParam("type") String recordType, @DefaultValue("180") @QueryParam("retentionDays") Integer olderThan, @Context HttpServletRequest request) { + logger.debug("==> PublicAPIsv2.purgeRecords({}, {})", recordType, olderThan); + + List ret = serviceREST.purgeRecords(recordType, olderThan, request); + + logger.debug("<== PublicAPIsv2.purgeRecords({}, {}): ret={}", recordType, olderThan, ret); + + return ret; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/rest/RangerHealthREST.java b/security-admin/src/main/java/org/apache/ranger/rest/RangerHealthREST.java index c982a9e8d5..2798866e95 100644 --- a/security-admin/src/main/java/org/apache/ranger/rest/RangerHealthREST.java +++ b/security-admin/src/main/java/org/apache/ranger/rest/RangerHealthREST.java @@ -19,9 +19,6 @@ package org.apache.ranger.rest; -import javax.ws.rs.GET; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; import org.apache.ranger.biz.RangerBizUtil; import org.apache.ranger.plugin.model.RangerServerHealth; import org.apache.ranger.util.RangerServerHealthUtil; @@ -31,6 +28,10 @@ import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; + @Path("actuator") @Component @Scope("request") @@ -46,11 +47,11 @@ public class RangerHealthREST { */ @GET @Path("/health") - @Produces({"application/json"}) + @Produces("application/json") @Transactional(propagation = Propagation.NOT_SUPPORTED) public RangerServerHealth getRangerServerHealth() { - String dbVersion = xaBizUtil.getDBVersion(); + String dbVersion = xaBizUtil.getDBVersion(); return rangerServerHealthUtil.getRangerServerHealth(dbVersion); } -} \ No newline at end of file +} diff --git a/security-admin/src/main/java/org/apache/ranger/rest/RoleREST.java b/security-admin/src/main/java/org/apache/ranger/rest/RoleREST.java index d8e30b516a..3a80595da7 100644 --- a/security-admin/src/main/java/org/apache/ranger/rest/RoleREST.java +++ b/security-admin/src/main/java/org/apache/ranger/rest/RoleREST.java @@ -19,24 +19,11 @@ package org.apache.ranger.rest; -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Set; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.ws.rs.*; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.MediaType; - -import org.apache.commons.lang.StringUtils; +import com.sun.jersey.core.header.FormDataContentDisposition; +import com.sun.jersey.multipart.FormDataParam; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.io.IOUtils; +import org.apache.commons.lang.StringUtils; import org.apache.ranger.admin.client.datatype.RESTResponse; import org.apache.ranger.authorization.utils.StringUtil; import org.apache.ranger.biz.AssetMgr; @@ -45,15 +32,15 @@ import org.apache.ranger.biz.ServiceDBStore; import org.apache.ranger.biz.ServiceDBStore.JSON_FILE_NAME_TYPE; import org.apache.ranger.biz.XUserMgr; +import org.apache.ranger.common.AppConstants; +import org.apache.ranger.common.ContextUtil; +import org.apache.ranger.common.MessageEnums; +import org.apache.ranger.common.PropertiesUtil; import org.apache.ranger.common.RESTErrorUtil; import org.apache.ranger.common.RangerSearchUtil; import org.apache.ranger.common.RangerValidatorFactory; import org.apache.ranger.common.ServiceUtil; import org.apache.ranger.common.UserSessionBase; -import org.apache.ranger.common.PropertiesUtil; -import org.apache.ranger.common.AppConstants; -import org.apache.ranger.common.ContextUtil; -import org.apache.ranger.common.MessageEnums; import org.apache.ranger.db.RangerDaoManager; import org.apache.ranger.entity.XXService; import org.apache.ranger.entity.XXServiceDef; @@ -85,8 +72,30 @@ import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; -import com.sun.jersey.multipart.FormDataParam; -import com.sun.jersey.core.header.FormDataContentDisposition; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.DefaultValue; +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.WebApplicationException; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; + +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Set; @Path("roles") @Component @@ -95,12 +104,12 @@ public class RoleREST { private static final Logger LOG = LoggerFactory.getLogger(RoleREST.class); - private static List INVALID_USERS = new ArrayList<>(); - - public static final String POLICY_DOWNLOAD_USERS = "policy.download.auth.users"; - public static final String PARAM_ROLE_NAME = "roleName"; + public static final String POLICY_DOWNLOAD_USERS = "policy.download.auth.users"; + public static final String PARAM_ROLE_NAME = "roleName"; public static final String PARAM_IMPORT_IN_PROGRESS = "importInProgress"; + private static final List INVALID_USERS = new ArrayList<>(); + @Autowired RESTErrorUtil restErrorUtil; @@ -137,224 +146,242 @@ public class RoleREST { @Autowired XUserMgr userMgr; - static { - INVALID_USERS.add(RangerPolicyEngine.USER_CURRENT); - INVALID_USERS.add(RangerPolicyEngine.RESOURCE_OWNER); - } - - /* This operation is allowed only when effective User has ranger admin privilege - * if execUser is not same as logged-in user then effective user is execUser - * else effective user is logged-in user. - * This logic is implemented as part of ensureAdminAccess(String serviceName, String userName); - */ - @POST @Path("/roles") - @Consumes({ "application/json" }) - @Produces({ "application/json" }) - public RangerRole createRole(@QueryParam("serviceName") String serviceName, RangerRole role - , @DefaultValue("false") @QueryParam("createNonExistUserGroup") Boolean createNonExistUserGroup - ) { - if (LOG.isDebugEnabled()) { - LOG.debug("==> createRole("+ role + ")"); - } + @Consumes("application/json") + @Produces("application/json") + public RangerRole createRole(@QueryParam("serviceName") String serviceName, RangerRole role, @DefaultValue("false") @QueryParam("createNonExistUserGroup") Boolean createNonExistUserGroup) { + LOG.debug("==> createRole({})", role); RangerRole ret; + try { RangerRoleValidator validator = validatorFactory.getRangerRoleValidator(roleStore); + validator.validate(role, RangerValidator.Action.CREATE); String userName = role.getCreatedByUser(); + ensureAdminAccess(serviceName, userName); + if (containsInvalidMember(role.getUsers())) { throw new Exception("Invalid role user(s)"); } + ret = roleStore.createRole(role, createNonExistUserGroup); - } catch(WebApplicationException excp) { + } catch (WebApplicationException excp) { throw excp; - } catch(Throwable excp) { - LOG.error("createRole(" + role + ") failed", excp); + } catch (Throwable excp) { + LOG.error("createRole({}) failed", role, excp); throw restErrorUtil.createRESTException(excp.getMessage()); } - if (LOG.isDebugEnabled()) { - LOG.debug("<== createRole("+ role + "):" + ret); - } + + LOG.debug("<== createRole({}): {}", role, ret); + return ret; } - /* This operation is allowed only when - - * Logged in user has ranger admin role + /* This operation is allowed only when effective User has ranger admin privilege + * if execUser is not same as logged-in user then effective user is execUser + * else effective user is logged-in user. + * This logic is implemented as part of ensureAdminAccess(String serviceName, String userName); */ @PUT @Path("/roles/{id}") - @Consumes({ "application/json" }) - @Produces({ "application/json" }) - public RangerRole updateRole(@PathParam("id") Long roleId - , RangerRole role - , @DefaultValue("false") @QueryParam("createNonExistUserGroup") Boolean createNonExistUserGroup - ) { - if (LOG.isDebugEnabled()) { - LOG.debug("==> updateRole(id=" + roleId +", " + role + ")"); - } + @Consumes("application/json") + @Produces("application/json") + public RangerRole updateRole(@PathParam("id") Long roleId, RangerRole role, @DefaultValue("false") @QueryParam("createNonExistUserGroup") Boolean createNonExistUserGroup) { + LOG.debug("==> updateRole(id={}, role={})", roleId, role); if (role.getId() != null && !roleId.equals(role.getId())) { throw restErrorUtil.createRESTException("roleId mismatch!!"); } else { role.setId(roleId); } + RangerRole ret; + try { UserSessionBase usb = ContextUtil.getCurrentUserSession(); String loggedInUser = usb != null ? usb.getLoginId() : null; RangerRole existingRole = getRole(roleId); if (!bizUtil.isUserRangerAdmin(loggedInUser) && !ensureRoleAccess(loggedInUser, userMgr.getGroupsForUser(loggedInUser), existingRole)) { - LOG.error("User " + loggedInUser + " does not have permission for this operation"); + LOG.error("User {} does not have permission for this operation", loggedInUser); throw new Exception("User does not have permission for this operation"); } RangerRoleValidator validator = validatorFactory.getRangerRoleValidator(roleStore); + validator.validate(role, RangerValidator.Action.UPDATE); if (containsInvalidMember(role.getUsers())) { throw new Exception("Invalid role user(s)"); } + ret = roleStore.updateRole(role, createNonExistUserGroup); - } catch(WebApplicationException excp) { + } catch (WebApplicationException excp) { throw excp; - } catch(Throwable excp) { - LOG.error("updateRole(" + role + ") failed", excp); + } catch (Throwable excp) { + LOG.error("updateRole({}) failed", role, excp); throw restErrorUtil.createRESTException(excp.getMessage()); } - if (LOG.isDebugEnabled()) { - LOG.debug("<== updateRole(id=" + roleId +", " + role + "):" + ret); - } + + LOG.debug("<== updateRole(id={}, role={}) => ret:{}", roleId, role, ret); + return ret; } - /* This operation is allowed only when effective User has ranger admin privilege - * if execUser is not same as logged-in user then effective user is execUser - * else effective user is logged-in user. - * This logic is implemented as part of ensureAdminAccess(String serviceName, String userName); + /* This operation is allowed only when - + * Logged in user has ranger admin role */ @DELETE @Path("/roles/name/{name}") public void deleteRole(@QueryParam("serviceName") String serviceName, @QueryParam("execUser") String execUser, @PathParam("name") String roleName) { - if (LOG.isDebugEnabled()) { - LOG.debug("==> deleteRole(user=" + execUser + " name=" + roleName + ")"); - } + LOG.debug("==> deleteRole(user={}, name={})", execUser, roleName); + try { RangerRoleValidator validator = validatorFactory.getRangerRoleValidator(roleStore); + validator.validate(roleName, RangerRoleValidator.Action.DELETE); ensureAdminAccess(serviceName, execUser); + roleStore.deleteRole(roleName); - } catch(WebApplicationException excp) { + } catch (WebApplicationException excp) { throw excp; - } catch(Throwable excp) { - LOG.error("deleteRole(" + roleName + ") failed", excp); + } catch (Throwable excp) { + LOG.error("deleteRole({}) failed", roleName, excp); throw restErrorUtil.createRESTException(excp.getMessage()); } - if (LOG.isDebugEnabled()) { - LOG.debug("<== deleteRole(name=" + roleName + ")"); - } + + LOG.debug("<== deleteRole(name={})", roleName); } - /* This operation is allowed only when - - * Logged in user has ranger admin role + /* This operation is allowed only when effective User has ranger admin privilege + * if execUser is not same as logged-in user then effective user is execUser + * else effective user is logged-in user. + * This logic is implemented as part of ensureAdminAccess(String serviceName, String userName); */ @DELETE @Path("/roles/{id}") public void deleteRole(@PathParam("id") Long roleId) { - if (LOG.isDebugEnabled()) { - LOG.debug("==> deleteRole(id=" + roleId + ")"); - } + LOG.debug("==> deleteRole(id={})", roleId); + try { RangerRoleValidator validator = validatorFactory.getRangerRoleValidator(roleStore); + validator.validate(roleId, RangerRoleValidator.Action.DELETE); ensureAdminAccess(null, null); + roleStore.deleteRole(roleId); - } catch(WebApplicationException excp) { + } catch (WebApplicationException excp) { throw excp; - } catch(Throwable excp) { - LOG.error("deleteRole(" + roleId + ") failed", excp); + } catch (Throwable excp) { + LOG.error("deleteRole({}) failed", roleId, excp); if (excp.getMessage().contains(String.valueOf(ValidationErrorCode.ROLE_VALIDATION_ERR_INVALID_ROLE_ID.getErrorCode()))) { - throw restErrorUtil.createRESTException( - "Data Not Found for given Id", - MessageEnums.DATA_NOT_FOUND, roleId, null, - "readResource : No Object found with given id."); + throw restErrorUtil.createRESTException("Data Not Found for given Id", MessageEnums.DATA_NOT_FOUND, roleId, null, "readResource : No Object found with given id."); } else { throw restErrorUtil.createRESTException(excp.getMessage()); } } - if (LOG.isDebugEnabled()) { - LOG.debug("<== deleteRole(id=" + roleId + ")"); - } + + LOG.debug("<== deleteRole(id={})", roleId); } - /* - * Minimum required privilege is the effective user has admin option for this role. - * This is used to list all the roles, groups, and users who belong to this role. + /* This operation is allowed only when - + * Logged in user has ranger admin role */ @GET @Path("/roles/name/{name}") - @Produces({ "application/json" }) + @Produces("application/json") public RangerRole getRole(@QueryParam("serviceName") String serviceName, @QueryParam("execUser") String execUser, @PathParam("name") String roleName) { - if (LOG.isDebugEnabled()) { - LOG.debug("==> getRole(name=" + roleName + ", execUser=" + execUser + ")"); - } + LOG.debug("==> getRole(name={}, execUser={})", roleName, execUser); + RangerRole ret; try { Set userGroups = StringUtils.isNotEmpty(execUser) ? userMgr.getGroupsForUser(execUser) : new HashSet<>(); ret = getRoleIfAccessible(roleName, serviceName, execUser, userGroups); + if (ret == null) { throw restErrorUtil.createRESTException("User doesn't have permissions to get details for " + roleName); } - - } catch(WebApplicationException excp) { + } catch (WebApplicationException excp) { throw excp; - } catch(Throwable excp) { - LOG.error("getRole(name=" + roleName + ", execUser=" + execUser + ") failed", excp); + } catch (Throwable excp) { + LOG.error("getRole(name={}, execUser={}) failed", roleName, execUser, excp); + throw restErrorUtil.createRESTException(excp.getMessage()); } - if (LOG.isDebugEnabled()) { - LOG.debug("<== getRole(name=" + roleName + ", execUser=" + execUser + "):" + ret); - } + + LOG.debug("<== getRole(name={}, execUser={}):{}", roleName, execUser, ret); + return ret; } + /* + * Minimum required privilege is the effective user has admin option for this role. + * This is used to list all the roles, groups, and users who belong to this role. + */ + @GET @Path("/roles/{id}") - @Produces({ "application/json" }) + @Produces("application/json") public RangerRole getRole(@PathParam("id") Long id) { - if (LOG.isDebugEnabled()) { - LOG.debug("==> getRole(id=" + id + ")"); - } + LOG.debug("==> getRole(id={})", id); + RangerRole ret; + try { ret = roleStore.getRole(id); - } catch(WebApplicationException excp) { + } catch (WebApplicationException excp) { throw excp; - } catch(Throwable excp) { - LOG.error("getRole(" + id + ") failed", excp); + } catch (Throwable excp) { + LOG.error("getRole({}) failed", id, excp); throw restErrorUtil.createRESTException(excp.getMessage()); } - if (LOG.isDebugEnabled()) { - LOG.debug("<== getRole(id=" + id + "):" + ret); + + LOG.debug("<== getRole(id={}):{}", id, ret); + + return ret; + } + + @GET + @Path("/roles") + @Produces("application/json") + public RangerRoleList getAllRoles(@Context HttpServletRequest request) { + LOG.debug("==> getAllRoles()"); + + RangerRoleList ret = new RangerRoleList(); + SearchFilter filter = searchUtil.getSearchFilter(request, roleService.sortFields); + + try { + ensureAdminAccess(null, null); + + roleStore.getRoles(filter, ret); + } catch (WebApplicationException excp) { + throw excp; + } catch (Throwable excp) { + LOG.error("getRoles() failed", excp); + + throw restErrorUtil.createRESTException(excp.getMessage()); } + + LOG.debug("<== getAllRoles():{}", ret); + return ret; } @@ -365,271 +392,242 @@ public RangerRole getRole(@PathParam("id") Long id) { */ @GET - @Path("/roles") - @Produces({ "application/json" }) - public RangerRoleList getAllRoles(@Context HttpServletRequest request) { - RangerRoleList ret = new RangerRoleList(); - if (LOG.isDebugEnabled()) { - LOG.debug("==> getAllRoles()"); - } - SearchFilter filter = searchUtil.getSearchFilter(request, roleService.sortFields); + @Path("/roles/exportJson") + @Produces("application/json") + @PreAuthorize("@rangerPreAuthSecurityHandler.isAdminRole()") + public void getRolesInJson(@Context HttpServletRequest request, @Context HttpServletResponse response) { + LOG.debug("==> getRolesInJson()"); + try { - ensureAdminAccess(null, null); - roleStore.getRoles(filter,ret); - } catch(WebApplicationException excp) { + List roleLists = getAllFilteredRoleList(request); + + if (CollectionUtils.isNotEmpty(roleLists)) { + svcStore.getObjectInJson(roleLists, response, JSON_FILE_NAME_TYPE.ROLE); + } else { + response.setStatus(HttpServletResponse.SC_NO_CONTENT); + + LOG.error("There is no Role to Export!!"); + } + } catch (WebApplicationException excp) { throw excp; - } catch(Throwable excp) { - LOG.error("getRoles() failed", excp); + } catch (Throwable excp) { + LOG.error("Error while exporting policy file!!", excp); throw restErrorUtil.createRESTException(excp.getMessage()); } - if (LOG.isDebugEnabled()) { - LOG.debug("<== getAllRoles():" + ret); + + LOG.debug("<== getRolesInJson()"); + } + + @POST + @Path("/roles/importRolesFromFile") + @Consumes({MediaType.MULTIPART_FORM_DATA, MediaType.APPLICATION_JSON}) + @Produces({"application/json", "application/xml"}) + @PreAuthorize("@rangerPreAuthSecurityHandler.isAdminRole()") + public RESTResponse importRolesFromFile(@Context HttpServletRequest request, @FormDataParam("file") InputStream uploadedInputStream, @FormDataParam("file") FormDataContentDisposition fileDetail, @QueryParam("updateIfExists") Boolean updateIfExists, @DefaultValue("false") @QueryParam("createNonExistUserGroupRole") Boolean createNonExistUserGroupRole) { + LOG.debug("==> RoleREST.importRolesFromFile()"); + + RESTResponse ret = new RESTResponse(); + String metaDataInfo = null; + + RangerContextHolder.getOrCreateOpContext().setBulkModeContext(true); + + request.setAttribute(PARAM_IMPORT_IN_PROGRESS, true); + + try { + roleService.createTransactionLog(new XXTrxLogV2(AppConstants.CLASS_TYPE_RANGER_ROLE, null, null, "IMPORT START"), "Import", "IMPORT START", null); + + if (updateIfExists == null) { + updateIfExists = false; + } + + List roleNameList = getRoleNameList(request, new ArrayList<>()); + String fileName = fileDetail.getFileName(); + int totalRoleCreate = 0; + int totalRoleUpdate = 0; + int totalRoleUnchange = 0; + String msg; + + if (fileName.endsWith("json")) { + try { + RangerExportRoleList rangerExportRoleList = processRoleInputJsonForMetaData(uploadedInputStream, null); + + if (rangerExportRoleList != null && !CollectionUtils.sizeIsEmpty(rangerExportRoleList.getMetaDataInfo())) { + metaDataInfo = JsonUtilsV2.mapToJson(rangerExportRoleList.getMetaDataInfo()); + } else { + LOG.info("metadata info is not provided!!"); + } + + List roles = getRolesFromProvidedJson(rangerExportRoleList); + + if (roles != null && !CollectionUtils.sizeIsEmpty(roles)) { + for (RangerRole roleInJson : roles) { + if (roleInJson != null && StringUtils.isNotEmpty(roleInJson.getName().trim())) { + String roleNameInJson = roleInJson.getName().trim(); + + if (CollectionUtils.isNotEmpty(roleNameList) && roleNameList.contains(roleNameInJson)) { + // check updateIfExists + if (updateIfExists) { + try { + RangerRole exitingRole = roleStore.getRole(roleNameInJson); + + if (!exitingRole.getId().equals(roleInJson.getId())) { + roleInJson.setId(exitingRole.getId()); + } + + if (exitingRole.equals(roleInJson)) { + totalRoleUnchange++; + + LOG.debug("Ignoring Roles from provided role in Json file... {}", roleNameInJson); + } else { + roleStore.updateRole(roleInJson, createNonExistUserGroupRole); + + totalRoleUpdate++; + } + } catch (WebApplicationException excp) { + throw excp; + } catch (Throwable excp) { + LOG.error("updateRole({}) failed", roleInJson, excp); + + throw restErrorUtil.createRESTException(excp.getMessage()); + } + } else { + totalRoleUnchange++; + + LOG.debug("Ignoring Roles from provided role in Json file... {}", roleNameInJson); + } + + ret.setStatusCode(RESTResponse.STATUS_SUCCESS); + } else if (!roleNameList.contains(roleNameInJson) && (!roleNameInJson.isEmpty())) { + try { + roleStore.createRole(roleInJson, createNonExistUserGroupRole); + } catch (WebApplicationException excp) { + throw excp; + } catch (Throwable excp) { + LOG.error("createRole({}) failed", roleInJson, excp); + + throw restErrorUtil.createRESTException(excp.getMessage()); + } + + totalRoleCreate++; + + ret.setStatusCode(RESTResponse.STATUS_SUCCESS); + } + } + } + } else { + LOG.error("Json File does not contain any role."); + + throw restErrorUtil.createRESTException("Json File does not contain any role."); + } + + if (updateIfExists) { + msg = "Total Role Created = " + totalRoleCreate + " , Total Role Updated = " + totalRoleUpdate + " , Total Role Unchanged = " + totalRoleUnchange; + + ret.setMsgDesc(msg); + } else { + msg = "Total Role Created = " + totalRoleCreate + " , Total Role Unchanged = " + totalRoleUnchange; + + ret.setMsgDesc(msg); + } + } catch (IOException e) { + LOG.error(e.getMessage()); + + throw restErrorUtil.createRESTException(e.getMessage()); + } + } else { + LOG.error("Provided file format is not supported!!"); + + throw restErrorUtil.createRESTException("Provided file format is not supported!!"); + } + } catch (WebApplicationException excp) { + LOG.error("Error while importing role from file!!", excp); + + roleService.createTransactionLog(new XXTrxLogV2(AppConstants.CLASS_TYPE_RANGER_ROLE, null, null, "IMPORT ERROR"), "Import failed", StringUtils.isNotEmpty(metaDataInfo) ? metaDataInfo : null, null); + + throw excp; + } catch (Throwable excp) { + LOG.error("Error while importing role from file!!", excp); + + roleService.createTransactionLog(new XXTrxLogV2(AppConstants.CLASS_TYPE_RANGER_ROLE, null, null, "IMPORT ERROR"), "Import failed", StringUtils.isNotEmpty(metaDataInfo) ? metaDataInfo : null, null); + + throw restErrorUtil.createRESTException(excp.getMessage()); + } finally { + roleService.createTransactionLog(new XXTrxLogV2(AppConstants.CLASS_TYPE_RANGER_ROLE, null, null, "IMPORT END"), "IMPORT END", StringUtils.isNotEmpty(metaDataInfo) ? metaDataInfo : null, null); + + LOG.debug("<== RoleREST.importRolesFromFile()"); } + return ret; } - @GET - @Path("/roles/exportJson") - @Produces({ "application/json" }) - @PreAuthorize("@rangerPreAuthSecurityHandler.isAdminRole()") - public void getRolesInJson(@Context HttpServletRequest request, @Context HttpServletResponse response) { - if (LOG.isDebugEnabled()) { - LOG.debug("==> getRolesInJson()"); - } - try { - List roleLists = getAllFilteredRoleList(request); - - if (CollectionUtils.isNotEmpty(roleLists)) { - svcStore.getObjectInJson(roleLists, response, JSON_FILE_NAME_TYPE.ROLE); - } else { - response.setStatus(HttpServletResponse.SC_NO_CONTENT); - LOG.error("There is no Role to Export!!"); - } - - } catch (WebApplicationException excp) { - throw excp; - } catch (Throwable excp) { - LOG.error("Error while exporting policy file!!", excp); - throw restErrorUtil.createRESTException(excp.getMessage()); - } - if (LOG.isDebugEnabled()) { - LOG.debug("<== getRolesInJson()"); - } - } - - @POST - @Path("/roles/importRolesFromFile") - @Consumes({ MediaType.MULTIPART_FORM_DATA, MediaType.APPLICATION_JSON }) - @Produces({ "application/json", "application/xml" }) - @PreAuthorize("@rangerPreAuthSecurityHandler.isAdminRole()") - public RESTResponse importRolesFromFile(@Context HttpServletRequest request, - @FormDataParam("file") InputStream uploadedInputStream, - @FormDataParam("file") FormDataContentDisposition fileDetail, - @QueryParam("updateIfExists") Boolean updateIfExists, - @DefaultValue("false") @QueryParam("createNonExistUserGroupRole") Boolean createNonExistUserGroupRole) { - if (LOG.isDebugEnabled()) { - LOG.debug("==> RoleREST.importRolesFromFile()"); - } - RESTResponse ret = new RESTResponse(); - - RangerContextHolder.getOrCreateOpContext().setBulkModeContext(true); - - String metaDataInfo = null; - request.setAttribute(PARAM_IMPORT_IN_PROGRESS, true); - - try { - roleService.createTransactionLog(new XXTrxLogV2(AppConstants.CLASS_TYPE_RANGER_ROLE, null, null, "IMPORT START"), "Import", "IMPORT START", null); - - if (updateIfExists == null) { - updateIfExists = false; - } - List roleNameList = new ArrayList(); - - roleNameList = getRoleNameList(request, roleNameList); - - String fileName = fileDetail.getFileName(); - int totalRoleCreate = 0; - int totalRoleUpdate = 0; - int totalRoleUnchange = 0; - String msg; - - if (fileName.endsWith("json")) { - try { - RangerExportRoleList rangerExportRoleList = null; - List roles = null; - rangerExportRoleList = processRoleInputJsonForMetaData(uploadedInputStream, rangerExportRoleList); - - if (rangerExportRoleList != null - && !CollectionUtils.sizeIsEmpty(rangerExportRoleList.getMetaDataInfo())) { - metaDataInfo = JsonUtilsV2.mapToJson(rangerExportRoleList.getMetaDataInfo()); - } else { - LOG.info("metadata info is not provided!!"); - } - roles = getRolesFromProvidedJson(rangerExportRoleList); - - if (roles != null && !CollectionUtils.sizeIsEmpty(roles)) { - for (RangerRole roleInJson : roles) { - - if (roleInJson != null && StringUtils.isNotEmpty(roleInJson.getName().trim())) { - String roleNameInJson = roleInJson.getName().trim(); - if (CollectionUtils.isNotEmpty(roleNameList) && roleNameList.contains(roleNameInJson)) { - - // check updateIfExists - if (updateIfExists) { - try { - RangerRole exitingRole = roleStore.getRole(roleNameInJson); - if (!exitingRole.getId().equals(roleInJson.getId())) { - roleInJson.setId(exitingRole.getId()); - } - if(exitingRole.equals(roleInJson)){ - totalRoleUnchange++; - if (LOG.isDebugEnabled()) { - LOG.debug("Ignoring Roles from provided role in Json file... "+ roleNameInJson); - } - } - else { - roleStore.updateRole(roleInJson, createNonExistUserGroupRole); - totalRoleUpdate++; - } - } catch (WebApplicationException excp) { - throw excp; - } catch (Throwable excp) { - LOG.error("updateRole(" + roleInJson + ") failed", excp); - - throw restErrorUtil.createRESTException(excp.getMessage()); - } - } else { - totalRoleUnchange++; - if (LOG.isDebugEnabled()) { - LOG.debug("Ignoring Roles from provided role in Json file... " + roleNameInJson); - } - } - ret.setStatusCode(RESTResponse.STATUS_SUCCESS); - } else if (!roleNameList.contains(roleNameInJson) && (!roleNameInJson.isEmpty())) { - try { - roleStore.createRole(roleInJson, createNonExistUserGroupRole); - } catch (WebApplicationException excp) { - throw excp; - } catch (Throwable excp) { - LOG.error("createRole(" + roleInJson + ") failed", excp); - - throw restErrorUtil.createRESTException(excp.getMessage()); - } - totalRoleCreate++; - ret.setStatusCode(RESTResponse.STATUS_SUCCESS); - } - } - } - } else { - LOG.error("Json File does not contain any role."); - throw restErrorUtil.createRESTException("Json File does not contain any role."); - } - if (updateIfExists) { - msg = "Total Role Created = " + totalRoleCreate + " , Total Role Updated = " + totalRoleUpdate + " , Total Role Unchanged = " + totalRoleUnchange; - ret.setMsgDesc(msg); - } else { - msg = "Total Role Created = " + totalRoleCreate + " , Total Role Unchanged = " + totalRoleUnchange; - ret.setMsgDesc(msg); - } - - } catch (IOException e) { - LOG.error(e.getMessage()); - throw restErrorUtil.createRESTException(e.getMessage()); - } - } else { - LOG.error("Provided file format is not supported!!"); - throw restErrorUtil.createRESTException("Provided file format is not supported!!"); - } - } catch (WebApplicationException excp) { - LOG.error("Error while importing role from file!!", excp); - - roleService.createTransactionLog(new XXTrxLogV2(AppConstants.CLASS_TYPE_RANGER_ROLE, null, null, "IMPORT ERROR"), "Import failed", StringUtils.isNotEmpty(metaDataInfo) ? metaDataInfo : null, null); - - throw excp; - } catch (Throwable excp) { - LOG.error("Error while importing role from file!!", excp); - - roleService.createTransactionLog(new XXTrxLogV2(AppConstants.CLASS_TYPE_RANGER_ROLE, null, null, "IMPORT ERROR"), "Import failed", StringUtils.isNotEmpty(metaDataInfo) ? metaDataInfo : null, null); - - throw restErrorUtil.createRESTException(excp.getMessage()); - } finally { - roleService.createTransactionLog(new XXTrxLogV2(AppConstants.CLASS_TYPE_RANGER_ROLE, null, null, "IMPORT END"), "IMPORT END", StringUtils.isNotEmpty(metaDataInfo) ? metaDataInfo : null, null); - - if (LOG.isDebugEnabled()) { - LOG.debug("<== RoleREST.importRolesFromFile()"); - } - } - - return ret; - } - @GET @Path("/lookup/roles") - @Produces({ "application/json" }) + @Produces("application/json") public RangerRoleList getAllRolesForUser(@Context HttpServletRequest request) { - RangerRoleList ret = new RangerRoleList(); - if (LOG.isDebugEnabled()) { - LOG.debug("==> getAllRolesForUser()"); - } - SearchFilter filter = searchUtil.getSearchFilter(request, roleService.sortFields); + LOG.debug("==> getAllRolesForUser()"); + + RangerRoleList ret = new RangerRoleList(); + SearchFilter filter = searchUtil.getSearchFilter(request, roleService.sortFields); + try { - roleStore.getRolesForUser(filter,ret); - } catch(WebApplicationException excp) { + roleStore.getRolesForUser(filter, ret); + } catch (WebApplicationException excp) { throw excp; - } catch(Throwable excp) { + } catch (Throwable excp) { LOG.error("getRoles() failed", excp); throw restErrorUtil.createRESTException(excp.getMessage()); } - if (LOG.isDebugEnabled()) { - LOG.debug("<== getAllRoles():" + ret); - } + + LOG.debug("<== getAllRoles():{}", ret); + return ret; } - /* This operation is allowed only when effective User has ranger admin privilege - * if execUser is not same as logged-in user then effective user is execUser - * else effective user is logged-in user. - * This logic is implemented as part of ensureAdminAccess(String serviceName, String userName); - */ - @GET @Path("/roles/names") - @Produces({ "application/json" }) + @Produces("application/json") public List getAllRoleNames(@QueryParam("serviceName") String serviceName, @QueryParam("execUser") String userName, @Context HttpServletRequest request) { final List ret; - if (LOG.isDebugEnabled()) { - LOG.debug("==> getAllRoleNames()"); - } + + LOG.debug("==> getAllRoleNames()"); + SearchFilter filter = searchUtil.getSearchFilter(request, roleService.sortFields); + try { ensureAdminAccess(serviceName, userName); - ret = roleStore.getRoleNames(filter); - } catch(WebApplicationException excp) { + ret = roleStore.getRoleNames(filter); + } catch (WebApplicationException excp) { throw excp; - } catch(Throwable excp) { + } catch (Throwable excp) { LOG.error("getAllRoleNames() failed", excp); throw restErrorUtil.createRESTException(excp.getMessage()); } - if (LOG.isDebugEnabled()) { - LOG.debug("<== getAllRoleNames():" + ret); - } + + LOG.debug("<== getAllRoleNames():{}", ret); + return ret; } + /* This operation is allowed only when effective User has ranger admin privilege + * if execUser is not same as logged-in user then effective user is execUser + * else effective user is logged-in user. + * This logic is implemented as part of ensureAdminAccess(String serviceName, String userName); + */ + /* This API is used to add users and groups with/without GRANT privileges to this Role. It follows add-or-update semantics */ @PUT @Path("/roles/{id}/addUsersAndGroups") - @Consumes({ "application/json" }) - @Produces({ "application/json" }) + @Consumes("application/json") + @Produces("application/json") public RangerRole addUsersAndGroups(@PathParam("id") Long roleId, List users, List groups, Boolean isAdmin) { if (LOG.isDebugEnabled()) { - LOG.debug("==> addUsersAndGroups(id=" + roleId + ", users=" + Arrays.toString(users.toArray()) + ", groups=" + Arrays.toString(groups.toArray()) + ", isAdmin=" + isAdmin + ")"); + LOG.debug("==> addUsersAndGroups(id={}, users={}, groups={}, isAdmin={})", roleId, Arrays.toString(users.toArray()), Arrays.toString(groups.toArray()), isAdmin); } RangerRole role; @@ -637,22 +635,26 @@ public RangerRole addUsersAndGroups(@PathParam("id") Long roleId, List u try { // Real processing ensureAdminAccess(null, null); + if (containsInvalidUser(users)) { throw new Exception("Invalid role user(s)"); } role = getRole(roleId); - Set roleUsers = new HashSet<>(); + Set roleUsers = new HashSet<>(); Set roleGroups = new HashSet<>(); for (RangerRole.RoleMember user : role.getUsers()) { if (users.contains(user.getName()) && isAdmin == Boolean.TRUE) { - user.setIsAdmin(isAdmin); + user.setIsAdmin(true); + roleUsers.add(user); } } + Set existingUsernames = getUserNames(role); + for (String user : users) { if (!existingUsernames.contains(user)) { roleUsers.add(new RangerRole.RoleMember(user, isAdmin)); @@ -664,24 +666,25 @@ public RangerRole addUsersAndGroups(@PathParam("id") Long roleId, List u roleGroups.add(group); } } + for (String group : groups) { roleGroups.add(new RangerRole.RoleMember(group, isAdmin)); } + role.setUsers(new ArrayList<>(roleUsers)); role.setGroups(new ArrayList<>(roleGroups)); - role = roleStore.updateRole(role,false); - - } catch(WebApplicationException excp) { + role = roleStore.updateRole(role, false); + } catch (WebApplicationException excp) { throw excp; - } catch(Throwable excp) { + } catch (Throwable excp) { LOG.error("addUsersAndGroups() failed", excp); throw restErrorUtil.createRESTException(excp.getMessage()); } if (LOG.isDebugEnabled()) { - LOG.debug("==> addUsersAndGroups(id=" + roleId + ", users=" + Arrays.toString(users.toArray()) + ", groups=" + Arrays.toString(groups.toArray()) + ", isAdmin=" + isAdmin + ")"); + LOG.debug("==> addUsersAndGroups(id={}, users={}, groups={}, isAdmin={})", roleId, Arrays.toString(users.toArray()), Arrays.toString(groups.toArray()), isAdmin); } return role; @@ -692,33 +695,40 @@ public RangerRole addUsersAndGroups(@PathParam("id") Long roleId, List u */ @PUT @Path("/roles/{id}/removeUsersAndGroups") - @Consumes({ "application/json" }) - @Produces({ "application/json" }) + @Consumes("application/json") + @Produces("application/json") public RangerRole removeUsersAndGroups(@PathParam("id") Long roleId, List users, List groups) { if (LOG.isDebugEnabled()) { - LOG.debug("==> removeUsersAndGroups(id=" + roleId + ", users=" + Arrays.toString(users.toArray()) + ", groups=" + Arrays.toString(groups.toArray()) + ")"); + LOG.debug("==> removeUsersAndGroups(id={}, users={}, groups={})", roleId, Arrays.toString(users.toArray()), Arrays.toString(groups.toArray())); } + RangerRole role; try { // Real processing ensureAdminAccess(null, null); + role = getRole(roleId); for (String user : users) { Iterator iter = role.getUsers().iterator(); + while (iter.hasNext()) { RangerRole.RoleMember member = iter.next(); + if (StringUtils.equals(member.getName(), user)) { iter.remove(); break; } } } + for (String group : groups) { Iterator iter = role.getGroups().iterator(); + while (iter.hasNext()) { RangerRole.RoleMember member = iter.next(); + if (StringUtils.equals(member.getName(), group)) { iter.remove(); break; @@ -727,16 +737,16 @@ public RangerRole removeUsersAndGroups(@PathParam("id") Long roleId, List users, List groups) { - if (LOG.isDebugEnabled()) { - LOG.debug("==> removeAdminFromUsersAndGroups(id=" + roleId + ", users=" + Arrays.toString(users.toArray()) + ", groups=" + Arrays.toString(groups.toArray()) + ")"); - } + LOG.debug("==> removeAdminFromUsersAndGroups(id={}, users={}, groups={})", roleId, Arrays.toString(users.toArray()), Arrays.toString(groups.toArray())); + RangerRole role; + try { // Real processing ensureAdminAccess(null, null); + role = getRole(roleId); for (String user : users) { @@ -766,6 +777,7 @@ public RangerRole removeAdminFromUsersAndGroups(@PathParam("id") Long roleId, Li } } } + for (String group : groups) { for (RangerRole.RoleMember member : role.getGroups()) { if (StringUtils.equals(member.getName(), group) && member.getIsAdmin()) { @@ -775,111 +787,109 @@ public RangerRole removeAdminFromUsersAndGroups(@PathParam("id") Long roleId, Li } role = roleStore.updateRole(role, false); - - } catch(WebApplicationException excp) { + } catch (WebApplicationException excp) { throw excp; - } catch(Throwable excp) { + } catch (Throwable excp) { LOG.error("removeAdminFromUsersAndGroups() failed", excp); throw restErrorUtil.createRESTException(excp.getMessage()); } - if (LOG.isDebugEnabled()) { - LOG.debug("==> removeAdminFromUsersAndGroups(id=" + roleId + ", users=" + Arrays.toString(users.toArray()) + ", groups=" + Arrays.toString(groups.toArray()) + ")"); - } + LOG.debug("==> removeAdminFromUsersAndGroups(id={}, users={}, groups={})", roleId, Arrays.toString(users.toArray()), Arrays.toString(groups.toArray())); return role; } - /* - * This API is used to GRANT role to users and roles with/without ADMIN option. It follows add-or-update semantics - * Minimum required privilege is the effective user has admin option for the target roles - */ - @PUT - @Consumes({ "application/json" }) - @Produces({ "application/json" }) + @Consumes("application/json") + @Produces("application/json") @Path("/roles/grant/{serviceName}") public RESTResponse grantRole(@PathParam("serviceName") String serviceName, GrantRevokeRoleRequest grantRoleRequest, @Context HttpServletRequest request) { - if(LOG.isDebugEnabled()) { - LOG.debug("==> RoleREST.grantRole(" + serviceName + ", " + grantRoleRequest + ")"); - } - RESTResponse ret = new RESTResponse(); + LOG.debug("==> RoleREST.grantRole({}, {})", serviceName, grantRoleRequest); + + RESTResponse ret = new RESTResponse(); try { validateUsersGroupsAndRoles(grantRoleRequest); + String userName = grantRoleRequest.getGrantor(); + for (String roleName : grantRoleRequest.getTargetRoles()) { /* For each target Role, check following to allow access * If userName (execUser) is not same as logged in user then check - * If logged-in user is not ranger admin/service admin/service user, then deny the operation - * effective User is execUser + * If logged-in user is not ranger admin/service admin/service user, then deny the operation + * effective User is execUser * else - * effective user is logged-in user + * effective user is logged-in user * If effective user is ranger admin/has role admin privilege, then allow the operation * else deny the operation * This logic is implemented as part of getRoleIfAccessible(roleName, serviceName, userName, userGroups) - */ - Set userGroups = CollectionUtils.isNotEmpty(grantRoleRequest.getGrantorGroups()) ? grantRoleRequest.getGrantorGroups() : userMgr.getGroupsForUser(userName); - RangerRole existingRole = getRoleIfAccessible(roleName, serviceName, userName, userGroups); + */ + Set userGroups = CollectionUtils.isNotEmpty(grantRoleRequest.getGrantorGroups()) ? grantRoleRequest.getGrantorGroups() : userMgr.getGroupsForUser(userName); + RangerRole existingRole = getRoleIfAccessible(roleName, serviceName, userName, userGroups); + if (existingRole == null) { throw restErrorUtil.createRESTException("User doesn't have permissions to grant role " + roleName); } existingRole.setUpdatedBy(userName); + addUsersGroupsAndRoles(existingRole, grantRoleRequest.getUsers(), grantRoleRequest.getGroups(), grantRoleRequest.getRoles(), grantRoleRequest.getGrantOption()); } - } catch(WebApplicationException excp) { + } catch (WebApplicationException excp) { throw excp; - } catch(Throwable excp) { + } catch (Throwable excp) { LOG.error("grantRole() failed", excp); throw restErrorUtil.createRESTException(excp.getMessage()); } if (LOG.isDebugEnabled()) { - LOG.debug("==> grantRole(serviceName=" + serviceName + ", users=" + Arrays.toString(grantRoleRequest.getUsers().toArray()) + ", groups=" + Arrays.toString(grantRoleRequest.getRoles().toArray()) + ", isAdmin=" + grantRoleRequest.getGrantOption() + ")"); + LOG.debug("==> grantRole(serviceName={}, users={}, groups={}, isAdmin={})", serviceName, Arrays.toString(grantRoleRequest.getUsers().toArray()), Arrays.toString(grantRoleRequest.getRoles().toArray()), grantRoleRequest.getGrantOption()); } + ret.setStatusCode(RESTResponse.STATUS_SUCCESS); return ret; } /* - * This API is used to remove users and roles, with regard to their REVOKE role from users and roles. - * Minimum required privilege is the execUser (or doAsUser) has admin option for the target roles + * This API is used to GRANT role to users and roles with/without ADMIN option. It follows add-or-update semantics + * Minimum required privilege is the effective user has admin option for the target roles */ @PUT @Path("/roles/revoke/{serviceName}") - @Consumes({ "application/json" }) - @Produces({ "application/json" }) + @Consumes("application/json") + @Produces("application/json") public RESTResponse revokeRole(@PathParam("serviceName") String serviceName, GrantRevokeRoleRequest revokeRoleRequest, @Context HttpServletRequest request) { + LOG.debug("==> RoleREST.revokeRole({}, {})", serviceName, revokeRoleRequest); - if(LOG.isDebugEnabled()) { - LOG.debug("==> RoleREST.revokeRole(" + serviceName + ", " + revokeRoleRequest + ")"); - } - RESTResponse ret = new RESTResponse(); + RESTResponse ret = new RESTResponse(); try { validateUsersGroupsAndRoles(revokeRoleRequest); + String userName = revokeRoleRequest.getGrantor(); + for (String roleName : revokeRoleRequest.getTargetRoles()) { /* For each target Role, check following to allow access * If userName (execUser) is not same as logged in user then check - * If logged-in user is not ranger admin/service admin/service user, then deny the operation - * effective User is execUser + * If logged-in user is not ranger admin/service admin/service user, then deny the operation + * effective User is execUser * else - * effective user is logged-in user + * effective user is logged-in user * If effective user is ranger admin/has role admin privilege, then allow the operation * else deny the operation * This logic is implemented as part of getRoleIfAccessible(roleName, serviceName, userName, userGroups) */ - Set userGroups = CollectionUtils.isNotEmpty(revokeRoleRequest.getGrantorGroups()) ? revokeRoleRequest.getGrantorGroups() : userMgr.getGroupsForUser(userName); - RangerRole existingRole = getRoleIfAccessible(roleName, serviceName, userName, userGroups); + Set userGroups = CollectionUtils.isNotEmpty(revokeRoleRequest.getGrantorGroups()) ? revokeRoleRequest.getGrantorGroups() : userMgr.getGroupsForUser(userName); + RangerRole existingRole = getRoleIfAccessible(roleName, serviceName, userName, userGroups); + if (existingRole == null) { throw restErrorUtil.createRESTException("User doesn't have permissions to revoke role " + roleName); } + existingRole.setUpdatedBy(userName); if (revokeRoleRequest.getGrantOption()) { @@ -888,108 +898,111 @@ public RESTResponse revokeRole(@PathParam("serviceName") String serviceName, Gra removeUsersGroupsAndRoles(existingRole, revokeRoleRequest.getUsers(), revokeRoleRequest.getGroups(), revokeRoleRequest.getRoles()); } } - } catch(WebApplicationException excp) { + } catch (WebApplicationException excp) { throw excp; - } catch(Throwable excp) { + } catch (Throwable excp) { LOG.error("revokeRole() failed", excp); throw restErrorUtil.createRESTException(excp.getMessage()); } if (LOG.isDebugEnabled()) { - LOG.debug("==> revokeRole(serviceName=" + serviceName + ", users=" + Arrays.toString(revokeRoleRequest.getUsers().toArray()) + ", roles=" + Arrays.toString(revokeRoleRequest.getRoles().toArray()) + ", isAdmin=" + revokeRoleRequest.getGrantOption() + ")"); + LOG.debug("==> revokeRole(serviceName={}, users={}, groups={}, isAdmin={})", serviceName, Arrays.toString(revokeRoleRequest.getUsers().toArray()), Arrays.toString(revokeRoleRequest.getRoles().toArray()), revokeRoleRequest.getGrantOption()); } + ret.setStatusCode(RESTResponse.STATUS_SUCCESS); return ret; } - /* Get all the roles that this user or user's groups belong to + /* + * This API is used to remove users and roles, with regard to their REVOKE role from users and roles. + * Minimum required privilege is the execUser (or doAsUser) has admin option for the target roles */ @GET @Path("/roles/user/{user}") - @Produces({ "application/json" }) + @Produces("application/json") public List getUserRoles(@PathParam("user") String userName, @Context HttpServletRequest request) { Set ret = new HashSet<>(); - if (LOG.isDebugEnabled()) { - LOG.debug("==> getUserRoles()"); - } + LOG.debug("==> getUserRoles()"); + try { if (xUserService.getXUserByUserName(userName) == null) { throw restErrorUtil.createRESTException(HttpServletResponse.SC_NOT_FOUND, "User:" + userName + " not found", false); } + Set roleList = roleStore.getRoleNames(userName, userMgr.getGroupsForUser(userName)); + for (RangerRole role : roleList) { ret.add(role.getName()); + Set roleMembers = new HashSet<>(); + getRoleMemberNames(roleMembers, role); + ret.addAll(roleMembers); } - } catch(WebApplicationException excp) { + } catch (WebApplicationException excp) { throw excp; - } catch(Throwable excp) { + } catch (Throwable excp) { LOG.error("getUserRoles() failed", excp); throw restErrorUtil.createRESTException(excp.getMessage()); } - if (LOG.isDebugEnabled()) { - LOG.debug("<== getUserRoles():" + ret); - } + + LOG.debug("<== getUserRoles():{}", ret); + return new ArrayList<>(ret); } + /* Get all the roles that this user or user's groups belong to + */ + @GET @Path("/download/{serviceName}") - @Produces({ "application/json" }) - public RangerRoles getRangerRolesIfUpdated( - @PathParam("serviceName") String serviceName, - @DefaultValue("-1") @QueryParam("lastKnownRoleVersion") Long lastKnownRoleVersion, - @DefaultValue("0") @QueryParam("lastActivationTime") Long lastActivationTime, - @QueryParam("pluginId") String pluginId, - @DefaultValue("") @QueryParam("clusterName") String clusterName, - @DefaultValue("") @QueryParam(RangerRESTUtils.REST_PARAM_CAPABILITIES) String pluginCapabilities, - @Context HttpServletRequest request) throws Exception { - if (LOG.isDebugEnabled()) { - LOG.debug("==> RoleREST.getRangerRolesIfUpdated(" - + serviceName + ", " + lastKnownRoleVersion + ", " + lastActivationTime + ")"); - } - RangerRoles ret = null; + @Produces("application/json") + public RangerRoles getRangerRolesIfUpdated(@PathParam("serviceName") String serviceName, @DefaultValue("-1") @QueryParam("lastKnownRoleVersion") Long lastKnownRoleVersion, @DefaultValue("0") @QueryParam("lastActivationTime") Long lastActivationTime, @QueryParam("pluginId") String pluginId, @DefaultValue("") @QueryParam("clusterName") String clusterName, @DefaultValue("") @QueryParam(RangerRESTUtils.REST_PARAM_CAPABILITIES) String pluginCapabilities, @Context HttpServletRequest request) { + LOG.debug("==> RoleREST.getRangerRolesIfUpdated({}, {}, {})", serviceName, lastKnownRoleVersion, lastActivationTime); - boolean isValid = false; - int httpCode = HttpServletResponse.SC_OK; - Long downloadedVersion = null; - String logMsg = null; + RangerRoles ret = null; + boolean isValid = false; + int httpCode = HttpServletResponse.SC_OK; + Long downloadedVersion = null; + String logMsg = null; try { bizUtil.failUnauthenticatedDownloadIfNotAllowed(); + isValid = serviceUtil.isValidService(serviceName, request); } catch (WebApplicationException webException) { httpCode = webException.getResponse().getStatus(); - logMsg = webException.getResponse().getEntity().toString(); + logMsg = webException.getResponse().getEntity().toString(); } catch (Exception e) { httpCode = HttpServletResponse.SC_BAD_REQUEST; - logMsg = e.getMessage(); + logMsg = e.getMessage(); } + if (isValid) { try { RangerRoles roles = roleStore.getRoles(serviceName, lastKnownRoleVersion); + if (roles == null) { downloadedVersion = lastKnownRoleVersion; - httpCode = HttpServletResponse.SC_NOT_MODIFIED; - logMsg = "No change since last update"; + httpCode = HttpServletResponse.SC_NOT_MODIFIED; + logMsg = "No change since last update"; } else { - downloadedVersion = roles.getRoleVersion(); roles.setServiceName(serviceName); - ret = roles; - httpCode = HttpServletResponse.SC_OK; - logMsg = "Returning RangerRoles =>" + (ret.toString()); - } + downloadedVersion = roles.getRoleVersion(); + ret = roles; + logMsg = "Returning RangerRoles =>" + (ret); + } } catch (Throwable excp) { - LOG.error("getRangerRolesIfUpdated(" + serviceName + ", " + lastKnownRoleVersion + ", " + lastActivationTime + ") failed", excp); + LOG.error("getRangerRolesIfUpdated({}, {}, {}) failed", serviceName, lastKnownRoleVersion, lastActivationTime, excp); + httpCode = HttpServletResponse.SC_BAD_REQUEST; - logMsg = excp.getMessage(); + logMsg = excp.getMessage(); } } @@ -997,71 +1010,64 @@ public RangerRoles getRangerRolesIfUpdated( if (httpCode != HttpServletResponse.SC_OK) { boolean logError = httpCode != HttpServletResponse.SC_NOT_MODIFIED; + throw restErrorUtil.createRESTException(httpCode, logMsg, logError); } - if (LOG.isDebugEnabled()) { - LOG.debug("<== RoleREST.getRangerRolesIfUpdated(" + serviceName + ", " + lastKnownRoleVersion + ", " + lastActivationTime + ")" + ret); - } + LOG.debug("<== RoleREST.getRangerRolesIfUpdated({}, {}, {}) ret:{}", serviceName, lastKnownRoleVersion, lastActivationTime, ret); + return ret; } @GET @Path("/secure/download/{serviceName}") - @Produces({ "application/json" }) - public RangerRoles getSecureRangerRolesIfUpdated( - @PathParam("serviceName") String serviceName, - @DefaultValue("-1") @QueryParam("lastKnownRoleVersion") Long lastKnownRoleVersion, - @DefaultValue("0") @QueryParam("lastActivationTime") Long lastActivationTime, - @QueryParam("pluginId") String pluginId, - @DefaultValue("") @QueryParam("clusterName") String clusterName, - @DefaultValue("") @QueryParam(RangerRESTUtils.REST_PARAM_CAPABILITIES) String pluginCapabilities, - @Context HttpServletRequest request) throws Exception { - if (LOG.isDebugEnabled()) { - LOG.debug("==> RoleREST.getSecureRangerRolesIfUpdated(" - + serviceName + ", " + lastKnownRoleVersion + ", " + lastKnownRoleVersion + ")"); - } - RangerRoles ret = null; - int httpCode = HttpServletResponse.SC_OK; - String logMsg = null; - boolean isAllowed = false; - boolean isAdmin = bizUtil.isAdmin(); - boolean isKeyAdmin = bizUtil.isKeyAdmin(); - Long downloadedVersion = null; + @Produces("application/json") + public RangerRoles getSecureRangerRolesIfUpdated(@PathParam("serviceName") String serviceName, @DefaultValue("-1") @QueryParam("lastKnownRoleVersion") Long lastKnownRoleVersion, @DefaultValue("0") @QueryParam("lastActivationTime") Long lastActivationTime, @QueryParam("pluginId") String pluginId, @DefaultValue("") @QueryParam("clusterName") String clusterName, @DefaultValue("") @QueryParam(RangerRESTUtils.REST_PARAM_CAPABILITIES) String pluginCapabilities, @Context HttpServletRequest request) { + LOG.debug("==> RoleREST.getSecureRangerRolesIfUpdated({}, {}, {})", serviceName, lastKnownRoleVersion, lastActivationTime); + RangerRoles ret = null; + int httpCode = HttpServletResponse.SC_OK; + String logMsg = null; + boolean isAdmin = bizUtil.isAdmin(); + boolean isKeyAdmin = bizUtil.isKeyAdmin(); + Long downloadedVersion = null; + boolean isValid = false; + boolean isAllowed; request.setAttribute("downloadPolicy", "secure"); - boolean isValid = false; try { isValid = serviceUtil.isValidService(serviceName, request); } catch (WebApplicationException webException) { httpCode = webException.getResponse().getStatus(); - logMsg = webException.getResponse().getEntity().toString(); + logMsg = webException.getResponse().getEntity().toString(); } catch (Exception e) { httpCode = HttpServletResponse.SC_BAD_REQUEST; - logMsg = e.getMessage(); + logMsg = e.getMessage(); } + if (isValid) { try { XXService xService = daoManager.getXXService().findByName(serviceName); + if (xService == null) { - LOG.error("Requested Service not found. serviceName=" + serviceName); - throw restErrorUtil.createRESTException(HttpServletResponse.SC_NOT_FOUND, "Service:" + serviceName + " not found", - false); + LOG.error("Requested Service not found. serviceName={}", serviceName); + + throw restErrorUtil.createRESTException(HttpServletResponse.SC_NOT_FOUND, "Service:" + serviceName + " not found", false); } - XXServiceDef xServiceDef = daoManager.getXXServiceDef().getById(xService.getType()); + + XXServiceDef xServiceDef = daoManager.getXXServiceDef().getById(xService.getType()); RangerService rangerService = svcStore.getServiceByName(serviceName); if (StringUtils.equals(xServiceDef.getImplclassname(), EmbeddedServiceDefsUtil.KMS_IMPL_CLASS_NAME)) { if (isKeyAdmin) { isAllowed = true; - }else { + } else { isAllowed = bizUtil.isUserAllowed(rangerService, POLICY_DOWNLOAD_USERS); } - }else{ + } else { if (isAdmin) { isAllowed = true; - }else{ + } else { isAllowed = bizUtil.isUserAllowed(rangerService, POLICY_DOWNLOAD_USERS); } } @@ -1070,25 +1076,26 @@ public RangerRoles getSecureRangerRolesIfUpdated( RangerRoles roles = roleStore.getRoles(serviceName, lastKnownRoleVersion); if (roles == null) { downloadedVersion = lastKnownRoleVersion; - httpCode = HttpServletResponse.SC_NOT_MODIFIED; - logMsg = "No change since last update"; + httpCode = HttpServletResponse.SC_NOT_MODIFIED; + logMsg = "No change since last update"; } else { - downloadedVersion = roles.getRoleVersion(); roles.setServiceName(serviceName); - ret = roles; - httpCode = HttpServletResponse.SC_OK; - logMsg = "Returning RangerRoles =>" + (ret.toString()); + + downloadedVersion = roles.getRoleVersion(); + ret = roles; + logMsg = "Returning RangerRoles =>" + (ret); } } else { - LOG.error("getSecureRangerRolesIfUpdated(" + serviceName + ", " + lastKnownRoleVersion + ") failed as User doesn't have permission to UserGroupRoles"); + LOG.error("getSecureRangerRolesIfUpdated({}, {}) failed as User doesn't have permission to UserGroupRoles", serviceName, lastKnownRoleVersion); + httpCode = HttpServletResponse.SC_FORBIDDEN; // assert user is authenticated. - logMsg = "User doesn't have permission to download UserGroupRoles"; + logMsg = "User doesn't have permission to download UserGroupRoles"; } - } catch (Throwable excp) { - LOG.error("getSecureRangerRolesIfUpdated(" + serviceName + ", " + lastKnownRoleVersion + ", " + lastActivationTime + ") failed", excp); + LOG.error("getSecureRangerRolesIfUpdated({}, {}, {}) failed", serviceName, lastKnownRoleVersion, lastActivationTime, excp); + httpCode = HttpServletResponse.SC_BAD_REQUEST; - logMsg = excp.getMessage(); + logMsg = excp.getMessage(); } } @@ -1096,32 +1103,84 @@ public RangerRoles getSecureRangerRolesIfUpdated( if (httpCode != HttpServletResponse.SC_OK) { boolean logError = httpCode != HttpServletResponse.SC_NOT_MODIFIED; + throw restErrorUtil.createRESTException(httpCode, logMsg, logError); } - if (LOG.isDebugEnabled()) { - LOG.debug("<== RoleREST.getSecureRangerRolesIfUpdated(" + serviceName + ", " + lastKnownRoleVersion + ", " + lastActivationTime + ")" + ret); - } + LOG.debug("<== RoleREST.getSecureRangerRolesIfUpdated({}, {}, {}) ret:{}", serviceName, lastKnownRoleVersion, lastActivationTime, ret); + return ret; } - private void ensureAdminAccess(String serviceName, String userName) throws Exception { + protected List getAllFilteredRoleList(HttpServletRequest request) throws Exception { + LOG.debug("==> getAllFilteredRoleList()"); + + String roleNames = null; + List roleNameList = null; + List roleLists = new ArrayList<>(); + + if (request.getParameter(PARAM_ROLE_NAME) != null) { + roleNames = request.getParameter(PARAM_ROLE_NAME); + } + + if (StringUtils.isNotEmpty(roleNames)) { + roleNameList = new ArrayList<>(Arrays.asList(roleNames.split(","))); + } + + SearchFilter filter = new SearchFilter(); + List rangerRoleList = roleStore.getRoles(filter); + + if (!CollectionUtils.isEmpty(rangerRoleList)) { + for (RangerRole role : rangerRoleList) { + if (role != null) { + if (CollectionUtils.isNotEmpty(roleNameList)) { + if (roleNameList.contains(role.getName())) { + // set createTime & updateTime Time as null since exported Roles don't need this + role.setCreateTime(null); + role.setUpdateTime(null); + + roleLists.add(role); + + roleNameList.remove(role.getName()); + + if (roleNameList.isEmpty()) { + break; + } + } + } else { + // set createTime & updateTime Time as null since exported Roles don't need this + role.setCreateTime(null); + role.setUpdateTime(null); + + roleLists.add(role); + } + } + } + } + LOG.debug("<== getAllFilteredRoleList(){}", roleLists.size()); + + return roleLists; + } + + private void ensureAdminAccess(String serviceName, String userName) throws Exception { /* If userName (execUser) is not same as logged in user then check - * If logged-in user is not ranger admin/service admin/service user, then deny the operation - * effective User is execUser + * If logged-in user is not ranger admin/service admin/service user, then deny the operation + * effective User is execUser * else - * effective user is logged-in user + * effective user is logged-in user * If effective user is ranger admin, then allow the operation * else deny the operation */ - String effectiveUser; - UserSessionBase usb = ContextUtil.getCurrentUserSession(); - String loggedInUser = usb != null ? usb.getLoginId() : null; + String effectiveUser; + UserSessionBase usb = ContextUtil.getCurrentUserSession(); + String loggedInUser = usb != null ? usb.getLoginId() : null; + if (!StringUtil.equals(userName, loggedInUser)) { if (!bizUtil.isUserRangerAdmin(loggedInUser) && !userIsSrvAdmOrSrvUser(serviceName, loggedInUser)) { throw new Exception("User does not have permission for this operation"); } + effectiveUser = userName != null ? userName : loggedInUser; } else { effectiveUser = loggedInUser; @@ -1134,36 +1193,41 @@ private void ensureAdminAccess(String serviceName, String userName) throws Excep private RangerRole getRoleIfAccessible(String roleName, String serviceName, String userName, Set userGroups) { /* If userName (execUser) is not same as logged in user then check - * If logged-in user is not ranger admin/service admin/service user, then deny the operation - * effective User is execUser + * If logged-in user is not ranger admin/service admin/service user, then deny the operation + * effective User is execUser * else - * effective user is logged-in user + * effective user is logged-in user * If effective user is ranger admin/has role admin privilege, then allow the operation * else deny the operation */ - RangerRole existingRole; - String effectiveUser; - UserSessionBase usb = ContextUtil.getCurrentUserSession(); - String loggedInUser = usb != null ? usb.getLoginId() : null; + RangerRole existingRole; + String effectiveUser; + UserSessionBase usb = ContextUtil.getCurrentUserSession(); + String loggedInUser = usb != null ? usb.getLoginId() : null; + if (!StringUtil.equals(userName, loggedInUser)) { if (!bizUtil.isUserRangerAdmin(loggedInUser) && !userIsSrvAdmOrSrvUser(serviceName, loggedInUser)) { LOG.error("User does not have permission for this operation"); + return null; } + effectiveUser = userName != null ? userName : loggedInUser; } else { effectiveUser = loggedInUser; } + try { if (!bizUtil.isUserRangerAdmin(effectiveUser) && !svcStore.isServiceAdminUser(serviceName, effectiveUser)) { existingRole = roleStore.getRole(roleName); - ensureRoleAccess(effectiveUser, userGroups, existingRole); + ensureRoleAccess(effectiveUser, userGroups, existingRole); } else { existingRole = roleStore.getRole(roleName); } } catch (Exception ex) { LOG.error(ex.getMessage()); + return null; } @@ -1176,8 +1240,10 @@ private boolean userIsSrvAdmOrSrvUser(String serviceName, String username) { if (!StringUtil.isEmpty(serviceName)) { try { isServiceAdmin = svcStore.isServiceAdminUser(serviceName, username); + if (!isServiceAdmin) { RangerService rangerService = svcStore.getServiceByName(serviceName); + if (rangerService != null) { String serviceUser = PropertiesUtil.getProperty("ranger.plugins." + rangerService.getType() + ".serviceuser"); @@ -1188,22 +1254,27 @@ private boolean userIsSrvAdmOrSrvUser(String serviceName, String username) { LOG.error(ex.getMessage()); } } + return isServiceAdmin; } private boolean containsInvalidMember(List users) { boolean ret = false; + for (RangerRole.RoleMember user : users) { for (String invalidUser : INVALID_USERS) { if (StringUtils.equals(user.getName(), invalidUser)) { ret = true; + break; } } + if (ret) { break; } } + return ret; } @@ -1212,70 +1283,76 @@ private boolean containsInvalidUser(List users) { } private boolean ensureRoleAccess(String username, Set userGroups, RangerRole role) throws Exception { - if (LOG.isDebugEnabled()) { - LOG.debug("==> ensureRoleAccess("+ username + ", " + role + ")"); - } - boolean isAccessible = false; - List userList = role.getUsers(); - RangerRole.RoleMember userMember = new RangerRole.RoleMember(username, true); + LOG.debug("==> ensureRoleAccess({}, {})", username, role); + + boolean isAccessible = false; + List userList = role.getUsers(); + RangerRole.RoleMember userMember = new RangerRole.RoleMember(username, true); - if (!CollectionUtils.isEmpty(userList) && userList.contains(userMember)) { + if (!CollectionUtils.isEmpty(userList) && userList.contains(userMember)) { isAccessible = true; - if (LOG.isDebugEnabled()) { - LOG.debug("==> ensureRoleAccess(): user "+ username + " has permission for role " + role.getName()); - } + + LOG.debug("==> ensureRoleAccess(): user {} has permission for role {}", username, role.getName()); + return isAccessible; } if (!CollectionUtils.isEmpty(userGroups)) { List groupList = role.getGroups(); + for (RangerRole.RoleMember groupMember : groupList) { if (!groupMember.getIsAdmin()) { continue; } + if (userGroups.contains(groupMember.getName())) { isAccessible = true; - if (LOG.isDebugEnabled()) { - LOG.debug("==> ensureRoleAccess(): group " + groupMember.getName() + " has permission for role " + role.getName()); - } + + LOG.debug("==> ensureRoleAccess(): group {} has permission for role {}", groupMember.getName(), role.getName()); + return isAccessible; } } } Set roleMemberList = new HashSet<>(); + getRoleMembers(roleMemberList, role); + for (RangerRole.RoleMember roleMember : roleMemberList) { if (!roleMember.getIsAdmin()) { continue; } RangerRole roleMemberObj = roleStore.getRole(roleMember.getName()); + if (getUserNames(roleMemberObj).contains(username)) { isAccessible = true; - if (LOG.isDebugEnabled()) { - LOG.debug("==> ensureRoleAccess(): role "+ roleMember.getName() + " has permission for role " + role.getName()); - } + + LOG.debug("==> ensureRoleAccess(): role {} has permission for role {}", roleMember.getName(), role.getName()); + return isAccessible; } if (!CollectionUtils.isEmpty(userGroups) && !CollectionUtils.intersection(userGroups, getGroupNames(roleMemberObj)).isEmpty()) { isAccessible = true; - if (LOG.isDebugEnabled()) { - LOG.debug("==> ensureRoleAccess(): role " + roleMember.getName() + " has permission for role " + role.getName()); - } + + LOG.debug("==> ensureRoleAccess(): role {} has permission for role {}", roleMember.getName(), role.getName()); + return isAccessible; } } + if (!isAccessible) { throw restErrorUtil.createRESTException("User " + username + " does not have privilege to role " + role.getName()); } + return isAccessible; } private RangerRole addUsersGroupsAndRoles(RangerRole role, Set users, Set groups, Set roles, Boolean isAdmin) { if (LOG.isDebugEnabled()) { - LOG.debug("==> addUsersGroupsAndRoles(name=" + role.getName() + ", users=" + Arrays.toString(users.toArray()) + ", roles=" + Arrays.toString(roles.toArray()) + ", isAdmin=" + isAdmin + ")"); + LOG.debug("==> addUsersGroupsAndRoles(name={}, users={}, roles={}, isAdmin={})", role.getName(), Arrays.toString(users.toArray()), Arrays.toString(roles.toArray()), isAdmin); } try { @@ -1283,80 +1360,89 @@ private RangerRole addUsersGroupsAndRoles(RangerRole role, Set users, Se for (String newRole : roles) { //get members recursively and check if the grantor role is already a member Set roleMembers = new HashSet<>(); + getRoleMemberNames(roleMembers, roleStore.getRole(newRole)); - if (LOG.isDebugEnabled()) { - LOG.debug("Role members for " + newRole + " = " + roleMembers); - } + + LOG.debug("Role members for {} = {}", newRole, roleMembers); + if (roleMembers.contains(role.getName())) { throw new Exception("Invalid role grant"); } - } - Set roleUsers = new HashSet<>(); + Set roleUsers = new HashSet<>(); Set roleGroups = new HashSet<>(); - Set roleRoles = new HashSet<>(); + Set roleRoles = new HashSet<>(); + + for (RangerRole.RoleMember user : role.getUsers()) { + String userName = user.getName(); - for (RangerRole.RoleMember user : role.getUsers()) { - String userName = user.getName(); - if (users.contains(userName)) { - user.setIsAdmin(isAdmin); - } - roleUsers.add(user); - } + if (users.contains(userName)) { + user.setIsAdmin(isAdmin); + } + + roleUsers.add(user); + } Set existingUsernames = getUserNames(role); + for (String user : users) { if (!existingUsernames.contains(user)) { roleUsers.add(new RangerRole.RoleMember(user, isAdmin)); } } - for (RangerRole.RoleMember group : role.getGroups()) { - String groupName = group.getName(); - if (groups.contains(groupName)) { - group.setIsAdmin(isAdmin); - } - roleGroups.add(group); - } + for (RangerRole.RoleMember group : role.getGroups()) { + String groupName = group.getName(); + + if (groups.contains(groupName)) { + group.setIsAdmin(isAdmin); + } + + roleGroups.add(group); + } Set existingGroupnames = getGroupNames(role); + for (String group : groups) { if (!existingGroupnames.contains(group)) { roleGroups.add(new RangerRole.RoleMember(group, isAdmin)); } } - for (RangerRole.RoleMember roleMember : role.getRoles()) { - String roleName = roleMember.getName(); - if (roles.contains(roleName)) { - roleMember.setIsAdmin(isAdmin); - } - roleRoles.add(roleMember); - } + for (RangerRole.RoleMember roleMember : role.getRoles()) { + String roleName = roleMember.getName(); + + if (roles.contains(roleName)) { + roleMember.setIsAdmin(isAdmin); + } + + roleRoles.add(roleMember); + } Set existingRolenames = getRoleNames(role); + for (String newRole : roles) { if (!existingRolenames.contains(newRole)) { roleRoles.add(new RangerRole.RoleMember(newRole, isAdmin)); } } + role.setUsers(new ArrayList<>(roleUsers)); role.setGroups(new ArrayList<>(roleGroups)); role.setRoles(new ArrayList<>(roleRoles)); role = roleStore.updateRole(role, false); - - } catch(WebApplicationException excp) { + } catch (WebApplicationException excp) { throw excp; - } catch(Throwable excp) { + } catch (Throwable excp) { LOG.error("addUsersGroupsAndRoles() failed", excp); throw restErrorUtil.createRESTException(excp.getMessage()); } if (LOG.isDebugEnabled()) { - LOG.debug("<== addUsersGroupsAndRoles(name=" + role.getName() + ", users=" + Arrays.toString(users.toArray()) + ", roles=" + Arrays.toString(roles.toArray()) + ", isAdmin=" + isAdmin + ")"); + LOG.debug("<== addUsersGroupsAndRoles(name={}, users={}, roles={}, isAdmin={})", role.getName(), Arrays.toString(users.toArray()), Arrays.toString(roles.toArray()), isAdmin); } return role; @@ -1364,15 +1450,17 @@ private RangerRole addUsersGroupsAndRoles(RangerRole role, Set users, Se private RangerRole removeUsersGroupsAndRoles(RangerRole role, Set users, Set groups, Set roles) { if (LOG.isDebugEnabled()) { - LOG.debug("==> removeUsersGroupsAndRoles(name=" + role.getName() + ", users=" + Arrays.toString(users.toArray()) + ", roles=" + Arrays.toString(roles.toArray()) + ")"); + LOG.debug("==> removeUsersGroupsAndRoles(name={}, users={}, roles={})", role.getName(), Arrays.toString(users.toArray()), Arrays.toString(roles.toArray())); } try { // Real processing for (String user : users) { Iterator iter = role.getUsers().iterator(); + while (iter.hasNext()) { RangerRole.RoleMember member = iter.next(); + if (StringUtils.equals(member.getName(), user)) { iter.remove(); break; @@ -1382,8 +1470,10 @@ private RangerRole removeUsersGroupsAndRoles(RangerRole role, Set users, for (String group : groups) { Iterator iter = role.getGroups().iterator(); + while (iter.hasNext()) { RangerRole.RoleMember member = iter.next(); + if (StringUtils.equals(member.getName(), group)) { iter.remove(); break; @@ -1393,8 +1483,10 @@ private RangerRole removeUsersGroupsAndRoles(RangerRole role, Set users, for (String newRole : roles) { Iterator iter = role.getRoles().iterator(); + while (iter.hasNext()) { RangerRole.RoleMember member = iter.next(); + if (StringUtils.equals(member.getName(), newRole)) { iter.remove(); break; @@ -1403,16 +1495,16 @@ private RangerRole removeUsersGroupsAndRoles(RangerRole role, Set users, } role = roleStore.updateRole(role, false); - - } catch(WebApplicationException excp) { + } catch (WebApplicationException excp) { throw excp; - } catch(Throwable excp) { + } catch (Throwable excp) { LOG.error("removeUsersGroupsAndRoles() failed", excp); throw restErrorUtil.createRESTException(excp.getMessage()); } + if (LOG.isDebugEnabled()) { - LOG.debug("<== removeUsersGroupsAndRoles(name=" + role.getName() + ", users=" + Arrays.toString(users.toArray()) + ", roles=" + Arrays.toString(roles.toArray()) + ")"); + LOG.debug("<== removeUsersGroupsAndRoles(name={}, users={}, roles={})", role.getName(), Arrays.toString(users.toArray()), Arrays.toString(roles.toArray())); } return role; @@ -1420,8 +1512,9 @@ private RangerRole removeUsersGroupsAndRoles(RangerRole role, Set users, private RangerRole removeAdminFromUsersGroupsAndRoles(RangerRole role, Set users, Set groups, Set roles) { if (LOG.isDebugEnabled()) { - LOG.debug("==> removeAdminFromUsersGroupsAndRoles(name=" + role + ", users=" + Arrays.toString(users.toArray()) + ", roles=" + Arrays.toString(roles.toArray()) + ")"); + LOG.debug("==> removeAdminFromUsersGroupsAndRoles(name={}, users={}, roles={})", role.getName(), Arrays.toString(users.toArray()), Arrays.toString(roles.toArray())); } + try { // Real processing for (String user : users) { @@ -1431,6 +1524,7 @@ private RangerRole removeAdminFromUsersGroupsAndRoles(RangerRole role, Set getUserNames(RangerRole role) { - Set usernames = new HashSet<>(); + for (RangerRole.RoleMember user : role.getUsers()) { usernames.add(user.getName()); } + return usernames; } private Set getGroupNames(RangerRole role) { - Set groupnames = new HashSet<>(); + for (RangerRole.RoleMember group : role.getGroups()) { groupnames.add(group.getName()); } + return groupnames; } private Set getRoleNames(RangerRole role) { Set rolenames = new HashSet<>(); + for (RangerRole.RoleMember roleMember : role.getRoles()) { rolenames.add(roleMember.getName()); } + return rolenames; } private void getRoleMemberNames(Set roleMembers, RangerRole role) throws Exception { - for (RangerRole.RoleMember roleMember : role.getRoles()) { - roleMembers.add(roleMember.getName()); - getRoleMemberNames(roleMembers, roleStore.getRole(roleMember.getName())); + for (RangerRole.RoleMember roleMember : role.getRoles()) { + roleMembers.add(roleMember.getName()); + + getRoleMemberNames(roleMembers, roleStore.getRole(roleMember.getName())); } } private void getRoleMembers(Set roleMembers, RangerRole role) throws Exception { for (RangerRole.RoleMember roleMember : role.getRoles()) { roleMembers.add(roleMember); + getRoleMembers(roleMembers, roleStore.getRole(roleMember.getName())); } } - private void validateUsersGroupsAndRoles(GrantRevokeRoleRequest request){ + private void validateUsersGroupsAndRoles(GrantRevokeRoleRequest request) { if (request == null) { throw restErrorUtil.createRESTException("Invalid grant/revoke role request"); } - if(CollectionUtils.isEmpty(request.getUsers()) && CollectionUtils.isEmpty(request.getGroups()) && CollectionUtils.isEmpty(request.getRoles())) { + if (CollectionUtils.isEmpty(request.getUsers()) && CollectionUtils.isEmpty(request.getGroups()) && CollectionUtils.isEmpty(request.getRoles())) { throw restErrorUtil.createRESTException("Grantee users/groups/roles list is empty"); } + if (request.getUsers() == null) { request.setUsers(new HashSet<>()); } - if (request.getGroups() == null ) { + if (request.getGroups() == null) { request.setGroups(new HashSet<>()); } @@ -1525,82 +1625,44 @@ private void validateUsersGroupsAndRoles(GrantRevokeRoleRequest request){ } } - protected List getAllFilteredRoleList(HttpServletRequest request) throws Exception { - if (LOG.isDebugEnabled()) { - LOG.debug("==> getAllFilteredRoleList()"); - } - String roleNames = null; - List roleNameList = null; - List roleLists = new ArrayList<>(); - - if (request.getParameter(PARAM_ROLE_NAME) != null) { - roleNames = request.getParameter(PARAM_ROLE_NAME); - } - if (StringUtils.isNotEmpty(roleNames)) { - roleNameList = new ArrayList(Arrays.asList(roleNames.split(","))); - } - - List rangerRoleList = new ArrayList(); - SearchFilter filter = new SearchFilter(); - - rangerRoleList = roleStore.getRoles(filter); - - if (!CollectionUtils.isEmpty(rangerRoleList)) { - for (RangerRole role : rangerRoleList) { - if (role != null) { - if (CollectionUtils.isNotEmpty(roleNameList)) { - if (roleNameList.contains(role.getName())) { - // set createTime & updateTime Time as null since exported Roles don't need this - role.setCreateTime(null); - role.setUpdateTime(null); - roleLists.add(role); - roleNameList.remove(role.getName()); - if (roleNameList.size() == 0) { - break; - } - } - } else { - // set createTime & updateTime Time as null since exported Roles don't need this - role.setCreateTime(null); - role.setUpdateTime(null); - roleLists.add(role); - } - } - } - } - if (LOG.isDebugEnabled()) { - LOG.debug("<== getAllFilteredRoleList()" + roleLists.size()); - } - return roleLists; - } - - private List getRoleNameList(HttpServletRequest request, List roleNameList) throws Exception { - SearchFilter filter = searchUtil.getSearchFilter(request, roleService.sortFields); - roleNameList = roleStore.getRoleNames(filter); - return roleNameList; - } - - private RangerExportRoleList processRoleInputJsonForMetaData(InputStream uploadedInputStream, - RangerExportRoleList rangerExportRoleList) throws Exception { - String rolesString = IOUtils.toString(uploadedInputStream); - rolesString = rolesString.trim(); - if (StringUtils.isNotEmpty(rolesString)) { - rangerExportRoleList = JsonUtilsV2.jsonToObj(rolesString, RangerExportRoleList.class); - } else { - LOG.error("Provided json file is empty!!"); - throw restErrorUtil.createRESTException("Provided json file is empty!!"); - } - return rangerExportRoleList; - } - - private List getRolesFromProvidedJson(RangerExportRoleList rangerExportRoleList) { - List roles = null; - if (rangerExportRoleList != null && !CollectionUtils.sizeIsEmpty(rangerExportRoleList.getSecurityRoles())) { - roles = rangerExportRoleList.getSecurityRoles(); - } else { - LOG.error("Provided json file does not contain any role!!"); - throw restErrorUtil.createRESTException("Provided json file does not contain any role!!"); - } - return roles; - } + private List getRoleNameList(HttpServletRequest request, List roleNameList) throws Exception { + SearchFilter filter = searchUtil.getSearchFilter(request, roleService.sortFields); + + roleNameList = roleStore.getRoleNames(filter); + + return roleNameList; + } + + private RangerExportRoleList processRoleInputJsonForMetaData(InputStream uploadedInputStream, RangerExportRoleList rangerExportRoleList) throws Exception { + String rolesString = IOUtils.toString(uploadedInputStream).trim(); + + if (StringUtils.isNotEmpty(rolesString)) { + rangerExportRoleList = JsonUtilsV2.jsonToObj(rolesString, RangerExportRoleList.class); + } else { + LOG.error("Provided json file is empty!!"); + + throw restErrorUtil.createRESTException("Provided json file is empty!!"); + } + + return rangerExportRoleList; + } + + private List getRolesFromProvidedJson(RangerExportRoleList rangerExportRoleList) { + List roles; + + if (rangerExportRoleList != null && !CollectionUtils.sizeIsEmpty(rangerExportRoleList.getSecurityRoles())) { + roles = rangerExportRoleList.getSecurityRoles(); + } else { + LOG.error("Provided json file does not contain any role!!"); + + throw restErrorUtil.createRESTException("Provided json file does not contain any role!!"); + } + + return roles; + } + + static { + INVALID_USERS.add(RangerPolicyEngine.USER_CURRENT); + INVALID_USERS.add(RangerPolicyEngine.RESOURCE_OWNER); + } } diff --git a/security-admin/src/main/java/org/apache/ranger/rest/SecurityZoneREST.java b/security-admin/src/main/java/org/apache/ranger/rest/SecurityZoneREST.java index dab430bfd2..6689675058 100644 --- a/security-admin/src/main/java/org/apache/ranger/rest/SecurityZoneREST.java +++ b/security-admin/src/main/java/org/apache/ranger/rest/SecurityZoneREST.java @@ -19,36 +19,9 @@ package org.apache.ranger.rest; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Set; - -import javax.persistence.OptimisticLockException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.ws.rs.Consumes; -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.WebApplicationException; -import javax.ws.rs.core.Context; -import javax.ws.rs.DefaultValue; -import javax.ws.rs.QueryParam; - import org.apache.hadoop.thirdparty.com.google.common.collect.Sets; -import org.apache.ranger.biz.RangerPolicyAdmin; import org.apache.ranger.biz.RangerBizUtil; +import org.apache.ranger.biz.RangerPolicyAdmin; import org.apache.ranger.biz.SecurityZoneDBStore; import org.apache.ranger.biz.ServiceDBStore; import org.apache.ranger.biz.ServiceMgr; @@ -61,21 +34,21 @@ import org.apache.ranger.entity.XXService; import org.apache.ranger.entity.XXServiceDef; import org.apache.ranger.plugin.model.RangerSecurityZone; +import org.apache.ranger.plugin.model.RangerSecurityZone.RangerSecurityZoneService; +import org.apache.ranger.plugin.model.RangerSecurityZone.SecurityZoneSummary; import org.apache.ranger.plugin.model.RangerSecurityZoneHeaderInfo; import org.apache.ranger.plugin.model.RangerSecurityZoneV2; -import org.apache.ranger.plugin.model.RangerSecurityZone.SecurityZoneSummary; +import org.apache.ranger.plugin.model.RangerSecurityZoneV2.RangerSecurityZoneChangeRequest; +import org.apache.ranger.plugin.model.RangerSecurityZoneV2.RangerSecurityZoneResource; import org.apache.ranger.plugin.model.validation.RangerSecurityZoneValidator; import org.apache.ranger.plugin.model.validation.RangerValidator; +import org.apache.ranger.plugin.store.EmbeddedServiceDefsUtil; import org.apache.ranger.plugin.store.PList; import org.apache.ranger.plugin.util.RangerSecurityZoneHelper; import org.apache.ranger.plugin.util.RangerSecurityZoneHelper.RangerSecurityZoneServiceHelper; import org.apache.ranger.plugin.util.SearchFilter; import org.apache.ranger.service.RangerSecurityZoneServiceService; -import org.apache.ranger.plugin.model.RangerSecurityZone.RangerSecurityZoneService; -import org.apache.ranger.plugin.model.RangerSecurityZoneV2.RangerSecurityZoneChangeRequest; -import org.apache.ranger.plugin.model.RangerSecurityZoneV2.RangerSecurityZoneResource; import org.apache.ranger.view.RangerSecurityZoneList; -import org.apache.ranger.plugin.store.EmbeddedServiceDefsUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -84,13 +57,39 @@ import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; +import javax.persistence.OptimisticLockException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.DefaultValue; +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.WebApplicationException; +import javax.ws.rs.core.Context; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; @Path("zones") @Component @Scope("request") @Transactional(propagation = Propagation.REQUIRES_NEW) public class SecurityZoneREST { - private static final Logger LOG = LoggerFactory.getLogger(SecurityZoneREST.class); + private static final Logger LOG = LoggerFactory.getLogger(SecurityZoneREST.class); + private static final String STR_USER_NOT_AUTHORIZED_TO_ACCESS_ZONE = "User is not authorized to access zone(s)."; private static final String ERR_ANOTHER_SEC_ZONE_OPER_IN_PROGRESS = "Another security zone operation is already in progress"; @@ -107,7 +106,7 @@ public class SecurityZoneREST { ServiceDBStore svcStore; @Autowired - RangerSearchUtil searchUtil; + RangerSearchUtil searchUtil; @Autowired RangerValidatorFactory validatorFactory; @@ -115,25 +114,24 @@ public class SecurityZoneREST { @Autowired RangerBizUtil bizUtil; - @Autowired - ServiceREST serviceRest; + @Autowired + ServiceREST serviceRest; - @Autowired - RangerDaoManager daoManager; + @Autowired + RangerDaoManager daoManager; - @Autowired - ServiceMgr serviceMgr; + @Autowired + ServiceMgr serviceMgr; @POST @Path("/zones") - @Consumes({ "application/json" }) - @Produces({ "application/json" }) + @Consumes("application/json") + @Produces("application/json") public RangerSecurityZone createSecurityZone(RangerSecurityZone securityZone) { - if (LOG.isDebugEnabled()) { - LOG.debug("==> createSecurityZone("+ securityZone + ")"); - } + LOG.debug("==> createSecurityZone({})", securityZone); RangerSecurityZone ret; + try { RangerSecurityZoneHelper zoneHelper = new RangerSecurityZoneHelper(securityZone, bizUtil.getCurrentUserLoginId()); // this populates resourcesBaseInfo @@ -141,35 +139,35 @@ public RangerSecurityZone createSecurityZone(RangerSecurityZone securityZone) { ensureAdminAccess(securityZone); removeEmptyEntries(securityZone); + RangerSecurityZoneValidator validator = validatorFactory.getSecurityZoneValidator(svcStore, securityZoneStore); + validator.validate(securityZone, RangerValidator.Action.CREATE); + ret = securityZoneStore.createSecurityZone(securityZone); } catch (OptimisticLockException | org.eclipse.persistence.exceptions.OptimisticLockException excp) { - LOG.error("createSecurityZone(" + securityZone + ") failed", excp); + LOG.error("createSecurityZone({}) failed", securityZone, excp); throw restErrorUtil.createRESTException(HttpServletResponse.SC_CONFLICT, ERR_ANOTHER_SEC_ZONE_OPER_IN_PROGRESS, true); - } catch(WebApplicationException excp) { + } catch (WebApplicationException excp) { throw excp; - } catch(Throwable excp) { - LOG.error("createSecurityZone(" + securityZone + ") failed", excp); + } catch (Throwable excp) { + LOG.error("createSecurityZone({}) failed:", securityZone, excp); throw restErrorUtil.createRESTException(excp.getMessage()); } - if (LOG.isDebugEnabled()) { - LOG.debug("<== createSecurityZone("+ securityZone + "):" + ret); - } + + LOG.debug("<== createSecurityZone({}):{}", securityZone, ret); + return ret; } @PUT @Path("/zones/{id}") - @Consumes({ "application/json" }) - @Produces({ "application/json" }) - public RangerSecurityZone updateSecurityZone(@PathParam("id") Long zoneId, - RangerSecurityZone securityZone) { - if (LOG.isDebugEnabled()) { - LOG.debug("==> updateSecurityZone(id=" + zoneId +", " + securityZone + ")"); - } + @Consumes("application/json") + @Produces("application/json") + public RangerSecurityZone updateSecurityZone(@PathParam("id") Long zoneId, RangerSecurityZone securityZone) { + LOG.debug("==> updateSecurityZone(id={}, {})", zoneId, securityZone); if (zoneId != null && zoneId.equals(RangerSecurityZone.RANGER_UNZONED_SECURITY_ZONE_ID)) { throw restErrorUtil.createRESTException("Cannot update unzoned zone"); @@ -181,129 +179,130 @@ public RangerSecurityZone updateSecurityZone(@PathParam("id") Long zoneId, ensureUserAllowOperationOnServiceForZone(securityZone); removeEmptyEntries(securityZone); + if (securityZone.getId() != null && !zoneId.equals(securityZone.getId())) { throw restErrorUtil.createRESTException("zoneId mismatch!!"); } else { securityZone.setId(zoneId); } + RangerSecurityZone ret; + try { RangerSecurityZoneValidator validator = validatorFactory.getSecurityZoneValidator(svcStore, securityZoneStore); + validator.validate(securityZone, RangerValidator.Action.UPDATE); + ret = securityZoneStore.updateSecurityZoneById(securityZone); } catch (OptimisticLockException | org.eclipse.persistence.exceptions.OptimisticLockException excp) { - LOG.error("updateSecurityZone(" + securityZone + ") failed", excp); + LOG.error("updateSecurityZone({}) failed", securityZone, excp); throw restErrorUtil.createRESTException(HttpServletResponse.SC_CONFLICT, ERR_ANOTHER_SEC_ZONE_OPER_IN_PROGRESS, true); - } catch(WebApplicationException excp) { + } catch (WebApplicationException excp) { throw excp; - } catch(Throwable excp) { - LOG.error("updateSecurityZone(" + securityZone + ") failed", excp); + } catch (Throwable excp) { + LOG.error("updateSecurityZone({}) failed", securityZone, excp); throw restErrorUtil.createRESTException(excp.getMessage()); } - if (LOG.isDebugEnabled()) { - LOG.debug("<== updateSecurityZone(id=" + zoneId +", " + securityZone + "):" + ret); - } + + LOG.debug("<== updateSecurityZone(id={}, {}):{}", zoneId, securityZone, ret); + return ret; } @DELETE @Path("/zones/name/{name}") public void deleteSecurityZone(@PathParam("name") String zoneName) { - if (LOG.isDebugEnabled()) { - LOG.debug("==> deleteSecurityZone(name=" + zoneName + ")"); - } + LOG.debug("==> deleteSecurityZone(name={})", zoneName); + try { - ensureAdminAccess(); + ensureAdminAccess(); + RangerSecurityZoneValidator validator = validatorFactory.getSecurityZoneValidator(svcStore, securityZoneStore); + validator.validate(zoneName, RangerValidator.Action.DELETE); + securityZoneStore.deleteSecurityZoneByName(zoneName); } catch (OptimisticLockException | org.eclipse.persistence.exceptions.OptimisticLockException excp) { - LOG.error("deleteSecurityZone(" + zoneName + ") failed", excp); + LOG.error("deleteSecurityZone({}) failed", zoneName, excp); throw restErrorUtil.createRESTException(HttpServletResponse.SC_CONFLICT, ERR_ANOTHER_SEC_ZONE_OPER_IN_PROGRESS, true); - } catch(WebApplicationException excp) { + } catch (WebApplicationException excp) { throw excp; - } catch(Throwable excp) { - LOG.error("deleteSecurityZone(" + zoneName + ") failed", excp); + } catch (Throwable excp) { + LOG.error("deleteSecurityZone({}) failed", zoneName, excp); throw restErrorUtil.createRESTException(excp.getMessage()); } - if (LOG.isDebugEnabled()) { - LOG.debug("<== deleteSecurityZone(name=" + zoneName + ")"); - } + + LOG.debug("<== deleteSecurityZone(name=={})", zoneName); } @DELETE @Path("/zones/{id}") public void deleteSecurityZone(@PathParam("id") Long zoneId) { - if (LOG.isDebugEnabled()) { - LOG.debug("==> deleteSecurityZone(id=" + zoneId + ")"); - } + LOG.debug("==> deleteSecurityZone(id={})", zoneId); + if (zoneId != null && zoneId.equals(RangerSecurityZone.RANGER_UNZONED_SECURITY_ZONE_ID)) { throw restErrorUtil.createRESTException("Cannot delete unzoned zone"); } + try { - ensureAdminAccess(); + ensureAdminAccess(); + RangerSecurityZoneValidator validator = validatorFactory.getSecurityZoneValidator(svcStore, securityZoneStore); + validator.validate(zoneId, RangerValidator.Action.DELETE); + securityZoneStore.deleteSecurityZoneById(zoneId); } catch (OptimisticLockException | org.eclipse.persistence.exceptions.OptimisticLockException excp) { - LOG.error("deleteSecurityZone(" + zoneId + ") failed", excp); + LOG.error("deleteSecurityZone({}) failed", zoneId, excp); throw restErrorUtil.createRESTException(HttpServletResponse.SC_CONFLICT, ERR_ANOTHER_SEC_ZONE_OPER_IN_PROGRESS, true); - } catch(WebApplicationException excp) { + } catch (WebApplicationException excp) { throw excp; - } catch(Throwable excp) { - LOG.error("deleteSecurityZone(" + zoneId + ") failed", excp); + } catch (Throwable excp) { + LOG.error("deleteSecurityZone({}) failed", zoneId, excp); - throw restErrorUtil.createRESTException( - "Data Not Found for given Id", - MessageEnums.DATA_NOT_FOUND, zoneId, null, - "readResource : No Object found with given id."); - } - if (LOG.isDebugEnabled()) { - LOG.debug("<== deleteSecurityZone(id=" + zoneId + ")"); + throw restErrorUtil.createRESTException("Data Not Found for given Id", MessageEnums.DATA_NOT_FOUND, zoneId, null, "readResource : No Object found with given id."); } + + LOG.debug("<== deleteSecurityZone(id={})", zoneId); } @GET @Path("/zones/name/{name}") - @Produces({ "application/json" }) + @Produces("application/json") public RangerSecurityZone getSecurityZone(@PathParam("name") String zoneName) { - if (LOG.isDebugEnabled()) { - LOG.debug("==> getSecurityZone(name=" + zoneName + ")"); - } + LOG.debug("==> getSecurityZone(name={})", zoneName); if (!bizUtil.hasModuleAccess(RangerConstants.MODULE_SECURITY_ZONE)) { throw restErrorUtil.createRESTException(STR_USER_NOT_AUTHORIZED_TO_ACCESS_ZONE, MessageEnums.OPER_NO_PERMISSION); } RangerSecurityZone ret; + try { ret = securityZoneStore.getSecurityZoneByName(zoneName); - } catch(WebApplicationException excp) { + } catch (WebApplicationException excp) { throw excp; - } catch(Throwable excp) { - LOG.error("getSecurityZone(" + zoneName + ") failed", excp); + } catch (Throwable excp) { + LOG.error("getSecurityZone({}) failed", zoneName, excp); throw restErrorUtil.createRESTException(excp.getMessage()); } - if (LOG.isDebugEnabled()) { - LOG.debug("<== getSecurityZone(name=" + zoneName + "):" + ret); - } + LOG.debug("<== getSecurityZone(name={}):{}", zoneName, ret); + return ret; } @GET @Path("/zones/{id}") - @Produces({ "application/json" }) + @Produces("application/json") public RangerSecurityZone getSecurityZone(@PathParam("id") Long id) { - if (LOG.isDebugEnabled()) { - LOG.debug("==> getSecurityZone(id=" + id + ")"); - } + LOG.debug("==> getSecurityZone(id={})", id); if (!bizUtil.hasModuleAccess(RangerConstants.MODULE_SECURITY_ZONE)) { throw restErrorUtil.createRESTException(STR_USER_NOT_AUTHORIZED_TO_ACCESS_ZONE, MessageEnums.OPER_NO_PERMISSION); @@ -314,39 +313,39 @@ public RangerSecurityZone getSecurityZone(@PathParam("id") Long id) { } RangerSecurityZone ret; + try { ret = securityZoneStore.getSecurityZone(id); - } catch(WebApplicationException excp) { + } catch (WebApplicationException excp) { throw excp; - } catch(Throwable excp) { - LOG.error("getSecurityZone(" + id + ") failed", excp); + } catch (Throwable excp) { + LOG.error("getSecurityZone({}) failed", id, excp); throw restErrorUtil.createRESTException(excp.getMessage()); } - if (LOG.isDebugEnabled()) { - LOG.debug("<== getSecurityZone(id=" + id + "):" + ret); - } + LOG.debug("<== getSecurityZone(id={}):{}", id, ret); + return ret; } @GET @Path("/zones") - @Produces({ "application/json" }) + @Produces("application/json") public RangerSecurityZoneList getAllZones(@Context HttpServletRequest request) { - if (LOG.isDebugEnabled()) { - LOG.debug("==> getAllZones()"); - } + LOG.debug("==> getAllZones()"); if (!bizUtil.hasModuleAccess(RangerConstants.MODULE_SECURITY_ZONE)) { throw restErrorUtil.createRESTException(STR_USER_NOT_AUTHORIZED_TO_ACCESS_ZONE, MessageEnums.OPER_NO_PERMISSION); } - RangerSecurityZoneList ret = new RangerSecurityZoneList(); - SearchFilter filter = searchUtil.getSearchFilter(request, securityZoneService.sortFields); + RangerSecurityZoneList ret = new RangerSecurityZoneList(); + SearchFilter filter = searchUtil.getSearchFilter(request, securityZoneService.sortFields); try { List securityZones = securityZoneStore.getSecurityZones(filter); + ret.setSecurityZoneList(securityZones); + if (securityZones != null) { ret.setTotalCount(securityZones.size()); ret.setSortBy(filter.getSortBy()); @@ -361,23 +360,19 @@ public RangerSecurityZoneList getAllZones(@Context HttpServletRequest request) { throw restErrorUtil.createRESTException(excp.getMessage()); } - if (LOG.isDebugEnabled()) { - LOG.debug("<== getAllZones():" + ret); - } + LOG.debug("<== getAllZones():{}", ret); + return ret; } @GET @Path("/zone-names/{serviceName}/resource") - @Produces({ "application/json" }) + @Produces("application/json") public Collection getZoneNamesForResource(@PathParam("serviceName") String serviceName, @Context HttpServletRequest request) { - if (LOG.isDebugEnabled()) { - LOG.debug("==> SecurityZoneREST.getZoneNamesForResource(" + serviceName + ")"); - } + LOG.debug("==> SecurityZoneREST.getZoneNamesForResource({})", serviceName); if (!serviceRest.isServiceAdmin(serviceName)) { - throw restErrorUtil.createRESTException(HttpServletResponse.SC_FORBIDDEN, - "User '" + bizUtil.getCurrentUserLoginId() + "' does not have privilege", true); + throw restErrorUtil.createRESTException(HttpServletResponse.SC_FORBIDDEN, "User '" + bizUtil.getCurrentUserLoginId() + "' does not have privilege", true); } Collection ret = null; @@ -390,22 +385,16 @@ public Collection getZoneNamesForResource(@PathParam("serviceName") Stri ret = policyAdmin.getZoneNamesForResource(resource); } - if (LOG.isDebugEnabled()) { - LOG.debug("<== SecurityZoneREST.getZoneNamesForResource(" + serviceName + "): ret=" + ret); - } + LOG.debug("<== SecurityZoneREST.getZoneNamesForResource(serviceName={}):{}", serviceName, ret); return ret; } @GET @Path("/zones/zone-headers/for-service/{serviceId}") - @Produces({ "application/json" }) - public List getSecurityZoneHeaderInfoListByServiceId(@PathParam("serviceId") Long serviceId, - @DefaultValue("false") @QueryParam ("isTagService") Boolean isTagService, - @Context HttpServletRequest request) { - if (LOG.isDebugEnabled()) { - LOG.debug("==> SecurityZoneREST.getSecurityZoneHeaderInfoListByServiceId() serviceId:{}, isTagService:{}",serviceId,isTagService); - } + @Produces("application/json") + public List getSecurityZoneHeaderInfoListByServiceId(@PathParam("serviceId") Long serviceId, @DefaultValue("false") @QueryParam("isTagService") Boolean isTagService, @Context HttpServletRequest request) { + LOG.debug("==> SecurityZoneREST.getSecurityZoneHeaderInfoListByServiceId() serviceId:{}, isTagService:{}", serviceId, isTagService); List ret; @@ -418,27 +407,24 @@ public List getSecurityZoneHeaderInfoListByService throw restErrorUtil.createRESTException(excp.getMessage()); } - if (LOG.isDebugEnabled()) { - LOG.debug("<== SecurityZoneREST.getSecurityZoneHeaderInfoListByServiceId():" + ret); - } + LOG.debug("<== SecurityZoneREST.getSecurityZoneHeaderInfoListByServiceId():{}", ret); return ret; } @GET @Path("/summary") - @Produces({ "application/json" }) + @Produces("application/json") public PList getZonesSummary(@Context HttpServletRequest request) { - if (LOG.isDebugEnabled()) { - LOG.debug("==> getZonesSummary()"); - } + LOG.debug("==> getZonesSummary()"); if (!bizUtil.hasModuleAccess(RangerConstants.MODULE_SECURITY_ZONE)) { throw restErrorUtil.createRESTException(STR_USER_NOT_AUTHORIZED_TO_ACCESS_ZONE, MessageEnums.OPER_NO_PERMISSION); } - PList ret = null; - SearchFilter filter = searchUtil.getSearchFilter(request, securityZoneService.sortFields); + PList ret; + SearchFilter filter = searchUtil.getSearchFilter(request, securityZoneService.sortFields); + try { ret = securityZoneStore.getZonesSummary(filter); } catch (WebApplicationException excp) { @@ -449,9 +435,8 @@ public PList getZonesSummary(@Context HttpServletRequest re throw restErrorUtil.createRESTException(excp.getMessage()); } - if (LOG.isDebugEnabled()) { - LOG.debug("<== getZonesSummary():" + ret); - } + LOG.debug("<== getZonesSummary():{}", ret); + return ret; } @@ -486,8 +471,8 @@ public Boolean updateSecurityZone(Long zoneId, RangerSecurityZoneChangeRequest c RangerSecurityZone zone = getSecurityZone(zoneId); RangerSecurityZoneHelper zoneHelper = new RangerSecurityZoneHelper(zone, bizUtil.getCurrentUserLoginId()); RangerSecurityZone updatedZone = zoneHelper.updateZone(changeData); + RangerSecurityZone retV1 = updateSecurityZone(zoneId, updatedZone); - RangerSecurityZone retV1 = updateSecurityZone(zoneId, updatedZone); ret = retV1 != null; } catch (WebApplicationException excp) { throw excp; @@ -571,221 +556,191 @@ public PList getAllZonesV2(HttpServletRequest request) { return ret; } - private void ensureAdminAccess(){ - if(!bizUtil.isAdmin()){ - String userName = bizUtil.getCurrentUserLoginId(); - throw restErrorUtil.createRESTException(HttpServletResponse.SC_FORBIDDEN, "Ranger Security Zone is not accessible for user '" + userName + "'.", true); - } - } - - private void ensureUserAllowOperationOnServiceForZone( - RangerSecurityZone securityZone){ - if (!bizUtil.isAdmin()) { - String userName = bizUtil.getCurrentUserLoginId(); - RangerSecurityZone existingSecurityZone = null; - try { - existingSecurityZone = svcStore - .getSecurityZone(securityZone.getId()); - } catch (Exception ex) { - LOG.error("Unable to get Security Zone with id : " + securityZone.getId(), ex); - throw restErrorUtil.createRESTException(ex.getMessage()); - } - if (existingSecurityZone != null) { - /* Validation for non service related fields of security zone */ - - - if (!Objects.equals(securityZone.getName(), existingSecurityZone.getName())) { - throwRestError("User : " + userName - + " is not allowed to edit zone name of zone : " + existingSecurityZone.getName()); - } else if (!Objects.equals(securityZone.getDescription(), existingSecurityZone.getDescription())) { - throwRestError("User : " + userName - + " is not allowed to edit zone description of zone : " + existingSecurityZone.getName()); - } - if (!serviceMgr.isZoneAdmin(existingSecurityZone.getName())) { - if (!Objects.equals(securityZone.getAdminUserGroups(), existingSecurityZone.getAdminUserGroups())) { - throwRestError("User : " - + userName - + " is not allowed to edit zone Admin User Group of zone : " + existingSecurityZone.getName()); - } else if (!Objects.equals(securityZone.getAdminUsers(), existingSecurityZone.getAdminUsers())) { - throwRestError("User : " + userName - + " is not allowed to edit zone Admin User of zone : " + existingSecurityZone.getName()); + private void ensureAdminAccess() { + if (!bizUtil.isAdmin()) { + String userName = bizUtil.getCurrentUserLoginId(); + + throw restErrorUtil.createRESTException(HttpServletResponse.SC_FORBIDDEN, "Ranger Security Zone is not accessible for user '" + userName + "'.", true); + } + } + + private void ensureUserAllowOperationOnServiceForZone(RangerSecurityZone securityZone) { + if (!bizUtil.isAdmin()) { + String userName = bizUtil.getCurrentUserLoginId(); + RangerSecurityZone existingSecurityZone; + + try { + existingSecurityZone = svcStore.getSecurityZone(securityZone.getId()); + } catch (Exception ex) { + LOG.error("Unable to get Security Zone with id : {}", securityZone.getId(), ex); + + throw restErrorUtil.createRESTException(ex.getMessage()); + } + + if (existingSecurityZone != null) { + /* Validation for non service related fields of security zone */ + if (!Objects.equals(securityZone.getName(), existingSecurityZone.getName())) { + throwRestError("User : " + userName + " is not allowed to edit zone name of zone : " + existingSecurityZone.getName()); + } else if (!Objects.equals(securityZone.getDescription(), existingSecurityZone.getDescription())) { + throwRestError("User : " + userName + " is not allowed to edit zone description of zone : " + existingSecurityZone.getName()); + } + + if (!serviceMgr.isZoneAdmin(existingSecurityZone.getName())) { + if (!Objects.equals(securityZone.getAdminUserGroups(), existingSecurityZone.getAdminUserGroups())) { + throwRestError("User : " + userName + " is not allowed to edit zone Admin User Group of zone : " + existingSecurityZone.getName()); + } else if (!Objects.equals(securityZone.getAdminUsers(), existingSecurityZone.getAdminUsers())) { + throwRestError("User : " + userName + " is not allowed to edit zone Admin User of zone : " + existingSecurityZone.getName()); } else if (!Objects.equals(securityZone.getAdminRoles(), existingSecurityZone.getAdminRoles())) { - throwRestError("User : " + userName - + " is not allowed to edit zone Admin Roles of zone : " + existingSecurityZone.getName()); - } else if (!Objects.equals(securityZone.getAuditUsers(), existingSecurityZone.getAuditUsers())) { - throwRestError("User : " + userName - + " is not allowed to edit zone Audit User of zone : " + existingSecurityZone.getName()); - } else if (!Objects.equals(securityZone.getAuditUserGroups(), existingSecurityZone.getAuditUserGroups())) { - throwRestError("User : " - + userName - + " is not allowed to edit zone Audit User Group of zone : " + existingSecurityZone.getName()); + throwRestError("User : " + userName + " is not allowed to edit zone Admin Roles of zone : " + existingSecurityZone.getName()); + } else if (!Objects.equals(securityZone.getAuditUsers(), existingSecurityZone.getAuditUsers())) { + throwRestError("User : " + userName + " is not allowed to edit zone Audit User of zone : " + existingSecurityZone.getName()); + } else if (!Objects.equals(securityZone.getAuditUserGroups(), existingSecurityZone.getAuditUserGroups())) { + throwRestError("User : " + userName + " is not allowed to edit zone Audit User Group of zone : " + existingSecurityZone.getName()); } else if (!Objects.equals(securityZone.getAuditRoles(), existingSecurityZone.getAuditRoles())) { - throwRestError("User : " - + userName - + " is not allowed to edit zone Audit Roles of zone : " + existingSecurityZone.getName()); - } - } - - /* - * Validation on tag service association / disassociation with - * security zone - * */ - - List dbTagServices = existingSecurityZone - .getTagServices(); - List uiTagServices = securityZone.getTagServices(); - List addRmvTagSvc = new ArrayList(); - if (!dbTagServices.equals(uiTagServices)) { - for (String svc : dbTagServices) { - if (!uiTagServices.contains(svc)) { - addRmvTagSvc.add(svc); - } - } - - for (String svc : uiTagServices) { - if (!dbTagServices.contains(svc)) { - addRmvTagSvc.add(svc); - } - } - } - if (!addRmvTagSvc.isEmpty()) { - for (String svc : addRmvTagSvc) { - /* - * if user is neither svc admin nor admin then - * add/remove of svc in zone is not allowed - */ - if (!svcStore.isServiceAdminUser(svc, userName)) { - throwRestError("User : " - + userName - + " is not allowed to add/remove tag service : " - + svc + " in Ranger Security zone : " + existingSecurityZone.getName()); - - } - } - } - - - /* - * Validation on service association / disassociation with - * security zone - */ - Set existingRangerSecurityZoneService = existingSecurityZone - .getServices().keySet(); - Set newRangerSecurityZoneService = securityZone.getServices() - .keySet(); - Set diffServiceSet = new HashSet<>(Sets.difference( - newRangerSecurityZoneService, - existingRangerSecurityZoneService)); - diffServiceSet.addAll(Sets.difference( - existingRangerSecurityZoneService, - newRangerSecurityZoneService)); - - if (diffServiceSet != null && diffServiceSet.size() > 0) { - for (String svc : diffServiceSet) { - /* - * if user is neither svc admin nor admin then - * add/remove of svc in zone is not allowed - */ - if (!svcStore.isServiceAdminUser(svc, userName)) { - throwRestError("User : " - + userName - + " is not allowed to add/remove service : " - + svc + " in Ranger Security zone : " + existingSecurityZone.getName()); - - } - } - } - - /* Validation for resources on existing svc in security zone */ - for (String svc : existingRangerSecurityZoneService) { - RangerSecurityZoneService rangerSecurityZnSvcFromDB = existingSecurityZone - .getServices().get(svc); - - RangerSecurityZoneService rangerSecurityZnSvcFromUI = securityZone - .getServices().get(svc); - - if (rangerSecurityZnSvcFromUI != null) { - if (!Objects.equals(rangerSecurityZnSvcFromDB.getResources(), rangerSecurityZnSvcFromUI.getResources())) { - if (!svcStore.isServiceAdminUser(svc, userName)) { - throwRestError("User : " - + userName - + " is not allowed to edit resource in service : " - + svc + " in Ranger Security zone : " + existingSecurityZone.getName()); - } - } - } - - } - } - - } - } - - private void throwRestError(String message){ - throw restErrorUtil.createRESTException(HttpServletResponse.SC_FORBIDDEN, message, true); - } - - - private void ensureAdminAccess(RangerSecurityZone securityZone) { - if (!bizUtil.isAdmin()) { - String userName = bizUtil.getCurrentUserLoginId(); - throw restErrorUtil.createRESTException( - "Ranger Securtiy Zone is not accessible for user '" + userName + "'.", - MessageEnums.OPER_NO_PERMISSION); - } - else { - blockAdminFromKMSService(securityZone); - } - } - - private void blockAdminFromKMSService(RangerSecurityZone securityZone) { - if(securityZone != null) { - Map serviceMap = securityZone.getServices(); - if (serviceMap != null) { - for (String serviceName : serviceMap.keySet()) { - XXService xService = daoManager.getXXService().findByName(serviceName); - if (xService != null) { - XXServiceDef xServiceDef = daoManager.getXXServiceDef().getById(xService.getType()); - if (EmbeddedServiceDefsUtil.KMS_IMPL_CLASS_NAME.equals(xServiceDef.getImplclassname())) { - throw restErrorUtil.createRESTException( - "KMS Services/Service-Defs are not accessible for Zone operations", - MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY); - } - } - } - } - } - } - - private void removeEmptyEntries(RangerSecurityZone securityZone) { - bizUtil.removeEmptyStrings(securityZone.getTagServices()); - bizUtil.removeEmptyStrings(securityZone.getAdminUsers()); - bizUtil.removeEmptyStrings(securityZone.getAdminUserGroups()); + throwRestError("User : " + userName + " is not allowed to edit zone Audit Roles of zone : " + existingSecurityZone.getName()); + } + } + + /* + * Validation on tag service association / disassociation with + * security zone + * */ + + List dbTagServices = existingSecurityZone.getTagServices(); + List uiTagServices = securityZone.getTagServices(); + List addRmvTagSvc = new ArrayList<>(); + + if (!dbTagServices.equals(uiTagServices)) { + for (String svc : dbTagServices) { + if (!uiTagServices.contains(svc)) { + addRmvTagSvc.add(svc); + } + } + + for (String svc : uiTagServices) { + if (!dbTagServices.contains(svc)) { + addRmvTagSvc.add(svc); + } + } + } + + if (!addRmvTagSvc.isEmpty()) { + for (String svc : addRmvTagSvc) { + /* + * if user is neither svc admin nor admin then + * add/remove of svc in zone is not allowed + */ + if (!svcStore.isServiceAdminUser(svc, userName)) { + throwRestError("User : " + userName + " is not allowed to add/remove tag service : " + svc + " in Ranger Security zone : " + existingSecurityZone.getName()); + } + } + } + + /* + * Validation on service association / disassociation with + * security zone + */ + Set existingRangerSecurityZoneService = existingSecurityZone.getServices().keySet(); + Set newRangerSecurityZoneService = securityZone.getServices().keySet(); + Set diffServiceSet = new HashSet<>(Sets.difference(newRangerSecurityZoneService, existingRangerSecurityZoneService)); + + diffServiceSet.addAll(Sets.difference(existingRangerSecurityZoneService, newRangerSecurityZoneService)); + + if (!diffServiceSet.isEmpty()) { + for (String svc : diffServiceSet) { + /* + * if user is neither svc admin nor admin then + * add/remove of svc in zone is not allowed + */ + if (!svcStore.isServiceAdminUser(svc, userName)) { + throwRestError("User : " + userName + " is not allowed to add/remove service : " + svc + " in Ranger Security zone : " + existingSecurityZone.getName()); + } + } + } + + /* Validation for resources on existing svc in security zone */ + for (String svc : existingRangerSecurityZoneService) { + RangerSecurityZoneService rangerSecurityZnSvcFromDB = existingSecurityZone.getServices().get(svc); + RangerSecurityZoneService rangerSecurityZnSvcFromUI = securityZone.getServices().get(svc); + + if (rangerSecurityZnSvcFromUI != null) { + if (!Objects.equals(rangerSecurityZnSvcFromDB.getResources(), rangerSecurityZnSvcFromUI.getResources())) { + if (!svcStore.isServiceAdminUser(svc, userName)) { + throwRestError("User : " + userName + " is not allowed to edit resource in service : " + svc + " in Ranger Security zone : " + existingSecurityZone.getName()); + } + } + } + } + } + } + } + + private void throwRestError(String message) { + throw restErrorUtil.createRESTException(HttpServletResponse.SC_FORBIDDEN, message, true); + } + + private void ensureAdminAccess(RangerSecurityZone securityZone) { + if (!bizUtil.isAdmin()) { + String userName = bizUtil.getCurrentUserLoginId(); + + throw restErrorUtil.createRESTException("Ranger Security Zone is not accessible for user '" + userName + "'.", MessageEnums.OPER_NO_PERMISSION); + } else { + blockAdminFromKMSService(securityZone); + } + } + + private void blockAdminFromKMSService(RangerSecurityZone securityZone) { + if (securityZone != null) { + Map serviceMap = securityZone.getServices(); + + if (serviceMap != null) { + for (String serviceName : serviceMap.keySet()) { + XXService xService = daoManager.getXXService().findByName(serviceName); + + if (xService != null) { + XXServiceDef xServiceDef = daoManager.getXXServiceDef().getById(xService.getType()); + + if (EmbeddedServiceDefsUtil.KMS_IMPL_CLASS_NAME.equals(xServiceDef.getImplclassname())) { + throw restErrorUtil.createRESTException("KMS Services/Service-Defs are not accessible for Zone operations", MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY); + } + } + } + } + } + } + + private void removeEmptyEntries(RangerSecurityZone securityZone) { + bizUtil.removeEmptyStrings(securityZone.getTagServices()); + bizUtil.removeEmptyStrings(securityZone.getAdminUsers()); + bizUtil.removeEmptyStrings(securityZone.getAdminUserGroups()); bizUtil.removeEmptyStrings(securityZone.getAdminRoles()); - bizUtil.removeEmptyStrings(securityZone.getAuditUsers()); - bizUtil.removeEmptyStrings(securityZone.getAuditUserGroups()); + bizUtil.removeEmptyStrings(securityZone.getAuditUsers()); + bizUtil.removeEmptyStrings(securityZone.getAuditUserGroups()); bizUtil.removeEmptyStrings(securityZone.getAdminRoles()); - Map serviceResouceMap=securityZone.getServices(); - if(serviceResouceMap!=null) { - Set> serviceResouceMapEntries = serviceResouceMap.entrySet(); - Iterator> iterator=serviceResouceMapEntries.iterator(); - while (iterator.hasNext()){ - Map.Entry serviceResouceMapEntry = iterator.next(); - RangerSecurityZoneService rangerSecurityZoneService=serviceResouceMapEntry.getValue(); - List>> resources=rangerSecurityZoneService.getResources(); - if(resources!=null) { - for (Map> resource : resources) { - if (resource!=null) { - for (Map.Entry> entry : resource.entrySet()) { - List resourceValues = entry.getValue(); - bizUtil.removeEmptyStrings(resourceValues); - } - } - } - } - } - } - } + + Map serviceResouceMap = securityZone.getServices(); + + if (serviceResouceMap != null) { + Set> serviceResouceMapEntries = serviceResouceMap.entrySet(); + + for (Map.Entry serviceResouceMapEntry : serviceResouceMapEntries) { + RangerSecurityZoneService rangerSecurityZoneService = serviceResouceMapEntry.getValue(); + List>> resources = rangerSecurityZoneService.getResources(); + + if (resources != null) { + for (Map> resource : resources) { + if (resource != null) { + for (Map.Entry> entry : resource.entrySet()) { + List resourceValues = entry.getValue(); + + bizUtil.removeEmptyStrings(resourceValues); + } + } + } + } + } + } + } private PList getResources(RangerSecurityZone zone, String serviceName, @Context HttpServletRequest request) { RangerSecurityZoneHelper zoneHelper = new RangerSecurityZoneHelper(zone, bizUtil.getCurrentUserLoginId()); diff --git a/security-admin/src/main/java/org/apache/ranger/rest/ServiceREST.java b/security-admin/src/main/java/org/apache/ranger/rest/ServiceREST.java index 9d27309371..fb1a729952 100644 --- a/security-admin/src/main/java/org/apache/ranger/rest/ServiceREST.java +++ b/security-admin/src/main/java/org/apache/ranger/rest/ServiceREST.java @@ -19,31 +19,9 @@ package org.apache.ranger.rest; -import java.io.IOException; -import java.io.InputStream; -import java.security.SecureRandom; -import java.util.*; -import java.util.Map.Entry; -import java.util.stream.IntStream; - -import javax.annotation.Nonnull; -import javax.annotation.PostConstruct; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.ws.rs.Consumes; -import javax.ws.rs.DELETE; -import javax.ws.rs.DefaultValue; -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.WebApplicationException; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.MediaType; - +import com.google.gson.JsonSyntaxException; +import com.sun.jersey.core.header.FormDataContentDisposition; +import com.sun.jersey.multipart.FormDataParam; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.MapUtils; import org.apache.commons.io.IOUtils; @@ -55,8 +33,8 @@ import org.apache.ranger.authorization.utils.StringUtil; import org.apache.ranger.biz.AssetMgr; import org.apache.ranger.biz.PolicyRefUpdater; -import org.apache.ranger.biz.RangerPolicyAdmin; import org.apache.ranger.biz.RangerBizUtil; +import org.apache.ranger.biz.RangerPolicyAdmin; import org.apache.ranger.biz.RangerPolicyAdminCacheForEngineOptions; import org.apache.ranger.biz.RoleDBStore; import org.apache.ranger.biz.SecurityZoneDBStore; @@ -79,19 +57,28 @@ import org.apache.ranger.common.UserSessionBase; import org.apache.ranger.common.db.RangerTransactionSynchronizationAdapter; import org.apache.ranger.db.RangerDaoManager; +import org.apache.ranger.db.XXRoleDao; import org.apache.ranger.entity.XXPolicy; import org.apache.ranger.entity.XXPolicyExportAudit; +import org.apache.ranger.entity.XXPolicyLabel; +import org.apache.ranger.entity.XXRole; import org.apache.ranger.entity.XXSecurityZone; import org.apache.ranger.entity.XXSecurityZoneRefService; import org.apache.ranger.entity.XXSecurityZoneRefTagService; import org.apache.ranger.entity.XXService; import org.apache.ranger.entity.XXServiceDef; import org.apache.ranger.entity.XXTrxLogV2; -import org.apache.ranger.entity.XXRole; -import org.apache.ranger.plugin.model.*; +import org.apache.ranger.plugin.model.RangerPluginInfo; +import org.apache.ranger.plugin.model.RangerPolicy; import org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyItem; import org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyItemAccess; import org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyResource; +import org.apache.ranger.plugin.model.RangerPolicyDelta; +import org.apache.ranger.plugin.model.RangerPolicyResourceSignature; +import org.apache.ranger.plugin.model.RangerService; +import org.apache.ranger.plugin.model.RangerServiceDef; +import org.apache.ranger.plugin.model.RangerServiceHeaderInfo; +import org.apache.ranger.plugin.model.ServiceDeleteResponse; import org.apache.ranger.plugin.model.validation.RangerPolicyValidator; import org.apache.ranger.plugin.model.validation.RangerServiceDefHelper; import org.apache.ranger.plugin.model.validation.RangerServiceDefValidator; @@ -140,4533 +127,4528 @@ import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; -import com.google.gson.JsonSyntaxException; -import com.sun.jersey.core.header.FormDataContentDisposition; -import com.sun.jersey.multipart.FormDataParam; +import javax.annotation.Nonnull; +import javax.annotation.PostConstruct; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.DefaultValue; +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.WebApplicationException; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; -import static org.apache.ranger.plugin.store.EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_GDS_NAME; +import java.io.IOException; +import java.io.InputStream; +import java.security.SecureRandom; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Comparator; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.ListIterator; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Objects; +import java.util.Set; +import java.util.TreeMap; +import java.util.stream.IntStream; +import static org.apache.ranger.plugin.store.EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_GDS_NAME; @Path("plugins") @Component @Scope("request") @Transactional(propagation = Propagation.REQUIRES_NEW) public class ServiceREST { - private static final Logger LOG = LoggerFactory.getLogger(ServiceREST.class); - private static final Logger PERF_LOG = RangerPerfTracer.getPerfLogger("rest.ServiceREST"); - - final static public String PARAM_SERVICE_NAME = "serviceName"; - final static public String PARAM_SERVICE_TYPE = "serviceType"; - final static public String PARAM_POLICY_NAME = "policyName"; - final static public String PARAM_ZONE_NAME = "zoneName"; - final static public String PARAM_UPDATE_IF_EXISTS = "updateIfExists"; - final static public String PARAM_MERGE_IF_EXISTS = "mergeIfExists"; - final static public String PARAM_DELETE_IF_EXISTS = "deleteIfExists"; - final static public String PARAM_IMPORT_IN_PROGRESS = "importInProgress"; - public static final String Allowed_User_List_For_Download = "policy.download.auth.users"; - public static final String Allowed_User_List_For_Grant_Revoke = "policy.grantrevoke.auth.users"; - - public static final String isCSRF_ENABLED = "ranger.rest-csrf.enabled"; - public static final String BROWSER_USER_AGENT_PARAM = "ranger.rest-csrf.browser-useragents-regex"; - public static final String CUSTOM_METHODS_TO_IGNORE_PARAM = "ranger.rest-csrf.methods-to-ignore"; - public static final String CUSTOM_HEADER_PARAM = "ranger.rest-csrf.custom-header"; - public static final String CSRF_TOKEN_LENGTH = "ranger.rest-csrf.token.length"; - final static public String POLICY_MATCHING_ALGO_BY_POLICYNAME = "matchByName"; - final static public String POLICY_MATCHING_ALGO_BY_RESOURCE = "matchByPolicySignature"; - final static public String PARAM_POLICY_MATCHING_ALGORITHM = "policyMatchingAlgorithm"; - - public static final String PURGE_RECORD_TYPE_LOGIN_LOGS = "login_records"; - public static final String PURGE_RECORD_TYPE_TRX_LOGS = "trx_records"; - public static final String PURGE_RECORD_TYPE_POLICY_EXPORT_LOGS = "policy_export_logs"; - - @Autowired - RESTErrorUtil restErrorUtil; - - @Autowired - ServiceMgr serviceMgr; - - @Autowired - XUserService xUserService; - - @Autowired - AssetMgr assetMgr; - - @Autowired - XUserMgr userMgr; - - @Autowired - ServiceDBStore svcStore; - - @Autowired - RoleDBStore roleDBStore; - - @Autowired - SecurityZoneDBStore zoneStore; - - @Autowired - ServiceUtil serviceUtil; - - @Autowired - RangerPolicyService policyService; - - @Autowired - RangerPolicyLabelsService policyLabelsService; - - @Autowired - RangerServiceService svcService; - - @Autowired - RangerServiceDefService serviceDefService; - - @Autowired + private static final Logger LOG = LoggerFactory.getLogger(ServiceREST.class); + private static final Logger PERF_LOG = RangerPerfTracer.getPerfLogger("rest.ServiceREST"); + + public static final String PARAM_SERVICE_NAME = "serviceName"; + public static final String PARAM_SERVICE_TYPE = "serviceType"; + public static final String PARAM_POLICY_NAME = "policyName"; + public static final String PARAM_ZONE_NAME = "zoneName"; + public static final String PARAM_UPDATE_IF_EXISTS = "updateIfExists"; + public static final String PARAM_MERGE_IF_EXISTS = "mergeIfExists"; + public static final String PARAM_DELETE_IF_EXISTS = "deleteIfExists"; + public static final String PARAM_IMPORT_IN_PROGRESS = "importInProgress"; + public static final String Allowed_User_List_For_Download = "policy.download.auth.users"; + public static final String Allowed_User_List_For_Grant_Revoke = "policy.grantrevoke.auth.users"; + public static final String isCSRF_ENABLED = "ranger.rest-csrf.enabled"; + public static final String BROWSER_USER_AGENT_PARAM = "ranger.rest-csrf.browser-useragents-regex"; + public static final String CUSTOM_METHODS_TO_IGNORE_PARAM = "ranger.rest-csrf.methods-to-ignore"; + public static final String CUSTOM_HEADER_PARAM = "ranger.rest-csrf.custom-header"; + public static final String CSRF_TOKEN_LENGTH = "ranger.rest-csrf.token.length"; + public static final String POLICY_MATCHING_ALGO_BY_POLICYNAME = "matchByName"; + public static final String POLICY_MATCHING_ALGO_BY_RESOURCE = "matchByPolicySignature"; + public static final String PARAM_POLICY_MATCHING_ALGORITHM = "policyMatchingAlgorithm"; + public static final String PURGE_RECORD_TYPE_LOGIN_LOGS = "login_records"; + public static final String PURGE_RECORD_TYPE_TRX_LOGS = "trx_records"; + public static final String PURGE_RECORD_TYPE_POLICY_EXPORT_LOGS = "policy_export_logs"; + + private final RangerAdminConfig config = RangerAdminConfig.getInstance(); + private final int maxPolicyNameLength = config.getInt("ranger.policyname.maxlength", 255); + private final boolean isPolicyNameLengthValidationEnabled = config.getBoolean("ranger.policyname.maxlength.validation.enabled", true); + + @Autowired + RESTErrorUtil restErrorUtil; + + @Autowired + ServiceMgr serviceMgr; + + @Autowired + XUserService xUserService; + + @Autowired + AssetMgr assetMgr; + + @Autowired + XUserMgr userMgr; + + @Autowired + ServiceDBStore svcStore; + + @Autowired + RoleDBStore roleDBStore; + + @Autowired + SecurityZoneDBStore zoneStore; + + @Autowired + ServiceUtil serviceUtil; + + @Autowired + RangerPolicyService policyService; + + @Autowired + RangerPolicyLabelsService policyLabelsService; + + @Autowired + RangerServiceService svcService; + + @Autowired + RangerServiceDefService serviceDefService; + + @Autowired RangerPluginInfoService pluginInfoService; - @Autowired - RangerSearchUtil searchUtil; - + @Autowired + RangerSearchUtil searchUtil; + @Autowired RangerBizUtil bizUtil; - @Autowired - GUIDUtil guidUtil; - - @Autowired - RangerValidatorFactory validatorFactory; - - @Autowired - RangerDaoManager daoManager; - - @Autowired - TagDBStore tagStore; - - @Autowired - RangerTransactionSynchronizationAdapter rangerTransactionSynchronizationAdapter; - - private RangerPolicyEngineOptions delegateAdminOptions; - private RangerPolicyEngineOptions policySearchAdminOptions; - private RangerPolicyEngineOptions defaultAdminOptions; - private final RangerAdminConfig config = RangerAdminConfig.getInstance(); - - private final int maxPolicyNameLength = config.getInt("ranger.policyname.maxlength", 255); - private final boolean isPolicyNameLengthValidationEnabled = config.getBoolean("ranger.policyname.maxlength.validation.enabled", true); - - public ServiceREST() { - } - - @PostConstruct - public void initStore() { - tagStore.setServiceStore(svcStore); - delegateAdminOptions = getDelegatedAdminPolicyEngineOptions(); - policySearchAdminOptions = getPolicySearchRangerAdminPolicyEngineOptions(); - defaultAdminOptions = getDefaultRangerAdminPolicyEngineOptions(); - } - - @POST - @Path("/definitions") - @Consumes({ "application/json" }) - @Produces({ "application/json" }) - @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.CREATE_SERVICE_DEF + "\")") - public RangerServiceDef createServiceDef(RangerServiceDef serviceDef) { - if(LOG.isDebugEnabled()) { - LOG.debug("==> ServiceREST.createServiceDef(" + serviceDef + ")"); - } - - RangerServiceDef ret = null; - RangerPerfTracer perf = null; - - /** - * If display name is blank (EMPTY String or NULL), use name. - */ - if (StringUtils.isBlank(serviceDef.getDisplayName())) { - serviceDef.setDisplayName(serviceDef.getName()); - } - - try { - if(RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { - perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "ServiceREST.createServiceDef(serviceDefName=" + serviceDef.getName() + ")"); - } - RangerServiceDefValidator validator = validatorFactory.getServiceDefValidator(svcStore); - validator.validate(serviceDef, Action.CREATE); - - bizUtil.hasAdminPermissions("Service-Def"); - bizUtil.hasKMSPermissions("Service-Def", serviceDef.getImplClass()); - bizUtil.blockAuditorRoleUser(); - ret = svcStore.createServiceDef(serviceDef); - } catch(WebApplicationException excp) { - throw excp; - } catch(Throwable excp) { - LOG.error("createServiceDef(" + serviceDef + ") failed", excp); - - throw restErrorUtil.createRESTException(excp.getMessage()); - } finally { - RangerPerfTracer.log(perf); - } - - if(LOG.isDebugEnabled()) { - LOG.debug("<== ServiceREST.createServiceDef(" + serviceDef + "): " + ret); - } - - return ret; - } - - @PUT - @Path("/definitions/{id}") - @Consumes({ "application/json" }) - @Produces({ "application/json" }) - @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.UPDATE_SERVICE_DEF + "\")") - public RangerServiceDef updateServiceDef(RangerServiceDef serviceDef, @PathParam("id") Long id) { - if(LOG.isDebugEnabled()) { - LOG.debug("==> ServiceREST.updateServiceDef(serviceDefName=" + serviceDef.getName() + ")"); - } - - // if serviceDef.id and param 'id' are specified, serviceDef.id should be same as the param 'id' - // if serviceDef.id is null, then set param 'id' into serviceDef Object - if (serviceDef.getId() == null) { - serviceDef.setId(id); - } else if(StringUtils.isBlank(serviceDef.getName()) && !serviceDef.getId().equals(id)) { - throw restErrorUtil.createRESTException(HttpServletResponse.SC_BAD_REQUEST , "serviceDef Id mismatch", true); - } - - RangerServiceDef ret = null; - RangerPerfTracer perf = null; - - try { - if(RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { - perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "ServiceREST.updateServiceDef(" + serviceDef.getName() + ")"); - } - - /** - * If display name is blank (EMPTY String or NULL), use previous display name. - */ - if (StringUtils.isBlank(serviceDef.getDisplayName())) { - RangerServiceDef rangerServiceDef = svcStore.getServiceDef(serviceDef.getId()); - - // If previous display name is blank (EMPTY String or NULL), user name. - if (Objects.isNull(rangerServiceDef) || StringUtils.isBlank(rangerServiceDef.getDisplayName())) { - serviceDef.setDisplayName(serviceDef.getName()); - } else { - serviceDef.setDisplayName(rangerServiceDef.getDisplayName()); - } - } - - RangerServiceDefValidator validator = validatorFactory.getServiceDefValidator(svcStore); - validator.validate(serviceDef, Action.UPDATE); - - bizUtil.hasAdminPermissions("Service-Def"); - bizUtil.hasKMSPermissions("Service-Def", serviceDef.getImplClass()); - bizUtil.blockAuditorRoleUser(); - ret = svcStore.updateServiceDef(serviceDef); - } catch(WebApplicationException excp) { - throw excp; - } catch(Throwable excp) { - LOG.error("updateServiceDef(" + serviceDef + ") failed", excp); - - throw restErrorUtil.createRESTException(excp.getMessage()); - } finally { - RangerPerfTracer.log(perf); - } - - if(LOG.isDebugEnabled()) { - LOG.debug("<== ServiceREST.updateServiceDef(" + serviceDef + "): " + ret); - } - - return ret; - } - - @DELETE - @Path("/definitions/{id}") - @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.DELETE_SERVICE_DEF + "\")") - public void deleteServiceDef(@PathParam("id") Long id, @Context HttpServletRequest request) { - if(LOG.isDebugEnabled()) { - LOG.debug("==> ServiceREST.deleteServiceDef(" + id + ")"); - } - RangerPerfTracer perf = null; - - try { - if(RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { - perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "ServiceREST.deleteServiceDef(serviceDefId=" + id + ")"); - } - RangerServiceDefValidator validator = validatorFactory.getServiceDefValidator(svcStore); - validator.validate(id, Action.DELETE); - - bizUtil.hasAdminPermissions("Service-Def"); - XXServiceDef xServiceDef = daoManager.getXXServiceDef().getById(id); - if (xServiceDef != null) { - bizUtil.hasKMSPermissions("Service-Def", xServiceDef.getImplclassname()); - - String forceDeleteStr = request.getParameter("forceDelete"); - boolean forceDelete = false; - if (!StringUtils.isEmpty(forceDeleteStr) && "true".equalsIgnoreCase(forceDeleteStr)) { - forceDelete = true; - } - - svcStore.deleteServiceDef(id, forceDelete); - } else { - LOG.error("Cannot retrieve service-definition:[" + id + "] for deletion"); - throw new Exception("deleteServiceDef(" + id + ") failed"); - } - } catch(WebApplicationException excp) { - throw excp; - } catch(Throwable excp) { - LOG.error("deleteServiceDef(" + id + ") failed", excp); - - throw restErrorUtil.createRESTException(excp.getMessage()); - } finally { - RangerPerfTracer.log(perf); - } - - if(LOG.isDebugEnabled()) { - LOG.debug("<== ServiceREST.deleteServiceDef(" + id + ")"); - } - } - - @GET - @Path("/definitions/{id}") - @Produces({ "application/json" }) - @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.GET_SERVICE_DEF + "\")") - public RangerServiceDef getServiceDef(@PathParam("id") Long id) { - if(LOG.isDebugEnabled()) { - LOG.debug("==> ServiceREST.getServiceDef(" + id + ")"); - } - - RangerServiceDef ret = null; - RangerPerfTracer perf = null; - - try { - if(RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { - perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "ServiceREST.getServiceDef(serviceDefId=" + id + ")"); - } - XXServiceDef xServiceDef = daoManager.getXXServiceDef().getById(id); - if (xServiceDef != null) { - if (EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_TAG_NAME.equals(xServiceDef.getName())) { - if (!bizUtil.hasModuleAccess(RangerConstants.MODULE_TAG_BASED_POLICIES)) { - throw restErrorUtil.createRESTException(HttpServletResponse.SC_FORBIDDEN, - "User is not having permissions on the tag module.", true); - } - } - if (!bizUtil.hasAccess(xServiceDef, null)) { - throw restErrorUtil.createRESTException( - "User is not allowed to access service-def, id: " + xServiceDef.getId(), - MessageEnums.OPER_NO_PERMISSION); - } - } - - ret = svcStore.getServiceDef(id); - } catch(WebApplicationException excp) { - throw excp; - } catch(Throwable excp) { - LOG.error("getServiceDef(" + id + ") failed", excp); - - throw restErrorUtil.createRESTException(excp.getMessage()); - } finally { - RangerPerfTracer.log(perf); - } - - if(ret == null) { - throw restErrorUtil.createRESTException(HttpServletResponse.SC_NOT_FOUND, "Not found", true); - } - - if(LOG.isDebugEnabled()) { - LOG.debug("<== ServiceREST.getServiceDef(" + id + "): " + ret); - } - - return ret; - } - - @GET - @Path("/definitions/name/{name}") - @Produces({ "application/json" }) - @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.GET_SERVICE_DEF_BY_NAME + "\")") - public RangerServiceDef getServiceDefByName(@PathParam("name") String name) { - if(LOG.isDebugEnabled()) { - LOG.debug("==> ServiceREST.getServiceDefByName(serviceDefName=" + name + ")"); - } - - RangerServiceDef ret = null; - RangerPerfTracer perf = null; - - try { - if(RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { - perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "ServiceREST.getServiceDefByName(" + name + ")"); - } - XXServiceDef xServiceDef = daoManager.getXXServiceDef().findByName(name); - if (xServiceDef != null) { - if(EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_TAG_NAME.equals(xServiceDef.getName())) { - if (!bizUtil.hasModuleAccess(RangerConstants.MODULE_TAG_BASED_POLICIES)) { - throw restErrorUtil.createRESTException(HttpServletResponse.SC_FORBIDDEN, "User is not having permissions on the tag module", true); - } - } - if (!bizUtil.hasAccess(xServiceDef, null)) { - throw restErrorUtil.createRESTException( - "User is not allowed to access service-def: " + xServiceDef.getName(), - MessageEnums.OPER_NO_PERMISSION); - } - } - - ret = svcStore.getServiceDefByName(name); - } catch(WebApplicationException excp) { - throw excp; - } catch(Throwable excp) { - LOG.error("getServiceDefByName(" + name + ") failed", excp); - - throw restErrorUtil.createRESTException(excp.getMessage()); - } finally { - RangerPerfTracer.log(perf); - } - - if(ret == null) { - throw restErrorUtil.createRESTException(HttpServletResponse.SC_NOT_FOUND, "Not found", true); - } - - if(LOG.isDebugEnabled()) { - LOG.debug("<== ServiceREST.getServiceDefByName(" + name + "): " + ret); - } - - return ret; - } - - @GET - @Path("/definitions") - @Produces({ "application/json" }) - @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.GET_SERVICE_DEFS + "\")") - public RangerServiceDefList getServiceDefs(@Context HttpServletRequest request) { - if (LOG.isDebugEnabled()) { - LOG.debug("==> ServiceREST.getServiceDefs()"); - } - - if (!bizUtil.hasModuleAccess(RangerConstants.MODULE_RESOURCE_BASED_POLICIES)) { - throw restErrorUtil.createRESTException(HttpServletResponse.SC_FORBIDDEN, "User is not having permissions on the "+RangerConstants.MODULE_RESOURCE_BASED_POLICIES+" module.", true); - } - - RangerServiceDefList ret = null; - RangerPerfTracer perf = null; - - PList paginatedSvcDefs = null; - - SearchFilter filter = searchUtil.getSearchFilter(request, serviceDefService.sortFields); - String pageSource= null; - pageSource=request.getParameter("pageSource"); - if(pageSource!=null) - filter.setParam("pageSource",pageSource); - - try { - if(RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { - perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "ServiceREST.getServiceDefs()"); - } - paginatedSvcDefs = svcStore.getPaginatedServiceDefs(filter); - - if(paginatedSvcDefs != null) { - ret = new RangerServiceDefList(); - - ret.setServiceDefs(paginatedSvcDefs.getList()); - ret.setPageSize(paginatedSvcDefs.getPageSize()); - ret.setResultSize(paginatedSvcDefs.getResultSize()); - ret.setStartIndex(paginatedSvcDefs.getStartIndex()); - ret.setTotalCount(paginatedSvcDefs.getTotalCount()); - ret.setSortBy(paginatedSvcDefs.getSortBy()); - ret.setSortType(paginatedSvcDefs.getSortType()); - } - } catch(WebApplicationException excp) { - throw excp; - } catch (Throwable excp) { - LOG.error("getServiceDefs() failed", excp); - - throw restErrorUtil.createRESTException(excp.getMessage()); - } finally { - RangerPerfTracer.log(perf); - } - - if (LOG.isDebugEnabled()) { - LOG.debug("<== ServiceREST.getServiceDefs(): count=" + (ret == null ? 0 : ret.getListSize())); - } - return ret; - } - - @GET - @Path("/policies/{serviceDefName}/for-resource") - @Produces({ "application/json" }) - public List getPoliciesForResource(@PathParam("serviceDefName") String serviceDefName, - @DefaultValue("") @QueryParam("serviceName") String serviceName, - @Context HttpServletRequest request) { - if (LOG.isDebugEnabled()) { - LOG.debug("==> ServiceREST.getPoliciesForResource(service-type=" + serviceDefName + ", service-name=" + serviceName + ")"); - } - - List ret = new ArrayList<>(); - - List services = new ArrayList<>(); - Map resource = new HashMap<>(); - - String validationMessage = validateResourcePoliciesRequest(serviceDefName, serviceName, request, services, resource); - - if (StringUtils.isNotEmpty(validationMessage)) { - LOG.error("Invalid request: [" + validationMessage + "]"); - throw restErrorUtil.createRESTException(validationMessage, - MessageEnums.INVALID_INPUT_DATA); - } else { - RangerService service = services.get(0); - if (LOG.isDebugEnabled()) { - LOG.debug("getServicePolicies with service-name=" + service.getName()); - } - - RangerPolicyAdmin policyAdmin = null; - - try { - policyAdmin = getPolicyAdminForSearch(service.getName()); - } catch (Exception e) { - LOG.error("Cannot initialize Policy-Engine", e); - throw restErrorUtil.createRESTException("Cannot initialize Policy Engine", - MessageEnums.ERROR_SYSTEM); - } - - if (policyAdmin != null) { - ret = policyAdmin.getMatchingPolicies(new RangerAccessResourceImpl(resource)); - ret = applyAdminAccessFilter(ret); - } - - } - - if (LOG.isDebugEnabled()) { - LOG.debug("<== ServiceREST.getPoliciesForResource(service-type=" + serviceDefName + ", service-name=" + serviceName + ") : " + ret.toString()); - } - return ret; - } - - private String validateResourcePoliciesRequest(String serviceDefName, String serviceName, HttpServletRequest request, List services, Map resource) { - if (LOG.isDebugEnabled()) { - LOG.debug("==> ServiceREST.validatePoliciesForResourceRequest(service-type=" + serviceDefName + ", service-name=" + serviceName + ")"); - } - final String ret; - - if (MapUtils.isNotEmpty(request.getParameterMap())) { - for (Entry e : request.getParameterMap().entrySet()) { - String name = e.getKey(); - String[] values = e.getValue(); - - if (!StringUtils.isEmpty(name) && !ArrayUtils.isEmpty(values) - && name.startsWith(SearchFilter.RESOURCE_PREFIX)) { - resource.put(name.substring(SearchFilter.RESOURCE_PREFIX.length()), values[0]); - } - } - } - if (MapUtils.isEmpty(resource)) { - ret = "No resource specified"; - } else { - RangerServiceDef serviceDef = null; - try { - serviceDef = svcStore.getServiceDefByName(serviceDefName); - } catch (Exception e) { - LOG.error("Invalid service-type:[" + serviceDefName + "]", e); - } - if (serviceDef == null) { - ret = "Invalid service-type:[" + serviceDefName + "]"; - } else { - Set resourceDefNames = resource.keySet(); - RangerServiceDefHelper serviceDefHelper = new RangerServiceDefHelper(serviceDef); - Set> resourceHierarchies = serviceDefHelper.getResourceHierarchies(RangerPolicy.POLICY_TYPE_ACCESS, resourceDefNames); - if (CollectionUtils.isEmpty(resourceHierarchies)) { - ret = "Invalid resource specified: resource-names:" + resourceDefNames +" are not part of any valid resource hierarchy for service-type:[" + serviceDefName + "]"; - } else { - if (StringUtils.isNotBlank(serviceName)) { - RangerService service = null; - try { - service = svcStore.getServiceByName(serviceName); - } catch (Exception e) { - LOG.error("Invalid service-name:[" + serviceName + "]"); - } - if (service == null || !StringUtils.equals(service.getType(), serviceDefName)) { - ret = "Invalid service-name:[" + serviceName + "] or service-type:[" + serviceDefName + "]"; - } else { - services.add(service); - ret = StringUtils.EMPTY; - } - } else { - SearchFilter filter = new SearchFilter(); - filter.setParam(SearchFilter.SERVICE_TYPE, serviceDefName); - List serviceList = null; - try { - serviceList = svcStore.getServices(filter); - } catch (Exception e) { - LOG.error("Cannot find service of service-type:[" + serviceDefName + "]"); - } - if (CollectionUtils.isEmpty(serviceList) || serviceList.size() != 1) { - ret = "Either 0 or more than 1 services found for service-type :[" + serviceDefName + "]"; - } else { - services.add(serviceList.get(0)); - ret = StringUtils.EMPTY; - } - } - } - } - } - - if (LOG.isDebugEnabled()) { - LOG.debug("<== ServiceREST.validatePoliciesForResourceRequest(service-type=" + serviceDefName + ", service-name=" + serviceName + ") : " + ret); - } - return ret; - } - - @POST - @Path("/services") - @Consumes({ "application/json" }) - @Produces({ "application/json" }) - @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.CREATE_SERVICE + "\")") - public RangerService createService(RangerService service) { - if(LOG.isDebugEnabled()) { - LOG.debug("==> ServiceREST.createService(" + service + ")"); - } - - RangerService ret = null; - RangerPerfTracer perf = null; - - /** - * If display name is blank (EMPTY String or NULL), use name. - */ - if (StringUtils.isBlank(service.getDisplayName())) { - service.setDisplayName(service.getName()); - } - - try { - - if(RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { - perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "ServiceREST.createService(serviceName=" + service.getName() + ")"); - } - RangerServiceValidator validator = validatorFactory.getServiceValidator(svcStore); - validator.validate(service, Action.CREATE); - - if(!StringUtils.isEmpty(service.getName().trim())){ - service.setName(service.getName().trim()); - } - - if(!StringUtils.isEmpty(service.getDisplayName().trim())){ - service.setDisplayName(service.getDisplayName().trim()); - } - - UserSessionBase session = ContextUtil.getCurrentUserSession(); - XXServiceDef xxServiceDef = daoManager.getXXServiceDef().findByName(service.getType()); - if(session != null && !session.isSpnegoEnabled()){ - bizUtil.hasAdminPermissions("Services"); - - // TODO: As of now we are allowing SYS_ADMIN to create all the - // services including KMS - bizUtil.hasKMSPermissions("Service", xxServiceDef.getImplclassname()); - } - if(session != null && session.isSpnegoEnabled()){ - if (session.isKeyAdmin() && !EmbeddedServiceDefsUtil.KMS_IMPL_CLASS_NAME.equals(xxServiceDef.getImplclassname())) { - throw restErrorUtil.createRESTException("KeyAdmin can create/update/delete only KMS ", - MessageEnums.OPER_NO_PERMISSION); - } - if ((!session.isKeyAdmin() && !session.isUserAdmin()) && EmbeddedServiceDefsUtil.KMS_IMPL_CLASS_NAME.equals(xxServiceDef.getImplclassname())) { - throw restErrorUtil.createRESTException("User cannot create/update/delete KMS Service", - MessageEnums.OPER_NO_PERMISSION); - } - } - bizUtil.blockAuditorRoleUser(); - - String serviceType = xxServiceDef != null ? xxServiceDef.getName() : null; - - if (StringUtils.isBlank(service.getTagService()) && - !StringUtils.equals(EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_TAG_NAME, serviceType) && - !StringUtils.equals(EMBEDDED_SERVICEDEF_GDS_NAME, serviceType) && - !StringUtils.equals(EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_KMS_NAME , serviceType)) { - createOrGetLinkedServices(service); - } - - ret = svcStore.createService(service); - } catch(WebApplicationException excp) { - throw excp; - } catch(Throwable excp) { - LOG.error("createService(" + service + ") failed", excp); - - throw restErrorUtil.createRESTException(excp.getMessage()); - } finally { - RangerPerfTracer.log(perf); - } - - if(LOG.isDebugEnabled()) { - LOG.debug("<== ServiceREST.createService(" + service + "): " + ret); - } - - return ret; - } - - @PUT - @Path("/services/{id}") - @Consumes({ "application/json" }) - @Produces({ "application/json" }) - @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.UPDATE_SERVICE + "\")") - public RangerService updateService(RangerService service, - @Context HttpServletRequest request) { - if(LOG.isDebugEnabled()) { - LOG.debug("==> ServiceREST.updateService(): " + service); - } - - RangerService ret = null; - RangerPerfTracer perf = null; - - try { - - if(RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { - perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "ServiceREST.updateService(serviceName=" + service.getName() + ")"); - } - - /** - * If display name is blank (EMPTY String or NULL), use previous display name. - */ - if (StringUtils.isBlank(service.getDisplayName())) { - RangerService rangerService = svcStore.getService(service.getId()); - - // If previous display name is blank (EMPTY String or NULL), user name. - if (Objects.isNull(rangerService) || StringUtils.isBlank(rangerService.getDisplayName())) { - service.setDisplayName(service.getName()); - } else { - service.setDisplayName(rangerService.getDisplayName()); - } - } - - RangerServiceValidator validator = validatorFactory.getServiceValidator(svcStore); - validator.validate(service, Action.UPDATE); - - if(!StringUtils.isEmpty(service.getName().trim())){ - service.setName(service.getName().trim()); - } - - if(!StringUtils.isEmpty(service.getDisplayName().trim())){ - service.setDisplayName(service.getDisplayName().trim()); - } - - bizUtil.hasAdminPermissions("Services"); - - // TODO: As of now we are allowing SYS_ADMIN to create all the - // services including KMS - - XXServiceDef xxServiceDef = daoManager.getXXServiceDef().findByName(service.getType()); - bizUtil.hasKMSPermissions("Service", xxServiceDef.getImplclassname()); - bizUtil.blockAuditorRoleUser(); - Map options = getOptions(request); + @Autowired + GUIDUtil guidUtil; - ret = svcStore.updateService(service, options); - } catch(WebApplicationException excp) { - throw excp; - } catch(Throwable excp) { - LOG.error("updateService(" + service + ") failed", excp); - - throw restErrorUtil.createRESTException(excp.getMessage()); - } finally { - RangerPerfTracer.log(perf); - } - - if(LOG.isDebugEnabled()) { - LOG.debug("<== ServiceREST.updateService(" + service + "): " + ret); - } - - return ret; - } - - @DELETE - @Path("/services/{id}") - @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.DELETE_SERVICE + "\")") - public void deleteService(@PathParam("id") Long id) { - if(LOG.isDebugEnabled()) { - LOG.debug("==> ServiceREST.deleteService(" + id + ")"); - } - - String deletedServiceName = deleteServiceById(id); - - if(LOG.isDebugEnabled()) { - LOG.debug("<== ServiceREST.deleteService() - [id="+deletedServiceName + "],[deletedServiceName="+deletedServiceName+"]"); - } - } - - @GET - @Path("/services/{id}") - @Produces({ "application/json" }) - @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.GET_SERVICE + "\")") - public RangerService getService(@PathParam("id") Long id) { - if(LOG.isDebugEnabled()) { - LOG.debug("==> ServiceREST.getService(" + id + ")"); - } - - RangerService ret = null; - RangerPerfTracer perf = null; - - try { - if(RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { - perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "ServiceREST.getService(serviceId=" + id + ")"); - } - ret = svcStore.getService(id); - - if (ret != null) { - UserSessionBase userSession = ContextUtil - .getCurrentUserSession(); - if (userSession != null && userSession.getLoginId() != null) { - VXUser loggedInVXUser = xUserService - .getXUserByUserName(userSession.getLoginId()); - if (loggedInVXUser != null) { - if (loggedInVXUser.getUserRoleList().size() == 1 - && loggedInVXUser.getUserRoleList().contains( - RangerConstants.ROLE_USER)) { - - ret = hideCriticalServiceDetailsForRoleUser(ret); - } - } - } - } - } catch(WebApplicationException excp) { - throw excp; - } catch(Throwable excp) { - LOG.error("getService(" + id + ") failed", excp); - - throw restErrorUtil.createRESTException(excp.getMessage()); - } finally { - RangerPerfTracer.log(perf); - } - - if(ret == null) { - throw restErrorUtil.createRESTException(HttpServletResponse.SC_NOT_FOUND, "Not found", true); - } - - if(LOG.isDebugEnabled()) { - LOG.debug("<== ServiceREST.getService(" + id + "): " + ret); - } - - return ret; - } - - @GET - @Path("/services/name/{name}") - @Produces({ "application/json" }) - @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.GET_SERVICE_BY_NAME + "\")") - public RangerService getServiceByName(@PathParam("name") String name) { - if(LOG.isDebugEnabled()) { - LOG.debug("==> ServiceREST.getServiceByName(" + name + ")"); - } - - RangerService ret = null; - RangerPerfTracer perf = null; - - try { - if(RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { - perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "ServiceREST.getService(serviceName=" + name + ")"); - } - ret = svcStore.getServiceByName(name); - - if (ret != null) { - UserSessionBase userSession = ContextUtil - .getCurrentUserSession(); - if (userSession != null && userSession.getLoginId() != null) { - VXUser loggedInVXUser = xUserService - .getXUserByUserName(userSession.getLoginId()); - if (loggedInVXUser != null) { - if (loggedInVXUser.getUserRoleList().size() == 1 - && loggedInVXUser.getUserRoleList().contains( - RangerConstants.ROLE_USER)) { - - ret = hideCriticalServiceDetailsForRoleUser(ret); - } - } - } - } - - } catch(WebApplicationException excp) { - throw excp; - } catch(Throwable excp) { - LOG.error("getServiceByName(" + name + ") failed", excp); - - throw restErrorUtil.createRESTException(excp.getMessage()); - } finally { - RangerPerfTracer.log(perf); - } - - if(ret == null) { - throw restErrorUtil.createRESTException(HttpServletResponse.SC_NOT_FOUND, "Not found", true); - } - - if(LOG.isDebugEnabled()) { - LOG.debug("<== ServiceREST.getServiceByName(" + name + "): " + ret); - } - - return ret; - } - - @GET - @Path("/services") - @Produces({ "application/json" }) - @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.GET_SERVICES + "\")") - public RangerServiceList getServices(@Context HttpServletRequest request) { - if (LOG.isDebugEnabled()) { - LOG.debug("==> ServiceREST.getServices()"); - } - - RangerServiceList ret = null; - RangerPerfTracer perf = null; - - PList paginatedSvcs = null; - - SearchFilter filter = searchUtil.getSearchFilter(request, svcService.sortFields); - - try { - if(RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { - perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "ServiceREST.getServices()"); - } - paginatedSvcs = svcStore.getPaginatedServices(filter); - - if(paginatedSvcs!= null && !paginatedSvcs.getList().isEmpty()){ - UserSessionBase userSession = ContextUtil - .getCurrentUserSession(); - if (userSession != null && userSession.getLoginId() != null) { - VXUser loggedInVXUser = xUserService - .getXUserByUserName(userSession.getLoginId()); - if (loggedInVXUser != null) { - if (loggedInVXUser.getUserRoleList().size() == 1 - && loggedInVXUser.getUserRoleList().contains( - RangerConstants.ROLE_USER)) { - - List updateServiceList = new ArrayList(); - for(RangerService rangerService : paginatedSvcs.getList()){ - - if(rangerService != null){ - updateServiceList.add(hideCriticalServiceDetailsForRoleUser(rangerService)); - } - } - - if(updateServiceList != null && !updateServiceList.isEmpty()){ - paginatedSvcs.setList(updateServiceList); - } - } - } - } - } - - if(paginatedSvcs != null) { - ret = new RangerServiceList(); - - ret.setServices(paginatedSvcs.getList()); - ret.setPageSize(paginatedSvcs.getPageSize()); - ret.setResultSize(paginatedSvcs.getResultSize()); - ret.setStartIndex(paginatedSvcs.getStartIndex()); - ret.setTotalCount(paginatedSvcs.getTotalCount()); - ret.setSortBy(paginatedSvcs.getSortBy()); - ret.setSortType(paginatedSvcs.getSortType()); - } - } catch(WebApplicationException excp) { - throw excp; - } catch (Throwable excp) { - LOG.error("getServices() failed", excp); - - throw restErrorUtil.createRESTException(excp.getMessage()); - } finally { - RangerPerfTracer.log(perf); - } - - if (LOG.isDebugEnabled()) { - LOG.debug("<== ServiceREST.getServices(): count=" + (ret == null ? 0 : ret.getListSize())); - } - return ret; - } - - public List getServices(SearchFilter filter) { - if(LOG.isDebugEnabled()) { - LOG.debug("==> ServiceREST.getServices():"); - } - - List ret = null; - RangerPerfTracer perf = null; - - try { - if(RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { - perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "ServiceREST.getServices()"); - } - ret = svcStore.getServices(filter); - } catch(WebApplicationException excp) { - throw excp; - } catch(Throwable excp) { - LOG.error("getServices() failed", excp); - - throw restErrorUtil.createRESTException(excp.getMessage()); - } finally { - RangerPerfTracer.log(perf); - } - - if(LOG.isDebugEnabled()) { - LOG.debug("<== ServiceREST.getServices(): count=" + (ret == null ? 0 : ret.size())); - } - - return ret; - } - - public List getServiceHeaders(@Context HttpServletRequest request) { - LOG.debug("==> ServiceREST.getServiceHeaders()"); - - String namePrefix = request.getParameter(SearchFilter.SERVICE_NAME_PREFIX); - String svcType = request.getParameter(SearchFilter.SERVICE_TYPE); - boolean filterByNamePrefix = StringUtils.isNotBlank(namePrefix); - boolean filterByType = StringUtils.isNotBlank(svcType); - - List ret = daoManager.getXXService().findServiceHeaders(); - - for (ListIterator iter = ret.listIterator(); iter.hasNext(); ) { - RangerServiceHeaderInfo serviceHeader = iter.next(); - - if (EMBEDDED_SERVICEDEF_GDS_NAME.equals(serviceHeader.getType())) { - iter.remove(); - } else if (filterByNamePrefix && !StringUtils.startsWithIgnoreCase(serviceHeader.getName(), namePrefix)) { - iter.remove(); - } else if (filterByType && !StringUtils.equals(serviceHeader.getType(), svcType)) { - iter.remove(); - } else if(!bizUtil.hasAccess(null, serviceHeader)) { - iter.remove(); - } - } - - LOG.debug("<== ServiceREST.getServiceHeaders(namePrefix={}, svcType={}): ret={}", namePrefix, svcType, ret); - - return ret; - } - - @GET - @Path("/services/count") - @Produces({ "application/json" }) - @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.COUNT_SERVICES + "\")") - public Long countServices(@Context HttpServletRequest request) { - if(LOG.isDebugEnabled()) { - LOG.debug("==> ServiceREST.countServices():"); - } - - Long ret = null; - RangerPerfTracer perf = null; - - try { - if(RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { - perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "ServiceREST.countService()"); - } - List services = getServices(request).getServices(); - - ret = Long.valueOf(services == null ? 0 : services.size()); - } catch(WebApplicationException excp) { - throw excp; - } catch(Throwable excp) { - LOG.error("countServices() failed", excp); - - throw restErrorUtil.createRESTException(excp.getMessage()); - } finally { - RangerPerfTracer.log(perf); - } - - if(LOG.isDebugEnabled()) { - LOG.debug("<== ServiceREST.countServices(): " + ret); - } - - return ret; - } - - @POST - @Path("/services/validateConfig") - @Produces({ "application/json" }) - @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.VALIDATE_CONFIG + "\")") - public VXResponse validateConfig(RangerService service) { - if(LOG.isDebugEnabled()) { - LOG.debug("==> ServiceREST.validateConfig(" + service + ")"); - } - - VXResponse ret = new VXResponse(); - RangerPerfTracer perf = null; - - try { - if (RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { - perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "ServiceREST.validateConfig(serviceName=" + service.getName() + ")"); - } - ret = serviceMgr.validateConfig(service, svcStore); - } catch(WebApplicationException excp) { - throw excp; - } catch(Throwable excp) { - LOG.error("validateConfig(" + service + ") failed", excp); - - throw restErrorUtil.createRESTException(excp.getMessage()); - } finally { - RangerPerfTracer.log(perf); - } - - if(LOG.isDebugEnabled()) { - LOG.debug("<== ServiceREST.validateConfig(" + service + "): " + ret); - } - - return ret; - } - - @POST - @Path("/services/lookupResource/{serviceName}") - @Consumes({ "application/json" }) - @Produces({ "application/json" }) - @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.LOOKUP_RESOURCE + "\")") - public List lookupResource(@PathParam("serviceName") String serviceName, ResourceLookupContext context) { - if(LOG.isDebugEnabled()) { - LOG.debug("==> ServiceREST.lookupResource(" + serviceName + ")"); - } - - List ret = new ArrayList(); - RangerPerfTracer perf = null; - - try { - if (RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { - perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "ServiceREST.lookupResource(serviceName=" + serviceName + ")"); - } - ret = serviceMgr.lookupResource(serviceName, context, svcStore); - } catch(WebApplicationException excp) { - throw excp; - } catch(Throwable excp) { - LOG.error("lookupResource(" + serviceName + ", " + context + ") failed", excp); - - throw restErrorUtil.createRESTException(excp.getMessage()); - } finally { - RangerPerfTracer.log(perf); - } - - if(LOG.isDebugEnabled()) { - LOG.debug("<== ServiceREST.lookupResource(" + serviceName + "): " + ret); - } - - return ret; - } - - @POST - @Path("/services/grant/{serviceName}") - @Consumes({ "application/json" }) - @Produces({ "application/json" }) - public RESTResponse grantAccess(@PathParam("serviceName") String serviceName, GrantRevokeRequest grantRequest, @Context HttpServletRequest request) throws Exception { - if(LOG.isDebugEnabled()) { - LOG.debug("==> ServiceREST.grantAccess(" + serviceName + ", " + grantRequest + ")"); - } - - RESTResponse ret = new RESTResponse(); - RangerPerfTracer perf = null; - - if(grantRequest!=null){ - if (serviceUtil.isValidateHttpsAuthentication(serviceName, request)) { - - try { - bizUtil.failUnauthenticatedIfNotAllowed(); - - if(RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { - perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "ServiceREST.grantAccess(serviceName=" + serviceName + ")"); - } - - // This is an open API - dont care about who calls it. Caller is treated as privileged user - boolean hasAdminPrivilege = true; - String loggedInUser = null; - validateGrantRevokeRequest(grantRequest, hasAdminPrivilege, loggedInUser); - - String userName = grantRequest.getGrantor(); - Set userGroups = CollectionUtils.isNotEmpty(grantRequest.getGrantorGroups()) ? grantRequest.getGrantorGroups() : userMgr.getGroupsForUser(userName); - String ownerUser = grantRequest.getOwnerUser(); - RangerAccessResource resource = new RangerAccessResourceImpl(getAccessResourceObjectMap(grantRequest.getResource()), ownerUser); - Set accessTypes = grantRequest.getAccessTypes(); - VXUser vxUser = xUserService.getXUserByUserName(userName); - - if (vxUser.getUserRoleList().contains(RangerConstants.ROLE_ADMIN_AUDITOR) || vxUser.getUserRoleList().contains(RangerConstants.ROLE_KEY_ADMIN_AUDITOR)) { - VXResponse vXResponse = new VXResponse(); - vXResponse.setStatusCode(HttpServletResponse.SC_FORBIDDEN); - vXResponse.setMsgDesc("Operation denied. LoggedInUser=" + vxUser.getId() + " is not permitted to perform the action."); - throw restErrorUtil.generateRESTException(vXResponse); - } - RangerService rangerService = svcStore.getServiceByName(serviceName); - - String zoneName = getRangerAdminZoneName(serviceName, grantRequest); - boolean isAdmin = bizUtil.isUserRangerAdmin(userName) || bizUtil.isUserServiceAdmin(rangerService, userName) || hasAdminAccess(serviceName, zoneName, userName, userGroups, resource, accessTypes); - - if(!isAdmin) { - throw restErrorUtil.createGrantRevokeRESTException( "User doesn't have necessary permission to grant access"); - } - - RangerPolicy policy = getExactMatchPolicyForResource(serviceName, resource, zoneName, userName); - - if(policy != null) { - boolean policyUpdated = false; - policyUpdated = ServiceRESTUtil.processGrantRequest(policy, grantRequest); - - if(policyUpdated) { - policy.setZoneName(zoneName); - ensureAdminAccess(policy); - svcStore.updatePolicy(policy); - } else { - LOG.error("processGrantRequest processing failed"); - throw new Exception("processGrantRequest processing failed"); - } - } else { - policy = new RangerPolicy(); - policy.setService(serviceName); - policy.setName("grant-" + System.currentTimeMillis()); // TODO: better policy name - policy.setDescription("created by grant"); - policy.setIsAuditEnabled(grantRequest.getEnableAudit()); - policy.setCreatedBy(userName); - - Map policyResources = new HashMap(); - Set resourceNames = resource.getKeys(); - - if(! CollectionUtils.isEmpty(resourceNames)) { - for(String resourceName : resourceNames) { - policyResources.put(resourceName, getPolicyResource(resource.getValue(resourceName), grantRequest)); - } - } - policy.setResources(policyResources); - - RangerPolicyItem policyItem = new RangerPolicyItem(); - - policyItem.setDelegateAdmin(grantRequest.getDelegateAdmin()); - policyItem.addUsers(grantRequest.getUsers()); - policyItem.addGroups(grantRequest.getGroups()); - policyItem.addRoles(grantRequest.getRoles()); - - for(String accessType : grantRequest.getAccessTypes()) { - policyItem.addAccess(new RangerPolicyItemAccess(accessType, Boolean.TRUE)); - } - - policy.addPolicyItem(policyItem); - policy.setZoneName(zoneName); - - ensureAdminAccess(policy); - svcStore.createPolicy(policy); - } - } catch(WebApplicationException excp) { - throw excp; - } catch(Throwable excp) { - LOG.error("grantAccess(" + serviceName + ", " + grantRequest + ") failed", excp); - - throw restErrorUtil.createRESTException(excp.getMessage()); - } finally { - RangerPerfTracer.log(perf); - } - - ret.setStatusCode(RESTResponse.STATUS_SUCCESS); - } - } - if(LOG.isDebugEnabled()) { - LOG.debug("<== ServiceREST.grantAccess(" + serviceName + ", " + grantRequest + "): " + ret); - } - - return ret; - } - - @POST - @Path("/secure/services/grant/{serviceName}") - @Consumes({ "application/json" }) - @Produces({ "application/json" }) - public RESTResponse secureGrantAccess(@PathParam("serviceName") String serviceName, GrantRevokeRequest grantRequest, @Context HttpServletRequest request) throws Exception { - if(LOG.isDebugEnabled()) { - LOG.debug("==> ServiceREST.secureGrantAccess(" + serviceName + ", " + grantRequest + ")"); - } - RESTResponse ret = new RESTResponse(); - RangerPerfTracer perf = null; - - bizUtil.blockAuditorRoleUser(); - - if(grantRequest != null) { - if (serviceUtil.isValidService(serviceName, request)) { - try { - if(RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { - perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "ServiceREST.scureGrantAccess(serviceName=" + serviceName + ")"); - } - - XXService xService = daoManager.getXXService().findByName(serviceName); - XXServiceDef xServiceDef = daoManager.getXXServiceDef().getById(xService.getType()); - RangerService rangerService = svcStore.getServiceByName(serviceName); - - String loggedInUser = bizUtil.getCurrentUserLoginId(); - boolean hasAdminPrivilege = bizUtil.isAdmin() || bizUtil.isUserServiceAdmin(rangerService, loggedInUser) || bizUtil.isUserAllowedForGrantRevoke(rangerService, loggedInUser); - - validateGrantRevokeRequest(grantRequest, hasAdminPrivilege, loggedInUser); - - String userName = grantRequest.getGrantor(); - Set userGroups = grantRequest.getGrantorGroups(); - String ownerUser = grantRequest.getOwnerUser(); - - RangerAccessResource resource = new RangerAccessResourceImpl(getAccessResourceObjectMap(grantRequest.getResource()), ownerUser); - Set accessTypes = grantRequest.getAccessTypes(); - String zoneName = getRangerAdminZoneName(serviceName, grantRequest); - - boolean isAllowed = false; - - if (StringUtils.equals(xServiceDef.getImplclassname(), EmbeddedServiceDefsUtil.KMS_IMPL_CLASS_NAME)) { - if (bizUtil.isKeyAdmin() || bizUtil.isUserAllowedForGrantRevoke(rangerService, loggedInUser)) { - isAllowed = true; - } - } else { - isAllowed = bizUtil.isUserRangerAdmin(userName) || bizUtil.isUserServiceAdmin(rangerService, userName) || hasAdminAccess(serviceName, zoneName, userName, userGroups, resource, accessTypes); - } - - if (isAllowed) { - RangerPolicy policy = getExactMatchPolicyForResource(serviceName, resource, zoneName, userName); - - if(policy != null) { - boolean policyUpdated = false; - policyUpdated = ServiceRESTUtil.processGrantRequest(policy, grantRequest); - - if(policyUpdated) { - policy.setZoneName(zoneName); - - ensureAdminAccess(policy); - - svcStore.updatePolicy(policy); - } else { - LOG.error("processSecureGrantRequest processing failed"); - throw new Exception("processSecureGrantRequest processing failed"); - } - } else { - policy = new RangerPolicy(); - policy.setService(serviceName); - policy.setName("grant-" + System.currentTimeMillis()); // TODO: better policy name - policy.setDescription("created by grant"); - policy.setIsAuditEnabled(grantRequest.getEnableAudit()); - policy.setCreatedBy(userName); - - Map policyResources = new HashMap(); - Set resourceNames = resource.getKeys(); - - if(! CollectionUtils.isEmpty(resourceNames)) { - for(String resourceName : resourceNames) { - policyResources.put(resourceName, getPolicyResource(resource.getValue(resourceName), grantRequest)); - } - } - policy.setResources(policyResources); - - RangerPolicyItem policyItem = new RangerPolicyItem(); - - policyItem.setDelegateAdmin(grantRequest.getDelegateAdmin()); - policyItem.addUsers(grantRequest.getUsers()); - policyItem.addGroups(grantRequest.getGroups()); - policyItem.addRoles(grantRequest.getRoles()); - - for(String accessType : grantRequest.getAccessTypes()) { - policyItem.addAccess(new RangerPolicyItemAccess(accessType, Boolean.TRUE)); - } - - policy.addPolicyItem(policyItem); - policy.setZoneName(zoneName); - - ensureAdminAccess(policy); - - svcStore.createPolicy(policy); - } - }else{ - LOG.error("secureGrantAccess(" + serviceName + ", " + grantRequest + ") failed as User doesn't have permission to grant Policy"); - throw restErrorUtil.createGrantRevokeRESTException( "User doesn't have necessary permission to grant access"); - } - } catch(WebApplicationException excp) { - throw excp; - } catch(Throwable excp) { - LOG.error("secureGrantAccess(" + serviceName + ", " + grantRequest + ") failed", excp); - - throw restErrorUtil.createRESTException(excp.getMessage()); - } finally { - RangerPerfTracer.log(perf); - } - - ret.setStatusCode(RESTResponse.STATUS_SUCCESS); - } - } - if(LOG.isDebugEnabled()) { - LOG.debug("<== ServiceREST.secureGrantAccess(" + serviceName + ", " + grantRequest + "): " + ret); - } - return ret; - } - - @POST - @Path("/services/revoke/{serviceName}") - @Consumes({ "application/json" }) - @Produces({ "application/json" }) - public RESTResponse revokeAccess(@PathParam("serviceName") String serviceName, GrantRevokeRequest revokeRequest, @Context HttpServletRequest request) throws Exception { - if(LOG.isDebugEnabled()) { - LOG.debug("==> ServiceREST.revokeAccess(" + serviceName + ", " + revokeRequest + ")"); - } - - RESTResponse ret = new RESTResponse(); - RangerPerfTracer perf = null; - - if(revokeRequest!=null){ - if (serviceUtil.isValidateHttpsAuthentication(serviceName,request)) { - - try { - bizUtil.failUnauthenticatedIfNotAllowed(); - - if(RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { - perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "ServiceREST.revokeAccess(serviceName=" + serviceName + ")"); - } - - // This is an open API - dont care about who calls it. Caller is treated as privileged user - boolean hasAdminPrivilege = true; - String loggedInUser = null; - validateGrantRevokeRequest(revokeRequest, hasAdminPrivilege, loggedInUser); - - String userName = revokeRequest.getGrantor(); - Set userGroups = CollectionUtils.isNotEmpty(revokeRequest.getGrantorGroups()) ? revokeRequest.getGrantorGroups() : userMgr.getGroupsForUser(userName); - String ownerUser = revokeRequest.getOwnerUser(); - RangerAccessResource resource = new RangerAccessResourceImpl(getAccessResourceObjectMap(revokeRequest.getResource()), ownerUser); - Set accessTypes = revokeRequest.getAccessTypes(); - VXUser vxUser = xUserService.getXUserByUserName(userName); - - if (vxUser.getUserRoleList().contains(RangerConstants.ROLE_ADMIN_AUDITOR) || vxUser.getUserRoleList().contains(RangerConstants.ROLE_KEY_ADMIN_AUDITOR)) { - VXResponse vXResponse = new VXResponse(); - vXResponse.setStatusCode(HttpServletResponse.SC_FORBIDDEN); - vXResponse.setMsgDesc("Operation denied. LoggedInUser=" + vxUser.getId() + " is not permitted to perform the action."); - throw restErrorUtil.generateRESTException(vXResponse); - } - RangerService rangerService = svcStore.getServiceByName(serviceName); - String zoneName = getRangerAdminZoneName(serviceName, revokeRequest); - - boolean isAdmin = bizUtil.isUserRangerAdmin(userName) || bizUtil.isUserServiceAdmin(rangerService, userName) || hasAdminAccess(serviceName, zoneName, userName, userGroups, resource, accessTypes); - - if(!isAdmin) { - throw restErrorUtil.createGrantRevokeRESTException("User doesn't have necessary permission to revoke access"); - } - - RangerPolicy policy = getExactMatchPolicyForResource(serviceName, resource, zoneName, userName); - - if(policy != null) { - boolean policyUpdated = false; - policyUpdated = ServiceRESTUtil.processRevokeRequest(policy, revokeRequest); - - if(policyUpdated) { - policy.setZoneName(zoneName); - - ensureAdminAccess(policy); - - svcStore.updatePolicy(policy); - } else { - LOG.error("processRevokeRequest processing failed"); - throw new Exception("processRevokeRequest processing failed"); - } - } - } catch(WebApplicationException excp) { - throw excp; - } catch(Throwable excp) { - LOG.error("revokeAccess(" + serviceName + ", " + revokeRequest + ") failed", excp); - - throw restErrorUtil.createRESTException(excp.getMessage()); - } finally { - RangerPerfTracer.log(perf); - } - - ret.setStatusCode(RESTResponse.STATUS_SUCCESS); - } - } - if(LOG.isDebugEnabled()) { - LOG.debug("<== ServiceREST.revokeAccess(" + serviceName + ", " + revokeRequest + "): " + ret); - } - - return ret; - } - - @POST - @Path("/secure/services/revoke/{serviceName}") - @Consumes({ "application/json" }) - @Produces({ "application/json" }) - public RESTResponse secureRevokeAccess(@PathParam("serviceName") String serviceName, GrantRevokeRequest revokeRequest, @Context HttpServletRequest request) throws Exception { - if(LOG.isDebugEnabled()) { - LOG.debug("==> ServiceREST.secureRevokeAccess(" + serviceName + ", " + revokeRequest + ")"); - } - RESTResponse ret = new RESTResponse(); - RangerPerfTracer perf = null; - - bizUtil.blockAuditorRoleUser(); - - if (revokeRequest != null) { - if (serviceUtil.isValidService(serviceName,request)) { - try { - if(RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { - perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "ServiceREST.secureRevokeAccess(serviceName=" + serviceName + ")"); - } - - XXService xService = daoManager.getXXService().findByName(serviceName); - XXServiceDef xServiceDef = daoManager.getXXServiceDef().getById(xService.getType()); - RangerService rangerService = svcStore.getServiceByName(serviceName); - - String loggedInUser = bizUtil.getCurrentUserLoginId(); - boolean hasAdminPrivilege = bizUtil.isAdmin() || bizUtil.isUserServiceAdmin(rangerService, loggedInUser) || bizUtil.isUserAllowedForGrantRevoke(rangerService, loggedInUser); - - validateGrantRevokeRequest(revokeRequest, hasAdminPrivilege, loggedInUser); - - String userName = revokeRequest.getGrantor(); - Set userGroups = revokeRequest.getGrantorGroups(); - String ownerUser = revokeRequest.getOwnerUser(); - - RangerAccessResource resource = new RangerAccessResourceImpl(getAccessResourceObjectMap(revokeRequest.getResource()), ownerUser); - Set accessTypes = revokeRequest.getAccessTypes(); - String zoneName = getRangerAdminZoneName(serviceName, revokeRequest); - - - boolean isAllowed = false; - - if (StringUtils.equals(xServiceDef.getImplclassname(), EmbeddedServiceDefsUtil.KMS_IMPL_CLASS_NAME)) { - if (bizUtil.isKeyAdmin() || bizUtil.isUserAllowedForGrantRevoke(rangerService, loggedInUser)) { - isAllowed = true; - } - } else { - isAllowed = bizUtil.isUserRangerAdmin(userName) || bizUtil.isUserServiceAdmin(rangerService, userName) || hasAdminAccess(serviceName, zoneName, userName, userGroups, resource, accessTypes); - } - - if (isAllowed) { - RangerPolicy policy = getExactMatchPolicyForResource(serviceName, resource, zoneName, userName); - - if(policy != null) { - boolean policyUpdated = false; - policyUpdated = ServiceRESTUtil.processRevokeRequest(policy, revokeRequest); - - if(policyUpdated) { - policy.setZoneName(zoneName); - - ensureAdminAccess(policy); - - svcStore.updatePolicy(policy); - } else { - LOG.error("processSecureRevokeRequest processing failed"); - throw new Exception("processSecureRevokeRequest processing failed"); - } - } - }else{ - LOG.error("secureRevokeAccess(" + serviceName + ", " + revokeRequest + ") failed as User doesn't have permission to revoke Policy"); - throw restErrorUtil.createGrantRevokeRESTException("User doesn't have necessary permission to revoke access"); - } - } catch(WebApplicationException excp) { - throw excp; - } catch(Throwable excp) { - LOG.error("secureRevokeAccess(" + serviceName + ", " + revokeRequest + ") failed", excp); - - throw restErrorUtil.createRESTException(excp.getMessage()); - } finally { - RangerPerfTracer.log(perf); - } - - ret.setStatusCode(RESTResponse.STATUS_SUCCESS); - } - } - if(LOG.isDebugEnabled()) { - LOG.debug("<== ServiceREST.secureRevokeAccess(" + serviceName + ", " + revokeRequest + "): " + ret); - } - return ret; - } - - @POST - @Path("/policies") - @Consumes({ "application/json" }) - @Produces({ "application/json" }) - public RangerPolicy createPolicy(RangerPolicy policy, @Context HttpServletRequest request) { - if(LOG.isDebugEnabled()) { - LOG.debug("==> ServiceREST.createPolicy(" + policy + ")"); - } - RangerPolicy ret = null; - RangerPerfTracer perf = null; - - try { - if(RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { - perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "ServiceREST.createPolicy(policyName=" + policy.getName() + ")"); - } - - if(request != null) { - boolean deleteIfExists=("true".equalsIgnoreCase(StringUtils.trimToEmpty(request.getParameter(PARAM_DELETE_IF_EXISTS)))) ? true : false ; - if(deleteIfExists) { - boolean importInProgress=("true".equalsIgnoreCase(StringUtils.trimToEmpty(String.valueOf(request.getAttribute(PARAM_IMPORT_IN_PROGRESS))))) ? true : false ; - if (!importInProgress) { - List policies=new ArrayList() { { add(policy); } }; - deleteExactMatchPolicyForResource(policies, request.getRemoteUser(), null); - } - } - boolean updateIfExists=("true".equalsIgnoreCase(StringUtils.trimToEmpty(request.getParameter(PARAM_UPDATE_IF_EXISTS)))) ? true : false ; - boolean mergeIfExists = "true".equalsIgnoreCase(StringUtils.trimToEmpty(request.getParameter(PARAM_MERGE_IF_EXISTS))) ? true : false; - // Default POLICY_MATCHING_ALGO_BY_RESOURCE - String policyMatchingAlgo = POLICY_MATCHING_ALGO_BY_POLICYNAME.equalsIgnoreCase(StringUtils.trimToEmpty(request.getParameter(PARAM_POLICY_MATCHING_ALGORITHM))) ? POLICY_MATCHING_ALGO_BY_POLICYNAME : POLICY_MATCHING_ALGO_BY_RESOURCE; - if(LOG.isDebugEnabled()) { - LOG.debug(" policyMatchingAlgo : "+policyMatchingAlgo + " updateIfExists : " +updateIfExists + " mergeIfExists: "+mergeIfExists + " deleteIfExists : "+deleteIfExists); - } - if (mergeIfExists && updateIfExists) { - LOG.warn("Cannot use both updateIfExists and mergeIfExists for a createPolicy. mergeIfExists will override updateIfExists for policy :[" + policy.getName() + "]"); - } - - if (!mergeIfExists && !updateIfExists) { - ret = createPolicyUnconditionally(policy); - } else if (mergeIfExists) { - ret = applyPolicy(policy, request); - } else if (policyMatchingAlgo.equalsIgnoreCase(POLICY_MATCHING_ALGO_BY_RESOURCE)) { - ret = applyPolicy(policy, request); - } else if (policyMatchingAlgo.equalsIgnoreCase(POLICY_MATCHING_ALGO_BY_POLICYNAME)) { - RangerPolicy existingPolicy = getPolicyMatchByName(policy, request); - if (existingPolicy != null) { - policy.setId(existingPolicy.getId()); - ret = updatePolicy(policy, null); - } else { - ret = createPolicyUnconditionally(policy); - } - } - - if(LOG.isDebugEnabled()) { - LOG.debug("<== ServiceREST.createPolicy(" + policy + "): " + ret); - } - return ret; - - } - - if(ret == null) { - ret = createPolicyUnconditionally(policy); - } - } catch(WebApplicationException excp) { - throw excp; - } catch(Throwable excp) { - LOG.error("createPolicy(" + policy + ") failed", excp); - - throw restErrorUtil.createRESTException(excp.getMessage()); - } finally { - RangerPerfTracer.log(perf); - } - - if(LOG.isDebugEnabled()) { - LOG.debug("<== ServiceREST.createPolicy(" + policy + "): " + ret); - } - - return ret; - } - - /* - The verb for applyPolicy is POST as it could be partial update or a create - */ - - @POST - @Path("/policies/apply") - @Consumes({ "application/json" }) - @Produces({ "application/json" }) - public RangerPolicy applyPolicy(RangerPolicy policy, @Context HttpServletRequest request) { - if (LOG.isDebugEnabled()) { - LOG.debug("==> ServiceREST.applyPolicy(" + policy + ")"); - } - - RangerPolicy ret = null; - - if (policy != null && StringUtils.isNotBlank(policy.getService())) { - try { - - final RangerPolicy existingPolicy; - String signature = (new RangerPolicyResourceSignature(policy)).getSignature(); - List policiesWithMatchingSignature = svcStore.getPoliciesByResourceSignature(policy.getService(), signature, true); - - if (CollectionUtils.isNotEmpty(policiesWithMatchingSignature)) { - if (policiesWithMatchingSignature.size() == 1) { - existingPolicy = policiesWithMatchingSignature.get(0); - } else { - throw new Exception("Multiple policies with matching policy-signature are found. Cannot determine target for applying policy"); - } - } else { - existingPolicy = null; - } - - if (existingPolicy == null) { - if (StringUtils.isNotEmpty(policy.getName())) { - String policyName = StringUtils.isNotBlank(policy.getName()) ? policy.getName() : null; - String serviceName = StringUtils.isNotBlank(policy.getService()) ? policy.getService() : null; - String zoneName = StringUtils.isNotBlank(policy.getZoneName()) ? policy.getZoneName() : null; - XXPolicy dbPolicy = daoManager.getXXPolicy().findPolicy(policyName, serviceName, zoneName); - //XXPolicy dbPolicy = daoManager.getXXPolicy().findPolicy(policy.getName(), policy.getService(), policy.getZoneName()); - if (dbPolicy != null) { - policy.setName(policy.getName() + System.currentTimeMillis()); - } - } - - ret = createPolicy(policy, null); - } else { - boolean mergeIfExists = "true".equalsIgnoreCase(StringUtils.trimToEmpty(request.getParameter(PARAM_MERGE_IF_EXISTS))); - - if (!mergeIfExists) { - boolean updateIfExists = "true".equalsIgnoreCase(StringUtils.trimToEmpty(request.getParameter(PARAM_UPDATE_IF_EXISTS))); - if (updateIfExists) { - // Called with explicit intent of updating an existing policy - mergeIfExists = false; - } else { - // Invoked through REST API. Merge with existing policy unless 'mergeIfExists' is explicitly set to false in HttpServletRequest - mergeIfExists = !"false".equalsIgnoreCase(StringUtils.trimToEmpty(request.getParameter(PARAM_MERGE_IF_EXISTS))); - } - } - - if(mergeIfExists) { - if (!existingPolicy.getIsDenyAllElse() && policy.getIsDenyAllElse()) { - LOG.error("Attempt to change the isDenyAllElse flag from false to true! Not supported!!"); - throw new Exception("Merging existing policy(isDenyAllElse=false) with another policy(isDenyAllElse=true) is not allowed!"); - } - ServiceRESTUtil.processApplyPolicy(existingPolicy, policy); - policy = existingPolicy; - } else { - policy.setId(existingPolicy.getId()); - } - ret = updatePolicy(policy, policy.getId()); - } - } catch(WebApplicationException excp) { - throw excp; - } catch (Exception exception) { - LOG.error("Failed to apply policy:", exception); - throw restErrorUtil.createRESTException(exception.getMessage()); - } - } else { - throw restErrorUtil.createRESTException("Non-existing service specified:"); - } - - if (LOG.isDebugEnabled()) { - LOG.debug("<== ServiceREST.applyPolicy(" + policy + ") : " + ret); - } - - return ret; - } - - @PUT - @Path("/policies/{id}") - @Consumes({ "application/json" }) - @Produces({ "application/json" }) - public RangerPolicy updatePolicy(RangerPolicy policy, @PathParam("id") Long id) { - if(LOG.isDebugEnabled()) { - LOG.debug("==> ServiceREST.updatePolicy(" + policy + ")"); - } - - // if policy.id and param 'id' are specified, policy.id should be same as the param 'id' - // if policy.id is null, then set param 'id' into policy Object - if (policy.getId() == null) { - policy.setId(id); - } else if(!policy.getId().equals(id)) { - throw restErrorUtil.createRESTException(HttpServletResponse.SC_BAD_REQUEST , "policyID mismatch", true); - } - - RangerPolicy ret = null; - RangerPerfTracer perf = null; - - try { - if(RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { - perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "ServiceREST.updatePolicy(policyId=" + policy.getId() + ")"); - } - if (isPolicyNameLengthValidationEnabled) { - if (policy.getName().length() > maxPolicyNameLength) { - throw restErrorUtil.createRESTException( - "Policy name should not be longer than " + maxPolicyNameLength + " characters", - MessageEnums.INPUT_DATA_OUT_OF_BOUND, null, "policy name", "" + policy.getName()); - } - } - RangerPolicyValidator validator = validatorFactory.getPolicyValidator(svcStore); - validator.validate(policy, Action.UPDATE, bizUtil.isAdmin() || isServiceAdmin(policy.getService()) || isZoneAdmin(policy.getZoneName())); - - ensureAdminAccess(policy); - bizUtil.blockAuditorRoleUser(); - - ret = svcStore.updatePolicy(policy); - } catch(WebApplicationException excp) { - throw excp; - } catch(Throwable excp) { - LOG.error("updatePolicy(" + policy + ") failed", excp); - - throw restErrorUtil.createRESTException(excp.getMessage()); - } finally { - RangerPerfTracer.log(perf); - } - - if(LOG.isDebugEnabled()) { - LOG.debug("<== ServiceREST.updatePolicy(" + policy + "): " + ret); - } - - return ret; - } - - @DELETE - @Path("/policies/{id}") - public void deletePolicy(@PathParam("id") Long id) { - if(LOG.isDebugEnabled()) { - LOG.debug("==> ServiceREST.deletePolicy(" + id + ")"); - } - - RangerPerfTracer perf = null; - - try { - if(RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { - perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "ServiceREST.deletePolicy(policyId=" + id + ")"); - } - RangerPolicyValidator validator = validatorFactory.getPolicyValidator(svcStore); - validator.validate(id, Action.DELETE); - - RangerPolicy policy = svcStore.getPolicy(id); - - ensureAdminAccess(policy); - bizUtil.blockAuditorRoleUser(); - svcStore.deletePolicy(policy); - } catch(WebApplicationException excp) { - throw excp; - } catch(Throwable excp) { - LOG.error("deletePolicy(" + id + ") failed", excp); - - throw restErrorUtil.createRESTException(excp.getMessage()); - } finally { - RangerPerfTracer.log(perf); - } - - if(LOG.isDebugEnabled()) { - LOG.debug("<== ServiceREST.deletePolicy(" + id + ")"); - } - } - - @GET - @Path("/policies/{id}") - @Produces({ "application/json" }) - public RangerPolicy getPolicy(@PathParam("id") Long id) { - if(LOG.isDebugEnabled()) { - LOG.debug("==> ServiceREST.getPolicy(" + id + ")"); - } - - RangerPolicy ret = null; - RangerPerfTracer perf = null; - - try { - if(RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { - perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "ServiceREST.getPolicy(policyId=" + id + ")"); - } - ret = svcStore.getPolicy(id); - - if(ret != null) { - ensureAdminAndAuditAccess(ret); - } - } catch(WebApplicationException excp) { - throw excp; - } catch(Throwable excp) { - LOG.error("getPolicy(" + id + ") failed", excp); - - throw restErrorUtil.createRESTException(excp.getMessage()); - } finally { - RangerPerfTracer.log(perf); - } - - if(ret == null) { - throw restErrorUtil.createRESTException(HttpServletResponse.SC_NOT_FOUND, "Not found", true); - } - - if(LOG.isDebugEnabled()) { - LOG.debug("<== ServiceREST.getPolicy(" + id + "): " + ret); - } - - return ret; - } - - @GET - @Path("/policyLabels") - @Produces({ "application/json" }) - public List getPolicyLabels(@Context HttpServletRequest request) { - if (LOG.isDebugEnabled()) { - LOG.debug("==> ServiceREST.getPolicyLabels()"); - } - - List ret = new ArrayList(); - RangerPerfTracer perf = null; - - try { - if (RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { - perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "ServiceREST.getPolicyLabels()"); - } - - SearchFilter filter = searchUtil.getSearchFilter(request, policyLabelsService.sortFields); - ret = svcStore.getPolicyLabels(filter); - } catch (WebApplicationException excp) { - throw excp; - } catch (Throwable excp) { - LOG.error("getPolicyLabels() failed", excp); - - throw restErrorUtil.createRESTException(excp.getMessage()); - } finally { - RangerPerfTracer.log(perf); - } - - if (LOG.isDebugEnabled()) { - LOG.debug("<== ServiceREST.getPolicyLabels()"); - } - return ret; - } - - @GET - @Path("/policies") - @Produces({ "application/json" }) - public RangerPolicyList getPolicies(@Context HttpServletRequest request) { - if (LOG.isDebugEnabled()) { - LOG.debug("==> ServiceREST.getPolicies()"); - } - - RangerPolicyList ret = new RangerPolicyList(); - RangerPerfTracer perf = null; - - SearchFilter filter = searchUtil.getSearchFilter(request, policyService.sortFields); - - try { - if(RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { - perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "ServiceREST.getPolicies()"); - } - // get all policies from the store; pick the page to return after applying filter - final int savedStartIndex = filter.getStartIndex(); - final int savedMaxRows = filter.getMaxRows(); - - filter.setStartIndex(0); - filter.setMaxRows(Integer.MAX_VALUE); - - List policies = svcStore.getPolicies(filter); - - filter.setStartIndex(savedStartIndex); - filter.setMaxRows(savedMaxRows); - - policies = applyAdminAccessFilter(policies); - - ret = toRangerPolicyList(policies, filter); - - } catch(WebApplicationException excp) { - throw excp; - } catch (Throwable excp) { - LOG.error("getPolicies() failed", excp); - - throw restErrorUtil.createRESTException(excp.getMessage()); - } finally { - RangerPerfTracer.log(perf); - } - - if (LOG.isDebugEnabled()) { - LOG.debug("<== ServiceREST.getPolicies(): count=" + (ret == null ? 0 : ret.getListSize())); - } - return ret; - } + @Autowired + RangerValidatorFactory validatorFactory; - /** - * Resets/ removes service policy cache for given service. - * @param serviceName non-empty serviceName - * @return {@code true} if successfully reseted/ removed for given service, {@code false} otherwise. - */ - @GET - @Path("/policies/cache/reset") - @Produces({ "application/json" }) - public boolean resetPolicyCache(@QueryParam("serviceName") String serviceName) { - if (LOG.isDebugEnabled()) { - LOG.debug("==> ServiceREST.resetPolicyCache(" + serviceName + ")"); - } + @Autowired + RangerDaoManager daoManager; - if (StringUtils.isEmpty(serviceName)) { - throw restErrorUtil.createRESTException("Required parameter [serviceName] is missing.", MessageEnums.INVALID_INPUT_DATA); - } + @Autowired + TagDBStore tagStore; - RangerService rangerService = null; - try { - rangerService = svcStore.getServiceByName(serviceName); - } catch (Exception e) { - LOG.error( HttpServletResponse.SC_BAD_REQUEST + "No Service Found for ServiceName:" + serviceName ); - } + @Autowired + RangerTransactionSynchronizationAdapter rangerTransactionSynchronizationAdapter; - if (rangerService == null) { - throw restErrorUtil.createRESTException(HttpServletResponse.SC_BAD_REQUEST , "Invalid service name", true); - } + private RangerPolicyEngineOptions delegateAdminOptions; + private RangerPolicyEngineOptions policySearchAdminOptions; + private RangerPolicyEngineOptions defaultAdminOptions; - // check for ADMIN access - if (!bizUtil.isAdmin()) { - boolean isServiceAdmin = false; - String loggedInUser = bizUtil.getCurrentUserLoginId(); + public static Map getAccessResourceObjectMap(Map map) { + Map ret = null; - try { - isServiceAdmin = bizUtil.isUserServiceAdmin(rangerService, loggedInUser); - } catch (Exception e) { - LOG.warn("Failed to find if user [" + loggedInUser + "] has service admin privileges on service [" + serviceName + "]", e); - } + if (map != null) { + ret = new HashMap<>(map.size()); - if (!isServiceAdmin) { - throw restErrorUtil.createRESTException("User cannot reset policy cache", MessageEnums.OPER_NO_PERMISSION); + for (Map.Entry e : map.entrySet()) { + if (e.getValue().contains(",")) { + List values = Arrays.asList(e.getValue().split(",")); + + ret.put(e.getKey(), values); + } else { + ret.put(e.getKey(), e.getValue()); + } } } - boolean ret = svcStore.resetPolicyCache(serviceName); + return ret; + } + + @PostConstruct + public void initStore() { + tagStore.setServiceStore(svcStore); + + delegateAdminOptions = getDelegatedAdminPolicyEngineOptions(); + policySearchAdminOptions = getPolicySearchRangerAdminPolicyEngineOptions(); + defaultAdminOptions = getDefaultRangerAdminPolicyEngineOptions(); + } + + @POST + @Path("/definitions") + @Consumes("application/json") + @Produces("application/json") + @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.CREATE_SERVICE_DEF + "\")") + public RangerServiceDef createServiceDef(RangerServiceDef serviceDef) { + LOG.debug("==> ServiceREST.createServiceDef({})", serviceDef); + + RangerServiceDef ret; + RangerPerfTracer perf = null; + + /** + * If display name is blank (EMPTY String or NULL), use name. + */ + if (StringUtils.isBlank(serviceDef.getDisplayName())) { + serviceDef.setDisplayName(serviceDef.getName()); + } - if (LOG.isDebugEnabled()) { - LOG.debug("<== ServiceREST.resetPolicyCache(): ret=" + ret); + try { + if (RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { + perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "ServiceREST.createServiceDef(serviceDefName=" + serviceDef.getName() + ")"); + } + + RangerServiceDefValidator validator = validatorFactory.getServiceDefValidator(svcStore); + + validator.validate(serviceDef, Action.CREATE); + + bizUtil.hasAdminPermissions("Service-Def"); + bizUtil.hasKMSPermissions("Service-Def", serviceDef.getImplClass()); + bizUtil.blockAuditorRoleUser(); + + ret = svcStore.createServiceDef(serviceDef); + } catch (WebApplicationException excp) { + throw excp; + } catch (Throwable excp) { + LOG.error("createServiceDef({}) failed", serviceDef, excp); + + throw restErrorUtil.createRESTException(excp.getMessage()); + } finally { + RangerPerfTracer.log(perf); } + LOG.debug("<== ServiceREST.createServiceDef({}): {}", serviceDef, ret); + return ret; } - /** - * Resets/ removes service policy cache for all. - * @return {@code true} if successfully reseted/ removed, {@code false} otherwise. - */ - @GET - @Path("/policies/cache/reset-all") - @Produces({ "application/json" }) - public boolean resetPolicyCacheAll() { - if (LOG.isDebugEnabled()) { - LOG.debug("==> ServiceREST.resetPolicyCacheAll()"); + @PUT + @Path("/definitions/{id}") + @Consumes("application/json") + @Produces("application/json") + @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.UPDATE_SERVICE_DEF + "\")") + public RangerServiceDef updateServiceDef(RangerServiceDef serviceDef, @PathParam("id") Long id) { + LOG.debug("==> ServiceREST.updateServiceDef(serviceDefName={})", serviceDef.getName()); + + // if serviceDef.id and param 'id' are specified, serviceDef.id should be same as the param 'id' + // if serviceDef.id is null, then set param 'id' into serviceDef Object + if (serviceDef.getId() == null) { + serviceDef.setId(id); + } else if (StringUtils.isBlank(serviceDef.getName()) && !serviceDef.getId().equals(id)) { + throw restErrorUtil.createRESTException(HttpServletResponse.SC_BAD_REQUEST, "serviceDef Id mismatch", true); } - // check for ADMIN access - if (!bizUtil.isAdmin()) { - throw restErrorUtil.createRESTException("User cannot reset policy cache", MessageEnums.OPER_NO_PERMISSION); - } + RangerServiceDef ret; + RangerPerfTracer perf = null; - boolean ret = svcStore.resetPolicyCache(null); + try { + if (RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { + perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "ServiceREST.updateServiceDef(" + serviceDef.getName() + ")"); + } + + /** + * If display name is blank (EMPTY String or NULL), use previous display name. + */ + if (StringUtils.isBlank(serviceDef.getDisplayName())) { + RangerServiceDef rangerServiceDef = svcStore.getServiceDef(serviceDef.getId()); + + // If previous display name is blank (EMPTY String or NULL), user name. + if (Objects.isNull(rangerServiceDef) || StringUtils.isBlank(rangerServiceDef.getDisplayName())) { + serviceDef.setDisplayName(serviceDef.getName()); + } else { + serviceDef.setDisplayName(rangerServiceDef.getDisplayName()); + } + } + + RangerServiceDefValidator validator = validatorFactory.getServiceDefValidator(svcStore); + + validator.validate(serviceDef, Action.UPDATE); + + bizUtil.hasAdminPermissions("Service-Def"); + bizUtil.hasKMSPermissions("Service-Def", serviceDef.getImplClass()); + bizUtil.blockAuditorRoleUser(); + + ret = svcStore.updateServiceDef(serviceDef); + } catch (WebApplicationException excp) { + throw excp; + } catch (Throwable excp) { + LOG.error("updateServiceDef({}) failed", serviceDef, excp); - if (LOG.isDebugEnabled()) { - LOG.debug("<== ServiceREST.resetPolicyCacheAll(): ret=" + ret); + throw restErrorUtil.createRESTException(excp.getMessage()); + } finally { + RangerPerfTracer.log(perf); } + LOG.debug("<== ServiceREST.updateServiceDef({}): {}", serviceDef, ret); + return ret; } - @GET - @Path("/policies/downloadExcel") - @Produces("application/ms-excel") - public void getPoliciesInExcel(@Context HttpServletRequest request, - @Context HttpServletResponse response) { - - if (LOG.isDebugEnabled()) { - LOG.debug("==> ServiceREST.getPoliciesInExcel()"); - } - RangerPerfTracer perf = null; - SearchFilter filter = searchUtil.getSearchFilter(request, policyService.sortFields); - - try { - if (RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { - perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "ServiceREST.getPoliciesInExcel()"); - } - List policyLists = new ArrayList(); - - policyLists = getAllFilteredPolicyList(filter, request, policyLists); - if (CollectionUtils.isNotEmpty(policyLists)){ - Map mapServiceTypeAndImplClass = new HashMap(); - for (RangerPolicy rangerPolicy : policyLists) { - if (rangerPolicy != null) { - ensureAdminAndAuditAccess(rangerPolicy, mapServiceTypeAndImplClass); - } - } - svcStore.getPoliciesInExcel(policyLists, response); - }else{ - response.setStatus(HttpServletResponse.SC_NO_CONTENT); - LOG.error("No policies found to download!"); - } - - RangerExportPolicyList rangerExportPolicyList = new RangerExportPolicyList(); - rangerExportPolicyList.setMetaDataInfo(svcStore.getMetaDataInfo()); - String metaDataInfo = JsonUtilsV2.mapToJson(rangerExportPolicyList.getMetaDataInfo()); - - policyService.createTransactionLog(new XXTrxLogV2(AppConstants.CLASS_TYPE_RANGER_POLICY, null, null, "EXPORT EXCEL"), "Export Excel", metaDataInfo, null); - } catch (WebApplicationException excp) { - throw excp; - } catch (Throwable excp) { - LOG.error("Error while downloading policy report", excp); - throw restErrorUtil.createRESTException(excp.getMessage()); - } finally { - RangerPerfTracer.log(perf); - } - } - - @GET - @Path("/policies/csv") - @Produces("text/csv") - public void getPoliciesInCsv(@Context HttpServletRequest request, @Context HttpServletResponse response) throws IOException { - - if (LOG.isDebugEnabled()) { - LOG.debug("==> ServiceREST.getPoliciesInCsv()"); - } - RangerPerfTracer perf = null; - - SearchFilter filter = searchUtil.getSearchFilter(request, policyService.sortFields); - - try { - if (RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { - perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "ServiceREST.getPoliciesInCsv()"); - } - List policyLists = new ArrayList(); - - policyLists = getAllFilteredPolicyList(filter, request, policyLists); - if (CollectionUtils.isNotEmpty(policyLists)){ - Map mapServiceTypeAndImplClass = new HashMap (); - for (RangerPolicy rangerPolicy : policyLists) { - if (rangerPolicy != null) { - ensureAdminAndAuditAccess(rangerPolicy, mapServiceTypeAndImplClass); - } - } - svcStore.getPoliciesInCSV(policyLists, response); - }else{ - response.setStatus(HttpServletResponse.SC_NO_CONTENT); - LOG.error("No policies found to download!"); - } - - RangerExportPolicyList rangerExportPolicyList = new RangerExportPolicyList(); - rangerExportPolicyList.setMetaDataInfo(svcStore.getMetaDataInfo()); - String metaDataInfo = JsonUtilsV2.mapToJson(rangerExportPolicyList.getMetaDataInfo()); - - policyService.createTransactionLog(new XXTrxLogV2(AppConstants.CLASS_TYPE_RANGER_POLICY, null, null, "EXPORT CSV"), "Export CSV", metaDataInfo, null); - } catch (WebApplicationException excp) { - throw excp; - } catch (Throwable excp) { - LOG.error("Error while downloading policy report", excp); - throw restErrorUtil.createRESTException(excp.getMessage()); - } finally { - RangerPerfTracer.log(perf); - } - } - - @GET - @Path("/policies/exportJson") - @Produces("text/json") - public void getPoliciesInJson(@Context HttpServletRequest request, - @Context HttpServletResponse response, - @QueryParam("checkPoliciesExists") Boolean checkPoliciesExists) { - if (LOG.isDebugEnabled()) { - LOG.debug("==> ServiceREST.getPoliciesInJson()"); - } - - RangerPerfTracer perf = null; - SearchFilter filter = searchUtil.getSearchFilter(request,policyService.sortFields); - requestParamsValidation(filter); - try { - if (RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { - perf = RangerPerfTracer.getPerfTracer(PERF_LOG,"ServiceREST.getPoliciesInJson()"); - } - if (checkPoliciesExists == null){ - checkPoliciesExists = false; - } - - List policyLists = new ArrayList(); - - policyLists = getAllFilteredPolicyList(filter, request, policyLists); - - if (CollectionUtils.isNotEmpty(policyLists)) { - Map mapServiceTypeAndImplClass = new HashMap (); - for (RangerPolicy rangerPolicy : policyLists) { - if (rangerPolicy != null) { - ensureAdminAndAuditAccess(rangerPolicy, mapServiceTypeAndImplClass); - } - } - bizUtil.blockAuditorRoleUser(); - svcStore.getObjectInJson(policyLists, response, JSON_FILE_NAME_TYPE.POLICY); - } else { - checkPoliciesExists = true; - response.setStatus(HttpServletResponse.SC_NO_CONTENT); - LOG.error("There is no Policy to Export!!"); - } - - if(!checkPoliciesExists){ - RangerExportPolicyList rangerExportPolicyList = new RangerExportPolicyList(); - rangerExportPolicyList.setMetaDataInfo(svcStore.getMetaDataInfo()); - String metaDataInfo = JsonUtilsV2.mapToJson(rangerExportPolicyList.getMetaDataInfo()); - - policyService.createTransactionLog(new XXTrxLogV2(AppConstants.CLASS_TYPE_RANGER_POLICY, null, null, "EXPORT JSON"), "Export Json", metaDataInfo, null); - } - } catch (WebApplicationException excp) { - throw excp; - } catch (Throwable excp) { - LOG.error("Error while exporting policy file!!", excp); - throw restErrorUtil.createRESTException(excp.getMessage()); - } finally { - RangerPerfTracer.log(perf); - } - } - - private void requestParamsValidation(SearchFilter filter) { - Boolean fetchAllZonePolicies = Boolean.valueOf(filter.getParam(SearchFilter.FETCH_ZONE_UNZONE_POLICIES)); - String zoneName = filter.getParam(SearchFilter.ZONE_NAME); - - if (fetchAllZonePolicies && StringUtils.isNotEmpty(zoneName)) { - throw restErrorUtil.createRESTException("Invalid parameter: " + SearchFilter.ZONE_NAME + " can not be provided, along with " + SearchFilter.FETCH_ZONE_UNZONE_POLICIES + "=true"); - } - } - - @POST - @Path("/policies/importPoliciesFromFile") - @Consumes({MediaType.MULTIPART_FORM_DATA, MediaType.APPLICATION_JSON}) - @Produces({ "application/json" }) - @PreAuthorize("@rangerPreAuthSecurityHandler.isAdminOrKeyAdminRole()") - public void importPoliciesFromFile( - @Context HttpServletRequest request, - @FormDataParam("servicesMapJson") InputStream serviceMapStream, - @FormDataParam("zoneMapJson") InputStream zoneMapStream, - @FormDataParam("file") InputStream uploadedInputStream, - @FormDataParam("file") FormDataContentDisposition fileDetail, - @QueryParam("isOverride") Boolean isOverride, - @QueryParam("importType") String importType) { - if (LOG.isDebugEnabled()) { - LOG.debug("==> ServiceREST.importPoliciesFromFile()"); - } - - RangerContextHolder.getOrCreateOpContext().setBulkModeContext(true); - - RangerPerfTracer perf = null; - String metaDataInfo = null; - request.setAttribute(PARAM_IMPORT_IN_PROGRESS, true); - - try { - if (RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { - perf = RangerPerfTracer.getPerfTracer(PERF_LOG,"ServiceREST.importPoliciesFromFile()"); - } - - policyService.createTransactionLog(new XXTrxLogV2(AppConstants.CLASS_TYPE_RANGER_POLICY, null, null, "IMPORT START"), "Import", "IMPORT START", null); - - if (isOverride == null){ - isOverride = false; - } - List serviceNameList = new ArrayList(); - - getServiceNameList(request,serviceNameList); - Map servicesMappingMap = new LinkedHashMap(); - List sourceServices = new ArrayList(); - List destinationServices = new ArrayList(); - Map zoneMappingMap = new LinkedHashMap(); - List sourceZones = new ArrayList(); - List destinationZones = new ArrayList(); - if (zoneMapStream != null) { - zoneMappingMap = svcStore.getMapFromInputStream(zoneMapStream); - processZoneMapping(zoneMappingMap, sourceZones, destinationZones); - } - - if (serviceMapStream != null){ - servicesMappingMap = svcStore.getMapFromInputStream(serviceMapStream); - processServiceMapping(servicesMappingMap, sourceServices, destinationServices); - } - - String fileName = fileDetail.getFileName(); - int totalPolicyCreate = 0; - String zoneNameInJson = null; - Map policiesMap = new LinkedHashMap(); - List dataFileSourceServices = new ArrayList(); - if (fileName.endsWith("json")) { - try { - RangerExportPolicyList rangerExportPolicyList = null; - List policies = null; - rangerExportPolicyList = processPolicyInputJsonForMetaData(uploadedInputStream,rangerExportPolicyList); - if (rangerExportPolicyList != null && !CollectionUtils.sizeIsEmpty(rangerExportPolicyList.getMetaDataInfo())) { - metaDataInfo = JsonUtilsV2.mapToJson(rangerExportPolicyList.getMetaDataInfo()); - } else { - LOG.info("metadata info is not provided!!"); - } - policies = getPoliciesFromProvidedJson(rangerExportPolicyList); - - int i = 0; - if (CollectionUtils.sizeIsEmpty(servicesMappingMap) && isOverride){ - if(policies != null && !CollectionUtils.sizeIsEmpty(policies)){ - for (RangerPolicy policyInJson: policies){ - if (policyInJson != null ) { - if (i == 0 && StringUtils.isNotBlank(policyInJson.getZoneName())) { - zoneNameInJson = policyInJson.getZoneName().trim(); - } - if (StringUtils.isNotEmpty(policyInJson.getService().trim())) { - String serviceName = policyInJson.getService().trim(); - if (CollectionUtils.isNotEmpty(serviceNameList) && serviceNameList.contains(serviceName) && !sourceServices.contains(serviceName) && !destinationServices.contains(serviceName)) { - sourceServices.add(serviceName); - destinationServices.add(serviceName); - } else if (CollectionUtils.isEmpty(serviceNameList) - && !sourceServices.contains(serviceName) - && !destinationServices.contains(serviceName)) { - sourceServices.add(serviceName); - destinationServices.add(serviceName); - } - }else{ - LOG.error("Service Name or Policy Name is not provided!!"); - throw restErrorUtil.createRESTException("Service Name or Policy Name is not provided!!"); - } - } - i++; - } - } - }else if (!CollectionUtils.sizeIsEmpty(servicesMappingMap)) { - if (policies != null && !CollectionUtils.sizeIsEmpty(policies)){ - i = 0; - for (RangerPolicy policyInJson: policies){ - if (policyInJson != null){ - if (i == 0 && StringUtils.isNotBlank(policyInJson.getZoneName())) { - zoneNameInJson = policyInJson.getZoneName().trim(); - } - if (StringUtils.isNotEmpty(policyInJson.getService().trim())) { - dataFileSourceServices.add(policyInJson.getService().trim()); - }else{ - LOG.error("Service Name or Policy Name is not provided!!"); - throw restErrorUtil.createRESTException("Service Name or Policy Name is not provided!!"); - } - i++; - } - } - if(!dataFileSourceServices.containsAll(sourceServices)){ - LOG.error("Json File does not contain sepcified source service name."); - throw restErrorUtil.createRESTException("Json File does not contain sepcified source service name."); - } - } - } - boolean deleteIfExists=("true".equalsIgnoreCase(StringUtils.trimToEmpty(request.getParameter(PARAM_DELETE_IF_EXISTS)))) ? true : false ; - boolean updateIfExists=("true".equalsIgnoreCase(StringUtils.trimToEmpty(request.getParameter(PARAM_UPDATE_IF_EXISTS)))) ? true : false ; - String polResource = request.getParameter(SearchFilter.POL_RESOURCE); - if (updateIfExists) { - isOverride = false; - } - - String destinationZoneName = getDestinationZoneName(destinationZones,zoneNameInJson); - if (isOverride && !updateIfExists && StringUtils.isEmpty(polResource)) { - if (LOG.isDebugEnabled()) { - LOG.debug("Deleting Policy from provided services in servicesMapJson file..."); - } - if (CollectionUtils.isNotEmpty(sourceServices) && CollectionUtils.isNotEmpty(destinationServices)) { - deletePoliciesProvidedInServiceMap(sourceServices, destinationServices,destinationZoneName);//In order to delete Zone specific policies from service - } - } else if (updateIfExists && StringUtils.isNotEmpty(polResource)) { - if (LOG.isDebugEnabled()) { - LOG.debug("Deleting Policy from provided services in servicesMapJson file for specific resource..."); - } - if (CollectionUtils.isNotEmpty(sourceServices) && CollectionUtils.isNotEmpty(destinationServices)){ - deletePoliciesForResource(sourceServices, destinationServices, request, policies,destinationZoneName);//In order to delete Zone specific policies from service - } - } - if (policies != null && !CollectionUtils.sizeIsEmpty(policies)){ - for (RangerPolicy policyInJson: policies){ - if (policyInJson != null){ - if (StringUtils.isNotBlank(destinationZoneName)) { - boolean isZoneServiceExistAtDestination = validateDestZoneServiceMapping(destinationZoneName, policyInJson, servicesMappingMap); - if(!isZoneServiceExistAtDestination) { - LOG.warn("provided service of policy in File is not associated with zone"); - continue; - } - } - policiesMap = svcStore.createPolicyMap(zoneMappingMap, sourceZones, destinationZoneName, - servicesMappingMap, sourceServices, destinationServices, policyInJson, - policiesMap);// zone Info is also sent for creating policy map - } - } - if (deleteIfExists) { - //deleting target policies if already exist - deleteExactMatchPolicyForResource(policies, request.getRemoteUser(), destinationZoneName); - } - } - - totalPolicyCreate = createPolicesBasedOnPolicyMap(request,policiesMap, serviceNameList, updateIfExists, totalPolicyCreate); - if(!(totalPolicyCreate > 0)){ - LOG.error("zero policy is created from provided data file!!"); - throw restErrorUtil.createRESTException("zero policy is created from provided data file!!"); - } - - } catch (IOException e) { - LOG.error(e.getMessage()); - throw restErrorUtil.createRESTException(e.getMessage()); - } - }else{ - LOG.error("Provided file format is not supported!!"); - throw restErrorUtil.createRESTException("Provided file format is not supported!!"); - } - } catch(JsonSyntaxException ex) { - LOG.error("Provided json file is not valid!!", ex); - - policyService.createTransactionLog(new XXTrxLogV2(AppConstants.CLASS_TYPE_RANGER_POLICY, null, null, "IMPORT ERROR"), "Import failed", StringUtils.isNotEmpty(metaDataInfo) ? metaDataInfo : null, null); - - throw restErrorUtil.createRESTException(ex.getMessage()); - }catch (WebApplicationException excp) { - LOG.error("Error while importing policy from file!!", excp); - - policyService.createTransactionLog(new XXTrxLogV2(AppConstants.CLASS_TYPE_RANGER_POLICY, null, null, "IMPORT ERROR"), "Import failed", StringUtils.isNotEmpty(metaDataInfo) ? metaDataInfo : null, null); - - throw excp; - } catch (Throwable excp) { - LOG.error("Error while importing policy from file!!", excp); - - policyService.createTransactionLog(new XXTrxLogV2(AppConstants.CLASS_TYPE_RANGER_POLICY, null, null, "IMPORT ERROR"), "Import failed", StringUtils.isNotEmpty(metaDataInfo) ? metaDataInfo : null, null); - - throw restErrorUtil.createRESTException(excp.getMessage()); - } finally { - RangerPerfTracer.log(perf); - - policyService.createTransactionLog(new XXTrxLogV2(AppConstants.CLASS_TYPE_RANGER_POLICY, null, null, "IMPORT END"), "IMPORT END", StringUtils.isNotEmpty(metaDataInfo) ? metaDataInfo : null, null); - - if (LOG.isDebugEnabled()) { - LOG.debug("<== ServiceREST.importPoliciesFromFile()"); - } - } - } - - private int createPolicesBasedOnPolicyMap(HttpServletRequest request, Map policiesMap, - List serviceNameList, boolean updateIfExists, int totalPolicyCreate) { - boolean mergeIfExists = "true".equalsIgnoreCase(StringUtils.trimToEmpty(request.getParameter(PARAM_MERGE_IF_EXISTS))) ? true : false; - boolean deleteIfExists = "true".equalsIgnoreCase(StringUtils.trimToEmpty(request.getParameter(PARAM_DELETE_IF_EXISTS))) ? true : false; - if (!CollectionUtils.sizeIsEmpty(policiesMap.entrySet())) { - for (Entry entry : policiesMap.entrySet()) { - RangerPolicy policy = entry.getValue(); - if (policy != null){ - if (!CollectionUtils.isEmpty(serviceNameList)) { - for (String service : serviceNameList) { - if (StringUtils.isNotEmpty(service.trim()) && StringUtils.isNotEmpty(policy.getService().trim())){ - if (policy.getService().trim().equalsIgnoreCase(service.trim())) { - if (updateIfExists || mergeIfExists || deleteIfExists) { - request.setAttribute(PARAM_SERVICE_NAME, policy.getService()); - request.setAttribute(PARAM_POLICY_NAME, policy.getName()); - request.setAttribute(PARAM_ZONE_NAME, policy.getZoneName()); - if(mergeIfExists && !ServiceRESTUtil.containsRangerCondition(policy)) { - String user = request.getRemoteUser(); - RangerPolicy existingPolicy; - try { - existingPolicy = getExactMatchPolicyForResource(policy, StringUtils.isNotBlank(user) ? user :"admin"); - } catch (Exception e) { - existingPolicy=null; - } - if (existingPolicy == null) { - createPolicy(policy, request); - } else { - ServiceRESTUtil.mergeExactMatchPolicyForResource(existingPolicy, policy); - updatePolicy(existingPolicy, null); - } - } else { - createPolicy(policy, request); - } - } else { - createPolicy(policy, request); - } - totalPolicyCreate = totalPolicyCreate + 1; - if (LOG.isDebugEnabled()) { - LOG.debug("Policy " + policy.getName() + " created successfully."); - } - break; - } - } else { - LOG.error("Service Name or Policy Name is not provided!!"); - throw restErrorUtil.createRESTException("Service Name or Policy Name is not provided!!"); - } - } - } else { - if (updateIfExists || mergeIfExists || deleteIfExists) { - request.setAttribute(PARAM_SERVICE_NAME, policy.getService()); - request.setAttribute(PARAM_POLICY_NAME, policy.getName()); - request.setAttribute(PARAM_ZONE_NAME, policy.getZoneName()); - if(mergeIfExists && !ServiceRESTUtil.containsRangerCondition(policy)) { - String user = request.getRemoteUser(); - RangerPolicy existingPolicy; - try { - existingPolicy = getExactMatchPolicyForResource(policy, StringUtils.isNotBlank(user) ? user :"admin"); - } catch (Exception e) { - existingPolicy=null; - } - if (existingPolicy == null) { - createPolicy(policy, request); - } else { - ServiceRESTUtil.mergeExactMatchPolicyForResource(existingPolicy, policy); - updatePolicy(existingPolicy, null); - } - } else { - createPolicy(policy, request); - } - } else { - createPolicy(policy, request); - } - totalPolicyCreate = totalPolicyCreate + 1; - if (LOG.isDebugEnabled()) { - LOG.debug("Policy " + policy.getName() + " created successfully."); - } - } - } - if(totalPolicyCreate % RangerBizUtil.POLICY_BATCH_SIZE == 0) { - bizUtil.bulkModeOnlyFlushAndClear(); - } - } - bizUtil.bulkModeOnlyFlushAndClear(); - if (LOG.isDebugEnabled()) { - LOG.debug("Total Policy Created From Json file : " + totalPolicyCreate); - } - } - return totalPolicyCreate; - } - - private List getPoliciesFromProvidedJson(RangerExportPolicyList rangerExportPolicyList) { - List policies = null; - if (rangerExportPolicyList != null && !CollectionUtils.sizeIsEmpty(rangerExportPolicyList.getPolicies())) { - policies = rangerExportPolicyList.getPolicies(); - } else { - LOG.error("Provided json file does not contain any policy!!"); - throw restErrorUtil.createRESTException("Provided json file does not contain any policy!!"); - } - return policies; - } - - private RangerExportPolicyList processPolicyInputJsonForMetaData(InputStream uploadedInputStream, - RangerExportPolicyList rangerExportPolicyList) throws Exception { - String policiesString = IOUtils.toString(uploadedInputStream); - policiesString = policiesString.trim(); - if (StringUtils.isNotEmpty(policiesString)) { - rangerExportPolicyList = JsonUtilsV2.jsonToObj(policiesString, RangerExportPolicyList.class); - } else { - LOG.error("Provided json file is empty!!"); - throw restErrorUtil.createRESTException("Provided json file is empty!!"); - } - return rangerExportPolicyList; - } - - private void getServiceNameList(HttpServletRequest request, List serviceNameList) { - SearchFilter filter = searchUtil.getSearchFilter(request,policyService.sortFields); - String serviceType = null; - List serviceTypeList = null; - if (StringUtils.isNotEmpty(request.getParameter(PARAM_SERVICE_TYPE))){ - serviceType = request.getParameter(PARAM_SERVICE_TYPE); - } - if(StringUtils.isNotEmpty(serviceType)){ - serviceTypeList = new ArrayList(Arrays.asList(serviceType.split(","))); - } - List rangerServiceList = null; - List rangerServiceLists = new ArrayList(); - if (CollectionUtils.isNotEmpty(serviceTypeList)){ - for (String s : serviceTypeList) { - filter.removeParam(PARAM_SERVICE_TYPE); - filter.setParam(PARAM_SERVICE_TYPE, s.trim()); - rangerServiceList = getServices(filter); - rangerServiceLists.addAll(rangerServiceList); - } - } - if(!CollectionUtils.sizeIsEmpty(rangerServiceLists)){ - for(RangerService rService : rangerServiceLists){ - if (StringUtils.isNotEmpty(rService.getName())){ - serviceNameList.add(rService.getName()); - } - } - } - } - - private boolean validateDestZoneServiceMapping(String destinationZoneName, RangerPolicy policyInJson, - Map servicesMappingMap) { - boolean isZoneServiceExistAtDestination = false; - XXSecurityZone xdestZone = daoManager.getXXSecurityZoneDao().findByZoneName(destinationZoneName); - if (xdestZone == null) { - LOG.error("destination zone provided does not exist"); - throw restErrorUtil.createRESTException("destination zone provided does not exist"); - } - // CHECK IF json policies service is there on destination and asscioated with - // destination zone. - - String serviceNameToCheck = policyInJson.getService(); - - if (StringUtils.isNotBlank(serviceNameToCheck) && servicesMappingMap.containsKey(serviceNameToCheck)) { - serviceNameToCheck = servicesMappingMap.get(policyInJson.getService()); - } - List serviceZoneMapping = daoManager.getXXSecurityZoneRefService() - .findByServiceNameAndZoneId(serviceNameToCheck, xdestZone.getId()); - List tagServiceZoneMapping = daoManager.getXXSecurityZoneRefTagService() - .findByTagServiceNameAndZoneId(serviceNameToCheck, xdestZone.getId()); - - if (!CollectionUtils.isEmpty(serviceZoneMapping) || !CollectionUtils.isEmpty(tagServiceZoneMapping)) { - isZoneServiceExistAtDestination = true; - } - - return isZoneServiceExistAtDestination; - } - - private String getDestinationZoneName(List destinationZones, String zoneNameInJson) { - String destinationZoneName = null; - if (CollectionUtils.isNotEmpty(destinationZones)) { - destinationZoneName = destinationZones.get(0); - } else { - destinationZoneName = zoneNameInJson; - } - return destinationZoneName; - } - - private void processServiceMapping(Map servicesMappingMap, List sourceServices, - List destinationServices) { - if (!CollectionUtils.sizeIsEmpty(servicesMappingMap)) { - for (Entry map : servicesMappingMap.entrySet()) { - String sourceServiceName = null; - String destinationServiceName = null; - if (StringUtils.isNotEmpty(map.getKey().trim()) && StringUtils.isNotEmpty(map.getValue().trim())) { - sourceServiceName = map.getKey().trim(); - destinationServiceName = map.getValue().trim(); - } else { - LOG.error("Source service or destination service name is not provided!!"); - throw restErrorUtil - .createRESTException("Source service or destonation service name is not provided!!"); - } - if (StringUtils.isNotEmpty(sourceServiceName) && StringUtils.isNotEmpty(destinationServiceName)) { - sourceServices.add(sourceServiceName); - destinationServices.add(destinationServiceName); - } - } - } - } - - private void processZoneMapping(Map zoneMappingMap, List sourceZones, - List destinationZones) { - - if (!CollectionUtils.sizeIsEmpty(zoneMappingMap)) { - for (Entry map : zoneMappingMap.entrySet()) { - String sourceZoneName = null; - String destinationZoneName = null; - if (StringUtils.isNotEmpty(map.getKey().trim()) || StringUtils.isNotEmpty(map.getValue().trim())) { - // zone to zone - // zone to unzone - // unzone to zone - sourceZoneName = map.getKey().trim(); - destinationZoneName = map.getValue().trim(); - LOG.info("sourceZoneName =" + sourceZoneName + "destinationZoneName = " + destinationZoneName); - } else if (StringUtils.isEmpty(map.getKey().trim()) && StringUtils.isEmpty(map.getValue().trim())) { - LOG.info("Unzone to unzone policies import"); - } else { - LOG.error("Source zone or destination zone name is not provided!!"); - throw restErrorUtil.createRESTException("Source zone or destination zone name is not provided!!"); - } - if (StringUtils.isNotEmpty(sourceZoneName) || StringUtils.isNotEmpty(destinationZoneName)) { - sourceZones.add(sourceZoneName); - destinationZones.add(destinationZoneName); - } - } - } - } - - private List getAllFilteredPolicyList(SearchFilter filter, - HttpServletRequest request, List policyLists) { - String serviceNames = null; - String serviceType = null; - List serviceNameList = null; - List serviceTypeList = null; - List serviceNameInServiceTypeList = new ArrayList(); - boolean isServiceExists = false; - - if (request.getParameter(PARAM_SERVICE_NAME) != null){ - serviceNames = request.getParameter(PARAM_SERVICE_NAME); - } - if (StringUtils.isNotEmpty(serviceNames)) { - serviceNameList = new ArrayList(Arrays.asList(serviceNames.split(","))); - } - - if (request.getParameter(PARAM_SERVICE_TYPE) != null){ - serviceType = request.getParameter(PARAM_SERVICE_TYPE); - } - if(StringUtils.isNotEmpty(serviceType)){ - serviceTypeList = new ArrayList(Arrays.asList(serviceType.split(","))); - } - - List policyList = new ArrayList(); - List policyListByServiceName = new ArrayList(); - - if (filter != null) { - filter.setStartIndex(0); - filter.setMaxRows(Integer.MAX_VALUE); - - if (!CollectionUtils.isEmpty(serviceTypeList)) { - for (String s : serviceTypeList) { - filter.removeParam(PARAM_SERVICE_TYPE); - if (request.getParameter(PARAM_SERVICE_NAME) != null){ - filter.removeParam(PARAM_SERVICE_NAME); - } - filter.setParam(PARAM_SERVICE_TYPE, s.trim()); - policyList = getPolicies(filter); - policyLists.addAll(policyList); - } - if(!CollectionUtils.sizeIsEmpty(policyLists)){ - for (RangerPolicy rangerPolicy:policyLists){ - if (StringUtils.isNotEmpty(rangerPolicy.getService())){ - serviceNameInServiceTypeList.add(rangerPolicy.getService()); - } - } - } - } - if (!CollectionUtils.isEmpty(serviceNameList) && !CollectionUtils.isEmpty(serviceTypeList)){ - isServiceExists = serviceNameInServiceTypeList.containsAll(serviceNameList); - if(isServiceExists){ - for (String s : serviceNameList) { - filter.removeParam(PARAM_SERVICE_NAME); - filter.removeParam(PARAM_SERVICE_TYPE); - filter.setParam(PARAM_SERVICE_NAME, s.trim()); - policyList = getPolicies(filter); - policyListByServiceName.addAll(policyList); - } - policyLists = policyListByServiceName; - }else{ - policyLists = new ArrayList(); - } - }else if (CollectionUtils.isEmpty(serviceNameList) && CollectionUtils.isEmpty(serviceTypeList)){ - policyLists = getPolicies(filter); - } - if (!CollectionUtils.isEmpty(serviceNameList) && CollectionUtils.isEmpty(serviceTypeList)) { - for (String s : serviceNameList) { - filter.removeParam(PARAM_SERVICE_NAME); - filter.setParam(PARAM_SERVICE_NAME, s.trim()); - policyList = getPolicies(filter); - policyLists.addAll(policyList); - } - } - } - if (StringUtils.isNotEmpty(request.getParameter("resourceMatch")) - && "full".equalsIgnoreCase(request.getParameter("resourceMatch"))) { - policyLists = serviceUtil.getMatchingPoliciesForResource(request, policyLists); - } - Map orderedPolicies = new TreeMap(); - - if (!CollectionUtils.isEmpty(policyLists)) { - for (RangerPolicy policy : policyLists) { - if (policy != null) { - //set createTime & updateTime Time as null since exported policies dont need this - policy.setCreateTime(null); - policy.setUpdateTime(null); - orderedPolicies.put(policy.getId(), policy); - } - } - if (!orderedPolicies.isEmpty()) { - policyLists.clear(); - policyLists.addAll(orderedPolicies.values()); - } - } - return policyLists; - } - - private void deletePoliciesProvidedInServiceMap(List sourceServices, List destinationServices, String zoneName) throws Exception { - int totalDeletedPolicies = 0; - if (CollectionUtils.isNotEmpty(sourceServices) - && CollectionUtils.isNotEmpty(destinationServices)) { - RangerPolicyValidator validator = validatorFactory.getPolicyValidator(svcStore); - for (int i = 0; i < sourceServices.size(); i++) { - if (!destinationServices.get(i).isEmpty() ) { - SearchFilter filter = new SearchFilter(); - filter.setParam(SearchFilter.ZONE_NAME, zoneName); - filter.setParam(SearchFilter.SERVICE_NAME, destinationServices.get(i)); - RangerService service=getServiceByName(destinationServices.get(i)); - final RangerPolicyList servicePolicies = getServicePolicies(destinationServices.get(i),filter); - if (servicePolicies != null) { - List rangerPolicyList = servicePolicies.getPolicies(); - if (CollectionUtils.isNotEmpty(rangerPolicyList)) { - for (RangerPolicy rangerPolicy : rangerPolicyList) { - if (rangerPolicy != null) { - validator.validate(rangerPolicy.getId(), Action.DELETE); - ensureAdminAccess(rangerPolicy); - bizUtil.blockAuditorRoleUser(); - svcStore.deletePolicy(rangerPolicy, service); - totalDeletedPolicies = totalDeletedPolicies + 1; - if (totalDeletedPolicies % RangerBizUtil.POLICY_BATCH_SIZE == 0) { - bizUtil.bulkModeOnlyFlushAndClear(); - } - if (LOG.isDebugEnabled()) { - LOG.debug("Policy " + rangerPolicy.getName() + " deleted successfully."); - LOG.debug("TotalDeletedPilicies: " + totalDeletedPolicies); - } - } - } - bizUtil.bulkModeOnlyFlushAndClear(); - } - } - } - } - } - if (LOG.isDebugEnabled()) { - LOG.debug("Total Deleted Policy : " + totalDeletedPolicies); - } - } - - private void deletePoliciesForResource(List sourceServices, List destinationServices, HttpServletRequest request, List exportPolicies, String zoneName) throws Exception { - int totalDeletedPolicies = 0; - if (CollectionUtils.isNotEmpty(sourceServices) - && CollectionUtils.isNotEmpty(destinationServices)) { - Set exportedPolicyNames=new HashSet(); - if (CollectionUtils.isNotEmpty(exportPolicies)) { - for (RangerPolicy rangerPolicy : exportPolicies) { - if (rangerPolicy!=null) { - exportedPolicyNames.add(rangerPolicy.getName()); - } - } - } - for (int i = 0; i < sourceServices.size(); i++) { - if (!destinationServices.get(i).isEmpty()) { - RangerPolicyList servicePolicies = null; - SearchFilter filter = searchUtil.getSearchFilter(request,policyService.sortFields); - filter.setParam("zoneName", zoneName); - servicePolicies = getServicePolicies(destinationServices.get(i), filter); - RangerService service=getServiceByName(destinationServices.get(i)); - if (servicePolicies != null) { - List rangerPolicyList = servicePolicies.getPolicies(); - if (CollectionUtils.isNotEmpty(rangerPolicyList)) { - List policiesToBeDeleted = new ArrayList(); - for (RangerPolicy rangerPolicy : rangerPolicyList) { - if (rangerPolicy != null) { - Map rangerPolicyResourceMap=rangerPolicy.getResources(); - if (rangerPolicyResourceMap!=null) { - RangerPolicyResource rangerPolicyResource=null; - if (rangerPolicyResourceMap.containsKey("path")) { - rangerPolicyResource=rangerPolicyResourceMap.get("path"); - } else if (rangerPolicyResourceMap.containsKey("database")) { - rangerPolicyResource=rangerPolicyResourceMap.get("database"); - } - if (rangerPolicyResource!=null) { - if (CollectionUtils.isNotEmpty(rangerPolicyResource.getValues()) && rangerPolicyResource.getValues().size()>1) { - continue; - } - } - } - if (rangerPolicy.getId() != null) { - if (!exportedPolicyNames.contains(rangerPolicy.getName())) { - policiesToBeDeleted.add(rangerPolicy); - } - } - } - } - if (CollectionUtils.isNotEmpty(policiesToBeDeleted)) { - for (RangerPolicy rangerPolicy : policiesToBeDeleted) { - svcStore.deletePolicy(rangerPolicy, service); - if (LOG.isDebugEnabled()) { - LOG.debug("Policy " + rangerPolicy.getName() + " deleted successfully."); - } - totalDeletedPolicies = totalDeletedPolicies + 1; - if (totalDeletedPolicies % RangerBizUtil.POLICY_BATCH_SIZE == 0) { - bizUtil.bulkModeOnlyFlushAndClear(); - } - } - bizUtil.bulkModeOnlyFlushAndClear(); - } - } - } - } - } - } - } - - public List getPolicies(SearchFilter filter) { - if(LOG.isDebugEnabled()) { - LOG.debug("==> ServiceREST.getPolicies(filter)"); - } - - List ret = null; - RangerPerfTracer perf = null; - - try { - if (RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { - perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "ServiceREST.getPolicies()"); - } - ret = svcStore.getPolicies(filter); - - ret = applyAdminAccessFilter(ret); - } catch(WebApplicationException excp) { - throw excp; - } catch(Throwable excp) { - LOG.error("getPolicies() failed", excp); - - throw restErrorUtil.createRESTException(excp.getMessage()); - } finally { - RangerPerfTracer.log(perf); - } - - if(LOG.isDebugEnabled()) { - LOG.debug("<== ServiceREST.getPolicies(filter): count=" + (ret == null ? 0 : ret.size())); - } - - return ret; - } - - @GET - @Path("/policies/count") - @Produces({ "application/json" }) - public Long countPolicies( @Context HttpServletRequest request) { - if(LOG.isDebugEnabled()) { - LOG.debug("==> ServiceREST.countPolicies():"); - } - - Long ret = null; - RangerPerfTracer perf = null; - - try { - if(RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { - perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "ServiceREST.countPolicies()"); - } - List policies = getPolicies(request).getPolicies(); - - policies = applyAdminAccessFilter(policies); - - ret = Long.valueOf(policies == null ? 0 : policies.size()); - } catch(WebApplicationException excp) { - throw excp; - } catch(Throwable excp) { - LOG.error("countPolicies() failed", excp); - - throw restErrorUtil.createRESTException(excp.getMessage()); - } finally { - RangerPerfTracer.log(perf); - } - - if(LOG.isDebugEnabled()) { - LOG.debug("<== ServiceREST.countPolicies(): " + ret); - } - - return ret; - } - - @GET - @Path("/policies/service/{id}") - @Produces({ "application/json" }) - public RangerPolicyList getServicePolicies(@PathParam("id") Long serviceId, - @Context HttpServletRequest request) { - if (LOG.isDebugEnabled()) { - LOG.debug("==> ServiceREST.getServicePolicies(" + serviceId + ")"); - } - - RangerPolicyList ret = new RangerPolicyList(); - RangerPerfTracer perf = null; - - SearchFilter filter = searchUtil.getSearchFilter(request, policyService.sortFields); - try { - if(RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { - perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "ServiceREST.getServicePolicies(serviceId=" + serviceId + ")"); - } - - String policyTypeStr = filter.getParam(SearchFilter.POLICY_TYPE); - if (policyTypeStr != null && !IntStream.of(RangerPolicy.POLICY_TYPES).anyMatch(x -> x == Integer.parseInt(policyTypeStr))) { - throw restErrorUtil.createRESTException("policyTypes with id: " + policyTypeStr + " does not exist", - MessageEnums.DATA_NOT_FOUND, Long.parseLong(policyTypeStr), null, - "readResource : No Object found with given id."); - } - - // get all policies from the store; pick the page to return after applying filter - int savedStartIndex = filter == null ? 0 : filter.getStartIndex(); - int savedMaxRows = filter == null ? Integer.MAX_VALUE : filter.getMaxRows(); - - if(filter != null) { - filter.setStartIndex(0); - filter.setMaxRows(Integer.MAX_VALUE); - } - - List servicePolicies = svcStore.getServicePolicies(serviceId, filter); - - if(filter != null) { - filter.setStartIndex(savedStartIndex); - filter.setMaxRows(savedMaxRows); - } - - servicePolicies = applyAdminAccessFilter(servicePolicies); - - ret = toRangerPolicyList(servicePolicies, filter); - - } catch(WebApplicationException excp) { - throw excp; - } catch (Throwable excp) { - LOG.error("getServicePolicies(" + serviceId + ") failed", excp); - - throw restErrorUtil.createRESTException(excp.getMessage()); - } finally { - RangerPerfTracer.log(perf); - } - - if (LOG.isDebugEnabled()) { - LOG.debug("<== ServiceREST.getServicePolicies(" + serviceId + "): count=" - + (ret == null ? 0 : ret.getListSize())); - } - return ret; - } - - - @GET - @Path("/policies/service/name/{name}") - @Produces({ "application/json" }) - public RangerPolicyList getServicePoliciesByName(@PathParam("name") String serviceName, - @Context HttpServletRequest request) { - if (LOG.isDebugEnabled()) { - LOG.debug("==> ServiceREST.getServicePolicies(" + serviceName + ")"); - } - - SearchFilter filter = searchUtil.getSearchFilter(request, policyService.sortFields); - - RangerPolicyList ret = getServicePolicies(serviceName, filter); - - if (LOG.isDebugEnabled()) { - LOG.debug("<== ServiceREST.getServicePolicies(" + serviceName + "): count=" - + (ret == null ? 0 : ret.getListSize())); - } - - return ret; - } - - private RangerPolicyList getServicePolicies(String serviceName, SearchFilter filter) { - RangerPerfTracer perf = null; - try { - if(RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { - perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "ServiceREST.getServicePolicies(serviceName=" + serviceName + ")"); - } - - // get all policies from the store; pick the page to return after applying filter - int savedStartIndex = filter == null ? 0 : filter.getStartIndex(); - int savedMaxRows = filter == null ? Integer.MAX_VALUE : filter.getMaxRows(); - - if(filter != null) { - filter.setStartIndex(0); - filter.setMaxRows(Integer.MAX_VALUE); - } - - List servicePolicies = svcStore.getServicePolicies(serviceName, filter); - - if(filter != null) { - filter.setStartIndex(savedStartIndex); - filter.setMaxRows(savedMaxRows); - } - - servicePolicies = applyAdminAccessFilter(servicePolicies); - - return toRangerPolicyList(servicePolicies, filter); - - } catch(WebApplicationException excp) { - throw excp; - } catch (Throwable excp) { - LOG.error("getServicePolicies(" + serviceName + ") failed", excp); - - throw restErrorUtil.createRESTException(excp.getMessage()); - } finally { - RangerPerfTracer.log(perf); - } - } - - @GET - @Path("/policies/download/{serviceName}") - @Produces({ "application/json" }) - public ServicePolicies getServicePoliciesIfUpdated( - @PathParam("serviceName") String serviceName, - @DefaultValue("-1") @QueryParam("lastKnownVersion") Long lastKnownVersion, - @DefaultValue("0") @QueryParam("lastActivationTime") Long lastActivationTime, - @QueryParam("pluginId") String pluginId, - @DefaultValue("") @QueryParam("clusterName") String clusterName, - @DefaultValue("") @QueryParam("zoneName") String zoneName, - @DefaultValue("false") @QueryParam("supportsPolicyDeltas") Boolean supportsPolicyDeltas, - @DefaultValue("") @QueryParam("pluginCapabilities") String pluginCapabilities, - @Context HttpServletRequest request) throws Exception { - if (LOG.isDebugEnabled()) { - LOG.debug("==> ServiceREST.getServicePoliciesIfUpdated(" - + serviceName + ", " + lastKnownVersion + ", " - + lastActivationTime + ", " + pluginId + ", " - + clusterName + ", " + supportsPolicyDeltas + ")"); - } - - ServicePolicies ret = null; - int httpCode = HttpServletResponse.SC_OK; - String logMsg = null; - RangerPerfTracer perf = null; - Long downloadedVersion = null; - boolean isValid = false; - - try { - bizUtil.failUnauthenticatedDownloadIfNotAllowed(); - - isValid = serviceUtil.isValidateHttpsAuthentication(serviceName, request); - } catch (WebApplicationException webException) { - httpCode = webException.getResponse().getStatus(); - logMsg = webException.getResponse().getEntity().toString(); - } catch (Exception e) { - httpCode = HttpServletResponse.SC_BAD_REQUEST; - logMsg = e.getMessage(); - } - - if (isValid) { - try { - if(RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { - perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "ServiceREST.getServicePoliciesIfUpdated(serviceName=" + serviceName + ",lastKnownVersion=" + lastKnownVersion + ",lastActivationTime=" + lastActivationTime + ")"); - } - ret = svcStore.getServicePoliciesIfUpdated(serviceName, lastKnownVersion, !supportsPolicyDeltas); - - if (ret == null) { - downloadedVersion = lastKnownVersion; - httpCode = HttpServletResponse.SC_NOT_MODIFIED; - logMsg = "No change since last update"; - } else { - downloadedVersion = ret.getPolicyVersion(); - httpCode = HttpServletResponse.SC_OK; - logMsg = "Returning " + (ret.getPolicies() != null ? ret.getPolicies().size() : (ret.getPolicyDeltas() != null ? ret.getPolicyDeltas().size() : 0)) + " policies. Policy version=" + ret.getPolicyVersion(); - } - } catch (Throwable excp) { - LOG.error("getServicePoliciesIfUpdated(" + serviceName + ", " + lastKnownVersion + ", " + lastActivationTime + ") failed", excp); - - httpCode = HttpServletResponse.SC_BAD_REQUEST; - logMsg = excp.getMessage(); - } finally { - createPolicyDownloadAudit(serviceName, lastKnownVersion, pluginId, httpCode, clusterName, zoneName, request); - RangerPerfTracer.log(perf); - } - } - assetMgr.createPluginInfo(serviceName, pluginId, request, RangerPluginInfo.ENTITY_TYPE_POLICIES, downloadedVersion, lastKnownVersion, lastActivationTime, httpCode, clusterName, pluginCapabilities); - - if(httpCode != HttpServletResponse.SC_OK) { - boolean logError = httpCode != HttpServletResponse.SC_NOT_MODIFIED; - throw restErrorUtil.createRESTException(httpCode, logMsg, logError); - } - - if(LOG.isDebugEnabled()) { - LOG.debug("<== ServiceREST.getServicePoliciesIfUpdated(" + serviceName + ", " + lastKnownVersion + ", " + lastActivationTime + ", " + pluginId + ", " + clusterName + ", " + supportsPolicyDeltas + "): count=" + ((ret == null || ret.getPolicies() == null) ? 0 : ret.getPolicies().size())); - } - - return ret; - } - - @GET - @Path("/secure/policies/download/{serviceName}") - @Produces({ "application/json" }) - public ServicePolicies getSecureServicePoliciesIfUpdated( - @PathParam("serviceName") String serviceName, - @DefaultValue("-1") @QueryParam("lastKnownVersion") Long lastKnownVersion, - @DefaultValue("0") @QueryParam("lastActivationTime") Long lastActivationTime, - @QueryParam("pluginId") String pluginId, - @DefaultValue("") @QueryParam("clusterName") String clusterName, - @DefaultValue("") @QueryParam("zoneName") String zoneName, - @DefaultValue("false") @QueryParam("supportsPolicyDeltas") Boolean supportsPolicyDeltas, - @DefaultValue("") @QueryParam("pluginCapabilities") String pluginCapabilities, - @Context HttpServletRequest request) throws Exception { - if (LOG.isDebugEnabled()) { - LOG.debug("==> ServiceREST.getSecureServicePoliciesIfUpdated(" - + serviceName + ", " + lastKnownVersion + ", " - + lastActivationTime + ", " + pluginId + ", " - + clusterName + ", " + supportsPolicyDeltas + ")"); - } - ServicePolicies ret = null; - int httpCode = HttpServletResponse.SC_OK; - String logMsg = null; - RangerPerfTracer perf = null; - boolean isAllowed = false; - boolean isAdmin = bizUtil.isAdmin(); - boolean isKeyAdmin = bizUtil.isKeyAdmin(); - request.setAttribute("downloadPolicy", "secure"); - Long downloadedVersion = null; - boolean isValid = false; - try { - isValid = serviceUtil.isValidService(serviceName, request); - } catch (WebApplicationException webException) { - httpCode = webException.getResponse().getStatus(); - logMsg = webException.getResponse().getEntity().toString(); - } catch (Exception e) { - httpCode = HttpServletResponse.SC_BAD_REQUEST; - logMsg = e.getMessage(); - } - - if (isValid) { - try { - if (RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { - perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "ServiceREST.getSecureServicePoliciesIfUpdated(serviceName=" + serviceName + ",lastKnownVersion=" + lastKnownVersion + ",lastActivationTime=" + lastActivationTime + ")"); - } - XXService xService = daoManager.getXXService().findByName(serviceName); - XXServiceDef xServiceDef = daoManager.getXXServiceDef().getById(xService.getType()); - RangerService rangerService = null; - - if (StringUtils.equals(xServiceDef.getImplclassname(), EmbeddedServiceDefsUtil.KMS_IMPL_CLASS_NAME)) { - rangerService = svcStore.getServiceByNameForDP(serviceName); - if (isKeyAdmin) { - isAllowed = true; - } else { - if (rangerService != null) { - isAllowed = bizUtil.isUserAllowed(rangerService, Allowed_User_List_For_Download); - if (!isAllowed) { - isAllowed = bizUtil.isUserAllowed(rangerService, Allowed_User_List_For_Grant_Revoke); - } - } - } - } else { - rangerService = svcStore.getServiceByName(serviceName); - if (isAdmin) { - isAllowed = true; - } else { - if (rangerService != null) { - isAllowed = bizUtil.isUserAllowed(rangerService, Allowed_User_List_For_Download); - if (!isAllowed) { - isAllowed = bizUtil.isUserAllowed(rangerService, Allowed_User_List_For_Grant_Revoke); - } - } - } - } - if (isAllowed) { - ret = svcStore.getServicePoliciesIfUpdated(serviceName, lastKnownVersion, !supportsPolicyDeltas); - if (ret == null) { - downloadedVersion = lastKnownVersion; - httpCode = HttpServletResponse.SC_NOT_MODIFIED; - logMsg = "No change since last update"; - } else { - downloadedVersion = ret.getPolicyVersion(); - - httpCode = HttpServletResponse.SC_OK; - logMsg = "Returning " + (ret.getPolicies() != null ? ret.getPolicies().size() : (ret.getPolicyDeltas() != null ? ret.getPolicyDeltas().size() : 0)) + " policies. Policy version=" + ret.getPolicyVersion(); - } - - } else { - LOG.error("getSecureServicePoliciesIfUpdated(" + serviceName + ", " + lastKnownVersion + ") failed as User doesn't have permission to download Policy"); - httpCode = HttpServletResponse.SC_FORBIDDEN; // assert user is authenticated. - logMsg = "User doesn't have permission to download policy"; - } - } catch (Throwable excp) { - LOG.error("getSecureServicePoliciesIfUpdated(" + serviceName + ", " + lastKnownVersion + ", " + lastActivationTime + ") failed", excp); - httpCode = HttpServletResponse.SC_BAD_REQUEST; - logMsg = excp.getMessage(); - } finally { - createPolicyDownloadAudit(serviceName, lastKnownVersion, pluginId, httpCode, clusterName, zoneName, request); - RangerPerfTracer.log(perf); - } - } - assetMgr.createPluginInfo(serviceName, pluginId, request, RangerPluginInfo.ENTITY_TYPE_POLICIES, downloadedVersion, lastKnownVersion, lastActivationTime, httpCode, clusterName, pluginCapabilities); - - if (httpCode != HttpServletResponse.SC_OK) { - boolean logError = httpCode != HttpServletResponse.SC_NOT_MODIFIED; - throw restErrorUtil.createRESTException(httpCode, logMsg, logError); - } - if (LOG.isDebugEnabled()) { - LOG.debug("<== ServiceREST.getSecureServicePoliciesIfUpdated(" + serviceName + ", " + lastKnownVersion + ", " + lastActivationTime + ", " + pluginId + ", " + clusterName + ", " + supportsPolicyDeltas + "): count=" + ((ret == null || ret.getPolicies() == null) ? 0 : ret.getPolicies().size())); - } - return ret; - } - - @DELETE - @Path("/server/policydeltas") - @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") - public void deletePolicyDeltas(@DefaultValue("7") @QueryParam("days") Integer olderThan, @Context HttpServletRequest request) { - if (LOG.isDebugEnabled()) { - LOG.debug("==> ServiceREST.deletePolicyDeltas(" + olderThan + ")"); - } - - svcStore.resetPolicyUpdateLog(olderThan, RangerPolicyDelta.CHANGE_TYPE_INVALIDATE_POLICY_DELTAS); - - if (LOG.isDebugEnabled()) { - LOG.debug("<== ServiceREST.deletePolicyDeltas(" + olderThan + ")"); - } - } - - @DELETE - @Path("/server/purgepolicies/{serviceName}") - @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") - public void purgeEmptyPolicies(@PathParam("serviceName") String serviceName, @Context HttpServletRequest request) { - if (LOG.isDebugEnabled()) { - LOG.debug("==> ServiceREST.purgeEmptyPolicies(" + serviceName + ")"); - } - - if (serviceName == null) { - throw restErrorUtil.createRESTException(HttpServletResponse.SC_BAD_REQUEST , "Invalid service name", true); - } - - RangerPerfTracer perf = null; - - try { - if(RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { - perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "ServiceREST.purgeEmptyPolicies(serviceName=" + serviceName + ")"); - } - - if (svcStore.getServiceByName(serviceName) == null) { - throw new Exception("service does not exist - name=" + serviceName); - } - - ServicePolicies servicePolicies = svcStore.getServicePolicies(serviceName, -1L); - if (servicePolicies != null && CollectionUtils.isNotEmpty(servicePolicies.getPolicies())) { - for (RangerPolicy policy : servicePolicies.getPolicies()) { - if (CollectionUtils.isEmpty(PolicyRefUpdater.getAllPolicyItems(policy))) { - deletePolicy(policy.getId()); - } - } - } - } catch(WebApplicationException excp) { - throw excp; - } catch(Throwable excp) { - LOG.error("purgeEmptyPolicies(" + serviceName + ") failed", excp); - - throw restErrorUtil.createRESTException(excp.getMessage()); - } finally { - RangerPerfTracer.log(perf); - } - - if (LOG.isDebugEnabled()) { - LOG.debug("<== ServiceREST.purgeEmptyPolicies(" + serviceName + ")"); - } - } - - private void createPolicyDownloadAudit(String serviceName, Long lastKnownVersion, String pluginId, int httpRespCode, String clusterName, String zoneName, HttpServletRequest request) { - try { - String ipAddress = request.getHeader("X-FORWARDED-FOR"); - - if (ipAddress == null) { - ipAddress = request.getRemoteAddr(); - } - - XXPolicyExportAudit policyExportAudit = new XXPolicyExportAudit(); - - policyExportAudit.setRepositoryName(serviceName); - policyExportAudit.setAgentId(pluginId); - policyExportAudit.setClientIP(ipAddress); - policyExportAudit.setRequestedEpoch(lastKnownVersion); - policyExportAudit.setHttpRetCode(httpRespCode); - policyExportAudit.setClusterName(clusterName); - policyExportAudit.setZoneName(zoneName); - assetMgr.createPolicyAudit(policyExportAudit); - } catch(Exception excp) { - LOG.error("error while creating policy download audit", excp); - } - } - - private RangerPolicy getExactMatchPolicyForResource(String serviceName, RangerAccessResource resource, String zoneName, String user) throws Exception { - if(LOG.isDebugEnabled()) { - LOG.debug("==> ServiceREST.getExactMatchPolicyForResource(" + resource + ", " + zoneName + ", " + user + ")"); - } - - RangerPolicy ret = null; - RangerPolicyAdmin policyAdmin = getPolicyAdmin(serviceName); - List policies = policyAdmin != null ? policyAdmin.getExactMatchPolicies(resource, zoneName, null) : null; - - if(CollectionUtils.isNotEmpty(policies)) { - // at this point, ret is a policy in policy-engine; the caller might update the policy (for grant/revoke); so get a copy from the store - ret = svcStore.getPolicy(policies.get(0).getId()); - } - - if(LOG.isDebugEnabled()) { - LOG.debug("<== ServiceREST.getExactMatchPolicyForResource(" + resource + ", " + zoneName + ", " + user + "): " + ret); - } - - return ret; - } - - private RangerPolicy getExactMatchPolicyForResource(RangerPolicy policy, String user) throws Exception { - if(LOG.isDebugEnabled()) { - LOG.debug("==> ServiceREST.getExactMatchPolicyForResource(" + policy + ", " + user + ")"); - } - - RangerPolicy ret = null; - RangerPolicyAdmin policyAdmin = getPolicyAdmin(policy.getService()); - List policies = policyAdmin != null ? policyAdmin.getExactMatchPolicies(policy, null) : null; - - if(CollectionUtils.isNotEmpty(policies)) { - // at this point, ret is a policy in policy-engine; the caller might update the policy (for grant/revoke); so get a copy from the store - if(policies.size()==1) { - ret = svcStore.getPolicy(policies.get(0).getId()); - } else { - if (StringUtils.isNotEmpty(policy.getZoneName())) { - for(RangerPolicy existingPolicy:policies) { - if (StringUtils.equals(policy.getZoneName(), existingPolicy.getZoneName())) { - ret = svcStore.getPolicy(existingPolicy.getId()); - break; - } - } - } - } - } - - if(LOG.isDebugEnabled()) { - LOG.debug("<== ServiceREST.getExactMatchPolicyForResource(" + policy + ", " + user + "): " + ret); - } - - return ret; - } - - @GET - @Path("/policies/eventTime") - @Produces({ "application/json" }) - @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.GET_POLICY_FROM_EVENT_TIME + "\")") - public RangerPolicy getPolicyFromEventTime(@Context HttpServletRequest request) { - if (LOG.isDebugEnabled()) { - LOG.debug("==> ServiceREST.getPolicyFromEventTime()"); - } - - String eventTimeStr = request.getParameter("eventTime"); - String policyIdStr = request.getParameter("policyId"); - String versionNoStr = request.getParameter("versionNo"); - - if (StringUtils.isEmpty(eventTimeStr) || StringUtils.isEmpty(policyIdStr)) { - throw restErrorUtil.createRESTException("EventTime or policyId cannot be null or empty string.", - MessageEnums.INVALID_INPUT_DATA); - } - - Long policyId = Long.parseLong(policyIdStr); - - RangerPolicy policy=null; - - if (!StringUtil.isEmpty(versionNoStr)) { - int policyVersion = Integer.parseInt(versionNoStr); - try { - policy = svcStore.getPolicyForVersionNumber(policyId, policyVersion); - if (policy != null) { - ensureAdminAndAuditAccess(policy); - } - } catch (WebApplicationException excp) { - throw excp; - } catch (Throwable excp) { - // Ignore any other exception and go for fetching the policy by eventTime - } - } - - if (policy == null) { - try { - policy = svcStore.getPolicyFromEventTime(eventTimeStr, policyId); - if (policy != null) { - ensureAdminAndAuditAccess(policy); - } - } catch (WebApplicationException excp) { - throw excp; - } catch (Throwable excp) { - LOG.error("getPolicy(" + policyId + ") failed", excp); - - throw restErrorUtil.createRESTException(excp.getMessage()); - } - } - - if(policy == null) { - throw restErrorUtil.createRESTException(HttpServletResponse.SC_NOT_FOUND, "Not found", true); - } - - if(LOG.isDebugEnabled()) { - LOG.debug("<== ServiceREST.getPolicy(" + policyId + "): " + policy); - } - - if (LOG.isDebugEnabled()) { - LOG.debug("<== ServiceREST.getPolicyFromEventTime()"); - } - - return policy; - } - - @GET - @Path("/policy/{policyId}/versionList") - @Produces({ "application/json" }) - @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.GET_POLICY_VERSION_LIST + "\")") - public VXString getPolicyVersionList(@PathParam("policyId") Long policyId) { - - VXString policyVersionListStr = svcStore.getPolicyVersionList(policyId); - - return policyVersionListStr; - } - - @GET - @Path("/policy/{policyId}/version/{versionNo}") - @Produces({ "application/json" }) - @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.GET_POLICY_FOR_VERSION_NO + "\")") - public RangerPolicy getPolicyForVersionNumber(@PathParam("policyId") Long policyId, - @PathParam("versionNo") int versionNo) { - RangerPolicy policy = svcStore.getPolicyForVersionNumber(policyId, versionNo); - if (policy != null) { - ensureAdminAndAuditAccess(policy); - } - return policy; - } - - @GET - @Path("/plugins/info") - @Produces({ "application/json" }) - @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.GET_PLUGINS_INFO + "\")") - public RangerPluginInfoList getPluginsInfo(@Context HttpServletRequest request) { - if (LOG.isDebugEnabled()) { - LOG.debug("==> ServiceREST.getPluginsInfo()"); - } - - RangerPluginInfoList ret = null; - - SearchFilter filter = searchUtil.getSearchFilter(request, pluginInfoService.getSortFields()); - - try { - PList paginatedPluginsInfo = pluginInfoService.searchRangerPluginInfo(filter); - if (paginatedPluginsInfo != null) { - ret = new RangerPluginInfoList(); - - ret.setPluginInfoList(paginatedPluginsInfo.getList()); - ret.setPageSize(paginatedPluginsInfo.getPageSize()); - ret.setResultSize(paginatedPluginsInfo.getResultSize()); - ret.setStartIndex(paginatedPluginsInfo.getStartIndex()); - ret.setTotalCount(paginatedPluginsInfo.getTotalCount()); - ret.setSortBy(paginatedPluginsInfo.getSortBy()); - ret.setSortType(paginatedPluginsInfo.getSortType()); - } - } catch (WebApplicationException excp) { - throw excp; - } catch (Throwable excp) { - LOG.error("getPluginsInfo() failed", excp); - - throw restErrorUtil.createRESTException(excp.getMessage()); - } - if (LOG.isDebugEnabled()) { - LOG.debug("<== ServiceREST.getPluginsInfo()"); - } - - return ret; - } - - private List applyAdminAccessFilter(List policies) { - List ret = new ArrayList(); - RangerPerfTracer perf = null; - - if(RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { - perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "ServiceREST.applyAdminAccessFilter(policyCount=" + (policies == null ? 0 : policies.size()) + ")"); - } - - if (CollectionUtils.isNotEmpty(policies)) { - boolean isAdmin = bizUtil.isAdmin(); - boolean isKeyAdmin = bizUtil.isKeyAdmin(); - String userName = bizUtil.getCurrentUserLoginId(); - boolean isAuditAdmin = bizUtil.isAuditAdmin(); - boolean isAuditKeyAdmin = bizUtil.isAuditKeyAdmin(); - Set userGroups = null; - - Map> servicePoliciesMap = new HashMap>(); - Map evalContext = new HashMap<>(); - - RangerAccessRequestUtil.setCurrentUserInContext(evalContext, userName); - - for (int i = 0; i < policies.size(); i++) { - RangerPolicy policy = policies.get(i); - String serviceName = policy.getService(); - List policyList = servicePoliciesMap.get(serviceName); - - if (policyList == null) { - policyList = new ArrayList(); - - servicePoliciesMap.put(serviceName, policyList); - } - policyList.add(policy); - } - - for (Entry> entry : servicePoliciesMap.entrySet()) { - String serviceName = entry.getKey(); - List listToFilter = entry.getValue(); - - if (CollectionUtils.isNotEmpty(listToFilter)) { - boolean isServiceAdminUser = svcStore.isServiceAdminUser(serviceName, userName); - if (isServiceAdminUser) { - ret.addAll(listToFilter); - continue; - } else if (isAdmin || isKeyAdmin || isAuditAdmin || isAuditKeyAdmin) { - XXService xService = daoManager.getXXService().findByName(serviceName); - Long serviceDefId = xService.getType(); - boolean isKmsService = serviceDefId.equals(EmbeddedServiceDefsUtil.instance().getKmsServiceDefId()); - - if (isAdmin) { - if (!isKmsService) { - ret.addAll(listToFilter); - } - } else if (isAuditAdmin) { - if (!isKmsService) { - ret.addAll(listToFilter); - } - } else if (isAuditKeyAdmin) { - if (isKmsService) { - ret.addAll(listToFilter); - } - } else if (isKeyAdmin) { - if (isKmsService) { - ret.addAll(listToFilter); - } - } - continue; - } - - RangerPolicyAdmin policyAdmin = getPolicyAdminForDelegatedAdmin(serviceName); - - if (policyAdmin != null) { - if(userGroups == null) { - userGroups = daoManager.getXXGroupUser().findGroupNamesByUserName(userName); - } - - Set roles = policyAdmin.getRolesFromUserAndGroups(userName, userGroups); - - for (RangerPolicy policy : listToFilter) { - if ((policyAdmin.isDelegatedAdminAccessAllowedForRead(policy, userName, userGroups, roles, evalContext)) - || (!StringUtils.isEmpty(policy.getZoneName()) && (serviceMgr.isZoneAdmin(policy.getZoneName()) || serviceMgr.isZoneAuditor(policy.getZoneName())))) { - ret.add(policy); - } - } - } - - } - } - } - - RangerPerfTracer.log(perf); - - return ret; - } - - void ensureAdminAccess(RangerPolicy policy) { - blockIfGdsService(policy.getService()); - - boolean isAdmin = bizUtil.isAdmin(); - boolean isKeyAdmin = bizUtil.isKeyAdmin(); - String userName = bizUtil.getCurrentUserLoginId(); - boolean isSvcAdmin = isAdmin || svcStore.isServiceAdminUser(policy.getService(), userName); - - if (!isAdmin && !isKeyAdmin && !isSvcAdmin) { - boolean isAllowed = false; - - Set userGroups = userMgr.getGroupsForUser(userName); - - //for zone policy create /update / delete - if(!StringUtils.isEmpty(policy.getZoneName()) && serviceMgr.isZoneAdmin(policy.getZoneName())){ - isAllowed = true; - }else{ - isAllowed = hasAdminAccess(policy, userName, userGroups); - } - - - - if (!isAllowed) { - throw restErrorUtil.createRESTException(HttpServletResponse.SC_FORBIDDEN, - "User '" + userName + "' does not have delegated-admin privilege on given resources", true); - } - } else { - - XXService xService = daoManager.getXXService().findByName(policy.getService()); - XXServiceDef xServiceDef = daoManager.getXXServiceDef().getById(xService.getType()); - - if (isAdmin) { - if (EmbeddedServiceDefsUtil.KMS_IMPL_CLASS_NAME.equals(xServiceDef.getImplclassname())) { - throw restErrorUtil.createRESTException( - "KMS Policies/Services/Service-Defs are not accessible for user '" + userName + "'.", - MessageEnums.OPER_NO_PERMISSION); - } - } else if (isKeyAdmin) { - if (!EmbeddedServiceDefsUtil.KMS_IMPL_CLASS_NAME.equals(xServiceDef.getImplclassname())) { - throw restErrorUtil.createRESTException( - "Only KMS Policies/Services/Service-Defs are accessible for user '" + userName + "'.", - MessageEnums.OPER_NO_PERMISSION); - } - } - } - } - - public void blockIfGdsService(String serviceName) { - String serviceType = daoManager.getXXServiceDef().findServiceDefTypeByServiceName(serviceName); - - if (EMBEDDED_SERVICEDEF_GDS_NAME.equals(serviceType)) { - throw restErrorUtil.createRESTException(HttpServletResponse.SC_FORBIDDEN, EMBEDDED_SERVICEDEF_GDS_NAME.toUpperCase() + " policies can't be managed via this API", true); - } - } - - private RangerPolicyEngineOptions getDelegatedAdminPolicyEngineOptions() { - RangerPolicyEngineOptions opts = new RangerPolicyEngineOptions(); - - final String propertyPrefix = "ranger.admin"; - - opts.configureDelegateAdmin(config, propertyPrefix); - - return opts; - } - - private RangerPolicyEngineOptions getPolicySearchRangerAdminPolicyEngineOptions() { - RangerPolicyEngineOptions opts = new RangerPolicyEngineOptions(); - - final String propertyPrefix = "ranger.admin"; - - opts.configureRangerAdminForPolicySearch(config, propertyPrefix); - return opts; - } - - private RangerPolicyEngineOptions getDefaultRangerAdminPolicyEngineOptions() { - RangerPolicyEngineOptions opts = new RangerPolicyEngineOptions(); - - final String propertyPrefix = "ranger.admin"; - - opts.configureDefaultRangerAdmin(config, propertyPrefix); - return opts; - } - - private boolean hasAdminAccess(RangerPolicy policy, String userName, Set userGroups) { - boolean isAllowed = false; - RangerPolicyAdmin policyAdmin = getPolicyAdminForDelegatedAdmin(policy.getService()); - - if(policyAdmin != null) { - Map evalContext = new HashMap<>(); - RangerAccessRequestUtil.setCurrentUserInContext(evalContext, userName); - - Set roles = policyAdmin.getRolesFromUserAndGroups(userName, userGroups); - - isAllowed = policyAdmin.isDelegatedAdminAccessAllowedForModify(policy, userName, userGroups, roles, evalContext); - } - - return isAllowed; - } - private boolean hasAdminAccess(String serviceName, String zoneName, String userName, Set userGroups, RangerAccessResource resource, Set accessTypes) { - boolean isAllowed = false; - - RangerPolicyAdmin policyAdmin = getPolicyAdminForDelegatedAdmin(serviceName); - - if(policyAdmin != null) { - isAllowed = CollectionUtils.isNotEmpty(accessTypes) && policyAdmin.isDelegatedAdminAccessAllowed(resource, zoneName, userName, userGroups, accessTypes); - } - - return isAllowed; - } - - public RangerPolicyAdmin getPolicyAdminForDelegatedAdmin(String serviceName) { - return RangerPolicyAdminCacheForEngineOptions.getInstance().getServicePoliciesAdmin(serviceName, svcStore, zoneStore, roleDBStore, delegateAdminOptions); - } - - private RangerPolicyAdmin getPolicyAdminForSearch(String serviceName) { - return RangerPolicyAdminCacheForEngineOptions.getInstance().getServicePoliciesAdmin(serviceName, svcStore, zoneStore, roleDBStore, policySearchAdminOptions); - } - - private RangerPolicyAdmin getPolicyAdmin(String serviceName) { - return RangerPolicyAdminCacheForEngineOptions.getInstance().getServicePoliciesAdmin(serviceName, svcStore, zoneStore,roleDBStore, defaultAdminOptions); - } + @DELETE + @Path("/definitions/{id}") + @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.DELETE_SERVICE_DEF + "\")") + public void deleteServiceDef(@PathParam("id") Long id, @Context HttpServletRequest request) { + LOG.debug("==> ServiceREST.deleteServiceDef({})", id); - public List getPoliciesWithMetaAttributes(List policies) { - return svcStore.getPoliciesWithMetaAttributes(policies); - } + RangerPerfTracer perf = null; - @GET - @Path("/checksso") - @Produces(MediaType.TEXT_PLAIN) - public String checkSSO() { - return String.valueOf(bizUtil.isSSOEnabled()); - } - - @GET - @Path("/csrfconf") - @Produces({ "application/json"}) - public HashMap getCSRFProperties(@Context HttpServletRequest request) { - return getCSRFPropertiesMap(request); - } + try { + if (RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { + perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "ServiceREST.deleteServiceDef(serviceDefId=" + id + ")"); + } - @GET - @Path("/metrics/type/{type}") - @Produces({ "application/json" }) - @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.GET_METRICS_BY_TYPE + "\")") - public String getMetricByType(@PathParam("type") String type) { - if (LOG.isDebugEnabled()) { - LOG.debug("==> ServiceREST.getMetricByType(serviceDefName=" + type + ")"); + RangerServiceDefValidator validator = validatorFactory.getServiceDefValidator(svcStore); + + validator.validate(id, Action.DELETE); + + bizUtil.hasAdminPermissions("Service-Def"); + + XXServiceDef xServiceDef = daoManager.getXXServiceDef().getById(id); + + if (xServiceDef != null) { + bizUtil.hasKMSPermissions("Service-Def", xServiceDef.getImplclassname()); + + String forceDeleteStr = request.getParameter("forceDelete"); + boolean forceDelete = !StringUtils.isEmpty(forceDeleteStr) && "true".equalsIgnoreCase(forceDeleteStr); + + svcStore.deleteServiceDef(id, forceDelete); + } else { + LOG.error("Cannot retrieve service-definition:[{}] for deletion", id); + + throw new Exception("deleteServiceDef(" + id + ") failed"); + } + } catch (WebApplicationException excp) { + throw excp; + } catch (Throwable excp) { + LOG.error("deleteServiceDef({}) failed", id, excp); + + throw restErrorUtil.createRESTException(excp.getMessage()); + } finally { + RangerPerfTracer.log(perf); } - // as of now we are allowing only users with Admin role to access this - // API - bizUtil.checkSystemAdminAccess(); - bizUtil.blockAuditorRoleUser(); - String ret = null; + + LOG.debug("<== ServiceREST.deleteServiceDef({})", id); + } + + @GET + @Path("/definitions/{id}") + @Produces("application/json") + @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.GET_SERVICE_DEF + "\")") + public RangerServiceDef getServiceDef(@PathParam("id") Long id) { + LOG.debug("==> ServiceREST.getServiceDef({})", id); + + RangerServiceDef ret; + RangerPerfTracer perf = null; + try { - ServiceDBStore.METRIC_TYPE metricType = ServiceDBStore.METRIC_TYPE.getMetricTypeByName(type); - if (metricType == null) { - throw restErrorUtil.createRESTException("Metric type="+type+", not supported."); + if (RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { + perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "ServiceREST.getServiceDef(serviceDefId=" + id + ")"); } - ret = svcStore.getMetricByType(metricType); + XXServiceDef xServiceDef = daoManager.getXXServiceDef().getById(id); + + if (xServiceDef != null) { + if (EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_TAG_NAME.equals(xServiceDef.getName())) { + if (!bizUtil.hasModuleAccess(RangerConstants.MODULE_TAG_BASED_POLICIES)) { + throw restErrorUtil.createRESTException(HttpServletResponse.SC_FORBIDDEN, "User is not having permissions on the tag module.", true); + } + } + + if (!bizUtil.hasAccess(xServiceDef, null)) { + throw restErrorUtil.createRESTException("User is not allowed to access service-def, id: " + xServiceDef.getId(), MessageEnums.OPER_NO_PERMISSION); + } + } + + ret = svcStore.getServiceDef(id); } catch (WebApplicationException excp) { throw excp; } catch (Throwable excp) { - LOG.error("getMetricByType(" + type + ") failed", excp); + LOG.error("getServiceDef({}) failed", id, excp); + throw restErrorUtil.createRESTException(excp.getMessage()); + } finally { + RangerPerfTracer.log(perf); } + if (ret == null) { throw restErrorUtil.createRESTException(HttpServletResponse.SC_NOT_FOUND, "Not found", true); } - if (LOG.isDebugEnabled()) { - LOG.debug("<== ServiceREST.getMetricByType(" + type + "): " + ret); - } + LOG.debug("<== ServiceREST.getServiceDef({}): {}", id, ret); + return ret; } - /** - * Delete services/ repos associated with cluster. - * Only users with Ranger UserAdmin OR KeyAdmin are allowed to access this API. - * @param clusterName - * @return List of {@link ServiceDeleteResponse serviceDeleteResponse}. - */ - @DELETE - @Path("/cluster-services/{clusterName}") - @Produces({ "application/json" }) - @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.DELETE_CLUSTER_SERVICES + "\")") - public ResponseEntity> deleteClusterServices(@PathParam("clusterName") String clusterName) { - if(LOG.isDebugEnabled()) { - LOG.debug("==> ServiceREST.deleteClusterServices("+ clusterName +")"); - } - - List deletedServices = new ArrayList<>(); - HttpStatus responseStatus = HttpStatus.OK; - - try { - //check if user has ADMIN privileges - bizUtil.hasAdminPermissions("Services"); - - //get all service/ repo IDs to delete - List serviceIdsToBeDeleted = daoManager.getXXServiceConfigMap().findServiceIdsByClusterName(clusterName); - - if (serviceIdsToBeDeleted.isEmpty()) { - responseStatus = HttpStatus.NOT_FOUND; - } else { - //delete each service/ repo one by one - for (Long serviceId : serviceIdsToBeDeleted) { - ServiceDeleteResponse deleteResponse = new ServiceDeleteResponse(serviceId); - try { - String serviceName = this.deleteServiceById(serviceId); - deleteResponse.setServiceName(serviceName); - deleteResponse.setIsDeleted(Boolean.TRUE); - } catch (Throwable e) { - //log and proceed - LOG.warn("Skipping deletion of service with ID="+serviceId); - e.printStackTrace(); - deleteResponse.setIsDeleted(Boolean.FALSE); - deleteResponse.setErrorMsg(e.getMessage()); - } - deletedServices.add(deleteResponse); - - } - } - } catch(WebApplicationException excp) { - throw excp; - } catch(Throwable excp) { - LOG.error("Deleting services associated with cluster=" + clusterName + " failed.", excp); - - throw restErrorUtil.createRESTException(excp.getMessage()); - } - - if(LOG.isDebugEnabled()) { - LOG.debug("<== ServiceREST.deleteClusterServices() - deletedServices: " +deletedServices); - } - - return new ResponseEntity<>(deletedServices, responseStatus); - } - - @GET - @Path("/policies/guid/{guid}") - @Produces({ "application/json" }) - public RangerPolicy getPolicyByGUIDAndServiceNameAndZoneName(@PathParam("guid") String guid, - @DefaultValue("") @QueryParam("serviceName") String serviceName, - @DefaultValue("") @QueryParam("zoneName") String zoneName) { - if (LOG.isDebugEnabled()) { - LOG.debug("==> ServiceREST.getPolicyByGUIDAndServiceNameAndZoneName(" + guid + ", " + serviceName + ", " + zoneName + ")"); - } - RangerPolicy ret = null; - RangerPerfTracer perf = null; - try { - if (RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { - perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "ServiceREST.getPolicyByGUIDAndServiceNameAndZoneName(policyGUID=" + guid + ", serviceName="+ serviceName + ", zoneName="+ zoneName + ")"); - } - ret = svcStore.getPolicy(guid, serviceName, zoneName); - if (ret != null) { - ensureAdminAndAuditAccess(ret); - } - } catch (WebApplicationException excp) { - throw excp; - } catch (Throwable excp) { - LOG.error("getPolicyByGUIDAndServiceNameAndZoneName(" + guid + "," + serviceName + ", " + zoneName + ") failed", excp); - throw restErrorUtil.createRESTException(excp.getMessage()); - } finally { - RangerPerfTracer.log(perf); - } - if (ret == null) { - throw restErrorUtil.createRESTException(HttpServletResponse.SC_NOT_FOUND, "Not found", true); - } - if (LOG.isDebugEnabled()) { - LOG.debug("<== ServiceREST.getPolicyByGUIDAndServiceNameAndZoneName(" + guid + ", " + serviceName + ", " + zoneName +"): " + ret); - } - return ret; - } - - @DELETE - @Path("/policies/guid/{guid}") - public void deletePolicyByGUIDAndServiceNameAndZoneName(@PathParam("guid") String guid, - @DefaultValue("") @QueryParam("serviceName") String serviceName, - @DefaultValue("") @QueryParam("zoneName") String zoneName) { - if (LOG.isDebugEnabled()) { - LOG.debug("==> ServiceREST.deletePolicyByGUIDAndServiceNameAndZoneName(" + guid + ", " + serviceName + ", " + zoneName +")"); - } - RangerPolicy ret = null; - RangerPerfTracer perf = null; - try { - if (RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { - perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "ServiceREST.deletePolicyByGUIDAndServiceNameAndZoneName(policyGUID=" + guid + ", serviceName="+ serviceName + ", zoneName="+ zoneName +")"); - } - ret = getPolicyByGUIDAndServiceNameAndZoneName(guid, serviceName, zoneName); - if (ret != null) { - deletePolicy(ret.getId()); - } - } catch (WebApplicationException excp) { - throw excp; - } catch (Throwable excp) { - LOG.error("deletePolicyByGUIDAndServiceNameAndZoneName(" + guid + "," + serviceName + ", " + zoneName + ") failed", excp); - throw restErrorUtil.createRESTException(excp.getMessage()); - } finally { - RangerPerfTracer.log(perf); - } - if (LOG.isDebugEnabled()) { - LOG.debug("<== ServiceREST.deletePolicyByGUIDAndServiceNameAndZoneName(" + guid + ", " + serviceName + ", " + zoneName +")"); - } - } - - @DELETE - @Path("/server/purge/records") - @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") - public List purgeRecords(@QueryParam("type") String recordType, @DefaultValue("180") @QueryParam("retentionDays") Integer olderThan, @Context HttpServletRequest request) { - if (LOG.isDebugEnabled()) { - LOG.debug("==> ServiceREST.purgeRecords(" + recordType + ", " + olderThan + ")"); - } - - List ret = new ArrayList<>(); - RangerPerfTracer perf = null; - - try { - if (RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { - perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "ServiceREST.purgeRecords(recordType=" + recordType + ", olderThan=" + olderThan + ")"); - } - - if (olderThan < 1) { - throw restErrorUtil.createRESTException(HttpServletResponse.SC_BAD_REQUEST, "Retention days can't be lesser than 1", true); - } - - if (PURGE_RECORD_TYPE_LOGIN_LOGS.equalsIgnoreCase(recordType)) { - svcStore.removeAuthSessions(olderThan, ret); - } else if (PURGE_RECORD_TYPE_TRX_LOGS.equalsIgnoreCase(recordType)) { - svcStore.removeTransactionLogs(olderThan, ret); - } else if (PURGE_RECORD_TYPE_POLICY_EXPORT_LOGS.equalsIgnoreCase(recordType)) { - svcStore.removePolicyExportLogs(olderThan, ret); - } else { - throw restErrorUtil.createRESTException(HttpServletResponse.SC_BAD_REQUEST, - recordType + ": invalid record type. Valid values: [ " + PURGE_RECORD_TYPE_LOGIN_LOGS + ", " + PURGE_RECORD_TYPE_TRX_LOGS + ", " + PURGE_RECORD_TYPE_POLICY_EXPORT_LOGS + " ]", - true); - } - } catch (WebApplicationException excp) { - throw excp; - } catch (Throwable excp) { - LOG.error("purgeRecords(" + recordType + ", " + olderThan + ") failed", excp); - throw restErrorUtil.createRESTException(excp.getMessage()); - } finally { - RangerPerfTracer.log(perf); - } - - if (LOG.isDebugEnabled()) { - LOG.debug("<== ServiceREST.purgeRecords(" + recordType + ", " + olderThan + "): ret=" + ret); - } - - return ret; - } - - public RangerPolicyResource getPolicyResource(Object resourceName, GrantRevokeRequest grantRequest) { - RangerPolicyResource ret; - if (resourceName instanceof List) { - List resourceValues = (List) resourceName; - ret = new RangerPolicyResource(resourceValues, false, grantRequest.getIsRecursive()); - } else { - ret = new RangerPolicyResource((String) resourceName); - ret.setIsRecursive(grantRequest.getIsRecursive()); - } - return ret; - } - - public static Map getAccessResourceObjectMap(Map map) { - Map ret = null; - - if (map != null) { - ret = new HashMap<>(map.size()); - - for (Map.Entry e : map.entrySet()) { - if (e.getValue().contains(",")) { - List values = Arrays.asList(e.getValue().split(",")); - ret.put(e.getKey(),values); - } else { - ret.put(e.getKey(), e.getValue()); - } - } - } - - return ret; - } - - private HashMap getCSRFPropertiesMap(HttpServletRequest request) { - HashMap map = new HashMap(); - map.put(isCSRF_ENABLED, PropertiesUtil.getBooleanProperty(isCSRF_ENABLED, true)); - map.put(CUSTOM_HEADER_PARAM, PropertiesUtil.getProperty(CUSTOM_HEADER_PARAM, RangerCSRFPreventionFilter.HEADER_DEFAULT)); - map.put(BROWSER_USER_AGENT_PARAM, PropertiesUtil.getProperty(BROWSER_USER_AGENT_PARAM, RangerCSRFPreventionFilter.BROWSER_USER_AGENTS_DEFAULT)); - map.put(CUSTOM_METHODS_TO_IGNORE_PARAM, PropertiesUtil.getProperty(CUSTOM_METHODS_TO_IGNORE_PARAM, RangerCSRFPreventionFilter.METHODS_TO_IGNORE_DEFAULT)); - map.put(RangerCSRFPreventionFilter.CSRF_TOKEN, getCSRFToken(request)); - return map; - } - - private static String getCSRFToken(HttpServletRequest request) { - String salt = (String) request.getSession().getAttribute(RangerCSRFPreventionFilter.CSRF_TOKEN); - if (StringUtils.isEmpty(salt)) { - final int tokenLength = PropertiesUtil.getIntProperty(CSRF_TOKEN_LENGTH, 20); - salt = RandomStringUtils.random(tokenLength, 0, 0, true, true, null, new SecureRandom()); - request.getSession().setAttribute(RangerCSRFPreventionFilter.CSRF_TOKEN, salt); - } - return salt; - } - - private RangerPolicyList toRangerPolicyList(List policyList, SearchFilter filter) { - RangerPolicyList ret = new RangerPolicyList(); - - if(CollectionUtils.isNotEmpty(policyList)) { - int totalCount = policyList.size(); - int startIndex = filter.getStartIndex(); - int pageSize = filter.getMaxRows(); - int toIndex = Math.min(startIndex + pageSize, totalCount); - String sortType = filter.getSortType(); - String sortBy = filter.getSortBy(); - - if (StringUtils.isNotEmpty(sortBy) && StringUtils.isNotEmpty(sortType)) { - // By default policyList is sorted by policyId in asc order, So handling only desc case. - if (SearchFilter.POLICY_ID.equalsIgnoreCase(sortBy)) { - if (SORT_ORDER.DESC.name().equalsIgnoreCase(sortType)) { - policyList.sort(this.getPolicyComparator(sortBy, sortType)); - } - } else if (SearchFilter.POLICY_NAME.equalsIgnoreCase(sortBy)) { - if (SORT_ORDER.ASC.name().equalsIgnoreCase(sortType)) { - policyList.sort(this.getPolicyComparator(sortBy, sortType)); - } else if (SORT_ORDER.DESC.name().equalsIgnoreCase(sortType)) { - policyList.sort(this.getPolicyComparator(sortBy, sortType)); - } else { - LOG.info("Invalid or Unsupported sortType : " + sortType); - } - } else { - LOG.info("Invalid or Unsupported sortBy property : " + sortBy); - } - } - - List retList = new ArrayList(); - for(int i = startIndex; i < toIndex; i++) { - retList.add(policyList.get(i)); - } - - ret.setPolicies(retList); - ret.setPageSize(pageSize); - ret.setResultSize(retList.size()); - ret.setStartIndex(startIndex); - ret.setTotalCount(totalCount); - ret.setSortBy(sortBy); - ret.setSortType(sortType); - } - - return ret; - } - - private Comparator getPolicyComparator(String sortBy, String sortType) { - Comparator rangerPolComparator = (RangerPolicy me, RangerPolicy other) -> { - int ret = 0; - if (SearchFilter.POLICY_ID.equalsIgnoreCase(sortBy)) { - ret = Long.compare(other.getId(), me.getId()); - } else if (SearchFilter.POLICY_NAME.equalsIgnoreCase(sortBy)) { - if (SORT_ORDER.ASC.name().equalsIgnoreCase(sortType)) { - ret = me.getName().compareTo(other.getName()); - } else if (SORT_ORDER.DESC.name().equalsIgnoreCase(sortType)) { - ret = other.getName().compareTo(me.getName()); - } - } - return ret; - }; - return rangerPolComparator; - } - - private void validateGrantRevokeRequest(GrantRevokeRequest request, final boolean hasAdminPrivilege, final String loggedInUser) { - if (request != null) { - validateUsersGroupsAndRoles(request.getUsers(),request.getGroups(), request.getRoles()); - validateGrantor(request.getGrantor()); - validateGrantees(request.getUsers()); - validateGroups(request.getGroups()); - validateRoles(request.getRoles()); - - if (!hasAdminPrivilege) { - if (!StringUtils.equals(request.getGrantor(), loggedInUser) || StringUtils.isNotBlank(request.getOwnerUser())) { - throw restErrorUtil.createGrantRevokeRESTException("Invalid grant/revoke request - contains grantor or userOwner specification"); - } - request.setGrantorGroups(userMgr.getGroupsForUser(request.getGrantor())); - } - } - } - - private void validateUsersGroupsAndRoles(Set users, Set groups, Set roles){ - if(CollectionUtils.isEmpty(users) && CollectionUtils.isEmpty(groups) && CollectionUtils.isEmpty(roles)) { - throw restErrorUtil.createGrantRevokeRESTException("Grantee users/groups/roles list is empty"); - } - } - - private void validateGrantor(String grantor) { - VXUser vxUser = null; - if (grantor != null) { - try { - vxUser = xUserService.getXUserByUserName(grantor); - if (vxUser == null) { - throw restErrorUtil.createGrantRevokeRESTException("Grantor user " + grantor + " doesn't exist"); - } - } catch (Exception e) { - throw restErrorUtil.createGrantRevokeRESTException("Grantor user " + grantor + " doesn't exist"); - } - } - } - - private void validateGrantees(Set grantees) { - VXUser vxUser = null; - for (String userName : grantees) { - try { - vxUser = xUserService.getXUserByUserName(userName); - if (vxUser == null) { - throw restErrorUtil.createGrantRevokeRESTException("Grantee user " + userName + " doesn't exist"); - } - } catch (Exception e) { - throw restErrorUtil.createGrantRevokeRESTException("Grantee user " + userName + " doesn't exist"); - } - } - } - - private void validateGroups(Set groups) { - VXGroup vxGroup = null; - for (String groupName : groups) { - try { - vxGroup = userMgr.getGroupByGroupName(groupName); - if (vxGroup == null) { - throw restErrorUtil.createGrantRevokeRESTException( "Grantee group "+ groupName +" doesn't exist"); - } - } catch (Exception e) { - throw restErrorUtil.createGrantRevokeRESTException( "Grantee group "+ groupName +" doesn't exist"); - } - } - } - - private void validateRoles(Set roles) { - XXRole xxRole = null; - for (String role : roles) { - try { - xxRole = daoManager.getXXRole().findByRoleName(role); - if (xxRole == null) { - throw restErrorUtil.createGrantRevokeRESTException( "Grantee role "+ role +" doesn't exist"); - } - } catch (Exception e) { - throw restErrorUtil.createGrantRevokeRESTException( "Grantee role "+ role +" doesn't exist"); - } - } - } - - private Map getOptions(HttpServletRequest request) { - Map ret = null; - if (request != null) { - String isForceRenameOption = request.getParameter(ServiceStore.OPTION_FORCE_RENAME); - if (StringUtils.isNotBlank(isForceRenameOption)) { - ret = new HashMap(); - ret.put(ServiceStore.OPTION_FORCE_RENAME, Boolean.valueOf(isForceRenameOption)); + @GET + @Path("/definitions/name/{name}") + @Produces("application/json") + @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.GET_SERVICE_DEF_BY_NAME + "\")") + public RangerServiceDef getServiceDefByName(@PathParam("name") String name) { + LOG.debug("==> ServiceREST.getServiceDefByName(serviceDefName={})", name); + + RangerServiceDef ret; + RangerPerfTracer perf = null; + + try { + if (RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { + perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "ServiceREST.getServiceDefByName(" + name + ")"); + } + + XXServiceDef xServiceDef = daoManager.getXXServiceDef().findByName(name); + + if (xServiceDef != null) { + if (EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_TAG_NAME.equals(xServiceDef.getName())) { + if (!bizUtil.hasModuleAccess(RangerConstants.MODULE_TAG_BASED_POLICIES)) { + throw restErrorUtil.createRESTException(HttpServletResponse.SC_FORBIDDEN, "User is not having permissions on the tag module", true); + } + } + + if (!bizUtil.hasAccess(xServiceDef, null)) { + throw restErrorUtil.createRESTException("User is not allowed to access service-def: " + xServiceDef.getName(), MessageEnums.OPER_NO_PERMISSION); + } } + + ret = svcStore.getServiceDefByName(name); + } catch (WebApplicationException excp) { + throw excp; + } catch (Throwable excp) { + LOG.error("getServiceDefByName({}) failed", name, excp); + + throw restErrorUtil.createRESTException(excp.getMessage()); + } finally { + RangerPerfTracer.log(perf); + } + + if (ret == null) { + throw restErrorUtil.createRESTException(HttpServletResponse.SC_NOT_FOUND, "Not found", true); } + + LOG.debug("<== ServiceREST.getServiceDefByName({}): {}", name, ret); + return ret; } - - private RangerService hideCriticalServiceDetailsForRoleUser(RangerService rangerService){ - RangerService ret = rangerService; - - ret.setConfigs(null); - ret.setDescription(null); - ret.setCreatedBy(null); - ret.setUpdatedBy(null); - ret.setCreateTime(null); - ret.setUpdateTime(null); - ret.setPolicyVersion(null); - ret.setPolicyUpdateTime(null); - ret.setTagVersion(null); - ret.setTagUpdateTime(null); - ret.setVersion(null); - - return ret; - } - - void ensureAdminAndAuditAccess(RangerPolicy policy) { - ensureAdminAndAuditAccess (policy, new HashMap()); - } - - void ensureAdminAndAuditAccess(RangerPolicy policy, Map mapServiceTypeAndImplClass) { - boolean isAdmin = bizUtil.isAdmin(); - boolean isKeyAdmin = bizUtil.isKeyAdmin(); - String userName = bizUtil.getCurrentUserLoginId(); - boolean isAuditAdmin = bizUtil.isAuditAdmin(); - boolean isAuditKeyAdmin = bizUtil.isAuditKeyAdmin(); - boolean isSvcAdmin = isAdmin || svcStore.isServiceAdminUser(policy.getService(), userName) || (!StringUtils.isEmpty(policy.getZoneName()) && (serviceMgr.isZoneAdmin(policy.getZoneName()) || serviceMgr.isZoneAuditor(policy.getZoneName()))); - if (!isAdmin && !isKeyAdmin && !isSvcAdmin && !isAuditAdmin && !isAuditKeyAdmin) { - boolean isAllowed = false; - - Set userGroups = userMgr.getGroupsForUser(userName); - RangerPolicyAdmin policyAdmin = getPolicyAdminForDelegatedAdmin(policy.getService()); - - if(policyAdmin != null) { - Map evalContext = new HashMap<>(); - RangerAccessRequestUtil.setCurrentUserInContext(evalContext, userName); - - Set roles = policyAdmin.getRolesFromUserAndGroups(userName, userGroups); - - isAllowed = policyAdmin.isDelegatedAdminAccessAllowedForRead(policy, userName, userGroups, roles, evalContext); - } - - if (!isAllowed) { - throw restErrorUtil.createRESTException(HttpServletResponse.SC_FORBIDDEN, "User '" - + userName + "' does not have delegated-admin privilege on given resources", true); - } - } else { - if (StringUtils.isBlank(policy.getServiceType())) { - XXService xService = daoManager.getXXService().findByName(policy.getService()); - XXServiceDef xServiceDef = daoManager.getXXServiceDef().getById(xService.getType()); - mapServiceTypeAndImplClass.put(xServiceDef.getName(), xServiceDef.getImplclassname()); - policy.setServiceType(xServiceDef.getName()); - } else if (!mapServiceTypeAndImplClass.containsKey(policy.getServiceType())) { - XXService xService = daoManager.getXXService().findByName(policy.getService()); - XXServiceDef xServiceDef = daoManager.getXXServiceDef().getById(xService.getType()); - mapServiceTypeAndImplClass.put(xServiceDef.getName(), xServiceDef.getImplclassname()); - } - String serviceDefImplClass = mapServiceTypeAndImplClass.get(policy.getServiceType()); - if (isAdmin || isAuditAdmin) { - if (EmbeddedServiceDefsUtil.KMS_IMPL_CLASS_NAME.equals(serviceDefImplClass)) { - throw restErrorUtil.createRESTException( - "KMS Policies/Services/Service-Defs are not accessible for user '" - + userName + "'.", MessageEnums.OPER_NO_PERMISSION); - } - } else if (isKeyAdmin || isAuditKeyAdmin) { - if (!EmbeddedServiceDefsUtil.KMS_IMPL_CLASS_NAME.equals(serviceDefImplClass)) { - throw restErrorUtil.createRESTException("Only KMS Policies/Services/Service-Defs are accessible for user '" - + userName + "'.", MessageEnums.OPER_NO_PERMISSION); - } - } - } - } - - private void createOrGetLinkedServices(RangerService resourceService) { - if (LOG.isDebugEnabled()) { - LOG.debug("==> createOrGetLinkedServices(resourceService=" + resourceService.getName() + ")"); - } - - Runnable createAndLinkTagServiceTask = new Runnable() { - @Override - public void run() { - final LinkedServiceCreator creator = new LinkedServiceCreator(resourceService.getName(), EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_TAG_NAME); - - creator.doCreateAndLinkService(); - } - }; - - rangerTransactionSynchronizationAdapter.executeOnTransactionCommit(createAndLinkTagServiceTask); - - if (LOG.isDebugEnabled()) { - LOG.debug("<== createOrGetLinkedServices(resourceService=" + resourceService.getName() + ")"); - } - } - - private final class LinkedServiceCreator { - static final char SEP = '_'; - - final String resourceServiceName; - final String linkedServiceType; - final String linkedServiceName; - final boolean isAutoCreate; - final boolean isAutoLink; - - LinkedServiceCreator(@Nonnull String resourceServiceName, @Nonnull String linkedServiceType) { - this.resourceServiceName = resourceServiceName; - this.linkedServiceType = linkedServiceType; - this.linkedServiceName = computeLinkedServiceName(); - this.isAutoCreate = config.getBoolean("ranger." + linkedServiceType + "service.auto.create", true); - this.isAutoLink = config.getBoolean("ranger." + linkedServiceType + "service.auto.link", true); - } - - void doCreateAndLinkService() { - if (LOG.isDebugEnabled()) { - LOG.debug("==> doCreateAndLinkService()"); - } - - RangerService resourceService = null; - - try { - resourceService = svcStore.getServiceByName(resourceServiceName); - LOG.info("Successfully retrieved resource-service:[" + resourceService.getName() + "]"); - } catch (Exception e) { - LOG.error("Resource-service:[" + resourceServiceName + "] cannot be retrieved"); - } - - if (resourceService != null) { - try { - RangerService linkedService = svcStore.getServiceByName(linkedServiceName); - - if (linkedService == null && isAutoCreate) { - linkedService = new RangerService(); - - linkedService.setName(linkedServiceName); - linkedService.setDisplayName(linkedServiceName); //set DEFAULT display name - linkedService.setType(linkedServiceType); - - LOG.info("creating service [" + linkedServiceName + "]"); - - svcStore.createService(linkedService); - } - } catch (Exception e) { - throw new RuntimeException(e); - } - - if (isAutoLink) { - doLinkService(); - } - - } else { - LOG.info("Resource service :[" + resourceServiceName + "] not found! Returning without linking " + linkedServiceType + " service!!"); - } - - if (LOG.isDebugEnabled()) { - LOG.debug("<== doCreateAndLinkService()"); - } - } - - private String computeLinkedServiceName() { - String ret = config.get("ranger." + linkedServiceType + "service.auto.name"); - - if (StringUtils.isBlank(ret)) { - final int lastIndexOfSep = StringUtils.lastIndexOf(resourceServiceName, SEP); - - ret = (lastIndexOfSep != -1) ? resourceServiceName.substring(0, lastIndexOfSep) + SEP + linkedServiceType : linkedServiceType; - } - - return ret; - } - - private void doLinkService() { - if (LOG.isDebugEnabled()) { - LOG.debug("==> doLinkTagService()"); - } - - try { - RangerService resourceService = svcStore.getServiceByName(resourceServiceName); - LOG.info("Successfully retrieved resource-service:[" + resourceService.getName() + "]"); - - RangerService linkedService = svcStore.getServiceByName(linkedServiceName); - - if (linkedService == null) { - LOG.error("Failed to link service[" + resourceServiceName + "] with service [" + linkedServiceName + "]: " + linkedServiceName + " not found"); - } else if (EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_TAG_NAME.equals(linkedServiceType)) { - LOG.info("Successfully retrieved service:[" + linkedService.getName() + "]"); - - if (!StringUtils.equals(linkedService.getName(), resourceService.getTagService())) { - resourceService.setTagService(linkedService.getName()); - - LOG.info("Linking resource-service[" + resourceService.getName() + "] with tag-service [" + linkedService.getName() + "]"); - - RangerService service = svcStore.updateService(resourceService, null); - - LOG.info("Updated resource-service:[" + service.getName() + "]"); - } - } - } catch (Exception e) { - LOG.error("Failed to link service[" + resourceServiceName + "] with service [" + linkedServiceName + "]"); - } - if (LOG.isDebugEnabled()) { - LOG.debug("<== doLinkTagService()"); - } - } - - @Override - public String toString() { - return "{resourceServiceName=" + resourceServiceName + ", linkedServiceType=" + linkedServiceType + ", isAutoCreate=" + isAutoCreate + ", isAutoLink=" + isAutoLink + "}"; - } - } - - private void deleteExactMatchPolicyForResource(List policies, String user, String zoneName) throws Exception { - if (CollectionUtils.isNotEmpty(policies)) { - long totalDeletedPolicies = 0; - for (RangerPolicy rangerPolicy : policies) { - RangerPolicy existingPolicy = null ; - try { - if(zoneName!=null) { - rangerPolicy.setZoneName(zoneName); - } - existingPolicy = getExactMatchPolicyForResource(rangerPolicy, StringUtils.isNotBlank(user) ? user :"admin"); - } catch (Exception e) { - existingPolicy=null; - } - if (existingPolicy != null) { - svcStore.deletePolicy(existingPolicy, null); - totalDeletedPolicies = totalDeletedPolicies + 1; - if (totalDeletedPolicies % RangerBizUtil.POLICY_BATCH_SIZE == 0) { - bizUtil.bulkModeOnlyFlushAndClear(); - } - if (LOG.isDebugEnabled()) { - LOG.debug("Policy " + rangerPolicy.getName() + " deleted successfully."); - } - } - } - bizUtil.bulkModeOnlyFlushAndClear(); - } - } - - private String getRangerAdminZoneName(String serviceName, GrantRevokeRequest grantRevokeRequest) { - String ret = grantRevokeRequest.getZoneName(); - - if (StringUtils.isEmpty(ret)) { - RangerPolicyAdmin policyAdmin = getPolicyAdmin(serviceName); - if (policyAdmin != null) { - ret = policyAdmin.getUniquelyMatchedZoneName(grantRevokeRequest); - } - } - - return ret; - } - - /** - * Returns {@link RangerPolicy} for non-empty serviceName, policyName and zoneName null otherwise. - * @param serviceName - * @param policyName - * @param zoneName - * @return - */ - - public RangerPolicy getPolicyByName(String serviceName, String policyName, String zoneName) { - if (LOG.isDebugEnabled()) { - LOG.debug("==> ServiceREST.getPolicyByName(" + serviceName + "," + policyName + "," + zoneName + ")"); + + @GET + @Path("/definitions") + @Produces("application/json") + @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.GET_SERVICE_DEFS + "\")") + public RangerServiceDefList getServiceDefs(@Context HttpServletRequest request) { + LOG.debug("==> ServiceREST.getServiceDefs()"); + + if (!bizUtil.hasModuleAccess(RangerConstants.MODULE_RESOURCE_BASED_POLICIES)) { + throw restErrorUtil.createRESTException(HttpServletResponse.SC_FORBIDDEN, "User is not having permissions on the " + RangerConstants.MODULE_RESOURCE_BASED_POLICIES + " module.", true); } - RangerPolicy ret = null; - if (StringUtils.isNotBlank(serviceName) && StringUtils.isNotBlank(policyName)) { - XXPolicy dbPolicy = daoManager.getXXPolicy().findPolicy(policyName, serviceName, zoneName); + RangerServiceDefList ret = null; + RangerPerfTracer perf = null; + SearchFilter filter = searchUtil.getSearchFilter(request, serviceDefService.sortFields); + String pageSource = request.getParameter("pageSource"); - if (dbPolicy != null) { - ret = policyService.getPopulatedViewObject(dbPolicy); + if (pageSource != null) { + filter.setParam("pageSource", pageSource); + } + + try { + if (RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { + perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "ServiceREST.getServiceDefs()"); } - if (ret != null) { - ensureAdminAndAuditAccess(ret); + PList paginatedSvcDefs = svcStore.getPaginatedServiceDefs(filter); + + if (paginatedSvcDefs != null) { + ret = new RangerServiceDefList(); + + ret.setServiceDefs(paginatedSvcDefs.getList()); + ret.setPageSize(paginatedSvcDefs.getPageSize()); + ret.setResultSize(paginatedSvcDefs.getResultSize()); + ret.setStartIndex(paginatedSvcDefs.getStartIndex()); + ret.setTotalCount(paginatedSvcDefs.getTotalCount()); + ret.setSortBy(paginatedSvcDefs.getSortBy()); + ret.setSortType(paginatedSvcDefs.getSortType()); } - } + } catch (WebApplicationException excp) { + throw excp; + } catch (Throwable excp) { + LOG.error("getServiceDefs() failed", excp); - if (LOG.isDebugEnabled()) { - LOG.debug("<== ServiceREST.getPolicyByName(" + serviceName + "," + policyName + "," + zoneName + ") " + (ret != null ? ret : "ret is null")); + throw restErrorUtil.createRESTException(excp.getMessage()); + } finally { + RangerPerfTracer.log(perf); } + + LOG.debug("<== ServiceREST.getServiceDefs(): count={}", (ret == null ? 0 : ret.getListSize())); + return ret; } - private RangerPolicy createPolicyUnconditionally(RangerPolicy policy) throws Exception { - if(LOG.isDebugEnabled()) { - LOG.debug("==> ServiceREST.createPolicyUnconditionally( "+ policy +")"); - } - RangerPolicy ret = null; - if (StringUtils.isBlank(policy.getName())) { - String guid = policy.getGuid(); - if (StringUtils.isBlank(guid)) { - guid = guidUtil.genGUID(); - policy.setGuid(guid); - if (LOG.isDebugEnabled()) { - LOG.debug("No GUID supplied on the policy! Ok, setting GUID to [" + guid + "]."); - } - } - String name = policy.getService() + "-" + guid; - policy.setName(name); - if (LOG.isDebugEnabled()) { - LOG.debug("Policy did not have its name set! Ok, setting name to [" + name + "]"); - } - } else if (isPolicyNameLengthValidationEnabled) { - if (policy.getName().length() > maxPolicyNameLength) { - throw restErrorUtil.createRESTException( - "Policy name should not be longer than " + maxPolicyNameLength + " characters", - MessageEnums.INPUT_DATA_OUT_OF_BOUND, null, "policy name", "" + policy.getName()); - } - } - RangerPolicyValidator validator = validatorFactory.getPolicyValidator(svcStore); - validator.validate(policy, Action.CREATE, bizUtil.isAdmin() || isServiceAdmin(policy.getService()) || isZoneAdmin(policy.getZoneName())); - - ensureAdminAccess(policy); - bizUtil.blockAuditorRoleUser(); - - ret = svcStore.createPolicy(policy); - if(LOG.isDebugEnabled()) { - LOG.debug("<== ServiceREST.createPolicyUnconditionally( " + ret + ")"); - } - - return ret; - } - - private RangerPolicy getPolicyMatchByName(RangerPolicy policy, HttpServletRequest request) { - if(LOG.isDebugEnabled()) { - LOG.debug("==> ServiceREST.getPolicyMatchByName( " + policy + ")"); - } - RangerPolicy existingPolicy = null; - String serviceName = request.getParameter(PARAM_SERVICE_NAME); - if (serviceName == null) { - serviceName = (String) request.getAttribute(PARAM_SERVICE_NAME); - } - if (StringUtils.isNotEmpty(serviceName)) { - policy.setService(serviceName); - } - String policyName = request.getParameter(PARAM_POLICY_NAME); - if (policyName == null) { - policyName = (String) request.getAttribute(PARAM_POLICY_NAME); - } - if (StringUtils.isNotEmpty(policyName)) { - policy.setName(StringUtils.trim(policyName)); - } - if (StringUtils.isNotEmpty(serviceName) && StringUtils.isNotEmpty(policyName)) { - String zoneName = request.getParameter(PARAM_ZONE_NAME); - if (StringUtils.isBlank(zoneName)) { - zoneName = (String) request.getAttribute(PARAM_ZONE_NAME); - } - if (StringUtils.isNotBlank(zoneName)) { - policy.setZoneName(StringUtils.trim(zoneName)); - } - existingPolicy = getPolicyByName(policy.getService(), policy.getName(), policy.getZoneName()); - } - - if(LOG.isDebugEnabled()) { - LOG.debug("<== ServiceREST.getPolicyMatchByName( " + existingPolicy + ")"); - } - return existingPolicy; - } - - private String deleteServiceById(Long id) { - if(LOG.isDebugEnabled()) { - LOG.debug("==> ServiceREST.deleteServiceById( " + id + ")"); - } - - RangerContextHolder.getOrCreateOpContext().setBulkModeContext(true); - - RangerPerfTracer perf = null; - String deletedServiceName = null; - - try { - if(RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { - perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "ServiceREST.deleteService(serviceId=" + id + ")"); - } - RangerServiceValidator validator = validatorFactory.getServiceValidator(svcStore); - validator.validate(id, Action.DELETE); - UserSessionBase session = ContextUtil.getCurrentUserSession(); - if (session != null) { - XXService service = daoManager.getXXService().getById(id); - if (service != null) { - //if logged-in user is not the service creator then check admin priv. - if (!session.getUserId().equals(service.getAddedByUserId())) { - bizUtil.hasAdminPermissions("Services"); - } - EmbeddedServiceDefsUtil embeddedServiceDefsUtil = EmbeddedServiceDefsUtil.instance(); - if (service.getType().equals(embeddedServiceDefsUtil.getTagServiceDefId())) { - List referringServices = daoManager.getXXService().findByTagServiceId(id); - if (!CollectionUtils.isEmpty(referringServices)) { - Set referringServiceNames = new HashSet(); - for (XXService xXService : referringServices) { - referringServiceNames.add(xXService.getName()); - if (referringServiceNames.size() >= 10) { - break; - } - } - if (referringServices.size() <= 10) { - throw restErrorUtil.createRESTException("Tag service '" + service.getName() + "' is being referenced by " + referringServices.size() + " services: " + referringServiceNames, MessageEnums.OPER_NOT_ALLOWED_FOR_STATE); - } else { - throw restErrorUtil.createRESTException("Tag service '" + service.getName() + "' is being referenced by " + referringServices.size() + " services: " + referringServiceNames + " and more..", MessageEnums.OPER_NOT_ALLOWED_FOR_STATE); - } - } - } - XXServiceDef xxServiceDef = daoManager.getXXServiceDef().getById(service.getType()); - if (!session.getUserId().equals(service.getAddedByUserId())) { - bizUtil.hasKMSPermissions("Service", xxServiceDef.getImplclassname()); - bizUtil.blockAuditorRoleUser(); - } - - tagStore.deleteAllTagObjectsForService(service.getName()); - - deletedServiceName = service.getName(); - - svcStore.deleteService(id); - } else { - LOG.error("Cannot retrieve service:[" + id + "] for deletion"); - throw restErrorUtil.createRESTException( - "Data Not Found for given Id", - MessageEnums.DATA_NOT_FOUND, id, null, - "readResource : No Object found with given id."); - } - } else { - LOG.error("Cannot retrieve user session."); - throw new Exception("deleteService(" + id + ") failed"); - } - } catch(WebApplicationException excp) { - throw excp; - } catch(Throwable excp) { - LOG.error("deleteService(" + id + ") failed", excp); - - throw restErrorUtil.createRESTException(excp.getMessage()); - } finally { - RangerPerfTracer.log(perf); - } - - if(LOG.isDebugEnabled()) { - LOG.debug("<== ServiceREST.deleteServiceById() - deletedServiceName="+deletedServiceName); - } - return deletedServiceName; - } - - boolean isServiceAdmin(String serviceName) { - boolean ret = bizUtil.isAdmin(); - - if (!ret && StringUtils.isNotEmpty(serviceName)) { - ret = svcStore.isServiceAdminUser(serviceName, bizUtil.getCurrentUserLoginId()); - } - - return ret; - } - - private boolean isZoneAdmin(String zoneName) { - boolean ret = bizUtil.isAdmin(); - - if (!ret && StringUtils.isNotEmpty(zoneName)) { - ret = serviceMgr.isZoneAdmin(zoneName); - } - - return ret; - } -} + @GET + @Path("/policies/{serviceDefName}/for-resource") + @Produces("application/json") + public List getPoliciesForResource(@PathParam("serviceDefName") String serviceDefName, @DefaultValue("") @QueryParam("serviceName") String serviceName, @Context HttpServletRequest request) { + LOG.debug("==> ServiceREST.getPoliciesForResource(service-type={}, service-name={})", serviceDefName, serviceName); + + List ret = new ArrayList<>(); + List services = new ArrayList<>(); + Map resource = new HashMap<>(); + String validationMessage = validateResourcePoliciesRequest(serviceDefName, serviceName, request, services, resource); + + if (StringUtils.isNotEmpty(validationMessage)) { + LOG.error("Invalid request: [{}]", validationMessage); + throw restErrorUtil.createRESTException(validationMessage, MessageEnums.INVALID_INPUT_DATA); + } else { + RangerService service = services.get(0); + LOG.debug("getServicePolicies with service-name={}", service.getName()); + + RangerPolicyAdmin policyAdmin; + + try { + policyAdmin = getPolicyAdminForSearch(service.getName()); + } catch (Exception e) { + LOG.error("Cannot initialize Policy-Engine", e); + + throw restErrorUtil.createRESTException("Cannot initialize Policy Engine", MessageEnums.ERROR_SYSTEM); + } + + if (policyAdmin != null) { + ret = policyAdmin.getMatchingPolicies(new RangerAccessResourceImpl(resource)); + ret = applyAdminAccessFilter(ret); + } + } + + LOG.debug("<== ServiceREST.getPoliciesForResource(service-type={}, service-name={}) : {}", serviceDefName, serviceName, ret); + + return ret; + } + + @POST + @Path("/services") + @Consumes("application/json") + @Produces("application/json") + @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.CREATE_SERVICE + "\")") + public RangerService createService(RangerService service) { + LOG.debug("==> ServiceREST.createService({})", service); + + RangerService ret; + RangerPerfTracer perf = null; + + /** + * If display name is blank (EMPTY String or NULL), use name. + */ + if (StringUtils.isBlank(service.getDisplayName())) { + service.setDisplayName(service.getName()); + } + + try { + if (RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { + perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "ServiceREST.createService(serviceName=" + service.getName() + ")"); + } + + RangerServiceValidator validator = validatorFactory.getServiceValidator(svcStore); + + validator.validate(service, Action.CREATE); + + if (!StringUtils.isEmpty(service.getName().trim())) { + service.setName(service.getName().trim()); + } + + if (!StringUtils.isEmpty(service.getDisplayName().trim())) { + service.setDisplayName(service.getDisplayName().trim()); + } + + UserSessionBase session = ContextUtil.getCurrentUserSession(); + XXServiceDef xxServiceDef = daoManager.getXXServiceDef().findByName(service.getType()); + + if (session != null && !session.isSpnegoEnabled()) { + bizUtil.hasAdminPermissions("Services"); + + // TODO: As of now we are allowing SYS_ADMIN to create all the + // services including KMS + bizUtil.hasKMSPermissions("Service", xxServiceDef.getImplclassname()); + } + + if (session != null && session.isSpnegoEnabled()) { + if (session.isKeyAdmin() && !EmbeddedServiceDefsUtil.KMS_IMPL_CLASS_NAME.equals(xxServiceDef.getImplclassname())) { + throw restErrorUtil.createRESTException("KeyAdmin can create/update/delete only KMS ", MessageEnums.OPER_NO_PERMISSION); + } + + if ((!session.isKeyAdmin() && !session.isUserAdmin()) && EmbeddedServiceDefsUtil.KMS_IMPL_CLASS_NAME.equals(xxServiceDef.getImplclassname())) { + throw restErrorUtil.createRESTException("User cannot create/update/delete KMS Service", MessageEnums.OPER_NO_PERMISSION); + } + } + + bizUtil.blockAuditorRoleUser(); + + String serviceType = xxServiceDef != null ? xxServiceDef.getName() : null; + + if (StringUtils.isBlank(service.getTagService()) && !StringUtils.equals(EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_TAG_NAME, serviceType) && !StringUtils.equals(EMBEDDED_SERVICEDEF_GDS_NAME, serviceType) && !StringUtils.equals(EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_KMS_NAME, serviceType)) { + createOrGetLinkedServices(service); + } + + ret = svcStore.createService(service); + } catch (WebApplicationException excp) { + throw excp; + } catch (Throwable excp) { + LOG.error("createService({}) failed", service, excp); + + throw restErrorUtil.createRESTException(excp.getMessage()); + } finally { + RangerPerfTracer.log(perf); + } + + LOG.debug("<== ServiceREST.createService({}): {}", service, ret); + + return ret; + } + + @PUT + @Path("/services/{id}") + @Consumes("application/json") + @Produces("application/json") + @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.UPDATE_SERVICE + "\")") + public RangerService updateService(RangerService service, @Context HttpServletRequest request) { + LOG.debug("==> ServiceREST.updateService(): {}", service); + + RangerService ret; + RangerPerfTracer perf = null; + + try { + if (RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { + perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "ServiceREST.updateService(serviceName=" + service.getName() + ")"); + } + + /** + * If display name is blank (EMPTY String or NULL), use previous display name. + */ + if (StringUtils.isBlank(service.getDisplayName())) { + RangerService rangerService = svcStore.getService(service.getId()); + + // If previous display name is blank (EMPTY String or NULL), user name. + if (Objects.isNull(rangerService) || StringUtils.isBlank(rangerService.getDisplayName())) { + service.setDisplayName(service.getName()); + } else { + service.setDisplayName(rangerService.getDisplayName()); + } + } + + RangerServiceValidator validator = validatorFactory.getServiceValidator(svcStore); + + validator.validate(service, Action.UPDATE); + + if (!StringUtils.isEmpty(service.getName().trim())) { + service.setName(service.getName().trim()); + } + + if (!StringUtils.isEmpty(service.getDisplayName().trim())) { + service.setDisplayName(service.getDisplayName().trim()); + } + + bizUtil.hasAdminPermissions("Services"); + + // TODO: As of now we are allowing SYS_ADMIN to create all the + // services including KMS + + XXServiceDef xxServiceDef = daoManager.getXXServiceDef().findByName(service.getType()); + + bizUtil.hasKMSPermissions("Service", xxServiceDef.getImplclassname()); + bizUtil.blockAuditorRoleUser(); + + Map options = getOptions(request); + + ret = svcStore.updateService(service, options); + } catch (WebApplicationException excp) { + throw excp; + } catch (Throwable excp) { + LOG.error("updateService({}) failed", service, excp); + + throw restErrorUtil.createRESTException(excp.getMessage()); + } finally { + RangerPerfTracer.log(perf); + } + + LOG.debug("<== ServiceREST.updateService({}): {}", service, ret); + + return ret; + } + + @DELETE + @Path("/services/{id}") + @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.DELETE_SERVICE + "\")") + public void deleteService(@PathParam("id") Long id) { + LOG.debug("==> ServiceREST.deleteService({})", id); + + String deletedServiceName = deleteServiceById(id); + + LOG.debug("<== ServiceREST.deleteService() - [id={}],[deletedServiceName={}]", deletedServiceName, deletedServiceName); + } + + @GET + @Path("/services/{id}") + @Produces("application/json") + @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.GET_SERVICE + "\")") + public RangerService getService(@PathParam("id") Long id) { + LOG.debug("==> ServiceREST.getService({})", id); + + RangerService ret; + RangerPerfTracer perf = null; + + try { + if (RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { + perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "ServiceREST.getService(serviceId=" + id + ")"); + } + + ret = svcStore.getService(id); + + if (ret != null) { + UserSessionBase userSession = ContextUtil.getCurrentUserSession(); + + if (userSession != null && userSession.getLoginId() != null) { + VXUser loggedInVXUser = xUserService.getXUserByUserName(userSession.getLoginId()); + + if (loggedInVXUser != null) { + if (loggedInVXUser.getUserRoleList().size() == 1 && loggedInVXUser.getUserRoleList().contains(RangerConstants.ROLE_USER)) { + hideCriticalServiceDetailsForRoleUser(ret); + } + } + } + } + } catch (WebApplicationException excp) { + throw excp; + } catch (Throwable excp) { + LOG.error("getService({}) failed", id, excp); + + throw restErrorUtil.createRESTException(excp.getMessage()); + } finally { + RangerPerfTracer.log(perf); + } + + if (ret == null) { + throw restErrorUtil.createRESTException(HttpServletResponse.SC_NOT_FOUND, "Not found", true); + } + + LOG.debug("<== ServiceREST.getService({}): {}", id, ret); + + return ret; + } + + @GET + @Path("/services/name/{name}") + @Produces("application/json") + @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.GET_SERVICE_BY_NAME + "\")") + public RangerService getServiceByName(@PathParam("name") String name) { + LOG.debug("==> ServiceREST.getServiceByName({})", name); + + RangerService ret; + RangerPerfTracer perf = null; + + try { + if (RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { + perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "ServiceREST.getService(serviceName=" + name + ")"); + } + + ret = svcStore.getServiceByName(name); + + if (ret != null) { + UserSessionBase userSession = ContextUtil.getCurrentUserSession(); + + if (userSession != null && userSession.getLoginId() != null) { + VXUser loggedInVXUser = xUserService.getXUserByUserName(userSession.getLoginId()); + + if (loggedInVXUser != null) { + if (loggedInVXUser.getUserRoleList().size() == 1 && loggedInVXUser.getUserRoleList().contains(RangerConstants.ROLE_USER)) { + hideCriticalServiceDetailsForRoleUser(ret); + } + } + } + } + } catch (WebApplicationException excp) { + throw excp; + } catch (Throwable excp) { + LOG.error("getServiceByName({}) failed", name, excp); + + throw restErrorUtil.createRESTException(excp.getMessage()); + } finally { + RangerPerfTracer.log(perf); + } + + if (ret == null) { + throw restErrorUtil.createRESTException(HttpServletResponse.SC_NOT_FOUND, "Not found", true); + } + + LOG.debug("<== ServiceREST.getServiceByName({}): {}", name, ret); + + return ret; + } + + @GET + @Path("/services") + @Produces("application/json") + @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.GET_SERVICES + "\")") + public RangerServiceList getServices(@Context HttpServletRequest request) { + LOG.debug("==> ServiceREST.getServices()"); + + RangerServiceList ret = null; + RangerPerfTracer perf = null; + SearchFilter filter = searchUtil.getSearchFilter(request, svcService.sortFields); + + try { + if (RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { + perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "ServiceREST.getServices()"); + } + + PList paginatedSvcs = svcStore.getPaginatedServices(filter); + + if (paginatedSvcs != null && !paginatedSvcs.getList().isEmpty()) { + UserSessionBase userSession = ContextUtil.getCurrentUserSession(); + + if (userSession != null && userSession.getLoginId() != null) { + VXUser loggedInVXUser = xUserService.getXUserByUserName(userSession.getLoginId()); + + if (loggedInVXUser != null) { + if (loggedInVXUser.getUserRoleList().size() == 1 && loggedInVXUser.getUserRoleList().contains(RangerConstants.ROLE_USER)) { + List updateServiceList = new ArrayList<>(); + + for (RangerService rangerService : paginatedSvcs.getList()) { + if (rangerService != null) { + updateServiceList.add(hideCriticalServiceDetailsForRoleUser(rangerService)); + } + } + + if (!updateServiceList.isEmpty()) { + paginatedSvcs.setList(updateServiceList); + } + } + } + } + } + + if (paginatedSvcs != null) { + ret = new RangerServiceList(); + + ret.setServices(paginatedSvcs.getList()); + ret.setPageSize(paginatedSvcs.getPageSize()); + ret.setResultSize(paginatedSvcs.getResultSize()); + ret.setStartIndex(paginatedSvcs.getStartIndex()); + ret.setTotalCount(paginatedSvcs.getTotalCount()); + ret.setSortBy(paginatedSvcs.getSortBy()); + ret.setSortType(paginatedSvcs.getSortType()); + } + } catch (WebApplicationException excp) { + throw excp; + } catch (Throwable excp) { + LOG.error("getServices() failed", excp); + + throw restErrorUtil.createRESTException(excp.getMessage()); + } finally { + RangerPerfTracer.log(perf); + } + + LOG.debug("<== ServiceREST.getServices(): count={}", (ret == null ? 0 : ret.getListSize())); + + return ret; + } + + public List getServices(SearchFilter filter) { + LOG.debug("==> ServiceREST.getServices():"); + + List ret; + RangerPerfTracer perf = null; + + try { + if (RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { + perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "ServiceREST.getServices()"); + } + + ret = svcStore.getServices(filter); + } catch (WebApplicationException excp) { + throw excp; + } catch (Throwable excp) { + LOG.error("getServices() failed", excp); + + throw restErrorUtil.createRESTException(excp.getMessage()); + } finally { + RangerPerfTracer.log(perf); + } + + LOG.debug("<== ServiceREST.getServices(): count={}", (ret == null ? 0 : ret.size())); + + return ret; + } + + public List getServiceHeaders(@Context HttpServletRequest request) { + LOG.debug("==> ServiceREST.getServiceHeaders()"); + + String namePrefix = request.getParameter(SearchFilter.SERVICE_NAME_PREFIX); + String svcType = request.getParameter(SearchFilter.SERVICE_TYPE); + boolean filterByNamePrefix = StringUtils.isNotBlank(namePrefix); + boolean filterByType = StringUtils.isNotBlank(svcType); + + List ret = daoManager.getXXService().findServiceHeaders(); + + for (ListIterator iter = ret.listIterator(); iter.hasNext(); ) { + RangerServiceHeaderInfo serviceHeader = iter.next(); + + if (EMBEDDED_SERVICEDEF_GDS_NAME.equals(serviceHeader.getType())) { + iter.remove(); + } else if (filterByNamePrefix && !StringUtils.startsWithIgnoreCase(serviceHeader.getName(), namePrefix)) { + iter.remove(); + } else if (filterByType && !StringUtils.equals(serviceHeader.getType(), svcType)) { + iter.remove(); + } else if (!bizUtil.hasAccess(null, serviceHeader)) { + iter.remove(); + } + } + + LOG.debug("<== ServiceREST.getServiceHeaders(namePrefix={}, svcType={}): ret={}", namePrefix, svcType, ret); + + return ret; + } + + @GET + @Path("/services/count") + @Produces("application/json") + @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.COUNT_SERVICES + "\")") + public Long countServices(@Context HttpServletRequest request) { + LOG.debug("==> ServiceREST.countServices():"); + + Long ret; + RangerPerfTracer perf = null; + + try { + if (RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { + perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "ServiceREST.countService()"); + } + + List services = getServices(request).getServices(); + + ret = services == null ? 0L : services.size(); + } catch (WebApplicationException excp) { + throw excp; + } catch (Throwable excp) { + LOG.error("countServices() failed", excp); + + throw restErrorUtil.createRESTException(excp.getMessage()); + } finally { + RangerPerfTracer.log(perf); + } + + LOG.debug("<== ServiceREST.countServices(): {}", ret); + + return ret; + } + + @POST + @Path("/services/validateConfig") + @Produces("application/json") + @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.VALIDATE_CONFIG + "\")") + public VXResponse validateConfig(RangerService service) { + LOG.debug("==> ServiceREST.validateConfig({})", service); + + VXResponse ret; + RangerPerfTracer perf = null; + + try { + if (RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { + perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "ServiceREST.validateConfig(serviceName=" + service.getName() + ")"); + } + + ret = serviceMgr.validateConfig(service, svcStore); + } catch (WebApplicationException excp) { + throw excp; + } catch (Throwable excp) { + LOG.error("validateConfig({}) failed", service, excp); + + throw restErrorUtil.createRESTException(excp.getMessage()); + } finally { + RangerPerfTracer.log(perf); + } + + LOG.debug("<== ServiceREST.validateConfig({}) :{}", service, ret); + + return ret; + } + + @POST + @Path("/services/lookupResource/{serviceName}") + @Consumes("application/json") + @Produces("application/json") + @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.LOOKUP_RESOURCE + "\")") + public List lookupResource(@PathParam("serviceName") String serviceName, ResourceLookupContext context) { + LOG.debug("==> ServiceREST.lookupResource({})", serviceName); + + List ret; + RangerPerfTracer perf = null; + + try { + if (RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { + perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "ServiceREST.lookupResource(serviceName=" + serviceName + ")"); + } + + ret = serviceMgr.lookupResource(serviceName, context, svcStore); + } catch (WebApplicationException excp) { + throw excp; + } catch (Throwable excp) { + LOG.error("lookupResource({}, {}) failed", serviceName, context, excp); + + throw restErrorUtil.createRESTException(excp.getMessage()); + } finally { + RangerPerfTracer.log(perf); + } + + LOG.debug("<== ServiceREST.lookupResource({}) :{}", serviceName, ret); + + return ret; + } + + @POST + @Path("/services/grant/{serviceName}") + @Consumes("application/json") + @Produces("application/json") + public RESTResponse grantAccess(@PathParam("serviceName") String serviceName, GrantRevokeRequest grantRequest, @Context HttpServletRequest request) throws Exception { + LOG.debug("==> ServiceREST.grantAccess({}, {})", serviceName, grantRequest); + + RESTResponse ret = new RESTResponse(); + RangerPerfTracer perf = null; + + if (grantRequest != null) { + if (serviceUtil.isValidateHttpsAuthentication(serviceName, request)) { + try { + bizUtil.failUnauthenticatedIfNotAllowed(); + + if (RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { + perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "ServiceREST.grantAccess(serviceName=" + serviceName + ")"); + } + + // This is an open API - dont care about who calls it. Caller is treated as privileged user + boolean hasAdminPrivilege = true; + String loggedInUser = null; + + validateGrantRevokeRequest(grantRequest, hasAdminPrivilege, loggedInUser); + + String userName = grantRequest.getGrantor(); + Set userGroups = CollectionUtils.isNotEmpty(grantRequest.getGrantorGroups()) ? grantRequest.getGrantorGroups() : userMgr.getGroupsForUser(userName); + String ownerUser = grantRequest.getOwnerUser(); + RangerAccessResource resource = new RangerAccessResourceImpl(getAccessResourceObjectMap(grantRequest.getResource()), ownerUser); + Set accessTypes = grantRequest.getAccessTypes(); + VXUser vxUser = xUserService.getXUserByUserName(userName); + + if (vxUser.getUserRoleList().contains(RangerConstants.ROLE_ADMIN_AUDITOR) || vxUser.getUserRoleList().contains(RangerConstants.ROLE_KEY_ADMIN_AUDITOR)) { + VXResponse vXResponse = new VXResponse(); + + vXResponse.setStatusCode(HttpServletResponse.SC_FORBIDDEN); + vXResponse.setMsgDesc("Operation denied. LoggedInUser=" + vxUser.getId() + " is not permitted to perform the action."); + + throw restErrorUtil.generateRESTException(vXResponse); + } + + RangerService rangerService = svcStore.getServiceByName(serviceName); + String zoneName = getRangerAdminZoneName(serviceName, grantRequest); + boolean isAdmin = bizUtil.isUserRangerAdmin(userName) || bizUtil.isUserServiceAdmin(rangerService, userName) || hasAdminAccess(serviceName, zoneName, userName, userGroups, resource, accessTypes); + + if (!isAdmin) { + throw restErrorUtil.createGrantRevokeRESTException("User doesn't have necessary permission to grant access"); + } + + RangerPolicy policy = getExactMatchPolicyForResource(serviceName, resource, zoneName, userName); + + if (policy != null) { + boolean policyUpdated = ServiceRESTUtil.processGrantRequest(policy, grantRequest); + + if (policyUpdated) { + policy.setZoneName(zoneName); + + ensureAdminAccess(policy); + + svcStore.updatePolicy(policy); + } else { + LOG.error("processGrantRequest processing failed"); + + throw new Exception("processGrantRequest processing failed"); + } + } else { + policy = new RangerPolicy(); + + policy.setService(serviceName); + policy.setName("grant-" + System.currentTimeMillis()); // TODO: better policy name + policy.setDescription("created by grant"); + policy.setIsAuditEnabled(grantRequest.getEnableAudit()); + policy.setCreatedBy(userName); + + Map policyResources = new HashMap<>(); + Set resourceNames = resource.getKeys(); + + if (!CollectionUtils.isEmpty(resourceNames)) { + for (String resourceName : resourceNames) { + policyResources.put(resourceName, getPolicyResource(resource.getValue(resourceName), grantRequest)); + } + } + + policy.setResources(policyResources); + + RangerPolicyItem policyItem = new RangerPolicyItem(); + + policyItem.setDelegateAdmin(grantRequest.getDelegateAdmin()); + policyItem.addUsers(grantRequest.getUsers()); + policyItem.addGroups(grantRequest.getGroups()); + policyItem.addRoles(grantRequest.getRoles()); + + for (String accessType : grantRequest.getAccessTypes()) { + policyItem.addAccess(new RangerPolicyItemAccess(accessType, Boolean.TRUE)); + } + + policy.addPolicyItem(policyItem); + policy.setZoneName(zoneName); + + ensureAdminAccess(policy); + + svcStore.createPolicy(policy); + } + } catch (WebApplicationException excp) { + throw excp; + } catch (Throwable excp) { + LOG.error("grantAccess({}, {}) failed", serviceName, grantRequest, excp); + + throw restErrorUtil.createRESTException(excp.getMessage()); + } finally { + RangerPerfTracer.log(perf); + } + + ret.setStatusCode(RESTResponse.STATUS_SUCCESS); + } + } + + LOG.debug("<== ServiceREST.grantAccess({}, {}) :{}", serviceName, grantRequest, ret); + + return ret; + } + + @POST + @Path("/secure/services/grant/{serviceName}") + @Consumes("application/json") + @Produces("application/json") + public RESTResponse secureGrantAccess(@PathParam("serviceName") String serviceName, GrantRevokeRequest grantRequest, @Context HttpServletRequest request) throws Exception { + LOG.debug("==> ServiceREST.secureGrantAccess({}, {})", serviceName, grantRequest); + + RESTResponse ret = new RESTResponse(); + RangerPerfTracer perf = null; + + bizUtil.blockAuditorRoleUser(); + + if (grantRequest != null) { + if (serviceUtil.isValidService(serviceName, request)) { + try { + if (RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { + perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "ServiceREST.scureGrantAccess(serviceName=" + serviceName + ")"); + } + + XXService xService = daoManager.getXXService().findByName(serviceName); + XXServiceDef xServiceDef = daoManager.getXXServiceDef().getById(xService.getType()); + RangerService rangerService = svcStore.getServiceByName(serviceName); + String loggedInUser = bizUtil.getCurrentUserLoginId(); + boolean hasAdminPrivilege = bizUtil.isAdmin() || bizUtil.isUserServiceAdmin(rangerService, loggedInUser) || bizUtil.isUserAllowedForGrantRevoke(rangerService, loggedInUser); + + validateGrantRevokeRequest(grantRequest, hasAdminPrivilege, loggedInUser); + + String userName = grantRequest.getGrantor(); + Set userGroups = grantRequest.getGrantorGroups(); + String ownerUser = grantRequest.getOwnerUser(); + RangerAccessResource resource = new RangerAccessResourceImpl(getAccessResourceObjectMap(grantRequest.getResource()), ownerUser); + Set accessTypes = grantRequest.getAccessTypes(); + String zoneName = getRangerAdminZoneName(serviceName, grantRequest); + boolean isAllowed = false; + + if (StringUtils.equals(xServiceDef.getImplclassname(), EmbeddedServiceDefsUtil.KMS_IMPL_CLASS_NAME)) { + if (bizUtil.isKeyAdmin() || bizUtil.isUserAllowedForGrantRevoke(rangerService, loggedInUser)) { + isAllowed = true; + } + } else { + isAllowed = bizUtil.isUserRangerAdmin(userName) || bizUtil.isUserServiceAdmin(rangerService, userName) || hasAdminAccess(serviceName, zoneName, userName, userGroups, resource, accessTypes); + } + + if (isAllowed) { + RangerPolicy policy = getExactMatchPolicyForResource(serviceName, resource, zoneName, userName); + + if (policy != null) { + boolean policyUpdated = ServiceRESTUtil.processGrantRequest(policy, grantRequest); + + if (policyUpdated) { + policy.setZoneName(zoneName); + + ensureAdminAccess(policy); + + svcStore.updatePolicy(policy); + } else { + LOG.error("processSecureGrantRequest processing failed"); + + throw new Exception("processSecureGrantRequest processing failed"); + } + } else { + policy = new RangerPolicy(); + + policy.setService(serviceName); + policy.setName("grant-" + System.currentTimeMillis()); // TODO: better policy name + policy.setDescription("created by grant"); + policy.setIsAuditEnabled(grantRequest.getEnableAudit()); + policy.setCreatedBy(userName); + + Map policyResources = new HashMap<>(); + Set resourceNames = resource.getKeys(); + + if (!CollectionUtils.isEmpty(resourceNames)) { + for (String resourceName : resourceNames) { + policyResources.put(resourceName, getPolicyResource(resource.getValue(resourceName), grantRequest)); + } + } + + policy.setResources(policyResources); + + RangerPolicyItem policyItem = new RangerPolicyItem(); + + policyItem.setDelegateAdmin(grantRequest.getDelegateAdmin()); + policyItem.addUsers(grantRequest.getUsers()); + policyItem.addGroups(grantRequest.getGroups()); + policyItem.addRoles(grantRequest.getRoles()); + + for (String accessType : grantRequest.getAccessTypes()) { + policyItem.addAccess(new RangerPolicyItemAccess(accessType, Boolean.TRUE)); + } + + policy.addPolicyItem(policyItem); + policy.setZoneName(zoneName); + + ensureAdminAccess(policy); + + svcStore.createPolicy(policy); + } + } else { + LOG.error("secureGrantAccess({}, {}) failed as User doesn't have permission to grant Policy", serviceName, grantRequest); + + throw restErrorUtil.createGrantRevokeRESTException("User doesn't have necessary permission to grant access"); + } + } catch (WebApplicationException excp) { + throw excp; + } catch (Throwable excp) { + LOG.error("secureGrantAccess({}, {}) failed", serviceName, grantRequest, excp); + + throw restErrorUtil.createRESTException(excp.getMessage()); + } finally { + RangerPerfTracer.log(perf); + } + + ret.setStatusCode(RESTResponse.STATUS_SUCCESS); + } + } + + LOG.debug("<== ServiceREST.secureGrantAccess({}, {}) :{}", serviceName, grantRequest, ret); + + return ret; + } + + @POST + @Path("/services/revoke/{serviceName}") + @Consumes("application/json") + @Produces("application/json") + public RESTResponse revokeAccess(@PathParam("serviceName") String serviceName, GrantRevokeRequest revokeRequest, @Context HttpServletRequest request) throws Exception { + LOG.debug("==> ServiceREST.revokeAccess({}, {})", serviceName, revokeRequest); + + RESTResponse ret = new RESTResponse(); + RangerPerfTracer perf = null; + + if (revokeRequest != null) { + if (serviceUtil.isValidateHttpsAuthentication(serviceName, request)) { + try { + bizUtil.failUnauthenticatedIfNotAllowed(); + + if (RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { + perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "ServiceREST.revokeAccess(serviceName=" + serviceName + ")"); + } + + // This is an open API - dont care about who calls it. Caller is treated as privileged user + boolean hasAdminPrivilege = true; + String loggedInUser = null; + + validateGrantRevokeRequest(revokeRequest, hasAdminPrivilege, loggedInUser); + + String userName = revokeRequest.getGrantor(); + Set userGroups = CollectionUtils.isNotEmpty(revokeRequest.getGrantorGroups()) ? revokeRequest.getGrantorGroups() : userMgr.getGroupsForUser(userName); + String ownerUser = revokeRequest.getOwnerUser(); + RangerAccessResource resource = new RangerAccessResourceImpl(getAccessResourceObjectMap(revokeRequest.getResource()), ownerUser); + Set accessTypes = revokeRequest.getAccessTypes(); + VXUser vxUser = xUserService.getXUserByUserName(userName); + + if (vxUser.getUserRoleList().contains(RangerConstants.ROLE_ADMIN_AUDITOR) || vxUser.getUserRoleList().contains(RangerConstants.ROLE_KEY_ADMIN_AUDITOR)) { + VXResponse vXResponse = new VXResponse(); + + vXResponse.setStatusCode(HttpServletResponse.SC_FORBIDDEN); + vXResponse.setMsgDesc("Operation denied. LoggedInUser=" + vxUser.getId() + " is not permitted to perform the action."); + + throw restErrorUtil.generateRESTException(vXResponse); + } + + RangerService rangerService = svcStore.getServiceByName(serviceName); + String zoneName = getRangerAdminZoneName(serviceName, revokeRequest); + boolean isAdmin = bizUtil.isUserRangerAdmin(userName) || bizUtil.isUserServiceAdmin(rangerService, userName) || hasAdminAccess(serviceName, zoneName, userName, userGroups, resource, accessTypes); + + if (!isAdmin) { + throw restErrorUtil.createGrantRevokeRESTException("User doesn't have necessary permission to revoke access"); + } + + RangerPolicy policy = getExactMatchPolicyForResource(serviceName, resource, zoneName, userName); + + if (policy != null) { + boolean policyUpdated = ServiceRESTUtil.processRevokeRequest(policy, revokeRequest); + + if (policyUpdated) { + policy.setZoneName(zoneName); + + ensureAdminAccess(policy); + + svcStore.updatePolicy(policy); + } else { + LOG.error("processRevokeRequest processing failed"); + throw new Exception("processRevokeRequest processing failed"); + } + } + } catch (WebApplicationException excp) { + throw excp; + } catch (Throwable excp) { + LOG.error("secureGrantAccess({}, {}) failed", serviceName, revokeRequest, excp); + + throw restErrorUtil.createRESTException(excp.getMessage()); + } finally { + RangerPerfTracer.log(perf); + } + + ret.setStatusCode(RESTResponse.STATUS_SUCCESS); + } + } + + LOG.debug("<== ServiceREST.revokeAccess({}, {}) :{}", serviceName, revokeRequest, ret); + + return ret; + } + + @POST + @Path("/secure/services/revoke/{serviceName}") + @Consumes("application/json") + @Produces("application/json") + public RESTResponse secureRevokeAccess(@PathParam("serviceName") String serviceName, GrantRevokeRequest revokeRequest, @Context HttpServletRequest request) throws Exception { + LOG.debug("==> ServiceREST.secureRevokeAccess({}, {})", serviceName, revokeRequest); + + RESTResponse ret = new RESTResponse(); + RangerPerfTracer perf = null; + + bizUtil.blockAuditorRoleUser(); + + if (revokeRequest != null) { + if (serviceUtil.isValidService(serviceName, request)) { + try { + if (RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { + perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "ServiceREST.secureRevokeAccess(serviceName=" + serviceName + ")"); + } + + XXService xService = daoManager.getXXService().findByName(serviceName); + XXServiceDef xServiceDef = daoManager.getXXServiceDef().getById(xService.getType()); + RangerService rangerService = svcStore.getServiceByName(serviceName); + String loggedInUser = bizUtil.getCurrentUserLoginId(); + boolean hasAdminPrivilege = bizUtil.isAdmin() || bizUtil.isUserServiceAdmin(rangerService, loggedInUser) || bizUtil.isUserAllowedForGrantRevoke(rangerService, loggedInUser); + + validateGrantRevokeRequest(revokeRequest, hasAdminPrivilege, loggedInUser); + + String userName = revokeRequest.getGrantor(); + Set userGroups = revokeRequest.getGrantorGroups(); + String ownerUser = revokeRequest.getOwnerUser(); + RangerAccessResource resource = new RangerAccessResourceImpl(getAccessResourceObjectMap(revokeRequest.getResource()), ownerUser); + Set accessTypes = revokeRequest.getAccessTypes(); + String zoneName = getRangerAdminZoneName(serviceName, revokeRequest); + boolean isAllowed = false; + + if (StringUtils.equals(xServiceDef.getImplclassname(), EmbeddedServiceDefsUtil.KMS_IMPL_CLASS_NAME)) { + if (bizUtil.isKeyAdmin() || bizUtil.isUserAllowedForGrantRevoke(rangerService, loggedInUser)) { + isAllowed = true; + } + } else { + isAllowed = bizUtil.isUserRangerAdmin(userName) || bizUtil.isUserServiceAdmin(rangerService, userName) || hasAdminAccess(serviceName, zoneName, userName, userGroups, resource, accessTypes); + } + + if (isAllowed) { + RangerPolicy policy = getExactMatchPolicyForResource(serviceName, resource, zoneName, userName); + + if (policy != null) { + boolean policyUpdated = ServiceRESTUtil.processRevokeRequest(policy, revokeRequest); + + if (policyUpdated) { + policy.setZoneName(zoneName); + + ensureAdminAccess(policy); + + svcStore.updatePolicy(policy); + } else { + LOG.error("processSecureRevokeRequest processing failed"); + + throw new Exception("processSecureRevokeRequest processing failed"); + } + } + } else { + LOG.error("secureRevokeAccess({}, {}) failed as User doesn't have permission to revoke Policy", serviceName, revokeRequest); + + throw restErrorUtil.createGrantRevokeRESTException("User doesn't have necessary permission to revoke access"); + } + } catch (WebApplicationException excp) { + throw excp; + } catch (Throwable excp) { + LOG.error("secureRevokeAccess({}, {}) failed", serviceName, revokeRequest, excp); + + throw restErrorUtil.createRESTException(excp.getMessage()); + } finally { + RangerPerfTracer.log(perf); + } + + ret.setStatusCode(RESTResponse.STATUS_SUCCESS); + } + } + + LOG.debug("<== ServiceREST.secureRevokeAccess({}, {}) :{}", serviceName, revokeRequest, ret); + + return ret; + } + + @POST + @Path("/policies") + @Consumes("application/json") + @Produces("application/json") + public RangerPolicy createPolicy(RangerPolicy policy, @Context HttpServletRequest request) { + LOG.debug("==> ServiceREST.createPolicy({})", policy); + + RangerPolicy ret = null; + RangerPerfTracer perf = null; + + try { + if (RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { + perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "ServiceREST.createPolicy(policyName=" + policy.getName() + ")"); + } + + if (request != null) { + boolean deleteIfExists = "true".equalsIgnoreCase(StringUtils.trimToEmpty(request.getParameter(PARAM_DELETE_IF_EXISTS))); + + if (deleteIfExists) { + boolean importInProgress = "true".equalsIgnoreCase(StringUtils.trimToEmpty(String.valueOf(request.getAttribute(PARAM_IMPORT_IN_PROGRESS)))); + + if (!importInProgress) { + List policies = new ArrayList() { + { + add(policy); + } + }; + + deleteExactMatchPolicyForResource(policies, request.getRemoteUser(), null); + } + } + + boolean updateIfExists = "true".equalsIgnoreCase(StringUtils.trimToEmpty(request.getParameter(PARAM_UPDATE_IF_EXISTS))); + boolean mergeIfExists = "true".equalsIgnoreCase(StringUtils.trimToEmpty(request.getParameter(PARAM_MERGE_IF_EXISTS))); + + // Default POLICY_MATCHING_ALGO_BY_RESOURCE + String policyMatchingAlgo = POLICY_MATCHING_ALGO_BY_POLICYNAME.equalsIgnoreCase(StringUtils.trimToEmpty(request.getParameter(PARAM_POLICY_MATCHING_ALGORITHM))) ? POLICY_MATCHING_ALGO_BY_POLICYNAME : POLICY_MATCHING_ALGO_BY_RESOURCE; + + LOG.debug(" policyMatchingAlgo: {} updateIfExists: {} mergeIfExists: {} deleteIfExists: {}", policyMatchingAlgo, updateIfExists, mergeIfExists, deleteIfExists); + + if (mergeIfExists && updateIfExists) { + LOG.warn("Cannot use both updateIfExists and mergeIfExists for a createPolicy. mergeIfExists will override updateIfExists for policy :[{}]", policy.getName()); + } + + if (!mergeIfExists && !updateIfExists) { + ret = createPolicyUnconditionally(policy); + } else if (mergeIfExists) { + ret = applyPolicy(policy, request); + } else if (policyMatchingAlgo.equalsIgnoreCase(POLICY_MATCHING_ALGO_BY_RESOURCE)) { + ret = applyPolicy(policy, request); + } else if (policyMatchingAlgo.equalsIgnoreCase(POLICY_MATCHING_ALGO_BY_POLICYNAME)) { + RangerPolicy existingPolicy = getPolicyMatchByName(policy, request); + + if (existingPolicy != null) { + policy.setId(existingPolicy.getId()); + + ret = updatePolicy(policy, null); + } else { + ret = createPolicyUnconditionally(policy); + } + } + + LOG.debug("<== ServiceREST.createPolicy({}): {}", policy, ret); + + return ret; + } + + if (ret == null) { + ret = createPolicyUnconditionally(policy); + } + } catch (WebApplicationException excp) { + throw excp; + } catch (Throwable excp) { + LOG.error("createPolicy({}) failed", policy, excp); + + throw restErrorUtil.createRESTException(excp.getMessage()); + } finally { + RangerPerfTracer.log(perf); + } + + LOG.debug("<== ServiceREST.createPolicy({}): {}", policy, ret); + + return ret; + } + + /* + The verb for applyPolicy is POST as it could be partial update or a create + */ + + @POST + @Path("/policies/apply") + @Consumes("application/json") + @Produces("application/json") + public RangerPolicy applyPolicy(RangerPolicy policy, @Context HttpServletRequest request) { + LOG.debug("==> ServiceREST.applyPolicy({})", policy); + + RangerPolicy ret; + + if (policy != null && StringUtils.isNotBlank(policy.getService())) { + try { + final RangerPolicy existingPolicy; + String signature = (new RangerPolicyResourceSignature(policy)).getSignature(); + List policiesWithMatchingSignature = svcStore.getPoliciesByResourceSignature(policy.getService(), signature, true); + + if (CollectionUtils.isNotEmpty(policiesWithMatchingSignature)) { + if (policiesWithMatchingSignature.size() == 1) { + existingPolicy = policiesWithMatchingSignature.get(0); + } else { + throw new Exception("Multiple policies with matching policy-signature are found. Cannot determine target for applying policy"); + } + } else { + existingPolicy = null; + } + + if (existingPolicy == null) { + if (StringUtils.isNotEmpty(policy.getName())) { + String policyName = StringUtils.isNotBlank(policy.getName()) ? policy.getName() : null; + String serviceName = StringUtils.isNotBlank(policy.getService()) ? policy.getService() : null; + String zoneName = StringUtils.isNotBlank(policy.getZoneName()) ? policy.getZoneName() : null; + XXPolicy dbPolicy = daoManager.getXXPolicy().findPolicy(policyName, serviceName, zoneName); + //XXPolicy dbPolicy = daoManager.getXXPolicy().findPolicy(policy.getName(), policy.getService(), policy.getZoneName()); + + if (dbPolicy != null) { + policy.setName(policy.getName() + System.currentTimeMillis()); + } + } + + ret = createPolicy(policy, null); + } else { + boolean mergeIfExists = "true".equalsIgnoreCase(StringUtils.trimToEmpty(request.getParameter(PARAM_MERGE_IF_EXISTS))); + + if (!mergeIfExists) { + boolean updateIfExists = "true".equalsIgnoreCase(StringUtils.trimToEmpty(request.getParameter(PARAM_UPDATE_IF_EXISTS))); + + if (updateIfExists) { + // Called with explicit intent of updating an existing policy + mergeIfExists = false; + } else { + // Invoked through REST API. Merge with existing policy unless 'mergeIfExists' is explicitly set to false in HttpServletRequest + mergeIfExists = !"false".equalsIgnoreCase(StringUtils.trimToEmpty(request.getParameter(PARAM_MERGE_IF_EXISTS))); + } + } + + if (mergeIfExists) { + if (!existingPolicy.getIsDenyAllElse() && policy.getIsDenyAllElse()) { + LOG.error("Attempt to change the isDenyAllElse flag from false to true! Not supported!!"); + + throw new Exception("Merging existing policy(isDenyAllElse=false) with another policy(isDenyAllElse=true) is not allowed!"); + } + + ServiceRESTUtil.processApplyPolicy(existingPolicy, policy); + + policy = existingPolicy; + } else { + policy.setId(existingPolicy.getId()); + } + + ret = updatePolicy(policy, policy.getId()); + } + } catch (WebApplicationException excp) { + throw excp; + } catch (Exception exception) { + LOG.error("Failed to apply policy:", exception); + + throw restErrorUtil.createRESTException(exception.getMessage()); + } + } else { + throw restErrorUtil.createRESTException("Non-existing service specified:"); + } + + LOG.debug("<== ServiceREST.applyPolicy({}): {}", policy, ret); + + return ret; + } + + @PUT + @Path("/policies/{id}") + @Consumes("application/json") + @Produces("application/json") + public RangerPolicy updatePolicy(RangerPolicy policy, @PathParam("id") Long id) { + LOG.debug("==> ServiceREST.updatePolicy({})", policy); + + // if policy.id and param 'id' are specified, policy.id should be same as the param 'id' + // if policy.id is null, then set param 'id' into policy Object + if (policy.getId() == null) { + policy.setId(id); + } else if (!policy.getId().equals(id)) { + throw restErrorUtil.createRESTException(HttpServletResponse.SC_BAD_REQUEST, "policyID mismatch", true); + } + + RangerPolicy ret; + RangerPerfTracer perf = null; + + try { + if (RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { + perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "ServiceREST.updatePolicy(policyId=" + policy.getId() + ")"); + } + + if (isPolicyNameLengthValidationEnabled) { + if (policy.getName().length() > maxPolicyNameLength) { + throw restErrorUtil.createRESTException("Policy name should not be longer than " + maxPolicyNameLength + " characters", MessageEnums.INPUT_DATA_OUT_OF_BOUND, null, "policy name", policy.getName()); + } + } + + RangerPolicyValidator validator = validatorFactory.getPolicyValidator(svcStore); + + validator.validate(policy, Action.UPDATE, bizUtil.isAdmin() || isServiceAdmin(policy.getService()) || isZoneAdmin(policy.getZoneName())); + + ensureAdminAccess(policy); + + bizUtil.blockAuditorRoleUser(); + + ret = svcStore.updatePolicy(policy); + } catch (WebApplicationException excp) { + throw excp; + } catch (Throwable excp) { + LOG.error("updatePolicy({}) failed", policy, excp); + + throw restErrorUtil.createRESTException(excp.getMessage()); + } finally { + RangerPerfTracer.log(perf); + } + + LOG.debug("<== ServiceREST.updatePolicy({}): {}", policy, ret); + + return ret; + } + + @DELETE + @Path("/policies/{id}") + public void deletePolicy(@PathParam("id") Long id) { + LOG.debug("==> ServiceREST.deletePolicy({})", id); + + RangerPerfTracer perf = null; + + try { + if (RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { + perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "ServiceREST.deletePolicy(policyId=" + id + ")"); + } + + RangerPolicyValidator validator = validatorFactory.getPolicyValidator(svcStore); + + validator.validate(id, Action.DELETE); + + RangerPolicy policy = svcStore.getPolicy(id); + + ensureAdminAccess(policy); + + bizUtil.blockAuditorRoleUser(); + + svcStore.deletePolicy(policy); + } catch (WebApplicationException excp) { + throw excp; + } catch (Throwable excp) { + LOG.error("deletePolicy({}) failed", id, excp); + + throw restErrorUtil.createRESTException(excp.getMessage()); + } finally { + RangerPerfTracer.log(perf); + } + + LOG.debug("<== ServiceREST.deletePolicy({})", id); + } + + @GET + @Path("/policies/{id}") + @Produces("application/json") + public RangerPolicy getPolicy(@PathParam("id") Long id) { + LOG.debug("==> ServiceREST.getPolicy({})", id); + + RangerPolicy ret; + RangerPerfTracer perf = null; + + try { + if (RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { + perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "ServiceREST.getPolicy(policyId=" + id + ")"); + } + + ret = svcStore.getPolicy(id); + + if (ret != null) { + ensureAdminAndAuditAccess(ret); + } + } catch (WebApplicationException excp) { + throw excp; + } catch (Throwable excp) { + LOG.error("getPolicy({}) failed", id, excp); + + throw restErrorUtil.createRESTException(excp.getMessage()); + } finally { + RangerPerfTracer.log(perf); + } + + if (ret == null) { + throw restErrorUtil.createRESTException(HttpServletResponse.SC_NOT_FOUND, "Not found", true); + } + + LOG.debug("<== ServiceREST.getPolicy({}): {}", id, ret); + + return ret; + } + + @GET + @Path("/policyLabels") + @Produces("application/json") + public List getPolicyLabels(@Context HttpServletRequest request) { + LOG.debug("==> ServiceREST.getPolicyLabels()"); + + List ret; + RangerPerfTracer perf = null; + + try { + if (RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { + perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "ServiceREST.getPolicyLabels()"); + } + + SearchFilter filter = searchUtil.getSearchFilter(request, policyLabelsService.sortFields); + + ret = svcStore.getPolicyLabels(filter); + } catch (WebApplicationException excp) { + throw excp; + } catch (Throwable excp) { + LOG.error("getPolicyLabels() failed", excp); + + throw restErrorUtil.createRESTException(excp.getMessage()); + } finally { + RangerPerfTracer.log(perf); + } + + LOG.debug("<== ServiceREST.getPolicyLabels()"); + + return ret; + } + + @GET + @Path("/policies") + @Produces("application/json") + public RangerPolicyList getPolicies(@Context HttpServletRequest request) { + LOG.debug("==> ServiceREST.getPolicies()"); + + RangerPolicyList ret; + RangerPerfTracer perf = null; + SearchFilter filter = searchUtil.getSearchFilter(request, policyService.sortFields); + + try { + if (RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { + perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "ServiceREST.getPolicies()"); + } + + // get all policies from the store; pick the page to return after applying filter + final int savedStartIndex = filter.getStartIndex(); + final int savedMaxRows = filter.getMaxRows(); + + filter.setStartIndex(0); + filter.setMaxRows(Integer.MAX_VALUE); + + List policies = svcStore.getPolicies(filter); + + filter.setStartIndex(savedStartIndex); + filter.setMaxRows(savedMaxRows); + + policies = applyAdminAccessFilter(policies); + ret = toRangerPolicyList(policies, filter); + } catch (WebApplicationException excp) { + throw excp; + } catch (Throwable excp) { + LOG.error("getPolicies() failed", excp); + + throw restErrorUtil.createRESTException(excp.getMessage()); + } finally { + RangerPerfTracer.log(perf); + } + + LOG.debug("<== ServiceREST.getPolicies(): count={}", (ret == null ? 0 : ret.getListSize())); + + return ret; + } + + /** + * Resets/ removes service policy cache for given service. + * + * @param serviceName non-empty serviceName + * @return {@code true} if successfully reseted/ removed for given service, {@code false} otherwise. + */ + @GET + @Path("/policies/cache/reset") + @Produces("application/json") + public boolean resetPolicyCache(@QueryParam("serviceName") String serviceName) { + LOG.debug("==> ServiceREST.resetPolicyCache({})", serviceName); + + if (StringUtils.isEmpty(serviceName)) { + throw restErrorUtil.createRESTException("Required parameter [serviceName] is missing.", MessageEnums.INVALID_INPUT_DATA); + } + + RangerService rangerService = null; + + try { + rangerService = svcStore.getServiceByName(serviceName); + } catch (Exception e) { + LOG.error(" {} No Service Found for ServiceName:{}", HttpServletResponse.SC_BAD_REQUEST, serviceName); + } + + if (rangerService == null) { + throw restErrorUtil.createRESTException(HttpServletResponse.SC_BAD_REQUEST, "Invalid service name", true); + } + + // check for ADMIN access + if (!bizUtil.isAdmin()) { + boolean isServiceAdmin = false; + String loggedInUser = bizUtil.getCurrentUserLoginId(); + + try { + isServiceAdmin = bizUtil.isUserServiceAdmin(rangerService, loggedInUser); + } catch (Exception e) { + LOG.warn("Failed to find if user [{}] has service admin privileges on service [{}]", loggedInUser, serviceName, e); + } + + if (!isServiceAdmin) { + throw restErrorUtil.createRESTException("User cannot reset policy cache", MessageEnums.OPER_NO_PERMISSION); + } + } + + boolean ret = svcStore.resetPolicyCache(serviceName); + + LOG.debug("<== ServiceREST.resetPolicyCache(): ret={}", ret); + + return ret; + } + + /** + * Resets/ removes service policy cache for all. + * + * @return {@code true} if successfully reseted/ removed, {@code false} otherwise. + */ + @GET + @Path("/policies/cache/reset-all") + @Produces("application/json") + public boolean resetPolicyCacheAll() { + LOG.debug("==> ServiceREST.resetPolicyCacheAll()"); + + // check for ADMIN access + if (!bizUtil.isAdmin()) { + throw restErrorUtil.createRESTException("User cannot reset policy cache", MessageEnums.OPER_NO_PERMISSION); + } + + boolean ret = svcStore.resetPolicyCache(null); + + LOG.debug("<== ServiceREST.resetPolicyCacheAll(): ret={}", ret); + + return ret; + } + + @GET + @Path("/policies/downloadExcel") + @Produces("application/ms-excel") + public void getPoliciesInExcel(@Context HttpServletRequest request, @Context HttpServletResponse response) { + LOG.debug("==> ServiceREST.getPoliciesInExcel()"); + + RangerPerfTracer perf = null; + SearchFilter filter = searchUtil.getSearchFilter(request, policyService.sortFields); + + try { + if (RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { + perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "ServiceREST.getPoliciesInExcel()"); + } + + List policyLists = new ArrayList<>(); + + policyLists = getAllFilteredPolicyList(filter, request, policyLists); + + if (CollectionUtils.isNotEmpty(policyLists)) { + Map mapServiceTypeAndImplClass = new HashMap<>(); + + for (RangerPolicy rangerPolicy : policyLists) { + if (rangerPolicy != null) { + ensureAdminAndAuditAccess(rangerPolicy, mapServiceTypeAndImplClass); + } + } + + svcStore.getPoliciesInExcel(policyLists, response); + } else { + response.setStatus(HttpServletResponse.SC_NO_CONTENT); + + LOG.error("No policies found to download!"); + } + + RangerExportPolicyList rangerExportPolicyList = new RangerExportPolicyList(); + + rangerExportPolicyList.setMetaDataInfo(svcStore.getMetaDataInfo()); + + String metaDataInfo = JsonUtilsV2.mapToJson(rangerExportPolicyList.getMetaDataInfo()); + + policyService.createTransactionLog(new XXTrxLogV2(AppConstants.CLASS_TYPE_RANGER_POLICY, null, null, "EXPORT EXCEL"), "Export Excel", metaDataInfo, null); + } catch (WebApplicationException excp) { + throw excp; + } catch (Throwable excp) { + LOG.error("Error while downloading policy report", excp); + + throw restErrorUtil.createRESTException(excp.getMessage()); + } finally { + RangerPerfTracer.log(perf); + } + } + + @GET + @Path("/policies/csv") + @Produces("text/csv") + public void getPoliciesInCsv(@Context HttpServletRequest request, @Context HttpServletResponse response) throws IOException { + LOG.debug("==> ServiceREST.getPoliciesInCsv()"); + + RangerPerfTracer perf = null; + SearchFilter filter = searchUtil.getSearchFilter(request, policyService.sortFields); + + try { + if (RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { + perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "ServiceREST.getPoliciesInCsv()"); + } + + List policyLists = new ArrayList<>(); + + policyLists = getAllFilteredPolicyList(filter, request, policyLists); + + if (CollectionUtils.isNotEmpty(policyLists)) { + Map mapServiceTypeAndImplClass = new HashMap<>(); + + for (RangerPolicy rangerPolicy : policyLists) { + if (rangerPolicy != null) { + ensureAdminAndAuditAccess(rangerPolicy, mapServiceTypeAndImplClass); + } + } + + svcStore.getPoliciesInCSV(policyLists, response); + } else { + response.setStatus(HttpServletResponse.SC_NO_CONTENT); + + LOG.error("No policies found to download!"); + } + + RangerExportPolicyList rangerExportPolicyList = new RangerExportPolicyList(); + + rangerExportPolicyList.setMetaDataInfo(svcStore.getMetaDataInfo()); + + String metaDataInfo = JsonUtilsV2.mapToJson(rangerExportPolicyList.getMetaDataInfo()); + + policyService.createTransactionLog(new XXTrxLogV2(AppConstants.CLASS_TYPE_RANGER_POLICY, null, null, "EXPORT CSV"), "Export CSV", metaDataInfo, null); + } catch (WebApplicationException excp) { + throw excp; + } catch (Throwable excp) { + LOG.error("Error while downloading policy report", excp); + + throw restErrorUtil.createRESTException(excp.getMessage()); + } finally { + RangerPerfTracer.log(perf); + } + } + + @GET + @Path("/policies/exportJson") + @Produces("text/json") + public void getPoliciesInJson(@Context HttpServletRequest request, @Context HttpServletResponse response, @QueryParam("checkPoliciesExists") Boolean checkPoliciesExists) { + LOG.debug("==> ServiceREST.getPoliciesInJson()"); + + RangerPerfTracer perf = null; + SearchFilter filter = searchUtil.getSearchFilter(request, policyService.sortFields); + + requestParamsValidation(filter); + + try { + if (RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { + perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "ServiceREST.getPoliciesInJson()"); + } + + if (checkPoliciesExists == null) { + checkPoliciesExists = false; + } + + List policyLists = new ArrayList<>(); + + policyLists = getAllFilteredPolicyList(filter, request, policyLists); + + if (CollectionUtils.isNotEmpty(policyLists)) { + Map mapServiceTypeAndImplClass = new HashMap<>(); + + for (RangerPolicy rangerPolicy : policyLists) { + if (rangerPolicy != null) { + ensureAdminAndAuditAccess(rangerPolicy, mapServiceTypeAndImplClass); + } + } + + bizUtil.blockAuditorRoleUser(); + + svcStore.getObjectInJson(policyLists, response, JSON_FILE_NAME_TYPE.POLICY); + } else { + checkPoliciesExists = true; + + response.setStatus(HttpServletResponse.SC_NO_CONTENT); + + LOG.error("There is no Policy to Export!!"); + } + + if (!checkPoliciesExists) { + RangerExportPolicyList rangerExportPolicyList = new RangerExportPolicyList(); + + rangerExportPolicyList.setMetaDataInfo(svcStore.getMetaDataInfo()); + + String metaDataInfo = JsonUtilsV2.mapToJson(rangerExportPolicyList.getMetaDataInfo()); + + policyService.createTransactionLog(new XXTrxLogV2(AppConstants.CLASS_TYPE_RANGER_POLICY, null, null, "EXPORT JSON"), "Export Json", metaDataInfo, null); + } + } catch (WebApplicationException excp) { + throw excp; + } catch (Throwable excp) { + LOG.error("Error while exporting policy file!!", excp); + + throw restErrorUtil.createRESTException(excp.getMessage()); + } finally { + RangerPerfTracer.log(perf); + } + } + + @POST + @Path("/policies/importPoliciesFromFile") + @Consumes({MediaType.MULTIPART_FORM_DATA, MediaType.APPLICATION_JSON}) + @Produces("application/json") + @PreAuthorize("@rangerPreAuthSecurityHandler.isAdminOrKeyAdminRole()") + public void importPoliciesFromFile(@Context HttpServletRequest request, @FormDataParam("servicesMapJson") InputStream serviceMapStream, @FormDataParam("zoneMapJson") InputStream zoneMapStream, @FormDataParam("file") InputStream uploadedInputStream, @FormDataParam("file") FormDataContentDisposition fileDetail, @QueryParam("isOverride") Boolean isOverride, @QueryParam("importType") String importType) { + LOG.debug("==> ServiceREST.importPoliciesFromFile()"); + + RangerContextHolder.getOrCreateOpContext().setBulkModeContext(true); + + RangerPerfTracer perf = null; + String metaDataInfo = null; + + request.setAttribute(PARAM_IMPORT_IN_PROGRESS, true); + + try { + if (RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { + perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "ServiceREST.importPoliciesFromFile()"); + } + + policyService.createTransactionLog(new XXTrxLogV2(AppConstants.CLASS_TYPE_RANGER_POLICY, null, null, "IMPORT START"), "Import", "IMPORT START", null); + + if (isOverride == null) { + isOverride = false; + } + + List serviceNameList = new ArrayList<>(); + + getServiceNameList(request, serviceNameList); + + Map servicesMappingMap = new LinkedHashMap<>(); + List sourceServices = new ArrayList<>(); + List destinationServices = new ArrayList<>(); + Map zoneMappingMap = new LinkedHashMap<>(); + List sourceZones = new ArrayList<>(); + List destinationZones = new ArrayList<>(); + + if (zoneMapStream != null) { + zoneMappingMap = svcStore.getMapFromInputStream(zoneMapStream); + + processZoneMapping(zoneMappingMap, sourceZones, destinationZones); + } + + if (serviceMapStream != null) { + servicesMappingMap = svcStore.getMapFromInputStream(serviceMapStream); + + processServiceMapping(servicesMappingMap, sourceServices, destinationServices); + } + + String fileName = fileDetail.getFileName(); + int totalPolicyCreate = 0; + String zoneNameInJson = null; + Map policiesMap = new LinkedHashMap<>(); + List dataFileSourceServices = new ArrayList<>(); + + if (fileName.endsWith("json")) { + try { + RangerExportPolicyList rangerExportPolicyList = processPolicyInputJsonForMetaData(uploadedInputStream, null); + + if (rangerExportPolicyList != null && !CollectionUtils.sizeIsEmpty(rangerExportPolicyList.getMetaDataInfo())) { + metaDataInfo = JsonUtilsV2.mapToJson(rangerExportPolicyList.getMetaDataInfo()); + } else { + LOG.info("metadata info is not provided!!"); + } + + List policies = getPoliciesFromProvidedJson(rangerExportPolicyList); + + int i = 0; + if (CollectionUtils.sizeIsEmpty(servicesMappingMap) && isOverride) { + if (policies != null && !CollectionUtils.sizeIsEmpty(policies)) { + for (RangerPolicy policyInJson : policies) { + if (policyInJson != null) { + if (i == 0 && StringUtils.isNotBlank(policyInJson.getZoneName())) { + zoneNameInJson = policyInJson.getZoneName().trim(); + } + + if (StringUtils.isNotEmpty(policyInJson.getService().trim())) { + String serviceName = policyInJson.getService().trim(); + + if (CollectionUtils.isNotEmpty(serviceNameList) && serviceNameList.contains(serviceName) && !sourceServices.contains(serviceName) && !destinationServices.contains(serviceName)) { + sourceServices.add(serviceName); + destinationServices.add(serviceName); + } else if (CollectionUtils.isEmpty(serviceNameList) && !sourceServices.contains(serviceName) && !destinationServices.contains(serviceName)) { + sourceServices.add(serviceName); + destinationServices.add(serviceName); + } + } else { + LOG.error("Service Name or Policy Name is not provided!!"); + + throw restErrorUtil.createRESTException("Service Name or Policy Name is not provided!!"); + } + } + + i++; + } + } + } else if (!CollectionUtils.sizeIsEmpty(servicesMappingMap)) { + if (policies != null && !CollectionUtils.sizeIsEmpty(policies)) { + i = 0; + + for (RangerPolicy policyInJson : policies) { + if (policyInJson != null) { + if (i == 0 && StringUtils.isNotBlank(policyInJson.getZoneName())) { + zoneNameInJson = policyInJson.getZoneName().trim(); + } + + if (StringUtils.isNotEmpty(policyInJson.getService().trim())) { + dataFileSourceServices.add(policyInJson.getService().trim()); + } else { + LOG.error("Service Name or Policy Name is not provided!!"); + + throw restErrorUtil.createRESTException("Service Name or Policy Name is not provided!!"); + } + + i++; + } + } + + if (!dataFileSourceServices.containsAll(sourceServices)) { + LOG.error("Json File does not contain specified source service name."); + + throw restErrorUtil.createRESTException("Json File does not contain specified source service name."); + } + } + } + + boolean deleteIfExists = "true".equalsIgnoreCase(StringUtils.trimToEmpty(request.getParameter(PARAM_DELETE_IF_EXISTS))); + boolean updateIfExists = "true".equalsIgnoreCase(StringUtils.trimToEmpty(request.getParameter(PARAM_UPDATE_IF_EXISTS))); + String polResource = request.getParameter(SearchFilter.POL_RESOURCE); + + if (updateIfExists) { + isOverride = false; + } + + String destinationZoneName = getDestinationZoneName(destinationZones, zoneNameInJson); + + if (isOverride && !updateIfExists && StringUtils.isEmpty(polResource)) { + LOG.debug("Deleting Policy from provided services in servicesMapJson file..."); + + if (CollectionUtils.isNotEmpty(sourceServices) && CollectionUtils.isNotEmpty(destinationServices)) { + deletePoliciesProvidedInServiceMap(sourceServices, destinationServices, destinationZoneName); //In order to delete Zone specific policies from service + } + } else if (updateIfExists && StringUtils.isNotEmpty(polResource)) { + LOG.debug("Deleting Policy from provided services in servicesMapJson file for specific resource..."); + + if (CollectionUtils.isNotEmpty(sourceServices) && CollectionUtils.isNotEmpty(destinationServices)) { + deletePoliciesForResource(sourceServices, destinationServices, request, policies, destinationZoneName); //In order to delete Zone specific policies from service + } + } + + if (policies != null && !CollectionUtils.sizeIsEmpty(policies)) { + for (RangerPolicy policyInJson : policies) { + if (policyInJson != null) { + if (StringUtils.isNotBlank(destinationZoneName)) { + boolean isZoneServiceExistAtDestination = validateDestZoneServiceMapping(destinationZoneName, policyInJson, servicesMappingMap); + + if (!isZoneServiceExistAtDestination) { + LOG.warn("provided service of policy in File is not associated with zone"); + + continue; + } + } + + policiesMap = svcStore.createPolicyMap(zoneMappingMap, sourceZones, destinationZoneName, servicesMappingMap, sourceServices, destinationServices, policyInJson, policiesMap); // zone Info is also sent for creating policy map + } + } + + if (deleteIfExists) { + //deleting target policies if already exist + deleteExactMatchPolicyForResource(policies, request.getRemoteUser(), destinationZoneName); + } + } + + totalPolicyCreate = createPolicesBasedOnPolicyMap(request, policiesMap, serviceNameList, updateIfExists, totalPolicyCreate); + + if (!(totalPolicyCreate > 0)) { + LOG.error("zero policy is created from provided data file!!"); + + throw restErrorUtil.createRESTException("zero policy is created from provided data file!!"); + } + } catch (IOException e) { + LOG.error(e.getMessage()); + + throw restErrorUtil.createRESTException(e.getMessage()); + } + } else { + LOG.error("Provided file format is not supported!!"); + + throw restErrorUtil.createRESTException("Provided file format is not supported!!"); + } + } catch (JsonSyntaxException ex) { + LOG.error("Provided json file is not valid!!", ex); + + policyService.createTransactionLog(new XXTrxLogV2(AppConstants.CLASS_TYPE_RANGER_POLICY, null, null, "IMPORT ERROR"), "Import failed", StringUtils.isNotEmpty(metaDataInfo) ? metaDataInfo : null, null); + + throw restErrorUtil.createRESTException(ex.getMessage()); + } catch (WebApplicationException excp) { + LOG.error("Error while importing policy from file!!", excp); + + policyService.createTransactionLog(new XXTrxLogV2(AppConstants.CLASS_TYPE_RANGER_POLICY, null, null, "IMPORT ERROR"), "Import failed", StringUtils.isNotEmpty(metaDataInfo) ? metaDataInfo : null, null); + + throw excp; + } catch (Throwable excp) { + LOG.error("Error while importing policy from file!!", excp); + + policyService.createTransactionLog(new XXTrxLogV2(AppConstants.CLASS_TYPE_RANGER_POLICY, null, null, "IMPORT ERROR"), "Import failed", StringUtils.isNotEmpty(metaDataInfo) ? metaDataInfo : null, null); + + throw restErrorUtil.createRESTException(excp.getMessage()); + } finally { + RangerPerfTracer.log(perf); + + policyService.createTransactionLog(new XXTrxLogV2(AppConstants.CLASS_TYPE_RANGER_POLICY, null, null, "IMPORT END"), "IMPORT END", StringUtils.isNotEmpty(metaDataInfo) ? metaDataInfo : null, null); + + LOG.debug("<== ServiceREST.importPoliciesFromFile()"); + } + } + + public List getPolicies(SearchFilter filter) { + LOG.debug("==> ServiceREST.getPolicies(filter)"); + + List ret; + RangerPerfTracer perf = null; + + try { + if (RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { + perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "ServiceREST.getPolicies()"); + } + + ret = svcStore.getPolicies(filter); + ret = applyAdminAccessFilter(ret); + } catch (WebApplicationException excp) { + throw excp; + } catch (Throwable excp) { + LOG.error("getPolicies() failed", excp); + + throw restErrorUtil.createRESTException(excp.getMessage()); + } finally { + RangerPerfTracer.log(perf); + } + + LOG.debug("<== ServiceREST.getPolicies(filter): count={}", (ret == null ? 0 : ret.size())); + + return ret; + } + + @GET + @Path("/policies/count") + @Produces("application/json") + public Long countPolicies(@Context HttpServletRequest request) { + LOG.debug("==> ServiceREST.countPolicies():"); + + Long ret; + RangerPerfTracer perf = null; + + try { + if (RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { + perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "ServiceREST.countPolicies()"); + } + + List policies = getPolicies(request).getPolicies(); + + policies = applyAdminAccessFilter(policies); + + ret = policies == null ? 0L : policies.size(); + } catch (WebApplicationException excp) { + throw excp; + } catch (Throwable excp) { + LOG.error("countPolicies() failed", excp); + + throw restErrorUtil.createRESTException(excp.getMessage()); + } finally { + RangerPerfTracer.log(perf); + } + + LOG.debug("<== ServiceREST.countPolicies(): {}", ret); + + return ret; + } + + @GET + @Path("/policies/service/{id}") + @Produces("application/json") + public RangerPolicyList getServicePolicies(@PathParam("id") Long serviceId, @Context HttpServletRequest request) { + LOG.debug("==> ServiceREST.getServicePolicies({})", serviceId); + + RangerPolicyList ret; + RangerPerfTracer perf = null; + SearchFilter filter = searchUtil.getSearchFilter(request, policyService.sortFields); + + try { + if (RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { + perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "ServiceREST.getServicePolicies(serviceId=" + serviceId + ")"); + } + + String policyTypeStr = filter.getParam(SearchFilter.POLICY_TYPE); + + if (policyTypeStr != null) { + int policyType = Integer.parseInt(policyTypeStr); + + if (IntStream.of(RangerPolicy.POLICY_TYPES).noneMatch(x -> x == policyType)) { + throw restErrorUtil.createRESTException("policyTypes with id: " + policyTypeStr + " does not exist", MessageEnums.DATA_NOT_FOUND, Long.parseLong(policyTypeStr), null, "readResource : No Object found with given id."); + } + } + + // get all policies from the store; pick the page to return after applying filter + int savedStartIndex = filter.getStartIndex(); + int savedMaxRows = filter.getMaxRows(); + + filter.setStartIndex(0); + filter.setMaxRows(Integer.MAX_VALUE); + + List servicePolicies = svcStore.getServicePolicies(serviceId, filter); + + filter.setStartIndex(savedStartIndex); + filter.setMaxRows(savedMaxRows); + + servicePolicies = applyAdminAccessFilter(servicePolicies); + + ret = toRangerPolicyList(servicePolicies, filter); + } catch (WebApplicationException excp) { + throw excp; + } catch (Throwable excp) { + LOG.error("getServicePolicies({}) failed", serviceId, excp); + + throw restErrorUtil.createRESTException(excp.getMessage()); + } finally { + RangerPerfTracer.log(perf); + } + + LOG.debug("<== ServiceREST.getServicePolicies({}): count={}", serviceId, (ret == null ? 0 : ret.getListSize())); + + return ret; + } + + @GET + @Path("/policies/service/name/{name}") + @Produces("application/json") + public RangerPolicyList getServicePoliciesByName(@PathParam("name") String serviceName, @Context HttpServletRequest request) { + LOG.debug("==> ServiceREST.getServicePolicies({})", serviceName); + + SearchFilter filter = searchUtil.getSearchFilter(request, policyService.sortFields); + RangerPolicyList ret = getServicePolicies(serviceName, filter); + + LOG.debug("<== ServiceREST.getServicePolicies({}): count={}", serviceName, (ret == null ? 0 : ret.getListSize())); + + return ret; + } + + @GET + @Path("/policies/download/{serviceName}") + @Produces("application/json") + public ServicePolicies getServicePoliciesIfUpdated(@PathParam("serviceName") String serviceName, @DefaultValue("-1") @QueryParam("lastKnownVersion") Long lastKnownVersion, @DefaultValue("0") @QueryParam("lastActivationTime") Long lastActivationTime, @QueryParam("pluginId") String pluginId, @DefaultValue("") @QueryParam("clusterName") String clusterName, @DefaultValue("") @QueryParam("zoneName") String zoneName, @DefaultValue("false") @QueryParam("supportsPolicyDeltas") Boolean supportsPolicyDeltas, @DefaultValue("") @QueryParam("pluginCapabilities") String pluginCapabilities, @Context HttpServletRequest request) throws Exception { + LOG.debug("==> ServiceREST.getServicePoliciesIfUpdated({}, {}, {}, {}, {}, {})", serviceName, lastKnownVersion, lastActivationTime, pluginId, clusterName, supportsPolicyDeltas); + + ServicePolicies ret = null; + int httpCode = HttpServletResponse.SC_OK; + String logMsg = null; + RangerPerfTracer perf = null; + Long downloadedVersion = null; + boolean isValid = false; + + try { + bizUtil.failUnauthenticatedDownloadIfNotAllowed(); + + isValid = serviceUtil.isValidateHttpsAuthentication(serviceName, request); + } catch (WebApplicationException webException) { + httpCode = webException.getResponse().getStatus(); + logMsg = webException.getResponse().getEntity().toString(); + } catch (Exception e) { + httpCode = HttpServletResponse.SC_BAD_REQUEST; + logMsg = e.getMessage(); + } + + if (isValid) { + try { + if (RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { + perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "ServiceREST.getServicePoliciesIfUpdated(serviceName=" + serviceName + ",lastKnownVersion=" + lastKnownVersion + ",lastActivationTime=" + lastActivationTime + ")"); + } + + ret = svcStore.getServicePoliciesIfUpdated(serviceName, lastKnownVersion, !supportsPolicyDeltas); + + if (ret == null) { + downloadedVersion = lastKnownVersion; + httpCode = HttpServletResponse.SC_NOT_MODIFIED; + logMsg = "No change since last update"; + } else { + downloadedVersion = ret.getPolicyVersion(); + logMsg = "Returning " + (ret.getPolicies() != null ? ret.getPolicies().size() : (ret.getPolicyDeltas() != null ? ret.getPolicyDeltas().size() : 0)) + " policies. Policy version=" + ret.getPolicyVersion(); + } + } catch (Throwable excp) { + LOG.error("getServicePoliciesIfUpdated({}, {}, {}) failed", serviceName, lastKnownVersion, lastActivationTime, excp); + + httpCode = HttpServletResponse.SC_BAD_REQUEST; + logMsg = excp.getMessage(); + } finally { + createPolicyDownloadAudit(serviceName, lastKnownVersion, pluginId, httpCode, clusterName, zoneName, request); + RangerPerfTracer.log(perf); + } + } + assetMgr.createPluginInfo(serviceName, pluginId, request, RangerPluginInfo.ENTITY_TYPE_POLICIES, downloadedVersion, lastKnownVersion, lastActivationTime, httpCode, clusterName, pluginCapabilities); + + if (httpCode != HttpServletResponse.SC_OK) { + boolean logError = httpCode != HttpServletResponse.SC_NOT_MODIFIED; + + throw restErrorUtil.createRESTException(httpCode, logMsg, logError); + } + + LOG.debug("<== ServiceREST.getServicePoliciesIfUpdated({}, {}, {}, {}, {}, {}) : count={}", serviceName, lastKnownVersion, lastActivationTime, pluginId, clusterName, supportsPolicyDeltas, ((ret == null || ret.getPolicies() == null) ? 0 : ret.getPolicies().size())); + + return ret; + } + + @GET + @Path("/secure/policies/download/{serviceName}") + @Produces("application/json") + public ServicePolicies getSecureServicePoliciesIfUpdated(@PathParam("serviceName") String serviceName, @DefaultValue("-1") @QueryParam("lastKnownVersion") Long lastKnownVersion, @DefaultValue("0") @QueryParam("lastActivationTime") Long lastActivationTime, @QueryParam("pluginId") String pluginId, @DefaultValue("") @QueryParam("clusterName") String clusterName, @DefaultValue("") @QueryParam("zoneName") String zoneName, @DefaultValue("false") @QueryParam("supportsPolicyDeltas") Boolean supportsPolicyDeltas, @DefaultValue("") @QueryParam("pluginCapabilities") String pluginCapabilities, @Context HttpServletRequest request) throws Exception { + LOG.debug("==> ServiceREST.getSecureServicePoliciesIfUpdated({}, {}, {}, {}, {}, {})", serviceName, lastKnownVersion, lastActivationTime, pluginId, clusterName, supportsPolicyDeltas); + + ServicePolicies ret = null; + int httpCode = HttpServletResponse.SC_OK; + String logMsg = null; + RangerPerfTracer perf = null; + boolean isAllowed = false; + boolean isAdmin = bizUtil.isAdmin(); + boolean isKeyAdmin = bizUtil.isKeyAdmin(); + Long downloadedVersion = null; + boolean isValid = false; + + request.setAttribute("downloadPolicy", "secure"); + + try { + isValid = serviceUtil.isValidService(serviceName, request); + } catch (WebApplicationException webException) { + httpCode = webException.getResponse().getStatus(); + logMsg = webException.getResponse().getEntity().toString(); + } catch (Exception e) { + httpCode = HttpServletResponse.SC_BAD_REQUEST; + logMsg = e.getMessage(); + } + + if (isValid) { + try { + if (RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { + perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "ServiceREST.getSecureServicePoliciesIfUpdated(serviceName=" + serviceName + ",lastKnownVersion=" + lastKnownVersion + ",lastActivationTime=" + lastActivationTime + ")"); + } + + XXService xService = daoManager.getXXService().findByName(serviceName); + XXServiceDef xServiceDef = daoManager.getXXServiceDef().getById(xService.getType()); + RangerService rangerService; + + if (StringUtils.equals(xServiceDef.getImplclassname(), EmbeddedServiceDefsUtil.KMS_IMPL_CLASS_NAME)) { + rangerService = svcStore.getServiceByNameForDP(serviceName); + + if (isKeyAdmin) { + isAllowed = true; + } else { + if (rangerService != null) { + isAllowed = bizUtil.isUserAllowed(rangerService, Allowed_User_List_For_Download); + + if (!isAllowed) { + isAllowed = bizUtil.isUserAllowed(rangerService, Allowed_User_List_For_Grant_Revoke); + } + } + } + } else { + rangerService = svcStore.getServiceByName(serviceName); + + if (isAdmin) { + isAllowed = true; + } else { + if (rangerService != null) { + isAllowed = bizUtil.isUserAllowed(rangerService, Allowed_User_List_For_Download); + + if (!isAllowed) { + isAllowed = bizUtil.isUserAllowed(rangerService, Allowed_User_List_For_Grant_Revoke); + } + } + } + } + + if (isAllowed) { + ret = svcStore.getServicePoliciesIfUpdated(serviceName, lastKnownVersion, !supportsPolicyDeltas); + + if (ret == null) { + downloadedVersion = lastKnownVersion; + httpCode = HttpServletResponse.SC_NOT_MODIFIED; + logMsg = "No change since last update"; + } else { + downloadedVersion = ret.getPolicyVersion(); + logMsg = "Returning " + (ret.getPolicies() != null ? ret.getPolicies().size() : (ret.getPolicyDeltas() != null ? ret.getPolicyDeltas().size() : 0)) + " policies. Policy version=" + ret.getPolicyVersion(); + } + } else { + LOG.error("getSecureServicePoliciesIfUpdated({}, {}) failed as User doesn't have permission to download Policy", serviceName, lastKnownVersion); + + httpCode = HttpServletResponse.SC_FORBIDDEN; // assert user is authenticated. + logMsg = "User doesn't have permission to download policy"; + } + } catch (Throwable excp) { + LOG.error("getSecureServicePoliciesIfUpdated({}, {}, {}) failed", serviceName, lastKnownVersion, lastActivationTime, excp); + + httpCode = HttpServletResponse.SC_BAD_REQUEST; + logMsg = excp.getMessage(); + } finally { + createPolicyDownloadAudit(serviceName, lastKnownVersion, pluginId, httpCode, clusterName, zoneName, request); + RangerPerfTracer.log(perf); + } + } + + assetMgr.createPluginInfo(serviceName, pluginId, request, RangerPluginInfo.ENTITY_TYPE_POLICIES, downloadedVersion, lastKnownVersion, lastActivationTime, httpCode, clusterName, pluginCapabilities); + + if (httpCode != HttpServletResponse.SC_OK) { + boolean logError = httpCode != HttpServletResponse.SC_NOT_MODIFIED; + + throw restErrorUtil.createRESTException(httpCode, logMsg, logError); + } + + LOG.debug("<== ServiceREST.getSecureServicePoliciesIfUpdated({}, {}, {}, {}, {}, {}) : count={}", serviceName, lastKnownVersion, lastActivationTime, pluginId, clusterName, supportsPolicyDeltas, ((ret == null || ret.getPolicies() == null) ? 0 : ret.getPolicies().size())); + + return ret; + } + + @DELETE + @Path("/server/policydeltas") + @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") + public void deletePolicyDeltas(@DefaultValue("7") @QueryParam("days") Integer olderThan, @Context HttpServletRequest request) { + LOG.debug("==> ServiceREST.deletePolicyDeltas({})", olderThan); + + svcStore.resetPolicyUpdateLog(olderThan, RangerPolicyDelta.CHANGE_TYPE_INVALIDATE_POLICY_DELTAS); + + LOG.debug("<== ServiceREST.deletePolicyDeltas({})", olderThan); + } + + @DELETE + @Path("/server/purgepolicies/{serviceName}") + @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") + public void purgeEmptyPolicies(@PathParam("serviceName") String serviceName, @Context HttpServletRequest request) { + LOG.debug("==> ServiceREST.purgeEmptyPolicies({})", serviceName); + + if (serviceName == null) { + throw restErrorUtil.createRESTException(HttpServletResponse.SC_BAD_REQUEST, "Invalid service name", true); + } + + RangerPerfTracer perf = null; + + try { + if (RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { + perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "ServiceREST.purgeEmptyPolicies(serviceName=" + serviceName + ")"); + } + + if (svcStore.getServiceByName(serviceName) == null) { + throw new Exception("service does not exist - name=" + serviceName); + } + + ServicePolicies servicePolicies = svcStore.getServicePolicies(serviceName, -1L); + + if (servicePolicies != null && CollectionUtils.isNotEmpty(servicePolicies.getPolicies())) { + for (RangerPolicy policy : servicePolicies.getPolicies()) { + if (CollectionUtils.isEmpty(PolicyRefUpdater.getAllPolicyItems(policy))) { + deletePolicy(policy.getId()); + } + } + } + } catch (WebApplicationException excp) { + throw excp; + } catch (Throwable excp) { + LOG.error("purgeEmptyPolicies({}) failed", serviceName, excp); + + throw restErrorUtil.createRESTException(excp.getMessage()); + } finally { + RangerPerfTracer.log(perf); + } + + LOG.debug("<== ServiceREST.purgeEmptyPolicies({})", serviceName); + } + + @GET + @Path("/policies/eventTime") + @Produces("application/json") + @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.GET_POLICY_FROM_EVENT_TIME + "\")") + public RangerPolicy getPolicyFromEventTime(@Context HttpServletRequest request) { + LOG.debug("==> ServiceREST.getPolicyFromEventTime()"); + + String eventTimeStr = request.getParameter("eventTime"); + String policyIdStr = request.getParameter("policyId"); + String versionNoStr = request.getParameter("versionNo"); + + if (StringUtils.isEmpty(eventTimeStr) || StringUtils.isEmpty(policyIdStr)) { + throw restErrorUtil.createRESTException("EventTime or policyId cannot be null or empty string.", MessageEnums.INVALID_INPUT_DATA); + } + + Long policyId = Long.parseLong(policyIdStr); + RangerPolicy policy = null; + + if (!StringUtil.isEmpty(versionNoStr)) { + int policyVersion = Integer.parseInt(versionNoStr); + + try { + policy = svcStore.getPolicyForVersionNumber(policyId, policyVersion); + + if (policy != null) { + ensureAdminAndAuditAccess(policy); + } + } catch (WebApplicationException excp) { + throw excp; + } catch (Throwable excp) { + // Ignore any other exception and go for fetching the policy by eventTime + } + } + + if (policy == null) { + try { + policy = svcStore.getPolicyFromEventTime(eventTimeStr, policyId); + + if (policy != null) { + ensureAdminAndAuditAccess(policy); + } + } catch (WebApplicationException excp) { + throw excp; + } catch (Throwable excp) { + LOG.error("getPolicy({}) failed", policyId, excp); + + throw restErrorUtil.createRESTException(excp.getMessage()); + } + } + + if (policy == null) { + throw restErrorUtil.createRESTException(HttpServletResponse.SC_NOT_FOUND, "Not found", true); + } + + LOG.debug("<== ServiceREST.getPolicy({}): {}", policyId, policy); + LOG.debug("<== ServiceREST.getPolicyFromEventTime()"); + + return policy; + } + + @GET + @Path("/policy/{policyId}/versionList") + @Produces("application/json") + @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.GET_POLICY_VERSION_LIST + "\")") + public VXString getPolicyVersionList(@PathParam("policyId") Long policyId) { + return svcStore.getPolicyVersionList(policyId); + } + + @GET + @Path("/policy/{policyId}/version/{versionNo}") + @Produces("application/json") + @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.GET_POLICY_FOR_VERSION_NO + "\")") + public RangerPolicy getPolicyForVersionNumber(@PathParam("policyId") Long policyId, @PathParam("versionNo") int versionNo) { + RangerPolicy policy = svcStore.getPolicyForVersionNumber(policyId, versionNo); + + if (policy != null) { + ensureAdminAndAuditAccess(policy); + } + + return policy; + } + + @GET + @Path("/plugins/info") + @Produces("application/json") + @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.GET_PLUGINS_INFO + "\")") + public RangerPluginInfoList getPluginsInfo(@Context HttpServletRequest request) { + LOG.debug("==> ServiceREST.getPluginsInfo()"); + + RangerPluginInfoList ret = null; + SearchFilter filter = searchUtil.getSearchFilter(request, pluginInfoService.getSortFields()); + + try { + PList paginatedPluginsInfo = pluginInfoService.searchRangerPluginInfo(filter); + if (paginatedPluginsInfo != null) { + ret = new RangerPluginInfoList(); + + ret.setPluginInfoList(paginatedPluginsInfo.getList()); + ret.setPageSize(paginatedPluginsInfo.getPageSize()); + ret.setResultSize(paginatedPluginsInfo.getResultSize()); + ret.setStartIndex(paginatedPluginsInfo.getStartIndex()); + ret.setTotalCount(paginatedPluginsInfo.getTotalCount()); + ret.setSortBy(paginatedPluginsInfo.getSortBy()); + ret.setSortType(paginatedPluginsInfo.getSortType()); + } + } catch (WebApplicationException excp) { + throw excp; + } catch (Throwable excp) { + LOG.error("getPluginsInfo() failed", excp); + + throw restErrorUtil.createRESTException(excp.getMessage()); + } + + LOG.debug("<== ServiceREST.getPluginsInfo()"); + + return ret; + } + + public void blockIfGdsService(String serviceName) { + String serviceType = daoManager.getXXServiceDef().findServiceDefTypeByServiceName(serviceName); + + if (EMBEDDED_SERVICEDEF_GDS_NAME.equals(serviceType)) { + throw restErrorUtil.createRESTException(HttpServletResponse.SC_FORBIDDEN, EMBEDDED_SERVICEDEF_GDS_NAME.toUpperCase() + " policies can't be managed via this API", true); + } + } + + public RangerPolicyAdmin getPolicyAdminForDelegatedAdmin(String serviceName) { + return RangerPolicyAdminCacheForEngineOptions.getInstance().getServicePoliciesAdmin(serviceName, svcStore, zoneStore, roleDBStore, delegateAdminOptions); + } + + public List getPoliciesWithMetaAttributes(List policies) { + return svcStore.getPoliciesWithMetaAttributes(policies); + } + + @GET + @Path("/checksso") + @Produces(MediaType.TEXT_PLAIN) + public String checkSSO() { + return String.valueOf(bizUtil.isSSOEnabled()); + } + + @GET + @Path("/csrfconf") + @Produces("application/json") + public HashMap getCSRFProperties(@Context HttpServletRequest request) { + return getCSRFPropertiesMap(request); + } + + @GET + @Path("/metrics/type/{type}") + @Produces("application/json") + @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.GET_METRICS_BY_TYPE + "\")") + public String getMetricByType(@PathParam("type") String type) { + LOG.debug("==> ServiceREST.getMetricByType(serviceDefName={})", type); + + // as of now we are allowing only users with Admin role to access this + // API + bizUtil.checkSystemAdminAccess(); + bizUtil.blockAuditorRoleUser(); + + String ret; + + try { + ServiceDBStore.METRIC_TYPE metricType = ServiceDBStore.METRIC_TYPE.getMetricTypeByName(type); + + if (metricType == null) { + throw restErrorUtil.createRESTException("Metric type=" + type + ", not supported."); + } + + ret = svcStore.getMetricByType(metricType); + } catch (WebApplicationException excp) { + throw excp; + } catch (Throwable excp) { + LOG.error("getMetricByType({}) failed", type, excp); + throw restErrorUtil.createRESTException(excp.getMessage()); + } + + if (ret == null) { + throw restErrorUtil.createRESTException(HttpServletResponse.SC_NOT_FOUND, "Not found", true); + } + + LOG.debug("<== ServiceREST.getMetricByType({}): {}", type, ret); + + return ret; + } + + /** + * Delete services/ repos associated with cluster. + * Only users with Ranger UserAdmin OR KeyAdmin are allowed to access this API. + * + * @param clusterName + * @return List of {@link ServiceDeleteResponse serviceDeleteResponse}. + */ + @DELETE + @Path("/cluster-services/{clusterName}") + @Produces("application/json") + @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.DELETE_CLUSTER_SERVICES + "\")") + public ResponseEntity> deleteClusterServices(@PathParam("clusterName") String clusterName) { + LOG.debug("==> ServiceREST.deleteClusterServices({})", clusterName); + + List deletedServices = new ArrayList<>(); + HttpStatus responseStatus = HttpStatus.OK; + + try { + //check if user has ADMIN privileges + bizUtil.hasAdminPermissions("Services"); + + //get all service/ repo IDs to delete + List serviceIdsToBeDeleted = daoManager.getXXServiceConfigMap().findServiceIdsByClusterName(clusterName); + + if (serviceIdsToBeDeleted.isEmpty()) { + responseStatus = HttpStatus.NOT_FOUND; + } else { + //delete each service/ repo one by one + for (Long serviceId : serviceIdsToBeDeleted) { + ServiceDeleteResponse deleteResponse = new ServiceDeleteResponse(serviceId); + + try { + String serviceName = this.deleteServiceById(serviceId); + + deleteResponse.setServiceName(serviceName); + deleteResponse.setIsDeleted(Boolean.TRUE); + } catch (Throwable e) { + //log and proceed + LOG.warn("Skipping deletion of service with ID={}", serviceId); + + e.printStackTrace(); + deleteResponse.setIsDeleted(Boolean.FALSE); + deleteResponse.setErrorMsg(e.getMessage()); + } + + deletedServices.add(deleteResponse); + } + } + } catch (WebApplicationException excp) { + throw excp; + } catch (Throwable excp) { + LOG.error("Deleting services associated with cluster=({}) failed", clusterName, excp); + + throw restErrorUtil.createRESTException(excp.getMessage()); + } + + LOG.debug("<== ServiceREST.deleteClusterServices() - deletedServices: {}", deletedServices); + + return new ResponseEntity<>(deletedServices, responseStatus); + } + + @GET + @Path("/policies/guid/{guid}") + @Produces("application/json") + public RangerPolicy getPolicyByGUIDAndServiceNameAndZoneName(@PathParam("guid") String guid, @DefaultValue("") @QueryParam("serviceName") String serviceName, @DefaultValue("") @QueryParam("zoneName") String zoneName) { + LOG.debug("==> ServiceREST.getPolicyByGUIDAndServiceNameAndZoneName({}, {}, {})", guid, serviceName, zoneName); + + RangerPolicy ret; + RangerPerfTracer perf = null; + + try { + if (RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { + perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "ServiceREST.getPolicyByGUIDAndServiceNameAndZoneName(policyGUID=" + guid + ", serviceName=" + serviceName + ", zoneName=" + zoneName + ")"); + } + + ret = svcStore.getPolicy(guid, serviceName, zoneName); + + if (ret != null) { + ensureAdminAndAuditAccess(ret); + } + } catch (WebApplicationException excp) { + throw excp; + } catch (Throwable excp) { + LOG.error("getPolicyByGUIDAndServiceNameAndZoneName({}, {}, {}) failed", guid, serviceName, zoneName, excp); + + throw restErrorUtil.createRESTException(excp.getMessage()); + } finally { + RangerPerfTracer.log(perf); + } + + if (ret == null) { + throw restErrorUtil.createRESTException(HttpServletResponse.SC_NOT_FOUND, "Not found", true); + } + + LOG.debug("<== ServiceREST.getPolicyByGUIDAndServiceNameAndZoneName({}, {}, {}) : {}", guid, serviceName, zoneName, ret); + + return ret; + } + + @DELETE + @Path("/policies/guid/{guid}") + public void deletePolicyByGUIDAndServiceNameAndZoneName(@PathParam("guid") String guid, @DefaultValue("") @QueryParam("serviceName") String serviceName, @DefaultValue("") @QueryParam("zoneName") String zoneName) { + LOG.debug("==> ServiceREST.deletePolicyByGUIDAndServiceNameAndZoneName({}, {}, {})", guid, serviceName, zoneName); + + RangerPolicy ret; + RangerPerfTracer perf = null; + + try { + if (RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { + perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "ServiceREST.deletePolicyByGUIDAndServiceNameAndZoneName(policyGUID=" + guid + ", serviceName=" + serviceName + ", zoneName=" + zoneName + ")"); + } + + ret = getPolicyByGUIDAndServiceNameAndZoneName(guid, serviceName, zoneName); + + if (ret != null) { + deletePolicy(ret.getId()); + } + } catch (WebApplicationException excp) { + throw excp; + } catch (Throwable excp) { + LOG.error("deletePolicyByGUIDAndServiceNameAndZoneName({}, {}, {}) failed", guid, serviceName, zoneName, excp); + + throw restErrorUtil.createRESTException(excp.getMessage()); + } finally { + RangerPerfTracer.log(perf); + } + + LOG.debug("<== ServiceREST.deletePolicyByGUIDAndServiceNameAndZoneName({}, {}, {}) : {}", guid, serviceName, zoneName, ret); + } + + @DELETE + @Path("/server/purge/records") + @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") + public List purgeRecords(@QueryParam("type") String recordType, @DefaultValue("180") @QueryParam("retentionDays") Integer olderThan, @Context HttpServletRequest request) { + LOG.debug("==> ServiceREST.purgeRecords({}, {})", recordType, olderThan); + + List ret = new ArrayList<>(); + RangerPerfTracer perf = null; + + try { + if (RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { + perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "ServiceREST.purgeRecords(recordType=" + recordType + ", olderThan=" + olderThan + ")"); + } + + if (olderThan < 1) { + throw restErrorUtil.createRESTException(HttpServletResponse.SC_BAD_REQUEST, "Retention days can't be lesser than 1", true); + } + + if (PURGE_RECORD_TYPE_LOGIN_LOGS.equalsIgnoreCase(recordType)) { + svcStore.removeAuthSessions(olderThan, ret); + } else if (PURGE_RECORD_TYPE_TRX_LOGS.equalsIgnoreCase(recordType)) { + svcStore.removeTransactionLogs(olderThan, ret); + } else if (PURGE_RECORD_TYPE_POLICY_EXPORT_LOGS.equalsIgnoreCase(recordType)) { + svcStore.removePolicyExportLogs(olderThan, ret); + } else { + throw restErrorUtil.createRESTException(HttpServletResponse.SC_BAD_REQUEST, recordType + ": invalid record type. Valid values: [ " + PURGE_RECORD_TYPE_LOGIN_LOGS + ", " + PURGE_RECORD_TYPE_TRX_LOGS + ", " + PURGE_RECORD_TYPE_POLICY_EXPORT_LOGS + " ]", true); + } + } catch (WebApplicationException excp) { + throw excp; + } catch (Throwable excp) { + LOG.error("purgeRecords({}, {}) failed", recordType, olderThan, excp); + + throw restErrorUtil.createRESTException(excp.getMessage()); + } finally { + RangerPerfTracer.log(perf); + } + + LOG.debug("<== ServiceREST.purgeRecords({}, {}) : {}", recordType, olderThan, ret); + + return ret; + } + + public RangerPolicyResource getPolicyResource(Object resourceName, GrantRevokeRequest grantRequest) { + RangerPolicyResource ret; + + if (resourceName instanceof List) { + List resourceValues = (List) resourceName; + + ret = new RangerPolicyResource(resourceValues, false, grantRequest.getIsRecursive()); + } else { + ret = new RangerPolicyResource((String) resourceName); + + ret.setIsRecursive(grantRequest.getIsRecursive()); + } + + return ret; + } + + /** + * Returns {@link RangerPolicy} for non-empty serviceName, policyName and zoneName null otherwise. + * + * @param serviceName + * @param policyName + * @param zoneName + * @return + */ + public RangerPolicy getPolicyByName(String serviceName, String policyName, String zoneName) { + LOG.debug("==> ServiceREST.getPolicyByName({}, {}, {})", serviceName, policyName, zoneName); + + RangerPolicy ret = null; + + if (StringUtils.isNotBlank(serviceName) && StringUtils.isNotBlank(policyName)) { + XXPolicy dbPolicy = daoManager.getXXPolicy().findPolicy(policyName, serviceName, zoneName); + + if (dbPolicy != null) { + ret = policyService.getPopulatedViewObject(dbPolicy); + } + + if (ret != null) { + ensureAdminAndAuditAccess(ret); + } + } + + LOG.debug("<== ServiceREST.getPolicyByName({}, {}, {}) : {}", serviceName, policyName, zoneName, (ret != null ? ret : "ret is null")); + + return ret; + } + + void ensureAdminAccess(RangerPolicy policy) { + blockIfGdsService(policy.getService()); + + boolean isAdmin = bizUtil.isAdmin(); + boolean isKeyAdmin = bizUtil.isKeyAdmin(); + String userName = bizUtil.getCurrentUserLoginId(); + boolean isSvcAdmin = isAdmin || svcStore.isServiceAdminUser(policy.getService(), userName); + + if (!isAdmin && !isKeyAdmin && !isSvcAdmin) { + Set userGroups = userMgr.getGroupsForUser(userName); + boolean isAllowed; + + //for zone policy create /update / delete + if (!StringUtils.isEmpty(policy.getZoneName()) && serviceMgr.isZoneAdmin(policy.getZoneName())) { + isAllowed = true; + } else { + isAllowed = hasAdminAccess(policy, userName, userGroups); + } + + if (!isAllowed) { + throw restErrorUtil.createRESTException(HttpServletResponse.SC_FORBIDDEN, "User '" + userName + "' does not have delegated-admin privilege on given resources", true); + } + } else { + XXService xService = daoManager.getXXService().findByName(policy.getService()); + XXServiceDef xServiceDef = daoManager.getXXServiceDef().getById(xService.getType()); + + if (isAdmin) { + if (EmbeddedServiceDefsUtil.KMS_IMPL_CLASS_NAME.equals(xServiceDef.getImplclassname())) { + throw restErrorUtil.createRESTException("KMS Policies/Services/Service-Defs are not accessible for user '" + userName + "'.", MessageEnums.OPER_NO_PERMISSION); + } + } else if (isKeyAdmin) { + if (!EmbeddedServiceDefsUtil.KMS_IMPL_CLASS_NAME.equals(xServiceDef.getImplclassname())) { + throw restErrorUtil.createRESTException("Only KMS Policies/Services/Service-Defs are accessible for user '" + userName + "'.", MessageEnums.OPER_NO_PERMISSION); + } + } + } + } + + void ensureAdminAndAuditAccess(RangerPolicy policy) { + ensureAdminAndAuditAccess(policy, new HashMap<>()); + } + + void ensureAdminAndAuditAccess(RangerPolicy policy, Map mapServiceTypeAndImplClass) { + boolean isAdmin = bizUtil.isAdmin(); + boolean isKeyAdmin = bizUtil.isKeyAdmin(); + String userName = bizUtil.getCurrentUserLoginId(); + boolean isAuditAdmin = bizUtil.isAuditAdmin(); + boolean isAuditKeyAdmin = bizUtil.isAuditKeyAdmin(); + boolean isSvcAdmin = isAdmin || svcStore.isServiceAdminUser(policy.getService(), userName) || (!StringUtils.isEmpty(policy.getZoneName()) && (serviceMgr.isZoneAdmin(policy.getZoneName()) || serviceMgr.isZoneAuditor(policy.getZoneName()))); + + if (!isAdmin && !isKeyAdmin && !isSvcAdmin && !isAuditAdmin && !isAuditKeyAdmin) { + boolean isAllowed = false; + Set userGroups = userMgr.getGroupsForUser(userName); + RangerPolicyAdmin policyAdmin = getPolicyAdminForDelegatedAdmin(policy.getService()); + + if (policyAdmin != null) { + Map evalContext = new HashMap<>(); + + RangerAccessRequestUtil.setCurrentUserInContext(evalContext, userName); + + Set roles = policyAdmin.getRolesFromUserAndGroups(userName, userGroups); + + isAllowed = policyAdmin.isDelegatedAdminAccessAllowedForRead(policy, userName, userGroups, roles, evalContext); + } + + if (!isAllowed) { + throw restErrorUtil.createRESTException(HttpServletResponse.SC_FORBIDDEN, "User '" + userName + "' does not have delegated-admin privilege on given resources", true); + } + } else { + if (StringUtils.isBlank(policy.getServiceType())) { + XXService xService = daoManager.getXXService().findByName(policy.getService()); + XXServiceDef xServiceDef = daoManager.getXXServiceDef().getById(xService.getType()); + + mapServiceTypeAndImplClass.put(xServiceDef.getName(), xServiceDef.getImplclassname()); + policy.setServiceType(xServiceDef.getName()); + } else if (!mapServiceTypeAndImplClass.containsKey(policy.getServiceType())) { + XXService xService = daoManager.getXXService().findByName(policy.getService()); + XXServiceDef xServiceDef = daoManager.getXXServiceDef().getById(xService.getType()); + + mapServiceTypeAndImplClass.put(xServiceDef.getName(), xServiceDef.getImplclassname()); + } + + String serviceDefImplClass = mapServiceTypeAndImplClass.get(policy.getServiceType()); + + if (isAdmin || isAuditAdmin) { + if (EmbeddedServiceDefsUtil.KMS_IMPL_CLASS_NAME.equals(serviceDefImplClass)) { + throw restErrorUtil.createRESTException("KMS Policies/Services/Service-Defs are not accessible for user '" + userName + "'.", MessageEnums.OPER_NO_PERMISSION); + } + } else if (isKeyAdmin || isAuditKeyAdmin) { + if (!EmbeddedServiceDefsUtil.KMS_IMPL_CLASS_NAME.equals(serviceDefImplClass)) { + throw restErrorUtil.createRESTException("Only KMS Policies/Services/Service-Defs are accessible for user '" + userName + "'.", MessageEnums.OPER_NO_PERMISSION); + } + } + } + } + + boolean isServiceAdmin(String serviceName) { + boolean ret = bizUtil.isAdmin(); + + if (!ret && StringUtils.isNotEmpty(serviceName)) { + ret = svcStore.isServiceAdminUser(serviceName, bizUtil.getCurrentUserLoginId()); + } + + return ret; + } + + private String validateResourcePoliciesRequest(String serviceDefName, String serviceName, HttpServletRequest request, List services, Map resource) { + LOG.debug("==> ServiceREST.validatePoliciesForResourceRequest(service-type={}, service-name={})", serviceDefName, serviceName); + + final String ret; + + if (MapUtils.isNotEmpty(request.getParameterMap())) { + for (Entry e : request.getParameterMap().entrySet()) { + String name = e.getKey(); + String[] values = e.getValue(); + + if (!StringUtils.isEmpty(name) && !ArrayUtils.isEmpty(values) && name.startsWith(SearchFilter.RESOURCE_PREFIX)) { + resource.put(name.substring(SearchFilter.RESOURCE_PREFIX.length()), values[0]); + } + } + } + + if (MapUtils.isEmpty(resource)) { + ret = "No resource specified"; + } else { + RangerServiceDef serviceDef = null; + + try { + serviceDef = svcStore.getServiceDefByName(serviceDefName); + } catch (Exception e) { + LOG.error("Invalid service-type:[{}]", serviceDefName, e); + } + + if (serviceDef == null) { + ret = "Invalid service-type:[" + serviceDefName + "]"; + } else { + Set resourceDefNames = resource.keySet(); + RangerServiceDefHelper serviceDefHelper = new RangerServiceDefHelper(serviceDef); + Set> resourceHierarchies = serviceDefHelper.getResourceHierarchies(RangerPolicy.POLICY_TYPE_ACCESS, resourceDefNames); + + if (CollectionUtils.isEmpty(resourceHierarchies)) { + ret = "Invalid resource specified: resource-names:" + resourceDefNames + " are not part of any valid resource hierarchy for service-type:[" + serviceDefName + "]"; + } else { + if (StringUtils.isNotBlank(serviceName)) { + RangerService service = null; + + try { + service = svcStore.getServiceByName(serviceName); + } catch (Exception e) { + LOG.error("Invalid service-name:[{}]", serviceName); + } + + if (service == null || !StringUtils.equals(service.getType(), serviceDefName)) { + ret = "Invalid service-name:[" + serviceName + "] or service-type:[" + serviceDefName + "]"; + } else { + services.add(service); + ret = StringUtils.EMPTY; + } + } else { + SearchFilter filter = new SearchFilter(); + + filter.setParam(SearchFilter.SERVICE_TYPE, serviceDefName); + + List serviceList = null; + + try { + serviceList = svcStore.getServices(filter); + } catch (Exception e) { + LOG.error("Cannot find service of service-type:[{}]", serviceDefName); + } + + if (CollectionUtils.isEmpty(serviceList) || serviceList.size() != 1) { + ret = "Either 0 or more than 1 services found for service-type :[" + serviceDefName + "]"; + } else { + services.add(serviceList.get(0)); + + ret = StringUtils.EMPTY; + } + } + } + } + } + + LOG.debug("<== ServiceREST.validatePoliciesForResourceRequest(service-type={}, service-name={}) : {}", serviceDefName, serviceName, ret); + + return ret; + } + + private void requestParamsValidation(SearchFilter filter) { + boolean fetchAllZonePolicies = Boolean.parseBoolean(filter.getParam(SearchFilter.FETCH_ZONE_UNZONE_POLICIES)); + String zoneName = filter.getParam(SearchFilter.ZONE_NAME); + + if (fetchAllZonePolicies && StringUtils.isNotEmpty(zoneName)) { + throw restErrorUtil.createRESTException("Invalid parameter: " + SearchFilter.ZONE_NAME + " can not be provided, along with " + SearchFilter.FETCH_ZONE_UNZONE_POLICIES + "=true"); + } + } + + private int createPolicesBasedOnPolicyMap(HttpServletRequest request, Map policiesMap, List serviceNameList, boolean updateIfExists, int totalPolicyCreate) { + boolean mergeIfExists = "true".equalsIgnoreCase(StringUtils.trimToEmpty(request.getParameter(PARAM_MERGE_IF_EXISTS))); + boolean deleteIfExists = "true".equalsIgnoreCase(StringUtils.trimToEmpty(request.getParameter(PARAM_DELETE_IF_EXISTS))); + + if (!CollectionUtils.sizeIsEmpty(policiesMap.entrySet())) { + for (Entry entry : policiesMap.entrySet()) { + RangerPolicy policy = entry.getValue(); + + if (policy != null) { + if (!CollectionUtils.isEmpty(serviceNameList)) { + for (String service : serviceNameList) { + if (StringUtils.isNotEmpty(service.trim()) && StringUtils.isNotEmpty(policy.getService().trim())) { + if (policy.getService().trim().equalsIgnoreCase(service.trim())) { + if (updateIfExists || mergeIfExists || deleteIfExists) { + request.setAttribute(PARAM_SERVICE_NAME, policy.getService()); + request.setAttribute(PARAM_POLICY_NAME, policy.getName()); + request.setAttribute(PARAM_ZONE_NAME, policy.getZoneName()); + + if (mergeIfExists && !ServiceRESTUtil.containsRangerCondition(policy)) { + String user = request.getRemoteUser(); + RangerPolicy existingPolicy; + + try { + existingPolicy = getExactMatchPolicyForResource(policy, StringUtils.isNotBlank(user) ? user : "admin"); + } catch (Exception e) { + existingPolicy = null; + } + + if (existingPolicy == null) { + createPolicy(policy, request); + } else { + ServiceRESTUtil.mergeExactMatchPolicyForResource(existingPolicy, policy); + + updatePolicy(existingPolicy, null); + } + } else { + createPolicy(policy, request); + } + } else { + createPolicy(policy, request); + } + + totalPolicyCreate = totalPolicyCreate + 1; + + LOG.debug("Policy {} created successfully.", policy.getName()); + + break; + } + } else { + LOG.error("Service Name or Policy Name is not provided!!"); + + throw restErrorUtil.createRESTException("Service Name or Policy Name is not provided!!"); + } + } + } else { + if (updateIfExists || mergeIfExists || deleteIfExists) { + request.setAttribute(PARAM_SERVICE_NAME, policy.getService()); + request.setAttribute(PARAM_POLICY_NAME, policy.getName()); + request.setAttribute(PARAM_ZONE_NAME, policy.getZoneName()); + + if (mergeIfExists && !ServiceRESTUtil.containsRangerCondition(policy)) { + String user = request.getRemoteUser(); + RangerPolicy existingPolicy; + + try { + existingPolicy = getExactMatchPolicyForResource(policy, StringUtils.isNotBlank(user) ? user : "admin"); + } catch (Exception e) { + existingPolicy = null; + } + + if (existingPolicy == null) { + createPolicy(policy, request); + } else { + ServiceRESTUtil.mergeExactMatchPolicyForResource(existingPolicy, policy); + + updatePolicy(existingPolicy, null); + } + } else { + createPolicy(policy, request); + } + } else { + createPolicy(policy, request); + } + + totalPolicyCreate = totalPolicyCreate + 1; + + LOG.debug("Policy {} created successfully.", policy.getName()); + } + } + + if (totalPolicyCreate % RangerBizUtil.POLICY_BATCH_SIZE == 0) { + bizUtil.bulkModeOnlyFlushAndClear(); + } + } + + bizUtil.bulkModeOnlyFlushAndClear(); + + LOG.debug("Total Policy Created From Json file : {}", totalPolicyCreate); + } + + return totalPolicyCreate; + } + + private List getPoliciesFromProvidedJson(RangerExportPolicyList rangerExportPolicyList) { + List policies; + + if (rangerExportPolicyList != null && !CollectionUtils.sizeIsEmpty(rangerExportPolicyList.getPolicies())) { + policies = rangerExportPolicyList.getPolicies(); + } else { + LOG.error("Provided json file does not contain any policy!!"); + + throw restErrorUtil.createRESTException("Provided json file does not contain any policy!!"); + } + + return policies; + } + + private RangerExportPolicyList processPolicyInputJsonForMetaData(InputStream uploadedInputStream, RangerExportPolicyList rangerExportPolicyList) throws Exception { + String policiesString = IOUtils.toString(uploadedInputStream).trim(); + + if (StringUtils.isNotEmpty(policiesString)) { + rangerExportPolicyList = JsonUtilsV2.jsonToObj(policiesString, RangerExportPolicyList.class); + } else { + LOG.error("Provided json file is empty!!"); + + throw restErrorUtil.createRESTException("Provided json file is empty!!"); + } + + return rangerExportPolicyList; + } + + private void getServiceNameList(HttpServletRequest request, List serviceNameList) { + SearchFilter filter = searchUtil.getSearchFilter(request, policyService.sortFields); + String serviceType = null; + List serviceTypeList = null; + + if (StringUtils.isNotEmpty(request.getParameter(PARAM_SERVICE_TYPE))) { + serviceType = request.getParameter(PARAM_SERVICE_TYPE); + } + + if (StringUtils.isNotEmpty(serviceType)) { + serviceTypeList = new ArrayList<>(Arrays.asList(serviceType.split(","))); + } + + List rangerServiceList; + List rangerServiceLists = new ArrayList<>(); + + if (CollectionUtils.isNotEmpty(serviceTypeList)) { + for (String s : serviceTypeList) { + filter.removeParam(PARAM_SERVICE_TYPE); + filter.setParam(PARAM_SERVICE_TYPE, s.trim()); + + rangerServiceList = getServices(filter); + + rangerServiceLists.addAll(rangerServiceList); + } + } + + if (!CollectionUtils.sizeIsEmpty(rangerServiceLists)) { + for (RangerService rService : rangerServiceLists) { + if (StringUtils.isNotEmpty(rService.getName())) { + serviceNameList.add(rService.getName()); + } + } + } + } + + private boolean validateDestZoneServiceMapping(String destinationZoneName, RangerPolicy policyInJson, Map servicesMappingMap) { + boolean isZoneServiceExistAtDestination = false; + XXSecurityZone xdestZone = daoManager.getXXSecurityZoneDao().findByZoneName(destinationZoneName); + + if (xdestZone == null) { + LOG.error("destination zone provided does not exist"); + throw restErrorUtil.createRESTException("destination zone provided does not exist"); + } + + // CHECK IF json policies service is there on destination and asscioated with + // destination zone. + + String serviceNameToCheck = policyInJson.getService(); + + if (StringUtils.isNotBlank(serviceNameToCheck) && servicesMappingMap.containsKey(serviceNameToCheck)) { + serviceNameToCheck = servicesMappingMap.get(policyInJson.getService()); + } + + List serviceZoneMapping = daoManager.getXXSecurityZoneRefService().findByServiceNameAndZoneId(serviceNameToCheck, xdestZone.getId()); + List tagServiceZoneMapping = daoManager.getXXSecurityZoneRefTagService().findByTagServiceNameAndZoneId(serviceNameToCheck, xdestZone.getId()); + + if (!CollectionUtils.isEmpty(serviceZoneMapping) || !CollectionUtils.isEmpty(tagServiceZoneMapping)) { + isZoneServiceExistAtDestination = true; + } + + return isZoneServiceExistAtDestination; + } + + private String getDestinationZoneName(List destinationZones, String zoneNameInJson) { + String destinationZoneName; + + if (CollectionUtils.isNotEmpty(destinationZones)) { + destinationZoneName = destinationZones.get(0); + } else { + destinationZoneName = zoneNameInJson; + } + + return destinationZoneName; + } + + private void processServiceMapping(Map servicesMappingMap, List sourceServices, List destinationServices) { + if (!CollectionUtils.sizeIsEmpty(servicesMappingMap)) { + for (Entry map : servicesMappingMap.entrySet()) { + String sourceServiceName; + String destinationServiceName; + + if (StringUtils.isNotEmpty(map.getKey().trim()) && StringUtils.isNotEmpty(map.getValue().trim())) { + sourceServiceName = map.getKey().trim(); + destinationServiceName = map.getValue().trim(); + } else { + LOG.error("Source service or destination service name is not provided!!"); + + throw restErrorUtil.createRESTException("Source service or destonation service name is not provided!!"); + } + + if (StringUtils.isNotEmpty(sourceServiceName) && StringUtils.isNotEmpty(destinationServiceName)) { + sourceServices.add(sourceServiceName); + destinationServices.add(destinationServiceName); + } + } + } + } + + private void processZoneMapping(Map zoneMappingMap, List sourceZones, List destinationZones) { + if (!CollectionUtils.sizeIsEmpty(zoneMappingMap)) { + for (Entry map : zoneMappingMap.entrySet()) { + String sourceZoneName = null; + String destinationZoneName = null; + + if (StringUtils.isNotEmpty(map.getKey().trim()) || StringUtils.isNotEmpty(map.getValue().trim())) { + // zone to zone + // zone to unzone + // unzone to zone + sourceZoneName = map.getKey().trim(); + destinationZoneName = map.getValue().trim(); + + LOG.info("sourceZoneName = {} destinationZoneName = {}", sourceZoneName, destinationZoneName); + } else if (StringUtils.isEmpty(map.getKey().trim()) && StringUtils.isEmpty(map.getValue().trim())) { + LOG.info("Unzone to unzone policies import"); + } else { + LOG.error("Source zone or destination zone name is not provided!!"); + + throw restErrorUtil.createRESTException("Source zone or destination zone name is not provided!!"); + } + + if (StringUtils.isNotEmpty(sourceZoneName) || StringUtils.isNotEmpty(destinationZoneName)) { + sourceZones.add(sourceZoneName); + destinationZones.add(destinationZoneName); + } + } + } + } + + private List getAllFilteredPolicyList(SearchFilter filter, HttpServletRequest request, List policyLists) { + String serviceNames = null; + String serviceType = null; + List serviceNameList = null; + List serviceTypeList = null; + List serviceNameInServiceTypeList = new ArrayList<>(); + boolean isServiceExists; + + if (request.getParameter(PARAM_SERVICE_NAME) != null) { + serviceNames = request.getParameter(PARAM_SERVICE_NAME); + } + + if (StringUtils.isNotEmpty(serviceNames)) { + serviceNameList = new ArrayList<>(Arrays.asList(serviceNames.split(","))); + } + + if (request.getParameter(PARAM_SERVICE_TYPE) != null) { + serviceType = request.getParameter(PARAM_SERVICE_TYPE); + } + + if (StringUtils.isNotEmpty(serviceType)) { + serviceTypeList = new ArrayList<>(Arrays.asList(serviceType.split(","))); + } + + List policyList; + List policyListByServiceName = new ArrayList<>(); + + if (filter != null) { + filter.setStartIndex(0); + filter.setMaxRows(Integer.MAX_VALUE); + + if (!CollectionUtils.isEmpty(serviceTypeList)) { + for (String s : serviceTypeList) { + filter.removeParam(PARAM_SERVICE_TYPE); + + if (request.getParameter(PARAM_SERVICE_NAME) != null) { + filter.removeParam(PARAM_SERVICE_NAME); + } + + filter.setParam(PARAM_SERVICE_TYPE, s.trim()); + + policyList = getPolicies(filter); + + policyLists.addAll(policyList); + } + if (!CollectionUtils.sizeIsEmpty(policyLists)) { + for (RangerPolicy rangerPolicy : policyLists) { + if (StringUtils.isNotEmpty(rangerPolicy.getService())) { + serviceNameInServiceTypeList.add(rangerPolicy.getService()); + } + } + } + } + if (!CollectionUtils.isEmpty(serviceNameList) && !CollectionUtils.isEmpty(serviceTypeList)) { + isServiceExists = serviceNameInServiceTypeList.containsAll(serviceNameList); + + if (isServiceExists) { + for (String s : serviceNameList) { + filter.removeParam(PARAM_SERVICE_NAME); + filter.removeParam(PARAM_SERVICE_TYPE); + filter.setParam(PARAM_SERVICE_NAME, s.trim()); + + policyList = getPolicies(filter); + + policyListByServiceName.addAll(policyList); + } + + policyLists = policyListByServiceName; + } else { + policyLists = new ArrayList<>(); + } + } else if (CollectionUtils.isEmpty(serviceNameList) && CollectionUtils.isEmpty(serviceTypeList)) { + policyLists = getPolicies(filter); + } + if (!CollectionUtils.isEmpty(serviceNameList) && CollectionUtils.isEmpty(serviceTypeList)) { + for (String s : serviceNameList) { + filter.removeParam(PARAM_SERVICE_NAME); + filter.setParam(PARAM_SERVICE_NAME, s.trim()); + + policyList = getPolicies(filter); + + policyLists.addAll(policyList); + } + } + } + + if (StringUtils.isNotEmpty(request.getParameter("resourceMatch")) && "full".equalsIgnoreCase(request.getParameter("resourceMatch"))) { + policyLists = serviceUtil.getMatchingPoliciesForResource(request, policyLists); + } + + Map orderedPolicies = new TreeMap<>(); + + if (!CollectionUtils.isEmpty(policyLists)) { + for (RangerPolicy policy : policyLists) { + if (policy != null) { + //set createTime & updateTime Time as null since exported policies dont need this + policy.setCreateTime(null); + policy.setUpdateTime(null); + + orderedPolicies.put(policy.getId(), policy); + } + } + if (!orderedPolicies.isEmpty()) { + policyLists.clear(); + + policyLists.addAll(orderedPolicies.values()); + } + } + + return policyLists; + } + + private void deletePoliciesProvidedInServiceMap(List sourceServices, List destinationServices, String zoneName) throws Exception { + int totalDeletedPolicies = 0; + + if (CollectionUtils.isNotEmpty(sourceServices) && CollectionUtils.isNotEmpty(destinationServices)) { + RangerPolicyValidator validator = validatorFactory.getPolicyValidator(svcStore); + + for (int i = 0; i < sourceServices.size(); i++) { + if (!destinationServices.get(i).isEmpty()) { + SearchFilter filter = new SearchFilter(); + + filter.setParam(SearchFilter.ZONE_NAME, zoneName); + filter.setParam(SearchFilter.SERVICE_NAME, destinationServices.get(i)); + + RangerService service = getServiceByName(destinationServices.get(i)); + final RangerPolicyList servicePolicies = getServicePolicies(destinationServices.get(i), filter); + + if (servicePolicies != null) { + List rangerPolicyList = servicePolicies.getPolicies(); + + if (CollectionUtils.isNotEmpty(rangerPolicyList)) { + for (RangerPolicy rangerPolicy : rangerPolicyList) { + if (rangerPolicy != null) { + validator.validate(rangerPolicy.getId(), Action.DELETE); + + ensureAdminAccess(rangerPolicy); + + bizUtil.blockAuditorRoleUser(); + svcStore.deletePolicy(rangerPolicy, service); + + totalDeletedPolicies = totalDeletedPolicies + 1; + + if (totalDeletedPolicies % RangerBizUtil.POLICY_BATCH_SIZE == 0) { + bizUtil.bulkModeOnlyFlushAndClear(); + } + + LOG.debug("Policy {} deleted successfully.", rangerPolicy.getName()); + LOG.debug("TotalDeletedPolicies: {}", totalDeletedPolicies); + } + } + + bizUtil.bulkModeOnlyFlushAndClear(); + } + } + } + } + } + + LOG.debug("Total Deleted Policy : {}", totalDeletedPolicies); + } + + private void deletePoliciesForResource(List sourceServices, List destinationServices, HttpServletRequest request, List exportPolicies, String zoneName) throws Exception { + int totalDeletedPolicies = 0; + if (CollectionUtils.isNotEmpty(sourceServices) && CollectionUtils.isNotEmpty(destinationServices)) { + Set exportedPolicyNames = new HashSet<>(); + + if (CollectionUtils.isNotEmpty(exportPolicies)) { + for (RangerPolicy rangerPolicy : exportPolicies) { + if (rangerPolicy != null) { + exportedPolicyNames.add(rangerPolicy.getName()); + } + } + } + + for (int i = 0; i < sourceServices.size(); i++) { + if (!destinationServices.get(i).isEmpty()) { + SearchFilter filter = searchUtil.getSearchFilter(request, policyService.sortFields); + + filter.setParam("zoneName", zoneName); + + RangerPolicyList servicePolicies = getServicePolicies(destinationServices.get(i), filter); + RangerService service = getServiceByName(destinationServices.get(i)); + + if (servicePolicies != null) { + List rangerPolicyList = servicePolicies.getPolicies(); + + if (CollectionUtils.isNotEmpty(rangerPolicyList)) { + List policiesToBeDeleted = new ArrayList<>(); + + for (RangerPolicy rangerPolicy : rangerPolicyList) { + if (rangerPolicy != null) { + Map rangerPolicyResourceMap = rangerPolicy.getResources(); + + if (rangerPolicyResourceMap != null) { + RangerPolicyResource rangerPolicyResource = null; + + if (rangerPolicyResourceMap.containsKey("path")) { + rangerPolicyResource = rangerPolicyResourceMap.get("path"); + } else if (rangerPolicyResourceMap.containsKey("database")) { + rangerPolicyResource = rangerPolicyResourceMap.get("database"); + } + + if (rangerPolicyResource != null) { + if (CollectionUtils.isNotEmpty(rangerPolicyResource.getValues()) && rangerPolicyResource.getValues().size() > 1) { + continue; + } + } + } + + if (rangerPolicy.getId() != null) { + if (!exportedPolicyNames.contains(rangerPolicy.getName())) { + policiesToBeDeleted.add(rangerPolicy); + } + } + } + } + + if (CollectionUtils.isNotEmpty(policiesToBeDeleted)) { + for (RangerPolicy rangerPolicy : policiesToBeDeleted) { + svcStore.deletePolicy(rangerPolicy, service); + + LOG.debug("Policy {} deleted successfully.", rangerPolicy.getName()); + + totalDeletedPolicies = totalDeletedPolicies + 1; + + if (totalDeletedPolicies % RangerBizUtil.POLICY_BATCH_SIZE == 0) { + bizUtil.bulkModeOnlyFlushAndClear(); + } + } + + bizUtil.bulkModeOnlyFlushAndClear(); + } + } + } + } + } + } + } + + private RangerPolicyList getServicePolicies(String serviceName, SearchFilter filter) { + RangerPerfTracer perf = null; + + try { + if (RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { + perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "ServiceREST.getServicePolicies(serviceName=" + serviceName + ")"); + } + + // get all policies from the store; pick the page to return after applying filter + int savedStartIndex = filter == null ? 0 : filter.getStartIndex(); + int savedMaxRows = filter == null ? Integer.MAX_VALUE : filter.getMaxRows(); + + if (filter != null) { + filter.setStartIndex(0); + filter.setMaxRows(Integer.MAX_VALUE); + } + + List servicePolicies = svcStore.getServicePolicies(serviceName, filter); + + if (filter != null) { + filter.setStartIndex(savedStartIndex); + filter.setMaxRows(savedMaxRows); + } + + servicePolicies = applyAdminAccessFilter(servicePolicies); + + return toRangerPolicyList(servicePolicies, filter); + } catch (WebApplicationException excp) { + throw excp; + } catch (Throwable excp) { + LOG.error("getServicePolicies({}) failed", serviceName, excp); + + throw restErrorUtil.createRESTException(excp.getMessage()); + } finally { + RangerPerfTracer.log(perf); + } + } + + private void createPolicyDownloadAudit(String serviceName, Long lastKnownVersion, String pluginId, int httpRespCode, String clusterName, String zoneName, HttpServletRequest request) { + try { + String ipAddress = request.getHeader("X-FORWARDED-FOR"); + + if (ipAddress == null) { + ipAddress = request.getRemoteAddr(); + } + + XXPolicyExportAudit policyExportAudit = new XXPolicyExportAudit(); + + policyExportAudit.setRepositoryName(serviceName); + policyExportAudit.setAgentId(pluginId); + policyExportAudit.setClientIP(ipAddress); + policyExportAudit.setRequestedEpoch(lastKnownVersion); + policyExportAudit.setHttpRetCode(httpRespCode); + policyExportAudit.setClusterName(clusterName); + policyExportAudit.setZoneName(zoneName); + + assetMgr.createPolicyAudit(policyExportAudit); + } catch (Exception excp) { + LOG.error("error while creating policy download audit", excp); + } + } + + private RangerPolicy getExactMatchPolicyForResource(String serviceName, RangerAccessResource resource, String zoneName, String user) throws Exception { + LOG.debug("==> ServiceREST.getExactMatchPolicyForResource({}, {}, {})", resource, zoneName, user); + + RangerPolicy ret = null; + RangerPolicyAdmin policyAdmin = getPolicyAdmin(serviceName); + List policies = policyAdmin != null ? policyAdmin.getExactMatchPolicies(resource, zoneName, null) : null; + + if (CollectionUtils.isNotEmpty(policies)) { + // at this point, ret is a policy in policy-engine; the caller might update the policy (for grant/revoke); so get a copy from the store + ret = svcStore.getPolicy(policies.get(0).getId()); + } + + LOG.debug("<== ServiceREST.getExactMatchPolicyForResource({}, {}, {}): {}", resource, zoneName, user, ret); + + return ret; + } + + private RangerPolicy getExactMatchPolicyForResource(RangerPolicy policy, String user) throws Exception { + LOG.debug("==> ServiceREST.getExactMatchPolicyForResource({}, {})", policy, user); + + RangerPolicy ret = null; + RangerPolicyAdmin policyAdmin = getPolicyAdmin(policy.getService()); + List policies = policyAdmin != null ? policyAdmin.getExactMatchPolicies(policy, null) : null; + + if (CollectionUtils.isNotEmpty(policies)) { + // at this point, ret is a policy in policy-engine; the caller might update the policy (for grant/revoke); so get a copy from the store + if (policies.size() == 1) { + ret = svcStore.getPolicy(policies.get(0).getId()); + } else { + if (StringUtils.isNotEmpty(policy.getZoneName())) { + for (RangerPolicy existingPolicy : policies) { + if (StringUtils.equals(policy.getZoneName(), existingPolicy.getZoneName())) { + ret = svcStore.getPolicy(existingPolicy.getId()); + break; + } + } + } + } + } + + LOG.debug("<== ServiceREST.getExactMatchPolicyForResource({}, {}): {}", policy, user, ret); + + return ret; + } + + private List applyAdminAccessFilter(List policies) { + List ret = new ArrayList<>(); + RangerPerfTracer perf = null; + + if (RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { + perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "ServiceREST.applyAdminAccessFilter(policyCount=" + (policies == null ? 0 : policies.size()) + ")"); + } + + if (CollectionUtils.isNotEmpty(policies)) { + boolean isAdmin = bizUtil.isAdmin(); + boolean isKeyAdmin = bizUtil.isKeyAdmin(); + String userName = bizUtil.getCurrentUserLoginId(); + boolean isAuditAdmin = bizUtil.isAuditAdmin(); + boolean isAuditKeyAdmin = bizUtil.isAuditKeyAdmin(); + Set userGroups = null; + + Map> servicePoliciesMap = new HashMap<>(); + Map evalContext = new HashMap<>(); + + RangerAccessRequestUtil.setCurrentUserInContext(evalContext, userName); + + for (RangerPolicy policy : policies) { + String serviceName = policy.getService(); + List policyList = servicePoliciesMap.computeIfAbsent(serviceName, k -> new ArrayList<>()); + + policyList.add(policy); + } + + for (Entry> entry : servicePoliciesMap.entrySet()) { + String serviceName = entry.getKey(); + List listToFilter = entry.getValue(); + + if (CollectionUtils.isNotEmpty(listToFilter)) { + boolean isServiceAdminUser = svcStore.isServiceAdminUser(serviceName, userName); + + if (isServiceAdminUser) { + ret.addAll(listToFilter); + continue; + } else if (isAdmin || isKeyAdmin || isAuditAdmin || isAuditKeyAdmin) { + XXService xService = daoManager.getXXService().findByName(serviceName); + Long serviceDefId = xService.getType(); + boolean isKmsService = serviceDefId.equals(EmbeddedServiceDefsUtil.instance().getKmsServiceDefId()); + + if (isAdmin) { + if (!isKmsService) { + ret.addAll(listToFilter); + } + } else if (isAuditAdmin) { + if (!isKmsService) { + ret.addAll(listToFilter); + } + } else if (isAuditKeyAdmin) { + if (isKmsService) { + ret.addAll(listToFilter); + } + } else if (isKeyAdmin) { + if (isKmsService) { + ret.addAll(listToFilter); + } + } + + continue; + } + + RangerPolicyAdmin policyAdmin = getPolicyAdminForDelegatedAdmin(serviceName); + + if (policyAdmin != null) { + if (userGroups == null) { + userGroups = daoManager.getXXGroupUser().findGroupNamesByUserName(userName); + } + + Set roles = policyAdmin.getRolesFromUserAndGroups(userName, userGroups); + + for (RangerPolicy policy : listToFilter) { + if ((policyAdmin.isDelegatedAdminAccessAllowedForRead(policy, userName, userGroups, roles, evalContext)) || (!StringUtils.isEmpty(policy.getZoneName()) && (serviceMgr.isZoneAdmin(policy.getZoneName()) || serviceMgr.isZoneAuditor(policy.getZoneName())))) { + ret.add(policy); + } + } + } + } + } + } + + RangerPerfTracer.log(perf); + + return ret; + } + + private RangerPolicyEngineOptions getDelegatedAdminPolicyEngineOptions() { + RangerPolicyEngineOptions opts = new RangerPolicyEngineOptions(); + + final String propertyPrefix = "ranger.admin"; + + opts.configureDelegateAdmin(config, propertyPrefix); + + return opts; + } + + private RangerPolicyEngineOptions getPolicySearchRangerAdminPolicyEngineOptions() { + RangerPolicyEngineOptions opts = new RangerPolicyEngineOptions(); + + final String propertyPrefix = "ranger.admin"; + + opts.configureRangerAdminForPolicySearch(config, propertyPrefix); + + return opts; + } + + private RangerPolicyEngineOptions getDefaultRangerAdminPolicyEngineOptions() { + RangerPolicyEngineOptions opts = new RangerPolicyEngineOptions(); + + final String propertyPrefix = "ranger.admin"; + + opts.configureDefaultRangerAdmin(config, propertyPrefix); + + return opts; + } + + private boolean hasAdminAccess(RangerPolicy policy, String userName, Set userGroups) { + boolean isAllowed = false; + RangerPolicyAdmin policyAdmin = getPolicyAdminForDelegatedAdmin(policy.getService()); + + if (policyAdmin != null) { + Map evalContext = new HashMap<>(); + + RangerAccessRequestUtil.setCurrentUserInContext(evalContext, userName); + + Set roles = policyAdmin.getRolesFromUserAndGroups(userName, userGroups); + + isAllowed = policyAdmin.isDelegatedAdminAccessAllowedForModify(policy, userName, userGroups, roles, evalContext); + } + + return isAllowed; + } + + private boolean hasAdminAccess(String serviceName, String zoneName, String userName, Set userGroups, RangerAccessResource resource, Set accessTypes) { + boolean isAllowed = false; + + RangerPolicyAdmin policyAdmin = getPolicyAdminForDelegatedAdmin(serviceName); + + if (policyAdmin != null) { + isAllowed = CollectionUtils.isNotEmpty(accessTypes) && policyAdmin.isDelegatedAdminAccessAllowed(resource, zoneName, userName, userGroups, accessTypes); + } + + return isAllowed; + } + + private RangerPolicyAdmin getPolicyAdminForSearch(String serviceName) { + return RangerPolicyAdminCacheForEngineOptions.getInstance().getServicePoliciesAdmin(serviceName, svcStore, zoneStore, roleDBStore, policySearchAdminOptions); + } + + private RangerPolicyAdmin getPolicyAdmin(String serviceName) { + return RangerPolicyAdminCacheForEngineOptions.getInstance().getServicePoliciesAdmin(serviceName, svcStore, zoneStore, roleDBStore, defaultAdminOptions); + } + + private HashMap getCSRFPropertiesMap(HttpServletRequest request) { + HashMap map = new HashMap<>(); + + map.put(isCSRF_ENABLED, PropertiesUtil.getBooleanProperty(isCSRF_ENABLED, true)); + map.put(CUSTOM_HEADER_PARAM, PropertiesUtil.getProperty(CUSTOM_HEADER_PARAM, RangerCSRFPreventionFilter.HEADER_DEFAULT)); + map.put(BROWSER_USER_AGENT_PARAM, PropertiesUtil.getProperty(BROWSER_USER_AGENT_PARAM, RangerCSRFPreventionFilter.BROWSER_USER_AGENTS_DEFAULT)); + map.put(CUSTOM_METHODS_TO_IGNORE_PARAM, PropertiesUtil.getProperty(CUSTOM_METHODS_TO_IGNORE_PARAM, RangerCSRFPreventionFilter.METHODS_TO_IGNORE_DEFAULT)); + map.put(RangerCSRFPreventionFilter.CSRF_TOKEN, getCSRFToken(request)); + + return map; + } + + private static String getCSRFToken(HttpServletRequest request) { + String salt = (String) request.getSession().getAttribute(RangerCSRFPreventionFilter.CSRF_TOKEN); + + if (StringUtils.isEmpty(salt)) { + final int tokenLength = PropertiesUtil.getIntProperty(CSRF_TOKEN_LENGTH, 20); + + salt = RandomStringUtils.random(tokenLength, 0, 0, true, true, null, new SecureRandom()); + + request.getSession().setAttribute(RangerCSRFPreventionFilter.CSRF_TOKEN, salt); + } + + return salt; + } + + private RangerPolicyList toRangerPolicyList(List policyList, SearchFilter filter) { + RangerPolicyList ret = new RangerPolicyList(); + + if (CollectionUtils.isNotEmpty(policyList)) { + int totalCount = policyList.size(); + int startIndex = filter.getStartIndex(); + int pageSize = filter.getMaxRows(); + int toIndex = Math.min(startIndex + pageSize, totalCount); + String sortType = filter.getSortType(); + String sortBy = filter.getSortBy(); + + if (StringUtils.isNotEmpty(sortBy) && StringUtils.isNotEmpty(sortType)) { + // By default policyList is sorted by policyId in asc order, So handling only desc case. + if (SearchFilter.POLICY_ID.equalsIgnoreCase(sortBy)) { + if (SORT_ORDER.DESC.name().equalsIgnoreCase(sortType)) { + policyList.sort(this.getPolicyComparator(sortBy, sortType)); + } + } else if (SearchFilter.POLICY_NAME.equalsIgnoreCase(sortBy)) { + if (SORT_ORDER.ASC.name().equalsIgnoreCase(sortType)) { + policyList.sort(this.getPolicyComparator(sortBy, sortType)); + } else if (SORT_ORDER.DESC.name().equalsIgnoreCase(sortType)) { + policyList.sort(this.getPolicyComparator(sortBy, sortType)); + } else { + LOG.info("Invalid or Unsupported sortType : {}", sortType); + } + } else { + LOG.info("Invalid or Unsupported sortBy property : {}", sortBy); + } + } + + List retList = new ArrayList<>(); + + for (int i = startIndex; i < toIndex; i++) { + retList.add(policyList.get(i)); + } + + ret.setPolicies(retList); + ret.setPageSize(pageSize); + ret.setResultSize(retList.size()); + ret.setStartIndex(startIndex); + ret.setTotalCount(totalCount); + ret.setSortBy(sortBy); + ret.setSortType(sortType); + } + + return ret; + } + + private Comparator getPolicyComparator(String sortBy, String sortType) { + return (RangerPolicy me, RangerPolicy other) -> { + int ret = 0; + + if (SearchFilter.POLICY_ID.equalsIgnoreCase(sortBy)) { + ret = Long.compare(other.getId(), me.getId()); + } else if (SearchFilter.POLICY_NAME.equalsIgnoreCase(sortBy)) { + if (SORT_ORDER.ASC.name().equalsIgnoreCase(sortType)) { + ret = me.getName().compareTo(other.getName()); + } else if (SORT_ORDER.DESC.name().equalsIgnoreCase(sortType)) { + ret = other.getName().compareTo(me.getName()); + } + } + + return ret; + }; + } + + private void validateGrantRevokeRequest(GrantRevokeRequest request, final boolean hasAdminPrivilege, final String loggedInUser) { + if (request != null) { + validateUsersGroupsAndRoles(request.getUsers(), request.getGroups(), request.getRoles()); + validateGrantor(request.getGrantor()); + validateGrantees(request.getUsers()); + validateGroups(request.getGroups()); + validateRoles(request.getRoles()); + + if (!hasAdminPrivilege) { + if (!StringUtils.equals(request.getGrantor(), loggedInUser) || StringUtils.isNotBlank(request.getOwnerUser())) { + throw restErrorUtil.createGrantRevokeRESTException("Invalid grant/revoke request - contains grantor or userOwner specification"); + } + + request.setGrantorGroups(userMgr.getGroupsForUser(request.getGrantor())); + } + } + } + + private void validateUsersGroupsAndRoles(Set users, Set groups, Set roles) { + if (CollectionUtils.isEmpty(users) && CollectionUtils.isEmpty(groups) && CollectionUtils.isEmpty(roles)) { + throw restErrorUtil.createGrantRevokeRESTException("Grantee users/groups/roles list is empty"); + } + } + + private void validateGrantor(String grantor) { + if (grantor != null) { + try { + VXUser vxUser = xUserService.getXUserByUserName(grantor); + + if (vxUser == null) { + throw restErrorUtil.createGrantRevokeRESTException("Grantor user " + grantor + " doesn't exist"); + } + } catch (Exception e) { + throw restErrorUtil.createGrantRevokeRESTException("Grantor user " + grantor + " doesn't exist"); + } + } + } + + private void validateGrantees(Set grantees) { + for (String userName : grantees) { + try { + VXUser vxUser = xUserService.getXUserByUserName(userName); + + if (vxUser == null) { + throw restErrorUtil.createGrantRevokeRESTException("Grantee user " + userName + " doesn't exist"); + } + } catch (Exception e) { + throw restErrorUtil.createGrantRevokeRESTException("Grantee user " + userName + " doesn't exist"); + } + } + } + + private void validateGroups(Set groups) { + for (String groupName : groups) { + try { + VXGroup vxGroup = userMgr.getGroupByGroupName(groupName); + + if (vxGroup == null) { + throw restErrorUtil.createGrantRevokeRESTException("Grantee group " + groupName + " doesn't exist"); + } + } catch (Exception e) { + throw restErrorUtil.createGrantRevokeRESTException("Grantee group " + groupName + " doesn't exist"); + } + } + } + + private void validateRoles(Set roles) { + XXRoleDao roleDao = daoManager.getXXRole(); + + for (String role : roles) { + try { + XXRole xxRole = roleDao.findByRoleName(role); + + if (xxRole == null) { + throw restErrorUtil.createGrantRevokeRESTException("Grantee role " + role + " doesn't exist"); + } + } catch (Exception e) { + throw restErrorUtil.createGrantRevokeRESTException("Grantee role " + role + " doesn't exist"); + } + } + } + + private Map getOptions(HttpServletRequest request) { + Map ret = null; + + if (request != null) { + String isForceRenameOption = request.getParameter(ServiceStore.OPTION_FORCE_RENAME); + + if (StringUtils.isNotBlank(isForceRenameOption)) { + ret = new HashMap<>(); + + ret.put(ServiceStore.OPTION_FORCE_RENAME, Boolean.valueOf(isForceRenameOption)); + } + } + + return ret; + } + + private RangerService hideCriticalServiceDetailsForRoleUser(RangerService rangerService) { + rangerService.setConfigs(null); + rangerService.setDescription(null); + rangerService.setCreatedBy(null); + rangerService.setUpdatedBy(null); + rangerService.setCreateTime(null); + rangerService.setUpdateTime(null); + rangerService.setPolicyVersion(null); + rangerService.setPolicyUpdateTime(null); + rangerService.setTagVersion(null); + rangerService.setTagUpdateTime(null); + rangerService.setVersion(null); + + return rangerService; + } + + private void createOrGetLinkedServices(RangerService resourceService) { + LOG.debug("==> createOrGetLinkedServices(resourceService={})", resourceService.getName()); + + Runnable createAndLinkTagServiceTask = () -> { + final LinkedServiceCreator creator = new LinkedServiceCreator(resourceService.getName(), EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_TAG_NAME); + + creator.doCreateAndLinkService(); + }; + + rangerTransactionSynchronizationAdapter.executeOnTransactionCommit(createAndLinkTagServiceTask); + + LOG.debug("<== createOrGetLinkedServices(resourceService={})", resourceService.getName()); + } + + private void deleteExactMatchPolicyForResource(List policies, String user, String zoneName) throws Exception { + if (CollectionUtils.isNotEmpty(policies)) { + long totalDeletedPolicies = 0; + + for (RangerPolicy rangerPolicy : policies) { + RangerPolicy existingPolicy; + + try { + if (zoneName != null) { + rangerPolicy.setZoneName(zoneName); + } + + existingPolicy = getExactMatchPolicyForResource(rangerPolicy, StringUtils.isNotBlank(user) ? user : "admin"); + } catch (Exception e) { + existingPolicy = null; + } + + if (existingPolicy != null) { + svcStore.deletePolicy(existingPolicy, null); + + totalDeletedPolicies = totalDeletedPolicies + 1; + + if (totalDeletedPolicies % RangerBizUtil.POLICY_BATCH_SIZE == 0) { + bizUtil.bulkModeOnlyFlushAndClear(); + } + + LOG.debug("Policy {} deleted successfully.", rangerPolicy.getName()); + } + } + + bizUtil.bulkModeOnlyFlushAndClear(); + } + } + + private String getRangerAdminZoneName(String serviceName, GrantRevokeRequest grantRevokeRequest) { + String ret = grantRevokeRequest.getZoneName(); + + if (StringUtils.isEmpty(ret)) { + RangerPolicyAdmin policyAdmin = getPolicyAdmin(serviceName); + + if (policyAdmin != null) { + ret = policyAdmin.getUniquelyMatchedZoneName(grantRevokeRequest); + } + } + + return ret; + } + + private RangerPolicy createPolicyUnconditionally(RangerPolicy policy) throws Exception { + LOG.debug("==> ServiceREST.createPolicyUnconditionally({})", policy); + + RangerPolicy ret; + + if (StringUtils.isBlank(policy.getName())) { + String guid = policy.getGuid(); + + if (StringUtils.isBlank(guid)) { + guid = guidUtil.genGUID(); + + policy.setGuid(guid); + + LOG.debug("No GUID supplied on the policy! Ok, setting GUID to [{}].", guid); + } + + String name = policy.getService() + "-" + guid; + + policy.setName(name); + + LOG.debug("Policy did not have its name set! Ok, setting name to [{}]", name); + } else if (isPolicyNameLengthValidationEnabled) { + if (policy.getName().length() > maxPolicyNameLength) { + throw restErrorUtil.createRESTException("Policy name should not be longer than " + maxPolicyNameLength + " characters", MessageEnums.INPUT_DATA_OUT_OF_BOUND, null, "policy name", policy.getName()); + } + } + + RangerPolicyValidator validator = validatorFactory.getPolicyValidator(svcStore); + + validator.validate(policy, Action.CREATE, bizUtil.isAdmin() || isServiceAdmin(policy.getService()) || isZoneAdmin(policy.getZoneName())); + + ensureAdminAccess(policy); + + bizUtil.blockAuditorRoleUser(); + + ret = svcStore.createPolicy(policy); + + LOG.debug("<== ServiceREST.createPolicyUnconditionally({})", ret); + + return ret; + } + + private RangerPolicy getPolicyMatchByName(RangerPolicy policy, HttpServletRequest request) { + LOG.debug("==> ServiceREST.getPolicyMatchByName({})", policy); + + RangerPolicy existingPolicy = null; + String serviceName = request.getParameter(PARAM_SERVICE_NAME); + + if (serviceName == null) { + serviceName = (String) request.getAttribute(PARAM_SERVICE_NAME); + } + + if (StringUtils.isNotEmpty(serviceName)) { + policy.setService(serviceName); + } + + String policyName = request.getParameter(PARAM_POLICY_NAME); + + if (policyName == null) { + policyName = (String) request.getAttribute(PARAM_POLICY_NAME); + } + + if (StringUtils.isNotEmpty(policyName)) { + policy.setName(StringUtils.trim(policyName)); + } + + if (StringUtils.isNotEmpty(serviceName) && StringUtils.isNotEmpty(policyName)) { + String zoneName = request.getParameter(PARAM_ZONE_NAME); + + if (StringUtils.isBlank(zoneName)) { + zoneName = (String) request.getAttribute(PARAM_ZONE_NAME); + } + + if (StringUtils.isNotBlank(zoneName)) { + policy.setZoneName(StringUtils.trim(zoneName)); + } + + existingPolicy = getPolicyByName(policy.getService(), policy.getName(), policy.getZoneName()); + } + + LOG.debug("<== ServiceREST.getPolicyMatchByName({})", existingPolicy); + + return existingPolicy; + } + + private String deleteServiceById(Long id) { + LOG.debug("==> ServiceREST.deleteServiceById({})", id); + + RangerContextHolder.getOrCreateOpContext().setBulkModeContext(true); + + RangerPerfTracer perf = null; + String deletedServiceName; + + try { + if (RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { + perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "ServiceREST.deleteService(serviceId=" + id + ")"); + } + + RangerServiceValidator validator = validatorFactory.getServiceValidator(svcStore); + + validator.validate(id, Action.DELETE); + + UserSessionBase session = ContextUtil.getCurrentUserSession(); + + if (session != null) { + XXService service = daoManager.getXXService().getById(id); + + if (service != null) { + //if logged-in user is not the service creator then check admin priv. + if (!session.getUserId().equals(service.getAddedByUserId())) { + bizUtil.hasAdminPermissions("Services"); + } + + EmbeddedServiceDefsUtil embeddedServiceDefsUtil = EmbeddedServiceDefsUtil.instance(); + + if (service.getType().equals(embeddedServiceDefsUtil.getTagServiceDefId())) { + List referringServices = daoManager.getXXService().findByTagServiceId(id); + + if (!CollectionUtils.isEmpty(referringServices)) { + Set referringServiceNames = new HashSet<>(); + + for (XXService xXService : referringServices) { + referringServiceNames.add(xXService.getName()); + + if (referringServiceNames.size() >= 10) { + break; + } + } + + if (referringServices.size() <= 10) { + throw restErrorUtil.createRESTException("Tag service '" + service.getName() + "' is being referenced by " + referringServices.size() + " services: " + referringServiceNames, MessageEnums.OPER_NOT_ALLOWED_FOR_STATE); + } else { + throw restErrorUtil.createRESTException("Tag service '" + service.getName() + "' is being referenced by " + referringServices.size() + " services: " + referringServiceNames + " and more..", MessageEnums.OPER_NOT_ALLOWED_FOR_STATE); + } + } + } + + XXServiceDef xxServiceDef = daoManager.getXXServiceDef().getById(service.getType()); + + if (!session.getUserId().equals(service.getAddedByUserId())) { + bizUtil.hasKMSPermissions("Service", xxServiceDef.getImplclassname()); + bizUtil.blockAuditorRoleUser(); + } + + tagStore.deleteAllTagObjectsForService(service.getName()); + + deletedServiceName = service.getName(); + + svcStore.deleteService(id); + } else { + LOG.error("Cannot retrieve service:[{}] for deletion", id); + + throw restErrorUtil.createRESTException("Data Not Found for given Id", MessageEnums.DATA_NOT_FOUND, id, null, "readResource : No Object found with given id."); + } + } else { + LOG.error("Cannot retrieve user session."); + + throw new Exception("deleteService(" + id + ") failed"); + } + } catch (WebApplicationException excp) { + throw excp; + } catch (Throwable excp) { + LOG.error("deleteService({}) failed", id, excp); + + throw restErrorUtil.createRESTException(excp.getMessage()); + } finally { + RangerPerfTracer.log(perf); + } + + LOG.debug("<== ServiceREST.deleteServiceById() - deletedServiceName={}", deletedServiceName); + + return deletedServiceName; + } + + private boolean isZoneAdmin(String zoneName) { + boolean ret = bizUtil.isAdmin(); + + if (!ret && StringUtils.isNotEmpty(zoneName)) { + ret = serviceMgr.isZoneAdmin(zoneName); + } + + return ret; + } + + private final class LinkedServiceCreator { + static final char SEP = '_'; + + final String resourceServiceName; + final String linkedServiceType; + final String linkedServiceName; + final boolean isAutoCreate; + final boolean isAutoLink; + + LinkedServiceCreator(@Nonnull String resourceServiceName, @Nonnull String linkedServiceType) { + this.resourceServiceName = resourceServiceName; + this.linkedServiceType = linkedServiceType; + this.linkedServiceName = computeLinkedServiceName(); + this.isAutoCreate = config.getBoolean("ranger." + linkedServiceType + "service.auto.create", true); + this.isAutoLink = config.getBoolean("ranger." + linkedServiceType + "service.auto.link", true); + } + + @Override + public String toString() { + return "{resourceServiceName=" + resourceServiceName + ", linkedServiceType=" + linkedServiceType + ", isAutoCreate=" + isAutoCreate + ", isAutoLink=" + isAutoLink + "}"; + } + + void doCreateAndLinkService() { + LOG.debug("==> doCreateAndLinkService()"); + + RangerService resourceService = null; + + try { + resourceService = svcStore.getServiceByName(resourceServiceName); + + LOG.info("Successfully retrieved resource-service:[{}]", resourceService.getName()); + } catch (Exception e) { + LOG.error("Resource-service:[{}] cannot be retrieved", resourceServiceName); + } + + if (resourceService != null) { + try { + RangerService linkedService = svcStore.getServiceByName(linkedServiceName); + + if (linkedService == null && isAutoCreate) { + linkedService = new RangerService(); + + linkedService.setName(linkedServiceName); + linkedService.setDisplayName(linkedServiceName); //set DEFAULT display name + linkedService.setType(linkedServiceType); + + LOG.info("creating service [{}]", linkedServiceName); + + svcStore.createService(linkedService); + } + } catch (Exception e) { + throw new RuntimeException(e); + } + + if (isAutoLink) { + doLinkService(); + } + } else { + LOG.info("Resource service :[{}] not found! Returning without linking {} service!!", resourceServiceName, linkedServiceType); + } + + LOG.debug("<== doCreateAndLinkService()"); + } + + private String computeLinkedServiceName() { + String ret = config.get("ranger." + linkedServiceType + "service.auto.name"); + + if (StringUtils.isBlank(ret)) { + final int lastIndexOfSep = StringUtils.lastIndexOf(resourceServiceName, SEP); + + ret = (lastIndexOfSep != -1) ? resourceServiceName.substring(0, lastIndexOfSep) + SEP + linkedServiceType : linkedServiceType; + } + + return ret; + } + + private void doLinkService() { + LOG.debug("==> doLinkTagService()"); + + try { + RangerService resourceService = svcStore.getServiceByName(resourceServiceName); + + LOG.info("Successfully retrieved resource-service:[{}]", resourceService.getName()); + + RangerService linkedService = svcStore.getServiceByName(linkedServiceName); + + if (linkedService == null) { + LOG.error("Failed to link service[{}] with service [{}]: {} not found", resourceServiceName, linkedServiceName, linkedServiceName); + } else if (EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_TAG_NAME.equals(linkedServiceType)) { + LOG.info("Successfully retrieved service:[{}]", linkedService.getName()); + + if (!StringUtils.equals(linkedService.getName(), resourceService.getTagService())) { + resourceService.setTagService(linkedService.getName()); + + LOG.info("Linking resource-service[{}] with tag-service [{}]", resourceService.getName(), linkedService.getName()); + + RangerService service = svcStore.updateService(resourceService, null); + + LOG.info("Updated resource-service:[{}]", service.getName()); + } + } + } catch (Exception e) { + LOG.error("Failed to link service[{}] with service [{}]", resourceServiceName, linkedServiceName); + } + LOG.debug("<== doLinkTagService()"); + } + } +} diff --git a/security-admin/src/main/java/org/apache/ranger/rest/ServiceRESTUtil.java b/security-admin/src/main/java/org/apache/ranger/rest/ServiceRESTUtil.java index d7fb1e1c8c..81ed00ec0b 100644 --- a/security-admin/src/main/java/org/apache/ranger/rest/ServiceRESTUtil.java +++ b/security-admin/src/main/java/org/apache/ranger/rest/ServiceRESTUtil.java @@ -22,6 +22,8 @@ import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang.StringUtils; import org.apache.ranger.plugin.model.RangerPolicy; +import org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyItem; +import org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyItemAccess; import org.apache.ranger.plugin.util.GrantRevokeRequest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -35,1128 +37,1078 @@ import java.util.TreeSet; public class ServiceRESTUtil { - private static final Logger LOG = LoggerFactory.getLogger(ServiceRESTUtil.class); + private static final Logger LOG = LoggerFactory.getLogger(ServiceRESTUtil.class); - private enum POLICYITEM_TYPE { - ALLOW, DENY, ALLOW_EXCEPTIONS, DENY_EXCEPTIONS - } + private ServiceRESTUtil() { + //To block instantiation + } - static public boolean processGrantRequest(RangerPolicy policy, GrantRevokeRequest grantRequest) { - if (LOG.isDebugEnabled()) { - LOG.debug("==> ServiceRESTUtil.processGrantRequest()"); - } + public static boolean processGrantRequest(RangerPolicy policy, GrantRevokeRequest grantRequest) { + LOG.debug("==> ServiceRESTUtil.processGrantRequest()"); - boolean policyUpdated = false; + // replace all existing privileges for users, groups, and roles + if (grantRequest.getReplaceExistingPermissions()) { + removeUsersGroupsAndRolesFromPolicy(policy, grantRequest.getUsers(), grantRequest.getGroups(), grantRequest.getRoles()); + } - // replace all existing privileges for users, groups, and roles - if (grantRequest.getReplaceExistingPermissions()) { - policyUpdated = removeUsersGroupsAndRolesFromPolicy(policy, grantRequest.getUsers(), grantRequest.getGroups(), grantRequest.getRoles()); - } + //Build a policy and set up policyItem in it to mimic grant request + RangerPolicy appliedPolicy = new RangerPolicy(); + RangerPolicyItem policyItem = new RangerPolicyItem(); - //Build a policy and set up policyItem in it to mimic grant request - RangerPolicy appliedPolicy = new RangerPolicy(); - - RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem(); - - policyItem.setDelegateAdmin(grantRequest.getDelegateAdmin()); - policyItem.addUsers(grantRequest.getUsers()); - policyItem.addGroups(grantRequest.getGroups()); - policyItem.addRoles(grantRequest.getRoles()); - - List accesses = new ArrayList(); - - Set accessTypes = grantRequest.getAccessTypes(); - for (String accessType : accessTypes) { - accesses.add(new RangerPolicy.RangerPolicyItemAccess(accessType, true)); - } - - policyItem.setAccesses(accesses); - - appliedPolicy.addPolicyItem(policyItem); - - processApplyPolicy(policy, appliedPolicy); - - policyUpdated = true; - - if (LOG.isDebugEnabled()) { - LOG.debug("<== ServiceRESTUtil.processGrantRequest() : " + policyUpdated); - } - - return policyUpdated; - } - - static public boolean processRevokeRequest(RangerPolicy existingRangerPolicy, GrantRevokeRequest revokeRequest) { - if (LOG.isDebugEnabled()) { - LOG.debug("==> ServiceRESTUtil.processRevokeRequest()"); - } - - boolean policyUpdated = false; - - // remove all existing privileges for users and groups - if (revokeRequest.getReplaceExistingPermissions()) { - policyUpdated = removeUsersGroupsAndRolesFromPolicy(existingRangerPolicy, revokeRequest.getUsers(), revokeRequest.getGroups(), revokeRequest.getRoles()); - } else { - //Build a policy and set up policyItem in it to mimic revoke request - RangerPolicy appliedRangerPolicy = new RangerPolicy(); - - RangerPolicy.RangerPolicyItem appliedRangerPolicyItem = new RangerPolicy.RangerPolicyItem(); - - appliedRangerPolicyItem.setDelegateAdmin(revokeRequest.getDelegateAdmin()); - appliedRangerPolicyItem.addUsers(revokeRequest.getUsers()); - appliedRangerPolicyItem.addGroups(revokeRequest.getGroups()); - appliedRangerPolicyItem.addRoles(revokeRequest.getRoles()); - - List appliedRangerPolicyItemAccess = new ArrayList(); - - Set appliedPolicyItemAccessType = revokeRequest.getAccessTypes(); - for (String accessType : appliedPolicyItemAccessType) { - appliedRangerPolicyItemAccess.add(new RangerPolicy.RangerPolicyItemAccess(accessType, false)); - } - - appliedRangerPolicyItem.setAccesses(appliedRangerPolicyItemAccess); - - appliedRangerPolicy.addPolicyItem(appliedRangerPolicyItem); - - List appliedRangerPolicyItems = appliedRangerPolicy.getPolicyItems(); - //processApplyPolicyForItemType(existingRangerPolicy, appliedRangerPolicy, POLICYITEM_TYPE.ALLOW); - if (CollectionUtils.isNotEmpty(appliedRangerPolicyItems)) { - Set users = new HashSet(); - Set groups = new HashSet(); - Set roles = new HashSet<>(); - - Map userPolicyItems = new HashMap(); - Map groupPolicyItems = new HashMap(); - Map rolePolicyItems = new HashMap(); - - // Extract users, groups, and roles specified in appliedPolicy items - extractUsersGroupsAndRoles(appliedRangerPolicyItems, users, groups, roles); - - // Split existing policyItems for users, groups, and roles extracted from appliedPolicyItem into userPolicyItems, groupPolicyItems and rolePolicyItems - splitExistingPolicyItems(existingRangerPolicy, users, userPolicyItems, groups, groupPolicyItems, roles, rolePolicyItems); - - for (RangerPolicy.RangerPolicyItem tempPolicyItem : appliedRangerPolicyItems) { - List appliedPolicyItemsUser = tempPolicyItem.getUsers(); - for (String user : appliedPolicyItemsUser) { - RangerPolicy.RangerPolicyItem[] rangerPolicyItems = userPolicyItems.get(user); - if(rangerPolicyItems!=null && rangerPolicyItems.length>0){ - if(rangerPolicyItems[POLICYITEM_TYPE.ALLOW.ordinal()]!=null){ - removeAccesses(rangerPolicyItems[POLICYITEM_TYPE.ALLOW.ordinal()], tempPolicyItem.getAccesses()); - if(!CollectionUtils.isEmpty(rangerPolicyItems[POLICYITEM_TYPE.ALLOW.ordinal()].getAccesses())){ - rangerPolicyItems[POLICYITEM_TYPE.ALLOW.ordinal()].setDelegateAdmin(revokeRequest.getDelegateAdmin()); - }else{ - rangerPolicyItems[POLICYITEM_TYPE.ALLOW.ordinal()].setDelegateAdmin(Boolean.FALSE); - } - } - if(rangerPolicyItems[POLICYITEM_TYPE.DENY_EXCEPTIONS.ordinal()]!=null){ - removeAccesses(rangerPolicyItems[POLICYITEM_TYPE.DENY_EXCEPTIONS.ordinal()], tempPolicyItem.getAccesses()); - rangerPolicyItems[POLICYITEM_TYPE.DENY_EXCEPTIONS.ordinal()].setDelegateAdmin(Boolean.FALSE); - } - } - } - } - for (RangerPolicy.RangerPolicyItem tempPolicyItem : appliedRangerPolicyItems) { - List appliedPolicyItemsGroup = tempPolicyItem.getGroups(); - for (String group : appliedPolicyItemsGroup) { - RangerPolicy.RangerPolicyItem[] rangerPolicyItems = groupPolicyItems.get(group); - if(rangerPolicyItems!=null && rangerPolicyItems.length>0){ - if(rangerPolicyItems[POLICYITEM_TYPE.ALLOW.ordinal()]!=null){ - removeAccesses(rangerPolicyItems[POLICYITEM_TYPE.ALLOW.ordinal()], tempPolicyItem.getAccesses()); - if(!CollectionUtils.isEmpty(rangerPolicyItems[POLICYITEM_TYPE.ALLOW.ordinal()].getAccesses())){ - rangerPolicyItems[POLICYITEM_TYPE.ALLOW.ordinal()].setDelegateAdmin(revokeRequest.getDelegateAdmin()); - }else{ - rangerPolicyItems[POLICYITEM_TYPE.ALLOW.ordinal()].setDelegateAdmin(Boolean.FALSE); - } - } - if(rangerPolicyItems[POLICYITEM_TYPE.DENY_EXCEPTIONS.ordinal()]!=null){ - removeAccesses(rangerPolicyItems[POLICYITEM_TYPE.DENY_EXCEPTIONS.ordinal()], tempPolicyItem.getAccesses()); - rangerPolicyItems[POLICYITEM_TYPE.DENY_EXCEPTIONS.ordinal()].setDelegateAdmin(Boolean.FALSE); - } - } - } - } - - for (RangerPolicy.RangerPolicyItem tempPolicyItem : appliedRangerPolicyItems) { - List appliedPolicyItemsRole = tempPolicyItem.getRoles(); - for (String role : appliedPolicyItemsRole) { - RangerPolicy.RangerPolicyItem[] rangerPolicyItems = rolePolicyItems.get(role); - if(rangerPolicyItems!=null && rangerPolicyItems.length>0){ - if(rangerPolicyItems[POLICYITEM_TYPE.ALLOW.ordinal()]!=null){ - removeAccesses(rangerPolicyItems[POLICYITEM_TYPE.ALLOW.ordinal()], tempPolicyItem.getAccesses()); - if(!CollectionUtils.isEmpty(rangerPolicyItems[POLICYITEM_TYPE.ALLOW.ordinal()].getAccesses())){ - rangerPolicyItems[POLICYITEM_TYPE.ALLOW.ordinal()].setDelegateAdmin(revokeRequest.getDelegateAdmin()); - }else{ - rangerPolicyItems[POLICYITEM_TYPE.ALLOW.ordinal()].setDelegateAdmin(Boolean.FALSE); - } - } - if(rangerPolicyItems[POLICYITEM_TYPE.DENY_EXCEPTIONS.ordinal()]!=null){ - removeAccesses(rangerPolicyItems[POLICYITEM_TYPE.DENY_EXCEPTIONS.ordinal()], tempPolicyItem.getAccesses()); - rangerPolicyItems[POLICYITEM_TYPE.DENY_EXCEPTIONS.ordinal()].setDelegateAdmin(Boolean.FALSE); - } - } - } - } - // Add modified/new policyItems back to existing policy - mergeProcessedPolicyItems(existingRangerPolicy, userPolicyItems, groupPolicyItems, rolePolicyItems); - compactPolicy(existingRangerPolicy); - } - - policyUpdated = true; - } - - if (LOG.isDebugEnabled()) { - LOG.debug("<== ServiceRESTUtil.processRevokeRequest() : " + policyUpdated); - } - - return policyUpdated; - } - - static public void processApplyPolicy(RangerPolicy existingPolicy, RangerPolicy appliedPolicy) { - if (LOG.isDebugEnabled()) { - LOG.debug("==> ServiceRESTUtil.processApplyPolicy()"); - } - - // Check if applied policy or existing policy contains any conditions - if (ServiceRESTUtil.containsRangerCondition(existingPolicy) || ServiceRESTUtil.containsRangerCondition(appliedPolicy)) { - LOG.info("Applied policy [" + appliedPolicy + "] or existing policy [" + existingPolicy + "] contains condition(s). Combining two policies."); - combinePolicy(existingPolicy, appliedPolicy); - } else { - processApplyPolicyForItemType(existingPolicy, appliedPolicy, POLICYITEM_TYPE.ALLOW); - processApplyPolicyForItemType(existingPolicy, appliedPolicy, POLICYITEM_TYPE.DENY); - processApplyPolicyForItemType(existingPolicy, appliedPolicy, POLICYITEM_TYPE.ALLOW_EXCEPTIONS); - processApplyPolicyForItemType(existingPolicy, appliedPolicy, POLICYITEM_TYPE.DENY_EXCEPTIONS); - } - - if (LOG.isDebugEnabled()) { - LOG.debug("<== ServiceRESTUtil.processApplyPolicy()"); - } - } - - static private void combinePolicy(RangerPolicy existingPolicy, RangerPolicy appliedPolicy) { - combinePolicyItems(existingPolicy, appliedPolicy, POLICYITEM_TYPE.ALLOW); - combinePolicyItems(existingPolicy, appliedPolicy, POLICYITEM_TYPE.DENY); - combinePolicyItems(existingPolicy, appliedPolicy, POLICYITEM_TYPE.ALLOW_EXCEPTIONS); - combinePolicyItems(existingPolicy, appliedPolicy, POLICYITEM_TYPE.DENY_EXCEPTIONS); - } - - static private void combinePolicyItems(RangerPolicy existingPolicy, RangerPolicy appliedPolicy, POLICYITEM_TYPE polityItemType) { - List existingPolicyItems; - List appliedPolicyItems; - - switch (polityItemType) { - case ALLOW: - existingPolicyItems = existingPolicy.getPolicyItems(); - appliedPolicyItems = appliedPolicy.getPolicyItems(); - break; - case DENY: - existingPolicyItems = existingPolicy.getDenyPolicyItems(); - appliedPolicyItems = appliedPolicy.getDenyPolicyItems(); - break; - case ALLOW_EXCEPTIONS: - existingPolicyItems = existingPolicy.getAllowExceptions(); - appliedPolicyItems = appliedPolicy.getAllowExceptions(); - break; - case DENY_EXCEPTIONS: - existingPolicyItems = existingPolicy.getDenyExceptions(); - appliedPolicyItems = appliedPolicy.getDenyExceptions(); - break; - default: - existingPolicyItems = null; - appliedPolicyItems = null; - break; - } - - if (CollectionUtils.isNotEmpty(appliedPolicyItems)) { - if (CollectionUtils.isNotEmpty(existingPolicyItems)) { - List itemsToAdd = new ArrayList<>(); - for (RangerPolicy.RangerPolicyItem appliedPolicyItem : appliedPolicyItems) { - if (!existingPolicyItems.contains(appliedPolicyItem)) { - itemsToAdd.add(appliedPolicyItem); - } - } - existingPolicyItems.addAll(itemsToAdd); - } else { - switch (polityItemType) { - case ALLOW: - existingPolicy.setPolicyItems(appliedPolicyItems); - break; - case DENY: - existingPolicy.setDenyPolicyItems(appliedPolicyItems); - break; - case ALLOW_EXCEPTIONS: - existingPolicy.setAllowExceptions(appliedPolicyItems); - break; - case DENY_EXCEPTIONS: - existingPolicy.setDenyExceptions(appliedPolicyItems); - break; - } - } - } - } - - static private void processApplyPolicyForItemType(RangerPolicy existingPolicy, RangerPolicy appliedPolicy, POLICYITEM_TYPE policyItemType) { - if (LOG.isDebugEnabled()) { - LOG.debug("==> ServiceRESTUtil.processApplyPolicyForItemType()"); - } - - List appliedPolicyItems = null; - - switch (policyItemType) { - case ALLOW: - appliedPolicyItems = appliedPolicy.getPolicyItems(); - break; - case DENY: - appliedPolicyItems = appliedPolicy.getDenyPolicyItems(); - break; - case ALLOW_EXCEPTIONS: - appliedPolicyItems = appliedPolicy.getAllowExceptions(); - break; - case DENY_EXCEPTIONS: - appliedPolicyItems = appliedPolicy.getDenyExceptions(); - break; - default: - LOG.warn("processApplyPolicyForItemType(): invalid policyItemType=" + policyItemType); - } - - if (CollectionUtils.isNotEmpty(appliedPolicyItems)) { - - Set users = new HashSet(); - Set groups = new HashSet(); - Set roles = new HashSet(); - - Map userPolicyItems = new HashMap(); - Map groupPolicyItems = new HashMap(); - Map rolePolicyItems = new HashMap(); - - // Extract users, groups, and roles specified in appliedPolicy items - extractUsersGroupsAndRoles(appliedPolicyItems, users, groups, roles); - - // Split existing policyItems for users, groups, and roles extracted from appliedPolicyItem into userPolicyItems, groupPolicyItems, and rolePolicyItems - splitExistingPolicyItems(existingPolicy, users, userPolicyItems, groups, groupPolicyItems, roles, rolePolicyItems); - - // Apply policyItems of given type in appliedPolicy to policyItems extracted from existingPolicy - applyPolicyItems(appliedPolicyItems, policyItemType, userPolicyItems, groupPolicyItems, rolePolicyItems); - - // Add modified/new policyItems back to existing policy - mergeProcessedPolicyItems(existingPolicy, userPolicyItems, groupPolicyItems, rolePolicyItems); - - compactPolicy(existingPolicy); - } - - if (LOG.isDebugEnabled()) { - LOG.debug("<== ServiceRESTUtil.processApplyPolicyForItemType()"); - } - } - - static public void mergeExactMatchPolicyForResource(RangerPolicy existingPolicy, RangerPolicy appliedPolicy) { - if (LOG.isDebugEnabled()) { - LOG.debug("==> ServiceRESTUtil.mergeExactMatchPolicyForResource()"); - } - mergeExactMatchPolicyForItemType(existingPolicy, appliedPolicy, POLICYITEM_TYPE.ALLOW); - mergeExactMatchPolicyForItemType(existingPolicy, appliedPolicy, POLICYITEM_TYPE.DENY); - mergeExactMatchPolicyForItemType(existingPolicy, appliedPolicy, POLICYITEM_TYPE.ALLOW_EXCEPTIONS); - mergeExactMatchPolicyForItemType(existingPolicy, appliedPolicy, POLICYITEM_TYPE.DENY_EXCEPTIONS); - if (LOG.isDebugEnabled()) { - LOG.debug("<== ServiceRESTUtil.mergeExactMatchPolicyForResource()"); - } - } - - static private void mergeExactMatchPolicyForItemType(RangerPolicy existingPolicy, RangerPolicy appliedPolicy, POLICYITEM_TYPE policyItemType) { - if (LOG.isDebugEnabled()) { - LOG.debug("==> ServiceRESTUtil.mergeExactMatchPolicyForItemType()"); - } - List appliedPolicyItems = null; - switch (policyItemType) { - case ALLOW: - appliedPolicyItems = appliedPolicy.getPolicyItems(); - break; - case DENY: - appliedPolicyItems = appliedPolicy.getDenyPolicyItems(); - break; - case ALLOW_EXCEPTIONS: - appliedPolicyItems = appliedPolicy.getAllowExceptions(); - break; - case DENY_EXCEPTIONS: - appliedPolicyItems = appliedPolicy.getDenyExceptions(); - break; - default: - LOG.warn("mergeExactMatchPolicyForItemType(): invalid policyItemType=" + policyItemType); - } - - if (CollectionUtils.isNotEmpty(appliedPolicyItems)) { - - Set users = new HashSet(); - Set groups = new HashSet(); - Set roles = new HashSet(); - - Map userPolicyItems = new HashMap(); - Map groupPolicyItems = new HashMap(); - Map rolePolicyItems = new HashMap(); - - // Extract users and groups specified in appliedPolicy items - extractUsersGroupsAndRoles(appliedPolicyItems, users, groups, roles); - - // Split existing policyItems for users and groups extracted from appliedPolicyItem into userPolicyItems and groupPolicyItems - splitExistingPolicyItems(existingPolicy, users, userPolicyItems, groups, groupPolicyItems, roles, rolePolicyItems); - // Apply policyItems of given type in appliedPlicy to policyItems extracted from existingPolicy - mergePolicyItems(appliedPolicyItems, policyItemType, userPolicyItems, groupPolicyItems, rolePolicyItems); - // Add modified/new policyItems back to existing policy - mergeProcessedPolicyItems(existingPolicy, userPolicyItems, groupPolicyItems, rolePolicyItems); - compactPolicy(existingPolicy); - } - - if (LOG.isDebugEnabled()) { - LOG.debug("<== ServiceRESTUtil.mergeExactMatchPolicyForItemType()"); - } - } - - static private void extractUsersGroupsAndRoles(List policyItems, Set users, Set groups, Set roles) { - if (LOG.isDebugEnabled()) { - LOG.debug("==> ServiceRESTUtil.extractUsersGroupsAndRoles()"); - } - if (CollectionUtils.isNotEmpty(policyItems)) { - for (RangerPolicy.RangerPolicyItem policyItem : policyItems) { - if (CollectionUtils.isNotEmpty(policyItem.getUsers())) { - users.addAll(policyItem.getUsers()); - } - if (CollectionUtils.isNotEmpty(policyItem.getGroups())) { - groups.addAll(policyItem.getGroups()); - } - - if (CollectionUtils.isNotEmpty(policyItem.getRoles())) { - roles.addAll(policyItem.getRoles()); - } - } - } - if (LOG.isDebugEnabled()) { - LOG.debug("<== ServiceRESTUtil.extractUsersGroupsAndRoles()"); - } - } - - static private void splitExistingPolicyItems(RangerPolicy existingPolicy, - Set users, Map userPolicyItems, Set groups, - Map groupPolicyItems, Set roles, - Map rolePolicyItems) { - - if (existingPolicy == null - || users == null || userPolicyItems == null - || groups == null || groupPolicyItems == null - || roles == null || rolePolicyItems == null) { - return; - } - - if (LOG.isDebugEnabled()) { - LOG.debug("==> ServiceRESTUtil.splitExistingPolicyItems()"); - } - - List allowItems = existingPolicy.getPolicyItems(); - List denyItems = existingPolicy.getDenyPolicyItems(); - List allowExceptionItems = existingPolicy.getAllowExceptions(); - List denyExceptionItems = existingPolicy.getDenyExceptions(); - - for (String user : users) { - RangerPolicy.RangerPolicyItem value[] = userPolicyItems.get(user); - if (value == null) { - value = new RangerPolicy.RangerPolicyItem[4]; - userPolicyItems.put(user, value); - } - - RangerPolicy.RangerPolicyItem policyItem = null; - - policyItem = splitAndGetConsolidatedPolicyItemForUser(allowItems, user); - value[POLICYITEM_TYPE.ALLOW.ordinal()] = policyItem; - policyItem = splitAndGetConsolidatedPolicyItemForUser(denyItems, user); - value[POLICYITEM_TYPE.DENY.ordinal()] = policyItem; - policyItem = splitAndGetConsolidatedPolicyItemForUser(allowExceptionItems, user); - value[POLICYITEM_TYPE.ALLOW_EXCEPTIONS.ordinal()] = policyItem; - policyItem = splitAndGetConsolidatedPolicyItemForUser(denyExceptionItems, user); - value[POLICYITEM_TYPE.DENY_EXCEPTIONS.ordinal()] = policyItem; - } - - for (String group : groups) { - RangerPolicy.RangerPolicyItem value[] = groupPolicyItems.get(group); - if (value == null) { - value = new RangerPolicy.RangerPolicyItem[4]; - groupPolicyItems.put(group, value); - } - - RangerPolicy.RangerPolicyItem policyItem = null; - - policyItem = splitAndGetConsolidatedPolicyItemForGroup(allowItems, group); - value[POLICYITEM_TYPE.ALLOW.ordinal()] = policyItem; - policyItem = splitAndGetConsolidatedPolicyItemForGroup(denyItems, group); - value[POLICYITEM_TYPE.DENY.ordinal()] = policyItem; - policyItem = splitAndGetConsolidatedPolicyItemForGroup(allowExceptionItems, group); - value[POLICYITEM_TYPE.ALLOW_EXCEPTIONS.ordinal()] = policyItem; - policyItem = splitAndGetConsolidatedPolicyItemForGroup(denyExceptionItems, group); - value[POLICYITEM_TYPE.DENY_EXCEPTIONS.ordinal()] = policyItem; - } - for (String role : roles) { - RangerPolicy.RangerPolicyItem value[] = rolePolicyItems.get(role); - if (value == null) { - value = new RangerPolicy.RangerPolicyItem[4]; - rolePolicyItems.put(role, value); - } - - RangerPolicy.RangerPolicyItem policyItem = null; - - policyItem = splitAndGetConsolidatedPolicyItemForRole(allowItems, role); - value[POLICYITEM_TYPE.ALLOW.ordinal()] = policyItem; - policyItem = splitAndGetConsolidatedPolicyItemForRole(denyItems, role); - value[POLICYITEM_TYPE.DENY.ordinal()] = policyItem; - policyItem = splitAndGetConsolidatedPolicyItemForRole(allowExceptionItems, role); - value[POLICYITEM_TYPE.ALLOW_EXCEPTIONS.ordinal()] = policyItem; - policyItem = splitAndGetConsolidatedPolicyItemForRole(denyExceptionItems, role); - value[POLICYITEM_TYPE.DENY_EXCEPTIONS.ordinal()] = policyItem; - } - - if (LOG.isDebugEnabled()) { - LOG.debug("<== ServiceRESTUtil.splitExistingPolicyItems()"); - } - } - - static private RangerPolicy.RangerPolicyItem splitAndGetConsolidatedPolicyItemForUser(List policyItems, String user) { - if (LOG.isDebugEnabled()) { - LOG.debug("==> ServiceRESTUtil.splitAndGetConsolidatedPolicyItemForUser()"); - } - - RangerPolicy.RangerPolicyItem ret = null; - - if (CollectionUtils.isNotEmpty(policyItems)) { - for (RangerPolicy.RangerPolicyItem policyItem : policyItems) { - List users = policyItem.getUsers(); - if (users.contains(user)) { - if (ret == null) { - ret = new RangerPolicy.RangerPolicyItem(); - } - ret.addUser(user); - if (policyItem.getDelegateAdmin()) { - ret.setDelegateAdmin(Boolean.TRUE); - } - addAccesses(ret, policyItem.getAccesses()); - - // Remove this user from existingPolicyItem - users.remove(user); - } - } - } - - if (LOG.isDebugEnabled()) { - LOG.debug("<== ServiceRESTUtil.splitAndGetConsolidatedPolicyItemForUser()"); - } - - return ret; - } - - static private RangerPolicy.RangerPolicyItem splitAndGetConsolidatedPolicyItemForGroup(List policyItems, String group) { - if (LOG.isDebugEnabled()) { - LOG.debug("==> ServiceRESTUtil.splitAndGetConsolidatedPolicyItemForGroup()"); - } - - RangerPolicy.RangerPolicyItem ret = null; - - if (CollectionUtils.isNotEmpty(policyItems)) { - for (RangerPolicy.RangerPolicyItem policyItem : policyItems) { - List groups = policyItem.getGroups(); - if (groups.contains(group)) { - if (ret == null) { - ret = new RangerPolicy.RangerPolicyItem(); - } - ret.addGroup(group); - if (policyItem.getDelegateAdmin()) { - ret.setDelegateAdmin(Boolean.TRUE); - } - addAccesses(ret, policyItem.getAccesses()); - - // Remove this group from existingPolicyItem - groups.remove(group); - } - } - } - - if (LOG.isDebugEnabled()) { - LOG.debug("<== ServiceRESTUtil.splitAndGetConsolidatedPolicyItemForGroup()"); - } - - return ret; - } - - static private RangerPolicy.RangerPolicyItem splitAndGetConsolidatedPolicyItemForRole(List policyItems, String role) { - if (LOG.isDebugEnabled()) { - LOG.debug("==> ServiceRESTUtil.splitAndGetConsolidatedPolicyItemForGroup()"); - } - - RangerPolicy.RangerPolicyItem ret = null; - - if (CollectionUtils.isNotEmpty(policyItems)) { - for (RangerPolicy.RangerPolicyItem policyItem : policyItems) { - List roles = policyItem.getRoles(); - if (roles.contains(role)) { - if (ret == null) { - ret = new RangerPolicy.RangerPolicyItem(); - } - ret.addRole(role); - if (policyItem.getDelegateAdmin()) { - ret.setDelegateAdmin(Boolean.TRUE); - } - addAccesses(ret, policyItem.getAccesses()); - - // Remove this role from existingPolicyItem - roles.remove(role); - } - } - } - - if (LOG.isDebugEnabled()) { - LOG.debug("<== ServiceRESTUtil.splitAndGetConsolidatedPolicyItemForGroup()"); - } - - return ret; - } - - static private void applyPolicyItems(List appliedPolicyItems, POLICYITEM_TYPE policyItemType, Map existingUserPolicyItems, - Map existingGroupPolicyItems, Map existingRolePolicyItems) { - if (LOG.isDebugEnabled()) { - LOG.debug("==> ServiceRESTUtil.applyPolicyItems()"); - } - - for (RangerPolicy.RangerPolicyItem policyItem : appliedPolicyItems) { - List users = policyItem.getUsers(); - for (String user : users) { - RangerPolicy.RangerPolicyItem[] existingPolicyItems = existingUserPolicyItems.get(user); - - if (existingPolicyItems == null) { - // Should not get here - LOG.warn("Should not have come here.."); - existingPolicyItems = new RangerPolicy.RangerPolicyItem[4]; - existingUserPolicyItems.put(user, existingPolicyItems); - } - - addPolicyItemForUser(existingPolicyItems, policyItemType.ordinal(), user, policyItem); - - switch (policyItemType) { - case ALLOW: - RangerPolicy.RangerPolicyItem denyPolicyItem = existingPolicyItems[POLICYITEM_TYPE.DENY.ordinal()]; - if (denyPolicyItem != null) { - removeAccesses(existingPolicyItems[POLICYITEM_TYPE.DENY.ordinal()], policyItem.getAccesses()); - addPolicyItemForUser(existingPolicyItems, POLICYITEM_TYPE.DENY_EXCEPTIONS.ordinal(), user, policyItem); - } - removeAccesses(existingPolicyItems[POLICYITEM_TYPE.ALLOW_EXCEPTIONS.ordinal()], policyItem.getAccesses()); - break; - case DENY: - RangerPolicy.RangerPolicyItem allowPolicyItem = existingPolicyItems[POLICYITEM_TYPE.ALLOW.ordinal()]; - if (allowPolicyItem != null) { - removeAccesses(existingPolicyItems[POLICYITEM_TYPE.ALLOW.ordinal()], policyItem.getAccesses()); - addPolicyItemForUser(existingPolicyItems, POLICYITEM_TYPE.ALLOW_EXCEPTIONS.ordinal(), user, policyItem); - } - removeAccesses(existingPolicyItems[POLICYITEM_TYPE.DENY_EXCEPTIONS.ordinal()], policyItem.getAccesses()); - break; - case ALLOW_EXCEPTIONS: - removeAccesses(existingPolicyItems[POLICYITEM_TYPE.ALLOW.ordinal()], policyItem.getAccesses()); - break; - case DENY_EXCEPTIONS: - removeAccesses(existingPolicyItems[POLICYITEM_TYPE.DENY.ordinal()], policyItem.getAccesses()); - break; - default: - LOG.warn("Should not have come here.."); - break; - } - } - } - - for (RangerPolicy.RangerPolicyItem policyItem : appliedPolicyItems) { - List groups = policyItem.getGroups(); - for (String group : groups) { - RangerPolicy.RangerPolicyItem[] existingPolicyItems = existingGroupPolicyItems.get(group); - - if (existingPolicyItems == null) { - // Should not get here - existingPolicyItems = new RangerPolicy.RangerPolicyItem[4]; - existingGroupPolicyItems.put(group, existingPolicyItems); - } - - addPolicyItemForGroup(existingPolicyItems, policyItemType.ordinal(), group, policyItem); - - switch (policyItemType) { - case ALLOW: - RangerPolicy.RangerPolicyItem denyPolicyItem = existingPolicyItems[POLICYITEM_TYPE.DENY.ordinal()]; - if (denyPolicyItem != null) { - removeAccesses(existingPolicyItems[POLICYITEM_TYPE.DENY.ordinal()], policyItem.getAccesses()); - addPolicyItemForGroup(existingPolicyItems, POLICYITEM_TYPE.DENY_EXCEPTIONS.ordinal(), group, policyItem); - } - removeAccesses(existingPolicyItems[POLICYITEM_TYPE.ALLOW_EXCEPTIONS.ordinal()], policyItem.getAccesses()); - break; - case DENY: - RangerPolicy.RangerPolicyItem allowPolicyItem = existingPolicyItems[POLICYITEM_TYPE.ALLOW.ordinal()]; - if (allowPolicyItem != null) { - removeAccesses(existingPolicyItems[POLICYITEM_TYPE.ALLOW.ordinal()], policyItem.getAccesses()); - addPolicyItemForGroup(existingPolicyItems, POLICYITEM_TYPE.ALLOW_EXCEPTIONS.ordinal(), group, policyItem); - } - removeAccesses(existingPolicyItems[POLICYITEM_TYPE.DENY_EXCEPTIONS.ordinal()], policyItem.getAccesses()); - break; - case ALLOW_EXCEPTIONS: - removeAccesses(existingPolicyItems[POLICYITEM_TYPE.ALLOW.ordinal()], policyItem.getAccesses()); - break; - case DENY_EXCEPTIONS: - removeAccesses(existingPolicyItems[POLICYITEM_TYPE.DENY.ordinal()], policyItem.getAccesses()); - break; - default: - break; - } - } - } - - for (RangerPolicy.RangerPolicyItem policyItem : appliedPolicyItems) { - List roles = policyItem.getRoles(); - for (String role : roles) { - RangerPolicy.RangerPolicyItem[] existingPolicyItems = existingRolePolicyItems.get(role); - - if (existingPolicyItems == null) { - // Should not get here - existingPolicyItems = new RangerPolicy.RangerPolicyItem[4]; - existingRolePolicyItems.put(role, existingPolicyItems); - } - - addPolicyItemForRole(existingPolicyItems, policyItemType.ordinal(), role, policyItem); - - switch (policyItemType) { - case ALLOW: - RangerPolicy.RangerPolicyItem denyPolicyItem = existingPolicyItems[POLICYITEM_TYPE.DENY.ordinal()]; - if (denyPolicyItem != null) { - removeAccesses(existingPolicyItems[POLICYITEM_TYPE.DENY.ordinal()], policyItem.getAccesses()); - addPolicyItemForRole(existingPolicyItems, POLICYITEM_TYPE.DENY_EXCEPTIONS.ordinal(), role, policyItem); - } - removeAccesses(existingPolicyItems[POLICYITEM_TYPE.ALLOW_EXCEPTIONS.ordinal()], policyItem.getAccesses()); - break; - case DENY: - RangerPolicy.RangerPolicyItem allowPolicyItem = existingPolicyItems[POLICYITEM_TYPE.ALLOW.ordinal()]; - if (allowPolicyItem != null) { - removeAccesses(existingPolicyItems[POLICYITEM_TYPE.ALLOW.ordinal()], policyItem.getAccesses()); - addPolicyItemForRole(existingPolicyItems, POLICYITEM_TYPE.ALLOW_EXCEPTIONS.ordinal(), role, policyItem); - } - removeAccesses(existingPolicyItems[POLICYITEM_TYPE.DENY_EXCEPTIONS.ordinal()], policyItem.getAccesses()); - break; - case ALLOW_EXCEPTIONS: - removeAccesses(existingPolicyItems[POLICYITEM_TYPE.ALLOW.ordinal()], policyItem.getAccesses()); - break; - case DENY_EXCEPTIONS: - removeAccesses(existingPolicyItems[POLICYITEM_TYPE.DENY.ordinal()], policyItem.getAccesses()); - break; - default: - break; - } - } - } - - if (LOG.isDebugEnabled()) { - LOG.debug("<== ServiceRESTUtil.applyPolicyItems()"); - } - } - - static private void mergePolicyItems(List appliedPolicyItems, - POLICYITEM_TYPE policyItemType, Map existingUserPolicyItems, - Map existingGroupPolicyItems, - Map existingRolePolicyItems ) { - if (LOG.isDebugEnabled()) { - LOG.debug("==> ServiceRESTUtil.mergePolicyItems()"); - } - for (RangerPolicy.RangerPolicyItem policyItem : appliedPolicyItems) { - List users = policyItem.getUsers(); - for (String user : users) { - RangerPolicy.RangerPolicyItem[] items = existingUserPolicyItems.get(user); - if (items == null) { - // Should not get here - LOG.warn("Should not have come here.."); - items = new RangerPolicy.RangerPolicyItem[4]; - existingUserPolicyItems.put(user, items); - } - addPolicyItemForUser(items, policyItemType.ordinal(), user, policyItem); - } - } - - for (RangerPolicy.RangerPolicyItem policyItem : appliedPolicyItems) { - List groups = policyItem.getGroups(); - for (String group : groups) { - RangerPolicy.RangerPolicyItem[] items = existingGroupPolicyItems.get(group); - if (items == null) { - // Should not get here - items = new RangerPolicy.RangerPolicyItem[4]; - existingGroupPolicyItems.put(group, items); - } - addPolicyItemForGroup(items, policyItemType.ordinal(), group, policyItem); - } - } - - for (RangerPolicy.RangerPolicyItem policyItem : appliedPolicyItems) { - List roles = policyItem.getRoles(); - for (String role : roles) { - RangerPolicy.RangerPolicyItem[] items = existingRolePolicyItems.get(role); - if (items == null) { - // Should not get here - items = new RangerPolicy.RangerPolicyItem[4]; - existingRolePolicyItems.put(role, items); - } - addPolicyItemForRole(items, policyItemType.ordinal(), role, policyItem); - } - } - - if (LOG.isDebugEnabled()) { - LOG.debug("<== ServiceRESTUtil.mergePolicyItems()"); - } - } - - static private void mergeProcessedPolicyItems(RangerPolicy existingPolicy, Map userPolicyItems, - Map groupPolicyItems, - Map rolePolicyItems) { - if (LOG.isDebugEnabled()) { - LOG.debug("==> ServiceRESTUtil.mergeProcessedPolicyItems()"); - } - - for (Map.Entry entry : userPolicyItems.entrySet()) { - RangerPolicy.RangerPolicyItem[] items = entry.getValue(); - - RangerPolicy.RangerPolicyItem item = null; - - item = items[POLICYITEM_TYPE.ALLOW.ordinal()]; - if (item != null) { - existingPolicy.addPolicyItem(item); - } - - item = items[POLICYITEM_TYPE.DENY.ordinal()]; - if (item != null) { - existingPolicy.addDenyPolicyItem(item); - } - - item = items[POLICYITEM_TYPE.ALLOW_EXCEPTIONS.ordinal()]; - if (item != null) { - existingPolicy.addAllowException(item); - } - - item = items[POLICYITEM_TYPE.DENY_EXCEPTIONS.ordinal()]; - if (item != null) { - existingPolicy.addDenyException(item); - } - } - - for (Map.Entry entry : groupPolicyItems.entrySet()) { - RangerPolicy.RangerPolicyItem[] items = entry.getValue(); - - RangerPolicy.RangerPolicyItem item = null; - - item = items[POLICYITEM_TYPE.ALLOW.ordinal()]; - if (item != null) { - existingPolicy.addPolicyItem(item); - } - - item = items[POLICYITEM_TYPE.DENY.ordinal()]; - if (item != null) { - existingPolicy.addDenyPolicyItem(item); - } - - item = items[POLICYITEM_TYPE.ALLOW_EXCEPTIONS.ordinal()]; - if (item != null) { - existingPolicy.addAllowException(item); - } - - item = items[POLICYITEM_TYPE.DENY_EXCEPTIONS.ordinal()]; - if (item != null) { - existingPolicy.addDenyException(item); - } - } - - for (Map.Entry entry : rolePolicyItems.entrySet()) { - RangerPolicy.RangerPolicyItem[] items = entry.getValue(); - - RangerPolicy.RangerPolicyItem item = null; - - item = items[POLICYITEM_TYPE.ALLOW.ordinal()]; - if (item != null) { - existingPolicy.addPolicyItem(item); - } - - item = items[POLICYITEM_TYPE.DENY.ordinal()]; - if (item != null) { - existingPolicy.addDenyPolicyItem(item); - } - - item = items[POLICYITEM_TYPE.ALLOW_EXCEPTIONS.ordinal()]; - if (item != null) { - existingPolicy.addAllowException(item); - } - - item = items[POLICYITEM_TYPE.DENY_EXCEPTIONS.ordinal()]; - if (item != null) { - existingPolicy.addDenyException(item); - } - } - - if (LOG.isDebugEnabled()) { - LOG.debug("<== ServiceRESTUtil.mergeProcessedPolicyItems()"); - } - } - - static private boolean addAccesses(RangerPolicy.RangerPolicyItem policyItem, List accesses) { - if (LOG.isDebugEnabled()) { - LOG.debug("==> ServiceRESTUtil.addAccesses()"); - } - - boolean ret = false; - - for (RangerPolicy.RangerPolicyItemAccess access : accesses) { - RangerPolicy.RangerPolicyItemAccess policyItemAccess = null; - String accessType = access.getType(); - - for (RangerPolicy.RangerPolicyItemAccess itemAccess : policyItem.getAccesses()) { - if (StringUtils.equals(itemAccess.getType(), accessType)) { - policyItemAccess = itemAccess; - break; - } - } - - if (policyItemAccess != null) { - if (!policyItemAccess.getIsAllowed()) { - policyItemAccess.setIsAllowed(Boolean.TRUE); - ret = true; - } - } else { - policyItem.addAccess(new RangerPolicy.RangerPolicyItemAccess(accessType, Boolean.TRUE)); - ret = true; - } - } - - if (LOG.isDebugEnabled()) { - LOG.debug("<== ServiceRESTUtil.addAccesses() " + ret); - } - return ret; - } - - static private boolean removeAccesses(RangerPolicy.RangerPolicyItem policyItem, List accesses) { - if (LOG.isDebugEnabled()) { - LOG.debug("==> ServiceRESTUtil.removeAccesses()"); - } - - boolean ret = false; - - if (policyItem != null) { - for (RangerPolicy.RangerPolicyItemAccess access : accesses) { - String accessType = access.getType(); - - int numOfAccesses = policyItem.getAccesses().size(); - - for (int i = 0; i < numOfAccesses; i++) { - RangerPolicy.RangerPolicyItemAccess itemAccess = policyItem.getAccesses().get(i); - - if (StringUtils.equals(itemAccess.getType(), accessType)) { - policyItem.getAccesses().remove(i); - numOfAccesses--; - i--; - - ret = true; - } - } - } - } - if (LOG.isDebugEnabled()) { - LOG.debug("<== ServiceRESTUtil.removeAccesses() " + ret); - } - return ret; - } - - static private void compactPolicy(RangerPolicy policy) { - policy.setPolicyItems(mergePolicyItems(policy.getPolicyItems())); - policy.setDenyPolicyItems(mergePolicyItems(policy.getDenyPolicyItems())); - policy.setAllowExceptions(mergePolicyItems(policy.getAllowExceptions())); - policy.setDenyExceptions(mergePolicyItems(policy.getDenyExceptions())); - } - - static private List mergePolicyItems(List policyItems) { - List ret = new ArrayList(); - - if (CollectionUtils.isNotEmpty(policyItems)) { - Map matchedPolicyItems = new HashMap(); - - for (RangerPolicy.RangerPolicyItem policyItem : policyItems) { - if((CollectionUtils.isEmpty(policyItem.getUsers()) && CollectionUtils.isEmpty(policyItem.getGroups()) && CollectionUtils.isEmpty(policyItem.getRoles())) || - (CollectionUtils.isEmpty(policyItem.getAccesses()) && !policyItem.getDelegateAdmin())) { - continue; - } - - if (policyItem.getConditions().size() > 1) { - ret.add(policyItem); - continue; - } - TreeSet accesses = new TreeSet(); - - for (RangerPolicy.RangerPolicyItemAccess access : policyItem.getAccesses()) { - accesses.add(access.getType()); - } - if (policyItem.getDelegateAdmin()) { - accesses.add("delegateAdmin"); - } - - String allAccessesString = accesses.toString(); - - RangerPolicy.RangerPolicyItem matchingPolicyItem = matchedPolicyItems.get(allAccessesString); - - if (matchingPolicyItem != null) { - addDistinctUsers(policyItem.getUsers(), matchingPolicyItem); - addDistinctGroups(policyItem.getGroups(), matchingPolicyItem); - addDistinctRoles(policyItem.getRoles(), matchingPolicyItem); - } else { - matchedPolicyItems.put(allAccessesString, policyItem); - } - } - - for (Map.Entry entry : matchedPolicyItems.entrySet()) { - ret.add(entry.getValue()); - } - } - - return ret; - } - - static void addPolicyItemForUser(RangerPolicy.RangerPolicyItem[] items, int typeOfItems, String user, RangerPolicy.RangerPolicyItem policyItem) { - - if (items[typeOfItems] == null) { - RangerPolicy.RangerPolicyItem newItem = new RangerPolicy.RangerPolicyItem(); - newItem.addUser(user); - - items[typeOfItems] = newItem; - } + policyItem.setDelegateAdmin(grantRequest.getDelegateAdmin()); + policyItem.addUsers(grantRequest.getUsers()); + policyItem.addGroups(grantRequest.getGroups()); + policyItem.addRoles(grantRequest.getRoles()); - addAccesses(items[typeOfItems], policyItem.getAccesses()); - - if (policyItem.getDelegateAdmin()) { - items[typeOfItems].setDelegateAdmin(Boolean.TRUE); - } - } + List accesses = new ArrayList<>(); - static void addPolicyItemForGroup(RangerPolicy.RangerPolicyItem[] items, int typeOfItems, String group, RangerPolicy.RangerPolicyItem policyItem) { + for (String accessType : grantRequest.getAccessTypes()) { + accesses.add(new RangerPolicyItemAccess(accessType, true)); + } - if (items[typeOfItems] == null) { - RangerPolicy.RangerPolicyItem newItem = new RangerPolicy.RangerPolicyItem(); - newItem.addGroup(group); + policyItem.setAccesses(accesses); - items[typeOfItems] = newItem; - } + appliedPolicy.addPolicyItem(policyItem); - addAccesses(items[typeOfItems], policyItem.getAccesses()); - - if (policyItem.getDelegateAdmin()) { - items[typeOfItems].setDelegateAdmin(Boolean.TRUE); - } - } - - static void addPolicyItemForRole(RangerPolicy.RangerPolicyItem[] items, int typeOfItems, String role, RangerPolicy.RangerPolicyItem policyItem) { - - if (items[typeOfItems] == null) { - RangerPolicy.RangerPolicyItem newItem = new RangerPolicy.RangerPolicyItem(); - newItem.addRole(role); - - items[typeOfItems] = newItem; - } - - addAccesses(items[typeOfItems], policyItem.getAccesses()); - - if (policyItem.getDelegateAdmin()) { - items[typeOfItems].setDelegateAdmin(Boolean.TRUE); - } - } - - static private void addDistinctUsers(List users, RangerPolicy.RangerPolicyItem policyItem) { - for (String user : users) { - if (! policyItem.getUsers().contains(user)) { - policyItem.addUser(user); - } - } - } + processApplyPolicy(policy, appliedPolicy); - static private void addDistinctGroups(List groups, RangerPolicy.RangerPolicyItem policyItem) { - for (String group : groups) { - if (! policyItem.getGroups().contains(group)) { - policyItem.addGroup(group); - } - } - } + boolean policyUpdated = true; - static private void addDistinctRoles(List roles, RangerPolicy.RangerPolicyItem policyItem) { - for (String role : roles) { - if (! policyItem.getRoles().contains(role)) { - policyItem.addRole(role); - } - } - } + LOG.debug("<== ServiceRESTUtil.processGrantRequest() : {}", policyUpdated); - static private boolean removeUsersGroupsAndRolesFromPolicy(RangerPolicy policy, Set users, Set groups, Set roles) { - boolean policyUpdated = false; + return policyUpdated; + } - List policyItems = policy.getPolicyItems(); + public static boolean processRevokeRequest(RangerPolicy existingRangerPolicy, GrantRevokeRequest revokeRequest) { + LOG.debug("==> ServiceRESTUtil.processRevokeRequest()"); - int numOfItems = policyItems.size(); + boolean policyUpdated; - for(int i = 0; i < numOfItems; i++) { - RangerPolicy.RangerPolicyItem policyItem = policyItems.get(i); + // remove all existing privileges for users and groups + if (revokeRequest.getReplaceExistingPermissions()) { + policyUpdated = removeUsersGroupsAndRolesFromPolicy(existingRangerPolicy, revokeRequest.getUsers(), revokeRequest.getGroups(), revokeRequest.getRoles()); + } else { + //Build a policy and set up policyItem in it to mimic revoke request + RangerPolicy appliedRangerPolicy = new RangerPolicy(); + RangerPolicyItem appliedRangerPolicyItem = new RangerPolicyItem(); - if(CollectionUtils.containsAny(policyItem.getUsers(), users)) { - policyItem.getUsers().removeAll(users); + appliedRangerPolicyItem.setDelegateAdmin(revokeRequest.getDelegateAdmin()); + appliedRangerPolicyItem.addUsers(revokeRequest.getUsers()); + appliedRangerPolicyItem.addGroups(revokeRequest.getGroups()); + appliedRangerPolicyItem.addRoles(revokeRequest.getRoles()); - policyUpdated = true; - } + List appliedRangerPolicyItemAccess = new ArrayList<>(); - if(CollectionUtils.containsAny(policyItem.getGroups(), groups)) { - policyItem.getGroups().removeAll(groups); + for (String accessType : revokeRequest.getAccessTypes()) { + appliedRangerPolicyItemAccess.add(new RangerPolicyItemAccess(accessType, false)); + } - policyUpdated = true; - } + appliedRangerPolicyItem.setAccesses(appliedRangerPolicyItemAccess); - if(CollectionUtils.containsAny(policyItem.getRoles(), roles)) { - policyItem.getRoles().removeAll(roles); + appliedRangerPolicy.addPolicyItem(appliedRangerPolicyItem); - policyUpdated = true; - } + List appliedRangerPolicyItems = appliedRangerPolicy.getPolicyItems(); - if(CollectionUtils.isEmpty(policyItem.getUsers()) && CollectionUtils.isEmpty(policyItem.getGroups()) && CollectionUtils.isEmpty(policyItem.getRoles())) { - policyItems.remove(i); - numOfItems--; - i--; + //processApplyPolicyForItemType(existingRangerPolicy, appliedRangerPolicy, PolicyTermType.ALLOW); + if (CollectionUtils.isNotEmpty(appliedRangerPolicyItems)) { + Set users = new HashSet<>(); + Set groups = new HashSet<>(); + Set roles = new HashSet<>(); - policyUpdated = true; - } - } + Map userPolicyItems = new HashMap<>(); + Map groupPolicyItems = new HashMap<>(); + Map rolePolicyItems = new HashMap<>(); - return policyUpdated; - } + // Extract users, groups, and roles specified in appliedPolicy items + extractUsersGroupsAndRoles(appliedRangerPolicyItems, users, groups, roles); - static boolean containsRangerCondition(RangerPolicy policy) { - boolean ret = false; + // Split existing policyItems for users, groups, and roles extracted from appliedPolicyItem into userPolicyItems, groupPolicyItems and rolePolicyItems + splitExistingPolicyItems(existingRangerPolicy, users, userPolicyItems, groups, groupPolicyItems, roles, rolePolicyItems); - if (LOG.isDebugEnabled()) { - LOG.debug("==> ServiceRESTUtil.containsRangerCondition(" + policy +")"); - } + for (RangerPolicyItem tempPolicyItem : appliedRangerPolicyItems) { + List appliedPolicyItemsUser = tempPolicyItem.getUsers(); - if (policy != null) { - if (CollectionUtils.isNotEmpty(policy.getConditions())) { - ret = true; - } else { - List allItems = new ArrayList(); + for (String user : appliedPolicyItemsUser) { + RangerPolicyItem[] rangerPolicyItems = userPolicyItems.get(user); - allItems.addAll(policy.getPolicyItems()); - allItems.addAll(policy.getDenyPolicyItems()); - allItems.addAll(policy.getAllowExceptions()); - allItems.addAll(policy.getDenyExceptions()); - - for (RangerPolicy.RangerPolicyItem policyItem : allItems) { - if (!policyItem.getConditions().isEmpty()) { - ret = true; - break; - } - } - } - } - - if (LOG.isDebugEnabled()) { - LOG.debug("<== ServiceRESTUtil.containsRangerCondition(" + policy +"): " + ret); - } - - return ret; - } + if (rangerPolicyItems != null && rangerPolicyItems.length > 0) { + if (rangerPolicyItems[PolicyTermType.ALLOW.ordinal()] != null) { + removeAccesses(rangerPolicyItems[PolicyTermType.ALLOW.ordinal()], tempPolicyItem.getAccesses()); + + if (!CollectionUtils.isEmpty(rangerPolicyItems[PolicyTermType.ALLOW.ordinal()].getAccesses())) { + rangerPolicyItems[PolicyTermType.ALLOW.ordinal()].setDelegateAdmin(revokeRequest.getDelegateAdmin()); + } else { + rangerPolicyItems[PolicyTermType.ALLOW.ordinal()].setDelegateAdmin(Boolean.FALSE); + } + } + + if (rangerPolicyItems[PolicyTermType.DENY_EXCEPTIONS.ordinal()] != null) { + removeAccesses(rangerPolicyItems[PolicyTermType.DENY_EXCEPTIONS.ordinal()], tempPolicyItem.getAccesses()); + rangerPolicyItems[PolicyTermType.DENY_EXCEPTIONS.ordinal()].setDelegateAdmin(Boolean.FALSE); + } + } + } + } + + for (RangerPolicyItem tempPolicyItem : appliedRangerPolicyItems) { + List appliedPolicyItemsGroup = tempPolicyItem.getGroups(); + + for (String group : appliedPolicyItemsGroup) { + RangerPolicyItem[] rangerPolicyItems = groupPolicyItems.get(group); + + if (rangerPolicyItems != null && rangerPolicyItems.length > 0) { + if (rangerPolicyItems[PolicyTermType.ALLOW.ordinal()] != null) { + removeAccesses(rangerPolicyItems[PolicyTermType.ALLOW.ordinal()], tempPolicyItem.getAccesses()); + + if (!CollectionUtils.isEmpty(rangerPolicyItems[PolicyTermType.ALLOW.ordinal()].getAccesses())) { + rangerPolicyItems[PolicyTermType.ALLOW.ordinal()].setDelegateAdmin(revokeRequest.getDelegateAdmin()); + } else { + rangerPolicyItems[PolicyTermType.ALLOW.ordinal()].setDelegateAdmin(Boolean.FALSE); + } + } + + if (rangerPolicyItems[PolicyTermType.DENY_EXCEPTIONS.ordinal()] != null) { + removeAccesses(rangerPolicyItems[PolicyTermType.DENY_EXCEPTIONS.ordinal()], tempPolicyItem.getAccesses()); + rangerPolicyItems[PolicyTermType.DENY_EXCEPTIONS.ordinal()].setDelegateAdmin(Boolean.FALSE); + } + } + } + } + + for (RangerPolicyItem tempPolicyItem : appliedRangerPolicyItems) { + List appliedPolicyItemsRole = tempPolicyItem.getRoles(); + + for (String role : appliedPolicyItemsRole) { + RangerPolicyItem[] rangerPolicyItems = rolePolicyItems.get(role); + + if (rangerPolicyItems != null && rangerPolicyItems.length > 0) { + if (rangerPolicyItems[PolicyTermType.ALLOW.ordinal()] != null) { + removeAccesses(rangerPolicyItems[PolicyTermType.ALLOW.ordinal()], tempPolicyItem.getAccesses()); + + if (!CollectionUtils.isEmpty(rangerPolicyItems[PolicyTermType.ALLOW.ordinal()].getAccesses())) { + rangerPolicyItems[PolicyTermType.ALLOW.ordinal()].setDelegateAdmin(revokeRequest.getDelegateAdmin()); + } else { + rangerPolicyItems[PolicyTermType.ALLOW.ordinal()].setDelegateAdmin(Boolean.FALSE); + } + } + + if (rangerPolicyItems[PolicyTermType.DENY_EXCEPTIONS.ordinal()] != null) { + removeAccesses(rangerPolicyItems[PolicyTermType.DENY_EXCEPTIONS.ordinal()], tempPolicyItem.getAccesses()); + rangerPolicyItems[PolicyTermType.DENY_EXCEPTIONS.ordinal()].setDelegateAdmin(Boolean.FALSE); + } + } + } + } + + // Add modified/new policyItems back to existing policy + mergeProcessedPolicyItems(existingRangerPolicy, userPolicyItems, groupPolicyItems, rolePolicyItems); + compactPolicy(existingRangerPolicy); + } + + policyUpdated = true; + } + + LOG.debug("<== ServiceRESTUtil.processRevokeRequest() : {}", policyUpdated); + + return policyUpdated; + } + + public static void processApplyPolicy(RangerPolicy existingPolicy, RangerPolicy appliedPolicy) { + LOG.debug("==> ServiceRESTUtil.processApplyPolicy()"); + + // Check if applied policy or existing policy contains any conditions + if (ServiceRESTUtil.containsRangerCondition(existingPolicy) || ServiceRESTUtil.containsRangerCondition(appliedPolicy)) { + LOG.info("Applied policy [{}] or existing policy [{}] contains condition(s). Combining two policies.", appliedPolicy, existingPolicy); + + combinePolicy(existingPolicy, appliedPolicy); + } else { + processApplyPolicyForItemType(existingPolicy, appliedPolicy, PolicyTermType.ALLOW); + processApplyPolicyForItemType(existingPolicy, appliedPolicy, PolicyTermType.DENY); + processApplyPolicyForItemType(existingPolicy, appliedPolicy, PolicyTermType.ALLOW_EXCEPTIONS); + processApplyPolicyForItemType(existingPolicy, appliedPolicy, PolicyTermType.DENY_EXCEPTIONS); + } + + LOG.debug("<== ServiceRESTUtil.processApplyPolicy()"); + } + + public static void mergeExactMatchPolicyForResource(RangerPolicy existingPolicy, RangerPolicy appliedPolicy) { + LOG.debug("==> ServiceRESTUtil.mergeExactMatchPolicyForResource()"); + + mergeExactMatchPolicyForItemType(existingPolicy, appliedPolicy, PolicyTermType.ALLOW); + mergeExactMatchPolicyForItemType(existingPolicy, appliedPolicy, PolicyTermType.DENY); + mergeExactMatchPolicyForItemType(existingPolicy, appliedPolicy, PolicyTermType.ALLOW_EXCEPTIONS); + mergeExactMatchPolicyForItemType(existingPolicy, appliedPolicy, PolicyTermType.DENY_EXCEPTIONS); + + LOG.debug("<== ServiceRESTUtil.mergeExactMatchPolicyForResource()"); + } + + static void addPolicyItemForUser(RangerPolicyItem[] items, int typeOfItems, String user, RangerPolicyItem policyItem) { + if (items[typeOfItems] == null) { + RangerPolicyItem newItem = new RangerPolicyItem(); + + newItem.addUser(user); + + items[typeOfItems] = newItem; + } + + addAccesses(items[typeOfItems], policyItem.getAccesses()); + + if (policyItem.getDelegateAdmin()) { + items[typeOfItems].setDelegateAdmin(Boolean.TRUE); + } + } + + static void addPolicyItemForGroup(RangerPolicyItem[] items, int typeOfItems, String group, RangerPolicyItem policyItem) { + if (items[typeOfItems] == null) { + RangerPolicyItem newItem = new RangerPolicyItem(); + + newItem.addGroup(group); + + items[typeOfItems] = newItem; + } + + addAccesses(items[typeOfItems], policyItem.getAccesses()); + + if (policyItem.getDelegateAdmin()) { + items[typeOfItems].setDelegateAdmin(Boolean.TRUE); + } + } + + static void addPolicyItemForRole(RangerPolicyItem[] items, int typeOfItems, String role, RangerPolicyItem policyItem) { + if (items[typeOfItems] == null) { + RangerPolicyItem newItem = new RangerPolicyItem(); + + newItem.addRole(role); + + items[typeOfItems] = newItem; + } + + addAccesses(items[typeOfItems], policyItem.getAccesses()); + + if (policyItem.getDelegateAdmin()) { + items[typeOfItems].setDelegateAdmin(Boolean.TRUE); + } + } + + static boolean containsRangerCondition(RangerPolicy policy) { + boolean ret = false; + + LOG.debug("==> ServiceRESTUtil.containsRangerCondition({})", policy); + + if (policy != null) { + if (CollectionUtils.isNotEmpty(policy.getConditions())) { + ret = true; + } else { + List allItems = new ArrayList<>(); + + allItems.addAll(policy.getPolicyItems()); + allItems.addAll(policy.getDenyPolicyItems()); + allItems.addAll(policy.getAllowExceptions()); + allItems.addAll(policy.getDenyExceptions()); + + for (RangerPolicyItem policyItem : allItems) { + if (!policyItem.getConditions().isEmpty()) { + ret = true; + break; + } + } + } + } + + LOG.debug("<== ServiceRESTUtil.containsRangerCondition({}):{}", policy, ret); + + return ret; + } + + private static void combinePolicy(RangerPolicy existingPolicy, RangerPolicy appliedPolicy) { + combinePolicyItems(existingPolicy, appliedPolicy, PolicyTermType.ALLOW); + combinePolicyItems(existingPolicy, appliedPolicy, PolicyTermType.DENY); + combinePolicyItems(existingPolicy, appliedPolicy, PolicyTermType.ALLOW_EXCEPTIONS); + combinePolicyItems(existingPolicy, appliedPolicy, PolicyTermType.DENY_EXCEPTIONS); + } + + private static void combinePolicyItems(RangerPolicy existingPolicy, RangerPolicy appliedPolicy, PolicyTermType polityItemType) { + List existingPolicyItems; + List appliedPolicyItems; + + switch (polityItemType) { + case ALLOW: + existingPolicyItems = existingPolicy.getPolicyItems(); + appliedPolicyItems = appliedPolicy.getPolicyItems(); + break; + case DENY: + existingPolicyItems = existingPolicy.getDenyPolicyItems(); + appliedPolicyItems = appliedPolicy.getDenyPolicyItems(); + break; + case ALLOW_EXCEPTIONS: + existingPolicyItems = existingPolicy.getAllowExceptions(); + appliedPolicyItems = appliedPolicy.getAllowExceptions(); + break; + case DENY_EXCEPTIONS: + existingPolicyItems = existingPolicy.getDenyExceptions(); + appliedPolicyItems = appliedPolicy.getDenyExceptions(); + break; + default: + existingPolicyItems = null; + appliedPolicyItems = null; + break; + } + + if (CollectionUtils.isNotEmpty(appliedPolicyItems)) { + if (CollectionUtils.isNotEmpty(existingPolicyItems)) { + List itemsToAdd = new ArrayList<>(); + + for (RangerPolicyItem appliedPolicyItem : appliedPolicyItems) { + if (!existingPolicyItems.contains(appliedPolicyItem)) { + itemsToAdd.add(appliedPolicyItem); + } + } + + existingPolicyItems.addAll(itemsToAdd); + } else { + switch (polityItemType) { + case ALLOW: + existingPolicy.setPolicyItems(appliedPolicyItems); + break; + case DENY: + existingPolicy.setDenyPolicyItems(appliedPolicyItems); + break; + case ALLOW_EXCEPTIONS: + existingPolicy.setAllowExceptions(appliedPolicyItems); + break; + case DENY_EXCEPTIONS: + existingPolicy.setDenyExceptions(appliedPolicyItems); + break; + } + } + } + } + + private static void processApplyPolicyForItemType(RangerPolicy existingPolicy, RangerPolicy appliedPolicy, PolicyTermType policyItemType) { + LOG.debug("==> ServiceRESTUtil.processApplyPolicyForItemType()"); + + List appliedPolicyItems = null; + + switch (policyItemType) { + case ALLOW: + appliedPolicyItems = appliedPolicy.getPolicyItems(); + break; + case DENY: + appliedPolicyItems = appliedPolicy.getDenyPolicyItems(); + break; + case ALLOW_EXCEPTIONS: + appliedPolicyItems = appliedPolicy.getAllowExceptions(); + break; + case DENY_EXCEPTIONS: + appliedPolicyItems = appliedPolicy.getDenyExceptions(); + break; + default: + LOG.warn("processApplyPolicyForItemType(): invalid policyItemType={}", policyItemType); + } + + if (CollectionUtils.isNotEmpty(appliedPolicyItems)) { + Set users = new HashSet<>(); + Set groups = new HashSet<>(); + Set roles = new HashSet<>(); + + Map userPolicyItems = new HashMap<>(); + Map groupPolicyItems = new HashMap<>(); + Map rolePolicyItems = new HashMap<>(); + + // Extract users, groups, and roles specified in appliedPolicy items + extractUsersGroupsAndRoles(appliedPolicyItems, users, groups, roles); + + // Split existing policyItems for users, groups, and roles extracted from appliedPolicyItem into userPolicyItems, groupPolicyItems, and rolePolicyItems + splitExistingPolicyItems(existingPolicy, users, userPolicyItems, groups, groupPolicyItems, roles, rolePolicyItems); + + // Apply policyItems of given type in appliedPolicy to policyItems extracted from existingPolicy + applyPolicyItems(appliedPolicyItems, policyItemType, userPolicyItems, groupPolicyItems, rolePolicyItems); + + // Add modified/new policyItems back to existing policy + mergeProcessedPolicyItems(existingPolicy, userPolicyItems, groupPolicyItems, rolePolicyItems); + + compactPolicy(existingPolicy); + } + + LOG.debug("<== ServiceRESTUtil.processApplyPolicyForItemType()"); + } + + private static void mergeExactMatchPolicyForItemType(RangerPolicy existingPolicy, RangerPolicy appliedPolicy, PolicyTermType policyItemType) { + LOG.debug("==> ServiceRESTUtil.mergeExactMatchPolicyForItemType()"); + List appliedPolicyItems = null; + + switch (policyItemType) { + case ALLOW: + appliedPolicyItems = appliedPolicy.getPolicyItems(); + break; + case DENY: + appliedPolicyItems = appliedPolicy.getDenyPolicyItems(); + break; + case ALLOW_EXCEPTIONS: + appliedPolicyItems = appliedPolicy.getAllowExceptions(); + break; + case DENY_EXCEPTIONS: + appliedPolicyItems = appliedPolicy.getDenyExceptions(); + break; + default: + LOG.warn("mergeExactMatchPolicyForItemType(): invalid policyItemType={}", policyItemType); + } + + if (CollectionUtils.isNotEmpty(appliedPolicyItems)) { + Set users = new HashSet<>(); + Set groups = new HashSet<>(); + Set roles = new HashSet<>(); + + Map userPolicyItems = new HashMap<>(); + Map groupPolicyItems = new HashMap<>(); + Map rolePolicyItems = new HashMap<>(); + + // Extract users and groups specified in appliedPolicy items + extractUsersGroupsAndRoles(appliedPolicyItems, users, groups, roles); + + // Split existing policyItems for users and groups extracted from appliedPolicyItem into userPolicyItems and groupPolicyItems + splitExistingPolicyItems(existingPolicy, users, userPolicyItems, groups, groupPolicyItems, roles, rolePolicyItems); + + // Apply policyItems of given type in appliedPlicy to policyItems extracted from existingPolicy + mergePolicyItems(appliedPolicyItems, policyItemType, userPolicyItems, groupPolicyItems, rolePolicyItems); + + // Add modified/new policyItems back to existing policy + mergeProcessedPolicyItems(existingPolicy, userPolicyItems, groupPolicyItems, rolePolicyItems); + + compactPolicy(existingPolicy); + } + + LOG.debug("<== ServiceRESTUtil.mergeExactMatchPolicyForItemType()"); + } + + private static void extractUsersGroupsAndRoles(List policyItems, Set users, Set groups, Set roles) { + LOG.debug("==> ServiceRESTUtil.extractUsersGroupsAndRoles()"); + + if (CollectionUtils.isNotEmpty(policyItems)) { + for (RangerPolicyItem policyItem : policyItems) { + if (CollectionUtils.isNotEmpty(policyItem.getUsers())) { + users.addAll(policyItem.getUsers()); + } + + if (CollectionUtils.isNotEmpty(policyItem.getGroups())) { + groups.addAll(policyItem.getGroups()); + } + + if (CollectionUtils.isNotEmpty(policyItem.getRoles())) { + roles.addAll(policyItem.getRoles()); + } + } + } + + LOG.debug("<== ServiceRESTUtil.extractUsersGroupsAndRoles()"); + } + + private static void splitExistingPolicyItems(RangerPolicy existingPolicy, Set users, Map userPolicyItems, Set groups, Map groupPolicyItems, Set roles, Map rolePolicyItems) { + if (existingPolicy == null || users == null || userPolicyItems == null || groups == null || groupPolicyItems == null || roles == null || rolePolicyItems == null) { + return; + } + + LOG.debug("==> ServiceRESTUtil.splitExistingPolicyItems()"); + + List allowItems = existingPolicy.getPolicyItems(); + List denyItems = existingPolicy.getDenyPolicyItems(); + List allowExceptionItems = existingPolicy.getAllowExceptions(); + List denyExceptionItems = existingPolicy.getDenyExceptions(); + + for (String user : users) { + RangerPolicyItem[] value = userPolicyItems.computeIfAbsent(user, k -> new RangerPolicyItem[4]); + RangerPolicyItem policyItem; + + policyItem = splitAndGetConsolidatedPolicyItemForUser(allowItems, user); + value[PolicyTermType.ALLOW.ordinal()] = policyItem; + policyItem = splitAndGetConsolidatedPolicyItemForUser(denyItems, user); + value[PolicyTermType.DENY.ordinal()] = policyItem; + policyItem = splitAndGetConsolidatedPolicyItemForUser(allowExceptionItems, user); + value[PolicyTermType.ALLOW_EXCEPTIONS.ordinal()] = policyItem; + policyItem = splitAndGetConsolidatedPolicyItemForUser(denyExceptionItems, user); + value[PolicyTermType.DENY_EXCEPTIONS.ordinal()] = policyItem; + } + + for (String group : groups) { + RangerPolicyItem[] value = groupPolicyItems.computeIfAbsent(group, k -> new RangerPolicyItem[4]); + RangerPolicyItem policyItem; + + policyItem = splitAndGetConsolidatedPolicyItemForGroup(allowItems, group); + value[PolicyTermType.ALLOW.ordinal()] = policyItem; + policyItem = splitAndGetConsolidatedPolicyItemForGroup(denyItems, group); + value[PolicyTermType.DENY.ordinal()] = policyItem; + policyItem = splitAndGetConsolidatedPolicyItemForGroup(allowExceptionItems, group); + value[PolicyTermType.ALLOW_EXCEPTIONS.ordinal()] = policyItem; + policyItem = splitAndGetConsolidatedPolicyItemForGroup(denyExceptionItems, group); + value[PolicyTermType.DENY_EXCEPTIONS.ordinal()] = policyItem; + } + for (String role : roles) { + RangerPolicyItem[] value = rolePolicyItems.computeIfAbsent(role, k -> new RangerPolicyItem[4]); + RangerPolicyItem policyItem; + + policyItem = splitAndGetConsolidatedPolicyItemForRole(allowItems, role); + value[PolicyTermType.ALLOW.ordinal()] = policyItem; + policyItem = splitAndGetConsolidatedPolicyItemForRole(denyItems, role); + value[PolicyTermType.DENY.ordinal()] = policyItem; + policyItem = splitAndGetConsolidatedPolicyItemForRole(allowExceptionItems, role); + value[PolicyTermType.ALLOW_EXCEPTIONS.ordinal()] = policyItem; + policyItem = splitAndGetConsolidatedPolicyItemForRole(denyExceptionItems, role); + value[PolicyTermType.DENY_EXCEPTIONS.ordinal()] = policyItem; + } + + LOG.debug("<== ServiceRESTUtil.splitExistingPolicyItems()"); + } + + private static RangerPolicyItem splitAndGetConsolidatedPolicyItemForUser(List policyItems, String user) { + LOG.debug("==> ServiceRESTUtil.splitAndGetConsolidatedPolicyItemForUser()"); + + RangerPolicyItem ret = null; + + if (CollectionUtils.isNotEmpty(policyItems)) { + for (RangerPolicyItem policyItem : policyItems) { + List users = policyItem.getUsers(); + + if (users.contains(user)) { + if (ret == null) { + ret = new RangerPolicyItem(); + } + + ret.addUser(user); + + if (policyItem.getDelegateAdmin()) { + ret.setDelegateAdmin(Boolean.TRUE); + } + + addAccesses(ret, policyItem.getAccesses()); + + // Remove this user from existingPolicyItem + users.remove(user); + } + } + } + + LOG.debug("<== ServiceRESTUtil.splitAndGetConsolidatedPolicyItemForUser()"); + + return ret; + } + + private static RangerPolicyItem splitAndGetConsolidatedPolicyItemForGroup(List policyItems, String group) { + LOG.debug("==> ServiceRESTUtil.splitAndGetConsolidatedPolicyItemForGroup()"); + + RangerPolicyItem ret = null; + + if (CollectionUtils.isNotEmpty(policyItems)) { + for (RangerPolicyItem policyItem : policyItems) { + List groups = policyItem.getGroups(); + + if (groups.contains(group)) { + if (ret == null) { + ret = new RangerPolicyItem(); + } + + ret.addGroup(group); + + if (policyItem.getDelegateAdmin()) { + ret.setDelegateAdmin(Boolean.TRUE); + } + + addAccesses(ret, policyItem.getAccesses()); + + // Remove this group from existingPolicyItem + groups.remove(group); + } + } + } + + LOG.debug("<== ServiceRESTUtil.splitAndGetConsolidatedPolicyItemForGroup()"); + + return ret; + } + + private static RangerPolicyItem splitAndGetConsolidatedPolicyItemForRole(List policyItems, String role) { + LOG.debug("==> ServiceRESTUtil.splitAndGetConsolidatedPolicyItemForGroup()"); + + RangerPolicyItem ret = null; + + if (CollectionUtils.isNotEmpty(policyItems)) { + for (RangerPolicyItem policyItem : policyItems) { + List roles = policyItem.getRoles(); + + if (roles.contains(role)) { + if (ret == null) { + ret = new RangerPolicyItem(); + } + + ret.addRole(role); + + if (policyItem.getDelegateAdmin()) { + ret.setDelegateAdmin(Boolean.TRUE); + } + + addAccesses(ret, policyItem.getAccesses()); + + // Remove this role from existingPolicyItem + roles.remove(role); + } + } + } + + LOG.debug("<== ServiceRESTUtil.splitAndGetConsolidatedPolicyItemForGroup()"); + + return ret; + } + + private static void applyPolicyItems(List appliedPolicyItems, PolicyTermType policyItemType, Map existingUserPolicyItems, Map existingGroupPolicyItems, Map existingRolePolicyItems) { + LOG.debug("==> ServiceRESTUtil.applyPolicyItems()"); + + for (RangerPolicyItem policyItem : appliedPolicyItems) { + List users = policyItem.getUsers(); + + for (String user : users) { + RangerPolicyItem[] existingPolicyItems = existingUserPolicyItems.get(user); + + if (existingPolicyItems == null) { + // Should not get here + LOG.warn("Should not have come here.."); + + existingPolicyItems = new RangerPolicyItem[4]; + + existingUserPolicyItems.put(user, existingPolicyItems); + } + + addPolicyItemForUser(existingPolicyItems, policyItemType.ordinal(), user, policyItem); + + switch (policyItemType) { + case ALLOW: + RangerPolicyItem denyPolicyItem = existingPolicyItems[PolicyTermType.DENY.ordinal()]; + + if (denyPolicyItem != null) { + removeAccesses(existingPolicyItems[PolicyTermType.DENY.ordinal()], policyItem.getAccesses()); + addPolicyItemForUser(existingPolicyItems, PolicyTermType.DENY_EXCEPTIONS.ordinal(), user, policyItem); + } + + removeAccesses(existingPolicyItems[PolicyTermType.ALLOW_EXCEPTIONS.ordinal()], policyItem.getAccesses()); + break; + case DENY: + RangerPolicyItem allowPolicyItem = existingPolicyItems[PolicyTermType.ALLOW.ordinal()]; + + if (allowPolicyItem != null) { + removeAccesses(existingPolicyItems[PolicyTermType.ALLOW.ordinal()], policyItem.getAccesses()); + addPolicyItemForUser(existingPolicyItems, PolicyTermType.ALLOW_EXCEPTIONS.ordinal(), user, policyItem); + } + + removeAccesses(existingPolicyItems[PolicyTermType.DENY_EXCEPTIONS.ordinal()], policyItem.getAccesses()); + break; + case ALLOW_EXCEPTIONS: + removeAccesses(existingPolicyItems[PolicyTermType.ALLOW.ordinal()], policyItem.getAccesses()); + break; + case DENY_EXCEPTIONS: + removeAccesses(existingPolicyItems[PolicyTermType.DENY.ordinal()], policyItem.getAccesses()); + break; + default: + LOG.warn("Should not have come here.."); + break; + } + } + } + + for (RangerPolicyItem policyItem : appliedPolicyItems) { + List groups = policyItem.getGroups(); + + for (String group : groups) { + RangerPolicyItem[] existingPolicyItems = existingGroupPolicyItems.computeIfAbsent(group, k -> new RangerPolicyItem[4]); + + // Should not get here + + addPolicyItemForGroup(existingPolicyItems, policyItemType.ordinal(), group, policyItem); + + switch (policyItemType) { + case ALLOW: + RangerPolicyItem denyPolicyItem = existingPolicyItems[PolicyTermType.DENY.ordinal()]; + + if (denyPolicyItem != null) { + removeAccesses(existingPolicyItems[PolicyTermType.DENY.ordinal()], policyItem.getAccesses()); + addPolicyItemForGroup(existingPolicyItems, PolicyTermType.DENY_EXCEPTIONS.ordinal(), group, policyItem); + } + + removeAccesses(existingPolicyItems[PolicyTermType.ALLOW_EXCEPTIONS.ordinal()], policyItem.getAccesses()); + break; + case DENY: + RangerPolicyItem allowPolicyItem = existingPolicyItems[PolicyTermType.ALLOW.ordinal()]; + + if (allowPolicyItem != null) { + removeAccesses(existingPolicyItems[PolicyTermType.ALLOW.ordinal()], policyItem.getAccesses()); + addPolicyItemForGroup(existingPolicyItems, PolicyTermType.ALLOW_EXCEPTIONS.ordinal(), group, policyItem); + } + + removeAccesses(existingPolicyItems[PolicyTermType.DENY_EXCEPTIONS.ordinal()], policyItem.getAccesses()); + break; + case ALLOW_EXCEPTIONS: + removeAccesses(existingPolicyItems[PolicyTermType.ALLOW.ordinal()], policyItem.getAccesses()); + break; + case DENY_EXCEPTIONS: + removeAccesses(existingPolicyItems[PolicyTermType.DENY.ordinal()], policyItem.getAccesses()); + break; + default: + break; + } + } + } + + for (RangerPolicyItem policyItem : appliedPolicyItems) { + List roles = policyItem.getRoles(); + + for (String role : roles) { + RangerPolicyItem[] existingPolicyItems = existingRolePolicyItems.computeIfAbsent(role, k -> new RangerPolicyItem[4]); + + // Should not get here + + addPolicyItemForRole(existingPolicyItems, policyItemType.ordinal(), role, policyItem); + + switch (policyItemType) { + case ALLOW: + RangerPolicyItem denyPolicyItem = existingPolicyItems[PolicyTermType.DENY.ordinal()]; + + if (denyPolicyItem != null) { + removeAccesses(existingPolicyItems[PolicyTermType.DENY.ordinal()], policyItem.getAccesses()); + addPolicyItemForRole(existingPolicyItems, PolicyTermType.DENY_EXCEPTIONS.ordinal(), role, policyItem); + } + + removeAccesses(existingPolicyItems[PolicyTermType.ALLOW_EXCEPTIONS.ordinal()], policyItem.getAccesses()); + break; + case DENY: + RangerPolicyItem allowPolicyItem = existingPolicyItems[PolicyTermType.ALLOW.ordinal()]; + + if (allowPolicyItem != null) { + removeAccesses(existingPolicyItems[PolicyTermType.ALLOW.ordinal()], policyItem.getAccesses()); + addPolicyItemForRole(existingPolicyItems, PolicyTermType.ALLOW_EXCEPTIONS.ordinal(), role, policyItem); + } + + removeAccesses(existingPolicyItems[PolicyTermType.DENY_EXCEPTIONS.ordinal()], policyItem.getAccesses()); + break; + case ALLOW_EXCEPTIONS: + removeAccesses(existingPolicyItems[PolicyTermType.ALLOW.ordinal()], policyItem.getAccesses()); + break; + case DENY_EXCEPTIONS: + removeAccesses(existingPolicyItems[PolicyTermType.DENY.ordinal()], policyItem.getAccesses()); + break; + default: + break; + } + } + } + + LOG.debug("<== ServiceRESTUtil.applyPolicyItems()"); + } + + private static void mergePolicyItems(List appliedPolicyItems, PolicyTermType policyItemType, Map existingUserPolicyItems, Map existingGroupPolicyItems, Map existingRolePolicyItems) { + LOG.debug("==> ServiceRESTUtil.mergePolicyItems()"); + + for (RangerPolicyItem policyItem : appliedPolicyItems) { + List users = policyItem.getUsers(); + + for (String user : users) { + RangerPolicyItem[] items = existingUserPolicyItems.get(user); + + if (items == null) { + // Should not get here + LOG.warn("Should not have come here.."); + + items = new RangerPolicyItem[4]; + + existingUserPolicyItems.put(user, items); + } + + addPolicyItemForUser(items, policyItemType.ordinal(), user, policyItem); + } + } + + for (RangerPolicyItem policyItem : appliedPolicyItems) { + List groups = policyItem.getGroups(); + + for (String group : groups) { + RangerPolicyItem[] items = existingGroupPolicyItems.computeIfAbsent(group, k -> new RangerPolicyItem[4]); + + // Should not get here + addPolicyItemForGroup(items, policyItemType.ordinal(), group, policyItem); + } + } + + for (RangerPolicyItem policyItem : appliedPolicyItems) { + List roles = policyItem.getRoles(); + + for (String role : roles) { + RangerPolicyItem[] items = existingRolePolicyItems.computeIfAbsent(role, k -> new RangerPolicyItem[4]); + + // Should not get here + addPolicyItemForRole(items, policyItemType.ordinal(), role, policyItem); + } + } + + LOG.debug("<== ServiceRESTUtil.mergePolicyItems()"); + } + + private static void mergeProcessedPolicyItems(RangerPolicy existingPolicy, Map userPolicyItems, Map groupPolicyItems, Map rolePolicyItems) { + LOG.debug("==> ServiceRESTUtil.mergeProcessedPolicyItems()"); + + for (Map.Entry entry : userPolicyItems.entrySet()) { + RangerPolicyItem[] items = entry.getValue(); + RangerPolicyItem item; + + item = items[PolicyTermType.ALLOW.ordinal()]; + if (item != null) { + existingPolicy.addPolicyItem(item); + } + + item = items[PolicyTermType.DENY.ordinal()]; + if (item != null) { + existingPolicy.addDenyPolicyItem(item); + } + + item = items[PolicyTermType.ALLOW_EXCEPTIONS.ordinal()]; + if (item != null) { + existingPolicy.addAllowException(item); + } + + item = items[PolicyTermType.DENY_EXCEPTIONS.ordinal()]; + if (item != null) { + existingPolicy.addDenyException(item); + } + } + + for (Map.Entry entry : groupPolicyItems.entrySet()) { + RangerPolicyItem[] items = entry.getValue(); + RangerPolicyItem item; + + item = items[PolicyTermType.ALLOW.ordinal()]; + if (item != null) { + existingPolicy.addPolicyItem(item); + } + + item = items[PolicyTermType.DENY.ordinal()]; + if (item != null) { + existingPolicy.addDenyPolicyItem(item); + } + + item = items[PolicyTermType.ALLOW_EXCEPTIONS.ordinal()]; + if (item != null) { + existingPolicy.addAllowException(item); + } + + item = items[PolicyTermType.DENY_EXCEPTIONS.ordinal()]; + if (item != null) { + existingPolicy.addDenyException(item); + } + } + + for (Map.Entry entry : rolePolicyItems.entrySet()) { + RangerPolicyItem[] items = entry.getValue(); + RangerPolicyItem item; + + item = items[PolicyTermType.ALLOW.ordinal()]; + if (item != null) { + existingPolicy.addPolicyItem(item); + } + + item = items[PolicyTermType.DENY.ordinal()]; + if (item != null) { + existingPolicy.addDenyPolicyItem(item); + } + + item = items[PolicyTermType.ALLOW_EXCEPTIONS.ordinal()]; + if (item != null) { + existingPolicy.addAllowException(item); + } + + item = items[PolicyTermType.DENY_EXCEPTIONS.ordinal()]; + if (item != null) { + existingPolicy.addDenyException(item); + } + } + + LOG.debug("<== ServiceRESTUtil.mergeProcessedPolicyItems()"); + } + + private static boolean addAccesses(RangerPolicyItem policyItem, List accesses) { + LOG.debug("==> ServiceRESTUtil.addAccesses()"); + + boolean ret = false; + + for (RangerPolicyItemAccess access : accesses) { + RangerPolicyItemAccess policyItemAccess = null; + String accessType = access.getType(); + + for (RangerPolicyItemAccess itemAccess : policyItem.getAccesses()) { + if (StringUtils.equals(itemAccess.getType(), accessType)) { + policyItemAccess = itemAccess; + break; + } + } + + if (policyItemAccess != null) { + if (!policyItemAccess.getIsAllowed()) { + policyItemAccess.setIsAllowed(Boolean.TRUE); + ret = true; + } + } else { + policyItem.addAccess(new RangerPolicyItemAccess(accessType, Boolean.TRUE)); + ret = true; + } + } + + LOG.debug("<== ServiceRESTUtil.addAccesses() {}", ret); + + return ret; + } + + private static boolean removeAccesses(RangerPolicyItem policyItem, List accesses) { + LOG.debug("==> ServiceRESTUtil.removeAccesses()"); + + boolean ret = false; + + if (policyItem != null) { + for (RangerPolicyItemAccess access : accesses) { + String accessType = access.getType(); + int numOfAccesses = policyItem.getAccesses().size(); + + for (int i = 0; i < numOfAccesses; i++) { + RangerPolicyItemAccess itemAccess = policyItem.getAccesses().get(i); + + if (StringUtils.equals(itemAccess.getType(), accessType)) { + policyItem.getAccesses().remove(i); + + numOfAccesses--; + i--; + + ret = true; + } + } + } + } + + LOG.debug("<== ServiceRESTUtil.removeAccesses() {}", ret); + + return ret; + } + + private static void compactPolicy(RangerPolicy policy) { + policy.setPolicyItems(mergePolicyItems(policy.getPolicyItems())); + policy.setDenyPolicyItems(mergePolicyItems(policy.getDenyPolicyItems())); + policy.setAllowExceptions(mergePolicyItems(policy.getAllowExceptions())); + policy.setDenyExceptions(mergePolicyItems(policy.getDenyExceptions())); + } + + private static List mergePolicyItems(List policyItems) { + List ret = new ArrayList<>(); + + if (CollectionUtils.isNotEmpty(policyItems)) { + Map matchedPolicyItems = new HashMap<>(); + + for (RangerPolicyItem policyItem : policyItems) { + if ((CollectionUtils.isEmpty(policyItem.getUsers()) && CollectionUtils.isEmpty(policyItem.getGroups()) && CollectionUtils.isEmpty(policyItem.getRoles())) || + (CollectionUtils.isEmpty(policyItem.getAccesses()) && !policyItem.getDelegateAdmin())) { + continue; + } + + if (policyItem.getConditions().size() > 1) { + ret.add(policyItem); + continue; + } + + TreeSet accesses = new TreeSet<>(); + + for (RangerPolicyItemAccess access : policyItem.getAccesses()) { + accesses.add(access.getType()); + } + + if (policyItem.getDelegateAdmin()) { + accesses.add("delegateAdmin"); + } + + String allAccessesString = accesses.toString(); + RangerPolicyItem matchingPolicyItem = matchedPolicyItems.get(allAccessesString); + + if (matchingPolicyItem != null) { + addDistinctUsers(policyItem.getUsers(), matchingPolicyItem); + addDistinctGroups(policyItem.getGroups(), matchingPolicyItem); + addDistinctRoles(policyItem.getRoles(), matchingPolicyItem); + } else { + matchedPolicyItems.put(allAccessesString, policyItem); + } + } + + for (Map.Entry entry : matchedPolicyItems.entrySet()) { + ret.add(entry.getValue()); + } + } + + return ret; + } + + private static void addDistinctUsers(List users, RangerPolicyItem policyItem) { + for (String user : users) { + if (!policyItem.getUsers().contains(user)) { + policyItem.addUser(user); + } + } + } + + private static void addDistinctGroups(List groups, RangerPolicyItem policyItem) { + for (String group : groups) { + if (!policyItem.getGroups().contains(group)) { + policyItem.addGroup(group); + } + } + } + + private static void addDistinctRoles(List roles, RangerPolicyItem policyItem) { + for (String role : roles) { + if (!policyItem.getRoles().contains(role)) { + policyItem.addRole(role); + } + } + } + + private static boolean removeUsersGroupsAndRolesFromPolicy(RangerPolicy policy, Set users, Set groups, Set roles) { + boolean policyUpdated = false; + List policyItems = policy.getPolicyItems(); + int numOfItems = policyItems.size(); + + for (int i = 0; i < numOfItems; i++) { + RangerPolicyItem policyItem = policyItems.get(i); + + if (CollectionUtils.containsAny(policyItem.getUsers(), users)) { + policyItem.getUsers().removeAll(users); + + policyUpdated = true; + } + + if (CollectionUtils.containsAny(policyItem.getGroups(), groups)) { + policyItem.getGroups().removeAll(groups); + + policyUpdated = true; + } + + if (CollectionUtils.containsAny(policyItem.getRoles(), roles)) { + policyItem.getRoles().removeAll(roles); + + policyUpdated = true; + } + + if (CollectionUtils.isEmpty(policyItem.getUsers()) && CollectionUtils.isEmpty(policyItem.getGroups()) && CollectionUtils.isEmpty(policyItem.getRoles())) { + policyItems.remove(i); + + numOfItems--; + i--; + + policyUpdated = true; + } + } + + return policyUpdated; + } + + private enum PolicyTermType { + ALLOW, DENY, ALLOW_EXCEPTIONS, DENY_EXCEPTIONS + } } diff --git a/security-admin/src/main/java/org/apache/ranger/rest/ServiceTagsProcessor.java b/security-admin/src/main/java/org/apache/ranger/rest/ServiceTagsProcessor.java index ecdf504e3a..f2fbb620c3 100644 --- a/security-admin/src/main/java/org/apache/ranger/rest/ServiceTagsProcessor.java +++ b/security-admin/src/main/java/org/apache/ranger/rest/ServiceTagsProcessor.java @@ -40,619 +40,592 @@ import java.util.Map; public class ServiceTagsProcessor { - private static final Logger LOG = LoggerFactory.getLogger(ServiceTagsProcessor.class); - private static final Logger PERF_LOG_ADD_OR_UPDATE = RangerPerfTracer.getPerfLogger("tags.addOrUpdate"); - - private final TagStore tagStore; - - public ServiceTagsProcessor(TagStore tagStore) { - this.tagStore = tagStore; - } - - public void process(ServiceTags serviceTags) throws Exception { - if (LOG.isDebugEnabled()) { - LOG.debug("==> ServiceTagsProcessor.process()"); - } - - if (tagStore != null && serviceTags != null) { - if (LOG.isDebugEnabled()) { - LOG.debug("serviceTags: op=" + serviceTags.getOp()); - } - String op = serviceTags.getOp(); - - if (StringUtils.equalsIgnoreCase(op, ServiceTags.OP_ADD_OR_UPDATE)) { - addOrUpdate(serviceTags); - } else if (StringUtils.equalsIgnoreCase(op, ServiceTags.OP_DELETE)) { - delete(serviceTags); - } else if (StringUtils.equalsIgnoreCase(op, ServiceTags.OP_REPLACE)) { - replace(serviceTags); - } else { - LOG.error("Unknown op, op=" + op); - } - } else { - if(tagStore == null) { - LOG.error("tagStore is null!!"); - } - - if (serviceTags == null) { - LOG.error("No ServiceTags to import!!"); - } - } - - if (LOG.isDebugEnabled()) { - LOG.debug("<== ServiceTagsProcessor.process()"); - } - } - - // Map tagdef, tag, serviceResource ids to created ids and use them in tag-resource-mapping - private void addOrUpdate(ServiceTags serviceTags) throws Exception { - if (LOG.isDebugEnabled()) { - LOG.debug("==> ServiceTagsProcessor.createOrUpdate()"); - } - - RangerPerfTracer perfTotal = null; - RangerPerfTracer perf = null; - - Map tagDefsInStore = new HashMap(); - Map resourcesInStore = new HashMap(); - - if(RangerPerfTracer.isPerfTraceEnabled(PERF_LOG_ADD_OR_UPDATE)) { - perfTotal = RangerPerfTracer.getPerfTracer(PERF_LOG_ADD_OR_UPDATE, "tags.addOrUpdate()"); - } - - if (MapUtils.isNotEmpty(serviceTags.getTagDefinitions())) { - RangerTagDef tagDef = null; - - try { - for (Map.Entry entry : serviceTags.getTagDefinitions().entrySet()) { - tagDef = entry.getValue(); - - RangerTagDef existing = null; - - if(StringUtils.isNotEmpty(tagDef.getGuid())) { - existing = tagStore.getTagDefByGuid(tagDef.getGuid()); - } - - if(existing == null && StringUtils.isNotEmpty(tagDef.getName())) { - existing = tagStore.getTagDefByName(tagDef.getName()); - } - - RangerTagDef tagDefInStore = null; - - if(existing == null) { - tagDefInStore = tagStore.createTagDef(tagDef); - } else { - if (LOG.isDebugEnabled()) { - LOG.debug("tagDef for name:" + tagDef.getName() + " exists, will not update it"); - } - tagDefInStore = existing; - } - - tagDefsInStore.put(entry.getKey(), tagDefInStore); - } - } catch (Exception exception) { - LOG.error("createTagDef failed, tagDef=" + tagDef, exception); - throw exception; - } - } - - List resources = serviceTags.getServiceResources(); - if (CollectionUtils.isNotEmpty(resources)) { - RangerServiceResource resource = null; - - try { - for (int i = 0; i < resources.size(); i++) { - resource = resources.get(i); - - if (StringUtils.isBlank(resource.getServiceName())) { - resource.setServiceName(serviceTags.getServiceName()); - } - - RangerServiceResource existing = null; - String resourceSignature = null; - Long resourceId = resource.getId(); - - if(StringUtils.isNotEmpty(resource.getGuid())) { - if(RangerPerfTracer.isPerfTraceEnabled(PERF_LOG_ADD_OR_UPDATE)) { - perf = RangerPerfTracer.getPerfTracer(PERF_LOG_ADD_OR_UPDATE, "tags.search_service_resource_by_guid(" + resourceId + ")"); - } - existing = tagStore.getServiceResourceByGuid(resource.getGuid()); - RangerPerfTracer.logAlways(perf); - } - - if (existing == null) { - if(MapUtils.isNotEmpty(resource.getResourceElements())) { - if(RangerPerfTracer.isPerfTraceEnabled(PERF_LOG_ADD_OR_UPDATE)) { - perf = RangerPerfTracer.getPerfTracer(PERF_LOG_ADD_OR_UPDATE, "tags.search_service_resource_by_signature(" + resourceId + ")"); - } - RangerServiceResourceSignature serializer = new RangerServiceResourceSignature(resource); - - resourceSignature = serializer.getSignature(); - resource.setResourceSignature(resourceSignature); - - existing = tagStore.getServiceResourceByServiceAndResourceSignature(resource.getServiceName(), resourceSignature); - - RangerPerfTracer.logAlways(perf); - } - } - - RangerServiceResource resourceInStore = null; - - if(RangerPerfTracer.isPerfTraceEnabled(PERF_LOG_ADD_OR_UPDATE)) { - perf = RangerPerfTracer.getPerfTracer(PERF_LOG_ADD_OR_UPDATE, "tags.createOrUpdate_service_resource(" + resourceId + ")"); - } - if (existing == null) { - resourceInStore = tagStore.createServiceResource(resource); - - } else if (StringUtils.isEmpty(resource.getServiceName()) || MapUtils.isEmpty(resource.getResourceElements())) { - resourceInStore = existing; - } else { - resource.setId(existing.getId()); - resource.setGuid(existing.getGuid()); - - resourceInStore = tagStore.updateServiceResource(resource); - } - - resourcesInStore.put(resourceId, resourceInStore); - RangerPerfTracer.logAlways(perf); - } - } catch (Exception exception) { - LOG.error("createServiceResource failed, resource=" + resource, exception); - throw exception; - } - } - - if (MapUtils.isNotEmpty(serviceTags.getResourceToTagIds())) { - for (Map.Entry> entry : serviceTags.getResourceToTagIds().entrySet()) { - Long resourceId = entry.getKey(); - - RangerServiceResource resourceInStore = resourcesInStore.get(resourceId); - - if (resourceInStore == null) { - LOG.error("Resource (id=" + resourceId + ") not found. Skipping tags update"); - continue; - } - - if(RangerPerfTracer.isPerfTraceEnabled(PERF_LOG_ADD_OR_UPDATE)) { - perf = RangerPerfTracer.getPerfTracer(PERF_LOG_ADD_OR_UPDATE, "tags.get_tags_for_service_resource(" + resourceInStore.getId() + ")"); - } - - // Get all tags associated with this resourceId - List associatedTags = null; - - try { - associatedTags = tagStore.getTagsForResourceId(resourceInStore.getId()); - } catch (Exception exception) { - LOG.error("RangerTags cannot be retrieved for resource with guid=" + resourceInStore.getGuid()); - throw exception; - } finally { - RangerPerfTracer.logAlways(perf); - } - - List tagsToRetain = new ArrayList(); - boolean isAnyTagUpdated = false; - - List tagIds = entry.getValue(); - try { - for (Long tagId : tagIds) { - RangerTag incomingTag = MapUtils.isNotEmpty(serviceTags.getTags()) ? serviceTags.getTags().get(tagId) : null; - - if (incomingTag == null) { - LOG.error("Tag (id=" + tagId + ") not found. Skipping addition of this tag for resource (id=" + resourceId + ")"); - continue; - } - - RangerTag matchingTag = findMatchingTag(incomingTag, associatedTags); - if (matchingTag == null) { - if (LOG.isDebugEnabled()) { - LOG.debug("Did not find matching tag for tagId=" + tagId); - } - // create new tag from incoming tag and associate it with service-resource - if (RangerPerfTracer.isPerfTraceEnabled(PERF_LOG_ADD_OR_UPDATE)) { - perf = RangerPerfTracer.getPerfTracer(PERF_LOG_ADD_OR_UPDATE, "tags.create_tag(" + tagId + ")"); - } - RangerTag newTag = tagStore.createTag(incomingTag); - RangerPerfTracer.logAlways(perf); - - RangerTagResourceMap tagResourceMap = new RangerTagResourceMap(); - - tagResourceMap.setTagId(newTag.getId()); - tagResourceMap.setResourceId(resourceInStore.getId()); - if (RangerPerfTracer.isPerfTraceEnabled(PERF_LOG_ADD_OR_UPDATE)) { - perf = RangerPerfTracer.getPerfTracer(PERF_LOG_ADD_OR_UPDATE, "tags.create_tagResourceMap(" + tagId + ")"); - } - tagResourceMap = tagStore.createTagResourceMap(tagResourceMap); - RangerPerfTracer.logAlways(perf); - - associatedTags.add(newTag); - tagsToRetain.add(newTag); - - } else { - - if (LOG.isDebugEnabled()) { - LOG.debug("Found matching tag for tagId=" + tagId + ", matchingTag=" + matchingTag); - } - - if (isResourcePrivateTag(incomingTag)) { - if (!isResourcePrivateTag(matchingTag)) { - // create new tag from incoming tag and associate it with service-resource - RangerTag newTag = tagStore.createTag(incomingTag); - - RangerTagResourceMap tagResourceMap = new RangerTagResourceMap(); - - tagResourceMap.setTagId(newTag.getId()); - tagResourceMap.setResourceId(resourceInStore.getId()); - - tagResourceMap = tagStore.createTagResourceMap(tagResourceMap); - - associatedTags.add(newTag); - tagsToRetain.add(newTag); - - } else { - tagsToRetain.add(matchingTag); - - boolean isTagUpdateNeeded = false; - - // Note that as there is no easy way to check validityPeriods for equality, an easy way to rule out the possibility of validityPeriods - // not matching is to check if both old and new tags have empty validityPeriods - if (matchingTag.getGuid() != null && matchingTag.getGuid().equals(incomingTag.getGuid())) { - if (isMatch(incomingTag, matchingTag) && CollectionUtils.isEmpty(incomingTag.getValidityPeriods()) && CollectionUtils.isEmpty(matchingTag.getValidityPeriods())) { - if (LOG.isDebugEnabled()) { - LOG.debug("No need to update existing-tag:[" + matchingTag + "] with incoming-tag:[" + incomingTag + "]"); - } - } else { - isTagUpdateNeeded = true; - } - } else { - if (CollectionUtils.isEmpty(incomingTag.getValidityPeriods()) && CollectionUtils.isEmpty(matchingTag.getValidityPeriods())) { - // Completely matched tags. No need to update - if (LOG.isDebugEnabled()) { - LOG.debug("No need to update existing-tag:[" + matchingTag + "] with incoming-tag:[" + incomingTag + "]"); - } - } else { - isTagUpdateNeeded = true; - } - } - if (isTagUpdateNeeded) { - // Keep this tag, and update it with attribute-values and validity schedules from incoming tag - if (LOG.isDebugEnabled()) { - LOG.debug("Updating existing private tag with id=" + matchingTag.getId()); - } - incomingTag.setId(matchingTag.getId()); - tagStore.updateTag(incomingTag); - isAnyTagUpdated = true; - } - } - } else { // shared model - if (isResourcePrivateTag(matchingTag)) { - // create new tag from incoming tag and associate it with service-resource - RangerTag newTag = tagStore.createTag(incomingTag); - - RangerTagResourceMap tagResourceMap = new RangerTagResourceMap(); - - tagResourceMap.setTagId(newTag.getId()); - tagResourceMap.setResourceId(resourceInStore.getId()); - - tagResourceMap = tagStore.createTagResourceMap(tagResourceMap); - - associatedTags.add(newTag); - tagsToRetain.add(newTag); - - } else { - // Keep this tag, but update it with attribute-values from incoming tag - tagsToRetain.add(matchingTag); - - // Update shared tag with new values - incomingTag.setId(matchingTag.getId()); - tagStore.updateTag(incomingTag); - - // associate with service-resource if not already associated - if (findTagInList(matchingTag, associatedTags) == null) { - RangerTagResourceMap tagResourceMap = new RangerTagResourceMap(); - - tagResourceMap.setTagId(matchingTag.getId()); - tagResourceMap.setResourceId(resourceInStore.getId()); - - tagResourceMap = tagStore.createTagResourceMap(tagResourceMap); - } else { - isAnyTagUpdated = true; - } - - } - } - - } - } - - } catch (Exception exception) { - LOG.error("createRangerTagResourceMap failed", exception); - throw exception; - } - - if (CollectionUtils.isNotEmpty(associatedTags)) { - Long tagId = null; - - try { - for (RangerTag associatedTag : associatedTags) { - if (findTagInList(associatedTag, tagsToRetain) == null) { - - tagId = associatedTag.getId(); - - RangerTagResourceMap tagResourceMap = tagStore.getTagResourceMapForTagAndResourceId(tagId, resourceInStore.getId()); - - if (tagResourceMap != null) { - tagStore.deleteTagResourceMap(tagResourceMap.getId()); - } - - if (LOG.isDebugEnabled()) { - LOG.debug("Deleted tagResourceMap(tagId=" + tagId + ", resourceId=" + resourceInStore.getId()); - } - } - } - } catch(Exception exception) { - LOG.error("deleteTagResourceMap failed, tagId=" + tagId + ", resourceId=" + resourceInStore.getId()); - throw exception; - } - } - if (isAnyTagUpdated) { - if(RangerPerfTracer.isPerfTraceEnabled(PERF_LOG_ADD_OR_UPDATE)) { - perf = RangerPerfTracer.getPerfTracer(PERF_LOG_ADD_OR_UPDATE, "tags.refreshServiceResource(" + resourceInStore.getId() + ")"); - } - tagStore.refreshServiceResource(resourceInStore.getId()); - RangerPerfTracer.logAlways(perf); - } else { - if (CollectionUtils.isEmpty(tagIds)) { - // No tags associated with the resource - delete the resource too - tagStore.deleteServiceResource(resourceInStore.getId()); - } - } - } - } - - RangerPerfTracer.logAlways(perfTotal); - - if (LOG.isDebugEnabled()) { - LOG.debug("<== ServiceTagsProcessor.createOrUpdate()"); - } - } - - private RangerTag findTagInList(RangerTag object, List list) { - if (LOG.isDebugEnabled()) { - LOG.debug("==> ServiceTagsProcessor.findTagInList(): object=" + (object == null ? null : object.getId())); - } - RangerTag ret = null; - if (object != null) { - for (RangerTag tag : list) { - if (LOG.isDebugEnabled()) { - LOG.debug("==> ServiceTagsProcessor.findTagInList(): tag=" + tag.getId()); - } - if (tag.getId().equals(object.getId())) { - ret = tag; - if (LOG.isDebugEnabled()) { - LOG.debug("==> ServiceTagsProcessor.findTagInList(): found tag=" + tag.getId()); - } - break; - } - } - } - if (LOG.isDebugEnabled()) { - LOG.debug("<== ServiceTagsProcessor.findTagInList(): ret=" + (ret == null ? null : ret.getId())); - } - return ret; - } - private boolean isResourcePrivateTag(RangerTag tag) { - return tag.getOwner() == null || tag.getOwner() == RangerTag.OWNER_SERVICERESOURCE; - } - - private RangerTag findMatchingTag(RangerTag incomingTag, List existingTags) throws Exception { - - RangerTag ret = null; - - if(StringUtils.isNotEmpty(incomingTag.getGuid())) { - ret = tagStore.getTagByGuid(incomingTag.getGuid()); - } - - if (ret == null) { - - if (isResourcePrivateTag(incomingTag)) { - - for (RangerTag existingTag : existingTags) { - if (isMatch(incomingTag, existingTag)) { - ret = existingTag; - break; - } - } - } - - } - - return ret; - } - - private boolean isMatch(final RangerTag incomingTag, final RangerTag existingTag) { - boolean ret = false; - - if (incomingTag != null && existingTag != null) { - - if (StringUtils.equals(incomingTag.getType(), existingTag.getType())) { - - // Check attribute values - Map incomingTagAttributes = incomingTag.getAttributes() != null ? incomingTag.getAttributes() : Collections.emptyMap(); - Map existingTagAttributes = existingTag.getAttributes() != null ? existingTag.getAttributes() : Collections.emptyMap(); - - if (CollectionUtils.isEqualCollection(incomingTagAttributes.keySet(), existingTagAttributes.keySet())) { - - boolean matched = true; - - for (Map.Entry entry : incomingTagAttributes.entrySet()) { - - String key = entry.getKey(); - String value = entry.getValue(); - - if (!StringUtils.equals(value, existingTagAttributes.get(key))) { - matched = false; - break; - } - - } - if (matched) { - ret = true; - } - } - - } - } - return ret; - } - - private void delete(ServiceTags serviceTags) throws Exception { - if (LOG.isDebugEnabled()) { - LOG.debug("==> ServiceTagsProcessor.delete()"); - } - - // We dont expect any resourceId->tagId mappings in delete operation, so ignoring them if specified - - List serviceResources = serviceTags.getServiceResources(); - if (CollectionUtils.isNotEmpty(serviceResources)) { - - for (RangerServiceResource serviceResource : serviceResources) { - if (StringUtils.isBlank(serviceResource.getServiceName())) { - serviceResource.setServiceName(serviceTags.getServiceName()); - } - - RangerServiceResource objToDelete = null; - - try { - if (StringUtils.isNotBlank(serviceResource.getGuid())) { - objToDelete = tagStore.getServiceResourceByGuid(serviceResource.getGuid()); - } - - if (objToDelete == null) { - if (MapUtils.isNotEmpty(serviceResource.getResourceElements())) { - RangerServiceResourceSignature serializer = new RangerServiceResourceSignature(serviceResource); + private static final Logger LOG = LoggerFactory.getLogger(ServiceTagsProcessor.class); + private static final Logger PERF_LOG_ADD_OR_UPDATE = RangerPerfTracer.getPerfLogger("tags.addOrUpdate"); - String serviceResourceSignature = serializer.getSignature(); + private final TagStore tagStore; - objToDelete = tagStore.getServiceResourceByServiceAndResourceSignature(serviceResource.getServiceName(), serviceResourceSignature); - } - } + public ServiceTagsProcessor(TagStore tagStore) { + this.tagStore = tagStore; + } - if (objToDelete != null) { + public void process(ServiceTags serviceTags) throws Exception { + LOG.debug("==> ServiceTagsProcessor.process()"); - List tagResourceMaps = tagStore.getTagResourceMapsForResourceGuid(objToDelete.getGuid()); + if (tagStore != null && serviceTags != null) { + LOG.debug("serviceTags: op={}", serviceTags.getOp()); - if (CollectionUtils.isNotEmpty(tagResourceMaps)) { - for (RangerTagResourceMap tagResourceMap : tagResourceMaps) { - tagStore.deleteTagResourceMap(tagResourceMap.getId()); - } - } + String op = serviceTags.getOp(); - tagStore.deleteServiceResource(objToDelete.getId()); - } - } catch (Exception exception) { - LOG.error("deleteServiceResourceByGuid failed, guid=" + serviceResource.getGuid(), exception); - throw exception; - } - } - } + if (StringUtils.equalsIgnoreCase(op, ServiceTags.OP_ADD_OR_UPDATE)) { + addOrUpdate(serviceTags); + } else if (StringUtils.equalsIgnoreCase(op, ServiceTags.OP_DELETE)) { + delete(serviceTags); + } else if (StringUtils.equalsIgnoreCase(op, ServiceTags.OP_REPLACE)) { + replace(serviceTags); + } else { + LOG.error("Unknown op, op={}", op); + } + } else { + if (tagStore == null) { + LOG.error("tagStore is null!!"); + } - Map tagsMap = serviceTags.getTags(); - if (MapUtils.isNotEmpty(tagsMap)) { - for (Map.Entry entry : tagsMap.entrySet()) { - RangerTag tag = entry.getValue(); - try { - RangerTag objToDelete = tagStore.getTagByGuid(tag.getGuid()); + if (serviceTags == null) { + LOG.error("No ServiceTags to import!!"); + } + } - if (objToDelete != null) { - tagStore.deleteTag(objToDelete.getId()); - } - } catch (Exception exception) { - LOG.error("deleteTag failed, guid=" + tag.getGuid(), exception); - throw exception; - } - } - } + LOG.debug("<== ServiceTagsProcessor.process()"); + } - Map tagDefsMap = serviceTags.getTagDefinitions(); - if (MapUtils.isNotEmpty(tagDefsMap)) { - for (Map.Entry entry : tagDefsMap.entrySet()) { - RangerTagDef tagDef = entry.getValue(); - try { - RangerTagDef objToDelete = tagStore.getTagDefByGuid(tagDef.getGuid()); + // Map tagdef, tag, serviceResource ids to created ids and use them in tag-resource-mapping + private void addOrUpdate(ServiceTags serviceTags) throws Exception { + LOG.debug("==> ServiceTagsProcessor.createOrUpdate()"); - if(objToDelete != null) { - tagStore.deleteTagDef(objToDelete.getId()); - } - } catch (Exception exception) { - LOG.error("deleteTagDef failed, guid=" + tagDef.getGuid(), exception); - throw exception; - } - } - } - - if (LOG.isDebugEnabled()) { - LOG.debug("<== ServiceTagsProcessor.delete()"); - } - } - - private void replace(ServiceTags serviceTags) throws Exception { - if (LOG.isDebugEnabled()) { - LOG.debug("==> ServiceTagsProcessor.replace()"); - } + RangerPerfTracer perfTotal = null; + RangerPerfTracer perf = null; - // Delete those service-resources which are in ranger database but not in provided service-tags + Map tagDefsInStore = new HashMap<>(); + Map resourcesInStore = new HashMap<>(); - Map serviceResourcesInServiceTagsMap = new HashMap(); + if (RangerPerfTracer.isPerfTraceEnabled(PERF_LOG_ADD_OR_UPDATE)) { + perfTotal = RangerPerfTracer.getPerfTracer(PERF_LOG_ADD_OR_UPDATE, "tags.addOrUpdate()"); + } - List serviceResourcesInServiceTags = serviceTags.getServiceResources(); + if (MapUtils.isNotEmpty(serviceTags.getTagDefinitions())) { + RangerTagDef tagDef = null; - for (RangerServiceResource rangerServiceResource : serviceResourcesInServiceTags) { - String guid = rangerServiceResource.getGuid(); + try { + for (Map.Entry entry : serviceTags.getTagDefinitions().entrySet()) { + tagDef = entry.getValue(); - if(serviceResourcesInServiceTagsMap.containsKey(guid)) { - LOG.warn("duplicate service-resource found: guid=" + guid); - } + RangerTagDef existing = null; - serviceResourcesInServiceTagsMap.put(guid, rangerServiceResource); - } - - List serviceResourcesInDb = tagStore.getServiceResourceGuidsByService(serviceTags.getServiceName()); + if (StringUtils.isNotEmpty(tagDef.getGuid())) { + existing = tagStore.getTagDefByGuid(tagDef.getGuid()); + } - if (CollectionUtils.isNotEmpty(serviceResourcesInDb)) { - for (String dbServiceResourceGuid : serviceResourcesInDb) { + if (existing == null && StringUtils.isNotEmpty(tagDef.getName())) { + existing = tagStore.getTagDefByName(tagDef.getName()); + } - if (!serviceResourcesInServiceTagsMap.containsKey(dbServiceResourceGuid)) { - - if (LOG.isDebugEnabled()) { - LOG.debug("Deleting serviceResource(guid=" + dbServiceResourceGuid + ") and its tag-associations..."); - } + RangerTagDef tagDefInStore; - List tagResourceMaps = tagStore.getTagResourceMapsForResourceGuid(dbServiceResourceGuid); + if (existing == null) { + tagDefInStore = tagStore.createTagDef(tagDef); + } else { + LOG.debug("tagDef for name: {} exists, will not update it", tagDef.getName()); - if (CollectionUtils.isNotEmpty(tagResourceMaps)) { - for (RangerTagResourceMap tagResourceMap : tagResourceMaps) { - tagStore.deleteTagResourceMap(tagResourceMap.getId()); - } - } - - tagStore.deleteServiceResourceByGuid(dbServiceResourceGuid); - } - - } - } - - // Add/update resources and other tag-model objects provided in service-tags - - addOrUpdate(serviceTags); - - // All private tags at this point are associated with some service-resource and shared - // tags cannot be deleted as they belong to some other service. In any case, any tags that - // are not associated with service-resource will not be downloaded to plugin. - - // Tag-defs cannot be deleted as there may be a shared tag that it refers to it. - - if (LOG.isDebugEnabled()) { - LOG.debug("<== ServiceTagsProcessor.replace()"); - } - } + tagDefInStore = existing; + } + + tagDefsInStore.put(entry.getKey(), tagDefInStore); + } + } catch (Exception exception) { + LOG.error("createTagDef failed, tagDef={}", tagDef, exception); + + throw exception; + } + } + + List resources = serviceTags.getServiceResources(); + + if (CollectionUtils.isNotEmpty(resources)) { + RangerServiceResource resource = null; + + try { + for (RangerServiceResource rangerServiceResource : resources) { + resource = rangerServiceResource; + + if (StringUtils.isBlank(resource.getServiceName())) { + resource.setServiceName(serviceTags.getServiceName()); + } + + RangerServiceResource existing = null; + Long resourceId = resource.getId(); + + if (StringUtils.isNotEmpty(resource.getGuid())) { + if (RangerPerfTracer.isPerfTraceEnabled(PERF_LOG_ADD_OR_UPDATE)) { + perf = RangerPerfTracer.getPerfTracer(PERF_LOG_ADD_OR_UPDATE, "tags.search_service_resource_by_guid(" + resourceId + ")"); + } + + existing = tagStore.getServiceResourceByGuid(resource.getGuid()); + + RangerPerfTracer.logAlways(perf); + } + + if (existing == null) { + if (MapUtils.isNotEmpty(resource.getResourceElements())) { + if (RangerPerfTracer.isPerfTraceEnabled(PERF_LOG_ADD_OR_UPDATE)) { + perf = RangerPerfTracer.getPerfTracer(PERF_LOG_ADD_OR_UPDATE, "tags.search_service_resource_by_signature(" + resourceId + ")"); + } + + RangerServiceResourceSignature serializer = new RangerServiceResourceSignature(resource); + String resourceSignature = serializer.getSignature(); + + resource.setResourceSignature(resourceSignature); + + existing = tagStore.getServiceResourceByServiceAndResourceSignature(resource.getServiceName(), resourceSignature); + + RangerPerfTracer.logAlways(perf); + } + } + + if (RangerPerfTracer.isPerfTraceEnabled(PERF_LOG_ADD_OR_UPDATE)) { + perf = RangerPerfTracer.getPerfTracer(PERF_LOG_ADD_OR_UPDATE, "tags.createOrUpdate_service_resource(" + resourceId + ")"); + } + + RangerServiceResource resourceInStore; + + if (existing == null) { + resourceInStore = tagStore.createServiceResource(resource); + } else if (StringUtils.isEmpty(resource.getServiceName()) || MapUtils.isEmpty(resource.getResourceElements())) { + resourceInStore = existing; + } else { + resource.setId(existing.getId()); + resource.setGuid(existing.getGuid()); + + resourceInStore = tagStore.updateServiceResource(resource); + } + + resourcesInStore.put(resourceId, resourceInStore); + + RangerPerfTracer.logAlways(perf); + } + } catch (Exception exception) { + LOG.error("createServiceResource failed, resource={}", resource, exception); + + throw exception; + } + } + + if (MapUtils.isNotEmpty(serviceTags.getResourceToTagIds())) { + for (Map.Entry> entry : serviceTags.getResourceToTagIds().entrySet()) { + Long resourceId = entry.getKey(); + RangerServiceResource resourceInStore = resourcesInStore.get(resourceId); + + if (resourceInStore == null) { + LOG.error("Resource (id={}) not found. Skipping tags update", resourceId); + continue; + } + + if (RangerPerfTracer.isPerfTraceEnabled(PERF_LOG_ADD_OR_UPDATE)) { + perf = RangerPerfTracer.getPerfTracer(PERF_LOG_ADD_OR_UPDATE, "tags.get_tags_for_service_resource(" + resourceInStore.getId() + ")"); + } + + // Get all tags associated with this resourceId + List associatedTags; + + try { + associatedTags = tagStore.getTagsForResourceId(resourceInStore.getId()); + } catch (Exception exception) { + LOG.error("RangerTags cannot be retrieved for resource with guid={}", resourceInStore.getGuid()); + + throw exception; + } finally { + RangerPerfTracer.logAlways(perf); + } + + List tagsToRetain = new ArrayList<>(); + boolean isAnyTagUpdated = false; + List tagIds = entry.getValue(); + + try { + for (Long tagId : tagIds) { + RangerTag incomingTag = MapUtils.isNotEmpty(serviceTags.getTags()) ? serviceTags.getTags().get(tagId) : null; + + if (incomingTag == null) { + LOG.error("Tag (id={}) not found. Skipping addition of this tag for resource (id={})", tagId, resourceId); + continue; + } + + RangerTag matchingTag = findMatchingTag(incomingTag, associatedTags); + + if (matchingTag == null) { + LOG.debug("Did not find matching tag for tagId={}", tagId); + + // create new tag from incoming tag and associate it with service-resource + if (RangerPerfTracer.isPerfTraceEnabled(PERF_LOG_ADD_OR_UPDATE)) { + perf = RangerPerfTracer.getPerfTracer(PERF_LOG_ADD_OR_UPDATE, "tags.create_tag(" + tagId + ")"); + } + + RangerTag newTag = tagStore.createTag(incomingTag); + + RangerPerfTracer.logAlways(perf); + + RangerTagResourceMap tagResourceMap = new RangerTagResourceMap(); + + tagResourceMap.setTagId(newTag.getId()); + tagResourceMap.setResourceId(resourceInStore.getId()); + + if (RangerPerfTracer.isPerfTraceEnabled(PERF_LOG_ADD_OR_UPDATE)) { + perf = RangerPerfTracer.getPerfTracer(PERF_LOG_ADD_OR_UPDATE, "tags.create_tagResourceMap(" + tagId + ")"); + } + + tagResourceMap = tagStore.createTagResourceMap(tagResourceMap); + + RangerPerfTracer.logAlways(perf); + + associatedTags.add(newTag); + tagsToRetain.add(newTag); + } else { + LOG.debug("Found matching tag for tagId={}, matchingTag={}", tagId, matchingTag); + + if (isResourcePrivateTag(incomingTag)) { + if (!isResourcePrivateTag(matchingTag)) { + // create new tag from incoming tag and associate it with service-resource + RangerTag newTag = tagStore.createTag(incomingTag); + + RangerTagResourceMap tagResourceMap = new RangerTagResourceMap(); + + tagResourceMap.setTagId(newTag.getId()); + tagResourceMap.setResourceId(resourceInStore.getId()); + + tagResourceMap = tagStore.createTagResourceMap(tagResourceMap); + + associatedTags.add(newTag); + tagsToRetain.add(newTag); + } else { + tagsToRetain.add(matchingTag); + + boolean isTagUpdateNeeded = false; + + // Note that as there is no easy way to check validityPeriods for equality, an easy way to rule out the possibility of validityPeriods + // not matching is to check if both old and new tags have empty validityPeriods + if (matchingTag.getGuid() != null && matchingTag.getGuid().equals(incomingTag.getGuid())) { + if (isMatch(incomingTag, matchingTag) && CollectionUtils.isEmpty(incomingTag.getValidityPeriods()) && CollectionUtils.isEmpty(matchingTag.getValidityPeriods())) { + LOG.debug("No need to update existing-tag:[{}] with incoming-tag:[{}]", matchingTag, incomingTag); + } else { + isTagUpdateNeeded = true; + } + } else { + if (CollectionUtils.isEmpty(incomingTag.getValidityPeriods()) && CollectionUtils.isEmpty(matchingTag.getValidityPeriods())) { + // Completely matched tags. No need to update + LOG.debug("No need to update existing-tag:[{}] with incoming-tag:[{}]", matchingTag, incomingTag); + } else { + isTagUpdateNeeded = true; + } + } + if (isTagUpdateNeeded) { + // Keep this tag, and update it with attribute-values and validity schedules from incoming tag + LOG.debug("Updating existing private tag with id={}", matchingTag.getId()); + + incomingTag.setId(matchingTag.getId()); + + tagStore.updateTag(incomingTag); + + isAnyTagUpdated = true; + } + } + } else { // shared model + if (isResourcePrivateTag(matchingTag)) { + // create new tag from incoming tag and associate it with service-resource + RangerTag newTag = tagStore.createTag(incomingTag); + + RangerTagResourceMap tagResourceMap = new RangerTagResourceMap(); + + tagResourceMap.setTagId(newTag.getId()); + tagResourceMap.setResourceId(resourceInStore.getId()); + + tagResourceMap = tagStore.createTagResourceMap(tagResourceMap); + + associatedTags.add(newTag); + tagsToRetain.add(newTag); + } else { + // Keep this tag, but update it with attribute-values from incoming tag + tagsToRetain.add(matchingTag); + + // Update shared tag with new values + incomingTag.setId(matchingTag.getId()); + + tagStore.updateTag(incomingTag); + + // associate with service-resource if not already associated + if (findTagInList(matchingTag, associatedTags) == null) { + RangerTagResourceMap tagResourceMap = new RangerTagResourceMap(); + + tagResourceMap.setTagId(matchingTag.getId()); + tagResourceMap.setResourceId(resourceInStore.getId()); + + tagResourceMap = tagStore.createTagResourceMap(tagResourceMap); + } else { + isAnyTagUpdated = true; + } + } + } + } + } + } catch (Exception exception) { + LOG.error("createRangerTagResourceMap failed", exception); + + throw exception; + } + + if (CollectionUtils.isNotEmpty(associatedTags)) { + Long tagId = null; + + try { + for (RangerTag associatedTag : associatedTags) { + if (findTagInList(associatedTag, tagsToRetain) == null) { + tagId = associatedTag.getId(); + + RangerTagResourceMap tagResourceMap = tagStore.getTagResourceMapForTagAndResourceId(tagId, resourceInStore.getId()); + + if (tagResourceMap != null) { + tagStore.deleteTagResourceMap(tagResourceMap.getId()); + } + + LOG.debug("Deleted tagResourceMap(tagId={}, resourceId={}", tagId, resourceInStore.getId()); + } + } + } catch (Exception exception) { + LOG.error("deleteTagResourceMap failed, tagId={}, resourceId={}", tagId, resourceInStore.getId()); + + throw exception; + } + } + + if (isAnyTagUpdated) { + if (RangerPerfTracer.isPerfTraceEnabled(PERF_LOG_ADD_OR_UPDATE)) { + perf = RangerPerfTracer.getPerfTracer(PERF_LOG_ADD_OR_UPDATE, "tags.refreshServiceResource(" + resourceInStore.getId() + ")"); + } + + tagStore.refreshServiceResource(resourceInStore.getId()); + + RangerPerfTracer.logAlways(perf); + } else { + if (CollectionUtils.isEmpty(tagIds)) { + // No tags associated with the resource - delete the resource too + tagStore.deleteServiceResource(resourceInStore.getId()); + } + } + } + } + + RangerPerfTracer.logAlways(perfTotal); + + LOG.debug("<== ServiceTagsProcessor.createOrUpdate()"); + } + + private RangerTag findTagInList(RangerTag object, List list) { + LOG.debug("==> ServiceTagsProcessor.findTagInList(): object={}", (object == null ? null : object.getId())); + RangerTag ret = null; + + if (object != null) { + for (RangerTag tag : list) { + LOG.debug("==> ServiceTagsProcessor.findTagInList(): tag={}", tag.getId()); + + if (tag.getId().equals(object.getId())) { + ret = tag; + + LOG.debug("==> ServiceTagsProcessor.findTagInList(): found tag={}", tag.getId()); + + break; + } + } + } + + LOG.debug("<== ServiceTagsProcessor.findTagInList(): ret={}", (ret == null ? null : ret.getId())); + + return ret; + } + + private boolean isResourcePrivateTag(RangerTag tag) { + return tag.getOwner() == null || tag.getOwner() == RangerTag.OWNER_SERVICERESOURCE; + } + + private RangerTag findMatchingTag(RangerTag incomingTag, List existingTags) throws Exception { + RangerTag ret = null; + + if (StringUtils.isNotEmpty(incomingTag.getGuid())) { + ret = tagStore.getTagByGuid(incomingTag.getGuid()); + } + + if (ret == null) { + if (isResourcePrivateTag(incomingTag)) { + for (RangerTag existingTag : existingTags) { + if (isMatch(incomingTag, existingTag)) { + ret = existingTag; + break; + } + } + } + } + + return ret; + } + + private boolean isMatch(final RangerTag incomingTag, final RangerTag existingTag) { + boolean ret = false; + + if (incomingTag != null && existingTag != null) { + if (StringUtils.equals(incomingTag.getType(), existingTag.getType())) { + // Check attribute values + Map incomingTagAttributes = incomingTag.getAttributes() != null ? incomingTag.getAttributes() : Collections.emptyMap(); + Map existingTagAttributes = existingTag.getAttributes() != null ? existingTag.getAttributes() : Collections.emptyMap(); + + if (CollectionUtils.isEqualCollection(incomingTagAttributes.keySet(), existingTagAttributes.keySet())) { + boolean matched = true; + + for (Map.Entry entry : incomingTagAttributes.entrySet()) { + String key = entry.getKey(); + String value = entry.getValue(); + + if (!StringUtils.equals(value, existingTagAttributes.get(key))) { + matched = false; + break; + } + } + + if (matched) { + ret = true; + } + } + } + } + + return ret; + } + + private void delete(ServiceTags serviceTags) throws Exception { + LOG.debug("==> ServiceTagsProcessor.delete()"); + + // We dont expect any resourceId->tagId mappings in delete operation, so ignoring them if specified + + List serviceResources = serviceTags.getServiceResources(); + + if (CollectionUtils.isNotEmpty(serviceResources)) { + for (RangerServiceResource serviceResource : serviceResources) { + if (StringUtils.isBlank(serviceResource.getServiceName())) { + serviceResource.setServiceName(serviceTags.getServiceName()); + } + + RangerServiceResource objToDelete = null; + + try { + if (StringUtils.isNotBlank(serviceResource.getGuid())) { + objToDelete = tagStore.getServiceResourceByGuid(serviceResource.getGuid()); + } + + if (objToDelete == null) { + if (MapUtils.isNotEmpty(serviceResource.getResourceElements())) { + RangerServiceResourceSignature serializer = new RangerServiceResourceSignature(serviceResource); + String serviceResourceSignature = serializer.getSignature(); + + objToDelete = tagStore.getServiceResourceByServiceAndResourceSignature(serviceResource.getServiceName(), serviceResourceSignature); + } + } + + if (objToDelete != null) { + List tagResourceMaps = tagStore.getTagResourceMapsForResourceGuid(objToDelete.getGuid()); + + if (CollectionUtils.isNotEmpty(tagResourceMaps)) { + for (RangerTagResourceMap tagResourceMap : tagResourceMaps) { + tagStore.deleteTagResourceMap(tagResourceMap.getId()); + } + } + + tagStore.deleteServiceResource(objToDelete.getId()); + } + } catch (Exception exception) { + LOG.error("deleteServiceResourceByGuid failed, guid={}", serviceResource.getGuid(), exception); + + throw exception; + } + } + } + + Map tagsMap = serviceTags.getTags(); + + if (MapUtils.isNotEmpty(tagsMap)) { + for (Map.Entry entry : tagsMap.entrySet()) { + RangerTag tag = entry.getValue(); + + try { + RangerTag objToDelete = tagStore.getTagByGuid(tag.getGuid()); + + if (objToDelete != null) { + tagStore.deleteTag(objToDelete.getId()); + } + } catch (Exception exception) { + LOG.error("deleteTag failed, guid={}", tag.getGuid(), exception); + + throw exception; + } + } + } + + Map tagDefsMap = serviceTags.getTagDefinitions(); + + if (MapUtils.isNotEmpty(tagDefsMap)) { + for (Map.Entry entry : tagDefsMap.entrySet()) { + RangerTagDef tagDef = entry.getValue(); + + try { + RangerTagDef objToDelete = tagStore.getTagDefByGuid(tagDef.getGuid()); + + if (objToDelete != null) { + tagStore.deleteTagDef(objToDelete.getId()); + } + } catch (Exception exception) { + LOG.error("deleteTagDef failed, guid={}", tagDef.getGuid(), exception); + throw exception; + } + } + } + + LOG.debug("<== ServiceTagsProcessor.delete()"); + } + + private void replace(ServiceTags serviceTags) throws Exception { + LOG.debug("==> ServiceTagsProcessor.replace()"); + + // Delete those service-resources which are in ranger database but not in provided service-tags + + Map serviceResourcesInServiceTagsMap = new HashMap<>(); + List serviceResourcesInServiceTags = serviceTags.getServiceResources(); + + for (RangerServiceResource rangerServiceResource : serviceResourcesInServiceTags) { + String guid = rangerServiceResource.getGuid(); + + if (serviceResourcesInServiceTagsMap.containsKey(guid)) { + LOG.warn("duplicate service-resource found: guid={}", guid); + } + + serviceResourcesInServiceTagsMap.put(guid, rangerServiceResource); + } + + List serviceResourcesInDb = tagStore.getServiceResourceGuidsByService(serviceTags.getServiceName()); + + if (CollectionUtils.isNotEmpty(serviceResourcesInDb)) { + for (String dbServiceResourceGuid : serviceResourcesInDb) { + if (!serviceResourcesInServiceTagsMap.containsKey(dbServiceResourceGuid)) { + LOG.debug("Deleting serviceResource(guid={}) and its tag-associations...", dbServiceResourceGuid); + + List tagResourceMaps = tagStore.getTagResourceMapsForResourceGuid(dbServiceResourceGuid); + + if (CollectionUtils.isNotEmpty(tagResourceMaps)) { + for (RangerTagResourceMap tagResourceMap : tagResourceMaps) { + tagStore.deleteTagResourceMap(tagResourceMap.getId()); + } + } + + tagStore.deleteServiceResourceByGuid(dbServiceResourceGuid); + } + } + } + + // Add/update resources and other tag-model objects provided in service-tags + + addOrUpdate(serviceTags); + + // All private tags at this point are associated with some service-resource and shared + // tags cannot be deleted as they belong to some other service. In any case, any tags that + // are not associated with service-resource will not be downloaded to plugin. + + // Tag-defs cannot be deleted as there may be a shared tag that it refers to it. + + LOG.debug("<== ServiceTagsProcessor.replace()"); + } } diff --git a/security-admin/src/main/java/org/apache/ranger/rest/TagREST.java b/security-admin/src/main/java/org/apache/ranger/rest/TagREST.java index 6675d71a6d..92535a453f 100755 --- a/security-admin/src/main/java/org/apache/ranger/rest/TagREST.java +++ b/security-admin/src/main/java/org/apache/ranger/rest/TagREST.java @@ -19,7 +19,6 @@ package org.apache.ranger.rest; -import javax.ws.rs.Consumes; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang.StringUtils; import org.apache.ranger.biz.AssetMgr; @@ -36,8 +35,8 @@ import org.apache.ranger.plugin.model.RangerService; import org.apache.ranger.plugin.model.RangerServiceResource; import org.apache.ranger.plugin.model.RangerTag; -import org.apache.ranger.plugin.model.RangerTagResourceMap; import org.apache.ranger.plugin.model.RangerTagDef; +import org.apache.ranger.plugin.model.RangerTagResourceMap; import org.apache.ranger.plugin.store.EmbeddedServiceDefsUtil; import org.apache.ranger.plugin.store.PList; import org.apache.ranger.plugin.store.RangerServiceResourceSignature; @@ -65,6 +64,7 @@ import javax.annotation.PostConstruct; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.DefaultValue; import javax.ws.rs.GET; @@ -90,20 +90,20 @@ public class TagREST { public static final String Allowed_User_List_For_Tag_Download = "tag.download.auth.users"; - @Autowired - RESTErrorUtil restErrorUtil; + @Autowired + RESTErrorUtil restErrorUtil; - @Autowired - ServiceDBStore svcStore; + @Autowired + ServiceDBStore svcStore; - @Autowired - TagDBStore tagStore; - - @Autowired - RangerDaoManager daoManager; - - @Autowired - RangerBizUtil bizUtil; + @Autowired + TagDBStore tagStore; + + @Autowired + RangerDaoManager daoManager; + + @Autowired + RangerBizUtil bizUtil; @Autowired AssetMgr assetMgr; @@ -129,34 +129,29 @@ public class TagREST { RangerTagResourceMapService rangerTagResourceMapService; public TagREST() { - } + } - @PostConstruct - public void initStore() { - validator = new TagValidator(); + @PostConstruct + public void initStore() { + validator = new TagValidator(); tagStore.setServiceStore(svcStore); validator.setTagStore(tagStore); - } - - TagStore getTagStore() { - return tagStore; } @POST @Path(TagRESTConstants.TAGDEFS_RESOURCE) - @Consumes({ "application/json" }) - @Produces({ "application/json" }) + @Consumes("application/json") + @Produces("application/json") @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") public RangerTagDef createTagDef(RangerTagDef tagDef, @DefaultValue("true") @QueryParam("updateIfExists") boolean updateIfExists) { - if(LOG.isDebugEnabled()) { - LOG.debug("==> TagREST.createTagDef(" + tagDef + ", " + updateIfExists + ")"); - } + LOG.debug("==> TagREST.createTagDef({}, {})", tagDef, updateIfExists); RangerTagDef ret; try { RangerTagDef exist = validator.preCreateTagDef(tagDef, updateIfExists); + if (exist == null) { ret = tagStore.createTagDef(tagDef); } else if (updateIfExists) { @@ -164,34 +159,29 @@ public RangerTagDef createTagDef(RangerTagDef tagDef, @DefaultValue("true") @Que } else { throw new Exception("tag-definition with Id " + exist.getId() + " already exists"); } - } catch(Exception excp) { - LOG.error("createTagDef(" + tagDef + ") failed", excp); + } catch (Exception excp) { + LOG.error("createTagDef({}) failed", tagDef, excp); throw restErrorUtil.createRESTException(HttpServletResponse.SC_BAD_REQUEST, excp.getMessage(), true); } - if(LOG.isDebugEnabled()) { - LOG.debug("<== TagREST.createTagDef(" + tagDef + ", " + updateIfExists + "): " + ret); - } + LOG.debug("<== TagREST.createTagDef({}, {}): {}", tagDef, updateIfExists, ret); return ret; } - @PUT @Path(TagRESTConstants.TAGDEF_RESOURCE + "{id}") - @Consumes({ "application/json" }) - @Produces({ "application/json" }) + @Consumes("application/json") + @Produces("application/json") @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") public RangerTagDef updateTagDef(@PathParam("id") Long id, RangerTagDef tagDef) { + LOG.debug("==> TagREST.updateTagDef({})", id); - if(LOG.isDebugEnabled()) { - LOG.debug("==> TagREST.updateTagDef(" + id + ")"); - } if (tagDef.getId() == null) { tagDef.setId(id); } else if (!tagDef.getId().equals(id)) { - throw restErrorUtil.createRESTException(HttpServletResponse.SC_BAD_REQUEST , "tag name mismatch", true); + throw restErrorUtil.createRESTException(HttpServletResponse.SC_BAD_REQUEST, "tag name mismatch", true); } RangerTagDef ret; @@ -199,12 +189,12 @@ public RangerTagDef updateTagDef(@PathParam("id") Long id, RangerTagDef tagDef) try { ret = tagStore.updateTagDef(tagDef); } catch (Exception excp) { - LOG.error("updateTagDef(" + id + ") failed", excp); + LOG.error("updateTagDef({}) failed", id, excp); + throw restErrorUtil.createRESTException(HttpServletResponse.SC_BAD_REQUEST, excp.getMessage(), true); } - if(LOG.isDebugEnabled()) { - LOG.debug("<== TagREST.updateTagDef(" + id + ")"); - } + + LOG.debug("<== TagREST.updateTagDef({})", id); return ret; } @@ -213,175 +203,150 @@ public RangerTagDef updateTagDef(@PathParam("id") Long id, RangerTagDef tagDef) @Path(TagRESTConstants.TAGDEF_RESOURCE + "{id}") @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") public void deleteTagDef(@PathParam("id") Long id) { - if(LOG.isDebugEnabled()) { - LOG.debug("==> TagREST.deleteTagDef(" + id + ")"); - } + LOG.debug("==> TagREST.deleteTagDef({})", id); try { tagStore.deleteTagDef(id); - } catch(Exception excp) { - LOG.error("deleteTagDef(" + id + ") failed", excp); + } catch (Exception excp) { + LOG.error("deleteTagDef({}) failed", id, excp); throw restErrorUtil.createRESTException(HttpServletResponse.SC_BAD_REQUEST, excp.getMessage(), true); } - if(LOG.isDebugEnabled()) { - LOG.debug("<== TagREST.deleteTagDef(" + id + ")"); - } + LOG.debug("<== TagREST.deleteTagDef({})", id); } @DELETE @Path(TagRESTConstants.TAGDEF_RESOURCE + "guid/{guid}") @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") public void deleteTagDefByGuid(@PathParam("guid") String guid) { - if(LOG.isDebugEnabled()) { - LOG.debug("==> TagREST.deleteTagDefByGuid(" + guid + ")"); - } + LOG.debug("==> TagREST.deleteTagDefByGuid({})", guid); try { RangerTagDef exist = tagStore.getTagDefByGuid(guid); - if(exist!=null){ - tagStore.deleteTagDef(exist.getId()); - } - } catch(Exception excp) { - LOG.error("deleteTagDef(" + guid + ") failed", excp); + + if (exist != null) { + tagStore.deleteTagDef(exist.getId()); + } + } catch (Exception excp) { + LOG.error("deleteTagDef({}) failed", guid, excp); throw restErrorUtil.createRESTException(HttpServletResponse.SC_BAD_REQUEST, excp.getMessage(), true); } - if(LOG.isDebugEnabled()) { - LOG.debug("<== TagREST.deleteTagDefByGuid(" + guid + ")"); - } + LOG.debug("<== TagREST.deleteTagDefByGuid({})", guid); } @GET @Path(TagRESTConstants.TAGDEF_RESOURCE + "{id}") - @Produces({ "application/json" }) + @Produces("application/json") @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") public RangerTagDef getTagDef(@PathParam("id") Long id) { - if(LOG.isDebugEnabled()) { - LOG.debug("==> TagREST.getTagDef(" + id + ")"); - } + LOG.debug("==> TagREST.getTagDef({})", id); RangerTagDef ret; try { ret = tagStore.getTagDef(id); - } catch(Exception excp) { - LOG.error("getTagDef(" + id + ") failed", excp); + } catch (Exception excp) { + LOG.error("getTagDef({}) failed", id, excp); throw restErrorUtil.createRESTException(HttpServletResponse.SC_BAD_REQUEST, excp.getMessage(), true); } - if(ret == null) { + if (ret == null) { throw restErrorUtil.createRESTException(HttpServletResponse.SC_NOT_FOUND, "Not found", true); } - if(LOG.isDebugEnabled()) { - LOG.debug("<== TagREST.getTagDef(" + id + "): " + ret); - } + LOG.debug("<== TagREST.getTagDef({}): {}", id, ret); return ret; } @GET @Path(TagRESTConstants.TAGDEF_RESOURCE + "guid/{guid}") - @Produces({ "application/json" }) + @Produces("application/json") @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") public RangerTagDef getTagDefByGuid(@PathParam("guid") String guid) { - if(LOG.isDebugEnabled()) { - LOG.debug("==> TagREST.getTagDefByGuid(" + guid + ")"); - } + LOG.debug("==> TagREST.getTagDefByGuid({})", guid); RangerTagDef ret; try { ret = tagStore.getTagDefByGuid(guid); - } catch(Exception excp) { - LOG.error("getTagDefByGuid(" + guid + ") failed", excp); + } catch (Exception excp) { + LOG.error("getTagDefByGuid({}) failed", guid, excp); throw restErrorUtil.createRESTException(HttpServletResponse.SC_BAD_REQUEST, excp.getMessage(), true); } - if(ret == null) { + if (ret == null) { throw restErrorUtil.createRESTException(HttpServletResponse.SC_NOT_FOUND, "Not found", true); } - if(LOG.isDebugEnabled()) { - LOG.debug("<== TagREST.getTagDefByGuid(" + guid + "): " + ret); - } + LOG.debug("<== TagREST.getTagDefByGuid({}): {}", guid, ret); return ret; } @GET @Path(TagRESTConstants.TAGDEF_RESOURCE + "name/{name}") - @Produces({ "application/json" }) + @Produces("application/json") @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") public RangerTagDef getTagDefByName(@PathParam("name") String name) { - if(LOG.isDebugEnabled()) { - LOG.debug("==> TagREST.getTagDefByName(" + name + ")"); - } + LOG.debug("==> TagREST.getTagDefByName({})", name); RangerTagDef ret; try { ret = tagStore.getTagDefByName(name); - } catch(Exception excp) { - LOG.error("getTagDefByName(" + name + ") failed", excp); + } catch (Exception excp) { + LOG.error("getTagDefByName({}) failed", name, excp); throw restErrorUtil.createRESTException(HttpServletResponse.SC_BAD_REQUEST, excp.getMessage(), true); } - if(ret == null) { + if (ret == null) { throw restErrorUtil.createRESTException(HttpServletResponse.SC_NOT_FOUND, "Not found", true); } - if(LOG.isDebugEnabled()) { - LOG.debug("<== TagREST.getTagDefByName(" + name + "): " + ret); - } + LOG.debug("<== TagREST.getTagDefByName({}): {}", name, ret); return ret; } @GET @Path(TagRESTConstants.TAGDEFS_RESOURCE) - @Produces({ "application/json" }) + @Produces("application/json") @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") public List getAllTagDefs() { - if(LOG.isDebugEnabled()) { - LOG.debug("==> TagREST.getAllTagDefs()"); - } + LOG.debug("==> TagREST.getAllTagDefs()"); List ret; try { ret = tagStore.getTagDefs(new SearchFilter()); - } catch(Exception excp) { + } catch (Exception excp) { LOG.error("getAllTagDefs() failed", excp); throw restErrorUtil.createRESTException(HttpServletResponse.SC_BAD_REQUEST, excp.getMessage(), true); } - if(ret == null) { + if (ret == null) { throw restErrorUtil.createRESTException(HttpServletResponse.SC_NOT_FOUND, "Not found", true); } - if(LOG.isDebugEnabled()) { - LOG.debug("<== TagREST.getAllTagDefs()"); - } + LOG.debug("<== TagREST.getAllTagDefs()"); return ret; } @GET @Path(TagRESTConstants.TAGDEFS_RESOURCE_PAGINATED) - @Produces({ "application/json" }) + @Produces("application/json") @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") public PList getTagDefs(@Context HttpServletRequest request) { - if (LOG.isDebugEnabled()) { - LOG.debug("==> TagREST.getTagDefs()"); - } + LOG.debug("==> TagREST.getTagDefs()"); final PList ret; @@ -399,58 +364,50 @@ public PList getTagDefs(@Context HttpServletRequest request) { throw restErrorUtil.createRESTException(HttpServletResponse.SC_NOT_FOUND, "Not found", true); } - if (LOG.isDebugEnabled()) { - LOG.debug("<== TagREST.getTagDefs(): count=" + ((ret == null || ret.getList() == null) ? 0 : ret.getList().size())); - } + LOG.debug("<== TagREST.getTagDefs(): count={}", ret.getList() == null ? 0 : ret.getList().size()); return ret; } @GET @Path(TagRESTConstants.TAGTYPES_RESOURCE) - @Produces({ "application/json" }) + @Produces("application/json") public List getTagTypes() { - if(LOG.isDebugEnabled()) { - LOG.debug("==> TagREST.getTagTypes()"); - } + LOG.debug("==> TagREST.getTagTypes()"); // check for ADMIN access if (!bizUtil.isAdmin()) { throw restErrorUtil.createRESTException(HttpServletResponse.SC_FORBIDDEN, "User don't have permission to perform this action", true); } - List ret = null; + List ret; try { ret = tagStore.getTagTypes(); - } catch(Exception excp) { + } catch (Exception excp) { LOG.error("getTagTypes() failed", excp); throw restErrorUtil.createRESTException(HttpServletResponse.SC_BAD_REQUEST, excp.getMessage(), true); } - if(LOG.isDebugEnabled()) { - LOG.debug("<== TagREST.getTagTypes(): count=" + (ret != null ? ret.size() : 0)); - } + LOG.debug("<== TagREST.getTagTypes(): count={}", (ret != null ? ret.size() : 0)); return ret; } - @POST @Path(TagRESTConstants.TAGS_RESOURCE) - @Consumes({ "application/json" }) - @Produces({ "application/json" }) + @Consumes("application/json") + @Produces("application/json") @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") public RangerTag createTag(RangerTag tag, @DefaultValue("true") @QueryParam("updateIfExists") boolean updateIfExists) { - if(LOG.isDebugEnabled()) { - LOG.debug("==> TagREST.createTag(" + tag + ", " + updateIfExists + ")"); - } + LOG.debug("==> TagREST.createTag({}, {})", tag, updateIfExists); RangerTag ret; try { RangerTag exist = validator.preCreateTag(tag); + if (exist == null) { ret = tagStore.createTag(tag); } else if (updateIfExists) { @@ -458,65 +415,61 @@ public RangerTag createTag(RangerTag tag, @DefaultValue("true") @QueryParam("upd } else { throw new Exception("tag with Id " + exist.getId() + " already exists"); } - } catch(Exception excp) { - LOG.error("createTag(" + tag + ") failed", excp); + } catch (Exception excp) { + LOG.error("createTag({}) failed", tag, excp); throw restErrorUtil.createRESTException(HttpServletResponse.SC_BAD_REQUEST, excp.getMessage(), true); } - if(LOG.isDebugEnabled()) { - LOG.debug("<== TagREST.createTag(" + tag + ", " + updateIfExists + "): " + ret); - } + LOG.debug("<== TagREST.createTag({}, {}): {}", tag, updateIfExists, ret); return ret; } @PUT @Path(TagRESTConstants.TAG_RESOURCE + "{id}") - @Consumes({ "application/json" }) - @Produces({ "application/json" }) + @Consumes("application/json") + @Produces("application/json") @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") public RangerTag updateTag(@PathParam("id") Long id, RangerTag tag) { - RangerTag ret; try { validator.preUpdateTag(id, tag); + ret = tagStore.updateTag(tag); } catch (Exception excp) { - LOG.error("updateTag(" + id + ") failed", excp); + LOG.error("updateTag({}) failed", id, excp); + throw restErrorUtil.createRESTException(HttpServletResponse.SC_BAD_REQUEST, excp.getMessage(), true); } - if(LOG.isDebugEnabled()) { - LOG.debug("<== TagREST.updateTag(" + id + "): " + ret); - } + + LOG.debug("<== TagREST.updateTag({}): {}", id, ret); return ret; } @PUT @Path(TagRESTConstants.TAG_RESOURCE + "guid/{guid}") - @Consumes({ "application/json" }) - @Produces({ "application/json" }) + @Consumes("application/json") + @Produces("application/json") @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") public RangerTag updateTagByGuid(@PathParam("guid") String guid, RangerTag tag) { - - if(LOG.isDebugEnabled()) { - LOG.debug("==> TagREST.updateTagByGuid(" + guid + ")"); - } + LOG.debug("==> TagREST.updateTagByGuid({})", guid); RangerTag ret; try { validator.preUpdateTagByGuid(guid, tag); + ret = tagStore.updateTag(tag); } catch (Exception excp) { - LOG.error("updateTagByGuid(" + guid + ") failed", excp); + LOG.error("updateTagByGuid({}) failed", guid, excp); + throw restErrorUtil.createRESTException(HttpServletResponse.SC_BAD_REQUEST, excp.getMessage(), true); } - if(LOG.isDebugEnabled()) { - LOG.debug("<== TagREST.updateTagByGuid(" + guid + "): " + ret); - } + + LOG.debug("<== TagREST.updateTagByGuid({}): {}", guid, ret); return ret; } @@ -525,127 +478,110 @@ public RangerTag updateTagByGuid(@PathParam("guid") String guid, RangerTag tag) @Path(TagRESTConstants.TAG_RESOURCE + "{id}") @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") public void deleteTag(@PathParam("id") Long id) { - if(LOG.isDebugEnabled()) { - LOG.debug("==> TagREST.deleteTag(" + id +")"); - } + LOG.debug("==> TagREST.deleteTag({})", id); try { validator.preDeleteTag(id); tagStore.deleteTag(id); - } catch(Exception excp) { - LOG.error("deleteTag(" + id + ") failed", excp); + } catch (Exception excp) { + LOG.error("deleteTag({}) failed", id, excp); + throw restErrorUtil.createRESTException(HttpServletResponse.SC_BAD_REQUEST, excp.getMessage(), true); } - if(LOG.isDebugEnabled()) { - LOG.debug("<== TagREST.deleteTag(" + id + ")"); - } + LOG.debug("<== TagREST.deleteTag({})", id); } @DELETE @Path(TagRESTConstants.TAG_RESOURCE + "guid/{guid}") @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") public void deleteTagByGuid(@PathParam("guid") String guid) { - if(LOG.isDebugEnabled()) { - LOG.debug("==> TagREST.deleteTagByGuid(" + guid + ")"); - } + LOG.debug("==> TagREST.deleteTagByGuid({})", guid); try { RangerTag exist = validator.preDeleteTagByGuid(guid); + tagStore.deleteTag(exist.getId()); - } catch(Exception excp) { - LOG.error("deleteTagByGuid(" + guid + ") failed", excp); + } catch (Exception excp) { + LOG.error("deleteTagByGuid({}) failed", guid, excp); throw restErrorUtil.createRESTException(HttpServletResponse.SC_BAD_REQUEST, excp.getMessage(), true); } - if(LOG.isDebugEnabled()) { - LOG.debug("<== TagREST.deleteTagByGuid(" + guid + ")"); - } + LOG.debug("<== TagREST.deleteTagByGuid({})", guid); } @GET @Path(TagRESTConstants.TAG_RESOURCE + "{id}") - @Produces({ "application/json" }) + @Produces("application/json") @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") public RangerTag getTag(@PathParam("id") Long id) { - if(LOG.isDebugEnabled()) { - LOG.debug("==> TagREST.getTag(" + id + ")"); - } + LOG.debug("==> TagREST.getTag({})", id); + RangerTag ret; try { ret = tagStore.getTag(id); - } catch(Exception excp) { - LOG.error("getTag(" + id + ") failed", excp); + } catch (Exception excp) { + LOG.error("getTag({}) failed", id, excp); throw restErrorUtil.createRESTException(HttpServletResponse.SC_BAD_REQUEST, excp.getMessage(), true); } - if(LOG.isDebugEnabled()) { - LOG.debug("<== TagREST.getTag(" + id + "): " + ret); - } + LOG.debug("<== TagREST.getTag({}): {}", id, ret); return ret; } @GET @Path(TagRESTConstants.TAG_RESOURCE + "guid/{guid}") - @Produces({ "application/json" }) + @Produces("application/json") @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") public RangerTag getTagByGuid(@PathParam("guid") String guid) { - if(LOG.isDebugEnabled()) { - LOG.debug("==> TagREST.getTagByGuid(" + guid + ")"); - } + LOG.debug("==> TagREST.getTagByGuid({})", guid); + RangerTag ret; try { ret = tagStore.getTagByGuid(guid); - } catch(Exception excp) { - LOG.error("getTagByGuid(" + guid + ") failed", excp); + } catch (Exception excp) { + LOG.error("getTagByGuid({}) failed", guid, excp); throw restErrorUtil.createRESTException(HttpServletResponse.SC_BAD_REQUEST, excp.getMessage(), true); } - if(LOG.isDebugEnabled()) { - LOG.debug("<== TagREST.getTagByGuid(" + guid + "): " + ret); - } + LOG.debug("<== TagREST.getTagByGuid({}): {}", guid, ret); return ret; } @GET @Path(TagRESTConstants.TAGS_RESOURCE + "type/{type}") - @Produces({ "application/json" }) + @Produces("application/json") @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") public List getTagsByType(@PathParam("type") String type) { - if(LOG.isDebugEnabled()) { - LOG.debug("==> TagREST.getTagsByType(" + type + ")"); - } + LOG.debug("==> TagREST.getTagsByType({})", type); + List ret; try { ret = tagStore.getTagsByType(type); - } catch(Exception excp) { - LOG.error("getTagsByType(" + type + ") failed", excp); + } catch (Exception excp) { + LOG.error("getTagsByType({}) failed", type, excp); throw restErrorUtil.createRESTException(HttpServletResponse.SC_BAD_REQUEST, excp.getMessage(), true); } - if(LOG.isDebugEnabled()) { - LOG.debug("<== TagREST.getTagsByType(" + type + "): " + ret); - } + LOG.debug("<== TagREST.getTagsByType({}): {}", type, ret); return ret; } @GET @Path(TagRESTConstants.TAGS_RESOURCE) - @Produces({ "application/json" }) + @Produces("application/json") public List getAllTags() { - if(LOG.isDebugEnabled()) { - LOG.debug("==> TagREST.getAllTags()"); - } + LOG.debug("==> TagREST.getAllTags()"); // check for ADMIN access if (!bizUtil.isAdmin()) { @@ -656,32 +592,27 @@ public List getAllTags() { try { ret = tagStore.getTags(new SearchFilter()); - } catch(Exception excp) { + } catch (Exception excp) { LOG.error("getAllTags() failed", excp); throw restErrorUtil.createRESTException(HttpServletResponse.SC_BAD_REQUEST, excp.getMessage(), true); } if (CollectionUtils.isEmpty(ret)) { - if (LOG.isDebugEnabled()) { - LOG.debug("getAllTags() - No tags found"); - } - } - if(LOG.isDebugEnabled()) { - LOG.debug("<== TagREST.getAllTags(): " + ret); + LOG.debug("getAllTags() - No tags found"); } + LOG.debug("<== TagREST.getAllTags(): {}", ret); + return ret; } @GET @Path(TagRESTConstants.TAGS_RESOURCE_PAGINATED) - @Produces({ "application/json" }) + @Produces("application/json") @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") public PList getTags(@Context HttpServletRequest request) { - if (LOG.isDebugEnabled()) { - LOG.debug("==> TagREST.getTags()"); - } + LOG.debug("==> TagREST.getTags()"); final PList ret; @@ -698,44 +629,40 @@ public PList getTags(@Context HttpServletRequest request) { } if (CollectionUtils.isEmpty(ret.getList())) { - if (LOG.isDebugEnabled()) { - LOG.debug("getTags() - No tags found"); - } + LOG.debug("getTags() - No tags found"); } - if (LOG.isDebugEnabled()) { - LOG.debug("<== TagREST.getTags(): count=" + ((ret == null || ret.getList() == null) ? 0 : ret.getList().size())); - } + LOG.debug("<== TagREST.getTags(): count={}", ret.getList() == null ? 0 : ret.getList().size()); return ret; } /** * Resets/ removes tag policy cache for given service. + * * @param serviceName non-empty service-name * @return {@code true} if successfully reseted/ removed for given service, {@code false} otherwise. */ @GET @Path(TagRESTConstants.TAGS_RESOURCE + "cache/reset") - @Produces({ "application/json" }) + @Produces("application/json") public boolean resetTagCache(@QueryParam("serviceName") String serviceName) { - if (LOG.isDebugEnabled()) { - LOG.debug("==> TagREST.resetTagCache({})", serviceName); - } + LOG.debug("==> TagREST.resetTagCache({})", serviceName); if (StringUtils.isEmpty(serviceName)) { throw restErrorUtil.createRESTException("Required parameter [serviceName] is missing.", MessageEnums.INVALID_INPUT_DATA); } RangerService rangerService = null; + try { rangerService = svcStore.getServiceByName(serviceName); } catch (Exception e) { - LOG.error( HttpServletResponse.SC_BAD_REQUEST + "No Service Found for ServiceName:" + serviceName ); + LOG.error("{} No Service Found for ServiceName: {}", HttpServletResponse.SC_BAD_REQUEST, serviceName); } if (rangerService == null) { - throw restErrorUtil.createRESTException(HttpServletResponse.SC_BAD_REQUEST , "Invalid service name", true); + throw restErrorUtil.createRESTException(HttpServletResponse.SC_BAD_REQUEST, "Invalid service name", true); } // check for ADMIN access @@ -746,7 +673,7 @@ public boolean resetTagCache(@QueryParam("serviceName") String serviceName) { try { isServiceAdmin = bizUtil.isUserServiceAdmin(rangerService, loggedInUser); } catch (Exception e) { - LOG.warn("Failed to find if user [" + loggedInUser + "] has service admin privileges on service [" + serviceName + "]", e); + LOG.warn("Failed to find if user [{}] has service admin privileges on service [{}]", loggedInUser, serviceName, e); } if (!isServiceAdmin) { @@ -756,24 +683,21 @@ public boolean resetTagCache(@QueryParam("serviceName") String serviceName) { boolean ret = tagStore.resetTagCache(serviceName); - if (LOG.isDebugEnabled()) { - LOG.debug("<== TagREST.resetTagCache(): ret={}", ret); - } + LOG.debug("<== TagREST.resetTagCache(): ret={}", ret); return ret; } /** * Resets/ removes tag policy cache for all. + * * @return {@code true} if successfully reseted/ removed, {@code false} otherwise. */ @GET @Path(TagRESTConstants.TAGS_RESOURCE + "cache/reset-all") - @Produces({ "application/json" }) + @Produces("application/json") public boolean resetTagCacheAll() { - if (LOG.isDebugEnabled()) { - LOG.debug("==> TagREST.resetTagCacheAll()"); - } + LOG.debug("==> TagREST.resetTagCacheAll()"); // check for ADMIN access if (!bizUtil.isAdmin()) { @@ -782,27 +706,24 @@ public boolean resetTagCacheAll() { boolean ret = tagStore.resetTagCache(null); - if (LOG.isDebugEnabled()) { - LOG.debug("<== TagREST.resetTagCacheAll(): ret={}", ret); - } + LOG.debug("<== TagREST.resetTagCacheAll(): ret={}", ret); return ret; } @POST @Path(TagRESTConstants.RESOURCES_RESOURCE) - @Consumes({ "application/json" }) - @Produces({ "application/json" }) + @Consumes("application/json") + @Produces("application/json") @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") public RangerServiceResource createServiceResource(RangerServiceResource resource, @DefaultValue("true") @QueryParam("updateIfExists") boolean updateIfExists) { - if(LOG.isDebugEnabled()) { - LOG.debug("==> TagREST.createServiceResource(" + resource + ", " + updateIfExists + ")"); - } + LOG.debug("==> TagREST.createServiceResource({}, {})", resource, updateIfExists); RangerServiceResource ret; try { RangerServiceResource exist = validator.preCreateServiceResource(resource); + if (exist == null) { ret = tagStore.createServiceResource(resource); } else if (updateIfExists) { @@ -810,66 +731,64 @@ public RangerServiceResource createServiceResource(RangerServiceResource resourc } else { throw new Exception("resource with Id " + exist.getId() + " already exists"); } - } catch(Exception excp) { - LOG.error("createServiceResource(" + resource + ") failed", excp); + } catch (Exception excp) { + LOG.error("createServiceResource({}) failed", resource, excp); throw restErrorUtil.createRESTException(HttpServletResponse.SC_BAD_REQUEST, excp.getMessage(), true); } - if(LOG.isDebugEnabled()) { - LOG.debug("<== TagREST.createServiceResource(" + resource + ", " + updateIfExists + "): " + ret); - } + LOG.debug("<== TagREST.createServiceResource({}, {}): {}", resource, updateIfExists, ret); return ret; } @PUT @Path(TagRESTConstants.RESOURCE_RESOURCE + "{id}") - @Consumes({ "application/json" }) - @Produces({ "application/json" }) + @Consumes("application/json") + @Produces("application/json") @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") public RangerServiceResource updateServiceResource(@PathParam("id") Long id, RangerServiceResource resource) { - if(LOG.isDebugEnabled()) { - LOG.debug("==> TagREST.updateServiceResource(" + id + ")"); - } + LOG.debug("==> TagREST.updateServiceResource({})", id); + RangerServiceResource ret; try { validator.preUpdateServiceResource(id, resource); + ret = tagStore.updateServiceResource(resource); - } catch(Exception excp) { - LOG.error("updateServiceResource(" + resource + ") failed", excp); + } catch (Exception excp) { + LOG.error("updateServiceResource({}) failed", resource, excp); throw restErrorUtil.createRESTException(HttpServletResponse.SC_BAD_REQUEST, excp.getMessage(), true); } - if(LOG.isDebugEnabled()) { - LOG.debug("<== TagREST.updateServiceResource(" + id + "): " + ret); - } + LOG.debug("<== TagREST.updateServiceResource({}): {}", id, ret); + return ret; } @PUT @Path(TagRESTConstants.RESOURCE_RESOURCE + "guid/{guid}") - @Consumes({ "application/json" }) - @Produces({ "application/json" }) + @Consumes("application/json") + @Produces("application/json") @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") public RangerServiceResource updateServiceResourceByGuid(@PathParam("guid") String guid, RangerServiceResource resource) { - if(LOG.isDebugEnabled()) { - LOG.debug("==> TagREST.updateServiceResourceByGuid(" + guid + ", " + resource + ")"); - } + LOG.debug("==> TagREST.updateServiceResourceByGuid({}, {})", guid, resource); + RangerServiceResource ret; + try { validator.preUpdateServiceResourceByGuid(guid, resource); + ret = tagStore.updateServiceResource(resource); - } catch(Exception excp) { - LOG.error("updateServiceResourceByGuid(" + guid + ", " + resource + ") failed", excp); + } catch (Exception excp) { + LOG.error("updateServiceResourceByGuid({}, {}) failed", guid, resource, excp); throw restErrorUtil.createRESTException(HttpServletResponse.SC_BAD_REQUEST, excp.getMessage(), true); } - if(LOG.isDebugEnabled()) { - LOG.debug("<== TagREST.updateServiceResourceByGuid(" + guid + ", " + resource + "): " + ret); - } + + LOG.debug("<== TagREST.updateServiceResourceByGuid({}, {}): {}", guid, resource, ret); + return ret; } @@ -877,9 +796,8 @@ public RangerServiceResource updateServiceResourceByGuid(@PathParam("guid") Stri @Path(TagRESTConstants.RESOURCE_RESOURCE + "{id}") @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") public void deleteServiceResource(@PathParam("id") Long id) { - if(LOG.isDebugEnabled()) { - LOG.debug("==> TagREST.deleteServiceResource(" + id + ")"); - } + LOG.debug("==> TagREST.deleteServiceResource({})", id); + try { validator.preDeleteServiceResource(id); tagStore.deleteServiceResource(id); @@ -889,171 +807,151 @@ public void deleteServiceResource(@PathParam("id") Long id) { throw restErrorUtil.createRESTException(HttpServletResponse.SC_BAD_REQUEST, excp.getMessage(), true); } - if(LOG.isDebugEnabled()) { - LOG.debug("<== TagREST.deleteServiceResource(" + id + ")"); - } + LOG.debug("<== TagREST.deleteServiceResource({})", id); } @DELETE @Path(TagRESTConstants.RESOURCE_RESOURCE + "guid/{guid}") @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") public void deleteServiceResourceByGuid(@PathParam("guid") String guid, @DefaultValue("false") @QueryParam("deleteReferences") boolean deleteReferences) { - if(LOG.isDebugEnabled()) { - LOG.debug("==> TagREST.deleteServiceResourceByGuid(" + guid + ", " + deleteReferences + ")"); - } + LOG.debug("==> TagREST.deleteServiceResourceByGuid({}, {})", guid, deleteReferences); try { RangerServiceResource exist = validator.preDeleteServiceResourceByGuid(guid, deleteReferences); + if (deleteReferences) { List tagResourceMaps = tagStore.getTagResourceMapsForResourceGuid(exist.getGuid()); + if (CollectionUtils.isNotEmpty(tagResourceMaps)) { for (RangerTagResourceMap tagResourceMap : tagResourceMaps) { deleteTagResourceMap(tagResourceMap.getId()); } } } + tagStore.deleteServiceResource(exist.getId()); - } catch(Exception excp) { - LOG.error("deleteServiceResourceByGuid(" + guid + ", " + deleteReferences + ") failed", excp); + } catch (Exception excp) { + LOG.error("deleteServiceResourceByGuid({}, {}) failed", guid, deleteReferences, excp); throw restErrorUtil.createRESTException(HttpServletResponse.SC_BAD_REQUEST, excp.getMessage(), true); } - if(LOG.isDebugEnabled()) { - LOG.debug("<== TagREST.deleteServiceResourceByGuid(" + guid + ", " + deleteReferences + ")"); - } + LOG.debug("<== TagREST.deleteServiceResourceByGuid({}, {})", guid, deleteReferences); } @GET @Path(TagRESTConstants.RESOURCE_RESOURCE + "{id}") - @Produces({ "application/json" }) + @Produces("application/json") @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") public RangerServiceResource getServiceResource(@PathParam("id") Long id) { - if(LOG.isDebugEnabled()) { - LOG.debug("==> TagREST.getServiceResource(" + id + ")"); - } + LOG.debug("==> TagREST.getServiceResource({})", id); + RangerServiceResource ret; + try { ret = tagStore.getServiceResource(id); - } catch(Exception excp) { - LOG.error("getServiceResource(" + id + ") failed", excp); + } catch (Exception excp) { + LOG.error("getServiceResource({}) failed", id, excp); throw restErrorUtil.createRESTException(HttpServletResponse.SC_BAD_REQUEST, excp.getMessage(), true); } - if(LOG.isDebugEnabled()) { - LOG.debug("<== TagREST.getServiceResource(" + id + "): " + ret); - } + + LOG.debug("<== TagREST.getServiceResource({}): {}", id, ret); + return ret; } @GET @Path(TagRESTConstants.RESOURCE_RESOURCE + "guid/{guid}") - @Produces({ "application/json" }) + @Produces("application/json") @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") public RangerServiceResource getServiceResourceByGuid(@PathParam("guid") String guid) { - if(LOG.isDebugEnabled()) { - LOG.debug("==> TagREST.getServiceResourceByGuid(" + guid + ")"); - } + LOG.debug("==> TagREST.getServiceResourceByGuid({})", guid); + RangerServiceResource ret; + try { ret = tagStore.getServiceResourceByGuid(guid); - } catch(Exception excp) { - LOG.error("getServiceResourceByGuid(" + guid + ") failed", excp); + } catch (Exception excp) { + LOG.error("getServiceResourceByGuid({}) failed", guid, excp); throw restErrorUtil.createRESTException(HttpServletResponse.SC_BAD_REQUEST, excp.getMessage(), true); } - if(LOG.isDebugEnabled()) { - LOG.debug("<== TagREST.getServiceResourceByGuid(" + guid + "): " + ret); - } + + LOG.debug("<== TagREST.getServiceResourceByGuid({}): {}", guid, ret); + return ret; } @GET @Path(TagRESTConstants.RESOURCES_RESOURCE + "service/{serviceName}") - @Produces({ "application/json" }) + @Produces("application/json") @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") public List getServiceResourcesByService(@PathParam("serviceName") String serviceName) { - if(LOG.isDebugEnabled()) { - LOG.debug("==> TagREST.getServiceResourcesByService(" + serviceName + ")"); - } + LOG.debug("==> TagREST.getServiceResourcesByService({})", serviceName); - List ret = null; + List ret; try { ret = tagStore.getServiceResourcesByService(serviceName); - } catch(Exception excp) { - LOG.error("getServiceResourcesByService(" + serviceName + ") failed", excp); + } catch (Exception excp) { + LOG.error("getServiceResourcesByService({}) failed", serviceName, excp); throw restErrorUtil.createRESTException(HttpServletResponse.SC_BAD_REQUEST, excp.getMessage(), true); } if (CollectionUtils.isEmpty(ret)) { - if (LOG.isDebugEnabled()) { - LOG.debug("getServiceResourcesByService(" + serviceName + ") - No service-resources found"); - } - } - if(LOG.isDebugEnabled()) { - LOG.debug("<== TagREST.getServiceResourcesByService(" + serviceName + "): count=" + (ret == null ? 0 : ret.size())); + LOG.debug("getServiceResourcesByService({}) - No service-resources found", serviceName); } + LOG.debug("<== TagREST.getServiceResourcesByService({}): count={}", serviceName, (ret == null ? 0 : ret.size())); return ret; } @GET @Path(TagRESTConstants.RESOURCE_RESOURCE + "service/{serviceName}/signature/{resourceSignature}") - @Produces({ "application/json" }) + @Produces("application/json") @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") - public RangerServiceResource getServiceResourceByServiceAndResourceSignature(@PathParam("serviceName") String serviceName, - @PathParam("resourceSignature") String resourceSignature) { - if(LOG.isDebugEnabled()) { - LOG.debug("==> TagREST.getServiceResourceByServiceAndResourceSignature(" + serviceName + ", " + resourceSignature + ")"); - } + public RangerServiceResource getServiceResourceByServiceAndResourceSignature(@PathParam("serviceName") String serviceName, @PathParam("resourceSignature") String resourceSignature) { + LOG.debug("==> TagREST.getServiceResourceByServiceAndResourceSignature({}, {})", serviceName, resourceSignature); - RangerServiceResource ret = null; + RangerServiceResource ret; try { ret = tagStore.getServiceResourceByServiceAndResourceSignature(serviceName, resourceSignature); - } catch(Exception excp) { - LOG.error("getServiceResourceByServiceAndResourceSignature(" + serviceName + ", " + resourceSignature + ") failed", excp); + } catch (Exception excp) { + LOG.error("getServiceResourceByServiceAndResourceSignature({}, {})", serviceName, resourceSignature, excp); throw restErrorUtil.createRESTException(HttpServletResponse.SC_BAD_REQUEST, excp.getMessage(), true); } - if(LOG.isDebugEnabled()) { - LOG.debug("<== TagREST.getServiceResourceByServiceAndResourceSignature(" + serviceName + ", " + resourceSignature + "): " + ret); - } + LOG.debug("<== TagREST.getServiceResourceByServiceAndResourceSignature({}, {}): {}", serviceName, resourceSignature, ret); return ret; } @GET @Path(TagRESTConstants.RESOURCE_RESOURCE + "service/{serviceName}/resource") - @Produces({ "application/json" }) + @Produces("application/json") @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") public RangerServiceResource getServiceResourceByResource(@PathParam("serviceName") String serviceName, @Context HttpServletRequest request) { - if (LOG.isDebugEnabled()) { - LOG.debug("==> TagREST.getServiceResourceByResource(" + serviceName + ")"); - } + LOG.debug("==> TagREST.getServiceResourceByResource({})", serviceName); Map resourceMap = searchUtil.getMultiValueParamsWithPrefix(request, SearchFilter.RESOURCE_PREFIX, true); - RangerServiceResource serviceResource = tagStore.toRangerServiceResource(serviceName, resourceMap); + RangerServiceResource serviceResource = TagDBStore.toRangerServiceResource(serviceName, resourceMap); serviceResource = getServiceResourceByServiceAndResourceSignature(serviceName, new RangerServiceResourceSignature(serviceResource).getSignature()); - if(LOG.isDebugEnabled()) { - LOG.debug("<== TagREST.getServiceResourceByResource(serviceName={" + serviceName + "} RangerServiceResource={" + serviceResource + "})"); - } + LOG.debug("<== TagREST.getServiceResourceByResource(serviceName=[{}] RangerServiceResource=[{}])", serviceName, serviceResource); return serviceResource; } @GET @Path(TagRESTConstants.RESOURCES_RESOURCE) - @Produces({ "application/json" }) + @Produces("application/json") public List getAllServiceResources() { - if(LOG.isDebugEnabled()) { - LOG.debug("==> TagREST.getAllServiceResources()"); - } + LOG.debug("==> TagREST.getAllServiceResources()"); // check for ADMIN access if (!bizUtil.isAdmin()) { @@ -1064,34 +962,32 @@ public List getAllServiceResources() { try { ret = tagStore.getServiceResources(new SearchFilter()); - } catch(Exception excp) { + } catch (Exception excp) { LOG.error("getAllServiceResources() failed", excp); throw restErrorUtil.createRESTException(HttpServletResponse.SC_BAD_REQUEST, excp.getMessage(), true); } - if(LOG.isDebugEnabled()) { - LOG.debug("<== TagREST.getAllServiceResources(): count=" + (ret == null ? 0 : ret.size())); - } + LOG.debug("<== TagREST.getAllServiceResources(): count={}", (ret == null ? 0 : ret.size())); return ret; } @GET @Path(TagRESTConstants.RESOURCES_RESOURCE_PAGINATED) - @Produces({ "application/json" }) + @Produces("application/json") @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") public RangerServiceResourceWithTagsList getServiceResourcesWithTags(@Context HttpServletRequest request) { - if (LOG.isDebugEnabled()) { - LOG.debug("==> TagREST.getServiceResources()"); - } + LOG.debug("==> TagREST.getServiceResources()"); RangerServiceResourceWithTagsList ret; try { SearchFilter filter = searchUtil.getSearchFilter(request, rangerServiceResourceWithTagsService.sortFields); + searchUtil.extractIntList(request, filter, SearchFilter.TAG_RESOURCE_IDS, "Tag resource list"); searchUtil.extractStringList(request, filter, SearchFilter.TAG_NAMES, "Tag type List", "tagTypes", null, null); + ret = tagStore.getPaginatedServiceResourcesWithTags(filter); } catch (Exception excp) { LOG.error("getServiceResources() failed", excp); @@ -1099,28 +995,24 @@ public RangerServiceResourceWithTagsList getServiceResourcesWithTags(@Context Ht throw restErrorUtil.createRESTException(HttpServletResponse.SC_BAD_REQUEST, excp.getMessage(), true); } - if (LOG.isDebugEnabled()) { - LOG.debug("<== TagREST.getServiceResources(): count=" + ((ret == null || ret.getList() == null) ? 0 : ret.getList().size())); - } + LOG.debug("<== TagREST.getServiceResources(): count={}", ((ret == null || ret.getList() == null) ? 0 : ret.getList().size())); return ret; } @POST @Path(TagRESTConstants.TAGRESOURCEMAPS_RESOURCE) - @Consumes({ "application/json" }) - @Produces({ "application/json" }) + @Consumes("application/json") + @Produces("application/json") @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") - public RangerTagResourceMap createTagResourceMap(@QueryParam("tag-guid") String tagGuid, @QueryParam("resource-guid") String resourceGuid, - @DefaultValue("false") @QueryParam("lenient") boolean lenient) { - if(LOG.isDebugEnabled()) { - LOG.debug("==> TagREST.createTagResourceMap(" + tagGuid + ", " + resourceGuid + ", " + lenient + ")"); - } + public RangerTagResourceMap createTagResourceMap(@QueryParam("tag-guid") String tagGuid, @QueryParam("resource-guid") String resourceGuid, @DefaultValue("false") @QueryParam("lenient") boolean lenient) { + LOG.debug("==> TagREST.createTagResourceMap({}, {}, {})", tagGuid, resourceGuid, lenient); RangerTagResourceMap tagResourceMap; try { tagResourceMap = tagStore.getTagResourceMapForTagAndResourceGuid(tagGuid, resourceGuid); + if (tagResourceMap == null) { tagResourceMap = validator.preCreateTagResourceMap(tagGuid, resourceGuid); @@ -1128,15 +1020,13 @@ public RangerTagResourceMap createTagResourceMap(@QueryParam("tag-guid") String } else if (!lenient) { throw new Exception("tagResourceMap with tag-guid=" + tagGuid + " and resource-guid=" + resourceGuid + " already exists"); } - } catch(Exception excp) { - LOG.error("createTagResourceMap(" + tagGuid + ", " + resourceGuid + ", " + lenient + ") failed", excp); + } catch (Exception excp) { + LOG.error("createTagResourceMap({}, {}, {})", tagGuid, resourceGuid, lenient, excp); throw restErrorUtil.createRESTException(HttpServletResponse.SC_BAD_REQUEST, excp.getMessage(), true); } - if(LOG.isDebugEnabled()) { - LOG.debug("==> TagREST.createTagResourceMap(" + tagGuid + ", " + resourceGuid + ", " + lenient + ")"); - } + LOG.debug("==> TagREST.createTagResourceMap({}, {}, {})", tagGuid, resourceGuid, lenient); return tagResourceMap; } @@ -1145,9 +1035,8 @@ public RangerTagResourceMap createTagResourceMap(@QueryParam("tag-guid") String @Path(TagRESTConstants.TAGRESOURCEMAP_RESOURCE + "{id}") @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") public void deleteTagResourceMap(@PathParam("id") Long id) { - if(LOG.isDebugEnabled()) { - LOG.debug("==> TagREST.deleteTagResourceMap(" + id + ")"); - } + LOG.debug("==> TagREST.deleteTagResourceMap({})", id); + try { validator.preDeleteTagResourceMap(id); tagStore.deleteTagResourceMap(id); @@ -1157,170 +1046,142 @@ public void deleteTagResourceMap(@PathParam("id") Long id) { throw restErrorUtil.createRESTException(HttpServletResponse.SC_BAD_REQUEST, excp.getMessage(), true); } - if(LOG.isDebugEnabled()) { - LOG.debug("<== TagREST.deleteTagResourceMap(" + id + ")"); - } + LOG.debug("<== TagREST.deleteTagResourceMap({})", id); } @DELETE @Path(TagRESTConstants.TAGRESOURCEMAP_RESOURCE + "guid/{guid}") @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") public void deleteTagResourceMapByGuid(@PathParam("guid") String guid) { - if(LOG.isDebugEnabled()) { - LOG.debug("==> TagREST.deleteTagResourceMapByGuid(" + guid + ")"); - } + LOG.debug("==> TagREST.deleteTagResourceMapByGuid({})", guid); try { RangerTagResourceMap exist = validator.preDeleteTagResourceMapByGuid(guid); + tagStore.deleteTagResourceMap(exist.getId()); - } catch(Exception excp) { - LOG.error("deleteTagResourceMapByGuid(" + guid + ") failed", excp); + } catch (Exception excp) { + LOG.error("deleteTagResourceMapByGuid({}) failed", guid, excp); throw restErrorUtil.createRESTException(HttpServletResponse.SC_BAD_REQUEST, excp.getMessage(), true); } - if(LOG.isDebugEnabled()) { - LOG.debug("<== TagREST.deleteTagResourceMapByGuid(" + guid + ")"); - } + LOG.debug("<== TagREST.deleteTagResourceMapByGuid({})", guid); } @DELETE @Path(TagRESTConstants.TAGRESOURCEMAPS_RESOURCE) @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") public void deleteTagResourceMap(@QueryParam("tag-guid") String tagGuid, @QueryParam("resource-guid") String resourceGuid) { - if(LOG.isDebugEnabled()) { - LOG.debug("==> TagREST.deleteTagResourceMap(" + tagGuid + ", " + resourceGuid + ")"); - } + LOG.debug("==> TagREST.deleteTagResourceMap({}, {})", tagGuid, resourceGuid); try { RangerTagResourceMap exist = validator.preDeleteTagResourceMap(tagGuid, resourceGuid); + tagStore.deleteTagResourceMap(exist.getId()); - } catch(Exception excp) { - LOG.error("deleteTagResourceMap(" + tagGuid + ", " + resourceGuid + ") failed", excp); + } catch (Exception excp) { + LOG.error("deleteTagResourceMap({}, {}) failed", tagGuid, resourceGuid, excp); throw restErrorUtil.createRESTException(HttpServletResponse.SC_BAD_REQUEST, excp.getMessage(), true); } - if(LOG.isDebugEnabled()) { - LOG.debug("==> TagREST.deleteTagResourceMap(" + tagGuid + ", " + resourceGuid + ")"); - } + LOG.debug("==> TagREST.deleteTagResourceMap({}, {})", tagGuid, resourceGuid); } @GET @Path(TagRESTConstants.TAGRESOURCEMAP_RESOURCE + "{id}") - @Produces({ "application/json" }) + @Produces("application/json") @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") public RangerTagResourceMap getTagResourceMap(@PathParam("id") Long id) { - if(LOG.isDebugEnabled()) { - LOG.debug("==> TagREST.getTagResourceMap(" + id + ")"); - } + LOG.debug("==> TagREST.getTagResourceMap({})", id); RangerTagResourceMap ret; try { ret = tagStore.getTagResourceMap(id); - } catch(Exception excp) { - LOG.error("getTagResourceMap(" + id + ") failed", excp); + } catch (Exception excp) { + LOG.error("getTagResourceMap({}) failed", id, excp); throw restErrorUtil.createRESTException(HttpServletResponse.SC_BAD_REQUEST, excp.getMessage(), true); } - if(LOG.isDebugEnabled()) { - LOG.debug("<== TagREST.getTagResourceMap(" + id + "): " + ret); - } + LOG.debug("<== TagREST.getTagResourceMap({}): {}", id, ret); return ret; } @GET @Path(TagRESTConstants.TAGRESOURCEMAP_RESOURCE + "guid/{guid}") - @Produces({ "application/json" }) + @Produces("application/json") @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") public RangerTagResourceMap getTagResourceMapByGuid(@PathParam("guid") String guid) { - if(LOG.isDebugEnabled()) { - LOG.debug("==> TagREST.getTagResourceMapByGuid(" + guid + ")"); - } + LOG.debug("==> TagREST.getTagResourceMapByGuid({})", guid); RangerTagResourceMap ret; try { ret = tagStore.getTagResourceMapByGuid(guid); - } catch(Exception excp) { - LOG.error("getTagResourceMapByGuid(" + guid + ") failed", excp); + } catch (Exception excp) { + LOG.error("getTagResourceMapByGuid({}) failed", guid, excp); throw restErrorUtil.createRESTException(HttpServletResponse.SC_BAD_REQUEST, excp.getMessage(), true); } - if(LOG.isDebugEnabled()) { - LOG.debug("<== TagREST.getTagResourceMapByGuid(" + guid + "): " + ret); - } + LOG.debug("<== TagREST.getTagResourceMapByGuid({}): {}", guid, ret); return ret; } @GET @Path(TagRESTConstants.TAGRESOURCEMAP_RESOURCE + "tag-resource-guid") - @Produces({ "application/json" }) + @Produces("application/json") @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") public RangerTagResourceMap getTagResourceMap(@QueryParam("tagGuid") String tagGuid, @QueryParam("resourceGuid") String resourceGuid) { - if(LOG.isDebugEnabled()) { - LOG.debug("==> TagREST.getTagResourceMap(" + tagGuid + ", " + resourceGuid + ")"); - } + LOG.debug("==> TagREST.getTagResourceMap({}, {})", tagGuid, resourceGuid); - RangerTagResourceMap ret = null; + RangerTagResourceMap ret; try { ret = tagStore.getTagResourceMapForTagAndResourceGuid(tagGuid, resourceGuid); - } catch(Exception excp) { - LOG.error("getTagResourceMap(" + tagGuid + ", " + resourceGuid + ") failed", excp); + } catch (Exception excp) { + LOG.error("getTagResourceMap({}, {}) failed", tagGuid, resourceGuid, excp); throw restErrorUtil.createRESTException(HttpServletResponse.SC_BAD_REQUEST, excp.getMessage(), true); } - if(LOG.isDebugEnabled()) { - LOG.debug("==> TagREST.getTagResourceMap(" + tagGuid + ", " + resourceGuid + ")"); - } + LOG.debug("==> TagREST.getTagResourceMap({}, {})", tagGuid, resourceGuid); return ret; } @GET @Path(TagRESTConstants.TAGRESOURCEMAPS_RESOURCE) - @Produces({ "application/json" }) + @Produces("application/json") @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") public List getAllTagResourceMaps() { - if(LOG.isDebugEnabled()) { - LOG.debug("==> TagREST.getAllTagResourceMaps()"); - } + LOG.debug("==> TagREST.getAllTagResourceMaps()"); List ret; try { ret = tagStore.getTagResourceMaps(new SearchFilter()); - } catch(Exception excp) { + } catch (Exception excp) { LOG.error("getAllTagResourceMaps() failed", excp); throw restErrorUtil.createRESTException(HttpServletResponse.SC_BAD_REQUEST, excp.getMessage(), true); } if (CollectionUtils.isEmpty(ret)) { - if (LOG.isDebugEnabled()) { - LOG.debug("getAllTagResourceMaps() - No tag-resource-maps found"); - } - } - if(LOG.isDebugEnabled()) { - LOG.debug("<== TagREST.getAllTagResourceMaps(): " + ret); + LOG.debug("getAllTagResourceMaps() - No tag-resource-maps found"); } + LOG.debug("<== TagREST.getAllTagResourceMaps(): {}", ret); return ret; } @GET @Path(TagRESTConstants.TAGRESOURCEMAPS_RESOURCE_PAGINATED) - @Produces({ "application/json" }) + @Produces("application/json") @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") public PList getTagResourceMaps(@Context HttpServletRequest request) { - if (LOG.isDebugEnabled()) { - LOG.debug("==> TagREST.getTagResourceMaps()"); - } + LOG.debug("==> TagREST.getTagResourceMaps()"); final PList ret; @@ -1338,33 +1199,28 @@ public PList getTagResourceMaps(@Context HttpServletReques throw restErrorUtil.createRESTException(HttpServletResponse.SC_NOT_FOUND, "Not found", true); } - if (LOG.isDebugEnabled()) { - LOG.debug("<== TagREST.getTagResourceMaps(): " + ret); - } + LOG.debug("<== TagREST.getTagResourceMaps(): {}", ret); return ret; } - // This API is used by tag-sync to upload tag-objects - @PUT @Path(TagRESTConstants.IMPORT_SERVICETAGS_RESOURCE) - @Consumes({ "application/json" }) - @Produces({ "application/json" }) + @Consumes("application/json") + @Produces("application/json") @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") public void importServiceTags(ServiceTags serviceTags) { - if(LOG.isDebugEnabled()) { - LOG.debug("==> TagREST.importServiceTags()"); - } + LOG.debug("==> TagREST.importServiceTags()"); RangerPerfTracer perf = null; - if(RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { + if (RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "TagREST.importServiceTags(service=" + (serviceTags != null ? serviceTags.getServiceName() : null) + ")"); } try { ServiceTagsProcessor serviceTagsProcessor = new ServiceTagsProcessor(tagStore); + serviceTagsProcessor.process(serviceTags); } catch (Exception excp) { LOG.error("importServiceTags() failed", excp); @@ -1374,40 +1230,32 @@ public void importServiceTags(ServiceTags serviceTags) { RangerPerfTracer.log(perf); } - if(LOG.isDebugEnabled()) { - LOG.debug("<== TagREST.importServiceTags()"); - } + LOG.debug("<== TagREST.importServiceTags()"); } - // This API is typically used by plug-in to get selected tagged resources from RangerAdmin + // This API is used by tag-sync to upload tag-objects @GET @Path(TagRESTConstants.TAGS_DOWNLOAD + "{serviceName}") - @Produces({ "application/json" }) - public ServiceTags getServiceTagsIfUpdated(@PathParam("serviceName") String serviceName, - @QueryParam(TagRESTConstants.LAST_KNOWN_TAG_VERSION_PARAM) Long lastKnownVersion, - @DefaultValue("0") @QueryParam(TagRESTConstants.LAST_ACTIVATION_TIME) Long lastActivationTime, @QueryParam("pluginId") String pluginId, - @DefaultValue("false") @QueryParam(RangerRESTUtils.REST_PARAM_SUPPORTS_TAG_DELTAS) Boolean supportsTagDeltas, - @DefaultValue("") @QueryParam(RangerRESTUtils.REST_PARAM_CAPABILITIES) String pluginCapabilities, - @Context HttpServletRequest request) { - if(LOG.isDebugEnabled()) { - LOG.debug("==> TagREST.getServiceTagsIfUpdated(" + serviceName + ", " + lastKnownVersion + ", " + lastActivationTime + ", " + pluginId + ", " + supportsTagDeltas + ")"); - } + @Produces("application/json") + public ServiceTags getServiceTagsIfUpdated(@PathParam("serviceName") String serviceName, @QueryParam(TagRESTConstants.LAST_KNOWN_TAG_VERSION_PARAM) Long lastKnownVersion, @DefaultValue("0") @QueryParam(TagRESTConstants.LAST_ACTIVATION_TIME) Long lastActivationTime, @QueryParam("pluginId") String pluginId, @DefaultValue("false") @QueryParam(RangerRESTUtils.REST_PARAM_SUPPORTS_TAG_DELTAS) Boolean supportsTagDeltas, @DefaultValue("") @QueryParam(RangerRESTUtils.REST_PARAM_CAPABILITIES) String pluginCapabilities, @Context HttpServletRequest request) { + LOG.debug("==> TagREST.getServiceTagsIfUpdated({}, {}, {}, {}, {})", serviceName, lastKnownVersion, lastActivationTime, pluginId, supportsTagDeltas); RangerPerfTracer perf = null; - if(RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { + if (RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "TagREST.getServiceTagsIfUpdated(service=" + serviceName + ", lastKnownVersion=" + lastKnownVersion + ")"); } - ServiceTags ret = null; - int httpCode = HttpServletResponse.SC_OK; - String logMsg = null; - Long downloadedVersion = null; - String clusterName = null; - if (request != null) { - clusterName = !StringUtils.isEmpty(request.getParameter(SearchFilter.CLUSTER_NAME)) ? request.getParameter(SearchFilter.CLUSTER_NAME) : ""; - } + ServiceTags ret = null; + int httpCode = HttpServletResponse.SC_OK; + Long downloadedVersion = null; + String clusterName = null; + String logMsg; + + if (request != null) { + clusterName = !StringUtils.isEmpty(request.getParameter(SearchFilter.CLUSTER_NAME)) ? request.getParameter(SearchFilter.CLUSTER_NAME) : ""; + } try { bizUtil.failUnauthenticatedDownloadIfNotAllowed(); @@ -1416,129 +1264,123 @@ public ServiceTags getServiceTagsIfUpdated(@PathParam("serviceName") String serv if (ret == null) { downloadedVersion = lastKnownVersion; - httpCode = HttpServletResponse.SC_NOT_MODIFIED; - logMsg = "No change since last update"; + httpCode = HttpServletResponse.SC_NOT_MODIFIED; + logMsg = "No change since last update"; } else { downloadedVersion = ret.getTagVersion(); - httpCode = HttpServletResponse.SC_OK; - logMsg = "Returning " + (ret.getTags() != null ? ret.getTags().size() : 0) + " tags. Tag version=" + ret.getTagVersion(); + logMsg = "Returning " + (ret.getTags() != null ? ret.getTags().size() : 0) + " tags. Tag version=" + ret.getTagVersion(); } } catch (WebApplicationException webException) { httpCode = webException.getResponse().getStatus(); - logMsg = webException.getResponse().getEntity().toString(); - } catch(Exception excp) { - httpCode = HttpServletResponse.SC_BAD_REQUEST; - logMsg = excp.getMessage(); + logMsg = webException.getResponse().getEntity().toString(); + } catch (Exception excp) { + httpCode = HttpServletResponse.SC_BAD_REQUEST; + logMsg = excp.getMessage(); } finally { assetMgr.createPluginInfo(serviceName, pluginId, request, RangerPluginInfo.ENTITY_TYPE_TAGS, downloadedVersion, lastKnownVersion, lastActivationTime, httpCode, clusterName, pluginCapabilities); RangerPerfTracer.log(perf); } - if(httpCode != HttpServletResponse.SC_OK) { + if (httpCode != HttpServletResponse.SC_OK) { boolean logError = httpCode != HttpServletResponse.SC_NOT_MODIFIED; + throw restErrorUtil.createRESTException(httpCode, logMsg, logError); } - if(LOG.isDebugEnabled()) { - LOG.debug("<== TagREST.getServiceTagsIfUpdated(" + serviceName + ", " + lastKnownVersion + ", " + lastActivationTime + ", " + pluginId + ", " + supportsTagDeltas + ")"); - } + LOG.debug("<== TagREST.getServiceTagsIfUpdated({}, {}, {}, {}, {})", serviceName, lastKnownVersion, lastActivationTime, pluginId, supportsTagDeltas); return ret; } + // This API is typically used by plug-in to get selected tagged resources from RangerAdmin + @GET @Path(TagRESTConstants.TAGS_SECURE_DOWNLOAD + "{serviceName}") - @Produces({ "application/json" }) - public ServiceTags getSecureServiceTagsIfUpdated(@PathParam("serviceName") String serviceName, - @QueryParam(TagRESTConstants.LAST_KNOWN_TAG_VERSION_PARAM) Long lastKnownVersion, - @DefaultValue("0") @QueryParam(TagRESTConstants.LAST_ACTIVATION_TIME) Long lastActivationTime, @QueryParam("pluginId") String pluginId, - @DefaultValue("false") @QueryParam(RangerRESTUtils.REST_PARAM_SUPPORTS_TAG_DELTAS) Boolean supportsTagDeltas, - @DefaultValue("") @QueryParam(RangerRESTUtils.REST_PARAM_CAPABILITIES) String pluginCapabilities, - @Context HttpServletRequest request) { - - if(LOG.isDebugEnabled()) { - LOG.debug("==> TagREST.getSecureServiceTagsIfUpdated(" + serviceName + ", " + lastKnownVersion + ", " + lastActivationTime + ", " + pluginId + ", " + supportsTagDeltas + ")"); - } + @Produces("application/json") + public ServiceTags getSecureServiceTagsIfUpdated(@PathParam("serviceName") String serviceName, @QueryParam(TagRESTConstants.LAST_KNOWN_TAG_VERSION_PARAM) Long lastKnownVersion, @DefaultValue("0") @QueryParam(TagRESTConstants.LAST_ACTIVATION_TIME) Long lastActivationTime, @QueryParam("pluginId") String pluginId, @DefaultValue("false") @QueryParam(RangerRESTUtils.REST_PARAM_SUPPORTS_TAG_DELTAS) Boolean supportsTagDeltas, @DefaultValue("") @QueryParam(RangerRESTUtils.REST_PARAM_CAPABILITIES) String pluginCapabilities, @Context HttpServletRequest request) { + LOG.debug("==> TagREST.getSecureServiceTagsIfUpdated({}, {}, {}, {}, {})", serviceName, lastKnownVersion, lastActivationTime, pluginId, supportsTagDeltas); RangerPerfTracer perf = null; - if(RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { + if (RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "TagREST.getSecureServiceTagsIfUpdated(service=" + serviceName + ", lastKnownVersion=" + lastKnownVersion + ")"); } - ServiceTags ret = null; - int httpCode = HttpServletResponse.SC_OK; - String logMsg = null; - boolean isAllowed = false; - boolean isAdmin = bizUtil.isAdmin(); - boolean isKeyAdmin = bizUtil.isKeyAdmin(); - Long downloadedVersion = null; - String clusterName = null; - if (request != null) { - clusterName = !StringUtils.isEmpty(request.getParameter(SearchFilter.CLUSTER_NAME)) ? request.getParameter(SearchFilter.CLUSTER_NAME) : ""; - } + ServiceTags ret = null; + int httpCode = HttpServletResponse.SC_OK; + boolean isAdmin = bizUtil.isAdmin(); + boolean isKeyAdmin = bizUtil.isKeyAdmin(); + Long downloadedVersion = null; + String clusterName = null; + String logMsg; + boolean isAllowed; + + if (request != null) { + clusterName = !StringUtils.isEmpty(request.getParameter(SearchFilter.CLUSTER_NAME)) ? request.getParameter(SearchFilter.CLUSTER_NAME) : ""; + } try { - XXService xService = daoManager.getXXService().findByName(serviceName); - if (xService == null) { - LOG.error("Requested Service not found. serviceName=" + serviceName); - throw restErrorUtil.createRESTException(HttpServletResponse.SC_NOT_FOUND, "Service:" + serviceName + " not found", - false); + XXService xService = daoManager.getXXService().findByName(serviceName); + + if (xService == null) { + LOG.error("Requested Service not found. serviceName={}", serviceName); + + throw restErrorUtil.createRESTException(HttpServletResponse.SC_NOT_FOUND, "Service:" + serviceName + " not found", false); } - XXServiceDef xServiceDef = daoManager.getXXServiceDef().getById(xService.getType()); - RangerService rangerService = svcStore.getServiceByName(serviceName); - - if (StringUtils.equals(xServiceDef.getImplclassname(), EmbeddedServiceDefsUtil.KMS_IMPL_CLASS_NAME)) { - if (isKeyAdmin) { - isAllowed = true; - }else { - isAllowed = bizUtil.isUserAllowed(rangerService, Allowed_User_List_For_Tag_Download); - } - }else{ - if (isAdmin) { - isAllowed = true; - }else{ - isAllowed = bizUtil.isUserAllowed(rangerService, Allowed_User_List_For_Tag_Download); - } - } - if (isAllowed) { - ret = tagStore.getServiceTagsIfUpdated(serviceName, lastKnownVersion, !supportsTagDeltas); - - if(ret == null) { + + XXServiceDef xServiceDef = daoManager.getXXServiceDef().getById(xService.getType()); + RangerService rangerService = svcStore.getServiceByName(serviceName); + + if (StringUtils.equals(xServiceDef.getImplclassname(), EmbeddedServiceDefsUtil.KMS_IMPL_CLASS_NAME)) { + if (isKeyAdmin) { + isAllowed = true; + } else { + isAllowed = bizUtil.isUserAllowed(rangerService, Allowed_User_List_For_Tag_Download); + } + } else { + if (isAdmin) { + isAllowed = true; + } else { + isAllowed = bizUtil.isUserAllowed(rangerService, Allowed_User_List_For_Tag_Download); + } + } + if (isAllowed) { + ret = tagStore.getServiceTagsIfUpdated(serviceName, lastKnownVersion, !supportsTagDeltas); + + if (ret == null) { downloadedVersion = lastKnownVersion; - httpCode = HttpServletResponse.SC_NOT_MODIFIED; - logMsg = "No change since last update"; - } else { + httpCode = HttpServletResponse.SC_NOT_MODIFIED; + logMsg = "No change since last update"; + } else { downloadedVersion = ret.getTagVersion(); - httpCode = HttpServletResponse.SC_OK; - logMsg = "Returning " + (ret.getTags() != null ? ret.getTags().size() : 0) + " tags. Tag version=" + ret.getTagVersion(); - } - }else{ - LOG.error("getSecureServiceTagsIfUpdated(" + serviceName + ", " + lastKnownVersion + ", " + lastActivationTime + ") failed as User doesn't have permission to download tags"); - httpCode = HttpServletResponse.SC_FORBIDDEN; // assert user is authenticated. - logMsg = "User doesn't have permission to download tags"; - } + logMsg = "Returning " + (ret.getTags() != null ? ret.getTags().size() : 0) + " tags. Tag version=" + ret.getTagVersion(); + } + } else { + LOG.error("getSecureServiceTagsIfUpdated({}, {}, {}) failed as User doesn't have permission to download tags", serviceName, lastKnownVersion, lastActivationTime); + + httpCode = HttpServletResponse.SC_FORBIDDEN; // assert user is authenticated. + logMsg = "User doesn't have permission to download tags"; + } } catch (WebApplicationException webException) { httpCode = webException.getResponse().getStatus(); - logMsg = webException.getResponse().getEntity().toString(); + logMsg = webException.getResponse().getEntity().toString(); } catch (Exception excp) { - httpCode = HttpServletResponse.SC_BAD_REQUEST; - logMsg = excp.getMessage(); - } finally { + httpCode = HttpServletResponse.SC_BAD_REQUEST; + logMsg = excp.getMessage(); + } finally { assetMgr.createPluginInfo(serviceName, pluginId, request, RangerPluginInfo.ENTITY_TYPE_TAGS, downloadedVersion, lastKnownVersion, lastActivationTime, httpCode, clusterName, pluginCapabilities); RangerPerfTracer.log(perf); } - if(httpCode != HttpServletResponse.SC_OK) { + if (httpCode != HttpServletResponse.SC_OK) { boolean logError = httpCode != HttpServletResponse.SC_NOT_MODIFIED; + throw restErrorUtil.createRESTException(httpCode, logMsg, logError); } - if(LOG.isDebugEnabled()) { - LOG.debug("<== TagREST.getSecureServiceTagsIfUpdated(" + serviceName + ", " + lastKnownVersion + ", " + lastActivationTime + ", " + pluginId + ", " + supportsTagDeltas + ")"); - } + LOG.debug("<== TagREST.getSecureServiceTagsIfUpdated({}, {}, {}, {}, {})", serviceName, lastKnownVersion, lastActivationTime, pluginId, supportsTagDeltas); return ret; } @@ -1547,15 +1389,14 @@ public ServiceTags getSecureServiceTagsIfUpdated(@PathParam("serviceName") Strin @Path("/server/tagdeltas") @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") public void deleteTagDeltas(@DefaultValue("3") @QueryParam("days") Integer olderThan, @Context HttpServletRequest request) { - if (LOG.isDebugEnabled()) { - LOG.debug("==> ServiceREST.deleteTagDeltas(" + olderThan + ")"); - } + LOG.debug("==> ServiceREST.deleteTagDeltas({})", olderThan); svcStore.resetTagUpdateLog(olderThan, ServiceTags.TagsChangeType.INVALIDATE_TAG_DELTAS); - if (LOG.isDebugEnabled()) { - LOG.debug("<== ServiceREST.deleteTagDeltas(" + olderThan + ")"); - } + LOG.debug("<== ServiceREST.deleteTagDeltas({})", olderThan); } + TagStore getTagStore() { + return tagStore; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/rest/TagRESTConstants.java b/security-admin/src/main/java/org/apache/ranger/rest/TagRESTConstants.java index fe05d9febf..ee80ad8eeb 100644 --- a/security-admin/src/main/java/org/apache/ranger/rest/TagRESTConstants.java +++ b/security-admin/src/main/java/org/apache/ranger/rest/TagRESTConstants.java @@ -20,28 +20,30 @@ package org.apache.ranger.rest; public class TagRESTConstants { - public static final String TAGDEF_NAME_AND_VERSION = "tags"; + public static final String TAGDEF_NAME_AND_VERSION = "tags"; + public static final String SERVICE_NAME_PARAM = "serviceName"; + public static final String LAST_KNOWN_TAG_VERSION_PARAM = "lastKnownVersion"; + public static final String LAST_ACTIVATION_TIME = "lastActivationTime"; + public static final String PATTERN_PARAM = "pattern"; + static final String TAGDEFS_RESOURCE = "/tagdefs/"; + static final String TAGDEFS_RESOURCE_PAGINATED = "/tagdefs/paginated"; + static final String TAGDEF_RESOURCE = "/tagdef/"; + static final String TAGS_RESOURCE = "/tags/"; + static final String TAGS_RESOURCE_PAGINATED = "/tags/paginated"; + static final String TAG_RESOURCE = "/tag/"; + static final String RESOURCES_RESOURCE = "/resources/"; + static final String RESOURCES_RESOURCE_PAGINATED = "/resources/paginated"; + static final String RESOURCE_RESOURCE = "/resource/"; + static final String TAGRESOURCEMAPS_RESOURCE = "/tagresourcemaps/"; + static final String TAGRESOURCEMAPS_RESOURCE_PAGINATED = "/tagresourcemaps/paginated"; + static final String IMPORT_SERVICETAGS_RESOURCE = "/importservicetags/"; + static final String TAGRESOURCEMAP_RESOURCE = "/tagresourcemap/"; + static final String TAGTYPES_RESOURCE = "/types/"; + static final String TAGTYPES_LOOKUP_RESOURCE = "/types/lookup/"; + static final String TAGS_DOWNLOAD = "/download/"; + static final String TAGS_SECURE_DOWNLOAD = "/secure/download/"; - static final String TAGDEFS_RESOURCE = "/tagdefs/"; - static final String TAGDEFS_RESOURCE_PAGINATED = "/tagdefs/paginated"; - static final String TAGDEF_RESOURCE = "/tagdef/"; - static final String TAGS_RESOURCE = "/tags/"; - static final String TAGS_RESOURCE_PAGINATED = "/tags/paginated"; - static final String TAG_RESOURCE = "/tag/"; - static final String RESOURCES_RESOURCE = "/resources/"; - static final String RESOURCES_RESOURCE_PAGINATED = "/resources/paginated"; - static final String RESOURCE_RESOURCE = "/resource/"; - static final String TAGRESOURCEMAPS_RESOURCE = "/tagresourcemaps/"; - static final String TAGRESOURCEMAPS_RESOURCE_PAGINATED = "/tagresourcemaps/paginated"; - static final String IMPORT_SERVICETAGS_RESOURCE = "/importservicetags/"; - static final String TAGRESOURCEMAP_RESOURCE = "/tagresourcemap/"; - static final String TAGTYPES_RESOURCE = "/types/"; - static final String TAGTYPES_LOOKUP_RESOURCE = "/types/lookup/"; - static final String TAGS_DOWNLOAD = "/download/"; - static final String TAGS_SECURE_DOWNLOAD = "/secure/download/"; - - public static final String SERVICE_NAME_PARAM = "serviceName"; - public static final String LAST_KNOWN_TAG_VERSION_PARAM = "lastKnownVersion"; - public static final String LAST_ACTIVATION_TIME = "lastActivationTime"; - public static final String PATTERN_PARAM = "pattern"; + private TagRESTConstants() { + //To block instantiation + } } diff --git a/security-admin/src/main/java/org/apache/ranger/rest/UserREST.java b/security-admin/src/main/java/org/apache/ranger/rest/UserREST.java index 4708b86387..8f8692afd5 100644 --- a/security-admin/src/main/java/org/apache/ranger/rest/UserREST.java +++ b/security-admin/src/main/java/org/apache/ranger/rest/UserREST.java @@ -17,22 +17,7 @@ * under the License. */ - package org.apache.ranger.rest; - -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -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.core.Context; +package org.apache.ranger.rest; import org.apache.ranger.biz.UserMgr; import org.apache.ranger.biz.XUserMgr; @@ -66,6 +51,20 @@ import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; +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.core.Context; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; @Path("users") @Component @@ -73,293 +72,289 @@ @RangerAnnotationJSMgrName("UserMgr") @Transactional(propagation = Propagation.REQUIRES_NEW) public class UserREST { - private static final Logger logger = LoggerFactory.getLogger(UserREST.class); - - @Autowired - StringUtil stringUtil; - - @Autowired - RangerDaoManager daoManager; - - @Autowired - RangerConfigUtil configUtil; - - @Autowired - RESTErrorUtil restErrorUtil; - - @Autowired - SearchUtil searchUtil; - - @Autowired - UserMgr userManager; - - @Autowired - RangerRestUtil msRestUtil; - - @Autowired - XUserMgr xUserMgr; - - private final static List SORT_FIELDS = Arrays.asList( - new SortField("requestDate", "requestDate"), - new SortField("approvedDate", "approvedDate"), - new SortField("activationDate", "activationDate"), - new SortField("emailAddress", "emailAddress"), - new SortField("firstName", "firstName"), - new SortField("lastName", "lastName") - ); - /** - * Implements the traditional search functionalities for UserProfile - * - * @param request - * @return - */ - @GET - @Produces({ "application/json" }) - @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.SEARCH_USERS + "\")") - public VXPortalUserList searchUsers(@Context HttpServletRequest request) { - SearchCriteria searchCriteria = searchUtil.extractCommonCriterias( - request, SORT_FIELDS); - - // 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", RangerConstants.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/json" }) - @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.GET_USER_PROFILE_FOR_USER + "\")") - 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" }) - @Produces({ "application/json" }) - @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.CREATE + "\")") - 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" }) - @Produces({ "application/json" }) - @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.CREATE_DEFAULT_ACCOUNT_USER + "\")") - public VXPortalUser createDefaultAccountUser(VXPortalUser userProfile, - @Context HttpServletRequest servletRequest) { - VXPortalUser vxPortalUser; - vxPortalUser=userManager.createDefaultAccountUser(userProfile); - if(vxPortalUser!=null) - { - xUserMgr.assignPermissionToUser(vxPortalUser, true); - } - return vxPortalUser; - } - - - @PUT - @Consumes({ "application/json" }) - @Produces({ "application/json" }) - @RangerAnnotationRestAPI(updates_classes = "VUserProfile") - @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.UPDATE + "\")") - 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") - @Consumes({ "application/json" }) - @Produces({ "application/json" }) - @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.SET_USER_ROLES + "\")") - 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") - @Consumes({ "application/json" }) - @Produces({ "application/json" }) - @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.DEACTIVATE_USER + "\")") - @RangerAnnotationClassName(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/json" }) - public VXPortalUser getUserProfile(@Context HttpServletRequest request) { - try { - logger.debug("getUserProfile(). httpSessionId=" - + request.getSession().getId()); - Map configProperties = new HashMap<>(); - Long inactivityTimeout = PropertiesUtil.getLongProperty("ranger.service.inactivity.timeout", 15*60); - configProperties.put("inactivityTimeout", Long.toString(inactivityTimeout)); - VXPortalUser userProfile = userManager.getUserProfileByLoginId(); - userProfile.setConfigProperties(configProperties); - return userProfile; - } catch (Throwable t) { - logger.error( - "getUserProfile() no user session. error=" + t.toString(), - t); - } - return null; - } - - /** - * @param userId - * @param changePassword - * @return - */ - @POST - @Path("{userId}/passwordchange") - @Consumes({ "application/json" }) - @Produces({ "application/json" }) - public VXResponse changePassword(@PathParam("userId") Long userId, - VXPasswordChange changePassword) { - if(changePassword==null || stringUtil.isEmpty(changePassword.getLoginId())) { - logger.warn("SECURITY:changePassword(): Invalid loginId provided. loginId was empty or null"); - throw restErrorUtil.createRESTException("serverMsg.userRestUser", MessageEnums.DATA_NOT_FOUND, null, null, ""); - } else if (changePassword.getId() == null) { - changePassword.setId(userId); - } else if (!changePassword.getId().equals(userId) ) { - logger.warn("SECURITY:changePassword(): userId mismatch"); - throw restErrorUtil.createRESTException("serverMsg.userRestUser",MessageEnums.DATA_NOT_FOUND, null, null,""); - } - - XXPortalUser gjUser = daoManager.getXXPortalUser().findByLoginId(changePassword.getLoginId()); - if (gjUser == null) { - logger.warn("SECURITY:changePassword(): Invalid loginId provided: loginId="+ changePassword.getLoginId()); - throw restErrorUtil.createRESTException("serverMsg.userRestUser",MessageEnums.DATA_NOT_FOUND, null, null, changePassword.getLoginId()); - } - - changePassword.setId(gjUser.getId()); - VXResponse ret = userManager.changePassword(changePassword); - return ret; - } - - /** - * - * @param userId - * @param changeEmail - * @return - */ - @POST - @Path("{userId}/emailchange") - @Consumes({ "application/json" }) - @Produces({ "application/json" }) - public VXPortalUser changeEmailAddress(@PathParam("userId") Long userId, - VXPasswordChange changeEmail) { - if(changeEmail==null || stringUtil.isEmpty(changeEmail.getLoginId())) { - logger.warn("SECURITY:changeEmail(): Invalid loginId provided. loginId was empty or null"); - throw restErrorUtil.createRESTException("serverMsg.userRestUser", MessageEnums.DATA_NOT_FOUND, null, null, ""); - } else if (changeEmail.getId() == null) { - changeEmail.setId(userId); - } else if (!changeEmail.getId().equals(userId) ) { - logger.warn("SECURITY:changeEmail(): userId mismatch"); - throw restErrorUtil.createRESTException("serverMsg.userRestUser",MessageEnums.DATA_NOT_FOUND, null, null,""); - } - - logger.info("changeEmail:" + changeEmail.getLoginId()); - XXPortalUser gjUser = daoManager.getXXPortalUser().findByLoginId(changeEmail.getLoginId()); - if (gjUser == null) { - logger.warn("SECURITY:changeEmail(): Invalid loginId provided: loginId="+ changeEmail.getLoginId()); - throw restErrorUtil.createRESTException("serverMsg.userRestUser",MessageEnums.DATA_NOT_FOUND, null, null, changeEmail.getLoginId()); - } - - changeEmail.setId(gjUser.getId()); - VXPortalUser ret = userManager.changeEmailAddress(gjUser, changeEmail); - return ret; - } - + private static final Logger logger = LoggerFactory.getLogger(UserREST.class); + + private static final List SORT_FIELDS = Arrays.asList(new SortField("requestDate", "requestDate"), new SortField("approvedDate", "approvedDate"), new SortField("activationDate", "activationDate"), new SortField("emailAddress", "emailAddress"), new SortField("firstName", "firstName"), new SortField("lastName", "lastName")); + + @Autowired + StringUtil stringUtil; + + @Autowired + RangerDaoManager daoManager; + + @Autowired + RangerConfigUtil configUtil; + + @Autowired + RESTErrorUtil restErrorUtil; + + @Autowired + SearchUtil searchUtil; + + @Autowired + UserMgr userManager; + + @Autowired + RangerRestUtil msRestUtil; + + @Autowired + XUserMgr xUserMgr; + + /** + * Implements the traditional search functionalities for UserProfile + * + * @param request + * @return + */ + @GET + @Produces("application/json") + @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.SEARCH_USERS + "\")") + public VXPortalUserList searchUsers(@Context HttpServletRequest request) { + SearchCriteria searchCriteria = searchUtil.extractCommonCriterias(request, SORT_FIELDS); + + // 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", RangerConstants.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/json") + @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.GET_USER_PROFILE_FOR_USER + "\")") + public VXPortalUser getUserProfileForUser(@PathParam("userId") Long userId) { + try { + VXPortalUser userProfile = userManager.getUserProfile(userId); + + if (userProfile != null) { + 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={}", String.valueOf(t)); + } + + return null; + } + + @POST + @Consumes("application/json") + @Produces("application/json") + @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.CREATE + "\")") + 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") + @Produces("application/json") + @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.CREATE_DEFAULT_ACCOUNT_USER + "\")") + public VXPortalUser createDefaultAccountUser(VXPortalUser userProfile, @Context HttpServletRequest servletRequest) { + VXPortalUser vxPortalUser = userManager.createDefaultAccountUser(userProfile); + + if (vxPortalUser != null) { + xUserMgr.assignPermissionToUser(vxPortalUser, true); + } + + return vxPortalUser; + } + + @PUT + @Consumes("application/json") + @Produces("application/json") + @RangerAnnotationRestAPI(updates_classes = "VUserProfile") + @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.UPDATE + "\")") + 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") + @Consumes("application/json") + @Produces("application/json") + @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.SET_USER_ROLES + "\")") + 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") + @Consumes("application/json") + @Produces("application/json") + @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.DEACTIVATE_USER + "\")") + @RangerAnnotationClassName(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/json") + public VXPortalUser getUserProfile(@Context HttpServletRequest request) { + try { + logger.debug("getUserProfile(). httpSessionId={}", request.getSession().getId()); + + Map configProperties = new HashMap<>(); + long inactivityTimeout = PropertiesUtil.getLongProperty("ranger.service.inactivity.timeout", 15 * 60); + + configProperties.put("inactivityTimeout", Long.toString(inactivityTimeout)); + + VXPortalUser userProfile = userManager.getUserProfileByLoginId(); + + userProfile.setConfigProperties(configProperties); + + return userProfile; + } catch (Throwable t) { + logger.error("getUserProfile() no user session. error={}", t, t); + } + return null; + } + + /** + * @param userId + * @param changePassword + * @return + */ + @POST + @Path("{userId}/passwordchange") + @Consumes("application/json") + @Produces("application/json") + public VXResponse changePassword(@PathParam("userId") Long userId, VXPasswordChange changePassword) { + if (changePassword == null || stringUtil.isEmpty(changePassword.getLoginId())) { + logger.warn("SECURITY:changePassword(): Invalid loginId provided. loginId was empty or null"); + + throw restErrorUtil.createRESTException("serverMsg.userRestUser", MessageEnums.DATA_NOT_FOUND, null, null, ""); + } else if (changePassword.getId() == null) { + changePassword.setId(userId); + } else if (!changePassword.getId().equals(userId)) { + logger.warn("SECURITY:changePassword(): userId mismatch"); + + throw restErrorUtil.createRESTException("serverMsg.userRestUser", MessageEnums.DATA_NOT_FOUND, null, null, ""); + } + + XXPortalUser gjUser = daoManager.getXXPortalUser().findByLoginId(changePassword.getLoginId()); + + if (gjUser == null) { + logger.warn("SECURITY:changePassword(): Invalid loginId provided: loginId={}", changePassword.getLoginId()); + + throw restErrorUtil.createRESTException("serverMsg.userRestUser", MessageEnums.DATA_NOT_FOUND, null, null, changePassword.getLoginId()); + } + + changePassword.setId(gjUser.getId()); + + return userManager.changePassword(changePassword); + } + + /** + * @param userId + * @param changeEmail + * @return + */ + @POST + @Path("{userId}/emailchange") + @Consumes("application/json") + @Produces("application/json") + public VXPortalUser changeEmailAddress(@PathParam("userId") Long userId, VXPasswordChange changeEmail) { + if (changeEmail == null || stringUtil.isEmpty(changeEmail.getLoginId())) { + logger.warn("SECURITY:changeEmail(): Invalid loginId provided. loginId was empty or null"); + + throw restErrorUtil.createRESTException("serverMsg.userRestUser", MessageEnums.DATA_NOT_FOUND, null, null, ""); + } else if (changeEmail.getId() == null) { + changeEmail.setId(userId); + } else if (!changeEmail.getId().equals(userId)) { + logger.warn("SECURITY:changeEmail(): userId mismatch"); + + throw restErrorUtil.createRESTException("serverMsg.userRestUser", MessageEnums.DATA_NOT_FOUND, null, null, ""); + } + + logger.info("changeEmail:{}", changeEmail.getLoginId()); + + XXPortalUser gjUser = daoManager.getXXPortalUser().findByLoginId(changeEmail.getLoginId()); + + if (gjUser == null) { + logger.warn("SECURITY:changeEmail(): Invalid loginId provided: loginId={}", changeEmail.getLoginId()); + + throw restErrorUtil.createRESTException("serverMsg.userRestUser", MessageEnums.DATA_NOT_FOUND, null, null, changeEmail.getLoginId()); + } + + changeEmail.setId(gjUser.getId()); + + return userManager.changeEmailAddress(gjUser, changeEmail); + } } diff --git a/security-admin/src/main/java/org/apache/ranger/rest/XAuditREST.java b/security-admin/src/main/java/org/apache/ranger/rest/XAuditREST.java index 4160f15022..6784143490 100644 --- a/security-admin/src/main/java/org/apache/ranger/rest/XAuditREST.java +++ b/security-admin/src/main/java/org/apache/ranger/rest/XAuditREST.java @@ -17,27 +17,18 @@ * under the License. */ - package org.apache.ranger.rest; - -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.Consumes; -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; +package org.apache.ranger.rest; +import org.apache.ranger.biz.RangerBizUtil; import org.apache.ranger.biz.XAuditMgr; import org.apache.ranger.common.SearchCriteria; import org.apache.ranger.common.SearchUtil; import org.apache.ranger.common.annotation.RangerAnnotationClassName; import org.apache.ranger.common.annotation.RangerAnnotationJSMgrName; +import org.apache.ranger.plugin.store.EmbeddedServiceDefsUtil; import org.apache.ranger.security.context.RangerAPIList; -import org.apache.ranger.service.XAccessAuditService; import org.apache.ranger.service.RangerTrxLogV2Service; +import org.apache.ranger.service.XAccessAuditService; import org.apache.ranger.view.VXAccessAuditList; import org.apache.ranger.view.VXLong; import org.apache.ranger.view.VXTrxLog; @@ -48,8 +39,17 @@ import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; -import org.apache.ranger.plugin.store.EmbeddedServiceDefsUtil; -import org.apache.ranger.biz.RangerBizUtil; + +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.Consumes; +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; @Path("xaudit") @Component @@ -57,125 +57,120 @@ @RangerAnnotationJSMgrName("XAuditMgr") @Transactional(propagation = Propagation.REQUIRES_NEW) public class XAuditREST { - - @Autowired - SearchUtil searchUtil; - - @Autowired - XAuditMgr xAuditMgr; - - @Autowired - RangerTrxLogV2Service xTrxLogService; - - @Autowired - XAccessAuditService xAccessAuditService; - - @Autowired - RangerBizUtil bizUtil; - - // Handle XTrxLog - @GET - @Path("/trx_log/{id}") - @Produces({ "application/json" }) - @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.GET_X_TRX_LOG + "\")") - public VXTrxLog getXTrxLog( - @PathParam("id") Long id) { - return xAuditMgr.getXTrxLog(id); - } - - @POST - @Path("/trx_log") - @Consumes({ "application/json" }) - @Produces({ "application/json" }) - @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.CREATE_X_TRX_LOG + "\")") - public VXTrxLog createXTrxLog(VXTrxLog vXTrxLog) { - return xAuditMgr.createXTrxLog(vXTrxLog); - } - - @PUT - @Path("/trx_log") - @Consumes({ "application/json" }) - @Produces({ "application/json" }) - @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.UPDATE_X_TRX_LOG + "\")") - public VXTrxLog updateXTrxLog(VXTrxLog vXTrxLog) { - return xAuditMgr.updateXTrxLog(vXTrxLog); - } - - @DELETE - @Path("/trx_log/{id}") - @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.DELETE_X_TRX_LOG + "\")") - @RangerAnnotationClassName(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/json" }) - @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.SEARCH_X_TRX_LOG + "\")") - public VXTrxLogList searchXTrxLogs(@Context HttpServletRequest request) { - SearchCriteria searchCriteria = searchUtil.extractCommonCriterias( - request, xTrxLogService.getSortFields()); - return xAuditMgr.searchXTrxLogs(searchCriteria); - } - - @GET - @Path("/trx_log/count") - @Produces({ "application/json" }) - @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.COUNT_X_TRX_LOGS + "\")") - public VXLong countXTrxLogs(@Context HttpServletRequest request) { - SearchCriteria searchCriteria = searchUtil.extractCommonCriterias( - request, xTrxLogService.getSortFields()); - - return xAuditMgr.getXTrxLogSearchCount(searchCriteria); - } - - - /** - * Implements the traditional search functionalities for XAccessAudits - * - * @param request - * @return - */ - @GET - @Path("/access_audit") - @Produces({ "application/json" }) - @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.SEARCH_X_ACCESS_AUDITS + "\")") - public VXAccessAuditList searchXAccessAudits(@Context HttpServletRequest request) { - SearchCriteria searchCriteria = searchUtil.extractCommonCriterias(request, xAccessAuditService.sortFields); - long kmsServiceDefId = EmbeddedServiceDefsUtil.instance().getKmsServiceDefId(); - - if (kmsServiceDefId != -1) { - boolean includeKmsAuditLogs = bizUtil.isKeyAdmin() || bizUtil.isAuditKeyAdmin(); - - if (includeKmsAuditLogs) { - searchCriteria.getParamList().put("repoType", kmsServiceDefId); - } else { - searchCriteria.getParamList().put("-repoType", kmsServiceDefId); - } - } - - return xAuditMgr.searchXAccessAudits(searchCriteria); - } - - @GET - @Path("/access_audit/count") - @Produces({ "application/json" }) - @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.COUNT_X_ACCESS_AUDITS + "\")") - public VXLong countXAccessAudits(@Context HttpServletRequest request) { - VXLong ret = new VXLong(); - - ret.setValue(searchXAccessAudits(request).getTotalCount()); - - return ret; - } - + @Autowired + SearchUtil searchUtil; + + @Autowired + XAuditMgr xAuditMgr; + + @Autowired + RangerTrxLogV2Service xTrxLogService; + + @Autowired + XAccessAuditService xAccessAuditService; + + @Autowired + RangerBizUtil bizUtil; + + // Handle XTrxLog + @GET + @Path("/trx_log/{id}") + @Produces("application/json") + @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.GET_X_TRX_LOG + "\")") + public VXTrxLog getXTrxLog(@PathParam("id") Long id) { + return xAuditMgr.getXTrxLog(id); + } + + @POST + @Path("/trx_log") + @Consumes("application/json") + @Produces("application/json") + @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.CREATE_X_TRX_LOG + "\")") + public VXTrxLog createXTrxLog(VXTrxLog vXTrxLog) { + return xAuditMgr.createXTrxLog(vXTrxLog); + } + + @PUT + @Path("/trx_log") + @Consumes("application/json") + @Produces("application/json") + @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.UPDATE_X_TRX_LOG + "\")") + public VXTrxLog updateXTrxLog(VXTrxLog vXTrxLog) { + return xAuditMgr.updateXTrxLog(vXTrxLog); + } + + @DELETE + @Path("/trx_log/{id}") + @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.DELETE_X_TRX_LOG + "\")") + @RangerAnnotationClassName(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/json") + @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.SEARCH_X_TRX_LOG + "\")") + public VXTrxLogList searchXTrxLogs(@Context HttpServletRequest request) { + SearchCriteria searchCriteria = searchUtil.extractCommonCriterias(request, xTrxLogService.getSortFields()); + + return xAuditMgr.searchXTrxLogs(searchCriteria); + } + + @GET + @Path("/trx_log/count") + @Produces("application/json") + @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.COUNT_X_TRX_LOGS + "\")") + public VXLong countXTrxLogs(@Context HttpServletRequest request) { + SearchCriteria searchCriteria = searchUtil.extractCommonCriterias(request, xTrxLogService.getSortFields()); + + return xAuditMgr.getXTrxLogSearchCount(searchCriteria); + } + + /** + * Implements the traditional search functionalities for XAccessAudits + * + * @param request + * @return + */ + @GET + @Path("/access_audit") + @Produces("application/json") + @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.SEARCH_X_ACCESS_AUDITS + "\")") + public VXAccessAuditList searchXAccessAudits(@Context HttpServletRequest request) { + SearchCriteria searchCriteria = searchUtil.extractCommonCriterias(request, xAccessAuditService.sortFields); + long kmsServiceDefId = EmbeddedServiceDefsUtil.instance().getKmsServiceDefId(); + + if (kmsServiceDefId != -1) { + boolean includeKmsAuditLogs = bizUtil.isKeyAdmin() || bizUtil.isAuditKeyAdmin(); + + if (includeKmsAuditLogs) { + searchCriteria.getParamList().put("repoType", kmsServiceDefId); + } else { + searchCriteria.getParamList().put("-repoType", kmsServiceDefId); + } + } + + return xAuditMgr.searchXAccessAudits(searchCriteria); + } + + @GET + @Path("/access_audit/count") + @Produces("application/json") + @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.COUNT_X_ACCESS_AUDITS + "\")") + public VXLong countXAccessAudits(@Context HttpServletRequest request) { + VXLong ret = new VXLong(); + + ret.setValue(searchXAccessAudits(request).getTotalCount()); + + return ret; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/rest/XKeyREST.java b/security-admin/src/main/java/org/apache/ranger/rest/XKeyREST.java index f07c7824c1..192fe63211 100755 --- a/security-admin/src/main/java/org/apache/ranger/rest/XKeyREST.java +++ b/security-admin/src/main/java/org/apache/ranger/rest/XKeyREST.java @@ -18,20 +18,9 @@ */ package org.apache.ranger.rest; -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.Consumes; -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.QueryParam; -import javax.ws.rs.core.Context; - import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonNode; +import com.sun.jersey.api.client.UniformInterfaceException; import org.apache.ranger.biz.KmsKeyMgr; import org.apache.ranger.common.MessageEnums; import org.apache.ranger.common.RESTErrorUtil; @@ -50,8 +39,17 @@ import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; -import com.sun.jersey.api.client.UniformInterfaceException; - +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.Consumes; +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.QueryParam; +import javax.ws.rs.core.Context; @Path("keys") @Component @@ -59,164 +57,200 @@ @RangerAnnotationJSMgrName("KeyMgr") @Transactional(propagation = Propagation.REQUIRES_NEW) public class XKeyREST { - private static final Logger logger = LoggerFactory.getLogger(XKeyREST.class); - - private static String UNAUTHENTICATED_MSG = "Unauthenticated : Please check the permission in the policy for the user"; - - @Autowired - KmsKeyMgr keyMgr; - - @Autowired - SearchUtil searchUtil; - - @Autowired - RESTErrorUtil restErrorUtil; - - /** - * Implements the traditional search functionalities for Keys - * - * @param request - * @return - */ - @GET - @Path("/keys") - @Produces({ "application/json" }) - @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.SEARCH_KEYS + "\")") - public VXKmsKeyList searchKeys(@Context HttpServletRequest request, @QueryParam("provider") String provider) { - VXKmsKeyList vxKmsKeyList = new VXKmsKeyList(); - try{ - vxKmsKeyList = keyMgr.searchKeys(request, provider); - }catch(Exception e){ - handleError(e); - } - return vxKmsKeyList; - } - - /** - * Implements the Rollover key functionality - * @param vXKey - * @return - */ - @PUT - @Path("/key") - @Consumes({ "application/json" }) - @Produces({ "application/json" }) - @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.ROLLOVER_KEYS + "\")") - public VXKmsKey rolloverKey(@QueryParam("provider") String provider, VXKmsKey vXKey) { - VXKmsKey vxKmsKey = new VXKmsKey(); - try{ - String name = vXKey.getName(); - if (name == null || name.isEmpty()) { - throw restErrorUtil.createRESTException("Please provide a valid " - + "alias.", MessageEnums.INVALID_INPUT_DATA); - } - if(vXKey.getCipher() == null || vXKey.getCipher().trim().isEmpty()){ - vXKey.setCipher(null); - } - vxKmsKey = keyMgr.rolloverKey(provider, vXKey); - }catch(Exception e){ - handleError(e); - } - return vxKmsKey; - } - - /** - * Implements the delete key functionality - * @param name - * @param request - */ - @DELETE - @Path("/key/{alias}") - @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.DELETE_KEY + "\")") - public void deleteKey(@PathParam("alias") String name, @QueryParam("provider") String provider, @Context HttpServletRequest request) { - try{ - if (name == null || name.isEmpty()) { - throw restErrorUtil.createRESTException("Please provide a valid " - + "alias.", MessageEnums.INVALID_INPUT_DATA); - } - keyMgr.deleteKey(provider, name); - }catch(Exception e){ - handleError(e); - } - } - - /** - * Implements the create key functionality - * @param vXKey - * @return - */ - @POST - @Path("/key") - @Consumes({ "application/json" }) - @Produces({ "application/json" }) - @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.CREATE_KEY + "\")") - public VXKmsKey createKey(@QueryParam("provider") String provider, VXKmsKey vXKey) { - VXKmsKey vxKmsKey = new VXKmsKey(); - try{ - String name = vXKey.getName(); - if (name == null || name.isEmpty()) { - throw restErrorUtil.createRESTException("Please provide a valid " - + "alias.", MessageEnums.INVALID_INPUT_DATA); - } - if(vXKey.getCipher() == null || vXKey.getCipher().trim().isEmpty()){ - vXKey.setCipher(null); - } - vxKmsKey = keyMgr.createKey(provider, vXKey); - }catch(Exception e){ - handleError(e); - } - return vxKmsKey; - } - - /** - * - * @param name - * @param provider - * @return - */ - @GET - @Path("/key/{alias}") - @Produces({ "application/json" }) - @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.GET_KEY + "\")") - public VXKmsKey getKey(@PathParam("alias") String name,@QueryParam("provider") String provider){ - VXKmsKey vxKmsKey = new VXKmsKey(); - try{ - if (name == null || name.isEmpty()) { - throw restErrorUtil.createRESTException("Please provide a valid " - + "alias.", MessageEnums.INVALID_INPUT_DATA); - } - vxKmsKey = keyMgr.getKey(provider, name); - }catch(Exception e){ - handleError(e); - } - return vxKmsKey; - } - - private void handleError(Exception e) { - String message = e.getMessage(); - if (e instanceof UniformInterfaceException){ - UniformInterfaceException uie=(UniformInterfaceException)e; - message = uie.getResponse().getEntity(String.class); - logger.error(message); - try { - JsonNode rootNode = JsonUtilsV2.getMapper().readTree(message); - JsonNode excpNode = rootNode != null ? rootNode.get("RemoteException") : null; - JsonNode msgNode = excpNode != null ? excpNode.get("message") : null; - - message = msgNode != null ? msgNode.asText() : null; - } catch (JsonProcessingException e1) { - logger.error("Unable to parse the error message, So sending error message as it is - Error : " + e1.getMessage()); - } - } - if (!(message==null) && !(message.isEmpty()) && message.contains("Connection refused")){ - message = "Connection refused : Please check the KMS provider URL and whether the Ranger KMS is running"; - } else if (!(message==null) && !(message.isEmpty()) && (message.contains("response status of 403") || message.contains("HTTP Status 403"))){ - message = UNAUTHENTICATED_MSG; - } else if (!(message==null) && !(message.isEmpty()) && (message.contains("response status of 401") || message.contains("HTTP Status 401 - Authentication required"))){ - message = UNAUTHENTICATED_MSG; - } else if (message == null) { - message = UNAUTHENTICATED_MSG; - } - throw restErrorUtil.createRESTException(message, MessageEnums.ERROR_SYSTEM); - } + private static final Logger logger = LoggerFactory.getLogger(XKeyREST.class); + + private static final String UNAUTHENTICATED_MSG = "Unauthenticated : Please check the permission in the policy for the user"; + + @Autowired + KmsKeyMgr keyMgr; + + @Autowired + SearchUtil searchUtil; + + @Autowired + RESTErrorUtil restErrorUtil; + + /** + * Implements the traditional search functionalities for Keys + * + * @param request + * @return + */ + @GET + @Path("/keys") + @Produces("application/json") + @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.SEARCH_KEYS + "\")") + public VXKmsKeyList searchKeys(@Context HttpServletRequest request, @QueryParam("provider") String provider) { + VXKmsKeyList vxKmsKeyList = null; + + try { + vxKmsKeyList = keyMgr.searchKeys(request, provider); + } catch (Exception e) { + handleError(e); + } finally { + if (vxKmsKeyList == null) { + vxKmsKeyList = new VXKmsKeyList(); + } + } + + return vxKmsKeyList; + } + + /** + * Implements the Rollover key functionality + * + * @param vXKey + * @return + */ + @PUT + @Path("/key") + @Consumes("application/json") + @Produces("application/json") + @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.ROLLOVER_KEYS + "\")") + public VXKmsKey rolloverKey(@QueryParam("provider") String provider, VXKmsKey vXKey) { + VXKmsKey vxKmsKey = null; + + try { + String name = vXKey.getName(); + + if (name == null || name.isEmpty()) { + throw restErrorUtil.createRESTException("Please provide a valid " + "alias.", MessageEnums.INVALID_INPUT_DATA); + } + + if (vXKey.getCipher() == null || vXKey.getCipher().trim().isEmpty()) { + vXKey.setCipher(null); + } + + vxKmsKey = keyMgr.rolloverKey(provider, vXKey); + } catch (Exception e) { + handleError(e); + } finally { + if (vxKmsKey == null) { + vxKmsKey = new VXKmsKey(); + } + } + + return vxKmsKey; + } + + /** + * Implements the delete key functionality + * + * @param name + * @param request + */ + @DELETE + @Path("/key/{alias}") + @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.DELETE_KEY + "\")") + public void deleteKey(@PathParam("alias") String name, @QueryParam("provider") String provider, @Context HttpServletRequest request) { + try { + if (name == null || name.isEmpty()) { + throw restErrorUtil.createRESTException("Please provide a valid " + "alias.", MessageEnums.INVALID_INPUT_DATA); + } + + keyMgr.deleteKey(provider, name); + } catch (Exception e) { + handleError(e); + } + } + + /** + * Implements the create key functionality + * + * @param vXKey + * @return + */ + @POST + @Path("/key") + @Consumes("application/json") + @Produces("application/json") + @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.CREATE_KEY + "\")") + public VXKmsKey createKey(@QueryParam("provider") String provider, VXKmsKey vXKey) { + VXKmsKey vxKmsKey = null; + + try { + String name = vXKey.getName(); + + if (name == null || name.isEmpty()) { + throw restErrorUtil.createRESTException("Please provide a valid " + "alias.", MessageEnums.INVALID_INPUT_DATA); + } + + if (vXKey.getCipher() == null || vXKey.getCipher().trim().isEmpty()) { + vXKey.setCipher(null); + } + + vxKmsKey = keyMgr.createKey(provider, vXKey); + } catch (Exception e) { + handleError(e); + } finally { + if (vxKmsKey == null) { + vxKmsKey = new VXKmsKey(); + } + } + + return vxKmsKey; + } + + /** + * @param name + * @param provider + * @return + */ + @GET + @Path("/key/{alias}") + @Produces("application/json") + @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.GET_KEY + "\")") + public VXKmsKey getKey(@PathParam("alias") String name, @QueryParam("provider") String provider) { + VXKmsKey vxKmsKey = null; + + try { + if (name == null || name.isEmpty()) { + throw restErrorUtil.createRESTException("Please provide a valid " + "alias.", MessageEnums.INVALID_INPUT_DATA); + } + + vxKmsKey = keyMgr.getKey(provider, name); + } catch (Exception e) { + handleError(e); + } finally { + if (vxKmsKey == null) { + vxKmsKey = new VXKmsKey(); + } + } + + return vxKmsKey; + } + + private void handleError(Exception e) { + String message = e.getMessage(); + + if (e instanceof UniformInterfaceException) { + UniformInterfaceException uie = (UniformInterfaceException) e; + + message = uie.getResponse().getEntity(String.class); + + logger.error(message); + + try { + JsonNode rootNode = JsonUtilsV2.getMapper().readTree(message); + JsonNode excpNode = rootNode != null ? rootNode.get("RemoteException") : null; + JsonNode msgNode = excpNode != null ? excpNode.get("message") : null; + + message = msgNode != null ? msgNode.asText() : null; + } catch (JsonProcessingException e1) { + logger.error("Unable to parse the error message, So sending error message as it is - Error : {}", e1.getMessage()); + } + } + + if (message == null) { + message = UNAUTHENTICATED_MSG; + } else if (message.contains("Connection refused")) { + message = "Connection refused : Please check the KMS provider URL and whether the Ranger KMS is running"; + } else if (message.contains("response status of 403") || message.contains("HTTP Status 403")) { + message = UNAUTHENTICATED_MSG; + } else if (message.contains("response status of 401") || message.contains("HTTP Status 401 - Authentication required")) { + message = UNAUTHENTICATED_MSG; + } + + throw restErrorUtil.createRESTException(message, MessageEnums.ERROR_SYSTEM); + } } diff --git a/security-admin/src/main/java/org/apache/ranger/rest/XUserREST.java b/security-admin/src/main/java/org/apache/ranger/rest/XUserREST.java index 020cf61847..e8b51db0a8 100755 --- a/security-admin/src/main/java/org/apache/ranger/rest/XUserREST.java +++ b/security-admin/src/main/java/org/apache/ranger/rest/XUserREST.java @@ -19,42 +19,20 @@ package org.apache.ranger.rest; -import java.util.Set; -import java.util.Map; -import java.util.List; -import java.util.ArrayList; -import java.util.HashMap; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.ws.rs.Consumes; -import javax.ws.rs.DefaultValue; -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.QueryParam; -import javax.ws.rs.WebApplicationException; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.Response; - import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang.StringUtils; +import org.apache.ranger.biz.AssetMgr; import org.apache.ranger.biz.RangerBizUtil; +import org.apache.ranger.biz.ServiceDBStore; import org.apache.ranger.biz.SessionMgr; import org.apache.ranger.biz.XUserMgr; -import org.apache.ranger.biz.AssetMgr; -import org.apache.ranger.biz.ServiceDBStore; -import org.apache.ranger.common.ServiceUtil; import org.apache.ranger.common.ContextUtil; import org.apache.ranger.common.MessageEnums; import org.apache.ranger.common.RESTErrorUtil; import org.apache.ranger.common.RangerConstants; import org.apache.ranger.common.SearchCriteria; import org.apache.ranger.common.SearchUtil; +import org.apache.ranger.common.ServiceUtil; import org.apache.ranger.common.StringUtil; import org.apache.ranger.common.UserSessionBase; import org.apache.ranger.common.annotation.RangerAnnotationClassName; @@ -82,7 +60,31 @@ import org.apache.ranger.service.XUserService; import org.apache.ranger.ugsyncutil.model.GroupUserInfo; import org.apache.ranger.ugsyncutil.model.UsersGroupRoleAssignments; -import org.apache.ranger.view.*; +import org.apache.ranger.view.VXAuditMap; +import org.apache.ranger.view.VXAuditMapList; +import org.apache.ranger.view.VXAuthSession; +import org.apache.ranger.view.VXAuthSessionList; +import org.apache.ranger.view.VXGroup; +import org.apache.ranger.view.VXGroupList; +import org.apache.ranger.view.VXGroupPermission; +import org.apache.ranger.view.VXGroupPermissionList; +import org.apache.ranger.view.VXGroupUser; +import org.apache.ranger.view.VXGroupUserInfo; +import org.apache.ranger.view.VXGroupUserList; +import org.apache.ranger.view.VXLong; +import org.apache.ranger.view.VXModuleDef; +import org.apache.ranger.view.VXModuleDefList; +import org.apache.ranger.view.VXModulePermissionList; +import org.apache.ranger.view.VXPermMap; +import org.apache.ranger.view.VXPermMapList; +import org.apache.ranger.view.VXString; +import org.apache.ranger.view.VXStringList; +import org.apache.ranger.view.VXUgsyncAuditInfo; +import org.apache.ranger.view.VXUser; +import org.apache.ranger.view.VXUserGroupInfo; +import org.apache.ranger.view.VXUserList; +import org.apache.ranger.view.VXUserPermission; +import org.apache.ranger.view.VXUserPermissionList; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -92,1327 +94,1297 @@ import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.DefaultValue; +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.WebApplicationException; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.Response; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + import static org.apache.ranger.common.RangerCommonEnums.GROUP_EXTERNAL; import static org.apache.ranger.common.RangerCommonEnums.USER_EXTERNAL; - @Path("xusers") @Component @Scope("request") @RangerAnnotationJSMgrName("XUserMgr") @Transactional(propagation = Propagation.REQUIRES_NEW) public class XUserREST { + static final Logger logger = LoggerFactory.getLogger(XUserREST.class); - public static final String USERSTORE_DOWNLOAD_USERS = "userstore.download.auth.users"; + public static final String USERSTORE_DOWNLOAD_USERS = "userstore.download.auth.users"; - @Autowired - SearchUtil searchUtil; + @Autowired + SearchUtil searchUtil; - @Autowired - XUserMgr xUserMgr; + @Autowired + XUserMgr xUserMgr; - @Autowired - XGroupService xGroupService; + @Autowired + XGroupService xGroupService; - @Autowired - XModuleDefService xModuleDefService; + @Autowired + XModuleDefService xModuleDefService; - @Autowired - XUserPermissionService xUserPermissionService; + @Autowired + XUserPermissionService xUserPermissionService; - @Autowired - XGroupPermissionService xGroupPermissionService; - - @Autowired - XUserService xUserService; - - @Autowired - XGroupUserService xGroupUserService; - - @Autowired - XPermMapService xPermMapService; - - @Autowired - XAuditMapService xAuditMapService; - - @Autowired - RESTErrorUtil restErrorUtil; - - @Autowired - RangerDaoManager rangerDaoManager; - - @Autowired - SessionMgr sessionMgr; - - @Autowired - AuthSessionService authSessionService; - - @Autowired - RangerBizUtil bizUtil; - - @Autowired - XResourceService xResourceService; - - @Autowired - StringUtil stringUtil; - - @Autowired - AssetMgr assetMgr; - - @Autowired - ServiceUtil serviceUtil; - - @Autowired - ServiceDBStore svcStore; - - - static final Logger logger = LoggerFactory.getLogger(XUserMgr.class); - - // Handle XGroup - @GET - @Path("/groups/{id}") - @Produces({ "application/json" }) - @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.GET_X_GROUP + "\")") - public VXGroup getXGroup(@PathParam("id") Long id) { - return xUserMgr.getXGroup(id); - } - - @GET - @Path("/secure/groups/{id}") - @Produces({ "application/json" }) - @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.SECURE_GET_X_GROUP + "\")") - public VXGroup secureGetXGroup(@PathParam("id") Long id) { - return xUserMgr.getXGroup(id); - } - - @POST - @Path("/groups") - @Consumes({ "application/json" }) - @Produces({ "application/json" }) - @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") - public VXGroup createXGroup(VXGroup vXGroup) { - return xUserMgr.createXGroupWithoutLogin(vXGroup); - } - - @POST - @Path("/groups/groupinfo") - @Consumes({ "application/json" }) - @Produces({ "application/json" }) - @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") - public VXGroupUserInfo createXGroupUserFromMap(VXGroupUserInfo vXGroupUserInfo) { - return xUserMgr.createXGroupUserFromMap(vXGroupUserInfo); - } - - @POST - @Path("/secure/groups") - @Consumes({ "application/json" }) - @Produces({ "application/json" }) - @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") - public VXGroup secureCreateXGroup(VXGroup vXGroup) { - return xUserMgr.createXGroup(vXGroup); - } - - @PUT - @Path("/groups") - @Consumes({ "application/json" }) - @Produces({ "application/json" }) - public VXGroup updateXGroup(VXGroup vXGroup) { - return xUserMgr.updateXGroup(vXGroup); - } - - @PUT - @Path("/secure/groups/{id}") - @Consumes({ "application/json" }) - @Produces({ "application/json" }) - public VXGroup secureUpdateXGroup(VXGroup vXGroup) { - return xUserMgr.updateXGroup(vXGroup); - } - - @PUT - @Path("/secure/groups/visibility") - @Consumes({ "application/json" }) - @Produces({ "application/json" }) - @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.MODIFY_GROUPS_VISIBILITY + "\")") - public void modifyGroupsVisibility(HashMap groupVisibilityMap){ - xUserMgr.modifyGroupsVisibility(groupVisibilityMap); - } - - @DELETE - @Path("/groups/{id}") - @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") - @RangerAnnotationClassName(class_name = VXGroup.class) - public void deleteXGroup(@PathParam("id") Long id, - @Context HttpServletRequest request) { - String forceDeleteStr = request.getParameter("forceDelete"); - boolean forceDelete = false; - if(!StringUtils.isEmpty(forceDeleteStr) && "true".equalsIgnoreCase(forceDeleteStr.trim())) { - forceDelete = true; - } - xUserMgr.deleteXGroup(id, forceDelete); - } - - /** - * Implements the traditional search functionalities for XGroups - * - * @param request - * @return - */ - @GET - @Path("/groups") - @Produces({ "application/json" }) - @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.SEARCH_X_GROUPS + "\")") - public VXGroupList searchXGroups(@Context HttpServletRequest request) { - SearchCriteria searchCriteria = searchUtil.extractCommonCriterias( - request, xGroupService.sortFields); - searchUtil.extractString(request, searchCriteria, "name", "group name", null); - searchUtil.extractInt(request, searchCriteria, "isVisible", "Group Visibility"); - searchUtil.extractInt(request, searchCriteria, "groupSource", "group source"); - searchUtil.extractString(request, searchCriteria, "syncSource", "Sync Source", null); - return xUserMgr.searchXGroups(searchCriteria); - } - - @GET - @Path("/groups/count") - @Produces({ "application/json" }) - @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.COUNT_X_GROUPS + "\")") - 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/json" }) - @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.GET_X_USER + "\")") - public VXUser getXUser(@PathParam("id") Long id) { - return xUserMgr.getXUser(id); - } - - @GET - @Path("/secure/users/{id}") - @Produces({ "application/json" }) - @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.SECURE_GET_X_USER + "\")") - public VXUser secureGetXUser(@PathParam("id") Long id) { - return xUserMgr.getXUser(id); - } - - @POST - @Path("/users") - @Consumes({ "application/json" }) - @Produces({ "application/json" }) - @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") - public VXUser createXUser(VXUser vXUser) { - return xUserMgr.createXUserWithOutLogin(vXUser); - } - - @POST - @Path("/users/external") - @Consumes({ "application/json" }) - @Produces({ "application/json" }) - @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") - public VXUser createExternalUser(VXUser vXUser) { - return xUserMgr.createExternalUser(vXUser.getName()); - } - - @POST - @Path("/users/userinfo") - @Consumes({ "application/json" }) - @Produces({ "application/json" }) - @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") - public VXUserGroupInfo createXUserGroupFromMap(VXUserGroupInfo vXUserGroupInfo) { - return xUserMgr.createXUserGroupFromMap(vXUserGroupInfo); - } - - @POST - @Path("/secure/users") - @Consumes({ "application/json" }) - @Produces({ "application/json" }) - @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") - public VXUser secureCreateXUser(VXUser vXUser) { - - bizUtil.checkUserAccessible(vXUser); - return xUserMgr.createXUser(vXUser); - } - - @PUT - @Path("/users") - @Consumes({ "application/json" }) - @Produces({ "application/json" }) - public VXUser updateXUser(VXUser vXUser) { - bizUtil.checkUserAccessible(vXUser); - return xUserMgr.updateXUser(vXUser); - } - - @PUT - @Path("/secure/users/{id}") - @Consumes({ "application/json" }) - @Produces({ "application/json" }) - public VXUser secureUpdateXUser(VXUser vXUser) { - - bizUtil.checkUserAccessible(vXUser); - return xUserMgr.updateXUser(vXUser); - } - - @PUT - @Path("/secure/users/visibility") - @Consumes({ "application/json" }) - @Produces({ "application/json" }) - @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.MODIFY_USER_VISIBILITY + "\")") - public void modifyUserVisibility(HashMap visibilityMap){ - xUserMgr.modifyUserVisibility(visibilityMap); - } - - @DELETE - @Path("/users/{id}") - @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") - @RangerAnnotationClassName(class_name = VXUser.class) - public void deleteXUser(@PathParam("id") Long id, - @Context HttpServletRequest request) { - String forceDeleteStr = request.getParameter("forceDelete"); - boolean forceDelete = false; - if(!StringUtils.isEmpty(forceDeleteStr) && forceDeleteStr.equalsIgnoreCase("true")) { - forceDelete = true; - } - xUserMgr.deleteXUser(id, forceDelete); - } - - /** - * Implements the traditional search functionalities for XUsers - * - * @param request - * @return - */ - @GET - @Path("/users") - @Produces({ "application/json" }) - @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.SEARCH_X_USERS + "\")") - public VXUserList searchXUsers(@Context HttpServletRequest request, @QueryParam("syncSource") String syncSource, @QueryParam("userRole") String userRole) { - String UserRoleParamName = RangerConstants.ROLE_USER; - SearchCriteria searchCriteria = searchUtil.extractCommonCriterias( - request, xUserService.sortFields); - String userName = null; - if (request.getUserPrincipal() != null){ - userName = request.getUserPrincipal().getName(); - } - searchUtil.extractString(request, searchCriteria, "name", "User name",null); - searchUtil.extractString(request, searchCriteria, "emailAddress", "Email Address", - null); - searchUtil.extractInt(request, searchCriteria, "userSource", "User Source"); - searchUtil.extractInt(request, searchCriteria, "isVisible", "User Visibility"); - searchUtil.extractInt(request, searchCriteria, "status", "User Status"); - List userRolesList = searchUtil.extractStringList(request, searchCriteria, "userRoleList", - "User Role List", "userRoleList", null, null); - searchUtil.extractRoleString(request, searchCriteria, "userRole", "Role", null); - searchUtil.extractString(request, searchCriteria, "syncSource", "Sync Source", null); - - if (CollectionUtils.isNotEmpty(userRolesList) && CollectionUtils.size(userRolesList) == 1 && userRolesList.get(0).equalsIgnoreCase(UserRoleParamName)) { - if (!(searchCriteria.getParamList().containsKey("name"))) { - searchCriteria.addParam("name", userName); - } - else if ((searchCriteria.getParamList().containsKey("name")) && userName!= null && userName.contains((String) searchCriteria.getParamList().get("name"))) { - searchCriteria.addParam("name", userName); - } - } - - - UserSessionBase userSession = ContextUtil.getCurrentUserSession(); - if (userSession != null && userSession.getLoginId() != null) { - VXUser loggedInVXUser = xUserService.getXUserByUserName(userSession.getLoginId()); - if (loggedInVXUser != null && loggedInVXUser.getUserRoleList().size() == 1) { - if (loggedInVXUser.getUserRoleList().contains(RangerConstants.ROLE_SYS_ADMIN) || loggedInVXUser.getUserRoleList().contains(RangerConstants.ROLE_ADMIN_AUDITOR)) { - boolean hasRole = false; - hasRole = !userRolesList.contains(RangerConstants.ROLE_SYS_ADMIN) ? userRolesList.add(RangerConstants.ROLE_SYS_ADMIN) : hasRole; - hasRole = !userRolesList.contains(RangerConstants.ROLE_ADMIN_AUDITOR) ? userRolesList.add(RangerConstants.ROLE_ADMIN_AUDITOR) : hasRole; - hasRole = !userRolesList.contains(RangerConstants.ROLE_USER) ? userRolesList.add(RangerConstants.ROLE_USER) : hasRole; - if (loggedInVXUser.getUserRoleList().contains(RangerConstants.ROLE_SYS_ADMIN) && "rangerusersync".equalsIgnoreCase(userSession.getLoginId())) { - hasRole = !userRolesList.contains(RangerConstants.ROLE_KEY_ADMIN) ? userRolesList.add(RangerConstants.ROLE_KEY_ADMIN) : hasRole; - hasRole = !userRolesList.contains(RangerConstants.ROLE_KEY_ADMIN_AUDITOR) ? userRolesList.add(RangerConstants.ROLE_KEY_ADMIN_AUDITOR) : hasRole; - } - } else if (loggedInVXUser.getUserRoleList().contains(RangerConstants.ROLE_KEY_ADMIN) || loggedInVXUser.getUserRoleList().contains(RangerConstants.ROLE_KEY_ADMIN_AUDITOR)) { - boolean hasRole = false; - hasRole = !userRolesList.contains(RangerConstants.ROLE_KEY_ADMIN) ? userRolesList.add(RangerConstants.ROLE_KEY_ADMIN) : hasRole; - hasRole = !userRolesList.contains(RangerConstants.ROLE_KEY_ADMIN_AUDITOR) ? userRolesList.add(RangerConstants.ROLE_KEY_ADMIN_AUDITOR) : hasRole; - hasRole = !userRolesList.contains(RangerConstants.ROLE_USER) ? userRolesList.add(RangerConstants.ROLE_USER) : hasRole; - } else if (loggedInVXUser.getUserRoleList().contains(RangerConstants.ROLE_USER)) { - logger.info("Logged-In user having user role will be able to fetch his own user details."); - if (!searchCriteria.getParamList().containsKey("name")) { - searchCriteria.addParam("name", loggedInVXUser.getName()); - }else if(searchCriteria.getParamList().containsKey("name") - && !stringUtil.isEmpty(searchCriteria.getParamValue("name").toString()) - && !searchCriteria.getParamValue("name").toString().equalsIgnoreCase(loggedInVXUser.getName())){ - throw restErrorUtil.create403RESTException("Logged-In user is not allowed to access requested user data."); - } - - } - } - } - - return xUserMgr.searchXUsers(searchCriteria); - } - - @GET - @Path("/lookup/users") - @Produces({ "application/json" }) - @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.GET_USERS_LOOKUP + "\")") - public VXStringList getUsersLookup(@Context HttpServletRequest request) { - SearchCriteria searchCriteria = searchUtil.extractCommonCriterias( - request, xUserService.sortFields); - VXStringList ret = new VXStringList(); - List vXList = new ArrayList<>(); - searchUtil.extractString(request, searchCriteria, "name", "User name",null); - searchUtil.extractInt(request, searchCriteria, "isVisible", "User Visibility"); - try { - VXUserList vXUserList = xUserMgr.lookupXUsers(searchCriteria); - VXString VXString = null; - for (VXUser vxUser : vXUserList.getList()) { - VXString = new VXString(); - VXString.setValue(vxUser.getName()); - vXList.add(VXString); - } - ret.setVXStrings(vXList); - ret.setPageSize(vXUserList.getPageSize()); - ret.setTotalCount(vXUserList.getTotalCount()); - ret.setSortType(vXUserList.getSortType()); - ret.setSortBy(vXUserList.getSortBy()); - } - catch(Throwable excp){ - throw restErrorUtil.createRESTException(excp.getMessage()); - } - return ret; - } - - @GET - @Path("/lookup/groups") - @Produces({ "application/json" }) - @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.GET_GROUPS_LOOKUP + "\")") - public VXStringList getGroupsLookup(@Context HttpServletRequest request) { - VXStringList ret = new VXStringList(); - SearchCriteria searchCriteria = searchUtil.extractCommonCriterias( - request, xGroupService.sortFields); - List vXList = new ArrayList<>(); - searchUtil.extractString(request, searchCriteria, "name", "group name", null); - searchUtil.extractInt(request, searchCriteria, "isVisible", "Group Visibility"); - try { - VXGroupList vXGroupList = xUserMgr.lookupXGroups(searchCriteria); - for (VXGroup vxGroup : vXGroupList.getList()) { - VXString VXString = new VXString(); - VXString.setValue(vxGroup.getName()); - vXList.add(VXString); - } - ret.setVXStrings(vXList); - ret.setPageSize(vXGroupList.getPageSize()); - ret.setTotalCount(vXGroupList.getTotalCount()); - ret.setSortType(vXGroupList.getSortType()); - ret.setSortBy(vXGroupList.getSortBy()); - } - catch(Throwable excp){ - throw restErrorUtil.createRESTException(excp.getMessage()); - } - return ret; - } - - @GET - @Path("/lookup/principals") - @Produces({ "application/json" }) - @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.GET_PRINCIPALS_LOOKUP + "\")") - public List getPrincipalsLookup(@Context HttpServletRequest request) { - SearchCriteria searchCriteria = searchUtil.extractCommonCriterias(request, xGroupService.sortFields); - - searchUtil.extractString(request, searchCriteria, "name", null, null); - - List ret = xUserMgr.getRangerPrincipals(searchCriteria); - - return ret; - } - @GET - @Path("/users/count") - @Produces({ "application/json" }) - @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.COUNT_X_USERS + "\")") - 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/json" }) - @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.GET_X_GROUP_USER + "\")") - public VXGroupUser getXGroupUser(@PathParam("id") Long id) { - return xUserMgr.getXGroupUser(id); - } - - @POST - @Path("/groupusers") - @Consumes({ "application/json" }) - @Produces({ "application/json" }) - @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") - public VXGroupUser createXGroupUser(VXGroupUser vXGroupUser) { - if (vXGroupUser == null || StringUtils.isBlank(vXGroupUser.getName()) || vXGroupUser.getUserId() == null) { - throw restErrorUtil.createRESTException(HttpServletResponse.SC_BAD_REQUEST , "Group name or UserId is empty or null", true); - } - return xUserMgr.createXGroupUser(vXGroupUser); - } - - @PUT - @Path("/groupusers") - @Consumes({ "application/json" }) - @Produces({ "application/json" }) - public VXGroupUser updateXGroupUser(VXGroupUser vXGroupUser) { - if (vXGroupUser == null || StringUtils.isBlank(vXGroupUser.getName()) || vXGroupUser.getUserId() == null) { - throw restErrorUtil.createRESTException(HttpServletResponse.SC_BAD_REQUEST , "Group name or UserId is empty or null", true); - } - return xUserMgr.updateXGroupUser(vXGroupUser); - } - - @DELETE - @Path("/groupusers/{id}") - @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") - @RangerAnnotationClassName(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/json" }) - @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.SEARCH_X_GROUP_USERS + "\")") - public VXGroupUserList searchXGroupUsers(@Context HttpServletRequest request) { - SearchCriteria searchCriteria = searchUtil.extractCommonCriterias( - request, xGroupUserService.sortFields); - return xUserMgr.searchXGroupUsers(searchCriteria); - } - - /** - * Implements the traditional search functionalities for XGroupUsers by Group name - * - * @param request - * @return - */ - @GET - @Path("/groupusers/groupName/{groupName}") - @Produces({ "application/json" }) - @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.GET_X_GROUP_USERS_BY_GROUP_NAME + "\")") - public VXGroupUserInfo getXGroupUsersByGroupName(@Context HttpServletRequest request, - @PathParam("groupName") String groupName) { - return xUserMgr.getXGroupUserFromMap(groupName); - } - - @GET - @Path("/groupusers/count") - @Produces({ "application/json" }) - @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.COUNT_X_GROUP_USERS + "\")") - public VXLong countXGroupUsers(@Context HttpServletRequest request) { - SearchCriteria searchCriteria = searchUtil.extractCommonCriterias( - request, xGroupUserService.sortFields); - - return xUserMgr.getXGroupUserSearchCount(searchCriteria); - } - - // Handle XPermMap - @GET - @Path("/permmaps/{id}") - @Produces({ "application/json" }) - @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.GET_X_PERM_MAP + "\")") - public VXPermMap getXPermMap(@PathParam("id") Long id) { - VXPermMap permMap = xUserMgr.getXPermMap(id); - - if (permMap != null) { - if (xResourceService.readResource(permMap.getResourceId()) == null) { - throw restErrorUtil.createRESTException("Invalid Input Data - No resource found with Id: " + permMap.getResourceId(), MessageEnums.INVALID_INPUT_DATA); - } - } - - return permMap; - } - - @POST - @Path("/permmaps") - @Consumes({ "application/json" }) - @Produces({ "application/json" }) - @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.CREATE_X_PERM_MAP + "\")") - public VXPermMap createXPermMap(VXPermMap vXPermMap) { - - if (vXPermMap != null) { - if (xResourceService.readResource(vXPermMap.getResourceId()) == null) { - throw restErrorUtil.createRESTException("Invalid Input Data - No resource found with Id: " + vXPermMap.getResourceId(), MessageEnums.INVALID_INPUT_DATA); - } - } - - return xUserMgr.createXPermMap(vXPermMap); - } - - @PUT - @Path("/permmaps") - @Consumes({ "application/json" }) - @Produces({ "application/json" }) - @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.UPDATE_X_PERM_MAP + "\")") - public VXPermMap updateXPermMap(VXPermMap vXPermMap) { - VXPermMap vXPermMapRet = null; - if (vXPermMap != null) { - if (xResourceService.readResource(vXPermMap.getResourceId()) == null) { - throw restErrorUtil.createRESTException("Invalid Input Data - No resource found with Id: " + vXPermMap.getResourceId()); - } - else{ - vXPermMapRet = xUserMgr.updateXPermMap(vXPermMap); - } - } - - return vXPermMapRet; - } - - @DELETE - @Path("/permmaps/{id}") - @RangerAnnotationClassName(class_name = VXPermMap.class) - @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.DELETE_X_PERM_MAP + "\")") - 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/json" }) - @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.SEARCH_X_PERM_MAPS + "\")") - public VXPermMapList searchXPermMaps(@Context HttpServletRequest request) { - SearchCriteria searchCriteria = searchUtil.extractCommonCriterias( - request, xPermMapService.sortFields); - return xUserMgr.searchXPermMaps(searchCriteria); - } - - @GET - @Path("/permmaps/count") - @Produces({ "application/json" }) - @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.COUNT_X_PERM_MAPS + "\")") - 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/json" }) - @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.GET_X_AUDIT_MAP + "\")") - public VXAuditMap getXAuditMap(@PathParam("id") Long id) { - VXAuditMap vXAuditMap = xUserMgr.getXAuditMap(id); - - if (vXAuditMap != null) { - if (xResourceService.readResource(vXAuditMap.getResourceId()) == null) { - throw restErrorUtil.createRESTException("Invalid Input Data - No resource found with Id: " + vXAuditMap.getResourceId(), MessageEnums.INVALID_INPUT_DATA); - } - } - - return vXAuditMap; - } - - @POST - @Path("/auditmaps") - @Consumes({ "application/json" }) - @Produces({ "application/json" }) - @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.CREATE_X_AUDIT_MAP + "\")") - public VXAuditMap createXAuditMap(VXAuditMap vXAuditMap) { - - if (vXAuditMap != null) { - if (xResourceService.readResource(vXAuditMap.getResourceId()) == null) { - throw restErrorUtil.createRESTException("Invalid Input Data - No resource found with Id: " + vXAuditMap.getResourceId(), MessageEnums.INVALID_INPUT_DATA); - } - } - - return xUserMgr.createXAuditMap(vXAuditMap); - } - - @PUT - @Path("/auditmaps") - @Consumes({ "application/json" }) - @Produces({ "application/json" }) - @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.UPDATE_X_AUDIT_MAP + "\")") - public VXAuditMap updateXAuditMap(VXAuditMap vXAuditMap) { - VXAuditMap vXAuditMapRet = null; - if (vXAuditMap != null) { - if (xResourceService.readResource(vXAuditMap.getResourceId()) == null) { - throw restErrorUtil.createRESTException("Invalid Input Data - No resource found with Id: " + vXAuditMap.getResourceId(), MessageEnums.INVALID_INPUT_DATA); - } - else{ - vXAuditMapRet = xUserMgr.updateXAuditMap(vXAuditMap); - } - } - - return vXAuditMapRet; - } - - @DELETE - @Path("/auditmaps/{id}") - @RangerAnnotationClassName(class_name = VXAuditMap.class) - @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.DELETE_X_AUDIT_MAP + "\")") - 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/json" }) - @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.SEARCH_X_AUDIT_MAPS + "\")") - public VXAuditMapList searchXAuditMaps(@Context HttpServletRequest request) { - SearchCriteria searchCriteria = searchUtil.extractCommonCriterias( - request, xAuditMapService.sortFields); - return xUserMgr.searchXAuditMaps(searchCriteria); - } - - @GET - @Path("/auditmaps/count") - @Produces({ "application/json" }) - @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.COUNT_X_AUDIT_MAPS + "\")") - 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/json" }) - @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.GET_X_USER_BY_USER_NAME + "\")") - public VXUser getXUserByUserName(@Context HttpServletRequest request, - @PathParam("userName") String userName) { - return xUserMgr.getXUserByUserName(userName); - } - - @GET - @Path("/groups/groupName/{groupName}") - @Produces({ "application/json" }) - @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.GET_X_GROUP_BY_GROUP_NAME + "\")") - public VXGroup getXGroupByGroupName(@Context HttpServletRequest request, - @PathParam("groupName") String groupName) { - VXGroup vXGroup = xGroupService.getGroupByGroupName(groupName); - UserSessionBase userSession = ContextUtil.getCurrentUserSession(); - if (userSession != null && userSession.getLoginId() != null && userSession.getUserRoleList().contains(RangerConstants.ROLE_USER)) { - VXUser loggedInVXUser = xUserService.getXUserByUserName(userSession.getLoginId()); - boolean isMatch = false; - if (loggedInVXUser != null && vXGroup != null) { - List userGroups = xGroupService.getGroupsByUserId(loggedInVXUser.getId()); - for (XXGroup xXGroup: userGroups) { - if (xXGroup != null && StringUtils.equals(xXGroup.getName(), vXGroup.getName())) { - isMatch = true; - break; - } - } - } - if (!isMatch) { - vXGroup = null; - } - } - return vXGroup; - } - - @DELETE - @Path("/users/userName/{userName}") - @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") - public void deleteXUserByUserName(@PathParam("userName") String userName, - @Context HttpServletRequest request) { - String forceDeleteStr = request.getParameter("forceDelete"); - boolean forceDelete = false; - if(!StringUtils.isEmpty(forceDeleteStr) && forceDeleteStr.equalsIgnoreCase("true")) { - forceDelete = true; - } - VXUser vxUser = xUserService.getXUserByUserName(userName); - xUserMgr.deleteXUser(vxUser.getId(), forceDelete); - } - - - /** - * Proceed with caution: Force deletes users from the ranger db, - * Delete happens one at a time with immediate commit on the transaction. - */ - @DELETE - @Path("/delete/external/users") - @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") - @Produces({ "application/json" }) - public Response forceDeleteExternalUsers(@Context HttpServletRequest request) { - SearchCriteria searchCriteria = new SearchCriteria(); - searchUtil.extractString( - request, searchCriteria, "name", "User name",null); - searchUtil.extractString( - request, searchCriteria, "emailAddress", "Email Address", null); - searchUtil.extractInt( - request, searchCriteria, "isVisible", "User Visibility"); - searchUtil.extractInt( - request, searchCriteria, "status", "User Status"); - searchUtil.extractString( - request, searchCriteria, "syncSource", "Sync Source", null); - searchUtil.extractRoleString( - request, searchCriteria, "userRole", "Role", null); - - // for invalid params - if(request.getQueryString() != null && searchCriteria.getParamList().size() == 0){ - return Response.status(Response.Status.BAD_REQUEST).entity("Invalid query params!").build(); - } - - // only for external users - searchCriteria.addParam("userSource", USER_EXTERNAL); - - List userIds = xUserService.searchXUsersForIds(searchCriteria); - long usersDeleted = xUserMgr.forceDeleteExternalUsers(userIds); - String response = "No users were deleted!"; - if (usersDeleted == 1) { - response = "1 user deleted successfully."; - } else if (usersDeleted > 0) { - response = String.format("%d users deleted successfully.", usersDeleted); - } - return Response.ok(response).build(); - } - - /** - * Proceed with caution: Force deletes groups from the ranger db, - * Delete happens one at a time with immediate commit on the transaction. - */ - @DELETE - @Path("/delete/external/groups") - @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") - @Produces({ "application/json" }) - public Response forceDeleteExternalGroups(@Context HttpServletRequest request) { - SearchCriteria searchCriteria = new SearchCriteria(); - searchUtil.extractString( - request, searchCriteria, "name", "Group Name",null); - searchUtil.extractInt( - request, searchCriteria, "isVisible", "Group Visibility"); - searchUtil.extractString( - request, searchCriteria, "syncSource", "Sync Source", null); - - // for invalid params - if(request.getQueryString() != null && searchCriteria.getParamList().size() == 0){ - return Response.status(Response.Status.BAD_REQUEST).entity("Invalid query params!").build(); - } - - // only for external groups - searchCriteria.addParam("groupSource", GROUP_EXTERNAL); - - List groupIds = xGroupService.searchXGroupsForIds(searchCriteria); - long groupsDeleted = xUserMgr.forceDeleteExternalGroups(groupIds); - String response = "No groups were deleted!"; - if (groupsDeleted == 1) { - response = "1 group deleted successfully."; - } else if (groupsDeleted > 0) { - response = String.format("%d groups deleted successfully.", groupsDeleted); - } - return Response.ok(response).build(); - } - - @DELETE - @Path("/groups/groupName/{groupName}") - @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") - public void deleteXGroupByGroupName( - @PathParam("groupName") String groupName, - @Context HttpServletRequest request) { - String forceDeleteStr = request.getParameter("forceDelete"); - boolean forceDelete = false; - if(!StringUtils.isEmpty(forceDeleteStr) && forceDeleteStr.equalsIgnoreCase("true")) { - forceDelete = true; - } - VXGroup vxGroup = xGroupService.getGroupByGroupName(groupName); - xUserMgr.deleteXGroup(vxGroup.getId(), forceDelete); - } - - @DELETE - @Path("/group/{groupName}/user/{userName}") - @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") - public void deleteXGroupAndXUser(@PathParam("groupName") String groupName, - @PathParam("userName") String userName, - @Context HttpServletRequest request) { - xUserMgr.deleteXGroupAndXUser(groupName, userName); - } - - @GET - @Path("/{userId}/groups") - @Produces({ "application/json" }) - @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.GET_X_USER_GROUPS + "\")") - public VXGroupList getXUserGroups(@Context HttpServletRequest request, - @PathParam("userId") Long id){ - return xUserMgr.getXUserGroups(id); - } - - @GET - @Path("/{groupId}/users") - @Produces({ "application/json" }) - @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.GET_X_GROUP_USERS + "\")") - public VXUserList getXGroupUsers(@Context HttpServletRequest request, - @PathParam("groupId") Long id){ - SearchCriteria searchCriteria = searchUtil.extractCommonCriterias( - request, xGroupUserService.sortFields); - searchCriteria.addParam("xGroupId", id); - return xUserMgr.getXGroupUsers(searchCriteria); - } - - @GET - @Path("/authSessions") - @Produces({ "application/json" }) - @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.GET_AUTH_SESSIONS + "\")") - 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", "Login 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", null); - searchUtil.extractDate(request, searchCriteria, "endDate", "End Date", null); - return sessionMgr.searchAuthSessions(searchCriteria); - } - - @GET - @Path("/authSessions/info") - @Produces({ "application/json" }) - @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.GET_AUTH_SESSION + "\")") - public VXAuthSession getAuthSession(@Context HttpServletRequest request){ - String authSessionId = request.getParameter("extSessionId"); - return sessionMgr.getAuthSessionBySessionId(authSessionId); - } - - // Handle module permissions - @POST - @Path("/permission") - @Consumes({ "application/json" }) - @Produces({ "application/json" }) - @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.CREATE_X_MODULE_DEF_PERMISSION + "\")") - public VXModuleDef createXModuleDefPermission(VXModuleDef vXModuleDef) { - xUserMgr.checkAdminAccess(); - bizUtil.blockAuditorRoleUser(); - return xUserMgr.createXModuleDefPermission(vXModuleDef); - } - - @GET - @Path("/permission/{id}") - @Produces({ "application/json" }) - @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.GET_X_MODULE_DEF_PERMISSION + "\")") - public VXModuleDef getXModuleDefPermission(@PathParam("id") Long id) { - return xUserMgr.getXModuleDefPermission(id); - } - - @PUT - @Path("/permission/{id}") - @Consumes({ "application/json" }) - @Produces({ "application/json" }) - @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.UPDATE_X_MODULE_DEF_PERMISSION + "\")") - public VXModuleDef updateXModuleDefPermission(VXModuleDef vXModuleDef) { - xUserMgr.checkAdminAccess(); - bizUtil.blockAuditorRoleUser(); - return xUserMgr.updateXModuleDefPermission(vXModuleDef); - } - - @DELETE - @Path("/permission/{id}") - @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.DELETE_X_MODULE_DEF_PERMISSION + "\")") - public void deleteXModuleDefPermission(@PathParam("id") Long id, - @Context HttpServletRequest request) { - boolean force = true; - xUserMgr.checkAdminAccess(); - bizUtil.blockAuditorRoleUser(); - xUserMgr.deleteXModuleDefPermission(id, force); - } - - @GET - @Path("/permission") - @Produces({ "application/json" }) - @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.SEARCH_X_MODULE_DEF + "\")") - public VXModuleDefList searchXModuleDef(@Context HttpServletRequest request) { - SearchCriteria searchCriteria = searchUtil.extractCommonCriterias( - request, xModuleDefService.sortFields); - - searchUtil.extractString(request, searchCriteria, "module", - "modulename", null); - - searchUtil.extractString(request, searchCriteria, "moduleDefList", - "id", null); - searchUtil.extractString(request, searchCriteria, "userName", - "userName", null); - searchUtil.extractString(request, searchCriteria, "groupName", - "groupName", null); - - return xUserMgr.searchXModuleDef(searchCriteria); - } - - @GET - @Path("/permissionlist") - @Produces({ "application/json" }) - @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.SEARCH_X_MODULE_DEF + "\")") - public VXModulePermissionList searchXModuleDefList(@Context HttpServletRequest request) { - SearchCriteria searchCriteria = searchUtil.extractCommonCriterias( - request, xModuleDefService.sortFields); - - searchUtil.extractString(request, searchCriteria, "module", - "modulename", null); - - searchUtil.extractString(request, searchCriteria, "moduleDefList", - "id", null); - searchUtil.extractString(request, searchCriteria, "userName", - "userName", null); - searchUtil.extractString(request, searchCriteria, "groupName", - "groupName", null); - - return xUserMgr.searchXModuleDefList(searchCriteria); - } - - @GET - @Path("/permission/count") - @Produces({ "application/json" }) - @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.COUNT_X_MODULE_DEF + "\")") - public VXLong countXModuleDef(@Context HttpServletRequest request) { - SearchCriteria searchCriteria = searchUtil.extractCommonCriterias( - request, xModuleDefService.sortFields); - return xUserMgr.getXModuleDefSearchCount(searchCriteria); - } - - // Handle user permissions - @POST - @Path("/permission/user") - @Consumes({ "application/json" }) - @Produces({ "application/json" }) - @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.CREATE_X_USER_PERMISSION + "\")") - public VXUserPermission createXUserPermission( - VXUserPermission vXUserPermission) { - xUserMgr.checkAdminAccess(); - bizUtil.blockAuditorRoleUser(); - return xUserMgr.createXUserPermission(vXUserPermission); - } - - @GET - @Path("/permission/user/{id}") - @Produces({ "application/json" }) - @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.GET_X_USER_PERMISSION + "\")") - public VXUserPermission getXUserPermission(@PathParam("id") Long id) { - return xUserMgr.getXUserPermission(id); - } - - @PUT - @Path("/permission/user/{id}") - @Consumes({ "application/json" }) - @Produces({ "application/json" }) - @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.UPDATE_X_USER_PERMISSION + "\")") - public VXUserPermission updateXUserPermission( - VXUserPermission vXUserPermission) { - xUserMgr.checkAdminAccess(); - bizUtil.blockAuditorRoleUser(); - return xUserMgr.updateXUserPermission(vXUserPermission); - } - - @DELETE - @Path("/permission/user/{id}") - @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.DELETE_X_USER_PERMISSION + "\")") - public void deleteXUserPermission(@PathParam("id") Long id, - @Context HttpServletRequest request) { - boolean force = true; - xUserMgr.checkAdminAccess(); - xUserMgr.deleteXUserPermission(id, force); - } - - @GET - @Path("/permission/user") - @Produces({ "application/json" }) - @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.SEARCH_X_USER_PERMISSION + "\")") - public VXUserPermissionList searchXUserPermission( - @Context HttpServletRequest request) { - SearchCriteria searchCriteria = searchUtil.extractCommonCriterias( - request, xUserPermissionService.sortFields); - searchUtil.extractString(request, searchCriteria, "id", "id", - StringUtil.VALIDATION_NAME); - - searchUtil.extractString(request, searchCriteria, "userPermissionList", - "userId", StringUtil.VALIDATION_NAME); - return xUserMgr.searchXUserPermission(searchCriteria); - } - - @GET - @Path("/permission/user/count") - @Produces({ "application/json" }) - @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.COUNT_X_USER_PERMISSION + "\")") - public VXLong countXUserPermission(@Context HttpServletRequest request) { - SearchCriteria searchCriteria = searchUtil.extractCommonCriterias( - request, xUserPermissionService.sortFields); - return xUserMgr.getXUserPermissionSearchCount(searchCriteria); - } - - // Handle group permissions - @POST - @Path("/permission/group") - @Consumes({ "application/json" }) - @Produces({ "application/json" }) - @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.CREATE_X_GROUP_PERMISSION + "\")") - public VXGroupPermission createXGroupPermission( - VXGroupPermission vXGroupPermission) { - xUserMgr.checkAdminAccess(); - bizUtil.blockAuditorRoleUser(); - return xUserMgr.createXGroupPermission(vXGroupPermission); - } - - @GET - @Path("/permission/group/{id}") - @Produces({ "application/json" }) - @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.GET_X_GROUP_PERMISSION + "\")") - public VXGroupPermission getXGroupPermission(@PathParam("id") Long id) { - return xUserMgr.getXGroupPermission(id); - } - - @PUT - @Path("/permission/group/{id}") - @Consumes({ "application/json" }) - @Produces({ "application/json" }) - @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.UPDATE_X_GROUP_PERMISSION + "\")") - public VXGroupPermission updateXGroupPermission(@PathParam("id") Long id, - VXGroupPermission vXGroupPermission) { - // if VXGroupPermission.id is specified, it should be same as the param 'id' - if(vXGroupPermission.getId() == null) { - vXGroupPermission.setId(id); - } else if(!vXGroupPermission.getId().equals(id)) { - throw restErrorUtil.createRESTException(HttpServletResponse.SC_BAD_REQUEST , "vXGroupPermission Id mismatch", true); - } - xUserMgr.checkAdminAccess(); - bizUtil.blockAuditorRoleUser(); - return xUserMgr.updateXGroupPermission(vXGroupPermission); - } - - @DELETE - @Path("/permission/group/{id}") - @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.DELETE_X_GROUP_PERMISSION + "\")") - public void deleteXGroupPermission(@PathParam("id") Long id, - @Context HttpServletRequest request) { - boolean force = true; - xUserMgr.checkAdminAccess(); - bizUtil.blockAuditorRoleUser(); - xUserMgr.deleteXGroupPermission(id, force); - } - - @GET - @Path("/permission/group") - @Produces({ "application/json" }) - @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.SEARCH_X_GROUP_PERMISSION + "\")") - public VXGroupPermissionList searchXGroupPermission( - @Context HttpServletRequest request) { - SearchCriteria searchCriteria = searchUtil.extractCommonCriterias( - request, xGroupPermissionService.sortFields); - searchUtil.extractString(request, searchCriteria, "id", "id", - StringUtil.VALIDATION_NAME); - searchUtil.extractString(request, searchCriteria, - "groupPermissionList", "groupId", StringUtil.VALIDATION_NAME); - return xUserMgr.searchXGroupPermission(searchCriteria); - } - - @GET - @Path("/permission/group/count") - @Produces({ "application/json" }) - @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.COUNT_X_GROUP_PERMISSION + "\")") - public VXLong countXGroupPermission(@Context HttpServletRequest request) { - SearchCriteria searchCriteria = searchUtil.extractCommonCriterias( - request, xGroupPermissionService.sortFields); - return xUserMgr.getXGroupPermissionSearchCount(searchCriteria); - } - - @PUT - @Path("/secure/users/activestatus") - @Produces({ "application/json" }) - @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.MODIFY_USER_ACTIVE_STATUS + "\")") - public void modifyUserActiveStatus(HashMap statusMap){ - xUserMgr.modifyUserActiveStatus(statusMap); - } - - @PUT - @Path("/secure/users/roles/{userId}") - @Consumes({ "application/json" }) - @Produces({ "application/json" }) - @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.SET_USER_ROLES_BY_ID + "\")") - public VXStringList setUserRolesByExternalID(@PathParam("userId") Long userId, - VXStringList roleList) { - return xUserMgr.setUserRolesByExternalID(userId, roleList.getVXStrings()); - } - - @PUT - @Path("/secure/users/roles/userName/{userName}") - @Consumes({ "application/json" }) - @Produces({ "application/json" }) - @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.SET_USER_ROLES_BY_NAME + "\")") - public VXStringList setUserRolesByName(@PathParam("userName") String userName, - VXStringList roleList) { - return xUserMgr.setUserRolesByName(userName, roleList.getVXStrings()); - } - - @GET - @Path("/secure/users/external/{userId}") - @Produces({ "application/json" }) - @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.GET_USER_ROLES_BY_ID + "\")") - public VXStringList getUserRolesByExternalID(@PathParam("userId") Long userId) { - VXStringList vXStringList=new VXStringList(); - vXStringList=xUserMgr.getUserRolesByExternalID(userId); - return vXStringList; - } - - @GET - @Path("/secure/users/roles/userName/{userName}") - @Produces({ "application/json" }) - @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.GET_USER_ROLES_BY_NAME + "\")") - public VXStringList getUserRolesByName(@PathParam("userName") String userName) { - VXStringList vXStringList=new VXStringList(); - vXStringList=xUserMgr.getUserRolesByName(userName); - return vXStringList; - } - - - @DELETE - @Path("/secure/users/delete") - @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") - public void deleteUsersByUserName(@Context HttpServletRequest request,VXStringList userList){ - String forceDeleteStr = request.getParameter("forceDelete"); - boolean forceDelete = false; - if(StringUtils.isNotEmpty(forceDeleteStr) && "true".equalsIgnoreCase(forceDeleteStr)) { - forceDelete = true; - } - if(userList!=null && userList.getList()!=null){ - for(VXString userName:userList.getList()){ - if(StringUtils.isNotEmpty(userName.getValue())){ - VXUser vxUser = xUserService.getXUserByUserName(userName.getValue()); - xUserMgr.deleteXUser(vxUser.getId(), forceDelete); - } - } - } - } - - - @DELETE - @Path("/secure/groups/delete") - @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") - public void deleteGroupsByGroupName( - @Context HttpServletRequest request,VXStringList groupList) { - String forceDeleteStr = request.getParameter("forceDelete"); - boolean forceDelete = false; - if(StringUtils.isNotEmpty(forceDeleteStr) && "true".equalsIgnoreCase(forceDeleteStr)) { - forceDelete = true; - } - if(groupList!=null && groupList.getList()!=null){ - for(VXString groupName:groupList.getList()){ - if(StringUtils.isNotEmpty(groupName.getValue())){ - VXGroup vxGroup = xGroupService.getGroupByGroupName(groupName.getValue()); - xUserMgr.deleteXGroup(vxGroup.getId(), forceDelete); - } - } - } - } - - @DELETE - @Path("/secure/users/{userName}") - @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") - public void deleteSingleUserByUserName(@Context HttpServletRequest request, @PathParam("userName") String userName) { - String forceDeleteStr = request.getParameter("forceDelete"); - boolean forceDelete = false; - if (StringUtils.isNotEmpty(forceDeleteStr) && "true".equalsIgnoreCase(forceDeleteStr)) { - forceDelete = true; - } + @Autowired + XGroupPermissionService xGroupPermissionService; - if (StringUtils.isNotEmpty(userName)) { - VXUser vxUser = xUserService.getXUserByUserName(userName); - xUserMgr.deleteXUser(vxUser.getId(), forceDelete); - } + @Autowired + XUserService xUserService; + + @Autowired + XGroupUserService xGroupUserService; + + @Autowired + XPermMapService xPermMapService; + + @Autowired + XAuditMapService xAuditMapService; + + @Autowired + RESTErrorUtil restErrorUtil; + + @Autowired + RangerDaoManager rangerDaoManager; + + @Autowired + SessionMgr sessionMgr; + + @Autowired + AuthSessionService authSessionService; + + @Autowired + RangerBizUtil bizUtil; + + @Autowired + XResourceService xResourceService; + + @Autowired + StringUtil stringUtil; + + @Autowired + AssetMgr assetMgr; + + @Autowired + ServiceUtil serviceUtil; + + @Autowired + ServiceDBStore svcStore; + + // Handle XGroup + @GET + @Path("/groups/{id}") + @Produces("application/json") + @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.GET_X_GROUP + "\")") + public VXGroup getXGroup(@PathParam("id") Long id) { + return xUserMgr.getXGroup(id); + } + + @GET + @Path("/secure/groups/{id}") + @Produces("application/json") + @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.SECURE_GET_X_GROUP + "\")") + public VXGroup secureGetXGroup(@PathParam("id") Long id) { + return xUserMgr.getXGroup(id); + } + + @POST + @Path("/groups") + @Consumes("application/json") + @Produces("application/json") + @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") + public VXGroup createXGroup(VXGroup vXGroup) { + return xUserMgr.createXGroupWithoutLogin(vXGroup); + } + + @POST + @Path("/groups/groupinfo") + @Consumes("application/json") + @Produces("application/json") + @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") + public VXGroupUserInfo createXGroupUserFromMap(VXGroupUserInfo vXGroupUserInfo) { + return xUserMgr.createXGroupUserFromMap(vXGroupUserInfo); + } + + @POST + @Path("/secure/groups") + @Consumes("application/json") + @Produces("application/json") + @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") + public VXGroup secureCreateXGroup(VXGroup vXGroup) { + return xUserMgr.createXGroup(vXGroup); + } + + @PUT + @Path("/groups") + @Consumes("application/json") + @Produces("application/json") + public VXGroup updateXGroup(VXGroup vXGroup) { + return xUserMgr.updateXGroup(vXGroup); + } + + @PUT + @Path("/secure/groups/{id}") + @Consumes("application/json") + @Produces("application/json") + public VXGroup secureUpdateXGroup(VXGroup vXGroup) { + return xUserMgr.updateXGroup(vXGroup); + } + + @PUT + @Path("/secure/groups/visibility") + @Consumes("application/json") + @Produces("application/json") + @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.MODIFY_GROUPS_VISIBILITY + "\")") + public void modifyGroupsVisibility(HashMap groupVisibilityMap) { + xUserMgr.modifyGroupsVisibility(groupVisibilityMap); + } + + @DELETE + @Path("/groups/{id}") + @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") + @RangerAnnotationClassName(class_name = VXGroup.class) + public void deleteXGroup(@PathParam("id") Long id, @Context HttpServletRequest request) { + String forceDeleteStr = request.getParameter("forceDelete"); + boolean forceDelete = !StringUtils.isEmpty(forceDeleteStr) && "true".equalsIgnoreCase(forceDeleteStr.trim()); + + xUserMgr.deleteXGroup(id, forceDelete); + } + + /** + * Implements the traditional search functionalities for XGroups + * + * @param request + * @return + */ + @GET + @Path("/groups") + @Produces("application/json") + @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.SEARCH_X_GROUPS + "\")") + public VXGroupList searchXGroups(@Context HttpServletRequest request) { + SearchCriteria searchCriteria = searchUtil.extractCommonCriterias(request, xGroupService.sortFields); + + searchUtil.extractString(request, searchCriteria, "name", "group name", null); + searchUtil.extractInt(request, searchCriteria, "isVisible", "Group Visibility"); + searchUtil.extractInt(request, searchCriteria, "groupSource", "group source"); + searchUtil.extractString(request, searchCriteria, "syncSource", "Sync Source", null); + + return xUserMgr.searchXGroups(searchCriteria); + } + + @GET + @Path("/groups/count") + @Produces("application/json") + @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.COUNT_X_GROUPS + "\")") + 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/json") + @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.GET_X_USER + "\")") + public VXUser getXUser(@PathParam("id") Long id) { + return xUserMgr.getXUser(id); + } + + @GET + @Path("/secure/users/{id}") + @Produces("application/json") + @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.SECURE_GET_X_USER + "\")") + public VXUser secureGetXUser(@PathParam("id") Long id) { + return xUserMgr.getXUser(id); + } + + @POST + @Path("/users") + @Consumes("application/json") + @Produces("application/json") + @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") + public VXUser createXUser(VXUser vXUser) { + return xUserMgr.createXUserWithOutLogin(vXUser); + } + + @POST + @Path("/users/external") + @Consumes("application/json") + @Produces("application/json") + @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") + public VXUser createExternalUser(VXUser vXUser) { + return xUserMgr.createExternalUser(vXUser.getName()); + } + + @POST + @Path("/users/userinfo") + @Consumes("application/json") + @Produces("application/json") + @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") + public VXUserGroupInfo createXUserGroupFromMap(VXUserGroupInfo vXUserGroupInfo) { + return xUserMgr.createXUserGroupFromMap(vXUserGroupInfo); + } + + @POST + @Path("/secure/users") + @Consumes("application/json") + @Produces("application/json") + @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") + public VXUser secureCreateXUser(VXUser vXUser) { + bizUtil.checkUserAccessible(vXUser); + + return xUserMgr.createXUser(vXUser); + } + + @PUT + @Path("/users") + @Consumes("application/json") + @Produces("application/json") + public VXUser updateXUser(VXUser vXUser) { + bizUtil.checkUserAccessible(vXUser); + + return xUserMgr.updateXUser(vXUser); + } + + @PUT + @Path("/secure/users/{id}") + @Consumes("application/json") + @Produces("application/json") + public VXUser secureUpdateXUser(VXUser vXUser) { + bizUtil.checkUserAccessible(vXUser); + + return xUserMgr.updateXUser(vXUser); + } + + @PUT + @Path("/secure/users/visibility") + @Consumes("application/json") + @Produces("application/json") + @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.MODIFY_USER_VISIBILITY + "\")") + public void modifyUserVisibility(HashMap visibilityMap) { + xUserMgr.modifyUserVisibility(visibilityMap); + } + + @DELETE + @Path("/users/{id}") + @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") + @RangerAnnotationClassName(class_name = VXUser.class) + public void deleteXUser(@PathParam("id") Long id, @Context HttpServletRequest request) { + String forceDeleteStr = request.getParameter("forceDelete"); + boolean forceDelete = !StringUtils.isEmpty(forceDeleteStr) && forceDeleteStr.equalsIgnoreCase("true"); + + xUserMgr.deleteXUser(id, forceDelete); + } + + /** + * Implements the traditional search functionalities for XUsers + * + * @param request + * @return + */ + @GET + @Path("/users") + @Produces("application/json") + @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.SEARCH_X_USERS + "\")") + public VXUserList searchXUsers(@Context HttpServletRequest request, @QueryParam("syncSource") String syncSource, @QueryParam("userRole") String userRole) { + String userRoleParamName = RangerConstants.ROLE_USER; + SearchCriteria searchCriteria = searchUtil.extractCommonCriterias(request, xUserService.sortFields); + String userName = null; + + if (request.getUserPrincipal() != null) { + userName = request.getUserPrincipal().getName(); } - @DELETE - @Path("/secure/groups/{groupName}") - @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") - public void deleteSingleGroupByGroupName(@Context HttpServletRequest request, @PathParam("groupName") String groupName) { - String forceDeleteStr = request.getParameter("forceDelete"); - boolean forceDelete = false; - if (StringUtils.isNotEmpty(forceDeleteStr) && "true".equalsIgnoreCase(forceDeleteStr)) { - forceDelete = true; - } - if (StringUtils.isNotEmpty(groupName)) { - VXGroup vxGroup = xGroupService.getGroupByGroupName(groupName.trim()); - xUserMgr.deleteXGroup(vxGroup.getId(), forceDelete); - } + searchUtil.extractString(request, searchCriteria, "name", "User name", null); + searchUtil.extractString(request, searchCriteria, "emailAddress", "Email Address", null); + searchUtil.extractInt(request, searchCriteria, "userSource", "User Source"); + searchUtil.extractInt(request, searchCriteria, "isVisible", "User Visibility"); + searchUtil.extractInt(request, searchCriteria, "status", "User Status"); + + List userRolesList = searchUtil.extractStringList(request, searchCriteria, "userRoleList", "User Role List", "userRoleList", null, null); + + searchUtil.extractRoleString(request, searchCriteria, "userRole", "Role", null); + searchUtil.extractString(request, searchCriteria, "syncSource", "Sync Source", null); + + if (CollectionUtils.isNotEmpty(userRolesList) && CollectionUtils.size(userRolesList) == 1 && userRolesList.get(0).equalsIgnoreCase(userRoleParamName)) { + if (!(searchCriteria.getParamList().containsKey("name"))) { + searchCriteria.addParam("name", userName); + } else if ((searchCriteria.getParamList().containsKey("name")) && userName != null && userName.contains((String) searchCriteria.getParamList().get("name"))) { + searchCriteria.addParam("name", userName); + } } - @DELETE - @Path("/secure/users/id/{userId}") - @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") - public void deleteSingleUserByUserId(@Context HttpServletRequest request, @PathParam("userId") Long userId) { - String forceDeleteStr = request.getParameter("forceDelete"); - boolean forceDelete = false; - if (StringUtils.isNotEmpty(forceDeleteStr) && "true".equalsIgnoreCase(forceDeleteStr)) { - forceDelete = true; + UserSessionBase userSession = ContextUtil.getCurrentUserSession(); + + if (userSession != null && userSession.getLoginId() != null) { + VXUser loggedInVXUser = xUserService.getXUserByUserName(userSession.getLoginId()); + + if (loggedInVXUser != null && loggedInVXUser.getUserRoleList().size() == 1) { + if (loggedInVXUser.getUserRoleList().contains(RangerConstants.ROLE_SYS_ADMIN) || loggedInVXUser.getUserRoleList().contains(RangerConstants.ROLE_ADMIN_AUDITOR)) { + boolean hasRole = false; + + hasRole = !userRolesList.contains(RangerConstants.ROLE_SYS_ADMIN) ? userRolesList.add(RangerConstants.ROLE_SYS_ADMIN) : hasRole; + hasRole = !userRolesList.contains(RangerConstants.ROLE_ADMIN_AUDITOR) ? userRolesList.add(RangerConstants.ROLE_ADMIN_AUDITOR) : hasRole; + hasRole = !userRolesList.contains(RangerConstants.ROLE_USER) ? userRolesList.add(RangerConstants.ROLE_USER) : hasRole; + + if (loggedInVXUser.getUserRoleList().contains(RangerConstants.ROLE_SYS_ADMIN) && "rangerusersync".equalsIgnoreCase(userSession.getLoginId())) { + hasRole = !userRolesList.contains(RangerConstants.ROLE_KEY_ADMIN) ? userRolesList.add(RangerConstants.ROLE_KEY_ADMIN) : hasRole; + hasRole = !userRolesList.contains(RangerConstants.ROLE_KEY_ADMIN_AUDITOR) ? userRolesList.add(RangerConstants.ROLE_KEY_ADMIN_AUDITOR) : hasRole; + } + } else if (loggedInVXUser.getUserRoleList().contains(RangerConstants.ROLE_KEY_ADMIN) || loggedInVXUser.getUserRoleList().contains(RangerConstants.ROLE_KEY_ADMIN_AUDITOR)) { + boolean hasRole = false; + + hasRole = !userRolesList.contains(RangerConstants.ROLE_KEY_ADMIN) ? userRolesList.add(RangerConstants.ROLE_KEY_ADMIN) : hasRole; + hasRole = !userRolesList.contains(RangerConstants.ROLE_KEY_ADMIN_AUDITOR) ? userRolesList.add(RangerConstants.ROLE_KEY_ADMIN_AUDITOR) : hasRole; + hasRole = !userRolesList.contains(RangerConstants.ROLE_USER) ? userRolesList.add(RangerConstants.ROLE_USER) : hasRole; + } else if (loggedInVXUser.getUserRoleList().contains(RangerConstants.ROLE_USER)) { + logger.info("Logged-In user having user role will be able to fetch his own user details."); + + if (!searchCriteria.getParamList().containsKey("name")) { + searchCriteria.addParam("name", loggedInVXUser.getName()); + } else if (searchCriteria.getParamList().containsKey("name") && !stringUtil.isEmpty(searchCriteria.getParamValue("name").toString()) && !searchCriteria.getParamValue("name").toString().equalsIgnoreCase(loggedInVXUser.getName())) { + throw restErrorUtil.create403RESTException("Logged-In user is not allowed to access requested user data."); + } } - if (userId != null) { - xUserMgr.deleteXUser(userId, forceDelete); + } + } + + return xUserMgr.searchXUsers(searchCriteria); + } + + @GET + @Path("/lookup/users") + @Produces("application/json") + @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.GET_USERS_LOOKUP + "\")") + public VXStringList getUsersLookup(@Context HttpServletRequest request) { + SearchCriteria searchCriteria = searchUtil.extractCommonCriterias(request, xUserService.sortFields); + VXStringList ret = new VXStringList(); + List vXList = new ArrayList<>(); + + searchUtil.extractString(request, searchCriteria, "name", "User name", null); + searchUtil.extractInt(request, searchCriteria, "isVisible", "User Visibility"); + + try { + VXUserList vXUserList = xUserMgr.lookupXUsers(searchCriteria); + + for (VXUser vxUser : vXUserList.getList()) { + VXString vXString = new VXString(); + + vXString.setValue(vxUser.getName()); + + vXList.add(vXString); + } + + ret.setVXStrings(vXList); + ret.setPageSize(vXUserList.getPageSize()); + ret.setTotalCount(vXUserList.getTotalCount()); + ret.setSortType(vXUserList.getSortType()); + ret.setSortBy(vXUserList.getSortBy()); + } catch (Throwable excp) { + throw restErrorUtil.createRESTException(excp.getMessage()); + } + + return ret; + } + + @GET + @Path("/lookup/groups") + @Produces("application/json") + @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.GET_GROUPS_LOOKUP + "\")") + public VXStringList getGroupsLookup(@Context HttpServletRequest request) { + VXStringList ret = new VXStringList(); + SearchCriteria searchCriteria = searchUtil.extractCommonCriterias(request, xGroupService.sortFields); + List vXList = new ArrayList<>(); + + searchUtil.extractString(request, searchCriteria, "name", "group name", null); + searchUtil.extractInt(request, searchCriteria, "isVisible", "Group Visibility"); + + try { + VXGroupList vXGroupList = xUserMgr.lookupXGroups(searchCriteria); + + for (VXGroup vxGroup : vXGroupList.getList()) { + VXString vXString = new VXString(); + + vXString.setValue(vxGroup.getName()); + + vXList.add(vXString); + } + + ret.setVXStrings(vXList); + ret.setPageSize(vXGroupList.getPageSize()); + ret.setTotalCount(vXGroupList.getTotalCount()); + ret.setSortType(vXGroupList.getSortType()); + ret.setSortBy(vXGroupList.getSortBy()); + } catch (Throwable excp) { + throw restErrorUtil.createRESTException(excp.getMessage()); + } + + return ret; + } + + @GET + @Path("/lookup/principals") + @Produces("application/json") + @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.GET_PRINCIPALS_LOOKUP + "\")") + public List getPrincipalsLookup(@Context HttpServletRequest request) { + SearchCriteria searchCriteria = searchUtil.extractCommonCriterias(request, xGroupService.sortFields); + + searchUtil.extractString(request, searchCriteria, "name", null, null); + + return xUserMgr.getRangerPrincipals(searchCriteria); + } + + @GET + @Path("/users/count") + @Produces("application/json") + @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.COUNT_X_USERS + "\")") + 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/json") + @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.GET_X_GROUP_USER + "\")") + public VXGroupUser getXGroupUser(@PathParam("id") Long id) { + return xUserMgr.getXGroupUser(id); + } + + @POST + @Path("/groupusers") + @Consumes("application/json") + @Produces("application/json") + @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") + public VXGroupUser createXGroupUser(VXGroupUser vXGroupUser) { + if (vXGroupUser == null || StringUtils.isBlank(vXGroupUser.getName()) || vXGroupUser.getUserId() == null) { + throw restErrorUtil.createRESTException(HttpServletResponse.SC_BAD_REQUEST, "Group name or UserId is empty or null", true); + } + + return xUserMgr.createXGroupUser(vXGroupUser); + } + + @PUT + @Path("/groupusers") + @Consumes("application/json") + @Produces("application/json") + public VXGroupUser updateXGroupUser(VXGroupUser vXGroupUser) { + if (vXGroupUser == null || StringUtils.isBlank(vXGroupUser.getName()) || vXGroupUser.getUserId() == null) { + throw restErrorUtil.createRESTException(HttpServletResponse.SC_BAD_REQUEST, "Group name or UserId is empty or null", true); + } + + return xUserMgr.updateXGroupUser(vXGroupUser); + } + + @DELETE + @Path("/groupusers/{id}") + @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") + @RangerAnnotationClassName(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/json") + @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.SEARCH_X_GROUP_USERS + "\")") + public VXGroupUserList searchXGroupUsers(@Context HttpServletRequest request) { + SearchCriteria searchCriteria = searchUtil.extractCommonCriterias(request, xGroupUserService.sortFields); + + return xUserMgr.searchXGroupUsers(searchCriteria); + } + + /** + * Implements the traditional search functionalities for XGroupUsers by Group name + * + * @param request + * @return + */ + @GET + @Path("/groupusers/groupName/{groupName}") + @Produces("application/json") + @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.GET_X_GROUP_USERS_BY_GROUP_NAME + "\")") + public VXGroupUserInfo getXGroupUsersByGroupName(@Context HttpServletRequest request, @PathParam("groupName") String groupName) { + return xUserMgr.getXGroupUserFromMap(groupName); + } + + @GET + @Path("/groupusers/count") + @Produces("application/json") + @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.COUNT_X_GROUP_USERS + "\")") + public VXLong countXGroupUsers(@Context HttpServletRequest request) { + SearchCriteria searchCriteria = searchUtil.extractCommonCriterias(request, xGroupUserService.sortFields); + + return xUserMgr.getXGroupUserSearchCount(searchCriteria); + } + + // Handle XPermMap + @GET + @Path("/permmaps/{id}") + @Produces("application/json") + @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.GET_X_PERM_MAP + "\")") + public VXPermMap getXPermMap(@PathParam("id") Long id) { + VXPermMap permMap = xUserMgr.getXPermMap(id); + + if (permMap != null) { + if (xResourceService.readResource(permMap.getResourceId()) == null) { + throw restErrorUtil.createRESTException("Invalid Input Data - No resource found with Id: " + permMap.getResourceId(), MessageEnums.INVALID_INPUT_DATA); + } + } + + return permMap; + } + + @POST + @Path("/permmaps") + @Consumes("application/json") + @Produces("application/json") + @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.CREATE_X_PERM_MAP + "\")") + public VXPermMap createXPermMap(VXPermMap vXPermMap) { + if (vXPermMap != null) { + if (xResourceService.readResource(vXPermMap.getResourceId()) == null) { + throw restErrorUtil.createRESTException("Invalid Input Data - No resource found with Id: " + vXPermMap.getResourceId(), MessageEnums.INVALID_INPUT_DATA); + } + } + + return xUserMgr.createXPermMap(vXPermMap); + } + + @PUT + @Path("/permmaps") + @Consumes("application/json") + @Produces("application/json") + @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.UPDATE_X_PERM_MAP + "\")") + public VXPermMap updateXPermMap(VXPermMap vXPermMap) { + VXPermMap vXPermMapRet = null; + + if (vXPermMap != null) { + if (xResourceService.readResource(vXPermMap.getResourceId()) == null) { + throw restErrorUtil.createRESTException("Invalid Input Data - No resource found with Id: " + vXPermMap.getResourceId()); + } else { + vXPermMapRet = xUserMgr.updateXPermMap(vXPermMap); + } + } + + return vXPermMapRet; + } + + @DELETE + @Path("/permmaps/{id}") + @RangerAnnotationClassName(class_name = VXPermMap.class) + @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.DELETE_X_PERM_MAP + "\")") + 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/json") + @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.SEARCH_X_PERM_MAPS + "\")") + public VXPermMapList searchXPermMaps(@Context HttpServletRequest request) { + SearchCriteria searchCriteria = searchUtil.extractCommonCriterias(request, xPermMapService.sortFields); + + return xUserMgr.searchXPermMaps(searchCriteria); + } + + @GET + @Path("/permmaps/count") + @Produces("application/json") + @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.COUNT_X_PERM_MAPS + "\")") + 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/json") + @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.GET_X_AUDIT_MAP + "\")") + public VXAuditMap getXAuditMap(@PathParam("id") Long id) { + VXAuditMap vXAuditMap = xUserMgr.getXAuditMap(id); + + if (vXAuditMap != null) { + if (xResourceService.readResource(vXAuditMap.getResourceId()) == null) { + throw restErrorUtil.createRESTException("Invalid Input Data - No resource found with Id: " + vXAuditMap.getResourceId(), MessageEnums.INVALID_INPUT_DATA); + } + } + + return vXAuditMap; + } + + @POST + @Path("/auditmaps") + @Consumes("application/json") + @Produces("application/json") + @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.CREATE_X_AUDIT_MAP + "\")") + public VXAuditMap createXAuditMap(VXAuditMap vXAuditMap) { + if (vXAuditMap != null) { + if (xResourceService.readResource(vXAuditMap.getResourceId()) == null) { + throw restErrorUtil.createRESTException("Invalid Input Data - No resource found with Id: " + vXAuditMap.getResourceId(), MessageEnums.INVALID_INPUT_DATA); + } + } + + return xUserMgr.createXAuditMap(vXAuditMap); + } + + @PUT + @Path("/auditmaps") + @Consumes("application/json") + @Produces("application/json") + @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.UPDATE_X_AUDIT_MAP + "\")") + public VXAuditMap updateXAuditMap(VXAuditMap vXAuditMap) { + VXAuditMap vXAuditMapRet = null; + + if (vXAuditMap != null) { + if (xResourceService.readResource(vXAuditMap.getResourceId()) == null) { + throw restErrorUtil.createRESTException("Invalid Input Data - No resource found with Id: " + vXAuditMap.getResourceId(), MessageEnums.INVALID_INPUT_DATA); + } else { + vXAuditMapRet = xUserMgr.updateXAuditMap(vXAuditMap); + } + } + + return vXAuditMapRet; + } + + @DELETE + @Path("/auditmaps/{id}") + @RangerAnnotationClassName(class_name = VXAuditMap.class) + @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.DELETE_X_AUDIT_MAP + "\")") + 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/json") + @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.SEARCH_X_AUDIT_MAPS + "\")") + public VXAuditMapList searchXAuditMaps(@Context HttpServletRequest request) { + SearchCriteria searchCriteria = searchUtil.extractCommonCriterias(request, xAuditMapService.sortFields); + + return xUserMgr.searchXAuditMaps(searchCriteria); + } + + @GET + @Path("/auditmaps/count") + @Produces("application/json") + @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.COUNT_X_AUDIT_MAPS + "\")") + 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/json") + @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.GET_X_USER_BY_USER_NAME + "\")") + public VXUser getXUserByUserName(@Context HttpServletRequest request, @PathParam("userName") String userName) { + return xUserMgr.getXUserByUserName(userName); + } + + @GET + @Path("/groups/groupName/{groupName}") + @Produces("application/json") + @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.GET_X_GROUP_BY_GROUP_NAME + "\")") + public VXGroup getXGroupByGroupName(@Context HttpServletRequest request, @PathParam("groupName") String groupName) { + VXGroup vXGroup = xGroupService.getGroupByGroupName(groupName); + UserSessionBase userSession = ContextUtil.getCurrentUserSession(); + + if (userSession != null && userSession.getLoginId() != null && userSession.getUserRoleList().contains(RangerConstants.ROLE_USER)) { + VXUser loggedInVXUser = xUserService.getXUserByUserName(userSession.getLoginId()); + boolean isMatch = false; + + if (loggedInVXUser != null && vXGroup != null) { + List userGroups = xGroupService.getGroupsByUserId(loggedInVXUser.getId()); + + for (XXGroup xXGroup : userGroups) { + if (xXGroup != null && StringUtils.equals(xXGroup.getName(), vXGroup.getName())) { + isMatch = true; + break; + } } + } + + if (!isMatch) { + vXGroup = null; + } + } + + return vXGroup; + } + + @DELETE + @Path("/users/userName/{userName}") + @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") + public void deleteXUserByUserName(@PathParam("userName") String userName, @Context HttpServletRequest request) { + String forceDeleteStr = request.getParameter("forceDelete"); + boolean forceDelete = !StringUtils.isEmpty(forceDeleteStr) && forceDeleteStr.equalsIgnoreCase("true"); + VXUser vxUser = xUserService.getXUserByUserName(userName); + + xUserMgr.deleteXUser(vxUser.getId(), forceDelete); + } + + /** + * Proceed with caution: Force deletes users from the ranger db, + * Delete happens one at a time with immediate commit on the transaction. + */ + @DELETE + @Path("/delete/external/users") + @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") + @Produces("application/json") + public Response forceDeleteExternalUsers(@Context HttpServletRequest request) { + SearchCriteria searchCriteria = new SearchCriteria(); + + searchUtil.extractString(request, searchCriteria, "name", "User name", null); + searchUtil.extractString(request, searchCriteria, "emailAddress", "Email Address", null); + searchUtil.extractInt(request, searchCriteria, "isVisible", "User Visibility"); + searchUtil.extractInt(request, searchCriteria, "status", "User Status"); + searchUtil.extractString(request, searchCriteria, "syncSource", "Sync Source", null); + searchUtil.extractRoleString(request, searchCriteria, "userRole", "Role", null); + + // for invalid params + if (request.getQueryString() != null && searchCriteria.getParamList().isEmpty()) { + return Response.status(Response.Status.BAD_REQUEST).entity("Invalid query params!").build(); + } + + // only for external users + searchCriteria.addParam("userSource", USER_EXTERNAL); + + List userIds = xUserService.searchXUsersForIds(searchCriteria); + long usersDeleted = xUserMgr.forceDeleteExternalUsers(userIds); + String response = "No users were deleted!"; + + if (usersDeleted == 1) { + response = "1 user deleted successfully."; + } else if (usersDeleted > 0) { + response = String.format("%d users deleted successfully.", usersDeleted); + } + + return Response.ok(response).build(); + } + + /** + * Proceed with caution: Force deletes groups from the ranger db, + * Delete happens one at a time with immediate commit on the transaction. + */ + @DELETE + @Path("/delete/external/groups") + @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") + @Produces("application/json") + public Response forceDeleteExternalGroups(@Context HttpServletRequest request) { + SearchCriteria searchCriteria = new SearchCriteria(); + + searchUtil.extractString(request, searchCriteria, "name", "Group Name", null); + searchUtil.extractInt(request, searchCriteria, "isVisible", "Group Visibility"); + searchUtil.extractString(request, searchCriteria, "syncSource", "Sync Source", null); + + // for invalid params + if (request.getQueryString() != null && searchCriteria.getParamList().isEmpty()) { + return Response.status(Response.Status.BAD_REQUEST).entity("Invalid query params!").build(); + } + + // only for external groups + searchCriteria.addParam("groupSource", GROUP_EXTERNAL); + + List groupIds = xGroupService.searchXGroupsForIds(searchCriteria); + long groupsDeleted = xUserMgr.forceDeleteExternalGroups(groupIds); + String response = "No groups were deleted!"; + + if (groupsDeleted == 1) { + response = "1 group deleted successfully."; + } else if (groupsDeleted > 0) { + response = String.format("%d groups deleted successfully.", groupsDeleted); + } + + return Response.ok(response).build(); + } + + @DELETE + @Path("/groups/groupName/{groupName}") + @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") + public void deleteXGroupByGroupName(@PathParam("groupName") String groupName, @Context HttpServletRequest request) { + String forceDeleteStr = request.getParameter("forceDelete"); + boolean forceDelete = !StringUtils.isEmpty(forceDeleteStr) && forceDeleteStr.equalsIgnoreCase("true"); + VXGroup vxGroup = xGroupService.getGroupByGroupName(groupName); + + xUserMgr.deleteXGroup(vxGroup.getId(), forceDelete); + } + + @DELETE + @Path("/group/{groupName}/user/{userName}") + @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") + public void deleteXGroupAndXUser(@PathParam("groupName") String groupName, @PathParam("userName") String userName, @Context HttpServletRequest request) { + xUserMgr.deleteXGroupAndXUser(groupName, userName); + } + + @GET + @Path("/{userId}/groups") + @Produces("application/json") + @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.GET_X_USER_GROUPS + "\")") + public VXGroupList getXUserGroups(@Context HttpServletRequest request, @PathParam("userId") Long id) { + return xUserMgr.getXUserGroups(id); + } + + @GET + @Path("/{groupId}/users") + @Produces("application/json") + @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.GET_X_GROUP_USERS + "\")") + public VXUserList getXGroupUsers(@Context HttpServletRequest request, @PathParam("groupId") Long id) { + SearchCriteria searchCriteria = searchUtil.extractCommonCriterias(request, xGroupUserService.sortFields); + + searchCriteria.addParam("xGroupId", id); + + return xUserMgr.getXGroupUsers(searchCriteria); + } + + @GET + @Path("/authSessions") + @Produces("application/json") + @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.GET_AUTH_SESSIONS + "\")") + 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", "Login 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", null); + searchUtil.extractDate(request, searchCriteria, "endDate", "End Date", null); + + return sessionMgr.searchAuthSessions(searchCriteria); + } + + @GET + @Path("/authSessions/info") + @Produces("application/json") + @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.GET_AUTH_SESSION + "\")") + public VXAuthSession getAuthSession(@Context HttpServletRequest request) { + String authSessionId = request.getParameter("extSessionId"); + + return sessionMgr.getAuthSessionBySessionId(authSessionId); + } + + // Handle module permissions + @POST + @Path("/permission") + @Consumes("application/json") + @Produces("application/json") + @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.CREATE_X_MODULE_DEF_PERMISSION + "\")") + public VXModuleDef createXModuleDefPermission(VXModuleDef vXModuleDef) { + xUserMgr.checkAdminAccess(); + bizUtil.blockAuditorRoleUser(); + + return xUserMgr.createXModuleDefPermission(vXModuleDef); + } + + @GET + @Path("/permission/{id}") + @Produces("application/json") + @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.GET_X_MODULE_DEF_PERMISSION + "\")") + public VXModuleDef getXModuleDefPermission(@PathParam("id") Long id) { + return xUserMgr.getXModuleDefPermission(id); + } + + @PUT + @Path("/permission/{id}") + @Consumes("application/json") + @Produces("application/json") + @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.UPDATE_X_MODULE_DEF_PERMISSION + "\")") + public VXModuleDef updateXModuleDefPermission(VXModuleDef vXModuleDef) { + xUserMgr.checkAdminAccess(); + bizUtil.blockAuditorRoleUser(); + + return xUserMgr.updateXModuleDefPermission(vXModuleDef); + } + + @DELETE + @Path("/permission/{id}") + @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.DELETE_X_MODULE_DEF_PERMISSION + "\")") + public void deleteXModuleDefPermission(@PathParam("id") Long id, @Context HttpServletRequest request) { + boolean force = true; + + xUserMgr.checkAdminAccess(); + bizUtil.blockAuditorRoleUser(); + xUserMgr.deleteXModuleDefPermission(id, force); + } + + @GET + @Path("/permission") + @Produces("application/json") + @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.SEARCH_X_MODULE_DEF + "\")") + public VXModuleDefList searchXModuleDef(@Context HttpServletRequest request) { + SearchCriteria searchCriteria = searchUtil.extractCommonCriterias(request, xModuleDefService.sortFields); + + searchUtil.extractString(request, searchCriteria, "module", "modulename", null); + searchUtil.extractString(request, searchCriteria, "moduleDefList", "id", null); + searchUtil.extractString(request, searchCriteria, "userName", "userName", null); + searchUtil.extractString(request, searchCriteria, "groupName", "groupName", null); + + return xUserMgr.searchXModuleDef(searchCriteria); + } + + @GET + @Path("/permissionlist") + @Produces("application/json") + @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.SEARCH_X_MODULE_DEF + "\")") + public VXModulePermissionList searchXModuleDefList(@Context HttpServletRequest request) { + SearchCriteria searchCriteria = searchUtil.extractCommonCriterias(request, xModuleDefService.sortFields); + + searchUtil.extractString(request, searchCriteria, "module", "modulename", null); + searchUtil.extractString(request, searchCriteria, "moduleDefList", "id", null); + searchUtil.extractString(request, searchCriteria, "userName", "userName", null); + searchUtil.extractString(request, searchCriteria, "groupName", "groupName", null); + + return xUserMgr.searchXModuleDefList(searchCriteria); + } + + @GET + @Path("/permission/count") + @Produces("application/json") + @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.COUNT_X_MODULE_DEF + "\")") + public VXLong countXModuleDef(@Context HttpServletRequest request) { + SearchCriteria searchCriteria = searchUtil.extractCommonCriterias(request, xModuleDefService.sortFields); + + return xUserMgr.getXModuleDefSearchCount(searchCriteria); + } + + // Handle user permissions + @POST + @Path("/permission/user") + @Consumes("application/json") + @Produces("application/json") + @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.CREATE_X_USER_PERMISSION + "\")") + public VXUserPermission createXUserPermission(VXUserPermission vXUserPermission) { + xUserMgr.checkAdminAccess(); + bizUtil.blockAuditorRoleUser(); + + return xUserMgr.createXUserPermission(vXUserPermission); + } + + @GET + @Path("/permission/user/{id}") + @Produces("application/json") + @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.GET_X_USER_PERMISSION + "\")") + public VXUserPermission getXUserPermission(@PathParam("id") Long id) { + return xUserMgr.getXUserPermission(id); + } + + @PUT + @Path("/permission/user/{id}") + @Consumes("application/json") + @Produces("application/json") + @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.UPDATE_X_USER_PERMISSION + "\")") + public VXUserPermission updateXUserPermission(VXUserPermission vXUserPermission) { + xUserMgr.checkAdminAccess(); + bizUtil.blockAuditorRoleUser(); + + return xUserMgr.updateXUserPermission(vXUserPermission); + } + + @DELETE + @Path("/permission/user/{id}") + @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.DELETE_X_USER_PERMISSION + "\")") + public void deleteXUserPermission(@PathParam("id") Long id, @Context HttpServletRequest request) { + boolean force = true; + + xUserMgr.checkAdminAccess(); + xUserMgr.deleteXUserPermission(id, force); + } + + @GET + @Path("/permission/user") + @Produces("application/json") + @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.SEARCH_X_USER_PERMISSION + "\")") + public VXUserPermissionList searchXUserPermission(@Context HttpServletRequest request) { + SearchCriteria searchCriteria = searchUtil.extractCommonCriterias(request, xUserPermissionService.sortFields); + + searchUtil.extractString(request, searchCriteria, "id", "id", StringUtil.VALIDATION_NAME); + searchUtil.extractString(request, searchCriteria, "userPermissionList", "userId", StringUtil.VALIDATION_NAME); + + return xUserMgr.searchXUserPermission(searchCriteria); + } + + @GET + @Path("/permission/user/count") + @Produces("application/json") + @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.COUNT_X_USER_PERMISSION + "\")") + public VXLong countXUserPermission(@Context HttpServletRequest request) { + SearchCriteria searchCriteria = searchUtil.extractCommonCriterias(request, xUserPermissionService.sortFields); + + return xUserMgr.getXUserPermissionSearchCount(searchCriteria); + } + + // Handle group permissions + @POST + @Path("/permission/group") + @Consumes("application/json") + @Produces("application/json") + @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.CREATE_X_GROUP_PERMISSION + "\")") + public VXGroupPermission createXGroupPermission(VXGroupPermission vXGroupPermission) { + xUserMgr.checkAdminAccess(); + bizUtil.blockAuditorRoleUser(); + + return xUserMgr.createXGroupPermission(vXGroupPermission); + } + + @GET + @Path("/permission/group/{id}") + @Produces("application/json") + @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.GET_X_GROUP_PERMISSION + "\")") + public VXGroupPermission getXGroupPermission(@PathParam("id") Long id) { + return xUserMgr.getXGroupPermission(id); + } + + @PUT + @Path("/permission/group/{id}") + @Consumes("application/json") + @Produces("application/json") + @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.UPDATE_X_GROUP_PERMISSION + "\")") + public VXGroupPermission updateXGroupPermission(@PathParam("id") Long id, VXGroupPermission vXGroupPermission) { + // if VXGroupPermission.id is specified, it should be same as the param 'id' + if (vXGroupPermission.getId() == null) { + vXGroupPermission.setId(id); + } else if (!vXGroupPermission.getId().equals(id)) { + throw restErrorUtil.createRESTException(HttpServletResponse.SC_BAD_REQUEST, "vXGroupPermission Id mismatch", true); } - @DELETE - @Path("/secure/groups/id/{groupId}") - @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") - public void deleteSingleGroupByGroupId(@Context HttpServletRequest request, @PathParam("groupId") Long groupId) { - String forceDeleteStr = request.getParameter("forceDelete"); - boolean forceDelete = false; - if (StringUtils.isNotEmpty(forceDeleteStr) && "true".equalsIgnoreCase(forceDeleteStr)) { - forceDelete = true; + xUserMgr.checkAdminAccess(); + bizUtil.blockAuditorRoleUser(); + + return xUserMgr.updateXGroupPermission(vXGroupPermission); + } + + @DELETE + @Path("/permission/group/{id}") + @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.DELETE_X_GROUP_PERMISSION + "\")") + public void deleteXGroupPermission(@PathParam("id") Long id, @Context HttpServletRequest request) { + boolean force = true; + + xUserMgr.checkAdminAccess(); + bizUtil.blockAuditorRoleUser(); + xUserMgr.deleteXGroupPermission(id, force); + } + + @GET + @Path("/permission/group") + @Produces("application/json") + @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.SEARCH_X_GROUP_PERMISSION + "\")") + public VXGroupPermissionList searchXGroupPermission(@Context HttpServletRequest request) { + SearchCriteria searchCriteria = searchUtil.extractCommonCriterias(request, xGroupPermissionService.sortFields); + + searchUtil.extractString(request, searchCriteria, "id", "id", StringUtil.VALIDATION_NAME); + searchUtil.extractString(request, searchCriteria, "groupPermissionList", "groupId", StringUtil.VALIDATION_NAME); + + return xUserMgr.searchXGroupPermission(searchCriteria); + } + + @GET + @Path("/permission/group/count") + @Produces("application/json") + @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.COUNT_X_GROUP_PERMISSION + "\")") + public VXLong countXGroupPermission(@Context HttpServletRequest request) { + SearchCriteria searchCriteria = searchUtil.extractCommonCriterias(request, xGroupPermissionService.sortFields); + + return xUserMgr.getXGroupPermissionSearchCount(searchCriteria); + } + + @PUT + @Path("/secure/users/activestatus") + @Produces("application/json") + @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.MODIFY_USER_ACTIVE_STATUS + "\")") + public void modifyUserActiveStatus(HashMap statusMap) { + xUserMgr.modifyUserActiveStatus(statusMap); + } + + @PUT + @Path("/secure/users/roles/{userId}") + @Consumes("application/json") + @Produces("application/json") + @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.SET_USER_ROLES_BY_ID + "\")") + public VXStringList setUserRolesByExternalID(@PathParam("userId") Long userId, VXStringList roleList) { + return xUserMgr.setUserRolesByExternalID(userId, roleList.getVXStrings()); + } + + @PUT + @Path("/secure/users/roles/userName/{userName}") + @Consumes("application/json") + @Produces("application/json") + @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.SET_USER_ROLES_BY_NAME + "\")") + public VXStringList setUserRolesByName(@PathParam("userName") String userName, VXStringList roleList) { + return xUserMgr.setUserRolesByName(userName, roleList.getVXStrings()); + } + + @GET + @Path("/secure/users/external/{userId}") + @Produces("application/json") + @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.GET_USER_ROLES_BY_ID + "\")") + public VXStringList getUserRolesByExternalID(@PathParam("userId") Long userId) { + return xUserMgr.getUserRolesByExternalID(userId); + } + + @GET + @Path("/secure/users/roles/userName/{userName}") + @Produces("application/json") + @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.GET_USER_ROLES_BY_NAME + "\")") + public VXStringList getUserRolesByName(@PathParam("userName") String userName) { + return xUserMgr.getUserRolesByName(userName); + } + + @DELETE + @Path("/secure/users/delete") + @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") + public void deleteUsersByUserName(@Context HttpServletRequest request, VXStringList userList) { + String forceDeleteStr = request.getParameter("forceDelete"); + boolean forceDelete = StringUtils.isNotEmpty(forceDeleteStr) && "true".equalsIgnoreCase(forceDeleteStr); + + if (userList != null && userList.getList() != null) { + for (VXString userName : userList.getList()) { + if (StringUtils.isNotEmpty(userName.getValue())) { + VXUser vxUser = xUserService.getXUserByUserName(userName.getValue()); + + xUserMgr.deleteXUser(vxUser.getId(), forceDelete); } - if (groupId != null) { - xUserMgr.deleteXGroup(groupId, forceDelete); + } + } + } + + @DELETE + @Path("/secure/groups/delete") + @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") + public void deleteGroupsByGroupName(@Context HttpServletRequest request, VXStringList groupList) { + String forceDeleteStr = request.getParameter("forceDelete"); + boolean forceDelete = StringUtils.isNotEmpty(forceDeleteStr) && "true".equalsIgnoreCase(forceDeleteStr); + + if (groupList != null && groupList.getList() != null) { + for (VXString groupName : groupList.getList()) { + if (StringUtils.isNotEmpty(groupName.getValue())) { + VXGroup vxGroup = xGroupService.getGroupByGroupName(groupName.getValue()); + + xUserMgr.deleteXGroup(vxGroup.getId(), forceDelete); } + } + } + } + + @DELETE + @Path("/secure/users/{userName}") + @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") + public void deleteSingleUserByUserName(@Context HttpServletRequest request, @PathParam("userName") String userName) { + String forceDeleteStr = request.getParameter("forceDelete"); + boolean forceDelete = StringUtils.isNotEmpty(forceDeleteStr) && "true".equalsIgnoreCase(forceDeleteStr); + + if (StringUtils.isNotEmpty(userName)) { + VXUser vxUser = xUserService.getXUserByUserName(userName); + + xUserMgr.deleteXUser(vxUser.getId(), forceDelete); } + } + + @DELETE + @Path("/secure/groups/{groupName}") + @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") + public void deleteSingleGroupByGroupName(@Context HttpServletRequest request, @PathParam("groupName") String groupName) { + String forceDeleteStr = request.getParameter("forceDelete"); + boolean forceDelete = StringUtils.isNotEmpty(forceDeleteStr) && "true".equalsIgnoreCase(forceDeleteStr); + + if (StringUtils.isNotEmpty(groupName)) { + VXGroup vxGroup = xGroupService.getGroupByGroupName(groupName.trim()); + + xUserMgr.deleteXGroup(vxGroup.getId(), forceDelete); + } + } + + @DELETE + @Path("/secure/users/id/{userId}") + @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") + public void deleteSingleUserByUserId(@Context HttpServletRequest request, @PathParam("userId") Long userId) { + String forceDeleteStr = request.getParameter("forceDelete"); + boolean forceDelete = StringUtils.isNotEmpty(forceDeleteStr) && "true".equalsIgnoreCase(forceDeleteStr); + + if (userId != null) { + xUserMgr.deleteXUser(userId, forceDelete); + } + } + + @DELETE + @Path("/secure/groups/id/{groupId}") + @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") + public void deleteSingleGroupByGroupId(@Context HttpServletRequest request, @PathParam("groupId") Long groupId) { + String forceDeleteStr = request.getParameter("forceDelete"); + boolean forceDelete = StringUtils.isNotEmpty(forceDeleteStr) && "true".equalsIgnoreCase(forceDeleteStr); + + if (groupId != null) { + xUserMgr.deleteXGroup(groupId, forceDelete); + } + } @GET @Path("/download/{serviceName}") - @Produces({ "application/json" }) - public RangerUserStore getRangerUserStoreIfUpdated(@PathParam("serviceName") String serviceName, - @DefaultValue("-1") @QueryParam("lastKnownUserStoreVersion") Long lastKnownUserStoreVersion, - @DefaultValue("0") @QueryParam("lastActivationTime") Long lastActivationTime, - @QueryParam("pluginId") String pluginId, - @DefaultValue("") @QueryParam("clusterName") String clusterName, - @DefaultValue("") @QueryParam(RangerRESTUtils.REST_PARAM_CAPABILITIES) String pluginCapabilities, - @Context HttpServletRequest request) throws Exception { - if (logger.isDebugEnabled()) { - logger.debug("==> XUserREST.getRangerUserStoreIfUpdated(serviceName={}, lastKnownUserStoreVersion={}, lastActivationTime={})", serviceName, lastKnownUserStoreVersion, lastActivationTime); - } + @Produces("application/json") + public RangerUserStore getRangerUserStoreIfUpdated(@PathParam("serviceName") String serviceName, @DefaultValue("-1") @QueryParam("lastKnownUserStoreVersion") Long lastKnownUserStoreVersion, @DefaultValue("0") @QueryParam("lastActivationTime") Long lastActivationTime, @QueryParam("pluginId") String pluginId, @DefaultValue("") @QueryParam("clusterName") String clusterName, @DefaultValue("") @QueryParam(RangerRESTUtils.REST_PARAM_CAPABILITIES) String pluginCapabilities, @Context HttpServletRequest request) { + logger.debug("==> XUserREST.getRangerUserStoreIfUpdated(serviceName={}, lastKnownUserStoreVersion={}, lastActivationTime={})", serviceName, lastKnownUserStoreVersion, lastActivationTime); - RangerUserStore ret = null; - boolean isValid = false; - int httpCode = HttpServletResponse.SC_OK; - String logMsg = null; - Long downloadedVersion = null; + RangerUserStore ret = null; + boolean isValid = false; + int httpCode = HttpServletResponse.SC_OK; + String logMsg = null; + Long downloadedVersion = null; - try { + try { bizUtil.failUnauthenticatedDownloadIfNotAllowed(); isValid = serviceUtil.isValidService(serviceName, request); @@ -1429,7 +1401,6 @@ public RangerUserStore getRangerUserStoreIfUpdated(@PathParam("serviceName") Str XXService xService = rangerDaoManager.getXXService().findByName(serviceName); if (xService != null) { - RangerUserStore rangerUserStore = xUserMgr.getRangerUserStoreIfUpdated(lastKnownUserStoreVersion); if (rangerUserStore == null) { @@ -1439,7 +1410,6 @@ public RangerUserStore getRangerUserStoreIfUpdated(@PathParam("serviceName") Str } else { downloadedVersion = rangerUserStore.getUserStoreVersion(); ret = rangerUserStore; - httpCode = HttpServletResponse.SC_OK; logMsg = "Returning RangerUserStore version " + downloadedVersion; } } @@ -1459,178 +1429,170 @@ public RangerUserStore getRangerUserStoreIfUpdated(@PathParam("serviceName") Str throw restErrorUtil.createRESTException(httpCode, logMsg, logError); } - if (logger.isDebugEnabled()) { - logger.debug("<== XUserREST.getRangerUserStoreIfUpdated(serviceName={}, lastKnownUserStoreVersion={}, lastActivationTime={}): {}", serviceName, lastKnownUserStoreVersion, lastActivationTime, ret); + logger.debug("<== XUserREST.getRangerUserStoreIfUpdated(serviceName={}, lastKnownUserStoreVersion={}, lastActivationTime={}): {}", serviceName, lastKnownUserStoreVersion, lastActivationTime, ret); + + return ret; + } + + @GET + @Path("/secure/download/{serviceName}") + @Produces("application/json") + public RangerUserStore getSecureRangerUserStoreIfUpdated(@PathParam("serviceName") String serviceName, @DefaultValue("-1") @QueryParam("lastKnownUserStoreVersion") Long lastKnownUserStoreVersion, @DefaultValue("0") @QueryParam("lastActivationTime") Long lastActivationTime, @QueryParam("pluginId") String pluginId, @DefaultValue("") @QueryParam("clusterName") String clusterName, @DefaultValue("") @QueryParam(RangerRESTUtils.REST_PARAM_CAPABILITIES) String pluginCapabilities, @Context HttpServletRequest request) { + logger.debug("==> XUserREST.getSecureRangerUserStoreIfUpdated({}, {}, {})", serviceName, lastKnownUserStoreVersion, lastActivationTime); + + RangerUserStore ret = null; + int httpCode = HttpServletResponse.SC_OK; + String logMsg = null; + boolean isAdmin = bizUtil.isAdmin(); + boolean isKeyAdmin = bizUtil.isKeyAdmin(); + Long downloadedVersion = null; + boolean isValid = false; + boolean isAllowed; + + try { + isValid = serviceUtil.isValidService(serviceName, request); + } catch (WebApplicationException webException) { + httpCode = webException.getResponse().getStatus(); + logMsg = webException.getResponse().getEntity().toString(); + } catch (Exception e) { + httpCode = HttpServletResponse.SC_BAD_REQUEST; + logMsg = e.getMessage(); + } + + try { + XXService xService = rangerDaoManager.getXXService().findByName(serviceName); + + if (xService != null) { + isValid = true; + } + + if (isValid) { + XXServiceDef xServiceDef = rangerDaoManager.getXXServiceDef().getById(xService.getType()); + RangerService rangerService = svcStore.getServiceByName(serviceName); + + if (StringUtils.equals(xServiceDef.getImplclassname(), EmbeddedServiceDefsUtil.KMS_IMPL_CLASS_NAME)) { + if (isKeyAdmin) { + isAllowed = true; + } else { + isAllowed = bizUtil.isUserAllowed(rangerService, USERSTORE_DOWNLOAD_USERS); + } + } else { + if (isAdmin) { + isAllowed = true; + } else { + isAllowed = bizUtil.isUserAllowed(rangerService, USERSTORE_DOWNLOAD_USERS); + } + } + + if (isAllowed) { + RangerUserStore rangerUserStore = xUserMgr.getRangerUserStoreIfUpdated(lastKnownUserStoreVersion); + + if (rangerUserStore == null) { + downloadedVersion = lastKnownUserStoreVersion; + httpCode = HttpServletResponse.SC_NOT_MODIFIED; + logMsg = "No change since last update"; + } else { + downloadedVersion = rangerUserStore.getUserStoreVersion(); + ret = rangerUserStore; + logMsg = "Returning RangerUserStore =>" + (ret); + } + } else { + logger.error("getSecureRangerUserStoreIfUpdated({}, {}) failed as User doesn't have permission to download UsersAndGroups", serviceName, lastKnownUserStoreVersion); + + httpCode = HttpServletResponse.SC_FORBIDDEN; // assert user is authenticated. + logMsg = "User doesn't have permission to download UsersAndGroups"; + } + } + } catch (Throwable excp) { + logger.error("getSecureRangerUserStoreIfUpdated({}, {}, {}) failed", serviceName, lastKnownUserStoreVersion, lastActivationTime, excp); + + httpCode = HttpServletResponse.SC_BAD_REQUEST; + logMsg = excp.getMessage(); } + assetMgr.createPluginInfo(serviceName, pluginId, request, RangerPluginInfo.ENTITY_TYPE_USERSTORE, downloadedVersion, lastKnownUserStoreVersion, lastActivationTime, httpCode, clusterName, pluginCapabilities); + + if (httpCode != HttpServletResponse.SC_OK) { + boolean logError = httpCode != HttpServletResponse.SC_NOT_MODIFIED; + + throw restErrorUtil.createRESTException(httpCode, logMsg, logError); + } + + logger.debug("<== XUserREST.getSecureRangerUserStoreIfUpdated({}, {}, {}): {}", serviceName, lastKnownUserStoreVersion, lastActivationTime, ret); + return ret; } - @GET - @Path("/secure/download/{serviceName}") - @Produces({ "application/json" }) - public RangerUserStore getSecureRangerUserStoreIfUpdated(@PathParam("serviceName") String serviceName, - @DefaultValue("-1") @QueryParam("lastKnownUserStoreVersion") Long lastKnownUserStoreVersion, - @DefaultValue("0") @QueryParam("lastActivationTime") Long lastActivationTime, - @QueryParam("pluginId") String pluginId, - @DefaultValue("") @QueryParam("clusterName") String clusterName, - @DefaultValue("") @QueryParam(RangerRESTUtils.REST_PARAM_CAPABILITIES) String pluginCapabilities, - @Context HttpServletRequest request) throws Exception { - if (logger.isDebugEnabled()) { - logger.debug("==> XUserREST.getSecureRangerUserStoreIfUpdated(" - + serviceName + ", " + lastKnownUserStoreVersion + ", " + lastActivationTime + ")"); - } - RangerUserStore ret = null; - int httpCode = HttpServletResponse.SC_OK; - String logMsg = null; - boolean isAllowed = false; - boolean isAdmin = bizUtil.isAdmin(); - boolean isKeyAdmin = bizUtil.isKeyAdmin(); - Long downloadedVersion = null; - - boolean isValid = false; - try { - isValid = serviceUtil.isValidService(serviceName, request); - } catch (WebApplicationException webException) { - httpCode = webException.getResponse().getStatus(); - logMsg = webException.getResponse().getEntity().toString(); - } catch (Exception e) { - httpCode = HttpServletResponse.SC_BAD_REQUEST; - logMsg = e.getMessage(); - } - - try { - XXService xService = rangerDaoManager.getXXService().findByName(serviceName); - if (xService != null) { - isValid = true; - } - if (isValid) { - XXServiceDef xServiceDef = rangerDaoManager.getXXServiceDef().getById(xService.getType()); - RangerService rangerService = svcStore.getServiceByName(serviceName); - - if (StringUtils.equals(xServiceDef.getImplclassname(), EmbeddedServiceDefsUtil.KMS_IMPL_CLASS_NAME)) { - if (isKeyAdmin) { - isAllowed = true; - } else { - isAllowed = bizUtil.isUserAllowed(rangerService, USERSTORE_DOWNLOAD_USERS); - } - } else { - if (isAdmin) { - isAllowed = true; - } else { - isAllowed = bizUtil.isUserAllowed(rangerService, USERSTORE_DOWNLOAD_USERS); - } - } - - if (isAllowed) { - RangerUserStore rangerUserStore = xUserMgr.getRangerUserStoreIfUpdated(lastKnownUserStoreVersion); - if (rangerUserStore == null) { - downloadedVersion = lastKnownUserStoreVersion; - httpCode = HttpServletResponse.SC_NOT_MODIFIED; - logMsg = "No change since last update"; - } else { - downloadedVersion = rangerUserStore.getUserStoreVersion(); - ret = rangerUserStore; - httpCode = HttpServletResponse.SC_OK; - logMsg = "Returning RangerUserStore =>" + (ret.toString()); - } - } else { - logger.error("getSecureRangerUserStoreIfUpdated(" + serviceName + ", " + lastKnownUserStoreVersion + ") failed as User doesn't have permission to download UsersAndGroups"); - httpCode = HttpServletResponse.SC_FORBIDDEN; // assert user is authenticated. - logMsg = "User doesn't have permission to download UsersAndGroups"; - } - } - - } catch (Throwable excp) { - logger.error("getSecureRangerUserStoreIfUpdated(" + serviceName + ", " + lastKnownUserStoreVersion + ", " + lastActivationTime + ") failed", excp); - httpCode = HttpServletResponse.SC_BAD_REQUEST; - logMsg = excp.getMessage(); - } - - assetMgr.createPluginInfo(serviceName, pluginId, request, RangerPluginInfo.ENTITY_TYPE_USERSTORE, downloadedVersion, lastKnownUserStoreVersion, lastActivationTime, httpCode, clusterName, pluginCapabilities); - - if (httpCode != HttpServletResponse.SC_OK) { - boolean logError = httpCode != HttpServletResponse.SC_NOT_MODIFIED; - throw restErrorUtil.createRESTException(httpCode, logMsg, logError); - } - - if (logger.isDebugEnabled()) { - logger.debug("<== XUserREST.getSecureRangerUserStoreIfUpdated(" + serviceName + ", " + lastKnownUserStoreVersion + ", " + lastActivationTime + ")" + ret); - } - return ret; - } - - @POST - @Path("/ugsync/auditinfo") - @Consumes({ "application/json" }) - @Produces({ "application/json" }) - @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") - public VXUgsyncAuditInfo postUserGroupAuditInfo(VXUgsyncAuditInfo vxUgsyncAuditInfo) { - - return xUserMgr.postUserGroupAuditInfo(vxUgsyncAuditInfo); - } - - @GET - @Path("/ugsync/groupusers") - @Produces({ "application/json" }) - @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") - public Map> getAllGroupUsers() { - return rangerDaoManager.getXXGroupUser().findUsersByGroupIds(); - } - - @POST - @Path("/ugsync/users") - @Consumes({ "application/json" }) - @Produces({ "application/json" }) - @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") - @Transactional(readOnly = false, propagation = Propagation.NOT_SUPPORTED) - public String addOrUpdateUsers(VXUserList users) { - int ret = xUserMgr.createOrUpdateXUsers(users); - return String.valueOf(ret); - } - - @POST - @Path("/ugsync/groups") - @Consumes({ "application/json" }) - @Produces({ "application/json" }) - @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") - public int addOrUpdateGroups(VXGroupList groups) { - int ret = xUserMgr.createOrUpdateXGroups(groups); - return ret; - } - - @POST - @Path("/ugsync/groupusers") - @Consumes({ "application/json" }) - @Produces({ "application/json" }) - @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") - public int addOrUpdateGroupUsersList(List groupUserInfoList) { - return xUserMgr.createOrDeleteXGroupUserList(groupUserInfoList); - } - - @POST - @Path("/users/roleassignments") - @Produces({ "application/json" }) - @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") - public List setXUserRolesByName(UsersGroupRoleAssignments ugRoleAssignments) { - return xUserMgr.updateUserRoleAssignments(ugRoleAssignments); - } - - @POST - @Path("/ugsync/groups/visibility") - @Consumes({ "application/json" }) - @Produces({ "application/json" }) - @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") - public int updateDeletedGroups(Set deletedGroups){ - return xUserMgr.updateDeletedGroups(deletedGroups); - } - - @POST - @Path("/ugsync/users/visibility") - @Consumes({ "application/json" }) - @Produces({ "application/json" }) - @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") - public int updateDeletedUsers(Set deletedUsers){ - return xUserMgr.updateDeletedUsers(deletedUsers); - } + @POST + @Path("/ugsync/auditinfo") + @Consumes("application/json") + @Produces("application/json") + @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") + public VXUgsyncAuditInfo postUserGroupAuditInfo(VXUgsyncAuditInfo vxUgsyncAuditInfo) { + return xUserMgr.postUserGroupAuditInfo(vxUgsyncAuditInfo); + } + + @GET + @Path("/ugsync/groupusers") + @Produces("application/json") + @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") + public Map> getAllGroupUsers() { + return rangerDaoManager.getXXGroupUser().findUsersByGroupIds(); + } + + @POST + @Path("/ugsync/users") + @Consumes("application/json") + @Produces("application/json") + @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") + @Transactional(readOnly = false, propagation = Propagation.NOT_SUPPORTED) + public String addOrUpdateUsers(VXUserList users) { + int ret = xUserMgr.createOrUpdateXUsers(users); + + return String.valueOf(ret); + } + + @POST + @Path("/ugsync/groups") + @Consumes("application/json") + @Produces("application/json") + @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") + public int addOrUpdateGroups(VXGroupList groups) { + return xUserMgr.createOrUpdateXGroups(groups); + } + + @POST + @Path("/ugsync/groupusers") + @Consumes("application/json") + @Produces("application/json") + @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") + public int addOrUpdateGroupUsersList(List groupUserInfoList) { + return xUserMgr.createOrDeleteXGroupUserList(groupUserInfoList); + } + + @POST + @Path("/users/roleassignments") + @Produces("application/json") + @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") + public List setXUserRolesByName(UsersGroupRoleAssignments ugRoleAssignments) { + return xUserMgr.updateUserRoleAssignments(ugRoleAssignments); + } + + @POST + @Path("/ugsync/groups/visibility") + @Consumes("application/json") + @Produces("application/json") + @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") + public int updateDeletedGroups(Set deletedGroups) { + return xUserMgr.updateDeletedGroups(deletedGroups); + } + + @POST + @Path("/ugsync/users/visibility") + @Consumes("application/json") + @Produces("application/json") + @PreAuthorize("hasRole('ROLE_SYS_ADMIN')") + public int updateDeletedUsers(Set deletedUsers) { + return xUserMgr.updateDeletedUsers(deletedUsers); + } } diff --git a/security-admin/src/test/java/org/apache/ranger/rest/TestServiceREST.java b/security-admin/src/test/java/org/apache/ranger/rest/TestServiceREST.java index 3683442be9..3a23d96ceb 100644 --- a/security-admin/src/test/java/org/apache/ranger/rest/TestServiceREST.java +++ b/security-admin/src/test/java/org/apache/ranger/rest/TestServiceREST.java @@ -894,7 +894,7 @@ public void test23getServicePoliciesByName() throws Exception { HttpServletRequest request = Mockito.mock(HttpServletRequest.class); RangerPolicy rangerPolicy = rangerPolicy(); - List ret = Mockito.mock(List.class); + List ret = Collections.emptyList(); SearchFilter filter = new SearchFilter(); filter.setParam(SearchFilter.POLICY_NAME, "policyName"); From 376b2afa7ac47b4d93cd3a2dbc9c9b63809d0a01 Mon Sep 17 00:00:00 2001 From: PradeeP AgrawaL Date: Sun, 12 Jan 2025 14:37:00 +0530 Subject: [PATCH 14/15] RANGER-5061: checkstyle compliance updates - security-admin modules : org.apache.ranger.entity package (#504) --- .../apache/ranger/entity/XXAccessAudit.java | 171 +- .../ranger/entity/XXAccessAuditBase.java | 1240 +++++++------- .../apache/ranger/entity/XXAccessAuditV4.java | 15 +- .../apache/ranger/entity/XXAccessAuditV5.java | 111 +- .../apache/ranger/entity/XXAccessTypeDef.java | 587 ++++--- .../ranger/entity/XXAccessTypeDefGrants.java | 278 ++- .../org/apache/ranger/entity/XXAsset.java | 522 +++--- .../org/apache/ranger/entity/XXAuditMap.java | 389 ++--- .../apache/ranger/entity/XXAuthSession.java | 924 +++++----- .../ranger/entity/XXContextEnricherDef.java | 500 +++--- .../ranger/entity/XXCredentialStore.java | 268 +-- .../org/apache/ranger/entity/XXDBBase.java | 418 ++--- .../org/apache/ranger/entity/XXDataHist.java | 817 ++++----- .../ranger/entity/XXDataMaskTypeDef.java | 785 ++++----- .../org/apache/ranger/entity/XXEnumDef.java | 408 ++--- .../ranger/entity/XXEnumElementDef.java | 483 +++--- .../apache/ranger/entity/XXGdsDataShare.java | 206 ++- .../entity/XXGdsDataShareInDataset.java | 178 +- .../apache/ranger/entity/XXGdsDataset.java | 164 +- .../ranger/entity/XXGdsDatasetInProject.java | 181 +- .../ranger/entity/XXGdsDatasetPolicyMap.java | 58 +- .../apache/ranger/entity/XXGdsProject.java | 145 +- .../ranger/entity/XXGdsProjectPolicyMap.java | 59 +- .../ranger/entity/XXGdsSharedResource.java | 242 ++- .../apache/ranger/entity/XXGlobalState.java | 25 +- .../ranger/entity/XXGlobalStateBase.java | 36 +- .../org/apache/ranger/entity/XXGroup.java | 646 +++---- .../apache/ranger/entity/XXGroupGroup.java | 328 ++-- .../ranger/entity/XXGroupPermission.java | 247 ++- .../org/apache/ranger/entity/XXGroupUser.java | 331 ++-- .../org/apache/ranger/entity/XXModuleDef.java | 189 +- .../org/apache/ranger/entity/XXPermMap.java | 732 ++++---- .../apache/ranger/entity/XXPluginInfo.java | 359 ++-- .../org/apache/ranger/entity/XXPolicy.java | 91 +- .../apache/ranger/entity/XXPolicyBase.java | 712 ++++---- .../ranger/entity/XXPolicyChangeLog.java | 159 +- .../ranger/entity/XXPolicyConditionDef.java | 1008 +++++------ .../ranger/entity/XXPolicyExportAudit.java | 739 ++++---- .../apache/ranger/entity/XXPolicyItem.java | 586 +++---- .../ranger/entity/XXPolicyItemAccess.java | 469 +++-- .../ranger/entity/XXPolicyItemCondition.java | 469 +++-- .../entity/XXPolicyItemDataMaskInfo.java | 411 ++--- .../ranger/entity/XXPolicyItemGroupPerm.java | 347 ++-- .../entity/XXPolicyItemRowFilterInfo.java | 278 ++- .../ranger/entity/XXPolicyItemUserPerm.java | 353 ++-- .../apache/ranger/entity/XXPolicyLabel.java | 206 ++- .../ranger/entity/XXPolicyLabelMap.java | 260 ++- .../ranger/entity/XXPolicyRefAccessType.java | 320 ++-- .../ranger/entity/XXPolicyRefCondition.java | 320 ++-- .../entity/XXPolicyRefDataMaskType.java | 321 ++-- .../ranger/entity/XXPolicyRefGroup.java | 318 ++-- .../ranger/entity/XXPolicyRefResource.java | 320 ++-- .../apache/ranger/entity/XXPolicyRefRole.java | 130 +- .../apache/ranger/entity/XXPolicyRefUser.java | 320 ++-- .../ranger/entity/XXPolicyResource.java | 402 ++--- .../ranger/entity/XXPolicyResourceMap.java | 347 ++-- .../ranger/entity/XXPolicyWithAssignedId.java | 73 +- .../apache/ranger/entity/XXPortalUser.java | 855 +++++----- .../ranger/entity/XXPortalUserRole.java | 315 ++-- .../ranger/entity/XXRMSMappingProvider.java | 80 +- .../ranger/entity/XXRMSNotification.java | 233 +-- .../ranger/entity/XXRMSResourceMapping.java | 122 +- .../ranger/entity/XXRMSServiceResource.java | 397 ++--- .../org/apache/ranger/entity/XXResource.java | 1367 ++++++++------- .../apache/ranger/entity/XXResourceDef.java | 1520 ++++++++--------- .../java/org/apache/ranger/entity/XXRole.java | 31 +- .../org/apache/ranger/entity/XXRoleBase.java | 44 +- .../apache/ranger/entity/XXRoleRefGroup.java | 150 +- .../apache/ranger/entity/XXRoleRefRole.java | 151 +- .../apache/ranger/entity/XXRoleRefUser.java | 148 +- .../apache/ranger/entity/XXSecurityZone.java | 23 +- .../ranger/entity/XXSecurityZoneBase.java | 48 +- .../ranger/entity/XXSecurityZoneRefGroup.java | 320 ++-- .../entity/XXSecurityZoneRefResource.java | 263 ++- .../ranger/entity/XXSecurityZoneRefRole.java | 259 ++- .../entity/XXSecurityZoneRefService.java | 264 ++- .../entity/XXSecurityZoneRefTagService.java | 117 +- .../ranger/entity/XXSecurityZoneRefUser.java | 316 ++-- .../org/apache/ranger/entity/XXService.java | 90 +- .../apache/ranger/entity/XXServiceBase.java | 748 ++++---- .../ranger/entity/XXServiceConfigDef.java | 1130 ++++++------ .../ranger/entity/XXServiceConfigMap.java | 347 ++-- .../apache/ranger/entity/XXServiceDef.java | 111 +- .../ranger/entity/XXServiceDefBase.java | 736 ++++---- .../entity/XXServiceDefWithAssignedId.java | 77 +- .../ranger/entity/XXServiceResource.java | 435 +++-- .../entity/XXServiceResourceElement.java | 333 ++-- .../entity/XXServiceResourceElementValue.java | 289 ++-- .../ranger/entity/XXServiceVersionInfo.java | 436 ++--- .../entity/XXServiceWithAssignedId.java | 81 +- .../java/org/apache/ranger/entity/XXTag.java | 367 ++-- .../apache/ranger/entity/XXTagAttribute.java | 289 ++-- .../ranger/entity/XXTagAttributeDef.java | 287 ++-- .../apache/ranger/entity/XXTagChangeLog.java | 109 +- .../org/apache/ranger/entity/XXTagDef.java | 404 ++--- .../ranger/entity/XXTagResourceMap.java | 289 ++-- .../org/apache/ranger/entity/XXTrxLog.java | 1001 +++++------ .../org/apache/ranger/entity/XXTrxLogV2.java | 149 +- .../ranger/entity/XXUgsyncAuditInfo.java | 420 +++-- .../java/org/apache/ranger/entity/XXUser.java | 556 +++--- .../ranger/entity/XXUserPermission.java | 254 ++- .../ranger/entity/view/VXXPrincipal.java | 355 ++-- .../metrics/RangerAdminMetricsWrapper.java | 2 +- 103 files changed, 18158 insertions(+), 19161 deletions(-) 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 index 0b0c1e4fa8..84ad79a759 100644 --- a/security-admin/src/main/java/org/apache/ranger/entity/XXAccessAudit.java +++ b/security-admin/src/main/java/org/apache/ranger/entity/XXAccessAudit.java @@ -17,94 +17,109 @@ * under the License. */ - package org.apache.ranger.entity; +package org.apache.ranger.entity; /** * Access Audit - * */ import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Table; +import java.util.Objects; + @Entity -@Table(name="xa_access_audit") +@Table(name = "xa_access_audit") public class XXAccessAudit extends XXAccessAuditBase implements java.io.Serializable { - private static final long serialVersionUID = 1L; - - @Column(name="SEQ_NUM") - protected long sequenceNumber; - - @Column(name="EVENT_COUNT") - protected long eventCount; - - //event duration in ms - @Column(name="EVENT_DUR_MS") - protected long eventDuration; - - public long getSequenceNumber() { - return sequenceNumber; - } - public void setSequenceNumber(long sequenceNumber) { - this.sequenceNumber = sequenceNumber; - } - public long getEventCount() { - return eventCount; - } - public void setEventCount(long eventCount) { - this.eventCount = eventCount; - } - public long getEventDuration() { - return eventDuration; - } - public void setEventDuration(long eventDuration) { - this.eventDuration = eventDuration; - } - - @Column(name="tags") - protected String tags; - - /** - * @return the tags - */ - public String getTags() { - return tags; - } - /** - * @param tags the tags to set - */ - public void setTags(String tags) { - this.tags = tags; - } - /** - * This return the bean content in string format - * @return formatedStr - */ - @Override - public String toString( ) { - String str = super.toString(); - str += "sequenceNumber={" + sequenceNumber + "}"; - str += "eventCount={" + eventCount + "}"; - str += "eventDuration={" + eventDuration + "}"; - str += "tags={" + tags + "}"; - 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.tags == null && other.tags != null) || (this.tags != null && !this.tags.equals(other.tags))) { - return false; - } - return true; - } + private static final long serialVersionUID = 1L; + + @Column(name = "SEQ_NUM") + protected long sequenceNumber; + + @Column(name = "EVENT_COUNT") + protected long eventCount; + + //event duration in ms + @Column(name = "EVENT_DUR_MS") + protected long eventDuration; + + @Column(name = "tags") + protected String tags; + + public long getSequenceNumber() { + return sequenceNumber; + } + + public void setSequenceNumber(long sequenceNumber) { + this.sequenceNumber = sequenceNumber; + } + + public long getEventCount() { + return eventCount; + } + + public void setEventCount(long eventCount) { + this.eventCount = eventCount; + } + + public long getEventDuration() { + return eventDuration; + } + + public void setEventDuration(long eventDuration) { + this.eventDuration = eventDuration; + } + + /** + * @return the tags + */ + public String getTags() { + return tags; + } + + /** + * @param tags the tags to set + */ + public void setTags(String tags) { + this.tags = tags; + } + + @Override + public int hashCode() { + return super.hashCode(); + } + + /** + * Checks for all attributes except referenced db objects + * + * @return true if all attributes match + */ + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } else if (!super.equals(obj)) { + return false; + } + + XXAccessAudit other = (XXAccessAudit) obj; + + return Objects.equals(tags, other.tags); + } + /** + * This return the bean content in string format + * + * @return formatedStr + */ + @Override + public String toString() { + String str = super.toString(); + str += "sequenceNumber={" + sequenceNumber + "}"; + str += "eventCount={" + eventCount + "}"; + str += "eventDuration={" + eventDuration + "}"; + str += "tags={" + tags + "}"; + return str; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/entity/XXAccessAuditBase.java b/security-admin/src/main/java/org/apache/ranger/entity/XXAccessAuditBase.java index c00a69da09..bbffa5273d 100644 --- a/security-admin/src/main/java/org/apache/ranger/entity/XXAccessAuditBase.java +++ b/security-admin/src/main/java/org/apache/ranger/entity/XXAccessAuditBase.java @@ -17,14 +17,15 @@ * under the License. */ - package org.apache.ranger.entity; +package org.apache.ranger.entity; /** * Access Audit - * */ -import java.util.Date; +import org.apache.ranger.common.AppConstants; +import org.apache.ranger.common.DateUtil; +import org.apache.ranger.common.RangerConstants; import javax.persistence.Column; import javax.persistence.GeneratedValue; @@ -35,623 +36,624 @@ import javax.persistence.Temporal; import javax.persistence.TemporalType; -import org.apache.ranger.common.AppConstants; -import org.apache.ranger.common.DateUtil; -import org.apache.ranger.common.RangerConstants; +import java.util.Date; +import java.util.Objects; @MappedSuperclass public class XXAccessAuditBase 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 - *
    - *
  • This attribute is of type enum CommonEnums::AssetType - *
- * - */ - @Column(name="AUDIT_TYPE" , nullable=false ) - protected int auditType = AppConstants.ASSET_UNKNOWN; - - /** - * Access Result - *
    - *
  • This attribute is of type enum CommonEnums::AccessResult - *
- * - */ - @Column(name="ACCESS_RESULT" ) - protected int accessResult = RangerConstants.ACCESS_RESULT_DENIED; - - /** - * Access Type - *
    - *
  • The maximum length for this attribute is 255. - *
- * - */ - @Column(name="ACCESS_TYPE" , length=255) - protected String accessType; - - /** - * Acl Enforcer - *
    - *
  • The maximum length for this attribute is 255. - *
- * - */ - @Column(name="ACL_ENFORCER" , length=255) - protected String aclEnforcer; - - /** - * Agent Id - *
    - *
  • The maximum length for this attribute is 255. - *
- * - */ - @Column(name="AGENT_ID" , length=255) - protected String agentId; - - /** - * Client Ip - *
    - *
  • The maximum length for this attribute is 255. - *
- * - */ - @Column(name="CLIENT_IP" , length=255) - protected String clientIP; - - /** - * Client Type - *
    - *
  • The maximum length for this attribute is 255. - *
- * - */ - @Column(name="CLIENT_TYPE" , length=255) - protected String clientType; - - /** - * Policy Id - *
    - *
- * - */ - @Column(name="POLICY_ID" ) - protected long policyId; - - /** - * Repository Name - *
    - *
  • The maximum length for this attribute is 255. - *
- * - */ - @Column(name="REPO_NAME" , length=255) - protected String repoName; - - /** - * Repository Type - *
    - *
- * - */ - @Column(name="REPO_TYPE" ) - protected int repoType; - - /** - * Reason of result - *
    - *
  • The maximum length for this attribute is 255. - *
- * - */ - @Column(name="RESULT_REASON" , length=255) - protected String resultReason; - - /** - * Session Id - *
    - *
  • The maximum length for this attribute is 255. - *
- * - */ - @Column(name="SESSION_ID" , length=255) - protected String sessionId; - - /** - * Event Time - *
    - *
- * - */ - @Temporal(TemporalType.TIMESTAMP) - @Column(name="EVENT_TIME" ) - protected Date eventTime = DateUtil.getUTCDate(); - - /** - * Requesting User - *
    - *
  • The maximum length for this attribute is 255. - *
- * - */ - @Column(name="REQUEST_USER" , length=255) - protected String requestUser; - - /** - * Action - *
    - *
  • The maximum length for this attribute is 2000. - *
- * - */ - @Column(name="ACTION" , length=2000) - protected String action; - - /** - * Requesting Data - *
    - *
  • The maximum length for this attribute is 2000. - *
- * - */ - @Column(name="REQUEST_DATA" , length=2000) - protected String requestData; - - /** - * Resource Path - *
    - *
  • The maximum length for this attribute is 2000. - *
- * - */ - @Column(name="RESOURCE_PATH" , length=2000) - protected String resourcePath; - - /** - * Resource Type - *
    - *
  • The maximum length for this attribute is 255. - *
- * - */ - @Column(name="RESOURCE_TYPE" , length=255) - protected String resourceType; - - - - /** - * Default constructor. This will set all the attributes to default value. - */ - public XXAccessAuditBase ( ) { - auditType = AppConstants.ASSET_UNKNOWN; - accessResult = RangerConstants.ACCESS_RESULT_DENIED; - } - - @Override - public int getMyClassType( ) { - return AppConstants.CLASS_TYPE_XA_ACCESS_AUDIT; - } - - /** - * This method sets the value to the member attribute auditType. - * You cannot set null to the attribute. - * @param auditType Value to set member attribute auditType - */ - public void setAuditType( int auditType ) { - this.auditType = auditType; - } - - /** - * Returns the value for the member attribute auditType - * @return int - value of member attribute auditType. - */ - public int getAuditType( ) { - return this.auditType; - } - - /** - * This method sets the value to the member attribute accessResult. - * You cannot set null to the attribute. - * @param accessResult Value to set member attribute accessResult - */ - public void setAccessResult( int accessResult ) { - this.accessResult = accessResult; - } - - /** - * Returns the value for the member attribute accessResult - * @return int - value of member attribute accessResult. - */ - public int getAccessResult( ) { - return this.accessResult; - } - - /** - * This method sets the value to the member attribute accessType. - * You cannot set null to the attribute. - * @param accessType Value to set member attribute accessType - */ - public void setAccessType( String accessType ) { - this.accessType = accessType; - } - - /** - * Returns the value for the member attribute accessType - * @return String - value of member attribute accessType. - */ - public String getAccessType( ) { - return this.accessType; - } - - /** - * This method sets the value to the member attribute aclEnforcer. - * You cannot set null to the attribute. - * @param aclEnforcer Value to set member attribute aclEnforcer - */ - public void setAclEnforcer( String aclEnforcer ) { - this.aclEnforcer = aclEnforcer; - } - - /** - * Returns the value for the member attribute aclEnforcer - * @return String - value of member attribute aclEnforcer. - */ - public String getAclEnforcer( ) { - return this.aclEnforcer; - } - - /** - * This method sets the value to the member attribute agentId. - * You cannot set null to the attribute. - * @param agentId Value to set member attribute agentId - */ - public void setAgentId( String agentId ) { - this.agentId = agentId; - } - - /** - * Returns the value for the member attribute agentId - * @return String - value of member attribute agentId. - */ - public String getAgentId( ) { - return this.agentId; - } - - /** - * This method sets the value to the member attribute clientIP. - * You cannot set null to the attribute. - * @param clientIP Value to set member attribute clientIP - */ - public void setClientIP( String clientIP ) { - this.clientIP = clientIP; - } - - /** - * Returns the value for the member attribute clientIP - * @return String - value of member attribute clientIP. - */ - public String getClientIP( ) { - return this.clientIP; - } - - /** - * This method sets the value to the member attribute clientType. - * You cannot set null to the attribute. - * @param clientType Value to set member attribute clientType - */ - public void setClientType( String clientType ) { - this.clientType = clientType; - } - - /** - * Returns the value for the member attribute clientType - * @return String - value of member attribute clientType. - */ - public String getClientType( ) { - return this.clientType; - } - - /** - * This method sets the value to the member attribute policyId. - * You cannot set null to the attribute. - * @param policyId Value to set member attribute policyId - */ - public void setPolicyId( long policyId ) { - this.policyId = policyId; - } - - /** - * Returns the value for the member attribute policyId - * @return long - value of member attribute policyId. - */ - public long getPolicyId( ) { - return this.policyId; - } - - /** - * This method sets the value to the member attribute repoName. - * You cannot set null to the attribute. - * @param repoName Value to set member attribute repoName - */ - public void setRepoName( String repoName ) { - this.repoName = repoName; - } - - /** - * Returns the value for the member attribute repoName - * @return String - value of member attribute repoName. - */ - public String getRepoName( ) { - return this.repoName; - } - - /** - * This method sets the value to the member attribute repoType. - * You cannot set null to the attribute. - * @param repoType Value to set member attribute repoType - */ - public void setRepoType( int repoType ) { - this.repoType = repoType; - } - - /** - * Returns the value for the member attribute repoType - * @return int - value of member attribute repoType. - */ - public int getRepoType( ) { - return this.repoType; - } - - /** - * This method sets the value to the member attribute resultReason. - * You cannot set null to the attribute. - * @param resultReason Value to set member attribute resultReason - */ - public void setResultReason( String resultReason ) { - this.resultReason = resultReason; - } - - /** - * Returns the value for the member attribute resultReason - * @return String - value of member attribute resultReason. - */ - public String getResultReason( ) { - return this.resultReason; - } - - /** - * This method sets the value to the member attribute sessionId. - * You cannot set null to the attribute. - * @param sessionId Value to set member attribute sessionId - */ - public void setSessionId( String sessionId ) { - this.sessionId = sessionId; - } - - /** - * Returns the value for the member attribute sessionId - * @return String - value of member attribute sessionId. - */ - public String getSessionId( ) { - return this.sessionId; - } - - /** - * This method sets the value to the member attribute eventTime. - * You cannot set null to the attribute. - * @param eventTime Value to set member attribute eventTime - */ - public void setEventTime( Date eventTime ) { - this.eventTime = eventTime; - } - - /** - * Returns the value for the member attribute eventTime - * @return Date - value of member attribute eventTime. - */ - public Date getEventTime( ) { - return this.eventTime; - } - - /** - * This method sets the value to the member attribute requestUser. - * You cannot set null to the attribute. - * @param requestUser Value to set member attribute requestUser - */ - public void setRequestUser( String requestUser ) { - this.requestUser = requestUser; - } - - /** - * Returns the value for the member attribute requestUser - * @return String - value of member attribute requestUser. - */ - public String getRequestUser( ) { - return this.requestUser; - } - - /** - * This method sets the value to the member attribute action. - * You cannot set null to the attribute. - * @param action Value to set member attribute action - */ - public void setAction( String action ) { - this.action = action; - } - - /** - * Returns the value for the member attribute action - * @return String - value of member attribute action. - */ - public String getAction( ) { - return this.action; - } - - /** - * This method sets the value to the member attribute requestData. - * You cannot set null to the attribute. - * @param requestData Value to set member attribute requestData - */ - public void setRequestData( String requestData ) { - this.requestData = requestData; - } - - /** - * Returns the value for the member attribute requestData - * @return String - value of member attribute requestData. - */ - public String getRequestData( ) { - return this.requestData; - } - - /** - * This method sets the value to the member attribute resourcePath. - * You cannot set null to the attribute. - * @param resourcePath Value to set member attribute resourcePath - */ - public void setResourcePath( String resourcePath ) { - this.resourcePath = resourcePath; - } - - /** - * Returns the value for the member attribute resourcePath - * @return String - value of member attribute resourcePath. - */ - public String getResourcePath( ) { - return this.resourcePath; - } - - /** - * This method sets the value to the member attribute resourceType. - * You cannot set null to the attribute. - * @param resourceType Value to set member attribute resourceType - */ - public void setResourceType( String resourceType ) { - this.resourceType = resourceType; - } - - /** - * Returns the value for the member attribute resourceType - * @return String - value of member attribute resourceType. - */ - 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 += "id={" + id + "} "; - 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 += "eventTime={" + eventTime + "} "; - str += "requestUser={" + requestUser + "} "; - str += "action={" + action + "} "; - str += "requestData={" + requestData + "} "; - str += "resourcePath={" + resourcePath + "} "; - str += "resourceType={" + resourceType + "} "; - 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; - } - XXAccessAuditBase other = (XXAccessAuditBase) 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( "auditType".equals(fieldName) ) { - return "CommonEnums.AssetType"; - } - if( "accessResult".equals(fieldName) ) { - return "CommonEnums.AccessResult"; - } - return null; - } - + 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; + + /** + * Repository Type + *
    + *
  • This attribute is of type enum CommonEnums::AssetType + *
+ */ + @Column(name = "AUDIT_TYPE", nullable = false) + protected int auditType = AppConstants.ASSET_UNKNOWN; + + /** + * Access Result + *
    + *
  • This attribute is of type enum CommonEnums::AccessResult + *
+ */ + @Column(name = "ACCESS_RESULT") + protected int accessResult = RangerConstants.ACCESS_RESULT_DENIED; + + /** + * Access Type + *
    + *
  • The maximum length for this attribute is 255. + *
+ */ + @Column(name = "ACCESS_TYPE", length = 255) + protected String accessType; + + /** + * Acl Enforcer + *
    + *
  • The maximum length for this attribute is 255. + *
+ */ + @Column(name = "ACL_ENFORCER", length = 255) + protected String aclEnforcer; + + /** + * Agent Id + *
    + *
  • The maximum length for this attribute is 255. + *
+ */ + @Column(name = "AGENT_ID", length = 255) + protected String agentId; + + /** + * Client Ip + *
    + *
  • The maximum length for this attribute is 255. + *
+ */ + @Column(name = "CLIENT_IP", length = 255) + protected String clientIP; + + /** + * Client Type + *
    + *
  • The maximum length for this attribute is 255. + *
+ */ + @Column(name = "CLIENT_TYPE", length = 255) + protected String clientType; + + /** + * Policy Id + *
    + *
+ */ + @Column(name = "POLICY_ID") + protected long policyId; + + /** + * Repository Name + *
    + *
  • The maximum length for this attribute is 255. + *
+ */ + @Column(name = "REPO_NAME", length = 255) + protected String repoName; + + /** + * Repository Type + *
    + *
+ */ + @Column(name = "REPO_TYPE") + protected int repoType; + + /** + * Reason of result + *
    + *
  • The maximum length for this attribute is 255. + *
+ */ + @Column(name = "RESULT_REASON", length = 255) + protected String resultReason; + + /** + * Session Id + *
    + *
  • The maximum length for this attribute is 255. + *
+ */ + @Column(name = "SESSION_ID", length = 255) + protected String sessionId; + + /** + * Event Time + *
    + *
+ */ + @Temporal(TemporalType.TIMESTAMP) + @Column(name = "EVENT_TIME") + protected Date eventTime = DateUtil.getUTCDate(); + + /** + * Requesting User + *
    + *
  • The maximum length for this attribute is 255. + *
+ */ + @Column(name = "REQUEST_USER", length = 255) + protected String requestUser; + + /** + * Action + *
    + *
  • The maximum length for this attribute is 2000. + *
+ */ + @Column(name = "ACTION", length = 2000) + protected String action; + + /** + * Requesting Data + *
    + *
  • The maximum length for this attribute is 2000. + *
+ */ + @Column(name = "REQUEST_DATA", length = 2000) + protected String requestData; + + /** + * Resource Path + *
    + *
  • The maximum length for this attribute is 2000. + *
+ */ + @Column(name = "RESOURCE_PATH", length = 2000) + protected String resourcePath; + + /** + * Resource Type + *
    + *
  • The maximum length for this attribute is 255. + *
+ */ + @Column(name = "RESOURCE_TYPE", length = 255) + protected String resourceType; + + /** + * Default constructor. This will set all the attributes to default value. + */ + public XXAccessAuditBase() { + auditType = AppConstants.ASSET_UNKNOWN; + accessResult = RangerConstants.ACCESS_RESULT_DENIED; + } + + public static String getEnumName(String fieldName) { + if ("auditType".equals(fieldName)) { + return "CommonEnums.AssetType"; + } + + if ("accessResult".equals(fieldName)) { + return "CommonEnums.AccessResult"; + } + + return null; + } + + @Override + public int getMyClassType() { + return AppConstants.CLASS_TYPE_XA_ACCESS_AUDIT; + } + + @Override + public Long getId() { + return id; + } + + @Override + public void setId(Long id) { + this.id = id; + } + + @Override + public int hashCode() { + return super.hashCode(); + } + + /** + * Checks for all attributes except referenced db objects + * + * @return true if all attributes match + */ + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } else if (!super.equals(obj)) { + return false; + } + + XXAccessAuditBase other = (XXAccessAuditBase) obj; + + return Objects.equals(auditType, other.auditType) && + Objects.equals(accessResult, other.accessResult) && + Objects.equals(accessType, other.accessType) && + Objects.equals(aclEnforcer, other.aclEnforcer) && + Objects.equals(agentId, other.agentId) && + Objects.equals(clientIP, other.clientIP) && + Objects.equals(clientType, other.clientType) && + Objects.equals(policyId, other.policyId) && + Objects.equals(repoName, other.repoName) && + Objects.equals(resultReason, other.resultReason) && + Objects.equals(sessionId, other.sessionId) && + Objects.equals(eventTime, other.eventTime) && + Objects.equals(requestUser, other.requestUser) && + Objects.equals(action, other.action) && + Objects.equals(requestData, other.requestData) && + Objects.equals(resourcePath, other.resourcePath) && + Objects.equals(resourceType, other.resourceType); + } + + /** + * This return the bean content in string format + * + * @return formatedStr + */ + @Override + public String toString() { + String str = "XXAccessAudit="; + + str += super.toString(); + str += "id={" + id + "} "; + 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 += "eventTime={" + eventTime + "} "; + str += "requestUser={" + requestUser + "} "; + str += "action={" + action + "} "; + str += "requestData={" + requestData + "} "; + str += "resourcePath={" + resourcePath + "} "; + str += "resourceType={" + resourceType + "} "; + + return str; + } + + /** + * Returns the value for the member attribute auditType + * + * @return int - value of member attribute auditType. + */ + public int getAuditType() { + return this.auditType; + } + + /** + * This method sets the value to the member attribute auditType. + * You cannot set null to the attribute. + * + * @param auditType Value to set member attribute auditType + */ + public void setAuditType(int auditType) { + this.auditType = auditType; + } + + /** + * Returns the value for the member attribute accessResult + * + * @return int - value of member attribute accessResult. + */ + public int getAccessResult() { + return this.accessResult; + } + + /** + * This method sets the value to the member attribute accessResult. + * You cannot set null to the attribute. + * + * @param accessResult Value to set member attribute accessResult + */ + public void setAccessResult(int accessResult) { + this.accessResult = accessResult; + } + + /** + * Returns the value for the member attribute accessType + * + * @return String - value of member attribute accessType. + */ + public String getAccessType() { + return this.accessType; + } + + /** + * This method sets the value to the member attribute accessType. + * You cannot set null to the attribute. + * + * @param accessType Value to set member attribute accessType + */ + public void setAccessType(String accessType) { + this.accessType = accessType; + } + + /** + * Returns the value for the member attribute aclEnforcer + * + * @return String - value of member attribute aclEnforcer. + */ + public String getAclEnforcer() { + return this.aclEnforcer; + } + + /** + * This method sets the value to the member attribute aclEnforcer. + * You cannot set null to the attribute. + * + * @param aclEnforcer Value to set member attribute aclEnforcer + */ + public void setAclEnforcer(String aclEnforcer) { + this.aclEnforcer = aclEnforcer; + } + + /** + * Returns the value for the member attribute agentId + * + * @return String - value of member attribute agentId. + */ + public String getAgentId() { + return this.agentId; + } + + /** + * This method sets the value to the member attribute agentId. + * You cannot set null to the attribute. + * + * @param agentId Value to set member attribute agentId + */ + public void setAgentId(String agentId) { + this.agentId = agentId; + } + + /** + * Returns the value for the member attribute clientIP + * + * @return String - value of member attribute clientIP. + */ + public String getClientIP() { + return this.clientIP; + } + + /** + * This method sets the value to the member attribute clientIP. + * You cannot set null to the attribute. + * + * @param clientIP Value to set member attribute clientIP + */ + public void setClientIP(String clientIP) { + this.clientIP = clientIP; + } + + /** + * Returns the value for the member attribute clientType + * + * @return String - value of member attribute clientType. + */ + public String getClientType() { + return this.clientType; + } + + /** + * This method sets the value to the member attribute clientType. + * You cannot set null to the attribute. + * + * @param clientType Value to set member attribute clientType + */ + public void setClientType(String clientType) { + this.clientType = clientType; + } + + /** + * Returns the value for the member attribute policyId + * + * @return long - value of member attribute policyId. + */ + public long getPolicyId() { + return this.policyId; + } + + /** + * This method sets the value to the member attribute policyId. + * You cannot set null to the attribute. + * + * @param policyId Value to set member attribute policyId + */ + public void setPolicyId(long policyId) { + this.policyId = policyId; + } + + /** + * Returns the value for the member attribute repoName + * + * @return String - value of member attribute repoName. + */ + public String getRepoName() { + return this.repoName; + } + + /** + * This method sets the value to the member attribute repoName. + * You cannot set null to the attribute. + * + * @param repoName Value to set member attribute repoName + */ + public void setRepoName(String repoName) { + this.repoName = repoName; + } + + /** + * Returns the value for the member attribute repoType + * + * @return int - value of member attribute repoType. + */ + public int getRepoType() { + return this.repoType; + } + + /** + * This method sets the value to the member attribute repoType. + * You cannot set null to the attribute. + * + * @param repoType Value to set member attribute repoType + */ + public void setRepoType(int repoType) { + this.repoType = repoType; + } + + /** + * Returns the value for the member attribute resultReason + * + * @return String - value of member attribute resultReason. + */ + public String getResultReason() { + return this.resultReason; + } + + /** + * This method sets the value to the member attribute resultReason. + * You cannot set null to the attribute. + * + * @param resultReason Value to set member attribute resultReason + */ + public void setResultReason(String resultReason) { + this.resultReason = resultReason; + } + + /** + * Returns the value for the member attribute sessionId + * + * @return String - value of member attribute sessionId. + */ + public String getSessionId() { + return this.sessionId; + } + + /** + * This method sets the value to the member attribute sessionId. + * You cannot set null to the attribute. + * + * @param sessionId Value to set member attribute sessionId + */ + public void setSessionId(String sessionId) { + this.sessionId = sessionId; + } + + /** + * Returns the value for the member attribute eventTime + * + * @return Date - value of member attribute eventTime. + */ + public Date getEventTime() { + return this.eventTime; + } + + /** + * This method sets the value to the member attribute eventTime. + * You cannot set null to the attribute. + * + * @param eventTime Value to set member attribute eventTime + */ + public void setEventTime(Date eventTime) { + this.eventTime = eventTime; + } + + /** + * Returns the value for the member attribute requestUser + * + * @return String - value of member attribute requestUser. + */ + public String getRequestUser() { + return this.requestUser; + } + + /** + * This method sets the value to the member attribute requestUser. + * You cannot set null to the attribute. + * + * @param requestUser Value to set member attribute requestUser + */ + public void setRequestUser(String requestUser) { + this.requestUser = requestUser; + } + + /** + * Returns the value for the member attribute action + * + * @return String - value of member attribute action. + */ + public String getAction() { + return this.action; + } + + /** + * This method sets the value to the member attribute action. + * You cannot set null to the attribute. + * + * @param action Value to set member attribute action + */ + public void setAction(String action) { + this.action = action; + } + + /** + * Returns the value for the member attribute requestData + * + * @return String - value of member attribute requestData. + */ + public String getRequestData() { + return this.requestData; + } + + /** + * This method sets the value to the member attribute requestData. + * You cannot set null to the attribute. + * + * @param requestData Value to set member attribute requestData + */ + public void setRequestData(String requestData) { + this.requestData = requestData; + } + + /** + * Returns the value for the member attribute resourcePath + * + * @return String - value of member attribute resourcePath. + */ + public String getResourcePath() { + return this.resourcePath; + } + + /** + * This method sets the value to the member attribute resourcePath. + * You cannot set null to the attribute. + * + * @param resourcePath Value to set member attribute resourcePath + */ + public void setResourcePath(String resourcePath) { + this.resourcePath = resourcePath; + } + + /** + * Returns the value for the member attribute resourceType + * + * @return String - value of member attribute resourceType. + */ + public String getResourceType() { + return this.resourceType; + } + + /** + * This method sets the value to the member attribute resourceType. + * You cannot set null to the attribute. + * + * @param resourceType Value to set member attribute resourceType + */ + public void setResourceType(String resourceType) { + this.resourceType = resourceType; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/entity/XXAccessAuditV4.java b/security-admin/src/main/java/org/apache/ranger/entity/XXAccessAuditV4.java index d6aee1c0cf..9728f894f6 100644 --- a/security-admin/src/main/java/org/apache/ranger/entity/XXAccessAuditV4.java +++ b/security-admin/src/main/java/org/apache/ranger/entity/XXAccessAuditV4.java @@ -19,19 +19,18 @@ package org.apache.ranger.entity; +import org.apache.ranger.common.AppConstants; + import javax.persistence.Entity; import javax.persistence.Table; -import org.apache.ranger.common.AppConstants; - @Entity @Table(name = "xa_access_audit") public class XXAccessAuditV4 extends XXAccessAuditBase implements java.io.Serializable { - private static final long serialVersionUID = 1L; - - @Override - public int getMyClassType() { - return AppConstants.CLASS_TYPE_XA_ACCESS_AUDIT_V4; - } + private static final long serialVersionUID = 1L; + @Override + public int getMyClassType() { + return AppConstants.CLASS_TYPE_XA_ACCESS_AUDIT_V4; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/entity/XXAccessAuditV5.java b/security-admin/src/main/java/org/apache/ranger/entity/XXAccessAuditV5.java index b82bc05158..c8a6b42396 100644 --- a/security-admin/src/main/java/org/apache/ranger/entity/XXAccessAuditV5.java +++ b/security-admin/src/main/java/org/apache/ranger/entity/XXAccessAuditV5.java @@ -17,68 +17,75 @@ * under the License. */ - package org.apache.ranger.entity; +package org.apache.ranger.entity; /** * Access Audit - * */ +import org.apache.ranger.common.AppConstants; + import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Table; -import org.apache.ranger.common.AppConstants; - @Entity @Table(name = "xa_access_audit") public class XXAccessAuditV5 extends XXAccessAuditBase implements java.io.Serializable { - private static final long serialVersionUID = 1L; - - @Override - public int getMyClassType() { - return AppConstants.CLASS_TYPE_XA_ACCESS_AUDIT_V5; - } - - @Column(name="SEQ_NUM") - protected long sequenceNumber; - - @Column(name="EVENT_COUNT") - protected long eventCount; - - //event duration in ms - @Column(name="EVENT_DUR_MS") - protected long eventDuration; - - public long getSequenceNumber() { - return sequenceNumber; - } - public void setSequenceNumber(long sequenceNumber) { - this.sequenceNumber = sequenceNumber; - } - public long getEventCount() { - return eventCount; - } - public void setEventCount(long eventCount) { - this.eventCount = eventCount; - } - public long getEventDuration() { - return eventDuration; - } - public void setEventDuration(long eventDuration) { - this.eventDuration = eventDuration; - } - - /** - * This return the bean content in string format - * @return formatedStr - */ - @Override - public String toString( ) { - String str = super.toString(); - str += "sequenceNumber={" + sequenceNumber + "}"; - str += "eventCount={" + eventCount + "}"; - str += "eventDuration={" + eventDuration + "}"; - return str; - } + private static final long serialVersionUID = 1L; + + @Column(name = "SEQ_NUM") + protected long sequenceNumber; + + @Column(name = "EVENT_COUNT") + protected long eventCount; + + //event duration in ms + @Column(name = "EVENT_DUR_MS") + protected long eventDuration; + + @Override + public int getMyClassType() { + return AppConstants.CLASS_TYPE_XA_ACCESS_AUDIT_V5; + } + + /** + * This return the bean content in string format + * + * @return formatedStr + */ + @Override + public String toString() { + String str = super.toString(); + + str += "sequenceNumber={" + sequenceNumber + "}"; + str += "eventCount={" + eventCount + "}"; + str += "eventDuration={" + eventDuration + "}"; + + return str; + } + + public long getSequenceNumber() { + return sequenceNumber; + } + + public void setSequenceNumber(long sequenceNumber) { + this.sequenceNumber = sequenceNumber; + } + + public long getEventCount() { + return eventCount; + } + + public void setEventCount(long eventCount) { + this.eventCount = eventCount; + } + + public long getEventDuration() { + return eventDuration; + } + + public void setEventDuration(long eventDuration) { + this.eventDuration = eventDuration; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/entity/XXAccessTypeDef.java b/security-admin/src/main/java/org/apache/ranger/entity/XXAccessTypeDef.java index 846479d89d..7b2b12e9a3 100644 --- a/security-admin/src/main/java/org/apache/ranger/entity/XXAccessTypeDef.java +++ b/security-admin/src/main/java/org/apache/ranger/entity/XXAccessTypeDef.java @@ -18,304 +18,303 @@ */ package org.apache.ranger.entity; -import javax.persistence.*; +import javax.persistence.Cacheable; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.SequenceGenerator; +import javax.persistence.Table; + import java.util.Objects; @Entity @Cacheable @Table(name = "x_access_type_def") public class XXAccessTypeDef extends XXDBBase implements java.io.Serializable { - private static final long serialVersionUID = 1L; - /** - * id of the XXAccessTypeDef - *
    - *
- * - */ - @Id - @SequenceGenerator(name = "x_access_type_def_SEQ", sequenceName = "x_access_type_def_SEQ", allocationSize = 1) - @GeneratedValue(strategy = GenerationType.AUTO, generator = "x_access_type_def_SEQ") - @Column(name = "id") - protected Long id; - - /** - * defId of the XXAccessTypeDef - *
    - *
- * - */ - @Column(name = "def_id") - protected Long defId; - - /** - * itemId of the XXAccessTypeDef - *
    - *
- * - */ - @Column(name = "item_id") - protected Long itemId; - - /** - * name of the XXAccessTypeDef - *
    - *
- * - */ - @Column(name = "name") - protected String name; - - /** - * label of the XXAccessTypeDef - *
    - *
- * - */ - @Column(name = "label") - protected String label; - - /** - * rbKeyLabel of the XXAccessTypeDef - *
    - *
- * - */ - @Column(name = "rb_key_label") - protected String rbKeyLabel; - - /** - * category of the XXAccessTypeDef - */ - @Column(name = "category") - protected Short category; - - /** - * order of the XXAccessTypeDef - *
    - *
- * - */ - @Column(name = "sort_order") - protected Integer order; - - /** - * dataMaskOptions of the XXAccessTypeDef - *
    - *
- * - */ - @Column(name = "datamask_options") - protected String dataMaskOptions; - - /** - * rowFilterOptions of the XXAccessTypeDef - *
    - *
- * - */ - @Column(name = "rowfilter_options") - protected String rowFilterOptions; - - /** - * This method sets the value to the member attribute id . You - * cannot set null to the attribute. - * - * @param id - * Value to set member attribute id - */ - public void setId(Long id) { - this.id = id; - } - - /** - * Returns the value for the member attribute id - * - * @return Date - value of member attribute id . - */ - public Long getId() { - return this.id; - } - - /** - * This method sets the value to the member attribute defId . You - * cannot set null to the attribute. - * - * @param defId - * Value to set member attribute defId - */ - public void setDefid(Long defId) { - this.defId = defId; - } - - /** - * Returns the value for the member attribute defId - * - * @return Date - value of member attribute defId . - */ - public Long getDefid() { - return this.defId; - } - - /** - * This method sets the value to the member attribute itemId . You - * cannot set null to the attribute. - * - * @param itemId - * Value to set member attribute itemId - */ - public void setItemId(Long itemId) { - this.itemId = itemId; - } - - /** - * Returns the value for the member attribute itemId - * - * @return Long - value of member attribute itemId . - */ - public Long getItemId() { - return this.itemId; - } - - /** - * This method sets the value to the member attribute name . You - * cannot set null to the attribute. - * - * @param name - * Value to set member attribute name - */ - public void setName(String name) { - this.name = name; - } - - /** - * Returns the value for the member attribute name - * - * @return Date - value of member attribute name . - */ - public String getName() { - return this.name; - } - - /** - * This method sets the value to the member attribute label . You - * cannot set null to the attribute. - * - * @param label - * Value to set member attribute label - */ - public void setLabel(String label) { - this.label = label; - } - - /** - * Returns the value for the member attribute label - * - * @return Date - value of member attribute label . - */ - public String getLabel() { - return this.label; - } - - /** - * This method sets the value to the member attribute rbKeyLabel . - * You cannot set null to the attribute. - * - * @param rbKeyLabel - * Value to set member attribute rbKeyLabel - */ - public void setRbkeylabel(String rbKeyLabel) { - this.rbKeyLabel = rbKeyLabel; - } - - /** - * Returns the value for the member attribute rbKeyLabel - * - * @return Date - value of member attribute rbKeyLabel . - */ - public String getRbkeylabel() { - return this.rbKeyLabel; - } - - public Short getCategory() { - return category; - } - - public void setCategory(Short category) { - this.category = category; - } - - /** - * This method sets the value to the member attribute order . You - * cannot set null to the attribute. - * - * @param order - * Value to set member attribute order - */ - public void setOrder(Integer order) { - this.order = order; - } - - /** - * Returns the value for the member attribute order - * - * @return Date - value of member attribute order . - */ - public Integer getOrder() { - return this.order; - } - - public String getDataMaskOptions() { - return dataMaskOptions; - } - - public void setDataMaskOptions(String dataMaskOptions) { - this.dataMaskOptions = dataMaskOptions; - } - - public String getRowFilterOptions() { return rowFilterOptions; } - - public void setRowFilterOptions(String rowFilterOptions) { this.rowFilterOptions = rowFilterOptions; } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#equals(java.lang.Object) - */ - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } else if (getClass() != obj.getClass()) { - return false; - } else if (!super.equals(obj)) { - return false; - } - - XXAccessTypeDef other = (XXAccessTypeDef) obj; - - return Objects.equals(defId, other.defId) && - Objects.equals(itemId, other.itemId) && - Objects.equals(id, other.id) && - Objects.equals(name, other.name) && - Objects.equals(label, other.label) && - Objects.equals(rbKeyLabel, other.rbKeyLabel) && - Objects.equals(category, other.category) && - Objects.equals(dataMaskOptions, other.dataMaskOptions) && - Objects.equals(rowFilterOptions, other.rowFilterOptions) && - Objects.equals(order, other.order); - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#toString() - */ - @Override - public String toString() { - return "XXAccessTypeDef [" + super.toString() + " id=" + id - + ", defId=" + defId + ", itemId=" + itemId + ", name=" + name + ", label=" + label - + ", rbKeyLabel=" + rbKeyLabel + ", category=" + category + ", dataMaskOptions=" + dataMaskOptions - + ", rowFilterOptions=" + rowFilterOptions + ", order=" + order + "]"; - } - + private static final long serialVersionUID = 1L; + + /** + * id of the XXAccessTypeDef + *
    + *
+ */ + @Id + @SequenceGenerator(name = "x_access_type_def_SEQ", sequenceName = "x_access_type_def_SEQ", allocationSize = 1) + @GeneratedValue(strategy = GenerationType.AUTO, generator = "x_access_type_def_SEQ") + @Column(name = "id") + protected Long id; + + /** + * defId of the XXAccessTypeDef + *
    + *
+ */ + @Column(name = "def_id") + protected Long defId; + + /** + * itemId of the XXAccessTypeDef + *
    + *
+ */ + @Column(name = "item_id") + protected Long itemId; + + /** + * name of the XXAccessTypeDef + *
    + *
+ */ + @Column(name = "name") + protected String name; + + /** + * label of the XXAccessTypeDef + *
    + *
+ */ + @Column(name = "label") + protected String label; + + /** + * rbKeyLabel of the XXAccessTypeDef + *
    + *
+ */ + @Column(name = "rb_key_label") + protected String rbKeyLabel; + + /** + * category of the XXAccessTypeDef + */ + @Column(name = "category") + protected Short category; + + /** + * order of the XXAccessTypeDef + *
    + *
+ */ + @Column(name = "sort_order") + protected Integer order; + + /** + * dataMaskOptions of the XXAccessTypeDef + *
    + *
+ */ + @Column(name = "datamask_options") + protected String dataMaskOptions; + + /** + * rowFilterOptions of the XXAccessTypeDef + *
    + *
+ */ + @Column(name = "rowfilter_options") + protected String rowFilterOptions; + + /** + * Returns the value for the member attribute id + * + * @return Date - value of member attribute id . + */ + public Long getId() { + return this.id; + } + + /** + * This method sets the value to the member attribute id . You + * cannot set null to the attribute. + * + * @param id Value to set member attribute id + */ + public void setId(Long id) { + this.id = id; + } + + @Override + public int hashCode() { + return super.hashCode(); + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#equals(java.lang.Object) + */ + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } else if (!super.equals(obj)) { + return false; + } + + XXAccessTypeDef other = (XXAccessTypeDef) obj; + + return Objects.equals(defId, other.defId) && + Objects.equals(itemId, other.itemId) && + Objects.equals(id, other.id) && + Objects.equals(name, other.name) && + Objects.equals(label, other.label) && + Objects.equals(rbKeyLabel, other.rbKeyLabel) && + Objects.equals(category, other.category) && + Objects.equals(dataMaskOptions, other.dataMaskOptions) && + Objects.equals(rowFilterOptions, other.rowFilterOptions) && + Objects.equals(order, other.order); + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + return "XXAccessTypeDef [" + super.toString() + " id=" + id + + ", defId=" + defId + ", itemId=" + itemId + ", name=" + name + ", label=" + label + + ", rbKeyLabel=" + rbKeyLabel + ", category=" + category + ", dataMaskOptions=" + dataMaskOptions + + ", rowFilterOptions=" + rowFilterOptions + ", order=" + order + "]"; + } + + /** + * Returns the value for the member attribute defId + * + * @return Date - value of member attribute defId . + */ + public Long getDefid() { + return this.defId; + } + + /** + * This method sets the value to the member attribute defId . You + * cannot set null to the attribute. + * + * @param defId Value to set member attribute defId + */ + public void setDefid(Long defId) { + this.defId = defId; + } + + /** + * Returns the value for the member attribute itemId + * + * @return Long - value of member attribute itemId . + */ + public Long getItemId() { + return this.itemId; + } + + /** + * This method sets the value to the member attribute itemId . You + * cannot set null to the attribute. + * + * @param itemId Value to set member attribute itemId + */ + public void setItemId(Long itemId) { + this.itemId = itemId; + } + + /** + * Returns the value for the member attribute name + * + * @return Date - value of member attribute name . + */ + public String getName() { + return this.name; + } + + /** + * This method sets the value to the member attribute name . You + * cannot set null to the attribute. + * + * @param name Value to set member attribute name + */ + public void setName(String name) { + this.name = name; + } + + /** + * Returns the value for the member attribute label + * + * @return Date - value of member attribute label . + */ + public String getLabel() { + return this.label; + } + + /** + * This method sets the value to the member attribute label . You + * cannot set null to the attribute. + * + * @param label Value to set member attribute label + */ + public void setLabel(String label) { + this.label = label; + } + + /** + * Returns the value for the member attribute rbKeyLabel + * + * @return Date - value of member attribute rbKeyLabel . + */ + public String getRbkeylabel() { + return this.rbKeyLabel; + } + + /** + * This method sets the value to the member attribute rbKeyLabel . + * You cannot set null to the attribute. + * + * @param rbKeyLabel Value to set member attribute rbKeyLabel + */ + public void setRbkeylabel(String rbKeyLabel) { + this.rbKeyLabel = rbKeyLabel; + } + + public Short getCategory() { + return category; + } + + public void setCategory(Short category) { + this.category = category; + } + + /** + * Returns the value for the member attribute order + * + * @return Date - value of member attribute order . + */ + public Integer getOrder() { + return this.order; + } + + /** + * This method sets the value to the member attribute order . You + * cannot set null to the attribute. + * + * @param order Value to set member attribute order + */ + public void setOrder(Integer order) { + this.order = order; + } + + public String getDataMaskOptions() { + return dataMaskOptions; + } + + public void setDataMaskOptions(String dataMaskOptions) { + this.dataMaskOptions = dataMaskOptions; + } + + public String getRowFilterOptions() { + return rowFilterOptions; + } + + public void setRowFilterOptions(String rowFilterOptions) { + this.rowFilterOptions = rowFilterOptions; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/entity/XXAccessTypeDefGrants.java b/security-admin/src/main/java/org/apache/ranger/entity/XXAccessTypeDefGrants.java index 4024a50576..f531172324 100644 --- a/security-admin/src/main/java/org/apache/ranger/entity/XXAccessTypeDefGrants.java +++ b/security-admin/src/main/java/org/apache/ranger/entity/XXAccessTypeDefGrants.java @@ -18,157 +18,139 @@ */ package org.apache.ranger.entity; -import javax.persistence.*; +import javax.persistence.Cacheable; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.SequenceGenerator; +import javax.persistence.Table; + +import java.util.Objects; @Entity @Cacheable @Table(name = "x_access_type_def_grants") -public class XXAccessTypeDefGrants extends XXDBBase implements - java.io.Serializable { - private static final long serialVersionUID = 1L; - /** - * id of the XXAccessTypeDefGrants - *
    - *
- * - */ - @Id - @SequenceGenerator(name = "x_access_type_def_grants_SEQ", sequenceName = "x_access_type_def_grants_SEQ", allocationSize = 1) - @GeneratedValue(strategy = GenerationType.AUTO, generator = "x_access_type_def_grants_SEQ") - @Column(name = "id") - protected Long id; - - /** - * atdId of the XXAccessTypeDefGrants - *
    - *
- * - */ - @Column(name = "atd_id") - protected Long atdId; - - /** - * impliedGrant of the XXAccessTypeDefGrants - *
    - *
- * - */ - @Column(name = "implied_grant") - protected String impliedGrant; - - /** - * This method sets the value to the member attribute id . You - * cannot set null to the attribute. - * - * @param id - * Value to set member attribute id - */ - public void setId(Long id) { - this.id = id; - } - - /** - * Returns the value for the member attribute id - * - * @return Date - value of member attribute id . - */ - public Long getId() { - return this.id; - } - - /** - * This method sets the value to the member attribute atdId . You - * cannot set null to the attribute. - * - * @param atdId - * Value to set member attribute atdId - */ - public void setAtdId(Long atdId) { - this.atdId = atdId; - } - - /** - * Returns the value for the member attribute atdId - * - * @return Date - value of member attribute atdId . - */ - public Long getAtdId() { - return this.atdId; - } - - /** - * This method sets the value to the member attribute impliedGrant . - * You cannot set null to the attribute. - * - * @param impliedGrant - * Value to set member attribute impliedGrant - */ - public void setImpliedGrant(String impliedGrant) { - this.impliedGrant = impliedGrant; - } - - /** - * Returns the value for the member attribute impliedGrant - * - * @return Date - value of member attribute impliedGrant . - */ - public String getImpliedGrant() { - return this.impliedGrant; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#equals(java.lang.Object) - */ - @Override - public boolean equals(Object obj) { - if (!super.equals(obj)) { - return false; - } - if (this == obj) { - return true; - } - if (!super.equals(obj)) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - XXAccessTypeDefGrants other = (XXAccessTypeDefGrants) obj; - if (atdId == null) { - if (other.atdId != null) { - return false; - } - } else if (!atdId.equals(other.atdId)) { - return false; - } - if (id == null) { - if (other.id != null) { - return false; - } - } else if (!id.equals(other.id)) { - return false; - } - if (impliedGrant == null) { - if (other.impliedGrant != null) { - return false; - } - } else if (!impliedGrant.equals(other.impliedGrant)) { - return false; - } - return true; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#toString() - */ - @Override - public String toString() { - return "XXAccessTypeDefGrants [" + super.toString() + " id=" + id - + ", atdId=" + atdId + ", impliedGrant=" + impliedGrant + "]"; - } +public class XXAccessTypeDefGrants extends XXDBBase implements java.io.Serializable { + private static final long serialVersionUID = 1L; + + /** + * id of the XXAccessTypeDefGrants + *
    + *
+ */ + @Id + @SequenceGenerator(name = "x_access_type_def_grants_SEQ", sequenceName = "x_access_type_def_grants_SEQ", allocationSize = 1) + @GeneratedValue(strategy = GenerationType.AUTO, generator = "x_access_type_def_grants_SEQ") + @Column(name = "id") + protected Long id; + + /** + * atdId of the XXAccessTypeDefGrants + *
    + *
+ */ + @Column(name = "atd_id") + protected Long atdId; + + /** + * impliedGrant of the XXAccessTypeDefGrants + *
    + *
+ */ + @Column(name = "implied_grant") + protected String impliedGrant; + + /** + * Returns the value for the member attribute id + * + * @return Date - value of member attribute id . + */ + public Long getId() { + return this.id; + } + + /** + * This method sets the value to the member attribute id . You + * cannot set null to the attribute. + * + * @param id Value to set member attribute id + */ + public void setId(Long id) { + this.id = id; + } + + @Override + public int hashCode() { + return super.hashCode(); + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#equals(java.lang.Object) + */ + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } else if (!super.equals(obj)) { + return false; + } + + XXAccessTypeDefGrants other = (XXAccessTypeDefGrants) obj; + + return Objects.equals(atdId, other.atdId) && + Objects.equals(id, other.id) && + Objects.equals(impliedGrant, other.impliedGrant); + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + return "XXAccessTypeDefGrants [" + super.toString() + " id=" + id + ", atdId=" + atdId + ", impliedGrant=" + impliedGrant + "]"; + } + + /** + * Returns the value for the member attribute atdId + * + * @return Date - value of member attribute atdId . + */ + public Long getAtdId() { + return this.atdId; + } + + /** + * This method sets the value to the member attribute atdId . You + * cannot set null to the attribute. + * + * @param atdId Value to set member attribute atdId + */ + public void setAtdId(Long atdId) { + this.atdId = atdId; + } + + /** + * Returns the value for the member attribute impliedGrant + * + * @return Date - value of member attribute impliedGrant . + */ + public String getImpliedGrant() { + return this.impliedGrant; + } + /** + * This method sets the value to the member attribute impliedGrant . + * You cannot set null to the attribute. + * + * @param impliedGrant Value to set member attribute impliedGrant + */ + public void setImpliedGrant(String impliedGrant) { + this.impliedGrant = impliedGrant; + } } 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 index 9683db0389..713d9e5a2b 100644 --- a/security-admin/src/main/java/org/apache/ranger/entity/XXAsset.java +++ b/security-admin/src/main/java/org/apache/ranger/entity/XXAsset.java @@ -17,13 +17,15 @@ * under the License. */ - package org.apache.ranger.entity; +package org.apache.ranger.entity; /** * Asset - * */ +import org.apache.ranger.common.AppConstants; +import org.apache.ranger.common.RangerConstants; + import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; @@ -32,260 +34,272 @@ import javax.persistence.SequenceGenerator; import javax.persistence.Table; -import org.apache.ranger.common.AppConstants; -import org.apache.ranger.common.RangerConstants; - +import java.util.Objects; @Entity -@Table(name="x_asset") +@Table(name = "x_asset") 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 - *
    - *
  • The maximum length for this attribute is 1024. - *
- * - */ - @Column(name="ASSET_NAME" , nullable=false , length=1024) - protected String name; - - /** - * Description - *
    - *
  • The maximum length for this attribute is 4000. - *
- * - */ - @Column(name="DESCR" , nullable=false , length=4000) - protected String description; - - /** - * Status - *
    - *
  • This attribute is of type enum CommonEnums::ActiveStatus - *
- * - */ - @Column(name="ACT_STATUS" , nullable=false ) - protected int activeStatus = RangerConstants.STATUS_DISABLED; - - /** - * Type of asset - *
    - *
  • This attribute is of type enum CommonEnums::AssetType - *
- * - */ - @Column(name="ASSET_TYPE" , nullable=false ) - protected int assetType = AppConstants.ASSET_UNKNOWN; - - /** - * Config in json format - *
    - *
  • The maximum length for this attribute is 10000. - *
- * - */ - @Column(name="CONFIG" , length=10000) - protected String config; - - /** - * Support native authorization - *
    - *
- * - */ - @Column(name="SUP_NATIVE" , nullable=false ) - protected boolean supportNative = false; - - /** - * Default constructor. This will set all the attributes to default value. - */ - public XXAsset ( ) { - activeStatus = RangerConstants.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 name. - * You cannot set null to the attribute. - * @param name Value to set member attribute name - */ - public void setName( String name ) { - this.name = name; - } - - /** - * Returns the value for the member attribute name - * @return String - value of member attribute name. - */ - public String getName( ) { - return this.name; - } - - /** - * This method sets the value to the member attribute description. - * You cannot set null to the attribute. - * @param description Value to set member attribute description - */ - public void setDescription( String description ) { - this.description = description; - } - - /** - * Returns the value for the member attribute description - * @return String - value of member attribute description. - */ - public String getDescription( ) { - return this.description; - } - - /** - * This method sets the value to the member attribute activeStatus. - * You cannot set null to the attribute. - * @param activeStatus Value to set member attribute activeStatus - */ - public void setActiveStatus( int activeStatus ) { - this.activeStatus = activeStatus; - } - - /** - * Returns the value for the member attribute activeStatus - * @return int - value of member attribute activeStatus. - */ - public int getActiveStatus( ) { - return this.activeStatus; - } - - /** - * This method sets the value to the member attribute assetType. - * You cannot set null to the attribute. - * @param assetType Value to set member attribute assetType - */ - public void setAssetType( int assetType ) { - this.assetType = assetType; - } - - /** - * Returns the value for the member attribute assetType - * @return int - value of member attribute assetType. - */ - public int getAssetType( ) { - return this.assetType; - } - - /** - * This method sets the value to the member attribute config. - * You cannot set null to the attribute. - * @param config Value to set member attribute config - */ - public void setConfig( String config ) { - this.config = config; - } - - /** - * Returns the value for the member attribute config - * @return String - value of member attribute config. - */ - public String getConfig( ) { - return this.config; - } - - /** - * This method sets the value to the member attribute supportNative. - * You cannot set null to the attribute. - * @param supportNative Value to set member attribute supportNative - */ - public void setSupportNative( boolean supportNative ) { - this.supportNative = supportNative; - } - - /** - * Returns the value for the member attribute supportNative - * @return boolean - value of member attribute supportNative. - */ - 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( "activeStatus".equals(fieldName) ) { - return "CommonEnums.ActiveStatus"; - } - if( "assetType".equals(fieldName) ) { - return "CommonEnums.AssetType"; - } - //Later TODO - //return super.getEnumName(fieldName); - return null; - } + 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; + + /** + * Name + *
    + *
  • The maximum length for this attribute is 1024. + *
+ */ + @Column(name = "ASSET_NAME", nullable = false, length = 1024) + protected String name; + + /** + * Description + *
    + *
  • The maximum length for this attribute is 4000. + *
+ */ + @Column(name = "DESCR", nullable = false, length = 4000) + protected String description; + + /** + * Status + *
    + *
  • This attribute is of type enum CommonEnums::ActiveStatus + *
+ */ + @Column(name = "ACT_STATUS", nullable = false) + protected int activeStatus = RangerConstants.STATUS_DISABLED; + + /** + * Type of asset + *
    + *
  • This attribute is of type enum CommonEnums::AssetType + *
+ */ + @Column(name = "ASSET_TYPE", nullable = false) + protected int assetType = AppConstants.ASSET_UNKNOWN; + + /** + * Config in json format + *
    + *
  • The maximum length for this attribute is 10000. + *
+ */ + @Column(name = "CONFIG", length = 10000) + protected String config; + + /** + * Support native authorization + *
    + *
+ */ + @Column(name = "SUP_NATIVE", nullable = false) + protected boolean supportNative; + + /** + * Default constructor. This will set all the attributes to default value. + */ + public XXAsset() { + activeStatus = RangerConstants.STATUS_DISABLED; + assetType = AppConstants.ASSET_UNKNOWN; + } + + public static String getEnumName(String fieldName) { + if ("activeStatus".equals(fieldName)) { + return "CommonEnums.ActiveStatus"; + } + + if ("assetType".equals(fieldName)) { + return "CommonEnums.AssetType"; + } + + //Later TODO + //return super.getEnumName(fieldName); + return null; + } + + @Override + public int getMyClassType() { + return AppConstants.CLASS_TYPE_XA_ASSET; + } + + @Override + public String getMyDisplayValue() { + return getDescription(); + } + + @Override + public Long getId() { + return id; + } + + @Override + public void setId(Long id) { + this.id = id; + } + + @Override + public int hashCode() { + return super.hashCode(); + } + + /** + * Checks for all attributes except referenced db objects + * + * @return true if all attributes match + */ + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } if (!super.equals(obj)) { + return false; + } + + XXAsset other = (XXAsset) obj; + + return Objects.equals(name, other.name) && + Objects.equals(description, other.description) && + Objects.equals(activeStatus, other.activeStatus) && + Objects.equals(assetType, other.assetType) && + Objects.equals(config, other.config) && + Objects.equals(supportNative, other.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; + } + + /** + * Returns the value for the member attribute name + * + * @return String - value of member attribute name. + */ + public String getName() { + return this.name; + } + + /** + * This method sets the value to the member attribute name. + * You cannot set null to the attribute. + * + * @param name Value to set member attribute name + */ + public void setName(String name) { + this.name = name; + } + + /** + * Returns the value for the member attribute description + * + * @return String - value of member attribute description. + */ + public String getDescription() { + return this.description; + } + + /** + * This method sets the value to the member attribute description. + * You cannot set null to the attribute. + * + * @param description Value to set member attribute description + */ + public void setDescription(String description) { + this.description = description; + } + + /** + * Returns the value for the member attribute activeStatus + * + * @return int - value of member attribute activeStatus. + */ + public int getActiveStatus() { + return this.activeStatus; + } + + /** + * This method sets the value to the member attribute activeStatus. + * You cannot set null to the attribute. + * + * @param activeStatus Value to set member attribute activeStatus + */ + public void setActiveStatus(int activeStatus) { + this.activeStatus = activeStatus; + } + + /** + * Returns the value for the member attribute assetType + * + * @return int - value of member attribute assetType. + */ + public int getAssetType() { + return this.assetType; + } + + /** + * This method sets the value to the member attribute assetType. + * You cannot set null to the attribute. + * + * @param assetType Value to set member attribute assetType + */ + public void setAssetType(int assetType) { + this.assetType = assetType; + } + + /** + * Returns the value for the member attribute config + * + * @return String - value of member attribute config. + */ + public String getConfig() { + return this.config; + } + + /** + * This method sets the value to the member attribute config. + * You cannot set null to the attribute. + * + * @param config Value to set member attribute config + */ + public void setConfig(String config) { + this.config = config; + } + + /** + * Returns the value for the member attribute supportNative + * + * @return boolean - value of member attribute supportNative. + */ + public boolean isSupportNative() { + return this.supportNative; + } + /** + * This method sets the value to the member attribute supportNative. + * You cannot set null to the attribute. + * + * @param supportNative Value to set member attribute supportNative + */ + public void setSupportNative(boolean supportNative) { + this.supportNative = supportNative; + } } 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 index 60695af4d7..47bc4eb7f4 100644 --- a/security-admin/src/main/java/org/apache/ranger/entity/XXAuditMap.java +++ b/security-admin/src/main/java/org/apache/ranger/entity/XXAuditMap.java @@ -17,13 +17,14 @@ * under the License. */ - package org.apache.ranger.entity; +package org.apache.ranger.entity; /** * Audi map - * */ +import org.apache.ranger.common.AppConstants; + import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; @@ -32,198 +33,200 @@ import javax.persistence.SequenceGenerator; import javax.persistence.Table; -import org.apache.ranger.common.AppConstants; - +import java.util.Objects; @Entity -@Table(name="x_audit_map") +@Table(name = "x_audit_map") 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 - *
    - *
- * - */ - @Column(name="RES_ID" ) - protected Long resourceId; - - - /** - * Id of the group - *
    - *
- * - */ - @Column(name="GROUP_ID" ) - protected Long groupId; - - - /** - * Id of the user - *
    - *
- * - */ - @Column(name="USER_ID" ) - protected Long userId; - - - /** - * Type of audit - *
    - *
  • This attribute is of type enum CommonEnums::XAAuditType - *
- * - */ - @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 resourceId. - * You cannot set null to the attribute. - * @param resourceId Value to set member attribute resourceId - */ - public void setResourceId( Long resourceId ) { - this.resourceId = resourceId; - } - - /** - * Returns the value for the member attribute resourceId - * @return Long - value of member attribute resourceId. - */ - public Long getResourceId( ) { - return this.resourceId; - } - - - /** - * This method sets the value to the member attribute groupId. - * You cannot set null to the attribute. - * @param groupId Value to set member attribute groupId - */ - public void setGroupId( Long groupId ) { - this.groupId = groupId; - } - - /** - * Returns the value for the member attribute groupId - * @return Long - value of member attribute groupId. - */ - public Long getGroupId( ) { - return this.groupId; - } - - - /** - * This method sets the value to the member attribute userId. - * You cannot set null to the attribute. - * @param userId Value to set member attribute userId - */ - public void setUserId( Long userId ) { - this.userId = userId; - } - - /** - * Returns the value for the member attribute userId - * @return Long - value of member attribute userId. - */ - public Long getUserId( ) { - return this.userId; - } - - - /** - * This method sets the value to the member attribute auditType. - * You cannot set null to the attribute. - * @param auditType Value to set member attribute auditType - */ - public void setAuditType( int auditType ) { - this.auditType = auditType; - } - - /** - * Returns the value for the member attribute auditType - * @return int - value of member attribute auditType. - */ - 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( "auditType".equals(fieldName) ) { - return "CommonEnums.XAAuditType"; - } - //Later TODO - //return super.getEnumName(fieldName); - return null; - } - + 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; + + /** + * Id of the resource + *
    + *
+ */ + @Column(name = "RES_ID") + protected Long resourceId; + + /** + * Id of the group + *
    + *
+ */ + @Column(name = "GROUP_ID") + protected Long groupId; + + /** + * Id of the user + *
    + *
+ */ + @Column(name = "USER_ID") + protected Long userId; + + /** + * Type of audit + *
    + *
  • This attribute is of type enum CommonEnums::XAAuditType + *
+ */ + @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; + } + + public static String getEnumName(String fieldName) { + if ("auditType".equals(fieldName)) { + return "CommonEnums.XAAuditType"; + } + + //Later TODO + //return super.getEnumName(fieldName); + return null; + } + + @Override + public int getMyClassType() { + return AppConstants.CLASS_TYPE_XA_AUDIT_MAP; + } + + @Override + public Long getId() { + return id; + } + + @Override + public void setId(Long id) { + this.id = id; + } + + @Override + public int hashCode() { + return super.hashCode(); + } + + /** + * Checks for all attributes except referenced db objects + * + * @return true if all attributes match + */ + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } else if (!super.equals(obj)) { + return false; + } + + XXAuditMap other = (XXAuditMap) obj; + + return Objects.equals(resourceId, other.resourceId) && + Objects.equals(groupId, other.groupId) && + Objects.equals(userId, other.userId) && + Objects.equals(auditType, other.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; + } + + /** + * Returns the value for the member attribute resourceId + * + * @return Long - value of member attribute resourceId. + */ + public Long getResourceId() { + return this.resourceId; + } + + /** + * This method sets the value to the member attribute resourceId. + * You cannot set null to the attribute. + * + * @param resourceId Value to set member attribute resourceId + */ + public void setResourceId(Long resourceId) { + this.resourceId = resourceId; + } + + /** + * Returns the value for the member attribute groupId + * + * @return Long - value of member attribute groupId. + */ + public Long getGroupId() { + return this.groupId; + } + + /** + * This method sets the value to the member attribute groupId. + * You cannot set null to the attribute. + * + * @param groupId Value to set member attribute groupId + */ + public void setGroupId(Long groupId) { + this.groupId = groupId; + } + + /** + * Returns the value for the member attribute userId + * + * @return Long - value of member attribute userId. + */ + public Long getUserId() { + return this.userId; + } + + /** + * This method sets the value to the member attribute userId. + * You cannot set null to the attribute. + * + * @param userId Value to set member attribute userId + */ + public void setUserId(Long userId) { + this.userId = userId; + } + + /** + * Returns the value for the member attribute auditType + * + * @return int - value of member attribute auditType. + */ + public int getAuditType() { + return this.auditType; + } + + /** + * This method sets the value to the member attribute auditType. + * You cannot set null to the attribute. + * + * @param auditType Value to set member attribute auditType + */ + public void setAuditType(int auditType) { + this.auditType = auditType; + } } 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 index c03bb11296..00132e7f0e 100644 --- a/security-admin/src/main/java/org/apache/ranger/entity/XXAuthSession.java +++ b/security-admin/src/main/java/org/apache/ranger/entity/XXAuthSession.java @@ -17,14 +17,15 @@ * under the License. */ - package org.apache.ranger.entity; +package org.apache.ranger.entity; /** * Authentication session - * */ -import java.util.Date; +import org.apache.ranger.common.AppConstants; +import org.apache.ranger.common.DateUtil; +import org.apache.ranger.common.RangerConstants; import javax.persistence.Column; import javax.persistence.Entity; @@ -36,458 +37,473 @@ import javax.persistence.Temporal; import javax.persistence.TemporalType; -import org.apache.ranger.common.AppConstants; -import org.apache.ranger.common.DateUtil; -import org.apache.ranger.common.RangerConstants; - +import java.util.Date; +import java.util.Objects; @Entity -@Table(name="x_auth_sess") +@Table(name = "x_auth_sess") 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; - - /** - * AUTH_TYPE_KERBEROS is an element of enum AuthType. Its value is "AUTH_TYPE_KERBEROS". - */ - public static final int AUTH_TYPE_KERBEROS = 2; - - /** - * AUTH_TYPE_SSO is an element of enum AuthType. Its value is "AUTH_TYPE_SSO". - */ - public static final int AUTH_TYPE_SSO = 3; - - /** - * AUTH_TYPE_TRUSTED_PROXY is an element of enum AuthType. Its value is "AUTH_TYPE_TRUSTED_PROXY". - */ - public static final int AUTH_TYPE_TRUSTED_PROXY = 4; - - /** - * Max value for enum AuthType_MAX - */ - public static final int AuthType_MAX = 4; - - - - /** - * Login ID of the user - *
    - *
  • The maximum length for this attribute is 767. - *
- * - */ - @Column(name="LOGIN_ID" , nullable=false , length=767) - protected String loginId; - - /** - * Id of the user - *
    - *
- * - */ - @Column(name="USER_ID" ) - protected Long userId; - - - /** - * External session id. Currently spring/http session - *
    - *
  • The maximum length for this attribute is 512. - *
- * - */ - @Column(name="EXT_SESS_ID" , length=512) - protected String extSessionId; - - /** - * Date and time of authentication - *
    - *
- * - */ - @Temporal(TemporalType.TIMESTAMP) - @Column(name="AUTH_TIME" , nullable=false ) - protected Date authTime = DateUtil.getUTCDate(); - - /** - * Authentication status - *
    - *
  • This attribute is of type enum XXAuthSession::AuthStatus - *
- * - */ - @Column(name="AUTH_STATUS" , nullable=false ) - protected int authStatus = AUTH_STATUS_UNKNOWN; - - /** - * Authentication type - *
    - *
  • This attribute is of type enum XXAuthSession::AuthType - *
- * - */ - @Column(name="AUTH_TYPE" , nullable=false ) - protected int authType = AUTH_TYPE_UNKNOWN; - - /** - * Authentication provider - *
    - *
  • This attribute is of type enum XXAuthSession::AuthType - *
- * - */ - @Column(name="AUTH_PROVIDER" , nullable=false ) - protected int authProvider = AUTH_TYPE_UNKNOWN; - - /** - * Type of the device - *
    - *
  • This attribute is of type enum CommonEnums::DeviceType - *
- * - */ - @Column(name="DEVICE_TYPE" , nullable=false ) - protected int deviceType = RangerConstants.DEVICE_UNKNOWN; - - /** - * IP where the request came from - *
    - *
  • The maximum length for this attribute is 48. - *
- * - */ - @Column(name="REQ_IP" , nullable=false , length=48) - protected String requestIP; - - /** - * UserAgent of the requesting device - *
    - *
  • The maximum length for this attribute is 1024. - *
- * - */ - @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 = RangerConstants.DEVICE_UNKNOWN; - } - - @Override - public int getMyClassType( ) { - return AppConstants.CLASS_TYPE_AUTH_SESS; - } - - /** - * This method sets the value to the member attribute loginId. - * You cannot set null to the attribute. - * @param loginId Value to set member attribute loginId - */ - public void setLoginId( String loginId ) { - this.loginId = loginId; - } - - /** - * Returns the value for the member attribute loginId - * @return String - value of member attribute loginId. - */ - public String getLoginId( ) { - return this.loginId; - } - - /** - * This method sets the value to the member attribute userId. - * You cannot set null to the attribute. - * @param userId Value to set member attribute userId - */ - public void setUserId( Long userId ) { - this.userId = userId; - } - - /** - * Returns the value for the member attribute userId - * @return Long - value of member attribute userId. - */ - public Long getUserId( ) { - return this.userId; - } - - - /** - * This method sets the value to the member attribute extSessionId. - * You cannot set null to the attribute. - * @param extSessionId Value to set member attribute extSessionId - */ - public void setExtSessionId( String extSessionId ) { - this.extSessionId = extSessionId; - } - - /** - * Returns the value for the member attribute extSessionId - * @return String - value of member attribute extSessionId. - */ - public String getExtSessionId( ) { - return this.extSessionId; - } - - /** - * This method sets the value to the member attribute authTime. - * You cannot set null to the attribute. - * @param authTime Value to set member attribute authTime - */ - public void setAuthTime( Date authTime ) { - this.authTime = authTime; - } - - /** - * Returns the value for the member attribute authTime - * @return Date - value of member attribute authTime. - */ - public Date getAuthTime( ) { - return this.authTime; - } - - /** - * This method sets the value to the member attribute authStatus. - * You cannot set null to the attribute. - * @param authStatus Value to set member attribute authStatus - */ - public void setAuthStatus( int authStatus ) { - this.authStatus = authStatus; - } - - /** - * Returns the value for the member attribute authStatus - * @return int - value of member attribute authStatus. - */ - public int getAuthStatus( ) { - return this.authStatus; - } - - /** - * This method sets the value to the member attribute authType. - * You cannot set null to the attribute. - * @param authType Value to set member attribute authType - */ - public void setAuthType( int authType ) { - this.authType = authType; - } - - /** - * Returns the value for the member attribute authType - * @return int - value of member attribute authType. - */ - public int getAuthType( ) { - return this.authType; - } - - /** - * This method sets the value to the member attribute authProvider. - * You cannot set null to the attribute. - * @param authProvider Value to set member attribute authProvider - */ - public void setAuthProvider( int authProvider ) { - this.authProvider = authProvider; - } - - /** - * Returns the value for the member attribute authProvider - * @return int - value of member attribute authProvider. - */ - public int getAuthProvider( ) { - return this.authProvider; - } - - /** - * This method sets the value to the member attribute deviceType. - * You cannot set null to the attribute. - * @param deviceType Value to set member attribute deviceType - */ - public void setDeviceType( int deviceType ) { - this.deviceType = deviceType; - } - - /** - * Returns the value for the member attribute deviceType - * @return int - value of member attribute deviceType. - */ - public int getDeviceType( ) { - return this.deviceType; - } - - /** - * This method sets the value to the member attribute requestIP. - * You cannot set null to the attribute. - * @param requestIP Value to set member attribute requestIP - */ - public void setRequestIP( String requestIP ) { - this.requestIP = requestIP; - } - - /** - * Returns the value for the member attribute requestIP - * @return String - value of member attribute requestIP. - */ - public String getRequestIP( ) { - return this.requestIP; - } - - /** - * This method sets the value to the member attribute requestUserAgent. - * You cannot set null to the attribute. - * @param requestUserAgent Value to set member attribute requestUserAgent - */ - public void setRequestUserAgent( String requestUserAgent ) { - this.requestUserAgent = requestUserAgent; - } - - /** - * Returns the value for the member attribute requestUserAgent - * @return String - value of member attribute requestUserAgent. - */ - 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 += "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( "authStatus".equals(fieldName) ) { - return "CommonEnums.AuthStatus"; - } - if( "authType".equals(fieldName) ) { - return "CommonEnums.AuthType"; - } - if( "authProvider".equals(fieldName) ) { - return "CommonEnums.AuthType"; - } - if( "deviceType".equals(fieldName) ) { - return "CommonEnums.DeviceType"; - } - //Later TODO - //return super.getEnumName(fieldName); - return null; - } - + private static final long serialVersionUID = 1L; + + /** + * 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; + + /** + * Enum values for AuthStatus + */ + /** + * 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; + + /** + * 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; + + /** + * AUTH_TYPE_KERBEROS is an element of enum AuthType. Its value is "AUTH_TYPE_KERBEROS". + */ + public static final int AUTH_TYPE_KERBEROS = 2; + + /** + * AUTH_TYPE_SSO is an element of enum AuthType. Its value is "AUTH_TYPE_SSO". + */ + public static final int AUTH_TYPE_SSO = 3; + + /** + * Enum values for AuthType + */ + /** + * AUTH_TYPE_TRUSTED_PROXY is an element of enum AuthType. Its value is "AUTH_TYPE_TRUSTED_PROXY". + */ + public static final int AUTH_TYPE_TRUSTED_PROXY = 4; + + /** + * Max value for enum AuthType_MAX + */ + public static final int AuthType_MAX = 4; + + @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; + + /** + * Login ID of the user + *
    + *
  • The maximum length for this attribute is 767. + *
+ */ + @Column(name = "LOGIN_ID", nullable = false, length = 767) + protected String loginId; + + /** + * Id of the user + *
    + *
+ */ + @Column(name = "USER_ID") + protected Long userId; + + /** + * External session id. Currently spring/http session + *
    + *
  • The maximum length for this attribute is 512. + *
+ */ + @Column(name = "EXT_SESS_ID", length = 512) + protected String extSessionId; + + /** + * Date and time of authentication + *
    + *
+ */ + @Temporal(TemporalType.TIMESTAMP) + @Column(name = "AUTH_TIME", nullable = false) + protected Date authTime = DateUtil.getUTCDate(); + + /** + * Authentication status + *
    + *
  • This attribute is of type enum XXAuthSession::AuthStatus + *
+ */ + @Column(name = "AUTH_STATUS", nullable = false) + protected int authStatus = AUTH_STATUS_UNKNOWN; + + /** + * Authentication type + *
    + *
  • This attribute is of type enum XXAuthSession::AuthType + *
+ */ + @Column(name = "AUTH_TYPE", nullable = false) + protected int authType = AUTH_TYPE_UNKNOWN; + + /** + * Authentication provider + *
    + *
  • This attribute is of type enum XXAuthSession::AuthType + *
+ */ + @Column(name = "AUTH_PROVIDER", nullable = false) + protected int authProvider = AUTH_TYPE_UNKNOWN; + + /** + * Type of the device + *
    + *
  • This attribute is of type enum CommonEnums::DeviceType + *
+ */ + @Column(name = "DEVICE_TYPE", nullable = false) + protected int deviceType = RangerConstants.DEVICE_UNKNOWN; + + /** + * IP where the request came from + *
    + *
  • The maximum length for this attribute is 48. + *
+ */ + @Column(name = "REQ_IP", nullable = false, length = 48) + protected String requestIP; + + /** + * UserAgent of the requesting device + *
    + *
  • The maximum length for this attribute is 1024. + *
+ */ + @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 = RangerConstants.DEVICE_UNKNOWN; + } + + public static String getEnumName(String fieldName) { + if ("authStatus".equals(fieldName)) { + return "CommonEnums.AuthStatus"; + } + + if ("authType".equals(fieldName)) { + return "CommonEnums.AuthType"; + } + + if ("authProvider".equals(fieldName)) { + return "CommonEnums.AuthType"; + } + + if ("deviceType".equals(fieldName)) { + return "CommonEnums.DeviceType"; + } + + //Later TODO + //return super.getEnumName(fieldName); + return null; + } + + @Override + public int getMyClassType() { + return AppConstants.CLASS_TYPE_AUTH_SESS; + } + + @Override + public Long getId() { + return id; + } + + @Override + public void setId(Long id) { + this.id = id; + } + + @Override + public int hashCode() { + return super.hashCode(); + } + + /** + * Checks for all attributes except referenced db objects + * + * @return true if all attributes match + */ + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } else if (!super.equals(obj)) { + return false; + } + + XXAuthSession other = (XXAuthSession) obj; + + return Objects.equals(loginId, other.loginId) && + Objects.equals(userId, other.userId) && + Objects.equals(extSessionId, other.extSessionId) && + Objects.equals(authTime, other.authTime) && + Objects.equals(authStatus, other.authStatus) && + Objects.equals(authType, other.authType) && + Objects.equals(authProvider, other.authProvider) && + Objects.equals(deviceType, other.deviceType) && + Objects.equals(requestIP, other.requestIP) && + Objects.equals(requestUserAgent, other.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 += "authTime={" + authTime + "} "; + str += "authStatus={" + authStatus + "} "; + str += "authType={" + authType + "} "; + str += "authProvider={" + authProvider + "} "; + str += "deviceType={" + deviceType + "} "; + str += "requestIP={" + requestIP + "} "; + str += "requestUserAgent={" + requestUserAgent + "} "; + str += "}"; + return str; + } + + /** + * Returns the value for the member attribute loginId + * + * @return String - value of member attribute loginId. + */ + public String getLoginId() { + return this.loginId; + } + + /** + * This method sets the value to the member attribute loginId. + * You cannot set null to the attribute. + * + * @param loginId Value to set member attribute loginId + */ + public void setLoginId(String loginId) { + this.loginId = loginId; + } + + /** + * Returns the value for the member attribute userId + * + * @return Long - value of member attribute userId. + */ + public Long getUserId() { + return this.userId; + } + + /** + * This method sets the value to the member attribute userId. + * You cannot set null to the attribute. + * + * @param userId Value to set member attribute userId + */ + public void setUserId(Long userId) { + this.userId = userId; + } + + /** + * Returns the value for the member attribute extSessionId + * + * @return String - value of member attribute extSessionId. + */ + public String getExtSessionId() { + return this.extSessionId; + } + + /** + * This method sets the value to the member attribute extSessionId. + * You cannot set null to the attribute. + * + * @param extSessionId Value to set member attribute extSessionId + */ + public void setExtSessionId(String extSessionId) { + this.extSessionId = extSessionId; + } + + /** + * Returns the value for the member attribute authTime + * + * @return Date - value of member attribute authTime. + */ + public Date getAuthTime() { + return this.authTime; + } + + /** + * This method sets the value to the member attribute authTime. + * You cannot set null to the attribute. + * + * @param authTime Value to set member attribute authTime + */ + public void setAuthTime(Date authTime) { + this.authTime = authTime; + } + + /** + * Returns the value for the member attribute authStatus + * + * @return int - value of member attribute authStatus. + */ + public int getAuthStatus() { + return this.authStatus; + } + + /** + * This method sets the value to the member attribute authStatus. + * You cannot set null to the attribute. + * + * @param authStatus Value to set member attribute authStatus + */ + public void setAuthStatus(int authStatus) { + this.authStatus = authStatus; + } + + /** + * Returns the value for the member attribute authType + * + * @return int - value of member attribute authType. + */ + public int getAuthType() { + return this.authType; + } + + /** + * This method sets the value to the member attribute authType. + * You cannot set null to the attribute. + * + * @param authType Value to set member attribute authType + */ + public void setAuthType(int authType) { + this.authType = authType; + } + + /** + * Returns the value for the member attribute authProvider + * + * @return int - value of member attribute authProvider. + */ + public int getAuthProvider() { + return this.authProvider; + } + + /** + * This method sets the value to the member attribute authProvider. + * You cannot set null to the attribute. + * + * @param authProvider Value to set member attribute authProvider + */ + public void setAuthProvider(int authProvider) { + this.authProvider = authProvider; + } + + /** + * Returns the value for the member attribute deviceType + * + * @return int - value of member attribute deviceType. + */ + public int getDeviceType() { + return this.deviceType; + } + + /** + * This method sets the value to the member attribute deviceType. + * You cannot set null to the attribute. + * + * @param deviceType Value to set member attribute deviceType + */ + public void setDeviceType(int deviceType) { + this.deviceType = deviceType; + } + + /** + * Returns the value for the member attribute requestIP + * + * @return String - value of member attribute requestIP. + */ + public String getRequestIP() { + return this.requestIP; + } + + /** + * This method sets the value to the member attribute requestIP. + * You cannot set null to the attribute. + * + * @param requestIP Value to set member attribute requestIP + */ + public void setRequestIP(String requestIP) { + this.requestIP = requestIP; + } + + /** + * Returns the value for the member attribute requestUserAgent + * + * @return String - value of member attribute requestUserAgent. + */ + public String getRequestUserAgent() { + return this.requestUserAgent; + } + + /** + * This method sets the value to the member attribute requestUserAgent. + * You cannot set null to the attribute. + * + * @param requestUserAgent Value to set member attribute requestUserAgent + */ + public void setRequestUserAgent(String requestUserAgent) { + this.requestUserAgent = requestUserAgent; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/entity/XXContextEnricherDef.java b/security-admin/src/main/java/org/apache/ranger/entity/XXContextEnricherDef.java index 98ae4a3945..d722abd677 100644 --- a/security-admin/src/main/java/org/apache/ranger/entity/XXContextEnricherDef.java +++ b/security-admin/src/main/java/org/apache/ranger/entity/XXContextEnricherDef.java @@ -18,307 +18,255 @@ */ package org.apache.ranger.entity; -import javax.persistence.*; +import javax.persistence.Cacheable; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.SequenceGenerator; +import javax.persistence.Table; + +import java.util.Objects; @Entity @Cacheable @Table(name = "x_context_enricher_def") -public class XXContextEnricherDef extends XXDBBase implements - java.io.Serializable { - private static final long serialVersionUID = 1L; - /** - * id of the XXContextEnricherDef - *
    - *
- * - */ - @Id - @SequenceGenerator(name = "x_context_enricher_def_SEQ", sequenceName = "x_context_enricher_def_SEQ", allocationSize = 1) - @GeneratedValue(strategy = GenerationType.AUTO, generator = "x_context_enricher_def_SEQ") - @Column(name = "id") - protected Long id; +public class XXContextEnricherDef extends XXDBBase implements java.io.Serializable { + private static final long serialVersionUID = 1L; + + /** + * id of the XXContextEnricherDef + *
    + *
+ */ + @Id + @SequenceGenerator(name = "x_context_enricher_def_SEQ", sequenceName = "x_context_enricher_def_SEQ", allocationSize = 1) + @GeneratedValue(strategy = GenerationType.AUTO, generator = "x_context_enricher_def_SEQ") + @Column(name = "id") + protected Long id; + + /** + * defId of the XXContextEnricherDef + *
    + *
+ */ + @Column(name = "def_id") + protected Long defId; + + /** + * itemId of the XXContextEnricherDef + *
    + *
+ */ + @Column(name = "item_id") + protected Long itemId; - /** - * defId of the XXContextEnricherDef - *
    - *
- * - */ - @Column(name = "def_id") - protected Long defId; + /** + * name of the XXContextEnricherDef + *
    + *
+ */ + @Column(name = "name") + protected String name; - /** - * itemId of the XXContextEnricherDef - *
    - *
- * - */ - @Column(name = "item_id") - protected Long itemId; + /** + * enricher of the XXContextEnricherDef + *
    + *
+ */ + @Column(name = "enricher") + protected String enricher; - /** - * name of the XXContextEnricherDef - *
    - *
- * - */ - @Column(name = "name") - protected String name; + /** + * enricherOptions of the XXContextEnricherDef + *
    + *
+ */ + @Column(name = "enricher_options") + protected String enricherOptions; - /** - * enricher of the XXContextEnricherDef - *
    - *
- * - */ - @Column(name = "enricher") - protected String enricher; + /** + * order of the XXContextEnricherDef + *
    + *
+ */ + @Column(name = "sort_order") + protected Integer order; - /** - * enricherOptions of the XXContextEnricherDef - *
    - *
- * - */ - @Column(name = "enricher_options") - protected String enricherOptions; + /** + * Returns the value for the member attribute id + * + * @return Date - value of member attribute id . + */ + public Long getId() { + return this.id; + } - /** - * order of the XXContextEnricherDef - *
    - *
- * - */ - @Column(name = "sort_order") - protected Integer order; + /** + * This method sets the value to the member attribute id . You + * cannot set null to the attribute. + * + * @param id Value to set member attribute id + */ + public void setId(Long id) { + this.id = id; + } - /** - * This method sets the value to the member attribute id . You - * cannot set null to the attribute. - * - * @param id - * Value to set member attribute id - */ - public void setId(Long id) { - this.id = id; - } + @Override + public int hashCode() { + return super.hashCode(); + } - /** - * Returns the value for the member attribute id - * - * @return Date - value of member attribute id . - */ - public Long getId() { - return this.id; - } + /* + * (non-Javadoc) + * + * @see java.lang.Object#equals(java.lang.Object) + */ + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } else if (!super.equals(obj)) { + return false; + } - /** - * This method sets the value to the member attribute defId . You - * cannot set null to the attribute. - * - * @param defId - * Value to set member attribute defId - */ - public void setDefid(Long defId) { - this.defId = defId; - } + XXContextEnricherDef other = (XXContextEnricherDef) obj; - /** - * Returns the value for the member attribute itemId - * - * @return Long - value of member attribute itemId . - */ - public Long getItemId() { - return this.itemId; - } + return Objects.equals(defId, other.defId) && + Objects.equals(itemId, other.itemId) && + Objects.equals(enricher, other.enricher) && + Objects.equals(enricherOptions, other.enricherOptions) && + Objects.equals(id, other.id) && + Objects.equals(name, other.name) && + Objects.equals(order, other.order); + } - /** - * This method sets the value to the member attribute defId . You - * cannot set null to the attribute. - * - * @param defId - * Value to set member attribute defId - */ - public void setItemId(Long itemId) { - this.itemId = itemId; - } + /* + * (non-Javadoc) + * + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + String str = "XXContextEnricherDef={"; + str += super.toString(); + str += " [id=" + id + ", defId=" + defId + ", itemId=" + itemId + ", name=" + name + ", enricher=" + enricherOptions + ", enricherOptions=" + enricherOptions + ", order=" + order + "]"; + str += "}"; + return str; + } - /** - * Returns the value for the member attribute defId - * - * @return Date - value of member attribute defId . - */ - public Long getDefid() { - return this.defId; - } + /** + * Returns the value for the member attribute itemId + * + * @return Long - value of member attribute itemId . + */ + public Long getItemId() { + return this.itemId; + } - /** - * This method sets the value to the member attribute name . You - * cannot set null to the attribute. - * - * @param name - * Value to set member attribute name - */ - public void setName(String name) { - this.name = name; - } + /** + * This method sets the value to the member attribute defId . You + * cannot set null to the attribute. + * + * @param itemId Value to set member attribute defId + */ + public void setItemId(Long itemId) { + this.itemId = itemId; + } - /** - * Returns the value for the member attribute name - * - * @return Date - value of member attribute name . - */ - public String getName() { - return this.name; - } + /** + * Returns the value for the member attribute defId + * + * @return Date - value of member attribute defId . + */ + public Long getDefid() { + return this.defId; + } - /** - * This method sets the value to the member attribute enricher . - * You cannot set null to the attribute. - * - * @param enricher - * Value to set member attribute enricher - */ - public void setEnricher(String enricher) { - this.enricher = enricher; - } + /** + * This method sets the value to the member attribute defId . You + * cannot set null to the attribute. + * + * @param defId Value to set member attribute defId + */ + public void setDefid(Long defId) { + this.defId = defId; + } - /** - * Returns the value for the member attribute enricher - * - * @return String - value of member attribute enricher . - */ - public String getEnricher() { - return this.enricher; - } + /** + * Returns the value for the member attribute name + * + * @return Date - value of member attribute name . + */ + public String getName() { + return this.name; + } - /** - * This method sets the value to the member attribute - * enricherOptions . You cannot set null to the attribute. - * - * @param enricherOptions - * Value to set member attribute enricherOptions - */ - public void setEnricherOptions(String enricherOptions) { - this.enricherOptions = enricherOptions; - } + /** + * This method sets the value to the member attribute name . You + * cannot set null to the attribute. + * + * @param name Value to set member attribute name + */ + public void setName(String name) { + this.name = name; + } - /** - * Returns the value for the member attribute evaluatorOptions - * - * @return Date - value of member attribute evaluatorOptions . - */ - public String getEnricherOptions() { - return this.enricherOptions; - } + /** + * Returns the value for the member attribute enricher + * + * @return String - value of member attribute enricher . + */ + public String getEnricher() { + return this.enricher; + } - /** - * This method sets the value to the member attribute order . You - * cannot set null to the attribute. - * - * @param order - * Value to set member attribute order - */ - public void setOrder(Integer order) { - this.order = order; - } + /** + * This method sets the value to the member attribute enricher . + * You cannot set null to the attribute. + * + * @param enricher Value to set member attribute enricher + */ + public void setEnricher(String enricher) { + this.enricher = enricher; + } - /** - * Returns the value for the member attribute order - * - * @return Integer - value of member attribute order . - */ - public Integer getOrder() { - return this.order; - } + /** + * Returns the value for the member attribute evaluatorOptions + * + * @return Date - value of member attribute evaluatorOptions . + */ + public String getEnricherOptions() { + return this.enricherOptions; + } - /* - * (non-Javadoc) - * - * @see java.lang.Object#equals(java.lang.Object) - */ - @Override - public boolean equals(Object obj) { - if (!super.equals(obj)) { - return false; - } - if (this == obj) { - return true; - } - if (!super.equals(obj)) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - XXContextEnricherDef other = (XXContextEnricherDef) obj; - if (defId == null) { - if (other.defId != null) { - return false; - } - } else if (!defId.equals(other.defId)) { - return false; - } - if (itemId == null) { - if (other.itemId != null) { - return false; - } - } else if (!itemId.equals(other.itemId)) { - return false; - } - if (enricher == null) { - if (other.enricher != null) { - return false; - } - } else if (!enricher.equals(other.enricher)) { - return false; - } - if (enricherOptions == null) { - if (other.enricherOptions != null) { - return false; - } - } else if (!enricherOptions.equals(other.enricherOptions)) { - return false; - } - if (id == null) { - if (other.id != null) { - return false; - } - } else if (!id.equals(other.id)) { - return false; - } - if (name == null) { - if (other.name != null) { - return false; - } - } else if (!name.equals(other.name)) { - return false; - } - if (order == null) { - if (other.order != null) { - return false; - } - } else if (!order.equals(other.order)) { - return false; - } - return true; - } + /** + * This method sets the value to the member attribute + * enricherOptions . You cannot set null to the attribute. + * + * @param enricherOptions Value to set member attribute enricherOptions + */ + public void setEnricherOptions(String enricherOptions) { + this.enricherOptions = enricherOptions; + } - /* - * (non-Javadoc) - * - * @see java.lang.Object#toString() - */ - @Override - public String toString() { - String str = "XXContextEnricherDef={"; - str += super.toString(); - str+=" [id=" + id + ", defId=" + defId + ", itemId=" + itemId - + ", name=" + name + ", enricher=" + enricherOptions - + ", enricherOptions=" + enricherOptions + ", order=" + order - + "]"; - str += "}"; - return str; - } + /** + * Returns the value for the member attribute order + * + * @return Integer - value of member attribute order . + */ + public Integer getOrder() { + return this.order; + } + /** + * This method sets the value to the member attribute order . You + * cannot set null to the attribute. + * + * @param order Value to set member attribute order + */ + public void setOrder(Integer order) { + this.order = order; + } } 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 index cdbf1d8e5e..f7a44720e8 100644 --- a/security-admin/src/main/java/org/apache/ranger/entity/XXCredentialStore.java +++ b/security-admin/src/main/java/org/apache/ranger/entity/XXCredentialStore.java @@ -17,13 +17,14 @@ * under the License. */ - package org.apache.ranger.entity; +package org.apache.ranger.entity; /** * Credential Store - * */ +import org.apache.ranger.common.AppConstants; + import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; @@ -32,134 +33,143 @@ import javax.persistence.SequenceGenerator; import javax.persistence.Table; -import org.apache.ranger.common.AppConstants; - +import java.util.Objects; @Entity -@Table(name="x_cred_store") +@Table(name = "x_cred_store") 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 - *
    - *
  • The maximum length for this attribute is 1024. - *
- * - */ - @Column(name="STORE_NAME" , nullable=false , length=1024) - protected String name; - - /** - * Description - *
    - *
  • The maximum length for this attribute is 4000. - *
- * - */ - @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 name. - * You cannot set null to the attribute. - * @param name Value to set member attribute name - */ - public void setName( String name ) { - this.name = name; - } - - /** - * Returns the value for the member attribute name - * @return String - value of member attribute name. - */ - public String getName( ) { - return this.name; - } - - /** - * This method sets the value to the member attribute description. - * You cannot set null to the attribute. - * @param description Value to set member attribute description - */ - public void setDescription( String description ) { - this.description = description; - } - - /** - * Returns the value for the member attribute description - * @return String - value of member attribute description. - */ - 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; - } - + 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; + + /** + * Name + *
    + *
  • The maximum length for this attribute is 1024. + *
+ */ + @Column(name = "STORE_NAME", nullable = false, length = 1024) + protected String name; + + /** + * Description + *
    + *
  • The maximum length for this attribute is 4000. + *
+ */ + @Column(name = "DESCR", nullable = false, length = 4000) + protected String description; + + /** + * Default constructor. This will set all the attributes to default value. + */ + public XXCredentialStore() { + } + + public static String getEnumName(String fieldName) { + //Later TODO + //return super.getEnumName(fieldName); + return null; + } + + @Override + public int getMyClassType() { + return AppConstants.CLASS_TYPE_XA_CRED_STORE; + } + + @Override + public String getMyDisplayValue() { + return getDescription(); + } + + @Override + public Long getId() { + return id; + } + + @Override + public void setId(Long id) { + this.id = id; + } + + @Override + public int hashCode() { + return super.hashCode(); + } + + /** + * Checks for all attributes except referenced db objects + * + * @return true if all attributes match + */ + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } else if (!super.equals(obj)) { + return false; + } + + XXCredentialStore other = (XXCredentialStore) obj; + + return Objects.equals(name, other.name) && + Objects.equals(description, other.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; + } + + /** + * Returns the value for the member attribute name + * + * @return String - value of member attribute name. + */ + public String getName() { + return this.name; + } + + /** + * This method sets the value to the member attribute name. + * You cannot set null to the attribute. + * + * @param name Value to set member attribute name + */ + public void setName(String name) { + this.name = name; + } + + /** + * Returns the value for the member attribute description + * + * @return String - value of member attribute description. + */ + public String getDescription() { + return this.description; + } + + /** + * This method sets the value to the member attribute description. + * You cannot set null to the attribute. + * + * @param description Value to set member attribute description + */ + public void setDescription(String description) { + this.description = description; + } } 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 index f70afcee1c..461124b785 100644 --- a/security-admin/src/main/java/org/apache/ranger/entity/XXDBBase.java +++ b/security-admin/src/main/java/org/apache/ranger/entity/XXDBBase.java @@ -17,15 +17,14 @@ * under the License. */ - package org.apache.ranger.entity; +package org.apache.ranger.entity; /** * Base JPA class with id, versionNumber and other common attributes - * */ -import java.util.Date; -import java.util.Objects; +import org.apache.ranger.common.AppConstants; +import org.apache.ranger.common.DateUtil; import javax.persistence.Column; import javax.persistence.EntityListeners; @@ -33,220 +32,221 @@ import javax.persistence.Temporal; import javax.persistence.TemporalType; -import org.apache.ranger.common.AppConstants; -import org.apache.ranger.common.DateUtil; - +import java.util.Date; +import java.util.Objects; -@MappedSuperclass @EntityListeners( org.apache.ranger.common.db.JPABeanCallbacks.class) +@MappedSuperclass +@EntityListeners(org.apache.ranger.common.db.JPABeanCallbacks.class) public abstract class XXDBBase implements java.io.Serializable { - private static final long serialVersionUID = 1L; - - - - /** - * Id for the object - *
    - *
  • This attribute is the Primary Key for this class
    . - *
- * - */ - - /** - * Date/Time creation of this user. - *
    - *
- * - */ - @Temporal(TemporalType.TIMESTAMP) - @Column(name="CREATE_TIME" ) - protected Date createTime = DateUtil.getUTCDate(); - - /** - * Date value. - *
    - *
- * - */ - @Temporal(TemporalType.TIMESTAMP) - @Column(name="UPDATE_TIME" ) - protected Date updateTime = DateUtil.getUTCDate(); - - /** - * Added by - *
    - *
- * - */ - @Column(name="ADDED_BY_ID" ) - protected Long addedByUserId; - - - /** - * Last updated by - *
    - *
- * - */ - @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 id. - * You cannot set null to the attribute. - * @param id Value to set member attribute id - */ - public abstract void setId( Long id ); - - /** - * Returns the value for the member attribute id - * @return Long - value of member attribute id. - */ - public abstract Long getId( ); - - /** - * This method sets the value to the member attribute createTime. - * You cannot set null to the attribute. - * @param createTime Value to set member attribute createTime - */ - public void setCreateTime( Date createTime ) { - this.createTime = createTime; - } - - /** - * Returns the value for the member attribute createTime - * @return Date - value of member attribute createTime. - */ - public Date getCreateTime( ) { - return this.createTime; - } - - /** - * This method sets the value to the member attribute updateTime. - * You cannot set null to the attribute. - * @param updateTime Value to set member attribute updateTime - */ - public void setUpdateTime( Date updateTime ) { - this.updateTime = updateTime; - } - - /** - * Returns the value for the member attribute updateTime - * @return Date - value of member attribute updateTime. - */ - public Date getUpdateTime( ) { - return this.updateTime; - } - - /** - * This method sets the value to the member attribute addedByUserId. - * You cannot set null to the attribute. - * @param addedByUserId Value to set member attribute addedByUserId - */ - public void setAddedByUserId( Long addedByUserId ) { - this.addedByUserId = addedByUserId; - } - - /** - * Returns the value for the member attribute addedByUserId - * @return Long - value of member attribute addedByUserId. - */ - public Long getAddedByUserId( ) { - return this.addedByUserId; - } - - - /** - * This method sets the value to the member attribute updatedByUserId. - * You cannot set null to the attribute. - * @param updatedByUserId Value to set member attribute updatedByUserId - */ - public void setUpdatedByUserId( Long updatedByUserId ) { - this.updatedByUserId = updatedByUserId; - } - - /** - * Returns the value for the member attribute updatedByUserId - * @return Long - value of member attribute updatedByUserId. - */ - 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; - } - - @Override - public int hashCode() { - return Objects.hash(createTime, updateTime, addedByUserId, updatedByUserId); - } - - /** - * 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; - } - - public static boolean equals(Object object1, Object object2) { + private static final long serialVersionUID = 1L; + + /** + * Id for the object + *
    + *
  • This attribute is the Primary Key for this class
    . + *
+ * + */ + + /** + * Date/Time creation of this user. + *
    + *
+ */ + @Temporal(TemporalType.TIMESTAMP) + @Column(name = "CREATE_TIME") + protected Date createTime = DateUtil.getUTCDate(); + + /** + * Date value. + *
    + *
+ */ + @Temporal(TemporalType.TIMESTAMP) + @Column(name = "UPDATE_TIME") + protected Date updateTime = DateUtil.getUTCDate(); + + /** + * Added by + *
    + *
+ */ + @Column(name = "ADDED_BY_ID") + protected Long addedByUserId; + + /** + * Last updated by + *
    + *
+ */ + @Column(name = "UPD_BY_ID") + protected Long updatedByUserId; + + /** + * Default constructor. This will set all the attributes to default value. + */ + public XXDBBase() { + } + + public static String getEnumName(String fieldName) { + //Later TODO + //return super.getEnumName(fieldName); + return null; + } + + public static boolean equals(Object object1, Object object2) { if (object1 == object2) { return true; } + if ((object1 == null) || (object2 == null)) { return false; } + return object1.equals(object2); } + public int getMyClassType() { + return AppConstants.CLASS_TYPE_NONE; + } + + public String getMyDisplayValue() { + return null; + } + + /** + * Returns the value for the member attribute id + * + * @return Long - value of member attribute id. + */ + public abstract Long getId(); + + /** + * This method sets the value to the member attribute id. + * You cannot set null to the attribute. + * + * @param id Value to set member attribute id + */ + public abstract void setId(Long id); + + /** + * Returns the value for the member attribute createTime + * + * @return Date - value of member attribute createTime. + */ + public Date getCreateTime() { + return this.createTime; + } + + /** + * This method sets the value to the member attribute createTime. + * You cannot set null to the attribute. + * + * @param createTime Value to set member attribute createTime + */ + public void setCreateTime(Date createTime) { + this.createTime = createTime; + } + + /** + * Returns the value for the member attribute updateTime + * + * @return Date - value of member attribute updateTime. + */ + public Date getUpdateTime() { + return this.updateTime; + } + + /** + * This method sets the value to the member attribute updateTime. + * You cannot set null to the attribute. + * + * @param updateTime Value to set member attribute updateTime + */ + public void setUpdateTime(Date updateTime) { + this.updateTime = updateTime; + } + + /** + * Returns the value for the member attribute addedByUserId + * + * @return Long - value of member attribute addedByUserId. + */ + public Long getAddedByUserId() { + return this.addedByUserId; + } + + /** + * This method sets the value to the member attribute addedByUserId. + * You cannot set null to the attribute. + * + * @param addedByUserId Value to set member attribute addedByUserId + */ + public void setAddedByUserId(Long addedByUserId) { + this.addedByUserId = addedByUserId; + } + + /** + * Returns the value for the member attribute updatedByUserId + * + * @return Long - value of member attribute updatedByUserId. + */ + public Long getUpdatedByUserId() { + return this.updatedByUserId; + } + + /** + * This method sets the value to the member attribute updatedByUserId. + * You cannot set null to the attribute. + * + * @param updatedByUserId Value to set member attribute updatedByUserId + */ + public void setUpdatedByUserId(Long updatedByUserId) { + this.updatedByUserId = updatedByUserId; + } + + @Override + public int hashCode() { + return Objects.hash(createTime, updateTime, addedByUserId, updatedByUserId); + } + + /** + * Checks for all attributes except referenced db objects + * + * @return true if all attributes match + */ + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } else if (obj == null) { + return false; + } else if (this.getClass() != obj.getClass()) { + return false; + } + + XXDBBase other = (XXDBBase) obj; + + return Objects.equals(createTime, other.createTime) && + Objects.equals(updateTime, other.updateTime) && + Objects.equals(addedByUserId, other.addedByUserId) && + Objects.equals(updatedByUserId, other.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; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/entity/XXDataHist.java b/security-admin/src/main/java/org/apache/ranger/entity/XXDataHist.java index 216eef2e0b..c3bd1c4b2d 100644 --- a/security-admin/src/main/java/org/apache/ranger/entity/XXDataHist.java +++ b/security-admin/src/main/java/org/apache/ranger/entity/XXDataHist.java @@ -18,455 +18,384 @@ */ package org.apache.ranger.entity; -import java.util.Date; +import org.apache.ranger.common.DateUtil; -import javax.persistence.*; +import javax.persistence.Cacheable; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.SequenceGenerator; +import javax.persistence.Table; +import javax.persistence.Temporal; +import javax.persistence.TemporalType; -import org.apache.ranger.common.DateUtil; +import java.util.Date; +import java.util.Objects; @Entity @Cacheable @Table(name = "x_data_hist") public class XXDataHist implements java.io.Serializable { - private static final long serialVersionUID = 1L; - /** - * id of the XXDataHist - *
    - *
- * - */ - @Id - @SequenceGenerator(name = "x_data_hist_SEQ", sequenceName = "x_data_hist_SEQ", allocationSize = 1) - @GeneratedValue(strategy = GenerationType.AUTO, generator = "x_data_hist_SEQ") - @Column(name = "id") - protected Long id; - - /** - * Date/Time creation of this user. - *
    - *
- * - */ - @Temporal(TemporalType.TIMESTAMP) - @Column(name = "CREATE_TIME") - protected Date createTime = DateUtil.getUTCDate(); - - /** - * Date value. - *
    - *
- * - */ - @Temporal(TemporalType.TIMESTAMP) - @Column(name = "UPDATE_TIME") - protected Date updateTime = DateUtil.getUTCDate(); - - /** - * version of the XXDataHist - *
    - *
- * - */ - @Column(name = "version") - protected Long version; - - /** - * type of the XXDataHist - *
    - *
- * - */ - @Column(name = "obj_guid") - protected String objectGuid; - - /** - * type of the XXDataHist - *
    - *
- * - */ - @Column(name = "obj_class_type") - protected Integer objectClassType; - - /** - * type of the XXDataHist - *
    - *
- * - */ - @Column(name = "obj_id") - protected Long objectId; - - /** - * name of the XXDataHist - *
    - *
- * - */ - @Column(name = "obj_name") - protected String objectName; - - /** - * action of the XXDataHist - *
    - *
- * - */ - @Column(name = "action") - protected String action; - - /** - * fromTime of the XXDataHist - *
    - *
- * - */ - @Temporal(TemporalType.TIMESTAMP) - @Column(name = "from_time") - protected Date fromTime; - - /** - * toTime of the XXDataHist - *
    - *
- * - */ - @Temporal(TemporalType.TIMESTAMP) - @Column(name = "to_time") - protected Date toTime; - - /** - * content of the XXDataHist - *
    - *
- * - */ - @Column(name = "content") - protected String content; - - /** - * This method sets the value to the member attribute id . You - * cannot set null to the attribute. - * - * @param id - * Value to set member attribute id - */ - public void setId(Long id) { - this.id = id; - } - - /** - * Returns the value for the member attribute id - * - * @return Date - value of member attribute id . - */ - public Long getId() { - return this.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; - } - - /** - * Returns the value for the member attribute version - * - * @return Date - value of member attribute version . - */ - public Long getVersion() { - return this.version; - } - - /** - * This method sets the value to the member attribute version . You - * cannot set null to the attribute. - * - * @param version - * Value to set member attribute version - */ - public void setVersion(Long version) { - this.version = version; - } - - /** - * This method sets the value to the member attribute action . You - * cannot set null to the attribute. - * - * @param action - * Value to set member attribute action - */ - public void setAction(String action) { - this.action = action; - } - - /** - * @return the objectGuid - */ - public String getObjectGuid() { - return objectGuid; - } - - /** - * @param objectGuid the objectGuid to set - */ - public void setObjectGuid(String objectGuid) { - this.objectGuid = objectGuid; - } - - /** - * @return the objectId - */ - public Long getObjectId() { - return objectId; - } - - /** - * @param objectId the objectId to set - */ - public void setObjectId(Long objectId) { - this.objectId = objectId; - } - - /** - * This method sets the value to the member attribute type . You - * cannot set null to the attribute. - * - * @param objectClassType - * Value to set member attribute type - */ - public void setObjectClassType(Integer objectClassType) { - this.objectClassType = objectClassType; - } - - /** - * Returns the value for the member attribute type - * - * @return Date - value of member attribute type . - */ - public Integer getObjectClassType() { - return this.objectClassType; - } - - /** - * This method sets the value to the member attribute name . You - * cannot set null to the attribute. - * - * @param name - * Value to set member attribute name - */ - public void setObjectName(String name) { - this.objectName = name; - } - - /** - * Returns the value for the member attribute name - * - * @return Date - value of member attribute name . - */ - public String getObjectName() { - return this.objectName; - } - - /** - * Returns the value for the member attribute action - * - * @return Date - value of member attribute action . - */ - public String getAction() { - return this.action; - } - - /** - * This method sets the value to the member attribute fromTime . You - * cannot set null to the attribute. - * - * @param fromTime - * Value to set member attribute fromTime - */ - public void setFromTime(Date fromTime) { - this.fromTime = fromTime; - } - - /** - * Returns the value for the member attribute fromTime - * - * @return Date - value of member attribute fromTime . - */ - public Date getFromTime() { - return this.fromTime; - } - - /** - * This method sets the value to the member attribute toTime . You - * cannot set null to the attribute. - * - * @param toTime - * Value to set member attribute toTime - */ - public void setToTime(Date toTime) { - this.toTime = toTime; - } - - /** - * Returns the value for the member attribute toTime - * - * @return Date - value of member attribute toTime . - */ - public Date getToTime() { - return this.toTime; - } - - /** - * This method sets the value to the member attribute content . You - * cannot set null to the attribute. - * - * @param content - * Value to set member attribute content - */ - public void setContent(String content) { - this.content = content; - } - - /** - * Returns the value for the member attribute content - * - * @return Date - value of member attribute content . - */ - public String getContent() { - return this.content; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#equals(java.lang.Object) - */ - @Override - public boolean equals(Object obj) { - if ( !super.equals(obj) ) { - return false; - } - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - XXDataHist other = (XXDataHist) obj; - if (action == null) { - if (other.action != null) { - return false; - } - } else if (!action.equals(other.action)) { - return false; - } - if (content == null) { - if (other.content != null) { - return false; - } - } else if (!content.equals(other.content)) { - return false; - } - if (createTime == null) { - if (other.createTime != null) { - return false; - } - } else if (!createTime.equals(other.createTime)) { - return false; - } - if (fromTime == null) { - if (other.fromTime != null) { - return false; - } - } else if (!fromTime.equals(other.fromTime)) { - return false; - } - if (id == null) { - if (other.id != null) { - return false; - } - } else if (!id.equals(other.id)) { - return false; - } - if (objectName == null) { - if (other.objectName != null) { - return false; - } - } else if (!objectName.equals(other.objectName)) { - return false; - } - if (toTime == null) { - if (other.toTime != null) { - return false; - } - } else if (!toTime.equals(other.toTime)) { - return false; - } - if (objectClassType == null) { - if (other.objectClassType != null) { - return false; - } - } else if (!objectClassType.equals(other.objectClassType)) { - return false; - } - if (updateTime == null) { - if (other.updateTime != null) { - return false; - } - } else if (!updateTime.equals(other.updateTime)) { - return false; - } - if (version == null) { - if (other.version != null) { - return false; - } - } else if (!version.equals(other.version)) { - return false; - } - return true; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#toString() - */ - @Override - public String toString() { - return "XXDataHist [id=" + id + ", createTime=" + createTime - + ", updateTime=" + updateTime + ", type=" + objectClassType + ", name=" - + objectName + ", version=" + version + ", action=" + action - + ", fromTime=" + fromTime + ", toTime=" + toTime - + ", content=" + content + "]"; - } - + private static final long serialVersionUID = 1L; + + /** + * id of the XXDataHist + *
    + *
+ */ + @Id + @SequenceGenerator(name = "x_data_hist_SEQ", sequenceName = "x_data_hist_SEQ", allocationSize = 1) + @GeneratedValue(strategy = GenerationType.AUTO, generator = "x_data_hist_SEQ") + @Column(name = "id") + protected Long id; + + /** + * Date/Time creation of this user. + *
    + *
+ */ + @Temporal(TemporalType.TIMESTAMP) + @Column(name = "CREATE_TIME") + protected Date createTime = DateUtil.getUTCDate(); + + /** + * Date value. + *
    + *
+ */ + @Temporal(TemporalType.TIMESTAMP) + @Column(name = "UPDATE_TIME") + protected Date updateTime = DateUtil.getUTCDate(); + + /** + * version of the XXDataHist + *
    + *
+ */ + @Column(name = "version") + protected Long version; + + /** + * type of the XXDataHist + *
    + *
+ */ + @Column(name = "obj_guid") + protected String objectGuid; + + /** + * type of the XXDataHist + *
    + *
+ */ + @Column(name = "obj_class_type") + protected Integer objectClassType; + + /** + * type of the XXDataHist + *
    + *
+ */ + @Column(name = "obj_id") + protected Long objectId; + + /** + * name of the XXDataHist + *
    + *
+ */ + @Column(name = "obj_name") + protected String objectName; + + /** + * action of the XXDataHist + *
    + *
+ */ + @Column(name = "action") + protected String action; + + /** + * fromTime of the XXDataHist + *
    + *
+ */ + @Temporal(TemporalType.TIMESTAMP) + @Column(name = "from_time") + protected Date fromTime; + + /** + * toTime of the XXDataHist + *
    + *
+ */ + @Temporal(TemporalType.TIMESTAMP) + @Column(name = "to_time") + protected Date toTime; + + /** + * content of the XXDataHist + *
    + *
+ */ + @Column(name = "content") + protected String content; + + /** + * Returns the value for the member attribute id + * + * @return Date - value of member attribute id . + */ + public Long getId() { + return this.id; + } + + /** + * This method sets the value to the member attribute id . You + * cannot set null to the attribute. + * + * @param id Value to set member attribute id + */ + 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; + } + + /** + * Returns the value for the member attribute version + * + * @return Date - value of member attribute version . + */ + public Long getVersion() { + return this.version; + } + + /** + * This method sets the value to the member attribute version . You + * cannot set null to the attribute. + * + * @param version Value to set member attribute version + */ + public void setVersion(Long version) { + this.version = version; + } + + /** + * @return the objectGuid + */ + public String getObjectGuid() { + return objectGuid; + } + + /** + * @param objectGuid the objectGuid to set + */ + public void setObjectGuid(String objectGuid) { + this.objectGuid = objectGuid; + } + + /** + * @return the objectId + */ + public Long getObjectId() { + return objectId; + } + + /** + * @param objectId the objectId to set + */ + public void setObjectId(Long objectId) { + this.objectId = objectId; + } + + /** + * Returns the value for the member attribute type + * + * @return Date - value of member attribute type . + */ + public Integer getObjectClassType() { + return this.objectClassType; + } + + /** + * This method sets the value to the member attribute type . You + * cannot set null to the attribute. + * + * @param objectClassType Value to set member attribute type + */ + public void setObjectClassType(Integer objectClassType) { + this.objectClassType = objectClassType; + } + + /** + * Returns the value for the member attribute name + * + * @return Date - value of member attribute name . + */ + public String getObjectName() { + return this.objectName; + } + + /** + * This method sets the value to the member attribute name . You + * cannot set null to the attribute. + * + * @param name Value to set member attribute name + */ + public void setObjectName(String name) { + this.objectName = name; + } + + /** + * Returns the value for the member attribute action + * + * @return Date - value of member attribute action . + */ + public String getAction() { + return this.action; + } + + /** + * This method sets the value to the member attribute action . You + * cannot set null to the attribute. + * + * @param action Value to set member attribute action + */ + public void setAction(String action) { + this.action = action; + } + + /** + * Returns the value for the member attribute fromTime + * + * @return Date - value of member attribute fromTime . + */ + public Date getFromTime() { + return this.fromTime; + } + + /** + * This method sets the value to the member attribute fromTime . You + * cannot set null to the attribute. + * + * @param fromTime Value to set member attribute fromTime + */ + public void setFromTime(Date fromTime) { + this.fromTime = fromTime; + } + + /** + * Returns the value for the member attribute toTime + * + * @return Date - value of member attribute toTime . + */ + public Date getToTime() { + return this.toTime; + } + + /** + * This method sets the value to the member attribute toTime . You + * cannot set null to the attribute. + * + * @param toTime Value to set member attribute toTime + */ + public void setToTime(Date toTime) { + this.toTime = toTime; + } + + /** + * Returns the value for the member attribute content + * + * @return Date - value of member attribute content . + */ + public String getContent() { + return this.content; + } + + /** + * This method sets the value to the member attribute content . You + * cannot set null to the attribute. + * + * @param content Value to set member attribute content + */ + public void setContent(String content) { + this.content = content; + } + + @Override + public int hashCode() { + return super.hashCode(); + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#equals(java.lang.Object) + */ + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } else if (obj == null) { + return false; + } else if (getClass() != obj.getClass()) { + return false; + } + + XXDataHist other = (XXDataHist) obj; + + return Objects.equals(action, other.action) && + Objects.equals(content, other.content) && + Objects.equals(createTime, other.createTime) && + Objects.equals(fromTime, other.fromTime) && + Objects.equals(id, other.id) && + Objects.equals(objectName, other.objectName) && + Objects.equals(toTime, other.toTime) && + Objects.equals(objectClassType, other.objectClassType) && + Objects.equals(updateTime, other.updateTime) && + Objects.equals(version, other.version); + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + return "XXDataHist [id=" + id + ", createTime=" + createTime + + ", updateTime=" + updateTime + ", type=" + objectClassType + ", name=" + + objectName + ", version=" + version + ", action=" + action + + ", fromTime=" + fromTime + ", toTime=" + toTime + + ", content=" + content + "]"; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/entity/XXDataMaskTypeDef.java b/security-admin/src/main/java/org/apache/ranger/entity/XXDataMaskTypeDef.java index bc893f3d93..2902e966b9 100644 --- a/security-admin/src/main/java/org/apache/ranger/entity/XXDataMaskTypeDef.java +++ b/security-admin/src/main/java/org/apache/ranger/entity/XXDataMaskTypeDef.java @@ -18,441 +18,362 @@ */ package org.apache.ranger.entity; -import javax.persistence.*; +import javax.persistence.Cacheable; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.SequenceGenerator; +import javax.persistence.Table; + +import java.util.Objects; @Entity @Cacheable @Table(name = "x_datamask_type_def") public class XXDataMaskTypeDef extends XXDBBase implements java.io.Serializable { - private static final long serialVersionUID = 1L; - /** - * id of the XXDataMaskTypeDef - *
    - *
- * - */ - @Id - @SequenceGenerator(name = "x_datamask_type_def_SEQ", sequenceName = "x_datamask_type_def_SEQ", allocationSize = 1) - @GeneratedValue(strategy = GenerationType.AUTO, generator = "x_datamask_type_def_SEQ") - @Column(name = "id") - protected Long id; - - /** - * defId of the XXDataMaskTypeDef - *
    - *
- * - */ - @Column(name = "def_id") - protected Long defId; - - /** - * itemId of the XXDataMaskTypeDef - *
    - *
- * - */ - @Column(name = "item_id") - protected Long itemId; - - /** - * name of the XXDataMaskTypeDef - *
    - *
- * - */ - @Column(name = "name") - protected String name; - - /** - * label of the XXDataMaskTypeDef - *
    - *
- * - */ - @Column(name = "label") - protected String label; - - /** - * description of the XXDataMaskTypeDef - *
    - *
- * - */ - @Column(name = "description") - protected String description; - - /** - * transformer of the XXDataMaskTypeDef - *
    - *
- * - */ - @Column(name = "transformer") - protected String transformer; - - /** - * dataMaskOptions of the XXDataMaskTypeDef - *
    - *
- * - */ - @Column(name = "datamask_options") - protected String dataMaskOptions; - - /** - * rbKeyLabel of the XXDataMaskTypeDef - *
    - *
- * - */ - @Column(name = "rb_key_label") - protected String rbKeyLabel; - - /** - * rbKeyDescription of the XXDataMaskTypeDef - *
    - *
- * - */ - @Column(name = "rb_key_description") - protected String rbKeyDescription; - - /** - * order of the XXDataMaskTypeDef - *
    - *
- * - */ - @Column(name = "sort_order") - protected Integer order; - - /** - * This method sets the value to the member attribute id . You - * cannot set null to the attribute. - * - * @param id - * Value to set member attribute id - */ - public void setId(Long id) { - this.id = id; - } - - /** - * Returns the value for the member attribute id - * - * @return Date - value of member attribute id . - */ - public Long getId() { - return this.id; - } - - /** - * This method sets the value to the member attribute defId . You - * cannot set null to the attribute. - * - * @param defId - * Value to set member attribute defId - */ - public void setDefid(Long defId) { - this.defId = defId; - } - - /** - * Returns the value for the member attribute defId - * - * @return Date - value of member attribute defId . - */ - public Long getDefid() { - return this.defId; - } - - /** - * This method sets the value to the member attribute itemId . You - * cannot set null to the attribute. - * - * @param itemId - * Value to set member attribute itemId - */ - public void setItemId(Long itemId) { - this.itemId = itemId; - } - - /** - * Returns the value for the member attribute itemId - * - * @return Long - value of member attribute itemId . - */ - public Long getItemId() { - return this.itemId; - } - - /** - * This method sets the value to the member attribute name . You - * cannot set null to the attribute. - * - * @param name - * Value to set member attribute name - */ - public void setName(String name) { - this.name = name; - } - - /** - * Returns the value for the member attribute name - * - * @return Date - value of member attribute name . - */ - public String getName() { - return this.name; - } - - /** - * This method sets the value to the member attribute label . You - * cannot set null to the attribute. - * - * @param label - * Value to set member attribute label - */ - public void setLabel(String label) { - this.label = label; - } - - /** - * Returns the value for the member attribute label - * - * @return Date - value of member attribute label . - */ - public String getLabel() { - return this.label; - } - - /** - * This method sets the value to the member attribute description . - * - * @param description - * Value to set member attribute description - */ - public void setDescription(String description) { - this.description = description; - } - - /** - * Returns the value for the member attribute description - * - * @return String - value of member attribute description . - */ - public String getDescription() { - return this.description; - } - - /** - * This method sets the value to the member attribute transformer . - * - * @param transformer - * Value to set member attribute transformer - */ - public void setTransformer(String transformer) { - this.transformer = transformer; - } - - /** - * Returns the value for the member attribute transformer - * - * @return String - value of member attribute transformer . - */ - public String getTransformer() { - return this.transformer; - } - - /** - * This method sets the value to the member attribute dataMaskOptions . - * - * @param dataMaskOptions - * Value to set member attribute dataMaskOptions - */ - public void setDataMaskOptions(String dataMaskOptions) { - this.dataMaskOptions = dataMaskOptions; - } - - /** - * Returns the value for the member attribute dataMaskOptions - * - * @return String - value of member attribute dataMaskOptions . - */ - public String getDataMaskOptions() { - return this.dataMaskOptions; - } - - /** - * This method sets the value to the member attribute rbKeyLabel . - * You cannot set null to the attribute. - * - * @param rbKeyLabel - * Value to set member attribute rbKeyLabel - */ - public void setRbkeylabel(String rbKeyLabel) { - this.rbKeyLabel = rbKeyLabel; - } - - /** - * Returns the value for the member attribute rbKeyLabel - * - * @return Date - value of member attribute rbKeyLabel . - */ - public String getRbkeylabel() { - return this.rbKeyLabel; - } - /** - * This method sets the value to the member attribute rbKeyDescription . - * - * @param rbKeyDescription - * Value to set member attribute rbKeyDescription - */ - public void setRbKeyDescription(String rbKeyDescription) { - this.rbKeyDescription = rbKeyDescription; - } - - /** - * Returns the value for the member attribute rbKeyDescription - * - * @return String - value of member attribute rbKeyDescription . - */ - public String getRbKeyDescription() { - return this.rbKeyDescription; - } - - /** - * This method sets the value to the member attribute order . You - * cannot set null to the attribute. - * - * @param order - * Value to set member attribute order - */ - public void setOrder(Integer order) { - this.order = order; - } - - /** - * Returns the value for the member attribute order - * - * @return Date - value of member attribute order . - */ - public Integer getOrder() { - return this.order; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#equals(java.lang.Object) - */ - @Override - public boolean equals(Object obj) { - if (!super.equals(obj)) { - return false; - } - if (this == obj) { - return true; - } - if (!super.equals(obj)) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - XXDataMaskTypeDef other = (XXDataMaskTypeDef) obj; - if (id == null) { - if (other.id != null) { - return false; - } - } else if (!id.equals(other.id)) { - return false; - } - if (defId == null) { - if (other.defId != null) { - return false; - } - } else if (!defId.equals(other.defId)) { - return false; - } - if (itemId == null) { - if (other.itemId != null) { - return false; - } - } else if (!itemId.equals(other.itemId)) { - return false; - } - if (name == null) { - if (other.name != null) { - return false; - } - } else if (!name.equals(other.name)) { - return false; - } - if (label == null) { - if (other.label != null) { - return false; - } - } else if (!label.equals(other.label)) { - return false; - } - if (description == null) { - if (other.description != null) { - return false; - } - } else if (!description.equals(other.description)) { - return false; - } - if (transformer == null) { - if (other.transformer != null) { - return false; - } - } else if (!transformer.equals(other.transformer)) { - return false; - } - if (dataMaskOptions == null) { - if (other.dataMaskOptions != null) { - return false; - } - } else if (!dataMaskOptions.equals(other.dataMaskOptions)) { - return false; - } - if (rbKeyLabel == null) { - if (other.rbKeyLabel != null) { - return false; - } - } else if (!rbKeyLabel.equals(other.rbKeyLabel)) { - return false; - } - if (rbKeyDescription == null) { - if (other.rbKeyDescription != null) { - return false; - } - } else if (!rbKeyDescription.equals(other.rbKeyDescription)) { - return false; - } - if (order == null) { - if (other.order != null) { - return false; - } - } else if (!order.equals(other.order)) { - return false; - } - return true; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#toString() - */ - @Override - public String toString() { - return "XXDataMaskTypeDef [" + super.toString() + " id=" + id - + ", defId=" + defId + ", itemId=" + itemId + ", name=" + name + ", label=" + label - + ", description=" + description + ", transformer=" + transformer + ", dataMaskOptions=" + dataMaskOptions - + ", rbKeyLabel=" + rbKeyLabel + ", rbKeyDescription=" + rbKeyDescription + ", order=" + order + "]"; - } - + private static final long serialVersionUID = 1L; + + /** + * id of the XXDataMaskTypeDef + *
    + *
+ */ + @Id + @SequenceGenerator(name = "x_datamask_type_def_SEQ", sequenceName = "x_datamask_type_def_SEQ", allocationSize = 1) + @GeneratedValue(strategy = GenerationType.AUTO, generator = "x_datamask_type_def_SEQ") + @Column(name = "id") + protected Long id; + + /** + * defId of the XXDataMaskTypeDef + *
    + *
+ */ + @Column(name = "def_id") + protected Long defId; + + /** + * itemId of the XXDataMaskTypeDef + *
    + *
+ */ + @Column(name = "item_id") + protected Long itemId; + + /** + * name of the XXDataMaskTypeDef + *
    + *
+ */ + @Column(name = "name") + protected String name; + + /** + * label of the XXDataMaskTypeDef + *
    + *
+ */ + @Column(name = "label") + protected String label; + + /** + * description of the XXDataMaskTypeDef + *
    + *
+ */ + @Column(name = "description") + protected String description; + + /** + * transformer of the XXDataMaskTypeDef + *
    + *
+ */ + @Column(name = "transformer") + protected String transformer; + + /** + * dataMaskOptions of the XXDataMaskTypeDef + *
    + *
+ */ + @Column(name = "datamask_options") + protected String dataMaskOptions; + + /** + * rbKeyLabel of the XXDataMaskTypeDef + *
    + *
+ */ + @Column(name = "rb_key_label") + protected String rbKeyLabel; + + /** + * rbKeyDescription of the XXDataMaskTypeDef + *
    + *
+ */ + @Column(name = "rb_key_description") + protected String rbKeyDescription; + + /** + * order of the XXDataMaskTypeDef + *
    + *
+ */ + @Column(name = "sort_order") + protected Integer order; + + /** + * Returns the value for the member attribute id + * + * @return Date - value of member attribute id . + */ + public Long getId() { + return this.id; + } + + /** + * This method sets the value to the member attribute id . You + * cannot set null to the attribute. + * + * @param id Value to set member attribute id + */ + public void setId(Long id) { + this.id = id; + } + + @Override + public int hashCode() { + return super.hashCode(); + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#equals(java.lang.Object) + */ + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } else if (!super.equals(obj)) { + return false; + } + + XXDataMaskTypeDef other = (XXDataMaskTypeDef) obj; + + return Objects.equals(id, other.id) && + Objects.equals(defId, other.defId) && + Objects.equals(itemId, other.itemId) && + Objects.equals(name, other.name) && + Objects.equals(label, other.label) && + Objects.equals(description, other.description) && + Objects.equals(transformer, other.transformer) && + Objects.equals(dataMaskOptions, other.dataMaskOptions) && + Objects.equals(rbKeyLabel, other.rbKeyLabel) && + Objects.equals(rbKeyDescription, other.rbKeyDescription) && + Objects.equals(order, other.order); + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + return "XXDataMaskTypeDef [" + super.toString() + " id=" + id + + ", defId=" + defId + ", itemId=" + itemId + ", name=" + name + ", label=" + label + + ", description=" + description + ", transformer=" + transformer + ", dataMaskOptions=" + dataMaskOptions + + ", rbKeyLabel=" + rbKeyLabel + ", rbKeyDescription=" + rbKeyDescription + ", order=" + order + "]"; + } + + /** + * Returns the value for the member attribute defId + * + * @return Date - value of member attribute defId . + */ + public Long getDefid() { + return this.defId; + } + + /** + * This method sets the value to the member attribute defId . You + * cannot set null to the attribute. + * + * @param defId Value to set member attribute defId + */ + public void setDefid(Long defId) { + this.defId = defId; + } + + /** + * Returns the value for the member attribute itemId + * + * @return Long - value of member attribute itemId . + */ + public Long getItemId() { + return this.itemId; + } + + /** + * This method sets the value to the member attribute itemId . You + * cannot set null to the attribute. + * + * @param itemId Value to set member attribute itemId + */ + public void setItemId(Long itemId) { + this.itemId = itemId; + } + + /** + * Returns the value for the member attribute name + * + * @return Date - value of member attribute name . + */ + public String getName() { + return this.name; + } + + /** + * This method sets the value to the member attribute name . You + * cannot set null to the attribute. + * + * @param name Value to set member attribute name + */ + public void setName(String name) { + this.name = name; + } + + /** + * Returns the value for the member attribute label + * + * @return Date - value of member attribute label . + */ + public String getLabel() { + return this.label; + } + + /** + * This method sets the value to the member attribute label . You + * cannot set null to the attribute. + * + * @param label Value to set member attribute label + */ + public void setLabel(String label) { + this.label = label; + } + + /** + * Returns the value for the member attribute description + * + * @return String - value of member attribute description . + */ + public String getDescription() { + return this.description; + } + + /** + * This method sets the value to the member attribute description . + * + * @param description Value to set member attribute description + */ + public void setDescription(String description) { + this.description = description; + } + + /** + * Returns the value for the member attribute transformer + * + * @return String - value of member attribute transformer . + */ + public String getTransformer() { + return this.transformer; + } + + /** + * This method sets the value to the member attribute transformer . + * + * @param transformer Value to set member attribute transformer + */ + public void setTransformer(String transformer) { + this.transformer = transformer; + } + + /** + * Returns the value for the member attribute dataMaskOptions + * + * @return String - value of member attribute dataMaskOptions . + */ + public String getDataMaskOptions() { + return this.dataMaskOptions; + } + + /** + * This method sets the value to the member attribute dataMaskOptions . + * + * @param dataMaskOptions Value to set member attribute dataMaskOptions + */ + public void setDataMaskOptions(String dataMaskOptions) { + this.dataMaskOptions = dataMaskOptions; + } + + /** + * Returns the value for the member attribute rbKeyLabel + * + * @return Date - value of member attribute rbKeyLabel . + */ + public String getRbkeylabel() { + return this.rbKeyLabel; + } + + /** + * This method sets the value to the member attribute rbKeyLabel . + * You cannot set null to the attribute. + * + * @param rbKeyLabel Value to set member attribute rbKeyLabel + */ + public void setRbkeylabel(String rbKeyLabel) { + this.rbKeyLabel = rbKeyLabel; + } + + /** + * Returns the value for the member attribute rbKeyDescription + * + * @return String - value of member attribute rbKeyDescription . + */ + public String getRbKeyDescription() { + return this.rbKeyDescription; + } + + /** + * This method sets the value to the member attribute rbKeyDescription . + * + * @param rbKeyDescription Value to set member attribute rbKeyDescription + */ + public void setRbKeyDescription(String rbKeyDescription) { + this.rbKeyDescription = rbKeyDescription; + } + + /** + * Returns the value for the member attribute order + * + * @return Date - value of member attribute order . + */ + public Integer getOrder() { + return this.order; + } + + /** + * This method sets the value to the member attribute order . You + * cannot set null to the attribute. + * + * @param order Value to set member attribute order + */ + public void setOrder(Integer order) { + this.order = order; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/entity/XXEnumDef.java b/security-admin/src/main/java/org/apache/ranger/entity/XXEnumDef.java index a5806630e4..8eef90de83 100644 --- a/security-admin/src/main/java/org/apache/ranger/entity/XXEnumDef.java +++ b/security-admin/src/main/java/org/apache/ranger/entity/XXEnumDef.java @@ -18,229 +18,197 @@ */ package org.apache.ranger.entity; -import javax.persistence.*; +import javax.persistence.Cacheable; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.SequenceGenerator; +import javax.persistence.Table; + +import java.util.Objects; @Entity @Cacheable @Table(name = "x_enum_def") public class XXEnumDef extends XXDBBase implements java.io.Serializable { - private static final long serialVersionUID = 1L; - /** - * id of the XXEnumDef - *
    - *
- * - */ - @Id - @SequenceGenerator(name = "x_enum_def_SEQ", sequenceName = "x_enum_def_SEQ", allocationSize = 1) - @GeneratedValue(strategy = GenerationType.AUTO, generator = "x_enum_def_SEQ") - @Column(name = "id") - protected Long id; - - /** - * defId of the XXEnumDef - *
    - *
- * - */ - @Column(name = "def_id") - protected Long defId; - - /** - * itemId of the XXEnumDef - *
    - *
- * - */ - @Column(name = "item_id") - protected Long itemId; - - /** - * name of the XXEnumDef - *
    - *
- * - */ - @Column(name = "name") - protected String name; - - /** - * defaultIndex of the XXEnumDef - *
    - *
- * - */ - @Column(name = "default_index") - protected Integer defaultIndex; - - /** - * This method sets the value to the member attribute id . You - * cannot set null to the attribute. - * - * @param id - * Value to set member attribute id - */ - public void setId(Long id) { - this.id = id; - } - - /** - * Returns the value for the member attribute id - * - * @return Date - value of member attribute id . - */ - public Long getId() { - return this.id; - } - - /** - * This method sets the value to the member attribute defId . You - * cannot set null to the attribute. - * - * @param defId - * Value to set member attribute defId - */ - public void setDefid(Long defId) { - this.defId = defId; - } - - /** - * Returns the value for the member attribute defId - * - * @return Date - value of member attribute defId . - */ - public Long getDefid() { - return this.defId; - } - - /** - * This method sets the value to the member attribute itemId . You - * cannot set null to the attribute. - * - * @param defId - * Value to set member attribute itemId - */ - public void setItemId(Long itemId) { - this.itemId = itemId; - } - - /** - * Returns the value for the member attribute itemId - * - * @return Long - value of member attribute itemId . - */ - public Long getItemId() { - return this.itemId; - } - - /** - * This method sets the value to the member attribute name . You - * cannot set null to the attribute. - * - * @param name - * Value to set member attribute name - */ - public void setName(String name) { - this.name = name; - } - - /** - * Returns the value for the member attribute name - * - * @return Date - value of member attribute name . - */ - public String getName() { - return this.name; - } - - /** - * This method sets the value to the member attribute defaultIndex . - * You cannot set null to the attribute. - * - * @param defaultIndex - * Value to set member attribute defaultIndex - */ - public void setDefaultindex(Integer defaultIndex) { - this.defaultIndex = defaultIndex; - } - - /** - * Returns the value for the member attribute defaultIndex - * - * @return Date - value of member attribute defaultIndex . - */ - public Integer getDefaultindex() { - return this.defaultIndex; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#equals(java.lang.Object) - */ - @Override - public boolean equals(Object obj) { - if (!super.equals(obj)) { - return false; - } - if (this == obj) { - return true; - } - if (!super.equals(obj)) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - XXEnumDef other = (XXEnumDef) obj; - if (defId == null) { - if (other.defId != null) { - return false; - } - } else if (!defId.equals(other.defId)) { - return false; - } - if (itemId == null) { - if (other.itemId != null) { - return false; - } - } else if (!itemId.equals(other.itemId)) { - return false; - } - if (defaultIndex == null) { - if (other.defaultIndex != null) { - return false; - } - } else if (!defaultIndex.equals(other.defaultIndex)) { - return false; - } - if (id == null) { - if (other.id != null) { - return false; - } - } else if (!id.equals(other.id)) { - return false; - } - if (name == null) { - if (other.name != null) { - return false; - } - } else if (!name.equals(other.name)) { - return false; - } - return true; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#toString() - */ - @Override - public String toString() { - return "XXEnumDef [" + super.toString() + " id=" + id + ", defId=" - + defId + ", itemId=" + itemId + ", name=" + name + ", defaultIndex=" + defaultIndex - + "]"; - } - + private static final long serialVersionUID = 1L; + + /** + * id of the XXEnumDef + *
    + *
+ */ + @Id + @SequenceGenerator(name = "x_enum_def_SEQ", sequenceName = "x_enum_def_SEQ", allocationSize = 1) + @GeneratedValue(strategy = GenerationType.AUTO, generator = "x_enum_def_SEQ") + @Column(name = "id") + protected Long id; + + /** + * defId of the XXEnumDef + *
    + *
+ */ + @Column(name = "def_id") + protected Long defId; + + /** + * itemId of the XXEnumDef + *
    + *
+ */ + @Column(name = "item_id") + protected Long itemId; + + /** + * name of the XXEnumDef + *
    + *
+ */ + @Column(name = "name") + protected String name; + + /** + * defaultIndex of the XXEnumDef + *
    + *
+ */ + @Column(name = "default_index") + protected Integer defaultIndex; + + /** + * Returns the value for the member attribute id + * + * @return Date - value of member attribute id . + */ + public Long getId() { + return this.id; + } + + /** + * This method sets the value to the member attribute id . You + * cannot set null to the attribute. + * + * @param id Value to set member attribute id + */ + public void setId(Long id) { + this.id = id; + } + + @Override + public int hashCode() { + return super.hashCode(); + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#equals(java.lang.Object) + */ + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } else if (!super.equals(obj)) { + return false; + } + + XXEnumDef other = (XXEnumDef) obj; + + return Objects.equals(defId, other.defId) && + Objects.equals(itemId, other.itemId) && + Objects.equals(defaultIndex, other.defaultIndex) && + Objects.equals(id, other.id) && + Objects.equals(name, other.name); + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + return "XXEnumDef [" + super.toString() + " id=" + id + ", defId=" + + defId + ", itemId=" + itemId + ", name=" + name + ", defaultIndex=" + defaultIndex + + "]"; + } + + /** + * Returns the value for the member attribute defId + * + * @return Date - value of member attribute defId . + */ + public Long getDefid() { + return this.defId; + } + + /** + * This method sets the value to the member attribute defId . You + * cannot set null to the attribute. + * + * @param defId Value to set member attribute defId + */ + public void setDefid(Long defId) { + this.defId = defId; + } + + /** + * Returns the value for the member attribute itemId + * + * @return Long - value of member attribute itemId . + */ + public Long getItemId() { + return this.itemId; + } + + /** + * This method sets the value to the member attribute itemId . You + * cannot set null to the attribute. + * + * @param itemId Value to set member attribute itemId + */ + public void setItemId(Long itemId) { + this.itemId = itemId; + } + + /** + * Returns the value for the member attribute name + * + * @return Date - value of member attribute name . + */ + public String getName() { + return this.name; + } + + /** + * This method sets the value to the member attribute name . You + * cannot set null to the attribute. + * + * @param name Value to set member attribute name + */ + public void setName(String name) { + this.name = name; + } + + /** + * Returns the value for the member attribute defaultIndex + * + * @return Date - value of member attribute defaultIndex . + */ + public Integer getDefaultindex() { + return this.defaultIndex; + } + + /** + * This method sets the value to the member attribute defaultIndex . + * You cannot set null to the attribute. + * + * @param defaultIndex Value to set member attribute defaultIndex + */ + public void setDefaultindex(Integer defaultIndex) { + this.defaultIndex = defaultIndex; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/entity/XXEnumElementDef.java b/security-admin/src/main/java/org/apache/ranger/entity/XXEnumElementDef.java index 555984f96b..c12ae922bc 100644 --- a/security-admin/src/main/java/org/apache/ranger/entity/XXEnumElementDef.java +++ b/security-admin/src/main/java/org/apache/ranger/entity/XXEnumElementDef.java @@ -18,295 +18,252 @@ */ package org.apache.ranger.entity; -import javax.persistence.*; +import javax.persistence.Cacheable; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.SequenceGenerator; +import javax.persistence.Table; + +import java.util.Objects; @Entity @Cacheable @Table(name = "x_enum_element_def") public class XXEnumElementDef extends XXDBBase implements java.io.Serializable { - private static final long serialVersionUID = 1L; - /** - * id of the XXEnumDefElement - *
    - *
- * - */ - @Id - @SequenceGenerator(name = "x_enum_element_def_SEQ", sequenceName = "x_enum_element_def_SEQ", allocationSize = 1) - @GeneratedValue(strategy = GenerationType.AUTO, generator = "x_enum_element_def_SEQ") - @Column(name = "id") - protected Long id; + private static final long serialVersionUID = 1L; + /** + * id of the XXEnumDefElement + *
    + *
+ */ + @Id + @SequenceGenerator(name = "x_enum_element_def_SEQ", sequenceName = "x_enum_element_def_SEQ", allocationSize = 1) + @GeneratedValue(strategy = GenerationType.AUTO, generator = "x_enum_element_def_SEQ") + @Column(name = "id") + protected Long id; + + /** + * enumDefId of the XXEnumDefElement + *
    + *
+ */ + @Column(name = "enum_def_id") + protected Long enumDefId; + + /** + * itemId of the XXEnumDefElement + *
    + *
+ */ + @Column(name = "item_id") + protected Long itemId; - /** - * enumDefId of the XXEnumDefElement - *
    - *
- * - */ - @Column(name = "enum_def_id") - protected Long enumDefId; + /** + * name of the XXEnumDefElement + *
    + *
+ */ + @Column(name = "name") + protected String name; - /** - * itemId of the XXEnumDefElement - *
    - *
- * - */ - @Column(name = "item_id") - protected Long itemId; + /** + * label of the XXEnumDefElement + *
    + *
+ */ + @Column(name = "label") + protected String label; - /** - * name of the XXEnumDefElement - *
    - *
- * - */ - @Column(name = "name") - protected String name; + /** + * rbKeyLabel of the XXEnumDefElement + *
    + *
+ */ + @Column(name = "rb_key_label") + protected String rbKeyLabel; - /** - * label of the XXEnumDefElement - *
    - *
- * - */ - @Column(name = "label") - protected String label; + /** + * order of the XXEnumDefElement + *
    + *
+ */ + @Column(name = "sort_order") + protected Integer order; - /** - * rbKeyLabel of the XXEnumDefElement - *
    - *
- * - */ - @Column(name = "rb_key_label") - protected String rbKeyLabel; + /** + * Returns the value for the member attribute id + * + * @return Date - value of member attribute id . + */ + public Long getId() { + return this.id; + } - /** - * order of the XXEnumDefElement - *
    - *
- * - */ - @Column(name = "sort_order") - protected Integer order; + /** + * This method sets the value to the member attribute id . You + * cannot set null to the attribute. + * + * @param id Value to set member attribute id + */ + public void setId(Long id) { + this.id = id; + } - /** - * This method sets the value to the member attribute id . You - * cannot set null to the attribute. - * - * @param id - * Value to set member attribute id - */ - public void setId(Long id) { - this.id = id; - } + @Override + public int hashCode() { + return super.hashCode(); + } - /** - * Returns the value for the member attribute id - * - * @return Date - value of member attribute id . - */ - public Long getId() { - return this.id; - } + /* + * (non-Javadoc) + * + * @see java.lang.Object#equals(java.lang.Object) + */ + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } else if (!super.equals(obj)) { + return false; + } - /** - * This method sets the value to the member attribute enumDefId . - * You cannot set null to the attribute. - * - * @param enumDefId - * Value to set member attribute enumDefId - */ - public void setEnumdefid(Long enumDefId) { - this.enumDefId = enumDefId; - } + XXEnumElementDef other = (XXEnumElementDef) obj; - /** - * Returns the value for the member attribute enumDefId - * - * @return Date - value of member attribute enumDefId . - */ - public Long getEnumdefid() { - return this.enumDefId; - } + return Objects.equals(enumDefId, other.enumDefId) && + Objects.equals(id, other.id) && + Objects.equals(label, other.label) && + Objects.equals(name, other.name) && + Objects.equals(order, other.order) && + Objects.equals(rbKeyLabel, other.rbKeyLabel); + } - /** - * This method sets the value to the member attribute itemId . - * You cannot set null to the attribute. - * - * @param itemId - * Value to set member attribute itemId - */ - public void setItemId(Long itemId) { - this.itemId = itemId; - } + /* + * (non-Javadoc) + * + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + return "XXEnumElementDef [" + super.toString() + " id=" + id + + ", enumDefId=" + enumDefId + "itemId=" + itemId + ", name=" + name + ", label=" + + label + ", rbKeyLabel=" + rbKeyLabel + ", order=" + order + + "]"; + } - /** - * Returns the value for the member attribute itemId - * - * @return Long - value of member attribute itemId . - */ - public Long getItemId() { - return this.itemId; - } + /** + * Returns the value for the member attribute enumDefId + * + * @return Date - value of member attribute enumDefId . + */ + public Long getEnumdefid() { + return this.enumDefId; + } - /** - * This method sets the value to the member attribute name . You - * cannot set null to the attribute. - * - * @param name - * Value to set member attribute name - */ - public void setName(String name) { - this.name = name; - } + /** + * This method sets the value to the member attribute enumDefId . + * You cannot set null to the attribute. + * + * @param enumDefId Value to set member attribute enumDefId + */ + public void setEnumdefid(Long enumDefId) { + this.enumDefId = enumDefId; + } - /** - * Returns the value for the member attribute name - * - * @return Date - value of member attribute name . - */ - public String getName() { - return this.name; - } + /** + * Returns the value for the member attribute itemId + * + * @return Long - value of member attribute itemId . + */ + public Long getItemId() { + return this.itemId; + } - /** - * This method sets the value to the member attribute label . You - * cannot set null to the attribute. - * - * @param label - * Value to set member attribute label - */ - public void setLabel(String label) { - this.label = label; - } + /** + * This method sets the value to the member attribute itemId . + * You cannot set null to the attribute. + * + * @param itemId Value to set member attribute itemId + */ + public void setItemId(Long itemId) { + this.itemId = itemId; + } - /** - * Returns the value for the member attribute label - * - * @return Date - value of member attribute label . - */ - public String getLabel() { - return this.label; - } + /** + * Returns the value for the member attribute name + * + * @return Date - value of member attribute name . + */ + public String getName() { + return this.name; + } - /** - * This method sets the value to the member attribute rbKeyLabel . - * You cannot set null to the attribute. - * - * @param rbKeyLabel - * Value to set member attribute rbKeyLabel - */ - public void setRbkeylabel(String rbKeyLabel) { - this.rbKeyLabel = rbKeyLabel; - } + /** + * This method sets the value to the member attribute name . You + * cannot set null to the attribute. + * + * @param name Value to set member attribute name + */ + public void setName(String name) { + this.name = name; + } - /** - * Returns the value for the member attribute rbKeyLabel - * - * @return Date - value of member attribute rbKeyLabel . - */ - public String getRbkeylabel() { - return this.rbKeyLabel; - } + /** + * Returns the value for the member attribute label + * + * @return Date - value of member attribute label . + */ + public String getLabel() { + return this.label; + } - /** - * This method sets the value to the member attribute order . You - * cannot set null to the attribute. - * - * @param order - * Value to set member attribute order - */ - public void setOrder(Integer order) { - this.order = order; - } + /** + * This method sets the value to the member attribute label . You + * cannot set null to the attribute. + * + * @param label Value to set member attribute label + */ + public void setLabel(String label) { + this.label = label; + } - /** - * Returns the value for the member attribute order - * - * @return Date - value of member attribute order . - */ - public Integer getOrder() { - return this.order; - } + /** + * Returns the value for the member attribute rbKeyLabel + * + * @return Date - value of member attribute rbKeyLabel . + */ + public String getRbkeylabel() { + return this.rbKeyLabel; + } - /* - * (non-Javadoc) - * - * @see java.lang.Object#equals(java.lang.Object) - */ - @Override - public boolean equals(Object obj) { - if (!super.equals(obj)) { - return false; - } - if (this == obj) { - return true; - } - if (!super.equals(obj)) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - XXEnumElementDef other = (XXEnumElementDef) obj; - if (enumDefId == null) { - if (other.enumDefId != null) { - return false; - } - } else if (!enumDefId.equals(other.enumDefId)) { - return false; - } - if (id == null) { - if (other.id != null) { - return false; - } - } else if (!id.equals(other.id)) { - return false; - } - if (label == null) { - if (other.label != null) { - return false; - } - } else if (!label.equals(other.label)) { - return false; - } - if (name == null) { - if (other.name != null) { - return false; - } - } else if (!name.equals(other.name)) { - return false; - } - if (order == null) { - if (other.order != null) { - return false; - } - } else if (!order.equals(other.order)) { - return false; - } - if (rbKeyLabel == null) { - if (other.rbKeyLabel != null) { - return false; - } - } else if (!rbKeyLabel.equals(other.rbKeyLabel)) { - return false; - } - return true; - } + /** + * This method sets the value to the member attribute rbKeyLabel . + * You cannot set null to the attribute. + * + * @param rbKeyLabel Value to set member attribute rbKeyLabel + */ + public void setRbkeylabel(String rbKeyLabel) { + this.rbKeyLabel = rbKeyLabel; + } - /* - * (non-Javadoc) - * - * @see java.lang.Object#toString() - */ - @Override - public String toString() { - return "XXEnumElementDef [" + super.toString() + " id=" + id - + ", enumDefId=" + enumDefId + "itemId=" + itemId + ", name=" + name + ", label=" - + label + ", rbKeyLabel=" + rbKeyLabel + ", order=" + order - + "]"; - } + /** + * Returns the value for the member attribute order + * + * @return Date - value of member attribute order . + */ + public Integer getOrder() { + return this.order; + } + /** + * This method sets the value to the member attribute order . You + * cannot set null to the attribute. + * + * @param order Value to set member attribute order + */ + public void setOrder(Integer order) { + this.order = order; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/entity/XXGdsDataShare.java b/security-admin/src/main/java/org/apache/ranger/entity/XXGdsDataShare.java index 3ab96e29c6..36ab4de01e 100644 --- a/security-admin/src/main/java/org/apache/ranger/entity/XXGdsDataShare.java +++ b/security-admin/src/main/java/org/apache/ranger/entity/XXGdsDataShare.java @@ -21,14 +21,23 @@ import org.apache.ranger.common.AppConstants; -import javax.persistence.*; +import javax.persistence.Cacheable; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.SequenceGenerator; +import javax.persistence.Table; +import javax.persistence.Version; import javax.xml.bind.annotation.XmlRootElement; + import java.io.Serializable; import java.util.Objects; @Entity @Cacheable -@Table(name="x_gds_data_share") +@Table(name = "x_gds_data_share") @XmlRootElement public class XXGdsDataShare extends XXDBBase implements Serializable { private static final long serialVersionUID = 1L; @@ -82,71 +91,132 @@ public class XXGdsDataShare extends XXDBBase implements Serializable { @Column(name = "additional_info") protected String additionalInfo; + public String getGuid() { + return guid; + } - @Override - public void setId(Long id) { this.id = id; } - - @Override - public Long getId() { return id; } + public void setGuid(String guid) { + this.guid = guid; + } - public String getGuid() { return guid; } + public Long getVersion() { + return version; + } - public void setGuid(String guid) { this.guid = guid; } + public void setVersion(Long version) { + this.version = version; + } - public Long getVersion() { return version; } + public Boolean getIsEnabled() { + return isEnabled; + } - public void setVersion(Long version) { this.version = version; } + public void setIsEnabled(Boolean isEnabled) { + this.isEnabled = isEnabled; + } - public Boolean getIsEnabled() { return isEnabled; } + public Long getServiceId() { + return serviceId; + } - public void setIsEnabled(Boolean isEnabled) { this.isEnabled = isEnabled; } + public void setServiceId(Long serviceId) { + this.serviceId = serviceId; + } - public Long getServiceId() { return serviceId; } + public Long getZoneId() { + return zoneId; + } - public void setServiceId(Long serviceId) { this.serviceId = serviceId; } + public void setZoneId(Long zoneId) { + this.zoneId = zoneId; + } - public Long getZoneId() { return zoneId; } + public String getName() { + return name; + } - public void setZoneId(Long zoneId) { this.zoneId = zoneId; } + public void setName(String name) { + this.name = name; + } - public String getName() { return name; } + public String getDescription() { + return description; + } - public void setName(String name) { this.name = name; } + public void setDescription(String description) { + this.description = description; + } - public String getDescription() { return description; } + public String getAcl() { + return acl; + } - public void setDescription(String description) { this.description = description; } + public void setAcl(String acl) { + this.acl = acl; + } - public String getAcl() { return acl; } + public String getConditionExpr() { + return conditionExpr; + } - public void setAcl(String acl) { this.acl = acl; } + public void setConditionExpr(String conditionExpr) { + this.conditionExpr = conditionExpr; + } - public String getConditionExpr() { return conditionExpr; } + public String getDefaultAccessTypes() { + return defaultAccessTypes; + } - public void setConditionExpr(String conditionExpr) { this.conditionExpr = conditionExpr; } + public void setDefaultAccessTypes(String defaultAccessTypes) { + this.defaultAccessTypes = defaultAccessTypes; + } - public String getDefaultAccessTypes() { return defaultAccessTypes; } + public String getDefaultTagMasks() { + return defaultTagMasks; + } - public void setDefaultAccessTypes(String defaultAccessTypes) { this.defaultAccessTypes = defaultAccessTypes; } + public void setDefaultTagMasks(String defaultMasks) { + this.defaultTagMasks = defaultMasks; + } - public String getDefaultTagMasks() { return defaultTagMasks; } + public String getTermsOfUse() { + return termsOfUse; + } - public void setDefaultTagMasks(String defaultMasks) {this.defaultTagMasks = defaultMasks; } + public void setTermsOfUse(String termsOfUse) { + this.termsOfUse = termsOfUse; + } - public String getTermsOfUse() { return termsOfUse; } + public String getOptions() { + return options; + } - public void setTermsOfUse(String termsOfUse) { this.termsOfUse = termsOfUse; } + public void setOptions(String options) { + this.options = options; + } - public String getOptions() { return options; } + public String getAdditionalInfo() { + return additionalInfo; + } - public void setOptions(String options) { this.options = options; } + public void setAdditionalInfo(String additionalInfo) { + this.additionalInfo = additionalInfo; + } - public String getAdditionalInfo() { return additionalInfo; } + @Override + public int getMyClassType() { + return AppConstants.CLASS_TYPE_GDS_DATA_SHARE; + } - public void setAdditionalInfo(String additionalInfo) { this.additionalInfo = additionalInfo; } + @Override + public Long getId() { + return id; + } @Override - public int getMyClassType() { return AppConstants.CLASS_TYPE_GDS_DATA_SHARE; } + public void setId(Long id) { + this.id = id; + } @Override public int hashCode() { @@ -159,27 +229,25 @@ public boolean equals(Object obj) { return true; } else if (!super.equals(obj)) { return false; - } else if (getClass() != obj.getClass()) { - return false; } XXGdsDataShare other = (XXGdsDataShare) obj; return Objects.equals(id, other.id) && - Objects.equals(guid, other.guid) && - Objects.equals(version, other.version) && - Objects.equals(isEnabled, other.isEnabled) && - Objects.equals(serviceId, other.serviceId) && - Objects.equals(zoneId, other.zoneId) && - Objects.equals(name, other.name) && - Objects.equals(description, other.description) && - Objects.equals(acl, other.acl) && - Objects.equals(conditionExpr, other.conditionExpr) && - Objects.equals(defaultAccessTypes, other.defaultAccessTypes) && - Objects.equals(defaultTagMasks, other.defaultTagMasks) && - Objects.equals(termsOfUse, other.termsOfUse) && - Objects.equals(options, other.options) && - Objects.equals(additionalInfo, other.additionalInfo); + Objects.equals(guid, other.guid) && + Objects.equals(version, other.version) && + Objects.equals(isEnabled, other.isEnabled) && + Objects.equals(serviceId, other.serviceId) && + Objects.equals(zoneId, other.zoneId) && + Objects.equals(name, other.name) && + Objects.equals(description, other.description) && + Objects.equals(acl, other.acl) && + Objects.equals(conditionExpr, other.conditionExpr) && + Objects.equals(defaultAccessTypes, other.defaultAccessTypes) && + Objects.equals(defaultTagMasks, other.defaultTagMasks) && + Objects.equals(termsOfUse, other.termsOfUse) && + Objects.equals(options, other.options) && + Objects.equals(additionalInfo, other.additionalInfo); } @Override @@ -189,23 +257,23 @@ public String toString() { public StringBuilder toString(StringBuilder sb) { sb.append("XXGdsDataShare={ ") - .append(super.toString()).append(" ") - .append("id={").append(id).append("} ") - .append("guid={").append(guid).append("} ") - .append("version={").append(version).append("} ") - .append("isEnabled={").append(isEnabled).append("} ") - .append("serviceId={").append(serviceId).append("} ") - .append("zoneId={").append(zoneId).append("} ") - .append("name={").append(name).append("} ") - .append("description={").append(description).append("} ") - .append("acl={").append(acl).append("} ") - .append("conditionExpr={").append(conditionExpr).append("} ") - .append("defaultAccessTypes={").append(defaultAccessTypes).append("} ") - .append("defaultMasks={").append(defaultTagMasks).append("} ") - .append("termsOfUse={").append(termsOfUse).append("} ") - .append("options={").append(options).append("} ") - .append("additionalInfo={").append(additionalInfo).append("} ") - .append(" }"); + .append(super.toString()).append(" ") + .append("id={").append(id).append("} ") + .append("guid={").append(guid).append("} ") + .append("version={").append(version).append("} ") + .append("isEnabled={").append(isEnabled).append("} ") + .append("serviceId={").append(serviceId).append("} ") + .append("zoneId={").append(zoneId).append("} ") + .append("name={").append(name).append("} ") + .append("description={").append(description).append("} ") + .append("acl={").append(acl).append("} ") + .append("conditionExpr={").append(conditionExpr).append("} ") + .append("defaultAccessTypes={").append(defaultAccessTypes).append("} ") + .append("defaultMasks={").append(defaultTagMasks).append("} ") + .append("termsOfUse={").append(termsOfUse).append("} ") + .append("options={").append(options).append("} ") + .append("additionalInfo={").append(additionalInfo).append("} ") + .append(" }"); return sb; } diff --git a/security-admin/src/main/java/org/apache/ranger/entity/XXGdsDataShareInDataset.java b/security-admin/src/main/java/org/apache/ranger/entity/XXGdsDataShareInDataset.java index 5c06e152cf..7526b11980 100644 --- a/security-admin/src/main/java/org/apache/ranger/entity/XXGdsDataShareInDataset.java +++ b/security-admin/src/main/java/org/apache/ranger/entity/XXGdsDataShareInDataset.java @@ -21,14 +21,23 @@ import org.apache.ranger.common.AppConstants; -import javax.persistence.*; +import javax.persistence.Cacheable; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.SequenceGenerator; +import javax.persistence.Table; +import javax.persistence.Version; import javax.xml.bind.annotation.XmlRootElement; + import java.io.Serializable; import java.util.Objects; @Entity @Cacheable -@Table(name="x_gds_data_share_in_dataset") +@Table(name = "x_gds_data_share_in_dataset") @XmlRootElement public class XXGdsDataShareInDataset extends XXDBBase implements Serializable { private static final long serialVersionUID = 1L; @@ -76,62 +85,116 @@ public class XXGdsDataShareInDataset extends XXDBBase implements Serializable { @Column(name = "approver_id") protected Long approverId; - @Override - public void setId(Long id) { this.id = id; } + public String getGuid() { + return guid; + } - @Override - public Long getId() { return id; } + public void setGuid(String guid) { + this.guid = guid; + } - public String getGuid() { return guid; } + public Long getVersion() { + return version; + } - public void setGuid(String guid) { this.guid = guid; } + public void setVersion(Long version) { + this.version = version; + } - public Long getVersion() { return version; } + public Boolean getIsEnabled() { + return isEnabled; + } - public void setVersion(Long version) { this.version = version; } + public void setIsEnabled(Boolean isEnabled) { + this.isEnabled = isEnabled; + } - public Boolean getIsEnabled() { return isEnabled; } + public String getDescription() { + return description; + } - public void setIsEnabled(Boolean isEnabled) { this.isEnabled = isEnabled; } + public void setDescription(String description) { + this.description = description; + } - public String getDescription() { return description; } + public Long getDataShareId() { + return dataShareId; + } - public void setDescription(String description) { this.description = description; } + public void setDataShareId(Long dataShareId) { + this.dataShareId = dataShareId; + } - public Long getDataShareId() { return dataShareId; } + public Long getDatasetId() { + return datasetId; + } - public void setDataShareId(Long dataShareId) { this.dataShareId = dataShareId; } + public void setDatasetId(Long datasetId) { + this.datasetId = datasetId; + } - public Long getDatasetId() { return datasetId; } + public Short getStatus() { + return status; + } - public void setDatasetId(Long datasetId) { this.datasetId = datasetId; } + public void setStatus(Short status) { + this.status = status; + } - public Short getStatus() { return status; } + public String getValidityPeriod() { + return validityPeriod; + } - public void setStatus(Short status) { this.status = status; } + public void setValidityPeriod(String validityPeriod) { + this.validityPeriod = validityPeriod; + } - public String getValidityPeriod() { return validityPeriod; } + public String getProfiles() { + return profiles; + } - public void setValidityPeriod(String validityPeriod) { this.validityPeriod = validityPeriod; } + public void setProfiles(String profiles) { + this.profiles = profiles; + } - public String getProfiles() { return profiles; } + public String getOptions() { + return options; + } - public void setProfiles(String profiles) { this.profiles = profiles; } + public void setOptions(String options) { + this.options = options; + } - public String getOptions() { return options; } + public String getAdditionalInfo() { + return additionalInfo; + } - public void setOptions(String options) { this.options = options; } + public void setAdditionalInfo(String additionalInfo) { + this.additionalInfo = additionalInfo; + } - public String getAdditionalInfo() { return additionalInfo; } + public Long getApproverId() { + return approverId; + } - public void setAdditionalInfo(String additionalInfo) { this.additionalInfo = additionalInfo; } + public void setApproverId(Long approverId) { + this.approverId = approverId; + } - public Long getApproverId() { return approverId; } + @Override + public int getMyClassType() { + return AppConstants.CLASS_TYPE_GDS_DATA_SHARE_IN_DATASET; + } - public void setApproverId(Long approverId) { this.approverId = approverId; } + @Override + public Long getId() { + return id; + } @Override - public int getMyClassType() { return AppConstants.CLASS_TYPE_GDS_DATA_SHARE_IN_DATASET; } + public void setId(Long id) { + this.id = id; + } @Override public int hashCode() { @@ -142,8 +205,6 @@ public int hashCode() { public boolean equals(Object obj) { if (this == obj) { return true; - } else if (getClass() != obj.getClass()) { - return false; } else if (!super.equals(obj)) { return false; } @@ -151,17 +212,17 @@ public boolean equals(Object obj) { XXGdsDataShareInDataset other = (XXGdsDataShareInDataset) obj; return Objects.equals(id, other.id) && - Objects.equals(guid, other.guid) && - Objects.equals(version, other.version) && - Objects.equals(isEnabled, other.isEnabled) && - Objects.equals(dataShareId, other.dataShareId) && - Objects.equals(datasetId, other.datasetId) && - Objects.equals(status, other.status) && - Objects.equals(validityPeriod, other.validityPeriod) && - Objects.equals(profiles, other.profiles) && - Objects.equals(options, other.options) && - Objects.equals(additionalInfo, other.additionalInfo) && - Objects.equals(approverId, other.approverId); + Objects.equals(guid, other.guid) && + Objects.equals(version, other.version) && + Objects.equals(isEnabled, other.isEnabled) && + Objects.equals(dataShareId, other.dataShareId) && + Objects.equals(datasetId, other.datasetId) && + Objects.equals(status, other.status) && + Objects.equals(validityPeriod, other.validityPeriod) && + Objects.equals(profiles, other.profiles) && + Objects.equals(options, other.options) && + Objects.equals(additionalInfo, other.additionalInfo) && + Objects.equals(approverId, other.approverId); } @Override @@ -171,22 +232,21 @@ public String toString() { public StringBuilder toString(StringBuilder sb) { sb.append("XXDataShareInDataset={ ") - .append(super.toString() + "} ") - .append("id={").append(id).append("} ") - .append("guid={").append(guid).append("} ") - .append("version={").append(version).append("} ") - .append("isEnabled={").append(isEnabled).append("} ") - .append("dataShareId={").append(dataShareId).append("} ") - .append("datasetId={").append(datasetId).append("} ") - .append("status={").append(status).append("} ") - .append("validityPeriod={").append(validityPeriod).append("} ") - .append("profiles={").append(profiles).append("} ") - .append("options={").append(options).append("} ") - .append("additionalInfo={").append(additionalInfo).append("} ") - .append("approverId={").append(approverId).append("} ") - .append(" }"); + .append(super.toString() + "} ") + .append("id={").append(id).append("} ") + .append("guid={").append(guid).append("} ") + .append("version={").append(version).append("} ") + .append("isEnabled={").append(isEnabled).append("} ") + .append("dataShareId={").append(dataShareId).append("} ") + .append("datasetId={").append(datasetId).append("} ") + .append("status={").append(status).append("} ") + .append("validityPeriod={").append(validityPeriod).append("} ") + .append("profiles={").append(profiles).append("} ") + .append("options={").append(options).append("} ") + .append("additionalInfo={").append(additionalInfo).append("} ") + .append("approverId={").append(approverId).append("} ") + .append(" }"); return sb; } - } diff --git a/security-admin/src/main/java/org/apache/ranger/entity/XXGdsDataset.java b/security-admin/src/main/java/org/apache/ranger/entity/XXGdsDataset.java index 7a1404d229..e4aa5f11ec 100644 --- a/security-admin/src/main/java/org/apache/ranger/entity/XXGdsDataset.java +++ b/security-admin/src/main/java/org/apache/ranger/entity/XXGdsDataset.java @@ -21,14 +21,23 @@ import org.apache.ranger.common.AppConstants; -import javax.persistence.*; +import javax.persistence.Cacheable; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.SequenceGenerator; +import javax.persistence.Table; +import javax.persistence.Version; import javax.xml.bind.annotation.XmlRootElement; + import java.io.Serializable; import java.util.Objects; @Entity @Cacheable -@Table(name="x_gds_dataset") +@Table(name = "x_gds_dataset") @XmlRootElement public class XXGdsDataset extends XXDBBase implements Serializable { private static final long serialVersionUID = 1L; @@ -76,48 +85,77 @@ public class XXGdsDataset extends XXDBBase implements Serializable { @Column(name = "keywords") protected String keywords; + public String getGuid() { + return guid; + } - @Override - public void setId(Long id) { this.id = id; } - - @Override - public Long getId() { return id; } - - public String getGuid() { return guid; } - - public void setGuid(String guid) { this.guid = guid; } + public void setGuid(String guid) { + this.guid = guid; + } - public Long getVersion() { return version; } + public Long getVersion() { + return version; + } - public void setVersion(Long version) { this.version = version; } + public void setVersion(Long version) { + this.version = version; + } - public Boolean getIsEnabled() { return isEnabled; } + public Boolean getIsEnabled() { + return isEnabled; + } - public void setIsEnabled(Boolean isEnabled) { this.isEnabled = isEnabled; } + public void setIsEnabled(Boolean isEnabled) { + this.isEnabled = isEnabled; + } - public String getName() { return name; } + public String getName() { + return name; + } - public void setName(String name) { this.name = name; } + public void setName(String name) { + this.name = name; + } - public String getDescription() { return description; } + public String getDescription() { + return description; + } - public void setDescription(String description) { this.description = description; } + public void setDescription(String description) { + this.description = description; + } - public String getAcl() { return acl; } + public String getAcl() { + return acl; + } - public void setAcl(String acl) { this.acl = acl; } + public void setAcl(String acl) { + this.acl = acl; + } - public String getTermsOfUse() { return termsOfUse; } + public String getTermsOfUse() { + return termsOfUse; + } - public void setTermsOfUse(String termsOfUse) { this.termsOfUse = termsOfUse; } + public void setTermsOfUse(String termsOfUse) { + this.termsOfUse = termsOfUse; + } - public String getOptions() { return options; } + public String getOptions() { + return options; + } - public void setOptions(String options) { this.options = options; } + public void setOptions(String options) { + this.options = options; + } - public String getAdditionalInfo() { return additionalInfo; } + public String getAdditionalInfo() { + return additionalInfo; + } - public void setAdditionalInfo(String additionalInfo) { this.additionalInfo = additionalInfo; } + public void setAdditionalInfo(String additionalInfo) { + this.additionalInfo = additionalInfo; + } public String getValiditySchedule() { return validitySchedule; @@ -144,7 +182,19 @@ public void setKeywords(String keywords) { } @Override - public int getMyClassType() { return AppConstants.CLASS_TYPE_GDS_DATASET; } + public int getMyClassType() { + return AppConstants.CLASS_TYPE_GDS_DATASET; + } + + @Override + public Long getId() { + return id; + } + + @Override + public void setId(Long id) { + this.id = id; + } @Override public int hashCode() { @@ -158,25 +208,23 @@ public boolean equals(Object obj) { return true; } else if (!super.equals(obj)) { return false; - } else if (getClass() != obj.getClass()) { - return false; } XXGdsDataset other = (XXGdsDataset) obj; return Objects.equals(id, other.id) && - Objects.equals(guid, other.guid) && - Objects.equals(version, other.version) && - Objects.equals(isEnabled, other.isEnabled) && - Objects.equals(name, other.name) && - Objects.equals(description, other.description) && - Objects.equals(acl, other.acl) && - Objects.equals(termsOfUse, other.termsOfUse) && - Objects.equals(options, other.options) && - Objects.equals(additionalInfo, other.additionalInfo) && - Objects.equals(validitySchedule, other.validitySchedule) && - Objects.equals(labels, other.labels) && - Objects.equals(keywords, other.keywords); + Objects.equals(guid, other.guid) && + Objects.equals(version, other.version) && + Objects.equals(isEnabled, other.isEnabled) && + Objects.equals(name, other.name) && + Objects.equals(description, other.description) && + Objects.equals(acl, other.acl) && + Objects.equals(termsOfUse, other.termsOfUse) && + Objects.equals(options, other.options) && + Objects.equals(additionalInfo, other.additionalInfo) && + Objects.equals(validitySchedule, other.validitySchedule) && + Objects.equals(labels, other.labels) && + Objects.equals(keywords, other.keywords); } @Override @@ -186,22 +234,22 @@ public String toString() { public StringBuilder toString(StringBuilder sb) { sb.append("XXGdsDataset={ ") - .append(super.toString()).append(" ") - .append("id={").append(id).append("} ") - .append("guid={").append(guid).append("} ") - .append("version={").append(version).append("} ") - .append("isEnabled={").append(isEnabled).append("} ") - .append("name={").append(name).append("} ") - .append("description={").append(description).append("} ") - .append("condition={").append(acl).append("} ") - .append("acl={").append(acl).append("} ") - .append("termsOfUse={").append(termsOfUse).append("} ") - .append("options={").append(options).append("} ") - .append("additionalInfo={").append(additionalInfo).append("} ") - .append("validitySchedule={").append(validitySchedule).append("} ") - .append("labels={").append(labels).append("} ") - .append("keywords={").append(keywords).append("} ") - .append(" }"); + .append(super.toString()).append(" ") + .append("id={").append(id).append("} ") + .append("guid={").append(guid).append("} ") + .append("version={").append(version).append("} ") + .append("isEnabled={").append(isEnabled).append("} ") + .append("name={").append(name).append("} ") + .append("description={").append(description).append("} ") + .append("condition={").append(acl).append("} ") + .append("acl={").append(acl).append("} ") + .append("termsOfUse={").append(termsOfUse).append("} ") + .append("options={").append(options).append("} ") + .append("additionalInfo={").append(additionalInfo).append("} ") + .append("validitySchedule={").append(validitySchedule).append("} ") + .append("labels={").append(labels).append("} ") + .append("keywords={").append(keywords).append("} ") + .append(" }"); return sb; } diff --git a/security-admin/src/main/java/org/apache/ranger/entity/XXGdsDatasetInProject.java b/security-admin/src/main/java/org/apache/ranger/entity/XXGdsDatasetInProject.java index 49bb4ab6bd..b2a7f9a01d 100644 --- a/security-admin/src/main/java/org/apache/ranger/entity/XXGdsDatasetInProject.java +++ b/security-admin/src/main/java/org/apache/ranger/entity/XXGdsDatasetInProject.java @@ -21,14 +21,23 @@ import org.apache.ranger.common.AppConstants; -import javax.persistence.*; +import javax.persistence.Cacheable; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.SequenceGenerator; +import javax.persistence.Table; +import javax.persistence.Version; import javax.xml.bind.annotation.XmlRootElement; + import java.io.Serializable; import java.util.Objects; @Entity @Cacheable -@Table(name="x_gds_dataset_in_project") +@Table(name = "x_gds_dataset_in_project") @XmlRootElement public class XXGdsDatasetInProject extends XXDBBase implements Serializable { private static final long serialVersionUID = 1L; @@ -76,62 +85,116 @@ public class XXGdsDatasetInProject extends XXDBBase implements Serializable { @Column(name = "approver_id") protected Long approverId; - @Override - public void setId(Long id) { this.id = id; } + public String getGuid() { + return guid; + } - @Override - public Long getId() { return id; } + public void setGuid(String guid) { + this.guid = guid; + } - public String getGuid() { return guid; } + public Long getVersion() { + return version; + } - public void setGuid(String guid) { this.guid = guid; } + public void setVersion(Long version) { + this.version = version; + } - public Long getVersion() { return version; } + public Boolean getIsEnabled() { + return isEnabled; + } - public void setVersion(Long version) { this.version = version; } + public void setIsEnabled(Boolean isEnabled) { + this.isEnabled = isEnabled; + } - public Boolean getIsEnabled() { return isEnabled; } + public String getDescription() { + return description; + } - public void setIsEnabled(Boolean isEnabled) { this.isEnabled = isEnabled; } + public void setDescription(String description) { + this.description = description; + } - public String getDescription() { return description; } + public Long getDatasetId() { + return datasetId; + } - public void setDescription(String description) { this.description = description; } + public void setDatasetId(Long datasetId) { + this.datasetId = datasetId; + } - public Long getDatasetId() { return datasetId; } + public Long getProjectId() { + return projectId; + } - public void setDatasetId(Long datasetId) { this.datasetId = datasetId; } + public void setProjectId(Long projectId) { + this.projectId = projectId; + } - public Long getProjectId() { return projectId; } + public Short getStatus() { + return status; + } - public void setProjectId(Long projectId) { this.projectId = projectId; } + public void setStatus(Short status) { + this.status = status; + } - public Short getStatus() { return status; } + public String getValidityPeriod() { + return validityPeriod; + } - public void setStatus(Short status) { this.status = status; } + public void setValidityPeriod(String validityPeriod) { + this.validityPeriod = validityPeriod; + } - public String getValidityPeriod() { return validityPeriod; } + public String getProfiles() { + return profiles; + } - public void setValidityPeriod(String validityPeriod) { this.validityPeriod = validityPeriod; } + public void setProfiles(String profiles) { + this.profiles = profiles; + } - public String getProfiles() { return profiles; } + public String getOptions() { + return options; + } - public void setProfiles(String profiles) { this.profiles = profiles; } + public void setOptions(String options) { + this.options = options; + } - public String getOptions() { return options; } + public String getAdditionalInfo() { + return additionalInfo; + } - public void setOptions(String options) { this.options = options; } + public void setAdditionalInfo(String additionalInfo) { + this.additionalInfo = additionalInfo; + } - public String getAdditionalInfo() { return additionalInfo; } + public Long getApproverId() { + return approverId; + } - public void setAdditionalInfo(String additionalInfo) { this.additionalInfo = additionalInfo; } + public void setApproverId(Long approverId) { + this.approverId = approverId; + } - public Long getApproverId() { return approverId; } + @Override + public int getMyClassType() { + return AppConstants.CLASS_TYPE_GDS_DATASET_IN_PROJECT; + } - public void setApproverId(Long approverId) { this.approverId = approverId; } + @Override + public Long getId() { + return id; + } @Override - public int getMyClassType() { return AppConstants.CLASS_TYPE_GDS_DATASET_IN_PROJECT; } + public void setId(Long id) { + this.id = id; + } @Override public int hashCode() { @@ -142,8 +205,6 @@ public int hashCode() { public boolean equals(Object obj) { if (this == obj) { return true; - } else if (getClass() != obj.getClass()) { - return false; } else if (!super.equals(obj)) { return false; } @@ -151,18 +212,18 @@ public boolean equals(Object obj) { XXGdsDatasetInProject other = (XXGdsDatasetInProject) obj; return Objects.equals(id, other.id) && - Objects.equals(guid, other.guid) && - Objects.equals(version, other.version) && - Objects.equals(isEnabled, other.isEnabled) && - Objects.equals(description, other.description) && - Objects.equals(datasetId, other.datasetId) && - Objects.equals(projectId, other.projectId) && - Objects.equals(status, other.status) && - Objects.equals(validityPeriod, other.validityPeriod) && - Objects.equals(profiles, other.profiles) && - Objects.equals(options, other.options) && - Objects.equals(additionalInfo, other.additionalInfo) && - Objects.equals(approverId, other.approverId); + Objects.equals(guid, other.guid) && + Objects.equals(version, other.version) && + Objects.equals(isEnabled, other.isEnabled) && + Objects.equals(description, other.description) && + Objects.equals(datasetId, other.datasetId) && + Objects.equals(projectId, other.projectId) && + Objects.equals(status, other.status) && + Objects.equals(validityPeriod, other.validityPeriod) && + Objects.equals(profiles, other.profiles) && + Objects.equals(options, other.options) && + Objects.equals(additionalInfo, other.additionalInfo) && + Objects.equals(approverId, other.approverId); } @Override @@ -172,21 +233,21 @@ public String toString() { public StringBuilder toString(StringBuilder sb) { sb.append("XXDataShareInDataset={ ") - .append(super.toString() + "} ") - .append("id={").append(id).append("} ") - .append("guid={").append(guid).append("} ") - .append("version={").append(version).append("} ") - .append("isEnabled={").append(isEnabled).append("} ") - .append("description={").append(description).append("} ") - .append("datasetId={").append(datasetId).append("} ") - .append("dataShareId={").append(projectId).append("} ") - .append("status={").append(status).append("} ") - .append("validityPeriod={").append(validityPeriod).append("} ") - .append("profiles={").append(profiles).append("} ") - .append("options={").append(options).append("} ") - .append("additionalInfo={").append(additionalInfo).append("} ") - .append("approverId={").append(approverId).append("} ") - .append(" }"); + .append(super.toString() + "} ") + .append("id={").append(id).append("} ") + .append("guid={").append(guid).append("} ") + .append("version={").append(version).append("} ") + .append("isEnabled={").append(isEnabled).append("} ") + .append("description={").append(description).append("} ") + .append("datasetId={").append(datasetId).append("} ") + .append("dataShareId={").append(projectId).append("} ") + .append("status={").append(status).append("} ") + .append("validityPeriod={").append(validityPeriod).append("} ") + .append("profiles={").append(profiles).append("} ") + .append("options={").append(options).append("} ") + .append("additionalInfo={").append(additionalInfo).append("} ") + .append("approverId={").append(approverId).append("} ") + .append(" }"); return sb; } diff --git a/security-admin/src/main/java/org/apache/ranger/entity/XXGdsDatasetPolicyMap.java b/security-admin/src/main/java/org/apache/ranger/entity/XXGdsDatasetPolicyMap.java index 2d79c94c38..b76f48ba4a 100644 --- a/security-admin/src/main/java/org/apache/ranger/entity/XXGdsDatasetPolicyMap.java +++ b/security-admin/src/main/java/org/apache/ranger/entity/XXGdsDatasetPolicyMap.java @@ -21,14 +21,22 @@ import org.apache.ranger.common.AppConstants; -import javax.persistence.*; +import javax.persistence.Cacheable; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.SequenceGenerator; +import javax.persistence.Table; import javax.xml.bind.annotation.XmlRootElement; + import java.io.Serializable; import java.util.Objects; @Entity @Cacheable -@Table(name="x_gds_dataset_policy_map") +@Table(name = "x_gds_dataset_policy_map") @XmlRootElement public class XXGdsDatasetPolicyMap implements Serializable { private static final long serialVersionUID = 1L; @@ -45,26 +53,40 @@ public class XXGdsDatasetPolicyMap implements Serializable { @Column(name = "policy_id") protected Long policyId; - public XXGdsDatasetPolicyMap() { } + public XXGdsDatasetPolicyMap() {} public XXGdsDatasetPolicyMap(Long datasetId, Long policyId) { setDatasetId(datasetId); setPolicyId(policyId); } - public void setId(Long id) { this.id = id; } + public Long getId() { + return id; + } - public Long getId() { return id; } + public void setId(Long id) { + this.id = id; + } - public Long getDatasetId() { return datasetId; } + public Long getDatasetId() { + return datasetId; + } - public void setDatasetId(Long datasetId) { this.datasetId = datasetId; } + public void setDatasetId(Long datasetId) { + this.datasetId = datasetId; + } - public Long getPolicyId() { return policyId; } + public Long getPolicyId() { + return policyId; + } - public void setPolicyId(Long policyId) { this.policyId = policyId; } + public void setPolicyId(Long policyId) { + this.policyId = policyId; + } - public int getMyClassType() { return AppConstants.CLASS_TYPE_GDS_DATASET_POLICY_MAP; } + public int getMyClassType() { + return AppConstants.CLASS_TYPE_GDS_DATASET_POLICY_MAP; + } @Override public int hashCode() { @@ -75,8 +97,6 @@ public int hashCode() { public boolean equals(Object obj) { if (this == obj) { return true; - } else if (getClass() != obj.getClass()) { - return false; } else if (!super.equals(obj)) { return false; } @@ -84,8 +104,8 @@ public boolean equals(Object obj) { XXGdsDatasetPolicyMap other = (XXGdsDatasetPolicyMap) obj; return Objects.equals(id, other.id) && - Objects.equals(datasetId, other.datasetId) && - Objects.equals(policyId, other.policyId); + Objects.equals(datasetId, other.datasetId) && + Objects.equals(policyId, other.policyId); } @Override @@ -95,11 +115,11 @@ public String toString() { public StringBuilder toString(StringBuilder sb) { sb.append("XXGdsDatasetPolicyMap={ ") - .append(super.toString() + "} ") - .append("id={").append(id).append("} ") - .append("datasetId={").append(datasetId).append("} ") - .append("policyId={").append(policyId).append("} ") - .append(" }"); + .append(super.toString() + "} ") + .append("id={").append(id).append("} ") + .append("datasetId={").append(datasetId).append("} ") + .append("policyId={").append(policyId).append("} ") + .append(" }"); return sb; } diff --git a/security-admin/src/main/java/org/apache/ranger/entity/XXGdsProject.java b/security-admin/src/main/java/org/apache/ranger/entity/XXGdsProject.java index 566fdac96a..0919e32c94 100644 --- a/security-admin/src/main/java/org/apache/ranger/entity/XXGdsProject.java +++ b/security-admin/src/main/java/org/apache/ranger/entity/XXGdsProject.java @@ -21,14 +21,23 @@ import org.apache.ranger.common.AppConstants; -import javax.persistence.*; +import javax.persistence.Cacheable; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.SequenceGenerator; +import javax.persistence.Table; +import javax.persistence.Version; import javax.xml.bind.annotation.XmlRootElement; + import java.io.Serializable; import java.util.Objects; @Entity @Cacheable -@Table(name="x_gds_project") +@Table(name = "x_gds_project") @XmlRootElement public class XXGdsProject extends XXDBBase implements Serializable { private static final long serialVersionUID = 1L; @@ -67,50 +76,92 @@ public class XXGdsProject extends XXDBBase implements Serializable { @Column(name = "additional_info") protected String additionalInfo; - @Override - public void setId(Long id) { this.id = id; } + public String getGuid() { + return guid; + } - @Override - public Long getId() { return id; } + public void setGuid(String guid) { + this.guid = guid; + } - public String getGuid() { return guid; } + public Long getVersion() { + return version; + } - public void setGuid(String guid) { this.guid = guid; } + public void setVersion(Long version) { + this.version = version; + } - public Long getVersion() { return version; } + public Boolean getIsEnabled() { + return isEnabled; + } - public void setVersion(Long version) { this.version = version; } + public void setIsEnabled(Boolean isEnabled) { + this.isEnabled = isEnabled; + } - public Boolean getIsEnabled() { return isEnabled; } + public String getName() { + return name; + } - public void setIsEnabled(Boolean isEnabled) { this.isEnabled = isEnabled; } + public void setName(String name) { + this.name = name; + } - public String getName() { return name; } + public String getDescription() { + return description; + } - public void setName(String name) { this.name = name; } + public void setDescription(String description) { + this.description = description; + } - public String getDescription() { return description; } + public String getAcl() { + return acl; + } - public void setDescription(String description) { this.description = description; } + public void setAcl(String acl) { + this.acl = acl; + } - public String getAcl() { return acl; } + public String getTermsOfUse() { + return termsOfUse; + } - public void setAcl(String acl) { this.acl = acl; } + public void setTermsOfUse(String termsOfUse) { + this.termsOfUse = termsOfUse; + } - public String getTermsOfUse() { return termsOfUse; } + public String getOptions() { + return options; + } - public void setTermsOfUse(String termsOfUse) { this.termsOfUse = termsOfUse; } + public void setOptions(String options) { + this.options = options; + } - public String getOptions() { return options; } + public String getAdditionalInfo() { + return additionalInfo; + } - public void setOptions(String options) { this.options = options; } + public void setAdditionalInfo(String additionalInfo) { + this.additionalInfo = additionalInfo; + } - public String getAdditionalInfo() { return additionalInfo; } + @Override + public int getMyClassType() { + return AppConstants.CLASS_TYPE_GDS_PROJECT; + } - public void setAdditionalInfo(String additionalInfo) { this.additionalInfo = additionalInfo; } + @Override + public Long getId() { + return id; + } @Override - public int getMyClassType() { return AppConstants.CLASS_TYPE_GDS_PROJECT; } + public void setId(Long id) { + this.id = id; + } @Override public int hashCode() { @@ -123,22 +174,20 @@ public boolean equals(Object obj) { return true; } else if (!super.equals(obj)) { return false; - } else if (getClass() != obj.getClass()) { - return false; } XXGdsProject other = (XXGdsProject) obj; return Objects.equals(id, other.id) && - Objects.equals(guid, other.guid) && - Objects.equals(version, other.version) && - Objects.equals(isEnabled, other.isEnabled) && - Objects.equals(name, other.name) && - Objects.equals(description, other.description) && - Objects.equals(acl, other.acl) && - Objects.equals(termsOfUse, other.termsOfUse) && - Objects.equals(options, other.options) && - Objects.equals(additionalInfo, other.additionalInfo); + Objects.equals(guid, other.guid) && + Objects.equals(version, other.version) && + Objects.equals(isEnabled, other.isEnabled) && + Objects.equals(name, other.name) && + Objects.equals(description, other.description) && + Objects.equals(acl, other.acl) && + Objects.equals(termsOfUse, other.termsOfUse) && + Objects.equals(options, other.options) && + Objects.equals(additionalInfo, other.additionalInfo); } @Override @@ -148,18 +197,18 @@ public String toString() { public StringBuilder toString(StringBuilder sb) { sb.append("XXGdsProject={ ") - .append(super.toString()).append(" ") - .append("id={").append(id).append("} ") - .append("guid={").append(guid).append("} ") - .append("version={").append(version).append("} ") - .append("isEnabled={").append(isEnabled).append("} ") - .append("name={").append(name).append("} ") - .append("description={").append(description).append("} ") - .append("condition={").append(acl).append("} ") - .append("termsOfUse={").append(termsOfUse).append("} ") - .append("options={").append(options).append("} ") - .append("additionalInfo={").append(additionalInfo).append("} ") - .append(" }"); + .append(super.toString()).append(" ") + .append("id={").append(id).append("} ") + .append("guid={").append(guid).append("} ") + .append("version={").append(version).append("} ") + .append("isEnabled={").append(isEnabled).append("} ") + .append("name={").append(name).append("} ") + .append("description={").append(description).append("} ") + .append("condition={").append(acl).append("} ") + .append("termsOfUse={").append(termsOfUse).append("} ") + .append("options={").append(options).append("} ") + .append("additionalInfo={").append(additionalInfo).append("} ") + .append(" }"); return sb; } diff --git a/security-admin/src/main/java/org/apache/ranger/entity/XXGdsProjectPolicyMap.java b/security-admin/src/main/java/org/apache/ranger/entity/XXGdsProjectPolicyMap.java index e7f1358ada..44dd0a16e8 100644 --- a/security-admin/src/main/java/org/apache/ranger/entity/XXGdsProjectPolicyMap.java +++ b/security-admin/src/main/java/org/apache/ranger/entity/XXGdsProjectPolicyMap.java @@ -21,14 +21,22 @@ import org.apache.ranger.common.AppConstants; -import javax.persistence.*; +import javax.persistence.Cacheable; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.SequenceGenerator; +import javax.persistence.Table; import javax.xml.bind.annotation.XmlRootElement; + import java.io.Serializable; import java.util.Objects; @Entity @Cacheable -@Table(name="x_gds_project_policy_map") +@Table(name = "x_gds_project_policy_map") @XmlRootElement public class XXGdsProjectPolicyMap implements Serializable { private static final long serialVersionUID = 1L; @@ -45,26 +53,40 @@ public class XXGdsProjectPolicyMap implements Serializable { @Column(name = "policy_id") protected Long policyId; - public XXGdsProjectPolicyMap() { } + public XXGdsProjectPolicyMap() {} public XXGdsProjectPolicyMap(Long projectId, Long policyId) { setProjectId(projectId); setPolicyId(policyId); } - public void setId(Long id) { this.id = id; } + public Long getId() { + return id; + } - public Long getId() { return id; } + public void setId(Long id) { + this.id = id; + } - public Long getProjectId() { return projectId; } + public Long getProjectId() { + return projectId; + } - public void setProjectId(Long projectId) { this.projectId = projectId; } + public void setProjectId(Long projectId) { + this.projectId = projectId; + } - public Long getPolicyId() { return policyId; } + public Long getPolicyId() { + return policyId; + } - public void setPolicyId(Long policyId) { this.policyId = policyId; } + public void setPolicyId(Long policyId) { + this.policyId = policyId; + } - public int getMyClassType() { return AppConstants.CLASS_TYPE_GDS_PROJECT_POLICY_MAP; } + public int getMyClassType() { + return AppConstants.CLASS_TYPE_GDS_PROJECT_POLICY_MAP; + } @Override public int hashCode() { @@ -75,6 +97,8 @@ public int hashCode() { public boolean equals(Object obj) { if (this == obj) { return true; + } else if (obj == null) { + return false; } else if (getClass() != obj.getClass()) { return false; } else if (!super.equals(obj)) { @@ -84,8 +108,8 @@ public boolean equals(Object obj) { XXGdsProjectPolicyMap other = (XXGdsProjectPolicyMap) obj; return Objects.equals(id, other.id) && - Objects.equals(projectId, other.projectId) && - Objects.equals(policyId, other.policyId); + Objects.equals(projectId, other.projectId) && + Objects.equals(policyId, other.policyId); } @Override @@ -94,12 +118,11 @@ public String toString() { } public StringBuilder toString(StringBuilder sb) { - sb.append("XXGdsProjectPolicyMap={ ") - .append(super.toString() + "} ") - .append("id={").append(id).append("} ") - .append("projectId={").append(projectId).append("} ") - .append("policyId={").append(policyId).append("} ") - .append(" }"); + sb.append("XXGdsProjectPolicyMap={ ").append(super.toString()).append("} ") + .append("id={").append(id).append("} ") + .append("projectId={").append(projectId).append("} ") + .append("policyId={").append(policyId).append("} ") + .append(" }"); return sb; } diff --git a/security-admin/src/main/java/org/apache/ranger/entity/XXGdsSharedResource.java b/security-admin/src/main/java/org/apache/ranger/entity/XXGdsSharedResource.java index b6096f2174..90968f8a64 100644 --- a/security-admin/src/main/java/org/apache/ranger/entity/XXGdsSharedResource.java +++ b/security-admin/src/main/java/org/apache/ranger/entity/XXGdsSharedResource.java @@ -21,14 +21,23 @@ import org.apache.ranger.common.AppConstants; -import javax.persistence.*; +import javax.persistence.Cacheable; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.SequenceGenerator; +import javax.persistence.Table; +import javax.persistence.Version; import javax.xml.bind.annotation.XmlRootElement; + import java.io.Serializable; import java.util.Objects; @Entity @Cacheable -@Table(name="x_gds_shared_resource") +@Table(name = "x_gds_shared_resource") @XmlRootElement public class XXGdsSharedResource extends XXDBBase implements Serializable { private static final long serialVersionUID = 1L; @@ -91,83 +100,156 @@ public class XXGdsSharedResource extends XXDBBase implements Serializable { @Column(name = "additional_info") protected String additionalInfo; + public String getGuid() { + return guid; + } - @Override - public void setId(Long id) { this.id = id; } - - @Override - public Long getId() { return id; } + public void setGuid(String guid) { + this.guid = guid; + } - public String getGuid() { return guid; } + public Long getVersion() { + return version; + } - public void setGuid(String guid) { this.guid = guid; } + public void setVersion(Long version) { + this.version = version; + } - public Long getVersion() { return version; } + public Boolean getIsEnabled() { + return isEnabled; + } - public void setVersion(Long version) { this.version = version; } + public void setIsEnabled(Boolean isEnabled) { + this.isEnabled = isEnabled; + } - public Boolean getIsEnabled() { return isEnabled; } + public String getName() { + return name; + } - public void setIsEnabled(Boolean isEnabled) { this.isEnabled = isEnabled; } + public void setName(String name) { + this.name = name; + } - public String getName() { return name; } + public String getDescription() { + return description; + } - public void setName(String name) { this.name = name; } + public void setDescription(String description) { + this.description = description; + } - public String getDescription() { return description; } + public Long getDataShareId() { + return dataShareId; + } - public void setDescription(String description) { this.description = description; } + public void setDataShareId(Long dataShareId) { + this.dataShareId = dataShareId; + } - public Long getDataShareId() { return dataShareId; } + public String getResource() { + return resource; + } - public void setDataShareId(Long dataShareId) { this.dataShareId = dataShareId; } + public void setResource(String resource) { + this.resource = resource; + } - public String getResource() { return resource; } + public String getSubResource() { + return subResource; + } - public void setResource(String resource) { this.resource = resource; } + public void setSubResource(String subResource) { + this.subResource = subResource; + } - public String getSubResource() { return subResource; } + public String getSubResourceType() { + return subResourceType; + } - public void setSubResource(String subResource) {this.subResource = subResource; } + public void setSubResourceType(String subResourceType) { + this.subResourceType = subResourceType; + } - public String getSubResourceType() { return subResourceType; } + public String getResourceSignature() { + return resourceSignature; + } - public void setSubResourceType(String subResourceType) {this.subResourceType = subResourceType; } + public void setResourceSignature(String resourceSignature) { + this.resourceSignature = resourceSignature; + } - public String getResourceSignature() { return resourceSignature; } + public String getConditionExpr() { + return conditionExpr; + } - public void setResourceSignature(String resourceSignature) { this.resourceSignature = resourceSignature; } + public void setConditionExpr(String conditionExpr) { + this.conditionExpr = conditionExpr; + } - public String getConditionExpr() { return conditionExpr; } + public String getAccessTypes() { + return accessTypes; + } - public void setConditionExpr(String conditionExpr) { this.conditionExpr = conditionExpr; } + public void setAccessTypes(String accessTypes) { + this.accessTypes = accessTypes; + } - public String getAccessTypes() { return accessTypes; } + public String getRowFilter() { + return rowFilter; + } - public void setAccessTypes(String accessTypes) { this.accessTypes = accessTypes; } + public void setRowFilter(String rowFilter) { + this.rowFilter = rowFilter; + } - public String getRowFilter() { return rowFilter; } + public String getSubResourceMasks() { + return subResourceMasks; + } - public void setRowFilter(String rowFilter) { this.rowFilter = rowFilter; } + public void setSubResourceMasks(String subResourceMasks) { + this.subResourceMasks = subResourceMasks; + } - public String getSubResourceMasks() { return subResourceMasks; } + public String getProfiles() { + return profiles; + } - public void setSubResourceMasks(String subResourceMasks) { this.subResourceMasks = subResourceMasks; } + public void setProfiles(String profiles) { + this.profiles = profiles; + } - public String getProfiles() { return profiles; } + public String getOptions() { + return options; + } - public void setProfiles(String profiles) { this.profiles = profiles; } + public void setOptions(String options) { + this.options = options; + } - public String getOptions() { return options; } + public String getAdditionalInfo() { + return additionalInfo; + } - public void setOptions(String options) { this.options = options; } + public void setAdditionalInfo(String additionalInfo) { + this.additionalInfo = additionalInfo; + } - public String getAdditionalInfo() { return additionalInfo; } + @Override + public int getMyClassType() { + return AppConstants.CLASS_TYPE_GDS_SHARED_RESOURCE; + } - public void setAdditionalInfo(String additionalInfo) { this.additionalInfo = additionalInfo; } + @Override + public Long getId() { + return id; + } @Override - public int getMyClassType() { return AppConstants.CLASS_TYPE_GDS_SHARED_RESOURCE; } + public void setId(Long id) { + this.id = id; + } @Override public int hashCode() { @@ -178,8 +260,6 @@ public int hashCode() { public boolean equals(Object obj) { if (this == obj) { return true; - } else if (getClass() != obj.getClass()) { - return false; } else if (!super.equals(obj)) { return false; } @@ -187,23 +267,23 @@ public boolean equals(Object obj) { XXGdsSharedResource other = (XXGdsSharedResource) obj; return Objects.equals(id, other.id) && - Objects.equals(guid, other.guid) && - Objects.equals(version, other.version) && - Objects.equals(isEnabled, other.isEnabled) && - Objects.equals(name, other.name) && - Objects.equals(description, other.description) && - Objects.equals(dataShareId, other.dataShareId) && - Objects.equals(resource, other.resource) && - Objects.equals(subResource, other.subResource) && - Objects.equals(subResourceType, other.subResourceType) && - Objects.equals(resourceSignature, other.resourceSignature) && - Objects.equals(conditionExpr, other.conditionExpr) && - Objects.equals(accessTypes, other.accessTypes) && - Objects.equals(rowFilter, other.rowFilter) && - Objects.equals(subResourceMasks, other.subResourceMasks) && - Objects.equals(profiles, other.profiles) && - Objects.equals(options, other.options) && - Objects.equals(additionalInfo, other.additionalInfo); + Objects.equals(guid, other.guid) && + Objects.equals(version, other.version) && + Objects.equals(isEnabled, other.isEnabled) && + Objects.equals(name, other.name) && + Objects.equals(description, other.description) && + Objects.equals(dataShareId, other.dataShareId) && + Objects.equals(resource, other.resource) && + Objects.equals(subResource, other.subResource) && + Objects.equals(subResourceType, other.subResourceType) && + Objects.equals(resourceSignature, other.resourceSignature) && + Objects.equals(conditionExpr, other.conditionExpr) && + Objects.equals(accessTypes, other.accessTypes) && + Objects.equals(rowFilter, other.rowFilter) && + Objects.equals(subResourceMasks, other.subResourceMasks) && + Objects.equals(profiles, other.profiles) && + Objects.equals(options, other.options) && + Objects.equals(additionalInfo, other.additionalInfo); } @Override @@ -213,26 +293,26 @@ public String toString() { public StringBuilder toString(StringBuilder sb) { sb.append("XXGdsSharedResource={ ") - .append(super.toString()).append(" ") - .append("id={").append(id).append("} ") - .append("guid={").append(guid).append("} ") - .append("version={").append(version).append("} ") - .append("isEnabled={").append(isEnabled).append("} ") - .append("description={").append(description).append("} ") - .append("name={").append(name).append("} ") - .append("description={").append(description).append("} ") - .append("dataShareId={").append(dataShareId).append("} ") - .append("resource={").append(resource).append("} ") - .append("subResource={").append(subResource).append("} ") - .append("subResourceType={").append(subResourceType).append("} ") - .append("conditionExpr={").append(conditionExpr).append("} ") - .append("accessTypes={").append(accessTypes).append("} ") - .append("rowFilter={").append(rowFilter).append("} ") - .append("subResourceMasks={").append(subResourceMasks).append("} ") - .append("profiles={").append(profiles).append("} ") - .append("options={").append(options).append("} ") - .append("additionalInfo={").append(additionalInfo).append("} ") - .append(" }"); + .append(super.toString()).append(" ") + .append("id={").append(id).append("} ") + .append("guid={").append(guid).append("} ") + .append("version={").append(version).append("} ") + .append("isEnabled={").append(isEnabled).append("} ") + .append("description={").append(description).append("} ") + .append("name={").append(name).append("} ") + .append("description={").append(description).append("} ") + .append("dataShareId={").append(dataShareId).append("} ") + .append("resource={").append(resource).append("} ") + .append("subResource={").append(subResource).append("} ") + .append("subResourceType={").append(subResourceType).append("} ") + .append("conditionExpr={").append(conditionExpr).append("} ") + .append("accessTypes={").append(accessTypes).append("} ") + .append("rowFilter={").append(rowFilter).append("} ") + .append("subResourceMasks={").append(subResourceMasks).append("} ") + .append("profiles={").append(profiles).append("} ") + .append("options={").append(options).append("} ") + .append("additionalInfo={").append(additionalInfo).append("} ") + .append(" }"); return sb; } diff --git a/security-admin/src/main/java/org/apache/ranger/entity/XXGlobalState.java b/security-admin/src/main/java/org/apache/ranger/entity/XXGlobalState.java index 2bec48fedf..b927cf98b2 100644 --- a/security-admin/src/main/java/org/apache/ranger/entity/XXGlobalState.java +++ b/security-admin/src/main/java/org/apache/ranger/entity/XXGlobalState.java @@ -25,6 +25,7 @@ import javax.persistence.Id; import javax.persistence.SequenceGenerator; import javax.persistence.Table; + import java.util.Objects; @Entity @@ -36,7 +37,12 @@ public class XXGlobalState extends XXGlobalStateBase implements java.io.Serializ @SequenceGenerator(name = "x_ranger_global_state_SEQ", sequenceName = "x_ranger_global_state_SEQ", allocationSize = 1) @GeneratedValue(strategy = GenerationType.AUTO, generator = "x_ranger_global_state_SEQ") @Column(name = "id") - protected Long id; + protected Long id; + + @Override + public Long getId() { + return id; + } @Override public void setId(Long id) { @@ -44,32 +50,25 @@ public void setId(Long id) { } @Override - public Long getId() { - return id; + public int hashCode() { + return Objects.hash(super.hashCode(), id); } @Override public boolean equals(Object obj) { - if (this == obj) + if (this == obj) { return true; - if (getClass() != obj.getClass()) - return false; - if (!super.equals(obj)) + } else if (!super.equals(obj)) { return false; + } XXGlobalState other = (XXGlobalState) obj; return Objects.equals(id, other.id); } - @Override - public int hashCode() { - return Objects.hash(super.hashCode(), id); - } - @Override public String toString() { return "GlobalState [id=" + id + "]"; } } - diff --git a/security-admin/src/main/java/org/apache/ranger/entity/XXGlobalStateBase.java b/security-admin/src/main/java/org/apache/ranger/entity/XXGlobalStateBase.java index a1a39c672c..47848a929f 100644 --- a/security-admin/src/main/java/org/apache/ranger/entity/XXGlobalStateBase.java +++ b/security-admin/src/main/java/org/apache/ranger/entity/XXGlobalStateBase.java @@ -20,6 +20,7 @@ import javax.persistence.Column; import javax.persistence.MappedSuperclass; import javax.persistence.Version; + import java.util.Objects; @MappedSuperclass @@ -36,25 +37,36 @@ public abstract class XXGlobalStateBase extends XXDBBase { @Column(name = "app_data") protected String appData; - public Long getVersion() { return version; } - public String getStateName() { return stateName; } + public Long getVersion() { + return version; + } + + public String getStateName() { + return stateName; + } public void setStateName(String stateName) { this.stateName = stateName; } - public void setAppData(String appData) {this.appData = appData;} - public String getAppData() { return appData; } + public String getAppData() { + return appData; + } + + public void setAppData(String appData) { + this.appData = appData; + } + + @Override + public int hashCode() { + return Objects.hash(super.hashCode(), version, stateName); + } @Override public boolean equals(Object obj) { if (this == obj) { return true; - } - if (getClass() != obj.getClass()) { - return false; - } - if (!super.equals(obj)) { + } else if (!super.equals(obj)) { return false; } @@ -65,11 +77,6 @@ public boolean equals(Object obj) { Objects.equals(appData, other.appData); } - @Override - public int hashCode() { - return Objects.hash(super.hashCode(), version, stateName); - } - @Override public String toString() { String str = "XXGlobalStateBase={"; @@ -79,4 +86,3 @@ public String toString() { return str; } } - 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 index 179b7f95c8..30e9166617 100644 --- a/security-admin/src/main/java/org/apache/ranger/entity/XXGroup.java +++ b/security-admin/src/main/java/org/apache/ranger/entity/XXGroup.java @@ -17,13 +17,16 @@ * under the License. */ - package org.apache.ranger.entity; +package org.apache.ranger.entity; /** * Group - * */ +import org.apache.ranger.common.AppConstants; +import org.apache.ranger.common.RangerCommonEnums; +import org.apache.ranger.common.RangerConstants; + import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; @@ -32,321 +35,332 @@ import javax.persistence.SequenceGenerator; import javax.persistence.Table; -import org.apache.ranger.common.AppConstants; -import org.apache.ranger.common.RangerCommonEnums; -import org.apache.ranger.common.RangerConstants; - +import java.util.Objects; @Entity -@Table(name="x_group") +@Table(name = "x_group") 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 - *
    - *
  • The maximum length for this attribute is 1024. - *
- * - */ - @Column(name="GROUP_NAME" , nullable=false , length=1024) - protected String name; - - /** - * Description - *
    - *
  • The maximum length for this attribute is 4000. - *
- * - */ - @Column(name="DESCR" , nullable=false , length=4000) - protected String description; - - /** - * Status - *
    - *
  • This attribute is of type enum CommonEnums::ActiveStatus - *
- * - */ - @Column(name="STATUS" , nullable=false ) - protected int status = RangerConstants.STATUS_DISABLED; - - /** - * IsVisible - *
    - *
  • This attribute is of type enum CommonEnums::ActiveVisiblility - *
- * - */ - @Column(name="IS_VISIBLE" , nullable=false ) - protected Integer isVisible; - - /** - * Type of group - *
    - *
  • This attribute is of type enum CommonEnums::XAGroupType - *
- * - */ - @Column(name="GROUP_TYPE" , nullable=false ) - protected int groupType = AppConstants.XA_GROUP_UNKNOWN; - - @Column(name="GROUP_SRC" , nullable=false ) - protected int groupSource = RangerCommonEnums.GROUP_INTERNAL; - - /** - * Id of the credential store - *
    - *
- * - */ - @Column(name="CRED_STORE_ID" ) - protected Long credStoreId; - - /** - * Additional store attributes. - *
    - *
- * - */ - @Column(name="OTHER_ATTRIBUTES") - protected String otherAttributes; - - /** - * Sync Source Attribute. - *
    - *
- * - */ - @Column(name="SYNC_SOURCE") - protected String syncSource; - - /** - * Default constructor. This will set all the attributes to default value. - */ - public XXGroup ( ) { - status = RangerConstants.STATUS_DISABLED; - groupType = AppConstants.XA_GROUP_UNKNOWN; - groupSource = RangerCommonEnums.GROUP_INTERNAL; - isVisible = RangerCommonEnums.IS_VISIBLE; - } - - @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 name. - * You cannot set null to the attribute. - * @param name Value to set member attribute name - */ - public void setName( String name ) { - this.name = name; - } - - /** - * Returns the value for the member attribute name - * @return String - value of member attribute name. - */ - public String getName( ) { - return this.name; - } - - /** - * This method sets the value to the member attribute description. - * You cannot set null to the attribute. - * @param description Value to set member attribute description - */ - public void setDescription( String description ) { - this.description = description; - } - - /** - * Returns the value for the member attribute description - * @return String - value of member attribute description. - */ - public String getDescription( ) { - return this.description; - } - - /** - * This method sets the value to the member attribute status. - * You cannot set null to the attribute. - * @param status Value to set member attribute status - */ - public void setStatus( int status ) { - this.status = status; - } - - /** - * Returns the value for the member attribute status - * @return int - value of member attribute status. - */ - public int getStatus( ) { - return this.status; - } - - /** - * @return the isVisible - */ - public Integer getIsVisible() { - return isVisible; - } - - /** - * @param isVisible the isVisible to set - */ - public void setIsVisible(Integer isVisible) { - this.isVisible = isVisible; - } - - /** - * This method sets the value to the member attribute groupType. - * You cannot set null to the attribute. - * @param groupType Value to set member attribute groupType - */ - public void setGroupType( int groupType ) { - this.groupType = groupType; - } - - /** - * Returns the value for the member attribute groupType - * @return int - value of member attribute groupType. - */ - public int getGroupType( ) { - return this.groupType; - } - - /** - * This method sets the value to the member attribute credStoreId. - * You cannot set null to the attribute. - * @param credStoreId Value to set member attribute credStoreId - */ - public void setCredStoreId( Long credStoreId ) { - this.credStoreId = credStoreId; - } - - /** - * Returns the value for the member attribute credStoreId - * @return Long - value of member attribute credStoreId. - */ - public Long getCredStoreId( ) { - return this.credStoreId; - } - - /** - * This method sets JSON {@link String} representation of additional store attributes. - * This method accepts null values. - * @param otherAttributes - */ - public void setOtherAttributes(String otherAttributes) { - this.otherAttributes = otherAttributes; - } - - /** - * @return JSON {@link String} representation of additional store attributes if available, - * null otherwise. - */ - public String getOtherAttributes() { - return otherAttributes; - } - - /** - * This method sets JSON {@link String} representation of sync source attribute. - * This method accepts null values. - * @param syncSource - */ - public void setSyncSource(String syncSource) { - this.syncSource = syncSource; - } - - /** - * @return JSON {@link String} representation of sync source attribute if available, - * null otherwise. - */ - public String getSyncSource() { return syncSource; } - /** - * 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 += "isvisible={" + isVisible + "} "; - str += "groupType={" + groupType + "} "; - str += "credStoreId={" + credStoreId + "} "; - str += "groupSrc={" + groupSource + "} "; - str += "otherAttributes={" + otherAttributes + "} "; - str += "syncSource={" + syncSource + "} "; - 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( "status".equals(fieldName) ) { - return "CommonEnums.ActiveStatus"; - } - if( "groupType".equals(fieldName) ) { - return "CommonEnums.XAGroupType"; - } - //Later TODO - //return super.getEnumName(fieldName); - return null; - } - + 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; + + /** + * Name + *
    + *
  • The maximum length for this attribute is 1024. + *
+ */ + @Column(name = "GROUP_NAME", nullable = false, length = 1024) + protected String name; + + /** + * Description + *
    + *
  • The maximum length for this attribute is 4000. + *
+ */ + @Column(name = "DESCR", nullable = false, length = 4000) + protected String description; + + /** + * Status + *
    + *
  • This attribute is of type enum CommonEnums::ActiveStatus + *
+ */ + @Column(name = "STATUS", nullable = false) + protected int status = RangerConstants.STATUS_DISABLED; + + /** + * IsVisible + *
    + *
  • This attribute is of type enum CommonEnums::ActiveVisiblility + *
+ */ + @Column(name = "IS_VISIBLE", nullable = false) + protected Integer isVisible; + + /** + * Type of group + *
    + *
  • This attribute is of type enum CommonEnums::XAGroupType + *
+ */ + @Column(name = "GROUP_TYPE", nullable = false) + protected int groupType = AppConstants.XA_GROUP_UNKNOWN; + + @Column(name = "GROUP_SRC", nullable = false) + protected int groupSource = RangerCommonEnums.GROUP_INTERNAL; + + /** + * Id of the credential store + *
    + *
+ */ + @Column(name = "CRED_STORE_ID") + protected Long credStoreId; + + /** + * Additional store attributes. + *
    + *
+ */ + @Column(name = "OTHER_ATTRIBUTES") + protected String otherAttributes; + + /** + * Sync Source Attribute. + *
    + *
+ */ + @Column(name = "SYNC_SOURCE") + protected String syncSource; + + /** + * Default constructor. This will set all the attributes to default value. + */ + public XXGroup() { + status = RangerConstants.STATUS_DISABLED; + groupType = AppConstants.XA_GROUP_UNKNOWN; + groupSource = RangerCommonEnums.GROUP_INTERNAL; + isVisible = RangerCommonEnums.IS_VISIBLE; + } + + public static String getEnumName(String fieldName) { + if ("status".equals(fieldName)) { + return "CommonEnums.ActiveStatus"; + } else if ("groupType".equals(fieldName)) { + return "CommonEnums.XAGroupType"; + } + + //Later TODO + //return super.getEnumName(fieldName); + return null; + } + + @Override + public int getMyClassType() { + return AppConstants.CLASS_TYPE_XA_GROUP; + } + + @Override + public String getMyDisplayValue() { + return getDescription(); + } + + @Override + public Long getId() { + return id; + } + + @Override + public void setId(Long id) { + this.id = id; + } + + @Override + public int hashCode() { + return super.hashCode(); + } + + /** + * Checks for all attributes except referenced db objects + * + * @return true if all attributes match + */ + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } else if (!super.equals(obj)) { + return false; + } + + XXGroup other = (XXGroup) obj; + + return Objects.equals(name, other.name) && + Objects.equals(description, other.description) && + Objects.equals(status, other.status) && + Objects.equals(groupType, other.groupType) && + Objects.equals(credStoreId, other.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 += "isvisible={" + isVisible + "} "; + str += "groupType={" + groupType + "} "; + str += "credStoreId={" + credStoreId + "} "; + str += "groupSrc={" + groupSource + "} "; + str += "otherAttributes={" + otherAttributes + "} "; + str += "syncSource={" + syncSource + "} "; + str += "}"; + return str; + } + + /** + * Returns the value for the member attribute name + * + * @return String - value of member attribute name. + */ + public String getName() { + return this.name; + } + + /** + * This method sets the value to the member attribute name. + * You cannot set null to the attribute. + * + * @param name Value to set member attribute name + */ + public void setName(String name) { + this.name = name; + } + + /** + * Returns the value for the member attribute description + * + * @return String - value of member attribute description. + */ + public String getDescription() { + return this.description; + } + + /** + * This method sets the value to the member attribute description. + * You cannot set null to the attribute. + * + * @param description Value to set member attribute description + */ + public void setDescription(String description) { + this.description = description; + } + + /** + * Returns the value for the member attribute status + * + * @return int - value of member attribute status. + */ + public int getStatus() { + return this.status; + } + + /** + * This method sets the value to the member attribute status. + * You cannot set null to the attribute. + * + * @param status Value to set member attribute status + */ + public void setStatus(int status) { + this.status = status; + } + + /** + * @return the isVisible + */ + public Integer getIsVisible() { + return isVisible; + } + + /** + * @param isVisible the isVisible to set + */ + public void setIsVisible(Integer isVisible) { + this.isVisible = isVisible; + } + + /** + * Returns the value for the member attribute groupType + * + * @return int - value of member attribute groupType. + */ + public int getGroupType() { + return this.groupType; + } + + /** + * This method sets the value to the member attribute groupType. + * You cannot set null to the attribute. + * + * @param groupType Value to set member attribute groupType + */ + public void setGroupType(int groupType) { + this.groupType = groupType; + } + + /** + * Returns the value for the member attribute credStoreId + * + * @return Long - value of member attribute credStoreId. + */ + public Long getCredStoreId() { + return this.credStoreId; + } + + /** + * This method sets the value to the member attribute credStoreId. + * You cannot set null to the attribute. + * + * @param credStoreId Value to set member attribute credStoreId + */ + public void setCredStoreId(Long credStoreId) { + this.credStoreId = credStoreId; + } + + /** + * @return JSON {@link String} representation of additional store attributes if available, + * null otherwise. + */ + public String getOtherAttributes() { + return otherAttributes; + } + + /** + * This method sets JSON {@link String} representation of additional store attributes. + * This method accepts null values. + * + * @param otherAttributes + */ + public void setOtherAttributes(String otherAttributes) { + this.otherAttributes = otherAttributes; + } + + /** + * @return JSON {@link String} representation of sync source attribute if available, + * null otherwise. + */ + public String getSyncSource() { + return syncSource; + } + + /** + * This method sets JSON {@link String} representation of sync source attribute. + * This method accepts null values. + * + * @param syncSource + */ + public void setSyncSource(String syncSource) { + this.syncSource = syncSource; + } + + public int getGroupSource() { + return groupSource; + } + + public void setGroupSource(int groupSource) { + this.groupSource = groupSource; + } } 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 index bc410017a3..d8d9b49c9b 100644 --- a/security-admin/src/main/java/org/apache/ranger/entity/XXGroupGroup.java +++ b/security-admin/src/main/java/org/apache/ranger/entity/XXGroupGroup.java @@ -17,13 +17,14 @@ * under the License. */ - package org.apache.ranger.entity; +package org.apache.ranger.entity; /** * Group of groups - * */ +import org.apache.ranger.common.AppConstants; + import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; @@ -32,166 +33,171 @@ import javax.persistence.SequenceGenerator; import javax.persistence.Table; -import org.apache.ranger.common.AppConstants; - +import java.util.Objects; @Entity -@Table(name="x_group_groups") +@Table(name = "x_group_groups") 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 - *
    - *
  • The maximum length for this attribute is 1024. - *
- * - */ - @Column(name="GROUP_NAME" , nullable=false , length=1024) - protected String name; - - /** - * Id of the parent group - *
    - *
- * - */ - @Column(name="P_GROUP_ID" ) - protected Long parentGroupId; - - - /** - * Id of the group - *
    - *
- * - */ - @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 name. - * You cannot set null to the attribute. - * @param name Value to set member attribute name - */ - public void setName( String name ) { - this.name = name; - } - - /** - * Returns the value for the member attribute name - * @return String - value of member attribute name. - */ - public String getName( ) { - return this.name; - } - - /** - * This method sets the value to the member attribute parentGroupId. - * You cannot set null to the attribute. - * @param parentGroupId Value to set member attribute parentGroupId - */ - public void setParentGroupId( Long parentGroupId ) { - this.parentGroupId = parentGroupId; - } - - /** - * Returns the value for the member attribute parentGroupId - * @return Long - value of member attribute parentGroupId. - */ - public Long getParentGroupId( ) { - return this.parentGroupId; - } - - - /** - * This method sets the value to the member attribute groupId. - * You cannot set null to the attribute. - * @param groupId Value to set member attribute groupId - */ - public void setGroupId( Long groupId ) { - this.groupId = groupId; - } - - /** - * Returns the value for the member attribute groupId - * @return Long - value of member attribute groupId. - */ - 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; - } - + 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; + + /** + * Name + *
    + *
  • The maximum length for this attribute is 1024. + *
+ */ + @Column(name = "GROUP_NAME", nullable = false, length = 1024) + protected String name; + + /** + * Id of the parent group + *
    + *
+ */ + @Column(name = "P_GROUP_ID") + protected Long parentGroupId; + + /** + * Id of the group + *
    + *
+ */ + @Column(name = "GROUP_ID") + protected Long groupId; + + /** + * Default constructor. This will set all the attributes to default value. + */ + public XXGroupGroup() { + } + + public static String getEnumName(String fieldName) { + //Later TODO + //return super.getEnumName(fieldName); + return null; + } + + @Override + public int getMyClassType() { + return AppConstants.CLASS_TYPE_XA_GROUP_GROUP; + } + + @Override + public String getMyDisplayValue() { + return getName(); + } + + @Override + public Long getId() { + return id; + } + + @Override + public void setId(Long id) { + this.id = id; + } + + @Override + public int hashCode() { + return super.hashCode(); + } + + /** + * Checks for all attributes except referenced db objects + * + * @return true if all attributes match + */ + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } else if (!super.equals(obj)) { + return false; + } + + XXGroupGroup other = (XXGroupGroup) obj; + + return Objects.equals(name, other.name) && + Objects.equals(parentGroupId, other.parentGroupId) && + Objects.equals(groupId, other.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; + } + + /** + * Returns the value for the member attribute name + * + * @return String - value of member attribute name. + */ + public String getName() { + return this.name; + } + + /** + * This method sets the value to the member attribute name. + * You cannot set null to the attribute. + * + * @param name Value to set member attribute name + */ + public void setName(String name) { + this.name = name; + } + + /** + * Returns the value for the member attribute parentGroupId + * + * @return Long - value of member attribute parentGroupId. + */ + public Long getParentGroupId() { + return this.parentGroupId; + } + + /** + * This method sets the value to the member attribute parentGroupId. + * You cannot set null to the attribute. + * + * @param parentGroupId Value to set member attribute parentGroupId + */ + public void setParentGroupId(Long parentGroupId) { + this.parentGroupId = parentGroupId; + } + + /** + * Returns the value for the member attribute groupId + * + * @return Long - value of member attribute groupId. + */ + public Long getGroupId() { + return this.groupId; + } + + /** + * This method sets the value to the member attribute groupId. + * You cannot set null to the attribute. + * + * @param groupId Value to set member attribute groupId + */ + public void setGroupId(Long groupId) { + this.groupId = groupId; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/entity/XXGroupPermission.java b/security-admin/src/main/java/org/apache/ranger/entity/XXGroupPermission.java index 745e609101..98b3e03e61 100644 --- a/security-admin/src/main/java/org/apache/ranger/entity/XXGroupPermission.java +++ b/security-admin/src/main/java/org/apache/ranger/entity/XXGroupPermission.java @@ -17,6 +17,9 @@ package org.apache.ranger.entity; +import org.apache.ranger.common.AppConstants; +import org.apache.ranger.common.RangerCommonEnums; + import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; @@ -25,134 +28,124 @@ import javax.persistence.SequenceGenerator; import javax.persistence.Table; -import org.apache.ranger.common.AppConstants; -import org.apache.ranger.common.RangerCommonEnums; +import java.util.Objects; @Entity -@Table(name="x_group_module_perm") +@Table(name = "x_group_module_perm") public class XXGroupPermission extends XXDBBase implements java.io.Serializable { - - private static final long serialVersionUID = 1L; - - @Id - @SequenceGenerator(name="X_GROUP_MODULE_PERM_SEQ",sequenceName="X_GROUP_MODULE_PERM_SEQ",allocationSize=1) - @GeneratedValue(strategy=GenerationType.AUTO,generator="X_GROUP_MODULE_PERM_SEQ") - @Column(name="ID") - protected Long id; - - @Column(name="GROUP_ID" , nullable=false) - protected Long groupId; - - @Column(name="MODULE_ID" , nullable=false) - protected Long moduleId; - - @Column(name="IS_ALLOWED" , nullable=false) - protected Integer isAllowed; - - public XXGroupPermission() { - isAllowed = RangerCommonEnums.STATUS_ENABLED; - } - - /** - * @return the id - */ - public Long getId() { - return id; - } - /** - * @param id the id to set - */ - public void setId(Long id) { - this.id = id; - } - - /** - * @return the groupId - */ - public Long getGroupId() { - return groupId; - } - /** - * @param groupId the groupId to set - */ - public void setGroupId(Long groupId) { - this.groupId = groupId; - } - - /** - * @return the moduleId - */ - public Long getModuleId() { - return moduleId; - } - /** - * @param moduleId the moduleId to set - */ - public void setModuleId(Long moduleId) { - this.moduleId = moduleId; - } - - /** - * @return the isAllowed - */ - public Integer getIsAllowed() { - return isAllowed; - } - /** - * @param isAllowed the isAllowed to set - */ - public void setIsAllowed(Integer isAllowed) { - this.isAllowed = isAllowed; - } - - @Override - public int getMyClassType() { - return AppConstants.CLASS_TYPE_RANGER_GROUP_PERMISSION; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (!super.equals(obj)) - return false; - if (getClass() != obj.getClass()) - return false; - XXGroupPermission other = (XXGroupPermission) obj; - if (groupId == null) { - if (other.groupId != null) - return false; - } else if (!groupId.equals(other.groupId)) - return false; - if (id == null) { - if (other.id != null) - return false; - } else if (!id.equals(other.id)) - return false; - if (isAllowed == null) { - if (other.isAllowed != null) - return false; - } else if (!isAllowed.equals(other.isAllowed)) - return false; - if (moduleId == null) { - if (other.moduleId != null) - return false; - } else if (!moduleId.equals(other.moduleId)) - return false; - return true; - } - - @Override - public String toString() { - - String str = "XXGroupPermission={"; - str += super.toString(); - str += "id={" + id + "} "; - str += "groupId={" + groupId + "} "; - str += "moduleId={" + moduleId + "} "; - str += "isAllowed={" + isAllowed + "} "; - str += "}"; - - return str; - } + private static final long serialVersionUID = 1L; + + @Id + @SequenceGenerator(name = "X_GROUP_MODULE_PERM_SEQ", sequenceName = "X_GROUP_MODULE_PERM_SEQ", allocationSize = 1) + @GeneratedValue(strategy = GenerationType.AUTO, generator = "X_GROUP_MODULE_PERM_SEQ") + @Column(name = "ID") + protected Long id; + + @Column(name = "GROUP_ID", nullable = false) + protected Long groupId; + + @Column(name = "MODULE_ID", nullable = false) + protected Long moduleId; + + @Column(name = "IS_ALLOWED", nullable = false) + protected Integer isAllowed; + + public XXGroupPermission() { + isAllowed = RangerCommonEnums.STATUS_ENABLED; + } + + /** + * @return the groupId + */ + public Long getGroupId() { + return groupId; + } + + /** + * @param groupId the groupId to set + */ + public void setGroupId(Long groupId) { + this.groupId = groupId; + } + + /** + * @return the moduleId + */ + public Long getModuleId() { + return moduleId; + } + + /** + * @param moduleId the moduleId to set + */ + public void setModuleId(Long moduleId) { + this.moduleId = moduleId; + } + + /** + * @return the isAllowed + */ + public Integer getIsAllowed() { + return isAllowed; + } + + /** + * @param isAllowed the isAllowed to set + */ + public void setIsAllowed(Integer isAllowed) { + this.isAllowed = isAllowed; + } + + @Override + public int getMyClassType() { + return AppConstants.CLASS_TYPE_RANGER_GROUP_PERMISSION; + } + + /** + * @return the id + */ + public Long getId() { + return id; + } + + /** + * @param id the id to set + */ + public void setId(Long id) { + this.id = id; + } + + @Override + public int hashCode() { + return super.hashCode(); + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } else if (!super.equals(obj)) { + return false; + } + + XXGroupPermission other = (XXGroupPermission) obj; + + return Objects.equals(groupId, other.groupId) && + Objects.equals(id, other.id) && + Objects.equals(isAllowed, other.isAllowed) && + Objects.equals(moduleId, other.moduleId); + } + + @Override + public String toString() { + String str = "XXGroupPermission={"; + str += super.toString(); + str += "id={" + id + "} "; + str += "groupId={" + groupId + "} "; + str += "moduleId={" + moduleId + "} "; + str += "isAllowed={" + isAllowed + "} "; + str += "}"; + + return str; + } } 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 index 6ba1b8b28e..6fa0094de7 100644 --- a/security-admin/src/main/java/org/apache/ranger/entity/XXGroupUser.java +++ b/security-admin/src/main/java/org/apache/ranger/entity/XXGroupUser.java @@ -17,13 +17,14 @@ * under the License. */ - package org.apache.ranger.entity; +package org.apache.ranger.entity; /** * Group of users - * */ +import org.apache.ranger.common.AppConstants; + import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; @@ -32,169 +33,171 @@ import javax.persistence.SequenceGenerator; import javax.persistence.Table; -import org.apache.ranger.common.AppConstants; - +import java.util.Objects; @Entity -@Table(name="x_group_users") +@Table(name = "x_group_users") 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 - *
    - *
  • The maximum length for this attribute is 1024. - *
- * - */ - @Column(name="GROUP_NAME" , nullable=false , length=1024) - protected String name; - - /** - * Id of the group - *
    - *
- * - */ - @Column(name="P_GROUP_ID" ) - protected Long parentGroupId; - - - /** - * Id of the user - *
    - *
- * - */ - @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 name. - * You cannot set null to the attribute. - * @param name Value to set member attribute name - */ - public void setName( String name ) { - this.name = name; - } - - /** - * Returns the value for the member attribute name - * @return String - value of member attribute name. - */ - public String getName( ) { - return this.name; - } - - /** - * This method sets the value to the member attribute parentGroupId. - * You cannot set null to the attribute. - * @param parentGroupId Value to set member attribute parentGroupId - */ - public void setParentGroupId( Long parentGroupId ) { - this.parentGroupId = parentGroupId; - } - - /** - * Returns the value for the member attribute parentGroupId - * @return Long - value of member attribute parentGroupId. - */ - public Long getParentGroupId( ) { - return this.parentGroupId; - } - - - /** - * This method sets the value to the member attribute userId. - * You cannot set null to the attribute. - * @param userId Value to set member attribute userId - */ - public void setUserId( Long userId ) { - this.userId = userId; - } - - /** - * Returns the value for the member attribute userId - * @return Long - value of member attribute userId. - */ - 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; - } - + 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; + + /** + * Name + *
    + *
  • The maximum length for this attribute is 1024. + *
+ */ + @Column(name = "GROUP_NAME", nullable = false, length = 1024) + protected String name; + + /** + * Id of the group + *
    + *
+ */ + @Column(name = "P_GROUP_ID") + protected Long parentGroupId; + + /** + * Id of the user + *
    + *
+ */ + @Column(name = "USER_ID") + protected Long userId; + + /** + * Default constructor. This will set all the attributes to default value. + */ + public XXGroupUser() { + } + + public static String getEnumName(String fieldName) { + //Later TODO + //return super.getEnumName(fieldName); + return null; + } + + @Override + public int getMyClassType() { + return AppConstants.CLASS_TYPE_XA_GROUP_USER; + } + + @Override + public String getMyDisplayValue() { + return getName(); + } + + @Override + public Long getId() { + return id; + } + + @Override + public void setId(Long id) { + this.id = id; + } + + @Override + public int hashCode() { + return super.hashCode(); + } + + /** + * Checks for all attributes except referenced db objects + * + * @return true if all attributes match + */ + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } else if (!super.equals(obj)) { + return false; + } + + XXGroupUser other = (XXGroupUser) obj; + + return Objects.equals(name, other.name) && + Objects.equals(parentGroupId, other.parentGroupId) && + Objects.equals(userId, other.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; + } + + /** + * Returns the value for the member attribute name + * + * @return String - value of member attribute name. + */ + public String getName() { + return this.name; + } + + /** + * This method sets the value to the member attribute name. + * You cannot set null to the attribute. + * + * @param name Value to set member attribute name + */ + public void setName(String name) { + this.name = name; + } + + /** + * Returns the value for the member attribute parentGroupId + * + * @return Long - value of member attribute parentGroupId. + */ + public Long getParentGroupId() { + return this.parentGroupId; + } + + /** + * This method sets the value to the member attribute parentGroupId. + * You cannot set null to the attribute. + * + * @param parentGroupId Value to set member attribute parentGroupId + */ + public void setParentGroupId(Long parentGroupId) { + this.parentGroupId = parentGroupId; + } + + /** + * Returns the value for the member attribute userId + * + * @return Long - value of member attribute userId. + */ + public Long getUserId() { + return this.userId; + } + + /** + * This method sets the value to the member attribute userId. + * You cannot set null to the attribute. + * + * @param userId Value to set member attribute userId + */ + public void setUserId(Long userId) { + this.userId = userId; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/entity/XXModuleDef.java b/security-admin/src/main/java/org/apache/ranger/entity/XXModuleDef.java index 24f5763060..3d7bc79cc9 100644 --- a/security-admin/src/main/java/org/apache/ranger/entity/XXModuleDef.java +++ b/security-admin/src/main/java/org/apache/ranger/entity/XXModuleDef.java @@ -17,6 +17,8 @@ package org.apache.ranger.entity; +import org.apache.ranger.common.AppConstants; + import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; @@ -24,104 +26,101 @@ import javax.persistence.Id; import javax.persistence.SequenceGenerator; import javax.persistence.Table; -import org.apache.ranger.common.AppConstants; + +import java.util.Objects; @Entity -@Table(name="x_modules_master") +@Table(name = "x_modules_master") public class XXModuleDef extends XXDBBase implements java.io.Serializable { + private static final long serialVersionUID = 1L; + + @Id + @SequenceGenerator(name = "X_MODULES_MASTER_SEQ", sequenceName = "X_MODULES_MASTER_SEQ", allocationSize = 1) + @GeneratedValue(strategy = GenerationType.AUTO, generator = "X_MODULES_MASTER_SEQ") + @Column(name = "ID") + protected Long id; + + @Column(name = "MODULE", nullable = false) + protected String module; + + @Column(name = "URL", nullable = false) + protected String url; + + /** + * @return the module + */ + public String getModule() { + return module; + } + + /** + * @param module the module to set + */ + public void setModule(String module) { + this.module = module; + } + + /** + * @return the url + */ + public String getUrl() { + return url; + } + + /** + * @param url the url to set + */ + public void setUrl(String url) { + this.url = url; + } + + @Override + public int getMyClassType() { + return AppConstants.CLASS_TYPE_RANGER_MODULE_DEF; + } + + /** + * @return the id + */ + public Long getId() { + return id; + } + + /** + * @param id the id to set + */ + public void setId(Long id) { + this.id = id; + } + + @Override + public int hashCode() { + return super.hashCode(); + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } else if (!super.equals(obj)) { + return false; + } + + XXModuleDef other = (XXModuleDef) obj; - private static final long serialVersionUID = 1L; - - @Id - @SequenceGenerator(name="X_MODULES_MASTER_SEQ",sequenceName="X_MODULES_MASTER_SEQ",allocationSize=1) - @GeneratedValue(strategy=GenerationType.AUTO,generator="X_MODULES_MASTER_SEQ") - @Column(name="ID") - protected Long id; - - /** - * @return the id - */ - public Long getId() { - return id; - } - /** - * @param id the id to set - */ - public void setId(Long id) { - this.id = id; - } - - @Column(name="MODULE" , nullable=false) - protected String module; - /** - * @return the module - */ - public String getModule() { - return module; - } - /** - * @param module the module to set - */ - public void setModule(String module) { - this.module = module; - } - - @Column(name="URL" , nullable=false) - protected String url; - /** - * @return the url - */ - public String getUrl() { - return url; - } - /** - * @param url the url to set - */ - public void setUrl(String url) { - this.url = url; - } - - @Override - public int getMyClassType( ) { - return AppConstants.CLASS_TYPE_RANGER_MODULE_DEF; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (!super.equals(obj)) - return false; - if (getClass() != obj.getClass()) - return false; - XXModuleDef other = (XXModuleDef) obj; - if (id == null) { - if (other.id != null) - return false; - } else if (!id.equals(other.id)) - return false; - if (module == null) { - if (other.module != null) - return false; - } else if (!module.equals(other.module)) - return false; - if (url == null) { - if (other.url != null) - return false; - } else if (!url.equals(other.url)) - return false; - return true; - } - - @Override - public String toString() { - String str = "XXModuleDef={"; - str += super.toString(); - str += "id={" + id + "} "; - str += "module={" + module + "} "; - str += "url={" + url + "} "; - str += "}"; - return str; - } + return Objects.equals(id, other.id) && + Objects.equals(module, other.module) && + Objects.equals(url, other.url); + } + @Override + public String toString() { + String str = "XXModuleDef={"; + str += super.toString(); + str += "id={" + id + "} "; + str += "module={" + module + "} "; + str += "url={" + url + "} "; + str += "}"; + return str; + } } 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 index cb524c3113..7103221ee8 100644 --- a/security-admin/src/main/java/org/apache/ranger/entity/XXPermMap.java +++ b/security-admin/src/main/java/org/apache/ranger/entity/XXPermMap.java @@ -17,13 +17,15 @@ * under the License. */ - package org.apache.ranger.entity; +package org.apache.ranger.entity; /** * Permission map - * */ +import org.apache.ranger.common.AppConstants; +import org.apache.ranger.common.RangerConstants; + import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; @@ -32,369 +34,371 @@ import javax.persistence.SequenceGenerator; import javax.persistence.Table; -import org.apache.ranger.common.AppConstants; -import org.apache.ranger.common.RangerConstants; - +import java.util.Objects; @Entity -@Table(name="x_perm_map") +@Table(name = "x_perm_map") 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 - *
    - *
  • The maximum length for this attribute is 1024. - *
- * - */ - @Column(name="PERM_GROUP" , length=1024) - protected String permGroup; - - /** - * Id of the resource - *
    - *
- * - */ - @Column(name="RES_ID" ) - protected Long resourceId; - - - /** - * Id of the group - *
    - *
- * - */ - @Column(name="GROUP_ID" ) - protected Long groupId; - - - /** - * Id of the user - *
    - *
- * - */ - @Column(name="USER_ID" ) - protected Long userId; - - - /** - * Permission for user or group - *
    - *
  • This attribute is of type enum CommonEnums::XAPermForType - *
- * - */ - @Column(name="PERM_FOR" , nullable=false ) - protected int permFor = AppConstants.XA_PERM_FOR_UNKNOWN; - - /** - * Type of permission - *
    - *
  • This attribute is of type enum CommonEnums::XAPermType - *
- * - */ - @Column(name="PERM_TYPE" , nullable=false ) - protected int permType = AppConstants.XA_PERM_TYPE_UNKNOWN; - - /** - * Is recursive - *
    - *
  • This attribute is of type enum CommonEnums::BooleanValue - *
- * - */ - @Column(name="IS_RECURSIVE" , nullable=false ) - protected int isRecursive = RangerConstants.BOOL_NONE; - - /** - * Is wild card - *
    - *
- * - */ - @Column(name="IS_WILD_CARD" , nullable=false ) - protected boolean isWildCard = true; - - /** - * Grant is true and revoke is false - *
    - *
- * - */ - @Column(name="GRANT_REVOKE" , nullable=false ) - protected boolean grantOrRevoke = true; - /** - * IP address to which the group belongs to - *
    - *
  • The maximum length for this attribute is 1024. - *
- * - */ - @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 = RangerConstants.BOOL_NONE; - } - - @Override - public int getMyClassType( ) { - return AppConstants.CLASS_TYPE_XA_PERM_MAP; - } - - /** - * This method sets the value to the member attribute permGroup. - * You cannot set null to the attribute. - * @param permGroup Value to set member attribute permGroup - */ - public void setPermGroup( String permGroup ) { - this.permGroup = permGroup; - } - - /** - * Returns the value for the member attribute permGroup - * @return String - value of member attribute permGroup. - */ - public String getPermGroup( ) { - return this.permGroup; - } - - /** - * This method sets the value to the member attribute resourceId. - * You cannot set null to the attribute. - * @param resourceId Value to set member attribute resourceId - */ - public void setResourceId( Long resourceId ) { - this.resourceId = resourceId; - } - - /** - * Returns the value for the member attribute resourceId - * @return Long - value of member attribute resourceId. - */ - public Long getResourceId( ) { - return this.resourceId; - } - - - /** - * This method sets the value to the member attribute groupId. - * You cannot set null to the attribute. - * @param groupId Value to set member attribute groupId - */ - public void setGroupId( Long groupId ) { - this.groupId = groupId; - } - - /** - * Returns the value for the member attribute groupId - * @return Long - value of member attribute groupId. - */ - public Long getGroupId( ) { - return this.groupId; - } - - - /** - * This method sets the value to the member attribute userId. - * You cannot set null to the attribute. - * @param userId Value to set member attribute userId - */ - public void setUserId( Long userId ) { - this.userId = userId; - } - - /** - * Returns the value for the member attribute userId - * @return Long - value of member attribute userId. - */ - public Long getUserId( ) { - return this.userId; - } - - - /** - * This method sets the value to the member attribute permFor. - * You cannot set null to the attribute. - * @param permFor Value to set member attribute permFor - */ - public void setPermFor( int permFor ) { - this.permFor = permFor; - } - - /** - * Returns the value for the member attribute permFor - * @return int - value of member attribute permFor. - */ - public int getPermFor( ) { - return this.permFor; - } - - /** - * This method sets the value to the member attribute permType. - * You cannot set null to the attribute. - * @param permType Value to set member attribute permType - */ - public void setPermType( int permType ) { - this.permType = permType; - } - - /** - * Returns the value for the member attribute permType - * @return int - value of member attribute permType. - */ - public int getPermType( ) { - return this.permType; - } - - /** - * This method sets the value to the member attribute isRecursive. - * You cannot set null to the attribute. - * @param isRecursive Value to set member attribute isRecursive - */ - public void setIsRecursive( int isRecursive ) { - this.isRecursive = isRecursive; - } - - /** - * Returns the value for the member attribute isRecursive - * @return int - value of member attribute isRecursive. - */ - public int getIsRecursive( ) { - return this.isRecursive; - } - - /** - * This method sets the value to the member attribute isWildCard. - * You cannot set null to the attribute. - * @param isWildCard Value to set member attribute isWildCard - */ - public void setIsWildCard( boolean isWildCard ) { - this.isWildCard = isWildCard; - } - - /** - * Returns the value for the member attribute isWildCard - * @return boolean - value of member attribute isWildCard. - */ - public boolean isIsWildCard( ) { - return this.isWildCard; - } - - /** - * This method sets the value to the member attribute grantOrRevoke. - * You cannot set null to the attribute. - * @param grantOrRevoke Value to set member attribute grantOrRevoke - */ - public void setGrantOrRevoke( boolean grantOrRevoke ) { - this.grantOrRevoke = grantOrRevoke; - } - - /** - * Returns the value for the member attribute grantOrRevoke - * @return boolean - value of member attribute grantOrRevoke. - */ - 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( "permFor".equals(fieldName) ) { - return "CommonEnums.XAPermForType"; - } - if( "permType".equals(fieldName) ) { - return "CommonEnums.XAPermType"; - } - if( "isRecursive".equals(fieldName) ) { - return "CommonEnums.BooleanValue"; - } - //Later TODO - //return super.getEnumName(fieldName); - return null; - } - + 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; + + /** + * Group to which the permission belongs to + *
    + *
  • The maximum length for this attribute is 1024. + *
+ */ + @Column(name = "PERM_GROUP", length = 1024) + protected String permGroup; + + /** + * Id of the resource + *
    + *
+ */ + @Column(name = "RES_ID") + protected Long resourceId; + + /** + * Id of the group + *
    + *
+ */ + @Column(name = "GROUP_ID") + protected Long groupId; + + /** + * Id of the user + *
    + *
+ */ + @Column(name = "USER_ID") + protected Long userId; + + /** + * Permission for user or group + *
    + *
  • This attribute is of type enum CommonEnums::XAPermForType + *
+ */ + @Column(name = "PERM_FOR", nullable = false) + protected int permFor = AppConstants.XA_PERM_FOR_UNKNOWN; + + /** + * Type of permission + *
    + *
  • This attribute is of type enum CommonEnums::XAPermType + *
+ */ + @Column(name = "PERM_TYPE", nullable = false) + protected int permType = AppConstants.XA_PERM_TYPE_UNKNOWN; + + /** + * Is recursive + *
    + *
  • This attribute is of type enum CommonEnums::BooleanValue + *
+ */ + @Column(name = "IS_RECURSIVE", nullable = false) + protected int isRecursive = RangerConstants.BOOL_NONE; + + /** + * Is wild card + *
    + *
+ */ + @Column(name = "IS_WILD_CARD", nullable = false) + protected boolean isWildCard = true; + + /** + * Grant is true and revoke is false + *
    + *
+ */ + @Column(name = "GRANT_REVOKE", nullable = false) + protected boolean grantOrRevoke = true; + + /** + * IP address to which the group belongs to + *
    + *
  • The maximum length for this attribute is 1024. + *
+ */ + @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 = RangerConstants.BOOL_NONE; + } + + public static String getEnumName(String fieldName) { + if ("permFor".equals(fieldName)) { + return "CommonEnums.XAPermForType"; + } else if ("permType".equals(fieldName)) { + return "CommonEnums.XAPermType"; + } else if ("isRecursive".equals(fieldName)) { + return "CommonEnums.BooleanValue"; + } + + //Later TODO + //return super.getEnumName(fieldName); + return null; + } + + @Override + public int getMyClassType() { + return AppConstants.CLASS_TYPE_XA_PERM_MAP; + } + + @Override + public Long getId() { + return id; + } + + @Override + public void setId(Long id) { + this.id = id; + } + + @Override + public int hashCode() { + return super.hashCode(); + } + + /** + * Checks for all attributes except referenced db objects + * + * @return true if all attributes match + */ + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } else if (!super.equals(obj)) { + return false; + } + + XXPermMap other = (XXPermMap) obj; + + return Objects.equals(permGroup, other.permGroup) && + Objects.equals(resourceId, other.resourceId) && + Objects.equals(groupId, other.groupId) && + Objects.equals(userId, other.userId) && + Objects.equals(permFor, other.permFor) && + Objects.equals(permType, other.permType) && + Objects.equals(isRecursive, other.isRecursive) && + Objects.equals(isWildCard, other.isWildCard) && + Objects.equals(grantOrRevoke, other.grantOrRevoke); + } + + /** + * 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; + } + + /** + * Returns the value for the member attribute permGroup + * + * @return String - value of member attribute permGroup. + */ + public String getPermGroup() { + return this.permGroup; + } + + /** + * This method sets the value to the member attribute permGroup. + * You cannot set null to the attribute. + * + * @param permGroup Value to set member attribute permGroup + */ + public void setPermGroup(String permGroup) { + this.permGroup = permGroup; + } + + /** + * Returns the value for the member attribute resourceId + * + * @return Long - value of member attribute resourceId. + */ + public Long getResourceId() { + return this.resourceId; + } + + /** + * This method sets the value to the member attribute resourceId. + * You cannot set null to the attribute. + * + * @param resourceId Value to set member attribute resourceId + */ + public void setResourceId(Long resourceId) { + this.resourceId = resourceId; + } + + /** + * Returns the value for the member attribute groupId + * + * @return Long - value of member attribute groupId. + */ + public Long getGroupId() { + return this.groupId; + } + + /** + * This method sets the value to the member attribute groupId. + * You cannot set null to the attribute. + * + * @param groupId Value to set member attribute groupId + */ + public void setGroupId(Long groupId) { + this.groupId = groupId; + } + + /** + * Returns the value for the member attribute userId + * + * @return Long - value of member attribute userId. + */ + public Long getUserId() { + return this.userId; + } + + /** + * This method sets the value to the member attribute userId. + * You cannot set null to the attribute. + * + * @param userId Value to set member attribute userId + */ + public void setUserId(Long userId) { + this.userId = userId; + } + + /** + * Returns the value for the member attribute permFor + * + * @return int - value of member attribute permFor. + */ + public int getPermFor() { + return this.permFor; + } + + /** + * This method sets the value to the member attribute permFor. + * You cannot set null to the attribute. + * + * @param permFor Value to set member attribute permFor + */ + public void setPermFor(int permFor) { + this.permFor = permFor; + } + + /** + * Returns the value for the member attribute permType + * + * @return int - value of member attribute permType. + */ + public int getPermType() { + return this.permType; + } + + /** + * This method sets the value to the member attribute permType. + * You cannot set null to the attribute. + * + * @param permType Value to set member attribute permType + */ + public void setPermType(int permType) { + this.permType = permType; + } + + /** + * Returns the value for the member attribute isRecursive + * + * @return int - value of member attribute isRecursive. + */ + public int getIsRecursive() { + return this.isRecursive; + } + + /** + * This method sets the value to the member attribute isRecursive. + * You cannot set null to the attribute. + * + * @param isRecursive Value to set member attribute isRecursive + */ + public void setIsRecursive(int isRecursive) { + this.isRecursive = isRecursive; + } + + /** + * Returns the value for the member attribute isWildCard + * + * @return boolean - value of member attribute isWildCard. + */ + public boolean isIsWildCard() { + return this.isWildCard; + } + + /** + * This method sets the value to the member attribute isWildCard. + * You cannot set null to the attribute. + * + * @param isWildCard Value to set member attribute isWildCard + */ + public void setIsWildCard(boolean isWildCard) { + this.isWildCard = isWildCard; + } + + /** + * Returns the value for the member attribute grantOrRevoke + * + * @return boolean - value of member attribute grantOrRevoke. + */ + public boolean isGrantOrRevoke() { + return this.grantOrRevoke; + } + + /** + * This method sets the value to the member attribute grantOrRevoke. + * You cannot set null to the attribute. + * + * @param grantOrRevoke Value to set member attribute grantOrRevoke + */ + public void setGrantOrRevoke(boolean grantOrRevoke) { + this.grantOrRevoke = grantOrRevoke; + } + + public String getIpAddress() { + return ipAddress; + } + + public void setIpAddress(String ipAddress) { + this.ipAddress = ipAddress; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/entity/XXPluginInfo.java b/security-admin/src/main/java/org/apache/ranger/entity/XXPluginInfo.java index a15d8d056d..6762a850c7 100644 --- a/security-admin/src/main/java/org/apache/ranger/entity/XXPluginInfo.java +++ b/security-admin/src/main/java/org/apache/ranger/entity/XXPluginInfo.java @@ -6,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY @@ -19,11 +19,11 @@ package org.apache.ranger.entity; -import java.util.Date; +import org.apache.ranger.common.AppConstants; import javax.persistence.Cacheable; -import javax.persistence.Entity; import javax.persistence.Column; +import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; @@ -32,188 +32,181 @@ import javax.persistence.Temporal; import javax.persistence.TemporalType; -import org.apache.ranger.common.AppConstants; +import java.util.Date; +import java.util.Objects; @Entity @Cacheable @Table(name = "x_plugin_info") public class XXPluginInfo implements java.io.Serializable { - private static final long serialVersionUID = 1L; - - @Id - @SequenceGenerator(name = "X_PLUGIN_INFO_SEQ", sequenceName = "X_PLUGIN_INFO_SEQ", allocationSize = 1) - @GeneratedValue(strategy = GenerationType.AUTO, generator = "X_PLUGIN_INFO_SEQ") - @Column(name = "id") - protected Long id; - - @Temporal(TemporalType.TIMESTAMP) - @Column(name="CREATE_TIME" ) - protected Date createTime; - - @Temporal(TemporalType.TIMESTAMP) - @Column(name="UPDATE_TIME" ) - protected Date updateTime; - - @Column(name = "service_name") - protected String serviceName; - - @Column(name = "app_type") - protected String appType; - - @Column(name = "host_name") - protected String hostName; - - @Column(name = "ip_address") - protected String ipAddress; - - @Column(name = "info") - protected String info; - - /** - * Default constructor. This will set all the attributes to default value. - */ - public XXPluginInfo( ) { - } - - public int getMyClassType( ) { - return AppConstants.CLASS_TYPE_NONE; - } - - public String getMyDisplayValue() { - return null; - } - - public void setId(Long id) { - this.id = id; - } - - public Long getId() { - return this.id; - } - - public void setCreateTime( Date createTime ) { - this.createTime = createTime; - } - - public Date getCreateTime( ) { - return this.createTime; - } - - public void setUpdateTime( Date updateTime ) { - this.updateTime = updateTime; - } - - public Date getUpdateTime( ) { - return this.updateTime; - } - - public void setServiceName(String serviceName) { - this.serviceName = serviceName; - } - - public String getServiceName() { - return this.serviceName; - } - - public void setAppType(String appType) { - this.appType = appType; - } - - public String getAppType() { - return this.appType; - } - - public void setHostName(String hostName) { - this.hostName = hostName; - } - - public String getHostName() { - return this.hostName; - } - - public void setIpAddress(String ipAddress) { - this.ipAddress = ipAddress; - } - - public String getIpAddress() { - return this.ipAddress; - } - - public void setInfo(String info) { - this.info = info; - } - - public String getInfo() { - return this.info; - } - - /** - * This return the bean content in string format - * @return formatedStr - */ - @Override - public String toString( ) { - String str = "XXPluginInfo={"; - str += "id={" + id + "} "; - str += "createTime={" + createTime + "} "; - str += "updateTime={" + updateTime + "} "; - str += "serviceName={" + serviceName + "} "; - str += "hostName={" + hostName + "} "; - str += "appType={" + appType + "} "; - str += "ipAddress={" + ipAddress + "} "; - str += "info={" + info + "} "; - str += "}"; - return str; - } - - /** - * Checks for all attributes except referenced db objects - * @return true if all attributes match - */ - @Override - public boolean equals( Object obj) { - if (obj == null) - return false; - if (this == obj) - return true; - if (getClass() != obj.getClass()) - return false; - XXPluginInfo other = (XXPluginInfo) 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.serviceName == null && other.serviceName != null) || (this.serviceName != null && !this.serviceName.equals(other.serviceName))) { - return false; - } - if ((this.hostName == null && other.hostName != null) || (this.hostName != null && !this.hostName.equals(other.hostName))) { - return false; - } - if ((this.appType == null && other.appType != null) || (this.appType != null && !this.appType.equals(other.appType))) { - return false; - } - if ((this.ipAddress == null && other.ipAddress != null) || (this.ipAddress != null && !this.ipAddress.equals(other.ipAddress))) { - return false; - } - if ((this.info == null && other.info != null) || (this.info != null && !this.info.equals(other.info))) { - return false; - } - return true; - } - - public static boolean equals(Object object1, Object object2) { - if (object1 == object2) { - return true; - } - if ((object1 == null) || (object2 == null)) { - return false; - } - return object1.equals(object2); - } - + private static final long serialVersionUID = 1L; + + @Id + @SequenceGenerator(name = "X_PLUGIN_INFO_SEQ", sequenceName = "X_PLUGIN_INFO_SEQ", allocationSize = 1) + @GeneratedValue(strategy = GenerationType.AUTO, generator = "X_PLUGIN_INFO_SEQ") + @Column(name = "id") + protected Long id; + + @Temporal(TemporalType.TIMESTAMP) + @Column(name = "CREATE_TIME") + protected Date createTime; + + @Temporal(TemporalType.TIMESTAMP) + @Column(name = "UPDATE_TIME") + protected Date updateTime; + + @Column(name = "service_name") + protected String serviceName; + + @Column(name = "app_type") + protected String appType; + + @Column(name = "host_name") + protected String hostName; + + @Column(name = "ip_address") + protected String ipAddress; + + @Column(name = "info") + protected String info; + + /** + * Default constructor. This will set all the attributes to default value. + */ + public XXPluginInfo() { + } + + public static boolean equals(Object object1, Object object2) { + if (object1 == object2) { + return true; + } else if ((object1 == null) || (object2 == null)) { + return false; + } + + return object1.equals(object2); + } + + @Override + public int hashCode() { + return super.hashCode(); + } + + /** + * Checks for all attributes except referenced db objects + * + * @return true if all attributes match + */ + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } else if (obj == null) { + return false; + } else if (getClass() != obj.getClass()) { + return false; + } + + XXPluginInfo other = (XXPluginInfo) obj; + + return Objects.equals(id, other.id) && + Objects.equals(createTime, other.createTime) && + Objects.equals(updateTime, other.updateTime) && + Objects.equals(serviceName, other.serviceName) && + Objects.equals(hostName, other.hostName) && + Objects.equals(appType, other.appType) && + Objects.equals(ipAddress, other.ipAddress) && + Objects.equals(info, other.info); + } + + /** + * This return the bean content in string format + * + * @return formatedStr + */ + @Override + public String toString() { + String str = "XXPluginInfo={"; + str += "id={" + id + "} "; + str += "createTime={" + createTime + "} "; + str += "updateTime={" + updateTime + "} "; + str += "serviceName={" + serviceName + "} "; + str += "hostName={" + hostName + "} "; + str += "appType={" + appType + "} "; + str += "ipAddress={" + ipAddress + "} "; + str += "info={" + info + "} "; + str += "}"; + return str; + } + + public int getMyClassType() { + return AppConstants.CLASS_TYPE_NONE; + } + + public String getMyDisplayValue() { + return null; + } + + public Long getId() { + return this.id; + } + + public void setId(Long id) { + this.id = id; + } + + public Date getCreateTime() { + return this.createTime; + } + + public void setCreateTime(Date createTime) { + this.createTime = createTime; + } + + public Date getUpdateTime() { + return this.updateTime; + } + + public void setUpdateTime(Date updateTime) { + this.updateTime = updateTime; + } + + public String getServiceName() { + return this.serviceName; + } + + public void setServiceName(String serviceName) { + this.serviceName = serviceName; + } + + public String getAppType() { + return this.appType; + } + + public void setAppType(String appType) { + this.appType = appType; + } + + public String getHostName() { + return this.hostName; + } + + public void setHostName(String hostName) { + this.hostName = hostName; + } + + public String getIpAddress() { + return this.ipAddress; + } + + public void setIpAddress(String ipAddress) { + this.ipAddress = ipAddress; + } + + public String getInfo() { + return this.info; + } + + public void setInfo(String info) { + this.info = info; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/entity/XXPolicy.java b/security-admin/src/main/java/org/apache/ranger/entity/XXPolicy.java index a84ecfafeb..6c7a4a45b5 100644 --- a/security-admin/src/main/java/org/apache/ranger/entity/XXPolicy.java +++ b/security-admin/src/main/java/org/apache/ranger/entity/XXPolicy.java @@ -18,55 +18,64 @@ */ package org.apache.ranger.entity; -import javax.persistence.*; +import javax.persistence.Cacheable; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.SequenceGenerator; +import javax.persistence.Table; + +import java.util.Objects; @Entity @Cacheable @Table(name = "x_policy") public class XXPolicy extends XXPolicyBase implements java.io.Serializable { - private static final long serialVersionUID = 1L; - /** - * id of the XXPolicy - *
    - *
- * - */ - @Id - @SequenceGenerator(name = "x_policy_SEQ", sequenceName = "x_policy_SEQ", allocationSize = 1) - @GeneratedValue(strategy = GenerationType.AUTO, generator = "x_policy_SEQ") - @Column(name = "id") - protected Long id; + private static final long serialVersionUID = 1L; + + /** + * id of the XXPolicy + *
    + *
+ */ + @Id + @SequenceGenerator(name = "x_policy_SEQ", sequenceName = "x_policy_SEQ", allocationSize = 1) + @GeneratedValue(strategy = GenerationType.AUTO, generator = "x_policy_SEQ") + @Column(name = "id") + protected Long id; + + @Override + public Long getId() { + return id; + } + + @Override + public void setId(Long id) { + this.id = id; + } - @Override - public void setId(Long id) { - this.id = id; - } + @Override + public int hashCode() { + return super.hashCode(); + } - @Override - public Long getId() { - return id; - } + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } else if (!super.equals(obj)) { + return false; + } - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (!super.equals(obj)) - return false; - if (getClass() != obj.getClass()) - return false; - XXPolicy other = (XXPolicy) obj; - if (id == null) { - if (other.id != null) - return false; - } else if (!id.equals(other.id)) - return false; - return true; - } + XXPolicy other = (XXPolicy) obj; - @Override - public String toString() { - return "XXPolicy [id=" + id + "]"; - } + return Objects.equals(id, other.id); + } + @Override + public String toString() { + return "XXPolicy [id=" + id + "]"; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/entity/XXPolicyBase.java b/security-admin/src/main/java/org/apache/ranger/entity/XXPolicyBase.java index 5817352551..c863a94482 100644 --- a/security-admin/src/main/java/org/apache/ranger/entity/XXPolicyBase.java +++ b/security-admin/src/main/java/org/apache/ranger/entity/XXPolicyBase.java @@ -21,438 +21,348 @@ import javax.persistence.MappedSuperclass; import javax.persistence.Version; +import java.util.Objects; + @MappedSuperclass public abstract class XXPolicyBase extends XXDBBase { - private static final long serialVersionUID = 1L; - - /** - * Global Id for the object - *
    - *
  • The maximum length for this attribute is 512. - *
- * - */ - @Column(name = "guid", unique = true, nullable = false, length = 512) - protected String guid; - - /** - * version of the XXPolicy - *
    - *
- * - */ - @Version - @Column(name = "version") - protected Long version; - - /** - * service of the XXPolicy - *
    - *
- * - */ - @Column(name = "service") - protected Long service; - - /** - * name of the XXPolicy - *
    - *
- * - */ - @Column(name = "name") - protected String name; - - /** - * policyType of the XXPolicy - *
    - *
- * - */ - @Column(name = "policy_type") - protected Integer policyType; - - /** - * policyPriority of the XXPolicy - *
    - *
- * - */ - @Column(name = "policy_priority") - protected Integer policyPriority; - /** - * description of the XXPolicy - *
    - *
- * - */ - @Column(name = "description") - protected String description; - - /** - * resource_signature of the XXPolicy - *
    - *
- * - */ - @Column(name = "resource_signature") - protected String resourceSignature; - - /** - * isEnabled of the XXPolicy - *
    - *
- * - */ - @Column(name = "is_enabled") - protected boolean isEnabled; - - /** - * isAuditEnabled of the XXPolicy - *
    - *
- * - */ - @Column(name = "is_audit_enabled") - protected boolean isAuditEnabled; + private static final long serialVersionUID = 1L; + + /** + * Global Id for the object + *
    + *
  • The maximum length for this attribute is 512. + *
+ */ + @Column(name = "guid", unique = true, nullable = false, length = 512) + protected String guid; + + /** + * version of the XXPolicy + *
    + *
+ */ + @Version + @Column(name = "version") + protected Long version; + + /** + * service of the XXPolicy + *
    + *
+ */ + @Column(name = "service") + protected Long service; + + /** + * name of the XXPolicy + *
    + *
+ */ + @Column(name = "name") + protected String name; + + /** + * policyType of the XXPolicy + *
    + *
+ */ + @Column(name = "policy_type") + protected Integer policyType; + + /** + * policyPriority of the XXPolicy + *
    + *
+ */ + @Column(name = "policy_priority") + protected Integer policyPriority; + /** + * description of the XXPolicy + *
    + *
+ */ + @Column(name = "description") + protected String description; + + /** + * resource_signature of the XXPolicy + *
    + *
+ */ + @Column(name = "resource_signature") + protected String resourceSignature; + + /** + * isEnabled of the XXPolicy + *
    + *
+ */ + @Column(name = "is_enabled") + protected boolean isEnabled; + + /** + * isAuditEnabled of the XXPolicy + *
    + *
+ */ + @Column(name = "is_audit_enabled") + protected boolean isAuditEnabled; /** * options of the XXPolicy *
    *
- * */ @Column(name = "policy_options") protected String options; - @Column(name = "policy_text") - protected String policyText; + @Column(name = "policy_text") + protected String policyText; @Column(name = "zone_id") protected Long zoneId; - /** - * @return the gUID - */ - public String getGuid() { - return guid; - } - - /** - * @param gUID - * the gUID to set - */ - public void setGuid(String gUID) { - guid = gUID; - } - - /** - * This method sets the value to the member attribute version . You - * cannot set null to the attribute. - * - * @param version - * Value to set member attribute version - */ - public void setVersion(Long version) { - this.version = version; - } - - /** - * Returns the value for the member attribute version - * - * @return Date - value of member attribute version . - */ - public Long getVersion() { - return this.version; - } - - /** - * This method sets the value to the member attribute service . You - * cannot set null to the attribute. - * - * @param service - * Value to set member attribute service - */ - public void setService(Long service) { - this.service = service; - } - - /** - * Returns the value for the member attribute service - * - * @return Date - value of member attribute service . - */ - public Long getService() { - return this.service; - } - - /** - * This method sets the value to the member attribute name . You - * cannot set null to the attribute. - * - * @param name - * Value to set member attribute name - */ - public void setName(String name) { - this.name = name; - } - - /** - * Returns the value for the member attribute name - * - * @return Date - value of member attribute name . - */ - public String getName() { - return this.name; - } - - /** - * This method sets the value to the member attribute description . - * You cannot set null to the attribute. - * - * @param description - * Value to set member attribute description - */ - public void setDescription(String description) { - this.description = description; - } - - /** - * Returns the value for the member attribute description - * - * @return Date - value of member attribute description . - */ - public String getDescription() { - return this.description; - } - - /** - * @return the resourceSignature - */ - public String getResourceSignature() { - return resourceSignature; - } - - /** - * @param resourceSignature the resourceSignature to set - */ - public void setResourceSignature(String resourceSignature) { - this.resourceSignature = resourceSignature; - } - - /** - * This method sets the value to the member attribute isEnabled . - * You cannot set null to the attribute. - * - * @param isEnabled - * Value to set member attribute isEnabled - */ - public void setIsEnabled(boolean isEnabled) { - this.isEnabled = isEnabled; - } - - /** - * Returns the value for the member attribute isEnabled - * - * @return Value of member attribute isEnabled . - */ - public boolean getIsEnabled() { - return this.isEnabled; - } - - /** - * This method sets the value to the member attribute isAuditEnabled - * . You cannot set null to the attribute. - * - * @param isAuditEnabled - * Value to set member attribute isAuditEnabled - */ - public void setIsAuditEnabled(boolean isAuditEnabled) { - this.isAuditEnabled = isAuditEnabled; - } - - /** - * Returns the value for the member attribute isAuditEnabled - * - * @return Value of member attribute isAuditEnabled . - */ - public boolean getIsAuditEnabled() { - return this.isAuditEnabled; - } - - public Integer getPolicyType() { - return policyType; - } - - public void setPolicyType(Integer policyType) { - this.policyType = policyType; - } - - public Integer getPolicyPriority() { - return policyPriority; - } - - public void setPolicyPriority(Integer policyPriority) { - this.policyPriority = policyPriority; - } - - /** - * This method sets the value to the member attribute options . - * - * @param options - * Value to set member attribute options - */ - public void setOptions(String options) { - this.options = options; + /** + * @return the gUID + */ + public String getGuid() { + return guid; + } + + /** + * @param gUID the gUID to set + */ + public void setGuid(String gUID) { + guid = gUID; + } + + /** + * Returns the value for the member attribute version + * + * @return Date - value of member attribute version . + */ + public Long getVersion() { + return this.version; + } + + /** + * This method sets the value to the member attribute version . You + * cannot set null to the attribute. + * + * @param version Value to set member attribute version + */ + public void setVersion(Long version) { + this.version = version; + } + + /** + * Returns the value for the member attribute service + * + * @return Date - value of member attribute service . + */ + public Long getService() { + return this.service; + } + + /** + * This method sets the value to the member attribute service . You + * cannot set null to the attribute. + * + * @param service Value to set member attribute service + */ + public void setService(Long service) { + this.service = service; } - /** - * Returns the value for the member attribute options - * - * @return Value of member attribute options . - */ - public String getOptions() { + /** + * Returns the value for the member attribute name + * + * @return Date - value of member attribute name . + */ + public String getName() { + return this.name; + } + + /** + * This method sets the value to the member attribute name . You + * cannot set null to the attribute. + * + * @param name Value to set member attribute name + */ + public void setName(String name) { + this.name = name; + } + + /** + * Returns the value for the member attribute description + * + * @return Date - value of member attribute description . + */ + public String getDescription() { + return this.description; + } + + /** + * This method sets the value to the member attribute description . + * You cannot set null to the attribute. + * + * @param description Value to set member attribute description + */ + public void setDescription(String description) { + this.description = description; + } + + /** + * @return the resourceSignature + */ + public String getResourceSignature() { + return resourceSignature; + } + + /** + * @param resourceSignature the resourceSignature to set + */ + public void setResourceSignature(String resourceSignature) { + this.resourceSignature = resourceSignature; + } + + /** + * Returns the value for the member attribute isEnabled + * + * @return Value of member attribute isEnabled . + */ + public boolean getIsEnabled() { + return this.isEnabled; + } + + /** + * This method sets the value to the member attribute isEnabled . + * You cannot set null to the attribute. + * + * @param isEnabled Value to set member attribute isEnabled + */ + public void setIsEnabled(boolean isEnabled) { + this.isEnabled = isEnabled; + } + + /** + * Returns the value for the member attribute isAuditEnabled + * + * @return Value of member attribute isAuditEnabled . + */ + public boolean getIsAuditEnabled() { + return this.isAuditEnabled; + } + + /** + * This method sets the value to the member attribute isAuditEnabled + * . You cannot set null to the attribute. + * + * @param isAuditEnabled Value to set member attribute isAuditEnabled + */ + public void setIsAuditEnabled(boolean isAuditEnabled) { + this.isAuditEnabled = isAuditEnabled; + } + + public Integer getPolicyType() { + return policyType; + } + + public void setPolicyType(Integer policyType) { + this.policyType = policyType; + } + + public Integer getPolicyPriority() { + return policyPriority; + } + + public void setPolicyPriority(Integer policyPriority) { + this.policyPriority = policyPriority; + } + + /** + * Returns the value for the member attribute options + * + * @return Value of member attribute options . + */ + public String getOptions() { return this.options; } + /** + * This method sets the value to the member attribute options . + * + * @param options Value to set member attribute options + */ + public void setOptions(String options) { + this.options = options; + } - public void setPolicyText(String policyText) { - this.policyText = policyText; - } + public String getPolicyText() { + return this.policyText; + } - public String getPolicyText() { - return this.policyText; - } + public void setPolicyText(String policyText) { + this.policyText = policyText; + } - public Long getZoneId() {return zoneId; } + public Long getZoneId() { + return zoneId; + } - public void setZoneId(Long zoneId) { + public void setZoneId(Long zoneId) { this.zoneId = zoneId; } + @Override + public int hashCode() { + return super.hashCode(); + } /* - * (non-Javadoc) - * - * @see java.lang.Object#equals(java.lang.Object) - */ - @Override - public boolean equals(Object obj) { - if (!super.equals(obj)) { - return false; - } - if (this == obj) { - return true; - } - if (!super.equals(obj)) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - XXPolicyBase other = (XXPolicyBase) obj; - if (guid == null) { - if (other.guid != null) { - return false; - } - } else if (!guid.equals(other.guid)) { - return false; - } - if (description == null) { - if (other.description != null) { - return false; - } - } else if (!description.equals(other.description)) { - return false; - } - if (resourceSignature == null) { - if (other.resourceSignature != null) { - return false; - } - } else if (!resourceSignature.equals(other.resourceSignature)) { - return false; - } - if (isAuditEnabled != other.isAuditEnabled) { - return false; - } - if (isEnabled != other.isEnabled) { - return false; - } - if (name == null) { - if (other.name != null) { - return false; - } - } else if (!name.equals(other.name)) { - return false; - } - if (service == null) { - if (other.service != null) { - return false; - } - } else if (!service.equals(other.service)) { - return false; - } - if (version == null) { - if (other.version != null) { - return false; - } - } else if (!version.equals(other.version)) { - return false; - } - if (policyType == null) { - if (other.policyType != null) { - return false; - } - } else if (!policyType.equals(other.policyType)) { - return false; - } - if (policyPriority == null) { - if (other.policyPriority != null) { - return false; - } - } else if (!policyPriority.equals(other.policyPriority)) { - return false; - } - if (options == null) { - if (other.options != null) { - return false; - } - } else if (!options.equals(other.options)) { - return false; - } - if (policyText == null) { - if (other.policyText != null) { - return false; - } - } else if (!policyText.equals(other.policyText)) { + * (non-Javadoc) + * + * @see java.lang.Object#equals(java.lang.Object) + */ + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } else if (!super.equals(obj)) { return false; } - if (zoneId == null) { - if (other.zoneId != null) { - return false; - } - } else if (!zoneId.equals(other.zoneId)) { - return false; - } - return true; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#toString() - */ - @Override - public String toString() { - String str = "XXPolicyBase={"; - str += super.toString(); - str += " [guid=" + guid + ", version=" + version + ", service=" + service + ", name=" + name - + ", policyType=" + policyType + ", policyPriority=" + policyPriority + ", description=" + description + ", resourceSignature=" - + resourceSignature + ", isEnabled=" + isEnabled + ", isAuditEnabled=" + isAuditEnabled - + ", options=" + options + ", zoneId=" + zoneId + "]"; - str += "}"; - return str; - } + XXPolicyBase other = (XXPolicyBase) obj; + + return Objects.equals(guid, other.guid) && + Objects.equals(description, other.description) && + Objects.equals(resourceSignature, other.resourceSignature) && + Objects.equals(isAuditEnabled, other.isAuditEnabled) && + Objects.equals(isEnabled, other.isEnabled) && + Objects.equals(name, other.name) && + Objects.equals(service, other.service) && + Objects.equals(version, other.version) && + Objects.equals(policyType, other.policyType) && + Objects.equals(policyPriority, other.policyPriority) && + Objects.equals(options, other.options) && + Objects.equals(policyText, other.policyText) && + Objects.equals(zoneId, other.zoneId); + } + /* + * (non-Javadoc) + * + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + String str = "XXPolicyBase={"; + str += super.toString(); + str += " [guid=" + guid + ", version=" + version + ", service=" + service + ", name=" + name + + ", policyType=" + policyType + ", policyPriority=" + policyPriority + ", description=" + description + ", resourceSignature=" + + resourceSignature + ", isEnabled=" + isEnabled + ", isAuditEnabled=" + isAuditEnabled + + ", options=" + options + ", zoneId=" + zoneId + "]"; + str += "}"; + return str; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/entity/XXPolicyChangeLog.java b/security-admin/src/main/java/org/apache/ranger/entity/XXPolicyChangeLog.java index f1c026cea2..9bb88d58df 100644 --- a/security-admin/src/main/java/org/apache/ranger/entity/XXPolicyChangeLog.java +++ b/security-admin/src/main/java/org/apache/ranger/entity/XXPolicyChangeLog.java @@ -19,12 +19,12 @@ package org.apache.ranger.entity; -import java.util.Date; -import java.util.Objects; +import org.apache.ranger.common.AppConstants; +import org.apache.ranger.common.DateUtil; import javax.persistence.Cacheable; -import javax.persistence.Entity; import javax.persistence.Column; +import javax.persistence.Entity; import javax.persistence.EntityListeners; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; @@ -34,10 +34,10 @@ import javax.persistence.Temporal; import javax.persistence.TemporalType; -import org.apache.ranger.common.AppConstants; -import org.apache.ranger.common.DateUtil; +import java.util.Date; +import java.util.Objects; -@EntityListeners( org.apache.ranger.common.db.JPABeanCallbacks.class) +@EntityListeners(org.apache.ranger.common.db.JPABeanCallbacks.class) @Entity @Cacheable @Table(name = "x_policy_change_log") @@ -51,7 +51,7 @@ public class XXPolicyChangeLog implements java.io.Serializable { protected Long id; @Temporal(TemporalType.TIMESTAMP) - @Column(name="create_time" ) + @Column(name = "create_time") protected Date createTime = DateUtil.getUTCDate(); @Column(name = "service_id") @@ -63,28 +63,28 @@ public class XXPolicyChangeLog implements java.io.Serializable { @Column(name = "policy_version") protected Long policyVersion; - @Column(name = "service_type") - protected String serviceType; + @Column(name = "service_type") + protected String serviceType; - @Column(name = "policy_type") - protected Integer policyType; + @Column(name = "policy_type") + protected Integer policyType; - @Column(name = "zone_name") + @Column(name = "zone_name") protected String zoneName; - @Column(name = "policy_id") - protected Long policyId; + @Column(name = "policy_id") + protected Long policyId; - @Column(name = "policy_guid") - protected String policyGuid; + @Column(name = "policy_guid") + protected String policyGuid; /** * Default constructor. This will set all the attributes to default value. */ - public XXPolicyChangeLog( ) { + public XXPolicyChangeLog() { } - public int getMyClassType( ) { + public int getMyClassType() { return AppConstants.CLASS_TYPE_NONE; } @@ -92,84 +92,118 @@ public String getMyDisplayValue() { return null; } + public Long getId() { + return this.id; + } + public void setId(Long id) { this.id = id; } - public Long getId() { - return this.id; + public Date getCreateTime() { + return this.createTime; } - public void setCreateTime( Date createTime ) { + public void setCreateTime(Date createTime) { this.createTime = createTime; } - public Date getCreateTime( ) { - return this.createTime; + public Long getServiceId() { + return this.serviceId; } public void setServiceId(Long serviceId) { this.serviceId = serviceId; } - public Long getServiceId() { - return this.serviceId; + public Long getPolicyVersion() { + return this.policyVersion; } public void setPolicyVersion(Long policyVersion) { this.policyVersion = policyVersion; } - public Long getPolicyVersion() { - return this.policyVersion; + public Integer getChangeType() { + return this.changeType; } public void setChangeType(Integer changeType) { this.changeType = changeType; } - public Integer getChangeType() { - return this.changeType; + public String getServiceType() { + return this.serviceType; } - public String getServiceType() { return this.serviceType; } - - public void setServiceType(String serviceType) { - this.serviceType = serviceType; - } + public void setServiceType(String serviceType) { + this.serviceType = serviceType; + } - public Integer getPolicyType() { return this.policyType; } + public Integer getPolicyType() { + return this.policyType; + } - public void setPolicyType(Integer policyType) { - this.policyType = policyType; - } + public void setPolicyType(Integer policyType) { + this.policyType = policyType; + } - public String getZoneName() { return this.zoneName; } + public String getZoneName() { + return this.zoneName; + } public void setZoneName(String zoneName) { this.zoneName = zoneName; } - public Long getPolicyId() { return this.policyId; } + public Long getPolicyId() { + return this.policyId; + } - public void setPolicyId(Long policyId) { - this.policyId = policyId; - } + public void setPolicyId(Long policyId) { + this.policyId = policyId; + } - public String getPolicyGuid() { - return this.policyGuid; - } + public String getPolicyGuid() { + return this.policyGuid; + } - public void setPolicyGuid(String policyGuid) { - this.policyGuid = policyGuid; - } + public void setPolicyGuid(String policyGuid) { + this.policyGuid = policyGuid; + } + + @Override + public int hashCode() { + return super.hashCode(); + } + + /** + * Checks for all attributes except referenced db objects + * + * @return true if all attributes match + */ + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } else if (obj == null) { + return false; + } else if (getClass() != obj.getClass()) { + return false; + } + + XXPolicyChangeLog other = (XXPolicyChangeLog) obj; + + return Objects.equals(this.id, other.id) && Objects.equals(this.serviceId, other.serviceId) && Objects.equals(this.policyVersion, other.policyVersion) && Objects.equals(this.createTime, other.createTime) && Objects.equals(this.changeType, other.changeType) && Objects.equals(this.serviceType, other.serviceType) && Objects.equals(this.policyType, other.policyType) && Objects.equals(this.zoneName, other.zoneName) && Objects.equals(this.policyId, other.policyId) && Objects.equals(this.policyGuid, other.policyGuid); + } /** * This return the bean content in string format + * * @return formatedStr */ @Override - public String toString( ) { + public String toString() { String str = "XXPolicyChangeLog={"; str += "id={" + id + "} "; str += "createTime={" + createTime + "} "; @@ -184,29 +218,4 @@ public String toString( ) { str += "}"; return str; } - - /** - * Checks for all attributes except referenced db objects - * @return true if all attributes match - */ - @Override - public boolean equals( Object obj) { - if (obj == null) - return false; - if (this == obj) - return true; - if (!super.equals(obj)) - return false; - if (getClass() != obj.getClass()) - return false; - - XXPolicyChangeLog other = (XXPolicyChangeLog) obj; - - return Objects.equals(this.id, other.id) && Objects.equals(this.serviceId, other.serviceId) && Objects.equals(this.policyVersion, other.policyVersion) - && Objects.equals(this.createTime, other.createTime) && Objects.equals(this.changeType, other.changeType) && Objects.equals(this.serviceType, other.serviceType) - && Objects.equals(this.policyType, other.policyType) && Objects.equals(this.zoneName, other.zoneName) && Objects.equals(this.policyId, other.policyId) - && Objects.equals(this.policyGuid, other.policyGuid); - } - } - diff --git a/security-admin/src/main/java/org/apache/ranger/entity/XXPolicyConditionDef.java b/security-admin/src/main/java/org/apache/ranger/entity/XXPolicyConditionDef.java index 393f043d0c..27007ccb58 100644 --- a/security-admin/src/main/java/org/apache/ranger/entity/XXPolicyConditionDef.java +++ b/security-admin/src/main/java/org/apache/ranger/entity/XXPolicyConditionDef.java @@ -18,558 +18,468 @@ */ package org.apache.ranger.entity; -import javax.persistence.*; +import javax.persistence.Cacheable; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.SequenceGenerator; +import javax.persistence.Table; +import java.util.Objects; @Entity @Cacheable @Table(name = "x_policy_condition_def") -public class XXPolicyConditionDef extends XXDBBase implements - java.io.Serializable { - private static final long serialVersionUID = 1L; - /** - * id of the XXPolicyConditionDef - *
    - *
- * - */ - @Id - @SequenceGenerator(name = "x_policy_condition_def_SEQ", sequenceName = "x_policy_condition_def_SEQ", allocationSize = 1) - @GeneratedValue(strategy = GenerationType.AUTO, generator = "x_policy_condition_def_SEQ") - @Column(name = "id") - protected Long id; - - /** - * defId of the XXPolicyConditionDef - *
    - *
- * - */ - @Column(name = "def_id") - protected Long defId; - - /** - * itemId of the XXPolicyConditionDef - *
    - *
- * - */ - @Column(name = "item_id") - protected Long itemId; - - /** - * name of the XXPolicyConditionDef - *
    - *
- * - */ - @Column(name = "name") - protected String name; - - /** - * evaluator of the XXPolicyConditionDef - *
    - *
- * - */ - @Column(name = "evaluator") - protected String evaluator; - - /** - * evaluatorOptions of the XXPolicyConditionDef - *
    - *
- * - */ - @Column(name = "evaluator_options") - protected String evaluatorOptions; - - /** - * validationRegEx of the XXPolicyConditionDef - *
    - *
- * - */ - @Column(name = "validation_reg_ex") - protected String validationRegEx; - - /** - * validationMessage of the XXPolicyConditionDef - *
    - *
- * - */ - @Column(name = "validation_message") - protected String validationMessage; - - /** - * uiHint of the XXPolicyConditionDef - *
    - *
- * - */ - @Column(name = "ui_hint") - protected String uiHint; - - /** - * label of the XXPolicyConditionDef - *
    - *
- * - */ - @Column(name = "label") - protected String label; - - /** - * description of the XXPolicyConditionDef - *
    - *
- * - */ - @Column(name = "description") - protected String description; - - /** - * rbKeyLabel of the XXPolicyConditionDef - *
    - *
- * - */ - @Column(name = "rb_key_label") - protected String rbKeyLabel; - - /** - * rbKeyDescription of the XXPolicyConditionDef - *
    - *
- * - */ - @Column(name = "rb_key_description") - protected String rbKeyDescription; - - /** - * rbKeyValidationMessage of the XXPolicyConditionDef - *
    - *
- * - */ - @Column(name = "rb_key_validation_message") - protected String rbKeyValidationMessage; - - /** - * order of the XXPolicyConditionDef - *
    - *
- * - */ - @Column(name = "sort_order") - protected Integer order; - - /** - * This method sets the value to the member attribute id . You - * cannot set null to the attribute. - * - * @param id - * Value to set member attribute id - */ - public void setId(Long id) { - this.id = id; - } - - /** - * Returns the value for the member attribute id - * - * @return Date - value of member attribute id . - */ - public Long getId() { - return this.id; - } - - /** - * This method sets the value to the member attribute defId . You - * cannot set null to the attribute. - * - * @param defId - * Value to set member attribute defId - */ - public void setDefid(Long defId) { - this.defId = defId; - } - - /** - * Returns the value for the member attribute itemId - * - * @return Long - value of member attribute itemId . - */ - public Long getItemId() { - return this.itemId; - } - - /** - * This method sets the value to the member attribute itemId . You - * cannot set null to the attribute. - * - * @param itemId - * Value to set member attribute itemId - */ - public void setItemId(Long itemId) { - this.itemId = itemId; - } - - /** - * Returns the value for the member attribute defId - * - * @return Date - value of member attribute defId . - */ - public Long getDefid() { - return this.defId; - } - - /** - * This method sets the value to the member attribute name . You - * cannot set null to the attribute. - * - * @param name - * Value to set member attribute name - */ - public void setName(String name) { - this.name = name; - } - - /** - * Returns the value for the member attribute name - * - * @return Date - value of member attribute name . - */ - public String getName() { - return this.name; - } - - /** - * This method sets the value to the member attribute evaluator . - * You cannot set null to the attribute. - * - * @param evaluator - * Value to set member attribute evaluator - */ - public void setEvaluator(String evaluator) { - this.evaluator = evaluator; - } - - /** - * Returns the value for the member attribute evaluator - * - * @return Date - value of member attribute evaluator . - */ - public String getEvaluator() { - return this.evaluator; - } - - /** - * This method sets the value to the member attribute - * evaluatorOptions . You cannot set null to the attribute. - * - * @param evaluatorOptions - * Value to set member attribute evaluatorOptions - */ - public void setEvaluatoroptions(String evaluatorOptions) { - this.evaluatorOptions = evaluatorOptions; - } - - /** - * Returns the value for the member attribute evaluatorOptions - * - * @return Date - value of member attribute evaluatorOptions . - */ - public String getEvaluatoroptions() { - return this.evaluatorOptions; - } - - /** - * @return the validationRegEx - */ - public String getValidationRegEx() { - return validationRegEx; - } - - /** - * @param validationRegEx the validationRegEx to set - */ - public void setValidationRegEx(String validationRegEx) { - this.validationRegEx = validationRegEx; - } - - /** - * @return the validationMessage - */ - public String getValidationMessage() { - return validationMessage; - } - - /** - * @param validationMessage the validationMessage to set - */ - public void setValidationMessage(String validationMessage) { - this.validationMessage = validationMessage; - } - - /** - * @return the uiHint - */ - public String getUiHint() { - return uiHint; - } - - /** - * @param uiHint the uiHint to set - */ - public void setUiHint(String uiHint) { - this.uiHint = uiHint; - } - - /** - * This method sets the value to the member attribute label . You - * cannot set null to the attribute. - * - * @param label - * Value to set member attribute label - */ - public void setLabel(String label) { - this.label = label; - } - - /** - * Returns the value for the member attribute label - * - * @return Date - value of member attribute label . - */ - public String getLabel() { - return this.label; - } - - /** - * This method sets the value to the member attribute description . - * You cannot set null to the attribute. - * - * @param description - * Value to set member attribute description - */ - public void setDescription(String description) { - this.description = description; - } - - /** - * Returns the value for the member attribute description - * - * @return Date - value of member attribute description . - */ - public String getDescription() { - return this.description; - } - - /** - * This method sets the value to the member attribute rbKeyLabel . - * You cannot set null to the attribute. - * - * @param rbKeyLabel - * Value to set member attribute rbKeyLabel - */ - public void setRbkeylabel(String rbKeyLabel) { - this.rbKeyLabel = rbKeyLabel; - } - - /** - * Returns the value for the member attribute rbKeyLabel - * - * @return Date - value of member attribute rbKeyLabel . - */ - public String getRbkeylabel() { - return this.rbKeyLabel; - } - - /** - * This method sets the value to the member attribute - * rbKeyDescription . You cannot set null to the attribute. - * - * @param rbKeyDescription - * Value to set member attribute rbKeyDescription - */ - public void setRbkeydescription(String rbKeyDescription) { - this.rbKeyDescription = rbKeyDescription; - } - - /** - * Returns the value for the member attribute rbKeyDescription - * - * @return Date - value of member attribute rbKeyDescription . - */ - public String getRbkeydescription() { - return this.rbKeyDescription; - } - - /** - * @return the rbKeyValidationMessage - */ - public String getRbKeyValidationMessage() { - return rbKeyValidationMessage; - } - - /** - * @param rbKeyValidationMessage the rbKeyValidationMessage to set - */ - public void setRbKeyValidationMessage(String rbKeyValidationMessage) { - this.rbKeyValidationMessage = rbKeyValidationMessage; - } - - /** - * This method sets the value to the member attribute order . You - * cannot set null to the attribute. - * - * @param order - * Value to set member attribute order - */ - public void setOrder(Integer order) { - this.order = order; - } - - /** - * Returns the value for the member attribute order - * - * @return Date - value of member attribute order . - */ - public Integer getOrder() { - return this.order; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#equals(java.lang.Object) - */ - @Override - public boolean equals(Object obj) { - if (!super.equals(obj)) { - return false; - } - if (this == obj) { - return true; - } - if (!super.equals(obj)) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - XXPolicyConditionDef other = (XXPolicyConditionDef) obj; - if (defId == null) { - if (other.defId != null) { - return false; - } - } else if (!defId.equals(other.defId)) { - return false; - } - if (itemId == null) { - if (other.itemId != null) { - return false; - } - } else if (!itemId.equals(other.itemId)) { - return false; - } - if (description == null) { - if (other.description != null) { - return false; - } - } else if (!description.equals(other.description)) { - return false; - } - if (evaluator == null) { - if (other.evaluator != null) { - return false; - } - } else if (!evaluator.equals(other.evaluator)) { - return false; - } - if (evaluatorOptions == null) { - if (other.evaluatorOptions != null) { - return false; - } - } else if (!evaluatorOptions.equals(other.evaluatorOptions)) { - return false; - } - if (id == null) { - if (other.id != null) { - return false; - } - } else if (!id.equals(other.id)) { - return false; - } - - if(!equals(validationRegEx, other.validationRegEx) || - !equals(validationMessage, other.validationMessage) || - !equals(uiHint, other.uiHint) || - !equals(rbKeyValidationMessage, other.rbKeyValidationMessage)) { - return false; - } - - if (label == null) { - if (other.label != null) { - return false; - } - } else if (!label.equals(other.label)) { - return false; - } - if (name == null) { - if (other.name != null) { - return false; - } - } else if (!name.equals(other.name)) { - return false; - } - if (order == null) { - if (other.order != null) { - return false; - } - } else if (!order.equals(other.order)) { - return false; - } - if (rbKeyDescription == null) { - if (other.rbKeyDescription != null) { - return false; - } - } else if (!rbKeyDescription.equals(other.rbKeyDescription)) { - return false; - } - if (rbKeyLabel == null) { - if (other.rbKeyLabel != null) { - return false; - } - } else if (!rbKeyLabel.equals(other.rbKeyLabel)) { - return false; - } - return true; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#toString() - */ - @Override - public String toString() { - String str = "XXPolicyConditionDef={"; - str += super.toString(); - str += " [id=" + id + ", defId=" + defId + ", itemId=" + itemId - + ", name=" + name + ", evaluator=" + evaluator - + ", evaluatorOptions=" + evaluatorOptions + ", label=" + label - + ", validationRegEx=" + validationRegEx - + ", validationMessage=" + validationMessage - + ", uiHint=" + uiHint - + ", description=" + description + ", rbKeyLabel=" + rbKeyLabel - + ", rbKeyValidationMessage=" + rbKeyValidationMessage - + ", rbKeyDescription=" + rbKeyDescription + ", order=" + order - + "]"; - str += "}"; - return str; - } - +public class XXPolicyConditionDef extends XXDBBase implements java.io.Serializable { + private static final long serialVersionUID = 1L; + + /** + * id of the XXPolicyConditionDef + *
    + *
+ */ + @Id + @SequenceGenerator(name = "x_policy_condition_def_SEQ", sequenceName = "x_policy_condition_def_SEQ", allocationSize = 1) + @GeneratedValue(strategy = GenerationType.AUTO, generator = "x_policy_condition_def_SEQ") + @Column(name = "id") + protected Long id; + + /** + * defId of the XXPolicyConditionDef + *
    + *
+ */ + @Column(name = "def_id") + protected Long defId; + + /** + * itemId of the XXPolicyConditionDef + *
    + *
+ */ + @Column(name = "item_id") + protected Long itemId; + + /** + * name of the XXPolicyConditionDef + *
    + *
+ */ + @Column(name = "name") + protected String name; + + /** + * evaluator of the XXPolicyConditionDef + *
    + *
+ */ + @Column(name = "evaluator") + protected String evaluator; + + /** + * evaluatorOptions of the XXPolicyConditionDef + *
    + *
+ */ + @Column(name = "evaluator_options") + protected String evaluatorOptions; + + /** + * validationRegEx of the XXPolicyConditionDef + *
    + *
+ */ + @Column(name = "validation_reg_ex") + protected String validationRegEx; + + /** + * validationMessage of the XXPolicyConditionDef + *
    + *
+ */ + @Column(name = "validation_message") + protected String validationMessage; + + /** + * uiHint of the XXPolicyConditionDef + *
    + *
+ */ + @Column(name = "ui_hint") + protected String uiHint; + + /** + * label of the XXPolicyConditionDef + *
    + *
+ */ + @Column(name = "label") + protected String label; + + /** + * description of the XXPolicyConditionDef + *
    + *
+ */ + @Column(name = "description") + protected String description; + + /** + * rbKeyLabel of the XXPolicyConditionDef + *
    + *
+ */ + @Column(name = "rb_key_label") + protected String rbKeyLabel; + + /** + * rbKeyDescription of the XXPolicyConditionDef + *
    + *
+ */ + @Column(name = "rb_key_description") + protected String rbKeyDescription; + + /** + * rbKeyValidationMessage of the XXPolicyConditionDef + *
    + *
+ */ + @Column(name = "rb_key_validation_message") + protected String rbKeyValidationMessage; + + /** + * order of the XXPolicyConditionDef + *
    + *
+ */ + @Column(name = "sort_order") + protected Integer order; + + /** + * Returns the value for the member attribute id + * + * @return Date - value of member attribute id . + */ + public Long getId() { + return this.id; + } + + /** + * This method sets the value to the member attribute id . You + * cannot set null to the attribute. + * + * @param id Value to set member attribute id + */ + public void setId(Long id) { + this.id = id; + } + + @Override + public int hashCode() { + return super.hashCode(); + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#equals(java.lang.Object) + */ + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } else if (!super.equals(obj)) { + return false; + } + + XXPolicyConditionDef other = (XXPolicyConditionDef) obj; + + return Objects.equals(defId, other.defId) && + Objects.equals(itemId, other.itemId) && + Objects.equals(description, other.description) && + Objects.equals(evaluator, other.evaluator) && + Objects.equals(evaluatorOptions, other.evaluatorOptions) && + Objects.equals(id, other.id) && + Objects.equals(label, other.label) && + Objects.equals(name, other.name) && + Objects.equals(order, other.order) && + Objects.equals(rbKeyDescription, other.rbKeyDescription) && + Objects.equals(rbKeyLabel, other.rbKeyLabel) && + Objects.equals(validationRegEx, other.validationRegEx) && + Objects.equals(validationMessage, other.validationMessage) && + Objects.equals(uiHint, other.uiHint) && + Objects.equals(rbKeyValidationMessage, other.rbKeyValidationMessage); + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + String str = "XXPolicyConditionDef={"; + str += super.toString(); + str += " [id=" + id + ", defId=" + defId + ", itemId=" + itemId + + ", name=" + name + ", evaluator=" + evaluator + + ", evaluatorOptions=" + evaluatorOptions + ", label=" + label + + ", validationRegEx=" + validationRegEx + + ", validationMessage=" + validationMessage + + ", uiHint=" + uiHint + + ", description=" + description + ", rbKeyLabel=" + rbKeyLabel + + ", rbKeyValidationMessage=" + rbKeyValidationMessage + + ", rbKeyDescription=" + rbKeyDescription + ", order=" + order + + "]"; + str += "}"; + return str; + } + + /** + * Returns the value for the member attribute itemId + * + * @return Long - value of member attribute itemId . + */ + public Long getItemId() { + return this.itemId; + } + + /** + * This method sets the value to the member attribute itemId . You + * cannot set null to the attribute. + * + * @param itemId Value to set member attribute itemId + */ + public void setItemId(Long itemId) { + this.itemId = itemId; + } + + /** + * Returns the value for the member attribute defId + * + * @return Date - value of member attribute defId . + */ + public Long getDefid() { + return this.defId; + } + + /** + * This method sets the value to the member attribute defId . You + * cannot set null to the attribute. + * + * @param defId Value to set member attribute defId + */ + public void setDefid(Long defId) { + this.defId = defId; + } + + /** + * Returns the value for the member attribute name + * + * @return Date - value of member attribute name . + */ + public String getName() { + return this.name; + } + + /** + * This method sets the value to the member attribute name . You + * cannot set null to the attribute. + * + * @param name Value to set member attribute name + */ + public void setName(String name) { + this.name = name; + } + + /** + * Returns the value for the member attribute evaluator + * + * @return Date - value of member attribute evaluator . + */ + public String getEvaluator() { + return this.evaluator; + } + + /** + * This method sets the value to the member attribute evaluator . + * You cannot set null to the attribute. + * + * @param evaluator Value to set member attribute evaluator + */ + public void setEvaluator(String evaluator) { + this.evaluator = evaluator; + } + + /** + * Returns the value for the member attribute evaluatorOptions + * + * @return Date - value of member attribute evaluatorOptions . + */ + public String getEvaluatoroptions() { + return this.evaluatorOptions; + } + + /** + * This method sets the value to the member attribute + * evaluatorOptions . You cannot set null to the attribute. + * + * @param evaluatorOptions Value to set member attribute evaluatorOptions + */ + public void setEvaluatoroptions(String evaluatorOptions) { + this.evaluatorOptions = evaluatorOptions; + } + + /** + * @return the validationRegEx + */ + public String getValidationRegEx() { + return validationRegEx; + } + + /** + * @param validationRegEx the validationRegEx to set + */ + public void setValidationRegEx(String validationRegEx) { + this.validationRegEx = validationRegEx; + } + + /** + * @return the validationMessage + */ + public String getValidationMessage() { + return validationMessage; + } + + /** + * @param validationMessage the validationMessage to set + */ + public void setValidationMessage(String validationMessage) { + this.validationMessage = validationMessage; + } + + /** + * @return the uiHint + */ + public String getUiHint() { + return uiHint; + } + + /** + * @param uiHint the uiHint to set + */ + public void setUiHint(String uiHint) { + this.uiHint = uiHint; + } + + /** + * Returns the value for the member attribute label + * + * @return Date - value of member attribute label . + */ + public String getLabel() { + return this.label; + } + + /** + * This method sets the value to the member attribute label . You + * cannot set null to the attribute. + * + * @param label Value to set member attribute label + */ + public void setLabel(String label) { + this.label = label; + } + + /** + * Returns the value for the member attribute description + * + * @return Date - value of member attribute description . + */ + public String getDescription() { + return this.description; + } + + /** + * This method sets the value to the member attribute description . + * You cannot set null to the attribute. + * + * @param description Value to set member attribute description + */ + public void setDescription(String description) { + this.description = description; + } + + /** + * Returns the value for the member attribute rbKeyLabel + * + * @return Date - value of member attribute rbKeyLabel . + */ + public String getRbkeylabel() { + return this.rbKeyLabel; + } + + /** + * This method sets the value to the member attribute rbKeyLabel . + * You cannot set null to the attribute. + * + * @param rbKeyLabel Value to set member attribute rbKeyLabel + */ + public void setRbkeylabel(String rbKeyLabel) { + this.rbKeyLabel = rbKeyLabel; + } + + /** + * Returns the value for the member attribute rbKeyDescription + * + * @return Date - value of member attribute rbKeyDescription . + */ + public String getRbkeydescription() { + return this.rbKeyDescription; + } + + /** + * This method sets the value to the member attribute + * rbKeyDescription . You cannot set null to the attribute. + * + * @param rbKeyDescription Value to set member attribute rbKeyDescription + */ + public void setRbkeydescription(String rbKeyDescription) { + this.rbKeyDescription = rbKeyDescription; + } + + /** + * @return the rbKeyValidationMessage + */ + public String getRbKeyValidationMessage() { + return rbKeyValidationMessage; + } + + /** + * @param rbKeyValidationMessage the rbKeyValidationMessage to set + */ + public void setRbKeyValidationMessage(String rbKeyValidationMessage) { + this.rbKeyValidationMessage = rbKeyValidationMessage; + } + + /** + * Returns the value for the member attribute order + * + * @return Date - value of member attribute order . + */ + public Integer getOrder() { + return this.order; + } + + /** + * This method sets the value to the member attribute order . You + * cannot set null to the attribute. + * + * @param order Value to set member attribute order + */ + public void setOrder(Integer order) { + this.order = order; + } } 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 index 15f7098688..8ef004c519 100644 --- a/security-admin/src/main/java/org/apache/ranger/entity/XXPolicyExportAudit.java +++ b/security-admin/src/main/java/org/apache/ranger/entity/XXPolicyExportAudit.java @@ -17,14 +17,13 @@ * under the License. */ - package org.apache.ranger.entity; +package org.apache.ranger.entity; /** * Audit Log for Policy Export - * */ -import java.util.Date; +import org.apache.ranger.common.AppConstants; import javax.persistence.Column; import javax.persistence.Entity; @@ -36,373 +35,375 @@ import javax.persistence.Temporal; import javax.persistence.TemporalType; -import org.apache.ranger.common.AppConstants; - +import java.util.Date; +import java.util.Objects; @Entity -@Table(name="x_policy_export_audit") +@Table(name = "x_policy_export_audit") 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 - *
    - *
  • The maximum length for this attribute is 255. - *
- * - */ - @Column(name="CLIENT_IP" , nullable=false , length=255) - protected String clientIP; - - /** - * XA Agent Id - *
    - *
  • The maximum length for this attribute is 255. - *
- * - */ - @Column(name="AGENT_ID" , length=255) - protected String agentId; - - /** - * Last update timestamp in request - *
    - *
- * - */ - @Column(name="REQ_EPOCH" , nullable=false ) - protected Long requestedEpoch; - - /** - * Date and time of the last policy update - *
    - *
- * - */ - @Temporal(TemporalType.TIMESTAMP) - @Column(name="LAST_UPDATED" ) - protected Date lastUpdated; - - /** - * Name of the Asset - *
    - *
  • The maximum length for this attribute is 1024. - *
- * - */ - @Column(name="REPOSITORY_NAME" , length=1024) - protected String repositoryName; - - /** - * JSON of the policies exported - *
    - *
  • The maximum length for this attribute is 30000. - *
- * - */ - @Column(name="EXPORTED_JSON" , length=30000) - protected String exportedJson; - - /** - * HTTP Response Code - *
    - *
- * - */ - @Column(name="HTTP_RET_CODE" , nullable=false ) - protected int httpRetCode; - - /** - * Name of the Cluster - *
    - *
  • The maximum length for this attribute is 255. - *
- * - */ - @Column(name="CLUSTER_NAME" , nullable=false , length=255) - protected String clusterName; - - /** - * Name of the ZoneName - *
    - *
  • The maximum length for this attribute is 255. - *
- * - */ - @Column(name="ZONE_NAME" , nullable=false , length=255) - protected String zoneName; - - - /** - * Name of the policyVersion - *
    - *
- */ - @Column(name="POLICY_VERSION") - protected Long policyVersion; - - /** - * 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 clientIP. - * You cannot set null to the attribute. - * @param clientIP Value to set member attribute clientIP - */ - public void setClientIP( String clientIP ) { - this.clientIP = clientIP; - } - - /** - * Returns the value for the member attribute clientIP - * @return String - value of member attribute clientIP. - */ - public String getClientIP( ) { - return this.clientIP; - } - - /** - * This method sets the value to the member attribute agentId. - * You cannot set null to the attribute. - * @param agentId Value to set member attribute agentId - */ - public void setAgentId( String agentId ) { - this.agentId = agentId; - } - - /** - * Returns the value for the member attribute agentId - * @return String - value of member attribute agentId. - */ - public String getAgentId( ) { - return this.agentId; - } - - /** - * This method sets the value to the member attribute requestedEpoch. - * You cannot set null to the attribute. - * @param requestedEpoch Value to set member attribute requestedEpoch - */ - public void setRequestedEpoch( Long requestedEpoch ) { - this.requestedEpoch = requestedEpoch; - } - - /** - * Returns the value for the member attribute requestedEpoch - * @return Long - value of member attribute requestedEpoch. - */ - public Long getRequestedEpoch( ) { - return this.requestedEpoch; - } - - /** - * This method sets the value to the member attribute lastUpdated. - * You cannot set null to the attribute. - * @param lastUpdated Value to set member attribute lastUpdated - */ - public void setLastUpdated( Date lastUpdated ) { - this.lastUpdated = lastUpdated; - } - - /** - * Returns the value for the member attribute lastUpdated - * @return Date - value of member attribute lastUpdated. - */ - public Date getLastUpdated( ) { - return this.lastUpdated; - } - - /** - * This method sets the value to the member attribute repositoryName. - * You cannot set null to the attribute. - * @param repositoryName Value to set member attribute repositoryName - */ - public void setRepositoryName( String repositoryName ) { - this.repositoryName = repositoryName; - } - - /** - * Returns the value for the member attribute repositoryName - * @return String - value of member attribute repositoryName. - */ - public String getRepositoryName( ) { - return this.repositoryName; - } - - /** - * This method sets the value to the member attribute exportedJson. - * You cannot set null to the attribute. - * @param exportedJson Value to set member attribute exportedJson - */ - public void setExportedJson( String exportedJson ) { - this.exportedJson = exportedJson; - } - - /** - * Returns the value for the member attribute exportedJson - * @return String - value of member attribute exportedJson. - */ - public String getExportedJson( ) { - return this.exportedJson; - } - - /** - * This method sets the value to the member attribute httpRetCode. - * You cannot set null to the attribute. - * @param httpRetCode Value to set member attribute httpRetCode - */ - public void setHttpRetCode( int httpRetCode ) { - this.httpRetCode = httpRetCode; - } - - /** - * Returns the value for the member attribute httpRetCode - * @return int - value of member attribute httpRetCode. - */ - public int getHttpRetCode( ) { - return this.httpRetCode; - } - - /** - * This method sets the value to the member attribute clusterName. - * You cannot set null to the attribute. - * @param clusterName Value to set member attribute clusterName - */ - public void setClusterName(String clusterName) { - this.clusterName = clusterName; - } - - /** - * Returns the value for the member attribute clusterName - * @return String - value of member attribute clusterName. - */ - public String getClusterName() { - return clusterName; - } - - /** - * This method sets the value to the member attribute zoneName. - * You cannot set null to the attribute. - * @param zoneName Value to set member attribute zoneName - */ - public void setZoneName(String zoneName) { - this.zoneName = zoneName; - } - - /** - * Returns the value for the member attribute zoneName - * @return String - value of member attribute zoneName. - */ - public String getZoneName() { - return zoneName; - } - - /** - * This method sets the value to the member attribute policyVersion. - * @param policyVersion Value to set member attribute policyVersion - */ - public void setPolicyVersion(Long policyVersion) { - this.policyVersion = policyVersion; - } - - /** - * Returns the value for the member attribute policyVersion - * @return String - value of member attribute policyVersion. - */ - public Long getPolicyVersion() { - return policyVersion; - } - - /** - * 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 += "clusterName={" + clusterName + "} "; - str += "zoneName={" + zoneName + "} "; - str += "policyVersion={" + policyVersion + "} "; - 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; - if ((this.clusterName == null && other.clusterName != null) || (this.clusterName != null && !this.clusterName.equals(other.clusterName))) { - return false; - } - if ((this.zoneName == null && other.zoneName != null) || (this.zoneName != null && !this.zoneName.equals(other.zoneName))) { - return false; - } - if ((this.policyVersion == null && other.policyVersion != null) || (this.policyVersion != null && !this.policyVersion.equals(other.policyVersion))) { - return false; - } - return true; - } - public static String getEnumName(String fieldName ) { - //Later TODO - //return super.getEnumName(fieldName); - return null; - } - + 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; + + /** + * XA Agent IP Address + *
    + *
  • The maximum length for this attribute is 255. + *
+ */ + @Column(name = "CLIENT_IP", nullable = false, length = 255) + protected String clientIP; + + /** + * XA Agent Id + *
    + *
  • The maximum length for this attribute is 255. + *
+ */ + @Column(name = "AGENT_ID", length = 255) + protected String agentId; + + /** + * Last update timestamp in request + *
    + *
+ */ + @Column(name = "REQ_EPOCH", nullable = false) + protected Long requestedEpoch; + + /** + * Date and time of the last policy update + *
    + *
+ */ + @Temporal(TemporalType.TIMESTAMP) + @Column(name = "LAST_UPDATED") + protected Date lastUpdated; + + /** + * Name of the Asset + *
    + *
  • The maximum length for this attribute is 1024. + *
+ */ + @Column(name = "REPOSITORY_NAME", length = 1024) + protected String repositoryName; + + /** + * JSON of the policies exported + *
    + *
  • The maximum length for this attribute is 30000. + *
+ */ + @Column(name = "EXPORTED_JSON", length = 30000) + protected String exportedJson; + + /** + * HTTP Response Code + *
    + *
+ */ + @Column(name = "HTTP_RET_CODE", nullable = false) + protected int httpRetCode; + + /** + * Name of the Cluster + *
    + *
  • The maximum length for this attribute is 255. + *
+ */ + @Column(name = "CLUSTER_NAME", nullable = false, length = 255) + protected String clusterName; + + /** + * Name of the ZoneName + *
    + *
  • The maximum length for this attribute is 255. + *
+ */ + @Column(name = "ZONE_NAME", nullable = false, length = 255) + protected String zoneName; + + /** + * Name of the policyVersion + *
    + *
+ */ + @Column(name = "POLICY_VERSION") + protected Long policyVersion; + + /** + * Default constructor. This will set all the attributes to default value. + */ + public XXPolicyExportAudit() { + } + + public static String getEnumName(String fieldName) { + //Later TODO + //return super.getEnumName(fieldName); + return null; + } + + @Override + public int getMyClassType() { + return AppConstants.CLASS_TYPE_XA_POLICY_EXPORT_AUDIT; + } + + @Override + public Long getId() { + return id; + } + + @Override + public void setId(Long id) { + this.id = id; + } + + @Override + public int hashCode() { + return super.hashCode(); + } + + /** + * Checks for all attributes except referenced db objects + * + * @return true if all attributes match + */ + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } else if (!super.equals(obj)) { + return false; + } + + XXPolicyExportAudit other = (XXPolicyExportAudit) obj; + + return Objects.equals(clientIP, other.clientIP) && + Objects.equals(agentId, other.agentId) && + Objects.equals(requestedEpoch, other.requestedEpoch) && + Objects.equals(lastUpdated, other.lastUpdated) && + Objects.equals(repositoryName, other.repositoryName) && + Objects.equals(exportedJson, other.exportedJson) && + Objects.equals(httpRetCode, other.httpRetCode) && + Objects.equals(clusterName, other.clusterName) && + Objects.equals(zoneName, other.zoneName) && + Objects.equals(policyVersion, other.policyVersion); + } + + /** + * 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 += "clusterName={" + clusterName + "} "; + str += "zoneName={" + zoneName + "} "; + str += "policyVersion={" + policyVersion + "} "; + str += "}"; + return str; + } + + /** + * Returns the value for the member attribute clientIP + * + * @return String - value of member attribute clientIP. + */ + public String getClientIP() { + return this.clientIP; + } + + /** + * This method sets the value to the member attribute clientIP. + * You cannot set null to the attribute. + * + * @param clientIP Value to set member attribute clientIP + */ + public void setClientIP(String clientIP) { + this.clientIP = clientIP; + } + + /** + * Returns the value for the member attribute agentId + * + * @return String - value of member attribute agentId. + */ + public String getAgentId() { + return this.agentId; + } + + /** + * This method sets the value to the member attribute agentId. + * You cannot set null to the attribute. + * + * @param agentId Value to set member attribute agentId + */ + public void setAgentId(String agentId) { + this.agentId = agentId; + } + + /** + * Returns the value for the member attribute requestedEpoch + * + * @return Long - value of member attribute requestedEpoch. + */ + public Long getRequestedEpoch() { + return this.requestedEpoch; + } + + /** + * This method sets the value to the member attribute requestedEpoch. + * You cannot set null to the attribute. + * + * @param requestedEpoch Value to set member attribute requestedEpoch + */ + public void setRequestedEpoch(Long requestedEpoch) { + this.requestedEpoch = requestedEpoch; + } + + /** + * Returns the value for the member attribute lastUpdated + * + * @return Date - value of member attribute lastUpdated. + */ + public Date getLastUpdated() { + return this.lastUpdated; + } + + /** + * This method sets the value to the member attribute lastUpdated. + * You cannot set null to the attribute. + * + * @param lastUpdated Value to set member attribute lastUpdated + */ + public void setLastUpdated(Date lastUpdated) { + this.lastUpdated = lastUpdated; + } + + /** + * Returns the value for the member attribute repositoryName + * + * @return String - value of member attribute repositoryName. + */ + public String getRepositoryName() { + return this.repositoryName; + } + + /** + * This method sets the value to the member attribute repositoryName. + * You cannot set null to the attribute. + * + * @param repositoryName Value to set member attribute repositoryName + */ + public void setRepositoryName(String repositoryName) { + this.repositoryName = repositoryName; + } + + /** + * Returns the value for the member attribute exportedJson + * + * @return String - value of member attribute exportedJson. + */ + public String getExportedJson() { + return this.exportedJson; + } + + /** + * This method sets the value to the member attribute exportedJson. + * You cannot set null to the attribute. + * + * @param exportedJson Value to set member attribute exportedJson + */ + public void setExportedJson(String exportedJson) { + this.exportedJson = exportedJson; + } + + /** + * Returns the value for the member attribute httpRetCode + * + * @return int - value of member attribute httpRetCode. + */ + public int getHttpRetCode() { + return this.httpRetCode; + } + + /** + * This method sets the value to the member attribute httpRetCode. + * You cannot set null to the attribute. + * + * @param httpRetCode Value to set member attribute httpRetCode + */ + public void setHttpRetCode(int httpRetCode) { + this.httpRetCode = httpRetCode; + } + + /** + * Returns the value for the member attribute clusterName + * + * @return String - value of member attribute clusterName. + */ + public String getClusterName() { + return clusterName; + } + + /** + * This method sets the value to the member attribute clusterName. + * You cannot set null to the attribute. + * + * @param clusterName Value to set member attribute clusterName + */ + public void setClusterName(String clusterName) { + this.clusterName = clusterName; + } + + /** + * Returns the value for the member attribute zoneName + * + * @return String - value of member attribute zoneName. + */ + public String getZoneName() { + return zoneName; + } + + /** + * This method sets the value to the member attribute zoneName. + * You cannot set null to the attribute. + * + * @param zoneName Value to set member attribute zoneName + */ + public void setZoneName(String zoneName) { + this.zoneName = zoneName; + } + + /** + * Returns the value for the member attribute policyVersion + * + * @return String - value of member attribute policyVersion. + */ + public Long getPolicyVersion() { + return policyVersion; + } + + /** + * This method sets the value to the member attribute policyVersion. + * + * @param policyVersion Value to set member attribute policyVersion + */ + public void setPolicyVersion(Long policyVersion) { + this.policyVersion = policyVersion; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/entity/XXPolicyItem.java b/security-admin/src/main/java/org/apache/ranger/entity/XXPolicyItem.java index 369b8a05e8..31d6422184 100644 --- a/security-admin/src/main/java/org/apache/ranger/entity/XXPolicyItem.java +++ b/security-admin/src/main/java/org/apache/ranger/entity/XXPolicyItem.java @@ -18,329 +18,277 @@ */ package org.apache.ranger.entity; -import javax.persistence.*; +import javax.persistence.Cacheable; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.SequenceGenerator; +import javax.persistence.Table; + +import java.util.Objects; @Entity @Cacheable @Table(name = "x_policy_item") public class XXPolicyItem extends XXDBBase implements java.io.Serializable { - private static final long serialVersionUID = 1L; - /** - * id of the XXPolicyItem - *
    - *
- * - */ - @Id - @SequenceGenerator(name = "x_policy_item_SEQ", sequenceName = "x_policy_item_SEQ", allocationSize = 1) - @GeneratedValue(strategy = GenerationType.AUTO, generator = "x_policy_item_SEQ") - @Column(name = "id") - protected Long id; - - /** - * Global Id for the object - *
    - *
  • The maximum length for this attribute is 512. - *
- * - */ - @Column(name = "guid", unique = true, nullable = false, length = 512) - protected String GUID; - - /** - * policyId of the XXPolicyItem - *
    - *
- * - */ - @Column(name = "policy_id") - protected Long policyId; - - /** - * delegateAdmin of the XXPolicyItem - *
    - *
- * - */ - @Column(name = "delegate_admin") - protected Boolean delegateAdmin; - - /** - * item_type of the XXPolicyItem - *
    - *
- * - */ - @Column(name = "item_type") - protected Integer itemType; - - /** - * isEnabled of the XXPolicyItem - *
    - *
- * - */ - @Column(name = "is_enabled") - protected Boolean isEnabled; - - /** - * comments of the XXPolicyItem - *
    - *
- * - */ - @Column(name = "comments") - protected String comments; - - /** - * order of the XXPolicyItem - *
    - *
- * - */ - @Column(name = "sort_order") - protected Integer order; - - /** - * This method sets the value to the member attribute id . You - * cannot set null to the attribute. - * - * @param id - * Value to set member attribute id - */ - public void setId(Long id) { - this.id = id; - } - - /** - * Returns the value for the member attribute id - * - * @return Date - value of member attribute id . - */ - public Long getId() { - return this.id; - } - - /** - * @return the gUID - */ - public String getGUID() { - return GUID; - } - - /** - * @param gUID - * the gUID to set - */ - public void setGUID(String gUID) { - GUID = gUID; - } - - /** - * This method sets the value to the member attribute policyId . You - * cannot set null to the attribute. - * - * @param policyId - * Value to set member attribute policyId - */ - public void setPolicyId(Long policyId) { - this.policyId = policyId; - } - - /** - * Returns the value for the member attribute policyId - * - * @return Date - value of member attribute policyId . - */ - public Long getPolicyid() { - return this.policyId; - } - - /** - * This method sets the value to the member attribute delegateAdmin - * . You cannot set null to the attribute. - * - * @param delegateAdmin - * Value to set member attribute delegateAdmin - */ - public void setDelegateAdmin(Boolean delegateAdmin) { - this.delegateAdmin = delegateAdmin; - } - - /** - * Returns the value for the member attribute delegateAdmin - * - * @return Date - value of member attribute delegateAdmin . - */ - public Boolean getDelegateAdmin() { - return this.delegateAdmin; - } - - /** - * This method sets the value to the member attribute itemType . You - * cannot set null to the attribute. - * - * @param itemType - * Value to set member attribute itemType - */ - public void setItemType(Integer itemType) { - this.itemType = itemType; - } - - /** - * Returns the value for the member attribute itemType - * - * @return Integer - value of member attribute itemType . - */ - public Integer getItemType() { - return this.itemType; - } - - /** - * This method sets the value to the member attribute isEnabled . You - * cannot set null to the attribute. - * - * @param isEnabled - * Value to set member attribute isEnabled - */ - public void setIsEnabled(Boolean isEnabled) { - this.isEnabled = isEnabled; - } - - /** - * Returns the value for the member attribute isEnabled - * - * @return Boolean - value of member attribute isEnabled . - */ - public Boolean getIsEnabled() { - return this.isEnabled; - } - - /** - * This method sets the value to the member attribute comments . You - * cannot set null to the attribute. - * - * @param comments - * Value to set member attribute comments - */ - public void setComments(String comments) { - this.comments = comments; - } - - /** - * Returns the value for the member attribute comments - * - * @return Boolean - value of member attribute comments . - */ - public String getComments() { - return this.comments; - } - - /** - * This method sets the value to the member attribute order . You - * cannot set null to the attribute. - * - * @param order - * Value to set member attribute order - */ - public void setOrder(Integer order) { - this.order = order; - } - - /** - * Returns the value for the member attribute order - * - * @return Date - value of member attribute order . - */ - public Integer getOrder() { - return this.order; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#equals(java.lang.Object) - */ - @Override - public boolean equals(Object obj) { - if (!super.equals(obj)) { - return false; - } - if (this == obj) { - return true; - } - if (!super.equals(obj)) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - XXPolicyItem other = (XXPolicyItem) obj; - if (delegateAdmin != other.delegateAdmin) { - return false; - } - if (GUID == null) { - if (other.GUID != null) { - return false; - } - } else if (!GUID.equals(other.GUID)) { - return false; - } - if (id == null) { - if (other.id != null) { - return false; - } - } else if (!id.equals(other.id)) { - return false; - } - if (order == null) { - if (other.order != null) { - return false; - } - } else if (!order.equals(other.order)) { - return false; - } - if (policyId == null) { - if (other.policyId != null) { - return false; - } - } else if (!policyId.equals(other.policyId)) { - return false; - } - if (itemType == null) { - if (other.itemType != null) { - return false; - } - } else if (!itemType.equals(other.itemType)) { - return false; - } - if (isEnabled == null) { - if (other.isEnabled != null) { - return false; - } - } else if (!isEnabled.equals(other.isEnabled)) { - return false; - } - if (comments == null) { - if (other.comments != null) { - return false; - } - } else if (!comments.equals(other.comments)) { - return false; - } - return true; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#toString() - */ - @Override - public String toString() { - return "XXPolicyItem [" + super.toString() + " id=" + id + ", guid=" - + GUID + ", policyId=" + policyId - + ", delegateAdmin=" + delegateAdmin + ", itemType=" + itemType + ", order=" + order + "]"; - } + private static final long serialVersionUID = 1L; + + /** + * id of the XXPolicyItem + *
    + *
+ */ + @Id + @SequenceGenerator(name = "x_policy_item_SEQ", sequenceName = "x_policy_item_SEQ", allocationSize = 1) + @GeneratedValue(strategy = GenerationType.AUTO, generator = "x_policy_item_SEQ") + @Column(name = "id") + protected Long id; + + /** + * Global Id for the object + *
    + *
  • The maximum length for this attribute is 512. + *
+ */ + @Column(name = "guid", unique = true, nullable = false, length = 512) + protected String guid; + + /** + * policyId of the XXPolicyItem + *
    + *
+ */ + @Column(name = "policy_id") + protected Long policyId; + + /** + * delegateAdmin of the XXPolicyItem + *
    + *
+ */ + @Column(name = "delegate_admin") + protected Boolean delegateAdmin; + + /** + * item_type of the XXPolicyItem + *
    + *
+ */ + @Column(name = "item_type") + protected Integer itemType; + + /** + * isEnabled of the XXPolicyItem + *
    + *
+ */ + @Column(name = "is_enabled") + protected Boolean isEnabled; + + /** + * comments of the XXPolicyItem + *
    + *
+ */ + @Column(name = "comments") + protected String comments; + + /** + * order of the XXPolicyItem + *
    + *
+ */ + @Column(name = "sort_order") + protected Integer order; + + /** + * Returns the value for the member attribute id + * + * @return Date - value of member attribute id . + */ + public Long getId() { + return this.id; + } + + /** + * This method sets the value to the member attribute id . You + * cannot set null to the attribute. + * + * @param id Value to set member attribute id + */ + public void setId(Long id) { + this.id = id; + } + + @Override + public int hashCode() { + return super.hashCode(); + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#equals(java.lang.Object) + */ + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } else if (!super.equals(obj)) { + return false; + } + + XXPolicyItem other = (XXPolicyItem) obj; + + return Objects.equals(delegateAdmin, other.delegateAdmin) && + Objects.equals(guid, other.guid) && + Objects.equals(id, other.id) && + Objects.equals(order, other.order) && + Objects.equals(policyId, other.policyId) && + Objects.equals(itemType, other.itemType) && + Objects.equals(isEnabled, other.isEnabled) && + Objects.equals(comments, other.comments); + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + return "XXPolicyItem [" + super.toString() + " id=" + id + ", guid=" + + guid + ", policyId=" + policyId + + ", delegateAdmin=" + delegateAdmin + ", itemType=" + itemType + ", order=" + order + "]"; + } + + /** + * @return the gUID + */ + public String getGUID() { + return guid; + } + + /** + * @param gUID the gUID to set + */ + public void setGUID(String gUID) { + guid = gUID; + } + + /** + * This method sets the value to the member attribute policyId . You + * cannot set null to the attribute. + * + * @param policyId Value to set member attribute policyId + */ + public void setPolicyId(Long policyId) { + this.policyId = policyId; + } + + /** + * Returns the value for the member attribute policyId + * + * @return Date - value of member attribute policyId . + */ + public Long getPolicyid() { + return this.policyId; + } + + /** + * Returns the value for the member attribute delegateAdmin + * + * @return Date - value of member attribute delegateAdmin . + */ + public Boolean getDelegateAdmin() { + return this.delegateAdmin; + } + + /** + * This method sets the value to the member attribute delegateAdmin + * . You cannot set null to the attribute. + * + * @param delegateAdmin Value to set member attribute delegateAdmin + */ + public void setDelegateAdmin(Boolean delegateAdmin) { + this.delegateAdmin = delegateAdmin; + } + + /** + * Returns the value for the member attribute itemType + * + * @return Integer - value of member attribute itemType . + */ + public Integer getItemType() { + return this.itemType; + } + + /** + * This method sets the value to the member attribute itemType . You + * cannot set null to the attribute. + * + * @param itemType Value to set member attribute itemType + */ + public void setItemType(Integer itemType) { + this.itemType = itemType; + } + + /** + * Returns the value for the member attribute isEnabled + * + * @return Boolean - value of member attribute isEnabled . + */ + public Boolean getIsEnabled() { + return this.isEnabled; + } + + /** + * This method sets the value to the member attribute isEnabled . You + * cannot set null to the attribute. + * + * @param isEnabled Value to set member attribute isEnabled + */ + public void setIsEnabled(Boolean isEnabled) { + this.isEnabled = isEnabled; + } + + /** + * Returns the value for the member attribute comments + * + * @return Boolean - value of member attribute comments . + */ + public String getComments() { + return this.comments; + } + + /** + * This method sets the value to the member attribute comments . You + * cannot set null to the attribute. + * + * @param comments Value to set member attribute comments + */ + public void setComments(String comments) { + this.comments = comments; + } + + /** + * Returns the value for the member attribute order + * + * @return Date - value of member attribute order . + */ + public Integer getOrder() { + return this.order; + } + /** + * This method sets the value to the member attribute order . You + * cannot set null to the attribute. + * + * @param order Value to set member attribute order + */ + public void setOrder(Integer order) { + this.order = order; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/entity/XXPolicyItemAccess.java b/security-admin/src/main/java/org/apache/ranger/entity/XXPolicyItemAccess.java index eca99b8f99..64cee7915d 100644 --- a/security-admin/src/main/java/org/apache/ranger/entity/XXPolicyItemAccess.java +++ b/security-admin/src/main/java/org/apache/ranger/entity/XXPolicyItemAccess.java @@ -18,263 +18,222 @@ */ package org.apache.ranger.entity; -import javax.persistence.*; +import javax.persistence.Cacheable; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.SequenceGenerator; +import javax.persistence.Table; + +import java.util.Objects; @Entity @Cacheable @Table(name = "x_policy_item_access") -public class XXPolicyItemAccess extends XXDBBase implements - java.io.Serializable { - private static final long serialVersionUID = 1L; - /** - * id of the XXPolicyItemAccess - *
    - *
- * - */ - @Id - @SequenceGenerator(name = "x_policy_item_access_SEQ", sequenceName = "x_policy_item_access_SEQ", allocationSize = 1) - @GeneratedValue(strategy = GenerationType.AUTO, generator = "x_policy_item_access_SEQ") - @Column(name = "id") - protected Long id; - - /** - * Global Id for the object - *
    - *
  • The maximum length for this attribute is 512. - *
- * - */ - @Column(name = "guid", unique = true, nullable = false, length = 512) - protected String GUID; - - /** - * policyItemId of the XXPolicyItemAccess - *
    - *
- * - */ - @Column(name = "policy_item_id") - protected Long policyItemId; - - /** - * type of the XXPolicyItemAccess - *
    - *
- * - */ - @Column(name = "type") - protected Long type; - - /** - * isAllowed of the XXPolicyItemAccess - *
    - *
- * - */ - @Column(name = "is_allowed") - protected Boolean isAllowed; - - /** - * order of the XXPolicyItemAccess - *
    - *
- * - */ - @Column(name = "sort_order") - protected Integer order; - - /** - * This method sets the value to the member attribute id . You - * cannot set null to the attribute. - * - * @param id - * Value to set member attribute id - */ - public void setId(Long id) { - this.id = id; - } - - /** - * Returns the value for the member attribute id - * - * @return Date - value of member attribute id . - */ - public Long getId() { - return this.id; - } - - /** - * @return the gUID - */ - public String getGUID() { - return GUID; - } - - /** - * @param gUID - * the gUID to set - */ - public void setGUID(String gUID) { - GUID = gUID; - } - - /** - * This method sets the value to the member attribute policyItemId . - * You cannot set null to the attribute. - * - * @param policyItemId - * Value to set member attribute policyItemId - */ - public void setPolicyitemid(Long policyItemId) { - this.policyItemId = policyItemId; - } - - /** - * Returns the value for the member attribute policyItemId - * - * @return Date - value of member attribute policyItemId . - */ - public Long getPolicyitemid() { - return this.policyItemId; - } - - /** - * This method sets the value to the member attribute type . You - * cannot set null to the attribute. - * - * @param type - * Value to set member attribute type - */ - public void setType(Long type) { - this.type = type; - } - - /** - * Returns the value for the member attribute type - * - * @return Date - value of member attribute type . - */ - public Long getType() { - return this.type; - } - - /** - * This method sets the value to the member attribute isAllowed . - * You cannot set null to the attribute. - * - * @param isAllowed - * Value to set member attribute isAllowed - */ - public void setIsAllowed(Boolean isAllowed) { - this.isAllowed = isAllowed; - } - - /** - * Returns the value for the member attribute isAllowed - * - * @return Date - value of member attribute isAllowed . - */ - public Boolean getIsallowed() { - return this.isAllowed; - } - - /** - * This method sets the value to the member attribute order . You - * cannot set null to the attribute. - * - * @param order - * Value to set member attribute order - */ - public void setOrder(Integer order) { - this.order = order; - } - - /** - * Returns the value for the member attribute order - * - * @return Date - value of member attribute order . - */ - public Integer getOrder() { - return this.order; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#equals(java.lang.Object) - */ - @Override - public boolean equals(Object obj) { - if (!super.equals(obj)) { - return false; - } - if (this == obj) { - return true; - } - if (!super.equals(obj)) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - XXPolicyItemAccess other = (XXPolicyItemAccess) obj; - if (id == null) { - if (other.id != null) { - return false; - } - } else if (!id.equals(other.id)) { - return false; - } - if (isAllowed == null) { - if (other.isAllowed != null) { - return false; - } - } else if (!isAllowed.equals(other.isAllowed)) { - return false; - } - if (order == null) { - if (other.order != null) { - return false; - } - } else if (!order.equals(other.order)) { - return false; - } - if (policyItemId == null) { - if (other.policyItemId != null) { - return false; - } - } else if (!policyItemId.equals(other.policyItemId)) { - return false; - } - if (type == null) { - if (other.type != null) { - return false; - } - } else if (!type.equals(other.type)) { - return false; - } - if (GUID == null) { - if (other.GUID != null) { - return false; - } - } else if (!GUID.equals(other.GUID)) { - return false; - } - return true; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#toString() - */ - @Override - public String toString() { - return "XXPolicyItemAccess [" + super.toString() + " id=" + id - + ", guid=" + GUID + ", policyItemId=" - + policyItemId + ", type=" + type + ", isAllowed=" + isAllowed - + ", order=" + order + "]"; - } - +public class XXPolicyItemAccess extends XXDBBase implements java.io.Serializable { + private static final long serialVersionUID = 1L; + + /** + * id of the XXPolicyItemAccess + *
    + *
+ */ + @Id + @SequenceGenerator(name = "x_policy_item_access_SEQ", sequenceName = "x_policy_item_access_SEQ", allocationSize = 1) + @GeneratedValue(strategy = GenerationType.AUTO, generator = "x_policy_item_access_SEQ") + @Column(name = "id") + protected Long id; + + /** + * Global Id for the object + *
    + *
  • The maximum length for this attribute is 512. + *
+ */ + @Column(name = "guid", unique = true, nullable = false, length = 512) + protected String guid; + + /** + * policyItemId of the XXPolicyItemAccess + *
    + *
+ */ + @Column(name = "policy_item_id") + protected Long policyItemId; + + /** + * type of the XXPolicyItemAccess + *
    + *
+ */ + @Column(name = "type") + protected Long type; + + /** + * isAllowed of the XXPolicyItemAccess + *
    + *
+ */ + @Column(name = "is_allowed") + protected Boolean isAllowed; + + /** + * order of the XXPolicyItemAccess + *
    + *
+ */ + @Column(name = "sort_order") + protected Integer order; + + /** + * Returns the value for the member attribute id + * + * @return Date - value of member attribute id . + */ + public Long getId() { + return this.id; + } + + /** + * This method sets the value to the member attribute id . You + * cannot set null to the attribute. + * + * @param id Value to set member attribute id + */ + public void setId(Long id) { + this.id = id; + } + + @Override + public int hashCode() { + return super.hashCode(); + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#equals(java.lang.Object) + */ + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } else if (!super.equals(obj)) { + return false; + } + + XXPolicyItemAccess other = (XXPolicyItemAccess) obj; + + return Objects.equals(id, other.id) && + Objects.equals(isAllowed, other.isAllowed) && + Objects.equals(order, other.order) && + Objects.equals(policyItemId, other.policyItemId) && + Objects.equals(type, other.type) && + Objects.equals(guid, other.guid); + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + return "XXPolicyItemAccess [" + super.toString() + " id=" + id + + ", guid=" + guid + ", policyItemId=" + + policyItemId + ", type=" + type + ", isAllowed=" + isAllowed + + ", order=" + order + "]"; + } + + /** + * @return the gUID + */ + public String getGUID() { + return guid; + } + + /** + * @param gUID the gUID to set + */ + public void setGUID(String gUID) { + guid = gUID; + } + + /** + * Returns the value for the member attribute policyItemId + * + * @return Date - value of member attribute policyItemId . + */ + public Long getPolicyitemid() { + return this.policyItemId; + } + + /** + * This method sets the value to the member attribute policyItemId . + * You cannot set null to the attribute. + * + * @param policyItemId Value to set member attribute policyItemId + */ + public void setPolicyitemid(Long policyItemId) { + this.policyItemId = policyItemId; + } + + /** + * Returns the value for the member attribute type + * + * @return Date - value of member attribute type . + */ + public Long getType() { + return this.type; + } + + /** + * This method sets the value to the member attribute type . You + * cannot set null to the attribute. + * + * @param type Value to set member attribute type + */ + public void setType(Long type) { + this.type = type; + } + + /** + * This method sets the value to the member attribute isAllowed . + * You cannot set null to the attribute. + * + * @param isAllowed Value to set member attribute isAllowed + */ + public void setIsAllowed(Boolean isAllowed) { + this.isAllowed = isAllowed; + } + + /** + * Returns the value for the member attribute isAllowed + * + * @return Date - value of member attribute isAllowed . + */ + public Boolean getIsallowed() { + return this.isAllowed; + } + + /** + * Returns the value for the member attribute order + * + * @return Date - value of member attribute order . + */ + public Integer getOrder() { + return this.order; + } + + /** + * This method sets the value to the member attribute order . You + * cannot set null to the attribute. + * + * @param order Value to set member attribute order + */ + public void setOrder(Integer order) { + this.order = order; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/entity/XXPolicyItemCondition.java b/security-admin/src/main/java/org/apache/ranger/entity/XXPolicyItemCondition.java index 183091753b..4a1ad3da56 100644 --- a/security-admin/src/main/java/org/apache/ranger/entity/XXPolicyItemCondition.java +++ b/security-admin/src/main/java/org/apache/ranger/entity/XXPolicyItemCondition.java @@ -18,263 +18,222 @@ */ package org.apache.ranger.entity; -import javax.persistence.*; +import javax.persistence.Cacheable; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.SequenceGenerator; +import javax.persistence.Table; + +import java.util.Objects; @Entity @Cacheable @Table(name = "x_policy_item_condition") -public class XXPolicyItemCondition extends XXDBBase implements - java.io.Serializable { - private static final long serialVersionUID = 1L; - /** - * id of the XXPolicyItemCondition - *
    - *
- * - */ - @Id - @SequenceGenerator(name = "x_policy_item_condition_SEQ", sequenceName = "x_policy_item_condition_SEQ", allocationSize = 1) - @GeneratedValue(strategy = GenerationType.AUTO, generator = "x_policy_item_condition_SEQ") - @Column(name = "id") - protected Long id; - - /** - * Global Id for the object - *
    - *
  • The maximum length for this attribute is 512. - *
- * - */ - @Column(name = "guid", unique = true, nullable = false, length = 512) - protected String GUID; - - /** - * policyItemId of the XXPolicyItemCondition - *
    - *
- * - */ - @Column(name = "policy_item_id") - protected Long policyItemId; - - /** - * type of the XXPolicyItemCondition - *
    - *
- * - */ - @Column(name = "type") - protected Long type; - - /** - * value of the XXPolicyItemCondition - *
    - *
- * - */ - @Column(name = "value") - protected String value; - - /** - * order of the XXPolicyItemCondition - *
    - *
- * - */ - @Column(name = "sort_order") - protected Integer order; - - /** - * This method sets the value to the member attribute id . You - * cannot set null to the attribute. - * - * @param id - * Value to set member attribute id - */ - public void setId(Long id) { - this.id = id; - } - - /** - * Returns the value for the member attribute id - * - * @return Date - value of member attribute id . - */ - public Long getId() { - return this.id; - } - - /** - * This method sets the value to the member attribute policyItemId . - * You cannot set null to the attribute. - * - * @param policyItemId - * Value to set member attribute policyItemId - */ - public void setPolicyItemId(Long policyItemId) { - this.policyItemId = policyItemId; - } - - /** - * Returns the value for the member attribute policyItemId - * - * @return Date - value of member attribute policyItemId . - */ - public Long getPolicyitemid() { - return this.policyItemId; - } - - /** - * This method sets the value to the member attribute type . You - * cannot set null to the attribute. - * - * @param type - * Value to set member attribute type - */ - public void setType(Long type) { - this.type = type; - } - - /** - * Returns the value for the member attribute type - * - * @return Date - value of member attribute type . - */ - public Long getType() { - return this.type; - } - - /** - * This method sets the value to the member attribute value . You - * cannot set null to the attribute. - * - * @param value - * Value to set member attribute value - */ - public void setValue(String value) { - this.value = value; - } - - /** - * Returns the value for the member attribute value - * - * @return Date - value of member attribute value . - */ - public String getValue() { - return this.value; - } - - /** - * This method sets the value to the member attribute order . You - * cannot set null to the attribute. - * - * @param order - * Value to set member attribute order - */ - public void setOrder(Integer order) { - this.order = order; - } - - /** - * Returns the value for the member attribute order - * - * @return Date - value of member attribute order . - */ - public Integer getOrder() { - return this.order; - } - - /** - * @return the gUID - */ - public String getGUID() { - return GUID; - } - - /** - * @param gUID - * the gUID to set - */ - public void setGUID(String gUID) { - GUID = gUID; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#equals(java.lang.Object) - */ - @Override - public boolean equals(Object obj) { - if (!super.equals(obj)) { - return false; - } - if (this == obj) { - return true; - } - if (!super.equals(obj)) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - XXPolicyItemCondition other = (XXPolicyItemCondition) obj; - if (id == null) { - if (other.id != null) { - return false; - } - } else if (!id.equals(other.id)) { - return false; - } - if (order == null) { - if (other.order != null) { - return false; - } - } else if (!order.equals(other.order)) { - return false; - } - if (policyItemId == null) { - if (other.policyItemId != null) { - return false; - } - } else if (!policyItemId.equals(other.policyItemId)) { - return false; - } - if (type == null) { - if (other.type != null) { - return false; - } - } else if (!type.equals(other.type)) { - return false; - } - if (value == null) { - if (other.value != null) { - return false; - } - } else if (!value.equals(other.value)) { - return false; - } - if (GUID == null) { - if (other.GUID != null) { - return false; - } - } else if (!GUID.equals(other.GUID)) { - return false; - } - return true; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#toString() - */ - @Override - public String toString() { - return "XXPolicyItemCondition [" + super.toString() + " id=" + id - + ", guid=" + GUID + ", policyItemId=" - + policyItemId + ", type=" + type + ", value=" + value - + ", order=" + order + "]"; - } - +public class XXPolicyItemCondition extends XXDBBase implements java.io.Serializable { + private static final long serialVersionUID = 1L; + + /** + * id of the XXPolicyItemCondition + *
    + *
+ */ + @Id + @SequenceGenerator(name = "x_policy_item_condition_SEQ", sequenceName = "x_policy_item_condition_SEQ", allocationSize = 1) + @GeneratedValue(strategy = GenerationType.AUTO, generator = "x_policy_item_condition_SEQ") + @Column(name = "id") + protected Long id; + + /** + * Global Id for the object + *
    + *
  • The maximum length for this attribute is 512. + *
+ */ + @Column(name = "guid", unique = true, nullable = false, length = 512) + protected String guid; + + /** + * policyItemId of the XXPolicyItemCondition + *
    + *
+ */ + @Column(name = "policy_item_id") + protected Long policyItemId; + + /** + * type of the XXPolicyItemCondition + *
    + *
+ */ + @Column(name = "type") + protected Long type; + + /** + * value of the XXPolicyItemCondition + *
    + *
+ */ + @Column(name = "value") + protected String value; + + /** + * order of the XXPolicyItemCondition + *
    + *
+ */ + @Column(name = "sort_order") + protected Integer order; + + /** + * Returns the value for the member attribute id + * + * @return Date - value of member attribute id . + */ + public Long getId() { + return this.id; + } + + /** + * This method sets the value to the member attribute id . You + * cannot set null to the attribute. + * + * @param id Value to set member attribute id + */ + public void setId(Long id) { + this.id = id; + } + + @Override + public int hashCode() { + return super.hashCode(); + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#equals(java.lang.Object) + */ + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } else if (!super.equals(obj)) { + return false; + } + + XXPolicyItemCondition other = (XXPolicyItemCondition) obj; + + return Objects.equals(id, other.id) && + Objects.equals(order, other.order) && + Objects.equals(policyItemId, other.policyItemId) && + Objects.equals(type, other.type) && + Objects.equals(value, other.value) && + Objects.equals(guid, other.guid); + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + return "XXPolicyItemCondition [" + super.toString() + " id=" + id + + ", guid=" + guid + ", policyItemId=" + + policyItemId + ", type=" + type + ", value=" + value + + ", order=" + order + "]"; + } + + /** + * This method sets the value to the member attribute policyItemId . + * You cannot set null to the attribute. + * + * @param policyItemId Value to set member attribute policyItemId + */ + public void setPolicyItemId(Long policyItemId) { + this.policyItemId = policyItemId; + } + + /** + * Returns the value for the member attribute policyItemId + * + * @return Date - value of member attribute policyItemId . + */ + public Long getPolicyitemid() { + return this.policyItemId; + } + + /** + * Returns the value for the member attribute type + * + * @return Date - value of member attribute type . + */ + public Long getType() { + return this.type; + } + + /** + * This method sets the value to the member attribute type . You + * cannot set null to the attribute. + * + * @param type Value to set member attribute type + */ + public void setType(Long type) { + this.type = type; + } + + /** + * Returns the value for the member attribute value + * + * @return Date - value of member attribute value . + */ + public String getValue() { + return this.value; + } + + /** + * This method sets the value to the member attribute value . You + * cannot set null to the attribute. + * + * @param value Value to set member attribute value + */ + public void setValue(String value) { + this.value = value; + } + + /** + * Returns the value for the member attribute order + * + * @return Date - value of member attribute order . + */ + public Integer getOrder() { + return this.order; + } + + /** + * This method sets the value to the member attribute order . You + * cannot set null to the attribute. + * + * @param order Value to set member attribute order + */ + public void setOrder(Integer order) { + this.order = order; + } + + /** + * @return the gUID + */ + public String getGUID() { + return guid; + } + + /** + * @param gUID the gUID to set + */ + public void setGUID(String gUID) { + guid = gUID; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/entity/XXPolicyItemDataMaskInfo.java b/security-admin/src/main/java/org/apache/ranger/entity/XXPolicyItemDataMaskInfo.java index cebe4c3e66..e8d4856e2b 100644 --- a/security-admin/src/main/java/org/apache/ranger/entity/XXPolicyItemDataMaskInfo.java +++ b/security-admin/src/main/java/org/apache/ranger/entity/XXPolicyItemDataMaskInfo.java @@ -18,230 +18,197 @@ */ package org.apache.ranger.entity; -import javax.persistence.*; +import javax.persistence.Cacheable; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.SequenceGenerator; +import javax.persistence.Table; + +import java.util.Objects; @Entity @Cacheable @Table(name = "x_policy_item_datamask") -public class XXPolicyItemDataMaskInfo extends XXDBBase implements - java.io.Serializable { - private static final long serialVersionUID = 1L; - /** - * id of the XXPolicyItemDataMaskInfo - *
    - *
- * - */ - @Id - @SequenceGenerator(name = "x_policy_item_datamask_SEQ", sequenceName = "x_policy_item_datamask_SEQ", allocationSize = 1) - @GeneratedValue(strategy = GenerationType.AUTO, generator = "x_policy_item_datamask_SEQ") - @Column(name = "id") - protected Long id; - - /** - * policyItemId of the XXPolicyItemDataMaskInfo - *
    - *
- * - */ - @Column(name = "policy_item_id") - protected Long policyItemId; - - /** - * type of the XXPolicyItemDataMaskInfo - *
    - *
- * - */ - @Column(name = "type") - protected Long type; - - /** - * isAllowed of the XXPolicyItemDataMaskInfo - *
    - *
- * - */ - @Column(name = "condition_expr") - protected String conditionExpr; - - /** - * order of the XXPolicyItemDataMaskInfo - *
    - *
- * - */ - @Column(name = "value_expr") - protected String valueExpr; - - /** - * This method sets the value to the member attribute id . You - * cannot set null to the attribute. - * - * @param id - * Value to set member attribute id - */ - public void setId(Long id) { - this.id = id; - } - - /** - * Returns the value for the member attribute id - * - * @return Date - value of member attribute id . - */ - public Long getId() { - return this.id; - } - - /** - * This method sets the value to the member attribute policyItemId . - * You cannot set null to the attribute. - * - * @param policyItemId - * Value to set member attribute policyItemId - */ - public void setPolicyItemId(Long policyItemId) { - this.policyItemId = policyItemId; - } - - /** - * Returns the value for the member attribute policyItemId - * - * @return Date - value of member attribute policyItemId . - */ - public Long getPolicyItemId() { - return this.policyItemId; - } - - /** - * This method sets the value to the member attribute type . You - * cannot set null to the attribute. - * - * @param type - * Value to set member attribute type - */ - public void setType(Long type) { - this.type = type; - } - - /** - * Returns the value for the member attribute type - * - * @return Date - value of member attribute type . - */ - public Long getType() { - return this.type; - } - - /** - * This method sets the value to the member attribute conditionExpr . - * You cannot set null to the attribute. - * - * @param conditionExpr - * Value to set member attribute conditionExpr - */ - public void setConditionExpr(String conditionExpr) { - this.conditionExpr = conditionExpr; - } - - /** - * Returns the value for the member attribute valueExpr - * - * @return String - value of member attribute valueExpr . - */ - public String getConditionExpr() { - return this.valueExpr; - } - - /** - * This method sets the value to the member attribute valueExpr . You - * cannot set null to the attribute. - * - * @param valueExpr - * Value to set member attribute valueExpr - */ - public void setValueExpr(String valueExpr) { - this.valueExpr = valueExpr; - } - - /** - * Returns the value for the member attribute valueExpr - * - * @return String - value of member attribute valueExpr . - */ - public String getValueExpr() { - return this.valueExpr; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#equals(java.lang.Object) - */ - @Override - public boolean equals(Object obj) { - if (!super.equals(obj)) { - return false; - } - if (this == obj) { - return true; - } - if (!super.equals(obj)) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - XXPolicyItemDataMaskInfo other = (XXPolicyItemDataMaskInfo) obj; - if (id == null) { - if (other.id != null) { - return false; - } - } else if (!id.equals(other.id)) { - return false; - } - if (conditionExpr == null) { - if (other.conditionExpr != null) { - return false; - } - } else if (!conditionExpr.equals(other.conditionExpr)) { - return false; - } - if (valueExpr == null) { - if (other.valueExpr != null) { - return false; - } - } else if (!valueExpr.equals(other.valueExpr)) { - return false; - } - if (policyItemId == null) { - if (other.policyItemId != null) { - return false; - } - } else if (!policyItemId.equals(other.policyItemId)) { - return false; - } - if (type == null) { - if (other.type != null) { - return false; - } - } else if (!type.equals(other.type)) { - return false; - } - return true; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#toString() - */ - @Override - public String toString() { - return "XXPolicyItemDataMaskInfo [" + super.toString() + " id=" + id - + ", policyItemId=" + policyItemId + ", type=" + type - + ", conditionExpr=" + conditionExpr + ", valueExpr=" + valueExpr + "]"; - } - +public class XXPolicyItemDataMaskInfo extends XXDBBase implements java.io.Serializable { + private static final long serialVersionUID = 1L; + + /** + * id of the XXPolicyItemDataMaskInfo + *
    + *
+ */ + @Id + @SequenceGenerator(name = "x_policy_item_datamask_SEQ", sequenceName = "x_policy_item_datamask_SEQ", allocationSize = 1) + @GeneratedValue(strategy = GenerationType.AUTO, generator = "x_policy_item_datamask_SEQ") + @Column(name = "id") + protected Long id; + + /** + * policyItemId of the XXPolicyItemDataMaskInfo + *
    + *
+ */ + @Column(name = "policy_item_id") + protected Long policyItemId; + + /** + * type of the XXPolicyItemDataMaskInfo + *
    + *
+ */ + @Column(name = "type") + protected Long type; + + /** + * isAllowed of the XXPolicyItemDataMaskInfo + *
    + *
+ */ + @Column(name = "condition_expr") + protected String conditionExpr; + + /** + * order of the XXPolicyItemDataMaskInfo + *
    + *
+ */ + @Column(name = "value_expr") + protected String valueExpr; + + /** + * Returns the value for the member attribute id + * + * @return Date - value of member attribute id . + */ + public Long getId() { + return this.id; + } + + /** + * This method sets the value to the member attribute id . You + * cannot set null to the attribute. + * + * @param id Value to set member attribute id + */ + public void setId(Long id) { + this.id = id; + } + + @Override + public int hashCode() { + return super.hashCode(); + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#equals(java.lang.Object) + */ + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } else if (!super.equals(obj)) { + return false; + } + + XXPolicyItemDataMaskInfo other = (XXPolicyItemDataMaskInfo) obj; + + return Objects.equals(id, other.id) && + Objects.equals(conditionExpr, other.conditionExpr) && + Objects.equals(valueExpr, other.valueExpr) && + Objects.equals(policyItemId, other.policyItemId) && + Objects.equals(type, other.type); + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + return "XXPolicyItemDataMaskInfo [" + super.toString() + " id=" + id + + ", policyItemId=" + policyItemId + ", type=" + type + + ", conditionExpr=" + conditionExpr + ", valueExpr=" + valueExpr + "]"; + } + + /** + * Returns the value for the member attribute policyItemId + * + * @return Date - value of member attribute policyItemId . + */ + public Long getPolicyItemId() { + return this.policyItemId; + } + + /** + * This method sets the value to the member attribute policyItemId . + * You cannot set null to the attribute. + * + * @param policyItemId Value to set member attribute policyItemId + */ + public void setPolicyItemId(Long policyItemId) { + this.policyItemId = policyItemId; + } + + /** + * Returns the value for the member attribute type + * + * @return Date - value of member attribute type . + */ + public Long getType() { + return this.type; + } + + /** + * This method sets the value to the member attribute type . You + * cannot set null to the attribute. + * + * @param type Value to set member attribute type + */ + public void setType(Long type) { + this.type = type; + } + + /** + * Returns the value for the member attribute valueExpr + * + * @return String - value of member attribute valueExpr . + */ + public String getConditionExpr() { + return this.valueExpr; + } + + /** + * This method sets the value to the member attribute conditionExpr . + * You cannot set null to the attribute. + * + * @param conditionExpr Value to set member attribute conditionExpr + */ + public void setConditionExpr(String conditionExpr) { + this.conditionExpr = conditionExpr; + } + + /** + * Returns the value for the member attribute valueExpr + * + * @return String - value of member attribute valueExpr . + */ + public String getValueExpr() { + return this.valueExpr; + } + + /** + * This method sets the value to the member attribute valueExpr . You + * cannot set null to the attribute. + * + * @param valueExpr Value to set member attribute valueExpr + */ + public void setValueExpr(String valueExpr) { + this.valueExpr = valueExpr; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/entity/XXPolicyItemGroupPerm.java b/security-admin/src/main/java/org/apache/ranger/entity/XXPolicyItemGroupPerm.java index 0a88c0f23a..6ed2c5ec53 100644 --- a/security-admin/src/main/java/org/apache/ranger/entity/XXPolicyItemGroupPerm.java +++ b/security-admin/src/main/java/org/apache/ranger/entity/XXPolicyItemGroupPerm.java @@ -18,194 +18,169 @@ */ package org.apache.ranger.entity; -import javax.persistence.*; +import javax.persistence.Cacheable; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.SequenceGenerator; +import javax.persistence.Table; + +import java.util.Objects; @Entity @Cacheable @Table(name = "x_policy_item_group_perm") -public class XXPolicyItemGroupPerm extends XXDBBase implements - java.io.Serializable { - private static final long serialVersionUID = 1L; - /** - * id of the XXPolicyItemGroupPerm - *
    - *
- * - */ - @Id - @SequenceGenerator(name = "x_policy_item_group_perm_SEQ", sequenceName = "x_policy_item_group_perm_SEQ", allocationSize = 1) - @GeneratedValue(strategy = GenerationType.AUTO, generator = "x_policy_item_group_perm_SEQ") - @Column(name = "id") - protected Long id; - - /** - * policyItemId of the XXPolicyItemGroupPerm - *
    - *
- * - */ - @Column(name = "policy_item_id") - protected Long policyItemId; - - /** - * groupId of the XXPolicyItemGroupPerm - *
    - *
- * - */ - @Column(name = "group_id") - protected Long groupId; - - /** - * order of the XXPolicyItemGroupPerm - *
    - *
- * - */ - @Column(name = "sort_order") - protected Integer order; - - /** - * This method sets the value to the member attribute id . You - * cannot set null to the attribute. - * - * @param id - * Value to set member attribute id - */ - public void setId(Long id) { - this.id = id; - } - - /** - * Returns the value for the member attribute id - * - * @return Date - value of member attribute id . - */ - public Long getId() { - return this.id; - } - - /** - * This method sets the value to the member attribute policyItemId . - * You cannot set null to the attribute. - * - * @param policyItemId - * Value to set member attribute policyItemId - */ - public void setPolicyItemId(Long policyItemId) { - this.policyItemId = policyItemId; - } - - /** - * Returns the value for the member attribute policyItemId - * - * @return Date - value of member attribute policyItemId . - */ - public Long getPolicyitemid() { - return this.policyItemId; - } - - /** - * This method sets the value to the member attribute groupId . You - * cannot set null to the attribute. - * - * @param groupId - * Value to set member attribute groupId - */ - public void setGroupId(Long groupId) { - this.groupId = groupId; - } - - /** - * Returns the value for the member attribute groupId - * - * @return Date - value of member attribute groupId . - */ - public Long getGroupid() { - return this.groupId; - } - - /** - * This method sets the value to the member attribute order . You - * cannot set null to the attribute. - * - * @param order - * Value to set member attribute order - */ - public void setOrder(Integer order) { - this.order = order; - } - - /** - * Returns the value for the member attribute order - * - * @return Date - value of member attribute order . - */ - public Integer getOrder() { - return this.order; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#equals(java.lang.Object) - */ - @Override - public boolean equals(Object obj) { - if (!super.equals(obj)) { - return false; - } - if (this == obj) { - return true; - } - if (!super.equals(obj)) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - XXPolicyItemGroupPerm other = (XXPolicyItemGroupPerm) obj; - if (groupId == null) { - if (other.groupId != null) { - return false; - } - } else if (!groupId.equals(other.groupId)) { - return false; - } - if (id == null) { - if (other.id != null) { - return false; - } - } else if (!id.equals(other.id)) { - return false; - } - if (order == null) { - if (other.order != null) { - return false; - } - } else if (!order.equals(other.order)) { - return false; - } - if (policyItemId == null) { - if (other.policyItemId != null) { - return false; - } - } else if (!policyItemId.equals(other.policyItemId)) { - return false; - } - return true; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#toString() - */ - @Override - public String toString() { - return "XXPolicyItemGroupPerm [" + super.toString() + " id=" + id - + ", policyItemId=" + policyItemId + ", groupId=" + groupId - + ", order=" + order + "]"; - } - +public class XXPolicyItemGroupPerm extends XXDBBase implements java.io.Serializable { + private static final long serialVersionUID = 1L; + + /** + * id of the XXPolicyItemGroupPerm + *
    + *
+ */ + @Id + @SequenceGenerator(name = "x_policy_item_group_perm_SEQ", sequenceName = "x_policy_item_group_perm_SEQ", allocationSize = 1) + @GeneratedValue(strategy = GenerationType.AUTO, generator = "x_policy_item_group_perm_SEQ") + @Column(name = "id") + protected Long id; + + /** + * policyItemId of the XXPolicyItemGroupPerm + *
    + *
+ */ + @Column(name = "policy_item_id") + protected Long policyItemId; + + /** + * groupId of the XXPolicyItemGroupPerm + *
    + *
+ */ + @Column(name = "group_id") + protected Long groupId; + + /** + * order of the XXPolicyItemGroupPerm + *
    + *
+ */ + @Column(name = "sort_order") + protected Integer order; + + /** + * Returns the value for the member attribute id + * + * @return Date - value of member attribute id . + */ + public Long getId() { + return this.id; + } + + /** + * This method sets the value to the member attribute id . You + * cannot set null to the attribute. + * + * @param id Value to set member attribute id + */ + public void setId(Long id) { + this.id = id; + } + + @Override + public int hashCode() { + return super.hashCode(); + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#equals(java.lang.Object) + */ + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } else if (!super.equals(obj)) { + return false; + } + + XXPolicyItemGroupPerm other = (XXPolicyItemGroupPerm) obj; + + return Objects.equals(groupId, other.groupId) && + Objects.equals(id, other.id) && + Objects.equals(order, other.order) && + Objects.equals(policyItemId, other.policyItemId); + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + return "XXPolicyItemGroupPerm [" + super.toString() + " id=" + id + + ", policyItemId=" + policyItemId + ", groupId=" + groupId + + ", order=" + order + "]"; + } + + /** + * This method sets the value to the member attribute policyItemId . + * You cannot set null to the attribute. + * + * @param policyItemId Value to set member attribute policyItemId + */ + public void setPolicyItemId(Long policyItemId) { + this.policyItemId = policyItemId; + } + + /** + * Returns the value for the member attribute policyItemId + * + * @return Date - value of member attribute policyItemId . + */ + public Long getPolicyitemid() { + return this.policyItemId; + } + + /** + * This method sets the value to the member attribute groupId . You + * cannot set null to the attribute. + * + * @param groupId Value to set member attribute groupId + */ + public void setGroupId(Long groupId) { + this.groupId = groupId; + } + + /** + * Returns the value for the member attribute groupId + * + * @return Date - value of member attribute groupId . + */ + public Long getGroupid() { + return this.groupId; + } + + /** + * Returns the value for the member attribute order + * + * @return Date - value of member attribute order . + */ + public Integer getOrder() { + return this.order; + } + + /** + * This method sets the value to the member attribute order . You + * cannot set null to the attribute. + * + * @param order Value to set member attribute order + */ + public void setOrder(Integer order) { + this.order = order; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/entity/XXPolicyItemRowFilterInfo.java b/security-admin/src/main/java/org/apache/ranger/entity/XXPolicyItemRowFilterInfo.java index 8042fe74a3..d2cdf6d48f 100644 --- a/security-admin/src/main/java/org/apache/ranger/entity/XXPolicyItemRowFilterInfo.java +++ b/security-admin/src/main/java/org/apache/ranger/entity/XXPolicyItemRowFilterInfo.java @@ -18,157 +18,139 @@ */ package org.apache.ranger.entity; -import javax.persistence.*; +import javax.persistence.Cacheable; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.SequenceGenerator; +import javax.persistence.Table; + +import java.util.Objects; @Entity @Cacheable @Table(name = "x_policy_item_rowfilter") -public class XXPolicyItemRowFilterInfo extends XXDBBase implements - java.io.Serializable { - private static final long serialVersionUID = 1L; - /** - * id of the XXPolicyItemRowFilterInfo - *
    - *
- * - */ - @Id - @SequenceGenerator(name = "x_policy_item_rowfilter_SEQ", sequenceName = "x_policy_item_rowfilter_SEQ", allocationSize = 1) - @GeneratedValue(strategy = GenerationType.AUTO, generator = "x_policy_item_rowfilter_SEQ") - @Column(name = "id") - protected Long id; - - /** - * policyItemId of the XXPolicyItemRowFilterInfo - *
    - *
- * - */ - @Column(name = "policy_item_id") - protected Long policyItemId; - - /** - * filter_expr of the XXPolicyItemRowFilterInfo - *
    - *
- * - */ - @Column(name = "filter_expr") - protected String filterExpr; - - /** - * This method sets the value to the member attribute id . You - * cannot set null to the attribute. - * - * @param id - * Value to set member attribute id - */ - public void setId(Long id) { - this.id = id; - } - - /** - * Returns the value for the member attribute id - * - * @return Long - value of member attribute id . - */ - public Long getId() { - return this.id; - } - - /** - * This method sets the value to the member attribute policyItemId . - * You cannot set null to the attribute. - * - * @param policyItemId - * Value to set member attribute policyItemId - */ - public void setPolicyItemId(Long policyItemId) { - this.policyItemId = policyItemId; - } - - /** - * Returns the value for the member attribute policyItemId - * - * @return Long - value of member attribute policyItemId . - */ - public Long getPolicyItemId() { - return this.policyItemId; - } - - /** - * This method sets the value to the member attribute filterExpr . - * You cannot set null to the attribute. - * - * @param filterExpr - * Value to set member attribute filterExpr - */ - public void setFilterExpr(String filterExpr) { - this.filterExpr = filterExpr; - } - - /** - * Returns the value for the member attribute filterExpr - * - * @return String - value of member attribute filterExpr . - */ - public String getFilterExpr() { - return this.filterExpr; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#equals(java.lang.Object) - */ - @Override - public boolean equals(Object obj) { - if (!super.equals(obj)) { - return false; - } - if (this == obj) { - return true; - } - if (!super.equals(obj)) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - XXPolicyItemRowFilterInfo other = (XXPolicyItemRowFilterInfo) obj; - if (id == null) { - if (other.id != null) { - return false; - } - } else if (!id.equals(other.id)) { - return false; - } - if (filterExpr == null) { - if (other.filterExpr != null) { - return false; - } - } else if (!filterExpr.equals(other.filterExpr)) { - return false; - } - if (policyItemId == null) { - if (other.policyItemId != null) { - return false; - } - } else if (!policyItemId.equals(other.policyItemId)) { - return false; - } - return true; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#toString() - */ - @Override - public String toString() { - return "XXPolicyItemDataMaskInfo [" + super.toString() + " id=" + id - + ", policyItemId=" + policyItemId + ", filterExpr=" + filterExpr + "]"; - } +public class XXPolicyItemRowFilterInfo extends XXDBBase implements java.io.Serializable { + private static final long serialVersionUID = 1L; + + /** + * id of the XXPolicyItemRowFilterInfo + *
    + *
+ */ + @Id + @SequenceGenerator(name = "x_policy_item_rowfilter_SEQ", sequenceName = "x_policy_item_rowfilter_SEQ", allocationSize = 1) + @GeneratedValue(strategy = GenerationType.AUTO, generator = "x_policy_item_rowfilter_SEQ") + @Column(name = "id") + protected Long id; + + /** + * policyItemId of the XXPolicyItemRowFilterInfo + *
    + *
+ */ + @Column(name = "policy_item_id") + protected Long policyItemId; + + /** + * filter_expr of the XXPolicyItemRowFilterInfo + *
    + *
+ */ + @Column(name = "filter_expr") + protected String filterExpr; + + /** + * Returns the value for the member attribute id + * + * @return Long - value of member attribute id . + */ + public Long getId() { + return this.id; + } + + /** + * This method sets the value to the member attribute id . You + * cannot set null to the attribute. + * + * @param id Value to set member attribute id + */ + public void setId(Long id) { + this.id = id; + } + + @Override + public int hashCode() { + return super.hashCode(); + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#equals(java.lang.Object) + */ + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } else if (!super.equals(obj)) { + return false; + } + + XXPolicyItemRowFilterInfo other = (XXPolicyItemRowFilterInfo) obj; + + return Objects.equals(id, other.id) && + Objects.equals(filterExpr, other.filterExpr) && + Objects.equals(policyItemId, other.policyItemId); + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + return "XXPolicyItemDataMaskInfo [" + super.toString() + " id=" + id + ", policyItemId=" + policyItemId + ", filterExpr=" + filterExpr + "]"; + } + + /** + * Returns the value for the member attribute policyItemId + * + * @return Long - value of member attribute policyItemId . + */ + public Long getPolicyItemId() { + return this.policyItemId; + } + + /** + * This method sets the value to the member attribute policyItemId . + * You cannot set null to the attribute. + * + * @param policyItemId Value to set member attribute policyItemId + */ + public void setPolicyItemId(Long policyItemId) { + this.policyItemId = policyItemId; + } + + /** + * Returns the value for the member attribute filterExpr + * + * @return String - value of member attribute filterExpr . + */ + public String getFilterExpr() { + return this.filterExpr; + } + /** + * This method sets the value to the member attribute filterExpr . + * You cannot set null to the attribute. + * + * @param filterExpr Value to set member attribute filterExpr + */ + public void setFilterExpr(String filterExpr) { + this.filterExpr = filterExpr; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/entity/XXPolicyItemUserPerm.java b/security-admin/src/main/java/org/apache/ranger/entity/XXPolicyItemUserPerm.java index f5691496b4..2c4a6f908c 100644 --- a/security-admin/src/main/java/org/apache/ranger/entity/XXPolicyItemUserPerm.java +++ b/security-admin/src/main/java/org/apache/ranger/entity/XXPolicyItemUserPerm.java @@ -18,198 +18,171 @@ */ package org.apache.ranger.entity; -import javax.persistence.*; +import javax.persistence.Cacheable; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.SequenceGenerator; +import javax.persistence.Table; + +import java.util.Objects; @Entity @Cacheable @Table(name = "x_policy_item_user_perm") -public class XXPolicyItemUserPerm extends XXDBBase implements - java.io.Serializable { - private static final long serialVersionUID = 1L; - /** - * id of the XXPolicyItemUserPerm - *
    - *
- * - */ - @Id - @SequenceGenerator(name = "x_policy_item_user_perm_SEQ", sequenceName = "x_policy_item_user_perm_SEQ", allocationSize = 1) - @GeneratedValue(strategy = GenerationType.AUTO, generator = "x_policy_item_user_perm_SEQ") - @Column(name = "id") - protected Long id; - - /** - * policyItemId of the XXPolicyItemUserPerm - *
    - *
- * - */ - @Column(name = "policy_item_id") - protected Long policyItemId; - - /** - * userId of the XXPolicyItemUserPerm - *
    - *
- * - */ - @Column(name = "user_id") - protected Long userId; - - /** - * order of the XXPolicyItemUserPerm - *
    - *
- * - */ - @Column(name = "sort_order") - protected Integer order; - - /** - * This method sets the value to the member attribute id . You - * cannot set null to the attribute. - * - * @param id - * Value to set member attribute id - */ - public void setId(Long id) { - this.id = id; - } - - /** - * Returns the value for the member attribute id - * - * @return Date - value of member attribute id . - */ - public Long getId() { - return this.id; - } - - /** - * This method sets the value to the member attribute policyItemId . - * You cannot set null to the attribute. - * - * @param policyItemId - * Value to set member attribute policyItemId - */ - public void setPolicyItemId(Long policyItemId) { - this.policyItemId = policyItemId; - } - - /** - * Returns the value for the member attribute policyItemId - * - * @return Date - value of member attribute policyItemId . - */ - public Long getPolicyitemid() { - return this.policyItemId; - } - - /** - * This method sets the value to the member attribute userId . You - * cannot set null to the attribute. - * - * @param userId - * Value to set member attribute userId - */ - public void setUserId(Long userId) { - this.userId = userId; - } - - /** - * Returns the value for the member attribute userId - * - * @return Date - value of member attribute userId . - */ - public Long getUserid() { - return this.userId; - } - - /** - * This method sets the value to the member attribute order . You - * cannot set null to the attribute. - * - * @param order - * Value to set member attribute order - */ - public void setOrder(Integer order) { - this.order = order; - } - - /** - * Returns the value for the member attribute order - * - * @return Date - value of member attribute order . - */ - public Integer getOrder() { - return this.order; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#equals(java.lang.Object) - */ - @Override - public boolean equals(Object obj) { - if (!super.equals(obj)) { - return false; - } - if (this == obj) { - return true; - } - if (!super.equals(obj)) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - XXPolicyItemUserPerm other = (XXPolicyItemUserPerm) obj; - if (id == null) { - if (other.id != null) { - return false; - } - } else if (!id.equals(other.id)) { - return false; - } - if (order == null) { - if (other.order != null) { - return false; - } - } else if (!order.equals(other.order)) { - return false; - } - if (policyItemId == null) { - if (other.policyItemId != null) { - return false; - } - } else if (!policyItemId.equals(other.policyItemId)) { - return false; - } - if (userId == null) { - if (other.userId != null) { - return false; - } - } else if (!userId.equals(other.userId)) { - return false; - } - return true; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#toString() - */ - @Override - public String toString() { - String str = "XXPolicyItemUserPerm={"; - str += super.toString(); - str += " [id=" + id + ", policyItemId=" - + policyItemId + ", userId=" + userId + ", order=" + order - + "]"; - str += "}"; - return str; - } - +public class XXPolicyItemUserPerm extends XXDBBase implements java.io.Serializable { + private static final long serialVersionUID = 1L; + + /** + * id of the XXPolicyItemUserPerm + *
    + *
+ */ + @Id + @SequenceGenerator(name = "x_policy_item_user_perm_SEQ", sequenceName = "x_policy_item_user_perm_SEQ", allocationSize = 1) + @GeneratedValue(strategy = GenerationType.AUTO, generator = "x_policy_item_user_perm_SEQ") + @Column(name = "id") + protected Long id; + + /** + * policyItemId of the XXPolicyItemUserPerm + *
    + *
+ */ + @Column(name = "policy_item_id") + protected Long policyItemId; + + /** + * userId of the XXPolicyItemUserPerm + *
    + *
+ */ + @Column(name = "user_id") + protected Long userId; + + /** + * order of the XXPolicyItemUserPerm + *
    + *
+ */ + @Column(name = "sort_order") + protected Integer order; + + /** + * Returns the value for the member attribute id + * + * @return Date - value of member attribute id . + */ + public Long getId() { + return this.id; + } + + /** + * This method sets the value to the member attribute id . You + * cannot set null to the attribute. + * + * @param id Value to set member attribute id + */ + public void setId(Long id) { + this.id = id; + } + + @Override + public int hashCode() { + return super.hashCode(); + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#equals(java.lang.Object) + */ + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } else if (!super.equals(obj)) { + return false; + } + + XXPolicyItemUserPerm other = (XXPolicyItemUserPerm) obj; + + return Objects.equals(id, other.id) && + Objects.equals(order, other.order) && + Objects.equals(policyItemId, other.policyItemId) && + Objects.equals(userId, other.userId); + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + String str = "XXPolicyItemUserPerm={"; + str += super.toString(); + str += " [id=" + id + ", policyItemId=" + policyItemId + ", userId=" + userId + ", order=" + order + "]"; + str += "}"; + return str; + } + + /** + * This method sets the value to the member attribute policyItemId . + * You cannot set null to the attribute. + * + * @param policyItemId Value to set member attribute policyItemId + */ + public void setPolicyItemId(Long policyItemId) { + this.policyItemId = policyItemId; + } + + /** + * Returns the value for the member attribute policyItemId + * + * @return Date - value of member attribute policyItemId . + */ + public Long getPolicyitemid() { + return this.policyItemId; + } + + /** + * This method sets the value to the member attribute userId . You + * cannot set null to the attribute. + * + * @param userId Value to set member attribute userId + */ + public void setUserId(Long userId) { + this.userId = userId; + } + + /** + * Returns the value for the member attribute userId + * + * @return Date - value of member attribute userId . + */ + public Long getUserid() { + return this.userId; + } + + /** + * Returns the value for the member attribute order + * + * @return Date - value of member attribute order . + */ + public Integer getOrder() { + return this.order; + } + + /** + * This method sets the value to the member attribute order . You + * cannot set null to the attribute. + * + * @param order Value to set member attribute order + */ + public void setOrder(Integer order) { + this.order = order; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/entity/XXPolicyLabel.java b/security-admin/src/main/java/org/apache/ranger/entity/XXPolicyLabel.java index 011af17c69..c13f906d8b 100644 --- a/security-admin/src/main/java/org/apache/ranger/entity/XXPolicyLabel.java +++ b/security-admin/src/main/java/org/apache/ranger/entity/XXPolicyLabel.java @@ -19,8 +19,6 @@ package org.apache.ranger.entity; -import java.io.Serializable; - import javax.persistence.Cacheable; import javax.persistence.Column; import javax.persistence.Entity; @@ -30,119 +28,105 @@ import javax.persistence.SequenceGenerator; import javax.persistence.Table; +import java.io.Serializable; +import java.util.Objects; + @Entity @Cacheable @Table(name = "x_policy_label") public class XXPolicyLabel extends XXDBBase implements Serializable { - private static final long serialVersionUID = 1L; - - /** - * id of the XXPolicyLabel - *
    - *
- * - */ - @Id - @SequenceGenerator(name = "X_POLICY_LABEL_SEQ", sequenceName = "X_POLICY_LABEL_SEQ", allocationSize = 1) - @GeneratedValue(strategy = GenerationType.AUTO, generator = "X_POLICY_LABEL_SEQ") - @Column(name = "id") - protected Long id; - - /** - * Global Id for the object - *
    - *
  • The maximum length for this attribute is 512. - *
- * - */ - @Column(name = "guid", unique = true, nullable = false, length = 512) - protected String guid; - - /** - * policyLabel of the XXPolicyLabel - *
    - *
- * - */ - @Column(name = "label_name") - protected String policyLabel; - - - public void setId(Long id) { - this.id = id; + private static final long serialVersionUID = 1L; + + /** + * id of the XXPolicyLabel + *
    + *
+ */ + @Id + @SequenceGenerator(name = "X_POLICY_LABEL_SEQ", sequenceName = "X_POLICY_LABEL_SEQ", allocationSize = 1) + @GeneratedValue(strategy = GenerationType.AUTO, generator = "X_POLICY_LABEL_SEQ") + @Column(name = "id") + protected Long id; + + /** + * Global Id for the object + *
    + *
  • The maximum length for this attribute is 512. + *
+ */ + @Column(name = "guid", unique = true, nullable = false, length = 512) + protected String guid; + + /** + * policyLabel of the XXPolicyLabel + *
    + *
+ */ + @Column(name = "label_name") + protected String policyLabel; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + @Override + public int hashCode() { + return super.hashCode(); + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } else if (!super.equals(obj)) { + return false; } - public Long getId() { - return id; - } - - /** - * @return the gUID - */ - public String getGuid() { - return guid; - } - - /** - * @param gUID - * the gUID to set - */ - public void setGuid(String gUID) { - guid = gUID; - } - - /** - * @param policyLabel - * the policyLabel to set - */ - public void setPolicyLabel(String policyLabel) { - this.policyLabel = policyLabel; - } - - /** - * @return the policyLabel - */ - public String getPolicyLabel() { - return policyLabel; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (!super.equals(obj)) - return false; - if (getClass() != obj.getClass()) - return false; - XXPolicyLabel other = (XXPolicyLabel) obj; - if (id == null) { - if (other.id != null) - return false; - } else if (!id.equals(other.id)) - return false; - if (guid == null) { - if (other.guid != null) { - return false; - } - } else if (!guid.equals(other.guid)) { - return false; - } - if (policyLabel == null) { - if (other.policyLabel != null) { - return false; - } - } else if (!policyLabel.equals(other.policyLabel)) { - return false; - } - return true; - } - - @Override - public String toString() { - String str = "XXPolicyLabel={[id=" + id + ", "; - str += super.toString(); - str += " , guid=" + guid + ", policyLabel=" + policyLabel + "]"; - str += "}"; - return str; - } + XXPolicyLabel other = (XXPolicyLabel) obj; + + return Objects.equals(id, other.id) && + Objects.equals(guid, other.guid) && + Objects.equals(policyLabel, other.policyLabel); + } + + @Override + public String toString() { + String str = "XXPolicyLabel={[id=" + id + ", "; + str += super.toString(); + str += " , guid=" + guid + ", policyLabel=" + policyLabel + "]"; + str += "}"; + return str; + } + + /** + * @return the gUID + */ + public String getGuid() { + return guid; + } + + /** + * @param gUID the gUID to set + */ + public void setGuid(String gUID) { + guid = gUID; + } + + /** + * @return the policyLabel + */ + public String getPolicyLabel() { + return policyLabel; + } + + /** + * @param policyLabel the policyLabel to set + */ + public void setPolicyLabel(String policyLabel) { + this.policyLabel = policyLabel; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/entity/XXPolicyLabelMap.java b/security-admin/src/main/java/org/apache/ranger/entity/XXPolicyLabelMap.java index af13f09078..0f4c66443a 100644 --- a/security-admin/src/main/java/org/apache/ranger/entity/XXPolicyLabelMap.java +++ b/security-admin/src/main/java/org/apache/ranger/entity/XXPolicyLabelMap.java @@ -19,8 +19,6 @@ package org.apache.ranger.entity; -import java.io.Serializable; - import javax.persistence.Cacheable; import javax.persistence.Column; import javax.persistence.Entity; @@ -30,150 +28,128 @@ import javax.persistence.SequenceGenerator; import javax.persistence.Table; +import java.io.Serializable; +import java.util.Objects; + @Entity @Cacheable @Table(name = "x_policy_label_map") public class XXPolicyLabelMap extends XXDBBase implements Serializable { - private static final long serialVersionUID = 1L; - - /** - * id of the XXPolicyLabelMap - *
    - *
- * - */ - @Id - @SequenceGenerator(name = "X_POLICY_LABEL_MAP_SEQ", sequenceName = "X_POLICY_LABEL_MAP_SEQ", allocationSize = 1) - @GeneratedValue(strategy = GenerationType.AUTO, generator = "X_POLICY_LABEL_MAP_SEQ") - @Column(name = "id") - protected Long id; - - /** - * Global Id for the object - *
    - *
  • The maximum length for this attribute is 512. - *
- * - */ - @Column(name = "guid", unique = true, nullable = false, length = 512) - protected String guid; - - /** - * policyId of the XXPolicyLabelMap - *
    - *
- * - */ - @Column(name = "policy_id") - protected Long policyId; - - /** - * policyLabelId of the XXPolicyLabelMap - *
    - *
- * - */ - @Column(name = "policy_label_id") - protected Long policyLabelId; - - public void setId(Long id) { - this.id = id; - } - - public Long getId() { - return id; - } - - /** - * @return the gUID - */ - public String getGuid() { - return guid; - } - - /** - * @param gUID - * the gUID to set - */ - public void setGuid(String gUID) { - guid = gUID; - } - - /** - * @return the policyId - */ - public Long getPolicyId() { - return policyId; - } - - /** - * @param policyId - * the policyId to set - */ - public void setPolicyId(Long policyId) { - this.policyId = policyId; - } - - /** - * @return the policyLabelId - */ - public Long getPolicyLabelId() { - return policyLabelId; - } - - /** - * @param policyLabelId - * the policyLabelId to set - */ - public void setPolicyLabelId(Long policyLabelId) { - this.policyLabelId = policyLabelId; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (!super.equals(obj)) - return false; - if (getClass() != obj.getClass()) - return false; - XXPolicyLabelMap other = (XXPolicyLabelMap) obj; - if (id == null) { - if (other.id != null) - return false; - } else if (!id.equals(other.id)) - return false; - if (guid == null) { - if (other.guid != null) { - return false; - } - } else if (!guid.equals(other.guid)) { - return false; - } - if (policyId == null) { - if (other.policyId != null) { - return false; - } - } else if (!policyId.equals(other.policyId)) { - return false; - } - if (policyLabelId == null) { - if (other.policyLabelId != null) { - return false; - } - } else if (!policyLabelId.equals(other.policyLabelId)) { - return false; - } - return true; - } - - @Override - public String toString() { - String str = "XXPolicyLabelMap={[id=" + id + "]"; - str += super.toString(); - str += " [guid=" + guid + ", policyId=" + policyId + ", policyLabelId=" + policyLabelId + "]"; - str += "}"; - return str; + private static final long serialVersionUID = 1L; + + /** + * id of the XXPolicyLabelMap + *
    + *
+ */ + @Id + @SequenceGenerator(name = "X_POLICY_LABEL_MAP_SEQ", sequenceName = "X_POLICY_LABEL_MAP_SEQ", allocationSize = 1) + @GeneratedValue(strategy = GenerationType.AUTO, generator = "X_POLICY_LABEL_MAP_SEQ") + @Column(name = "id") + protected Long id; + + /** + * Global Id for the object + *
    + *
  • The maximum length for this attribute is 512. + *
+ */ + @Column(name = "guid", unique = true, nullable = false, length = 512) + protected String guid; + + /** + * policyId of the XXPolicyLabelMap + *
    + *
+ */ + @Column(name = "policy_id") + protected Long policyId; + + /** + * policyLabelId of the XXPolicyLabelMap + *
    + *
+ */ + @Column(name = "policy_label_id") + protected Long policyLabelId; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + @Override + public int hashCode() { + return super.hashCode(); + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } else if (!super.equals(obj)) { + return false; } + XXPolicyLabelMap other = (XXPolicyLabelMap) obj; + + return Objects.equals(id, other.id) && + Objects.equals(guid, other.guid) && + Objects.equals(policyId, other.policyId) && + Objects.equals(policyLabelId, other.policyLabelId); + } + + @Override + public String toString() { + String str = "XXPolicyLabelMap={[id=" + id + "]"; + str += super.toString(); + str += " [guid=" + guid + ", policyId=" + policyId + ", policyLabelId=" + policyLabelId + "]"; + str += "}"; + return str; + } + + /** + * @return the gUID + */ + public String getGuid() { + return guid; + } + + /** + * @param gUID the gUID to set + */ + public void setGuid(String gUID) { + guid = gUID; + } + + /** + * @return the policyId + */ + public Long getPolicyId() { + return policyId; + } + + /** + * @param policyId the policyId to set + */ + public void setPolicyId(Long policyId) { + this.policyId = policyId; + } + + /** + * @return the policyLabelId + */ + public Long getPolicyLabelId() { + return policyLabelId; + } + + /** + * @param policyLabelId the policyLabelId to set + */ + public void setPolicyLabelId(Long policyLabelId) { + this.policyLabelId = policyLabelId; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/entity/XXPolicyRefAccessType.java b/security-admin/src/main/java/org/apache/ranger/entity/XXPolicyRefAccessType.java index f1e8f90bcf..13bf1d8f1e 100644 --- a/security-admin/src/main/java/org/apache/ranger/entity/XXPolicyRefAccessType.java +++ b/security-admin/src/main/java/org/apache/ranger/entity/XXPolicyRefAccessType.java @@ -18,172 +18,166 @@ */ package org.apache.ranger.entity; -import javax.persistence.*; +import javax.persistence.Cacheable; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.SequenceGenerator; +import javax.persistence.Table; + import java.util.Objects; @Entity @Cacheable @Table(name = "x_policy_ref_access_type") -public class XXPolicyRefAccessType extends XXDBBase implements - java.io.Serializable { - private static final long serialVersionUID = 1L; - /** - * id of the XXPolicyRefAccessType - *
    - *
- * - */ - @Id - @SequenceGenerator(name = "x_policy_ref_access_type_SEQ", sequenceName = "x_policy_ref_access_type_SEQ", allocationSize = 1) - @GeneratedValue(strategy = GenerationType.AUTO, generator = "x_policy_ref_access_type_SEQ") - @Column(name = "id") - protected Long id; - - /** - * policyId of the XXPolicyRefAccessType - *
    - *
- * - */ - @Column(name = "policy_id") - protected Long policyId; - - /** - * accessDefId of the XXPolicyRefAccessType - *
    - *
- * - */ - @Column(name = "access_def_id") - protected Long accessDefId; - - /** - * accessTypeName of the XXPolicyRefAccessType - *
    - *
- * - */ - @Column(name = "access_type_name") - protected String accessTypeName; - - /** - * This method sets the value to the member attribute id . You - * cannot set null to the attribute. - * - * @param id - * Value to set member attribute id - */ - public void setId(Long id) { - this.id = id; - } - - /** - * Returns the value for the member attribute id - * - * @return Date - value of member attribute id . - */ - public Long getId() { - return this.id; - } - - /** - * This method sets the value to the member attribute policyId . - * You cannot set null to the attribute. - * - * @param policyId - * Value to set member attribute policyId - */ - public void setPolicyId(Long policyId) { - this.policyId = policyId; - } - - /** - * Returns the value for the member attribute policyId - * - * @return Date - value of member attribute policyId . - */ - public Long getPolicyId() { - return this.policyId; - } - - /** - * This method sets the value to the member attribute accessDefId . - * You cannot set null to the attribute. - * - * @param accessDefId - * Value to set member attribute accessDefId - */ - public void setAccessDefId(Long accessDefId) { - this.accessDefId = accessDefId; - } - - /** - * Returns the value for the member attribute accessDefId - * - * @return Date - value of member attribute accessDefId . - */ - public Long getAccessDefId() { - return accessDefId; - } - - /** - * This method sets the value to the member attribute accessTypeName . - * You cannot set null to the attribute. - * - * @param accessTypeName - * Value to set member attribute accessTypeName - */ - public void setAccessTypeName(String accessTypeName) { - this.accessTypeName = accessTypeName; - } - - /** - * Returns the value for the member attribute accessTypeName - * - * @return Date - value of member attribute accessTypeName . - */ - public String getAccessTypeName() { - return accessTypeName; - } - - @Override - public int hashCode() { - return Objects.hash(super.hashCode(), id, policyId, accessDefId, accessTypeName); - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#equals(java.lang.Object) - */ - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - - if (getClass() != obj.getClass()) { - return false; - } - - XXPolicyRefAccessType other = (XXPolicyRefAccessType) obj; - - return super.equals(obj) && - Objects.equals(id, other.id) && - Objects.equals(policyId, other.policyId) && - Objects.equals(accessDefId, other.accessDefId) && - Objects.equals(accessTypeName, other.accessTypeName); - } - - /* (non-Javadoc) - * @see java.lang.Object#toString() - */ - @Override - public String toString() { - return "XXPolicyRefAccessType [" + super.toString() + " id=" + id + ", policyId=" + policyId + ", accessDefId=" - + accessDefId + ", accessTypeName=" + accessTypeName + "]"; - } - - - +public class XXPolicyRefAccessType extends XXDBBase implements java.io.Serializable { + private static final long serialVersionUID = 1L; + + /** + * id of the XXPolicyRefAccessType + *
    + *
+ */ + @Id + @SequenceGenerator(name = "x_policy_ref_access_type_SEQ", sequenceName = "x_policy_ref_access_type_SEQ", allocationSize = 1) + @GeneratedValue(strategy = GenerationType.AUTO, generator = "x_policy_ref_access_type_SEQ") + @Column(name = "id") + protected Long id; + + /** + * policyId of the XXPolicyRefAccessType + *
    + *
+ */ + @Column(name = "policy_id") + protected Long policyId; + + /** + * accessDefId of the XXPolicyRefAccessType + *
    + *
+ */ + @Column(name = "access_def_id") + protected Long accessDefId; + + /** + * accessTypeName of the XXPolicyRefAccessType + *
    + *
+ */ + @Column(name = "access_type_name") + protected String accessTypeName; + + /** + * Returns the value for the member attribute id + * + * @return Date - value of member attribute id . + */ + public Long getId() { + return this.id; + } + + /** + * This method sets the value to the member attribute id . You + * cannot set null to the attribute. + * + * @param id Value to set member attribute id + */ + public void setId(Long id) { + this.id = id; + } + + @Override + public int hashCode() { + return Objects.hash(super.hashCode(), id, policyId, accessDefId, accessTypeName); + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#equals(java.lang.Object) + */ + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } else if (!super.equals(obj)) { + return false; + } + + XXPolicyRefAccessType other = (XXPolicyRefAccessType) obj; + + return super.equals(obj) && + Objects.equals(id, other.id) && + Objects.equals(policyId, other.policyId) && + Objects.equals(accessDefId, other.accessDefId) && + Objects.equals(accessTypeName, other.accessTypeName); + } + + /* (non-Javadoc) + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + return "XXPolicyRefAccessType [" + super.toString() + " id=" + id + ", policyId=" + policyId + ", accessDefId=" + accessDefId + ", accessTypeName=" + accessTypeName + "]"; + } + + /** + * Returns the value for the member attribute policyId + * + * @return Date - value of member attribute policyId . + */ + public Long getPolicyId() { + return this.policyId; + } + + /** + * This method sets the value to the member attribute policyId . + * You cannot set null to the attribute. + * + * @param policyId Value to set member attribute policyId + */ + public void setPolicyId(Long policyId) { + this.policyId = policyId; + } + + /** + * Returns the value for the member attribute accessDefId + * + * @return Date - value of member attribute accessDefId . + */ + public Long getAccessDefId() { + return accessDefId; + } + + /** + * This method sets the value to the member attribute accessDefId . + * You cannot set null to the attribute. + * + * @param accessDefId Value to set member attribute accessDefId + */ + public void setAccessDefId(Long accessDefId) { + this.accessDefId = accessDefId; + } + + /** + * Returns the value for the member attribute accessTypeName + * + * @return Date - value of member attribute accessTypeName . + */ + public String getAccessTypeName() { + return accessTypeName; + } + + /** + * This method sets the value to the member attribute accessTypeName . + * You cannot set null to the attribute. + * + * @param accessTypeName Value to set member attribute accessTypeName + */ + public void setAccessTypeName(String accessTypeName) { + this.accessTypeName = accessTypeName; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/entity/XXPolicyRefCondition.java b/security-admin/src/main/java/org/apache/ranger/entity/XXPolicyRefCondition.java index fcae3bb10e..d060aefd46 100644 --- a/security-admin/src/main/java/org/apache/ranger/entity/XXPolicyRefCondition.java +++ b/security-admin/src/main/java/org/apache/ranger/entity/XXPolicyRefCondition.java @@ -18,172 +18,166 @@ */ package org.apache.ranger.entity; -import javax.persistence.*; +import javax.persistence.Cacheable; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.SequenceGenerator; +import javax.persistence.Table; + import java.util.Objects; @Entity @Cacheable @Table(name = "x_policy_ref_condition") -public class XXPolicyRefCondition extends XXDBBase implements - java.io.Serializable { - private static final long serialVersionUID = 1L; - /** - * id of the XXPolicyRefCondition - *
    - *
- * - */ - @Id - @SequenceGenerator(name = "x_policy_ref_condition_SEQ", sequenceName = "x_policy_ref_condition_SEQ", allocationSize = 1) - @GeneratedValue(strategy = GenerationType.AUTO, generator = "x_policy_ref_condition_SEQ") - @Column(name = "id") - protected Long id; - - /** - * policyId of the XXPolicyRefCondition - *
    - *
- * - */ - @Column(name = "policy_id") - protected Long policyId; - - /** - * conditionDefId of the XXPolicyRefCondition - *
    - *
- * - */ - @Column(name = "condition_def_id") - protected Long conditionDefId; - - /** - * conditionName of the XXPolicyRefCondition - *
    - *
- * - */ - @Column(name = "condition_name") - protected String conditionName; - - /** - * This method sets the value to the member attribute id . You - * cannot set null to the attribute. - * - * @param id - * Value to set member attribute id - */ - public void setId(Long id) { - this.id = id; - } - - /** - * Returns the value for the member attribute id - * - * @return Date - value of member attribute id . - */ - public Long getId() { - return this.id; - } - - /** - * This method sets the value to the member attribute policyId . - * You cannot set null to the attribute. - * - * @param policyId - * Value to set member attribute policyId - */ - public void setPolicyId(Long policyId) { - this.policyId = policyId; - } - - /** - * Returns the value for the member attribute policyId - * - * @return Date - value of member attribute policyId . - */ - public Long getPolicyId() { - return this.policyId; - } - - /** - * This method sets the value to the member attribute conditionDefId . - * You cannot set null to the attribute. - * - * @param conditionDefId - * Value to set member attribute conditionDefId - */ - public void setConditionDefId(Long conditionDefId) { - this.conditionDefId = conditionDefId; - } - - /** - * Returns the value for the member attribute conditionDefId - * - * @return Date - value of member attribute conditionDefId . - */ - public Long getConditionDefId() { - return conditionDefId; - } - - /** - * This method sets the value to the member attribute conditionName . - * You cannot set null to the attribute. - * - * @param conditionName - * Value to set member attribute conditionName - */ - public void setConditionName(String conditionName) { - this.conditionName = conditionName; - } - - /** - * Returns the value for the member attribute conditionName - * - * @return Date - value of member attribute conditionName . - */ - public String getConditionName() { - return conditionName; - } - - @Override - public int hashCode() { - return Objects.hash(super.hashCode(), id, policyId, conditionDefId, conditionName); - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#equals(java.lang.Object) - */ - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - - if (getClass() != obj.getClass()) { - return false; - } - - XXPolicyRefCondition other = (XXPolicyRefCondition) obj; - - return super.equals(obj) && - Objects.equals(id, other.id) && - Objects.equals(policyId, other.policyId) && - Objects.equals(conditionDefId, other.conditionDefId) && - Objects.equals(conditionName, other.conditionName); - } - - /* (non-Javadoc) - * @see java.lang.Object#toString() - */ - @Override - public String toString() { - return "XXPolicyRefCondition [" + super.toString() + " id=" + id + ", policyId=" + policyId + ", conditionDefId=" - + conditionDefId + ", conditionName=" + conditionName + "]"; - } - - - +public class XXPolicyRefCondition extends XXDBBase implements java.io.Serializable { + private static final long serialVersionUID = 1L; + + /** + * id of the XXPolicyRefCondition + *
    + *
+ */ + @Id + @SequenceGenerator(name = "x_policy_ref_condition_SEQ", sequenceName = "x_policy_ref_condition_SEQ", allocationSize = 1) + @GeneratedValue(strategy = GenerationType.AUTO, generator = "x_policy_ref_condition_SEQ") + @Column(name = "id") + protected Long id; + + /** + * policyId of the XXPolicyRefCondition + *
    + *
+ */ + @Column(name = "policy_id") + protected Long policyId; + + /** + * conditionDefId of the XXPolicyRefCondition + *
    + *
+ */ + @Column(name = "condition_def_id") + protected Long conditionDefId; + + /** + * conditionName of the XXPolicyRefCondition + *
    + *
+ */ + @Column(name = "condition_name") + protected String conditionName; + + /** + * Returns the value for the member attribute id + * + * @return Date - value of member attribute id . + */ + public Long getId() { + return this.id; + } + + /** + * This method sets the value to the member attribute id . You + * cannot set null to the attribute. + * + * @param id Value to set member attribute id + */ + public void setId(Long id) { + this.id = id; + } + + @Override + public int hashCode() { + return Objects.hash(super.hashCode(), id, policyId, conditionDefId, conditionName); + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#equals(java.lang.Object) + */ + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } else if (!super.equals(obj)) { + return false; + } + + XXPolicyRefCondition other = (XXPolicyRefCondition) obj; + + return super.equals(obj) && + Objects.equals(id, other.id) && + Objects.equals(policyId, other.policyId) && + Objects.equals(conditionDefId, other.conditionDefId) && + Objects.equals(conditionName, other.conditionName); + } + + /* (non-Javadoc) + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + return "XXPolicyRefCondition [" + super.toString() + " id=" + id + ", policyId=" + policyId + ", conditionDefId=" + conditionDefId + ", conditionName=" + conditionName + "]"; + } + + /** + * Returns the value for the member attribute policyId + * + * @return Date - value of member attribute policyId . + */ + public Long getPolicyId() { + return this.policyId; + } + + /** + * This method sets the value to the member attribute policyId . + * You cannot set null to the attribute. + * + * @param policyId Value to set member attribute policyId + */ + public void setPolicyId(Long policyId) { + this.policyId = policyId; + } + + /** + * Returns the value for the member attribute conditionDefId + * + * @return Date - value of member attribute conditionDefId . + */ + public Long getConditionDefId() { + return conditionDefId; + } + + /** + * This method sets the value to the member attribute conditionDefId . + * You cannot set null to the attribute. + * + * @param conditionDefId Value to set member attribute conditionDefId + */ + public void setConditionDefId(Long conditionDefId) { + this.conditionDefId = conditionDefId; + } + + /** + * Returns the value for the member attribute conditionName + * + * @return Date - value of member attribute conditionName . + */ + public String getConditionName() { + return conditionName; + } + + /** + * This method sets the value to the member attribute conditionName . + * You cannot set null to the attribute. + * + * @param conditionName Value to set member attribute conditionName + */ + public void setConditionName(String conditionName) { + this.conditionName = conditionName; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/entity/XXPolicyRefDataMaskType.java b/security-admin/src/main/java/org/apache/ranger/entity/XXPolicyRefDataMaskType.java index e6c40cc71c..66e138e8c3 100644 --- a/security-admin/src/main/java/org/apache/ranger/entity/XXPolicyRefDataMaskType.java +++ b/security-admin/src/main/java/org/apache/ranger/entity/XXPolicyRefDataMaskType.java @@ -18,173 +18,166 @@ */ package org.apache.ranger.entity; -import javax.persistence.*; +import javax.persistence.Cacheable; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.SequenceGenerator; +import javax.persistence.Table; + import java.util.Objects; @Entity @Cacheable @Table(name = "x_policy_ref_datamask_type") -public class XXPolicyRefDataMaskType extends XXDBBase implements - java.io.Serializable { - private static final long serialVersionUID = 1L; - /** - * id of the XXPolicyRefDataMaskType - *
    - *
- * - */ - @Id - @SequenceGenerator(name = "x_policy_ref_datamask_type_SEQ", sequenceName = "x_policy_ref_datamask_type_SEQ", allocationSize = 1) - @GeneratedValue(strategy = GenerationType.AUTO, generator = "x_policy_ref_datamask_type_SEQ") - @Column(name = "id") - protected Long id; - - /** - * policyId of the XXPolicyRefDataMaskType - *
    - *
- * - */ - @Column(name = "policy_id") - protected Long policyId; - - /** - * DatamaskDefId of the XXPolicyRefDataMaskType - *
    - *
- * - */ - @Column(name = "datamask_def_id") - protected Long dataMaskDefId; - - /** - * dataMaskTypeName of the XXPolicyRefDataMaskType - *
    - *
- * - */ - @Column(name = "datamask_type_name") - protected String dataMaskTypeName; - - /** - * This method sets the value to the member attribute id . You - * cannot set null to the attribute. - * - * @param id - * Value to set member attribute id - */ - public void setId(Long id) { - this.id = id; - } - - /** - * Returns the value for the member attribute id - * - * @return Date - value of member attribute id . - */ - public Long getId() { - return this.id; - } - - - /** - * This method sets the value to the member attribute policyId . - * You cannot set null to the attribute. - * - * @param policyId - * Value to set member attribute policyId - */ - public void setPolicyId(Long policyId) { - this.policyId = policyId; - } - - /** - * Returns the value for the member attribute policyId - * - * @return Date - value of member attribute policyId . - */ - public Long getPolicyId() { - return this.policyId; - } - - /** - * This method sets the value to the member attribute dataMaskDefId . - * You cannot set null to the attribute. - * - * @param dataMaskDefId - * Value to set member attribute dataMaskDefId - */ - public void setDataMaskDefId(Long dataMaskDefId) { - this.dataMaskDefId = dataMaskDefId; - } - - /** - * Returns the value for the member attribute dataMaskDefId - * - * @return Date - value of member attribute dataMaskDefId . - */ - public Long getDataMaskDefId() { - return dataMaskDefId; - } - - /** - * This method sets the value to the member attribute dataMaskTypeName . - * You cannot set null to the attribute. - * - * @param dataMaskTypeName - * Value to set member attribute dataMaskTypeName - */ - public void setDataMaskTypeName(String dataMaskTypeName) { - this.dataMaskTypeName = dataMaskTypeName; - } - - /** - * Returns the value for the member attribute dataMaskTypeName - * - * @return Date - value of member attribute dataMaskTypeName . - */ - public String getDataMaskTypeName() { - return dataMaskTypeName; - } - - @Override - public int hashCode() { - return Objects.hash(super.hashCode(), id, policyId, dataMaskDefId, dataMaskTypeName); - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#equals(java.lang.Object) - */ - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - - if (getClass() != obj.getClass()) { - return false; - } - - XXPolicyRefDataMaskType other = (XXPolicyRefDataMaskType) obj; - - return super.equals(obj) && - Objects.equals(id, other.id) && - Objects.equals(policyId, other.policyId) && - Objects.equals(dataMaskDefId, other.dataMaskDefId) && - Objects.equals(dataMaskTypeName, other.dataMaskTypeName); - } - - /* (non-Javadoc) - * @see java.lang.Object#toString() - */ - @Override - public String toString() { - return "XXPolicyRefDataMaskType [" + super.toString() + " id=" + id + ", policyId=" + policyId + ", dataMaskDefId=" - + dataMaskDefId + ", dataMaskTypeName=" + dataMaskTypeName + "]"; - } - - - +public class XXPolicyRefDataMaskType extends XXDBBase implements java.io.Serializable { + private static final long serialVersionUID = 1L; + + /** + * id of the XXPolicyRefDataMaskType + *
    + *
+ */ + @Id + @SequenceGenerator(name = "x_policy_ref_datamask_type_SEQ", sequenceName = "x_policy_ref_datamask_type_SEQ", allocationSize = 1) + @GeneratedValue(strategy = GenerationType.AUTO, generator = "x_policy_ref_datamask_type_SEQ") + @Column(name = "id") + protected Long id; + + /** + * policyId of the XXPolicyRefDataMaskType + *
    + *
+ */ + @Column(name = "policy_id") + protected Long policyId; + + /** + * DatamaskDefId of the XXPolicyRefDataMaskType + *
    + *
+ */ + @Column(name = "datamask_def_id") + protected Long dataMaskDefId; + + /** + * dataMaskTypeName of the XXPolicyRefDataMaskType + *
    + *
+ */ + @Column(name = "datamask_type_name") + protected String dataMaskTypeName; + + /** + * Returns the value for the member attribute id + * + * @return Date - value of member attribute id . + */ + public Long getId() { + return this.id; + } + + /** + * This method sets the value to the member attribute id . You + * cannot set null to the attribute. + * + * @param id Value to set member attribute id + */ + public void setId(Long id) { + this.id = id; + } + + @Override + public int hashCode() { + return Objects.hash(super.hashCode(), id, policyId, dataMaskDefId, dataMaskTypeName); + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#equals(java.lang.Object) + */ + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } else if (!super.equals(obj)) { + return false; + } + + XXPolicyRefDataMaskType other = (XXPolicyRefDataMaskType) obj; + + return super.equals(obj) && + Objects.equals(id, other.id) && + Objects.equals(policyId, other.policyId) && + Objects.equals(dataMaskDefId, other.dataMaskDefId) && + Objects.equals(dataMaskTypeName, other.dataMaskTypeName); + } + + /* (non-Javadoc) + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + return "XXPolicyRefDataMaskType [" + super.toString() + " id=" + id + ", policyId=" + policyId + ", dataMaskDefId=" + dataMaskDefId + ", dataMaskTypeName=" + dataMaskTypeName + "]"; + } + + /** + * Returns the value for the member attribute policyId + * + * @return Date - value of member attribute policyId . + */ + public Long getPolicyId() { + return this.policyId; + } + + /** + * This method sets the value to the member attribute policyId . + * You cannot set null to the attribute. + * + * @param policyId Value to set member attribute policyId + */ + public void setPolicyId(Long policyId) { + this.policyId = policyId; + } + + /** + * Returns the value for the member attribute dataMaskDefId + * + * @return Date - value of member attribute dataMaskDefId . + */ + public Long getDataMaskDefId() { + return dataMaskDefId; + } + + /** + * This method sets the value to the member attribute dataMaskDefId . + * You cannot set null to the attribute. + * + * @param dataMaskDefId Value to set member attribute dataMaskDefId + */ + public void setDataMaskDefId(Long dataMaskDefId) { + this.dataMaskDefId = dataMaskDefId; + } + + /** + * Returns the value for the member attribute dataMaskTypeName + * + * @return Date - value of member attribute dataMaskTypeName . + */ + public String getDataMaskTypeName() { + return dataMaskTypeName; + } + + /** + * This method sets the value to the member attribute dataMaskTypeName . + * You cannot set null to the attribute. + * + * @param dataMaskTypeName Value to set member attribute dataMaskTypeName + */ + public void setDataMaskTypeName(String dataMaskTypeName) { + this.dataMaskTypeName = dataMaskTypeName; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/entity/XXPolicyRefGroup.java b/security-admin/src/main/java/org/apache/ranger/entity/XXPolicyRefGroup.java index 1c9adfd532..b73d022325 100644 --- a/security-admin/src/main/java/org/apache/ranger/entity/XXPolicyRefGroup.java +++ b/security-admin/src/main/java/org/apache/ranger/entity/XXPolicyRefGroup.java @@ -19,9 +19,6 @@ package org.apache.ranger.entity; -import java.io.Serializable; -import java.util.Objects; - import javax.persistence.Cacheable; import javax.persistence.Column; import javax.persistence.Entity; @@ -31,174 +28,163 @@ import javax.persistence.SequenceGenerator; import javax.persistence.Table; +import java.io.Serializable; +import java.util.Objects; /** * The persistent class for the x_policy_ref_group database table. - * */ @Entity @Cacheable -@Table(name="x_policy_ref_group") +@Table(name = "x_policy_ref_group") public class XXPolicyRefGroup extends XXDBBase implements Serializable { - - private static final long serialVersionUID = 1L; - /** - * id of the XXPolicyRefGroup - *
    - *
- * - */ - @Id - @SequenceGenerator(name = "x_policy_ref_group_SEQ", sequenceName = "x_policy_ref_group_SEQ", allocationSize = 1) - @GeneratedValue(strategy = GenerationType.AUTO, generator = "x_policy_ref_group_SEQ") - @Column(name = "id") - protected Long id; - - /** - * policyId of the XXPolicyRefGroup - *
    - *
- * - */ - @Column(name = "policy_id") - protected Long policyId; - - /** - * groupId of the XXPolicyRefGroup - *
    - *
- * - */ - @Column(name = "group_id") - protected Long groupId; - - /** - * groupName of the XXPolicyRefGroup - *
    - *
- * - */ - @Column(name = "group_name") - protected String groupName; - - /** - * This method sets the value to the member attribute id . You - * cannot set null to the attribute. - * - * @param id - * Value to set member attribute id - */ - public void setId(Long id) { - this.id = id; - } - - /** - * Returns the value for the member attribute id - * - * @return Date - value of member attribute id . - */ - public Long getId() { - return this.id; - } - - /** - * This method sets the value to the member attribute policyId . - * You cannot set null to the attribute. - * - * @param policyId - * Value to set member attribute policyId - */ - public void setPolicyId(Long policyId) { - this.policyId = policyId; - } - - /** - * Returns the value for the member attribute policyId - * - * @return Date - value of member attribute policyId . - */ - public Long getPolicyId() { - return this.policyId; - } - - /** - * This method sets the value to the member attribute groupId . - * You cannot set null to the attribute. - * - * @param groupId - * Value to set member attribute groupId - */ - public void setGroupId(Long groupId) { - this.groupId = groupId; - } - - /** - * Returns the value for the member attribute groupId - * - * @return Date - value of member attribute groupId . - */ - public Long getGroupId() { - return groupId; - } - - /** - * This method sets the value to the member attribute groupName . - * You cannot set null to the attribute. - * - * @param groupName - * Value to set member attribute groupName - */ - public void setGroupName(String groupName) { - this.groupName = groupName; - } - - /** - * Returns the value for the member attribute groupName - * - * @return Date - value of member attribute groupName . - */ - public String getGroupName() { - return groupName; - } - - @Override - public int hashCode() { - return Objects.hash(super.hashCode(), id, policyId, groupId, groupName); - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#equals(java.lang.Object) - */ - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - - if (getClass() != obj.getClass()) { - return false; - } - - XXPolicyRefGroup other = (XXPolicyRefGroup) obj; - - return super.equals(obj) && - Objects.equals(id, other.id) && - Objects.equals(policyId, other.policyId) && - Objects.equals(groupId, other.groupId) && - Objects.equals(groupName, other.groupName); - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#toString() - */ - @Override - public String toString() { - return "XXPolicyRefGroup [" + super.toString() + " id=" + id + ", policyId=" + policyId + ", groupId=" + groupId - + ", groupName=" + groupName + "]"; - } - + private static final long serialVersionUID = 1L; + + /** + * id of the XXPolicyRefGroup + *
    + *
+ */ + @Id + @SequenceGenerator(name = "x_policy_ref_group_SEQ", sequenceName = "x_policy_ref_group_SEQ", allocationSize = 1) + @GeneratedValue(strategy = GenerationType.AUTO, generator = "x_policy_ref_group_SEQ") + @Column(name = "id") + protected Long id; + + /** + * policyId of the XXPolicyRefGroup + *
    + *
+ */ + @Column(name = "policy_id") + protected Long policyId; + + /** + * groupId of the XXPolicyRefGroup + *
    + *
+ */ + @Column(name = "group_id") + protected Long groupId; + + /** + * groupName of the XXPolicyRefGroup + *
    + *
+ */ + @Column(name = "group_name") + protected String groupName; + + /** + * Returns the value for the member attribute id + * + * @return Date - value of member attribute id . + */ + public Long getId() { + return this.id; + } + + /** + * This method sets the value to the member attribute id . You + * cannot set null to the attribute. + * + * @param id Value to set member attribute id + */ + public void setId(Long id) { + this.id = id; + } + + @Override + public int hashCode() { + return Objects.hash(super.hashCode(), id, policyId, groupId, groupName); + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#equals(java.lang.Object) + */ + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } else if (!super.equals(obj)) { + return false; + } + + XXPolicyRefGroup other = (XXPolicyRefGroup) obj; + + return super.equals(obj) && + Objects.equals(id, other.id) && + Objects.equals(policyId, other.policyId) && + Objects.equals(groupId, other.groupId) && + Objects.equals(groupName, other.groupName); + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + return "XXPolicyRefGroup [" + super.toString() + " id=" + id + ", policyId=" + policyId + ", groupId=" + groupId + ", groupName=" + groupName + "]"; + } + + /** + * Returns the value for the member attribute policyId + * + * @return Date - value of member attribute policyId . + */ + public Long getPolicyId() { + return this.policyId; + } + + /** + * This method sets the value to the member attribute policyId . + * You cannot set null to the attribute. + * + * @param policyId Value to set member attribute policyId + */ + public void setPolicyId(Long policyId) { + this.policyId = policyId; + } + + /** + * Returns the value for the member attribute groupId + * + * @return Date - value of member attribute groupId . + */ + public Long getGroupId() { + return groupId; + } + + /** + * This method sets the value to the member attribute groupId . + * You cannot set null to the attribute. + * + * @param groupId Value to set member attribute groupId + */ + public void setGroupId(Long groupId) { + this.groupId = groupId; + } + + /** + * Returns the value for the member attribute groupName + * + * @return Date - value of member attribute groupName . + */ + public String getGroupName() { + return groupName; + } + + /** + * This method sets the value to the member attribute groupName . + * You cannot set null to the attribute. + * + * @param groupName Value to set member attribute groupName + */ + public void setGroupName(String groupName) { + this.groupName = groupName; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/entity/XXPolicyRefResource.java b/security-admin/src/main/java/org/apache/ranger/entity/XXPolicyRefResource.java index ddc33e1efa..4f04b035c5 100644 --- a/security-admin/src/main/java/org/apache/ranger/entity/XXPolicyRefResource.java +++ b/security-admin/src/main/java/org/apache/ranger/entity/XXPolicyRefResource.java @@ -18,172 +18,166 @@ */ package org.apache.ranger.entity; -import javax.persistence.*; +import javax.persistence.Cacheable; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.SequenceGenerator; +import javax.persistence.Table; + import java.util.Objects; @Entity @Cacheable @Table(name = "x_policy_ref_resource") -public class XXPolicyRefResource extends XXDBBase implements - java.io.Serializable { - private static final long serialVersionUID = 1L; - /** - * id of the XXPolicyRefResource - *
    - *
- * - */ - @Id - @SequenceGenerator(name = "x_policy_ref_resource_SEQ", sequenceName = "x_policy_ref_resource_SEQ", allocationSize = 1) - @GeneratedValue(strategy = GenerationType.AUTO, generator = "x_policy_ref_resource_SEQ") - @Column(name = "id") - protected Long id; - - /** - * policyId of the XXPolicyRefResource - *
    - *
- * - */ - @Column(name = "policy_id") - protected Long policyId; - - /** - * resourceDefId of the XXPolicyRefResource - *
    - *
- * - */ - @Column(name = "resource_def_id") - protected Long resourceDefId; - - /** - * resource_name of the XXPolicyRefResource - *
    - *
- * - */ - @Column(name = "resource_name") - protected String resourceName; - - /** - * This method sets the value to the member attribute id . You - * cannot set null to the attribute. - * - * @param id - * Value to set member attribute id - */ - public void setId(Long id) { - this.id = id; - } - - /** - * Returns the value for the member attribute id - * - * @return Date - value of member attribute id . - */ - public Long getId() { - return this.id; - } - - /** - * This method sets the value to the member attribute policyId . - * You cannot set null to the attribute. - * - * @param policyId - * Value to set member attribute policyId - */ - public void setPolicyId(Long policyId) { - this.policyId = policyId; - } - - /** - * Returns the value for the member attribute policyId - * - * @return Date - value of member attribute policyId . - */ - public Long getPolicyId() { - return this.policyId; - } - - /** - * This method sets the value to the member attribute resourceDefId . - * You cannot set null to the attribute. - * - * @param resourceDefId - * Value to set member attribute resourceDefId - */ - public void setResourceDefId(Long resourceDefId) { - this.resourceDefId = resourceDefId; - } - - /** - * Returns the value for the member attribute resourceDefId - * - * @return Date - value of member attribute resourceDefId . - */ - public Long getResourceDefId() { - return resourceDefId; - } - - /** - * This method sets the value to the member attribute resource_name . - * You cannot set null to the attribute. - * - * @param resourceName - * Value to set member attribute resource_name - */ - public void setResourceName(String resourceName) { - this.resourceName = resourceName; - } - - /** - * Returns the value for the member attribute resourceName - * - * @return Date - value of member attribute resourceName . - */ - public String getResourceName() { - return resourceName; - } - - @Override - public int hashCode() { - return Objects.hash(super.hashCode(), id, policyId, resourceDefId, resourceName); - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#equals(java.lang.Object) - */ - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - - if (getClass() != obj.getClass()) { - return false; - } - - XXPolicyRefResource other = (XXPolicyRefResource) obj; - - return super.equals(obj) && - Objects.equals(id, other.id) && - Objects.equals(policyId, other.policyId) && - Objects.equals(resourceDefId, other.resourceDefId) && - Objects.equals(resourceName, other.resourceName); - } - - /* (non-Javadoc) - * @see java.lang.Object#toString() - */ - @Override - public String toString() { - return "XXPolicyRefResource [" + super.toString() + " id=" + id + ", policyId=" + policyId + ", resourceDefId=" - + resourceDefId + ", resource_name=" + resourceName + "]"; - } - - - +public class XXPolicyRefResource extends XXDBBase implements java.io.Serializable { + private static final long serialVersionUID = 1L; + + /** + * id of the XXPolicyRefResource + *
    + *
+ */ + @Id + @SequenceGenerator(name = "x_policy_ref_resource_SEQ", sequenceName = "x_policy_ref_resource_SEQ", allocationSize = 1) + @GeneratedValue(strategy = GenerationType.AUTO, generator = "x_policy_ref_resource_SEQ") + @Column(name = "id") + protected Long id; + + /** + * policyId of the XXPolicyRefResource + *
    + *
+ */ + @Column(name = "policy_id") + protected Long policyId; + + /** + * resourceDefId of the XXPolicyRefResource + *
    + *
+ */ + @Column(name = "resource_def_id") + protected Long resourceDefId; + + /** + * resource_name of the XXPolicyRefResource + *
    + *
+ */ + @Column(name = "resource_name") + protected String resourceName; + + /** + * Returns the value for the member attribute id + * + * @return Date - value of member attribute id . + */ + public Long getId() { + return this.id; + } + + /** + * This method sets the value to the member attribute id . You + * cannot set null to the attribute. + * + * @param id Value to set member attribute id + */ + public void setId(Long id) { + this.id = id; + } + + @Override + public int hashCode() { + return Objects.hash(super.hashCode(), id, policyId, resourceDefId, resourceName); + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#equals(java.lang.Object) + */ + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } else if (!super.equals(obj)) { + return false; + } + + XXPolicyRefResource other = (XXPolicyRefResource) obj; + + return super.equals(obj) && + Objects.equals(id, other.id) && + Objects.equals(policyId, other.policyId) && + Objects.equals(resourceDefId, other.resourceDefId) && + Objects.equals(resourceName, other.resourceName); + } + + /* (non-Javadoc) + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + return "XXPolicyRefResource [" + super.toString() + " id=" + id + ", policyId=" + policyId + ", resourceDefId=" + resourceDefId + ", resource_name=" + resourceName + "]"; + } + + /** + * Returns the value for the member attribute policyId + * + * @return Date - value of member attribute policyId . + */ + public Long getPolicyId() { + return this.policyId; + } + + /** + * This method sets the value to the member attribute policyId . + * You cannot set null to the attribute. + * + * @param policyId Value to set member attribute policyId + */ + public void setPolicyId(Long policyId) { + this.policyId = policyId; + } + + /** + * Returns the value for the member attribute resourceDefId + * + * @return Date - value of member attribute resourceDefId . + */ + public Long getResourceDefId() { + return resourceDefId; + } + + /** + * This method sets the value to the member attribute resourceDefId . + * You cannot set null to the attribute. + * + * @param resourceDefId Value to set member attribute resourceDefId + */ + public void setResourceDefId(Long resourceDefId) { + this.resourceDefId = resourceDefId; + } + + /** + * Returns the value for the member attribute resourceName + * + * @return Date - value of member attribute resourceName . + */ + public String getResourceName() { + return resourceName; + } + + /** + * This method sets the value to the member attribute resource_name . + * You cannot set null to the attribute. + * + * @param resourceName Value to set member attribute resource_name + */ + public void setResourceName(String resourceName) { + this.resourceName = resourceName; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/entity/XXPolicyRefRole.java b/security-admin/src/main/java/org/apache/ranger/entity/XXPolicyRefRole.java index f0a91159fe..3a3a4b7a53 100644 --- a/security-admin/src/main/java/org/apache/ranger/entity/XXPolicyRefRole.java +++ b/security-admin/src/main/java/org/apache/ranger/entity/XXPolicyRefRole.java @@ -19,9 +19,6 @@ package org.apache.ranger.entity; -import java.io.Serializable; -import java.util.Objects; - import javax.persistence.Cacheable; import javax.persistence.Column; import javax.persistence.Entity; @@ -31,22 +28,22 @@ import javax.persistence.SequenceGenerator; import javax.persistence.Table; +import java.io.Serializable; +import java.util.Objects; /** * The persistent class for the x_policy_ref_role database table. - * */ @Entity @Cacheable -@Table(name="x_policy_ref_role") +@Table(name = "x_policy_ref_role") public class XXPolicyRefRole extends XXDBBase implements Serializable { - private static final long serialVersionUID = 1L; + /** * id of the XXPolicyRefRole *
    *
- * */ @Id @SequenceGenerator(name = "x_policy_ref_role_SEQ", sequenceName = "x_policy_ref_role_SEQ", allocationSize = 1) @@ -58,7 +55,6 @@ public class XXPolicyRefRole extends XXDBBase implements Serializable { * policyId of the XXPolicyRefRole *
    *
- * */ @Column(name = "policy_id") protected Long policyId; @@ -67,7 +63,6 @@ public class XXPolicyRefRole extends XXDBBase implements Serializable { * roleId of the XXPolicyRefRole *
    *
- * */ @Column(name = "role_id") protected Long roleId; @@ -76,40 +71,64 @@ public class XXPolicyRefRole extends XXDBBase implements Serializable { * roleName of the XXPolicyRefRole *
    *
- * */ @Column(name = "role_name") protected String roleName; + /** + * Returns the value for the member attribute id + * + * @return Date - value of member attribute id . + */ + public Long getId() { + return this.id; + } + /** * This method sets the value to the member attribute id . You * cannot set null to the attribute. * - * @param id - * Value to set member attribute id + * @param id Value to set member attribute id */ public void setId(Long id) { this.id = id; } - /** - * Returns the value for the member attribute id + @Override + public int hashCode() { + return Objects.hash(super.hashCode(), id, policyId, roleId, roleName); + } + + /* + * (non-Javadoc) * - * @return Date - value of member attribute id . + * @see java.lang.Object#equals(java.lang.Object) */ - public Long getId() { - return this.id; + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } else if (!super.equals(obj)) { + return false; + } + + XXPolicyRefRole other = (XXPolicyRefRole) obj; + + return super.equals(obj) && + Objects.equals(id, other.id) && + Objects.equals(policyId, other.policyId) && + Objects.equals(roleId, other.roleId) && + Objects.equals(roleName, other.roleName); } - /** - * This method sets the value to the member attribute policyId . - * You cannot set null to the attribute. + /* + * (non-Javadoc) * - * @param policyId - * Value to set member attribute policyId + * @see java.lang.Object#toString() */ - public void setPolicyId(Long policyId) { - this.policyId = policyId; + @Override + public String toString() { + return "XXPolicyRefRole [" + super.toString() + " id=" + id + ", policyId=" + policyId + ", roleId=" + roleId + ", roleName=" + roleName + "]"; } /** @@ -122,14 +141,13 @@ public Long getPolicyId() { } /** - * This method sets the value to the member attribute roleId . + * This method sets the value to the member attribute policyId . * You cannot set null to the attribute. * - * @param roleId - * Value to set member attribute roleId + * @param policyId Value to set member attribute policyId */ - public void setRoleId(Long roleId) { - this.roleId = roleId; + public void setPolicyId(Long policyId) { + this.policyId = policyId; } /** @@ -142,63 +160,29 @@ public Long getRoleId() { } /** - * This method sets the value to the member attribute roleName . + * This method sets the value to the member attribute roleId . * You cannot set null to the attribute. * - * @param roleName - * Value to set member attribute roleName + * @param roleId Value to set member attribute roleId */ - public void setRoleName(String roleName) { - this.roleName = roleName; + public void setRoleId(Long roleId) { + this.roleId = roleId; } /** * Returns the value for the member attribute roleName - * */ public String getRoleName() { return roleName; } - @Override - public int hashCode() { - return Objects.hash(super.hashCode(), id, policyId, roleId, roleName); - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#equals(java.lang.Object) - */ - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - - if (getClass() != obj.getClass()) { - return false; - } - - XXPolicyRefRole other = (XXPolicyRefRole) obj; - - return super.equals(obj) && - Objects.equals(id, other.id) && - Objects.equals(policyId, other.policyId) && - Objects.equals(roleId, other.roleId) && - Objects.equals(roleName, other.roleName); - } - - /* - * (non-Javadoc) + /** + * This method sets the value to the member attribute roleName . + * You cannot set null to the attribute. * - * @see java.lang.Object#toString() + * @param roleName Value to set member attribute roleName */ - @Override - public String toString() { - return "XXPolicyRefRole [" + super.toString() + " id=" + id + ", policyId=" + policyId + ", roleId=" + roleId - + ", roleName=" + roleName + "]"; + public void setRoleName(String roleName) { + this.roleName = roleName; } - } - diff --git a/security-admin/src/main/java/org/apache/ranger/entity/XXPolicyRefUser.java b/security-admin/src/main/java/org/apache/ranger/entity/XXPolicyRefUser.java index 8897af9017..c7d3d27b8f 100644 --- a/security-admin/src/main/java/org/apache/ranger/entity/XXPolicyRefUser.java +++ b/security-admin/src/main/java/org/apache/ranger/entity/XXPolicyRefUser.java @@ -18,172 +18,166 @@ */ package org.apache.ranger.entity; -import javax.persistence.*; +import javax.persistence.Cacheable; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.SequenceGenerator; +import javax.persistence.Table; + import java.util.Objects; @Entity @Cacheable @Table(name = "x_policy_ref_user") -public class XXPolicyRefUser extends XXDBBase implements - java.io.Serializable { - private static final long serialVersionUID = 1L; - /** - * id of the XXPolicyRefUser - *
    - *
- * - */ - @Id - @SequenceGenerator(name = "x_policy_ref_user_SEQ", sequenceName = "x_policy_ref_user_SEQ", allocationSize = 1) - @GeneratedValue(strategy = GenerationType.AUTO, generator = "x_policy_ref_user_SEQ") - @Column(name = "id") - protected Long id; - - /** - * policyId of the XXPolicyRefUser - *
    - *
- * - */ - @Column(name = "policy_id") - protected Long policyId; - - /** - * userId of the XXPolicyRefUser - *
    - *
- * - */ - @Column(name = "user_id") - protected Long userId; - - /** - * userName of the XXPolicyRefUser - *
    - *
- * - */ - @Column(name = "user_name") - protected String userName; - - /** - * This method sets the value to the member attribute id . You - * cannot set null to the attribute. - * - * @param id - * Value to set member attribute id - */ - public void setId(Long id) { - this.id = id; - } - - /** - * Returns the value for the member attribute id - * - * @return Date - value of member attribute id . - */ - public Long getId() { - return this.id; - } - - /** - * This method sets the value to the member attribute policyId . - * You cannot set null to the attribute. - * - * @param policyId - * Value to set member attribute policyId - */ - public void setPolicyId(Long policyId) { - this.policyId = policyId; - } - - /** - * Returns the value for the member attribute policyId - * - * @return Date - value of member attribute policyId . - */ - public Long getPolicyId() { - return this.policyId; - } - - /** - * This method sets the value to the member attribute userId . - * You cannot set null to the attribute. - * - * @param userId - * Value to set member attribute userId - */ - public void setUserId(Long userId) { - this.userId = userId; - } - - /** - * Returns the value for the member attribute userId - * - * @return Date - value of member attribute userId . - */ - public Long getUserId() { - return userId; - } - - /** - * This method sets the value to the member attribute userName . - * You cannot set null to the attribute. - * - * @param userName - * Value to set member attribute userName - */ - public void setUserName(String userName) { - this.userName = userName; - } - - /** - * Returns the value for the member attribute userName - * - * @return Date - value of member attribute userName . - */ - public String getUserName() { - return userName; - } - - @Override - public int hashCode() { - return Objects.hash(super.hashCode(), id, policyId, userId, userName); - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#equals(java.lang.Object) - */ - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - - if (getClass() != obj.getClass()) { - return false; - } - - XXPolicyRefUser other = (XXPolicyRefUser) obj; - - return super.equals(obj) && - Objects.equals(id, other.id) && - Objects.equals(policyId, other.policyId) && - Objects.equals(userId, other.userId) && - Objects.equals(userName, other.userName); - } - - /* (non-Javadoc) - * @see java.lang.Object#toString() - */ - @Override - public String toString() { - return "XXPolicyRefUser [" + super.toString() + " id=" + id + ", policyId=" + policyId + ", userId=" - + userId + ", userName=" + userName + "]"; - } - - - +public class XXPolicyRefUser extends XXDBBase implements java.io.Serializable { + private static final long serialVersionUID = 1L; + + /** + * id of the XXPolicyRefUser + *
    + *
+ */ + @Id + @SequenceGenerator(name = "x_policy_ref_user_SEQ", sequenceName = "x_policy_ref_user_SEQ", allocationSize = 1) + @GeneratedValue(strategy = GenerationType.AUTO, generator = "x_policy_ref_user_SEQ") + @Column(name = "id") + protected Long id; + + /** + * policyId of the XXPolicyRefUser + *
    + *
+ */ + @Column(name = "policy_id") + protected Long policyId; + + /** + * userId of the XXPolicyRefUser + *
    + *
+ */ + @Column(name = "user_id") + protected Long userId; + + /** + * userName of the XXPolicyRefUser + *
    + *
+ */ + @Column(name = "user_name") + protected String userName; + + /** + * Returns the value for the member attribute id + * + * @return Date - value of member attribute id . + */ + public Long getId() { + return this.id; + } + + /** + * This method sets the value to the member attribute id . You + * cannot set null to the attribute. + * + * @param id Value to set member attribute id + */ + public void setId(Long id) { + this.id = id; + } + + @Override + public int hashCode() { + return Objects.hash(super.hashCode(), id, policyId, userId, userName); + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#equals(java.lang.Object) + */ + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } else if (!super.equals(obj)) { + return false; + } + + XXPolicyRefUser other = (XXPolicyRefUser) obj; + + return super.equals(obj) && + Objects.equals(id, other.id) && + Objects.equals(policyId, other.policyId) && + Objects.equals(userId, other.userId) && + Objects.equals(userName, other.userName); + } + + /* (non-Javadoc) + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + return "XXPolicyRefUser [" + super.toString() + " id=" + id + ", policyId=" + policyId + ", userId=" + userId + ", userName=" + userName + "]"; + } + + /** + * Returns the value for the member attribute policyId + * + * @return Date - value of member attribute policyId . + */ + public Long getPolicyId() { + return this.policyId; + } + + /** + * This method sets the value to the member attribute policyId . + * You cannot set null to the attribute. + * + * @param policyId Value to set member attribute policyId + */ + public void setPolicyId(Long policyId) { + this.policyId = policyId; + } + + /** + * Returns the value for the member attribute userId + * + * @return Date - value of member attribute userId . + */ + public Long getUserId() { + return userId; + } + + /** + * This method sets the value to the member attribute userId . + * You cannot set null to the attribute. + * + * @param userId Value to set member attribute userId + */ + public void setUserId(Long userId) { + this.userId = userId; + } + + /** + * Returns the value for the member attribute userName + * + * @return Date - value of member attribute userName . + */ + public String getUserName() { + return userName; + } + + /** + * This method sets the value to the member attribute userName . + * You cannot set null to the attribute. + * + * @param userName Value to set member attribute userName + */ + public void setUserName(String userName) { + this.userName = userName; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/entity/XXPolicyResource.java b/security-admin/src/main/java/org/apache/ranger/entity/XXPolicyResource.java index d21e153695..bc756c4526 100644 --- a/security-admin/src/main/java/org/apache/ranger/entity/XXPolicyResource.java +++ b/security-admin/src/main/java/org/apache/ranger/entity/XXPolicyResource.java @@ -18,222 +18,198 @@ */ package org.apache.ranger.entity; -import javax.persistence.*; +import javax.persistence.Cacheable; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.SequenceGenerator; +import javax.persistence.Table; + +import java.util.Objects; @Entity @Cacheable @Table(name = "x_policy_resource") public class XXPolicyResource extends XXDBBase implements java.io.Serializable { - private static final long serialVersionUID = 1L; - /** - * id of the XXPolicyResource - *
    - *
- * - */ - @Id - @SequenceGenerator(name = "x_policy_resource_SEQ", sequenceName = "x_policy_resource_SEQ", allocationSize = 1) - @GeneratedValue(strategy = GenerationType.AUTO, generator = "x_policy_resource_SEQ") - @Column(name = "id") - protected Long id; - - /** - * policyId of the XXPolicyResource - *
    - *
- * - */ - @Column(name = "policy_id") - protected Long policyId; - - /** - * resDefId of the XXPolicyResource - *
    - *
- * - */ - @Column(name = "res_def_id") - protected Long resDefId; - - /** - * isExcludes of the XXPolicyResource - *
    - *
- * - */ - @Column(name = "is_excludes") - protected boolean isExcludes; - - /** - * isRecursive of the XXPolicyResource - *
    - *
- * - */ - @Column(name = "is_recursive") - protected boolean isRecursive; - - /** - * This method sets the value to the member attribute id . You - * cannot set null to the attribute. - * - * @param id - * Value to set member attribute id - */ - public void setId(Long id) { - this.id = id; - } - - /** - * Returns the value for the member attribute id - * - * @return Date - value of member attribute id . - */ - public Long getId() { - return this.id; - } - - /** - * This method sets the value to the member attribute policyId . You - * cannot set null to the attribute. - * - * @param policyId - * Value to set member attribute policyId - */ - public void setPolicyId(Long policyId) { - this.policyId = policyId; - } - - /** - * Returns the value for the member attribute policyId - * - * @return Date - value of member attribute policyId . - */ - public Long getPolicyid() { - return this.policyId; - } - - /** - * This method sets the value to the member attribute resDefId . You - * cannot set null to the attribute. - * - * @param resDefId - * Value to set member attribute resDefId - */ - public void setResDefId(Long resDefId) { - this.resDefId = resDefId; - } - - /** - * Returns the value for the member attribute resDefId - * - * @return Date - value of member attribute resDefId . - */ - public Long getResdefid() { - return this.resDefId; - } - - /** - * This method sets the value to the member attribute isExcludes . - * You cannot set null to the attribute. - * - * @param isExcludes - * Value to set member attribute isExcludes - */ - public void setIsExcludes(boolean isExcludes) { - this.isExcludes = isExcludes; - } - - /** - * Returns the value for the member attribute isExcludes - * - * @return Date - value of member attribute isExcludes . - */ - public boolean getIsexcludes() { - return this.isExcludes; - } - - /** - * This method sets the value to the member attribute isRecursive . - * You cannot set null to the attribute. - * - * @param isRecursive - * Value to set member attribute isRecursive - */ - public void setIsRecursive(boolean isRecursive) { - this.isRecursive = isRecursive; - } - - /** - * Returns the value for the member attribute isRecursive - * - * @return Date - value of member attribute isRecursive . - */ - public boolean getIsrecursive() { - return this.isRecursive; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#equals(java.lang.Object) - */ - @Override - public boolean equals(Object obj) { - if (!super.equals(obj)) { - return false; - } - if (this == obj) { - return true; - } - if (!super.equals(obj)) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - XXPolicyResource other = (XXPolicyResource) obj; - if (id == null) { - if (other.id != null) { - return false; - } - } else if (!id.equals(other.id)) { - return false; - } - if (isExcludes != other.isExcludes) { - return false; - } - if (isRecursive != other.isRecursive) { - return false; - } - if (policyId == null) { - if (other.policyId != null) { - return false; - } - } else if (!policyId.equals(other.policyId)) { - return false; - } - if (resDefId == null) { - if (other.resDefId != null) { - return false; - } - } else if (!resDefId.equals(other.resDefId)) { - return false; - } - return true; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#toString() - */ - @Override - public String toString() { - return "XXPolicyResource [" + super.toString() + " id=" + id - + ", policyId=" + policyId + ", resDefId=" + resDefId - + ", isExcludes=" + isExcludes + ", isRecursive=" + isRecursive - + "]"; - } - + private static final long serialVersionUID = 1L; + + /** + * id of the XXPolicyResource + *
    + *
+ */ + @Id + @SequenceGenerator(name = "x_policy_resource_SEQ", sequenceName = "x_policy_resource_SEQ", allocationSize = 1) + @GeneratedValue(strategy = GenerationType.AUTO, generator = "x_policy_resource_SEQ") + @Column(name = "id") + protected Long id; + + /** + * policyId of the XXPolicyResource + *
    + *
+ */ + @Column(name = "policy_id") + protected Long policyId; + + /** + * resDefId of the XXPolicyResource + *
    + *
+ */ + @Column(name = "res_def_id") + protected Long resDefId; + + /** + * isExcludes of the XXPolicyResource + *
    + *
+ */ + @Column(name = "is_excludes") + protected boolean isExcludes; + + /** + * isRecursive of the XXPolicyResource + *
    + *
+ */ + @Column(name = "is_recursive") + protected boolean isRecursive; + + /** + * Returns the value for the member attribute id + * + * @return Date - value of member attribute id . + */ + public Long getId() { + return this.id; + } + + /** + * This method sets the value to the member attribute id . You + * cannot set null to the attribute. + * + * @param id Value to set member attribute id + */ + public void setId(Long id) { + this.id = id; + } + + @Override + public int hashCode() { + return super.hashCode(); + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#equals(java.lang.Object) + */ + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } else if (!super.equals(obj)) { + return false; + } + + XXPolicyResource other = (XXPolicyResource) obj; + + return Objects.equals(id, other.id) && + Objects.equals(isExcludes, other.isExcludes) && + Objects.equals(isRecursive, other.isRecursive) && + Objects.equals(policyId, other.policyId) && + Objects.equals(resDefId, other.resDefId); + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + return "XXPolicyResource [" + super.toString() + " id=" + id + + ", policyId=" + policyId + ", resDefId=" + resDefId + + ", isExcludes=" + isExcludes + ", isRecursive=" + isRecursive + + "]"; + } + + /** + * This method sets the value to the member attribute policyId . You + * cannot set null to the attribute. + * + * @param policyId Value to set member attribute policyId + */ + public void setPolicyId(Long policyId) { + this.policyId = policyId; + } + + /** + * Returns the value for the member attribute policyId + * + * @return Date - value of member attribute policyId . + */ + public Long getPolicyid() { + return this.policyId; + } + + /** + * This method sets the value to the member attribute resDefId . You + * cannot set null to the attribute. + * + * @param resDefId Value to set member attribute resDefId + */ + public void setResDefId(Long resDefId) { + this.resDefId = resDefId; + } + + /** + * Returns the value for the member attribute resDefId + * + * @return Date - value of member attribute resDefId . + */ + public Long getResdefid() { + return this.resDefId; + } + + /** + * This method sets the value to the member attribute isExcludes . + * You cannot set null to the attribute. + * + * @param isExcludes Value to set member attribute isExcludes + */ + public void setIsExcludes(boolean isExcludes) { + this.isExcludes = isExcludes; + } + + /** + * Returns the value for the member attribute isExcludes + * + * @return Date - value of member attribute isExcludes . + */ + public boolean getIsexcludes() { + return this.isExcludes; + } + + /** + * This method sets the value to the member attribute isRecursive . + * You cannot set null to the attribute. + * + * @param isRecursive Value to set member attribute isRecursive + */ + public void setIsRecursive(boolean isRecursive) { + this.isRecursive = isRecursive; + } + + /** + * Returns the value for the member attribute isRecursive + * + * @return Date - value of member attribute isRecursive . + */ + public boolean getIsrecursive() { + return this.isRecursive; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/entity/XXPolicyResourceMap.java b/security-admin/src/main/java/org/apache/ranger/entity/XXPolicyResourceMap.java index 393fb635fd..9d1e23a070 100644 --- a/security-admin/src/main/java/org/apache/ranger/entity/XXPolicyResourceMap.java +++ b/security-admin/src/main/java/org/apache/ranger/entity/XXPolicyResourceMap.java @@ -18,194 +18,169 @@ */ package org.apache.ranger.entity; -import javax.persistence.*; +import javax.persistence.Cacheable; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.SequenceGenerator; +import javax.persistence.Table; + +import java.util.Objects; @Entity @Cacheable @Table(name = "x_policy_resource_map") -public class XXPolicyResourceMap extends XXDBBase implements - java.io.Serializable { - private static final long serialVersionUID = 1L; - /** - * id of the XXPolicyResourceMap - *
    - *
- * - */ - @Id - @SequenceGenerator(name = "x_policy_resource_map_SEQ", sequenceName = "x_policy_resource_map_SEQ", allocationSize = 1) - @GeneratedValue(strategy = GenerationType.AUTO, generator = "x_policy_resource_map_SEQ") - @Column(name = "id") - protected Long id; - - /** - * resourceId of the XXPolicyResourceMap - *
    - *
- * - */ - @Column(name = "resource_id") - protected Long resourceId; - - /** - * value of the XXPolicyResourceMap - *
    - *
- * - */ - @Column(name = "value") - protected String value; - - /** - * order of the XXPolicyResourceMap - *
    - *
- * - */ - @Column(name = "sort_order") - protected Integer order; - - /** - * This method sets the value to the member attribute id . You - * cannot set null to the attribute. - * - * @param id - * Value to set member attribute id - */ - public void setId(Long id) { - this.id = id; - } - - /** - * Returns the value for the member attribute id - * - * @return Date - value of member attribute id . - */ - public Long getId() { - return this.id; - } - - /** - * This method sets the value to the member attribute resourceId . - * You cannot set null to the attribute. - * - * @param resourceId - * Value to set member attribute resourceId - */ - public void setResourceId(Long resourceId) { - this.resourceId = resourceId; - } - - /** - * Returns the value for the member attribute resourceId - * - * @return Date - value of member attribute resourceId . - */ - public Long getResourceid() { - return this.resourceId; - } - - /** - * This method sets the value to the member attribute value . You - * cannot set null to the attribute. - * - * @param value - * Value to set member attribute value - */ - public void setValue(String value) { - this.value = value; - } - - /** - * Returns the value for the member attribute value - * - * @return Date - value of member attribute value . - */ - public String getValue() { - return this.value; - } - - /** - * This method sets the value to the member attribute order . You - * cannot set null to the attribute. - * - * @param order - * Value to set member attribute order - */ - public void setOrder(Integer order) { - this.order = order; - } - - /** - * Returns the value for the member attribute order - * - * @return Date - value of member attribute order . - */ - public Integer getOrder() { - return this.order; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#equals(java.lang.Object) - */ - @Override - public boolean equals(Object obj) { - if (!super.equals(obj)) { - return false; - } - if (this == obj) { - return true; - } - if (!super.equals(obj)) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - XXPolicyResourceMap other = (XXPolicyResourceMap) obj; - if (id == null) { - if (other.id != null) { - return false; - } - } else if (!id.equals(other.id)) { - return false; - } - if (order == null) { - if (other.order != null) { - return false; - } - } else if (!order.equals(other.order)) { - return false; - } - if (resourceId == null) { - if (other.resourceId != null) { - return false; - } - } else if (!resourceId.equals(other.resourceId)) { - return false; - } - if (value == null) { - if (other.value != null) { - return false; - } - } else if (!value.equals(other.value)) { - return false; - } - return true; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#toString() - */ - @Override - public String toString() { - return "XXPolicyResourceMap [" + super.toString() + " id=" + id - + ", resourceId=" + resourceId + ", value=" + value - + ", order=" + order + "]"; - } - +public class XXPolicyResourceMap extends XXDBBase implements java.io.Serializable { + private static final long serialVersionUID = 1L; + + /** + * id of the XXPolicyResourceMap + *
    + *
+ */ + @Id + @SequenceGenerator(name = "x_policy_resource_map_SEQ", sequenceName = "x_policy_resource_map_SEQ", allocationSize = 1) + @GeneratedValue(strategy = GenerationType.AUTO, generator = "x_policy_resource_map_SEQ") + @Column(name = "id") + protected Long id; + + /** + * resourceId of the XXPolicyResourceMap + *
    + *
+ */ + @Column(name = "resource_id") + protected Long resourceId; + + /** + * value of the XXPolicyResourceMap + *
    + *
+ */ + @Column(name = "value") + protected String value; + + /** + * order of the XXPolicyResourceMap + *
    + *
+ */ + @Column(name = "sort_order") + protected Integer order; + + /** + * Returns the value for the member attribute id + * + * @return Date - value of member attribute id . + */ + public Long getId() { + return this.id; + } + + /** + * This method sets the value to the member attribute id . You + * cannot set null to the attribute. + * + * @param id Value to set member attribute id + */ + public void setId(Long id) { + this.id = id; + } + + @Override + public int hashCode() { + return super.hashCode(); + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#equals(java.lang.Object) + */ + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } else if (!super.equals(obj)) { + return false; + } + + XXPolicyResourceMap other = (XXPolicyResourceMap) obj; + + return Objects.equals(id, other.id) && + Objects.equals(order, other.order) && + Objects.equals(resourceId, other.resourceId) && + Objects.equals(value, other.value); + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + return "XXPolicyResourceMap [" + super.toString() + " id=" + id + + ", resourceId=" + resourceId + ", value=" + value + + ", order=" + order + "]"; + } + + /** + * This method sets the value to the member attribute resourceId . + * You cannot set null to the attribute. + * + * @param resourceId Value to set member attribute resourceId + */ + public void setResourceId(Long resourceId) { + this.resourceId = resourceId; + } + + /** + * Returns the value for the member attribute resourceId + * + * @return Date - value of member attribute resourceId . + */ + public Long getResourceid() { + return this.resourceId; + } + + /** + * Returns the value for the member attribute value + * + * @return Date - value of member attribute value . + */ + public String getValue() { + return this.value; + } + + /** + * This method sets the value to the member attribute value . You + * cannot set null to the attribute. + * + * @param value Value to set member attribute value + */ + public void setValue(String value) { + this.value = value; + } + + /** + * Returns the value for the member attribute order + * + * @return Date - value of member attribute order . + */ + public Integer getOrder() { + return this.order; + } + + /** + * This method sets the value to the member attribute order . You + * cannot set null to the attribute. + * + * @param order Value to set member attribute order + */ + public void setOrder(Integer order) { + this.order = order; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/entity/XXPolicyWithAssignedId.java b/security-admin/src/main/java/org/apache/ranger/entity/XXPolicyWithAssignedId.java index 7a1741a0f5..790068322e 100644 --- a/security-admin/src/main/java/org/apache/ranger/entity/XXPolicyWithAssignedId.java +++ b/security-admin/src/main/java/org/apache/ranger/entity/XXPolicyWithAssignedId.java @@ -23,50 +23,51 @@ import javax.persistence.Id; import javax.persistence.Table; +import java.util.Objects; + @Entity @Cacheable @Table(name = "x_policy") public class XXPolicyWithAssignedId extends XXPolicyBase { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; + + /** + * id of the XXPolicy + */ + @Id + @Column(name = "id") + protected Long id; + + @Override + public Long getId() { + return id; + } - /** - * id of the XXPolicy - * - */ - @Id - @Column(name = "id") - protected Long id; + @Override + public void setId(Long id) { + this.id = id; + } - @Override - public void setId(Long id) { - this.id = id; - } + @Override + public int hashCode() { + return super.hashCode(); + } - @Override - public Long getId() { - return id; - } + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } else if (!super.equals(obj)) { + return false; + } - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (!super.equals(obj)) - return false; - if (getClass() != obj.getClass()) - return false; - XXPolicyWithAssignedId other = (XXPolicyWithAssignedId) obj; - if (id == null) { - if (other.id != null) - return false; - } else if (!id.equals(other.id)) - return false; - return true; - } + XXPolicyWithAssignedId other = (XXPolicyWithAssignedId) obj; - @Override - public String toString() { - return "XXPolicyWithAssignedId [id=" + id + "]"; - } + return Objects.equals(id, other.id); + } + @Override + public String toString() { + return "XXPolicyWithAssignedId [id=" + id + "]"; + } } 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 index 881b181cd4..2c4ee927e8 100644 --- a/security-admin/src/main/java/org/apache/ranger/entity/XXPortalUser.java +++ b/security-admin/src/main/java/org/apache/ranger/entity/XXPortalUser.java @@ -17,13 +17,16 @@ * under the License. */ - package org.apache.ranger.entity; +package org.apache.ranger.entity; /** * User details - * */ +import org.apache.ranger.common.AppConstants; +import org.apache.ranger.common.DateUtil; +import org.apache.ranger.common.RangerConstants; + import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; @@ -34,429 +37,435 @@ import javax.persistence.Temporal; import javax.persistence.TemporalType; -import org.apache.ranger.common.AppConstants; -import org.apache.ranger.common.DateUtil; -import org.apache.ranger.common.RangerConstants; - import java.util.Date; - +import java.util.Objects; @Entity -@Table(name="x_portal_user") +@Table(name = "x_portal_user") 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 - *
    - *
  • The maximum length for this attribute is 1022. - *
- * - */ - @Column(name="FIRST_NAME" , length=1022) - protected String firstName; - - /** - * Last name of the user - *
    - *
  • The maximum length for this attribute is 1022. - *
- * - */ - @Column(name="LAST_NAME" , length=1022) - protected String lastName; - - /** - * Public screen name for the user - *
    - *
  • The maximum length for this attribute is 2048. - *
- * - */ - @Column(name="PUB_SCR_NAME" , length=2048) - protected String publicScreenName; - - /** - * Login ID of the user - *
    - *
  • The maximum length for this attribute is 767. - *
- * - */ - @Column(name="LOGIN_ID" , unique=true , length=767) - protected String loginId; - - /** - *
    - *
  • The maximum length for this attribute is 512. - *
- * - */ - @Column(name="PASSWORD" , nullable=false , length=512) - protected String password; - - /** - * Email address of the user - *
    - *
  • The maximum length for this attribute is 512. - *
- * - */ - @Column(name="EMAIL" , unique=true , length=512) - protected String emailAddress; - - /** - * Status of the user - *
    - *
  • This attribute is of type enum CommonEnums::ActivationStatus - *
- * - */ - @Column(name="STATUS" , nullable=false ) - protected int status = RangerConstants.ACT_STATUS_DISABLED; - - /** - * Source of the user - *
    - *
  • This attribute is of type enum CommonEnums::UserSource - *
- * - */ - @Column(name="USER_SRC" , nullable=false ) - protected int userSource = RangerConstants.USER_APP; - - /** - * Note - *
    - *
  • The maximum length for this attribute is 4000. - *
- * - */ - @Column(name="NOTES" , length=4000) - protected String notes; - - /** - * Additional store attributes. - *
    - *
- * - */ - @Column(name="OTHER_ATTRIBUTES") - protected String otherAttributes; - - /** - * Sync Source Attribute. - *
    - *
- * - */ - @Column(name="SYNC_SOURCE") - protected String syncSource; - - @Column(name="OLD_PASSWORDS") - protected String oldPasswords; - - @Temporal(TemporalType.TIMESTAMP) - @Column(name="PASSWORD_UPDATED_TIME") - protected Date passwordUpdatedTime = DateUtil.getUTCDate(); - - /** - * Default constructor. This will set all the attributes to default value. - */ - public XXPortalUser ( ) { - status = RangerConstants.ACT_STATUS_DISABLED; - userSource = RangerConstants.USER_APP; - } - - @Override - public int getMyClassType( ) { - return AppConstants.CLASS_TYPE_USER_PROFILE; - } - - /** - * This method sets the value to the member attribute firstName. - * You cannot set null to the attribute. - * @param firstName Value to set member attribute firstName - */ - public void setFirstName( String firstName ) { - this.firstName = firstName; - } - - /** - * Returns the value for the member attribute firstName - * @return String - value of member attribute firstName. - */ - public String getFirstName( ) { - return this.firstName; - } - - /** - * This method sets the value to the member attribute lastName. - * You cannot set null to the attribute. - * @param lastName Value to set member attribute lastName - */ - public void setLastName( String lastName ) { - this.lastName = lastName; - } - - /** - * Returns the value for the member attribute lastName - * @return String - value of member attribute lastName. - */ - public String getLastName( ) { - return this.lastName; - } - - /** - * This method sets the value to the member attribute publicScreenName. - * You cannot set null to the attribute. - * @param publicScreenName Value to set member attribute publicScreenName - */ - public void setPublicScreenName( String publicScreenName ) { - this.publicScreenName = publicScreenName; - } - - /** - * Returns the value for the member attribute publicScreenName - * @return String - value of member attribute publicScreenName. - */ - public String getPublicScreenName( ) { - return this.publicScreenName; - } - - /** - * This method sets the value to the member attribute loginId. - * You cannot set null to the attribute. - * @param loginId Value to set member attribute loginId - */ - public void setLoginId( String loginId ) { - this.loginId = loginId; - } - - /** - * Returns the value for the member attribute loginId - * @return String - value of member attribute loginId. - */ - public String getLoginId( ) { - return this.loginId; - } - - /** - * This method sets the value to the member attribute password. - * You cannot set null to the attribute. - * @param password Value to set member attribute password - */ - public void setPassword( String password ) { - this.password = password; - } - - /** - * Returns the value for the member attribute password - * @return String - value of member attribute password. - */ - public String getPassword( ) { - return this.password; - } - - /** - * This method sets the value to the member attribute emailAddress. - * You cannot set null to the attribute. - * @param emailAddress Value to set member attribute emailAddress - */ - public void setEmailAddress( String emailAddress ) { - this.emailAddress = emailAddress; - } - - /** - * Returns the value for the member attribute emailAddress - * @return String - value of member attribute emailAddress. - */ - public String getEmailAddress( ) { - return this.emailAddress; - } - - /** - * This method sets the value to the member attribute status. - * You cannot set null to the attribute. - * @param status Value to set member attribute status - */ - public void setStatus( int status ) { - this.status = status; - } - - /** - * Returns the value for the member attribute status - * @return int - value of member attribute status. - */ - public int getStatus( ) { - return this.status; - } - - /** - * This method sets the value to the member attribute userSource. - * You cannot set null to the attribute. - * @param userSource Value to set member attribute userSource - */ - public void setUserSource( int userSource ) { - this.userSource = userSource; - } - - /** - * Returns the value for the member attribute userSource - * @return int - value of member attribute userSource. - */ - public int getUserSource( ) { - return this.userSource; - } - - /** - * This method sets the value to the member attribute notes. - * You cannot set null to the attribute. - * @param notes Value to set member attribute notes - */ - public void setNotes( String notes ) { - this.notes = notes; - } - - /** - * Returns the value for the member attribute notes - * @return String - value of member attribute notes. - */ - public String getNotes( ) { - return this.notes; - } - - /** - * This method sets JSON {@link String} representation of additional store attributes. - * This method accepts null values. - * @param otherAttributes - */ - public void setOtherAttributes(String otherAttributes) { - this.otherAttributes = otherAttributes; - } - - /** - * @return JSON {@link String} representation of additional store attributes if available, - * null otherwise. - */ - public String getOtherAttributes() { - return otherAttributes; - } - - /** - * This method sets JSON {@link String} representation of sync source attribute. - * This method accepts null values. - * @param syncSource - */ - public void setSyncSource(String syncSource) { - this.syncSource = syncSource; - } - - /** - * @return JSON {@link String} representation of sync source attribute if available, - * null otherwise. - */ - public String getSyncSource() { return syncSource; } - - public String getOldPasswords() { - return oldPasswords; - } - - public void setOldPasswords(String oldPasswords) { - this.oldPasswords = oldPasswords; - } - - public Date getPasswordUpdatedTime() { - return passwordUpdatedTime; - } - - public void setPasswordUpdatedTime(Date passwordUpdatedTime) { - this.passwordUpdatedTime = passwordUpdatedTime; - } - - /** - * 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 += "emailAddress={" + emailAddress + "} "; - str += "status={" + status + "} "; - str += "userSource={" + userSource + "} "; - str += "notes={" + notes + "} "; - str += "otherAttributes={" + otherAttributes + "} "; - str += "syncSource={" + syncSource + "} "; - str += "passwordUpdatedTime={" + passwordUpdatedTime + "} "; - 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( "status".equals(fieldName) ) { - return "CommonEnums.ActivationStatus"; - } - if( "userSource".equals(fieldName) ) { - return "CommonEnums.UserSource"; - } - //Later TODO - //return super.getEnumName(fieldName); - return null; - } - + 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; + + /** + * First name of the user + *
    + *
  • The maximum length for this attribute is 1022. + *
+ */ + @Column(name = "FIRST_NAME", length = 1022) + protected String firstName; + + /** + * Last name of the user + *
    + *
  • The maximum length for this attribute is 1022. + *
+ */ + @Column(name = "LAST_NAME", length = 1022) + protected String lastName; + + /** + * Public screen name for the user + *
    + *
  • The maximum length for this attribute is 2048. + *
+ */ + @Column(name = "PUB_SCR_NAME", length = 2048) + protected String publicScreenName; + + /** + * Login ID of the user + *
    + *
  • The maximum length for this attribute is 767. + *
+ */ + @Column(name = "LOGIN_ID", unique = true, length = 767) + protected String loginId; + + /** + *
    + *
  • The maximum length for this attribute is 512. + *
+ */ + @Column(name = "PASSWORD", nullable = false, length = 512) + protected String password; + + /** + * Email address of the user + *
    + *
  • The maximum length for this attribute is 512. + *
+ */ + @Column(name = "EMAIL", unique = true, length = 512) + protected String emailAddress; + + /** + * Status of the user + *
    + *
  • This attribute is of type enum CommonEnums::ActivationStatus + *
+ */ + @Column(name = "STATUS", nullable = false) + protected int status = RangerConstants.ACT_STATUS_DISABLED; + + /** + * Source of the user + *
    + *
  • This attribute is of type enum CommonEnums::UserSource + *
+ */ + @Column(name = "USER_SRC", nullable = false) + protected int userSource = RangerConstants.USER_APP; + + /** + * Note + *
    + *
  • The maximum length for this attribute is 4000. + *
+ */ + @Column(name = "NOTES", length = 4000) + protected String notes; + + /** + * Additional store attributes. + *
    + *
+ */ + @Column(name = "OTHER_ATTRIBUTES") + protected String otherAttributes; + + /** + * Sync Source Attribute. + *
    + *
+ */ + @Column(name = "SYNC_SOURCE") + protected String syncSource; + + @Column(name = "OLD_PASSWORDS") + protected String oldPasswords; + + @Temporal(TemporalType.TIMESTAMP) + @Column(name = "PASSWORD_UPDATED_TIME") + protected Date passwordUpdatedTime = DateUtil.getUTCDate(); + + /** + * Default constructor. This will set all the attributes to default value. + */ + public XXPortalUser() { + status = RangerConstants.ACT_STATUS_DISABLED; + userSource = RangerConstants.USER_APP; + } + + public static String getEnumName(String fieldName) { + if ("status".equals(fieldName)) { + return "CommonEnums.ActivationStatus"; + } + if ("userSource".equals(fieldName)) { + return "CommonEnums.UserSource"; + } + //Later TODO + //return super.getEnumName(fieldName); + return null; + } + + @Override + public int getMyClassType() { + return AppConstants.CLASS_TYPE_USER_PROFILE; + } + + @Override + public Long getId() { + // TODO Auto-generated method stub + return id; + } + + @Override + public void setId(Long id) { + // TODO Auto-generated method stub + this.id = id; + } + + @Override + public int hashCode() { + return super.hashCode(); + } + + /** + * Checks for all attributes except referenced db objects + * + * @return true if all attributes match + */ + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } else if (!super.equals(obj)) { + return false; + } + + XXPortalUser other = (XXPortalUser) obj; + + return Objects.equals(firstName, other.firstName) && + Objects.equals(lastName, other.lastName) && + Objects.equals(publicScreenName, other.publicScreenName) && + Objects.equals(loginId, other.loginId) && + Objects.equals(password, other.password) && + Objects.equals(emailAddress, other.emailAddress) && + Objects.equals(status, other.status) && + Objects.equals(userSource, other.userSource) && + Objects.equals(notes, other.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 += "emailAddress={" + emailAddress + "} "; + str += "status={" + status + "} "; + str += "userSource={" + userSource + "} "; + str += "notes={" + notes + "} "; + str += "otherAttributes={" + otherAttributes + "} "; + str += "syncSource={" + syncSource + "} "; + str += "passwordUpdatedTime={" + passwordUpdatedTime + "} "; + str += "}"; + return str; + } + + /** + * Returns the value for the member attribute firstName + * + * @return String - value of member attribute firstName. + */ + public String getFirstName() { + return this.firstName; + } + + /** + * This method sets the value to the member attribute firstName. + * You cannot set null to the attribute. + * + * @param firstName Value to set member attribute firstName + */ + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + /** + * Returns the value for the member attribute lastName + * + * @return String - value of member attribute lastName. + */ + public String getLastName() { + return this.lastName; + } + + /** + * This method sets the value to the member attribute lastName. + * You cannot set null to the attribute. + * + * @param lastName Value to set member attribute lastName + */ + public void setLastName(String lastName) { + this.lastName = lastName; + } + + /** + * Returns the value for the member attribute publicScreenName + * + * @return String - value of member attribute publicScreenName. + */ + public String getPublicScreenName() { + return this.publicScreenName; + } + + /** + * This method sets the value to the member attribute publicScreenName. + * You cannot set null to the attribute. + * + * @param publicScreenName Value to set member attribute publicScreenName + */ + public void setPublicScreenName(String publicScreenName) { + this.publicScreenName = publicScreenName; + } + + /** + * Returns the value for the member attribute loginId + * + * @return String - value of member attribute loginId. + */ + public String getLoginId() { + return this.loginId; + } + + /** + * This method sets the value to the member attribute loginId. + * You cannot set null to the attribute. + * + * @param loginId Value to set member attribute loginId + */ + public void setLoginId(String loginId) { + this.loginId = loginId; + } + + /** + * Returns the value for the member attribute password + * + * @return String - value of member attribute password. + */ + public String getPassword() { + return this.password; + } + + /** + * This method sets the value to the member attribute password. + * You cannot set null to the attribute. + * + * @param password Value to set member attribute password + */ + public void setPassword(String password) { + this.password = password; + } + + /** + * Returns the value for the member attribute emailAddress + * + * @return String - value of member attribute emailAddress. + */ + public String getEmailAddress() { + return this.emailAddress; + } + + /** + * This method sets the value to the member attribute emailAddress. + * You cannot set null to the attribute. + * + * @param emailAddress Value to set member attribute emailAddress + */ + public void setEmailAddress(String emailAddress) { + this.emailAddress = emailAddress; + } + + /** + * Returns the value for the member attribute status + * + * @return int - value of member attribute status. + */ + public int getStatus() { + return this.status; + } + + /** + * This method sets the value to the member attribute status. + * You cannot set null to the attribute. + * + * @param status Value to set member attribute status + */ + public void setStatus(int status) { + this.status = status; + } + + /** + * Returns the value for the member attribute userSource + * + * @return int - value of member attribute userSource. + */ + public int getUserSource() { + return this.userSource; + } + + /** + * This method sets the value to the member attribute userSource. + * You cannot set null to the attribute. + * + * @param userSource Value to set member attribute userSource + */ + public void setUserSource(int userSource) { + this.userSource = userSource; + } + + /** + * Returns the value for the member attribute notes + * + * @return String - value of member attribute notes. + */ + public String getNotes() { + return this.notes; + } + + /** + * This method sets the value to the member attribute notes. + * You cannot set null to the attribute. + * + * @param notes Value to set member attribute notes + */ + public void setNotes(String notes) { + this.notes = notes; + } + + /** + * @return JSON {@link String} representation of additional store attributes if available, + * null otherwise. + */ + public String getOtherAttributes() { + return otherAttributes; + } + + /** + * This method sets JSON {@link String} representation of additional store attributes. + * This method accepts null values. + * + * @param otherAttributes + */ + public void setOtherAttributes(String otherAttributes) { + this.otherAttributes = otherAttributes; + } + + /** + * @return JSON {@link String} representation of sync source attribute if available, + * null otherwise. + */ + public String getSyncSource() { + return syncSource; + } + + /** + * This method sets JSON {@link String} representation of sync source attribute. + * This method accepts null values. + * + * @param syncSource + */ + public void setSyncSource(String syncSource) { + this.syncSource = syncSource; + } + + public String getOldPasswords() { + return oldPasswords; + } + + public void setOldPasswords(String oldPasswords) { + this.oldPasswords = oldPasswords; + } + + public Date getPasswordUpdatedTime() { + return passwordUpdatedTime; + } + + public void setPasswordUpdatedTime(Date passwordUpdatedTime) { + this.passwordUpdatedTime = passwordUpdatedTime; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/entity/XXPortalUserRole.java b/security-admin/src/main/java/org/apache/ranger/entity/XXPortalUserRole.java index 8469e61965..3b6a7ff837 100644 --- a/security-admin/src/main/java/org/apache/ranger/entity/XXPortalUserRole.java +++ b/security-admin/src/main/java/org/apache/ranger/entity/XXPortalUserRole.java @@ -17,13 +17,14 @@ * under the License. */ - package org.apache.ranger.entity; +package org.apache.ranger.entity; /** * Role of the user - * */ +import org.apache.ranger.common.RangerConstants; + import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; @@ -32,158 +33,166 @@ import javax.persistence.SequenceGenerator; import javax.persistence.Table; -import org.apache.ranger.common.RangerConstants; - +import java.util.Objects; @Entity -@Table(name="x_portal_user_role") +@Table(name = "x_portal_user_role") 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 - *
    - *
- * - */ - @Column(name="USER_ID" , nullable=false ) - protected Long userId; - - - /** - * Role of the user - *
    - *
  • The maximum length for this attribute is 128. - *
- * - */ - @Column(name="USER_ROLE" , length=128) - protected String userRole; - - /** - * Status - *
    - *
  • This attribute is of type enum CommonEnums::ActiveStatus - *
- * - */ - @Column(name="STATUS" , nullable=false ) - protected int status = RangerConstants.STATUS_DISABLED; - - /** - * Default constructor. This will set all the attributes to default value. - */ - public XXPortalUserRole ( ) { - status = RangerConstants.STATUS_DISABLED; - } - - /** - * This method sets the value to the member attribute userId. - * You cannot set null to the attribute. - * @param userId Value to set member attribute userId - */ - public void setUserId( Long userId ) { - this.userId = userId; - } - - /** - * Returns the value for the member attribute userId - * @return Long - value of member attribute userId. - */ - public Long getUserId( ) { - return this.userId; - } - - - /** - * This method sets the value to the member attribute userRole. - * You cannot set null to the attribute. - * @param userRole Value to set member attribute userRole - */ - public void setUserRole( String userRole ) { - this.userRole = userRole; - } - - /** - * Returns the value for the member attribute userRole - * @return String - value of member attribute userRole. - */ - public String getUserRole( ) { - return this.userRole; - } - - /** - * This method sets the value to the member attribute status. - * You cannot set null to the attribute. - * @param status Value to set member attribute status - */ - public void setStatus( int status ) { - this.status = status; - } - - /** - * Returns the value for the member attribute status - * @return int - value of member attribute status. - */ - 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( "status".equals(fieldName) ) { - return "CommonEnums.ActiveStatus"; - } - //Later TODO - //return super.getEnumName(fieldName); - return null; - } - + 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; + + /** + * Id of the user + *
    + *
+ */ + @Column(name = "USER_ID", nullable = false) + protected Long userId; + + /** + * Role of the user + *
    + *
  • The maximum length for this attribute is 128. + *
+ */ + @Column(name = "USER_ROLE", length = 128) + protected String userRole; + + /** + * Status + *
    + *
  • This attribute is of type enum CommonEnums::ActiveStatus + *
+ */ + @Column(name = "STATUS", nullable = false) + protected int status = RangerConstants.STATUS_DISABLED; + + /** + * Default constructor. This will set all the attributes to default value. + */ + public XXPortalUserRole() { + status = RangerConstants.STATUS_DISABLED; + } + + public static String getEnumName(String fieldName) { + if ("status".equals(fieldName)) { + return "CommonEnums.ActiveStatus"; + } + //Later TODO + //return super.getEnumName(fieldName); + return null; + } + + @Override + public Long getId() { + return id; + } + + @Override + public void setId(Long id) { + this.id = id; + } + + @Override + public int hashCode() { + return super.hashCode(); + } + + /** + * Checks for all attributes except referenced db objects + * + * @return true if all attributes match + */ + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } else if (!super.equals(obj)) { + return false; + } + + XXPortalUserRole other = (XXPortalUserRole) obj; + + return Objects.equals(userId, other.userId) && + Objects.equals(userRole, other.userRole) && + Objects.equals(status, other.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; + } + + /** + * Returns the value for the member attribute userId + * + * @return Long - value of member attribute userId. + */ + public Long getUserId() { + return this.userId; + } + + /** + * This method sets the value to the member attribute userId. + * You cannot set null to the attribute. + * + * @param userId Value to set member attribute userId + */ + public void setUserId(Long userId) { + this.userId = userId; + } + + /** + * Returns the value for the member attribute userRole + * + * @return String - value of member attribute userRole. + */ + public String getUserRole() { + return this.userRole; + } + + /** + * This method sets the value to the member attribute userRole. + * You cannot set null to the attribute. + * + * @param userRole Value to set member attribute userRole + */ + public void setUserRole(String userRole) { + this.userRole = userRole; + } + + /** + * Returns the value for the member attribute status + * + * @return int - value of member attribute status. + */ + public int getStatus() { + return this.status; + } + + /** + * This method sets the value to the member attribute status. + * You cannot set null to the attribute. + * + * @param status Value to set member attribute status + */ + public void setStatus(int status) { + this.status = status; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/entity/XXRMSMappingProvider.java b/security-admin/src/main/java/org/apache/ranger/entity/XXRMSMappingProvider.java index c16592f722..17d8420bdf 100644 --- a/security-admin/src/main/java/org/apache/ranger/entity/XXRMSMappingProvider.java +++ b/security-admin/src/main/java/org/apache/ranger/entity/XXRMSMappingProvider.java @@ -21,9 +21,6 @@ import org.apache.ranger.common.AppConstants; -import java.io.Serializable; -import java.util.Date; - import javax.persistence.Cacheable; import javax.persistence.Column; import javax.persistence.Entity; @@ -35,9 +32,13 @@ import javax.persistence.Temporal; import javax.persistence.TemporalType; +import java.io.Serializable; +import java.util.Date; +import java.util.Objects; + @Entity @Cacheable -@Table(name="x_rms_mapping_provider") +@Table(name = "x_rms_mapping_provider") public class XXRMSMappingProvider implements Serializable { private static final long serialVersionUID = 1L; @@ -45,22 +46,17 @@ public class XXRMSMappingProvider implements Serializable { @SequenceGenerator(name = "X_RMS_MAPPING_PROVIDER_SEQ", sequenceName = "X_RMS_MAPPING_PROVIDER_SEQ", allocationSize = 1) @GeneratedValue(strategy = GenerationType.AUTO, generator = "X_RMS_MAPPING_PROVIDER_SEQ") @Column(name = "id") - protected Long id; + protected Long id; + @Temporal(TemporalType.TIMESTAMP) - @Column(name="change_timestamp") - protected Date changeTimestamp; - public Date getChangeTimestamp() { - return changeTimestamp; - } - public void setChangeTimestamp(Date changeTimestamp) { - this.changeTimestamp = changeTimestamp; - } + @Column(name = "change_timestamp") + protected Date changeTimestamp; @Column(name = "name") protected String name; @Column(name = "last_known_version") - protected Long lastKnownVersion; + protected Long lastKnownVersion; public XXRMSMappingProvider() {} @@ -69,14 +65,22 @@ public XXRMSMappingProvider(String name) { setLastKnownVersion(-1L); } - public void setId(Long id) { - this.id = id; + public Date getChangeTimestamp() { + return changeTimestamp; + } + + public void setChangeTimestamp(Date changeTimestamp) { + this.changeTimestamp = changeTimestamp; } public Long getId() { return id; } + public void setId(Long id) { + this.id = id; + } + /** * @return name */ @@ -85,8 +89,7 @@ public String getName() { } /** - * @param name - * the serviceId to set + * @param name the serviceId to set */ public void setName(String name) { this.name = name; @@ -100,8 +103,7 @@ public Long getLastKnownVersion() { } /** - * @param lastKnownVersion - * the lastKnownVersion to set + * @param lastKnownVersion the lastKnownVersion to set */ public void setLastKnownVersion(Long lastKnownVersion) { this.lastKnownVersion = lastKnownVersion; @@ -118,12 +120,7 @@ public int getMyClassType() { */ @Override public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((id == null) ? 0 : id.hashCode()); - result = prime * result + ((name == null) ? 0 : name.hashCode()); - result = prime * result + ((lastKnownVersion == null) ? 0 : lastKnownVersion.hashCode()); - return result; + return Objects.hash(id, name, lastKnownVersion); } /* @@ -133,29 +130,19 @@ public int hashCode() { */ @Override public boolean equals(Object obj) { - if (this == obj) + if (this == obj) { return true; - if (!super.equals(obj)) + } else if (obj == null) { return false; - if (getClass() != obj.getClass()) + } else if (getClass() != obj.getClass()) { return false; + } + XXRMSMappingProvider other = (XXRMSMappingProvider) obj; - if (name == null) { - if (other.name != null) - return false; - } else if (!name.equals(other.name)) - return false; - if (id == null) { - if (other.id != null) - return false; - } else if (!id.equals(other.id)) - return false; - if (lastKnownVersion == null) { - if (other.lastKnownVersion != null) - return false; - } else if (!lastKnownVersion.equals(other.lastKnownVersion)) - return false; - return true; + + return Objects.equals(name, other.name) && + Objects.equals(id, other.id) && + Objects.equals(lastKnownVersion, other.lastKnownVersion); } /* @@ -173,12 +160,11 @@ public String toString() { public StringBuilder toString(StringBuilder sb) { sb.append("{ "); sb.append("id={").append(id).append("} "); - sb.append("changeTimestamp={" + changeTimestamp + "} "); + sb.append("changeTimestamp={").append(changeTimestamp).append("} "); sb.append("resourceSignature={").append(name).append("} "); sb.append("serviceId={").append(lastKnownVersion).append("} "); sb.append(" }"); return sb; } - } diff --git a/security-admin/src/main/java/org/apache/ranger/entity/XXRMSNotification.java b/security-admin/src/main/java/org/apache/ranger/entity/XXRMSNotification.java index 4768382a76..b75a303bb8 100644 --- a/security-admin/src/main/java/org/apache/ranger/entity/XXRMSNotification.java +++ b/security-admin/src/main/java/org/apache/ranger/entity/XXRMSNotification.java @@ -20,9 +20,6 @@ import org.apache.ranger.common.AppConstants; -import java.io.Serializable; -import java.util.Date; - import javax.persistence.Cacheable; import javax.persistence.Column; import javax.persistence.Entity; @@ -34,112 +31,134 @@ import javax.persistence.Temporal; import javax.persistence.TemporalType; +import java.io.Serializable; +import java.util.Date; + @Entity @Cacheable(false) -@Table(name="x_rms_notification") +@Table(name = "x_rms_notification") public class XXRMSNotification implements Serializable { - private static final long serialVersionUID = 1L; - - @Id - @SequenceGenerator(name="X_RMS_NOTIFICATION_SEQ",sequenceName="X_RMS_NOTIFICATION_SEQ",allocationSize=1) - @GeneratedValue(strategy=GenerationType.AUTO,generator="X_RMS_NOTIFICATION_SEQ") - @Column(name="ID") - protected Long id; - public Long getId() { - return id; - } - public void setId(Long id) { - this.id = id; - } - - @Column(name="hms_name", length=128) - protected String hmsName; - public String getHmsName() { - return hmsName; - } - public void setHmsName(String hmsName) { - this.hmsName = hmsName; - } - - @Column(name="notification_id") - protected Long notificationId; - public Long getNotificationId() { - return notificationId; - } - public void setNotificationId(Long notificationId) { - this.notificationId = notificationId; - } - - @Temporal(TemporalType.TIMESTAMP) - @Column(name="change_timestamp") - protected Date changeTimestamp; - public Date getChangeTimestamp() { - return changeTimestamp; - } - public void setChangeTimestamp(Date changeTimestamp) { - this.changeTimestamp = changeTimestamp; - } - - @Column(name="change_type" , length=64 ) - protected String changeType; - public String getChangeType() { - return changeType; - } - public void setChangeType(String changeType) { - this.changeType = changeType; - } - - @Column(name="hl_resource_id") - protected Long hlResourceId; - public Long getHlResourceId() { - return hlResourceId; - } - public void setHlResourceId(Long hlResourceId) { - this.hlResourceId = hlResourceId; - } - - @Column(name="hl_service_id") - protected Long hlServiceId; - public Long getHlServiceId() { - return hlServiceId; - } - public void setHlServiceId(Long hlServiceId) { - this.hlServiceId = hlServiceId; - } - - @Column(name="ll_resource_id") - protected Long llResourceId; - public Long getLlResourceId() { - return llResourceId; - } - public void setLlResourceId(Long llResourceId) { - this.llResourceId = llResourceId; - } - - @Column(name="ll_service_id") - protected Long llServiceId; - public Long getLlServiceId() { return llServiceId; } - public void setLlServiceId(Long llServiceId) { - this.llServiceId = llServiceId; - } - - public int getMyClassType() { - return AppConstants.CLASS_TYPE_RMS_MAPPING_PROVIDER; - } - - public String toString( ) { - String str = "XXNotification={"; - str += "hmsName={" + hmsName + "} "; - str += "notificationId={" + notificationId + "} "; - str += "changeTimestamp={" + changeTimestamp + "} "; - str += "changeType={" + changeType + "} "; - str += "hlResourceId={" + hlResourceId + "} "; - str += "hlServiceId={" + hlServiceId + "} "; - str += "llResourceId={" + llResourceId + "} "; - str += "llServiceId={" + llServiceId + "} "; - str += "}"; - - return str; - } + private static final long serialVersionUID = 1L; + + @Id + @SequenceGenerator(name = "X_RMS_NOTIFICATION_SEQ", sequenceName = "X_RMS_NOTIFICATION_SEQ", allocationSize = 1) + @GeneratedValue(strategy = GenerationType.AUTO, generator = "X_RMS_NOTIFICATION_SEQ") + @Column(name = "ID") + protected Long id; + + @Column(name = "hms_name", length = 128) + protected String hmsName; + + @Column(name = "notification_id") + protected Long notificationId; + + @Temporal(TemporalType.TIMESTAMP) + @Column(name = "change_timestamp") + protected Date changeTimestamp; + + @Column(name = "change_type", length = 64) + protected String changeType; + + @Column(name = "hl_resource_id") + protected Long hlResourceId; + + @Column(name = "hl_service_id") + protected Long hlServiceId; + + @Column(name = "ll_resource_id") + protected Long llResourceId; + + @Column(name = "ll_service_id") + protected Long llServiceId; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getHmsName() { + return hmsName; + } + + public void setHmsName(String hmsName) { + this.hmsName = hmsName; + } + + public Long getNotificationId() { + return notificationId; + } + + public void setNotificationId(Long notificationId) { + this.notificationId = notificationId; + } + + public Date getChangeTimestamp() { + return changeTimestamp; + } + + public void setChangeTimestamp(Date changeTimestamp) { + this.changeTimestamp = changeTimestamp; + } + + public String getChangeType() { + return changeType; + } + + public void setChangeType(String changeType) { + this.changeType = changeType; + } + + public Long getHlResourceId() { + return hlResourceId; + } + + public void setHlResourceId(Long hlResourceId) { + this.hlResourceId = hlResourceId; + } + + public Long getHlServiceId() { + return hlServiceId; + } + + public void setHlServiceId(Long hlServiceId) { + this.hlServiceId = hlServiceId; + } + + public Long getLlResourceId() { + return llResourceId; + } + + public void setLlResourceId(Long llResourceId) { + this.llResourceId = llResourceId; + } + + public Long getLlServiceId() { + return llServiceId; + } + + public void setLlServiceId(Long llServiceId) { + this.llServiceId = llServiceId; + } + + public int getMyClassType() { + return AppConstants.CLASS_TYPE_RMS_MAPPING_PROVIDER; + } + + public String toString() { + String str = "XXNotification={"; + str += "hmsName={" + hmsName + "} "; + str += "notificationId={" + notificationId + "} "; + str += "changeTimestamp={" + changeTimestamp + "} "; + str += "changeType={" + changeType + "} "; + str += "hlResourceId={" + hlResourceId + "} "; + str += "hlServiceId={" + hlServiceId + "} "; + str += "llResourceId={" + llResourceId + "} "; + str += "llServiceId={" + llServiceId + "} "; + str += "}"; + return str; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/entity/XXRMSResourceMapping.java b/security-admin/src/main/java/org/apache/ranger/entity/XXRMSResourceMapping.java index ff220b372f..6bb0931b4c 100644 --- a/security-admin/src/main/java/org/apache/ranger/entity/XXRMSResourceMapping.java +++ b/security-admin/src/main/java/org/apache/ranger/entity/XXRMSResourceMapping.java @@ -29,68 +29,76 @@ import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; + import java.io.Serializable; import java.util.Date; @Entity @Cacheable(false) -@Table(name="x_rms_resource_mapping") +@Table(name = "x_rms_resource_mapping") public class XXRMSResourceMapping implements Serializable { - private static final long serialVersionUID = 1L; - - @Id - @SequenceGenerator(name="X_RMS_RESOURCE_MAPPING_SEQ",sequenceName="X_RMS_RESOURCE_MAPPING_SEQ",allocationSize=1) - @GeneratedValue(strategy=GenerationType.AUTO,generator="X_RMS_RESOURCE_MAPPING_SEQ") - @Column(name="id") - protected Long id; - public Long getId() { - return id; - } - public void setId(Long id) { - this.id = id; - } - - @Temporal(TemporalType.TIMESTAMP) - @Column(name="change_timestamp") - protected Date changeTimestamp; - public Date getChangeTimestamp() { - return changeTimestamp; - } - public void setChangeTimestamp(Date changeTimestamp) { - this.changeTimestamp = changeTimestamp; - } - - @Column(name="hl_resource_id") - protected Long hlResourceId; - public Long getHlResourceId() { - return hlResourceId; - } - public void setHlResourceId(Long hlResourceId) { - this.hlResourceId = hlResourceId; - } - - @Column(name="ll_resource_id") - protected Long llResourceId; - public Long getLlResourceId() { - return llResourceId; - } - public void setLlResourceId(Long llResourceId) { - this.llResourceId = llResourceId; - } - - public int getMyClassType() { - return AppConstants.CLASS_TYPE_RMS_RESOURCE_MAPPING; - } - - public String toString( ) { - String str = "XXResourceMapping={"; - str += "id={" + id + "} "; - str += "changeTimestamp={" + changeTimestamp + "} "; - str += "hlResourceId={" + hlResourceId + "} "; - str += "llResourceId={" + llResourceId + "} "; - str += "}"; - - return str; - } + private static final long serialVersionUID = 1L; + + @Id + @SequenceGenerator(name = "X_RMS_RESOURCE_MAPPING_SEQ", sequenceName = "X_RMS_RESOURCE_MAPPING_SEQ", allocationSize = 1) + @GeneratedValue(strategy = GenerationType.AUTO, generator = "X_RMS_RESOURCE_MAPPING_SEQ") + @Column(name = "id") + protected Long id; + + @Temporal(TemporalType.TIMESTAMP) + @Column(name = "change_timestamp") + protected Date changeTimestamp; + + @Column(name = "hl_resource_id") + protected Long hlResourceId; + + @Column(name = "ll_resource_id") + protected Long llResourceId; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public Date getChangeTimestamp() { + return changeTimestamp; + } + + public void setChangeTimestamp(Date changeTimestamp) { + this.changeTimestamp = changeTimestamp; + } + + public Long getHlResourceId() { + return hlResourceId; + } + + public void setHlResourceId(Long hlResourceId) { + this.hlResourceId = hlResourceId; + } + + public Long getLlResourceId() { + return llResourceId; + } + + public void setLlResourceId(Long llResourceId) { + this.llResourceId = llResourceId; + } + + public int getMyClassType() { + return AppConstants.CLASS_TYPE_RMS_RESOURCE_MAPPING; + } + + public String toString() { + String str = "XXResourceMapping={"; + str += "id={" + id + "} "; + str += "changeTimestamp={" + changeTimestamp + "} "; + str += "hlResourceId={" + hlResourceId + "} "; + str += "llResourceId={" + llResourceId + "} "; + str += "}"; + return str; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/entity/XXRMSServiceResource.java b/security-admin/src/main/java/org/apache/ranger/entity/XXRMSServiceResource.java index 9df61dc39d..fba032017f 100644 --- a/security-admin/src/main/java/org/apache/ranger/entity/XXRMSServiceResource.java +++ b/security-admin/src/main/java/org/apache/ranger/entity/XXRMSServiceResource.java @@ -31,225 +31,186 @@ import javax.persistence.Table; import javax.persistence.Version; +import java.util.Objects; + @Entity @Cacheable -@Table(name="x_rms_service_resource") +@Table(name = "x_rms_service_resource") public class XXRMSServiceResource extends XXDBBase { - private static final long serialVersionUID = 1L; - - @Id - @SequenceGenerator(name = "X_RMS_SERVICE_RESOURCE_SEQ", sequenceName = "X_RMS_SERVICE_RESOURCE_SEQ", allocationSize = 1) - @GeneratedValue(strategy = GenerationType.AUTO, generator = "X_RMS_SERVICE_RESOURCE_SEQ") - @Column(name = "id") - protected Long id; - - @Column(name = "guid", unique = true, nullable = false, length = 512) - protected String guid; - - @Version - @Column(name = "version") - protected Long version; - - @Column(name = "is_enabled") - protected Boolean isEnabled; - - @Column(name = "resource_signature") - protected String resourceSignature; - - @Column(name = "service_id") - protected Long serviceId; - - @Column(name = "service_resource_elements_text") - protected String serviceResourceElements; - - public void setId(Long id) { - this.id = id; - } - - public Long getId() { - return id; - } - - /** - * @return the guid - */ - public String getGuid() { - return guid; - } - - /** - * @param guid - * the guid to set - */ - public void setGuid(String guid) { - this.guid = guid; - } - - /** - * @return the serviceId - */ - public Long getServiceId() { - return serviceId; - } - - /** - * @param serviceId - * the serviceId to set - */ - public void setServiceId(Long serviceId) { - this.serviceId = serviceId; - } - - /** - * @return the resourceSignature - */ - public String getResourceSignature() { - return resourceSignature; - } - - /** - * @param resourceSignature - * the resourceSignature to set - */ - public void setResourceSignature(String resourceSignature) { - this.resourceSignature = resourceSignature; - } - - /** - * @return the version - */ - public Long getVersion() { - return version; - } - - /** - * @param version - * the version to set - */ - public void setVersion(Long version) { - this.version = version; - } - - /** - * @return the isEnabled - */ - public Boolean getIsEnabled() { - return isEnabled; - } - - /** - * @param isEnabled - * the isEnabled to set - */ - public void setIsEnabled(Boolean isEnabled) { - this.isEnabled = isEnabled; - } - - public String getServiceResourceElements() { return serviceResourceElements; } - - public void setServiceResourceElements(String serviceResourceElements) { - this.serviceResourceElements = serviceResourceElements; - } - - public int getMyClassType() { - return AppConstants.CLASS_TYPE_RMS_SERVICE_RESOURCE; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#hashCode() - */ - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((id == null) ? 0 : id.hashCode()); - result = prime * result + ((guid == null) ? 0 : guid.hashCode()); - result = prime * result + ((version == null) ? 0 : version.hashCode()); - result = prime * result + ((isEnabled == null) ? 0 : isEnabled.hashCode()); - result = prime * result + ((resourceSignature == null) ? 0 : resourceSignature.hashCode()); - result = prime * result + ((serviceId == null) ? 0 : serviceId.hashCode()); - result = prime * result + ((serviceResourceElements == null) ? 0 : serviceResourceElements.hashCode()); - return result; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#equals(java.lang.Object) - */ - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (!super.equals(obj)) - return false; - if (getClass() != obj.getClass()) - return false; - XXRMSServiceResource other = (XXRMSServiceResource) obj; - if (resourceSignature == null) { - if (other.resourceSignature != null) - return false; - } else if (!resourceSignature.equals(other.resourceSignature)) - return false; - if (guid == null) { - if (other.guid != null) - return false; - } else if (!guid.equals(other.guid)) - return false; - if (id == null) { - if (other.id != null) - return false; - } else if (!id.equals(other.id)) - return false; - if (isEnabled == null) { - if (other.isEnabled != null) - return false; - } else if (!isEnabled.equals(other.isEnabled)) - return false; - if (serviceId == null) { - if (other.serviceId != null) - return false; - } else if (!serviceId.equals(other.serviceId)) - return false; - if (version == null) { - if (other.version != null) - return false; - } else if (!version.equals(other.version)) - return false; - if (serviceResourceElements == null) { - if (other.serviceResourceElements != null) - return false; - } else if (!serviceResourceElements.equals(other.serviceResourceElements)) - return false; - return true; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#toString() - */ - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - toString(sb); - return sb.toString(); - } - - public StringBuilder toString(StringBuilder sb) { - sb.append("{ "); - sb.append("id={").append(id).append("} "); - sb.append("guid={").append(guid).append("} "); - sb.append("version={").append(version).append("} "); - sb.append("isEnabled={").append(isEnabled).append("} "); - sb.append("resourceSignature={").append(resourceSignature).append("} "); - sb.append("serviceId={").append(serviceId).append("} "); - sb.append("serviceResourceElements={").append(serviceResourceElements).append("} "); - sb.append(" }"); - - return sb; - } - + private static final long serialVersionUID = 1L; + + @Id + @SequenceGenerator(name = "X_RMS_SERVICE_RESOURCE_SEQ", sequenceName = "X_RMS_SERVICE_RESOURCE_SEQ", allocationSize = 1) + @GeneratedValue(strategy = GenerationType.AUTO, generator = "X_RMS_SERVICE_RESOURCE_SEQ") + @Column(name = "id") + protected Long id; + + @Column(name = "guid", unique = true, nullable = false, length = 512) + protected String guid; + + @Version + @Column(name = "version") + protected Long version; + + @Column(name = "is_enabled") + protected Boolean isEnabled; + + @Column(name = "resource_signature") + protected String resourceSignature; + + @Column(name = "service_id") + protected Long serviceId; + + @Column(name = "service_resource_elements_text") + protected String serviceResourceElements; + + /** + * @return the guid + */ + public String getGuid() { + return guid; + } + + /** + * @param guid the guid to set + */ + public void setGuid(String guid) { + this.guid = guid; + } + + /** + * @return the serviceId + */ + public Long getServiceId() { + return serviceId; + } + + /** + * @param serviceId the serviceId to set + */ + public void setServiceId(Long serviceId) { + this.serviceId = serviceId; + } + + /** + * @return the resourceSignature + */ + public String getResourceSignature() { + return resourceSignature; + } + + /** + * @param resourceSignature the resourceSignature to set + */ + public void setResourceSignature(String resourceSignature) { + this.resourceSignature = resourceSignature; + } + + /** + * @return the version + */ + public Long getVersion() { + return version; + } + + /** + * @param version the version to set + */ + public void setVersion(Long version) { + this.version = version; + } + + /** + * @return the isEnabled + */ + public Boolean getIsEnabled() { + return isEnabled; + } + + /** + * @param isEnabled the isEnabled to set + */ + public void setIsEnabled(Boolean isEnabled) { + this.isEnabled = isEnabled; + } + + public String getServiceResourceElements() { + return serviceResourceElements; + } + + public void setServiceResourceElements(String serviceResourceElements) { + this.serviceResourceElements = serviceResourceElements; + } + + public int getMyClassType() { + return AppConstants.CLASS_TYPE_RMS_SERVICE_RESOURCE; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#hashCode() + */ + @Override + public int hashCode() { + return Objects.hash(super.hashCode(), id, guid, version, isEnabled, resourceSignature, serviceId, serviceResourceElements); + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#equals(java.lang.Object) + */ + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } else if (!super.equals(obj)) { + return false; + } + + XXRMSServiceResource other = (XXRMSServiceResource) obj; + + return Objects.equals(resourceSignature, other.resourceSignature) && + Objects.equals(guid, other.guid) && + Objects.equals(id, other.id) && + Objects.equals(isEnabled, other.isEnabled) && + Objects.equals(serviceId, other.serviceId) && + Objects.equals(version, other.version) && + Objects.equals(serviceResourceElements, other.serviceResourceElements); + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + toString(sb); + return sb.toString(); + } + + public StringBuilder toString(StringBuilder sb) { + sb.append("{ "); + sb.append("id={").append(id).append("} "); + sb.append("guid={").append(guid).append("} "); + sb.append("version={").append(version).append("} "); + sb.append("isEnabled={").append(isEnabled).append("} "); + sb.append("resourceSignature={").append(resourceSignature).append("} "); + sb.append("serviceId={").append(serviceId).append("} "); + sb.append("serviceResourceElements={").append(serviceResourceElements).append("} "); + sb.append(" }"); + + return sb; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/entity/XXResource.java b/security-admin/src/main/java/org/apache/ranger/entity/XXResource.java index 5b2e19ca4c..efe8b08760 100644 --- a/security-admin/src/main/java/org/apache/ranger/entity/XXResource.java +++ b/security-admin/src/main/java/org/apache/ranger/entity/XXResource.java @@ -17,13 +17,15 @@ * under the License. */ - package org.apache.ranger.entity; +package org.apache.ranger.entity; /** * Resource - * */ +import org.apache.ranger.common.AppConstants; +import org.apache.ranger.common.RangerConstants; + import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; @@ -32,690 +34,685 @@ import javax.persistence.SequenceGenerator; import javax.persistence.Table; -import org.apache.ranger.common.AppConstants; -import org.apache.ranger.common.RangerConstants; - +import java.util.Objects; @Entity -@Table(name="x_resource") +@Table(name = "x_resource") 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 - *
    - *
  • The maximum length for this attribute is 4000. - *
- * - */ - @Column(name="RES_NAME" , length=4000) - protected String name; - - @Column(name="POLICY_NAME" , length=500) - protected String policyName; - /** - * Description - *
    - *
  • The maximum length for this attribute is 4000. - *
- * - */ - @Column(name="DESCR" , length=4000) - protected String description; - - /** - * Status - *
    - *
  • This attribute is of type enum CommonEnums::ResourceType - *
- * - */ - @Column(name="RES_TYPE" , nullable=false ) - protected int resourceType = AppConstants.RESOURCE_PATH; - - /** - * Id of the asset - *
    - *
- * - */ - @Column(name="ASSET_ID" , nullable=false ) - protected Long assetId; - - - /** - * Id of the parent - *
    - *
- * - */ - @Column(name="PARENT_ID" ) - protected Long parentId; - - - /** - * Path for the parent - *
    - *
  • The maximum length for this attribute is 4000. - *
- * - */ - @Column(name="PARENT_PATH" , length=4000) - protected String parentPath; - - /** - * Whether to encrypt this resource - *
    - *
  • This attribute is of type enum CommonEnums::BooleanValue - *
- * - */ - @Column(name="IS_ENCRYPT" , nullable=false ) - protected int isEncrypt = RangerConstants.BOOL_FALSE; - - /** - * Is recursive - *
    - *
  • This attribute is of type enum CommonEnums::BooleanValue - *
- * - */ - @Column(name="IS_RECURSIVE" , nullable=false ) - protected int isRecursive = RangerConstants.BOOL_NONE; - - /** - * Group to which this resource belongs to - *
    - *
  • The maximum length for this attribute is 1024. - *
- * - */ - @Column(name="RES_GROUP" , length=1024) - protected String resourceGroup; - - /** - * Databases - *
    - *
  • The maximum length for this attribute is 10000. - *
- * - */ - @Column(name="RES_DBS" , length=10000) - protected String databases; - - /** - * Tables - *
    - *
  • The maximum length for this attribute is 10000. - *
- * - */ - @Column(name="RES_TABLES" , length=10000) - protected String tables; - - /** - * Column families - *
    - *
  • The maximum length for this attribute is 10000. - *
- * - */ - @Column(name="RES_COL_FAMS" , length=10000) - protected String columnFamilies; - - /** - * Columns - *
    - *
  • The maximum length for this attribute is 10000. - *
- * - */ - @Column(name="RES_COLS" , length=10000) - protected String columns; - - /** - * UDFs - *
    - *
  • The maximum length for this attribute is 10000. - *
- * - */ - @Column(name="RES_UDFS" , length=10000) - protected String udfs; - - /** - * Resource Status - *
    - *
  • This attribute is of type enum CommonEnums::ActiveStatus - *
- * - */ - @Column(name="RES_STATUS" , nullable=false ) - protected int resourceStatus = RangerConstants.STATUS_ENABLED; - - /** - * Table Type - *
    - *
  • This attribute is of type enum CommonEnums::PolicyType - *
- * - */ - @Column(name="TABLE_TYPE" , nullable=false ) - protected int tableType = AppConstants.POLICY_INCLUSION; - - /** - * Resource Status - *
    - *
  • This attribute is of type enum CommonEnums::PolicyType - *
- * - */ - @Column(name="COL_TYPE" , nullable=false ) - protected int columnType = AppConstants.POLICY_INCLUSION; - /** - * Topologoies - *
    - *
  • The maximum length for this attribute is 10000. - *
- * - */ - @Column(name="RES_TOPOLOGIES" , length=10000) - protected String topologies; - /** - * SERVICENAMES - *
    - *
  • The maximum length for this attribute is 10000. - *
- * - */ - @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 = RangerConstants.BOOL_FALSE; - isRecursive = RangerConstants.BOOL_NONE; - resourceStatus = RangerConstants.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 name. - * You cannot set null to the attribute. - * @param name Value to set member attribute name - */ - 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 name - * @return String - value of member attribute name. - */ - public String getName( ) { - return this.name; - } - - /** - * This method sets the value to the member attribute description. - * You cannot set null to the attribute. - * @param description Value to set member attribute description - */ - public void setDescription( String description ) { - this.description = description; - } - - /** - * Returns the value for the member attribute description - * @return String - value of member attribute description. - */ - public String getDescription( ) { - return this.description; - } - - /** - * This method sets the value to the member attribute resourceType. - * You cannot set null to the attribute. - * @param resourceType Value to set member attribute resourceType - */ - public void setResourceType( int resourceType ) { - this.resourceType = resourceType; - } - - /** - * Returns the value for the member attribute resourceType - * @return int - value of member attribute resourceType. - */ - public int getResourceType( ) { - return this.resourceType; - } - - /** - * This method sets the value to the member attribute assetId. - * You cannot set null to the attribute. - * @param assetId Value to set member attribute assetId - */ - public void setAssetId( Long assetId ) { - this.assetId = assetId; - } - - /** - * Returns the value for the member attribute assetId - * @return Long - value of member attribute assetId. - */ - public Long getAssetId( ) { - return this.assetId; - } - - - /** - * This method sets the value to the member attribute parentId. - * You cannot set null to the attribute. - * @param parentId Value to set member attribute parentId - */ - public void setParentId( Long parentId ) { - this.parentId = parentId; - } - - /** - * Returns the value for the member attribute parentId - * @return Long - value of member attribute parentId. - */ - public Long getParentId( ) { - return this.parentId; - } - - - /** - * This method sets the value to the member attribute parentPath. - * You cannot set null to the attribute. - * @param parentPath Value to set member attribute parentPath - */ - public void setParentPath( String parentPath ) { - this.parentPath = parentPath; - } - - /** - * Returns the value for the member attribute parentPath - * @return String - value of member attribute parentPath. - */ - public String getParentPath( ) { - return this.parentPath; - } - - /** - * This method sets the value to the member attribute isEncrypt. - * You cannot set null to the attribute. - * @param isEncrypt Value to set member attribute isEncrypt - */ - public void setIsEncrypt( int isEncrypt ) { - this.isEncrypt = isEncrypt; - } - - /** - * Returns the value for the member attribute isEncrypt - * @return int - value of member attribute isEncrypt. - */ - public int getIsEncrypt( ) { - return this.isEncrypt; - } - - /** - * This method sets the value to the member attribute isRecursive. - * You cannot set null to the attribute. - * @param isRecursive Value to set member attribute isRecursive - */ - public void setIsRecursive( int isRecursive ) { - this.isRecursive = isRecursive; - } - - /** - * Returns the value for the member attribute isRecursive - * @return int - value of member attribute isRecursive. - */ - public int getIsRecursive( ) { - return this.isRecursive; - } - - /** - * This method sets the value to the member attribute resourceGroup. - * You cannot set null to the attribute. - * @param resourceGroup Value to set member attribute resourceGroup - */ - public void setResourceGroup( String resourceGroup ) { - this.resourceGroup = resourceGroup; - } - - /** - * Returns the value for the member attribute resourceGroup - * @return String - value of member attribute resourceGroup. - */ - public String getResourceGroup( ) { - return this.resourceGroup; - } - - /** - * This method sets the value to the member attribute databases. - * You cannot set null to the attribute. - * @param databases Value to set member attribute databases - */ - public void setDatabases( String databases ) { - this.databases = databases; - } - - /** - * Returns the value for the member attribute databases - * @return String - value of member attribute databases. - */ - public String getDatabases( ) { - return this.databases; - } - - /** - * This method sets the value to the member attribute tables. - * You cannot set null to the attribute. - * @param tables Value to set member attribute tables - */ - public void setTables( String tables ) { - this.tables = tables; - } - - /** - * Returns the value for the member attribute tables - * @return String - value of member attribute tables. - */ - public String getTables( ) { - return this.tables; - } - - /** - * This method sets the value to the member attribute columnFamilies. - * You cannot set null to the attribute. - * @param columnFamilies Value to set member attribute columnFamilies - */ - public void setColumnFamilies( String columnFamilies ) { - this.columnFamilies = columnFamilies; - } - - /** - * Returns the value for the member attribute columnFamilies - * @return String - value of member attribute columnFamilies. - */ - public String getColumnFamilies( ) { - return this.columnFamilies; - } - - /** - * This method sets the value to the member attribute columns. - * You cannot set null to the attribute. - * @param columns Value to set member attribute columns - */ - public void setColumns( String columns ) { - this.columns = columns; - } - - /** - * Returns the value for the member attribute columns - * @return String - value of member attribute columns. - */ - public String getColumns( ) { - return this.columns; - } - - /** - * This method sets the value to the member attribute udfs. - * You cannot set null to the attribute. - * @param udfs Value to set member attribute udfs - */ - public void setUdfs( String udfs ) { - this.udfs = udfs; - } - - /** - * Returns the value for the member attribute udfs - * @return String - value of member attribute udfs. - */ - public String getUdfs( ) { - return this.udfs; - } - - /** - * This method sets the value to the member attribute resourceStatus. - * You cannot set null to the attribute. - * @param resourceStatus Value to set member attribute resourceStatus - */ - public void setResourceStatus( int resourceStatus ) { - this.resourceStatus = resourceStatus; - } - - /** - * Returns the value for the member attribute resourceStatus - * @return int - value of member attribute resourceStatus. - */ - public int getResourceStatus( ) { - return this.resourceStatus; - } - - /** - * This method sets the value to the member attribute tableType. - * You cannot set null to the attribute. - * @param tableType Value to set member attribute tableType - */ - public void setTableType( int tableType ) { - this.tableType = tableType; - } - - /** - * Returns the value for the member attribute tableType - * @return int - value of member attribute tableType. - */ - public int getTableType( ) { - return this.tableType; - } - - /** - * This method sets the value to the member attribute columnType. - * You cannot set null to the attribute. - * @param columnType Value to set member attribute columnType - */ - public void setColumnType( int columnType ) { - this.columnType = columnType; - } - - /** - * Returns the value for the member attribute columnType - * @return int - value of member attribute columnType. - */ - public int getColumnType( ) { - return this.columnType; - } - - /** - * Returns the value for the member attribute topologies - * @return String - value of member attribute topologies. - */ - public String getTopologies() { - return topologies; - } - - /** - * This method sets the value to the member attribute topologies. - * You cannot set null to the attribute. - * @param topologies Value to set member attribute topologies - */ - public void setTopologies(String topologies) { - this.topologies = topologies; - } - - /** - * Returns the value for the member attribute services - * @return String - value of member attribute services. - */ - public String getServices() { - return services; - } - - /** - * This method sets the value to the member attribute services. - * You cannot set null to the attribute. - * @param services Value to set member attribute services - */ - 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( "resourceType".equals(fieldName) ) { - return "CommonEnums.ResourceType"; - } - if( "isEncrypt".equals(fieldName) ) { - return "CommonEnums.BooleanValue"; - } - if( "isRecursive".equals(fieldName) ) { - return "CommonEnums.BooleanValue"; - } - if( "resourceStatus".equals(fieldName) ) { - return "CommonEnums.ActiveStatus"; - } - if( "tableType".equals(fieldName) ) { - return "CommonEnums.PolicyType"; - } - if( "columnType".equals(fieldName) ) { - return "CommonEnums.PolicyType"; - } - if( "assetType".equals(fieldName) ) { - return "CommonEnums.AssetType"; - } - //Later TODO - //return super.getEnumName(fieldName); - return null; - } - + 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; + + /** + * Name + *
    + *
  • The maximum length for this attribute is 4000. + *
+ */ + @Column(name = "RES_NAME", length = 4000) + protected String name; + + @Column(name = "POLICY_NAME", length = 500) + protected String policyName; + + /** + * Description + *
    + *
  • The maximum length for this attribute is 4000. + *
+ */ + @Column(name = "DESCR", length = 4000) + protected String description; + + /** + * Status + *
    + *
  • This attribute is of type enum CommonEnums::ResourceType + *
+ */ + @Column(name = "RES_TYPE", nullable = false) + protected int resourceType = AppConstants.RESOURCE_PATH; + + /** + * Id of the asset + *
    + *
+ */ + @Column(name = "ASSET_ID", nullable = false) + protected Long assetId; + + /** + * Id of the parent + *
    + *
+ */ + @Column(name = "PARENT_ID") + protected Long parentId; + + /** + * Path for the parent + *
    + *
  • The maximum length for this attribute is 4000. + *
+ */ + @Column(name = "PARENT_PATH", length = 4000) + protected String parentPath; + + /** + * Whether to encrypt this resource + *
    + *
  • This attribute is of type enum CommonEnums::BooleanValue + *
+ */ + @Column(name = "IS_ENCRYPT", nullable = false) + protected int isEncrypt = RangerConstants.BOOL_FALSE; + + /** + * Is recursive + *
    + *
  • This attribute is of type enum CommonEnums::BooleanValue + *
+ */ + @Column(name = "IS_RECURSIVE", nullable = false) + protected int isRecursive = RangerConstants.BOOL_NONE; + + /** + * Group to which this resource belongs to + *
    + *
  • The maximum length for this attribute is 1024. + *
+ */ + @Column(name = "RES_GROUP", length = 1024) + protected String resourceGroup; + + /** + * Databases + *
    + *
  • The maximum length for this attribute is 10000. + *
+ */ + @Column(name = "RES_DBS", length = 10000) + protected String databases; + + /** + * Tables + *
    + *
  • The maximum length for this attribute is 10000. + *
+ */ + @Column(name = "RES_TABLES", length = 10000) + protected String tables; + + /** + * Column families + *
    + *
  • The maximum length for this attribute is 10000. + *
+ */ + @Column(name = "RES_COL_FAMS", length = 10000) + protected String columnFamilies; + + /** + * Columns + *
    + *
  • The maximum length for this attribute is 10000. + *
+ */ + @Column(name = "RES_COLS", length = 10000) + protected String columns; + + /** + * UDFs + *
    + *
  • The maximum length for this attribute is 10000. + *
+ */ + @Column(name = "RES_UDFS", length = 10000) + protected String udfs; + + /** + * Resource Status + *
    + *
  • This attribute is of type enum CommonEnums::ActiveStatus + *
+ */ + @Column(name = "RES_STATUS", nullable = false) + protected int resourceStatus = RangerConstants.STATUS_ENABLED; + + /** + * Table Type + *
    + *
  • This attribute is of type enum CommonEnums::PolicyType + *
+ */ + @Column(name = "TABLE_TYPE", nullable = false) + protected int tableType = AppConstants.POLICY_INCLUSION; + + /** + * Resource Status + *
    + *
  • This attribute is of type enum CommonEnums::PolicyType + *
+ */ + @Column(name = "COL_TYPE", nullable = false) + protected int columnType = AppConstants.POLICY_INCLUSION; + + /** + * Topologoies + *
    + *
  • The maximum length for this attribute is 10000. + *
+ */ + @Column(name = "RES_TOPOLOGIES", length = 10000) + protected String topologies; + + /** + * SERVICENAMES + *
    + *
  • The maximum length for this attribute is 10000. + *
+ */ + @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 = RangerConstants.BOOL_FALSE; + isRecursive = RangerConstants.BOOL_NONE; + resourceStatus = RangerConstants.STATUS_ENABLED; + tableType = AppConstants.POLICY_INCLUSION; + columnType = AppConstants.POLICY_INCLUSION; + } + + public static String getEnumName(String fieldName) { + if ("resourceType".equals(fieldName)) { + return "CommonEnums.ResourceType"; + } else if ("isEncrypt".equals(fieldName)) { + return "CommonEnums.BooleanValue"; + } else if ("isRecursive".equals(fieldName)) { + return "CommonEnums.BooleanValue"; + } else if ("resourceStatus".equals(fieldName)) { + return "CommonEnums.ActiveStatus"; + } else if ("tableType".equals(fieldName)) { + return "CommonEnums.PolicyType"; + } else if ("columnType".equals(fieldName)) { + return "CommonEnums.PolicyType"; + } else if ("assetType".equals(fieldName)) { + return "CommonEnums.AssetType"; + } + + //Later TODO + //return super.getEnumName(fieldName); + return null; + } + + @Override + public int getMyClassType() { + return AppConstants.CLASS_TYPE_XA_RESOURCE; + } + + @Override + public String getMyDisplayValue() { + return getDescription(); + } + + @Override + public Long getId() { + return id; + } + + @Override + public void setId(Long id) { + this.id = id; + } + + @Override + public int hashCode() { + return super.hashCode(); + } + + /** + * Checks for all attributes except referenced db objects + * + * @return true if all attributes match + */ + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } else if (!super.equals(obj)) { + return false; + } + + XXResource other = (XXResource) obj; + + return Objects.equals(name, other.name) && + Objects.equals(description, other.description) && + Objects.equals(resourceType, other.resourceType) && + Objects.equals(assetId, other.assetId) && + Objects.equals(parentId, other.parentId) && + Objects.equals(parentPath, other.parentPath) && + Objects.equals(isEncrypt, other.isEncrypt) && + Objects.equals(isRecursive, other.isRecursive) && + Objects.equals(resourceGroup, other.resourceGroup) && + Objects.equals(databases, other.databases) && + Objects.equals(tables, other.tables) && + Objects.equals(columnFamilies, other.columnFamilies) && + Objects.equals(columns, other.columns) && + Objects.equals(udfs, other.udfs) && + Objects.equals(resourceStatus, other.resourceStatus) && + Objects.equals(tableType, other.tableType) && + Objects.equals(columnType, other.columnType) && + Objects.equals(topologies, other.topologies) && + Objects.equals(services, other.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; + } + + public String getPolicyName() { + return policyName; + } + + public void setPolicyName(String policyName) { + this.policyName = policyName; + } + + /** + * Returns the value for the member attribute name + * + * @return String - value of member attribute name. + */ + public String getName() { + return this.name; + } + + /** + * This method sets the value to the member attribute name. + * You cannot set null to the attribute. + * + * @param name Value to set member attribute name + */ + public void setName(String name) { + this.name = name; + } + + /** + * Returns the value for the member attribute description + * + * @return String - value of member attribute description. + */ + public String getDescription() { + return this.description; + } + + /** + * This method sets the value to the member attribute description. + * You cannot set null to the attribute. + * + * @param description Value to set member attribute description + */ + public void setDescription(String description) { + this.description = description; + } + + /** + * Returns the value for the member attribute resourceType + * + * @return int - value of member attribute resourceType. + */ + public int getResourceType() { + return this.resourceType; + } + + /** + * This method sets the value to the member attribute resourceType. + * You cannot set null to the attribute. + * + * @param resourceType Value to set member attribute resourceType + */ + public void setResourceType(int resourceType) { + this.resourceType = resourceType; + } + + /** + * Returns the value for the member attribute assetId + * + * @return Long - value of member attribute assetId. + */ + public Long getAssetId() { + return this.assetId; + } + + /** + * This method sets the value to the member attribute assetId. + * You cannot set null to the attribute. + * + * @param assetId Value to set member attribute assetId + */ + public void setAssetId(Long assetId) { + this.assetId = assetId; + } + + /** + * Returns the value for the member attribute parentId + * + * @return Long - value of member attribute parentId. + */ + public Long getParentId() { + return this.parentId; + } + + /** + * This method sets the value to the member attribute parentId. + * You cannot set null to the attribute. + * + * @param parentId Value to set member attribute parentId + */ + public void setParentId(Long parentId) { + this.parentId = parentId; + } + + /** + * Returns the value for the member attribute parentPath + * + * @return String - value of member attribute parentPath. + */ + public String getParentPath() { + return this.parentPath; + } + + /** + * This method sets the value to the member attribute parentPath. + * You cannot set null to the attribute. + * + * @param parentPath Value to set member attribute parentPath + */ + public void setParentPath(String parentPath) { + this.parentPath = parentPath; + } + + /** + * Returns the value for the member attribute isEncrypt + * + * @return int - value of member attribute isEncrypt. + */ + public int getIsEncrypt() { + return this.isEncrypt; + } + + /** + * This method sets the value to the member attribute isEncrypt. + * You cannot set null to the attribute. + * + * @param isEncrypt Value to set member attribute isEncrypt + */ + public void setIsEncrypt(int isEncrypt) { + this.isEncrypt = isEncrypt; + } + + /** + * Returns the value for the member attribute isRecursive + * + * @return int - value of member attribute isRecursive. + */ + public int getIsRecursive() { + return this.isRecursive; + } + + /** + * This method sets the value to the member attribute isRecursive. + * You cannot set null to the attribute. + * + * @param isRecursive Value to set member attribute isRecursive + */ + public void setIsRecursive(int isRecursive) { + this.isRecursive = isRecursive; + } + + /** + * Returns the value for the member attribute resourceGroup + * + * @return String - value of member attribute resourceGroup. + */ + public String getResourceGroup() { + return this.resourceGroup; + } + + /** + * This method sets the value to the member attribute resourceGroup. + * You cannot set null to the attribute. + * + * @param resourceGroup Value to set member attribute resourceGroup + */ + public void setResourceGroup(String resourceGroup) { + this.resourceGroup = resourceGroup; + } + + /** + * Returns the value for the member attribute databases + * + * @return String - value of member attribute databases. + */ + public String getDatabases() { + return this.databases; + } + + /** + * This method sets the value to the member attribute databases. + * You cannot set null to the attribute. + * + * @param databases Value to set member attribute databases + */ + public void setDatabases(String databases) { + this.databases = databases; + } + + /** + * Returns the value for the member attribute tables + * + * @return String - value of member attribute tables. + */ + public String getTables() { + return this.tables; + } + + /** + * This method sets the value to the member attribute tables. + * You cannot set null to the attribute. + * + * @param tables Value to set member attribute tables + */ + public void setTables(String tables) { + this.tables = tables; + } + + /** + * Returns the value for the member attribute columnFamilies + * + * @return String - value of member attribute columnFamilies. + */ + public String getColumnFamilies() { + return this.columnFamilies; + } + + /** + * This method sets the value to the member attribute columnFamilies. + * You cannot set null to the attribute. + * + * @param columnFamilies Value to set member attribute columnFamilies + */ + public void setColumnFamilies(String columnFamilies) { + this.columnFamilies = columnFamilies; + } + + /** + * Returns the value for the member attribute columns + * + * @return String - value of member attribute columns. + */ + public String getColumns() { + return this.columns; + } + + /** + * This method sets the value to the member attribute columns. + * You cannot set null to the attribute. + * + * @param columns Value to set member attribute columns + */ + public void setColumns(String columns) { + this.columns = columns; + } + + /** + * Returns the value for the member attribute udfs + * + * @return String - value of member attribute udfs. + */ + public String getUdfs() { + return this.udfs; + } + + /** + * This method sets the value to the member attribute udfs. + * You cannot set null to the attribute. + * + * @param udfs Value to set member attribute udfs + */ + public void setUdfs(String udfs) { + this.udfs = udfs; + } + + /** + * Returns the value for the member attribute resourceStatus + * + * @return int - value of member attribute resourceStatus. + */ + public int getResourceStatus() { + return this.resourceStatus; + } + + /** + * This method sets the value to the member attribute resourceStatus. + * You cannot set null to the attribute. + * + * @param resourceStatus Value to set member attribute resourceStatus + */ + public void setResourceStatus(int resourceStatus) { + this.resourceStatus = resourceStatus; + } + + /** + * Returns the value for the member attribute tableType + * + * @return int - value of member attribute tableType. + */ + public int getTableType() { + return this.tableType; + } + + /** + * This method sets the value to the member attribute tableType. + * You cannot set null to the attribute. + * + * @param tableType Value to set member attribute tableType + */ + public void setTableType(int tableType) { + this.tableType = tableType; + } + + /** + * Returns the value for the member attribute columnType + * + * @return int - value of member attribute columnType. + */ + public int getColumnType() { + return this.columnType; + } + + /** + * This method sets the value to the member attribute columnType. + * You cannot set null to the attribute. + * + * @param columnType Value to set member attribute columnType + */ + public void setColumnType(int columnType) { + this.columnType = columnType; + } + + /** + * Returns the value for the member attribute topologies + * + * @return String - value of member attribute topologies. + */ + public String getTopologies() { + return topologies; + } + + /** + * This method sets the value to the member attribute topologies. + * You cannot set null to the attribute. + * + * @param topologies Value to set member attribute topologies + */ + public void setTopologies(String topologies) { + this.topologies = topologies; + } + + /** + * Returns the value for the member attribute services + * + * @return String - value of member attribute services. + */ + public String getServices() { + return services; + } + + /** + * This method sets the value to the member attribute services. + * You cannot set null to the attribute. + * + * @param services Value to set member attribute services + */ + public void setServices(String services) { + this.services = services; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/entity/XXResourceDef.java b/security-admin/src/main/java/org/apache/ranger/entity/XXResourceDef.java index 0bf2b781a9..b817f471f6 100644 --- a/security-admin/src/main/java/org/apache/ranger/entity/XXResourceDef.java +++ b/security-admin/src/main/java/org/apache/ranger/entity/XXResourceDef.java @@ -18,837 +18,701 @@ */ package org.apache.ranger.entity; -import javax.persistence.*; +import javax.persistence.Cacheable; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.SequenceGenerator; +import javax.persistence.Table; + +import java.util.Objects; @Entity @Cacheable @Table(name = "x_resource_def") public class XXResourceDef extends XXDBBase implements java.io.Serializable { - private static final long serialVersionUID = 1L; - /** - * id of the XXResourceDef - *
    - *
- * - */ - @Id - @SequenceGenerator(name = "x_resource_def_SEQ", sequenceName = "x_resource_def_SEQ", allocationSize = 1) - @GeneratedValue(strategy = GenerationType.AUTO, generator = "x_resource_def_SEQ") - @Column(name = "id") - protected Long id; - - /** - * defId of the XXResourceDef - *
    - *
- * - */ - @Column(name = "def_id") - protected Long defId; - - /** - * itemId of the XXResourceDef - *
    - *
- * - */ - @Column(name = "item_id") - protected Long itemId; - - /** - * name of the XXResourceDef - *
    - *
- * - */ - @Column(name = "name") - protected String name; - - /** - * type of the XXResourceDef - *
    - *
- * - */ - @Column(name = "type") - protected String type; - - /** - * level of the XXResourceDef - *
    - *
- * - */ - @Column(name = "res_level") - protected Integer level; - - /** - * parent of the XXResourceDef - *
    - *
- * - */ - @Column(name = "parent") - protected Long parent; - - /** - * mandatory of the XXResourceDef - *
    - *
- * - */ - @Column(name = "mandatory") - protected boolean mandatory; - - /** - * lookUpSupported of the XXResourceDef - *
    - *
- * - */ - @Column(name = "look_up_supported") - protected boolean lookUpSupported; - - /** - * recursiveSupported of the XXResourceDef - *
    - *
- * - */ - @Column(name = "recursive_supported") - protected boolean recursiveSupported; - - /** - * excludesSupported of the XXResourceDef - *
    - *
- * - */ - @Column(name = "excludes_supported") - protected boolean excludesSupported; - - /** - * matcher of the XXResourceDef - *
    - *
- * - */ - @Column(name = "matcher") - protected String matcher; - - /** - * matcherOptions of the XXResourceDef - *
    - *
- * - */ - @Column(name = "matcher_options") - protected String matcherOptions; - - /** - * validationRegEx of the XXResourceDef - *
    - *
- * - */ - @Column(name = "validation_reg_ex") - protected String validationRegEx; - - /** - * validationMessage of the XXResourceDef - *
    - *
- * - */ - @Column(name = "validation_message") - protected String validationMessage; - - /** - * uiHint of the XXResourceDef - *
    - *
- * - */ - @Column(name = "ui_hint") - protected String uiHint; - - /** - * label of the XXResourceDef - *
    - *
- * - */ - @Column(name = "label") - protected String label; - - /** - * description of the XXResourceDef - *
    - *
- * - */ - @Column(name = "description") - protected String description; - - /** - * rbKeyLabel of the XXResourceDef - *
    - *
- * - */ - @Column(name = "rb_key_label") - protected String rbKeyLabel; - - /** - * rbKeyDescription of the XXResourceDef - *
    - *
- * - */ - @Column(name = "rb_key_description") - protected String rbKeyDescription; - - /** - * rbKeyValidationMessage of the XXResourceDef - *
    - *
- * - */ - @Column(name = "rb_key_validation_message") - protected String rbKeyValidationMessage; - - /** - * order of the XXResourceDef - *
    - *
- * - */ - @Column(name = "sort_order") - protected Integer order; - - /** - * dataMaskOptions of the XXResourceDef - *
    - *
- * - */ - @Column(name = "datamask_options") - protected String dataMaskOptions; - - /** - * rowFilterOptions of the XXAccessTypeDef - *
    - *
- * - */ - @Column(name = "rowfilter_options") - protected String rowFilterOptions; - - /** - * This method sets the value to the member attribute id . You - * cannot set null to the attribute. - * - * @param id - * Value to set member attribute id - */ - public void setId(Long id) { - this.id = id; - } - - /** - * Returns the value for the member attribute id - * - * @return Date - value of member attribute id . - */ - public Long getId() { - return this.id; - } - - /** - * This method sets the value to the member attribute defId . You - * cannot set null to the attribute. - * - * @param defId - * Value to set member attribute defId - */ - public void setDefid(Long defId) { - this.defId = defId; - } - - /** - * Returns the value for the member attribute itemId - * - * @return Long - value of member attribute itemId . - */ - public Long getItemId() { - return this.itemId; - } - - /** - * This method sets the value to the member attribute itemId . You - * cannot set null to the attribute. - * - * @param itemId - * Value to set member attribute itemId - */ - public void setItemId(Long itemId) { - this.itemId = itemId; - } - - /** - * Returns the value for the member attribute defId - * - * @return Date - value of member attribute defId . - */ - public Long getDefid() { - return this.defId; - } - - /** - * This method sets the value to the member attribute name . You - * cannot set null to the attribute. - * - * @param name - * Value to set member attribute name - */ - public void setName(String name) { - this.name = name; - } - - /** - * Returns the value for the member attribute name - * - * @return Date - value of member attribute name . - */ - public String getName() { - return this.name; - } - - /** - * This method sets the value to the member attribute type . You - * cannot set null to the attribute. - * - * @param type - * Value to set member attribute type - */ - public void setType(String type) { - this.type = type; - } - - /** - * Returns the value for the member attribute type - * - * @return Date - value of member attribute type . - */ - public String getType() { - return this.type; - } - - /** - * This method sets the value to the member attribute level . You - * cannot set null to the attribute. - * - * @param level - * Value to set member attribute level - */ - public void setLevel(Integer level) { - this.level = level; - } - - /** - * Returns the value for the member attribute level - * - * @return Date - value of member attribute level . - */ - public Integer getLevel() { - return this.level; - } - - /** - * This method sets the value to the member attribute parent . You - * cannot set null to the attribute. - * - * @param parent - * Value to set member attribute parent - */ - public void setParent(Long parent) { - this.parent = parent; - } - - /** - * Returns the value for the member attribute parent - * - * @return Date - value of member attribute parent . - */ - public Long getParent() { - return this.parent; - } - - /** - * This method sets the value to the member attribute mandatory . - * You cannot set null to the attribute. - * - * @param mandatory - * Value to set member attribute mandatory - */ - public void setMandatory(boolean mandatory) { - this.mandatory = mandatory; - } - - /** - * Returns the value for the member attribute mandatory - * - * @return Date - value of member attribute mandatory . - */ - public boolean getMandatory() { - return this.mandatory; - } - - /** - * This method sets the value to the member attribute - * lookUpSupported . You cannot set null to the attribute. - * - * @param lookUpSupported - * Value to set member attribute lookUpSupported - */ - public void setLookupsupported(boolean lookUpSupported) { - this.lookUpSupported = lookUpSupported; - } - - /** - * Returns the value for the member attribute lookUpSupported - * - * @return Date - value of member attribute lookUpSupported . - */ - public boolean getLookupsupported() { - return this.lookUpSupported; - } - - /** - * This method sets the value to the member attribute - * recursiveSupported . You cannot set null to the attribute. - * - * @param recursiveSupported - * Value to set member attribute recursiveSupported - */ - public void setRecursivesupported(boolean recursiveSupported) { - this.recursiveSupported = recursiveSupported; - } - - /** - * Returns the value for the member attribute recursiveSupported - * - * @return Date - value of member attribute recursiveSupported . - */ - public boolean getRecursivesupported() { - return this.recursiveSupported; - } - - /** - * This method sets the value to the member attribute - * excludesSupported . You cannot set null to the attribute. - * - * @param excludesSupported - * Value to set member attribute excludesSupported - */ - public void setExcludessupported(boolean excludesSupported) { - this.excludesSupported = excludesSupported; - } - - /** - * Returns the value for the member attribute excludesSupported - * - * @return Date - value of member attribute excludesSupported . - */ - public boolean getExcludessupported() { - return this.excludesSupported; - } - - /** - * This method sets the value to the member attribute matcher . You - * cannot set null to the attribute. - * - * @param matcher - * Value to set member attribute matcher - */ - public void setMatcher(String matcher) { - this.matcher = matcher; - } - - /** - * Returns the value for the member attribute matcher - * - * @return Date - value of member attribute matcher . - */ - public String getMatcher() { - return this.matcher; - } - - /** - * This method sets the value to the member attribute matcherOptions - * . You cannot set null to the attribute. - * - * @param matcherOptions - * Value to set member attribute matcherOptions - */ - public void setMatcheroptions(String matcherOptions) { - this.matcherOptions = matcherOptions; - } - - /** - * Returns the value for the member attribute matcherOptions - * - * @return Date - value of member attribute matcherOptions . - */ - public String getMatcheroptions() { - return this.matcherOptions; - } - - /** - * @return the validationRegEx - */ - public String getValidationRegEx() { - return validationRegEx; - } - - /** - * @param validationRegEx the validationRegEx to set - */ - public void setValidationRegEx(String validationRegEx) { - this.validationRegEx = validationRegEx; - } - - /** - * @return the validationMessage - */ - public String getValidationMessage() { - return validationMessage; - } - - /** - * @param validationMessage the validationMessage to set - */ - public void setValidationMessage(String validationMessage) { - this.validationMessage = validationMessage; - } - - /** - * @return the uiHint - */ - public String getUiHint() { - return uiHint; - } - - /** - * @param uiHint the uiHint to set - */ - public void setUiHint(String uiHint) { - this.uiHint = uiHint; - } - - /** - * This method sets the value to the member attribute label . You - * cannot set null to the attribute. - * - * @param label - * Value to set member attribute label - */ - public void setLabel(String label) { - this.label = label; - } - - /** - * Returns the value for the member attribute label - * - * @return Date - value of member attribute label . - */ - public String getLabel() { - return this.label; - } - - /** - * This method sets the value to the member attribute description . - * You cannot set null to the attribute. - * - * @param description - * Value to set member attribute description - */ - public void setDescription(String description) { - this.description = description; - } - - /** - * Returns the value for the member attribute description - * - * @return Date - value of member attribute description . - */ - public String getDescription() { - return this.description; - } - - /** - * This method sets the value to the member attribute rbKeyLabel . - * You cannot set null to the attribute. - * - * @param rbKeyLabel - * Value to set member attribute rbKeyLabel - */ - public void setRbkeylabel(String rbKeyLabel) { - this.rbKeyLabel = rbKeyLabel; - } - - /** - * Returns the value for the member attribute rbKeyLabel - * - * @return Date - value of member attribute rbKeyLabel . - */ - public String getRbkeylabel() { - return this.rbKeyLabel; - } - - /** - * This method sets the value to the member attribute - * rbKeyDescription . You cannot set null to the attribute. - * - * @param rbKeyDescription - * Value to set member attribute rbKeyDescription - */ - public void setRbkeydescription(String rbKeyDescription) { - this.rbKeyDescription = rbKeyDescription; - } - - /** - * Returns the value for the member attribute rbKeyDescription - * - * @return Date - value of member attribute rbKeyDescription . - */ - public String getRbkeydescription() { - return this.rbKeyDescription; - } - - /** - * @return the rbKeyValidationMessage - */ - public String getRbKeyValidationMessage() { - return rbKeyValidationMessage; - } - - /** - * @param rbKeyValidationMessage the rbKeyValidationMessage to set - */ - public void setRbKeyValidationMessage(String rbKeyValidationMessage) { - this.rbKeyValidationMessage = rbKeyValidationMessage; - } - - /** - * This method sets the value to the member attribute order . You - * cannot set null to the attribute. - * - * @param order - * Value to set member attribute order - */ - public void setOrder(Integer order) { - this.order = order; - } - - /** - * Returns the value for the member attribute order - * - * @return Date - value of member attribute order . - */ - public Integer getOrder() { - return this.order; - } - - public String getDataMaskOptions() { - return dataMaskOptions; - } - - public void setDataMaskOptions(String dataMaskOptions) { - this.dataMaskOptions = dataMaskOptions; - } - - public String getRowFilterOptions() { return rowFilterOptions; } - - public void setRowFilterOptions(String rowFilterOptions) { this.rowFilterOptions = rowFilterOptions; } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#equals(java.lang.Object) - */ - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (!super.equals(obj)) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - XXResourceDef other = (XXResourceDef) obj; - if (defId == null) { - if (other.defId != null) { - return false; - } - } else if (!defId.equals(other.defId)) { - return false; - } - if (itemId == null) { - if (other.itemId != null) { - return false; - } - } else if (!itemId.equals(other.itemId)) { - return false; - } - if (description == null) { - if (other.description != null) { - return false; - } - } else if (!description.equals(other.description)) { - return false; - } - if (excludesSupported != other.excludesSupported) { - return false; - } - if (id == null) { - if (other.id != null) { - return false; - } - } else if (!id.equals(other.id)) { - return false; - } - - if(!equals(validationRegEx, other.validationRegEx) || - !equals(validationMessage, other.validationMessage) || - !equals(uiHint, other.uiHint) || - !equals(rbKeyValidationMessage, other.rbKeyValidationMessage)) { - return false; - } - - if (label == null) { - if (other.label != null) { - return false; - } - } else if (!label.equals(other.label)) { - return false; - } - if (level == null) { - if (other.level != null) { - return false; - } - } else if (!level.equals(other.level)) { - return false; - } - if (lookUpSupported != other.lookUpSupported) { - return false; - } - if (mandatory != other.mandatory) { - return false; - } - if (matcher == null) { - if (other.matcher != null) { - return false; - } - } else if (!matcher.equals(other.matcher)) { - return false; - } - if (matcherOptions == null) { - if (other.matcherOptions != null) { - return false; - } - } else if (!matcherOptions.equals(other.matcherOptions)) { - return false; - } - if (name == null) { - if (other.name != null) { - return false; - } - } else if (!name.equals(other.name)) { - return false; - } - if (order == null) { - if (other.order != null) { - return false; - } - } else if (!order.equals(other.order)) { - return false; - } - if (parent == null) { - if (other.parent != null) { - return false; - } - } else if (!parent.equals(other.parent)) { - return false; - } - if (rbKeyDescription == null) { - if (other.rbKeyDescription != null) { - return false; - } - } else if (!rbKeyDescription.equals(other.rbKeyDescription)) { - return false; - } - if (rbKeyLabel == null) { - if (other.rbKeyLabel != null) { - return false; - } - } else if (!rbKeyLabel.equals(other.rbKeyLabel)) { - return false; - } - if (recursiveSupported != other.recursiveSupported) { - return false; - } - if (type == null) { - if (other.type != null) { - return false; - } - } else if (!type.equals(other.type)) { - return false; - } - if (dataMaskOptions == null) { - if (other.dataMaskOptions != null) { - return false; - } - } else if (!dataMaskOptions.equals(other.dataMaskOptions)) { - return false; - } - if (rowFilterOptions == null) { - if (other.rowFilterOptions != null) { - return false; - } - } else if (!rowFilterOptions.equals(other.rowFilterOptions)) { - return false; - } - return true; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#toString() - */ - @Override - public String toString() { - return "XXResourceDef [" + super.toString() + " id=" + id + ", defId=" - + defId + ", itemId=" + itemId + ", name=" + name + ", type=" + type + ", level=" - + level + ", parent=" + parent + ", mandatory=" + mandatory - + ", lookUpSupported=" + lookUpSupported - + ", recursiveSupported=" + recursiveSupported - + ", excludesSupported=" + excludesSupported + ", matcher=" - + matcher + ", matcherOptions=" + matcherOptions - + ", validationRegEx=" + validationRegEx - + ", validationMessage=" + validationMessage - + ", uiHint=" + uiHint - + ", label=" + label + ", description=" + description - + ", rbKeyLabel="+ rbKeyLabel - + ", rbKeyDescription=" + rbKeyDescription - + ", rbKeyValidationMessage=" + rbKeyValidationMessage - + ", order=" + order - + ", dataMaskOptions=" + dataMaskOptions - + ", rowFilterOptions=" + rowFilterOptions - + "]"; - } - + private static final long serialVersionUID = 1L; + + /** + * id of the XXResourceDef + *
    + *
+ */ + @Id + @SequenceGenerator(name = "x_resource_def_SEQ", sequenceName = "x_resource_def_SEQ", allocationSize = 1) + @GeneratedValue(strategy = GenerationType.AUTO, generator = "x_resource_def_SEQ") + @Column(name = "id") + protected Long id; + + /** + * defId of the XXResourceDef + *
    + *
+ */ + @Column(name = "def_id") + protected Long defId; + + /** + * itemId of the XXResourceDef + *
    + *
+ */ + @Column(name = "item_id") + protected Long itemId; + + /** + * name of the XXResourceDef + *
    + *
+ */ + @Column(name = "name") + protected String name; + + /** + * type of the XXResourceDef + *
    + *
+ */ + @Column(name = "type") + protected String type; + + /** + * level of the XXResourceDef + *
    + *
+ */ + @Column(name = "res_level") + protected Integer level; + + /** + * parent of the XXResourceDef + *
    + *
+ */ + @Column(name = "parent") + protected Long parent; + + /** + * mandatory of the XXResourceDef + *
    + *
+ */ + @Column(name = "mandatory") + protected boolean mandatory; + + /** + * lookUpSupported of the XXResourceDef + *
    + *
+ */ + @Column(name = "look_up_supported") + protected boolean lookUpSupported; + + /** + * recursiveSupported of the XXResourceDef + *
    + *
+ */ + @Column(name = "recursive_supported") + protected boolean recursiveSupported; + + /** + * excludesSupported of the XXResourceDef + *
    + *
+ */ + @Column(name = "excludes_supported") + protected boolean excludesSupported; + + /** + * matcher of the XXResourceDef + *
    + *
+ */ + @Column(name = "matcher") + protected String matcher; + + /** + * matcherOptions of the XXResourceDef + *
    + *
+ */ + @Column(name = "matcher_options") + protected String matcherOptions; + + /** + * validationRegEx of the XXResourceDef + *
    + *
+ */ + @Column(name = "validation_reg_ex") + protected String validationRegEx; + + /** + * validationMessage of the XXResourceDef + *
    + *
+ */ + @Column(name = "validation_message") + protected String validationMessage; + + /** + * uiHint of the XXResourceDef + *
    + *
+ */ + @Column(name = "ui_hint") + protected String uiHint; + + /** + * label of the XXResourceDef + *
    + *
+ */ + @Column(name = "label") + protected String label; + + /** + * description of the XXResourceDef + *
    + *
+ */ + @Column(name = "description") + protected String description; + + /** + * rbKeyLabel of the XXResourceDef + *
    + *
+ */ + @Column(name = "rb_key_label") + protected String rbKeyLabel; + + /** + * rbKeyDescription of the XXResourceDef + *
    + *
+ */ + @Column(name = "rb_key_description") + protected String rbKeyDescription; + + /** + * rbKeyValidationMessage of the XXResourceDef + *
    + *
+ */ + @Column(name = "rb_key_validation_message") + protected String rbKeyValidationMessage; + + /** + * order of the XXResourceDef + *
    + *
+ */ + @Column(name = "sort_order") + protected Integer order; + + /** + * dataMaskOptions of the XXResourceDef + *
    + *
+ */ + @Column(name = "datamask_options") + protected String dataMaskOptions; + + /** + * rowFilterOptions of the XXAccessTypeDef + *
    + *
+ */ + @Column(name = "rowfilter_options") + protected String rowFilterOptions; + + /** + * Returns the value for the member attribute id + * + * @return Date - value of member attribute id . + */ + public Long getId() { + return this.id; + } + + /** + * This method sets the value to the member attribute id . You + * cannot set null to the attribute. + * + * @param id Value to set member attribute id + */ + public void setId(Long id) { + this.id = id; + } + + @Override + public int hashCode() { + return super.hashCode(); + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#equals(java.lang.Object) + */ + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } else if (!super.equals(obj)) { + return false; + } + + XXResourceDef other = (XXResourceDef) obj; + + return Objects.equals(defId, other.defId) && + Objects.equals(itemId, other.itemId) && + Objects.equals(description, other.description) && + Objects.equals(excludesSupported, other.excludesSupported) && + Objects.equals(id, other.id) && + Objects.equals(validationRegEx, other.validationRegEx) && + Objects.equals(validationMessage, other.validationMessage) && + Objects.equals(uiHint, other.uiHint) && + Objects.equals(rbKeyValidationMessage, other.rbKeyValidationMessage) && + Objects.equals(label, other.label) && + Objects.equals(lookUpSupported, other.lookUpSupported) && + Objects.equals(mandatory, other.mandatory) && + Objects.equals(matcher, other.matcher) && + Objects.equals(matcherOptions, other.matcherOptions) && + Objects.equals(name, other.name) && + Objects.equals(order, other.order) && + Objects.equals(parent, other.parent) && + Objects.equals(rbKeyDescription, other.rbKeyDescription) && + Objects.equals(rbKeyLabel, other.rbKeyLabel) && + Objects.equals(recursiveSupported, other.recursiveSupported) && + Objects.equals(type, other.type) && + Objects.equals(dataMaskOptions, other.dataMaskOptions) && + Objects.equals(rowFilterOptions, other.rowFilterOptions); + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + return "XXResourceDef [" + super.toString() + " id=" + id + ", defId=" + + defId + ", itemId=" + itemId + ", name=" + name + ", type=" + type + ", level=" + + level + ", parent=" + parent + ", mandatory=" + mandatory + + ", lookUpSupported=" + lookUpSupported + + ", recursiveSupported=" + recursiveSupported + + ", excludesSupported=" + excludesSupported + ", matcher=" + matcher + + ", matcherOptions=" + matcherOptions + + ", validationRegEx=" + validationRegEx + + ", validationMessage=" + validationMessage + + ", uiHint=" + uiHint + + ", label=" + label + ", description=" + description + + ", rbKeyLabel=" + rbKeyLabel + + ", rbKeyDescription=" + rbKeyDescription + + ", rbKeyValidationMessage=" + rbKeyValidationMessage + + ", order=" + order + + ", dataMaskOptions=" + dataMaskOptions + + ", rowFilterOptions=" + rowFilterOptions + + "]"; + } + + /** + * Returns the value for the member attribute itemId + * + * @return Long - value of member attribute itemId . + */ + public Long getItemId() { + return this.itemId; + } + + /** + * This method sets the value to the member attribute itemId . You + * cannot set null to the attribute. + * + * @param itemId Value to set member attribute itemId + */ + public void setItemId(Long itemId) { + this.itemId = itemId; + } + + /** + * Returns the value for the member attribute defId + * + * @return Date - value of member attribute defId . + */ + public Long getDefid() { + return this.defId; + } + + /** + * This method sets the value to the member attribute defId . You + * cannot set null to the attribute. + * + * @param defId Value to set member attribute defId + */ + public void setDefid(Long defId) { + this.defId = defId; + } + + /** + * Returns the value for the member attribute name + * + * @return Date - value of member attribute name . + */ + public String getName() { + return this.name; + } + + /** + * This method sets the value to the member attribute name . You + * cannot set null to the attribute. + * + * @param name Value to set member attribute name + */ + public void setName(String name) { + this.name = name; + } + + /** + * Returns the value for the member attribute type + * + * @return Date - value of member attribute type . + */ + public String getType() { + return this.type; + } + + /** + * This method sets the value to the member attribute type . You + * cannot set null to the attribute. + * + * @param type Value to set member attribute type + */ + public void setType(String type) { + this.type = type; + } + + /** + * Returns the value for the member attribute level + * + * @return Date - value of member attribute level . + */ + public Integer getLevel() { + return this.level; + } + + /** + * This method sets the value to the member attribute level . You + * cannot set null to the attribute. + * + * @param level Value to set member attribute level + */ + public void setLevel(Integer level) { + this.level = level; + } + + /** + * Returns the value for the member attribute parent + * + * @return Date - value of member attribute parent . + */ + public Long getParent() { + return this.parent; + } + + /** + * This method sets the value to the member attribute parent . You + * cannot set null to the attribute. + * + * @param parent Value to set member attribute parent + */ + public void setParent(Long parent) { + this.parent = parent; + } + + /** + * Returns the value for the member attribute mandatory + * + * @return Date - value of member attribute mandatory . + */ + public boolean getMandatory() { + return this.mandatory; + } + + /** + * This method sets the value to the member attribute mandatory . + * You cannot set null to the attribute. + * + * @param mandatory Value to set member attribute mandatory + */ + public void setMandatory(boolean mandatory) { + this.mandatory = mandatory; + } + + /** + * Returns the value for the member attribute lookUpSupported + * + * @return Date - value of member attribute lookUpSupported . + */ + public boolean getLookupsupported() { + return this.lookUpSupported; + } + + /** + * This method sets the value to the member attribute + * lookUpSupported . You cannot set null to the attribute. + * + * @param lookUpSupported Value to set member attribute lookUpSupported + */ + public void setLookupsupported(boolean lookUpSupported) { + this.lookUpSupported = lookUpSupported; + } + + /** + * Returns the value for the member attribute recursiveSupported + * + * @return Date - value of member attribute recursiveSupported . + */ + public boolean getRecursivesupported() { + return this.recursiveSupported; + } + + /** + * This method sets the value to the member attribute + * recursiveSupported . You cannot set null to the attribute. + * + * @param recursiveSupported Value to set member attribute recursiveSupported + */ + public void setRecursivesupported(boolean recursiveSupported) { + this.recursiveSupported = recursiveSupported; + } + + /** + * Returns the value for the member attribute excludesSupported + * + * @return Date - value of member attribute excludesSupported . + */ + public boolean getExcludessupported() { + return this.excludesSupported; + } + + /** + * This method sets the value to the member attribute + * excludesSupported . You cannot set null to the attribute. + * + * @param excludesSupported Value to set member attribute excludesSupported + */ + public void setExcludessupported(boolean excludesSupported) { + this.excludesSupported = excludesSupported; + } + + /** + * Returns the value for the member attribute matcher + * + * @return Date - value of member attribute matcher . + */ + public String getMatcher() { + return this.matcher; + } + + /** + * This method sets the value to the member attribute matcher . You + * cannot set null to the attribute. + * + * @param matcher Value to set member attribute matcher + */ + public void setMatcher(String matcher) { + this.matcher = matcher; + } + + /** + * Returns the value for the member attribute matcherOptions + * + * @return Date - value of member attribute matcherOptions . + */ + public String getMatcheroptions() { + return this.matcherOptions; + } + + /** + * This method sets the value to the member attribute matcherOptions + * . You cannot set null to the attribute. + * + * @param matcherOptions Value to set member attribute matcherOptions + */ + public void setMatcheroptions(String matcherOptions) { + this.matcherOptions = matcherOptions; + } + + /** + * @return the validationRegEx + */ + public String getValidationRegEx() { + return validationRegEx; + } + + /** + * @param validationRegEx the validationRegEx to set + */ + public void setValidationRegEx(String validationRegEx) { + this.validationRegEx = validationRegEx; + } + + /** + * @return the validationMessage + */ + public String getValidationMessage() { + return validationMessage; + } + + /** + * @param validationMessage the validationMessage to set + */ + public void setValidationMessage(String validationMessage) { + this.validationMessage = validationMessage; + } + + /** + * @return the uiHint + */ + public String getUiHint() { + return uiHint; + } + + /** + * @param uiHint the uiHint to set + */ + public void setUiHint(String uiHint) { + this.uiHint = uiHint; + } + + /** + * Returns the value for the member attribute label + * + * @return Date - value of member attribute label . + */ + public String getLabel() { + return this.label; + } + + /** + * This method sets the value to the member attribute label . You + * cannot set null to the attribute. + * + * @param label Value to set member attribute label + */ + public void setLabel(String label) { + this.label = label; + } + + /** + * Returns the value for the member attribute description + * + * @return Date - value of member attribute description . + */ + public String getDescription() { + return this.description; + } + + /** + * This method sets the value to the member attribute description . + * You cannot set null to the attribute. + * + * @param description Value to set member attribute description + */ + public void setDescription(String description) { + this.description = description; + } + + /** + * Returns the value for the member attribute rbKeyLabel + * + * @return Date - value of member attribute rbKeyLabel . + */ + public String getRbkeylabel() { + return this.rbKeyLabel; + } + + /** + * This method sets the value to the member attribute rbKeyLabel . + * You cannot set null to the attribute. + * + * @param rbKeyLabel Value to set member attribute rbKeyLabel + */ + public void setRbkeylabel(String rbKeyLabel) { + this.rbKeyLabel = rbKeyLabel; + } + + /** + * Returns the value for the member attribute rbKeyDescription + * + * @return Date - value of member attribute rbKeyDescription . + */ + public String getRbkeydescription() { + return this.rbKeyDescription; + } + + /** + * This method sets the value to the member attribute + * rbKeyDescription . You cannot set null to the attribute. + * + * @param rbKeyDescription Value to set member attribute rbKeyDescription + */ + public void setRbkeydescription(String rbKeyDescription) { + this.rbKeyDescription = rbKeyDescription; + } + + /** + * @return the rbKeyValidationMessage + */ + public String getRbKeyValidationMessage() { + return rbKeyValidationMessage; + } + + /** + * @param rbKeyValidationMessage the rbKeyValidationMessage to set + */ + public void setRbKeyValidationMessage(String rbKeyValidationMessage) { + this.rbKeyValidationMessage = rbKeyValidationMessage; + } + + /** + * Returns the value for the member attribute order + * + * @return Date - value of member attribute order . + */ + public Integer getOrder() { + return this.order; + } + + /** + * This method sets the value to the member attribute order . You + * cannot set null to the attribute. + * + * @param order Value to set member attribute order + */ + public void setOrder(Integer order) { + this.order = order; + } + + public String getDataMaskOptions() { + return dataMaskOptions; + } + + public void setDataMaskOptions(String dataMaskOptions) { + this.dataMaskOptions = dataMaskOptions; + } + + public String getRowFilterOptions() { + return rowFilterOptions; + } + + public void setRowFilterOptions(String rowFilterOptions) { + this.rowFilterOptions = rowFilterOptions; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/entity/XXRole.java b/security-admin/src/main/java/org/apache/ranger/entity/XXRole.java index b79e7fa1fb..22660df30c 100644 --- a/security-admin/src/main/java/org/apache/ranger/entity/XXRole.java +++ b/security-admin/src/main/java/org/apache/ranger/entity/XXRole.java @@ -25,6 +25,7 @@ import javax.persistence.Id; import javax.persistence.SequenceGenerator; import javax.persistence.Table; + import java.util.Objects; @Entity @@ -32,6 +33,7 @@ @Table(name = "x_role") public class XXRole extends XXRoleBase implements java.io.Serializable { private static final long serialVersionUID = 1L; + @Id @SequenceGenerator(name = "x_role_SEQ", sequenceName = "x_role_SEQ", initialValue = 1, allocationSize = 1) @GeneratedValue(strategy = GenerationType.AUTO, generator = "x_role_SEQ") @@ -39,23 +41,17 @@ public class XXRole extends XXRoleBase implements java.io.Serializable { protected Long id; @Override - public void setId(Long id) { - this.id = id; - } - - @Override - public Long getId() { - return id; + public int hashCode() { + return Objects.hash(super.hashCode(), id); } @Override public boolean equals(Object obj) { - if (this == obj) + if (this == obj) { return true; - if (getClass() != obj.getClass()) - return false; - if (!super.equals(obj)) + } else if (!super.equals(obj)) { return false; + } XXRole other = (XXRole) obj; @@ -63,12 +59,17 @@ public boolean equals(Object obj) { } @Override - public int hashCode() { - return Objects.hash(super.hashCode(), id); + public String toString() { + return "Role [id=" + id + "]"; } @Override - public String toString() { - return "Role [id=" + id + "]"; + public Long getId() { + return id; + } + + @Override + public void setId(Long id) { + this.id = id; } } diff --git a/security-admin/src/main/java/org/apache/ranger/entity/XXRoleBase.java b/security-admin/src/main/java/org/apache/ranger/entity/XXRoleBase.java index 6a3728bda2..28d4564e44 100644 --- a/security-admin/src/main/java/org/apache/ranger/entity/XXRoleBase.java +++ b/security-admin/src/main/java/org/apache/ranger/entity/XXRoleBase.java @@ -20,6 +20,7 @@ import javax.persistence.Column; import javax.persistence.MappedSuperclass; import javax.persistence.Version; + import java.util.Objects; @MappedSuperclass @@ -42,35 +43,52 @@ public abstract class XXRoleBase extends XXDBBase { @Column(name = "role_text") protected String roleText; + public Long getVersion() { + return version; + } - public Long getVersion() { return version; } - public String getName() { return name; } - public String getDescription() { return description; } - public String getOptions() { return options; } - public String getRoleText() { return roleText; } + public String getName() { + return name; + } public void setName(String name) { this.name = name; } + + public String getDescription() { + return description; + } + public void setDescription(String description) { this.description = description; } + + public String getOptions() { + return options; + } + public void setOptions(String options) { this.options = options; } + + public String getRoleText() { + return roleText; + } + public void setRoleText(String roleText) { this.roleText = roleText; } + @Override + public int hashCode() { + return Objects.hash(super.hashCode(), version, name, options, roleText); + } + @Override public boolean equals(Object obj) { if (this == obj) { return true; - } - if (getClass() != obj.getClass()) { - return false; - } - if (!super.equals(obj)) { + } else if (!super.equals(obj)) { return false; } @@ -82,11 +100,6 @@ public boolean equals(Object obj) { Objects.equals(roleText, other.roleText); } - @Override - public int hashCode() { - return Objects.hash(super.hashCode(), version, name, options, roleText); - } - @Override public String toString() { String str = "XXRoleBase={"; @@ -96,4 +109,3 @@ public String toString() { return str; } } - diff --git a/security-admin/src/main/java/org/apache/ranger/entity/XXRoleRefGroup.java b/security-admin/src/main/java/org/apache/ranger/entity/XXRoleRefGroup.java index 596b9a12ad..6fd26af1b6 100644 --- a/security-admin/src/main/java/org/apache/ranger/entity/XXRoleRefGroup.java +++ b/security-admin/src/main/java/org/apache/ranger/entity/XXRoleRefGroup.java @@ -18,9 +18,6 @@ package org.apache.ranger.entity; -import java.io.Serializable; -import java.util.Objects; - import javax.persistence.Cacheable; import javax.persistence.Column; import javax.persistence.Entity; @@ -30,23 +27,22 @@ import javax.persistence.SequenceGenerator; import javax.persistence.Table; +import java.io.Serializable; +import java.util.Objects; /** * The persistent class for the x_role_ref_group database table. - * */ @Entity @Cacheable -@Table(name="x_role_ref_group") +@Table(name = "x_role_ref_group") public class XXRoleRefGroup extends XXDBBase implements Serializable { - private static final long serialVersionUID = 1L; /** * id of the XXRoleRefGroup *
    *
- * */ @Id @SequenceGenerator(name = "x_role_ref_group_SEQ", sequenceName = "x_role_ref_group_SEQ", allocationSize = 1) @@ -58,7 +54,6 @@ public class XXRoleRefGroup extends XXDBBase implements Serializable { * roleId of the XXRoleRefGroup *
    *
- * */ @Column(name = "role_id") protected Long roleId; @@ -67,7 +62,6 @@ public class XXRoleRefGroup extends XXDBBase implements Serializable { * groupId of the XXRoleRefGroup *
    *
- * */ @Column(name = "group_id") protected Long groupId; @@ -76,7 +70,6 @@ public class XXRoleRefGroup extends XXDBBase implements Serializable { * groupName of the XXRoleRefGroup *
    *
- * */ @Column(name = "group_name") protected String groupName; @@ -85,40 +78,64 @@ public class XXRoleRefGroup extends XXDBBase implements Serializable { * groupType of the XXRoleRefGroup *
    *
- * */ @Column(name = "priv_Type") protected Integer groupType; - /** + /** + * Returns the value for the member attribute id + * + * @return Date - value of member attribute id . + */ + public Long getId() { + return this.id; + } + + /** * This method sets the value to the member attribute id . You * cannot set null to the attribute. * - * @param id - * Value to set member attribute id + * @param id Value to set member attribute id */ public void setId(Long id) { this.id = id; } - /** - * Returns the value for the member attribute id + @Override + public int hashCode() { + return Objects.hash(super.hashCode(), id, roleId, groupId, groupName, groupType); + } + + /* + * (non-Javadoc) * - * @return Date - value of member attribute id . + * @see java.lang.Object#equals(java.lang.Object) */ - public Long getId() { - return this.id; + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } else if (!super.equals(obj)) { + return false; + } + + XXRoleRefGroup other = (XXRoleRefGroup) obj; + + return Objects.equals(id, other.id) && + Objects.equals(roleId, other.roleId) && + Objects.equals(groupId, other.groupId) && + Objects.equals(groupName, other.groupName) && + Objects.equals(groupType, other.groupType); } - /** - * This method sets the value to the member attribute roleId . - * You cannot set null to the attribute. + /* + * (non-Javadoc) * - * @param roleId - * Value to set member attribute roleId + * @see java.lang.Object#toString() */ - public void setRoleId(Long roleId) { - this.roleId = roleId; + @Override + public String toString() { + return "XXRoleRefGroup [" + super.toString() + " id=" + id + ", roleId=" + roleId + ", groupId=" + groupId + ", groupName=" + groupName + ", groupType=" + groupType + "]"; } /** @@ -131,14 +148,13 @@ public Long getRoleId() { } /** - * This method sets the value to the member attribute groupId . + * This method sets the value to the member attribute roleId . * You cannot set null to the attribute. * - * @param groupId - * Value to set member attribute groupId + * @param roleId Value to set member attribute roleId */ - public void setGroupId(Long groupId) { - this.groupId = groupId; + public void setRoleId(Long roleId) { + this.roleId = roleId; } /** @@ -151,82 +167,48 @@ public Long getGroupId() { } /** - * This method sets the value to the member attribute groupName . + * This method sets the value to the member attribute groupId . * You cannot set null to the attribute. * - * @param groupName - * Value to set member attribute groupName + * @param groupId Value to set member attribute groupId */ - public void setGroupName(String groupName) { - this.groupName = groupName; + public void setGroupId(Long groupId) { + this.groupId = groupId; } /** * Returns the value for the member attribute groupName - * */ public String getGroupName() { return groupName; } + /** + * This method sets the value to the member attribute groupName . + * You cannot set null to the attribute. + * + * @param groupName Value to set member attribute groupName + */ + public void setGroupName(String groupName) { + this.groupName = groupName; + } + /** * Returns the value for the member attribute groupType * * @return groupType - value of member attribute groupType . */ public Integer getGroupType() { - return groupType; - } + return groupType; + } /** * This method sets the value to the member attribute groupType . You * cannot set null to the attribute. * - * @param groupType - * Value to set member attribute groupType - */ - public void setGroupType(Integer groupType) { - this.groupType = groupType; - } - - @Override - public int hashCode() { - return Objects.hash(super.hashCode(), id, roleId, groupId, groupName, groupType); - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#equals(java.lang.Object) + * @param groupType Value to set member attribute groupType */ - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - - if (getClass() != obj.getClass()) { - return false; - } - - XXRoleRefGroup other = (XXRoleRefGroup) obj; - - return super.equals(obj) && - Objects.equals(id, other.id) && - Objects.equals(roleId, other.roleId) && - Objects.equals(groupId, other.groupId) && - Objects.equals(groupName, other.groupName) && - Objects.equals(groupType, other.groupType); - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#toString() - */ - @Override - public String toString() { - return "XXRoleRefGroup [" + super.toString() + " id=" + id + ", roleId=" + roleId +", groupId=" + groupId - + ", groupName=" + groupName + ", groupType=" + groupType + "]"; + public void setGroupType(Integer groupType) { + this.groupType = groupType; } } diff --git a/security-admin/src/main/java/org/apache/ranger/entity/XXRoleRefRole.java b/security-admin/src/main/java/org/apache/ranger/entity/XXRoleRefRole.java index b2b60ff5c6..a9e7407606 100644 --- a/security-admin/src/main/java/org/apache/ranger/entity/XXRoleRefRole.java +++ b/security-admin/src/main/java/org/apache/ranger/entity/XXRoleRefRole.java @@ -18,9 +18,6 @@ package org.apache.ranger.entity; -import java.io.Serializable; -import java.util.Objects; - import javax.persistence.Cacheable; import javax.persistence.Column; import javax.persistence.Entity; @@ -30,22 +27,22 @@ import javax.persistence.SequenceGenerator; import javax.persistence.Table; +import java.io.Serializable; +import java.util.Objects; + /** * The persistent class for the x_role_ref_role database table. - * */ @Entity @Cacheable -@Table(name="x_role_ref_role") +@Table(name = "x_role_ref_role") public class XXRoleRefRole extends XXDBBase implements Serializable { - private static final long serialVersionUID = 1L; /** * id of the XXRoleRefRole *
    *
- * */ @Id @SequenceGenerator(name = "x_role_ref_role_SEQ", sequenceName = "x_role_ref_role_SEQ", allocationSize = 1) @@ -57,7 +54,6 @@ public class XXRoleRefRole extends XXDBBase implements Serializable { * roleId of the XXRoleRefRole *
    *
- * */ @Column(name = "role_id") protected Long roleId; @@ -66,7 +62,6 @@ public class XXRoleRefRole extends XXDBBase implements Serializable { * subRoleId of the XXRoleRefRole *
    *
- * */ @Column(name = "role_ref_id") protected Long subRoleId; @@ -75,7 +70,6 @@ public class XXRoleRefRole extends XXDBBase implements Serializable { * subRoleName of the XXRoleRefRole *
    *
- * */ @Column(name = "role_name") protected String subRoleName; @@ -84,40 +78,64 @@ public class XXRoleRefRole extends XXDBBase implements Serializable { * subRoleType of the XXRoleRefRole *
    *
- * */ @Column(name = "priv_type") protected Integer subRoleType; - /** + /** + * Returns the value for the member attribute id + * + * @return Date - value of member attribute id . + */ + public Long getId() { + return this.id; + } + + /** * This method sets the value to the member attribute id . You * cannot set null to the attribute. * - * @param id - * Value to set member attribute id + * @param id Value to set member attribute id */ public void setId(Long id) { this.id = id; } - /** - * Returns the value for the member attribute id + @Override + public int hashCode() { + return Objects.hash(super.hashCode(), id, roleId, subRoleId, subRoleName, subRoleType); + } + + /* + * (non-Javadoc) * - * @return Date - value of member attribute id . + * @see java.lang.Object#equals(java.lang.Object) */ - public Long getId() { - return this.id; + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } else if (!super.equals(obj)) { + return false; + } + + XXRoleRefRole other = (XXRoleRefRole) obj; + + return Objects.equals(id, other.id) && + Objects.equals(roleId, other.roleId) && + Objects.equals(subRoleId, other.subRoleId) && + Objects.equals(subRoleName, other.subRoleName) && + Objects.equals(subRoleType, other.subRoleType); } - /** - * This method sets the value to the member attribute roleId . - * You cannot set null to the attribute. + /* + * (non-Javadoc) * - * @param roleId - * Value to set member attribute roleId + * @see java.lang.Object#toString() */ - public void setRoleId(Long roleId) { - this.roleId = roleId; + @Override + public String toString() { + return "XXRoleRefRole [" + super.toString() + " id=" + id + ", roleId=" + roleId + ", subRoleId=" + subRoleId + ", subRoleName=" + subRoleName + ", subRoleType=" + subRoleType + "]"; } /** @@ -130,14 +148,13 @@ public Long getRoleId() { } /** - * This method sets the value to the member attribute subRoleId . + * This method sets the value to the member attribute roleId . * You cannot set null to the attribute. * - * @param subRoleId - * Value to set member attribute subRoleId + * @param roleId Value to set member attribute roleId */ - public void setSubRoleId(Long subRoleId) { - this.subRoleId = subRoleId; + public void setRoleId(Long roleId) { + this.roleId = roleId; } /** @@ -150,82 +167,48 @@ public Long getSubRoleId() { } /** - * This method sets the value to the member attribute subRoleName . + * This method sets the value to the member attribute subRoleId . * You cannot set null to the attribute. * - * @param subRoleName - * Value to set member attribute subRoleName + * @param subRoleId Value to set member attribute subRoleId */ - public void setSubRoleName(String subRoleName) { - this.subRoleName = subRoleName; + public void setSubRoleId(Long subRoleId) { + this.subRoleId = subRoleId; } /** * Returns the value for the member attribute subRoleName - * */ public String getSubRoleName() { return subRoleName; } + /** + * This method sets the value to the member attribute subRoleName . + * You cannot set null to the attribute. + * + * @param subRoleName Value to set member attribute subRoleName + */ + public void setSubRoleName(String subRoleName) { + this.subRoleName = subRoleName; + } + /** * Returns the value for the member attribute subRoleType * * @return subRoleType - value of member attribute subRoleType . */ public Integer getSubRoleType() { - return subRoleType; - } + return subRoleType; + } /** * This method sets the value to the member attribute subRoleType . You * cannot set null to the attribute. * - * @param subRoleType - * Value to set member attribute subRoleType + * @param subRoleType Value to set member attribute subRoleType */ - public void setSubRoleType(Integer subRoleType) { - this.subRoleType = subRoleType; - } - - @Override - public int hashCode() { - return Objects.hash(super.hashCode(), id, roleId, subRoleId, subRoleName, subRoleType); - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#equals(java.lang.Object) - */ - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - - if (getClass() != obj.getClass()) { - return false; - } - - XXRoleRefRole other = (XXRoleRefRole) obj; - - return super.equals(obj) && - Objects.equals(id, other.id) && - Objects.equals(roleId, other.roleId) && - Objects.equals(subRoleId, other.subRoleId) && - Objects.equals(subRoleName, other.subRoleName) && - Objects.equals(subRoleType, other.subRoleType); - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#toString() - */ - @Override - public String toString() { - return "XXRoleRefRole [" + super.toString() + " id=" + id + ", roleId=" + roleId +", subRoleId=" + subRoleId - + ", subRoleName=" + subRoleName + ", subRoleType=" + subRoleType + "]"; + public void setSubRoleType(Integer subRoleType) { + this.subRoleType = subRoleType; } } diff --git a/security-admin/src/main/java/org/apache/ranger/entity/XXRoleRefUser.java b/security-admin/src/main/java/org/apache/ranger/entity/XXRoleRefUser.java index 24926506fa..4223647eda 100644 --- a/security-admin/src/main/java/org/apache/ranger/entity/XXRoleRefUser.java +++ b/security-admin/src/main/java/org/apache/ranger/entity/XXRoleRefUser.java @@ -18,9 +18,6 @@ package org.apache.ranger.entity; -import java.io.Serializable; -import java.util.Objects; - import javax.persistence.Cacheable; import javax.persistence.Column; import javax.persistence.Entity; @@ -30,23 +27,22 @@ import javax.persistence.SequenceGenerator; import javax.persistence.Table; +import java.io.Serializable; +import java.util.Objects; /** * The persistent class for the x_role_ref_user database table. - * */ @Entity @Cacheable -@Table(name="x_role_ref_user") +@Table(name = "x_role_ref_user") public class XXRoleRefUser extends XXDBBase implements Serializable { - private static final long serialVersionUID = 1L; /** * id of the XXRoleRefUser *
    *
- * */ @Id @SequenceGenerator(name = "x_role_ref_user_SEQ", sequenceName = "x_role_ref_user_SEQ", allocationSize = 1) @@ -58,7 +54,6 @@ public class XXRoleRefUser extends XXDBBase implements Serializable { * roleId of the XXRoleRefUser *
    *
- * */ @Column(name = "role_id") protected Long roleId; @@ -67,7 +62,6 @@ public class XXRoleRefUser extends XXDBBase implements Serializable { * userId of the XXRoleRefUser *
    *
- * */ @Column(name = "user_id") protected Long userId; @@ -76,7 +70,6 @@ public class XXRoleRefUser extends XXDBBase implements Serializable { * userName of the XXRoleRefUser *
    *
- * */ @Column(name = "user_name") protected String userName; @@ -85,40 +78,64 @@ public class XXRoleRefUser extends XXDBBase implements Serializable { * userType of the XXRoleRefGroup *
    *
- * */ @Column(name = "priv_type") protected Integer userType; + /** + * Returns the value for the member attribute id + * + * @return Date - value of member attribute id . + */ + public Long getId() { + return this.id; + } + /** * This method sets the value to the member attribute id . You * cannot set null to the attribute. * - * @param id - * Value to set member attribute id + * @param id Value to set member attribute id */ public void setId(Long id) { this.id = id; } - /** - * Returns the value for the member attribute id + @Override + public int hashCode() { + return Objects.hash(super.hashCode(), id, roleId, userId, userName, userType); + } + + /* + * (non-Javadoc) * - * @return Date - value of member attribute id . + * @see java.lang.Object#equals(java.lang.Object) */ - public Long getId() { - return this.id; + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } else if (!super.equals(obj)) { + return false; + } + + XXRoleRefUser other = (XXRoleRefUser) obj; + + return Objects.equals(id, other.id) && + Objects.equals(roleId, other.roleId) && + Objects.equals(userId, other.userId) && + Objects.equals(userName, other.userName) && + Objects.equals(userType, other.userType); } - /** - * This method sets the value to the member attribute roleId . - * You cannot set null to the attribute. + /* + * (non-Javadoc) * - * @param roleId - * Value to set member attribute roleId + * @see java.lang.Object#toString() */ - public void setRoleId(Long roleId) { - this.roleId = roleId; + @Override + public String toString() { + return "XXRoleRefUser [" + super.toString() + " id=" + id + ", roleId=" + roleId + ", userId=" + userId + ", userName=" + userName + ", userType=" + userType + "]"; } /** @@ -131,14 +148,13 @@ public Long getRoleId() { } /** - * This method sets the value to the member attribute userId . + * This method sets the value to the member attribute roleId . * You cannot set null to the attribute. * - * @param userId - * Value to set member attribute userId + * @param roleId Value to set member attribute roleId */ - public void setUserId(Long userId) { - this.userId = userId; + public void setRoleId(Long roleId) { + this.roleId = roleId; } /** @@ -151,82 +167,48 @@ public Long getUserId() { } /** - * This method sets the value to the member attribute userName . + * This method sets the value to the member attribute userId . * You cannot set null to the attribute. * - * @param userName - * Value to set member attribute userName + * @param userId Value to set member attribute userId */ - public void setUserName(String userName) { - this.userName = userName; + public void setUserId(Long userId) { + this.userId = userId; } /** * Returns the value for the member attribute userName - * */ public String getUserName() { return userName; } + /** + * This method sets the value to the member attribute userName . + * You cannot set null to the attribute. + * + * @param userName Value to set member attribute userName + */ + public void setUserName(String userName) { + this.userName = userName; + } + /** * Returns the value for the member attribute userType * * @return userType - value of member attribute userType . */ public Integer getUserType() { - return userType; - } + return userType; + } /** * This method sets the value to the member attribute userType . You * cannot set null to the attribute. * - * @param userType - * Value to set member attribute userType + * @param userType Value to set member attribute userType */ - public void setUserType(Integer userType) { - this.userType = userType; - } - - @Override - public int hashCode() { - return Objects.hash(super.hashCode(), id, roleId, userId, userName, userType); - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#equals(java.lang.Object) - */ - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - - if (getClass() != obj.getClass()) { - return false; - } - - XXRoleRefUser other = (XXRoleRefUser) obj; - - return super.equals(obj) && - Objects.equals(id, other.id) && - Objects.equals(roleId, other.roleId) && - Objects.equals(userId, other.userId) && - Objects.equals(userName, other.userName) && - Objects.equals(userType, other.userType); - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#toString() - */ - @Override - public String toString() { - return "XXRoleRefUser [" + super.toString() + " id=" + id + ", roleId=" + roleId +", userId=" + userId - + ", userName=" + userName + ", userType=" + userType + "]"; + public void setUserType(Integer userType) { + this.userType = userType; } } diff --git a/security-admin/src/main/java/org/apache/ranger/entity/XXSecurityZone.java b/security-admin/src/main/java/org/apache/ranger/entity/XXSecurityZone.java index 0e082d0e86..74e7802b82 100644 --- a/security-admin/src/main/java/org/apache/ranger/entity/XXSecurityZone.java +++ b/security-admin/src/main/java/org/apache/ranger/entity/XXSecurityZone.java @@ -25,6 +25,7 @@ import javax.persistence.Id; import javax.persistence.SequenceGenerator; import javax.persistence.Table; + import java.util.Objects; @Entity @@ -32,41 +33,41 @@ @Table(name = "x_security_zone") public class XXSecurityZone extends XXSecurityZoneBase implements java.io.Serializable { private static final long serialVersionUID = 1L; + @Id @SequenceGenerator(name = "x_security_zone_SEQ", sequenceName = "x_security_zone_SEQ", initialValue = 1, allocationSize = 1) @GeneratedValue(strategy = GenerationType.AUTO, generator = "x_security_zone_SEQ") @Column(name = "id") protected Long id; + @Override + public Long getId() { + return id; + } + @Override public void setId(Long id) { this.id = id; } @Override - public Long getId() { - return id; + public int hashCode() { + return Objects.hash(super.hashCode(), id); } @Override public boolean equals(Object obj) { - if (this == obj) + if (this == obj) { return true; - if (getClass() != obj.getClass()) - return false; - if (!super.equals(obj)) + } else if (!super.equals(obj)) { return false; + } XXSecurityZone other = (XXSecurityZone) obj; return Objects.equals(id, other.id); } - @Override - public int hashCode() { - return Objects.hash(super.hashCode(), id); - } - @Override public String toString() { return "SecurityZone [id=" + id + "]"; diff --git a/security-admin/src/main/java/org/apache/ranger/entity/XXSecurityZoneBase.java b/security-admin/src/main/java/org/apache/ranger/entity/XXSecurityZoneBase.java index e46b2c8a8d..346d8f5248 100644 --- a/security-admin/src/main/java/org/apache/ranger/entity/XXSecurityZoneBase.java +++ b/security-admin/src/main/java/org/apache/ranger/entity/XXSecurityZoneBase.java @@ -20,6 +20,7 @@ import javax.persistence.Column; import javax.persistence.MappedSuperclass; import javax.persistence.Version; + import java.util.Objects; @MappedSuperclass @@ -42,32 +43,52 @@ public abstract class XXSecurityZoneBase extends XXDBBase { @Column(name = "description") protected String description; - public Long getVersion() { return version; } - public String getName() { return name; } - public String getJsonData() { return jsonData; } - public byte[] getGzJsonData() { return gzJsonData; } - public String getDescription() { return description; } + public Long getVersion() { + return version; + } + + public String getName() { + return name; + } public void setName(String name) { this.name = name; } + + public String getJsonData() { + return jsonData; + } + public void setJsonData(String jsonData) { this.jsonData = jsonData; } - public void setGzJsonData(byte[] gzJsonData) { this.gzJsonData = gzJsonData; } + + public byte[] getGzJsonData() { + return gzJsonData; + } + + public void setGzJsonData(byte[] gzJsonData) { + this.gzJsonData = gzJsonData; + } + + public String getDescription() { + return description; + } + public void setDescription(String description) { this.description = description; } + @Override + public int hashCode() { + return Objects.hash(super.hashCode(), version, name, jsonData, gzJsonData); + } + @Override public boolean equals(Object obj) { if (this == obj) { return true; - } - if (getClass() != obj.getClass()) { - return false; - } - if (!super.equals(obj)) { + } else if (!super.equals(obj)) { return false; } @@ -79,11 +100,6 @@ public boolean equals(Object obj) { Objects.equals(gzJsonData, other.gzJsonData); } - @Override - public int hashCode() { - return Objects.hash(super.hashCode(), version, name, jsonData, gzJsonData); - } - @Override public String toString() { String str = "XXSecurityZoneBase={"; diff --git a/security-admin/src/main/java/org/apache/ranger/entity/XXSecurityZoneRefGroup.java b/security-admin/src/main/java/org/apache/ranger/entity/XXSecurityZoneRefGroup.java index 79e0151fe8..337de5d230 100644 --- a/security-admin/src/main/java/org/apache/ranger/entity/XXSecurityZoneRefGroup.java +++ b/security-admin/src/main/java/org/apache/ranger/entity/XXSecurityZoneRefGroup.java @@ -19,7 +19,6 @@ package org.apache.ranger.entity; -import java.util.Objects; import javax.persistence.Cacheable; import javax.persistence.Column; import javax.persistence.Entity; @@ -29,60 +28,63 @@ import javax.persistence.SequenceGenerator; import javax.persistence.Table; +import java.util.Objects; + @Entity @Cacheable @Table(name = "x_security_zone_ref_group") -public class XXSecurityZoneRefGroup extends XXDBBase implements java.io.Serializable{ - private static final long serialVersionUID = 1L; - @Id +public class XXSecurityZoneRefGroup extends XXDBBase implements java.io.Serializable { + private static final long serialVersionUID = 1L; + + @Id @SequenceGenerator(name = "x_sec_zone_ref_group_SEQ", sequenceName = "x_sec_zone_ref_group_SEQ", allocationSize = 1) @GeneratedValue(strategy = GenerationType.AUTO, generator = "x_sec_zone_ref_group_SEQ") @Column(name = "id") protected Long id; - /** - * zoneId of the XXSecurityZoneRefGroup - *
    - *
- * - */ - @Column(name = "zone_id") - protected Long zoneId; - - /** - * groupId of the XXSecurityZoneRefGroup - *
    - *
- * - */ - @Column(name = "group_id") - protected Long groupId; - - /** - * groupName of the XXSecurityZoneRefGroup - *
    - *
- * - */ - @Column(name = "group_name") - protected String groupName; - - /** - * groupType of the XXSecurityZoneRefGroup , 1 for admin,0 for audit user. - *
    - *
- * - */ - @Column(name = "group_type") - protected Integer groupType; - - /** - * This method sets the value to the member attribute id . You - * cannot set null to the attribute. - * - * @param id - * Value to set member attribute id - */ + /** + * zoneId of the XXSecurityZoneRefGroup + *
    + *
+ */ + @Column(name = "zone_id") + protected Long zoneId; + + /** + * groupId of the XXSecurityZoneRefGroup + *
    + *
+ */ + @Column(name = "group_id") + protected Long groupId; + + /** + * groupName of the XXSecurityZoneRefGroup + *
    + *
+ */ + @Column(name = "group_name") + protected String groupName; + + /** + * groupType of the XXSecurityZoneRefGroup , 1 for admin,0 for audit user. + *
    + *
+ */ + @Column(name = "group_type") + protected Integer groupType; + + @Override + public Long getId() { + return id; + } + + /** + * This method sets the value to the member attribute id . You + * cannot set null to the attribute. + * + * @param id Value to set member attribute id + */ @Override public void setId(Long id) { @@ -90,125 +92,113 @@ public void setId(Long id) { } @Override - public Long getId() { - return id; + public int hashCode() { + return Objects.hash(super.hashCode(), id, zoneId, groupId, groupName, groupType); + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#equals(java.lang.Object) + */ + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } else if (!super.equals(obj)) { + return false; + } + + XXSecurityZoneRefGroup other = (XXSecurityZoneRefGroup) obj; + + return Objects.equals(id, other.id) && + Objects.equals(zoneId, other.zoneId) && + Objects.equals(groupId, other.groupId) && + Objects.equals(groupName, other.groupName) && + Objects.equals(groupType, other.groupType); + } + + /* (non-Javadoc) + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + return "XXSecurityZoneRefGroup [" + super.toString() + " id=" + id + ", zoneId=" + zoneId + ", groupId=" + groupId + ", groupName=" + groupName + ", groupType=" + groupType + "]"; + } + + /** + * Returns the value for the member attribute zoneId + * + * @return Date - value of member attribute zoneId . + */ + public Long getZoneId() { + return this.zoneId; + } + + /** + * This method sets the value to the member attribute zoneId . + * You cannot set null to the attribute. + * + * @param zoneId Value to set member attribute zoneId + */ + public void setZoneId(Long zoneId) { + this.zoneId = zoneId; + } + + /** + * Returns the value for the member attribute groupId + * + * @return Date - value of member attribute groupId . + */ + public Long getGroupId() { + return groupId; + } + + /** + * This method sets the value to the member attribute groupId . + * You cannot set null to the attribute. + * + * @param groupId Value to set member attribute groupId + */ + public void setGroupId(Long groupId) { + this.groupId = groupId; + } + + /** + * Returns the value for the member attribute groupName + * + * @return Date - value of member attribute groupName . + */ + public String getGroupName() { + return groupName; + } + + /** + * This method sets the value to the member attribute groupName . + * You cannot set null to the attribute. + * + * @param groupName Value to set member attribute groupName + */ + public void setGroupName(String groupName) { + this.groupName = groupName; + } + + /** + * This method sets the value to the member attribute groupType . + * You cannot set null to the attribute. + * + * @param groupType Value to set member attribute groupType + */ + public void setGroupType(Integer groupType) { + this.groupType = groupType; } /** - * This method sets the value to the member attribute zoneId . - * You cannot set null to the attribute. - * - * @param zoneId - * Value to set member attribute zoneId - */ - public void setZoneId(Long zoneId) { - this.zoneId = zoneId; - } - - /** - * Returns the value for the member attribute zoneId - * - * @return Date - value of member attribute zoneId . - */ - public Long getZoneId() { - return this.zoneId; - } - - /** - * This method sets the value to the member attribute groupId . - * You cannot set null to the attribute. - * - * @param groupId - * Value to set member attribute groupId - */ - public void setGroupId(Long groupId) { - this.groupId = groupId; - } - - /** - * Returns the value for the member attribute groupId - * - * @return Date - value of member attribute groupId . - */ - public Long getGroupId() { - return groupId; - } - - /** - * This method sets the value to the member attribute groupName . - * You cannot set null to the attribute. - * - * @param groupName - * Value to set member attribute groupName - */ - public void setGroupName(String groupName) { - this.groupName = groupName; - } - - /** - * Returns the value for the member attribute groupName - * - * @return Date - value of member attribute groupName . - */ - public String getGroupName() { - return groupName; - } - - /** - * This method sets the value to the member attribute groupType . - * You cannot set null to the attribute. - * - * @param groupType - * Value to set member attribute groupType - */ - public void setGroupType(Integer groupType) { - this.groupType = groupType; - } - - /** - * Returns the value for the member attribute groupType - * - * @return Date - value of member attribute groupType . - */ - public Integer getUserType() { - return groupType; - } - @Override - public int hashCode() { - return Objects.hash(super.hashCode(), id, zoneId, groupId, groupName, groupType); - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#equals(java.lang.Object) - */ - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - - if (getClass() != obj.getClass()) { - return false; - } - - XXSecurityZoneRefGroup other = (XXSecurityZoneRefGroup) obj; - - return super.equals(obj) && - Objects.equals(id, other.id) && - Objects.equals(zoneId, other.zoneId) && - Objects.equals(groupId, other.groupId) && - Objects.equals(groupName, other.groupName) && - Objects.equals(groupType, other.groupType); - } - - /* (non-Javadoc) - * @see java.lang.Object#toString() - */ - @Override - public String toString() { - return "XXSecurityZoneRefGroup [" + super.toString() + " id=" + id + ", zoneId=" + zoneId + ", groupId=" - + groupId + ", groupName=" + groupName +", groupType=" + groupType + "]"; - } + * Returns the value for the member attribute groupType + * + * @return Date - value of member attribute groupType . + */ + public Integer getUserType() { + return groupType; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/entity/XXSecurityZoneRefResource.java b/security-admin/src/main/java/org/apache/ranger/entity/XXSecurityZoneRefResource.java index a3e6606c1a..ac5b13383e 100644 --- a/security-admin/src/main/java/org/apache/ranger/entity/XXSecurityZoneRefResource.java +++ b/security-admin/src/main/java/org/apache/ranger/entity/XXSecurityZoneRefResource.java @@ -19,7 +19,6 @@ package org.apache.ranger.entity; -import java.util.Objects; import javax.persistence.Cacheable; import javax.persistence.Column; import javax.persistence.Entity; @@ -29,51 +28,55 @@ import javax.persistence.SequenceGenerator; import javax.persistence.Table; +import java.util.Objects; + @Entity @Cacheable @Table(name = "x_security_zone_ref_resource") -public class XXSecurityZoneRefResource extends XXDBBase implements java.io.Serializable{ - private static final long serialVersionUID = 1L; - @Id +public class XXSecurityZoneRefResource extends XXDBBase implements java.io.Serializable { + private static final long serialVersionUID = 1L; + + @Id @SequenceGenerator(name = "x_sec_zone_ref_resource_SEQ", sequenceName = "x_sec_zone_ref_resource_SEQ", allocationSize = 1) @GeneratedValue(strategy = GenerationType.AUTO, generator = "x_sec_zone_ref_resource_SEQ") @Column(name = "id") protected Long id; - /** - * zoneId of the XXSecurityZoneRefResource - *
    - *
- * - */ - @Column(name = "zone_id") - protected Long zoneId; - - /** - * resourceDefId of the XXSecurityZoneRefResource - *
    - *
- * - */ - @Column(name = "resource_def_id") - protected Long resourceDefId; - - /** - * resourceName of the XXSecurityZoneRefResource - *
    - *
- * - */ - @Column(name = "resource_name") - protected String resourceName; - - /** - * This method sets the value to the member attribute id . You - * cannot set null to the attribute. - * - * @param id - * Value to set member attribute id - */ + /** + * zoneId of the XXSecurityZoneRefResource + *
    + *
+ */ + @Column(name = "zone_id") + protected Long zoneId; + + /** + * resourceDefId of the XXSecurityZoneRefResource + *
    + *
+ */ + @Column(name = "resource_def_id") + protected Long resourceDefId; + + /** + * resourceName of the XXSecurityZoneRefResource + *
    + *
+ */ + @Column(name = "resource_name") + protected String resourceName; + + @Override + public Long getId() { + return id; + } + + /** + * This method sets the value to the member attribute id . You + * cannot set null to the attribute. + * + * @param id Value to set member attribute id + */ @Override public void setId(Long id) { @@ -81,105 +84,93 @@ public void setId(Long id) { } @Override - public Long getId() { - return id; + public int hashCode() { + return Objects.hash(super.hashCode(), id, zoneId, resourceDefId, resourceName); + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#equals(java.lang.Object) + */ + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } else if (!super.equals(obj)) { + return false; + } + + XXSecurityZoneRefResource other = (XXSecurityZoneRefResource) obj; + + return Objects.equals(id, other.id) && + Objects.equals(zoneId, other.zoneId) && + Objects.equals(resourceDefId, other.resourceDefId) && + Objects.equals(resourceName, other.resourceName); + } + + /* (non-Javadoc) + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + return "XXSecurityZoneRefResource [" + super.toString() + " id=" + id + ", zoneId=" + zoneId + ", resourceDefId=" + resourceDefId + ", resourceName=" + resourceName + "]"; + } + + /** + * Returns the value for the member attribute zoneId + * + * @return Date - value of member attribute zoneId . + */ + public Long getZoneId() { + return this.zoneId; + } + + /** + * This method sets the value to the member attribute zoneId . + * You cannot set null to the attribute. + * + * @param zoneId Value to set member attribute zoneId + */ + public void setZoneId(Long zoneId) { + this.zoneId = zoneId; } /** - * This method sets the value to the member attribute zoneId . - * You cannot set null to the attribute. - * - * @param zoneId - * Value to set member attribute zoneId - */ - public void setZoneId(Long zoneId) { - this.zoneId = zoneId; - } - - /** - * Returns the value for the member attribute zoneId - * - * @return Date - value of member attribute zoneId . - */ - public Long getZoneId() { - return this.zoneId; - } - - /** - * This method sets the value to the member attribute resourceDefId . - * You cannot set null to the attribute. - * - * @param resourceDefId - * Value to set member attribute resourceDefId - */ - public void setResourceDefId(Long resourceDefId) { - this.resourceDefId = resourceDefId; - } - - /** - * Returns the value for the member attribute resourceDefId - * - * @return Date - value of member attribute resourceDefId . - */ - public Long getResourceDefId() { - return resourceDefId; - } - - /** - * This method sets the value to the member attribute resourceName . - * You cannot set null to the attribute. - * - * @param resourceName - * Value to set member attribute resourceName - */ - public void setResourceName(String resourceName) { - this.resourceName = resourceName; - } - - /** - * Returns the value for the member attribute resourceName - * - * @return Date - value of member attribute resourceName . - */ - public String getResourceName() { - return resourceName; - } - - @Override - public int hashCode() { - return Objects.hash(super.hashCode(), id, zoneId, resourceDefId, resourceName); - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#equals(java.lang.Object) - */ - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - - if (getClass() != obj.getClass()) { - return false; - } - - XXSecurityZoneRefResource other = (XXSecurityZoneRefResource) obj; - - return super.equals(obj) && - Objects.equals(id, other.id) && - Objects.equals(zoneId, other.zoneId) && - Objects.equals(resourceDefId, other.resourceDefId) && - Objects.equals(resourceName, other.resourceName); - } - - /* (non-Javadoc) - * @see java.lang.Object#toString() - */ - @Override - public String toString() { - return "XXSecurityZoneRefResource [" + super.toString() + " id=" + id + ", zoneId=" + zoneId + ", resourceDefId=" - + resourceDefId + ", resourceName=" + resourceName + "]"; - } + * Returns the value for the member attribute resourceDefId + * + * @return Date - value of member attribute resourceDefId . + */ + public Long getResourceDefId() { + return resourceDefId; + } + + /** + * This method sets the value to the member attribute resourceDefId . + * You cannot set null to the attribute. + * + * @param resourceDefId Value to set member attribute resourceDefId + */ + public void setResourceDefId(Long resourceDefId) { + this.resourceDefId = resourceDefId; + } + + /** + * Returns the value for the member attribute resourceName + * + * @return Date - value of member attribute resourceName . + */ + public String getResourceName() { + return resourceName; + } + + /** + * This method sets the value to the member attribute resourceName . + * You cannot set null to the attribute. + * + * @param resourceName Value to set member attribute resourceName + */ + public void setResourceName(String resourceName) { + this.resourceName = resourceName; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/entity/XXSecurityZoneRefRole.java b/security-admin/src/main/java/org/apache/ranger/entity/XXSecurityZoneRefRole.java index 7da2c4e143..1634461a40 100644 --- a/security-admin/src/main/java/org/apache/ranger/entity/XXSecurityZoneRefRole.java +++ b/security-admin/src/main/java/org/apache/ranger/entity/XXSecurityZoneRefRole.java @@ -27,157 +27,148 @@ import javax.persistence.Id; import javax.persistence.SequenceGenerator; import javax.persistence.Table; + import java.util.Objects; @Entity @Cacheable @Table(name = "x_security_zone_ref_role") -public class XXSecurityZoneRefRole extends XXDBBase implements java.io.Serializable{ - private static final long serialVersionUID = 1L; - @Id +public class XXSecurityZoneRefRole extends XXDBBase implements java.io.Serializable { + private static final long serialVersionUID = 1L; + + @Id @SequenceGenerator(name = "x_sec_zone_ref_role_SEQ", sequenceName = "x_sec_zone_ref_role_SEQ", allocationSize = 1) @GeneratedValue(strategy = GenerationType.AUTO, generator = "x_sec_zone_ref_role_SEQ") @Column(name = "id") protected Long id; - /** - * zoneId of the XXSecurityZoneRefRole - *
    - *
- * - */ - @Column(name = "zone_id") - protected Long zoneId; - - /** - * roleId of the XXSecurityZoneRefRole - *
    - *
- * - */ - @Column(name = "role_id") - protected Long roleId; - - /** - * roleName of the XXSecurityZoneRefRole - *
    - *
- * - */ - @Column(name = "role_name") - protected String roleName; - - /** - * roleType of the XXSecurityZoneRefRole , 1 for admin,0 for audit user. - *
    - *
- * - */ + /** + * zoneId of the XXSecurityZoneRefRole + *
    + *
+ */ + @Column(name = "zone_id") + protected Long zoneId; + + /** + * roleId of the XXSecurityZoneRefRole + *
    + *
+ */ + @Column(name = "role_id") + protected Long roleId; + + /** + * roleName of the XXSecurityZoneRefRole + *
    + *
+ */ + @Column(name = "role_name") + protected String roleName; + + @Override + public Long getId() { + return id; + } + + /** + * roleType of the XXSecurityZoneRefRole , 1 for admin,0 for audit user. + *
    + *
+ */ @Override public void setId(Long id) { this.id = id; } @Override - public Long getId() { - return id; + public int hashCode() { + return Objects.hash(super.hashCode(), id, zoneId, roleId, roleName); + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#equals(java.lang.Object) + */ + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } else if (!super.equals(obj)) { + return false; + } + + XXSecurityZoneRefRole other = (XXSecurityZoneRefRole) obj; + + return Objects.equals(id, other.id) && + Objects.equals(zoneId, other.zoneId) && + Objects.equals(roleId, other.roleId) && + Objects.equals(roleName, other.roleName); + } + + /* (non-Javadoc) + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + return "XXSecurityZoneRefRole [" + super.toString() + " id=" + id + ", zoneId=" + zoneId + ", roleId=" + roleId + ", roleName=" + roleName + "]"; + } + + /** + * Returns the value for the member attribute zoneId + * + * @return Date - value of member attribute zoneId . + */ + public Long getZoneId() { + return this.zoneId; } /** - * This method sets the value to the member attribute zoneId . - * You cannot set null to the attribute. - * - * @param zoneId - * Value to set member attribute zoneId - */ - public void setZoneId(Long zoneId) { - this.zoneId = zoneId; - } - - /** - * Returns the value for the member attribute zoneId - * - * @return Date - value of member attribute zoneId . - */ - public Long getZoneId() { - return this.zoneId; - } - - /** - * This method sets the value to the member attribute roleId . - * You cannot set null to the attribute. - * - * @param roleId - * Value to set member attribute roleId - */ - public void setRoleId(Long roleId) { - this.roleId = roleId; - } - - /** - * Returns the value for the member attribute roleId - * - * @return Date - value of member attribute roleId . - */ - public Long getRoleId() { - return roleId; - } - - /** - * This method sets the value to the member attribute roleName . - * You cannot set null to the attribute. - * - * @param roleName - * Value to set member attribute roleName - */ - public void setRoleName(String roleName) { - this.roleName = roleName; - } - - /** - * Returns the value for the member attribute roleName - * - * @return Date - value of member attribute roleName . - */ - public String getRoleName() { - return roleName; - } - - @Override - public int hashCode() { - return Objects.hash(super.hashCode(), id, zoneId, roleId, roleName); - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#equals(java.lang.Object) - */ - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - - if (getClass() != obj.getClass()) { - return false; - } - - XXSecurityZoneRefRole other = (XXSecurityZoneRefRole) obj; - - return super.equals(obj) && - Objects.equals(id, other.id) && - Objects.equals(zoneId, other.zoneId) && - Objects.equals(roleId, other.roleId) && - Objects.equals(roleName, other.roleName); - } - - /* (non-Javadoc) - * @see java.lang.Object#toString() - */ - @Override - public String toString() { - return "XXSecurityZoneRefRole [" + super.toString() + " id=" + id + ", zoneId=" + zoneId + ", roleId=" - + roleId + ", roleName=" + roleName + "]"; - } + * This method sets the value to the member attribute zoneId . + * You cannot set null to the attribute. + * + * @param zoneId Value to set member attribute zoneId + */ + public void setZoneId(Long zoneId) { + this.zoneId = zoneId; + } + + /** + * Returns the value for the member attribute roleId + * + * @return Date - value of member attribute roleId . + */ + public Long getRoleId() { + return roleId; + } + + /** + * This method sets the value to the member attribute roleId . + * You cannot set null to the attribute. + * + * @param roleId Value to set member attribute roleId + */ + public void setRoleId(Long roleId) { + this.roleId = roleId; + } + + /** + * Returns the value for the member attribute roleName + * + * @return Date - value of member attribute roleName . + */ + public String getRoleName() { + return roleName; + } + + /** + * This method sets the value to the member attribute roleName . + * You cannot set null to the attribute. + * + * @param roleName Value to set member attribute roleName + */ + public void setRoleName(String roleName) { + this.roleName = roleName; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/entity/XXSecurityZoneRefService.java b/security-admin/src/main/java/org/apache/ranger/entity/XXSecurityZoneRefService.java index 14647821fc..dff80e93b1 100644 --- a/security-admin/src/main/java/org/apache/ranger/entity/XXSecurityZoneRefService.java +++ b/security-admin/src/main/java/org/apache/ranger/entity/XXSecurityZoneRefService.java @@ -19,7 +19,6 @@ package org.apache.ranger.entity; -import java.util.Objects; import javax.persistence.Cacheable; import javax.persistence.Column; import javax.persistence.Entity; @@ -29,158 +28,149 @@ import javax.persistence.SequenceGenerator; import javax.persistence.Table; +import java.util.Objects; + @Entity @Cacheable @Table(name = "x_security_zone_ref_service") -public class XXSecurityZoneRefService extends XXDBBase implements java.io.Serializable{ - private static final long serialVersionUID = 1L; - @Id +public class XXSecurityZoneRefService extends XXDBBase implements java.io.Serializable { + private static final long serialVersionUID = 1L; + + @Id @SequenceGenerator(name = "x_sec_zone_ref_service_SEQ", sequenceName = "x_sec_zone_ref_service_SEQ", allocationSize = 1) @GeneratedValue(strategy = GenerationType.AUTO, generator = "x_sec_zone_ref_service_SEQ") @Column(name = "id") protected Long id; - /** - * zoneId of the XXSecurityZoneRefService - *
    - *
- * - */ - @Column(name = "zone_id") - protected Long zoneId; - - /** - * serviceId of the XXSecurityZoneRefService - *
    - *
- * - */ - @Column(name = "service_id") - protected Long serviceId; - - /** - * serviceName of the XXSecurityZoneRefService - *
    - *
- * - */ - @Column(name = "service_name") - protected String serviceName; - - /** - * This method sets the value to the member attribute id . You - * cannot set null to the attribute. - * - * @param id - * Value to set member attribute id - */ - + /** + * zoneId of the XXSecurityZoneRefService + *
    + *
+ */ + @Column(name = "zone_id") + protected Long zoneId; + + /** + * serviceId of the XXSecurityZoneRefService + *
    + *
+ */ + @Column(name = "service_id") + protected Long serviceId; + + /** + * serviceName of the XXSecurityZoneRefService + *
    + *
+ */ + @Column(name = "service_name") + protected String serviceName; + + @Override + public Long getId() { + return id; + } + + /** + * This method sets the value to the member attribute id . You + * cannot set null to the attribute. + * + * @param id Value to set member attribute id + */ + @Override public void setId(Long id) { this.id = id; } @Override - public Long getId() { - return id; + public int hashCode() { + return Objects.hash(super.hashCode(), id, zoneId, serviceId, serviceName); + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#equals(java.lang.Object) + */ + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } else if (!super.equals(obj)) { + return false; + } + + XXSecurityZoneRefService other = (XXSecurityZoneRefService) obj; + + return Objects.equals(id, other.id) && + Objects.equals(zoneId, other.zoneId) && + Objects.equals(serviceId, other.serviceId) && + Objects.equals(serviceName, other.serviceName); + } + + /* (non-Javadoc) + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + return "XXSecurityZoneRefService [" + super.toString() + " id=" + id + ", zoneId=" + zoneId + ", serviceId=" + serviceId + ", serviceName=" + serviceName + "]"; + } + + /** + * Returns the value for the member attribute zoneId + * + * @return Date - value of member attribute zoneId . + */ + public Long getZoneId() { + return this.zoneId; + } + + /** + * This method sets the value to the member attribute zoneId . + * You cannot set null to the attribute. + * + * @param zoneId Value to set member attribute zoneId + */ + public void setZoneId(Long zoneId) { + this.zoneId = zoneId; + } + + /** + * Returns the value for the member attribute serviceId + * + * @return Date - value of member attribute serviceId . + */ + public Long getServiceId() { + return serviceId; + } + + /** + * This method sets the value to the member attribute serviceId . + * You cannot set null to the attribute. + * + * @param serviceId Value to set member attribute serviceId + */ + public void setServiceId(Long serviceId) { + this.serviceId = serviceId; } /** - * This method sets the value to the member attribute zoneId . - * You cannot set null to the attribute. - * - * @param zoneId - * Value to set member attribute zoneId - */ - public void setZoneId(Long zoneId) { - this.zoneId = zoneId; - } - - /** - * Returns the value for the member attribute zoneId - * - * @return Date - value of member attribute zoneId . - */ - public Long getZoneId() { - return this.zoneId; - } - - /** - * This method sets the value to the member attribute serviceId . - * You cannot set null to the attribute. - * - * @param serviceId - * Value to set member attribute serviceId - */ - public void setServiceId(Long serviceId) { - this.serviceId = serviceId; - } - - /** - * Returns the value for the member attribute serviceId - * - * @return Date - value of member attribute serviceId . - */ - public Long getServiceId() { - return serviceId; - } - - /** - * This method sets the value to the member attribute serviceName . - * You cannot set null to the attribute. - * - * @param serviceName - * Value to set member attribute serviceName - */ - public void setServiceName(String serviceName) { - this.serviceName = serviceName; - } - - /** - * Returns the value for the member attribute serviceName - * - * @return Date - value of member attribute serviceName . - */ - public String getServiceName() { - return serviceName; - } - - @Override - public int hashCode() { - return Objects.hash(super.hashCode(), id, zoneId, serviceId, serviceName); - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#equals(java.lang.Object) - */ - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - - if (getClass() != obj.getClass()) { - return false; - } - - XXSecurityZoneRefService other = (XXSecurityZoneRefService) obj; - - return super.equals(obj) && - Objects.equals(id, other.id) && - Objects.equals(zoneId, other.zoneId) && - Objects.equals(serviceId, other.serviceId) && - Objects.equals(serviceName, other.serviceName); - } - - /* (non-Javadoc) - * @see java.lang.Object#toString() - */ - @Override - public String toString() { - return "XXSecurityZoneRefService [" + super.toString() + " id=" + id + ", zoneId=" + zoneId + ", serviceId=" - + serviceId + ", serviceName=" + serviceName + "]"; - } + * Returns the value for the member attribute serviceName + * + * @return Date - value of member attribute serviceName . + */ + public String getServiceName() { + return serviceName; + } + /** + * This method sets the value to the member attribute serviceName . + * You cannot set null to the attribute. + * + * @param serviceName Value to set member attribute serviceName + */ + public void setServiceName(String serviceName) { + this.serviceName = serviceName; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/entity/XXSecurityZoneRefTagService.java b/security-admin/src/main/java/org/apache/ranger/entity/XXSecurityZoneRefTagService.java index d419bc9ed5..aaa44b3fdd 100644 --- a/security-admin/src/main/java/org/apache/ranger/entity/XXSecurityZoneRefTagService.java +++ b/security-admin/src/main/java/org/apache/ranger/entity/XXSecurityZoneRefTagService.java @@ -18,8 +18,6 @@ */ package org.apache.ranger.entity; -import java.util.Objects; - import javax.persistence.Cacheable; import javax.persistence.Column; import javax.persistence.Entity; @@ -28,87 +26,84 @@ import javax.persistence.Id; import javax.persistence.SequenceGenerator; import javax.persistence.Table; + +import java.util.Objects; + @Entity @Cacheable @Table(name = "x_security_zone_ref_tag_srvc") -public class XXSecurityZoneRefTagService extends XXDBBase implements java.io.Serializable{ - private static final long serialVersionUID = 1L; - @Id +public class XXSecurityZoneRefTagService extends XXDBBase implements java.io.Serializable { + private static final long serialVersionUID = 1L; + + @Id @SequenceGenerator(name = "x_sec_zone_ref_tag_srvc_SEQ", sequenceName = "x_sec_zone_ref_tag_srvc_SEQ", allocationSize = 1) @GeneratedValue(strategy = GenerationType.AUTO, generator = "x_sec_zone_ref_tag_srvc_SEQ") @Column(name = "id") protected Long id; - @Column(name = "zone_id") - protected Long zoneId; + @Column(name = "zone_id") + protected Long zoneId; - @Column(name = "tag_srvc_id") - protected Long tagServiceId; + @Column(name = "tag_srvc_id") + protected Long tagServiceId; - @Column(name = "tag_srvc_name") - protected String tagServiceName; + @Column(name = "tag_srvc_name") + protected String tagServiceName; - @Override - public void setId(Long id) { - this.id=id; - } + @Override + public Long getId() { + return id; + } - @Override - public Long getId() { - return id; - } + @Override + public void setId(Long id) { + this.id = id; + } - public Long getZoneId() { - return zoneId; - } + @Override + public int hashCode() { + return Objects.hash(super.hashCode(), id, zoneId, tagServiceId, tagServiceName); + } - public Long getTagServiceId() { - return tagServiceId; + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } else if (!super.equals(obj)) { + return false; } - public String getTagServiceName() { - return tagServiceName; - } - - public void setZoneId(Long zoneId) { - this.zoneId = zoneId; - } + XXSecurityZoneRefTagService other = (XXSecurityZoneRefTagService) obj; - public void setTagServiceId(Long tagServiceId) { - this.tagServiceId = tagServiceId; - } + return Objects.equals(id, other.id) && Objects.equals(zoneId, other.zoneId) && Objects.equals(tagServiceId, other.tagServiceId) && Objects.equals(tagServiceName, other.tagServiceName); + } - public void setTagServiceName(String tagServiceName) { - this.tagServiceName = tagServiceName; - } + @Override + public String toString() { + return "XXSecurityZoneRefTagService [id=" + id + ", zoneId=" + zoneId + ", tagServiceId=" + tagServiceId + ", tagServiceName=" + tagServiceName + "]"; + } - @Override - public int hashCode() { - return Objects.hash(super.hashCode(), id, zoneId, tagServiceId, tagServiceName); - } + public Long getZoneId() { + return zoneId; + } - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } + public void setZoneId(Long zoneId) { + this.zoneId = zoneId; + } - if (getClass() != obj.getClass()) { - return false; - } + public Long getTagServiceId() { + return tagServiceId; + } - XXSecurityZoneRefTagService other = (XXSecurityZoneRefTagService) obj; + public void setTagServiceId(Long tagServiceId) { + this.tagServiceId = tagServiceId; + } - return super.equals(obj) && - Objects.equals(id, other.id) && - Objects.equals(zoneId, other.zoneId) && - Objects.equals(tagServiceId, other.tagServiceId) && - Objects.equals(tagServiceName, other.tagServiceName); - } + public String getTagServiceName() { + return tagServiceName; + } - @Override - public String toString() { - return "XXSecurityZoneRefTagService [id=" + id + ", zoneId=" + zoneId + ", tagServiceId=" + tagServiceId - + ", tagServiceName=" + tagServiceName + "]"; - } + public void setTagServiceName(String tagServiceName) { + this.tagServiceName = tagServiceName; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/entity/XXSecurityZoneRefUser.java b/security-admin/src/main/java/org/apache/ranger/entity/XXSecurityZoneRefUser.java index 68e66c2f11..6564455ab6 100644 --- a/security-admin/src/main/java/org/apache/ranger/entity/XXSecurityZoneRefUser.java +++ b/security-admin/src/main/java/org/apache/ranger/entity/XXSecurityZoneRefUser.java @@ -19,7 +19,6 @@ package org.apache.ranger.entity; -import java.util.Objects; import javax.persistence.Cacheable; import javax.persistence.Column; import javax.persistence.Entity; @@ -29,60 +28,63 @@ import javax.persistence.SequenceGenerator; import javax.persistence.Table; +import java.util.Objects; + @Entity @Cacheable @Table(name = "x_security_zone_ref_user") -public class XXSecurityZoneRefUser extends XXDBBase implements java.io.Serializable{ - private static final long serialVersionUID = 1L; - @Id +public class XXSecurityZoneRefUser extends XXDBBase implements java.io.Serializable { + private static final long serialVersionUID = 1L; + + @Id @SequenceGenerator(name = "x_sec_zone_ref_user_SEQ", sequenceName = "x_sec_zone_ref_user_SEQ", allocationSize = 1) @GeneratedValue(strategy = GenerationType.AUTO, generator = "x_sec_zone_ref_user_SEQ") @Column(name = "id") protected Long id; - /** - * zoneId of the XXSecurityZoneRefUser - *
    - *
- * - */ - @Column(name = "zone_id") - protected Long zoneId; - - /** - * userId of the XXSecurityZoneRefUser - *
    - *
- * - */ - @Column(name = "user_id") - protected Long userId; - - /** - * userName of the XXSecurityZoneRefUser - *
    - *
- * - */ - @Column(name = "user_name") - protected String userName; - - /** - * userType of the XXSecurityZoneRefUser , 1 for admin,0 for audit user. - *
    - *
- * - */ - @Column(name = "user_type") - protected Integer userType; - - /** - * This method sets the value to the member attribute id . You - * cannot set null to the attribute. - * - * @param id - * Value to set member attribute id - */ + /** + * zoneId of the XXSecurityZoneRefUser + *
    + *
+ */ + @Column(name = "zone_id") + protected Long zoneId; + + /** + * userId of the XXSecurityZoneRefUser + *
    + *
+ */ + @Column(name = "user_id") + protected Long userId; + + /** + * userName of the XXSecurityZoneRefUser + *
    + *
+ */ + @Column(name = "user_name") + protected String userName; + + /** + * userType of the XXSecurityZoneRefUser , 1 for admin,0 for audit user. + *
    + *
+ */ + @Column(name = "user_type") + protected Integer userType; + + @Override + public Long getId() { + return id; + } + + /** + * This method sets the value to the member attribute id . You + * cannot set null to the attribute. + * + * @param id Value to set member attribute id + */ @Override public void setId(Long id) { @@ -90,125 +92,109 @@ public void setId(Long id) { } @Override - public Long getId() { - return id; + public int hashCode() { + return Objects.hash(super.hashCode(), id, zoneId, userId, userName, userType); + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#equals(java.lang.Object) + */ + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } else if (!super.equals(obj)) { + return false; + } + + XXSecurityZoneRefUser other = (XXSecurityZoneRefUser) obj; + + return Objects.equals(id, other.id) && Objects.equals(zoneId, other.zoneId) && Objects.equals(userId, other.userId) && Objects.equals(userName, other.userName) && Objects.equals(userType, other.userType); + } + + /* (non-Javadoc) + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + return "XXSecurityZoneRefUser [" + super.toString() + " id=" + id + ", zoneId=" + zoneId + ", userId=" + userId + ", userName=" + userName + ", userType=" + userType + "]"; } /** - * This method sets the value to the member attribute zoneId . - * You cannot set null to the attribute. - * - * @param zoneId - * Value to set member attribute zoneId - */ - public void setZoneId(Long zoneId) { - this.zoneId = zoneId; - } - - /** - * Returns the value for the member attribute zoneId - * - * @return Date - value of member attribute zoneId . - */ - public Long getZoneId() { - return this.zoneId; - } - - /** - * This method sets the value to the member attribute userId . - * You cannot set null to the attribute. - * - * @param userId - * Value to set member attribute userId - */ - public void setUserId(Long userId) { - this.userId = userId; - } - - /** - * Returns the value for the member attribute userId - * - * @return Date - value of member attribute userId . - */ - public Long getUserId() { - return userId; - } - - /** - * This method sets the value to the member attribute userName . - * You cannot set null to the attribute. - * - * @param userName - * Value to set member attribute userName - */ - public void setUserName(String userName) { - this.userName = userName; - } - - /** - * Returns the value for the member attribute userName - * - * @return Date - value of member attribute userName . - */ - public String getUserName() { - return userName; - } - - /** - * This method sets the value to the member attribute userType . - * You cannot set null to the attribute. - * - * @param i - * Value to set member attribute userType - */ - public void setUserType(int i) { - this.userType = i; - } - - /** - * Returns the value for the member attribute userType - * - * @return Date - value of member attribute userType . - */ - public Integer getUserType() { - return userType; - } - @Override - public int hashCode() { - return Objects.hash(super.hashCode(), id, zoneId, userId, userName, userType); - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#equals(java.lang.Object) - */ - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - - if (getClass() != obj.getClass()) { - return false; - } - - XXSecurityZoneRefUser other = (XXSecurityZoneRefUser) obj; - - return super.equals(obj) && - Objects.equals(id, other.id) && - Objects.equals(zoneId, other.zoneId) && - Objects.equals(userId, other.userId) && - Objects.equals(userName, other.userName) && - Objects.equals(userType, other.userType); - } - - /* (non-Javadoc) - * @see java.lang.Object#toString() - */ - @Override - public String toString() { - return "XXSecurityZoneRefUser [" + super.toString() + " id=" + id + ", zoneId=" + zoneId + ", userId=" - + userId + ", userName=" + userName +", userType=" + userType + "]"; - } + * Returns the value for the member attribute zoneId + * + * @return Date - value of member attribute zoneId . + */ + public Long getZoneId() { + return this.zoneId; + } + + /** + * This method sets the value to the member attribute zoneId . + * You cannot set null to the attribute. + * + * @param zoneId Value to set member attribute zoneId + */ + public void setZoneId(Long zoneId) { + this.zoneId = zoneId; + } + + /** + * Returns the value for the member attribute userId + * + * @return Date - value of member attribute userId . + */ + public Long getUserId() { + return userId; + } + + /** + * This method sets the value to the member attribute userId . + * You cannot set null to the attribute. + * + * @param userId Value to set member attribute userId + */ + public void setUserId(Long userId) { + this.userId = userId; + } + + /** + * Returns the value for the member attribute userName + * + * @return Date - value of member attribute userName . + */ + public String getUserName() { + return userName; + } + + /** + * This method sets the value to the member attribute userName . + * You cannot set null to the attribute. + * + * @param userName Value to set member attribute userName + */ + public void setUserName(String userName) { + this.userName = userName; + } + + /** + * Returns the value for the member attribute userType + * + * @return Date - value of member attribute userType . + */ + public Integer getUserType() { + return userType; + } + + /** + * This method sets the value to the member attribute userType . + * You cannot set null to the attribute. + * + * @param i Value to set member attribute userType + */ + public void setUserType(int i) { + this.userType = i; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/entity/XXService.java b/security-admin/src/main/java/org/apache/ranger/entity/XXService.java index 0ddad21439..b67113baf8 100644 --- a/security-admin/src/main/java/org/apache/ranger/entity/XXService.java +++ b/security-admin/src/main/java/org/apache/ranger/entity/XXService.java @@ -18,56 +18,64 @@ */ package org.apache.ranger.entity; -import javax.persistence.*; +import javax.persistence.Cacheable; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.SequenceGenerator; +import javax.persistence.Table; + +import java.util.Objects; @Entity @Cacheable @Table(name = "x_service") public class XXService extends XXServiceBase implements java.io.Serializable { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; + + /** + * id of the XXService + *
    + *
+ */ + @Id + @SequenceGenerator(name = "x_service_SEQ", sequenceName = "x_service_SEQ", allocationSize = 1) + @GeneratedValue(strategy = GenerationType.AUTO, generator = "x_service_SEQ") + @Column(name = "id") + protected Long id; + + @Override + public Long getId() { + return id; + } - /** - * id of the XXService - *
    - *
- * - */ - @Id - @SequenceGenerator(name = "x_service_SEQ", sequenceName = "x_service_SEQ", allocationSize = 1) - @GeneratedValue(strategy = GenerationType.AUTO, generator = "x_service_SEQ") - @Column(name = "id") - protected Long id; + @Override + public void setId(Long id) { + this.id = id; + } - @Override - public void setId(Long id) { - this.id = id; - } + @Override + public int hashCode() { + return super.hashCode(); + } - @Override - public Long getId() { - return id; - } + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } else if (!super.equals(obj)) { + return false; + } - @Override - public String toString() { - return "XXService [id=" + id + "]"; - } + XXService other = (XXService) obj; - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (!super.equals(obj)) - return false; - if (getClass() != obj.getClass()) - return false; - XXService other = (XXService) obj; - if (id == null) { - if (other.id != null) - return false; - } else if (!id.equals(other.id)) - return false; - return true; - } + return Objects.equals(id, other.id); + } + @Override + public String toString() { + return "XXService [id=" + id + "]"; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/entity/XXServiceBase.java b/security-admin/src/main/java/org/apache/ranger/entity/XXServiceBase.java index 2abc391fef..0b136e4b2b 100644 --- a/security-admin/src/main/java/org/apache/ranger/entity/XXServiceBase.java +++ b/security-admin/src/main/java/org/apache/ranger/entity/XXServiceBase.java @@ -17,396 +17,376 @@ package org.apache.ranger.entity; -import java.util.Date; -import java.util.Objects; - import javax.persistence.Column; import javax.persistence.MappedSuperclass; import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.persistence.Version; +import java.util.Date; +import java.util.Objects; + @MappedSuperclass public abstract class XXServiceBase extends XXDBBase { - private static final long serialVersionUID = 1L; - - /** - * Global Id for the object - *
    - *
  • The maximum length for this attribute is 512. - *
- * - */ - @Column(name = "guid", unique = true, nullable = false, length = 512) - protected String guid; - - /** - * version of the XXServiceDef - *
    - *
- * - */ - @Version - @Column(name = "version") - protected Long version; - - /** - * type of the XXService - *
    - *
- * - */ - @Column(name = "type") - protected Long type; - - /** - * name of the XXService - *
    - *
- * - */ - @Column(name = "name") - protected String name; - - /** - * displayName of the XXService - *
    - *
- * - */ - @Column(name = "display_name") - protected String displayName; - /** - * tagService of the XXService - *
    - *
- * - */ - @Column(name = "tag_service") - protected Long tagService; - - /** - * policyVersion of the XXService - *
    - *
- * - */ - @Column(name = "policy_version") - protected Long policyVersion; - - /** - * policyUpdateTime of the XXService - *
    - *
- * - */ - @Temporal(TemporalType.TIMESTAMP) - @Column(name = "policy_update_time") - protected Date policyUpdateTime; - - /** - * tagVersion of the XXService - *
    - *
- * - */ - @Column(name = "tag_version") - protected Long tagVersion; - - /** - * tagUpdateTime of the XXService - *
    - *
- * - */ - @Temporal(TemporalType.TIMESTAMP) - @Column(name = "tag_update_time") - protected Date tagUpdateTime; - - /** - * description of the XXService - *
    - *
- * - */ - @Column(name = "description") - protected String description; - - /** - * isEnabled of the XXService - *
    - *
- * - */ - @Column(name = "is_enabled") - protected Boolean isEnabled; - - /** - * @return the gUID - */ - public String getGuid() { - return this.guid; - } - - /** - * @param guid - * the gUID to set - */ - public void setGuid(String guid) { - this.guid = guid; - } - - /** - * This method sets the value to the member attribute version . You - * cannot set null to the attribute. - * - * @param version - * Value to set member attribute version - */ - public void setVersion(Long version) { - this.version = version; - } - - /** - * Returns the value for the member attribute version - * - * @return Date - value of member attribute version . - */ - public Long getVersion() { - return this.version; - } - - /** - * This method sets the value to the member attribute type . You - * cannot set null to the attribute. - * - * @param type - * Value to set member attribute type - */ - public void setType(Long type) { - this.type = type; - } - - /** - * Returns the value for the member attribute type - * - * @return Date - value of member attribute type . - */ - public Long getType() { - return this.type; - } - - /** - * This method sets the value to the member attribute name . You - * cannot set null to the attribute. - * - * @param name - * Value to set member attribute name - */ - public void setName(String name) { - this.name = name; - } - - /** - * Returns the value for the member attribute name - * - * @return Date - value of member attribute name . - */ - public String getName() { - return this.name; - } - - public String getDisplayName() { - return displayName; - } - - public void setDisplayName(String displayName) { - this.displayName = displayName; - } - - /** - * This method sets the value to the member attribute tagService . - * - * @param tagService - * Value to set member attribute tagService - */ - public void setTagService(Long tagService) { - this.tagService = tagService; - } - - /** - * Returns the value for the member attribute tagService - * - * @return Long - value of member attribute tagService . - */ - public Long getTagService() { - return this.tagService; - } - - /** - * This method sets the value to the member attribute policyVersion - * . You cannot set null to the attribute. - * - * @param policyVersion - * Value to set member attribute policyVersion - */ - public void setPolicyVersion(Long policyVersion) { - this.policyVersion = policyVersion; - } - - /** - * Returns the value for the member attribute policyVersion - * - * @return Date - value of member attribute policyVersion . - */ - public Long getPolicyVersion() { - return this.policyVersion; - } - - /** - * This method sets the value to the member attribute - * policyUpdateTime . You cannot set null to the attribute. - * - * @param policyUpdateTime - * Value to set member attribute policyUpdateTime - */ - public void setPolicyUpdateTime(Date policyUpdateTime) { - this.policyUpdateTime = policyUpdateTime; - } - - /** - * Returns the value for the member attribute policyUpdateTime - * - * @return Date - value of member attribute policyUpdateTime . - */ - public Date getPolicyUpdateTime() { - return this.policyUpdateTime; - } - - /** - * This method sets the value to the member attribute tagVersion - * . You cannot set null to the attribute. - * - * @param tagVersion - * Value to set member attribute tagVersion - */ - public void setTagVersion(Long tagVersion) { - this.tagVersion = tagVersion; - } - - /** - * Returns the value for the member attribute tagVersion - * - * @return Long - value of member attribute tagVersion . - */ - public Long getTagVersion() { - return this.tagVersion; - } - - /** - * This method sets the value to the member attribute - * tagUpdateTime . You cannot set null to the attribute. - * - * @param tagUpdateTime - * Value to set member attribute tagUpdateTime - */ - public void setTagUpdateTime(Date tagUpdateTime) { - this.tagUpdateTime = tagUpdateTime; - } - - /** - * Returns the value for the member attribute tagUpdateTime - * - * @return Date - value of member attribute tagUpdateTime . - */ - public Date getTagUpdateTime() { - return this.tagUpdateTime; - } - - /** - * This method sets the value to the member attribute description . - * You cannot set null to the attribute. - * - * @param description - * Value to set member attribute description - */ - public void setDescription(String description) { - this.description = description; - } - - /** - * Returns the value for the member attribute description - * - * @return Date - value of member attribute description . - */ - public String getDescription() { - return this.description; - } - - /** - * This method sets the value to the member attribute isEnabled . - * You cannot set null to the attribute. - * - * @param isEnabled - * Value to set member attribute isEnabled - */ - public void setIsEnabled(Boolean isEnabled) { - this.isEnabled = isEnabled; - } - - /** - * Returns the value for the member attribute isEnabled - * - * @return Date - value of member attribute isEnabled . - */ - public Boolean getIsenabled() { - return this.isEnabled; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#equals(java.lang.Object) - */ - @Override - public boolean equals(Object obj) { - final boolean ret; - - if (this == obj) { - ret = true; - } else if (obj == null || getClass() != obj.getClass()) { - ret = false; - } else { - XXServiceBase other = (XXServiceBase) obj; - - ret = super.equals(obj) && - Objects.equals(description, other.description) && - Objects.equals(isEnabled, other.isEnabled) && - Objects.equals(name, other.name) && - Objects.equals(policyUpdateTime, other.policyUpdateTime) && - Objects.equals(policyVersion, other.policyVersion) && - Objects.equals(tagService, other.tagService) && - Objects.equals(tagVersion, other.tagVersion) && - Objects.equals(tagUpdateTime, other.tagUpdateTime) && - Objects.equals(type, other.type) && - Objects.equals(version, other.version) && - Objects.equals(guid, other.guid); - } - - return ret; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#toString() - */ - @Override - public String toString() { - return "XXServiceBase [" + super.toString() + " guid=" + guid + ", version=" + version + ", type=" + type - + ", name=" + name +", displayName=" + displayName + ", tagService=" + tagService + ", policyVersion=" + policyVersion + ", policyUpdateTime=" + policyUpdateTime - + ", tagVersion=" + tagVersion + ", tagUpdateTime=" + tagUpdateTime - + ", description=" + description + ", isEnabled=" + isEnabled + "]"; - } - + private static final long serialVersionUID = 1L; + + /** + * Global Id for the object + *
    + *
  • The maximum length for this attribute is 512. + *
+ */ + @Column(name = "guid", unique = true, nullable = false, length = 512) + protected String guid; + + /** + * version of the XXServiceDef + *
    + *
+ */ + @Version + @Column(name = "version") + protected Long version; + + /** + * type of the XXService + *
    + *
+ */ + @Column(name = "type") + protected Long type; + + /** + * name of the XXService + *
    + *
+ */ + @Column(name = "name") + protected String name; + + /** + * displayName of the XXService + *
    + *
+ */ + @Column(name = "display_name") + protected String displayName; + /** + * tagService of the XXService + *
    + *
+ */ + @Column(name = "tag_service") + protected Long tagService; + + /** + * policyVersion of the XXService + *
    + *
+ */ + @Column(name = "policy_version") + protected Long policyVersion; + + /** + * policyUpdateTime of the XXService + *
    + *
+ */ + @Temporal(TemporalType.TIMESTAMP) + @Column(name = "policy_update_time") + protected Date policyUpdateTime; + + /** + * tagVersion of the XXService + *
    + *
+ */ + @Column(name = "tag_version") + protected Long tagVersion; + + /** + * tagUpdateTime of the XXService + *
    + *
+ */ + @Temporal(TemporalType.TIMESTAMP) + @Column(name = "tag_update_time") + protected Date tagUpdateTime; + + /** + * description of the XXService + *
    + *
+ */ + @Column(name = "description") + protected String description; + + /** + * isEnabled of the XXService + *
    + *
+ */ + @Column(name = "is_enabled") + protected Boolean isEnabled; + + /** + * @return the gUID + */ + public String getGuid() { + return this.guid; + } + + /** + * @param guid the gUID to set + */ + public void setGuid(String guid) { + this.guid = guid; + } + + /** + * Returns the value for the member attribute version + * + * @return Date - value of member attribute version . + */ + public Long getVersion() { + return this.version; + } + + /** + * This method sets the value to the member attribute version . You + * cannot set null to the attribute. + * + * @param version Value to set member attribute version + */ + public void setVersion(Long version) { + this.version = version; + } + + /** + * Returns the value for the member attribute type + * + * @return Date - value of member attribute type . + */ + public Long getType() { + return this.type; + } + + /** + * This method sets the value to the member attribute type . You + * cannot set null to the attribute. + * + * @param type Value to set member attribute type + */ + public void setType(Long type) { + this.type = type; + } + + /** + * Returns the value for the member attribute name + * + * @return Date - value of member attribute name . + */ + public String getName() { + return this.name; + } + + /** + * This method sets the value to the member attribute name . You + * cannot set null to the attribute. + * + * @param name Value to set member attribute name + */ + public void setName(String name) { + this.name = name; + } + + public String getDisplayName() { + return displayName; + } + + public void setDisplayName(String displayName) { + this.displayName = displayName; + } + + /** + * Returns the value for the member attribute tagService + * + * @return Long - value of member attribute tagService . + */ + public Long getTagService() { + return this.tagService; + } + + /** + * This method sets the value to the member attribute tagService . + * + * @param tagService Value to set member attribute tagService + */ + public void setTagService(Long tagService) { + this.tagService = tagService; + } + + /** + * Returns the value for the member attribute policyVersion + * + * @return Date - value of member attribute policyVersion . + */ + public Long getPolicyVersion() { + return this.policyVersion; + } + + /** + * This method sets the value to the member attribute policyVersion + * . You cannot set null to the attribute. + * + * @param policyVersion Value to set member attribute policyVersion + */ + public void setPolicyVersion(Long policyVersion) { + this.policyVersion = policyVersion; + } + + /** + * Returns the value for the member attribute policyUpdateTime + * + * @return Date - value of member attribute policyUpdateTime . + */ + public Date getPolicyUpdateTime() { + return this.policyUpdateTime; + } + + /** + * This method sets the value to the member attribute + * policyUpdateTime . You cannot set null to the attribute. + * + * @param policyUpdateTime Value to set member attribute policyUpdateTime + */ + public void setPolicyUpdateTime(Date policyUpdateTime) { + this.policyUpdateTime = policyUpdateTime; + } + + /** + * Returns the value for the member attribute tagVersion + * + * @return Long - value of member attribute tagVersion . + */ + public Long getTagVersion() { + return this.tagVersion; + } + + /** + * This method sets the value to the member attribute tagVersion + * . You cannot set null to the attribute. + * + * @param tagVersion Value to set member attribute tagVersion + */ + public void setTagVersion(Long tagVersion) { + this.tagVersion = tagVersion; + } + + /** + * Returns the value for the member attribute tagUpdateTime + * + * @return Date - value of member attribute tagUpdateTime . + */ + public Date getTagUpdateTime() { + return this.tagUpdateTime; + } + + /** + * This method sets the value to the member attribute + * tagUpdateTime . You cannot set null to the attribute. + * + * @param tagUpdateTime Value to set member attribute tagUpdateTime + */ + public void setTagUpdateTime(Date tagUpdateTime) { + this.tagUpdateTime = tagUpdateTime; + } + + /** + * Returns the value for the member attribute description + * + * @return Date - value of member attribute description . + */ + public String getDescription() { + return this.description; + } + + /** + * This method sets the value to the member attribute description . + * You cannot set null to the attribute. + * + * @param description Value to set member attribute description + */ + public void setDescription(String description) { + this.description = description; + } + + /** + * This method sets the value to the member attribute isEnabled . + * You cannot set null to the attribute. + * + * @param isEnabled Value to set member attribute isEnabled + */ + public void setIsEnabled(Boolean isEnabled) { + this.isEnabled = isEnabled; + } + + /** + * Returns the value for the member attribute isEnabled + * + * @return Date - value of member attribute isEnabled . + */ + public Boolean getIsenabled() { + return this.isEnabled; + } + + @Override + public int hashCode() { + return super.hashCode(); + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#equals(java.lang.Object) + */ + @Override + public boolean equals(Object obj) { + final boolean ret; + + if (this == obj) { + ret = true; + } else if (!super.equals(obj)) { + ret = false; + } else { + XXServiceBase other = (XXServiceBase) obj; + + ret = Objects.equals(description, other.description) && + Objects.equals(isEnabled, other.isEnabled) && + Objects.equals(name, other.name) && + Objects.equals(policyUpdateTime, other.policyUpdateTime) && + Objects.equals(policyVersion, other.policyVersion) && + Objects.equals(tagService, other.tagService) && + Objects.equals(tagVersion, other.tagVersion) && + Objects.equals(tagUpdateTime, other.tagUpdateTime) && + Objects.equals(type, other.type) && + Objects.equals(version, other.version) && + Objects.equals(guid, other.guid); + } + + return ret; + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + return "XXServiceBase [" + super.toString() + " guid=" + guid + ", version=" + version + ", type=" + type + + ", name=" + name + ", displayName=" + displayName + ", tagService=" + tagService + ", policyVersion=" + policyVersion + ", policyUpdateTime=" + policyUpdateTime + + ", tagVersion=" + tagVersion + ", tagUpdateTime=" + tagUpdateTime + + ", description=" + description + ", isEnabled=" + isEnabled + "]"; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/entity/XXServiceConfigDef.java b/security-admin/src/main/java/org/apache/ranger/entity/XXServiceConfigDef.java index b58827addd..2ffc4a103c 100644 --- a/security-admin/src/main/java/org/apache/ranger/entity/XXServiceConfigDef.java +++ b/security-admin/src/main/java/org/apache/ranger/entity/XXServiceConfigDef.java @@ -18,624 +18,522 @@ */ package org.apache.ranger.entity; -import javax.persistence.*; +import javax.persistence.Cacheable; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.SequenceGenerator; +import javax.persistence.Table; + +import java.util.Objects; @Entity @Cacheable @Table(name = "x_service_config_def") -public class XXServiceConfigDef extends XXDBBase implements - java.io.Serializable { - private static final long serialVersionUID = 1L; - /** - * id of the XXServiceConfigDef - *
    - *
- * - */ - @Id - @SequenceGenerator(name = "x_service_config_def_SEQ", sequenceName = "x_service_config_def_SEQ", allocationSize = 1) - @GeneratedValue(strategy = GenerationType.AUTO, generator = "x_service_config_def_SEQ") - @Column(name = "id") - protected Long id; - - /** - * defId of the XXServiceConfigDef - *
    - *
- * - */ - @Column(name = "def_id") - protected Long defId; - - /** - * itemId of the XXServiceConfigDef - *
    - *
- * - */ - @Column(name = "item_id") - protected Long itemId; - - /** - * name of the XXServiceConfigDef - *
    - *
- * - */ - @Column(name = "name") - protected String name; - - /** - * type of the XXServiceConfigDef - *
    - *
- * - */ - @Column(name = "type") - protected String type; - - /** - * subType of the XXServiceConfigDef - *
    - *
- * - */ - @Column(name = "sub_type") - protected String subType; - - /** - * isMandatory of the XXServiceConfigDef - *
    - *
- * - */ - @Column(name = "is_mandatory") - protected boolean isMandatory; - - /** - * defaultValue of the XXServiceConfigDef - *
    - *
- * - */ - @Column(name = "default_value") - protected String defaultValue; - - /** - * validationRegEx of the XXServiceConfigDef - *
    - *
- * - */ - @Column(name = "validation_reg_ex") - protected String validationRegEx; - - /** - * validationMessage of the XXServiceConfigDef - *
    - *
- * - */ - @Column(name = "validation_message") - protected String validationMessage; - - /** - * uiHint of the XXServiceConfigDef - *
    - *
- * - */ - @Column(name = "ui_hint") - protected String uiHint; - - /** - * label of the XXServiceConfigDef - *
    - *
- * - */ - @Column(name = "label") - protected String label; - - /** - * description of the XXServiceConfigDef - *
    - *
- * - */ - @Column(name = "description") - protected String description; - - /** - * rbKeyLabel of the XXServiceConfigDef - *
    - *
- * - */ - @Column(name = "rb_key_label") - protected String rbKeyLabel; - - /** - * rbKeyDecription of the XXServiceConfigDef - *
    - *
- * - */ - @Column(name = "rb_key_description") - protected String rbKeyDescription; - - /** - * rbKeyValidationMessage of the XXServiceConfigDef - *
    - *
- * - */ - @Column(name = "rb_key_validation_message") - protected String rbKeyValidationMessage; - - /** - * order of the XXServiceConfigDef - *
    - *
- * - */ - @Column(name = "sort_order") - protected Integer order; - - /** - * This method sets the value to the member attribute id . You - * cannot set null to the attribute. - * - * @param id - * Value to set member attribute id - */ - public void setId(Long id) { - this.id = id; - } - - /** - * Returns the value for the member attribute id - * - * @return Date - value of member attribute id . - */ - public Long getId() { - return this.id; - } - - /** - * This method sets the value to the member attribute defId . You - * cannot set null to the attribute. - * - * @param defId - * Value to set member attribute defId - */ - public void setDefid(Long defId) { - this.defId = defId; - } - - /** - * Returns the value for the member attribute defId - * - * @return Date - value of member attribute defId . - */ - public Long getDefid() { - return this.defId; - } - - /** - * This method sets the value to the member attribute itemId . You - * cannot set null to the attribute. - * - * @param itemId - * Value to set member attribute itemId - */ - public void setItemId(Long itemId) { - this.itemId = itemId; - } - - /** - * Returns the value for the member attribute itemId - * - * @return Long - value of member attribute itemId . - */ - public Long getItemId() { - return this.itemId; - } - - /** - * This method sets the value to the member attribute name . You - * cannot set null to the attribute. - * - * @param name - * Value to set member attribute name - */ - public void setName(String name) { - this.name = name; - } - - /** - * Returns the value for the member attribute name - * - * @return Date - value of member attribute name . - */ - public String getName() { - return this.name; - } - - /** - * This method sets the value to the member attribute type . You - * cannot set null to the attribute. - * - * @param type - * Value to set member attribute type - */ - public void setType(String type) { - this.type = type; - } - - /** - * Returns the value for the member attribute type - * - * @return Date - value of member attribute type . - */ - public String getType() { - return this.type; - } - - /** - * This method sets the value to the member attribute subType . You - * cannot set null to the attribute. - * - * @param subType - * Value to set member attribute subType - */ - public void setSubtype(String subType) { - this.subType = subType; - } - - /** - * Returns the value for the member attribute subType - * - * @return Date - value of member attribute subType . - */ - public String getSubtype() { - return this.subType; - } - - /** - * This method sets the value to the member attribute isMandatory . - * You cannot set null to the attribute. - * - * @param isMandatory - * Value to set member attribute isMandatory - */ - public void setIsMandatory(boolean isMandatory) { - this.isMandatory = isMandatory; - } - - /** - * Returns the value for the member attribute isMandatory - * - * @return Date - value of member attribute isMandatory . - */ - public boolean getIsMandatory() { - return this.isMandatory; - } - - /** - * This method sets the value to the member attribute defaultValue . - * You cannot set null to the attribute. - * - * @param defaultValue - * Value to set member attribute defaultValue - */ - public void setDefaultvalue(String defaultValue) { - this.defaultValue = defaultValue; - } - - /** - * Returns the value for the member attribute defaultValue - * - * @return Date - value of member attribute defaultValue . - */ - public String getDefaultvalue() { - return this.defaultValue; - } - - /** - * @return the validationRegEx - */ - public String getValidationRegEx() { - return validationRegEx; - } - - /** - * @param validationRegEx the validationRegEx to set - */ - public void setValidationRegEx(String validationRegEx) { - this.validationRegEx = validationRegEx; - } - - /** - * @return the validationMessage - */ - public String getValidationMessage() { - return validationMessage; - } - - /** - * @param validationMessage the validationMessage to set - */ - public void setValidationMessage(String validationMessage) { - this.validationMessage = validationMessage; - } - - /** - * @return the uiHint - */ - public String getUiHint() { - return uiHint; - } - - /** - * @param uiHint the uiHint to set - */ - public void setUiHint(String uiHint) { - this.uiHint = uiHint; - } - - /** - * This method sets the value to the member attribute label . You - * cannot set null to the attribute. - * - * @param label - * Value to set member attribute label - */ - public void setLabel(String label) { - this.label = label; - } - - /** - * Returns the value for the member attribute label - * - * @return Date - value of member attribute label . - */ - public String getLabel() { - return this.label; - } - - /** - * This method sets the value to the member attribute description . - * You cannot set null to the attribute. - * - * @param description - * Value to set member attribute description - */ - public void setDescription(String description) { - this.description = description; - } - - /** - * Returns the value for the member attribute description - * - * @return Date - value of member attribute description . - */ - public String getDescription() { - return this.description; - } - - /** - * This method sets the value to the member attribute rbKeyLabel . - * You cannot set null to the attribute. - * - * @param rbKeyLabel - * Value to set member attribute rbKeyLabel - */ - public void setRbkeylabel(String rbKeyLabel) { - this.rbKeyLabel = rbKeyLabel; - } - - /** - * Returns the value for the member attribute rbKeyLabel - * - * @return Date - value of member attribute rbKeyLabel . - */ - public String getRbkeylabel() { - return this.rbKeyLabel; - } - - /** - * This method sets the value to the member attribute - * rbKeyDecription . You cannot set null to the attribute. - * - * @param rbKeyDescription - * Value to set member attribute rbKeyDecription - */ - public void setRbkeydescription(String rbKeyDescription) { - this.rbKeyDescription = rbKeyDescription; - } - - /** - * Returns the value for the member attribute rbKeyDecription - * - * @return Date - value of member attribute rbKeyDecription . - */ - public String getRbkeydescription() { - return this.rbKeyDescription; - } - - /** - * @return the rbKeyValidationMessage - */ - public String getRbKeyValidationMessage() { - return rbKeyValidationMessage; - } - - /** - * @param rbKeyValidationMessage the rbKeyValidationMessage to set - */ - public void setRbKeyValidationMessage(String rbKeyValidationMessage) { - this.rbKeyValidationMessage = rbKeyValidationMessage; - } - - /** - * This method sets the value to the member attribute order . You - * cannot set null to the attribute. - * - * @param order - * Value to set member attribute order - */ - public void setOrder(Integer order) { - this.order = order; - } - - /** - * Returns the value for the member attribute order - * - * @return Date - value of member attribute order . - */ - public Integer getOrder() { - return this.order; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#equals(java.lang.Object) - */ - @Override - public boolean equals(Object obj) { - if (!super.equals(obj)) { - return false; - } - if (this == obj) { - return true; - } - if (!super.equals(obj)) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - XXServiceConfigDef other = (XXServiceConfigDef) obj; - if (defId == null) { - if (other.defId != null) { - return false; - } - } else if (!defId.equals(other.defId)) { - return false; - } - if (itemId == null) { - if (other.itemId != null) { - return false; - } - } else if (!itemId.equals(other.itemId)) { - return false; - } - if (defaultValue == null) { - if (other.defaultValue != null) { - return false; - } - } else if (!defaultValue.equals(other.defaultValue)) { - return false; - } - if (description == null) { - if (other.description != null) { - return false; - } - } else if (!description.equals(other.description)) { - return false; - } - if (id == null) { - if (other.id != null) { - return false; - } - } else if (!id.equals(other.id)) { - return false; - } - if (isMandatory != other.isMandatory) { - return false; - } - - if(!equals(validationRegEx, other.validationRegEx) || - !equals(validationMessage, other.validationMessage) || - !equals(uiHint, other.uiHint) || - !equals(rbKeyValidationMessage, other.rbKeyValidationMessage)) { - return false; - } - - if (label == null) { - if (other.label != null) { - return false; - } - } else if (!label.equals(other.label)) { - return false; - } - if (name == null) { - if (other.name != null) { - return false; - } - } else if (!name.equals(other.name)) { - return false; - } - if (order == null) { - if (other.order != null) { - return false; - } - } else if (!order.equals(other.order)) { - return false; - } - if (rbKeyDescription == null) { - if (other.rbKeyDescription != null) { - return false; - } - } else if (!rbKeyDescription.equals(other.rbKeyDescription)) { - return false; - } - if (rbKeyLabel == null) { - if (other.rbKeyLabel != null) { - return false; - } - } else if (!rbKeyLabel.equals(other.rbKeyLabel)) { - return false; - } - if (subType == null) { - if (other.subType != null) { - return false; - } - } else if (!subType.equals(other.subType)) { - return false; - } - if (type == null) { - if (other.type != null) { - return false; - } - } else if (!type.equals(other.type)) { - return false; - } - - return true; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#toString() - */ - @Override - public String toString() { - return "XXServiceConfigDef [" + super.toString() + " id=" + id - + ", defId=" + defId + ", name=" + name + ", type=" + type - + ", itemId=" + itemId - + ", subType=" + subType + ", isMandatory=" + isMandatory - + ", defaultValue=" + defaultValue + ", label=" + label - + ", validationRegEx=" + validationRegEx - + ", validationMessage=" + validationMessage - + ", uiHint=" + uiHint - + ", description=" + description + ", rbKeyLabel=" + rbKeyLabel - + ", rbKeyValidationMessage=" + rbKeyValidationMessage - + ", rbKeyDecription=" + rbKeyDescription + ", order=" + order - + "]"; - } - +public class XXServiceConfigDef extends XXDBBase implements java.io.Serializable { + private static final long serialVersionUID = 1L; + + /** + * id of the XXServiceConfigDef + *
    + *
+ */ + @Id + @SequenceGenerator(name = "x_service_config_def_SEQ", sequenceName = "x_service_config_def_SEQ", allocationSize = 1) + @GeneratedValue(strategy = GenerationType.AUTO, generator = "x_service_config_def_SEQ") + @Column(name = "id") + protected Long id; + + /** + * defId of the XXServiceConfigDef + *
    + *
+ */ + @Column(name = "def_id") + protected Long defId; + + /** + * itemId of the XXServiceConfigDef + *
    + *
+ */ + @Column(name = "item_id") + protected Long itemId; + + /** + * name of the XXServiceConfigDef + *
    + *
+ */ + @Column(name = "name") + protected String name; + + /** + * type of the XXServiceConfigDef + *
    + *
+ */ + @Column(name = "type") + protected String type; + + /** + * subType of the XXServiceConfigDef + *
    + *
+ */ + @Column(name = "sub_type") + protected String subType; + + /** + * isMandatory of the XXServiceConfigDef + *
    + *
+ */ + @Column(name = "is_mandatory") + protected boolean isMandatory; + + /** + * defaultValue of the XXServiceConfigDef + *
    + *
+ */ + @Column(name = "default_value") + protected String defaultValue; + + /** + * validationRegEx of the XXServiceConfigDef + *
    + *
+ */ + @Column(name = "validation_reg_ex") + protected String validationRegEx; + + /** + * validationMessage of the XXServiceConfigDef + *
    + *
+ */ + @Column(name = "validation_message") + protected String validationMessage; + + /** + * uiHint of the XXServiceConfigDef + *
    + *
+ */ + @Column(name = "ui_hint") + protected String uiHint; + + /** + * label of the XXServiceConfigDef + *
    + *
+ */ + @Column(name = "label") + protected String label; + + /** + * description of the XXServiceConfigDef + *
    + *
+ */ + @Column(name = "description") + protected String description; + + /** + * rbKeyLabel of the XXServiceConfigDef + *
    + *
+ */ + @Column(name = "rb_key_label") + protected String rbKeyLabel; + + /** + * rbKeyDecription of the XXServiceConfigDef + *
    + *
+ */ + @Column(name = "rb_key_description") + protected String rbKeyDescription; + + /** + * rbKeyValidationMessage of the XXServiceConfigDef + *
    + *
+ */ + @Column(name = "rb_key_validation_message") + protected String rbKeyValidationMessage; + + /** + * order of the XXServiceConfigDef + *
    + *
+ */ + @Column(name = "sort_order") + protected Integer order; + + /** + * Returns the value for the member attribute id + * + * @return Date - value of member attribute id . + */ + public Long getId() { + return this.id; + } + + /** + * This method sets the value to the member attribute id . You + * cannot set null to the attribute. + * + * @param id Value to set member attribute id + */ + public void setId(Long id) { + this.id = id; + } + + @Override + public int hashCode() { + return super.hashCode(); + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#equals(java.lang.Object) + */ + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } else if (!super.equals(obj)) { + return false; + } + + XXServiceConfigDef other = (XXServiceConfigDef) obj; + + return Objects.equals(defId, other.defId) && + Objects.equals(itemId, other.itemId) && + Objects.equals(defaultValue, other.defaultValue) && + Objects.equals(description, other.description) && + Objects.equals(id, other.id) && + Objects.equals(isMandatory, other.isMandatory) && + Objects.equals(validationRegEx, other.validationRegEx) && + Objects.equals(validationMessage, other.validationMessage) && + Objects.equals(uiHint, other.uiHint) && + Objects.equals(rbKeyValidationMessage, other.rbKeyValidationMessage) && + Objects.equals(label, other.label) && + Objects.equals(name, other.name) && + Objects.equals(order, other.order) && + Objects.equals(rbKeyDescription, other.rbKeyDescription) && + Objects.equals(rbKeyLabel, other.rbKeyLabel) && + Objects.equals(subType, other.subType) && + Objects.equals(type, other.type); + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + return "XXServiceConfigDef [" + super.toString() + " id=" + id + + ", defId=" + defId + ", name=" + name + ", type=" + type + + ", itemId=" + itemId + + ", subType=" + subType + ", isMandatory=" + isMandatory + + ", defaultValue=" + defaultValue + ", label=" + label + + ", validationRegEx=" + validationRegEx + + ", validationMessage=" + validationMessage + + ", uiHint=" + uiHint + + ", description=" + description + ", rbKeyLabel=" + rbKeyLabel + + ", rbKeyValidationMessage=" + rbKeyValidationMessage + + ", rbKeyDecription=" + rbKeyDescription + ", order=" + order + + "]"; + } + + /** + * Returns the value for the member attribute defId + * + * @return Date - value of member attribute defId . + */ + public Long getDefid() { + return this.defId; + } + + /** + * This method sets the value to the member attribute defId . You + * cannot set null to the attribute. + * + * @param defId Value to set member attribute defId + */ + public void setDefid(Long defId) { + this.defId = defId; + } + + /** + * Returns the value for the member attribute itemId + * + * @return Long - value of member attribute itemId . + */ + public Long getItemId() { + return this.itemId; + } + + /** + * This method sets the value to the member attribute itemId . You + * cannot set null to the attribute. + * + * @param itemId Value to set member attribute itemId + */ + public void setItemId(Long itemId) { + this.itemId = itemId; + } + + /** + * Returns the value for the member attribute name + * + * @return Date - value of member attribute name . + */ + public String getName() { + return this.name; + } + + /** + * This method sets the value to the member attribute name . You + * cannot set null to the attribute. + * + * @param name Value to set member attribute name + */ + public void setName(String name) { + this.name = name; + } + + /** + * Returns the value for the member attribute type + * + * @return Date - value of member attribute type . + */ + public String getType() { + return this.type; + } + + /** + * This method sets the value to the member attribute type . You + * cannot set null to the attribute. + * + * @param type Value to set member attribute type + */ + public void setType(String type) { + this.type = type; + } + + /** + * Returns the value for the member attribute subType + * + * @return Date - value of member attribute subType . + */ + public String getSubtype() { + return this.subType; + } + + /** + * This method sets the value to the member attribute subType . You + * cannot set null to the attribute. + * + * @param subType Value to set member attribute subType + */ + public void setSubtype(String subType) { + this.subType = subType; + } + + /** + * Returns the value for the member attribute isMandatory + * + * @return Date - value of member attribute isMandatory . + */ + public boolean getIsMandatory() { + return this.isMandatory; + } + + /** + * This method sets the value to the member attribute isMandatory . + * You cannot set null to the attribute. + * + * @param isMandatory Value to set member attribute isMandatory + */ + public void setIsMandatory(boolean isMandatory) { + this.isMandatory = isMandatory; + } + + /** + * Returns the value for the member attribute defaultValue + * + * @return Date - value of member attribute defaultValue . + */ + public String getDefaultvalue() { + return this.defaultValue; + } + + /** + * This method sets the value to the member attribute defaultValue . + * You cannot set null to the attribute. + * + * @param defaultValue Value to set member attribute defaultValue + */ + public void setDefaultvalue(String defaultValue) { + this.defaultValue = defaultValue; + } + + /** + * @return the validationRegEx + */ + public String getValidationRegEx() { + return validationRegEx; + } + + /** + * @param validationRegEx the validationRegEx to set + */ + public void setValidationRegEx(String validationRegEx) { + this.validationRegEx = validationRegEx; + } + + /** + * @return the validationMessage + */ + public String getValidationMessage() { + return validationMessage; + } + + /** + * @param validationMessage the validationMessage to set + */ + public void setValidationMessage(String validationMessage) { + this.validationMessage = validationMessage; + } + + /** + * @return the uiHint + */ + public String getUiHint() { + return uiHint; + } + + /** + * @param uiHint the uiHint to set + */ + public void setUiHint(String uiHint) { + this.uiHint = uiHint; + } + + /** + * Returns the value for the member attribute label + * + * @return Date - value of member attribute label . + */ + public String getLabel() { + return this.label; + } + + /** + * This method sets the value to the member attribute label . You + * cannot set null to the attribute. + * + * @param label Value to set member attribute label + */ + public void setLabel(String label) { + this.label = label; + } + + /** + * Returns the value for the member attribute description + * + * @return Date - value of member attribute description . + */ + public String getDescription() { + return this.description; + } + + /** + * This method sets the value to the member attribute description . + * You cannot set null to the attribute. + * + * @param description Value to set member attribute description + */ + public void setDescription(String description) { + this.description = description; + } + + /** + * Returns the value for the member attribute rbKeyLabel + * + * @return Date - value of member attribute rbKeyLabel . + */ + public String getRbkeylabel() { + return this.rbKeyLabel; + } + + /** + * This method sets the value to the member attribute rbKeyLabel . + * You cannot set null to the attribute. + * + * @param rbKeyLabel Value to set member attribute rbKeyLabel + */ + public void setRbkeylabel(String rbKeyLabel) { + this.rbKeyLabel = rbKeyLabel; + } + + /** + * Returns the value for the member attribute rbKeyDecription + * + * @return Date - value of member attribute rbKeyDecription . + */ + public String getRbkeydescription() { + return this.rbKeyDescription; + } + + /** + * This method sets the value to the member attribute + * rbKeyDecription . You cannot set null to the attribute. + * + * @param rbKeyDescription Value to set member attribute rbKeyDecription + */ + public void setRbkeydescription(String rbKeyDescription) { + this.rbKeyDescription = rbKeyDescription; + } + + /** + * @return the rbKeyValidationMessage + */ + public String getRbKeyValidationMessage() { + return rbKeyValidationMessage; + } + + /** + * @param rbKeyValidationMessage the rbKeyValidationMessage to set + */ + public void setRbKeyValidationMessage(String rbKeyValidationMessage) { + this.rbKeyValidationMessage = rbKeyValidationMessage; + } + + /** + * Returns the value for the member attribute order + * + * @return Date - value of member attribute order . + */ + public Integer getOrder() { + return this.order; + } + + /** + * This method sets the value to the member attribute order . You + * cannot set null to the attribute. + * + * @param order Value to set member attribute order + */ + public void setOrder(Integer order) { + this.order = order; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/entity/XXServiceConfigMap.java b/security-admin/src/main/java/org/apache/ranger/entity/XXServiceConfigMap.java index 094c589d29..0fbd66dd60 100644 --- a/security-admin/src/main/java/org/apache/ranger/entity/XXServiceConfigMap.java +++ b/security-admin/src/main/java/org/apache/ranger/entity/XXServiceConfigMap.java @@ -18,194 +18,169 @@ */ package org.apache.ranger.entity; -import javax.persistence.*; +import javax.persistence.Cacheable; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.SequenceGenerator; +import javax.persistence.Table; + +import java.util.Objects; @Entity @Cacheable @Table(name = "x_service_config_map") -public class XXServiceConfigMap extends XXDBBase implements - java.io.Serializable { - private static final long serialVersionUID = 1L; - /** - * id of the XXServiceConfigMap - *
    - *
- * - */ - @Id - @SequenceGenerator(name = "x_service_config_map_SEQ", sequenceName = "x_service_config_map_SEQ", allocationSize = 1) - @GeneratedValue(strategy = GenerationType.AUTO, generator = "x_service_config_map_SEQ") - @Column(name = "id") - protected Long id; - - /** - * service of the XXServiceConfigMap - *
    - *
- * - */ - @Column(name = "service") - protected Long serviceId; - - /** - * configKey of the XXServiceConfigMap - *
    - *
- * - */ - @Column(name = "config_key") - protected String configKey; - - /** - * configValue of the XXServiceConfigMap - *
    - *
- * - */ - @Column(name = "config_value") - protected String configValue; - - /** - * This method sets the value to the member attribute id . You - * cannot set null to the attribute. - * - * @param id - * Value to set member attribute id - */ - public void setId(Long id) { - this.id = id; - } - - /** - * Returns the value for the member attribute id - * - * @return Date - value of member attribute id . - */ - public Long getId() { - return this.id; - } - - /** - * This method sets the value to the member attribute service . You - * cannot set null to the attribute. - * - * @param service - * Value to set member attribute service - */ - public void setServiceId(Long serviceId) { - this.serviceId = serviceId; - } - - /** - * Returns the value for the member attribute service - * - * @return Date - value of member attribute service . - */ - public Long getServiceId() { - return this.serviceId; - } - - /** - * This method sets the value to the member attribute configKey . - * You cannot set null to the attribute. - * - * @param configKey - * Value to set member attribute configKey - */ - public void setConfigkey(String configKey) { - this.configKey = configKey; - } - - /** - * Returns the value for the member attribute configKey - * - * @return Date - value of member attribute configKey . - */ - public String getConfigkey() { - return this.configKey; - } - - /** - * This method sets the value to the member attribute configValue . - * You cannot set null to the attribute. - * - * @param configValue - * Value to set member attribute configValue - */ - public void setConfigvalue(String configValue) { - this.configValue = configValue; - } - - /** - * Returns the value for the member attribute configValue - * - * @return Date - value of member attribute configValue . - */ - public String getConfigvalue() { - return this.configValue; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#equals(java.lang.Object) - */ - @Override - public boolean equals(Object obj) { - if (!super.equals(obj)) { - return false; - } - if (this == obj) { - return true; - } - if (!super.equals(obj)) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - XXServiceConfigMap other = (XXServiceConfigMap) obj; - if (configKey == null) { - if (other.configKey != null) { - return false; - } - } else if (!configKey.equals(other.configKey)) { - return false; - } - if (configValue == null) { - if (other.configValue != null) { - return false; - } - } else if (!configValue.equals(other.configValue)) { - return false; - } - if (id == null) { - if (other.id != null) { - return false; - } - } else if (!id.equals(other.id)) { - return false; - } - if (serviceId == null) { - if (other.serviceId != null) { - return false; - } - } else if (!serviceId.equals(other.serviceId)) { - return false; - } - return true; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#toString() - */ - @Override - public String toString() { - return "XXServiceConfigMap [" + super.toString() + " id=" + id - + ", service=" + serviceId + ", configKey=" + configKey - + ", configValue=" + configValue + "]"; - } - +public class XXServiceConfigMap extends XXDBBase implements java.io.Serializable { + private static final long serialVersionUID = 1L; + + /** + * id of the XXServiceConfigMap + *
    + *
+ */ + @Id + @SequenceGenerator(name = "x_service_config_map_SEQ", sequenceName = "x_service_config_map_SEQ", allocationSize = 1) + @GeneratedValue(strategy = GenerationType.AUTO, generator = "x_service_config_map_SEQ") + @Column(name = "id") + protected Long id; + + /** + * service of the XXServiceConfigMap + *
    + *
+ */ + @Column(name = "service") + protected Long serviceId; + + /** + * configKey of the XXServiceConfigMap + *
    + *
+ */ + @Column(name = "config_key") + protected String configKey; + + /** + * configValue of the XXServiceConfigMap + *
    + *
+ */ + @Column(name = "config_value") + protected String configValue; + + /** + * Returns the value for the member attribute id + * + * @return Date - value of member attribute id . + */ + public Long getId() { + return this.id; + } + + /** + * This method sets the value to the member attribute id . You + * cannot set null to the attribute. + * + * @param id Value to set member attribute id + */ + public void setId(Long id) { + this.id = id; + } + + @Override + public int hashCode() { + return super.hashCode(); + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#equals(java.lang.Object) + */ + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } else if (!super.equals(obj)) { + return false; + } + + XXServiceConfigMap other = (XXServiceConfigMap) obj; + + return Objects.equals(configKey, other.configKey) && + Objects.equals(configValue, other.configValue) && + Objects.equals(id, other.id) && + Objects.equals(serviceId, other.serviceId); + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + return "XXServiceConfigMap [" + super.toString() + " id=" + id + + ", service=" + serviceId + ", configKey=" + configKey + + ", configValue=" + configValue + "]"; + } + + /** + * Returns the value for the member attribute service + * + * @return Date - value of member attribute service . + */ + public Long getServiceId() { + return this.serviceId; + } + + /** + * This method sets the value to the member attribute service . You + * cannot set null to the attribute. + * + * @param service Value to set member attribute service + */ + public void setServiceId(Long serviceId) { + this.serviceId = serviceId; + } + + /** + * Returns the value for the member attribute configKey + * + * @return Date - value of member attribute configKey . + */ + public String getConfigkey() { + return this.configKey; + } + + /** + * This method sets the value to the member attribute configKey . + * You cannot set null to the attribute. + * + * @param configKey Value to set member attribute configKey + */ + public void setConfigkey(String configKey) { + this.configKey = configKey; + } + + /** + * Returns the value for the member attribute configValue + * + * @return Date - value of member attribute configValue . + */ + public String getConfigvalue() { + return this.configValue; + } + + /** + * This method sets the value to the member attribute configValue . + * You cannot set null to the attribute. + * + * @param configValue Value to set member attribute configValue + */ + public void setConfigvalue(String configValue) { + this.configValue = configValue; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/entity/XXServiceDef.java b/security-admin/src/main/java/org/apache/ranger/entity/XXServiceDef.java index dd6d66d4ca..c67e1ee4df 100644 --- a/security-admin/src/main/java/org/apache/ranger/entity/XXServiceDef.java +++ b/security-admin/src/main/java/org/apache/ranger/entity/XXServiceDef.java @@ -18,67 +18,74 @@ */ package org.apache.ranger.entity; -import javax.persistence.*; +import javax.persistence.Cacheable; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.SequenceGenerator; +import javax.persistence.Table; + +import java.util.Objects; @Entity @Cacheable @Table(name = "x_service_def") public class XXServiceDef extends XXServiceDefBase implements java.io.Serializable { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; + + /** + * id of the XXServiceDef + *
    + *
+ */ + @Id + @SequenceGenerator(name = "x_service_def_SEQ", sequenceName = "x_service_def_SEQ", allocationSize = 1) + @GeneratedValue(strategy = GenerationType.AUTO, generator = "x_service_def_SEQ") + @Column(name = "id") + protected Long id; + + /** + * Returns the value for the member attribute id + * + * @return Date - value of member attribute id . + */ + @Override + public Long getId() { + return this.id; + } - /** - * id of the XXServiceDef - *
    - *
- * - */ - @Id - @SequenceGenerator(name = "x_service_def_SEQ", sequenceName = "x_service_def_SEQ", allocationSize = 1) - @GeneratedValue(strategy = GenerationType.AUTO, generator = "x_service_def_SEQ") - @Column(name = "id") - protected Long id; + /** + * This method sets the value to the member attribute id . You cannot set null to the attribute. + * + * @param id Value to set member attribute id + */ + @Override + public void setId(Long id) { + this.id = id; + } - /** - * This method sets the value to the member attribute id . You cannot set null to the attribute. - * - * @param id - * Value to set member attribute id - */ - @Override - public void setId(Long id) { - this.id = id; - } + @Override + public int hashCode() { + return super.hashCode(); + } - /** - * Returns the value for the member attribute id - * - * @return Date - value of member attribute id . - */ - @Override - public Long getId() { - return this.id; - } + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } else if (!super.equals(obj)) { + return false; + } - @Override - public String toString() { - return "XXServiceDef [id=" + id + "]"; - } + XXServiceDef other = (XXServiceDef) obj; - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (!super.equals(obj)) - return false; - if (getClass() != obj.getClass()) - return false; - XXServiceDef other = (XXServiceDef) obj; - if (id == null) { - if (other.id != null) - return false; - } else if (!id.equals(other.id)) - return false; - return true; - } + return Objects.equals(id, other.id); + } + @Override + public String toString() { + return "XXServiceDef [id=" + id + "]"; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/entity/XXServiceDefBase.java b/security-admin/src/main/java/org/apache/ranger/entity/XXServiceDefBase.java index 0741458e51..ba86de242d 100644 --- a/security-admin/src/main/java/org/apache/ranger/entity/XXServiceDefBase.java +++ b/security-admin/src/main/java/org/apache/ranger/entity/XXServiceDefBase.java @@ -17,415 +17,341 @@ package org.apache.ranger.entity; -import java.io.Serializable; - import javax.persistence.Column; import javax.persistence.MappedSuperclass; import javax.persistence.Version; +import java.io.Serializable; +import java.util.Objects; + @MappedSuperclass public abstract class XXServiceDefBase extends XXDBBase implements Serializable { - private static final long serialVersionUID = 1L; - - /** - * Global Id for the object - *
    - *
  • The maximum length for this attribute is 512. - *
- * - */ - @Column(name = "guid", unique = true, nullable = false, length = 512) - protected String guid; - /** - * version of the XXServiceDef - *
    - *
- * - */ - @Version - @Column(name = "version") - protected Long version; - - /** - * name of the XXServiceDef - *
    - *
- * - */ - @Column(name = "name") - protected String name; - - /** - * displayName of the XXServiceDef - *
    - *
- * - */ - @Column(name = "display_name") - protected String displayName; - - /** - * implClassName of the XXServiceDef - *
    - *
- * - */ - @Column(name = "impl_class_name") - protected String implClassName; - - /** - * label of the XXServiceDef - *
    - *
- * - */ - @Column(name = "label") - protected String label; - - /** - * description of the XXServiceDef - *
    - *
- * - */ - @Column(name = "description") - protected String description; - - /** - * options of the XXServiceDef - *
    - *
- * - */ - @Column(name = "def_options") - protected String defOptions; - - /** - * rbKeyLabel of the XXServiceDef - *
    - *
- * - */ - @Column(name = "rb_key_label") - protected String rbKeyLabel; - - /** - * rbKeyDescription of the XXServiceDef - *
    - *
- * - */ - @Column(name = "rb_key_description") - protected String rbKeyDescription; - /** - * isEnabled of the XXPolicy - *
    - *
- * - */ - @Column(name = "is_enabled") - protected Boolean isEnabled; - - /** - * @return the gUID - */ - public String getGuid() { - return this.guid; - } - - /** - * @param guid - * the gUID to set - */ - public void setGuid(String guid) { - this.guid = guid; - } - - /** - * This method sets the value to the member attribute version . You cannot set null to the attribute. - * - * @param version - * Value to set member attribute version - */ - public void setVersion(Long version) { - this.version = version; - } - - /** - * Returns the value for the member attribute version - * - * @return Date - value of member attribute version . - */ - public Long getVersion() { - return this.version; - } - - /** - * This method sets the value to the member attribute name . You cannot set null to the attribute. - * - * @param name - * Value to set member attribute name - */ - public void setName(String name) { - this.name = name; - } - - /** - * Returns the value for the member attribute name - * - * @return Date - value of member attribute name . - */ - public String getName() { - return this.name; - } - - /** - * This method sets the value to the member attribute implClassName . You cannot set null to the attribute. - * - * @param implClassName - * Value to set member attribute implClassName - */ - public void setImplclassname(String implClassName) { - this.implClassName = implClassName; - } - - /** - * Returns the value for the member attribute implClassName - * - * @return Date - value of member attribute implClassName . - */ - public String getImplclassname() { - return this.implClassName; - } - - /** - * This method sets the value to the member attribute label . You cannot set null to the attribute. - * - * @param label - * Value to set member attribute label - */ - public void setLabel(String label) { - this.label = label; - } - - /** - * Returns the value for the member attribute label - * - * @return Date - value of member attribute label . - */ - public String getLabel() { - return this.label; - } - - /** - * This method sets the value to the member attribute description . You cannot set null to the attribute. - * - * @param description - * Value to set member attribute description - */ - public void setDescription(String description) { - this.description = description; - } - - /** - * Returns the value for the member attribute description - * - * @return Date - value of member attribute description . - */ - public String getDescription() { - return this.description; - } - - /** - * This method sets the value to the member attribute defOptions . - * - * @param options - * Value to set member attribute defOptions - */ - public void setDefOptions(String options) { - this.defOptions = options; - } - - /** - * Returns the value for the member attribute defOptions - * - * @return String - value of member attribute defOptions . - */ - public String getDefOptions() { - return this.defOptions; - } - - /** - * This method sets the value to the member attribute rbKeyLabel . You cannot set null to the attribute. - * - * @param rbKeyLabel - * Value to set member attribute rbKeyLabel - */ - public void setRbkeylabel(String rbKeyLabel) { - this.rbKeyLabel = rbKeyLabel; - } - - /** - * Returns the value for the member attribute rbKeyLabel - * - * @return Date - value of member attribute rbKeyLabel . - */ - public String getRbkeylabel() { - return this.rbKeyLabel; - } - - /** - * This method sets the value to the member attribute rbKeyDescription . You cannot set null to the - * attribute. - * - * @param rbKeyDescription - * Value to set member attribute rbKeyDescription - */ - public void setRbkeydescription(String rbKeyDescription) { - this.rbKeyDescription = rbKeyDescription; - } - - /** - * Returns the value for the member attribute rbKeyDescription - * - * @return Date - value of member attribute rbKeyDescription . - */ - public String getRbkeydescription() { - return this.rbKeyDescription; - } - - /** - * This method sets the value to the member attribute isEnabled . You cannot set null to the attribute. - * - * @param isEnabled - * Value to set member attribute isEnabled - */ - public void setIsEnabled(boolean isEnabled) { - this.isEnabled = isEnabled; - } - - /** - * Returns the value for the member attribute isEnabled - * - * @return Date - value of member attribute isEnabled . - */ - public boolean getIsEnabled() { - return this.isEnabled; - } - - /** - * This method sets the value to the member attribute displayName . You cannot set null to the attribute. - * - * @param displayName - * Value to set member attribute displayName - */ - public void setDisplayName(String displayName) { - this.displayName = displayName; - } - - /** - * Returns the value for the member attribute displayName - * - * @return Date - value of member attribute displayName . - */ - public String getDisplayName() { - return displayName; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#equals(java.lang.Object) - */ - @Override - public boolean equals(Object obj) { - if (!super.equals(obj)) { - return false; - } - if (this == obj) { - return true; - } - if (getClass() != obj.getClass()) { - return false; - } - XXServiceDefBase other = (XXServiceDefBase) obj; - if (description == null) { - if (other.description != null) { - return false; - } - } else if (!description.equals(other.description)) { - return false; - } - if (guid == null) { - if (other.guid != null) { - return false; - } - } else if (!guid.equals(other.guid)) { - return false; - } - if (implClassName == null) { - if (other.implClassName != null) { - return false; - } - } else if (!implClassName.equals(other.implClassName)) { - return false; - } - if (label == null) { - if (other.label != null) { - return false; - } - } else if (!label.equals(other.label)) { - return false; - } - if (name == null) { - if (other.name != null) { - return false; - } - } else if (!name.equals(other.name)) { - return false; - } - if (rbKeyDescription == null) { - if (other.rbKeyDescription != null) { - return false; - } - } else if (!rbKeyDescription.equals(other.rbKeyDescription)) { - return false; - } - if (rbKeyLabel == null) { - if (other.rbKeyLabel != null) { - return false; - } - } else if (!rbKeyLabel.equals(other.rbKeyLabel)) { - return false; - } - if (version == null) { - if (other.version != null) { - return false; - } - } else if (!version.equals(other.version)) { - return false; - } - if (isEnabled == null) { - if (other.isEnabled != null) { - return false; - } - } else if (!isEnabled.equals(other.isEnabled)) { - return false; - } - return true; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#toString() - */ - @Override - public String toString() { - return "XXServiceDefBase [" + super.toString() + " guid=" + guid + ", version=" + version + ", name=" + name +", displayName=" + displayName - + ", implClassName=" + implClassName + ", label=" + label + ", description=" + description - + ", rbKeyLabel=" + rbKeyLabel + ", rbKeyDescription=" + rbKeyDescription + ", isEnabled" + isEnabled - + "]"; - } - + private static final long serialVersionUID = 1L; + + /** + * Global Id for the object + *
    + *
  • The maximum length for this attribute is 512. + *
+ */ + @Column(name = "guid", unique = true, nullable = false, length = 512) + protected String guid; + /** + * version of the XXServiceDef + *
    + *
+ */ + @Version + @Column(name = "version") + protected Long version; + + /** + * name of the XXServiceDef + *
    + *
+ */ + @Column(name = "name") + protected String name; + + /** + * displayName of the XXServiceDef + *
    + *
+ */ + @Column(name = "display_name") + protected String displayName; + + /** + * implClassName of the XXServiceDef + *
    + *
+ */ + @Column(name = "impl_class_name") + protected String implClassName; + + /** + * label of the XXServiceDef + *
    + *
+ */ + @Column(name = "label") + protected String label; + + /** + * description of the XXServiceDef + *
    + *
+ */ + @Column(name = "description") + protected String description; + + /** + * options of the XXServiceDef + *
    + *
+ */ + @Column(name = "def_options") + protected String defOptions; + + /** + * rbKeyLabel of the XXServiceDef + *
    + *
+ */ + @Column(name = "rb_key_label") + protected String rbKeyLabel; + + /** + * rbKeyDescription of the XXServiceDef + *
    + *
+ */ + @Column(name = "rb_key_description") + protected String rbKeyDescription; + /** + * isEnabled of the XXPolicy + *
    + *
+ */ + @Column(name = "is_enabled") + protected Boolean isEnabled; + + /** + * @return the gUID + */ + public String getGuid() { + return this.guid; + } + + /** + * @param guid the gUID to set + */ + public void setGuid(String guid) { + this.guid = guid; + } + + /** + * Returns the value for the member attribute version + * + * @return Date - value of member attribute version . + */ + public Long getVersion() { + return this.version; + } + + /** + * This method sets the value to the member attribute version . You cannot set null to the attribute. + * + * @param version Value to set member attribute version + */ + public void setVersion(Long version) { + this.version = version; + } + + /** + * Returns the value for the member attribute name + * + * @return Date - value of member attribute name . + */ + public String getName() { + return this.name; + } + + /** + * This method sets the value to the member attribute name . You cannot set null to the attribute. + * + * @param name Value to set member attribute name + */ + public void setName(String name) { + this.name = name; + } + + /** + * Returns the value for the member attribute implClassName + * + * @return Date - value of member attribute implClassName . + */ + public String getImplclassname() { + return this.implClassName; + } + + /** + * This method sets the value to the member attribute implClassName . You cannot set null to the attribute. + * + * @param implClassName Value to set member attribute implClassName + */ + public void setImplclassname(String implClassName) { + this.implClassName = implClassName; + } + + /** + * Returns the value for the member attribute label + * + * @return Date - value of member attribute label . + */ + public String getLabel() { + return this.label; + } + + /** + * This method sets the value to the member attribute label . You cannot set null to the attribute. + * + * @param label Value to set member attribute label + */ + public void setLabel(String label) { + this.label = label; + } + + /** + * Returns the value for the member attribute description + * + * @return Date - value of member attribute description . + */ + public String getDescription() { + return this.description; + } + + /** + * This method sets the value to the member attribute description . You cannot set null to the attribute. + * + * @param description Value to set member attribute description + */ + public void setDescription(String description) { + this.description = description; + } + + /** + * Returns the value for the member attribute defOptions + * + * @return String - value of member attribute defOptions . + */ + public String getDefOptions() { + return this.defOptions; + } + + /** + * This method sets the value to the member attribute defOptions . + * + * @param options Value to set member attribute defOptions + */ + public void setDefOptions(String options) { + this.defOptions = options; + } + + /** + * Returns the value for the member attribute rbKeyLabel + * + * @return Date - value of member attribute rbKeyLabel . + */ + public String getRbkeylabel() { + return this.rbKeyLabel; + } + + /** + * This method sets the value to the member attribute rbKeyLabel . You cannot set null to the attribute. + * + * @param rbKeyLabel Value to set member attribute rbKeyLabel + */ + public void setRbkeylabel(String rbKeyLabel) { + this.rbKeyLabel = rbKeyLabel; + } + + /** + * Returns the value for the member attribute rbKeyDescription + * + * @return Date - value of member attribute rbKeyDescription . + */ + public String getRbkeydescription() { + return this.rbKeyDescription; + } + + /** + * This method sets the value to the member attribute rbKeyDescription . You cannot set null to the + * attribute. + * + * @param rbKeyDescription Value to set member attribute rbKeyDescription + */ + public void setRbkeydescription(String rbKeyDescription) { + this.rbKeyDescription = rbKeyDescription; + } + + /** + * Returns the value for the member attribute isEnabled + * + * @return Date - value of member attribute isEnabled . + */ + public boolean getIsEnabled() { + return this.isEnabled; + } + + /** + * This method sets the value to the member attribute isEnabled . You cannot set null to the attribute. + * + * @param isEnabled Value to set member attribute isEnabled + */ + public void setIsEnabled(boolean isEnabled) { + this.isEnabled = isEnabled; + } + + /** + * Returns the value for the member attribute displayName + * + * @return Date - value of member attribute displayName . + */ + public String getDisplayName() { + return displayName; + } + + /** + * This method sets the value to the member attribute displayName . You cannot set null to the attribute. + * + * @param displayName Value to set member attribute displayName + */ + public void setDisplayName(String displayName) { + this.displayName = displayName; + } + + @Override + public int hashCode() { + return super.hashCode(); + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#equals(java.lang.Object) + */ + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } else if (!super.equals(obj)) { + return false; + } + + XXServiceDefBase other = (XXServiceDefBase) obj; + + return Objects.equals(description, other.description) && + Objects.equals(guid, other.guid) && + Objects.equals(implClassName, other.implClassName) && + Objects.equals(label, other.label) && + Objects.equals(name, other.name) && + Objects.equals(rbKeyDescription, other.rbKeyDescription) && + Objects.equals(rbKeyLabel, other.rbKeyLabel) && + Objects.equals(version, other.version) && + Objects.equals(isEnabled, other.isEnabled); + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + return "XXServiceDefBase [" + super.toString() + " guid=" + guid + ", version=" + version + ", name=" + name + ", displayName=" + displayName + + ", implClassName=" + implClassName + ", label=" + label + ", description=" + description + + ", rbKeyLabel=" + rbKeyLabel + ", rbKeyDescription=" + rbKeyDescription + ", isEnabled" + isEnabled + + "]"; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/entity/XXServiceDefWithAssignedId.java b/security-admin/src/main/java/org/apache/ranger/entity/XXServiceDefWithAssignedId.java index d4802b7b06..f9d5ba23d5 100644 --- a/security-admin/src/main/java/org/apache/ranger/entity/XXServiceDefWithAssignedId.java +++ b/security-admin/src/main/java/org/apache/ranger/entity/XXServiceDefWithAssignedId.java @@ -23,52 +23,53 @@ import javax.persistence.Id; import javax.persistence.Table; +import java.util.Objects; + @Entity @Cacheable @Table(name = "x_service_def") public class XXServiceDefWithAssignedId extends XXServiceDefBase { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; + + /** + * id of the XXService + *
    + *
+ */ + @Id + @Column(name = "id") + protected Long id; + + @Override + public Long getId() { + return id; + } - /** - * id of the XXService - *
    - *
- * - */ - @Id - @Column(name = "id") - protected Long id; + @Override + public void setId(Long id) { + this.id = id; + } - @Override - public void setId(Long id) { - this.id = id; - } + @Override + public int hashCode() { + return super.hashCode(); + } - @Override - public Long getId() { - return id; - } + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } else if (!super.equals(obj)) { + return false; + } - @Override - public String toString() { - return "XXServiceDefWithAssignedId [id=" + id + "]"; - } + XXServiceDefWithAssignedId other = (XXServiceDefWithAssignedId) obj; - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (!super.equals(obj)) - return false; - if (getClass() != obj.getClass()) - return false; - XXServiceDefWithAssignedId other = (XXServiceDefWithAssignedId) obj; - if (id == null) { - if (other.id != null) - return false; - } else if (!id.equals(other.id)) - return false; - return true; - } + return Objects.equals(id, other.id); + } + @Override + public String toString() { + return "XXServiceDefWithAssignedId [id=" + id + "]"; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/entity/XXServiceResource.java b/security-admin/src/main/java/org/apache/ranger/entity/XXServiceResource.java index 937b99baf1..a551adb7bd 100644 --- a/security-admin/src/main/java/org/apache/ranger/entity/XXServiceResource.java +++ b/security-admin/src/main/java/org/apache/ranger/entity/XXServiceResource.java @@ -19,7 +19,7 @@ package org.apache.ranger.entity; -import java.io.Serializable; +import org.apache.ranger.common.AppConstants; import javax.persistence.Cacheable; import javax.persistence.Column; @@ -31,245 +31,204 @@ import javax.persistence.Table; import javax.persistence.Version; -import org.apache.ranger.common.AppConstants; +import java.io.Serializable; +import java.util.Objects; @Entity @Cacheable -@Table(name="x_service_resource") +@Table(name = "x_service_resource") public class XXServiceResource extends XXDBBase implements Serializable { - private static final long serialVersionUID = 1L; - - @Id - @SequenceGenerator(name = "X_SERVICE_RESOURCE_SEQ", sequenceName = "X_SERVICE_RESOURCE_SEQ", allocationSize = 1) - @GeneratedValue(strategy = GenerationType.AUTO, generator = "X_SERVICE_RESOURCE_SEQ") - @Column(name = "id") - protected Long id; - - @Column(name = "guid", unique = true, nullable = false, length = 512) - protected String guid; - - @Version - @Column(name = "version") - protected Long version; - - @Column(name = "is_enabled") - protected Boolean isEnabled; - - @Column(name = "resource_signature") - protected String resourceSignature; - - @Column(name = "service_id") - protected Long serviceId; - - @Column(name = "service_resource_elements_text") - protected String serviceResourceElements; - - @Column(name = "tags_text") - protected String tags; - - @Override - public void setId(Long id) { - this.id = id; - } - - @Override - public Long getId() { - return id; - } - - /** - * @return the guid - */ - public String getGuid() { - return guid; - } - - /** - * @param guid - * the guid to set - */ - public void setGuid(String guid) { - this.guid = guid; - } - - /** - * @return the serviceId - */ - public Long getServiceId() { - return serviceId; - } - - /** - * @param serviceId - * the serviceId to set - */ - public void setServiceId(Long serviceId) { - this.serviceId = serviceId; - } - - /** - * @return the resourceSignature - */ - public String getResourceSignature() { - return resourceSignature; - } - - /** - * @param resourceSignature - * the resourceSignature to set - */ - public void setResourceSignature(String resourceSignature) { - this.resourceSignature = resourceSignature; - } - - /** - * @return the version - */ - public Long getVersion() { - return version; - } - - /** - * @param version - * the version to set - */ - public void setVersion(Long version) { - this.version = version; - } - - /** - * @return the isEnabled - */ - public Boolean getIsEnabled() { - return isEnabled; - } - - /** - * @param isEnabled - * the isEnabled to set - */ - public void setIsEnabled(Boolean isEnabled) { - this.isEnabled = isEnabled; - } - - public String getServiceResourceElements() { return serviceResourceElements; } - - public void setServiceResourceElements(String serviceResourceElements) { - this.serviceResourceElements = serviceResourceElements; - } - - public String getTags() { return tags; } - - public void setTags(String tags) { this.tags = tags; } - - @Override - public int getMyClassType() { - return AppConstants.CLASS_TYPE_XA_SERVICE_RESOURCE; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#hashCode() - */ - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((id == null) ? 0 : id.hashCode()); - result = prime * result + ((guid == null) ? 0 : guid.hashCode()); - result = prime * result + ((version == null) ? 0 : version.hashCode()); - result = prime * result + ((isEnabled == null) ? 0 : isEnabled.hashCode()); - result = prime * result + ((resourceSignature == null) ? 0 : resourceSignature.hashCode()); - result = prime * result + ((serviceId == null) ? 0 : serviceId.hashCode()); - result = prime * result + ((serviceResourceElements == null) ? 0 : serviceResourceElements.hashCode()); - result = prime * result + ((tags == null) ? 0 : tags.hashCode()); - return result; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#equals(java.lang.Object) - */ - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (!super.equals(obj)) - return false; - if (getClass() != obj.getClass()) - return false; - XXServiceResource other = (XXServiceResource) obj; - if (resourceSignature == null) { - if (other.resourceSignature != null) - return false; - } else if (!resourceSignature.equals(other.resourceSignature)) - return false; - if (guid == null) { - if (other.guid != null) - return false; - } else if (!guid.equals(other.guid)) - return false; - if (id == null) { - if (other.id != null) - return false; - } else if (!id.equals(other.id)) - return false; - if (isEnabled == null) { - if (other.isEnabled != null) - return false; - } else if (!isEnabled.equals(other.isEnabled)) - return false; - if (serviceId == null) { - if (other.serviceId != null) - return false; - } else if (!serviceId.equals(other.serviceId)) - return false; - if (version == null) { - if (other.version != null) - return false; - } else if (!version.equals(other.version)) - return false; - if (serviceResourceElements == null) { - if (other.serviceResourceElements != null) - return false; - } else if (!serviceResourceElements.equals(other.serviceResourceElements)) - return false; - if (tags == null) { - if (other.tags != null) - return false; - } else if (!tags.equals(other.tags)) - return false; - return true; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#toString() - */ - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - toString(sb); - return sb.toString(); - } - - public StringBuilder toString(StringBuilder sb) { - sb.append("{ "); - sb.append(super.toString() + "} "); - sb.append("id={").append(id).append("} "); - sb.append("guid={").append(guid).append("} "); - sb.append("version={").append(version).append("} "); - sb.append("isEnabled={").append(isEnabled).append("} "); - sb.append("resourceSignature={").append(resourceSignature).append("} "); - sb.append("serviceId={").append(serviceId).append("} "); - sb.append("serviceResourceElements={").append(serviceResourceElements).append("} "); - sb.append("tags={").append(tags).append("} "); - sb.append(" }"); - - return sb; - } - + private static final long serialVersionUID = 1L; + + @Id + @SequenceGenerator(name = "X_SERVICE_RESOURCE_SEQ", sequenceName = "X_SERVICE_RESOURCE_SEQ", allocationSize = 1) + @GeneratedValue(strategy = GenerationType.AUTO, generator = "X_SERVICE_RESOURCE_SEQ") + @Column(name = "id") + protected Long id; + + @Column(name = "guid", unique = true, nullable = false, length = 512) + protected String guid; + + @Version + @Column(name = "version") + protected Long version; + + @Column(name = "is_enabled") + protected Boolean isEnabled; + + @Column(name = "resource_signature") + protected String resourceSignature; + + @Column(name = "service_id") + protected Long serviceId; + + @Column(name = "service_resource_elements_text") + protected String serviceResourceElements; + + @Column(name = "tags_text") + protected String tags; + + /** + * @return the guid + */ + public String getGuid() { + return guid; + } + + /** + * @param guid the guid to set + */ + public void setGuid(String guid) { + this.guid = guid; + } + + /** + * @return the serviceId + */ + public Long getServiceId() { + return serviceId; + } + + /** + * @param serviceId the serviceId to set + */ + public void setServiceId(Long serviceId) { + this.serviceId = serviceId; + } + + /** + * @return the resourceSignature + */ + public String getResourceSignature() { + return resourceSignature; + } + + /** + * @param resourceSignature the resourceSignature to set + */ + public void setResourceSignature(String resourceSignature) { + this.resourceSignature = resourceSignature; + } + + /** + * @return the version + */ + public Long getVersion() { + return version; + } + + /** + * @param version the version to set + */ + public void setVersion(Long version) { + this.version = version; + } + + /** + * @return the isEnabled + */ + public Boolean getIsEnabled() { + return isEnabled; + } + + /** + * @param isEnabled the isEnabled to set + */ + public void setIsEnabled(Boolean isEnabled) { + this.isEnabled = isEnabled; + } + + public String getServiceResourceElements() { + return serviceResourceElements; + } + + public void setServiceResourceElements(String serviceResourceElements) { + this.serviceResourceElements = serviceResourceElements; + } + + public String getTags() { + return tags; + } + + public void setTags(String tags) { + this.tags = tags; + } + + @Override + public int getMyClassType() { + return AppConstants.CLASS_TYPE_XA_SERVICE_RESOURCE; + } + + @Override + public Long getId() { + return id; + } + + @Override + public void setId(Long id) { + this.id = id; + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#hashCode() + */ + @Override + public int hashCode() { + return Objects.hash(super.hashCode(), id, guid, version, isEnabled, resourceSignature, serviceId, serviceResourceElements, tags); + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#equals(java.lang.Object) + */ + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } else if (!super.equals(obj)) { + return false; + } + + XXServiceResource other = (XXServiceResource) obj; + + return Objects.equals(resourceSignature, other.resourceSignature) && + Objects.equals(guid, other.guid) && + Objects.equals(id, other.id) && + Objects.equals(isEnabled, other.isEnabled) && + Objects.equals(serviceId, other.serviceId) && + Objects.equals(version, other.version) && + Objects.equals(serviceResourceElements, other.serviceResourceElements) && + Objects.equals(tags, other.tags); + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + toString(sb); + return sb.toString(); + } + + public StringBuilder toString(StringBuilder sb) { + sb.append("{ "); + sb.append(super.toString() + "} "); + sb.append("id={").append(id).append("} "); + sb.append("guid={").append(guid).append("} "); + sb.append("version={").append(version).append("} "); + sb.append("isEnabled={").append(isEnabled).append("} "); + sb.append("resourceSignature={").append(resourceSignature).append("} "); + sb.append("serviceId={").append(serviceId).append("} "); + sb.append("serviceResourceElements={").append(serviceResourceElements).append("} "); + sb.append("tags={").append(tags).append("} "); + sb.append(" }"); + + return sb; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/entity/XXServiceResourceElement.java b/security-admin/src/main/java/org/apache/ranger/entity/XXServiceResourceElement.java index e3480be362..777f44b5c8 100644 --- a/security-admin/src/main/java/org/apache/ranger/entity/XXServiceResourceElement.java +++ b/security-admin/src/main/java/org/apache/ranger/entity/XXServiceResourceElement.java @@ -19,7 +19,7 @@ package org.apache.ranger.entity; -import java.io.Serializable; +import org.apache.ranger.common.AppConstants; import javax.persistence.Cacheable; import javax.persistence.Column; @@ -30,189 +30,158 @@ import javax.persistence.SequenceGenerator; import javax.persistence.Table; -import org.apache.ranger.common.AppConstants; +import java.io.Serializable; +import java.util.Objects; @Entity @Cacheable -@Table(name="x_service_resource_element") +@Table(name = "x_service_resource_element") public class XXServiceResourceElement extends XXDBBase implements Serializable { - private static final long serialVersionUID = 1L; - - @Id - @SequenceGenerator(name = "X_SERVICE_RESOURCE_ELEMENT_SEQ", sequenceName = "X_SERVICE_RESOURCE_ELEMENT_SEQ", allocationSize = 1) - @GeneratedValue(strategy = GenerationType.AUTO, generator = "X_SERVICE_RESOURCE_ELEMENT_SEQ") - @Column(name = "id") - protected Long id; - - @Column(name = "res_def_id") - protected Long resDefId; - - @Column(name = "res_id") - protected Long resourceId; - - @Column(name = "is_excludes") - protected Boolean isExcludes; - - @Column(name = "is_recursive") - protected Boolean isRecursive; - - @Override - public void setId(Long id) { - this.id = id; - } - - @Override - public Long getId() { - return id; - } - - /** - * @return the resDefId - */ - public Long getResDefId() { - return resDefId; - } - - /** - * @param resDefId - * the resDefId to set - */ - public void setResDefId(Long resDefId) { - this.resDefId = resDefId; - } - - /** - * @return the isExcludes - */ - public Boolean getIsExcludes() { - return isExcludes; - } - - /** - * @param isExcludes - * the isExcludes to set - */ - public void setIsExcludes(Boolean isExcludes) { - this.isExcludes = isExcludes; - } - - /** - * @return the isRecursive - */ - public Boolean getIsRecursive() { - return isRecursive; - } - - /** - * @param isRecursive - * the isRecursive to set - */ - public void setIsRecursive(Boolean isRecursive) { - this.isRecursive = isRecursive; - } - - /** - * @return the resourceId - */ - public Long getResourceId() { - return resourceId; - } - - /** - * @param resourceId - * the resourceId to set - */ - public void setResourceId(Long resourceId) { - this.resourceId = resourceId; - } - - @Override - public int getMyClassType() { - return AppConstants.CLASS_TYPE_XA_SERVICE_RESOURCE_ELEMENT; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#hashCode() - */ - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((id == null) ? 0 : id.hashCode()); - result = prime * result + ((isExcludes == null) ? 0 : isExcludes.hashCode()); - result = prime * result + ((isRecursive == null) ? 0 : isRecursive.hashCode()); - result = prime * result + ((resDefId == null) ? 0 : resDefId.hashCode()); - result = prime * result + ((resourceId == null) ? 0 : resourceId.hashCode()); - return result; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#equals(java.lang.Object) - */ - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (!super.equals(obj)) - return false; - if (getClass() != obj.getClass()) - return false; - XXServiceResourceElement other = (XXServiceResourceElement) obj; - if (id == null) { - if (other.id != null) - return false; - } else if (!id.equals(other.id)) - return false; - if (isExcludes == null) { - if (other.isExcludes != null) - return false; - } else if (!isExcludes.equals(other.isExcludes)) - return false; - if (isRecursive == null) { - if (other.isRecursive != null) - return false; - } else if (!isRecursive.equals(other.isRecursive)) - return false; - if (resDefId == null) { - if (other.resDefId != null) - return false; - } else if (!resDefId.equals(other.resDefId)) - return false; - if (resourceId == null) { - if (other.resourceId != null) - return false; - } else if (!resourceId.equals(other.resourceId)) - return false; - return true; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#toString() - */ - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - toString(sb); - return sb.toString(); - } - - public StringBuilder toString(StringBuilder sb) { - sb.append("{ "); - sb.append(super.toString() + "} "); - sb.append("id={").append(id).append("} "); - sb.append("resDefId={").append(resDefId).append("} "); - sb.append("resourceId={").append(resourceId).append("} "); - sb.append("isExcludes={").append(isExcludes).append("} "); - sb.append("isRecursive={").append(isRecursive).append("} "); - sb.append(" }"); - - return sb; - } - + private static final long serialVersionUID = 1L; + + @Id + @SequenceGenerator(name = "X_SERVICE_RESOURCE_ELEMENT_SEQ", sequenceName = "X_SERVICE_RESOURCE_ELEMENT_SEQ", allocationSize = 1) + @GeneratedValue(strategy = GenerationType.AUTO, generator = "X_SERVICE_RESOURCE_ELEMENT_SEQ") + @Column(name = "id") + protected Long id; + + @Column(name = "res_def_id") + protected Long resDefId; + + @Column(name = "res_id") + protected Long resourceId; + + @Column(name = "is_excludes") + protected Boolean isExcludes; + + @Column(name = "is_recursive") + protected Boolean isRecursive; + + /** + * @return the resDefId + */ + public Long getResDefId() { + return resDefId; + } + + /** + * @param resDefId the resDefId to set + */ + public void setResDefId(Long resDefId) { + this.resDefId = resDefId; + } + + /** + * @return the isExcludes + */ + public Boolean getIsExcludes() { + return isExcludes; + } + + /** + * @param isExcludes the isExcludes to set + */ + public void setIsExcludes(Boolean isExcludes) { + this.isExcludes = isExcludes; + } + + /** + * @return the isRecursive + */ + public Boolean getIsRecursive() { + return isRecursive; + } + + /** + * @param isRecursive the isRecursive to set + */ + public void setIsRecursive(Boolean isRecursive) { + this.isRecursive = isRecursive; + } + + /** + * @return the resourceId + */ + public Long getResourceId() { + return resourceId; + } + + /** + * @param resourceId the resourceId to set + */ + public void setResourceId(Long resourceId) { + this.resourceId = resourceId; + } + + @Override + public int getMyClassType() { + return AppConstants.CLASS_TYPE_XA_SERVICE_RESOURCE_ELEMENT; + } + + @Override + public Long getId() { + return id; + } + + @Override + public void setId(Long id) { + this.id = id; + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#hashCode() + */ + @Override + public int hashCode() { + return Objects.hash(super.hashCode(), id, isExcludes, isRecursive, resDefId, resourceId); + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#equals(java.lang.Object) + */ + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } else if (!super.equals(obj)) { + return false; + } + + XXServiceResourceElement other = (XXServiceResourceElement) obj; + + return Objects.equals(id, other.id) && + Objects.equals(isExcludes, other.isExcludes) && + Objects.equals(isRecursive, other.isRecursive) && + Objects.equals(resDefId, other.resDefId) && + Objects.equals(resourceId, other.resourceId); + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + toString(sb); + return sb.toString(); + } + + public StringBuilder toString(StringBuilder sb) { + sb.append("{ "); + sb.append(super.toString()).append("} "); + sb.append("id={").append(id).append("} "); + sb.append("resDefId={").append(resDefId).append("} "); + sb.append("resourceId={").append(resourceId).append("} "); + sb.append("isExcludes={").append(isExcludes).append("} "); + sb.append("isRecursive={").append(isRecursive).append("} "); + sb.append(" }"); + + return sb; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/entity/XXServiceResourceElementValue.java b/security-admin/src/main/java/org/apache/ranger/entity/XXServiceResourceElementValue.java index 76716ea08d..2ac102268b 100644 --- a/security-admin/src/main/java/org/apache/ranger/entity/XXServiceResourceElementValue.java +++ b/security-admin/src/main/java/org/apache/ranger/entity/XXServiceResourceElementValue.java @@ -19,7 +19,7 @@ package org.apache.ranger.entity; -import java.io.Serializable; +import org.apache.ranger.common.AppConstants; import javax.persistence.Cacheable; import javax.persistence.Column; @@ -30,164 +30,139 @@ import javax.persistence.SequenceGenerator; import javax.persistence.Table; -import org.apache.ranger.common.AppConstants; +import java.io.Serializable; +import java.util.Objects; @Entity @Cacheable -@Table(name="x_service_resource_element_val") +@Table(name = "x_service_resource_element_val") public class XXServiceResourceElementValue extends XXDBBase implements Serializable { - private static final long serialVersionUID = 1L; - - @Id - @SequenceGenerator(name = "X_SERVICE_RES_EL_VAL_SEQ", sequenceName = "X_SERVICE_RES_EL_VAL_SEQ", allocationSize = 1) - @GeneratedValue(strategy = GenerationType.AUTO, generator = "X_SERVICE_RES_EL_VAL_SEQ") - @Column(name = "id") - protected Long id; - - @Column(name = "res_element_id") - protected Long resElementId; - - @Column(name = "value") - protected String value; - - @Column(name = "sort_order") - protected Integer sortOrder; - - @Override - public void setId(Long id) { - this.id = id; - } - - @Override - public Long getId() { - return id; - } - - /** - * @return the resElementId - */ - public Long getResElementId() { - return resElementId; - } - - /** - * @param resElementId - * the resElementId to set - */ - public void setResElementId(Long resElementId) { - this.resElementId = resElementId; - } - - /** - * @return the value - */ - public String getValue() { - return value; - } - - /** - * @param value - * the value to set - */ - public void setValue(String value) { - this.value = value; - } - - /** - * @return the sortOrder - */ - public Integer getSortOrder() { - return sortOrder; - } - - /** - * @param sortOrder - * the sortOrder to set - */ - public void setSortOrder(Integer sortOrder) { - this.sortOrder = sortOrder; - } - - @Override - public int getMyClassType() { - return AppConstants.CLASS_TYPE_XA_SERVICE_RESOURCE_ELEMENT_VALUE; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#hashCode() - */ - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((id == null) ? 0 : id.hashCode()); - result = prime * result + ((resElementId == null) ? 0 : resElementId.hashCode()); - result = prime * result + ((sortOrder == null) ? 0 : sortOrder.hashCode()); - result = prime * result + ((value == null) ? 0 : value.hashCode()); - return result; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#equals(java.lang.Object) - */ - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (!super.equals(obj)) - return false; - if (getClass() != obj.getClass()) - return false; - XXServiceResourceElementValue other = (XXServiceResourceElementValue) obj; - if (id == null) { - if (other.id != null) - return false; - } else if (!id.equals(other.id)) - return false; - if (resElementId == null) { - if (other.resElementId != null) - return false; - } else if (!resElementId.equals(other.resElementId)) - return false; - if (sortOrder == null) { - if (other.sortOrder != null) - return false; - } else if (!sortOrder.equals(other.sortOrder)) - return false; - if (value == null) { - if (other.value != null) - return false; - } else if (!value.equals(other.value)) - return false; - return true; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#toString() - */ - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - toString(sb); - return sb.toString(); - } - - public StringBuilder toString(StringBuilder sb) { - sb.append("{ "); - sb.append(super.toString() + "} "); - sb.append("id={").append(id).append("} "); - sb.append("resElementId={").append(resElementId).append("} "); - sb.append("value={").append(value).append("} "); - sb.append("sortOrder={").append(sortOrder).append("} "); - sb.append(" }"); - - return sb; - } - + private static final long serialVersionUID = 1L; + + @Id + @SequenceGenerator(name = "X_SERVICE_RES_EL_VAL_SEQ", sequenceName = "X_SERVICE_RES_EL_VAL_SEQ", allocationSize = 1) + @GeneratedValue(strategy = GenerationType.AUTO, generator = "X_SERVICE_RES_EL_VAL_SEQ") + @Column(name = "id") + protected Long id; + + @Column(name = "res_element_id") + protected Long resElementId; + + @Column(name = "value") + protected String value; + + @Column(name = "sort_order") + protected Integer sortOrder; + + /** + * @return the resElementId + */ + public Long getResElementId() { + return resElementId; + } + + /** + * @param resElementId the resElementId to set + */ + public void setResElementId(Long resElementId) { + this.resElementId = resElementId; + } + + /** + * @return the value + */ + public String getValue() { + return value; + } + + /** + * @param value the value to set + */ + public void setValue(String value) { + this.value = value; + } + + /** + * @return the sortOrder + */ + public Integer getSortOrder() { + return sortOrder; + } + + /** + * @param sortOrder the sortOrder to set + */ + public void setSortOrder(Integer sortOrder) { + this.sortOrder = sortOrder; + } + + @Override + public int getMyClassType() { + return AppConstants.CLASS_TYPE_XA_SERVICE_RESOURCE_ELEMENT_VALUE; + } + + @Override + public Long getId() { + return id; + } + + @Override + public void setId(Long id) { + this.id = id; + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#hashCode() + */ + @Override + public int hashCode() { + return Objects.hash(super.hashCode(), id, resElementId, sortOrder, value); + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#equals(java.lang.Object) + */ + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } else if (!super.equals(obj)) { + return false; + } + + XXServiceResourceElementValue other = (XXServiceResourceElementValue) obj; + + return Objects.equals(id, other.id) && + Objects.equals(resElementId, other.resElementId) && + Objects.equals(sortOrder, other.sortOrder) && + Objects.equals(value, other.value); + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + toString(sb); + return sb.toString(); + } + + public StringBuilder toString(StringBuilder sb) { + sb.append("{ "); + sb.append(super.toString() + "} "); + sb.append("id={").append(id).append("} "); + sb.append("resElementId={").append(resElementId).append("} "); + sb.append("value={").append(value).append("} "); + sb.append("sortOrder={").append(sortOrder).append("} "); + sb.append(" }"); + + return sb; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/entity/XXServiceVersionInfo.java b/security-admin/src/main/java/org/apache/ranger/entity/XXServiceVersionInfo.java index ccd8031427..243aa33d7e 100644 --- a/security-admin/src/main/java/org/apache/ranger/entity/XXServiceVersionInfo.java +++ b/security-admin/src/main/java/org/apache/ranger/entity/XXServiceVersionInfo.java @@ -19,12 +19,12 @@ package org.apache.ranger.entity; -import java.util.Date; -import java.util.Objects; +import org.apache.ranger.common.AppConstants; +import org.apache.ranger.common.DateUtil; import javax.persistence.Cacheable; -import javax.persistence.Entity; import javax.persistence.Column; +import javax.persistence.Entity; import javax.persistence.EntityListeners; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; @@ -35,222 +35,226 @@ import javax.persistence.TemporalType; import javax.persistence.Version; -import org.apache.ranger.common.AppConstants; -import org.apache.ranger.common.DateUtil; +import java.util.Date; +import java.util.Objects; -@EntityListeners( org.apache.ranger.common.db.JPABeanCallbacks.class) +@EntityListeners(org.apache.ranger.common.db.JPABeanCallbacks.class) @Entity @Cacheable @Table(name = "x_service_version_info") public class XXServiceVersionInfo implements java.io.Serializable { - private static final long serialVersionUID = 1L; - - @Id - @SequenceGenerator(name = "X_SERVICE_VERSION_INFO_SEQ", sequenceName = "X_SERVICE_VERSION_INFO_SEQ", allocationSize = 1) - @GeneratedValue(strategy = GenerationType.AUTO, generator = "X_SERVICE_VERSION_INFO_SEQ") - - @Column(name = "id") - protected Long id; - - @Column(name = "service_id") - protected Long serviceId; - - @Column(name = "policy_version") - protected Long policyVersion; - - @Temporal(TemporalType.TIMESTAMP) - @Column(name="policy_update_time" ) - protected Date policyUpdateTime = DateUtil.getUTCDate(); - - @Column(name = "tag_version") - protected Long tagVersion; - - @Temporal(TemporalType.TIMESTAMP) - @Column(name="tag_update_time" ) - protected Date tagUpdateTime = DateUtil.getUTCDate(); - - @Column(name = "role_version") - protected Long roleVersion; - - @Temporal(TemporalType.TIMESTAMP) - @Column(name="role_update_time" ) - protected Date roleUpdateTime = DateUtil.getUTCDate(); - - @Column(name = "gds_version") - protected Long gdsVersion; - - @Temporal(TemporalType.TIMESTAMP) - @Column(name="gds_update_time" ) - protected Date gdsUpdateTime = DateUtil.getUTCDate(); - - @Version - @Column(name = "version") - protected Long version; - - /** - * Default constructor. This will set all the attributes to default value. - */ - public XXServiceVersionInfo ( ) { - } - - public int getMyClassType( ) { - return AppConstants.CLASS_TYPE_NONE; - } - - public String getMyDisplayValue() { - return null; - } - - public void setId(Long id) { - this.id = id; - } - - public void setVersion(Long version) { - this.version = version; - } - - public Long getId() { - return this.id; - } - - public Long getVersion() { - return version; - } - - public void setServiceId(Long serviceId) { - this.serviceId = serviceId; - } - - public Long getServiceId() { - return this.serviceId; - } - - public void setPolicyVersion(Long policyVersion) { - this.policyVersion = policyVersion; - } - - public Long getPolicyVersion() { - return this.policyVersion; - } - - public void setPolicyUpdateTime( Date updateTime ) { - this.policyUpdateTime = updateTime; - } - - public Date getPolicyUpdateTime( ) { - return this.policyUpdateTime; - } - - public void setTagVersion(Long tagVersion) { - this.tagVersion = tagVersion; - } - - public Long getTagVersion() { - return this.tagVersion; - } - - public void setTagUpdateTime( Date updateTime ) { - this.tagUpdateTime = updateTime; - } - - public Date getTagUpdateTime( ) { - return this.tagUpdateTime; - } - - public void setRoleVersion(Long roleVersion) { - this.roleVersion = roleVersion; - } - - public Long getRoleVersion() { - return this.roleVersion; - } - - public void setRoleUpdateTime( Date updateTime ) { - this.roleUpdateTime = updateTime; - } - - public Date getRoleUpdateTime( ) { - return this.roleUpdateTime; - } - - public void setGdsVersion(Long gdsVersion) { - this.gdsVersion = gdsVersion; - } - - public Long getGdsVersion() { - return this.gdsVersion; - } - - public void setGdsUpdateTime( Date updateTime ) { - this.gdsUpdateTime = updateTime; - } - - public Date getGdsUpdateTime( ) { - return this.gdsUpdateTime; - } - - /** - * This return the bean content in string format - * @return formatedStr - */ - @Override - public String toString( ) { - String str = "XXServiceVersionInfo={"; - str += "id={" + id + "} "; - str += "version={" + version + "} "; - str += "serviceId={" + serviceId + "} "; - str += "policyVersion={" + policyVersion + "} "; - str += "policyUpdateTime={" + policyUpdateTime + "} "; - str += "tagVersion={" + tagVersion + "} "; - str += "tagUpdateTime={" + tagUpdateTime + "} "; - str += "setRoleVersion={" + roleVersion + "}" ; - str += "setRoleUpdateTime={" + roleUpdateTime + "}" ; - str += "gdsVersion={" + gdsVersion + "} "; - str += "gdsUpdateTime={" + gdsUpdateTime + "} "; - str += "}"; - return str; - } - - /** - * Checks for all attributes except referenced db objects - * @return true if all attributes match - */ - @Override - public boolean equals( Object obj) { - final boolean ret; - - if (this == obj) { - ret = true; - } else if (obj == null || getClass() != obj.getClass()) { - ret = false; - } else { - XXServiceVersionInfo other = (XXServiceVersionInfo) obj; - - ret = super.equals(obj) && - Objects.equals(id, other.id) && - Objects.equals(version, other.version) && - Objects.equals(serviceId, other.serviceId) && - Objects.equals(policyVersion, other.policyVersion) && - Objects.equals(policyUpdateTime, other.policyUpdateTime) && - Objects.equals(tagVersion, other.tagVersion) && - Objects.equals(tagUpdateTime, other.tagUpdateTime) && - Objects.equals(roleVersion, other.roleVersion) && - Objects.equals(roleUpdateTime, other.roleUpdateTime) && - Objects.equals(gdsVersion, other.gdsVersion) && - Objects.equals(gdsUpdateTime, other.gdsUpdateTime); - } - - return ret; - } - - public static boolean equals(Object object1, Object object2) { - if (object1 == object2) { - return true; - } - if ((object1 == null) || (object2 == null)) { - return false; - } - return object1.equals(object2); - } - + private static final long serialVersionUID = 1L; + + @Id + @SequenceGenerator(name = "X_SERVICE_VERSION_INFO_SEQ", sequenceName = "X_SERVICE_VERSION_INFO_SEQ", allocationSize = 1) + @GeneratedValue(strategy = GenerationType.AUTO, generator = "X_SERVICE_VERSION_INFO_SEQ") + @Column(name = "id") + protected Long id; + + @Column(name = "service_id") + protected Long serviceId; + + @Column(name = "policy_version") + protected Long policyVersion; + + @Temporal(TemporalType.TIMESTAMP) + @Column(name = "policy_update_time") + protected Date policyUpdateTime = DateUtil.getUTCDate(); + + @Column(name = "tag_version") + protected Long tagVersion; + + @Temporal(TemporalType.TIMESTAMP) + @Column(name = "tag_update_time") + protected Date tagUpdateTime = DateUtil.getUTCDate(); + + @Column(name = "role_version") + protected Long roleVersion; + + @Temporal(TemporalType.TIMESTAMP) + @Column(name = "role_update_time") + protected Date roleUpdateTime = DateUtil.getUTCDate(); + + @Column(name = "gds_version") + protected Long gdsVersion; + + @Temporal(TemporalType.TIMESTAMP) + @Column(name = "gds_update_time") + protected Date gdsUpdateTime = DateUtil.getUTCDate(); + + @Version + @Column(name = "version") + protected Long version; + + /** + * Default constructor. This will set all the attributes to default value. + */ + public XXServiceVersionInfo() { + } + + public static boolean equals(Object object1, Object object2) { + if (object1 == object2) { + return true; + } + if ((object1 == null) || (object2 == null)) { + return false; + } + return object1.equals(object2); + } + + @Override + public int hashCode() { + return super.hashCode(); + } + + /** + * Checks for all attributes except referenced db objects + * + * @return true if all attributes match + */ + @Override + public boolean equals(Object obj) { + final boolean ret; + + if (this == obj) { + ret = true; + } else if (obj == null || getClass() != obj.getClass()) { + ret = false; + } else { + XXServiceVersionInfo other = (XXServiceVersionInfo) obj; + + ret = Objects.equals(id, other.id) && + Objects.equals(version, other.version) && + Objects.equals(serviceId, other.serviceId) && + Objects.equals(policyVersion, other.policyVersion) && + Objects.equals(policyUpdateTime, other.policyUpdateTime) && + Objects.equals(tagVersion, other.tagVersion) && + Objects.equals(tagUpdateTime, other.tagUpdateTime) && + Objects.equals(roleVersion, other.roleVersion) && + Objects.equals(roleUpdateTime, other.roleUpdateTime) && + Objects.equals(gdsVersion, other.gdsVersion) && + Objects.equals(gdsUpdateTime, other.gdsUpdateTime); + } + + return ret; + } + + /** + * This return the bean content in string format + * + * @return formatedStr + */ + @Override + public String toString() { + String str = "XXServiceVersionInfo={"; + str += "id={" + id + "} "; + str += "version={" + version + "} "; + str += "serviceId={" + serviceId + "} "; + str += "policyVersion={" + policyVersion + "} "; + str += "policyUpdateTime={" + policyUpdateTime + "} "; + str += "tagVersion={" + tagVersion + "} "; + str += "tagUpdateTime={" + tagUpdateTime + "} "; + str += "setRoleVersion={" + roleVersion + "}"; + str += "setRoleUpdateTime={" + roleUpdateTime + "}"; + str += "gdsVersion={" + gdsVersion + "} "; + str += "gdsUpdateTime={" + gdsUpdateTime + "} "; + str += "}"; + return str; + } + + public int getMyClassType() { + return AppConstants.CLASS_TYPE_NONE; + } + + public String getMyDisplayValue() { + return null; + } + + public Long getId() { + return this.id; + } + + public void setId(Long id) { + this.id = id; + } + + public Long getVersion() { + return version; + } + + public void setVersion(Long version) { + this.version = version; + } + + public Long getServiceId() { + return this.serviceId; + } + + public void setServiceId(Long serviceId) { + this.serviceId = serviceId; + } + + public Long getPolicyVersion() { + return this.policyVersion; + } + + public void setPolicyVersion(Long policyVersion) { + this.policyVersion = policyVersion; + } + + public Date getPolicyUpdateTime() { + return this.policyUpdateTime; + } + + public void setPolicyUpdateTime(Date updateTime) { + this.policyUpdateTime = updateTime; + } + + public Long getTagVersion() { + return this.tagVersion; + } + + public void setTagVersion(Long tagVersion) { + this.tagVersion = tagVersion; + } + + public Date getTagUpdateTime() { + return this.tagUpdateTime; + } + + public void setTagUpdateTime(Date updateTime) { + this.tagUpdateTime = updateTime; + } + + public Long getRoleVersion() { + return this.roleVersion; + } + + public void setRoleVersion(Long roleVersion) { + this.roleVersion = roleVersion; + } + + public Date getRoleUpdateTime() { + return this.roleUpdateTime; + } + + public void setRoleUpdateTime(Date updateTime) { + this.roleUpdateTime = updateTime; + } + + public Long getGdsVersion() { + return this.gdsVersion; + } + + public void setGdsVersion(Long gdsVersion) { + this.gdsVersion = gdsVersion; + } + + public Date getGdsUpdateTime() { + return this.gdsUpdateTime; + } + + public void setGdsUpdateTime(Date updateTime) { + this.gdsUpdateTime = updateTime; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/entity/XXServiceWithAssignedId.java b/security-admin/src/main/java/org/apache/ranger/entity/XXServiceWithAssignedId.java index 1d1ed66140..21a149aa38 100644 --- a/security-admin/src/main/java/org/apache/ranger/entity/XXServiceWithAssignedId.java +++ b/security-admin/src/main/java/org/apache/ranger/entity/XXServiceWithAssignedId.java @@ -23,52 +23,53 @@ import javax.persistence.Id; import javax.persistence.Table; +import java.util.Objects; + @Entity @Cacheable @Table(name = "x_service") public class XXServiceWithAssignedId extends XXServiceBase { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; + + /** + * id of the XXService + *
    + *
+ */ + @Id + @Column(name = "id") + protected Long id; + + @Override + public Long getId() { + return id; + } + + @Override + public void setId(Long id) { + this.id = id; + } + + @Override + public int hashCode() { + return super.hashCode(); + } - /** - * id of the XXService - *
    - *
- * - */ - @Id - @Column(name = "id") - protected Long id; + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } else if (!super.equals(obj)) { + return false; + } - @Override - public void setId(Long id) { - this.id = id; - } + XXServiceWithAssignedId other = (XXServiceWithAssignedId) obj; - @Override - public Long getId() { - return id; - } - - @Override - public String toString() { - return "XXService [id=" + id + "]"; - } + return Objects.equals(id, other.id); + } - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (!super.equals(obj)) - return false; - if (getClass() != obj.getClass()) - return false; - XXServiceWithAssignedId other = (XXServiceWithAssignedId) obj; - if (id == null) { - if (other.id != null) - return false; - } else if (!id.equals(other.id)) - return false; - return true; - } - + @Override + public String toString() { + return "XXService [id=" + id + "]"; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/entity/XXTag.java b/security-admin/src/main/java/org/apache/ranger/entity/XXTag.java index 42a73d910c..74f6b5c5fb 100644 --- a/security-admin/src/main/java/org/apache/ranger/entity/XXTag.java +++ b/security-admin/src/main/java/org/apache/ranger/entity/XXTag.java @@ -19,7 +19,7 @@ package org.apache.ranger.entity; -import java.io.Serializable; +import org.apache.ranger.common.AppConstants; import javax.persistence.Cacheable; import javax.persistence.Column; @@ -31,209 +31,178 @@ import javax.persistence.Table; import javax.persistence.Version; -import org.apache.ranger.common.AppConstants; +import java.io.Serializable; +import java.util.Objects; @Entity @Cacheable -@Table(name="x_tag") +@Table(name = "x_tag") public class XXTag extends XXDBBase implements Serializable { - private static final long serialVersionUID = 1L; - - @Id - @SequenceGenerator(name = "X_TAG_SEQ", sequenceName = "X_TAG_SEQ", allocationSize = 1) - @GeneratedValue(strategy = GenerationType.AUTO, generator = "X_TAG_SEQ") - @Column(name = "id") - protected Long id; - - @Column(name = "guid", unique = true, nullable = false, length = 512) - protected String guid; - - @Version - @Column(name = "version") - protected Long version; - - @Column(name = "type") - protected Long type; - - @Column(name = "owned_by") - protected Short owner; - - @Column(name = "policy_options") - protected String options; - - @Column(name = "tag_attrs_text") - protected String tagAttrs; - - @Override - public void setId(Long id) { - this.id = id; - } - - @Override - public Long getId() { - return id; - } - - /** - * @return the guid - */ - public String getGuid() { - return guid; - } - - /** - * @param guid - * the guid to set - */ - public void setGuid(String guid) { - this.guid = guid; - } - - /** - * @return the version - */ - public Long getVersion() { - return version; - } - - /** - * @param version - * the version to set - */ - public void setVersion(Long version) { - this.version = version; - } - - /** - * @return the type - */ - public Long getType() { - return type; - } - - /** - * @param type - * the type to set - */ - public void setType(Long type) { - this.type = type; - } - - public Short getOwner() { return owner; } - public void setOwner(Short owner) { this.owner = owner; } - - public void setOptions(String options) { - this.options = options; - } - - public String getOptions() { - return this.options; - } - - public String getTagAttrs() { return tagAttrs; } - - public void setTagAttrs(String tagAttrs) { this.tagAttrs = tagAttrs; } + private static final long serialVersionUID = 1L; + + @Id + @SequenceGenerator(name = "X_TAG_SEQ", sequenceName = "X_TAG_SEQ", allocationSize = 1) + @GeneratedValue(strategy = GenerationType.AUTO, generator = "X_TAG_SEQ") + @Column(name = "id") + protected Long id; + + @Column(name = "guid", unique = true, nullable = false, length = 512) + protected String guid; + + @Version + @Column(name = "version") + protected Long version; + + @Column(name = "type") + protected Long type; + + @Column(name = "owned_by") + protected Short owner; + + @Column(name = "policy_options") + protected String options; + + @Column(name = "tag_attrs_text") + protected String tagAttrs; + + /** + * @return the guid + */ + public String getGuid() { + return guid; + } + + /** + * @param guid the guid to set + */ + public void setGuid(String guid) { + this.guid = guid; + } + + /** + * @return the version + */ + public Long getVersion() { + return version; + } + + /** + * @param version the version to set + */ + public void setVersion(Long version) { + this.version = version; + } + + /** + * @return the type + */ + public Long getType() { + return type; + } + + /** + * @param type the type to set + */ + public void setType(Long type) { + this.type = type; + } + + public Short getOwner() { + return owner; + } + + public void setOwner(Short owner) { + this.owner = owner; + } + + public String getOptions() { + return this.options; + } + + public void setOptions(String options) { + this.options = options; + } + + public String getTagAttrs() { + return tagAttrs; + } + + public void setTagAttrs(String tagAttrs) { + this.tagAttrs = tagAttrs; + } + + @Override + public int getMyClassType() { + return AppConstants.CLASS_TYPE_XA_TAG; + } @Override - public int getMyClassType() { - return AppConstants.CLASS_TYPE_XA_TAG; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#hashCode() - */ - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((version == null) ? 0 : version.hashCode()); - result = prime * result + ((guid == null) ? 0 : guid.hashCode()); - result = prime * result + ((id == null) ? 0 : id.hashCode()); - result = prime * result + ((type == null) ? 0 : type.hashCode()); - result = prime * result + ((owner == null) ? 0 : owner.hashCode()); - result = prime * result + ((options == null) ? 0 : options.hashCode()); - result = prime * result + ((tagAttrs == null) ? 0 : tagAttrs.hashCode()); - return result; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#equals(java.lang.Object) - */ - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (!super.equals(obj)) - return false; - if (getClass() != obj.getClass()) - return false; - XXTag other = (XXTag) obj; - if (version == null) { - if (other.version != null) - return false; - } else if (!version.equals(other.version)) - return false; - if (guid == null) { - if (other.guid != null) - return false; - } else if (!guid.equals(other.guid)) - return false; - if (id == null) { - if (other.id != null) - return false; - } else if (!id.equals(other.id)) - return false; - if (type == null) { - if (other.type != null) - return false; - } else if (!type.equals(other.type)) - return false; - if (owner == null) { - if (other.owner != null) - return false; - } else if (!owner.equals(other.owner)) - return false; - if (options == null) { - if (other.options != null) - return false; - } else if (!options.equals(other.options)) - - if (tagAttrs == null) { - if (other.tagAttrs != null) - return false; - } else if (!tagAttrs.equals(other.tagAttrs)) - return false; - return true; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#toString() - */ - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - toString(sb); - return sb.toString(); - } - - public StringBuilder toString(StringBuilder sb) { - sb.append("{ "); - sb.append(super.toString() + "} "); - sb.append("id={").append(id).append("} "); - sb.append("guid={").append(guid).append("} "); - sb.append("type={").append(type).append("} "); - sb.append("owned_by={").append(owner).append("} "); - sb.append("options={").append(options).append("} "); - sb.append("tagAttrs={").append(tagAttrs).append("} "); - sb.append(" }"); - - return sb; - } + public Long getId() { + return id; + } + @Override + public void setId(Long id) { + this.id = id; + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#hashCode() + */ + @Override + public int hashCode() { + return Objects.hash(super.hashCode(), version, guid, id, type, owner, options, tagAttrs); + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#equals(java.lang.Object) + */ + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } else if (!super.equals(obj)) { + return false; + } + + XXTag other = (XXTag) obj; + + return Objects.equals(version, other.version) && + Objects.equals(guid, other.guid) && + Objects.equals(id, other.id) && + Objects.equals(type, other.type) && + Objects.equals(owner, other.owner) && + Objects.equals(options, other.options) && + Objects.equals(tagAttrs, other.tagAttrs); + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + toString(sb); + return sb.toString(); + } + + public StringBuilder toString(StringBuilder sb) { + sb.append("{ "); + sb.append(super.toString()).append("} "); + sb.append("id={").append(id).append("} "); + sb.append("guid={").append(guid).append("} "); + sb.append("type={").append(type).append("} "); + sb.append("owned_by={").append(owner).append("} "); + sb.append("options={").append(options).append("} "); + sb.append("tagAttrs={").append(tagAttrs).append("} "); + sb.append(" }"); + + return sb; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/entity/XXTagAttribute.java b/security-admin/src/main/java/org/apache/ranger/entity/XXTagAttribute.java index a9ae637124..126eb1e52b 100644 --- a/security-admin/src/main/java/org/apache/ranger/entity/XXTagAttribute.java +++ b/security-admin/src/main/java/org/apache/ranger/entity/XXTagAttribute.java @@ -19,7 +19,7 @@ package org.apache.ranger.entity; -import java.io.Serializable; +import org.apache.ranger.common.AppConstants; import javax.persistence.Cacheable; import javax.persistence.Column; @@ -30,164 +30,139 @@ import javax.persistence.SequenceGenerator; import javax.persistence.Table; -import org.apache.ranger.common.AppConstants; +import java.io.Serializable; +import java.util.Objects; @Entity @Cacheable -@Table(name="x_tag_attr") +@Table(name = "x_tag_attr") public class XXTagAttribute extends XXDBBase implements Serializable { - private static final long serialVersionUID = 1L; - - @Id - @SequenceGenerator(name = "X_TAG_ATTR_SEQ", sequenceName = "X_TAG_ATTR_SEQ", allocationSize = 1) - @GeneratedValue(strategy = GenerationType.AUTO, generator = "X_TAG_ATTR_SEQ") - @Column(name = "id") - protected Long id; - - @Column(name = "tag_id") - protected Long tagId; - - @Column(name = "name") - protected String name; - - @Column(name = "value") - protected String value; - - @Override - public void setId(Long id) { - this.id = id; - } - - @Override - public Long getId() { - return id; - } - - /** - * @return the tagId - */ - public Long getTagId() { - return tagId; - } - - /** - * @param tagId - * the tagId to set - */ - public void setTagId(Long tagId) { - this.tagId = tagId; - } - - /** - * @return the name - */ - public String getName() { - return name; - } - - /** - * @param name - * the name to set - */ - public void setName(String name) { - this.name = name; - } - - /** - * @return the value - */ - public String getValue() { - return value; - } - - /** - * @param value - * the value to set - */ - public void setValue(String value) { - this.value = value; - } - - @Override - public int getMyClassType() { - return AppConstants.CLASS_TYPE_XA_TAG_ATTR; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#hashCode() - */ - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((id == null) ? 0 : id.hashCode()); - result = prime * result + ((name == null) ? 0 : name.hashCode()); - result = prime * result + ((tagId == null) ? 0 : tagId.hashCode()); - result = prime * result + ((value == null) ? 0 : value.hashCode()); - return result; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#equals(java.lang.Object) - */ - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (!super.equals(obj)) - return false; - if (getClass() != obj.getClass()) - return false; - XXTagAttribute other = (XXTagAttribute) obj; - if (id == null) { - if (other.id != null) - return false; - } else if (!id.equals(other.id)) - return false; - if (name == null) { - if (other.name != null) - return false; - } else if (!name.equals(other.name)) - return false; - if (tagId == null) { - if (other.tagId != null) - return false; - } else if (!tagId.equals(other.tagId)) - return false; - if (value == null) { - if (other.value != null) - return false; - } else if (!value.equals(other.value)) - return false; - return true; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#toString() - */ - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - toString(sb); - return sb.toString(); - } - - public StringBuilder toString(StringBuilder sb) { - sb.append("{ "); - sb.append(super.toString() + "} "); - sb.append("id={").append(id).append("} "); - sb.append("tagId={").append(tagId).append("} "); - sb.append("name={").append(name).append("} "); - sb.append("value={").append(value).append("} "); - sb.append(" }"); - - return sb; - } - + private static final long serialVersionUID = 1L; + + @Id + @SequenceGenerator(name = "X_TAG_ATTR_SEQ", sequenceName = "X_TAG_ATTR_SEQ", allocationSize = 1) + @GeneratedValue(strategy = GenerationType.AUTO, generator = "X_TAG_ATTR_SEQ") + @Column(name = "id") + protected Long id; + + @Column(name = "tag_id") + protected Long tagId; + + @Column(name = "name") + protected String name; + + @Column(name = "value") + protected String value; + + /** + * @return the tagId + */ + public Long getTagId() { + return tagId; + } + + /** + * @param tagId the tagId to set + */ + public void setTagId(Long tagId) { + this.tagId = tagId; + } + + /** + * @return the name + */ + public String getName() { + return name; + } + + /** + * @param name the name to set + */ + public void setName(String name) { + this.name = name; + } + + /** + * @return the value + */ + public String getValue() { + return value; + } + + /** + * @param value the value to set + */ + public void setValue(String value) { + this.value = value; + } + + @Override + public int getMyClassType() { + return AppConstants.CLASS_TYPE_XA_TAG_ATTR; + } + + @Override + public Long getId() { + return id; + } + + @Override + public void setId(Long id) { + this.id = id; + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#hashCode() + */ + @Override + public int hashCode() { + return Objects.hash(super.hashCode(), id, name, tagId, value); + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#equals(java.lang.Object) + */ + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } else if (!super.equals(obj)) { + return false; + } + + XXTagAttribute other = (XXTagAttribute) obj; + + return Objects.equals(id, other.id) && + Objects.equals(name, other.name) && + Objects.equals(tagId, other.tagId) && + Objects.equals(value, other.value); + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + toString(sb); + return sb.toString(); + } + + public StringBuilder toString(StringBuilder sb) { + sb.append("{ "); + sb.append(super.toString()).append("} "); + sb.append("id={").append(id).append("} "); + sb.append("tagId={").append(tagId).append("} "); + sb.append("name={").append(name).append("} "); + sb.append("value={").append(value).append("} "); + sb.append(" }"); + + return sb; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/entity/XXTagAttributeDef.java b/security-admin/src/main/java/org/apache/ranger/entity/XXTagAttributeDef.java index 8b7eb23ce1..953d5fbf9b 100644 --- a/security-admin/src/main/java/org/apache/ranger/entity/XXTagAttributeDef.java +++ b/security-admin/src/main/java/org/apache/ranger/entity/XXTagAttributeDef.java @@ -19,7 +19,7 @@ package org.apache.ranger.entity; -import java.io.Serializable; +import org.apache.ranger.common.AppConstants; import javax.persistence.Cacheable; import javax.persistence.Column; @@ -30,164 +30,139 @@ import javax.persistence.SequenceGenerator; import javax.persistence.Table; -import org.apache.ranger.common.AppConstants; +import java.io.Serializable; +import java.util.Objects; @Entity @Cacheable @Table(name = "x_tag_attr_def") public class XXTagAttributeDef extends XXDBBase implements Serializable { - private static final long serialVersionUID = 1L; - - @Id - @SequenceGenerator(name = "X_TAG_ATTR_DEF_SEQ", sequenceName = "X_TAG_ATTR_DEF_SEQ", allocationSize = 1) - @GeneratedValue(strategy = GenerationType.AUTO, generator = "X_TAG_ATTR_DEF_SEQ") - @Column(name = "id") - protected Long id; - - @Column(name = "tag_def_id") - protected Long tagDefId; - - @Column(name = "name") - protected String name; - - @Column(name = "type") - protected String type; - - @Override - public void setId(Long id) { - this.id = id; - } - - @Override - public Long getId() { - return id; - } - - /** - * @return the tagDefId - */ - public Long getTagDefId() { - return tagDefId; - } - - /** - * @param tagDefId - * the tagDefId to set - */ - public void setTagDefId(Long tagDefId) { - this.tagDefId = tagDefId; - } - - /** - * @return the name - */ - public String getName() { - return name; - } - - /** - * @param name - * the name to set - */ - public void setName(String name) { - this.name = name; - } - - /** - * @return the type - */ - public String getType() { - return type; - } - - /** - * @param type - * the type to set - */ - public void setType(String type) { - this.type = type; - } - - @Override - public int getMyClassType() { - return AppConstants.CLASS_TYPE_XA_TAG_ATTR_DEF; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#hashCode() - */ - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((id == null) ? 0 : id.hashCode()); - result = prime * result + ((name == null) ? 0 : name.hashCode()); - result = prime * result + ((tagDefId == null) ? 0 : tagDefId.hashCode()); - result = prime * result + ((type == null) ? 0 : type.hashCode()); - return result; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#equals(java.lang.Object) - */ - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (!super.equals(obj)) - return false; - if (getClass() != obj.getClass()) - return false; - XXTagAttributeDef other = (XXTagAttributeDef) obj; - if (id == null) { - if (other.id != null) - return false; - } else if (!id.equals(other.id)) - return false; - if (name == null) { - if (other.name != null) - return false; - } else if (!name.equals(other.name)) - return false; - if (tagDefId == null) { - if (other.tagDefId != null) - return false; - } else if (!tagDefId.equals(other.tagDefId)) - return false; - if (type == null) { - if (other.type != null) - return false; - } else if (!type.equals(other.type)) - return false; - return true; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#toString() - */ - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - toString(sb); - return sb.toString(); - } - - public StringBuilder toString(StringBuilder sb) { - sb.append("{ "); - sb.append(super.toString() + "} "); - sb.append("id={").append(id).append("} "); - sb.append("tagDefId={").append(tagDefId).append("} "); - sb.append("name={").append(name).append("} "); - sb.append("type={").append(type).append("} "); - sb.append(" }"); - - return sb; - } - + private static final long serialVersionUID = 1L; + + @Id + @SequenceGenerator(name = "X_TAG_ATTR_DEF_SEQ", sequenceName = "X_TAG_ATTR_DEF_SEQ", allocationSize = 1) + @GeneratedValue(strategy = GenerationType.AUTO, generator = "X_TAG_ATTR_DEF_SEQ") + @Column(name = "id") + protected Long id; + + @Column(name = "tag_def_id") + protected Long tagDefId; + + @Column(name = "name") + protected String name; + + @Column(name = "type") + protected String type; + + /** + * @return the tagDefId + */ + public Long getTagDefId() { + return tagDefId; + } + + /** + * @param tagDefId the tagDefId to set + */ + public void setTagDefId(Long tagDefId) { + this.tagDefId = tagDefId; + } + + /** + * @return the name + */ + public String getName() { + return name; + } + + /** + * @param name the name to set + */ + public void setName(String name) { + this.name = name; + } + + /** + * @return the type + */ + public String getType() { + return type; + } + + /** + * @param type the type to set + */ + public void setType(String type) { + this.type = type; + } + + @Override + public int getMyClassType() { + return AppConstants.CLASS_TYPE_XA_TAG_ATTR_DEF; + } + + @Override + public Long getId() { + return id; + } + + @Override + public void setId(Long id) { + this.id = id; + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#hashCode() + */ + @Override + public int hashCode() { + return Objects.hash(super.hashCode(), id, name, tagDefId, type); + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#equals(java.lang.Object) + */ + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } else if (!super.equals(obj)) { + return false; + } + + XXTagAttributeDef other = (XXTagAttributeDef) obj; + + return Objects.equals(id, other.id) && + Objects.equals(name, other.name) && + Objects.equals(tagDefId, other.tagDefId) && + Objects.equals(type, other.type); + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + toString(sb); + return sb.toString(); + } + + public StringBuilder toString(StringBuilder sb) { + sb.append("{ "); + sb.append(super.toString()).append("} "); + sb.append("id={").append(id).append("} "); + sb.append("tagDefId={").append(tagDefId).append("} "); + sb.append("name={").append(name).append("} "); + sb.append("type={").append(type).append("} "); + sb.append(" }"); + + return sb; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/entity/XXTagChangeLog.java b/security-admin/src/main/java/org/apache/ranger/entity/XXTagChangeLog.java index 79264f63cd..7657123544 100644 --- a/security-admin/src/main/java/org/apache/ranger/entity/XXTagChangeLog.java +++ b/security-admin/src/main/java/org/apache/ranger/entity/XXTagChangeLog.java @@ -19,12 +19,12 @@ package org.apache.ranger.entity; -import java.util.Date; -import java.util.Objects; +import org.apache.ranger.common.AppConstants; +import org.apache.ranger.common.DateUtil; import javax.persistence.Cacheable; -import javax.persistence.Entity; import javax.persistence.Column; +import javax.persistence.Entity; import javax.persistence.EntityListeners; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; @@ -34,10 +34,10 @@ import javax.persistence.Temporal; import javax.persistence.TemporalType; -import org.apache.ranger.common.AppConstants; -import org.apache.ranger.common.DateUtil; +import java.util.Date; +import java.util.Objects; -@EntityListeners( org.apache.ranger.common.db.JPABeanCallbacks.class) +@EntityListeners(org.apache.ranger.common.db.JPABeanCallbacks.class) @Entity @Cacheable @Table(name = "x_tag_change_log") @@ -51,7 +51,7 @@ public class XXTagChangeLog implements java.io.Serializable { protected Long id; @Temporal(TemporalType.TIMESTAMP) - @Column(name="create_time" ) + @Column(name = "create_time") protected Date createTime = DateUtil.getUTCDate(); @Column(name = "service_id") @@ -72,11 +72,11 @@ public class XXTagChangeLog implements java.io.Serializable { /** * Default constructor. This will set all the attributes to default value. */ - public XXTagChangeLog( ) { + public XXTagChangeLog() { this(null, null, null, null, null, null, null); } - public XXTagChangeLog(Long id, Integer changeType, Long serviceTagsVersion, Long serviceResourceId, Long tagId) { + public XXTagChangeLog(Long id, Integer changeType, Long serviceTagsVersion, Long serviceResourceId, Long tagId) { this(id, null, null, changeType, serviceTagsVersion, serviceResourceId, tagId); } @@ -90,7 +90,7 @@ public XXTagChangeLog(Long id, Date createTime, Long serviceId, Integer changeTy setTagId(tagId); } - public int getMyClassType( ) { + public int getMyClassType() { return AppConstants.CLASS_TYPE_NONE; } @@ -98,94 +98,103 @@ public String getMyDisplayValue() { return null; } + public Long getId() { + return this.id; + } + public void setId(Long id) { this.id = id; } - public Long getId() { - return this.id; + public Date getCreateTime() { + return this.createTime; } - public void setCreateTime( Date createTime ) { + public void setCreateTime(Date createTime) { this.createTime = createTime; } - public Date getCreateTime( ) { - return this.createTime; + public Long getServiceId() { + return this.serviceId; } public void setServiceId(Long serviceId) { this.serviceId = serviceId; } - public Long getServiceId() { - return this.serviceId; + public Integer getChangeType() { + return this.changeType; } - public void setChangeType(Integer changeType) { this.changeType = changeType; } + public void setChangeType(Integer changeType) { + this.changeType = changeType; + } - public Integer getChangeType() { return this.changeType; } + public Long getServiceTagsVersion() { + return this.serviceTagsVersion; + } public void setServiceTagsVersion(Long serviceTagsVersion) { this.serviceTagsVersion = serviceTagsVersion; } - public Long getServiceTagsVersion() { - return this.serviceTagsVersion; + public Long getServiceResourceId() { + return this.serviceResourceId; } - public Long getServiceResourceId() { return this.serviceResourceId; } - public void setServiceResourceId(Long serviceResourceId) { this.serviceResourceId = serviceResourceId; } - public Long getTagId() { return this.tagId; } + public Long getTagId() { + return this.tagId; + } public void setTagId(Long tagId) { this.tagId = tagId; } - /** - * This return the bean content in string format - * @return formatedStr - */ @Override - public String toString( ) { - String str = "XXTagChangeLog={"; - str += "id={" + id + "} "; - str += "createTime={" + createTime + "} "; - str += "serviceId={" + serviceId + "} "; - str += "changeType={" + changeType + "} "; - str += "serviceTagsVersion={" + serviceTagsVersion + "} "; - str += "serviceResourceId={" + serviceResourceId + "} "; - str += "tagId={" + tagId + "} "; - str += "}"; - return str; + public int hashCode() { + return super.hashCode(); } /** * Checks for all attributes except referenced db objects + * * @return true if all attributes match */ @Override - public boolean equals( Object obj) { - if (obj == null) - return false; - if (this == obj) + public boolean equals(Object obj) { + if (this == obj) { return true; - if (!super.equals(obj)) + } else if (obj == null) { return false; - if (getClass() != obj.getClass()) + } else if (getClass() != obj.getClass()) { return false; + } XXTagChangeLog other = (XXTagChangeLog) obj; - return Objects.equals(this.id, other.id) && Objects.equals(this.createTime, other.createTime) && Objects.equals(this.serviceId, other.serviceId) - && Objects.equals(this.changeType, other.changeType) && Objects.equals(this.serviceTagsVersion, other.serviceTagsVersion) - && Objects.equals(this.serviceResourceId, other.serviceResourceId) && Objects.equals(this.tagId, other.tagId); + return Objects.equals(this.id, other.id) && Objects.equals(this.createTime, other.createTime) && Objects.equals(this.serviceId, other.serviceId) && Objects.equals(this.changeType, other.changeType) && Objects.equals(this.serviceTagsVersion, other.serviceTagsVersion) && Objects.equals(this.serviceResourceId, other.serviceResourceId) && Objects.equals(this.tagId, other.tagId); } + /** + * This return the bean content in string format + * + * @return formatedStr + */ + @Override + public String toString() { + String str = "XXTagChangeLog={"; + str += "id={" + id + "} "; + str += "createTime={" + createTime + "} "; + str += "serviceId={" + serviceId + "} "; + str += "changeType={" + changeType + "} "; + str += "serviceTagsVersion={" + serviceTagsVersion + "} "; + str += "serviceResourceId={" + serviceResourceId + "} "; + str += "tagId={" + tagId + "} "; + str += "}"; + return str; + } } - - diff --git a/security-admin/src/main/java/org/apache/ranger/entity/XXTagDef.java b/security-admin/src/main/java/org/apache/ranger/entity/XXTagDef.java index 7aeaf2354f..f48cfd0a53 100644 --- a/security-admin/src/main/java/org/apache/ranger/entity/XXTagDef.java +++ b/security-admin/src/main/java/org/apache/ranger/entity/XXTagDef.java @@ -19,7 +19,7 @@ package org.apache.ranger.entity; -import java.io.Serializable; +import org.apache.ranger.common.AppConstants; import javax.persistence.Cacheable; import javax.persistence.Column; @@ -31,229 +31,191 @@ import javax.persistence.Table; import javax.persistence.Version; -import org.apache.ranger.common.AppConstants; +import java.io.Serializable; +import java.util.Objects; @Entity @Cacheable @Table(name = "x_tag_def") public class XXTagDef extends XXDBBase implements Serializable { - private static final long serialVersionUID = 1L; - - @Id - @SequenceGenerator(name = "X_TAG_DEF_SEQ", sequenceName = "X_TAG_DEF_SEQ", allocationSize = 1) - @GeneratedValue(strategy = GenerationType.AUTO, generator = "X_TAG_DEF_SEQ") - @Column(name = "id") - protected Long id; - - @Column(name = "guid", unique = true, nullable = false, length = 512) - protected String guid; - - @Version - @Column(name = "version") - protected Long version; - - @Column(name = "is_enabled") - protected Boolean isEnabled; - - @Column(name = "name") - protected String name; - - @Column(name = "source") - protected String source; - - @Column(name = "tag_attrs_def_text") - protected String tagAttrDefs; - - /** - * @return the guid - */ - public String getGuid() { - return guid; - } - - /** - * @param guid - * the guid to set - */ - public void setGuid(String guid) { - this.guid = guid; - } - - /** - * @return the version - */ - public Long getVersion() { - return version; - } - - /** - * @param version - * the version to set - */ - public void setVersion(Long version) { - this.version = version; - } - - /** - * @return the isEnabled - */ - public Boolean getIsEnabled() { - return isEnabled; - } - - /** - * @param isEnabled - * the isEnabled to set - */ - public void setIsEnabled(Boolean isEnabled) { - this.isEnabled = isEnabled; - } - - /** - * @return the name - */ - public String getName() { - return name; - } - - /** - * @param name - * the name to set - */ - public void setName(String name) { - this.name = name; - } - - /** - * @return the source - */ - public String getSource() { - return source; - } - - /** - * @param source - * the source to set - */ - public void setSource(String source) { - this.source = source; - } - - public String getTagAttrDefs() { return tagAttrDefs; } - - public void setTagAttrDefs(String tagAttrDefs) { this.tagAttrDefs = tagAttrDefs; } - - @Override - public void setId(Long id) { - this.id = id; - } - - @Override - public Long getId() { - return id; - } - - @Override - public int getMyClassType() { - return AppConstants.CLASS_TYPE_XA_TAG_DEF; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#hashCode() - */ - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((guid == null) ? 0 : guid.hashCode()); - result = prime * result + ((id == null) ? 0 : id.hashCode()); - result = prime * result + ((isEnabled == null) ? 0 : isEnabled.hashCode()); - result = prime * result + ((name == null) ? 0 : name.hashCode()); - result = prime * result + ((source == null) ? 0 : source.hashCode()); - result = prime * result + ((version == null) ? 0 : version.hashCode()); - result = prime * result + ((tagAttrDefs == null) ? 0 : tagAttrDefs.hashCode()); - return result; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#equals(java.lang.Object) - */ - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (!super.equals(obj)) - return false; - if (getClass() != obj.getClass()) - return false; - XXTagDef other = (XXTagDef) obj; - if (guid == null) { - if (other.guid != null) - return false; - } else if (!guid.equals(other.guid)) - return false; - if (id == null) { - if (other.id != null) - return false; - } else if (!id.equals(other.id)) - return false; - if (isEnabled == null) { - if (other.isEnabled != null) - return false; - } else if (!isEnabled.equals(other.isEnabled)) - return false; - if (name == null) { - if (other.name != null) - return false; - } else if (!name.equals(other.name)) - return false; - if (source == null) { - if (other.source != null) - return false; - } else if (!source.equals(other.source)) - return false; - if (version == null) { - if (other.version != null) - return false; - } else if (!version.equals(other.version)) - return false; - if (tagAttrDefs == null) { - if (other.tagAttrDefs != null) - return false; - } else if (!tagAttrDefs.equals(other.tagAttrDefs)) - return false; - return true; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#toString() - */ - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - toString(sb); - return sb.toString(); - } - - public StringBuilder toString(StringBuilder sb) { - sb.append("{ "); - sb.append(super.toString() + "} "); - sb.append("id={").append(id).append("} "); - sb.append("guid={").append(guid).append("} "); - sb.append("version={").append(version).append("} "); - sb.append("isEnabled={").append(isEnabled).append("} "); - sb.append("source={").append(source).append("} "); - sb.append("name={").append(name).append("} "); - sb.append("tagAttrDefs={").append(tagAttrDefs).append("} "); - sb.append(" }"); - - return sb; - } - + private static final long serialVersionUID = 1L; + + @Id + @SequenceGenerator(name = "X_TAG_DEF_SEQ", sequenceName = "X_TAG_DEF_SEQ", allocationSize = 1) + @GeneratedValue(strategy = GenerationType.AUTO, generator = "X_TAG_DEF_SEQ") + @Column(name = "id") + protected Long id; + + @Column(name = "guid", unique = true, nullable = false, length = 512) + protected String guid; + + @Version + @Column(name = "version") + protected Long version; + + @Column(name = "is_enabled") + protected Boolean isEnabled; + + @Column(name = "name") + protected String name; + + @Column(name = "source") + protected String source; + + @Column(name = "tag_attrs_def_text") + protected String tagAttrDefs; + + /** + * @return the guid + */ + public String getGuid() { + return guid; + } + + /** + * @param guid the guid to set + */ + public void setGuid(String guid) { + this.guid = guid; + } + + /** + * @return the version + */ + public Long getVersion() { + return version; + } + + /** + * @param version the version to set + */ + public void setVersion(Long version) { + this.version = version; + } + + /** + * @return the isEnabled + */ + public Boolean getIsEnabled() { + return isEnabled; + } + + /** + * @param isEnabled the isEnabled to set + */ + public void setIsEnabled(Boolean isEnabled) { + this.isEnabled = isEnabled; + } + + /** + * @return the name + */ + public String getName() { + return name; + } + + /** + * @param name the name to set + */ + public void setName(String name) { + this.name = name; + } + + /** + * @return the source + */ + public String getSource() { + return source; + } + + /** + * @param source the source to set + */ + public void setSource(String source) { + this.source = source; + } + + public String getTagAttrDefs() { + return tagAttrDefs; + } + + public void setTagAttrDefs(String tagAttrDefs) { + this.tagAttrDefs = tagAttrDefs; + } + + @Override + public int getMyClassType() { + return AppConstants.CLASS_TYPE_XA_TAG_DEF; + } + + @Override + public Long getId() { + return id; + } + + @Override + public void setId(Long id) { + this.id = id; + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#hashCode() + */ + @Override + public int hashCode() { + return Objects.hash(super.hashCode(), guid, id, isEnabled, name, source, version, tagAttrDefs); + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#equals(java.lang.Object) + */ + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } else if (!super.equals(obj)) { + return false; + } + + XXTagDef other = (XXTagDef) obj; + + return Objects.equals(guid, other.guid) && + Objects.equals(id, other.id) && + Objects.equals(isEnabled, other.isEnabled) && + Objects.equals(name, other.name) && + Objects.equals(source, other.source) && + Objects.equals(version, other.version) && + Objects.equals(tagAttrDefs, other.tagAttrDefs); + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + toString(sb); + return sb.toString(); + } + + public StringBuilder toString(StringBuilder sb) { + sb.append("{ "); + sb.append(super.toString()).append("} "); + sb.append("id={").append(id).append("} "); + sb.append("guid={").append(guid).append("} "); + sb.append("version={").append(version).append("} "); + sb.append("isEnabled={").append(isEnabled).append("} "); + sb.append("source={").append(source).append("} "); + sb.append("name={").append(name).append("} "); + sb.append("tagAttrDefs={").append(tagAttrDefs).append("} "); + sb.append(" }"); + + return sb; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/entity/XXTagResourceMap.java b/security-admin/src/main/java/org/apache/ranger/entity/XXTagResourceMap.java index 64625b5063..2de0681f94 100644 --- a/security-admin/src/main/java/org/apache/ranger/entity/XXTagResourceMap.java +++ b/security-admin/src/main/java/org/apache/ranger/entity/XXTagResourceMap.java @@ -19,7 +19,7 @@ package org.apache.ranger.entity; -import java.io.Serializable; +import org.apache.ranger.common.AppConstants; import javax.persistence.Cacheable; import javax.persistence.Column; @@ -30,164 +30,139 @@ import javax.persistence.SequenceGenerator; import javax.persistence.Table; -import org.apache.ranger.common.AppConstants; +import java.io.Serializable; +import java.util.Objects; @Entity @Cacheable -@Table(name="x_tag_resource_map") +@Table(name = "x_tag_resource_map") public class XXTagResourceMap extends XXDBBase implements Serializable { - private static final long serialVersionUID = 1L; - - @Id - @SequenceGenerator(name = "X_TAG_RESOURCE_MAP_SEQ", sequenceName = "X_TAG_RESOURCE_MAP_SEQ", allocationSize = 1) - @GeneratedValue(strategy = GenerationType.AUTO, generator = "X_TAG_RESOURCE_MAP_SEQ") - @Column(name = "id") - protected Long id; - - @Column(name = "guid", unique = true, nullable = false, length = 512) - protected String guid; - - @Column(name = "tag_id") - protected Long tagId; - - @Column(name = "res_id") - protected Long resourceId; - - @Override - public void setId(Long id) { - this.id = id; - } - - @Override - public Long getId() { - return id; - } - - /** - * @return the guid - */ - public String getGuid() { - return guid; - } - - /** - * @param guid - * the guid to set - */ - public void setGuid(String guid) { - this.guid = guid; - } - - /** - * @return the tagId - */ - public Long getTagId() { - return tagId; - } - - /** - * @param tagId - * the tagId to set - */ - public void setTagId(Long tagId) { - this.tagId = tagId; - } - - /** - * @return the resourceId - */ - public Long getResourceId() { - return resourceId; - } - - /** - * @param resourceId - * the resourceId to set - */ - public void setResourceId(Long resourceId) { - this.resourceId = resourceId; - } - - @Override - public int getMyClassType() { - return AppConstants.CLASS_TYPE_XA_TAG_RESOURCE_MAP; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#hashCode() - */ - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((guid == null) ? 0 : guid.hashCode()); - result = prime * result + ((id == null) ? 0 : id.hashCode()); - result = prime * result + ((tagId == null) ? 0 : tagId.hashCode()); - result = prime * result + ((resourceId == null) ? 0 : resourceId.hashCode()); - return result; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#equals(java.lang.Object) - */ - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (!super.equals(obj)) - return false; - if (getClass() != obj.getClass()) - return false; - XXTagResourceMap other = (XXTagResourceMap) obj; - if (guid == null) { - if (other.guid != null) - return false; - } else if (!guid.equals(other.guid)) - return false; - if (id == null) { - if (other.id != null) - return false; - } else if (!id.equals(other.id)) - return false; - if (tagId == null) { - if (other.tagId != null) - return false; - } else if (!tagId.equals(other.tagId)) - return false; - if (resourceId == null) { - if (other.resourceId != null) - return false; - } else if (!resourceId.equals(other.resourceId)) - return false; - return true; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#toString() - */ - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - toString(sb); - return sb.toString(); - } - - public StringBuilder toString(StringBuilder sb) { - sb.append("{ "); - sb.append(super.toString() + "} "); - sb.append("id={").append(id).append("} "); - sb.append("guid={").append(guid).append("} "); - sb.append("tagId={").append(tagId).append("} "); - sb.append("resourceId={").append(resourceId).append("} "); - sb.append(" }"); - - return sb; - } - + private static final long serialVersionUID = 1L; + + @Id + @SequenceGenerator(name = "X_TAG_RESOURCE_MAP_SEQ", sequenceName = "X_TAG_RESOURCE_MAP_SEQ", allocationSize = 1) + @GeneratedValue(strategy = GenerationType.AUTO, generator = "X_TAG_RESOURCE_MAP_SEQ") + @Column(name = "id") + protected Long id; + + @Column(name = "guid", unique = true, nullable = false, length = 512) + protected String guid; + + @Column(name = "tag_id") + protected Long tagId; + + @Column(name = "res_id") + protected Long resourceId; + + /** + * @return the guid + */ + public String getGuid() { + return guid; + } + + /** + * @param guid the guid to set + */ + public void setGuid(String guid) { + this.guid = guid; + } + + /** + * @return the tagId + */ + public Long getTagId() { + return tagId; + } + + /** + * @param tagId the tagId to set + */ + public void setTagId(Long tagId) { + this.tagId = tagId; + } + + /** + * @return the resourceId + */ + public Long getResourceId() { + return resourceId; + } + + /** + * @param resourceId the resourceId to set + */ + public void setResourceId(Long resourceId) { + this.resourceId = resourceId; + } + + @Override + public int getMyClassType() { + return AppConstants.CLASS_TYPE_XA_TAG_RESOURCE_MAP; + } + + @Override + public Long getId() { + return id; + } + + @Override + public void setId(Long id) { + this.id = id; + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#hashCode() + */ + @Override + public int hashCode() { + return Objects.hash(super.hashCode(), guid, id, tagId, resourceId); + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#equals(java.lang.Object) + */ + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } else if (!super.equals(obj)) { + return false; + } + + XXTagResourceMap other = (XXTagResourceMap) obj; + + return Objects.equals(guid, other.guid) && + Objects.equals(id, other.id) && + Objects.equals(tagId, other.tagId) && + Objects.equals(resourceId, other.resourceId); + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + toString(sb); + return sb.toString(); + } + + public StringBuilder toString(StringBuilder sb) { + sb.append("{ "); + sb.append(super.toString()).append("} "); + sb.append("id={").append(id).append("} "); + sb.append("guid={").append(guid).append("} "); + sb.append("tagId={").append(tagId).append("} "); + sb.append("resourceId={").append(resourceId).append("} "); + sb.append(" }"); + + return sb; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/entity/XXTrxLog.java b/security-admin/src/main/java/org/apache/ranger/entity/XXTrxLog.java index 9722f9ce1a..00f5c3f2e1 100644 --- a/security-admin/src/main/java/org/apache/ranger/entity/XXTrxLog.java +++ b/security-admin/src/main/java/org/apache/ranger/entity/XXTrxLog.java @@ -17,13 +17,15 @@ * under the License. */ - package org.apache.ranger.entity; +package org.apache.ranger.entity; /** * Logging table for all DB create and update queries - * */ +import org.apache.ranger.common.AppConstants; +import org.apache.ranger.common.RangerConstants; + import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; @@ -32,504 +34,505 @@ import javax.persistence.SequenceGenerator; import javax.persistence.Table; -import org.apache.ranger.common.AppConstants; -import org.apache.ranger.common.RangerConstants; - +import java.util.Objects; @Entity -@Table(name="x_trx_log") +@Table(name = "x_trx_log") 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 - *
    - *
  • This attribute is of type enum CommonEnums::ClassTypes - *
- * - */ - @Column(name="CLASS_TYPE" , nullable=false ) - protected int objectClassType = RangerConstants.CLASS_TYPE_NONE; - - /** - * Id of the object to which this notes refers to - *
    - *
- * - */ - @Column(name="OBJECT_ID" ) - protected Long objectId; - - /** - * Object Id of the parent object - *
    - *
- * - */ - @Column(name="PARENT_OBJECT_ID" ) - protected Long parentObjectId; - - /** - * Object Class Type of the parent object - *
    - *
- * - */ - @Column(name="PARENT_OBJECT_CLASS_TYPE" , nullable=false ) - protected int parentObjectClassType; - - /** - * Name of the attribute that was changed - *
    - *
  • The maximum length for this attribute is 1024. - *
- * - */ - @Column(name="PARENT_OBJECT_NAME" , length=1024) - protected String parentObjectName; - - /** - * Name of the attribute that was changed - *
    - *
  • The maximum length for this attribute is 1024. - *
- * - */ - @Column(name="OBJECT_NAME" , length=1024) - protected String objectName; - - /** - * Name of the attribute that was changed - *
    - *
  • The maximum length for this attribute is 255. - *
- * - */ - @Column(name="ATTR_NAME" , length=255) - protected String attributeName; - - /** - * Previous value - *
    - *
  • The maximum length for this attribute is 1024. - *
- * - */ - @Column(name="PREV_VAL" , length=1024) - protected String previousValue; - - /** - * New value - *
    - *
  • The maximum length for this attribute is 1024. - *
- * - */ - @Column(name="NEW_VAL" , length=1024) - protected String newValue; - - /** - * Transaction id - *
    - *
  • The maximum length for this attribute is 1024. - *
- * - */ - @Column(name="TRX_ID" , length=1024) - protected String transactionId; - - /** - * Action of the transaction - *
    - *
  • The maximum length for this attribute is 255. - *
- * - */ - @Column(name="ACTION" , length=255) - protected String action; - - /** - * Session Id - *
    - *
  • The maximum length for this attribute is 512. - *
- * - */ - @Column(name="SESS_ID" , length=512) - protected String sessionId; - - /** - * Request Id - *
    - *
- * - */ - @Column(name="REQ_ID" ) - protected String requestId; - - /** - * Session Type - *
    - *
- * - */ - @Column(name="SESS_TYPE" ) - protected String sessionType; - - /** - * Default constructor. This will set all the attributes to default value. - */ - public XXTrxLog ( ) { - objectClassType = RangerConstants.CLASS_TYPE_NONE; - } - - public XXTrxLog(int objectClassType, Long objectId, String objectName, String action, String attributeName, String previousValue, String newValue) { - this.objectClassType = objectClassType; - this.objectId = objectId; - this.objectName = objectName; - this.action = action; - this.attributeName = attributeName; - this.previousValue = previousValue; - this.newValue = newValue; - } - - @Override - public int getMyClassType( ) { - return AppConstants.CLASS_TYPE_TRX_LOG; - } - - /** - * This method sets the value to the member attribute objectClassType. - * You cannot set null to the attribute. - * @param objectClassType Value to set member attribute objectClassType - */ - public void setObjectClassType( int objectClassType ) { - this.objectClassType = objectClassType; - } - - /** - * Returns the value for the member attribute objectClassType - * @return int - value of member attribute objectClassType. - */ - public int getObjectClassType( ) { - return this.objectClassType; - } - - /** - * This method sets the value to the member attribute objectId. - * You cannot set null to the attribute. - * @param objectId Value to set member attribute objectId - */ - public void setObjectId( Long objectId ) { - this.objectId = objectId; - } - - /** - * Returns the value for the member attribute objectId - * @return Long - value of member attribute objectId. - */ - public Long getObjectId( ) { - return this.objectId; - } - - /** - * This method sets the value to the member attribute parentObjectId. - * You cannot set null to the attribute. - * @param parentObjectId Value to set member attribute parentObjectId - */ - public void setParentObjectId( Long parentObjectId ) { - this.parentObjectId = parentObjectId; - } - - /** - * Returns the value for the member attribute parentObjectId - * @return Long - value of member attribute parentObjectId. - */ - public Long getParentObjectId( ) { - return this.parentObjectId; - } - - /** - * This method sets the value to the member attribute parentObjectClassType. - * You cannot set null to the attribute. - * @param parentObjectClassType Value to set member attribute parentObjectClassType - */ - public void setParentObjectClassType( int parentObjectClassType ) { - this.parentObjectClassType = parentObjectClassType; - } - - /** - * Returns the value for the member attribute parentObjectClassType - * @return int - value of member attribute parentObjectClassType. - */ - public int getParentObjectClassType( ) { - return this.parentObjectClassType; - } - - /** - * This method sets the value to the member attribute parentObjectName. - * You cannot set null to the attribute. - * @param parentObjectName Value to set member attribute parentObjectName - */ - public void setParentObjectName( String parentObjectName ) { - this.parentObjectName = parentObjectName; - } - - /** - * Returns the value for the member attribute parentObjectName - * @return String - value of member attribute parentObjectName. - */ - public String getParentObjectName( ) { - return this.parentObjectName; - } - - /** - * This method sets the value to the member attribute objectName. - * You cannot set null to the attribute. - * @param objectName Value to set member attribute objectName - */ - public void setObjectName( String objectName ) { - this.objectName = objectName; - } - - /** - * Returns the value for the member attribute objectName - * @return String - value of member attribute objectName. - */ - public String getObjectName( ) { - return this.objectName; - } - - /** - * This method sets the value to the member attribute attributeName. - * You cannot set null to the attribute. - * @param attributeName Value to set member attribute attributeName - */ - public void setAttributeName( String attributeName ) { - this.attributeName = attributeName; - } - - /** - * Returns the value for the member attribute attributeName - * @return String - value of member attribute attributeName. - */ - public String getAttributeName( ) { - return this.attributeName; - } - - /** - * This method sets the value to the member attribute previousValue. - * You cannot set null to the attribute. - * @param previousValue Value to set member attribute previousValue - */ - public void setPreviousValue( String previousValue ) { - this.previousValue = previousValue; - } - - /** - * Returns the value for the member attribute previousValue - * @return String - value of member attribute previousValue. - */ - public String getPreviousValue( ) { - return this.previousValue; - } - - /** - * This method sets the value to the member attribute newValue. - * You cannot set null to the attribute. - * @param newValue Value to set member attribute newValue - */ - public void setNewValue( String newValue ) { - this.newValue = newValue; - } - - /** - * Returns the value for the member attribute newValue - * @return String - value of member attribute newValue. - */ - public String getNewValue( ) { - return this.newValue; - } - - /** - * This method sets the value to the member attribute transactionId. - * You cannot set null to the attribute. - * @param transactionId Value to set member attribute transactionId - */ - public void setTransactionId( String transactionId ) { - this.transactionId = transactionId; - } - - /** - * Returns the value for the member attribute transactionId - * @return String - value of member attribute transactionId. - */ - public String getTransactionId( ) { - return this.transactionId; - } - - /** - * This method sets the value to the member attribute action. - * You cannot set null to the attribute. - * @param action Value to set member attribute action - */ - public void setAction( String action ) { - this.action = action; - } - - /** - * Returns the value for the member attribute action - * @return String - value of member attribute action. - */ - public String getAction( ) { - return this.action; - } - - /** - * This method sets the value to the member attribute sessionId. - * You cannot set null to the attribute. - * @param sessionId Value to set member attribute sessionId - */ - public void setSessionId( String sessionId ) { - this.sessionId = sessionId; - } - - /** - * Returns the value for the member attribute sessionId - * @return String - value of member attribute sessionId. - */ - public String getSessionId( ) { - return this.sessionId; - } - - /** - * This method sets the value to the member attribute requestId. - * You cannot set null to the attribute. - * @param requestId Value to set member attribute requestId - */ - public void setRequestId( String requestId ) { - this.requestId = requestId; - } - - /** - * Returns the value for the member attribute requestId - * @return String - value of member attribute requestId. - */ - public String getRequestId( ) { - return this.requestId; - } - - /** - * This method sets the value to the member attribute sessionType. - * You cannot set null to the attribute. - * @param sessionType Value to set member attribute sessionType - */ - public void setSessionType( String sessionType ) { - this.sessionType = sessionType; - } - - /** - * Returns the value for the member attribute sessionType - * @return String - value of member attribute sessionType. - */ - 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 += "requestId={" + requestId + "} "; - 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( "objectClassType".equals(fieldName) ) { - return "CommonEnums.ClassTypes"; - } - //Later TODO - //return super.getEnumName(fieldName); - return null; - } - + 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; + + /** + * Name of the class to which the object id belongs to + *
    + *
  • This attribute is of type enum CommonEnums::ClassTypes + *
+ */ + @Column(name = "CLASS_TYPE", nullable = false) + protected int objectClassType = RangerConstants.CLASS_TYPE_NONE; + + /** + * Id of the object to which this notes refers to + *
    + *
+ */ + @Column(name = "OBJECT_ID") + protected Long objectId; + + /** + * Object Id of the parent object + *
    + *
+ */ + @Column(name = "PARENT_OBJECT_ID") + protected Long parentObjectId; + + /** + * Object Class Type of the parent object + *
    + *
+ */ + @Column(name = "PARENT_OBJECT_CLASS_TYPE", nullable = false) + protected int parentObjectClassType; + + /** + * Name of the attribute that was changed + *
    + *
  • The maximum length for this attribute is 1024. + *
+ */ + @Column(name = "PARENT_OBJECT_NAME", length = 1024) + protected String parentObjectName; + + /** + * Name of the attribute that was changed + *
    + *
  • The maximum length for this attribute is 1024. + *
+ */ + @Column(name = "OBJECT_NAME", length = 1024) + protected String objectName; + + /** + * Name of the attribute that was changed + *
    + *
  • The maximum length for this attribute is 255. + *
+ */ + @Column(name = "ATTR_NAME", length = 255) + protected String attributeName; + + /** + * Previous value + *
    + *
  • The maximum length for this attribute is 1024. + *
+ */ + @Column(name = "PREV_VAL", length = 1024) + protected String previousValue; + + /** + * New value + *
    + *
  • The maximum length for this attribute is 1024. + *
+ */ + @Column(name = "NEW_VAL", length = 1024) + protected String newValue; + + /** + * Transaction id + *
    + *
  • The maximum length for this attribute is 1024. + *
+ */ + @Column(name = "TRX_ID", length = 1024) + protected String transactionId; + + /** + * Action of the transaction + *
    + *
  • The maximum length for this attribute is 255. + *
+ */ + @Column(name = "ACTION", length = 255) + protected String action; + + /** + * Session Id + *
    + *
  • The maximum length for this attribute is 512. + *
+ */ + @Column(name = "SESS_ID", length = 512) + protected String sessionId; + + /** + * Request Id + *
    + *
+ */ + @Column(name = "REQ_ID") + protected String requestId; + + /** + * Session Type + *
    + *
+ */ + @Column(name = "SESS_TYPE") + protected String sessionType; + + /** + * Default constructor. This will set all the attributes to default value. + */ + public XXTrxLog() { + objectClassType = RangerConstants.CLASS_TYPE_NONE; + } + + public XXTrxLog(int objectClassType, Long objectId, String objectName, String action, String attributeName, String previousValue, String newValue) { + this.objectClassType = objectClassType; + this.objectId = objectId; + this.objectName = objectName; + this.action = action; + this.attributeName = attributeName; + this.previousValue = previousValue; + this.newValue = newValue; + } + + public static String getEnumName(String fieldName) { + if ("objectClassType".equals(fieldName)) { + return "CommonEnums.ClassTypes"; + } + //Later TODO + //return super.getEnumName(fieldName); + return null; + } + + @Override + public int getMyClassType() { + return AppConstants.CLASS_TYPE_TRX_LOG; + } + + @Override + public Long getId() { + return id; + } + + @Override + public void setId(Long id) { + this.id = id; + } + + @Override + public int hashCode() { + return super.hashCode(); + } + + /** + * Checks for all attributes except referenced db objects + * + * @return true if all attributes match + */ + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } else if (!super.equals(obj)) { + return false; + } + + XXTrxLog other = (XXTrxLog) obj; + + return Objects.equals(objectClassType, other.objectClassType) && + Objects.equals(objectId, other.objectId) && + Objects.equals(parentObjectId, other.parentObjectId) && + Objects.equals(parentObjectClassType, other.parentObjectClassType) && + Objects.equals(parentObjectName, other.parentObjectName) && + Objects.equals(objectName, other.objectName) && + Objects.equals(attributeName, other.attributeName) && + Objects.equals(previousValue, other.previousValue) && + Objects.equals(newValue, other.newValue) && + Objects.equals(transactionId, other.transactionId) && + Objects.equals(action, other.action) && + Objects.equals(sessionId, other.sessionId) && + Objects.equals(requestId, other.requestId) && + Objects.equals(sessionType, other.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 += "requestId={" + requestId + "} "; + str += "}"; + return str; + } + + /** + * Returns the value for the member attribute objectClassType + * + * @return int - value of member attribute objectClassType. + */ + public int getObjectClassType() { + return this.objectClassType; + } + + /** + * This method sets the value to the member attribute objectClassType. + * You cannot set null to the attribute. + * + * @param objectClassType Value to set member attribute objectClassType + */ + public void setObjectClassType(int objectClassType) { + this.objectClassType = objectClassType; + } + + /** + * Returns the value for the member attribute objectId + * + * @return Long - value of member attribute objectId. + */ + public Long getObjectId() { + return this.objectId; + } + + /** + * This method sets the value to the member attribute objectId. + * You cannot set null to the attribute. + * + * @param objectId Value to set member attribute objectId + */ + public void setObjectId(Long objectId) { + this.objectId = objectId; + } + + /** + * Returns the value for the member attribute parentObjectId + * + * @return Long - value of member attribute parentObjectId. + */ + public Long getParentObjectId() { + return this.parentObjectId; + } + + /** + * This method sets the value to the member attribute parentObjectId. + * You cannot set null to the attribute. + * + * @param parentObjectId Value to set member attribute parentObjectId + */ + public void setParentObjectId(Long parentObjectId) { + this.parentObjectId = parentObjectId; + } + + /** + * Returns the value for the member attribute parentObjectClassType + * + * @return int - value of member attribute parentObjectClassType. + */ + public int getParentObjectClassType() { + return this.parentObjectClassType; + } + + /** + * This method sets the value to the member attribute parentObjectClassType. + * You cannot set null to the attribute. + * + * @param parentObjectClassType Value to set member attribute parentObjectClassType + */ + public void setParentObjectClassType(int parentObjectClassType) { + this.parentObjectClassType = parentObjectClassType; + } + + /** + * Returns the value for the member attribute parentObjectName + * + * @return String - value of member attribute parentObjectName. + */ + public String getParentObjectName() { + return this.parentObjectName; + } + + /** + * This method sets the value to the member attribute parentObjectName. + * You cannot set null to the attribute. + * + * @param parentObjectName Value to set member attribute parentObjectName + */ + public void setParentObjectName(String parentObjectName) { + this.parentObjectName = parentObjectName; + } + + /** + * Returns the value for the member attribute objectName + * + * @return String - value of member attribute objectName. + */ + public String getObjectName() { + return this.objectName; + } + + /** + * This method sets the value to the member attribute objectName. + * You cannot set null to the attribute. + * + * @param objectName Value to set member attribute objectName + */ + public void setObjectName(String objectName) { + this.objectName = objectName; + } + + /** + * Returns the value for the member attribute attributeName + * + * @return String - value of member attribute attributeName. + */ + public String getAttributeName() { + return this.attributeName; + } + + /** + * This method sets the value to the member attribute attributeName. + * You cannot set null to the attribute. + * + * @param attributeName Value to set member attribute attributeName + */ + public void setAttributeName(String attributeName) { + this.attributeName = attributeName; + } + + /** + * Returns the value for the member attribute previousValue + * + * @return String - value of member attribute previousValue. + */ + public String getPreviousValue() { + return this.previousValue; + } + + /** + * This method sets the value to the member attribute previousValue. + * You cannot set null to the attribute. + * + * @param previousValue Value to set member attribute previousValue + */ + public void setPreviousValue(String previousValue) { + this.previousValue = previousValue; + } + + /** + * Returns the value for the member attribute newValue + * + * @return String - value of member attribute newValue. + */ + public String getNewValue() { + return this.newValue; + } + + /** + * This method sets the value to the member attribute newValue. + * You cannot set null to the attribute. + * + * @param newValue Value to set member attribute newValue + */ + public void setNewValue(String newValue) { + this.newValue = newValue; + } + + /** + * Returns the value for the member attribute transactionId + * + * @return String - value of member attribute transactionId. + */ + public String getTransactionId() { + return this.transactionId; + } + + /** + * This method sets the value to the member attribute transactionId. + * You cannot set null to the attribute. + * + * @param transactionId Value to set member attribute transactionId + */ + public void setTransactionId(String transactionId) { + this.transactionId = transactionId; + } + + /** + * Returns the value for the member attribute action + * + * @return String - value of member attribute action. + */ + public String getAction() { + return this.action; + } + + /** + * This method sets the value to the member attribute action. + * You cannot set null to the attribute. + * + * @param action Value to set member attribute action + */ + public void setAction(String action) { + this.action = action; + } + + /** + * Returns the value for the member attribute sessionId + * + * @return String - value of member attribute sessionId. + */ + public String getSessionId() { + return this.sessionId; + } + + /** + * This method sets the value to the member attribute sessionId. + * You cannot set null to the attribute. + * + * @param sessionId Value to set member attribute sessionId + */ + public void setSessionId(String sessionId) { + this.sessionId = sessionId; + } + + /** + * Returns the value for the member attribute requestId + * + * @return String - value of member attribute requestId. + */ + public String getRequestId() { + return this.requestId; + } + + /** + * This method sets the value to the member attribute requestId. + * You cannot set null to the attribute. + * + * @param requestId Value to set member attribute requestId + */ + public void setRequestId(String requestId) { + this.requestId = requestId; + } + + /** + * Returns the value for the member attribute sessionType + * + * @return String - value of member attribute sessionType. + */ + public String getSessionType() { + return this.sessionType; + } + + /** + * This method sets the value to the member attribute sessionType. + * You cannot set null to the attribute. + * + * @param sessionType Value to set member attribute sessionType + */ + public void setSessionType(String sessionType) { + this.sessionType = sessionType; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/entity/XXTrxLogV2.java b/security-admin/src/main/java/org/apache/ranger/entity/XXTrxLogV2.java index cfc8637d85..3fb9677c81 100644 --- a/security-admin/src/main/java/org/apache/ranger/entity/XXTrxLogV2.java +++ b/security-admin/src/main/java/org/apache/ranger/entity/XXTrxLogV2.java @@ -17,78 +17,85 @@ * under the License. */ - package org.apache.ranger.entity; +package org.apache.ranger.entity; /** * Logging table for all DB create and update queries - * */ import org.apache.ranger.common.DateUtil; import org.apache.ranger.common.RangerConstants; -import javax.persistence.*; -import java.util.Date; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.SequenceGenerator; +import javax.persistence.Table; +import javax.persistence.Temporal; +import javax.persistence.TemporalType; +import java.util.Date; @Entity -@Table(name="x_trx_log_v2") +@Table(name = "x_trx_log_v2") public class XXTrxLogV2 implements java.io.Serializable { private static final long serialVersionUID = 1L; @Id - @SequenceGenerator(name="X_TRX_LOG_V2_SEQ", sequenceName="X_TRX_LOG_V2_SEQ", allocationSize=1) - @GeneratedValue(strategy=GenerationType.AUTO, generator="X_TRX_LOG_V2_SEQ") - @Column(name="ID") + @SequenceGenerator(name = "X_TRX_LOG_V2_SEQ", sequenceName = "X_TRX_LOG_V2_SEQ", allocationSize = 1) + @GeneratedValue(strategy = GenerationType.AUTO, generator = "X_TRX_LOG_V2_SEQ") + @Column(name = "ID") protected Long id; @Temporal(TemporalType.TIMESTAMP) - @Column(name="CREATE_TIME") + @Column(name = "CREATE_TIME") protected Date createTime = DateUtil.getUTCDate(); - @Column(name="ADDED_BY_ID") + @Column(name = "ADDED_BY_ID") protected Long addedByUserId; - @Column(name="CLASS_TYPE", nullable=false ) - protected int objectClassType = RangerConstants.CLASS_TYPE_NONE; + @Column(name = "CLASS_TYPE", nullable = false) + protected int objectClassType = RangerConstants.CLASS_TYPE_NONE; - @Column(name="OBJECT_ID") + @Column(name = "OBJECT_ID") protected Long objectId; - @Column(name="OBJECT_NAME") + @Column(name = "OBJECT_NAME") protected String objectName; - @Column(name="PARENT_OBJECT_CLASS_TYPE", nullable=false ) + @Column(name = "PARENT_OBJECT_CLASS_TYPE", nullable = false) protected int parentObjectClassType; - @Column(name="PARENT_OBJECT_ID") + @Column(name = "PARENT_OBJECT_ID") protected Long parentObjectId; - @Column(name="PARENT_OBJECT_NAME", length=1024) + @Column(name = "PARENT_OBJECT_NAME", length = 1024) protected String parentObjectName; - @Column(name="ACTION", length=255) + @Column(name = "ACTION", length = 255) protected String action; - @Column(name="CHANGE_INFO") + @Column(name = "CHANGE_INFO") protected String changeInfo; - @Column(name="TRX_ID", length=1024) + @Column(name = "TRX_ID", length = 1024) protected String transactionId; - @Column(name="REQ_ID") + @Column(name = "REQ_ID") protected String requestId; - @Column(name="SESS_ID", length=512) + @Column(name = "SESS_ID", length = 512) protected String sessionId; - @Column(name="SESS_TYPE") + @Column(name = "SESS_TYPE") protected String sessionType; /** * Default constructor. This will set all the attributes to default value. */ - public XXTrxLogV2( ) { + public XXTrxLogV2() { } public XXTrxLogV2(int objectClassType, Long objectId, String objectName, String action) { @@ -119,128 +126,128 @@ public XXTrxLogV2(int objectClassType, Long objectId, String objectName, int par this.changeInfo = changeInfo; } - public void setId(Long id) { - this.id=id; - } - public Long getId() { return id; } - public void setCreateTime( Date createTime ) { - this.createTime = createTime; + public void setId(Long id) { + this.id = id; } - public Date getCreateTime( ) { + public Date getCreateTime() { return this.createTime; } - public void setAddedByUserId( Long addedByUserId ) { - this.addedByUserId = addedByUserId; + public void setCreateTime(Date createTime) { + this.createTime = createTime; } - public Long getAddedByUserId( ) { + public Long getAddedByUserId() { return this.addedByUserId; } - public void setObjectClassType( int objectClassType ) { - this.objectClassType = objectClassType; + public void setAddedByUserId(Long addedByUserId) { + this.addedByUserId = addedByUserId; } - public int getObjectClassType( ) { + public int getObjectClassType() { return this.objectClassType; } - public void setObjectId( Long objectId ) { - this.objectId = objectId; + public void setObjectClassType(int objectClassType) { + this.objectClassType = objectClassType; } - public Long getObjectId( ) { + public Long getObjectId() { return this.objectId; } - public void setObjectName( String objectName ) { - this.objectName = objectName; + public void setObjectId(Long objectId) { + this.objectId = objectId; } - public String getObjectName( ) { + public String getObjectName() { return this.objectName; } - public void setParentObjectClassType( int parentObjectClassType ) { - this.parentObjectClassType = parentObjectClassType; + public void setObjectName(String objectName) { + this.objectName = objectName; } - public int getParentObjectClassType( ) { + public int getParentObjectClassType() { return this.parentObjectClassType; } - public void setParentObjectId( Long parentObjectId ) { - this.parentObjectId = parentObjectId; + public void setParentObjectClassType(int parentObjectClassType) { + this.parentObjectClassType = parentObjectClassType; } - public Long getParentObjectId( ) { + public Long getParentObjectId() { return this.parentObjectId; } - public void setParentObjectName( String parentObjectName ) { - this.parentObjectName = parentObjectName; + public void setParentObjectId(Long parentObjectId) { + this.parentObjectId = parentObjectId; } - public String getParentObjectName( ) { + public String getParentObjectName() { return this.parentObjectName; } - public void setAction( String action ) { - this.action = action; + public void setParentObjectName(String parentObjectName) { + this.parentObjectName = parentObjectName; } - public String getAction( ) { + public String getAction() { return this.action; } - public void setChangeInfo( String changeInfo ) { - this.changeInfo = changeInfo; + public void setAction(String action) { + this.action = action; } - public String getChangeInfo( ) { + public String getChangeInfo() { return this.changeInfo; } - public void setTransactionId( String transactionId ) { - this.transactionId = transactionId; + public void setChangeInfo(String changeInfo) { + this.changeInfo = changeInfo; } - public String getTransactionId( ) { + public String getTransactionId() { return this.transactionId; } - public void setRequestId( String requestId ) { - this.requestId = requestId; + public void setTransactionId(String transactionId) { + this.transactionId = transactionId; } - public String getRequestId( ) { + public String getRequestId() { return this.requestId; } - public void setSessionId( String sessionId ) { - this.sessionId = sessionId; + public void setRequestId(String requestId) { + this.requestId = requestId; } - public String getSessionId( ) { + public String getSessionId() { return this.sessionId; } - public void setSessionType( String sessionType ) { - this.sessionType = sessionType; + public void setSessionId(String sessionId) { + this.sessionId = sessionId; } - public String getSessionType( ) { + public String getSessionType() { return this.sessionType; } + public void setSessionType(String sessionType) { + this.sessionType = sessionType; + } + @Override - public String toString( ) { + public String toString() { String str = "XXTrxLogV2={"; str += super.toString(); str += "objectClassType={" + objectClassType + "} "; diff --git a/security-admin/src/main/java/org/apache/ranger/entity/XXUgsyncAuditInfo.java b/security-admin/src/main/java/org/apache/ranger/entity/XXUgsyncAuditInfo.java index 9449afee9c..5bbe64397c 100644 --- a/security-admin/src/main/java/org/apache/ranger/entity/XXUgsyncAuditInfo.java +++ b/security-admin/src/main/java/org/apache/ranger/entity/XXUgsyncAuditInfo.java @@ -6,9 +6,9 @@ * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY @@ -21,219 +21,217 @@ import org.apache.ranger.common.AppConstants; -import javax.persistence.*; +import javax.persistence.Cacheable; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.SequenceGenerator; +import javax.persistence.Table; +import javax.persistence.Temporal; +import javax.persistence.TemporalType; + import java.util.Date; +import java.util.Objects; @Entity @Cacheable @Table(name = "x_ugsync_audit_info") public class XXUgsyncAuditInfo extends XXDBBase implements java.io.Serializable { - private static final long serialVersionUID = 1L; - - @Id - @SequenceGenerator(name = "X_UGSYNC_AUDIT_INFO_SEQ", sequenceName = "X_UGSYNC_AUDIT_INFO_SEQ", allocationSize = 1) - @GeneratedValue(strategy = GenerationType.AUTO, generator = "X_UGSYNC_AUDIT_INFO_SEQ") - @Column(name = "id") - protected Long id; - - @Temporal(TemporalType.TIMESTAMP) - @Column(name="event_time" ) - protected Date eventTime; - - @Column(name = "user_name") - protected String userName; - - @Column(name = "sync_source") - protected String syncSource; - - @Column(name = "no_of_new_users") - protected Long noOfNewUsers; - - @Column(name = "no_of_new_groups") - protected Long noOfNewGroups; - - @Column(name = "no_of_modified_users") - protected Long noOfModifiedUsers; - - @Column(name = "no_of_modified_groups") - protected Long noOfModifiedGroups; - - @Column(name = "sync_source_info") - protected String syncSourceInfo; - - @Column(name="session_id") - protected String sessionId; - - /** - * Default constructor. This will set all the attributes to default value. - */ - public XXUgsyncAuditInfo() { - } - - public int getMyClassType( ) { - return AppConstants.CLASS_TYPE_UGYNC_AUDIT_INFO; - } - - public String getMyDisplayValue() { - return null; - } - - public void setId(Long id) { - this.id = id; - } - - public Long getId() { - return this.id; - } - - public Date getEventTime() { - return eventTime; - } - - public void setEventTime(Date eventTime) { - this.eventTime = eventTime; - } - - public String getUserName() { - return userName; - } - - public void setUserName(String userName) { - this.userName = userName; - } - - public String getSyncSource() { - return syncSource; - } - - public void setSyncSource(String syncSource) { - this.syncSource = syncSource; - } - - - public Long getNoOfNewUsers() { - return noOfNewUsers; - } - - public void setNoOfNewUsers(Long noOfUsers) { - this.noOfNewUsers = noOfUsers; - } - - public Long getNoOfModifiedUsers() { - return noOfModifiedUsers; - } - - public void setNoOfModifiedUsers(Long noOfModifiedUsers) { - this.noOfModifiedUsers = noOfModifiedUsers; - } - - public Long getNoOfNewGroups() { - return noOfNewGroups; - } - - public void setNoOfNewGroups(Long noOfNewGroups) { - this.noOfNewGroups = noOfNewGroups; - } - - public Long getNoOfModifiedGroups() { - return noOfModifiedGroups; - } - - public void setNoOfModifiedGroups(Long noOfModifiedGroups) { - this.noOfModifiedGroups = noOfModifiedGroups; - } - - public String getSyncSourceInfo() { - return syncSourceInfo; - } - - public void setSyncSourceInfo(String syncSourceInfo) { - this.syncSourceInfo = syncSourceInfo; - } - - public String getSessionId() { - return sessionId; - } - - public void setSessionId(String sessionId) { - this.sessionId = sessionId; - } - - /** - * This return the bean content in string format - * @return formatedStr - */ - @Override - public String toString( ) { - String str = "XXUgsyncAuditInfo={"; - str += "id={" + id + "} "; - str += "eventTime={" + eventTime + "} "; - str += "userName={" + userName + "} "; - str += "syncSource={" + syncSource + "} "; - str += "noOfNewUsers={" + noOfNewUsers + "} "; - str += "noOfNewGroups={" + noOfNewGroups + "} "; - str += "noOfModifiedUsers={" + noOfModifiedUsers + "} "; - str += "noOfModifiedGroups={" + noOfModifiedGroups + "} "; - str += "syncSourceInfo={" + syncSourceInfo + "} "; - str += "sessionId={" + sessionId + "} "; - str += "}"; - return str; - } - - /** - * Checks for all attributes except referenced db objects - * @return true if all attributes match - */ - @Override - public boolean equals( Object obj) { - if (obj == null) - return false; - if (this == obj) - return true; - if (getClass() != obj.getClass()) - return false; - XXUgsyncAuditInfo other = (XXUgsyncAuditInfo) obj; - if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) { - return false; - } - if ((this.eventTime == null && other.eventTime != null) || (this.eventTime != null && !this.eventTime.equals(other.eventTime))) { - return false; - } - if ((this.userName == null && other.userName != null) || (this.userName != null && !this.userName.equals(other.userName))) { - return false; - } - if ((this.syncSource == null && other.syncSource != null) || (this.syncSource != null && !this.syncSource.equals(other.syncSource))) { - return false; - } - if ((this.noOfNewUsers == null && other.noOfNewUsers != null) || (this.noOfNewUsers != null && !this.noOfNewUsers.equals(other.noOfNewUsers))) { - return false; - } - if ((this.noOfNewGroups == null && other.noOfNewGroups != null) || (this.noOfNewGroups != null && !this.noOfNewGroups.equals(other.noOfNewGroups))) { - return false; - } - if ((this.noOfModifiedUsers == null && other.noOfModifiedUsers != null) || (this.noOfModifiedUsers != null && !this.noOfModifiedUsers.equals(other.noOfModifiedUsers))) { - return false; - } - if ((this.noOfModifiedGroups == null && other.noOfModifiedGroups != null) || (this.noOfModifiedGroups != null && !this.noOfModifiedGroups.equals(other.noOfModifiedGroups))) { - return false; - } - if ((this.syncSourceInfo == null && other.syncSourceInfo != null) || (this.syncSourceInfo != null && !this.syncSourceInfo.equals(other.syncSourceInfo))) { - return false; - } - if ((this.sessionId == null && other.sessionId != null) || (this.sessionId != null && !this.sessionId.equals(other.sessionId))) { - return false; - } - return true; - } - - public static boolean equals(Object object1, Object object2) { - if (object1 == object2) { - return true; - } - if ((object1 == null) || (object2 == null)) { - return false; - } - return object1.equals(object2); - } - + private static final long serialVersionUID = 1L; + + @Id + @SequenceGenerator(name = "X_UGSYNC_AUDIT_INFO_SEQ", sequenceName = "X_UGSYNC_AUDIT_INFO_SEQ", allocationSize = 1) + @GeneratedValue(strategy = GenerationType.AUTO, generator = "X_UGSYNC_AUDIT_INFO_SEQ") + @Column(name = "id") + protected Long id; + + @Temporal(TemporalType.TIMESTAMP) + @Column(name = "event_time") + protected Date eventTime; + + @Column(name = "user_name") + protected String userName; + + @Column(name = "sync_source") + protected String syncSource; + + @Column(name = "no_of_new_users") + protected Long noOfNewUsers; + + @Column(name = "no_of_new_groups") + protected Long noOfNewGroups; + + @Column(name = "no_of_modified_users") + protected Long noOfModifiedUsers; + + @Column(name = "no_of_modified_groups") + protected Long noOfModifiedGroups; + + @Column(name = "sync_source_info") + protected String syncSourceInfo; + + @Column(name = "session_id") + protected String sessionId; + + /** + * Default constructor. This will set all the attributes to default value. + */ + public XXUgsyncAuditInfo() { + } + + public static boolean equals(Object object1, Object object2) { + if (object1 == object2) { + return true; + } + + if ((object1 == null) || (object2 == null)) { + return false; + } + + return object1.equals(object2); + } + + public int getMyClassType() { + return AppConstants.CLASS_TYPE_UGYNC_AUDIT_INFO; + } + + public String getMyDisplayValue() { + return null; + } + + public Long getId() { + return this.id; + } + + public void setId(Long id) { + this.id = id; + } + + @Override + public int hashCode() { + return super.hashCode(); + } + + /** + * Checks for all attributes except referenced db objects + * + * @return true if all attributes match + */ + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } else if (!super.equals(obj)) { + return false; + } + + XXUgsyncAuditInfo other = (XXUgsyncAuditInfo) obj; + + return Objects.equals(id, other.id) && + Objects.equals(eventTime, other.eventTime) && + Objects.equals(userName, other.userName) && + Objects.equals(syncSource, other.syncSource) && + Objects.equals(noOfNewUsers, other.noOfNewUsers) && + Objects.equals(noOfNewGroups, other.noOfNewGroups) && + Objects.equals(noOfModifiedUsers, other.noOfModifiedUsers) && + Objects.equals(noOfModifiedGroups, other.noOfModifiedGroups) && + Objects.equals(syncSourceInfo, other.syncSourceInfo) && + Objects.equals(sessionId, other.sessionId); + } + + /** + * This return the bean content in string format + * + * @return formatedStr + */ + @Override + public String toString() { + String str = "XXUgsyncAuditInfo={"; + str += "id={" + id + "} "; + str += "eventTime={" + eventTime + "} "; + str += "userName={" + userName + "} "; + str += "syncSource={" + syncSource + "} "; + str += "noOfNewUsers={" + noOfNewUsers + "} "; + str += "noOfNewGroups={" + noOfNewGroups + "} "; + str += "noOfModifiedUsers={" + noOfModifiedUsers + "} "; + str += "noOfModifiedGroups={" + noOfModifiedGroups + "} "; + str += "syncSourceInfo={" + syncSourceInfo + "} "; + str += "sessionId={" + sessionId + "} "; + str += "}"; + return str; + } + + public Date getEventTime() { + return eventTime; + } + + public void setEventTime(Date eventTime) { + this.eventTime = eventTime; + } + + public String getUserName() { + return userName; + } + + public void setUserName(String userName) { + this.userName = userName; + } + + public String getSyncSource() { + return syncSource; + } + + public void setSyncSource(String syncSource) { + this.syncSource = syncSource; + } + + public Long getNoOfNewUsers() { + return noOfNewUsers; + } + + public void setNoOfNewUsers(Long noOfUsers) { + this.noOfNewUsers = noOfUsers; + } + + public Long getNoOfModifiedUsers() { + return noOfModifiedUsers; + } + + public void setNoOfModifiedUsers(Long noOfModifiedUsers) { + this.noOfModifiedUsers = noOfModifiedUsers; + } + + public Long getNoOfNewGroups() { + return noOfNewGroups; + } + + public void setNoOfNewGroups(Long noOfNewGroups) { + this.noOfNewGroups = noOfNewGroups; + } + + public Long getNoOfModifiedGroups() { + return noOfModifiedGroups; + } + + public void setNoOfModifiedGroups(Long noOfModifiedGroups) { + this.noOfModifiedGroups = noOfModifiedGroups; + } + + public String getSyncSourceInfo() { + return syncSourceInfo; + } + + public void setSyncSourceInfo(String syncSourceInfo) { + this.syncSourceInfo = syncSourceInfo; + } + + public String getSessionId() { + return sessionId; + } + + public void setSessionId(String sessionId) { + this.sessionId = sessionId; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/entity/XXUser.java b/security-admin/src/main/java/org/apache/ranger/entity/XXUser.java index 885973496c..488ecad92c 100644 --- a/security-admin/src/main/java/org/apache/ranger/entity/XXUser.java +++ b/security-admin/src/main/java/org/apache/ranger/entity/XXUser.java @@ -17,13 +17,16 @@ * under the License. */ - package org.apache.ranger.entity; +package org.apache.ranger.entity; /** * User - * */ +import org.apache.ranger.common.AppConstants; +import org.apache.ranger.common.RangerCommonEnums; +import org.apache.ranger.common.RangerConstants; + import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; @@ -32,280 +35,283 @@ import javax.persistence.SequenceGenerator; import javax.persistence.Table; -import org.apache.ranger.common.AppConstants; -import org.apache.ranger.common.RangerCommonEnums; -import org.apache.ranger.common.RangerConstants; - +import java.util.Objects; @Entity -@Table(name="x_user") +@Table(name = "x_user") 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 - *
    - *
  • The maximum length for this attribute is 1024. - *
- * - */ - @Column(name="USER_NAME" , nullable=false , length=1024) - protected String name; - - /** - * Description - *
    - *
  • The maximum length for this attribute is 4000. - *
- * - */ - @Column(name="DESCR" , nullable=false , length=4000) - protected String description; - - /** - * Status - *
    - *
  • This attribute is of type enum CommonEnums::ActiveStatus - *
- * - */ - @Column(name="STATUS" , nullable=false ) - protected int status = RangerConstants.STATUS_DISABLED; - - /** - * Status - *
    - *
  • This attribute is of type enum CommonEnums::ActiveStatus - *
- * - */ - @Column(name="IS_VISIBLE" , nullable=false ) - protected Integer isVisible; - /** - * Id of the credential store - *
    - *
- * - */ - @Column(name="CRED_STORE_ID" ) - protected Long credStoreId; - - /** - * Additional store attributes. - *
    - *
- * - */ - @Column(name="OTHER_ATTRIBUTES") - protected String otherAttributes; - - /** - * Sync Source attribute. - *
    - *
- * - */ - @Column(name="SYNC_SOURCE") - protected String syncSource; - - /** - * Default constructor. This will set all the attributes to default value. - */ - public XXUser ( ) { - status = RangerConstants.STATUS_DISABLED; - isVisible = RangerCommonEnums.IS_VISIBLE; - } - - @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 name. - * You cannot set null to the attribute. - * @param name Value to set member attribute name - */ - public void setName( String name ) { - this.name = name; - } - - /** - * Returns the value for the member attribute name - * @return String - value of member attribute name. - */ - public String getName( ) { - return this.name; - } - - /** - * This method sets the value to the member attribute description. - * You cannot set null to the attribute. - * @param description Value to set member attribute description - */ - public void setDescription( String description ) { - this.description = description; - } - - /** - * Returns the value for the member attribute description - * @return String - value of member attribute description. - */ - public String getDescription( ) { - return this.description; - } - - /** - * This method sets the value to the member attribute status. - * You cannot set null to the attribute. - * @param status Value to set member attribute status - */ - public void setStatus( int status ) { - this.status = status; - } - - /** - * Returns the value for the member attribute status - * @return int - value of member attribute status. - */ - public int getStatus( ) { - return this.status; - } - - /** - * This method sets the value to the member attribute isVisible. - * You cannot set null to the attribute. - * @param status Value to set member attribute isVisible - */ - public void setIsVisible(Integer isVisible) { - this.isVisible = isVisible; - } - - /** - * Returns the value for the member attribute isVisible - * @return int - value of member attribute isVisible. - */ - public Integer getIsVisible() { - return isVisible; - } - - /** - * This method sets the value to the member attribute credStoreId. - * You cannot set null to the attribute. - * @param credStoreId Value to set member attribute credStoreId - */ - public void setCredStoreId( Long credStoreId ) { - this.credStoreId = credStoreId; - } - - /** - * Returns the value for the member attribute credStoreId - * @return Long - value of member attribute credStoreId. - */ - public Long getCredStoreId( ) { - return this.credStoreId; - } - - - /** - * This method sets JSON {@link String} representation of additional store attributes. - * This method accepts null values. - * @param otherAttributes - */ - public void setOtherAttributes(String otherAttributes) { - this.otherAttributes = otherAttributes; - } - - /** - * @return JSON {@link String} representation of additional store attributes if available, - * null otherwise. - */ - public String getOtherAttributes() { - return otherAttributes; - } - - /** - * This method sets JSON {@link String} representation of sync source attribute. - * This method accepts null values. - * @param syncSource - */ - public void setSyncSource(String syncSource) { - this.syncSource = syncSource; - } - - /** - * @return JSON {@link String} representation of sync source attribute if available, - * null otherwise. - */ - public String getSyncSource() { return syncSource; } - - /** - * 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 += "isvisible={" + isVisible + "} "; - str += "credStoreId={" + credStoreId + "} "; - str += "otherAttributes={" + otherAttributes + "} "; - str += "syncSource={" + syncSource + "} "; - 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( "status".equals(fieldName) ) { - return "CommonEnums.ActiveStatus"; - } - //Later TODO - //return super.getEnumName(fieldName); - return null; - } - + 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; + /** + * Name + *
    + *
  • The maximum length for this attribute is 1024. + *
+ */ + @Column(name = "USER_NAME", nullable = false, length = 1024) + protected String name; + /** + * Description + *
    + *
  • The maximum length for this attribute is 4000. + *
+ */ + @Column(name = "DESCR", nullable = false, length = 4000) + protected String description; + /** + * Status + *
    + *
  • This attribute is of type enum CommonEnums::ActiveStatus + *
+ */ + @Column(name = "STATUS", nullable = false) + protected int status = RangerConstants.STATUS_DISABLED; + /** + * Status + *
    + *
  • This attribute is of type enum CommonEnums::ActiveStatus + *
+ */ + @Column(name = "IS_VISIBLE", nullable = false) + protected Integer isVisible; + /** + * Id of the credential store + *
    + *
+ */ + @Column(name = "CRED_STORE_ID") + protected Long credStoreId; + /** + * Additional store attributes. + *
    + *
+ */ + @Column(name = "OTHER_ATTRIBUTES") + protected String otherAttributes; + /** + * Sync Source attribute. + *
    + *
+ */ + @Column(name = "SYNC_SOURCE") + protected String syncSource; + + /** + * Default constructor. This will set all the attributes to default value. + */ + public XXUser() { + status = RangerConstants.STATUS_DISABLED; + isVisible = RangerCommonEnums.IS_VISIBLE; + } + + public static String getEnumName(String fieldName) { + if ("status".equals(fieldName)) { + return "CommonEnums.ActiveStatus"; + } + //Later TODO + //return super.getEnumName(fieldName); + return null; + } + + @Override + public int getMyClassType() { + return AppConstants.CLASS_TYPE_XA_USER; + } + + @Override + public String getMyDisplayValue() { + return getDescription(); + } + + @Override + public Long getId() { + return id; + } + + @Override + public void setId(Long id) { + this.id = id; + } + + @Override + public int hashCode() { + return super.hashCode(); + } + + /** + * Checks for all attributes except referenced db objects + * + * @return true if all attributes match + */ + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } else if (!super.equals(obj)) { + return false; + } + + XXUser other = (XXUser) obj; + + return Objects.equals(name, other.name) && + Objects.equals(description, other.description) && + Objects.equals(status, other.status) && + Objects.equals(credStoreId, other.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 += "isvisible={" + isVisible + "} "; + str += "credStoreId={" + credStoreId + "} "; + str += "otherAttributes={" + otherAttributes + "} "; + str += "syncSource={" + syncSource + "} "; + str += "}"; + return str; + } + + /** + * Returns the value for the member attribute name + * + * @return String - value of member attribute name. + */ + public String getName() { + return this.name; + } + + /** + * This method sets the value to the member attribute name. + * You cannot set null to the attribute. + * + * @param name Value to set member attribute name + */ + public void setName(String name) { + this.name = name; + } + + /** + * Returns the value for the member attribute description + * + * @return String - value of member attribute description. + */ + public String getDescription() { + return this.description; + } + + /** + * This method sets the value to the member attribute description. + * You cannot set null to the attribute. + * + * @param description Value to set member attribute description + */ + public void setDescription(String description) { + this.description = description; + } + + /** + * Returns the value for the member attribute status + * + * @return int - value of member attribute status. + */ + public int getStatus() { + return this.status; + } + + /** + * This method sets the value to the member attribute status. + * You cannot set null to the attribute. + * + * @param status Value to set member attribute status + */ + public void setStatus(int status) { + this.status = status; + } + + /** + * Returns the value for the member attribute isVisible + * + * @return int - value of member attribute isVisible. + */ + public Integer getIsVisible() { + return isVisible; + } + + /** + * This method sets the value to the member attribute isVisible. + * You cannot set null to the attribute. + * + * @param isVisible Value to set member attribute isVisible + */ + public void setIsVisible(Integer isVisible) { + this.isVisible = isVisible; + } + + /** + * Returns the value for the member attribute credStoreId + * + * @return Long - value of member attribute credStoreId. + */ + public Long getCredStoreId() { + return this.credStoreId; + } + + /** + * This method sets the value to the member attribute credStoreId. + * You cannot set null to the attribute. + * + * @param credStoreId Value to set member attribute credStoreId + */ + public void setCredStoreId(Long credStoreId) { + this.credStoreId = credStoreId; + } + + /** + * @return JSON {@link String} representation of additional store attributes if available, + * null otherwise. + */ + public String getOtherAttributes() { + return otherAttributes; + } + + /** + * This method sets JSON {@link String} representation of additional store attributes. + * This method accepts null values. + * + * @param otherAttributes + */ + public void setOtherAttributes(String otherAttributes) { + this.otherAttributes = otherAttributes; + } + + /** + * @return JSON {@link String} representation of sync source attribute if available, + * null otherwise. + */ + public String getSyncSource() { + return syncSource; + } + + /** + * This method sets JSON {@link String} representation of sync source attribute. + * This method accepts null values. + * + * @param syncSource + */ + public void setSyncSource(String syncSource) { + this.syncSource = syncSource; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/entity/XXUserPermission.java b/security-admin/src/main/java/org/apache/ranger/entity/XXUserPermission.java index ab1a3c0fee..bdf03212a0 100644 --- a/security-admin/src/main/java/org/apache/ranger/entity/XXUserPermission.java +++ b/security-admin/src/main/java/org/apache/ranger/entity/XXUserPermission.java @@ -17,6 +17,9 @@ package org.apache.ranger.entity; +import org.apache.ranger.common.AppConstants; +import org.apache.ranger.common.RangerCommonEnums; + import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; @@ -24,142 +27,125 @@ import javax.persistence.Id; import javax.persistence.SequenceGenerator; import javax.persistence.Table; -import org.apache.ranger.common.AppConstants; -import org.apache.ranger.common.RangerCommonEnums; + +import java.util.Objects; @Entity @Table(name = "x_user_module_perm") public class XXUserPermission extends XXDBBase implements java.io.Serializable { - - private static final long serialVersionUID = 1L; - - @Id - @SequenceGenerator(name = "X_USER_MODULE_PERM_SEQ", sequenceName = "X_USER_MODULE_PERM_SEQ", allocationSize = 1) - @GeneratedValue(strategy = GenerationType.AUTO, generator = "X_USER_MODULE_PERM_SEQ") - @Column(name = "ID") - protected Long id; - - @Column(name = "USER_ID", nullable = false) - protected Long userId; - - @Column(name = "MODULE_ID", nullable = false) - protected Long moduleId; - - @Column(name = "IS_ALLOWED", nullable = false) - protected Integer isAllowed; - - public XXUserPermission(){ - isAllowed = RangerCommonEnums.IS_ALLOWED; - } - - /** - * @return the id - */ - public Long getId() { - return id; - } - - /** - * @param id - * the id to set - */ - public void setId(Long id) { - this.id = id; - } - - /** - * @return the userId - */ - public Long getUserId() { - return userId; - } - - /** - * @param userId - * the userId to set - */ - public void setUserId(Long userId) { - this.userId = userId; - } - - /** - * @return the moduleId - */ - public Long getModuleId() { - return moduleId; - } - - /** - * @param moduleId - * the moduleId to set - */ - public void setModuleId(Long moduleId) { - this.moduleId = moduleId; - } - - /** - * @return the isAllowed - */ - public Integer getIsAllowed() { - return isAllowed; - } - - /** - * @param isAllowed - * the isAllowed to set - */ - public void setIsAllowed(Integer isAllowed) { - this.isAllowed = isAllowed; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (!super.equals(obj)) - return false; - if (getClass() != obj.getClass()) - return false; - XXUserPermission other = (XXUserPermission) obj; - if (id == null) { - if (other.id != null) - return false; - } else if (!id.equals(other.id)) - return false; - if (isAllowed == null) { - if (other.isAllowed != null) - return false; - } else if (!isAllowed.equals(other.isAllowed)) - return false; - if (moduleId == null) { - if (other.moduleId != null) - return false; - } else if (!moduleId.equals(other.moduleId)) - return false; - if (userId == null) { - if (other.userId != null) - return false; - } else if (!userId.equals(other.userId)) - return false; - return true; - } - - @Override - public int getMyClassType() { - return AppConstants.CLASS_TYPE_RANGER_USER_PERMISSION; - } - - @Override - public String toString() { - - String str = "VXUserPermission={"; - str += super.toString(); - str += "id={" + id + "} "; - str += "userId={" + userId + "} "; - str += "moduleId={" + moduleId + "} "; - str += "isAllowed={" + isAllowed + "} "; - str += "}"; - - return str; - } + private static final long serialVersionUID = 1L; + + @Id + @SequenceGenerator(name = "X_USER_MODULE_PERM_SEQ", sequenceName = "X_USER_MODULE_PERM_SEQ", allocationSize = 1) + @GeneratedValue(strategy = GenerationType.AUTO, generator = "X_USER_MODULE_PERM_SEQ") + @Column(name = "ID") + protected Long id; + + @Column(name = "USER_ID", nullable = false) + protected Long userId; + + @Column(name = "MODULE_ID", nullable = false) + protected Long moduleId; + + @Column(name = "IS_ALLOWED", nullable = false) + protected Integer isAllowed; + + public XXUserPermission() { + isAllowed = RangerCommonEnums.IS_ALLOWED; + } + + /** + * @return the userId + */ + public Long getUserId() { + return userId; + } + + /** + * @param userId the userId to set + */ + public void setUserId(Long userId) { + this.userId = userId; + } + + /** + * @return the moduleId + */ + public Long getModuleId() { + return moduleId; + } + + /** + * @param moduleId the moduleId to set + */ + public void setModuleId(Long moduleId) { + this.moduleId = moduleId; + } + + /** + * @return the isAllowed + */ + public Integer getIsAllowed() { + return isAllowed; + } + + /** + * @param isAllowed the isAllowed to set + */ + public void setIsAllowed(Integer isAllowed) { + this.isAllowed = isAllowed; + } + + @Override + public int getMyClassType() { + return AppConstants.CLASS_TYPE_RANGER_USER_PERMISSION; + } + + /** + * @return the id + */ + public Long getId() { + return id; + } + + /** + * @param id the id to set + */ + public void setId(Long id) { + this.id = id; + } + + @Override + public int hashCode() { + return super.hashCode(); + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } else if (!super.equals(obj)) { + return false; + } + + XXUserPermission other = (XXUserPermission) obj; + + return Objects.equals(id, other.id) && + Objects.equals(isAllowed, other.isAllowed) && + Objects.equals(moduleId, other.moduleId) && + Objects.equals(userId, other.userId); + } + + @Override + public String toString() { + String str = "VXUserPermission={"; + str += super.toString(); + str += "id={" + id + "} "; + str += "userId={" + userId + "} "; + str += "moduleId={" + moduleId + "} "; + str += "isAllowed={" + isAllowed + "} "; + str += "}"; + + return str; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/entity/view/VXXPrincipal.java b/security-admin/src/main/java/org/apache/ranger/entity/view/VXXPrincipal.java index e1ff6e837f..19e329101e 100644 --- a/security-admin/src/main/java/org/apache/ranger/entity/view/VXXPrincipal.java +++ b/security-admin/src/main/java/org/apache/ranger/entity/view/VXXPrincipal.java @@ -17,186 +17,193 @@ * under the License. */ - package org.apache.ranger.entity.view; - +package org.apache.ranger.entity.view; import org.apache.ranger.common.DateUtil; import org.apache.ranger.common.RangerConstants; -import javax.persistence.*; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; +import javax.persistence.Temporal; +import javax.persistence.TemporalType; + import java.util.Date; @Entity -@Table(name="vx_principal") +@Table(name = "vx_principal") public class VXXPrincipal implements java.io.Serializable { - private static final long serialVersionUID = 1L; - - @Id - @Column(name="PRINCIPAL_NAME", nullable=false) - protected String principalName; - - @Id - @Column(name="PRINCIPAL_TYPE", nullable=false) - protected Integer principalType; - - @Column(name="STATUS", nullable=false) - protected int status = RangerConstants.STATUS_DISABLED; - - @Column(name="IS_VISIBLE", nullable=false ) - protected Integer isVisible; - - @Column(name="OTHER_ATTRIBUTES") - protected String otherAttributes; - - @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; - - - - /** - * @return the principalName - */ - public String getPrincipalName() { - return principalName; - } - - /** - * @param principalName the principalName to set - */ - public void setPrincipalName(String principalName) { - this.principalName = principalName; - } - - /** - * @return the principalType - */ - public Integer getPrincipalType() { - return principalType; - } - - /** - * @param principalType the principalType to set - */ - public void setPrincipalType(Integer principalType) { - this.principalType = principalType; - } - - /** - * This method sets the value to the member attribute status. - * You cannot set null to the attribute. - * @param status Value to set member attribute status - */ - public void setStatus( int status ) { - this.status = status; - } - - /** - * Returns the value for the member attribute status - * @return int - value of member attribute status. - */ - public int getStatus( ) { - return this.status; - } - - /** - * This method sets the value to the member attribute isVisible. - * You cannot set null to the attribute. - * @param isVisible Value to set member attribute isVisible - */ - public void setIsVisible(Integer isVisible) { - this.isVisible = isVisible; - } - - /** - * Returns the value for the member attribute isVisible - * @return int - value of member attribute isVisible. - */ - public Integer getIsVisible() { - return isVisible; - } - - /** - * This method sets JSON {@link String} representation of additional store attributes. - * This method accepts null values. - * @param otherAttributes - */ - public void setOtherAttributes(String otherAttributes) { - this.otherAttributes = otherAttributes; - } - - /** - * @return JSON {@link String} representation of additional store attributes if available, - * null otherwise. - */ - public String getOtherAttributes() { - return otherAttributes; - } - - /** - * @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; - } + private static final long serialVersionUID = 1L; + + @Id + @Column(name = "PRINCIPAL_NAME", nullable = false) + protected String principalName; + + @Id + @Column(name = "PRINCIPAL_TYPE", nullable = false) + protected Integer principalType; + + @Column(name = "STATUS", nullable = false) + protected int status = RangerConstants.STATUS_DISABLED; + + @Column(name = "IS_VISIBLE", nullable = false) + protected Integer isVisible; + + @Column(name = "OTHER_ATTRIBUTES") + protected String otherAttributes; + + @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; + + /** + * @return the principalName + */ + public String getPrincipalName() { + return principalName; + } + + /** + * @param principalName the principalName to set + */ + public void setPrincipalName(String principalName) { + this.principalName = principalName; + } + + /** + * @return the principalType + */ + public Integer getPrincipalType() { + return principalType; + } + + /** + * @param principalType the principalType to set + */ + public void setPrincipalType(Integer principalType) { + this.principalType = principalType; + } + + /** + * Returns the value for the member attribute status + * + * @return int - value of member attribute status. + */ + public int getStatus() { + return this.status; + } + + /** + * This method sets the value to the member attribute status. + * You cannot set null to the attribute. + * + * @param status Value to set member attribute status + */ + public void setStatus(int status) { + this.status = status; + } + + /** + * Returns the value for the member attribute isVisible + * + * @return int - value of member attribute isVisible. + */ + public Integer getIsVisible() { + return isVisible; + } + + /** + * This method sets the value to the member attribute isVisible. + * You cannot set null to the attribute. + * + * @param isVisible Value to set member attribute isVisible + */ + public void setIsVisible(Integer isVisible) { + this.isVisible = isVisible; + } + + /** + * @return JSON {@link String} representation of additional store attributes if available, + * null otherwise. + */ + public String getOtherAttributes() { + return otherAttributes; + } + + /** + * This method sets JSON {@link String} representation of additional store attributes. + * This method accepts null values. + * + * @param otherAttributes + */ + public void setOtherAttributes(String otherAttributes) { + this.otherAttributes = otherAttributes; + } + + /** + * @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; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/metrics/RangerAdminMetricsWrapper.java b/security-admin/src/main/java/org/apache/ranger/metrics/RangerAdminMetricsWrapper.java index 7fe5f1b7c0..f3265c1fde 100644 --- a/security-admin/src/main/java/org/apache/ranger/metrics/RangerAdminMetricsWrapper.java +++ b/security-admin/src/main/java/org/apache/ranger/metrics/RangerAdminMetricsWrapper.java @@ -41,7 +41,7 @@ @Component public class RangerAdminMetricsWrapper { - private static final Logger LOG= LoggerFactory.getLogger(RangerAdminMetricsWrapper.class); + private static final Logger LOG = LoggerFactory.getLogger(RangerAdminMetricsWrapper.class); private static final String context = "admin"; From 610bd5eb805d1031c9e69c182cbff05eb25c3f16 Mon Sep 17 00:00:00 2001 From: PradeeP AgrawaL Date: Mon, 13 Jan 2025 17:11:06 +0530 Subject: [PATCH 15/15] RANGER-5061: checkstyle compliance updates - security-admin module's biz and util package (#507) * RANGER-5061: checkstyle compliance updates - security-admin org.apache.ranger.rest (#505) * RANGER-5061: checkstyle compliance updates - security-admin modules : org.apache.ranger.biz package * RANGER-5061: checkstyle compliance updates - security-admin modules : org.apache.ranger.util package * Remove unmatched curly in BaseMgr.java * Update RangerAdminCache.java * Update RangerRestUtil.java userProfile.setFirstName is called twice, probably not needed ? * Update RestUtil.java * RANGER-5061: checkstyle compliance updates - security-admin modules : org.apache.ranger.biz package --------- Co-authored-by: Abhishek Kumar Co-authored-by: Madhan Neethiraj --- dev-support/checkstyle-suppressions.xml | 5 + .../java/org/apache/ranger/biz/AssetMgr.java | 2525 ++-- .../org/apache/ranger/biz/AssetMgrBase.java | 152 +- .../java/org/apache/ranger/biz/BaseMgr.java | 44 +- .../org/apache/ranger/biz/GdsDBStore.java | 1197 +- .../ranger/biz/GdsPolicyAdminCache.java | 10 +- .../java/org/apache/ranger/biz/KmsKeyMgr.java | 1408 +- .../apache/ranger/biz/PolicyRefUpdater.java | 952 +- .../org/apache/ranger/biz/RangerBizUtil.java | 3101 ++-- .../apache/ranger/biz/RangerPolicyAdmin.java | 12 +- .../ranger/biz/RangerPolicyAdminCache.java | 364 +- ...angerPolicyAdminCacheForEngineOptions.java | 6 +- .../ranger/biz/RangerPolicyAdminImpl.java | 588 +- .../ranger/biz/RangerPolicyRetriever.java | 1186 +- .../ranger/biz/RangerTagDBRetriever.java | 682 +- .../org/apache/ranger/biz/RoleDBStore.java | 455 +- .../org/apache/ranger/biz/RoleRefUpdater.java | 649 +- .../ranger/biz/SecurityZoneDBStore.java | 129 +- .../ranger/biz/SecurityZoneRefUpdater.java | 353 +- .../org/apache/ranger/biz/ServiceDBStore.java | 12430 ++++++++-------- .../org/apache/ranger/biz/ServiceMgr.java | 1318 +- .../org/apache/ranger/biz/SessionMgr.java | 976 +- .../org/apache/ranger/biz/TagDBStore.java | 2010 ++- .../java/org/apache/ranger/biz/UserMgr.java | 2778 ++-- .../org/apache/ranger/biz/UserMgrBase.java | 63 +- .../java/org/apache/ranger/biz/XAuditMgr.java | 240 +- .../org/apache/ranger/biz/XAuditMgrBase.java | 148 +- .../java/org/apache/ranger/biz/XUserMgr.java | 7094 ++++----- .../org/apache/ranger/biz/XUserMgrBase.java | 438 +- .../ranger/service/RangerRoleService.java | 2 - .../java/org/apache/ranger/util/CLIUtil.java | 115 +- .../util/Pbkdf2PasswordEncoderCust.java | 38 +- .../apache/ranger/util/RangerAdminCache.java | 44 +- .../apache/ranger/util/RangerEnumUtil.java | 3954 ++--- .../apache/ranger/util/RangerMetricsUtil.java | 25 +- .../apache/ranger/util/RangerRestUtil.java | 143 +- .../ranger/util/RangerServerHealthUtil.java | 4 +- .../java/org/apache/ranger/util/RestUtil.java | 305 +- .../main/resources/hadoop-metrics2.properties | 1 - .../internationalization/messages.properties | 2 +- .../messages_cs_CZ.properties | 2 +- .../messages_de.properties | 2 +- .../messages_es_ES.properties | 2 +- .../messages_fr.properties | 2 +- .../messages_it.properties | 2 +- .../messages_ko_KR.properties | 2 +- .../messages_lt.properties | 2 +- .../messages_pl.properties | 2 +- .../messages_pt_BR.properties | 2 +- .../messages_pt_PT.properties | 2 +- .../messages_uk_UA.properties | 2 +- .../messages_zh_CN.properties | 2 +- .../main/resources/resourcenamemap.properties | 2 +- 53 files changed, 23349 insertions(+), 22623 deletions(-) diff --git a/dev-support/checkstyle-suppressions.xml b/dev-support/checkstyle-suppressions.xml index 9856e3ca8c..624016707b 100644 --- a/dev-support/checkstyle-suppressions.xml +++ b/dev-support/checkstyle-suppressions.xml @@ -28,13 +28,18 @@ + + + + + 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 index 620d1e6193..4d55598883 100644 --- a/security-admin/src/main/java/org/apache/ranger/biz/AssetMgr.java +++ b/security-admin/src/main/java/org/apache/ranger/biz/AssetMgr.java @@ -17,24 +17,7 @@ * under the License. */ - package org.apache.ranger.biz; - -import java.security.cert.X509Certificate; -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.Set; -import java.util.stream.Collectors; - -import javax.annotation.PostConstruct; -import javax.naming.InvalidNameException; -import javax.naming.ldap.LdapName; -import javax.naming.ldap.Rdn; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +package org.apache.ranger.biz; import org.apache.commons.lang.StringUtils; import org.apache.ranger.amazon.cloudwatch.CloudWatchAccessAuditsService; @@ -60,1078 +43,654 @@ import org.apache.ranger.plugin.util.RangerPluginCapability; import org.apache.ranger.plugin.util.RangerRESTUtils; import org.apache.ranger.plugin.util.SearchFilter; -import org.apache.ranger.service.*; +import org.apache.ranger.service.RangerPluginInfoService; +import org.apache.ranger.service.RangerTrxLogV2Service; +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.XUgsyncAuditInfoService; +import org.apache.ranger.service.XUserService; import org.apache.ranger.solr.SolrAccessAuditsService; import org.apache.ranger.util.RestUtil; -import org.apache.ranger.view.*; +import org.apache.ranger.view.VXAccessAuditList; +import org.apache.ranger.view.VXAsset; +import org.apache.ranger.view.VXAuditMap; +import org.apache.ranger.view.VXGroup; +import org.apache.ranger.view.VXGroupList; +import org.apache.ranger.view.VXPermMap; +import org.apache.ranger.view.VXPolicyExportAuditList; +import org.apache.ranger.view.VXResource; +import org.apache.ranger.view.VXTrxLog; +import org.apache.ranger.view.VXTrxLogList; +import org.apache.ranger.view.VXTrxLogV2; import org.apache.ranger.view.VXTrxLogV2.AttributeChangeInfo; import org.apache.ranger.view.VXTrxLogV2.ObjectChangeInfo; +import org.apache.ranger.view.VXUgsyncAuditInfoList; +import org.apache.ranger.view.VXUser; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.util.CollectionUtils; +import javax.annotation.PostConstruct; +import javax.naming.InvalidNameException; +import javax.naming.ldap.LdapName; +import javax.naming.ldap.Rdn; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import java.security.cert.X509Certificate; +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.Set; +import java.util.stream.Collectors; + @Component public class AssetMgr extends AssetMgrBase { - private static final String PROP_RANGER_LOG_SC_NOT_MODIFIED = "ranger.log.SC_NOT_MODIFIED"; - private static final String PROP_PLUGIN_ACTIVITY_AUDIT_NOT_MODIFIED = "ranger.plugin.activity.audit.not.modified"; - private static final String PROP_PLUGIN_ACTIVITY_AUDIT_COMMIT_INLINE = "ranger.plugin.activity.audit.commit.inline"; + private static final Logger logger = LoggerFactory.getLogger(AssetMgr.class); + + private static final String PROP_RANGER_LOG_SC_NOT_MODIFIED = "ranger.log.SC_NOT_MODIFIED"; + private static final String PROP_PLUGIN_ACTIVITY_AUDIT_NOT_MODIFIED = "ranger.plugin.activity.audit.not.modified"; + private static final String PROP_PLUGIN_ACTIVITY_AUDIT_COMMIT_INLINE = "ranger.plugin.activity.audit.commit.inline"; + private static final String adminCapabilities = Long.toHexString(new RangerPluginCapability().getPluginCapabilities()); + + @Autowired + XPermMapService xPermMapService; + + @Autowired + XAuditMapService xAuditMapService; + + @Autowired + JSONUtil jsonUtil; - @Autowired - XPermMapService xPermMapService; + @Autowired + RangerBizUtil msBizUtil; - @Autowired - XAuditMapService xAuditMapService; + @Autowired + StringUtil stringUtil; - @Autowired - JSONUtil jsonUtil; + @Autowired + RangerDaoManager rangerDaoManager; - @Autowired - RangerBizUtil msBizUtil; + @Autowired + XUserService xUserService; - @Autowired - StringUtil stringUtil; + @Autowired + RangerBizUtil xaBizUtil; - @Autowired - RangerDaoManager rangerDaoManager; + @Autowired + RangerTrxLogV2Service xTrxLogService; - @Autowired - XUserService xUserService; + @Autowired + XAccessAuditService xAccessAuditService; - @Autowired - RangerBizUtil xaBizUtil; + @Autowired + XGroupService xGroupService; - @Autowired - RangerTrxLogV2Service xTrxLogService; + @Autowired + XUserMgr xUserMgr; - @Autowired - XAccessAuditService xAccessAuditService; + @Autowired + SolrAccessAuditsService solrAccessAuditsService; - @Autowired - XGroupService xGroupService; - - @Autowired - XUserMgr xUserMgr; + @Autowired + ElasticSearchAccessAuditsService elasticSearchAccessAuditsService; - @Autowired - SolrAccessAuditsService solrAccessAuditsService; + @Autowired + CloudWatchAccessAuditsService cloudWatchAccessAuditsService; - @Autowired - ElasticSearchAccessAuditsService elasticSearchAccessAuditsService; + @Autowired + XPolicyService xPolicyService; - @Autowired - CloudWatchAccessAuditsService cloudWatchAccessAuditsService; + @Autowired + RangerTransactionSynchronizationAdapter transactionSynchronizationAdapter; - @Autowired - XPolicyService xPolicyService; + @Autowired + RangerPluginInfoService pluginInfoService; - @Autowired - RangerTransactionSynchronizationAdapter transactionSynchronizationAdapter; + @Autowired + XUgsyncAuditInfoService xUgsyncAuditInfoService; - @Autowired - RangerPluginInfoService pluginInfoService; + @Autowired + ServiceMgr serviceMgr; - @Autowired - XUgsyncAuditInfoService xUgsyncAuditInfoService; + boolean rangerLogNotModified; + boolean pluginActivityAuditLogNotModified; + boolean pluginActivityAuditCommitInline; - @Autowired - ServiceMgr serviceMgr; - - boolean rangerLogNotModified = false; - boolean pluginActivityAuditLogNotModified = false; - boolean pluginActivityAuditCommitInline = false; - - private static final Logger logger = LoggerFactory.getLogger(AssetMgr.class); - - private static final String adminCapabilities = Long.toHexString(new RangerPluginCapability().getPluginCapabilities()); - - @PostConstruct - public void init() { - logger.info("==> AssetMgr.init()"); - - rangerLogNotModified = RangerAdminConfig.getInstance().getBoolean(PROP_RANGER_LOG_SC_NOT_MODIFIED, false); - pluginActivityAuditLogNotModified = RangerAdminConfig.getInstance().getBoolean(PROP_PLUGIN_ACTIVITY_AUDIT_NOT_MODIFIED, false); - pluginActivityAuditCommitInline = RangerAdminConfig.getInstance().getBoolean(PROP_PLUGIN_ACTIVITY_AUDIT_COMMIT_INLINE, false); - - logger.info("{}={}", PROP_RANGER_LOG_SC_NOT_MODIFIED, rangerLogNotModified); - logger.info("{}={}", PROP_PLUGIN_ACTIVITY_AUDIT_NOT_MODIFIED, pluginActivityAuditLogNotModified); - logger.info("{}={}", PROP_PLUGIN_ACTIVITY_AUDIT_COMMIT_INLINE, pluginActivityAuditCommitInline); - - logger.info("<== AssetMgr.init()"); - } - - public String getLatestRepoPolicy(VXAsset xAsset, List xResourceList, Long updatedTime, - X509Certificate[] certchain, boolean httpEnabled, String epoch, - String ipAddress, boolean isSecure, String count, String agentId) { - if(xAsset == null) { - logger.error("Requested repository not found"); - throw restErrorUtil.createRESTException("No Data Found.", - MessageEnums.DATA_NOT_FOUND); - } - if (xResourceList == null) { - logger.error("ResourceList is found"); - throw restErrorUtil.createRESTException("No Data Found.", - MessageEnums.DATA_NOT_FOUND); - } - if(xAsset.getActiveStatus() == RangerCommonEnums.ACT_STATUS_DISABLED) { - logger.error("Requested repository is disabled"); - throw restErrorUtil.createRESTException("Unauthorized access.", - MessageEnums.OPER_NO_EXPORT); - } - - HashMap updatedRepo = new HashMap(); - updatedRepo.put("repository_name", xAsset.getName()); - - XXPolicyExportAudit policyExportAudit = new XXPolicyExportAudit(); - policyExportAudit.setRepositoryName(xAsset.getName()); - - if (agentId != null && !agentId.isEmpty()) { - policyExportAudit.setAgentId(agentId); - } - - policyExportAudit.setClientIP(ipAddress); - - if (epoch != null && !epoch.trim().isEmpty() && !"null".equalsIgnoreCase(epoch)) { - 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 ("CN".equalsIgnoreCase(rdn.getType())) { - commonName = rdn.getValue() + ""; - break; - } - } - if (commonName == null) { - policyExportAudit - .setHttpRetCode(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(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 (policyCount == null) { - policyCount = 0L; - } - - if (commonName != null) { - String config = xAsset.getConfig(); - Map configMap = jsonUtil.jsonToMap(config); - String cnFromConfig = configMap.get("commonNameForCertificate"); - - if (cnFromConfig == null - || !commonName.equalsIgnoreCase(cnFromConfig)) { - policyExportAudit - .setHttpRetCode(HttpServletResponse.SC_BAD_REQUEST); - createPolicyAudit(policyExportAudit); - - throw restErrorUtil.createRESTException( - "Unauthorized access. expected [" + cnFromConfig - + "], found [" + commonName + "]", - MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY); - } - } - - long epochTime = epoch != null ? Long.parseLong(epoch) : 0; - - if(epochTime == updatedTime) { - int resourceListSz = xResourceList.size(); - - if (policyCount == resourceListSz) { - policyExportAudit - .setHttpRetCode(HttpServletResponse.SC_NOT_MODIFIED); - createPolicyAudit(policyExportAudit); - - throw restErrorUtil.createRESTException( - HttpServletResponse.SC_NOT_MODIFIED, - "No change since last update", false); - } - } - - List> resourceList = new ArrayList>(); - - // HDFS Repository - if (xAsset.getAssetType() == AppConstants.ASSET_HDFS) { - for (VXResource xResource : xResourceList) { - HashMap resourceMap = new HashMap(); - resourceMap.put("id", xResource.getId()); - resourceMap.put("resource", xResource.getName()); - resourceMap.put("isRecursive", - getBooleanValue(xResource.getIsRecursive())); - resourceMap.put("policyStatus", RangerCommonEnums - .getLabelFor_ActiveStatus(xResource - .getResourceStatus())); - // resourceMap.put("isEncrypt", - // AKAConstants.getLabelFor_BooleanValue(xResource.getIsEncrypt())); - populatePermMap(xResource, resourceMap, AppConstants.ASSET_HDFS); - List xAuditMaps = xResource.getAuditList(); - if (xAuditMaps.size() != 0) { - resourceMap.put("audit", 1); - } else { - resourceMap.put("audit", 0); - } - - resourceList.add(resourceMap); - } - } else if (xAsset.getAssetType() == AppConstants.ASSET_HIVE) { - for (VXResource xResource : xResourceList) { - HashMap resourceMap = new HashMap(); - resourceMap.put("id", xResource.getId()); - resourceMap.put("database_name", xResource.getDatabases()); - resourceMap.put("policyStatus", RangerCommonEnums - .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 xAuditMaps = xResource.getAuditList(); - if (xAuditMaps.size() != 0) { - resourceMap.put("audit", 1); - } else { - resourceMap.put("audit", 0); - } - resourceList.add(resourceMap); - } - } - - else if (xAsset.getAssetType() == AppConstants.ASSET_HBASE) { - for (VXResource xResource : xResourceList) { - HashMap resourceMap = new HashMap(); - - 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", RangerCommonEnums - .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 xAuditMaps = xResource.getAuditList(); - if (xAuditMaps.size() != 0) { - resourceMap.put("audit", 1); - } else { - resourceMap.put("audit", 0); - } - resourceList.add(resourceMap); - } - } - else if (xAsset.getAssetType() == AppConstants.ASSET_KNOX) { - for (VXResource xResource : xResourceList) { - HashMap resourceMap = new HashMap(); - - resourceMap.put("id", xResource.getId()); - resourceMap.put("topology_name", xResource.getTopologies()); - resourceMap.put("service_name", xResource.getServices()); - resourceMap.put("policyStatus", RangerCommonEnums - .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 xAuditMaps = xResource.getAuditList(); - if (xAuditMaps.size() != 0) { - resourceMap.put("audit", 1); - } else { - resourceMap.put("audit", 0); - } - resourceList.add(resourceMap); - } - + @PostConstruct + public void init() { + logger.info("==> AssetMgr.init()"); + + rangerLogNotModified = RangerAdminConfig.getInstance().getBoolean(PROP_RANGER_LOG_SC_NOT_MODIFIED, false); + pluginActivityAuditLogNotModified = RangerAdminConfig.getInstance().getBoolean(PROP_PLUGIN_ACTIVITY_AUDIT_NOT_MODIFIED, false); + pluginActivityAuditCommitInline = RangerAdminConfig.getInstance().getBoolean(PROP_PLUGIN_ACTIVITY_AUDIT_COMMIT_INLINE, false); + + logger.info("{}={}", PROP_RANGER_LOG_SC_NOT_MODIFIED, rangerLogNotModified); + logger.info("{}={}", PROP_PLUGIN_ACTIVITY_AUDIT_NOT_MODIFIED, pluginActivityAuditLogNotModified); + logger.info("{}={}", PROP_PLUGIN_ACTIVITY_AUDIT_COMMIT_INLINE, pluginActivityAuditCommitInline); + + logger.info("<== AssetMgr.init()"); + } + + public String getLatestRepoPolicy(VXAsset xAsset, List xResourceList, Long updatedTime, X509Certificate[] certchain, boolean httpEnabled, String epoch, String ipAddress, boolean isSecure, String count, String agentId) { + if (xAsset == null) { + logger.error("Requested repository not found"); + + throw restErrorUtil.createRESTException("No Data Found.", MessageEnums.DATA_NOT_FOUND); } - else if (xAsset.getAssetType() == AppConstants.ASSET_STORM) { - for (VXResource xResource : xResourceList) { - HashMap resourceMap = new HashMap(); - - resourceMap.put("id", xResource.getId()); - resourceMap.put("topology_name", xResource.getTopologies()); - resourceMap.put("policyStatus", RangerCommonEnums - .getLabelFor_ActiveStatus(xResource - .getResourceStatus())); - if (xResource.getIsEncrypt() == 1) { - resourceMap.put("encrypt", 1); - } else { - resourceMap.put("encrypt", 0); - } - populatePermMap(xResource, resourceMap, AppConstants.ASSET_STORM); - List xAuditMaps = xResource.getAuditList(); - if (xAuditMaps.size() != 0) { - resourceMap.put("audit", 1); - } else { - resourceMap.put("audit", 0); - } - resourceList.add(resourceMap); + + if (xResourceList == null) { + logger.error("ResourceList is found"); + + throw restErrorUtil.createRESTException("No Data Found.", MessageEnums.DATA_NOT_FOUND); + } + + if (xAsset.getActiveStatus() == RangerCommonEnums.ACT_STATUS_DISABLED) { + logger.error("Requested repository is disabled"); + + throw restErrorUtil.createRESTException("Unauthorized access.", MessageEnums.OPER_NO_EXPORT); + } + + HashMap updatedRepo = new HashMap<>(); + + updatedRepo.put("repository_name", xAsset.getName()); + + XXPolicyExportAudit policyExportAudit = new XXPolicyExportAudit(); + + policyExportAudit.setRepositoryName(xAsset.getName()); + + if (agentId != null && !agentId.isEmpty()) { + policyExportAudit.setAgentId(agentId); + } + + policyExportAudit.setClientIP(ipAddress); + + if (epoch != null && !epoch.trim().isEmpty() && !"null".equalsIgnoreCase(epoch)) { + 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 ("CN".equalsIgnoreCase(rdn.getType())) { + commonName = rdn.getValue() + ""; + break; + } + } + + if (commonName == null) { + policyExportAudit.setHttpRetCode(HttpServletResponse.SC_BAD_REQUEST); + + createPolicyAudit(policyExportAudit); + + throw restErrorUtil.createRESTException("Unauthorized access - Unable to find Common Name from [" + dn + "]", MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY); } - } else { - policyExportAudit - .setHttpRetCode(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(HttpServletResponse.SC_OK); - createPolicyAudit(policyExportAudit); - - return updatedPolicyStr; - } - @SuppressWarnings("unchecked") - private HashMap populatePermMap(VXResource xResource, - HashMap resourceMap, int assetType) { - List xPermMapList = xResource.getPermMapList(); - - Set groupList = new HashSet(); - for (VXPermMap xPermMap : xPermMapList) { - groupList.add(xPermMap.getId()); - } - - List> sortedPermMapGroupList = new ArrayList>(); - - // Loop for adding group perms - for (VXPermMap xPermMap : xPermMapList) { - String groupKey = xPermMap.getPermGroup(); - if (groupKey != null) { - boolean found = false; - for (HashMap sortedPermMap : sortedPermMapGroupList) { - if (sortedPermMap.containsValue(groupKey)) { - found = true; - - Long groupId = xPermMap.getGroupId(); - Long userId = xPermMap.getUserId(); - - if (groupId != null) { - Set groups = (Set) sortedPermMap.get("groups"); - - if(groups != null) { - groups.add(xPermMap.getGroupName()); - sortedPermMap.put("groups", groups); - } - } else if (userId != null) { - Set users = (Set) sortedPermMap.get("users"); - - if (users != null) { - users.add(xPermMap.getUserName()); - sortedPermMap.put("users", users); - } - } - - Set access = (Set) sortedPermMap - .get("access"); - String perm = AppConstants - .getLabelFor_XAPermType(xPermMap.getPermType()); - access.add(perm); - sortedPermMap.put("access", access); - } - } - if (!found) { - HashMap sortedPermMap = new HashMap(); - sortedPermMap.put("groupKey", xPermMap.getPermGroup()); - - Set permSet = new HashSet(); - 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 groupSet = new HashSet(); - String group = xPermMap.getGroupName(); - groupSet.add(group); - sortedPermMap.put("groups", groupSet); - } else if (userId != null) { - Set userSet = new HashSet(); - String user = xPermMap.getUserName(); - userSet.add(user); - sortedPermMap.put("users", userSet); - } - - sortedPermMapGroupList.add(sortedPermMap); - } - } - } - - for (HashMap sortedPermMap : sortedPermMapGroupList) { - sortedPermMap.remove("groupKey"); - } - - for (HashMap 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 UpdateDefaultPolicyUserAndPerm(VXResource vXResource, - String userName) { - if (userName != null && !userName.isEmpty()) { - XXUser xxUser = rangerDaoManager.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 xxPermMapList = rangerDaoManager.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 void createPolicyAudit(final XXPolicyExportAudit xXPolicyExportAudit) { - final Runnable commitWork; - if (xXPolicyExportAudit.getHttpRetCode() == HttpServletResponse.SC_NOT_MODIFIED) { - if (!rangerLogNotModified) { - logger.debug("Not logging HttpServletResponse. SC_NOT_MODIFIED. To enable, set configuration: {}=true", PROP_RANGER_LOG_SC_NOT_MODIFIED); - - commitWork = null; - } else { - // Create PolicyExportAudit record after transaction is completed. If it is created in-line here - // then the TransactionManager will roll-back the changes because the HTTP return code is - // HttpServletResponse.SC_NOT_MODIFIED - commitWork = new Runnable() { - @Override - public void run() { - rangerDaoManager.getXXPolicyExportAudit().create(xXPolicyExportAudit); - } - }; - } - } else { - commitWork = new Runnable() { - @Override - public void run() { - rangerDaoManager.getXXPolicyExportAudit().create(xXPolicyExportAudit); - } - }; - } - - if (commitWork != null) { - if (pluginActivityAuditCommitInline) { - transactionSynchronizationAdapter.executeOnTransactionCompletion(commitWork); - } else { - transactionSynchronizationAdapter.executeAsyncOnTransactionComplete(commitWork); - } - } - } - - public void createPluginInfo(String serviceName, String pluginId, HttpServletRequest request, int entityType, Long downloadedVersion, Long lastKnownVersion, long lastActivationTime, int httpCode, String clusterName, String pluginCapabilities) { - RangerRESTUtils restUtils = new RangerRESTUtils(); - - final String ipAddress = getRemoteAddress(request); - final String appType = restUtils.getAppIdFromPluginId(pluginId); - - String tmpHostName = null; - if (StringUtils.isNotBlank(pluginId)) { - tmpHostName = restUtils.getHostnameFromPluginId(pluginId, serviceName); - } - if (StringUtils.isBlank(tmpHostName) && request != null) { - tmpHostName = request.getRemoteHost(); - } - - final String hostName = (StringUtils.isBlank(tmpHostName)) ? ipAddress : tmpHostName; - - RangerPluginInfo pluginSvcVersionInfo = new RangerPluginInfo(); - - pluginSvcVersionInfo.setServiceName(serviceName); - pluginSvcVersionInfo.setAppType(appType); - pluginSvcVersionInfo.setHostName(hostName); - pluginSvcVersionInfo.setIpAddress(ipAddress); - pluginSvcVersionInfo.setPluginCapabilities(StringUtils.isEmpty(pluginCapabilities) ? RangerPluginCapability.getBaseRangerCapabilities() : pluginCapabilities); - - switch (entityType) { - case RangerPluginInfo.ENTITY_TYPE_POLICIES: - pluginSvcVersionInfo.setPolicyActiveVersion(lastKnownVersion); - pluginSvcVersionInfo.setPolicyActivationTime(lastActivationTime); - pluginSvcVersionInfo.setPolicyDownloadedVersion(downloadedVersion); - pluginSvcVersionInfo.setPolicyDownloadTime(new Date().getTime()); - break; - case RangerPluginInfo.ENTITY_TYPE_TAGS: - pluginSvcVersionInfo.setTagActiveVersion(lastKnownVersion); - pluginSvcVersionInfo.setTagActivationTime(lastActivationTime); - pluginSvcVersionInfo.setTagDownloadedVersion(downloadedVersion); - pluginSvcVersionInfo.setTagDownloadTime(new Date().getTime()); - break; - case RangerPluginInfo.ENTITY_TYPE_ROLES: - pluginSvcVersionInfo.setRoleActiveVersion(lastKnownVersion); - pluginSvcVersionInfo.setRoleActivationTime(lastActivationTime); - pluginSvcVersionInfo.setRoleDownloadedVersion(downloadedVersion); - pluginSvcVersionInfo.setRoleDownloadTime(new Date().getTime()); - break; - case RangerPluginInfo.ENTITY_TYPE_USERSTORE: - pluginSvcVersionInfo.setUserStoreActiveVersion(lastKnownVersion); - pluginSvcVersionInfo.setUserStoreActivationTime(lastActivationTime); - pluginSvcVersionInfo.setUserStoreDownloadedVersion(downloadedVersion); - pluginSvcVersionInfo.setUserStoreDownloadTime(new Date().getTime()); - break; - case RangerPluginInfo.ENTITY_TYPE_GDS: - pluginSvcVersionInfo.setGdsActiveVersion(lastKnownVersion); - pluginSvcVersionInfo.setGdsActivationTime(lastActivationTime); - pluginSvcVersionInfo.setGdsDownloadedVersion(downloadedVersion); - pluginSvcVersionInfo.setGdsDownloadTime(new Date().getTime()); - break; - } - - createOrUpdatePluginInfo(pluginSvcVersionInfo, entityType , httpCode, clusterName); - } - - private void createOrUpdatePluginInfo(final RangerPluginInfo pluginInfo, int entityType, final int httpCode, String clusterName) { - - if (logger.isDebugEnabled()) { - logger.debug("==> createOrUpdatePluginInfo(pluginInfo = " + pluginInfo + ", isPolicyDownloadRequest = " + isPolicyDownloadRequest(entityType) + ", httpCode = " + httpCode + ")"); - } - - final boolean isTagVersionResetNeeded; - final Runnable commitWork; - - if (httpCode == HttpServletResponse.SC_NOT_MODIFIED) { - if (!pluginActivityAuditLogNotModified) { - logger.debug("Not logging HttpServletResponse. SC_NOT_MODIFIED. To enable, set configuration: {}=true", PROP_PLUGIN_ACTIVITY_AUDIT_NOT_MODIFIED); - - commitWork = null; - } else { - // Create or update PluginInfo record after transaction is completed. If it is created in-line here - // then the TransactionManager will roll-back the changes because the HTTP return code is - // HttpServletResponse.SC_NOT_MODIFIED - - switch (entityType) { - case RangerPluginInfo.ENTITY_TYPE_POLICIES: - isTagVersionResetNeeded = rangerDaoManager.getXXService().findAssociatedTagService(pluginInfo.getServiceName()) == null; - break; - case RangerPluginInfo.ENTITY_TYPE_TAGS: - case RangerPluginInfo.ENTITY_TYPE_ROLES: - case RangerPluginInfo.ENTITY_TYPE_USERSTORE: - case RangerPluginInfo.ENTITY_TYPE_GDS: - default: - isTagVersionResetNeeded = false; - break; - } - - commitWork = new Runnable() { - @Override - public void run() { - doCreateOrUpdateXXPluginInfo(pluginInfo, entityType, isTagVersionResetNeeded, clusterName); - } - }; - } - } else if (httpCode == HttpServletResponse.SC_NOT_FOUND) { - if ((isPolicyDownloadRequest(entityType) && (pluginInfo.getPolicyActiveVersion() == null || pluginInfo.getPolicyActiveVersion() == -1)) - || (isTagDownloadRequest(entityType) && (pluginInfo.getTagActiveVersion() == null || pluginInfo.getTagActiveVersion() == -1)) - || (isRoleDownloadRequest(entityType) && (pluginInfo.getRoleActiveVersion() == null || pluginInfo.getRoleActiveVersion() == -1)) - || (isUserStoreDownloadRequest(entityType) && (pluginInfo.getUserStoreActiveVersion() == null || pluginInfo.getUserStoreActiveVersion() == -1)) - || (isGdsDownloadRequest(entityType) && (pluginInfo.getGdsActiveVersion() == null || pluginInfo.getGdsActiveVersion() == -1))) { - commitWork = new Runnable() { - @Override - public void run() { - doDeleteXXPluginInfo(pluginInfo); - } - }; - } else { - commitWork = new Runnable() { - @Override - public void run() { - doCreateOrUpdateXXPluginInfo(pluginInfo, entityType, false, clusterName); - } - }; - } - } else { - isTagVersionResetNeeded = false; - - commitWork = new Runnable() { - @Override - public void run() { - doCreateOrUpdateXXPluginInfo(pluginInfo, entityType, isTagVersionResetNeeded, clusterName); - } - }; - } - - if (commitWork != null) { - if (pluginActivityAuditCommitInline) { - transactionSynchronizationAdapter.executeOnTransactionCompletion(commitWork); - } else { - transactionSynchronizationAdapter.executeAsyncOnTransactionComplete(commitWork); - } - } - - if (logger.isDebugEnabled()) { - logger.debug("<== createOrUpdatePluginInfo(pluginInfo = " + pluginInfo + ", isPolicyDownloadRequest = " + isPolicyDownloadRequest(entityType) + ", httpCode = " + httpCode + ")"); - } - - } - - private XXPluginInfo doCreateOrUpdateXXPluginInfo(RangerPluginInfo pluginInfo, int entityType, final boolean isTagVersionResetNeeded, String clusterName) { - XXPluginInfo ret = null; - Map infoMap = null; - - if (StringUtils.isNotBlank(pluginInfo.getServiceName())) { - - XXPluginInfo xObj = rangerDaoManager.getXXPluginInfo().find(pluginInfo.getServiceName(), - pluginInfo.getHostName(), pluginInfo.getAppType()); - - if (xObj == null) { - infoMap = pluginInfo.getInfo(); - if(!stringUtil.isEmpty(clusterName) && infoMap != null ) { - infoMap.put(SearchFilter.CLUSTER_NAME, clusterName); - pluginInfo.setInfo(infoMap); - } - // ranger-admin is restarted, plugin contains latest versions and no earlier record for this plug-in client - if (isPolicyDownloadRequest(entityType)) { - if (pluginInfo.getPolicyDownloadedVersion() != null && pluginInfo.getPolicyDownloadedVersion().equals(pluginInfo.getPolicyActiveVersion())) { - // This is our best guess of when policies may have been downloaded - pluginInfo.setPolicyDownloadTime(pluginInfo.getPolicyActivationTime()); - } - } else if (isTagDownloadRequest(entityType)) { - if (pluginInfo.getTagDownloadedVersion() != null && pluginInfo.getTagDownloadedVersion().equals(pluginInfo.getTagActiveVersion())) { - // This is our best guess of when tags may have been downloaded - pluginInfo.setTagDownloadTime(pluginInfo.getTagActivationTime()); - } - } else if (isRoleDownloadRequest(entityType)) { - if (pluginInfo.getRoleDownloadTime() != null && pluginInfo.getRoleDownloadedVersion().equals(pluginInfo.getRoleActiveVersion())) { - // This is our best guess of when role may have been downloaded - pluginInfo.setRoleDownloadTime(pluginInfo.getRoleActivationTime()); - } - } else if (isUserStoreDownloadRequest(entityType)) { - if (pluginInfo.getUserStoreDownloadTime() != null && pluginInfo.getUserStoreDownloadedVersion().equals(pluginInfo.getUserStoreActiveVersion())) { - // This is our best guess of when users and groups may have been downloaded - pluginInfo.setUserStoreDownloadTime(pluginInfo.getUserStoreActivationTime()); - } - } else if (isGdsDownloadRequest(entityType)) { - if (pluginInfo.getGdsDownloadTime() != null && pluginInfo.getGdsDownloadedVersion().equals(pluginInfo.getGdsActiveVersion())) { - // This is our best guess of when GDS info may have been downloaded - pluginInfo.setGdsDownloadTime(pluginInfo.getGdsActivationTime()); - } - } - - pluginInfo.setAdminCapabilities(adminCapabilities); - - xObj = pluginInfoService.populateDBObject(pluginInfo); - - if (logger.isDebugEnabled()) { - logger.debug("Creating RangerPluginInfo record for service-version"); - } - ret = rangerDaoManager.getXXPluginInfo().create(xObj); - } else { - boolean needsUpdating = false; - - RangerPluginInfo dbObj = pluginInfoService.populateViewObject(xObj); - - infoMap = dbObj.getInfo(); - if (infoMap != null && !stringUtil.isEmpty(clusterName)) { - if(!stringUtil.isEmpty(infoMap.get(SearchFilter.CLUSTER_NAME)) && !stringUtil.equals(infoMap.get(SearchFilter.CLUSTER_NAME) , clusterName) ) { - infoMap.put(SearchFilter.CLUSTER_NAME, clusterName); - needsUpdating = true; - } - } - if (!dbObj.getIpAddress().equals(pluginInfo.getIpAddress())) { - dbObj.setIpAddress(pluginInfo.getIpAddress()); - needsUpdating = true; - } - if (isPolicyDownloadRequest(entityType)) { - if (dbObj.getPolicyDownloadedVersion() == null || !dbObj.getPolicyDownloadedVersion().equals(pluginInfo.getPolicyDownloadedVersion())) { - dbObj.setPolicyDownloadedVersion(pluginInfo.getPolicyDownloadedVersion()); - dbObj.setPolicyDownloadTime(pluginInfo.getPolicyDownloadTime()); - needsUpdating = true; - } - Long lastKnownPolicyVersion = pluginInfo.getPolicyActiveVersion(); - Long lastPolicyActivationTime = pluginInfo.getPolicyActivationTime(); - String lastPluginCapabilityVector = pluginInfo.getPluginCapabilities(); - - if (lastKnownPolicyVersion != null && lastKnownPolicyVersion == -1) { - // First download request after plug-in's policy-refresher starts - dbObj.setPolicyDownloadTime(pluginInfo.getPolicyDownloadTime()); - needsUpdating = true; - } - if (lastKnownPolicyVersion != null && lastKnownPolicyVersion > 0 && (dbObj.getPolicyActiveVersion() == null || !dbObj.getPolicyActiveVersion().equals(lastKnownPolicyVersion))) { - dbObj.setPolicyActiveVersion(lastKnownPolicyVersion); - needsUpdating = true; - } - if (lastPolicyActivationTime != null && lastPolicyActivationTime > 0 && (dbObj.getPolicyActivationTime() == null || !dbObj.getPolicyActivationTime().equals(lastPolicyActivationTime))) { - dbObj.setPolicyActivationTime(lastPolicyActivationTime); - needsUpdating = true; - } - if (lastPluginCapabilityVector != null && (dbObj.getPluginCapabilities() == null || !dbObj.getPluginCapabilities().equals(lastPluginCapabilityVector))) { - dbObj.setPluginCapabilities(lastPluginCapabilityVector); - needsUpdating = true; - } - if (dbObj.getAdminCapabilities() == null || !dbObj.getAdminCapabilities().equals(adminCapabilities)) { - dbObj.setAdminCapabilities(adminCapabilities); - needsUpdating = true; - } - } else if (isTagDownloadRequest(entityType)){ - if (dbObj.getTagDownloadedVersion() == null || !dbObj.getTagDownloadedVersion().equals(pluginInfo.getTagDownloadedVersion())) { - // First download for tags after tag-service is associated with resource-service - dbObj.setTagDownloadedVersion(pluginInfo.getTagDownloadedVersion()); - dbObj.setTagDownloadTime(pluginInfo.getTagDownloadTime()); - needsUpdating = true; - } - - Long lastKnownTagVersion = pluginInfo.getTagActiveVersion(); - Long lastTagActivationTime = pluginInfo.getTagActivationTime(); - - if (lastKnownTagVersion != null && lastKnownTagVersion == -1) { - // First download request after plug-in's tag-refresher restarts - dbObj.setTagDownloadTime(pluginInfo.getTagDownloadTime()); - needsUpdating = true; - } - if (lastKnownTagVersion != null && lastKnownTagVersion > 0 && (dbObj.getTagActiveVersion() == null || !dbObj.getTagActiveVersion().equals(lastKnownTagVersion))) { - dbObj.setTagActiveVersion(lastKnownTagVersion); - needsUpdating = true; - } - - if (lastTagActivationTime != null && lastTagActivationTime > 0 && (dbObj.getTagActivationTime() == null || !dbObj.getTagActivationTime().equals(lastTagActivationTime))) { - dbObj.setTagActivationTime(lastTagActivationTime); - needsUpdating = true; - } - } else if (isRoleDownloadRequest(entityType)){ - if (dbObj.getRoleDownloadedVersion() == null || !dbObj.getRoleDownloadedVersion().equals(pluginInfo.getRoleDownloadedVersion())) { - dbObj.setRoleDownloadedVersion(pluginInfo.getRoleDownloadedVersion()); - dbObj.setRoleDownloadTime(pluginInfo.getRoleDownloadTime()); - needsUpdating = true; - } - - Long lastKnownRoleVersion = pluginInfo.getRoleActiveVersion(); - Long lastRoleActivationTime = pluginInfo.getRoleActivationTime(); - - if (lastKnownRoleVersion != null && lastKnownRoleVersion == -1) { - dbObj.setRoleDownloadTime(pluginInfo.getRoleDownloadTime()); - needsUpdating = true; - } - - if (lastKnownRoleVersion != null && lastKnownRoleVersion > 0 && (dbObj.getRoleActiveVersion() == null || !dbObj.getRoleActiveVersion().equals(lastKnownRoleVersion))) { - dbObj.setRoleActiveVersion(lastKnownRoleVersion); - needsUpdating = true; - } - - if (lastRoleActivationTime != null && lastRoleActivationTime > 0 && (dbObj.getRoleActivationTime() == null || !dbObj.getRoleActivationTime().equals(lastRoleActivationTime))) { - dbObj.setRoleActivationTime(lastRoleActivationTime); - needsUpdating = true; - } - } else if (isUserStoreDownloadRequest(entityType)) { - if (dbObj.getUserStoreDownloadedVersion() == null || !dbObj.getUserStoreDownloadedVersion().equals(pluginInfo.getUserStoreDownloadedVersion())) { - dbObj.setUserStoreDownloadedVersion(pluginInfo.getUserStoreDownloadedVersion()); - dbObj.setUserStoreDownloadTime(pluginInfo.getUserStoreDownloadTime()); - needsUpdating = true; - } - - Long lastKnownUserStoreVersion = pluginInfo.getUserStoreActiveVersion(); - Long lastUserStoreActivationTime = pluginInfo.getUserStoreActivationTime(); - - if (lastKnownUserStoreVersion != null && lastKnownUserStoreVersion == -1) { - dbObj.setUserStoreDownloadTime(pluginInfo.getUserStoreDownloadTime()); - needsUpdating = true; - } - - if (lastKnownUserStoreVersion != null && lastKnownUserStoreVersion > 0 && (dbObj.getUserStoreActiveVersion() == null || !dbObj.getUserStoreActiveVersion().equals(lastKnownUserStoreVersion))) { - dbObj.setUserStoreActiveVersion(lastKnownUserStoreVersion); - needsUpdating = true; - } - - if (lastUserStoreActivationTime != null && lastUserStoreActivationTime > 0 && (dbObj.getUserStoreActivationTime() == null || !dbObj.getUserStoreActivationTime().equals(lastUserStoreActivationTime))) { - dbObj.setUserStoreActivationTime(lastUserStoreActivationTime); - needsUpdating = true; - } - } else if (isGdsDownloadRequest(entityType)) { - if (dbObj.getGdsDownloadedVersion() == null || !dbObj.getGdsDownloadedVersion().equals(pluginInfo.getGdsDownloadedVersion())) { - dbObj.setGdsDownloadedVersion(pluginInfo.getGdsDownloadedVersion()); - dbObj.setGdsDownloadTime(pluginInfo.getGdsDownloadTime()); - needsUpdating = true; - } - - Long lastKnownGdsVersion = pluginInfo.getGdsActiveVersion(); - Long lastGdsActivationTime = pluginInfo.getGdsActivationTime(); - - if (lastKnownGdsVersion != null && lastKnownGdsVersion == -1) { - dbObj.setGdsDownloadTime(pluginInfo.getGdsDownloadTime()); - needsUpdating = true; - } - - if (lastKnownGdsVersion != null && lastKnownGdsVersion > 0 && (dbObj.getGdsActiveVersion() == null || !dbObj.getGdsActiveVersion().equals(lastKnownGdsVersion))) { - dbObj.setGdsActiveVersion(lastKnownGdsVersion); - needsUpdating = true; - } - - if (lastGdsActivationTime != null && lastGdsActivationTime > 0 && (dbObj.getGdsActivationTime() == null || !dbObj.getGdsActivationTime().equals(lastGdsActivationTime))) { - dbObj.setGdsActivationTime(lastGdsActivationTime); - needsUpdating = true; - } - } - - if (isTagVersionResetNeeded) { - dbObj.setTagDownloadedVersion(null); - dbObj.setTagDownloadTime(null); - dbObj.setTagActiveVersion(null); - dbObj.setTagActivationTime(null); - needsUpdating = true; - } - - if (needsUpdating) { - if (logger.isDebugEnabled()) { - logger.debug("Updating XXPluginInfo record for service-version"); - } - xObj = pluginInfoService.populateDBObject(dbObj); - - ret = rangerDaoManager.getXXPluginInfo().update(xObj); - } - } - } else { - logger.error("Invalid parameters: pluginInfo=" + pluginInfo + ")"); - } - - return ret; - } - - private void doDeleteXXPluginInfo(RangerPluginInfo pluginInfo) { - XXPluginInfo xObj = rangerDaoManager.getXXPluginInfo().find(pluginInfo.getServiceName(), - pluginInfo.getHostName(), pluginInfo.getAppType()); - if (xObj != null) { - rangerDaoManager.getXXPluginInfo().remove(xObj.getId()); - } - } - - private String getRemoteAddress(final HttpServletRequest request) { - String ret = null; - - if (request != null) { - String xForwardedAddress = request.getHeader("X-Forwarded-For"); - if (StringUtils.isNotBlank(xForwardedAddress)) { - String[] forwardedAddresses = xForwardedAddress.split(","); - if (forwardedAddresses.length > 0) { - // Use first one. Hope it is the IP of the originating client - ret = forwardedAddresses[0].trim(); - } - } - if (ret == null) { - ret = request.getRemoteAddr(); - } - } - return ret; - } - - public VXTrxLogList getReportLogs(SearchCriteria searchCriteria) { - if (xaBizUtil.isAdmin() || xaBizUtil.isKeyAdmin() || xaBizUtil.isAuditAdmin() || xaBizUtil.isAuditKeyAdmin()) { - if (searchCriteria == null) { - searchCriteria = new SearchCriteria(); - } - - if (searchCriteria.getParamList() != null - && !searchCriteria.getParamList().isEmpty()) { - int clientTimeOffsetInMinute = RestUtil.getClientTimeOffset(); - Date temp = null; - DateUtil dateUtil = new DateUtil(); - if (searchCriteria.getParamList().containsKey("startDate")) { - temp = (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 = (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 = rangerDaoManager.getXXPortalUser().findByLoginId( - (searchCriteria.getParamList().get("owner").toString())); - if(xXPortalUser != null) { - searchCriteria.getParamList().put("owner", xXPortalUser.getId()); - } else { - searchCriteria.getParamList().put("owner", 0); - } - - } - } - - - - searchCriteria.setGetCount(true); - - PList vXTrxLogsV2 = xTrxLogService.searchTrxLogs(searchCriteria); - List vxTrxLogs = vXTrxLogsV2.getList().stream().map(VXTrxLogV2::toVXTrxLog).collect(Collectors.toList()); - VXTrxLogList ret = new VXTrxLogList(validateXXTrxLogList(vxTrxLogs)); - - ret.setStartIndex(vXTrxLogsV2.getStartIndex()); - ret.setPageSize(vXTrxLogsV2.getPageSize()); - ret.setTotalCount(vXTrxLogsV2.getTotalCount()); - ret.setResultSize(vXTrxLogsV2.getResultSize()); - ret.setSortBy(vXTrxLogsV2.getSortBy()); - ret.setSortType(vXTrxLogsV2.getSortType()); - - return ret; + } catch (InvalidNameException e) { + policyExportAudit.setHttpRetCode(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 (policyCount == null) { + policyCount = 0L; + } + + if (commonName != null) { + String config = xAsset.getConfig(); + Map configMap = jsonUtil.jsonToMap(config); + String cnFromConfig = configMap.get("commonNameForCertificate"); + + if (!commonName.equalsIgnoreCase(cnFromConfig)) { + policyExportAudit.setHttpRetCode(HttpServletResponse.SC_BAD_REQUEST); + + createPolicyAudit(policyExportAudit); + + throw restErrorUtil.createRESTException("Unauthorized access. expected [" + cnFromConfig + "], found [" + commonName + "]", MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY); + } + } + + long epochTime = epoch != null ? Long.parseLong(epoch) : 0; + + if (epochTime == updatedTime) { + int resourceListSz = xResourceList.size(); + + if (policyCount == resourceListSz) { + policyExportAudit.setHttpRetCode(HttpServletResponse.SC_NOT_MODIFIED); + + createPolicyAudit(policyExportAudit); + + throw restErrorUtil.createRESTException(HttpServletResponse.SC_NOT_MODIFIED, "No change since last update", false); + } + } + + List> resourceList = new ArrayList<>(); + + // HDFS Repository + if (xAsset.getAssetType() == AppConstants.ASSET_HDFS) { + for (VXResource xResource : xResourceList) { + HashMap resourceMap = new HashMap<>(); + + resourceMap.put("id", xResource.getId()); + resourceMap.put("resource", xResource.getName()); + resourceMap.put("isRecursive", getBooleanValue(xResource.getIsRecursive())); + resourceMap.put("policyStatus", RangerCommonEnums.getLabelFor_ActiveStatus(xResource.getResourceStatus())); + // resourceMap.put("isEncrypt", AKAConstants.getLabelFor_BooleanValue(xResource.getIsEncrypt())); + populatePermMap(xResource, resourceMap, AppConstants.ASSET_HDFS); + + List xAuditMaps = xResource.getAuditList(); + + if (!xAuditMaps.isEmpty()) { + resourceMap.put("audit", 1); + } else { + resourceMap.put("audit", 0); + } + + resourceList.add(resourceMap); + } + } else if (xAsset.getAssetType() == AppConstants.ASSET_HIVE) { + for (VXResource xResource : xResourceList) { + HashMap resourceMap = new HashMap<>(); + + resourceMap.put("id", xResource.getId()); + resourceMap.put("database_name", xResource.getDatabases()); + resourceMap.put("policyStatus", RangerCommonEnums.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 xAuditMaps = xResource.getAuditList(); + + if (!xAuditMaps.isEmpty()) { + resourceMap.put("audit", 1); } else { - throw restErrorUtil.create403RESTException("Permission Denied !"); - } - } + resourceMap.put("audit", 0); + } - public VXAccessAuditList getAccessLogs(SearchCriteria searchCriteria) { + resourceList.add(resourceMap); + } + } else if (xAsset.getAssetType() == AppConstants.ASSET_HBASE) { + for (VXResource xResource : xResourceList) { + HashMap resourceMap = new HashMap<>(); + + 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", RangerCommonEnums.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 xAuditMaps = xResource.getAuditList(); + + if (!xAuditMaps.isEmpty()) { + resourceMap.put("audit", 1); + } else { + resourceMap.put("audit", 0); + } + + resourceList.add(resourceMap); + } + } else if (xAsset.getAssetType() == AppConstants.ASSET_KNOX) { + for (VXResource xResource : xResourceList) { + HashMap resourceMap = new HashMap<>(); + + resourceMap.put("id", xResource.getId()); + resourceMap.put("topology_name", xResource.getTopologies()); + resourceMap.put("service_name", xResource.getServices()); + resourceMap.put("policyStatus", RangerCommonEnums.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 xAuditMaps = xResource.getAuditList(); + + if (!xAuditMaps.isEmpty()) { + resourceMap.put("audit", 1); + } else { + resourceMap.put("audit", 0); + } + + resourceList.add(resourceMap); + } + } else if (xAsset.getAssetType() == AppConstants.ASSET_STORM) { + for (VXResource xResource : xResourceList) { + HashMap resourceMap = new HashMap<>(); + + resourceMap.put("id", xResource.getId()); + resourceMap.put("topology_name", xResource.getTopologies()); + resourceMap.put("policyStatus", RangerCommonEnums.getLabelFor_ActiveStatus(xResource.getResourceStatus())); + + if (xResource.getIsEncrypt() == 1) { + resourceMap.put("encrypt", 1); + } else { + resourceMap.put("encrypt", 0); + } + + populatePermMap(xResource, resourceMap, AppConstants.ASSET_STORM); + + List xAuditMaps = xResource.getAuditList(); + + if (!xAuditMaps.isEmpty()) { + resourceMap.put("audit", 1); + } else { + resourceMap.put("audit", 0); + } + + resourceList.add(resourceMap); + } + } else { + policyExportAudit.setHttpRetCode(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) 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(HttpServletResponse.SC_OK); + + createPolicyAudit(policyExportAudit); + + return updatedPolicyStr; + } + + public void updateDefaultPolicyUserAndPerm(VXResource vXResource, String userName) { + if (userName != null && !userName.isEmpty()) { + XXUser xxUser = rangerDaoManager.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 xxPermMapList = rangerDaoManager.getXXPermMap().findByResourceId(vXResource.getId()); + VXPermMap vXPermMap = null; + + if (xxPermMapList != null && !xxPermMapList.isEmpty()) { + 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 void createPolicyAudit(final XXPolicyExportAudit xXPolicyExportAudit) { + final Runnable commitWork; + + if (xXPolicyExportAudit.getHttpRetCode() == HttpServletResponse.SC_NOT_MODIFIED) { + if (!rangerLogNotModified) { + logger.debug("Not logging HttpServletResponse. SC_NOT_MODIFIED. To enable, set configuration: {}=true", PROP_RANGER_LOG_SC_NOT_MODIFIED); + + commitWork = null; + } else { + // Create PolicyExportAudit record after transaction is completed. If it is created in-line here + // then the TransactionManager will roll-back the changes because the HTTP return code is + // HttpServletResponse.SC_NOT_MODIFIED + commitWork = () -> rangerDaoManager.getXXPolicyExportAudit().create(xXPolicyExportAudit); + } + } else { + commitWork = () -> rangerDaoManager.getXXPolicyExportAudit().create(xXPolicyExportAudit); + } + + if (commitWork != null) { + if (pluginActivityAuditCommitInline) { + transactionSynchronizationAdapter.executeOnTransactionCompletion(commitWork); + } else { + transactionSynchronizationAdapter.executeAsyncOnTransactionComplete(commitWork); + } + } + } + + public void createPluginInfo(String serviceName, String pluginId, HttpServletRequest request, int entityType, Long downloadedVersion, Long lastKnownVersion, long lastActivationTime, int httpCode, String clusterName, String pluginCapabilities) { + RangerRESTUtils restUtils = new RangerRESTUtils(); + final String ipAddress = getRemoteAddress(request); + final String appType = restUtils.getAppIdFromPluginId(pluginId); + String tmpHostName = null; + + if (StringUtils.isNotBlank(pluginId)) { + tmpHostName = restUtils.getHostnameFromPluginId(pluginId, serviceName); + } + + if (StringUtils.isBlank(tmpHostName) && request != null) { + tmpHostName = request.getRemoteHost(); + } + + final String hostName = (StringUtils.isBlank(tmpHostName)) ? ipAddress : tmpHostName; + + RangerPluginInfo pluginSvcVersionInfo = new RangerPluginInfo(); + + pluginSvcVersionInfo.setServiceName(serviceName); + pluginSvcVersionInfo.setAppType(appType); + pluginSvcVersionInfo.setHostName(hostName); + pluginSvcVersionInfo.setIpAddress(ipAddress); + pluginSvcVersionInfo.setPluginCapabilities(StringUtils.isEmpty(pluginCapabilities) ? RangerPluginCapability.getBaseRangerCapabilities() : pluginCapabilities); + + switch (entityType) { + case RangerPluginInfo.ENTITY_TYPE_POLICIES: + pluginSvcVersionInfo.setPolicyActiveVersion(lastKnownVersion); + pluginSvcVersionInfo.setPolicyActivationTime(lastActivationTime); + pluginSvcVersionInfo.setPolicyDownloadedVersion(downloadedVersion); + pluginSvcVersionInfo.setPolicyDownloadTime(new Date().getTime()); + break; + case RangerPluginInfo.ENTITY_TYPE_TAGS: + pluginSvcVersionInfo.setTagActiveVersion(lastKnownVersion); + pluginSvcVersionInfo.setTagActivationTime(lastActivationTime); + pluginSvcVersionInfo.setTagDownloadedVersion(downloadedVersion); + pluginSvcVersionInfo.setTagDownloadTime(new Date().getTime()); + break; + case RangerPluginInfo.ENTITY_TYPE_ROLES: + pluginSvcVersionInfo.setRoleActiveVersion(lastKnownVersion); + pluginSvcVersionInfo.setRoleActivationTime(lastActivationTime); + pluginSvcVersionInfo.setRoleDownloadedVersion(downloadedVersion); + pluginSvcVersionInfo.setRoleDownloadTime(new Date().getTime()); + break; + case RangerPluginInfo.ENTITY_TYPE_USERSTORE: + pluginSvcVersionInfo.setUserStoreActiveVersion(lastKnownVersion); + pluginSvcVersionInfo.setUserStoreActivationTime(lastActivationTime); + pluginSvcVersionInfo.setUserStoreDownloadedVersion(downloadedVersion); + pluginSvcVersionInfo.setUserStoreDownloadTime(new Date().getTime()); + break; + case RangerPluginInfo.ENTITY_TYPE_GDS: + pluginSvcVersionInfo.setGdsActiveVersion(lastKnownVersion); + pluginSvcVersionInfo.setGdsActivationTime(lastActivationTime); + pluginSvcVersionInfo.setGdsDownloadedVersion(downloadedVersion); + pluginSvcVersionInfo.setGdsDownloadTime(new Date().getTime()); + break; + } + + createOrUpdatePluginInfo(pluginSvcVersionInfo, entityType, httpCode, clusterName); + } + + public VXTrxLogList getReportLogs(SearchCriteria searchCriteria) { + if (xaBizUtil.isAdmin() || xaBizUtil.isKeyAdmin() || xaBizUtil.isAuditAdmin() || xaBizUtil.isAuditKeyAdmin()) { + if (searchCriteria == null) { + searchCriteria = new SearchCriteria(); + } + + if (searchCriteria.getParamList() != null && !searchCriteria.getParamList().isEmpty()) { + int clientTimeOffsetInMinute = RestUtil.getClientTimeOffset(); + DateUtil dateUtil = new DateUtil(); + + if (searchCriteria.getParamList().containsKey("startDate")) { + Date temp = (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")) { + Date temp = (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 = rangerDaoManager.getXXPortalUser().findByLoginId((searchCriteria.getParamList().get("owner").toString())); + + if (xXPortalUser != null) { + searchCriteria.getParamList().put("owner", xXPortalUser.getId()); + } else { + searchCriteria.getParamList().put("owner", 0); + } + } + } + + searchCriteria.setGetCount(true); + + PList vXTrxLogsV2 = xTrxLogService.searchTrxLogs(searchCriteria); + List vxTrxLogs = vXTrxLogsV2.getList().stream().map(VXTrxLogV2::toVXTrxLog).collect(Collectors.toList()); + VXTrxLogList ret = new VXTrxLogList(validateXXTrxLogList(vxTrxLogs)); + + ret.setStartIndex(vXTrxLogsV2.getStartIndex()); + ret.setPageSize(vXTrxLogsV2.getPageSize()); + ret.setTotalCount(vXTrxLogsV2.getTotalCount()); + ret.setResultSize(vXTrxLogsV2.getResultSize()); + ret.setSortBy(vXTrxLogsV2.getSortBy()); + ret.setSortType(vXTrxLogsV2.getSortType()); + + return ret; + } else { + throw restErrorUtil.create403RESTException("Permission Denied !"); + } + } + + public VXAccessAuditList getAccessLogs(SearchCriteria searchCriteria) { if (searchCriteria == null) { searchCriteria = new SearchCriteria(); } - if (searchCriteria.getParamList() != null - && !searchCriteria.getParamList().isEmpty()) { - int clientTimeOffsetInMinute = RestUtil.getClientTimeOffset(); - Date temp = null; - DateUtil dateUtil = new DateUtil(); + + if (searchCriteria.getParamList() != null && !searchCriteria.getParamList().isEmpty()) { + int clientTimeOffsetInMinute = RestUtil.getClientTimeOffset(); + DateUtil dateUtil = new DateUtil(); + if (searchCriteria.getParamList().containsKey("startDate")) { - temp = (Date) searchCriteria.getParamList().get( - "startDate"); + Date temp = (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 = (Date) searchCriteria.getParamList().get( - "endDate"); + Date temp = (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 (!"asc".equalsIgnoreCase(searchCriteria.getSortType()) && !"desc".equalsIgnoreCase(searchCriteria.getSortType())) { @@ -1139,33 +698,32 @@ public VXAccessAuditList getAccessLogs(SearchCriteria searchCriteria) { } if (!xaBizUtil.isAdmin()) { - Long userId = xaBizUtil.getXUserId(); - List userZones = rangerDaoManager.getXXSecurityZoneDao().findZoneNamesByUserId(userId); - Set zoneNameSet = new HashSet(userZones); - - VXGroupList groupList = xUserMgr.getXUserGroups(userId); - for (VXGroup group : groupList.getList()) { - List userGroupZones = rangerDaoManager.getXXSecurityZoneDao().findZoneNamesByGroupId(group.getId()); - for (String zoneName : userGroupZones) { - zoneNameSet.add(zoneName); - } - } - - List zoneNameList = (List) searchCriteria.getParamValue("zoneName"); - - if ((zoneNameList == null || zoneNameList.isEmpty())) { - if (!zoneNameSet.isEmpty()) { - searchCriteria.getParamList().put("zoneName", new ArrayList(zoneNameSet)); - } else { - searchCriteria.getParamList().put("zoneName", null); - } - } else if (!zoneNameList.isEmpty() && !zoneNameSet.isEmpty()) { - for (String znName : zoneNameList) { - if (!serviceMgr.isZoneAdmin(znName) && !serviceMgr.isZoneAuditor(znName)) { - throw restErrorUtil.createRESTException(HttpServletResponse.SC_FORBIDDEN, "User is not the zone admin or zone auditor of zone " + znName, true); - } - } - } + Long userId = xaBizUtil.getXUserId(); + List userZones = rangerDaoManager.getXXSecurityZoneDao().findZoneNamesByUserId(userId); + Set zoneNameSet = new HashSet<>(userZones); + VXGroupList groupList = xUserMgr.getXUserGroups(userId); + + for (VXGroup group : groupList.getList()) { + List userGroupZones = rangerDaoManager.getXXSecurityZoneDao().findZoneNamesByGroupId(group.getId()); + + zoneNameSet.addAll(userGroupZones); + } + + List zoneNameList = (List) searchCriteria.getParamValue("zoneName"); + + if ((zoneNameList == null || zoneNameList.isEmpty())) { + if (!zoneNameSet.isEmpty()) { + searchCriteria.getParamList().put("zoneName", new ArrayList<>(zoneNameSet)); + } else { + searchCriteria.getParamList().put("zoneName", null); + } + } else if (!zoneNameSet.isEmpty()) { + for (String znName : zoneNameList) { + if (!serviceMgr.isZoneAdmin(znName) && !serviceMgr.isZoneAuditor(znName)) { + throw restErrorUtil.createRESTException(HttpServletResponse.SC_FORBIDDEN, "User is not the zone admin or zone auditor of zone " + znName, true); + } + } + } } if (RangerBizUtil.AUDIT_STORE_SOLR.equalsIgnoreCase(xaBizUtil.getAuditDBType())) { @@ -1179,199 +737,670 @@ public VXAccessAuditList getAccessLogs(SearchCriteria searchCriteria) { } } - public VXTrxLogList getTransactionReport(String transactionId) { - List trxLogsV2 = xTrxLogService.findByTransactionId(transactionId); - List trxLogs = new ArrayList<>(); - long nextLogId = 1; - - for (VXTrxLogV2 trxLogV2 : trxLogsV2) { - ObjectChangeInfo objChangeInfo = trxLogV2.getChangeInfo(); - - if (objChangeInfo == null || CollectionUtils.isEmpty(objChangeInfo.getAttributes())) { - VXTrxLog trxLog = VXTrxLogV2.toVXTrxLog(trxLogV2); - - trxLog.setId(nextLogId++); - - trxLogs.add(trxLog); - } else { - for (AttributeChangeInfo attrChangeInfo : objChangeInfo.getAttributes()) { - VXTrxLog trxLog = VXTrxLogV2.toVXTrxLog(trxLogV2); - - trxLog.setId(nextLogId++); - trxLog.setAttributeName(attrChangeInfo.getAttributeName()); - trxLog.setPreviousValue(attrChangeInfo.getOldValue()); - trxLog.setNewValue(attrChangeInfo.getNewValue()); - - trxLogs.add(trxLog); - } - } - } - - return new VXTrxLogList(validateXXTrxLogList(trxLogs)); - } - - public List validateXXTrxLogList(List xTrxLogList) { - List vXTrxLogs = new ArrayList(); - - for (VXTrxLog vXTrxLog : xTrxLogList) { - if(vXTrxLog.getPreviousValue() == null || "null".equalsIgnoreCase(vXTrxLog.getPreviousValue())) { - vXTrxLog.setPreviousValue(""); - } - if(vXTrxLog.getNewValue() == null || "null".equalsIgnoreCase(vXTrxLog.getNewValue())) { - vXTrxLog.setNewValue(""); - } - if(vXTrxLog.getAttributeName() != null && "Password".equalsIgnoreCase(vXTrxLog.getAttributeName())) { - vXTrxLog.setPreviousValue("*********"); - vXTrxLog.setNewValue("***********"); - } - if(vXTrxLog.getAttributeName() != null && "Connection Configurations".equalsIgnoreCase(vXTrxLog.getAttributeName())) { - if(vXTrxLog.getPreviousValue() != null && vXTrxLog.getPreviousValue().contains("password")) { - String tempPreviousStr = vXTrxLog.getPreviousValue(); - String tempPreviousArr[] = vXTrxLog.getPreviousValue().split(","); - for (String tempPrevious : tempPreviousArr) { - if(tempPrevious.contains("{\"password") && tempPrevious.contains("}")) { - vXTrxLog.setPreviousValue(tempPreviousStr.replace(tempPrevious,"{\"password\":\"*****\"}")); - break; - } else if(tempPrevious.contains("{\"password")) { - vXTrxLog.setPreviousValue(tempPreviousStr.replace(tempPrevious, "{\"password\":\"*****\"")); - break; - } else if(tempPrevious.contains("\"password") && tempPrevious.contains("}")) { - vXTrxLog.setPreviousValue(tempPreviousStr.replace(tempPrevious, "\"password\":\"******\"}")); - break; - } else if(tempPrevious.contains("\"password")) { - vXTrxLog.setPreviousValue(tempPreviousStr.replace(tempPrevious, "\"password\":\"******\"")); - break; - } - } - } - if(vXTrxLog.getNewValue() != null && vXTrxLog.getNewValue().contains("password")) { - String tempNewStr = vXTrxLog.getNewValue(); - String tempNewArr[] = vXTrxLog.getNewValue().split(","); - for (String tempNew : tempNewArr) { - if(tempNew.contains("{\"password") && tempNew.contains("}")) { - vXTrxLog.setNewValue(tempNewStr.replace(tempNew, "{\"password\":\"*****\"}")); - break; - } else if(tempNew.contains("{\"password")) { - vXTrxLog.setNewValue(tempNewStr.replace(tempNew, "{\"password\":\"*****\"")); - break; - } else if(tempNew.contains("\"password") && tempNew.contains("}")) { - vXTrxLog.setNewValue(tempNewStr.replace(tempNew, "\"password\":\"******\"}")); - break; - } else if(tempNew.contains("\"password")) { - vXTrxLog.setNewValue(tempNewStr.replace(tempNew, "\"password\":\"******\"")); - break; - } - } - } - } - - vXTrxLogs.add(vXTrxLog); - } - return vXTrxLogs; - } - /* - * (non-Javadoc) - * - * @see - * org.apache.ranger.biz.AssetMgrBase#searchXPolicyExportAudits(org.apache.ranger. - * common.SearchCriteria) - */ - @Override - public VXPolicyExportAuditList searchXPolicyExportAudits( - SearchCriteria searchCriteria) { - - if (searchCriteria == null) { - searchCriteria = new SearchCriteria(); - } - - if (searchCriteria.getParamList() != null - && !searchCriteria.getParamList().isEmpty()) { - - int clientTimeOffsetInMinute = RestUtil.getClientTimeOffset(); - Date temp = null; - DateUtil dateUtil = new DateUtil(); + public VXTrxLogList getTransactionReport(String transactionId) { + List trxLogsV2 = xTrxLogService.findByTransactionId(transactionId); + List trxLogs = new ArrayList<>(); + long nextLogId = 1; + + for (VXTrxLogV2 trxLogV2 : trxLogsV2) { + ObjectChangeInfo objChangeInfo = trxLogV2.getChangeInfo(); + + if (objChangeInfo == null || CollectionUtils.isEmpty(objChangeInfo.getAttributes())) { + VXTrxLog trxLog = VXTrxLogV2.toVXTrxLog(trxLogV2); + + trxLog.setId(nextLogId++); + + trxLogs.add(trxLog); + } else { + for (AttributeChangeInfo attrChangeInfo : objChangeInfo.getAttributes()) { + VXTrxLog trxLog = VXTrxLogV2.toVXTrxLog(trxLogV2); + + trxLog.setId(nextLogId++); + trxLog.setAttributeName(attrChangeInfo.getAttributeName()); + trxLog.setPreviousValue(attrChangeInfo.getOldValue()); + trxLog.setNewValue(attrChangeInfo.getNewValue()); + + trxLogs.add(trxLog); + } + } + } + + return new VXTrxLogList(validateXXTrxLogList(trxLogs)); + } + + public List validateXXTrxLogList(List xTrxLogList) { + List vXTrxLogs = new ArrayList<>(); + + for (VXTrxLog vXTrxLog : xTrxLogList) { + if (vXTrxLog.getPreviousValue() == null || "null".equalsIgnoreCase(vXTrxLog.getPreviousValue())) { + vXTrxLog.setPreviousValue(""); + } + + if (vXTrxLog.getNewValue() == null || "null".equalsIgnoreCase(vXTrxLog.getNewValue())) { + vXTrxLog.setNewValue(""); + } + + if (vXTrxLog.getAttributeName() != null && "Password".equalsIgnoreCase(vXTrxLog.getAttributeName())) { + vXTrxLog.setPreviousValue("*********"); + vXTrxLog.setNewValue("***********"); + } + + if (vXTrxLog.getAttributeName() != null && "Connection Configurations".equalsIgnoreCase(vXTrxLog.getAttributeName())) { + if (vXTrxLog.getPreviousValue() != null && vXTrxLog.getPreviousValue().contains("password")) { + String tempPreviousStr = vXTrxLog.getPreviousValue(); + String[] tempPreviousArr = vXTrxLog.getPreviousValue().split(","); + + for (String tempPrevious : tempPreviousArr) { + if (tempPrevious.contains("{\"password") && tempPrevious.contains("}")) { + vXTrxLog.setPreviousValue(tempPreviousStr.replace(tempPrevious, "{\"password\":\"*****\"}")); + break; + } else if (tempPrevious.contains("{\"password")) { + vXTrxLog.setPreviousValue(tempPreviousStr.replace(tempPrevious, "{\"password\":\"*****\"")); + break; + } else if (tempPrevious.contains("\"password") && tempPrevious.contains("}")) { + vXTrxLog.setPreviousValue(tempPreviousStr.replace(tempPrevious, "\"password\":\"******\"}")); + break; + } else if (tempPrevious.contains("\"password")) { + vXTrxLog.setPreviousValue(tempPreviousStr.replace(tempPrevious, "\"password\":\"******\"")); + break; + } + } + } + + if (vXTrxLog.getNewValue() != null && vXTrxLog.getNewValue().contains("password")) { + String tempNewStr = vXTrxLog.getNewValue(); + String[] tempNewArr = vXTrxLog.getNewValue().split(","); + + for (String tempNew : tempNewArr) { + if (tempNew.contains("{\"password") && tempNew.contains("}")) { + vXTrxLog.setNewValue(tempNewStr.replace(tempNew, "{\"password\":\"*****\"}")); + break; + } else if (tempNew.contains("{\"password")) { + vXTrxLog.setNewValue(tempNewStr.replace(tempNew, "{\"password\":\"*****\"")); + break; + } else if (tempNew.contains("\"password") && tempNew.contains("}")) { + vXTrxLog.setNewValue(tempNewStr.replace(tempNew, "\"password\":\"******\"}")); + break; + } else if (tempNew.contains("\"password")) { + vXTrxLog.setNewValue(tempNewStr.replace(tempNew, "\"password\":\"******\"")); + break; + } + } + } + } + + vXTrxLogs.add(vXTrxLog); + } + + return vXTrxLogs; + } + + /* + * (non-Javadoc) + * + * @see + * org.apache.ranger.biz.AssetMgrBase#searchXPolicyExportAudits(org.apache.ranger. + * common.SearchCriteria) + */ + @Override + public VXPolicyExportAuditList searchXPolicyExportAudits(SearchCriteria searchCriteria) { + if (searchCriteria == null) { + searchCriteria = new SearchCriteria(); + } + + if (searchCriteria.getParamList() != null && !searchCriteria.getParamList().isEmpty()) { + int clientTimeOffsetInMinute = RestUtil.getClientTimeOffset(); + DateUtil dateUtil = new DateUtil(); + if (searchCriteria.getParamList().containsKey("startDate")) { - temp = (Date) searchCriteria.getParamList().get( - "startDate"); + Date temp = (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 = (Date) searchCriteria.getParamList().get( - "endDate"); + Date temp = (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 VXUgsyncAuditInfoList getUgsyncAudits(SearchCriteria searchCriteria) { - if (!msBizUtil.hasModuleAccess(RangerConstants.MODULE_AUDIT)) { - throw restErrorUtil.createRESTException(HttpServletResponse.SC_FORBIDDEN, "User is not having permissions on the "+RangerConstants.MODULE_AUDIT+" module.", true); - } - if (searchCriteria == null) { - searchCriteria = new SearchCriteria(); - } - if (searchCriteria.getParamList() != null - && !searchCriteria.getParamList().isEmpty()) { - int clientTimeOffsetInMinute = RestUtil.getClientTimeOffset(); - Date temp = null; - DateUtil dateUtil = new DateUtil(); - if (searchCriteria.getParamList().containsKey("startDate")) { - temp = (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 = (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 (!"asc".equalsIgnoreCase(searchCriteria.getSortType()) && !"desc".equalsIgnoreCase(searchCriteria.getSortType())) { - searchCriteria.setSortType("desc"); - } - return xUgsyncAuditInfoService.searchXUgsyncAuditInfoList(searchCriteria); - } - - public VXUgsyncAuditInfoList getUgsyncAuditsBySyncSource(String syncSource) { - if (!msBizUtil.hasModuleAccess(RangerConstants.MODULE_AUDIT)) { - throw restErrorUtil.createRESTException(HttpServletResponse.SC_FORBIDDEN, "User is not having permissions on the "+RangerConstants.MODULE_AUDIT+" module.", true); - } - if(syncSource!=null && !syncSource.trim().isEmpty()){ - return xUgsyncAuditInfoService.searchXUgsyncAuditInfoBySyncSource(syncSource); - }else{ - throw restErrorUtil.createRESTException("Please provide a valid syncSource", MessageEnums.INVALID_INPUT_DATA); - } - } - - private boolean isPolicyDownloadRequest(int entityType) { - return entityType == RangerPluginInfo.ENTITY_TYPE_POLICIES; - } - - private boolean isTagDownloadRequest(int entityType) { - return entityType == RangerPluginInfo.ENTITY_TYPE_TAGS; - } - - private boolean isRoleDownloadRequest(int entityType) { - return entityType == RangerPluginInfo.ENTITY_TYPE_ROLES; - } - - private boolean isUserStoreDownloadRequest(int entityType) { - return entityType == RangerPluginInfo.ENTITY_TYPE_USERSTORE; - } - - private boolean isGdsDownloadRequest(int entityType) { - return entityType == RangerPluginInfo.ENTITY_TYPE_GDS; - } + public VXUgsyncAuditInfoList getUgsyncAudits(SearchCriteria searchCriteria) { + if (!msBizUtil.hasModuleAccess(RangerConstants.MODULE_AUDIT)) { + throw restErrorUtil.createRESTException(HttpServletResponse.SC_FORBIDDEN, "User is not having permissions on the " + RangerConstants.MODULE_AUDIT + " module.", true); + } + + if (searchCriteria == null) { + searchCriteria = new SearchCriteria(); + } + + if (searchCriteria.getParamList() != null && !searchCriteria.getParamList().isEmpty()) { + int clientTimeOffsetInMinute = RestUtil.getClientTimeOffset(); + DateUtil dateUtil = new DateUtil(); + if (searchCriteria.getParamList().containsKey("startDate")) { + Date temp = (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")) { + Date temp = (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 (!"asc".equalsIgnoreCase(searchCriteria.getSortType()) && !"desc".equalsIgnoreCase(searchCriteria.getSortType())) { + searchCriteria.setSortType("desc"); + } + + return xUgsyncAuditInfoService.searchXUgsyncAuditInfoList(searchCriteria); + } + + public VXUgsyncAuditInfoList getUgsyncAuditsBySyncSource(String syncSource) { + if (!msBizUtil.hasModuleAccess(RangerConstants.MODULE_AUDIT)) { + throw restErrorUtil.createRESTException(HttpServletResponse.SC_FORBIDDEN, "User is not having permissions on the " + RangerConstants.MODULE_AUDIT + " module.", true); + } + + if (syncSource != null && !syncSource.trim().isEmpty()) { + return xUgsyncAuditInfoService.searchXUgsyncAuditInfoBySyncSource(syncSource); + } else { + throw restErrorUtil.createRESTException("Please provide a valid syncSource", MessageEnums.INVALID_INPUT_DATA); + } + } + + @SuppressWarnings("unchecked") + private HashMap populatePermMap(VXResource xResource, HashMap resourceMap, int assetType) { + List xPermMapList = xResource.getPermMapList(); + Set groupList = new HashSet<>(); + + for (VXPermMap xPermMap : xPermMapList) { + groupList.add(xPermMap.getId()); + } + + List> sortedPermMapGroupList = new ArrayList<>(); + + // Loop for adding group perms + for (VXPermMap xPermMap : xPermMapList) { + String groupKey = xPermMap.getPermGroup(); + + if (groupKey != null) { + boolean found = false; + + for (HashMap sortedPermMap : sortedPermMapGroupList) { + if (sortedPermMap.containsValue(groupKey)) { + found = true; + + Long groupId = xPermMap.getGroupId(); + Long userId = xPermMap.getUserId(); + + if (groupId != null) { + Set groups = (Set) sortedPermMap.get("groups"); + + if (groups != null) { + groups.add(xPermMap.getGroupName()); + + sortedPermMap.put("groups", groups); + } + } else if (userId != null) { + Set users = (Set) sortedPermMap.get("users"); + + if (users != null) { + users.add(xPermMap.getUserName()); + + sortedPermMap.put("users", users); + } + } + + Set access = (Set) sortedPermMap.get("access"); + String perm = AppConstants.getLabelFor_XAPermType(xPermMap.getPermType()); + + access.add(perm); + + sortedPermMap.put("access", access); + } + } + if (!found) { + HashMap sortedPermMap = new HashMap<>(); + + sortedPermMap.put("groupKey", xPermMap.getPermGroup()); + + Set permSet = new HashSet<>(); + 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 groupSet = new HashSet<>(); + String group = xPermMap.getGroupName(); + + groupSet.add(group); + + sortedPermMap.put("groups", groupSet); + } else if (userId != null) { + Set userSet = new HashSet<>(); + String user = xPermMap.getUserName(); + + userSet.add(user); + + sortedPermMap.put("users", userSet); + } + + sortedPermMapGroupList.add(sortedPermMap); + } + } + } + + for (HashMap sortedPermMap : sortedPermMapGroupList) { + sortedPermMap.remove("groupKey"); + } + + for (HashMap 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 + } + + private void createOrUpdatePluginInfo(final RangerPluginInfo pluginInfo, int entityType, final int httpCode, String clusterName) { + logger.debug("==> createOrUpdatePluginInfo(pluginInfo = {}, isPolicyDownloadRequest = {}, httpCode = {})", pluginInfo, isPolicyDownloadRequest(entityType), httpCode); + + final boolean isTagVersionResetNeeded; + final Runnable commitWork; + + if (httpCode == HttpServletResponse.SC_NOT_MODIFIED) { + if (!pluginActivityAuditLogNotModified) { + logger.debug("Not logging HttpServletResponse. SC_NOT_MODIFIED. To enable, set configuration: {}=true", PROP_PLUGIN_ACTIVITY_AUDIT_NOT_MODIFIED); + + commitWork = null; + } else { + // Create or update PluginInfo record after transaction is completed. If it is created in-line here + // then the TransactionManager will roll-back the changes because the HTTP return code is + // HttpServletResponse.SC_NOT_MODIFIED + + switch (entityType) { + case RangerPluginInfo.ENTITY_TYPE_POLICIES: + isTagVersionResetNeeded = rangerDaoManager.getXXService().findAssociatedTagService(pluginInfo.getServiceName()) == null; + break; + case RangerPluginInfo.ENTITY_TYPE_TAGS: + case RangerPluginInfo.ENTITY_TYPE_ROLES: + case RangerPluginInfo.ENTITY_TYPE_USERSTORE: + case RangerPluginInfo.ENTITY_TYPE_GDS: + default: + isTagVersionResetNeeded = false; + break; + } + + commitWork = () -> doCreateOrUpdateXXPluginInfo(pluginInfo, entityType, isTagVersionResetNeeded, clusterName); + } + } else if (httpCode == HttpServletResponse.SC_NOT_FOUND) { + if ((isPolicyDownloadRequest(entityType) && (pluginInfo.getPolicyActiveVersion() == null || pluginInfo.getPolicyActiveVersion() == -1)) + || (isTagDownloadRequest(entityType) && (pluginInfo.getTagActiveVersion() == null || pluginInfo.getTagActiveVersion() == -1)) + || (isRoleDownloadRequest(entityType) && (pluginInfo.getRoleActiveVersion() == null || pluginInfo.getRoleActiveVersion() == -1)) + || (isUserStoreDownloadRequest(entityType) && (pluginInfo.getUserStoreActiveVersion() == null || pluginInfo.getUserStoreActiveVersion() == -1)) + || (isGdsDownloadRequest(entityType) && (pluginInfo.getGdsActiveVersion() == null || pluginInfo.getGdsActiveVersion() == -1))) { + commitWork = () -> doDeleteXXPluginInfo(pluginInfo); + } else { + commitWork = () -> doCreateOrUpdateXXPluginInfo(pluginInfo, entityType, false, clusterName); + } + } else { + isTagVersionResetNeeded = false; + + commitWork = () -> doCreateOrUpdateXXPluginInfo(pluginInfo, entityType, isTagVersionResetNeeded, clusterName); + } + + if (commitWork != null) { + if (pluginActivityAuditCommitInline) { + transactionSynchronizationAdapter.executeOnTransactionCompletion(commitWork); + } else { + transactionSynchronizationAdapter.executeAsyncOnTransactionComplete(commitWork); + } + } + + logger.debug("<== createOrUpdatePluginInfo(pluginInfo = {}, isPolicyDownloadRequest = {}, httpCode = {})", pluginInfo, isPolicyDownloadRequest(entityType), httpCode); + } + + private XXPluginInfo doCreateOrUpdateXXPluginInfo(RangerPluginInfo pluginInfo, int entityType, final boolean isTagVersionResetNeeded, String clusterName) { + XXPluginInfo ret = null; + + if (StringUtils.isNotBlank(pluginInfo.getServiceName())) { + XXPluginInfo xObj = rangerDaoManager.getXXPluginInfo().find(pluginInfo.getServiceName(), pluginInfo.getHostName(), pluginInfo.getAppType()); + + if (xObj == null) { + Map infoMap = pluginInfo.getInfo(); + + if (!stringUtil.isEmpty(clusterName) && infoMap != null) { + infoMap.put(SearchFilter.CLUSTER_NAME, clusterName); + + pluginInfo.setInfo(infoMap); + } + + // ranger-admin is restarted, plugin contains latest versions and no earlier record for this plug-in client + if (isPolicyDownloadRequest(entityType)) { + if (pluginInfo.getPolicyDownloadedVersion() != null && pluginInfo.getPolicyDownloadedVersion().equals(pluginInfo.getPolicyActiveVersion())) { + // This is our best guess of when policies may have been downloaded + pluginInfo.setPolicyDownloadTime(pluginInfo.getPolicyActivationTime()); + } + } else if (isTagDownloadRequest(entityType)) { + if (pluginInfo.getTagDownloadedVersion() != null && pluginInfo.getTagDownloadedVersion().equals(pluginInfo.getTagActiveVersion())) { + // This is our best guess of when tags may have been downloaded + pluginInfo.setTagDownloadTime(pluginInfo.getTagActivationTime()); + } + } else if (isRoleDownloadRequest(entityType)) { + if (pluginInfo.getRoleDownloadTime() != null && pluginInfo.getRoleDownloadedVersion().equals(pluginInfo.getRoleActiveVersion())) { + // This is our best guess of when role may have been downloaded + pluginInfo.setRoleDownloadTime(pluginInfo.getRoleActivationTime()); + } + } else if (isUserStoreDownloadRequest(entityType)) { + if (pluginInfo.getUserStoreDownloadTime() != null && pluginInfo.getUserStoreDownloadedVersion().equals(pluginInfo.getUserStoreActiveVersion())) { + // This is our best guess of when users and groups may have been downloaded + pluginInfo.setUserStoreDownloadTime(pluginInfo.getUserStoreActivationTime()); + } + } else if (isGdsDownloadRequest(entityType)) { + if (pluginInfo.getGdsDownloadTime() != null && pluginInfo.getGdsDownloadedVersion().equals(pluginInfo.getGdsActiveVersion())) { + // This is our best guess of when GDS info may have been downloaded + pluginInfo.setGdsDownloadTime(pluginInfo.getGdsActivationTime()); + } + } + + pluginInfo.setAdminCapabilities(adminCapabilities); + + xObj = pluginInfoService.populateDBObject(pluginInfo); + + logger.debug("Creating RangerPluginInfo record for service-version"); + + ret = rangerDaoManager.getXXPluginInfo().create(xObj); + } else { + boolean needsUpdating = false; + RangerPluginInfo dbObj = pluginInfoService.populateViewObject(xObj); + Map infoMap = dbObj.getInfo(); + + if (infoMap != null && !stringUtil.isEmpty(clusterName)) { + if (!stringUtil.isEmpty(infoMap.get(SearchFilter.CLUSTER_NAME)) && !stringUtil.equals(infoMap.get(SearchFilter.CLUSTER_NAME), clusterName)) { + infoMap.put(SearchFilter.CLUSTER_NAME, clusterName); + + needsUpdating = true; + } + } + + if (!dbObj.getIpAddress().equals(pluginInfo.getIpAddress())) { + dbObj.setIpAddress(pluginInfo.getIpAddress()); + + needsUpdating = true; + } + + if (isPolicyDownloadRequest(entityType)) { + if (dbObj.getPolicyDownloadedVersion() == null || !dbObj.getPolicyDownloadedVersion().equals(pluginInfo.getPolicyDownloadedVersion())) { + dbObj.setPolicyDownloadedVersion(pluginInfo.getPolicyDownloadedVersion()); + dbObj.setPolicyDownloadTime(pluginInfo.getPolicyDownloadTime()); + + needsUpdating = true; + } + + Long lastKnownPolicyVersion = pluginInfo.getPolicyActiveVersion(); + Long lastPolicyActivationTime = pluginInfo.getPolicyActivationTime(); + String lastPluginCapabilityVector = pluginInfo.getPluginCapabilities(); + + if (lastKnownPolicyVersion != null && lastKnownPolicyVersion == -1) { + // First download request after plug-in's policy-refresher starts + dbObj.setPolicyDownloadTime(pluginInfo.getPolicyDownloadTime()); + + needsUpdating = true; + } + + if (lastKnownPolicyVersion != null && lastKnownPolicyVersion > 0 && (dbObj.getPolicyActiveVersion() == null || !dbObj.getPolicyActiveVersion().equals(lastKnownPolicyVersion))) { + dbObj.setPolicyActiveVersion(lastKnownPolicyVersion); + + needsUpdating = true; + } + + if (lastPolicyActivationTime != null && lastPolicyActivationTime > 0 && (dbObj.getPolicyActivationTime() == null || !dbObj.getPolicyActivationTime().equals(lastPolicyActivationTime))) { + dbObj.setPolicyActivationTime(lastPolicyActivationTime); + + needsUpdating = true; + } + + if (lastPluginCapabilityVector != null && (dbObj.getPluginCapabilities() == null || !dbObj.getPluginCapabilities().equals(lastPluginCapabilityVector))) { + dbObj.setPluginCapabilities(lastPluginCapabilityVector); + + needsUpdating = true; + } + + if (dbObj.getAdminCapabilities() == null || !dbObj.getAdminCapabilities().equals(adminCapabilities)) { + dbObj.setAdminCapabilities(adminCapabilities); + + needsUpdating = true; + } + } else if (isTagDownloadRequest(entityType)) { + if (dbObj.getTagDownloadedVersion() == null || !dbObj.getTagDownloadedVersion().equals(pluginInfo.getTagDownloadedVersion())) { + // First download for tags after tag-service is associated with resource-service + dbObj.setTagDownloadedVersion(pluginInfo.getTagDownloadedVersion()); + dbObj.setTagDownloadTime(pluginInfo.getTagDownloadTime()); + + needsUpdating = true; + } + + Long lastKnownTagVersion = pluginInfo.getTagActiveVersion(); + Long lastTagActivationTime = pluginInfo.getTagActivationTime(); + + if (lastKnownTagVersion != null && lastKnownTagVersion == -1) { + // First download request after plug-in's tag-refresher restarts + dbObj.setTagDownloadTime(pluginInfo.getTagDownloadTime()); + + needsUpdating = true; + } + + if (lastKnownTagVersion != null && lastKnownTagVersion > 0 && (dbObj.getTagActiveVersion() == null || !dbObj.getTagActiveVersion().equals(lastKnownTagVersion))) { + dbObj.setTagActiveVersion(lastKnownTagVersion); + + needsUpdating = true; + } + + if (lastTagActivationTime != null && lastTagActivationTime > 0 && (dbObj.getTagActivationTime() == null || !dbObj.getTagActivationTime().equals(lastTagActivationTime))) { + dbObj.setTagActivationTime(lastTagActivationTime); + + needsUpdating = true; + } + } else if (isRoleDownloadRequest(entityType)) { + if (dbObj.getRoleDownloadedVersion() == null || !dbObj.getRoleDownloadedVersion().equals(pluginInfo.getRoleDownloadedVersion())) { + dbObj.setRoleDownloadedVersion(pluginInfo.getRoleDownloadedVersion()); + dbObj.setRoleDownloadTime(pluginInfo.getRoleDownloadTime()); + + needsUpdating = true; + } + + Long lastKnownRoleVersion = pluginInfo.getRoleActiveVersion(); + Long lastRoleActivationTime = pluginInfo.getRoleActivationTime(); + + if (lastKnownRoleVersion != null && lastKnownRoleVersion == -1) { + dbObj.setRoleDownloadTime(pluginInfo.getRoleDownloadTime()); + + needsUpdating = true; + } + + if (lastKnownRoleVersion != null && lastKnownRoleVersion > 0 && (dbObj.getRoleActiveVersion() == null || !dbObj.getRoleActiveVersion().equals(lastKnownRoleVersion))) { + dbObj.setRoleActiveVersion(lastKnownRoleVersion); + + needsUpdating = true; + } + + if (lastRoleActivationTime != null && lastRoleActivationTime > 0 && (dbObj.getRoleActivationTime() == null || !dbObj.getRoleActivationTime().equals(lastRoleActivationTime))) { + dbObj.setRoleActivationTime(lastRoleActivationTime); + + needsUpdating = true; + } + } else if (isUserStoreDownloadRequest(entityType)) { + if (dbObj.getUserStoreDownloadedVersion() == null || !dbObj.getUserStoreDownloadedVersion().equals(pluginInfo.getUserStoreDownloadedVersion())) { + dbObj.setUserStoreDownloadedVersion(pluginInfo.getUserStoreDownloadedVersion()); + dbObj.setUserStoreDownloadTime(pluginInfo.getUserStoreDownloadTime()); + + needsUpdating = true; + } + + Long lastKnownUserStoreVersion = pluginInfo.getUserStoreActiveVersion(); + Long lastUserStoreActivationTime = pluginInfo.getUserStoreActivationTime(); + + if (lastKnownUserStoreVersion != null && lastKnownUserStoreVersion == -1) { + dbObj.setUserStoreDownloadTime(pluginInfo.getUserStoreDownloadTime()); + + needsUpdating = true; + } + + if (lastKnownUserStoreVersion != null && lastKnownUserStoreVersion > 0 && (dbObj.getUserStoreActiveVersion() == null || !dbObj.getUserStoreActiveVersion().equals(lastKnownUserStoreVersion))) { + dbObj.setUserStoreActiveVersion(lastKnownUserStoreVersion); + + needsUpdating = true; + } + + if (lastUserStoreActivationTime != null && lastUserStoreActivationTime > 0 && (dbObj.getUserStoreActivationTime() == null || !dbObj.getUserStoreActivationTime().equals(lastUserStoreActivationTime))) { + dbObj.setUserStoreActivationTime(lastUserStoreActivationTime); + + needsUpdating = true; + } + } else if (isGdsDownloadRequest(entityType)) { + if (dbObj.getGdsDownloadedVersion() == null || !dbObj.getGdsDownloadedVersion().equals(pluginInfo.getGdsDownloadedVersion())) { + dbObj.setGdsDownloadedVersion(pluginInfo.getGdsDownloadedVersion()); + dbObj.setGdsDownloadTime(pluginInfo.getGdsDownloadTime()); + + needsUpdating = true; + } + + Long lastKnownGdsVersion = pluginInfo.getGdsActiveVersion(); + Long lastGdsActivationTime = pluginInfo.getGdsActivationTime(); + + if (lastKnownGdsVersion != null && lastKnownGdsVersion == -1) { + dbObj.setGdsDownloadTime(pluginInfo.getGdsDownloadTime()); + + needsUpdating = true; + } + + if (lastKnownGdsVersion != null && lastKnownGdsVersion > 0 && (dbObj.getGdsActiveVersion() == null || !dbObj.getGdsActiveVersion().equals(lastKnownGdsVersion))) { + dbObj.setGdsActiveVersion(lastKnownGdsVersion); + + needsUpdating = true; + } + + if (lastGdsActivationTime != null && lastGdsActivationTime > 0 && (dbObj.getGdsActivationTime() == null || !dbObj.getGdsActivationTime().equals(lastGdsActivationTime))) { + dbObj.setGdsActivationTime(lastGdsActivationTime); + + needsUpdating = true; + } + } + + if (isTagVersionResetNeeded) { + dbObj.setTagDownloadedVersion(null); + dbObj.setTagDownloadTime(null); + dbObj.setTagActiveVersion(null); + dbObj.setTagActivationTime(null); + + needsUpdating = true; + } + + if (needsUpdating) { + logger.debug("Updating XXPluginInfo record for service-version"); + + xObj = pluginInfoService.populateDBObject(dbObj); + + ret = rangerDaoManager.getXXPluginInfo().update(xObj); + } + } + } else { + logger.error("Invalid parameters: pluginInfo={})", pluginInfo); + } + + return ret; + } + + private void doDeleteXXPluginInfo(RangerPluginInfo pluginInfo) { + XXPluginInfo xObj = rangerDaoManager.getXXPluginInfo().find(pluginInfo.getServiceName(), pluginInfo.getHostName(), pluginInfo.getAppType()); + + if (xObj != null) { + rangerDaoManager.getXXPluginInfo().remove(xObj.getId()); + } + } + + private String getRemoteAddress(final HttpServletRequest request) { + String ret = null; + + if (request != null) { + String xForwardedAddress = request.getHeader("X-Forwarded-For"); + + if (StringUtils.isNotBlank(xForwardedAddress)) { + String[] forwardedAddresses = xForwardedAddress.split(","); + + if (forwardedAddresses.length > 0) { + // Use first one. Hope it is the IP of the originating client + ret = forwardedAddresses[0].trim(); + } + } + + if (ret == null) { + ret = request.getRemoteAddr(); + } + } + + return ret; + } + + private boolean isPolicyDownloadRequest(int entityType) { + return entityType == RangerPluginInfo.ENTITY_TYPE_POLICIES; + } + + private boolean isTagDownloadRequest(int entityType) { + return entityType == RangerPluginInfo.ENTITY_TYPE_TAGS; + } + + private boolean isRoleDownloadRequest(int entityType) { + return entityType == RangerPluginInfo.ENTITY_TYPE_ROLES; + } + + private boolean isUserStoreDownloadRequest(int entityType) { + return entityType == RangerPluginInfo.ENTITY_TYPE_USERSTORE; + } + + private boolean isGdsDownloadRequest(int entityType) { + return entityType == RangerPluginInfo.ENTITY_TYPE_GDS; + } } 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 index 840bb38214..50f6676908 100644 --- a/security-admin/src/main/java/org/apache/ranger/biz/AssetMgrBase.java +++ b/security-admin/src/main/java/org/apache/ranger/biz/AssetMgrBase.java @@ -17,7 +17,7 @@ * under the License. */ - package org.apache.ranger.biz; +package org.apache.ranger.biz; import org.apache.ranger.common.MessageEnums; import org.apache.ranger.common.RESTErrorUtil; @@ -33,83 +33,79 @@ import org.springframework.beans.factory.annotation.Autowired; public class AssetMgrBase { + @Autowired + RESTErrorUtil restErrorUtil; - @Autowired - RESTErrorUtil restErrorUtil; - - @Autowired - XResourceService xResourceService; - - @Autowired - XCredentialStoreService xCredentialStoreService; - - @Autowired - XPolicyExportAuditService xPolicyExportAuditService; - - 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); - } + @Autowired + XResourceService xResourceService; + @Autowired + XCredentialStoreService xCredentialStoreService; + + @Autowired + XPolicyExportAuditService xPolicyExportAuditService; + + public VXCredentialStore getXCredentialStore(Long id) { + return xCredentialStoreService.readResource(id); + } + + public VXCredentialStore createXCredentialStore(VXCredentialStore vXCredentialStore) { + vXCredentialStore = xCredentialStoreService.createResource(vXCredentialStore); + + return vXCredentialStore; + } + + public VXCredentialStore updateXCredentialStore(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 xPolicyExportAuditService.readResource(id); + } + + public VXPolicyExportAudit createXPolicyExportAudit(VXPolicyExportAudit vXPolicyExportAudit) { + vXPolicyExportAudit = xPolicyExportAuditService.createResource(vXPolicyExportAudit); + + return vXPolicyExportAudit; + } + + public VXPolicyExportAudit updateXPolicyExportAudit(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); + } } 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 index 5cc6436f92..369958c68d 100644 --- a/security-admin/src/main/java/org/apache/ranger/biz/BaseMgr.java +++ b/security-admin/src/main/java/org/apache/ranger/biz/BaseMgr.java @@ -17,7 +17,7 @@ * under the License. */ - /** +/** * */ package org.apache.ranger.biz; @@ -44,37 +44,31 @@ public abstract class BaseMgr { RESTErrorUtil restErrorUtil; public RangerDaoManager getDaoManager() { - return daoManager; + return daoManager; } - public void deleteEntity(BaseDao 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); - } + public void deleteEntity(BaseDao baseDao, Long id, String entityName) { + XXDBBase entity = baseDao.getById(id); + + if (entity != null) { + try { + baseDao.remove(id); + } catch (Exception e) { + logger.error("Error deleting {}. Id={}", entityName, 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 {} id={}", entityName, id); + } } /** * @param objectClassType */ protected void validateClassType(int objectClassType) { - // objectClassType - restErrorUtil.validateMinMax(objectClassType, 1, - RangerConstants.ClassTypes_MAX, "Invalid classType", null, - "objectClassType"); + // objectClassType + restErrorUtil.validateMinMax(objectClassType, 1, RangerConstants.ClassTypes_MAX, "Invalid classType", null, "objectClassType"); } - } diff --git a/security-admin/src/main/java/org/apache/ranger/biz/GdsDBStore.java b/security-admin/src/main/java/org/apache/ranger/biz/GdsDBStore.java index 11983a2727..7916f08188 100755 --- a/security-admin/src/main/java/org/apache/ranger/biz/GdsDBStore.java +++ b/security-admin/src/main/java/org/apache/ranger/biz/GdsDBStore.java @@ -19,15 +19,45 @@ package org.apache.ranger.biz; -import org.apache.http.HttpStatus; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.StringUtils; +import org.apache.http.HttpStatus; import org.apache.ranger.biz.ServiceDBStore.REMOVE_REF_TYPE; -import org.apache.ranger.common.*; +import org.apache.ranger.common.GUIDUtil; +import org.apache.ranger.common.MessageEnums; +import org.apache.ranger.common.RESTErrorUtil; +import org.apache.ranger.common.RangerConstants; +import org.apache.ranger.common.ServiceGdsInfoCache; import org.apache.ranger.common.db.RangerTransactionSynchronizationAdapter; -import org.apache.ranger.db.*; -import org.apache.ranger.entity.*; -import org.apache.ranger.plugin.model.RangerGds.*; +import org.apache.ranger.db.RangerDaoManager; +import org.apache.ranger.db.XXGdsDataShareDao; +import org.apache.ranger.db.XXGdsDataShareInDatasetDao; +import org.apache.ranger.db.XXGdsDatasetDao; +import org.apache.ranger.db.XXGdsDatasetInProjectDao; +import org.apache.ranger.db.XXGdsProjectDao; +import org.apache.ranger.db.XXServiceDao; +import org.apache.ranger.entity.XXGdsDataShare; +import org.apache.ranger.entity.XXGdsDataShareInDataset; +import org.apache.ranger.entity.XXGdsDataset; +import org.apache.ranger.entity.XXGdsDatasetInProject; +import org.apache.ranger.entity.XXGdsDatasetPolicyMap; +import org.apache.ranger.entity.XXGdsProject; +import org.apache.ranger.entity.XXGdsProjectPolicyMap; +import org.apache.ranger.entity.XXSecurityZone; +import org.apache.ranger.entity.XXService; +import org.apache.ranger.plugin.model.RangerGds.DataShareInDatasetSummary; +import org.apache.ranger.plugin.model.RangerGds.DataShareSummary; +import org.apache.ranger.plugin.model.RangerGds.DatasetSummary; +import org.apache.ranger.plugin.model.RangerGds.GdsPermission; +import org.apache.ranger.plugin.model.RangerGds.GdsShareStatus; +import org.apache.ranger.plugin.model.RangerGds.RangerDataShare; +import org.apache.ranger.plugin.model.RangerGds.RangerDataShareInDataset; +import org.apache.ranger.plugin.model.RangerGds.RangerDataset; +import org.apache.ranger.plugin.model.RangerGds.RangerDatasetInProject; +import org.apache.ranger.plugin.model.RangerGds.RangerGdsBaseModelObject; +import org.apache.ranger.plugin.model.RangerGds.RangerGdsObjectACL; +import org.apache.ranger.plugin.model.RangerGds.RangerProject; +import org.apache.ranger.plugin.model.RangerGds.RangerSharedResource; import org.apache.ranger.plugin.model.RangerPolicy; import org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyItem; import org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyResource; @@ -36,11 +66,23 @@ import org.apache.ranger.plugin.store.AbstractGdsStore; import org.apache.ranger.plugin.store.PList; import org.apache.ranger.plugin.store.ServiceStore; -import org.apache.ranger.plugin.util.*; -import org.apache.ranger.service.*; +import org.apache.ranger.plugin.util.SearchFilter; +import org.apache.ranger.plugin.util.ServiceGdsInfo; +import org.apache.ranger.service.RangerGdsDataShareInDatasetService; +import org.apache.ranger.service.RangerGdsDataShareService; +import org.apache.ranger.service.RangerGdsDatasetInProjectService; +import org.apache.ranger.service.RangerGdsDatasetService; +import org.apache.ranger.service.RangerGdsProjectService; +import org.apache.ranger.service.RangerGdsSharedResourceService; +import org.apache.ranger.service.RangerServiceService; import org.apache.ranger.validation.RangerGdsValidationDBProvider; import org.apache.ranger.validation.RangerGdsValidator; -import org.apache.ranger.view.RangerGdsVList.*; +import org.apache.ranger.view.RangerGdsVList.RangerDataShareInDatasetList; +import org.apache.ranger.view.RangerGdsVList.RangerDataShareList; +import org.apache.ranger.view.RangerGdsVList.RangerDatasetInProjectList; +import org.apache.ranger.view.RangerGdsVList.RangerDatasetList; +import org.apache.ranger.view.RangerGdsVList.RangerProjectList; +import org.apache.ranger.view.RangerGdsVList.RangerSharedResourceList; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -48,21 +90,30 @@ import javax.annotation.PostConstruct; -import java.util.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; import java.util.function.Function; import java.util.stream.Collectors; import static org.apache.ranger.db.XXGlobalStateDao.RANGER_GLOBAL_STATE_NAME_GDS; import static org.apache.ranger.plugin.store.EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_GDS_NAME; - @Component public class GdsDBStore extends AbstractGdsStore { private static final Logger LOG = LoggerFactory.getLogger(GdsDBStore.class); public static final String RESOURCE_NAME_DATASET_ID = "dataset-id"; public static final String RESOURCE_NAME_PROJECT_ID = "project-id"; - public static final String NOT_AUTHORIZED_FOR_DATASET_POLICIES = "User is not authorized to manage policies for this dataset"; public static final String NOT_AUTHORIZED_TO_VIEW_DATASET_POLICIES = "User is not authorized to view policies for this dataset"; public static final String NOT_AUTHORIZED_FOR_PROJECT_POLICIES = "User is not authorized to manage policies for this dataset"; @@ -121,13 +172,9 @@ public class GdsDBStore extends AbstractGdsStore { @PostConstruct public void initStore() { - if (LOG.isDebugEnabled()) { - LOG.debug("==> GdsInMemoryStore.initStore()"); - } + LOG.debug("==> GdsInMemoryStore.initStore()"); - if (LOG.isDebugEnabled()) { - LOG.debug("<== GdsInMemoryStore.initStore()"); - } + LOG.debug("<== GdsInMemoryStore.initStore()"); } @Override @@ -290,9 +337,9 @@ public PList getDatasetNames(SearchFilter filter) { public PList searchDatasets(SearchFilter filter) { LOG.debug("==> searchDatasets({})", filter); - if (filter.getParam(SearchFilter.CREATED_BY) != null) { - setUserId(filter, SearchFilter.CREATED_BY); - } + if (filter.getParam(SearchFilter.CREATED_BY) != null) { + setUserId(filter, SearchFilter.CREATED_BY); + } PList ret = getUnscrubbedDatasets(filter); GdsPermission gdsPermission = getGdsPermissionFromFilter(filter); @@ -308,135 +355,6 @@ public PList searchDatasets(SearchFilter filter) { return ret; } - @Override - public RangerPolicy addDatasetPolicy(Long datasetId, RangerPolicy policy) throws Exception { - LOG.debug("==> addDatasetPolicy({}, {})", datasetId, policy); - - RangerDataset dataset = datasetService.read(datasetId); - - if (!validator.hasPermission(dataset.getAcl(), GdsPermission.POLICY_ADMIN)) { - throw restErrorUtil.create403RESTException(NOT_AUTHORIZED_FOR_DATASET_POLICIES); - } - - prepareDatasetPolicy(dataset, policy); - - RangerPolicy ret = svcStore.createPolicy(policy); - - daoMgr.getXXGdsDatasetPolicyMap().create(new XXGdsDatasetPolicyMap(datasetId, ret.getId())); - - updateGdsVersionForDataset(datasetId); - - LOG.debug("<== addDatasetPolicy({}, {}): ret={}", datasetId, policy, ret); - - return ret; - } - - @Override - public RangerPolicy updateDatasetPolicy(Long datasetId, RangerPolicy policy) throws Exception { - LOG.debug("==> updateDatasetPolicy({}, {})", datasetId, policy); - - RangerDataset dataset = datasetService.read(datasetId); - - if (!validator.hasPermission(dataset.getAcl(), GdsPermission.POLICY_ADMIN)) { - throw restErrorUtil.create403RESTException(NOT_AUTHORIZED_FOR_DATASET_POLICIES); - } - - XXGdsDatasetPolicyMap existing = daoMgr.getXXGdsDatasetPolicyMap().getDatasetPolicyMap(datasetId, policy.getId()); - - if (existing == null) { - throw new Exception("no policy exists: datasetId=" + datasetId + ", policyId=" + policy.getId()); - } - - prepareDatasetPolicy(dataset, policy); - - RangerPolicy ret = svcStore.updatePolicy(policy); - - updateGdsVersionForDataset(datasetId); - - LOG.debug("<== updateDatasetPolicy({}, {}): ret={}", datasetId, policy, ret); - - return ret; - } - - @Override - public void deleteDatasetPolicy(Long datasetId, Long policyId) throws Exception { - LOG.debug("==> deleteDatasetPolicy({}, {})", datasetId, policyId); - - RangerDataset dataset = datasetService.read(datasetId); - - if (!validator.hasPermission(dataset.getAcl(), GdsPermission.POLICY_ADMIN)) { - throw restErrorUtil.create403RESTException(NOT_AUTHORIZED_FOR_DATASET_POLICIES); - } - - XXGdsDatasetPolicyMap existing = daoMgr.getXXGdsDatasetPolicyMap().getDatasetPolicyMap(datasetId, policyId); - - if (existing == null) { - throw new Exception("no policy exists: datasetId=" + datasetId + ", policyId=" + policyId); - } - - RangerPolicy policy = svcStore.getPolicy(policyId); - - daoMgr.getXXGdsDatasetPolicyMap().remove(existing); - svcStore.deletePolicy(policy); - - updateGdsVersionForDataset(datasetId); - - LOG.debug("<== deleteDatasetPolicy({}, {})", datasetId, policyId); - } - - @Override - public void deleteDatasetPolicies(Long datasetId) throws Exception { - LOG.debug("==> deleteDatasetPolicies({})", datasetId); - - RangerDataset dataset = datasetService.read(datasetId); - - deleteDatasetPolicies(dataset); - - updateGdsVersionForDataset(datasetId); - - LOG.debug("<== deleteDatasetPolicy({})", datasetId); - } - - @Override - public RangerPolicy getDatasetPolicy(Long datasetId, Long policyId) throws Exception { - LOG.debug("==> getDatasetPolicy({}, {})", datasetId, policyId); - - RangerDataset dataset = datasetService.read(datasetId); - - if (!validator.hasPermission(dataset.getAcl(), GdsPermission.AUDIT)) { - throw restErrorUtil.create403RESTException(NOT_AUTHORIZED_TO_VIEW_DATASET_POLICIES); - } - - XXGdsDatasetPolicyMap existing = daoMgr.getXXGdsDatasetPolicyMap().getDatasetPolicyMap(datasetId, policyId); - - if (existing == null) { - throw new Exception("no policy exists: datasetId=" + datasetId + ", policyId=" + policyId); - } - - RangerPolicy ret = svcStore.getPolicy(policyId); - - LOG.debug("<== getDatasetPolicy({}, {}): ret={}", datasetId, policyId, ret); - - return ret; - } - - @Override - public List getDatasetPolicies(Long datasetId) throws Exception { - LOG.debug("==> getDatasetPolicies({})", datasetId); - - RangerDataset dataset = datasetService.read(datasetId); - - if (!validator.hasPermission(dataset.getAcl(), GdsPermission.AUDIT)) { - throw restErrorUtil.create403RESTException(NOT_AUTHORIZED_TO_VIEW_DATASET_POLICIES); - } - - List ret = getPolicies(daoMgr.getXXGdsDatasetPolicyMap().getDatasetPolicyIds(datasetId)); - - LOG.debug("<== getDatasetPolicies({}): ret={}", datasetId, ret); - - return ret; - } - @Override public RangerProject createProject(RangerProject project) { LOG.debug("==> createProject({})", project); @@ -513,7 +431,7 @@ public void deleteProject(Long projectId, boolean forceDelete) throws Exception try { existing = projectService.read(projectId); - } catch(Exception excp) { + } catch (Exception excp) { // ignore } @@ -611,253 +529,123 @@ public PList searchProjects(SearchFilter filter) { } @Override - public RangerPolicy addProjectPolicy(Long projectId, RangerPolicy policy) throws Exception { - LOG.debug("==> addProjectPolicy({}, {})", projectId, policy); + public RangerDataShare createDataShare(RangerDataShare dataShare) { + LOG.debug("==> createDataShare({})", dataShare); - RangerProject project = projectService.read(projectId); + dataShare.setName(StringUtils.trim(dataShare.getName())); - if (!validator.hasPermission(project.getAcl(), GdsPermission.POLICY_ADMIN)) { - throw restErrorUtil.create403RESTException(NOT_AUTHORIZED_FOR_PROJECT_POLICIES); + validator.validateCreate(dataShare); + + if (StringUtils.isBlank(dataShare.getGuid())) { + dataShare.setGuid(guidUtil.genGUID()); } - prepareProjectPolicy(project, policy); + if (dataShare.getAcl() == null) { + dataShare.setAcl(new RangerGdsObjectACL()); + } - RangerPolicy ret = svcStore.createPolicy(policy); + addCreatorAsAclAdmin(dataShare.getAcl()); - daoMgr.getXXGdsProjectPolicyMap().create(new XXGdsProjectPolicyMap(projectId, ret.getId())); + RangerDataShare ret = dataShareService.create(dataShare); - updateGdsVersionForProject(project.getId()); + dataShareService.onObjectChange(ret, null, RangerServiceService.OPERATION_CREATE_CONTEXT); - LOG.debug("<== addProjectPolicy({}, {}): ret={}", projectId, policy, ret); + updateGdsVersion(); + + LOG.debug("<== createDataShare({}): ret={}", dataShare, ret); return ret; } @Override - public RangerPolicy updateProjectPolicy(Long projectId, RangerPolicy policy) throws Exception { - LOG.debug("==> updateProjectPolicy({}, {})", projectId, policy); + public RangerDataShare updateDataShare(RangerDataShare dataShare) { + LOG.debug("==> updateDataShare({})", dataShare); - RangerProject project = projectService.read(projectId); + RangerDataShare existing = null; - if (!validator.hasPermission(project.getAcl(), GdsPermission.POLICY_ADMIN)) { - throw restErrorUtil.create403RESTException(NOT_AUTHORIZED_FOR_PROJECT_POLICIES); + try { + existing = dataShareService.read(dataShare.getId()); + } catch (Exception excp) { + // ignore } - XXGdsProjectPolicyMap existing = daoMgr.getXXGdsProjectPolicyMap().getProjectPolicyMap(projectId, policy.getId()); + dataShare.setName(StringUtils.trim(dataShare.getName())); - if (existing == null) { - throw new Exception("no policy exists: projectId=" + projectId + ", policyId=" + policy.getId()); - } + validator.validateUpdate(dataShare, existing); - prepareProjectPolicy(project, policy); + copyExistingBaseFields(dataShare, existing); - RangerPolicy ret = svcStore.updatePolicy(policy); + RangerDataShare ret = dataShareService.update(dataShare); - updateGdsVersionForProject(project.getId()); + dataShareService.onObjectChange(ret, existing, RangerServiceService.OPERATION_UPDATE_CONTEXT); - LOG.debug("<== updateProjectPolicy({}, {}): ret={}", projectId, policy, ret); + updateGdsVersionForService(dataShare.getService()); + + LOG.debug("<== updateDataShare({}): ret={}", dataShare, ret); return ret; } @Override - public void deleteProjectPolicy(Long projectId, Long policyId) throws Exception { - LOG.debug("==> deleteProjectPolicy({}, {})", projectId, policyId); + public void deleteDataShare(Long dataShareId, boolean forceDelete) { + LOG.debug("==> deleteDataShare(dataShareId: {}, forceDelete: {})", dataShareId, forceDelete); - RangerProject project = projectService.read(projectId); + RangerDataShare existing = null; - if (!validator.hasPermission(project.getAcl(), GdsPermission.POLICY_ADMIN)) { - throw restErrorUtil.create403RESTException(NOT_AUTHORIZED_FOR_DATASET_POLICIES); + try { + existing = dataShareService.read(dataShareId); + } catch (Exception excp) { + // ignore } - XXGdsProjectPolicyMap existing = daoMgr.getXXGdsProjectPolicyMap().getProjectPolicyMap(projectId, policyId); + validator.validateDelete(dataShareId, existing); - if (existing == null) { - throw new Exception("no policy exists: projectId=" + projectId + ", policyId=" + policyId); - } + if (existing != null) { + if (forceDelete) { + removeDshInDsForDataShare(dataShareId); + removeSharedResourcesForDataShare(dataShareId); + } - RangerPolicy policy = svcStore.getPolicy(policyId); + dataShareService.delete(existing); - daoMgr.getXXGdsProjectPolicyMap().remove(existing); - svcStore.deletePolicy(policy); + dataShareService.onObjectChange(null, existing, RangerServiceService.OPERATION_DELETE_CONTEXT); - updateGdsVersionForProject(project.getId()); + updateGdsVersionForService(existing.getService()); + } - LOG.debug("<== deleteProjectPolicy({}, {})", projectId, policyId); + LOG.debug("<== deleteDataShare(dataShareId: {}, forceDelete: {})", dataShareId, forceDelete); } @Override - public void deleteProjectPolicies(Long projectId) throws Exception { - LOG.debug("==> deleteProjectPolicies({})", projectId); + public RangerDataShare getDataShare(Long dataShareId) throws Exception { + LOG.debug("==> getDataShare({})", dataShareId); - RangerProject project = projectService.read(projectId); + RangerDataShare ret = dataShareService.read(dataShareId); - deleteProjectPolicies(project); + if (ret != null && !validator.hasPermission(ret.getAcl(), GdsPermission.VIEW)) { + throw new Exception("no permission on dataShare id=" + dataShareId); + } - updateGdsVersionForProject(project.getId()); + LOG.debug("<== getDataShare({}): ret={}", dataShareId, ret); - LOG.debug("<== deleteProjectPolicy({})", projectId); + return ret; } @Override - public RangerPolicy getProjectPolicy(Long projectId, Long policyId) throws Exception { - LOG.debug("==> getProjectPolicy({}, {})", projectId, policyId); + public PList searchDataShares(SearchFilter filter) { + LOG.debug("==> searchDataShares({})", filter); - RangerProject project = projectService.read(projectId); + PList ret = getUnscrubbedDataShares(filter); + List dataShares = ret.getList(); + GdsPermission gdsPermission = getGdsPermissionFromFilter(filter); - if (!validator.hasPermission(project.getAcl(), GdsPermission.AUDIT)) { - throw restErrorUtil.create403RESTException(NOT_AUTHORIZED_TO_VIEW_PROJECT_POLICIES); + for (RangerDataShare dataShare : dataShares) { + if (gdsPermission.equals(GdsPermission.LIST)) { + scrubDataShareForListing(dataShare); + } } - XXGdsProjectPolicyMap existing = daoMgr.getXXGdsProjectPolicyMap().getProjectPolicyMap(projectId, policyId); - - if (existing == null) { - throw new Exception("no policy exists: projectId=" + projectId + ", policyId=" + policyId); - } - - RangerPolicy ret = svcStore.getPolicy(policyId); - - LOG.debug("<== getProjectPolicy({}, {}): ret={}", projectId, policyId, ret); - - return ret; - } - - @Override - public List getProjectPolicies(Long projectId) throws Exception { - LOG.debug("==> getProjectPolicies({})", projectId); - - RangerProject project = projectService.read(projectId); - - if (!validator.hasPermission(project.getAcl(), GdsPermission.AUDIT)) { - throw restErrorUtil.create403RESTException(NOT_AUTHORIZED_TO_VIEW_PROJECT_POLICIES); - } - - List ret = getPolicies(daoMgr.getXXGdsProjectPolicyMap().getProjectPolicyIds(projectId)); - - LOG.debug("<== getProjectPolicies({}): ret={}", projectId, ret); - - return ret; - } - - - @Override - public RangerDataShare createDataShare(RangerDataShare dataShare) { - LOG.debug("==> createDataShare({})", dataShare); - - dataShare.setName(StringUtils.trim(dataShare.getName())); - - validator.validateCreate(dataShare); - - if (StringUtils.isBlank(dataShare.getGuid())) { - dataShare.setGuid(guidUtil.genGUID()); - } - - if (dataShare.getAcl() == null) { - dataShare.setAcl(new RangerGdsObjectACL()); - } - - addCreatorAsAclAdmin(dataShare.getAcl()); - - RangerDataShare ret = dataShareService.create(dataShare); - - dataShareService.onObjectChange(ret, null, RangerServiceService.OPERATION_CREATE_CONTEXT); - - updateGdsVersion(); - - LOG.debug("<== createDataShare({}): ret={}", dataShare, ret); - - return ret; - } - - @Override - public RangerDataShare updateDataShare(RangerDataShare dataShare) { - LOG.debug("==> updateDataShare({})", dataShare); - - RangerDataShare existing = null; - - try { - existing = dataShareService.read(dataShare.getId()); - } catch (Exception excp) { - // ignore - } - - dataShare.setName(StringUtils.trim(dataShare.getName())); - - validator.validateUpdate(dataShare, existing); - - copyExistingBaseFields(dataShare, existing); - - RangerDataShare ret = dataShareService.update(dataShare); - - dataShareService.onObjectChange(ret, existing, RangerServiceService.OPERATION_UPDATE_CONTEXT); - - updateGdsVersionForService(dataShare.getService()); - - LOG.debug("<== updateDataShare({}): ret={}", dataShare, ret); - - return ret; - } - - @Override - public void deleteDataShare(Long dataShareId, boolean forceDelete) { - LOG.debug("==> deleteDataShare(dataShareId: {}, forceDelete: {})", dataShareId, forceDelete); - - RangerDataShare existing = null; - - try { - existing = dataShareService.read(dataShareId); - } catch (Exception excp) { - // ignore - } - - validator.validateDelete(dataShareId, existing); - - if (existing != null) { - if (forceDelete) { - removeDshInDsForDataShare(dataShareId); - removeSharedResourcesForDataShare(dataShareId); - } - - dataShareService.delete(existing); - - dataShareService.onObjectChange(null, existing, RangerServiceService.OPERATION_DELETE_CONTEXT); - - updateGdsVersionForService(existing.getService()); - } - - LOG.debug("<== deleteDataShare(dataShareId: {}, forceDelete: {})", dataShareId, forceDelete); - } - - @Override - public RangerDataShare getDataShare(Long dataShareId) throws Exception { - LOG.debug("==> getDataShare({})", dataShareId); - - RangerDataShare ret = dataShareService.read(dataShareId); - - if (ret != null && !validator.hasPermission(ret.getAcl(), GdsPermission.VIEW)) { - throw new Exception("no permission on dataShare id=" + dataShareId); - } - - LOG.debug("<== getDataShare({}): ret={}", dataShareId, ret); - - return ret; - } - - @Override - public PList searchDataShares(SearchFilter filter) { - LOG.debug("==> searchDataShares({})", filter); - - PList ret = getUnscrubbedDataShares(filter); - List dataShares = ret.getList(); - GdsPermission gdsPermission = getGdsPermissionFromFilter(filter); - - for (RangerDataShare dataShare : dataShares) { - if (gdsPermission.equals(GdsPermission.LIST)) { - scrubDataShareForListing(dataShare); - } - } - - LOG.debug("<== searchDataShares({}): ret={}", filter, ret); + LOG.debug("<== searchDataShares({}): ret={}", filter, ret); return ret; } @@ -964,15 +752,15 @@ public RangerSharedResource getSharedResource(Long sharedResourceId) { public PList searchSharedResources(SearchFilter filter) { LOG.debug("==> searchSharedResources({})", filter); - int maxRows = filter.getMaxRows(); + int maxRows = filter.getMaxRows(); int startIndex = filter.getStartIndex(); final String resourceContains = filter.getParam(SearchFilter.RESOURCE_CONTAINS); filter.removeParam(SearchFilter.RESOURCE_CONTAINS); - if (StringUtils.isNotEmpty(resourceContains)) { - filter.setParam(SearchFilter.RETRIEVE_ALL_PAGES, "true"); - } + if (StringUtils.isNotEmpty(resourceContains)) { + filter.setParam(SearchFilter.RETRIEVE_ALL_PAGES, "true"); + } RangerSharedResourceList result = sharedResourceService.searchSharedResources(filter); List sharedResources = new ArrayList<>(); @@ -989,12 +777,12 @@ public PList searchSharedResources(SearchFilter filter) { if (CollectionUtils.isNotEmpty(resources)) { includeResource = resources.stream().filter(Objects::nonNull) - .map(RangerPolicyResource::getValues).filter(Objects::nonNull) - .anyMatch(res -> hasResource(res, resourceContains)); + .map(RangerPolicyResource::getValues).filter(Objects::nonNull) + .anyMatch(res -> hasResource(res, resourceContains)); if (!includeResource && sharedResource.getSubResource() != null && CollectionUtils.isNotEmpty(sharedResource.getSubResource().getValues())) { includeResource = sharedResource.getSubResource().getValues().stream().filter(Objects::nonNull) - .anyMatch(value -> value.contains(resourceContains)); + .anyMatch(value -> value.contains(resourceContains)); } } } @@ -1012,22 +800,6 @@ public PList searchSharedResources(SearchFilter filter) { return ret; } - public List addDataSharesInDataset(List dataSharesInDataset) throws Exception { - LOG.debug("==> addDataSharesInDataset({})", dataSharesInDataset); - - List ret = new ArrayList<>(); - - validate(dataSharesInDataset); - - for (RangerDataShareInDataset dataShareInDataset : dataSharesInDataset) { - ret.add(createDataShareInDataset(dataShareInDataset)); - } - - LOG.debug("<== addDataSharesInDataset({}): ret={}", dataSharesInDataset, ret); - - return ret; - } - @Override public RangerDataShareInDataset addDataShareInDataset(RangerDataShareInDataset dataShareInDataset) throws Exception { LOG.debug("==> addDataShareInDataset({})", dataShareInDataset); @@ -1053,168 +825,426 @@ public RangerDataShareInDataset updateDataShareInDataset(RangerDataShareInDatase dataShareInDataset.setApprover(validator.needApproverUpdate(existing.getStatus(), dataShareInDataset.getStatus()) ? bizUtil.getCurrentUserLoginId() : existing.getApprover()); - RangerDataShareInDataset ret = dataShareInDatasetService.update(dataShareInDataset); + RangerDataShareInDataset ret = dataShareInDatasetService.update(dataShareInDataset); + + dataShareInDatasetService.onObjectChange(ret, existing, RangerServiceService.OPERATION_UPDATE_CONTEXT); + + updateGdsVersionForDataset(dataShareInDataset.getDatasetId()); + + LOG.debug("<== updateDataShareInDataset({}): ret={}", dataShareInDataset, ret); + + return ret; + } + + @Override + public void removeDataShareInDataset(Long dataShareInDatasetId) { + LOG.debug("==> removeDataShareInDataset({})", dataShareInDatasetId); + + RangerDataShareInDataset existing = dataShareInDatasetService.read(dataShareInDatasetId); + + validator.validateDelete(dataShareInDatasetId, existing); + + dataShareInDatasetService.delete(existing); + + dataShareInDatasetService.onObjectChange(null, existing, RangerServiceService.OPERATION_DELETE_CONTEXT); + + updateGdsVersionForDataset(existing.getDatasetId()); + + LOG.debug("<== removeDataShareInDataset({})", dataShareInDatasetId); + } + + @Override + public RangerDataShareInDataset getDataShareInDataset(Long dataShareInDatasetId) { + LOG.debug("==> getDataShareInDataset({})", dataShareInDatasetId); + + RangerDataShareInDataset ret = dataShareInDatasetService.read(dataShareInDatasetId); + + LOG.debug("<== getDataShareInDataset({}): ret={}", dataShareInDatasetId, ret); + + return ret; + } + + @Override + public PList searchDataShareInDatasets(SearchFilter filter) { + LOG.debug("==> searchDataShareInDatasets({})", filter); + + int maxRows = filter.getMaxRows(); + int startIndex = filter.getStartIndex(); + + List dataShareInDatasets = new ArrayList<>(); + RangerDataShareInDatasetList result = dataShareInDatasetService.searchDataShareInDatasets(filter); + + for (RangerDataShareInDataset dataShareInDataset : result.getList()) { + // TODO: enforce RangerSharedResource.acl + + dataShareInDatasets.add(dataShareInDataset); + } + + PList ret = getPList(dataShareInDatasets, startIndex, maxRows, result.getSortBy(), result.getSortType()); + + LOG.debug("<== searchDataShareInDatasets({}): ret={}", filter, ret); + + return ret; + } + + @Override + public RangerDatasetInProject addDatasetInProject(RangerDatasetInProject datasetInProject) throws Exception { + LOG.debug("==> addDatasetInProject({})", datasetInProject); + + XXGdsDatasetInProjectDao datasetDao = daoMgr.getXXGdsDatasetInProject(); + XXGdsDatasetInProject existing = datasetDao.findByDatasetIdAndProjectId(datasetInProject.getDatasetId(), datasetInProject.getProjectId()); + + if (existing != null) { + throw new Exception("dataset '" + datasetInProject.getDatasetId() + "' already shared with project " + datasetInProject.getProjectId() + " - id=" + existing.getId()); + } + + validator.validateCreate(datasetInProject); + + if (StringUtils.isBlank(datasetInProject.getGuid())) { + datasetInProject.setGuid(guidUtil.genGUID()); + } + + RangerDatasetInProject ret = datasetInProjectService.create(datasetInProject); + + datasetInProjectService.onObjectChange(ret, null, RangerServiceService.OPERATION_CREATE_CONTEXT); + + updateGdsVersionForDataset(datasetInProject.getDatasetId()); + + LOG.debug("<== addDatasetInProject({}): ret={}", datasetInProject, ret); + + return ret; + } + + @Override + public RangerDatasetInProject updateDatasetInProject(RangerDatasetInProject datasetInProject) { + LOG.debug("==> updateDatasetInProject({})", datasetInProject); + + RangerDatasetInProject existing = datasetInProjectService.read(datasetInProject.getId()); + + validator.validateUpdate(datasetInProject, existing); + + copyExistingBaseFields(datasetInProject, existing); + + datasetInProject.setApprover(validator.needApproverUpdate(existing.getStatus(), datasetInProject.getStatus()) ? bizUtil.getCurrentUserLoginId() : existing.getApprover()); + + RangerDatasetInProject ret = datasetInProjectService.update(datasetInProject); + + datasetInProjectService.onObjectChange(ret, existing, RangerServiceService.OPERATION_UPDATE_CONTEXT); + + updateGdsVersionForDataset(datasetInProject.getDatasetId()); + + LOG.debug("<== updateDatasetInProject({}): ret={}", datasetInProject, ret); + + return ret; + } + + @Override + public void removeDatasetInProject(Long datasetInProjectId) { + LOG.debug("==> removeDatasetInProject({})", datasetInProjectId); + + RangerDatasetInProject existing = datasetInProjectService.read(datasetInProjectId); + + validator.validateDelete(datasetInProjectId, existing); + + datasetInProjectService.delete(existing); + + datasetInProjectService.onObjectChange(null, existing, RangerServiceService.OPERATION_DELETE_CONTEXT); + + updateGdsVersionForDataset(existing.getDatasetId()); + + LOG.debug("<== removeDatasetInProject({})", datasetInProjectId); + } + + @Override + public RangerDatasetInProject getDatasetInProject(Long datasetInProjectId) { + LOG.debug("==> getDatasetInProject({})", datasetInProjectId); + + RangerDatasetInProject ret = datasetInProjectService.read(datasetInProjectId); + + // TODO: enforce RangerDatasetInProject.acl + + LOG.debug("<== getDatasetInProject({}): ret={}", datasetInProjectId, ret); + + return ret; + } + + @Override + public PList searchDatasetInProjects(SearchFilter filter) { + LOG.debug("==> searchDatasetInProjects({})", filter); + + int maxRows = filter.getMaxRows(); + int startIndex = filter.getStartIndex(); + + List datasetInProjects = new ArrayList<>(); + RangerDatasetInProjectList result = datasetInProjectService.searchDatasetInProjects(filter); + + for (RangerDatasetInProject datasetInProject : result.getList()) { + // TODO: enforce RangerDatasetInProject.acl + + datasetInProjects.add(datasetInProject); + } + + PList ret = getPList(datasetInProjects, startIndex, maxRows, result.getSortBy(), result.getSortType()); + + LOG.debug("<== searchDatasetInProjects({}): ret={}", filter, ret); + + return ret; + } + + @Override + public RangerPolicy addDatasetPolicy(Long datasetId, RangerPolicy policy) throws Exception { + LOG.debug("==> addDatasetPolicy({}, {})", datasetId, policy); + + RangerDataset dataset = datasetService.read(datasetId); + + if (!validator.hasPermission(dataset.getAcl(), GdsPermission.POLICY_ADMIN)) { + throw restErrorUtil.create403RESTException(NOT_AUTHORIZED_FOR_DATASET_POLICIES); + } + + prepareDatasetPolicy(dataset, policy); + + RangerPolicy ret = svcStore.createPolicy(policy); + + daoMgr.getXXGdsDatasetPolicyMap().create(new XXGdsDatasetPolicyMap(datasetId, ret.getId())); + + updateGdsVersionForDataset(datasetId); + + LOG.debug("<== addDatasetPolicy({}, {}): ret={}", datasetId, policy, ret); + + return ret; + } + + @Override + public RangerPolicy updateDatasetPolicy(Long datasetId, RangerPolicy policy) throws Exception { + LOG.debug("==> updateDatasetPolicy({}, {})", datasetId, policy); + + RangerDataset dataset = datasetService.read(datasetId); + + if (!validator.hasPermission(dataset.getAcl(), GdsPermission.POLICY_ADMIN)) { + throw restErrorUtil.create403RESTException(NOT_AUTHORIZED_FOR_DATASET_POLICIES); + } + + XXGdsDatasetPolicyMap existing = daoMgr.getXXGdsDatasetPolicyMap().getDatasetPolicyMap(datasetId, policy.getId()); + + if (existing == null) { + throw new Exception("no policy exists: datasetId=" + datasetId + ", policyId=" + policy.getId()); + } + + prepareDatasetPolicy(dataset, policy); + + RangerPolicy ret = svcStore.updatePolicy(policy); + + updateGdsVersionForDataset(datasetId); + + LOG.debug("<== updateDatasetPolicy({}, {}): ret={}", datasetId, policy, ret); + + return ret; + } + + @Override + public void deleteDatasetPolicy(Long datasetId, Long policyId) throws Exception { + LOG.debug("==> deleteDatasetPolicy({}, {})", datasetId, policyId); + + RangerDataset dataset = datasetService.read(datasetId); + + if (!validator.hasPermission(dataset.getAcl(), GdsPermission.POLICY_ADMIN)) { + throw restErrorUtil.create403RESTException(NOT_AUTHORIZED_FOR_DATASET_POLICIES); + } + + XXGdsDatasetPolicyMap existing = daoMgr.getXXGdsDatasetPolicyMap().getDatasetPolicyMap(datasetId, policyId); + + if (existing == null) { + throw new Exception("no policy exists: datasetId=" + datasetId + ", policyId=" + policyId); + } + + RangerPolicy policy = svcStore.getPolicy(policyId); + + daoMgr.getXXGdsDatasetPolicyMap().remove(existing); + svcStore.deletePolicy(policy); + + updateGdsVersionForDataset(datasetId); + + LOG.debug("<== deleteDatasetPolicy({}, {})", datasetId, policyId); + } + + @Override + public void deleteDatasetPolicies(Long datasetId) throws Exception { + LOG.debug("==> deleteDatasetPolicies({})", datasetId); - dataShareInDatasetService.onObjectChange(ret, existing, RangerServiceService.OPERATION_UPDATE_CONTEXT); + RangerDataset dataset = datasetService.read(datasetId); - updateGdsVersionForDataset(dataShareInDataset.getDatasetId()); + deleteDatasetPolicies(dataset); - LOG.debug("<== updateDataShareInDataset({}): ret={}", dataShareInDataset, ret); + updateGdsVersionForDataset(datasetId); - return ret; + LOG.debug("<== deleteDatasetPolicy({})", datasetId); } @Override - public void removeDataShareInDataset(Long dataShareInDatasetId) { - LOG.debug("==> removeDataShareInDataset({})", dataShareInDatasetId); + public RangerPolicy getDatasetPolicy(Long datasetId, Long policyId) throws Exception { + LOG.debug("==> getDatasetPolicy({}, {})", datasetId, policyId); - RangerDataShareInDataset existing = dataShareInDatasetService.read(dataShareInDatasetId); + RangerDataset dataset = datasetService.read(datasetId); - validator.validateDelete(dataShareInDatasetId, existing); + if (!validator.hasPermission(dataset.getAcl(), GdsPermission.AUDIT)) { + throw restErrorUtil.create403RESTException(NOT_AUTHORIZED_TO_VIEW_DATASET_POLICIES); + } - dataShareInDatasetService.delete(existing); + XXGdsDatasetPolicyMap existing = daoMgr.getXXGdsDatasetPolicyMap().getDatasetPolicyMap(datasetId, policyId); - dataShareInDatasetService.onObjectChange(null, existing, RangerServiceService.OPERATION_DELETE_CONTEXT); + if (existing == null) { + throw new Exception("no policy exists: datasetId=" + datasetId + ", policyId=" + policyId); + } - updateGdsVersionForDataset(existing.getDatasetId()); + RangerPolicy ret = svcStore.getPolicy(policyId); - LOG.debug("<== removeDataShareInDataset({})", dataShareInDatasetId); + LOG.debug("<== getDatasetPolicy({}, {}): ret={}", datasetId, policyId, ret); + + return ret; } @Override - public RangerDataShareInDataset getDataShareInDataset(Long dataShareInDatasetId) { - LOG.debug("==> getDataShareInDataset({})", dataShareInDatasetId); + public List getDatasetPolicies(Long datasetId) { + LOG.debug("==> getDatasetPolicies({})", datasetId); - RangerDataShareInDataset ret = dataShareInDatasetService.read(dataShareInDatasetId); + RangerDataset dataset = datasetService.read(datasetId); - LOG.debug("<== getDataShareInDataset({}): ret={}", dataShareInDatasetId, ret); + if (!validator.hasPermission(dataset.getAcl(), GdsPermission.AUDIT)) { + throw restErrorUtil.create403RESTException(NOT_AUTHORIZED_TO_VIEW_DATASET_POLICIES); + } + + List ret = getPolicies(daoMgr.getXXGdsDatasetPolicyMap().getDatasetPolicyIds(datasetId)); + + LOG.debug("<== getDatasetPolicies({}): ret={}", datasetId, ret); return ret; } @Override - public PList searchDataShareInDatasets(SearchFilter filter) { - LOG.debug("==> searchDataShareInDatasets({})", filter); + public RangerPolicy addProjectPolicy(Long projectId, RangerPolicy policy) throws Exception { + LOG.debug("==> addProjectPolicy({}, {})", projectId, policy); - int maxRows = filter.getMaxRows(); - int startIndex = filter.getStartIndex(); + RangerProject project = projectService.read(projectId); - List dataShareInDatasets = new ArrayList<>(); - RangerDataShareInDatasetList result = dataShareInDatasetService.searchDataShareInDatasets(filter); + if (!validator.hasPermission(project.getAcl(), GdsPermission.POLICY_ADMIN)) { + throw restErrorUtil.create403RESTException(NOT_AUTHORIZED_FOR_PROJECT_POLICIES); + } - for (RangerDataShareInDataset dataShareInDataset : result.getList()) { - // TODO: enforce RangerSharedResource.acl + prepareProjectPolicy(project, policy); - dataShareInDatasets.add(dataShareInDataset); - } + RangerPolicy ret = svcStore.createPolicy(policy); - PList ret = getPList(dataShareInDatasets, startIndex, maxRows, result.getSortBy(), result.getSortType()); + daoMgr.getXXGdsProjectPolicyMap().create(new XXGdsProjectPolicyMap(projectId, ret.getId())); - LOG.debug("<== searchDataShareInDatasets({}): ret={}", filter, ret); + updateGdsVersionForProject(project.getId()); + + LOG.debug("<== addProjectPolicy({}, {}): ret={}", projectId, policy, ret); return ret; } @Override - public RangerDatasetInProject addDatasetInProject(RangerDatasetInProject datasetInProject) throws Exception { - LOG.debug("==> addDatasetInProject({})", datasetInProject); + public RangerPolicy updateProjectPolicy(Long projectId, RangerPolicy policy) throws Exception { + LOG.debug("==> updateProjectPolicy({}, {})", projectId, policy); - XXGdsDatasetInProjectDao datasetDao = daoMgr.getXXGdsDatasetInProject(); - XXGdsDatasetInProject existing = datasetDao.findByDatasetIdAndProjectId(datasetInProject.getDatasetId(), datasetInProject.getProjectId()); + RangerProject project = projectService.read(projectId); - if (existing != null) { - throw new Exception("dataset '" + datasetInProject.getDatasetId() + "' already shared with project " + datasetInProject.getProjectId() + " - id=" + existing.getId()); + if (!validator.hasPermission(project.getAcl(), GdsPermission.POLICY_ADMIN)) { + throw restErrorUtil.create403RESTException(NOT_AUTHORIZED_FOR_PROJECT_POLICIES); } - validator.validateCreate(datasetInProject); + XXGdsProjectPolicyMap existing = daoMgr.getXXGdsProjectPolicyMap().getProjectPolicyMap(projectId, policy.getId()); - if (StringUtils.isBlank(datasetInProject.getGuid())) { - datasetInProject.setGuid(guidUtil.genGUID()); + if (existing == null) { + throw new Exception("no policy exists: projectId=" + projectId + ", policyId=" + policy.getId()); } - RangerDatasetInProject ret = datasetInProjectService.create(datasetInProject); + prepareProjectPolicy(project, policy); - datasetInProjectService.onObjectChange(ret, null, RangerServiceService.OPERATION_CREATE_CONTEXT); + RangerPolicy ret = svcStore.updatePolicy(policy); - updateGdsVersionForDataset(datasetInProject.getDatasetId()); + updateGdsVersionForProject(project.getId()); - LOG.debug("<== addDatasetInProject({}): ret={}", datasetInProject, ret); + LOG.debug("<== updateProjectPolicy({}, {}): ret={}", projectId, policy, ret); return ret; } @Override - public RangerDatasetInProject updateDatasetInProject(RangerDatasetInProject datasetInProject) { - LOG.debug("==> updateDatasetInProject({})", datasetInProject); - - RangerDatasetInProject existing = datasetInProjectService.read(datasetInProject.getId()); + public void deleteProjectPolicy(Long projectId, Long policyId) throws Exception { + LOG.debug("==> deleteProjectPolicy({}, {})", projectId, policyId); - validator.validateUpdate(datasetInProject, existing); + RangerProject project = projectService.read(projectId); - copyExistingBaseFields(datasetInProject, existing); + if (!validator.hasPermission(project.getAcl(), GdsPermission.POLICY_ADMIN)) { + throw restErrorUtil.create403RESTException(NOT_AUTHORIZED_FOR_DATASET_POLICIES); + } - datasetInProject.setApprover(validator.needApproverUpdate(existing.getStatus(), datasetInProject.getStatus()) ? bizUtil.getCurrentUserLoginId() : existing.getApprover()); + XXGdsProjectPolicyMap existing = daoMgr.getXXGdsProjectPolicyMap().getProjectPolicyMap(projectId, policyId); - RangerDatasetInProject ret = datasetInProjectService.update(datasetInProject); + if (existing == null) { + throw new Exception("no policy exists: projectId=" + projectId + ", policyId=" + policyId); + } - datasetInProjectService.onObjectChange(ret, existing, RangerServiceService.OPERATION_UPDATE_CONTEXT); + RangerPolicy policy = svcStore.getPolicy(policyId); - updateGdsVersionForDataset(datasetInProject.getDatasetId()); + daoMgr.getXXGdsProjectPolicyMap().remove(existing); + svcStore.deletePolicy(policy); - LOG.debug("<== updateDatasetInProject({}): ret={}", datasetInProject, ret); + updateGdsVersionForProject(project.getId()); - return ret; + LOG.debug("<== deleteProjectPolicy({}, {})", projectId, policyId); } @Override - public void removeDatasetInProject(Long datasetInProjectId) { - LOG.debug("==> removeDatasetInProject({})", datasetInProjectId); - - RangerDatasetInProject existing = datasetInProjectService.read(datasetInProjectId); - - validator.validateDelete(datasetInProjectId, existing); + public void deleteProjectPolicies(Long projectId) throws Exception { + LOG.debug("==> deleteProjectPolicies({})", projectId); - datasetInProjectService.delete(existing); + RangerProject project = projectService.read(projectId); - datasetInProjectService.onObjectChange(null, existing, RangerServiceService.OPERATION_DELETE_CONTEXT); + deleteProjectPolicies(project); - updateGdsVersionForDataset(existing.getDatasetId()); + updateGdsVersionForProject(project.getId()); - LOG.debug("<== removeDatasetInProject({})", datasetInProjectId); + LOG.debug("<== deleteProjectPolicy({})", projectId); } @Override - public RangerDatasetInProject getDatasetInProject(Long datasetInProjectId) { - LOG.debug("==> getDatasetInProject({})", datasetInProjectId); + public RangerPolicy getProjectPolicy(Long projectId, Long policyId) throws Exception { + LOG.debug("==> getProjectPolicy({}, {})", projectId, policyId); - RangerDatasetInProject ret = datasetInProjectService.read(datasetInProjectId); + RangerProject project = projectService.read(projectId); - // TODO: enforce RangerDatasetInProject.acl + if (!validator.hasPermission(project.getAcl(), GdsPermission.AUDIT)) { + throw restErrorUtil.create403RESTException(NOT_AUTHORIZED_TO_VIEW_PROJECT_POLICIES); + } - LOG.debug("<== getDatasetInProject({}): ret={}", datasetInProjectId, ret); + XXGdsProjectPolicyMap existing = daoMgr.getXXGdsProjectPolicyMap().getProjectPolicyMap(projectId, policyId); + + if (existing == null) { + throw new Exception("no policy exists: projectId=" + projectId + ", policyId=" + policyId); + } + + RangerPolicy ret = svcStore.getPolicy(policyId); + + LOG.debug("<== getProjectPolicy({}, {}): ret={}", projectId, policyId, ret); return ret; } @Override - public PList searchDatasetInProjects(SearchFilter filter) { - LOG.debug("==> searchDatasetInProjects({})", filter); - - int maxRows = filter.getMaxRows(); - int startIndex = filter.getStartIndex(); - - List datasetInProjects = new ArrayList<>(); - RangerDatasetInProjectList result = datasetInProjectService.searchDatasetInProjects(filter); + public List getProjectPolicies(Long projectId) { + LOG.debug("==> getProjectPolicies({})", projectId); - for (RangerDatasetInProject datasetInProject : result.getList()) { - // TODO: enforce RangerDatasetInProject.acl + RangerProject project = projectService.read(projectId); - datasetInProjects.add(datasetInProject); + if (!validator.hasPermission(project.getAcl(), GdsPermission.AUDIT)) { + throw restErrorUtil.create403RESTException(NOT_AUTHORIZED_TO_VIEW_PROJECT_POLICIES); } - PList ret = getPList(datasetInProjects, startIndex, maxRows, result.getSortBy(), result.getSortType()); + List ret = getPolicies(daoMgr.getXXGdsProjectPolicyMap().getProjectPolicyIds(projectId)); - LOG.debug("<== searchDatasetInProjects({}): ret={}", filter, ret); + LOG.debug("<== getProjectPolicies({}): ret={}", projectId, ret); return ret; } @@ -1311,8 +1341,24 @@ public void onSecurityZoneUpdate(Long zoneId, Collection updatedServices LOG.debug("<== onSecurityZoneUpdate({}, {}, {})", zoneId, updatedServices, removedServices); } - public ServiceGdsInfo getGdsInfoIfUpdated(String serviceName, Long lastKnownVersion) throws Exception { - LOG.debug("==> GdsDBStore.getGdsInfoIfUpdated({}, {})", serviceName , lastKnownVersion); + public List addDataSharesInDataset(List dataSharesInDataset) throws Exception { + LOG.debug("==> addDataSharesInDataset({})", dataSharesInDataset); + + List ret = new ArrayList<>(); + + validate(dataSharesInDataset); + + for (RangerDataShareInDataset dataShareInDataset : dataSharesInDataset) { + ret.add(createDataShareInDataset(dataShareInDataset)); + } + + LOG.debug("<== addDataSharesInDataset({}): ret={}", dataSharesInDataset, ret); + + return ret; + } + + public ServiceGdsInfo getGdsInfoIfUpdated(String serviceName, Long lastKnownVersion) { + LOG.debug("==> GdsDBStore.getGdsInfoIfUpdated({}, {})", serviceName, lastKnownVersion); ServiceGdsInfo latest = serviceGdsInfoCache.get(serviceName); Long latestVersion = latest != null ? latest.getGdsVersion() : null; @@ -1323,7 +1369,7 @@ public ServiceGdsInfo getGdsInfoIfUpdated(String serviceName, Long lastKnownVers return ret; } - public PList getDatasetSummary(SearchFilter filter) throws Exception { + public PList getDatasetSummary(SearchFilter filter) { LOG.debug("==> getDatasetSummary({})", filter); PList datasets = getUnscrubbedDatasets(filter); @@ -1352,39 +1398,39 @@ public PList getDataShareSummary(SearchFilter filter) { } public PList getDshInDsSummary(SearchFilter filter) { - LOG.debug("==> getDshInDsSummary({})", filter); + LOG.debug("==> getDshInDsSummary({})", filter); - int maxRows = filter.getMaxRows(); - int startIndex = filter.getStartIndex(); + int maxRows = filter.getMaxRows(); + int startIndex = filter.getStartIndex(); filter.setParam(SearchFilter.GDS_PERMISSION, GdsPermission.ADMIN.name()); - if (filter.getParam(SearchFilter.CREATED_BY) != null) { - setUserId(filter, SearchFilter.CREATED_BY); - } + if (filter.getParam(SearchFilter.CREATED_BY) != null) { + setUserId(filter, SearchFilter.CREATED_BY); + } - if(filter.getParam(SearchFilter.APPROVER)!= null) { - setUserId(filter, SearchFilter.APPROVER); - } + if (filter.getParam(SearchFilter.APPROVER) != null) { + setUserId(filter, SearchFilter.APPROVER); + } - if (filter.getParam(SearchFilter.SHARE_STATUS) != null) { - String shareStatus = filter.getParam(SearchFilter.SHARE_STATUS); - int status = GdsShareStatus.valueOf(shareStatus).ordinal(); + if (filter.getParam(SearchFilter.SHARE_STATUS) != null) { + String shareStatus = filter.getParam(SearchFilter.SHARE_STATUS); + int status = GdsShareStatus.valueOf(shareStatus).ordinal(); - filter.setParam(SearchFilter.SHARE_STATUS, Integer.toString(status)); - } + filter.setParam(SearchFilter.SHARE_STATUS, Integer.toString(status)); + } - List datasets = getUnscrubbedDatasets(filter).getList(); - List dataShares = getUnscrubbedDataShares(filter).getList(); - RangerDataShareInDatasetList dshInDsList = dataShareInDatasetService.searchDataShareInDatasets(filter); - List dshInDsSummary = getDshInDsSummary(dataShares, datasets, dshInDsList); + List datasets = getUnscrubbedDatasets(filter).getList(); + List dataShares = getUnscrubbedDataShares(filter).getList(); + RangerDataShareInDatasetList dshInDsList = dataShareInDatasetService.searchDataShareInDatasets(filter); + List dshInDsSummary = getDshInDsSummary(dataShares, datasets, dshInDsList); - PList ret = getPList(dshInDsSummary, startIndex, maxRows, filter.getSortBy(), filter.getSortType()); + PList ret = getPList(dshInDsSummary, startIndex, maxRows, filter.getSortBy(), filter.getSortType()); - LOG.debug("<== getDshInDsSummary({}): ret={}", filter, ret); + LOG.debug("<== getDshInDsSummary({}): ret={}", filter, ret); - return ret; - } + return ret; + } public void deletePrincipalFromGdsAcl(String principalType, String principalName) { Map datsetAcls = daoMgr.getXXGdsDataset().getDatasetIdsAndACLs(); @@ -1428,63 +1474,44 @@ public void deletePrincipalFromGdsAcl(String principalType, String principalName } } - private List getDshInDsSummary(List dataShares, List datasets, RangerDataShareInDatasetList dshInDsList) { - Set ret = new LinkedHashSet<>(); - Map datasetMap = toMap(datasets); - Map dataShareMap = toMap(dataShares); + private List getDshInDsSummary(List dataShares, List datasets, RangerDataShareInDatasetList dshInDsList) { + Set ret = new LinkedHashSet<>(); + Map datasetMap = toMap(datasets); + Map dataShareMap = toMap(dataShares); - for (RangerDataShareInDataset dshInDs : dshInDsList.getList()) { - RangerDataset dataset = datasetMap.get(dshInDs.getDatasetId()); - RangerDataShare dataShare = dataShareMap.get(dshInDs.getDataShareId()); + for (RangerDataShareInDataset dshInDs : dshInDsList.getList()) { + RangerDataset dataset = datasetMap.get(dshInDs.getDatasetId()); + RangerDataShare dataShare = dataShareMap.get(dshInDs.getDataShareId()); - if (dataset != null || dataShare != null) { + if (dataset != null || dataShare != null) { if (dataset == null) { dataset = datasetService.read(dshInDs.getDatasetId()); } else if (dataShare == null) { dataShare = dataShareService.read(dshInDs.getDataShareId()); } - ret.add(toDshInDsSummary(dataset, dataShare, dshInDs)); - } - } + ret.add(toDshInDsSummary(dataset, dataShare, dshInDs)); + } + } - return Collections.unmodifiableList(new ArrayList<>(ret)); - } + return Collections.unmodifiableList(new ArrayList<>(ret)); + } - private Map toMap(List gdsObjects) { - return gdsObjects.stream().collect(Collectors.toMap(RangerGdsBaseModelObject::getId, Function.identity())); - } + private Map toMap(List gdsObjects) { + return gdsObjects.stream().collect(Collectors.toMap(RangerGdsBaseModelObject::getId, Function.identity())); + } private void updateGdsVersion() { transactionSynchronizationAdapter.executeOnTransactionCommit(new GlobalVersionUpdater(daoMgr, RANGER_GLOBAL_STATE_NAME_GDS)); } - private void setUserId(SearchFilter filter, String filterParam) { - String userName = filter.getParam(filterParam); - Long userId = daoMgr.getXXPortalUser().findByLoginId(userName).getId(); - filter.setParam(filterParam, Long.toString(userId)); - } - - private static class GlobalVersionUpdater implements Runnable { - final RangerDaoManager daoManager; - final String stateName; - - public GlobalVersionUpdater(RangerDaoManager daoManager, String stateName) { - this.daoManager = daoManager; - this.stateName = stateName; - } - - @Override - public void run() { - try { - this.daoManager.getXXGlobalState().onGlobalAppDataChange(stateName); - } catch (Exception e) { - LOG.error("Failed to update GlobalState version for state:[{}]", stateName , e); - } - } + private void setUserId(SearchFilter filter, String filterParam) { + String userName = filter.getParam(filterParam); + Long userId = daoMgr.getXXPortalUser().findByLoginId(userName).getId(); + filter.setParam(filterParam, Long.toString(userId)); } - private List toDatasetSummary(List datasets, GdsPermission gdsPermission) throws Exception { + private List toDatasetSummary(List datasets, GdsPermission gdsPermission) { List ret = new ArrayList<>(); String currentUser = bizUtil.getCurrentUserLoginId(); @@ -1524,9 +1551,9 @@ private List toDatasetSummary(List datasets, GdsP datasetSummary.setDataShares(dataSharesSummary); datasetSummary.setTotalResourceCount(dataSharesSummary.stream() - .map(DataShareInDatasetSummary::getResourceCount) - .mapToLong(Long::longValue) - .sum()); + .map(DataShareInDatasetSummary::getResourceCount) + .mapToLong(Long::longValue) + .sum()); } return ret; @@ -1584,7 +1611,7 @@ private Long getDIPCountForDataset(Long datasetId) { return datasetInProjectService.getDatasetsInProjectCount(datasetId); } - private Map getPrincipalCountForDataset(RangerDataset dataset) throws Exception { + private Map getPrincipalCountForDataset(RangerDataset dataset) { Map ret = new HashMap<>(); Set users = Collections.emptySet(); Set groups = Collections.emptySet(); @@ -1604,9 +1631,9 @@ private Map getPrincipalCountForDataset(RangerDataset da } } - ret.put(PrincipalType.USER, users.size()); + ret.put(PrincipalType.USER, users.size()); ret.put(PrincipalType.GROUP, groups.size()); - ret.put(PrincipalType.ROLE, roles.size()); + ret.put(PrincipalType.ROLE, roles.size()); return ret; } @@ -1637,7 +1664,6 @@ private Map getAclPrincipalCountForDataset(RangerDataset return ret; } - private PList getUnscrubbedProjects(SearchFilter filter) { filter.setParam(SearchFilter.RETRIEVE_ALL_PAGES, "true"); @@ -1724,9 +1750,9 @@ private PList getUnscrubbedDataShares(SearchFilter filter) { dataSharesToExclude = Collections.emptyList(); } - GdsPermission gdsPermission = getGdsPermissionFromFilter(filter); - RangerDataShareList result = dataShareService.searchDataShares(filter); - List dataShares = new ArrayList<>(); + GdsPermission gdsPermission = getGdsPermissionFromFilter(filter); + RangerDataShareList result = dataShareService.searchDataShares(filter); + List dataShares = new ArrayList<>(); for (RangerDataShare dataShare : result.getList()) { if (dataShare == null) { @@ -1803,10 +1829,10 @@ private void removeDshInDsForDataShare(Long dataShareId) { SearchFilter filter = new SearchFilter(SearchFilter.DATA_SHARE_ID, dataShareId.toString()); RangerDataShareInDatasetList dshInDsList = dataShareInDatasetService.searchDataShareInDatasets(filter); - for(RangerDataShareInDataset dshInDs : dshInDsList.getList()) { + for (RangerDataShareInDataset dshInDs : dshInDsList.getList()) { final boolean dshInDsDeleted = dataShareInDatasetService.delete(dshInDs); - if(!dshInDsDeleted) { + if (!dshInDsDeleted) { throw restErrorUtil.createRESTException("DataShareInDataset could not be deleted", MessageEnums.ERROR_DELETE_OBJECT, dshInDs.getId(), "DataSHareInDatasetId", null, 500); } } @@ -1919,8 +1945,8 @@ private void removeDIPForDataset(Long datasetId) { if (!dipDeleted) { throw restErrorUtil.createRESTException("DatasetInProject could not be deleted", - MessageEnums.ERROR_DELETE_OBJECT, dip.getId(), "DatasetInProjectId", null, - HttpStatus.SC_INTERNAL_SERVER_ERROR); + MessageEnums.ERROR_DELETE_OBJECT, dip.getId(), "DatasetInProjectId", null, + HttpStatus.SC_INTERNAL_SERVER_ERROR); } } } @@ -1934,8 +1960,8 @@ private void removeDSHIDForDataset(Long datasetId) { if (!dshidDeleted) { throw restErrorUtil.createRESTException("DataShareInDataset could not be deleted", - MessageEnums.ERROR_DELETE_OBJECT, dshid.getId(), "DataShareInDataset", null, - HttpStatus.SC_INTERNAL_SERVER_ERROR); + MessageEnums.ERROR_DELETE_OBJECT, dshid.getId(), "DataShareInDataset", null, + HttpStatus.SC_INTERNAL_SERVER_ERROR); } } } @@ -1949,15 +1975,15 @@ private void removeDIPForProject(Long projectId) { if (!dipDeleted) { throw restErrorUtil.createRESTException("DatasetInProject could not be deleted", - MessageEnums.ERROR_DELETE_OBJECT, dip.getId(), "DatasetInProjectId", null, - HttpStatus.SC_INTERNAL_SERVER_ERROR); + MessageEnums.ERROR_DELETE_OBJECT, dip.getId(), "DatasetInProjectId", null, + HttpStatus.SC_INTERNAL_SERVER_ERROR); } } } private void addCreatorAsAclAdmin(RangerGdsObjectACL acl) { - String currentUser = bizUtil.getCurrentUserLoginId(); - Map userAcl = acl.getUsers(); + String currentUser = bizUtil.getCurrentUserLoginId(); + Map userAcl = acl.getUsers(); if (userAcl == null) { userAcl = new HashMap<>(); @@ -2059,35 +2085,35 @@ private DataShareInDatasetSummary toDshInDsSummary(RangerDataset dataset, List zoneIds = new HashMap<>(); - DataShareInDatasetSummary summary = new DataShareInDatasetSummary(); - - summary.setId(dshInDs.getId()); - summary.setGuid(dshInDs.getGuid()); - summary.setCreatedBy(dshInDs.getCreatedBy()); - summary.setCreateTime(dshInDs.getCreateTime()); - summary.setUpdatedBy(dshInDs.getUpdatedBy()); - summary.setUpdateTime(dshInDs.getUpdateTime()); - - summary.setApprover(dshInDs.getApprover()); - summary.setShareStatus(dshInDs.getStatus()); - summary.setDatasetId(dataset.getId()); - summary.setDatasetName(dataset.getName()); - summary.setDataShareId(dataShare.getId()); - summary.setDataShareName(dataShare.getName()); - if (dataShare.getZone() != null && !dataShare.getZone().isEmpty()) { - summary.setZoneName(dataShare.getZone()); - summary.setZoneId(getZoneId(dataShare.getZone(),zoneIds)); - } - summary.setServiceName(dataShare.getService()); - summary.setServiceId(getServiceId(dataShare.getService())); - summary.setDataShareName(dataShare.getName()); - summary.setResourceCount(sharedResourceService.getResourceCountForDataShare(dataShare.getId())); - - return summary; - } + private DataShareInDatasetSummary toDshInDsSummary(RangerDataset dataset, RangerDataShare dataShare, + RangerDataShareInDataset dshInDs) { + Map zoneIds = new HashMap<>(); + DataShareInDatasetSummary summary = new DataShareInDatasetSummary(); + + summary.setId(dshInDs.getId()); + summary.setGuid(dshInDs.getGuid()); + summary.setCreatedBy(dshInDs.getCreatedBy()); + summary.setCreateTime(dshInDs.getCreateTime()); + summary.setUpdatedBy(dshInDs.getUpdatedBy()); + summary.setUpdateTime(dshInDs.getUpdateTime()); + + summary.setApprover(dshInDs.getApprover()); + summary.setShareStatus(dshInDs.getStatus()); + summary.setDatasetId(dataset.getId()); + summary.setDatasetName(dataset.getName()); + summary.setDataShareId(dataShare.getId()); + summary.setDataShareName(dataShare.getName()); + if (dataShare.getZone() != null && !dataShare.getZone().isEmpty()) { + summary.setZoneName(dataShare.getZone()); + summary.setZoneId(getZoneId(dataShare.getZone(), zoneIds)); + } + summary.setServiceName(dataShare.getService()); + summary.setServiceId(getServiceId(dataShare.getService())); + summary.setDataShareName(dataShare.getName()); + summary.setResourceCount(sharedResourceService.getResourceCountForDataShare(dataShare.getId())); + + return summary; + } private Long getServiceId(String serviceName) { XXService xService = daoMgr.getXXService().findByName(serviceName); @@ -2116,8 +2142,8 @@ private boolean hasResource(List resources, String resourceValue) { private void validate(List dataSharesInDataset) throws Exception { XXGdsDataShareInDatasetDao dshInDsDao = daoMgr.getXXGdsDataShareInDataset(); - if(CollectionUtils.isNotEmpty(dataSharesInDataset)) { - for(RangerDataShareInDataset dataShareInDataset : dataSharesInDataset) { + if (CollectionUtils.isNotEmpty(dataSharesInDataset)) { + for (RangerDataShareInDataset dataShareInDataset : dataSharesInDataset) { XXGdsDataShareInDataset existing = dshInDsDao.findByDataShareIdAndDatasetId(dataShareInDataset.getDataShareId(), dataShareInDataset.getDatasetId()); if (existing != null) { @@ -2189,7 +2215,7 @@ private List getPolicies(List policyIds) { ret.add(policy); } } catch (Exception excp) { - LOG.error("getPolicies(): failed to get policy with id=" + policyId, excp); + LOG.error("getPolicies(): failed to get policy with id={}", policyId, excp); } } } @@ -2245,21 +2271,21 @@ private void updateGdsVersionForDataShare(Long dataShareId) { } } - private GdsPermission deletePrincipalFromAcl(RangerGdsObjectACL acl, String principalName, String principalType) { + private GdsPermission deletePrincipalFromAcl(RangerGdsObjectACL acl, String principalName, String principalType) { final Map principalAcls; - if (principalType.equalsIgnoreCase(REMOVE_REF_TYPE.USER.toString())) { + if (principalType.equalsIgnoreCase(REMOVE_REF_TYPE.USER.toString())) { principalAcls = acl.getUsers(); - } else if (principalType.equalsIgnoreCase(REMOVE_REF_TYPE.GROUP.toString())) { + } else if (principalType.equalsIgnoreCase(REMOVE_REF_TYPE.GROUP.toString())) { principalAcls = acl.getGroups(); - } else if (principalType.equalsIgnoreCase(REMOVE_REF_TYPE.ROLE.toString())) { + } else if (principalType.equalsIgnoreCase(REMOVE_REF_TYPE.ROLE.toString())) { principalAcls = acl.getRoles(); - } else { + } else { principalAcls = null; } - return principalAcls != null ? principalAcls.remove(principalName) : null; - } + return principalAcls != null ? principalAcls.remove(principalName) : null; + } private void copyExistingBaseFields(RangerGdsBaseModelObject objToUpdate, RangerGdsBaseModelObject existingObj) { if (objToUpdate != null && existingObj != null) { @@ -2286,4 +2312,23 @@ private void copyExistingBaseFields(RangerGdsBaseModelObject objToUpdate, Ranger } } } + + private static class GlobalVersionUpdater implements Runnable { + final RangerDaoManager daoManager; + final String stateName; + + public GlobalVersionUpdater(RangerDaoManager daoManager, String stateName) { + this.daoManager = daoManager; + this.stateName = stateName; + } + + @Override + public void run() { + try { + this.daoManager.getXXGlobalState().onGlobalAppDataChange(stateName); + } catch (Exception e) { + LOG.error("Failed to update GlobalState version for state:[{}]", stateName, e); + } + } + } } diff --git a/security-admin/src/main/java/org/apache/ranger/biz/GdsPolicyAdminCache.java b/security-admin/src/main/java/org/apache/ranger/biz/GdsPolicyAdminCache.java index 41056c9c23..0c43250c15 100644 --- a/security-admin/src/main/java/org/apache/ranger/biz/GdsPolicyAdminCache.java +++ b/security-admin/src/main/java/org/apache/ranger/biz/GdsPolicyAdminCache.java @@ -30,8 +30,12 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; -import java.util.*; - +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; @Component public class GdsPolicyAdminCache { @@ -40,7 +44,7 @@ public class GdsPolicyAdminCache { @Autowired ServiceDBStore svcStore; - private volatile GdsPolicies policies = null; + private volatile GdsPolicies policies; public GdsPolicyAdminCache() { } diff --git a/security-admin/src/main/java/org/apache/ranger/biz/KmsKeyMgr.java b/security-admin/src/main/java/org/apache/ranger/biz/KmsKeyMgr.java index 0501bebc3b..a8fb2942f1 100755 --- a/security-admin/src/main/java/org/apache/ranger/biz/KmsKeyMgr.java +++ b/security-admin/src/main/java/org/apache/ranger/biz/KmsKeyMgr.java @@ -19,23 +19,11 @@ package org.apache.ranger.biz; -import java.io.IOException; -import java.net.MalformedURLException; -import java.net.URI; -import java.net.URISyntaxException; -import java.net.URL; -import java.security.PrivilegedAction; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.regex.Pattern; - -import javax.security.auth.Subject; -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.core.MediaType; - +import com.sun.jersey.api.client.Client; +import com.sun.jersey.api.client.UniformInterfaceException; +import com.sun.jersey.api.client.WebResource; +import com.sun.jersey.api.client.config.ClientConfig; +import com.sun.jersey.api.client.config.DefaultClientConfig; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.MapUtils; import org.apache.commons.collections.Predicate; @@ -48,7 +36,6 @@ import org.apache.ranger.authorization.utils.JsonUtils; import org.apache.ranger.common.ContextUtil; import org.apache.ranger.common.MessageEnums; -import org.apache.ranger.plugin.util.PasswordUtils; import org.apache.ranger.common.PropertiesUtil; import org.apache.ranger.common.RESTErrorUtil; import org.apache.ranger.common.RangerConfigUtil; @@ -59,6 +46,7 @@ import org.apache.ranger.entity.XXServiceConfigMap; import org.apache.ranger.plugin.model.RangerService; import org.apache.ranger.plugin.util.KeySearchFilter; +import org.apache.ranger.plugin.util.PasswordUtils; import org.apache.ranger.view.VXKmsKey; import org.apache.ranger.view.VXKmsKeyList; import org.slf4j.Logger; @@ -66,661 +54,739 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; -import com.sun.jersey.api.client.Client; -import com.sun.jersey.api.client.UniformInterfaceException; -import com.sun.jersey.api.client.WebResource; -import com.sun.jersey.api.client.config.ClientConfig; -import com.sun.jersey.api.client.config.DefaultClientConfig; +import javax.security.auth.Subject; +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.core.MediaType; + +import java.io.IOException; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.URL; +import java.security.PrivilegedAction; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.regex.Pattern; @Component public class KmsKeyMgr { + private static final Logger logger = LoggerFactory.getLogger(KmsKeyMgr.class); + + static final String NAME_RULES = "hadoop.security.auth_to_local"; + static final String RANGER_AUTH_TYPE = "hadoop.security.authentication"; + static final String HOST_NAME = "ranger.service.host"; + + private static final String KMS_KEY_LIST_URI = "v1/keys/names"; //GET + private static final String KMS_ADD_KEY_URI = "v1/keys"; //POST + private static final String KMS_ROLL_KEY_URI = "v1/key/${alias}"; //POST + private static final String KMS_DELETE_KEY_URI = "v1/key/${alias}"; //DELETE + private static final String KMS_KEY_METADATA_URI = "v1/key/${alias}/_metadata"; //GET + private static final String KMS_URL_CONFIG = "provider"; + private static final String KMS_PASSWORD = "password"; + private static final String KMS_USERNAME = "username"; + private static final String KERBEROS_TYPE = "kerberos"; + private static final String ADMIN_USER_PRINCIPAL = "ranger.admin.kerberos.principal"; + private static final String ADMIN_USER_KEYTAB = "ranger.admin.kerberos.keytab"; + private static final Map providerList = new HashMap<>(); + private static int nextProvider; + + @Autowired + ServiceDBStore svcStore; + + @Autowired + RESTErrorUtil restErrorUtil; + + @Autowired + RangerConfigUtil configUtil; + + @Autowired + RangerDaoManagerBase rangerDaoManagerBase; + + @Autowired + RangerBizUtil rangerBizUtil; + + public VXKmsKeyList searchKeys(HttpServletRequest request, String repoName) throws Exception { + String[] providers = null; + + try { + providers = getKMSURL(repoName); + } catch (Exception e) { + logger.error("getKey({}) failed", repoName, e); + } + + List vXKeys = new ArrayList<>(); + VXKmsKeyList vxKmsKeyList = new VXKmsKeyList(); + String connProvider = null; + boolean isKerberos = false; + + try { + isKerberos = checkKerberos(); + } catch (Exception e1) { + logger.error("checkKerberos({}) failed", repoName, e1); + } + + if (providers != null) { + for (int i = 0; i < providers.length; i++) { + Client c = getClient(); + String currentUserLoginId = StringUtil.getUTFEncodedString(ContextUtil.getCurrentUserLoginId()); + String keyLists = KMS_KEY_LIST_URI.replaceAll(Pattern.quote("${userName}"), currentUserLoginId); + + connProvider = providers[i]; + + String uri = providers[i] + (providers[i].endsWith("/") ? keyLists : ("/" + keyLists)); + + if (!isKerberos) { + uri = uri.concat("?user.name=" + currentUserLoginId); + } else { + uri = uri.concat("?doAs=" + currentUserLoginId); + } + + final WebResource r = c.resource(uri); + + try { + String response; + + if (!isKerberos) { + response = r.accept(MediaType.APPLICATION_JSON_TYPE).type(MediaType.APPLICATION_JSON_TYPE).get(String.class); + } else { + Subject sub = getSubjectForKerberos(repoName); + + response = Subject.doAs(sub, (PrivilegedAction) () -> r.accept(MediaType.APPLICATION_JSON_TYPE).type(MediaType.APPLICATION_JSON_TYPE).get(String.class)); + } + + logger.debug(" Search Key RESPONSE: [{}]", response); + + List keys = JsonUtils.jsonToListString(response); + + Collections.sort(keys); + + VXKmsKeyList vxKmsKeyList2 = new VXKmsKeyList(); + List vXKeys2 = new ArrayList<>(); + + for (String name : keys) { + VXKmsKey key = new VXKmsKey(); + + key.setName(name); + + vXKeys2.add(key); + } + + vxKmsKeyList2.setVXKeys(vXKeys2); + + vxKmsKeyList = getFilteredKeyList(request, vxKmsKeyList2); + + break; + } catch (Exception e) { + if (e instanceof UniformInterfaceException || i == providers.length - 1) { + throw e; + } else { + continue; + } + } + } + } + + //details + if (vxKmsKeyList != null && vxKmsKeyList.getVXKeys() != null && !vxKmsKeyList.getVXKeys().isEmpty()) { + List lstKMSKey = vxKmsKeyList.getVXKeys(); + int startIndex = restErrorUtil.parseInt(request.getParameter("startIndex"), 0, "Invalid value for parameter startIndex", MessageEnums.INVALID_INPUT_DATA, null, "startIndex"); + + startIndex = startIndex < 0 ? 0 : startIndex; + + int pageSize = restErrorUtil.parseInt(request.getParameter("pageSize"), 0, "Invalid value for parameter pageSize", MessageEnums.INVALID_INPUT_DATA, null, "pageSize"); + + pageSize = pageSize < 0 ? 0 : pageSize; + + vxKmsKeyList.setResultSize(lstKMSKey.size()); + vxKmsKeyList.setTotalCount(lstKMSKey.size()); + + if ((startIndex + pageSize) <= lstKMSKey.size()) { + lstKMSKey = lstKMSKey.subList(startIndex, (startIndex + pageSize)); + } else { + startIndex = startIndex >= lstKMSKey.size() ? 0 : startIndex; + lstKMSKey = lstKMSKey.subList(startIndex, lstKMSKey.size()); + } + + if (CollectionUtils.isNotEmpty(lstKMSKey)) { + for (VXKmsKey kmsKey : lstKMSKey) { + if (kmsKey != null) { + VXKmsKey key = getKeyFromUri(connProvider, kmsKey.getName(), isKerberos, repoName); + + vXKeys.add(key); + } + } + } + + vxKmsKeyList.setStartIndex(startIndex); + vxKmsKeyList.setPageSize(pageSize); + } + + if (vxKmsKeyList != null) { + vxKmsKeyList.setVXKeys(vXKeys); + } + + return vxKmsKeyList; + } + + public VXKmsKey rolloverKey(String provider, VXKmsKey vXKey) throws Exception { + String[] providers = null; + + rangerBizUtil.blockAuditorRoleUser(); + + try { + providers = getKMSURL(provider); + } catch (Exception e) { + logger.error("rolloverKey({}, {}) failed", provider, vXKey.getName(), e); + } + + VXKmsKey ret = null; + boolean isKerberos = false; + + try { + isKerberos = checkKerberos(); + } catch (Exception e1) { + logger.error("checkKerberos({}) failed", provider, e1); + } + + if (providers != null) { + for (int i = 0; i < providers.length; i++) { + Client c = getClient(); + String rollRest = KMS_ROLL_KEY_URI.replaceAll(Pattern.quote("${alias}"), vXKey.getName()); + String currentUserLoginId = StringUtil.getUTFEncodedString(ContextUtil.getCurrentUserLoginId()); + String uri = providers[i] + (providers[i].endsWith("/") ? rollRest : ("/" + rollRest)); + + if (!isKerberos) { + uri = uri.concat("?user.name=" + currentUserLoginId); + } else { + uri = uri.concat("?doAs=" + currentUserLoginId); + } + + final WebResource r = c.resource(uri); + final String jsonString = JsonUtils.objectToJson(vXKey); + + try { + String response; + + if (!isKerberos) { + response = r.accept(MediaType.APPLICATION_JSON_TYPE).type(MediaType.APPLICATION_JSON_TYPE).post(String.class, jsonString); + } else { + Subject sub = getSubjectForKerberos(provider); + + response = Subject.doAs(sub, (PrivilegedAction) () -> r.accept(MediaType.APPLICATION_JSON_TYPE).type(MediaType.APPLICATION_JSON_TYPE).post(String.class, jsonString)); + } + + logger.debug("Roll RESPONSE: [{}]", response); + + ret = JsonUtils.jsonToObject(response, VXKmsKey.class); + + break; + } catch (Exception e) { + if (e instanceof UniformInterfaceException || i == providers.length - 1) { + throw e; + } else { + continue; + } + } + } + } + return ret; + } + + public void deleteKey(String provider, String name) throws Exception { + String[] providers = null; + + rangerBizUtil.blockAuditorRoleUser(); + + try { + providers = getKMSURL(provider); + } catch (Exception e) { + logger.error("deleteKey({}, {}) failed", provider, name, e); + } + + boolean isKerberos = false; + + try { + isKerberos = checkKerberos(); + } catch (Exception e1) { + logger.error("checkKerberos({}) failed", provider, e1); + } + + if (providers != null) { + for (int i = 0; i < providers.length; i++) { + Client c = getClient(); + String deleteRest = KMS_DELETE_KEY_URI.replaceAll(Pattern.quote("${alias}"), name); + String currentUserLoginId = StringUtil.getUTFEncodedString(ContextUtil.getCurrentUserLoginId()); + String uri = providers[i] + (providers[i].endsWith("/") ? deleteRest : ("/" + deleteRest)); + + if (!isKerberos) { + uri = uri.concat("?user.name=" + currentUserLoginId); + } else { + uri = uri.concat("?doAs=" + currentUserLoginId); + } + + final WebResource r = c.resource(uri); + try { + String response; + + if (!isKerberos) { + response = r.delete(String.class); + } else { + Subject sub = getSubjectForKerberos(provider); + + response = Subject.doAs(sub, (PrivilegedAction) () -> r.delete(String.class)); + } + + logger.debug("delete RESPONSE: [{}]", response); + break; + } catch (Exception e) { + if (e instanceof UniformInterfaceException || i == providers.length - 1) { + throw e; + } else { + continue; + } + } + } + } + } + + public VXKmsKey createKey(String provider, VXKmsKey vXKey) throws Exception { + String[] providers = null; + + rangerBizUtil.blockAuditorRoleUser(); + + try { + providers = getKMSURL(provider); + } catch (Exception e) { + logger.error("createKey({}, {}) failed", provider, vXKey.getName(), e); + } + + VXKmsKey ret = null; + boolean isKerberos = false; + + try { + isKerberos = checkKerberos(); + } catch (Exception e1) { + logger.error("checkKerberos({}) failed", provider, e1); + } + + if (providers != null) { + for (int i = 0; i < providers.length; i++) { + Client c = getClient(); + String currentUserLoginId = StringUtil.getUTFEncodedString(ContextUtil.getCurrentUserLoginId()); + String uri = providers[i] + (providers[i].endsWith("/") ? KMS_ADD_KEY_URI : ("/" + KMS_ADD_KEY_URI)); + + if (!isKerberos) { + uri = uri.concat("?user.name=" + currentUserLoginId); + } else { + uri = uri.concat("?doAs=" + currentUserLoginId); + } + + final WebResource r = c.resource(uri); + final String jsonString = JsonUtils.objectToJson(vXKey); + + try { + String response; + + if (!isKerberos) { + response = r.accept(MediaType.APPLICATION_JSON_TYPE).type(MediaType.APPLICATION_JSON_TYPE).post(String.class, jsonString); + } else { + Subject sub = getSubjectForKerberos(provider); + + response = Subject.doAs(sub, (PrivilegedAction) () -> r.accept(MediaType.APPLICATION_JSON_TYPE).type(MediaType.APPLICATION_JSON_TYPE).post(String.class, jsonString)); + } + + logger.debug("Create RESPONSE: [{}]", response); + + ret = JsonUtils.jsonToObject(response, VXKmsKey.class); + + return ret; + } catch (Exception e) { + if (e instanceof UniformInterfaceException || i == providers.length - 1) { + throw e; + } else { + continue; + } + } + } + } + + return ret; + } + + public VXKmsKey getKey(String provider, String name) throws Exception { + String[] providers = null; + + try { + providers = getKMSURL(provider); + } catch (Exception e) { + logger.error("getKey({}, {}) failed", provider, name, e); + } + + boolean isKerberos = false; + + try { + isKerberos = checkKerberos(); + } catch (Exception e1) { + logger.error("checkKerberos({}) failed", provider, e1); + } + + if (providers != null) { + for (int i = 0; i < providers.length; i++) { + Client c = getClient(); + String keyRest = KMS_KEY_METADATA_URI.replaceAll(Pattern.quote("${alias}"), name); + String currentUserLoginId = StringUtil.getUTFEncodedString(ContextUtil.getCurrentUserLoginId()); + String uri = providers[i] + (providers[i].endsWith("/") ? keyRest : ("/" + keyRest)); + + if (!isKerberos) { + uri = uri.concat("?user.name=" + currentUserLoginId); + } else { + uri = uri.concat("?doAs=" + currentUserLoginId); + } + + final WebResource r = c.resource(uri); + + try { + String response; + + if (!isKerberos) { + response = r.accept(MediaType.APPLICATION_JSON_TYPE).type(MediaType.APPLICATION_JSON_TYPE).get(String.class); + } else { + Subject sub = getSubjectForKerberos(provider); + + response = Subject.doAs(sub, (PrivilegedAction) () -> r.accept(MediaType.APPLICATION_JSON_TYPE).type(MediaType.APPLICATION_JSON_TYPE).get(String.class)); + } + + logger.debug("RESPONSE: [{}]", response); + + return JsonUtils.jsonToObject(response, VXKmsKey.class); + } catch (Exception e) { + if (e instanceof UniformInterfaceException || i == providers.length - 1) { + throw e; + } else { + continue; + } + } + } + } + + return null; + } + + public VXKmsKey getKeyFromUri(String provider, String name, boolean isKerberos, String repoName) throws Exception { + Client c = getClient(); + String keyRest = KMS_KEY_METADATA_URI.replaceAll(Pattern.quote("${alias}"), name); + String currentUserLoginId = StringUtil.getUTFEncodedString(ContextUtil.getCurrentUserLoginId()); + String uri = provider + (provider.endsWith("/") ? keyRest : ("/" + keyRest)); + + if (!isKerberos) { + uri = uri.concat("?user.name=" + currentUserLoginId); + } else { + uri = uri.concat("?doAs=" + currentUserLoginId); + } + + final WebResource r = c.resource(uri); + String response; + + if (!isKerberos) { + response = r.accept(MediaType.APPLICATION_JSON_TYPE).type(MediaType.APPLICATION_JSON_TYPE).get(String.class); + } else { + Subject sub = getSubjectForKerberos(repoName); + + response = Subject.doAs(sub, (PrivilegedAction) () -> r.accept(MediaType.APPLICATION_JSON_TYPE).type(MediaType.APPLICATION_JSON_TYPE).get(String.class)); + } + + logger.debug("RESPONSE: [{}]", response); + + return JsonUtils.jsonToObject(response, VXKmsKey.class); + } + + public VXKmsKeyList getFilteredKeyList(HttpServletRequest request, VXKmsKeyList vXKmsKeyList) { + List sortFields = new ArrayList<>(); + + sortFields.add(new SortField(KeySearchFilter.KEY_NAME, KeySearchFilter.KEY_NAME)); + + KeySearchFilter filter = getKeySearchFilter(request, sortFields); + + Predicate pred = getPredicate(filter); + + if (pred != null) { + CollectionUtils.filter(vXKmsKeyList.getVXKeys(), pred); + } + + return vXKmsKeyList; + } + + private String[] getKMSURL(String name) throws Exception { + String[] providers; + + try { + RangerService rangerService = svcStore.getServiceByName(name); + + if (rangerService != null) { + String kmsUrl = rangerService.getConfigs().get(KMS_URL_CONFIG); + String dbKmsUrl = kmsUrl; + + if (providerList.containsKey(kmsUrl)) { + kmsUrl = providerList.get(kmsUrl); + } else { + providerList.put(kmsUrl, kmsUrl); + } + + providers = createProvider(dbKmsUrl, kmsUrl); + } else { + throw new Exception("Service " + name + " not found"); + } + } catch (Exception excp) { + logger.error("getServiceByName({}) failed", name, excp); + + throw new Exception("getServiceByName(" + name + ") failed", excp); + } + + if (providers == null) { + throw new Exception("Providers for service " + name + " not found"); + } + + return providers; + } + + private String[] createProvider(String dbKmsUrl, String uri) throws IOException, URISyntaxException { + URI providerUri = new URI(uri); + URL origUrl = new URL(extractKMSPath(providerUri).toString()); + String authority = origUrl.getAuthority(); + + // check for ';' which delimits the backup hosts + if (StringUtils.isEmpty(authority)) { + throw new IOException("No valid authority in kms uri [" + origUrl + "]"); + } + + // Check if port is present in authority + // In the current scheme, all hosts have to run on the same port + int port = -1; + String hostsPart = authority; + + if (authority.contains(":")) { + String[] t = authority.split(":"); + + try { + port = Integer.parseInt(t[1]); + } catch (Exception e) { + throw new IOException("Could not parse port in kms uri [" + origUrl + "]"); + } + + hostsPart = t[0]; + } + + return createProvider(dbKmsUrl, providerUri, origUrl, port, hostsPart); + } + + private static Path extractKMSPath(URI uri) { + return ProviderUtils.unnestUri(uri); + } + + private String[] createProvider(String dbkmsUrl, URI providerUri, URL origUrl, int port, String hostsPart) throws IOException { + String[] hosts = hostsPart.split(";"); + String[] providers = new String[hosts.length]; + + if (hosts.length == 1) { + providers[0] = origUrl.toString(); + } else { + String providerNext = providerUri.getScheme() + "://" + origUrl.getProtocol() + "@"; + + for (int i = nextProvider; i < hosts.length; i++) { + providerNext = providerNext + hosts[i]; + + if (i != (hosts.length - 1)) { + providerNext = providerNext + ";"; + } + } + + for (int i = 0; i < nextProvider && i < hosts.length; i++) { + providerNext = providerNext + ";" + hosts[i]; + } + + if (nextProvider != hosts.length - 1) { + nextProvider = nextProvider + 1; + } else { + nextProvider = 0; + } + + providerNext = providerNext + ":" + port + origUrl.getPath(); + + providerList.put(dbkmsUrl, providerNext); + + for (int i = 0; i < hosts.length; i++) { + try { + String url = origUrl.getProtocol() + "://" + hosts[i] + ":" + port + origUrl.getPath(); + + providers[i] = new URI(url).toString(); + } catch (URISyntaxException e) { + throw new IOException("Could not Prase KMS URL..", e); + } + } + } + + return providers; + } + + private Subject getSubjectForKerberos(String provider) throws Exception { + String userName = getKMSUserName(provider); + String password = getKMSPassword(provider); + String nameRules = PropertiesUtil.getProperty(NAME_RULES); + + if (StringUtils.isEmpty(nameRules)) { + KerberosName.setRules("DEFAULT"); + + nameRules = "DEFAULT"; + } else { + KerberosName.setRules(nameRules); + } + + Subject sub; + String rangerPrincipal = SecureClientLogin.getPrincipal(PropertiesUtil.getProperty(ADMIN_USER_PRINCIPAL), PropertiesUtil.getProperty(HOST_NAME)); + + if (checkKerberos()) { + if (SecureClientLogin.isKerberosCredentialExists(rangerPrincipal, PropertiesUtil.getProperty(ADMIN_USER_KEYTAB))) { + sub = SecureClientLogin.loginUserFromKeytab(rangerPrincipal, PropertiesUtil.getProperty(ADMIN_USER_KEYTAB), nameRules); + } else { + sub = SecureClientLogin.loginUserWithPassword(userName, password); + } + } else { + sub = SecureClientLogin.login(userName); + } + + return sub; + } + + private String getKMSPassword(String srvName) throws Exception { + XXService rangerService = rangerDaoManagerBase.getXXService().findByName(srvName); + XXServiceConfigMap xxConfigMap = rangerDaoManagerBase.getXXServiceConfigMap().findByServiceAndConfigKey(rangerService.getId(), KMS_PASSWORD); + String encryptedPwd = xxConfigMap.getConfigvalue(); + + return PasswordUtils.decryptPassword(encryptedPwd); + } + + private String getKMSUserName(String srvName) throws Exception { + RangerService rangerService = svcStore.getServiceByName(srvName); + + return rangerService.getConfigs().get(KMS_USERNAME); + } + + private boolean checkKerberos() { + return KERBEROS_TYPE.equalsIgnoreCase(PropertiesUtil.getProperty(RANGER_AUTH_TYPE, "simple")); + } + + private synchronized Client getClient() { + ClientConfig cc = new DefaultClientConfig(); + + cc.getProperties().put(ClientConfig.PROPERTY_FOLLOW_REDIRECTS, true); + + return Client.create(cc); + } + + private Predicate getPredicate(KeySearchFilter filter) { + if (filter == null || filter.isEmpty()) { + return null; + } + + List predicates = new ArrayList<>(); + + addPredicateForKeyName(filter.getParam(KeySearchFilter.KEY_NAME), predicates); + + return CollectionUtils.isEmpty(predicates) ? null : PredicateUtils.allPredicate(predicates); + } + + private Predicate addPredicateForKeyName(final String name, List predicates) { + if (StringUtils.isEmpty(name)) { + return null; + } + + Predicate ret = object -> { + if (object == null) { + return false; + } + + boolean ret1 = false; + + if (object instanceof VXKmsKey) { + VXKmsKey vXKmsKey = (VXKmsKey) object; + + if (StringUtils.isEmpty(vXKmsKey.getName())) { + ret1 = true; + } else { + ret1 = vXKmsKey.getName().contains(name); + } + } else { + ret1 = true; + } + + return ret1; + }; + + if (predicates != null) { + predicates.add(ret); + } + + return ret; + } + + private KeySearchFilter getKeySearchFilter(HttpServletRequest request, List sortFields) { + if (request == null) { + return null; + } + + KeySearchFilter ret = new KeySearchFilter(); + + if (MapUtils.isEmpty(request.getParameterMap())) { + ret.setParams(new HashMap<>()); + } + + ret.setParam(KeySearchFilter.KEY_NAME, request.getParameter(KeySearchFilter.KEY_NAME)); + + extractCommonCriteriasForFilter(request, ret, sortFields); + + return ret; + } + + private KeySearchFilter extractCommonCriteriasForFilter(HttpServletRequest request, KeySearchFilter ret, List sortFields) { + int startIndex = restErrorUtil.parseInt(request.getParameter(KeySearchFilter.START_INDEX), 0, "Invalid value for parameter startIndex", MessageEnums.INVALID_INPUT_DATA, null, KeySearchFilter.START_INDEX); + + ret.setStartIndex(startIndex); + + int pageSize = restErrorUtil.parseInt(request.getParameter(KeySearchFilter.PAGE_SIZE), configUtil.getDefaultMaxRows(), "Invalid value for parameter pageSize", MessageEnums.INVALID_INPUT_DATA, null, KeySearchFilter.PAGE_SIZE); + + ret.setMaxRows(pageSize); + + ret.setGetCount(restErrorUtil.parseBoolean(request.getParameter("getCount"), true)); + + String sortBy = restErrorUtil.validateString(request.getParameter(KeySearchFilter.SORT_BY), StringUtil.VALIDATION_ALPHA, "Invalid value for parameter sortBy", MessageEnums.INVALID_INPUT_DATA, null, KeySearchFilter.SORT_BY); + boolean sortSet = false; + + if (!StringUtils.isEmpty(sortBy)) { + for (SortField sortField : sortFields) { + if (sortField.getParamName().equalsIgnoreCase(sortBy)) { + ret.setSortBy(sortField.getParamName()); + + String sortType = restErrorUtil.validateString(request.getParameter("sortType"), StringUtil.VALIDATION_ALPHA, "Invalid value for parameter sortType", MessageEnums.INVALID_INPUT_DATA, null, "sortType"); + + ret.setSortType(sortType); + + sortSet = true; + + break; + } + } + } + + if (!sortSet && !StringUtils.isEmpty(sortBy)) { + logger.info("Invalid or unsupported sortBy field passed. sortBy={}", sortBy, new Throwable()); + } + + if (ret.getParams() == null) { + ret.setParams(new HashMap<>()); + } - private static final Logger logger = LoggerFactory.getLogger(KmsKeyMgr.class); - - private static final String KMS_KEY_LIST_URI = "v1/keys/names"; //GET - private static final String KMS_ADD_KEY_URI = "v1/keys"; //POST - private static final String KMS_ROLL_KEY_URI = "v1/key/${alias}"; //POST - private static final String KMS_DELETE_KEY_URI = "v1/key/${alias}"; //DELETE - private static final String KMS_KEY_METADATA_URI = "v1/key/${alias}/_metadata"; //GET - private static final String KMS_URL_CONFIG = "provider"; - private static final String KMS_PASSWORD = "password"; - private static final String KMS_USERNAME = "username"; - private static Map providerList = new HashMap(); - private static int nextProvider = 0; - static final String NAME_RULES = "hadoop.security.auth_to_local"; - static final String RANGER_AUTH_TYPE = "hadoop.security.authentication"; - private static final String KERBEROS_TYPE = "kerberos"; - private static final String ADMIN_USER_PRINCIPAL = "ranger.admin.kerberos.principal"; - private static final String ADMIN_USER_KEYTAB = "ranger.admin.kerberos.keytab"; - static final String HOST_NAME = "ranger.service.host"; - - @Autowired - ServiceDBStore svcStore; - - @Autowired - RESTErrorUtil restErrorUtil; - - @Autowired - RangerConfigUtil configUtil; - - @Autowired - RangerDaoManagerBase rangerDaoManagerBase; - - @Autowired - RangerBizUtil rangerBizUtil; - - @SuppressWarnings("unchecked") - public VXKmsKeyList searchKeys(HttpServletRequest request, String repoName) throws Exception { - String providers[] = null; - try { - providers = getKMSURL(repoName); - } catch (Exception e) { - logger.error("getKey(" + repoName + ") failed", e); - } - List vXKeys = new ArrayList(); - VXKmsKeyList vxKmsKeyList = new VXKmsKeyList(); - List keys = null; - String connProvider = null; - boolean isKerberos=false; - try { - isKerberos = checkKerberos(); - } catch (Exception e1) { - logger.error("checkKerberos(" + repoName + ") failed", e1); - } - if(providers!=null){ - for (int i = 0; i < providers.length; i++) { - Client c = getClient(); - String currentUserLoginId = StringUtil.getUTFEncodedString(ContextUtil.getCurrentUserLoginId()); - String keyLists = KMS_KEY_LIST_URI.replaceAll( - Pattern.quote("${userName}"), currentUserLoginId); - connProvider = providers[i]; - String uri = providers[i] - + (providers[i].endsWith("/") ? keyLists : ("/" + keyLists)); - if(!isKerberos){ - uri = uri.concat("?user.name="+currentUserLoginId); - }else{ - uri = uri.concat("?doAs="+currentUserLoginId); - } - - final WebResource r = c.resource(uri); - try { - String response = null; - if(!isKerberos){ - response = r.accept(MediaType.APPLICATION_JSON_TYPE).type(MediaType.APPLICATION_JSON_TYPE).get(String.class); - }else{ - Subject sub = getSubjectForKerberos(repoName); - response = Subject.doAs(sub, new PrivilegedAction() { - @Override - public String run() { - return r.accept(MediaType.APPLICATION_JSON_TYPE).type(MediaType.APPLICATION_JSON_TYPE).get(String.class); - } - }); - } - - logger.debug(" Search Key RESPONSE: [" + response + "]"); - keys = JsonUtils.jsonToListString(response); - Collections.sort(keys); - VXKmsKeyList vxKmsKeyList2 = new VXKmsKeyList(); - List vXKeys2 = new ArrayList(); - for (String name : keys) { - VXKmsKey key = new VXKmsKey(); - key.setName(name); - vXKeys2.add(key); - } - vxKmsKeyList2.setVXKeys(vXKeys2); - vxKmsKeyList = getFilteredKeyList(request, vxKmsKeyList2); - break; - } catch (Exception e) { - if (e instanceof UniformInterfaceException || i == providers.length - 1) - throw e; - else - continue; - } - } - } - //details - if (vxKmsKeyList != null && vxKmsKeyList.getVXKeys() != null && !vxKmsKeyList.getVXKeys().isEmpty()) { - List lstKMSKey = vxKmsKeyList.getVXKeys(); - int startIndex=restErrorUtil.parseInt( - request.getParameter("startIndex"), 0, - "Invalid value for parameter startIndex", - MessageEnums.INVALID_INPUT_DATA, null, "startIndex"); - startIndex = startIndex < 0 ? 0 : startIndex; - - int pageSize=restErrorUtil.parseInt( - request.getParameter("pageSize"), 0, - "Invalid value for parameter pageSize", - MessageEnums.INVALID_INPUT_DATA, null, "pageSize"); - pageSize = pageSize < 0 ? 0 : pageSize; - - vxKmsKeyList.setResultSize(lstKMSKey.size()); - vxKmsKeyList.setTotalCount(lstKMSKey.size()); - if((startIndex+pageSize) <= lstKMSKey.size()){ - lstKMSKey = lstKMSKey.subList(startIndex, (startIndex+pageSize));} - else{ - startIndex = startIndex >= lstKMSKey.size() ? 0 : startIndex; - lstKMSKey = lstKMSKey.subList(startIndex, lstKMSKey.size()); - } - if(CollectionUtils.isNotEmpty(lstKMSKey)){ - for (VXKmsKey kmsKey : lstKMSKey) { - if(kmsKey!=null){ - VXKmsKey key = getKeyFromUri(connProvider, kmsKey.getName(), isKerberos, repoName); - vXKeys.add(key); - } - } - } - vxKmsKeyList.setStartIndex(startIndex); - vxKmsKeyList.setPageSize(pageSize); - } - if(vxKmsKeyList!=null){ - vxKmsKeyList.setVXKeys(vXKeys); - } - return vxKmsKeyList; - } - - public VXKmsKey rolloverKey(String provider, VXKmsKey vXKey) throws Exception{ - String providers[] = null; - rangerBizUtil.blockAuditorRoleUser(); - try { - providers = getKMSURL(provider); - } catch (Exception e) { - logger.error("rolloverKey(" + provider + ", " + vXKey.getName() + ") failed", e); - } - VXKmsKey ret = null; - boolean isKerberos=false; - try { - isKerberos = checkKerberos(); - } catch (Exception e1) { - logger.error("checkKerberos(" + provider + ") failed", e1); - } - if(providers!=null){ - for (int i = 0; i < providers.length; i++) { - Client c = getClient(); - String rollRest = KMS_ROLL_KEY_URI.replaceAll(Pattern.quote("${alias}"), vXKey.getName()); - String currentUserLoginId = StringUtil.getUTFEncodedString(ContextUtil.getCurrentUserLoginId()); - String uri = providers[i] + (providers[i].endsWith("/") ? rollRest : ("/" + rollRest)); - if(!isKerberos){ - uri = uri.concat("?user.name="+currentUserLoginId); - }else{ - uri = uri.concat("?doAs="+currentUserLoginId); - } - final WebResource r = c.resource(uri); - final String jsonString = JsonUtils.objectToJson(vXKey); - try { - String response = null; - if(!isKerberos){ - response = r.accept(MediaType.APPLICATION_JSON_TYPE).type(MediaType.APPLICATION_JSON_TYPE).post(String.class, jsonString);} - else{ - Subject sub = getSubjectForKerberos(provider); - response = Subject.doAs(sub, new PrivilegedAction() { - @Override - public String run() { - return r.accept(MediaType.APPLICATION_JSON_TYPE).type(MediaType.APPLICATION_JSON_TYPE).post(String.class, jsonString); - } - }); - } - logger.debug("Roll RESPONSE: [" + response + "]"); - ret = JsonUtils.jsonToObject(response, VXKmsKey.class); - break; - } catch (Exception e) { - if (e instanceof UniformInterfaceException || i == providers.length - 1) - throw e; - else - continue; - } - } - } - return ret; - } - - public void deleteKey(String provider, String name) throws Exception{ - String providers[] = null; - rangerBizUtil.blockAuditorRoleUser(); - try { - providers = getKMSURL(provider); - } catch (Exception e) { - logger.error("deleteKey(" + provider + ", " + name + ") failed", e); - } - boolean isKerberos=false; - try { - isKerberos = checkKerberos(); - } catch (Exception e1) { - logger.error("checkKerberos(" + provider + ") failed", e1); - } - if(providers!=null){ - for (int i = 0; i < providers.length; i++) { - Client c = getClient(); - String deleteRest = KMS_DELETE_KEY_URI.replaceAll(Pattern.quote("${alias}"), name); - String currentUserLoginId = StringUtil.getUTFEncodedString(ContextUtil.getCurrentUserLoginId()); - String uri = providers[i] + (providers[i].endsWith("/") ? deleteRest : ("/" + deleteRest)); - if(!isKerberos){ - uri = uri.concat("?user.name="+currentUserLoginId); - }else{ - uri = uri.concat("?doAs="+currentUserLoginId); - } - final WebResource r = c.resource(uri); - try { - String response = null; - if(!isKerberos){ - response = r.delete(String.class); - }else{ - Subject sub = getSubjectForKerberos(provider); - response = Subject.doAs(sub, new PrivilegedAction() { - @Override - public String run() { - return r.delete(String.class); - } - }); - } - logger.debug("delete RESPONSE: [" + response + "]"); - break; - } catch (Exception e) { - if (e instanceof UniformInterfaceException || i == providers.length - 1) - throw e; - else - continue; - } - } - } - } - - public VXKmsKey createKey(String provider, VXKmsKey vXKey) throws Exception{ - String providers[] = null; - rangerBizUtil.blockAuditorRoleUser(); - try { - providers = getKMSURL(provider); - } catch (Exception e) { - logger.error("createKey(" + provider + ", " + vXKey.getName() - + ") failed", e); - } - VXKmsKey ret = null; - boolean isKerberos=false; - try { - isKerberos = checkKerberos(); - } catch (Exception e1) { - logger.error("checkKerberos(" + provider + ") failed", e1); - } - if(providers!=null){ - for (int i = 0; i < providers.length; i++) { - Client c = getClient(); - String currentUserLoginId = StringUtil.getUTFEncodedString(ContextUtil.getCurrentUserLoginId()); - String uri = providers[i] + (providers[i].endsWith("/") ? KMS_ADD_KEY_URI : ("/" + KMS_ADD_KEY_URI)); - if(!isKerberos){ - uri = uri.concat("?user.name="+currentUserLoginId); - }else{ - uri = uri.concat("?doAs="+currentUserLoginId); - } - final WebResource r = c.resource(uri); - final String jsonString = JsonUtils.objectToJson(vXKey); - try { - String response = null; - if(!isKerberos){ - response = r.accept(MediaType.APPLICATION_JSON_TYPE).type(MediaType.APPLICATION_JSON_TYPE).post(String.class, jsonString); - }else{ - Subject sub = getSubjectForKerberos(provider); - response = Subject.doAs(sub, new PrivilegedAction() { - @Override - public String run() { - return r.accept(MediaType.APPLICATION_JSON_TYPE).type(MediaType.APPLICATION_JSON_TYPE).post(String.class, jsonString); - } - }); - } - logger.debug("Create RESPONSE: [" + response + "]"); - ret = JsonUtils.jsonToObject(response, VXKmsKey.class); - return ret; - } catch (Exception e) { - if (e instanceof UniformInterfaceException || i == providers.length - 1) - throw e; - else - continue; - } - } - } - return ret; - } - - public VXKmsKey getKey(String provider, String name) throws Exception{ - String providers[] = null; - try { - providers = getKMSURL(provider); - } catch (Exception e) { - logger.error("getKey(" + provider + ", " + name + ") failed", e); - } - boolean isKerberos=false; - try { - isKerberos = checkKerberos(); - } catch (Exception e1) { - logger.error("checkKerberos(" + provider + ") failed", e1); - } - if(providers!=null){ - for (int i = 0; i < providers.length; i++) { - Client c = getClient(); - String keyRest = KMS_KEY_METADATA_URI.replaceAll(Pattern.quote("${alias}"), name); - String currentUserLoginId = StringUtil.getUTFEncodedString(ContextUtil.getCurrentUserLoginId()); - String uri = providers[i] + (providers[i].endsWith("/") ? keyRest : ("/" + keyRest)); - if(!isKerberos){ - uri = uri.concat("?user.name="+currentUserLoginId); - }else{ - uri = uri.concat("?doAs="+currentUserLoginId); - } - final WebResource r = c.resource(uri); - try { - String response = null; - if(!isKerberos){ - response = r.accept(MediaType.APPLICATION_JSON_TYPE).type(MediaType.APPLICATION_JSON_TYPE).get(String.class); - }else{ - Subject sub = getSubjectForKerberos(provider); - response = Subject.doAs(sub, new PrivilegedAction() { - @Override - public String run() { - return r.accept(MediaType.APPLICATION_JSON_TYPE).type(MediaType.APPLICATION_JSON_TYPE).get(String.class); - } - }); - } - logger.debug("RESPONSE: [" + response + "]"); - VXKmsKey key = JsonUtils.jsonToObject(response, VXKmsKey.class); - return key; - } catch (Exception e) { - if (e instanceof UniformInterfaceException || i == providers.length - 1) - throw e; - else - continue; - } - } - } - return null; - } - - public VXKmsKey getKeyFromUri(String provider, String name, boolean isKerberos, String repoName) throws Exception { - Client c = getClient(); - String keyRest = KMS_KEY_METADATA_URI.replaceAll(Pattern.quote("${alias}"), name); - String currentUserLoginId = StringUtil.getUTFEncodedString(ContextUtil.getCurrentUserLoginId()); - String uri = provider + (provider.endsWith("/") ? keyRest : ("/" + keyRest)); - if(!isKerberos){ - uri = uri.concat("?user.name="+currentUserLoginId); - }else{ - uri = uri.concat("?doAs="+currentUserLoginId); - } - final WebResource r = c.resource(uri); - String response = null; - if(!isKerberos){ - response = r.accept(MediaType.APPLICATION_JSON_TYPE).type(MediaType.APPLICATION_JSON_TYPE).get(String.class); - }else{ - Subject sub = getSubjectForKerberos(repoName); - response = Subject.doAs(sub, new PrivilegedAction() { - @Override - public String run() { - return r.accept(MediaType.APPLICATION_JSON_TYPE).type(MediaType.APPLICATION_JSON_TYPE).get(String.class); - } - }); - } - logger.debug("RESPONSE: [" + response + "]"); - VXKmsKey key = JsonUtils.jsonToObject(response, VXKmsKey.class); - return key; - } - - private String[] getKMSURL(String name) throws Exception{ - String providers[] = null; - RangerService rangerService = null; - try { - rangerService = svcStore.getServiceByName(name); - if(rangerService!=null){ - String kmsUrl = rangerService.getConfigs().get(KMS_URL_CONFIG); - String dbKmsUrl = kmsUrl; - if(providerList.containsKey(kmsUrl)){ - kmsUrl = providerList.get(kmsUrl); - }else{ - providerList.put(kmsUrl, kmsUrl); - } - providers = createProvider(dbKmsUrl,kmsUrl); - }else{ - throw new Exception("Service " + name + " not found"); - } - } catch (Exception excp) { - logger.error("getServiceByName(" + name + ") failed", excp); - throw new Exception("getServiceByName(" + name + ") failed", excp); - } - if (providers == null) { - throw new Exception("Providers for service " + name + " not found"); - } - return providers; - } - - private String[] createProvider(String dbKmsUrl, String uri) throws IOException,URISyntaxException { - URI providerUri = new URI(uri); - URL origUrl = new URL(extractKMSPath(providerUri).toString()); - String authority = origUrl.getAuthority(); - // check for ';' which delimits the backup hosts - if (StringUtils.isEmpty(authority)) { - throw new IOException("No valid authority in kms uri [" + origUrl+ "]"); - } - // Check if port is present in authority - // In the current scheme, all hosts have to run on the same port - int port = -1; - String hostsPart = authority; - if (authority.contains(":")) { - String[] t = authority.split(":"); - try { - port = Integer.parseInt(t[1]); - } catch (Exception e) { - throw new IOException("Could not parse port in kms uri [" - + origUrl + "]"); - } - hostsPart = t[0]; - } - return createProvider(dbKmsUrl, providerUri, origUrl, port, hostsPart); - } - - private static Path extractKMSPath(URI uri) throws MalformedURLException,IOException { - return ProviderUtils.unnestUri(uri); - } - - private String[] createProvider(String dbkmsUrl, URI providerUri, URL origUrl, int port, - String hostsPart) throws IOException { - String[] hosts = hostsPart.split(";"); - String[] providers = new String[hosts.length]; - if (hosts.length == 1) { - providers[0] = origUrl.toString(); - } else { - String providerNext=providerUri.getScheme()+"://"+origUrl.getProtocol()+"@"; - for(int i=nextProvider; i sortFields = new ArrayList(); - sortFields.add(new SortField(KeySearchFilter.KEY_NAME, KeySearchFilter.KEY_NAME)); - - KeySearchFilter filter = getKeySearchFilter(request, sortFields); - - Predicate pred = getPredicate(filter); - - if(pred != null) { - CollectionUtils.filter(vXKmsKeyList.getVXKeys(), pred); - } - return vXKmsKeyList; - } - - private Predicate getPredicate(KeySearchFilter filter) { - if(filter == null || filter.isEmpty()) { - return null; - } - - List predicates = new ArrayList(); - - addPredicateForKeyName(filter.getParam(KeySearchFilter.KEY_NAME), predicates); - - Predicate ret = CollectionUtils.isEmpty(predicates) ? null : PredicateUtils.allPredicate(predicates); - - return ret; - } - - private Predicate addPredicateForKeyName(final String name, List predicates) { - if(StringUtils.isEmpty(name)) { - return null; - } - - Predicate ret = new Predicate() { - @Override - public boolean evaluate(Object object) { - if(object == null) { - return false; - } - - boolean ret = false; - - if(object instanceof VXKmsKey) { - VXKmsKey vXKmsKey = (VXKmsKey)object; - if(StringUtils.isEmpty(vXKmsKey.getName())) { - ret = true; - }else{ - ret = vXKmsKey.getName().contains(name); - } - } else { - ret = true; - } - - return ret; - } - }; - - if(predicates != null) { - predicates.add(ret); - } - - return ret; - } - - private KeySearchFilter getKeySearchFilter(HttpServletRequest request, List sortFields) { - if (request == null) { - return null; - } - KeySearchFilter ret = new KeySearchFilter(); - - if (MapUtils.isEmpty(request.getParameterMap())) { - ret.setParams(new HashMap()); - } - - ret.setParam(KeySearchFilter.KEY_NAME, request.getParameter(KeySearchFilter.KEY_NAME)); - extractCommonCriteriasForFilter(request, ret, sortFields); - return ret; - } - - private KeySearchFilter extractCommonCriteriasForFilter(HttpServletRequest request, KeySearchFilter ret, List sortFields) { - int startIndex = restErrorUtil.parseInt(request.getParameter(KeySearchFilter.START_INDEX), 0, - "Invalid value for parameter startIndex", MessageEnums.INVALID_INPUT_DATA, null, - KeySearchFilter.START_INDEX); - ret.setStartIndex(startIndex); - - int pageSize = restErrorUtil.parseInt(request.getParameter(KeySearchFilter.PAGE_SIZE), - configUtil.getDefaultMaxRows(), "Invalid value for parameter pageSize", - MessageEnums.INVALID_INPUT_DATA, null, KeySearchFilter.PAGE_SIZE); - ret.setMaxRows(pageSize); - - ret.setGetCount(restErrorUtil.parseBoolean(request.getParameter("getCount"), true)); - String sortBy = restErrorUtil.validateString(request.getParameter(KeySearchFilter.SORT_BY), - StringUtil.VALIDATION_ALPHA, "Invalid value for parameter sortBy", MessageEnums.INVALID_INPUT_DATA, - null, KeySearchFilter.SORT_BY); - boolean sortSet = false; - if (!StringUtils.isEmpty(sortBy)) { - for (SortField sortField : sortFields) { - if (sortField.getParamName().equalsIgnoreCase(sortBy)) { - ret.setSortBy(sortField.getParamName()); - String sortType = restErrorUtil.validateString(request.getParameter("sortType"), - StringUtil.VALIDATION_ALPHA, "Invalid value for parameter sortType", - MessageEnums.INVALID_INPUT_DATA, null, "sortType"); - ret.setSortType(sortType); - sortSet = true; - break; - } - } - } - - if (!sortSet && !StringUtils.isEmpty(sortBy)) { - logger.info("Invalid or unsupported sortBy field passed. sortBy=" + sortBy, new Throwable()); - } - - if(ret.getParams() == null) { - ret.setParams(new HashMap()); - } - return ret; - } + return ret; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/biz/PolicyRefUpdater.java b/security-admin/src/main/java/org/apache/ranger/biz/PolicyRefUpdater.java index ed0992604d..4ed8ef9105 100644 --- a/security-admin/src/main/java/org/apache/ranger/biz/PolicyRefUpdater.java +++ b/security-admin/src/main/java/org/apache/ranger/biz/PolicyRefUpdater.java @@ -18,11 +18,6 @@ */ package org.apache.ranger.biz; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang.StringUtils; import org.apache.ranger.common.RESTErrorUtil; @@ -65,476 +60,501 @@ import javax.servlet.http.HttpServletResponse; -import static org.apache.ranger.service.RangerBaseModelService.OPERATION_CREATE_CONTEXT; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import static org.apache.ranger.service.RangerBaseModelService.OPERATION_CREATE_CONTEXT; @Component public class PolicyRefUpdater { + private static final Logger LOG = LoggerFactory.getLogger(PolicyRefUpdater.class); + + @Autowired + RangerDaoManager daoMgr; + + @Autowired + RangerAuditFields rangerAuditFields; + + @Autowired + XUserMgr xUserMgr; + + @Autowired + RoleDBStore roleStore; + + @Autowired + RangerBizUtil rangerBizUtil; + + @Autowired + XGroupService xGroupService; + + @Autowired + RangerTransactionSynchronizationAdapter rangerTransactionSynchronizationAdapter; + + @Autowired + RESTErrorUtil restErrorUtil; + + public static List> getAllPolicyItems(RangerPolicy policy) { + List> ret = new ArrayList<>(); + + if (CollectionUtils.isNotEmpty(policy.getPolicyItems())) { + ret.add(policy.getPolicyItems()); + } + + if (CollectionUtils.isNotEmpty(policy.getDenyPolicyItems())) { + ret.add(policy.getDenyPolicyItems()); + } + + if (CollectionUtils.isNotEmpty(policy.getAllowExceptions())) { + ret.add(policy.getAllowExceptions()); + } + + if (CollectionUtils.isNotEmpty(policy.getDenyExceptions())) { + ret.add(policy.getDenyExceptions()); + } + + if (CollectionUtils.isNotEmpty(policy.getDataMaskPolicyItems())) { + ret.add(policy.getDataMaskPolicyItems()); + } + + if (CollectionUtils.isNotEmpty(policy.getRowFilterPolicyItems())) { + ret.add(policy.getRowFilterPolicyItems()); + } + + return ret; + } + + public void createNewPolMappingForRefTable(RangerPolicy policy, XXPolicy xPolicy, XXServiceDef xServiceDef, boolean createPrincipalsIfAbsent) throws Exception { + if (policy == null) { + return; + } + + cleanupRefTables(policy); + + final Set resourceNames = policy.getResources().keySet(); + final Set roleNames = new HashSet<>(); + final Set groupNames = new HashSet<>(); + final Set userNames = new HashSet<>(); + final Set accessTypes = new HashSet<>(); + final Set conditionTypes = new HashSet<>(); + final Set dataMaskTypes = new HashSet<>(); + boolean oldBulkMode = RangerBizUtil.isBulkMode(); + + List rangerPolicyConditions = policy.getConditions(); + + if (CollectionUtils.isNotEmpty(rangerPolicyConditions)) { + for (RangerPolicy.RangerPolicyItemCondition condition : rangerPolicyConditions) { + conditionTypes.add(condition.getType()); + } + } + + for (List policyItems : getAllPolicyItems(policy)) { + if (CollectionUtils.isEmpty(policyItems)) { + continue; + } + + for (RangerPolicyItem policyItem : policyItems) { + roleNames.addAll(policyItem.getRoles()); + groupNames.addAll(policyItem.getGroups()); + userNames.addAll(policyItem.getUsers()); + + if (CollectionUtils.isNotEmpty(policyItem.getAccesses())) { + for (RangerPolicyItemAccess access : policyItem.getAccesses()) { + accessTypes.add(access.getType()); + } + } + + if (CollectionUtils.isNotEmpty(policyItem.getConditions())) { + for (RangerPolicyItemCondition condition : policyItem.getConditions()) { + conditionTypes.add(condition.getType()); + } + } + + if (policyItem instanceof RangerDataMaskPolicyItem) { + RangerPolicyItemDataMaskInfo dataMaskInfo = ((RangerDataMaskPolicyItem) policyItem).getDataMaskInfo(); + + dataMaskTypes.add(dataMaskInfo.getDataMaskType()); + } + } + } + + List xPolResources = new ArrayList<>(); + + for (String resource : resourceNames) { + XXResourceDef xResDef = daoMgr.getXXResourceDef().findByNameAndPolicyId(resource, policy.getId()); + + if (xResDef == null) { + throw new Exception(resource + ": is not a valid resource-type. policy='" + policy.getName() + "' service='" + policy.getService() + "'"); + } + + XXPolicyRefResource xPolRes = rangerAuditFields.populateAuditFields(new XXPolicyRefResource(), xPolicy); + + xPolRes.setPolicyId(policy.getId()); + xPolRes.setResourceDefId(xResDef.getId()); + xPolRes.setResourceName(resource); + + xPolResources.add(xPolRes); + } + + daoMgr.getXXPolicyRefResource().batchCreate(xPolResources); + + if (createPrincipalsIfAbsent && !rangerBizUtil.checkAdminAccess()) { + LOG.warn("policy={}: createPrincipalIfAbsent=true, but current user does not have admin privileges!", policy.getName()); + + createPrincipalsIfAbsent = false; + } + + List xPolRoles = new ArrayList<>(); + + for (String role : roleNames) { + if (StringUtils.isBlank(role)) { + continue; + } + + PolicyPrincipalAssociator associator = new PolicyPrincipalAssociator(PRINCIPAL_TYPE.ROLE, role, xPolicy); + + if (!associator.doAssociate(false)) { + if (createPrincipalsIfAbsent) { + rangerTransactionSynchronizationAdapter.executeOnTransactionCommit(associator); + } else { + VXResponse gjResponse = new VXResponse(); + + gjResponse.setStatusCode(HttpServletResponse.SC_BAD_REQUEST); + gjResponse.setMsgDesc("Operation denied. Role name: " + role + " specified in policy does not exist in ranger admin."); + + throw restErrorUtil.generateRESTException(gjResponse); + } + } + } + + RangerBizUtil.setBulkMode(oldBulkMode); + + daoMgr.getXXPolicyRefRole().batchCreate(xPolRoles); + + for (String group : groupNames) { + if (StringUtils.isBlank(group)) { + continue; + } + + PolicyPrincipalAssociator associator = new PolicyPrincipalAssociator(PRINCIPAL_TYPE.GROUP, group, xPolicy); + + if (!associator.doAssociate(false)) { + if (createPrincipalsIfAbsent) { + rangerTransactionSynchronizationAdapter.executeOnTransactionCommit(associator); + } else { + VXResponse gjResponse = new VXResponse(); + + gjResponse.setStatusCode(HttpServletResponse.SC_BAD_REQUEST); + gjResponse.setMsgDesc("Operation denied. Group name: " + group + " specified in policy does not exist in ranger admin."); + + throw restErrorUtil.generateRESTException(gjResponse); + } + } + } + + for (String user : userNames) { + if (StringUtils.isBlank(user)) { + continue; + } + + PolicyPrincipalAssociator associator = new PolicyPrincipalAssociator(PRINCIPAL_TYPE.USER, user, xPolicy); + + if (!associator.doAssociate(false)) { + if (createPrincipalsIfAbsent) { + rangerTransactionSynchronizationAdapter.executeOnTransactionCommit(associator); + } else { + VXResponse gjResponse = new VXResponse(); + + gjResponse.setStatusCode(HttpServletResponse.SC_BAD_REQUEST); + gjResponse.setMsgDesc("Operation denied. User name: " + user + " specified in policy does not exist in ranger admin."); + + throw restErrorUtil.generateRESTException(gjResponse); + } + } + } + + List xPolAccesses = new ArrayList<>(); + + // ignore built-in access-types while creating ref-table entries + accessTypes.removeAll(ServiceDefUtil.ACCESS_TYPE_MARKERS); + + for (String accessType : accessTypes) { + XXAccessTypeDef xAccTypeDef = daoMgr.getXXAccessTypeDef().findByNameAndServiceId(accessType, xPolicy.getService()); + + if (xAccTypeDef == null) { + throw new Exception(accessType + ": is not a valid access-type. policy='" + policy.getName() + "' service='" + policy.getService() + "'"); + } + + XXPolicyRefAccessType xPolAccess = rangerAuditFields.populateAuditFields(new XXPolicyRefAccessType(), xPolicy); + + xPolAccess.setPolicyId(policy.getId()); + xPolAccess.setAccessDefId(xAccTypeDef.getId()); + xPolAccess.setAccessTypeName(accessType); + + xPolAccesses.add(xPolAccess); + } + + daoMgr.getXXPolicyRefAccessType().batchCreate(xPolAccesses); + + List xPolConds = new ArrayList<>(); + + for (String condition : conditionTypes) { + XXPolicyConditionDef xPolCondDef = daoMgr.getXXPolicyConditionDef().findByServiceDefIdAndName(xServiceDef.getId(), condition); + + if (xPolCondDef == null) { + if (StringUtils.equalsIgnoreCase(condition, ServiceDefUtil.IMPLICIT_CONDITION_EXPRESSION_NAME)) { + continue; + } + + throw new Exception(condition + ": is not a valid condition-type. policy='" + xPolicy.getName() + "' service='" + xPolicy.getService() + "'"); + } + + XXPolicyRefCondition xPolCond = rangerAuditFields.populateAuditFields(new XXPolicyRefCondition(), xPolicy); + + xPolCond.setPolicyId(policy.getId()); + xPolCond.setConditionDefId(xPolCondDef.getId()); + xPolCond.setConditionName(condition); + + xPolConds.add(xPolCond); + } + + daoMgr.getXXPolicyRefCondition().batchCreate(xPolConds); + + List xxDataMaskInfos = new ArrayList<>(); + + for (String dataMaskType : dataMaskTypes) { + XXDataMaskTypeDef dataMaskDef = daoMgr.getXXDataMaskTypeDef().findByNameAndServiceId(dataMaskType, xPolicy.getService()); + + if (dataMaskDef == null) { + throw new Exception(dataMaskType + ": is not a valid datamask-type. policy='" + policy.getName() + "' service='" + policy.getService() + "'"); + } + + XXPolicyRefDataMaskType xxDataMaskInfo = new XXPolicyRefDataMaskType(); + + xxDataMaskInfo.setPolicyId(policy.getId()); + xxDataMaskInfo.setDataMaskDefId(dataMaskDef.getId()); + xxDataMaskInfo.setDataMaskTypeName(dataMaskType); + + xxDataMaskInfos.add(xxDataMaskInfo); + } + + daoMgr.getXXPolicyRefDataMaskType().batchCreate(xxDataMaskInfos); + } - private static final Logger LOG = LoggerFactory.getLogger(PolicyRefUpdater.class); + public Boolean cleanupRefTables(RangerPolicy policy) { + final Long policyId = policy == null ? null : policy.getId(); - public enum PRINCIPAL_TYPE { USER, GROUP, ROLE } + if (policyId == null) { + return false; + } + + daoMgr.getXXPolicyRefResource().deleteByPolicyId(policyId); + daoMgr.getXXPolicyRefRole().deleteByPolicyId(policyId); + daoMgr.getXXPolicyRefGroup().deleteByPolicyId(policyId); + daoMgr.getXXPolicyRefUser().deleteByPolicyId(policyId); + daoMgr.getXXPolicyRefAccessType().deleteByPolicyId(policyId); + daoMgr.getXXPolicyRefCondition().deleteByPolicyId(policyId); + daoMgr.getXXPolicyRefDataMaskType().deleteByPolicyId(policyId); - @Autowired - RangerDaoManager daoMgr; + return true; + } - @Autowired - RangerAuditFields rangerAuditFields; + public enum PRINCIPAL_TYPE { USER, GROUP, ROLE } - @Autowired - XUserMgr xUserMgr; + private class PolicyPrincipalAssociator implements Runnable { + final PRINCIPAL_TYPE type; + final String name; + final XXPolicy xPolicy; - @Autowired - RoleDBStore roleStore; - - @Autowired - RangerBizUtil rangerBizUtil; - - @Autowired - XGroupService xGroupService; - - @Autowired - RangerTransactionSynchronizationAdapter rangerTransactionSynchronizationAdapter; - - @Autowired - RESTErrorUtil restErrorUtil; - - public void createNewPolMappingForRefTable(RangerPolicy policy, XXPolicy xPolicy, XXServiceDef xServiceDef, boolean createPrincipalsIfAbsent) throws Exception { - if(policy == null) { - return; - } - - cleanupRefTables(policy); - - final Set resourceNames = policy.getResources().keySet(); - final Set roleNames = new HashSet<>(); - final Set groupNames = new HashSet<>(); - final Set userNames = new HashSet<>(); - final Set accessTypes = new HashSet<>(); - final Set conditionTypes = new HashSet<>(); - final Set dataMaskTypes = new HashSet<>(); - boolean oldBulkMode = RangerBizUtil.isBulkMode(); - - List rangerPolicyConditions = policy.getConditions(); - if (CollectionUtils.isNotEmpty(rangerPolicyConditions)) { - for (RangerPolicy.RangerPolicyItemCondition condition : rangerPolicyConditions) { - conditionTypes.add(condition.getType()); - } - } - - for (List policyItems : getAllPolicyItems(policy)) { - if (CollectionUtils.isEmpty(policyItems)) { - continue; - } - - for (RangerPolicyItem policyItem : policyItems) { - roleNames.addAll(policyItem.getRoles()); - groupNames.addAll(policyItem.getGroups()); - userNames.addAll(policyItem.getUsers()); - - if (CollectionUtils.isNotEmpty(policyItem.getAccesses())) { - for (RangerPolicyItemAccess access : policyItem.getAccesses()) { - accessTypes.add(access.getType()); - } - } - - if (CollectionUtils.isNotEmpty(policyItem.getConditions())) { - for (RangerPolicyItemCondition condition : policyItem.getConditions()) { - conditionTypes.add(condition.getType()); - } - } - - if (policyItem instanceof RangerDataMaskPolicyItem) { - RangerPolicyItemDataMaskInfo dataMaskInfo = ((RangerDataMaskPolicyItem) policyItem).getDataMaskInfo(); - - dataMaskTypes.add(dataMaskInfo.getDataMaskType()); - } - } - } - - List xPolResources = new ArrayList<>(); - for (String resource : resourceNames) { - XXResourceDef xResDef = daoMgr.getXXResourceDef().findByNameAndPolicyId(resource, policy.getId()); - - if (xResDef == null) { - throw new Exception(resource + ": is not a valid resource-type. policy='"+ policy.getName() + "' service='"+ policy.getService() + "'"); - } - - XXPolicyRefResource xPolRes = rangerAuditFields.populateAuditFields(new XXPolicyRefResource(), xPolicy); - - xPolRes.setPolicyId(policy.getId()); - xPolRes.setResourceDefId(xResDef.getId()); - xPolRes.setResourceName(resource); - - xPolResources.add(xPolRes); - } - daoMgr.getXXPolicyRefResource().batchCreate(xPolResources); - - if (createPrincipalsIfAbsent && !rangerBizUtil.checkAdminAccess()) { - LOG.warn("policy=" + policy.getName() + ": createPrincipalIfAbsent=true, but current user does not have admin privileges!"); - - createPrincipalsIfAbsent = false; - } - - List xPolRoles = new ArrayList<>(); - for (String role : roleNames) { - if (StringUtils.isBlank(role)) { - continue; - } - PolicyPrincipalAssociator associator = new PolicyPrincipalAssociator(PRINCIPAL_TYPE.ROLE, role, xPolicy); - if (!associator.doAssociate(false)) { - if (createPrincipalsIfAbsent) { - rangerTransactionSynchronizationAdapter.executeOnTransactionCommit(associator); - } else { - VXResponse gjResponse = new VXResponse(); - gjResponse.setStatusCode(HttpServletResponse.SC_BAD_REQUEST); - gjResponse.setMsgDesc("Operation denied. Role name: " + role + " specified in policy does not exist in ranger admin."); - throw restErrorUtil.generateRESTException(gjResponse); - } - } - } - RangerBizUtil.setBulkMode(oldBulkMode); - daoMgr.getXXPolicyRefRole().batchCreate(xPolRoles); - - for (String group : groupNames) { - if (StringUtils.isBlank(group)) { - continue; - } - - PolicyPrincipalAssociator associator = new PolicyPrincipalAssociator(PRINCIPAL_TYPE.GROUP, group, xPolicy); - if (!associator.doAssociate(false)) { - if (createPrincipalsIfAbsent) { - rangerTransactionSynchronizationAdapter.executeOnTransactionCommit(associator); - } else { - VXResponse gjResponse = new VXResponse(); - gjResponse.setStatusCode(HttpServletResponse.SC_BAD_REQUEST); - gjResponse.setMsgDesc("Operation denied. Group name: " + group + " specified in policy does not exist in ranger admin."); - throw restErrorUtil.generateRESTException(gjResponse); - } - } - } - - for (String user : userNames) { - if (StringUtils.isBlank(user)) { - continue; - } - PolicyPrincipalAssociator associator = new PolicyPrincipalAssociator(PRINCIPAL_TYPE.USER, user, xPolicy); - if (!associator.doAssociate(false)) { - if (createPrincipalsIfAbsent) { - rangerTransactionSynchronizationAdapter.executeOnTransactionCommit(associator); - } else { - VXResponse gjResponse = new VXResponse(); - gjResponse.setStatusCode(HttpServletResponse.SC_BAD_REQUEST); - gjResponse.setMsgDesc("Operation denied. User name: " + user + " specified in policy does not exist in ranger admin."); - throw restErrorUtil.generateRESTException(gjResponse); - } - } - } - - List xPolAccesses = new ArrayList<>(); - - // ignore built-in access-types while creating ref-table entries - accessTypes.removeAll(ServiceDefUtil.ACCESS_TYPE_MARKERS); - - for (String accessType : accessTypes) { - XXAccessTypeDef xAccTypeDef = daoMgr.getXXAccessTypeDef().findByNameAndServiceId(accessType, xPolicy.getService()); - - if (xAccTypeDef == null) { - throw new Exception(accessType + ": is not a valid access-type. policy='" + policy.getName() + "' service='" + policy.getService() + "'"); - } - - XXPolicyRefAccessType xPolAccess = rangerAuditFields.populateAuditFields(new XXPolicyRefAccessType(), xPolicy); - - xPolAccess.setPolicyId(policy.getId()); - xPolAccess.setAccessDefId(xAccTypeDef.getId()); - xPolAccess.setAccessTypeName(accessType); - - xPolAccesses.add(xPolAccess); - } - daoMgr.getXXPolicyRefAccessType().batchCreate(xPolAccesses); - - List xPolConds = new ArrayList<>(); - for (String condition : conditionTypes) { - XXPolicyConditionDef xPolCondDef = daoMgr.getXXPolicyConditionDef().findByServiceDefIdAndName(xServiceDef.getId(), condition); - - if (xPolCondDef == null) { - if (StringUtils.equalsIgnoreCase(condition, ServiceDefUtil.IMPLICIT_CONDITION_EXPRESSION_NAME)) { - continue; - } - - throw new Exception(condition + ": is not a valid condition-type. policy='"+ xPolicy.getName() + "' service='"+ xPolicy.getService() + "'"); - } - - XXPolicyRefCondition xPolCond = rangerAuditFields.populateAuditFields(new XXPolicyRefCondition(), xPolicy); - - xPolCond.setPolicyId(policy.getId()); - xPolCond.setConditionDefId(xPolCondDef.getId()); - xPolCond.setConditionName(condition); - - xPolConds.add(xPolCond); - } - daoMgr.getXXPolicyRefCondition().batchCreate(xPolConds); - - List xxDataMaskInfos = new ArrayList<>(); - for (String dataMaskType : dataMaskTypes ) { - XXDataMaskTypeDef dataMaskDef = daoMgr.getXXDataMaskTypeDef().findByNameAndServiceId(dataMaskType, xPolicy.getService()); - - if (dataMaskDef == null) { - throw new Exception(dataMaskType + ": is not a valid datamask-type. policy='" + policy.getName() + "' service='" + policy.getService() + "'"); - } - - XXPolicyRefDataMaskType xxDataMaskInfo = new XXPolicyRefDataMaskType(); - - xxDataMaskInfo.setPolicyId(policy.getId()); - xxDataMaskInfo.setDataMaskDefId(dataMaskDef.getId()); - xxDataMaskInfo.setDataMaskTypeName(dataMaskType); - - xxDataMaskInfos.add(xxDataMaskInfo); - } - daoMgr.getXXPolicyRefDataMaskType().batchCreate(xxDataMaskInfos); - } - - private class PolicyPrincipalAssociator implements Runnable { - final PRINCIPAL_TYPE type; - final String name; - final XXPolicy xPolicy; - - public PolicyPrincipalAssociator(PRINCIPAL_TYPE type, String name, XXPolicy xPolicy) { - this.type = type; - this.name = name; - this.xPolicy = xPolicy; - } - - @Override - public void run() { - if (doAssociate(true)) { - if (LOG.isDebugEnabled()) { - LOG.debug("Associated " + type.name() + ":" + name + " with policy id:[" + xPolicy.getId() + "]"); - } - } else { - throw new RuntimeException("Failed to associate " + type.name() + ":" + name + " with policy id:[" + xPolicy.getId() + "]"); - } - } - - boolean doAssociate(boolean isAdmin) { - if (LOG.isDebugEnabled()) { - LOG.debug("===> PolicyPrincipalAssociator.doAssociate(" + isAdmin + ")"); - } - final boolean ret; - - Long id = createOrGetPrincipal(isAdmin); - if (id != null) { - // associate with policy - createPolicyAssociation(id, name); - ret = true; - } else { - ret = false; - } - - if (LOG.isDebugEnabled()) { - LOG.debug("<=== PolicyPrincipalAssociator.doAssociate(" + isAdmin + ") : " + ret); - } - return ret; - } - - private Long createOrGetPrincipal(final boolean createIfAbsent) { - if (LOG.isDebugEnabled()) { - LOG.debug("===> PolicyPrincipalAssociator.createOrGetPrincipal(" + createIfAbsent + ")"); - } - - Long ret = null; - - switch (type) { - case USER: { - XXUser xUser = daoMgr.getXXUser().findByUserName(name); - if (xUser != null) { - ret = xUser.getId(); - } else { - if (createIfAbsent) { - ret = createPrincipal(name); - } - } - } - break; - case GROUP: { - XXGroup xGroup = daoMgr.getXXGroup().findByGroupName(name); - - if (xGroup != null) { - ret = xGroup.getId(); - } else { - if (createIfAbsent) { - ret = createPrincipal(name); - } - } - } - break; - case ROLE: { - XXRole xRole = daoMgr.getXXRole().findByRoleName(name); - if (xRole != null) { - ret = xRole.getId(); - } else { - if (createIfAbsent) { - RangerBizUtil.setBulkMode(false); - ret = createPrincipal(name); - } - } - } - break; - default: - break; - } - if (LOG.isDebugEnabled()) { - LOG.debug("<=== PolicyPrincipalAssociator.createOrGetPrincipal(" + createIfAbsent + ") : " + ret); - } - return ret; - } - - private Long createPrincipal(String user) { - LOG.warn("User specified in policy does not exist in ranger admin, creating new user, Type: " + type.name() + ", name = " + user); - - if (LOG.isDebugEnabled()) { - LOG.debug("===> PolicyPrincipalAssociator.createPrincipal(type=" + type.name() +", name=" + name + ")"); - } - - Long ret = null; - - switch (type) { - case USER: { - // Create External user - VXUser vXUser = xUserMgr.createServiceConfigUser(name); - if (vXUser != null) { - XXUser xUser = daoMgr.getXXUser().findByUserName(name); - - if (xUser == null) { - LOG.error("No User created!! Irrecoverable error! [" + name + "]"); - } else { - ret = xUser.getId(); - } - } else { - LOG.warn("serviceConfigUser:[" + name + "] creation failed. This may be a transient/spurious condition that may correct itself when transaction is committed"); - } - } - break; - case GROUP: { - // Create group - VXGroup vxGroup = new VXGroup(); - vxGroup.setName(name); - vxGroup.setDescription(name); - vxGroup.setGroupSource(RangerCommonEnums.GROUP_EXTERNAL); - VXGroup vXGroup = xGroupService.createXGroupWithOutLogin(vxGroup); - if (vXGroup != null) { - xGroupService.createTransactionLog(vXGroup, null, OPERATION_CREATE_CONTEXT, xPolicy.getAddedByUserId()); - - ret = vXGroup.getId(); - } - } - break; - case ROLE: { - try { - RangerRole rRole = new RangerRole(name, null, null, null, null); - RangerRole createdRole = roleStore.createRole(rRole, false); - ret = createdRole.getId(); - } catch (Exception e) { - // Ignore - } - } - break; - default: - break; - } - if (LOG.isDebugEnabled()) { - LOG.debug("<=== PolicyPrincipalAssociator.createPrincipal(type=" + type.name() + ", name=" + name + ") : " + ret); - } - return ret; - } - - private void createPolicyAssociation(Long id, String name) { - if(LOG.isDebugEnabled()) { - LOG.debug("===> PolicyPrincipalAssociator.createPolicyAssociation(policyId=" + xPolicy.getId() + ", type=" + type.name() + ", name=" + name + ", id=" + id + ")"); - } - switch (type) { - case USER: { - XXPolicyRefUser xPolUser = rangerAuditFields.populateAuditFields(new XXPolicyRefUser(), xPolicy); - - xPolUser.setPolicyId(xPolicy.getId()); - xPolUser.setUserId(id); - xPolUser.setUserName(name); - daoMgr.getXXPolicyRefUser().create(xPolUser); - } - break; - case GROUP: { - XXPolicyRefGroup xPolGroup = rangerAuditFields.populateAuditFields(new XXPolicyRefGroup(), xPolicy); - - xPolGroup.setPolicyId(xPolicy.getId()); - xPolGroup.setGroupId(id); - xPolGroup.setGroupName(name); - daoMgr.getXXPolicyRefGroup().create(xPolGroup); - } - break; - case ROLE: { - XXPolicyRefRole xPolRole = rangerAuditFields.populateAuditFields(new XXPolicyRefRole(), xPolicy); - - xPolRole.setPolicyId(xPolicy.getId()); - xPolRole.setRoleId(id); - xPolRole.setRoleName(name); - daoMgr.getXXPolicyRefRole().create(xPolRole); - } - break; - default: - break; - } - if(LOG.isDebugEnabled()) { - LOG.debug("<=== PolicyPrincipalAssociator.createPolicyAssociation(policyId=" + xPolicy.getId() + ", type=" + type.name() + ", name=" + name + ", id=" + id + ")"); - } - } - } - - public Boolean cleanupRefTables(RangerPolicy policy) { - final Long policyId = policy == null ? null : policy.getId(); - - if (policyId == null) { - return false; - } - - daoMgr.getXXPolicyRefResource().deleteByPolicyId(policyId); - daoMgr.getXXPolicyRefRole().deleteByPolicyId(policyId); - daoMgr.getXXPolicyRefGroup().deleteByPolicyId(policyId); - daoMgr.getXXPolicyRefUser().deleteByPolicyId(policyId); - daoMgr.getXXPolicyRefAccessType().deleteByPolicyId(policyId); - daoMgr.getXXPolicyRefCondition().deleteByPolicyId(policyId); - daoMgr.getXXPolicyRefDataMaskType().deleteByPolicyId(policyId); - - return true; - } - - public static List> getAllPolicyItems(RangerPolicy policy) { - List> ret = new ArrayList<>(); - - if (CollectionUtils.isNotEmpty(policy.getPolicyItems())) { - ret.add(policy.getPolicyItems()); - } - - if (CollectionUtils.isNotEmpty(policy.getDenyPolicyItems())) { - ret.add(policy.getDenyPolicyItems()); - } - - if (CollectionUtils.isNotEmpty(policy.getAllowExceptions())) { - ret.add(policy.getAllowExceptions()); - } - - if (CollectionUtils.isNotEmpty(policy.getDenyExceptions())) { - ret.add(policy.getDenyExceptions()); - } - - if (CollectionUtils.isNotEmpty(policy.getDataMaskPolicyItems())) { - ret.add(policy.getDataMaskPolicyItems()); - } - - if (CollectionUtils.isNotEmpty(policy.getRowFilterPolicyItems())) { - ret.add(policy.getRowFilterPolicyItems()); - } - - return ret; - } + public PolicyPrincipalAssociator(PRINCIPAL_TYPE type, String name, XXPolicy xPolicy) { + this.type = type; + this.name = name; + this.xPolicy = xPolicy; + } + @Override + public void run() { + if (doAssociate(true)) { + LOG.debug("Associated {}:{} with policy id:[{}]", type.name(), name, xPolicy.getId()); + } else { + throw new RuntimeException("Failed to associate " + type.name() + ":" + name + " with policy id:[" + xPolicy.getId() + "]"); + } + } + + boolean doAssociate(boolean isAdmin) { + LOG.debug("===> PolicyPrincipalAssociator.doAssociate({})", isAdmin); + + final boolean ret; + + Long id = createOrGetPrincipal(isAdmin); + + if (id != null) { + // associate with policy + createPolicyAssociation(id, name); + + ret = true; + } else { + ret = false; + } + + LOG.debug("<=== PolicyPrincipalAssociator.doAssociate({}) : {}", isAdmin, ret); + + return ret; + } + + private Long createOrGetPrincipal(final boolean createIfAbsent) { + LOG.debug("===> PolicyPrincipalAssociator.createOrGetPrincipal({})", createIfAbsent); + + Long ret = null; + + switch (type) { + case USER: { + XXUser xUser = daoMgr.getXXUser().findByUserName(name); + + if (xUser != null) { + ret = xUser.getId(); + } else { + if (createIfAbsent) { + ret = createPrincipal(name); + } + } + } + break; + case GROUP: { + XXGroup xGroup = daoMgr.getXXGroup().findByGroupName(name); + + if (xGroup != null) { + ret = xGroup.getId(); + } else { + if (createIfAbsent) { + ret = createPrincipal(name); + } + } + } + break; + case ROLE: { + XXRole xRole = daoMgr.getXXRole().findByRoleName(name); + + if (xRole != null) { + ret = xRole.getId(); + } else { + if (createIfAbsent) { + RangerBizUtil.setBulkMode(false); + ret = createPrincipal(name); + } + } + } + break; + default: + break; + } + + LOG.debug("<=== PolicyPrincipalAssociator.createOrGetPrincipal({}) : {}", createIfAbsent, ret); + + return ret; + } + + private Long createPrincipal(String user) { + LOG.warn("User specified in policy does not exist in ranger admin, creating new user, Type: {}, name = {}", type.name(), user); + + LOG.debug("===> PolicyPrincipalAssociator.createPrincipal(type={}, name={})", type.name(), name); + + Long ret = null; + + switch (type) { + case USER: { + // Create External user + VXUser vXUser = xUserMgr.createServiceConfigUser(name); + if (vXUser != null) { + XXUser xUser = daoMgr.getXXUser().findByUserName(name); + + if (xUser == null) { + LOG.error("No User created!! Irrecoverable error! [{}]", name); + } else { + ret = xUser.getId(); + } + } else { + LOG.warn("serviceConfigUser:[{}] creation failed. This may be a transient/spurious condition that may correct itself when transaction is committed", name); + } + } + break; + case GROUP: { + // Create group + VXGroup vxGroup = new VXGroup(); + + vxGroup.setName(name); + vxGroup.setDescription(name); + vxGroup.setGroupSource(RangerCommonEnums.GROUP_EXTERNAL); + + VXGroup vXGroup = xGroupService.createXGroupWithOutLogin(vxGroup); + + if (vXGroup != null) { + xGroupService.createTransactionLog(vXGroup, null, OPERATION_CREATE_CONTEXT, xPolicy.getAddedByUserId()); + + ret = vXGroup.getId(); + } + } + break; + case ROLE: { + try { + RangerRole rRole = new RangerRole(name, null, null, null, null); + RangerRole createdRole = roleStore.createRole(rRole, false); + + ret = createdRole.getId(); + } catch (Exception e) { + // Ignore + } + } + break; + default: + break; + } + + LOG.debug("<=== PolicyPrincipalAssociator.createPrincipal(type={}, name={}) : {}", type.name(), name, ret); + + return ret; + } + + private void createPolicyAssociation(Long id, String name) { + LOG.debug("===> PolicyPrincipalAssociator.createPolicyAssociation(policyId={}, type={}, name={}, id={})", xPolicy.getId(), type.name(), name, id); + + switch (type) { + case USER: { + XXPolicyRefUser xPolUser = rangerAuditFields.populateAuditFields(new XXPolicyRefUser(), xPolicy); + + xPolUser.setPolicyId(xPolicy.getId()); + xPolUser.setUserId(id); + xPolUser.setUserName(name); + + daoMgr.getXXPolicyRefUser().create(xPolUser); + } + break; + case GROUP: { + XXPolicyRefGroup xPolGroup = rangerAuditFields.populateAuditFields(new XXPolicyRefGroup(), xPolicy); + + xPolGroup.setPolicyId(xPolicy.getId()); + xPolGroup.setGroupId(id); + xPolGroup.setGroupName(name); + + daoMgr.getXXPolicyRefGroup().create(xPolGroup); + } + break; + case ROLE: { + XXPolicyRefRole xPolRole = rangerAuditFields.populateAuditFields(new XXPolicyRefRole(), xPolicy); + + xPolRole.setPolicyId(xPolicy.getId()); + xPolRole.setRoleId(id); + xPolRole.setRoleName(name); + + daoMgr.getXXPolicyRefRole().create(xPolRole); + } + break; + default: + break; + } + + LOG.debug("<=== PolicyPrincipalAssociator.createPolicyAssociation(policyId={}, type={}, name={}, id={})", xPolicy.getId(), type.name(), name, id); + } + } } diff --git a/security-admin/src/main/java/org/apache/ranger/biz/RangerBizUtil.java b/security-admin/src/main/java/org/apache/ranger/biz/RangerBizUtil.java index b98504fd33..f697d9ce5b 100644 --- a/security-admin/src/main/java/org/apache/ranger/biz/RangerBizUtil.java +++ b/security-admin/src/main/java/org/apache/ranger/biz/RangerBizUtil.java @@ -19,18 +19,6 @@ package org.apache.ranger.biz; -import java.security.SecureRandom; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Set; -import javax.servlet.http.HttpServletResponse; - import org.apache.commons.collections.CollectionUtils; import org.apache.commons.io.FilenameUtils; import org.apache.commons.io.IOCase; @@ -79,1555 +67,1576 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; +import javax.servlet.http.HttpServletResponse; + +import java.security.SecureRandom; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + @Component public class RangerBizUtil { - private static final Logger logger = LoggerFactory.getLogger(RangerBizUtil.class); - - @Autowired - RESTErrorUtil restErrorUtil; - - @Autowired - RangerDaoManager daoManager; - - @Autowired - StringUtil stringUtil; - - @Autowired - UserMgr userMgr; - - @Autowired - XUserService xUserService; - - @Autowired - GUIDUtil guidUtil; - - Set> groupEditableClasses; - private Class[] groupEditableClassesList = {}; - - private int maxFirstNameLength; - int maxDisplayNameLength = 150; - boolean enableResourceAccessControl; - private SecureRandom 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; - public static final String AUDIT_STORE_RDBMS = "DB"; - public static final String AUDIT_STORE_SOLR = "solr"; - public static final String AUDIT_STORE_ELASTIC_SEARCH = "elasticSearch"; - public static final String AUDIT_STORE_CLOUD_WATCH = "cloudwatch"; - public static final boolean BATCH_CLEAR_ENABLED = PropertiesUtil.getBooleanProperty("ranger.jpa.jdbc.batch-clear.enable", true); - public static final int POLICY_BATCH_SIZE = PropertiesUtil.getIntProperty("ranger.jpa.jdbc.batch-clear.size", 10); - public static final int BATCH_PERSIST_SIZE = PropertiesUtil.getIntProperty("ranger.jpa.jdbc.batch-persist.size", 500); - - String auditDBType = AUDIT_STORE_RDBMS; - private final boolean allowUnauthenticatedAccessInSecureEnvironment; - private final boolean allowUnauthenticatedDownloadAccessInSecureEnvironment; - - static String fileSeparator = PropertiesUtil.getProperty("ranger.file.separator", "/"); - - public RangerBizUtil() { - RangerAdminConfig config = RangerAdminConfig.getInstance(); - - allowUnauthenticatedAccessInSecureEnvironment = config.getBoolean("ranger.admin.allow.unauthenticated.access", false); - allowUnauthenticatedDownloadAccessInSecureEnvironment = config.getBoolean("ranger.admin.allow.unauthenticated.download.access", - allowUnauthenticatedAccessInSecureEnvironment); - - maxFirstNameLength = Integer.parseInt(PropertiesUtil.getProperty("ranger.user.firstname.maxlength", "16")); - maxDisplayNameLength = PropertiesUtil.getIntProperty("ranger.bookmark.name.maxlen", maxDisplayNameLength); - - groupEditableClasses = new HashSet<>( - Arrays.asList(groupEditableClassesList)); - enableResourceAccessControl = PropertiesUtil.getBooleanProperty("ranger.resource.accessControl.enabled", true); - - auditDBType = PropertiesUtil.getProperty("ranger.audit.source.type", - auditDBType).toLowerCase(); - logger.info("java.library.path is " + System.getProperty("java.library.path")); - logger.info("Audit datasource is " + auditDBType); - random = new SecureRandom(); - } - - // 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 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 VXStringList mapStringListToVStringList(List stringList) { - if (stringList == null) { - return null; - } - - List vStringList = new ArrayList<>(); - 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 xResourceList = daoManager.getXXResource() - .findByAssetIdAndResourceStatus(assetId, RangerCommonEnums.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, 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, 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; - } + private static final Logger logger = LoggerFactory.getLogger(RangerBizUtil.class); - public boolean isAuditAdmin() { - UserSessionBase currentUserSession = ContextUtil - .getCurrentUserSession(); - if (currentUserSession == null) { - logger.debug("Unable to find session."); - return false; + public static final String AUDIT_STORE_RDBMS = "DB"; + public static final String AUDIT_STORE_SOLR = "solr"; + public static final String AUDIT_STORE_ELASTIC_SEARCH = "elasticSearch"; + public static final String AUDIT_STORE_CLOUD_WATCH = "cloudwatch"; + public static final boolean BATCH_CLEAR_ENABLED = PropertiesUtil.getBooleanProperty("ranger.jpa.jdbc.batch-clear.enable", true); + public static final int POLICY_BATCH_SIZE = PropertiesUtil.getIntProperty("ranger.jpa.jdbc.batch-clear.size", 10); + public static final int BATCH_PERSIST_SIZE = PropertiesUtil.getIntProperty("ranger.jpa.jdbc.batch-persist.size", 500); + + private static final String PATH_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrst0123456789-_."; + + static String fileSeparator = PropertiesUtil.getProperty("ranger.file.separator", "/"); + + private static final char[] PATH_CHAR_SET = PATH_CHARS.toCharArray(); + private static final int PATH_CHAR_SET_LEN = PATH_CHAR_SET.length; + + @Autowired + RESTErrorUtil restErrorUtil; + + @Autowired + RangerDaoManager daoManager; + + @Autowired + StringUtil stringUtil; + + @Autowired + UserMgr userMgr; + + @Autowired + XUserService xUserService; + + @Autowired + GUIDUtil guidUtil; + + private final boolean allowUnauthenticatedAccessInSecureEnvironment; + private final boolean allowUnauthenticatedDownloadAccessInSecureEnvironment; + private final Class[] groupEditableClassesList = {}; + private final int maxFirstNameLength; + private final SecureRandom random; + + Set> groupEditableClasses; + int maxDisplayNameLength = 150; + boolean enableResourceAccessControl; + String auditDBType = AUDIT_STORE_RDBMS; + + public RangerBizUtil() { + RangerAdminConfig config = RangerAdminConfig.getInstance(); + + allowUnauthenticatedAccessInSecureEnvironment = config.getBoolean("ranger.admin.allow.unauthenticated.access", false); + allowUnauthenticatedDownloadAccessInSecureEnvironment = config.getBoolean("ranger.admin.allow.unauthenticated.download.access", allowUnauthenticatedAccessInSecureEnvironment); + + maxFirstNameLength = Integer.parseInt(PropertiesUtil.getProperty("ranger.user.firstname.maxlength", "16")); + maxDisplayNameLength = PropertiesUtil.getIntProperty("ranger.bookmark.name.maxlen", maxDisplayNameLength); + + groupEditableClasses = new HashSet<>(Arrays.asList(groupEditableClassesList)); + enableResourceAccessControl = PropertiesUtil.getBooleanProperty("ranger.resource.accessControl.enabled", true); + + auditDBType = PropertiesUtil.getProperty("ranger.audit.source.type", auditDBType).toLowerCase(); + + logger.info("java.library.path is {}", System.getProperty("java.library.path")); + logger.info("Audit datasource is {}", auditDBType); + + random = new SecureRandom(); + } + + /** + * 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; } - if (currentUserSession.isAuditUserAdmin()) { - return true; + } + + return true; + } + + public static int getDBFlavor() { + String[] propertyNames = {"xa.db.flavor", + "ranger.jpa.jdbc.dialect", + "ranger.jpa.jdbc.url", + "ranger.jpa.jdbc.driver" + }; + + for (String propertyName : propertyNames) { + String propertyValue = PropertiesUtil.getProperty(propertyName); + + if (StringUtils.isBlank(propertyValue)) { + continue; + } + + if (StringUtils.containsIgnoreCase(propertyValue, "mysql")) { + return AppConstants.DB_FLAVOR_MYSQL; + } else if (StringUtils.containsIgnoreCase(propertyValue, "oracle")) { + return AppConstants.DB_FLAVOR_ORACLE; + } else if (StringUtils.containsIgnoreCase(propertyValue, "postgresql")) { + return AppConstants.DB_FLAVOR_POSTGRES; + } else if (StringUtils.containsIgnoreCase(propertyValue, "sqlserver")) { + return AppConstants.DB_FLAVOR_SQLSERVER; + } else if (StringUtils.containsIgnoreCase(propertyValue, "mssql")) { + return AppConstants.DB_FLAVOR_SQLSERVER; + } else if (StringUtils.containsIgnoreCase(propertyValue, "sqlanywhere")) { + return AppConstants.DB_FLAVOR_SQLANYWHERE; + } else if (StringUtils.containsIgnoreCase(propertyValue, "sqla")) { + return AppConstants.DB_FLAVOR_SQLANYWHERE; + } else { + logger.debug("DB Flavor could not be determined from property - {}={}", propertyName, propertyValue); + } + } + + logger.error("DB Flavor could not be determined"); + + return AppConstants.DB_FLAVOR_UNKNOWN; + } + + public static String getDBFlavorType(int dbFlavor) { + final String dbFlavourType; + + switch (dbFlavor) { + case AppConstants.DB_FLAVOR_MYSQL: + dbFlavourType = "MYSQL"; + break; + case AppConstants.DB_FLAVOR_ORACLE: + dbFlavourType = "ORACLE"; + break; + case AppConstants.DB_FLAVOR_POSTGRES: + dbFlavourType = "POSTGRES"; + break; + case AppConstants.DB_FLAVOR_SQLANYWHERE: + dbFlavourType = "SQLANYWHERE"; + break; + case AppConstants.DB_FLAVOR_SQLSERVER: + dbFlavourType = "SQLSERVER"; + break; + default: + dbFlavourType = "Unknown"; + break; + } + + return dbFlavourType; + } + + public static String getDBVersionQuery(int dbFlavor) { + final String dbQuery; + + switch (dbFlavor) { + case AppConstants.DB_FLAVOR_ORACLE: + dbQuery = "SELECT banner from v$version where rownum<2"; + break; + case AppConstants.DB_FLAVOR_MYSQL: + case AppConstants.DB_FLAVOR_POSTGRES: + dbQuery = "SELECT version()"; + break; + case AppConstants.DB_FLAVOR_SQLANYWHERE: + case AppConstants.DB_FLAVOR_SQLSERVER: + dbQuery = "SELECT @@version"; + break; + default: + dbQuery = null; + break; + } + + return dbQuery; + } + + public static boolean isBulkMode() { + return ContextUtil.isBulkModeContext(); + } + + public static boolean setBulkMode(boolean val) { + RangerContextHolder.getOrCreateOpContext().setBulkModeContext(val); + + return isBulkMode(); + } + + // 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 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.isEmpty()) { + publicName = fName + " " + lastName.charAt(0) + "."; + } + + return publicName; + } + + public VXStringList mapStringListToVStringList(List stringList) { + if (stringList == null) { + return null; + } + + List vStringList = new ArrayList<>(); + + 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 xResourceList = daoManager.getXXResource().findByAssetIdAndResourceStatus(assetId, RangerCommonEnums.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, 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, 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; + } + + return currentUserSession.isUserAdmin(); } - /** - * return username of currently logged in user - * - * @return - */ - public String getCurrentUserLoginId() { - String ret = null; - - UserSessionBase currentUserSession = ContextUtil.getCurrentUserSession(); - - if (currentUserSession != null) { - ret = currentUserSession.getLoginId(); - } - - return ret; - } - - /** - * 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 xResourceList, Long xUserId, int permission) { - boolean matchFound = false; - resourceName = replaceMetaChars(resourceName); - - for (XXResource xResource : xResourceList) { - if (xResource.getResourceStatus() != RangerCommonEnums.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() == RangerCommonEnums.BOOL_TRUE) { - matchFound = isRecursiveWildCardMatch(resourceName, - dbResourceName); - } else { - matchFound = nonRecursiveWildCardMatch( - resourceName, dbResourceName); - } - } - if (matchFound) { - break; - } - } - if (matchFound) { - break; - } - } - } - return matchFound; - } - - public void failUnauthenticatedIfNotAllowed() throws Exception { - if (UserGroupInformation.isSecurityEnabled()) { - UserSessionBase currentUserSession = ContextUtil.getCurrentUserSession(); - if (currentUserSession == null && !allowUnauthenticatedAccessInSecureEnvironment) { - throw new Exception("Unauthenticated access not allowed"); - } - } - } - - public void failUnauthenticatedDownloadIfNotAllowed() throws Exception { - if (UserGroupInformation.isSecurityEnabled()) { - UserSessionBase currentUserSession = ContextUtil.getCurrentUserSession(); - if (currentUserSession == null && !allowUnauthenticatedDownloadAccessInSecureEnvironment) { - throw new Exception("Unauthenticated access not allowed"); - } - } - } - - /** - * 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 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) || 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) - || 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) - || matchPath(colName, xColumns); - } - } - - if (matchFound) { - policyMatched = true; - break; - } - } - return policyMatched; - } - - public boolean matchHivePolicy(String resourceName, - List 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 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() != RangerCommonEnums.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) - || 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) - || 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) - || 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 xUserId - * @param permission - * @return - */ - private boolean matchKnoxPolicy(String resourceName, - List xResourceList, - 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() != RangerCommonEnums.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 || "".equalsIgnoreCase(xResource - .getTopologies())) ? null - : stringUtil.split(xResource.getTopologies(), ","); - String[] xServices = (xResource.getServices() == null || "".equalsIgnoreCase(xResource - .getServices())) ? 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 xUserId - * @param permission - * @return - */ - private boolean matchStormPolicy(String resourceName, - List xResourceList, - 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() != RangerCommonEnums.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 || "".equalsIgnoreCase(xResource - .getTopologies())) ? null - : stringUtil.split(xResource.getTopologies(), ","); - - 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 && 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 - } - 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(); - if(randomNum<0){ - randomNum=Math.abs(randomNum); - } - return ((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 userGroups = daoManager.getXXGroup().findByUserId(xUserId); - List 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.equals(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( - RangerConstants.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 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 - * - * List of all possible parent return type for some specific resourceType - * - * @param resourceType - * , assetType - * - */ - public List getResorceTypeParentHirearchy(int resourceType, - int assetType) { - List resourceTypeList = new ArrayList<>(); - - 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 pathToCheckArray = new ArrayList<>(); - List wildcardPathArray = new ArrayList<>(); - - Collections.addAll(pathToCheckArray, pathToCheck.split(fileSeparator)); - Collections.addAll(wildcardPathArray, wildcardPath.split(fileSeparator)); - - 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 trxLogList) { - if (trxLogList == null || trxLogList.size() == 0) { - return; - } - - if (guidUtil == null) { - // log a warning - return; - } - - XXTrxLogV2Dao dao = daoManager.getXXTrxLogV2(); - String trxId = Long.toString(guidUtil.genLong()); - UserSessionBase usb = ContextUtil.getCurrentUserSession(); - String sessionId = usb != null && usb.getSessionId() != null ? usb.getSessionId().toString() : null; - Long userId = usb != null ? usb.getUserId() : null; - - for (XXTrxLogV2 xTrxLog : trxLogList) { - xTrxLog.setTransactionId(trxId); - xTrxLog.setSessionId(sessionId); - xTrxLog.setSessionType("Spring Authenticated Session"); - xTrxLog.setRequestId(trxId); - - if (xTrxLog.getAddedByUserId() == null) { - xTrxLog.setAddedByUserId(userId); - } - - dao.create(xTrxLog); - } - } - - public static int getDBFlavor() { - String[] propertyNames = { "xa.db.flavor", - "ranger.jpa.jdbc.dialect", - "ranger.jpa.jdbc.url", - "ranger.jpa.jdbc.driver" - }; - - for(String propertyName : propertyNames) { - String propertyValue = PropertiesUtil.getProperty(propertyName); - - if(StringUtils.isBlank(propertyValue)) { - continue; - } - - if (StringUtils.containsIgnoreCase(propertyValue, "mysql")) { - return AppConstants.DB_FLAVOR_MYSQL; - } else if (StringUtils.containsIgnoreCase(propertyValue, "oracle")) { - return AppConstants.DB_FLAVOR_ORACLE; - } else if (StringUtils.containsIgnoreCase(propertyValue, "postgresql")) { - return AppConstants.DB_FLAVOR_POSTGRES; - } else if (StringUtils.containsIgnoreCase(propertyValue, "sqlserver")) { - return AppConstants.DB_FLAVOR_SQLSERVER; - } else if (StringUtils.containsIgnoreCase(propertyValue, "mssql")) { - return AppConstants.DB_FLAVOR_SQLSERVER; - } else if (StringUtils.containsIgnoreCase(propertyValue, "sqlanywhere")) { - return AppConstants.DB_FLAVOR_SQLANYWHERE; - } else if (StringUtils.containsIgnoreCase(propertyValue, "sqla")) { - return AppConstants.DB_FLAVOR_SQLANYWHERE; - }else { - if(logger.isDebugEnabled()) { - logger.debug("DB Flavor could not be determined from property - " + propertyName + "=" + propertyValue); - } - } - } - - logger.error("DB Flavor could not be determined"); - - return AppConstants.DB_FLAVOR_UNKNOWN; - } - - public static String getDBFlavorType(int dbFlavor) { - final String dbFlavourType; - - switch (dbFlavor) { - case AppConstants.DB_FLAVOR_MYSQL: - dbFlavourType = "MYSQL"; - break; - case AppConstants.DB_FLAVOR_ORACLE: - dbFlavourType = "ORACLE"; - break; - case AppConstants.DB_FLAVOR_POSTGRES: - dbFlavourType = "POSTGRES"; - break; - case AppConstants.DB_FLAVOR_SQLANYWHERE: - dbFlavourType = "SQLANYWHERE"; - break; - case AppConstants.DB_FLAVOR_SQLSERVER: - dbFlavourType = "SQLSERVER"; - break; - default: - dbFlavourType = "Unknown"; - break; - } - - return dbFlavourType; - } - - public static String getDBVersionQuery(int dbFlavor){ - final String dbQuery; - - switch (dbFlavor) { - case AppConstants.DB_FLAVOR_ORACLE: - dbQuery = "SELECT banner from v$version where rownum<2"; - break; - case AppConstants.DB_FLAVOR_MYSQL: - case AppConstants.DB_FLAVOR_POSTGRES: - dbQuery = "SELECT version()"; - break; - case AppConstants.DB_FLAVOR_SQLANYWHERE: - case AppConstants.DB_FLAVOR_SQLSERVER: - dbQuery = "SELECT @@version"; - break; - default: - dbQuery = null; - break; - } - - return dbQuery; - } - - - public String getDBVersion(){ - return daoManager.getXXUser().getDBVersion(); - } - - public String getAuditDBType() { - return auditDBType; - } - - public void setAuditDBType(String auditDBType) { - this.auditDBType = auditDBType; - } - - /** - * return true id current logged in session is owned by keyadmin - * - * @return - */ - public boolean isKeyAdmin() { - UserSessionBase currentUserSession = ContextUtil.getCurrentUserSession(); - if (currentUserSession == null) { - logger.debug("Unable to find session."); - return false; - } - - return currentUserSession.isKeyAdmin(); - } - public boolean isAuditKeyAdmin() { + public boolean isAuditAdmin() { UserSessionBase currentUserSession = ContextUtil.getCurrentUserSession(); + if (currentUserSession == null) { - logger.debug("Unable to find session."); - return false; + logger.debug("Unable to find session."); + + return false; } - return (currentUserSession.isAuditKeyAdmin()); + + return currentUserSession.isAuditUserAdmin(); } - /** - * @param xxDbBase - * @param baseModel - * @return Boolean - * - * @NOTE: Kindly check all the references of this function before making any changes - */ - public Boolean hasAccess(XXDBBase xxDbBase, RangerBaseModelObject baseModel) { - UserSessionBase session = ContextUtil.getCurrentUserSession(); - if (session == null) { - logger.info("User session not found, granting access."); - return true; - } - - boolean isKeyAdmin = session.isKeyAdmin(); - boolean isSysAdmin = session.isUserAdmin(); - boolean isAuditor = session.isAuditUserAdmin(); - boolean isAuditorKeyAdmin = session.isAuditKeyAdmin(); - boolean isUser = session.getUserRoleList().contains(RangerConstants.ROLE_USER); - - if (xxDbBase != null && xxDbBase instanceof XXServiceDef) { - return hasAccessToXXServiceDef((XXServiceDef) xxDbBase, isKeyAdmin, isSysAdmin, isAuditor, isAuditorKeyAdmin, isUser); - } - - if (xxDbBase != null && xxDbBase instanceof XXService) { - return hasAccessToXXService((XXService) xxDbBase, isKeyAdmin, isSysAdmin, isAuditor, isAuditorKeyAdmin, isUser); - } - - if (baseModel != null && baseModel instanceof RangerServiceHeaderInfo) { - return hasAccessToRangerServiceHeaderInfo((RangerServiceHeaderInfo) baseModel, isKeyAdmin, isSysAdmin, isAuditor, isAuditorKeyAdmin, isUser); - } - return false; - } - - private Boolean hasAccessToXXServiceDef(XXServiceDef xxDbBase, boolean isKeyAdmin, boolean isSysAdmin, boolean isAuditor, boolean isAuditorKeyAdmin, boolean isUser) { - XXServiceDef xServiceDef = xxDbBase; - final String implClass = xServiceDef.getImplclassname(); - if (EmbeddedServiceDefsUtil.KMS_IMPL_CLASS_NAME.equals(implClass)) { - // KMS case - return isKeyAdmin || isAuditorKeyAdmin; - } else { - // Other cases - implClass can be null! - return isSysAdmin || isUser || isAuditor; - } - } - - private Boolean hasAccessToXXService(XXService xxDbBase, boolean isKeyAdmin, boolean isSysAdmin, boolean isAuditor, boolean isAuditorKeyAdmin, boolean isUser) { - // TODO: As of now we are allowing SYS_ADMIN to create/update/read/delete all the - // services including KMS - if (isSysAdmin || isAuditor) { - return true; - } - - XXService xService = xxDbBase; - XXServiceDef xServiceDef = daoManager.getXXServiceDef().getById(xService.getType()); - String implClass = xServiceDef.getImplclassname(); - if (EmbeddedServiceDefsUtil.KMS_IMPL_CLASS_NAME.equals(implClass)) { - // KMS case - return isKeyAdmin || isAuditorKeyAdmin; - } else { - // Other cases - implClass can be null! - return isUser; - } - } - - private Boolean hasAccessToRangerServiceHeaderInfo(RangerServiceHeaderInfo serviceHeader, boolean isKeyAdmin, boolean isSysAdmin, boolean isAuditor, boolean isAuditorKeyAdmin, boolean isUser) { - // TODO: As of now we are allowing SYS_ADMIN to read all the - // services including KMS - if (isSysAdmin || isAuditor) { - return true; - } - - return EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_KMS_NAME.equals(serviceHeader.getType()) ? (isKeyAdmin || isAuditorKeyAdmin) : isUser; - } - - public void hasAdminPermissions(String objType) { - - UserSessionBase session = ContextUtil.getCurrentUserSession(); - - if (session == null) { - throw restErrorUtil.createRESTException("UserSession cannot be null, only Admin can create/update/delete " - + objType, MessageEnums.OPER_NO_PERMISSION); - } - - if (!session.isKeyAdmin() && !session.isUserAdmin()) { - throw restErrorUtil.createRESTException( - "This user is not allowed this operation. Only users with Admin permission have access to this operation " + objType, - MessageEnums.OPER_NO_PERMISSION); - } - } - - public void hasKMSPermissions(String objType, String implClassName) { - UserSessionBase session = ContextUtil.getCurrentUserSession(); - if (session == null) { - throw restErrorUtil.createRESTException("UserSession cannot be null, only KeyAdmin can create/update/delete " - + objType, MessageEnums.OPER_NO_PERMISSION); - } - - if (session.isKeyAdmin() && !EmbeddedServiceDefsUtil.KMS_IMPL_CLASS_NAME.equals(implClassName)) { - throw restErrorUtil.createRESTException("KeyAdmin can create/update/delete only KMS " + objType, - MessageEnums.OPER_NO_PERMISSION); - } - - // TODO: As of now we are allowing SYS_ADMIN to create/update/read/delete all the - // services including KMS - - if ("Service-Def".equalsIgnoreCase(objType) && session.isUserAdmin() && EmbeddedServiceDefsUtil.KMS_IMPL_CLASS_NAME.equals(implClassName)) { - throw restErrorUtil.createRESTException("System Admin cannot create/update/delete KMS " + objType, - MessageEnums.OPER_NO_PERMISSION); - } - } - - public boolean checkUserAccessible(VXUser vXUser) { - boolean isAccessible = true; - Collection roleList = userMgr.getRolesByLoginId(vXUser - .getName()); - if (isKeyAdmin()) { - if (vXUser.getUserRoleList().contains(RangerConstants.ROLE_SYS_ADMIN) - || vXUser.getUserRoleList().contains(RangerConstants.ROLE_ADMIN_AUDITOR) - || roleList.contains(RangerConstants.ROLE_SYS_ADMIN) - || roleList.contains(RangerConstants.ROLE_ADMIN_AUDITOR)) { - isAccessible = false; - } - } - if (isAdmin()) { - if (vXUser.getUserRoleList().contains(RangerConstants.ROLE_KEY_ADMIN) - || vXUser.getUserRoleList().contains(RangerConstants.ROLE_KEY_ADMIN_AUDITOR) - || roleList.contains(RangerConstants.ROLE_KEY_ADMIN) - || roleList.contains(RangerConstants.ROLE_KEY_ADMIN_AUDITOR)) { - isAccessible = false; - } + /** + * return username of currently logged in user + * + * @return + */ + public String getCurrentUserLoginId() { + String ret = null; + UserSessionBase currentUserSession = ContextUtil.getCurrentUserSession(); + + if (currentUserSession != null) { + ret = currentUserSession.getLoginId(); + } + + return ret; + } + + /** + * 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 :{} with name {}", user.getId(), user.getFirstName()); + + return null; + } + + return xUser.getId(); + } + + public void failUnauthenticatedIfNotAllowed() throws Exception { + if (UserGroupInformation.isSecurityEnabled()) { + UserSessionBase currentUserSession = ContextUtil.getCurrentUserSession(); + + if (currentUserSession == null && !allowUnauthenticatedAccessInSecureEnvironment) { + throw new Exception("Unauthenticated access not allowed"); + } + } + } + + public void failUnauthenticatedDownloadIfNotAllowed() throws Exception { + if (UserGroupInformation.isSecurityEnabled()) { + UserSessionBase currentUserSession = ContextUtil.getCurrentUserSession(); + + if (currentUserSession == null && !allowUnauthenticatedDownloadAccessInSecureEnvironment) { + throw new Exception("Unauthenticated access not allowed"); + } + } + } + + /** + * 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 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) || 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) || 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) || matchPath(colName, xColumns); } - if (!isAccessible) { - throw restErrorUtil.createRESTException( - "Logged in user is not allowed to create/update user", - MessageEnums.OPER_NO_PERMISSION); - } - return isAccessible; - } - - public boolean isSSOEnabled() { - UserSessionBase session = ContextUtil.getCurrentUserSession(); - if (session != null) { - return session.isSSOEnabled() == null ? PropertiesUtil.getBooleanProperty("ranger.sso.enabled", false) : session.isSSOEnabled(); - } else { - throw restErrorUtil.createRESTException( - "User session is not created", - MessageEnums.OPER_NOT_ALLOWED_FOR_STATE); - } - } - - public boolean isUserAllowed(RangerService rangerService, String cfgNameAllowedUsers) { - Map map = rangerService.getConfigs(); - String user = null; - UserSessionBase userSession = ContextUtil.getCurrentUserSession(); - if(userSession != null){ - user = userSession.getLoginId(); - } - if (map != null && map.containsKey(cfgNameAllowedUsers)) { - String userNames = map.get(cfgNameAllowedUsers); - String[] userList = userNames.split(","); - if(userList != null){ - for (String u : userList) { - if ("*".equals(u) || (user != null && u.equalsIgnoreCase(user))) { - return true; - } - } - } - } - return false; - } - - public boolean isUserAllowedForGrantRevoke(RangerService rangerService, String userName) { - return isUserInConfigParameter(rangerService, ServiceREST.Allowed_User_List_For_Grant_Revoke, userName); - } - - public boolean isUserRangerAdmin(String username) { - boolean isAdmin = false; - try { - VXUser vxUser = xUserService.getXUserByUserName(username); - if (vxUser != null && (vxUser.getUserRoleList().contains(RangerConstants.ROLE_ADMIN) || vxUser.getUserRoleList().contains(RangerConstants.ROLE_SYS_ADMIN))) { - isAdmin = true; - } - } catch (Exception ex) { - } - return isAdmin; - } - - public boolean isUserServiceAdmin(RangerService rangerService, String userName) { - boolean ret = isUserInConfigParameter(rangerService, ServiceDBStore.SERVICE_ADMIN_USERS, userName); - - if (!ret && userMgr != null && userMgr.xUserMgr != null) { - ret = isAnyGroupInConfigParameter(rangerService, ServiceDBStore.SERVICE_ADMIN_GROUPS, userMgr.xUserMgr.getGroupsForUser(userName)); - } - - return ret; - } - - public boolean isUserInConfigParameter(RangerService rangerService, String configParamName, String userName) { - Map map = rangerService.getConfigs(); - - if (map != null && map.containsKey(configParamName)) { - String userNames = map.get(configParamName); - String[] userList = userNames.split(","); - if (userList != null) { - for (String u : userList) { - if ("*".equals(u) || (userName != null && u.equalsIgnoreCase(userName))) { - return true; - } - } - } - } - return false; - } - - public boolean isAnyGroupInConfigParameter(RangerService rangerService, String configParamName, Set groupNames) { - boolean ret = false; - Map map = rangerService.getConfigs(); - String cfgValue = map != null ? map.get(configParamName) : null; - - if (StringUtils.isNotBlank(cfgValue) && CollectionUtils.isNotEmpty(groupNames)) { - String[] svcCfgGroupNames = cfgValue.split(","); - - for (String svcCfgGroupName : svcCfgGroupNames) { - if (RangerConstants.GROUP_PUBLIC.equals(svcCfgGroupName) || groupNames.contains(svcCfgGroupName)) { - ret = true; - - break; - } - } - } - - return ret; - } - - public void blockAuditorRoleUser() { - UserSessionBase session = ContextUtil.getCurrentUserSession(); - if (session != null) { - if (session.isAuditKeyAdmin() || session.isAuditUserAdmin()) { - VXResponse vXResponse = new VXResponse(); - vXResponse.setStatusCode(HttpServletResponse.SC_FORBIDDEN); - vXResponse.setMsgDesc("Operation" - + " denied. LoggedInUser=" - + session.getXXPortalUser().getId() - + " ,isn't permitted to perform the action."); - throw restErrorUtil.generateRESTException(vXResponse); - } + } + + if (matchFound) { + policyMatched = true; + break; + } + } + + return policyMatched; + } + + public boolean matchHivePolicy(String resourceName, List 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 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() != RangerCommonEnums.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) || 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 { - VXResponse vXResponse = new VXResponse(); - vXResponse.setStatusCode(HttpServletResponse.SC_UNAUTHORIZED); // user is null - vXResponse.setMsgDesc("Bad Credentials"); - throw restErrorUtil.generateRESTException(vXResponse); + policyMatched = true; + break; } - } + } else { + // 2. does the policy match the table? + String[] xTables = stringUtil.isEmpty(xResource.getTables()) ? null : stringUtil.split(xResource.getTables(), ","); - public boolean hasModuleAccess(String moduleName) { - UserSessionBase currentUserSession = ContextUtil.getCurrentUserSession(); - if(currentUserSession == null) { - return false; - } - if(!currentUserSession.isUserAdmin() && !currentUserSession.isAuditUserAdmin()) { - if(!currentUserSession.getRangerUserPermission().getUserPermissions().contains(moduleName)) { - return false; - } - } - return true; - } - - public void removeEmptyStrings(List list) { - if(!CollectionUtils.isEmpty(list)) { - Iterator i = list.iterator(); - while (i.hasNext()){ - String item = i.next(); - if (item == null || StringUtils.isEmpty(StringUtils.trim(item))){ - i.remove(); - } - } - trimAll(list); - } - } - - public void trimAll(List list) { - if(!CollectionUtils.isEmpty(list)) { - for (int i = 0; i < list.size(); i++) { - String item=list.get(i); - if(item.startsWith(" ") || item.endsWith(" ")) { - list.set(i, StringUtils.trim(item)); - } - } - } - } - - public static boolean isBulkMode() { - return ContextUtil.isBulkModeContext(); - } - - public static boolean setBulkMode(boolean val) { - RangerContextHolder.getOrCreateOpContext().setBulkModeContext(val); - - return isBulkMode(); - } - - public boolean getCreatePrincipalsIfAbsent() { - RangerAdminOpContext opContext = RangerContextHolder.getOpContext(); - Boolean ret = opContext != null ? opContext.getCreatePrincipalsIfAbsent() : null; - - return ret != null && ret; - } - - //should be used only in bulk operation like importPolicies, policies delete. - public void bulkModeOnlyFlushAndClear() { - if (BATCH_CLEAR_ENABLED) { - XXDBBaseDao xXDBBaseDao = daoManager.getXXDBBase(); - if (xXDBBaseDao != null) { - xXDBBaseDao.flush(); - xXDBBaseDao.clear(); - } - } - } - - public boolean checkAdminAccess() { - UserSessionBase currentUserSession = ContextUtil.getCurrentUserSession(); - if (currentUserSession != null) { - return currentUserSession.isUserAdmin(); - } else { - VXResponse vXResponse = new VXResponse(); - vXResponse.setStatusCode(HttpServletResponse.SC_UNAUTHORIZED); // user is null - vXResponse.setMsgDesc("Bad Credentials"); - throw restErrorUtil.generateRESTException(vXResponse); - } - } - - public boolean isGdsServiceDef(XXDBBase xxdbBase) { - return (xxdbBase instanceof XXServiceDef) && EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_GDS_NAME.equals(((XXServiceDef) xxdbBase).getName()); - } - - public boolean isGdsService(XXDBBase xxdbBase) { - return (xxdbBase instanceof XXService) && EmbeddedServiceDefsUtil.instance().getGdsServiceDefId() == ((XXService) xxdbBase).getType(); - } + matchFound = (xTables == null || xTables.length == 0) || 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) || matchPath(colName, xColumns); + + if (xResource.getColumnType() == AppConstants.POLICY_EXCLUSION) { + matchFound = !matchFound; + } + + if (!matchFound) { + continue; + } else { + 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; + } + + public Long getPublicGroupId() { + XXGroup xXGroupPublic = daoManager.getXXGroup().findByGroupName(RangerConstants.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 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); + } + } + + return false; + } + + /** + * return List + *

+ * List of all possible parent return type for some specific resourceType + * + * @param resourceType , assetType + */ + public List getResorceTypeParentHirearchy(int resourceType, int assetType) { + List resourceTypeList = new ArrayList<>(); + + 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 pathToCheckArray = new ArrayList<>(); + List wildcardPathArray = new ArrayList<>(); + + Collections.addAll(pathToCheckArray, pathToCheck.split(fileSeparator)); + Collections.addAll(wildcardPathArray, wildcardPath.split(fileSeparator)); + + 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; + } + + public void createTrxLog(List trxLogList) { + if (trxLogList == null || trxLogList.isEmpty()) { + return; + } + + if (guidUtil == null) { + // log a warning + return; + } + + XXTrxLogV2Dao dao = daoManager.getXXTrxLogV2(); + String trxId = Long.toString(guidUtil.genLong()); + UserSessionBase usb = ContextUtil.getCurrentUserSession(); + String sessionId = usb != null && usb.getSessionId() != null ? usb.getSessionId().toString() : null; + Long userId = usb != null ? usb.getUserId() : null; + + for (XXTrxLogV2 xTrxLog : trxLogList) { + xTrxLog.setTransactionId(trxId); + xTrxLog.setSessionId(sessionId); + xTrxLog.setSessionType("Spring Authenticated Session"); + xTrxLog.setRequestId(trxId); + + if (xTrxLog.getAddedByUserId() == null) { + xTrxLog.setAddedByUserId(userId); + } + + dao.create(xTrxLog); + } + } + + public String getDBVersion() { + return daoManager.getXXUser().getDBVersion(); + } + + public String getAuditDBType() { + return auditDBType; + } + + public void setAuditDBType(String auditDBType) { + this.auditDBType = auditDBType; + } + + /** + * return true id current logged in session is owned by keyadmin + * + * @return + */ + public boolean isKeyAdmin() { + UserSessionBase currentUserSession = ContextUtil.getCurrentUserSession(); + + if (currentUserSession == null) { + logger.debug("Unable to find session."); + + return false; + } + + return currentUserSession.isKeyAdmin(); + } + + public boolean isAuditKeyAdmin() { + UserSessionBase currentUserSession = ContextUtil.getCurrentUserSession(); + + if (currentUserSession == null) { + logger.debug("Unable to find session."); + return false; + } + + return (currentUserSession.isAuditKeyAdmin()); + } + + /** + * @param xxDbBase + * @param baseModel + * @return Boolean + * @NOTE: Kindly check all the references of this function before making any changes + */ + public Boolean hasAccess(XXDBBase xxDbBase, RangerBaseModelObject baseModel) { + UserSessionBase session = ContextUtil.getCurrentUserSession(); + + if (session == null) { + logger.info("User session not found, granting access."); + return true; + } + + boolean isKeyAdmin = session.isKeyAdmin(); + boolean isSysAdmin = session.isUserAdmin(); + boolean isAuditor = session.isAuditUserAdmin(); + boolean isAuditorKeyAdmin = session.isAuditKeyAdmin(); + boolean isUser = session.getUserRoleList().contains(RangerConstants.ROLE_USER); + + if (xxDbBase instanceof XXServiceDef) { + return hasAccessToXXServiceDef((XXServiceDef) xxDbBase, isKeyAdmin, isSysAdmin, isAuditor, isAuditorKeyAdmin, isUser); + } + + if (xxDbBase instanceof XXService) { + return hasAccessToXXService((XXService) xxDbBase, isKeyAdmin, isSysAdmin, isAuditor, isAuditorKeyAdmin, isUser); + } + + if (baseModel instanceof RangerServiceHeaderInfo) { + return hasAccessToRangerServiceHeaderInfo((RangerServiceHeaderInfo) baseModel, isKeyAdmin, isSysAdmin, isAuditor, isAuditorKeyAdmin, isUser); + } + + return false; + } + + public void hasAdminPermissions(String objType) { + UserSessionBase session = ContextUtil.getCurrentUserSession(); + + if (session == null) { + throw restErrorUtil.createRESTException("UserSession cannot be null, only Admin can create/update/delete " + objType, MessageEnums.OPER_NO_PERMISSION); + } + + if (!session.isKeyAdmin() && !session.isUserAdmin()) { + throw restErrorUtil.createRESTException("This user is not allowed this operation. Only users with Admin permission have access to this operation " + objType, MessageEnums.OPER_NO_PERMISSION); + } + } + + public void hasKMSPermissions(String objType, String implClassName) { + UserSessionBase session = ContextUtil.getCurrentUserSession(); + + if (session == null) { + throw restErrorUtil.createRESTException("UserSession cannot be null, only KeyAdmin can create/update/delete " + objType, MessageEnums.OPER_NO_PERMISSION); + } + + if (session.isKeyAdmin() && !EmbeddedServiceDefsUtil.KMS_IMPL_CLASS_NAME.equals(implClassName)) { + throw restErrorUtil.createRESTException("KeyAdmin can create/update/delete only KMS " + objType, MessageEnums.OPER_NO_PERMISSION); + } + + // TODO: As of now we are allowing SYS_ADMIN to create/update/read/delete all the + // services including KMS + + if ("Service-Def".equalsIgnoreCase(objType) && session.isUserAdmin() && EmbeddedServiceDefsUtil.KMS_IMPL_CLASS_NAME.equals(implClassName)) { + throw restErrorUtil.createRESTException("System Admin cannot create/update/delete KMS " + objType, MessageEnums.OPER_NO_PERMISSION); + } + } + + public boolean checkUserAccessible(VXUser vXUser) { + boolean isAccessible = true; + Collection roleList = userMgr.getRolesByLoginId(vXUser.getName()); + + if (isKeyAdmin()) { + if (vXUser.getUserRoleList().contains(RangerConstants.ROLE_SYS_ADMIN) + || vXUser.getUserRoleList().contains(RangerConstants.ROLE_ADMIN_AUDITOR) + || roleList.contains(RangerConstants.ROLE_SYS_ADMIN) + || roleList.contains(RangerConstants.ROLE_ADMIN_AUDITOR)) { + isAccessible = false; + } + } + if (isAdmin()) { + if (vXUser.getUserRoleList().contains(RangerConstants.ROLE_KEY_ADMIN) + || vXUser.getUserRoleList().contains(RangerConstants.ROLE_KEY_ADMIN_AUDITOR) + || roleList.contains(RangerConstants.ROLE_KEY_ADMIN) + || roleList.contains(RangerConstants.ROLE_KEY_ADMIN_AUDITOR)) { + isAccessible = false; + } + } + + if (!isAccessible) { + throw restErrorUtil.createRESTException("Logged in user is not allowed to create/update user", MessageEnums.OPER_NO_PERMISSION); + } + + return isAccessible; + } + + public boolean isSSOEnabled() { + UserSessionBase session = ContextUtil.getCurrentUserSession(); + + if (session != null) { + return session.isSSOEnabled() == null ? PropertiesUtil.getBooleanProperty("ranger.sso.enabled", false) : session.isSSOEnabled(); + } else { + throw restErrorUtil.createRESTException("User session is not created", MessageEnums.OPER_NOT_ALLOWED_FOR_STATE); + } + } + + public boolean isUserAllowed(RangerService rangerService, String cfgNameAllowedUsers) { + Map map = rangerService.getConfigs(); + String user = null; + UserSessionBase userSession = ContextUtil.getCurrentUserSession(); + + if (userSession != null) { + user = userSession.getLoginId(); + } + + if (map != null && map.containsKey(cfgNameAllowedUsers)) { + String userNames = map.get(cfgNameAllowedUsers); + String[] userList = userNames.split(","); + + for (String u : userList) { + if ("*".equals(u) || (u.equalsIgnoreCase(user))) { + return true; + } + } + } + + return false; + } + + public boolean isUserAllowedForGrantRevoke(RangerService rangerService, String userName) { + return isUserInConfigParameter(rangerService, ServiceREST.Allowed_User_List_For_Grant_Revoke, userName); + } + + public boolean isUserRangerAdmin(String username) { + boolean isAdmin = false; + + try { + VXUser vxUser = xUserService.getXUserByUserName(username); + + if (vxUser != null && (vxUser.getUserRoleList().contains(RangerConstants.ROLE_ADMIN) || vxUser.getUserRoleList().contains(RangerConstants.ROLE_SYS_ADMIN))) { + isAdmin = true; + } + } catch (Exception ex) { + // ignored + } + + return isAdmin; + } + + public boolean isUserServiceAdmin(RangerService rangerService, String userName) { + boolean ret = isUserInConfigParameter(rangerService, ServiceDBStore.SERVICE_ADMIN_USERS, userName); + + if (!ret && userMgr != null && userMgr.xUserMgr != null) { + ret = isAnyGroupInConfigParameter(rangerService, ServiceDBStore.SERVICE_ADMIN_GROUPS, userMgr.xUserMgr.getGroupsForUser(userName)); + } + + return ret; + } + + public boolean isUserInConfigParameter(RangerService rangerService, String configParamName, String userName) { + Map map = rangerService.getConfigs(); + + if (map != null && map.containsKey(configParamName)) { + String userNames = map.get(configParamName); + String[] userList = userNames.split(","); + + for (String u : userList) { + if ("*".equals(u) || (u.equalsIgnoreCase(userName))) { + return true; + } + } + } + + return false; + } + + public boolean isAnyGroupInConfigParameter(RangerService rangerService, String configParamName, Set groupNames) { + boolean ret = false; + Map map = rangerService.getConfigs(); + String cfgValue = map != null ? map.get(configParamName) : null; + + if (StringUtils.isNotBlank(cfgValue) && CollectionUtils.isNotEmpty(groupNames)) { + String[] svcCfgGroupNames = cfgValue.split(","); + + for (String svcCfgGroupName : svcCfgGroupNames) { + if (RangerConstants.GROUP_PUBLIC.equals(svcCfgGroupName) || groupNames.contains(svcCfgGroupName)) { + ret = true; + + break; + } + } + } + + return ret; + } + + public void blockAuditorRoleUser() { + UserSessionBase session = ContextUtil.getCurrentUserSession(); + + if (session != null) { + if (session.isAuditKeyAdmin() || session.isAuditUserAdmin()) { + VXResponse vXResponse = new VXResponse(); + + vXResponse.setStatusCode(HttpServletResponse.SC_FORBIDDEN); + vXResponse.setMsgDesc("Operation denied. LoggedInUser=" + session.getXXPortalUser().getId() + " ,isn't permitted to perform the action."); + + throw restErrorUtil.generateRESTException(vXResponse); + } + } else { + VXResponse vXResponse = new VXResponse(); + + vXResponse.setStatusCode(HttpServletResponse.SC_UNAUTHORIZED); // user is null + vXResponse.setMsgDesc("Bad Credentials"); + + throw restErrorUtil.generateRESTException(vXResponse); + } + } + + public boolean hasModuleAccess(String moduleName) { + UserSessionBase currentUserSession = ContextUtil.getCurrentUserSession(); + + if (currentUserSession == null) { + return false; + } + + if (!currentUserSession.isUserAdmin() && !currentUserSession.isAuditUserAdmin()) { + return currentUserSession.getRangerUserPermission().getUserPermissions().contains(moduleName); + } + + return true; + } + + public void removeEmptyStrings(List list) { + if (!CollectionUtils.isEmpty(list)) { + list.removeIf(StringUtils::isBlank); + + trimAll(list); + } + } + + public void trimAll(List list) { + if (!CollectionUtils.isEmpty(list)) { + for (int i = 0; i < list.size(); i++) { + String item = list.get(i); + + if (item.startsWith(" ") || item.endsWith(" ")) { + list.set(i, StringUtils.trim(item)); + } + } + } + } + + public boolean getCreatePrincipalsIfAbsent() { + RangerAdminOpContext opContext = RangerContextHolder.getOpContext(); + Boolean ret = opContext != null ? opContext.getCreatePrincipalsIfAbsent() : null; + + return ret != null && ret; + } + + //should be used only in bulk operation like importPolicies, policies delete. + public void bulkModeOnlyFlushAndClear() { + if (BATCH_CLEAR_ENABLED) { + XXDBBaseDao xXDBBaseDao = daoManager.getXXDBBase(); + + if (xXDBBaseDao != null) { + xXDBBaseDao.flush(); + xXDBBaseDao.clear(); + } + } + } + + public boolean checkAdminAccess() { + UserSessionBase currentUserSession = ContextUtil.getCurrentUserSession(); + + if (currentUserSession != null) { + return currentUserSession.isUserAdmin(); + } else { + VXResponse vXResponse = new VXResponse(); + + vXResponse.setStatusCode(HttpServletResponse.SC_UNAUTHORIZED); // user is null + vXResponse.setMsgDesc("Bad Credentials"); + + throw restErrorUtil.generateRESTException(vXResponse); + } + } + + public boolean isGdsServiceDef(XXDBBase xxdbBase) { + return (xxdbBase instanceof XXServiceDef) && EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_GDS_NAME.equals(((XXServiceDef) xxdbBase).getName()); + } + + public boolean isGdsService(XXDBBase xxdbBase) { + return (xxdbBase instanceof XXService) && EmbeddedServiceDefsUtil.instance().getGdsServiceDefId() == ((XXService) xxdbBase).getType(); + } + + /** + * 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 xResourceList, Long xUserId, int permission) { + boolean matchFound = false; + + resourceName = replaceMetaChars(resourceName); + + for (XXResource xResource : xResourceList) { + if (xResource.getResourceStatus() != RangerCommonEnums.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() == RangerCommonEnums.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 xUserId + * @param permission + * @return + */ + private boolean matchKnoxPolicy(String resourceName, List xResourceList, 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() != RangerCommonEnums.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 || "".equalsIgnoreCase(xResource.getTopologies())) ? null : stringUtil.split(xResource.getTopologies(), ","); + String[] xServices = (xResource.getServices() == null || "".equalsIgnoreCase(xResource.getServices())) ? 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; + } + } else if (index == 1) { // check whether given service resource matches with any existing service resource + 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 xUserId + * @param permission + * @return + */ + private boolean matchStormPolicy(String resourceName, List xResourceList, 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() != RangerCommonEnums.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 || "".equalsIgnoreCase(xResource.getTopologies())) ? null : stringUtil.split(xResource.getTopologies(), ","); + 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 && 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 + } + + if (matchFound) { + policyMatched = true; + break; + } + } + } + + return policyMatched; + } + + /** + * 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(); + + if (randomNum < 0) { + randomNum = Math.abs(randomNum); + } + + return ((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 userGroups = daoManager.getXXGroup().findByUserId(xUserId); + List 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.equals(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; + } + + /** + * 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; + } + + private Boolean hasAccessToXXServiceDef(XXServiceDef xxDbBase, boolean isKeyAdmin, boolean isSysAdmin, boolean isAuditor, boolean isAuditorKeyAdmin, boolean isUser) { + XXServiceDef xServiceDef = xxDbBase; + final String implClass = xServiceDef.getImplclassname(); + + if (EmbeddedServiceDefsUtil.KMS_IMPL_CLASS_NAME.equals(implClass)) { + // KMS case + return isKeyAdmin || isAuditorKeyAdmin; + } else { + // Other cases - implClass can be null! + return isSysAdmin || isUser || isAuditor; + } + } + + private Boolean hasAccessToXXService(XXService xxDbBase, boolean isKeyAdmin, boolean isSysAdmin, boolean isAuditor, boolean isAuditorKeyAdmin, boolean isUser) { + // TODO: As of now we are allowing SYS_ADMIN to create/update/read/delete all the + // services including KMS + if (isSysAdmin || isAuditor) { + return true; + } + + XXService xService = xxDbBase; + XXServiceDef xServiceDef = daoManager.getXXServiceDef().getById(xService.getType()); + String implClass = xServiceDef.getImplclassname(); + + if (EmbeddedServiceDefsUtil.KMS_IMPL_CLASS_NAME.equals(implClass)) { + // KMS case + return isKeyAdmin || isAuditorKeyAdmin; + } else { + // Other cases - implClass can be null! + return isUser; + } + } + + private Boolean hasAccessToRangerServiceHeaderInfo(RangerServiceHeaderInfo serviceHeader, boolean isKeyAdmin, boolean isSysAdmin, boolean isAuditor, boolean isAuditorKeyAdmin, boolean isUser) { + // TODO: As of now we are allowing SYS_ADMIN to read all the + // services including KMS + if (isSysAdmin || isAuditor) { + return true; + } + + return EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_KMS_NAME.equals(serviceHeader.getType()) ? (isKeyAdmin || isAuditorKeyAdmin) : isUser; + } } diff --git a/security-admin/src/main/java/org/apache/ranger/biz/RangerPolicyAdmin.java b/security-admin/src/main/java/org/apache/ranger/biz/RangerPolicyAdmin.java index 15a1e71188..68c9200e15 100644 --- a/security-admin/src/main/java/org/apache/ranger/biz/RangerPolicyAdmin.java +++ b/security-admin/src/main/java/org/apache/ranger/biz/RangerPolicyAdmin.java @@ -19,11 +19,6 @@ package org.apache.ranger.biz; -import java.util.Collection; -import java.util.List; -import java.util.Map; -import java.util.Set; - import org.apache.ranger.plugin.model.RangerPolicy; import org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyResource; import org.apache.ranger.plugin.model.RangerServiceDef; @@ -32,8 +27,12 @@ import org.apache.ranger.plugin.util.GrantRevokeRequest; import org.apache.ranger.plugin.util.RangerRoles; -public interface RangerPolicyAdmin { +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.Set; +public interface RangerPolicyAdmin { boolean isDelegatedAdminAccessAllowed(RangerAccessResource resource, String zoneName, String user, Set userGroups, Set accessTypes); boolean isDelegatedAdminAccessAllowedForRead(RangerPolicy policy, String user, Set userGroups, Set roles, Map evalContext); @@ -69,5 +68,4 @@ public interface RangerPolicyAdmin { List getAllowedUnzonedPolicies(String user, Set userGroups, String accessType); void setServiceStore(ServiceStore svcStore); - } diff --git a/security-admin/src/main/java/org/apache/ranger/biz/RangerPolicyAdminCache.java b/security-admin/src/main/java/org/apache/ranger/biz/RangerPolicyAdminCache.java index 5bd3a0934a..3bd5fb5537 100644 --- a/security-admin/src/main/java/org/apache/ranger/biz/RangerPolicyAdminCache.java +++ b/security-admin/src/main/java/org/apache/ranger/biz/RangerPolicyAdminCache.java @@ -19,18 +19,11 @@ package org.apache.ranger.biz; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; -import java.util.concurrent.locks.Lock; -import java.util.concurrent.locks.ReentrantLock; - import org.apache.ranger.authorization.hadoop.config.RangerPluginConfig; import org.apache.ranger.plugin.model.RangerServiceDef; -import org.apache.ranger.plugin.store.RoleStore; import org.apache.ranger.plugin.policyengine.RangerPluginContext; import org.apache.ranger.plugin.policyengine.RangerPolicyEngineOptions; +import org.apache.ranger.plugin.store.RoleStore; import org.apache.ranger.plugin.store.SecurityZoneStore; import org.apache.ranger.plugin.store.ServiceStore; import org.apache.ranger.plugin.util.RangerPolicyDeltaUtil; @@ -39,177 +32,188 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -public class RangerPolicyAdminCache { +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReentrantLock; - static class RangerPolicyAdminWrapper { - final RangerPolicyAdmin policyAdmin; - final Lock lock = new ReentrantLock(); - - RangerPolicyAdminWrapper(RangerPolicyAdmin policyAdmin) { - this.policyAdmin = policyAdmin; - } - RangerPolicyAdmin getPolicyAdmin() { - return policyAdmin; - } - Lock getLock() { - return lock; - } - } - - private static final Logger LOG = LoggerFactory.getLogger(RangerPolicyAdminCache.class); - - private final Map policyAdminCache = Collections.synchronizedMap(new HashMap<>()); - - final RangerPolicyAdmin getServicePoliciesAdmin(String serviceName, ServiceStore svcStore, RoleStore roleStore, SecurityZoneStore zoneStore, RangerPolicyEngineOptions options) { - - if (serviceName == null || svcStore == null || roleStore == null || zoneStore == null) { - LOG.warn("Cannot get policy-admin for null serviceName or serviceStore or roleStore or zoneStore"); - - return null; - } - - try { - if (!svcStore.serviceExists(serviceName)) { - LOG.warn("Service:[" + serviceName + "] does not exist in service-store. Returning null policy-engine!"); - - policyAdminCache.remove(serviceName); - - return null; - } - } catch (Exception exception) { - LOG.error("Failed to check if service:[" + serviceName + "] exists in service-store", exception); - - return null; - } - - long policyVersion; - long roleVersion; - RangerRoles roles; - boolean isRolesUpdated = true; - - RangerPolicyAdminWrapper ret = policyAdminCache.get(serviceName); - - try { - if (ret == null) { - policyVersion = -1L; - roleVersion = -1L; - roles = roleStore.getRoles(serviceName, roleVersion); - - if (roles == null) { - if (LOG.isDebugEnabled()) { - LOG.debug("There are no roles in ranger-admin for service:" + serviceName + "]"); - } - } - } else { - policyVersion = ret.getPolicyAdmin().getPolicyVersion(); - roleVersion = ret.getPolicyAdmin().getRoleVersion(); - roles = roleStore.getRoles(serviceName, roleVersion); - - if (roles == null) { // No changes to roles - roles = roleStore.getRoles(serviceName, -1L); - isRolesUpdated = false; - } - } - - ServicePolicies policies = svcStore.getServicePoliciesIfUpdated(serviceName, policyVersion, ServiceDBStore.isSupportsPolicyDeltas()); - - if (policies != null) { - ret = addOrUpdatePolicyAdmin(ret, policies, roles, options); - - if (ret == null) { - LOG.error("getPolicyAdmin(" + serviceName + "): failed to build engine from policies from service-store"); - } else { - if (isRolesUpdated) { - ret.getPolicyAdmin().setRoles(roles); - } - } - } - } catch (Exception exception) { - LOG.error("getPolicyAdmin(" + serviceName + "): failed to get latest policies from service-store", exception); - } - - if (ret == null) { - LOG.error("Policy-engine is not built! Returning null policy-engine!"); - } else { - ret.getPolicyAdmin().setServiceStore(svcStore); - } - - return ret == null ? null : ret.getPolicyAdmin(); - - } - - private RangerPolicyAdminWrapper addOrUpdatePolicyAdmin(RangerPolicyAdminWrapper policyAdminWrapper, ServicePolicies policies, RangerRoles roles, RangerPolicyEngineOptions options) { - final RangerPolicyAdminWrapper ret; - - RangerPolicyAdmin policyAdmin = null; - boolean isPolicyEngineShared = false; - - RangerPolicyAdminImpl oldPolicyAdmin = policyAdminWrapper == null ? null : (RangerPolicyAdminImpl) policyAdminWrapper.getPolicyAdmin(); - Boolean hasPolicyDeltas = RangerPolicyDeltaUtil.hasPolicyDeltas(policies); - - if (hasPolicyDeltas != null) { - if (hasPolicyDeltas.equals(Boolean.TRUE)) { - if (oldPolicyAdmin != null) { - boolean isLocked = false; - - try { - policyAdminWrapper.getLock().lockInterruptibly(); - isLocked = true; - } catch (Exception e) { - // Ignore - } - - if (isLocked) { - try { - policyAdmin = RangerPolicyAdminImpl.getPolicyAdmin(oldPolicyAdmin, policies); - if (policyAdmin != null) { - policyAdmin.setRoles(roles); - isPolicyEngineShared = true; - } - } finally { - policyAdminWrapper.getLock().unlock(); - } - } - } else { - LOG.error("Old policy engine is null! Cannot apply deltas without old policy engine!"); - } - } else { - if (policies.getPolicies() == null) { - policies.setPolicies(new ArrayList<>()); - } - policyAdmin = addPolicyAdmin(policies, roles, options); - } - } else { - LOG.warn("Provided policies do not require policy change !! [" + policies + "]. Keeping old policy-engine!"); - policyAdmin = oldPolicyAdmin; - } - - if (policyAdmin != null) { - if (LOG.isDebugEnabled()) { - if (oldPolicyAdmin == null) { - LOG.debug("Adding policy-engine to cache with serviceName:[" + policies.getServiceName() + "] as key"); - } else { - LOG.debug("Replacing policy-engine in cache with serviceName:[" + policies.getServiceName() + "] as key"); - } - } - ret = new RangerPolicyAdminWrapper(policyAdmin); - policyAdminCache.put(policies.getServiceName(), ret); - if (oldPolicyAdmin != null && oldPolicyAdmin != policyAdmin) { - oldPolicyAdmin.releaseResources(!isPolicyEngineShared); - } - } else { - LOG.warn("Could not build new policy-engine."); - ret = null; - } - - return ret; - } - - private RangerPolicyAdmin addPolicyAdmin(ServicePolicies policies, RangerRoles roles, RangerPolicyEngineOptions options) { - RangerServiceDef serviceDef = policies.getServiceDef(); - String serviceType = (serviceDef != null) ? serviceDef.getName() : ""; - RangerPluginContext rangerPluginContext = new RangerPluginContext(new RangerPluginConfig(serviceType, null, "ranger-admin", null, null, options)); - - return new RangerPolicyAdminImpl(policies, rangerPluginContext, roles); - } +public class RangerPolicyAdminCache { + private static final Logger LOG = LoggerFactory.getLogger(RangerPolicyAdminCache.class); + + private final Map policyAdminCache = Collections.synchronizedMap(new HashMap<>()); + + final RangerPolicyAdmin getServicePoliciesAdmin(String serviceName, ServiceStore svcStore, RoleStore roleStore, SecurityZoneStore zoneStore, RangerPolicyEngineOptions options) { + if (serviceName == null || svcStore == null || roleStore == null || zoneStore == null) { + LOG.warn("Cannot get policy-admin for null serviceName or serviceStore or roleStore or zoneStore"); + + return null; + } + + try { + if (!svcStore.serviceExists(serviceName)) { + LOG.warn("Service:[{}] does not exist in service-store. Returning null policy-engine!", serviceName); + + policyAdminCache.remove(serviceName); + + return null; + } + } catch (Exception exception) { + LOG.error("Failed to check if service:[{}] exists in service-store", serviceName, exception); + + return null; + } + + long policyVersion; + long roleVersion; + RangerRoles roles; + boolean isRolesUpdated = true; + + RangerPolicyAdminWrapper ret = policyAdminCache.get(serviceName); + + try { + if (ret == null) { + policyVersion = -1L; + roleVersion = -1L; + roles = roleStore.getRoles(serviceName, roleVersion); + + if (roles == null) { + LOG.debug("There are no roles in ranger-admin for service:{}]", serviceName); + } + } else { + policyVersion = ret.getPolicyAdmin().getPolicyVersion(); + roleVersion = ret.getPolicyAdmin().getRoleVersion(); + roles = roleStore.getRoles(serviceName, roleVersion); + + if (roles == null) { // No changes to roles + roles = roleStore.getRoles(serviceName, -1L); + isRolesUpdated = false; + } + } + + ServicePolicies policies = svcStore.getServicePoliciesIfUpdated(serviceName, policyVersion, ServiceDBStore.isSupportsPolicyDeltas()); + + if (policies != null) { + ret = addOrUpdatePolicyAdmin(ret, policies, roles, options); + + if (ret == null) { + LOG.error("getPolicyAdmin({}): failed to build engine from policies from service-store", serviceName); + } else { + if (isRolesUpdated) { + ret.getPolicyAdmin().setRoles(roles); + } + } + } + } catch (Exception exception) { + LOG.error("getPolicyAdmin({}): failed to get latest policies from service-store", serviceName, exception); + } + + if (ret == null) { + LOG.error("Policy-engine is not built! Returning null policy-engine!"); + } else { + ret.getPolicyAdmin().setServiceStore(svcStore); + } + + return ret == null ? null : ret.getPolicyAdmin(); + } + + private RangerPolicyAdminWrapper addOrUpdatePolicyAdmin(RangerPolicyAdminWrapper policyAdminWrapper, ServicePolicies policies, RangerRoles roles, RangerPolicyEngineOptions options) { + final RangerPolicyAdminWrapper ret; + + RangerPolicyAdmin policyAdmin = null; + boolean isPolicyEngineShared = false; + RangerPolicyAdminImpl oldPolicyAdmin = policyAdminWrapper == null ? null : (RangerPolicyAdminImpl) policyAdminWrapper.getPolicyAdmin(); + Boolean hasPolicyDeltas = RangerPolicyDeltaUtil.hasPolicyDeltas(policies); + + if (hasPolicyDeltas != null) { + if (hasPolicyDeltas.equals(Boolean.TRUE)) { + if (oldPolicyAdmin != null) { + boolean isLocked = false; + + try { + policyAdminWrapper.getLock().lockInterruptibly(); + + isLocked = true; + } catch (Exception e) { + // Ignore + } + + if (isLocked) { + try { + policyAdmin = RangerPolicyAdminImpl.getPolicyAdmin(oldPolicyAdmin, policies); + + if (policyAdmin != null) { + policyAdmin.setRoles(roles); + + isPolicyEngineShared = true; + } + } finally { + policyAdminWrapper.getLock().unlock(); + } + } + } else { + LOG.error("Old policy engine is null! Cannot apply deltas without old policy engine!"); + } + } else { + if (policies.getPolicies() == null) { + policies.setPolicies(new ArrayList<>()); + } + + policyAdmin = addPolicyAdmin(policies, roles, options); + } + } else { + LOG.warn("Provided policies do not require policy change !! [{}]. Keeping old policy-engine!", policies); + + policyAdmin = oldPolicyAdmin; + } + + if (policyAdmin != null) { + if (LOG.isDebugEnabled()) { + if (oldPolicyAdmin == null) { + LOG.debug("Adding policy-engine to cache with serviceName:[{}] as key", policies.getServiceName()); + } else { + LOG.debug("Replacing policy-engine in cache with serviceName:[{}] as key", policies.getServiceName()); + } + } + + ret = new RangerPolicyAdminWrapper(policyAdmin); + + policyAdminCache.put(policies.getServiceName(), ret); + + if (oldPolicyAdmin != null && oldPolicyAdmin != policyAdmin) { + oldPolicyAdmin.releaseResources(!isPolicyEngineShared); + } + } else { + LOG.warn("Could not build new policy-engine."); + ret = null; + } + + return ret; + } + + private RangerPolicyAdmin addPolicyAdmin(ServicePolicies policies, RangerRoles roles, RangerPolicyEngineOptions options) { + RangerServiceDef serviceDef = policies.getServiceDef(); + String serviceType = (serviceDef != null) ? serviceDef.getName() : ""; + RangerPluginContext rangerPluginContext = new RangerPluginContext(new RangerPluginConfig(serviceType, null, "ranger-admin", null, null, options)); + + return new RangerPolicyAdminImpl(policies, rangerPluginContext, roles); + } + + static class RangerPolicyAdminWrapper { + final RangerPolicyAdmin policyAdmin; + final Lock lock = new ReentrantLock(); + + RangerPolicyAdminWrapper(RangerPolicyAdmin policyAdmin) { + this.policyAdmin = policyAdmin; + } + + RangerPolicyAdmin getPolicyAdmin() { + return policyAdmin; + } + + Lock getLock() { + return lock; + } + } } diff --git a/security-admin/src/main/java/org/apache/ranger/biz/RangerPolicyAdminCacheForEngineOptions.java b/security-admin/src/main/java/org/apache/ranger/biz/RangerPolicyAdminCacheForEngineOptions.java index 771d320289..8aee0a42ef 100644 --- a/security-admin/src/main/java/org/apache/ranger/biz/RangerPolicyAdminCacheForEngineOptions.java +++ b/security-admin/src/main/java/org/apache/ranger/biz/RangerPolicyAdminCacheForEngineOptions.java @@ -19,8 +19,8 @@ package org.apache.ranger.biz; -import org.apache.ranger.plugin.store.RoleStore; import org.apache.ranger.plugin.policyengine.RangerPolicyEngineOptions; +import org.apache.ranger.plugin.store.RoleStore; import org.apache.ranger.plugin.store.SecurityZoneStore; import org.apache.ranger.plugin.store.ServiceStore; @@ -29,7 +29,7 @@ import java.util.Map; public class RangerPolicyAdminCacheForEngineOptions { - private static volatile RangerPolicyAdminCacheForEngineOptions sInstance = null; + private static volatile RangerPolicyAdminCacheForEngineOptions sInstance; private final Map policyAdminCacheForEngineOptions = Collections.synchronizedMap(new HashMap<>()); @@ -55,7 +55,6 @@ public final RangerPolicyAdmin getServicePoliciesAdmin(String serviceName, Servi } private RangerPolicyAdmin getServicePoliciesAdmin(String serviceName, ServiceStore svcStore, RoleStore roleStore, SecurityZoneStore zoneStore, RangerPolicyEngineOptions options) { - RangerPolicyAdminCache policyAdminCache = policyAdminCacheForEngineOptions.get(options); if (policyAdminCache == null) { @@ -73,4 +72,3 @@ private RangerPolicyAdmin getServicePoliciesAdmin(String serviceName, ServiceSto return policyAdminCache.getServicePoliciesAdmin(serviceName, svcStore, roleStore, zoneStore, options); } } - diff --git a/security-admin/src/main/java/org/apache/ranger/biz/RangerPolicyAdminImpl.java b/security-admin/src/main/java/org/apache/ranger/biz/RangerPolicyAdminImpl.java index 2434db1710..95ed16dad5 100644 --- a/security-admin/src/main/java/org/apache/ranger/biz/RangerPolicyAdminImpl.java +++ b/security-admin/src/main/java/org/apache/ranger/biz/RangerPolicyAdminImpl.java @@ -63,23 +63,31 @@ import java.util.Set; public class RangerPolicyAdminImpl implements RangerPolicyAdmin { - private static final Logger LOG = LoggerFactory.getLogger(RangerPolicyAdminImpl.class); - + private static final Logger LOG = LoggerFactory.getLogger(RangerPolicyAdminImpl.class); private static final Logger PERF_POLICYENGINE_REQUEST_LOG = RangerPerfTracer.getPerfLogger("policyengine.request"); - private final PolicyEngine policyEngine; - private final RangerAccessRequestProcessor requestProcessor; - private final static Map wildcardEvalContext = new HashMap() { + private static final Map wildcardEvalContext = new HashMap() { @Override - public Object get(Object key) { return RangerAbstractResourceMatcher.WILDCARD_ASTERISK; } + public Object get(Object key) { + return RangerAbstractResourceMatcher.WILDCARD_ASTERISK; + } }; + + private final PolicyEngine policyEngine; + private final RangerAccessRequestProcessor requestProcessor; private ServiceDBStore serviceDBStore; - static { - wildcardEvalContext.put(RangerAbstractResourceMatcher.WILDCARD_ASTERISK, RangerAbstractResourceMatcher.WILDCARD_ASTERISK); + RangerPolicyAdminImpl(ServicePolicies servicePolicies, RangerPluginContext pluginContext, RangerRoles roles) { + this.policyEngine = new PolicyEngine(servicePolicies, pluginContext, roles, ServiceDBStore.SUPPORTS_IN_PLACE_POLICY_UPDATES); + this.requestProcessor = new RangerDefaultRequestProcessor(policyEngine); } - static public RangerPolicyAdmin getPolicyAdmin(final RangerPolicyAdminImpl other, final ServicePolicies servicePolicies) { + private RangerPolicyAdminImpl(final PolicyEngine policyEngine) { + this.policyEngine = policyEngine; + this.requestProcessor = new RangerDefaultRequestProcessor(policyEngine); + } + + public static RangerPolicyAdmin getPolicyAdmin(final RangerPolicyAdminImpl other, final ServicePolicies servicePolicies) { RangerPolicyAdmin ret = null; if (other != null && servicePolicies != null) { @@ -97,76 +105,53 @@ static public RangerPolicyAdmin getPolicyAdmin(final RangerPolicyAdminImpl other return ret; } - RangerPolicyAdminImpl(ServicePolicies servicePolicies, RangerPluginContext pluginContext, RangerRoles roles) { - this.policyEngine = new PolicyEngine(servicePolicies, pluginContext, roles, ServiceDBStore.SUPPORTS_IN_PLACE_POLICY_UPDATES); - this.requestProcessor = new RangerDefaultRequestProcessor(policyEngine); - } - - private RangerPolicyAdminImpl(final PolicyEngine policyEngine) { - this.policyEngine = policyEngine; - this.requestProcessor = new RangerDefaultRequestProcessor(policyEngine); - } - - @Override - public void setServiceStore(ServiceStore svcStore) { - if (svcStore instanceof ServiceDBStore) { - this.serviceDBStore = (ServiceDBStore) svcStore; - } - } - @Override public boolean isDelegatedAdminAccessAllowed(RangerAccessResource resource, String zoneName, String user, Set userGroups, Set accessTypes) { - if (LOG.isDebugEnabled()) { - LOG.debug("==> RangerPolicyAdminImpl.isDelegatedAdminAccessAllowed(" + resource + ", " + zoneName + ", " + user + ", " + userGroups + ", " + accessTypes + ")"); - } + LOG.debug("==> RangerPolicyAdminImpl.isDelegatedAdminAccessAllowed({}, {}, {}, {}, {})", resource, zoneName, user, userGroups, accessTypes); boolean ret = false; RangerPerfTracer perf = null; - if(RangerPerfTracer.isPerfTraceEnabled(PERF_POLICYENGINE_REQUEST_LOG)) { + if (RangerPerfTracer.isPerfTraceEnabled(PERF_POLICYENGINE_REQUEST_LOG)) { perf = RangerPerfTracer.getPerfTracer(PERF_POLICYENGINE_REQUEST_LOG, "RangerPolicyAdminImpl.isDelegatedAdminAccessAllowed(user=" + user + ",accessTypes=" + accessTypes + "resource=" + resource.getAsString() + ")"); } try (RangerReadWriteLock.RangerLock readLock = policyEngine.getReadLock()) { - if (LOG.isDebugEnabled()) { if (readLock.isLockingEnabled()) { - LOG.debug("Acquired lock - " + readLock); + LOG.debug("Acquired lock - {}", readLock); } } final RangerPolicyRepository matchedRepository = policyEngine.getRepositoryForZone(zoneName); if (matchedRepository != null) { - Set roles = getRolesFromUserAndGroups(user, userGroups); - Set requestedAccesses = new HashSet<>(accessTypes); + Set roles = getRolesFromUserAndGroups(user, userGroups); + Set requestedAccesses = new HashSet<>(accessTypes); + RangerAccessRequestImpl request = new RangerAccessRequestImpl(); - RangerAccessRequestImpl request = new RangerAccessRequestImpl(); request.setResource(resource); for (RangerPolicyEvaluator evaluator : matchedRepository.getLikelyMatchPolicyEvaluators(request, RangerPolicy.POLICY_TYPE_ACCESS)) { - Set allowedAccesses = evaluator.getAllowedAccesses(resource, user, userGroups, roles, requestedAccesses); + if (CollectionUtils.isNotEmpty(allowedAccesses)) { requestedAccesses.removeAll(allowedAccesses); + if (CollectionUtils.isEmpty(requestedAccesses)) { - if (LOG.isDebugEnabled()) { - LOG.debug("Access granted by policy:[" + evaluator.getPolicy() + "]"); - } + LOG.debug("Access granted by policy:[{}]", evaluator.getPolicy()); + ret = true; break; } } } - } - } + RangerPerfTracer.log(perf); - if (LOG.isDebugEnabled()) { - LOG.debug("<== RangerPolicyAdminImpl.isDelegatedAdminAccessAllowed(" + resource + ", " + zoneName + ", " + user + ", " + userGroups + ", " + accessTypes + "): " + ret); - } + LOG.debug("<== RangerPolicyAdminImpl.isDelegatedAdminAccessAllowed({}, {}, {}, {}, {}): {}", resource, zoneName, user, userGroups, accessTypes, ret); return ret; } @@ -181,174 +166,16 @@ public boolean isDelegatedAdminAccessAllowedForModify(RangerPolicy policy, Strin return isDelegatedAdminAccessAllowed(policy, user, userGroups, roles, false, evalContext); } - boolean isDelegatedAdminAccessAllowed(RangerPolicy policy, String user, Set userGroups, Set roles, boolean isRead, Map evalContext) { - if (LOG.isDebugEnabled()) { - LOG.debug("==> RangerPolicyAdminImpl.isDelegatedAdminAccessAllowed(" + policy.getId() + ", " + user + ", " + userGroups + ", " + roles + ", " + isRead + ", " + evalContext + ")"); - } - - boolean ret = false; - RangerPerfTracer perf = null; - - if(RangerPerfTracer.isPerfTraceEnabled(PERF_POLICYENGINE_REQUEST_LOG)) { - perf = RangerPerfTracer.getPerfTracer(PERF_POLICYENGINE_REQUEST_LOG, "RangerPolicyEngine.isDelegatedAdminAccessAllowed(user=" + user + "," + userGroups + ", roles=" + roles + ")"); - } - - try (RangerReadWriteLock.RangerLock readLock = policyEngine.getReadLock()) { - - if (LOG.isDebugEnabled()) { - if (readLock.isLockingEnabled()) { - LOG.debug("Acquired lock - " + readLock); - } - } - - final RangerPolicyRepository matchedRepository = policyEngine.getRepositoryForMatchedZone(policy); - - if (matchedRepository != null) { - if (isRead) { - Set accessTypes = getAllAccessTypes(policy, getServiceDef()); - ret = isDelegatedAdminAccessAllowedForPolicy(matchedRepository, policy, user, userGroups, roles, accessTypes, true, evalContext); - } else { - // Get old policy from policy-engine - RangerPolicy oldPolicy = null; - if (policy.getId() != null) { - try { - oldPolicy = serviceDBStore.getPolicy(policy.getId()); - } catch (Exception e) { - LOG.error("Cannot get old policy from DB: policy-id:[" + policy.getId() + "]"); - } - } - - if (oldPolicy != null) { - String oldResourceSignature = getResourceSignature(oldPolicy); - String newResourceSignature = getResourceSignature(policy); - - if (StringUtils.equals(oldResourceSignature, newResourceSignature)) { - Set modifiedAccessTypes = getAllModifiedAccessTypes(oldPolicy, policy, getServiceDef()); - ret = isDelegatedAdminAccessAllowedForPolicy(matchedRepository, policy, user, userGroups, roles, modifiedAccessTypes, false, evalContext); - } else { - Set removedAccessTypes = getAllAccessTypes(oldPolicy, getServiceDef()); - // Ensure that current policy-engine (without current policy) allows old-policy to be modified - final boolean isOldPolicyChangeAllowed = isDelegatedAdminAccessAllowedForPolicy(matchedRepository, oldPolicy, user, userGroups, roles, removedAccessTypes, false, evalContext); - if (isOldPolicyChangeAllowed) { - Set addedAccessTypes = getAllAccessTypes(policy, getServiceDef()); - ret = isDelegatedAdminAccessAllowedForPolicy(matchedRepository, policy, user, userGroups, roles, addedAccessTypes, false, evalContext); - } - } - } else { - LOG.warn("Cannot get unmodified policy with id:[" + policy.getId() + "]. Checking if thi"); - Set addedAccessTypes = getAllAccessTypes(policy, getServiceDef()); - ret = isDelegatedAdminAccessAllowedForPolicy(matchedRepository, policy, user, userGroups, roles, addedAccessTypes, false, evalContext); - } - } - } - } - - RangerPerfTracer.log(perf); - - if (LOG.isDebugEnabled()) { - LOG.debug("<== RangerPolicyAdminImpl.isDelegatedAdminAccessAllowed(" + policy.getId() + ", " + user + ", " + userGroups + ", " + roles + ", " + isRead + ", " + evalContext + "): " + ret); - } - - return ret; - } - - private boolean isDelegatedAdminAccessAllowedForPolicy(RangerPolicyRepository matchedRepository, RangerPolicy policy, String user, Set userGroups, Set roles, Set accessTypes, boolean isRead, Map evalContext) { - if (LOG.isDebugEnabled()) { - LOG.debug("==> RangerPolicyAdminImpl.isDelegatedAdminAccessAllowedForPolicy(" + policy.getId() + ", " + user + ", " + userGroups + ", " + roles + ", accessTypes" + accessTypes + ", " + isRead + ", " + evalContext + ")"); - } - - boolean ret = false; - - if (CollectionUtils.isEmpty(accessTypes)) { - LOG.error("Could not get access-types for policy-id:[" + policy.getId() + "]"); - } else { - if (LOG.isDebugEnabled()) { - LOG.debug("Checking delegate-admin access for the access-types:[" + accessTypes + "]"); - } - - Set allowedAccesses = getAllowedAccesses(matchedRepository, policy.getResources(), user, userGroups, roles, accessTypes, evalContext); - - if (CollectionUtils.isEmpty(allowedAccesses)) { - ret = false; - } else { - ret = isRead ? CollectionUtils.containsAny(allowedAccesses, accessTypes) : allowedAccesses.containsAll(accessTypes); - } - - if (ret && CollectionUtils.isNotEmpty(policy.getAdditionalResources())) { - for (Map additionalResource : policy.getAdditionalResources()) { - Set additionalResourceAllowedActions = getAllowedAccesses(matchedRepository, additionalResource, user, userGroups, roles, accessTypes, evalContext); - - if (CollectionUtils.isEmpty(additionalResourceAllowedActions)) { - allowedAccesses.clear(); - - ret = false; - } else { - allowedAccesses.retainAll(additionalResourceAllowedActions); // allowedAccesses to contain only access-types that are allowed on all resources in the policy - - if (isRead) { - ret = !allowedAccesses.isEmpty(); - } else { - ret = additionalResourceAllowedActions.containsAll(accessTypes); - } - } - - if (!ret) { - break; - } - } - } - - if (!ret) { - Collection unauthorizedAccesses = CollectionUtils.isEmpty(allowedAccesses) ? accessTypes : CollectionUtils.subtract(accessTypes, allowedAccesses); - - LOG.info("Accesses : " + unauthorizedAccesses + " are not authorized for the policy:[" + policy.getId() + "] by any of delegated-admin policies"); - } - } - - if (LOG.isDebugEnabled()) { - LOG.debug("<== RangerPolicyAdminImpl.isDelegatedAdminAccessAllowedForPolicy(" + policy.getId() + ", " + user + ", " + userGroups + ", " + roles + ", accessTypes" + accessTypes + ", " + isRead + ", " + evalContext + "): " + ret); - } - - return ret; - } - - private Set getAllowedAccesses(RangerPolicyRepository matchedRepository, Map resource, String user, Set userGroups, Set roles, Set accessTypes, Map evalContext) { - // RANGER-3082 - // Convert policy resources to by substituting macros with ASTERISK - Map modifiedResource = getPolicyResourcesWithMacrosReplaced(resource, wildcardEvalContext); - Set ret = null; - - for (RangerPolicyEvaluator evaluator : matchedRepository.getPolicyEvaluators()) { - Set allowedAccesses = evaluator.getAllowedAccesses(modifiedResource, user, userGroups, roles, accessTypes, evalContext); - - if (CollectionUtils.isNotEmpty(allowedAccesses)) { - if (ret == null) { - ret = new HashSet<>(allowedAccesses); - } else { - ret.addAll(allowedAccesses); - } - - if (ret.containsAll(accessTypes)) { - break; - } - } - } - - return ret; - } - @Override public List getExactMatchPolicies(RangerAccessResource resource, String zoneName, Map evalContext) { - if (LOG.isDebugEnabled()) { - LOG.debug("==> RangerPolicyAdminImpl.getExactMatchPolicies(" + resource + ", " + zoneName + ", " + evalContext + ")"); - } + LOG.debug("==> RangerPolicyAdminImpl.getExactMatchPolicies({}, {}, {})", resource, zoneName, evalContext); - List ret = null; + List ret = null; try (RangerReadWriteLock.RangerLock readLock = policyEngine.getReadLock()) { if (LOG.isDebugEnabled()) { if (readLock.isLockingEnabled()) { - LOG.debug("Acquired lock - " + readLock); + LOG.debug("Acquired lock - {}", readLock); } } @@ -365,29 +192,23 @@ public List getExactMatchPolicies(RangerAccessResource resource, S } } } - } - if (LOG.isDebugEnabled()) { - LOG.debug("<==> RangerPolicyAdminImpl.getExactMatchPolicies(" + resource + ", " + zoneName + ", " + evalContext + "): " + ret); - } + LOG.debug("<==> RangerPolicyAdminImpl.getExactMatchPolicies({}, {}, {}): {}", resource, zoneName, evalContext, ret); return ret; } @Override public List getExactMatchPolicies(RangerPolicy policy, Map evalContext) { - if (LOG.isDebugEnabled()) { - LOG.debug("==> RangerPolicyAdminImpl.getExactMatchPolicies(" + policy + ", " + evalContext + ")"); - } + LOG.debug("==> RangerPolicyAdminImpl.getExactMatchPolicies({}, {})", policy, evalContext); - List ret = null; + List ret = null; try (RangerReadWriteLock.RangerLock readLock = policyEngine.getReadLock()) { - if (LOG.isDebugEnabled()) { if (readLock.isLockingEnabled()) { - LOG.debug("Acquired lock - " + readLock); + LOG.debug("Acquired lock - {}", readLock); } } @@ -404,35 +225,30 @@ public List getExactMatchPolicies(RangerPolicy policy, Map getMatchingPolicies(RangerAccessResource resource) { - if (LOG.isDebugEnabled()) { - LOG.debug("==> RangerPolicyAdminImpl.getMatchingPolicies(" + resource + ")"); - } + LOG.debug("==> RangerPolicyAdminImpl.getMatchingPolicies({})", resource); + List ret; try (RangerReadWriteLock.RangerLock readLock = policyEngine.getReadLock()) { if (LOG.isDebugEnabled()) { if (readLock.isLockingEnabled()) { - LOG.debug("Acquired lock - " + readLock); + LOG.debug("Acquired lock - {}", readLock); } } + ret = getMatchingPolicies(resource, RangerPolicyEngine.ANY_ACCESS); } - if (LOG.isDebugEnabled()) { - LOG.debug("<== RangerPolicyAdminImpl.getMatchingPolicies(" + resource + ") : " + ret.size()); - } + LOG.debug("<== RangerPolicyAdminImpl.getMatchingPolicies({}) : {}", resource, ret.size()); return ret; } @@ -444,28 +260,46 @@ public long getPolicyVersion() { try (RangerReadWriteLock.RangerLock readLock = policyEngine.getReadLock()) { if (LOG.isDebugEnabled()) { if (readLock.isLockingEnabled()) { - LOG.debug("Acquired lock - " + readLock); + LOG.debug("Acquired lock - {}", readLock); } } + ret = policyEngine.getPolicyVersion(); } + return ret; } @Override public long getRoleVersion() { long ret; + try (RangerReadWriteLock.RangerLock readLock = policyEngine.getReadLock()) { if (LOG.isDebugEnabled()) { if (readLock.isLockingEnabled()) { - LOG.debug("Acquired lock - " + readLock); + LOG.debug("Acquired lock - {}", readLock); } } + ret = policyEngine.getRoleVersion(); } + return ret; } + @Override + public void setRoles(RangerRoles roles) { + try (RangerReadWriteLock.RangerLock writeLock = policyEngine.getWriteLock()) { + if (LOG.isDebugEnabled()) { + if (writeLock.isLockingEnabled()) { + LOG.debug("Acquired lock - {}", writeLock); + } + } + + policyEngine.setRoles(roles); + } + } + @Override public String getServiceName() { String ret; @@ -473,98 +307,88 @@ public String getServiceName() { try (RangerReadWriteLock.RangerLock readLock = policyEngine.getReadLock()) { if (LOG.isDebugEnabled()) { if (readLock.isLockingEnabled()) { - LOG.debug("Acquired lock - " + readLock); + LOG.debug("Acquired lock - {}", readLock); } } + ret = policyEngine.getServiceName(); } + return ret; } - @Override public RangerServiceDef getServiceDef() { RangerServiceDef ret; + try (RangerReadWriteLock.RangerLock readLock = policyEngine.getReadLock()) { if (LOG.isDebugEnabled()) { if (readLock.isLockingEnabled()) { - LOG.debug("Acquired lock - " + readLock); + LOG.debug("Acquired lock - {}", readLock); } } + ret = policyEngine.getServiceDef(); } + return ret; } - @Override - public void setRoles(RangerRoles roles) { - try (RangerReadWriteLock.RangerLock writeLock = policyEngine.getWriteLock()) { - if (LOG.isDebugEnabled()) { - if (writeLock.isLockingEnabled()) { - LOG.debug("Acquired lock - " + writeLock); - } - } - policyEngine.setRoles(roles); - } - } @Override public Set getRolesFromUserAndGroups(String user, Set groups) { Set ret; + try (RangerReadWriteLock.RangerLock readLock = policyEngine.getReadLock()) { if (LOG.isDebugEnabled()) { if (readLock.isLockingEnabled()) { - LOG.debug("Acquired lock - " + readLock); + LOG.debug("Acquired lock - {}", readLock); } } + ret = policyEngine.getPluginContext().getAuthContext().getRolesForUserAndGroups(user, groups); } + return ret; } @Override public Collection getZoneNamesForResource(Map resource) { - if (LOG.isDebugEnabled()) { - LOG.debug("==> RangerPolicyAdminImpl.getSecurityZonesForResource(" + resource + ")"); - } + LOG.debug("==> RangerPolicyAdminImpl.getSecurityZonesForResource({})", resource); - Collection ret = null; + Collection ret; try (RangerReadWriteLock.RangerLock readLock = policyEngine.getReadLock()) { if (LOG.isDebugEnabled()) { if (readLock.isLockingEnabled()) { - LOG.debug("Acquired lock - " + readLock); + LOG.debug("Acquired lock - {}", readLock); } } ret = policyEngine.getMatchedZonesForResourceAndChildren(resource); } - if (LOG.isDebugEnabled()) { - LOG.debug("<== RangerPolicyAdminImpl.getSecurityZonesForResource(" + resource + ") : " + ret); - } + LOG.debug("<== RangerPolicyAdminImpl.getSecurityZonesForResource({}) : {}", resource, ret); return ret; } @Override public String getUniquelyMatchedZoneName(GrantRevokeRequest grantRevokeRequest) { - if (LOG.isDebugEnabled()) { - LOG.debug("==> RangerPolicyAdminImpl.getUniquelyMatchedZoneName(" + grantRevokeRequest + ")"); - } + LOG.debug("==> RangerPolicyAdminImpl.getUniquelyMatchedZoneName({})", grantRevokeRequest); + String ret; try (RangerReadWriteLock.RangerLock readLock = policyEngine.getReadLock()) { if (LOG.isDebugEnabled()) { if (readLock.isLockingEnabled()) { - LOG.debug("Acquired lock - " + readLock); + LOG.debug("Acquired lock - {}", readLock); } } + ret = policyEngine.getUniquelyMatchedZoneName(grantRevokeRequest.getResource()); } - if (LOG.isDebugEnabled()) { - LOG.debug("<== RangerPolicyAdminImpl.getUniquelyMatchedZoneName(" + grantRevokeRequest + ") : " + ret); - } + LOG.debug("<== RangerPolicyAdminImpl.getUniquelyMatchedZoneName({}) : {}", grantRevokeRequest, ret); return ret; } @@ -572,14 +396,12 @@ public String getUniquelyMatchedZoneName(GrantRevokeRequest grantRevokeRequest) // This API is used only by test-code; checks only policies within default security-zone @Override public boolean isAccessAllowedByUnzonedPolicies(Map resources, List> additionalResources, String user, Set userGroups, String accessType) { - if (LOG.isDebugEnabled()) { - LOG.debug("==> RangerPolicyAdminImpl.isAccessAllowedByUnzonedPolicies(" + resources + ", " + user + ", " + userGroups + ", " + accessType + ")"); - } + LOG.debug("==> RangerPolicyAdminImpl.isAccessAllowedByUnzonedPolicies({}, {}, {}, {})", resources, user, userGroups, accessType); boolean ret = false; RangerPerfTracer perf = null; - if(RangerPerfTracer.isPerfTraceEnabled(PERF_POLICYENGINE_REQUEST_LOG)) { + if (RangerPerfTracer.isPerfTraceEnabled(PERF_POLICYENGINE_REQUEST_LOG)) { perf = RangerPerfTracer.getPerfTracer(PERF_POLICYENGINE_REQUEST_LOG, "RangerPolicyEngine.isAccessAllowed(user=" + user + "," + userGroups + ",accessType=" + accessType + ")"); } @@ -587,18 +409,15 @@ public boolean isAccessAllowedByUnzonedPolicies(Map getAllowedUnzonedPolicies(String user, Set userGroups, String accessType) { - if (LOG.isDebugEnabled()) { - LOG.debug("==> RangerPolicyAdminImpl.getAllowedByUnzonedPolicies(" + user + ", " + userGroups + ", " + accessType + ")"); - } + LOG.debug("==> RangerPolicyAdminImpl.getAllowedByUnzonedPolicies({}, {}, {})", user, userGroups, accessType); List ret = new ArrayList<>(); // TODO: run through evaluator in tagPolicyRepository as well for (RangerPolicyEvaluator evaluator : policyEngine.getPolicyRepository().getPolicyEvaluators()) { - RangerPolicy policy = evaluator.getPolicy(); - - boolean isAccessAllowed = isAccessAllowedByUnzonedPolicies(policy.getResources(), policy.getAdditionalResources(), user, userGroups, accessType); + RangerPolicy policy = evaluator.getPolicy(); + boolean isAccessAllowed = isAccessAllowedByUnzonedPolicies(policy.getResources(), policy.getAdditionalResources(), user, userGroups, accessType); if (isAccessAllowed) { ret.add(policy); } } - if (LOG.isDebugEnabled()) { - LOG.debug("<== RangerPolicyAdminImpl.getAllowedByUnzonedPolicies(" + user + ", " + userGroups + ", " + accessType + "): policyCount=" + ret.size()); + LOG.debug("<== RangerPolicyAdminImpl.getAllowedByUnzonedPolicies({}, {}, {}): policyCount={}", user, userGroups, accessType, ret.size()); + + return ret; + } + + @Override + public void setServiceStore(ServiceStore svcStore) { + if (svcStore instanceof ServiceDBStore) { + this.serviceDBStore = (ServiceDBStore) svcStore; + } + } + + boolean isDelegatedAdminAccessAllowed(RangerPolicy policy, String user, Set userGroups, Set roles, boolean isRead, Map evalContext) { + LOG.debug("==> RangerPolicyAdminImpl.isDelegatedAdminAccessAllowed({}, {}, {}, {}, {}, {})", policy.getId(), user, userGroups, roles, isRead, evalContext); + + boolean ret = false; + RangerPerfTracer perf = null; + + if (RangerPerfTracer.isPerfTraceEnabled(PERF_POLICYENGINE_REQUEST_LOG)) { + perf = RangerPerfTracer.getPerfTracer(PERF_POLICYENGINE_REQUEST_LOG, "RangerPolicyEngine.isDelegatedAdminAccessAllowed(user=" + user + "," + userGroups + ", roles=" + roles + ")"); } + try (RangerReadWriteLock.RangerLock readLock = policyEngine.getReadLock()) { + if (LOG.isDebugEnabled()) { + if (readLock.isLockingEnabled()) { + LOG.debug("Acquired lock - {}", readLock); + } + } + + final RangerPolicyRepository matchedRepository = policyEngine.getRepositoryForMatchedZone(policy); + + if (matchedRepository != null) { + if (isRead) { + Set accessTypes = getAllAccessTypes(policy, getServiceDef()); + + ret = isDelegatedAdminAccessAllowedForPolicy(matchedRepository, policy, user, userGroups, roles, accessTypes, true, evalContext); + } else { + // Get old policy from policy-engine + RangerPolicy oldPolicy = null; + + if (policy.getId() != null) { + try { + oldPolicy = serviceDBStore.getPolicy(policy.getId()); + } catch (Exception e) { + LOG.error("Cannot get old policy from DB: policy-id:[{}]", policy.getId()); + } + } + + if (oldPolicy != null) { + String oldResourceSignature = getResourceSignature(oldPolicy); + String newResourceSignature = getResourceSignature(policy); + + if (StringUtils.equals(oldResourceSignature, newResourceSignature)) { + Set modifiedAccessTypes = getAllModifiedAccessTypes(oldPolicy, policy, getServiceDef()); + + ret = isDelegatedAdminAccessAllowedForPolicy(matchedRepository, policy, user, userGroups, roles, modifiedAccessTypes, false, evalContext); + } else { + Set removedAccessTypes = getAllAccessTypes(oldPolicy, getServiceDef()); + // Ensure that current policy-engine (without current policy) allows old-policy to be modified + final boolean isOldPolicyChangeAllowed = isDelegatedAdminAccessAllowedForPolicy(matchedRepository, oldPolicy, user, userGroups, roles, removedAccessTypes, false, evalContext); + + if (isOldPolicyChangeAllowed) { + Set addedAccessTypes = getAllAccessTypes(policy, getServiceDef()); + + ret = isDelegatedAdminAccessAllowedForPolicy(matchedRepository, policy, user, userGroups, roles, addedAccessTypes, false, evalContext); + } + } + } else { + LOG.warn("Cannot get unmodified policy with id:[{}]. Checking if thi", policy.getId()); + + Set addedAccessTypes = getAllAccessTypes(policy, getServiceDef()); + + ret = isDelegatedAdminAccessAllowedForPolicy(matchedRepository, policy, user, userGroups, roles, addedAccessTypes, false, evalContext); + } + } + } + } + + RangerPerfTracer.log(perf); + + LOG.debug("<== RangerPolicyAdminImpl.isDelegatedAdminAccessAllowed({}, {}, {}, {}, {}, {}): {}", policy.getId(), user, userGroups, roles, isRead, evalContext, ret); + return ret; } @@ -636,11 +530,86 @@ void releaseResources(boolean isForced) { } } - private List getMatchingPolicies(RangerAccessResource resource, String accessType) { - if (LOG.isDebugEnabled()) { - LOG.debug("==> RangerPolicyAdminImpl.getMatchingPolicies(" + resource + ", " + accessType + ")"); + private boolean isDelegatedAdminAccessAllowedForPolicy(RangerPolicyRepository matchedRepository, RangerPolicy policy, String user, Set userGroups, Set roles, Set accessTypes, boolean isRead, Map evalContext) { + LOG.debug("==> RangerPolicyAdminImpl.isDelegatedAdminAccessAllowedForPolicy({}, {}, {}, {}, accessTypes{}, {}, {})", policy.getId(), user, userGroups, roles, accessTypes, isRead, evalContext); + + boolean ret = false; + + if (CollectionUtils.isEmpty(accessTypes)) { + LOG.error("Could not get access-types for policy-id:[{}]", policy.getId()); + } else { + LOG.debug("Checking delegate-admin access for the access-types:[{}]", accessTypes); + + Set allowedAccesses = getAllowedAccesses(matchedRepository, policy.getResources(), user, userGroups, roles, accessTypes, evalContext); + + if (CollectionUtils.isNotEmpty(allowedAccesses)) { + ret = isRead ? CollectionUtils.containsAny(allowedAccesses, accessTypes) : allowedAccesses.containsAll(accessTypes); + } + + if (ret && CollectionUtils.isNotEmpty(policy.getAdditionalResources())) { + for (Map additionalResource : policy.getAdditionalResources()) { + Set additionalResourceAllowedActions = getAllowedAccesses(matchedRepository, additionalResource, user, userGroups, roles, accessTypes, evalContext); + + if (CollectionUtils.isEmpty(additionalResourceAllowedActions)) { + allowedAccesses.clear(); + + ret = false; + } else { + allowedAccesses.retainAll(additionalResourceAllowedActions); // allowedAccesses to contain only access-types that are allowed on all resources in the policy + + if (isRead) { + ret = !allowedAccesses.isEmpty(); + } else { + ret = additionalResourceAllowedActions.containsAll(accessTypes); + } + } + + if (!ret) { + break; + } + } + } + + if (!ret) { + Collection unauthorizedAccesses = CollectionUtils.isEmpty(allowedAccesses) ? accessTypes : CollectionUtils.subtract(accessTypes, allowedAccesses); + + LOG.info("Accesses : {} are not authorized for the policy:[{}] by any of delegated-admin policies", unauthorizedAccesses, policy.getId()); + } } + LOG.debug("<== RangerPolicyAdminImpl.isDelegatedAdminAccessAllowedForPolicy({}, {}, {}, {}, accessTypes{}, {}, {}): {}", policy.getId(), user, userGroups, roles, accessTypes, isRead, evalContext, ret); + + return ret; + } + + private Set getAllowedAccesses(RangerPolicyRepository matchedRepository, Map resource, String user, Set userGroups, Set roles, Set accessTypes, Map evalContext) { + // RANGER-3082 + // Convert policy resources to by substituting macros with ASTERISK + Map modifiedResource = getPolicyResourcesWithMacrosReplaced(resource, wildcardEvalContext); + Set ret = null; + + for (RangerPolicyEvaluator evaluator : matchedRepository.getPolicyEvaluators()) { + Set allowedAccesses = evaluator.getAllowedAccesses(modifiedResource, user, userGroups, roles, accessTypes, evalContext); + + if (CollectionUtils.isNotEmpty(allowedAccesses)) { + if (ret == null) { + ret = new HashSet<>(allowedAccesses); + } else { + ret.addAll(allowedAccesses); + } + + if (ret.containsAll(accessTypes)) { + break; + } + } + } + + return ret; + } + + private List getMatchingPolicies(RangerAccessResource resource, String accessType) { + LOG.debug("==> RangerPolicyAdminImpl.getMatchingPolicies({}, {})", resource, accessType); + List ret = new ArrayList<>(); RangerAccessRequestImpl request = new RangerAccessRequestImpl(resource, accessType, null, null, null); @@ -656,9 +625,7 @@ private List getMatchingPolicies(RangerAccessResource resource, St } } - if (LOG.isDebugEnabled()) { - LOG.debug("<== RangerPolicyAdminImpl.getMatchingPolicies(" + resource + ", " + accessType + ") : " + ret.size()); - } + LOG.debug("<== RangerPolicyAdminImpl.getMatchingPolicies({}, {}) : {}", resource, accessType, ret.size()); return ret; } @@ -683,17 +650,13 @@ private void getMatchingPoliciesForZone(RangerAccessRequest request, String zone if (useTagPoliciesFromDefaultZone) { if (StringUtils.isNotEmpty(policyZoneName)) { - if (LOG.isDebugEnabled()) { - LOG.debug("Tag policy [zone:" + policyZoneName + "] does not belong to default zone. Not evaluating this policy:[" + evaluator.getPolicy() + "]"); - } + LOG.debug("Tag policy [zone:{}] does not belong to default zone. Not evaluating this policy:[{}]", policyZoneName, evaluator.getPolicy()); continue; } } else { if (!StringUtils.equals(zoneName, policyZoneName)) { - if (LOG.isDebugEnabled()) { - LOG.debug("Tag policy [zone:" + policyZoneName + "] does not belong to the zone:[" + zoneName + "] of the accessed resource. Not evaluating this policy:[" + evaluator.getPolicy() + "]"); - } + LOG.debug("Tag policy [zone:{}] does not belong to the zone:[{}] of the accessed resource. Not evaluating this policy:[{}]", policyZoneName, zoneName, evaluator.getPolicy()); continue; } @@ -710,12 +673,10 @@ private void getMatchingPoliciesForZone(RangerAccessRequest request, String zone } } } - } } } - if (policyEngine.hasResourcePolicies(matchedRepository)) { List likelyEvaluators = matchedRepository.getLikelyMatchPolicyEvaluators(request); @@ -732,16 +693,13 @@ private void getMatchingPoliciesForZone(RangerAccessRequest request, String zone } } } - } } private Map getPolicyResourcesWithMacrosReplaced(Map resources, Map evalContext) { - if (LOG.isDebugEnabled()) { - LOG.debug("==> RangerPolicyAdminImpl.getPolicyResourcesWithMacrosReplaced(" + resources + ", " + evalContext + ")"); - } + LOG.debug("==> RangerPolicyAdminImpl.getPolicyResourcesWithMacrosReplaced({}, {})", resources, evalContext); - final Map ret; + final Map ret; Collection resourceKeys = resources == null ? null : resources.keySet(); @@ -761,10 +719,12 @@ private Map getPolicyResourcesWithMacrosReplaced(M for (String value : values) { // RANGER-3082 - replace macros in value with ASTERISK String modifiedValue = tokenReplacer.replaceTokens(value, evalContext); + modifiedValues.add(modifiedValue); } RangerPolicyResource modifiedPolicyResource = new RangerPolicyResource(modifiedValues, resourceValues.getIsExcludes(), resourceValues.getIsRecursive()); + ret.put(resourceName, modifiedPolicyResource); } else { ret.put(resourceName, resourceValues); @@ -777,9 +737,7 @@ private Map getPolicyResourcesWithMacrosReplaced(M ret = resources; } - if (LOG.isDebugEnabled()) { - LOG.debug("<== RangerPolicyEngineImpl.getPolicyResourcesWithMacrosReplaced(" + resources + ", " + evalContext + "): " + ret); - } + LOG.debug("<== RangerPolicyEngineImpl.getPolicyResourcesWithMacrosReplaced({}, {}): {}", resources, evalContext, ret); return ret; } @@ -787,12 +745,11 @@ private Map getPolicyResourcesWithMacrosReplaced(M private Set getAllAccessTypes(RangerPolicy policy, RangerServiceDef serviceDef) { Set ret = new HashSet<>(); - boolean isValid = true; + boolean isValid = true; Map> expandedAccesses = ServiceDefUtil.getExpandedImpliedGrants(serviceDef); if (MapUtils.isNotEmpty(expandedAccesses)) { - - Integer policyType = policy.getPolicyType() == null ? RangerPolicy.POLICY_TYPE_ACCESS : policy.getPolicyType(); + int policyType = policy.getPolicyType() == null ? RangerPolicy.POLICY_TYPE_ACCESS : policy.getPolicyType(); if (policyType == RangerPolicy.POLICY_TYPE_ACCESS) { for (RangerPolicy.RangerPolicyItem item : policy.getPolicyItems()) { @@ -800,16 +757,19 @@ private Set getAllAccessTypes(RangerPolicy policy, RangerServiceDef serv ret.addAll(expandedAccesses.get(access.getType())); } } + for (RangerPolicy.RangerPolicyItem item : policy.getDenyPolicyItems()) { for (RangerPolicy.RangerPolicyItemAccess access : item.getAccesses()) { ret.addAll(expandedAccesses.get(access.getType())); } } + for (RangerPolicy.RangerPolicyItem item : policy.getAllowExceptions()) { for (RangerPolicy.RangerPolicyItemAccess access : item.getAccesses()) { ret.addAll(expandedAccesses.get(access.getType())); } } + for (RangerPolicy.RangerPolicyItem item : policy.getDenyExceptions()) { for (RangerPolicy.RangerPolicyItemAccess access : item.getAccesses()) { ret.addAll(expandedAccesses.get(access.getType())); @@ -828,18 +788,20 @@ private Set getAllAccessTypes(RangerPolicy policy, RangerServiceDef serv } } } else { - LOG.error("Unknown policy-type :[" + policyType + "], returning empty access-type set"); + LOG.error("Unknown policy-type :[{}], returning empty access-type set", policyType); + isValid = false; } + if (isValid && ret.isEmpty()) { ret.add(RangerPolicyEngine.ADMIN_ACCESS); } } + return ret; } private Set getAllModifiedAccessTypes(RangerPolicy oldPolicy, RangerPolicy policy, RangerServiceDef serviceDef) { - Set ret = new HashSet<>(); Map> oldUserAccesses = new HashMap<>(); @@ -860,6 +822,7 @@ private Set getAllModifiedAccessTypes(RangerPolicy oldPolicy, RangerPoli if (ret.isEmpty()) { ret.add(RangerPolicyEngine.ADMIN_ACCESS); } + return ret; } @@ -867,8 +830,7 @@ private void collectAccessTypes(RangerPolicy policy, RangerServiceDef serviceDef Map> expandedAccesses = ServiceDefUtil.getExpandedImpliedGrants(serviceDef); if (MapUtils.isNotEmpty(expandedAccesses)) { - - Integer policyType = policy.getPolicyType() == null ? RangerPolicy.POLICY_TYPE_ACCESS : policy.getPolicyType(); + int policyType = policy.getPolicyType() == null ? RangerPolicy.POLICY_TYPE_ACCESS : policy.getPolicyType(); if (policyType == RangerPolicy.POLICY_TYPE_ACCESS) { collectAccessTypes(expandedAccesses, policy.getPolicyItems(), userAccesses, groupAccesses, roleAccesses); @@ -880,14 +842,13 @@ private void collectAccessTypes(RangerPolicy policy, RangerServiceDef serviceDef } else if (policyType == RangerPolicy.POLICY_TYPE_ROWFILTER) { collectAccessTypes(expandedAccesses, policy.getRowFilterPolicyItems(), userAccesses, groupAccesses, roleAccesses); } else { - LOG.error("Unknown policy-type :[" + policyType + "], returning empty access-type set"); + LOG.error("Unknown policy-type :[{}], returning empty access-type set", policyType); } } } private void collectAccessTypes(Map> expandedAccesses, List policyItems, Map> userAccesses, Map> groupAccesses, Map> roleAccesses) { for (RangerPolicy.RangerPolicyItem item : policyItems) { - Set accessTypes = new HashSet<>(); for (RangerPolicy.RangerPolicyItemAccess access : item.getAccesses()) { @@ -896,6 +857,7 @@ private void collectAccessTypes(Map> expandedAccesses for (String user : item.getUsers()) { Set oldAccesses = userAccesses.get(user); + if (oldAccesses != null) { oldAccesses.addAll(accessTypes); } else { @@ -905,6 +867,7 @@ private void collectAccessTypes(Map> expandedAccesses for (String group : item.getGroups()) { Set oldAccesses = groupAccesses.get(group); + if (oldAccesses != null) { oldAccesses.addAll(accessTypes); } else { @@ -914,6 +877,7 @@ private void collectAccessTypes(Map> expandedAccesses for (String role : item.getRoles()) { Set oldAccesses = roleAccesses.get(role); + if (oldAccesses != null) { oldAccesses.addAll(accessTypes); } else { @@ -928,17 +892,22 @@ private Set getAccessTypesDiff(Map> newAccessesMap, for (Map.Entry> entry : newAccessesMap.entrySet()) { Set oldAccesses = oldAccessesMap.get(entry.getKey()); + if (oldAccesses != null) { Collection added = CollectionUtils.subtract(entry.getValue(), oldAccesses); + ret.addAll(added); } else { ret.addAll(entry.getValue()); } } + for (Map.Entry> entry : oldAccessesMap.entrySet()) { Set newAccesses = newAccessesMap.get(entry.getKey()); + if (newAccesses != null) { Collection removed = CollectionUtils.subtract(entry.getValue(), newAccesses); + ret.addAll(removed); } else { ret.addAll(entry.getValue()); @@ -950,5 +919,8 @@ private Set getAccessTypesDiff(Map> newAccessesMap, private String getResourceSignature(final RangerPolicy policy) { return RangerPolicyResourceSignature.toSignatureString(policy.getResources(), policy.getAdditionalResources()); } -} + static { + wildcardEvalContext.put(RangerAbstractResourceMatcher.WILDCARD_ASTERISK, RangerAbstractResourceMatcher.WILDCARD_ASTERISK); + } +} diff --git a/security-admin/src/main/java/org/apache/ranger/biz/RangerPolicyRetriever.java b/security-admin/src/main/java/org/apache/ranger/biz/RangerPolicyRetriever.java index e94c37f7b9..f43b982188 100644 --- a/security-admin/src/main/java/org/apache/ranger/biz/RangerPolicyRetriever.java +++ b/security-admin/src/main/java/org/apache/ranger/biz/RangerPolicyRetriever.java @@ -19,12 +19,6 @@ package org.apache.ranger.biz; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.ListIterator; -import java.util.Map; - import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.MapUtils; import org.apache.commons.lang.StringUtils; @@ -49,651 +43,631 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.transaction.PlatformTransactionManager; -import org.springframework.transaction.TransactionStatus; -import org.springframework.transaction.support.TransactionCallback; import org.springframework.transaction.support.TransactionTemplate; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.ListIterator; +import java.util.Map; public class RangerPolicyRetriever { - static final Logger LOG = LoggerFactory.getLogger(RangerPolicyRetriever.class); - static final Logger PERF_LOG = RangerPerfTracer.getPerfLogger("db.RangerPolicyRetriever"); - - private final RangerDaoManager daoMgr; - private final LookupCache lookupCache = new LookupCache(); - - private final PlatformTransactionManager txManager; - private final TransactionTemplate txTemplate; - - public RangerPolicyRetriever(RangerDaoManager daoMgr, PlatformTransactionManager txManager) { - this.daoMgr = daoMgr; - this.txManager = txManager; - if (this.txManager != null) { - this.txTemplate = new TransactionTemplate(this.txManager); - this.txTemplate.setReadOnly(true); - } else { - this.txTemplate = null; - } - } - - public RangerPolicyRetriever(RangerDaoManager daoMgr) { - this.daoMgr = daoMgr; - this.txManager = null; - this.txTemplate = null; - } - - public List getServicePolicies(Long serviceId) { - List ret = null; - - if(serviceId != null) { - XXService xService = getXXService(serviceId); - - if(xService != null) { - ret = getServicePolicies(xService); - } else { - if(LOG.isDebugEnabled()) { - LOG.debug("RangerPolicyRetriever.getServicePolicies(serviceId=" + serviceId + "): service not found"); - } - } - } - - return ret; - } - - public List getServicePolicies(String serviceName) { - List ret = null; - - if(serviceName != null) { - XXService xService = getXXService(serviceName); - - if(xService != null) { - ret = getServicePolicies(xService); - } else { - if(LOG.isDebugEnabled()) { - LOG.debug("RangerPolicyRetriever.getServicePolicies(serviceName=" + serviceName + "): service not found"); - } - } - } - - return ret; - } - - private class PolicyLoaderThread extends Thread { - final TransactionTemplate txTemplate; - final XXService xService; - List policies; - - PolicyLoaderThread(TransactionTemplate txTemplate, final XXService xService) { - this.txTemplate = txTemplate; - this.xService = xService; - } - - public List getPolicies() { return policies; } - - @Override - public void run() { - try { - txTemplate.setReadOnly(true); - policies = txTemplate.execute(new TransactionCallback>() { - @Override - public List doInTransaction(TransactionStatus status) { - try { - RetrieverContext ctx = new RetrieverContext(xService); - return ctx.getAllPolicies(); - } catch (Exception ex) { - LOG.error("RangerPolicyRetriever.getServicePolicies(): Failed to get policies for service:[" + xService.getName() + "] in a new transaction", ex); - status.setRollbackOnly(); - return null; - } - } - }); - } catch (Throwable ex) { - LOG.error("RangerPolicyRetriever.getServicePolicies(): Failed to get policies for service:[" + xService.getName() + "] in a new transaction", ex); - } - } - } - - public List getServicePolicies(final XXService xService) { - String serviceName = xService == null ? null : xService.getName(); - Long serviceId = xService == null ? null : xService.getId(); - - if(LOG.isDebugEnabled()) { - LOG.debug("==> RangerPolicyRetriever.getServicePolicies(serviceName=" + serviceName + ", serviceId=" + serviceId + ")"); - } - - List ret = null; - RangerPerfTracer perf = null; - - if(RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { - perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "RangerPolicyRetriever.getServicePolicies(serviceName=" + serviceName + ",serviceId=" + serviceId + ")"); - } - - if(xService != null) { - if (txTemplate == null) { - if (LOG.isDebugEnabled()) { - LOG.debug("Transaction Manager is null; Retrieving policies in the existing transaction"); - } - RetrieverContext ctx = new RetrieverContext(xService); - ret = ctx.getAllPolicies(); - } else { - if (LOG.isDebugEnabled()) { - LOG.debug("Retrieving policies in a new, read-only transaction"); - } - - PolicyLoaderThread t = new PolicyLoaderThread(txTemplate, xService); - t.setDaemon(true); - t.start(); - try { - t.join(); - ret = t.getPolicies(); - } catch (InterruptedException ie) { - LOG.error("Failed to retrieve policies in a new, read-only thread.", ie); - } - } - } else { - if(LOG.isDebugEnabled()) { - LOG.debug("RangerPolicyRetriever.getServicePolicies(xService=" + xService + "): invalid parameter"); - } - } - - RangerPerfTracer.log(perf); - - if(LOG.isDebugEnabled()) { - LOG.debug("<== RangerPolicyRetriever.getServicePolicies(serviceName=" + serviceName + ", serviceId=" + serviceId + "): policyCount=" + (ret == null ? 0 : ret.size())); - } - - return ret; - } - - public RangerPolicy getPolicy(Long policyId) { - RangerPolicy ret = null; - - if(policyId != null) { - XXPolicy xPolicy = getXXPolicy(policyId); - - if(xPolicy != null) { - ret = getPolicy(xPolicy); - } else { - if(LOG.isDebugEnabled()) { - LOG.debug("RangerPolicyRetriever.getPolicy(policyId=" + policyId + "): policy not found"); - } - } - - } - - return ret; - } - - public RangerPolicy getPolicy(XXPolicy xPolicy) { - RangerPolicy ret = null; - - if(xPolicy != null) { - XXService xService = getXXService(xPolicy.getService()); - - if(xService != null) { - ret = getPolicy(xPolicy, xService); - } else { - if(LOG.isDebugEnabled()) { - LOG.debug("RangerPolicyRetriever.getPolicy(policyId=" + xPolicy.getId() + "): service not found (serviceId=" + xPolicy.getService() + ")"); - } - } - } - - return ret; - } - - public RangerPolicy getPolicy(XXPolicy xPolicy, XXService xService) { - Long policyId = xPolicy == null ? null : xPolicy.getId(); - - if(LOG.isDebugEnabled()) { - LOG.debug("==> RangerPolicyRetriever.getPolicy(" + policyId + ")"); - } - - RangerPolicy ret = null; - RangerPerfTracer perf = null; - - if(RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { - perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "RangerPolicyRetriever.getPolicy(policyId=" + policyId + ")"); - } - - if(xPolicy != null && xService != null) { - RetrieverContext ctx = new RetrieverContext(xPolicy, xService); - - ret = ctx.getNextPolicy(); - } else { - if(LOG.isDebugEnabled()) { - LOG.debug("RangerPolicyRetriever.getPolicy(xPolicy=" + xPolicy + ", xService=" + xService + "): invalid parameter(s)"); - } - } - - RangerPerfTracer.log(perf); - - if(LOG.isDebugEnabled()) { - LOG.debug("<== RangerPolicyRetriever.getPolicy(" + policyId + "): " + ret); - } - - return ret; - } - - private XXService getXXService(Long serviceId) { - XXService ret = null; - - if(serviceId != null) { - ret = daoMgr.getXXService().getById(serviceId); - } - - return ret; - } - - private XXService getXXService(String serviceName) { - XXService ret = null; + static final Logger LOG = LoggerFactory.getLogger(RangerPolicyRetriever.class); + static final Logger PERF_LOG = RangerPerfTracer.getPerfLogger("db.RangerPolicyRetriever"); + + private final RangerDaoManager daoMgr; + private final LookupCache lookupCache = new LookupCache(); + private final PlatformTransactionManager txManager; + private final TransactionTemplate txTemplate; + + public RangerPolicyRetriever(RangerDaoManager daoMgr, PlatformTransactionManager txManager) { + this.daoMgr = daoMgr; + this.txManager = txManager; + + if (this.txManager != null) { + this.txTemplate = new TransactionTemplate(this.txManager); + this.txTemplate.setReadOnly(true); + } else { + this.txTemplate = null; + } + } + + public RangerPolicyRetriever(RangerDaoManager daoMgr) { + this.daoMgr = daoMgr; + this.txManager = null; + this.txTemplate = null; + } + + static List asList(XXPolicy policy) { + List ret = new ArrayList<>(); + + if (policy != null) { + ret.add(policy); + } + + return ret; + } + + public List getServicePolicies(Long serviceId) { + List ret = null; + + if (serviceId != null) { + XXService xService = getXXService(serviceId); + + if (xService != null) { + ret = getServicePolicies(xService); + } else { + LOG.debug("RangerPolicyRetriever.getServicePolicies(serviceId={}): service not found", serviceId); + } + } + + return ret; + } + + public List getServicePolicies(String serviceName) { + List ret = null; + + if (serviceName != null) { + XXService xService = getXXService(serviceName); + + if (xService != null) { + ret = getServicePolicies(xService); + } else { + LOG.debug("RangerPolicyRetriever.getServicePolicies(serviceName={}): service not found", serviceName); + } + } - if(serviceName != null) { - ret = daoMgr.getXXService().findByName(serviceName); - } + return ret; + } - return ret; - } + public List getServicePolicies(final XXService xService) { + String serviceName = xService == null ? null : xService.getName(); + Long serviceId = xService == null ? null : xService.getId(); - private XXPolicy getXXPolicy(Long policyId) { - XXPolicy ret = null; + LOG.debug("==> RangerPolicyRetriever.getServicePolicies(serviceName={}, serviceId={})", serviceName, serviceId); - if(policyId != null) { - ret = daoMgr.getXXPolicy().getById(policyId); - } + List ret = null; + RangerPerfTracer perf = null; - return ret; - } + if (RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { + perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "RangerPolicyRetriever.getServicePolicies(serviceName=" + serviceName + ",serviceId=" + serviceId + ")"); + } - class LookupCache { - final Map userScreenNames = new HashMap(); - final Map zoneNames = new HashMap(); - final Map> roleMappingsPerPolicy = new HashMap<>(); - final Map> groupMappingsPerPolicy = new HashMap<>(); - final Map> userMappingsPerPolicy = new HashMap<>(); - final Map> accessMappingsPerPolicy = new HashMap<>(); - final Map> resourceMappingsPerPolicy = new HashMap<>(); - final Map> dataMaskMappingsPerPolicy = new HashMap<>(); - final Map> conditionMappingsPerPolicy = new HashMap<>(); - final Map policyLabels = new HashMap(); + if (xService != null) { + if (txTemplate == null) { + LOG.debug("Transaction Manager is null; Retrieving policies in the existing transaction"); - String getPolicyLabelName(Long policyLabelId) { - String ret = null; + RetrieverContext ctx = new RetrieverContext(xService); - if (policyLabelId != null) { - ret = policyLabels.get(policyLabelId); + ret = ctx.getAllPolicies(); + } else { + LOG.debug("Retrieving policies in a new, read-only transaction"); - if (ret == null) { - XXPolicyLabel xxPolicyLabel = daoMgr.getXXPolicyLabels().getById(policyLabelId); + PolicyLoaderThread t = new PolicyLoaderThread(txTemplate, xService); - if (xxPolicyLabel != null) { - ret = xxPolicyLabel.getPolicyLabel(); + t.setDaemon(true); + t.start(); - policyLabels.put(policyLabelId, ret); - } - } - } + try { + t.join(); + + ret = t.getPolicies(); + } catch (InterruptedException ie) { + LOG.error("Failed to retrieve policies in a new, read-only thread.", ie); + } + } + } else { + LOG.debug("RangerPolicyRetriever.getServicePolicies(xService={}): invalid parameter", xService); + } - return ret; - } + RangerPerfTracer.log(perf); + + LOG.debug("<== RangerPolicyRetriever.getServicePolicies(serviceName={}, serviceId={}): policyCount={}", serviceName, serviceId, ret == null ? 0 : ret.size()); + + return ret; + } - String getUserScreenName(Long userId) { - String ret = null; + public RangerPolicy getPolicy(Long policyId) { + RangerPolicy ret = null; - if(userId != null) { - ret = userScreenNames.get(userId); + if (policyId != null) { + XXPolicy xPolicy = getXXPolicy(policyId); - if(ret == null) { - XXPortalUser user = daoMgr.getXXPortalUser().findById(userId); + if (xPolicy != null) { + ret = getPolicy(xPolicy); + } else { + LOG.debug("RangerPolicyRetriever.getPolicy(policyId={}): policy not found", policyId); + } + } - if(user != null) { - ret = user.getPublicScreenName(); + return ret; + } - if (StringUtil.isEmpty(ret)) { - ret = user.getFirstName(); + public RangerPolicy getPolicy(XXPolicy xPolicy) { + RangerPolicy ret = null; - if(StringUtil.isEmpty(ret)) { - ret = user.getLoginId(); - } else { - if(!StringUtil.isEmpty(user.getLastName())) { - ret += (" " + user.getLastName()); - } - } - } + if (xPolicy != null) { + XXService xService = getXXService(xPolicy.getService()); - if(ret != null) { - userScreenNames.put(userId, ret); - } - } - } - } + if (xService != null) { + ret = getPolicy(xPolicy, xService); + } else { + LOG.debug("RangerPolicyRetriever.getPolicy(policyId={}): service not found (serviceId={})", xPolicy.getId(), xPolicy.getService()); + } + } - return ret; - } + return ret; + } - String getSecurityZoneName(Long zoneId) { - String ret = null; + public RangerPolicy getPolicy(XXPolicy xPolicy, XXService xService) { + Long policyId = xPolicy == null ? null : xPolicy.getId(); - if(zoneId != null) { - if (zoneId == RangerSecurityZone.RANGER_UNZONED_SECURITY_ZONE_ID) { - ret = StringUtils.EMPTY; - } else { - ret = zoneNames.get(zoneId); + LOG.debug("==> RangerPolicyRetriever.getPolicy({})", policyId); - if (ret == null) { - XXSecurityZone securityZone = daoMgr.getXXSecurityZoneDao().getById(zoneId); + RangerPolicy ret = null; + RangerPerfTracer perf = null; - if (securityZone != null) { - ret = securityZone.getName(); + if (RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { + perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "RangerPolicyRetriever.getPolicy(policyId=" + policyId + ")"); + } - if (ret != null) { - zoneNames.put(zoneId, ret); - } - } - } - } - } + if (xPolicy != null && xService != null) { + RetrieverContext ctx = new RetrieverContext(xPolicy, xService); - return ret; - } - - void setNameMapping(Map> nameMappingContainer, List nameMappings) { - nameMappingContainer.clear(); - - for (PolicyTextNameMap nameMapping : nameMappings) { - Map policyNameMap = nameMappingContainer.get(nameMapping.policyId); - - if (policyNameMap == null) { - policyNameMap = new HashMap<>(); - - nameMappingContainer.put(nameMapping.policyId, policyNameMap); - } - - policyNameMap.put(nameMapping.oldName, nameMapping.currentName); - } - } + ret = ctx.getNextPolicy(); + } else { + LOG.debug("RangerPolicyRetriever.getPolicy(xPolicy={}, xService={}): invalid parameter(s)", xPolicy, xService); + } - String getMappedName(Map> nameMappingContainer, Long policyId, String nameToMap) { - Map policyNameMap = nameMappingContainer.get(policyId); + RangerPerfTracer.log(perf); - return policyNameMap != null ? policyNameMap.get(nameToMap) : null; - } + LOG.debug("<== RangerPolicyRetriever.getPolicy({}): {}", policyId, ret); - void setRoleNameMapping(List roleNameMapping) { - setNameMapping(roleMappingsPerPolicy, roleNameMapping); - } - void setGroupNameMapping(List groupNameMapping) { - setNameMapping(groupMappingsPerPolicy, groupNameMapping); - } + return ret; + } - void setUserNameMapping(List userNameMapping) { - setNameMapping(userMappingsPerPolicy, userNameMapping); - } + private XXService getXXService(Long serviceId) { + XXService ret = null; - void setAccessNameMapping(List accessNameMapping) { - setNameMapping(accessMappingsPerPolicy, accessNameMapping); - } + if (serviceId != null) { + ret = daoMgr.getXXService().getById(serviceId); + } - public void setResourceNameMapping(List resourceNameMapping) { - setNameMapping(resourceMappingsPerPolicy, resourceNameMapping); - } + return ret; + } - public void setDataMaskNameMapping(List dataMaskMapping) { - setNameMapping(dataMaskMappingsPerPolicy, dataMaskMapping); - } + private XXService getXXService(String serviceName) { + XXService ret = null; - public void setConditionNameMapping(List conditionNameMapping) { - setNameMapping(conditionMappingsPerPolicy, conditionNameMapping); - } + if (serviceName != null) { + ret = daoMgr.getXXService().findByName(serviceName); + } - } - - public static class PolicyTextNameMap { - final Long policyId; - final String oldName; - final String currentName; - - public PolicyTextNameMap(Long policyId, String oldName, String currentName) { - this.policyId = policyId; - this.oldName = oldName; - this.currentName = currentName; - } - } + return ret; + } - static List asList(XXPolicy policy) { - List ret = new ArrayList<>(); + private XXPolicy getXXPolicy(Long policyId) { + XXPolicy ret = null; - if (policy != null) { - ret.add(policy); + if (policyId != null) { + ret = daoMgr.getXXPolicy().getById(policyId); } return ret; } - class RetrieverContext { - final XXService service; - final ListIterator iterPolicy; - final ListIterator iterPolicyLabels; - final XXServiceDef serviceDef; - - RetrieverContext(XXService xService) { - if (xService != null) { - Long serviceId = xService.getId(); - - lookupCache.setRoleNameMapping(daoMgr.getXXPolicyRefRole().findUpdatedRoleNamesByService(serviceId)); - lookupCache.setGroupNameMapping(daoMgr.getXXPolicyRefGroup().findUpdatedGroupNamesByService(serviceId)); - lookupCache.setUserNameMapping(daoMgr.getXXPolicyRefUser().findUpdatedUserNamesByService(serviceId)); - lookupCache.setAccessNameMapping(daoMgr.getXXPolicyRefAccessType().findUpdatedAccessNamesByService(serviceId)); - lookupCache.setResourceNameMapping(daoMgr.getXXPolicyRefResource().findUpdatedResourceNamesByService(serviceId)); - lookupCache.setDataMaskNameMapping(daoMgr.getXXPolicyRefDataMaskType().findUpdatedDataMaskNamesByService(serviceId)); - lookupCache.setConditionNameMapping(daoMgr.getXXPolicyRefCondition().findUpdatedConditionNamesByService(serviceId)); - - this.service = xService; - this.serviceDef = daoMgr.getXXServiceDef().getById(xService.getType()); - this.iterPolicy = daoMgr.getXXPolicy().findByServiceId(serviceId).listIterator(); - this.iterPolicyLabels = daoMgr.getXXPolicyLabelMap().findByServiceId(serviceId).listIterator(); - } else { - this.service = null; - this.serviceDef = null; - this.iterPolicy = null; - this.iterPolicyLabels = null; - } - } - - RetrieverContext(XXPolicy xPolicy, XXService xService) { - Long policyId = xPolicy.getId(); - - lookupCache.setRoleNameMapping(daoMgr.getXXPolicyRefRole().findUpdatedRoleNamesByPolicy(policyId)); - lookupCache.setGroupNameMapping(daoMgr.getXXPolicyRefGroup().findUpdatedGroupNamesByPolicy(policyId)); - lookupCache.setUserNameMapping(daoMgr.getXXPolicyRefUser().findUpdatedUserNamesByPolicy(policyId)); - lookupCache.setAccessNameMapping(daoMgr.getXXPolicyRefAccessType().findUpdatedAccessNamesByPolicy(policyId)); - lookupCache.setResourceNameMapping(daoMgr.getXXPolicyRefResource().findUpdatedResourceNamesByPolicy(policyId)); - lookupCache.setDataMaskNameMapping(daoMgr.getXXPolicyRefDataMaskType().findUpdatedDataMaskNamesByPolicy(policyId)); - lookupCache.setConditionNameMapping(daoMgr.getXXPolicyRefCondition().findUpdatedConditionNamesByPolicy(policyId)); - - this.service = xService; - this.serviceDef = daoMgr.getXXServiceDef().getById(xService.getType()); - this.iterPolicy = asList(xPolicy).listIterator(); - List policyLabels = daoMgr.getXXPolicyLabelMap().findByPolicyId(policyId); - this.iterPolicyLabels = policyLabels != null ? policyLabels.listIterator() : null; - } - - RangerPolicy getNextPolicy() { - RangerPolicy ret = null; - - if (service != null && iterPolicy != null && iterPolicy.hasNext()) { - XXPolicy xPolicy = iterPolicy.next(); - - iterPolicy.remove(); - - if (xPolicy != null) { - String policyText = xPolicy.getPolicyText(); - - ret = JsonUtils.jsonToObject(policyText, RangerPolicy.class); - - if (ret != null) { - ret.setId(xPolicy.getId()); - ret.setGuid(xPolicy.getGuid()); - ret.setCreatedBy(lookupCache.getUserScreenName(xPolicy.getAddedByUserId())); - ret.setUpdatedBy(lookupCache.getUserScreenName(xPolicy.getUpdatedByUserId())); - ret.setCreateTime(xPolicy.getCreateTime()); - ret.setUpdateTime(xPolicy.getUpdateTime()); - ret.setVersion(xPolicy.getVersion()); - ret.setPolicyType(xPolicy.getPolicyType() == null ? RangerPolicy.POLICY_TYPE_ACCESS : xPolicy.getPolicyType()); - ret.setService(service.getName()); - ret.setServiceType(serviceDef.getName()); - ret.setZoneName(lookupCache.getSecurityZoneName(xPolicy.getZoneId())); - updatePolicyReferenceFields(ret); - getPolicyLabels(ret); - } - } - } - - return ret; - } - - private void getPolicyLabels(RangerPolicy ret) { - List xPolicyLabels = new ArrayList(); - if (iterPolicyLabels != null) { - while (iterPolicyLabels.hasNext()) { - XXPolicyLabelMap xPolicyLabel = iterPolicyLabels.next(); - if (xPolicyLabel.getPolicyId().equals(ret.getId())) { - String policyLabel = lookupCache.getPolicyLabelName(xPolicyLabel.getPolicyLabelId()); - if (policyLabel != null) { - xPolicyLabels.add(policyLabel); - } - ret.setPolicyLabels(xPolicyLabels); - } else { - if (iterPolicyLabels.hasPrevious()) { - iterPolicyLabels.previous(); - } - break; - } - } - } - } - - void updatePolicyReferenceFields(final RangerPolicy policy) { - final Long policyId = policy.getId(); - - Map policyResourceNameMap = lookupCache.resourceMappingsPerPolicy.get(policyId); - - if (MapUtils.isNotEmpty(policyResourceNameMap) && CollectionUtils.containsAny(policyResourceNameMap.keySet(), policy.getResources().keySet())) { - Map updatedResources = new HashMap<>(); - - for (Map.Entry entry : policy.getResources().entrySet()) { - String resourceName = entry.getKey(); - RangerPolicyResource policyResource = entry.getValue(); - String updatedName = policyResourceNameMap.get(resourceName); - - if (updatedName == null) { - updatedName = resourceName; - } - - updatedResources.put(updatedName, policyResource); - } - - policy.setResources(updatedResources); - } - - for (List policyItems : PolicyRefUpdater.getAllPolicyItems(policy)) { - if (CollectionUtils.isEmpty(policyItems)) { - continue; - } - - for (RangerPolicyItem policyItem : policyItems) { - if (lookupCache.roleMappingsPerPolicy.containsKey(policyId)) { - List updatedRoles = getUpdatedNames(lookupCache.roleMappingsPerPolicy, policyId, policyItem.getRoles()); - - if (updatedRoles != null) { - policyItem.setRoles(updatedRoles); - } - } - if (lookupCache.groupMappingsPerPolicy.containsKey(policyId)) { - List updatedGroups = getUpdatedNames(lookupCache.groupMappingsPerPolicy, policyId, policyItem.getGroups()); - - if (updatedGroups != null) { - policyItem.setGroups(updatedGroups); - } - } - - if (lookupCache.userMappingsPerPolicy.containsKey(policyId)) { - List updatedUsers = getUpdatedNames(lookupCache.userMappingsPerPolicy, policyId, policyItem.getUsers()); - - if (updatedUsers != null) { - policyItem.setUsers(updatedUsers); - } - } - - if (lookupCache.accessMappingsPerPolicy.containsKey(policyId)) { - for (RangerPolicyItemAccess itemAccess : policyItem.getAccesses()) { - String updatedName = lookupCache.getMappedName(lookupCache.accessMappingsPerPolicy, policyId, itemAccess.getType()); - - if (updatedName != null) { - itemAccess.setType(updatedName); - } - } - } - - if (lookupCache.conditionMappingsPerPolicy.containsKey(policyId)) { - for (RangerPolicyItemCondition condition : policyItem.getConditions()) { - String updatedName = lookupCache.getMappedName(lookupCache.conditionMappingsPerPolicy, policyId, condition.getType()); - - if (updatedName != null) { - condition.setType(updatedName); - } - } - } - - if (policyItem instanceof RangerDataMaskPolicyItem && lookupCache.dataMaskMappingsPerPolicy.containsKey(policyId)) { - RangerDataMaskPolicyItem dataMaskItem = (RangerDataMaskPolicyItem) policyItem; - String updatedName = lookupCache.getMappedName(lookupCache.dataMaskMappingsPerPolicy, policyId, dataMaskItem.getDataMaskInfo().getDataMaskType()); - - if (updatedName != null) { - dataMaskItem.getDataMaskInfo().setDataMaskType(updatedName); - } - } - } - } - } - - List getUpdatedNames(final Map> nameMappingContainer, final Long policyId, final List namesToMap) { - List ret = null; - Map policyNameMap = nameMappingContainer.get(policyId); - - if (MapUtils.isNotEmpty(policyNameMap) && CollectionUtils.containsAny(policyNameMap.keySet(), namesToMap)) { - ret = new ArrayList<>(); - - for (String nameToMap : namesToMap) { - String mappedName = policyNameMap.get(nameToMap); - - if (mappedName != null) { - ret.add(mappedName); - } else { - ret.add(nameToMap); - } - } - - } - - return ret; - } - - List getAllPolicies() { - List ret = new ArrayList<>(); - - if (iterPolicy != null) { - while (iterPolicy.hasNext()) { - RangerPolicy policy = getNextPolicy(); - - if (policy != null) { - ret.add(policy); - } - } - } - - return ret; - } - } + public static class PolicyTextNameMap { + final Long policyId; + final String oldName; + final String currentName; -} + public PolicyTextNameMap(Long policyId, String oldName, String currentName) { + this.policyId = policyId; + this.oldName = oldName; + this.currentName = currentName; + } + } + private class PolicyLoaderThread extends Thread { + final TransactionTemplate txTemplate; + final XXService xService; + List policies; + + PolicyLoaderThread(TransactionTemplate txTemplate, final XXService xService) { + this.txTemplate = txTemplate; + this.xService = xService; + } + + public List getPolicies() { + return policies; + } + + @Override + public void run() { + try { + txTemplate.setReadOnly(true); + policies = txTemplate.execute(status -> { + try { + RetrieverContext ctx = new RetrieverContext(xService); + + return ctx.getAllPolicies(); + } catch (Exception ex) { + LOG.error("RangerPolicyRetriever.getServicePolicies(): Failed to get policies for service:[{}] in a new transaction", xService.getName(), ex); + + status.setRollbackOnly(); + + return null; + } + }); + } catch (Throwable ex) { + LOG.error("RangerPolicyRetriever.getServicePolicies(): Failed to get policies for service:[{}] in a new transaction", xService.getName(), ex); + } + } + } + + class LookupCache { + final Map userScreenNames = new HashMap<>(); + final Map zoneNames = new HashMap<>(); + final Map> roleMappingsPerPolicy = new HashMap<>(); + final Map> groupMappingsPerPolicy = new HashMap<>(); + final Map> userMappingsPerPolicy = new HashMap<>(); + final Map> accessMappingsPerPolicy = new HashMap<>(); + final Map> resourceMappingsPerPolicy = new HashMap<>(); + final Map> dataMaskMappingsPerPolicy = new HashMap<>(); + final Map> conditionMappingsPerPolicy = new HashMap<>(); + final Map policyLabels = new HashMap<>(); + + public void setResourceNameMapping(List resourceNameMapping) { + setNameMapping(resourceMappingsPerPolicy, resourceNameMapping); + } + + public void setDataMaskNameMapping(List dataMaskMapping) { + setNameMapping(dataMaskMappingsPerPolicy, dataMaskMapping); + } + + public void setConditionNameMapping(List conditionNameMapping) { + setNameMapping(conditionMappingsPerPolicy, conditionNameMapping); + } + + String getPolicyLabelName(Long policyLabelId) { + String ret = null; + + if (policyLabelId != null) { + ret = policyLabels.get(policyLabelId); + + if (ret == null) { + XXPolicyLabel xxPolicyLabel = daoMgr.getXXPolicyLabels().getById(policyLabelId); + + if (xxPolicyLabel != null) { + ret = xxPolicyLabel.getPolicyLabel(); + + policyLabels.put(policyLabelId, ret); + } + } + } + + return ret; + } + + String getUserScreenName(Long userId) { + String ret = null; + + if (userId != null) { + ret = userScreenNames.get(userId); + + if (ret == null) { + XXPortalUser user = daoMgr.getXXPortalUser().findById(userId); + + if (user != null) { + ret = user.getPublicScreenName(); + + if (StringUtil.isEmpty(ret)) { + ret = user.getFirstName(); + + if (StringUtil.isEmpty(ret)) { + ret = user.getLoginId(); + } else { + if (!StringUtil.isEmpty(user.getLastName())) { + ret += (" " + user.getLastName()); + } + } + } + + if (ret != null) { + userScreenNames.put(userId, ret); + } + } + } + } + + return ret; + } + + String getSecurityZoneName(Long zoneId) { + String ret = null; + + if (zoneId != null) { + if (zoneId == RangerSecurityZone.RANGER_UNZONED_SECURITY_ZONE_ID) { + ret = StringUtils.EMPTY; + } else { + ret = zoneNames.get(zoneId); + + if (ret == null) { + XXSecurityZone securityZone = daoMgr.getXXSecurityZoneDao().getById(zoneId); + + if (securityZone != null) { + ret = securityZone.getName(); + + if (ret != null) { + zoneNames.put(zoneId, ret); + } + } + } + } + } + + return ret; + } + + void setNameMapping(Map> nameMappingContainer, List nameMappings) { + nameMappingContainer.clear(); + + for (PolicyTextNameMap nameMapping : nameMappings) { + Map policyNameMap = nameMappingContainer.computeIfAbsent(nameMapping.policyId, k -> new HashMap<>()); + + policyNameMap.put(nameMapping.oldName, nameMapping.currentName); + } + } + + String getMappedName(Map> nameMappingContainer, Long policyId, String nameToMap) { + Map policyNameMap = nameMappingContainer.get(policyId); + + return policyNameMap != null ? policyNameMap.get(nameToMap) : null; + } + + void setRoleNameMapping(List roleNameMapping) { + setNameMapping(roleMappingsPerPolicy, roleNameMapping); + } + + void setGroupNameMapping(List groupNameMapping) { + setNameMapping(groupMappingsPerPolicy, groupNameMapping); + } + + void setUserNameMapping(List userNameMapping) { + setNameMapping(userMappingsPerPolicy, userNameMapping); + } + + void setAccessNameMapping(List accessNameMapping) { + setNameMapping(accessMappingsPerPolicy, accessNameMapping); + } + } + + class RetrieverContext { + final XXService service; + final ListIterator iterPolicy; + final ListIterator iterPolicyLabels; + final XXServiceDef serviceDef; + + RetrieverContext(XXService xService) { + if (xService != null) { + Long serviceId = xService.getId(); + + lookupCache.setRoleNameMapping(daoMgr.getXXPolicyRefRole().findUpdatedRoleNamesByService(serviceId)); + lookupCache.setGroupNameMapping(daoMgr.getXXPolicyRefGroup().findUpdatedGroupNamesByService(serviceId)); + lookupCache.setUserNameMapping(daoMgr.getXXPolicyRefUser().findUpdatedUserNamesByService(serviceId)); + lookupCache.setAccessNameMapping(daoMgr.getXXPolicyRefAccessType().findUpdatedAccessNamesByService(serviceId)); + lookupCache.setResourceNameMapping(daoMgr.getXXPolicyRefResource().findUpdatedResourceNamesByService(serviceId)); + lookupCache.setDataMaskNameMapping(daoMgr.getXXPolicyRefDataMaskType().findUpdatedDataMaskNamesByService(serviceId)); + lookupCache.setConditionNameMapping(daoMgr.getXXPolicyRefCondition().findUpdatedConditionNamesByService(serviceId)); + + this.service = xService; + this.serviceDef = daoMgr.getXXServiceDef().getById(xService.getType()); + this.iterPolicy = daoMgr.getXXPolicy().findByServiceId(serviceId).listIterator(); + this.iterPolicyLabels = daoMgr.getXXPolicyLabelMap().findByServiceId(serviceId).listIterator(); + } else { + this.service = null; + this.serviceDef = null; + this.iterPolicy = null; + this.iterPolicyLabels = null; + } + } + + RetrieverContext(XXPolicy xPolicy, XXService xService) { + Long policyId = xPolicy.getId(); + + lookupCache.setRoleNameMapping(daoMgr.getXXPolicyRefRole().findUpdatedRoleNamesByPolicy(policyId)); + lookupCache.setGroupNameMapping(daoMgr.getXXPolicyRefGroup().findUpdatedGroupNamesByPolicy(policyId)); + lookupCache.setUserNameMapping(daoMgr.getXXPolicyRefUser().findUpdatedUserNamesByPolicy(policyId)); + lookupCache.setAccessNameMapping(daoMgr.getXXPolicyRefAccessType().findUpdatedAccessNamesByPolicy(policyId)); + lookupCache.setResourceNameMapping(daoMgr.getXXPolicyRefResource().findUpdatedResourceNamesByPolicy(policyId)); + lookupCache.setDataMaskNameMapping(daoMgr.getXXPolicyRefDataMaskType().findUpdatedDataMaskNamesByPolicy(policyId)); + lookupCache.setConditionNameMapping(daoMgr.getXXPolicyRefCondition().findUpdatedConditionNamesByPolicy(policyId)); + + this.service = xService; + this.serviceDef = daoMgr.getXXServiceDef().getById(xService.getType()); + this.iterPolicy = asList(xPolicy).listIterator(); + List policyLabels = daoMgr.getXXPolicyLabelMap().findByPolicyId(policyId); + this.iterPolicyLabels = policyLabels != null ? policyLabels.listIterator() : null; + } + + RangerPolicy getNextPolicy() { + RangerPolicy ret = null; + + if (service != null && iterPolicy != null && iterPolicy.hasNext()) { + XXPolicy xPolicy = iterPolicy.next(); + + iterPolicy.remove(); + + if (xPolicy != null) { + String policyText = xPolicy.getPolicyText(); + + ret = JsonUtils.jsonToObject(policyText, RangerPolicy.class); + + if (ret != null) { + ret.setId(xPolicy.getId()); + ret.setGuid(xPolicy.getGuid()); + ret.setCreatedBy(lookupCache.getUserScreenName(xPolicy.getAddedByUserId())); + ret.setUpdatedBy(lookupCache.getUserScreenName(xPolicy.getUpdatedByUserId())); + ret.setCreateTime(xPolicy.getCreateTime()); + ret.setUpdateTime(xPolicy.getUpdateTime()); + ret.setVersion(xPolicy.getVersion()); + ret.setPolicyType(xPolicy.getPolicyType() == null ? RangerPolicy.POLICY_TYPE_ACCESS : xPolicy.getPolicyType()); + ret.setService(service.getName()); + ret.setServiceType(serviceDef.getName()); + ret.setZoneName(lookupCache.getSecurityZoneName(xPolicy.getZoneId())); + updatePolicyReferenceFields(ret); + getPolicyLabels(ret); + } + } + } + + return ret; + } + + void updatePolicyReferenceFields(final RangerPolicy policy) { + final Long policyId = policy.getId(); + + Map policyResourceNameMap = lookupCache.resourceMappingsPerPolicy.get(policyId); + + if (MapUtils.isNotEmpty(policyResourceNameMap) && CollectionUtils.containsAny(policyResourceNameMap.keySet(), policy.getResources().keySet())) { + Map updatedResources = new HashMap<>(); + + for (Map.Entry entry : policy.getResources().entrySet()) { + String resourceName = entry.getKey(); + RangerPolicyResource policyResource = entry.getValue(); + String updatedName = policyResourceNameMap.get(resourceName); + + if (updatedName == null) { + updatedName = resourceName; + } + + updatedResources.put(updatedName, policyResource); + } + + policy.setResources(updatedResources); + } + + for (List policyItems : PolicyRefUpdater.getAllPolicyItems(policy)) { + if (CollectionUtils.isEmpty(policyItems)) { + continue; + } + + for (RangerPolicyItem policyItem : policyItems) { + if (lookupCache.roleMappingsPerPolicy.containsKey(policyId)) { + List updatedRoles = getUpdatedNames(lookupCache.roleMappingsPerPolicy, policyId, policyItem.getRoles()); + + if (updatedRoles != null) { + policyItem.setRoles(updatedRoles); + } + } + if (lookupCache.groupMappingsPerPolicy.containsKey(policyId)) { + List updatedGroups = getUpdatedNames(lookupCache.groupMappingsPerPolicy, policyId, policyItem.getGroups()); + + if (updatedGroups != null) { + policyItem.setGroups(updatedGroups); + } + } + + if (lookupCache.userMappingsPerPolicy.containsKey(policyId)) { + List updatedUsers = getUpdatedNames(lookupCache.userMappingsPerPolicy, policyId, policyItem.getUsers()); + + if (updatedUsers != null) { + policyItem.setUsers(updatedUsers); + } + } + + if (lookupCache.accessMappingsPerPolicy.containsKey(policyId)) { + for (RangerPolicyItemAccess itemAccess : policyItem.getAccesses()) { + String updatedName = lookupCache.getMappedName(lookupCache.accessMappingsPerPolicy, policyId, itemAccess.getType()); + + if (updatedName != null) { + itemAccess.setType(updatedName); + } + } + } + + if (lookupCache.conditionMappingsPerPolicy.containsKey(policyId)) { + for (RangerPolicyItemCondition condition : policyItem.getConditions()) { + String updatedName = lookupCache.getMappedName(lookupCache.conditionMappingsPerPolicy, policyId, condition.getType()); + + if (updatedName != null) { + condition.setType(updatedName); + } + } + } + + if (policyItem instanceof RangerDataMaskPolicyItem && lookupCache.dataMaskMappingsPerPolicy.containsKey(policyId)) { + RangerDataMaskPolicyItem dataMaskItem = (RangerDataMaskPolicyItem) policyItem; + String updatedName = lookupCache.getMappedName(lookupCache.dataMaskMappingsPerPolicy, policyId, dataMaskItem.getDataMaskInfo().getDataMaskType()); + + if (updatedName != null) { + dataMaskItem.getDataMaskInfo().setDataMaskType(updatedName); + } + } + } + } + } + + List getUpdatedNames(final Map> nameMappingContainer, final Long policyId, final List namesToMap) { + List ret = null; + Map policyNameMap = nameMappingContainer.get(policyId); + + if (MapUtils.isNotEmpty(policyNameMap) && CollectionUtils.containsAny(policyNameMap.keySet(), namesToMap)) { + ret = new ArrayList<>(); + + for (String nameToMap : namesToMap) { + String mappedName = policyNameMap.get(nameToMap); + + if (mappedName != null) { + ret.add(mappedName); + } else { + ret.add(nameToMap); + } + } + } + + return ret; + } + + List getAllPolicies() { + List ret = new ArrayList<>(); + + if (iterPolicy != null) { + while (iterPolicy.hasNext()) { + RangerPolicy policy = getNextPolicy(); + + if (policy != null) { + ret.add(policy); + } + } + } + + return ret; + } + + private void getPolicyLabels(RangerPolicy ret) { + List xPolicyLabels = new ArrayList<>(); + + if (iterPolicyLabels != null) { + while (iterPolicyLabels.hasNext()) { + XXPolicyLabelMap xPolicyLabel = iterPolicyLabels.next(); + + if (xPolicyLabel.getPolicyId().equals(ret.getId())) { + String policyLabel = lookupCache.getPolicyLabelName(xPolicyLabel.getPolicyLabelId()); + + if (policyLabel != null) { + xPolicyLabels.add(policyLabel); + } + + ret.setPolicyLabels(xPolicyLabels); + } else { + if (iterPolicyLabels.hasPrevious()) { + iterPolicyLabels.previous(); + } + break; + } + } + } + } + } +} diff --git a/security-admin/src/main/java/org/apache/ranger/biz/RangerTagDBRetriever.java b/security-admin/src/main/java/org/apache/ranger/biz/RangerTagDBRetriever.java index 0d97e306cb..779638e7bf 100644 --- a/security-admin/src/main/java/org/apache/ranger/biz/RangerTagDBRetriever.java +++ b/security-admin/src/main/java/org/apache/ranger/biz/RangerTagDBRetriever.java @@ -19,17 +19,12 @@ package org.apache.ranger.biz; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.ListIterator; -import java.util.Map; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.type.TypeReference; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang.StringUtils; -import org.apache.ranger.authorization.utils.StringUtil; import org.apache.ranger.authorization.utils.JsonUtils; +import org.apache.ranger.authorization.utils.StringUtil; import org.apache.ranger.db.RangerDaoManager; import org.apache.ranger.entity.XXPortalUser; import org.apache.ranger.entity.XXService; @@ -45,341 +40,350 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.transaction.PlatformTransactionManager; -import org.springframework.transaction.TransactionStatus; -import org.springframework.transaction.support.TransactionCallback; import org.springframework.transaction.support.TransactionTemplate; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.ListIterator; +import java.util.Map; + public class RangerTagDBRetriever { - private static final Logger LOG = LoggerFactory.getLogger(RangerTagDBRetriever.class); - private static final Logger PERF_LOG = RangerPerfTracer.getPerfLogger("db.RangerTagDBRetriever"); - - public static final TypeReference subsumedDataType = new TypeReference>() {}; - - private final RangerDaoManager daoMgr; - private final LookupCache lookupCache; - - private List serviceResources; - private Map tagDefs; - - RangerTagDBRetriever(final RangerDaoManager daoMgr, final PlatformTransactionManager txManager, final XXService xService) { - - this.daoMgr = daoMgr; - - final TransactionTemplate txTemplate; - - if (txManager != null) { - txTemplate = new TransactionTemplate(txManager); - txTemplate.setReadOnly(true); - } else { - txTemplate = null; - } - this.lookupCache = new LookupCache(); - - - if (this.daoMgr != null && xService != null) { - - RangerPerfTracer perf = null; - - if (RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { - perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "RangerTagDBRetriever.RangerTagDBRetriever(serviceName=" + xService.getName() + ")"); - } - - if (txTemplate == null) { - if (LOG.isDebugEnabled()) { - LOG.debug("Load Tags in the same thread and using an existing transaction"); - } - if (!initializeTagCache(xService)) { - LOG.error("Failed to get tags for service:[" + xService.getName() + "] in the same thread and using an existing transaction"); - } - } else { - if (LOG.isDebugEnabled()) { - LOG.debug("Load Tags in a separate thread and using a new transaction"); - } - - TagLoaderThread t = new TagLoaderThread(txTemplate, xService); - t.setDaemon(true); - t.start(); - try { - t.join(); - } catch (InterruptedException ie) { - LOG.error("Failed to get Tags in a separate thread and using a new transaction", ie); - } - } - - RangerPerfTracer.log(perf); - - } - } - - - List getServiceResources() { - return serviceResources; - } - - Map getTagDefs() { - return tagDefs; - } - - Map getTags() { - - Map ret = new HashMap<>(); - - if (CollectionUtils.isNotEmpty(serviceResources)) { - for (RangerServiceResource serviceResource : serviceResources) { - List tags = lookupCache.serviceResourceToTags.get(serviceResource.getId()); - if (CollectionUtils.isNotEmpty(tags)) { - for (RangerTag tag : tags) { - ret.put(tag.getId(), tag); - } - } - } - } - - return ret; - } - - Map> getResourceToTagIds() { - Map> ret = new HashMap<>(); - - if (CollectionUtils.isNotEmpty(serviceResources)) { - for (RangerServiceResource serviceResource : serviceResources) { - List tags = lookupCache.serviceResourceToTags.get(serviceResource.getId()); - if (CollectionUtils.isNotEmpty(tags)) { - List tagIds = new ArrayList<>(); - ret.put(serviceResource.getId(), tagIds); - for (RangerTag tag : tags) { - tagIds.add(tag.getId()); - } - } - } - } - return ret; - } - - private boolean initializeTagCache(XXService xService) { - boolean ret; - try { - serviceResources = new TagRetrieverServiceResourceContext(xService).getAllServiceResources(); - tagDefs = new TagRetrieverTagDefContext(xService).getAllTagDefs(); - - ret = true; - } catch (Exception ex) { - LOG.error("Failed to get tags for service:[" + xService.getName() + "]", ex); - serviceResources = null; - tagDefs = null; - ret = false; - } - return ret; - } - - private class LookupCache { - final Map userScreenNames = new HashMap<>(); - final Map> serviceResourceToTags = new HashMap<>(); - - String getUserScreenName(Long userId) { - String ret = null; - - if (userId != null) { - ret = userScreenNames.get(userId); - - if (ret == null) { - XXPortalUser user = daoMgr.getXXPortalUser().getById(userId); - - if (user != null) { - ret = user.getPublicScreenName(); - - if (StringUtil.isEmpty(ret)) { - ret = user.getFirstName(); - - if (StringUtil.isEmpty(ret)) { - ret = user.getLoginId(); - } else { - if (!StringUtil.isEmpty(user.getLastName())) { - ret += (" " + user.getLastName()); - } - } - } - - if (ret != null) { - userScreenNames.put(userId, ret); - } - } - } - } - - return ret; - } - - } - - private class TagLoaderThread extends Thread { - final TransactionTemplate txTemplate; - final XXService xService; - - TagLoaderThread(TransactionTemplate txTemplate, final XXService xService) { - this.txTemplate = txTemplate; - this.xService = xService; - } - - @Override - public void run() { - try { - txTemplate.setReadOnly(true); - Boolean result = txTemplate.execute(new TransactionCallback() { - @Override - public Boolean doInTransaction(TransactionStatus status) { - boolean ret = initializeTagCache(xService); - if (!ret) { - status.setRollbackOnly(); - LOG.error("Failed to get tags for service:[" + xService.getName() + "] in a new transaction"); - } - return ret; - } - }); - if (LOG.isDebugEnabled()) { - LOG.debug("transaction result:[" + result +"]"); - } - } catch (Throwable ex) { - LOG.error("Failed to get tags for service:[" + xService.getName() + "] in a new transaction", ex); - } - } - } - - private class TagRetrieverServiceResourceContext { - - final XXService service; - final ListIterator iterServiceResource; - - TagRetrieverServiceResourceContext(XXService xService) { - Long serviceId = xService == null ? null : xService.getId(); - this.service = xService; - - List xServiceResources = daoMgr.getXXServiceResource().findTaggedResourcesInServiceId(serviceId); - - this.iterServiceResource = xServiceResources.listIterator(); - - } - - List getAllServiceResources() { - List ret = new ArrayList<>(); - - while (iterServiceResource.hasNext()) { - RangerServiceResource serviceResource = getNextServiceResource(); - - if (serviceResource != null) { - ret.add(serviceResource); - } - } - return ret; - } - - RangerServiceResource getNextServiceResource() { - RangerServiceResource ret = null; - - if (iterServiceResource.hasNext()) { - XXServiceResource xServiceResource = iterServiceResource.next(); - - iterServiceResource.remove(); - - if (xServiceResource != null && StringUtils.isNotEmpty(xServiceResource.getTags())) { - ret = new RangerServiceResource(); - - ret.setId(xServiceResource.getId()); - ret.setGuid(xServiceResource.getGuid()); - ret.setIsEnabled(xServiceResource.getIsEnabled()); - ret.setCreatedBy(lookupCache.getUserScreenName(xServiceResource.getAddedByUserId())); - ret.setUpdatedBy(lookupCache.getUserScreenName(xServiceResource.getUpdatedByUserId())); - ret.setCreateTime(xServiceResource.getCreateTime()); - ret.setUpdateTime(xServiceResource.getUpdateTime()); - ret.setVersion(xServiceResource.getVersion()); - ret.setResourceSignature(xServiceResource.getResourceSignature()); - if (StringUtils.isNotEmpty(xServiceResource.getServiceResourceElements())) { - try { - Map serviceResourceElements = (Map) JsonUtils.jsonToObject(xServiceResource.getServiceResourceElements(), RangerServiceResourceService.subsumedDataType); - ret.setResourceElements(serviceResourceElements); - } catch (JsonProcessingException e) { - LOG.error("Error occurred while processing JSON ", e); - } - } - try { - List tags = (List) JsonUtils.jsonToObject(xServiceResource.getTags(), RangerServiceResourceService.duplicatedDataType); - if (CollectionUtils.isNotEmpty(tags)) { - for (RangerTag tag : tags) { - RangerServiceTagsDeltaUtil.pruneUnusedAttributes(tag); - } - } - lookupCache.serviceResourceToTags.put(xServiceResource.getId(), tags); - } catch (JsonProcessingException e) { - LOG.error("Error occurred while processing JSON ", e); - } - } - } - return ret; - } - } - - private class TagRetrieverTagDefContext { - - final XXService service; - final ListIterator iterTagDef; - - TagRetrieverTagDefContext(XXService xService) { - Long serviceId = xService == null ? null : xService.getId(); - - List xTagDefs = daoMgr.getXXTagDef().findByServiceId(serviceId); - - this.service = xService; - this.iterTagDef = xTagDefs.listIterator(); - } - - Map getAllTagDefs() { - Map ret = new HashMap<>(); - - while (iterTagDef.hasNext()) { - RangerTagDef tagDef = getNextTagDef(); - - if (tagDef != null) { - ret.put(tagDef.getId(), tagDef); - } - } - return ret; - } - - RangerTagDef getNextTagDef() { - RangerTagDef ret = null; - - if (iterTagDef.hasNext()) { - XXTagDef xTagDef = iterTagDef.next(); - - iterTagDef.remove(); - - if (xTagDef != null) { - ret = new RangerTagDef(); - - ret.setId(xTagDef.getId()); - ret.setGuid(xTagDef.getGuid()); - ret.setIsEnabled(xTagDef.getIsEnabled()); - ret.setCreatedBy(lookupCache.getUserScreenName(xTagDef.getAddedByUserId())); - ret.setUpdatedBy(lookupCache.getUserScreenName(xTagDef.getUpdatedByUserId())); - ret.setCreateTime(xTagDef.getCreateTime()); - ret.setUpdateTime(xTagDef.getUpdateTime()); - ret.setVersion(xTagDef.getVersion()); - ret.setName(xTagDef.getName()); - ret.setSource(xTagDef.getSource()); - if(StringUtils.isNotEmpty(xTagDef.getTagAttrDefs())) { - try { - List attributeDefs = (List) JsonUtils.jsonToObject(xTagDef.getTagAttrDefs(), RangerTagDBRetriever.subsumedDataType); - ret.setAttributeDefs(attributeDefs); - } catch (JsonProcessingException e) { - LOG.error("Error occurred while processing JSON ", e); - } - } - } - } - - return ret; - } - - } + private static final Logger LOG = LoggerFactory.getLogger(RangerTagDBRetriever.class); + private static final Logger PERF_LOG = RangerPerfTracer.getPerfLogger("db.RangerTagDBRetriever"); + + public static final TypeReference> subsumedDataType = new TypeReference>() {}; + + private final RangerDaoManager daoMgr; + private final LookupCache lookupCache; + + private List serviceResources; + private Map tagDefs; + + RangerTagDBRetriever(final RangerDaoManager daoMgr, final PlatformTransactionManager txManager, final XXService xService) { + this.daoMgr = daoMgr; + + final TransactionTemplate txTemplate; + + if (txManager != null) { + txTemplate = new TransactionTemplate(txManager); + + txTemplate.setReadOnly(true); + } else { + txTemplate = null; + } + + this.lookupCache = new LookupCache(); + + if (this.daoMgr != null && xService != null) { + RangerPerfTracer perf = null; + + if (RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { + perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "RangerTagDBRetriever.RangerTagDBRetriever(serviceName=" + xService.getName() + ")"); + } + + if (txTemplate == null) { + LOG.debug("Load Tags in the same thread and using an existing transaction"); + + if (!initializeTagCache(xService)) { + LOG.error("Failed to get tags for service:[{}] in the same thread and using an existing transaction", xService.getName()); + } + } else { + LOG.debug("Load Tags in a separate thread and using a new transaction"); + + TagLoaderThread t = new TagLoaderThread(txTemplate, xService); + + t.setDaemon(true); + t.start(); + + try { + t.join(); + } catch (InterruptedException ie) { + LOG.error("Failed to get Tags in a separate thread and using a new transaction", ie); + } + } + + RangerPerfTracer.log(perf); + } + } + + List getServiceResources() { + return serviceResources; + } + + Map getTagDefs() { + return tagDefs; + } + + Map getTags() { + Map ret = new HashMap<>(); + + if (CollectionUtils.isNotEmpty(serviceResources)) { + for (RangerServiceResource serviceResource : serviceResources) { + List tags = lookupCache.serviceResourceToTags.get(serviceResource.getId()); + + if (CollectionUtils.isNotEmpty(tags)) { + for (RangerTag tag : tags) { + ret.put(tag.getId(), tag); + } + } + } + } + + return ret; + } + + Map> getResourceToTagIds() { + Map> ret = new HashMap<>(); + + if (CollectionUtils.isNotEmpty(serviceResources)) { + for (RangerServiceResource serviceResource : serviceResources) { + List tags = lookupCache.serviceResourceToTags.get(serviceResource.getId()); + + if (CollectionUtils.isNotEmpty(tags)) { + List tagIds = new ArrayList<>(); + + ret.put(serviceResource.getId(), tagIds); + + for (RangerTag tag : tags) { + tagIds.add(tag.getId()); + } + } + } + } + + return ret; + } + + private boolean initializeTagCache(XXService xService) { + boolean ret; + try { + serviceResources = new TagRetrieverServiceResourceContext(xService).getAllServiceResources(); + tagDefs = new TagRetrieverTagDefContext(xService).getAllTagDefs(); + + ret = true; + } catch (Exception ex) { + LOG.error("Failed to get tags for service:[{}]", xService.getName(), ex); + + serviceResources = null; + tagDefs = null; + ret = false; + } + + return ret; + } + + private class LookupCache { + final Map userScreenNames = new HashMap<>(); + final Map> serviceResourceToTags = new HashMap<>(); + + String getUserScreenName(Long userId) { + String ret = null; + + if (userId != null) { + ret = userScreenNames.get(userId); + + if (ret == null) { + XXPortalUser user = daoMgr.getXXPortalUser().getById(userId); + + if (user != null) { + ret = user.getPublicScreenName(); + + if (StringUtil.isEmpty(ret)) { + ret = user.getFirstName(); + + if (StringUtil.isEmpty(ret)) { + ret = user.getLoginId(); + } else { + if (!StringUtil.isEmpty(user.getLastName())) { + ret += (" " + user.getLastName()); + } + } + } + + if (ret != null) { + userScreenNames.put(userId, ret); + } + } + } + } + + return ret; + } + } + + private class TagLoaderThread extends Thread { + final TransactionTemplate txTemplate; + final XXService xService; + + TagLoaderThread(TransactionTemplate txTemplate, final XXService xService) { + this.txTemplate = txTemplate; + this.xService = xService; + } + + @Override + public void run() { + try { + txTemplate.setReadOnly(true); + Boolean result = txTemplate.execute(status -> { + boolean ret = initializeTagCache(xService); + + if (!ret) { + status.setRollbackOnly(); + + LOG.error("Failed to get tags for service:[{}] in a new transaction", xService.getName()); + } + + return ret; + }); + + LOG.debug("transaction result:[{}]", result); + } catch (Throwable ex) { + LOG.error("Failed to get tags for service:[{}] in a new transaction", xService.getName(), ex); + } + } + } + + private class TagRetrieverServiceResourceContext { + final XXService service; + final ListIterator iterServiceResource; + + TagRetrieverServiceResourceContext(XXService xService) { + Long serviceId = xService == null ? null : xService.getId(); + + this.service = xService; + + List xServiceResources = daoMgr.getXXServiceResource().findTaggedResourcesInServiceId(serviceId); + + this.iterServiceResource = xServiceResources.listIterator(); + } + + List getAllServiceResources() { + List ret = new ArrayList<>(); + + while (iterServiceResource.hasNext()) { + RangerServiceResource serviceResource = getNextServiceResource(); + if (serviceResource != null) { + ret.add(serviceResource); + } + } + + return ret; + } + + RangerServiceResource getNextServiceResource() { + RangerServiceResource ret = null; + + if (iterServiceResource.hasNext()) { + XXServiceResource xServiceResource = iterServiceResource.next(); + + iterServiceResource.remove(); + + if (xServiceResource != null && StringUtils.isNotEmpty(xServiceResource.getTags())) { + ret = new RangerServiceResource(); + + ret.setId(xServiceResource.getId()); + ret.setGuid(xServiceResource.getGuid()); + ret.setIsEnabled(xServiceResource.getIsEnabled()); + ret.setCreatedBy(lookupCache.getUserScreenName(xServiceResource.getAddedByUserId())); + ret.setUpdatedBy(lookupCache.getUserScreenName(xServiceResource.getUpdatedByUserId())); + ret.setCreateTime(xServiceResource.getCreateTime()); + ret.setUpdateTime(xServiceResource.getUpdateTime()); + ret.setVersion(xServiceResource.getVersion()); + ret.setResourceSignature(xServiceResource.getResourceSignature()); + + if (StringUtils.isNotEmpty(xServiceResource.getServiceResourceElements())) { + try { + Map serviceResourceElements = JsonUtils.jsonToObject(xServiceResource.getServiceResourceElements(), RangerServiceResourceService.subsumedDataType); + + ret.setResourceElements(serviceResourceElements); + } catch (JsonProcessingException e) { + LOG.error("Error occurred while processing JSON ", e); + } + } + + try { + List tags = JsonUtils.jsonToObject(xServiceResource.getTags(), RangerServiceResourceService.duplicatedDataType); + + if (CollectionUtils.isNotEmpty(tags)) { + for (RangerTag tag : tags) { + RangerServiceTagsDeltaUtil.pruneUnusedAttributes(tag); + } + } + + lookupCache.serviceResourceToTags.put(xServiceResource.getId(), tags); + } catch (JsonProcessingException e) { + LOG.error("Error occurred while processing JSON ", e); + } + } + } + + return ret; + } + } + + private class TagRetrieverTagDefContext { + final XXService service; + final ListIterator iterTagDef; + + TagRetrieverTagDefContext(XXService xService) { + Long serviceId = xService == null ? null : xService.getId(); + List xTagDefs = daoMgr.getXXTagDef().findByServiceId(serviceId); + + this.service = xService; + this.iterTagDef = xTagDefs.listIterator(); + } + + Map getAllTagDefs() { + Map ret = new HashMap<>(); + + while (iterTagDef.hasNext()) { + RangerTagDef tagDef = getNextTagDef(); + + if (tagDef != null) { + ret.put(tagDef.getId(), tagDef); + } + } + + return ret; + } + + RangerTagDef getNextTagDef() { + RangerTagDef ret = null; + + if (iterTagDef.hasNext()) { + XXTagDef xTagDef = iterTagDef.next(); + + iterTagDef.remove(); + + if (xTagDef != null) { + ret = new RangerTagDef(); + + ret.setId(xTagDef.getId()); + ret.setGuid(xTagDef.getGuid()); + ret.setIsEnabled(xTagDef.getIsEnabled()); + ret.setCreatedBy(lookupCache.getUserScreenName(xTagDef.getAddedByUserId())); + ret.setUpdatedBy(lookupCache.getUserScreenName(xTagDef.getUpdatedByUserId())); + ret.setCreateTime(xTagDef.getCreateTime()); + ret.setUpdateTime(xTagDef.getUpdateTime()); + ret.setVersion(xTagDef.getVersion()); + ret.setName(xTagDef.getName()); + ret.setSource(xTagDef.getSource()); + + if (StringUtils.isNotEmpty(xTagDef.getTagAttrDefs())) { + try { + List attributeDefs = JsonUtils.jsonToObject(xTagDef.getTagAttrDefs(), RangerTagDBRetriever.subsumedDataType); + + ret.setAttributeDefs(attributeDefs); + } catch (JsonProcessingException e) { + LOG.error("Error occurred while processing JSON ", e); + } + } + } + } + + return ret; + } + } } diff --git a/security-admin/src/main/java/org/apache/ranger/biz/RoleDBStore.java b/security-admin/src/main/java/org/apache/ranger/biz/RoleDBStore.java index 930147b06e..f9296f699e 100644 --- a/security-admin/src/main/java/org/apache/ranger/biz/RoleDBStore.java +++ b/security-admin/src/main/java/org/apache/ranger/biz/RoleDBStore.java @@ -17,15 +17,7 @@ package org.apache.ranger.biz; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import javax.annotation.PostConstruct; - import org.apache.commons.collections.CollectionUtils; -import org.apache.commons.collections.ListUtils; import org.apache.commons.lang.StringUtils; import org.apache.ranger.authorization.hadoop.config.RangerAdminConfig; import org.apache.ranger.authorization.utils.JsonUtils; @@ -38,7 +30,11 @@ import org.apache.ranger.common.UserSessionBase; import org.apache.ranger.common.db.RangerTransactionSynchronizationAdapter; import org.apache.ranger.db.RangerDaoManager; -import org.apache.ranger.entity.*; +import org.apache.ranger.entity.XXRole; +import org.apache.ranger.entity.XXRoleRefGroup; +import org.apache.ranger.entity.XXRoleRefUser; +import org.apache.ranger.entity.XXService; +import org.apache.ranger.entity.XXServiceVersionInfo; import org.apache.ranger.plugin.model.RangerRole; import org.apache.ranger.plugin.store.AbstractPredicateUtil; import org.apache.ranger.plugin.store.RolePredicateUtil; @@ -55,6 +51,13 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; +import javax.annotation.PostConstruct; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Set; import static org.apache.ranger.db.XXGlobalStateDao.RANGER_GLOBAL_STATE_NAME_ROLE; @@ -75,46 +78,25 @@ public class RoleDBStore implements RoleStore { RESTErrorUtil restErrorUtil; @Autowired - RoleRefUpdater roleRefUpdater; + RoleRefUpdater roleRefUpdater; @Autowired - RangerTransactionSynchronizationAdapter transactionSynchronizationAdapter; - - @Autowired - ServiceDBStore svcStore; + RangerTransactionSynchronizationAdapter transactionSynchronizationAdapter; - @Autowired - GdsDBStore gdsStore; - - RangerAdminConfig config; + @Autowired + ServiceDBStore svcStore; - private Boolean populateExistingBaseFields = false; + @Autowired + GdsDBStore gdsStore; - AbstractPredicateUtil predicateUtil = null; + RangerAdminConfig config; + AbstractPredicateUtil predicateUtil; public void init() throws Exception {} - @PostConstruct - public void initStore() { - if (LOG.isDebugEnabled()) { - LOG.debug("==> RoleDBStore.initStore()"); - } - - config = RangerAdminConfig.getInstance(); - - roleService.setPopulateExistingBaseFields(populateExistingBaseFields); - predicateUtil = new RolePredicateUtil(); - - if (LOG.isDebugEnabled()) { - LOG.debug("<== RoleDBStore.initStore()"); - } - } - @Override public RangerRole createRole(RangerRole role, Boolean createNonExistUserGroupRole) throws Exception { - if (LOG.isDebugEnabled()) { - LOG.debug("==> RoleDBStore.createRole()"); - } + LOG.debug("==> RoleDBStore.createRole()"); XXRole xxRole = daoMgr.getXXRole().findByRoleName(role.getName()); @@ -126,7 +108,9 @@ public RangerRole createRole(RangerRole role, Boolean createNonExistUserGroupRol transactionSynchronizationAdapter.executeOnTransactionCommit(roleVersionUpdater); roleService.create(role); + RangerRole createdRole = getRole(role.getName()); + if (createdRole == null) { throw new Exception("Cannot create role:[" + role + "]"); } @@ -134,29 +118,34 @@ public RangerRole createRole(RangerRole role, Boolean createNonExistUserGroupRol roleRefUpdater.createNewRoleMappingForRefTable(createdRole, createNonExistUserGroupRole); roleService.createTransactionLog(createdRole, null, RangerBaseModelService.OPERATION_CREATE_CONTEXT); + return createdRole; } @Override public RangerRole updateRole(RangerRole role, Boolean createNonExistUserGroupRole) throws Exception { XXRole xxRole = daoMgr.getXXRole().findByRoleId(role.getId()); + if (xxRole == null) { throw restErrorUtil.createRESTException("role with id: " + role.getId() + " does not exist"); } - if (!role.getName().equals(xxRole.getName())) { // ensure only if role name is changed - ensureRoleNameUpdateAllowed(xxRole.getName()); - } + if (!role.getName().equals(xxRole.getName())) { // ensure only if role name is changed + ensureRoleNameUpdateAllowed(xxRole.getName()); + } + RangerRole oldRole = null; - if(StringUtils.isNotEmpty(xxRole.getRoleText())) { + + if (StringUtils.isNotEmpty(xxRole.getRoleText())) { oldRole = JsonUtils.jsonToObject(xxRole.getRoleText(), RangerRole.class); } - Runnable roleVersionUpdater = new RoleVersionUpdater(daoMgr); + transactionSynchronizationAdapter.executeOnTransactionCommit(roleVersionUpdater); RangerRole updatedRole = roleService.update(role); + if (updatedRole == null) { throw new Exception("Cannot update role:[" + role + "]"); } @@ -170,32 +159,14 @@ public RangerRole updateRole(RangerRole role, Boolean createNonExistUserGroupRol } roleService.createTransactionLog(updatedRole, oldRole, RangerBaseModelService.OPERATION_UPDATE_CONTEXT); + return role; } - private void ensureRoleNameUpdateAllowed(String roleName) throws Exception { - boolean roleNotInPolicy = ensureRoleNotInPolicy(roleName); - if (!roleNotInPolicy) { - throw new Exception( - "Rolename for '" + roleName + "' can not be updated as it is referenced in one or more policies"); - } - - boolean roleNotInOtherRole = ensureRoleNotInRole(roleName); - if (!roleNotInOtherRole) { - throw new Exception("Rolename for '" + roleName - + "' can not be updated as it is referenced in one or more other roles"); - } - - boolean rleNotInZone = ensureRoleNotInZone(roleName); - - if(!rleNotInZone) { - throw new Exception("Rolename for '"+ roleName + "' can not be updated as it is referenced in one or more security zones"); - } - } - - @Override + @Override public void deleteRole(String roleName) throws Exception { XXRole xxRole = daoMgr.getXXRole().findByRoleName(roleName); + if (xxRole == null) { throw restErrorUtil.createRESTException("Role with name: " + roleName + " does not exist"); } @@ -210,74 +181,40 @@ public void deleteRole(Long roleId) throws Exception { ensureRoleDeleteAllowed(role.getName()); Runnable roleVersionUpdater = new RoleVersionUpdater(daoMgr); + transactionSynchronizationAdapter.executeOnTransactionCommit(roleVersionUpdater); roleRefUpdater.cleanupRefTables(role); - // delete role from audit filter configs - svcStore.updateServiceAuditConfig(role.getName(), REMOVE_REF_TYPE.ROLE); + // delete role from audit filter configs + svcStore.updateServiceAuditConfig(role.getName(), REMOVE_REF_TYPE.ROLE); - // delete gdsObject mapping of role - gdsStore.deletePrincipalFromGdsAcl(REMOVE_REF_TYPE.ROLE.toString(), role.getName()); + // delete gdsObject mapping of role + gdsStore.deletePrincipalFromGdsAcl(REMOVE_REF_TYPE.ROLE.toString(), role.getName()); roleService.delete(role); roleService.createTransactionLog(role, null, RangerBaseModelService.OPERATION_DELETE_CONTEXT); } - private void ensureRoleDeleteAllowed(String roleName) throws Exception { - boolean roleNotInPolicy = ensureRoleNotInPolicy(roleName); - if(!roleNotInPolicy) { - throw new Exception("Role '"+ roleName +"' can not be deleted as it is referenced in one or more policies"); - } - - boolean roleNotInOtherRole = ensureRoleNotInRole(roleName); - if(!roleNotInOtherRole) { - throw new Exception("Role '"+ roleName + "' can not be deleted as it is referenced in one or more other roles"); - } - - boolean rleNotInZone = ensureRoleNotInZone(roleName); - - if(!rleNotInZone) { - throw new Exception("Role '"+ roleName + "' can not be deleted as it is referenced in one or more security zones"); - } - } - - private boolean ensureRoleNotInPolicy(String roleName) { - Long roleRefPolicyCount = daoMgr.getXXPolicyRefRole().findRoleRefPolicyCount(roleName); - - return roleRefPolicyCount < 1; - } - - private boolean ensureRoleNotInRole(String roleName) { - Long roleRefRoleCount = daoMgr.getXXRoleRefRole().findRoleRefRoleCount(roleName); - - return roleRefRoleCount < 1; - } - - private boolean ensureRoleNotInZone(String roleName) { - Long roleRefZoneCount = daoMgr.getXXSecurityZoneRefRole().findRoleRefZoneCount(roleName); - - return roleRefZoneCount < 1; - } - @Override - public RangerRole getRole(Long id) throws Exception { + public RangerRole getRole(Long id) { return roleService.read(id); } @Override - public RangerRole getRole(String name) throws Exception { + public RangerRole getRole(String name) { XXRole xxRole = daoMgr.getXXRole().findByRoleName(name); + if (xxRole == null) { throw restErrorUtil.createRESTException("Role with name: " + name + " does not exist"); } + return roleService.read(xxRole.getId()); } @Override public List getRoles(SearchFilter filter) throws Exception { - List ret = new ArrayList<>(); - - List xxRoles = daoMgr.getXXRole().getAll(); + List ret = new ArrayList<>(); + List xxRoles = daoMgr.getXXRole().getAll(); if (CollectionUtils.isNotEmpty(xxRoles)) { for (XXRole xxRole : xxRoles) { @@ -288,6 +225,7 @@ public List getRoles(SearchFilter filter) throws Exception { List copy = new ArrayList<>(ret); predicateUtil.applyFilter(copy, filter); + ret = copy; } } @@ -295,71 +233,8 @@ public List getRoles(SearchFilter filter) throws Exception { return ret; } - public RangerRoleList getRoles(SearchFilter filter, RangerRoleList rangerRoleList) throws Exception { - List roles = new ArrayList(); - List xxRoles = (List)roleService.searchResources(filter, roleService.searchFields, roleService.sortFields, rangerRoleList); - - if (CollectionUtils.isNotEmpty(xxRoles)) { - for (XXRole xxRole : xxRoles) { - roles.add(roleService.read(xxRole.getId())); - } - } - - rangerRoleList.setRoleList(roles); - return rangerRoleList; - } - - public RangerRoleList getRolesForUser(SearchFilter filter, RangerRoleList rangerRoleList) throws Exception { - List roles = new ArrayList(); - List xxRoles = null; - UserSessionBase userSession = ContextUtil.getCurrentUserSession(); - if (userSession != null && userSession.getUserRoleList().size() == 1 - && userSession.getUserRoleList().contains(RangerConstants.ROLE_USER) - && userSession.getLoginId() != null) { - VXUser loggedInVXUser = xUserService.getXUserByUserName(userSession.getLoginId()); - xxRoles = daoMgr.getXXRole().findByUserId(loggedInVXUser.getId()); - - if (CollectionUtils.isNotEmpty(xxRoles)) { - for (XXRole xxRole : xxRoles) { - roles.add(roleService.read(xxRole.getId())); - } - } - if (predicateUtil != null && filter != null && !filter.isEmpty()) { - List copy = new ArrayList<>(roles); - - predicateUtil.applyFilter(copy, filter); - roles = copy; - } - int totalCount = roles.size(); - int startIndex = filter.getStartIndex(); - int pageSize = filter.getMaxRows(); - int toIndex = Math.min(startIndex + pageSize, totalCount); - if (CollectionUtils.isNotEmpty(roles)) { - roles = roles.subList(startIndex, toIndex); - rangerRoleList.setResultSize(roles.size()); - rangerRoleList.setPageSize(filter.getMaxRows()); - rangerRoleList.setSortBy(filter.getSortBy()); - rangerRoleList.setSortType(filter.getSortType()); - rangerRoleList.setStartIndex(filter.getStartIndex()); - rangerRoleList.setTotalCount(totalCount); - } - } else { - xxRoles = (List) roleService.searchResources(filter, roleService.searchFields, - roleService.sortFields, rangerRoleList); - - if (CollectionUtils.isNotEmpty(xxRoles)) { - for (XXRole xxRole : xxRoles) { - roles.add(roleService.read(xxRole.getId())); - } - } - } - rangerRoleList.setRoleList(roles); - - return rangerRoleList; - } - @Override - public List getRoleNames(SearchFilter filter) throws Exception { + public List getRoleNames(SearchFilter filter) { return daoMgr.getXXRole().getAllNames(); } @@ -368,27 +243,24 @@ public RangerRoles getRoles(String serviceName, Long lastKnownRoleVersion) throw RangerRoles ret = null; Long rangerRoleVersionInDB = getRoleVersion(serviceName); - if (LOG.isDebugEnabled()) { - LOG.debug("==> RoleDBStore.getRoles() lastKnownRoleVersion= " + lastKnownRoleVersion + " rangerRoleVersionInDB= " + rangerRoleVersionInDB); - } + LOG.debug("==> RoleDBStore.getRoles() lastKnownRoleVersion= {} rangerRoleVersionInDB= {}", lastKnownRoleVersion, rangerRoleVersionInDB); if (rangerRoleVersionInDB != null) { ret = RangerRoleCache.getInstance().getLatestRangerRoleOrCached(serviceName, this, lastKnownRoleVersion, rangerRoleVersionInDB); } - if (LOG.isDebugEnabled()) { - LOG.debug("<= RoleDBStore.getRoles() lastKnownRoleVersion= " + lastKnownRoleVersion + " rangerRoleVersionInDB= " + rangerRoleVersionInDB + " RangerRoles= " + ret); - } + LOG.debug("<= RoleDBStore.getRoles() lastKnownRoleVersion= {} rangerRoleVersionInDB= {} RangerRoles= {}", lastKnownRoleVersion, rangerRoleVersionInDB, ret); return ret; } @Override public Long getRoleVersion(String serviceName) { - Long ret = null; + Long ret; if (ServiceDBStore.isSupportsRolesDownloadByService()) { XXServiceVersionInfo xxServiceVersionInfo = daoMgr.getXXServiceVersionInfo().findByServiceName(serviceName); + ret = (xxServiceVersionInfo != null) ? xxServiceVersionInfo.getRoleVersion() : null; } else { ret = daoMgr.getXXGlobalState().getAppDataVersion(RANGER_GLOBAL_STATE_NAME_ROLE); @@ -397,16 +269,116 @@ public Long getRoleVersion(String serviceName) { return ret; } - public Set getRoleNames(String userName, Set userGroups) throws Exception{ + @Override + public boolean roleExists(Long id) { + XXRole role = daoMgr.getXXRole().findByRoleId(id); + + return role != null; + } + + @Override + public boolean roleExists(String name) { + XXRole role = daoMgr.getXXRole().findByRoleName(name); + + return role != null; + } + + @PostConstruct + public void initStore() { + LOG.debug("==> RoleDBStore.initStore()"); + + config = RangerAdminConfig.getInstance(); + + Boolean populateExistingBaseFields = false; + + roleService.setPopulateExistingBaseFields(populateExistingBaseFields); + + predicateUtil = new RolePredicateUtil(); + + LOG.debug("<== RoleDBStore.initStore()"); + } + + public RangerRoleList getRoles(SearchFilter filter, RangerRoleList rangerRoleList) throws Exception { + List roles = new ArrayList<>(); + List xxRoles = roleService.searchResources(filter, roleService.searchFields, roleService.sortFields, rangerRoleList); + + if (CollectionUtils.isNotEmpty(xxRoles)) { + for (XXRole xxRole : xxRoles) { + roles.add(roleService.read(xxRole.getId())); + } + } + + rangerRoleList.setRoleList(roles); + + return rangerRoleList; + } + + public RangerRoleList getRolesForUser(SearchFilter filter, RangerRoleList rangerRoleList) { + List roles = new ArrayList<>(); + UserSessionBase userSession = ContextUtil.getCurrentUserSession(); + + if (userSession != null && userSession.getUserRoleList().size() == 1 && userSession.getUserRoleList().contains(RangerConstants.ROLE_USER) && userSession.getLoginId() != null) { + VXUser loggedInVXUser = xUserService.getXUserByUserName(userSession.getLoginId()); + List xxRoles = daoMgr.getXXRole().findByUserId(loggedInVXUser.getId()); + + if (CollectionUtils.isNotEmpty(xxRoles)) { + for (XXRole xxRole : xxRoles) { + roles.add(roleService.read(xxRole.getId())); + } + } + + if (predicateUtil != null && filter != null && !filter.isEmpty()) { + List copy = new ArrayList<>(roles); + + predicateUtil.applyFilter(copy, filter); + + roles = copy; + } + + int totalCount = roles.size(); + int startIndex = filter.getStartIndex(); + int pageSize = filter.getMaxRows(); + int toIndex = Math.min(startIndex + pageSize, totalCount); + + if (CollectionUtils.isNotEmpty(roles)) { + roles = roles.subList(startIndex, toIndex); + + rangerRoleList.setResultSize(roles.size()); + rangerRoleList.setPageSize(filter.getMaxRows()); + rangerRoleList.setSortBy(filter.getSortBy()); + rangerRoleList.setSortType(filter.getSortType()); + rangerRoleList.setStartIndex(filter.getStartIndex()); + rangerRoleList.setTotalCount(totalCount); + } + } else { + List xxRoles = roleService.searchResources(filter, roleService.searchFields, roleService.sortFields, rangerRoleList); + + if (CollectionUtils.isNotEmpty(xxRoles)) { + for (XXRole xxRole : xxRoles) { + roles.add(roleService.read(xxRole.getId())); + } + } + } + + rangerRoleList.setRoleList(roles); + + return rangerRoleList; + } + + public Set getRoleNames(String userName, Set userGroups) { Set ret = new HashSet<>(); + if (StringUtils.isNotEmpty(userName)) { List xxRoleRefUsers = roleRefUpdater.getRangerDaoManager().getXXRoleRefUser().findByUserName(userName); + for (XXRoleRefUser xxRoleRefUser : xxRoleRefUsers) { ret.add(getRole(xxRoleRefUser.getRoleId())); } } - for(String userGroup : userGroups) { + + for (String userGroup : userGroups) { List xxRoleRefGroups = roleRefUpdater.getRangerDaoManager().getXXRoleRefGroup().findByGroupName(userGroup); + for (XXRoleRefGroup xxRoleRefGroup : xxRoleRefGroups) { ret.add(getRole(xxRoleRefGroup.getRoleId())); } @@ -416,27 +388,32 @@ public Set getRoleNames(String userName, Set userGroups) thr } public List getRoles(String serviceName) { - List ret = ListUtils.EMPTY_LIST; + List ret = Collections.emptyList(); + if (StringUtils.isNotEmpty(serviceName)) { XXService xxService = daoMgr.getXXService().findByName(serviceName); + ret = getRoles(xxService); } + return ret; } public List getRoles(Long serviceId) { - List ret = ListUtils.EMPTY_LIST; + List ret = Collections.emptyList(); if (serviceId != null) { - String serviceTypeName = daoMgr.getXXServiceDef().findServiceDefTypeByServiceId(serviceId); - if (LOG.isDebugEnabled()) { - LOG.debug("Service Type for serviceId (" + serviceId + ") = " + serviceTypeName); - } - String serviceTypesToGetAllRoles = config.get("ranger.admin.service.types.for.returning.all.roles", "solr"); + String serviceTypeName = daoMgr.getXXServiceDef().findServiceDefTypeByServiceId(serviceId); + + LOG.debug("Service Type for serviceId ({}) = {}", serviceId, serviceTypeName); + + String serviceTypesToGetAllRoles = config.get("ranger.admin.service.types.for.returning.all.roles", "solr"); + + boolean getAllRoles = false; - boolean getAllRoles = false; if (StringUtils.isNotEmpty(serviceTypesToGetAllRoles)) { String[] allRolesServiceTypes = StringUtils.split(serviceTypesToGetAllRoles, ","); + if (allRolesServiceTypes != null) { for (String allRolesServiceType : allRolesServiceTypes) { if (StringUtils.equalsIgnoreCase(serviceTypeName, allRolesServiceType)) { @@ -446,49 +423,97 @@ public List getRoles(Long serviceId) { } } } + List rolesFromDb = getAllRoles ? daoMgr.getXXRole().getAll() : daoMgr.getXXRole().findByServiceId(serviceId); + if (CollectionUtils.isNotEmpty(rolesFromDb)) { ret = new ArrayList<>(); + for (XXRole xxRole : rolesFromDb) { ret.add(roleService.read(xxRole.getId())); } } } + return ret; } public List getRoles(XXService service) { - return service == null ? ListUtils.EMPTY_LIST : getRoles(service.getId()); + return service == null ? Collections.emptyList() : getRoles(service.getId()); } - @Override - public boolean roleExists(Long id) throws Exception { - XXRole role = daoMgr.getXXRole().findByRoleId(id); - return role != null; + private void ensureRoleNameUpdateAllowed(String roleName) throws Exception { + boolean roleNotInPolicy = ensureRoleNotInPolicy(roleName); + + if (!roleNotInPolicy) { + throw new Exception("Rolename for '" + roleName + "' can not be updated as it is referenced in one or more policies"); + } + + boolean roleNotInOtherRole = ensureRoleNotInRole(roleName); + + if (!roleNotInOtherRole) { + throw new Exception("Rolename for '" + roleName + "' can not be updated as it is referenced in one or more other roles"); + } + + boolean rleNotInZone = ensureRoleNotInZone(roleName); + + if (!rleNotInZone) { + throw new Exception("Rolename for '" + roleName + "' can not be updated as it is referenced in one or more security zones"); + } } - @Override - public boolean roleExists(String name) throws Exception { - XXRole role = daoMgr.getXXRole().findByRoleName(name); - return role != null; + private void ensureRoleDeleteAllowed(String roleName) throws Exception { + boolean roleNotInPolicy = ensureRoleNotInPolicy(roleName); + + if (!roleNotInPolicy) { + throw new Exception("Role '" + roleName + "' can not be deleted as it is referenced in one or more policies"); + } + + boolean roleNotInOtherRole = ensureRoleNotInRole(roleName); + + if (!roleNotInOtherRole) { + throw new Exception("Role '" + roleName + "' can not be deleted as it is referenced in one or more other roles"); + } + + boolean rleNotInZone = ensureRoleNotInZone(roleName); + + if (!rleNotInZone) { + throw new Exception("Role '" + roleName + "' can not be deleted as it is referenced in one or more security zones"); + } } - - public static class RoleVersionUpdater implements Runnable { - final RangerDaoManager daoManager; + private boolean ensureRoleNotInPolicy(String roleName) { + Long roleRefPolicyCount = daoMgr.getXXPolicyRefRole().findRoleRefPolicyCount(roleName); + + return roleRefPolicyCount < 1; + } - public RoleVersionUpdater(RangerDaoManager daoManager) { - this.daoManager = daoManager; - } + private boolean ensureRoleNotInRole(String roleName) { + Long roleRefRoleCount = daoMgr.getXXRoleRefRole().findRoleRefRoleCount(roleName); - @Override - public void run() { - try { - this.daoManager.getXXGlobalState().onGlobalAppDataChange(RANGER_GLOBAL_STATE_NAME_ROLE); - } catch (Exception e) { - LOG.error("Cannot update GlobalState version for state:[" + RANGER_GLOBAL_STATE_NAME_ROLE + "]", e); - } - } + return roleRefRoleCount < 1; } -} + private boolean ensureRoleNotInZone(String roleName) { + Long roleRefZoneCount = daoMgr.getXXSecurityZoneRefRole().findRoleRefZoneCount(roleName); + + return roleRefZoneCount < 1; + } + + public static class RoleVersionUpdater implements Runnable { + final RangerDaoManager daoManager; + + public RoleVersionUpdater(RangerDaoManager daoManager) { + this.daoManager = daoManager; + } + + @Override + public void run() { + try { + this.daoManager.getXXGlobalState().onGlobalAppDataChange(RANGER_GLOBAL_STATE_NAME_ROLE); + } catch (Exception e) { + LOG.error("Cannot update GlobalState version for state:[{}]", RANGER_GLOBAL_STATE_NAME_ROLE, e); + } + } + } +} diff --git a/security-admin/src/main/java/org/apache/ranger/biz/RoleRefUpdater.java b/security-admin/src/main/java/org/apache/ranger/biz/RoleRefUpdater.java index 26f7b3b83c..3863f5a088 100644 --- a/security-admin/src/main/java/org/apache/ranger/biz/RoleRefUpdater.java +++ b/security-admin/src/main/java/org/apache/ranger/biz/RoleRefUpdater.java @@ -19,10 +19,6 @@ package org.apache.ranger.biz; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang.StringUtils; import org.apache.ranger.common.MessageEnums; @@ -49,22 +45,26 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + import static org.apache.ranger.service.RangerBaseModelService.OPERATION_CREATE_CONTEXT; @Component public class RoleRefUpdater { - private static final Logger LOG = LoggerFactory.getLogger(RoleRefUpdater.class); + private static final Logger LOG = LoggerFactory.getLogger(RoleRefUpdater.class); - @Autowired - RangerDaoManager daoMgr; + @Autowired + RangerDaoManager daoMgr; - @Autowired - RangerAuditFields rangerAuditFields; + @Autowired + RangerAuditFields rangerAuditFields; - @Autowired - RESTErrorUtil restErrorUtil; + @Autowired + RESTErrorUtil restErrorUtil; - @Autowired + @Autowired XUserMgr xUserMgr; @Autowired @@ -73,315 +73,320 @@ public class RoleRefUpdater { @Autowired RangerTransactionSynchronizationAdapter rangerTransactionSynchronizationAdapter; - @Autowired - RoleDBStore roleStore; - - @Autowired - RangerBizUtil xaBizUtil; - public RangerDaoManager getRangerDaoManager() { - return daoMgr; - } - public void createNewRoleMappingForRefTable(RangerRole rangerRole, Boolean createNonExistUserGroupRole) { - if (rangerRole == null) { - return; - } - - cleanupRefTables(rangerRole); - final Long roleId = rangerRole.getId(); - - final Set roleUsers = new HashSet<>(); - final Set roleGroups = new HashSet<>(); - final Set roleRoles = new HashSet<>(); - - for (RangerRole.RoleMember user : rangerRole.getUsers()) { - roleUsers.add(user.getName()); - } - for (RangerRole.RoleMember group : rangerRole.getGroups()) { - roleGroups.add(group.getName()); - } - for (RangerRole.RoleMember role : rangerRole.getRoles()) { - roleRoles.add(role.getName()); - } - - final boolean isCreateNonExistentUGRs = createNonExistUserGroupRole && xaBizUtil.checkAdminAccess(); - - if (CollectionUtils.isNotEmpty(roleUsers)) { - for (String roleUser : roleUsers) { - - if (StringUtils.isBlank(roleUser)) { - continue; - } - RolePrincipalAssociator associator = new RolePrincipalAssociator(PolicyRefUpdater.PRINCIPAL_TYPE.USER, roleUser, roleId); - - if (!associator.doAssociate(false)) { - if (isCreateNonExistentUGRs) { - rangerTransactionSynchronizationAdapter.executeOnTransactionCommit(associator); - } else { - throw restErrorUtil.createRESTException("user with name: " + roleUser + " does not exist ", MessageEnums.INVALID_INPUT_DATA); - } - } - } - } - - if (CollectionUtils.isNotEmpty(roleGroups)) { - for (String roleGroup : roleGroups) { - - if (StringUtils.isBlank(roleGroup)) { - continue; - } - RolePrincipalAssociator associator = new RolePrincipalAssociator(PolicyRefUpdater.PRINCIPAL_TYPE.GROUP, roleGroup, roleId); - - if (!associator.doAssociate(false)) { - if (isCreateNonExistentUGRs) { - rangerTransactionSynchronizationAdapter.executeOnTransactionCommit(associator); - } else { - throw restErrorUtil.createRESTException("Group with name: " + roleGroup + " does not exist ", MessageEnums.INVALID_INPUT_DATA); - } - } - } - } - - if (CollectionUtils.isNotEmpty(roleRoles)) { - for (String roleRole : roleRoles) { - - if (StringUtils.isBlank(roleRole)) { - continue; - } - - RolePrincipalAssociator associator = new RolePrincipalAssociator(PolicyRefUpdater.PRINCIPAL_TYPE.ROLE, roleRole, roleId); - - if (!associator.doAssociate(false)) { - if (isCreateNonExistentUGRs) { - rangerTransactionSynchronizationAdapter.executeOnTransactionCommit(associator); - } else { - throw restErrorUtil.createRESTException("Role with name: " + roleRole + " does not exist ", MessageEnums.INVALID_INPUT_DATA); - } - } - } - } - - } - - public Boolean cleanupRefTables(RangerRole rangerRole) { - final Long roleId = rangerRole.getId(); - - if (roleId == null) { - return false; - } - - XXRoleRefUserDao xRoleUserDao = daoMgr.getXXRoleRefUser(); - XXRoleRefGroupDao xRoleGroupDao = daoMgr.getXXRoleRefGroup(); - XXRoleRefRoleDao xRoleRoleDao = daoMgr.getXXRoleRefRole(); - - List xxRoleRefUserIds = xRoleUserDao.findIdsByRoleId(roleId); - xRoleUserDao.deleteRoleRefUserByIds(xxRoleRefUserIds); - - List xxRoleRefGroupByIds = xRoleGroupDao.findIdsByRoleId(roleId); - xRoleGroupDao.deleteRoleRefGroupByIds(xxRoleRefGroupByIds); - - List xxRoleRefRoleIds = xRoleRoleDao.findIdsByRoleId(roleId); - xRoleRoleDao.deleteRoleRefRoleByIds(xxRoleRefRoleIds); - - return true; - } - - private class RolePrincipalAssociator implements Runnable { - final PolicyRefUpdater.PRINCIPAL_TYPE type; - final String name; - final Long roleId; - - public RolePrincipalAssociator(PolicyRefUpdater.PRINCIPAL_TYPE type, String name, Long roleId) { - this.type = type; - this.name = name; - this.roleId = roleId; - } - - @Override - public void run() { - if (doAssociate(true)) { - if (LOG.isDebugEnabled()) { - LOG.debug("Associated " + type.name() + ":" + name + " with role id:[" + roleId + "]"); - } - } else { - throw new RuntimeException("Failed to associate " + type.name() + ":" + name + " with role id:[" + roleId + "]"); - } - } - - boolean doAssociate(boolean isAdmin) { - if (LOG.isDebugEnabled()) { - LOG.debug("===> RolePrincipalAssociator.doAssociate(" + isAdmin + ")"); - } - final boolean ret; - - Long id = createOrGetPrincipal(isAdmin); - if (id != null) { - // associate with role - createRoleAssociation(id, name); - ret = true; - } else { - ret = false; - } - - if (LOG.isDebugEnabled()) { - LOG.debug("<=== RolePrincipalAssociator.doAssociate(" + isAdmin + ") : " + ret); - } - return ret; - } - - private Long createOrGetPrincipal(final boolean createIfAbsent) { - if (LOG.isDebugEnabled()) { - LOG.debug("===> RolePrincipalAssociator.createOrGetPrincipal(" + createIfAbsent + ")"); - } - - Long ret = null; - - switch (type) { - case USER: { - XXUser xUser = daoMgr.getXXUser().findByUserName(name); - if (xUser != null) { - ret = xUser.getId(); - } else { - if (createIfAbsent) { - ret = createPrincipal(name); - } - } - } - break; - case GROUP: { - XXGroup xGroup = daoMgr.getXXGroup().findByGroupName(name); - - if (xGroup != null) { - ret = xGroup.getId(); - } else { - if (createIfAbsent) { - ret = createPrincipal(name); - } - } - } - break; - case ROLE: { - XXRole xRole = daoMgr.getXXRole().findByRoleName(name); - if (xRole != null) { - ret = xRole.getId(); - } else { - if (createIfAbsent) { - RangerBizUtil.setBulkMode(false); - ret = createPrincipal(name); - } - } - } - break; - default: - break; - } - if (LOG.isDebugEnabled()) { - LOG.debug("<=== RolePrincipalAssociator.createOrGetPrincipal(" + createIfAbsent + ") : " + ret); - } - return ret; - } - - private Long createPrincipal(String user) { - LOG.warn(type.name()+" specified in role does not exist in ranger admin, creating new "+type.name()+", Type: " + type.name() + ", name = " + user); - - if (LOG.isDebugEnabled()) { - LOG.debug("===> RolePrincipalAssociator.createPrincipal(type=" + type.name() +", name=" + name + ")"); - } - - Long ret = null; - - switch (type) { - case USER: { - // Create External user - VXUser vXUser = xUserMgr.createServiceConfigUser(name); - if (vXUser != null) { - XXUser xUser = daoMgr.getXXUser().findByUserName(name); - - if (xUser == null) { - LOG.error("No User created!! Irrecoverable error! [" + name + "]"); - } else { - ret = xUser.getId(); - } - } else { - LOG.warn("serviceConfigUser:[" + name + "] creation failed. This may be a transient/spurious condition that may correct itself when transaction is committed"); - } - } - break; - case GROUP: { - // Create group - VXGroup vxGroup = new VXGroup(); - vxGroup.setName(name); - vxGroup.setDescription(name); - vxGroup.setGroupSource(RangerCommonEnums.GROUP_EXTERNAL); - VXGroup vXGroup = xGroupService.createXGroupWithOutLogin(vxGroup); - if (vXGroup != null) { - xGroupService.createTransactionLog(vXGroup, null, OPERATION_CREATE_CONTEXT); - - ret = vXGroup.getId(); - } - } - break; - case ROLE: { - // Create role - try { - RangerRole rRole = new RangerRole(name, null, null, null, null); - RangerRole createdRole = roleStore.createRole(rRole, false); - ret = createdRole.getId(); - } catch (Exception e) { - LOG.error("Failed to create Role "+ type.name()); - } - } - break; - default: - break; - } - if (LOG.isDebugEnabled()) { - LOG.debug("<=== RolePrincipalAssociator.createPrincipal(type=" + type.name() + ", name=" + name + ") : " + ret); - } - return ret; - } - - private void createRoleAssociation(Long id, String name) { - if(LOG.isDebugEnabled()) { - LOG.debug("===> RolePrincipalAssociator.createRoleAssociation(roleId=" + roleId + ", type=" + type.name() + ", name=" + name + ", id=" + id + ")"); - } - switch (type) { - case USER: { - XXRoleRefUser xRoleRefUser = rangerAuditFields.populateAuditFieldsForCreate(new XXRoleRefUser()); - - xRoleRefUser.setRoleId(roleId); - xRoleRefUser.setUserId(id); - xRoleRefUser.setUserName(name); - xRoleRefUser.setUserType(0); - daoMgr.getXXRoleRefUser().create(xRoleRefUser); - } - break; - case GROUP: { - XXRoleRefGroup xRoleRefGroup = rangerAuditFields.populateAuditFieldsForCreate(new XXRoleRefGroup()); - - xRoleRefGroup.setRoleId(roleId); - xRoleRefGroup.setGroupId(id); - xRoleRefGroup.setGroupName(name); - xRoleRefGroup.setGroupType(0); - daoMgr.getXXRoleRefGroup().create(xRoleRefGroup); - } - break; - case ROLE: { - XXRoleRefRole xRoleRefRole = rangerAuditFields.populateAuditFieldsForCreate(new XXRoleRefRole()); - - xRoleRefRole.setRoleId(roleId); - xRoleRefRole.setSubRoleId(id); - xRoleRefRole.setSubRoleName(name); - xRoleRefRole.setSubRoleType(0); - daoMgr.getXXRoleRefRole().create(xRoleRefRole); - } - break; - default: - break; - } - if(LOG.isDebugEnabled()) { - LOG.debug("<=== RolePrincipalAssociator.createRoleAssociation(roleId=" + roleId + ", type=" + type.name() + ", name=" + name + ", id=" + id + ")"); - } - } - } + @Autowired + RoleDBStore roleStore; + + @Autowired + RangerBizUtil xaBizUtil; + + public RangerDaoManager getRangerDaoManager() { + return daoMgr; + } + + public void createNewRoleMappingForRefTable(RangerRole rangerRole, Boolean createNonExistUserGroupRole) { + if (rangerRole == null) { + return; + } + + cleanupRefTables(rangerRole); + + final Long roleId = rangerRole.getId(); + final Set roleUsers = new HashSet<>(); + final Set roleGroups = new HashSet<>(); + final Set roleRoles = new HashSet<>(); + + for (RangerRole.RoleMember user : rangerRole.getUsers()) { + roleUsers.add(user.getName()); + } + + for (RangerRole.RoleMember group : rangerRole.getGroups()) { + roleGroups.add(group.getName()); + } + + for (RangerRole.RoleMember role : rangerRole.getRoles()) { + roleRoles.add(role.getName()); + } + + final boolean isCreateNonExistentUGRs = createNonExistUserGroupRole && xaBizUtil.checkAdminAccess(); + + if (CollectionUtils.isNotEmpty(roleUsers)) { + for (String roleUser : roleUsers) { + if (StringUtils.isBlank(roleUser)) { + continue; + } + + RolePrincipalAssociator associator = new RolePrincipalAssociator(PolicyRefUpdater.PRINCIPAL_TYPE.USER, roleUser, roleId); + + if (!associator.doAssociate(false)) { + if (isCreateNonExistentUGRs) { + rangerTransactionSynchronizationAdapter.executeOnTransactionCommit(associator); + } else { + throw restErrorUtil.createRESTException("user with name: " + roleUser + " does not exist ", MessageEnums.INVALID_INPUT_DATA); + } + } + } + } + + if (CollectionUtils.isNotEmpty(roleGroups)) { + for (String roleGroup : roleGroups) { + if (StringUtils.isBlank(roleGroup)) { + continue; + } + + RolePrincipalAssociator associator = new RolePrincipalAssociator(PolicyRefUpdater.PRINCIPAL_TYPE.GROUP, roleGroup, roleId); + if (!associator.doAssociate(false)) { + if (isCreateNonExistentUGRs) { + rangerTransactionSynchronizationAdapter.executeOnTransactionCommit(associator); + } else { + throw restErrorUtil.createRESTException("Group with name: " + roleGroup + " does not exist ", MessageEnums.INVALID_INPUT_DATA); + } + } + } + } + + if (CollectionUtils.isNotEmpty(roleRoles)) { + for (String roleRole : roleRoles) { + if (StringUtils.isBlank(roleRole)) { + continue; + } + + RolePrincipalAssociator associator = new RolePrincipalAssociator(PolicyRefUpdater.PRINCIPAL_TYPE.ROLE, roleRole, roleId); + + if (!associator.doAssociate(false)) { + if (isCreateNonExistentUGRs) { + rangerTransactionSynchronizationAdapter.executeOnTransactionCommit(associator); + } else { + throw restErrorUtil.createRESTException("Role with name: " + roleRole + " does not exist ", MessageEnums.INVALID_INPUT_DATA); + } + } + } + } + } + + public Boolean cleanupRefTables(RangerRole rangerRole) { + final Long roleId = rangerRole.getId(); + + if (roleId == null) { + return false; + } + + XXRoleRefUserDao xRoleUserDao = daoMgr.getXXRoleRefUser(); + XXRoleRefGroupDao xRoleGroupDao = daoMgr.getXXRoleRefGroup(); + XXRoleRefRoleDao xRoleRoleDao = daoMgr.getXXRoleRefRole(); + + List xxRoleRefUserIds = xRoleUserDao.findIdsByRoleId(roleId); + + xRoleUserDao.deleteRoleRefUserByIds(xxRoleRefUserIds); + + List xxRoleRefGroupByIds = xRoleGroupDao.findIdsByRoleId(roleId); + + xRoleGroupDao.deleteRoleRefGroupByIds(xxRoleRefGroupByIds); + + List xxRoleRefRoleIds = xRoleRoleDao.findIdsByRoleId(roleId); + + xRoleRoleDao.deleteRoleRefRoleByIds(xxRoleRefRoleIds); + + return true; + } + + private class RolePrincipalAssociator implements Runnable { + final PolicyRefUpdater.PRINCIPAL_TYPE type; + final String name; + final Long roleId; + + public RolePrincipalAssociator(PolicyRefUpdater.PRINCIPAL_TYPE type, String name, Long roleId) { + this.type = type; + this.name = name; + this.roleId = roleId; + } + + @Override + public void run() { + if (doAssociate(true)) { + LOG.debug("Associated {}:{} with role id:[{}]", type.name(), name, roleId); + } else { + throw new RuntimeException("Failed to associate " + type.name() + ":" + name + " with role id:[" + roleId + "]"); + } + } + + boolean doAssociate(boolean isAdmin) { + LOG.debug("===> RolePrincipalAssociator.doAssociate({})", isAdmin); + + final boolean ret; + + Long id = createOrGetPrincipal(isAdmin); + + if (id != null) { + // associate with role + createRoleAssociation(id, name); + + ret = true; + } else { + ret = false; + } + + LOG.debug("<=== RolePrincipalAssociator.doAssociate({}) : {}", isAdmin, ret); + + return ret; + } + + private Long createOrGetPrincipal(final boolean createIfAbsent) { + LOG.debug("===> RolePrincipalAssociator.createOrGetPrincipal({})", createIfAbsent); + + Long ret = null; + + switch (type) { + case USER: { + XXUser xUser = daoMgr.getXXUser().findByUserName(name); + + if (xUser != null) { + ret = xUser.getId(); + } else { + if (createIfAbsent) { + ret = createPrincipal(name); + } + } + } + break; + case GROUP: { + XXGroup xGroup = daoMgr.getXXGroup().findByGroupName(name); + + if (xGroup != null) { + ret = xGroup.getId(); + } else { + if (createIfAbsent) { + ret = createPrincipal(name); + } + } + } + break; + case ROLE: { + XXRole xRole = daoMgr.getXXRole().findByRoleName(name); + + if (xRole != null) { + ret = xRole.getId(); + } else { + if (createIfAbsent) { + RangerBizUtil.setBulkMode(false); + ret = createPrincipal(name); + } + } + } + break; + default: + break; + } + + LOG.debug("<=== RolePrincipalAssociator.createOrGetPrincipal({}) : {}", createIfAbsent, ret); + + return ret; + } + + private Long createPrincipal(String user) { + LOG.warn("{} specified in role does not exist in ranger admin, creating new {}, Type: {}, name = {}", type.name(), type.name(), type.name(), user); + + LOG.debug("===> RolePrincipalAssociator.createPrincipal(type={}, name={})", type.name(), name); + + Long ret = null; + + switch (type) { + case USER: { + // Create External user + VXUser vXUser = xUserMgr.createServiceConfigUser(name); + if (vXUser != null) { + XXUser xUser = daoMgr.getXXUser().findByUserName(name); + + if (xUser == null) { + LOG.error("No User created!! Irrecoverable error! [{}]", name); + } else { + ret = xUser.getId(); + } + } else { + LOG.warn("serviceConfigUser:[{}] creation failed. This may be a transient/spurious condition that may correct itself when transaction is committed", name); + } + } + break; + case GROUP: { + // Create group + VXGroup vxGroup = new VXGroup(); + + vxGroup.setName(name); + vxGroup.setDescription(name); + vxGroup.setGroupSource(RangerCommonEnums.GROUP_EXTERNAL); + + VXGroup vXGroup = xGroupService.createXGroupWithOutLogin(vxGroup); + + if (vXGroup != null) { + xGroupService.createTransactionLog(vXGroup, null, OPERATION_CREATE_CONTEXT); + + ret = vXGroup.getId(); + } + } + break; + case ROLE: { + // Create role + try { + RangerRole rRole = new RangerRole(name, null, null, null, null); + RangerRole createdRole = roleStore.createRole(rRole, false); + + ret = createdRole.getId(); + } catch (Exception e) { + LOG.error("Failed to create Role {}", type.name()); + } + } + break; + default: + break; + } + + LOG.debug("<=== RolePrincipalAssociator.createPrincipal(type={}, name={}) : {}", type.name(), name, ret); + + return ret; + } + + private void createRoleAssociation(Long id, String name) { + LOG.debug("===> RolePrincipalAssociator.createRoleAssociation(roleId={}, type={}, name={}, id={})", roleId, type.name(), name, id); + + switch (type) { + case USER: { + XXRoleRefUser xRoleRefUser = rangerAuditFields.populateAuditFieldsForCreate(new XXRoleRefUser()); + + xRoleRefUser.setRoleId(roleId); + xRoleRefUser.setUserId(id); + xRoleRefUser.setUserName(name); + xRoleRefUser.setUserType(0); + + daoMgr.getXXRoleRefUser().create(xRoleRefUser); + } + break; + case GROUP: { + XXRoleRefGroup xRoleRefGroup = rangerAuditFields.populateAuditFieldsForCreate(new XXRoleRefGroup()); + + xRoleRefGroup.setRoleId(roleId); + xRoleRefGroup.setGroupId(id); + xRoleRefGroup.setGroupName(name); + xRoleRefGroup.setGroupType(0); + + daoMgr.getXXRoleRefGroup().create(xRoleRefGroup); + } + break; + case ROLE: { + XXRoleRefRole xRoleRefRole = rangerAuditFields.populateAuditFieldsForCreate(new XXRoleRefRole()); + + xRoleRefRole.setRoleId(roleId); + xRoleRefRole.setSubRoleId(id); + xRoleRefRole.setSubRoleName(name); + xRoleRefRole.setSubRoleType(0); + + daoMgr.getXXRoleRefRole().create(xRoleRefRole); + } + break; + default: + break; + } + + LOG.debug("<=== RolePrincipalAssociator.createRoleAssociation(roleId={}, type={}, name={}, id={})", roleId, type.name(), name, id); + } + } } diff --git a/security-admin/src/main/java/org/apache/ranger/biz/SecurityZoneDBStore.java b/security-admin/src/main/java/org/apache/ranger/biz/SecurityZoneDBStore.java index 4d829619ba..547ed088ef 100755 --- a/security-admin/src/main/java/org/apache/ranger/biz/SecurityZoneDBStore.java +++ b/security-admin/src/main/java/org/apache/ranger/biz/SecurityZoneDBStore.java @@ -17,11 +17,6 @@ package org.apache.ranger.biz; -import java.util.*; - -import javax.annotation.PostConstruct; -import javax.servlet.http.HttpServletRequest; - import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections4.MapUtils; import org.apache.commons.lang.StringUtils; @@ -31,13 +26,13 @@ import org.apache.ranger.entity.XXSecurityZone; import org.apache.ranger.entity.XXService; import org.apache.ranger.entity.XXServiceDef; -import org.apache.ranger.plugin.model.RangerSecurityZone; -import org.apache.ranger.plugin.model.RangerSecurityZoneHeaderInfo; -import org.apache.ranger.plugin.model.RangerServiceHeaderInfo; import org.apache.ranger.plugin.model.RangerPrincipal.PrincipalType; +import org.apache.ranger.plugin.model.RangerSecurityZone; import org.apache.ranger.plugin.model.RangerSecurityZone.RangerSecurityZoneService; import org.apache.ranger.plugin.model.RangerSecurityZone.SecurityZoneSummary; import org.apache.ranger.plugin.model.RangerSecurityZone.ZoneServiceSummary; +import org.apache.ranger.plugin.model.RangerSecurityZoneHeaderInfo; +import org.apache.ranger.plugin.model.RangerServiceHeaderInfo; import org.apache.ranger.plugin.store.AbstractPredicateUtil; import org.apache.ranger.plugin.store.PList; import org.apache.ranger.plugin.store.SecurityZonePredicateUtil; @@ -50,9 +45,19 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; +import javax.annotation.PostConstruct; +import javax.servlet.http.HttpServletRequest; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + @Component public class SecurityZoneDBStore implements SecurityZoneStore { private static final Logger LOG = LoggerFactory.getLogger(SecurityZoneDBStore.class); + private static final String RANGER_GLOBAL_STATE_NAME = "RangerSecurityZone"; @Autowired @@ -65,36 +70,21 @@ public class SecurityZoneDBStore implements SecurityZoneStore { RESTErrorUtil restErrorUtil; @Autowired - SecurityZoneRefUpdater securityZoneRefUpdater; + SecurityZoneRefUpdater securityZoneRefUpdater; @Autowired RangerBizUtil bizUtil; - AbstractPredicateUtil predicateUtil = null; + AbstractPredicateUtil predicateUtil; @Autowired ServiceMgr serviceMgr; public void init() throws Exception {} - @PostConstruct - public void initStore() { - if (LOG.isDebugEnabled()) { - LOG.debug("==> SecurityZoneDBStore.initStore()"); - } - - predicateUtil = new SecurityZonePredicateUtil(); - - if (LOG.isDebugEnabled()) { - LOG.debug("<== SecurityZoneDBStore.initStore()"); - } - } - @Override public RangerSecurityZone createSecurityZone(RangerSecurityZone securityZone) throws Exception { - if (LOG.isDebugEnabled()) { - LOG.debug("==> SecurityZoneDBStore.createSecurityZone()"); - } + LOG.debug("==> SecurityZoneDBStore.createSecurityZone()"); XXSecurityZone xxSecurityZone = daoMgr.getXXSecurityZoneDao().findByZoneName(securityZone.getName()); @@ -105,39 +95,50 @@ public RangerSecurityZone createSecurityZone(RangerSecurityZone securityZone) th daoMgr.getXXGlobalState().onGlobalStateChange(RANGER_GLOBAL_STATE_NAME); RangerSecurityZone createdSecurityZone = securityZoneService.create(securityZone); + if (createdSecurityZone == null) { throw restErrorUtil.createRESTException("Cannot create security zone:[" + securityZone + "]"); } + securityZoneRefUpdater.createNewZoneMappingForRefTable(createdSecurityZone); securityZoneService.createTransactionLog(createdSecurityZone, null, RangerBaseModelService.OPERATION_CREATE_CONTEXT); + return createdSecurityZone; } @Override - public RangerSecurityZone updateSecurityZoneById(RangerSecurityZone securityZone) throws Exception { + public RangerSecurityZone updateSecurityZoneById(RangerSecurityZone securityZone) throws Exception { RangerSecurityZone oldSecurityZone = securityZoneService.read(securityZone.getId()); daoMgr.getXXGlobalState().onGlobalStateChange(RANGER_GLOBAL_STATE_NAME); RangerSecurityZone updatedSecurityZone = securityZoneService.update(securityZone); + if (updatedSecurityZone == null) { throw restErrorUtil.createRESTException("Cannot update security zone:[" + securityZone + "]"); } + securityZoneRefUpdater.createNewZoneMappingForRefTable(updatedSecurityZone); + boolean isRenamed = !StringUtils.equals(securityZone.getName(), (null == oldSecurityZone) ? null : oldSecurityZone.getName()); - if (isRenamed) { - securityZoneRefUpdater.updateResourceSignatureWithZoneName(updatedSecurityZone); - } + + if (isRenamed) { + securityZoneRefUpdater.updateResourceSignatureWithZoneName(updatedSecurityZone); + } + securityZoneService.createTransactionLog(updatedSecurityZone, oldSecurityZone, RangerBaseModelService.OPERATION_UPDATE_CONTEXT); + return securityZone; } @Override public void deleteSecurityZoneByName(String zoneName) throws Exception { XXSecurityZone xxSecurityZone = daoMgr.getXXSecurityZoneDao().findByZoneName(zoneName); + if (xxSecurityZone == null) { throw restErrorUtil.createRESTException("security-zone with name: " + zoneName + " does not exist"); } + RangerSecurityZone securityZone = securityZoneService.read(xxSecurityZone.getId()); daoMgr.getXXGlobalState().onGlobalStateChange(RANGER_GLOBAL_STATE_NAME); @@ -146,7 +147,7 @@ public void deleteSecurityZoneByName(String zoneName) throws Exception { securityZoneService.delete(securityZone); securityZoneService.createTransactionLog(securityZone, null, RangerBaseModelService.OPERATION_DELETE_CONTEXT); - } + } @Override public void deleteSecurityZoneById(Long zoneId) throws Exception { @@ -161,24 +162,25 @@ public void deleteSecurityZoneById(Long zoneId) throws Exception { } @Override - public RangerSecurityZone getSecurityZone(Long id) throws Exception { + public RangerSecurityZone getSecurityZone(Long id) { return securityZoneService.read(id); } @Override - public RangerSecurityZone getSecurityZoneByName(String name) throws Exception { + public RangerSecurityZone getSecurityZoneByName(String name) { XXSecurityZone xxSecurityZone = daoMgr.getXXSecurityZoneDao().findByZoneName(name); + if (xxSecurityZone == null) { throw restErrorUtil.createRESTException("security-zone with name: " + name + " does not exist"); } + return securityZoneService.read(xxSecurityZone.getId()); } @Override - public List getSecurityZones(SearchFilter filter) throws Exception { - List ret = new ArrayList<>(); - - List xxSecurityZones = daoMgr.getXXSecurityZoneDao().getAll(); + public List getSecurityZones(SearchFilter filter) { + List ret = new ArrayList<>(); + List xxSecurityZones = daoMgr.getXXSecurityZoneDao().getAll(); for (XXSecurityZone xxSecurityZone : xxSecurityZones) { if (!xxSecurityZone.getId().equals(RangerSecurityZone.RANGER_UNZONED_SECURITY_ZONE_ID)) { @@ -190,6 +192,7 @@ public List getSecurityZones(SearchFilter filter) throws Exc List copy = new ArrayList<>(ret); predicateUtil.applyFilter(copy, filter); + ret = copy; } @@ -201,6 +204,7 @@ public Map getSecurityZone Map ret = null; SearchFilter filter = new SearchFilter(); + filter.setParam(SearchFilter.SERVICE_NAME, serviceName); try { @@ -214,12 +218,21 @@ public Map getSecurityZone } } } catch (Exception excp) { - LOG.error("Failed to get security zones for service:[" + serviceName + "]", excp); + LOG.error("Failed to get security zones for service:[{}]", serviceName, excp); } return ret; } + @PostConstruct + public void initStore() { + LOG.debug("==> SecurityZoneDBStore.initStore()"); + + predicateUtil = new SecurityZonePredicateUtil(); + + LOG.debug("<== SecurityZoneDBStore.initStore()"); + } + public List getSecurityZoneHeaderInfoList(HttpServletRequest request) { String namePrefix = request.getParameter(SearchFilter.ZONE_NAME_PREFIX); boolean filterByNamePrefix = StringUtils.isNotBlank(namePrefix); @@ -227,13 +240,7 @@ public List getSecurityZoneHeaderInfoList(HttpServ List ret = daoMgr.getXXSecurityZoneDao().findAllZoneHeaderInfos(); if (!ret.isEmpty() && filterByNamePrefix) { - for (ListIterator iter = ret.listIterator(); iter.hasNext(); ) { - RangerSecurityZoneHeaderInfo zoneHeader = iter.next(); - - if (!StringUtils.startsWithIgnoreCase(zoneHeader.getName(), namePrefix)) { - iter.remove(); - } - } + ret.removeIf(zoneHeader -> !StringUtils.startsWithIgnoreCase(zoneHeader.getName(), namePrefix)); } return ret; @@ -251,20 +258,14 @@ public List getServiceHeaderInfoListByZoneId(Long zoneI ret.addAll(tagServices); if (!ret.isEmpty() && filterByNamePrefix) { - for (ListIterator iter = ret.listIterator(); iter.hasNext(); ) { - RangerServiceHeaderInfo serviceHeader = iter.next(); - - if (!StringUtils.startsWithIgnoreCase(serviceHeader.getName(), namePrefix)) { - iter.remove(); - } - } + ret.removeIf(serviceHeader -> !StringUtils.startsWithIgnoreCase(serviceHeader.getName(), namePrefix)); } return ret; } public List getSecurityZoneHeaderInfoListByServiceId(Long serviceId, Boolean isTagService, HttpServletRequest request) { - if (serviceId == null){ + if (serviceId == null) { throw restErrorUtil.createRESTException("Invalid value for serviceId", MessageEnums.INVALID_INPUT_DATA); } @@ -274,19 +275,13 @@ public List getSecurityZoneHeaderInfoListByService List ret = daoMgr.getXXSecurityZoneDao().findAllZoneHeaderInfosByServiceId(serviceId, isTagService); if (!ret.isEmpty() && filterByNamePrefix) { - for (ListIterator iter = ret.listIterator(); iter.hasNext(); ) { - RangerSecurityZoneHeaderInfo zoneHeader = iter.next(); - - if (!StringUtils.startsWithIgnoreCase(zoneHeader.getName(), namePrefix)) { - iter.remove(); - } - } + ret.removeIf(zoneHeader -> !StringUtils.startsWithIgnoreCase(zoneHeader.getName(), namePrefix)); } return ret; } - public PList getZonesSummary(SearchFilter filter) throws Exception { + public PList getZonesSummary(SearchFilter filter) { int maxRows = filter.getMaxRows(); int startIndex = filter.getStartIndex(); @@ -302,7 +297,7 @@ public PList getZonesSummary(SearchFilter filter) throws Ex } } - List paginatedList; + List paginatedList; if (summaryList.size() > startIndex) { int endIndex = Math.min((startIndex + maxRows), summaryList.size()); @@ -312,9 +307,7 @@ public PList getZonesSummary(SearchFilter filter) throws Ex paginatedList = Collections.emptyList(); } - PList ret = new PList<>(paginatedList, startIndex, maxRows, summaryList.size(), paginatedList.size(), filter.getSortType(), filter.getSortBy()); - - return ret; + return new PList<>(paginatedList, startIndex, maxRows, summaryList.size(), paginatedList.size(), filter.getSortType(), filter.getSortBy()); } private SecurityZoneSummary toSecurityZoneSummary(RangerSecurityZone securityZone) { @@ -357,8 +350,8 @@ private SecurityZoneSummary toSecurityZoneSummary(RangerSecurityZone securityZon private List getSecurityZoneServiceSummary(RangerSecurityZone securityZone) { List ret = new ArrayList<>(); - if(MapUtils.isNotEmpty(securityZone.getServices())) { - for(Map.Entry entry : securityZone.getServices().entrySet()) { + if (MapUtils.isNotEmpty(securityZone.getServices())) { + for (Map.Entry entry : securityZone.getServices().entrySet()) { String serviceName = entry.getKey(); RangerSecurityZoneService zoneService = entry.getValue(); XXService xService = daoMgr.getXXService().findByName(serviceName); @@ -369,7 +362,7 @@ private List getSecurityZoneServiceSummary(RangerSecurityZon summary.setName(serviceName); summary.setType(serviceDef.getName()); summary.setDisplayName(xService.getDisplayName()); - summary.setResourceCount((long)zoneService.getResources().size()); + summary.setResourceCount((long) zoneService.getResources().size()); ret.add(summary); } diff --git a/security-admin/src/main/java/org/apache/ranger/biz/SecurityZoneRefUpdater.java b/security-admin/src/main/java/org/apache/ranger/biz/SecurityZoneRefUpdater.java index 3fce1e02de..c7a8c46113 100644 --- a/security-admin/src/main/java/org/apache/ranger/biz/SecurityZoneRefUpdater.java +++ b/security-admin/src/main/java/org/apache/ranger/biz/SecurityZoneRefUpdater.java @@ -19,10 +19,6 @@ package org.apache.ranger.biz; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang.StringUtils; import org.apache.ranger.common.MessageEnums; @@ -60,246 +56,237 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + @Component public class SecurityZoneRefUpdater { - private static final Logger LOG = LoggerFactory.getLogger(SecurityZoneRefUpdater.class); - - @Autowired - RangerDaoManager daoMgr; - - @Autowired - RangerAuditFields rangerAuditFields; + private static final Logger LOG = LoggerFactory.getLogger(SecurityZoneRefUpdater.class); - @Autowired - RangerServiceService svcService; + @Autowired + RangerDaoManager daoMgr; - @Autowired - RESTErrorUtil restErrorUtil; + @Autowired + RangerAuditFields rangerAuditFields; - @Autowired - ServiceDBStore svcStore; + @Autowired + RangerServiceService svcService; - @Autowired - RangerPolicyService policyService; + @Autowired + RESTErrorUtil restErrorUtil; - public void createNewZoneMappingForRefTable(RangerSecurityZone rangerSecurityZone) throws Exception { + @Autowired + ServiceDBStore svcStore; - if(rangerSecurityZone == null) { - return; - } + @Autowired + RangerPolicyService policyService; - cleanupRefTables(rangerSecurityZone); + public void createNewZoneMappingForRefTable(RangerSecurityZone rangerSecurityZone) { + if (rangerSecurityZone == null) { + return; + } - final Long zoneId = rangerSecurityZone == null ? null : rangerSecurityZone.getId(); - final Map zoneServices = rangerSecurityZone.getServices(); + cleanupRefTables(rangerSecurityZone); - final Set users = new HashSet<>(); - final Set userGroups = new HashSet<>(); - final Set roles = new HashSet<>(); - final Set tagServices = new HashSet<>(); + final Long zoneId = rangerSecurityZone.getId(); + final Map zoneServices = rangerSecurityZone.getServices(); - users.addAll(rangerSecurityZone.getAdminUsers()); - userGroups.addAll(rangerSecurityZone.getAdminUserGroups()); - roles.addAll(rangerSecurityZone.getAdminRoles()); - users.addAll(rangerSecurityZone.getAuditUsers()); - userGroups.addAll(rangerSecurityZone.getAuditUserGroups()); - roles.addAll(rangerSecurityZone.getAuditRoles()); - tagServices.addAll(rangerSecurityZone.getTagServices()); + final Set users = new HashSet<>(rangerSecurityZone.getAdminUsers()); + final Set userGroups = new HashSet<>(rangerSecurityZone.getAdminUserGroups()); + final Set roles = new HashSet<>(rangerSecurityZone.getAdminRoles()); + final Set tagServices = new HashSet<>(rangerSecurityZone.getTagServices()); - for(Map.Entry service : zoneServices.entrySet()) { - String serviceName = service.getKey(); + users.addAll(rangerSecurityZone.getAuditUsers()); + userGroups.addAll(rangerSecurityZone.getAuditUserGroups()); + roles.addAll(rangerSecurityZone.getAuditRoles()); - if (StringUtils.isBlank(serviceName)) { - continue; - } + for (Map.Entry service : zoneServices.entrySet()) { + String serviceName = service.getKey(); - XXService xService = daoMgr.getXXService().findByName(serviceName); - RangerService rService = svcService.getPopulatedViewObject(xService); - XXServiceDef xServiceDef = daoMgr.getXXServiceDef().findByName(rService.getType()); - XXSecurityZoneRefService xZoneService = rangerAuditFields.populateAuditFieldsForCreate(new XXSecurityZoneRefService()); + if (StringUtils.isBlank(serviceName)) { + continue; + } - xZoneService.setZoneId(zoneId); - xZoneService.setServiceId(xService.getId()); - xZoneService.setServiceName(serviceName); + XXService xService = daoMgr.getXXService().findByName(serviceName); + RangerService rService = svcService.getPopulatedViewObject(xService); + XXServiceDef xServiceDef = daoMgr.getXXServiceDef().findByName(rService.getType()); + XXSecurityZoneRefService xZoneService = rangerAuditFields.populateAuditFieldsForCreate(new XXSecurityZoneRefService()); - daoMgr.getXXSecurityZoneRefService().create(xZoneService); + xZoneService.setZoneId(zoneId); + xZoneService.setServiceId(xService.getId()); + xZoneService.setServiceName(serviceName); - Set resourceDefNames = new HashSet<>(); + daoMgr.getXXSecurityZoneRefService().create(xZoneService); - for(Map> resourceMap:service.getValue().getResources()){//add all resourcedefs in pre defined set - for(Map.Entry> resource : resourceMap.entrySet()) { - String resourceName = resource.getKey(); - if (StringUtils.isBlank(resourceName)) { - continue; - } + Set resourceDefNames = new HashSet<>(); - resourceDefNames.add(resourceName); - } - } + for (Map> resourceMap : service.getValue().getResources()) { //add all resourcedefs in pre defined set + for (Map.Entry> resource : resourceMap.entrySet()) { + String resourceName = resource.getKey(); - for (String resourceName : resourceDefNames) { - XXResourceDef xResourceDef = daoMgr.getXXResourceDef().findByNameAndServiceDefId(resourceName, xServiceDef.getId()); + if (StringUtils.isBlank(resourceName)) { + continue; + } - XXSecurityZoneRefResource xZoneResource = rangerAuditFields.populateAuditFieldsForCreate(new XXSecurityZoneRefResource()); - - xZoneResource.setZoneId(zoneId); - xZoneResource.setResourceDefId(xResourceDef.getId()); - xZoneResource.setResourceName(resourceName); - - daoMgr.getXXSecurityZoneRefResource().create(xZoneResource); - } - } + resourceDefNames.add(resourceName); + } + } - if(CollectionUtils.isNotEmpty(tagServices)) { - for(String tagService : tagServices) { + for (String resourceName : resourceDefNames) { + XXResourceDef xResourceDef = daoMgr.getXXResourceDef().findByNameAndServiceDefId(resourceName, xServiceDef.getId()); + XXSecurityZoneRefResource xZoneResource = rangerAuditFields.populateAuditFieldsForCreate(new XXSecurityZoneRefResource()); - if (StringUtils.isBlank(tagService)) { - continue; - } + xZoneResource.setZoneId(zoneId); + xZoneResource.setResourceDefId(xResourceDef.getId()); + xZoneResource.setResourceName(resourceName); - XXService xService = daoMgr.getXXService().findByName(tagService); - if (xService == null || xService.getType() != RangerConstants.TAG_SERVICE_TYPE) { - throw restErrorUtil.createRESTException("Tag Service named: " + tagService + " does not exist ", - MessageEnums.INVALID_INPUT_DATA); - } + daoMgr.getXXSecurityZoneRefResource().create(xZoneResource); + } + } - XXSecurityZoneRefTagService xZoneTagService = rangerAuditFields.populateAuditFieldsForCreate(new XXSecurityZoneRefTagService()); + if (CollectionUtils.isNotEmpty(tagServices)) { + for (String tagService : tagServices) { + if (StringUtils.isBlank(tagService)) { + continue; + } - xZoneTagService.setZoneId(zoneId); - xZoneTagService.setTagServiceId(xService.getId()); - xZoneTagService.setTagServiceName(xService.getName()); + XXService xService = daoMgr.getXXService().findByName(tagService); - daoMgr.getXXSecurityZoneRefTagService().create(xZoneTagService); - } + if (xService == null || xService.getType() != RangerConstants.TAG_SERVICE_TYPE) { + throw restErrorUtil.createRESTException("Tag Service named: " + tagService + " does not exist ", MessageEnums.INVALID_INPUT_DATA); } - if(CollectionUtils.isNotEmpty(users)) { - for(String user : users) { + XXSecurityZoneRefTagService xZoneTagService = rangerAuditFields.populateAuditFieldsForCreate(new XXSecurityZoneRefTagService()); - if (StringUtils.isBlank(user)) { - continue; - } + xZoneTagService.setZoneId(zoneId); + xZoneTagService.setTagServiceId(xService.getId()); + xZoneTagService.setTagServiceName(xService.getName()); - XXUser xUser = daoMgr.getXXUser().findByUserName(user); + daoMgr.getXXSecurityZoneRefTagService().create(xZoneTagService); + } + } - if (xUser == null) { - throw restErrorUtil.createRESTException("user with name: " + user + " does not exist ", - MessageEnums.INVALID_INPUT_DATA); - } + if (CollectionUtils.isNotEmpty(users)) { + for (String user : users) { + if (StringUtils.isBlank(user)) { + continue; + } - XXSecurityZoneRefUser xZoneUser = rangerAuditFields.populateAuditFieldsForCreate(new XXSecurityZoneRefUser()); + XXUser xUser = daoMgr.getXXUser().findByUserName(user); - xZoneUser.setZoneId(zoneId); - xZoneUser.setUserId(xUser.getId()); - xZoneUser.setUserName(user); - xZoneUser.setUserType(1); + if (xUser == null) { + throw restErrorUtil.createRESTException("user with name: " + user + " does not exist ", MessageEnums.INVALID_INPUT_DATA); + } - daoMgr.getXXSecurityZoneRefUser().create(xZoneUser); - } - } + XXSecurityZoneRefUser xZoneUser = rangerAuditFields.populateAuditFieldsForCreate(new XXSecurityZoneRefUser()); - if(CollectionUtils.isNotEmpty(userGroups)) { - for(String userGroup : userGroups) { + xZoneUser.setZoneId(zoneId); + xZoneUser.setUserId(xUser.getId()); + xZoneUser.setUserName(user); + xZoneUser.setUserType(1); - if (StringUtils.isBlank(userGroup)) { - continue; - } + daoMgr.getXXSecurityZoneRefUser().create(xZoneUser); + } + } - XXGroup xGroup = daoMgr.getXXGroup().findByGroupName(userGroup); + if (CollectionUtils.isNotEmpty(userGroups)) { + for (String userGroup : userGroups) { + if (StringUtils.isBlank(userGroup)) { + continue; + } - if (xGroup == null) { - throw restErrorUtil.createRESTException("group with name: " + userGroup + " does not exist ", - MessageEnums.INVALID_INPUT_DATA); - } + XXGroup xGroup = daoMgr.getXXGroup().findByGroupName(userGroup); - XXSecurityZoneRefGroup xZoneGroup = rangerAuditFields.populateAuditFieldsForCreate(new XXSecurityZoneRefGroup()); + if (xGroup == null) { + throw restErrorUtil.createRESTException("group with name: " + userGroup + " does not exist ", MessageEnums.INVALID_INPUT_DATA); + } - xZoneGroup.setZoneId(zoneId); - xZoneGroup.setGroupId(xGroup.getId()); - xZoneGroup.setGroupName(userGroup); - xZoneGroup.setGroupType(1); + XXSecurityZoneRefGroup xZoneGroup = rangerAuditFields.populateAuditFieldsForCreate(new XXSecurityZoneRefGroup()); - daoMgr.getXXSecurityZoneRefGroup().create(xZoneGroup); - } - } + xZoneGroup.setZoneId(zoneId); + xZoneGroup.setGroupId(xGroup.getId()); + xZoneGroup.setGroupName(userGroup); + xZoneGroup.setGroupType(1); - if(CollectionUtils.isNotEmpty(roles)) { - for(String role : roles) { - if (StringUtils.isBlank(role)) { - continue; - } + daoMgr.getXXSecurityZoneRefGroup().create(xZoneGroup); + } + } - XXRole xRole = daoMgr.getXXRole().findByRoleName(role); + if (CollectionUtils.isNotEmpty(roles)) { + for (String role : roles) { + if (StringUtils.isBlank(role)) { + continue; + } - if (xRole == null) { - throw restErrorUtil.createRESTException("role with name: " + role + " does not exist ", - MessageEnums.INVALID_INPUT_DATA); - } + XXRole xRole = daoMgr.getXXRole().findByRoleName(role); - XXSecurityZoneRefRole xZoneRole = rangerAuditFields.populateAuditFieldsForCreate(new XXSecurityZoneRefRole()); + if (xRole == null) { + throw restErrorUtil.createRESTException("role with name: " + role + " does not exist ", MessageEnums.INVALID_INPUT_DATA); + } - xZoneRole.setZoneId(zoneId); - xZoneRole.setRoleId(xRole.getId()); - xZoneRole.setRoleName(role); + XXSecurityZoneRefRole xZoneRole = rangerAuditFields.populateAuditFieldsForCreate(new XXSecurityZoneRefRole()); - daoMgr.getXXSecurityZoneRefRole().create(xZoneRole); - } - } - } + xZoneRole.setZoneId(zoneId); + xZoneRole.setRoleId(xRole.getId()); + xZoneRole.setRoleName(role); + daoMgr.getXXSecurityZoneRefRole().create(xZoneRole); + } + } + } - public Boolean cleanupRefTables(RangerSecurityZone rangerSecurityZone) { - final Long zoneId = rangerSecurityZone == null ? null : rangerSecurityZone.getId(); + public Boolean cleanupRefTables(RangerSecurityZone rangerSecurityZone) { + final Long zoneId = rangerSecurityZone == null ? null : rangerSecurityZone.getId(); - if (zoneId == null) { - return false; - } + if (zoneId == null) { + return false; + } - XXSecurityZoneRefServiceDao xZoneServiceDao = daoMgr.getXXSecurityZoneRefService(); - XXSecurityZoneRefTagServiceDao xZoneTagServiceDao = daoMgr.getXXSecurityZoneRefTagService(); - XXSecurityZoneRefResourceDao xZoneResourceDao = daoMgr.getXXSecurityZoneRefResource(); - XXSecurityZoneRefUserDao xZoneUserDao = daoMgr.getXXSecurityZoneRefUser(); - XXSecurityZoneRefGroupDao xZoneGroupDao = daoMgr.getXXSecurityZoneRefGroup(); - XXSecurityZoneRefRoleDao xZoneRoleDao = daoMgr.getXXSecurityZoneRefRole(); + XXSecurityZoneRefServiceDao xZoneServiceDao = daoMgr.getXXSecurityZoneRefService(); + XXSecurityZoneRefTagServiceDao xZoneTagServiceDao = daoMgr.getXXSecurityZoneRefTagService(); + XXSecurityZoneRefResourceDao xZoneResourceDao = daoMgr.getXXSecurityZoneRefResource(); + XXSecurityZoneRefUserDao xZoneUserDao = daoMgr.getXXSecurityZoneRefUser(); + XXSecurityZoneRefGroupDao xZoneGroupDao = daoMgr.getXXSecurityZoneRefGroup(); + XXSecurityZoneRefRoleDao xZoneRoleDao = daoMgr.getXXSecurityZoneRefRole(); - for (XXSecurityZoneRefService service : xZoneServiceDao.findByZoneId(zoneId)) { - xZoneServiceDao.remove(service); - } + for (XXSecurityZoneRefService service : xZoneServiceDao.findByZoneId(zoneId)) { + xZoneServiceDao.remove(service); + } - for (XXSecurityZoneRefTagService service : xZoneTagServiceDao.findByZoneId(zoneId)) { - xZoneTagServiceDao.remove(service); - } + for (XXSecurityZoneRefTagService service : xZoneTagServiceDao.findByZoneId(zoneId)) { + xZoneTagServiceDao.remove(service); + } - for(XXSecurityZoneRefResource resource : xZoneResourceDao.findByZoneId(zoneId)) { - xZoneResourceDao.remove(resource); - } + for (XXSecurityZoneRefResource resource : xZoneResourceDao.findByZoneId(zoneId)) { + xZoneResourceDao.remove(resource); + } - for(XXSecurityZoneRefUser user : xZoneUserDao.findByZoneId(zoneId)) { - xZoneUserDao.remove(user); - } + for (XXSecurityZoneRefUser user : xZoneUserDao.findByZoneId(zoneId)) { + xZoneUserDao.remove(user); + } - for(XXSecurityZoneRefGroup group : xZoneGroupDao.findByZoneId(zoneId)) { - xZoneGroupDao.remove(group); - } + for (XXSecurityZoneRefGroup group : xZoneGroupDao.findByZoneId(zoneId)) { + xZoneGroupDao.remove(group); + } - for(XXSecurityZoneRefRole role : xZoneRoleDao.findByZoneId(zoneId)) { - xZoneRoleDao.remove(role); - } + for (XXSecurityZoneRefRole role : xZoneRoleDao.findByZoneId(zoneId)) { + xZoneRoleDao.remove(role); + } - return true; - } + return true; + } + public void updateResourceSignatureWithZoneName(RangerSecurityZone updatedSecurityZone) { + List policyList = daoMgr.getXXPolicy().findByZoneId(updatedSecurityZone.getId()); - public void updateResourceSignatureWithZoneName(RangerSecurityZone updatedSecurityZone) { - List policyList = daoMgr.getXXPolicy().findByZoneId(updatedSecurityZone.getId()); - if (LOG.isDebugEnabled()) { - LOG.debug("==> SecurityZoneRefUpdater.updateResourceSignatureWithZoneName() Count of policies with zone id : " +updatedSecurityZone.getId()+ " are : "+ policyList.size()); - } + LOG.debug("==> SecurityZoneRefUpdater.updateResourceSignatureWithZoneName() Count of policies with zone id : {} are : {}", updatedSecurityZone.getId(), policyList.size()); - for (XXPolicy policy : policyList) { - RangerPolicy policyToUpdate = policyService.getPopulatedViewObject(policy); - svcStore.updatePolicySignature(policyToUpdate); - policyService.update(policyToUpdate); - } - } + for (XXPolicy policy : policyList) { + RangerPolicy policyToUpdate = policyService.getPopulatedViewObject(policy); + svcStore.updatePolicySignature(policyToUpdate); + policyService.update(policyToUpdate); + } + } } diff --git a/security-admin/src/main/java/org/apache/ranger/biz/ServiceDBStore.java b/security-admin/src/main/java/org/apache/ranger/biz/ServiceDBStore.java index a21b8c8d21..8ea288a3bd 100644 --- a/security-admin/src/main/java/org/apache/ranger/biz/ServiceDBStore.java +++ b/security-admin/src/main/java/org/apache/ranger/biz/ServiceDBStore.java @@ -19,36 +19,6 @@ package org.apache.ranger.biz; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.net.UnknownHostException; -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.Comparator; -import java.util.Date; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Objects; -import java.util.Set; -import java.util.StringTokenizer; -import java.util.TreeSet; -import java.util.stream.Collectors; - -import javax.annotation.PostConstruct; -import javax.servlet.ServletOutputStream; -import javax.servlet.http.HttpServletResponse; - import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.MapUtils; import org.apache.commons.io.IOUtils; @@ -67,35 +37,13 @@ import org.apache.ranger.authorization.utils.JsonUtils; import org.apache.ranger.common.AppConstants; import org.apache.ranger.common.ContextUtil; -import org.apache.ranger.common.GUIDUtil; -import org.apache.ranger.common.MessageEnums; -import org.apache.ranger.common.RangerCommonEnums; -import org.apache.ranger.common.db.RangerTransactionSynchronizationAdapter; -import org.apache.ranger.db.XXAuthSessionDao; -import org.apache.ranger.db.XXGlobalStateDao; -import org.apache.ranger.db.XXPolicyDao; -import org.apache.ranger.db.XXTrxLogV2Dao; -import org.apache.ranger.entity.XXTagChangeLog; -import org.apache.ranger.plugin.model.RangerBaseModelObject; -import org.apache.ranger.plugin.model.RangerSecurityZone; -import org.apache.ranger.plugin.util.RangerCommonConstants; -import org.apache.ranger.plugin.util.ServiceDefUtil; -import org.apache.ranger.plugin.util.RangerPurgeResult; -import org.apache.ranger.plugin.util.ServiceTags; -import org.apache.ranger.plugin.model.validation.RangerServiceDefValidator; -import org.apache.ranger.plugin.model.validation.RangerValidator; -import org.apache.ranger.plugin.model.validation.ValidationFailureDetails; -import org.apache.ranger.plugin.model.RangerPolicyDelta; -import org.apache.ranger.plugin.policyengine.RangerPolicyEngine; -import org.apache.ranger.plugin.policyresourcematcher.RangerDefaultPolicyResourceMatcher; -import org.apache.ranger.plugin.policyresourcematcher.RangerPolicyResourceMatcher; -import org.apache.ranger.plugin.service.RangerBaseService; -import org.apache.ranger.plugin.store.ServiceStore; -import org.apache.ranger.plugin.util.PasswordUtils; import org.apache.ranger.common.DateUtil; +import org.apache.ranger.common.GUIDUtil; import org.apache.ranger.common.JSONUtil; +import org.apache.ranger.common.MessageEnums; import org.apache.ranger.common.PropertiesUtil; import org.apache.ranger.common.RESTErrorUtil; +import org.apache.ranger.common.RangerCommonEnums; import org.apache.ranger.common.RangerConstants; import org.apache.ranger.common.RangerFactory; import org.apache.ranger.common.RangerServicePoliciesCache; @@ -103,14 +51,18 @@ import org.apache.ranger.common.SearchCriteria; import org.apache.ranger.common.StringUtil; import org.apache.ranger.common.UserSessionBase; +import org.apache.ranger.common.db.RangerTransactionSynchronizationAdapter; import org.apache.ranger.db.RangerDaoManager; import org.apache.ranger.db.XXAccessTypeDefDao; import org.apache.ranger.db.XXAccessTypeDefGrantsDao; +import org.apache.ranger.db.XXAuthSessionDao; import org.apache.ranger.db.XXContextEnricherDefDao; import org.apache.ranger.db.XXDataMaskTypeDefDao; import org.apache.ranger.db.XXEnumDefDao; import org.apache.ranger.db.XXEnumElementDefDao; +import org.apache.ranger.db.XXGlobalStateDao; import org.apache.ranger.db.XXPolicyConditionDefDao; +import org.apache.ranger.db.XXPolicyDao; import org.apache.ranger.db.XXPolicyExportAuditDao; import org.apache.ranger.db.XXPolicyLabelMapDao; import org.apache.ranger.db.XXResourceDefDao; @@ -118,6 +70,7 @@ import org.apache.ranger.db.XXServiceConfigMapDao; import org.apache.ranger.db.XXServiceDao; import org.apache.ranger.db.XXServiceVersionInfoDao; +import org.apache.ranger.db.XXTrxLogV2Dao; import org.apache.ranger.entity.XXAccessTypeDef; import org.apache.ranger.entity.XXAccessTypeDefGrants; import org.apache.ranger.entity.XXContextEnricherDef; @@ -136,16 +89,18 @@ import org.apache.ranger.entity.XXPolicyRefResource; import org.apache.ranger.entity.XXPortalUser; import org.apache.ranger.entity.XXResourceDef; +import org.apache.ranger.entity.XXRole; import org.apache.ranger.entity.XXSecurityZone; import org.apache.ranger.entity.XXService; import org.apache.ranger.entity.XXServiceConfigDef; import org.apache.ranger.entity.XXServiceConfigMap; import org.apache.ranger.entity.XXServiceDef; import org.apache.ranger.entity.XXServiceVersionInfo; +import org.apache.ranger.entity.XXTagChangeLog; import org.apache.ranger.entity.XXTrxLogV2; -import org.apache.ranger.entity.XXRole; import org.apache.ranger.entity.XXUser; import org.apache.ranger.plugin.model.AuditFilter; +import org.apache.ranger.plugin.model.RangerBaseModelObject; import org.apache.ranger.plugin.model.RangerPolicy; import org.apache.ranger.plugin.model.RangerPolicy.RangerDataMaskPolicyItem; import org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyItem; @@ -153,8 +108,10 @@ import org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyItemCondition; import org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyResource; import org.apache.ranger.plugin.model.RangerPolicy.RangerRowFilterPolicyItem; -import org.apache.ranger.plugin.model.RangerSecurityZone.RangerSecurityZoneService; +import org.apache.ranger.plugin.model.RangerPolicyDelta; import org.apache.ranger.plugin.model.RangerPolicyResourceSignature; +import org.apache.ranger.plugin.model.RangerSecurityZone; +import org.apache.ranger.plugin.model.RangerSecurityZone.RangerSecurityZoneService; import org.apache.ranger.plugin.model.RangerService; import org.apache.ranger.plugin.model.RangerServiceDef; import org.apache.ranger.plugin.model.RangerServiceDef.RangerAccessTypeDef; @@ -168,13 +125,26 @@ import org.apache.ranger.plugin.model.RangerServiceDef.RangerRowFilterDef; import org.apache.ranger.plugin.model.RangerServiceDef.RangerServiceConfigDef; import org.apache.ranger.plugin.model.validation.RangerServiceDefHelper; +import org.apache.ranger.plugin.model.validation.RangerServiceDefValidator; +import org.apache.ranger.plugin.model.validation.RangerValidator; +import org.apache.ranger.plugin.model.validation.ValidationFailureDetails; +import org.apache.ranger.plugin.policyengine.RangerPolicyEngine; +import org.apache.ranger.plugin.policyresourcematcher.RangerDefaultPolicyResourceMatcher; +import org.apache.ranger.plugin.policyresourcematcher.RangerPolicyResourceMatcher; +import org.apache.ranger.plugin.service.RangerBaseService; import org.apache.ranger.plugin.store.AbstractServiceStore; import org.apache.ranger.plugin.store.EmbeddedServiceDefsUtil; import org.apache.ranger.plugin.store.PList; import org.apache.ranger.plugin.store.ServicePredicateUtil; +import org.apache.ranger.plugin.store.ServiceStore; +import org.apache.ranger.plugin.util.PasswordUtils; +import org.apache.ranger.plugin.util.RangerCommonConstants; import org.apache.ranger.plugin.util.RangerPolicyDeltaUtil; +import org.apache.ranger.plugin.util.RangerPurgeResult; import org.apache.ranger.plugin.util.SearchFilter; +import org.apache.ranger.plugin.util.ServiceDefUtil; import org.apache.ranger.plugin.util.ServicePolicies; +import org.apache.ranger.plugin.util.ServiceTags; import org.apache.ranger.rest.ServiceREST; import org.apache.ranger.rest.TagREST; import org.apache.ranger.service.RangerAuditFields; @@ -214,5591 +184,5932 @@ import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Component; import org.springframework.transaction.PlatformTransactionManager; -import org.springframework.transaction.TransactionStatus; -import org.springframework.transaction.support.TransactionCallback; import org.springframework.transaction.support.TransactionTemplate; +import javax.annotation.PostConstruct; +import javax.servlet.ServletOutputStream; +import javax.servlet.http.HttpServletResponse; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.UnknownHostException; +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Comparator; +import java.util.Date; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Objects; +import java.util.Set; +import java.util.StringTokenizer; +import java.util.TreeSet; +import java.util.stream.Collectors; import static org.apache.ranger.db.XXGlobalStateDao.RANGER_GLOBAL_STATE_NAME_GDS; import static org.apache.ranger.service.RangerBaseModelService.OPERATION_CREATE_CONTEXT; @Component public class ServiceDBStore extends AbstractServiceStore { - private static final Logger LOG = LoggerFactory.getLogger(ServiceDBStore.class); + private static final Logger LOG = LoggerFactory.getLogger(ServiceDBStore.class); + + public static final String SERVICE_ADMIN_USERS = "service.admin.users"; + public static final String SERVICE_ADMIN_GROUPS = "service.admin.groups"; + public static final String GDS_SERVICE_NAME = "_gds"; + public static final String CRYPT_ALGO = PropertiesUtil.getProperty("ranger.password.encryption.algorithm", PasswordUtils.DEFAULT_CRYPT_ALGO); + public static final String ENCRYPT_KEY = PropertiesUtil.getProperty("ranger.password.encryption.key", PasswordUtils.DEFAULT_ENCRYPT_KEY); + public static final String SALT = PropertiesUtil.getProperty("ranger.password.salt", PasswordUtils.DEFAULT_SALT); + public static final Integer ITERATION_COUNT = PropertiesUtil.getIntProperty("ranger.password.iteration.count", PasswordUtils.DEFAULT_ITERATION_COUNT); + public static final String RANGER_PLUGIN_AUDIT_FILTERS = "ranger.plugin.audit.filters"; + public static final String HIDDEN_PASSWORD_STR = "*****"; + public static final String CONFIG_KEY_PASSWORD = "password"; + public static final String ACCESS_TYPE_DECRYPT_EEK = "decrypteek"; + public static final String ACCESS_TYPE_GENERATE_EEK = "generateeek"; + public static final String ACCESS_TYPE_GET_METADATA = "getmetadata"; + + private static final String POLICY_ALLOW_EXCLUDE = "Policy Allow:Exclude"; + private static final String POLICY_ALLOW_INCLUDE = "Policy Allow:Include"; + private static final String POLICY_DENY_EXCLUDE = "Policy Deny:Exclude"; + private static final String POLICY_DENY_INCLUDE = "Policy Deny:Include"; + private static final String POLICY_TYPE_ACCESS = "Access"; + private static final String POLICY_TYPE_DATAMASK = "Masking"; + private static final String POLICY_TYPE_ROWFILTER = "Row Level Filter"; + private static final String HOSTNAME = "Host name"; + private static final String USER_NAME = "Exported by"; + private static final String RANGER_VERSION = "Ranger apache version"; + private static final String TIMESTAMP = "Export time"; + private static final String EXPORT_COUNT = "Exported count"; + private static final String SERVICE_CHECK_USER = "service.check.user"; + private static final String AMBARI_SERVICE_CHECK_USER = "ambari.service.check.user"; + private static final String RANGER_PLUGIN_CONFIG_PREFIX = "ranger.plugin."; + private static final String LINE_SEPARATOR = "\n"; + private static final String FILE_HEADER = "ID|Name|Resources|Roles|Groups|Users|Accesses|Service Type|Status|Policy Type|Delegate Admin|isRecursive|isExcludes|Service Name|Description|isAuditEnabled|Policy Conditions|Policy Condition Type|Masking Options|Row Filter Expr|Policy Label Name"; + private static final String COMMA_DELIMITER = "|"; - private static final String POLICY_ALLOW_EXCLUDE = "Policy Allow:Exclude"; + private static final Comparator POLICY_DELTA_ID_COMPARATOR = new RangerPolicyDeltaComparator(); - private static final String POLICY_ALLOW_INCLUDE = "Policy Allow:Include"; - private static final String POLICY_DENY_EXCLUDE = "Policy Deny:Exclude"; - private static final String POLICY_DENY_INCLUDE = "Policy Deny:Include"; + public static boolean SUPPORTS_POLICY_DELTAS; + public static boolean SUPPORTS_IN_PLACE_POLICY_UPDATES; + public static Integer RETENTION_PERIOD_IN_DAYS = 7; + public static Integer TAG_RETENTION_PERIOD_IN_DAYS = 3; + public static boolean SUPPORTS_PURGE_LOGIN_RECORDS; + public static Integer LOGIN_RECORDS_RETENTION_PERIOD_IN_DAYS; + public static boolean SUPPORTS_PURGE_TRANSACTION_RECORDS; + public static Integer TRANSACTION_RECORDS_RETENTION_PERIOD_IN_DAYS; + public static boolean SUPPORTS_PURGE_POLICY_EXPORT_LOGS; + public static Integer POLICY_EXPORT_LOGS_RETENTION_PERIOD_IN_DAYS; + + private static String LOCAL_HOSTNAME; + private static boolean isRolesDownloadedByService; - private static final String POLICY_TYPE_ACCESS = "Access"; - private static final String POLICY_TYPE_DATAMASK = "Masking"; - private static final String POLICY_TYPE_ROWFILTER = "Row Level Filter"; + private static volatile boolean legacyServiceDefsInitDone; - private static String LOCAL_HOSTNAME; - private static final String HOSTNAME = "Host name"; - private static final String USER_NAME = "Exported by"; - private static final String RANGER_VERSION = "Ranger apache version"; - private static final String TIMESTAMP = "Export time"; - private static final String EXPORT_COUNT = "Exported count"; + @Autowired + RangerServiceDefService serviceDefService; + + @Autowired + RangerDaoManager daoMgr; - private static final String SERVICE_CHECK_USER = "service.check.user"; - private static final String AMBARI_SERVICE_CHECK_USER = "ambari.service.check.user"; - public static final String SERVICE_ADMIN_USERS = "service.admin.users"; - public static final String SERVICE_ADMIN_GROUPS = "service.admin.groups"; - public static final String GDS_SERVICE_NAME = "_gds"; + @Autowired + RESTErrorUtil restErrorUtil; - private static boolean isRolesDownloadedByService = false; + @Autowired + RangerServiceService svcService; + + @Autowired + StringUtil stringUtil; + + @Autowired + RangerAuditFields rangerAuditFields; - public static final String CRYPT_ALGO = PropertiesUtil.getProperty("ranger.password.encryption.algorithm", PasswordUtils.DEFAULT_CRYPT_ALGO); - public static final String ENCRYPT_KEY = PropertiesUtil.getProperty("ranger.password.encryption.key", PasswordUtils.DEFAULT_ENCRYPT_KEY); - public static final String SALT = PropertiesUtil.getProperty("ranger.password.salt", PasswordUtils.DEFAULT_SALT); - public static final Integer ITERATION_COUNT = PropertiesUtil.getIntProperty("ranger.password.iteration.count", PasswordUtils.DEFAULT_ITERATION_COUNT); - public static boolean SUPPORTS_POLICY_DELTAS = false; - public static boolean SUPPORTS_IN_PLACE_POLICY_UPDATES = false; - public static Integer RETENTION_PERIOD_IN_DAYS = 7; - public static Integer TAG_RETENTION_PERIOD_IN_DAYS = 3; - public static boolean SUPPORTS_PURGE_LOGIN_RECORDS = false; - public static Integer LOGIN_RECORDS_RETENTION_PERIOD_IN_DAYS = 0; - public static boolean SUPPORTS_PURGE_TRANSACTION_RECORDS = false; - public static Integer TRANSACTION_RECORDS_RETENTION_PERIOD_IN_DAYS = 0; - public static boolean SUPPORTS_PURGE_POLICY_EXPORT_LOGS = false; - public static Integer POLICY_EXPORT_LOGS_RETENTION_PERIOD_IN_DAYS = 0; + @Autowired + RangerPolicyService policyService; + + @Autowired + RangerPolicyLabelsService policyLabelsService; + + @Autowired + XUserService xUserService; + + @Autowired + XUserMgr xUserMgr; + + @Autowired + XGroupService xGroupService; + + @Autowired + PolicyRefUpdater policyRefUpdater; + + @Autowired + RangerDataHistService dataHistService; + + @Autowired + @Qualifier(value = "transactionManager") + PlatformTransactionManager txManager; + + @Autowired + RangerBizUtil bizUtil; + + @Autowired + RangerPolicyWithAssignedIdService assignedIdPolicyService; + + @Autowired + RangerServiceWithAssignedIdService svcServiceWithAssignedId; + + @Autowired + RangerServiceDefWithAssignedIdService svcDefServiceWithAssignedId; + + @Autowired + RangerFactory factory; - private static final String RANGER_PLUGIN_CONFIG_PREFIX = "ranger.plugin."; - public static final String RANGER_PLUGIN_AUDIT_FILTERS = "ranger.plugin.audit.filters"; + @Autowired + JSONUtil jsonUtil; - static { - try { - LOCAL_HOSTNAME = java.net.InetAddress.getLocalHost().getCanonicalHostName(); - } catch (UnknownHostException e) { - LOCAL_HOSTNAME = "unknown"; - } - } + @Autowired + ServiceMgr serviceMgr; - @Autowired - RangerServiceDefService serviceDefService; + @Autowired + AssetMgr assetMgr; - @Autowired - RangerDaoManager daoMgr; + @Autowired + RangerTransactionSynchronizationAdapter transactionSynchronizationAdapter; - @Autowired - RESTErrorUtil restErrorUtil; + @Autowired + RangerSecurityZoneServiceService securityZoneService; - @Autowired - RangerServiceService svcService; + @Autowired + TagDBStore tagStore; - @Autowired - StringUtil stringUtil; + @Autowired + UserMgr userMgr; - @Autowired - RangerAuditFields rangerAuditFields; + @Autowired + SecurityZoneDBStore securityZoneStore; - @Autowired - RangerPolicyService policyService; + @Autowired + GUIDUtil guidUtil; - @Autowired - RangerPolicyLabelsService policyLabelsService; + private boolean populateExistingBaseFields; + private ServicePredicateUtil predicateUtil; + private RangerAdminConfig config; - @Autowired - XUserService xUserService; + public static void persistVersionChange(ServiceVersionUpdater serviceVersionUpdater) { + RangerDaoManager daoMgr = serviceVersionUpdater.daoManager; + Long id = serviceVersionUpdater.serviceId; + VERSION_TYPE versionType = serviceVersionUpdater.versionType; + Long nextVersion = 1L; + Date now = new Date(); - @Autowired - XUserMgr xUserMgr; + XXServiceVersionInfoDao serviceVersionInfoDao = daoMgr.getXXServiceVersionInfo(); + XXServiceVersionInfo serviceVersionInfoDbObj = serviceVersionInfoDao.findByServiceId(id); + XXService service = daoMgr.getXXService().getById(id); - @Autowired - XGroupService xGroupService; + if (serviceVersionInfoDbObj != null) { + if (versionType == VERSION_TYPE.POLICY_VERSION) { + nextVersion = getNextVersion(serviceVersionInfoDbObj.getPolicyVersion()); - @Autowired - PolicyRefUpdater policyRefUpdater; + serviceVersionInfoDbObj.setPolicyVersion(nextVersion); + serviceVersionInfoDbObj.setPolicyUpdateTime(now); + } else if (versionType == VERSION_TYPE.TAG_VERSION) { + nextVersion = getNextVersion(serviceVersionInfoDbObj.getTagVersion()); - @Autowired - RangerDataHistService dataHistService; + serviceVersionInfoDbObj.setTagVersion(nextVersion); + serviceVersionInfoDbObj.setTagUpdateTime(now); + } else if (versionType == VERSION_TYPE.ROLE_VERSION) { + // get the LatestRoleVersion from the GlobalTable and update ServiceInfo for a service + XXGlobalStateDao xxGlobalStateDao = daoMgr.getXXGlobalState(); - @Autowired - @Qualifier(value = "transactionManager") - PlatformTransactionManager txManager; + if (xxGlobalStateDao != null) { + Long roleVersion = xxGlobalStateDao.getAppDataVersion("RangerRole"); - @Autowired - RangerBizUtil bizUtil; + if (roleVersion != null) { + nextVersion = roleVersion; + } else { + LOG.error("No Global state for 'RoleVersion'. Cannot execute this object:[{}]", serviceVersionUpdater); + } - @Autowired - RangerPolicyWithAssignedIdService assignedIdPolicyService; + serviceVersionInfoDbObj.setRoleVersion(nextVersion); + serviceVersionInfoDbObj.setRoleUpdateTime(now); + } else { + LOG.error("No Global state DAO. Cannot execute this object:[{}]", serviceVersionUpdater); - @Autowired - RangerServiceWithAssignedIdService svcServiceWithAssignedId; + return; + } + } else if (versionType == VERSION_TYPE.GDS_VERSION) { + nextVersion = daoMgr.getXXGlobalState().getAppDataVersion(RANGER_GLOBAL_STATE_NAME_GDS); - @Autowired - RangerServiceDefWithAssignedIdService svcDefServiceWithAssignedId; + if (nextVersion == null) { + nextVersion = 1L; + } - @Autowired - RangerFactory factory; + serviceVersionInfoDbObj.setGdsVersion(nextVersion); + serviceVersionInfoDbObj.setGdsUpdateTime(now); + } else { + LOG.error("Unknown VERSION_TYPE:{}. Cannot execute this object:[{}]", versionType, serviceVersionUpdater); - @Autowired - JSONUtil jsonUtil; + return; + } - @Autowired - ServiceMgr serviceMgr; + serviceVersionUpdater.version = nextVersion; - @Autowired - AssetMgr assetMgr; + serviceVersionInfoDao.update(serviceVersionInfoDbObj); + } else { + if (service != null) { + serviceVersionInfoDbObj = new XXServiceVersionInfo(); - @Autowired - RangerTransactionSynchronizationAdapter transactionSynchronizationAdapter; + serviceVersionInfoDbObj.setServiceId(service.getId()); + serviceVersionInfoDbObj.setPolicyVersion(nextVersion); + serviceVersionInfoDbObj.setPolicyUpdateTime(now); + serviceVersionInfoDbObj.setTagVersion(nextVersion); + serviceVersionInfoDbObj.setTagUpdateTime(now); + serviceVersionInfoDbObj.setRoleVersion(nextVersion); + serviceVersionInfoDbObj.setRoleUpdateTime(now); + serviceVersionInfoDbObj.setGdsVersion(nextVersion); + serviceVersionInfoDbObj.setGdsUpdateTime(now); - @Autowired - RangerSecurityZoneServiceService securityZoneService; + serviceVersionUpdater.version = nextVersion; - @Autowired - TagDBStore tagStore; + serviceVersionInfoDao.create(serviceVersionInfoDbObj); + } + } - @Autowired - UserMgr userMgr; + if (service != null) { + if (versionType == VERSION_TYPE.POLICY_VERSION) { + persistChangeLog(service, versionType, serviceVersionInfoDbObj.getPolicyVersion(), serviceVersionUpdater); + } else if (versionType == VERSION_TYPE.TAG_VERSION) { + persistChangeLog(service, versionType, serviceVersionInfoDbObj.getTagVersion(), serviceVersionUpdater); + } + } + } - @Autowired - SecurityZoneDBStore securityZoneStore; + public static boolean isSupportsPolicyDeltas() { + return SUPPORTS_POLICY_DELTAS; + } - @Autowired - GUIDUtil guidUtil; + public static boolean isSupportsRolesDownloadByService() { + return isRolesDownloadedByService; + } - private static volatile boolean legacyServiceDefsInitDone = false; - private Boolean populateExistingBaseFields = false; + @Override + public void init() throws Exception { + LOG.debug("==> ServiceDBStore.init()"); - public static final String HIDDEN_PASSWORD_STR = "*****"; - public static final String CONFIG_KEY_PASSWORD = "password"; - public static final String ACCESS_TYPE_DECRYPT_EEK = "decrypteek"; - public static final String ACCESS_TYPE_GENERATE_EEK = "generateeek"; - public static final String ACCESS_TYPE_GET_METADATA = "getmetadata"; + LOG.debug("<== ServiceDBStore.init()"); + } - private ServicePredicateUtil predicateUtil = null; - private RangerAdminConfig config = null; + @Override + public RangerServiceDef createServiceDef(RangerServiceDef serviceDef) throws Exception { + LOG.debug("==> ServiceDBStore.createServiceDef({})", serviceDef); - @Override - public void init() throws Exception { - if (LOG.isDebugEnabled()) { - LOG.debug("==> ServiceDBStore.init()"); - } + XXServiceDef xServiceDef = daoMgr.getXXServiceDef().findByName(serviceDef.getName()); - if (LOG.isDebugEnabled()) { - LOG.debug("<== ServiceDBStore.init()"); - } - } + if (xServiceDef != null) { + throw restErrorUtil.createRESTException("service-def with name: " + serviceDef.getName() + " already exists", MessageEnums.ERROR_DUPLICATE_OBJECT); + } - @PostConstruct - public void initStore() { - if (LOG.isDebugEnabled()) { - LOG.debug("==> ServiceDBStore.initStore()"); - } + List configs = serviceDef.getConfigs(); + List resources = serviceDef.getResources(); - config = RangerAdminConfig.getInstance(); + if (CollectionUtils.isNotEmpty(resources)) { + RangerServiceDefValidator validator = new RangerServiceDefValidator(this); + List failures = new ArrayList<>(); + boolean isValidResources = validator.isValidResources(serviceDef, failures, RangerValidator.Action.CREATE); - String nullSafeSupplier = config.get("ranger.admin.null_safe.supplier", RangerBaseModelObject.NULL_SAFE_SUPPLIER_V2); + if (!isValidResources) { + throw restErrorUtil.createRESTException("service-def with name: " + serviceDef.getName() + " has invalid resources:[" + failures + "]", MessageEnums.INVALID_INPUT_DATA); + } + } - LOG.info("ranger.admin.null_safe.supplier=" + nullSafeSupplier); + List accessTypes = serviceDef.getAccessTypes(); + List policyConditions = serviceDef.getPolicyConditions(); + List contextEnrichers = serviceDef.getContextEnrichers(); + List enums = serviceDef.getEnums(); + RangerDataMaskDef dataMaskDef = serviceDef.getDataMaskDef(); + RangerRowFilterDef rowFilterDef = serviceDef.getRowFilterDef(); + List dataMaskTypes = dataMaskDef == null || dataMaskDef.getMaskTypes() == null ? new ArrayList<>() : dataMaskDef.getMaskTypes(); + List dataMaskAccessTypes = dataMaskDef == null || dataMaskDef.getAccessTypes() == null ? new ArrayList<>() : dataMaskDef.getAccessTypes(); + List dataMaskResources = dataMaskDef == null || dataMaskDef.getResources() == null ? new ArrayList<>() : dataMaskDef.getResources(); + List rowFilterAccessTypes = rowFilterDef == null || rowFilterDef.getAccessTypes() == null ? new ArrayList<>() : rowFilterDef.getAccessTypes(); + List rowFilterResources = rowFilterDef == null || rowFilterDef.getResources() == null ? new ArrayList<>() : rowFilterDef.getResources(); - RangerBaseModelObject.setNullSafeSupplier(nullSafeSupplier); - - if(! legacyServiceDefsInitDone) { - synchronized(ServiceDBStore.class) { - if(!legacyServiceDefsInitDone) { - - SUPPORTS_POLICY_DELTAS = config.getBoolean("ranger.admin" + RangerCommonConstants.RANGER_ADMIN_SUFFIX_POLICY_DELTA, RangerCommonConstants.RANGER_ADMIN_SUFFIX_POLICY_DELTA_DEFAULT); - RETENTION_PERIOD_IN_DAYS = config.getInt("ranger.admin.delta.retention.time.in.days", 7); - TAG_RETENTION_PERIOD_IN_DAYS = config.getInt("ranger.admin.tag.delta.retention.time.in.days", 3); - - SUPPORTS_PURGE_LOGIN_RECORDS = config.getBoolean("ranger.admin.init.purge.login_records", false); - SUPPORTS_PURGE_TRANSACTION_RECORDS = config.getBoolean("ranger.admin.init.purge.transaction_records", false); - SUPPORTS_PURGE_POLICY_EXPORT_LOGS = config.getBoolean("ranger.admin.init.purge.policy_export_logs", false); - LOGIN_RECORDS_RETENTION_PERIOD_IN_DAYS = config.getInt("ranger.admin.init.purge.login_records.retention.days", 0); - TRANSACTION_RECORDS_RETENTION_PERIOD_IN_DAYS = config.getInt("ranger.admin.init.purge.transaction_records.retention.days", 0); - POLICY_EXPORT_LOGS_RETENTION_PERIOD_IN_DAYS = config.getInt("ranger.admin.init.purge.policy_export_logs.retention.days", 0); - - isRolesDownloadedByService = config.getBoolean("ranger.support.for.service.specific.role.download", false); - SUPPORTS_IN_PLACE_POLICY_UPDATES = SUPPORTS_POLICY_DELTAS && config.getBoolean("ranger.admin" + RangerCommonConstants.RANGER_ADMIN_SUFFIX_IN_PLACE_POLICY_UPDATES, RangerCommonConstants.RANGER_ADMIN_SUFFIX_IN_PLACE_POLICY_UPDATES_DEFAULT); - - LOG.info("SUPPORTS_POLICY_DELTAS=" + SUPPORTS_POLICY_DELTAS); - LOG.info("RETENTION_PERIOD_IN_DAYS=" + RETENTION_PERIOD_IN_DAYS); - LOG.info("TAG_RETENTION_PERIOD_IN_DAYS=" + TAG_RETENTION_PERIOD_IN_DAYS); - LOG.info("SUPPORTS_PURGE_LOGIN_RECORDS=" + SUPPORTS_PURGE_LOGIN_RECORDS); - LOG.info("LOGIN_RECORDS_RETENTION_PERIOD_IN_DAYS=" + LOGIN_RECORDS_RETENTION_PERIOD_IN_DAYS); - LOG.info("SUPPORTS_PURGE_TRANSACTION_RECORDS=" + SUPPORTS_PURGE_TRANSACTION_RECORDS); - LOG.info("TRANSACTION_RECORDS_RETENTION_PERIOD_IN_DAYS=" + TRANSACTION_RECORDS_RETENTION_PERIOD_IN_DAYS); - LOG.info("SUPPORTS_PURGE_POLICY_EXPORT_LOGS=" + SUPPORTS_PURGE_POLICY_EXPORT_LOGS); - LOG.info("POLICY_EXPORT_LOGS_RETENTION_PERIOD_IN_DAYS=" + POLICY_EXPORT_LOGS_RETENTION_PERIOD_IN_DAYS); - LOG.info("isRolesDownloadedByService=" + isRolesDownloadedByService); - LOG.info("SUPPORTS_IN_PLACE_POLICY_UPDATES=" + SUPPORTS_IN_PLACE_POLICY_UPDATES); - - TransactionTemplate txTemplate = new TransactionTemplate(txManager); - - final ServiceDBStore dbStore = this; - predicateUtil = new ServicePredicateUtil(dbStore); - - try { - txTemplate.execute(new TransactionCallback() { - @Override - public Object doInTransaction(TransactionStatus status) { - EmbeddedServiceDefsUtil.instance().init(dbStore); - getServiceUpgraded(); - createGenericUsers(); - resetPolicyUpdateLog(RETENTION_PERIOD_IN_DAYS, RangerPolicyDelta.CHANGE_TYPE_RANGER_ADMIN_START); - resetTagUpdateLog(TAG_RETENTION_PERIOD_IN_DAYS, ServiceTags.TagsChangeType.RANGER_ADMIN_START); - - List purgeResults = new ArrayList<>(); - - if (SUPPORTS_PURGE_LOGIN_RECORDS) { - removeAuthSessions(LOGIN_RECORDS_RETENTION_PERIOD_IN_DAYS, purgeResults); - } - - if (SUPPORTS_PURGE_TRANSACTION_RECORDS) { - removeTransactionLogs(TRANSACTION_RECORDS_RETENTION_PERIOD_IN_DAYS, purgeResults); - } - - if (SUPPORTS_PURGE_POLICY_EXPORT_LOGS) { - removePolicyExportLogs(POLICY_EXPORT_LOGS_RETENTION_PERIOD_IN_DAYS, purgeResults); - } - - initRMSDaos(); - return null; - } - }); - } catch (Throwable ex) { - LOG.error("ServiceDBStore.initStore(): Failed to update DB: " + ex); - } - - legacyServiceDefsInitDone = true; - } - } - } - - if (LOG.isDebugEnabled()) { - LOG.debug("<== ServiceDBStore.initStore()"); - } - } - - @Override - public RangerServiceDef createServiceDef(RangerServiceDef serviceDef) throws Exception { - if (LOG.isDebugEnabled()) { - LOG.debug("==> ServiceDBStore.createServiceDef(" + serviceDef + ")"); - } - - XXServiceDef xServiceDef = daoMgr.getXXServiceDef().findByName( - serviceDef.getName()); - if (xServiceDef != null) { - throw restErrorUtil.createRESTException("service-def with name: " - + serviceDef.getName() + " already exists", - MessageEnums.ERROR_DUPLICATE_OBJECT); - } - - List configs = serviceDef.getConfigs(); - List resources = serviceDef.getResources(); - - if (CollectionUtils.isNotEmpty(resources)) { - RangerServiceDefValidator validator = new RangerServiceDefValidator(this); - List failures = new ArrayList<>(); - boolean isValidResources = validator.isValidResources(serviceDef, failures, RangerValidator.Action.CREATE); - if (!isValidResources) { - throw restErrorUtil.createRESTException("service-def with name: " - + serviceDef.getName() + " has invalid resources:[" + failures.toString() + "]", - MessageEnums.INVALID_INPUT_DATA); - } - } - - List accessTypes = serviceDef.getAccessTypes(); - List policyConditions = serviceDef.getPolicyConditions(); - List contextEnrichers = serviceDef.getContextEnrichers(); - List enums = serviceDef.getEnums(); - RangerDataMaskDef dataMaskDef = serviceDef.getDataMaskDef(); - RangerRowFilterDef rowFilterDef = serviceDef.getRowFilterDef(); - List dataMaskTypes = dataMaskDef == null || dataMaskDef.getMaskTypes() == null ? new ArrayList() : dataMaskDef.getMaskTypes(); - List dataMaskAccessTypes = dataMaskDef == null || dataMaskDef.getAccessTypes() == null ? new ArrayList() : dataMaskDef.getAccessTypes(); - List dataMaskResources = dataMaskDef == null || dataMaskDef.getResources() == null ? new ArrayList() : dataMaskDef.getResources(); - List rowFilterAccessTypes = rowFilterDef == null || rowFilterDef.getAccessTypes() == null ? new ArrayList() : rowFilterDef.getAccessTypes(); - List rowFilterResources = rowFilterDef == null || rowFilterDef.getResources() == null ? new ArrayList() : rowFilterDef.getResources(); - - RangerServiceDefHelper defHelper = new RangerServiceDefHelper(serviceDef, false); - defHelper.patchServiceDefWithDefaultValues(); - - // While creating, value of version should be 1. - serviceDef.setVersion(Long.valueOf(1)); - - if (populateExistingBaseFields) { - svcDefServiceWithAssignedId.setPopulateExistingBaseFields(true); - daoMgr.getXXServiceDef().setIdentityInsert(true); - - svcDefServiceWithAssignedId.create(serviceDef); - - svcDefServiceWithAssignedId.setPopulateExistingBaseFields(false); - daoMgr.getXXServiceDef().updateSequence(); - daoMgr.getXXServiceDef().setIdentityInsert(false); - } else { - // following fields will be auto populated - serviceDef.setId(null); - serviceDef.setCreateTime(null); - serviceDef.setUpdateTime(null); - serviceDef = serviceDefService.create(serviceDef); - } - Long serviceDefId = serviceDef.getId(); - XXServiceDef createdSvcDef = daoMgr.getXXServiceDef().getById(serviceDefId); - - XXServiceConfigDefDao xxServiceConfigDao = daoMgr.getXXServiceConfigDef(); - for(int i = 0; i < configs.size(); i++) { - RangerServiceConfigDef config = configs.get(i); - - XXServiceConfigDef xConfig = new XXServiceConfigDef(); - xConfig = serviceDefService.populateRangerServiceConfigDefToXX(config, xConfig, createdSvcDef, - RangerServiceDefService.OPERATION_CREATE_CONTEXT); - xConfig.setOrder(i); - xConfig = xxServiceConfigDao.create(xConfig); - } - - XXResourceDefDao xxResDefDao = daoMgr.getXXResourceDef(); - for(int i = 0; i < resources.size(); i++) { - RangerResourceDef resource = resources.get(i); - - XXResourceDef parent = xxResDefDao.findByNameAndServiceDefId(resource.getParent(), serviceDefId); - Long parentId = (parent != null) ? parent.getId() : null; - - XXResourceDef xResource = new XXResourceDef(); - xResource = serviceDefService.populateRangerResourceDefToXX(resource, xResource, createdSvcDef, - RangerServiceDefService.OPERATION_CREATE_CONTEXT); - xResource.setOrder(i); - xResource.setParent(parentId); - xResource = xxResDefDao.create(xResource); - } - - XXAccessTypeDefDao xxATDDao = daoMgr.getXXAccessTypeDef(); - for(int i = 0; i < accessTypes.size(); i++) { - RangerAccessTypeDef accessType = accessTypes.get(i); - - XXAccessTypeDef xAccessType = new XXAccessTypeDef(); - xAccessType = serviceDefService.populateRangerAccessTypeDefToXX(accessType, xAccessType, createdSvcDef, - RangerServiceDefService.OPERATION_CREATE_CONTEXT); - xAccessType.setOrder(i); - xAccessType = xxATDDao.create(xAccessType); - - Collection impliedGrants = accessType.getImpliedGrants(); - XXAccessTypeDefGrantsDao xxATDGrantDao = daoMgr.getXXAccessTypeDefGrants(); - for(String impliedGrant : impliedGrants) { - XXAccessTypeDefGrants xImpliedGrant = new XXAccessTypeDefGrants(); - xImpliedGrant.setAtdId(xAccessType.getId()); - xImpliedGrant.setImpliedGrant(impliedGrant); - xImpliedGrant = xxATDGrantDao.create(xImpliedGrant); - } - } - - XXPolicyConditionDefDao xxPolCondDao = daoMgr.getXXPolicyConditionDef(); - for (int i = 0; i < policyConditions.size(); i++) { - RangerPolicyConditionDef policyCondition = policyConditions.get(i); - - XXPolicyConditionDef xPolicyCondition = new XXPolicyConditionDef(); - xPolicyCondition = serviceDefService - .populateRangerPolicyConditionDefToXX(policyCondition, - xPolicyCondition, createdSvcDef, RangerServiceDefService.OPERATION_CREATE_CONTEXT); - xPolicyCondition.setOrder(i); - xPolicyCondition = xxPolCondDao.create(xPolicyCondition); - } - - XXContextEnricherDefDao xxContextEnricherDao = daoMgr.getXXContextEnricherDef(); - for (int i = 0; i < contextEnrichers.size(); i++) { - RangerContextEnricherDef contextEnricher = contextEnrichers.get(i); - - XXContextEnricherDef xContextEnricher = new XXContextEnricherDef(); - xContextEnricher = serviceDefService - .populateRangerContextEnricherDefToXX(contextEnricher, - xContextEnricher, createdSvcDef, RangerServiceDefService.OPERATION_CREATE_CONTEXT); - xContextEnricher.setOrder(i); - xContextEnricher = xxContextEnricherDao.create(xContextEnricher); - } - - XXEnumDefDao xxEnumDefDao = daoMgr.getXXEnumDef(); - for(RangerEnumDef vEnum : enums) { - XXEnumDef xEnum = new XXEnumDef(); - xEnum = serviceDefService.populateRangerEnumDefToXX(vEnum, xEnum, createdSvcDef, RangerServiceDefService.OPERATION_CREATE_CONTEXT); - xEnum = xxEnumDefDao.create(xEnum); - - List elements = vEnum.getElements(); - XXEnumElementDefDao xxEnumEleDefDao = daoMgr.getXXEnumElementDef(); - for(int i = 0; i < elements.size(); i++) { - RangerEnumElementDef element = elements.get(i); - - XXEnumElementDef xElement = new XXEnumElementDef(); - xElement = serviceDefService.populateRangerEnumElementDefToXX(element, xElement, xEnum, RangerServiceDefService.OPERATION_CREATE_CONTEXT); - xElement.setOrder(i); - xElement = xxEnumEleDefDao.create(xElement); - } - } - - XXDataMaskTypeDefDao xxDataMaskDefDao = daoMgr.getXXDataMaskTypeDef(); - for (int i = 0; i < dataMaskTypes.size(); i++) { - RangerDataMaskTypeDef dataMask = dataMaskTypes.get(i); - - XXDataMaskTypeDef xDataMaskDef = new XXDataMaskTypeDef(); - xDataMaskDef = serviceDefService.populateRangerDataMaskDefToXX(dataMask, xDataMaskDef, createdSvcDef, - RangerServiceDefService.OPERATION_CREATE_CONTEXT); - xDataMaskDef.setOrder(i); - xDataMaskDef = xxDataMaskDefDao.create(xDataMaskDef); - } - - List xxAccessTypeDefs = xxATDDao.findByServiceDefId(createdSvcDef.getId()); - - for(RangerAccessTypeDef accessType : dataMaskAccessTypes) { - if(! isAccessTypeInList(accessType.getName(), xxAccessTypeDefs)) { - throw restErrorUtil.createRESTException("accessType with name: " - + accessType.getName() + " does not exists", MessageEnums.DATA_NOT_FOUND); - } - } - - for(RangerAccessTypeDef accessType : rowFilterAccessTypes) { - if(! isAccessTypeInList(accessType.getName(), xxAccessTypeDefs)) { - throw restErrorUtil.createRESTException("accessType with name: " - + accessType.getName() + " does not exists", MessageEnums.DATA_NOT_FOUND); - } - } - - for(XXAccessTypeDef xxAccessTypeDef : xxAccessTypeDefs) { - String dataMaskOptions = null; - String rowFilterOptions = null; - - for(RangerAccessTypeDef accessTypeDef : dataMaskAccessTypes) { - if(StringUtils.equals(accessTypeDef.getName(), xxAccessTypeDef.getName())) { - dataMaskOptions = svcDefServiceWithAssignedId.objectToJson(accessTypeDef); - break; - } - } - - for(RangerAccessTypeDef accessTypeDef : rowFilterAccessTypes) { - if(StringUtils.equals(accessTypeDef.getName(), xxAccessTypeDef.getName())) { - rowFilterOptions = svcDefServiceWithAssignedId.objectToJson(accessTypeDef); - break; - } - } - - if(!StringUtils.equals(dataMaskOptions, xxAccessTypeDef.getDataMaskOptions()) || - !StringUtils.equals(rowFilterOptions, xxAccessTypeDef.getRowFilterOptions())) { - xxAccessTypeDef.setDataMaskOptions(dataMaskOptions); - xxAccessTypeDef.setRowFilterOptions(rowFilterOptions); - - xxATDDao.update(xxAccessTypeDef); - } - } - - List xxResourceDefs = xxResDefDao.findByServiceDefId(createdSvcDef.getId()); - - for(RangerResourceDef resource : dataMaskResources) { - if(! isResourceInList(resource.getName(), xxResourceDefs)) { - throw restErrorUtil.createRESTException("resource with name: " - + resource.getName() + " does not exists", MessageEnums.DATA_NOT_FOUND); - } - } - - for(RangerResourceDef resource : rowFilterResources) { - if(! isResourceInList(resource.getName(), xxResourceDefs)) { - throw restErrorUtil.createRESTException("resource with name: " - + resource.getName() + " does not exists", MessageEnums.DATA_NOT_FOUND); - } - } - - for(XXResourceDef xxResourceDef : xxResourceDefs) { - String dataMaskOptions = null; - String rowFilterOptions = null; - - for(RangerResourceDef resource : dataMaskResources) { - if(StringUtils.equals(resource.getName(), xxResourceDef.getName())) { - dataMaskOptions = svcDefServiceWithAssignedId.objectToJson(resource); - break; - } - } - - for(RangerResourceDef resource : rowFilterResources) { - if(StringUtils.equals(resource.getName(), xxResourceDef.getName())) { - rowFilterOptions = svcDefServiceWithAssignedId.objectToJson(resource); - break; - } - } - - if(!StringUtils.equals(dataMaskOptions, xxResourceDef.getDataMaskOptions()) || - !StringUtils.equals(rowFilterOptions, xxResourceDef.getRowFilterOptions())) { - xxResourceDef.setDataMaskOptions(dataMaskOptions); - xxResourceDef.setRowFilterOptions(rowFilterOptions); - - xxResDefDao.update(xxResourceDef); - } - } - - RangerServiceDef createdServiceDef = serviceDefService.getPopulatedViewObject(createdSvcDef); - dataHistService.createObjectDataHistory(createdServiceDef, RangerDataHistService.ACTION_CREATE); - - postCreate(createdServiceDef); - - if (LOG.isDebugEnabled()) { - LOG.debug("<== ServiceDBStore.createServiceDef(" + serviceDef + "): " + createdServiceDef); - } - - return createdServiceDef; - } - - @Override - public RangerServiceDef updateServiceDef(RangerServiceDef serviceDef) throws Exception { - if (LOG.isDebugEnabled()) { - LOG.debug("==> ServiceDBStore.updateServiceDef(" + serviceDef + ")"); - } - - Long serviceDefId = serviceDef.getId(); - - XXServiceDef existing = daoMgr.getXXServiceDef().getById(serviceDefId); - if (existing == null) { - throw restErrorUtil.createRESTException("no service-def exists with ID=" + serviceDef.getId(), - MessageEnums.DATA_NOT_FOUND); - } - - String existingName = existing.getName(); - - boolean renamed = !StringUtils.equalsIgnoreCase(serviceDef.getName(), existingName); - - if (renamed) { - XXServiceDef renamedSVCDef = daoMgr.getXXServiceDef().findByName(serviceDef.getName()); - - if (renamedSVCDef != null) { - throw restErrorUtil.createRESTException( - "another service-def already exists with name '" + serviceDef.getName() + "'. ID=" - + renamedSVCDef.getId(), MessageEnums.DATA_NOT_UPDATABLE); - } - } - - List configs = serviceDef.getConfigs() != null ? serviceDef.getConfigs() : new ArrayList<>(); - List resources = serviceDef.getResources() != null ? serviceDef.getResources() : new ArrayList<>(); - List accessTypes = serviceDef.getAccessTypes() != null ? serviceDef.getAccessTypes() : new ArrayList<>(); - List policyConditions = serviceDef.getPolicyConditions() != null ? serviceDef.getPolicyConditions() : new ArrayList<>(); - List contextEnrichers = serviceDef.getContextEnrichers() != null ? serviceDef.getContextEnrichers() : new ArrayList<>(); - List enums = serviceDef.getEnums() != null ? serviceDef.getEnums() : new ArrayList<>(); - RangerDataMaskDef dataMaskDef = serviceDef.getDataMaskDef(); - RangerRowFilterDef rowFilterDef = serviceDef.getRowFilterDef(); - - RangerServiceDefHelper defHelper = new RangerServiceDefHelper(serviceDef, false); - defHelper.patchServiceDefWithDefaultValues(); - - serviceDef.setCreateTime(existing.getCreateTime()); - serviceDef.setGuid(existing.getGuid()); - serviceDef.setVersion(existing.getVersion()); - - serviceDef = serviceDefService.update(serviceDef); - XXServiceDef createdSvcDef = daoMgr.getXXServiceDef().getById(serviceDefId); - - updateChildObjectsOfServiceDef(createdSvcDef, configs, resources, accessTypes, policyConditions, contextEnrichers, enums, dataMaskDef, rowFilterDef); - - RangerServiceDef updatedSvcDef = getServiceDef(serviceDefId); - dataHistService.createObjectDataHistory(updatedSvcDef, RangerDataHistService.ACTION_UPDATE); - - postUpdate(updatedSvcDef); - - - if (LOG.isDebugEnabled()) { - LOG.debug("<== ServiceDBStore.updateServiceDef(" + serviceDef + "): " + serviceDef); - } - - return updatedSvcDef; - } - - private void updateChildObjectsOfServiceDef(XXServiceDef createdSvcDef, List configs, - List resources, List accessTypes, - List policyConditions, List contextEnrichers, - List enums, RangerDataMaskDef dataMaskDef, RangerRowFilterDef rowFilterDef) { - - Long serviceDefId = createdSvcDef.getId(); - - List xxConfigs = daoMgr.getXXServiceConfigDef().findByServiceDefId(serviceDefId); - List xxResources = daoMgr.getXXResourceDef().findByServiceDefId(serviceDefId); - List xxAccessTypes = daoMgr.getXXAccessTypeDef().findByServiceDefId(serviceDefId); - List xxPolicyConditions = daoMgr.getXXPolicyConditionDef().findByServiceDefId( - serviceDefId); - List xxContextEnrichers = daoMgr.getXXContextEnricherDef().findByServiceDefId( - serviceDefId); - List xxEnums = daoMgr.getXXEnumDef().findByServiceDefId(serviceDefId); - - XXServiceConfigDefDao xxServiceConfigDao = daoMgr.getXXServiceConfigDef(); - for (int i = 0; i < configs.size(); i++) { - RangerServiceConfigDef config = configs.get(i); - boolean found = false; - for (XXServiceConfigDef xConfig : xxConfigs) { - if (config.getItemId() != null && config.getItemId().equals(xConfig.getItemId())) { - found = true; - xConfig = serviceDefService.populateRangerServiceConfigDefToXX(config, xConfig, createdSvcDef, - RangerServiceDefService.OPERATION_UPDATE_CONTEXT); - xConfig.setOrder(i); - xConfig = xxServiceConfigDao.update(xConfig); - config = serviceDefService.populateXXToRangerServiceConfigDef(xConfig); - break; - } - } - if (!found) { - XXServiceConfigDef xConfig = new XXServiceConfigDef(); - xConfig = serviceDefService.populateRangerServiceConfigDefToXX(config, xConfig, createdSvcDef, - RangerServiceDefService.OPERATION_CREATE_CONTEXT); - xConfig.setOrder(i); - xConfig = xxServiceConfigDao.create(xConfig); - config = serviceDefService.populateXXToRangerServiceConfigDef(xConfig); - } - } - for (XXServiceConfigDef xConfig : xxConfigs) { - boolean found = false; - for (RangerServiceConfigDef config : configs) { - if (xConfig.getItemId() != null && xConfig.getItemId().equals(config.getItemId())) { - found = true; - break; - } - } - if (!found) { - xxServiceConfigDao.remove(xConfig); - } - } - - XXResourceDefDao xxResDefDao = daoMgr.getXXResourceDef(); - for (RangerResourceDef resource : resources) { - boolean found = false; - for (XXResourceDef xRes : xxResources) { - if (resource.getItemId() != null && resource.getItemId().equals(xRes.getItemId())) { - found = true; - xRes = serviceDefService.populateRangerResourceDefToXX(resource, xRes, createdSvcDef, - RangerServiceDefService.OPERATION_UPDATE_CONTEXT); - xxResDefDao.update(xRes); - resource = serviceDefService.populateXXToRangerResourceDef(xRes); - break; - } - } - if (!found) { - XXResourceDef parent = xxResDefDao.findByNameAndServiceDefId(resource.getParent(), serviceDefId); - Long parentId = (parent != null) ? parent.getId() : null; - - XXResourceDef xResource = new XXResourceDef(); - xResource = serviceDefService.populateRangerResourceDefToXX(resource, xResource, createdSvcDef, - RangerServiceDefService.OPERATION_CREATE_CONTEXT); - xResource.setParent(parentId); - xResource = xxResDefDao.create(xResource); - } - } - for (XXResourceDef xRes : xxResources) { - boolean found = false; - for (RangerResourceDef resource : resources) { - if (xRes.getItemId() != null && xRes.getItemId().equals(resource.getItemId())) { - found = true; - break; - } - } - if (!found) { - List xxPolicyRefResource = daoMgr.getXXPolicyRefResource().findByResourceDefID(xRes.getId()); - if (!stringUtil.isEmpty(xxPolicyRefResource)) { - throw restErrorUtil.createRESTException("Policy/Policies are referring to this resource: " - + xRes.getName() + ". Please remove such references from policy before updating service-def.", - MessageEnums.DATA_NOT_UPDATABLE); - } - deleteXXResourceDef(xRes); - } - } - - XXAccessTypeDefDao xxATDDao = daoMgr.getXXAccessTypeDef(); - for(int i = 0; i < accessTypes.size(); i++) { - RangerAccessTypeDef access = accessTypes.get(i); - boolean found = false; - for (XXAccessTypeDef xAccess : xxAccessTypes) { - if (access.getItemId() != null && access.getItemId().equals(xAccess.getItemId())) { - found = true; - xAccess = serviceDefService.populateRangerAccessTypeDefToXX(access, xAccess, createdSvcDef, - RangerServiceDefService.OPERATION_UPDATE_CONTEXT); - xAccess.setOrder(i); - xAccess = xxATDDao.update(xAccess); - - Collection impliedGrants = access.getImpliedGrants(); - XXAccessTypeDefGrantsDao xxATDGrantDao = daoMgr.getXXAccessTypeDefGrants(); - List xxImpliedGrants = xxATDGrantDao.findImpliedGrantsByATDId(xAccess.getId()); - for (String impliedGrant : impliedGrants) { - boolean foundGrant = false; - for (String xImpliedGrant : xxImpliedGrants) { - if (StringUtils.equalsIgnoreCase(impliedGrant, xImpliedGrant)) { - foundGrant = true; - break; - } - } - if (!foundGrant) { - XXAccessTypeDefGrants xImpliedGrant = new XXAccessTypeDefGrants(); - xImpliedGrant.setAtdId(xAccess.getId()); - xImpliedGrant.setImpliedGrant(impliedGrant); - xImpliedGrant = xxATDGrantDao.create(xImpliedGrant); - } - } - for (String xImpliedGrant : xxImpliedGrants) { - boolean foundGrant = false; - for (String impliedGrant : impliedGrants) { - if (StringUtils.equalsIgnoreCase(xImpliedGrant, impliedGrant)) { - foundGrant = true; - break; - } - } - if (!foundGrant) { - XXAccessTypeDefGrants xATDGrant = xxATDGrantDao.findByNameAndATDId(xAccess.getId(), - xImpliedGrant); - xxATDGrantDao.remove(xATDGrant); - - } - } - access = serviceDefService.populateXXToRangerAccessTypeDef(xAccess); - break; - } - } - if (!found) { - XXAccessTypeDef xAccessType = new XXAccessTypeDef(); - xAccessType = serviceDefService.populateRangerAccessTypeDefToXX(access, xAccessType, createdSvcDef, - RangerServiceDefService.OPERATION_CREATE_CONTEXT); - xAccessType.setOrder(i); - xAccessType = xxATDDao.create(xAccessType); - - Collection impliedGrants = access.getImpliedGrants(); - XXAccessTypeDefGrantsDao xxATDGrantDao = daoMgr.getXXAccessTypeDefGrants(); - for (String impliedGrant : impliedGrants) { - XXAccessTypeDefGrants xImpliedGrant = new XXAccessTypeDefGrants(); - xImpliedGrant.setAtdId(xAccessType.getId()); - xImpliedGrant.setImpliedGrant(impliedGrant); - xImpliedGrant = xxATDGrantDao.create(xImpliedGrant); - } - access = serviceDefService.populateXXToRangerAccessTypeDef(xAccessType); - } - } - - for (XXAccessTypeDef xAccess : xxAccessTypes) { - boolean found = false; - for (RangerAccessTypeDef access : accessTypes) { - if (xAccess.getItemId() != null && xAccess.getItemId().equals(access.getItemId())) { - found = true; - break; - } - } - if (!found) { - List policyRefAccessTypeList = daoMgr.getXXPolicyRefAccessType().findByAccessTypeDefId(xAccess.getId()); - if(!stringUtil.isEmpty(policyRefAccessTypeList)) { - throw restErrorUtil.createRESTException("Policy/Policies are referring to this access-type: " - + xAccess.getName() + ". Please remove such references from policy before updating service-def.", - MessageEnums.DATA_NOT_UPDATABLE); - } - deleteXXAccessTypeDef(xAccess); - } - } - - XXPolicyConditionDefDao xxPolCondDao = daoMgr.getXXPolicyConditionDef(); - for (int i = 0; i < policyConditions.size(); i++) { - RangerPolicyConditionDef condition = policyConditions.get(i); - boolean found = false; - for (XXPolicyConditionDef xCondition : xxPolicyConditions) { - if (condition.getItemId() != null && condition.getItemId().equals(xCondition.getItemId())) { - found = true; - xCondition = serviceDefService.populateRangerPolicyConditionDefToXX(condition, xCondition, - createdSvcDef, RangerServiceDefService.OPERATION_UPDATE_CONTEXT); - xCondition.setOrder(i); - xCondition = xxPolCondDao.update(xCondition); - condition = serviceDefService.populateXXToRangerPolicyConditionDef(xCondition); - break; - } - } - if (!found) { - XXPolicyConditionDef xCondition = new XXPolicyConditionDef(); - xCondition = serviceDefService.populateRangerPolicyConditionDefToXX(condition, xCondition, - createdSvcDef, RangerServiceDefService.OPERATION_CREATE_CONTEXT); - xCondition.setOrder(i); - xCondition = xxPolCondDao.create(xCondition); - condition = serviceDefService.populateXXToRangerPolicyConditionDef(xCondition); - } - } - for(XXPolicyConditionDef xCondition : xxPolicyConditions) { - boolean found = false; - for(RangerPolicyConditionDef condition : policyConditions) { - if(xCondition.getItemId() != null && xCondition.getItemId().equals(condition.getItemId())) { - found = true; - break; - } - } - if(!found) { - List xxPolicyRefConditions = daoMgr.getXXPolicyRefCondition().findByConditionDefId(xCondition.getId()); - if(!stringUtil.isEmpty(xxPolicyRefConditions)) { - throw restErrorUtil.createRESTException("Policy/Policies are referring to this policy-condition: " - + xCondition.getName() + ". Please remove such references from policy before updating service-def.", - MessageEnums.DATA_NOT_UPDATABLE); - } - for(XXPolicyRefCondition xxPolicyRefCondition : xxPolicyRefConditions) { - daoMgr.getXXPolicyRefCondition().remove(xxPolicyRefCondition); - } - xxPolCondDao.remove(xCondition); - } - } - - XXContextEnricherDefDao xxContextEnricherDao = daoMgr.getXXContextEnricherDef(); - for (int i = 0; i < contextEnrichers.size(); i++) { - RangerContextEnricherDef context = contextEnrichers.get(i); - boolean found = false; - for (XXContextEnricherDef xContext : xxContextEnrichers) { - if (context.getItemId() != null && context.getItemId().equals(xContext.getItemId())) { - found = true; - xContext = serviceDefService.populateRangerContextEnricherDefToXX(context, xContext, createdSvcDef, - RangerServiceDefService.OPERATION_UPDATE_CONTEXT); - xContext.setOrder(i); - xContext = xxContextEnricherDao.update(xContext); - context = serviceDefService.populateXXToRangerContextEnricherDef(xContext); - break; - } - } - if (!found) { - XXContextEnricherDef xContext = new XXContextEnricherDef(); - xContext = serviceDefService.populateRangerContextEnricherDefToXX(context, xContext, createdSvcDef, - RangerServiceDefService.OPERATION_UPDATE_CONTEXT); - xContext.setOrder(i); - xContext = xxContextEnricherDao.create(xContext); - context = serviceDefService.populateXXToRangerContextEnricherDef(xContext); - } - } - for (XXContextEnricherDef xContext : xxContextEnrichers) { - boolean found = false; - for (RangerContextEnricherDef context : contextEnrichers) { - if (xContext.getItemId() != null && xContext.getItemId().equals(context.getItemId())) { - found = true; - break; - } - } - if (!found) { - daoMgr.getXXContextEnricherDef().remove(xContext); - } - } - - XXEnumDefDao xxEnumDefDao = daoMgr.getXXEnumDef(); - for (RangerEnumDef enumDef : enums) { - boolean found = false; - for (XXEnumDef xEnumDef : xxEnums) { - if (enumDef.getItemId() != null && enumDef.getItemId().equals(xEnumDef.getItemId())) { - found = true; - xEnumDef = serviceDefService.populateRangerEnumDefToXX(enumDef, xEnumDef, createdSvcDef, - RangerServiceDefService.OPERATION_UPDATE_CONTEXT); - xEnumDef = xxEnumDefDao.update(xEnumDef); - - XXEnumElementDefDao xEnumEleDao = daoMgr.getXXEnumElementDef(); - List xxEnumEleDefs = xEnumEleDao.findByEnumDefId(xEnumDef.getId()); - List enumEleDefs = enumDef.getElements(); - - for (int i = 0; i < enumEleDefs.size(); i++) { - RangerEnumElementDef eleDef = enumEleDefs.get(i); - boolean foundEle = false; - for (XXEnumElementDef xEleDef : xxEnumEleDefs) { - if (eleDef.getItemId() != null && eleDef.getItemId().equals(xEleDef.getItemId())) { - foundEle = true; - xEleDef = serviceDefService.populateRangerEnumElementDefToXX(eleDef, xEleDef, xEnumDef, - RangerServiceDefService.OPERATION_UPDATE_CONTEXT); - xEleDef.setOrder(i); - xEleDef = xEnumEleDao.update(xEleDef); - break; - } - } - if (!foundEle) { - XXEnumElementDef xElement = new XXEnumElementDef(); - xElement = serviceDefService.populateRangerEnumElementDefToXX(eleDef, xElement, xEnumDef, - RangerServiceDefService.OPERATION_CREATE_CONTEXT); - xElement.setOrder(i); - xElement = xEnumEleDao.create(xElement); - } - } - for (XXEnumElementDef xxEleDef : xxEnumEleDefs) { - boolean foundEle = false; - for (RangerEnumElementDef enumEle : enumEleDefs) { - if (xxEleDef.getItemId() != null && xxEleDef.getItemId().equals(enumEle.getItemId())) { - foundEle = true; - break; - } - } - if (!foundEle) { - xEnumEleDao.remove(xxEleDef); - } - } - enumDef = serviceDefService.populateXXToRangerEnumDef(xEnumDef); - break; - } - } - if (!found) { - XXEnumDef xEnum = new XXEnumDef(); - xEnum = serviceDefService.populateRangerEnumDefToXX(enumDef, xEnum, createdSvcDef, - RangerServiceDefService.OPERATION_CREATE_CONTEXT); - xEnum = xxEnumDefDao.create(xEnum); - - List elements = enumDef.getElements(); - XXEnumElementDefDao xxEnumEleDefDao = daoMgr.getXXEnumElementDef(); - for (RangerEnumElementDef element : elements) { - XXEnumElementDef xElement = new XXEnumElementDef(); - xElement = serviceDefService.populateRangerEnumElementDefToXX(element, xElement, xEnum, - RangerServiceDefService.OPERATION_CREATE_CONTEXT); - xElement = xxEnumEleDefDao.create(xElement); - } - enumDef = serviceDefService.populateXXToRangerEnumDef(xEnum); - } - } - for (XXEnumDef xEnumDef : xxEnums) { - boolean found = false; - for (RangerEnumDef enumDef : enums) { - if (xEnumDef.getItemId() != null && xEnumDef.getItemId().equals(enumDef.getItemId())) { - found = true; - break; - } - } - if (!found) { - List enumEleDefList = daoMgr.getXXEnumElementDef().findByEnumDefId(xEnumDef.getId()); - for (XXEnumElementDef eleDef : enumEleDefList) { - daoMgr.getXXEnumElementDef().remove(eleDef); - } - xxEnumDefDao.remove(xEnumDef); - } - } - - List dataMasks = dataMaskDef == null || dataMaskDef.getMaskTypes() == null ? new ArrayList() : dataMaskDef.getMaskTypes(); - List dataMaskAccessTypes = dataMaskDef == null || dataMaskDef.getAccessTypes() == null ? new ArrayList() : dataMaskDef.getAccessTypes(); - List dataMaskResources = dataMaskDef == null || dataMaskDef.getResources() == null ? new ArrayList() : dataMaskDef.getResources(); - List rowFilterAccessTypes = rowFilterDef == null || rowFilterDef.getAccessTypes() == null ? new ArrayList() : rowFilterDef.getAccessTypes(); - List rowFilterResources = rowFilterDef == null || rowFilterDef.getResources() == null ? new ArrayList() : rowFilterDef.getResources(); - XXDataMaskTypeDefDao dataMaskTypeDao = daoMgr.getXXDataMaskTypeDef(); - List xxDataMaskTypes = dataMaskTypeDao.findByServiceDefId(serviceDefId); - List xxAccessTypeDefs = xxATDDao.findByServiceDefId(serviceDefId); - List xxResourceDefs = xxResDefDao.findByServiceDefId(serviceDefId); - - // create or update dataMasks - for(int i = 0; i < dataMasks.size(); i++) { - RangerDataMaskTypeDef dataMask = dataMasks.get(i); - boolean found = false; - for (XXDataMaskTypeDef xxDataMask : xxDataMaskTypes) { - if (xxDataMask.getItemId() != null && xxDataMask.getItemId().equals(dataMask.getItemId())) { - if (LOG.isDebugEnabled()) { - LOG.debug("Updating existing dataMask with itemId=" + dataMask.getItemId()); - } - - found = true; - xxDataMask = serviceDefService.populateRangerDataMaskDefToXX(dataMask, xxDataMask, createdSvcDef, - RangerServiceDefService.OPERATION_UPDATE_CONTEXT); - xxDataMask.setOrder(i); - xxDataMask = dataMaskTypeDao.update(xxDataMask); - dataMask = serviceDefService.populateXXToRangerDataMaskTypeDef(xxDataMask); - break; - } - } - - if (!found) { - if (LOG.isDebugEnabled()) { - LOG.debug("Creating dataMask with itemId=" + dataMask.getItemId() + ""); - } - - XXDataMaskTypeDef xxDataMask = new XXDataMaskTypeDef(); - xxDataMask = serviceDefService.populateRangerDataMaskDefToXX(dataMask, xxDataMask, createdSvcDef, RangerServiceDefService.OPERATION_CREATE_CONTEXT); - xxDataMask.setOrder(i); - xxDataMask = dataMaskTypeDao.create(xxDataMask); - } - } - - // remove dataMasks - for (XXDataMaskTypeDef xxDataMask : xxDataMaskTypes) { - boolean found = false; - for (RangerDataMaskTypeDef dataMask : dataMasks) { - if (xxDataMask.getItemId() != null && xxDataMask.getItemId().equals(dataMask.getItemId())) { - found = true; - break; - } - } - if (!found) { - if(LOG.isDebugEnabled()) { - LOG.debug("Deleting dataMask with itemId=" + xxDataMask.getItemId()); - } - - dataMaskTypeDao.remove(xxDataMask); - } - } - - for(RangerAccessTypeDef accessType : dataMaskAccessTypes) { - if(! isAccessTypeInList(accessType.getName(), xxAccessTypeDefs)) { - throw restErrorUtil.createRESTException("accessType with name: " - + accessType.getName() + " does not exist", MessageEnums.DATA_NOT_FOUND); - } - } - - for(RangerAccessTypeDef accessType : rowFilterAccessTypes) { - if(! isAccessTypeInList(accessType.getName(), xxAccessTypeDefs)) { - throw restErrorUtil.createRESTException("accessType with name: " - + accessType.getName() + " does not exists", MessageEnums.DATA_NOT_FOUND); - } - } - - for(XXAccessTypeDef xxAccessTypeDef : xxAccessTypeDefs) { - String dataMaskOptions = null; - String rowFilterOptions = null; - - for(RangerAccessTypeDef accessTypeDef : dataMaskAccessTypes) { - if(StringUtils.equals(accessTypeDef.getName(), xxAccessTypeDef.getName())) { - dataMaskOptions = svcDefServiceWithAssignedId.objectToJson(accessTypeDef); - break; - } - } - - for(RangerAccessTypeDef accessTypeDef : rowFilterAccessTypes) { - if(StringUtils.equals(accessTypeDef.getName(), xxAccessTypeDef.getName())) { - rowFilterOptions = svcDefServiceWithAssignedId.objectToJson(accessTypeDef); - break; - } - } - - if(!StringUtils.equals(dataMaskOptions, xxAccessTypeDef.getDataMaskOptions()) || - !StringUtils.equals(rowFilterOptions, xxAccessTypeDef.getRowFilterOptions())) { - xxAccessTypeDef.setDataMaskOptions(dataMaskOptions); - xxAccessTypeDef.setRowFilterOptions(rowFilterOptions); - xxATDDao.update(xxAccessTypeDef); - } - } - - for(RangerResourceDef resource : dataMaskResources) { - if(! isResourceInList(resource.getName(), xxResourceDefs)) { - throw restErrorUtil.createRESTException("resource with name: " - + resource.getName() + " does not exists", MessageEnums.DATA_NOT_FOUND); - } - } - - for(RangerResourceDef resource : rowFilterResources) { - if(! isResourceInList(resource.getName(), xxResourceDefs)) { - throw restErrorUtil.createRESTException("resource with name: " - + resource.getName() + " does not exists", MessageEnums.DATA_NOT_FOUND); - } - } - - for(XXResourceDef xxResourceDef : xxResourceDefs) { - String dataMaskOptions = null; - String rowFilterOptions = null; - - for(RangerResourceDef resource : dataMaskResources) { - if(StringUtils.equals(resource.getName(), xxResourceDef.getName())) { - dataMaskOptions = svcDefServiceWithAssignedId.objectToJson(resource); - break; - } - } - - for(RangerResourceDef resource : rowFilterResources) { - if(StringUtils.equals(resource.getName(), xxResourceDef.getName())) { - rowFilterOptions = svcDefServiceWithAssignedId.objectToJson(resource); - break; - } - } - - if(!StringUtils.equals(dataMaskOptions, xxResourceDef.getDataMaskOptions()) || - !StringUtils.equals(rowFilterOptions, xxResourceDef.getRowFilterOptions())) { - xxResourceDef.setDataMaskOptions(dataMaskOptions); - xxResourceDef.setRowFilterOptions(rowFilterOptions); - xxResDefDao.update(xxResourceDef); - } - } - } - - public void deleteServiceDef(Long serviceDefId, Boolean forceDelete) throws Exception { - if (LOG.isDebugEnabled()) { - LOG.debug("==> ServiceDBStore.deleteServiceDef(" + serviceDefId + ", " + forceDelete + ")"); - } - bizUtil.blockAuditorRoleUser(); - UserSessionBase session = ContextUtil.getCurrentUserSession(); - if (session == null) { - throw restErrorUtil.createRESTException( - "UserSession cannot be null, only Admin can update service-def", - MessageEnums.OPER_NO_PERMISSION); - } - - if (!session.isKeyAdmin() && !session.isUserAdmin()) { - throw restErrorUtil.createRESTException( - "User is not allowed to update service-def, only Admin can update service-def", - MessageEnums.OPER_NO_PERMISSION); - } - - RangerServiceDef serviceDef = getServiceDef(serviceDefId); - if(serviceDef == null) { - throw restErrorUtil.createRESTException("No Service Definiton found for Id: " + serviceDefId, - MessageEnums.DATA_NOT_FOUND); - } - - List serviceList = daoMgr.getXXService().findByServiceDefId(serviceDefId); - if (!forceDelete) { - if(CollectionUtils.isNotEmpty(serviceList)) { - throw restErrorUtil.createRESTException( - "Services exists under given service definition, can't delete Service-Def: " - + serviceDef.getName(), MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY); - } - } - - if(CollectionUtils.isNotEmpty(serviceList)) { - for(XXService service : serviceList) { - deleteService(service.getId()); - } - } - - XXDataMaskTypeDefDao dataMaskDao = daoMgr.getXXDataMaskTypeDef(); - List dataMaskDefs = dataMaskDao.findByServiceDefId(serviceDefId); - for(XXDataMaskTypeDef dataMaskDef : dataMaskDefs) { - dataMaskDao.remove(dataMaskDef); - } - - List accTypeDefs = daoMgr.getXXAccessTypeDef().findByServiceDefId(serviceDefId); - for(XXAccessTypeDef accessType : accTypeDefs) { - deleteXXAccessTypeDef(accessType); - } - - XXContextEnricherDefDao xContextEnricherDao = daoMgr.getXXContextEnricherDef(); - List contextEnrichers = xContextEnricherDao.findByServiceDefId(serviceDefId); - for(XXContextEnricherDef context : contextEnrichers) { - xContextEnricherDao.remove(context); - } - - XXEnumDefDao enumDefDao = daoMgr.getXXEnumDef(); - List enumDefList = enumDefDao.findByServiceDefId(serviceDefId); - for (XXEnumDef enumDef : enumDefList) { - List enumEleDefList = daoMgr.getXXEnumElementDef().findByEnumDefId(enumDef.getId()); - for (XXEnumElementDef eleDef : enumEleDefList) { - daoMgr.getXXEnumElementDef().remove(eleDef); - } - enumDefDao.remove(enumDef); - } - - XXPolicyConditionDefDao policyCondDao = daoMgr.getXXPolicyConditionDef(); - List policyCondList = policyCondDao.findByServiceDefId(serviceDefId); - - for (XXPolicyConditionDef policyCond : policyCondList) { - List xxPolicyRefConditions = daoMgr.getXXPolicyRefCondition().findByConditionDefId(policyCond.getId()); - for (XXPolicyRefCondition XXPolicyRefCondition : xxPolicyRefConditions) { - daoMgr.getXXPolicyRefCondition().remove(XXPolicyRefCondition); - } - policyCondDao.remove(policyCond); - } - - List resDefList = daoMgr.getXXResourceDef().findByServiceDefId(serviceDefId); - for(XXResourceDef resDef : resDefList) { - deleteXXResourceDef(resDef); - } - - XXServiceConfigDefDao configDefDao = daoMgr.getXXServiceConfigDef(); - List configDefList = configDefDao.findByServiceDefId(serviceDefId); - for(XXServiceConfigDef configDef : configDefList) { - configDefDao.remove(configDef); - } - - Long version = serviceDef.getVersion(); - if(version == null) { - version = Long.valueOf(1); - LOG.info("Found Version Value: `null`, so setting value of version to 1, While updating object, version should not be null."); - } else { - version = Long.valueOf(version.longValue() + 1); - } - serviceDef.setVersion(version); - - serviceDefService.delete(serviceDef); - LOG.info("ServiceDefinition has been deleted successfully. Service-Def Name: " + serviceDef.getName()); - - dataHistService.createObjectDataHistory(serviceDef, RangerDataHistService.ACTION_DELETE); - - postDelete(serviceDef); - - if (LOG.isDebugEnabled()) { - LOG.debug("<== ServiceDBStore.deleteServiceDef(" + serviceDefId + ", " + forceDelete + ")"); - } - } - - public void deleteXXAccessTypeDef(XXAccessTypeDef xAccess) { - List atdGrantsList = daoMgr.getXXAccessTypeDefGrants().findByATDId(xAccess.getId()); - - for (XXAccessTypeDefGrants atdGrant : atdGrantsList) { - daoMgr.getXXAccessTypeDefGrants().remove(atdGrant); - } - - List policyRefAccessTypeList = daoMgr.getXXPolicyRefAccessType().findByAccessTypeDefId(xAccess.getId()); - for (XXPolicyRefAccessType xxPolicyRefAccessType : policyRefAccessTypeList) { - daoMgr.getXXPolicyRefAccessType().remove(xxPolicyRefAccessType); - } - daoMgr.getXXAccessTypeDef().remove(xAccess); - } - - public void deleteXXResourceDef(XXResourceDef xRes) { - List xChildObjs = daoMgr.getXXResourceDef().findByParentResId(xRes.getId()); - for(XXResourceDef childRes : xChildObjs) { - deleteXXResourceDef(childRes); - } - List xxPolicyRefResources = daoMgr.getXXPolicyRefResource().findByResourceDefID(xRes.getId()); - for (XXPolicyRefResource xPolRefRes : xxPolicyRefResources) { - daoMgr.getXXPolicyRefResource().remove(xPolRefRes); - } - daoMgr.getXXResourceDef().remove(xRes); - } - - @Override - public RangerServiceDef getServiceDef(Long id) throws Exception { - if (LOG.isDebugEnabled()) { - LOG.debug("==> ServiceDBStore.getServiceDef(" + id + ")"); - } - - RangerServiceDef ret = serviceDefService.read(id); - if (LOG.isDebugEnabled()) { - LOG.debug("<== ServiceDBStore.getServiceDef(" + id + "): " + ret); - } - - return ret; - } - - @Override - public RangerServiceDef getServiceDefByName(String name) throws Exception { - if (LOG.isDebugEnabled()) { - LOG.debug("==> ServiceDBStore.getServiceDefByName(" + name + ")"); - } - - RangerServiceDef ret = null; - - XXServiceDef xServiceDef = daoMgr.getXXServiceDef().findByName(name); - - if(xServiceDef != null) { - ret = serviceDefService.getPopulatedViewObject(xServiceDef); - } - - if (LOG.isDebugEnabled()) { - LOG.debug("== ServiceDBStore.getServiceDefByName(" + name + "): " ); - } - - return ret; - } - - /** - * @param displayName - * @return {@link RangerServiceDef} - service using display name if present in DB, null otherwise. - */ - @Override - public RangerServiceDef getServiceDefByDisplayName(String displayName) throws Exception { - if (LOG.isDebugEnabled()) { - LOG.debug("==> ServiceDBStore.getServiceDefByDisplayName(" + displayName + ")"); - } - - RangerServiceDef ret = null; - - XXServiceDef xServiceDef = daoMgr.getXXServiceDef().findByDisplayName(displayName); - - if(xServiceDef != null) { - ret = serviceDefService.getPopulatedViewObject(xServiceDef); - } - - if (LOG.isDebugEnabled()) { - LOG.debug("== ServiceDBStore.getServiceDefByName(" + displayName + "): " + ret); - } - - return ret; - } - - @Override - public List getServiceDefs(SearchFilter filter) throws Exception { - if (LOG.isDebugEnabled()) { - LOG.debug("==> ServiceDBStore.getServiceDefs(" + filter + ")"); - } - - RangerServiceDefList svcDefList = serviceDefService.searchRangerServiceDefs(filter); - - predicateUtil.applyFilter(svcDefList.getServiceDefs(), filter); - - List ret = svcDefList.getServiceDefs(); - - if (LOG.isDebugEnabled()) { - LOG.debug("==> ServiceDBStore.getServiceDefs(" + filter + "): " + ret); - } - - return ret; - } - - @Override - - public PList getPaginatedServiceDefs(SearchFilter filter) throws Exception { - if (LOG.isDebugEnabled()) { - LOG.debug("==> ServiceDBStore.getPaginatedServiceDefs(" + filter + ")"); - } - - RangerServiceDefList svcDefList = serviceDefService.searchRangerServiceDefs(filter); - - predicateUtil.applyFilter(svcDefList.getServiceDefs(), filter); - - if (LOG.isDebugEnabled()) { - LOG.debug("==> ServiceDBStore.getPaginatedServiceDefs(" + filter + ")"); - } - - return new PList(svcDefList.getServiceDefs(), svcDefList.getStartIndex(), svcDefList.getPageSize(), svcDefList.getTotalCount(), - svcDefList.getResultSize(), svcDefList.getSortType(), svcDefList.getSortBy()); - - } - public List findAllServiceDefNamesHavingContextEnrichers() { - return daoMgr.getXXServiceDef().findAllHavingEnrichers(); - } - - @Override - public RangerService createService(RangerService service) throws Exception { - if (LOG.isDebugEnabled()) { - LOG.debug("==> ServiceDBStore.createService(" + service + ")"); - } - - if (service == null) { - throw restErrorUtil.createRESTException("Service object cannot be null.", - MessageEnums.ERROR_CREATING_OBJECT); - } - - boolean createDefaultPolicy = true; - Map configs = service.getConfigs(); - Map validConfigs = validateRequiredConfigParams(service, configs); - if (validConfigs == null) { - if (LOG.isDebugEnabled()) { - LOG.debug("==> ConfigParams cannot be null, ServiceDBStore.createService(" + service + ")"); - } - throw restErrorUtil.createRESTException("ConfigParams cannot be null.", MessageEnums.ERROR_CREATING_OBJECT); - } - - // While creating, value of version should be 1. - service.setVersion(Long.valueOf(1)); - service.setTagVersion(Long.valueOf(1)); - - if (populateExistingBaseFields) { - svcServiceWithAssignedId.setPopulateExistingBaseFields(true); - daoMgr.getXXService().setIdentityInsert(true); - - service = svcServiceWithAssignedId.create(service); - - daoMgr.getXXService().setIdentityInsert(false); - daoMgr.getXXService().updateSequence(); - svcServiceWithAssignedId.setPopulateExistingBaseFields(false); - createDefaultPolicy = false; - } else { - service = svcService.create(service); - } - XXService xCreatedService = daoMgr.getXXService().getById(service.getId()); - - XXServiceConfigMapDao xConfMapDao = daoMgr.getXXServiceConfigMap(); - for (Entry configMap : validConfigs.entrySet()) { - String configKey = configMap.getKey(); - String configValue = configMap.getValue(); - - if (StringUtils.equalsIgnoreCase(configKey, "username")) { - String userName = stringUtil.getValidUserName(configValue); - XXUser xxUser = daoMgr.getXXUser().findByUserName(userName); - if (xxUser != null) { - VXUser vXUser = xUserService.populateViewBean(xxUser); - } else { - UserSessionBase usb = ContextUtil.getCurrentUserSession(); - if (usb != null && !usb.isUserAdmin() && !usb.isSpnegoEnabled()) { - throw restErrorUtil.createRESTException("User does not exist with given username: [" - + userName + "] please use existing user", MessageEnums.OPER_NO_PERMISSION); - } - xUserMgr.createServiceConfigUser(userName); - } - } - - if (StringUtils.equalsIgnoreCase(configKey, CONFIG_KEY_PASSWORD)) { - Joiner joiner = Joiner.on(",").skipNulls(); - String iv = PasswordUtils.generateIvIfNeeded(CRYPT_ALGO); - - String cryptConfigString = joiner.join(CRYPT_ALGO, ENCRYPT_KEY, SALT, ITERATION_COUNT, iv, configValue); - String encryptedPwd = PasswordUtils.encryptPassword(cryptConfigString); - - String paddedEncryptedPwd = joiner.join(CRYPT_ALGO, ENCRYPT_KEY, SALT, ITERATION_COUNT, iv, - encryptedPwd); - String decryptedPwd = PasswordUtils.decryptPassword(paddedEncryptedPwd); - if (StringUtils.equals(decryptedPwd, configValue)) { - configValue = paddedEncryptedPwd; - } - } - XXServiceConfigMap xConfMap = new XXServiceConfigMap(); - xConfMap = rangerAuditFields.populateAuditFields(xConfMap, xCreatedService); - xConfMap.setServiceId(xCreatedService.getId()); - xConfMap.setConfigkey(configKey); - if (StringUtils.equalsIgnoreCase(configKey, "username")) { - configValue = stringUtil.getValidUserName(configValue); - } - xConfMap.setConfigvalue(configValue); - xConfMap = xConfMapDao.create(xConfMap); - } - updateTabPermissions(service.getType(), validConfigs); + RangerServiceDefHelper defHelper = new RangerServiceDefHelper(serviceDef, false); - RangerService createdService = svcService.getPopulatedViewObject(xCreatedService); + defHelper.patchServiceDefWithDefaultValues(); - if (createdService == null) { - throw restErrorUtil.createRESTException("Could not create service - Internal error ", MessageEnums.ERROR_CREATING_OBJECT); - } + // While creating, value of version should be 1. + serviceDef.setVersion(1L); - dataHistService.createObjectDataHistory(createdService, RangerDataHistService.ACTION_CREATE); + if (populateExistingBaseFields) { + svcDefServiceWithAssignedId.setPopulateExistingBaseFields(true); - svcService.createTransactionLog(createdService, null, RangerServiceService.OPERATION_CREATE_CONTEXT); + daoMgr.getXXServiceDef().setIdentityInsert(true); - if (createDefaultPolicy) { - createDefaultPolicies(createdService); - } + svcDefServiceWithAssignedId.create(serviceDef); - return createdService; + svcDefServiceWithAssignedId.setPopulateExistingBaseFields(false); - } + daoMgr.getXXServiceDef().updateSequence(); + daoMgr.getXXServiceDef().setIdentityInsert(false); + } else { + // following fields will be auto populated + serviceDef.setId(null); + serviceDef.setCreateTime(null); + serviceDef.setUpdateTime(null); - @Override - public RangerService updateService(RangerService service, Map options) throws Exception { - if(LOG.isDebugEnabled()) { - LOG.debug("==> ServiceDBStore.updateService()"); - } + serviceDef = serviceDefService.create(serviceDef); + } - XXService xExisting = daoMgr.getXXService().getById(service.getId()); + Long serviceDefId = serviceDef.getId(); + XXServiceDef createdSvcDef = daoMgr.getXXServiceDef().getById(serviceDefId); + XXServiceConfigDefDao xxServiceConfigDao = daoMgr.getXXServiceConfigDef(); - if(xExisting == null) { - throw restErrorUtil.createRESTException( - "no service exists with ID=" + service.getId(), - MessageEnums.DATA_NOT_FOUND); - } + for (int i = 0; i < configs.size(); i++) { + RangerServiceConfigDef config = configs.get(i); + XXServiceConfigDef xConfig = new XXServiceConfigDef(); - RangerService existing = svcService.getPopulatedViewObject(xExisting); + xConfig = serviceDefService.populateRangerServiceConfigDefToXX(config, xConfig, createdSvcDef, RangerServiceDefService.OPERATION_CREATE_CONTEXT); - String existingName = existing.getName(); + xConfig.setOrder(i); - boolean renamed = !StringUtils.equalsIgnoreCase(service.getName(), existingName); + xxServiceConfigDao.create(xConfig); + } - if(renamed) { - XXService newNameService = daoMgr.getXXService().findByName(service.getName()); + XXResourceDefDao xxResDefDao = daoMgr.getXXResourceDef(); - if (newNameService != null) { - throw restErrorUtil.createRESTException("another service already exists with name '" - + service.getName() + "'. ID=" + newNameService.getId(), MessageEnums.DATA_NOT_UPDATABLE); - } + for (int i = 0; i < resources.size(); i++) { + RangerResourceDef resource = resources.get(i); + XXResourceDef parent = xxResDefDao.findByNameAndServiceDefId(resource.getParent(), serviceDefId); + Long parentId = (parent != null) ? parent.getId() : null; + XXResourceDef xResource = new XXResourceDef(); - long countOfTaggedResources = daoMgr.getXXServiceResource().countTaggedResourcesInServiceId(existing.getId()); + xResource = serviceDefService.populateRangerResourceDefToXX(resource, xResource, createdSvcDef, RangerServiceDefService.OPERATION_CREATE_CONTEXT); - Boolean isForceRename = options != null && options.get(ServiceStore.OPTION_FORCE_RENAME) != null ? (Boolean) options.get(ServiceStore.OPTION_FORCE_RENAME) : Boolean.FALSE; + xResource.setOrder(i); + xResource.setParent(parentId); - if (countOfTaggedResources != 0L) { - if (isForceRename) { - LOG.warn("Forcing the renaming of service from " + existingName + " to " + service.getName() + " although it is associated with " + countOfTaggedResources - + " service-resources!"); - } else { - throw restErrorUtil.createRESTException("Service " + existingName + " cannot be renamed, as it has associated service-resources", MessageEnums.DATA_NOT_UPDATABLE); - } - } + xxResDefDao.create(xResource); } - Map configs = service.getConfigs(); - Map validConfigs = validateRequiredConfigParams(service, configs); - if (validConfigs == null) { - if (LOG.isDebugEnabled()) { - LOG.debug("==> ConfigParams cannot be null, ServiceDBStore.createService(" + service + ")"); - } - throw restErrorUtil.createRESTException("ConfigParams cannot be null.", MessageEnums.ERROR_CREATING_OBJECT); - } - - boolean hasTagServiceValueChanged = false; - String existingTagService = existing.getTagService(); - String newTagServiceName = service.getTagService(); // null for old clients; empty string to remove existing association - Long newTagServiceId = null; - - if(newTagServiceName == null) { // old client; don't update existing tagService - if(existingTagService != null) { - newTagServiceName = existingTagService; - - service.setTagService(newTagServiceName); - - LOG.info("ServiceDBStore.updateService(id=" + service.getId() + "; name=" + service.getName() + "): tagService is null; using existing tagService '" + newTagServiceName + "'"); - } - } - - if (StringUtils.isNotBlank(newTagServiceName)) { - RangerService tmp = getServiceByName(newTagServiceName); - - if (tmp == null || !EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_TAG_NAME.equals(tmp.getType())) { - if (LOG.isDebugEnabled()) { - LOG.debug("ServiceDBStore.updateService() - " + newTagServiceName + " does not refer to a valid tag service.(" + service + ")"); - } - throw restErrorUtil.createRESTException("Invalid tag service name " + newTagServiceName, MessageEnums.ERROR_CREATING_OBJECT); - - } else { - newTagServiceId = tmp.getId(); - } - } - - if (existingTagService == null) { - if (newTagServiceId != null) { - hasTagServiceValueChanged = true; - } - } else if (!existingTagService.equals(newTagServiceName)) { - hasTagServiceValueChanged = true; - } - - boolean hasIsEnabledChanged = !existing.getIsEnabled().equals(service.getIsEnabled()); - - List dbConfigMaps = daoMgr.getXXServiceConfigMap().findByServiceId(service.getId()); - boolean hasServiceConfigForPluginChanged = hasServiceConfigForPluginChanged(dbConfigMaps, validConfigs); - - svcService.createTransactionLog(service, existing, RangerServiceService.OPERATION_UPDATE_CONTEXT); - - if(populateExistingBaseFields) { - svcServiceWithAssignedId.setPopulateExistingBaseFields(true); - service = svcServiceWithAssignedId.update(service); - svcServiceWithAssignedId.setPopulateExistingBaseFields(false); - } else { - service.setCreateTime(existing.getCreateTime()); - service.setGuid(existing.getGuid()); - service.setVersion(existing.getVersion()); - service = svcService.update(service); - - if (hasTagServiceValueChanged || hasIsEnabledChanged || hasServiceConfigForPluginChanged) { - updatePolicyVersion(service, RangerPolicyDelta.CHANGE_TYPE_SERVICE_CHANGE, null,false); - } - } - - XXService xUpdService = daoMgr.getXXService().getById(service.getId()); - - String oldPassword = null; - - for(XXServiceConfigMap dbConfigMap : dbConfigMaps) { - if(StringUtils.equalsIgnoreCase(dbConfigMap.getConfigkey(), CONFIG_KEY_PASSWORD)) { - oldPassword = dbConfigMap.getConfigvalue(); - } - daoMgr.getXXServiceConfigMap().remove(dbConfigMap); - } - - XXServiceConfigMapDao xConfMapDao = daoMgr.getXXServiceConfigMap(); - for (Entry configMap : validConfigs.entrySet()) { - String configKey = configMap.getKey(); - String configValue = configMap.getValue(); - - if(StringUtils.equalsIgnoreCase(configKey, "username")) { - String userName = stringUtil.getValidUserName(configValue); - XXUser xxUser = daoMgr.getXXUser().findByUserName(userName); - if (xxUser != null) { - VXUser vXUser = xUserService.populateViewBean(xxUser); - } else { - UserSessionBase usb = ContextUtil.getCurrentUserSession(); - if (usb != null && !usb.isUserAdmin()) { - throw restErrorUtil.createRESTException("User does not exist with given username: [" - + userName + "] please use existing user", MessageEnums.OPER_NO_PERMISSION); - } - xUserMgr.createServiceConfigUser(userName); - } - } - - if (StringUtils.equalsIgnoreCase(configKey, CONFIG_KEY_PASSWORD)) { - if (StringUtils.equalsIgnoreCase(configValue, HIDDEN_PASSWORD_STR)) { - if (oldPassword != null && oldPassword.contains(",")) { - PasswordUtils util = PasswordUtils.build(oldPassword); - if (!util.getCryptAlgo().equalsIgnoreCase(CRYPT_ALGO)) { - String decryptedPwd = PasswordUtils.decryptPassword(oldPassword); - String paddingString = Joiner.on(",").skipNulls().join(CRYPT_ALGO, - new String(util.getEncryptKey()), new String(util.getSalt()), - util.getIterationCount(), PasswordUtils.generateIvIfNeeded(CRYPT_ALGO)); - String encryptedPwd = PasswordUtils.encryptPassword(paddingString + "," + decryptedPwd); - String newDecryptedPwd = PasswordUtils.decryptPassword(paddingString + "," + encryptedPwd); - if (StringUtils.equals(newDecryptedPwd, decryptedPwd)) { - configValue = paddingString + "," + encryptedPwd; - } - } else { - configValue = oldPassword; - } - } else { - configValue = oldPassword; - } - } else { - String paddingString = Joiner.on(",").skipNulls().join(CRYPT_ALGO, ENCRYPT_KEY, SALT, - ITERATION_COUNT, PasswordUtils.generateIvIfNeeded(CRYPT_ALGO)); - String encryptedPwd = PasswordUtils.encryptPassword(paddingString + "," + configValue); - String decryptedPwd = PasswordUtils.decryptPassword(paddingString + "," + encryptedPwd); - if (StringUtils.equals(decryptedPwd, configValue)) { - configValue = paddingString + "," + encryptedPwd; - } - } - } - XXServiceConfigMap xConfMap = new XXServiceConfigMap(); - xConfMap = (XXServiceConfigMap) rangerAuditFields.populateAuditFields(xConfMap, xUpdService); - xConfMap.setServiceId(service.getId()); - xConfMap.setConfigkey(configKey); - xConfMap.setConfigvalue(configValue); - xConfMapDao.create(xConfMap); - } - updateTabPermissions(service.getType(), validConfigs); - - RangerService updService = svcService.getPopulatedViewObject(xUpdService); - dataHistService.createObjectDataHistory(updService, RangerDataHistService.ACTION_UPDATE); - - return updService; - } - - @Override - public void deleteService(Long id) throws Exception { - if(LOG.isDebugEnabled()) { - LOG.debug("==> ServiceDBStore.deleteService(" + id + ")"); - } - - RangerService service = getService(id); - - if(service == null) { - throw new Exception("no service exists with ID=" + id); - } - - // Manage zone - disassociateZonesForService(service); //RANGER-3016 - - List policyIds = daoMgr.getXXPolicy().findPolicyIdsByServiceId(service.getId()); - if (CollectionUtils.isNotEmpty(policyIds)) { - long totalDeletedPolicies = 0; - for (Long policyID : policyIds) { - RangerPolicy rangerPolicy = getPolicy(policyID); - deletePolicy(rangerPolicy, service); - totalDeletedPolicies = totalDeletedPolicies + 1; - // its a bulk policy delete call flush and clear - if (totalDeletedPolicies % RangerBizUtil.POLICY_BATCH_SIZE == 0) { - bizUtil.bulkModeOnlyFlushAndClear(); - } - } - bizUtil.bulkModeOnlyFlushAndClear(); - } - - XXServiceConfigMapDao configDao = daoMgr.getXXServiceConfigMap(); - List configs = configDao.findByServiceId(service.getId()); - for (XXServiceConfigMap configMap : configs) { - configDao.remove(configMap); - } - - // Purge x_rms data - daoMgr.getXXRMSServiceResource().purge(service.getId()); - - Long version = service.getVersion(); - if(version == null) { - version = Long.valueOf(1); - LOG.info("Found Version Value: `null`, so setting value of version to 1, While updating object, version should not be null."); - } else { - version = Long.valueOf(version.longValue() + 1); - } - service.setVersion(version); - - svcService.delete(service); - - dataHistService.createObjectDataHistory(service, RangerDataHistService.ACTION_DELETE); - - svcService.createTransactionLog(service, null, RangerServiceService.OPERATION_DELETE_CONTEXT); - - //During the servie deletion ,we need to clear the RangerServicePoliciesCache,RangerServiceTagsCache for the given serviceName. - resetPolicyCache(service.getName()); - tagStore.resetTagCache(service.getName()); - - } - - private void updateTabPermissions(String svcType, Map svcConfig) { - if (StringUtils.equalsIgnoreCase(svcType, EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_TAG_NAME)) { - String svcAdminUsers = svcConfig.get(SERVICE_ADMIN_USERS); - if (StringUtils.isNotEmpty(svcAdminUsers)) { - for (String user : svcAdminUsers.split(",")) { - validateUserAndProvideTabTagBasedPolicyPermission(user.trim()); - } - } - } - } - - private void validateUserAndProvideTabTagBasedPolicyPermission(String username){ - XXPortalUser xxPortalUser = daoMgr.getXXPortalUser().findByLoginId(username); - if (xxPortalUser == null) { - throw restErrorUtil - .createRESTException( - "Username : " - + username - + " does not exist. Please provide valid user as service admin for tag service .", - MessageEnums.ERROR_CREATING_OBJECT); - } else { - VXPortalUser vXPortalUser = userMgr - .mapXXPortalUserToVXPortalUserForDefaultAccount(xxPortalUser); - if (CollectionUtils.isNotEmpty(vXPortalUser.getUserRoleList()) - && vXPortalUser.getUserRoleList().size() == 1) { - for (String userRole : vXPortalUser.getUserRoleList()) { - if (userRole.equals(RangerConstants.ROLE_USER)) { - HashMap moduleNameId = xUserMgr - .getAllModuleNameAndIdMap(); - xUserMgr.createOrUpdateUserPermisson( - vXPortalUser, - moduleNameId.get(RangerConstants.MODULE_TAG_BASED_POLICIES),true); - } - } - } - } - } - - @Override - public List getPoliciesByResourceSignature(String serviceName, String policySignature, Boolean isPolicyEnabled) throws Exception { - - List xxPolicies = daoMgr.getXXPolicy().findByResourceSignatureByPolicyStatus(serviceName, policySignature, isPolicyEnabled); - List policies = new ArrayList(xxPolicies.size()); - for (XXPolicy xxPolicy : xxPolicies) { - RangerPolicy policy = policyService.getPopulatedViewObject(xxPolicy); - policies.add(policy); - } - - return policies; - } - - @Override - public boolean serviceExists(String name) { - boolean ret = false; - - if (LOG.isDebugEnabled()) { - LOG.debug("==> ServiceDBStore.serviceExists({})", name); - } - - Long id = daoMgr.getXXService().findIdByName(name); - - ret = id != null; - - if (LOG.isDebugEnabled()) { - LOG.debug("<== ServiceDBStore.serviceExists({}): ret={}", name, ret); - } - - return ret; - } - - @Override - public RangerService getService(Long id) throws Exception { - if(LOG.isDebugEnabled()) { - LOG.debug("==> ServiceDBStore.getService()"); - } - - UserSessionBase session = ContextUtil.getCurrentUserSession(); - if (session == null) { - throw restErrorUtil.createRESTException("UserSession cannot be null.", - MessageEnums.OPER_NOT_ALLOWED_FOR_STATE); - } - - XXService xService = daoMgr.getXXService().getById(id); - - // TODO: As of now we are allowing SYS_ADMIN to read all the - // services including KMS - - if (xService == null) { - throw restErrorUtil.createRESTException("Data Not Found for given Id", - MessageEnums.DATA_NOT_FOUND, id, null, "readResource : No Object found with given id."); - } - if (!bizUtil.hasAccess(xService, null)) { - throw restErrorUtil.createRESTException("Logged in user is not allowed to read service, id: " + id, - MessageEnums.OPER_NO_PERMISSION); - } - - return svcService.getPopulatedViewObject(xService); - } - - @Override - public RangerService getServiceByName(String name) throws Exception { - if(LOG.isDebugEnabled()) { - LOG.debug("==> ServiceDBStore.getServiceByName()"); - } - XXService xService = daoMgr.getXXService().findByName(name); - - // TODO: As of now we are allowing SYS_ADMIN to read all the - // services including KMS - - if (ContextUtil.getCurrentUserSession() != null) { - if (xService == null) { - return null; - } - if (!bizUtil.hasAccess(xService, null)) { - throw restErrorUtil.createRESTException("Logged in user is not allowed to read service, name: " + name, - MessageEnums.OPER_NO_PERMISSION); - } - } - return xService == null ? null : svcService.getPopulatedViewObject(xService); - } - - @Override - public RangerService getServiceByDisplayName(String displayName) throws Exception { - if(LOG.isDebugEnabled()) { - LOG.debug("==> ServiceDBStore.getServiceByName()"); - } - XXService xService = daoMgr.getXXService().findByDisplayName(displayName); - - if (ContextUtil.getCurrentUserSession() != null) { - if (xService == null) { - return null; - } - if (!bizUtil.hasAccess(xService, null)) { - throw restErrorUtil.createRESTException("Logged in user is not allowed to read service, name: " + displayName, - MessageEnums.OPER_NO_PERMISSION); - } - } - return xService == null ? null : svcService.getPopulatedViewObject(xService); - } - - public RangerService getServiceByNameForDP(String name) throws Exception { - if(LOG.isDebugEnabled()) { - LOG.debug("==> ServiceDBStore.getServiceByNameForDP()"); - } - XXService xService = daoMgr.getXXService().findByName(name); - if (ContextUtil.getCurrentUserSession() != null) { - if (xService == null) { - return null; - } - } - return xService == null ? null : svcService.getPopulatedViewObject(xService); - } - - @Override - public List getServices(SearchFilter filter) throws Exception { - if(LOG.isDebugEnabled()) { - LOG.debug("==> ServiceDBStore.getServices()"); - } - - RangerServiceList serviceList = svcService.searchRangerServices(filter); - predicateUtil.applyFilter(serviceList.getServices(), filter); - List ret = serviceList.getServices(); - - if (LOG.isDebugEnabled()) { - LOG.debug("<== ServiceDBStore.getServices()"); - } - - return ret; - } - - public PList getPaginatedServices(SearchFilter filter) throws Exception { - if (LOG.isDebugEnabled()) { - LOG.debug("==> ServiceDBStore.getPaginatedServices()"); - } - - RangerServiceList serviceList = svcService.searchRangerServices(filter); - if (StringUtils.isEmpty(filter.getParam("serviceNamePartial"))){ - - predicateUtil.applyFilter(serviceList.getServices(), filter); - - } - if (LOG.isDebugEnabled()) { - LOG.debug("<== ServiceDBStore.getPaginatedServices()"); - } - - return new PList(serviceList.getServices(), serviceList.getStartIndex(), serviceList.getPageSize(), serviceList.getTotalCount(), - serviceList.getResultSize(), serviceList.getSortType(), serviceList.getSortBy()); - - } - - @Override - public RangerPolicy createPolicy(RangerPolicy policy) throws Exception { - return createPolicy(policy, bizUtil.getCreatePrincipalsIfAbsent()); - } - - @Override - public RangerPolicy createDefaultPolicy(RangerPolicy policy) throws Exception { - return createPolicy(policy, true); - } - - public RangerPolicy createPolicy(RangerPolicy policy, boolean createPrincipalsIfAbsent) throws Exception { - - RangerService service = getServiceByName(policy.getService()); - - if(service == null) { - throw new Exception("service does not exist - name=" + policy.getService()); - } - - XXServiceDef xServiceDef = daoMgr.getXXServiceDef().findByName(service.getType()); - - if(xServiceDef == null) { - throw new Exception("service-def does not exist - name=" + service.getType()); - } - - Long zoneId = RangerSecurityZone.RANGER_UNZONED_SECURITY_ZONE_ID; - String zoneName = policy.getZoneName(); - if (StringUtils.isNotEmpty(zoneName)) { - RangerSecurityZone zone = getSecurityZone(zoneName); - if (zone == null) { - throw new Exception("zone does not exist - name=" + zoneName); - } else { - zoneId = zone.getId(); - } - } - XXPolicy existing = daoMgr.getXXPolicy().findByNameAndServiceIdAndZoneId(policy.getName(), service.getId(), zoneId); - - if(existing != null) { - throw new Exception("policy already exists: ServiceName=" + policy.getService() + "; PolicyName=" + policy.getName() + ". ID=" + existing.getId()); - } - - List policyLabels = policy.getPolicyLabels(); - Set uniquePolicyLabels = new TreeSet<>(policyLabels); - policy.setVersion(Long.valueOf(1)); - updatePolicySignature(policy); - - if(populateExistingBaseFields) { - assignedIdPolicyService.setPopulateExistingBaseFields(true); - daoMgr.getXXPolicy().setIdentityInsert(true); - - policy = assignedIdPolicyService.create(policy, true); - - daoMgr.getXXPolicy().setIdentityInsert(false); - daoMgr.getXXPolicy().updateSequence(); - assignedIdPolicyService.setPopulateExistingBaseFields(false); - } else { - policy = policyService.create(policy, true); - } - - XXPolicy xCreatedPolicy = daoMgr.getXXPolicy().getById(policy.getId()); - policyRefUpdater.createNewPolMappingForRefTable(policy, xCreatedPolicy, xServiceDef, createPrincipalsIfAbsent); - createOrMapLabels(xCreatedPolicy, uniquePolicyLabels); - RangerPolicy createdPolicy = policyService.getPopulatedViewObject(xCreatedPolicy); - - boolean updateServiceInfoRoleVersion = false; - if (isSupportsRolesDownloadByService()) { - updateServiceInfoRoleVersion = isRoleDownloadRequired(createdPolicy, service); - } - handlePolicyUpdate(service, RangerPolicyDelta.CHANGE_TYPE_POLICY_CREATE, createdPolicy, updateServiceInfoRoleVersion); - dataHistService.createObjectDataHistory(createdPolicy, RangerDataHistService.ACTION_CREATE); - - createTransactionLog(createdPolicy, RangerPolicyService.OPERATION_IMPORT_CREATE_CONTEXT, RangerPolicyService.OPERATION_CREATE_CONTEXT); - - return createdPolicy; - } - - public void createOrMapLabels(XXPolicy xPolicy, Set uniquePolicyLabels) { - if (LOG.isDebugEnabled()) { - LOG.debug("==> ServiceDBStore.createOrMapLabels()"); - } - - for (String policyLabel : uniquePolicyLabels) { - //check and create new label If does not exist - if (StringUtils.isNotEmpty(policyLabel)) { - transactionSynchronizationAdapter.executeOnTransactionCommit(new AssociatePolicyLabel(policyLabel, xPolicy)); - } - } - - if (LOG.isDebugEnabled()) { - LOG.debug("<== ServiceDBStore.createOrMapLabels()"); - } - } - - private class AssociatePolicyLabel implements Runnable { - private String policyLabel; - private XXPolicy xPolicy; - - AssociatePolicyLabel(String policyLabel, XXPolicy xPolicy) { - this.policyLabel = policyLabel; - this.xPolicy = xPolicy; - } - - @Override - public void run() { - getOrCreateLabel(); - } - - private void getOrCreateLabel() { - if (LOG.isDebugEnabled()) { - LOG.debug("==> AssociatePolicyLabel.getOrCreateLabel(policyId=" + xPolicy.getId() + ", label=" + policyLabel + ")"); - } - - XXPolicyLabel xxPolicyLabel = daoMgr.getXXPolicyLabels().findByName(policyLabel); - - if (xxPolicyLabel == null) { - xxPolicyLabel = daoMgr.getXXPolicyLabels().findByName(policyLabel); - - if (xxPolicyLabel == null) { - xxPolicyLabel = new XXPolicyLabel(); - xxPolicyLabel.setPolicyLabel(policyLabel); - xxPolicyLabel = rangerAuditFields.populateAuditFieldsForCreate(xxPolicyLabel); - xxPolicyLabel = daoMgr.getXXPolicyLabels().create(xxPolicyLabel); - } - } - - if (xxPolicyLabel != null) { - XXPolicyLabelMap xxPolicyLabelMap = new XXPolicyLabelMap(); - xxPolicyLabelMap.setPolicyId(xPolicy.getId()); - xxPolicyLabelMap.setPolicyLabelId(xxPolicyLabel.getId()); - xxPolicyLabelMap = rangerAuditFields.populateAuditFieldsForCreate(xxPolicyLabelMap); - daoMgr.getXXPolicyLabelMap().create(xxPolicyLabelMap); - } - if (LOG.isDebugEnabled()) { - LOG.debug("<== AssociatePolicyLabel.getOrCreateLabel(policyId=" + xPolicy.getId() + ", label=" + policyLabel + ")"); - } - } - } - - private boolean validatePolicyItems(List policyItems) { - - if (CollectionUtils.isNotEmpty(policyItems)) { - for (RangerPolicyItem policyItem : policyItems) { - if (policyItem == null) { - return false; - } - - if (CollectionUtils.isEmpty(policyItem.getUsers()) && CollectionUtils.isEmpty(policyItem.getGroups()) && CollectionUtils.isEmpty(policyItem.getRoles())) { - return false; - } - - if (policyItem.getUsers() != null && (policyItem.getUsers().contains(null) || policyItem.getUsers().contains(""))) { - return false; - } - - if (policyItem.getGroups() != null && (policyItem.getGroups().contains(null) || policyItem.getGroups().contains(""))) { - return false; - } - - if (policyItem.getRoles() != null && (policyItem.getRoles().contains(null) || policyItem.getRoles().contains(""))) { - return false; - } - - if (CollectionUtils.isEmpty(policyItem.getAccesses()) || policyItem.getAccesses().contains(null)) { - return false; - } - for (RangerPolicyItemAccess itemAccesses : policyItem.getAccesses()) { - if (itemAccesses.getType() == null || itemAccesses.getIsAllowed() == null) { - return false; - } - } - } - } - - return true; - } - - @Override - public RangerPolicy updatePolicy(RangerPolicy policy) throws Exception { - if(LOG.isDebugEnabled()) { - LOG.debug("==> ServiceDBStore.updatePolicy(" + policy + ")"); - } - - XXPolicy xxExisting = daoMgr.getXXPolicy().getById(policy.getId()); - RangerPolicy existing = policyService.getPopulatedViewObject(xxExisting); - - if(existing == null) { - throw new Exception("no policy exists with ID=" + policy.getId()); - } - - RangerService service = getServiceByName(policy.getService()); - - if(service == null) { - throw new Exception("service does not exist - name=" + policy.getService()); - } - - XXServiceDef xServiceDef = daoMgr.getXXServiceDef().findByName(service.getType()); - - if(xServiceDef == null) { - throw new Exception("service-def does not exist - name=" + service.getType()); - } - - if(! StringUtils.equalsIgnoreCase(existing.getService(), policy.getService())) { - throw new Exception("policy id=" + policy.getId() + " already exists in service " + existing.getService() + ". It can not be moved to service " + policy.getService()); - } - boolean renamed = !StringUtils.equalsIgnoreCase(policy.getName(), existing.getName()); - - if(renamed) { - XXPolicy newNamePolicy = daoMgr.getXXPolicy().findByNameAndServiceIdAndZoneId(policy.getName(), service.getId(), xxExisting.getZoneId()); - - if(newNamePolicy != null) { - throw new Exception("another policy already exists with name '" + policy.getName() + "'. ID=" + newNamePolicy.getId()); - } - } - List policyLabels = policy.getPolicyLabels(); - Set uniquePolicyLabels = new TreeSet<>(policyLabels); - policy.setCreateTime(xxExisting.getCreateTime()); - if (StringUtils.isEmpty(policy.getGuid())) { - policy.setGuid(xxExisting.getGuid()); - } - policy.setVersion(xxExisting.getVersion()); - - policyService.createTransactionLog(policy, existing, RangerPolicyService.OPERATION_UPDATE_CONTEXT); - - updatePolicySignature(policy); - - policy = policyService.update(policy); - XXPolicy newUpdPolicy = daoMgr.getXXPolicy().getById(policy.getId()); - - policyRefUpdater.cleanupRefTables(policy); - deleteExistingPolicyLabel(policy); - - policyRefUpdater.createNewPolMappingForRefTable(policy, newUpdPolicy, xServiceDef, bizUtil.getCreatePrincipalsIfAbsent()); - createOrMapLabels(newUpdPolicy, uniquePolicyLabels); - RangerPolicy updPolicy = policyService.getPopulatedViewObject(newUpdPolicy); - - boolean updateServiceInfoRoleVersion = false; - if (isSupportsRolesDownloadByService()) { - updateServiceInfoRoleVersion = isRoleDownloadRequired(updPolicy, service); - } - handlePolicyUpdate(service, RangerPolicyDelta.CHANGE_TYPE_POLICY_UPDATE, updPolicy, updateServiceInfoRoleVersion); - dataHistService.createObjectDataHistory(updPolicy, RangerDataHistService.ACTION_UPDATE); - - return updPolicy; - } - - @Override - public void deletePolicy(RangerPolicy policy) throws Exception { - if(LOG.isDebugEnabled()) { - LOG.debug("==> ServiceDBStore.deletePolicy(" + policy + ")"); - } - - if(policy == null) { - throw new Exception("No such policy exists"); - } - - String policyName = policy.getName(); - RangerService service = getServiceByName(policy.getService()); - - if(service == null) { - throw new Exception("service does not exist - name='" + policy.getService()); - } - - Long version = policy.getVersion(); - if(version == null) { - version = Long.valueOf(1); - LOG.info("Found Version Value: `null`, so setting value of version to 1, While updating object, version should not be null."); - } else { - version = Long.valueOf(version.longValue() + 1); - } - - policy.setVersion(version); - - createTransactionLog(policy, RangerPolicyService.OPERATION_IMPORT_DELETE_CONTEXT, RangerPolicyService.OPERATION_DELETE_CONTEXT); - - policyRefUpdater.cleanupRefTables(policy); - deleteExistingPolicyLabel(policy); - policyService.delete(policy); - - handlePolicyUpdate(service, RangerPolicyDelta.CHANGE_TYPE_POLICY_DELETE, policy, false); - - dataHistService.createObjectDataHistory(policy, RangerDataHistService.ACTION_DELETE); - - LOG.info("Policy Deleted Successfully. PolicyName : " + policyName); - } - - @Override - public void deletePolicy(RangerPolicy policy, RangerService service) throws Exception { - if(LOG.isDebugEnabled()) { - LOG.debug("==> ServiceDBStore.deletePolicy()"); - } - if(policy != null) { - if(service==null) { - service = getServiceByName(policy.getService()); - } - if(service != null) { - String policyName = policy.getName(); - if(LOG.isDebugEnabled()) { - LOG.debug("Deleting Policy, policyName: " + policyName); - } - Long version = policy.getVersion(); - if(version == null) { - version = Long.valueOf(1); - LOG.info("Found Version Value: `null`, so setting value of version to 1, While updating object, version should not be null."); - } else { - version = Long.valueOf(version.longValue() + 1); - } - policy.setVersion(version); - policyRefUpdater.cleanupRefTables(policy); - deleteExistingPolicyLabel(policy); - policyService.delete(policy); - createTransactionLog(policy, RangerPolicyService.OPERATION_IMPORT_DELETE_CONTEXT, RangerPolicyService.OPERATION_DELETE_CONTEXT); - handlePolicyUpdate(service, RangerPolicyDelta.CHANGE_TYPE_POLICY_DELETE, policy, false); - dataHistService.createObjectDataHistory(policy, RangerDataHistService.ACTION_DELETE); - } - } - if(LOG.isDebugEnabled()) { - LOG.debug("<== ServiceDBStore.deletePolicy()"); - } - } - - void createTransactionLog(RangerPolicy policy, int operationImportContext, int operationContext) { - StackTraceElement[] trace = Thread.currentThread().getStackTrace(); - if (trace.length > 3 && (StringUtils.contains(trace[4].getMethodName(), "import") || - StringUtils.contains(trace[5].getMethodName(), "import"))) { - policyService.createTransactionLog(policy, null, operationImportContext); - } else { - policyService.createTransactionLog(policy, null, operationContext); - } - } - - @Override - public boolean policyExists(Long id) throws Exception { - return daoMgr.getXXPolicy().getCountById(id) > 0; - } - - @Override - public RangerPolicy getPolicy(Long id) throws Exception { - return policyService.read(id); - } - - public RangerPolicy getPolicy(String guid, String serviceName, String zoneName) throws Exception { - RangerPolicy ret = null; - if (StringUtils.isNotBlank(guid)) { - XXPolicy xPolicy = daoMgr.getXXPolicy().findPolicyByGUIDAndServiceNameAndZoneName(guid, serviceName, zoneName); - if (xPolicy != null) { - ret = policyService.getPopulatedViewObject(xPolicy); - } - } - return ret; - } - - @Override - public List getPolicies(SearchFilter filter) throws Exception { - if(LOG.isDebugEnabled()) { - LOG.debug("==> ServiceDBStore.getPolicies()"); - } - Boolean fetchTagPolicies = Boolean.valueOf(filter.getParam(SearchFilter.FETCH_TAG_POLICIES)); - Boolean fetchAllZonePolicies = Boolean.valueOf(filter.getParam(SearchFilter.FETCH_ZONE_UNZONE_POLICIES)); - String zoneName = filter.getParam(SearchFilter.ZONE_NAME); - - List ret = new ArrayList(); - RangerPolicyList policyList = searchRangerPolicies(filter); - List resourcePolicies = policyList.getPolicies(); - List tagPolicies = new ArrayList<>(); - - if(fetchTagPolicies) { - tagPolicies = searchRangerTagPoliciesOnBasisOfServiceName(resourcePolicies); - Iterator itr = tagPolicies.iterator(); - while (itr.hasNext()) { - RangerPolicy pol = (RangerPolicy) itr.next(); - if(!fetchAllZonePolicies) { - if(StringUtils.isNotEmpty(zoneName)) { - if(!zoneName.equals(pol.getZoneName())){ - itr.remove(); - } - } else { - if(StringUtils.isNotEmpty(pol.getZoneName())) { - itr.remove(); - } - } - } - } - } - if(LOG.isDebugEnabled()) { - LOG.debug("<== ServiceDBStore.getPolicies()"); - } - ret.addAll(resourcePolicies); - ret.addAll(tagPolicies); - return ret; - } - - private List searchRangerTagPoliciesOnBasisOfServiceName(List allExceptTagPolicies) throws Exception { - List ret = new ArrayList<>(); - Set serviceNames = new HashSet<>(); - Map tagServices = new HashMap<>(); - - for(RangerPolicy pol : allExceptTagPolicies) { - serviceNames.add(pol.getService()); - } - - for(String serviceName : serviceNames) { - RangerService service = getServiceByName(serviceName); - - if (StringUtils.isNotBlank(service.getTagService())) { - RangerService tagService = getServiceByName(service.getTagService()); - - if (tagService != null) { - tagServices.put(tagService.getName(), tagService.getId()); - } - } - } - - for (Map.Entry entry : tagServices.entrySet()) { - String tagServiceName = entry.getKey(); - Long tagServiceId = entry.getValue(); - - ServicePolicies tagServicePolicies = RangerServicePoliciesCache.getInstance().getServicePolicies(tagServiceName, tagServiceId, -1L, true, this); - List policies = tagServicePolicies != null ? tagServicePolicies.getPolicies() : null; - - if (policies != null) { - ret.addAll(policies); - } - } - - return ret; - } - - @Override - public Long getPolicyId(final Long serviceId, final String policyName, final Long zoneId) { - if(LOG.isDebugEnabled()) { - LOG.debug("==> ServiceDBStore.getPolicyId()"); - } - Long ret = null; - XXPolicy xxPolicy = daoMgr.getXXPolicy().findByNameAndServiceIdAndZoneId(policyName, serviceId, zoneId); - if (xxPolicy != null) { - ret = xxPolicy.getId(); - } - if(LOG.isDebugEnabled()) { - LOG.debug("<== ServiceDBStore.getPolicyId()"); - } - return ret; - } - - - public void getPoliciesInExcel(List policies, HttpServletResponse response) throws Exception { - if (LOG.isDebugEnabled()) { - LOG.debug("==> ServiceDBStore.getPoliciesInExcel()"); - } - String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); - String excelFileName = "Ranger_Policies_"+timeStamp+".xls"; - writeExcel(policies, excelFileName, response); - } - - public void getPoliciesInCSV(List policies, - HttpServletResponse response) throws Exception { - if (LOG.isDebugEnabled()) { - LOG.debug("==> ServiceDBStore.getPoliciesInCSV()"); - } - ServletOutputStream out = null; - String CSVFileName = null; - try { - String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); - CSVFileName = "Ranger_Policies_" + timeStamp + ".csv"; - out = response.getOutputStream(); - StringBuilder sb = writeCSV(policies, CSVFileName, response); - IOUtils.write(sb.toString(), out, "UTF-8"); - } catch (Exception e) { - LOG.error("Error while generating report file " + CSVFileName, e); - e.printStackTrace(); - } finally { - try { - if (out != null) { - out.flush(); - out.close(); - } - } catch (Exception ex) { - } - } - } - - public enum JSON_FILE_NAME_TYPE { POLICY, ROLE } - public void getObjectInJson(List objList, - HttpServletResponse response, JSON_FILE_NAME_TYPE type) throws Exception { - if (LOG.isDebugEnabled()) { - LOG.debug("==> ServiceDBStore.getObjectInJson()"); - } - String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); - String jsonFileName; - switch(type) { - case POLICY : - jsonFileName = "Ranger_Policies_" + timeStamp + ".json"; - break; - case ROLE : - jsonFileName = "Ranger_Roles_" + timeStamp + ".json"; - break; - default : - throw restErrorUtil.createRESTException("Invalid type "+type); - } - writeJson(objList, jsonFileName, response, type); - } - - public PList getPaginatedPolicies(SearchFilter filter) throws Exception { - if (LOG.isDebugEnabled()) { - LOG.debug("==> ServiceDBStore.getPaginatedPolicies(+ " + filter + ")"); - } - - RangerPolicyList policyList = searchRangerPolicies(filter); - - if (LOG.isDebugEnabled()) { - LOG.debug("before filter: count=" + policyList.getListSize()); - } - predicateUtil.applyFilter(policyList.getPolicies(), filter); - if (LOG.isDebugEnabled()) { - LOG.debug("after filter: count=" + policyList.getListSize()); - } - - if (LOG.isDebugEnabled()) { - LOG.debug("<== ServiceDBStore.getPaginatedPolicies(" + filter + "): count=" + policyList.getListSize()); - } - - - return new PList<>(policyList.getPolicies(), policyList.getStartIndex(), policyList.getPageSize(), policyList.getTotalCount(), - policyList.getResultSize(), policyList.getSortType(), policyList.getSortBy()); - - } - - @Override - public List getServicePolicies(Long serviceId, SearchFilter filter) throws Exception { - if(LOG.isDebugEnabled()) { - LOG.debug("==> ServiceDBStore.getServicePolicies(" + serviceId + ")"); - } - String zoneName = filter.getParam(SearchFilter.FETCH_ZONE_NAME); - String denyCondition = filter.getParam(SearchFilter.FETCH_DENY_CONDITION); - XXService service = daoMgr.getXXService().getById(serviceId); - - if (service == null) { - throw new Exception("service does not exist - id='" + serviceId); - } - - List ret = getServicePolicies(service, filter); - if(!"true".equalsIgnoreCase(filter.getParam(SearchFilter.FETCH_ZONE_UNZONE_POLICIES))) { - if(StringUtils.isBlank(zoneName) && StringUtils.isBlank(denyCondition)) { - ret = noZoneFilter(ret); - } - } - if(LOG.isDebugEnabled()) { - LOG.debug("<== ServiceDBStore.getServicePolicies(" + serviceId + ") : policy-count=" + (ret == null ? 0 : ret.size())); - } - return ret; - - } - - public List noZoneFilter(List servicePolicies) { - List noZonePolicies = new ArrayList<>(); - if (CollectionUtils.isNotEmpty(servicePolicies)) { - for (RangerPolicy policy : servicePolicies) { - if (StringUtils.isBlank(policy.getZoneName())) { - noZonePolicies.add(policy); - } - } - } - return noZonePolicies; - } - - public PList getPaginatedServicePolicies(Long serviceId, SearchFilter filter) throws Exception { - if (LOG.isDebugEnabled()) { - LOG.debug("==> ServiceDBStore.getPaginatedServicePolicies(" + serviceId + ")"); - } - - XXService service = daoMgr.getXXService().getById(serviceId); - - if (service == null) { - throw new Exception("service does not exist - id='" + serviceId); - } - - PList ret = getPaginatedServicePolicies(service.getName(), filter); - - if (LOG.isDebugEnabled()) { - LOG.debug("<== ServiceDBStore.getPaginatedServicePolicies(" + serviceId + ")"); - } - return ret; - } - - @Override - public List getServicePolicies(String serviceName, SearchFilter filter) throws Exception { - if(LOG.isDebugEnabled()) { - LOG.debug("==> ServiceDBStore.getServicePolicies(" + serviceName + ")"); - } - - List ret = null; - String zoneName = filter.getParam("zoneName"); - XXService service = daoMgr.getXXService().findByName(serviceName); - - if (service == null) { - throw new Exception("service does not exist - name='" + serviceName); - } - - ret = getServicePolicies(service, filter); - if(StringUtils.isBlank(zoneName)) { - ret = noZoneFilter(ret); - } - if(LOG.isDebugEnabled()) { - LOG.debug("<== ServiceDBStore.getServicePolicies(" + serviceName + "): count=" + ((ret == null) ? 0 : ret.size())); - } - - return ret; - } - - @Override - public List getPoliciesWithMetaAttributes(List policiesList) { - if (CollectionUtils.isNotEmpty(policiesList)) { - List policies = new ArrayList<>(); - for (RangerPolicy policy : policiesList) { - RangerPolicy policyCopy = (RangerPolicy) SerializationUtils.clone(policy); - policies.add(policyCopy); - } - - List policytimeMetaDataList = daoMgr.getXXPolicy().getMetaAttributesForPolicies(policies.stream().map(RangerPolicy::getId).collect(Collectors.toList())); - if (CollectionUtils.isNotEmpty(policytimeMetaDataList)) { - Map> policyMap = policytimeMetaDataList.stream() - .filter(row -> row != null && row.length == 3 && row[0] != null && row[1] != null && row[2] != null) - .collect(Collectors.toMap(row -> (Long) row[0], row-> Arrays.asList((Date) row[1], (Date) row[2]))); - - for (RangerPolicy policy : policies) { - List timeMetaData = policyMap.get(policy.getId()); - if (timeMetaData != null && timeMetaData.size() == 2) { - policy.setCreateTime(timeMetaData.get(0)); - policy.setUpdateTime(timeMetaData.get(1)); - } - } - } - return policies; - } - return policiesList; - } - - private List getServicePolicies(XXService service, SearchFilter filter) throws Exception { - if(LOG.isDebugEnabled()) { - LOG.debug("==> ServiceDBStore.getServicePolicies()"); - } - - if (service == null) { - throw new Exception("service does not exist"); - } - - List ret = null; - - ServicePolicies servicePolicies = RangerServicePoliciesCache.getInstance().getServicePolicies(service.getName(), service.getId(), -1L, true, this); - final List policies = servicePolicies != null ? servicePolicies.getPolicies() : null; - - if(policies != null && filter != null && MapUtils.isNotEmpty(filter.getParams())) { - Map filterResources = filter.getParamsWithPrefix(SearchFilter.RESOURCE_PREFIX, true); - String resourceMatchScope = filter.getParam(SearchFilter.RESOURCE_MATCH_SCOPE); - boolean useLegacyResourceSearch = true; - SearchFilter searchFilter = new SearchFilter(filter); - - if (MapUtils.isNotEmpty(filterResources) && resourceMatchScope != null) { - useLegacyResourceSearch = false; - for (Map.Entry entry : filterResources.entrySet()) { - searchFilter.removeParam(SearchFilter.RESOURCE_PREFIX + entry.getKey()); - } - } - - if (LOG.isDebugEnabled()) { - LOG.debug("Using" + (useLegacyResourceSearch ? " old " : " new ") + "way of filtering service-policies"); - } - - ret = new ArrayList<>(policies); - predicateUtil.applyFilter(ret, searchFilter); - - if (!useLegacyResourceSearch && CollectionUtils.isNotEmpty(ret)) { - RangerPolicyResourceMatcher.MatchScope scope; - - if (StringUtils.equalsIgnoreCase(resourceMatchScope, "self")) { - scope = RangerPolicyResourceMatcher.MatchScope.SELF; - } else if (StringUtils.equalsIgnoreCase(resourceMatchScope, "ancestor")) { - scope = RangerPolicyResourceMatcher.MatchScope.ANCESTOR; - } else if (StringUtils.equalsIgnoreCase(resourceMatchScope, "self_or_ancestor")) { - scope = RangerPolicyResourceMatcher.MatchScope.SELF_OR_ANCESTOR; - } else { - // DESCENDANT match will never happen - scope = RangerPolicyResourceMatcher.MatchScope.SELF_OR_ANCESTOR; - } - - RangerServiceDef serviceDef = servicePolicies.getServiceDef(); - - switch (scope) { - case SELF : { - serviceDef = RangerServiceDefHelper.getServiceDefForPolicyFiltering(serviceDef); - break; - } - case ANCESTOR : { - Map updatedFilterResources = RangerServiceDefHelper.getFilterResourcesForAncestorPolicyFiltering(serviceDef, filterResources); - if (MapUtils.isNotEmpty(updatedFilterResources)) { - for (Map.Entry entry : updatedFilterResources.entrySet()) { - filterResources.put(entry.getKey(), entry.getValue()); - } - scope = RangerPolicyResourceMatcher.MatchScope.SELF_OR_ANCESTOR; - } - break; - } - default: - break; - } - - ret = applyResourceFilter(serviceDef, ret, filterResources, searchFilter, scope); - } - } else { - ret = policies; - } - - if(LOG.isDebugEnabled()) { - LOG.debug("<== ServiceDBStore.getServicePolicies(): count=" + ((ret == null) ? 0 : ret.size())); - } - - return ret; - } - - List applyResourceFilter(RangerServiceDef serviceDef, List policies, Map filterResources, SearchFilter filter, RangerPolicyResourceMatcher.MatchScope scope) { - if (LOG.isDebugEnabled()) { - LOG.debug("==> ServiceDBStore.applyResourceFilter(policies-size=" + policies.size() + ", filterResources=" + filterResources + ", " + scope + ")"); - } - - List ret = new ArrayList<>(); - - List matchers = getMatchers(serviceDef, filterResources, filter); - - if (CollectionUtils.isNotEmpty(matchers)) { - - for (RangerPolicy policy : policies) { - - for (RangerPolicyResourceMatcher matcher : matchers) { - - if (LOG.isDebugEnabled()) { - LOG.debug("Trying to match for policy:[" + policy + "] using RangerDefaultPolicyResourceMatcher:[" + matcher + "]"); - } - - if (matcher.isMatch(policy, scope, null)) { - if (LOG.isDebugEnabled()) { - LOG.debug("matched policy:[" + policy + "]"); - } - ret.add(policy); - break; - } - } - } - } + XXAccessTypeDefDao xxATDDao = daoMgr.getXXAccessTypeDef(); - if (LOG.isDebugEnabled()) { - LOG.debug("<== ServiceDBStore.applyResourceFilter(policies-size=" + ret.size() + ", filterResources=" + filterResources + ", " + scope + ")"); - } + for (int i = 0; i < accessTypes.size(); i++) { + RangerAccessTypeDef accessType = accessTypes.get(i); + XXAccessTypeDef xAccessType = new XXAccessTypeDef(); - return ret; - } + xAccessType = serviceDefService.populateRangerAccessTypeDefToXX(accessType, xAccessType, createdSvcDef, RangerServiceDefService.OPERATION_CREATE_CONTEXT); - List getMatchers(RangerServiceDef serviceDef, Map filterResources, SearchFilter filter) { - if (LOG.isDebugEnabled()) { - LOG.debug("==> ServiceDBStore.getMatchers(filterResources=" + filterResources + ")"); - } + xAccessType.setOrder(i); - List ret = new ArrayList<>(); + xAccessType = xxATDDao.create(xAccessType); - RangerServiceDefHelper serviceDefHelper = new RangerServiceDefHelper(serviceDef); + Collection impliedGrants = accessType.getImpliedGrants(); + XXAccessTypeDefGrantsDao xxATDGrantDao = daoMgr.getXXAccessTypeDefGrants(); - String policyTypeStr = filter.getParam(SearchFilter.POLICY_TYPE); + for (String impliedGrant : impliedGrants) { + XXAccessTypeDefGrants xImpliedGrant = new XXAccessTypeDefGrants(); - int[] policyTypes = RangerPolicy.POLICY_TYPES; + xImpliedGrant.setAtdId(xAccessType.getId()); + xImpliedGrant.setImpliedGrant(impliedGrant); - if (StringUtils.isNotBlank(policyTypeStr)) { - policyTypes = new int[1]; - policyTypes[0] = Integer.parseInt(policyTypeStr); - } + xxATDGrantDao.create(xImpliedGrant); + } + } - for (Integer policyType : policyTypes) { - Set> validResourceHierarchies = serviceDefHelper.getResourceHierarchies(policyType, filterResources.keySet()); + XXPolicyConditionDefDao xxPolCondDao = daoMgr.getXXPolicyConditionDef(); - if (LOG.isDebugEnabled()) { - LOG.debug("Found " + validResourceHierarchies.size() + " valid resource hierarchies for key-set " + filterResources.keySet()); - } + for (int i = 0; i < policyConditions.size(); i++) { + RangerPolicyConditionDef policyCondition = policyConditions.get(i); + XXPolicyConditionDef xPolicyCondition = new XXPolicyConditionDef(); - List> resourceHierarchies = new ArrayList<>(validResourceHierarchies); + xPolicyCondition = serviceDefService.populateRangerPolicyConditionDefToXX(policyCondition, xPolicyCondition, createdSvcDef, RangerServiceDefService.OPERATION_CREATE_CONTEXT); - for (List validResourceHierarchy : resourceHierarchies) { + xPolicyCondition.setOrder(i); + + xxPolCondDao.create(xPolicyCondition); + } - if (LOG.isDebugEnabled()) { - LOG.debug("validResourceHierarchy:[" + validResourceHierarchy + "]"); - } + XXContextEnricherDefDao xxContextEnricherDao = daoMgr.getXXContextEnricherDef(); - Map policyResources = new HashMap<>(); + for (int i = 0; i < contextEnrichers.size(); i++) { + RangerContextEnricherDef contextEnricher = contextEnrichers.get(i); + XXContextEnricherDef xContextEnricher = new XXContextEnricherDef(); - for (RangerResourceDef resourceDef : validResourceHierarchy) { - policyResources.put(resourceDef.getName(), new RangerPolicyResource(filterResources.get(resourceDef.getName()), false, resourceDef.getRecursiveSupported())); - } + xContextEnricher = serviceDefService.populateRangerContextEnricherDefToXX(contextEnricher, xContextEnricher, createdSvcDef, RangerServiceDefService.OPERATION_CREATE_CONTEXT); - RangerDefaultPolicyResourceMatcher matcher = new RangerDefaultPolicyResourceMatcher(); - matcher.setServiceDef(serviceDef); - matcher.setPolicyResources(policyResources, policyType); - matcher.init(); + xContextEnricher.setOrder(i); - ret.add(matcher); + xxContextEnricherDao.create(xContextEnricher); + } - if (LOG.isDebugEnabled()) { - LOG.debug("Added matcher:[" + matcher + "]"); - } - } - } + XXEnumDefDao xxEnumDefDao = daoMgr.getXXEnumDef(); - if (LOG.isDebugEnabled()) { - LOG.debug("<== ServiceDBStore.getMatchers(filterResources=" + filterResources + ", " + ", count=" + ret.size() + ")"); - } + for (RangerEnumDef vEnum : enums) { + XXEnumDef xEnum = new XXEnumDef(); - return ret; - } + xEnum = serviceDefService.populateRangerEnumDefToXX(vEnum, xEnum, createdSvcDef, RangerServiceDefService.OPERATION_CREATE_CONTEXT); + xEnum = xxEnumDefDao.create(xEnum); - private List getServicePoliciesFromDb(XXService service) throws Exception { - if(LOG.isDebugEnabled()) { - LOG.debug("==> ServiceDBStore.getServicePoliciesFromDb(" + service.getName() + ")"); - } + List elements = vEnum.getElements(); + XXEnumElementDefDao xxEnumEleDefDao = daoMgr.getXXEnumElementDef(); - RangerPolicyRetriever policyRetriever = new RangerPolicyRetriever(daoMgr, txManager); + for (int i = 0; i < elements.size(); i++) { + RangerEnumElementDef element = elements.get(i); + XXEnumElementDef xElement = new XXEnumElementDef(); - List ret = policyRetriever.getServicePolicies(service); + xElement = serviceDefService.populateRangerEnumElementDefToXX(element, xElement, xEnum, RangerServiceDefService.OPERATION_CREATE_CONTEXT); - if(LOG.isDebugEnabled()) { - LOG.debug("<== ServiceDBStore.getServicePoliciesFromDb(" + service.getName() + "): count=" + ((ret == null) ? 0 : ret.size())); - } + xElement.setOrder(i); - return ret; - } + xxEnumEleDefDao.create(xElement); + } + } - public PList getPaginatedServicePolicies(String serviceName, SearchFilter filter) throws Exception { - if (LOG.isDebugEnabled()) { - LOG.debug("==> ServiceDBStore.getPaginatedServicePolicies(" + serviceName + ")"); - } + XXDataMaskTypeDefDao xxDataMaskDefDao = daoMgr.getXXDataMaskTypeDef(); - if (filter == null) { - filter = new SearchFilter(); - } + for (int i = 0; i < dataMaskTypes.size(); i++) { + RangerDataMaskTypeDef dataMask = dataMaskTypes.get(i); + XXDataMaskTypeDef xDataMaskDef = new XXDataMaskTypeDef(); - filter.setParam(SearchFilter.SERVICE_NAME, serviceName); + xDataMaskDef = serviceDefService.populateRangerDataMaskDefToXX(dataMask, xDataMaskDef, createdSvcDef, RangerServiceDefService.OPERATION_CREATE_CONTEXT); - PList ret = getPaginatedPolicies(filter); + xDataMaskDef.setOrder(i); - if (LOG.isDebugEnabled()) { - LOG.debug("<== ServiceDBStore.getPaginatedServicePolicies(" + serviceName + "): count=" - + ((ret == null) ? 0 : ret.getListSize())); - } + xxDataMaskDefDao.create(xDataMaskDef); + } - return ret; - } + List xxAccessTypeDefs = xxATDDao.findByServiceDefId(createdSvcDef.getId()); - @Override - public ServicePolicies getServicePoliciesIfUpdated(String serviceName, Long lastKnownVersion, boolean needsBackwardCompatibility) throws Exception { - if (LOG.isDebugEnabled()) { - LOG.debug("==> ServiceDBStore.getServicePoliciesIfUpdated(" + serviceName + ", " + lastKnownVersion + ", " + needsBackwardCompatibility + ")"); - } + for (RangerAccessTypeDef accessType : dataMaskAccessTypes) { + if (!isAccessTypeInList(accessType.getName(), xxAccessTypeDefs)) { + throw restErrorUtil.createRESTException("accessType with name: " + accessType.getName() + " does not exists", MessageEnums.DATA_NOT_FOUND); + } + } - ServicePolicies ret = null; + for (RangerAccessTypeDef accessType : rowFilterAccessTypes) { + if (!isAccessTypeInList(accessType.getName(), xxAccessTypeDefs)) { + throw restErrorUtil.createRESTException("accessType with name: " + accessType.getName() + " does not exists", MessageEnums.DATA_NOT_FOUND); + } + } - XXService serviceDbObj = daoMgr.getXXService().findByName(serviceName); + for (XXAccessTypeDef xxAccessTypeDef : xxAccessTypeDefs) { + String dataMaskOptions = null; + String rowFilterOptions = null; - if (serviceDbObj == null) { - throw new Exception("service does not exist. name=" + serviceName); - } + for (RangerAccessTypeDef accessTypeDef : dataMaskAccessTypes) { + if (StringUtils.equals(accessTypeDef.getName(), xxAccessTypeDef.getName())) { + dataMaskOptions = svcDefServiceWithAssignedId.objectToJson(accessTypeDef); + break; + } + } - XXServiceVersionInfo serviceVersionInfoDbObj = daoMgr.getXXServiceVersionInfo().findByServiceName(serviceName); + for (RangerAccessTypeDef accessTypeDef : rowFilterAccessTypes) { + if (StringUtils.equals(accessTypeDef.getName(), xxAccessTypeDef.getName())) { + rowFilterOptions = svcDefServiceWithAssignedId.objectToJson(accessTypeDef); + break; + } + } - if (serviceVersionInfoDbObj == null) { - LOG.warn("serviceVersionInfo does not exist. name=" + serviceName); - } + if (!StringUtils.equals(dataMaskOptions, xxAccessTypeDef.getDataMaskOptions()) || !StringUtils.equals(rowFilterOptions, xxAccessTypeDef.getRowFilterOptions())) { + xxAccessTypeDef.setDataMaskOptions(dataMaskOptions); + xxAccessTypeDef.setRowFilterOptions(rowFilterOptions); - if (lastKnownVersion == null || serviceVersionInfoDbObj == null || serviceVersionInfoDbObj.getPolicyVersion() == null || !lastKnownVersion.equals(serviceVersionInfoDbObj.getPolicyVersion())) { - ret = RangerServicePoliciesCache.getInstance().getServicePolicies(serviceName, serviceDbObj.getId(), lastKnownVersion, needsBackwardCompatibility, this); - } + xxATDDao.update(xxAccessTypeDef); + } + } - if (LOG.isDebugEnabled()) { - RangerServicePoliciesCache.getInstance().dump(); - } + List xxResourceDefs = xxResDefDao.findByServiceDefId(createdSvcDef.getId()); - if (ret != null && lastKnownVersion != null && lastKnownVersion.equals(ret.getPolicyVersion())) { - // ServicePolicies are not changed - ret = null; - } + for (RangerResourceDef resource : dataMaskResources) { + if (!isResourceInList(resource.getName(), xxResourceDefs)) { + throw restErrorUtil.createRESTException("resource with name: " + resource.getName() + " does not exists", MessageEnums.DATA_NOT_FOUND); + } + } - if (ret != null) { - if (LOG.isDebugEnabled()) { - LOG.debug("Checking if resource-service:[" + ret.getServiceName() + "] is disabled"); - } - if (!serviceDbObj.getIsenabled()) { - ret = ServicePolicies.copyHeader(ret); - ret.setTagPolicies(null); - } else { - String tagServiceName = ret.getTagPolicies() != null ? ret.getTagPolicies().getServiceName() : null; - boolean isTagServiceActive = isServiceActive(tagServiceName); + for (RangerResourceDef resource : rowFilterResources) { + if (!isResourceInList(resource.getName(), xxResourceDefs)) { + throw restErrorUtil.createRESTException("resource with name: " + resource.getName() + " does not exists", MessageEnums.DATA_NOT_FOUND); + } + } - if (!isTagServiceActive) { - ServicePolicies copy = ServicePolicies.copyHeader(ret); + for (XXResourceDef xxResourceDef : xxResourceDefs) { + String dataMaskOptions = null; + String rowFilterOptions = null; - if (!isTagServiceActive) { - copy.setTagPolicies(null); - } + for (RangerResourceDef resource : dataMaskResources) { + if (StringUtils.equals(resource.getName(), xxResourceDef.getName())) { + dataMaskOptions = svcDefServiceWithAssignedId.objectToJson(resource); + break; + } + } - List copyPolicies = ret.getPolicies() != null ? new ArrayList<>(ret.getPolicies()) : null; - List copyPolicyDeltas = ret.getPolicyDeltas() != null ? new ArrayList<>(ret.getPolicyDeltas()) : null; + for (RangerResourceDef resource : rowFilterResources) { + if (StringUtils.equals(resource.getName(), xxResourceDef.getName())) { + rowFilterOptions = svcDefServiceWithAssignedId.objectToJson(resource); + break; + } + } - copy.setPolicies(copyPolicies); - copy.setPolicyDeltas(copyPolicyDeltas); + if (!StringUtils.equals(dataMaskOptions, xxResourceDef.getDataMaskOptions()) || !StringUtils.equals(rowFilterOptions, xxResourceDef.getRowFilterOptions())) { + xxResourceDef.setDataMaskOptions(dataMaskOptions); + xxResourceDef.setRowFilterOptions(rowFilterOptions); - ret = copy; - } - } + xxResDefDao.update(xxResourceDef); + } + } - Map securityZones = securityZoneStore.getSecurityZonesForService(serviceName); - ServicePolicies updatedServicePolicies = ret; - if (MapUtils.isNotEmpty(securityZones)) { - updatedServicePolicies = getUpdatedServicePoliciesForZones(ret, securityZones); - patchAssociatedTagServiceInSecurityZoneInfos(updatedServicePolicies); - } + RangerServiceDef createdServiceDef = serviceDefService.getPopulatedViewObject(createdSvcDef); - if (lastKnownVersion == null || lastKnownVersion == -1L || needsBackwardCompatibility) { - ret = filterServicePolicies(updatedServicePolicies); - } else { - ret = updatedServicePolicies; - } + dataHistService.createObjectDataHistory(createdServiceDef, RangerDataHistService.ACTION_CREATE); - ret.setServiceConfig(getServiceConfigForPlugin(ret.getServiceId())); + postCreate(createdServiceDef); - if (ret.getTagPolicies() != null && ret.getTagPolicies().getServiceId() != null) { - ret.getTagPolicies().setServiceConfig(getServiceConfigForPlugin(ret.getTagPolicies().getServiceId())); - } + LOG.debug("<== ServiceDBStore.createServiceDef({}): {}", serviceDef, createdServiceDef); - } + return createdServiceDef; + } - if (LOG.isDebugEnabled()) { - LOG.debug("<== ServiceDBStore.getServicePoliciesIfUpdated(" + serviceName + ", " + lastKnownVersion + ", " + needsBackwardCompatibility + "): count=" + ((ret == null || ret.getPolicies() == null) ? 0 : ret.getPolicies().size())); - } + @Override + public RangerServiceDef updateServiceDef(RangerServiceDef serviceDef) throws Exception { + LOG.debug("==> ServiceDBStore.updateServiceDef({})", serviceDef); - return ret; - } + Long serviceDefId = serviceDef.getId(); + XXServiceDef existing = daoMgr.getXXServiceDef().getById(serviceDefId); - @Override - public Long getServicePolicyVersion(String serviceName) { + if (existing == null) { + throw restErrorUtil.createRESTException("no service-def exists with ID=" + serviceDef.getId(), MessageEnums.DATA_NOT_FOUND); + } - XXServiceVersionInfo serviceVersionInfoDbObj = daoMgr.getXXServiceVersionInfo().findByServiceName(serviceName); + String existingName = existing.getName(); + boolean renamed = !StringUtils.equalsIgnoreCase(serviceDef.getName(), existingName); - return serviceVersionInfoDbObj != null ? serviceVersionInfoDbObj.getPolicyVersion() : null; - } + if (renamed) { + XXServiceDef renamedSVCDef = daoMgr.getXXServiceDef().findByName(serviceDef.getName()); - @Override - public ServicePolicies getServicePolicyDeltasOrPolicies(String serviceName, Long lastKnownVersion) throws Exception { - boolean getOnlyDeltas = false; - if (LOG.isDebugEnabled()) { - LOG.debug("Support for incremental policy updates enabled using \"ranger.admin" + RangerCommonConstants.RANGER_ADMIN_SUFFIX_POLICY_DELTA + "\" configuation parameter :[" + SUPPORTS_POLICY_DELTAS +"]"); - } - return getServicePolicies(serviceName, lastKnownVersion, getOnlyDeltas, SUPPORTS_POLICY_DELTAS, Long.MAX_VALUE); - } + if (renamedSVCDef != null) { + throw restErrorUtil.createRESTException("another service-def already exists with name '" + serviceDef.getName() + "'. ID=" + renamedSVCDef.getId(), MessageEnums.DATA_NOT_UPDATABLE); + } + } - @Override - public ServicePolicies getServicePolicyDeltas(String serviceName, Long lastKnownVersion, Long cachedPolicyVersion) throws Exception { - ServicePolicies ret = null; + List configs = serviceDef.getConfigs() != null ? serviceDef.getConfigs() : new ArrayList<>(); + List resources = serviceDef.getResources() != null ? serviceDef.getResources() : new ArrayList<>(); + List accessTypes = serviceDef.getAccessTypes() != null ? serviceDef.getAccessTypes() : new ArrayList<>(); + List policyConditions = serviceDef.getPolicyConditions() != null ? serviceDef.getPolicyConditions() : new ArrayList<>(); + List contextEnrichers = serviceDef.getContextEnrichers() != null ? serviceDef.getContextEnrichers() : new ArrayList<>(); + List enums = serviceDef.getEnums() != null ? serviceDef.getEnums() : new ArrayList<>(); + RangerDataMaskDef dataMaskDef = serviceDef.getDataMaskDef(); + RangerRowFilterDef rowFilterDef = serviceDef.getRowFilterDef(); + RangerServiceDefHelper defHelper = new RangerServiceDefHelper(serviceDef, false); - if (SUPPORTS_POLICY_DELTAS) { - if (LOG.isDebugEnabled()) { - LOG.debug("Support for incremental policy updates enabled using \"ranger.admin" + RangerCommonConstants.RANGER_ADMIN_SUFFIX_POLICY_DELTA + "\" configuation parameter :[" + SUPPORTS_POLICY_DELTAS + "]"); - } - ret = getServicePolicies(serviceName, lastKnownVersion, true, SUPPORTS_POLICY_DELTAS, cachedPolicyVersion); - } - - return ret; - } - - @Override - public ServicePolicies getServicePolicies(String serviceName, Long lastKnownVersion) throws Exception { - boolean getOnlyDeltas = false; - return getServicePolicies(serviceName, lastKnownVersion, getOnlyDeltas, false, Long.MAX_VALUE); - } - - private ServicePolicies getServicePolicies(String serviceName, Long lastKnownVersion, boolean getOnlyDeltas, boolean isDeltaEnabled, Long maxNeededVersion) throws Exception { - if (LOG.isDebugEnabled()) { - LOG.debug("==> ServiceDBStore.getServicePolicies(" + serviceName + ", " + lastKnownVersion + ")"); - } - - ServicePolicies ret = null; - - XXService serviceDbObj = daoMgr.getXXService().findByName(serviceName); - - if (serviceDbObj == null) { - throw new Exception("service does not exist. name=" + serviceName); - } + defHelper.patchServiceDefWithDefaultValues(); - XXServiceVersionInfo serviceVersionInfoDbObj = daoMgr.getXXServiceVersionInfo().findByServiceName(serviceName); + serviceDef.setCreateTime(existing.getCreateTime()); + serviceDef.setGuid(existing.getGuid()); + serviceDef.setVersion(existing.getVersion()); - if (serviceVersionInfoDbObj == null) { - LOG.warn("serviceVersionInfo does not exist. name=" + serviceName); - } + serviceDef = serviceDefService.update(serviceDef); - RangerServiceDef serviceDef = getServiceDef(serviceDbObj.getType()); + XXServiceDef createdSvcDef = daoMgr.getXXServiceDef().getById(serviceDefId); - if (serviceDef == null) { - throw new Exception("service-def does not exist. id=" + serviceDbObj.getType()); - } - String serviceType = serviceDef.getName(); + updateChildObjectsOfServiceDef(createdSvcDef, configs, resources, accessTypes, policyConditions, contextEnrichers, enums, dataMaskDef, rowFilterDef); - String auditMode = getAuditMode(serviceType, serviceName); + RangerServiceDef updatedSvcDef = getServiceDef(serviceDefId); - XXService tagServiceDbObj = null; - RangerServiceDef tagServiceDef = null; - XXServiceVersionInfo tagServiceVersionInfoDbObj= null; - - if (serviceDbObj.getTagService() != null) { - tagServiceDbObj = daoMgr.getXXService().getById(serviceDbObj.getTagService()); - } - - if (tagServiceDbObj != null) { - tagServiceDef = getServiceDef(tagServiceDbObj.getType()); + dataHistService.createObjectDataHistory(updatedSvcDef, RangerDataHistService.ACTION_UPDATE); - if (tagServiceDef == null) { - throw new Exception("service-def does not exist. id=" + tagServiceDbObj.getType()); - } + postUpdate(updatedSvcDef); - ServiceDefUtil.normalizeAccessTypeDefs(tagServiceDef, serviceType); + LOG.debug("<== ServiceDBStore.updateServiceDef({}): {}", serviceDef, serviceDef); - tagServiceVersionInfoDbObj = daoMgr.getXXServiceVersionInfo().findByServiceId(serviceDbObj.getTagService()); + return updatedSvcDef; + } - if (tagServiceVersionInfoDbObj == null) { - LOG.warn("serviceVersionInfo does not exist. name=" + tagServiceDbObj.getName()); - } - } + public void deleteServiceDef(Long serviceDefId, Boolean forceDelete) throws Exception { + LOG.debug("==> ServiceDBStore.deleteServiceDef({}, {})", serviceDefId, forceDelete); - if (isDeltaEnabled) { - ret = getServicePoliciesWithDeltas(serviceDef, serviceDbObj, tagServiceDef, tagServiceDbObj, lastKnownVersion, maxNeededVersion); - } + bizUtil.blockAuditorRoleUser(); - if (ret != null) { - ret.setPolicyUpdateTime(serviceVersionInfoDbObj == null ? null : serviceVersionInfoDbObj.getPolicyUpdateTime()); - ret.setAuditMode(auditMode); - if (ret.getTagPolicies() != null) { - ret.getTagPolicies().setPolicyUpdateTime(tagServiceVersionInfoDbObj == null ? null : tagServiceVersionInfoDbObj.getPolicyUpdateTime()); - ret.getTagPolicies().setAuditMode(auditMode); - } - } else if (!getOnlyDeltas) { - ServicePolicies.TagPolicies tagPolicies = null; + UserSessionBase session = ContextUtil.getCurrentUserSession(); - if (tagServiceDbObj != null) { - tagPolicies = new ServicePolicies.TagPolicies(); - - tagPolicies.setServiceId(tagServiceDbObj.getId()); - tagPolicies.setServiceName(tagServiceDbObj.getName()); - tagPolicies.setPolicyVersion(tagServiceVersionInfoDbObj == null ? null : tagServiceVersionInfoDbObj.getPolicyVersion()); - tagPolicies.setPolicyUpdateTime(tagServiceVersionInfoDbObj == null ? null : tagServiceVersionInfoDbObj.getPolicyUpdateTime()); - tagPolicies.setPolicies(getServicePoliciesFromDb(tagServiceDbObj)); - tagPolicies.setServiceDef(tagServiceDef); - tagPolicies.setAuditMode(auditMode); - } + if (session == null) { + throw restErrorUtil.createRESTException("UserSession cannot be null, only Admin can update service-def", MessageEnums.OPER_NO_PERMISSION); + } - List policies = getServicePoliciesFromDb(serviceDbObj); + if (!session.isKeyAdmin() && !session.isUserAdmin()) { + throw restErrorUtil.createRESTException("User is not allowed to update service-def, only Admin can update service-def", MessageEnums.OPER_NO_PERMISSION); + } - ret = new ServicePolicies(); + RangerServiceDef serviceDef = getServiceDef(serviceDefId); - ret.setServiceId(serviceDbObj.getId()); - ret.setServiceName(serviceDbObj.getName()); - ret.setPolicyVersion(serviceVersionInfoDbObj == null ? null : serviceVersionInfoDbObj.getPolicyVersion()); - ret.setPolicyUpdateTime(serviceVersionInfoDbObj == null ? null : serviceVersionInfoDbObj.getPolicyUpdateTime()); - ret.setPolicies(policies); - ret.setServiceDef(serviceDef); - ret.setAuditMode(auditMode); - ret.setTagPolicies(tagPolicies); - } + if (serviceDef == null) { + throw restErrorUtil.createRESTException("No Service Definiton found for Id: " + serviceDefId, MessageEnums.DATA_NOT_FOUND); + } - if (LOG.isDebugEnabled()) { - LOG.debug("<== ServiceDBStore.getServicePolicies(" + serviceName + ", " + lastKnownVersion + "): count=" + ((ret == null || ret.getPolicies() == null) ? 0 : ret.getPolicies().size()) + ", delta-count=" + ((ret == null || ret.getPolicyDeltas() == null) ? 0 : ret.getPolicyDeltas().size())); - } + List serviceList = daoMgr.getXXService().findByServiceDefId(serviceDefId); - return ret; - } + if (!forceDelete) { + if (CollectionUtils.isNotEmpty(serviceList)) { + throw restErrorUtil.createRESTException("Services exists under given service definition, can't delete Service-Def: " + serviceDef.getName(), MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY); + } + } - public boolean resetPolicyCache(final String serviceName) { - if (LOG.isDebugEnabled()) { - LOG.debug("==> ServiceDBStore.resetPolicyCache(" + serviceName + ")"); + if (CollectionUtils.isNotEmpty(serviceList)) { + for (XXService service : serviceList) { + deleteService(service.getId()); + } } - boolean ret = RangerServicePoliciesCache.getInstance().resetCache(serviceName); + XXDataMaskTypeDefDao dataMaskDao = daoMgr.getXXDataMaskTypeDef(); + List dataMaskDefs = dataMaskDao.findByServiceDefId(serviceDefId); - if (LOG.isDebugEnabled()) { - LOG.debug("<== ServiceDBStore.resetPolicyCache(): ret=" + ret); + for (XXDataMaskTypeDef dataMaskDef : dataMaskDefs) { + dataMaskDao.remove(dataMaskDef); } - return ret; - } + List accTypeDefs = daoMgr.getXXAccessTypeDef().findByServiceDefId(serviceDefId); - private static class RangerPolicyDeltaComparator implements Comparator, java.io.Serializable { - @Override - public int compare(RangerPolicyDelta me, RangerPolicyDelta other) { - return Long.compare(me.getId(), other.getId()); - } - } - - private static final Comparator POLICY_DELTA_ID_COMPARATOR = new RangerPolicyDeltaComparator(); - - private static List compressDeltas(List deltas) { - List ret = new ArrayList<>(); - - final Map> policyDeltaMap = new HashMap<>(); - - for (RangerPolicyDelta delta : deltas) { - Long policyId = delta.getPolicyId(); - List oldPolicyDeltas = policyDeltaMap.get(policyId); - - if (oldPolicyDeltas == null) { - oldPolicyDeltas = new ArrayList<>(); - policyDeltaMap.put(policyId, oldPolicyDeltas); - } - oldPolicyDeltas.add(delta); - } - - for (Map.Entry> entry : policyDeltaMap.entrySet()) { - List policyDeltas = entry.getValue(); - - if (policyDeltas.size() == 1) { - ret.addAll(policyDeltas); - } else { // Will always be greater than 1 - List policyDeltasForPolicy = new ArrayList<>(); - RangerPolicyDelta first = policyDeltas.get(0); - - policyDeltasForPolicy.add(first); - - int index = 1; - - switch (first.getChangeType()) { - case RangerPolicyDelta.CHANGE_TYPE_POLICY_CREATE: - while (index < policyDeltas.size()) { - RangerPolicyDelta policyDelta = policyDeltas.get(index); - switch (policyDelta.getChangeType()) { - case RangerPolicyDelta.CHANGE_TYPE_POLICY_CREATE: - LOG.error("Multiple policy creates!! [" + policyDelta + "]"); - policyDeltasForPolicy = null; - break; - case RangerPolicyDelta.CHANGE_TYPE_POLICY_UPDATE: - for (int i = index + 1; i < policyDeltas.size(); i++) { - RangerPolicyDelta next = policyDeltas.get(i); - if (next.getChangeType() == RangerPolicyDelta.CHANGE_TYPE_POLICY_UPDATE) { - index = i; - } else { - break; - } - } - policyDeltasForPolicy.clear(); - policyDeltas.get(index).setChangeType(RangerPolicyDelta.CHANGE_TYPE_POLICY_CREATE); - policyDeltasForPolicy.add(policyDeltas.get(index)); - index++; - break; - case RangerPolicyDelta.CHANGE_TYPE_POLICY_DELETE: - if (policyDeltas.size() == index + 1) { - // Last one - policyDeltasForPolicy.clear(); - index++; - } else { - LOG.error("CHANGE_TYPE_POLICY_DELETE should be the last policyDelta, found:[" + policyDeltas.get(index+1) +"]"); - policyDeltasForPolicy = null; - } - break; - default: - break; - } - if (policyDeltasForPolicy == null) { - break; - } - } - break; - case RangerPolicyDelta.CHANGE_TYPE_POLICY_UPDATE: - while (index < policyDeltas.size()) { - RangerPolicyDelta policyDelta = policyDeltas.get(index); - - switch (policyDelta.getChangeType()) { - case RangerPolicyDelta.CHANGE_TYPE_POLICY_CREATE: - LOG.error("Should not get here! policy is created after it is updated!! policy-delta:[" + policyDelta + "]"); - policyDeltasForPolicy = null; - break; - case RangerPolicyDelta.CHANGE_TYPE_POLICY_UPDATE: - for (int i = index + 1; i < policyDeltas.size(); i++) { - RangerPolicyDelta next = policyDeltas.get(i); - if (next.getChangeType() == RangerPolicyDelta.CHANGE_TYPE_POLICY_UPDATE) { - index = i; - } else { - break; - } - } - policyDeltasForPolicy.clear(); - policyDeltasForPolicy.add(policyDeltas.get(index)); - index++; - break; - case RangerPolicyDelta.CHANGE_TYPE_POLICY_DELETE: - if (policyDeltas.size() == index + 1) { - // Last one - policyDeltasForPolicy.clear(); - policyDeltasForPolicy.add(policyDeltas.get(index)); - index++; - } else { - LOG.error("CHANGE_TYPE_POLICY_DELETE should be the last policyDelta, found:[" + policyDeltas.get(index+1) +"]"); - policyDeltasForPolicy = null; - } - break; - default: - break; - } - if (policyDeltasForPolicy == null) { - break; - } - } - break; - case RangerPolicyDelta.CHANGE_TYPE_POLICY_DELETE: - LOG.error("CHANGE_TYPE_POLICY_DELETE should be the last policyDelta, found:[" + policyDeltas.get(index) +"]"); - policyDeltasForPolicy = null; - break; - default: - LOG.error("Should not get here for valid policy-delta:[" + first + "]"); - break; - } - if (policyDeltasForPolicy != null) { - if (LOG.isDebugEnabled()) { - LOG.debug("Processed deltas for policy:[" + entry.getKey() + "], compressed-deltas:[" + policyDeltasForPolicy + "]"); - } - ret.addAll(policyDeltasForPolicy); - } else { - LOG.error("Error processing deltas for policy:[" + entry.getKey() + "], Cannot compress deltas"); - ret = null; - break; - } - } - } - - if (ret != null) { - ret.sort(POLICY_DELTA_ID_COMPARATOR); - } - - return ret; - - } - - ServicePolicies getServicePoliciesWithDeltas(RangerServiceDef serviceDef, XXService service, RangerServiceDef tagServiceDef, XXService tagService, Long lastKnownVersion, Long maxNeededVersion) { - ServicePolicies ret = null; - - // if lastKnownVersion != -1L : try and get deltas. Get delta for serviceName first. Find id of the delta - // returned first in the list. and then find all ids greater than that for corresponding tag service. - if (LOG.isDebugEnabled()) { - LOG.debug("==> ServiceDBStore.getServicePoliciesWithDeltas(serviceType=" + serviceDef.getName() + ", serviceId=" + service.getId() - +", tagServiceId=" + (tagService != null ? tagService.getId() : null) + ", lastKnownVersion=" + lastKnownVersion + ")"); - } - if (lastKnownVersion != -1L) { - - List resourcePolicyDeltas; - List tagPolicyDeltas = null; - List gdsPolicyDeltas = null; - Long retrievedPolicyVersion = null; - Long retrievedTagPolicyVersion = null; - Long retrievedGdsPolicyVersion = null; - - String componentServiceType = serviceDef.getName(); - - boolean isValid; - - resourcePolicyDeltas = daoMgr.getXXPolicyChangeLog().findLaterThan(lastKnownVersion, maxNeededVersion, service.getId()); - if (CollectionUtils.isNotEmpty(resourcePolicyDeltas)) { - isValid = RangerPolicyDeltaUtil.isValidDeltas(resourcePolicyDeltas, componentServiceType); - - if (isValid) { - retrievedPolicyVersion = resourcePolicyDeltas.get(resourcePolicyDeltas.size() - 1).getPoliciesVersion(); - } else { - LOG.warn("Resource policy-Deltas :[" + resourcePolicyDeltas + "] from version :[" + lastKnownVersion + "] are not valid"); - } - - if (isValid && tagService != null) { - Long id = resourcePolicyDeltas.get(0).getId(); - tagPolicyDeltas = daoMgr.getXXPolicyChangeLog().findGreaterThan(id, maxNeededVersion, tagService.getId()); - - if (CollectionUtils.isNotEmpty(tagPolicyDeltas)) { - String tagServiceType = tagServiceDef.getName(); - - isValid = RangerPolicyDeltaUtil.isValidDeltas(tagPolicyDeltas, tagServiceType); - - if (isValid) { - retrievedTagPolicyVersion = tagPolicyDeltas.get(tagPolicyDeltas.size() - 1).getPoliciesVersion(); - } else { - LOG.warn("Tag policy-Deltas :[" + tagPolicyDeltas + "] for service-version :[" + lastKnownVersion + "] and delta-id :[" + id + "] are not valid"); - } - } - } - - if (isValid) { - if (CollectionUtils.isNotEmpty(tagPolicyDeltas)) { - // To ensure that resource-policy-deltas with service-type of 'tag' are ignored after validation - resourcePolicyDeltas.removeIf(rangerPolicyDelta -> StringUtils.equals(EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_TAG_NAME, rangerPolicyDelta.getServiceType())); - - resourcePolicyDeltas.addAll(tagPolicyDeltas); - } - - List compressedDeltas = compressDeltas(resourcePolicyDeltas); - - if (compressedDeltas != null) { - ret = new ServicePolicies(); - ret.setServiceId(service.getId()); - ret.setServiceName(service.getName()); - ret.setServiceDef(serviceDef); - ret.setPolicies(null); - ret.setPolicyDeltas(compressedDeltas); - ret.setPolicyVersion(retrievedPolicyVersion); - - if (tagServiceDef != null && tagService != null) { - ServicePolicies.TagPolicies tagPolicies = new ServicePolicies.TagPolicies(); - tagPolicies.setServiceDef(tagServiceDef); - tagPolicies.setServiceId(tagService.getId()); - tagPolicies.setServiceName(tagService.getName()); - tagPolicies.setPolicies(null); - tagPolicies.setPolicyVersion(retrievedTagPolicyVersion); - ret.setTagPolicies(tagPolicies); - } - } else { - LOG.warn("Deltas :[" + resourcePolicyDeltas + "] from version :[" + lastKnownVersion + "] after compressing are null!"); - } - } - } else { - LOG.warn("No policy-deltas found for serviceId=" + service.getId() + ", tagServiceId=" + (tagService != null ? tagService.getId() : null) + ", lastKnownVersion=" + lastKnownVersion + ")"); - } - } - - if (LOG.isDebugEnabled()) { - LOG.debug("<== ServiceDBStore.getServicePoliciesWithDeltas(serviceType=" + serviceDef.getName() + ", serviceId=" + service.getId() - +", tagServiceId=" + (tagService != null ? tagService.getId() : null) + ", lastKnownVersion=" + lastKnownVersion + ") : deltasSize=" + (ret != null && CollectionUtils.isNotEmpty(ret.getPolicyDeltas()) ? ret.getPolicyDeltas().size() : 0)); - } - return ret; - } - - void createDefaultPolicies(RangerService createdService) throws Exception { - - List defaultPolicies = populateDefaultPolicies(createdService); - - if (CollectionUtils.isNotEmpty(defaultPolicies)) { - - for (RangerPolicy defaultPolicy : defaultPolicies) { - createDefaultPolicy(defaultPolicy); - } - } - - } - - public void createZoneDefaultPolicies(Collection serviceNames, RangerSecurityZone zone) throws Exception { - - if (CollectionUtils.isNotEmpty(serviceNames)) { - - for (String serviceName : serviceNames) { - RangerService service = getServiceByName(serviceName); - - if (service != null) { - - List defaultPolicies = populateDefaultPolicies(service); - - if (CollectionUtils.isNotEmpty(defaultPolicies)) { - - String zoneName = zone.getName(); - - for (RangerPolicy defaultPolicy : defaultPolicies) { - - defaultPolicy.setZoneName(zoneName); - - createDefaultPolicy(defaultPolicy); - } - } - } - } - } - } - - public void deleteZonePolicies(Collection serviceNames, Long zoneId) throws Exception { - if (CollectionUtils.isNotEmpty(serviceNames)) { - XXPolicyDao policyDao = daoMgr.getXXPolicy(); - for (String serviceName : serviceNames) { - RangerService service = getServiceByName(serviceName); - List policyIds = policyDao.findPolicyIdsByServiceNameAndZoneId(serviceName, zoneId); - if (CollectionUtils.isNotEmpty(policyIds)) { - List rangerPolicyList = new ArrayList<>(); - for (Long id : policyIds) { - rangerPolicyList.add(getPolicy(id)); - } - long totalDeletedPolicies = 0; - for (RangerPolicy rangerPolicy : rangerPolicyList) { - deletePolicy(rangerPolicy, service); - totalDeletedPolicies = totalDeletedPolicies + 1; - if (totalDeletedPolicies % RangerBizUtil.POLICY_BATCH_SIZE == 0) { - bizUtil.bulkModeOnlyFlushAndClear(); - } - } - bizUtil.bulkModeOnlyFlushAndClear(); - } - } - } - } - - List populateDefaultPolicies(RangerService service) throws Exception { - - List ret = null; - - RangerBaseService svc = serviceMgr.getRangerServiceByService(service, this); - - if (svc != null) { - - List serviceCheckUsers = getServiceCheckUsers(service); - List users = new ArrayList<>(); - - /*Need to create ambari service check user before initiating policy creation. */ - if(serviceCheckUsers != null){ - for (String userName : serviceCheckUsers) { - if(!StringUtils.isEmpty(userName)){ - XXUser xxUser = daoMgr.getXXUser().findByUserName(userName); - if (xxUser != null) { - VXUser vXUser = xUserService.populateViewBean(xxUser); - } else { - xUserMgr.createServiceConfigUser(userName); - LOG.info("Creating Ambari Service Check User : "+ userName); - } - users.add(userName); - } - } - } + for (XXAccessTypeDef accessType : accTypeDefs) { + deleteXXAccessTypeDef(accessType); + } - List defaultPolicies = svc.getDefaultRangerPolicies(); - - if (CollectionUtils.isNotEmpty(defaultPolicies)) { - - createDefaultPolicyUsersAndGroups(defaultPolicies); - - for (RangerPolicy defaultPolicy : defaultPolicies) { - if (CollectionUtils.isNotEmpty(users) && StringUtils.equalsIgnoreCase(defaultPolicy.getService(), service.getName())) { - RangerPolicyItem defaultAllowPolicyItem = CollectionUtils.isNotEmpty(defaultPolicy.getPolicyItems()) ? defaultPolicy.getPolicyItems().get(0) : null; - - if (defaultAllowPolicyItem == null) { - LOG.error("There is no allow-policy-item in the default-policy:[" + defaultPolicy + "]"); - } else { - RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem(); - - policyItem.setUsers(users); - policyItem.setAccesses(defaultAllowPolicyItem.getAccesses()); - policyItem.setDelegateAdmin(true); - - defaultPolicy.addPolicyItem(policyItem); - } - } - - boolean isPolicyItemValid = validatePolicyItems(defaultPolicy.getPolicyItems()) - && validatePolicyItems(defaultPolicy.getDenyPolicyItems()) - && validatePolicyItems(defaultPolicy.getAllowExceptions()) - && validatePolicyItems(defaultPolicy.getDenyExceptions()) - && validatePolicyItems(defaultPolicy.getDataMaskPolicyItems()) - && validatePolicyItems(defaultPolicy.getRowFilterPolicyItems()); - - if (isPolicyItemValid) { - if (ret == null) { - ret = new ArrayList<>(); - } - ret.add(defaultPolicy); - } else { - LOG.warn("Default policy won't be created,since policyItems not valid-either users/groups not present or access not present in policy."); - } - } - } - } - return ret; - } - - void createDefaultPolicyUsersAndGroups(List defaultPolicies) { - Set defaultPolicyUsers = new HashSet<>(); - Set defaultPolicyGroups = new HashSet<>(); - - for (RangerPolicy defaultPolicy : defaultPolicies) { - - for (RangerPolicyItem defaultPolicyItem : defaultPolicy.getPolicyItems()) { - defaultPolicyUsers.addAll(defaultPolicyItem.getUsers()); - defaultPolicyGroups.addAll(defaultPolicyItem.getGroups()); - } - for (RangerPolicyItem defaultPolicyItem : defaultPolicy.getAllowExceptions()) { - defaultPolicyUsers.addAll(defaultPolicyItem.getUsers()); - defaultPolicyGroups.addAll(defaultPolicyItem.getGroups()); - } - for (RangerPolicyItem defaultPolicyItem : defaultPolicy.getDenyPolicyItems()) { - defaultPolicyUsers.addAll(defaultPolicyItem.getUsers()); - defaultPolicyGroups.addAll(defaultPolicyItem.getGroups()); - } - for (RangerPolicyItem defaultPolicyItem : defaultPolicy.getDenyExceptions()) { - defaultPolicyUsers.addAll(defaultPolicyItem.getUsers()); - defaultPolicyGroups.addAll(defaultPolicyItem.getGroups()); - } - for (RangerPolicyItem defaultPolicyItem : defaultPolicy.getDataMaskPolicyItems()) { - defaultPolicyUsers.addAll(defaultPolicyItem.getUsers()); - defaultPolicyGroups.addAll(defaultPolicyItem.getGroups()); - } - for (RangerPolicyItem defaultPolicyItem : defaultPolicy.getRowFilterPolicyItems()) { - defaultPolicyUsers.addAll(defaultPolicyItem.getUsers()); - defaultPolicyGroups.addAll(defaultPolicyItem.getGroups()); - } - } - for (String policyUser : defaultPolicyUsers) { - if (LOG.isDebugEnabled()) { - LOG.debug("Checking policyUser:[" + policyUser + "] for existence"); - } - if (StringUtils.isNotBlank(policyUser) && !StringUtils.equals(policyUser, RangerPolicyEngine.USER_CURRENT) - && !StringUtils.equals(policyUser, RangerPolicyEngine.RESOURCE_OWNER)) { - String userName = stringUtil.getValidUserName(policyUser); - XXUser xxUser = daoMgr.getXXUser().findByUserName(userName); - if (xxUser == null) { - UserSessionBase usb = ContextUtil.getCurrentUserSession(); - if (usb != null && !usb.isKeyAdmin() && !usb.isUserAdmin() && !usb.isSpnegoEnabled()) { - throw restErrorUtil.createRESTException("User does not exist with given username: [" - + policyUser + "] please use existing user", MessageEnums.OPER_NO_PERMISSION); - } - xUserMgr.createServiceConfigUser(userName); - } - } - } - for (String policyGroup : defaultPolicyGroups) { - if (LOG.isDebugEnabled()) { - LOG.debug("Checking policyGroup:[" + policyGroup + "] for existence"); - } - if (StringUtils.isNotBlank(policyGroup)) { - XXGroup xxGroup = daoMgr.getXXGroup().findByGroupName(policyGroup); - if (xxGroup == null) { - UserSessionBase usb = ContextUtil.getCurrentUserSession(); - if (usb != null && !usb.isKeyAdmin() && !usb.isUserAdmin() && !usb.isSpnegoEnabled()) { - throw restErrorUtil.createRESTException("Group does not exist with given groupname: [" - + policyGroup + "] please use existing group", MessageEnums.OPER_NO_PERMISSION); - } - VXGroup vXGroup = new VXGroup(); - vXGroup.setName(policyGroup); - vXGroup.setDescription(policyGroup); - vXGroup.setGroupSource(RangerCommonEnums.GROUP_INTERNAL); - vXGroup.setIsVisible(RangerCommonEnums.IS_VISIBLE); - VXGroup createdVXGrp = xGroupService.createResource(vXGroup); - xGroupService.createTransactionLog(createdVXGrp, null, OPERATION_CREATE_CONTEXT); - } - } - } - } - - List getServiceCheckUsers(RangerService createdService) { - List ret = new ArrayList<>(); - String userNames =""; - - Map serviceConfig = createdService.getConfigs(); - - if (serviceConfig.containsKey(SERVICE_CHECK_USER)) { - userNames = serviceConfig.get(SERVICE_CHECK_USER); - } else if (serviceConfig.containsKey(AMBARI_SERVICE_CHECK_USER)) { - userNames = serviceConfig.get(AMBARI_SERVICE_CHECK_USER); - } - - if (!StringUtils.isEmpty(userNames)) { - String[] userList = userNames.split(","); - for (String userName : userList) { - if (!StringUtils.isEmpty(userName)) { - ret.add(userName.trim()); - } - } - } - return ret; - } - - private Map validateRequiredConfigParams(RangerService service, Map configs) { - if(LOG.isDebugEnabled()) { - LOG.debug("==> ServiceDBStore.validateRequiredConfigParams()"); - } - if(configs == null) { - return null; - } - - List svcConfDefList = daoMgr.getXXServiceConfigDef() - .findByServiceDefName(service.getType()); - for(XXServiceConfigDef svcConfDef : svcConfDefList ) { - String confField = configs.get(svcConfDef.getName()); - - if(svcConfDef.getIsMandatory() && stringUtil.isEmpty(confField)) { - throw restErrorUtil.createRESTException( - "Please provide value of mandatory: "+ svcConfDef.getName(), - MessageEnums.INVALID_INPUT_DATA); - } - - if (StringUtils.equals(svcConfDef.getName(), RANGER_PLUGIN_AUDIT_FILTERS)) { - if (svcConfDef.getDefaultvalue() != null && !configs.containsKey(RANGER_PLUGIN_AUDIT_FILTERS)) { - configs.put(RANGER_PLUGIN_AUDIT_FILTERS, svcConfDef.getDefaultvalue()); - } - if (!stringUtil.isEmpty(configs.get(RANGER_PLUGIN_AUDIT_FILTERS)) && JsonUtils.jsonToAuditFilterList(configs.get(RANGER_PLUGIN_AUDIT_FILTERS)) == null) { - throw restErrorUtil.createRESTException("Invalid value for " + svcConfDef.getName()); - } - } - } - Map validConfigs = new HashMap<>(); - for(Entry config : configs.entrySet()) { - if(!stringUtil.isEmpty(config.getValue())) { - validConfigs.put(config.getKey(), config.getValue()); - } - } - return validConfigs; - } - - private void handlePolicyUpdate(RangerService service, Integer policyDeltaType, RangerPolicy policy, boolean updateServiceInfoRoleVersion) throws Exception { - updatePolicyVersion(service, policyDeltaType, policy, updateServiceInfoRoleVersion); - } - - public enum VERSION_TYPE { POLICY_VERSION, TAG_VERSION, ROLE_VERSION, GDS_VERSION } - - private void updatePolicyVersion(RangerService service, Integer policyDeltaType, RangerPolicy policy, boolean updateServiceInfoRoleVersion) throws Exception { - if(service == null || service.getId() == null) { - return; - } - - XXServiceDao serviceDao = daoMgr.getXXService(); - - final XXService serviceDbObj = serviceDao.getById(service.getId()); - if(serviceDbObj == null) { - LOG.warn("updatePolicyVersion(serviceId=" + service.getId() + "): service not found"); - - return; - } - - final RangerDaoManager daoManager = daoMgr; - final Long serviceId = serviceDbObj.getId(); - - // if this is a tag/gds service, update all services that refer to this service - // so that next policy-download from plugins will get updated tag/gds policies - boolean isTagService = serviceDbObj.getType() == EmbeddedServiceDefsUtil.instance().getTagServiceDefId(); - - if (isTagService) { - List referringServiceIds = serviceDao.findIdsByTagServiceId(serviceId); - - for (Long referringServiceId : referringServiceIds) { - Runnable policyVersionUpdater = new ServiceVersionUpdater(daoManager, referringServiceId, VERSION_TYPE.POLICY_VERSION, policy != null ? policy.getZoneName() : null, policyDeltaType, policy); - transactionSynchronizationAdapter.executeOnTransactionCommit(policyVersionUpdater); - - if (updateServiceInfoRoleVersion) { - Runnable roleVersionUpdater = new ServiceVersionUpdater(daoManager, referringServiceId, VERSION_TYPE.ROLE_VERSION, policy != null ? policy.getZoneName() : null, policyDeltaType, policy); - transactionSynchronizationAdapter.executeOnTransactionCommit(roleVersionUpdater); - } - } - } - - final VERSION_TYPE versionType = VERSION_TYPE.POLICY_VERSION; - - Runnable serviceVersionUpdater = new ServiceVersionUpdater(daoManager, serviceId, versionType, policy != null ? policy.getZoneName() : null, policyDeltaType, policy); - transactionSynchronizationAdapter.executeOnTransactionCommit(serviceVersionUpdater); - - if (updateServiceInfoRoleVersion) { - Runnable roleVersionUpdater = new ServiceVersionUpdater(daoManager, serviceId, VERSION_TYPE.ROLE_VERSION, policy != null ? policy.getZoneName() : null, policyDeltaType, policy); - transactionSynchronizationAdapter.executeOnTransactionCommit(roleVersionUpdater); - } - } - - public static void persistVersionChange(ServiceVersionUpdater serviceVersionUpdater) { - RangerDaoManager daoMgr = serviceVersionUpdater.daoManager; - Long id = serviceVersionUpdater.serviceId; - VERSION_TYPE versionType = serviceVersionUpdater.versionType; - - XXServiceVersionInfoDao serviceVersionInfoDao = daoMgr.getXXServiceVersionInfo(); - - XXServiceVersionInfo serviceVersionInfoDbObj = serviceVersionInfoDao.findByServiceId(id); - XXService service = daoMgr.getXXService().getById(id); - - Long nextVersion = 1L; - Date now = new Date(); - - if (serviceVersionInfoDbObj != null) { - if (versionType == VERSION_TYPE.POLICY_VERSION) { - nextVersion = getNextVersion(serviceVersionInfoDbObj.getPolicyVersion()); - serviceVersionInfoDbObj.setPolicyVersion(nextVersion); - serviceVersionInfoDbObj.setPolicyUpdateTime(now); - } else if (versionType == VERSION_TYPE.TAG_VERSION) { - nextVersion = getNextVersion(serviceVersionInfoDbObj.getTagVersion()); - serviceVersionInfoDbObj.setTagVersion(nextVersion); - serviceVersionInfoDbObj.setTagUpdateTime(now); - } else if(versionType == VERSION_TYPE.ROLE_VERSION) { - // get the LatestRoleVersion from the GlobalTable and update ServiceInfo for a service - XXGlobalStateDao xxGlobalStateDao = daoMgr.getXXGlobalState(); - if (xxGlobalStateDao != null) { - Long roleVersion = xxGlobalStateDao.getAppDataVersion("RangerRole"); - if (roleVersion != null) { - nextVersion = roleVersion; - } else { - LOG.error("No Global state for 'RoleVersion'. Cannot execute this object:[" + serviceVersionUpdater + "]"); - } - serviceVersionInfoDbObj.setRoleVersion(nextVersion); - serviceVersionInfoDbObj.setRoleUpdateTime(now); - } else { - LOG.error("No Global state DAO. Cannot execute this object:[" + serviceVersionUpdater + "]"); - return; - } - } else if (versionType == VERSION_TYPE.GDS_VERSION) { - nextVersion = daoMgr.getXXGlobalState().getAppDataVersion(RANGER_GLOBAL_STATE_NAME_GDS); - - if (nextVersion == null) { - nextVersion = 1L; - } - - serviceVersionInfoDbObj.setGdsVersion(nextVersion); - serviceVersionInfoDbObj.setGdsUpdateTime(now); - } else { - LOG.error("Unknown VERSION_TYPE:" + versionType + ". Cannot execute this object:[" + serviceVersionUpdater + "]"); - return; - } - - serviceVersionUpdater.version = nextVersion; - serviceVersionInfoDao.update(serviceVersionInfoDbObj); - } else { - if (service != null) { - serviceVersionInfoDbObj = new XXServiceVersionInfo(); - serviceVersionInfoDbObj.setServiceId(service.getId()); - serviceVersionInfoDbObj.setPolicyVersion(nextVersion); - serviceVersionInfoDbObj.setPolicyUpdateTime(now); - serviceVersionInfoDbObj.setTagVersion(nextVersion); - serviceVersionInfoDbObj.setTagUpdateTime(now); - serviceVersionInfoDbObj.setRoleVersion(nextVersion); - serviceVersionInfoDbObj.setRoleUpdateTime(now); - serviceVersionInfoDbObj.setGdsVersion(nextVersion); - serviceVersionInfoDbObj.setGdsUpdateTime(now); - - serviceVersionUpdater.version = nextVersion; - serviceVersionInfoDao.create(serviceVersionInfoDbObj); - } - } - - if (service != null) { - if (versionType == VERSION_TYPE.POLICY_VERSION) { - persistChangeLog(service, versionType, serviceVersionInfoDbObj.getPolicyVersion(), serviceVersionUpdater); - } else if (versionType == VERSION_TYPE.TAG_VERSION) { - persistChangeLog(service, versionType, serviceVersionInfoDbObj.getTagVersion(), serviceVersionUpdater); - } - } - } - - private boolean isRoleDownloadRequired(RangerPolicy policy, RangerService service) { - // Role Download to plugin is required if some role in the policy created/updated is not present in any other - // policy for that service. - boolean ret = false; - - if (policy != null) { - Set roleNames = getAllPolicyItemRoleNames(policy); - if (CollectionUtils.isNotEmpty(roleNames)) { - Long serviceId = service.getId(); - checkAndFilterRoleNames(roleNames, service); - if (CollectionUtils.isNotEmpty(roleNames)) { - for (String roleName : roleNames) { - long roleRefPolicyCount = daoMgr.getXXPolicy().findRoleRefPolicyCount(roleName, serviceId); - if (roleRefPolicyCount == 0) { - ret = true; - break; - } - } - } - } - } - - return ret; - } - - private void checkAndFilterRoleNames(Set roleNames, RangerService service) { - //remove all roles which are already in DB for this serviceId, so we just download roles if there are new roles added. - Set rolesToRemove = new HashSet<>(); - Long serviceId = service.getId(); - List rolesFromDb = daoMgr.getXXRole().findRoleNamesByServiceId(serviceId); - if(CollectionUtils.isNotEmpty(rolesFromDb)) { - rolesToRemove.addAll(rolesFromDb); - } - - String tagService = service.getTagService(); - XXService serviceDbObj = daoMgr.getXXService().findByName(tagService); - if (serviceDbObj != null) { - List rolesFromServiceTag = daoMgr.getXXRole().findRoleNamesByServiceId(serviceDbObj.getId()); - if (CollectionUtils.isNotEmpty(rolesFromServiceTag)) { - rolesToRemove.addAll(rolesFromServiceTag); - } - } - - roleNames.removeAll(rolesToRemove); - } - - private Set getAllPolicyItemRoleNames(RangerPolicy policy) { - Set ret = new HashSet<>(); - - List policyItems = policy.getPolicyItems(); - if (CollectionUtils.isNotEmpty(policyItems)) { - collectRolesFromPolicyItems(policyItems, ret); - } - - policyItems = policy.getDenyPolicyItems(); - if (CollectionUtils.isNotEmpty(policyItems)) { - collectRolesFromPolicyItems(policyItems, ret); - } - - policyItems = policy.getAllowExceptions(); - if (CollectionUtils.isNotEmpty(policyItems)) { - collectRolesFromPolicyItems(policyItems, ret); - } - - policyItems = policy.getDenyExceptions(); - if (CollectionUtils.isNotEmpty(policyItems)) { - collectRolesFromPolicyItems(policyItems, ret); - } - - policyItems = policy.getDataMaskPolicyItems(); - if (CollectionUtils.isNotEmpty(policyItems)) { - collectRolesFromPolicyItems(policyItems, ret); - } - - policyItems = policy.getRowFilterPolicyItems(); - if (CollectionUtils.isNotEmpty(policyItems)) { - collectRolesFromPolicyItems(policyItems, ret); - } - - return ret; - } - - private void collectRolesFromPolicyItems(List rangerPolicyItems, Set roleNames) { - for (RangerPolicyItem rangerPolicyItem : rangerPolicyItems) { - List rangerPolicyItemRoles = rangerPolicyItem.getRoles(); - if (CollectionUtils.isNotEmpty(rangerPolicyItemRoles)) { - roleNames.addAll(rangerPolicyItemRoles); - } - } - } - - private void persistChangeLog(ServiceVersionUpdater serviceVersionUpdater) { - XXServiceVersionInfoDao serviceVersionInfoDao = serviceVersionUpdater.daoManager.getXXServiceVersionInfo(); - - XXServiceVersionInfo serviceVersionInfoDbObj = serviceVersionInfoDao.findByServiceId(serviceVersionUpdater.serviceId); - XXService service = serviceVersionUpdater.daoManager.getXXService().getById(serviceVersionUpdater.serviceId); - - if (service != null && serviceVersionInfoDao != null) { - Long version = serviceVersionUpdater.versionType == VERSION_TYPE.TAG_VERSION ? serviceVersionInfoDbObj.getTagVersion() : serviceVersionInfoDbObj.getPolicyVersion(); - persistChangeLog(service, serviceVersionUpdater.versionType, version, serviceVersionUpdater); - } - } - - private static void persistChangeLog(XXService service, VERSION_TYPE versionType, Long version, ServiceVersionUpdater serviceVersionUpdater) { - Date now = new Date(); - - if (versionType == VERSION_TYPE.TAG_VERSION) { - ServiceTags.TagsChangeType tagChangeType = serviceVersionUpdater.tagChangeType; - if (tagChangeType == ServiceTags.TagsChangeType.RANGER_ADMIN_START || TagDBStore.isSupportsTagDeltas()) { - // Build and save TagChangeLog - XXTagChangeLog tagChangeLog = new XXTagChangeLog(); - - Long serviceResourceId = serviceVersionUpdater.resourceId; - Long tagId = serviceVersionUpdater.tagId; - - tagChangeLog.setCreateTime(now); - tagChangeLog.setServiceId(service.getId()); - tagChangeLog.setChangeType(tagChangeType.ordinal()); - tagChangeLog.setServiceTagsVersion(version); - tagChangeLog.setServiceResourceId(serviceResourceId); - tagChangeLog.setTagId(tagId); - - serviceVersionUpdater.daoManager.getXXTagChangeLog().create(tagChangeLog); - } - - } else { - Integer policyDeltaChange = serviceVersionUpdater.policyDeltaChange; - - if (policyDeltaChange == RangerPolicyDelta.CHANGE_TYPE_RANGER_ADMIN_START || isSupportsPolicyDeltas()) { - // Build and save PolicyChangeLog - XXPolicyChangeLog policyChangeLog = new XXPolicyChangeLog(); - - policyChangeLog.setCreateTime(now); - policyChangeLog.setServiceId(service.getId()); - policyChangeLog.setChangeType(serviceVersionUpdater.policyDeltaChange); - policyChangeLog.setPolicyVersion(version); - policyChangeLog.setZoneName(serviceVersionUpdater.zoneName); - - RangerPolicy policy = serviceVersionUpdater.policy; - if (policy != null) { - policyChangeLog.setServiceType(policy.getServiceType()); - policyChangeLog.setPolicyType(policy.getPolicyType()); - policyChangeLog.setPolicyId(policy.getId()); - policyChangeLog.setPolicyGuid(policy.getGuid()); - } - - serviceVersionUpdater.daoManager.getXXPolicyChangeLog().create(policyChangeLog); - } - } - - } - - - private Boolean deleteExistingPolicyLabel(RangerPolicy policy) { - if (policy == null) { - return false; - } - - List xxPolicyLabelMaps = daoMgr.getXXPolicyLabelMap().findByPolicyId(policy.getId()); - XXPolicyLabelMapDao policyLabelMapDao = daoMgr.getXXPolicyLabelMap(); - for (XXPolicyLabelMap xxPolicyLabelMap : xxPolicyLabelMaps) { - policyLabelMapDao.remove(xxPolicyLabelMap); - } - return true; - } - - @Override - public Boolean getPopulateExistingBaseFields() { - return populateExistingBaseFields; - } - - @Override - public void setPopulateExistingBaseFields(Boolean populateExistingBaseFields) { - this.populateExistingBaseFields = populateExistingBaseFields; - } - - public RangerPolicy getPolicyFromEventTime(String eventTime, Long policyId) { - - XXDataHist xDataHist = daoMgr.getXXDataHist().findObjByEventTimeClassTypeAndId(eventTime, - AppConstants.CLASS_TYPE_RANGER_POLICY, policyId); - - if (xDataHist == null) { - String errMsg = "No policy history found for given policy ID: " + policyId + " and event time: " + eventTime; - LOG.error(errMsg); - throw restErrorUtil.createRESTException(errMsg, MessageEnums.DATA_NOT_FOUND); - } - - String content = xDataHist.getContent(); - RangerPolicy policy = (RangerPolicy) jsonUtil.writeJsonToJavaObject(content, RangerPolicy.class); - - return policy; - } - - public VXString getPolicyVersionList(Long policyId) { - List versionList = daoMgr.getXXDataHist().getVersionListOfObject(policyId, - AppConstants.CLASS_TYPE_RANGER_POLICY); - - VXString vXString = new VXString(); - vXString.setValue(StringUtils.join(versionList, ",")); - - return vXString; - } - - public RangerPolicy getPolicyForVersionNumber(Long policyId, int versionNo) { - XXDataHist xDataHist = daoMgr.getXXDataHist().findObjectByVersionNumber(policyId, - AppConstants.CLASS_TYPE_RANGER_POLICY, versionNo); - - if (xDataHist == null) { - throw restErrorUtil.createRESTException("No Policy found for given version.", MessageEnums.DATA_NOT_FOUND); - } - - String content = xDataHist.getContent(); - RangerPolicy policy = (RangerPolicy) jsonUtil.writeJsonToJavaObject(content, RangerPolicy.class); - - return policy; - } - - void updatePolicySignature(RangerPolicy policy) { - String guid = policy.getGuid(); - if (StringUtils.isEmpty(guid)) { - guid = guidUtil.genGUID(); - policy.setGuid(guid); - } - RangerPolicyResourceSignature policySignature = factory.createPolicyResourceSignature(policy); - String signature = policySignature.getSignature(); - policy.setResourceSignature(signature); - if (LOG.isDebugEnabled()) { - String message = String.format("Setting signature on policy id=%d, name=%s to [%s]", policy.getId(), policy.getName(), signature); - LOG.debug(message); - } - } - - // when a service-def is updated, the updated service-def should be made available to plugins - // this is achieved by incrementing policyVersion of all services of this service-def - protected void updateServicesForServiceDefUpdate(RangerServiceDef serviceDef) throws Exception { - if(serviceDef == null) { - return; - } - - final RangerDaoManager daoManager = daoMgr; - - boolean isTagServiceDef = StringUtils.equals(serviceDef.getName(), EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_TAG_NAME); - - XXServiceDao serviceDao = daoMgr.getXXService(); - - List services = serviceDao.findByServiceDefId(serviceDef.getId()); - - if(CollectionUtils.isNotEmpty(services)) { - for(XXService service : services) { - - if(isTagServiceDef) { - List referringServices = serviceDao.findByTagServiceId(service.getId()); - - if(CollectionUtils.isNotEmpty(referringServices)) { - for(XXService referringService : referringServices) { - - final Long referringServiceId = referringService.getId(); - final VERSION_TYPE tagServiceVersionType = VERSION_TYPE.POLICY_VERSION; - - Runnable tagServiceVersionUpdater = new ServiceVersionUpdater(daoManager, referringServiceId, tagServiceVersionType, RangerPolicyDelta.CHANGE_TYPE_SERVICE_DEF_CHANGE); - transactionSynchronizationAdapter.executeOnTransactionCommit(tagServiceVersionUpdater); - } - } - } - - final Long serviceId = service.getId(); - final VERSION_TYPE versionType = VERSION_TYPE.POLICY_VERSION; - - Runnable serviceVersionUpdater = new ServiceVersionUpdater(daoManager, serviceId, versionType, RangerPolicyDelta.CHANGE_TYPE_SERVICE_DEF_CHANGE); - transactionSynchronizationAdapter.executeOnTransactionCommit(serviceVersionUpdater); - } - } - } - - @Override - public RangerSecurityZone getSecurityZone(Long id) throws Exception { - return securityZoneService.read(id); - } - - @Override - public RangerSecurityZone getSecurityZone(String name) throws Exception { - XXSecurityZone xxSecurityZone = daoMgr.getXXSecurityZoneDao().findByZoneName(name); - if (xxSecurityZone != null) { - return getSecurityZone(xxSecurityZone.getId()); - } - return null; - } - - @Override - public long getPoliciesCount(final String serviceName) { - final long ret; - if (StringUtils.isNotBlank(serviceName)) { - ret = daoMgr.getXXPolicy().getPoliciesCount(serviceName); - } else { - ret = 0L; - } - return ret; - } - - - private String getServiceName(Long serviceId) { - String ret = null; - - if(serviceId != null) { - XXService service = daoMgr.getXXService().getById(serviceId); - - if(service != null) { - ret = service.getName(); - } - } - - return ret; - } - - private boolean isAccessTypeInList(String accessType, List xAccessTypeDefs) { - for(XXAccessTypeDef xxAccessTypeDef : xAccessTypeDefs) { - if(StringUtils.equals(xxAccessTypeDef.getName(), accessType)) { - return true; - } - } - - return false; - } - - private boolean isResourceInList(String resource, List xResourceDefs) { - for(XXResourceDef xResourceDef : xResourceDefs) { - if(StringUtils.equals(xResourceDef.getName(), resource)) { - return true; - } - } - - return false; - } - - private void writeExcel(List policies, String excelFileName, HttpServletResponse response) throws IOException { - OutputStream outStream = null; - try (Workbook workbook = new HSSFWorkbook()) { - Sheet sheet = workbook.createSheet(); - createHeaderRow(sheet); - int rowCount = 0; - if (!CollectionUtils.isEmpty(policies)) { - Map svcNameToSvcType = new HashMap<>(); - for (RangerPolicy policy : policies) { - - List policyItems = policy.getPolicyItems(); - List rowFilterPolicyItems = policy.getRowFilterPolicyItems(); - List dataMaskPolicyItems = policy.getDataMaskPolicyItems(); - List allowExceptions = policy.getAllowExceptions(); - List denyExceptions = policy.getDenyExceptions(); - List denyPolicyItems = policy.getDenyPolicyItems(); - - String serviceType = policy.getServiceType(); - if (StringUtils.isBlank(serviceType)) { - serviceType = svcNameToSvcType.get(policy.getService()); - if (StringUtils.isBlank(serviceType)) { - serviceType = daoMgr.getXXServiceDef().findServiceDefTypeByServiceName(policy.getService()); - if (StringUtils.isNotBlank(serviceType)) { - svcNameToSvcType.put(policy.getService(), serviceType); - } - } - } - - if (CollectionUtils.isNotEmpty(policyItems)) { - for (RangerPolicyItem policyItem : policyItems) { - Row row = sheet.createRow(++rowCount); - writeBookForPolicyItems(svcNameToSvcType, policy, policyItem, null, null, row, POLICY_ALLOW_INCLUDE); - } - } else if (CollectionUtils.isNotEmpty(dataMaskPolicyItems)) { - for (RangerDataMaskPolicyItem dataMaskPolicyItem : dataMaskPolicyItems) { - Row row = sheet.createRow(++rowCount); - writeBookForPolicyItems(svcNameToSvcType, policy, null, dataMaskPolicyItem, null, row, null); - } - } else if (CollectionUtils.isNotEmpty(rowFilterPolicyItems)) { - for (RangerRowFilterPolicyItem rowFilterPolicyItem : rowFilterPolicyItems) { - Row row = sheet.createRow(++rowCount); - writeBookForPolicyItems(svcNameToSvcType, policy, null, null, rowFilterPolicyItem, row, null); - } - } else if (serviceType.equalsIgnoreCase(EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_TAG_NAME)) { - if (CollectionUtils.isEmpty(policyItems)) { - Row row = sheet.createRow(++rowCount); - RangerPolicyItem policyItem = new RangerPolicyItem(); - writeBookForPolicyItems(svcNameToSvcType, policy, policyItem, null, null, row, POLICY_ALLOW_INCLUDE); - } - } else if (CollectionUtils.isEmpty(policyItems)) { - Row row = sheet.createRow(++rowCount); - RangerPolicyItem policyItem = new RangerPolicyItem(); - writeBookForPolicyItems(svcNameToSvcType, policy, policyItem, null, null, row, POLICY_ALLOW_INCLUDE); - } - if (CollectionUtils.isNotEmpty(allowExceptions)) { - for (RangerPolicyItem policyItem : allowExceptions) { - Row row = sheet.createRow(++rowCount); - writeBookForPolicyItems(svcNameToSvcType, policy, policyItem, null, null, row, POLICY_ALLOW_EXCLUDE); - } - } - if (CollectionUtils.isNotEmpty(denyExceptions)) { - for (RangerPolicyItem policyItem : denyExceptions) { - Row row = sheet.createRow(++rowCount); - writeBookForPolicyItems(svcNameToSvcType, policy, policyItem, null, null, row, POLICY_DENY_EXCLUDE); - } - } - if (CollectionUtils.isNotEmpty(denyPolicyItems)) { - for (RangerPolicyItem policyItem : denyPolicyItems) { - Row row = sheet.createRow(++rowCount); - writeBookForPolicyItems(svcNameToSvcType, policy, policyItem, null, null, row, POLICY_DENY_INCLUDE); - } - } - } - } - ByteArrayOutputStream outByteStream = new ByteArrayOutputStream(); - workbook.write(outByteStream); - byte[] outArray = outByteStream.toByteArray(); - response.setContentType("application/ms-excel"); - response.setContentLength(outArray.length); - response.setHeader("Expires:", "0"); - response.setHeader("Content-Disposition", "attachment; filename=" + excelFileName); - response.setStatus(HttpServletResponse.SC_OK); - outStream = response.getOutputStream(); - outStream.write(outArray); - outStream.flush(); - } catch (IOException ex) { - LOG.error("Failed to create report file " + excelFileName, ex); - } catch (Exception ex) { - LOG.error("Error while generating report file " + excelFileName, ex); - } finally { - if (outStream != null) { - outStream.close(); - } - } - } - - private StringBuilder writeCSV(List policies, String cSVFileName, HttpServletResponse response) { - response.setContentType("text/csv"); - - final String LINE_SEPARATOR = "\n"; - final String FILE_HEADER = "ID|Name|Resources|Roles|Groups|Users|Accesses|Service Type|Status|Policy Type|Delegate Admin|isRecursive|" - + "isExcludes|Service Name|Description|isAuditEnabled|Policy Conditions|Policy Condition Type|Masking Options|Row Filter Expr|Policy Label Name"; - StringBuilder csvBuffer = new StringBuilder(); - csvBuffer.append(FILE_HEADER); - csvBuffer.append(LINE_SEPARATOR); - if (!CollectionUtils.isEmpty(policies)) { - Map svcNameToSvcType = new HashMap<>(); - for (RangerPolicy policy : policies) { - List policyItems = policy.getPolicyItems(); - List rowFilterPolicyItems = policy.getRowFilterPolicyItems(); - List dataMaskPolicyItems = policy.getDataMaskPolicyItems(); - List allowExceptions = policy.getAllowExceptions(); - List denyExceptions = policy.getDenyExceptions(); - List denyPolicyItems = policy.getDenyPolicyItems(); - - String serviceType = policy.getServiceType(); - if (StringUtils.isBlank(serviceType)) { - serviceType = svcNameToSvcType.get(policy.getService()); - if (StringUtils.isBlank(serviceType)) { - serviceType = daoMgr.getXXServiceDef().findServiceDefTypeByServiceName(policy.getService()); - if (StringUtils.isNotBlank(serviceType)) { - svcNameToSvcType.put(policy.getService(), serviceType); - } - } - } - - if (CollectionUtils.isNotEmpty(policyItems)) { - for (RangerPolicyItem policyItem : policyItems) { - writeCSVForPolicyItems(svcNameToSvcType, policy, policyItem, null, null, csvBuffer, POLICY_ALLOW_INCLUDE); - } - } else if (CollectionUtils.isNotEmpty(dataMaskPolicyItems)) { - for (RangerDataMaskPolicyItem dataMaskPolicyItem : dataMaskPolicyItems) { - writeCSVForPolicyItems(svcNameToSvcType, policy, null, dataMaskPolicyItem, null, csvBuffer, null); - } - } else if (CollectionUtils.isNotEmpty(rowFilterPolicyItems)) { - for (RangerRowFilterPolicyItem rowFilterPolicyItem : rowFilterPolicyItems) { - writeCSVForPolicyItems(svcNameToSvcType, policy, null, null, rowFilterPolicyItem, csvBuffer, null); - } - } else if (serviceType.equalsIgnoreCase(EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_TAG_NAME)) { - if (CollectionUtils.isEmpty(policyItems)) { - RangerPolicyItem policyItem = new RangerPolicyItem(); - writeCSVForPolicyItems(svcNameToSvcType, policy, policyItem, null, null, csvBuffer, POLICY_ALLOW_INCLUDE); - } - } else if (CollectionUtils.isEmpty(policyItems)) { - RangerPolicyItem policyItem = new RangerPolicyItem(); - writeCSVForPolicyItems(svcNameToSvcType, policy, policyItem, null, null, csvBuffer, POLICY_ALLOW_INCLUDE); - } - if (CollectionUtils.isNotEmpty(allowExceptions)) { - for (RangerPolicyItem policyItem : allowExceptions) { - writeCSVForPolicyItems(svcNameToSvcType, policy, policyItem, null, null, csvBuffer, POLICY_ALLOW_EXCLUDE); - } - } - if (CollectionUtils.isNotEmpty(denyExceptions)) { - for (RangerPolicyItem policyItem : denyExceptions) { - writeCSVForPolicyItems(svcNameToSvcType, policy, policyItem, null, null, csvBuffer, POLICY_DENY_EXCLUDE); - } - } - if (CollectionUtils.isNotEmpty(denyPolicyItems)) { - for (RangerPolicyItem policyItem : denyPolicyItems) { - writeCSVForPolicyItems(svcNameToSvcType, policy, policyItem, null, null, csvBuffer, POLICY_DENY_INCLUDE); - } - } - } - } - response.setHeader("Content-Disposition", "attachment; filename=" + cSVFileName); - response.setStatus(HttpServletResponse.SC_OK); - return csvBuffer; - } - - private void writeCSVForPolicyItems(Map svcNameToSvcType, RangerPolicy policy, RangerPolicyItem policyItem, RangerDataMaskPolicyItem dataMaskPolicyItem, RangerRowFilterPolicyItem rowFilterPolicyItem, StringBuilder csvBuffer, String policyConditionType) { - if (LOG.isDebugEnabled()) { - LOG.debug("policyConditionType:[" + policyConditionType + "]"); - } - final String COMMA_DELIMITER = "|"; - final String LINE_SEPARATOR = "\n"; - List roles = new ArrayList<>(); - List groups = new ArrayList<>(); - List users = new ArrayList<>(); - String roleNames = ""; - String groupNames = ""; - String userNames = ""; - String policyLabelName = ""; - String accessType = ""; - String policyStatus = ""; - String policyType = ""; - Boolean delegateAdmin = false; - String isRecursive = ""; - String isExcludes = ""; - String serviceName = ""; - String description = ""; - Boolean isAuditEnabled = true; - String isExcludesValue = ""; - String maskingInfo = ""; - List accesses = new ArrayList(); - List conditionsList = new ArrayList<>(); - String conditionKeyValue = ""; - String resValue = ""; - String resourceKeyVal = ""; - String isRecursiveValue = ""; - String resKey = ""; - String ServiceType = ""; - String filterExpr = ""; - String policyName = ""; - List policyLabels = new ArrayList<>(); - String policyConditionTypeValue = ""; - serviceName = policy.getService(); - description = policy.getDescription(); - isAuditEnabled = policy.getIsAuditEnabled(); - policyLabels = policy.getPolicyLabels(); - StringBuffer sb = new StringBuffer(); - StringBuffer sbIsRecursive = new StringBuffer(); - StringBuffer sbIsExcludes = new StringBuffer(); - Map resources = policy.getResources(); - RangerPolicy.RangerPolicyItemDataMaskInfo dataMaskInfo = new RangerPolicy.RangerPolicyItemDataMaskInfo(); - RangerPolicy.RangerPolicyItemRowFilterInfo filterInfo = new RangerPolicy.RangerPolicyItemRowFilterInfo(); - policyName = policy.getName(); - policyName = policyName.replace("|", ""); - if (resources != null) { - for (Entry resource : resources.entrySet()) { - resKey = resource.getKey(); - RangerPolicyResource policyResource = resource.getValue(); - List resvalueList = policyResource.getValues(); - isExcludes = policyResource.getIsExcludes().toString(); - isRecursive = policyResource.getIsRecursive().toString(); - resValue = resvalueList.toString(); - sb = sb.append(resourceKeyVal).append(" ").append(resKey).append("=").append(resValue); - sbIsExcludes = sbIsExcludes.append(resourceKeyVal).append(" ").append(resKey).append("=[").append(isExcludes).append("]"); - sbIsRecursive = sbIsRecursive.append(resourceKeyVal).append(" ").append(resKey).append("=[").append(isRecursive).append("]"); - } - isExcludesValue = sbIsExcludes.toString(); - isExcludesValue = isExcludesValue.substring(1); - isRecursiveValue = sbIsRecursive.toString(); - isRecursiveValue = isRecursiveValue.substring(1); - resourceKeyVal = sb.toString(); - resourceKeyVal = resourceKeyVal.substring(1); - if (policyItem != null && dataMaskPolicyItem == null && rowFilterPolicyItem == null) { - roles = policyItem.getRoles(); - groups = policyItem.getGroups(); - users = policyItem.getUsers(); - accesses = policyItem.getAccesses(); - delegateAdmin = policyItem.getDelegateAdmin(); - conditionsList = policyItem.getConditions(); - } else if (dataMaskPolicyItem != null && policyItem == null && rowFilterPolicyItem == null) { - roles = dataMaskPolicyItem.getRoles(); - groups = dataMaskPolicyItem.getGroups(); - users = dataMaskPolicyItem.getUsers(); - accesses = dataMaskPolicyItem.getAccesses(); - delegateAdmin = dataMaskPolicyItem.getDelegateAdmin(); - conditionsList = dataMaskPolicyItem.getConditions(); - dataMaskInfo = dataMaskPolicyItem.getDataMaskInfo(); - String dataMaskType = dataMaskInfo.getDataMaskType(); - String conditionExpr = dataMaskInfo.getConditionExpr(); - String valueExpr = dataMaskInfo.getValueExpr(); - maskingInfo = "dataMasktype=[" + dataMaskType + "]"; - if (conditionExpr != null && !conditionExpr.isEmpty() && valueExpr != null && !valueExpr.isEmpty()) { - maskingInfo = maskingInfo + "; conditionExpr=[" + conditionExpr + "]"; - } - } else if (rowFilterPolicyItem != null && policyItem == null && dataMaskPolicyItem == null) { - roles = rowFilterPolicyItem.getRoles(); - groups = rowFilterPolicyItem.getGroups(); - users = rowFilterPolicyItem.getUsers(); - accesses = rowFilterPolicyItem.getAccesses(); - delegateAdmin = rowFilterPolicyItem.getDelegateAdmin(); - conditionsList = rowFilterPolicyItem.getConditions(); - filterInfo = rowFilterPolicyItem.getRowFilterInfo(); - filterExpr = filterInfo.getFilterExpr(); - } - if (CollectionUtils.isNotEmpty(accesses)) { - for (RangerPolicyItemAccess access : accesses) { - if (access != null) { - accessType = accessType + access.getType().replace("#", "").replace("|", "") + "#"; - } - } - if (accessType.length() > 0) { - accessType = accessType.substring(0, accessType.lastIndexOf("#")); - } - } - if (CollectionUtils.isNotEmpty(roles)) { - for (String role : roles) { - if (StringUtils.isNotBlank(role)) { - role = role.replace("|", ""); - role = role.replace("#", ""); - roleNames = roleNames + role + "#"; - } - } - if (roleNames.length() > 0) { - roleNames = roleNames.substring(0, roleNames.lastIndexOf("#")); - } - } - if (CollectionUtils.isNotEmpty(groups)) { - for (String group : groups) { - if (StringUtils.isNotBlank(group)) { - group = group.replace("|", ""); - group = group.replace("#", ""); - groupNames = groupNames + group + "#"; - } - } - if (groupNames.length() > 0) { - groupNames = groupNames.substring(0, groupNames.lastIndexOf("#")); - } - } - if (CollectionUtils.isNotEmpty(users)) { - for (String user : users) { - if (StringUtils.isNotBlank(user)) { - user = user.replace("|", ""); - user = user.replace("#", ""); - userNames = userNames + user + "#"; - } - } - if (userNames.length() > 0) { - userNames = userNames.substring(0, userNames.lastIndexOf("#")); - } - } - String conditionValue = ""; - for (RangerPolicyItemCondition conditions : conditionsList) { - String conditionType = conditions.getType(); - List conditionList = conditions.getValues(); - conditionValue = conditionList.toString(); - conditionKeyValue = conditionType + "=" + conditionValue; - } - - ServiceType = policy.getServiceType(); - if (StringUtils.isBlank(ServiceType)) { - ServiceType = svcNameToSvcType.get(policy.getService()); - if (ServiceType == null) { - ServiceType = ""; - } - } - } - if (policyConditionType != null) { - policyConditionTypeValue = policyConditionType; - } - if (policyConditionType == null && ServiceType.equalsIgnoreCase("tag")) { - policyConditionTypeValue = POLICY_ALLOW_INCLUDE; - } else if (policyConditionType == null) { - policyConditionTypeValue = ""; - } - if (policy.getIsEnabled()) { - policyStatus = "Enabled"; - } else { - policyStatus = "Disabled"; - } - int policyTypeInt = policy.getPolicyType(); - switch (policyTypeInt) { - case RangerPolicy.POLICY_TYPE_ACCESS: - policyType = POLICY_TYPE_ACCESS; - break; - case RangerPolicy.POLICY_TYPE_DATAMASK: - policyType = POLICY_TYPE_DATAMASK; - break; - case RangerPolicy.POLICY_TYPE_ROWFILTER: - policyType = POLICY_TYPE_ROWFILTER; - break; - } - if (CollectionUtils.isNotEmpty(policyLabels)) { - for (String policyLabel : policyLabels) { - if (StringUtils.isNotBlank(policyLabel)) { - policyLabel = policyLabel.replace("|", ""); - policyLabel = policyLabel.replace("#", ""); - policyLabelName = policyLabelName + policyLabel + "#"; - } - } - if (policyLabelName.length() > 0) { - policyLabelName = policyLabelName.substring(0, policyLabelName.lastIndexOf("#")); - } - } - - csvBuffer.append(policy.getId()); - csvBuffer.append(COMMA_DELIMITER); - csvBuffer.append(policyName); - csvBuffer.append(COMMA_DELIMITER); - csvBuffer.append(resourceKeyVal); - csvBuffer.append(COMMA_DELIMITER); - csvBuffer.append(roleNames); - csvBuffer.append(COMMA_DELIMITER); - csvBuffer.append(groupNames); - csvBuffer.append(COMMA_DELIMITER); - csvBuffer.append(userNames); - csvBuffer.append(COMMA_DELIMITER); - csvBuffer.append(accessType.trim()); - csvBuffer.append(COMMA_DELIMITER); - csvBuffer.append(ServiceType); - csvBuffer.append(COMMA_DELIMITER); - csvBuffer.append(policyStatus); - csvBuffer.append(COMMA_DELIMITER); - csvBuffer.append(policyType); - csvBuffer.append(COMMA_DELIMITER); - csvBuffer.append(delegateAdmin.toString().toUpperCase()); - csvBuffer.append(COMMA_DELIMITER); - csvBuffer.append(isRecursiveValue); - csvBuffer.append(COMMA_DELIMITER); - csvBuffer.append(isExcludesValue); - csvBuffer.append(COMMA_DELIMITER); - csvBuffer.append(serviceName); - csvBuffer.append(COMMA_DELIMITER); - csvBuffer.append(description); - csvBuffer.append(COMMA_DELIMITER); - csvBuffer.append(isAuditEnabled.toString().toUpperCase()); - csvBuffer.append(COMMA_DELIMITER); - csvBuffer.append(conditionKeyValue.trim()); - csvBuffer.append(COMMA_DELIMITER); - csvBuffer.append(policyConditionTypeValue); - csvBuffer.append(COMMA_DELIMITER); - csvBuffer.append(maskingInfo); - csvBuffer.append(COMMA_DELIMITER); - csvBuffer.append(filterExpr); - csvBuffer.append(COMMA_DELIMITER); - csvBuffer.append(policyLabelName); - csvBuffer.append(COMMA_DELIMITER); - csvBuffer.append(LINE_SEPARATOR); - } - - public Map getMetaDataInfo() { - Map metaDataInfo = new LinkedHashMap<>(); - UserSessionBase usb = ContextUtil.getCurrentUserSession(); - String userId = usb!=null ? usb.getLoginId() : null; - DateFormat formatter = new SimpleDateFormat("MMM dd, yyyy h:mm:ss a"); - - metaDataInfo.put(HOSTNAME, LOCAL_HOSTNAME); - metaDataInfo.put(USER_NAME, userId); - metaDataInfo.put(TIMESTAMP, formatter.format(MiscUtil.getUTCDateForLocalDate(new Date()))); - metaDataInfo.put(RANGER_VERSION, RangerVersionInfo.getVersion()); - - return metaDataInfo; - } - - private void writeJson(List objList, String jsonFileName, - HttpServletResponse response, JSON_FILE_NAME_TYPE type) throws IOException { - response.setContentType("text/json"); - response.setHeader("Content-Disposition", "attachment; filename="+ jsonFileName); - ServletOutputStream out = null; - - String json = null; - - switch(type) { - case POLICY : - RangerExportPolicyList rangerExportPolicyList = new RangerExportPolicyList(); - rangerExportPolicyList.setGenericPolicies(objList); - rangerExportPolicyList.setMetaDataInfo(getMetaDataInfo()); - json = JsonUtils.objectToJson(rangerExportPolicyList); - break; - case ROLE : - RangerExportRoleList rangerExportRoleList = new RangerExportRoleList(); - rangerExportRoleList.setGenericRoleList(objList); - Map metaDataInfo = getMetaDataInfo(); - metaDataInfo.put(EXPORT_COUNT,rangerExportRoleList.getListSize()); - rangerExportRoleList.setMetaDataInfo(metaDataInfo); - json = JsonUtils.objectToJson(rangerExportRoleList); - break; - default : - throw restErrorUtil.createRESTException("Invalid type "+type); - } - try { - out = response.getOutputStream(); - response.setStatus(HttpServletResponse.SC_OK); - IOUtils.write(json, out, "UTF-8"); - } catch (Exception e) { - LOG.error("Error while exporting json file " + jsonFileName, e); - } finally { - try { - if (out != null) { - out.flush(); - out.close(); - } - } catch (Exception ex) { - } - } - } - - public Map getMapFromInputStream(InputStream mapStream) throws IOException { - if (LOG.isDebugEnabled()) { - LOG.debug("==> ServiceDBStore.getMapFromInputStream()"); - } - Map inputMap = new LinkedHashMap<>(); - String inputMapString = IOUtils.toString(mapStream); - if (StringUtils.isNotEmpty(inputMapString)) { - inputMap = jsonUtil.jsonToMap(inputMapString); - } - if (!CollectionUtils.sizeIsEmpty(inputMap)) { - if (LOG.isDebugEnabled()) { - LOG.debug("<== ServiceDBStore.getMapFromInputStream()"); - } - return inputMap; - } else { - LOG.error("Provided zone/service input map is empty!!"); - throw restErrorUtil.createRESTException("Provided zone/service map is empty!!"); - } - } - - public Map setPolicyMapKeyValue(Map policiesMap, RangerPolicy policy){ - if (StringUtils.isNotEmpty(policy.getName().trim()) - && StringUtils.isNotEmpty(policy.getService().trim()) - && StringUtils.isNotEmpty(policy.getResources().toString().trim())) { - policiesMap.put(policy.getName().trim() + " " + policy.getService().trim() + " " - + policy.getResources().toString().trim() + " " + policy.getZoneName(), policy); - }else if (StringUtils.isEmpty(policy.getName().trim()) && StringUtils.isNotEmpty(policy.getService().trim())){ - LOG.error("Policy Name is not provided for service : " + policy.getService().trim()); - throw restErrorUtil.createRESTException("Policy Name is not provided for service : " + policy.getService().trim()); - }else if (StringUtils.isNotEmpty(policy.getName().trim()) && StringUtils.isEmpty(policy.getService().trim())){ - LOG.error("Service Name is not provided for policy : " + policy.getName().trim()); - throw restErrorUtil.createRESTException("Service Name is not provided for policy : " + policy.getName().trim()); - }else{ - LOG.error("Service Name or Policy Name is not provided!!"); - throw restErrorUtil.createRESTException("Service Name or Policy Name is not provided!!"); - } - return policiesMap; - } - - public Map createPolicyMap(Map zoneMappingMap, List sourceZones, - String destinationZoneName, Map servicesMappingMap, List sourceServices, - List destinationServices, RangerPolicy policy, Map policiesMap) { - - if (!CollectionUtils.sizeIsEmpty(zoneMappingMap)) { - policy.setZoneName(destinationZoneName);// set destination zone name in policy. - } - if (!CollectionUtils.sizeIsEmpty(servicesMappingMap)) { - if (!StringUtils.isEmpty(policy.getService().trim())){ - if (sourceServices.contains(policy.getService().trim())) { - int index = sourceServices.indexOf(policy.getService().trim()); - policy.setService(destinationServices.get(index)); - policiesMap = setPolicyMapKeyValue(policiesMap, policy); - } - }else{ - LOG.error("Service Name or Policy Name is not provided!!"); - throw restErrorUtil.createRESTException("Service Name or Policy Name is not provided!!"); - } - } else if (CollectionUtils.sizeIsEmpty(servicesMappingMap)) { - policiesMap = setPolicyMapKeyValue(policiesMap, policy); - } - return policiesMap; - } - - private void writeBookForPolicyItems(Map svcNameToSvcType, RangerPolicy policy, RangerPolicyItem policyItem, RangerDataMaskPolicyItem dataMaskPolicyItem, RangerRowFilterPolicyItem rowFilterPolicyItem, Row row, String policyConditionType) { - if (LOG.isDebugEnabled()) { - LOG.debug("policyConditionType:[" + policyConditionType + "]"); - } - List groups = new ArrayList<>(); - List users = new ArrayList<>(); - List roles = new ArrayList<>(); - String roleNames = ""; - String groupNames = ""; - String policyConditionTypeValue = ""; - String userNames = ""; - String policyLabelNames = ""; - String accessType = ""; - String policyStatus = ""; - String policyType = ""; - Boolean delegateAdmin = false; - String isRecursive = ""; - String isExcludes = ""; - String serviceName = ""; - - String description = ""; - Boolean isAuditEnabled = true; - isAuditEnabled = policy.getIsAuditEnabled(); - String isExcludesValue = ""; - Cell cell = row.createCell(0); - cell.setCellValue(policy.getId()); - List accesses = new ArrayList<>(); - List conditionsList = new ArrayList<>(); - String conditionKeyValue = ""; - List policyLabels = new ArrayList<>(); - String resValue = ""; - String resourceKeyVal = ""; - String isRecursiveValue = ""; - String resKey = ""; - StringBuffer sb = new StringBuffer(); - StringBuffer sbIsRecursive = new StringBuffer(); - StringBuffer sbIsExcludes = new StringBuffer(); - Map resources = policy.getResources(); - RangerPolicy.RangerPolicyItemDataMaskInfo dataMaskInfo = new RangerPolicy.RangerPolicyItemDataMaskInfo(); - RangerPolicy.RangerPolicyItemRowFilterInfo filterInfo = new RangerPolicy.RangerPolicyItemRowFilterInfo(); - cell = row.createCell(1); - cell.setCellValue(policy.getName()); - cell = row.createCell(2); - if (resources != null) { - for (Entry resource : resources.entrySet()) { - resKey = resource.getKey(); - RangerPolicyResource policyResource = resource.getValue(); - List resvalueList = policyResource.getValues(); - isExcludes = policyResource.getIsExcludes().toString(); - isRecursive = policyResource.getIsRecursive().toString(); - resValue = resvalueList.toString(); - sb = sb.append(resourceKeyVal).append("; ").append(resKey).append("=").append(resValue); - sbIsExcludes = sbIsExcludes.append(resourceKeyVal).append("; ").append(resKey).append("=[").append(isExcludes).append("]"); - sbIsRecursive = sbIsRecursive.append(resourceKeyVal).append("; ").append(resKey).append("=[").append(isRecursive).append("]"); - } - isExcludesValue = sbIsExcludes.toString(); - isExcludesValue = isExcludesValue.substring(1); - isRecursiveValue = sbIsRecursive.toString(); - isRecursiveValue = isRecursiveValue.substring(1); - resourceKeyVal = sb.toString(); - resourceKeyVal = resourceKeyVal.substring(1); - cell.setCellValue(resourceKeyVal); - if (policyItem != null && dataMaskPolicyItem == null && rowFilterPolicyItem == null) { - roles = policyItem.getRoles(); - groups = policyItem.getGroups(); - users = policyItem.getUsers(); - accesses = policyItem.getAccesses(); - delegateAdmin = policyItem.getDelegateAdmin(); - conditionsList = policyItem.getConditions(); - } else if (dataMaskPolicyItem != null && policyItem == null && rowFilterPolicyItem == null) { - roles = dataMaskPolicyItem.getRoles(); - groups = dataMaskPolicyItem.getGroups(); - users = dataMaskPolicyItem.getUsers(); - accesses = dataMaskPolicyItem.getAccesses(); - delegateAdmin = dataMaskPolicyItem.getDelegateAdmin(); - conditionsList = dataMaskPolicyItem.getConditions(); - dataMaskInfo = dataMaskPolicyItem.getDataMaskInfo(); - String dataMaskType = dataMaskInfo.getDataMaskType(); - String conditionExpr = dataMaskInfo.getConditionExpr(); - String valueExpr = dataMaskInfo.getValueExpr(); - String maskingInfo = "dataMasktype=[" + dataMaskType + "]"; - if (conditionExpr != null && !conditionExpr.isEmpty() && valueExpr != null && !valueExpr.isEmpty()) { - maskingInfo = maskingInfo + "; conditionExpr=[" + conditionExpr + "]"; - } - cell = row.createCell(18); - cell.setCellValue(maskingInfo); - } else if (rowFilterPolicyItem != null && policyItem == null && dataMaskPolicyItem == null) { - roles = rowFilterPolicyItem.getRoles(); - groups = rowFilterPolicyItem.getGroups(); - users = rowFilterPolicyItem.getUsers(); - accesses = rowFilterPolicyItem.getAccesses(); - delegateAdmin = rowFilterPolicyItem.getDelegateAdmin(); - conditionsList = rowFilterPolicyItem.getConditions(); - filterInfo = rowFilterPolicyItem.getRowFilterInfo(); - String filterExpr = filterInfo.getFilterExpr(); - cell = row.createCell(19); - cell.setCellValue(filterExpr); - } - if (CollectionUtils.isNotEmpty(accesses)) { - for (RangerPolicyItemAccess access : accesses) { - accessType = accessType + access.getType(); - accessType = accessType + " ,"; - } - accessType = accessType.substring(0, accessType.lastIndexOf(",")); - } - if (CollectionUtils.isNotEmpty(roles)) { - roleNames = roleNames + roles.toString(); - StringTokenizer roleToken = new StringTokenizer(roleNames, "[]"); - while (roleToken.hasMoreTokens()) { - roleNames = roleToken.nextToken().toString(); - } - } - if (CollectionUtils.isNotEmpty(groups)) { - groupNames = groupNames + groups.toString(); - StringTokenizer groupToken = new StringTokenizer(groupNames, "[]"); - while (groupToken.hasMoreTokens()) { - groupNames = groupToken.nextToken().toString(); - } - } - if (CollectionUtils.isNotEmpty(users)) { - userNames = userNames + users.toString(); - StringTokenizer userToken = new StringTokenizer(userNames, "[]"); - while (userToken.hasMoreTokens()) { - userNames = userToken.nextToken().toString(); - } - } - String conditionValue = ""; - for (RangerPolicyItemCondition conditions : conditionsList) { - String conditionType = conditions.getType(); - List conditionList = conditions.getValues(); - conditionValue = conditionList.toString(); - conditionKeyValue = conditionType + "=" + conditionValue; - } - cell = row.createCell(3); - cell.setCellValue(roleNames); - cell = row.createCell(4); - cell.setCellValue(groupNames); - cell = row.createCell(5); - cell.setCellValue(userNames); - cell = row.createCell(6); - cell.setCellValue(accessType.trim()); - cell = row.createCell(7); - - String ServiceType = policy.getServiceType(); - if (StringUtils.isBlank(ServiceType)) { - ServiceType = svcNameToSvcType.get(policy.getService()); - if (ServiceType == null) { - ServiceType = ""; - } - } - - if (policyConditionType != null) { - policyConditionTypeValue = policyConditionType; - } - if (policyConditionType == null && ServiceType.equalsIgnoreCase("tag")) { - policyConditionTypeValue = POLICY_ALLOW_INCLUDE; - } else if (policyConditionType == null) { - policyConditionTypeValue = ""; - } - - cell.setCellValue(ServiceType); - cell = row.createCell(8); - - } - if (policy.getIsEnabled()) { - policyStatus = "Enabled"; - } else { - policyStatus = "Disabled"; - } - policyLabels = policy.getPolicyLabels(); - if (CollectionUtils.isNotEmpty(policyLabels)) { - policyLabelNames = policyLabelNames + policyLabels.toString(); - StringTokenizer policyLabelToken = new StringTokenizer(policyLabelNames, "[]"); - while (policyLabelToken.hasMoreTokens()) { - policyLabelNames = policyLabelToken.nextToken().toString(); - } - } - cell.setCellValue(policyStatus); - cell = row.createCell(9); - int policyTypeInt = policy.getPolicyType(); - switch (policyTypeInt) { - case RangerPolicy.POLICY_TYPE_ACCESS: - policyType = POLICY_TYPE_ACCESS; - break; - - case RangerPolicy.POLICY_TYPE_DATAMASK: - policyType = POLICY_TYPE_DATAMASK; - break; - - case RangerPolicy.POLICY_TYPE_ROWFILTER: - policyType = POLICY_TYPE_ROWFILTER; - break; - } - cell.setCellValue(policyType); - cell = row.createCell(10); - cell.setCellValue(delegateAdmin.toString().toUpperCase()); - cell = row.createCell(11); - cell.setCellValue(isRecursiveValue); - cell = row.createCell(12); - cell.setCellValue(isExcludesValue); - cell = row.createCell(13); - serviceName = policy.getService(); - cell.setCellValue(serviceName); - cell = row.createCell(14); - description = policy.getDescription(); - cell.setCellValue(description); - cell = row.createCell(15); - cell.setCellValue(isAuditEnabled.toString().toUpperCase()); - cell = row.createCell(16); - cell.setCellValue(conditionKeyValue.trim()); - cell = row.createCell(17); - cell.setCellValue(policyConditionTypeValue); - cell = row.createCell(20); - cell.setCellValue(policyLabelNames); - - } - - private void createHeaderRow(Sheet sheet) { - CellStyle cellStyle = sheet.getWorkbook().createCellStyle(); - Font font = sheet.getWorkbook().createFont(); - font.setBold(true); - font.setFontHeightInPoints((short) 12); - cellStyle.setFont(font); - - Row row = sheet.createRow(0); - - Cell cellID = row.createCell(0); - cellID.setCellStyle(cellStyle); - cellID.setCellValue("ID"); - - Cell cellNAME = row.createCell(1); - cellNAME.setCellStyle(cellStyle); - cellNAME.setCellValue("Name"); - - Cell cellResources = row.createCell(2); - cellResources.setCellStyle(cellStyle); - cellResources.setCellValue("Resources"); - - Cell cellRoles = row.createCell(3); - cellRoles.setCellStyle(cellStyle); - cellRoles.setCellValue("Roles"); - - Cell cellGroups = row.createCell(4); - cellGroups.setCellStyle(cellStyle); - cellGroups.setCellValue("Groups"); - - Cell cellUsers = row.createCell(5); - cellUsers.setCellStyle(cellStyle); - cellUsers.setCellValue("Users"); - - Cell cellAccesses = row.createCell(6); - cellAccesses.setCellStyle(cellStyle); - cellAccesses.setCellValue("Accesses"); - - Cell cellServiceType = row.createCell(7); - cellServiceType.setCellStyle(cellStyle); - cellServiceType.setCellValue("Service Type"); - - Cell cellStatus = row.createCell(8); - cellStatus.setCellStyle(cellStyle); - cellStatus.setCellValue("Status"); - - Cell cellPolicyType = row.createCell(9); - cellPolicyType.setCellStyle(cellStyle); - cellPolicyType.setCellValue("Policy Type"); - - Cell cellDelegateAdmin = row.createCell(10); - cellDelegateAdmin.setCellStyle(cellStyle); - cellDelegateAdmin.setCellValue("Delegate Admin"); - - Cell cellIsRecursive = row.createCell(11); - cellIsRecursive.setCellStyle(cellStyle); - cellIsRecursive.setCellValue("isRecursive"); - - Cell cellIsExcludes = row.createCell(12); - cellIsExcludes.setCellStyle(cellStyle); - cellIsExcludes.setCellValue("isExcludes"); - - Cell cellServiceName = row.createCell(13); - cellServiceName.setCellStyle(cellStyle); - cellServiceName.setCellValue("Service Name"); - - Cell cellDescription = row.createCell(14); - cellDescription.setCellStyle(cellStyle); - cellDescription.setCellValue("Description"); - - Cell cellisAuditEnabled = row.createCell(15); - cellisAuditEnabled.setCellStyle(cellStyle); - cellisAuditEnabled.setCellValue("isAuditEnabled"); - - Cell cellPolicyConditions = row.createCell(16); - cellPolicyConditions.setCellStyle(cellStyle); - cellPolicyConditions.setCellValue("Policy Conditions"); - - Cell cellPolicyConditionType = row.createCell(17); - cellPolicyConditionType.setCellStyle(cellStyle); - cellPolicyConditionType.setCellValue("Policy Condition Type"); - - Cell cellMaskingOptions = row.createCell(18); - cellMaskingOptions.setCellStyle(cellStyle); - cellMaskingOptions.setCellValue("Masking Options"); - - Cell cellRowFilterExpr = row.createCell(19); - cellRowFilterExpr.setCellStyle(cellStyle); - cellRowFilterExpr.setCellValue("Row Filter Expr"); - - Cell cellPolicyLabelName = row.createCell(20); - cellPolicyLabelName.setCellStyle(cellStyle); - cellPolicyLabelName.setCellValue("Policy Labels Name"); - } - - private RangerPolicyList searchRangerPolicies(SearchFilter searchFilter) { - List policyList = new ArrayList<>(); - RangerPolicyList retList = new RangerPolicyList(); - Map policyMap=new HashMap<>(); - Set processedServices=new HashSet<>(); - Set processedSvcIdsForRole = new HashSet<>(); - Set processedPolicies=new HashSet<>(); - Comparator comparator = new Comparator() { - public int compare(RangerPolicy c1, RangerPolicy c2) { - return (int) ((c1.getId()).compareTo(c2.getId())); - } - }; - - List xPolList = null; - Long serviceId = null; - String serviceName = searchFilter.getParam(ServiceREST.PARAM_SERVICE_NAME); - - if (StringUtils.isNotBlank(serviceName)) { - serviceId = getRangerServiceByName(serviceName.trim()); - if (serviceId != null) { - loadRangerPolicies(serviceId, processedServices, policyMap, searchFilter); - } - } else { - xPolList = policyService.searchResources(searchFilter, policyService.searchFields, policyService.sortFields, retList); - if (!CollectionUtils.isEmpty(xPolList)) { - for (XXPolicy xXPolicy : xPolList) { - if (!processedServices.contains(xXPolicy.getService())) { - loadRangerPolicies(xXPolicy.getService(), processedServices, policyMap, searchFilter); - } - } - } - } - - String userName = searchFilter.getParam("user"); - if (!StringUtils.isEmpty(userName)) { - searchFilter.setParam("user", RangerPolicyEngine.USER_CURRENT); - List xPolListForMacroUser = policyService.searchResources(searchFilter,policyService.searchFields, policyService.sortFields, retList); - Set processedSvcIdsForMacroUser = new HashSet<>(); - if (!CollectionUtils.isEmpty(xPolListForMacroUser)) { - for (XXPolicy xXPolicy : xPolListForMacroUser) { - if (!processedPolicies.contains(xXPolicy.getId())) { - if (!processedSvcIdsForMacroUser.contains(xXPolicy.getService())) { - loadRangerPolicies(xXPolicy.getService(), processedSvcIdsForMacroUser, policyMap, searchFilter); - } - if (policyMap.get(xXPolicy.getId()) != null) { - policyList.add(policyMap.get(xXPolicy.getId())); - processedPolicies.add(xXPolicy.getId()); - } - } - } - } + XXContextEnricherDefDao xContextEnricherDao = daoMgr.getXXContextEnricherDef(); + List contextEnrichers = xContextEnricherDao.findByServiceDefId(serviceDefId); - searchFilter.removeParam("user"); - Set groupNames = daoMgr.getXXGroupUser().findGroupNamesByUserName(userName); - groupNames.add(RangerConstants.GROUP_PUBLIC); - Set processedSvcIdsForGroup = new HashSet<>(); - Set processedGroupsName = new HashSet<>(); - List xPolList2; - for (String groupName : groupNames) { - searchFilter.setParam("group", groupName); - xPolList2 = policyService.searchResources(searchFilter, policyService.searchFields, policyService.sortFields, retList); - if (!CollectionUtils.isEmpty(xPolList2)) { - for (XXPolicy xPol2 : xPolList2) { - if(xPol2!=null){ - if (!processedPolicies.contains(xPol2.getId())) { - if (!processedSvcIdsForGroup.contains(xPol2.getService()) - || !processedGroupsName.contains(groupName)) { - loadRangerPolicies(xPol2.getService(), processedSvcIdsForGroup, policyMap, searchFilter); - processedGroupsName.add(groupName); - } - if (policyMap.containsKey(xPol2.getId())) { - policyList.add(policyMap.get(xPol2.getId())); - processedPolicies.add(xPol2.getId()); - } - } - } - } - } - } - - // fetch policies maintained for the roles belonging to the user - searchFilter.removeParam("group"); - XXUser xxUser = daoMgr.getXXUser().findByUserName(userName); - if (xxUser != null) { - Set allContainedRoles = new HashSet<>(); - List xxRoles = daoMgr.getXXRole().findByUserId(xxUser.getId()); - for(XXRole xxRole: xxRoles) { - getContainingRoles(xxRole.getId(), allContainedRoles); - } - Set roleNames = getRoleNames(allContainedRoles); - Set processedRoleName = new HashSet<>(); - List xPolList3; - for (String roleName : roleNames) { - searchFilter.setParam("role", roleName); - xPolList3 = policyService.searchResources(searchFilter, policyService.searchFields, policyService.sortFields, retList); - if (!CollectionUtils.isEmpty(xPolList3)) { - for (XXPolicy xPol3 : xPolList3) { - if (xPol3 != null) { - if (!processedPolicies.contains(xPol3.getId())) { - if (!processedSvcIdsForRole.contains(xPol3.getService()) - || !processedRoleName.contains(roleName)) { - loadRangerPolicies(xPol3.getService(), processedSvcIdsForRole, policyMap, searchFilter); - processedRoleName.add(roleName); - } - if (policyMap.containsKey(xPol3.getId())) { - policyList.add(policyMap.get(xPol3.getId())); - processedPolicies.add(xPol3.getId()); - } - } - } - } - } - } - } - } - - // fetch policies maintained for the roles and groups belonging to the group - String groupName = searchFilter.getParam("group"); - if (StringUtils.isBlank(groupName)) { - groupName = RangerConstants.GROUP_PUBLIC; - } - Set groupNames = daoMgr.getXXGroupGroup().findGroupNamesByGroupName(groupName); - groupNames.add(groupName); - Set processedSvcIdsForGroup = new HashSet<>(); - Set processedGroupsName = new HashSet<>(); - List xPolList2; - for (String grpName : groupNames) { - searchFilter.setParam("group", grpName); - xPolList2 = policyService.searchResources(searchFilter, policyService.searchFields, policyService.sortFields, retList); - if (!CollectionUtils.isEmpty(xPolList2)) { - for (XXPolicy xPol2 : xPolList2) { - if(xPol2!=null){ - if (!processedPolicies.contains(xPol2.getId())) { - if (!processedSvcIdsForGroup.contains(xPol2.getService()) - || !processedGroupsName.contains(groupName)) { - loadRangerPolicies(xPol2.getService(), processedSvcIdsForGroup, policyMap, searchFilter); - processedGroupsName.add(groupName); - } - if (policyMap.containsKey(xPol2.getId())) { - policyList.add(policyMap.get(xPol2.getId())); - processedPolicies.add(xPol2.getId()); - } - } - } - } - } - } - - searchFilter.removeParam("group"); - XXGroup xxGroup = daoMgr.getXXGroup().findByGroupName(groupName); - if (xxGroup != null) { - Set allContainedRoles = new HashSet<>(); - List xxRoles = daoMgr.getXXRole().findByGroupId(xxGroup.getId()); - for (XXRole xxRole : xxRoles) { - getContainingRoles(xxRole.getId(), allContainedRoles); - } - Set roleNames = getRoleNames(allContainedRoles); - Set processedRoleName = new HashSet<>(); - List xPolList3; - for (String roleName : roleNames) { - searchFilter.setParam("role", roleName); - xPolList3 = policyService.searchResources(searchFilter, policyService.searchFields, policyService.sortFields, retList); - if (!CollectionUtils.isEmpty(xPolList3)) { - for (XXPolicy xPol3 : xPolList3) { - if (xPol3 != null) { - if (!processedPolicies.contains(xPol3.getId())) { - if (!processedSvcIdsForRole.contains(xPol3.getService()) - || !processedRoleName.contains(roleName)) { - loadRangerPolicies(xPol3.getService(), processedSvcIdsForRole, policyMap, searchFilter); - processedRoleName.add(roleName); - } - if (policyMap.containsKey(xPol3.getId())) { - policyList.add(policyMap.get(xPol3.getId())); - processedPolicies.add(xPol3.getId()); - } - } - } - } - } - } - } - - if (!CollectionUtils.isEmpty(xPolList)) { - if (isSearchQuerybyResource(searchFilter)) { - if (MapUtils.isNotEmpty(policyMap)) { - for(Entry entry:policyMap.entrySet()) { - if (!processedPolicies.contains(entry.getKey())) { - policyList.add(entry.getValue()); - processedPolicies.add(entry.getKey()); - } - } - } - } else { - for (XXPolicy xPol : xPolList) { - if (xPol != null) { - if (!processedPolicies.contains(xPol.getId())) { - if (!processedServices.contains(xPol.getService())) { - loadRangerPolicies(xPol.getService(), processedServices, policyMap, searchFilter); - } - if (policyMap.containsKey(xPol.getId())) { - policyList.add(policyMap.get(xPol.getId())); - processedPolicies.add(xPol.getId()); - } - } - } - } - } - } else { - if (MapUtils.isNotEmpty(policyMap)) { - for(Entry entry:policyMap.entrySet()) { - if (!processedPolicies.contains(entry.getKey())) { - policyList.add(entry.getValue()); - processedPolicies.add(entry.getKey()); - } - } - } - } - - if (CollectionUtils.isNotEmpty(policyList)) { - Collections.sort(policyList, comparator); - } - retList.setPolicies(policyList); - return retList; - } - - private boolean isSearchQuerybyResource(SearchFilter searchFilter) { - boolean ret = false; - Map filterResourcesPrefix = searchFilter.getParamsWithPrefix(SearchFilter.RESOURCE_PREFIX, true); - if(MapUtils.isNotEmpty(filterResourcesPrefix)) { - ret = true; - } - if(!ret) { - Map filterResourcesPolResource = searchFilter.getParamsWithPrefix(SearchFilter.POL_RESOURCE, true); - if (MapUtils.isNotEmpty(filterResourcesPolResource)) { - ret = true; - } - } - return ret; - } - - private Long getRangerServiceByName(String name) { - XXService xxService = null; - XXServiceDao xxServiceDao = daoMgr.getXXService(); - if (xxServiceDao != null ) { - xxService = xxServiceDao.findByName(name); - } - return xxService == null ? null : xxService.getId(); - } - - private void loadRangerPolicies(Long serviceId,Set processedServices,Map policyMap,SearchFilter searchFilter){ - try { - List tempPolicyList = getServicePolicies(serviceId,searchFilter); - if(!CollectionUtils.isEmpty(tempPolicyList)){ - for (RangerPolicy rangerPolicy : tempPolicyList) { - if(!policyMap.containsKey(rangerPolicy.getId())){ - policyMap.put(rangerPolicy.getId(), rangerPolicy); - } - } - } - processedServices.add(serviceId); - } catch (Exception e) { - } - } - public void getServiceUpgraded(){ - LOG.info("==> ServiceDBStore.getServiceUpgraded()"); - updateServiceWithCustomProperty(); - LOG.info("<== ServiceDBStore.getServiceUpgraded()"); - } - private void updateServiceWithCustomProperty() { - LOG.info("Adding custom properties to services"); - SearchFilter filter = new SearchFilter(); - try { - List lstRangerService = getServices(filter); - for(RangerService rangerService : lstRangerService){ - String serviceUser = PropertiesUtil.getProperty("ranger.plugins."+rangerService.getType()+".serviceuser"); - if(!StringUtils.isEmpty(serviceUser)){ - boolean chkServiceUpdate = false; - LOG.debug("customproperty = " + rangerService.getConfigs().get(ServiceREST.Allowed_User_List_For_Download) + " for service = " + rangerService.getName()); - if(!rangerService.getConfigs().containsKey(ServiceREST.Allowed_User_List_For_Download)){ - rangerService.getConfigs().put(ServiceREST.Allowed_User_List_For_Download, serviceUser); - chkServiceUpdate = true; - } - if((!rangerService.getConfigs().containsKey(ServiceREST.Allowed_User_List_For_Grant_Revoke)) && ("hbase".equalsIgnoreCase(rangerService.getType()) || "hive".equalsIgnoreCase(rangerService.getType()))){ - rangerService.getConfigs().put(ServiceREST.Allowed_User_List_For_Grant_Revoke, serviceUser); - chkServiceUpdate = true; - } - if(!rangerService.getConfigs().containsKey(TagREST.Allowed_User_List_For_Tag_Download)){ - rangerService.getConfigs().put(TagREST.Allowed_User_List_For_Tag_Download, serviceUser); - chkServiceUpdate = true; - } - if(chkServiceUpdate){ - updateService(rangerService, null); - if(LOG.isDebugEnabled()){ - LOG.debug("Updated service "+rangerService.getName()+" with custom properties in secure environment"); - } - } - } - } - } catch (Throwable e) { - LOG.error("updateServiceWithCustomProperty failed with exception : "+e.getMessage()); - } - } - - private String getAuditMode(String serviceTypeName, String serviceName) { - String ret = config.get("ranger.audit.global.mode"); - if (StringUtils.isNotBlank(ret)) { - return ret; - } - ret = config.get("ranger.audit.servicedef." + serviceTypeName + ".mode"); - if (StringUtils.isNotBlank(ret)) { - return ret; - } - ret = config.get("ranger.audit.service." + serviceName + ".mode"); - if (StringUtils.isNotBlank(ret)) { - return ret; - } - return RangerPolicyEngine.AUDIT_DEFAULT; - } - - private void createGenericUsers() { - VXUser genericUser = new VXUser(); - - genericUser.setName(RangerPolicyEngine.USER_CURRENT); - genericUser.setDescription(RangerPolicyEngine.USER_CURRENT); - xUserService.createXUserWithOutLogin(genericUser); - - genericUser.setName(RangerPolicyEngine.RESOURCE_OWNER); - genericUser.setDescription(RangerPolicyEngine.RESOURCE_OWNER); - xUserService.createXUserWithOutLogin(genericUser); - } - - private void initRMSDaos() { - daoMgr.getXXService(); - daoMgr.getXXRMSMappingProvider(); - daoMgr.getXXRMSNotification(); - daoMgr.getXXRMSServiceResource(); - daoMgr.getXXRMSResourceMapping(); - } - - public void resetPolicyUpdateLog(int retentionInDays, Integer policyChangeType) { - if (LOG.isDebugEnabled()) { - LOG.debug("==> resetPolicyUpdateLog(" + retentionInDays + ", " + policyChangeType + ")"); - } - - daoMgr.getXXPolicyChangeLog().deleteOlderThan(retentionInDays); - - List allServiceIds = daoMgr.getXXService().getAllServiceIds(); - if (CollectionUtils.isNotEmpty(allServiceIds)) { - for (Long serviceId : allServiceIds) { - ServiceVersionUpdater updater = new ServiceVersionUpdater(daoMgr, serviceId, VERSION_TYPE.POLICY_VERSION, null, policyChangeType, null); - persistVersionChange(updater); - } - } - - if (LOG.isDebugEnabled()) { - LOG.debug("<== resetPolicyUpdateLog(" + retentionInDays + ", " + policyChangeType + ")"); - - } - } - public void resetTagUpdateLog(int retentionInDays, ServiceTags.TagsChangeType tagChangeType) { - if (LOG.isDebugEnabled()) { - LOG.debug("==> resetTagUpdateLog(" + retentionInDays + ", " + tagChangeType + ")"); - } - - daoMgr.getXXTagChangeLog().deleteOlderThan(retentionInDays); - - List allServiceIds = daoMgr.getXXService().getAllServiceIds(); - if (CollectionUtils.isNotEmpty(allServiceIds)) { - for (Long serviceId : allServiceIds) { - ServiceVersionUpdater updater = new ServiceVersionUpdater(daoMgr, serviceId, VERSION_TYPE.TAG_VERSION, tagChangeType, null, null); - persistVersionChange(updater); - } - } - - if (LOG.isDebugEnabled()) { - LOG.debug("<== resetTagUpdateLog(" + retentionInDays + ", " + tagChangeType + ")"); - - } - } - - public void removeAuthSessions(int retentionInDays, List result) { - if (LOG.isDebugEnabled()) { - LOG.debug("==> removeAuthSessions(" + retentionInDays + ")"); - } - - if (retentionInDays > 0) { - XXAuthSessionDao dao = daoMgr.getXXAuthSession(); - long rowsCount = dao.getAllCount(); - long rowsDeleted = dao.deleteOlderThan(retentionInDays); - - LOG.info("Deleted " + rowsDeleted + " records from x_auth_sess that are older than " + retentionInDays + " days"); - - svcService.createTransactionLog(new XXTrxLogV2(AppConstants.CLASS_TYPE_AUTH_SESS, null, null, "Deleted Auth Session records"), "Records count", "Total Records : " + rowsCount, "Deleted Records : " + rowsDeleted); - - result.add(new RangerPurgeResult(ServiceREST.PURGE_RECORD_TYPE_LOGIN_LOGS, rowsCount, rowsDeleted)); - } - - if (LOG.isDebugEnabled()) { - LOG.debug("<== removeAuthSessions(" + retentionInDays + ")"); - } - } - - public void removeTransactionLogs(int retentionInDays, List result) { - if (LOG.isDebugEnabled()) { - LOG.debug("==> removeTransactionLogs(" + retentionInDays + ")"); - } - - if (retentionInDays > 0) { - XXTrxLogV2Dao dao = daoMgr.getXXTrxLogV2(); - long rowsCount = dao.getAllCount(); - long rowsDeleted = dao.deleteOlderThan(retentionInDays); - - LOG.info("Deleted " + rowsDeleted + " records from x_trx_log that are older than " + retentionInDays + " days"); - - svcService.createTransactionLog(new XXTrxLogV2(AppConstants.CLASS_TYPE_TRX_LOG, null, null, "Deleted Transaction records"), "Records count", "Total Records : " + rowsCount, "Deleted Records : " + rowsDeleted); + for (XXContextEnricherDef context : contextEnrichers) { + xContextEnricherDao.remove(context); + } - result.add(new RangerPurgeResult(ServiceREST.PURGE_RECORD_TYPE_TRX_LOGS, rowsCount, rowsDeleted)); - } + XXEnumDefDao enumDefDao = daoMgr.getXXEnumDef(); + List enumDefList = enumDefDao.findByServiceDefId(serviceDefId); - if (LOG.isDebugEnabled()) { - LOG.debug("<== removeTransactionLogs(" + retentionInDays + ")"); - } - } + for (XXEnumDef enumDef : enumDefList) { + List enumEleDefList = daoMgr.getXXEnumElementDef().findByEnumDefId(enumDef.getId()); - public void removePolicyExportLogs(int retentionInDays, List result) { - if (LOG.isDebugEnabled()) { - LOG.debug("==> removePolicyExportLogs({})", retentionInDays); - } + for (XXEnumElementDef eleDef : enumEleDefList) { + daoMgr.getXXEnumElementDef().remove(eleDef); + } + + enumDefDao.remove(enumDef); + } - if (retentionInDays > 0) { - XXPolicyExportAuditDao dao = daoMgr.getXXPolicyExportAudit(); - long rowsCount = dao.getAllCount(); - long rowsDeleted = dao.deleteOlderThan(retentionInDays); + XXPolicyConditionDefDao policyCondDao = daoMgr.getXXPolicyConditionDef(); + List policyCondList = policyCondDao.findByServiceDefId(serviceDefId); - LOG.info("Deleted {} records from x_policy_export_audit that are older than {} days", rowsDeleted, retentionInDays); + for (XXPolicyConditionDef policyCond : policyCondList) { + List xxPolicyRefConditions = daoMgr.getXXPolicyRefCondition().findByConditionDefId(policyCond.getId()); - policyService.createTransactionLog(new XXTrxLogV2(AppConstants.CLASS_TYPE_XA_POLICY_EXPORT_AUDIT, null, null, "Deleted policy export audit records"), "Records count", "Total Records : " + rowsCount, "Deleted Records : " + rowsDeleted); + for (XXPolicyRefCondition xxPolicyRefCondition : xxPolicyRefConditions) { + daoMgr.getXXPolicyRefCondition().remove(xxPolicyRefCondition); + } - result.add(new RangerPurgeResult(ServiceREST.PURGE_RECORD_TYPE_POLICY_EXPORT_LOGS, rowsCount, rowsDeleted)); - } + policyCondDao.remove(policyCond); + } - if (LOG.isDebugEnabled()) { - LOG.debug("<== removePolicyExportLogs({})", retentionInDays); - } - } + List resDefList = daoMgr.getXXResourceDef().findByServiceDefId(serviceDefId); - public List getPolicyLabels(SearchFilter searchFilter) { - if (LOG.isDebugEnabled()) { - LOG.debug("==> ServiceDBStore.getPolicyLabels()"); + for (XXResourceDef resDef : resDefList) { + deleteXXResourceDef(resDef); } - VXPolicyLabelList vxPolicyLabelList = new VXPolicyLabelList(); - @SuppressWarnings("unchecked") - List xPolList = (List) policyLabelsService.searchResources(searchFilter, - policyLabelsService.searchFields, policyLabelsService.sortFields, vxPolicyLabelList); - List result = new ArrayList<>(); - for (XXPolicyLabel xPolicyLabel : xPolList) { - result.add(xPolicyLabel.getPolicyLabel()); + + XXServiceConfigDefDao configDefDao = daoMgr.getXXServiceConfigDef(); + List configDefList = configDefDao.findByServiceDefId(serviceDefId); + + for (XXServiceConfigDef configDef : configDefList) { + configDefDao.remove(configDef); } - if (LOG.isDebugEnabled()) { - LOG.debug("<== ServiceDBStore.getPolicyLabels()"); + + Long version = serviceDef.getVersion(); + + if (version == null) { + version = 1L; + + LOG.info("Found Version Value: `null`, so setting value of version to 1, While updating object, version should not be null."); + } else { + version = version + 1; } - return result; + + serviceDef.setVersion(version); + + serviceDefService.delete(serviceDef); + + LOG.info("ServiceDefinition has been deleted successfully. Service-Def Name: {}", serviceDef.getName()); + + dataHistService.createObjectDataHistory(serviceDef, RangerDataHistService.ACTION_DELETE); + + postDelete(serviceDef); + + LOG.debug("<== ServiceDBStore.deleteServiceDef({}, {})", serviceDefId, forceDelete); } - /** - * This method returns {@linkplain java.util.Map map} representing policy count for each service Definition, - * filtered by policy type, if policy type is not valid (null or less than zero) default policy type will - * be used (ie Resource Access) - * - * @param policyType - * @return {@linkplain java.util.Map map} representing policy count for each service Definition - */ - public Map getPolicyCountByTypeAndServiceType(Integer policyType) { - int type = 0; - if ((!Objects.isNull(policyType)) && policyType >= 0) { - type = policyType; - } - return daoMgr.getXXServiceDef().getPolicyCountByType(type); - } - - public Map getPolicyCountByDenyConditionsAndServiceDef() { - return daoMgr.getXXServiceDef().getPolicyCountByDenyItems(); - } - - public Map getServiceCountByType() { - return daoMgr.getXXServiceDef().getServiceCount(); - } + @Override + public RangerServiceDef getServiceDef(Long id) throws Exception { + LOG.debug("==> ServiceDBStore.getServiceDef({})", id); - public enum METRIC_TYPE { - USER_GROUP { - @Override - public String getMetric(ServiceDBStore ref, SearchCriteria searchCriteria) { - return ref.getMetricOfTypeUserGroup(searchCriteria); - }}, - AUDITS { - @Override - public String getMetric(ServiceDBStore ref, SearchCriteria searchCriteria) { - return ref.getMetricOfTypeAudits(searchCriteria); - }}, - SERVICES { - @Override - public String getMetric(ServiceDBStore ref, SearchCriteria searchCriteria) { - return ref.getMetricOfTypeServices(searchCriteria); - }}, - POLICIES { - @Override - public String getMetric(ServiceDBStore ref, SearchCriteria searchCriteria) { - return ref.getMetricOfTypePolicies(searchCriteria); - }}, - DATABASE { - @Override - public String getMetric(ServiceDBStore ref, SearchCriteria searchCriteria) { - return ref.getMetricOfTypeDatabase(searchCriteria); - }}, - CONTEXT_ENRICHERS { - @Override - public String getMetric(ServiceDBStore ref, SearchCriteria searchCriteria) { - return ref.getMetricOfTypeContextEnrichers(searchCriteria); - }}, - DENY_CONDITIONS { - @Override - public String getMetric(ServiceDBStore ref, SearchCriteria searchCriteria) { - return ref.getMetricOfTypeDenyConditions(searchCriteria); - }}; + RangerServiceDef ret = serviceDefService.read(id); - abstract String getMetric(final ServiceDBStore ref, final SearchCriteria searchCriteria); + LOG.debug("<== ServiceDBStore.getServiceDef({}): {}", id, ret); - public static METRIC_TYPE getMetricTypeByName(final String metricTypeName) { - METRIC_TYPE ret = null; + return ret; + } - if (metricTypeName != null) { - switch(metricTypeName) { - case "usergroup": - ret = METRIC_TYPE.USER_GROUP; - break; - case "audits": - ret = METRIC_TYPE.AUDITS; - break; - case "services": - ret = METRIC_TYPE.SERVICES; - break; - case "policies": - ret = METRIC_TYPE.POLICIES; - break; - case "database": - ret = METRIC_TYPE.DATABASE; - break; - case "contextenrichers": - ret = METRIC_TYPE.CONTEXT_ENRICHERS; - break; - case "denyconditions": - ret = METRIC_TYPE.DENY_CONDITIONS; - break; - } - } + @Override + public RangerServiceDef getServiceDefByName(String name) throws Exception { + LOG.debug("==> ServiceDBStore.getServiceDefByName({})", name); - return ret; + RangerServiceDef ret = null; + XXServiceDef xServiceDef = daoMgr.getXXServiceDef().findByName(name); + + if (xServiceDef != null) { + ret = serviceDefService.getPopulatedViewObject(xServiceDef); } + + LOG.debug("== ServiceDBStore.getServiceDefByName({}): ", name); + + return ret; } - private String getMetricOfTypeUserGroup(final SearchCriteria searchCriteria) { - String ret = null; + /** + * @param displayName + * @return {@link RangerServiceDef} - service using display name if present in DB, null otherwise. + */ + @Override + public RangerServiceDef getServiceDefByDisplayName(String displayName) { + LOG.debug("==> ServiceDBStore.getServiceDefByDisplayName({})", displayName); - try { - VXGroupList vxGroupList = xUserMgr.searchXGroups(searchCriteria); - long groupCount = vxGroupList.getTotalCount(); - ArrayList userAdminRoleCount = new ArrayList<>(); - userAdminRoleCount.add(RangerConstants.ROLE_SYS_ADMIN); - long userSysAdminCount = getUserCountBasedOnUserRole(userAdminRoleCount); - ArrayList userAdminAuditorRoleCount = new ArrayList<>(); - userAdminAuditorRoleCount.add(RangerConstants.ROLE_ADMIN_AUDITOR); - long userSysAdminAuditorCount = getUserCountBasedOnUserRole(userAdminAuditorRoleCount); - ArrayList userRoleListKeyRoleAdmin = new ArrayList<>(); - userRoleListKeyRoleAdmin.add(RangerConstants.ROLE_KEY_ADMIN); - long userKeyAdminCount = getUserCountBasedOnUserRole(userRoleListKeyRoleAdmin); - ArrayList userRoleListKeyadminAduitorRole = new ArrayList<>(); - userRoleListKeyadminAduitorRole.add(RangerConstants.ROLE_KEY_ADMIN_AUDITOR); - long userKeyadminAuditorCount = getUserCountBasedOnUserRole(userRoleListKeyadminAduitorRole); - ArrayList userRoleListUser = new ArrayList<>(); - userRoleListUser.add(RangerConstants.ROLE_USER); - long userRoleCount = getUserCountBasedOnUserRole(userRoleListUser); - long userTotalCount = userSysAdminCount + userKeyAdminCount + userRoleCount + userKeyadminAuditorCount + userSysAdminAuditorCount; - VXMetricUserGroupCount metricUserGroupCount = new VXMetricUserGroupCount(); - metricUserGroupCount.setUserCountOfUserRole(userRoleCount); - metricUserGroupCount.setUserCountOfKeyAdminRole(userKeyAdminCount); - metricUserGroupCount.setUserCountOfSysAdminRole(userSysAdminCount); - metricUserGroupCount.setUserCountOfKeyadminAuditorRole(userKeyadminAuditorCount); - metricUserGroupCount.setUserCountOfSysAdminAuditorRole(userSysAdminAuditorCount); - metricUserGroupCount.setUserTotalCount(userTotalCount); - metricUserGroupCount.setGroupCount(groupCount); - final String jsonUserGroupCount = JsonUtils.objectToJson(metricUserGroupCount); - ret = jsonUserGroupCount; - } catch (Exception e) { - LOG.error("ServiceDBStore.getMetricByType(usergroup): Error calculating Metric for usergroup : " + e.getMessage()); + RangerServiceDef ret = null; + XXServiceDef xServiceDef = daoMgr.getXXServiceDef().findByDisplayName(displayName); + + if (xServiceDef != null) { + ret = serviceDefService.getPopulatedViewObject(xServiceDef); } + LOG.debug("== ServiceDBStore.getServiceDefByName({}): {}", displayName, ret); + return ret; } - private String getMetricOfTypeAudits(final SearchCriteria searchCriteria) { - String ret = null; - try { - int clientTimeOffsetInMinute = RestUtil.getClientTimeOffset(); - String defaultDateFormat = "MM/dd/yyyy"; - DateFormat formatter = new SimpleDateFormat(defaultDateFormat); + @Override + public List getServiceDefs(SearchFilter filter) throws Exception { + LOG.debug("==> ServiceDBStore.getServiceDefs({})", filter); - VXMetricAuditDetailsCount auditObj = new VXMetricAuditDetailsCount(); - DateUtil dateUtilTwoDays = new DateUtil(); - Date startDateUtilTwoDays = dateUtilTwoDays.getDateFromNow(-2); - Date dStart2 = restErrorUtil.parseDate(formatter.format(startDateUtilTwoDays), "Invalid value for startDate", MessageEnums.INVALID_INPUT_DATA, null, - "startDate", defaultDateFormat); + RangerServiceDefList svcDefList = serviceDefService.searchRangerServiceDefs(filter); - Date endDateTwoDays = MiscUtil.getUTCDate(); - Date dEnd2 = restErrorUtil.parseDate(formatter.format(endDateTwoDays), "Invalid value for endDate", MessageEnums.INVALID_INPUT_DATA, null, "endDate", defaultDateFormat); - dEnd2 = dateUtilTwoDays.getDateFromGivenDate(dEnd2, 0, 23, 59, 59); - dEnd2 = dateUtilTwoDays.addTimeOffset(dEnd2, clientTimeOffsetInMinute); - VXMetricServiceCount deniedCountObj = getAuditsCount(0, dStart2, dEnd2); - auditObj.setDenialEventsCountTwoDays(deniedCountObj); + predicateUtil.applyFilter(svcDefList.getServiceDefs(), filter); - VXMetricServiceCount allowedCountObj = getAuditsCount(1, dStart2, dEnd2); - auditObj.setAccessEventsCountTwoDays(allowedCountObj); + List ret = svcDefList.getServiceDefs(); - long totalAuditsCountTwoDays = deniedCountObj.getTotalCount() + allowedCountObj.getTotalCount(); - auditObj.setSolrIndexCountTwoDays(totalAuditsCountTwoDays); + LOG.debug("==> ServiceDBStore.getServiceDefs({}): {}", filter, ret); - DateUtil dateUtilWeek = new DateUtil(); - Date startDateUtilWeek = dateUtilWeek.getDateFromNow(-7); - Date dStart7 = restErrorUtil.parseDate(formatter.format(startDateUtilWeek), "Invalid value for startDate", MessageEnums.INVALID_INPUT_DATA, null, "startDate", - defaultDateFormat); + return ret; + } - Date endDateWeek = MiscUtil.getUTCDate(); - DateUtil dateUtilweek = new DateUtil(); - Date dEnd7 = restErrorUtil.parseDate(formatter.format(endDateWeek), "Invalid value for endDate", MessageEnums.INVALID_INPUT_DATA, null, "endDate", defaultDateFormat); - dEnd7 = dateUtilweek.getDateFromGivenDate(dEnd7, 0, 23, 59, 59); - dEnd7 = dateUtilweek.addTimeOffset(dEnd7, clientTimeOffsetInMinute); - VXMetricServiceCount deniedCountObjWeek = getAuditsCount(0, dStart7, dEnd7); - auditObj.setDenialEventsCountWeek(deniedCountObjWeek); + @Override + public RangerService createService(RangerService service) throws Exception { + LOG.debug("==> ServiceDBStore.createService({})", service); - VXMetricServiceCount allowedCountObjWeek = getAuditsCount(1, dStart7, dEnd7); - auditObj.setAccessEventsCountWeek(allowedCountObjWeek); + if (service == null) { + throw restErrorUtil.createRESTException("Service object cannot be null.", MessageEnums.ERROR_CREATING_OBJECT); + } - long totalAuditsCountWeek = deniedCountObjWeek.getTotalCount() + allowedCountObjWeek.getTotalCount(); - auditObj.setSolrIndexCountWeek(totalAuditsCountWeek); + boolean createDefaultPolicy = true; + Map configs = service.getConfigs(); + Map validConfigs = validateRequiredConfigParams(service, configs); - final String jsonAudit = JsonUtils.objectToJson(auditObj); - ret = jsonAudit; - } catch (Exception e) { - LOG.error("ServiceDBStore.getMetricByType(audits): Error calculating Metric for audits : " + e.getMessage()); + if (validConfigs == null) { + LOG.debug("==> ConfigParams cannot be null, ServiceDBStore.createService({})", service); + + throw restErrorUtil.createRESTException("ConfigParams cannot be null.", MessageEnums.ERROR_CREATING_OBJECT); } - return ret; - } + // While creating, value of version should be 1. + service.setVersion(1L); + service.setTagVersion(1L); - private String getMetricOfTypeServices(final SearchCriteria searchCriteria) { - String ret = null; - try { - SearchFilter serviceFilter = new SearchFilter(); - serviceFilter.setMaxRows(200); - serviceFilter.setStartIndex(0); - serviceFilter.setGetCount(true); - serviceFilter.setSortBy("serviceId"); - serviceFilter.setSortType("asc"); - VXMetricServiceCount vXMetricServiceCount = new VXMetricServiceCount(); - PList paginatedSvcs = getPaginatedServices(serviceFilter); - long totalServiceCount = paginatedSvcs.getTotalCount(); - List rangerServiceList = paginatedSvcs.getList(); - Map services = new HashMap<>(); - for (Object rangerService : rangerServiceList) { - RangerService RangerServiceObj = (RangerService) rangerService; - String serviceName = RangerServiceObj.getType(); - if (!(services.containsKey(serviceName))) { - serviceFilter.setParam("serviceType", serviceName); - PList paginatedSvcscount = getPaginatedServices(serviceFilter); - services.put(serviceName, paginatedSvcscount.getTotalCount()); - } - } - vXMetricServiceCount.setServiceBasedCountList(services); - vXMetricServiceCount.setTotalCount(totalServiceCount); - final String jsonServices = JsonUtils.objectToJson(vXMetricServiceCount); - ret = jsonServices; - } catch (Exception e) { - LOG.error("ServiceDBStore.getMetricByType(services): Error calculating Metric for services : " + e.getMessage()); + if (populateExistingBaseFields) { + svcServiceWithAssignedId.setPopulateExistingBaseFields(true); + + daoMgr.getXXService().setIdentityInsert(true); + + service = svcServiceWithAssignedId.create(service); + + daoMgr.getXXService().setIdentityInsert(false); + daoMgr.getXXService().updateSequence(); + + svcServiceWithAssignedId.setPopulateExistingBaseFields(false); + + createDefaultPolicy = false; + } else { + service = svcService.create(service); } - return ret; - } - private String getMetricOfTypePolicies(final SearchCriteria searchCriteria) { - String ret = null; - try { - SearchFilter policyFilter = new SearchFilter(); - policyFilter.setMaxRows(200); - policyFilter.setStartIndex(0); - policyFilter.setGetCount(true); - policyFilter.setSortBy("serviceId"); - policyFilter.setSortType("asc"); - VXMetricPolicyWithServiceNameCount vXMetricPolicyWithServiceNameCount = new VXMetricPolicyWithServiceNameCount(); - PList paginatedSvcsList = getPaginatedPolicies(policyFilter); - vXMetricPolicyWithServiceNameCount.setTotalCount(paginatedSvcsList.getTotalCount()); - Map servicesWithPolicy = new HashMap<>(); - for (int k = 2; k >= 0; k--) { - String policyType = String.valueOf(k); - VXMetricServiceNameCount vXMetricServiceNameCount = getVXMetricServiceCount(policyType); - if (k == 2) { - servicesWithPolicy.put("rowFilteringPolicies", vXMetricServiceNameCount); - } else if (k == 1) { - servicesWithPolicy.put("maskingPolicies", vXMetricServiceNameCount); - } else if (k == 0) { - servicesWithPolicy.put("resourceAccessPolicies", vXMetricServiceNameCount); + XXService xCreatedService = daoMgr.getXXService().getById(service.getId()); + XXServiceConfigMapDao xConfMapDao = daoMgr.getXXServiceConfigMap(); + + for (Entry configMap : validConfigs.entrySet()) { + String configKey = configMap.getKey(); + String configValue = configMap.getValue(); + + if (StringUtils.equalsIgnoreCase(configKey, "username")) { + String userName = stringUtil.getValidUserName(configValue); + XXUser xxUser = daoMgr.getXXUser().findByUserName(userName); + + if (xxUser != null) { + xUserService.populateViewBean(xxUser); + } else { + UserSessionBase usb = ContextUtil.getCurrentUserSession(); + + if (usb != null && !usb.isUserAdmin() && !usb.isSpnegoEnabled()) { + throw restErrorUtil.createRESTException("User does not exist with given username: [" + userName + "] please use existing user", MessageEnums.OPER_NO_PERMISSION); + } + + xUserMgr.createServiceConfigUser(userName); } } - Map> tagMap = new HashMap<>(); - Map ServiceNameWithPolicyCount = new HashMap<>(); - boolean tagFlag = false; - if (tagFlag == false) { - policyFilter.setParam("serviceType", "tag"); - PList policiestype = getPaginatedPolicies(policyFilter); - List policies = policiestype.getList(); - for (RangerPolicy rangerPolicy : policies) { - if (ServiceNameWithPolicyCount.containsKey(rangerPolicy.getService())) { - Long tagServicePolicyCount = ServiceNameWithPolicyCount.get(rangerPolicy.getService()) + 1l; - ServiceNameWithPolicyCount.put(rangerPolicy.getService(), tagServicePolicyCount); - } else if (!rangerPolicy.getName().isEmpty()) { - ServiceNameWithPolicyCount.put(rangerPolicy.getService(), 1l); - } + + if (StringUtils.equalsIgnoreCase(configKey, CONFIG_KEY_PASSWORD)) { + Joiner joiner = Joiner.on(",").skipNulls(); + String iv = PasswordUtils.generateIvIfNeeded(CRYPT_ALGO); + String cryptConfigString = joiner.join(CRYPT_ALGO, ENCRYPT_KEY, SALT, ITERATION_COUNT, iv, configValue); + String encryptedPwd = PasswordUtils.encryptPassword(cryptConfigString); + String paddedEncryptedPwd = joiner.join(CRYPT_ALGO, ENCRYPT_KEY, SALT, ITERATION_COUNT, iv, encryptedPwd); + String decryptedPwd = PasswordUtils.decryptPassword(paddedEncryptedPwd); + + if (StringUtils.equals(decryptedPwd, configValue)) { + configValue = paddedEncryptedPwd; } - tagMap.put("tag", ServiceNameWithPolicyCount); - long tagCount = policiestype.getTotalCount(); - VXMetricServiceNameCount vXMetricServiceNameCount = new VXMetricServiceNameCount(); - vXMetricServiceNameCount.setServiceBasedCountList(tagMap); - vXMetricServiceNameCount.setTotalCount(tagCount); - servicesWithPolicy.put("tagAccessPolicies", vXMetricServiceNameCount); - tagFlag = true; } - vXMetricPolicyWithServiceNameCount.setPolicyCountList(servicesWithPolicy); - final String jsonPolicies = JsonUtils.objectToJson(vXMetricPolicyWithServiceNameCount); - ret = jsonPolicies; - } catch (Exception e) { - LOG.error("ServiceDBStore.getMetricByType(policies): Error calculating Metric for policies : " + e.getMessage()); + + XXServiceConfigMap xConfMap = new XXServiceConfigMap(); + + xConfMap = rangerAuditFields.populateAuditFields(xConfMap, xCreatedService); + + xConfMap.setServiceId(xCreatedService.getId()); + xConfMap.setConfigkey(configKey); + + if (StringUtils.equalsIgnoreCase(configKey, "username")) { + configValue = stringUtil.getValidUserName(configValue); + } + + xConfMap.setConfigvalue(configValue); + + xConfMapDao.create(xConfMap); } - return ret; - } - private String getMetricOfTypeDatabase(final SearchCriteria searchCriteria) { - String ret = null; - try { - int dbFlavor = RangerBizUtil.getDBFlavor(); - String dbFlavourType = RangerBizUtil.getDBFlavorType(dbFlavor); - String dbDetail = dbFlavourType + " " + bizUtil.getDBVersion(); + updateTabPermissions(service.getType(), validConfigs); - ret = JsonUtils.objectToJson(dbDetail); - } catch (Exception e) { - LOG.error("ServiceDBStore.getMetricByType(database): Error calculating Metric for database : " + e.getMessage()); + RangerService createdService = svcService.getPopulatedViewObject(xCreatedService); + + if (createdService == null) { + throw restErrorUtil.createRESTException("Could not create service - Internal error ", MessageEnums.ERROR_CREATING_OBJECT); } - return ret; + + dataHistService.createObjectDataHistory(createdService, RangerDataHistService.ACTION_CREATE); + + svcService.createTransactionLog(createdService, null, RangerServiceService.OPERATION_CREATE_CONTEXT); + + if (createDefaultPolicy) { + createDefaultPolicies(createdService); + } + + return createdService; } - private String getMetricOfTypeContextEnrichers(final SearchCriteria searchCriteria) { - String ret = null; - try { - SearchFilter filter = new SearchFilter(); - filter.setStartIndex(0); - VXMetricContextEnricher serviceWithContextEnrichers = new VXMetricContextEnricher(); - PList paginatedSvcDefs = getPaginatedServiceDefs(filter); - List repoTypeList = paginatedSvcDefs.getList(); - if (repoTypeList != null) { - for (RangerServiceDef repoType : repoTypeList) { - RangerServiceDef rangerServiceDefObj = (RangerServiceDef) repoType; - String name = rangerServiceDefObj.getName(); - List contextEnrichers = rangerServiceDefObj.getContextEnrichers(); - if (contextEnrichers != null && !contextEnrichers.isEmpty()) { - serviceWithContextEnrichers.setServiceName(name); - serviceWithContextEnrichers.setTotalCount(contextEnrichers.size()); - } + @Override + public RangerService updateService(RangerService service, Map options) throws Exception { + LOG.debug("==> ServiceDBStore.updateService()"); + + XXService xExisting = daoMgr.getXXService().getById(service.getId()); + + if (xExisting == null) { + throw restErrorUtil.createRESTException("no service exists with ID=" + service.getId(), MessageEnums.DATA_NOT_FOUND); + } + + RangerService existing = svcService.getPopulatedViewObject(xExisting); + + String existingName = existing.getName(); + + boolean renamed = !StringUtils.equalsIgnoreCase(service.getName(), existingName); + + if (renamed) { + XXService newNameService = daoMgr.getXXService().findByName(service.getName()); + + if (newNameService != null) { + throw restErrorUtil.createRESTException("another service already exists with name '" + service.getName() + "'. ID=" + newNameService.getId(), MessageEnums.DATA_NOT_UPDATABLE); + } + + long countOfTaggedResources = daoMgr.getXXServiceResource().countTaggedResourcesInServiceId(existing.getId()); + + Boolean isForceRename = options != null && options.get(ServiceStore.OPTION_FORCE_RENAME) != null ? (Boolean) options.get(ServiceStore.OPTION_FORCE_RENAME) : Boolean.FALSE; + + if (countOfTaggedResources != 0L) { + if (isForceRename) { + LOG.warn("Forcing the renaming of service from {} to {} although it is associated with {} service-resources!", existingName, service.getName(), countOfTaggedResources); + } else { + throw restErrorUtil.createRESTException("Service " + existingName + " cannot be renamed, as it has associated service-resources", MessageEnums.DATA_NOT_UPDATABLE); } } - final String jsonContextEnrichers = JsonUtils.objectToJson(serviceWithContextEnrichers); - ret = jsonContextEnrichers; - } catch (Exception e) { - LOG.error("ServiceDBStore.getMetricByType(contextenrichers): Error calculating Metric for contextenrichers : " + e.getMessage()); } - return ret; - } - private String getMetricOfTypeDenyConditions(final SearchCriteria searchCriteria) { - String ret = null; - try { - SearchFilter policyFilter1 = new SearchFilter(); - policyFilter1.setMaxRows(200); - policyFilter1.setStartIndex(0); - policyFilter1.setGetCount(true); - policyFilter1.setSortBy("serviceId"); - policyFilter1.setSortType("asc"); - policyFilter1.setParam("denyCondition", "true"); - int denyCount = 0; - Map denyconditionsonMap = new HashMap<>(); - PList paginatedSvcDefs = getPaginatedServiceDefs(policyFilter1); - if (paginatedSvcDefs != null) { - List rangerServiceDefs = paginatedSvcDefs.getList(); - if (rangerServiceDefs != null && !rangerServiceDefs.isEmpty()) { - for (RangerServiceDef rangerServiceDef : rangerServiceDefs) { - if (rangerServiceDef != null) { - String serviceDef = rangerServiceDef.getName(); - if (!StringUtils.isEmpty(serviceDef)) { - policyFilter1.setParam("serviceType", serviceDef); - PList policiesList = getPaginatedPolicies(policyFilter1); - if (policiesList != null && policiesList.getListSize() > 0) { - int policyListCount = policiesList.getListSize(); - if (policyListCount > 0 && policiesList.getList() != null) { - List policies = policiesList.getList(); - for (RangerPolicy policy : policies) { - if (policy != null) { - List policyItem = policy.getDenyPolicyItems(); - if (policyItem != null && !policyItem.isEmpty()) { + Map configs = service.getConfigs(); + Map validConfigs = validateRequiredConfigParams(service, configs); + + if (validConfigs == null) { + LOG.debug("==> ConfigParams cannot be null, ServiceDBStore.createService({})", service); + + throw restErrorUtil.createRESTException("ConfigParams cannot be null.", MessageEnums.ERROR_CREATING_OBJECT); + } + + boolean hasTagServiceValueChanged = false; + String existingTagService = existing.getTagService(); + String newTagServiceName = service.getTagService(); // null for old clients; empty string to remove existing association + Long newTagServiceId = null; + + if (newTagServiceName == null) { // old client; don't update existing tagService + if (existingTagService != null) { + newTagServiceName = existingTagService; + + service.setTagService(newTagServiceName); + + LOG.info("ServiceDBStore.updateService(id={}; name={}): tagService is null; using existing tagService '{}'", service.getId(), service.getName(), newTagServiceName); + } + } + + if (StringUtils.isNotBlank(newTagServiceName)) { + RangerService tmp = getServiceByName(newTagServiceName); + + if (tmp == null || !EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_TAG_NAME.equals(tmp.getType())) { + LOG.debug("ServiceDBStore.updateService() - {} does not refer to a valid tag service.({})", newTagServiceName, service); + + throw restErrorUtil.createRESTException("Invalid tag service name " + newTagServiceName, MessageEnums.ERROR_CREATING_OBJECT); + } else { + newTagServiceId = tmp.getId(); + } + } + + if (existingTagService == null) { + if (newTagServiceId != null) { + hasTagServiceValueChanged = true; + } + } else if (!existingTagService.equals(newTagServiceName)) { + hasTagServiceValueChanged = true; + } + + boolean hasIsEnabledChanged = !existing.getIsEnabled().equals(service.getIsEnabled()); + + List dbConfigMaps = daoMgr.getXXServiceConfigMap().findByServiceId(service.getId()); + boolean hasServiceConfigForPluginChanged = hasServiceConfigForPluginChanged(dbConfigMaps, validConfigs); + + svcService.createTransactionLog(service, existing, RangerServiceService.OPERATION_UPDATE_CONTEXT); + + if (populateExistingBaseFields) { + svcServiceWithAssignedId.setPopulateExistingBaseFields(true); + + service = svcServiceWithAssignedId.update(service); + + svcServiceWithAssignedId.setPopulateExistingBaseFields(false); + } else { + service.setCreateTime(existing.getCreateTime()); + service.setGuid(existing.getGuid()); + service.setVersion(existing.getVersion()); + + service = svcService.update(service); + + if (hasTagServiceValueChanged || hasIsEnabledChanged || hasServiceConfigForPluginChanged) { + updatePolicyVersion(service, RangerPolicyDelta.CHANGE_TYPE_SERVICE_CHANGE, null, false); + } + } + + XXService xUpdService = daoMgr.getXXService().getById(service.getId()); + String oldPassword = null; + + for (XXServiceConfigMap dbConfigMap : dbConfigMaps) { + if (StringUtils.equalsIgnoreCase(dbConfigMap.getConfigkey(), CONFIG_KEY_PASSWORD)) { + oldPassword = dbConfigMap.getConfigvalue(); + } + + daoMgr.getXXServiceConfigMap().remove(dbConfigMap); + } + + XXServiceConfigMapDao xConfMapDao = daoMgr.getXXServiceConfigMap(); + + for (Entry configMap : validConfigs.entrySet()) { + String configKey = configMap.getKey(); + String configValue = configMap.getValue(); + + if (StringUtils.equalsIgnoreCase(configKey, "username")) { + String userName = stringUtil.getValidUserName(configValue); + XXUser xxUser = daoMgr.getXXUser().findByUserName(userName); + + if (xxUser != null) { + xUserService.populateViewBean(xxUser); + } else { + UserSessionBase usb = ContextUtil.getCurrentUserSession(); + + if (usb != null && !usb.isUserAdmin()) { + throw restErrorUtil.createRESTException("User does not exist with given username: [" + userName + "] please use existing user", MessageEnums.OPER_NO_PERMISSION); + } + + xUserMgr.createServiceConfigUser(userName); + } + } + + if (StringUtils.equalsIgnoreCase(configKey, CONFIG_KEY_PASSWORD)) { + if (StringUtils.equalsIgnoreCase(configValue, HIDDEN_PASSWORD_STR)) { + if (oldPassword != null && oldPassword.contains(",")) { + PasswordUtils util = PasswordUtils.build(oldPassword); + + if (!util.getCryptAlgo().equalsIgnoreCase(CRYPT_ALGO)) { + String decryptedPwd = PasswordUtils.decryptPassword(oldPassword); + String paddingString = Joiner.on(",").skipNulls().join(CRYPT_ALGO, new String(util.getEncryptKey()), new String(util.getSalt()), util.getIterationCount(), PasswordUtils.generateIvIfNeeded(CRYPT_ALGO)); + String encryptedPwd = PasswordUtils.encryptPassword(paddingString + "," + decryptedPwd); + String newDecryptedPwd = PasswordUtils.decryptPassword(paddingString + "," + encryptedPwd); + + if (StringUtils.equals(newDecryptedPwd, decryptedPwd)) { + configValue = paddingString + "," + encryptedPwd; + } + } else { + configValue = oldPassword; + } + } else { + configValue = oldPassword; + } + } else { + String paddingString = Joiner.on(",").skipNulls().join(CRYPT_ALGO, ENCRYPT_KEY, SALT, ITERATION_COUNT, PasswordUtils.generateIvIfNeeded(CRYPT_ALGO)); + String encryptedPwd = PasswordUtils.encryptPassword(paddingString + "," + configValue); + String decryptedPwd = PasswordUtils.decryptPassword(paddingString + "," + encryptedPwd); + + if (StringUtils.equals(decryptedPwd, configValue)) { + configValue = paddingString + "," + encryptedPwd; + } + } + } + + XXServiceConfigMap xConfMap = new XXServiceConfigMap(); + + xConfMap = rangerAuditFields.populateAuditFields(xConfMap, xUpdService); + + xConfMap.setServiceId(service.getId()); + xConfMap.setConfigkey(configKey); + xConfMap.setConfigvalue(configValue); + + xConfMapDao.create(xConfMap); + } + + updateTabPermissions(service.getType(), validConfigs); + + RangerService updService = svcService.getPopulatedViewObject(xUpdService); + + dataHistService.createObjectDataHistory(updService, RangerDataHistService.ACTION_UPDATE); + + return updService; + } + + @Override + public void deleteService(Long id) throws Exception { + LOG.debug("==> ServiceDBStore.deleteService({})", id); + + RangerService service = getService(id); + + if (service == null) { + throw new Exception("no service exists with ID=" + id); + } + + // Manage zone + disassociateZonesForService(service); //RANGER-3016 + + List policyIds = daoMgr.getXXPolicy().findPolicyIdsByServiceId(service.getId()); + + if (CollectionUtils.isNotEmpty(policyIds)) { + long totalDeletedPolicies = 0; + + for (Long policyID : policyIds) { + RangerPolicy rangerPolicy = getPolicy(policyID); + + deletePolicy(rangerPolicy, service); + + totalDeletedPolicies = totalDeletedPolicies + 1; + + // its a bulk policy delete call flush and clear + if (totalDeletedPolicies % RangerBizUtil.POLICY_BATCH_SIZE == 0) { + bizUtil.bulkModeOnlyFlushAndClear(); + } + } + + bizUtil.bulkModeOnlyFlushAndClear(); + } + + XXServiceConfigMapDao configDao = daoMgr.getXXServiceConfigMap(); + List configs = configDao.findByServiceId(service.getId()); + + for (XXServiceConfigMap configMap : configs) { + configDao.remove(configMap); + } + + // Purge x_rms data + daoMgr.getXXRMSServiceResource().purge(service.getId()); + + Long version = service.getVersion(); + + if (version == null) { + version = 1L; + + LOG.info("Found Version Value: `null`, so setting value of version to 1, While updating object, version should not be null."); + } else { + version = version + 1; + } + + service.setVersion(version); + + svcService.delete(service); + + dataHistService.createObjectDataHistory(service, RangerDataHistService.ACTION_DELETE); + + svcService.createTransactionLog(service, null, RangerServiceService.OPERATION_DELETE_CONTEXT); + + //During the servie deletion ,we need to clear the RangerServicePoliciesCache,RangerServiceTagsCache for the given serviceName. + resetPolicyCache(service.getName()); + + tagStore.resetTagCache(service.getName()); + } + + @Override + public boolean serviceExists(String name) { + LOG.debug("==> ServiceDBStore.serviceExists({})", name); + + Long id = daoMgr.getXXService().findIdByName(name); + boolean ret = id != null; + + LOG.debug("<== ServiceDBStore.serviceExists({}): ret={}", name, ret); + + return ret; + } + + @Override + public RangerService getService(Long id) throws Exception { + LOG.debug("==> ServiceDBStore.getService()"); + + UserSessionBase session = ContextUtil.getCurrentUserSession(); + + if (session == null) { + throw restErrorUtil.createRESTException("UserSession cannot be null.", MessageEnums.OPER_NOT_ALLOWED_FOR_STATE); + } + + XXService xService = daoMgr.getXXService().getById(id); + + // TODO: As of now we are allowing SYS_ADMIN to read all the + // services including KMS + + if (xService == null) { + throw restErrorUtil.createRESTException("Data Not Found for given Id", MessageEnums.DATA_NOT_FOUND, id, null, "readResource : No Object found with given id."); + } + + if (!bizUtil.hasAccess(xService, null)) { + throw restErrorUtil.createRESTException("Logged in user is not allowed to read service, id: " + id, MessageEnums.OPER_NO_PERMISSION); + } + + return svcService.getPopulatedViewObject(xService); + } + + @Override + public RangerService getServiceByName(String name) throws Exception { + LOG.debug("==> ServiceDBStore.getServiceByName()"); + + XXService xService = daoMgr.getXXService().findByName(name); + + // TODO: As of now we are allowing SYS_ADMIN to read all the + // services including KMS + + if (ContextUtil.getCurrentUserSession() != null) { + if (xService == null) { + return null; + } + + if (!bizUtil.hasAccess(xService, null)) { + throw restErrorUtil.createRESTException("Logged in user is not allowed to read service, name: " + name, MessageEnums.OPER_NO_PERMISSION); + } + } + + return xService == null ? null : svcService.getPopulatedViewObject(xService); + } + + @Override + public RangerService getServiceByDisplayName(String displayName) { + LOG.debug("==> ServiceDBStore.getServiceByName()"); + + XXService xService = daoMgr.getXXService().findByDisplayName(displayName); + + if (ContextUtil.getCurrentUserSession() != null) { + if (xService == null) { + return null; + } + + if (!bizUtil.hasAccess(xService, null)) { + throw restErrorUtil.createRESTException("Logged in user is not allowed to read service, name: " + displayName, MessageEnums.OPER_NO_PERMISSION); + } + } + + return xService == null ? null : svcService.getPopulatedViewObject(xService); + } + + @Override + public List getServices(SearchFilter filter) throws Exception { + LOG.debug("==> ServiceDBStore.getServices()"); + + RangerServiceList serviceList = svcService.searchRangerServices(filter); + + predicateUtil.applyFilter(serviceList.getServices(), filter); + + List ret = serviceList.getServices(); + + LOG.debug("<== ServiceDBStore.getServices()"); + + return ret; + } + + @Override + public RangerPolicy createPolicy(RangerPolicy policy) throws Exception { + return createPolicy(policy, bizUtil.getCreatePrincipalsIfAbsent()); + } + + @Override + public RangerPolicy createDefaultPolicy(RangerPolicy policy) throws Exception { + return createPolicy(policy, true); + } + + @Override + public RangerPolicy updatePolicy(RangerPolicy policy) throws Exception { + LOG.debug("==> ServiceDBStore.updatePolicy({})", policy); + + XXPolicy xxExisting = daoMgr.getXXPolicy().getById(policy.getId()); + RangerPolicy existing = policyService.getPopulatedViewObject(xxExisting); + + if (existing == null) { + throw new Exception("no policy exists with ID=" + policy.getId()); + } + + RangerService service = getServiceByName(policy.getService()); + + if (service == null) { + throw new Exception("service does not exist - name=" + policy.getService()); + } + + XXServiceDef xServiceDef = daoMgr.getXXServiceDef().findByName(service.getType()); + + if (xServiceDef == null) { + throw new Exception("service-def does not exist - name=" + service.getType()); + } + + if (!StringUtils.equalsIgnoreCase(existing.getService(), policy.getService())) { + throw new Exception("policy id=" + policy.getId() + " already exists in service " + existing.getService() + ". It can not be moved to service " + policy.getService()); + } + + boolean renamed = !StringUtils.equalsIgnoreCase(policy.getName(), existing.getName()); + + if (renamed) { + XXPolicy newNamePolicy = daoMgr.getXXPolicy().findByNameAndServiceIdAndZoneId(policy.getName(), service.getId(), xxExisting.getZoneId()); + + if (newNamePolicy != null) { + throw new Exception("another policy already exists with name '" + policy.getName() + "'. ID=" + newNamePolicy.getId()); + } + } + + List policyLabels = policy.getPolicyLabels(); + Set uniquePolicyLabels = new TreeSet<>(policyLabels); + + policy.setCreateTime(xxExisting.getCreateTime()); + + if (StringUtils.isEmpty(policy.getGuid())) { + policy.setGuid(xxExisting.getGuid()); + } + + policy.setVersion(xxExisting.getVersion()); + + policyService.createTransactionLog(policy, existing, RangerPolicyService.OPERATION_UPDATE_CONTEXT); + + updatePolicySignature(policy); + + policy = policyService.update(policy); + + XXPolicy newUpdPolicy = daoMgr.getXXPolicy().getById(policy.getId()); + + policyRefUpdater.cleanupRefTables(policy); + + deleteExistingPolicyLabel(policy); + + policyRefUpdater.createNewPolMappingForRefTable(policy, newUpdPolicy, xServiceDef, bizUtil.getCreatePrincipalsIfAbsent()); + + createOrMapLabels(newUpdPolicy, uniquePolicyLabels); + + RangerPolicy updPolicy = policyService.getPopulatedViewObject(newUpdPolicy); + boolean updateServiceInfoRoleVersion = false; + + if (isSupportsRolesDownloadByService()) { + updateServiceInfoRoleVersion = isRoleDownloadRequired(updPolicy, service); + } + + handlePolicyUpdate(service, RangerPolicyDelta.CHANGE_TYPE_POLICY_UPDATE, updPolicy, updateServiceInfoRoleVersion); + + dataHistService.createObjectDataHistory(updPolicy, RangerDataHistService.ACTION_UPDATE); + + return updPolicy; + } + + @Override + public void deletePolicy(RangerPolicy policy, RangerService service) throws Exception { + LOG.debug("==> ServiceDBStore.deletePolicy()"); + + if (policy != null) { + if (service == null) { + service = getServiceByName(policy.getService()); + } + + if (service != null) { + String policyName = policy.getName(); + + LOG.debug("Deleting Policy, policyName: {}", policyName); + + Long version = policy.getVersion(); + + if (version == null) { + version = 1L; + + LOG.info("Found Version Value: `null`, so setting value of version to 1, While updating object, version should not be null."); + } else { + version = version + 1; + } + + policy.setVersion(version); + + policyRefUpdater.cleanupRefTables(policy); + + deleteExistingPolicyLabel(policy); + + policyService.delete(policy); + + createTransactionLog(policy, RangerPolicyService.OPERATION_IMPORT_DELETE_CONTEXT, RangerPolicyService.OPERATION_DELETE_CONTEXT); + handlePolicyUpdate(service, RangerPolicyDelta.CHANGE_TYPE_POLICY_DELETE, policy, false); + + dataHistService.createObjectDataHistory(policy, RangerDataHistService.ACTION_DELETE); + } + } + + LOG.debug("<== ServiceDBStore.deletePolicy()"); + } + + @Override + public void deletePolicy(RangerPolicy policy) throws Exception { + LOG.debug("==> ServiceDBStore.deletePolicy({})", policy); + + if (policy == null) { + throw new Exception("No such policy exists"); + } + + String policyName = policy.getName(); + RangerService service = getServiceByName(policy.getService()); + + if (service == null) { + throw new Exception("service does not exist - name='" + policy.getService()); + } + + Long version = policy.getVersion(); + if (version == null) { + version = 1L; + + LOG.info("Found Version Value: `null`, so setting value of version to 1, While updating object, version should not be null."); + } else { + version = version + 1; + } + + policy.setVersion(version); + + createTransactionLog(policy, RangerPolicyService.OPERATION_IMPORT_DELETE_CONTEXT, RangerPolicyService.OPERATION_DELETE_CONTEXT); + + policyRefUpdater.cleanupRefTables(policy); + + deleteExistingPolicyLabel(policy); + + policyService.delete(policy); + + handlePolicyUpdate(service, RangerPolicyDelta.CHANGE_TYPE_POLICY_DELETE, policy, false); + + dataHistService.createObjectDataHistory(policy, RangerDataHistService.ACTION_DELETE); + + LOG.info("Policy Deleted Successfully. PolicyName : {}", policyName); + } + + @Override + public boolean policyExists(Long id) { + return daoMgr.getXXPolicy().getCountById(id) > 0; + } + + @Override + public RangerPolicy getPolicy(Long id) throws Exception { + return policyService.read(id); + } + + @Override + public List getPolicies(SearchFilter filter) throws Exception { + LOG.debug("==> ServiceDBStore.getPolicies()"); + + boolean fetchTagPolicies = Boolean.parseBoolean(filter.getParam(SearchFilter.FETCH_TAG_POLICIES)); + boolean fetchAllZonePolicies = Boolean.parseBoolean(filter.getParam(SearchFilter.FETCH_ZONE_UNZONE_POLICIES)); + String zoneName = filter.getParam(SearchFilter.ZONE_NAME); + + List ret = new ArrayList<>(); + RangerPolicyList policyList = searchRangerPolicies(filter); + List resourcePolicies = policyList.getPolicies(); + List tagPolicies; + + if (fetchTagPolicies) { + tagPolicies = searchRangerTagPoliciesOnBasisOfServiceName(resourcePolicies); + + for (Iterator itr = tagPolicies.iterator(); itr.hasNext(); ) { + RangerPolicy pol = itr.next(); + + if (!fetchAllZonePolicies) { + if (StringUtils.isNotEmpty(zoneName)) { + if (!zoneName.equals(pol.getZoneName())) { + itr.remove(); + } + } else { + if (StringUtils.isNotEmpty(pol.getZoneName())) { + itr.remove(); + } + } + } + } + } else { + tagPolicies = new ArrayList<>(); + } + + LOG.debug("<== ServiceDBStore.getPolicies()"); + + ret.addAll(resourcePolicies); + ret.addAll(tagPolicies); + + return ret; + } + + @Override + public Long getPolicyId(final Long serviceId, final String policyName, final Long zoneId) { + LOG.debug("==> ServiceDBStore.getPolicyId()"); + + Long ret = null; + XXPolicy xxPolicy = daoMgr.getXXPolicy().findByNameAndServiceIdAndZoneId(policyName, serviceId, zoneId); + + if (xxPolicy != null) { + ret = xxPolicy.getId(); + } + + LOG.debug("<== ServiceDBStore.getPolicyId()"); + + return ret; + } + + @Override + public List getPoliciesByResourceSignature(String serviceName, String policySignature, Boolean isPolicyEnabled) throws Exception { + List xxPolicies = daoMgr.getXXPolicy().findByResourceSignatureByPolicyStatus(serviceName, policySignature, isPolicyEnabled); + List policies = new ArrayList<>(xxPolicies.size()); + + for (XXPolicy xxPolicy : xxPolicies) { + RangerPolicy policy = policyService.getPopulatedViewObject(xxPolicy); + + policies.add(policy); + } + + return policies; + } + + @Override + public List getServicePolicies(Long serviceId, SearchFilter filter) throws Exception { + LOG.debug("==> ServiceDBStore.getServicePolicies({})", serviceId); + + String zoneName = filter.getParam(SearchFilter.FETCH_ZONE_NAME); + String denyCondition = filter.getParam(SearchFilter.FETCH_DENY_CONDITION); + XXService service = daoMgr.getXXService().getById(serviceId); + + if (service == null) { + throw new Exception("service does not exist - id='" + serviceId); + } + + List ret = getServicePolicies(service, filter); + + if (!"true".equalsIgnoreCase(filter.getParam(SearchFilter.FETCH_ZONE_UNZONE_POLICIES))) { + if (StringUtils.isBlank(zoneName) && StringUtils.isBlank(denyCondition)) { + ret = noZoneFilter(ret); + } + } + + LOG.debug("<== ServiceDBStore.getServicePolicies({}) : policy-count={}", serviceId, ret == null ? 0 : ret.size()); + + return ret; + } + + @Override + public List getServicePolicies(String serviceName, SearchFilter filter) throws Exception { + LOG.debug("==> ServiceDBStore.getServicePolicies({})", serviceName); + + String zoneName = filter.getParam("zoneName"); + XXService service = daoMgr.getXXService().findByName(serviceName); + + if (service == null) { + throw new Exception("service does not exist - name='" + serviceName); + } + + List ret = getServicePolicies(service, filter); + + if (StringUtils.isBlank(zoneName)) { + ret = noZoneFilter(ret); + } + + LOG.debug("<== ServiceDBStore.getServicePolicies({}): count={}", service, ((ret == null) ? 0 : ret.size())); + + return ret; + } + + @Override + public ServicePolicies getServicePoliciesIfUpdated(String serviceName, Long lastKnownVersion, boolean needsBackwardCompatibility) throws Exception { + LOG.debug("==> ServiceDBStore.getServicePoliciesIfUpdated({}, {}, {})", serviceName, lastKnownVersion, needsBackwardCompatibility); + + ServicePolicies ret = null; + XXService serviceDbObj = daoMgr.getXXService().findByName(serviceName); + + if (serviceDbObj == null) { + throw new Exception("service does not exist. name=" + serviceName); + } + + XXServiceVersionInfo serviceVersionInfoDbObj = daoMgr.getXXServiceVersionInfo().findByServiceName(serviceName); + + if (serviceVersionInfoDbObj == null) { + LOG.warn("serviceVersionInfo does not exist. name={}", serviceName); + } + + if (lastKnownVersion == null || serviceVersionInfoDbObj == null || serviceVersionInfoDbObj.getPolicyVersion() == null || !lastKnownVersion.equals(serviceVersionInfoDbObj.getPolicyVersion())) { + ret = RangerServicePoliciesCache.getInstance().getServicePolicies(serviceName, serviceDbObj.getId(), lastKnownVersion, needsBackwardCompatibility, this); + } + + if (LOG.isDebugEnabled()) { + RangerServicePoliciesCache.getInstance().dump(); + } + + if (ret != null && lastKnownVersion != null && lastKnownVersion.equals(ret.getPolicyVersion())) { + // ServicePolicies are not changed + ret = null; + } + + if (ret != null) { + LOG.debug("Checking if resource-service:[{}] is disabled", ret.getServiceName()); + + if (!serviceDbObj.getIsenabled()) { + ret = ServicePolicies.copyHeader(ret); + + ret.setTagPolicies(null); + } else { + String tagServiceName = ret.getTagPolicies() != null ? ret.getTagPolicies().getServiceName() : null; + boolean isTagServiceActive = isServiceActive(tagServiceName); + + if (!isTagServiceActive) { + ServicePolicies copy = ServicePolicies.copyHeader(ret); + + copy.setTagPolicies(null); + + List copyPolicies = ret.getPolicies() != null ? new ArrayList<>(ret.getPolicies()) : null; + List copyPolicyDeltas = ret.getPolicyDeltas() != null ? new ArrayList<>(ret.getPolicyDeltas()) : null; + + copy.setPolicies(copyPolicies); + copy.setPolicyDeltas(copyPolicyDeltas); + + ret = copy; + } + } + + Map securityZones = securityZoneStore.getSecurityZonesForService(serviceName); + ServicePolicies updatedServicePolicies = ret; + + if (MapUtils.isNotEmpty(securityZones)) { + updatedServicePolicies = getUpdatedServicePoliciesForZones(ret, securityZones); + + patchAssociatedTagServiceInSecurityZoneInfos(updatedServicePolicies); + } + + if (lastKnownVersion == null || lastKnownVersion == -1L || needsBackwardCompatibility) { + ret = filterServicePolicies(updatedServicePolicies); + } else { + ret = updatedServicePolicies; + } + + ret.setServiceConfig(getServiceConfigForPlugin(ret.getServiceId())); + + if (ret.getTagPolicies() != null && ret.getTagPolicies().getServiceId() != null) { + ret.getTagPolicies().setServiceConfig(getServiceConfigForPlugin(ret.getTagPolicies().getServiceId())); + } + } + + LOG.debug("<== ServiceDBStore.getServicePoliciesIfUpdated({}, {}, {}): count={}", serviceName, lastKnownVersion, needsBackwardCompatibility, (ret == null || ret.getPolicies() == null) ? 0 : ret.getPolicies().size()); + + return ret; + } + + @Override + public ServicePolicies getServicePolicyDeltasOrPolicies(String serviceName, Long lastKnownVersion) throws Exception { + boolean getOnlyDeltas = false; + + LOG.debug("Support for incremental policy updates enabled using \"ranger.admin{}\" configuation parameter :[{}]", RangerCommonConstants.RANGER_ADMIN_SUFFIX_POLICY_DELTA, SUPPORTS_POLICY_DELTAS); + + return getServicePolicies(serviceName, lastKnownVersion, getOnlyDeltas, SUPPORTS_POLICY_DELTAS, Long.MAX_VALUE); + } + + @Override + public ServicePolicies getServicePolicyDeltas(String serviceName, Long lastKnownVersion, Long cachedPolicyVersion) throws Exception { + ServicePolicies ret = null; + + if (SUPPORTS_POLICY_DELTAS) { + LOG.debug("Support for incremental policy updates enabled using \"ranger.admin{}\" configuation parameter :[{}]", RangerCommonConstants.RANGER_ADMIN_SUFFIX_POLICY_DELTA, SUPPORTS_POLICY_DELTAS); + + ret = getServicePolicies(serviceName, lastKnownVersion, true, SUPPORTS_POLICY_DELTAS, cachedPolicyVersion); + } + + return ret; + } + + @Override + public ServicePolicies getServicePolicies(String serviceName, Long lastKnownVersion) throws Exception { + boolean getOnlyDeltas = false; + + return getServicePolicies(serviceName, lastKnownVersion, getOnlyDeltas, false, Long.MAX_VALUE); + } + + public RangerPolicy getPolicyFromEventTime(String eventTime, Long policyId) { + XXDataHist xDataHist = daoMgr.getXXDataHist().findObjByEventTimeClassTypeAndId(eventTime, AppConstants.CLASS_TYPE_RANGER_POLICY, policyId); + + if (xDataHist == null) { + String errMsg = "No policy history found for given policy ID: " + policyId + " and event time: " + eventTime; + + LOG.error(errMsg); + + throw restErrorUtil.createRESTException(errMsg, MessageEnums.DATA_NOT_FOUND); + } + + String content = xDataHist.getContent(); + + return jsonUtil.writeJsonToJavaObject(content, RangerPolicy.class); + } + + @Override + public Boolean getPopulateExistingBaseFields() { + return populateExistingBaseFields; + } + + @Override + public void setPopulateExistingBaseFields(Boolean populateExistingBaseFields) { + this.populateExistingBaseFields = populateExistingBaseFields; + } + + @Override + public RangerSecurityZone getSecurityZone(Long id) { + return securityZoneService.read(id); + } + + @Override + public RangerSecurityZone getSecurityZone(String name) { + XXSecurityZone xxSecurityZone = daoMgr.getXXSecurityZoneDao().findByZoneName(name); + + if (xxSecurityZone != null) { + return getSecurityZone(xxSecurityZone.getId()); + } + + return null; + } + + @Override + public long getPoliciesCount(final String serviceName) { + final long ret; + + if (StringUtils.isNotBlank(serviceName)) { + ret = daoMgr.getXXPolicy().getPoliciesCount(serviceName); + } else { + ret = 0L; + } + + return ret; + } + + @Override + public Map getServiceConfigForPlugin(Long serviceId) { + Map configs = new HashMap<>(); + List xxServiceConfigMaps = daoMgr.getXXServiceConfigMap().findByServiceId(serviceId); + + if (CollectionUtils.isNotEmpty(xxServiceConfigMaps)) { + for (XXServiceConfigMap svcConfMap : xxServiceConfigMaps) { + if (StringUtils.startsWith(svcConfMap.getConfigkey(), RANGER_PLUGIN_CONFIG_PREFIX)) { + configs.put(svcConfMap.getConfigkey(), svcConfMap.getConfigvalue()); + } + } + } + + return configs; + } + + @Override + public List getPoliciesWithMetaAttributes(List policiesList) { + if (CollectionUtils.isNotEmpty(policiesList)) { + List policies = new ArrayList<>(); + + for (RangerPolicy policy : policiesList) { + RangerPolicy policyCopy = (RangerPolicy) SerializationUtils.clone(policy); + + policies.add(policyCopy); + } + + List policytimeMetaDataList = daoMgr.getXXPolicy().getMetaAttributesForPolicies(policies.stream().map(RangerPolicy::getId).collect(Collectors.toList())); + + if (CollectionUtils.isNotEmpty(policytimeMetaDataList)) { + Map> policyMap = policytimeMetaDataList.stream() + .filter(row -> row != null && row.length == 3 && row[0] != null && row[1] != null && row[2] != null) + .collect(Collectors.toMap(row -> (Long) row[0], row -> Arrays.asList((Date) row[1], (Date) row[2]))); + + for (RangerPolicy policy : policies) { + List timeMetaData = policyMap.get(policy.getId()); + + if (timeMetaData != null && timeMetaData.size() == 2) { + policy.setCreateTime(timeMetaData.get(0)); + policy.setUpdateTime(timeMetaData.get(1)); + } + } + } + + return policies; + } + + return policiesList; + } + + @PostConstruct + public void initStore() { + LOG.debug("==> ServiceDBStore.initStore()"); + + config = RangerAdminConfig.getInstance(); + + String nullSafeSupplier = config.get("ranger.admin.null_safe.supplier", RangerBaseModelObject.NULL_SAFE_SUPPLIER_V2); + + LOG.info("ranger.admin.null_safe.supplier={}", nullSafeSupplier); + + RangerBaseModelObject.setNullSafeSupplier(nullSafeSupplier); + + if (!legacyServiceDefsInitDone) { + synchronized (ServiceDBStore.class) { + if (!legacyServiceDefsInitDone) { + SUPPORTS_POLICY_DELTAS = config.getBoolean("ranger.admin" + RangerCommonConstants.RANGER_ADMIN_SUFFIX_POLICY_DELTA, RangerCommonConstants.RANGER_ADMIN_SUFFIX_POLICY_DELTA_DEFAULT); + RETENTION_PERIOD_IN_DAYS = config.getInt("ranger.admin.delta.retention.time.in.days", 7); + TAG_RETENTION_PERIOD_IN_DAYS = config.getInt("ranger.admin.tag.delta.retention.time.in.days", 3); + + SUPPORTS_PURGE_LOGIN_RECORDS = config.getBoolean("ranger.admin.init.purge.login_records", false); + SUPPORTS_PURGE_TRANSACTION_RECORDS = config.getBoolean("ranger.admin.init.purge.transaction_records", false); + SUPPORTS_PURGE_POLICY_EXPORT_LOGS = config.getBoolean("ranger.admin.init.purge.policy_export_logs", false); + LOGIN_RECORDS_RETENTION_PERIOD_IN_DAYS = config.getInt("ranger.admin.init.purge.login_records.retention.days", 0); + TRANSACTION_RECORDS_RETENTION_PERIOD_IN_DAYS = config.getInt("ranger.admin.init.purge.transaction_records.retention.days", 0); + POLICY_EXPORT_LOGS_RETENTION_PERIOD_IN_DAYS = config.getInt("ranger.admin.init.purge.policy_export_logs.retention.days", 0); + + isRolesDownloadedByService = config.getBoolean("ranger.support.for.service.specific.role.download", false); + SUPPORTS_IN_PLACE_POLICY_UPDATES = SUPPORTS_POLICY_DELTAS && config.getBoolean("ranger.admin" + RangerCommonConstants.RANGER_ADMIN_SUFFIX_IN_PLACE_POLICY_UPDATES, RangerCommonConstants.RANGER_ADMIN_SUFFIX_IN_PLACE_POLICY_UPDATES_DEFAULT); + + LOG.info("SUPPORTS_POLICY_DELTAS={}", SUPPORTS_POLICY_DELTAS); + LOG.info("RETENTION_PERIOD_IN_DAYS={}", RETENTION_PERIOD_IN_DAYS); + LOG.info("TAG_RETENTION_PERIOD_IN_DAYS={}", TAG_RETENTION_PERIOD_IN_DAYS); + LOG.info("SUPPORTS_PURGE_LOGIN_RECORDS={}", SUPPORTS_PURGE_LOGIN_RECORDS); + LOG.info("LOGIN_RECORDS_RETENTION_PERIOD_IN_DAYS={}", LOGIN_RECORDS_RETENTION_PERIOD_IN_DAYS); + LOG.info("SUPPORTS_PURGE_TRANSACTION_RECORDS={}", SUPPORTS_PURGE_TRANSACTION_RECORDS); + LOG.info("TRANSACTION_RECORDS_RETENTION_PERIOD_IN_DAYS={}", TRANSACTION_RECORDS_RETENTION_PERIOD_IN_DAYS); + LOG.info("SUPPORTS_PURGE_POLICY_EXPORT_LOGS={}", SUPPORTS_PURGE_POLICY_EXPORT_LOGS); + LOG.info("POLICY_EXPORT_LOGS_RETENTION_PERIOD_IN_DAYS={}", POLICY_EXPORT_LOGS_RETENTION_PERIOD_IN_DAYS); + LOG.info("isRolesDownloadedByService={}", isRolesDownloadedByService); + LOG.info("SUPPORTS_IN_PLACE_POLICY_UPDATES={}", SUPPORTS_IN_PLACE_POLICY_UPDATES); + + TransactionTemplate txTemplate = new TransactionTemplate(txManager); + final ServiceDBStore dbStore = this; + + predicateUtil = new ServicePredicateUtil(dbStore); + + try { + txTemplate.execute(status -> { + EmbeddedServiceDefsUtil.instance().init(dbStore); + getServiceUpgraded(); + createGenericUsers(); + resetPolicyUpdateLog(RETENTION_PERIOD_IN_DAYS, RangerPolicyDelta.CHANGE_TYPE_RANGER_ADMIN_START); + resetTagUpdateLog(TAG_RETENTION_PERIOD_IN_DAYS, ServiceTags.TagsChangeType.RANGER_ADMIN_START); + + List purgeResults = new ArrayList<>(); + + if (SUPPORTS_PURGE_LOGIN_RECORDS) { + removeAuthSessions(LOGIN_RECORDS_RETENTION_PERIOD_IN_DAYS, purgeResults); + } + + if (SUPPORTS_PURGE_TRANSACTION_RECORDS) { + removeTransactionLogs(TRANSACTION_RECORDS_RETENTION_PERIOD_IN_DAYS, purgeResults); + } + + if (SUPPORTS_PURGE_POLICY_EXPORT_LOGS) { + removePolicyExportLogs(POLICY_EXPORT_LOGS_RETENTION_PERIOD_IN_DAYS, purgeResults); + } + + initRMSDaos(); + + return null; + }); + } catch (Throwable ex) { + LOG.error("ServiceDBStore.initStore(): Failed to update DB: {}", String.valueOf(ex)); + } + + legacyServiceDefsInitDone = true; + } + } + } + + LOG.debug("<== ServiceDBStore.initStore()"); + } + + public void deleteXXAccessTypeDef(XXAccessTypeDef xAccess) { + List atdGrantsList = daoMgr.getXXAccessTypeDefGrants().findByATDId(xAccess.getId()); + + for (XXAccessTypeDefGrants atdGrant : atdGrantsList) { + daoMgr.getXXAccessTypeDefGrants().remove(atdGrant); + } + + List policyRefAccessTypeList = daoMgr.getXXPolicyRefAccessType().findByAccessTypeDefId(xAccess.getId()); + + for (XXPolicyRefAccessType xxPolicyRefAccessType : policyRefAccessTypeList) { + daoMgr.getXXPolicyRefAccessType().remove(xxPolicyRefAccessType); + } + + daoMgr.getXXAccessTypeDef().remove(xAccess); + } + + public void deleteXXResourceDef(XXResourceDef xRes) { + List xChildObjs = daoMgr.getXXResourceDef().findByParentResId(xRes.getId()); + + for (XXResourceDef childRes : xChildObjs) { + deleteXXResourceDef(childRes); + } + + List xxPolicyRefResources = daoMgr.getXXPolicyRefResource().findByResourceDefID(xRes.getId()); + + for (XXPolicyRefResource xPolRefRes : xxPolicyRefResources) { + daoMgr.getXXPolicyRefResource().remove(xPolRefRes); + } + + daoMgr.getXXResourceDef().remove(xRes); + } + + @Override + + public PList getPaginatedServiceDefs(SearchFilter filter) throws Exception { + LOG.debug("==> ServiceDBStore.getPaginatedServiceDefs({})", filter); + + RangerServiceDefList svcDefList = serviceDefService.searchRangerServiceDefs(filter); + + predicateUtil.applyFilter(svcDefList.getServiceDefs(), filter); + + LOG.debug("==> ServiceDBStore.getPaginatedServiceDefs({})", filter); + + return new PList<>(svcDefList.getServiceDefs(), svcDefList.getStartIndex(), svcDefList.getPageSize(), svcDefList.getTotalCount(), svcDefList.getResultSize(), svcDefList.getSortType(), svcDefList.getSortBy()); + } + + public PList getPaginatedServices(SearchFilter filter) throws Exception { + LOG.debug("==> ServiceDBStore.getPaginatedServices()"); + + RangerServiceList serviceList = svcService.searchRangerServices(filter); + + if (StringUtils.isEmpty(filter.getParam("serviceNamePartial"))) { + predicateUtil.applyFilter(serviceList.getServices(), filter); + } + + LOG.debug("<== ServiceDBStore.getPaginatedServices()"); + + return new PList<>(serviceList.getServices(), serviceList.getStartIndex(), serviceList.getPageSize(), serviceList.getTotalCount(), serviceList.getResultSize(), serviceList.getSortType(), serviceList.getSortBy()); + } + + public PList getPaginatedPolicies(SearchFilter filter) { + LOG.debug("==> ServiceDBStore.getPaginatedPolicies(+ {})", filter); + + RangerPolicyList policyList = searchRangerPolicies(filter); + + LOG.debug("before filter: count={}", policyList.getListSize()); + + predicateUtil.applyFilter(policyList.getPolicies(), filter); + + LOG.debug("after filter: count={}", policyList.getListSize()); + + LOG.debug("<== ServiceDBStore.getPaginatedPolicies({}): count={}", filter, policyList.getListSize()); + + return new PList<>(policyList.getPolicies(), policyList.getStartIndex(), policyList.getPageSize(), policyList.getTotalCount(), policyList.getResultSize(), policyList.getSortType(), policyList.getSortBy()); + } + + public PList getPaginatedServicePolicies(Long serviceId, SearchFilter filter) throws Exception { + LOG.debug("==> ServiceDBStore.getPaginatedServicePolicies({})", serviceId); + + XXService service = daoMgr.getXXService().getById(serviceId); + + if (service == null) { + throw new Exception("service does not exist - id='" + serviceId); + } + + PList ret = getPaginatedServicePolicies(service.getName(), filter); + + LOG.debug("<== ServiceDBStore.getPaginatedServicePolicies({})", serviceId); + + return ret; + } + + public PList getPaginatedServicePolicies(String serviceName, SearchFilter filter) { + LOG.debug("==> ServiceDBStore.getPaginatedServicePolicies({})", serviceName); + + if (filter == null) { + filter = new SearchFilter(); + } + + filter.setParam(SearchFilter.SERVICE_NAME, serviceName); + + PList ret = getPaginatedPolicies(filter); + + LOG.debug("<== ServiceDBStore.getPaginatedServicePolicies({}): count={}", serviceName, (ret == null) ? 0 : ret.getListSize()); + + return ret; + } + + @Override + public Long getServicePolicyVersion(String serviceName) { + XXServiceVersionInfo serviceVersionInfoDbObj = daoMgr.getXXServiceVersionInfo().findByServiceName(serviceName); + + return serviceVersionInfoDbObj != null ? serviceVersionInfoDbObj.getPolicyVersion() : null; + } + + // when a service-def is updated, the updated service-def should be made available to plugins + // this is achieved by incrementing policyVersion of all services of this service-def + protected void updateServicesForServiceDefUpdate(RangerServiceDef serviceDef) { + if (serviceDef == null) { + return; + } + + final RangerDaoManager daoManager = daoMgr; + boolean isTagServiceDef = StringUtils.equals(serviceDef.getName(), EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_TAG_NAME); + XXServiceDao serviceDao = daoMgr.getXXService(); + List services = serviceDao.findByServiceDefId(serviceDef.getId()); + + if (CollectionUtils.isNotEmpty(services)) { + for (XXService service : services) { + if (isTagServiceDef) { + List referringServices = serviceDao.findByTagServiceId(service.getId()); + + if (CollectionUtils.isNotEmpty(referringServices)) { + for (XXService referringService : referringServices) { + final Long referringServiceId = referringService.getId(); + final VERSION_TYPE tagServiceVersionType = VERSION_TYPE.POLICY_VERSION; + + Runnable tagServiceVersionUpdater = new ServiceVersionUpdater(daoManager, referringServiceId, tagServiceVersionType, RangerPolicyDelta.CHANGE_TYPE_SERVICE_DEF_CHANGE); + + transactionSynchronizationAdapter.executeOnTransactionCommit(tagServiceVersionUpdater); + } + } + } + + final Long serviceId = service.getId(); + final VERSION_TYPE versionType = VERSION_TYPE.POLICY_VERSION; + + Runnable serviceVersionUpdater = new ServiceVersionUpdater(daoManager, serviceId, versionType, RangerPolicyDelta.CHANGE_TYPE_SERVICE_DEF_CHANGE); + + transactionSynchronizationAdapter.executeOnTransactionCommit(serviceVersionUpdater); + } + } + } + + public List findAllServiceDefNamesHavingContextEnrichers() { + return daoMgr.getXXServiceDef().findAllHavingEnrichers(); + } + + public RangerService getServiceByNameForDP(String name) throws Exception { + LOG.debug("==> ServiceDBStore.getServiceByNameForDP()"); + + XXService xService = daoMgr.getXXService().findByName(name); + + if (ContextUtil.getCurrentUserSession() != null) { + if (xService == null) { + return null; + } + } + + return xService == null ? null : svcService.getPopulatedViewObject(xService); + } + + public RangerPolicy createPolicy(RangerPolicy policy, boolean createPrincipalsIfAbsent) throws Exception { + RangerService service = getServiceByName(policy.getService()); + + if (service == null) { + throw new Exception("service does not exist - name=" + policy.getService()); + } + + XXServiceDef xServiceDef = daoMgr.getXXServiceDef().findByName(service.getType()); + + if (xServiceDef == null) { + throw new Exception("service-def does not exist - name=" + service.getType()); + } + + Long zoneId = RangerSecurityZone.RANGER_UNZONED_SECURITY_ZONE_ID; + String zoneName = policy.getZoneName(); + + if (StringUtils.isNotEmpty(zoneName)) { + RangerSecurityZone zone = getSecurityZone(zoneName); + + if (zone == null) { + throw new Exception("zone does not exist - name=" + zoneName); + } else { + zoneId = zone.getId(); + } + } + + XXPolicy existing = daoMgr.getXXPolicy().findByNameAndServiceIdAndZoneId(policy.getName(), service.getId(), zoneId); + + if (existing != null) { + throw new Exception("policy already exists: ServiceName=" + policy.getService() + "; PolicyName=" + policy.getName() + ". ID=" + existing.getId()); + } + + List policyLabels = policy.getPolicyLabels(); + Set uniquePolicyLabels = new TreeSet<>(policyLabels); + + policy.setVersion(1L); + + updatePolicySignature(policy); + + if (populateExistingBaseFields) { + assignedIdPolicyService.setPopulateExistingBaseFields(true); + + daoMgr.getXXPolicy().setIdentityInsert(true); + + policy = assignedIdPolicyService.create(policy, true); + + daoMgr.getXXPolicy().setIdentityInsert(false); + daoMgr.getXXPolicy().updateSequence(); + + assignedIdPolicyService.setPopulateExistingBaseFields(false); + } else { + policy = policyService.create(policy, true); + } + + XXPolicy xCreatedPolicy = daoMgr.getXXPolicy().getById(policy.getId()); + + policyRefUpdater.createNewPolMappingForRefTable(policy, xCreatedPolicy, xServiceDef, createPrincipalsIfAbsent); + + createOrMapLabels(xCreatedPolicy, uniquePolicyLabels); + + RangerPolicy createdPolicy = policyService.getPopulatedViewObject(xCreatedPolicy); + boolean updateServiceInfoRoleVersion = false; + + if (isSupportsRolesDownloadByService()) { + updateServiceInfoRoleVersion = isRoleDownloadRequired(createdPolicy, service); + } + + handlePolicyUpdate(service, RangerPolicyDelta.CHANGE_TYPE_POLICY_CREATE, createdPolicy, updateServiceInfoRoleVersion); + + dataHistService.createObjectDataHistory(createdPolicy, RangerDataHistService.ACTION_CREATE); + + createTransactionLog(createdPolicy, RangerPolicyService.OPERATION_IMPORT_CREATE_CONTEXT, RangerPolicyService.OPERATION_CREATE_CONTEXT); + + return createdPolicy; + } + + public void createOrMapLabels(XXPolicy xPolicy, Set uniquePolicyLabels) { + LOG.debug("==> ServiceDBStore.createOrMapLabels()"); + + for (String policyLabel : uniquePolicyLabels) { + //check and create new label If does not exist + if (StringUtils.isNotEmpty(policyLabel)) { + transactionSynchronizationAdapter.executeOnTransactionCommit(new AssociatePolicyLabel(policyLabel, xPolicy)); + } + } + + LOG.debug("<== ServiceDBStore.createOrMapLabels()"); + } + + public RangerPolicy getPolicy(String guid, String serviceName, String zoneName) throws Exception { + RangerPolicy ret = null; + + if (StringUtils.isNotBlank(guid)) { + XXPolicy xPolicy = daoMgr.getXXPolicy().findPolicyByGUIDAndServiceNameAndZoneName(guid, serviceName, zoneName); + + if (xPolicy != null) { + ret = policyService.getPopulatedViewObject(xPolicy); + } + } + + return ret; + } + + public void getPoliciesInExcel(List policies, HttpServletResponse response) throws Exception { + LOG.debug("==> ServiceDBStore.getPoliciesInExcel()"); + + String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); + String excelFileName = "Ranger_Policies_" + timeStamp + ".xls"; + + writeExcel(policies, excelFileName, response); + } + + public void getPoliciesInCSV(List policies, HttpServletResponse response) throws Exception { + LOG.debug("==> ServiceDBStore.getPoliciesInCSV()"); + + ServletOutputStream out = null; + String csvfilename = null; + + try { + String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); + + csvfilename = "Ranger_Policies_" + timeStamp + ".csv"; + out = response.getOutputStream(); + + StringBuilder sb = writeCSV(policies, csvfilename, response); + + IOUtils.write(sb.toString(), out, "UTF-8"); + } catch (Exception e) { + LOG.error("Error while generating report file {}", csvfilename, e); + + e.printStackTrace(); + } finally { + try { + if (out != null) { + out.flush(); + out.close(); + } + } catch (Exception ex) { + // ignored + } + } + } + + public void getObjectInJson(List objList, HttpServletResponse response, JSON_FILE_NAME_TYPE type) throws Exception { + LOG.debug("==> ServiceDBStore.getObjectInJson()"); + + String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); + String jsonFileName; + + switch (type) { + case POLICY: + jsonFileName = "Ranger_Policies_" + timeStamp + ".json"; + break; + case ROLE: + jsonFileName = "Ranger_Roles_" + timeStamp + ".json"; + break; + default: + throw restErrorUtil.createRESTException("Invalid type " + type); + } + + writeJson(objList, jsonFileName, response, type); + } + + public List noZoneFilter(List servicePolicies) { + List noZonePolicies = new ArrayList<>(); + + if (CollectionUtils.isNotEmpty(servicePolicies)) { + for (RangerPolicy policy : servicePolicies) { + if (StringUtils.isBlank(policy.getZoneName())) { + noZonePolicies.add(policy); + } + } + } + + return noZonePolicies; + } + + public boolean resetPolicyCache(final String serviceName) { + LOG.debug("==> ServiceDBStore.resetPolicyCache({})", serviceName); + + boolean ret = RangerServicePoliciesCache.getInstance().resetCache(serviceName); + + LOG.debug("<== ServiceDBStore.resetPolicyCache(): ret={}", ret); + + return ret; + } + + public void createZoneDefaultPolicies(Collection serviceNames, RangerSecurityZone zone) throws Exception { + if (CollectionUtils.isNotEmpty(serviceNames)) { + for (String serviceName : serviceNames) { + RangerService service = getServiceByName(serviceName); + + if (service != null) { + List defaultPolicies = populateDefaultPolicies(service); + + if (CollectionUtils.isNotEmpty(defaultPolicies)) { + String zoneName = zone.getName(); + + for (RangerPolicy defaultPolicy : defaultPolicies) { + defaultPolicy.setZoneName(zoneName); + + createDefaultPolicy(defaultPolicy); + } + } + } + } + } + } + + public void deleteZonePolicies(Collection serviceNames, Long zoneId) throws Exception { + if (CollectionUtils.isNotEmpty(serviceNames)) { + XXPolicyDao policyDao = daoMgr.getXXPolicy(); + + for (String serviceName : serviceNames) { + RangerService service = getServiceByName(serviceName); + List policyIds = policyDao.findPolicyIdsByServiceNameAndZoneId(serviceName, zoneId); + + if (CollectionUtils.isNotEmpty(policyIds)) { + List rangerPolicyList = new ArrayList<>(); + + for (Long id : policyIds) { + rangerPolicyList.add(getPolicy(id)); + } + + long totalDeletedPolicies = 0; + + for (RangerPolicy rangerPolicy : rangerPolicyList) { + deletePolicy(rangerPolicy, service); + + totalDeletedPolicies = totalDeletedPolicies + 1; + + if (totalDeletedPolicies % RangerBizUtil.POLICY_BATCH_SIZE == 0) { + bizUtil.bulkModeOnlyFlushAndClear(); + } + } + + bizUtil.bulkModeOnlyFlushAndClear(); + } + } + } + } + + public VXString getPolicyVersionList(Long policyId) { + List versionList = daoMgr.getXXDataHist().getVersionListOfObject(policyId, AppConstants.CLASS_TYPE_RANGER_POLICY); + + VXString vXString = new VXString(); + + vXString.setValue(StringUtils.join(versionList, ",")); + + return vXString; + } + + public RangerPolicy getPolicyForVersionNumber(Long policyId, int versionNo) { + XXDataHist xDataHist = daoMgr.getXXDataHist().findObjectByVersionNumber(policyId, AppConstants.CLASS_TYPE_RANGER_POLICY, versionNo); + + if (xDataHist == null) { + throw restErrorUtil.createRESTException("No Policy found for given version.", MessageEnums.DATA_NOT_FOUND); + } + + String content = xDataHist.getContent(); + + return jsonUtil.writeJsonToJavaObject(content, RangerPolicy.class); + } + + public Map getMetaDataInfo() { + Map metaDataInfo = new LinkedHashMap<>(); + UserSessionBase usb = ContextUtil.getCurrentUserSession(); + String userId = usb != null ? usb.getLoginId() : null; + DateFormat formatter = new SimpleDateFormat("MMM dd, yyyy h:mm:ss a"); + + metaDataInfo.put(HOSTNAME, LOCAL_HOSTNAME); + metaDataInfo.put(USER_NAME, userId); + metaDataInfo.put(TIMESTAMP, formatter.format(MiscUtil.getUTCDateForLocalDate(new Date()))); + metaDataInfo.put(RANGER_VERSION, RangerVersionInfo.getVersion()); + + return metaDataInfo; + } + + public Map getMapFromInputStream(InputStream mapStream) throws IOException { + LOG.debug("==> ServiceDBStore.getMapFromInputStream()"); + + Map inputMap = new LinkedHashMap<>(); + String inputMapString = IOUtils.toString(mapStream); + + if (StringUtils.isNotEmpty(inputMapString)) { + inputMap = jsonUtil.jsonToMap(inputMapString); + } + + if (!CollectionUtils.sizeIsEmpty(inputMap)) { + LOG.debug("<== ServiceDBStore.getMapFromInputStream()"); + + return inputMap; + } else { + LOG.error("Provided zone/service input map is empty!!"); + + throw restErrorUtil.createRESTException("Provided zone/service map is empty!!"); + } + } + + public Map setPolicyMapKeyValue(Map policiesMap, RangerPolicy policy) { + if (StringUtils.isNotEmpty(policy.getName().trim()) && StringUtils.isNotEmpty(policy.getService().trim()) && StringUtils.isNotEmpty(policy.getResources().toString().trim())) { + policiesMap.put(policy.getName().trim() + " " + policy.getService().trim() + " " + policy.getResources().toString().trim() + " " + policy.getZoneName(), policy); + } else if (StringUtils.isEmpty(policy.getName().trim()) && StringUtils.isNotEmpty(policy.getService().trim())) { + LOG.error("Policy Name is not provided for service : {}", policy.getService().trim()); + + throw restErrorUtil.createRESTException("Policy Name is not provided for service : " + policy.getService().trim()); + } else if (StringUtils.isNotEmpty(policy.getName().trim()) && StringUtils.isEmpty(policy.getService().trim())) { + LOG.error("Service Name is not provided for policy : {}", policy.getName().trim()); + + throw restErrorUtil.createRESTException("Service Name is not provided for policy : " + policy.getName().trim()); + } else { + LOG.error("Service Name or Policy Name is not provided!!"); + + throw restErrorUtil.createRESTException("Service Name or Policy Name is not provided!!"); + } + + return policiesMap; + } + + public Map createPolicyMap(Map zoneMappingMap, List sourceZones, String destinationZoneName, Map servicesMappingMap, List sourceServices, List destinationServices, RangerPolicy policy, Map policiesMap) { + if (!CollectionUtils.sizeIsEmpty(zoneMappingMap)) { + policy.setZoneName(destinationZoneName); // set destination zone name in policy. + } + + if (!CollectionUtils.sizeIsEmpty(servicesMappingMap)) { + if (!StringUtils.isEmpty(policy.getService().trim())) { + if (sourceServices.contains(policy.getService().trim())) { + int index = sourceServices.indexOf(policy.getService().trim()); + + policy.setService(destinationServices.get(index)); + + policiesMap = setPolicyMapKeyValue(policiesMap, policy); + } + } else { + LOG.error("Service Name or Policy Name is not provided!!"); + + throw restErrorUtil.createRESTException("Service Name or Policy Name is not provided!!"); + } + } else if (CollectionUtils.sizeIsEmpty(servicesMappingMap)) { + policiesMap = setPolicyMapKeyValue(policiesMap, policy); + } + + return policiesMap; + } + + public void getServiceUpgraded() { + LOG.info("==> ServiceDBStore.getServiceUpgraded()"); + + updateServiceWithCustomProperty(); + + LOG.info("<== ServiceDBStore.getServiceUpgraded()"); + } + + public void resetPolicyUpdateLog(int retentionInDays, Integer policyChangeType) { + LOG.debug("==> resetPolicyUpdateLog({}, {})", retentionInDays, policyChangeType); + + daoMgr.getXXPolicyChangeLog().deleteOlderThan(retentionInDays); + + List allServiceIds = daoMgr.getXXService().getAllServiceIds(); + + if (CollectionUtils.isNotEmpty(allServiceIds)) { + for (Long serviceId : allServiceIds) { + ServiceVersionUpdater updater = new ServiceVersionUpdater(daoMgr, serviceId, VERSION_TYPE.POLICY_VERSION, null, policyChangeType, null); + + persistVersionChange(updater); + } + } + + LOG.debug("<== resetPolicyUpdateLog({}, {})", retentionInDays, policyChangeType); + } + + public void resetTagUpdateLog(int retentionInDays, ServiceTags.TagsChangeType tagChangeType) { + LOG.debug("==> resetTagUpdateLog({}, {})", retentionInDays, tagChangeType); + + daoMgr.getXXTagChangeLog().deleteOlderThan(retentionInDays); + + List allServiceIds = daoMgr.getXXService().getAllServiceIds(); + + if (CollectionUtils.isNotEmpty(allServiceIds)) { + for (Long serviceId : allServiceIds) { + ServiceVersionUpdater updater = new ServiceVersionUpdater(daoMgr, serviceId, VERSION_TYPE.TAG_VERSION, tagChangeType, null, null); + + persistVersionChange(updater); + } + } + + LOG.debug("<== resetTagUpdateLog({}, {})", retentionInDays, tagChangeType); + } + + public void removeAuthSessions(int retentionInDays, List result) { + LOG.debug("==> removeAuthSessions({})", retentionInDays); + + if (retentionInDays > 0) { + XXAuthSessionDao dao = daoMgr.getXXAuthSession(); + long rowsCount = dao.getAllCount(); + long rowsDeleted = dao.deleteOlderThan(retentionInDays); + + LOG.info("Deleted {} records from x_auth_sess that are older than {} days", rowsDeleted, retentionInDays); + + svcService.createTransactionLog(new XXTrxLogV2(AppConstants.CLASS_TYPE_AUTH_SESS, null, null, "Deleted Auth Session records"), "Records count", "Total Records : " + rowsCount, "Deleted Records : " + rowsDeleted); + + result.add(new RangerPurgeResult(ServiceREST.PURGE_RECORD_TYPE_LOGIN_LOGS, rowsCount, rowsDeleted)); + } + + LOG.debug("<== removeAuthSessions({})", retentionInDays); + } + + public void removeTransactionLogs(int retentionInDays, List result) { + LOG.debug("==> removeTransactionLogs({})", retentionInDays); + + if (retentionInDays > 0) { + XXTrxLogV2Dao dao = daoMgr.getXXTrxLogV2(); + long rowsCount = dao.getAllCount(); + long rowsDeleted = dao.deleteOlderThan(retentionInDays); + + LOG.info("Deleted {} records from x_trx_log that are older than {} days", rowsDeleted, retentionInDays); + + svcService.createTransactionLog(new XXTrxLogV2(AppConstants.CLASS_TYPE_TRX_LOG, null, null, "Deleted Transaction records"), "Records count", "Total Records : " + rowsCount, "Deleted Records : " + rowsDeleted); + + result.add(new RangerPurgeResult(ServiceREST.PURGE_RECORD_TYPE_TRX_LOGS, rowsCount, rowsDeleted)); + } + + LOG.debug("<== removeTransactionLogs({})", retentionInDays); + } + + public void removePolicyExportLogs(int retentionInDays, List result) { + LOG.debug("==> removePolicyExportLogs({})", retentionInDays); + + if (retentionInDays > 0) { + XXPolicyExportAuditDao dao = daoMgr.getXXPolicyExportAudit(); + long rowsCount = dao.getAllCount(); + long rowsDeleted = dao.deleteOlderThan(retentionInDays); + + LOG.info("Deleted {} records from x_policy_export_audit that are older than {} days", rowsDeleted, retentionInDays); + + policyService.createTransactionLog(new XXTrxLogV2(AppConstants.CLASS_TYPE_XA_POLICY_EXPORT_AUDIT, null, null, "Deleted policy export audit records"), "Records count", "Total Records : " + rowsCount, "Deleted Records : " + rowsDeleted); + + result.add(new RangerPurgeResult(ServiceREST.PURGE_RECORD_TYPE_POLICY_EXPORT_LOGS, rowsCount, rowsDeleted)); + } + + LOG.debug("<== removePolicyExportLogs({})", retentionInDays); + } + + public List getPolicyLabels(SearchFilter searchFilter) { + LOG.debug("==> ServiceDBStore.getPolicyLabels()"); + + VXPolicyLabelList vxPolicyLabelList = new VXPolicyLabelList(); + List xPolList = policyLabelsService.searchResources(searchFilter, policyLabelsService.searchFields, policyLabelsService.sortFields, vxPolicyLabelList); + List result = new ArrayList<>(); + + for (XXPolicyLabel xPolicyLabel : xPolList) { + result.add(xPolicyLabel.getPolicyLabel()); + } + + LOG.debug("<== ServiceDBStore.getPolicyLabels()"); + + return result; + } + + /** + * This method returns {@linkplain java.util.Map map} representing policy count for each service Definition, + * filtered by policy type, if policy type is not valid (null or less than zero) default policy type will + * be used (ie Resource Access) + * + * @param policyType + * @return {@linkplain java.util.Map map} representing policy count for each service Definition + */ + public Map getPolicyCountByTypeAndServiceType(Integer policyType) { + int type = 0; + + if ((!Objects.isNull(policyType)) && policyType >= 0) { + type = policyType; + } + + return daoMgr.getXXServiceDef().getPolicyCountByType(type); + } + + public Map getPolicyCountByDenyConditionsAndServiceDef() { + return daoMgr.getXXServiceDef().getPolicyCountByDenyItems(); + } + + public Map getServiceCountByType() { + return daoMgr.getXXServiceDef().getServiceCount(); + } + + public String getMetricByType(final METRIC_TYPE metricType) throws Exception { + LOG.debug("==> ServiceDBStore.getMetricByType({})", metricType); + + String ret = null; + + try { + SearchCriteria searchCriteria = new SearchCriteria(); + + searchCriteria.setStartIndex(0); + searchCriteria.setMaxRows(100); + searchCriteria.setGetCount(true); + searchCriteria.setSortType("asc"); + + ret = metricType.getMetric(this, searchCriteria); + } catch (Exception e) { + LOG.error("ServiceDBStore.getMetricByType({}): Error calculating Metric : {}", metricType, e.getMessage()); + } + + LOG.debug("== ServiceDBStore.getMetricByType({}): {}", metricType, ret); + + return ret; + } + + public boolean isServiceAdminUser(String serviceName, String userName) { + boolean ret = false; + XXServiceConfigMapDao svcCfgMapDao = daoMgr.getXXServiceConfigMap(); + XXServiceConfigMap cfgSvcAdminUsers = svcCfgMapDao.findByServiceNameAndConfigKey(serviceName, SERVICE_ADMIN_USERS); + String svcAdminUsers = cfgSvcAdminUsers != null ? cfgSvcAdminUsers.getConfigvalue() : null; + + if (svcAdminUsers != null) { + for (String svcAdminUser : svcAdminUsers.split(",")) { + if (userName.equals(svcAdminUser)) { + ret = true; + break; + } + } + } + + if (!ret) { + XXServiceConfigMap cfgSvcAdminGroups = svcCfgMapDao.findByServiceNameAndConfigKey(serviceName, SERVICE_ADMIN_GROUPS); + String svcAdminGroups = cfgSvcAdminGroups != null ? cfgSvcAdminGroups.getConfigvalue() : null; + + if (StringUtils.isNotBlank(svcAdminGroups)) { + Set userGroups = xUserMgr.getGroupsForUser(userName); + + if (CollectionUtils.isNotEmpty(userGroups)) { + for (String svcAdminGroup : svcAdminGroups.split(",")) { + if (RangerConstants.GROUP_PUBLIC.equals(svcAdminGroup) || userGroups.contains(svcAdminGroup)) { + ret = true; + + break; + } + } + } + } + } + + return ret; + } + + public void updateServiceAuditConfig(String searchUsrGrpRoleName, REMOVE_REF_TYPE removeRefType) { + LOG.debug("===> ServiceDBStore.updateServiceAuditConfig( searchUsrGrpRoleName : {} removeRefType : {})", searchUsrGrpRoleName, removeRefType); + + List configMapToBeModified = getAuditFiltersServiceConfigByName(searchUsrGrpRoleName); + + if (CollectionUtils.isNotEmpty(configMapToBeModified)) { + for (XXServiceConfigMap xConfigMap : configMapToBeModified) { + String jsonStr = xConfigMap.getConfigvalue() != null ? xConfigMap.getConfigvalue() : null; + + if (StringUtils.isNotBlank(jsonStr)) { + List auditFilters = JsonUtils.jsonToAuditFilterList(jsonStr); + int filterCount = auditFilters != null ? auditFilters.size() : 0; + + if (filterCount > 0) { + String userName = null; + String groupName = null; + String roleName = null; + + if (removeRefType == REMOVE_REF_TYPE.USER) { + userName = searchUsrGrpRoleName; + } else if (removeRefType == REMOVE_REF_TYPE.GROUP) { + groupName = searchUsrGrpRoleName; + } else if (removeRefType == REMOVE_REF_TYPE.ROLE) { + roleName = searchUsrGrpRoleName; + } + + removeUserGroupRoleReferences(auditFilters, userName, groupName, roleName); + + String updatedJsonStr = JsonUtils.listToJson(auditFilters); + XXService xService = daoMgr.getXXService().getById(xConfigMap.getServiceId()); + RangerService rangerService = svcService.getPopulatedViewObject(xService); + Map configs = rangerService.getConfigs(); + + if (configs.containsKey(ServiceDBStore.RANGER_PLUGIN_AUDIT_FILTERS)) { + updatedJsonStr = StringUtils.isBlank(updatedJsonStr) ? "" : updatedJsonStr.replaceAll("\"", "'"); + + configs.put(ServiceDBStore.RANGER_PLUGIN_AUDIT_FILTERS, updatedJsonStr); + + try { + LOG.info("==>ServiceDBStore.updateServiceAuditConfig updating audit-filter of service : {} as part of delete request for : {}", rangerService.getName(), searchUsrGrpRoleName); + + updateService(rangerService, null); + } catch (Throwable excp) { + LOG.error("updateService({}) failed", rangerService, excp); + + throw restErrorUtil.createRESTException(excp.getMessage()); + } + } + } else { + LOG.debug("ServiceDBStore.updateServiceAuditConfig audit filter count is zero "); + } + } + } + } else { + LOG.debug("ServiceDBStore.updateServiceAuditConfig no service audit filter Config map found for : {}", searchUsrGrpRoleName); + } + + LOG.debug("<=== ServiceDBStore.updateServiceAuditConfig( searchUsrGrpRoleName : {} removeRefType : {})", searchUsrGrpRoleName, removeRefType); + } + + void createTransactionLog(RangerPolicy policy, int operationImportContext, int operationContext) { + StackTraceElement[] trace = Thread.currentThread().getStackTrace(); + + if (trace.length > 3 && (StringUtils.contains(trace[4].getMethodName(), "import") || StringUtils.contains(trace[5].getMethodName(), "import"))) { + policyService.createTransactionLog(policy, null, operationImportContext); + } else { + policyService.createTransactionLog(policy, null, operationContext); + } + } + + List applyResourceFilter(RangerServiceDef serviceDef, List policies, Map filterResources, SearchFilter filter, RangerPolicyResourceMatcher.MatchScope scope) { + LOG.debug("==> ServiceDBStore.applyResourceFilter(policies-size={}, filterResources={}, {})", policies.size(), filterResources, scope); + + List ret = new ArrayList<>(); + List matchers = getMatchers(serviceDef, filterResources, filter); + + if (CollectionUtils.isNotEmpty(matchers)) { + for (RangerPolicy policy : policies) { + for (RangerPolicyResourceMatcher matcher : matchers) { + LOG.debug("Trying to match for policy:[{}] using RangerDefaultPolicyResourceMatcher:[{}]", policy, matcher); + + if (matcher.isMatch(policy, scope, null)) { + LOG.debug("matched policy:[{}]", policy); + + ret.add(policy); + break; + } + } + } + } + + LOG.debug("<== ServiceDBStore.applyResourceFilter(policies-size={}, filterResources={}, {})", ret.size(), filterResources, scope); + + return ret; + } + + List getMatchers(RangerServiceDef serviceDef, Map filterResources, SearchFilter filter) { + LOG.debug("==> ServiceDBStore.getMatchers(filterResources={})", filterResources); + + List ret = new ArrayList<>(); + RangerServiceDefHelper serviceDefHelper = new RangerServiceDefHelper(serviceDef); + String policyTypeStr = filter.getParam(SearchFilter.POLICY_TYPE); + int[] policyTypes = RangerPolicy.POLICY_TYPES; + + if (StringUtils.isNotBlank(policyTypeStr)) { + policyTypes = new int[1]; + policyTypes[0] = Integer.parseInt(policyTypeStr); + } + + for (Integer policyType : policyTypes) { + Set> validResourceHierarchies = serviceDefHelper.getResourceHierarchies(policyType, filterResources.keySet()); + + LOG.debug("Found {} valid resource hierarchies for key-set {}", validResourceHierarchies.size(), filterResources.keySet()); + + List> resourceHierarchies = new ArrayList<>(validResourceHierarchies); + + for (List validResourceHierarchy : resourceHierarchies) { + LOG.debug("validResourceHierarchy:[{}]", validResourceHierarchy); + + Map policyResources = new HashMap<>(); + + for (RangerResourceDef resourceDef : validResourceHierarchy) { + policyResources.put(resourceDef.getName(), new RangerPolicyResource(filterResources.get(resourceDef.getName()), false, resourceDef.getRecursiveSupported())); + } + + RangerDefaultPolicyResourceMatcher matcher = new RangerDefaultPolicyResourceMatcher(); + + matcher.setServiceDef(serviceDef); + matcher.setPolicyResources(policyResources, policyType); + matcher.init(); + + ret.add(matcher); + + LOG.debug("Added matcher:[{}]", matcher); + } + } + + LOG.debug("<== ServiceDBStore.getMatchers(filterResources={}, , count={})", filterResources, ret.size()); + + return ret; + } + + ServicePolicies getServicePoliciesWithDeltas(RangerServiceDef serviceDef, XXService service, RangerServiceDef tagServiceDef, XXService tagService, Long lastKnownVersion, Long maxNeededVersion) { + ServicePolicies ret = null; + + // if lastKnownVersion != -1L : try and get deltas. Get delta for serviceName first. Find id of the delta + // returned first in the list. and then find all ids greater than that for corresponding tag service. + LOG.debug("==> ServiceDBStore.getServicePoliciesWithDeltas(serviceType={}, serviceId={}, tagServiceId={}, lastKnownVersion={})", serviceDef.getName(), service.getId(), tagService != null ? tagService.getId() : null, lastKnownVersion); + + if (lastKnownVersion != -1L) { + List tagPolicyDeltas = null; + Long retrievedPolicyVersion = null; + Long retrievedTagPolicyVersion = null; + String componentServiceType = serviceDef.getName(); + + List resourcePolicyDeltas = daoMgr.getXXPolicyChangeLog().findLaterThan(lastKnownVersion, maxNeededVersion, service.getId()); + + if (CollectionUtils.isNotEmpty(resourcePolicyDeltas)) { + boolean isValid = RangerPolicyDeltaUtil.isValidDeltas(resourcePolicyDeltas, componentServiceType); + + if (isValid) { + retrievedPolicyVersion = resourcePolicyDeltas.get(resourcePolicyDeltas.size() - 1).getPoliciesVersion(); + } else { + LOG.warn("Resource policy-Deltas :[{}] from version :[{}] are not valid", resourcePolicyDeltas, lastKnownVersion); + } + + if (isValid && tagService != null) { + Long id = resourcePolicyDeltas.get(0).getId(); + + tagPolicyDeltas = daoMgr.getXXPolicyChangeLog().findGreaterThan(id, maxNeededVersion, tagService.getId()); + + if (CollectionUtils.isNotEmpty(tagPolicyDeltas)) { + String tagServiceType = tagServiceDef.getName(); + + isValid = RangerPolicyDeltaUtil.isValidDeltas(tagPolicyDeltas, tagServiceType); + + if (isValid) { + retrievedTagPolicyVersion = tagPolicyDeltas.get(tagPolicyDeltas.size() - 1).getPoliciesVersion(); + } else { + LOG.warn("Tag policy-Deltas :[{}] for service-version :[{}] and delta-id :[{}] are not valid", tagPolicyDeltas, lastKnownVersion, id); + } + } + } + + if (isValid) { + if (CollectionUtils.isNotEmpty(tagPolicyDeltas)) { + // To ensure that resource-policy-deltas with service-type of 'tag' are ignored after validation + resourcePolicyDeltas.removeIf(rangerPolicyDelta -> StringUtils.equals(EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_TAG_NAME, rangerPolicyDelta.getServiceType())); + + resourcePolicyDeltas.addAll(tagPolicyDeltas); + } + + List compressedDeltas = compressDeltas(resourcePolicyDeltas); + + if (compressedDeltas != null) { + ret = new ServicePolicies(); + + ret.setServiceId(service.getId()); + ret.setServiceName(service.getName()); + ret.setServiceDef(serviceDef); + ret.setPolicies(null); + ret.setPolicyDeltas(compressedDeltas); + ret.setPolicyVersion(retrievedPolicyVersion); + + if (tagServiceDef != null && tagService != null) { + ServicePolicies.TagPolicies tagPolicies = new ServicePolicies.TagPolicies(); + + tagPolicies.setServiceDef(tagServiceDef); + tagPolicies.setServiceId(tagService.getId()); + tagPolicies.setServiceName(tagService.getName()); + tagPolicies.setPolicies(null); + tagPolicies.setPolicyVersion(retrievedTagPolicyVersion); + + ret.setTagPolicies(tagPolicies); + } + } else { + LOG.warn("Deltas :[{}] from version :[{}] after compressing are null!", resourcePolicyDeltas, lastKnownVersion); + } + } + } else { + LOG.warn("No policy-deltas found for serviceId={}, tagServiceId={}, lastKnownVersion={})", service.getId(), tagService != null ? tagService.getId() : null, lastKnownVersion); + } + } + + LOG.debug("<== ServiceDBStore.getServicePoliciesWithDeltas(serviceType={}, serviceId={}, tagServiceId={}, lastKnownVersion={}) : deltasSize={}", serviceDef.getName(), service.getId(), tagService != null ? tagService.getId() : null, lastKnownVersion, ret != null && CollectionUtils.isNotEmpty(ret.getPolicyDeltas()) ? ret.getPolicyDeltas().size() : 0); + + return ret; + } + + void createDefaultPolicies(RangerService createdService) throws Exception { + List defaultPolicies = populateDefaultPolicies(createdService); + + if (CollectionUtils.isNotEmpty(defaultPolicies)) { + for (RangerPolicy defaultPolicy : defaultPolicies) { + createDefaultPolicy(defaultPolicy); + } + } + } + + List populateDefaultPolicies(RangerService service) throws Exception { + List ret = null; + RangerBaseService svc = serviceMgr.getRangerServiceByService(service, this); + + if (svc != null) { + List serviceCheckUsers = getServiceCheckUsers(service); + List users = new ArrayList<>(); + + /*Need to create ambari service check user before initiating policy creation. */ + if (serviceCheckUsers != null) { + for (String userName : serviceCheckUsers) { + if (!StringUtils.isEmpty(userName)) { + XXUser xxUser = daoMgr.getXXUser().findByUserName(userName); + + if (xxUser != null) { + xUserService.populateViewBean(xxUser); + } else { + xUserMgr.createServiceConfigUser(userName); + + LOG.info("Creating Ambari Service Check User : {}", userName); + } + + users.add(userName); + } + } + } + + List defaultPolicies = svc.getDefaultRangerPolicies(); + + if (CollectionUtils.isNotEmpty(defaultPolicies)) { + createDefaultPolicyUsersAndGroups(defaultPolicies); + + for (RangerPolicy defaultPolicy : defaultPolicies) { + if (CollectionUtils.isNotEmpty(users) && StringUtils.equalsIgnoreCase(defaultPolicy.getService(), service.getName())) { + RangerPolicyItem defaultAllowPolicyItem = CollectionUtils.isNotEmpty(defaultPolicy.getPolicyItems()) ? defaultPolicy.getPolicyItems().get(0) : null; + + if (defaultAllowPolicyItem == null) { + LOG.error("There is no allow-policy-item in the default-policy:[{}]", defaultPolicy); + } else { + RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem(); + + policyItem.setUsers(users); + policyItem.setAccesses(defaultAllowPolicyItem.getAccesses()); + policyItem.setDelegateAdmin(true); + + defaultPolicy.addPolicyItem(policyItem); + } + } + + boolean isPolicyItemValid = validatePolicyItems(defaultPolicy.getPolicyItems()) + && validatePolicyItems(defaultPolicy.getDenyPolicyItems()) + && validatePolicyItems(defaultPolicy.getAllowExceptions()) + && validatePolicyItems(defaultPolicy.getDenyExceptions()) + && validatePolicyItems(defaultPolicy.getDataMaskPolicyItems()) + && validatePolicyItems(defaultPolicy.getRowFilterPolicyItems()); + + if (isPolicyItemValid) { + if (ret == null) { + ret = new ArrayList<>(); + } + + ret.add(defaultPolicy); + } else { + LOG.warn("Default policy won't be created,since policyItems not valid-either users/groups not present or access not present in policy."); + } + } + } + } + + return ret; + } + + void createDefaultPolicyUsersAndGroups(List defaultPolicies) { + Set defaultPolicyUsers = new HashSet<>(); + Set defaultPolicyGroups = new HashSet<>(); + + for (RangerPolicy defaultPolicy : defaultPolicies) { + for (RangerPolicyItem defaultPolicyItem : defaultPolicy.getPolicyItems()) { + defaultPolicyUsers.addAll(defaultPolicyItem.getUsers()); + defaultPolicyGroups.addAll(defaultPolicyItem.getGroups()); + } + + for (RangerPolicyItem defaultPolicyItem : defaultPolicy.getAllowExceptions()) { + defaultPolicyUsers.addAll(defaultPolicyItem.getUsers()); + defaultPolicyGroups.addAll(defaultPolicyItem.getGroups()); + } + + for (RangerPolicyItem defaultPolicyItem : defaultPolicy.getDenyPolicyItems()) { + defaultPolicyUsers.addAll(defaultPolicyItem.getUsers()); + defaultPolicyGroups.addAll(defaultPolicyItem.getGroups()); + } + + for (RangerPolicyItem defaultPolicyItem : defaultPolicy.getDenyExceptions()) { + defaultPolicyUsers.addAll(defaultPolicyItem.getUsers()); + defaultPolicyGroups.addAll(defaultPolicyItem.getGroups()); + } + + for (RangerPolicyItem defaultPolicyItem : defaultPolicy.getDataMaskPolicyItems()) { + defaultPolicyUsers.addAll(defaultPolicyItem.getUsers()); + defaultPolicyGroups.addAll(defaultPolicyItem.getGroups()); + } + + for (RangerPolicyItem defaultPolicyItem : defaultPolicy.getRowFilterPolicyItems()) { + defaultPolicyUsers.addAll(defaultPolicyItem.getUsers()); + defaultPolicyGroups.addAll(defaultPolicyItem.getGroups()); + } + } + + for (String policyUser : defaultPolicyUsers) { + LOG.debug("Checking policyUser:[{}] for existence", policyUser); + + if (StringUtils.isNotBlank(policyUser) && !StringUtils.equals(policyUser, RangerPolicyEngine.USER_CURRENT) && !StringUtils.equals(policyUser, RangerPolicyEngine.RESOURCE_OWNER)) { + String userName = stringUtil.getValidUserName(policyUser); + XXUser xxUser = daoMgr.getXXUser().findByUserName(userName); + + if (xxUser == null) { + UserSessionBase usb = ContextUtil.getCurrentUserSession(); + + if (usb != null && !usb.isKeyAdmin() && !usb.isUserAdmin() && !usb.isSpnegoEnabled()) { + throw restErrorUtil.createRESTException("User does not exist with given username: [" + policyUser + "] please use existing user", MessageEnums.OPER_NO_PERMISSION); + } + + xUserMgr.createServiceConfigUser(userName); + } + } + } + + for (String policyGroup : defaultPolicyGroups) { + LOG.debug("Checking policyGroup:[{}] for existence", policyGroup); + + if (StringUtils.isNotBlank(policyGroup)) { + XXGroup xxGroup = daoMgr.getXXGroup().findByGroupName(policyGroup); + + if (xxGroup == null) { + UserSessionBase usb = ContextUtil.getCurrentUserSession(); + + if (usb != null && !usb.isKeyAdmin() && !usb.isUserAdmin() && !usb.isSpnegoEnabled()) { + throw restErrorUtil.createRESTException("Group does not exist with given groupname: [" + policyGroup + "] please use existing group", MessageEnums.OPER_NO_PERMISSION); + } + + VXGroup vXGroup = new VXGroup(); + + vXGroup.setName(policyGroup); + vXGroup.setDescription(policyGroup); + vXGroup.setGroupSource(RangerCommonEnums.GROUP_INTERNAL); + vXGroup.setIsVisible(RangerCommonEnums.IS_VISIBLE); + + VXGroup createdVXGrp = xGroupService.createResource(vXGroup); + + xGroupService.createTransactionLog(createdVXGrp, null, OPERATION_CREATE_CONTEXT); + } + } + } + } + + List getServiceCheckUsers(RangerService createdService) { + List ret = new ArrayList<>(); + String userNames = ""; + Map serviceConfig = createdService.getConfigs(); + + if (serviceConfig.containsKey(SERVICE_CHECK_USER)) { + userNames = serviceConfig.get(SERVICE_CHECK_USER); + } else if (serviceConfig.containsKey(AMBARI_SERVICE_CHECK_USER)) { + userNames = serviceConfig.get(AMBARI_SERVICE_CHECK_USER); + } + + if (!StringUtils.isEmpty(userNames)) { + String[] userList = userNames.split(","); + + for (String userName : userList) { + if (!StringUtils.isEmpty(userName)) { + ret.add(userName.trim()); + } + } + } + + return ret; + } + + void updatePolicySignature(RangerPolicy policy) { + String guid = policy.getGuid(); + + if (StringUtils.isEmpty(guid)) { + guid = guidUtil.genGUID(); + + policy.setGuid(guid); + } + + RangerPolicyResourceSignature policySignature = factory.createPolicyResourceSignature(policy); + String signature = policySignature.getSignature(); + + policy.setResourceSignature(signature); + + LOG.debug("Setting signature on policy id={}, name={} to [{}]", policy.getId(), policy.getName(), signature); + } + + boolean hasServiceConfigForPluginChanged(List dbConfigMaps, Map validConfigs) { + boolean ret = false; + Map configs = new HashMap<>(); + + if (CollectionUtils.isNotEmpty(dbConfigMaps)) { + for (XXServiceConfigMap dbConfigMap : dbConfigMaps) { + if (StringUtils.startsWith(dbConfigMap.getConfigkey(), RANGER_PLUGIN_CONFIG_PREFIX)) { + configs.put(dbConfigMap.getConfigkey(), dbConfigMap.getConfigvalue()); + } + } + } + + if (MapUtils.isNotEmpty(validConfigs)) { + for (String key : validConfigs.keySet()) { + if (StringUtils.startsWith(key, RANGER_PLUGIN_CONFIG_PREFIX)) { + if (!StringUtils.equals(configs.get(key), validConfigs.get(key))) { + return true; + } else { + configs.remove(key); + } + } + } + } + + if (!configs.isEmpty()) { + return true; + } + + return ret; + } + + private void updateChildObjectsOfServiceDef(XXServiceDef createdSvcDef, List configs, + List resources, List accessTypes, + List policyConditions, List contextEnrichers, + List enums, RangerDataMaskDef dataMaskDef, RangerRowFilterDef rowFilterDef) { + Long serviceDefId = createdSvcDef.getId(); + List xxConfigs = daoMgr.getXXServiceConfigDef().findByServiceDefId(serviceDefId); + List xxResources = daoMgr.getXXResourceDef().findByServiceDefId(serviceDefId); + List xxAccessTypes = daoMgr.getXXAccessTypeDef().findByServiceDefId(serviceDefId); + List xxPolicyConditions = daoMgr.getXXPolicyConditionDef().findByServiceDefId(serviceDefId); + List xxContextEnrichers = daoMgr.getXXContextEnricherDef().findByServiceDefId(serviceDefId); + List xxEnums = daoMgr.getXXEnumDef().findByServiceDefId(serviceDefId); + XXServiceConfigDefDao xxServiceConfigDao = daoMgr.getXXServiceConfigDef(); + + for (int i = 0; i < configs.size(); i++) { + RangerServiceConfigDef config = configs.get(i); + boolean found = false; + + for (XXServiceConfigDef xConfig : xxConfigs) { + if (config.getItemId() != null && config.getItemId().equals(xConfig.getItemId())) { + found = true; + xConfig = serviceDefService.populateRangerServiceConfigDefToXX(config, xConfig, createdSvcDef, RangerServiceDefService.OPERATION_UPDATE_CONTEXT); + + xConfig.setOrder(i); + + xConfig = xxServiceConfigDao.update(xConfig); + config = serviceDefService.populateXXToRangerServiceConfigDef(xConfig); + break; + } + } + + if (!found) { + XXServiceConfigDef xConfig = new XXServiceConfigDef(); + + xConfig = serviceDefService.populateRangerServiceConfigDefToXX(config, xConfig, createdSvcDef, RangerServiceDefService.OPERATION_CREATE_CONTEXT); + + xConfig.setOrder(i); + + xConfig = xxServiceConfigDao.create(xConfig); + + serviceDefService.populateXXToRangerServiceConfigDef(xConfig); + } + } + + for (XXServiceConfigDef xConfig : xxConfigs) { + boolean found = false; + + for (RangerServiceConfigDef config : configs) { + if (xConfig.getItemId() != null && xConfig.getItemId().equals(config.getItemId())) { + found = true; + break; + } + } + + if (!found) { + xxServiceConfigDao.remove(xConfig); + } + } + + XXResourceDefDao xxResDefDao = daoMgr.getXXResourceDef(); + + for (RangerResourceDef resource : resources) { + boolean found = false; + + for (XXResourceDef xRes : xxResources) { + if (resource.getItemId() != null && resource.getItemId().equals(xRes.getItemId())) { + found = true; + xRes = serviceDefService.populateRangerResourceDefToXX(resource, xRes, createdSvcDef, RangerServiceDefService.OPERATION_UPDATE_CONTEXT); + + xxResDefDao.update(xRes); + + resource = serviceDefService.populateXXToRangerResourceDef(xRes); + break; + } + } + + if (!found) { + XXResourceDef parent = xxResDefDao.findByNameAndServiceDefId(resource.getParent(), serviceDefId); + Long parentId = (parent != null) ? parent.getId() : null; + XXResourceDef xResource = new XXResourceDef(); + + xResource = serviceDefService.populateRangerResourceDefToXX(resource, xResource, createdSvcDef, RangerServiceDefService.OPERATION_CREATE_CONTEXT); + + xResource.setParent(parentId); + + xxResDefDao.create(xResource); + } + } + + for (XXResourceDef xRes : xxResources) { + boolean found = false; + + for (RangerResourceDef resource : resources) { + if (xRes.getItemId() != null && xRes.getItemId().equals(resource.getItemId())) { + found = true; + break; + } + } + + if (!found) { + List xxPolicyRefResource = daoMgr.getXXPolicyRefResource().findByResourceDefID(xRes.getId()); + + if (!stringUtil.isEmpty(xxPolicyRefResource)) { + throw restErrorUtil.createRESTException("Policy/Policies are referring to this resource: " + xRes.getName() + ". Please remove such references from policy before updating service-def.", MessageEnums.DATA_NOT_UPDATABLE); + } + + deleteXXResourceDef(xRes); + } + } + + XXAccessTypeDefDao xxATDDao = daoMgr.getXXAccessTypeDef(); + + for (int i = 0; i < accessTypes.size(); i++) { + RangerAccessTypeDef access = accessTypes.get(i); + boolean found = false; + + for (XXAccessTypeDef xAccess : xxAccessTypes) { + if (access.getItemId() != null && access.getItemId().equals(xAccess.getItemId())) { + found = true; + xAccess = serviceDefService.populateRangerAccessTypeDefToXX(access, xAccess, createdSvcDef, RangerServiceDefService.OPERATION_UPDATE_CONTEXT); + + xAccess.setOrder(i); + + xAccess = xxATDDao.update(xAccess); + + Collection impliedGrants = access.getImpliedGrants(); + XXAccessTypeDefGrantsDao xxATDGrantDao = daoMgr.getXXAccessTypeDefGrants(); + List xxImpliedGrants = xxATDGrantDao.findImpliedGrantsByATDId(xAccess.getId()); + + for (String impliedGrant : impliedGrants) { + boolean foundGrant = false; + + for (String xImpliedGrant : xxImpliedGrants) { + if (StringUtils.equalsIgnoreCase(impliedGrant, xImpliedGrant)) { + foundGrant = true; + break; + } + } + + if (!foundGrant) { + XXAccessTypeDefGrants xImpliedGrant = new XXAccessTypeDefGrants(); + + xImpliedGrant.setAtdId(xAccess.getId()); + xImpliedGrant.setImpliedGrant(impliedGrant); + + xxATDGrantDao.create(xImpliedGrant); + } + } + + for (String xImpliedGrant : xxImpliedGrants) { + boolean foundGrant = false; + + for (String impliedGrant : impliedGrants) { + if (StringUtils.equalsIgnoreCase(xImpliedGrant, impliedGrant)) { + foundGrant = true; + break; + } + } + + if (!foundGrant) { + XXAccessTypeDefGrants xATDGrant = xxATDGrantDao.findByNameAndATDId(xAccess.getId(), xImpliedGrant); + + xxATDGrantDao.remove(xATDGrant); + } + } + + access = serviceDefService.populateXXToRangerAccessTypeDef(xAccess); + break; + } + } + + if (!found) { + XXAccessTypeDef xAccessType = new XXAccessTypeDef(); + + xAccessType = serviceDefService.populateRangerAccessTypeDefToXX(access, xAccessType, createdSvcDef, RangerServiceDefService.OPERATION_CREATE_CONTEXT); + + xAccessType.setOrder(i); + + xAccessType = xxATDDao.create(xAccessType); + + Collection impliedGrants = access.getImpliedGrants(); + XXAccessTypeDefGrantsDao xxATDGrantDao = daoMgr.getXXAccessTypeDefGrants(); + + for (String impliedGrant : impliedGrants) { + XXAccessTypeDefGrants xImpliedGrant = new XXAccessTypeDefGrants(); + + xImpliedGrant.setAtdId(xAccessType.getId()); + xImpliedGrant.setImpliedGrant(impliedGrant); + + xxATDGrantDao.create(xImpliedGrant); + } + + serviceDefService.populateXXToRangerAccessTypeDef(xAccessType); + } + } + + for (XXAccessTypeDef xAccess : xxAccessTypes) { + boolean found = false; + + for (RangerAccessTypeDef access : accessTypes) { + if (xAccess.getItemId() != null && xAccess.getItemId().equals(access.getItemId())) { + found = true; + break; + } + } + + if (!found) { + List policyRefAccessTypeList = daoMgr.getXXPolicyRefAccessType().findByAccessTypeDefId(xAccess.getId()); + + if (!stringUtil.isEmpty(policyRefAccessTypeList)) { + throw restErrorUtil.createRESTException("Policy/Policies are referring to this access-type: " + xAccess.getName() + ". Please remove such references from policy before updating service-def.", MessageEnums.DATA_NOT_UPDATABLE); + } + + deleteXXAccessTypeDef(xAccess); + } + } + + XXPolicyConditionDefDao xxPolCondDao = daoMgr.getXXPolicyConditionDef(); + + for (int i = 0; i < policyConditions.size(); i++) { + RangerPolicyConditionDef condition = policyConditions.get(i); + boolean found = false; + + for (XXPolicyConditionDef xCondition : xxPolicyConditions) { + if (condition.getItemId() != null && condition.getItemId().equals(xCondition.getItemId())) { + found = true; + xCondition = serviceDefService.populateRangerPolicyConditionDefToXX(condition, xCondition, createdSvcDef, RangerServiceDefService.OPERATION_UPDATE_CONTEXT); + + xCondition.setOrder(i); + + xCondition = xxPolCondDao.update(xCondition); + condition = serviceDefService.populateXXToRangerPolicyConditionDef(xCondition); + break; + } + } + + if (!found) { + XXPolicyConditionDef xCondition = new XXPolicyConditionDef(); + + xCondition = serviceDefService.populateRangerPolicyConditionDefToXX(condition, xCondition, createdSvcDef, RangerServiceDefService.OPERATION_CREATE_CONTEXT); + + xCondition.setOrder(i); + + xCondition = xxPolCondDao.create(xCondition); + + serviceDefService.populateXXToRangerPolicyConditionDef(xCondition); + } + } + + for (XXPolicyConditionDef xCondition : xxPolicyConditions) { + boolean found = false; + + for (RangerPolicyConditionDef condition : policyConditions) { + if (xCondition.getItemId() != null && xCondition.getItemId().equals(condition.getItemId())) { + found = true; + break; + } + } + + if (!found) { + List xxPolicyRefConditions = daoMgr.getXXPolicyRefCondition().findByConditionDefId(xCondition.getId()); + + if (!stringUtil.isEmpty(xxPolicyRefConditions)) { + throw restErrorUtil.createRESTException("Policy/Policies are referring to this policy-condition: " + xCondition.getName() + ". Please remove such references from policy before updating service-def.", MessageEnums.DATA_NOT_UPDATABLE); + } + + for (XXPolicyRefCondition xxPolicyRefCondition : xxPolicyRefConditions) { + daoMgr.getXXPolicyRefCondition().remove(xxPolicyRefCondition); + } + + xxPolCondDao.remove(xCondition); + } + } + + XXContextEnricherDefDao xxContextEnricherDao = daoMgr.getXXContextEnricherDef(); + + for (int i = 0; i < contextEnrichers.size(); i++) { + RangerContextEnricherDef context = contextEnrichers.get(i); + boolean found = false; + + for (XXContextEnricherDef xContext : xxContextEnrichers) { + if (context.getItemId() != null && context.getItemId().equals(xContext.getItemId())) { + found = true; + xContext = serviceDefService.populateRangerContextEnricherDefToXX(context, xContext, createdSvcDef, RangerServiceDefService.OPERATION_UPDATE_CONTEXT); + + xContext.setOrder(i); + + xContext = xxContextEnricherDao.update(xContext); + context = serviceDefService.populateXXToRangerContextEnricherDef(xContext); + break; + } + } + + if (!found) { + XXContextEnricherDef xContext = new XXContextEnricherDef(); + + xContext = serviceDefService.populateRangerContextEnricherDefToXX(context, xContext, createdSvcDef, RangerServiceDefService.OPERATION_UPDATE_CONTEXT); + + xContext.setOrder(i); + + xContext = xxContextEnricherDao.create(xContext); + + serviceDefService.populateXXToRangerContextEnricherDef(xContext); + } + } + + for (XXContextEnricherDef xContext : xxContextEnrichers) { + boolean found = false; + + for (RangerContextEnricherDef context : contextEnrichers) { + if (xContext.getItemId() != null && xContext.getItemId().equals(context.getItemId())) { + found = true; + break; + } + } + + if (!found) { + daoMgr.getXXContextEnricherDef().remove(xContext); + } + } + + XXEnumDefDao xxEnumDefDao = daoMgr.getXXEnumDef(); + + for (RangerEnumDef enumDef : enums) { + boolean found = false; + + for (XXEnumDef xEnumDef : xxEnums) { + if (enumDef.getItemId() != null && enumDef.getItemId().equals(xEnumDef.getItemId())) { + found = true; + xEnumDef = serviceDefService.populateRangerEnumDefToXX(enumDef, xEnumDef, createdSvcDef, RangerServiceDefService.OPERATION_UPDATE_CONTEXT); + xEnumDef = xxEnumDefDao.update(xEnumDef); + + XXEnumElementDefDao xEnumEleDao = daoMgr.getXXEnumElementDef(); + List xxEnumEleDefs = xEnumEleDao.findByEnumDefId(xEnumDef.getId()); + List enumEleDefs = enumDef.getElements(); + + for (int i = 0; i < enumEleDefs.size(); i++) { + RangerEnumElementDef eleDef = enumEleDefs.get(i); + boolean foundEle = false; + + for (XXEnumElementDef xEleDef : xxEnumEleDefs) { + if (eleDef.getItemId() != null && eleDef.getItemId().equals(xEleDef.getItemId())) { + foundEle = true; + xEleDef = serviceDefService.populateRangerEnumElementDefToXX(eleDef, xEleDef, xEnumDef, RangerServiceDefService.OPERATION_UPDATE_CONTEXT); + + xEleDef.setOrder(i); + + xEnumEleDao.update(xEleDef); + break; + } + } + + if (!foundEle) { + XXEnumElementDef xElement = new XXEnumElementDef(); + + xElement = serviceDefService.populateRangerEnumElementDefToXX(eleDef, xElement, xEnumDef, RangerServiceDefService.OPERATION_CREATE_CONTEXT); + + xElement.setOrder(i); + + xEnumEleDao.create(xElement); + } + } + + for (XXEnumElementDef xxEleDef : xxEnumEleDefs) { + boolean foundEle = false; + + for (RangerEnumElementDef enumEle : enumEleDefs) { + if (xxEleDef.getItemId() != null && xxEleDef.getItemId().equals(enumEle.getItemId())) { + foundEle = true; + break; + } + } + + if (!foundEle) { + xEnumEleDao.remove(xxEleDef); + } + } + + enumDef = serviceDefService.populateXXToRangerEnumDef(xEnumDef); + break; + } + } + + if (!found) { + XXEnumDef xEnum = new XXEnumDef(); + + xEnum = serviceDefService.populateRangerEnumDefToXX(enumDef, xEnum, createdSvcDef, RangerServiceDefService.OPERATION_CREATE_CONTEXT); + + xEnum = xxEnumDefDao.create(xEnum); + + List elements = enumDef.getElements(); + XXEnumElementDefDao xxEnumEleDefDao = daoMgr.getXXEnumElementDef(); + + for (RangerEnumElementDef element : elements) { + XXEnumElementDef xElement = new XXEnumElementDef(); + + xElement = serviceDefService.populateRangerEnumElementDefToXX(element, xElement, xEnum, RangerServiceDefService.OPERATION_CREATE_CONTEXT); + + xxEnumEleDefDao.create(xElement); + } + + serviceDefService.populateXXToRangerEnumDef(xEnum); + } + } + + for (XXEnumDef xEnumDef : xxEnums) { + boolean found = false; + + for (RangerEnumDef enumDef : enums) { + if (xEnumDef.getItemId() != null && xEnumDef.getItemId().equals(enumDef.getItemId())) { + found = true; + break; + } + } + + if (!found) { + List enumEleDefList = daoMgr.getXXEnumElementDef().findByEnumDefId(xEnumDef.getId()); + + for (XXEnumElementDef eleDef : enumEleDefList) { + daoMgr.getXXEnumElementDef().remove(eleDef); + } + + xxEnumDefDao.remove(xEnumDef); + } + } + + List dataMasks = dataMaskDef == null || dataMaskDef.getMaskTypes() == null ? new ArrayList<>() : dataMaskDef.getMaskTypes(); + List dataMaskAccessTypes = dataMaskDef == null || dataMaskDef.getAccessTypes() == null ? new ArrayList<>() : dataMaskDef.getAccessTypes(); + List dataMaskResources = dataMaskDef == null || dataMaskDef.getResources() == null ? new ArrayList<>() : dataMaskDef.getResources(); + List rowFilterAccessTypes = rowFilterDef == null || rowFilterDef.getAccessTypes() == null ? new ArrayList<>() : rowFilterDef.getAccessTypes(); + List rowFilterResources = rowFilterDef == null || rowFilterDef.getResources() == null ? new ArrayList<>() : rowFilterDef.getResources(); + XXDataMaskTypeDefDao dataMaskTypeDao = daoMgr.getXXDataMaskTypeDef(); + List xxDataMaskTypes = dataMaskTypeDao.findByServiceDefId(serviceDefId); + List xxAccessTypeDefs = xxATDDao.findByServiceDefId(serviceDefId); + List xxResourceDefs = xxResDefDao.findByServiceDefId(serviceDefId); + + // create or update dataMasks + for (int i = 0; i < dataMasks.size(); i++) { + RangerDataMaskTypeDef dataMask = dataMasks.get(i); + boolean found = false; + + for (XXDataMaskTypeDef xxDataMask : xxDataMaskTypes) { + if (xxDataMask.getItemId() != null && xxDataMask.getItemId().equals(dataMask.getItemId())) { + LOG.debug("Updating existing dataMask with itemId={}", dataMask.getItemId()); + + found = true; + xxDataMask = serviceDefService.populateRangerDataMaskDefToXX(dataMask, xxDataMask, createdSvcDef, RangerServiceDefService.OPERATION_UPDATE_CONTEXT); + + xxDataMask.setOrder(i); + + xxDataMask = dataMaskTypeDao.update(xxDataMask); + dataMask = serviceDefService.populateXXToRangerDataMaskTypeDef(xxDataMask); + break; + } + } + + if (!found) { + LOG.debug("Creating dataMask with itemId={}", dataMask.getItemId()); + + XXDataMaskTypeDef xxDataMask = new XXDataMaskTypeDef(); + + xxDataMask = serviceDefService.populateRangerDataMaskDefToXX(dataMask, xxDataMask, createdSvcDef, RangerServiceDefService.OPERATION_CREATE_CONTEXT); + + xxDataMask.setOrder(i); + + dataMaskTypeDao.create(xxDataMask); + } + } + + // remove dataMasks + for (XXDataMaskTypeDef xxDataMask : xxDataMaskTypes) { + boolean found = false; + + for (RangerDataMaskTypeDef dataMask : dataMasks) { + if (xxDataMask.getItemId() != null && xxDataMask.getItemId().equals(dataMask.getItemId())) { + found = true; + break; + } + } + + if (!found) { + LOG.debug("Deleting dataMask with itemId={}", xxDataMask.getItemId()); + + dataMaskTypeDao.remove(xxDataMask); + } + } + + for (RangerAccessTypeDef accessType : dataMaskAccessTypes) { + if (!isAccessTypeInList(accessType.getName(), xxAccessTypeDefs)) { + throw restErrorUtil.createRESTException("accessType with name: " + accessType.getName() + " does not exist", MessageEnums.DATA_NOT_FOUND); + } + } + + for (RangerAccessTypeDef accessType : rowFilterAccessTypes) { + if (!isAccessTypeInList(accessType.getName(), xxAccessTypeDefs)) { + throw restErrorUtil.createRESTException("accessType with name: " + accessType.getName() + " does not exists", MessageEnums.DATA_NOT_FOUND); + } + } + + for (XXAccessTypeDef xxAccessTypeDef : xxAccessTypeDefs) { + String dataMaskOptions = null; + String rowFilterOptions = null; + + for (RangerAccessTypeDef accessTypeDef : dataMaskAccessTypes) { + if (StringUtils.equals(accessTypeDef.getName(), xxAccessTypeDef.getName())) { + dataMaskOptions = svcDefServiceWithAssignedId.objectToJson(accessTypeDef); + break; + } + } + + for (RangerAccessTypeDef accessTypeDef : rowFilterAccessTypes) { + if (StringUtils.equals(accessTypeDef.getName(), xxAccessTypeDef.getName())) { + rowFilterOptions = svcDefServiceWithAssignedId.objectToJson(accessTypeDef); + break; + } + } + + if (!StringUtils.equals(dataMaskOptions, xxAccessTypeDef.getDataMaskOptions()) || !StringUtils.equals(rowFilterOptions, xxAccessTypeDef.getRowFilterOptions())) { + xxAccessTypeDef.setDataMaskOptions(dataMaskOptions); + xxAccessTypeDef.setRowFilterOptions(rowFilterOptions); + + xxATDDao.update(xxAccessTypeDef); + } + } + + for (RangerResourceDef resource : dataMaskResources) { + if (!isResourceInList(resource.getName(), xxResourceDefs)) { + throw restErrorUtil.createRESTException("resource with name: " + resource.getName() + " does not exists", MessageEnums.DATA_NOT_FOUND); + } + } + + for (RangerResourceDef resource : rowFilterResources) { + if (!isResourceInList(resource.getName(), xxResourceDefs)) { + throw restErrorUtil.createRESTException("resource with name: " + resource.getName() + " does not exists", MessageEnums.DATA_NOT_FOUND); + } + } + + for (XXResourceDef xxResourceDef : xxResourceDefs) { + String dataMaskOptions = null; + String rowFilterOptions = null; + + for (RangerResourceDef resource : dataMaskResources) { + if (StringUtils.equals(resource.getName(), xxResourceDef.getName())) { + dataMaskOptions = svcDefServiceWithAssignedId.objectToJson(resource); + break; + } + } + + for (RangerResourceDef resource : rowFilterResources) { + if (StringUtils.equals(resource.getName(), xxResourceDef.getName())) { + rowFilterOptions = svcDefServiceWithAssignedId.objectToJson(resource); + break; + } + } + + if (!StringUtils.equals(dataMaskOptions, xxResourceDef.getDataMaskOptions()) || !StringUtils.equals(rowFilterOptions, xxResourceDef.getRowFilterOptions())) { + xxResourceDef.setDataMaskOptions(dataMaskOptions); + xxResourceDef.setRowFilterOptions(rowFilterOptions); + + xxResDefDao.update(xxResourceDef); + } + } + } + + private void updateTabPermissions(String svcType, Map svcConfig) { + if (StringUtils.equalsIgnoreCase(svcType, EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_TAG_NAME)) { + String svcAdminUsers = svcConfig.get(SERVICE_ADMIN_USERS); + + if (StringUtils.isNotEmpty(svcAdminUsers)) { + for (String user : svcAdminUsers.split(",")) { + validateUserAndProvideTabTagBasedPolicyPermission(user.trim()); + } + } + } + } + + private void validateUserAndProvideTabTagBasedPolicyPermission(String username) { + XXPortalUser xxPortalUser = daoMgr.getXXPortalUser().findByLoginId(username); + + if (xxPortalUser == null) { + throw restErrorUtil.createRESTException("Username : " + username + " does not exist. Please provide valid user as service admin for tag service .", MessageEnums.ERROR_CREATING_OBJECT); + } else { + VXPortalUser vXPortalUser = userMgr.mapXXPortalUserToVXPortalUserForDefaultAccount(xxPortalUser); + + if (CollectionUtils.isNotEmpty(vXPortalUser.getUserRoleList()) && vXPortalUser.getUserRoleList().size() == 1) { + for (String userRole : vXPortalUser.getUserRoleList()) { + if (userRole.equals(RangerConstants.ROLE_USER)) { + HashMap moduleNameId = xUserMgr.getAllModuleNameAndIdMap(); + + xUserMgr.createOrUpdateUserPermisson(vXPortalUser, moduleNameId.get(RangerConstants.MODULE_TAG_BASED_POLICIES), true); + } + } + } + } + } + + private boolean validatePolicyItems(List policyItems) { + if (CollectionUtils.isNotEmpty(policyItems)) { + for (RangerPolicyItem policyItem : policyItems) { + if (policyItem == null) { + return false; + } + + if (CollectionUtils.isEmpty(policyItem.getUsers()) && CollectionUtils.isEmpty(policyItem.getGroups()) && CollectionUtils.isEmpty(policyItem.getRoles())) { + return false; + } + + if (policyItem.getUsers() != null && (policyItem.getUsers().contains(null) || policyItem.getUsers().contains(""))) { + return false; + } + + if (policyItem.getGroups() != null && (policyItem.getGroups().contains(null) || policyItem.getGroups().contains(""))) { + return false; + } + + if (policyItem.getRoles() != null && (policyItem.getRoles().contains(null) || policyItem.getRoles().contains(""))) { + return false; + } + + if (CollectionUtils.isEmpty(policyItem.getAccesses()) || policyItem.getAccesses().contains(null)) { + return false; + } + + for (RangerPolicyItemAccess itemAccesses : policyItem.getAccesses()) { + if (itemAccesses.getType() == null || itemAccesses.getIsAllowed() == null) { + return false; + } + } + } + } + + return true; + } + + private List searchRangerTagPoliciesOnBasisOfServiceName(List allExceptTagPolicies) throws Exception { + List ret = new ArrayList<>(); + Set serviceNames = new HashSet<>(); + Map tagServices = new HashMap<>(); + + for (RangerPolicy pol : allExceptTagPolicies) { + serviceNames.add(pol.getService()); + } + + for (String serviceName : serviceNames) { + RangerService service = getServiceByName(serviceName); + + if (StringUtils.isNotBlank(service.getTagService())) { + RangerService tagService = getServiceByName(service.getTagService()); + + if (tagService != null) { + tagServices.put(tagService.getName(), tagService.getId()); + } + } + } + + for (Map.Entry entry : tagServices.entrySet()) { + String tagServiceName = entry.getKey(); + Long tagServiceId = entry.getValue(); + + ServicePolicies tagServicePolicies = RangerServicePoliciesCache.getInstance().getServicePolicies(tagServiceName, tagServiceId, -1L, true, this); + List policies = tagServicePolicies != null ? tagServicePolicies.getPolicies() : null; + + if (policies != null) { + ret.addAll(policies); + } + } + + return ret; + } + + private List getServicePolicies(XXService service, SearchFilter filter) throws Exception { + LOG.debug("==> ServiceDBStore.getServicePolicies()"); + + if (service == null) { + throw new Exception("service does not exist"); + } + + List ret; + ServicePolicies servicePolicies = RangerServicePoliciesCache.getInstance().getServicePolicies(service.getName(), service.getId(), -1L, true, this); + final List policies = servicePolicies != null ? servicePolicies.getPolicies() : null; + + if (policies != null && filter != null && MapUtils.isNotEmpty(filter.getParams())) { + Map filterResources = filter.getParamsWithPrefix(SearchFilter.RESOURCE_PREFIX, true); + String resourceMatchScope = filter.getParam(SearchFilter.RESOURCE_MATCH_SCOPE); + boolean useLegacyResourceSearch = true; + SearchFilter searchFilter = new SearchFilter(filter); + + if (MapUtils.isNotEmpty(filterResources) && resourceMatchScope != null) { + useLegacyResourceSearch = false; + + for (Map.Entry entry : filterResources.entrySet()) { + searchFilter.removeParam(SearchFilter.RESOURCE_PREFIX + entry.getKey()); + } + } + + LOG.debug("Using{}way of filtering service-policies", useLegacyResourceSearch ? " old " : " new "); + + ret = new ArrayList<>(policies); + + predicateUtil.applyFilter(ret, searchFilter); + + if (!useLegacyResourceSearch && CollectionUtils.isNotEmpty(ret)) { + RangerPolicyResourceMatcher.MatchScope scope; + + if (StringUtils.equalsIgnoreCase(resourceMatchScope, "self")) { + scope = RangerPolicyResourceMatcher.MatchScope.SELF; + } else if (StringUtils.equalsIgnoreCase(resourceMatchScope, "ancestor")) { + scope = RangerPolicyResourceMatcher.MatchScope.ANCESTOR; + } else if (StringUtils.equalsIgnoreCase(resourceMatchScope, "self_or_ancestor")) { + scope = RangerPolicyResourceMatcher.MatchScope.SELF_OR_ANCESTOR; + } else { + // DESCENDANT match will never happen + scope = RangerPolicyResourceMatcher.MatchScope.SELF_OR_ANCESTOR; + } + + RangerServiceDef serviceDef = servicePolicies.getServiceDef(); + + switch (scope) { + case SELF: { + serviceDef = RangerServiceDefHelper.getServiceDefForPolicyFiltering(serviceDef); + break; + } + case ANCESTOR: { + Map updatedFilterResources = RangerServiceDefHelper.getFilterResourcesForAncestorPolicyFiltering(serviceDef, filterResources); + + if (MapUtils.isNotEmpty(updatedFilterResources)) { + filterResources.putAll(updatedFilterResources); + + scope = RangerPolicyResourceMatcher.MatchScope.SELF_OR_ANCESTOR; + } + break; + } + default: + break; + } + + ret = applyResourceFilter(serviceDef, ret, filterResources, searchFilter, scope); + } + } else { + ret = policies; + } + + LOG.debug("<== ServiceDBStore.getServicePolicies(): count={}", (ret == null) ? 0 : ret.size()); + + return ret; + } + + private List getServicePoliciesFromDb(XXService service) { + LOG.debug("==> ServiceDBStore.getServicePoliciesFromDb({})", service.getName()); + + RangerPolicyRetriever policyRetriever = new RangerPolicyRetriever(daoMgr, txManager); + List ret = policyRetriever.getServicePolicies(service); + + LOG.debug("<== ServiceDBStore.getServicePoliciesFromDb({}): count={}", service.getName(), (ret == null) ? 0 : ret.size()); + + return ret; + } + + private ServicePolicies getServicePolicies(String serviceName, Long lastKnownVersion, boolean getOnlyDeltas, boolean isDeltaEnabled, Long maxNeededVersion) throws Exception { + LOG.debug("==> ServiceDBStore.getServicePolicies({}, {})", serviceName, lastKnownVersion); + + ServicePolicies ret = null; + XXService serviceDbObj = daoMgr.getXXService().findByName(serviceName); + + if (serviceDbObj == null) { + throw new Exception("service does not exist. name=" + serviceName); + } + + XXServiceVersionInfo serviceVersionInfoDbObj = daoMgr.getXXServiceVersionInfo().findByServiceName(serviceName); + + if (serviceVersionInfoDbObj == null) { + LOG.warn("serviceVersionInfo does not exist. name={}", serviceName); + } + + RangerServiceDef serviceDef = getServiceDef(serviceDbObj.getType()); + + if (serviceDef == null) { + throw new Exception("service-def does not exist. id=" + serviceDbObj.getType()); + } + + String serviceType = serviceDef.getName(); + String auditMode = getAuditMode(serviceType, serviceName); + XXService tagServiceDbObj = null; + RangerServiceDef tagServiceDef = null; + XXServiceVersionInfo tagServiceVersionInfoDbObj = null; + + if (serviceDbObj.getTagService() != null) { + tagServiceDbObj = daoMgr.getXXService().getById(serviceDbObj.getTagService()); + } + + if (tagServiceDbObj != null) { + tagServiceDef = getServiceDef(tagServiceDbObj.getType()); + + if (tagServiceDef == null) { + throw new Exception("service-def does not exist. id=" + tagServiceDbObj.getType()); + } + + ServiceDefUtil.normalizeAccessTypeDefs(tagServiceDef, serviceType); + + tagServiceVersionInfoDbObj = daoMgr.getXXServiceVersionInfo().findByServiceId(serviceDbObj.getTagService()); + + if (tagServiceVersionInfoDbObj == null) { + LOG.warn("serviceVersionInfo does not exist. name={}", tagServiceDbObj.getName()); + } + } + + if (isDeltaEnabled) { + ret = getServicePoliciesWithDeltas(serviceDef, serviceDbObj, tagServiceDef, tagServiceDbObj, lastKnownVersion, maxNeededVersion); + } + + if (ret != null) { + ret.setPolicyUpdateTime(serviceVersionInfoDbObj == null ? null : serviceVersionInfoDbObj.getPolicyUpdateTime()); + ret.setAuditMode(auditMode); + + if (ret.getTagPolicies() != null) { + ret.getTagPolicies().setPolicyUpdateTime(tagServiceVersionInfoDbObj == null ? null : tagServiceVersionInfoDbObj.getPolicyUpdateTime()); + ret.getTagPolicies().setAuditMode(auditMode); + } + } else if (!getOnlyDeltas) { + ServicePolicies.TagPolicies tagPolicies = null; + + if (tagServiceDbObj != null) { + tagPolicies = new ServicePolicies.TagPolicies(); + + tagPolicies.setServiceId(tagServiceDbObj.getId()); + tagPolicies.setServiceName(tagServiceDbObj.getName()); + tagPolicies.setPolicyVersion(tagServiceVersionInfoDbObj == null ? null : tagServiceVersionInfoDbObj.getPolicyVersion()); + tagPolicies.setPolicyUpdateTime(tagServiceVersionInfoDbObj == null ? null : tagServiceVersionInfoDbObj.getPolicyUpdateTime()); + tagPolicies.setPolicies(getServicePoliciesFromDb(tagServiceDbObj)); + tagPolicies.setServiceDef(tagServiceDef); + tagPolicies.setAuditMode(auditMode); + } + + List policies = getServicePoliciesFromDb(serviceDbObj); + + ret = new ServicePolicies(); + + ret.setServiceId(serviceDbObj.getId()); + ret.setServiceName(serviceDbObj.getName()); + ret.setPolicyVersion(serviceVersionInfoDbObj == null ? null : serviceVersionInfoDbObj.getPolicyVersion()); + ret.setPolicyUpdateTime(serviceVersionInfoDbObj == null ? null : serviceVersionInfoDbObj.getPolicyUpdateTime()); + ret.setPolicies(policies); + ret.setServiceDef(serviceDef); + ret.setAuditMode(auditMode); + ret.setTagPolicies(tagPolicies); + } + + LOG.debug("<== ServiceDBStore.getServicePolicies({}, {}): count={}, delta-count={}", serviceName, lastKnownVersion, (ret == null || ret.getPolicies() == null) ? 0 : ret.getPolicies().size(), (ret == null || ret.getPolicyDeltas() == null) ? 0 : ret.getPolicyDeltas().size()); + + return ret; + } + + private static List compressDeltas(List deltas) { + List ret = new ArrayList<>(); + final Map> policyDeltaMap = new HashMap<>(); + + for (RangerPolicyDelta delta : deltas) { + Long policyId = delta.getPolicyId(); + List oldPolicyDeltas = policyDeltaMap.computeIfAbsent(policyId, k -> new ArrayList<>()); + + oldPolicyDeltas.add(delta); + } + + for (Map.Entry> entry : policyDeltaMap.entrySet()) { + List policyDeltas = entry.getValue(); + + if (policyDeltas.size() == 1) { + ret.addAll(policyDeltas); + } else { // Will always be greater than 1 + List policyDeltasForPolicy = new ArrayList<>(); + RangerPolicyDelta first = policyDeltas.get(0); + + policyDeltasForPolicy.add(first); + + int index = 1; + + switch (first.getChangeType()) { + case RangerPolicyDelta.CHANGE_TYPE_POLICY_CREATE: + while (index < policyDeltas.size()) { + RangerPolicyDelta policyDelta = policyDeltas.get(index); + + switch (policyDelta.getChangeType()) { + case RangerPolicyDelta.CHANGE_TYPE_POLICY_CREATE: + LOG.error("Multiple policy creates!! [{}]", policyDelta); + + policyDeltasForPolicy = null; + break; + case RangerPolicyDelta.CHANGE_TYPE_POLICY_UPDATE: + for (int i = index + 1; i < policyDeltas.size(); i++) { + RangerPolicyDelta next = policyDeltas.get(i); + + if (next.getChangeType() == RangerPolicyDelta.CHANGE_TYPE_POLICY_UPDATE) { + index = i; + } else { + break; + } + } + + policyDeltasForPolicy.clear(); + policyDeltas.get(index).setChangeType(RangerPolicyDelta.CHANGE_TYPE_POLICY_CREATE); + policyDeltasForPolicy.add(policyDeltas.get(index)); + index++; + break; + case RangerPolicyDelta.CHANGE_TYPE_POLICY_DELETE: + if (policyDeltas.size() == index + 1) { + // Last one + policyDeltasForPolicy.clear(); + index++; + } else { + LOG.error("CHANGE_TYPE_POLICY_DELETE should be the last policyDelta, found:[{}]", policyDeltas.get(index + 1)); + + policyDeltasForPolicy = null; + } + break; + default: + break; + } + if (policyDeltasForPolicy == null) { + break; + } + } + break; + case RangerPolicyDelta.CHANGE_TYPE_POLICY_UPDATE: + while (index < policyDeltas.size()) { + RangerPolicyDelta policyDelta = policyDeltas.get(index); + + switch (policyDelta.getChangeType()) { + case RangerPolicyDelta.CHANGE_TYPE_POLICY_CREATE: + LOG.error("Should not get here! policy is created after it is updated!! policy-delta:[{}]", policyDelta); + + policyDeltasForPolicy = null; + break; + case RangerPolicyDelta.CHANGE_TYPE_POLICY_UPDATE: + for (int i = index + 1; i < policyDeltas.size(); i++) { + RangerPolicyDelta next = policyDeltas.get(i); + + if (next.getChangeType() == RangerPolicyDelta.CHANGE_TYPE_POLICY_UPDATE) { + index = i; + } else { + break; + } + } + + policyDeltasForPolicy.clear(); + policyDeltasForPolicy.add(policyDeltas.get(index)); + index++; + break; + case RangerPolicyDelta.CHANGE_TYPE_POLICY_DELETE: + if (policyDeltas.size() == index + 1) { + // Last one + policyDeltasForPolicy.clear(); + policyDeltasForPolicy.add(policyDeltas.get(index)); + index++; + } else { + LOG.error("CHANGE_TYPE_POLICY_DELETE should be the last policyDelta, found:[{}]", policyDeltas.get(index + 1)); + + policyDeltasForPolicy = null; + } + break; + default: + break; + } + + if (policyDeltasForPolicy == null) { + break; + } + } + break; + case RangerPolicyDelta.CHANGE_TYPE_POLICY_DELETE: + LOG.error("CHANGE_TYPE_POLICY_DELETE should be the last policyDelta, found:[{}]", policyDeltas.get(index)); + + policyDeltasForPolicy = null; + break; + default: + LOG.error("Should not get here for valid policy-delta:[{}]", first); + break; + } + + if (policyDeltasForPolicy != null) { + LOG.debug("Processed deltas for policy:[{}], compressed-deltas:[{}]", entry.getKey(), policyDeltasForPolicy); + + ret.addAll(policyDeltasForPolicy); + } else { + LOG.error("Error processing deltas for policy:[{}], Cannot compress deltas", entry.getKey()); + + ret = null; + break; + } + } + } + + if (ret != null) { + ret.sort(POLICY_DELTA_ID_COMPARATOR); + } + + return ret; + } + + private Map validateRequiredConfigParams(RangerService service, Map configs) { + LOG.debug("==> ServiceDBStore.validateRequiredConfigParams()"); + + if (configs == null) { + return null; + } + + List svcConfDefList = daoMgr.getXXServiceConfigDef().findByServiceDefName(service.getType()); + + for (XXServiceConfigDef svcConfDef : svcConfDefList) { + String confField = configs.get(svcConfDef.getName()); + + if (svcConfDef.getIsMandatory() && stringUtil.isEmpty(confField)) { + throw restErrorUtil.createRESTException("Please provide value of mandatory: " + svcConfDef.getName(), MessageEnums.INVALID_INPUT_DATA); + } + + if (StringUtils.equals(svcConfDef.getName(), RANGER_PLUGIN_AUDIT_FILTERS)) { + if (svcConfDef.getDefaultvalue() != null && !configs.containsKey(RANGER_PLUGIN_AUDIT_FILTERS)) { + configs.put(RANGER_PLUGIN_AUDIT_FILTERS, svcConfDef.getDefaultvalue()); + } + + if (!stringUtil.isEmpty(configs.get(RANGER_PLUGIN_AUDIT_FILTERS)) && JsonUtils.jsonToAuditFilterList(configs.get(RANGER_PLUGIN_AUDIT_FILTERS)) == null) { + throw restErrorUtil.createRESTException("Invalid value for " + svcConfDef.getName()); + } + } + } + + Map validConfigs = new HashMap<>(); + + for (Entry config : configs.entrySet()) { + if (!stringUtil.isEmpty(config.getValue())) { + validConfigs.put(config.getKey(), config.getValue()); + } + } + + return validConfigs; + } + + private void handlePolicyUpdate(RangerService service, Integer policyDeltaType, RangerPolicy policy, boolean updateServiceInfoRoleVersion) { + updatePolicyVersion(service, policyDeltaType, policy, updateServiceInfoRoleVersion); + } + + private void updatePolicyVersion(RangerService service, Integer policyDeltaType, RangerPolicy policy, boolean updateServiceInfoRoleVersion) { + if (service == null || service.getId() == null) { + return; + } + + XXServiceDao serviceDao = daoMgr.getXXService(); + final XXService serviceDbObj = serviceDao.getById(service.getId()); + + if (serviceDbObj == null) { + LOG.warn("updatePolicyVersion(serviceId={}): service not found", service.getId()); + + return; + } + + final RangerDaoManager daoManager = daoMgr; + final Long serviceId = serviceDbObj.getId(); + + // if this is a tag/gds service, update all services that refer to this service + // so that next policy-download from plugins will get updated tag/gds policies + boolean isTagService = serviceDbObj.getType() == EmbeddedServiceDefsUtil.instance().getTagServiceDefId(); + + if (isTagService) { + List referringServiceIds = serviceDao.findIdsByTagServiceId(serviceId); + + for (Long referringServiceId : referringServiceIds) { + Runnable policyVersionUpdater = new ServiceVersionUpdater(daoManager, referringServiceId, VERSION_TYPE.POLICY_VERSION, policy != null ? policy.getZoneName() : null, policyDeltaType, policy); + + transactionSynchronizationAdapter.executeOnTransactionCommit(policyVersionUpdater); + + if (updateServiceInfoRoleVersion) { + Runnable roleVersionUpdater = new ServiceVersionUpdater(daoManager, referringServiceId, VERSION_TYPE.ROLE_VERSION, policy != null ? policy.getZoneName() : null, policyDeltaType, policy); + + transactionSynchronizationAdapter.executeOnTransactionCommit(roleVersionUpdater); + } + } + } + + final VERSION_TYPE versionType = VERSION_TYPE.POLICY_VERSION; + + Runnable serviceVersionUpdater = new ServiceVersionUpdater(daoManager, serviceId, versionType, policy != null ? policy.getZoneName() : null, policyDeltaType, policy); + + transactionSynchronizationAdapter.executeOnTransactionCommit(serviceVersionUpdater); + + if (updateServiceInfoRoleVersion) { + Runnable roleVersionUpdater = new ServiceVersionUpdater(daoManager, serviceId, VERSION_TYPE.ROLE_VERSION, policy != null ? policy.getZoneName() : null, policyDeltaType, policy); + + transactionSynchronizationAdapter.executeOnTransactionCommit(roleVersionUpdater); + } + } + + private boolean isRoleDownloadRequired(RangerPolicy policy, RangerService service) { + // Role Download to plugin is required if some role in the policy created/updated is not present in any other + // policy for that service. + boolean ret = false; + + if (policy != null) { + Set roleNames = getAllPolicyItemRoleNames(policy); + + if (CollectionUtils.isNotEmpty(roleNames)) { + Long serviceId = service.getId(); + + checkAndFilterRoleNames(roleNames, service); + + if (CollectionUtils.isNotEmpty(roleNames)) { + for (String roleName : roleNames) { + long roleRefPolicyCount = daoMgr.getXXPolicy().findRoleRefPolicyCount(roleName, serviceId); + + if (roleRefPolicyCount == 0) { + ret = true; + break; + } + } + } + } + } + + return ret; + } + + private void checkAndFilterRoleNames(Set roleNames, RangerService service) { + //remove all roles which are already in DB for this serviceId, so we just download roles if there are new roles added. + Set rolesToRemove = new HashSet<>(); + Long serviceId = service.getId(); + List rolesFromDb = daoMgr.getXXRole().findRoleNamesByServiceId(serviceId); + + if (CollectionUtils.isNotEmpty(rolesFromDb)) { + rolesToRemove.addAll(rolesFromDb); + } + + String tagService = service.getTagService(); + XXService serviceDbObj = daoMgr.getXXService().findByName(tagService); + + if (serviceDbObj != null) { + List rolesFromServiceTag = daoMgr.getXXRole().findRoleNamesByServiceId(serviceDbObj.getId()); + + if (CollectionUtils.isNotEmpty(rolesFromServiceTag)) { + rolesToRemove.addAll(rolesFromServiceTag); + } + } + + roleNames.removeAll(rolesToRemove); + } + + private Set getAllPolicyItemRoleNames(RangerPolicy policy) { + Set ret = new HashSet<>(); + List policyItems = policy.getPolicyItems(); + + if (CollectionUtils.isNotEmpty(policyItems)) { + collectRolesFromPolicyItems(policyItems, ret); + } + + policyItems = policy.getDenyPolicyItems(); + + if (CollectionUtils.isNotEmpty(policyItems)) { + collectRolesFromPolicyItems(policyItems, ret); + } + + policyItems = policy.getAllowExceptions(); + + if (CollectionUtils.isNotEmpty(policyItems)) { + collectRolesFromPolicyItems(policyItems, ret); + } + + policyItems = policy.getDenyExceptions(); + + if (CollectionUtils.isNotEmpty(policyItems)) { + collectRolesFromPolicyItems(policyItems, ret); + } + + policyItems = policy.getDataMaskPolicyItems(); + + if (CollectionUtils.isNotEmpty(policyItems)) { + collectRolesFromPolicyItems(policyItems, ret); + } + + policyItems = policy.getRowFilterPolicyItems(); + + if (CollectionUtils.isNotEmpty(policyItems)) { + collectRolesFromPolicyItems(policyItems, ret); + } + + return ret; + } + + private void collectRolesFromPolicyItems(List rangerPolicyItems, Set roleNames) { + for (RangerPolicyItem rangerPolicyItem : rangerPolicyItems) { + List rangerPolicyItemRoles = rangerPolicyItem.getRoles(); + + if (CollectionUtils.isNotEmpty(rangerPolicyItemRoles)) { + roleNames.addAll(rangerPolicyItemRoles); + } + } + } + + private void persistChangeLog(ServiceVersionUpdater serviceVersionUpdater) { + XXServiceVersionInfoDao serviceVersionInfoDao = serviceVersionUpdater.daoManager.getXXServiceVersionInfo(); + XXServiceVersionInfo serviceVersionInfoDbObj = serviceVersionInfoDao.findByServiceId(serviceVersionUpdater.serviceId); + XXService service = serviceVersionUpdater.daoManager.getXXService().getById(serviceVersionUpdater.serviceId); + + if (service != null) { + Long version = serviceVersionUpdater.versionType == VERSION_TYPE.TAG_VERSION ? serviceVersionInfoDbObj.getTagVersion() : serviceVersionInfoDbObj.getPolicyVersion(); + + persistChangeLog(service, serviceVersionUpdater.versionType, version, serviceVersionUpdater); + } + } + + private static void persistChangeLog(XXService service, VERSION_TYPE versionType, Long version, ServiceVersionUpdater serviceVersionUpdater) { + Date now = new Date(); + + if (versionType == VERSION_TYPE.TAG_VERSION) { + ServiceTags.TagsChangeType tagChangeType = serviceVersionUpdater.tagChangeType; + + if (tagChangeType == ServiceTags.TagsChangeType.RANGER_ADMIN_START || TagDBStore.isSupportsTagDeltas()) { + // Build and save TagChangeLog + XXTagChangeLog tagChangeLog = new XXTagChangeLog(); + Long serviceResourceId = serviceVersionUpdater.resourceId; + Long tagId = serviceVersionUpdater.tagId; + + tagChangeLog.setCreateTime(now); + tagChangeLog.setServiceId(service.getId()); + tagChangeLog.setChangeType(tagChangeType.ordinal()); + tagChangeLog.setServiceTagsVersion(version); + tagChangeLog.setServiceResourceId(serviceResourceId); + tagChangeLog.setTagId(tagId); + + serviceVersionUpdater.daoManager.getXXTagChangeLog().create(tagChangeLog); + } + } else { + Integer policyDeltaChange = serviceVersionUpdater.policyDeltaChange; + + if (policyDeltaChange == RangerPolicyDelta.CHANGE_TYPE_RANGER_ADMIN_START || isSupportsPolicyDeltas()) { + // Build and save PolicyChangeLog + XXPolicyChangeLog policyChangeLog = new XXPolicyChangeLog(); + + policyChangeLog.setCreateTime(now); + policyChangeLog.setServiceId(service.getId()); + policyChangeLog.setChangeType(serviceVersionUpdater.policyDeltaChange); + policyChangeLog.setPolicyVersion(version); + policyChangeLog.setZoneName(serviceVersionUpdater.zoneName); + + RangerPolicy policy = serviceVersionUpdater.policy; + + if (policy != null) { + policyChangeLog.setServiceType(policy.getServiceType()); + policyChangeLog.setPolicyType(policy.getPolicyType()); + policyChangeLog.setPolicyId(policy.getId()); + policyChangeLog.setPolicyGuid(policy.getGuid()); + } + + serviceVersionUpdater.daoManager.getXXPolicyChangeLog().create(policyChangeLog); + } + } + } + + private Boolean deleteExistingPolicyLabel(RangerPolicy policy) { + if (policy == null) { + return false; + } + + List xxPolicyLabelMaps = daoMgr.getXXPolicyLabelMap().findByPolicyId(policy.getId()); + XXPolicyLabelMapDao policyLabelMapDao = daoMgr.getXXPolicyLabelMap(); + + for (XXPolicyLabelMap xxPolicyLabelMap : xxPolicyLabelMaps) { + policyLabelMapDao.remove(xxPolicyLabelMap); + } + + return true; + } + + private String getServiceName(Long serviceId) { + String ret = null; + + if (serviceId != null) { + XXService service = daoMgr.getXXService().getById(serviceId); + + if (service != null) { + ret = service.getName(); + } + } + + return ret; + } + + private boolean isAccessTypeInList(String accessType, List xAccessTypeDefs) { + for (XXAccessTypeDef xxAccessTypeDef : xAccessTypeDefs) { + if (StringUtils.equals(xxAccessTypeDef.getName(), accessType)) { + return true; + } + } + + return false; + } + + private boolean isResourceInList(String resource, List xResourceDefs) { + for (XXResourceDef xResourceDef : xResourceDefs) { + if (StringUtils.equals(xResourceDef.getName(), resource)) { + return true; + } + } + + return false; + } + + private void writeExcel(List policies, String excelFileName, HttpServletResponse response) throws IOException { + OutputStream outStream = null; + + try (Workbook workbook = new HSSFWorkbook()) { + Sheet sheet = workbook.createSheet(); + + createHeaderRow(sheet); + + int rowCount = 0; + + if (!CollectionUtils.isEmpty(policies)) { + Map svcNameToSvcType = new HashMap<>(); + + for (RangerPolicy policy : policies) { + List policyItems = policy.getPolicyItems(); + List rowFilterPolicyItems = policy.getRowFilterPolicyItems(); + List dataMaskPolicyItems = policy.getDataMaskPolicyItems(); + List allowExceptions = policy.getAllowExceptions(); + List denyExceptions = policy.getDenyExceptions(); + List denyPolicyItems = policy.getDenyPolicyItems(); + String serviceType = policy.getServiceType(); + + if (StringUtils.isBlank(serviceType)) { + serviceType = svcNameToSvcType.get(policy.getService()); + + if (StringUtils.isBlank(serviceType)) { + serviceType = daoMgr.getXXServiceDef().findServiceDefTypeByServiceName(policy.getService()); + + if (StringUtils.isNotBlank(serviceType)) { + svcNameToSvcType.put(policy.getService(), serviceType); + } + } + } + + if (CollectionUtils.isNotEmpty(policyItems)) { + for (RangerPolicyItem policyItem : policyItems) { + Row row = sheet.createRow(++rowCount); + + writeBookForPolicyItems(svcNameToSvcType, policy, policyItem, null, null, row, POLICY_ALLOW_INCLUDE); + } + } else if (CollectionUtils.isNotEmpty(dataMaskPolicyItems)) { + for (RangerDataMaskPolicyItem dataMaskPolicyItem : dataMaskPolicyItems) { + Row row = sheet.createRow(++rowCount); + + writeBookForPolicyItems(svcNameToSvcType, policy, null, dataMaskPolicyItem, null, row, null); + } + } else if (CollectionUtils.isNotEmpty(rowFilterPolicyItems)) { + for (RangerRowFilterPolicyItem rowFilterPolicyItem : rowFilterPolicyItems) { + Row row = sheet.createRow(++rowCount); + + writeBookForPolicyItems(svcNameToSvcType, policy, null, null, rowFilterPolicyItem, row, null); + } + } else if (serviceType.equalsIgnoreCase(EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_TAG_NAME)) { + if (CollectionUtils.isEmpty(policyItems)) { + Row row = sheet.createRow(++rowCount); + RangerPolicyItem policyItem = new RangerPolicyItem(); + + writeBookForPolicyItems(svcNameToSvcType, policy, policyItem, null, null, row, POLICY_ALLOW_INCLUDE); + } + } else if (CollectionUtils.isEmpty(policyItems)) { + Row row = sheet.createRow(++rowCount); + RangerPolicyItem policyItem = new RangerPolicyItem(); + + writeBookForPolicyItems(svcNameToSvcType, policy, policyItem, null, null, row, POLICY_ALLOW_INCLUDE); + } + + if (CollectionUtils.isNotEmpty(allowExceptions)) { + for (RangerPolicyItem policyItem : allowExceptions) { + Row row = sheet.createRow(++rowCount); + + writeBookForPolicyItems(svcNameToSvcType, policy, policyItem, null, null, row, POLICY_ALLOW_EXCLUDE); + } + } + + if (CollectionUtils.isNotEmpty(denyExceptions)) { + for (RangerPolicyItem policyItem : denyExceptions) { + Row row = sheet.createRow(++rowCount); + + writeBookForPolicyItems(svcNameToSvcType, policy, policyItem, null, null, row, POLICY_DENY_EXCLUDE); + } + } + + if (CollectionUtils.isNotEmpty(denyPolicyItems)) { + for (RangerPolicyItem policyItem : denyPolicyItems) { + Row row = sheet.createRow(++rowCount); + + writeBookForPolicyItems(svcNameToSvcType, policy, policyItem, null, null, row, POLICY_DENY_INCLUDE); + } + } + } + } + + ByteArrayOutputStream outByteStream = new ByteArrayOutputStream(); + + workbook.write(outByteStream); + + byte[] outArray = outByteStream.toByteArray(); + + response.setContentType("application/ms-excel"); + response.setContentLength(outArray.length); + response.setHeader("Expires:", "0"); + response.setHeader("Content-Disposition", "attachment; filename=" + excelFileName); + response.setStatus(HttpServletResponse.SC_OK); + + outStream = response.getOutputStream(); + + outStream.write(outArray); + outStream.flush(); + } catch (IOException ex) { + LOG.error("Failed to create report file {}", excelFileName, ex); + } catch (Exception ex) { + LOG.error("Error while generating report file {}", excelFileName, ex); + } finally { + if (outStream != null) { + outStream.close(); + } + } + } + + private StringBuilder writeCSV(List policies, String cSVFileName, HttpServletResponse response) { + response.setContentType("text/csv"); + + StringBuilder csvBuffer = new StringBuilder(); + + csvBuffer.append(FILE_HEADER); + csvBuffer.append(LINE_SEPARATOR); + + if (!CollectionUtils.isEmpty(policies)) { + Map svcNameToSvcType = new HashMap<>(); + + for (RangerPolicy policy : policies) { + List policyItems = policy.getPolicyItems(); + List rowFilterPolicyItems = policy.getRowFilterPolicyItems(); + List dataMaskPolicyItems = policy.getDataMaskPolicyItems(); + List allowExceptions = policy.getAllowExceptions(); + List denyExceptions = policy.getDenyExceptions(); + List denyPolicyItems = policy.getDenyPolicyItems(); + String serviceType = policy.getServiceType(); + + if (StringUtils.isBlank(serviceType)) { + serviceType = svcNameToSvcType.get(policy.getService()); + + if (StringUtils.isBlank(serviceType)) { + serviceType = daoMgr.getXXServiceDef().findServiceDefTypeByServiceName(policy.getService()); + + if (StringUtils.isNotBlank(serviceType)) { + svcNameToSvcType.put(policy.getService(), serviceType); + } + } + } + + if (CollectionUtils.isNotEmpty(policyItems)) { + for (RangerPolicyItem policyItem : policyItems) { + writeCSVForPolicyItems(svcNameToSvcType, policy, policyItem, null, null, csvBuffer, POLICY_ALLOW_INCLUDE); + } + } else if (CollectionUtils.isNotEmpty(dataMaskPolicyItems)) { + for (RangerDataMaskPolicyItem dataMaskPolicyItem : dataMaskPolicyItems) { + writeCSVForPolicyItems(svcNameToSvcType, policy, null, dataMaskPolicyItem, null, csvBuffer, null); + } + } else if (CollectionUtils.isNotEmpty(rowFilterPolicyItems)) { + for (RangerRowFilterPolicyItem rowFilterPolicyItem : rowFilterPolicyItems) { + writeCSVForPolicyItems(svcNameToSvcType, policy, null, null, rowFilterPolicyItem, csvBuffer, null); + } + } else if (serviceType.equalsIgnoreCase(EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_TAG_NAME)) { + if (CollectionUtils.isEmpty(policyItems)) { + RangerPolicyItem policyItem = new RangerPolicyItem(); + writeCSVForPolicyItems(svcNameToSvcType, policy, policyItem, null, null, csvBuffer, POLICY_ALLOW_INCLUDE); + } + } else if (CollectionUtils.isEmpty(policyItems)) { + RangerPolicyItem policyItem = new RangerPolicyItem(); + writeCSVForPolicyItems(svcNameToSvcType, policy, policyItem, null, null, csvBuffer, POLICY_ALLOW_INCLUDE); + } + + if (CollectionUtils.isNotEmpty(allowExceptions)) { + for (RangerPolicyItem policyItem : allowExceptions) { + writeCSVForPolicyItems(svcNameToSvcType, policy, policyItem, null, null, csvBuffer, POLICY_ALLOW_EXCLUDE); + } + } + + if (CollectionUtils.isNotEmpty(denyExceptions)) { + for (RangerPolicyItem policyItem : denyExceptions) { + writeCSVForPolicyItems(svcNameToSvcType, policy, policyItem, null, null, csvBuffer, POLICY_DENY_EXCLUDE); + } + } + + if (CollectionUtils.isNotEmpty(denyPolicyItems)) { + for (RangerPolicyItem policyItem : denyPolicyItems) { + writeCSVForPolicyItems(svcNameToSvcType, policy, policyItem, null, null, csvBuffer, POLICY_DENY_INCLUDE); + } + } + } + } + + response.setHeader("Content-Disposition", "attachment; filename=" + cSVFileName); + response.setStatus(HttpServletResponse.SC_OK); + + return csvBuffer; + } + + private void writeCSVForPolicyItems(Map svcNameToSvcType, RangerPolicy policy, RangerPolicyItem policyItem, RangerDataMaskPolicyItem dataMaskPolicyItem, RangerRowFilterPolicyItem rowFilterPolicyItem, StringBuilder csvBuffer, String policyConditionType) { + LOG.debug("policyConditionType:[{}]", policyConditionType); + + List roles = new ArrayList<>(); + List groups = new ArrayList<>(); + List users = new ArrayList<>(); + String roleNames = ""; + String groupNames = ""; + String userNames = ""; + String policyLabelName = ""; + String accessType = ""; + String policyType = ""; + Boolean delegateAdmin = false; + String isExcludesValue = ""; + String maskingInfo = ""; + List accesses = new ArrayList<>(); + List conditionsList = new ArrayList<>(); + String conditionKeyValue = ""; + String resourceKeyVal = ""; + String isRecursiveValue = ""; + String serviceType = ""; + String filterExpr = ""; + String policyConditionTypeValue = ""; + String serviceName = policy.getService(); + String description = policy.getDescription(); + Boolean isAuditEnabled = policy.getIsAuditEnabled(); + List policyLabels = policy.getPolicyLabels(); + StringBuilder sb = new StringBuilder(); + StringBuilder sbIsRecursive = new StringBuilder(); + StringBuilder sbIsExcludes = new StringBuilder(); + Map resources = policy.getResources(); + String policyName = policy.getName(); + + policyName = policyName.replace("|", ""); + + if (resources != null) { + for (Entry resource : resources.entrySet()) { + String resKey = resource.getKey(); + RangerPolicyResource policyResource = resource.getValue(); + List resvalueList = policyResource.getValues(); + String isExcludes = policyResource.getIsExcludes().toString(); + String isRecursive = policyResource.getIsRecursive().toString(); + String resValue = resvalueList.toString(); + + sb.append(resourceKeyVal).append(" ").append(resKey).append("=").append(resValue); + sbIsExcludes.append(resourceKeyVal).append(" ").append(resKey).append("=[").append(isExcludes).append("]"); + sbIsRecursive.append(resourceKeyVal).append(" ").append(resKey).append("=[").append(isRecursive).append("]"); + } + + isExcludesValue = sbIsExcludes.toString(); + isExcludesValue = isExcludesValue.substring(1); + isRecursiveValue = sbIsRecursive.toString(); + isRecursiveValue = isRecursiveValue.substring(1); + resourceKeyVal = sb.toString(); + resourceKeyVal = resourceKeyVal.substring(1); + + if (policyItem != null && dataMaskPolicyItem == null && rowFilterPolicyItem == null) { + roles = policyItem.getRoles(); + groups = policyItem.getGroups(); + users = policyItem.getUsers(); + accesses = policyItem.getAccesses(); + delegateAdmin = policyItem.getDelegateAdmin(); + conditionsList = policyItem.getConditions(); + } else if (dataMaskPolicyItem != null && policyItem == null && rowFilterPolicyItem == null) { + roles = dataMaskPolicyItem.getRoles(); + groups = dataMaskPolicyItem.getGroups(); + users = dataMaskPolicyItem.getUsers(); + accesses = dataMaskPolicyItem.getAccesses(); + delegateAdmin = dataMaskPolicyItem.getDelegateAdmin(); + conditionsList = dataMaskPolicyItem.getConditions(); + + RangerPolicy.RangerPolicyItemDataMaskInfo dataMaskInfo = dataMaskPolicyItem.getDataMaskInfo(); + + String dataMaskType = dataMaskInfo.getDataMaskType(); + String conditionExpr = dataMaskInfo.getConditionExpr(); + String valueExpr = dataMaskInfo.getValueExpr(); + + maskingInfo = "dataMasktype=[" + dataMaskType + "]"; + + if (conditionExpr != null && !conditionExpr.isEmpty() && valueExpr != null && !valueExpr.isEmpty()) { + maskingInfo = maskingInfo + "; conditionExpr=[" + conditionExpr + "]"; + } + } else if (rowFilterPolicyItem != null && policyItem == null && dataMaskPolicyItem == null) { + roles = rowFilterPolicyItem.getRoles(); + groups = rowFilterPolicyItem.getGroups(); + users = rowFilterPolicyItem.getUsers(); + accesses = rowFilterPolicyItem.getAccesses(); + delegateAdmin = rowFilterPolicyItem.getDelegateAdmin(); + conditionsList = rowFilterPolicyItem.getConditions(); + + RangerPolicy.RangerPolicyItemRowFilterInfo filterInfo = rowFilterPolicyItem.getRowFilterInfo(); + + filterExpr = filterInfo.getFilterExpr(); + } + + if (CollectionUtils.isNotEmpty(accesses)) { + for (RangerPolicyItemAccess access : accesses) { + if (access != null) { + accessType = accessType + access.getType().replace("#", "").replace("|", "") + "#"; + } + } + + if (!accessType.isEmpty()) { + accessType = accessType.substring(0, accessType.lastIndexOf("#")); + } + } + + if (CollectionUtils.isNotEmpty(roles)) { + for (String role : roles) { + if (StringUtils.isNotBlank(role)) { + role = role.replace("|", ""); + role = role.replace("#", ""); + roleNames = roleNames + role + "#"; + } + } + + if (!roleNames.isEmpty()) { + roleNames = roleNames.substring(0, roleNames.lastIndexOf("#")); + } + } + + if (CollectionUtils.isNotEmpty(groups)) { + for (String group : groups) { + if (StringUtils.isNotBlank(group)) { + group = group.replace("|", ""); + group = group.replace("#", ""); + groupNames = groupNames + group + "#"; + } + } + + if (!groupNames.isEmpty()) { + groupNames = groupNames.substring(0, groupNames.lastIndexOf("#")); + } + } + + if (CollectionUtils.isNotEmpty(users)) { + for (String user : users) { + if (StringUtils.isNotBlank(user)) { + user = user.replace("|", ""); + user = user.replace("#", ""); + userNames = userNames + user + "#"; + } + } + + if (!userNames.isEmpty()) { + userNames = userNames.substring(0, userNames.lastIndexOf("#")); + } + } + + for (RangerPolicyItemCondition conditions : conditionsList) { + String conditionType = conditions.getType(); + List conditionList = conditions.getValues(); + String conditionValue = conditionList.toString(); + + conditionKeyValue = conditionType + "=" + conditionValue; + } + + serviceType = policy.getServiceType(); + + if (StringUtils.isBlank(serviceType)) { + serviceType = svcNameToSvcType.get(policy.getService()); + + if (serviceType == null) { + serviceType = ""; + } + } + } + + if (policyConditionType != null) { + policyConditionTypeValue = policyConditionType; + } + + if (policyConditionType == null && serviceType.equalsIgnoreCase("tag")) { + policyConditionTypeValue = POLICY_ALLOW_INCLUDE; + } else if (policyConditionType == null) { + policyConditionTypeValue = ""; + } + + String policyStatus; + + if (policy.getIsEnabled()) { + policyStatus = "Enabled"; + } else { + policyStatus = "Disabled"; + } + + int policyTypeInt = policy.getPolicyType(); + + switch (policyTypeInt) { + case RangerPolicy.POLICY_TYPE_ACCESS: + policyType = POLICY_TYPE_ACCESS; + break; + case RangerPolicy.POLICY_TYPE_DATAMASK: + policyType = POLICY_TYPE_DATAMASK; + break; + case RangerPolicy.POLICY_TYPE_ROWFILTER: + policyType = POLICY_TYPE_ROWFILTER; + break; + } + + if (CollectionUtils.isNotEmpty(policyLabels)) { + for (String policyLabel : policyLabels) { + if (StringUtils.isNotBlank(policyLabel)) { + policyLabel = policyLabel.replace("|", ""); + policyLabel = policyLabel.replace("#", ""); + policyLabelName = policyLabelName + policyLabel + "#"; + } + } + + if (!policyLabelName.isEmpty()) { + policyLabelName = policyLabelName.substring(0, policyLabelName.lastIndexOf("#")); + } + } + + csvBuffer.append(policy.getId()); + csvBuffer.append(COMMA_DELIMITER); + csvBuffer.append(policyName); + csvBuffer.append(COMMA_DELIMITER); + csvBuffer.append(resourceKeyVal); + csvBuffer.append(COMMA_DELIMITER); + csvBuffer.append(roleNames); + csvBuffer.append(COMMA_DELIMITER); + csvBuffer.append(groupNames); + csvBuffer.append(COMMA_DELIMITER); + csvBuffer.append(userNames); + csvBuffer.append(COMMA_DELIMITER); + csvBuffer.append(accessType.trim()); + csvBuffer.append(COMMA_DELIMITER); + csvBuffer.append(serviceType); + csvBuffer.append(COMMA_DELIMITER); + csvBuffer.append(policyStatus); + csvBuffer.append(COMMA_DELIMITER); + csvBuffer.append(policyType); + csvBuffer.append(COMMA_DELIMITER); + csvBuffer.append(delegateAdmin.toString().toUpperCase()); + csvBuffer.append(COMMA_DELIMITER); + csvBuffer.append(isRecursiveValue); + csvBuffer.append(COMMA_DELIMITER); + csvBuffer.append(isExcludesValue); + csvBuffer.append(COMMA_DELIMITER); + csvBuffer.append(serviceName); + csvBuffer.append(COMMA_DELIMITER); + csvBuffer.append(description); + csvBuffer.append(COMMA_DELIMITER); + csvBuffer.append(isAuditEnabled.toString().toUpperCase()); + csvBuffer.append(COMMA_DELIMITER); + csvBuffer.append(conditionKeyValue.trim()); + csvBuffer.append(COMMA_DELIMITER); + csvBuffer.append(policyConditionTypeValue); + csvBuffer.append(COMMA_DELIMITER); + csvBuffer.append(maskingInfo); + csvBuffer.append(COMMA_DELIMITER); + csvBuffer.append(filterExpr); + csvBuffer.append(COMMA_DELIMITER); + csvBuffer.append(policyLabelName); + csvBuffer.append(COMMA_DELIMITER); + csvBuffer.append(LINE_SEPARATOR); + } + + private void writeJson(List objList, String jsonFileName, HttpServletResponse response, JSON_FILE_NAME_TYPE type) { + response.setContentType("text/json"); + response.setHeader("Content-Disposition", "attachment; filename=" + jsonFileName); + + ServletOutputStream out = null; + String json; + + switch (type) { + case POLICY: + RangerExportPolicyList rangerExportPolicyList = new RangerExportPolicyList(); + + rangerExportPolicyList.setGenericPolicies(objList); + rangerExportPolicyList.setMetaDataInfo(getMetaDataInfo()); + + json = JsonUtils.objectToJson(rangerExportPolicyList); + break; + case ROLE: + RangerExportRoleList rangerExportRoleList = new RangerExportRoleList(); + + rangerExportRoleList.setGenericRoleList(objList); + + Map metaDataInfo = getMetaDataInfo(); + + metaDataInfo.put(EXPORT_COUNT, rangerExportRoleList.getListSize()); + + rangerExportRoleList.setMetaDataInfo(metaDataInfo); + + json = JsonUtils.objectToJson(rangerExportRoleList); + break; + default: + throw restErrorUtil.createRESTException("Invalid type " + type); + } + + try { + out = response.getOutputStream(); + + response.setStatus(HttpServletResponse.SC_OK); + + IOUtils.write(json, out, "UTF-8"); + } catch (Exception e) { + LOG.error("Error while exporting json file {}", jsonFileName, e); + } finally { + try { + if (out != null) { + out.flush(); + out.close(); + } + } catch (Exception ex) { + // ignored + } + } + } + + private void writeBookForPolicyItems(Map svcNameToSvcType, RangerPolicy policy, RangerPolicyItem policyItem, RangerDataMaskPolicyItem dataMaskPolicyItem, RangerRowFilterPolicyItem rowFilterPolicyItem, Row row, String policyConditionType) { + LOG.debug("policyConditionType:[{}]", policyConditionType); + + List groups = new ArrayList<>(); + List users = new ArrayList<>(); + List roles = new ArrayList<>(); + String roleNames = ""; + String groupNames = ""; + String policyConditionTypeValue = ""; + String userNames = ""; + String policyLabelNames = ""; + String accessType = ""; + String policyStatus; + String policyType = ""; + Boolean delegateAdmin = false; + String isRecursive; + String isExcludes; + String serviceName; + String description; + Boolean isAuditEnabled = policy.getIsAuditEnabled(); + String isExcludesValue = ""; + Cell cell = row.createCell(0); + + cell.setCellValue(policy.getId()); + + List accesses = new ArrayList<>(); + List conditionsList = new ArrayList<>(); + String conditionKeyValue = ""; + List policyLabels; + String resValue; + String resourceKeyVal = ""; + String isRecursiveValue = ""; + String resKey; + StringBuilder sb = new StringBuilder(); + StringBuilder sbIsRecursive = new StringBuilder(); + StringBuilder sbIsExcludes = new StringBuilder(); + Map resources = policy.getResources(); + RangerPolicy.RangerPolicyItemDataMaskInfo dataMaskInfo; + RangerPolicy.RangerPolicyItemRowFilterInfo filterInfo; + + cell = row.createCell(1); + + cell.setCellValue(policy.getName()); + + cell = row.createCell(2); + + if (resources != null) { + for (Entry resource : resources.entrySet()) { + resKey = resource.getKey(); + + RangerPolicyResource policyResource = resource.getValue(); + List resvalueList = policyResource.getValues(); + + isExcludes = policyResource.getIsExcludes().toString(); + isRecursive = policyResource.getIsRecursive().toString(); + resValue = resvalueList.toString(); + + sb.append(resourceKeyVal).append("; ").append(resKey).append("=").append(resValue); + sbIsExcludes.append(resourceKeyVal).append("; ").append(resKey).append("=[").append(isExcludes).append("]"); + sbIsRecursive.append(resourceKeyVal).append("; ").append(resKey).append("=[").append(isRecursive).append("]"); + } + + isExcludesValue = sbIsExcludes.toString(); + isExcludesValue = isExcludesValue.substring(1); + isRecursiveValue = sbIsRecursive.toString(); + isRecursiveValue = isRecursiveValue.substring(1); + resourceKeyVal = sb.toString(); + resourceKeyVal = resourceKeyVal.substring(1); + + cell.setCellValue(resourceKeyVal); + + if (policyItem != null && dataMaskPolicyItem == null && rowFilterPolicyItem == null) { + roles = policyItem.getRoles(); + groups = policyItem.getGroups(); + users = policyItem.getUsers(); + accesses = policyItem.getAccesses(); + delegateAdmin = policyItem.getDelegateAdmin(); + conditionsList = policyItem.getConditions(); + } else if (dataMaskPolicyItem != null && policyItem == null && rowFilterPolicyItem == null) { + roles = dataMaskPolicyItem.getRoles(); + groups = dataMaskPolicyItem.getGroups(); + users = dataMaskPolicyItem.getUsers(); + accesses = dataMaskPolicyItem.getAccesses(); + delegateAdmin = dataMaskPolicyItem.getDelegateAdmin(); + conditionsList = dataMaskPolicyItem.getConditions(); + dataMaskInfo = dataMaskPolicyItem.getDataMaskInfo(); + + String dataMaskType = dataMaskInfo.getDataMaskType(); + String conditionExpr = dataMaskInfo.getConditionExpr(); + String valueExpr = dataMaskInfo.getValueExpr(); + String maskingInfo = "dataMasktype=[" + dataMaskType + "]"; + + if (conditionExpr != null && !conditionExpr.isEmpty() && valueExpr != null && !valueExpr.isEmpty()) { + maskingInfo = maskingInfo + "; conditionExpr=[" + conditionExpr + "]"; + } + + cell = row.createCell(18); + cell.setCellValue(maskingInfo); + } else if (rowFilterPolicyItem != null && policyItem == null && dataMaskPolicyItem == null) { + roles = rowFilterPolicyItem.getRoles(); + groups = rowFilterPolicyItem.getGroups(); + users = rowFilterPolicyItem.getUsers(); + accesses = rowFilterPolicyItem.getAccesses(); + delegateAdmin = rowFilterPolicyItem.getDelegateAdmin(); + conditionsList = rowFilterPolicyItem.getConditions(); + filterInfo = rowFilterPolicyItem.getRowFilterInfo(); + + String filterExpr = filterInfo.getFilterExpr(); + + cell = row.createCell(19); + + cell.setCellValue(filterExpr); + } + + if (CollectionUtils.isNotEmpty(accesses)) { + for (RangerPolicyItemAccess access : accesses) { + accessType = accessType + access.getType(); + accessType = accessType + " ,"; + } + + accessType = accessType.substring(0, accessType.lastIndexOf(",")); + } + if (CollectionUtils.isNotEmpty(roles)) { + roleNames = roleNames + roles; + + StringTokenizer roleToken = new StringTokenizer(roleNames, "[]"); + + while (roleToken.hasMoreTokens()) { + roleNames = roleToken.nextToken(); + } + } + + if (CollectionUtils.isNotEmpty(groups)) { + groupNames = groupNames + groups; + + StringTokenizer groupToken = new StringTokenizer(groupNames, "[]"); + + while (groupToken.hasMoreTokens()) { + groupNames = groupToken.nextToken(); + } + } + + if (CollectionUtils.isNotEmpty(users)) { + userNames = userNames + users; + + StringTokenizer userToken = new StringTokenizer(userNames, "[]"); + + while (userToken.hasMoreTokens()) { + userNames = userToken.nextToken(); + } + } + + String conditionValue = ""; + + for (RangerPolicyItemCondition conditions : conditionsList) { + String conditionType = conditions.getType(); + List conditionList = conditions.getValues(); + + conditionValue = conditionList.toString(); + conditionKeyValue = conditionType + "=" + conditionValue; + } + + cell = row.createCell(3); + cell.setCellValue(roleNames); + cell = row.createCell(4); + cell.setCellValue(groupNames); + cell = row.createCell(5); + cell.setCellValue(userNames); + cell = row.createCell(6); + cell.setCellValue(accessType.trim()); + cell = row.createCell(7); + + String serviceType = policy.getServiceType(); + + if (StringUtils.isBlank(serviceType)) { + serviceType = svcNameToSvcType.get(policy.getService()); + + if (serviceType == null) { + serviceType = ""; + } + } + + if (policyConditionType != null) { + policyConditionTypeValue = policyConditionType; + } + + if (policyConditionType == null && serviceType.equalsIgnoreCase("tag")) { + policyConditionTypeValue = POLICY_ALLOW_INCLUDE; + } else if (policyConditionType == null) { + policyConditionTypeValue = ""; + } + + cell.setCellValue(serviceType); + + cell = row.createCell(8); + } + + if (policy.getIsEnabled()) { + policyStatus = "Enabled"; + } else { + policyStatus = "Disabled"; + } + + policyLabels = policy.getPolicyLabels(); + + if (CollectionUtils.isNotEmpty(policyLabels)) { + policyLabelNames = policyLabelNames + policyLabels; + + StringTokenizer policyLabelToken = new StringTokenizer(policyLabelNames, "[]"); + + while (policyLabelToken.hasMoreTokens()) { + policyLabelNames = policyLabelToken.nextToken(); + } + } + + cell.setCellValue(policyStatus); + + cell = row.createCell(9); + + int policyTypeInt = policy.getPolicyType(); + + switch (policyTypeInt) { + case RangerPolicy.POLICY_TYPE_ACCESS: + policyType = POLICY_TYPE_ACCESS; + break; + + case RangerPolicy.POLICY_TYPE_DATAMASK: + policyType = POLICY_TYPE_DATAMASK; + break; + + case RangerPolicy.POLICY_TYPE_ROWFILTER: + policyType = POLICY_TYPE_ROWFILTER; + break; + } + + cell.setCellValue(policyType); + cell = row.createCell(10); + cell.setCellValue(delegateAdmin.toString().toUpperCase()); + cell = row.createCell(11); + cell.setCellValue(isRecursiveValue); + cell = row.createCell(12); + cell.setCellValue(isExcludesValue); + cell = row.createCell(13); + serviceName = policy.getService(); + cell.setCellValue(serviceName); + cell = row.createCell(14); + description = policy.getDescription(); + cell.setCellValue(description); + cell = row.createCell(15); + cell.setCellValue(isAuditEnabled.toString().toUpperCase()); + cell = row.createCell(16); + cell.setCellValue(conditionKeyValue.trim()); + cell = row.createCell(17); + cell.setCellValue(policyConditionTypeValue); + cell = row.createCell(20); + cell.setCellValue(policyLabelNames); + } + + private void createHeaderRow(Sheet sheet) { + CellStyle cellStyle = sheet.getWorkbook().createCellStyle(); + Font font = sheet.getWorkbook().createFont(); + + font.setBold(true); + font.setFontHeightInPoints((short) 12); + cellStyle.setFont(font); + + Row row = sheet.createRow(0); + + Cell cellID = row.createCell(0); + cellID.setCellStyle(cellStyle); + cellID.setCellValue("ID"); + + Cell cellNAME = row.createCell(1); + cellNAME.setCellStyle(cellStyle); + cellNAME.setCellValue("Name"); + + Cell cellResources = row.createCell(2); + cellResources.setCellStyle(cellStyle); + cellResources.setCellValue("Resources"); + + Cell cellRoles = row.createCell(3); + cellRoles.setCellStyle(cellStyle); + cellRoles.setCellValue("Roles"); + + Cell cellGroups = row.createCell(4); + cellGroups.setCellStyle(cellStyle); + cellGroups.setCellValue("Groups"); + + Cell cellUsers = row.createCell(5); + cellUsers.setCellStyle(cellStyle); + cellUsers.setCellValue("Users"); + + Cell cellAccesses = row.createCell(6); + cellAccesses.setCellStyle(cellStyle); + cellAccesses.setCellValue("Accesses"); + + Cell cellServiceType = row.createCell(7); + cellServiceType.setCellStyle(cellStyle); + cellServiceType.setCellValue("Service Type"); + + Cell cellStatus = row.createCell(8); + cellStatus.setCellStyle(cellStyle); + cellStatus.setCellValue("Status"); + + Cell cellPolicyType = row.createCell(9); + cellPolicyType.setCellStyle(cellStyle); + cellPolicyType.setCellValue("Policy Type"); + + Cell cellDelegateAdmin = row.createCell(10); + cellDelegateAdmin.setCellStyle(cellStyle); + cellDelegateAdmin.setCellValue("Delegate Admin"); + + Cell cellIsRecursive = row.createCell(11); + cellIsRecursive.setCellStyle(cellStyle); + cellIsRecursive.setCellValue("isRecursive"); + + Cell cellIsExcludes = row.createCell(12); + cellIsExcludes.setCellStyle(cellStyle); + cellIsExcludes.setCellValue("isExcludes"); + + Cell cellServiceName = row.createCell(13); + cellServiceName.setCellStyle(cellStyle); + cellServiceName.setCellValue("Service Name"); + + Cell cellDescription = row.createCell(14); + cellDescription.setCellStyle(cellStyle); + cellDescription.setCellValue("Description"); + + Cell cellisAuditEnabled = row.createCell(15); + cellisAuditEnabled.setCellStyle(cellStyle); + cellisAuditEnabled.setCellValue("isAuditEnabled"); + + Cell cellPolicyConditions = row.createCell(16); + cellPolicyConditions.setCellStyle(cellStyle); + cellPolicyConditions.setCellValue("Policy Conditions"); + + Cell cellPolicyConditionType = row.createCell(17); + cellPolicyConditionType.setCellStyle(cellStyle); + cellPolicyConditionType.setCellValue("Policy Condition Type"); + + Cell cellMaskingOptions = row.createCell(18); + cellMaskingOptions.setCellStyle(cellStyle); + cellMaskingOptions.setCellValue("Masking Options"); + + Cell cellRowFilterExpr = row.createCell(19); + cellRowFilterExpr.setCellStyle(cellStyle); + cellRowFilterExpr.setCellValue("Row Filter Expr"); + + Cell cellPolicyLabelName = row.createCell(20); + cellPolicyLabelName.setCellStyle(cellStyle); + cellPolicyLabelName.setCellValue("Policy Labels Name"); + } + + private RangerPolicyList searchRangerPolicies(SearchFilter searchFilter) { + List policyList = new ArrayList<>(); + RangerPolicyList retList = new RangerPolicyList(); + Map policyMap = new HashMap<>(); + Set processedServices = new HashSet<>(); + Set processedSvcIdsForRole = new HashSet<>(); + Set processedPolicies = new HashSet<>(); + List xPolList = null; + String serviceName = searchFilter.getParam(ServiceREST.PARAM_SERVICE_NAME); + + if (StringUtils.isNotBlank(serviceName)) { + Long serviceId = getRangerServiceByName(serviceName.trim()); + + if (serviceId != null) { + loadRangerPolicies(serviceId, processedServices, policyMap, searchFilter); + } + } else { + xPolList = policyService.searchResources(searchFilter, policyService.searchFields, policyService.sortFields, retList); + + if (!CollectionUtils.isEmpty(xPolList)) { + for (XXPolicy xXPolicy : xPolList) { + if (!processedServices.contains(xXPolicy.getService())) { + loadRangerPolicies(xXPolicy.getService(), processedServices, policyMap, searchFilter); + } + } + } + } + + String userName = searchFilter.getParam("user"); + + if (!StringUtils.isEmpty(userName)) { + searchFilter.setParam("user", RangerPolicyEngine.USER_CURRENT); + + List xPolListForMacroUser = policyService.searchResources(searchFilter, policyService.searchFields, policyService.sortFields, retList); + Set processedSvcIdsForMacroUser = new HashSet<>(); + + if (!CollectionUtils.isEmpty(xPolListForMacroUser)) { + for (XXPolicy xXPolicy : xPolListForMacroUser) { + if (!processedPolicies.contains(xXPolicy.getId())) { + if (!processedSvcIdsForMacroUser.contains(xXPolicy.getService())) { + loadRangerPolicies(xXPolicy.getService(), processedSvcIdsForMacroUser, policyMap, searchFilter); + } + + if (policyMap.get(xXPolicy.getId()) != null) { + policyList.add(policyMap.get(xXPolicy.getId())); + + processedPolicies.add(xXPolicy.getId()); + } + } + } + } + + searchFilter.removeParam("user"); + + Set groupNames = daoMgr.getXXGroupUser().findGroupNamesByUserName(userName); + + groupNames.add(RangerConstants.GROUP_PUBLIC); + + Set processedSvcIdsForGroup = new HashSet<>(); + Set processedGroupsName = new HashSet<>(); + + for (String groupName : groupNames) { + searchFilter.setParam("group", groupName); + + List xPolList2 = policyService.searchResources(searchFilter, policyService.searchFields, policyService.sortFields, retList); + + if (!CollectionUtils.isEmpty(xPolList2)) { + for (XXPolicy xPol2 : xPolList2) { + if (xPol2 != null) { + if (!processedPolicies.contains(xPol2.getId())) { + if (!processedSvcIdsForGroup.contains(xPol2.getService()) || !processedGroupsName.contains(groupName)) { + loadRangerPolicies(xPol2.getService(), processedSvcIdsForGroup, policyMap, searchFilter); + + processedGroupsName.add(groupName); + } + + if (policyMap.containsKey(xPol2.getId())) { + policyList.add(policyMap.get(xPol2.getId())); + + processedPolicies.add(xPol2.getId()); + } + } + } + } + } + } + + // fetch policies maintained for the roles belonging to the user + searchFilter.removeParam("group"); + + XXUser xxUser = daoMgr.getXXUser().findByUserName(userName); + + if (xxUser != null) { + Set allContainedRoles = new HashSet<>(); + List xxRoles = daoMgr.getXXRole().findByUserId(xxUser.getId()); + + for (XXRole xxRole : xxRoles) { + getContainingRoles(xxRole.getId(), allContainedRoles); + } + + Set roleNames = getRoleNames(allContainedRoles); + Set processedRoleName = new HashSet<>(); + + for (String roleName : roleNames) { + searchFilter.setParam("role", roleName); + + List xPolList3 = policyService.searchResources(searchFilter, policyService.searchFields, policyService.sortFields, retList); + + if (!CollectionUtils.isEmpty(xPolList3)) { + for (XXPolicy xPol3 : xPolList3) { + if (xPol3 != null) { + if (!processedPolicies.contains(xPol3.getId())) { + if (!processedSvcIdsForRole.contains(xPol3.getService()) || !processedRoleName.contains(roleName)) { + loadRangerPolicies(xPol3.getService(), processedSvcIdsForRole, policyMap, searchFilter); + + processedRoleName.add(roleName); + } + + if (policyMap.containsKey(xPol3.getId())) { + policyList.add(policyMap.get(xPol3.getId())); + + processedPolicies.add(xPol3.getId()); + } + } + } + } + } + } + } + } + + // fetch policies maintained for the roles and groups belonging to the group + String groupName = searchFilter.getParam("group"); + + if (StringUtils.isBlank(groupName)) { + groupName = RangerConstants.GROUP_PUBLIC; + } + + Set groupNames = daoMgr.getXXGroupGroup().findGroupNamesByGroupName(groupName); + + groupNames.add(groupName); + + Set processedSvcIdsForGroup = new HashSet<>(); + Set processedGroupsName = new HashSet<>(); + + for (String grpName : groupNames) { + searchFilter.setParam("group", grpName); + + List xPolList2 = policyService.searchResources(searchFilter, policyService.searchFields, policyService.sortFields, retList); + + if (!CollectionUtils.isEmpty(xPolList2)) { + for (XXPolicy xPol2 : xPolList2) { + if (xPol2 != null) { + if (!processedPolicies.contains(xPol2.getId())) { + if (!processedSvcIdsForGroup.contains(xPol2.getService()) || !processedGroupsName.contains(groupName)) { + loadRangerPolicies(xPol2.getService(), processedSvcIdsForGroup, policyMap, searchFilter); + + processedGroupsName.add(groupName); + } + + if (policyMap.containsKey(xPol2.getId())) { + policyList.add(policyMap.get(xPol2.getId())); + + processedPolicies.add(xPol2.getId()); + } + } + } + } + } + } + + searchFilter.removeParam("group"); + + XXGroup xxGroup = daoMgr.getXXGroup().findByGroupName(groupName); + + if (xxGroup != null) { + Set allContainedRoles = new HashSet<>(); + List xxRoles = daoMgr.getXXRole().findByGroupId(xxGroup.getId()); + + for (XXRole xxRole : xxRoles) { + getContainingRoles(xxRole.getId(), allContainedRoles); + } + + Set roleNames = getRoleNames(allContainedRoles); + Set processedRoleName = new HashSet<>(); + + for (String roleName : roleNames) { + searchFilter.setParam("role", roleName); + + List xPolList3 = policyService.searchResources(searchFilter, policyService.searchFields, policyService.sortFields, retList); + + if (!CollectionUtils.isEmpty(xPolList3)) { + for (XXPolicy xPol3 : xPolList3) { + if (xPol3 != null) { + if (!processedPolicies.contains(xPol3.getId())) { + if (!processedSvcIdsForRole.contains(xPol3.getService()) || !processedRoleName.contains(roleName)) { + loadRangerPolicies(xPol3.getService(), processedSvcIdsForRole, policyMap, searchFilter); + + processedRoleName.add(roleName); + } + + if (policyMap.containsKey(xPol3.getId())) { + policyList.add(policyMap.get(xPol3.getId())); + + processedPolicies.add(xPol3.getId()); + } + } + } + } + } + } + } + + if (!CollectionUtils.isEmpty(xPolList)) { + if (isSearchQuerybyResource(searchFilter)) { + if (MapUtils.isNotEmpty(policyMap)) { + for (Entry entry : policyMap.entrySet()) { + if (!processedPolicies.contains(entry.getKey())) { + policyList.add(entry.getValue()); + + processedPolicies.add(entry.getKey()); + } + } + } + } else { + for (XXPolicy xPol : xPolList) { + if (xPol != null) { + if (!processedPolicies.contains(xPol.getId())) { + if (!processedServices.contains(xPol.getService())) { + loadRangerPolicies(xPol.getService(), processedServices, policyMap, searchFilter); + } + + if (policyMap.containsKey(xPol.getId())) { + policyList.add(policyMap.get(xPol.getId())); + + processedPolicies.add(xPol.getId()); + } + } + } + } + } + } else { + if (MapUtils.isNotEmpty(policyMap)) { + for (Entry entry : policyMap.entrySet()) { + if (!processedPolicies.contains(entry.getKey())) { + policyList.add(entry.getValue()); + + processedPolicies.add(entry.getKey()); + } + } + } + } + + Comparator comparator = Comparator.comparing(RangerBaseModelObject::getId); + + if (CollectionUtils.isNotEmpty(policyList)) { + policyList.sort(comparator); + } + + retList.setPolicies(policyList); + + return retList; + } + + private boolean isSearchQuerybyResource(SearchFilter searchFilter) { + boolean ret = false; + Map filterResourcesPrefix = searchFilter.getParamsWithPrefix(SearchFilter.RESOURCE_PREFIX, true); + + if (MapUtils.isNotEmpty(filterResourcesPrefix)) { + ret = true; + } + + if (!ret) { + Map filterResourcesPolResource = searchFilter.getParamsWithPrefix(SearchFilter.POL_RESOURCE, true); + + if (MapUtils.isNotEmpty(filterResourcesPolResource)) { + ret = true; + } + } + + return ret; + } + + private Long getRangerServiceByName(String name) { + XXService xxService = null; + XXServiceDao xxServiceDao = daoMgr.getXXService(); + + if (xxServiceDao != null) { + xxService = xxServiceDao.findByName(name); + } + + return xxService == null ? null : xxService.getId(); + } + + private void loadRangerPolicies(Long serviceId, Set processedServices, Map policyMap, SearchFilter searchFilter) { + try { + List tempPolicyList = getServicePolicies(serviceId, searchFilter); + + if (!CollectionUtils.isEmpty(tempPolicyList)) { + for (RangerPolicy rangerPolicy : tempPolicyList) { + if (!policyMap.containsKey(rangerPolicy.getId())) { + policyMap.put(rangerPolicy.getId(), rangerPolicy); + } + } + } + + processedServices.add(serviceId); + } catch (Exception e) { + // ignore + } + } + + private void updateServiceWithCustomProperty() { + LOG.info("Adding custom properties to services"); + + SearchFilter filter = new SearchFilter(); + + try { + List lstRangerService = getServices(filter); + + for (RangerService rangerService : lstRangerService) { + String serviceUser = PropertiesUtil.getProperty("ranger.plugins." + rangerService.getType() + ".serviceuser"); + + if (!StringUtils.isEmpty(serviceUser)) { + boolean chkServiceUpdate = false; + + LOG.debug("customproperty = {} for service = {}", rangerService.getConfigs().get(ServiceREST.Allowed_User_List_For_Download), rangerService.getName()); + + if (!rangerService.getConfigs().containsKey(ServiceREST.Allowed_User_List_For_Download)) { + rangerService.getConfigs().put(ServiceREST.Allowed_User_List_For_Download, serviceUser); + + chkServiceUpdate = true; + } + + if ((!rangerService.getConfigs().containsKey(ServiceREST.Allowed_User_List_For_Grant_Revoke)) && ("hbase".equalsIgnoreCase(rangerService.getType()) || "hive".equalsIgnoreCase(rangerService.getType()))) { + rangerService.getConfigs().put(ServiceREST.Allowed_User_List_For_Grant_Revoke, serviceUser); + + chkServiceUpdate = true; + } + + if (!rangerService.getConfigs().containsKey(TagREST.Allowed_User_List_For_Tag_Download)) { + rangerService.getConfigs().put(TagREST.Allowed_User_List_For_Tag_Download, serviceUser); + + chkServiceUpdate = true; + } + + if (chkServiceUpdate) { + updateService(rangerService, null); + + LOG.debug("Updated service {} with custom properties in secure environment", rangerService.getName()); + } + } + } + } catch (Throwable e) { + LOG.error("updateServiceWithCustomProperty failed with exception : {}", e.getMessage()); + } + } + + private String getAuditMode(String serviceTypeName, String serviceName) { + String ret = config.get("ranger.audit.global.mode"); + + if (StringUtils.isNotBlank(ret)) { + return ret; + } + + ret = config.get("ranger.audit.servicedef." + serviceTypeName + ".mode"); + + if (StringUtils.isNotBlank(ret)) { + return ret; + } + + ret = config.get("ranger.audit.service." + serviceName + ".mode"); + + if (StringUtils.isNotBlank(ret)) { + return ret; + } + + return RangerPolicyEngine.AUDIT_DEFAULT; + } + + private void createGenericUsers() { + VXUser genericUser = new VXUser(); + + genericUser.setName(RangerPolicyEngine.USER_CURRENT); + genericUser.setDescription(RangerPolicyEngine.USER_CURRENT); + + xUserService.createXUserWithOutLogin(genericUser); + + genericUser.setName(RangerPolicyEngine.RESOURCE_OWNER); + genericUser.setDescription(RangerPolicyEngine.RESOURCE_OWNER); + + xUserService.createXUserWithOutLogin(genericUser); + } + + private void initRMSDaos() { + daoMgr.getXXService(); + daoMgr.getXXRMSMappingProvider(); + daoMgr.getXXRMSNotification(); + daoMgr.getXXRMSServiceResource(); + daoMgr.getXXRMSResourceMapping(); + } + + private String getMetricOfTypeUserGroup(final SearchCriteria searchCriteria) { + String ret = null; + + try { + VXGroupList vxGroupList = xUserMgr.searchXGroups(searchCriteria); + long groupCount = vxGroupList.getTotalCount(); + ArrayList userAdminRoleCount = new ArrayList<>(); + + userAdminRoleCount.add(RangerConstants.ROLE_SYS_ADMIN); + + long userSysAdminCount = getUserCountBasedOnUserRole(userAdminRoleCount); + ArrayList userAdminAuditorRoleCount = new ArrayList<>(); + + userAdminAuditorRoleCount.add(RangerConstants.ROLE_ADMIN_AUDITOR); + + long userSysAdminAuditorCount = getUserCountBasedOnUserRole(userAdminAuditorRoleCount); + ArrayList userRoleListKeyRoleAdmin = new ArrayList<>(); + + userRoleListKeyRoleAdmin.add(RangerConstants.ROLE_KEY_ADMIN); + + long userKeyAdminCount = getUserCountBasedOnUserRole(userRoleListKeyRoleAdmin); + ArrayList userRoleListKeyadminAduitorRole = new ArrayList<>(); + + userRoleListKeyadminAduitorRole.add(RangerConstants.ROLE_KEY_ADMIN_AUDITOR); + + long userKeyadminAuditorCount = getUserCountBasedOnUserRole(userRoleListKeyadminAduitorRole); + ArrayList userRoleListUser = new ArrayList<>(); + + userRoleListUser.add(RangerConstants.ROLE_USER); + + long userRoleCount = getUserCountBasedOnUserRole(userRoleListUser); + long userTotalCount = userSysAdminCount + userKeyAdminCount + userRoleCount + userKeyadminAuditorCount + userSysAdminAuditorCount; + VXMetricUserGroupCount metricUserGroupCount = new VXMetricUserGroupCount(); + + metricUserGroupCount.setUserCountOfUserRole(userRoleCount); + metricUserGroupCount.setUserCountOfKeyAdminRole(userKeyAdminCount); + metricUserGroupCount.setUserCountOfSysAdminRole(userSysAdminCount); + metricUserGroupCount.setUserCountOfKeyadminAuditorRole(userKeyadminAuditorCount); + metricUserGroupCount.setUserCountOfSysAdminAuditorRole(userSysAdminAuditorCount); + metricUserGroupCount.setUserTotalCount(userTotalCount); + metricUserGroupCount.setGroupCount(groupCount); + + ret = JsonUtils.objectToJson(metricUserGroupCount); + } catch (Exception e) { + LOG.error("ServiceDBStore.getMetricByType(usergroup): Error calculating Metric for usergroup : {}", e.getMessage()); + } + + return ret; + } + + private String getMetricOfTypeAudits(final SearchCriteria searchCriteria) { + String ret = null; + + try { + int clientTimeOffsetInMinute = RestUtil.getClientTimeOffset(); + String defaultDateFormat = "MM/dd/yyyy"; + DateFormat formatter = new SimpleDateFormat(defaultDateFormat); + + VXMetricAuditDetailsCount auditObj = new VXMetricAuditDetailsCount(); + DateUtil dateUtilTwoDays = new DateUtil(); + Date startDateUtilTwoDays = dateUtilTwoDays.getDateFromNow(-2); + + Date dStart2 = restErrorUtil.parseDate(formatter.format(startDateUtilTwoDays), "Invalid value for startDate", MessageEnums.INVALID_INPUT_DATA, null, "startDate", defaultDateFormat); + Date endDateTwoDays = MiscUtil.getUTCDate(); + Date dEnd2 = restErrorUtil.parseDate(formatter.format(endDateTwoDays), "Invalid value for endDate", MessageEnums.INVALID_INPUT_DATA, null, "endDate", defaultDateFormat); + + dEnd2 = dateUtilTwoDays.getDateFromGivenDate(dEnd2, 0, 23, 59, 59); + dEnd2 = dateUtilTwoDays.addTimeOffset(dEnd2, clientTimeOffsetInMinute); + + VXMetricServiceCount deniedCountObj = getAuditsCount(0, dStart2, dEnd2); + + auditObj.setDenialEventsCountTwoDays(deniedCountObj); + + VXMetricServiceCount allowedCountObj = getAuditsCount(1, dStart2, dEnd2); + + auditObj.setAccessEventsCountTwoDays(allowedCountObj); + + long totalAuditsCountTwoDays = deniedCountObj.getTotalCount() + allowedCountObj.getTotalCount(); + + auditObj.setSolrIndexCountTwoDays(totalAuditsCountTwoDays); + + DateUtil dateUtilWeek = new DateUtil(); + Date startDateUtilWeek = dateUtilWeek.getDateFromNow(-7); + Date dStart7 = restErrorUtil.parseDate(formatter.format(startDateUtilWeek), "Invalid value for startDate", MessageEnums.INVALID_INPUT_DATA, null, "startDate", defaultDateFormat); + + Date endDateWeek = MiscUtil.getUTCDate(); + DateUtil dateUtilweek = new DateUtil(); + Date dEnd7 = restErrorUtil.parseDate(formatter.format(endDateWeek), "Invalid value for endDate", MessageEnums.INVALID_INPUT_DATA, null, "endDate", defaultDateFormat); + + dEnd7 = dateUtilweek.getDateFromGivenDate(dEnd7, 0, 23, 59, 59); + dEnd7 = dateUtilweek.addTimeOffset(dEnd7, clientTimeOffsetInMinute); + + VXMetricServiceCount deniedCountObjWeek = getAuditsCount(0, dStart7, dEnd7); + + auditObj.setDenialEventsCountWeek(deniedCountObjWeek); + + VXMetricServiceCount allowedCountObjWeek = getAuditsCount(1, dStart7, dEnd7); + + auditObj.setAccessEventsCountWeek(allowedCountObjWeek); + + long totalAuditsCountWeek = deniedCountObjWeek.getTotalCount() + allowedCountObjWeek.getTotalCount(); + + auditObj.setSolrIndexCountWeek(totalAuditsCountWeek); + + ret = JsonUtils.objectToJson(auditObj); + } catch (Exception e) { + LOG.error("ServiceDBStore.getMetricByType(audits): Error calculating Metric for audits : {}", e.getMessage()); + } + + return ret; + } + + private String getMetricOfTypeServices(final SearchCriteria searchCriteria) { + String ret = null; + + try { + SearchFilter serviceFilter = new SearchFilter(); + + serviceFilter.setMaxRows(200); + serviceFilter.setStartIndex(0); + serviceFilter.setGetCount(true); + serviceFilter.setSortBy("serviceId"); + serviceFilter.setSortType("asc"); + + VXMetricServiceCount vXMetricServiceCount = new VXMetricServiceCount(); + PList paginatedSvcs = getPaginatedServices(serviceFilter); + long totalServiceCount = paginatedSvcs.getTotalCount(); + List rangerServiceList = paginatedSvcs.getList(); + Map services = new HashMap<>(); + + for (RangerService rangerService : rangerServiceList) { + String serviceName = rangerService.getType(); + + if (!(services.containsKey(serviceName))) { + serviceFilter.setParam("serviceType", serviceName); + + PList paginatedSvcscount = getPaginatedServices(serviceFilter); + + services.put(serviceName, paginatedSvcscount.getTotalCount()); + } + } + + vXMetricServiceCount.setServiceBasedCountList(services); + vXMetricServiceCount.setTotalCount(totalServiceCount); + + ret = JsonUtils.objectToJson(vXMetricServiceCount); + } catch (Exception e) { + LOG.error("ServiceDBStore.getMetricByType(services): Error calculating Metric for services : {}", e.getMessage()); + } + + return ret; + } + + private String getMetricOfTypePolicies(final SearchCriteria searchCriteria) { + String ret = null; + + try { + SearchFilter policyFilter = new SearchFilter(); + + policyFilter.setMaxRows(200); + policyFilter.setStartIndex(0); + policyFilter.setGetCount(true); + policyFilter.setSortBy("serviceId"); + policyFilter.setSortType("asc"); + + VXMetricPolicyWithServiceNameCount vXMetricPolicyWithServiceNameCount = new VXMetricPolicyWithServiceNameCount(); + PList paginatedSvcsList = getPaginatedPolicies(policyFilter); + + vXMetricPolicyWithServiceNameCount.setTotalCount(paginatedSvcsList.getTotalCount()); + + Map servicesWithPolicy = new HashMap<>(); + + for (int k = 2; k >= 0; k--) { + String policyType = String.valueOf(k); + VXMetricServiceNameCount vXMetricServiceNameCount = getVXMetricServiceCount(policyType); + + if (k == 2) { + servicesWithPolicy.put("rowFilteringPolicies", vXMetricServiceNameCount); + } else if (k == 1) { + servicesWithPolicy.put("maskingPolicies", vXMetricServiceNameCount); + } else if (k == 0) { + servicesWithPolicy.put("resourceAccessPolicies", vXMetricServiceNameCount); + } + } + + Map> tagMap = new HashMap<>(); + Map serviceNameWithPolicyCount = new HashMap<>(); + boolean tagFlag = false; + + if (!tagFlag) { + policyFilter.setParam("serviceType", "tag"); + + PList policiestype = getPaginatedPolicies(policyFilter); + List policies = policiestype.getList(); + + for (RangerPolicy rangerPolicy : policies) { + if (serviceNameWithPolicyCount.containsKey(rangerPolicy.getService())) { + Long tagServicePolicyCount = serviceNameWithPolicyCount.get(rangerPolicy.getService()) + 1L; + serviceNameWithPolicyCount.put(rangerPolicy.getService(), tagServicePolicyCount); + } else if (!rangerPolicy.getName().isEmpty()) { + serviceNameWithPolicyCount.put(rangerPolicy.getService(), 1L); + } + } + + tagMap.put("tag", serviceNameWithPolicyCount); + + long tagCount = policiestype.getTotalCount(); + VXMetricServiceNameCount vXMetricServiceNameCount = new VXMetricServiceNameCount(); + + vXMetricServiceNameCount.setServiceBasedCountList(tagMap); + vXMetricServiceNameCount.setTotalCount(tagCount); + + servicesWithPolicy.put("tagAccessPolicies", vXMetricServiceNameCount); + } + + vXMetricPolicyWithServiceNameCount.setPolicyCountList(servicesWithPolicy); + + ret = JsonUtils.objectToJson(vXMetricPolicyWithServiceNameCount); + } catch (Exception e) { + LOG.error("ServiceDBStore.getMetricByType(policies): Error calculating Metric for policies : {}", e.getMessage()); + } + + return ret; + } + + private String getMetricOfTypeDatabase(final SearchCriteria searchCriteria) { + String ret = null; + + try { + int dbFlavor = RangerBizUtil.getDBFlavor(); + String dbFlavourType = RangerBizUtil.getDBFlavorType(dbFlavor); + String dbDetail = dbFlavourType + " " + bizUtil.getDBVersion(); + + ret = JsonUtils.objectToJson(dbDetail); + } catch (Exception e) { + LOG.error("ServiceDBStore.getMetricByType(database): Error calculating Metric for database : {}", e.getMessage()); + } + + return ret; + } + + private String getMetricOfTypeContextEnrichers(final SearchCriteria searchCriteria) { + String ret = null; + + try { + SearchFilter filter = new SearchFilter(); + + filter.setStartIndex(0); + + VXMetricContextEnricher serviceWithContextEnrichers = new VXMetricContextEnricher(); + PList paginatedSvcDefs = getPaginatedServiceDefs(filter); + List repoTypeList = paginatedSvcDefs.getList(); + + if (repoTypeList != null) { + for (RangerServiceDef repoType : repoTypeList) { + String name = repoType.getName(); + List contextEnrichers = repoType.getContextEnrichers(); + + if (contextEnrichers != null && !contextEnrichers.isEmpty()) { + serviceWithContextEnrichers.setServiceName(name); + serviceWithContextEnrichers.setTotalCount(contextEnrichers.size()); + } + } + } + + ret = JsonUtils.objectToJson(serviceWithContextEnrichers); + } catch (Exception e) { + LOG.error("ServiceDBStore.getMetricByType(contextenrichers): Error calculating Metric for contextenrichers : {}", e.getMessage()); + } + + return ret; + } + + private String getMetricOfTypeDenyConditions(final SearchCriteria searchCriteria) { + String ret = null; + + try { + SearchFilter policyFilter1 = new SearchFilter(); + + policyFilter1.setMaxRows(200); + policyFilter1.setStartIndex(0); + policyFilter1.setGetCount(true); + policyFilter1.setSortBy("serviceId"); + policyFilter1.setSortType("asc"); + policyFilter1.setParam("denyCondition", "true"); + + int denyCount = 0; + Map denyconditionsonMap = new HashMap<>(); + PList paginatedSvcDefs = getPaginatedServiceDefs(policyFilter1); + + if (paginatedSvcDefs != null) { + List rangerServiceDefs = paginatedSvcDefs.getList(); + + if (rangerServiceDefs != null && !rangerServiceDefs.isEmpty()) { + for (RangerServiceDef rangerServiceDef : rangerServiceDefs) { + if (rangerServiceDef != null) { + String serviceDef = rangerServiceDef.getName(); + + if (!StringUtils.isEmpty(serviceDef)) { + policyFilter1.setParam("serviceType", serviceDef); + + PList policiesList = getPaginatedPolicies(policyFilter1); + + if (policiesList != null && policiesList.getListSize() > 0) { + int policyListCount = policiesList.getListSize(); + + if (policyListCount > 0 && policiesList.getList() != null) { + List policies = policiesList.getList(); + + for (RangerPolicy policy : policies) { + if (policy != null) { + List policyItem = policy.getDenyPolicyItems(); + + if (policyItem != null && !policyItem.isEmpty()) { if (denyconditionsonMap.get(serviceDef) != null) { denyCount = denyconditionsonMap.get(serviceDef) + denyCount + policyItem.size(); } else { denyCount = denyCount + policyItem.size(); } } + List policyItemExclude = policy.getDenyExceptions(); + if (policyItemExclude != null && !policyItemExclude.isEmpty()) { if (denyconditionsonMap.get(serviceDef) != null) { denyCount = denyconditionsonMap.get(serviceDef) + denyCount + policyItemExclude.size(); @@ -5810,669 +6121,678 @@ private String getMetricOfTypeDenyConditions(final SearchCriteria searchCriteria } } } + policyFilter1.removeParam("serviceType"); } + denyconditionsonMap.put(serviceDef, denyCount); + denyCount = 0; } } } } - String jsonContextDenyCondtionOn = JsonUtils.objectToJson(denyconditionsonMap); - ret = jsonContextDenyCondtionOn; - } catch (Exception e) { - LOG.error("ServiceDBStore.getMetricByType(denyconditions): Error calculating Metric for denyconditions : " + e.getMessage()); + + ret = JsonUtils.objectToJson(denyconditionsonMap); + } catch (Exception e) { + LOG.error("ServiceDBStore.getMetricByType(denyconditions): Error calculating Metric for denyconditions : {}", e.getMessage()); + } + + return ret; + } + + private VXMetricServiceNameCount getVXMetricServiceCount(String policyType) throws Exception { + SearchFilter policyFilter1 = new SearchFilter(); + + policyFilter1.setMaxRows(200); + policyFilter1.setStartIndex(0); + policyFilter1.setGetCount(true); + policyFilter1.setSortBy("serviceId"); + policyFilter1.setSortType("asc"); + policyFilter1.setParam("policyType", policyType); + + PList policies = getPaginatedPolicies(policyFilter1); + PList paginatedSvcsSevice = getPaginatedServices(policyFilter1); + List rangerServiceList = paginatedSvcsSevice.getList(); + Map> servicesforPolicyType = new HashMap<>(); + + long tagCount = 0; + + for (RangerService rangerService : rangerServiceList) { + String servicetype = rangerService.getType(); + String serviceName = rangerService.getName(); + + policyFilter1.setParam("serviceName", serviceName); + + Map servicesNamewithPolicyCount = new HashMap<>(); + PList policiestype = getPaginatedPolicies(policyFilter1); + long count = policiestype.getTotalCount(); + + if (count != 0) { + if (!"tag".equalsIgnoreCase(servicetype)) { + if (!(servicesforPolicyType.containsKey(servicetype))) { + servicesNamewithPolicyCount.put(serviceName, count); + servicesforPolicyType.put(servicetype, servicesNamewithPolicyCount); + } else if (servicesforPolicyType.containsKey(servicetype)) { + Map previousPolicyCount = servicesforPolicyType.get(servicetype); + + if (!previousPolicyCount.containsKey(serviceName)) { + previousPolicyCount.put(serviceName, count); + servicesforPolicyType.put(servicetype, previousPolicyCount); + } + } + } else { + tagCount = tagCount + count; + } + } + } + + VXMetricServiceNameCount vXMetricServiceNameCount = new VXMetricServiceNameCount(); + + vXMetricServiceNameCount.setServiceBasedCountList(servicesforPolicyType); + + long totalCountOfPolicyType = policies.getTotalCount() - tagCount; + + vXMetricServiceNameCount.setTotalCount(totalCountOfPolicyType); + + return vXMetricServiceNameCount; + } + + private VXMetricServiceCount getAuditsCount(int accessResult, Date startDate, Date endDate) throws Exception { + long totalCountOfAudits = 0; + SearchFilter filter = new SearchFilter(); + + filter.setStartIndex(0); + + Map servicesRepoType = new HashMap<>(); + VXMetricServiceCount vXMetricServiceCount = new VXMetricServiceCount(); + PList paginatedSvcDefs = getPaginatedServiceDefs(filter); + Iterable repoTypeGet = paginatedSvcDefs.getList(); + + for (RangerServiceDef repoType : repoTypeGet) { + long id = repoType.getId(); + String serviceRepoName = repoType.getName(); + SearchCriteria searchCriteriaWithType = new SearchCriteria(); + + searchCriteriaWithType.getParamList().put("repoType", id); + searchCriteriaWithType.getParamList().put("accessResult", accessResult); + searchCriteriaWithType.addParam("startDate", startDate); + searchCriteriaWithType.addParam("endDate", endDate); + searchCriteriaWithType.setMaxRows(0); + searchCriteriaWithType.setGetCount(true); + + VXAccessAuditList vXAccessAuditListwithType = assetMgr.getAccessLogs(searchCriteriaWithType); + long totalCountOfRepo = vXAccessAuditListwithType.getTotalCount(); + + if (totalCountOfRepo != 0) { + servicesRepoType.put(serviceRepoName, totalCountOfRepo); + + totalCountOfAudits += totalCountOfRepo; + } + } + + vXMetricServiceCount.setServiceBasedCountList(servicesRepoType); + vXMetricServiceCount.setTotalCount(totalCountOfAudits); + + return vXMetricServiceCount; + } + + private Long getUserCountBasedOnUserRole(@SuppressWarnings("rawtypes") List userRoleList) { + SearchCriteria searchCriteria = new SearchCriteria(); + searchCriteria.setStartIndex(0); + searchCriteria.setMaxRows(100); + searchCriteria.setGetCount(true); + searchCriteria.setSortType("asc"); + searchCriteria.addParam("userRoleList", userRoleList); + + return xUserMgr.searchXUsers(searchCriteria).getTotalCount(); + } + + /** + * Removes given service from security zones. + * + * @param service + * @throws Exception + */ + private void disassociateZonesForService(RangerService service) throws Exception { + String serviceName = service.getName(); + List zonesNameList = daoMgr.getXXSecurityZoneDao().findZonesByServiceName(serviceName); + + if (CollectionUtils.isNotEmpty(zonesNameList)) { + for (String zoneName : zonesNameList) { + RangerSecurityZone securityZone = securityZoneStore.getSecurityZoneByName(zoneName); + Map zoneServices = securityZone.getServices(); + + if (zoneServices != null && !zoneServices.isEmpty()) { + zoneServices.remove(serviceName); + securityZone.setServices(zoneServices); + + securityZoneStore.updateSecurityZoneById(securityZone); + } + } + } + } + + private static ServicePolicies getUpdatedServicePoliciesForZones(ServicePolicies servicePolicies, Map securityZones) { + final ServicePolicies ret; + + if (MapUtils.isNotEmpty(securityZones)) { + ret = new ServicePolicies(); + + ret.setServiceDef(servicePolicies.getServiceDef()); + ret.setServiceId(servicePolicies.getServiceId()); + ret.setServiceName(servicePolicies.getServiceName()); + ret.setAuditMode(servicePolicies.getAuditMode()); + ret.setPolicyVersion(servicePolicies.getPolicyVersion()); + ret.setPolicyUpdateTime(servicePolicies.getPolicyUpdateTime()); + ret.setTagPolicies(servicePolicies.getTagPolicies()); + + Map securityZonesInfo = new HashMap<>(); + + if (CollectionUtils.isEmpty(servicePolicies.getPolicyDeltas())) { + List allPolicies = new ArrayList<>(servicePolicies.getPolicies()); + + for (Map.Entry entry : securityZones.entrySet()) { + List zonePolicies = extractZonePolicies(allPolicies, entry.getKey()); + + if (CollectionUtils.isNotEmpty(zonePolicies)) { + allPolicies.removeAll(zonePolicies); + } + + ServicePolicies.SecurityZoneInfo securityZoneInfo = new ServicePolicies.SecurityZoneInfo(); + + securityZoneInfo.setZoneName(entry.getKey()); + securityZoneInfo.setPolicies(zonePolicies); + securityZoneInfo.setResources(entry.getValue().getResources()); + securityZoneInfo.setContainsAssociatedTagService(false); + + securityZonesInfo.put(entry.getKey(), securityZoneInfo); + } + + ret.setPolicies(allPolicies); + } else { + List allPolicyDeltas = new ArrayList<>(servicePolicies.getPolicyDeltas()); + + for (Map.Entry entry : securityZones.entrySet()) { + List zonePolicyDeltas = extractZonePolicyDeltas(allPolicyDeltas, entry.getKey()); + + if (CollectionUtils.isNotEmpty(zonePolicyDeltas)) { + allPolicyDeltas.removeAll(zonePolicyDeltas); + } + + ServicePolicies.SecurityZoneInfo securityZoneInfo = new ServicePolicies.SecurityZoneInfo(); + + securityZoneInfo.setZoneName(entry.getKey()); + securityZoneInfo.setPolicyDeltas(zonePolicyDeltas); + securityZoneInfo.setResources(entry.getValue().getResources()); + securityZoneInfo.setContainsAssociatedTagService(false); + + securityZonesInfo.put(entry.getKey(), securityZoneInfo); + } + + ret.setPolicyDeltas(allPolicyDeltas); + } + + ret.setSecurityZones(securityZonesInfo); + } else { + ret = servicePolicies; } + return ret; } - public String getMetricByType(final METRIC_TYPE metricType) throws Exception { - if (LOG.isDebugEnabled()) { - LOG.debug("==> ServiceDBStore.getMetricByType(" + metricType + ")"); + private void patchAssociatedTagServiceInSecurityZoneInfos(ServicePolicies servicePolicies) { + if (servicePolicies != null && MapUtils.isNotEmpty(servicePolicies.getSecurityZones())) { + // Get list of zones that associated tag-service (if any) is associated with + List zonesInAssociatedTagService = new ArrayList<>(); + String tagServiceName = servicePolicies.getTagPolicies() != null ? servicePolicies.getTagPolicies().getServiceName() : null; + + if (StringUtils.isNotEmpty(tagServiceName)) { + try { + RangerService tagService = getServiceByName(tagServiceName); + + if (tagService != null && tagService.getIsEnabled()) { + zonesInAssociatedTagService = daoMgr.getXXSecurityZoneDao().findZonesByTagServiceName(tagServiceName); + } + } catch (Exception exception) { + LOG.warn("Could not get service associated with [{}]", tagServiceName, exception); + } + } + + if (CollectionUtils.isNotEmpty(zonesInAssociatedTagService)) { + for (Map.Entry entry : servicePolicies.getSecurityZones().entrySet()) { + String zoneName = entry.getKey(); + ServicePolicies.SecurityZoneInfo securityZoneInfo = entry.getValue(); + + securityZoneInfo.setContainsAssociatedTagService(zonesInAssociatedTagService.contains(zoneName)); + } + } } - String ret = null; - try { - SearchCriteria searchCriteria = new SearchCriteria(); - searchCriteria.setStartIndex(0); - searchCriteria.setMaxRows(100); - searchCriteria.setGetCount(true); - searchCriteria.setSortType("asc"); + } - ret = metricType.getMetric(this, searchCriteria); - } catch (Exception e) { - LOG.error("ServiceDBStore.getMetricByType(" + metricType + "): Error calculating Metric : " + e.getMessage()); + private static List extractZonePolicies(final List allPolicies, final String zoneName) { + final List ret = new ArrayList<>(); + + for (RangerPolicy policy : allPolicies) { + if (policy.getIsEnabled() && StringUtils.equals(policy.getZoneName(), zoneName)) { + ret.add(policy); + } } - if (LOG.isDebugEnabled()) { - LOG.debug("== ServiceDBStore.getMetricByType(" + metricType + "): " + ret); + + return ret; + } + + private static List extractZonePolicyDeltas(final List allPolicyDeltas, final String zoneName) { + final List ret = new ArrayList<>(); + + for (RangerPolicyDelta delta : allPolicyDeltas) { + if (StringUtils.equals(delta.getZoneName(), zoneName) && !StringUtils.equals(delta.getServiceType(), EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_TAG_NAME)) { + ret.add(delta); + } } + return ret; } - private VXMetricServiceNameCount getVXMetricServiceCount(String policyType) throws Exception { - SearchFilter policyFilter1 = new SearchFilter(); - policyFilter1.setMaxRows(200); - policyFilter1.setStartIndex(0); - policyFilter1.setGetCount(true); - policyFilter1.setSortBy("serviceId"); - policyFilter1.setSortType("asc"); - policyFilter1.setParam("policyType", policyType); - PList policies = getPaginatedPolicies(policyFilter1); - PList paginatedSvcsSevice = getPaginatedServices(policyFilter1); - List rangerServiceList = paginatedSvcsSevice.getList(); - Map > servicesforPolicyType = new HashMap<>(); - - long tagCount = 0; - for (Object rangerService : rangerServiceList) { - RangerService rangerServiceObj = (RangerService) rangerService; - String servicetype = rangerServiceObj.getType(); - String serviceName =rangerServiceObj.getName(); - policyFilter1.setParam("serviceName", serviceName); - Map servicesNamewithPolicyCount = new HashMap<>(); - PList policiestype = getPaginatedPolicies(policyFilter1); - long count = policiestype.getTotalCount(); - if (count != 0) { - if (!"tag".equalsIgnoreCase(servicetype)) { - if (!(servicesforPolicyType.containsKey(servicetype))) { - servicesNamewithPolicyCount.put(serviceName, count); - servicesforPolicyType.put(servicetype, servicesNamewithPolicyCount); - } - else if (servicesforPolicyType.containsKey(servicetype)) { - Map previousPolicyCount = servicesforPolicyType.get(servicetype); - if(!previousPolicyCount.containsKey(serviceName)) { - previousPolicyCount.put(serviceName, count); - servicesforPolicyType.put(servicetype, previousPolicyCount); - } - } - } else { - tagCount = tagCount + count; + private ServicePolicies filterServicePolicies(ServicePolicies servicePolicies) { + ServicePolicies ret = null; + boolean containsDisabledResourcePolicies = false; + boolean containsDisabledTagPolicies = false; + + if (servicePolicies != null) { + List policies = servicePolicies.getPolicies(); + + if (CollectionUtils.isNotEmpty(policies)) { + for (RangerPolicy policy : policies) { + if (!policy.getIsEnabled()) { + containsDisabledResourcePolicies = true; + break; + } + } + } + + if (servicePolicies.getTagPolicies() != null) { + policies = servicePolicies.getTagPolicies().getPolicies(); + + if (CollectionUtils.isNotEmpty(policies)) { + for (RangerPolicy policy : policies) { + if (!policy.getIsEnabled()) { + containsDisabledTagPolicies = true; + break; } } + } + } + + if (!containsDisabledResourcePolicies && !containsDisabledTagPolicies) { + ret = servicePolicies; + } else { + ret = new ServicePolicies(); + + ret.setServiceDef(servicePolicies.getServiceDef()); + ret.setServiceId(servicePolicies.getServiceId()); + ret.setServiceName(servicePolicies.getServiceName()); + ret.setPolicyVersion(servicePolicies.getPolicyVersion()); + ret.setPolicyUpdateTime(servicePolicies.getPolicyUpdateTime()); + ret.setPolicies(servicePolicies.getPolicies()); + ret.setTagPolicies(servicePolicies.getTagPolicies()); + ret.setSecurityZones(servicePolicies.getSecurityZones()); + + if (containsDisabledResourcePolicies) { + List filteredPolicies = new ArrayList<>(); + + for (RangerPolicy policy : servicePolicies.getPolicies()) { + if (policy.getIsEnabled()) { + filteredPolicies.add(policy); + } + } + + ret.setPolicies(filteredPolicies); + } + + if (containsDisabledTagPolicies) { + ServicePolicies.TagPolicies tagPolicies = new ServicePolicies.TagPolicies(); + + tagPolicies.setServiceDef(servicePolicies.getTagPolicies().getServiceDef()); + tagPolicies.setServiceId(servicePolicies.getTagPolicies().getServiceId()); + tagPolicies.setServiceName(servicePolicies.getTagPolicies().getServiceName()); + tagPolicies.setPolicyVersion(servicePolicies.getTagPolicies().getPolicyVersion()); + tagPolicies.setPolicyUpdateTime(servicePolicies.getTagPolicies().getPolicyUpdateTime()); + + List filteredPolicies = new ArrayList<>(); + + for (RangerPolicy policy : servicePolicies.getTagPolicies().getPolicies()) { + if (policy.getIsEnabled()) { + filteredPolicies.add(policy); + } + } + + tagPolicies.setPolicies(filteredPolicies); + + ret.setTagPolicies(tagPolicies); + } } - VXMetricServiceNameCount vXMetricServiceNameCount = new VXMetricServiceNameCount(); - vXMetricServiceNameCount.setServiceBasedCountList(servicesforPolicyType); - long totalCountOfPolicyType = 0; - totalCountOfPolicyType = policies.getTotalCount() - tagCount; - vXMetricServiceNameCount.setTotalCount(totalCountOfPolicyType); - return vXMetricServiceNameCount; + } + + return ret; } - private VXMetricServiceCount getAuditsCount(int accessResult,Date startDate, Date endDate) throws Exception { - long totalCountOfAudits = 0; - SearchFilter filter = new SearchFilter(); - filter.setStartIndex(0); - Map servicesRepoType = new HashMap<>(); - VXMetricServiceCount vXMetricServiceCount = new VXMetricServiceCount(); - PList paginatedSvcDefs = getPaginatedServiceDefs(filter); - Iterable repoTypeGet = paginatedSvcDefs.getList(); - for (Object repo : repoTypeGet) { - RangerServiceDef rangerServiceDefObj = (RangerServiceDef) repo; - long id = rangerServiceDefObj.getId(); - String serviceRepoName = rangerServiceDefObj.getName(); - SearchCriteria searchCriteriaWithType = new SearchCriteria(); - searchCriteriaWithType.getParamList().put("repoType", id); - searchCriteriaWithType.getParamList().put("accessResult", accessResult); - searchCriteriaWithType.addParam("startDate", startDate); - searchCriteriaWithType.addParam("endDate", endDate); - searchCriteriaWithType.setMaxRows(0); - searchCriteriaWithType.setGetCount(true); - VXAccessAuditList vXAccessAuditListwithType = assetMgr.getAccessLogs(searchCriteriaWithType); - long toltalCountOfRepo = vXAccessAuditListwithType.getTotalCount(); - if (toltalCountOfRepo != 0) { - servicesRepoType.put(serviceRepoName, toltalCountOfRepo); - totalCountOfAudits += toltalCountOfRepo; - } - } - vXMetricServiceCount.setServiceBasedCountList(servicesRepoType); - vXMetricServiceCount.setTotalCount(totalCountOfAudits); - return vXMetricServiceCount; + private List getAuditFiltersServiceConfigByName(String searchUsrGrpRoleName) { + LOG.debug("===> ServiceDBStore.getAuditFiltersServiceConfigByName( searchUsrGrpRoleName : {})", searchUsrGrpRoleName); + + List configMapToBeModified = null; + + if (StringUtils.isNotBlank(searchUsrGrpRoleName)) { + configMapToBeModified = new ArrayList<>(); + + XXServiceConfigMapDao configDao = daoMgr.getXXServiceConfigMap(); + List configs = configDao.findByConfigKey(ServiceDBStore.RANGER_PLUGIN_AUDIT_FILTERS); + + for (XXServiceConfigMap configMap : configs) { + if (StringUtils.contains(configMap.getConfigvalue(), searchUsrGrpRoleName)) { + configMapToBeModified.add(configMap); + } + } + } + + LOG.debug("<=== ServiceDBStore.getAuditFiltersServiceConfigByName( searchUsrGrpRoleName : {}) configMapToBeModified : {}", searchUsrGrpRoleName, configMapToBeModified); + + return configMapToBeModified; } - private Long getUserCountBasedOnUserRole(@SuppressWarnings("rawtypes") List userRoleList) { - SearchCriteria searchCriteria = new SearchCriteria(); - searchCriteria.setStartIndex(0); - searchCriteria.setMaxRows(100); - searchCriteria.setGetCount(true); - searchCriteria.setSortType("asc"); - searchCriteria.addParam("userRoleList", userRoleList); - return xUserMgr.searchXUsers(searchCriteria).getTotalCount(); + private void removeUserGroupRoleReferences(List auditFilters, String user, String group, String role) { + List itemsToRemove = null; + + LOG.debug("===> ServiceDBStore.removeUserGroupRoleReferences( user : {} group : {} role : {} auditFilters : {})", user, group, role, auditFilters); + + for (AuditFilter auditFilter : auditFilters) { + boolean isAuditFilterModified = false; + + if (StringUtils.isNotEmpty(user) && CollectionUtils.isNotEmpty(auditFilter.getUsers())) { + auditFilter.getUsers().remove(user); + + isAuditFilterModified = true; + } + + if (StringUtils.isNotEmpty(group) && CollectionUtils.isNotEmpty(auditFilter.getGroups())) { + auditFilter.getGroups().remove(group); + + isAuditFilterModified = true; + } + + if (StringUtils.isNotEmpty(role) && CollectionUtils.isNotEmpty(auditFilter.getRoles())) { + auditFilter.getRoles().remove(role); + + isAuditFilterModified = true; + } + + if (isAuditFilterModified && CollectionUtils.isEmpty(auditFilter.getUsers()) && CollectionUtils.isEmpty(auditFilter.getGroups()) && CollectionUtils.isEmpty(auditFilter.getRoles())) { + if (itemsToRemove == null) { + itemsToRemove = new ArrayList<>(); + } + + itemsToRemove.add(auditFilter); + } + } + + if (CollectionUtils.isNotEmpty(itemsToRemove)) { + auditFilters.removeAll(itemsToRemove); + } + + LOG.debug("<=== ServiceDBStore.removeUserGroupRoleReferences( user : {} group : {} role : {} auditFilters : {})", user, group, role, auditFilters); } - public boolean isServiceAdminUser(String serviceName, String userName) { - boolean ret = false; - XXServiceConfigMapDao svcCfgMapDao = daoMgr.getXXServiceConfigMap(); - XXServiceConfigMap cfgSvcAdminUsers = svcCfgMapDao.findByServiceNameAndConfigKey(serviceName, SERVICE_ADMIN_USERS); - String svcAdminUsers = cfgSvcAdminUsers != null ? cfgSvcAdminUsers.getConfigvalue() : null; - - if (svcAdminUsers != null) { - for (String svcAdminUser : svcAdminUsers.split(",")) { - if (userName.equals(svcAdminUser)) { - ret = true; - break; - } - } - } - - if (!ret) { - XXServiceConfigMap cfgSvcAdminGroups = svcCfgMapDao.findByServiceNameAndConfigKey(serviceName, SERVICE_ADMIN_GROUPS); - String svcAdminGroups = cfgSvcAdminGroups != null ? cfgSvcAdminGroups.getConfigvalue() : null; - - if (StringUtils.isNotBlank(svcAdminGroups)) { - Set userGroups = xUserMgr.getGroupsForUser(userName); - - if (CollectionUtils.isNotEmpty(userGroups)) { - for (String svcAdminGroup : svcAdminGroups.split(",")) { - if (RangerConstants.GROUP_PUBLIC.equals(svcAdminGroup) || userGroups.contains(svcAdminGroup)) { - ret = true; - - break; - } - } - } - } - } - - return ret; - } - - public static boolean isSupportsPolicyDeltas() { - return SUPPORTS_POLICY_DELTAS; - } - - public static boolean isSupportsRolesDownloadByService() { - return isRolesDownloadedByService; - } - - public static class ServiceVersionUpdater implements Runnable { - final Long serviceId; - final RangerDaoManager daoManager; - final VERSION_TYPE versionType; - final String zoneName; - final Integer policyDeltaChange; - final RangerPolicy policy; - long version = -1; - - final ServiceTags.TagsChangeType tagChangeType; - final Long resourceId; - final Long tagId; - - public ServiceVersionUpdater(RangerDaoManager daoManager, Long serviceId, VERSION_TYPE versionType, Integer policyDeltaType) { - this(daoManager, serviceId, versionType, null, policyDeltaType, null); - } - - public ServiceVersionUpdater(RangerDaoManager daoManager, Long serviceId, VERSION_TYPE versionType, String zoneName, Integer policyDeltaType, RangerPolicy policy ) { - this.serviceId = serviceId; - this.daoManager = daoManager; - this.versionType = versionType; - this.policyDeltaChange = policyDeltaType; - this.zoneName = zoneName; - this.policy = policy; - this.tagChangeType = ServiceTags.TagsChangeType.NONE; - this.resourceId = null; - this.tagId = null; - } - - public ServiceVersionUpdater(RangerDaoManager daoManager, Long serviceId, VERSION_TYPE versionType, ServiceTags.TagsChangeType tagChangeType, Long resourceId, Long tagId ) { - this.serviceId = serviceId; - this.daoManager = daoManager; - this.versionType = versionType; - this.zoneName = null; - this.policyDeltaChange = null; - this.policy = null; - this.tagChangeType = tagChangeType; - this.resourceId = resourceId; - this.tagId = tagId; - } - - @Override - public void run() { - ServiceDBStore.persistVersionChange(this); - } - - @Override - public String toString() { - return "ServiceVersionUpdater:[ " + - "serviceId=" + serviceId + - ", versionType=" + versionType + - ", version=" + version + - ", zoneName=" + zoneName + - ", policyDeltaChange=" + policyDeltaChange + - ", policy=" + policy + - ", tagChangeType=" + tagChangeType + - ", resourceId=" + resourceId + - ", tagId=" + tagId + - " ]"; - } - } - - @Override - public Map getServiceConfigForPlugin(Long serviceId) { - Map configs = new HashMap<>(); - List xxServiceConfigMaps = daoMgr.getXXServiceConfigMap().findByServiceId(serviceId); - if (CollectionUtils.isNotEmpty(xxServiceConfigMaps)) { - for (XXServiceConfigMap svcConfMap : xxServiceConfigMaps) { - if (StringUtils.startsWith(svcConfMap.getConfigkey(), RANGER_PLUGIN_CONFIG_PREFIX)) { - configs.put(svcConfMap.getConfigkey(), svcConfMap.getConfigvalue()); - } - } - } - return configs; - } - - boolean hasServiceConfigForPluginChanged(List dbConfigMaps, Map validConfigs) { - boolean ret = false; - Map configs = new HashMap<>(); - if (CollectionUtils.isNotEmpty(dbConfigMaps)) { - for (XXServiceConfigMap dbConfigMap : dbConfigMaps) { - if (StringUtils.startsWith(dbConfigMap.getConfigkey(), RANGER_PLUGIN_CONFIG_PREFIX)) { - configs.put(dbConfigMap.getConfigkey(), dbConfigMap.getConfigvalue()); - } - } - } - if (MapUtils.isNotEmpty(validConfigs)) { - for (String key : validConfigs.keySet()) { - if (StringUtils.startsWith(key, RANGER_PLUGIN_CONFIG_PREFIX)) { - if (!StringUtils.equals(configs.get(key), validConfigs.get(key))) { - return true; - } else { - configs.remove(key); - } - } - } - } - if (configs.size() > 0) { - return true; - } - - return ret; - } - - /** - * Removes given service from security zones. - * @param service - * @throws Exception - */ - private void disassociateZonesForService(RangerService service) throws Exception { - String serviceName = service.getName(); - List zonesNameList = daoMgr.getXXSecurityZoneDao().findZonesByServiceName(serviceName); - if (CollectionUtils.isNotEmpty(zonesNameList)) { - for (String zoneName : zonesNameList) { - RangerSecurityZone securityZone = securityZoneStore.getSecurityZoneByName(zoneName); - Map zoneServices = securityZone.getServices(); - - if (zoneServices != null && !zoneServices.isEmpty()) { - zoneServices.remove(serviceName); - securityZone.setServices(zoneServices); - securityZoneStore.updateSecurityZoneById(securityZone); - - } - } - } - } - - private static ServicePolicies getUpdatedServicePoliciesForZones(ServicePolicies servicePolicies, Map securityZones) { - final ServicePolicies ret; - - if (MapUtils.isNotEmpty(securityZones)) { - ret = new ServicePolicies(); - - ret.setServiceDef(servicePolicies.getServiceDef()); - ret.setServiceId(servicePolicies.getServiceId()); - ret.setServiceName(servicePolicies.getServiceName()); - ret.setAuditMode(servicePolicies.getAuditMode()); - ret.setPolicyVersion(servicePolicies.getPolicyVersion()); - ret.setPolicyUpdateTime(servicePolicies.getPolicyUpdateTime()); - ret.setTagPolicies(servicePolicies.getTagPolicies()); - - Map securityZonesInfo = new HashMap<>(); - - if (CollectionUtils.isEmpty(servicePolicies.getPolicyDeltas())) { - List allPolicies = new ArrayList<>(servicePolicies.getPolicies()); - - for (Map.Entry entry : securityZones.entrySet()) { - List zonePolicies = extractZonePolicies(allPolicies, entry.getKey()); - - if (CollectionUtils.isNotEmpty(zonePolicies)) { - allPolicies.removeAll(zonePolicies); - } - - ServicePolicies.SecurityZoneInfo securityZoneInfo = new ServicePolicies.SecurityZoneInfo(); - - securityZoneInfo.setZoneName(entry.getKey()); - securityZoneInfo.setPolicies(zonePolicies); - securityZoneInfo.setResources(entry.getValue().getResources()); - securityZoneInfo.setContainsAssociatedTagService(false); - securityZonesInfo.put(entry.getKey(), securityZoneInfo); - } - - ret.setPolicies(allPolicies); - } else { - List allPolicyDeltas = new ArrayList<>(servicePolicies.getPolicyDeltas()); - - for (Map.Entry entry : securityZones.entrySet()) { - List zonePolicyDeltas = extractZonePolicyDeltas(allPolicyDeltas, entry.getKey()); - - if (CollectionUtils.isNotEmpty(zonePolicyDeltas)) { - allPolicyDeltas.removeAll(zonePolicyDeltas); - } - - ServicePolicies.SecurityZoneInfo securityZoneInfo = new ServicePolicies.SecurityZoneInfo(); - - securityZoneInfo.setZoneName(entry.getKey()); - securityZoneInfo.setPolicyDeltas(zonePolicyDeltas); - securityZoneInfo.setResources(entry.getValue().getResources()); - securityZoneInfo.setContainsAssociatedTagService(false); - securityZonesInfo.put(entry.getKey(), securityZoneInfo); - } - - ret.setPolicyDeltas(allPolicyDeltas); - } - - ret.setSecurityZones(securityZonesInfo); - } else { - ret = servicePolicies; - } - - return ret; - } - - private void patchAssociatedTagServiceInSecurityZoneInfos(ServicePolicies servicePolicies) { - if (servicePolicies != null && MapUtils.isNotEmpty(servicePolicies.getSecurityZones())) { - - // Get list of zones that associated tag-service (if any) is associated with - List zonesInAssociatedTagService = new ArrayList<>(); - - String tagServiceName = servicePolicies.getTagPolicies() != null ? servicePolicies.getTagPolicies().getServiceName() : null; - - if (StringUtils.isNotEmpty(tagServiceName)) { - try { - RangerService tagService = getServiceByName(tagServiceName); - if (tagService != null && tagService.getIsEnabled()) { - zonesInAssociatedTagService = daoMgr.getXXSecurityZoneDao().findZonesByTagServiceName(tagServiceName); - } - } catch (Exception exception) { - LOG.warn("Could not get service associated with [" + tagServiceName + "]", exception); - } - } - - if (CollectionUtils.isNotEmpty(zonesInAssociatedTagService)) { - for (Map.Entry entry : servicePolicies.getSecurityZones().entrySet()) { - String zoneName = entry.getKey(); - ServicePolicies.SecurityZoneInfo securityZoneInfo = entry.getValue(); - - securityZoneInfo.setContainsAssociatedTagService(zonesInAssociatedTagService.contains(zoneName)); - } - } - } - } - - private static List extractZonePolicies(final List allPolicies, final String zoneName) { - final List ret = new ArrayList<>(); - - for (RangerPolicy policy : allPolicies) { - if (policy.getIsEnabled() && StringUtils.equals(policy.getZoneName(), zoneName)) { - ret.add(policy); - } - } - - return ret; - } - - private static List extractZonePolicyDeltas(final List allPolicyDeltas, final String zoneName) { - final List ret = new ArrayList<>(); - - for (RangerPolicyDelta delta : allPolicyDeltas) { - if (StringUtils.equals(delta.getZoneName(), zoneName) && !StringUtils.equals(delta.getServiceType(), EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_TAG_NAME)) { - ret.add(delta); - } - } - - return ret; - } - - private ServicePolicies filterServicePolicies(ServicePolicies servicePolicies) { - ServicePolicies ret = null; - boolean containsDisabledResourcePolicies = false; - boolean containsDisabledTagPolicies = false; - - if (servicePolicies != null) { - List policies = null; - - policies = servicePolicies.getPolicies(); - if (CollectionUtils.isNotEmpty(policies)) { - for (RangerPolicy policy : policies) { - if (!policy.getIsEnabled()) { - containsDisabledResourcePolicies = true; - break; - } - } - } - - if (servicePolicies.getTagPolicies() != null) { - policies = servicePolicies.getTagPolicies().getPolicies(); - if (CollectionUtils.isNotEmpty(policies)) { - for (RangerPolicy policy : policies) { - if (!policy.getIsEnabled()) { - containsDisabledTagPolicies = true; - break; - } - } - } - } - - if (!containsDisabledResourcePolicies && !containsDisabledTagPolicies) { - ret = servicePolicies; - } else { - ret = new ServicePolicies(); - - ret.setServiceDef(servicePolicies.getServiceDef()); - ret.setServiceId(servicePolicies.getServiceId()); - ret.setServiceName(servicePolicies.getServiceName()); - ret.setPolicyVersion(servicePolicies.getPolicyVersion()); - ret.setPolicyUpdateTime(servicePolicies.getPolicyUpdateTime()); - ret.setPolicies(servicePolicies.getPolicies()); - ret.setTagPolicies(servicePolicies.getTagPolicies()); - ret.setSecurityZones(servicePolicies.getSecurityZones()); - - if (containsDisabledResourcePolicies) { - List filteredPolicies = new ArrayList<>(); - for (RangerPolicy policy : servicePolicies.getPolicies()) { - if (policy.getIsEnabled()) { - filteredPolicies.add(policy); - } - } - ret.setPolicies(filteredPolicies); - } - - if (containsDisabledTagPolicies) { - ServicePolicies.TagPolicies tagPolicies = new ServicePolicies.TagPolicies(); - - tagPolicies.setServiceDef(servicePolicies.getTagPolicies().getServiceDef()); - tagPolicies.setServiceId(servicePolicies.getTagPolicies().getServiceId()); - tagPolicies.setServiceName(servicePolicies.getTagPolicies().getServiceName()); - tagPolicies.setPolicyVersion(servicePolicies.getTagPolicies().getPolicyVersion()); - tagPolicies.setPolicyUpdateTime(servicePolicies.getTagPolicies().getPolicyUpdateTime()); - - List filteredPolicies = new ArrayList<>(); - for (RangerPolicy policy : servicePolicies.getTagPolicies().getPolicies()) { - if (policy.getIsEnabled()) { - filteredPolicies.add(policy); - } - } - tagPolicies.setPolicies(filteredPolicies); - - ret.setTagPolicies(tagPolicies); - } - } - } - - return ret; - } - - private List getAuditFiltersServiceConfigByName(String searchUsrGrpRoleName) { - if (LOG.isDebugEnabled()) { - LOG.debug("===> ServiceDBStore.getAuditFiltersServiceConfigByName( searchUsrGrpRoleName : " - + searchUsrGrpRoleName + ")"); - } - List configMapToBeModified = null; - - if (StringUtils.isNotBlank(searchUsrGrpRoleName)) { - configMapToBeModified = new ArrayList<>(); - XXServiceConfigMapDao configDao = daoMgr.getXXServiceConfigMap(); - List configs = configDao.findByConfigKey(ServiceDBStore.RANGER_PLUGIN_AUDIT_FILTERS); - for (XXServiceConfigMap configMap : configs) { - if (StringUtils.contains(configMap.getConfigvalue(), searchUsrGrpRoleName)) { - configMapToBeModified.add(configMap); - } - } - } - - if (LOG.isDebugEnabled()) { - LOG.debug("<=== ServiceDBStore.getAuditFiltersServiceConfigByName( searchUsrGrpRoleName : " - + searchUsrGrpRoleName + ") configMapToBeModified : " + configMapToBeModified); - } - return configMapToBeModified; - } - - public enum REMOVE_REF_TYPE { USER, GROUP, ROLE } - - public void updateServiceAuditConfig(String searchUsrGrpRoleName, REMOVE_REF_TYPE removeRefType) { - if (LOG.isDebugEnabled()) { - LOG.debug("===> ServiceDBStore.updateServiceAuditConfig( searchUsrGrpRoleName : " + searchUsrGrpRoleName + " removeRefType : " - + removeRefType + ")"); - } - List configMapToBeModified = getAuditFiltersServiceConfigByName(searchUsrGrpRoleName); - if (CollectionUtils.isNotEmpty(configMapToBeModified)) { - for (XXServiceConfigMap xConfigMap : configMapToBeModified) { - String jsonStr = xConfigMap.getConfigvalue() != null ? xConfigMap.getConfigvalue() : null; - if (StringUtils.isNotBlank(jsonStr)) { - List auditFilters = JsonUtils.jsonToAuditFilterList(jsonStr); - int filterCount = auditFilters != null ? auditFilters.size() : 0; - RangerService rangerService = null; - if (filterCount > 0) { - String userName = null; - String groupName = null; - String roleName = null; - if (removeRefType == REMOVE_REF_TYPE.USER) { - userName = searchUsrGrpRoleName; - } else if (removeRefType == REMOVE_REF_TYPE.GROUP) { - groupName = searchUsrGrpRoleName; - } else if (removeRefType == REMOVE_REF_TYPE.ROLE) { - roleName = searchUsrGrpRoleName; - } - removeUserGroupRoleReferences(auditFilters, userName, groupName, roleName); - String updatedJsonStr = JsonUtils.listToJson(auditFilters); - XXService xService = daoMgr.getXXService().getById(xConfigMap.getServiceId()); - rangerService = svcService.getPopulatedViewObject(xService); - Map configs = rangerService.getConfigs(); - if (configs.containsKey(ServiceDBStore.RANGER_PLUGIN_AUDIT_FILTERS)) { - updatedJsonStr = StringUtils.isBlank(updatedJsonStr) ? "" - : updatedJsonStr.replaceAll("\"", "'"); - - configs.put(ServiceDBStore.RANGER_PLUGIN_AUDIT_FILTERS, updatedJsonStr); - - try { - LOG.info("==>ServiceDBStore.updateServiceAuditConfig updating audit-filter of service : "+rangerService.getName() +" as part of delete request for : " + searchUsrGrpRoleName); - updateService(rangerService, null); - } catch (Throwable excp) { - LOG.error("updateService(" + rangerService + ") failed", excp); - - throw restErrorUtil.createRESTException(excp.getMessage()); - } - } - } else { - if (LOG.isDebugEnabled()) { - LOG.debug("ServiceDBStore.updateServiceAuditConfig audit filter count is zero "); - } - } - } - } - } else { - if (LOG.isDebugEnabled()) { - LOG.info("ServiceDBStore.updateServiceAuditConfig no service audit filter Config map found for : " - + searchUsrGrpRoleName); - } - } - if (LOG.isDebugEnabled()) { - LOG.debug("<=== ServiceDBStore.updateServiceAuditConfig( searchUsrGrpRoleName : " + searchUsrGrpRoleName + " removeRefType : " - + removeRefType + ")"); - } - } - - private void removeUserGroupRoleReferences(List auditFilters, String user, String group, String role) { - List itemsToRemove = null; - if (LOG.isDebugEnabled()) { - LOG.debug("===> ServiceDBStore.removeUserGroupRoleReferences( user : "+ user + " group : "+ group + " role : " + role + " auditFilters : " + auditFilters +")"); - } - for (AuditFilter auditFilter : auditFilters) { - boolean isAuditFilterModified = false; - if (StringUtils.isNotEmpty(user) && CollectionUtils.isNotEmpty(auditFilter.getUsers())) { - auditFilter.getUsers().remove(user); - isAuditFilterModified = true; - } - if (StringUtils.isNotEmpty(group) && CollectionUtils.isNotEmpty(auditFilter.getGroups())) { - auditFilter.getGroups().remove(group); - isAuditFilterModified = true; - } - if (StringUtils.isNotEmpty(role) && CollectionUtils.isNotEmpty(auditFilter.getRoles())) { - auditFilter.getRoles().remove(role); - isAuditFilterModified = true; - } - if (isAuditFilterModified && CollectionUtils.isEmpty(auditFilter.getUsers()) - && CollectionUtils.isEmpty(auditFilter.getGroups()) - && CollectionUtils.isEmpty(auditFilter.getRoles())) { - if (itemsToRemove == null) { - itemsToRemove = new ArrayList<>(); - } - itemsToRemove.add(auditFilter); - } - } - if (CollectionUtils.isNotEmpty(itemsToRemove)) { - auditFilters.removeAll(itemsToRemove); - } - if (LOG.isDebugEnabled()) { - LOG.debug("<=== ServiceDBStore.removeUserGroupRoleReferences( user : "+ user + " group : "+ group + " role : " + role + " auditFilters : " + auditFilters +")"); - } - } - - private void getContainingRoles(Long roleId, Set allRoles) { - if (!allRoles.contains(roleId)) { - allRoles.add(roleId); - Set roles = daoMgr.getXXRoleRefRole().getContainingRoles(roleId); - for (Long role : roles) { - getContainingRoles(role, allRoles); - } - } - } - - private Set getRoleNames(Set roles) { - Set roleNames = new HashSet<>(); - if (CollectionUtils.isNotEmpty(roles)) { - List xxRoles = daoMgr.getXXRole().getAll(); - for (Long role : roles) { - for (XXRole xxRole : xxRoles) { - if (xxRole.getId() == role) { - roleNames.add(xxRole.getName()); - break; - } - } - } - } - return roleNames; - } - - private boolean isServiceActive(String serviceName) { - boolean ret = false; - - if (StringUtils.isNotBlank(serviceName)) { - XXService service = daoMgr.getXXService().findByName(serviceName); - - ret = (service != null && service.getIsenabled()); - - if (LOG.isDebugEnabled()) { - LOG.debug("isServiceActive(" + serviceName + "): " + ret); - } - } - - return ret; - } + private void getContainingRoles(Long roleId, Set allRoles) { + if (!allRoles.contains(roleId)) { + allRoles.add(roleId); + + Set roles = daoMgr.getXXRoleRefRole().getContainingRoles(roleId); + + for (Long role : roles) { + getContainingRoles(role, allRoles); + } + } + } + + private Set getRoleNames(Set roles) { + Set roleNames = new HashSet<>(); + + if (CollectionUtils.isNotEmpty(roles)) { + List xxRoles = daoMgr.getXXRole().getAll(); + + for (Long role : roles) { + for (XXRole xxRole : xxRoles) { + if (Objects.equals(xxRole.getId(), role)) { + roleNames.add(xxRole.getName()); + break; + } + } + } + } + + return roleNames; + } + + private boolean isServiceActive(String serviceName) { + boolean ret = false; + + if (StringUtils.isNotBlank(serviceName)) { + XXService service = daoMgr.getXXService().findByName(serviceName); + + ret = (service != null && service.getIsenabled()); + + LOG.debug("isServiceActive({}): {}", serviceName, ret); + } + + return ret; + } + + public enum JSON_FILE_NAME_TYPE { POLICY, ROLE } + + public enum VERSION_TYPE { POLICY_VERSION, TAG_VERSION, ROLE_VERSION, GDS_VERSION } + + public enum METRIC_TYPE { + USER_GROUP { + @Override + public String getMetric(ServiceDBStore ref, SearchCriteria searchCriteria) { + return ref.getMetricOfTypeUserGroup(searchCriteria); + } + }, + AUDITS { + @Override + public String getMetric(ServiceDBStore ref, SearchCriteria searchCriteria) { + return ref.getMetricOfTypeAudits(searchCriteria); + } + }, + SERVICES { + @Override + public String getMetric(ServiceDBStore ref, SearchCriteria searchCriteria) { + return ref.getMetricOfTypeServices(searchCriteria); + } + }, + POLICIES { + @Override + public String getMetric(ServiceDBStore ref, SearchCriteria searchCriteria) { + return ref.getMetricOfTypePolicies(searchCriteria); + } + }, + DATABASE { + @Override + public String getMetric(ServiceDBStore ref, SearchCriteria searchCriteria) { + return ref.getMetricOfTypeDatabase(searchCriteria); + } + }, + CONTEXT_ENRICHERS { + @Override + public String getMetric(ServiceDBStore ref, SearchCriteria searchCriteria) { + return ref.getMetricOfTypeContextEnrichers(searchCriteria); + } + }, + DENY_CONDITIONS { + @Override + public String getMetric(ServiceDBStore ref, SearchCriteria searchCriteria) { + return ref.getMetricOfTypeDenyConditions(searchCriteria); + } + }; + + public static METRIC_TYPE getMetricTypeByName(final String metricTypeName) { + METRIC_TYPE ret = null; + + if (metricTypeName != null) { + switch (metricTypeName) { + case "usergroup": + ret = METRIC_TYPE.USER_GROUP; + break; + case "audits": + ret = METRIC_TYPE.AUDITS; + break; + case "services": + ret = METRIC_TYPE.SERVICES; + break; + case "policies": + ret = METRIC_TYPE.POLICIES; + break; + case "database": + ret = METRIC_TYPE.DATABASE; + break; + case "contextenrichers": + ret = METRIC_TYPE.CONTEXT_ENRICHERS; + break; + case "denyconditions": + ret = METRIC_TYPE.DENY_CONDITIONS; + break; + } + } + + return ret; + } + + abstract String getMetric(ServiceDBStore ref, SearchCriteria searchCriteria); + } + + public enum REMOVE_REF_TYPE { USER, GROUP, ROLE } + + private static class RangerPolicyDeltaComparator implements Comparator, java.io.Serializable { + @Override + public int compare(RangerPolicyDelta me, RangerPolicyDelta other) { + return Long.compare(me.getId(), other.getId()); + } + } + + public static class ServiceVersionUpdater implements Runnable { + final Long serviceId; + final RangerDaoManager daoManager; + final VERSION_TYPE versionType; + final String zoneName; + final Integer policyDeltaChange; + final RangerPolicy policy; + final ServiceTags.TagsChangeType tagChangeType; + final Long resourceId; + final Long tagId; + + long version = -1; + + public ServiceVersionUpdater(RangerDaoManager daoManager, Long serviceId, VERSION_TYPE versionType, Integer policyDeltaType) { + this(daoManager, serviceId, versionType, null, policyDeltaType, null); + } + + public ServiceVersionUpdater(RangerDaoManager daoManager, Long serviceId, VERSION_TYPE versionType, String zoneName, Integer policyDeltaType, RangerPolicy policy) { + this.serviceId = serviceId; + this.daoManager = daoManager; + this.versionType = versionType; + this.policyDeltaChange = policyDeltaType; + this.zoneName = zoneName; + this.policy = policy; + this.tagChangeType = ServiceTags.TagsChangeType.NONE; + this.resourceId = null; + this.tagId = null; + } + + public ServiceVersionUpdater(RangerDaoManager daoManager, Long serviceId, VERSION_TYPE versionType, ServiceTags.TagsChangeType tagChangeType, Long resourceId, Long tagId) { + this.serviceId = serviceId; + this.daoManager = daoManager; + this.versionType = versionType; + this.zoneName = null; + this.policyDeltaChange = null; + this.policy = null; + this.tagChangeType = tagChangeType; + this.resourceId = resourceId; + this.tagId = tagId; + } + + @Override + public void run() { + ServiceDBStore.persistVersionChange(this); + } + + @Override + public String toString() { + return "ServiceVersionUpdater:[ " + + "serviceId=" + serviceId + + ", versionType=" + versionType + + ", version=" + version + + ", zoneName=" + zoneName + + ", policyDeltaChange=" + policyDeltaChange + + ", policy=" + policy + + ", tagChangeType=" + tagChangeType + + ", resourceId=" + resourceId + + ", tagId=" + tagId + + " ]"; + } + } + + private class AssociatePolicyLabel implements Runnable { + private final String policyLabel; + private final XXPolicy xPolicy; + + AssociatePolicyLabel(String policyLabel, XXPolicy xPolicy) { + this.policyLabel = policyLabel; + this.xPolicy = xPolicy; + } + + @Override + public void run() { + getOrCreateLabel(); + } + + private void getOrCreateLabel() { + LOG.debug("==> AssociatePolicyLabel.getOrCreateLabel(policyId={}, label={})", xPolicy.getId(), policyLabel); + + XXPolicyLabel xxPolicyLabel = daoMgr.getXXPolicyLabels().findByName(policyLabel); + + if (xxPolicyLabel == null) { + xxPolicyLabel = daoMgr.getXXPolicyLabels().findByName(policyLabel); + + if (xxPolicyLabel == null) { + xxPolicyLabel = new XXPolicyLabel(); + + xxPolicyLabel.setPolicyLabel(policyLabel); + + xxPolicyLabel = rangerAuditFields.populateAuditFieldsForCreate(xxPolicyLabel); + xxPolicyLabel = daoMgr.getXXPolicyLabels().create(xxPolicyLabel); + } + } + + if (xxPolicyLabel != null) { + XXPolicyLabelMap xxPolicyLabelMap = new XXPolicyLabelMap(); + + xxPolicyLabelMap.setPolicyId(xPolicy.getId()); + xxPolicyLabelMap.setPolicyLabelId(xxPolicyLabel.getId()); + + xxPolicyLabelMap = rangerAuditFields.populateAuditFieldsForCreate(xxPolicyLabelMap); + + daoMgr.getXXPolicyLabelMap().create(xxPolicyLabelMap); + } + + LOG.debug("<== AssociatePolicyLabel.getOrCreateLabel(policyId={}, label={})", xPolicy.getId(), policyLabel); + } + } + + static { + try { + LOCAL_HOSTNAME = java.net.InetAddress.getLocalHost().getCanonicalHostName(); + } catch (UnknownHostException e) { + LOCAL_HOSTNAME = "unknown"; + } + } } diff --git a/security-admin/src/main/java/org/apache/ranger/biz/ServiceMgr.java b/security-admin/src/main/java/org/apache/ranger/biz/ServiceMgr.java index 8108b71ed6..cea1c5736e 100755 --- a/security-admin/src/main/java/org/apache/ranger/biz/ServiceMgr.java +++ b/security-admin/src/main/java/org/apache/ranger/biz/ServiceMgr.java @@ -19,20 +19,6 @@ package org.apache.ranger.biz; -import java.io.File; -import java.net.URL; -import java.net.URLClassLoader; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Date; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.Callable; -import java.util.concurrent.TimeUnit; - import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang.StringUtils; import org.apache.hadoop.security.SecureClientLogin; @@ -61,680 +47,668 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; -import static org.apache.ranger.plugin.policyengine.RangerPolicyEngine.GROUP_PUBLIC; +import java.io.File; +import java.net.URL; +import java.net.URLClassLoader; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Date; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.Callable; +import java.util.concurrent.TimeUnit; +import static org.apache.ranger.plugin.policyengine.RangerPolicyEngine.GROUP_PUBLIC; @Component public class ServiceMgr { - private static final Logger LOG = LoggerFactory.getLogger(ServiceMgr.class); - - private static final String LOOKUP_PRINCIPAL = "ranger.lookup.kerberos.principal"; - private static final String LOOKUP_KEYTAB = "ranger.lookup.kerberos.keytab"; - private static final String ADMIN_USER_PRINCIPAL = "ranger.admin.kerberos.principal"; - private static final String ADMIN_USER_KEYTAB = "ranger.admin.kerberos.keytab"; - private static final String AUTHENTICATION_TYPE = "hadoop.security.authentication"; - private static final String KERBEROS_TYPE = "kerberos"; - private static final String NAME_RULES = "hadoop.security.auth_to_local"; - private static final String HOST_NAME = "ranger.service.host"; - - private static final long _DefaultTimeoutValue_Lookp = 1000; // 1 s - private static final long _DefaultTimeoutValue_ValidateConfig = 10000; // 10 s - - private static final Map> serviceTypeClassMap = new HashMap<>(); - - @Autowired - RangerServiceService rangerSvcService; - - @Autowired - ServiceDBStore svcDBStore; - - @Autowired - TagDBStore tagStore; - - @Autowired - RoleDBStore rolesStore; - - @Autowired - TimedExecutor timedExecutor; - - @Autowired - RangerBizUtil rangerBizUtil; - - @Autowired - SecurityZoneDBStore zoneStore; - - @Autowired - XXGroupUserDao groupUserDao; - - public List lookupResource(String serviceName, ResourceLookupContext context, ServiceStore svcStore) throws Exception { - List ret = null; - RangerService service = svcDBStore.getServiceByName(serviceName); - - String authType = PropertiesUtil.getProperty(AUTHENTICATION_TYPE); - String lookupPrincipal = SecureClientLogin.getPrincipal(PropertiesUtil.getProperty(LOOKUP_PRINCIPAL), PropertiesUtil.getProperty(HOST_NAME)); - String lookupKeytab = PropertiesUtil.getProperty(LOOKUP_KEYTAB); - String nameRules = PropertiesUtil.getProperty(NAME_RULES); - String rangerPrincipal = SecureClientLogin.getPrincipal(PropertiesUtil.getProperty(ADMIN_USER_PRINCIPAL), PropertiesUtil.getProperty(HOST_NAME)); - String rangerkeytab = PropertiesUtil.getProperty(ADMIN_USER_KEYTAB); - - if(!StringUtils.isEmpty(authType) && KERBEROS_TYPE.equalsIgnoreCase(authType.trim()) && SecureClientLogin.isKerberosCredentialExists(lookupPrincipal, lookupKeytab)){ - if(service != null && service.getConfigs() != null){ - service.getConfigs().put(HadoopConfigHolder.RANGER_LOOKUP_PRINCIPAL, lookupPrincipal); - service.getConfigs().put(HadoopConfigHolder.RANGER_LOOKUP_KEYTAB, lookupKeytab); - service.getConfigs().put(HadoopConfigHolder.RANGER_NAME_RULES, nameRules); - service.getConfigs().put(HadoopConfigHolder.RANGER_AUTH_TYPE, authType); - } - } - if(!StringUtils.isEmpty(authType) && KERBEROS_TYPE.equalsIgnoreCase(authType.trim()) && SecureClientLogin.isKerberosCredentialExists(rangerPrincipal, rangerkeytab)){ - if(service != null && service.getConfigs() != null){ - service.getConfigs().put(HadoopConfigHolder.RANGER_PRINCIPAL, rangerPrincipal); - service.getConfigs().put(HadoopConfigHolder.RANGER_KEYTAB, rangerkeytab); - service.getConfigs().put(HadoopConfigHolder.RANGER_NAME_RULES, nameRules); - service.getConfigs().put(HadoopConfigHolder.RANGER_AUTH_TYPE, authType); - } - } - - Map newConfigs = rangerSvcService.getConfigsWithDecryptedPassword(service); - service.setConfigs(newConfigs); - - RangerBaseService svc = getRangerServiceByService(service, svcStore); - - if(LOG.isDebugEnabled()) { - LOG.debug("==> ServiceMgr.lookupResource for Service: (" + svc + "Context: " + context + ")"); - } - - if(svc != null) { - if (StringUtils.equals(svc.getServiceDef().getName(), EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_TAG_NAME)) { - ret = svc.lookupResource(context); - } else { - LookupCallable callable = new LookupCallable(svc, context); - long time = getTimeoutValueForLookupInMilliSeconds(svc); - ret = timedExecutor.timedTask(callable, time, TimeUnit.MILLISECONDS); - } - } - - if(LOG.isDebugEnabled()) { - LOG.debug("==> ServiceMgr.lookupResource for Response: (" + ret + ")"); - } - - return ret; - } - - public VXResponse validateConfig(RangerService service, ServiceStore svcStore) throws Exception { - VXResponse ret = new VXResponse(); - String authType = PropertiesUtil.getProperty(AUTHENTICATION_TYPE); - String lookupPrincipal = SecureClientLogin.getPrincipal(PropertiesUtil.getProperty(LOOKUP_PRINCIPAL), PropertiesUtil.getProperty(HOST_NAME)); - String lookupKeytab = PropertiesUtil.getProperty(LOOKUP_KEYTAB); - String nameRules = PropertiesUtil.getProperty(NAME_RULES); - String rangerPrincipal = SecureClientLogin.getPrincipal(PropertiesUtil.getProperty(ADMIN_USER_PRINCIPAL), PropertiesUtil.getProperty(HOST_NAME)); - String rangerkeytab = PropertiesUtil.getProperty(ADMIN_USER_KEYTAB); - - if(!StringUtils.isEmpty(authType) && KERBEROS_TYPE.equalsIgnoreCase(authType.trim()) && SecureClientLogin.isKerberosCredentialExists(lookupPrincipal, lookupKeytab)){ - if(service != null && service.getConfigs() != null){ - service.getConfigs().put(HadoopConfigHolder.RANGER_LOOKUP_PRINCIPAL, lookupPrincipal); - service.getConfigs().put(HadoopConfigHolder.RANGER_LOOKUP_KEYTAB, lookupKeytab); - service.getConfigs().put(HadoopConfigHolder.RANGER_NAME_RULES, nameRules); - service.getConfigs().put(HadoopConfigHolder.RANGER_AUTH_TYPE, authType); - } - } - if(!StringUtils.isEmpty(authType) && KERBEROS_TYPE.equalsIgnoreCase(authType.trim()) && SecureClientLogin.isKerberosCredentialExists(rangerPrincipal, rangerkeytab)){ - if(service != null && service.getConfigs() != null){ - service.getConfigs().put(HadoopConfigHolder.RANGER_PRINCIPAL, rangerPrincipal); - service.getConfigs().put(HadoopConfigHolder.RANGER_KEYTAB, rangerkeytab); - service.getConfigs().put(HadoopConfigHolder.RANGER_NAME_RULES, nameRules); - service.getConfigs().put(HadoopConfigHolder.RANGER_AUTH_TYPE, authType); - } - } - RangerBaseService svc=null; - if(service!=null){ - Map newConfigs = rangerSvcService.getConfigsWithDecryptedPassword(service); - service.setConfigs(newConfigs); - svc = getRangerServiceByService(service, svcStore); - } - if(LOG.isDebugEnabled()) { - LOG.debug("==> ServiceMgr.validateConfig for Service: (" + svc + ")"); - } - - // check if service configs contains localhost/127.0.0.1 - if (service != null && service.getConfigs() != null) { - for (Map.Entry entry : service.getConfigs().entrySet()) { - if (entry.getValue() != null && StringUtils.containsIgnoreCase(entry.getValue(), "localhost") - || StringUtils.containsIgnoreCase(entry.getValue(), "127.0.0.1")) { - URL url = getValidURL(entry.getValue()); - if ((url != null) && (url.getHost().equalsIgnoreCase("localhost") || url.getHost().equals("127.0.0.1"))) { - throw new Exception("Invalid value for configuration " + entry.getKey() + ": host " + url.getHost() + " is not allowed"); - } - } - } - } - - if(svc != null) { - try { - // Timeout value use during validate config is 10 times that used during lookup - long time = getTimeoutValueForValidateConfigInMilliSeconds(svc); - ValidateCallable callable = new ValidateCallable(svc); - Map responseData = timedExecutor.timedTask(callable, time, TimeUnit.MILLISECONDS); - - ret = generateResponseForTestConn(responseData, ""); - } catch (Exception e) { - Map respData = (e instanceof HadoopException) ? ((HadoopException) e).getResponseData() : new HashMap<>(); - String msg; - - if (StringUtils.contains(e.getMessage(), RangerDefaultService.ERROR_MSG_VALIDATE_CONFIG_NOT_IMPLEMENTED)) { - msg = RangerDefaultService.ERROR_MSG_VALIDATE_CONFIG_NOT_IMPLEMENTED + " for " + svc.getServiceType(); - } else { - msg = "Unable to connect repository with given config for " + svc.getServiceName(); - } - - ret = generateResponseForTestConn(respData, msg); - - LOG.error("==> ServiceMgr.validateConfig Error:" + e); - } - } - - if(LOG.isDebugEnabled()) { - LOG.debug("==> ServiceMgr.validateConfig for Response: (" + ret + ")"); - } - - return ret; - } - - private static URL getValidURL(String urlString) { - try { - return new URL(urlString); - } catch (Exception e) { - return null; - } - } - - public boolean isZoneAdmin(String zoneName) { - boolean isZoneAdmin = false; - RangerSecurityZone securityZone = null; - - try { - securityZone = zoneStore.getSecurityZoneByName(zoneName); - } catch (Exception e) { - LOG.error("Unexpected error when fetching security zone with name:[" + zoneName + "] from database", e); - } - - if (securityZone != null) { - String userId = rangerBizUtil.getCurrentUserLoginId(); - - if (securityZone.getAdminUsers() != null && securityZone.getAdminUsers().contains(userId)) { - isZoneAdmin = true; - } - - Set loggedInUsersGroups = Collections.emptySet(); - - if (!isZoneAdmin && securityZone.getAdminUserGroups() != null) { - List groupUsers = groupUserDao.findByUserId(rangerBizUtil.getXUserId()); - - loggedInUsersGroups = new HashSet<>(); - - loggedInUsersGroups.add(GROUP_PUBLIC); - - if (groupUsers != null) { - for (XXGroupUser groupUser : groupUsers) { - loggedInUsersGroups.add(groupUser.getName()); - } - } - - isZoneAdmin = CollectionUtils.containsAny(securityZone.getAdminUserGroups(), loggedInUsersGroups); - } - - if (!isZoneAdmin && securityZone.getAdminRoles() != null) { - isZoneAdmin = isUserOrUserGroupsInRole(userId, loggedInUsersGroups, securityZone.getAdminRoles()); - } - } - - return isZoneAdmin; - } - - public boolean isZoneAuditor(String zoneName) { - boolean isZoneAuditor = false; - RangerSecurityZone securityZone = null; - - try { - securityZone = zoneStore.getSecurityZoneByName(zoneName); - } catch (Exception e) { - LOG.error("Unexpected error when fetching security zone with name:[" + zoneName + "] from database", e); - } - - if (securityZone != null) { - String userId = rangerBizUtil.getCurrentUserLoginId(); - - if (securityZone.getAuditUsers() != null && securityZone.getAuditUsers().contains(userId)) { - isZoneAuditor = true; - } + private static final Logger LOG = LoggerFactory.getLogger(ServiceMgr.class); - Set loggedInUsersGroups = Collections.emptySet(); + private static final String LOOKUP_PRINCIPAL = "ranger.lookup.kerberos.principal"; + private static final String LOOKUP_KEYTAB = "ranger.lookup.kerberos.keytab"; + private static final String ADMIN_USER_PRINCIPAL = "ranger.admin.kerberos.principal"; + private static final String ADMIN_USER_KEYTAB = "ranger.admin.kerberos.keytab"; + private static final String AUTHENTICATION_TYPE = "hadoop.security.authentication"; + private static final String KERBEROS_TYPE = "kerberos"; + private static final String NAME_RULES = "hadoop.security.auth_to_local"; + private static final String HOST_NAME = "ranger.service.host"; + + private static final long _DefaultTimeoutValue_Lookp = 1000; // 1 s + private static final long _DefaultTimeoutValue_ValidateConfig = 10000; // 10 s + + private static final Map> serviceTypeClassMap = new HashMap<>(); + + @Autowired + RangerServiceService rangerSvcService; + + @Autowired + ServiceDBStore svcDBStore; + + @Autowired + TagDBStore tagStore; + + @Autowired + RoleDBStore rolesStore; + + @Autowired + TimedExecutor timedExecutor; + + @Autowired + RangerBizUtil rangerBizUtil; + + @Autowired + SecurityZoneDBStore zoneStore; + + @Autowired + XXGroupUserDao groupUserDao; + + public List lookupResource(String serviceName, ResourceLookupContext context, ServiceStore svcStore) throws Exception { + List ret = null; + RangerService service = svcDBStore.getServiceByName(serviceName); + + String authType = PropertiesUtil.getProperty(AUTHENTICATION_TYPE); + String lookupPrincipal = SecureClientLogin.getPrincipal(PropertiesUtil.getProperty(LOOKUP_PRINCIPAL), PropertiesUtil.getProperty(HOST_NAME)); + String lookupKeytab = PropertiesUtil.getProperty(LOOKUP_KEYTAB); + String nameRules = PropertiesUtil.getProperty(NAME_RULES); + String rangerPrincipal = SecureClientLogin.getPrincipal(PropertiesUtil.getProperty(ADMIN_USER_PRINCIPAL), PropertiesUtil.getProperty(HOST_NAME)); + String rangerkeytab = PropertiesUtil.getProperty(ADMIN_USER_KEYTAB); + + if (!StringUtils.isEmpty(authType) && KERBEROS_TYPE.equalsIgnoreCase(authType.trim()) && SecureClientLogin.isKerberosCredentialExists(lookupPrincipal, lookupKeytab)) { + if (service != null && service.getConfigs() != null) { + service.getConfigs().put(HadoopConfigHolder.RANGER_LOOKUP_PRINCIPAL, lookupPrincipal); + service.getConfigs().put(HadoopConfigHolder.RANGER_LOOKUP_KEYTAB, lookupKeytab); + service.getConfigs().put(HadoopConfigHolder.RANGER_NAME_RULES, nameRules); + service.getConfigs().put(HadoopConfigHolder.RANGER_AUTH_TYPE, authType); + } + } + + if (!StringUtils.isEmpty(authType) && KERBEROS_TYPE.equalsIgnoreCase(authType.trim()) && SecureClientLogin.isKerberosCredentialExists(rangerPrincipal, rangerkeytab)) { + if (service != null && service.getConfigs() != null) { + service.getConfigs().put(HadoopConfigHolder.RANGER_PRINCIPAL, rangerPrincipal); + service.getConfigs().put(HadoopConfigHolder.RANGER_KEYTAB, rangerkeytab); + service.getConfigs().put(HadoopConfigHolder.RANGER_NAME_RULES, nameRules); + service.getConfigs().put(HadoopConfigHolder.RANGER_AUTH_TYPE, authType); + } + } + + Map newConfigs = rangerSvcService.getConfigsWithDecryptedPassword(service); + + service.setConfigs(newConfigs); + + RangerBaseService svc = getRangerServiceByService(service, svcStore); + + LOG.debug("==> ServiceMgr.lookupResource for Service: ({}Context: {})", svc, context); + + if (svc != null) { + if (StringUtils.equals(svc.getServiceDef().getName(), EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_TAG_NAME)) { + ret = svc.lookupResource(context); + } else { + LookupCallable callable = new LookupCallable(svc, context); + long time = getTimeoutValueForLookupInMilliSeconds(svc); + + ret = timedExecutor.timedTask(callable, time, TimeUnit.MILLISECONDS); + } + } + + LOG.debug("==> ServiceMgr.lookupResource for Response: ({})", ret); + + return ret; + } + + public VXResponse validateConfig(RangerService service, ServiceStore svcStore) throws Exception { + VXResponse ret = new VXResponse(); + String authType = PropertiesUtil.getProperty(AUTHENTICATION_TYPE); + String lookupPrincipal = SecureClientLogin.getPrincipal(PropertiesUtil.getProperty(LOOKUP_PRINCIPAL), PropertiesUtil.getProperty(HOST_NAME)); + String lookupKeytab = PropertiesUtil.getProperty(LOOKUP_KEYTAB); + String nameRules = PropertiesUtil.getProperty(NAME_RULES); + String rangerPrincipal = SecureClientLogin.getPrincipal(PropertiesUtil.getProperty(ADMIN_USER_PRINCIPAL), PropertiesUtil.getProperty(HOST_NAME)); + String rangerkeytab = PropertiesUtil.getProperty(ADMIN_USER_KEYTAB); + + if (!StringUtils.isEmpty(authType) && KERBEROS_TYPE.equalsIgnoreCase(authType.trim()) && SecureClientLogin.isKerberosCredentialExists(lookupPrincipal, lookupKeytab)) { + if (service != null && service.getConfigs() != null) { + service.getConfigs().put(HadoopConfigHolder.RANGER_LOOKUP_PRINCIPAL, lookupPrincipal); + service.getConfigs().put(HadoopConfigHolder.RANGER_LOOKUP_KEYTAB, lookupKeytab); + service.getConfigs().put(HadoopConfigHolder.RANGER_NAME_RULES, nameRules); + service.getConfigs().put(HadoopConfigHolder.RANGER_AUTH_TYPE, authType); + } + } - if (!isZoneAuditor && securityZone.getAuditUserGroups() != null) { - List groupUsers = groupUserDao.findByUserId(rangerBizUtil.getXUserId()); + if (!StringUtils.isEmpty(authType) && KERBEROS_TYPE.equalsIgnoreCase(authType.trim()) && SecureClientLogin.isKerberosCredentialExists(rangerPrincipal, rangerkeytab)) { + if (service != null && service.getConfigs() != null) { + service.getConfigs().put(HadoopConfigHolder.RANGER_PRINCIPAL, rangerPrincipal); + service.getConfigs().put(HadoopConfigHolder.RANGER_KEYTAB, rangerkeytab); + service.getConfigs().put(HadoopConfigHolder.RANGER_NAME_RULES, nameRules); + service.getConfigs().put(HadoopConfigHolder.RANGER_AUTH_TYPE, authType); + } + } + + RangerBaseService svc = null; + + if (service != null) { + Map newConfigs = rangerSvcService.getConfigsWithDecryptedPassword(service); + + service.setConfigs(newConfigs); + + svc = getRangerServiceByService(service, svcStore); + } + + LOG.debug("==> ServiceMgr.validateConfig for Service: ({})", svc); + + // check if service configs contains localhost/127.0.0.1 + if (service != null && service.getConfigs() != null) { + for (Map.Entry entry : service.getConfigs().entrySet()) { + if (entry.getValue() != null && StringUtils.containsIgnoreCase(entry.getValue(), "localhost") || StringUtils.containsIgnoreCase(entry.getValue(), "127.0.0.1")) { + URL url = getValidURL(entry.getValue()); + + if ((url != null) && (url.getHost().equalsIgnoreCase("localhost") || url.getHost().equals("127.0.0.1"))) { + throw new Exception("Invalid value for configuration " + entry.getKey() + ": host " + url.getHost() + " is not allowed"); + } + } + } + } + + if (svc != null) { + try { + // Timeout value use during validate config is 10 times that used during lookup + long time = getTimeoutValueForValidateConfigInMilliSeconds(svc); + ValidateCallable callable = new ValidateCallable(svc); + Map responseData = timedExecutor.timedTask(callable, time, TimeUnit.MILLISECONDS); + + ret = generateResponseForTestConn(responseData, ""); + } catch (Exception e) { + Map respData = (e instanceof HadoopException) ? ((HadoopException) e).getResponseData() : new HashMap<>(); + String msg; - loggedInUsersGroups = new HashSet<>(); + if (StringUtils.contains(e.getMessage(), RangerDefaultService.ERROR_MSG_VALIDATE_CONFIG_NOT_IMPLEMENTED)) { + msg = RangerDefaultService.ERROR_MSG_VALIDATE_CONFIG_NOT_IMPLEMENTED + " for " + svc.getServiceType(); + } else { + msg = "Unable to connect repository with given config for " + svc.getServiceName(); + } - loggedInUsersGroups.add(GROUP_PUBLIC); + ret = generateResponseForTestConn(respData, msg); - if (groupUsers != null) { - for (XXGroupUser groupUser : groupUsers) { - loggedInUsersGroups.add(groupUser.getName()); - } - } + LOG.error("==> ServiceMgr.validateConfig Error:{}", String.valueOf(e)); + } + } - isZoneAuditor = CollectionUtils.containsAny(securityZone.getAuditUserGroups(), loggedInUsersGroups); - } + LOG.debug("==> ServiceMgr.validateConfig for Response: ({})", ret); - if (!isZoneAuditor && securityZone.getAuditRoles() != null) { - isZoneAuditor = isUserOrUserGroupsInRole(userId, loggedInUsersGroups, securityZone.getAuditRoles()); - } - } + return ret; + } - return isZoneAuditor; - } + public boolean isZoneAdmin(String zoneName) { + boolean isZoneAdmin = false; + RangerSecurityZone securityZone = null; - public RangerBaseService getRangerServiceByName(String serviceName, ServiceStore svcStore) throws Exception { - if(LOG.isDebugEnabled()) { - LOG.debug("==> ServiceMgr.getRangerServiceByName(" + serviceName + ")"); - } + try { + securityZone = zoneStore.getSecurityZoneByName(zoneName); + } catch (Exception e) { + LOG.error("Unexpected error when fetching security zone with name:[{}] from database", zoneName, e); + } - RangerBaseService ret = null; - RangerService service = svcStore == null ? null : svcStore.getServiceByName(serviceName); + if (securityZone != null) { + String userId = rangerBizUtil.getCurrentUserLoginId(); - if(service != null) { - ret = getRangerServiceByService(service, svcStore); - } else { - LOG.warn("ServiceMgr.getRangerServiceByName(" + serviceName + "): could not find the service"); - } + if (securityZone.getAdminUsers() != null && securityZone.getAdminUsers().contains(userId)) { + isZoneAdmin = true; + } - if(LOG.isDebugEnabled()) { - LOG.debug("<== ServiceMgr.getRangerServiceByName(" + serviceName + "): " + ret); - } + Set loggedInUsersGroups = Collections.emptySet(); - return ret; - } - - public RangerBaseService getRangerServiceByService(RangerService service, ServiceStore svcStore) throws Exception{ - if(LOG.isDebugEnabled()) { - LOG.debug("==> ServiceMgr.getRangerServiceByService(" + service + ")"); - } - - RangerBaseService ret = null; - String serviceType = service == null ? null : service.getType(); - - if(! StringUtils.isEmpty(serviceType)) { - RangerServiceDef serviceDef = svcStore == null ? null : svcStore.getServiceDefByName(serviceType); - - if(serviceDef != null) { - Class cls = getClassForServiceType(serviceDef); - - if(cls != null) { - ret = cls.newInstance(); - - ret.init(serviceDef, service); - - if(ret instanceof RangerServiceTag) { - ((RangerServiceTag)ret).setTagStore(tagStore); - } - } else { - LOG.warn("ServiceMgr.getRangerServiceByService(" + service + "): could not find service class '" - + serviceDef.getImplClass() + "' for the service type '" + serviceType + "'"); - } - } else { - LOG.warn("ServiceMgr.getRangerServiceByService(" + service + "): could not find the service-def for the service type '" + serviceType + "'"); - } - } else { - LOG.warn("ServiceMgr.getRangerServiceByService(" + service + "): could not find the service-type '" + serviceType + "'"); - } + if (!isZoneAdmin && securityZone.getAdminUserGroups() != null) { + List groupUsers = groupUserDao.findByUserId(rangerBizUtil.getXUserId()); - if(LOG.isDebugEnabled()) { - LOG.debug("<== ServiceMgr.getRangerServiceByService(" + service + "): " + ret); - } - - return ret; - } - - @SuppressWarnings("unchecked") - private Class getClassForServiceType(RangerServiceDef serviceDef) throws Exception { - if(LOG.isDebugEnabled()) { - LOG.debug("==> ServiceMgr.getClassForServiceType(" + serviceDef + ")"); - } - - Class ret = null; - - if(serviceDef != null) { - String serviceType = serviceDef.getName(); - - ret = serviceTypeClassMap.get(serviceType); - - if(ret == null) { - synchronized(serviceTypeClassMap) { - ret = serviceTypeClassMap.get(serviceType); - - if(ret == null) { - String clsName = serviceDef.getImplClass(); - - if(LOG.isDebugEnabled()) { - LOG.debug("ServiceMgr.getClassForServiceType(" + serviceType + "): service-class " + clsName + " not found in cache"); - } - - try { - if (StringUtils.isEmpty(clsName)) { - if (LOG.isDebugEnabled()) { - LOG.debug("No service-class configured for service-type:[" + serviceType + "], using RangerDefaultService"); - } - - ret = RangerDefaultService.class; - } else { - URL[] pluginFiles = getPluginFilesForServiceType(serviceType); - URLClassLoader clsLoader = new URLClassLoader(pluginFiles, Thread.currentThread().getContextClassLoader()); - Class cls = Class.forName(clsName, true, clsLoader); - - ret = (Class) cls; - } - } catch (Exception excp) { - LOG.warn("ServiceMgr.getClassForServiceType(" + serviceType + "): failed to find service-class '" + clsName + "'. Resource lookup will not be available. Using RangerDefaultService", excp); - - ret = RangerDefaultService.class; - } - - serviceTypeClassMap.put(serviceType, ret); - - if (LOG.isDebugEnabled()) { - LOG.debug("ServiceMgr.getClassForServiceType(" + serviceType + "): service-class " + ret.getCanonicalName() + " added to cache"); - } - } else { - if(LOG.isDebugEnabled()) { - LOG.debug("ServiceMgr.getClassForServiceType(" + serviceType + "): service-class " + ret.getCanonicalName() + " found in cache"); - } - } - } - } else { - if(LOG.isDebugEnabled()) { - LOG.debug("ServiceMgr.getClassForServiceType(" + serviceType + "): service-class " + ret.getCanonicalName() + " found in cache"); - } - } - } - - if(LOG.isDebugEnabled()) { - LOG.debug("<== ServiceMgr.getClassForServiceType(" + serviceDef + "): " + ret); - } - - return ret; - } - - private URL[] getPluginFilesForServiceType(String serviceType) { - if(LOG.isDebugEnabled()) { - LOG.debug("==> ServiceMgr.getPluginFilesForServiceType(" + serviceType + ")"); - } - - List ret = new ArrayList(); - - getFilesInDirectory("ranger-plugins/" + serviceType, ret); - - if(LOG.isDebugEnabled()) { - LOG.debug("<== ServiceMgr.getPluginFilesForServiceType(" + serviceType + "): " + ret.size() + " files"); - } - - return ret.toArray(new URL[] { }); - } - - private void getFilesInDirectory(String dirPath, List files) { - if(LOG.isDebugEnabled()) { - LOG.debug("==> ServiceMgr.getFilesInDirectory(" + dirPath + ")"); - } - - URL pluginJarPath = getClass().getClassLoader().getResource(dirPath); - - if(pluginJarPath != null && "file".equals(pluginJarPath.getProtocol())) { - try { - File[] dirFiles = new File(pluginJarPath.toURI()).listFiles(); - - if(dirFiles != null) { - for(File dirFile : dirFiles) { - try { - URL jarPath = dirFile.toURI().toURL(); - - if (LOG.isDebugEnabled()) { - LOG.debug("getFilesInDirectory('" + dirPath + "'): adding " + dirFile.getAbsolutePath()); - } - - files.add(jarPath); - } catch(Exception excp) { - LOG.warn("getFilesInDirectory('" + dirPath + "'): failed to get URI for file " + dirFile.getAbsolutePath(), excp); - } - } - } - } catch(Exception excp) { - LOG.warn("getFilesInDirectory('" + dirPath + "'): error", excp); - } - } else { - if (LOG.isDebugEnabled()) { - LOG.debug("getFilesInDirectory('" + dirPath + "'): could not find directory in CLASSPATH"); - } - } - - if(LOG.isDebugEnabled()) { - LOG.debug("<== ServiceMgr.getFilesInDirectory(" + dirPath + ")"); - } - } - - private VXResponse generateResponseForTestConn( - Map responseData, String msg) { - VXResponse vXResponse = new VXResponse(); - - Long objId = null; - boolean connectivityStatus = false; - int statusCode = VXResponse.STATUS_ERROR; - String message = msg; - String description = msg; - String fieldName = null; - - if (responseData != null) { - if (responseData.get("objectId") != null) { - objId = Long.parseLong(responseData.get("objectId").toString()); - } - if (responseData.get("connectivityStatus") != null) { - connectivityStatus = Boolean.parseBoolean(responseData.get("connectivityStatus").toString()); - } - if (connectivityStatus) { - statusCode = VXResponse.STATUS_SUCCESS; - } - if (responseData.get("message") != null) { - message = responseData.get("message").toString(); - } - if (responseData.get("description") != null) { - description = responseData.get("description").toString(); - } - if (responseData.get("fieldName") != null) { - fieldName = responseData.get("fieldName").toString(); - } - } - - VXMessage vXMsg = new VXMessage(); - List vXMsgList = new ArrayList(); - vXMsg.setFieldName(fieldName); - vXMsg.setMessage(message); - vXMsg.setObjectId(objId); - vXMsgList.add(vXMsg); - - vXResponse.setMessageList(vXMsgList); - vXResponse.setMsgDesc(description); - vXResponse.setStatusCode(statusCode); - return vXResponse; - } - - private boolean isUserOrUserGroupsInRole(String userId, Set userGroups, List roles) { - boolean ret = false; - RangerRoles rangerRoles = null; - - try { - rangerRoles = rolesStore.getRoles("", -1L); - } catch (Exception excp) { - LOG.error("Unexpected error when fetching roles from database", excp); - } - - if (rangerRoles != null) { - RangerRolesUtil rolesUtil = new RangerRolesUtil(rangerRoles); - Set userRoles = rolesUtil.getUserRoleMapping().get(userId); - - ret = userRoles != null && CollectionUtils.containsAny(roles, userRoles); - - if (!ret && userGroups != null) { - for (String userGroup : userGroups) { - Set groupRoles = rolesUtil.getGroupRoleMapping().get(userGroup); - - ret = groupRoles != null && CollectionUtils.containsAny(roles, groupRoles); - - if (ret) { - break; - } - } - } - } - - return ret; - } - - long getTimeoutValueForLookupInMilliSeconds(RangerBaseService svc) { - return getTimeoutValueInMilliSeconds("resource.lookup", svc, _DefaultTimeoutValue_Lookp); - } - - long getTimeoutValueForValidateConfigInMilliSeconds(RangerBaseService svc) { - return getTimeoutValueInMilliSeconds("validate.config", svc, _DefaultTimeoutValue_ValidateConfig); - } - - long getTimeoutValueInMilliSeconds(final String type, RangerBaseService svc, long defaultValue) { - if (LOG.isDebugEnabled()) { - LOG.debug(String.format("==> ServiceMgr.getTimeoutValueInMilliSeconds (%s, %s)", type, svc)); - } - String propertyName = type + ".timeout.value.in.ms"; // type == "lookup" || type == "validate-config" - - Long result = null; - Map config = svc.getConfigs(); - if (config != null && config.containsKey(propertyName)) { - result = parseLong(config.get(propertyName)); - } - if (result != null) { - LOG.debug("Found override in service config!"); - } else { - String[] keys = new String[] { - "ranger.service." + svc.getServiceName() + "." + propertyName, - "ranger.servicetype." + svc.getServiceType() + "." + propertyName, - "ranger." + propertyName - }; - for (String key : keys) { - String value = PropertiesUtil.getProperty(key); - if (value != null) { - result = parseLong(value); - if (result != null) { - if (LOG.isDebugEnabled()) { - LOG.debug("Using the value[" + value + "] found in property[" + key + "]"); - } - break; - } - } - } - } - if (result == null) { - if (LOG.isDebugEnabled()) { - LOG.debug("No overrides found in service config of properties file. Using supplied default of[" + defaultValue + "]!"); - } - result = defaultValue; - } - - if (LOG.isDebugEnabled()) { - LOG.debug(String.format("<== ServiceMgr.getTimeoutValueInMilliSeconds (%s, %s): %s", type, svc, result)); - } - return result; - } - - Long parseLong(String str) { - try { - return Long.valueOf(str); - } catch (NumberFormatException e) { - if (LOG.isDebugEnabled()) { - LOG.debug("ServiceMgr.parseLong: could not parse [" + str + "] as Long! Returning null"); - } - return null; - } - } - - abstract static class TimedCallable implements Callable { - - final RangerBaseService svc; - final Date creation; // NOTE: This would be different from when the callable was actually offered to the executor - - public TimedCallable(RangerBaseService svc) { - this.svc = svc; - this.creation = new Date(); - } - - @Override - public T call() throws Exception { - Date start = null; - if (LOG.isDebugEnabled()) { - start = new Date(); - LOG.debug("==> TimedCallable: " + toString()); - } - - ClassLoader clsLoader = Thread.currentThread().getContextClassLoader(); - try { - Thread.currentThread().setContextClassLoader(svc.getClass().getClassLoader()); - return actualCall(); - } catch (Exception e) { - LOG.error("TimedCallable.call: Error:" + e); - throw e; - } finally { - Thread.currentThread().setContextClassLoader(clsLoader); - if (LOG.isDebugEnabled()) { - Date finish = new Date(); - long waitTime = start.getTime() - creation.getTime(); - long executionTime = finish.getTime() - start.getTime(); - LOG.debug(String.format("<== TimedCallable: %s: wait time[%d ms], execution time [%d ms]", toString(), waitTime, executionTime)); - } - } - } - - abstract T actualCall() throws Exception; - } - - static class LookupCallable extends TimedCallable> { - - final ResourceLookupContext context; - - public LookupCallable(final RangerBaseService svc, final ResourceLookupContext context) { - super(svc); - this.context = context; - } - - @Override - public String toString() { - return String.format("lookup resource[%s] for service[%s], ", context.toString(), svc.getServiceName()); - } - - @Override - public List actualCall() throws Exception { - List ret = svc.lookupResource(context); - return ret; - } - } - - static class ValidateCallable extends TimedCallable> { - - public ValidateCallable(RangerBaseService svc) { - super(svc); - } - - @Override - public String toString() { - return String.format("validate config for service[%s]", svc.getServiceName()); - } - - @Override - public Map actualCall() throws Exception { - return svc.validateConfig(); - } - } -} + loggedInUsersGroups = new HashSet<>(); + + loggedInUsersGroups.add(GROUP_PUBLIC); + + if (groupUsers != null) { + for (XXGroupUser groupUser : groupUsers) { + loggedInUsersGroups.add(groupUser.getName()); + } + } + + isZoneAdmin = CollectionUtils.containsAny(securityZone.getAdminUserGroups(), loggedInUsersGroups); + } + + if (!isZoneAdmin && securityZone.getAdminRoles() != null) { + isZoneAdmin = isUserOrUserGroupsInRole(userId, loggedInUsersGroups, securityZone.getAdminRoles()); + } + } + + return isZoneAdmin; + } + + public boolean isZoneAuditor(String zoneName) { + boolean isZoneAuditor = false; + RangerSecurityZone securityZone = null; + + try { + securityZone = zoneStore.getSecurityZoneByName(zoneName); + } catch (Exception e) { + LOG.error("Unexpected error when fetching security zone with name:[{}] from database", zoneName, e); + } + + if (securityZone != null) { + String userId = rangerBizUtil.getCurrentUserLoginId(); + + if (securityZone.getAuditUsers() != null && securityZone.getAuditUsers().contains(userId)) { + isZoneAuditor = true; + } + + Set loggedInUsersGroups = Collections.emptySet(); + + if (!isZoneAuditor && securityZone.getAuditUserGroups() != null) { + List groupUsers = groupUserDao.findByUserId(rangerBizUtil.getXUserId()); + + loggedInUsersGroups = new HashSet<>(); + + loggedInUsersGroups.add(GROUP_PUBLIC); + + if (groupUsers != null) { + for (XXGroupUser groupUser : groupUsers) { + loggedInUsersGroups.add(groupUser.getName()); + } + } + + isZoneAuditor = CollectionUtils.containsAny(securityZone.getAuditUserGroups(), loggedInUsersGroups); + } + + if (!isZoneAuditor && securityZone.getAuditRoles() != null) { + isZoneAuditor = isUserOrUserGroupsInRole(userId, loggedInUsersGroups, securityZone.getAuditRoles()); + } + } + + return isZoneAuditor; + } + + public RangerBaseService getRangerServiceByName(String serviceName, ServiceStore svcStore) throws Exception { + LOG.debug("==> ServiceMgr.getRangerServiceByName({})", serviceName); + + RangerBaseService ret = null; + RangerService service = svcStore == null ? null : svcStore.getServiceByName(serviceName); + + if (service != null) { + ret = getRangerServiceByService(service, svcStore); + } else { + LOG.warn("ServiceMgr.getRangerServiceByName({}): could not find the service", serviceName); + } + + LOG.debug("<== ServiceMgr.getRangerServiceByName({}): {}", serviceName, ret); + + return ret; + } + + public RangerBaseService getRangerServiceByService(RangerService service, ServiceStore svcStore) throws Exception { + LOG.debug("==> ServiceMgr.getRangerServiceByService({})", service); + + RangerBaseService ret = null; + String serviceType = service == null ? null : service.getType(); + + if (!StringUtils.isEmpty(serviceType)) { + RangerServiceDef serviceDef = svcStore == null ? null : svcStore.getServiceDefByName(serviceType); + + if (serviceDef != null) { + Class cls = getClassForServiceType(serviceDef); + + if (cls != null) { + ret = cls.newInstance(); + + ret.init(serviceDef, service); + + if (ret instanceof RangerServiceTag) { + ((RangerServiceTag) ret).setTagStore(tagStore); + } + } else { + LOG.warn("ServiceMgr.getRangerServiceByService({}): could not find service class '{}' for the service type '{}'", service, serviceDef.getImplClass(), serviceType); + } + } else { + LOG.warn("ServiceMgr.getRangerServiceByService({}): could not find the service-def for the service type '{}'", service, serviceType); + } + } else { + LOG.warn("ServiceMgr.getRangerServiceByService({}): could not find the service-type '{}'", service, serviceType); + } + + LOG.debug("<== ServiceMgr.getRangerServiceByService({}): {}", service, ret); + + return ret; + } + + long getTimeoutValueForLookupInMilliSeconds(RangerBaseService svc) { + return getTimeoutValueInMilliSeconds("resource.lookup", svc, _DefaultTimeoutValue_Lookp); + } + + long getTimeoutValueForValidateConfigInMilliSeconds(RangerBaseService svc) { + return getTimeoutValueInMilliSeconds("validate.config", svc, _DefaultTimeoutValue_ValidateConfig); + } + + long getTimeoutValueInMilliSeconds(final String type, RangerBaseService svc, long defaultValue) { + LOG.debug("==> ServiceMgr.getTimeoutValueInMilliSeconds ({}, {})", type, svc); + String propertyName = type + ".timeout.value.in.ms"; // type == "lookup" || type == "validate-config" + Long result = null; + Map config = svc.getConfigs(); + + if (config != null && config.containsKey(propertyName)) { + result = parseLong(config.get(propertyName)); + } + + if (result != null) { + LOG.debug("Found override in service config!"); + } else { + String[] keys = new String[] { + "ranger.service." + svc.getServiceName() + "." + propertyName, + "ranger.servicetype." + svc.getServiceType() + "." + propertyName, + "ranger." + propertyName + }; + + for (String key : keys) { + String value = PropertiesUtil.getProperty(key); + + if (value != null) { + result = parseLong(value); + + if (result != null) { + LOG.debug("Using the value[{}] found in property[{}]", value, key); + + break; + } + } + } + } + + if (result == null) { + LOG.debug("No overrides found in service config of properties file. Using supplied default of[{}]!", defaultValue); + + result = defaultValue; + } + + LOG.debug("<== ServiceMgr.getTimeoutValueInMilliSeconds ({}, {}): {}", type, svc, result); + + return result; + } + + Long parseLong(String str) { + try { + return Long.valueOf(str); + } catch (NumberFormatException e) { + LOG.debug("ServiceMgr.parseLong: could not parse [{}] as Long! Returning null", str); + + return null; + } + } + + private static URL getValidURL(String urlString) { + try { + return new URL(urlString); + } catch (Exception e) { + return null; + } + } + + @SuppressWarnings("unchecked") + private Class getClassForServiceType(RangerServiceDef serviceDef) { + LOG.debug("==> ServiceMgr.getClassForServiceType({})", serviceDef); + + Class ret = null; + + if (serviceDef != null) { + String serviceType = serviceDef.getName(); + + ret = serviceTypeClassMap.get(serviceType); + + if (ret == null) { + synchronized (serviceTypeClassMap) { + ret = serviceTypeClassMap.get(serviceType); + + if (ret == null) { + String clsName = serviceDef.getImplClass(); + + LOG.debug("ServiceMgr.getClassForServiceType({}): service-class {} not found in cache", serviceType, clsName); + + try { + if (StringUtils.isEmpty(clsName)) { + LOG.debug("No service-class configured for service-type:[{}], using RangerDefaultService", serviceType); + + ret = RangerDefaultService.class; + } else { + URL[] pluginFiles = getPluginFilesForServiceType(serviceType); + URLClassLoader clsLoader = new URLClassLoader(pluginFiles, Thread.currentThread().getContextClassLoader()); + Class cls = Class.forName(clsName, true, clsLoader); + + ret = (Class) cls; + } + } catch (Exception excp) { + LOG.warn("ServiceMgr.getClassForServiceType({}): failed to find service-class '{}'. Resource lookup will not be available. Using RangerDefaultService", serviceType, clsName, excp); + + ret = RangerDefaultService.class; + } + + serviceTypeClassMap.put(serviceType, ret); + + LOG.debug("ServiceMgr.getClassForServiceType({}): service-class {} added to cache", serviceType, ret.getCanonicalName()); + } else { + LOG.debug("ServiceMgr.getClassForServiceType({}): service-class {} found in cache", serviceType, ret.getCanonicalName()); + } + } + } else { + LOG.debug("ServiceMgr.getClassForServiceType({}): service-class {} found in cache", serviceType, ret.getCanonicalName()); + } + } + + LOG.debug("<== ServiceMgr.getClassForServiceType({}): {}", serviceDef, ret); + + return ret; + } + + private URL[] getPluginFilesForServiceType(String serviceType) { + LOG.debug("==> ServiceMgr.getPluginFilesForServiceType({})", serviceType); + + List ret = new ArrayList<>(); + + getFilesInDirectory("ranger-plugins/" + serviceType, ret); + + LOG.debug("<== ServiceMgr.getPluginFilesForServiceType({}): {} files", serviceType, ret.size()); + + return ret.toArray(new URL[] {}); + } + + private void getFilesInDirectory(String dirPath, List files) { + LOG.debug("==> ServiceMgr.getFilesInDirectory({})", dirPath); + + URL pluginJarPath = getClass().getClassLoader().getResource(dirPath); + + if (pluginJarPath != null && "file".equals(pluginJarPath.getProtocol())) { + try { + File[] dirFiles = new File(pluginJarPath.toURI()).listFiles(); + + if (dirFiles != null) { + for (File dirFile : dirFiles) { + try { + URL jarPath = dirFile.toURI().toURL(); + + LOG.debug("getFilesInDirectory('{}'): adding {}", dirPath, dirFile.getAbsolutePath()); + + files.add(jarPath); + } catch (Exception excp) { + LOG.warn("getFilesInDirectory('{}'): failed to get URI for file {}", dirPath, dirFile.getAbsolutePath(), excp); + } + } + } + } catch (Exception excp) { + LOG.warn("getFilesInDirectory('{}'): error", dirPath, excp); + } + } else { + LOG.debug("getFilesInDirectory('{}'): could not find directory in CLASSPATH", dirPath); + } + + LOG.debug("<== ServiceMgr.getFilesInDirectory({})", dirPath); + } + + private VXResponse generateResponseForTestConn(Map responseData, String msg) { + VXResponse vXResponse = new VXResponse(); + + Long objId = null; + boolean connectivityStatus = false; + int statusCode = VXResponse.STATUS_ERROR; + String message = msg; + String description = msg; + String fieldName = null; + + if (responseData != null) { + if (responseData.get("objectId") != null) { + objId = Long.parseLong(responseData.get("objectId").toString()); + } + + if (responseData.get("connectivityStatus") != null) { + connectivityStatus = Boolean.parseBoolean(responseData.get("connectivityStatus").toString()); + } + + if (connectivityStatus) { + statusCode = VXResponse.STATUS_SUCCESS; + } + + if (responseData.get("message") != null) { + message = responseData.get("message").toString(); + } + + if (responseData.get("description") != null) { + description = responseData.get("description").toString(); + } + + if (responseData.get("fieldName") != null) { + fieldName = responseData.get("fieldName").toString(); + } + } + + VXMessage vXMsg = new VXMessage(); + List vXMsgList = new ArrayList<>(); + + vXMsg.setFieldName(fieldName); + vXMsg.setMessage(message); + vXMsg.setObjectId(objId); + vXMsgList.add(vXMsg); + + vXResponse.setMessageList(vXMsgList); + vXResponse.setMsgDesc(description); + vXResponse.setStatusCode(statusCode); + + return vXResponse; + } + + private boolean isUserOrUserGroupsInRole(String userId, Set userGroups, List roles) { + boolean ret = false; + RangerRoles rangerRoles = null; + + try { + rangerRoles = rolesStore.getRoles("", -1L); + } catch (Exception excp) { + LOG.error("Unexpected error when fetching roles from database", excp); + } + + if (rangerRoles != null) { + RangerRolesUtil rolesUtil = new RangerRolesUtil(rangerRoles); + Set userRoles = rolesUtil.getUserRoleMapping().get(userId); + + ret = userRoles != null && CollectionUtils.containsAny(roles, userRoles); + + if (!ret && userGroups != null) { + for (String userGroup : userGroups) { + Set groupRoles = rolesUtil.getGroupRoleMapping().get(userGroup); + + ret = groupRoles != null && CollectionUtils.containsAny(roles, groupRoles); + + if (ret) { + break; + } + } + } + } + + return ret; + } + + abstract static class TimedCallable implements Callable { + final RangerBaseService svc; + final Date creation; // NOTE: This would be different from when the callable was actually offered to the executor + + public TimedCallable(RangerBaseService svc) { + this.svc = svc; + this.creation = new Date(); + } + + @Override + public T call() throws Exception { + Date start = null; + + if (LOG.isDebugEnabled()) { + start = new Date(); + + LOG.debug("==> TimedCallable: {}", this); + } + + ClassLoader clsLoader = Thread.currentThread().getContextClassLoader(); + + try { + Thread.currentThread().setContextClassLoader(svc.getClass().getClassLoader()); + + return actualCall(); + } catch (Exception e) { + LOG.error("TimedCallable.call: Error:{}", String.valueOf(e)); + + throw e; + } finally { + Thread.currentThread().setContextClassLoader(clsLoader); + + if (LOG.isDebugEnabled()) { + Date finish = new Date(); + long waitTime = start.getTime() - creation.getTime(); + long executionTime = finish.getTime() - start.getTime(); + + LOG.debug("<== TimedCallable: {}: wait time[{} ms], execution time [{} ms]", this, waitTime, executionTime); + } + } + } + + abstract T actualCall() throws Exception; + } + + static class LookupCallable extends TimedCallable> { + final ResourceLookupContext context; + + public LookupCallable(final RangerBaseService svc, final ResourceLookupContext context) { + super(svc); + + this.context = context; + } + + @Override + public String toString() { + return String.format("lookup resource[%s] for service[%s], ", context.toString(), svc.getServiceName()); + } + + @Override + public List actualCall() throws Exception { + return svc.lookupResource(context); + } + } + + static class ValidateCallable extends TimedCallable> { + public ValidateCallable(RangerBaseService svc) { + super(svc); + } + + @Override + public String toString() { + return String.format("validate config for service[%s]", svc.getServiceName()); + } + + @Override + public Map actualCall() throws Exception { + return svc.validateConfig(); + } + } +} 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 index ed13c783e3..68874e86c0 100644 --- a/security-admin/src/main/java/org/apache/ranger/biz/SessionMgr.java +++ b/security-admin/src/main/java/org/apache/ranger/biz/SessionMgr.java @@ -17,18 +17,7 @@ * under the License. */ - package org.apache.ranger.biz; - -import java.util.ArrayList; -import java.util.Calendar; -import java.util.HashSet; -import java.util.List; -import java.util.Set; -import java.util.concurrent.CopyOnWriteArrayList; -import java.util.concurrent.CopyOnWriteArraySet; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpSession; +package org.apache.ranger.biz; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang.StringUtils; @@ -67,495 +56,494 @@ import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpSession; + +import java.util.ArrayList; +import java.util.Calendar; +import java.util.Date; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.CopyOnWriteArraySet; + @Component @Transactional public class SessionMgr { + static final Logger logger = LoggerFactory.getLogger(SessionMgr.class); + + private static final Long SESSION_UPDATE_INTERVAL_IN_MILLIS = 30 * DateUtils.MILLIS_PER_MINUTE; + + @Autowired + RESTErrorUtil restErrorUtil; + + @Autowired + RangerDaoManager daoManager; + + @Autowired + XUserMgr xUserMgr; + + @Autowired + AuthSessionService authSessionService; + + @Autowired + HTTPUtil httpUtil; + + @Autowired + StringUtil stringUtil; + + public SessionMgr() { + logger.debug("SessionManager created"); + } + + public UserSessionBase processSuccessLogin(int authType, String userAgent, HttpServletRequest httpRequest) { + boolean newSessionCreation = true; + UserSessionBase userSession = null; + RangerSecurityContext context = RangerContextHolder.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) { + getSSOSpnegoAuthCheckForAPI(currentLoginId, httpRequest); + + // 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)); + + HttpSession session = httpRequest.getSession(); + + if (session != null) { + if (session.getAttribute("auditLoginId") == null) { + synchronized (session) { + if (session.getAttribute("auditLoginId") == null) { + boolean isDownloadLogEnabled = PropertiesUtil.getBooleanProperty("ranger.downloadpolicy.session.log.enabled", false); + + if (isDownloadLogEnabled) { + gjAuthSession = storeAuthSession(gjAuthSession); + + session.setAttribute("auditLoginId", gjAuthSession.getId()); + } else if (!StringUtils.isEmpty(httpRequest.getRequestURI()) && !(httpRequest.getRequestURI().contains("/secure/policies/download/") || httpRequest.getRequestURI().contains("/secure/download/"))) { + gjAuthSession = storeAuthSession(gjAuthSession); + + session.setAttribute("auditLoginId", gjAuthSession.getId()); + } else if (StringUtils.isEmpty(httpRequest.getRequestURI())) { + gjAuthSession = storeAuthSession(gjAuthSession); + + session.setAttribute("auditLoginId", gjAuthSession.getId()); + } else { //NOPMD + //do not log the details for download policy and tag + } + } + } + } + } + + userSession = new UserSessionBase(); + + userSession.setXXPortalUser(gjUser); + userSession.setXXAuthSession(gjAuthSession); + + if (httpRequest.getAttribute("spnegoEnabled") != null && (boolean) httpRequest.getAttribute("spnegoEnabled")) { + userSession.setSpnegoEnabled(true); + } + + boolean ssoEnabled; + + if (authType == XXAuthSession.AUTH_TYPE_TRUSTED_PROXY) { + ssoEnabled = true; + } else { + Object ssoEnabledObj = httpRequest.getAttribute("ssoEnabled"); + + ssoEnabled = ssoEnabledObj != null ? Boolean.parseBoolean(String.valueOf(ssoEnabledObj)) : PropertiesUtil.getBooleanProperty("ranger.sso.enabled", false); + } + + logger.debug("session id = {} ssoenabled = {}", userSession.getLoginId(), ssoEnabled); + + userSession.setSSOEnabled(ssoEnabled); + + resetUserSessionForProfiles(userSession); + resetUserModulePermission(userSession); + + if (logger.isDebugEnabled()) { + Calendar cal = Calendar.getInstance(); + + if (details != null) { + logger.debug("Login Success: loginId={}, sessionId={}, sessionId={}, requestId={}, epoch={}", currentLoginId, gjAuthSession.getId(), details.getSessionId(), details.getRemoteAddress(), cal.getTimeInMillis()); + } else { + logger.debug("Login Success: loginId={}, sessionId={}, details is null, epoch={}", currentLoginId, gjAuthSession.getId(), cal.getTimeInMillis()); + } + } + } + + return userSession; + } + + public void resetUserModulePermission(UserSessionBase userSession) { + XXUser xUser = daoManager.getXXUser().findByUserName(userSession.getLoginId()); + + if (xUser != null) { + List permissionList = daoManager.getXXModuleDef().findAccessibleModulesByUserId(userSession.getUserId(), xUser.getId()); + CopyOnWriteArraySet userPermissions = new CopyOnWriteArraySet<>(permissionList); + UserSessionBase.RangerUserPermission rangerUserPermission = userSession.getRangerUserPermission(); + + if (rangerUserPermission == null) { + rangerUserPermission = new UserSessionBase.RangerUserPermission(); + } + + rangerUserPermission.setUserPermissions(userPermissions); + rangerUserPermission.setLastUpdatedTime(Calendar.getInstance().getTimeInMillis()); + userSession.setRangerUserPermission(rangerUserPermission); + + logger.debug("UserSession Updated to set new Permissions to User: {}", userSession.getLoginId()); + } else { + logger.error("No XUser found with username: {}So Permission is not set for the user", userSession.getLoginId()); + } + } + + 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); + } - static final Logger logger = LoggerFactory.getLogger(SessionMgr.class); - - @Autowired - RESTErrorUtil restErrorUtil; - - @Autowired - RangerDaoManager daoManager; - - @Autowired - XUserMgr xUserMgr; - - @Autowired - AuthSessionService authSessionService; - - @Autowired - HTTPUtil httpUtil; - - @Autowired - StringUtil stringUtil; - - public SessionMgr() { - logger.debug("SessionManager created"); - } - - private static final Long SESSION_UPDATE_INTERVAL_IN_MILLIS = 30 * DateUtils.MILLIS_PER_MINUTE; - - public UserSessionBase processSuccessLogin(int authType, String userAgent, - HttpServletRequest httpRequest) { - boolean newSessionCreation = true; - UserSessionBase userSession = null; - - RangerSecurityContext context = RangerContextHolder.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) { - - getSSOSpnegoAuthCheckForAPI(currentLoginId, httpRequest); - // 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)); - HttpSession session = httpRequest.getSession(); - if (session != null) { - if (session.getAttribute("auditLoginId") == null) { - synchronized (session) { - if (session.getAttribute("auditLoginId") == null) { - boolean isDownloadLogEnabled = PropertiesUtil.getBooleanProperty("ranger.downloadpolicy.session.log.enabled", false); - if (isDownloadLogEnabled){ - gjAuthSession = storeAuthSession(gjAuthSession); - session.setAttribute("auditLoginId", gjAuthSession.getId()); - } - else if (!StringUtils.isEmpty(httpRequest.getRequestURI()) && !(httpRequest.getRequestURI().contains("/secure/policies/download/") || httpRequest.getRequestURI().contains("/secure/download/"))){ - gjAuthSession = storeAuthSession(gjAuthSession); - session.setAttribute("auditLoginId", gjAuthSession.getId()); - }else if (StringUtils.isEmpty(httpRequest.getRequestURI())){ - gjAuthSession = storeAuthSession(gjAuthSession); - session.setAttribute("auditLoginId", gjAuthSession.getId()); - }else{ //NOPMD - //do not log the details for download policy and tag - } - } - } - } - } - - userSession = new UserSessionBase(); - userSession.setXXPortalUser(gjUser); - userSession.setXXAuthSession(gjAuthSession); - if(httpRequest.getAttribute("spnegoEnabled") != null && (boolean)httpRequest.getAttribute("spnegoEnabled")){ - userSession.setSpnegoEnabled(true); - } - - Boolean ssoEnabled; - if (authType == XXAuthSession.AUTH_TYPE_TRUSTED_PROXY) { - ssoEnabled = true; - } else { - Object ssoEnabledObj = httpRequest.getAttribute("ssoEnabled"); - ssoEnabled = ssoEnabledObj != null ? Boolean.valueOf(String.valueOf(ssoEnabledObj)) : PropertiesUtil.getBooleanProperty("ranger.sso.enabled", false); - } - - if (logger.isDebugEnabled()) { - logger.debug("session id = " + userSession.getLoginId() + " ssoenabled = " + ssoEnabled); - } - userSession.setSSOEnabled(ssoEnabled); - - resetUserSessionForProfiles(userSession); - resetUserModulePermission(userSession); - - Calendar cal = Calendar.getInstance(); - if(logger.isDebugEnabled()) { - if (details != null) { - logger.debug("Login Success: loginId=" + currentLoginId - + ", sessionId=" + gjAuthSession.getId() - + ", sessionId=" + details.getSessionId() - + ", requestId=" + details.getRemoteAddress() - + ", epoch=" + cal.getTimeInMillis()); - } else { - logger.debug("Login Success: loginId=" + currentLoginId - + ", sessionId=" + gjAuthSession.getId() - + ", details is null" - + ", epoch=" + cal.getTimeInMillis()); - } - } - - } - - return userSession; - } - - private void getSSOSpnegoAuthCheckForAPI(String currentLoginId, HttpServletRequest request) { - - RangerSecurityContext context = RangerContextHolder.getSecurityContext(); - UserSessionBase session = context != null ? context.getUserSession() : null; - boolean ssoEnabled = session != null ? session.isSSOEnabled() : PropertiesUtil.getBooleanProperty("ranger.sso.enabled", false); - - XXPortalUser gjUser = daoManager.getXXPortalUser().findByLoginId(currentLoginId); - if (gjUser == null && ((request.getAttribute("spnegoEnabled") != null && (boolean)request.getAttribute("spnegoEnabled")) || (ssoEnabled))) { - if(logger.isDebugEnabled()){ - logger.debug("User : "+currentLoginId+" doesn't exist in Ranger DB So creating user as it's SSO or Spnego authenticated"); - } - xUserMgr.createServiceConfigUser(currentLoginId); - } - } - - public void resetUserModulePermission(UserSessionBase userSession) { - - XXUser xUser = daoManager.getXXUser().findByUserName(userSession.getLoginId()); - if (xUser != null) { - List permissionList = daoManager.getXXModuleDef().findAccessibleModulesByUserId(userSession.getUserId(), xUser.getId()); - CopyOnWriteArraySet userPermissions = new CopyOnWriteArraySet(permissionList); - - UserSessionBase.RangerUserPermission rangerUserPermission = userSession.getRangerUserPermission(); - - if (rangerUserPermission == null) { - rangerUserPermission = new UserSessionBase.RangerUserPermission(); - } - - rangerUserPermission.setUserPermissions(userPermissions); - rangerUserPermission.setLastUpdatedTime(Calendar.getInstance().getTimeInMillis()); - userSession.setRangerUserPermission(rangerUserPermission); - if (logger.isDebugEnabled()) { - logger.debug("UserSession Updated to set new Permissions to User: " + userSession.getLoginId()); - } - } else { - logger.error("No XUser found with username: " + userSession.getLoginId() + "So Permission is not set for the user"); - } - } - - 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 strRoleList = new ArrayList(); - List roleList = daoManager.getXXPortalUserRole().findByUserId( - userSession.getUserId()); - for (XXPortalUserRole gjUserRole : roleList) { - String userRole = gjUserRole.getUserRole(); - strRoleList.add(userRole); - } - - if (strRoleList.contains(RangerConstants.ROLE_SYS_ADMIN)) { - userSession.setUserAdmin(true); - userSession.setKeyAdmin(false); + public XXAuthSession processFailureLogin(int authStatus, int authType, String loginId, String remoteAddr, String sessionId, String userAgent) { + XXAuthSession gjAuthSession = new XXAuthSession(); + + gjAuthSession.setLoginId(loginId); + gjAuthSession.setUserId(null); + gjAuthSession.setAuthTime(DateUtil.getUTCDate()); + gjAuthSession.setAuthStatus(authStatus); + gjAuthSession.setAuthType(authType); + gjAuthSession.setDeviceType(RangerCommonEnums.DEVICE_UNKNOWN); + gjAuthSession.setExtSessionId(sessionId); + gjAuthSession.setRequestIP(remoteAddr); + gjAuthSession.setRequestUserAgent(userAgent); + + gjAuthSession = storeAuthSession(gjAuthSession); + + return gjAuthSession; + } + + // non-WEB processing + public UserSessionBase processStandaloneSuccessLogin(int authType, String ipAddress) { + Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); + String currentLoginId = authentication.getName(); + XXPortalUser gjUser = daoManager.getXXPortalUser().findByLoginId(currentLoginId); // Need to build the UserSession + + 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(RangerCommonEnums.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 + RangerSecurityContext context = new RangerSecurityContext(); + + context.setUserSession(userSession); + + RangerContextHolder.setSecurityContext(context); + + resetUserSessionForProfiles(userSession); + resetUserModulePermission(userSession); + + return userSession; + } + + /** + * @param searchCriteria + * @return + */ + public VXAuthSessionList searchAuthSessions(SearchCriteria searchCriteria) { + if (searchCriteria == null) { + searchCriteria = new SearchCriteria(); + } + + if (searchCriteria.getParamList() != null && !searchCriteria.getParamList().isEmpty()) { + int clientTimeOffsetInMinute = RestUtil.getClientTimeOffset(); + DateUtil dateUtil = new DateUtil(); + + if (searchCriteria.getParamList().containsKey("startDate")) { + Date temp = (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")) { + Date temp = (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); + } + + return authSessionService.populateViewBean(xXAuthSession); + } + + /** + * Check whether the user failed to log in so many times that we need to lock it for + * a while. The current limit of is to fail at most n times in a sliding time window, + * otherwise the login verification will not be performed in the future. + * + * @param loginId + * @return + */ + public boolean isLoginIdLocked(String loginId) { + boolean ret = false; + boolean autoLockEnabled = PropertiesUtil.getBooleanProperty("ranger.admin.login.autolock.enabled", true); + + if (autoLockEnabled) { + int windowSeconds = PropertiesUtil.getIntProperty("ranger.admin.login.autolock.window.seconds", 300); + int maxFailuresCount = PropertiesUtil.getIntProperty("ranger.admin.login.autolock.maxfailure", 5); + long failuresCount = daoManager.getXXAuthSession().getRecentAuthFailureCountByLoginId(loginId, windowSeconds); + + ret = failuresCount >= maxFailuresCount; + + logger.debug("isLoginIdLocked(loginId={}): windowSeconds={}, maxFailuresCount={}, failuresCount={}, ret={}", loginId, windowSeconds, maxFailuresCount, failuresCount, ret); + } + + return ret; + } + + public boolean isValidXAUser(String loginId) { + XXPortalUser pUser = daoManager.getXXPortalUser().findByLoginId(loginId); + + if (pUser == null || pUser.getUserSource() == RangerCommonEnums.USER_FEDERATED) { + logger.error("Error getting user for loginId={} or federated user", loginId); + + return false; + } else { + logger.debug("{} is a valid user", loginId); + + return true; + } + } + + public CopyOnWriteArrayList getActiveSessionsOnServer() { + CopyOnWriteArrayList activeHttpUserSessions = RangerHttpSessionListener.getActiveSessionOnServer(); + CopyOnWriteArrayList activeRangerUserSessions = new CopyOnWriteArrayList<>(); + + if (CollectionUtils.isEmpty(activeHttpUserSessions)) { + return activeRangerUserSessions; + } + + for (HttpSession httpSession : activeHttpUserSessions) { + if (httpSession.getAttribute(RangerSecurityContextFormationFilter.AKA_SC_SESSION_KEY) == null) { + continue; + } + + RangerSecurityContext securityContext = (RangerSecurityContext) httpSession.getAttribute(RangerSecurityContextFormationFilter.AKA_SC_SESSION_KEY); + + if (securityContext.getUserSession() != null) { + activeRangerUserSessions.add(securityContext.getUserSession()); + } + } + + return activeRangerUserSessions; + } + + public Set getActiveUserSessionsForPortalUserId(Long portalUserId) { + CopyOnWriteArrayList activeSessions = getActiveSessionsOnServer(); + + if (CollectionUtils.isEmpty(activeSessions)) { + return null; + } + + Set activeUserSessions = new HashSet<>(); + + for (UserSessionBase session : activeSessions) { + if (session.getUserId().equals(portalUserId)) { + activeUserSessions.add(session); + } + } + + logger.debug("No Session Found with portalUserId: {}", portalUserId); + + return activeUserSessions; + } + + public Set getActiveUserSessionsForXUserId(Long xUserId) { + XXPortalUser portalUser = daoManager.getXXPortalUser().findByXUserId(xUserId); + + if (portalUser != null) { + return getActiveUserSessionsForPortalUserId(portalUser.getId()); + } else { + logger.debug("Could not find corresponding portalUser for xUserId{}", xUserId); + + return null; + } + } + + public synchronized void refreshPermissionsIfNeeded(UserSessionBase userSession) { + if (userSession != null) { + Long lastUpdatedTime = (userSession.getRangerUserPermission() != null) ? userSession.getRangerUserPermission().getLastUpdatedTime() : null; + + if (lastUpdatedTime == null || (Calendar.getInstance().getTimeInMillis() - lastUpdatedTime) > SESSION_UPDATE_INTERVAL_IN_MILLIS) { + this.resetUserModulePermission(userSession); + } + } + } + + protected boolean validateUserSession(UserSessionBase userSession, String currentLoginId) { + if (currentLoginId.equalsIgnoreCase(userSession.getXXPortalUser().getLoginId())) { + return true; + } else { + logger.warn("loginId doesn't match loginId from HTTPSession. Will create new session. loginId={}, userSession={}", currentLoginId, 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; + } + + private void getSSOSpnegoAuthCheckForAPI(String currentLoginId, HttpServletRequest request) { + RangerSecurityContext context = RangerContextHolder.getSecurityContext(); + UserSessionBase session = context != null ? context.getUserSession() : null; + boolean ssoEnabled = session != null ? session.isSSOEnabled() : PropertiesUtil.getBooleanProperty("ranger.sso.enabled", false); + XXPortalUser gjUser = daoManager.getXXPortalUser().findByLoginId(currentLoginId); + + if (gjUser == null && ((request.getAttribute("spnegoEnabled") != null && (boolean) request.getAttribute("spnegoEnabled")) || (ssoEnabled))) { + logger.debug("User : {} doesn't exist in Ranger DB So creating user as it's SSO or Spnego authenticated", currentLoginId); + + xUserMgr.createServiceConfigUser(currentLoginId); + } + } + + private void setUserRoles(UserSessionBase userSession) { + List strRoleList = new ArrayList<>(); + List roleList = daoManager.getXXPortalUserRole().findByUserId(userSession.getUserId()); + + for (XXPortalUserRole gjUserRole : roleList) { + String userRole = gjUserRole.getUserRole(); + + strRoleList.add(userRole); + } + + if (strRoleList.contains(RangerConstants.ROLE_SYS_ADMIN)) { + userSession.setUserAdmin(true); + userSession.setKeyAdmin(false); userSession.setAuditUserAdmin(false); userSession.setAuditKeyAdmin(false); - } else if (strRoleList.contains(RangerConstants.ROLE_KEY_ADMIN)) { - userSession.setKeyAdmin(true); - userSession.setUserAdmin(false); + } else if (strRoleList.contains(RangerConstants.ROLE_KEY_ADMIN)) { + userSession.setKeyAdmin(true); + userSession.setUserAdmin(false); userSession.setAuditUserAdmin(false); userSession.setAuditKeyAdmin(false); - } else if (strRoleList.size() == 1 && RangerConstants.ROLE_USER.equals(strRoleList.get(0))) { - userSession.setKeyAdmin(false); - userSession.setUserAdmin(false); - userSession.setAuditUserAdmin(false); - userSession.setAuditKeyAdmin(false); - } else if (strRoleList.contains(RangerConstants.ROLE_ADMIN_AUDITOR)) { - userSession.setAuditUserAdmin(true); - userSession.setAuditKeyAdmin(false); - userSession.setKeyAdmin(false); - userSession.setUserAdmin(false); - } else if (strRoleList.contains(RangerConstants.ROLE_KEY_ADMIN_AUDITOR)) { - userSession.setAuditKeyAdmin(true); - userSession.setAuditUserAdmin(false); - userSession.setKeyAdmin(false); - userSession.setUserAdmin(false); - } - - userSession.setUserRoleList(strRoleList); - } - - public XXAuthSession processFailureLogin(int authStatus, int authType, - String loginId, String remoteAddr, String sessionId, String userAgent) { - XXAuthSession gjAuthSession = new XXAuthSession(); - gjAuthSession.setLoginId(loginId); - gjAuthSession.setUserId(null); - gjAuthSession.setAuthTime(DateUtil.getUTCDate()); - gjAuthSession.setAuthStatus(authStatus); - gjAuthSession.setAuthType(authType); - gjAuthSession.setDeviceType(RangerCommonEnums.DEVICE_UNKNOWN); - gjAuthSession.setExtSessionId(sessionId); - gjAuthSession.setRequestIP(remoteAddr); - gjAuthSession.setRequestUserAgent(userAgent); - - gjAuthSession = storeAuthSession(gjAuthSession); - return gjAuthSession; - } - - protected boolean validateUserSession(UserSessionBase userSession, - String currentLoginId) { - if (currentLoginId - .equalsIgnoreCase(userSession.getXXPortalUser().getLoginId())) { - return true; - } else { - logger.warn( - "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(RangerCommonEnums.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 - RangerSecurityContext context = new RangerSecurityContext(); - context.setUserSession(userSession); - RangerContextHolder.setSecurityContext(context); - - resetUserSessionForProfiles(userSession); - resetUserModulePermission(userSession); - - return userSession; - } - - /** - * @param searchCriteria - * @return - */ - public VXAuthSessionList searchAuthSessions(SearchCriteria searchCriteria) { - - if (searchCriteria == null) { - searchCriteria = new SearchCriteria(); - } - if (searchCriteria.getParamList() != null - && !searchCriteria.getParamList().isEmpty()) { - - 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; - } - - /** - * Check whether the user failed to log in so many times that we need to lock it for - * a while. The current limit of is to fail at most n times in a sliding time window, - * otherwise the login verification will not be performed in the future. - * @param loginId - * @return - */ - public boolean isLoginIdLocked(String loginId) { - boolean ret = false; - boolean autoLockEnabled = PropertiesUtil.getBooleanProperty("ranger.admin.login.autolock.enabled", true); - - if (autoLockEnabled) { - int windowSeconds = PropertiesUtil.getIntProperty("ranger.admin.login.autolock.window.seconds", 300); - int maxFailuresCount = PropertiesUtil.getIntProperty("ranger.admin.login.autolock.maxfailure", 5); - long failuresCount = daoManager.getXXAuthSession().getRecentAuthFailureCountByLoginId(loginId, windowSeconds); - - ret = failuresCount >= maxFailuresCount; - - if (logger.isDebugEnabled()) { - logger.debug("isLoginIdLocked(loginId={}): windowSeconds={}, maxFailuresCount={}, failuresCount={}, ret={}", loginId, windowSeconds, maxFailuresCount, failuresCount, ret); - } - } - - return ret; - } - - public boolean isValidXAUser(String loginId) { - XXPortalUser pUser = daoManager.getXXPortalUser().findByLoginId(loginId); - if (pUser == null || pUser.getUserSource() == RangerCommonEnums.USER_FEDERATED) { - logger.error("Error getting user for loginId=" + loginId + " or federated user"); - return false; - } else { - if(logger.isDebugEnabled()) { - logger.debug(loginId + " is a valid user"); - } - return true; - } - - } - - public CopyOnWriteArrayList getActiveSessionsOnServer() { - - CopyOnWriteArrayList activeHttpUserSessions = RangerHttpSessionListener.getActiveSessionOnServer(); - CopyOnWriteArrayList activeRangerUserSessions = new CopyOnWriteArrayList(); - - if (CollectionUtils.isEmpty(activeHttpUserSessions)) { - return activeRangerUserSessions; - } - - for (HttpSession httpSession : activeHttpUserSessions) { - - if (httpSession.getAttribute(RangerSecurityContextFormationFilter.AKA_SC_SESSION_KEY) == null) { - continue; - } - - RangerSecurityContext securityContext = (RangerSecurityContext) httpSession.getAttribute(RangerSecurityContextFormationFilter.AKA_SC_SESSION_KEY); - if (securityContext.getUserSession() != null) { - activeRangerUserSessions.add(securityContext.getUserSession()); - } - } - - return activeRangerUserSessions; - } - - public Set getActiveUserSessionsForPortalUserId(Long portalUserId) { - CopyOnWriteArrayList activeSessions = getActiveSessionsOnServer(); - - if (CollectionUtils.isEmpty(activeSessions)) { - return null; - } - - Set activeUserSessions = new HashSet(); - for (UserSessionBase session : activeSessions) { - if (session.getUserId().equals(portalUserId)) { - activeUserSessions.add(session); - } - } - if (logger.isDebugEnabled()) { - logger.debug("No Session Found with portalUserId: " + portalUserId); - } - return activeUserSessions; - } - - public Set getActiveUserSessionsForXUserId(Long xUserId) { - XXPortalUser portalUser = daoManager.getXXPortalUser().findByXUserId(xUserId); - if (portalUser != null) { - return getActiveUserSessionsForPortalUserId(portalUser.getId()); - } else { - if (logger.isDebugEnabled()) { - logger.debug("Could not find corresponding portalUser for xUserId" + xUserId); - } - return null; - } - } - - public synchronized void refreshPermissionsIfNeeded(UserSessionBase userSession) { - if (userSession != null) { - Long lastUpdatedTime = (userSession.getRangerUserPermission() != null) ? userSession.getRangerUserPermission().getLastUpdatedTime() : null; - if (lastUpdatedTime == null || (Calendar.getInstance().getTimeInMillis() - lastUpdatedTime) > SESSION_UPDATE_INTERVAL_IN_MILLIS) { - this.resetUserModulePermission(userSession); - } - } - } + } else if (strRoleList.size() == 1 && RangerConstants.ROLE_USER.equals(strRoleList.get(0))) { + userSession.setKeyAdmin(false); + userSession.setUserAdmin(false); + userSession.setAuditUserAdmin(false); + userSession.setAuditKeyAdmin(false); + } else if (strRoleList.contains(RangerConstants.ROLE_ADMIN_AUDITOR)) { + userSession.setAuditUserAdmin(true); + userSession.setAuditKeyAdmin(false); + userSession.setKeyAdmin(false); + userSession.setUserAdmin(false); + } else if (strRoleList.contains(RangerConstants.ROLE_KEY_ADMIN_AUDITOR)) { + userSession.setAuditKeyAdmin(true); + userSession.setAuditUserAdmin(false); + userSession.setKeyAdmin(false); + userSession.setUserAdmin(false); + } + userSession.setUserRoleList(strRoleList); + } } diff --git a/security-admin/src/main/java/org/apache/ranger/biz/TagDBStore.java b/security-admin/src/main/java/org/apache/ranger/biz/TagDBStore.java index 9134e39884..f7b750aba4 100755 --- a/security-admin/src/main/java/org/apache/ranger/biz/TagDBStore.java +++ b/security-admin/src/main/java/org/apache/ranger/biz/TagDBStore.java @@ -19,14 +19,6 @@ package org.apache.ranger.biz; -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 com.fasterxml.jackson.core.JsonProcessingException; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang.StringUtils; @@ -46,8 +38,13 @@ import org.apache.ranger.entity.XXTagChangeLog; import org.apache.ranger.entity.XXTagDef; import org.apache.ranger.entity.XXTagResourceMap; -import org.apache.ranger.plugin.model.*; import org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyResource; +import org.apache.ranger.plugin.model.RangerServiceDef; +import org.apache.ranger.plugin.model.RangerServiceResource; +import org.apache.ranger.plugin.model.RangerTag; +import org.apache.ranger.plugin.model.RangerTagDef; +import org.apache.ranger.plugin.model.RangerTagResourceMap; +import org.apache.ranger.plugin.model.RangerValiditySchedule; import org.apache.ranger.plugin.model.validation.RangerValidityScheduleValidator; import org.apache.ranger.plugin.model.validation.ValidationFailureDetails; import org.apache.ranger.plugin.store.AbstractTagStore; @@ -59,12 +56,12 @@ import org.apache.ranger.plugin.util.RangerServiceTagsDeltaUtil; import org.apache.ranger.plugin.util.SearchFilter; import org.apache.ranger.plugin.util.ServiceTags; +import org.apache.ranger.service.RangerServiceResourceService; +import org.apache.ranger.service.RangerServiceResourceWithTagsService; import org.apache.ranger.service.RangerTagDefService; import org.apache.ranger.service.RangerTagResourceMapService; import org.apache.ranger.service.RangerTagService; import org.apache.ranger.view.RangerServiceResourceWithTagsList; -import org.apache.ranger.service.RangerServiceResourceService; -import org.apache.ranger.service.RangerServiceResourceWithTagsService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -75,1402 +72,1179 @@ import javax.annotation.PostConstruct; import javax.servlet.http.HttpServletResponse; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + @Component public class TagDBStore extends AbstractTagStore { - private static final Logger LOG = LoggerFactory.getLogger(TagDBStore.class); - private static final Logger PERF_LOG = RangerPerfTracer.getPerfLogger("db.TagDBStore"); + private static final Logger LOG = LoggerFactory.getLogger(TagDBStore.class); + private static final Logger PERF_LOG = RangerPerfTracer.getPerfLogger("db.TagDBStore"); + + public static boolean SUPPORTS_IN_PLACE_TAG_UPDATES; + + private static boolean SUPPORTS_TAG_DELTAS; + private static boolean IS_SUPPORTS_TAG_DELTAS_INITIALIZED; + private static boolean SUPPORTS_TAGS_DEDUP_INITIALIZED; + private static boolean SUPPORTS_TAGS_DEDUP; + + @Autowired + RangerTagDefService rangerTagDefService; + + @Autowired + RangerTagService rangerTagService; + @Autowired + RangerServiceResourceService rangerServiceResourceService; - private static boolean SUPPORTS_TAG_DELTAS = false; - private static boolean IS_SUPPORTS_TAG_DELTAS_INITIALIZED = false; - public static boolean SUPPORTS_IN_PLACE_TAG_UPDATES = false; + @Autowired + RangerServiceResourceWithTagsService rangerServiceResourceWithTagsService; - @Autowired - RangerTagDefService rangerTagDefService; + @Autowired + RangerTagResourceMapService rangerTagResourceMapService; - @Autowired - RangerTagService rangerTagService; + @Autowired + RangerDaoManager daoManager; + + @Autowired + @Qualifier(value = "transactionManager") + PlatformTransactionManager txManager; + + @Autowired + RESTErrorUtil errorUtil; + + @Autowired + RESTErrorUtil restErrorUtil; + RangerAdminConfig config; + + public static boolean isSupportsTagDeltas() { + initStatics(); + + return SUPPORTS_TAG_DELTAS; + } - @Autowired - RangerServiceResourceService rangerServiceResourceService; + public static RangerServiceResource toRangerServiceResource(String serviceName, Map resourceMap) { + LOG.debug("==> TagDBStore.toRangerServiceResource(): serviceName={{}}", serviceName); - @Autowired - RangerServiceResourceWithTagsService rangerServiceResourceWithTagsService; + Map resourceElements = new HashMap<>(); + + for (Map.Entry entry : resourceMap.entrySet()) { + String[] parts = entry.getKey().split("\\."); + String[] valueArray = entry.getValue(); + + if (parts.length < 1 || valueArray == null) { + continue; + } + + String key = parts[0]; + RangerPolicyResource policyResource = resourceElements.get(key); + + if (policyResource == null) { + policyResource = new RangerPolicyResource(); + + resourceElements.put(key, policyResource); + } + + if (parts.length == 1) { + List valueList = new ArrayList<>(valueArray.length); + + for (String str : valueArray) { + valueList.add(str.trim()); + } + + policyResource.setValues(valueList); + } else if (parts.length == 2 && valueArray[0] != null) { + String subKey = parts[1]; + String value = valueArray[0]; + + if (subKey.equalsIgnoreCase("isExcludes")) { + policyResource.setIsExcludes(Boolean.parseBoolean(value.trim())); + } else if (subKey.equalsIgnoreCase("isRecursive")) { + policyResource.setIsRecursive(Boolean.parseBoolean(value.trim())); + } + } + } + + RangerServiceResource ret = new RangerServiceResource(serviceName, resourceElements); + + LOG.debug("<== TagDBStore.toRangerServiceResource(): (serviceName={{}} RangerServiceResource={{}})", serviceName, ret); + + return ret; + } + + public static boolean isSupportsTagsDedup() { + if (!SUPPORTS_TAGS_DEDUP_INITIALIZED) { + RangerAdminConfig config = RangerAdminConfig.getInstance(); + + SUPPORTS_TAGS_DEDUP = config.getBoolean("ranger.admin" + RangerCommonConstants.RANGER_SUPPORTS_TAGS_DEDUP, RangerCommonConstants.RANGER_SUPPORTS_TAGS_DEDUP_DEFAULT); + SUPPORTS_TAGS_DEDUP_INITIALIZED = true; + } + return SUPPORTS_TAGS_DEDUP; + } + + @PostConstruct + public void initStore() { + config = RangerAdminConfig.getInstance(); + + RangerAdminTagEnricher.setTagStore(this); + RangerAdminTagEnricher.setDaoManager(daoManager); + } + + @Override + public RangerTagDef createTagDef(RangerTagDef tagDef) { + LOG.debug("==> TagDBStore.createTagDef({})", tagDef); + + RangerTagDef ret = rangerTagDefService.create(tagDef); + + ret = rangerTagDefService.read(ret.getId()); + + LOG.debug("<== TagDBStore.createTagDef({}): id={}", tagDef, ret == null ? null : ret.getId()); + + return ret; + } - @Autowired - RangerTagResourceMapService rangerTagResourceMapService; + @Override + public RangerTagDef updateTagDef(RangerTagDef tagDef) { + LOG.debug("==> TagDBStore.updateTagDef({})", tagDef); - @Autowired - RangerDaoManager daoManager; + RangerTagDef existing = rangerTagDefService.read(tagDef.getId()); - @Autowired - @Qualifier(value = "transactionManager") - PlatformTransactionManager txManager; + if (existing == null) { + throw errorUtil.createRESTException("failed to update tag-def [" + tagDef.getName() + "], Reason: No TagDef found with id: [" + tagDef.getId() + "]", MessageEnums.DATA_NOT_UPDATABLE); + } else if (!existing.getName().equals(tagDef.getName())) { + throw errorUtil.createRESTException("Cannot change tag-def name; existing-name:[" + existing.getName() + "], new-name:[" + tagDef.getName() + "]", MessageEnums.DATA_NOT_UPDATABLE); + } - @Autowired - RESTErrorUtil errorUtil; + tagDef.setCreatedBy(existing.getCreatedBy()); + tagDef.setCreateTime(existing.getCreateTime()); + tagDef.setGuid(existing.getGuid()); + tagDef.setVersion(existing.getVersion()); - @Autowired - RESTErrorUtil restErrorUtil; + RangerTagDef ret = rangerTagDefService.update(tagDef); - RangerAdminConfig config; + ret = rangerTagDefService.read(ret.getId()); - @PostConstruct - public void initStore() { - config = RangerAdminConfig.getInstance(); + LOG.debug("<== TagDBStore.updateTagDef({}): {}", tagDef, ret); - RangerAdminTagEnricher.setTagStore(this); - RangerAdminTagEnricher.setDaoManager(daoManager); - } + return ret; + } - @Override - public RangerTagDef createTagDef(RangerTagDef tagDef) throws Exception { - if (LOG.isDebugEnabled()) { - LOG.debug("==> TagDBStore.createTagDef(" + tagDef + ")"); - } + @Override + public void deleteTagDefByName(String name) throws Exception { + LOG.debug("==> TagDBStore.deleteTagDefByName({})", name); - RangerTagDef ret = rangerTagDefService.create(tagDef); + if (StringUtils.isNotBlank(name)) { + deleteTagDef(getTagDefByName(name)); + } - ret = rangerTagDefService.read(ret.getId()); + LOG.debug("<== TagDBStore.deleteTagDefByName({})", name); + } - if (LOG.isDebugEnabled()) { - LOG.debug("<== TagDBStore.createTagDef(" + tagDef + "): id=" + (ret == null ? null : ret.getId())); - } + @Override + public void deleteTagDef(Long id) throws Exception { + LOG.debug("==> TagDBStore.deleteTagDef({})", id); - return ret; - } + if (id != null) { + deleteTagDef(rangerTagDefService.read(id)); + } - @Override - public RangerTagDef updateTagDef(RangerTagDef tagDef) throws Exception { - if (LOG.isDebugEnabled()) { - LOG.debug("==> TagDBStore.updateTagDef(" + tagDef + ")"); - } + LOG.debug("<== TagDBStore.deleteTagDef({})", id); + } - RangerTagDef existing = rangerTagDefService.read(tagDef.getId()); + @Override + public RangerTagDef getTagDef(Long id) { + LOG.debug("==> TagDBStore.getTagDef({})", id); - if (existing == null) { - throw errorUtil.createRESTException("failed to update tag-def [" + tagDef.getName() + "], Reason: No TagDef found with id: [" + tagDef.getId() + "]", MessageEnums.DATA_NOT_UPDATABLE); - } else if (!existing.getName().equals(tagDef.getName())) { - throw errorUtil.createRESTException("Cannot change tag-def name; existing-name:[" + existing.getName() + "], new-name:[" + tagDef.getName() + "]", MessageEnums.DATA_NOT_UPDATABLE); - } + RangerTagDef ret = rangerTagDefService.read(id); - tagDef.setCreatedBy(existing.getCreatedBy()); - tagDef.setCreateTime(existing.getCreateTime()); - tagDef.setGuid(existing.getGuid()); - tagDef.setVersion(existing.getVersion()); + LOG.debug("<== TagDBStore.getTagDef({}): {}", id, ret); - RangerTagDef ret = rangerTagDefService.update(tagDef); + return ret; + } - ret = rangerTagDefService.read(ret.getId()); + @Override + public RangerTagDef getTagDefByGuid(String guid) { + LOG.debug("==> TagDBStore.getTagDefByGuid({})", guid); - if (LOG.isDebugEnabled()) { - LOG.debug("<== TagDBStore.updateTagDef(" + tagDef + "): " + ret); - } + RangerTagDef ret = rangerTagDefService.getTagDefByGuid(guid); - return ret; - } + LOG.debug("<== TagDBStore.getTagDefByGuid({}): {}", guid, ret); - @Override - public void deleteTagDefByName(String name) throws Exception { - if (LOG.isDebugEnabled()) { - LOG.debug("==> TagDBStore.deleteTagDefByName(" + name + ")"); - } + return ret; + } - if (StringUtils.isNotBlank(name)) { - deleteTagDef(getTagDefByName(name)); - } + @Override + public RangerTagDef getTagDefByName(String name) { + LOG.debug("==> TagDBStore.getTagDefByName({})", name); - if (LOG.isDebugEnabled()) { - LOG.debug("<== TagDBStore.deleteTagDefByName(" + name + ")"); - } - } + RangerTagDef ret = null; - @Override - public void deleteTagDef(Long id) throws Exception { - if (LOG.isDebugEnabled()) { - LOG.debug("==> TagDBStore.deleteTagDef(" + id + ")"); - } + if (StringUtils.isNotBlank(name)) { + ret = rangerTagDefService.getTagDefByName(name); + } - if(id != null) { - deleteTagDef(rangerTagDefService.read(id)); - } + LOG.debug("<== TagDBStore.getTagDefByName({}): {}", name, ret); - if (LOG.isDebugEnabled()) { - LOG.debug("<== TagDBStore.deleteTagDef(" + id + ")"); - } - } + return ret; + } - @Override - public RangerTagDef getTagDef(Long id) throws Exception { - if (LOG.isDebugEnabled()) { - LOG.debug("==> TagDBStore.getTagDef(" + id + ")"); - } + @Override + public List getTagDefs(SearchFilter filter) { + LOG.debug("==> TagDBStore.getTagDefs({})", filter); - RangerTagDef ret = rangerTagDefService.read(id); + List ret = getPaginatedTagDefs(filter).getList(); - if (LOG.isDebugEnabled()) { - LOG.debug("<== TagDBStore.getTagDef(" + id + "): " + ret); - } + LOG.debug("<== TagDBStore.getTagDefs({}): {}", filter, ret); - return ret; - } + return ret; + } - @Override - public RangerTagDef getTagDefByGuid(String guid) throws Exception { - if (LOG.isDebugEnabled()) { - LOG.debug("==> TagDBStore.getTagDefByGuid(" + guid + ")"); - } + @Override + public PList getPaginatedTagDefs(SearchFilter filter) { + LOG.debug("==> TagDBStore.getPaginatedTagDefs({})", filter); - RangerTagDef ret = rangerTagDefService.getTagDefByGuid(guid); + PList ret = rangerTagDefService.searchRangerTagDefs(filter); - if (LOG.isDebugEnabled()) { - LOG.debug("<== TagDBStore.getTagDefByGuid(" + guid + "): " + ret); - } + LOG.debug("<== TagDBStore.getPaginatedTagDefs({}): {}", filter, ret); - return ret; - } + return ret; + } - @Override - public RangerTagDef getTagDefByName(String name) throws Exception { - if (LOG.isDebugEnabled()) { - LOG.debug("==> TagDBStore.getTagDefByName(" + name + ")"); - } + @Override + public List getTagTypes() { + LOG.debug("==> TagDBStore.getTagTypes()"); - RangerTagDef ret = null; + List ret = daoManager.getXXTagDef().getAllNames(); - if (StringUtils.isNotBlank(name)) { - ret = rangerTagDefService.getTagDefByName(name); - } + LOG.debug("<== TagDBStore.getTagTypes(): count={}", ret != null ? ret.size() : 0); - if (LOG.isDebugEnabled()) { - LOG.debug("<== TagDBStore.getTagDefByName(" + name + "): " + ret); - } + return ret; + } - return ret; - } + @Override + public RangerTag createTag(RangerTag tag) throws Exception { + LOG.debug("==> TagDBStore.createTag({})", tag); - @Override - public List getTagDefs(SearchFilter filter) throws Exception { - if (LOG.isDebugEnabled()) { - LOG.debug("==> TagDBStore.getTagDefs(" + filter + ")"); - } + tag = validateTag(tag); - List ret = getPaginatedTagDefs(filter).getList(); + RangerTag ret = rangerTagService.create(tag); - if (LOG.isDebugEnabled()) { - LOG.debug("<== TagDBStore.getTagDefs(" + filter + "): " + ret); - } + ret = rangerTagService.read(ret.getId()); - return ret; - } + LOG.debug("<== TagDBStore.createTag({}): {}", tag, ret); - @Override - public PList getPaginatedTagDefs(SearchFilter filter) throws Exception { - if (LOG.isDebugEnabled()) { - LOG.debug("==> TagDBStore.getPaginatedTagDefs(" + filter + ")"); - } + return ret; + } - PList ret = rangerTagDefService.searchRangerTagDefs(filter); + @Override + public RangerTag updateTag(RangerTag tag) throws Exception { + LOG.debug("==> TagDBStore.updateTag({})", tag); - if (LOG.isDebugEnabled()) { - LOG.debug("<== TagDBStore.getPaginatedTagDefs(" + filter + "): " + ret); - } + tag = validateTag(tag); - return ret; - } + RangerTag existing = rangerTagService.read(tag.getId()); - @Override - public List getTagTypes() throws Exception { - if (LOG.isDebugEnabled()) { - LOG.debug("==> TagDBStore.getTagTypes()"); - } + if (existing == null) { + throw errorUtil.createRESTException("failed to update tag [" + tag.getType() + "], Reason: No Tag found with id: [" + tag.getId() + "]", MessageEnums.DATA_NOT_UPDATABLE); + } - List ret = daoManager.getXXTagDef().getAllNames(); + tag.setCreatedBy(existing.getCreatedBy()); + tag.setCreateTime(existing.getCreateTime()); + tag.setGuid(existing.getGuid()); + tag.setVersion(existing.getVersion()); - if (LOG.isDebugEnabled()) { - LOG.debug("<== TagDBStore.getTagTypes(): count=" + (ret != null ? ret.size() : 0)); - } + RangerTag ret = rangerTagService.update(tag); - return ret; - } + ret = rangerTagService.read(ret.getId()); + LOG.debug("<== TagDBStore.updateTag({}) : {}", tag, ret); - @Override - public RangerTag createTag(RangerTag tag) throws Exception { - if (LOG.isDebugEnabled()) { - LOG.debug("==> TagDBStore.createTag(" + tag + ")"); - } + return ret; + } - tag = validateTag(tag); + @Override + public void deleteTag(Long id) { + LOG.debug("==> TagDBStore.deleteTag({})", id); - RangerTag ret = rangerTagService.create(tag); + RangerTag tag = rangerTagService.read(id); - ret = rangerTagService.read(ret.getId()); + rangerTagService.delete(tag); - if (LOG.isDebugEnabled()) { - LOG.debug("<== TagDBStore.createTag(" + tag + "): " + ret); - } + LOG.debug("<== TagDBStore.deleteTag({})", id); + } - return ret; - } - - @Override - public RangerTag updateTag(RangerTag tag) throws Exception { - if (LOG.isDebugEnabled()) { - LOG.debug("==> TagDBStore.updateTag(" + tag + ")"); - } + @Override + public RangerTag getTag(Long id) { + LOG.debug("==> TagDBStore.getTag({})", id); - tag = validateTag(tag); + RangerTag ret = rangerTagService.read(id); - RangerTag existing = rangerTagService.read(tag.getId()); + LOG.debug("<== TagDBStore.getTag({}): {}", id, ret); - if (existing == null) { - throw errorUtil.createRESTException("failed to update tag [" + tag.getType() + "], Reason: No Tag found with id: [" + tag.getId() + "]", MessageEnums.DATA_NOT_UPDATABLE); - } + return ret; + } - tag.setCreatedBy(existing.getCreatedBy()); - tag.setCreateTime(existing.getCreateTime()); - tag.setGuid(existing.getGuid()); - tag.setVersion(existing.getVersion()); + @Override + public RangerTag getTagByGuid(String guid) { + LOG.debug("==> TagDBStore.getTagByGuid({})", guid); - RangerTag ret = rangerTagService.update(tag); + RangerTag ret = rangerTagService.getTagByGuid(guid); - ret = rangerTagService.read(ret.getId()); + LOG.debug("<== TagDBStore.getTagByGuid({}): {}", guid, ret); - if (LOG.isDebugEnabled()) { - LOG.debug("<== TagDBStore.updateTag(" + tag + ") : " + ret); - } + return ret; + } - return ret; - } + @Override + public List getTagIdsForResourceId(Long resourceId) { + LOG.debug("==> TagDBStore.getTagIdsForResourceId({})", resourceId); - @Override - public void deleteTag(Long id) throws Exception { - if (LOG.isDebugEnabled()) { - LOG.debug("==> TagDBStore.deleteTag(" + id + ")"); - } + List ret = rangerTagResourceMapService.getTagIdsForResourceId(resourceId); - RangerTag tag = rangerTagService.read(id); + LOG.debug("<== TagDBStore.getTagIdsForResourceId({}): count={}", resourceId, ret == null ? 0 : ret.size()); - rangerTagService.delete(tag); + return ret; + } - if (LOG.isDebugEnabled()) { - LOG.debug("<== TagDBStore.deleteTag(" + id + ")"); - } - } + @Override + public List getTagsByType(String type) { + LOG.debug("==> TagDBStore.getTagsByType({})", type); - @Override - public RangerTag getTag(Long id) throws Exception { - if (LOG.isDebugEnabled()) { - LOG.debug("==> TagDBStore.getTag(" + id + ")"); - } + List ret = null; - RangerTag ret = rangerTagService.read(id); + if (StringUtils.isNotBlank(type)) { + ret = rangerTagService.getTagsByType(type); + } - if (LOG.isDebugEnabled()) { - LOG.debug("<== TagDBStore.getTag(" + id + "): " + ret); - } + LOG.debug("<== TagDBStore.getTagsByType({}): count={}", type, ret == null ? 0 : ret.size()); - return ret; - } + return ret; + } - @Override - public RangerTag getTagByGuid(String guid) throws Exception { - if (LOG.isDebugEnabled()) { - LOG.debug("==> TagDBStore.getTagByGuid(" + guid + ")"); - } + @Override + public List getTagsForResourceId(Long resourceId) { + LOG.debug("==> TagDBStore.getTagsForResourceId({})", resourceId); - RangerTag ret = rangerTagService.getTagByGuid(guid); + List ret = null; - if (LOG.isDebugEnabled()) { - LOG.debug("<== TagDBStore.getTagByGuid(" + guid + "): " + ret); - } + if (resourceId != null) { + ret = rangerTagService.getTagsForResourceId(resourceId); + } - return ret; - } + LOG.debug("<== TagDBStore.getTagsForResourceId({}): count={}", resourceId, ret == null ? 0 : ret.size()); - @Override - public List getTagsByType(String type) throws Exception { - if (LOG.isDebugEnabled()) { - LOG.debug("==> TagDBStore.getTagsByType(" + type + ")"); - } + return ret; + } - List ret = null; + @Override + public List getTagsForResourceGuid(String resourceGuid) { + LOG.debug("==> TagDBStore.getTagsForResourceGuid({})", resourceGuid); - if (StringUtils.isNotBlank(type)) { - ret = rangerTagService.getTagsByType(type); - } + List ret = null; - if (LOG.isDebugEnabled()) { - LOG.debug("<== TagDBStore.getTagsByType(" + type + "): count=" + (ret == null ? 0 : ret.size())); - } + if (resourceGuid != null) { + ret = rangerTagService.getTagsForResourceGuid(resourceGuid); + } - return ret; - } + LOG.debug("<== TagDBStore.getTagsForResourceGuid({}): count={}", resourceGuid, ret == null ? 0 : ret.size()); - @Override - public List getTagsForResourceId(Long resourceId) throws Exception { - if (LOG.isDebugEnabled()) { - LOG.debug("==> TagDBStore.getTagsForResourceId(" + resourceId + ")"); - } + return ret; + } - List ret = null; + @Override + public List getTags(SearchFilter filter) throws Exception { + LOG.debug("==> TagDBStore.getTags({})", filter); - if (resourceId != null) { - ret = rangerTagService.getTagsForResourceId(resourceId); - } + List ret = rangerTagService.searchRangerTags(filter).getList(); - if (LOG.isDebugEnabled()) { - LOG.debug("<== TagDBStore.getTagsForResourceId(" + resourceId + "): count=" + (ret == null ? 0 : ret.size())); - } + LOG.debug("<== TagDBStore.getTags({}): count={}", filter, ret == null ? 0 : ret.size()); - return ret; - } + return ret; + } - @Override - public List getTagsForResourceGuid(String resourceGuid) throws Exception { - if (LOG.isDebugEnabled()) { - LOG.debug("==> TagDBStore.getTagsForResourceGuid(" + resourceGuid + ")"); - } + @Override + public PList getPaginatedTags(SearchFilter filter) { + LOG.debug("==> TagDBStore.getPaginatedTags({})", filter); - List ret = null; + PList ret = rangerTagService.searchRangerTags(filter); - if (resourceGuid != null) { - ret = rangerTagService.getTagsForResourceGuid(resourceGuid); - } + LOG.debug("<== TagDBStore.getPaginatedTags({}): count={}", filter, ret == null ? 0 : ret.getPageSize()); - if (LOG.isDebugEnabled()) { - LOG.debug("<== TagDBStore.getTagsForResourceGuid(" + resourceGuid + "): count=" + (ret == null ? 0 : ret.size())); - } + return ret; + } - return ret; - } + @Override + public RangerServiceResource createServiceResource(RangerServiceResource resource) { + LOG.debug("==> TagDBStore.createServiceResource({})", resource); - @Override - public List getTags(SearchFilter filter) throws Exception { - if (LOG.isDebugEnabled()) { - LOG.debug("==> TagDBStore.getTags(" + filter + ")"); - } + if (StringUtils.isEmpty(resource.getResourceSignature())) { + RangerServiceResourceSignature serializer = new RangerServiceResourceSignature(resource); - List ret = rangerTagService.searchRangerTags(filter).getList(); + resource.setResourceSignature(serializer.getSignature()); + } - if (LOG.isDebugEnabled()) { - LOG.debug("<== TagDBStore.getTags(" + filter + "): count=" + (ret == null ? 0 : ret.size())); - } + RangerServiceResource ret = rangerServiceResourceService.create(resource); - return ret; - } + ret = rangerServiceResourceService.read(ret.getId()); - @Override - public PList getPaginatedTags(SearchFilter filter) throws Exception { - if (LOG.isDebugEnabled()) { - LOG.debug("==> TagDBStore.getPaginatedTags(" + filter + ")"); - } + LOG.debug("<== TagDBStore.createServiceResource({})", resource); - PList ret = rangerTagService.searchRangerTags(filter); + return ret; + } - if (LOG.isDebugEnabled()) { - LOG.debug("<== TagDBStore.getPaginatedTags(" + filter + "): count=" + (ret == null ? 0 : ret.getPageSize())); - } + @Override + public RangerServiceResource updateServiceResource(RangerServiceResource resource) { + LOG.debug("==> TagDBStore.updateResource({})", resource); - return ret; - } + RangerServiceResource existing = rangerServiceResourceService.read(resource.getId()); - public boolean resetTagCache(final String serviceName) { - if (LOG.isDebugEnabled()) { - LOG.debug("==> TagDBStore.resetTagCache({})", serviceName); + if (existing == null) { + throw errorUtil.createRESTException("failed to update tag [" + resource.getId() + "], Reason: No resource found with id: [" + resource.getId() + "]", MessageEnums.DATA_NOT_UPDATABLE); } - boolean ret = RangerServiceTagsCache.getInstance().resetCache(serviceName); + if (StringUtils.isEmpty(resource.getResourceSignature())) { + RangerServiceResourceSignature serializer = new RangerServiceResourceSignature(resource); - if (LOG.isDebugEnabled()) { - LOG.debug("<== TagDBStore.resetTagCache(): ret={}", ret); + resource.setResourceSignature(serializer.getSignature()); } + resource.setCreatedBy(existing.getCreatedBy()); + resource.setCreateTime(existing.getCreateTime()); + resource.setGuid(existing.getGuid()); + resource.setVersion(existing.getVersion()); + + rangerServiceResourceService.update(resource); + + RangerServiceResource ret = rangerServiceResourceService.read(existing.getId()); + + LOG.debug("<== TagDBStore.updateResource({}) : {}", resource, ret); + return ret; } - @Override - public RangerServiceResource createServiceResource(RangerServiceResource resource) throws Exception { - if (LOG.isDebugEnabled()) { - LOG.debug("==> TagDBStore.createServiceResource(" + resource + ")"); - } + @Override + public void refreshServiceResource(Long resourceId) { + XXServiceResource serviceResourceEntity = daoManager.getXXServiceResource().getById(resourceId); + String tagsText = null; + + List tagResourceMaps = getTagResourceMapsForResourceId(resourceId); + if (tagResourceMaps != null) { + List associatedTags = new ArrayList<>(); + for (RangerTagResourceMap element : tagResourceMaps) { + associatedTags.add(getTag(element.getTagId())); + } + tagsText = JsonUtils.listToJson(associatedTags); + } + serviceResourceEntity.setTags(tagsText); + daoManager.getXXServiceResource().update(serviceResourceEntity); + } - if (StringUtils.isEmpty(resource.getResourceSignature())) { - RangerServiceResourceSignature serializer = new RangerServiceResourceSignature(resource); + @Override + public void deleteServiceResource(Long id) { + LOG.debug("==> TagDBStore.deleteServiceResource({})", id); - resource.setResourceSignature(serializer.getSignature()); - } + RangerServiceResource resource = getServiceResource(id); - RangerServiceResource ret = rangerServiceResourceService.create(resource); + if (resource != null) { + rangerServiceResourceService.delete(resource); + } - ret = rangerServiceResourceService.read(ret.getId()); + LOG.debug("<== TagDBStore.deleteServiceResource({})", id); + } - if (LOG.isDebugEnabled()) { - LOG.debug("<== TagDBStore.createServiceResource(" + resource + ")"); - } + @Override + public void deleteServiceResourceByGuid(String guid) { + LOG.debug("==> TagDBStore.deleteServiceResourceByGuid({})", guid); - return ret; - } + RangerServiceResource resource = getServiceResourceByGuid(guid); - @Override - public RangerServiceResource updateServiceResource(RangerServiceResource resource) throws Exception { - if (LOG.isDebugEnabled()) { - LOG.debug("==> TagDBStore.updateResource(" + resource + ")"); - } + if (resource != null) { + rangerServiceResourceService.delete(resource); + } - RangerServiceResource existing = rangerServiceResourceService.read(resource.getId()); + LOG.debug("<== TagDBStore.deleteServiceResourceByGuid({})", guid); + } - if (existing == null) { - throw errorUtil.createRESTException("failed to update tag [" + resource.getId() + "], Reason: No resource found with id: [" + resource.getId() + "]", MessageEnums.DATA_NOT_UPDATABLE); - } + @Override + public RangerServiceResource getServiceResource(Long id) { + LOG.debug("==> TagDBStore.getServiceResource({})", id); - if (StringUtils.isEmpty(resource.getResourceSignature())) { - RangerServiceResourceSignature serializer = new RangerServiceResourceSignature(resource); + RangerServiceResource ret = rangerServiceResourceService.read(id); - resource.setResourceSignature(serializer.getSignature()); - } + LOG.debug("<== TagDBStore.getServiceResource({}): {}", id, ret); - resource.setCreatedBy(existing.getCreatedBy()); - resource.setCreateTime(existing.getCreateTime()); - resource.setGuid(existing.getGuid()); - resource.setVersion(existing.getVersion()); + return ret; + } - rangerServiceResourceService.update(resource); + @Override + public RangerServiceResource getServiceResourceByGuid(String guid) { + LOG.debug("==> TagDBStore.getServiceResourceByGuid({})", guid); - RangerServiceResource ret = rangerServiceResourceService.read(existing.getId()); + RangerServiceResource ret = rangerServiceResourceService.getServiceResourceByGuid(guid); - if (LOG.isDebugEnabled()) { - LOG.debug("<== TagDBStore.updateResource(" + resource + ") : " + ret); - } + LOG.debug("<== TagDBStore.getServiceResourceByGuid({}): {}", guid, ret); - return ret; - } + return ret; + } + @Override + public List getServiceResourcesByService(String serviceName) { + LOG.debug("==> TagDBStore.getServiceResourcesByService({})", serviceName); - @Override - public void refreshServiceResource(Long resourceId) throws Exception { - XXServiceResource serviceResourceEntity = daoManager.getXXServiceResource().getById(resourceId); - String tagsText = null; + List ret = null; - List tagResourceMaps = getTagResourceMapsForResourceId(resourceId); - if (tagResourceMaps != null) { - List associatedTags = new ArrayList<>(); - for (RangerTagResourceMap element : tagResourceMaps) { - associatedTags.add(getTag(element.getTagId())); - } - tagsText = JsonUtils.listToJson(associatedTags); - } - serviceResourceEntity.setTags(tagsText); - daoManager.getXXServiceResource().update(serviceResourceEntity); - } + Long serviceId = daoManager.getXXService().findIdByName(serviceName); - @Override - public void deleteServiceResource(Long id) throws Exception { - if (LOG.isDebugEnabled()) { - LOG.debug("==> TagDBStore.deleteServiceResource(" + id + ")"); - } + if (serviceId != null) { + ret = rangerServiceResourceService.getByServiceId(serviceId); + } - RangerServiceResource resource = getServiceResource(id); + LOG.debug("<== TagDBStore.getServiceResourcesByService({}): count={}", serviceName, ret == null ? 0 : ret.size()); - if(resource != null) { - rangerServiceResourceService.delete(resource); - } + return ret; + } - if (LOG.isDebugEnabled()) { - LOG.debug("<== TagDBStore.deleteServiceResource(" + id + ")"); - } - } + @Override + public List getServiceResourceGuidsByService(String serviceName) { + LOG.debug("==> TagDBStore.getServiceResourceGuidsByService({})", serviceName); - @Override - public void deleteServiceResourceByGuid(String guid) throws Exception { - if (LOG.isDebugEnabled()) { - LOG.debug("==> TagDBStore.deleteServiceResourceByGuid(" + guid + ")"); - } + List ret = null; - RangerServiceResource resource = getServiceResourceByGuid(guid); + Long serviceId = daoManager.getXXService().findIdByName(serviceName); - if(resource != null) { - rangerServiceResourceService.delete(resource); - } + if (serviceId != null) { + ret = daoManager.getXXServiceResource().findServiceResourceGuidsInServiceId(serviceId); + } - if (LOG.isDebugEnabled()) { - LOG.debug("<== TagDBStore.deleteServiceResourceByGuid(" + guid + ")"); - } - } + LOG.debug("<== TagDBStore.getServiceResourceGuidsByService({}): count={}", serviceName, ret == null ? 0 : ret.size()); - @Override - public RangerServiceResource getServiceResource(Long id) throws Exception { - if (LOG.isDebugEnabled()) { - LOG.debug("==> TagDBStore.getServiceResource(" + id + ")"); - } + return ret; + } - RangerServiceResource ret = rangerServiceResourceService.read(id); + @Override + public RangerServiceResource getServiceResourceByServiceAndResourceSignature(String serviceName, String resourceSignature) { + LOG.debug("==> TagDBStore.getServiceResourceByServiceAndResourceSignature({}, {})", serviceName, resourceSignature); - if (LOG.isDebugEnabled()) { - LOG.debug("<== TagDBStore.getServiceResource(" + id + "): " + ret); - } + RangerServiceResource ret = null; - return ret; - } + Long serviceId = daoManager.getXXService().findIdByName(serviceName); - @Override - public RangerServiceResource getServiceResourceByGuid(String guid) throws Exception { - if (LOG.isDebugEnabled()) { - LOG.debug("==> TagDBStore.getServiceResourceByGuid(" + guid + ")"); - } + if (serviceId != null) { + ret = rangerServiceResourceService.getByServiceAndResourceSignature(serviceId, resourceSignature); + } - RangerServiceResource ret = rangerServiceResourceService.getServiceResourceByGuid(guid); + LOG.debug("<== TagDBStore.getServiceResourceByServiceAndResourceSignature({}, {}): {}", serviceName, resourceSignature, ret); - if (LOG.isDebugEnabled()) { - LOG.debug("<== TagDBStore.getServiceResourceByGuid(" + guid + "): " + ret); - } + return ret; + } - return ret; - } + @Override + public List getServiceResources(SearchFilter filter) { + LOG.debug("==> TagDBStore.getServiceResources({})", filter); - @Override - public List getServiceResourcesByService(String serviceName) throws Exception { - if (LOG.isDebugEnabled()) { - LOG.debug("==> TagDBStore.getServiceResourcesByService(" + serviceName + ")"); - } + List ret = rangerServiceResourceService.searchServiceResources(filter).getList(); - List ret = null; + LOG.debug("<== TagDBStore.getServiceResources({}): count={}", filter, ret == null ? 0 : ret.size()); - Long serviceId = daoManager.getXXService().findIdByName(serviceName); + return ret; + } - if (serviceId != null) { - ret = rangerServiceResourceService.getByServiceId(serviceId); - } + @Override + public PList getPaginatedServiceResources(SearchFilter filter) { + LOG.debug("==> TagDBStore.getPaginatedServiceResources({})", filter); - if (LOG.isDebugEnabled()) { - LOG.debug("<== TagDBStore.getServiceResourcesByService(" + serviceName + "): count=" + (ret == null ? 0 : ret.size())); - } + PList ret = rangerServiceResourceService.searchServiceResources(filter); - return ret; - } + LOG.debug("<== TagDBStore.getPaginatedServiceResources({}): count={}", filter, ret == null ? 0 : ret.getPageSize()); - @Override - public List getServiceResourceGuidsByService(String serviceName) { - if (LOG.isDebugEnabled()) { - LOG.debug("==> TagDBStore.getServiceResourceGuidsByService(" + serviceName + ")"); - } + return ret; + } - List ret = null; + @Override + public RangerTagResourceMap createTagResourceMap(RangerTagResourceMap tagResourceMap) { + LOG.debug("==> TagDBStore.createTagResourceMap({})", tagResourceMap); - Long serviceId = daoManager.getXXService().findIdByName(serviceName); + RangerTagResourceMap ret = rangerTagResourceMapService.create(tagResourceMap); - if (serviceId != null) { - ret = daoManager.getXXServiceResource().findServiceResourceGuidsInServiceId(serviceId); - } + // We also need to update tags stored with the resource + refreshServiceResource(tagResourceMap.getResourceId()); - if (LOG.isDebugEnabled()) { - LOG.debug("<== TagDBStore.getServiceResourceGuidsByService(" + serviceName + "): count=" + (ret == null ? 0 : ret.size())); - } + LOG.debug("<== TagDBStore.createTagResourceMap({}): {}", tagResourceMap, ret); - return ret; - } + return ret; + } - @Override - public RangerServiceResource getServiceResourceByServiceAndResourceSignature(String serviceName, String resourceSignature) throws Exception { - if (LOG.isDebugEnabled()) { - LOG.debug("==> TagDBStore.getServiceResourceByServiceAndResourceSignature(" + serviceName + ", " + resourceSignature + ")"); - } + @Override + public void deleteTagResourceMap(Long id) { + LOG.debug("==> TagDBStore.deleteTagResourceMap({})", id); - RangerServiceResource ret = null; + RangerTagResourceMap tagResourceMap = rangerTagResourceMapService.read(id); + Long tagId = tagResourceMap.getTagId(); + RangerTag tag = getTag(tagId); - Long serviceId = daoManager.getXXService().findIdByName(serviceName); + rangerTagResourceMapService.delete(tagResourceMap); - if (serviceId != null) { - ret = rangerServiceResourceService.getByServiceAndResourceSignature(serviceId, resourceSignature); - } + if (tag.getOwner() == null || tag.getOwner() == RangerTag.OWNER_SERVICERESOURCE) { + deleteTag(tagId); + } + // We also need to update tags stored with the resource + refreshServiceResource(tagResourceMap.getResourceId()); - if (LOG.isDebugEnabled()) { - LOG.debug("<== TagDBStore.getServiceResourceByServiceAndResourceSignature(" + serviceName + ", " + resourceSignature + "): " + ret); - } + LOG.debug("<== TagDBStore.deleteTagResourceMap({})", id); + } - return ret; - } + @Override + public RangerTagResourceMap getTagResourceMap(Long id) { + LOG.debug("==> TagDBStore.getTagResourceMap({})", id); - @Override - public List getServiceResources(SearchFilter filter) throws Exception { - if (LOG.isDebugEnabled()) { - LOG.debug("==> TagDBStore.getServiceResources(" + filter + ")"); - } + RangerTagResourceMap ret = rangerTagResourceMapService.read(id); - List ret = rangerServiceResourceService.searchServiceResources(filter).getList(); + LOG.debug("<== TagDBStore.getTagResourceMap({})", id); - if (LOG.isDebugEnabled()) { - LOG.debug("<== TagDBStore.getServiceResources(" + filter + "): count=" + (ret == null ? 0 : ret.size())); - } + return ret; + } - return ret; - } + @Override + public RangerTagResourceMap getTagResourceMapByGuid(String guid) { + LOG.debug("==> TagDBStore.getTagResourceMapByGuid({})", guid); - @Override - public PList getPaginatedServiceResources(SearchFilter filter) throws Exception { - if (LOG.isDebugEnabled()) { - LOG.debug("==> TagDBStore.getPaginatedServiceResources(" + filter + ")"); - } + RangerTagResourceMap ret = rangerTagResourceMapService.getByGuid(guid); - PList ret = rangerServiceResourceService.searchServiceResources(filter); + LOG.debug("<== TagDBStore.getTagResourceMapByGuid({})", guid); - if (LOG.isDebugEnabled()) { - LOG.debug("<== TagDBStore.getPaginatedServiceResources(" + filter + "): count=" + (ret == null ? 0 : ret.getPageSize())); - } + return ret; + } + + @Override + public List getTagResourceMapsForTagId(Long tagId) { + LOG.debug("==> TagDBStore.getTagResourceMapsForTagId({})", tagId); + + List ret = rangerTagResourceMapService.getByTagId(tagId); + + LOG.debug("<== TagDBStore.getTagResourceMapsForTagId({}): count={}", tagId, ret == null ? 0 : ret.size()); + + return ret; + } + + @Override + public List getTagResourceMapsForTagGuid(String tagGuid) { + LOG.debug("==> TagDBStore.getTagResourceMapsForTagGuid({})", tagGuid); + + List ret = rangerTagResourceMapService.getByTagGuid(tagGuid); + + LOG.debug("<== TagDBStore.getTagResourceMapsForTagGuid({}): count={}", tagGuid, ret == null ? 0 : ret.size()); + + return ret; + } - return ret; - } + @Override + public List getTagResourceMapsForResourceId(Long resourceId) { + LOG.debug("==> TagDBStore.getTagResourceMapsForResourceId({})", resourceId); - public RangerServiceResourceWithTagsList getPaginatedServiceResourcesWithTags(SearchFilter filter) throws Exception { - return rangerServiceResourceWithTagsService.searchServiceResourcesWithTags(filter); - } + List ret = rangerTagResourceMapService.getByResourceId(resourceId); + LOG.debug("<== TagDBStore.getTagResourceMapsForResourceId({}): count={}", resourceId, ret == null ? 0 : ret.size()); - @Override - public RangerTagResourceMap createTagResourceMap(RangerTagResourceMap tagResourceMap) throws Exception { - if (LOG.isDebugEnabled()) { - LOG.debug("==> TagDBStore.createTagResourceMap(" + tagResourceMap + ")"); - } + return ret; + } - RangerTagResourceMap ret = rangerTagResourceMapService.create(tagResourceMap); + @Override + public List getTagResourceMapsForResourceGuid(String resourceGuid) { + LOG.debug("==> TagDBStore.getTagResourceMapsForResourceGuid({})", resourceGuid); - // We also need to update tags stored with the resource - refreshServiceResource(tagResourceMap.getResourceId()); + List ret = rangerTagResourceMapService.getByResourceGuid(resourceGuid); - if (LOG.isDebugEnabled()) { - LOG.debug("<== TagDBStore.createTagResourceMap(" + tagResourceMap + "): " + ret); - } + LOG.debug("<== TagDBStore.getTagResourceMapsForResourceGuid({}): count={}", resourceGuid, ret == null ? 0 : ret.size()); - return ret; - } + return ret; + } - @Override - public void deleteTagResourceMap(Long id) throws Exception { - if (LOG.isDebugEnabled()) { - LOG.debug("==> TagDBStore.deleteTagResourceMap(" + id + ")"); - } + @Override + public RangerTagResourceMap getTagResourceMapForTagAndResourceId(Long tagId, Long resourceId) { + LOG.debug("==> TagDBStore.getTagResourceMapsForTagAndResourceId({}, {})", tagId, resourceId); - RangerTagResourceMap tagResourceMap = rangerTagResourceMapService.read(id); - Long tagId = tagResourceMap.getTagId(); - RangerTag tag = getTag(tagId); + RangerTagResourceMap ret = rangerTagResourceMapService.getByTagAndResourceId(tagId, resourceId); - rangerTagResourceMapService.delete(tagResourceMap); + LOG.debug("<== TagDBStore.getTagResourceMapsForTagAndResourceId({}, {}): {}", tagId, resourceId, ret); - if (tag.getOwner() == null || tag.getOwner() == RangerTag.OWNER_SERVICERESOURCE) { - deleteTag(tagId); - } - // We also need to update tags stored with the resource - refreshServiceResource(tagResourceMap.getResourceId()); + return ret; + } - if (LOG.isDebugEnabled()) { - LOG.debug("<== TagDBStore.deleteTagResourceMap(" + id + ")"); - } - } + @Override + public RangerTagResourceMap getTagResourceMapForTagAndResourceGuid(String tagGuid, String resourceGuid) { + LOG.debug("==> TagDBStore.getTagResourceMapForTagAndResourceGuid({}, {})", tagGuid, resourceGuid); - @Override - public RangerTagResourceMap getTagResourceMap(Long id) throws Exception { - if (LOG.isDebugEnabled()) { - LOG.debug("==> TagDBStore.getTagResourceMap(" + id + ")"); - } + RangerTagResourceMap ret = rangerTagResourceMapService.getByTagAndResourceGuid(tagGuid, resourceGuid); - RangerTagResourceMap ret = rangerTagResourceMapService.read(id); + LOG.debug("<== TagDBStore.getTagResourceMapForTagAndResourceGuid({}, {}): {}", tagGuid, resourceGuid, ret); - if (LOG.isDebugEnabled()) { - LOG.debug("<== TagDBStore.getTagResourceMap(" + id + ")"); - } + return ret; + } - return ret; - } + @Override + public List getTagResourceMaps(SearchFilter filter) { + LOG.debug("==> TagDBStore.getTagResourceMaps({})", filter); - @Override - public RangerTagResourceMap getTagResourceMapByGuid(String guid) throws Exception { - if (LOG.isDebugEnabled()) { - LOG.debug("==> TagDBStore.getTagResourceMapByGuid(" + guid + ")"); - } + List ret = rangerTagResourceMapService.searchRangerTaggedResources(filter).getList(); - RangerTagResourceMap ret = rangerTagResourceMapService.getByGuid(guid); + LOG.debug("<== TagDBStore.getTagResourceMaps({}): count={}", filter, ret == null ? 0 : ret.size()); - if (LOG.isDebugEnabled()) { - LOG.debug("<== TagDBStore.getTagResourceMapByGuid(" + guid + ")"); - } + return ret; + } - return ret; - } + @Override + public PList getPaginatedTagResourceMaps(SearchFilter filter) { + LOG.debug("==> TagDBStore.getPaginatedTagResourceMaps({})", filter); - @Override - public List getTagResourceMapsForTagId(Long tagId) throws Exception { - if (LOG.isDebugEnabled()) { - LOG.debug("==> TagDBStore.getTagResourceMapsForTagId(" + tagId + ")"); - } + PList ret = rangerTagResourceMapService.searchRangerTaggedResources(filter); - List ret = rangerTagResourceMapService.getByTagId(tagId); + LOG.debug("<== TagDBStore.getPaginatedTagResourceMaps({}): count={}", filter, ret == null ? 0 : ret.getPageSize()); - if (LOG.isDebugEnabled()) { - LOG.debug("<== TagDBStore.getTagResourceMapsForTagId(" + tagId + "): count=" + (ret == null ? 0 : ret.size())); - } + return ret; + } - return ret; - } + @Override + public ServiceTags getServiceTagsIfUpdated(String serviceName, Long lastKnownVersion, boolean needsBackwardCompatibility) throws Exception { + LOG.debug("==> TagDBStore.getServiceTagsIfUpdated({}, {}, {})", serviceName, lastKnownVersion, needsBackwardCompatibility); - @Override - public List getTagResourceMapsForTagGuid(String tagGuid) throws Exception { - if (LOG.isDebugEnabled()) { - LOG.debug("==> TagDBStore.getTagResourceMapsForTagGuid(" + tagGuid + ")"); - } + ServiceTags ret = null; + Long serviceId = daoManager.getXXService().findIdByName(serviceName); - List ret = rangerTagResourceMapService.getByTagGuid(tagGuid); + if (serviceId == null) { + LOG.error("Requested Service not found. serviceName={}", serviceName); - if (LOG.isDebugEnabled()) { - LOG.debug("<== TagDBStore.getTagResourceMapsForTagGuid(" + tagGuid + "): count=" + (ret == null ? 0 : ret.size())); - } + throw restErrorUtil.createRESTException(HttpServletResponse.SC_NOT_FOUND, RangerServiceNotFoundException.buildExceptionMsg(serviceName), false); + } - return ret; - } + XXServiceVersionInfo serviceVersionInfoDbObj = daoManager.getXXServiceVersionInfo().findByServiceName(serviceName); - @Override - public List getTagIdsForResourceId(Long resourceId) throws Exception { - if (LOG.isDebugEnabled()) { - LOG.debug("==> TagDBStore.getTagIdsForResourceId(" + resourceId + ")"); - } + if (serviceVersionInfoDbObj == null) { + LOG.warn("serviceVersionInfo does not exist. name={}", serviceName); + } - List ret = rangerTagResourceMapService.getTagIdsForResourceId(resourceId); + if (lastKnownVersion == null || serviceVersionInfoDbObj == null || serviceVersionInfoDbObj.getTagVersion() == null || !lastKnownVersion.equals(serviceVersionInfoDbObj.getTagVersion())) { + ret = RangerServiceTagsCache.getInstance().getServiceTags(serviceName, serviceId, lastKnownVersion, needsBackwardCompatibility, this); + } - if (LOG.isDebugEnabled()) { - LOG.debug("<== TagDBStore.getTagIdsForResourceId(" + resourceId + "): count=" + (ret == null ? 0 : ret.size())); - } + if (ret != null && lastKnownVersion != null && lastKnownVersion.equals(ret.getTagVersion())) { + // ServiceTags are not changed + ret = null; + } - return ret; - } + if (LOG.isDebugEnabled()) { + RangerServiceTagsCache.getInstance().dump(); + } - @Override - public List getTagResourceMapsForResourceId(Long resourceId) throws Exception { - if (LOG.isDebugEnabled()) { - LOG.debug("==> TagDBStore.getTagResourceMapsForResourceId(" + resourceId + ")"); - } + LOG.debug("<== TagDBStore.getServiceTagsIfUpdated({}, {}, {}): count={}", serviceName, lastKnownVersion, needsBackwardCompatibility, (ret == null || ret.getTags() == null) ? 0 : ret.getTags().size()); - List ret = rangerTagResourceMapService.getByResourceId(resourceId); + return ret; + } - if (LOG.isDebugEnabled()) { - LOG.debug("<== TagDBStore.getTagResourceMapsForResourceId(" + resourceId + "): count=" + (ret == null ? 0 : ret.size())); - } + @Override + public ServiceTags getServiceTags(String serviceName, Long lastKnownVersion) throws Exception { + LOG.debug("==> TagDBStore.getServiceTags({}, {})", serviceName, lastKnownVersion); - return ret; - } + XXService xxService = daoManager.getXXService().findByName(serviceName); - @Override - public List getTagResourceMapsForResourceGuid(String resourceGuid) throws Exception { - if (LOG.isDebugEnabled()) { - LOG.debug("==> TagDBStore.getTagResourceMapsForResourceGuid(" + resourceGuid + ")"); - } + if (xxService == null) { + throw new Exception("service does not exist. name=" + serviceName); + } - List ret = rangerTagResourceMapService.getByResourceGuid(resourceGuid); + XXServiceVersionInfo serviceVersionInfoDbObj = daoManager.getXXServiceVersionInfo().findByServiceName(serviceName); - if (LOG.isDebugEnabled()) { - LOG.debug("<== TagDBStore.getTagResourceMapsForResourceGuid(" + resourceGuid + "): count=" + (ret == null ? 0 : ret.size())); - } + if (serviceVersionInfoDbObj == null) { + LOG.warn("serviceVersionInfo does not exist for service [{}]", serviceName); + } - return ret; - } + RangerServiceDef serviceDef = svcStore.getServiceDef(xxService.getType()); - @Override - public RangerTagResourceMap getTagResourceMapForTagAndResourceId(Long tagId, Long resourceId) throws Exception { - if (LOG.isDebugEnabled()) { - LOG.debug("==> TagDBStore.getTagResourceMapsForTagAndResourceId(" + tagId + ", " + resourceId + ")"); - } + if (serviceDef == null) { + throw new Exception("service-def does not exist. id=" + xxService.getType()); + } - RangerTagResourceMap ret = rangerTagResourceMapService.getByTagAndResourceId(tagId, resourceId); + ServiceTags delta = getServiceTagsDelta(xxService.getId(), serviceName, lastKnownVersion); + final ServiceTags ret; - if (LOG.isDebugEnabled()) { - LOG.debug("<== TagDBStore.getTagResourceMapsForTagAndResourceId(" + tagId + ", " + resourceId + "): " + ret); - } + if (delta != null) { + ret = delta; + } else { + RangerTagDBRetriever tagDBRetriever = new RangerTagDBRetriever(daoManager, txManager, xxService); - return ret; - } + Map tagDefMap = tagDBRetriever.getTagDefs(); + Map tagMap = tagDBRetriever.getTags(); + List resources = tagDBRetriever.getServiceResources(); + Map> resourceToTagIds = tagDBRetriever.getResourceToTagIds(); - @Override - public RangerTagResourceMap getTagResourceMapForTagAndResourceGuid(String tagGuid, String resourceGuid) throws Exception { - if (LOG.isDebugEnabled()) { - LOG.debug("==> TagDBStore.getTagResourceMapForTagAndResourceGuid(" + tagGuid + ", " + resourceGuid + ")"); - } + ret = new ServiceTags(); - RangerTagResourceMap ret = rangerTagResourceMapService.getByTagAndResourceGuid(tagGuid, resourceGuid); + ret.setServiceName(xxService.getName()); + ret.setTagVersion(serviceVersionInfoDbObj == null ? null : serviceVersionInfoDbObj.getTagVersion()); + ret.setTagUpdateTime(serviceVersionInfoDbObj == null ? null : serviceVersionInfoDbObj.getTagUpdateTime()); + ret.setTagDefinitions(tagDefMap); + ret.setTags(tagMap); + ret.setServiceResources(resources); + ret.setResourceToTagIds(resourceToTagIds); + ret.setIsTagsDeduped(isSupportsTagsDedup()); - if (LOG.isDebugEnabled()) { - LOG.debug("<== TagDBStore.getTagResourceMapForTagAndResourceGuid(" + tagGuid + ", " + resourceGuid + "): " + ret); - } + if (isSupportsTagsDedup()) { + final int countOfDuplicateTags = ret.dedupTags(); - return ret; - } + LOG.debug("Number of duplicate tags removed from the received serviceTags:[{}]. Number of tags in the de-duplicated serviceTags :[{}].", countOfDuplicateTags, ret.getTags().size()); + } + } + LOG.debug("<== TagDBStore.getServiceTags({}, {})", serviceName, lastKnownVersion); - @Override - public List getTagResourceMaps(SearchFilter filter) throws Exception { - if (LOG.isDebugEnabled()) { - LOG.debug("==> TagDBStore.getTagResourceMaps(" + filter+ ")"); - } + return ret; + } - List ret = rangerTagResourceMapService.searchRangerTaggedResources(filter).getList(); + @Override + public ServiceTags getServiceTagsDelta(String serviceName, Long lastKnownVersion) throws Exception { + LOG.debug("==> TagDBStore.getServiceTagsDelta({}, {})", serviceName, lastKnownVersion); - if (LOG.isDebugEnabled()) { - LOG.debug("<== TagDBStore.getTagResourceMaps(" + filter + "): count=" + (ret == null ? 0 : ret.size())); - } + final ServiceTags ret; - return ret; - } + if (lastKnownVersion == -1L || !isSupportsTagDeltas()) { + LOG.debug("Returning without computing tags-deltas.., SUPPORTS_TAG_DELTAS:[{}], lastKnownVersion:[{}]", SUPPORTS_TAG_DELTAS, lastKnownVersion); - @Override - public PList getPaginatedTagResourceMaps(SearchFilter filter) throws Exception { - if (LOG.isDebugEnabled()) { - LOG.debug("==> TagDBStore.getPaginatedTagResourceMaps(" + filter+ ")"); - } + ret = null; + } else { + Long serviceId = daoManager.getXXService().findIdByName(serviceName); - PList ret = rangerTagResourceMapService.searchRangerTaggedResources(filter); + if (serviceId == null) { + throw new Exception("service does not exist. name=" + serviceName); + } - if (LOG.isDebugEnabled()) { - LOG.debug("<== TagDBStore.getPaginatedTagResourceMaps(" + filter + "): count=" + (ret == null ? 0 : ret.getPageSize())); - } + ret = getServiceTagsDelta(serviceId, serviceName, lastKnownVersion); + } - return ret; - } + LOG.debug("<== TagDBStore.getServiceTagsDelta({}, {})", serviceName, lastKnownVersion); + return ret; + } - @Override - public ServiceTags getServiceTagsIfUpdated(String serviceName, Long lastKnownVersion, boolean needsBackwardCompatibility) throws Exception { - if (LOG.isDebugEnabled()) { - LOG.debug("==> TagDBStore.getServiceTagsIfUpdated(" + serviceName + ", " + lastKnownVersion + ", " + needsBackwardCompatibility + ")"); - } + @Override + public Long getTagVersion(String serviceName) { + XXServiceVersionInfo serviceVersionInfoDbObj = daoManager.getXXServiceVersionInfo().findByServiceName(serviceName); - ServiceTags ret = null; + return serviceVersionInfoDbObj != null ? serviceVersionInfoDbObj.getTagVersion() : null; + } - Long serviceId = daoManager.getXXService().findIdByName(serviceName); + @Override + public void deleteAllTagObjectsForService(String serviceName) { + LOG.debug("==> TagDBStore.deleteAllTagObjectsForService({})", serviceName); + + XXService service = daoManager.getXXService().findByName(serviceName); + + if (service != null) { + Long serviceId = service.getId(); + List xxTags = daoManager.getXXTag().findByServiceIdAndOwner(serviceId, RangerTag.OWNER_SERVICERESOURCE); + List xxTagResourceMaps = daoManager.getXXTagResourceMap().findByServiceId(serviceId); + + if (CollectionUtils.isNotEmpty(xxTagResourceMaps)) { + for (XXTagResourceMap xxTagResourceMap : xxTagResourceMaps) { + try { + daoManager.getXXTagResourceMap().remove(xxTagResourceMap); + } catch (Exception e) { + LOG.error("Error deleting RangerTagResourceMap with id={}", xxTagResourceMap.getId(), e); + + throw e; + } + } + } + + if (CollectionUtils.isNotEmpty(xxTags)) { + for (XXTag xxTag : xxTags) { + try { + daoManager.getXXTag().remove(xxTag); + } catch (Exception e) { + LOG.error("Error deleting RangerTag with id={}", xxTag.getId(), e); + + throw e; + } + } + } + + List xxServiceResources = daoManager.getXXServiceResource().findByServiceId(serviceId); + + if (CollectionUtils.isNotEmpty(xxServiceResources)) { + for (XXServiceResource xxServiceResource : xxServiceResources) { + try { + daoManager.getXXServiceResource().remove(xxServiceResource); + } catch (Exception e) { + LOG.error("Error deleting RangerServiceResource with id={}", xxServiceResource.getId(), e); + + throw e; + } + } + } + } - if (serviceId == null) { - LOG.error("Requested Service not found. serviceName=" + serviceName); - throw restErrorUtil.createRESTException(HttpServletResponse.SC_NOT_FOUND, RangerServiceNotFoundException.buildExceptionMsg(serviceName), - false); - } + LOG.debug("<== TagDBStore.deleteAllTagObjectsForService({})", serviceName); + } - XXServiceVersionInfo serviceVersionInfoDbObj = daoManager.getXXServiceVersionInfo().findByServiceName(serviceName); + public boolean isInPlaceTagUpdateSupported() { + initStatics(); + return SUPPORTS_IN_PLACE_TAG_UPDATES; + } - if (serviceVersionInfoDbObj == null) { - LOG.warn("serviceVersionInfo does not exist. name=" + serviceName); - } + public boolean resetTagCache(final String serviceName) { + LOG.debug("==> TagDBStore.resetTagCache({})", serviceName); - if (lastKnownVersion == null || serviceVersionInfoDbObj == null || serviceVersionInfoDbObj.getTagVersion() == null || !lastKnownVersion.equals(serviceVersionInfoDbObj.getTagVersion())) { - ret = RangerServiceTagsCache.getInstance().getServiceTags(serviceName, serviceId, lastKnownVersion, needsBackwardCompatibility, this); - } + boolean ret = RangerServiceTagsCache.getInstance().resetCache(serviceName); - if (ret != null && lastKnownVersion != null && lastKnownVersion.equals(ret.getTagVersion())) { - // ServiceTags are not changed - ret = null; - } + LOG.debug("<== TagDBStore.resetTagCache(): ret={}", ret); - if (LOG.isDebugEnabled()) { - RangerServiceTagsCache.getInstance().dump(); - } + return ret; + } - if (LOG.isDebugEnabled()) { - LOG.debug("<== TagDBStore.getServiceTagsIfUpdated(" + serviceName + ", " + lastKnownVersion + ", " + needsBackwardCompatibility + "): count=" + ((ret == null || ret.getTags() == null) ? 0 : ret.getTags().size())); - } + public RangerServiceResourceWithTagsList getPaginatedServiceResourcesWithTags(SearchFilter filter) { + return rangerServiceResourceWithTagsService.searchServiceResourcesWithTags(filter); + } - return ret; - } + private RangerTag validateTag(RangerTag tag) throws Exception { + List validityPeriods = tag.getValidityPeriods(); - @Override - public Long getTagVersion(String serviceName) { + if (CollectionUtils.isNotEmpty(validityPeriods)) { + List normalizedValidityPeriods = new ArrayList<>(); + List failures = new ArrayList<>(); - XXServiceVersionInfo serviceVersionInfoDbObj = daoManager.getXXServiceVersionInfo().findByServiceName(serviceName); + for (RangerValiditySchedule validityPeriod : validityPeriods) { + RangerValidityScheduleValidator validator = new RangerValidityScheduleValidator(validityPeriod); + RangerValiditySchedule normalizedValidityPeriod = validator.validate(failures); - return serviceVersionInfoDbObj != null ? serviceVersionInfoDbObj.getTagVersion() : null; - } + if (normalizedValidityPeriod != null && CollectionUtils.isEmpty(failures)) { + LOG.debug("Normalized ValidityPeriod:[{}]", normalizedValidityPeriod); - @Override - public ServiceTags getServiceTags(String serviceName, Long lastKnownVersion) throws Exception { - if (LOG.isDebugEnabled()) { - LOG.debug("==> TagDBStore.getServiceTags(" + serviceName + ", " + lastKnownVersion + ")"); - } + normalizedValidityPeriods.add(normalizedValidityPeriod); + } else { + String error = "Incorrect time-specification:[" + Collections.singletonList(failures) + "]"; - final ServiceTags ret; + LOG.error(error); - XXService xxService = daoManager.getXXService().findByName(serviceName); + throw new Exception(error); + } + } - if (xxService == null) { - throw new Exception("service does not exist. name=" + serviceName); - } + tag.setValidityPeriods(normalizedValidityPeriods); + } - XXServiceVersionInfo serviceVersionInfoDbObj = daoManager.getXXServiceVersionInfo().findByServiceName(serviceName); + return tag; + } - if (serviceVersionInfoDbObj == null) { - LOG.warn("serviceVersionInfo does not exist for service [" + serviceName + "]"); - } + private ServiceTags getServiceTagsDelta(Long serviceId, String serviceName, Long lastKnownVersion) { + LOG.debug("==> TagDBStore.getServiceTagsDelta(lastKnownVersion={})", lastKnownVersion); - RangerServiceDef serviceDef = svcStore.getServiceDef(xxService.getType()); + ServiceTags ret = null; - if (serviceDef == null) { - throw new Exception("service-def does not exist. id=" + xxService.getType()); - } + if (lastKnownVersion == -1L || !isSupportsTagDeltas()) { + LOG.debug("Returning without computing tags-deltas.., SUPPORTS_TAG_DELTAS:[{}], lastKnownVersion:[{}]", SUPPORTS_TAG_DELTAS, lastKnownVersion); + } else { + RangerPerfTracer perf = null; - ServiceTags delta = getServiceTagsDelta(xxService.getId(), serviceName, lastKnownVersion); + if (RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { + perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "TagDBStore.getServiceTagsDelta(serviceName=" + serviceName + ", lastKnownVersion=" + lastKnownVersion + ")"); + } - if (delta != null) { - ret = delta; - } else { - RangerTagDBRetriever tagDBRetriever = new RangerTagDBRetriever(daoManager, txManager, xxService); + List changeLogRecords = daoManager.getXXTagChangeLog().findLaterThan(lastKnownVersion, serviceId); - Map tagDefMap = tagDBRetriever.getTagDefs(); - Map tagMap = tagDBRetriever.getTags(); - List resources = tagDBRetriever.getServiceResources(); - Map> resourceToTagIds = tagDBRetriever.getResourceToTagIds(); + LOG.debug("Number of tag-change-log records found since {} :[{}] for serviceId:[{}]", lastKnownVersion, changeLogRecords == null ? 0 : changeLogRecords.size(), serviceId); - ret = new ServiceTags(); + try { + ret = createServiceTagsDelta(changeLogRecords); - ret.setServiceName(xxService.getName()); - ret.setTagVersion(serviceVersionInfoDbObj == null ? null : serviceVersionInfoDbObj.getTagVersion()); - ret.setTagUpdateTime(serviceVersionInfoDbObj == null ? null : serviceVersionInfoDbObj.getTagUpdateTime()); - ret.setTagDefinitions(tagDefMap); - ret.setTags(tagMap); - ret.setServiceResources(resources); - ret.setResourceToTagIds(resourceToTagIds); + if (ret != null) { + ret.setServiceName(serviceName); + } + } catch (Exception e) { + LOG.error("Perhaps some tag or service-resource could not be found", e); + } - ret.setIsTagsDeduped(isSupportsTagsDedup()); - - if (isSupportsTagsDedup()) { - final int countOfDuplicateTags = ret.dedupTags(); - if (LOG.isDebugEnabled()) { - LOG.debug("Number of duplicate tags removed from the received serviceTags:[" + countOfDuplicateTags + "]. Number of tags in the de-duplicated serviceTags :[" + ret.getTags().size() + "]."); - } - } - } - - if (LOG.isDebugEnabled()) { - LOG.debug("<== TagDBStore.getServiceTags(" + serviceName + ", " + lastKnownVersion + ")"); - } - - return ret; - } - - @Override - public ServiceTags getServiceTagsDelta(String serviceName, Long lastKnownVersion) throws Exception { - if (LOG.isDebugEnabled()) { - LOG.debug("==> TagDBStore.getServiceTagsDelta(" + serviceName + ", " + lastKnownVersion + ")"); - } - - final ServiceTags ret; - - if (lastKnownVersion == -1L || !isSupportsTagDeltas()) { - if (LOG.isDebugEnabled()) { - LOG.debug("Returning without computing tags-deltas.., SUPPORTS_TAG_DELTAS:[" + SUPPORTS_TAG_DELTAS + "], lastKnownVersion:[" + lastKnownVersion + "]"); - } - ret = null; - } else { - Long serviceId = daoManager.getXXService().findIdByName(serviceName); + RangerPerfTracer.logAlways(perf); + } - if (serviceId == null) { - throw new Exception("service does not exist. name=" + serviceName); - } + LOG.debug("<== TagDBStore.getServiceTagsDelta(lastKnownVersion={})", lastKnownVersion); - ret = getServiceTagsDelta(serviceId, serviceName, lastKnownVersion); - } - - if (LOG.isDebugEnabled()) { - LOG.debug("<== TagDBStore.getServiceTagsDelta(" + serviceName + ", " + lastKnownVersion + ")"); - } - return ret; - } - - @Override - public void deleteAllTagObjectsForService(String serviceName) throws Exception { - - if (LOG.isDebugEnabled()) { - LOG.debug("==> TagDBStore.deleteAllTagObjectsForService(" + serviceName + ")"); - } - - XXService service = daoManager.getXXService().findByName(serviceName); - - if (service != null) { - Long serviceId = service.getId(); - - List xxTags = daoManager.getXXTag().findByServiceIdAndOwner(serviceId, RangerTag.OWNER_SERVICERESOURCE); - - List xxTagResourceMaps = daoManager.getXXTagResourceMap().findByServiceId(serviceId); - - if (CollectionUtils.isNotEmpty(xxTagResourceMaps)) { - for (XXTagResourceMap xxTagResourceMap : xxTagResourceMaps) { - try { - daoManager.getXXTagResourceMap().remove(xxTagResourceMap); - } catch (Exception e) { - LOG.error("Error deleting RangerTagResourceMap with id=" + xxTagResourceMap.getId(), e); - throw e; - } - } - } - - if (CollectionUtils.isNotEmpty(xxTags)) { - for (XXTag xxTag : xxTags) { - try { - daoManager.getXXTag().remove(xxTag); - } catch (Exception e) { - LOG.error("Error deleting RangerTag with id=" + xxTag.getId(), e); - throw e; - } - } - } - - List xxServiceResources = daoManager.getXXServiceResource().findByServiceId(serviceId); - - if (CollectionUtils.isNotEmpty(xxServiceResources)) { - for (XXServiceResource xxServiceResource : xxServiceResources) { - try { - daoManager.getXXServiceResource().remove(xxServiceResource); - } catch (Exception e) { - LOG.error("Error deleting RangerServiceResource with id=" + xxServiceResource.getId(), e); - throw e; - } - } - } - - } - - if (LOG.isDebugEnabled()) { - LOG.debug("<== TagDBStore.deleteAllTagObjectsForService(" + serviceName + ")"); - } - } - - private RangerTag validateTag(RangerTag tag) throws Exception { - List validityPeriods = tag.getValidityPeriods(); - - if (CollectionUtils.isNotEmpty(validityPeriods)) { - List normalizedValidityPeriods = new ArrayList<>(); - List failures = new ArrayList<>(); - - for (RangerValiditySchedule validityPeriod : validityPeriods) { - RangerValidityScheduleValidator validator = new RangerValidityScheduleValidator(validityPeriod); - RangerValiditySchedule normalizedValidityPeriod = validator.validate(failures); - - if (normalizedValidityPeriod != null && CollectionUtils.isEmpty(failures)) { - if (LOG.isDebugEnabled()) { - LOG.debug("Normalized ValidityPeriod:[" + normalizedValidityPeriod + "]"); - } - - normalizedValidityPeriods.add(normalizedValidityPeriod); - } else { - String error = "Incorrect time-specification:[" + Arrays.asList(failures) + "]"; - - LOG.error(error); - - throw new Exception(error); - } - } - - tag.setValidityPeriods(normalizedValidityPeriods); - } - - return tag; - } - - private ServiceTags getServiceTagsDelta(Long serviceId, String serviceName, Long lastKnownVersion) { - if (LOG.isDebugEnabled()) { - LOG.debug("==> TagDBStore.getServiceTagsDelta(lastKnownVersion=" + lastKnownVersion + ")"); - } - ServiceTags ret = null; - - if (lastKnownVersion == -1L || !isSupportsTagDeltas()) { - if (LOG.isDebugEnabled()) { - LOG.debug("Returning without computing tags-deltas.., SUPPORTS_TAG_DELTAS:[" + SUPPORTS_TAG_DELTAS + "], lastKnownVersion:[" + lastKnownVersion + "]"); - } - } else { - RangerPerfTracer perf = null; - - if (RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { - perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "TagDBStore.getServiceTagsDelta(serviceName=" + serviceName + ", lastKnownVersion=" + lastKnownVersion + ")"); - } - - List changeLogRecords = daoManager.getXXTagChangeLog().findLaterThan(lastKnownVersion, serviceId); - - if (LOG.isDebugEnabled()) { - LOG.debug("Number of tag-change-log records found since " + lastKnownVersion + " :[" + (changeLogRecords == null ? 0 : changeLogRecords.size()) + "] for serviceId:[" + serviceId + "]"); - } - - try { - ret = createServiceTagsDelta(changeLogRecords); - if (ret != null) { - ret.setServiceName(serviceName); - } - } catch (Exception e) { - LOG.error("Perhaps some tag or service-resource could not be found", e); - } - - RangerPerfTracer.logAlways(perf); - } - - if (LOG.isDebugEnabled()) { - LOG.debug("<== TagDBStore.getServiceTagsDelta(lastKnownVersion=" + lastKnownVersion + ")"); - } - - return ret; - } - - private ServiceTags createServiceTagsDelta(List changeLogs) throws Exception { - if (LOG.isDebugEnabled()) { - LOG.debug("==> TagDBStore.createServiceTagsDelta()"); - } - - ServiceTags ret = null; - - if (CollectionUtils.isNotEmpty(changeLogs)) { - Set tagTypes = new HashSet<>(); - Set tagIds = new HashSet<>(); - Set serviceResourceIds = new HashSet<>(); - - for (XXTagChangeLog record : changeLogs) { - if (record.getChangeType().equals(ServiceTags.TagsChangeType.TAG_UPDATE.ordinal())) { - tagIds.add(record.getTagId()); - } else if (record.getChangeType().equals(ServiceTags.TagsChangeType.SERVICE_RESOURCE_UPDATE.ordinal())) { - serviceResourceIds.add(record.getServiceResourceId()); - } else if (record.getChangeType().equals(ServiceTags.TagsChangeType.TAG_RESOURCE_MAP_UPDATE.ordinal())) { - tagIds.add(record.getTagId()); - serviceResourceIds.add(record.getServiceResourceId()); - } else { - if (LOG.isDebugEnabled()) { - LOG.debug("Unknown changeType in tag-change-log record: [" + record + "]"); - LOG.debug("Returning without further processing"); - tagIds.clear(); - serviceResourceIds.clear(); - break; - } - } - } - - if (CollectionUtils.isNotEmpty(serviceResourceIds) || CollectionUtils.isNotEmpty(tagIds)) { - ret = new ServiceTags(); - ret.setIsDelta(true); - ret.setIsTagsDeduped(isSupportsTagsDedup()); - - ServiceTags.TagsChangeExtent tagsChangeExtent = ServiceTags.TagsChangeExtent.TAGS; - - ret.setTagVersion(changeLogs.get(changeLogs.size() - 1).getServiceTagsVersion()); - - XXTagDao tagDao = daoManager.getXXTag(); - - for (Long tagId : tagIds) { - RangerTag tag = null; - - try { - XXTag xTag = tagDao.getById(tagId); - - if (xTag != null) { - tag = rangerTagService.getPopulatedViewObject(xTag); - - tagTypes.add(tag.getType()); - } - } catch (Throwable t) { - if (LOG.isDebugEnabled()) { - LOG.debug("TagDBStore.createServiceTagsDelta(): failed to read tag id={}", tagId, t); - } - } finally { - if (tag == null) { - tag = new RangerTag(); - tag.setId(tagId); - } - } - - RangerServiceTagsDeltaUtil.pruneUnusedAttributes(tag); - - ret.getTags().put(tag.getId(), tag); - } - - XXTagDefDao tagDefDao = daoManager.getXXTagDef(); - - for (String tagType : tagTypes) { - try { - XXTagDef xTagDef = tagDefDao.findByName(tagType); - RangerTagDef tagDef = xTagDef != null ? rangerTagDefService.getPopulatedViewObject(xTagDef) : null; - - if (tagDef != null) { - RangerServiceTagsDeltaUtil.pruneUnusedAttributes(tagDef); - - ret.getTagDefinitions().put(tagDef.getId(), tagDef); - } else { - if (LOG.isDebugEnabled()) { - LOG.debug("TagDBStore.createServiceTagsDelta(): failed to load tagDef type={}", tagType); - } - } - } catch (Throwable t) { - if (LOG.isDebugEnabled()) { - LOG.debug("TagDBStore.createServiceTagsDelta(): failed to load tagDef type={}", tagType, t); - } - } - } - - for (Long serviceResourceId : serviceResourceIds) { - // Check if serviceResourceId is part of any resource->id mapping - XXServiceResource xServiceResource = null; - try { - xServiceResource = daoManager.getXXServiceResource().getById(serviceResourceId); - } catch (Throwable t) { - if (LOG.isDebugEnabled()) { - LOG.debug("TagDBStore.createServiceTagsDelta(): failed to read serviceResource id={}", serviceResourceId, t); - } - } - - final RangerServiceResource serviceResource; - - if (xServiceResource == null) { - serviceResource = new RangerServiceResource(); - serviceResource.setId(serviceResourceId); - } else { - serviceResource = rangerServiceResourceService.getPopulatedViewObject(xServiceResource); - - if (StringUtils.isNotEmpty(xServiceResource.getTags())) { - try { - List tags = (List) JsonUtils.jsonToObject(xServiceResource.getTags(), RangerServiceResourceService.duplicatedDataType); - - - if (CollectionUtils.isNotEmpty(tags)) { - List resourceTagIds = new ArrayList<>(tags.size()); - - for (RangerTag tag : tags) { - RangerServiceTagsDeltaUtil.pruneUnusedAttributes(tag); - - if (!ret.getTags().containsKey(tag.getId())) { - ret.getTags().put(tag.getId(), tag); - } - - resourceTagIds.add(tag.getId()); - } - - ret.getResourceToTagIds().put(serviceResourceId, resourceTagIds); - } - } catch (JsonProcessingException e) { - LOG.error("Error occurred while processing json", e); - } - } - } - - RangerServiceTagsDeltaUtil.pruneUnusedAttributes(serviceResource); - - ret.getServiceResources().add(serviceResource); - tagsChangeExtent = ServiceTags.TagsChangeExtent.SERVICE_RESOURCE; - } - - ret.setTagsChangeExtent(tagsChangeExtent); - } - } else { - if (LOG.isDebugEnabled()) { - LOG.debug("No tag-change-log records provided to createServiceTagsDelta()"); - } - } - if (LOG.isDebugEnabled()) { - LOG.debug("<== TagDBStore.createServiceTagsDelta() : serviceTagsDelta={" + ret + "}"); - } - - return ret; - } - - private static void initStatics() { - if (!IS_SUPPORTS_TAG_DELTAS_INITIALIZED) { - RangerAdminConfig config = RangerAdminConfig.getInstance(); - - SUPPORTS_TAG_DELTAS = config.getBoolean("ranger.admin" + RangerCommonConstants.RANGER_ADMIN_SUFFIX_TAG_DELTA, RangerCommonConstants.RANGER_ADMIN_SUFFIX_TAG_DELTA_DEFAULT); - SUPPORTS_IN_PLACE_TAG_UPDATES = SUPPORTS_TAG_DELTAS && config.getBoolean("ranger.admin" + RangerCommonConstants.RANGER_ADMIN_SUFFIX_IN_PLACE_TAG_UPDATES, RangerCommonConstants.RANGER_ADMIN_SUFFIX_IN_PLACE_TAG_UPDATES_DEFAULT); - IS_SUPPORTS_TAG_DELTAS_INITIALIZED = true; - - LOG.info("SUPPORTS_TAG_DELTAS=" + SUPPORTS_TAG_DELTAS); - LOG.info("SUPPORTS_IN_PLACE_TAG_UPDATES=" + SUPPORTS_IN_PLACE_TAG_UPDATES); - } - } - - public static boolean isSupportsTagDeltas() { - initStatics(); - return SUPPORTS_TAG_DELTAS; + return ret; } - public boolean isInPlaceTagUpdateSupported() { - initStatics(); - return SUPPORTS_IN_PLACE_TAG_UPDATES; - } + private ServiceTags createServiceTagsDelta(List changeLogs) { + LOG.debug("==> TagDBStore.createServiceTagsDelta()"); - private void deleteTagDef(RangerTagDef tagDef) throws Exception { - if (tagDef != null) { - if (LOG.isDebugEnabled()) { - LOG.debug("Deleting tag-def [name=" + tagDef.getName() + "; id=" + tagDef.getId() + "]"); - } + ServiceTags ret = null; - List tagsByType = rangerTagService.getTagsByType(tagDef.getName()); + if (CollectionUtils.isNotEmpty(changeLogs)) { + Set tagTypes = new HashSet<>(); + Set tagIds = new HashSet<>(); + Set serviceResourceIds = new HashSet<>(); - if (CollectionUtils.isEmpty(tagsByType)) { - rangerTagDefService.delete(tagDef); - } else { - throw new Exception("Cannot delete tag-def: " + tagDef.getName() + ". " + tagsByType.size() + " tag instances for this tag-def exist"); - } - } - } + for (XXTagChangeLog record : changeLogs) { + if (record.getChangeType().equals(ServiceTags.TagsChangeType.TAG_UPDATE.ordinal())) { + tagIds.add(record.getTagId()); + } else if (record.getChangeType().equals(ServiceTags.TagsChangeType.SERVICE_RESOURCE_UPDATE.ordinal())) { + serviceResourceIds.add(record.getServiceResourceId()); + } else if (record.getChangeType().equals(ServiceTags.TagsChangeType.TAG_RESOURCE_MAP_UPDATE.ordinal())) { + tagIds.add(record.getTagId()); + serviceResourceIds.add(record.getServiceResourceId()); + } else { + if (LOG.isDebugEnabled()) { + LOG.debug("Unknown changeType in tag-change-log record: [{}]", record); + LOG.debug("Returning without further processing"); - public static RangerServiceResource toRangerServiceResource(String serviceName, Map resourceMap) { - if (LOG.isDebugEnabled()) { - LOG.debug("==> TagDBStore.toRangerServiceResource(): serviceName={" + serviceName + "}"); - } + tagIds.clear(); + serviceResourceIds.clear(); + break; + } + } + } - Map resourceElements = new HashMap<>(); + if (CollectionUtils.isNotEmpty(serviceResourceIds) || CollectionUtils.isNotEmpty(tagIds)) { + ret = new ServiceTags(); - for (Map.Entry entry : resourceMap.entrySet()) { - String[] parts = entry.getKey().split("\\."); - String[] valueArray = entry.getValue(); + ret.setIsDelta(true); + ret.setIsTagsDeduped(isSupportsTagsDedup()); - if (parts.length < 1 || valueArray == null) { - continue; - } + ServiceTags.TagsChangeExtent tagsChangeExtent = ServiceTags.TagsChangeExtent.TAGS; - String key = parts[0]; + ret.setTagVersion(changeLogs.get(changeLogs.size() - 1).getServiceTagsVersion()); - RangerPolicyResource policyResource = resourceElements.get(key); + XXTagDao tagDao = daoManager.getXXTag(); - if (policyResource == null) { - policyResource = new RangerPolicyResource(); + for (Long tagId : tagIds) { + RangerTag tag = null; - resourceElements.put(key, policyResource); - } + try { + XXTag xTag = tagDao.getById(tagId); - if (parts.length == 1) { - List valueList = new ArrayList<>(valueArray.length); + if (xTag != null) { + tag = rangerTagService.getPopulatedViewObject(xTag); - for (String str : valueArray) { - valueList.add(str.trim()); - } + tagTypes.add(tag.getType()); + } + } catch (Throwable t) { + LOG.debug("TagDBStore.createServiceTagsDelta(): failed to read tag id={}", tagId, t); + } finally { + if (tag == null) { + tag = new RangerTag(); - policyResource.setValues(valueList); - } else if (parts.length == 2 && valueArray[0] != null) { - String subKey = parts[1]; - String value = valueArray[0]; + tag.setId(tagId); + } + } - if (subKey.equalsIgnoreCase("isExcludes")) { - policyResource.setIsExcludes(Boolean.parseBoolean(value.trim())); - } else if (subKey.equalsIgnoreCase("isRecursive")) { - policyResource.setIsRecursive(Boolean.parseBoolean(value.trim())); - } - } - } + RangerServiceTagsDeltaUtil.pruneUnusedAttributes(tag); - RangerServiceResource ret = new RangerServiceResource(serviceName, resourceElements); + ret.getTags().put(tag.getId(), tag); + } - if (LOG.isDebugEnabled()) { - LOG.debug("<== TagDBStore.toRangerServiceResource(): (serviceName={" + serviceName + "} RangerServiceResource={" + ret + "})"); - } + XXTagDefDao tagDefDao = daoManager.getXXTagDef(); - return ret; - } + for (String tagType : tagTypes) { + try { + XXTagDef xTagDef = tagDefDao.findByName(tagType); + RangerTagDef tagDef = xTagDef != null ? rangerTagDefService.getPopulatedViewObject(xTagDef) : null; - private static boolean SUPPORTS_TAGS_DEDUP_INITIALIZED = false; - private static boolean SUPPORTS_TAGS_DEDUP = false; + if (tagDef != null) { + RangerServiceTagsDeltaUtil.pruneUnusedAttributes(tagDef); - public static boolean isSupportsTagsDedup() { - if (!SUPPORTS_TAGS_DEDUP_INITIALIZED) { - RangerAdminConfig config = RangerAdminConfig.getInstance(); + ret.getTagDefinitions().put(tagDef.getId(), tagDef); + } else { + LOG.debug("TagDBStore.createServiceTagsDelta(): failed to load tagDef type={}", tagType); + } + } catch (Throwable t) { + LOG.debug("TagDBStore.createServiceTagsDelta(): failed to load tagDef type={}", tagType, t); + } + } - SUPPORTS_TAGS_DEDUP = config.getBoolean("ranger.admin" + RangerCommonConstants.RANGER_SUPPORTS_TAGS_DEDUP, RangerCommonConstants.RANGER_SUPPORTS_TAGS_DEDUP_DEFAULT); - SUPPORTS_TAGS_DEDUP_INITIALIZED = true; - } - return SUPPORTS_TAGS_DEDUP; - } + for (Long serviceResourceId : serviceResourceIds) { + // Check if serviceResourceId is part of any resource->id mapping + XXServiceResource xServiceResource = null; + + try { + xServiceResource = daoManager.getXXServiceResource().getById(serviceResourceId); + } catch (Throwable t) { + LOG.debug("TagDBStore.createServiceTagsDelta(): failed to read serviceResource id={}", serviceResourceId, t); + } + + final RangerServiceResource serviceResource; + + if (xServiceResource == null) { + serviceResource = new RangerServiceResource(); + + serviceResource.setId(serviceResourceId); + } else { + serviceResource = rangerServiceResourceService.getPopulatedViewObject(xServiceResource); + + if (StringUtils.isNotEmpty(xServiceResource.getTags())) { + try { + List tags = JsonUtils.jsonToObject(xServiceResource.getTags(), RangerServiceResourceService.duplicatedDataType); + + if (CollectionUtils.isNotEmpty(tags)) { + List resourceTagIds = new ArrayList<>(tags.size()); + + for (RangerTag tag : tags) { + RangerServiceTagsDeltaUtil.pruneUnusedAttributes(tag); + + if (!ret.getTags().containsKey(tag.getId())) { + ret.getTags().put(tag.getId(), tag); + } + + resourceTagIds.add(tag.getId()); + } + + ret.getResourceToTagIds().put(serviceResourceId, resourceTagIds); + } + } catch (JsonProcessingException e) { + LOG.error("Error occurred while processing json", e); + } + } + } + + RangerServiceTagsDeltaUtil.pruneUnusedAttributes(serviceResource); + + ret.getServiceResources().add(serviceResource); + + tagsChangeExtent = ServiceTags.TagsChangeExtent.SERVICE_RESOURCE; + } + + ret.setTagsChangeExtent(tagsChangeExtent); + } + } else { + LOG.debug("No tag-change-log records provided to createServiceTagsDelta()"); + } + + LOG.debug("<== TagDBStore.createServiceTagsDelta() : serviceTagsDelta={{}}", ret); + + return ret; + } + + private static void initStatics() { + if (!IS_SUPPORTS_TAG_DELTAS_INITIALIZED) { + RangerAdminConfig config = RangerAdminConfig.getInstance(); + + SUPPORTS_TAG_DELTAS = config.getBoolean("ranger.admin" + RangerCommonConstants.RANGER_ADMIN_SUFFIX_TAG_DELTA, RangerCommonConstants.RANGER_ADMIN_SUFFIX_TAG_DELTA_DEFAULT); + SUPPORTS_IN_PLACE_TAG_UPDATES = SUPPORTS_TAG_DELTAS && config.getBoolean("ranger.admin" + RangerCommonConstants.RANGER_ADMIN_SUFFIX_IN_PLACE_TAG_UPDATES, RangerCommonConstants.RANGER_ADMIN_SUFFIX_IN_PLACE_TAG_UPDATES_DEFAULT); + IS_SUPPORTS_TAG_DELTAS_INITIALIZED = true; + + LOG.info("SUPPORTS_TAG_DELTAS={}", SUPPORTS_TAG_DELTAS); + LOG.info("SUPPORTS_IN_PLACE_TAG_UPDATES={}", SUPPORTS_IN_PLACE_TAG_UPDATES); + } + } + + private void deleteTagDef(RangerTagDef tagDef) throws Exception { + if (tagDef != null) { + LOG.debug("Deleting tag-def [name={}; id={}]", tagDef.getName(), tagDef.getId()); + + List tagsByType = rangerTagService.getTagsByType(tagDef.getName()); + + if (CollectionUtils.isEmpty(tagsByType)) { + rangerTagDefService.delete(tagDef); + } else { + throw new Exception("Cannot delete tag-def: " + tagDef.getName() + ". " + tagsByType.size() + " tag instances for this tag-def exist"); + } + } + } } 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 index f19c049948..0686f37a51 100644 --- a/security-admin/src/main/java/org/apache/ranger/biz/UserMgr.java +++ b/security-admin/src/main/java/org/apache/ranger/biz/UserMgr.java @@ -19,18 +19,6 @@ package org.apache.ranger.biz; -import java.io.UnsupportedEncodingException; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.HashMap; -import java.util.List; - -import javax.persistence.Query; -import javax.servlet.http.HttpServletResponse; - import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang.StringUtils; import org.apache.ranger.authorization.hadoop.config.RangerAdminConfig; @@ -72,112 +60,121 @@ import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; +import javax.persistence.Query; +import javax.servlet.http.HttpServletResponse; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; + import static org.apache.ranger.service.RangerBaseModelService.OPERATION_UPDATE_CONTEXT; @Component public class UserMgr { + private static final Logger logger = LoggerFactory.getLogger(UserMgr.class); - private static final Logger logger = LoggerFactory.getLogger(UserMgr.class); - @Autowired - RangerDaoManager daoManager; + private static final int DEFAULT_PASSWORD_HISTORY_COUNT = 4; + private static final List DEFAULT_ROLE_LIST = new ArrayList<>(1); + private static final List VALID_ROLE_LIST = new ArrayList<>(2); - @Autowired - RESTErrorUtil restErrorUtil; + private final boolean isFipsEnabled; - @Autowired - StringUtil stringUtil; + @Autowired + RangerDaoManager daoManager; - @Autowired - SearchUtil searchUtil; + @Autowired + RESTErrorUtil restErrorUtil; - @Autowired - RangerBizUtil rangerBizUtil; + @Autowired + StringUtil stringUtil; - @Autowired - SessionMgr sessionMgr; + @Autowired + SearchUtil searchUtil; - @Autowired - XPortalUserService xPortalUserService; + @Autowired + RangerBizUtil rangerBizUtil; - @Autowired - XUserPermissionService xUserPermissionService; + @Autowired + SessionMgr sessionMgr; - @Autowired - XGroupPermissionService xGroupPermissionService; - - @Autowired - XUserMgr xUserMgr; + @Autowired + XPortalUserService xPortalUserService; - private final boolean isFipsEnabled; - private static final int DEFAULT_PASSWORD_HISTORY_COUNT = 4; - private int passwordHistoryCount = PropertiesUtil.getIntProperty("ranger.password.history.count", DEFAULT_PASSWORD_HISTORY_COUNT); - - String publicRoles[] = new String[] { RangerConstants.ROLE_USER, - RangerConstants.ROLE_OTHER }; + @Autowired + XUserPermissionService xUserPermissionService; - private static final List DEFAULT_ROLE_LIST = new ArrayList( - 1); + @Autowired + XGroupPermissionService xGroupPermissionService; - private static final List VALID_ROLE_LIST = new ArrayList(2); + @Autowired + XUserMgr xUserMgr; + + String[] publicRoles = new String[] {RangerConstants.ROLE_USER, RangerConstants.ROLE_OTHER}; + + private int passwordHistoryCount = PropertiesUtil.getIntProperty("ranger.password.history.count", DEFAULT_PASSWORD_HISTORY_COUNT); + + public UserMgr() { + logger.debug("UserMgr()"); + + this.isFipsEnabled = RangerAdminConfig.getInstance().isFipsEnabled(); + + if (passwordHistoryCount < 0) { + passwordHistoryCount = 0; + } + } + + public XXPortalUser createUser(VXPortalUser userProfile, int userStatus, Collection userRoleList) { + XXPortalUser user = mapVXPortalUserToXXPortalUser(userProfile); + + checkAdminAccess(); + + rangerBizUtil.blockAuditorRoleUser(); + + List userRolesList = new ArrayList<>(userRoleList); - static { - DEFAULT_ROLE_LIST.add(RangerConstants.ROLE_USER); - VALID_ROLE_LIST.add(RangerConstants.ROLE_SYS_ADMIN); - VALID_ROLE_LIST.add(RangerConstants.ROLE_USER); - VALID_ROLE_LIST.add(RangerConstants.ROLE_KEY_ADMIN); - VALID_ROLE_LIST.add(RangerConstants.ROLE_ADMIN_AUDITOR); - VALID_ROLE_LIST.add(RangerConstants.ROLE_KEY_ADMIN_AUDITOR); - } - - public UserMgr() { - if (logger.isDebugEnabled()) { - logger.debug("UserMgr()"); - } - this.isFipsEnabled = RangerAdminConfig.getInstance().isFipsEnabled(); - if (passwordHistoryCount < 0) { - passwordHistoryCount = 0; - } - } - - public XXPortalUser createUser(VXPortalUser userProfile, int userStatus, - Collection userRoleList) { - XXPortalUser user = mapVXPortalUserToXXPortalUser(userProfile); - checkAdminAccess(); - rangerBizUtil.blockAuditorRoleUser(); - List userRolesList = new ArrayList(userRoleList); xUserMgr.checkAccessRoles(userRolesList); - user = createUser(user, userStatus, userRoleList); - - return user; - } - - public XXPortalUser createUser(XXPortalUser user, int userStatus, - Collection userRoleList) { - user.setStatus(userStatus); - String saltEncodedpasswd = encrypt(user.getLoginId(), - user.getPassword()); - user.setPassword(saltEncodedpasswd); - user.setPasswordUpdatedTime(DateUtil.getUTCDate()); - daoManager.getXXPortalUser().create(user); - XXPortalUser xXPortalUser = daoManager.getXXPortalUser().findByLoginId(user.getLoginId()); - // Create the XXPortalUserRole entries for this user - if (xXPortalUser != null && xXPortalUser.getId() != null) { - if (CollectionUtils.isNotEmpty(userRoleList)) { - for (String userRole : userRoleList) { - addUserRole(xXPortalUser.getId(), userRole); - } - } - } else { - logger.error("XXPortalUser user creation failed for user=" + user.getLoginId()); - } - - return xXPortalUser; - } - - public XXPortalUser createUser(VXPortalUser userProfile, int userStatus) { - ArrayList roleList = new ArrayList(); - Collection reqRoleList = userProfile.getUserRoleList(); - if (reqRoleList != null && reqRoleList.size() > 0) { + + user = createUser(user, userStatus, userRoleList); + + return user; + } + + public XXPortalUser createUser(XXPortalUser user, int userStatus, Collection userRoleList) { + user.setStatus(userStatus); + + String saltEncodedpasswd = encrypt(user.getLoginId(), user.getPassword()); + + user.setPassword(saltEncodedpasswd); + user.setPasswordUpdatedTime(DateUtil.getUTCDate()); + + daoManager.getXXPortalUser().create(user); + + XXPortalUser xXPortalUser = daoManager.getXXPortalUser().findByLoginId(user.getLoginId()); + + // Create the XXPortalUserRole entries for this user + if (xXPortalUser != null && xXPortalUser.getId() != null) { + if (CollectionUtils.isNotEmpty(userRoleList)) { + for (String userRole : userRoleList) { + addUserRole(xXPortalUser.getId(), userRole); + } + } + } else { + logger.error("XXPortalUser user creation failed for user={}", user.getLoginId()); + } + + return xXPortalUser; + } + + public XXPortalUser createUser(VXPortalUser userProfile, int userStatus) { + ArrayList roleList = new ArrayList<>(); + Collection reqRoleList = userProfile.getUserRoleList(); + + if (reqRoleList != null && !reqRoleList.isEmpty()) { for (String role : reqRoleList) { if (role != null) { roleList.add(role); @@ -185,1250 +182,1381 @@ public XXPortalUser createUser(VXPortalUser userProfile, int userStatus) { roleList.add(RangerConstants.ROLE_USER); } } - } else { - roleList.add(RangerConstants.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); - rangerBizUtil.blockAuditorRoleUser(); - - VXPortalUser existing = xPortalUserService.populateViewBean(gjUser); - - // Selectively update fields - - // Allowing email address update even when its set to empty. - String emailAddress = userProfile.getEmailAddress(); - if (stringUtil.isEmpty(emailAddress)) { - userProfile.setEmailAddress(null); - } 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); - } - } else { - userProfile.setEmailAddress(emailAddress); - } - } else { - throw restErrorUtil.createRESTException("Please provide valid email address.", MessageEnums.INVALID_INPUT_DATA); - } - } - - // firstName - if("null".equalsIgnoreCase(userProfile.getFirstName())){ - userProfile.setFirstName(""); - } - if (!stringUtil.isEmpty(userProfile.getFirstName()) && !userProfile.getFirstName().equals(gjUser.getFirstName())) { - userProfile.setFirstName(stringUtil.toCamelCaseAllWords(userProfile.getFirstName())); - } - if("null".equalsIgnoreCase(userProfile.getLastName())){ - userProfile.setLastName(""); - } - if (!stringUtil.isEmpty(userProfile.getLastName()) && !userProfile.getLastName().equals(gjUser.getLastName())) { - userProfile.setLastName(stringUtil.toCamelCaseAllWords(userProfile.getLastName())); - } - - // publicScreenName - if (userProfile.getFirstName() != null && userProfile.getLastName() != null && !userProfile.getFirstName().trim().isEmpty() - && !userProfile.getLastName().trim().isEmpty()) { - userProfile.setPublicScreenName(userProfile.getFirstName() + " " + userProfile.getLastName()); - } else { - userProfile.setPublicScreenName(gjUser.getLoginId()); - } - - if (rangerBizUtil.isKeyAdmin() && userProfile.getStatus() != gjUser.getStatus()) { - throw restErrorUtil.createRESTException("Status update is not permitted to logged in user.", MessageEnums.INVALID_INPUT_DATA); - } - - // userRoleList - updateRoles(userProfile.getId(), userProfile.getUserRoleList()); - - List trxLogList = xPortalUserService.getTransactionLog(userProfile, existing, OPERATION_UPDATE_CONTEXT); - userProfile.setPassword(gjUser.getPassword()); - xPortalUserService.updateResource(userProfile); - sessionMgr.resetUserSessionForProfiles(ContextUtil.getCurrentUserSession()); - rangerBizUtil.createTrxLog(trxLogList); - return gjUser; - } - - public boolean updateRoles(Long userId, Collection rolesList) { - boolean rolesUpdated = false; - if (rolesList == null || rolesList.size() == 0) { - return false; - } - List stringRolesList = new ArrayList(); - for (String userRole : rolesList) { - if(!VALID_ROLE_LIST.contains(userRole.toUpperCase())){ - throw restErrorUtil.createRESTException("Invalid user role, please provide valid user role.",MessageEnums.INVALID_INPUT_DATA); - } - stringRolesList.add(userRole); - } - xUserMgr.checkAccessRoles(stringRolesList); - rangerBizUtil.blockAuditorRoleUser(); - // Let's first delete old roles - List 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 vStringRolesList - */ - public void setUserRoles(Long userId, List vStringRolesList) { - List stringRolesList = new ArrayList(); - for (VXString vXString : vStringRolesList) { - stringRolesList.add(vXString.getValue()); - } - xUserMgr.checkAccessRoles(stringRolesList); - rangerBizUtil.blockAuditorRoleUser(); - VXPortalUser oldUserProfile=getUserProfile(userId); - xUserMgr.updateUserRolesPermissions(oldUserProfile, stringRolesList); - } - - /** - * @param pwdChange - * @return - */ - public VXResponse changePassword(VXPasswordChange pwdChange) { - VXResponse ret = new VXResponse(); - // Get the user of whom we want to change the password - XXPortalUser gjUser = daoManager.getXXPortalUser().findByLoginId(pwdChange.getLoginId()); - if (gjUser == null) { - logger.warn("SECURITY:changePassword(). User not found. LoginId="+ pwdChange.getLoginId()); - throw restErrorUtil.createRESTException("serverMsg.userMgrInvalidUser",MessageEnums.DATA_NOT_FOUND, null, null,pwdChange.getLoginId()); - } + } else { + roleList.add(RangerConstants.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); + + rangerBizUtil.blockAuditorRoleUser(); + + VXPortalUser existing = xPortalUserService.populateViewBean(gjUser); + + // Selectively update fields + + // Allowing email address update even when its set to empty. + String emailAddress = userProfile.getEmailAddress(); + + if (stringUtil.isEmpty(emailAddress)) { + userProfile.setEmailAddress(null); + } 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); + } + } else { + userProfile.setEmailAddress(emailAddress); + } + } else { + throw restErrorUtil.createRESTException("Please provide valid email address.", MessageEnums.INVALID_INPUT_DATA); + } + } + + // firstName + if ("null".equalsIgnoreCase(userProfile.getFirstName())) { + userProfile.setFirstName(""); + } + + if (!stringUtil.isEmpty(userProfile.getFirstName()) && !userProfile.getFirstName().equals(gjUser.getFirstName())) { + userProfile.setFirstName(stringUtil.toCamelCaseAllWords(userProfile.getFirstName())); + } + + if ("null".equalsIgnoreCase(userProfile.getLastName())) { + userProfile.setLastName(""); + } + + if (!stringUtil.isEmpty(userProfile.getLastName()) && !userProfile.getLastName().equals(gjUser.getLastName())) { + userProfile.setLastName(stringUtil.toCamelCaseAllWords(userProfile.getLastName())); + } + + // publicScreenName + if (userProfile.getFirstName() != null && userProfile.getLastName() != null && !userProfile.getFirstName().trim().isEmpty() && !userProfile.getLastName().trim().isEmpty()) { + userProfile.setPublicScreenName(userProfile.getFirstName() + " " + userProfile.getLastName()); + } else { + userProfile.setPublicScreenName(gjUser.getLoginId()); + } + + if (rangerBizUtil.isKeyAdmin() && userProfile.getStatus() != gjUser.getStatus()) { + throw restErrorUtil.createRESTException("Status update is not permitted to logged in user.", MessageEnums.INVALID_INPUT_DATA); + } + + // userRoleList + updateRoles(userProfile.getId(), userProfile.getUserRoleList()); + + List trxLogList = xPortalUserService.getTransactionLog(userProfile, existing, OPERATION_UPDATE_CONTEXT); + + userProfile.setPassword(gjUser.getPassword()); + + xPortalUserService.updateResource(userProfile); + + sessionMgr.resetUserSessionForProfiles(ContextUtil.getCurrentUserSession()); + + rangerBizUtil.createTrxLog(trxLogList); + + return gjUser; + } + + public boolean updateRoles(Long userId, Collection rolesList) { + boolean rolesUpdated = false; + + if (rolesList == null || rolesList.isEmpty()) { + return false; + } + + List stringRolesList = new ArrayList<>(); + + for (String userRole : rolesList) { + if (!VALID_ROLE_LIST.contains(userRole.toUpperCase())) { + throw restErrorUtil.createRESTException("Invalid user role, please provide valid user role.", MessageEnums.INVALID_INPUT_DATA); + } + + stringRolesList.add(userRole); + } + + xUserMgr.checkAccessRoles(stringRolesList); + + rangerBizUtil.blockAuditorRoleUser(); + + // Let's first delete old roles + List 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 vStringRolesList + */ + public void setUserRoles(Long userId, List vStringRolesList) { + List stringRolesList = new ArrayList<>(); + + for (VXString vXString : vStringRolesList) { + stringRolesList.add(vXString.getValue()); + } + + xUserMgr.checkAccessRoles(stringRolesList); + + rangerBizUtil.blockAuditorRoleUser(); + + VXPortalUser oldUserProfile = getUserProfile(userId); + + xUserMgr.updateUserRolesPermissions(oldUserProfile, stringRolesList); + } + + /** + * @param pwdChange + * @return + */ + public VXResponse changePassword(VXPasswordChange pwdChange) { + VXResponse ret = new VXResponse(); + + // Get the user of whom we want to change the password + XXPortalUser gjUser = daoManager.getXXPortalUser().findByLoginId(pwdChange.getLoginId()); + + if (gjUser == null) { + logger.warn("SECURITY:changePassword(). User not found. LoginId={}", pwdChange.getLoginId()); + + throw restErrorUtil.createRESTException("serverMsg.userMgrInvalidUser", MessageEnums.DATA_NOT_FOUND, null, null, pwdChange.getLoginId()); + } + if (gjUser.getUserSource() == RangerCommonEnums.USER_EXTERNAL) { - logger.info("SECURITY:changePassword().Ranger External Users cannot change password. LoginId=" + pwdChange.getLoginId()); + logger.info("SECURITY:changePassword().Ranger External Users cannot change password. LoginId={}", pwdChange.getLoginId()); + VXResponse vXResponse = new VXResponse(); + vXResponse.setStatusCode(HttpServletResponse.SC_FORBIDDEN); vXResponse.setMsgDesc("SECURITY:changePassword().Ranger External Users cannot change password. LoginId=" + pwdChange.getLoginId()); + throw restErrorUtil.generateRESTException(vXResponse); } - checkAccess(gjUser); - String currentPassword = gjUser.getPassword(); - //check current password and provided old password is same or not - if (this.isFipsEnabled) { - if (!isPasswordValid(pwdChange.getLoginId(), currentPassword, pwdChange.getOldPassword())) { - logger.info("changePassword(). Invalid old password. LoginId="+ pwdChange.getLoginId()); - throw restErrorUtil.createRESTException("serverMsg.userMgrOldPassword",MessageEnums.INVALID_INPUT_DATA, null, null,pwdChange.getLoginId()); - } - } else { - String encryptedOldPwd = encrypt(pwdChange.getLoginId(),pwdChange.getOldPassword()); - if (!stringUtil.equals(encryptedOldPwd, gjUser.getPassword())) { - logger.info("changePassword(). Invalid old password. LoginId="+ pwdChange.getLoginId()); - throw restErrorUtil.createRESTException("serverMsg.userMgrOldPassword",MessageEnums.INVALID_INPUT_DATA, null, null,pwdChange.getLoginId()); - } - } - //validate new password - if (!stringUtil.validatePassword(pwdChange.getUpdPassword(),new String[] { gjUser.getFirstName(),gjUser.getLastName(), gjUser.getLoginId()})) { - logger.warn("SECURITY:changePassword(). Invalid new password. LoginId="+ pwdChange.getLoginId()); - throw restErrorUtil.createRESTException("serverMsg.userMgrNewPassword",MessageEnums.INVALID_PASSWORD, null, null,pwdChange.getLoginId()); - } - - String encryptedNewPwd = encrypt(pwdChange.getLoginId(),pwdChange.getUpdPassword()); - String oldPasswordStr = gjUser.getOldPasswords(); - List oldPasswords; - - if (StringUtils.isNotEmpty(oldPasswordStr)) { - oldPasswords = new ArrayList<>(Arrays.asList(oldPasswordStr.split(","))); - } else { - oldPasswords = new ArrayList<>(); - } - oldPasswords.add(gjUser.getPassword()); - while (oldPasswords.size() > this.passwordHistoryCount) { - oldPasswords.remove(0); - } - boolean isNewPasswordDifferent = oldPasswords.isEmpty(); - for (String oldPassword : oldPasswords) { - if (this.isFipsEnabled) { - isNewPasswordDifferent = isNewPasswordDifferent(pwdChange.getLoginId(), oldPassword, encryptedNewPwd); - } else { - isNewPasswordDifferent = !encryptedNewPwd.equals(oldPassword); - } - if (!isNewPasswordDifferent){ - break; - } - } - if (isNewPasswordDifferent) { - xPortalUserService.createTransactionLog(new XXTrxLogV2(AppConstants.CLASS_TYPE_PASSWORD_CHANGE, pwdChange.getId(), pwdChange.getLoginId(), "password change"), "Password", currentPassword, encryptedNewPwd); - - gjUser.setPassword(encryptedNewPwd); - updateOldPasswords(gjUser, oldPasswords); - gjUser = daoManager.getXXPortalUser().update(gjUser); - ret.setMsgDesc("Password successfully updated"); - ret.setStatusCode(VXResponse.STATUS_SUCCESS); - } else { - logger.error("SECURITY:changePassword(). Password update failed. LoginId="+ pwdChange.getLoginId()); - 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; - } - - private void updateOldPasswords(XXPortalUser gjUser, List oldPasswords) { - String oldPasswordStr = CollectionUtils.isNotEmpty(oldPasswords) ? StringUtils.join(oldPasswords, ",") : null; - gjUser.setOldPasswords(oldPasswordStr); - gjUser.setPasswordUpdatedTime(DateUtil.getUTCDate()); - } - - /** - * @param gjUser - * @param changeEmail - * @return - */ - public VXPortalUser changeEmailAddress(XXPortalUser gjUser, VXPasswordChange changeEmail) { - checkAccess(gjUser); - if (StringUtils.isEmpty(changeEmail.getEmailAddress())) { - changeEmail.setEmailAddress(null); - } - - if (!StringUtils.isEmpty(changeEmail.getEmailAddress()) && !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 (this.isFipsEnabled) { - if (!isPasswordValid(changeEmail.getLoginId(), gjUser.getPassword(), changeEmail.getOldPassword())) { - logger.info("changeEmailAddress(). Invalid password. changeEmail=" + changeEmail); - throw restErrorUtil.createRESTException("serverMsg.userMgrWrongPassword", - MessageEnums.OPER_NO_PERMISSION, null, null, "" + changeEmail); - } - } else { - String encryptedOldPwd = encrypt(gjUser.getLoginId(), changeEmail.getOldPassword()); - if (!stringUtil.equals(encryptedOldPwd, gjUser.getPassword())) { - encryptedOldPwd = encryptWithOlderAlgo(gjUser.getLoginId(), changeEmail.getOldPassword()); - 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())); - - String saltEncodedpasswd = encrypt(gjUser.getLoginId(), changeEmail.getOldPassword()); - if (gjUser.getUserSource() == RangerCommonEnums.USER_APP) { - gjUser.setPassword(saltEncodedpasswd); - } else if (gjUser.getUserSource() == RangerCommonEnums.USER_EXTERNAL) { - gjUser.setPassword(gjUser.getPassword()); - } - daoManager.getXXPortalUser().update(gjUser); - return mapXXPortalUserVXPortalUser(gjUser); - } - - /** - * @param gjUser - */ - public VXPortalUser deactivateUser(XXPortalUser gjUser) { - checkAdminAccess(); - rangerBizUtil.blockAuditorRoleUser(); - if (gjUser != null - && gjUser.getStatus() != RangerConstants.ACT_STATUS_DEACTIVATED) { - logger.info("Marking user " + gjUser.getLoginId() + " as deleted"); - gjUser.setStatus(RangerConstants.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) { - checkAccess(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()); - if("null".equalsIgnoreCase(userProfile.getFirstName())){ - userProfile.setFirstName(""); - } - gjUser.setFirstName(userProfile.getFirstName()); - if("null".equalsIgnoreCase(userProfile.getLastName())){ - userProfile.setLastName(""); - } - gjUser.setLastName(userProfile.getLastName()); - if (userProfile.getLoginId() == null - || userProfile.getLoginId().trim().isEmpty() - || "null".equalsIgnoreCase(userProfile.getLoginId())) { - throw restErrorUtil.createRESTException( - "LoginId should not be null or blank, It is", - MessageEnums.INVALID_INPUT_DATA); - } - gjUser.setLoginId(userProfile.getLoginId()); - gjUser.setPassword(userProfile.getPassword()); - gjUser.setUserSource(userProfile.getUserSource()); - gjUser.setPublicScreenName(userProfile.getPublicScreenName()); - gjUser.setOtherAttributes(userProfile.getOtherAttributes()); - gjUser.setSyncSource(userProfile.getSyncSource()); - gjUser.setStatus(userProfile.getStatus()); - if (userProfile.getFirstName() != null - && userProfile.getLastName() != null - && !userProfile.getFirstName().trim().isEmpty() - && !userProfile.getLastName().trim().isEmpty()) { - gjUser.setPublicScreenName(userProfile.getFirstName() + " " - + userProfile.getLastName()); - } else { - gjUser.setPublicScreenName(userProfile.getLoginId()); - } - return gjUser; - } - - /** - * @param user - * @return - */ - public VXPortalUser mapXXPortalUserToVXPortalUser(XXPortalUser user, - Collection 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.isKeyAdmin() - || sess.getXXPortalUser().getId().equals(user.getId())) { - if (userRoleList == null) { - userRoleList = new ArrayList(); - List gjUserRoleList = daoManager - .getXXPortalUserRole().findByParentId(user.getId()); - - for (XXPortalUserRole userRole : gjUserRoleList) { - userRoleList.add(userRole.getUserRole()); - } - } - - userProfile.setUserRoleList(userRoleList); - } - userProfile.setUserSource(user.getUserSource()); - return userProfile; - } - - protected void gjUserToUserProfile(XXPortalUser user, VXPortalUser userProfile) { - UserSessionBase sess = ContextUtil.getCurrentUserSession(); - if (sess == null) { - return; - } - - // Admin - if (sess.isUserAdmin() || sess.isKeyAdmin() - || sess.getXXPortalUser().getId().equals(user.getId())) { - userProfile.setLoginId(user.getLoginId()); - userProfile.setStatus(user.getStatus()); - userProfile.setUserRoleList(new ArrayList()); - - String emailAddress = user.getEmailAddress(); - - if (emailAddress != null && stringUtil.validateEmail(emailAddress)) { - userProfile.setEmailAddress(user.getEmailAddress()); - } - - userProfile.setUserSource(sess.getAuthProvider()); - - List gjUserRoleList = daoManager - .getXXPortalUserRole().findByParentId(user.getId()); - - for (XXPortalUserRole gjUserRole : gjUserRoleList) { - userProfile.getUserRoleList().add(gjUserRole.getUserRole()); - } - - userProfile.setId(user.getId()); - if (sess.isUserAdmin() || sess.getXXPortalUser().getId().equals(user.getId())) { - List xUserPermissions = daoManager.getXXUserPermission().findByUserPermissionIdAndIsAllowed(userProfile.getId()); - List xxGroupPermissions = daoManager.getXXGroupPermission().findbyVXPortalUserId(userProfile.getId()); - List groupPermissions = new ArrayList(); - List vxUserPermissions = new ArrayList(); - for (XXGroupPermission xxGroupPermission : xxGroupPermissions) { - VXGroupPermission groupPermission = xGroupPermissionService.populateViewBean(xxGroupPermission); - groupPermission.setModuleName(daoManager.getXXModuleDef().findByModuleId(groupPermission.getModuleId()).getModule()); - groupPermissions.add(groupPermission); - } - for (XXUserPermission xUserPermission : xUserPermissions) { - VXUserPermission vXUserPermission = xUserPermissionService.populateViewBean(xUserPermission); - vXUserPermission.setModuleName(daoManager.getXXModuleDef().findByModuleId(vXUserPermission.getModuleId()).getModule()); - vxUserPermissions.add(vXUserPermission); - } - userProfile.setGroupPermissions(groupPermissions); - userProfile.setUserPermList(vxUserPermissions); - } - userProfile.setFirstName(user.getFirstName()); - userProfile.setLastName(user.getLastName()); - userProfile.setPublicScreenName(user.getPublicScreenName()); - } - - } - - /** - * 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 getRolesForUser(XXPortalUser user) { - Collection roleList = new ArrayList(); - - Collection 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 objectList = new ArrayList(); - 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(); - int resultSize = count!=null ? count.intValue() :0; - if (resultSize == 0) { - return returnList; - } - - // Get actual data - - // Add sort by - String sortBy = searchCriteria.getSortBy(); - String querySortBy = "u.loginId"; - if (sortBy != null && !sortBy.trim().isEmpty()) { - 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 - int adminCount = 0; - for (Object object : resultList) { - XXPortalUser gjUser = (XXPortalUser) object; - VXPortalUser userProfile = new VXPortalUser(); - gjUserToUserProfile(gjUser, userProfile); - if (rangerBizUtil.isKeyAdmin() && (userProfile.getUserRoleList().contains(RangerConstants.ROLE_SYS_ADMIN) || userProfile.getUserRoleList().contains(RangerConstants.ROLE_ADMIN_AUDITOR))) { - adminCount++; - continue; - } else { - objectList.add(userProfile); - } - } - - returnList.setResultSize(resultSize-adminCount); - 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 - */ - protected Query createUserSearchQuery(String queryStr, String sortClause, - SearchCriteria searchCriteria) { - HashMap paramList = searchCriteria.getParamList(); - - String whereClause = "WHERE 1 = 1 "; - - // roles - @SuppressWarnings("unchecked") - List roleList = (List) 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 statusList = (List) 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 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 (RangerConstants.ROLE_USER.equals(gjUserRole.getUserRole())) { - * return false; } - */ - boolean publicRole = false; - for (String publicRoleStr : publicRoles) { - if (publicRoleStr.equalsIgnoreCase(gjUserRole.getUserRole())) { - publicRole = true; - break; - } - } - if (!publicRole) { - UserSessionBase sess = ContextUtil.getCurrentUserSession(); - if (sess == null || (!sess.isUserAdmin() && !sess.isKeyAdmin())) { - return false; - } - } - - daoManager.getXXPortalUserRole().remove(gjUserRole.getId()); - return true; - } - - public XXPortalUserRole addUserRole(Long userId, String userRole) { - List roleList = daoManager.getXXPortalUserRole() - .findByUserId(userId); - boolean publicRole = false; - for (String publicRoleStr : publicRoles) { - if (publicRoleStr.equalsIgnoreCase(userRole)) { - publicRole = true; - break; - } - } - if (!publicRole) { - UserSessionBase sess = ContextUtil.getCurrentUserSession(); - if (sess == null) { - return null; - } - // Admin - if (!sess.isUserAdmin() && !sess.isKeyAdmin()) { - logger.error( - "SECURITY WARNING: User trying to add non public role. userId=" - + userId + ", role=" + userRole + ", session=" - + sess.toString(), new Throwable()); - return null; - } - rangerBizUtil.blockAuditorRoleUser(); - } - - for (XXPortalUserRole gjUserRole : roleList) { - if (userRole.equalsIgnoreCase(gjUserRole.getUserRole())) { - return gjUserRole; - } - } - XXPortalUserRole userRoleObj = new XXPortalUserRole(); - if(!VALID_ROLE_LIST.contains(userRole.toUpperCase())){ - throw restErrorUtil.createRESTException("Invalid user role, please provide valid user role.",MessageEnums.INVALID_INPUT_DATA); - } - userRoleObj.setUserRole(userRole.toUpperCase()); - userRoleObj.setUserId(userId); - userRoleObj.setStatus(RangerConstants.STATUS_ENABLED); - daoManager.getXXPortalUserRole().create(userRoleObj); - - // If role is not OTHER, then remove OTHER - if (!RangerConstants.ROLE_OTHER.equalsIgnoreCase(userRole)) { - deleteUserRole(userId, RangerConstants.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"); - } - VXPortalUser requestedVXUser = getUserProfileByLoginId(gjUser.getLoginId()); - if (requestedVXUser !=null && CollectionUtils.isNotEmpty(requestedVXUser.getUserRoleList()) && hasAccessToGetUserInfo(requestedVXUser)) { - return; - } - logger.info("Logged-In user is not allowed to access requested user data."); - throw restErrorUtil.createRESTException(HttpServletResponse.SC_FORBIDDEN, "Logged-In user is not allowed to access requested user data", true); - - } - - public String encrypt(String loginId, String password) { - String saltEncodedpasswd = ""; - if (this.isFipsEnabled) { - try { - Pbkdf2PasswordEncoderCust pbkdf2Encoder = new Pbkdf2PasswordEncoderCust(loginId); - pbkdf2Encoder.setEncodeHashAsBase64(true); - if (password != null) { - saltEncodedpasswd = pbkdf2Encoder.encode(password); - } - } catch (Throwable t) { - logger.error("Password doesn't meet requirements"); - throw restErrorUtil.createRESTException("Invalid password", - MessageEnums.INVALID_PASSWORD, null, null, "" - + loginId); - } - } else { - String sha256PasswordUpdateDisable = PropertiesUtil.getProperty("ranger.sha256Password.update.disable", "false"); - - if ("false".equalsIgnoreCase(sha256PasswordUpdateDisable)) { - saltEncodedpasswd = encodeString(password, loginId, "SHA-256"); - } else { - saltEncodedpasswd = encodeString(password, loginId, "MD5"); - } - } - - return saltEncodedpasswd; - } - - public String encryptWithOlderAlgo(String loginId, String password) { - String saltEncodedpasswd = ""; - - saltEncodedpasswd = encodeString(password, loginId, "MD5"); - - return saltEncodedpasswd; - } - - public VXPortalUser createUser(VXPortalUser userProfile) { - checkAdminAccess(); - rangerBizUtil.blockAuditorRoleUser(); - XXPortalUser xXPortalUser = this.createUser(userProfile, - RangerCommonEnums.STATUS_ENABLED); - return mapXXPortalUserVXPortalUser(xXPortalUser); - } - - public VXPortalUser createDefaultAccountUser(VXPortalUser userProfile) { - if (userProfile.getUserSource() != RangerCommonEnums.USER_FEDERATED) { - if (StringUtils.isBlank(userProfile.getPassword())) { - userProfile.setUserSource(RangerCommonEnums.USER_EXTERNAL); - } - } - // access control - checkAdminAccess(); - rangerBizUtil.blockAuditorRoleUser(); - logger.info("create:" + userProfile.getLoginId()); - XXPortalUser xXPortalUser = null; - Collection existingRoleList = null; - Collection reqRoleList = 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.trim().isEmpty()) { - xXPortalUser = this.findByEmailAddress(emailAddress); - if (xXPortalUser == null) { - xXPortalUser = this.createUser(userProfile, - RangerCommonEnums.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 { - userProfile.setEmailAddress(null); - xXPortalUser = this.createUser(userProfile, - RangerCommonEnums.STATUS_ENABLED); - } - } else { //NOPMD - /* - * 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); - */ - } + + checkAccess(gjUser); + + String currentPassword = gjUser.getPassword(); + + //check current password and provided old password is same or not + if (this.isFipsEnabled) { + if (!isPasswordValid(pwdChange.getLoginId(), currentPassword, pwdChange.getOldPassword())) { + logger.info("changePassword(). Invalid old password. LoginId={}", pwdChange.getLoginId()); + + throw restErrorUtil.createRESTException("serverMsg.userMgrOldPassword", MessageEnums.INVALID_INPUT_DATA, null, null, pwdChange.getLoginId()); + } + } else { + String encryptedOldPwd = encrypt(pwdChange.getLoginId(), pwdChange.getOldPassword()); + + if (!stringUtil.equals(encryptedOldPwd, gjUser.getPassword())) { + logger.info("changePassword(). Invalid old password. LoginId={}", pwdChange.getLoginId()); + + throw restErrorUtil.createRESTException("serverMsg.userMgrOldPassword", MessageEnums.INVALID_INPUT_DATA, null, null, pwdChange.getLoginId()); + } } - VXPortalUser userProfileRes = null; - if (xXPortalUser != null) { - userProfileRes = mapXXPortalUserToVXPortalUserForDefaultAccount(xXPortalUser); - if (userProfile.getUserRoleList() != null - && userProfile.getUserRoleList().size() > 0 - && ((List) userProfile.getUserRoleList()).get(0) != null) { - reqRoleList = userProfile.getUserRoleList(); - existingRoleList = this.getRolesByLoginId(loginId); - XXPortalUser xxPortalUser = daoManager.getXXPortalUser() - .findByLoginId(userProfile.getLoginId()); - if (xxPortalUser != null - && xxPortalUser.getUserSource() == RangerCommonEnums.USER_EXTERNAL) { - userProfileRes = updateRoleForExternalUsers(reqRoleList, - existingRoleList, userProfileRes); - } + //validate new password + if (!stringUtil.validatePassword(pwdChange.getUpdPassword(), new String[] {gjUser.getFirstName(), gjUser.getLastName(), gjUser.getLoginId()})) { + logger.warn("SECURITY:changePassword(). Invalid new password. LoginId={}", pwdChange.getLoginId()); + + throw restErrorUtil.createRESTException("serverMsg.userMgrNewPassword", MessageEnums.INVALID_PASSWORD, null, null, pwdChange.getLoginId()); + } + + String encryptedNewPwd = encrypt(pwdChange.getLoginId(), pwdChange.getUpdPassword()); + String oldPasswordStr = gjUser.getOldPasswords(); + List oldPasswords; + + if (StringUtils.isNotEmpty(oldPasswordStr)) { + oldPasswords = new ArrayList<>(Arrays.asList(oldPasswordStr.split(","))); + } else { + oldPasswords = new ArrayList<>(); + } + + oldPasswords.add(gjUser.getPassword()); + + while (oldPasswords.size() > this.passwordHistoryCount) { + oldPasswords.remove(0); + } + + boolean isNewPasswordDifferent = oldPasswords.isEmpty(); + + for (String oldPassword : oldPasswords) { + if (this.isFipsEnabled) { + isNewPasswordDifferent = isNewPasswordDifferent(pwdChange.getLoginId(), oldPassword, encryptedNewPwd); + } else { + isNewPasswordDifferent = !encryptedNewPwd.equals(oldPassword); + } + + if (!isNewPasswordDifferent) { + break; } } - return userProfileRes; + + if (isNewPasswordDifferent) { + xPortalUserService.createTransactionLog(new XXTrxLogV2(AppConstants.CLASS_TYPE_PASSWORD_CHANGE, pwdChange.getId(), pwdChange.getLoginId(), "password change"), "Password", currentPassword, encryptedNewPwd); + + gjUser.setPassword(encryptedNewPwd); + updateOldPasswords(gjUser, oldPasswords); + + gjUser = daoManager.getXXPortalUser().update(gjUser); + + ret.setMsgDesc("Password successfully updated"); + ret.setStatusCode(VXResponse.STATUS_SUCCESS); + } else { + logger.error("SECURITY:changePassword(). Password update failed. LoginId={}", pwdChange.getLoginId()); + + ret.setMsgDesc("Password update failed"); + ret.setStatusCode(VXResponse.STATUS_ERROR); + + throw restErrorUtil.createRESTException("serverMsg.userMgrOldPassword", MessageEnums.INVALID_INPUT_DATA, gjUser.getId(), "password", gjUser.toString()); } - protected VXPortalUser updateRoleForExternalUsers( - Collection reqRoleList, - Collection existingRoleList, VXPortalUser userProfileRes) { - UserSessionBase session = ContextUtil.getCurrentUserSession(); - if (session != null && session.getXXPortalUser() != null && session.getXXPortalUser().getLoginId() != null && "rangerusersync".equals(session.getXXPortalUser().getLoginId()) - && reqRoleList != null && !reqRoleList.isEmpty() - && existingRoleList != null && !existingRoleList.isEmpty()) { - if (!reqRoleList.equals(existingRoleList)) { - userProfileRes.setUserRoleList(reqRoleList); - userProfileRes.setUserSource(RangerCommonEnums.USER_EXTERNAL); - List xuserPermissionList = daoManager - .getXXUserPermission().findByUserPermissionId( - userProfileRes.getId()); - if (xuserPermissionList != null - && xuserPermissionList.size() > 0) { - for (XXUserPermission xXUserPermission : xuserPermissionList) { - if (xXUserPermission != null) { - try { - xUserPermissionService - .deleteResource(xXUserPermission - .getId()); - } catch (Exception e) { - logger.error(e.getMessage()); - } - } + return ret; + } - } - } - updateUser(userProfileRes); + /** + * @param gjUser + * @param changeEmail + * @return + */ + public VXPortalUser changeEmailAddress(XXPortalUser gjUser, VXPasswordChange changeEmail) { + checkAccess(gjUser); + + if (StringUtils.isEmpty(changeEmail.getEmailAddress())) { + changeEmail.setEmailAddress(null); + } + + if (!StringUtils.isEmpty(changeEmail.getEmailAddress()) && !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 (this.isFipsEnabled) { + if (!isPasswordValid(changeEmail.getLoginId(), gjUser.getPassword(), changeEmail.getOldPassword())) { + logger.info("changeEmailAddress(). Invalid password. changeEmail={}", changeEmail); + + throw restErrorUtil.createRESTException("serverMsg.userMgrWrongPassword", MessageEnums.OPER_NO_PERMISSION, null, null, "" + changeEmail); } } else { - if (logger.isDebugEnabled()) { - logger.debug("Permission" - + " denied. LoggedInUser=" - + (session != null && session.getXXPortalUser() != null ? session.getXXPortalUser().getId() - : "") - + " isn't permitted to perform the action."); + String encryptedOldPwd = encrypt(gjUser.getLoginId(), changeEmail.getOldPassword()); + + if (!stringUtil.equals(encryptedOldPwd, gjUser.getPassword())) { + encryptedOldPwd = encryptWithOlderAlgo(gjUser.getLoginId(), changeEmail.getOldPassword()); + + 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); + } } } - return userProfileRes; + + // Normalize email. Make it lower case + gjUser.setEmailAddress(stringUtil.normalizeEmail(changeEmail.getEmailAddress())); + + String saltEncodedpasswd = encrypt(gjUser.getLoginId(), changeEmail.getOldPassword()); + + if (gjUser.getUserSource() == RangerCommonEnums.USER_APP) { + gjUser.setPassword(saltEncodedpasswd); + } else if (gjUser.getUserSource() == RangerCommonEnums.USER_EXTERNAL) { + gjUser.setPassword(gjUser.getPassword()); + } + + daoManager.getXXPortalUser().update(gjUser); + + return mapXXPortalUserVXPortalUser(gjUser); } - protected VXPortalUser mapXXPortalUserToVXPortalUserForDefaultAccount( - XXPortalUser user) { - - VXPortalUser userProfile = new VXPortalUser(); - - userProfile.setLoginId(user.getLoginId()); - userProfile.setEmailAddress(user.getEmailAddress()); - userProfile.setStatus(user.getStatus()); - userProfile.setUserRoleList(new ArrayList()); - userProfile.setId(user.getId()); - userProfile.setFirstName(user.getFirstName()); - userProfile.setLastName(user.getLastName()); - userProfile.setPublicScreenName(user.getPublicScreenName()); - userProfile.setOtherAttributes(user.getOtherAttributes()); - userProfile.setSyncSource(user.getSyncSource()); - List 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 (xXPortalUser == null) { - return null; - } - - 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); - if (xXPortalUser.getUserSource() != RangerCommonEnums.USER_EXTERNAL) { - String oldPasswordsStr = xXPortalUser.getOldPasswords(); - List oldPasswords; - if (StringUtils.isNotEmpty(oldPasswordsStr)) { - oldPasswords = new ArrayList<>(Arrays.asList(oldPasswordsStr.split(","))); - } else { - oldPasswords = new ArrayList<>(); - } - oldPasswords.add(encryptedNewPwd); - updateOldPasswords(xXPortalUser, oldPasswords); - xXPortalUser.setPassword(encryptedNewPwd); - } - xXPortalUser = daoManager.getXXPortalUser().update(xXPortalUser); - } - return xXPortalUser; - } - @Transactional(readOnly = false, propagation = Propagation.REQUIRED) - public XXPortalUser updatePasswordInSHA256(String userName,String userPassword,boolean logAudits) { - if (userName == null || userPassword == null - || userName.trim().isEmpty() || userPassword.trim().isEmpty()){ - return null; - } - - XXPortalUser xXPortalUser = this.findByLoginId(userName); - - if (xXPortalUser == null) { - return null; - } - String dbOldPwd =xXPortalUser.getPassword(); - String encryptedNewPwd = encrypt(xXPortalUser.getLoginId(),userPassword); - if (xXPortalUser.getUserSource() != RangerCommonEnums.USER_EXTERNAL) { - xXPortalUser.setPassword(encryptedNewPwd); - } + /** + * @param gjUser + */ + public VXPortalUser deactivateUser(XXPortalUser gjUser) { + checkAdminAccess(); - xXPortalUser = daoManager.getXXPortalUser().update(xXPortalUser); - if(xXPortalUser!=null && logAudits){ - String dbNewPwd=xXPortalUser.getPassword(); - if (!dbOldPwd.equals(dbNewPwd)) { - xPortalUserService.createTransactionLog(new XXTrxLogV2(AppConstants.CLASS_TYPE_PASSWORD_CHANGE, xXPortalUser.getId(), xXPortalUser.getLoginId(), "password change"), "Password", dbOldPwd, dbNewPwd); - } - } + rangerBizUtil.blockAuditorRoleUser(); - return xXPortalUser; - } - - public void checkAdminAccess() { - UserSessionBase sess = ContextUtil.getCurrentUserSession(); - if (sess != null && sess.isUserAdmin()) { - return; - } - throw restErrorUtil.create403RESTException("Operation not allowed." + " loggedInUser=" + (sess != null ? sess.getXXPortalUser().getId() : ". Not Logged In.")); - } - - public Collection getRolesByLoginId(String loginId) { - if (loginId == null || loginId.trim().isEmpty()){ - return DEFAULT_ROLE_LIST; - } - XXPortalUser xXPortalUser=daoManager.getXXPortalUser().findByLoginId(loginId); - if(xXPortalUser==null){ - return DEFAULT_ROLE_LIST; - } - Collection xXPortalUserRoles = daoManager - .getXXPortalUserRole().findByUserId(xXPortalUser.getId()); - if(xXPortalUserRoles==null){ - return DEFAULT_ROLE_LIST; - } - Collection roleList = new ArrayList(); - for (XXPortalUserRole role : xXPortalUserRoles) { - if(role!=null && VALID_ROLE_LIST.contains(role.getUserRole())){ - if(!roleList.contains(role.getUserRole())){ - roleList.add(role.getUserRole()); - } - } - } - if(roleList==null || roleList.size()==0){ - return DEFAULT_ROLE_LIST; - } - return roleList; - } - - @Transactional(readOnly = false, propagation = Propagation.REQUIRED) - public XXPortalUser updateOldUserName(String userLoginId,String newUserName, String currentPassword) { - if (userLoginId == null || newUserName == null - || userLoginId.trim().isEmpty() || newUserName.trim().isEmpty()){ - return null; - } + if (gjUser != null && gjUser.getStatus() != RangerConstants.ACT_STATUS_DEACTIVATED) { + logger.info("Marking user {} as deleted", gjUser.getLoginId()); - XXPortalUser xXPortalUser = this.findByLoginId(userLoginId); - XXUser xXUser = daoManager.getXXUser().findByUserName(userLoginId); - if (xXPortalUser == null || xXUser == null) { - return null; - } - xXUser.setName(newUserName); - daoManager.getXXUser().update(xXUser); - - xXPortalUser.setLoginId(newUserName); - // The old password needs to be encrypted by the new user name - String updatedPwd = encrypt(newUserName,currentPassword); - if (xXPortalUser.getUserSource() == RangerCommonEnums.USER_APP) { - xXPortalUser.setPassword(updatedPwd); - } - else if (xXPortalUser.getUserSource() == RangerCommonEnums.USER_EXTERNAL) { - xXPortalUser.setPassword(xXPortalUser.getPassword()); - } - xXPortalUser = daoManager.getXXPortalUser().update(xXPortalUser); - - xPortalUserService.createTransactionLog(new XXTrxLogV2(AppConstants.CLASS_TYPE_USER_PROFILE, xXPortalUser.getId(), xXPortalUser.getLoginId(), "update"), "User Name", userLoginId, newUserName); - - return xXPortalUser; - } - public boolean isPasswordValid(String loginId, String encodedPassword, String password) { - boolean isPasswordValid = false; - try { - Pbkdf2PasswordEncoderCust pbkdf2Encoder = new Pbkdf2PasswordEncoderCust(loginId); - pbkdf2Encoder.setEncodeHashAsBase64(true); - - if (pbkdf2Encoder.matches(password, encodedPassword)) { - isPasswordValid = true; - } - } catch (Throwable t) { - logger.error("Unable to validate old password ", t); - } - - return isPasswordValid; - } - - public boolean isNewPasswordDifferent(String loginId, String currentPassword, String newPassword) { - boolean isNewPasswordDifferent = true; - String saltEncodedpasswd = ""; - try { - Pbkdf2PasswordEncoderCust pbkdf2Encoder = new Pbkdf2PasswordEncoderCust(loginId); - pbkdf2Encoder.setEncodeHashAsBase64(true); - if (currentPassword != null) { - saltEncodedpasswd = pbkdf2Encoder.encode(currentPassword); - } - if (pbkdf2Encoder.matches(newPassword, saltEncodedpasswd)) { - isNewPasswordDifferent = false; - } - } catch (Throwable t) { - logger.error("Unable to validate old and new passwords ", t); - } - - return isNewPasswordDifferent; - } - - private String mergeTextAndSalt(String text, Object salt, boolean strict) { - if (text == null) { - text = ""; - } - - if ((strict) && (salt != null) && ((salt.toString().lastIndexOf("{") != -1) || (salt.toString().lastIndexOf("}") != -1))) { - throw new IllegalArgumentException("Cannot use { or } in salt.toString()"); - } - - if ((salt == null) || ("".equals(salt))) { - return text; - } - return text + "{" + salt.toString() + "}"; - } - - private String encodeString(String text, String salt, String algorithm) { - String mergedString = mergeTextAndSalt(text, salt, false); - try { - MessageDigest digest = MessageDigest.getInstance(algorithm); - return new String(Hex.encode(digest.digest(mergedString.getBytes("UTF-8")))); - } catch (UnsupportedEncodingException e) { - throw restErrorUtil.createRESTException("UTF-8 not supported"); - } catch (NoSuchAlgorithmException e) { - throw restErrorUtil.createRESTException("algorithm `" + algorithm + "' not supported"); - } - } - - private boolean hasAccessToGetUserInfo(VXPortalUser requestedVXUser) { - UserSessionBase userSession = ContextUtil.getCurrentUserSession(); - if (userSession != null && userSession.getLoginId() != null) { - VXPortalUser loggedInVXUser = getUserProfileByLoginId(userSession.getLoginId()); - if (loggedInVXUser != null && loggedInVXUser.getUserRoleList().size() == 1) { - if (loggedInVXUser.getUserRoleList().contains(RangerConstants.ROLE_USER)) { - return requestedVXUser.getId().equals(loggedInVXUser.getId()) ? true : false; - } else if (loggedInVXUser.getUserRoleList().contains(RangerConstants.ROLE_KEY_ADMIN) || loggedInVXUser.getUserRoleList().contains(RangerConstants.ROLE_KEY_ADMIN_AUDITOR)) { - if (requestedVXUser.getUserRoleList().contains(RangerConstants.ROLE_KEY_ADMIN) || requestedVXUser.getUserRoleList().contains(RangerConstants.ROLE_KEY_ADMIN_AUDITOR) || requestedVXUser.getUserRoleList().contains(RangerConstants.ROLE_USER)) { - return true; - } - } else if (loggedInVXUser.getUserRoleList().contains(RangerConstants.ROLE_SYS_ADMIN) || loggedInVXUser.getUserRoleList().contains(RangerConstants.ROLE_ADMIN_AUDITOR)) { - if (loggedInVXUser.getUserRoleList().contains(RangerConstants.ROLE_SYS_ADMIN) && "rangerusersync".equalsIgnoreCase(userSession.getLoginId())) { - return true; - } else if (requestedVXUser.getUserRoleList().contains(RangerConstants.ROLE_SYS_ADMIN) || requestedVXUser.getUserRoleList().contains(RangerConstants.ROLE_ADMIN_AUDITOR) || requestedVXUser.getUserRoleList().contains(RangerConstants.ROLE_USER)) { - return true; - } - } - } - } - return false; - } -} \ No newline at end of file + gjUser.setStatus(RangerConstants.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) { + checkAccess(user); + + return mapXXPortalUserVXPortalUser(user); + } else { + 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 { + logger.debug("User not found. loginId={}", loginId); + + return null; + } + } + + public XXPortalUser mapVXPortalUserToXXPortalUser(VXPortalUser userProfile) { + XXPortalUser gjUser = new XXPortalUser(); + + gjUser.setEmailAddress(userProfile.getEmailAddress()); + + if ("null".equalsIgnoreCase(userProfile.getFirstName())) { + userProfile.setFirstName(""); + } + + gjUser.setFirstName(userProfile.getFirstName()); + + if ("null".equalsIgnoreCase(userProfile.getLastName())) { + userProfile.setLastName(""); + } + + gjUser.setLastName(userProfile.getLastName()); + + if (userProfile.getLoginId() == null || userProfile.getLoginId().trim().isEmpty() || "null".equalsIgnoreCase(userProfile.getLoginId())) { + throw restErrorUtil.createRESTException("LoginId should not be null or blank, It is", MessageEnums.INVALID_INPUT_DATA); + } + + gjUser.setLoginId(userProfile.getLoginId()); + gjUser.setPassword(userProfile.getPassword()); + gjUser.setUserSource(userProfile.getUserSource()); + gjUser.setPublicScreenName(userProfile.getPublicScreenName()); + gjUser.setOtherAttributes(userProfile.getOtherAttributes()); + gjUser.setSyncSource(userProfile.getSyncSource()); + gjUser.setStatus(userProfile.getStatus()); + + if (userProfile.getFirstName() != null && userProfile.getLastName() != null && !userProfile.getFirstName().trim().isEmpty() && !userProfile.getLastName().trim().isEmpty()) { + gjUser.setPublicScreenName(userProfile.getFirstName() + " " + userProfile.getLastName()); + } else { + gjUser.setPublicScreenName(userProfile.getLoginId()); + } + + return gjUser; + } + + /** + * @param user + * @return + */ + public VXPortalUser mapXXPortalUserToVXPortalUser(XXPortalUser user, Collection 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.isKeyAdmin() || sess.getXXPortalUser().getId().equals(user.getId())) { + if (userRoleList == null) { + userRoleList = new ArrayList<>(); + + List gjUserRoleList = daoManager.getXXPortalUserRole().findByParentId(user.getId()); + + for (XXPortalUserRole userRole : gjUserRoleList) { + userRoleList.add(userRole.getUserRole()); + } + } + + userProfile.setUserRoleList(userRoleList); + } + + userProfile.setUserSource(user.getUserSource()); + + return userProfile; + } + + /** + * 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 getRolesForUser(XXPortalUser user) { + Collection roleList = new ArrayList<>(); + Collection 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 objectList = new ArrayList<>(); + 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(); + int resultSize = count != null ? count.intValue() : 0; + + if (resultSize == 0) { + return returnList; + } + + // Get actual data + + // Add sort by + String sortBy = searchCriteria.getSortBy(); + String querySortBy = "u.loginId"; + + if (sortBy != null && !sortBy.trim().isEmpty()) { + 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(); + int adminCount = 0; + + // 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); + + if (rangerBizUtil.isKeyAdmin() && (userProfile.getUserRoleList().contains(RangerConstants.ROLE_SYS_ADMIN) || userProfile.getUserRoleList().contains(RangerConstants.ROLE_ADMIN_AUDITOR))) { + adminCount++; + } else { + objectList.add(userProfile); + } + } + + returnList.setResultSize(resultSize - adminCount); + returnList.setPageSize(query.getMaxResults()); + returnList.setSortBy(sortBy); + returnList.setSortType(querySortType); + returnList.setStartIndex(query.getFirstResult()); + returnList.setTotalCount(count); + returnList.setVXPortalUsers(objectList); + + return returnList; + } + + public boolean deleteUserRole(Long userId, String userRole) { + List 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 (RangerConstants.ROLE_USER.equals(gjUserRole.getUserRole())) { + * return false; } + */ + boolean publicRole = false; + + for (String publicRoleStr : publicRoles) { + if (publicRoleStr.equalsIgnoreCase(gjUserRole.getUserRole())) { + publicRole = true; + break; + } + } + + if (!publicRole) { + UserSessionBase sess = ContextUtil.getCurrentUserSession(); + + if (sess == null || (!sess.isUserAdmin() && !sess.isKeyAdmin())) { + return false; + } + } + + daoManager.getXXPortalUserRole().remove(gjUserRole.getId()); + + return true; + } + + public XXPortalUserRole addUserRole(Long userId, String userRole) { + List roleList = daoManager.getXXPortalUserRole().findByUserId(userId); + boolean publicRole = false; + + for (String publicRoleStr : publicRoles) { + if (publicRoleStr.equalsIgnoreCase(userRole)) { + publicRole = true; + break; + } + } + + if (!publicRole) { + UserSessionBase sess = ContextUtil.getCurrentUserSession(); + + if (sess == null) { + return null; + } + + // Admin + if (!sess.isUserAdmin() && !sess.isKeyAdmin()) { + logger.error("SECURITY WARNING: User trying to add non public role. userId={}, role={}, session={}", userId, userRole, sess, new Throwable()); + + return null; + } + + rangerBizUtil.blockAuditorRoleUser(); + } + + for (XXPortalUserRole gjUserRole : roleList) { + if (userRole.equalsIgnoreCase(gjUserRole.getUserRole())) { + return gjUserRole; + } + } + + XXPortalUserRole userRoleObj = new XXPortalUserRole(); + + if (!VALID_ROLE_LIST.contains(userRole.toUpperCase())) { + throw restErrorUtil.createRESTException("Invalid user role, please provide valid user role.", MessageEnums.INVALID_INPUT_DATA); + } + + userRoleObj.setUserRole(userRole.toUpperCase()); + userRoleObj.setUserId(userId); + userRoleObj.setStatus(RangerConstants.STATUS_ENABLED); + + daoManager.getXXPortalUserRole().create(userRoleObj); + + // If role is not OTHER, then remove OTHER + if (!RangerConstants.ROLE_OTHER.equalsIgnoreCase(userRole)) { + deleteUserRole(userId, RangerConstants.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 + */ + public void checkAccess(XXPortalUser gjUser) { + if (gjUser == null) { + throw restErrorUtil.create403RESTException("serverMsg.userMgrWrongUser"); + } + + VXPortalUser requestedVXUser = getUserProfileByLoginId(gjUser.getLoginId()); + + if (requestedVXUser != null && CollectionUtils.isNotEmpty(requestedVXUser.getUserRoleList()) && hasAccessToGetUserInfo(requestedVXUser)) { + return; + } + + logger.info("Logged-In user is not allowed to access requested user data."); + + throw restErrorUtil.createRESTException(HttpServletResponse.SC_FORBIDDEN, "Logged-In user is not allowed to access requested user data", true); + } + + public String encrypt(String loginId, String password) { + String saltEncodedpasswd = ""; + + if (this.isFipsEnabled) { + try { + Pbkdf2PasswordEncoderCust pbkdf2Encoder = new Pbkdf2PasswordEncoderCust(loginId); + + pbkdf2Encoder.setEncodeHashAsBase64(true); + + if (password != null) { + saltEncodedpasswd = pbkdf2Encoder.encode(password); + } + } catch (Throwable t) { + logger.error("Password doesn't meet requirements"); + + throw restErrorUtil.createRESTException("Invalid password", MessageEnums.INVALID_PASSWORD, null, null, loginId); + } + } else { + String sha256PasswordUpdateDisable = PropertiesUtil.getProperty("ranger.sha256Password.update.disable", "false"); + + if ("false".equalsIgnoreCase(sha256PasswordUpdateDisable)) { + saltEncodedpasswd = encodeString(password, loginId, "SHA-256"); + } else { + saltEncodedpasswd = encodeString(password, loginId, "MD5"); + } + } + + return saltEncodedpasswd; + } + + public String encryptWithOlderAlgo(String loginId, String password) { + return encodeString(password, loginId, "MD5"); + } + + public VXPortalUser createUser(VXPortalUser userProfile) { + checkAdminAccess(); + + rangerBizUtil.blockAuditorRoleUser(); + + XXPortalUser xXPortalUser = this.createUser(userProfile, RangerCommonEnums.STATUS_ENABLED); + + return mapXXPortalUserVXPortalUser(xXPortalUser); + } + + public VXPortalUser createDefaultAccountUser(VXPortalUser userProfile) { + if (userProfile.getUserSource() != RangerCommonEnums.USER_FEDERATED) { + if (StringUtils.isBlank(userProfile.getPassword())) { + userProfile.setUserSource(RangerCommonEnums.USER_EXTERNAL); + } + } + + // access control + checkAdminAccess(); + + rangerBizUtil.blockAuditorRoleUser(); + + logger.info("create:{}", userProfile.getLoginId()); + + XXPortalUser xXPortalUser = null; + Collection existingRoleList; + Collection reqRoleList; + String loginId = userProfile.getLoginId(); + String emailAddress = userProfile.getEmailAddress(); + + if (loginId != null && !loginId.isEmpty()) { + xXPortalUser = this.findByLoginId(loginId); + + if (xXPortalUser == null) { + if (emailAddress != null && !emailAddress.trim().isEmpty()) { + xXPortalUser = this.findByEmailAddress(emailAddress); + + if (xXPortalUser == null) { + xXPortalUser = this.createUser(userProfile, RangerCommonEnums.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 { + userProfile.setEmailAddress(null); + + xXPortalUser = this.createUser(userProfile, RangerCommonEnums.STATUS_ENABLED); + } + } else { //NOPMD + /* + * 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); + */ + } + } + + VXPortalUser userProfileRes = null; + + if (xXPortalUser != null) { + userProfileRes = mapXXPortalUserToVXPortalUserForDefaultAccount(xXPortalUser); + + if (userProfile.getUserRoleList() != null && !userProfile.getUserRoleList().isEmpty() && ((List) userProfile.getUserRoleList()).get(0) != null) { + reqRoleList = userProfile.getUserRoleList(); + existingRoleList = this.getRolesByLoginId(loginId); + + XXPortalUser xxPortalUser = daoManager.getXXPortalUser().findByLoginId(userProfile.getLoginId()); + + if (xxPortalUser != null && xxPortalUser.getUserSource() == RangerCommonEnums.USER_EXTERNAL) { + userProfileRes = updateRoleForExternalUsers(reqRoleList, existingRoleList, userProfileRes); + } + } + } + + return userProfileRes; + } + + public boolean isUserInRole(Long userId, String role) { + XXPortalUserRole xXPortalUserRole = daoManager.getXXPortalUserRole().findByRoleUserId(userId, role); + + if (xXPortalUserRole != null) { + String userRole = xXPortalUserRole.getUserRole(); + + return userRole.equalsIgnoreCase(role); + } + + return false; + } + + public XXPortalUser updateUserWithPass(VXPortalUser userProfile) { + String updatedPassword = userProfile.getPassword(); + XXPortalUser xXPortalUser = this.updateUser(userProfile); + + if (xXPortalUser == null) { + return null; + } + + 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); + + if (xXPortalUser.getUserSource() != RangerCommonEnums.USER_EXTERNAL) { + String oldPasswordsStr = xXPortalUser.getOldPasswords(); + List oldPasswords; + + if (StringUtils.isNotEmpty(oldPasswordsStr)) { + oldPasswords = new ArrayList<>(Arrays.asList(oldPasswordsStr.split(","))); + } else { + oldPasswords = new ArrayList<>(); + } + + oldPasswords.add(encryptedNewPwd); + + updateOldPasswords(xXPortalUser, oldPasswords); + + xXPortalUser.setPassword(encryptedNewPwd); + } + + xXPortalUser = daoManager.getXXPortalUser().update(xXPortalUser); + } + + return xXPortalUser; + } + + @Transactional(readOnly = false, propagation = Propagation.REQUIRED) + public XXPortalUser updatePasswordInSHA256(String userName, String userPassword, boolean logAudits) { + if (userName == null || userPassword == null || userName.trim().isEmpty() || userPassword.trim().isEmpty()) { + return null; + } + + XXPortalUser xXPortalUser = this.findByLoginId(userName); + + if (xXPortalUser == null) { + return null; + } + + String dbOldPwd = xXPortalUser.getPassword(); + String encryptedNewPwd = encrypt(xXPortalUser.getLoginId(), userPassword); + + if (xXPortalUser.getUserSource() != RangerCommonEnums.USER_EXTERNAL) { + xXPortalUser.setPassword(encryptedNewPwd); + } + + xXPortalUser = daoManager.getXXPortalUser().update(xXPortalUser); + + if (xXPortalUser != null && logAudits) { + String dbNewPwd = xXPortalUser.getPassword(); + + if (!dbOldPwd.equals(dbNewPwd)) { + xPortalUserService.createTransactionLog(new XXTrxLogV2(AppConstants.CLASS_TYPE_PASSWORD_CHANGE, xXPortalUser.getId(), xXPortalUser.getLoginId(), "password change"), "Password", dbOldPwd, dbNewPwd); + } + } + + return xXPortalUser; + } + + public void checkAdminAccess() { + UserSessionBase sess = ContextUtil.getCurrentUserSession(); + + if (sess != null && sess.isUserAdmin()) { + return; + } + + throw restErrorUtil.create403RESTException("Operation not allowed." + " loggedInUser=" + (sess != null ? sess.getXXPortalUser().getId() : ". Not Logged In.")); + } + + public Collection getRolesByLoginId(String loginId) { + if (loginId == null || loginId.trim().isEmpty()) { + return DEFAULT_ROLE_LIST; + } + + XXPortalUser xXPortalUser = daoManager.getXXPortalUser().findByLoginId(loginId); + + if (xXPortalUser == null) { + return DEFAULT_ROLE_LIST; + } + + Collection xXPortalUserRoles = daoManager.getXXPortalUserRole().findByUserId(xXPortalUser.getId()); + + if (xXPortalUserRoles == null) { + return DEFAULT_ROLE_LIST; + } + + Collection roleList = new ArrayList<>(); + + for (XXPortalUserRole role : xXPortalUserRoles) { + if (role != null && VALID_ROLE_LIST.contains(role.getUserRole())) { + if (!roleList.contains(role.getUserRole())) { + roleList.add(role.getUserRole()); + } + } + } + + if (roleList.isEmpty()) { + return DEFAULT_ROLE_LIST; + } + + return roleList; + } + + @Transactional(readOnly = false, propagation = Propagation.REQUIRED) + public XXPortalUser updateOldUserName(String userLoginId, String newUserName, String currentPassword) { + if (userLoginId == null || newUserName == null || userLoginId.trim().isEmpty() || newUserName.trim().isEmpty()) { + return null; + } + + XXPortalUser xXPortalUser = this.findByLoginId(userLoginId); + XXUser xXUser = daoManager.getXXUser().findByUserName(userLoginId); + + if (xXPortalUser == null || xXUser == null) { + return null; + } + + xXUser.setName(newUserName); + + daoManager.getXXUser().update(xXUser); + + xXPortalUser.setLoginId(newUserName); + + // The old password needs to be encrypted by the new user name + String updatedPwd = encrypt(newUserName, currentPassword); + + if (xXPortalUser.getUserSource() == RangerCommonEnums.USER_APP) { + xXPortalUser.setPassword(updatedPwd); + } else if (xXPortalUser.getUserSource() == RangerCommonEnums.USER_EXTERNAL) { + xXPortalUser.setPassword(xXPortalUser.getPassword()); + } + + xXPortalUser = daoManager.getXXPortalUser().update(xXPortalUser); + + xPortalUserService.createTransactionLog(new XXTrxLogV2(AppConstants.CLASS_TYPE_USER_PROFILE, xXPortalUser.getId(), xXPortalUser.getLoginId(), "update"), "User Name", userLoginId, newUserName); + + return xXPortalUser; + } + + public boolean isPasswordValid(String loginId, String encodedPassword, String password) { + boolean isPasswordValid = false; + + try { + Pbkdf2PasswordEncoderCust pbkdf2Encoder = new Pbkdf2PasswordEncoderCust(loginId); + + pbkdf2Encoder.setEncodeHashAsBase64(true); + + if (pbkdf2Encoder.matches(password, encodedPassword)) { + isPasswordValid = true; + } + } catch (Throwable t) { + logger.error("Unable to validate old password ", t); + } + + return isPasswordValid; + } + + public boolean isNewPasswordDifferent(String loginId, String currentPassword, String newPassword) { + boolean isNewPasswordDifferent = true; + String saltEncodedpasswd = ""; + + try { + Pbkdf2PasswordEncoderCust pbkdf2Encoder = new Pbkdf2PasswordEncoderCust(loginId); + + pbkdf2Encoder.setEncodeHashAsBase64(true); + + if (currentPassword != null) { + saltEncodedpasswd = pbkdf2Encoder.encode(currentPassword); + } + + if (pbkdf2Encoder.matches(newPassword, saltEncodedpasswd)) { + isNewPasswordDifferent = false; + } + } catch (Throwable t) { + logger.error("Unable to validate old and new passwords ", t); + } + + return isNewPasswordDifferent; + } + + protected void gjUserToUserProfile(XXPortalUser user, VXPortalUser userProfile) { + UserSessionBase sess = ContextUtil.getCurrentUserSession(); + + if (sess == null) { + return; + } + + // Admin + if (sess.isUserAdmin() || sess.isKeyAdmin() || sess.getXXPortalUser().getId().equals(user.getId())) { + userProfile.setLoginId(user.getLoginId()); + userProfile.setStatus(user.getStatus()); + userProfile.setUserRoleList(new ArrayList<>()); + + String emailAddress = user.getEmailAddress(); + + if (emailAddress != null && stringUtil.validateEmail(emailAddress)) { + userProfile.setEmailAddress(user.getEmailAddress()); + } + + userProfile.setUserSource(sess.getAuthProvider()); + + List gjUserRoleList = daoManager.getXXPortalUserRole().findByParentId(user.getId()); + + for (XXPortalUserRole gjUserRole : gjUserRoleList) { + userProfile.getUserRoleList().add(gjUserRole.getUserRole()); + } + + userProfile.setId(user.getId()); + + if (sess.isUserAdmin() || sess.getXXPortalUser().getId().equals(user.getId())) { + List xUserPermissions = daoManager.getXXUserPermission().findByUserPermissionIdAndIsAllowed(userProfile.getId()); + List xxGroupPermissions = daoManager.getXXGroupPermission().findbyVXPortalUserId(userProfile.getId()); + List groupPermissions = new ArrayList<>(); + List vxUserPermissions = new ArrayList<>(); + + for (XXGroupPermission xxGroupPermission : xxGroupPermissions) { + VXGroupPermission groupPermission = xGroupPermissionService.populateViewBean(xxGroupPermission); + + groupPermission.setModuleName(daoManager.getXXModuleDef().findByModuleId(groupPermission.getModuleId()).getModule()); + + groupPermissions.add(groupPermission); + } + + for (XXUserPermission xUserPermission : xUserPermissions) { + VXUserPermission vXUserPermission = xUserPermissionService.populateViewBean(xUserPermission); + + vXUserPermission.setModuleName(daoManager.getXXModuleDef().findByModuleId(vXUserPermission.getModuleId()).getModule()); + + vxUserPermissions.add(vXUserPermission); + } + + userProfile.setGroupPermissions(groupPermissions); + userProfile.setUserPermList(vxUserPermissions); + } + + userProfile.setFirstName(user.getFirstName()); + userProfile.setLastName(user.getLastName()); + userProfile.setPublicScreenName(user.getPublicScreenName()); + } + } + + /** + * @param queryStr + * @param sortClause + * @param searchCriteria + * @return + */ + protected Query createUserSearchQuery(String queryStr, String sortClause, SearchCriteria searchCriteria) { + HashMap paramList = searchCriteria.getParamList(); + String whereClause = "WHERE 1 = 1 "; + + // roles + @SuppressWarnings("unchecked") + List roleList = (List) paramList.get("roleList"); + + if (roleList != null && !roleList.isEmpty()) { + 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 statusList = (List) 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.isEmpty()) { + 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; + } + + protected VXPortalUser updateRoleForExternalUsers(Collection reqRoleList, Collection existingRoleList, VXPortalUser userProfileRes) { + UserSessionBase session = ContextUtil.getCurrentUserSession(); + + if (session != null && session.getXXPortalUser() != null && session.getXXPortalUser().getLoginId() != null && "rangerusersync".equals(session.getXXPortalUser().getLoginId()) + && reqRoleList != null && !reqRoleList.isEmpty() && existingRoleList != null && !existingRoleList.isEmpty()) { + if (!reqRoleList.equals(existingRoleList)) { + userProfileRes.setUserRoleList(reqRoleList); + userProfileRes.setUserSource(RangerCommonEnums.USER_EXTERNAL); + + List xuserPermissionList = daoManager.getXXUserPermission().findByUserPermissionId(userProfileRes.getId()); + + if (xuserPermissionList != null && !xuserPermissionList.isEmpty()) { + for (XXUserPermission xXUserPermission : xuserPermissionList) { + if (xXUserPermission != null) { + try { + xUserPermissionService.deleteResource(xXUserPermission.getId()); + } catch (Exception e) { + logger.error(e.getMessage()); + } + } + } + } + + updateUser(userProfileRes); + } + } else { + logger.debug("Permission denied. LoggedInUser={} isn't permitted to perform the action.", session != null && session.getXXPortalUser() != null ? session.getXXPortalUser().getId() : ""); + } + + return userProfileRes; + } + + protected VXPortalUser mapXXPortalUserToVXPortalUserForDefaultAccount(XXPortalUser user) { + VXPortalUser userProfile = new VXPortalUser(); + + userProfile.setLoginId(user.getLoginId()); + userProfile.setEmailAddress(user.getEmailAddress()); + userProfile.setStatus(user.getStatus()); + userProfile.setUserRoleList(new ArrayList<>()); + userProfile.setId(user.getId()); + userProfile.setFirstName(user.getFirstName()); + userProfile.setLastName(user.getLastName()); + userProfile.setPublicScreenName(user.getPublicScreenName()); + userProfile.setOtherAttributes(user.getOtherAttributes()); + userProfile.setSyncSource(user.getSyncSource()); + + List gjUserRoleList = daoManager.getXXPortalUserRole().findByParentId(user.getId()); + + for (XXPortalUserRole gjUserRole : gjUserRoleList) { + userProfile.getUserRoleList().add(gjUserRole.getUserRole()); + } + + return userProfile; + } + + private void updateOldPasswords(XXPortalUser gjUser, List oldPasswords) { + String oldPasswordStr = CollectionUtils.isNotEmpty(oldPasswords) ? StringUtils.join(oldPasswords, ",") : null; + + gjUser.setOldPasswords(oldPasswordStr); + gjUser.setPasswordUpdatedTime(DateUtil.getUTCDate()); + } + + private String mergeTextAndSalt(String text, Object salt, boolean strict) { + if (text == null) { + text = ""; + } + + if ((strict) && (salt != null) && ((salt.toString().lastIndexOf("{") != -1) || (salt.toString().lastIndexOf("}") != -1))) { + throw new IllegalArgumentException("Cannot use { or } in salt.toString()"); + } + + if ((salt == null) || ("".equals(salt))) { + return text; + } + + return text + "{" + salt + "}"; + } + + private String encodeString(String text, String salt, String algorithm) { + String mergedString = mergeTextAndSalt(text, salt, false); + + try { + MessageDigest digest = MessageDigest.getInstance(algorithm); + + return new String(Hex.encode(digest.digest(mergedString.getBytes(StandardCharsets.UTF_8)))); + } catch (NoSuchAlgorithmException e) { + throw restErrorUtil.createRESTException("algorithm `" + algorithm + "' not supported"); + } + } + + private boolean hasAccessToGetUserInfo(VXPortalUser requestedVXUser) { + UserSessionBase userSession = ContextUtil.getCurrentUserSession(); + + if (userSession != null && userSession.getLoginId() != null) { + VXPortalUser loggedInVXUser = getUserProfileByLoginId(userSession.getLoginId()); + + if (loggedInVXUser != null && loggedInVXUser.getUserRoleList().size() == 1) { + if (loggedInVXUser.getUserRoleList().contains(RangerConstants.ROLE_USER)) { + return requestedVXUser.getId().equals(loggedInVXUser.getId()); + } else if (loggedInVXUser.getUserRoleList().contains(RangerConstants.ROLE_KEY_ADMIN) || loggedInVXUser.getUserRoleList().contains(RangerConstants.ROLE_KEY_ADMIN_AUDITOR)) { + return requestedVXUser.getUserRoleList().contains(RangerConstants.ROLE_KEY_ADMIN) || requestedVXUser.getUserRoleList().contains(RangerConstants.ROLE_KEY_ADMIN_AUDITOR) || requestedVXUser.getUserRoleList().contains(RangerConstants.ROLE_USER); + } else if (loggedInVXUser.getUserRoleList().contains(RangerConstants.ROLE_SYS_ADMIN) || loggedInVXUser.getUserRoleList().contains(RangerConstants.ROLE_ADMIN_AUDITOR)) { + if (loggedInVXUser.getUserRoleList().contains(RangerConstants.ROLE_SYS_ADMIN) && "rangerusersync".equalsIgnoreCase(userSession.getLoginId())) { + return true; + } else { + return requestedVXUser.getUserRoleList().contains(RangerConstants.ROLE_SYS_ADMIN) || requestedVXUser.getUserRoleList().contains(RangerConstants.ROLE_ADMIN_AUDITOR) || requestedVXUser.getUserRoleList().contains(RangerConstants.ROLE_USER); + } + } + } + } + + return false; + } + + static { + DEFAULT_ROLE_LIST.add(RangerConstants.ROLE_USER); + VALID_ROLE_LIST.add(RangerConstants.ROLE_SYS_ADMIN); + VALID_ROLE_LIST.add(RangerConstants.ROLE_USER); + VALID_ROLE_LIST.add(RangerConstants.ROLE_KEY_ADMIN); + VALID_ROLE_LIST.add(RangerConstants.ROLE_ADMIN_AUDITOR); + VALID_ROLE_LIST.add(RangerConstants.ROLE_KEY_ADMIN_AUDITOR); + } +} 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 index 67f62cc36f..ccbd2a055e 100644 --- a/security-admin/src/main/java/org/apache/ranger/biz/UserMgrBase.java +++ b/security-admin/src/main/java/org/apache/ranger/biz/UserMgrBase.java @@ -17,7 +17,7 @@ * under the License. */ - package org.apache.ranger.biz; +package org.apache.ranger.biz; import org.apache.ranger.common.MessageEnums; import org.apache.ranger.common.RESTErrorUtil; @@ -27,44 +27,43 @@ import org.apache.ranger.view.VXPortalUser; import org.apache.ranger.view.VXPortalUserList; import org.springframework.beans.factory.annotation.Autowired; + public class UserMgrBase { + @Autowired + RESTErrorUtil restErrorUtil; + + @Autowired + XPortalUserService xPortalUserService; - @Autowired - RESTErrorUtil restErrorUtil; + public VXPortalUser getXPortalUser(Long id) { + return xPortalUserService.readResource(id); + } - @Autowired - XPortalUserService xPortalUserService; - public VXPortalUser getXPortalUser(Long id){ - return (VXPortalUser)xPortalUserService.readResource(id); - } + public VXPortalUser createXPortalUser(VXPortalUser vXPortalUser) { + vXPortalUser = xPortalUserService.createResource(vXPortalUser); - public VXPortalUser createXPortalUser(VXPortalUser vXPortalUser){ - vXPortalUser = (VXPortalUser)xPortalUserService.createResource(vXPortalUser); - return vXPortalUser; - } + return vXPortalUser; + } - public VXPortalUser updateXPortalUser(VXPortalUser vXPortalUser) { - vXPortalUser = (VXPortalUser)xPortalUserService.updateResource(vXPortalUser); - return vXPortalUser; - } + public VXPortalUser updateXPortalUser(VXPortalUser vXPortalUser) { + vXPortalUser = xPortalUserService.updateResource(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); - } - } + return vXPortalUser; + } - public VXPortalUserList searchXPortalUsers(SearchCriteria searchCriteria) { - return xPortalUserService.searchXPortalUsers(searchCriteria); - } + 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 VXLong getXPortalUserSearchCount(SearchCriteria searchCriteria) { - return xPortalUserService.getSearchCount(searchCriteria, - xPortalUserService.searchFields); - } + public VXPortalUserList searchXPortalUsers(SearchCriteria searchCriteria) { + return xPortalUserService.searchXPortalUsers(searchCriteria); + } + public VXLong getXPortalUserSearchCount(SearchCriteria searchCriteria) { + return xPortalUserService.getSearchCount(searchCriteria, xPortalUserService.searchFields); + } } 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 index 038402fd00..67b10246c6 100644 --- a/security-admin/src/main/java/org/apache/ranger/biz/XAuditMgr.java +++ b/security-admin/src/main/java/org/apache/ranger/biz/XAuditMgr.java @@ -19,8 +19,6 @@ package org.apache.ranger.biz; -import javax.servlet.http.HttpServletResponse; - import org.apache.ranger.amazon.cloudwatch.CloudWatchAccessAuditsService; import org.apache.ranger.common.ContextUtil; import org.apache.ranger.common.SearchCriteria; @@ -36,120 +34,134 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; +import javax.servlet.http.HttpServletResponse; + @Component public class XAuditMgr extends XAuditMgrBase { + @Autowired + SolrAccessAuditsService solrAccessAuditsService; + + @Autowired + ElasticSearchAccessAuditsService elasticSearchAccessAuditsService; + + @Autowired + CloudWatchAccessAuditsService cloudWatchAccessAuditsService; + + @Autowired + RangerBizUtil rangerBizUtil; + + public VXTrxLog getXTrxLog(Long id) { + checkAllAdminsAccess(); + + return super.getXTrxLog(id); + } + + public VXTrxLog createXTrxLog(VXTrxLog vXTrxLog) { + checkAdminAccess(); + + rangerBizUtil.blockAuditorRoleUser(); + + return super.createXTrxLog(vXTrxLog); + } + + public VXTrxLog updateXTrxLog(VXTrxLog vXTrxLog) { + checkAdminAccess(); + + rangerBizUtil.blockAuditorRoleUser(); + + return super.updateXTrxLog(vXTrxLog); + } + + public void deleteXTrxLog(Long id, boolean force) { + checkAdminAccess(); + + rangerBizUtil.blockAuditorRoleUser(); + + super.deleteXTrxLog(id, force); + } + + public VXTrxLogList searchXTrxLogs(SearchCriteria searchCriteria) { + checkAllAdminsAccess(); + + return super.searchXTrxLogs(searchCriteria); + } + + public VXLong getXTrxLogSearchCount(SearchCriteria searchCriteria) { + checkAllAdminsAccess(); + + return super.getXTrxLogSearchCount(searchCriteria); + } + + public VXAccessAudit createXAccessAudit(VXAccessAudit vXAccessAudit) { + checkAdminAccess(); + + return super.createXAccessAudit(vXAccessAudit); + } + + public VXAccessAudit updateXAccessAudit(VXAccessAudit vXAccessAudit) { + checkAdminAccess(); + + return super.updateXAccessAudit(vXAccessAudit); + } + + public void deleteXAccessAudit(Long id, boolean force) { + checkAdminAccess(); + + super.deleteXAccessAudit(id, force); + } + + @Override + public VXAccessAuditList searchXAccessAudits(SearchCriteria searchCriteria) { + String auditDBType = rangerBizUtil.getAuditDBType(); + + if (RangerBizUtil.AUDIT_STORE_SOLR.equalsIgnoreCase(auditDBType)) { + return solrAccessAuditsService.searchXAccessAudits(searchCriteria); + } else if (RangerBizUtil.AUDIT_STORE_ELASTIC_SEARCH.equalsIgnoreCase(auditDBType)) { + return elasticSearchAccessAuditsService.searchXAccessAudits(searchCriteria); + } else if (RangerBizUtil.AUDIT_STORE_CLOUD_WATCH.equalsIgnoreCase(auditDBType)) { + return cloudWatchAccessAuditsService.searchXAccessAudits(searchCriteria); + } else { + return super.searchXAccessAudits(searchCriteria); + } + } + + @Override + public VXLong getXAccessAuditSearchCount(SearchCriteria searchCriteria) { + String auditDBType = rangerBizUtil.getAuditDBType(); + + if (RangerBizUtil.AUDIT_STORE_SOLR.equalsIgnoreCase(auditDBType)) { + return solrAccessAuditsService.getXAccessAuditSearchCount(searchCriteria); + } else if (RangerBizUtil.AUDIT_STORE_ELASTIC_SEARCH.equalsIgnoreCase(auditDBType)) { + return elasticSearchAccessAuditsService.getXAccessAuditSearchCount(searchCriteria); + } else if (RangerBizUtil.AUDIT_STORE_CLOUD_WATCH.equalsIgnoreCase(auditDBType)) { + return cloudWatchAccessAuditsService.getXAccessAuditSearchCount(searchCriteria); + } else { + return super.getXAccessAuditSearchCount(searchCriteria); + } + } + + public void checkAdminAccess() { + UserSessionBase session = ContextUtil.getCurrentUserSession(); + + if (session != null) { + if (!session.isUserAdmin()) { + throw restErrorUtil.create403RESTException("Operation" + " denied. LoggedInUser=" + session.getXXPortalUser().getId() + " ,isn't permitted to perform the action."); + } + } else { + VXResponse vXResponse = new VXResponse(); + + vXResponse.setStatusCode(HttpServletResponse.SC_UNAUTHORIZED); // user is null + vXResponse.setMsgDesc("Bad Credentials"); - @Autowired - SolrAccessAuditsService solrAccessAuditsService; - - @Autowired - ElasticSearchAccessAuditsService elasticSearchAccessAuditsService; - - @Autowired - CloudWatchAccessAuditsService cloudWatchAccessAuditsService; - - @Autowired - RangerBizUtil rangerBizUtil; - - public VXTrxLog getXTrxLog(Long id) { - checkAllAdminsAccess(); - return super.getXTrxLog(id); - } - - public VXTrxLog createXTrxLog(VXTrxLog vXTrxLog) { - checkAdminAccess(); - rangerBizUtil.blockAuditorRoleUser(); - return super.createXTrxLog(vXTrxLog); - } - - public VXTrxLog updateXTrxLog(VXTrxLog vXTrxLog) { - checkAdminAccess(); - rangerBizUtil.blockAuditorRoleUser(); - return super.updateXTrxLog(vXTrxLog); - } - - public void deleteXTrxLog(Long id, boolean force) { - checkAdminAccess(); - rangerBizUtil.blockAuditorRoleUser(); - super.deleteXTrxLog(id, force); - } - - public VXTrxLogList searchXTrxLogs(SearchCriteria searchCriteria) { - checkAllAdminsAccess(); - return super.searchXTrxLogs(searchCriteria); - } - - public VXLong getXTrxLogSearchCount(SearchCriteria searchCriteria) { - checkAllAdminsAccess(); - return super.getXTrxLogSearchCount(searchCriteria); - } - - public VXAccessAudit createXAccessAudit(VXAccessAudit vXAccessAudit) { - checkAdminAccess(); - return super.createXAccessAudit(vXAccessAudit); - } - - public VXAccessAudit updateXAccessAudit(VXAccessAudit vXAccessAudit) { - checkAdminAccess(); - return super.updateXAccessAudit(vXAccessAudit); - } - - public void deleteXAccessAudit(Long id, boolean force) { - checkAdminAccess(); - super.deleteXAccessAudit(id, force); - } - - public void checkAdminAccess() { - UserSessionBase session = ContextUtil.getCurrentUserSession(); - if (session != null) { - if (!session.isUserAdmin()) { - throw restErrorUtil.create403RESTException("Operation" - + " denied. LoggedInUser=" - + session.getXXPortalUser().getId() - + " ,isn't permitted to perform the action."); - } - } else { - VXResponse vXResponse = new VXResponse(); - vXResponse.setStatusCode(HttpServletResponse.SC_UNAUTHORIZED); // user is null - vXResponse.setMsgDesc("Bad Credentials"); - throw restErrorUtil.generateRESTException(vXResponse); - } - } - - @Override - public VXAccessAuditList searchXAccessAudits(SearchCriteria searchCriteria) { - String auditDBType = rangerBizUtil.getAuditDBType(); - if (RangerBizUtil.AUDIT_STORE_SOLR.equalsIgnoreCase(auditDBType)) { - return solrAccessAuditsService.searchXAccessAudits(searchCriteria); - } else if (RangerBizUtil.AUDIT_STORE_ELASTIC_SEARCH.equalsIgnoreCase(auditDBType)) { - return elasticSearchAccessAuditsService.searchXAccessAudits(searchCriteria); - } else if (RangerBizUtil.AUDIT_STORE_CLOUD_WATCH.equalsIgnoreCase(auditDBType)) { - return cloudWatchAccessAuditsService.searchXAccessAudits(searchCriteria); - } else { - return super.searchXAccessAudits(searchCriteria); - } - } - - @Override - public VXLong getXAccessAuditSearchCount(SearchCriteria searchCriteria) { - String auditDBType = rangerBizUtil.getAuditDBType(); - if (RangerBizUtil.AUDIT_STORE_SOLR.equalsIgnoreCase(auditDBType)) { - return solrAccessAuditsService.getXAccessAuditSearchCount(searchCriteria); - } else if (RangerBizUtil.AUDIT_STORE_ELASTIC_SEARCH.equalsIgnoreCase(auditDBType)) { - return elasticSearchAccessAuditsService.getXAccessAuditSearchCount(searchCriteria); - } else if (RangerBizUtil.AUDIT_STORE_CLOUD_WATCH.equalsIgnoreCase(auditDBType)) { - return cloudWatchAccessAuditsService.getXAccessAuditSearchCount(searchCriteria); - } else { - return super.getXAccessAuditSearchCount(searchCriteria); - } - } - - private boolean checkAllAdminsAccess(){ - if (rangerBizUtil.isAdmin() || rangerBizUtil.isKeyAdmin() || rangerBizUtil.isAuditAdmin() || rangerBizUtil.isAuditKeyAdmin()){ - return true; - } else { - throw restErrorUtil.createRESTException(HttpServletResponse.SC_FORBIDDEN, "User doesn't have permissions to perform this action", true); - } - } + throw restErrorUtil.generateRESTException(vXResponse); + } + } + private boolean checkAllAdminsAccess() { + if (rangerBizUtil.isAdmin() || rangerBizUtil.isKeyAdmin() || rangerBizUtil.isAuditAdmin() || rangerBizUtil.isAuditKeyAdmin()) { + return true; + } else { + throw restErrorUtil.createRESTException(HttpServletResponse.SC_FORBIDDEN, "User doesn't have permissions to perform this action", true); + } + } } 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 index 02b2e59a3f..5aa3e5c5c7 100644 --- a/security-admin/src/main/java/org/apache/ranger/biz/XAuditMgrBase.java +++ b/security-admin/src/main/java/org/apache/ranger/biz/XAuditMgrBase.java @@ -17,10 +17,7 @@ * under the License. */ - package org.apache.ranger.biz; - -import java.util.List; -import java.util.stream.Collectors; +package org.apache.ranger.biz; import org.apache.ranger.common.MessageEnums; import org.apache.ranger.common.RESTErrorUtil; @@ -36,100 +33,99 @@ import org.apache.ranger.view.VXTrxLogV2; import org.springframework.beans.factory.annotation.Autowired; +import java.util.List; +import java.util.stream.Collectors; + public class XAuditMgrBase { + @Autowired + RESTErrorUtil restErrorUtil; + + @Autowired + RangerTrxLogV2Service xTrxLogService; - @Autowired - RESTErrorUtil restErrorUtil; + @Autowired + XAccessAuditService xAccessAuditService; - @Autowired - RangerTrxLogV2Service xTrxLogService; + public VXTrxLog getXTrxLog(Long id) { + VXTrxLogV2 ret = xTrxLogService.readResource(id); - @Autowired - XAccessAuditService xAccessAuditService; - public VXTrxLog getXTrxLog(Long id){ - VXTrxLogV2 ret = xTrxLogService.readResource(id); + return ret != null ? VXTrxLogV2.toVXTrxLog(ret) : null; + } - return ret != null ? VXTrxLogV2.toVXTrxLog(ret) : null; - } + public VXTrxLog createXTrxLog(VXTrxLog vXTrxLog) { + VXTrxLogV2 ret = xTrxLogService.createResource(new VXTrxLogV2(vXTrxLog)); - public VXTrxLog createXTrxLog(VXTrxLog vXTrxLog){ - VXTrxLogV2 ret = xTrxLogService.createResource(new VXTrxLogV2(vXTrxLog)); + return ret != null ? VXTrxLogV2.toVXTrxLog(ret) : null; + } - return ret != null ? VXTrxLogV2.toVXTrxLog(ret) : null; - } + public VXTrxLog updateXTrxLog(VXTrxLog vXTrxLog) { + VXTrxLogV2 ret = xTrxLogService.updateResource(new VXTrxLogV2(vXTrxLog)); - public VXTrxLog updateXTrxLog(VXTrxLog vXTrxLog) { - VXTrxLogV2 ret = xTrxLogService.updateResource(new VXTrxLogV2(vXTrxLog)); + return ret != null ? VXTrxLogV2.toVXTrxLog(ret) : null; + } - return ret != null ? VXTrxLogV2.toVXTrxLog(ret) : null; - } + 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 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) { + PList vXTrxLogsV2 = xTrxLogService.searchTrxLogs(searchCriteria); + List vxTrxLogs = vXTrxLogsV2.getList().stream().map(VXTrxLogV2::toVXTrxLog).collect(Collectors.toList()); + VXTrxLogList ret = new VXTrxLogList(vxTrxLogs); - public VXTrxLogList searchXTrxLogs(SearchCriteria searchCriteria) { - PList vXTrxLogsV2 = xTrxLogService.searchTrxLogs(searchCriteria); - List vxTrxLogs = vXTrxLogsV2.getList().stream().map(VXTrxLogV2::toVXTrxLog).collect(Collectors.toList()); - VXTrxLogList ret = new VXTrxLogList(vxTrxLogs); + ret.setStartIndex(vXTrxLogsV2.getStartIndex()); + ret.setPageSize(vXTrxLogsV2.getPageSize()); + ret.setTotalCount(vXTrxLogsV2.getTotalCount()); + ret.setResultSize(vXTrxLogsV2.getResultSize()); + ret.setSortBy(vXTrxLogsV2.getSortBy()); + ret.setSortType(vXTrxLogsV2.getSortType()); - ret.setStartIndex(vXTrxLogsV2.getStartIndex()); - ret.setPageSize(vXTrxLogsV2.getPageSize()); - ret.setTotalCount(vXTrxLogsV2.getTotalCount()); - ret.setResultSize(vXTrxLogsV2.getResultSize()); - ret.setSortBy(vXTrxLogsV2.getSortBy()); - ret.setSortType(vXTrxLogsV2.getSortType()); + return ret; + } - return ret; - } + public VXLong getXTrxLogSearchCount(SearchCriteria searchCriteria) { + long count = xTrxLogService.getTrxLogsCount(searchCriteria); - public VXLong getXTrxLogSearchCount(SearchCriteria searchCriteria) { - long count = xTrxLogService.getTrxLogsCount(searchCriteria); + VXLong ret = new VXLong(); - VXLong ret = new VXLong(); + ret.setValue(count); - ret.setValue(count); + return ret; + } - return ret; - } + public VXAccessAudit getXAccessAudit(Long id) { + return xAccessAuditService.readResource(id); + } - public VXAccessAudit getXAccessAudit(Long id){ - return (VXAccessAudit)xAccessAuditService.readResource(id); - } + public VXAccessAudit createXAccessAudit(VXAccessAudit vXAccessAudit) { + vXAccessAudit = xAccessAuditService.createResource(vXAccessAudit); - public VXAccessAudit createXAccessAudit(VXAccessAudit vXAccessAudit){ - vXAccessAudit = (VXAccessAudit)xAccessAuditService.createResource(vXAccessAudit); - return vXAccessAudit; - } + return vXAccessAudit; + } - public VXAccessAudit updateXAccessAudit(VXAccessAudit vXAccessAudit) { - vXAccessAudit = (VXAccessAudit)xAccessAuditService.updateResource(vXAccessAudit); - return vXAccessAudit; - } + public VXAccessAudit updateXAccessAudit(VXAccessAudit vXAccessAudit) { + vXAccessAudit = xAccessAuditService.updateResource(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); - } - } + return vXAccessAudit; + } - public VXAccessAuditList searchXAccessAudits(SearchCriteria searchCriteria) { - return xAccessAuditService.searchXAccessAudits(searchCriteria); - } + 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 VXLong getXAccessAuditSearchCount(SearchCriteria searchCriteria) { - return xAccessAuditService.getSearchCount(searchCriteria, - xAccessAuditService.searchFields); - } + public VXAccessAuditList searchXAccessAudits(SearchCriteria searchCriteria) { + return xAccessAuditService.searchXAccessAudits(searchCriteria); + } + public VXLong getXAccessAuditSearchCount(SearchCriteria searchCriteria) { + return xAccessAuditService.getSearchCount(searchCriteria, xAccessAuditService.searchFields); + } } 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 index 0350704749..7941779fea 100755 --- a/security-admin/src/main/java/org/apache/ranger/biz/XUserMgr.java +++ b/security-admin/src/main/java/org/apache/ranger/biz/XUserMgr.java @@ -19,42 +19,24 @@ package org.apache.ranger.biz; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Set; - import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.MapUtils; import org.apache.commons.lang.StringUtils; import org.apache.hadoop.util.Time; import org.apache.ranger.biz.ServiceDBStore.REMOVE_REF_TYPE; -import org.apache.ranger.common.*; +import org.apache.ranger.common.AppConstants; +import org.apache.ranger.common.ContextUtil; +import org.apache.ranger.common.GUIDUtil; +import org.apache.ranger.common.MessageEnums; +import org.apache.ranger.common.PropertiesUtil; +import org.apache.ranger.common.RangerCommonEnums; +import org.apache.ranger.common.RangerConstants; +import org.apache.ranger.common.RangerServicePoliciesCache; +import org.apache.ranger.common.RangerUserStoreCache; +import org.apache.ranger.common.SearchCriteria; +import org.apache.ranger.common.StringUtil; +import org.apache.ranger.common.UserSessionBase; import org.apache.ranger.common.db.RangerTransactionSynchronizationAdapter; -import org.apache.ranger.entity.XXGroupPermission; -import org.apache.ranger.entity.XXModuleDef; -import org.apache.ranger.entity.XXUserPermission; -import org.apache.ranger.plugin.model.GroupInfo; -import org.apache.ranger.plugin.model.RangerPolicy; -import org.apache.ranger.plugin.model.RangerPolicy.RangerDataMaskPolicyItem; -import org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyItem; -import org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyResource; -import org.apache.ranger.plugin.model.RangerPolicy.RangerRowFilterPolicyItem; -import org.apache.ranger.plugin.model.RangerPrincipal; -import org.apache.ranger.plugin.model.UserInfo; -import org.apache.ranger.plugin.store.EmbeddedServiceDefsUtil; -import org.apache.ranger.plugin.util.RangerUserStore; -import org.apache.ranger.plugin.util.PasswordUtils.PasswordGenerator; -import org.apache.ranger.service.*; -import org.apache.ranger.ugsyncutil.model.GroupUserInfo; -import org.apache.ranger.ugsyncutil.model.UsersGroupRoleAssignments; -import org.apache.ranger.view.*; import org.apache.ranger.db.RangerDaoManager; import org.apache.ranger.db.XXAuditMapDao; import org.apache.ranger.db.XXAuthSessionDao; @@ -70,10 +52,13 @@ import org.apache.ranger.db.XXUserPermissionDao; import org.apache.ranger.entity.XXAuditMap; import org.apache.ranger.entity.XXGroup; +import org.apache.ranger.entity.XXGroupPermission; import org.apache.ranger.entity.XXGroupUser; +import org.apache.ranger.entity.XXModuleDef; import org.apache.ranger.entity.XXPermMap; import org.apache.ranger.entity.XXPolicy; import org.apache.ranger.entity.XXPortalUser; +import org.apache.ranger.entity.XXPortalUserRole; import org.apache.ranger.entity.XXResource; import org.apache.ranger.entity.XXRole; import org.apache.ranger.entity.XXRoleRefGroup; @@ -83,6 +68,45 @@ import org.apache.ranger.entity.XXSecurityZoneRefUser; import org.apache.ranger.entity.XXTrxLogV2; import org.apache.ranger.entity.XXUser; +import org.apache.ranger.entity.XXUserPermission; +import org.apache.ranger.plugin.model.GroupInfo; +import org.apache.ranger.plugin.model.RangerPolicy; +import org.apache.ranger.plugin.model.RangerPolicy.RangerDataMaskPolicyItem; +import org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyItem; +import org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyResource; +import org.apache.ranger.plugin.model.RangerPolicy.RangerRowFilterPolicyItem; +import org.apache.ranger.plugin.model.RangerPrincipal; +import org.apache.ranger.plugin.model.UserInfo; +import org.apache.ranger.plugin.store.EmbeddedServiceDefsUtil; +import org.apache.ranger.plugin.util.PasswordUtils.PasswordGenerator; +import org.apache.ranger.plugin.util.RangerUserStore; +import org.apache.ranger.service.RangerPolicyService; +import org.apache.ranger.service.XPortalUserService; +import org.apache.ranger.service.XResourceService; +import org.apache.ranger.service.XUgsyncAuditInfoService; +import org.apache.ranger.ugsyncutil.model.GroupUserInfo; +import org.apache.ranger.ugsyncutil.model.UsersGroupRoleAssignments; +import org.apache.ranger.view.VXAuditMap; +import org.apache.ranger.view.VXAuditMapList; +import org.apache.ranger.view.VXGroup; +import org.apache.ranger.view.VXGroupList; +import org.apache.ranger.view.VXGroupPermission; +import org.apache.ranger.view.VXGroupUser; +import org.apache.ranger.view.VXGroupUserInfo; +import org.apache.ranger.view.VXGroupUserList; +import org.apache.ranger.view.VXLong; +import org.apache.ranger.view.VXModuleDef; +import org.apache.ranger.view.VXPermMap; +import org.apache.ranger.view.VXPermMapList; +import org.apache.ranger.view.VXPortalUser; +import org.apache.ranger.view.VXResponse; +import org.apache.ranger.view.VXString; +import org.apache.ranger.view.VXStringList; +import org.apache.ranger.view.VXUgsyncAuditInfo; +import org.apache.ranger.view.VXUser; +import org.apache.ranger.view.VXUserGroupInfo; +import org.apache.ranger.view.VXUserList; +import org.apache.ranger.view.VXUserPermission; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -90,3305 +114,3741 @@ import org.springframework.stereotype.Component; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionDefinition; -import org.springframework.transaction.TransactionStatus; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionCallback; +import org.springframework.transaction.support.TransactionTemplate; import javax.servlet.http.HttpServletResponse; -import org.apache.ranger.entity.XXPortalUserRole; -import org.springframework.transaction.support.TransactionCallback; -import org.springframework.transaction.support.TransactionTemplate; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; import static org.apache.ranger.db.XXGlobalStateDao.RANGER_GLOBAL_STATE_NAME_USER_GROUP; import static org.apache.ranger.service.RangerBaseModelService.OPERATION_CREATE_CONTEXT; -import static org.apache.ranger.service.RangerBaseModelService.OPERATION_UPDATE_CONTEXT; import static org.apache.ranger.service.RangerBaseModelService.OPERATION_DELETE_CONTEXT; +import static org.apache.ranger.service.RangerBaseModelService.OPERATION_UPDATE_CONTEXT; @Component public class XUserMgr extends XUserMgrBase { + static final Logger logger = LoggerFactory.getLogger(XUserMgr.class); - private static final String USER = "User"; - private static final String GROUP = "Group"; - private static final int MAX_DB_TRANSACTION_RETRIES = 5; - private static final int PASSWORD_LENGTH = 16; - - @Autowired - RangerBizUtil msBizUtil; - - @Autowired - UserMgr userMgr; - - @Autowired - RangerDaoManager daoManager; - - @Autowired - RangerBizUtil xaBizUtil; - - @Autowired - XPortalUserService xPortalUserService; - - @Autowired - XResourceService xResourceService; - - @Autowired - SessionMgr sessionMgr; - - @Autowired - RangerPolicyService policyService; - - @Autowired - ServiceDBStore svcStore; - - @Autowired - GUIDUtil guidUtil; - - @Autowired - XUgsyncAuditInfoService xUgsyncAuditInfoService; - - @Autowired - StringUtil stringUtil; - - @Autowired - RangerTransactionSynchronizationAdapter transactionSynchronizationAdapter; - - @Autowired - GdsDBStore gdsStore; - - @Autowired - @Qualifier(value = "transactionManager") - PlatformTransactionManager txManager; - - static final Logger logger = LoggerFactory.getLogger(XUserMgr.class); - static final Set roleAssignmentUpdatedUsers = new HashSet<>(); - - static final String MSG_DATA_ACCESS_DENY = "Logged-In user is not allowed to access requested user data"; - - public VXUser getXUserByUserName(String userName) { - VXUser vXUser=null; - vXUser=xUserService.getXUserByUserName(userName); - if(vXUser != null && !hasAccessToGetUserInfo(vXUser)) { - logger.info(MSG_DATA_ACCESS_DENY); - throw restErrorUtil.createRESTException(HttpServletResponse.SC_FORBIDDEN, MSG_DATA_ACCESS_DENY, true); - } - if(vXUser!=null && !hasAccessToModule(RangerConstants.MODULE_USER_GROUPS)){ - vXUser=getMaskedVXUser(vXUser); - } - return vXUser; - } - - public VXGroup getGroupByGroupName(String groupName) { - VXGroup vxGroup = xGroupService.getGroupByGroupName(groupName); - if (vxGroup == null) { - throw restErrorUtil.createRESTException( - groupName + " is Not Found", MessageEnums.DATA_NOT_FOUND); - } - return vxGroup; - } - - public VXUser createXUser(VXUser vXUser) { - checkAdminAccess(); - xaBizUtil.blockAuditorRoleUser(); - - if (vXUser.getUserSource() == RangerCommonEnums.USER_FEDERATED) { - if (StringUtils.isEmpty(vXUser.getPassword())) { - PasswordGenerator passwordGenerator = new PasswordGenerator.PasswordGeneratorBuilder() - .useLower(true) - .useUpper(true) - .useDigits(true) - .useSymbols(true) - .build(); - String passWd = passwordGenerator.generate(PASSWORD_LENGTH); - vXUser.setPassword(passWd); - } - } - - validatePassword(vXUser); - String userName = vXUser.getName(); - String firstName = vXUser.getFirstName(); - if (userName == null || "null".equalsIgnoreCase(userName) - || userName.trim().isEmpty()) { - throw restErrorUtil.createRESTException( - "Please provide a valid username.", - MessageEnums.INVALID_INPUT_DATA); - } - - if (firstName == null || "null".equalsIgnoreCase(firstName) - || firstName.trim().isEmpty()) { - throw restErrorUtil.createRESTException( - "Please provide a valid first name.", - MessageEnums.INVALID_INPUT_DATA); - } - - if (vXUser.getDescription() == null) { - vXUser.setDescription(vXUser.getName()); - } - - String actualPassword = vXUser.getPassword(); - - VXPortalUser vXPortalUser = new VXPortalUser(); - vXPortalUser.setLoginId(userName); - vXPortalUser.setFirstName(vXUser.getFirstName()); - if("null".equalsIgnoreCase(vXPortalUser.getFirstName())){ - vXPortalUser.setFirstName(""); - } - vXPortalUser.setLastName(vXUser.getLastName()); - if("null".equalsIgnoreCase(vXPortalUser.getLastName())){ - vXPortalUser.setLastName(""); - } - - String emailAddress = vXUser.getEmailAddress(); - if (StringUtils.isNotEmpty(emailAddress) && !stringUtil.validateEmail(emailAddress)) { - logger.warn("Invalid email address:" + emailAddress); - throw restErrorUtil.createRESTException("Please provide valid email address.", - MessageEnums.INVALID_INPUT_DATA); - } - vXPortalUser.setEmailAddress(emailAddress); - - if (vXPortalUser.getFirstName() != null - && vXPortalUser.getLastName() != null - && !vXPortalUser.getFirstName().trim().isEmpty() - && !vXPortalUser.getLastName().trim().isEmpty()) { - vXPortalUser.setPublicScreenName(vXPortalUser.getFirstName() + " " - + vXPortalUser.getLastName()); - } else { - vXPortalUser.setPublicScreenName(vXUser.getName()); - } - vXPortalUser.setPassword(actualPassword); - vXPortalUser.setUserRoleList(vXUser.getUserRoleList()); - vXPortalUser = userMgr.createDefaultAccountUser(vXPortalUser); - - VXUser createdXUser = xUserService.createResource(vXUser); - - createdXUser.setPassword(actualPassword); - List trxLogList = xUserService.getTransactionLog(createdXUser, null, OPERATION_CREATE_CONTEXT); - - String hiddenPassword = PropertiesUtil.getProperty("ranger.password.hidden", "*****"); - createdXUser.setPassword(hiddenPassword); - Collection groupNamesList = new ArrayList(); - Collection groupIdList = vXUser.getGroupIdList(); - List vXGroupUsers = new ArrayList(); - if (groupIdList != null) { - for (Long groupId : groupIdList) { - VXGroupUser vXGroupUser = createXGroupUser( - createdXUser.getId(), groupId); - // trxLogList.addAll(xGroupUserService.getTransactionLog( - // vXGroupUser, "create")); - vXGroupUsers.add(vXGroupUser); - groupNamesList.add(vXGroupUser.getName()); - } - } - createdXUser.setGroupIdList(groupIdList); - createdXUser.setGroupNameList(groupNamesList); - for (VXGroupUser vXGroupUser : vXGroupUsers) { - List groupUserTrxLogs = xGroupUserService.getTransactionLog(vXGroupUser, null, OPERATION_CREATE_CONTEXT); - - if (CollectionUtils.isNotEmpty(groupUserTrxLogs)) { - if (trxLogList == null) { - trxLogList = new ArrayList<>(); - } - - trxLogList.addAll(groupUserTrxLogs); - } - } - // - xaBizUtil.createTrxLog(trxLogList); - if(vXPortalUser!=null){ - assignPermissionToUser(vXPortalUser, true); - } - - updateUserStoreVersion("createXUser(" + vXUser.getName() + ")"); - - return createdXUser; - } - - public void assignPermissionToUser(VXPortalUser vXPortalUser, boolean isCreate) { - HashMap moduleNameId = getAllModuleNameAndIdMap(); - if(moduleNameId!=null && vXPortalUser!=null && CollectionUtils.isNotEmpty(vXPortalUser.getUserRoleList())){ - for (String role : vXPortalUser.getUserRoleList()) { - if (RangerConstants.VALID_USER_ROLE_LIST.contains(role)){ - createOrUpdateUserPermisson(vXPortalUser, moduleNameId.get(RangerConstants.MODULE_RESOURCE_BASED_POLICIES), isCreate); - createOrUpdateUserPermisson(vXPortalUser, moduleNameId.get(RangerConstants.MODULE_REPORTS), isCreate); - if (role.equals(RangerConstants.ROLE_USER)){ - createOrUpdateUserPermisson(vXPortalUser, moduleNameId.get(RangerConstants.MODULE_SECURITY_ZONE), isCreate); - } else { - createOrUpdateUserPermisson(vXPortalUser, moduleNameId.get(RangerConstants.MODULE_AUDIT), isCreate); - createOrUpdateUserPermisson(vXPortalUser, moduleNameId.get(RangerConstants.MODULE_USER_GROUPS),isCreate); - createOrUpdateUserPermisson(vXPortalUser, moduleNameId.get(RangerConstants.MODULE_GOVERNED_DATA_SHARING), isCreate); - - if (role.equals(RangerConstants.ROLE_SYS_ADMIN) || role.equals(RangerConstants.ROLE_ADMIN_AUDITOR)) { - - createOrUpdateUserPermisson(vXPortalUser, moduleNameId.get(RangerConstants.MODULE_TAG_BASED_POLICIES), isCreate); - createOrUpdateUserPermisson(vXPortalUser, moduleNameId.get(RangerConstants.MODULE_SECURITY_ZONE), isCreate); - - } else { - createOrUpdateUserPermisson(vXPortalUser, moduleNameId.get(RangerConstants.MODULE_KEY_MANAGER), isCreate); - } - } - } - } - } - } - - // Insert or Updating Mapping permissions depending upon roles - public void createOrUpdateUserPermisson(VXPortalUser portalUser, Long moduleId, boolean isCreate) { - VXUserPermission vXUserPermission; - XXUserPermission xUserPermission = daoManager.getXXUserPermission().findByModuleIdAndPortalUserId(portalUser.getId(), moduleId); - if (xUserPermission == null) { - vXUserPermission = new VXUserPermission(); - - // When Creating XXUserPermission UI sends xUserId, to keep it consistent here xUserId should be used - XXUser xUser = daoManager.getXXUser().findByPortalUserId(portalUser.getId()); - if (xUser == null) { - logger.warn("Could not found corresponding xUser for username: [" + portalUser.getLoginId() + "], So not assigning permission to this user"); - return; - } else { - vXUserPermission.setUserId(xUser.getId()); - } - - vXUserPermission.setIsAllowed(RangerCommonEnums.IS_ALLOWED); - vXUserPermission.setModuleId(moduleId); - try { - vXUserPermission = this.createXUserPermission(vXUserPermission); - logger.info("Permission assigned to user: [" + vXUserPermission.getUserName() + "] For Module: [" + vXUserPermission.getModuleName() + "]"); - } catch (Exception e) { - logger.error("Error while assigning permission to user: [" + portalUser.getLoginId() + "] for module: [" + moduleId + "]", e); - } - } else if (isCreate) { - vXUserPermission = xUserPermissionService.populateViewBean(xUserPermission); - vXUserPermission.setIsAllowed(RangerCommonEnums.IS_ALLOWED); - vXUserPermission = this.updateXUserPermission(vXUserPermission); - logger.info("Permission Updated for user: [" + vXUserPermission.getUserName() + "] For Module: [" + vXUserPermission.getModuleName() + "]"); - } - } - - public HashMap getAllModuleNameAndIdMap() { - - List xXModuleDefs = daoManager.getXXModuleDef().getAll(); - - if (!CollectionUtils.isEmpty(xXModuleDefs)) { - HashMap moduleNameAndIdMap = new HashMap(); - for (XXModuleDef xXModuleDef : xXModuleDefs) { - moduleNameAndIdMap.put(xXModuleDef.getModule(), xXModuleDef.getId()); - } - return moduleNameAndIdMap; - } - - return null; - } - - protected 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) { - if (vXUser == null || vXUser.getName() == null - || "null".equalsIgnoreCase(vXUser.getName()) - || vXUser.getName().trim().isEmpty()) { - throw restErrorUtil.createRESTException("Please provide a valid " - + "username.", MessageEnums.INVALID_INPUT_DATA); - } - String firstName = vXUser.getFirstName(); - if (firstName == null || "null".equalsIgnoreCase(firstName) - || firstName.trim().isEmpty()) { - throw restErrorUtil.createRESTException("Please provide a valid first name.", MessageEnums.INVALID_INPUT_DATA); - } - - checkAccess(vXUser); - xaBizUtil.blockAuditorRoleUser(); - VXPortalUser oldUserProfile = userMgr.getUserProfileByLoginId(vXUser - .getName()); - if (oldUserProfile == null) { - throw restErrorUtil.createRESTException( - "user " + vXUser.getName() + " does not exist.", - MessageEnums.INVALID_INPUT_DATA); - } - VXPortalUser vXPortalUser = new VXPortalUser(); - if (oldUserProfile != null && oldUserProfile.getId() != null) { - vXPortalUser.setId(oldUserProfile.getId()); - } - - vXPortalUser.setFirstName(vXUser.getFirstName()); - if("null".equalsIgnoreCase(vXPortalUser.getFirstName())){ - vXPortalUser.setFirstName(""); - } - vXPortalUser.setLastName(vXUser.getLastName()); - if("null".equalsIgnoreCase(vXPortalUser.getLastName())){ - vXPortalUser.setLastName(""); - } - vXPortalUser.setEmailAddress(vXUser.getEmailAddress()); - vXPortalUser.setLoginId(vXUser.getName()); - vXPortalUser.setStatus(vXUser.getStatus()); - vXPortalUser.setUserRoleList(vXUser.getUserRoleList()); - if (vXPortalUser.getFirstName() != null - && vXPortalUser.getLastName() != null - && !vXPortalUser.getFirstName().trim().isEmpty() - && !vXPortalUser.getLastName().trim().isEmpty()) { - vXPortalUser.setPublicScreenName(vXPortalUser.getFirstName() + " " - + vXPortalUser.getLastName()); - } else { - vXPortalUser.setPublicScreenName(vXUser.getName()); - } - vXPortalUser.setUserSource(oldUserProfile.getUserSource()); - - String hiddenPasswordString = PropertiesUtil.getProperty("ranger.password.hidden", "*****"); - String password = vXUser.getPassword(); - if (oldUserProfile != null && password != null - && password.equals(hiddenPasswordString)) { - vXPortalUser.setPassword(oldUserProfile.getPassword()); - } - else if(oldUserProfile != null && oldUserProfile.getUserSource() == RangerCommonEnums.USER_EXTERNAL && password != null){ - vXPortalUser.setPassword(oldUserProfile.getPassword()); - logger.debug("User is trrying to change external user password which we are not allowing it to change"); - } - else if(password != null){ - validatePassword(vXUser); - vXPortalUser.setPassword(password); - } - Collection groupIdList = vXUser.getGroupIdList(); - VXUser existing = xUserService.readResource(vXUser.getId()); - XXPortalUser xXPortalUser = new XXPortalUser(); - xXPortalUser = userMgr.updateUserWithPass(vXPortalUser); - //update permissions start - Collection roleListUpdatedProfile =new ArrayList(); - if (oldUserProfile != null && oldUserProfile.getId() != null) { - if(vXUser!=null && vXUser.getUserRoleList()!=null){ - Collection roleListOldProfile = oldUserProfile.getUserRoleList(); - Collection roleListNewProfile = vXUser.getUserRoleList(); - if(roleListNewProfile!=null && roleListOldProfile!=null){ - for (String role : roleListNewProfile) { - if(role!=null && !roleListOldProfile.contains(role)){ - roleListUpdatedProfile.add(role); - } - } - - } - } - } - if(roleListUpdatedProfile!=null && roleListUpdatedProfile.size()>0){ - vXPortalUser.setUserRoleList(roleListUpdatedProfile); - List xuserPermissionList = daoManager - .getXXUserPermission() - .findByUserPermissionId(vXPortalUser.getId()); - if (xuserPermissionList!=null && xuserPermissionList.size()>0){ - for (XXUserPermission xXUserPermission : xuserPermissionList) { - if (xXUserPermission != null) { - try { - xUserPermissionService.deleteResource(xXUserPermission.getId()); - } catch (Exception e) { - logger.error(e.getMessage()); - } - } - } - } - assignPermissionToUser(vXPortalUser,true); - } - //update permissions end - Collection roleList = new ArrayList(); - if (xXPortalUser != null) { - roleList = userMgr.getRolesForUser(xXPortalUser); - } - if (roleList == null || roleList.size() == 0) { - roleList = new ArrayList(); - roleList.add(RangerConstants.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); - if (oldUserProfile != null) { - if (oldUserProfile.getUserSource() == RangerCommonEnums.USER_APP) { - vXUser.setPassword(password); - } - else if (oldUserProfile.getUserSource() == RangerCommonEnums.USER_EXTERNAL) { - vXUser.setPassword(oldUserProfile.getPassword()); - } - } - - if(password == null) { - vXUser.setPassword(hiddenPasswordString); //To stop Auditing Password transaction log, when it is not edited. - } - List trxLogList = xUserService.getTransactionLog(vXUser, existing, OPERATION_UPDATE_CONTEXT); - vXUser.setPassword(hiddenPasswordString); - - Long userId = vXUser.getId(); - List groupUsersToRemove = new ArrayList(); - List groupUserTrxLogs = createOrDelGrpUserWithUpdatedGrpId(vXUser, groupIdList,userId, groupUsersToRemove); - - if (CollectionUtils.isNotEmpty(groupUserTrxLogs)) { - if (trxLogList == null) { - trxLogList = new ArrayList<>(); - } - - trxLogList.addAll(groupUserTrxLogs); - } - - xaBizUtil.createTrxLog(trxLogList); - - updateUserStoreVersion("updateXUser(" + vXUser.getName() + ")"); - - return vXUser; - } - private List createOrDelGrpUserWithUpdatedGrpId(VXUser vXUser, Collection groupIdList,Long userId, List groupUsersToRemove) { - Collection groupNamesSet = new HashSet(); - List trxLogList = new ArrayList<>(); - if (groupIdList != null) { - SearchCriteria searchCriteria = new SearchCriteria(); - searchCriteria.addParam("xUserId", userId); - VXGroupUserList vXGroupUserList = xGroupUserService.searchXGroupUsers(searchCriteria); - List vXGroupUsers = vXGroupUserList.getList(); - if (vXGroupUsers != null) { - - for(VXGroupUser eachVXGrpUser : vXGroupUsers) { - groupNamesSet.add(eachVXGrpUser.getName()); - } - - // 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); - List groupUserTrxLogs = xGroupUserService.getTransactionLog(vXGroupUser, null, OPERATION_CREATE_CONTEXT); - if (CollectionUtils.isNotEmpty(groupUserTrxLogs)) { - trxLogList.addAll(groupUserTrxLogs); - } - groupNamesSet.add(vXGroupUser.getName()); - } - } - - // Delete - for (VXGroupUser vXGroupUser : vXGroupUsers) { - boolean found = false; - for (Long groupId : groupIdList) { - if (groupId.equals(vXGroupUser.getParentGroupId())) { - List groupUserTrxLogs = xGroupUserService.getTransactionLog(vXGroupUser, null, OPERATION_UPDATE_CONTEXT); - if (CollectionUtils.isNotEmpty(groupUserTrxLogs)) { - trxLogList.addAll(groupUserTrxLogs); - } - found = true; - break; - } - } - if (!found) { - // TODO I've to get the transaction log from here. - List groupUserTrxLogs = xGroupUserService.getTransactionLog(vXGroupUser, null, OPERATION_DELETE_CONTEXT); - if (CollectionUtils.isNotEmpty(groupUserTrxLogs)) { - trxLogList.addAll(groupUserTrxLogs); - } - groupUsersToRemove.add(vXGroupUser.getId()); - // xGroupUserService.deleteResource(vXGroupUser.getId()); - groupNamesSet.remove(vXGroupUser.getName()); - } - } - - } else { - for (Long groupId : groupIdList) { - VXGroupUser vXGroupUser = createXGroupUser(userId, groupId); - List groupUserTrxLogs = xGroupUserService.getTransactionLog(vXGroupUser, null, OPERATION_CREATE_CONTEXT); - if (CollectionUtils.isNotEmpty(groupUserTrxLogs)) { - trxLogList.addAll(groupUserTrxLogs); - } - groupNamesSet.add(vXGroupUser.getName()); - } - } - vXUser.setGroupIdList(groupIdList); - vXUser.setGroupNameList(new ArrayList<>(groupNamesSet)); - } else { - logger.debug( - "Group id list can't be null for user. Group user " + "mapping not updated for user : " + userId); - } - for (Long groupUserId : groupUsersToRemove) { - xGroupUserService.deleteResource(groupUserId); - } - return trxLogList; - } - - public VXUserGroupInfo createXUserGroupFromMap(VXUserGroupInfo vXUserGroupInfo) { - checkAdminAccess(); - xaBizUtil.blockAuditorRoleUser(); - VXUserGroupInfo vxUGInfo = new VXUserGroupInfo(); - VXUser vXUser = vXUserGroupInfo.getXuserInfo(); - VXPortalUser vXPortalUser = userMgr.getUserProfileByLoginId(vXUser - .getName()); - XXPortalUser xxPortalUser = daoManager.getXXPortalUser().findByLoginId( - vXUser.getName()); - Collection reqRoleList = vXUser.getUserRoleList(); - List existingRole = daoManager.getXXPortalUserRole() - .findXPortalUserRolebyXPortalUserId(xxPortalUser.getId()); - if (xxPortalUser.getUserSource() == RangerCommonEnums.USER_EXTERNAL) { - vXPortalUser = userMgr.updateRoleForExternalUsers(reqRoleList, existingRole, vXPortalUser); - } - vXUser = xUserService.createXUserWithOutLogin(vXUser); - vxUGInfo.setXuserInfo(vXUser); - List vxg = new ArrayList(); - for (VXGroup vXGroup : vXUserGroupInfo.getXgroupInfo()) { - VXGroup VvXGroup = xGroupService.createXGroupWithOutLogin(vXGroup); - vxg.add(VvXGroup); - VXGroupUser vXGroupUser = new VXGroupUser(); - vXGroupUser.setUserId(vXUser.getId()); - vXGroupUser.setName(VvXGroup.getName()); - vXGroupUser = xGroupUserService - .createXGroupUserWithOutLogin(vXGroupUser); - } - if (vXPortalUser != null) { - assignPermissionToUser(vXPortalUser, true); - } - vxUGInfo.setXgroupInfo(vxg); - - updateUserStoreVersion("createXUserGroupFromMap(" + vXUser.getName() + ")"); - - return vxUGInfo; - } - - @Transactional(readOnly = false, propagation = Propagation.REQUIRED) - public VXGroupUserInfo createXGroupUserFromMap( - VXGroupUserInfo vXGroupUserInfo) { - checkAdminAccess(); - xaBizUtil.blockAuditorRoleUser(); - VXGroupUserInfo vxGUInfo = new VXGroupUserInfo(); - - VXGroup vXGroup = vXGroupUserInfo.getXgroupInfo(); - // Add the group user mappings for a given group to x_group_user table - /*XXGroup xGroup = daoManager.getXXGroup().findByGroupName(vXGroup.getName()); - if (xGroup == null) { - return vxGUInfo; - }*/ - - List vxu = new ArrayList(); - for (VXUser vXUser : vXGroupUserInfo.getXuserInfo()) { - XXUser xUser = daoManager.getXXUser().findByUserName( - vXUser.getName()); - XXPortalUser xXPortalUser = daoManager.getXXPortalUser() - .findByLoginId(vXUser.getName()); - if (xUser != null) { - // Add or update group user mapping only if the user already exists in x_user table. - logger.debug(String.format("createXGroupUserFromMap(): Create or update group %s ", vXGroup.getName())); - vXGroup = xGroupService.createXGroupWithOutLogin(vXGroup); - vxGUInfo.setXgroupInfo(vXGroup); - vxu.add(vXUser); - VXGroupUser vXGroupUser = new VXGroupUser(); - vXGroupUser.setUserId(xUser.getId()); - vXGroupUser.setName(vXGroup.getName()); - if (xXPortalUser.getUserSource() == RangerCommonEnums.USER_EXTERNAL) { - vXGroupUser = xGroupUserService - .createXGroupUserWithOutLogin(vXGroupUser); - logger.debug(String.format("createXGroupUserFromMap(): Create or update group user mapping with groupname = " + vXGroup.getName() - + " username = %s userId = %d", xXPortalUser.getLoginId(), xUser.getId())); - } - Collection reqRoleList = vXUser.getUserRoleList(); - - XXPortalUser xxPortalUser = daoManager.getXXPortalUser() - .findByLoginId(vXUser.getName()); - List existingRole = daoManager.getXXPortalUserRole() - .findXPortalUserRolebyXPortalUserId( - xxPortalUser.getId()); - VXPortalUser vxPortalUser = userMgr - .mapXXPortalUserToVXPortalUserForDefaultAccount(xxPortalUser); - if (xxPortalUser.getUserSource() == RangerCommonEnums.USER_EXTERNAL) { - vxPortalUser = userMgr.updateRoleForExternalUsers( - reqRoleList, existingRole, vxPortalUser); - assignPermissionToUser(vxPortalUser, true); - } - } - } - - vxGUInfo.setXuserInfo(vxu); - - updateUserStoreVersion("createXGroupUserFromMap(" + vXGroup.getName() + ")"); - - return vxGUInfo; - } - - public VXGroupUserInfo getXGroupUserFromMap( - String groupName) { - checkAdminAccess(); - VXGroupUserInfo vxGUInfo = new VXGroupUserInfo(); - - XXGroup xGroup = daoManager.getXXGroup().findByGroupName(groupName); - if (xGroup == null) { - return vxGUInfo; - } - - VXGroup xgroupInfo = xGroupService.populateViewBean(xGroup); - vxGUInfo.setXgroupInfo(xgroupInfo); - - SearchCriteria searchCriteria = new SearchCriteria(); - searchCriteria.addParam("xGroupId", xGroup.getId()); - - VXGroupUserList vxGroupUserList = searchXGroupUsers(searchCriteria); - List vxu = new ArrayList(); - logger.debug("removing all the group user mapping for : " + xGroup.getName()); - for (VXGroupUser groupUser : vxGroupUserList.getList()) { - XXUser xUser = daoManager.getXXUser().getById(groupUser.getUserId()); - if (xUser != null) { - VXUser vxUser = new VXUser(); - vxUser.setName(xUser.getName()); - XXPortalUser xXPortalUser = daoManager.getXXPortalUser() - .findByLoginId(xUser.getName()); - if (xXPortalUser != null) { - List existingRole = daoManager - .getXXPortalUserRole() - .findXPortalUserRolebyXPortalUserId( - xXPortalUser.getId()); - if (existingRole != null) { - vxUser.setUserRoleList(existingRole); - } - } - vxu.add(vxUser); - } - - } - vxGUInfo.setXuserInfo(vxu); - - return vxGUInfo; - } - - - public VXUser createXUserWithOutLogin(VXUser vXUser) { - checkAdminAccess(); - xaBizUtil.blockAuditorRoleUser(); - validatePassword(vXUser); - VXUser ret = xUserService.createXUserWithOutLogin(vXUser); - - updateUserStoreVersion("createXUserWithOutLogin(" + vXUser.getName() + ")"); - - return ret; - } - - public VXUser createExternalUser(String userName) { - checkAdminAccess(); - xaBizUtil.blockAuditorRoleUser(); - return createServiceConfigUser(userName); - } - - public VXGroup createXGroup(VXGroup vXGroup) { - checkAdminAccess(); - xaBizUtil.blockAuditorRoleUser(); - if (vXGroup.getDescription() == null) { - vXGroup.setDescription(vXGroup.getName()); - } - - vXGroup = xGroupService.createResource(vXGroup); - xGroupService.createTransactionLog(vXGroup, null, OPERATION_CREATE_CONTEXT); - - updateUserStoreVersion("createXGroup(" + vXGroup.getName() + ")"); - - return vXGroup; - } - - public VXGroup createXGroupWithoutLogin(VXGroup vXGroup) { - checkAdminAccess(); - xaBizUtil.blockAuditorRoleUser(); - - VXGroup ret = xGroupService.createXGroupWithOutLogin(vXGroup); - - updateUserStoreVersion("createXGroupWithoutLogin(" + vXGroup.getName() + ")"); - - return ret; - } - - public VXGroupUser createXGroupUser(VXGroupUser vXGroupUser) { - checkAdminAccess(); - xaBizUtil.blockAuditorRoleUser(); - vXGroupUser = xGroupUserService - .createXGroupUserWithOutLogin(vXGroupUser); - return vXGroupUser; - } - - public VXUser getXUser(Long id) { - VXUser vXUser=null; - vXUser=xUserService.readResourceWithOutLogin(id); - if(vXUser != null && !hasAccessToGetUserInfo(vXUser)){ - logger.info(MSG_DATA_ACCESS_DENY); - throw restErrorUtil.createRESTException(HttpServletResponse.SC_FORBIDDEN, MSG_DATA_ACCESS_DENY, true); - } - - if(vXUser!=null && !hasAccessToModule(RangerConstants.MODULE_USER_GROUPS)){ - vXUser=getMaskedVXUser(vXUser); - } - return vXUser; - } - - private boolean hasAccessToGetUserInfo(VXUser requestedVXUser) { - UserSessionBase userSession = ContextUtil.getCurrentUserSession(); - if (userSession != null && userSession.getLoginId() != null) { - VXUser loggedInVXUser = xUserService.getXUserByUserName(userSession.getLoginId()); - if (requestedVXUser != null && CollectionUtils.isNotEmpty(requestedVXUser.getUserRoleList()) && loggedInVXUser != null && loggedInVXUser.getUserRoleList().size() == 1) { - if (loggedInVXUser.getUserRoleList().contains(RangerConstants.ROLE_USER)) { - return requestedVXUser.getId().equals(loggedInVXUser.getId()) ? true : false; - } else if (loggedInVXUser.getUserRoleList().contains(RangerConstants.ROLE_KEY_ADMIN) || loggedInVXUser.getUserRoleList().contains(RangerConstants.ROLE_KEY_ADMIN_AUDITOR)) { - if (requestedVXUser.getUserRoleList().contains(RangerConstants.ROLE_KEY_ADMIN) || requestedVXUser.getUserRoleList().contains(RangerConstants.ROLE_KEY_ADMIN_AUDITOR) || requestedVXUser.getUserRoleList().contains(RangerConstants.ROLE_USER)) { - return true; - } - } else if (loggedInVXUser.getUserRoleList().contains(RangerConstants.ROLE_SYS_ADMIN) || loggedInVXUser.getUserRoleList().contains(RangerConstants.ROLE_ADMIN_AUDITOR)) { - if (loggedInVXUser.getUserRoleList().contains(RangerConstants.ROLE_SYS_ADMIN) && "rangerusersync".equalsIgnoreCase(userSession.getLoginId())) { - return true; - } else if (requestedVXUser.getUserRoleList().contains(RangerConstants.ROLE_SYS_ADMIN) || requestedVXUser.getUserRoleList().contains(RangerConstants.ROLE_ADMIN_AUDITOR) || requestedVXUser.getUserRoleList().contains(RangerConstants.ROLE_USER)) { - return true; - } - } - } - } - return false; - } - - public VXGroupUser getXGroupUser(Long id) { - return xGroupUserService.readResourceWithOutLogin(id); - - } - - public VXGroup getXGroup(Long id) { - VXGroup vXGroup=null; - - UserSessionBase userSession = ContextUtil.getCurrentUserSession(); - if (userSession != null && userSession.getLoginId() != null) { - VXUser loggedInVXUser = xUserService.getXUserByUserName(userSession - .getLoginId()); - if (loggedInVXUser != null) { - if (loggedInVXUser.getUserRoleList().size() == 1 - && loggedInVXUser.getUserRoleList().contains( - RangerConstants.ROLE_USER)) { - - List listGroupId = daoManager.getXXGroupUser() - .findGroupIdListByUserId(loggedInVXUser.getId()); - - if (!listGroupId.contains(id)) { - logger.info(MSG_DATA_ACCESS_DENY); - throw restErrorUtil - .create403RESTException("Logged-In user is not allowed to access requested group data."); - } - - } - } - } - vXGroup=xGroupService.readResourceWithOutLogin(id); - if(vXGroup!=null && !hasAccessToModule(RangerConstants.MODULE_USER_GROUPS)){ - vXGroup=getMaskedVXGroup(vXGroup); - } - return vXGroup; - } - - /** - * // 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) { - checkAdminAccess(); - xaBizUtil.blockAuditorRoleUser(); - 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 vXGroups = new ArrayList(); - if (vXGroupUserList != null) { - List vXGroupUsers = vXGroupUserList.getList(); - Set groupIdList = new HashSet(); - 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 Set getGroupsForUser(String userName) { - Set ret = new HashSet(); - - try { - VXUser user = getXUserByUserName(userName); - - if (user != null) { - VXGroupList groups = getXUserGroups(user.getId()); - - if (groups != null - && !CollectionUtils.isEmpty(groups.getList())) { - for (VXGroup group : groups.getList()) { - ret.add(group.getName()); - } - } else { - if (logger.isDebugEnabled()) { - logger.debug("getGroupsForUser('" + userName - + "'): no groups found for user"); - } - } - } else { - if (logger.isDebugEnabled()) { - logger.debug("getGroupsForUser('" + userName - + "'): user not found"); - } - } - } catch (Exception excp) { - logger.error("getGroupsForUser('" + userName + "') failed", excp); - } - - return ret; - } - - public VXUserList getXGroupUsers(SearchCriteria searchCriteria) { - if (!msBizUtil.hasModuleAccess(RangerConstants.MODULE_USER_GROUPS)) { - throw restErrorUtil.createRESTException(HttpServletResponse.SC_FORBIDDEN, "User is not having permissions on the "+RangerConstants.MODULE_USER_GROUPS+" module.", true); - } - VXUserList vXUserList = new VXUserList(); - - VXGroupUserList vXGroupUserList = xGroupUserService - .searchXGroupUsers(searchCriteria); - - - List vXUsers = new ArrayList(); - if (vXGroupUserList != null) { - List vXGroupUsers = vXGroupUserList.getList(); - Set userIdList = new HashSet(); - for (VXGroupUser vXGroupUser : vXGroupUsers) { - userIdList.add(vXGroupUser.getUserId()); - } - for (Long userId : userIdList) { - VXUser vXUser = xUserService.readResource(userId); - vXUsers.add(vXUser); - - } - vXUserList.setVXUsers(vXUsers); - vXUserList.setStartIndex(searchCriteria.getStartIndex()); - vXUserList.setResultSize(vXGroupUserList.getList().size()); - vXUserList.setTotalCount(vXGroupUserList.getTotalCount()); - vXUserList.setPageSize(searchCriteria.getMaxRows()); - vXUserList.setSortBy(vXGroupUserList.getSortBy()); - vXUserList.setSortType(vXGroupUserList.getSortType()); - } else { - logger.debug("No users found for group id : " + searchCriteria.getParamValue("xGroupId")); - } - return vXUserList; - } - - @Override - public VXGroup updateXGroup(VXGroup vXGroup) { - checkAdminAccess(); - xaBizUtil.blockAuditorRoleUser(); - XXGroup xGroup = daoManager.getXXGroup().getById(vXGroup.getId()); - if (vXGroup != null && xGroup != null && !vXGroup.getName().equals(xGroup.getName())) { - throw restErrorUtil.createRESTException( - "group name updates are not allowed.", - MessageEnums.INVALID_INPUT_DATA); - } - VXGroup existing = xGroup != null ? xGroupService.populateViewBean(xGroup) : null; - List trxLogList = xGroupService.getTransactionLog(vXGroup, existing, OPERATION_UPDATE_CONTEXT); - xaBizUtil.createTrxLog(trxLogList); - vXGroup = (VXGroup) xGroupService.updateResource(vXGroup); - if (vXGroup != null) { - updateXgroupUserForGroupUpdate(vXGroup); - RangerServicePoliciesCache.sInstance=null; - } - return vXGroup; - } - - protected void updateXgroupUserForGroupUpdate(VXGroup vXGroup) { - List grpUsers = daoManager.getXXGroupUser().findByGroupId(vXGroup.getId()); - if(CollectionUtils.isNotEmpty(grpUsers)){ - for (XXGroupUser grpUser : grpUsers) { - VXGroupUser vXGroupUser = xGroupUserService.populateViewBean(grpUser); - vXGroupUser.setName(vXGroup.getName()); - updateXGroupUser(vXGroupUser); - } - } - } - - public VXGroupUser updateXGroupUser(VXGroupUser vXGroupUser) { - checkAdminAccess(); - xaBizUtil.blockAuditorRoleUser(); - return super.updateXGroupUser(vXGroupUser); - } - - public void deleteXGroupUser(Long id, boolean force) { - checkAdminAccess(); - xaBizUtil.blockAuditorRoleUser(); - super.deleteXGroupUser(id, force); - } - - public void deleteXPermMap(Long id, boolean force) { - xaBizUtil.blockAuditorRoleUser(); - if (force) { - XXPermMap xPermMap = daoManager.getXXPermMap().getById(id); - if (xPermMap != null) { - if (xResourceService.readResource(xPermMap.getResourceId()) == null) { - throw restErrorUtil.createRESTException("Invalid Input Data - No resource found with Id: " + xPermMap.getResourceId(), MessageEnums.INVALID_INPUT_DATA); - } - } - - xPermMapService.deleteResource(id); - } else { - throw restErrorUtil.createRESTException("serverMsg.modelMgrBaseDeleteModel", MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY); - } - } - - public VXLong getXPermMapSearchCount(SearchCriteria searchCriteria) { - VXPermMapList permMapList = xPermMapService.searchXPermMaps(searchCriteria); - VXLong vXLong = new VXLong(); - vXLong.setValue(permMapList.getListSize()); - return vXLong; - } - - public void deleteXAuditMap(Long id, boolean force) { - xaBizUtil.blockAuditorRoleUser(); - if (force) { - XXAuditMap xAuditMap = daoManager.getXXAuditMap().getById(id); - if (xAuditMap != null) { - if (xResourceService.readResource(xAuditMap.getResourceId()) == null) { - throw restErrorUtil.createRESTException("Invalid Input Data - No resource found with Id: " + xAuditMap.getResourceId(), MessageEnums.INVALID_INPUT_DATA); - } - } - - xAuditMapService.deleteResource(id); - } else { - throw restErrorUtil.createRESTException("serverMsg.modelMgrBaseDeleteModel", MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY); - } - } - - public VXLong getXAuditMapSearchCount(SearchCriteria searchCriteria) { - VXAuditMapList auditMapList = xAuditMapService.searchXAuditMaps(searchCriteria); - VXLong vXLong = new VXLong(); - vXLong.setValue(auditMapList.getListSize()); - return vXLong; - } - - public void modifyUserVisibility(HashMap visibilityMap) { - checkAdminAccess(); - xaBizUtil.blockAuditorRoleUser(); - Set> entries = visibilityMap.entrySet(); - for (Map.Entry entry : entries) { - XXUser xUser = daoManager.getXXUser().getById(entry.getKey()); - VXUser vObj = xUserService.populateViewBean(xUser); - vObj.setIsVisible(entry.getValue()); - vObj = xUserService.updateResource(vObj); - } - } - - public void modifyGroupsVisibility(HashMap groupVisibilityMap) { - checkAdminAccess(); - xaBizUtil.blockAuditorRoleUser(); - Set> entries = groupVisibilityMap.entrySet(); - for (Map.Entry entry : entries) { - XXGroup xGroup = daoManager.getXXGroup().getById(entry.getKey()); - VXGroup vObj = xGroupService.populateViewBean(xGroup); - vObj.setIsVisible(entry.getValue()); - vObj = xGroupService.updateResource(vObj); - } - } - - // Module permissions - public VXModuleDef createXModuleDefPermission(VXModuleDef vXModuleDef) { - - XXModuleDef xModDef = daoManager.getXXModuleDef().findByModuleName(vXModuleDef.getModule()); - - if (xModDef != null) { - throw restErrorUtil.createRESTException("Module Def with same name already exists.", MessageEnums.ERROR_DUPLICATE_OBJECT); - } - - return xModuleDefService.createResource(vXModuleDef); - } - - public VXModuleDef getXModuleDefPermission(Long id) { - return xModuleDefService.readResource(id); - } - - public VXModuleDef updateXModuleDefPermission(VXModuleDef vXModuleDef) { - - List groupPermListNew = vXModuleDef.getGroupPermList(); - List userPermListNew = vXModuleDef.getUserPermList(); - - List groupPermListOld = new ArrayList(); - List userPermListOld = new ArrayList(); - - XXModuleDef xModuleDef = daoManager.getXXModuleDef().getById(vXModuleDef.getId()); - if(!StringUtils.equals(xModuleDef.getModule(), vXModuleDef.getModule())) { - throw restErrorUtil.createRESTException("Module name change is not allowed!", MessageEnums.DATA_NOT_UPDATABLE); - } - - Map xXPortalUserIdXXUserMap = xUserService.getXXPortalUserIdXXUserNameMap(); - Map xXGroupMap = xGroupService.getXXGroupIdNameMap(); - VXModuleDef vModuleDefPopulateOld = xModuleDefService.populateViewBean(xModuleDef, xXPortalUserIdXXUserMap, xXGroupMap, true); - groupPermListOld = vModuleDefPopulateOld.getGroupPermList(); - userPermListOld = vModuleDefPopulateOld.getUserPermList(); - Map userPermMapOld = xUserPermissionService.convertVListToVMap(userPermListOld); - Map groupPermMapOld = xGroupPermissionService.convertVListToVMap(groupPermListOld); - - if (groupPermMapOld != null && groupPermListNew != null) { - for (VXGroupPermission newVXGroupPerm : groupPermListNew) { - boolean isExist = false; - VXGroupPermission oldVXGroupPerm = groupPermMapOld.get(newVXGroupPerm.getGroupId()); - if (oldVXGroupPerm != null && newVXGroupPerm.getGroupId().equals(oldVXGroupPerm.getGroupId()) - && newVXGroupPerm.getModuleId().equals(oldVXGroupPerm.getModuleId())) { - isExist = true; - if (!newVXGroupPerm.getIsAllowed().equals(oldVXGroupPerm.getIsAllowed())) { - oldVXGroupPerm.setIsAllowed(newVXGroupPerm.getIsAllowed()); - oldVXGroupPerm = this.updateXGroupPermission(oldVXGroupPerm); - } - } - if (!isExist) { - newVXGroupPerm = this.createXGroupPermission(newVXGroupPerm); - } - } - } - - if (userPermMapOld != null && userPermListNew != null) { - for (VXUserPermission newVXUserPerm : userPermListNew) { - - boolean isExist = false; - VXUserPermission oldVXUserPerm = userPermMapOld.get(newVXUserPerm.getUserId()); - if (oldVXUserPerm != null && newVXUserPerm.getUserId().equals(oldVXUserPerm.getUserId()) - && newVXUserPerm.getModuleId().equals(oldVXUserPerm.getModuleId())) { - isExist = true; - if (!newVXUserPerm.getIsAllowed().equals(oldVXUserPerm.getIsAllowed())) { - oldVXUserPerm.setIsAllowed(newVXUserPerm.getIsAllowed()); - oldVXUserPerm = this.updateXUserPermission(oldVXUserPerm); - } - } - if (!isExist) { - newVXUserPerm = this.createXUserPermission(newVXUserPerm); - } - } - } - vXModuleDef = xModuleDefService.updateResource(vXModuleDef); - - return vXModuleDef; - } - - public void deleteXModuleDefPermission(Long id, boolean force) { - daoManager.getXXUserPermission().deleteByModuleId(id); - daoManager.getXXGroupPermission().deleteByModuleId(id); - xModuleDefService.deleteResource(id); - } - - // User permission - public VXUserPermission createXUserPermission(VXUserPermission vXUserPermission) { - - vXUserPermission = xUserPermissionService.createResource(vXUserPermission); - - Set userSessions = sessionMgr.getActiveUserSessionsForPortalUserId(vXUserPermission.getUserId()); - if (!CollectionUtils.isEmpty(userSessions)) { - for (UserSessionBase userSession : userSessions) { - logger.info("Assigning permission to user who's found logged in into system, so updating permission in session of that user: [" + vXUserPermission.getUserName() - + "]"); - sessionMgr.resetUserModulePermission(userSession); - } - } - - return vXUserPermission; - } - - public VXUserPermission getXUserPermission(Long id) { - return xUserPermissionService.readResource(id); - } - - public VXUserPermission updateXUserPermission(VXUserPermission vXUserPermission) { - - vXUserPermission = xUserPermissionService.updateResource(vXUserPermission); - - Set userSessions = sessionMgr.getActiveUserSessionsForPortalUserId(vXUserPermission.getUserId()); - if (!CollectionUtils.isEmpty(userSessions)) { - for (UserSessionBase userSession : userSessions) { - logger.info("Updating permission of user who's found logged in into system, so updating permission in session of user: [" + vXUserPermission.getUserName() + "]"); - sessionMgr.resetUserModulePermission(userSession); - } - } - - return vXUserPermission; - } - - public void deleteXUserPermission(Long id, boolean force) { - - XXUserPermission xUserPermission = daoManager.getXXUserPermission().getById(id); - if (xUserPermission == null) { - throw restErrorUtil.createRESTException("No UserPermission found to delete, ID: " + id, MessageEnums.DATA_NOT_FOUND); - } - - xUserPermissionService.deleteResource(id); - - Set userSessions = sessionMgr.getActiveUserSessionsForPortalUserId(xUserPermission.getUserId()); - if (!CollectionUtils.isEmpty(userSessions)) { - for (UserSessionBase userSession : userSessions) { - logger.info("deleting permission of user who's found logged in into system, so updating permission in session of that user"); - sessionMgr.resetUserModulePermission(userSession); - } - } - } - - // Group permission - public VXGroupPermission createXGroupPermission(VXGroupPermission vXGroupPermission) { - - vXGroupPermission = xGroupPermissionService.createResource(vXGroupPermission); - - List grpUsers = daoManager.getXXGroupUser().findByGroupId(vXGroupPermission.getGroupId()); - for (XXGroupUser xGrpUser : grpUsers) { - Set userSessions = sessionMgr.getActiveUserSessionsForXUserId(xGrpUser.getUserId()); - if (!CollectionUtils.isEmpty(userSessions)) { - for (UserSessionBase userSession : userSessions) { - logger.info("Assigning permission to group, one of the user belongs to that group found logged in into system, so updating permission in session of that user"); - sessionMgr.resetUserModulePermission(userSession); - } - } - } - - return vXGroupPermission; - } - - public VXGroupPermission getXGroupPermission(Long id) { - return xGroupPermissionService.readResource(id); - } - - public VXGroupPermission updateXGroupPermission(VXGroupPermission vXGroupPermission) { - - vXGroupPermission = xGroupPermissionService.updateResource(vXGroupPermission); - - List grpUsers = daoManager.getXXGroupUser().findByGroupId(vXGroupPermission.getGroupId()); - for (XXGroupUser xGrpUser : grpUsers) { - Set userSessions = sessionMgr.getActiveUserSessionsForXUserId(xGrpUser.getUserId()); - if (!CollectionUtils.isEmpty(userSessions)) { - for (UserSessionBase userSession : userSessions) { - logger.info("Assigning permission to group whose one of the user found logged in into system, so updating permission in session of that user"); - sessionMgr.resetUserModulePermission(userSession); - } - } - } - - return vXGroupPermission; - } - - public void deleteXGroupPermission(Long id, boolean force) { - - XXGroupPermission xGrpPerm = daoManager.getXXGroupPermission().getById(id); - - if (xGrpPerm == null) { - throw restErrorUtil.createRESTException("No GroupPermission object with ID: [" + id + "found.", MessageEnums.DATA_NOT_FOUND); - } - - xGroupPermissionService.deleteResource(id); - - List grpUsers = daoManager.getXXGroupUser().findByGroupId(xGrpPerm.getGroupId()); - for (XXGroupUser xGrpUser : grpUsers) { - Set userSessions = sessionMgr.getActiveUserSessionsForXUserId(xGrpUser.getUserId()); - if (!CollectionUtils.isEmpty(userSessions)) { - for (UserSessionBase userSession : userSessions) { - logger.info("deleting permission of the group whose one of the user found logged in into system, so updating permission in session of that user"); - sessionMgr.resetUserModulePermission(userSession); - } - } - } - } - - public void modifyUserActiveStatus(HashMap statusMap) { - checkAdminAccess(); - UserSessionBase session = ContextUtil.getCurrentUserSession(); - String currentUser=null; - if(session!=null){ - currentUser=session.getLoginId(); - if(currentUser==null || currentUser.trim().isEmpty()){ - currentUser=null; - } - } - if(currentUser==null){ - return; - } - Set> entries = statusMap.entrySet(); - for (Map.Entry entry : entries) { - if(entry!=null && entry.getKey()!=null && entry.getValue()!=null){ - XXUser xUser = daoManager.getXXUser().getById(entry.getKey()); - if(xUser!=null){ - VXPortalUser vXPortalUser = userMgr.getUserProfileByLoginId(xUser.getName()); - if(vXPortalUser!=null){ - if(vXPortalUser.getLoginId()!=null && !vXPortalUser.getLoginId().equalsIgnoreCase(currentUser)){ - vXPortalUser.setStatus(entry.getValue()); - userMgr.updateUser(vXPortalUser); - } - } - } - } - } - } - - public void checkAdminAccess() { - UserSessionBase session = ContextUtil.getCurrentUserSession(); - if (session != null) { - if (!session.isUserAdmin()) { - VXResponse vXResponse = new VXResponse(); - vXResponse.setStatusCode(HttpServletResponse.SC_FORBIDDEN); - vXResponse.setMsgDesc("Operation" + " denied. LoggedInUser=" + (session != null ? session.getXXPortalUser().getId() : "Not Logged In") - + " ,isn't permitted to perform the action."); - throw restErrorUtil.generateRESTException(vXResponse); - } - } else { - VXResponse vXResponse = new VXResponse(); - vXResponse.setStatusCode(HttpServletResponse.SC_UNAUTHORIZED); // user is null - vXResponse.setMsgDesc("Bad Credentials"); - throw restErrorUtil.generateRESTException(vXResponse); - } - } - - public void checkAccess(VXUser vxUser) { - UserSessionBase session = ContextUtil.getCurrentUserSession(); - if (session != null) { - if (!hasAccessToGetUserInfo(vxUser)) { - throw restErrorUtil.create403RESTException("Operation" + " denied. LoggedInUser=" + (session != null ? session.getXXPortalUser().getId() : "Not Logged In") + " ,isn't permitted to perform the action."); - } - } else { - VXResponse vXResponse = new VXResponse(); - vXResponse.setStatusCode(HttpServletResponse.SC_UNAUTHORIZED); // user is null - vXResponse.setMsgDesc("Bad Credentials"); - throw restErrorUtil.generateRESTException(vXResponse); - } - } - - public VXPermMapList searchXPermMaps(SearchCriteria searchCriteria) { - VXPermMapList returnList = null; - UserSessionBase currentUserSession = ContextUtil.getCurrentUserSession(); - if (currentUserSession != null && currentUserSession.isUserAdmin()) { - returnList = super.searchXPermMaps(searchCriteria); - } else { - returnList = new VXPermMapList(); - int startIndex = searchCriteria.getStartIndex(); - int pageSize = searchCriteria.getMaxRows(); - searchCriteria.setStartIndex(0); - searchCriteria.setMaxRows(Integer.MAX_VALUE); - List resultList = xPermMapService.searchXPermMaps(searchCriteria).getVXPermMaps(); - - List adminPermResourceList = new ArrayList(); - for (VXPermMap xXPermMap : resultList) { - XXResource xRes = daoManager.getXXResource().getById(xXPermMap.getResourceId()); - VXResponse vXResponse = msBizUtil.hasPermission(xResourceService.populateViewBean(xRes), - AppConstants.XA_PERM_TYPE_ADMIN); - if (vXResponse.getStatusCode() == VXResponse.STATUS_SUCCESS) { - adminPermResourceList.add(xXPermMap); - } - } - - if (adminPermResourceList.size() > 0) { - populatePageList(adminPermResourceList, startIndex, pageSize, returnList); - } - } - return returnList; - } - - private void populatePageList(List permMapList, int startIndex, int pageSize, VXPermMapList vxPermMapList) { - List onePageList = new ArrayList(); - for (int i = startIndex; i < pageSize + startIndex && i < permMapList.size(); i++) { - VXPermMap vXPermMap = permMapList.get(i); - onePageList.add(vXPermMap); - } - vxPermMapList.setVXPermMaps(onePageList); - vxPermMapList.setStartIndex(startIndex); - vxPermMapList.setPageSize(pageSize); - vxPermMapList.setResultSize(onePageList.size()); - vxPermMapList.setTotalCount(permMapList.size()); - } - - public VXAuditMapList searchXAuditMaps(SearchCriteria searchCriteria) { - - VXAuditMapList returnList=new VXAuditMapList(); - UserSessionBase currentUserSession = ContextUtil.getCurrentUserSession(); - // If user is system admin - if (currentUserSession != null && currentUserSession.isUserAdmin()) { - returnList = super.searchXAuditMaps(searchCriteria); - } else { - int startIndex = searchCriteria.getStartIndex(); - int pageSize = searchCriteria.getMaxRows(); - searchCriteria.setStartIndex(0); - searchCriteria.setMaxRows(Integer.MAX_VALUE); - List resultList = xAuditMapService.searchXAuditMaps(searchCriteria).getVXAuditMaps(); - - List adminAuditResourceList = new ArrayList(); - for (VXAuditMap xXAuditMap : resultList) { - XXResource xRes = daoManager.getXXResource().getById(xXAuditMap.getResourceId()); - VXResponse vXResponse = msBizUtil.hasPermission(xResourceService.populateViewBean(xRes), - AppConstants.XA_PERM_TYPE_ADMIN); - if (vXResponse.getStatusCode() == VXResponse.STATUS_SUCCESS) { - adminAuditResourceList.add(xXAuditMap); - } - } - - if (adminAuditResourceList.size() > 0) { - populatePageList(adminAuditResourceList, startIndex, pageSize, returnList); - } - } - - return returnList; - } - - private void populatePageList(List auditMapList, int startIndex, int pageSize, - VXAuditMapList vxAuditMapList) { - List onePageList = new ArrayList(); - for (int i = startIndex; i < pageSize + startIndex && i < auditMapList.size(); i++) { - VXAuditMap vXAuditMap = auditMapList.get(i); - onePageList.add(vXAuditMap); - } - vxAuditMapList.setVXAuditMaps(onePageList); - vxAuditMapList.setStartIndex(startIndex); - vxAuditMapList.setPageSize(pageSize); - vxAuditMapList.setResultSize(onePageList.size()); - vxAuditMapList.setTotalCount(auditMapList.size()); - } - - public void checkAccessRoles(List stringRolesList) { - UserSessionBase session = ContextUtil.getCurrentUserSession(); - if (session != null && stringRolesList != null) { - if (!session.isUserAdmin() && !session.isKeyAdmin()) { - throw restErrorUtil.create403RESTException("Permission denied. LoggedInUser=" + (session != null ? session.getXXPortalUser().getId() : "Not Logged In") + " ,isn't permitted to perform the action."); - } else { - if (!"rangerusersync".equals(session.getXXPortalUser().getLoginId())) {// new logic for rangerusersync user - if (session.isUserAdmin() && (stringRolesList.contains(RangerConstants.ROLE_KEY_ADMIN) || stringRolesList.contains(RangerConstants.ROLE_KEY_ADMIN_AUDITOR))) { - throw restErrorUtil.create403RESTException("Permission denied. LoggedInUser=" + (session != null ? session.getXXPortalUser().getId() : "") + " isn't permitted to perform the action."); - } else if (session.isKeyAdmin() && (stringRolesList.contains(RangerConstants.ROLE_SYS_ADMIN) || stringRolesList.contains(RangerConstants.ROLE_ADMIN_AUDITOR))) { - throw restErrorUtil.create403RESTException("Permission denied. LoggedInUser=" + (session != null ? session.getXXPortalUser().getId() : "") + " isn't permitted to perform the action."); - } - } - } - } else { - VXResponse vXResponse = new VXResponse(); - vXResponse.setStatusCode(HttpServletResponse.SC_UNAUTHORIZED); // user is null or role is null - vXResponse.setMsgDesc("Bad Credentials"); - throw restErrorUtil.generateRESTException(vXResponse); - } - } - - public VXStringList setUserRolesByExternalID(Long userId, List vStringRolesList) { - xaBizUtil.blockAuditorRoleUser(); - List roleListNewProfile = new ArrayList(); - if(vStringRolesList!=null){ - for (VXString vXString : vStringRolesList) { - roleListNewProfile.add(vXString.getValue()); - } - } - VXUser vXUser=getXUser(userId); - checkAccessRoles(roleListNewProfile); - List portalUserRoleList =null; - if(vXUser!=null && roleListNewProfile.size()>0){ - VXPortalUser oldUserProfile = userMgr.getUserProfileByLoginId(vXUser.getName()); - if(oldUserProfile!=null){ - denySelfRoleChange(oldUserProfile.getLoginId()); - updateUserRolesPermissions(oldUserProfile,roleListNewProfile); - portalUserRoleList = daoManager.getXXPortalUserRole().findByUserId(oldUserProfile.getId()); - return getStringListFromUserRoleList(portalUserRoleList); - }else{ - throw restErrorUtil.createRESTException("User ID doesn't exist.", MessageEnums.INVALID_INPUT_DATA); - } - }else{ - throw restErrorUtil.createRESTException("User ID doesn't exist.", MessageEnums.INVALID_INPUT_DATA); - } - } - - public VXStringList setUserRolesByName(String userName, List vStringRolesList) { - xaBizUtil.blockAuditorRoleUser(); - List roleListNewProfile = new ArrayList(); - if(vStringRolesList!=null){ - for (VXString vXString : vStringRolesList) { - roleListNewProfile.add(vXString.getValue()); - } - } - VXUser vXUser=getXUserByUserName(userName); - checkAccessRoles(roleListNewProfile); - if(vXUser!=null && roleListNewProfile.size()>0){ - VXPortalUser oldUserProfile = userMgr.getUserProfileByLoginId(vXUser.getName()); - if(oldUserProfile!=null){ - denySelfRoleChange(oldUserProfile.getLoginId()); - updateUserRolesPermissions(oldUserProfile,roleListNewProfile); - List portalUserRoleList = daoManager.getXXPortalUserRole().findByUserId(oldUserProfile.getId()); - return getStringListFromUserRoleList(portalUserRoleList); - }else{ - throw restErrorUtil.createRESTException("Login ID doesn't exist.", MessageEnums.INVALID_INPUT_DATA); - } - }else{ - throw restErrorUtil.createRESTException("Login ID doesn't exist.", MessageEnums.INVALID_INPUT_DATA); - } - - } - - public VXStringList getUserRolesByExternalID(Long userId) { - VXUser vXUser=getXUser(userId); - if(vXUser==null){ - throw restErrorUtil.createRESTException("Please provide a valid ID", MessageEnums.INVALID_INPUT_DATA); - } - checkAccess(vXUser); - List portalUserRoleList =null; - VXPortalUser oldUserProfile = userMgr.getUserProfileByLoginId(vXUser.getName()); - if(oldUserProfile!=null){ - portalUserRoleList = daoManager.getXXPortalUserRole().findByUserId(oldUserProfile.getId()); - return getStringListFromUserRoleList(portalUserRoleList); - }else{ - throw restErrorUtil.createRESTException("User ID doesn't exist.", MessageEnums.INVALID_INPUT_DATA); - } - } - - public VXStringList getUserRolesByName(String userName) { - VXPortalUser vXPortalUser=null; - if(userName!=null && !userName.trim().isEmpty()){ - VXUser vXUser=xUserService.getXUserByUserName(userName); - checkAccess(vXUser); - vXPortalUser = userMgr.getUserProfileByLoginId(userName); - if(vXPortalUser!=null && vXPortalUser.getUserRoleList()!=null){ - List portalUserRoleList = daoManager.getXXPortalUserRole().findByUserId(vXPortalUser.getId()); - return getStringListFromUserRoleList(portalUserRoleList); - }else{ - throw restErrorUtil.createRESTException("Please provide a valid userName", MessageEnums.INVALID_INPUT_DATA); - } - }else{ - throw restErrorUtil.createRESTException("Please provide a valid userName", MessageEnums.INVALID_INPUT_DATA); - } - } - - public void updateUserRolesPermissions(VXPortalUser oldUserProfile,List roleListNewProfile){ - //update permissions start - Collection roleListUpdatedProfile =new ArrayList(); - if (oldUserProfile != null && oldUserProfile.getId() != null) { - Collection roleListOldProfile = oldUserProfile.getUserRoleList(); - if(roleListNewProfile!=null && roleListOldProfile!=null){ - for (String role : roleListNewProfile) { - if(role!=null && !roleListOldProfile.contains(role)){ - roleListUpdatedProfile.add(role); - } - } - } - } - if(roleListUpdatedProfile!=null && roleListUpdatedProfile.size()>0){ - oldUserProfile.setUserRoleList(roleListUpdatedProfile); - List xuserPermissionList = daoManager - .getXXUserPermission() - .findByUserPermissionId(oldUserProfile.getId()); - if (xuserPermissionList!=null && xuserPermissionList.size()>0){ - for (XXUserPermission xXUserPermission : xuserPermissionList) { - if (xXUserPermission != null) { - xUserPermissionService.deleteResource(xXUserPermission.getId()); - } - } - } - assignPermissionToUser(oldUserProfile,true); - if(roleListUpdatedProfile!=null && roleListUpdatedProfile.size()>0){ - userMgr.updateRoles(oldUserProfile.getId(), oldUserProfile.getUserRoleList()); - } - } - //update permissions end - } - - public VXStringList getStringListFromUserRoleList( - List listXXPortalUserRole) { - if(listXXPortalUserRole==null){ - return null; - } - List xStrList = new ArrayList(); - VXString vXStr=null; - for (XXPortalUserRole userRole : listXXPortalUserRole) { - if(userRole!=null){ - vXStr = new VXString(); - vXStr.setValue(userRole.getUserRole()); - xStrList.add(vXStr); - } - } - VXStringList vXStringList = new VXStringList(xStrList); - return vXStringList; - } - - public boolean hasAccess(String loginID) { - UserSessionBase session = ContextUtil.getCurrentUserSession(); - if (session != null) { - if(session.isUserAdmin() || session.getLoginId().equalsIgnoreCase(loginID)){ - return true; - } - } - return false; - } - - public VXUser getMaskedVXUser(VXUser vXUser) { - if(vXUser!=null){ - if(vXUser.getGroupIdList()!=null && vXUser.getGroupIdList().size()>0){ - vXUser.setGroupIdList(new ArrayList()); - } - if(vXUser.getGroupNameList()!=null && vXUser.getGroupNameList().size()>0){ - vXUser.setGroupNameList(getMaskedCollection(vXUser.getGroupNameList())); - } - if(vXUser.getUserRoleList()!=null && vXUser.getUserRoleList().size()>0){ - vXUser.setUserRoleList(getMaskedCollection(vXUser.getUserRoleList())); - } - vXUser.setUpdatedBy(AppConstants.Masked_String); - } - return vXUser; - } - - public VXGroup getMaskedVXGroup(VXGroup vXGroup) { - if(vXGroup!=null){ - vXGroup.setUpdatedBy(AppConstants.Masked_String); - } - return vXGroup; - } - - @Override - public VXUserList searchXUsers(SearchCriteria searchCriteria) { - VXUserList vXUserList = new VXUserList(); - VXUser vXUserExactMatch = null; - try{ - VXUserList vXUserListSort = new VXUserList(); - - if(searchCriteria.getParamList() != null && searchCriteria.getParamList().get("name") != null){ - searchCriteria.setSortBy("name"); - vXUserListSort = xUserService.searchXUsers(searchCriteria); - vXUserExactMatch = getXUserByUserName((String)searchCriteria.getParamList().get("name")); - } - int vXUserExactMatchwithSearchCriteria = 0; - if(vXUserExactMatch != null){ - vXUserListSort = xUserService.searchXUsers(searchCriteria); - HashMap searchCriteriaParamList = searchCriteria.getParamList(); - vXUserExactMatchwithSearchCriteria = 1; - for(Map.Entry entry:searchCriteriaParamList.entrySet()){ - String caseKey=entry.getKey(); - switch (caseKey.toLowerCase()) { - case "isvisible": - Integer isVisible = vXUserExactMatch.getIsVisible(); - if(isVisible != null && !isVisible.equals(entry.getValue())){ - vXUserExactMatchwithSearchCriteria = -1; - } - break; - case "status": - Integer status = vXUserExactMatch.getStatus(); - if(status != null && !status.equals(entry.getValue())){ - vXUserExactMatchwithSearchCriteria = -1; - } - break; - case "usersource": - Integer userSource = vXUserExactMatch.getUserSource(); - if(userSource != null && !userSource.equals(entry.getValue())){ - vXUserExactMatchwithSearchCriteria = -1; - } - break; - case "emailaddress": - String email = (String)entry.getValue(); - if(email != null && !email.equals(vXUserExactMatch.getEmailAddress())){ - vXUserExactMatchwithSearchCriteria = -1; - } - break; - case "userrole": - if(vXUserExactMatch.getUserRoleList() != null && !vXUserExactMatch.getUserRoleList().contains(entry.getValue())){ - vXUserExactMatchwithSearchCriteria = -1; - } - break; - case "userrolelist": - @SuppressWarnings("unchecked") - Collection userrolelist = (Collection) entry.getValue(); - if(!CollectionUtils.isEmpty(userrolelist)){ - for(String role:userrolelist){ - if(vXUserExactMatch.getUserRoleList() != null && vXUserExactMatch.getUserRoleList().contains(role)){ - vXUserExactMatchwithSearchCriteria = 1; - break; - } - else{ - vXUserExactMatchwithSearchCriteria = -1; - } - } - } - break; - default: - logger.warn("XUserMgr.searchXUsers: unexpected searchCriteriaParam:" + caseKey); - break; - } - if(vXUserExactMatchwithSearchCriteria == -1){ - break; - } - } - } - if(vXUserExactMatchwithSearchCriteria == 1){ - VXGroupList groups = getXUserGroups(vXUserExactMatch.getId()); - if(groups.getListSize() > 0){ - Collection groupNameList = new ArrayList(); - Collection groupIdList = new ArrayList(); - for(VXGroup group:groups.getList()){ - groupIdList.add(group.getId()); - groupNameList.add(group.getName()); - } - vXUserExactMatch.setGroupIdList(groupIdList); - vXUserExactMatch.setGroupNameList(groupNameList); - } - List vXUsers = new ArrayList(); - if(searchCriteria.getStartIndex() == 0){ - vXUsers.add(0,vXUserExactMatch); - } - for(VXUser vxUser:vXUserListSort.getVXUsers()){ - if(vXUserExactMatch.getId()!=null && vxUser!=null){ - if(!vXUserExactMatch.getId().equals(vxUser.getId())){ - vXUsers.add(vxUser); - } - } - } - vXUserList.setVXUsers(vXUsers); - vXUserList.setStartIndex(searchCriteria.getStartIndex()); - vXUserList.setResultSize(vXUserList.getVXUsers().size()); - vXUserList.setTotalCount(vXUserListSort.getTotalCount()); - vXUserList.setPageSize(searchCriteria.getMaxRows()); - vXUserList.setSortBy(searchCriteria.getSortBy()); - vXUserList.setSortType(searchCriteria.getSortType()); - } - } catch (Exception e){ - logger.error("Error getting the exact match of user =>"+e); - } - if (vXUserList.getVXUsers().isEmpty()) { - if (StringUtils.isBlank(searchCriteria.getSortBy())) { - searchCriteria.setSortBy("id"); - } - vXUserList = xUserService.searchXUsers(searchCriteria); - } - if(vXUserList!=null && !hasAccessToModule(RangerConstants.MODULE_USER_GROUPS)){ - List vXUsers = new ArrayList(); - if(vXUserList!=null && vXUserList.getListSize()>0){ - for(VXUser vXUser:vXUserList.getList()){ - vXUser=getMaskedVXUser(vXUser); - vXUsers.add(vXUser); - } - vXUserList.setVXUsers(vXUsers); - } - } - return vXUserList; - } - - @Override - public VXGroupList searchXGroups(SearchCriteria searchCriteria) { - VXGroupList vXGroupList= new VXGroupList(); - VXGroup vXGroupExactMatch = null; - VXUser loggedInVXUser = null; - try{ - //In case of user we need to fetch only its associated groups. - UserSessionBase userSession = ContextUtil.getCurrentUserSession(); - if (userSession != null - && userSession.getUserRoleList().size() == 1 - && userSession.getUserRoleList().contains( - RangerConstants.ROLE_USER) - && userSession.getLoginId() != null) { - loggedInVXUser = xUserService.getXUserByUserName(userSession - .getLoginId()); - if (loggedInVXUser != null) { - searchCriteria.addParam("userId", loggedInVXUser.getId()); - } - - } - - VXGroupList vXGroupListSort= new VXGroupList(); - if(searchCriteria.getParamList() != null && searchCriteria.getParamList().get("name") != null){ - searchCriteria.setSortBy("name"); - vXGroupListSort = xGroupService.searchXGroups(searchCriteria); - vXGroupExactMatch = getGroupByGroupName((String) searchCriteria.getParamList().get("name")); - } - int vXGroupExactMatchwithSearchCriteria = 0; - if(vXGroupExactMatch != null){ - HashMap searchCriteriaParamList = searchCriteria.getParamList(); - vXGroupExactMatchwithSearchCriteria = 1; - for (Map.Entry entry: searchCriteriaParamList.entrySet()){ - String caseKey=entry.getKey(); - switch (caseKey.toLowerCase()) { - case "isvisible": - Integer isVisible = vXGroupExactMatch.getIsVisible(); - if(isVisible != null && !isVisible.equals(entry.getValue())){ - vXGroupExactMatchwithSearchCriteria = -1; - } - break; - case "groupsource": - Integer groupsource = vXGroupExactMatch.getGroupSource(); - if(groupsource != null && !groupsource.equals(entry.getValue())){ - vXGroupExactMatchwithSearchCriteria = -1; - } - break; - //Its required because we need to filter groups for user role - case "userid": - if (loggedInVXUser != null) { - List listGroupId = daoManager - .getXXGroupUser() - .findGroupIdListByUserId(loggedInVXUser.getId()); - if (!listGroupId.contains(vXGroupExactMatch.getId())) { - vXGroupExactMatchwithSearchCriteria = -1; - } - } - - break; - default: - logger.warn("XUserMgr.searchXGroups: unexpected searchCriteriaParam:" + caseKey); - break; - } - if(vXGroupExactMatchwithSearchCriteria == -1){ - break; - } - } - } - - if(vXGroupExactMatchwithSearchCriteria == 1){ - List vXGroups = new ArrayList(); - if(searchCriteria.getStartIndex() == 0){ - vXGroups.add(0,vXGroupExactMatch); - } - for(VXGroup vXGroup:vXGroupListSort.getList()){ - if(vXGroupExactMatch.getId() != null && vXGroup != null){ - if(!vXGroupExactMatch.getId().equals(vXGroup.getId())){ - vXGroups.add(vXGroup); - } - } - } - vXGroupList.setVXGroups(vXGroups); - vXGroupList.setStartIndex(searchCriteria.getStartIndex()); - vXGroupList.setResultSize(vXGroupList.getList().size()); - vXGroupList.setTotalCount(vXGroupListSort.getTotalCount()); - vXGroupList.setPageSize(searchCriteria.getMaxRows()); - vXGroupList.setSortBy(searchCriteria.getSortBy()); - vXGroupList.setSortType(searchCriteria.getSortType()); - } - } catch (Exception e){ - logger.error("Error getting the exact match of group =>"+e); - } - if(vXGroupList.getList().isEmpty()) { - if(StringUtils.isBlank(searchCriteria.getSortBy())) { - searchCriteria.setSortBy("id"); - } - vXGroupList=xGroupService.searchXGroups(searchCriteria); - } - - if(vXGroupList!=null && !hasAccessToModule(RangerConstants.MODULE_USER_GROUPS)){ - if(vXGroupList!=null && vXGroupList.getListSize()>0){ - List listMasked=new ArrayList(); - for(VXGroup vXGroup:vXGroupList.getList()){ - vXGroup=getMaskedVXGroup(vXGroup); - listMasked.add(vXGroup); - } - vXGroupList.setVXGroups(listMasked); - } - } - return vXGroupList; - } - - public VXGroupList lookupXGroups(SearchCriteria searchCriteria) { - VXGroupList ret = null; - - try { - HashMap searchParams = searchCriteria.getParamList(); - String nameToLookFor = searchParams != null ? (String) searchParams.get("name") : null; - VXGroup exactMatch = null; - - if (StringUtils.isEmpty(searchCriteria.getSortBy())) { - searchCriteria.setSortBy(nameToLookFor != null ? "name" : "id"); - } - - if(nameToLookFor != null) { - exactMatch = getGroupByGroupName(nameToLookFor); - - for (Map.Entry entry : searchParams.entrySet()) { - if(exactMatch == null) { - break; - } - - String paramName = entry.getKey(); - Object paramValue = entry.getValue(); - - switch (paramName.toLowerCase()) { - case "isvisible": - if (!Objects.equals(exactMatch.getIsVisible(), paramValue)) { - exactMatch = null; - } - break; - - case "groupsource": - if (!Objects.equals(exactMatch.getGroupSource(), paramValue)) { - exactMatch = null; - } - break; - - default: - // ignore - break; - } - } - } - - VXGroupList searchResult = xGroupService.searchXGroups(searchCriteria); - - if (exactMatch != null && exactMatch.getId() != null) { - List groups = searchResult.getList(); - - if (!groups.isEmpty()) { // remove exactMatch from groups if it is present - boolean removed = false; - - for (Iterator iter = groups.iterator(); iter.hasNext(); ) { - VXGroup group = iter.next(); - - if (group != null && exactMatch.getId().equals(group.getId())) { - iter.remove(); - removed = true; - - break; - } - } - - if (!removed) { // remove the last entry, if exactMatch was not removed above - to accomodate for add() below - groups.remove(groups.size() - 1); - } - } - - groups.add(0, exactMatch); - - ret = new VXGroupList(groups); - - ret.setStartIndex(searchCriteria.getStartIndex()); - ret.setTotalCount(searchResult.getTotalCount()); - ret.setPageSize(searchCriteria.getMaxRows()); - ret.setSortBy(searchCriteria.getSortBy()); - ret.setSortType(searchCriteria.getSortType()); - } else { - ret = searchResult; - } - } catch (Exception e) { - logger.error("Error getting the exact match of group =>"+e); - } - if(ret == null || ret.getList().isEmpty()) { - searchCriteria.setSortBy("id"); - ret=xGroupService.searchXGroups(searchCriteria); - } - if (ret != null && ret.getListSize() > 0 && !hasAccessToModule(RangerConstants.MODULE_USER_GROUPS)) { - for(VXGroup vXGroup : ret.getList()) { - getMaskedVXGroup(vXGroup); - } - } - - return ret; - } - - public Collection getMaskedCollection(Collection listunMasked){ - List listMasked=new ArrayList(); - if(listunMasked!=null) { - for(int i = 0; i < listunMasked.size(); i++) { - listMasked.add(AppConstants.Masked_String); - } - } - return listMasked; - } - - public List getRangerPrincipals(SearchCriteria searchCriteria){ - String searchString = (String) searchCriteria.getParamValue("name"); - int startIdx = searchCriteria.getStartIndex(); - int maxRows = searchCriteria.getMaxRows(); - - List ret = daoManager.getXXUser().lookupPrincipalByName(searchString, startIdx, maxRows); - - return ret; - } - - public boolean hasAccessToModule(String moduleName){ - UserSessionBase userSession = ContextUtil.getCurrentUserSession(); - if (userSession != null && userSession.getLoginId()!=null){ - VXUser vxUser = xUserService.getXUserByUserName(userSession.getLoginId()); - if(vxUser!=null){ - List permissionList = daoManager.getXXModuleDef().findAccessibleModulesByUserId(userSession.getUserId(), vxUser.getId()); - if(permissionList!=null && permissionList.contains(moduleName)){ - return true; - } - } - } - return false; - } - - public void deleteXGroup(Long id, boolean force) { - checkAdminAccess(); - blockIfZoneGroup(id); - this.blockIfRoleGroup(id); - xaBizUtil.blockAuditorRoleUser(); - XXGroupDao xXGroupDao = daoManager.getXXGroup(); - XXGroup xXGroup = xXGroupDao.getById(id); - if (xXGroup == null) { - throw restErrorUtil.create404RESTException("Data Not Found for given Id", MessageEnums.DATA_NOT_FOUND, id, - null, "readResource : No Object found with given id."); - } - VXGroup vXGroup = xGroupService.populateViewBean(xXGroup); - if (vXGroup == null || StringUtils.isEmpty(vXGroup.getName())) { - throw restErrorUtil.createRESTException("Group ID doesn't exist.", MessageEnums.INVALID_INPUT_DATA); - } - if(logger.isDebugEnabled()){ - logger.info("Force delete status="+force+" for group="+vXGroup.getName()); - } - - SearchCriteria searchCriteria = new SearchCriteria(); - searchCriteria.addParam("xGroupId", id); - VXGroupUserList vxGroupUserList = searchXGroupUsers(searchCriteria); - - searchCriteria = new SearchCriteria(); - searchCriteria.addParam("groupId", id); - VXPermMapList vXPermMapList = searchXPermMaps(searchCriteria); - - searchCriteria = new SearchCriteria(); - searchCriteria.addParam("groupId", id); - VXAuditMapList vXAuditMapList = searchXAuditMaps(searchCriteria); - - XXGroupPermissionDao xXGroupPermissionDao=daoManager.getXXGroupPermission(); - List xXGroupPermissions=xXGroupPermissionDao.findByGroupId(id); - - XXPolicyDao xXPolicyDao = daoManager.getXXPolicy(); - List xXPolicyList = xXPolicyDao.findByGroupId(id); - logger.warn("Deleting GROUP : "+vXGroup.getName()); - if (force) { - //delete XXGroupUser records of matching group - XXGroupUserDao xGroupUserDao = daoManager.getXXGroupUser(); - XXUserDao xXUserDao = daoManager.getXXUser(); - XXUser xXUser =null; - for (VXGroupUser groupUser : vxGroupUserList.getList()) { - if(groupUser!=null){ - xXUser=xXUserDao.getById(groupUser.getUserId()); - if(xXUser!=null){ - logger.warn("Removing user '" + xXUser.getName() + "' from group '" + groupUser.getName() + "'"); - } - xGroupUserDao.remove(groupUser.getId()); - } - } - //delete XXPermMap records of matching group - XXPermMapDao xXPermMapDao = daoManager.getXXPermMap(); - XXResourceDao xXResourceDao = daoManager.getXXResource(); - XXResource xXResource =null; - for (VXPermMap vXPermMap : vXPermMapList.getList()) { - if(vXPermMap!=null){ - xXResource=xXResourceDao.getById(vXPermMap.getResourceId()); - if(xXResource!=null){ - logger.warn("Deleting '" + AppConstants.getLabelFor_XAPermType(vXPermMap.getPermType()) + "' permission from policy ID='" + vXPermMap.getResourceId() + "' for group '" + vXPermMap.getGroupName() + "'"); - } - xXPermMapDao.remove(vXPermMap.getId()); - } - } - //delete XXAuditMap records of matching group - XXAuditMapDao xXAuditMapDao = daoManager.getXXAuditMap(); - for (VXAuditMap vXAuditMap : vXAuditMapList.getList()) { - if(vXAuditMap!=null){ - xXResource=xXResourceDao.getById(vXAuditMap.getResourceId()); - xXAuditMapDao.remove(vXAuditMap.getId()); - } - } - //delete XXPolicyItemGroupPerm records of group - for (XXPolicy xXPolicy : xXPolicyList) { - RangerPolicy rangerPolicy = policyService.getPopulatedViewObject(xXPolicy); - List policyItems = rangerPolicy.getPolicyItems(); - removeUserGroupReferences(policyItems,null,vXGroup.getName()); - rangerPolicy.setPolicyItems(policyItems); - - List denyPolicyItems = rangerPolicy.getDenyPolicyItems(); - removeUserGroupReferences(denyPolicyItems,null,vXGroup.getName()); - rangerPolicy.setDenyPolicyItems(denyPolicyItems); - - List allowExceptions = rangerPolicy.getAllowExceptions(); - removeUserGroupReferences(allowExceptions,null,vXGroup.getName()); - rangerPolicy.setAllowExceptions(allowExceptions); - - List denyExceptions = rangerPolicy.getDenyExceptions(); - removeUserGroupReferences(denyExceptions,null,vXGroup.getName()); - rangerPolicy.setDenyExceptions(denyExceptions); - - List dataMaskItems = rangerPolicy.getDataMaskPolicyItems(); - removeUserGroupReferences(dataMaskItems,null,vXGroup.getName()); - rangerPolicy.setDataMaskPolicyItems(dataMaskItems); - - List rowFilterItems = rangerPolicy.getRowFilterPolicyItems(); - removeUserGroupReferences(rowFilterItems,null,vXGroup.getName()); - rangerPolicy.setRowFilterPolicyItems(rowFilterItems); - - try { - if (StringUtils.equals(rangerPolicy.getServiceType(), EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_GDS_NAME)) { - Map resources = rangerPolicy.getResources(); - - if (MapUtils.isEmpty(resources)) { - continue; - } - - if (resources.containsKey(GdsDBStore.RESOURCE_NAME_DATASET_ID)) { - RangerPolicyResource policyRes = resources.get(GdsDBStore.RESOURCE_NAME_DATASET_ID); - List resValues = policyRes != null ? policyRes.getValues() : null; - - if (CollectionUtils.isNotEmpty(resValues)) { - gdsStore.updateDatasetPolicy(Long.valueOf(resValues.get(0)), rangerPolicy); - } - } else if (resources.containsKey(GdsDBStore.RESOURCE_NAME_PROJECT_ID)) { - RangerPolicyResource policyRes = resources.get(GdsDBStore.RESOURCE_NAME_PROJECT_ID); - List resValues = policyRes != null ? policyRes.getValues() : null; - - if (CollectionUtils.isNotEmpty(resValues)) { - gdsStore.updateProjectPolicy(Long.valueOf(resValues.get(0)), rangerPolicy); - } - } - } else { - svcStore.updatePolicy(rangerPolicy); - } - } catch (Throwable excp) { - logger.error("updatePolicy(" + rangerPolicy + ") failed", excp); - restErrorUtil.createRESTException(excp.getMessage()); - } - } - - if(CollectionUtils.isNotEmpty(xXGroupPermissions)){ - for (XXGroupPermission xXGroupPermission : xXGroupPermissions) { - if(xXGroupPermission!=null){ - XXModuleDef xXModuleDef=daoManager.getXXModuleDef().findByModuleId(xXGroupPermission.getModuleId()); - if(xXModuleDef!=null){ - logger.warn("Deleting '" + xXModuleDef.getModule() + "' module permission for group '" + xXGroup.getName() + "'"); - } - xXGroupPermissionDao.remove(xXGroupPermission.getId()); - } - } - } - //delete group from audit filter configs - svcStore.updateServiceAuditConfig(vXGroup.getName(), REMOVE_REF_TYPE.GROUP); - // delete group from dataset,datashare,project - gdsStore.deletePrincipalFromGdsAcl(REMOVE_REF_TYPE.GROUP.toString(), vXGroup.getName()); - //delete XXGroup - xXGroupDao.remove(id); - //Create XXTrxLog - xGroupService.createTransactionLog(xGroupService.populateViewBean(xXGroup), null, OPERATION_DELETE_CONTEXT); - } else { - boolean hasReferences=false; - - if(vxGroupUserList.getListSize()>0){ - hasReferences=true; - } - if(hasReferences==false && CollectionUtils.isNotEmpty(xXPolicyList)){ - hasReferences=true; - } - if(hasReferences==false && vXPermMapList.getListSize()>0){ - hasReferences=true; - } - if(hasReferences==false && vXAuditMapList.getListSize()>0){ - hasReferences=true; - } - if(hasReferences==false && CollectionUtils.isNotEmpty(xXGroupPermissions)){ - hasReferences=true; - } - - if(hasReferences){ //change visibility to Hidden - if(vXGroup.getIsVisible()==RangerCommonEnums.IS_VISIBLE){ - vXGroup.setIsVisible(RangerCommonEnums.IS_HIDDEN); - xGroupService.updateResource(vXGroup); - } - }else{ - //delete XXGroup - xXGroupDao.remove(id); - //Create XXTrxLog - xGroupService.createTransactionLog(xGroupService.populateViewBean(xXGroup), null, OPERATION_DELETE_CONTEXT); - } - } - } - - public long forceDeleteExternalGroups(List groupIds){ - long groupsDeleted = 0; - long failedDeletes = 0; - long startTime = Time.now(); - for(Long groupId: groupIds){ - TransactionTemplate txTemplate = new TransactionTemplate(txManager); - txTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); - try { - txTemplate.execute(new TransactionCallback() { - @Override - public Object doInTransaction(TransactionStatus status) { - deleteXGroup(groupId, true); - return null; - } - }); - groupsDeleted += 1; - } catch (Throwable ex) { - logger.error("forceDeleteExternalGroups(): Failed to delete group id: {}", groupId, ex); - failedDeletes += 1; - } - } - if (failedDeletes == 1) { - logger.error("Failed to delete 1 group"); - } else if (failedDeletes > 1) { - logger.error("Failed to delete {} groups", failedDeletes); - } - if (groupIds.size() == 1) { - logger.info("Force Deletion of 1 group took {} milliseconds", (Time.now() - startTime)); - } else if (groupIds.size() > 1) { - logger.info("Force Deletion of {} groups took {} milliseconds", groupIds.size(), (Time.now() - startTime)); - } - return groupsDeleted; - } - - private void blockIfZoneGroup(Long grpId) { - List zoneRefGrpList = daoManager.getXXSecurityZoneRefGroup().findByGroupId(grpId); - if (CollectionUtils.isNotEmpty(zoneRefGrpList)) { - StringBuilder zones = new StringBuilder(); - for(XXSecurityZoneRefGroup zoneRefGrp : zoneRefGrpList) { - XXSecurityZone xSecZone=daoManager.getXXSecurityZoneDao().getById(zoneRefGrp.getZoneId()); - if(zones.indexOf(xSecZone.getName())<0) - zones.append(xSecZone.getName() + ","); - } - this.prepareAndThrow(zoneRefGrpList.get(0).getGroupName(), RangerConstants.MODULE_SECURITY_ZONE, zones, GROUP); - } - } - - public synchronized void deleteXUser(Long id, boolean force) { - checkAdminAccess(); - xaBizUtil.blockAuditorRoleUser(); - XXUserDao xXUserDao = daoManager.getXXUser(); - XXUser xXUser = xXUserDao.getById(id); - if (xXUser == null) { - throw restErrorUtil.create404RESTException("Data Not Found for given Id", MessageEnums.DATA_NOT_FOUND, id, - null, "readResource : No Object found with given id."); - } - VXUser vXUser = xUserService.populateViewBean(xXUser); - if(vXUser==null || StringUtils.isEmpty(vXUser.getName())){ - throw restErrorUtil.createRESTException("No user found with id=" + id); - } - XXPortalUserDao xXPortalUserDao=daoManager.getXXPortalUser(); - XXPortalUser xXPortalUser=xXPortalUserDao.findByLoginId(vXUser.getName().trim()); - VXPortalUser vXPortalUser=null; - if(xXPortalUser!=null){ - vXPortalUser=xPortalUserService.populateViewBean(xXPortalUser); - } - if(vXPortalUser==null || StringUtils.isEmpty(vXPortalUser.getLoginId())){ - throw restErrorUtil.createRESTException("No user found with id=" + id); - } - if (logger.isDebugEnabled()) { - logger.debug("Force delete status="+force+" for user="+vXUser.getName()); - } - restrictSelfAccountDeletion(vXUser.getName().trim()); - blockIfZoneUser(id); - this.blockIfRoleUser(id); - SearchCriteria searchCriteria = new SearchCriteria(); - searchCriteria.addParam("xUserId", id); - VXGroupUserList vxGroupUserList = searchXGroupUsers(searchCriteria); - - searchCriteria = new SearchCriteria(); - searchCriteria.addParam("userId", id); - VXPermMapList vXPermMapList = searchXPermMaps(searchCriteria); - - searchCriteria = new SearchCriteria(); - searchCriteria.addParam("userId", id); - VXAuditMapList vXAuditMapList = searchXAuditMaps(searchCriteria); - - long xXPortalUserId=0; - xXPortalUserId=vXPortalUser.getId(); - XXAuthSessionDao xXAuthSessionDao=daoManager.getXXAuthSession(); - XXUserPermissionDao xXUserPermissionDao=daoManager.getXXUserPermission(); - XXPortalUserRoleDao xXPortalUserRoleDao=daoManager.getXXPortalUserRole(); - List xXAuthSessionIds = xXAuthSessionDao.getAuthSessionIdsByUserId(xXPortalUserId); - List xXUserPermissions=xXUserPermissionDao.findByUserPermissionId(xXPortalUserId); - List xXPortalUserRoles=xXPortalUserRoleDao.findByUserId(xXPortalUserId); - - XXPolicyDao xXPolicyDao = daoManager.getXXPolicy(); - logger.warn("Deleting User : "+vXUser.getName()); - if (force) { - //delete XXGroupUser mapping - XXGroupUserDao xGroupUserDao = daoManager.getXXGroupUser(); - for (VXGroupUser groupUser : vxGroupUserList.getList()) { - if(groupUser!=null){ - logger.warn("Removing user '" + vXUser.getName() + "' from group '" + groupUser.getName() + "'"); - xGroupUserDao.remove(groupUser.getId()); - } - } - //delete XXPermMap records of user - XXPermMapDao xXPermMapDao = daoManager.getXXPermMap(); - for (VXPermMap vXPermMap : vXPermMapList.getList()) { - if(vXPermMap!=null){ - logger.warn("Deleting '" + AppConstants.getLabelFor_XAPermType(vXPermMap.getPermType()) + "' permission from policy ID='" + vXPermMap.getResourceId() + "' for user '" + vXPermMap.getUserName() + "'"); - xXPermMapDao.remove(vXPermMap.getId()); - } - } - //delete XXAuditMap records of user - XXAuditMapDao xXAuditMapDao = daoManager.getXXAuditMap(); - for (VXAuditMap vXAuditMap : vXAuditMapList.getList()) { - if(vXAuditMap!=null){ - xXAuditMapDao.remove(vXAuditMap.getId()); - } - } - //delete XXPortalUser references - if(vXPortalUser!=null){ - xPortalUserService.updateXXPortalUserReferences(xXPortalUserId); - if(CollectionUtils.isNotEmpty(xXAuthSessionIds)){ - logger.warn("Deleting " + xXAuthSessionIds.size() + " login session records for user '" + vXPortalUser.getLoginId() + "'"); - xXAuthSessionDao.deleteAuthSessionsByIds(xXAuthSessionIds); - } - - for (XXUserPermission xXUserPermission : xXUserPermissions) { - if(xXUserPermission!=null){ - XXModuleDef xXModuleDef=daoManager.getXXModuleDef().findByModuleId(xXUserPermission.getModuleId()); - if(xXModuleDef!=null){ - logger.warn("Deleting '" + xXModuleDef.getModule() + "' module permission for user '" + vXPortalUser.getLoginId() + "'"); - } - xXUserPermissionDao.remove(xXUserPermission.getId()); - } - } - for (XXPortalUserRole xXPortalUserRole : xXPortalUserRoles) { - if(xXPortalUserRole!=null){ - logger.warn("Deleting '" + xXPortalUserRole.getUserRole() + "' role for user '" + vXPortalUser.getLoginId() + "'"); - xXPortalUserRoleDao.remove(xXPortalUserRole.getId()); - } - } - } - //delete XXPolicyItemUserPerm records of user - List xXPolicyList=xXPolicyDao.findByUserId(id); - for(XXPolicy xXPolicy:xXPolicyList){ - RangerPolicy rangerPolicy = policyService.getPopulatedViewObject(xXPolicy); - List policyItems = rangerPolicy.getPolicyItems(); - removeUserGroupReferences(policyItems,vXUser.getName(),null); - rangerPolicy.setPolicyItems(policyItems); - - List denyPolicyItems = rangerPolicy.getDenyPolicyItems(); - removeUserGroupReferences(denyPolicyItems,vXUser.getName(),null); - rangerPolicy.setDenyPolicyItems(denyPolicyItems); - - List allowExceptions = rangerPolicy.getAllowExceptions(); - removeUserGroupReferences(allowExceptions,vXUser.getName(),null); - rangerPolicy.setAllowExceptions(allowExceptions); - - List denyExceptions = rangerPolicy.getDenyExceptions(); - removeUserGroupReferences(denyExceptions,vXUser.getName(),null); - rangerPolicy.setDenyExceptions(denyExceptions); - - List dataMaskItems = rangerPolicy.getDataMaskPolicyItems(); - removeUserGroupReferences(dataMaskItems,vXUser.getName(),null); - rangerPolicy.setDataMaskPolicyItems(dataMaskItems); - - List rowFilterItems = rangerPolicy.getRowFilterPolicyItems(); - removeUserGroupReferences(rowFilterItems,vXUser.getName(),null); - rangerPolicy.setRowFilterPolicyItems(rowFilterItems); - - try{ - if (StringUtils.equals(rangerPolicy.getServiceType(), EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_GDS_NAME)) { - Map resources = rangerPolicy.getResources(); - - if (MapUtils.isEmpty(resources)) { - continue; - } - - if (resources.containsKey(GdsDBStore.RESOURCE_NAME_DATASET_ID)) { - RangerPolicyResource policyRes = resources.get(GdsDBStore.RESOURCE_NAME_DATASET_ID); - List resValues = policyRes != null ? policyRes.getValues() : null; - - if (CollectionUtils.isNotEmpty(resValues)) { - gdsStore.updateDatasetPolicy(Long.valueOf(resValues.get(0)), rangerPolicy); - } - } else if (resources.containsKey(GdsDBStore.RESOURCE_NAME_PROJECT_ID)) { - RangerPolicyResource policyRes = resources.get(GdsDBStore.RESOURCE_NAME_PROJECT_ID); - List resValues = policyRes != null ? policyRes.getValues() : null; - - if (CollectionUtils.isNotEmpty(resValues)) { - gdsStore.updateProjectPolicy(Long.valueOf(resValues.get(0)), rangerPolicy); - } - } - } else { - svcStore.updatePolicy(rangerPolicy); - } - } catch(Throwable excp) { - logger.error("updatePolicy(" + rangerPolicy + ") failed", excp); - throw restErrorUtil.createRESTException(excp.getMessage()); - } - } - - //delete user from audit filter configs - svcStore.updateServiceAuditConfig(vXUser.getName(), REMOVE_REF_TYPE.USER); - //delete gdsObject mapping of user - gdsStore.deletePrincipalFromGdsAcl(REMOVE_REF_TYPE.USER.toString(),vXUser.getName()); - //delete XXUser entry of user - xXUserDao.remove(id); - //delete XXPortal entry of user - logger.warn("Deleting Portal User : "+vXPortalUser.getLoginId()); - xXPortalUserDao.remove(xXPortalUserId); - xUserService.createTransactionLog(xUserService.populateViewBean(xXUser), null, OPERATION_DELETE_CONTEXT); - if (xXPortalUser != null) { - xPortalUserService.createTransactionLog(xPortalUserService.populateViewBean(xXPortalUser), null, OPERATION_DELETE_CONTEXT); - } - } else { - boolean hasReferences=false; - List xXPolicyList=xXPolicyDao.findByUserId(id); - if(vxGroupUserList!=null && vxGroupUserList.getListSize()>0){ - hasReferences=true; - } - if(hasReferences==false && xXPolicyList!=null && xXPolicyList.size()>0){ - hasReferences=true; - } - if(hasReferences==false && vXPermMapList!=null && vXPermMapList.getListSize()>0){ - hasReferences=true; - } - if(hasReferences==false && vXAuditMapList!=null && vXAuditMapList.getListSize()>0){ - hasReferences=true; - } - if(hasReferences==false && CollectionUtils.isNotEmpty(xXAuthSessionIds)){ - hasReferences=true; - } - if(hasReferences==false && xXUserPermissions!=null && xXUserPermissions.size()>0){ - hasReferences=true; - } - if(hasReferences==false && xXPortalUserRoles!=null && xXPortalUserRoles.size()>0){ - hasReferences=true; - } - if(hasReferences){ - if(vXUser.getIsVisible()!=RangerCommonEnums.IS_HIDDEN){ - logger.info("Updating visibility of user '"+vXUser.getName()+"' to Hidden!"); - vXUser.setIsVisible(RangerCommonEnums.IS_HIDDEN); - xUserService.updateResource(vXUser); - } - }else{ - xPortalUserService.updateXXPortalUserReferences(xXPortalUserId); - //delete XXUser entry of user - xXUserDao.remove(id); - //delete XXPortal entry of user - logger.warn("Deleting Portal User : "+vXPortalUser.getLoginId()); - xXPortalUserDao.remove(xXPortalUserId); - xUserService.createTransactionLog(xUserService.populateViewBean(xXUser), null, OPERATION_DELETE_CONTEXT); - xPortalUserService.createTransactionLog(xPortalUserService.populateViewBean(xXPortalUser), null, OPERATION_DELETE_CONTEXT); - } - } - } - - public long forceDeleteExternalUsers(List userIds){ - long usersDeleted = 0; - long failedDeletes = 0; - long startTime = Time.now(); - for(Long userId: userIds){ - TransactionTemplate txTemplate = new TransactionTemplate(txManager); - txTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); - try { - txTemplate.execute(new TransactionCallback() { - @Override - public Object doInTransaction(TransactionStatus status) { - deleteXUser(userId, true); - return null; - } - }); - usersDeleted += 1; - } catch (Throwable ex) { - logger.error("forceDeleteExternalUsers(): Failed to delete user id: {}", userId, ex); - failedDeletes += 1; - } - } - if (failedDeletes == 1){ - logger.error("Failed to delete 1 user"); - } else if (failedDeletes > 1) { - logger.error("Failed to delete {} users", failedDeletes); - } - if (userIds.size() == 1) { - logger.info("Force Deletion of 1 user took {} milliseconds", (Time.now() - startTime)); - } else if (userIds.size() > 1) { - logger.info("Force Deletion of {} users took {} milliseconds", userIds.size(), (Time.now() - startTime)); - } - return usersDeleted; - } - - private void blockIfZoneUser(Long id) { - List zoneRefUserList = daoManager.getXXSecurityZoneRefUser().findByUserId(id); - if (CollectionUtils.isNotEmpty(zoneRefUserList)) { - StringBuilder zones = new StringBuilder(); - for(XXSecurityZoneRefUser zoneRefUser :zoneRefUserList ) { - XXSecurityZone xSecZone = daoManager.getXXSecurityZoneDao().getById(zoneRefUser.getZoneId()); - if(zones.indexOf(xSecZone.getName())<0) - zones.append(xSecZone.getName() + ","); - } - this.prepareAndThrow(zoneRefUserList.get(0).getUserName(), RangerConstants.MODULE_SECURITY_ZONE, zones, USER); - } - } - - private void blockIfRoleUser(Long id) { - List roleRefUsers = this.daoManager.getXXRoleRefUser().findByUserId(id); - if (CollectionUtils.isNotEmpty(roleRefUsers)) { - StringBuilder roles = new StringBuilder(); - for (XXRoleRefUser roleRefUser : roleRefUsers) { - XXRole xxRole = this.daoManager.getXXRole().getById(roleRefUser.getRoleId()); - final String roleName = xxRole.getName(); - if (roles.indexOf(roleName) < 0) - roles.append(roleName + ","); - } - final String roleRefUserName = roleRefUsers.get(0).getUserName(); - this.prepareAndThrow(roleRefUserName, RangerConstants.ROLE_FIELD, roles, USER); - } - } - - private void blockIfRoleGroup(Long id) { - List roleRefGroups = this.daoManager.getXXRoleRefGroup().findByGroupId(id); - if (CollectionUtils.isNotEmpty(roleRefGroups)) { - StringBuilder roles = new StringBuilder(); - for (XXRoleRefGroup roleRefGroup : roleRefGroups) { - XXRole xxRole = this.daoManager.getXXRole().getById(roleRefGroup.getRoleId()); - final String roleName = xxRole.getName(); - if (roles.indexOf(roleName) < 0) - roles.append(roleName + ","); - } - final String roleRefGroupName = roleRefGroups.get(0).getGroupName(); - this.prepareAndThrow(roleRefGroupName, RangerConstants.ROLE_FIELD, roles, GROUP); - } - } - - private void prepareAndThrow(String userGrpName, String moduleName, StringBuilder rolesOrZones, String userOrGrp) { - logger.error("Can Not Delete " + userOrGrp + ":" + userGrpName); - VXResponse vXResponse = new VXResponse(); - vXResponse.setStatusCode(HttpServletResponse.SC_BAD_REQUEST); - vXResponse.setMsgDesc("Can Not Delete " + userOrGrp + ": '" + userGrpName + "' as its present in " + moduleName - + " : " + rolesOrZones.deleteCharAt(rolesOrZones.length() - 1)); - throw restErrorUtil.generateRESTException(vXResponse); - } - - private void removeUserGroupReferences(List policyItems, String user, String group) { - List itemsToRemove = null; - for(T policyItem : policyItems) { - if(StringUtils.isNotEmpty(user)) { - policyItem.removeUser(user); - } - if(StringUtils.isNotEmpty(group)) { - policyItem.removeGroup(group); - } - if(policyItem.getUsers().isEmpty() && policyItem.getGroups().isEmpty() && policyItem.getRoles().isEmpty()) { - if(itemsToRemove == null) { - itemsToRemove = new ArrayList(); - } - itemsToRemove.add(policyItem); - } - } - if(CollectionUtils.isNotEmpty(itemsToRemove)) { - policyItems.removeAll(itemsToRemove); - } - } - - public void restrictSelfAccountDeletion(String loginID) { - UserSessionBase session = ContextUtil.getCurrentUserSession(); - if (session != null) { - if (!session.isUserAdmin()) { - VXResponse vXRes = new VXResponse(); - vXRes.setStatusCode(HttpServletResponse.SC_FORBIDDEN ); - vXRes.setMsgDesc("Operation denied. LoggedInUser= "+session.getXXPortalUser().getLoginId() + " isn't permitted to perform the action."); - throw restErrorUtil.generateRESTException(vXRes); - }else{ - if(StringUtils.isNotEmpty(loginID) && loginID.equals(session.getLoginId())){ - VXResponse vXResponse = new VXResponse(); - vXResponse.setStatusCode(HttpServletResponse.SC_FORBIDDEN ); - vXResponse.setMsgDesc("Operation denied. LoggedInUser= "+session.getXXPortalUser().getLoginId() + " isn't permitted to delete his own profile."); - throw restErrorUtil.generateRESTException(vXResponse); - } - } - } else { - VXResponse vXResponse = new VXResponse(); - vXResponse.setStatusCode(HttpServletResponse.SC_UNAUTHORIZED); // user is null - vXResponse.setMsgDesc("Bad Credentials"); - throw restErrorUtil.generateRESTException(vXResponse); - } - } - - public VXUser createServiceConfigUser(String userName){ - if (userName == null || "null".equalsIgnoreCase(userName) || userName.trim().isEmpty()) { - logger.error("User Name: "+userName); - throw restErrorUtil.createRESTException("Please provide a valid username.",MessageEnums.INVALID_INPUT_DATA); - } - - XXUser xxUser = daoManager.getXXUser().findByUserName(userName); - if (xxUser == null) { - transactionSynchronizationAdapter.executeOnTransactionCommit(new ExternalUserCreator(userName)); - } - - xxUser = daoManager.getXXUser().findByUserName(userName); - VXUser vXUser = null; - if (xxUser != null) { - vXUser = xUserService.populateViewBean(xxUser); - } - return vXUser; - } - - public VXUser createServiceConfigUserSynchronously(String userName){ - if (userName == null || "null".equalsIgnoreCase(userName) || userName.trim().isEmpty()) { - logger.error("User Name: "+userName); - throw restErrorUtil.createRESTException("Please provide a valid username.",MessageEnums.INVALID_INPUT_DATA); - } - - VXUser vXUser = null; - - XXUser xxUser = daoManager.getXXUser().findByUserName(userName); - if (xxUser == null) { - ExternalUserCreator externalUserCreator = new ExternalUserCreator(userName); - externalUserCreator.run(); - xxUser = daoManager.getXXUser().findByUserName(userName); - } - - if (xxUser != null) { - vXUser = xUserService.populateViewBean(xxUser); - } - return vXUser; - } - - protected void validatePassword(VXUser vXUser) { - if (vXUser.getPassword() != null && !vXUser.getPassword().isEmpty()) { - boolean checkPassword = false; - checkPassword = vXUser.getPassword().trim().matches(StringUtil.VALIDATION_CRED); - if (!checkPassword) { - logger.warn("validatePassword(). Password should be minimum 8 characters, at least one uppercase letter, one lowercase letter and one numeric."); - throw restErrorUtil.createRESTException("serverMsg.xuserMgrValidatePassword", MessageEnums.INVALID_PASSWORD, null, "Password should be minimum 8 characters, at least one uppercase letter, one lowercase letter and one numeric.", null); - } - } else { - logger.warn("validatePassword(). Password cannot be blank/null."); - throw restErrorUtil.createRESTException("serverMsg.xuserMgrValidatePassword", MessageEnums.INVALID_PASSWORD, null, "Password cannot be blank/null", null); - } - } - - public void denySelfRoleChange(String userName) { - UserSessionBase session = ContextUtil.getCurrentUserSession(); - if (session != null && session.getXXPortalUser()!=null) { - if (userName.equals(session.getXXPortalUser().getLoginId())) { - throw restErrorUtil.create403RESTException("Permission" - + " denied. LoggedInUser=" - + (session != null ? session.getXXPortalUser().getId() - : "Not Logged In") - + " ,isn't permitted to change its own role."); - } - } - } - - @Transactional(readOnly = false, propagation = Propagation.REQUIRED) - public synchronized VXUgsyncAuditInfo postUserGroupAuditInfo( - VXUgsyncAuditInfo vxUgsyncAuditInfo) { - checkAdminAccess(); - //logger.info("post usersync audit info"); - vxUgsyncAuditInfo = xUgsyncAuditInfoService.createUgsyncAuditInfo(vxUgsyncAuditInfo); - return vxUgsyncAuditInfo; - } - - public Long getUserStoreVersion() { - return daoManager.getXXGlobalState().getAppDataVersion(RANGER_GLOBAL_STATE_NAME_USER_GROUP); - } - - public Set getUsers() { - return new HashSet<>(xUserService.getUsers()); - } - - public Set getGroups() { - return new HashSet<>(xGroupService.getGroups()); - } - - public Map> getUserGroups() { - return daoManager.getXXUser().findGroupsByUserIds(); - } - - public RangerUserStore getRangerUserStoreIfUpdated(Long lastKnownUserStoreVersion) throws Exception { - if (logger.isDebugEnabled()) { - logger.debug("==> XUserMgr.getRangerUserStoreIfUpdated(lastKnownUserStoreVersion=" + lastKnownUserStoreVersion + ")"); - } - - RangerUserStore ret = RangerUserStoreCache.getInstance().getLatestRangerUserStoreOrCached(this); - - if (ret != null && Objects.equals(ret.getUserStoreVersion(), lastKnownUserStoreVersion)) { - ret = null; - } - - if (logger.isDebugEnabled()) { - logger.debug("<== XUserMgr.getRangerUserStoreIfUpdated(lastKnownUserStoreVersion=" + lastKnownUserStoreVersion + "): ret=" + ret); - } - - return ret; - } - - public int createOrUpdateXUsers(VXUserList users) { - if (logger.isDebugEnabled()) { - logger.debug("==> createOrUpdateXUsers(): Started"); - } - xaBizUtil.blockAuditorRoleUser(); - int ret = 0; - - for (VXUser vXUser : users.getList()) { - final String userName = vXUser == null ? null : vXUser.getName(); - final String firstName = vXUser == null ? null : vXUser.getFirstName(); - - if (userName == null || "null".equalsIgnoreCase(userName) || userName.trim().isEmpty()) { - logger.warn("Ignoring user {}: invalid username", userName); - continue; - } - - if (firstName == null || "null".equalsIgnoreCase(firstName) || firstName.trim().isEmpty()) { - logger.warn("Ignoring user {}: invalid firstName {}", userName, firstName); - continue; - } - - checkAccess(vXUser); - TransactionTemplate txTemplate = new TransactionTemplate(txManager); - txTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); - try { - txTemplate.execute(new TransactionCallback() { - @Override - public Object doInTransaction(TransactionStatus status) { - VXPortalUser vXPortalUser = userMgr.getUserProfileByLoginId(userName); - if (vXPortalUser == null) { - if (logger.isDebugEnabled()) { - logger.debug("create user " + userName); - } - createXUser(vXUser, userName); - } else { - if (logger.isDebugEnabled()) { - logger.debug("Update user " + userName); - } - updateXUser(vXUser, vXPortalUser); - } - return null; - } - }); - } catch (Throwable ex) { - logger.error("XUserMgr.createOrUpdateXUsers(): Failed to update DB for users: ", ex); - throw restErrorUtil.createRESTException("Failed to create or update users ", - MessageEnums.ERROR_CREATING_OBJECT); - } - ret++; - } - - if (ret == 0) { - if (logger.isDebugEnabled()) { - logger.debug("<== createOrUpdateXUsers(): No users created or updated"); - } - - return ret; - } - - TransactionTemplate txTemplate = new TransactionTemplate(txManager); - txTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); - try { - txTemplate.execute(new TransactionCallback() { - @Override - public Void doInTransaction(TransactionStatus status) { - int noOfRetries = 0; - Exception failureException = null; - do { - noOfRetries++; - try { - daoManager.getXXGlobalState().onGlobalAppDataChange(RANGER_GLOBAL_STATE_NAME_USER_GROUP); - if (logger.isDebugEnabled()) { - logger.debug("createOrUpdateXGroups(): Successfully updated x_ranger_global_state table"); - } - return null; - } catch (Exception excp) { - logger.warn("createOrUpdateXGroups(): Failed to update x_ranger_global_state table and retry count = " + noOfRetries); - failureException = excp; - } - } while (noOfRetries <= MAX_DB_TRANSACTION_RETRIES); - logger.error("createOrUpdateXGroups(): Failed to update x_ranger_global_state table after max retries", failureException); - throw new RuntimeException(failureException); - } - }); - } catch (Throwable ex) { - logger.error("XUserMgr.createOrUpdateXUsers(): Failed to update DB for GlobalState table ", ex); - throw restErrorUtil.createRESTException("Failed to create or update users ", - MessageEnums.ERROR_CREATING_OBJECT); - } - if (logger.isDebugEnabled()) { - logger.debug("<== createOrUpdateXUsers(): Done"); - } - - return ret; - } - - private void createXUser(VXUser vXUser, String username) { - if (logger.isDebugEnabled()) { - logger.debug("Creating user: " + username); - } - VXPortalUser vXPortalUser = new VXPortalUser(); - vXPortalUser.setLoginId(username); - vXPortalUser.setFirstName(vXUser.getFirstName()); - if ("null".equalsIgnoreCase(vXPortalUser.getFirstName())) { - vXPortalUser.setFirstName(""); - } - vXPortalUser.setLastName(vXUser.getLastName()); - if ("null".equalsIgnoreCase(vXPortalUser.getLastName())) { - vXPortalUser.setLastName(""); - } - - String emailAddress = vXUser.getEmailAddress(); - if (StringUtils.isNotEmpty(emailAddress) && !stringUtil.validateEmail(emailAddress)) { - logger.warn("Invalid email address:" + emailAddress); - throw restErrorUtil.createRESTException("Please provide valid email address.", - MessageEnums.INVALID_INPUT_DATA); - } - vXPortalUser.setEmailAddress(emailAddress); - - if (vXPortalUser.getFirstName() != null - && vXPortalUser.getLastName() != null - && !vXPortalUser.getFirstName().trim().isEmpty() - && !vXPortalUser.getLastName().trim().isEmpty()) { - vXPortalUser.setPublicScreenName(vXPortalUser.getFirstName() + " " - + vXPortalUser.getLastName()); - } else { - vXPortalUser.setPublicScreenName(vXUser.getName()); - } - - vXPortalUser.setStatus(RangerCommonEnums.STATUS_ENABLED); - vXPortalUser.setUserSource(RangerCommonEnums.USER_EXTERNAL); - String saltEncodedpasswd = userMgr.encrypt(username, - vXUser.getPassword()); - vXPortalUser.setPassword(saltEncodedpasswd); - vXPortalUser.setUserRoleList(vXUser.getUserRoleList()); - XXPortalUser user = userMgr.mapVXPortalUserToXXPortalUser(vXPortalUser); - - user = daoManager.getXXPortalUser().create(user); - - // Create the UserRole for this user - Collection userRoleList = vXUser.getUserRoleList(); - if (userRoleList != null) { - for (String userRole : userRoleList) { - userMgr.addUserRole(user.getId(), - userRole); - } - } - - XXUser xUser = daoManager.getXXUser().findByUserName(vXUser.getName()); - if (xUser == null) { - vXUser = xUserService.createResource(vXUser); - } else { - vXUser = xUserService.populateViewBean(xUser); - } - - xUserService.createTransactionLog(vXUser, null, OPERATION_CREATE_CONTEXT); - - if (vXPortalUser != null) { - assignPermissionToUser(vXPortalUser.getUserRoleList(), vXPortalUser.getId(), vXUser.getId(), true); - } - if (logger.isDebugEnabled()) { - logger.debug("Done creating user: " + username); - } - } - - @Transactional(readOnly = false, propagation = Propagation.REQUIRED) - public int createOrUpdateXGroups(VXGroupList groups) { - for (VXGroup vXGroup : groups.getList()) { - if (vXGroup == null || vXGroup.getName() == null - || "null".equalsIgnoreCase(vXGroup.getName()) - || vXGroup.getName().trim().isEmpty()) { - logger.warn("Ignoring invalid groupname " + vXGroup==null? null : vXGroup.getName()); - continue; + static final Set roleAssignmentUpdatedUsers = new HashSet<>(); + static final String MSG_DATA_ACCESS_DENY = "Logged-In user is not allowed to access requested user data"; + + private static final String USER = "User"; + private static final String GROUP = "Group"; + private static final int MAX_DB_TRANSACTION_RETRIES = 5; + private static final int PASSWORD_LENGTH = 16; + + @Autowired + RangerBizUtil msBizUtil; + + @Autowired + UserMgr userMgr; + + @Autowired + RangerDaoManager daoManager; + + @Autowired + RangerBizUtil xaBizUtil; + + @Autowired + XPortalUserService xPortalUserService; + + @Autowired + XResourceService xResourceService; + + @Autowired + SessionMgr sessionMgr; + + @Autowired + RangerPolicyService policyService; + + @Autowired + ServiceDBStore svcStore; + + @Autowired + GUIDUtil guidUtil; + + @Autowired + XUgsyncAuditInfoService xUgsyncAuditInfoService; + + @Autowired + StringUtil stringUtil; + + @Autowired + RangerTransactionSynchronizationAdapter transactionSynchronizationAdapter; + + @Autowired + GdsDBStore gdsStore; + + @Autowired + @Qualifier(value = "transactionManager") + + PlatformTransactionManager txManager; + + public VXUser getXUserByUserName(String userName) { + VXUser vXUser = xUserService.getXUserByUserName(userName); + + if (vXUser != null && !hasAccessToGetUserInfo(vXUser)) { + logger.info(MSG_DATA_ACCESS_DENY); + + throw restErrorUtil.createRESTException(HttpServletResponse.SC_FORBIDDEN, MSG_DATA_ACCESS_DENY, true); + } + + if (vXUser != null && !hasAccessToModule(RangerConstants.MODULE_USER_GROUPS)) { + vXUser = getMaskedVXUser(vXUser); + } + + return vXUser; + } + + public VXGroup getGroupByGroupName(String groupName) { + VXGroup vxGroup = xGroupService.getGroupByGroupName(groupName); + + if (vxGroup == null) { + throw restErrorUtil.createRESTException(groupName + " is Not Found", MessageEnums.DATA_NOT_FOUND); + } + + return vxGroup; + } + + public void assignPermissionToUser(VXPortalUser vXPortalUser, boolean isCreate) { + HashMap moduleNameId = getAllModuleNameAndIdMap(); + + if (moduleNameId != null && vXPortalUser != null && CollectionUtils.isNotEmpty(vXPortalUser.getUserRoleList())) { + for (String role : vXPortalUser.getUserRoleList()) { + if (RangerConstants.VALID_USER_ROLE_LIST.contains(role)) { + createOrUpdateUserPermisson(vXPortalUser, moduleNameId.get(RangerConstants.MODULE_RESOURCE_BASED_POLICIES), isCreate); + createOrUpdateUserPermisson(vXPortalUser, moduleNameId.get(RangerConstants.MODULE_REPORTS), isCreate); + + if (role.equals(RangerConstants.ROLE_USER)) { + createOrUpdateUserPermisson(vXPortalUser, moduleNameId.get(RangerConstants.MODULE_SECURITY_ZONE), isCreate); + } else { + createOrUpdateUserPermisson(vXPortalUser, moduleNameId.get(RangerConstants.MODULE_AUDIT), isCreate); + createOrUpdateUserPermisson(vXPortalUser, moduleNameId.get(RangerConstants.MODULE_USER_GROUPS), isCreate); + createOrUpdateUserPermisson(vXPortalUser, moduleNameId.get(RangerConstants.MODULE_GOVERNED_DATA_SHARING), isCreate); + + if (role.equals(RangerConstants.ROLE_SYS_ADMIN) || role.equals(RangerConstants.ROLE_ADMIN_AUDITOR)) { + createOrUpdateUserPermisson(vXPortalUser, moduleNameId.get(RangerConstants.MODULE_TAG_BASED_POLICIES), isCreate); + createOrUpdateUserPermisson(vXPortalUser, moduleNameId.get(RangerConstants.MODULE_SECURITY_ZONE), isCreate); + } else { + createOrUpdateUserPermisson(vXPortalUser, moduleNameId.get(RangerConstants.MODULE_KEY_MANAGER), isCreate); + } + } + } + } + } + } + + // Insert or Updating Mapping permissions depending upon roles + public void createOrUpdateUserPermisson(VXPortalUser portalUser, Long moduleId, boolean isCreate) { + VXUserPermission vXUserPermission; + XXUserPermission xUserPermission = daoManager.getXXUserPermission().findByModuleIdAndPortalUserId(portalUser.getId(), moduleId); + + if (xUserPermission == null) { + vXUserPermission = new VXUserPermission(); + + // When Creating XXUserPermission UI sends xUserId, to keep it consistent here xUserId should be used + XXUser xUser = daoManager.getXXUser().findByPortalUserId(portalUser.getId()); + + if (xUser == null) { + logger.warn("Could not found corresponding xUser for username: [{}], So not assigning permission to this user", portalUser.getLoginId()); + + return; + } else { + vXUserPermission.setUserId(xUser.getId()); + } + + vXUserPermission.setIsAllowed(RangerCommonEnums.IS_ALLOWED); + vXUserPermission.setModuleId(moduleId); + + try { + vXUserPermission = this.createXUserPermission(vXUserPermission); + + logger.info("Permission assigned to user: [{}] For Module: [{}]", vXUserPermission.getUserName(), vXUserPermission.getModuleName()); + } catch (Exception e) { + logger.error("Error while assigning permission to user: [{}] for module: [{}]", portalUser.getLoginId(), moduleId, e); + } + } else if (isCreate) { + vXUserPermission = xUserPermissionService.populateViewBean(xUserPermission); + + vXUserPermission.setIsAllowed(RangerCommonEnums.IS_ALLOWED); + + vXUserPermission = this.updateXUserPermission(vXUserPermission); + + logger.info("Permission Updated for user: [{}] For Module: [{}]", vXUserPermission.getUserName(), vXUserPermission.getModuleName()); + } + } + + public HashMap getAllModuleNameAndIdMap() { + List xXModuleDefs = daoManager.getXXModuleDef().getAll(); + + if (!CollectionUtils.isEmpty(xXModuleDefs)) { + HashMap moduleNameAndIdMap = new HashMap<>(); + + for (XXModuleDef xXModuleDef : xXModuleDefs) { + moduleNameAndIdMap.put(xXModuleDef.getModule(), xXModuleDef.getId()); + } + + return moduleNameAndIdMap; + } + + return null; + } + + public VXUserGroupInfo createXUserGroupFromMap(VXUserGroupInfo vXUserGroupInfo) { + checkAdminAccess(); + + xaBizUtil.blockAuditorRoleUser(); + + VXUserGroupInfo vxUGInfo = new VXUserGroupInfo(); + VXUser vXUser = vXUserGroupInfo.getXuserInfo(); + VXPortalUser vXPortalUser = userMgr.getUserProfileByLoginId(vXUser.getName()); + XXPortalUser xxPortalUser = daoManager.getXXPortalUser().findByLoginId(vXUser.getName()); + Collection reqRoleList = vXUser.getUserRoleList(); + List existingRole = daoManager.getXXPortalUserRole().findXPortalUserRolebyXPortalUserId(xxPortalUser.getId()); + + if (xxPortalUser.getUserSource() == RangerCommonEnums.USER_EXTERNAL) { + vXPortalUser = userMgr.updateRoleForExternalUsers(reqRoleList, existingRole, vXPortalUser); + } + + vXUser = xUserService.createXUserWithOutLogin(vXUser); + + vxUGInfo.setXuserInfo(vXUser); + + List vxg = new ArrayList<>(); + + for (VXGroup vXGroup : vXUserGroupInfo.getXgroupInfo()) { + VXGroup vvXGroup = xGroupService.createXGroupWithOutLogin(vXGroup); + + vxg.add(vvXGroup); + + VXGroupUser vXGroupUser = new VXGroupUser(); + + vXGroupUser.setUserId(vXUser.getId()); + vXGroupUser.setName(vvXGroup.getName()); + + xGroupUserService.createXGroupUserWithOutLogin(vXGroupUser); + } + + if (vXPortalUser != null) { + assignPermissionToUser(vXPortalUser, true); + } + + vxUGInfo.setXgroupInfo(vxg); + + updateUserStoreVersion("createXUserGroupFromMap(" + vXUser.getName() + ")"); + + return vxUGInfo; + } + + @Transactional(readOnly = false, propagation = Propagation.REQUIRED) + public VXGroupUserInfo createXGroupUserFromMap(VXGroupUserInfo vXGroupUserInfo) { + checkAdminAccess(); + + xaBizUtil.blockAuditorRoleUser(); + + VXGroupUserInfo vxGUInfo = new VXGroupUserInfo(); + VXGroup vXGroup = vXGroupUserInfo.getXgroupInfo(); + + // Add the group user mappings for a given group to x_group_user table + /*XXGroup xGroup = daoManager.getXXGroup().findByGroupName(vXGroup.getName()); + if (xGroup == null) { + return vxGUInfo; + }*/ + + List vxu = new ArrayList<>(); + + for (VXUser vXUser : vXGroupUserInfo.getXuserInfo()) { + XXUser xUser = daoManager.getXXUser().findByUserName(vXUser.getName()); + XXPortalUser xXPortalUser = daoManager.getXXPortalUser().findByLoginId(vXUser.getName()); + + if (xUser != null) { + // Add or update group user mapping only if the user already exists in x_user table. + logger.debug("createXGroupUserFromMap(): Create or update group {}", vXGroup.getName()); + + vXGroup = xGroupService.createXGroupWithOutLogin(vXGroup); + + vxGUInfo.setXgroupInfo(vXGroup); + vxu.add(vXUser); + + VXGroupUser vXGroupUser = new VXGroupUser(); + + vXGroupUser.setUserId(xUser.getId()); + vXGroupUser.setName(vXGroup.getName()); + + if (xXPortalUser.getUserSource() == RangerCommonEnums.USER_EXTERNAL) { + xGroupUserService.createXGroupUserWithOutLogin(vXGroupUser); + + logger.debug("createXGroupUserFromMap(): Create or update group user mapping with groupname = {} username = {} userId = {}", vXGroup.getName(), xXPortalUser.getLoginId(), xUser.getId()); + } + + Collection reqRoleList = vXUser.getUserRoleList(); + XXPortalUser xxPortalUser = daoManager.getXXPortalUser().findByLoginId(vXUser.getName()); + List existingRole = daoManager.getXXPortalUserRole().findXPortalUserRolebyXPortalUserId(xxPortalUser.getId()); + VXPortalUser vxPortalUser = userMgr.mapXXPortalUserToVXPortalUserForDefaultAccount(xxPortalUser); + + if (xxPortalUser.getUserSource() == RangerCommonEnums.USER_EXTERNAL) { + vxPortalUser = userMgr.updateRoleForExternalUsers(reqRoleList, existingRole, vxPortalUser); + + assignPermissionToUser(vxPortalUser, true); + } + } + } + + vxGUInfo.setXuserInfo(vxu); + + updateUserStoreVersion("createXGroupUserFromMap(" + vXGroup.getName() + ")"); + + return vxGUInfo; + } + + public VXGroupUserInfo getXGroupUserFromMap(String groupName) { + checkAdminAccess(); + + VXGroupUserInfo vxGUInfo = new VXGroupUserInfo(); + XXGroup xGroup = daoManager.getXXGroup().findByGroupName(groupName); + + if (xGroup == null) { + return vxGUInfo; + } + + VXGroup xgroupInfo = xGroupService.populateViewBean(xGroup); + + vxGUInfo.setXgroupInfo(xgroupInfo); + + SearchCriteria searchCriteria = new SearchCriteria(); + + searchCriteria.addParam("xGroupId", xGroup.getId()); + + VXGroupUserList vxGroupUserList = searchXGroupUsers(searchCriteria); + List vxu = new ArrayList<>(); + + logger.debug("removing all the group user mapping for : {}", xGroup.getName()); + + for (VXGroupUser groupUser : vxGroupUserList.getList()) { + XXUser xUser = daoManager.getXXUser().getById(groupUser.getUserId()); + + if (xUser != null) { + VXUser vxUser = new VXUser(); + + vxUser.setName(xUser.getName()); + + XXPortalUser xXPortalUser = daoManager.getXXPortalUser().findByLoginId(xUser.getName()); + + if (xXPortalUser != null) { + List existingRole = daoManager.getXXPortalUserRole().findXPortalUserRolebyXPortalUserId(xXPortalUser.getId()); + + if (existingRole != null) { + vxUser.setUserRoleList(existingRole); + } + } + + vxu.add(vxUser); + } + } + + vxGUInfo.setXuserInfo(vxu); + + return vxGUInfo; + } + + public VXUser createXUserWithOutLogin(VXUser vXUser) { + checkAdminAccess(); + + xaBizUtil.blockAuditorRoleUser(); + + validatePassword(vXUser); + + VXUser ret = xUserService.createXUserWithOutLogin(vXUser); + + updateUserStoreVersion("createXUserWithOutLogin(" + vXUser.getName() + ")"); + + return ret; + } + + public VXUser createExternalUser(String userName) { + checkAdminAccess(); + + xaBizUtil.blockAuditorRoleUser(); + + return createServiceConfigUser(userName); + } + + public VXGroup createXGroupWithoutLogin(VXGroup vXGroup) { + checkAdminAccess(); + + xaBizUtil.blockAuditorRoleUser(); + + VXGroup ret = xGroupService.createXGroupWithOutLogin(vXGroup); + + updateUserStoreVersion("createXGroupWithoutLogin(" + vXGroup.getName() + ")"); + + return ret; + } + + public VXGroup getXGroup(Long id) { + UserSessionBase userSession = ContextUtil.getCurrentUserSession(); + + if (userSession != null && userSession.getLoginId() != null) { + VXUser loggedInVXUser = xUserService.getXUserByUserName(userSession.getLoginId()); + + if (loggedInVXUser != null) { + if (loggedInVXUser.getUserRoleList().size() == 1 && loggedInVXUser.getUserRoleList().contains(RangerConstants.ROLE_USER)) { + List listGroupId = daoManager.getXXGroupUser().findGroupIdListByUserId(loggedInVXUser.getId()); + + if (!listGroupId.contains(id)) { + logger.info(MSG_DATA_ACCESS_DENY); + + throw restErrorUtil.create403RESTException("Logged-In user is not allowed to access requested group data."); + } + } + } + } + + VXGroup vXGroup = xGroupService.readResourceWithOutLogin(id); + + if (vXGroup != null && !hasAccessToModule(RangerConstants.MODULE_USER_GROUPS)) { + vXGroup = getMaskedVXGroup(vXGroup); + } + + return vXGroup; + } + + public VXGroup createXGroup(VXGroup vXGroup) { + checkAdminAccess(); + + xaBizUtil.blockAuditorRoleUser(); + + if (vXGroup.getDescription() == null) { + vXGroup.setDescription(vXGroup.getName()); + } + + vXGroup = xGroupService.createResource(vXGroup); + + xGroupService.createTransactionLog(vXGroup, null, OPERATION_CREATE_CONTEXT); + + updateUserStoreVersion("createXGroup(" + vXGroup.getName() + ")"); + + return vXGroup; + } + + @Override + public VXGroup updateXGroup(VXGroup vXGroup) { + checkAdminAccess(); + + xaBizUtil.blockAuditorRoleUser(); + + XXGroup xGroup = daoManager.getXXGroup().getById(vXGroup.getId()); + + if (xGroup != null && !vXGroup.getName().equals(xGroup.getName())) { + throw restErrorUtil.createRESTException("group name updates are not allowed.", MessageEnums.INVALID_INPUT_DATA); + } + + VXGroup existing = xGroup != null ? xGroupService.populateViewBean(xGroup) : null; + List trxLogList = xGroupService.getTransactionLog(vXGroup, existing, OPERATION_UPDATE_CONTEXT); + + xaBizUtil.createTrxLog(trxLogList); + + vXGroup = xGroupService.updateResource(vXGroup); + + if (vXGroup != null) { + updateXgroupUserForGroupUpdate(vXGroup); + + RangerServicePoliciesCache.sInstance = null; + } + + return vXGroup; + } + + public void deleteXGroup(Long id, boolean force) { + checkAdminAccess(); + + blockIfZoneGroup(id); + + this.blockIfRoleGroup(id); + + xaBizUtil.blockAuditorRoleUser(); + + XXGroupDao xXGroupDao = daoManager.getXXGroup(); + XXGroup xXGroup = xXGroupDao.getById(id); + + if (xXGroup == null) { + throw restErrorUtil.create404RESTException("Data Not Found for given Id", MessageEnums.DATA_NOT_FOUND, id, null, "readResource : No Object found with given id."); + } + + VXGroup vXGroup = xGroupService.populateViewBean(xXGroup); + + if (vXGroup == null || StringUtils.isEmpty(vXGroup.getName())) { + throw restErrorUtil.createRESTException("Group ID doesn't exist.", MessageEnums.INVALID_INPUT_DATA); + } + + logger.debug("Force delete status={} for group={}", force, vXGroup.getName()); + + SearchCriteria searchCriteria = new SearchCriteria(); + + searchCriteria.addParam("xGroupId", id); + + VXGroupUserList vxGroupUserList = searchXGroupUsers(searchCriteria); + + searchCriteria = new SearchCriteria(); + + searchCriteria.addParam("groupId", id); + + VXPermMapList vXPermMapList = searchXPermMaps(searchCriteria); + + searchCriteria = new SearchCriteria(); + + searchCriteria.addParam("groupId", id); + + VXAuditMapList vXAuditMapList = searchXAuditMaps(searchCriteria); + XXGroupPermissionDao xXGroupPermissionDao = daoManager.getXXGroupPermission(); + List xXGroupPermissions = xXGroupPermissionDao.findByGroupId(id); + XXPolicyDao xXPolicyDao = daoManager.getXXPolicy(); + List xXPolicyList = xXPolicyDao.findByGroupId(id); + + logger.warn("Deleting GROUP : {}", vXGroup.getName()); + + if (force) { + //delete XXGroupUser records of matching group + XXGroupUserDao xGroupUserDao = daoManager.getXXGroupUser(); + XXUserDao xXUserDao = daoManager.getXXUser(); + + for (VXGroupUser groupUser : vxGroupUserList.getList()) { + if (groupUser != null) { + XXUser xXUser = xXUserDao.getById(groupUser.getUserId()); + + if (xXUser != null) { + logger.warn("Removing user '{}' from group '{}'", xXUser.getName(), groupUser.getName()); + } + + xGroupUserDao.remove(groupUser.getId()); + } + } + + //delete XXPermMap records of matching group + XXPermMapDao xXPermMapDao = daoManager.getXXPermMap(); + XXResourceDao xXResourceDao = daoManager.getXXResource(); + + for (VXPermMap vXPermMap : vXPermMapList.getList()) { + if (vXPermMap != null) { + XXResource xXResource = xXResourceDao.getById(vXPermMap.getResourceId()); + + if (xXResource != null) { + logger.warn("Deleting '{}' permission from policy ID='{}' for group '{}'", AppConstants.getLabelFor_XAPermType(vXPermMap.getPermType()), vXPermMap.getResourceId(), vXPermMap.getGroupName()); + } + + xXPermMapDao.remove(vXPermMap.getId()); + } + } + + //delete XXAuditMap records of matching group + XXAuditMapDao xXAuditMapDao = daoManager.getXXAuditMap(); + + for (VXAuditMap vXAuditMap : vXAuditMapList.getList()) { + if (vXAuditMap != null) { + xXResourceDao.getById(vXAuditMap.getResourceId()); + + xXAuditMapDao.remove(vXAuditMap.getId()); + } + } + + //delete XXPolicyItemGroupPerm records of group + for (XXPolicy xXPolicy : xXPolicyList) { + RangerPolicy rangerPolicy = policyService.getPopulatedViewObject(xXPolicy); + List policyItems = rangerPolicy.getPolicyItems(); + + removeUserGroupReferences(policyItems, null, vXGroup.getName()); + rangerPolicy.setPolicyItems(policyItems); + + List denyPolicyItems = rangerPolicy.getDenyPolicyItems(); + removeUserGroupReferences(denyPolicyItems, null, vXGroup.getName()); + rangerPolicy.setDenyPolicyItems(denyPolicyItems); + + List allowExceptions = rangerPolicy.getAllowExceptions(); + removeUserGroupReferences(allowExceptions, null, vXGroup.getName()); + rangerPolicy.setAllowExceptions(allowExceptions); + + List denyExceptions = rangerPolicy.getDenyExceptions(); + removeUserGroupReferences(denyExceptions, null, vXGroup.getName()); + rangerPolicy.setDenyExceptions(denyExceptions); + + List dataMaskItems = rangerPolicy.getDataMaskPolicyItems(); + removeUserGroupReferences(dataMaskItems, null, vXGroup.getName()); + rangerPolicy.setDataMaskPolicyItems(dataMaskItems); + + List rowFilterItems = rangerPolicy.getRowFilterPolicyItems(); + removeUserGroupReferences(rowFilterItems, null, vXGroup.getName()); + rangerPolicy.setRowFilterPolicyItems(rowFilterItems); + + try { + if (StringUtils.equals(rangerPolicy.getServiceType(), EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_GDS_NAME)) { + Map resources = rangerPolicy.getResources(); + + if (MapUtils.isEmpty(resources)) { + continue; + } + + if (resources.containsKey(GdsDBStore.RESOURCE_NAME_DATASET_ID)) { + RangerPolicyResource policyRes = resources.get(GdsDBStore.RESOURCE_NAME_DATASET_ID); + List resValues = policyRes != null ? policyRes.getValues() : null; + + if (CollectionUtils.isNotEmpty(resValues)) { + gdsStore.updateDatasetPolicy(Long.valueOf(resValues.get(0)), rangerPolicy); + } + } else if (resources.containsKey(GdsDBStore.RESOURCE_NAME_PROJECT_ID)) { + RangerPolicyResource policyRes = resources.get(GdsDBStore.RESOURCE_NAME_PROJECT_ID); + List resValues = policyRes != null ? policyRes.getValues() : null; + + if (CollectionUtils.isNotEmpty(resValues)) { + gdsStore.updateProjectPolicy(Long.valueOf(resValues.get(0)), rangerPolicy); + } + } + } else { + svcStore.updatePolicy(rangerPolicy); + } + } catch (Throwable excp) { + logger.error("updatePolicy({}) failed", rangerPolicy, excp); + + throw restErrorUtil.createRESTException(excp.getMessage()); + } + } + + if (CollectionUtils.isNotEmpty(xXGroupPermissions)) { + for (XXGroupPermission xXGroupPermission : xXGroupPermissions) { + if (xXGroupPermission != null) { + XXModuleDef xXModuleDef = daoManager.getXXModuleDef().findByModuleId(xXGroupPermission.getModuleId()); + + if (xXModuleDef != null) { + logger.warn("Deleting '{}' module permission for group '{}'", xXModuleDef.getModule(), xXGroup.getName()); + } + + xXGroupPermissionDao.remove(xXGroupPermission.getId()); + } + } + } + + //delete group from audit filter configs + svcStore.updateServiceAuditConfig(vXGroup.getName(), REMOVE_REF_TYPE.GROUP); + + // delete group from dataset,datashare,project + gdsStore.deletePrincipalFromGdsAcl(REMOVE_REF_TYPE.GROUP.toString(), vXGroup.getName()); + + //delete XXGroup + xXGroupDao.remove(id); + + //Create XXTrxLog + xGroupService.createTransactionLog(xGroupService.populateViewBean(xXGroup), null, OPERATION_DELETE_CONTEXT); + } else { + boolean hasReferences = vxGroupUserList.getListSize() > 0; + + if (!hasReferences && CollectionUtils.isNotEmpty(xXPolicyList)) { + hasReferences = true; + } + + if (!hasReferences && vXPermMapList.getListSize() > 0) { + hasReferences = true; + } + + if (!hasReferences && vXAuditMapList.getListSize() > 0) { + hasReferences = true; + } + + if (!hasReferences && CollectionUtils.isNotEmpty(xXGroupPermissions)) { + hasReferences = true; } - createXGroupWithoutLogin(vXGroup); - } - - updateUserStoreVersion("createOrUpdateXGroups(groupsCount=" + groups.getListSize() + ")"); - - return groups.getListSize(); - } - - public int createOrDeleteXGroupUserList(List groupUserInfoList) { - int updatedGroups = 0; - Long mb = 1024L * 1024L; - if (logger.isDebugEnabled()) { - logger.debug("==>> createOrDeleteXGroupUserList"); - logger.debug("Max memory = " + Runtime.getRuntime().maxMemory()/mb + " Free memory = " + Runtime.getRuntime().freeMemory()/mb - + " Total memory = " + Runtime.getRuntime().totalMemory()/mb); - } - checkAdminAccess(); - xaBizUtil.blockAuditorRoleUser(); - if (CollectionUtils.isNotEmpty(groupUserInfoList)) { - if (logger.isDebugEnabled()) { - logger.debug("No. of groups to be updated = " + groupUserInfoList.size()); - } - Map usersFromDB = daoManager.getXXUser().getAllUserIds(); - if (MapUtils.isNotEmpty(usersFromDB)) { - if (logger.isDebugEnabled()) { - logger.debug("No. of users in DB = " + usersFromDB.size()); - logger.debug("After users from DB - Max memory = " + Runtime.getRuntime().maxMemory()/mb + " Free memory = " + Runtime.getRuntime().freeMemory()/mb - + " Total memory = " + Runtime.getRuntime().totalMemory()/mb); - } - for (GroupUserInfo groupUserInfo : groupUserInfoList) { - xGroupUserService.createOrDeleteXGroupUsers(groupUserInfo, usersFromDB); - } - updatedGroups = groupUserInfoList.size(); - } - } - if (logger.isDebugEnabled()) { - logger.debug("<<== createOrDeleteXGroupUserList"); - logger.debug("Max memory = " + Runtime.getRuntime().maxMemory()/mb + " Free memory = " + Runtime.getRuntime().freeMemory()/mb - + " Total memory = " + Runtime.getRuntime().totalMemory()/mb); - } - return updatedGroups; - } - - @Transactional(readOnly = false, propagation = Propagation.REQUIRED) - public List updateUserRoleAssignments(UsersGroupRoleAssignments ugRoleAssignments) { - List updatedUsers = new ArrayList<>(); - List requestedUsers = ugRoleAssignments.getUsers(); - Map userMap = ugRoleAssignments.getUserRoleAssignments(); - Map groupMap = ugRoleAssignments.getGroupRoleAssignments(); - Map whiteListUserMap = ugRoleAssignments.getWhiteListUserRoleAssignments(); - Map whiteListGroupMap = ugRoleAssignments.getWhiteListGroupRoleAssignments(); - if (logger.isDebugEnabled()) { - logger.debug("Request users for role updates = " + requestedUsers); - } - - // For each user get groups and compute roles based on group role assignments - for (String userName : requestedUsers) { - VXPortalUser vXPortalUser = userMgr.getUserProfileByLoginId(userName); - if (vXPortalUser == null) { - logger.info(userName + " doesn't exist and hence ignoring role assignments"); - continue; - } - if (vXPortalUser.getUserSource() != RangerCommonEnums.USER_EXTERNAL){ - logger.info(userName + " is internal to ranger admin and hence ignoring role assignments"); - continue; - } - - if (logger.isDebugEnabled()) { - logger.debug("Computing role for " + userName); - } - - Set groupUsers = getGroupsForUser(userName); - - String userRole = RangerConstants.ROLE_USER; - if (MapUtils.isNotEmpty(userMap) && userMap.containsKey(userName)) { - // Add the user role that is defined in user role assignments - userRole = userMap.get(userName); - } else if (MapUtils.isNotEmpty(groupMap) && CollectionUtils.isNotEmpty(groupUsers)) { - for (String group : groupMap.keySet()) { - if (groupUsers.contains(group)) { - String value = groupMap.get(group); - if (value != null) { - userRole = value; - break; - } - } - } - } - - if (MapUtils.isNotEmpty(whiteListUserMap) && whiteListUserMap.containsKey(userName)) { - userRole = whiteListUserMap.get(userName); - } else if (MapUtils.isNotEmpty(whiteListGroupMap) && CollectionUtils.isNotEmpty(groupUsers)) { - for (String group : whiteListGroupMap.keySet()) { - if (groupUsers.contains(group)) { - String value = whiteListGroupMap.get(group); - if (value != null) { - userRole = value; - break; - } - } - } - } - - if (!vXPortalUser.getUserRoleList().contains(userRole)) { - if (logger.isDebugEnabled()) { - logger.debug(String.format("Updating role for %s to %s", userName, userRole)); - } - //Update the role of the user only if newly computed role is different from the existing role. - String updatedUser = setRolesByUserName(userName, Collections.singletonList(userRole)); - if (updatedUser != null) { - updatedUsers.add(updatedUser); - } - } else { - if (logger.isDebugEnabled()) { - logger.debug(String.format("Role for %s unchanged: %s", userName, userRole)); - } - } - - if (ugRoleAssignments.isReset()) { // use below data structure only when reset is true - roleAssignmentUpdatedUsers.add(userName); - } - } - - // Reset the role of any other users that are not part of the updated role assignments rules - if (ugRoleAssignments.isReset() && ugRoleAssignments.isLastPage()) { - List externalUsersWithNonUserRole = daoManager.getXXPortalUser().getNonUserRoleExternalUsers(); - if (logger.isDebugEnabled()) { - logger.debug("Existing external users with roles excluding ROLE_USER role: " + externalUsersWithNonUserRole); - } - for (String userName : externalUsersWithNonUserRole) { - if (!roleAssignmentUpdatedUsers.contains(userName)) { - if (logger.isDebugEnabled()) { - logger.debug(String.format("Resetting to ROLE_USER for %s", userName)); - } - String updatedUser = setRolesByUserName(userName, Collections.singletonList(RangerConstants.ROLE_USER)); - if (updatedUser != null) { - updatedUsers.add(updatedUser); - } - } - } - roleAssignmentUpdatedUsers.clear(); - } - return updatedUsers; - } - - private String setRolesByUserName(String userName, List roleListNewProfile) { - if (logger.isDebugEnabled()) { - logger.debug("==> XUserMgr.setRolesByUserName(" + userName + ", " + roleListNewProfile + ")"); - } - String ret = null; - xaBizUtil.blockAuditorRoleUser(); - if (roleListNewProfile == null) { - roleListNewProfile = new ArrayList(); - } - - if(userName!=null && roleListNewProfile.size()>0){ - checkAccessRoles(roleListNewProfile); - VXPortalUser oldUserProfile = userMgr.getUserProfileByLoginId(userName); - if(oldUserProfile!=null){ - denySelfRoleChange(oldUserProfile.getLoginId()); - updateUserRolesPermissions(oldUserProfile,roleListNewProfile); - logger.info("<== XUserMgr.setRolesByUserName returned roles for " + userName + " are: " + roleListNewProfile ); - ret = userName; - }else{ - logger.error(userName + "doesn't exist."); - } - }else{ - logger.error(userName + "doesn't exist or new role assignments are empty"); - } - if (logger.isDebugEnabled()) { - logger.debug("<== XUserMgr.setRolesByUserName(" + userName + ", " + roleListNewProfile + ") ret = " + ret); - } - return ret; - } - - private void assignPermissionToUser(Collection vXPortalUserList, Long vXPortalUserId, Long xUserId, boolean isCreate) { - HashMap moduleNameId = getAllModuleNameAndIdMap(); - if(moduleNameId != null && CollectionUtils.isNotEmpty(vXPortalUserList)){ - for (String role : vXPortalUserList) { - if (RangerConstants.VALID_USER_ROLE_LIST.contains(role)){ - createOrUpdateUserPermisson(vXPortalUserId, xUserId, moduleNameId.get(RangerConstants.MODULE_RESOURCE_BASED_POLICIES), isCreate); - createOrUpdateUserPermisson(vXPortalUserId, xUserId, moduleNameId.get(RangerConstants.MODULE_REPORTS), isCreate); - if (role.equals(RangerConstants.ROLE_USER)){ - createOrUpdateUserPermisson(vXPortalUserId, xUserId, moduleNameId.get(RangerConstants.MODULE_SECURITY_ZONE), isCreate); - } else { - createOrUpdateUserPermisson(vXPortalUserId, xUserId, moduleNameId.get(RangerConstants.MODULE_AUDIT), isCreate); - createOrUpdateUserPermisson(vXPortalUserId, xUserId, moduleNameId.get(RangerConstants.MODULE_USER_GROUPS), isCreate); - - if (role.equals(RangerConstants.ROLE_SYS_ADMIN) || role.equals(RangerConstants.ROLE_ADMIN_AUDITOR)) { - - createOrUpdateUserPermisson(vXPortalUserId, xUserId, moduleNameId.get(RangerConstants.MODULE_TAG_BASED_POLICIES), isCreate); - createOrUpdateUserPermisson(vXPortalUserId, xUserId, moduleNameId.get(RangerConstants.MODULE_SECURITY_ZONE), isCreate); - - } else { - createOrUpdateUserPermisson(vXPortalUserId, xUserId, moduleNameId.get(RangerConstants.MODULE_KEY_MANAGER), isCreate); - } - } - } - } - } - } - - private void createOrUpdateUserPermisson(Long portalUserId, Long xUserId, Long moduleId, boolean isCreate) { - VXUserPermission vXUserPermission; - XXUserPermission xUserPermission = daoManager.getXXUserPermission().findByModuleIdAndPortalUserId(portalUserId, moduleId); - if (xUserPermission == null) { - vXUserPermission = new VXUserPermission(); - - // When Creating XXUserPermission UI sends xUserId, to keep it consistent here xUserId should be used - vXUserPermission.setUserId(xUserId); - - vXUserPermission.setIsAllowed(RangerCommonEnums.IS_ALLOWED); - vXUserPermission.setModuleId(moduleId); - try { - vXUserPermission = this.createXUserPermission(vXUserPermission); - logger.info("Permission assigned to user: [" + vXUserPermission.getUserName() + "] For Module: [" + vXUserPermission.getModuleName() + "]"); - } catch (Exception e) { - logger.error("Error while assigning permission to user: [" + portalUserId + "] for module: [" + moduleId + "]", e); - } - } else if (isCreate) { - vXUserPermission = xUserPermissionService.populateViewBean(xUserPermission); - vXUserPermission.setIsAllowed(RangerCommonEnums.IS_ALLOWED); - vXUserPermission = this.updateXUserPermission(vXUserPermission); - logger.info("Permission Updated for user: [" + vXUserPermission.getUserName() + "] For Module: [" + vXUserPermission.getModuleName() + "]"); - } - } - - private VXUser updateXUser(VXUser vXUser, VXPortalUser oldUserProfile) { - if (logger.isDebugEnabled()) { - logger.debug("Updating user: " + vXUser.getName()); - } - VXPortalUser vXPortalUser = new VXPortalUser(); - if (oldUserProfile != null && oldUserProfile.getId() != null) { - vXPortalUser.setId(oldUserProfile.getId()); - } - - vXPortalUser.setFirstName(vXUser.getFirstName()); - if("null".equalsIgnoreCase(vXPortalUser.getFirstName())){ - vXPortalUser.setFirstName(""); - } - vXPortalUser.setLastName(vXUser.getLastName()); - if("null".equalsIgnoreCase(vXPortalUser.getLastName())){ - vXPortalUser.setLastName(""); - } - vXPortalUser.setEmailAddress(vXUser.getEmailAddress()); - vXPortalUser.setLoginId(vXUser.getName()); - vXPortalUser.setStatus(vXUser.getStatus()); - vXPortalUser.setUserRoleList(vXUser.getUserRoleList()); - if (vXPortalUser.getFirstName() != null - && vXPortalUser.getLastName() != null - && !vXPortalUser.getFirstName().trim().isEmpty() - && !vXPortalUser.getLastName().trim().isEmpty()) { - vXPortalUser.setPublicScreenName(vXPortalUser.getFirstName() + " " - + vXPortalUser.getLastName()); - } else { - vXPortalUser.setPublicScreenName(vXUser.getName()); - } - vXPortalUser.setUserSource(vXUser.getUserSource()); - vXPortalUser.setSyncSource(vXUser.getSyncSource()); - - String hiddenPasswordString = PropertiesUtil.getProperty("ranger.password.hidden", "*****"); - String password = vXUser.getPassword(); - if (oldUserProfile != null && password != null - && password.equals(hiddenPasswordString)) { - vXPortalUser.setPassword(oldUserProfile.getPassword()); - } - else if(oldUserProfile != null && oldUserProfile.getUserSource() == RangerCommonEnums.USER_EXTERNAL && password != null){ - vXPortalUser.setPassword(oldUserProfile.getPassword()); - logger.debug("User is trying to change external user password which we are not allowing it to change"); - } - else if(password != null){ - validatePassword(vXUser); - vXPortalUser.setPassword(password); - } - XXPortalUser xXPortalUser = new XXPortalUser(); - xXPortalUser = userMgr.updateUserWithPass(vXPortalUser); - - //update permissions start - Collection roleListUpdatedProfile =new ArrayList(); - if (oldUserProfile != null && oldUserProfile.getId() != null) { - if(vXUser!=null && vXUser.getUserRoleList()!=null){ - Collection roleListOldProfile = oldUserProfile.getUserRoleList(); - Collection roleListNewProfile = vXUser.getUserRoleList(); - if(roleListNewProfile!=null && roleListOldProfile!=null){ - for (String role : roleListNewProfile) { - if(role!=null && !roleListOldProfile.contains(role)){ - roleListUpdatedProfile.add(role); - } - } - - } - } - } - if(roleListUpdatedProfile!=null && roleListUpdatedProfile.size()>0){ - vXPortalUser.setUserRoleList(roleListUpdatedProfile); - List xuserPermissionList = daoManager - .getXXUserPermission() - .findByUserPermissionId(vXPortalUser.getId()); - if (xuserPermissionList!=null && xuserPermissionList.size()>0){ - for (XXUserPermission xXUserPermission : xuserPermissionList) { - if (xXUserPermission != null) { - try { - xUserPermissionService.deleteResource(xXUserPermission.getId()); - } catch (Exception e) { - logger.error(e.getMessage()); - } - } - } - } - } - //update permissions end - Collection roleList = new ArrayList(); - if (xXPortalUser != null) { - roleList = userMgr.getRolesForUser(xXPortalUser); - } - if (roleList == null || roleList.size() == 0) { - roleList = new ArrayList(); - roleList.add(RangerConstants.ROLE_USER); - } - - // TODO I've to get the transaction log from here. - // There is nothing to log anything in XXUser so far. - XXUser xUser = daoManager.getXXUser().findByUserName(vXUser.getName()); - if (xUser == null) { - logger.warn("Could not find corresponding xUser for username: [" + vXPortalUser.getLoginId() + "], So not updating this user"); - return vXUser; - } - - VXUser existing = xUserService.populateViewBean(xUser); - - logger.info("xUser.getName() = " + xUser.getName() + " vXUser.getName() = " + vXUser.getName()); - vXUser.setId(xUser.getId()); - try { - vXUser = xUserService.updateResource(vXUser); - } catch (Exception ex) { - logger.warn("Failed to update username " + vXUser.getName()); - if (logger.isDebugEnabled()) { - logger.debug("Failed to update username " + vXUser.getName(), ex); - } - } - vXUser.setUserRoleList(roleList); - if (oldUserProfile != null) { - if (oldUserProfile.getUserSource() == RangerCommonEnums.USER_APP) { - vXUser.setPassword(password); - } - else if (oldUserProfile.getUserSource() == RangerCommonEnums.USER_EXTERNAL) { - vXUser.setPassword(oldUserProfile.getPassword()); - } - } - - List trxLogList = xUserService.getTransactionLog(vXUser, existing, OPERATION_UPDATE_CONTEXT); - vXUser.setPassword(hiddenPasswordString); - - Long userId = vXUser.getId(); - assignPermissionToUser(vXPortalUser.getUserRoleList(), vXPortalUser.getId(), userId, true); - - xaBizUtil.createTrxLog(trxLogList); - - if (logger.isDebugEnabled()) { - logger.debug("Done updating user: " + vXUser.getName()); - } - - return vXUser; - } - - public int updateDeletedUsers(Set deletedUsers) { - for (String deletedUser : deletedUsers) { - XXUser xUser = daoManager.getXXUser().findByUserName(deletedUser); - if (xUser != null) { - VXUser vObj = xUserService.populateViewBean(xUser); - vObj.setIsVisible(RangerCommonEnums.IS_HIDDEN); - xUserService.updateResource(vObj); - } - } - return deletedUsers.size(); - } - - public int updateDeletedGroups(Set deletedGroups) { - for (String deletedGroup : deletedGroups) { - XXGroup xGroup = daoManager.getXXGroup().findByGroupName(deletedGroup); - if (xGroup != null) { - VXGroup vObj = xGroupService.populateViewBean(xGroup); - vObj.setIsVisible(RangerCommonEnums.IS_HIDDEN); - xGroupService.updateResource(vObj); - } - } - return deletedGroups.size(); - } - - public VXUserList lookupXUsers(SearchCriteria searchCriteria) { - VXUserList vXUserList = new VXUserList(); - if (StringUtils.isBlank(searchCriteria.getSortBy())) { - searchCriteria.setSortBy("id"); - } - vXUserList = xUserService.lookupXUsers(searchCriteria, vXUserList); - return vXUserList; - } - - public Map getUserCountByRole() { - return daoManager.getXXPortalUser().getCountByUserRole(); - } - - private class ExternalUserCreator implements Runnable { - private String userName; - - ExternalUserCreator(String user) { - this.userName = user; - } - - @Override - public void run() { - createExternalUser(); - } - - private void createExternalUser() { - if (logger.isDebugEnabled()) { - logger.debug("==> ExternalUserCreator.createExternalUser(username=" + userName); - } - - XXPortalUser xXPortalUser = daoManager.getXXPortalUser().findByLoginId(userName); - if (xXPortalUser == null) { - if (logger.isDebugEnabled()) { - logger.debug("createExternalUser(): Couldn't find " + userName+ " and hence creating user in x_portal_user table"); - } - VXPortalUser vXPortalUser = new VXPortalUser(); - vXPortalUser.setLoginId(userName); - vXPortalUser.setUserSource(RangerCommonEnums.USER_EXTERNAL); - ArrayList roleList = new ArrayList(); - roleList.add(RangerConstants.ROLE_USER); - vXPortalUser.setUserRoleList(roleList); - xXPortalUser = userMgr.mapVXPortalUserToXXPortalUser(vXPortalUser); - try { - xXPortalUser = userMgr.createUser(xXPortalUser, RangerCommonEnums.STATUS_ENABLED, roleList); - if (logger.isDebugEnabled()) { - logger.debug("createExternalUser(): Successfully created user in x_portal_user table " + xXPortalUser.getLoginId()); - } - } catch (Exception ex) { - throw new RuntimeException("Failed to create user " + userName + " in x_portal_user table. retrying", ex); - } - } - - VXUser createdXUser = null; - String actualPassword = ""; - XXUser xXUser = daoManager.getXXUser().findByUserName(userName); - if (xXPortalUser != null && xXUser == null) { - VXUser vXUser = new VXUser(); - vXUser.setName(userName); - vXUser.setUserSource(RangerCommonEnums.USER_EXTERNAL); - vXUser.setDescription(vXUser.getName()); - actualPassword = vXUser.getPassword(); - try { - createdXUser = xUserService.createResource(vXUser); - if (logger.isDebugEnabled()) { - logger.debug("createExternalUser(): Successfully created user in x_user table " + vXUser.getName()); - } - } catch (Exception ex) { - throw new RuntimeException("Failed to create user " + userName + " in x_user table. retrying", ex); - } - } - - if (createdXUser != null) { - logger.info("User created: " + createdXUser.getName()); - try { - createdXUser.setPassword(actualPassword); - xUserService.createTransactionLog(createdXUser, null, OPERATION_CREATE_CONTEXT); - String hiddenPassword = PropertiesUtil.getProperty("ranger.password.hidden", "*****"); - createdXUser.setPassword(hiddenPassword); - } catch (Exception ex) { - throw new RuntimeException("Error while creating trx logs for user: " + createdXUser.getName(), ex); - } - - try { - if (xXPortalUser != null) { - VXPortalUser createdXPortalUser = userMgr.mapXXPortalUserToVXPortalUserForDefaultAccount(xXPortalUser); - assignPermissionToUser(createdXPortalUser, true); - } - } catch (Exception ex) { - throw new RuntimeException("Error while assigning permissions to user: " + createdXUser.getName(), ex); - } - } - - if (logger.isDebugEnabled()) { - logger.debug("<== ExternalUserCreator.createExternalUser(username=" + userName); - } - } - } - - private void updateUserStoreVersion(String label) { - try { - daoManager.getXXGlobalState().onGlobalAppDataChange(RANGER_GLOBAL_STATE_NAME_USER_GROUP); - } catch (Exception excp) { - logger.error(label + ": userStore version update failed", excp); - } - } + + if (hasReferences) { //change visibility to Hidden + if (vXGroup.getIsVisible() == RangerCommonEnums.IS_VISIBLE) { + vXGroup.setIsVisible(RangerCommonEnums.IS_HIDDEN); + + xGroupService.updateResource(vXGroup); + } + } else { + //delete XXGroup + xXGroupDao.remove(id); + + //Create XXTrxLog + xGroupService.createTransactionLog(xGroupService.populateViewBean(xXGroup), null, OPERATION_DELETE_CONTEXT); + } + } + } + + @Override + public VXGroupList searchXGroups(SearchCriteria searchCriteria) { + VXGroupList vXGroupList = new VXGroupList(); + VXGroup vXGroupExactMatch = null; + VXUser loggedInVXUser = null; + + try { + //In case of user we need to fetch only its associated groups. + UserSessionBase userSession = ContextUtil.getCurrentUserSession(); + + if (userSession != null && userSession.getUserRoleList().size() == 1 && userSession.getUserRoleList().contains(RangerConstants.ROLE_USER) && userSession.getLoginId() != null) { + loggedInVXUser = xUserService.getXUserByUserName(userSession.getLoginId()); + + if (loggedInVXUser != null) { + searchCriteria.addParam("userId", loggedInVXUser.getId()); + } + } + + VXGroupList vXGroupListSort = new VXGroupList(); + + if (searchCriteria.getParamList() != null && searchCriteria.getParamList().get("name") != null) { + searchCriteria.setSortBy("name"); + + vXGroupListSort = xGroupService.searchXGroups(searchCriteria); + vXGroupExactMatch = getGroupByGroupName((String) searchCriteria.getParamList().get("name")); + } + + int vXGroupExactMatchwithSearchCriteria = 0; + + if (vXGroupExactMatch != null) { + HashMap searchCriteriaParamList = searchCriteria.getParamList(); + + vXGroupExactMatchwithSearchCriteria = 1; + + for (Map.Entry entry : searchCriteriaParamList.entrySet()) { + String caseKey = entry.getKey(); + + switch (caseKey.toLowerCase()) { + case "isvisible": + Integer isVisible = vXGroupExactMatch.getIsVisible(); + + if (isVisible != null && !isVisible.equals(entry.getValue())) { + vXGroupExactMatchwithSearchCriteria = -1; + } + break; + case "groupsource": + Integer groupsource = vXGroupExactMatch.getGroupSource(); + + if (!groupsource.equals(entry.getValue())) { + vXGroupExactMatchwithSearchCriteria = -1; + } + break; + //Its required because we need to filter groups for user role + case "userid": + if (loggedInVXUser != null) { + List listGroupId = daoManager.getXXGroupUser().findGroupIdListByUserId(loggedInVXUser.getId()); + + if (!listGroupId.contains(vXGroupExactMatch.getId())) { + vXGroupExactMatchwithSearchCriteria = -1; + } + } + + break; + default: + logger.warn("XUserMgr.searchXGroups: unexpected searchCriteriaParam:{}", caseKey); + break; + } + + if (vXGroupExactMatchwithSearchCriteria == -1) { + break; + } + } + } + + if (vXGroupExactMatchwithSearchCriteria == 1) { + List vXGroups = new ArrayList<>(); + + if (searchCriteria.getStartIndex() == 0) { + vXGroups.add(0, vXGroupExactMatch); + } + + for (VXGroup vXGroup : vXGroupListSort.getList()) { + if (vXGroupExactMatch.getId() != null && vXGroup != null) { + if (!vXGroupExactMatch.getId().equals(vXGroup.getId())) { + vXGroups.add(vXGroup); + } + } + } + + vXGroupList.setVXGroups(vXGroups); + vXGroupList.setStartIndex(searchCriteria.getStartIndex()); + vXGroupList.setResultSize(vXGroupList.getList().size()); + vXGroupList.setTotalCount(vXGroupListSort.getTotalCount()); + vXGroupList.setPageSize(searchCriteria.getMaxRows()); + vXGroupList.setSortBy(searchCriteria.getSortBy()); + vXGroupList.setSortType(searchCriteria.getSortType()); + } + } catch (Exception e) { + logger.error("Error getting the exact match of group =>{}", String.valueOf(e)); + } + + if (vXGroupList.getList().isEmpty()) { + if (StringUtils.isBlank(searchCriteria.getSortBy())) { + searchCriteria.setSortBy("id"); + } + + vXGroupList = xGroupService.searchXGroups(searchCriteria); + } + + if (vXGroupList != null && !hasAccessToModule(RangerConstants.MODULE_USER_GROUPS)) { + if (vXGroupList.getListSize() > 0) { + List listMasked = new ArrayList<>(); + + for (VXGroup vXGroup : vXGroupList.getList()) { + vXGroup = getMaskedVXGroup(vXGroup); + + listMasked.add(vXGroup); + } + + vXGroupList.setVXGroups(listMasked); + } + } + + return vXGroupList; + } + + public VXUser getXUser(Long id) { + VXUser vXUser = xUserService.readResourceWithOutLogin(id); + + if (vXUser != null && !hasAccessToGetUserInfo(vXUser)) { + logger.info(MSG_DATA_ACCESS_DENY); + + throw restErrorUtil.createRESTException(HttpServletResponse.SC_FORBIDDEN, MSG_DATA_ACCESS_DENY, true); + } + + if (vXUser != null && !hasAccessToModule(RangerConstants.MODULE_USER_GROUPS)) { + vXUser = getMaskedVXUser(vXUser); + } + + return vXUser; + } + + public VXUser createXUser(VXUser vXUser) { + checkAdminAccess(); + + xaBizUtil.blockAuditorRoleUser(); + + if (vXUser.getUserSource() == RangerCommonEnums.USER_FEDERATED) { + if (StringUtils.isEmpty(vXUser.getPassword())) { + PasswordGenerator passwordGenerator = new PasswordGenerator.PasswordGeneratorBuilder() + .useLower(true) + .useUpper(true) + .useDigits(true) + .useSymbols(true) + .build(); + String passWd = passwordGenerator.generate(PASSWORD_LENGTH); + + vXUser.setPassword(passWd); + } + } + + validatePassword(vXUser); + + String userName = vXUser.getName(); + String firstName = vXUser.getFirstName(); + + if (userName == null || "null".equalsIgnoreCase(userName) || userName.trim().isEmpty()) { + throw restErrorUtil.createRESTException("Please provide a valid username.", MessageEnums.INVALID_INPUT_DATA); + } + + if (firstName == null || "null".equalsIgnoreCase(firstName) || firstName.trim().isEmpty()) { + throw restErrorUtil.createRESTException("Please provide a valid first name.", MessageEnums.INVALID_INPUT_DATA); + } + + if (vXUser.getDescription() == null) { + vXUser.setDescription(vXUser.getName()); + } + + String actualPassword = vXUser.getPassword(); + VXPortalUser vXPortalUser = new VXPortalUser(); + + vXPortalUser.setLoginId(userName); + vXPortalUser.setFirstName(vXUser.getFirstName()); + + if ("null".equalsIgnoreCase(vXPortalUser.getFirstName())) { + vXPortalUser.setFirstName(""); + } + + vXPortalUser.setLastName(vXUser.getLastName()); + + if ("null".equalsIgnoreCase(vXPortalUser.getLastName())) { + vXPortalUser.setLastName(""); + } + + String emailAddress = vXUser.getEmailAddress(); + + if (StringUtils.isNotEmpty(emailAddress) && !stringUtil.validateEmail(emailAddress)) { + logger.warn("Invalid email address:{}", emailAddress); + + throw restErrorUtil.createRESTException("Please provide valid email address.", MessageEnums.INVALID_INPUT_DATA); + } + + vXPortalUser.setEmailAddress(emailAddress); + + if (vXPortalUser.getFirstName() != null && vXPortalUser.getLastName() != null && !vXPortalUser.getFirstName().trim().isEmpty() && !vXPortalUser.getLastName().trim().isEmpty()) { + vXPortalUser.setPublicScreenName(vXPortalUser.getFirstName() + " " + vXPortalUser.getLastName()); + } else { + vXPortalUser.setPublicScreenName(vXUser.getName()); + } + + vXPortalUser.setPassword(actualPassword); + vXPortalUser.setUserRoleList(vXUser.getUserRoleList()); + + vXPortalUser = userMgr.createDefaultAccountUser(vXPortalUser); + + VXUser createdXUser = xUserService.createResource(vXUser); + + createdXUser.setPassword(actualPassword); + + List trxLogList = xUserService.getTransactionLog(createdXUser, null, OPERATION_CREATE_CONTEXT); + String hiddenPassword = PropertiesUtil.getProperty("ranger.password.hidden", "*****"); + + createdXUser.setPassword(hiddenPassword); + + Collection groupNamesList = new ArrayList<>(); + Collection groupIdList = vXUser.getGroupIdList(); + List vXGroupUsers = new ArrayList<>(); + + if (groupIdList != null) { + for (Long groupId : groupIdList) { + VXGroupUser vXGroupUser = createXGroupUser(createdXUser.getId(), groupId); + + // trxLogList.addAll(xGroupUserService.getTransactionLog( + // vXGroupUser, "create")); + vXGroupUsers.add(vXGroupUser); + + groupNamesList.add(vXGroupUser.getName()); + } + } + + createdXUser.setGroupIdList(groupIdList); + createdXUser.setGroupNameList(groupNamesList); + + for (VXGroupUser vXGroupUser : vXGroupUsers) { + List groupUserTrxLogs = xGroupUserService.getTransactionLog(vXGroupUser, null, OPERATION_CREATE_CONTEXT); + + if (CollectionUtils.isNotEmpty(groupUserTrxLogs)) { + if (trxLogList == null) { + trxLogList = new ArrayList<>(); + } + + trxLogList.addAll(groupUserTrxLogs); + } + } + + // + xaBizUtil.createTrxLog(trxLogList); + + if (vXPortalUser != null) { + assignPermissionToUser(vXPortalUser, true); + } + + updateUserStoreVersion("createXUser(" + vXUser.getName() + ")"); + + return createdXUser; + } + + public VXUser updateXUser(VXUser vXUser) { + if (vXUser == null || vXUser.getName() == null || "null".equalsIgnoreCase(vXUser.getName()) || vXUser.getName().trim().isEmpty()) { + throw restErrorUtil.createRESTException("Please provide a valid " + "username.", MessageEnums.INVALID_INPUT_DATA); + } + + String firstName = vXUser.getFirstName(); + + if (firstName == null || "null".equalsIgnoreCase(firstName) || firstName.trim().isEmpty()) { + throw restErrorUtil.createRESTException("Please provide a valid first name.", MessageEnums.INVALID_INPUT_DATA); + } + + checkAccess(vXUser); + + xaBizUtil.blockAuditorRoleUser(); + + VXPortalUser oldUserProfile = userMgr.getUserProfileByLoginId(vXUser.getName()); + + if (oldUserProfile == null) { + throw restErrorUtil.createRESTException("user " + vXUser.getName() + " does not exist.", MessageEnums.INVALID_INPUT_DATA); + } + + VXPortalUser vXPortalUser = new VXPortalUser(); + + if (oldUserProfile.getId() != null) { + vXPortalUser.setId(oldUserProfile.getId()); + } + + vXPortalUser.setFirstName(vXUser.getFirstName()); + + if ("null".equalsIgnoreCase(vXPortalUser.getFirstName())) { + vXPortalUser.setFirstName(""); + } + + vXPortalUser.setLastName(vXUser.getLastName()); + + if ("null".equalsIgnoreCase(vXPortalUser.getLastName())) { + vXPortalUser.setLastName(""); + } + + vXPortalUser.setEmailAddress(vXUser.getEmailAddress()); + vXPortalUser.setLoginId(vXUser.getName()); + vXPortalUser.setStatus(vXUser.getStatus()); + vXPortalUser.setUserRoleList(vXUser.getUserRoleList()); + + if (vXPortalUser.getFirstName() != null && vXPortalUser.getLastName() != null && !vXPortalUser.getFirstName().trim().isEmpty() && !vXPortalUser.getLastName().trim().isEmpty()) { + vXPortalUser.setPublicScreenName(vXPortalUser.getFirstName() + " " + vXPortalUser.getLastName()); + } else { + vXPortalUser.setPublicScreenName(vXUser.getName()); + } + + vXPortalUser.setUserSource(oldUserProfile.getUserSource()); + + String hiddenPasswordString = PropertiesUtil.getProperty("ranger.password.hidden", "*****"); + String password = vXUser.getPassword(); + + if (password != null && password.equals(hiddenPasswordString)) { + vXPortalUser.setPassword(oldUserProfile.getPassword()); + } else if (oldUserProfile.getUserSource() == RangerCommonEnums.USER_EXTERNAL && password != null) { + vXPortalUser.setPassword(oldUserProfile.getPassword()); + + logger.debug("User is trrying to change external user password which we are not allowing it to change"); + } else if (password != null) { + validatePassword(vXUser); + + vXPortalUser.setPassword(password); + } + + Collection groupIdList = vXUser.getGroupIdList(); + VXUser existing = xUserService.readResource(vXUser.getId()); + XXPortalUser xXPortalUser = userMgr.updateUserWithPass(vXPortalUser); + + //update permissions start + Collection roleListUpdatedProfile = new ArrayList<>(); + + if (oldUserProfile.getId() != null) { + if (vXUser.getUserRoleList() != null) { + Collection roleListOldProfile = oldUserProfile.getUserRoleList(); + Collection roleListNewProfile = vXUser.getUserRoleList(); + + if (roleListNewProfile != null && roleListOldProfile != null) { + for (String role : roleListNewProfile) { + if (role != null && !roleListOldProfile.contains(role)) { + roleListUpdatedProfile.add(role); + } + } + } + } + } + + if (!roleListUpdatedProfile.isEmpty()) { + vXPortalUser.setUserRoleList(roleListUpdatedProfile); + + List xuserPermissionList = daoManager.getXXUserPermission().findByUserPermissionId(vXPortalUser.getId()); + + if (xuserPermissionList != null && !xuserPermissionList.isEmpty()) { + for (XXUserPermission xXUserPermission : xuserPermissionList) { + if (xXUserPermission != null) { + try { + xUserPermissionService.deleteResource(xXUserPermission.getId()); + } catch (Exception e) { + logger.error(e.getMessage()); + } + } + } + } + + assignPermissionToUser(vXPortalUser, true); + } + + //update permissions end + Collection roleList = new ArrayList<>(); + + if (xXPortalUser != null) { + roleList = userMgr.getRolesForUser(xXPortalUser); + } + + if (roleList == null || roleList.isEmpty()) { + roleList = new ArrayList<>(); + + roleList.add(RangerConstants.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); + + if (oldUserProfile.getUserSource() == RangerCommonEnums.USER_APP) { + vXUser.setPassword(password); + } else if (oldUserProfile.getUserSource() == RangerCommonEnums.USER_EXTERNAL) { + vXUser.setPassword(oldUserProfile.getPassword()); + } + + if (password == null) { + vXUser.setPassword(hiddenPasswordString); //To stop Auditing Password transaction log, when it is not edited. + } + + List trxLogList = xUserService.getTransactionLog(vXUser, existing, OPERATION_UPDATE_CONTEXT); + + vXUser.setPassword(hiddenPasswordString); + + Long userId = vXUser.getId(); + List groupUsersToRemove = new ArrayList<>(); + List groupUserTrxLogs = createOrDelGrpUserWithUpdatedGrpId(vXUser, groupIdList, userId, groupUsersToRemove); + + if (CollectionUtils.isNotEmpty(groupUserTrxLogs)) { + if (trxLogList == null) { + trxLogList = new ArrayList<>(); + } + + trxLogList.addAll(groupUserTrxLogs); + } + + xaBizUtil.createTrxLog(trxLogList); + + updateUserStoreVersion("updateXUser(" + vXUser.getName() + ")"); + + return vXUser; + } + + public synchronized void deleteXUser(Long id, boolean force) { + checkAdminAccess(); + + xaBizUtil.blockAuditorRoleUser(); + + XXUserDao xXUserDao = daoManager.getXXUser(); + XXUser xXUser = xXUserDao.getById(id); + + if (xXUser == null) { + throw restErrorUtil.create404RESTException("Data Not Found for given Id", MessageEnums.DATA_NOT_FOUND, id, null, "readResource : No Object found with given id."); + } + + VXUser vXUser = xUserService.populateViewBean(xXUser); + + if (vXUser == null || StringUtils.isEmpty(vXUser.getName())) { + throw restErrorUtil.createRESTException("No user found with id=" + id); + } + + XXPortalUserDao xXPortalUserDao = daoManager.getXXPortalUser(); + XXPortalUser xXPortalUser = xXPortalUserDao.findByLoginId(vXUser.getName().trim()); + VXPortalUser vXPortalUser = null; + + if (xXPortalUser != null) { + vXPortalUser = xPortalUserService.populateViewBean(xXPortalUser); + } + + if (vXPortalUser == null || StringUtils.isEmpty(vXPortalUser.getLoginId())) { + throw restErrorUtil.createRESTException("No user found with id=" + id); + } + + logger.debug("Force delete status={} for user={}", force, vXUser.getName()); + + restrictSelfAccountDeletion(vXUser.getName().trim()); + + blockIfZoneUser(id); + + this.blockIfRoleUser(id); + + SearchCriteria searchCriteria = new SearchCriteria(); + + searchCriteria.addParam("xUserId", id); + + VXGroupUserList vxGroupUserList = searchXGroupUsers(searchCriteria); + + searchCriteria = new SearchCriteria(); + + searchCriteria.addParam("userId", id); + + VXPermMapList vXPermMapList = searchXPermMaps(searchCriteria); + + searchCriteria = new SearchCriteria(); + + searchCriteria.addParam("userId", id); + + VXAuditMapList vXAuditMapList = searchXAuditMaps(searchCriteria); + long xXPortalUserId = vXPortalUser.getId(); + XXAuthSessionDao xXAuthSessionDao = daoManager.getXXAuthSession(); + XXUserPermissionDao xXUserPermissionDao = daoManager.getXXUserPermission(); + XXPortalUserRoleDao xXPortalUserRoleDao = daoManager.getXXPortalUserRole(); + List xXAuthSessionIds = xXAuthSessionDao.getAuthSessionIdsByUserId(xXPortalUserId); + List xXUserPermissions = xXUserPermissionDao.findByUserPermissionId(xXPortalUserId); + List xXPortalUserRoles = xXPortalUserRoleDao.findByUserId(xXPortalUserId); + XXPolicyDao xXPolicyDao = daoManager.getXXPolicy(); + + logger.warn("Deleting User : {}", vXUser.getName()); + + if (force) { + //delete XXGroupUser mapping + XXGroupUserDao xGroupUserDao = daoManager.getXXGroupUser(); + + for (VXGroupUser groupUser : vxGroupUserList.getList()) { + if (groupUser != null) { + logger.warn("Removing user '{}' from group '{}'", vXUser.getName(), groupUser.getName()); + + xGroupUserDao.remove(groupUser.getId()); + } + } + + //delete XXPermMap records of user + XXPermMapDao xXPermMapDao = daoManager.getXXPermMap(); + + for (VXPermMap vXPermMap : vXPermMapList.getList()) { + if (vXPermMap != null) { + logger.warn("Deleting '{}' permission from policy ID='{}' for user '{}'", AppConstants.getLabelFor_XAPermType(vXPermMap.getPermType()), vXPermMap.getResourceId(), vXPermMap.getUserName()); + + xXPermMapDao.remove(vXPermMap.getId()); + } + } + + //delete XXAuditMap records of user + XXAuditMapDao xXAuditMapDao = daoManager.getXXAuditMap(); + + for (VXAuditMap vXAuditMap : vXAuditMapList.getList()) { + if (vXAuditMap != null) { + xXAuditMapDao.remove(vXAuditMap.getId()); + } + } + + //delete XXPortalUser references + xPortalUserService.updateXXPortalUserReferences(xXPortalUserId); + + if (CollectionUtils.isNotEmpty(xXAuthSessionIds)) { + logger.warn("Deleting {} login session records for user '{}'", xXAuthSessionIds.size(), vXPortalUser.getLoginId()); + + xXAuthSessionDao.deleteAuthSessionsByIds(xXAuthSessionIds); + } + + for (XXUserPermission xXUserPermission : xXUserPermissions) { + if (xXUserPermission != null) { + XXModuleDef xXModuleDef = daoManager.getXXModuleDef().findByModuleId(xXUserPermission.getModuleId()); + + if (xXModuleDef != null) { + logger.warn("Deleting '{}' module permission for user '{}'", xXModuleDef.getModule(), vXPortalUser.getLoginId()); + } + + xXUserPermissionDao.remove(xXUserPermission.getId()); + } + } + + for (XXPortalUserRole xXPortalUserRole : xXPortalUserRoles) { + if (xXPortalUserRole != null) { + logger.warn("Deleting '{}' role for user '{}'", xXPortalUserRole.getUserRole(), vXPortalUser.getLoginId()); + + xXPortalUserRoleDao.remove(xXPortalUserRole.getId()); + } + } + + //delete XXPolicyItemUserPerm records of user + List xXPolicyList = xXPolicyDao.findByUserId(id); + + for (XXPolicy xXPolicy : xXPolicyList) { + RangerPolicy rangerPolicy = policyService.getPopulatedViewObject(xXPolicy); + List policyItems = rangerPolicy.getPolicyItems(); + + removeUserGroupReferences(policyItems, vXUser.getName(), null); + rangerPolicy.setPolicyItems(policyItems); + + List denyPolicyItems = rangerPolicy.getDenyPolicyItems(); + + removeUserGroupReferences(denyPolicyItems, vXUser.getName(), null); + rangerPolicy.setDenyPolicyItems(denyPolicyItems); + + List allowExceptions = rangerPolicy.getAllowExceptions(); + + removeUserGroupReferences(allowExceptions, vXUser.getName(), null); + rangerPolicy.setAllowExceptions(allowExceptions); + + List denyExceptions = rangerPolicy.getDenyExceptions(); + + removeUserGroupReferences(denyExceptions, vXUser.getName(), null); + rangerPolicy.setDenyExceptions(denyExceptions); + + List dataMaskItems = rangerPolicy.getDataMaskPolicyItems(); + + removeUserGroupReferences(dataMaskItems, vXUser.getName(), null); + rangerPolicy.setDataMaskPolicyItems(dataMaskItems); + + List rowFilterItems = rangerPolicy.getRowFilterPolicyItems(); + + removeUserGroupReferences(rowFilterItems, vXUser.getName(), null); + rangerPolicy.setRowFilterPolicyItems(rowFilterItems); + + try { + if (StringUtils.equals(rangerPolicy.getServiceType(), EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_GDS_NAME)) { + Map resources = rangerPolicy.getResources(); + + if (MapUtils.isEmpty(resources)) { + continue; + } + + if (resources.containsKey(GdsDBStore.RESOURCE_NAME_DATASET_ID)) { + RangerPolicyResource policyRes = resources.get(GdsDBStore.RESOURCE_NAME_DATASET_ID); + List resValues = policyRes != null ? policyRes.getValues() : null; + + if (CollectionUtils.isNotEmpty(resValues)) { + gdsStore.updateDatasetPolicy(Long.valueOf(resValues.get(0)), rangerPolicy); + } + } else if (resources.containsKey(GdsDBStore.RESOURCE_NAME_PROJECT_ID)) { + RangerPolicyResource policyRes = resources.get(GdsDBStore.RESOURCE_NAME_PROJECT_ID); + List resValues = policyRes != null ? policyRes.getValues() : null; + + if (CollectionUtils.isNotEmpty(resValues)) { + gdsStore.updateProjectPolicy(Long.valueOf(resValues.get(0)), rangerPolicy); + } + } + } else { + svcStore.updatePolicy(rangerPolicy); + } + } catch (Throwable excp) { + logger.error("updatePolicy({}) failed", rangerPolicy, excp); + + throw restErrorUtil.createRESTException(excp.getMessage()); + } + } + + //delete user from audit filter configs + svcStore.updateServiceAuditConfig(vXUser.getName(), REMOVE_REF_TYPE.USER); + + //delete gdsObject mapping of user + gdsStore.deletePrincipalFromGdsAcl(REMOVE_REF_TYPE.USER.toString(), vXUser.getName()); + + //delete XXUser entry of user + xXUserDao.remove(id); + + //delete XXPortal entry of user + logger.warn("Deleting Portal User : {}", vXPortalUser.getLoginId()); + + xXPortalUserDao.remove(xXPortalUserId); + + xUserService.createTransactionLog(xUserService.populateViewBean(xXUser), null, OPERATION_DELETE_CONTEXT); + + xPortalUserService.createTransactionLog(xPortalUserService.populateViewBean(xXPortalUser), null, OPERATION_DELETE_CONTEXT); + } else { + boolean hasReferences = false; + List xXPolicyList = xXPolicyDao.findByUserId(id); + + if (vxGroupUserList != null && vxGroupUserList.getListSize() > 0) { + hasReferences = true; + } + + if (!hasReferences && xXPolicyList != null && !xXPolicyList.isEmpty()) { + hasReferences = true; + } + + if (!hasReferences && vXPermMapList != null && vXPermMapList.getListSize() > 0) { + hasReferences = true; + } + + if (!hasReferences && vXAuditMapList != null && vXAuditMapList.getListSize() > 0) { + hasReferences = true; + } + + if (!hasReferences && CollectionUtils.isNotEmpty(xXAuthSessionIds)) { + hasReferences = true; + } + + if (!hasReferences && xXUserPermissions != null && !xXUserPermissions.isEmpty()) { + hasReferences = true; + } + + if (!hasReferences && xXPortalUserRoles != null && !xXPortalUserRoles.isEmpty()) { + hasReferences = true; + } + + if (hasReferences) { + if (vXUser.getIsVisible() != RangerCommonEnums.IS_HIDDEN) { + logger.info("Updating visibility of user '{}' to Hidden!", vXUser.getName()); + + vXUser.setIsVisible(RangerCommonEnums.IS_HIDDEN); + + xUserService.updateResource(vXUser); + } + } else { + xPortalUserService.updateXXPortalUserReferences(xXPortalUserId); + + //delete XXUser entry of user + xXUserDao.remove(id); + + //delete XXPortal entry of user + logger.warn("Deleting Portal User : {}", vXPortalUser.getLoginId()); + + xXPortalUserDao.remove(xXPortalUserId); + + xUserService.createTransactionLog(xUserService.populateViewBean(xXUser), null, OPERATION_DELETE_CONTEXT); + + xPortalUserService.createTransactionLog(xPortalUserService.populateViewBean(xXPortalUser), null, OPERATION_DELETE_CONTEXT); + } + } + } + + @Override + public VXUserList searchXUsers(SearchCriteria searchCriteria) { + VXUserList vXUserList = new VXUserList(); + VXUser vXUserExactMatch = null; + + try { + VXUserList vXUserListSort = new VXUserList(); + + if (searchCriteria.getParamList() != null && searchCriteria.getParamList().get("name") != null) { + searchCriteria.setSortBy("name"); + + vXUserListSort = xUserService.searchXUsers(searchCriteria); + vXUserExactMatch = getXUserByUserName((String) searchCriteria.getParamList().get("name")); + } + + int vXUserExactMatchwithSearchCriteria = 0; + + if (vXUserExactMatch != null) { + vXUserListSort = xUserService.searchXUsers(searchCriteria); + + HashMap searchCriteriaParamList = searchCriteria.getParamList(); + + vXUserExactMatchwithSearchCriteria = 1; + + for (Map.Entry entry : searchCriteriaParamList.entrySet()) { + String caseKey = entry.getKey(); + + switch (caseKey.toLowerCase()) { + case "isvisible": + Integer isVisible = vXUserExactMatch.getIsVisible(); + + if (isVisible != null && !isVisible.equals(entry.getValue())) { + vXUserExactMatchwithSearchCriteria = -1; + } + break; + case "status": + Integer status = vXUserExactMatch.getStatus(); + + if (!status.equals(entry.getValue())) { + vXUserExactMatchwithSearchCriteria = -1; + } + break; + case "usersource": + Integer userSource = vXUserExactMatch.getUserSource(); + + if (!userSource.equals(entry.getValue())) { + vXUserExactMatchwithSearchCriteria = -1; + } + break; + case "emailaddress": + String email = (String) entry.getValue(); + + if (email != null && !email.equals(vXUserExactMatch.getEmailAddress())) { + vXUserExactMatchwithSearchCriteria = -1; + } + break; + case "userrole": + if (vXUserExactMatch.getUserRoleList() != null && !vXUserExactMatch.getUserRoleList().contains(entry.getValue())) { + vXUserExactMatchwithSearchCriteria = -1; + } + break; + case "userrolelist": + @SuppressWarnings("unchecked") + Collection userrolelist = (Collection) entry.getValue(); + + if (!CollectionUtils.isEmpty(userrolelist)) { + for (String role : userrolelist) { + if (vXUserExactMatch.getUserRoleList() != null && vXUserExactMatch.getUserRoleList().contains(role)) { + vXUserExactMatchwithSearchCriteria = 1; + break; + } else { + vXUserExactMatchwithSearchCriteria = -1; + } + } + } + break; + default: + logger.warn("XUserMgr.searchXUsers: unexpected searchCriteriaParam:{}", caseKey); + break; + } + + if (vXUserExactMatchwithSearchCriteria == -1) { + break; + } + } + } + + if (vXUserExactMatchwithSearchCriteria == 1) { + VXGroupList groups = getXUserGroups(vXUserExactMatch.getId()); + + if (groups.getListSize() > 0) { + Collection groupNameList = new ArrayList<>(); + Collection groupIdList = new ArrayList<>(); + + for (VXGroup group : groups.getList()) { + groupIdList.add(group.getId()); + + groupNameList.add(group.getName()); + } + + vXUserExactMatch.setGroupIdList(groupIdList); + vXUserExactMatch.setGroupNameList(groupNameList); + } + + List vXUsers = new ArrayList<>(); + + if (searchCriteria.getStartIndex() == 0) { + vXUsers.add(0, vXUserExactMatch); + } + + for (VXUser vxUser : vXUserListSort.getVXUsers()) { + if (vXUserExactMatch.getId() != null && vxUser != null) { + if (!vXUserExactMatch.getId().equals(vxUser.getId())) { + vXUsers.add(vxUser); + } + } + } + + vXUserList.setVXUsers(vXUsers); + vXUserList.setStartIndex(searchCriteria.getStartIndex()); + vXUserList.setResultSize(vXUserList.getVXUsers().size()); + vXUserList.setTotalCount(vXUserListSort.getTotalCount()); + vXUserList.setPageSize(searchCriteria.getMaxRows()); + vXUserList.setSortBy(searchCriteria.getSortBy()); + vXUserList.setSortType(searchCriteria.getSortType()); + } + } catch (Exception e) { + logger.error("Error getting the exact match of user =>{}", String.valueOf(e)); + } + + if (vXUserList.getVXUsers().isEmpty()) { + if (StringUtils.isBlank(searchCriteria.getSortBy())) { + searchCriteria.setSortBy("id"); + } + + vXUserList = xUserService.searchXUsers(searchCriteria); + } + + if (vXUserList != null && !hasAccessToModule(RangerConstants.MODULE_USER_GROUPS)) { + List vXUsers = new ArrayList<>(); + + if (vXUserList.getListSize() > 0) { + for (VXUser vXUser : vXUserList.getList()) { + vXUser = getMaskedVXUser(vXUser); + + vXUsers.add(vXUser); + } + + vXUserList.setVXUsers(vXUsers); + } + } + + return vXUserList; + } + + public VXGroupUser getXGroupUser(Long id) { + return xGroupUserService.readResourceWithOutLogin(id); + } + + public VXGroupUser createXGroupUser(VXGroupUser vXGroupUser) { + checkAdminAccess(); + + xaBizUtil.blockAuditorRoleUser(); + + vXGroupUser = xGroupUserService.createXGroupUserWithOutLogin(vXGroupUser); + + return vXGroupUser; + } + + public VXGroupUser updateXGroupUser(VXGroupUser vXGroupUser) { + checkAdminAccess(); + + xaBizUtil.blockAuditorRoleUser(); + + return super.updateXGroupUser(vXGroupUser); + } + + public void deleteXGroupUser(Long id, boolean force) { + checkAdminAccess(); + + xaBizUtil.blockAuditorRoleUser(); + + super.deleteXGroupUser(id, force); + } + + public void deleteXPermMap(Long id, boolean force) { + xaBizUtil.blockAuditorRoleUser(); + + if (force) { + XXPermMap xPermMap = daoManager.getXXPermMap().getById(id); + + if (xPermMap != null) { + if (xResourceService.readResource(xPermMap.getResourceId()) == null) { + throw restErrorUtil.createRESTException("Invalid Input Data - No resource found with Id: " + xPermMap.getResourceId(), MessageEnums.INVALID_INPUT_DATA); + } + } + + xPermMapService.deleteResource(id); + } else { + throw restErrorUtil.createRESTException("serverMsg.modelMgrBaseDeleteModel", MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY); + } + } + + public VXPermMapList searchXPermMaps(SearchCriteria searchCriteria) { + VXPermMapList returnList; + UserSessionBase currentUserSession = ContextUtil.getCurrentUserSession(); + + if (currentUserSession != null && currentUserSession.isUserAdmin()) { + returnList = super.searchXPermMaps(searchCriteria); + } else { + returnList = new VXPermMapList(); + + int startIndex = searchCriteria.getStartIndex(); + int pageSize = searchCriteria.getMaxRows(); + + searchCriteria.setStartIndex(0); + searchCriteria.setMaxRows(Integer.MAX_VALUE); + + List resultList = xPermMapService.searchXPermMaps(searchCriteria).getVXPermMaps(); + List adminPermResourceList = new ArrayList<>(); + + for (VXPermMap xXPermMap : resultList) { + XXResource xRes = daoManager.getXXResource().getById(xXPermMap.getResourceId()); + VXResponse vXResponse = msBizUtil.hasPermission(xResourceService.populateViewBean(xRes), AppConstants.XA_PERM_TYPE_ADMIN); + + if (vXResponse.getStatusCode() == VXResponse.STATUS_SUCCESS) { + adminPermResourceList.add(xXPermMap); + } + } + + if (!adminPermResourceList.isEmpty()) { + populatePageList(adminPermResourceList, startIndex, pageSize, returnList); + } + } + + return returnList; + } + + public VXLong getXPermMapSearchCount(SearchCriteria searchCriteria) { + VXPermMapList permMapList = xPermMapService.searchXPermMaps(searchCriteria); + VXLong vXLong = new VXLong(); + + vXLong.setValue(permMapList.getListSize()); + + return vXLong; + } + + public void deleteXAuditMap(Long id, boolean force) { + xaBizUtil.blockAuditorRoleUser(); + + if (force) { + XXAuditMap xAuditMap = daoManager.getXXAuditMap().getById(id); + + if (xAuditMap != null) { + if (xResourceService.readResource(xAuditMap.getResourceId()) == null) { + throw restErrorUtil.createRESTException("Invalid Input Data - No resource found with Id: " + xAuditMap.getResourceId(), MessageEnums.INVALID_INPUT_DATA); + } + } + + xAuditMapService.deleteResource(id); + } else { + throw restErrorUtil.createRESTException("serverMsg.modelMgrBaseDeleteModel", MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY); + } + } + + public VXAuditMapList searchXAuditMaps(SearchCriteria searchCriteria) { + VXAuditMapList returnList = new VXAuditMapList(); + UserSessionBase currentUserSession = ContextUtil.getCurrentUserSession(); + + // If user is system admin + if (currentUserSession != null && currentUserSession.isUserAdmin()) { + returnList = super.searchXAuditMaps(searchCriteria); + } else { + int startIndex = searchCriteria.getStartIndex(); + int pageSize = searchCriteria.getMaxRows(); + + searchCriteria.setStartIndex(0); + searchCriteria.setMaxRows(Integer.MAX_VALUE); + + List resultList = xAuditMapService.searchXAuditMaps(searchCriteria).getVXAuditMaps(); + List adminAuditResourceList = new ArrayList<>(); + + for (VXAuditMap xXAuditMap : resultList) { + XXResource xRes = daoManager.getXXResource().getById(xXAuditMap.getResourceId()); + VXResponse vXResponse = msBizUtil.hasPermission(xResourceService.populateViewBean(xRes), AppConstants.XA_PERM_TYPE_ADMIN); + + if (vXResponse.getStatusCode() == VXResponse.STATUS_SUCCESS) { + adminAuditResourceList.add(xXAuditMap); + } + } + + if (!adminAuditResourceList.isEmpty()) { + populatePageList(adminAuditResourceList, startIndex, pageSize, returnList); + } + } + + return returnList; + } + + public VXLong getXAuditMapSearchCount(SearchCriteria searchCriteria) { + VXAuditMapList auditMapList = xAuditMapService.searchXAuditMaps(searchCriteria); + VXLong vXLong = new VXLong(); + + vXLong.setValue(auditMapList.getListSize()); + + return vXLong; + } + + /** + * // 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) { + checkAdminAccess(); + + xaBizUtil.blockAuditorRoleUser(); + + 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 vXGroups = new ArrayList<>(); + + if (vXGroupUserList != null) { + List vXGroupUsers = vXGroupUserList.getList(); + Set groupIdList = new HashSet<>(); + + 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 Set getGroupsForUser(String userName) { + Set ret = new HashSet<>(); + + try { + VXUser user = getXUserByUserName(userName); + + if (user != null) { + VXGroupList groups = getXUserGroups(user.getId()); + + if (groups != null && !CollectionUtils.isEmpty(groups.getList())) { + for (VXGroup group : groups.getList()) { + ret.add(group.getName()); + } + } else { + logger.debug("getGroupsForUser('{}'): no groups found for user", userName); + } + } else { + logger.debug("getGroupsForUser('{}'): user not found", userName); + } + } catch (Exception excp) { + logger.error("getGroupsForUser('{}') failed", userName, excp); + } + + return ret; + } + + public VXUserList getXGroupUsers(SearchCriteria searchCriteria) { + if (!msBizUtil.hasModuleAccess(RangerConstants.MODULE_USER_GROUPS)) { + throw restErrorUtil.createRESTException(HttpServletResponse.SC_FORBIDDEN, "User is not having permissions on the " + RangerConstants.MODULE_USER_GROUPS + " module.", true); + } + + VXUserList vXUserList = new VXUserList(); + VXGroupUserList vXGroupUserList = xGroupUserService.searchXGroupUsers(searchCriteria); + List vXUsers = new ArrayList<>(); + + if (vXGroupUserList != null) { + List vXGroupUsers = vXGroupUserList.getList(); + Set userIdList = new HashSet<>(); + + for (VXGroupUser vXGroupUser : vXGroupUsers) { + userIdList.add(vXGroupUser.getUserId()); + } + + for (Long userId : userIdList) { + VXUser vXUser = xUserService.readResource(userId); + + vXUsers.add(vXUser); + } + + vXUserList.setVXUsers(vXUsers); + vXUserList.setStartIndex(searchCriteria.getStartIndex()); + vXUserList.setResultSize(vXGroupUserList.getList().size()); + vXUserList.setTotalCount(vXGroupUserList.getTotalCount()); + vXUserList.setPageSize(searchCriteria.getMaxRows()); + vXUserList.setSortBy(vXGroupUserList.getSortBy()); + vXUserList.setSortType(vXGroupUserList.getSortType()); + } else { + logger.debug("No users found for group id : {}", searchCriteria.getParamValue("xGroupId")); + } + + return vXUserList; + } + + public void modifyUserVisibility(HashMap visibilityMap) { + checkAdminAccess(); + + xaBizUtil.blockAuditorRoleUser(); + + Set> entries = visibilityMap.entrySet(); + + for (Map.Entry entry : entries) { + XXUser xUser = daoManager.getXXUser().getById(entry.getKey()); + VXUser vObj = xUserService.populateViewBean(xUser); + + vObj.setIsVisible(entry.getValue()); + + xUserService.updateResource(vObj); + } + } + + public void modifyGroupsVisibility(HashMap groupVisibilityMap) { + checkAdminAccess(); + + xaBizUtil.blockAuditorRoleUser(); + + Set> entries = groupVisibilityMap.entrySet(); + + for (Map.Entry entry : entries) { + XXGroup xGroup = daoManager.getXXGroup().getById(entry.getKey()); + VXGroup vObj = xGroupService.populateViewBean(xGroup); + + vObj.setIsVisible(entry.getValue()); + + xGroupService.updateResource(vObj); + } + } + + // Module permissions + public VXModuleDef createXModuleDefPermission(VXModuleDef vXModuleDef) { + XXModuleDef xModDef = daoManager.getXXModuleDef().findByModuleName(vXModuleDef.getModule()); + + if (xModDef != null) { + throw restErrorUtil.createRESTException("Module Def with same name already exists.", MessageEnums.ERROR_DUPLICATE_OBJECT); + } + + return xModuleDefService.createResource(vXModuleDef); + } + + public VXModuleDef getXModuleDefPermission(Long id) { + return xModuleDefService.readResource(id); + } + + public VXModuleDef updateXModuleDefPermission(VXModuleDef vXModuleDef) { + List groupPermListNew = vXModuleDef.getGroupPermList(); + List userPermListNew = vXModuleDef.getUserPermList(); + XXModuleDef xModuleDef = daoManager.getXXModuleDef().getById(vXModuleDef.getId()); + + if (!StringUtils.equals(xModuleDef.getModule(), vXModuleDef.getModule())) { + throw restErrorUtil.createRESTException("Module name change is not allowed!", MessageEnums.DATA_NOT_UPDATABLE); + } + + Map xXPortalUserIdXXUserMap = xUserService.getXXPortalUserIdXXUserNameMap(); + Map xXGroupMap = xGroupService.getXXGroupIdNameMap(); + VXModuleDef vModuleDefPopulateOld = xModuleDefService.populateViewBean(xModuleDef, xXPortalUserIdXXUserMap, xXGroupMap, true); + + List groupPermListOld = vModuleDefPopulateOld.getGroupPermList(); + List userPermListOld = vModuleDefPopulateOld.getUserPermList(); + Map userPermMapOld = xUserPermissionService.convertVListToVMap(userPermListOld); + Map groupPermMapOld = xGroupPermissionService.convertVListToVMap(groupPermListOld); + + if (groupPermMapOld != null && groupPermListNew != null) { + for (VXGroupPermission newVXGroupPerm : groupPermListNew) { + boolean isExist = false; + VXGroupPermission oldVXGroupPerm = groupPermMapOld.get(newVXGroupPerm.getGroupId()); + + if (oldVXGroupPerm != null && newVXGroupPerm.getGroupId().equals(oldVXGroupPerm.getGroupId()) && newVXGroupPerm.getModuleId().equals(oldVXGroupPerm.getModuleId())) { + isExist = true; + + if (!newVXGroupPerm.getIsAllowed().equals(oldVXGroupPerm.getIsAllowed())) { + oldVXGroupPerm.setIsAllowed(newVXGroupPerm.getIsAllowed()); + + this.updateXGroupPermission(oldVXGroupPerm); + } + } + + if (!isExist) { + this.createXGroupPermission(newVXGroupPerm); + } + } + } + + if (userPermMapOld != null && userPermListNew != null) { + for (VXUserPermission newVXUserPerm : userPermListNew) { + boolean isExist = false; + VXUserPermission oldVXUserPerm = userPermMapOld.get(newVXUserPerm.getUserId()); + + if (oldVXUserPerm != null && newVXUserPerm.getUserId().equals(oldVXUserPerm.getUserId()) && newVXUserPerm.getModuleId().equals(oldVXUserPerm.getModuleId())) { + isExist = true; + + if (!newVXUserPerm.getIsAllowed().equals(oldVXUserPerm.getIsAllowed())) { + oldVXUserPerm.setIsAllowed(newVXUserPerm.getIsAllowed()); + + this.updateXUserPermission(oldVXUserPerm); + } + } + + if (!isExist) { + this.createXUserPermission(newVXUserPerm); + } + } + } + + vXModuleDef = xModuleDefService.updateResource(vXModuleDef); + + return vXModuleDef; + } + + public void deleteXModuleDefPermission(Long id, boolean force) { + daoManager.getXXUserPermission().deleteByModuleId(id); + daoManager.getXXGroupPermission().deleteByModuleId(id); + + xModuleDefService.deleteResource(id); + } + + // User permission + public VXUserPermission createXUserPermission(VXUserPermission vXUserPermission) { + vXUserPermission = xUserPermissionService.createResource(vXUserPermission); + + Set userSessions = sessionMgr.getActiveUserSessionsForPortalUserId(vXUserPermission.getUserId()); + + if (!CollectionUtils.isEmpty(userSessions)) { + for (UserSessionBase userSession : userSessions) { + logger.info("Assigning permission to user who's found logged in into system, so updating permission in session of that user: [{}]", vXUserPermission.getUserName()); + + sessionMgr.resetUserModulePermission(userSession); + } + } + + return vXUserPermission; + } + + public VXUserPermission getXUserPermission(Long id) { + return xUserPermissionService.readResource(id); + } + + public VXUserPermission updateXUserPermission(VXUserPermission vXUserPermission) { + vXUserPermission = xUserPermissionService.updateResource(vXUserPermission); + + Set userSessions = sessionMgr.getActiveUserSessionsForPortalUserId(vXUserPermission.getUserId()); + + if (!CollectionUtils.isEmpty(userSessions)) { + for (UserSessionBase userSession : userSessions) { + logger.info("Updating permission of user who's found logged in into system, so updating permission in session of user: [{}]", vXUserPermission.getUserName()); + + sessionMgr.resetUserModulePermission(userSession); + } + } + + return vXUserPermission; + } + + public void deleteXUserPermission(Long id, boolean force) { + XXUserPermission xUserPermission = daoManager.getXXUserPermission().getById(id); + + if (xUserPermission == null) { + throw restErrorUtil.createRESTException("No UserPermission found to delete, ID: " + id, MessageEnums.DATA_NOT_FOUND); + } + + xUserPermissionService.deleteResource(id); + + Set userSessions = sessionMgr.getActiveUserSessionsForPortalUserId(xUserPermission.getUserId()); + + if (!CollectionUtils.isEmpty(userSessions)) { + for (UserSessionBase userSession : userSessions) { + logger.info("deleting permission of user who's found logged in into system, so updating permission in session of that user"); + + sessionMgr.resetUserModulePermission(userSession); + } + } + } + + // Group permission + public VXGroupPermission createXGroupPermission(VXGroupPermission vXGroupPermission) { + vXGroupPermission = xGroupPermissionService.createResource(vXGroupPermission); + + List grpUsers = daoManager.getXXGroupUser().findByGroupId(vXGroupPermission.getGroupId()); + + for (XXGroupUser xGrpUser : grpUsers) { + Set userSessions = sessionMgr.getActiveUserSessionsForXUserId(xGrpUser.getUserId()); + + if (!CollectionUtils.isEmpty(userSessions)) { + for (UserSessionBase userSession : userSessions) { + logger.info("Assigning permission to group, one of the user belongs to that group found logged in into system, so updating permission in session of that user"); + + sessionMgr.resetUserModulePermission(userSession); + } + } + } + + return vXGroupPermission; + } + + public VXGroupPermission getXGroupPermission(Long id) { + return xGroupPermissionService.readResource(id); + } + + public VXGroupPermission updateXGroupPermission(VXGroupPermission vXGroupPermission) { + vXGroupPermission = xGroupPermissionService.updateResource(vXGroupPermission); + + List grpUsers = daoManager.getXXGroupUser().findByGroupId(vXGroupPermission.getGroupId()); + + for (XXGroupUser xGrpUser : grpUsers) { + Set userSessions = sessionMgr.getActiveUserSessionsForXUserId(xGrpUser.getUserId()); + + if (!CollectionUtils.isEmpty(userSessions)) { + for (UserSessionBase userSession : userSessions) { + logger.info("Assigning permission to group whose one of the user found logged in into system, so updating permission in session of that user"); + + sessionMgr.resetUserModulePermission(userSession); + } + } + } + + return vXGroupPermission; + } + + public void deleteXGroupPermission(Long id, boolean force) { + XXGroupPermission xGrpPerm = daoManager.getXXGroupPermission().getById(id); + + if (xGrpPerm == null) { + throw restErrorUtil.createRESTException("No GroupPermission object with ID: [" + id + "found.", MessageEnums.DATA_NOT_FOUND); + } + + xGroupPermissionService.deleteResource(id); + + List grpUsers = daoManager.getXXGroupUser().findByGroupId(xGrpPerm.getGroupId()); + + for (XXGroupUser xGrpUser : grpUsers) { + Set userSessions = sessionMgr.getActiveUserSessionsForXUserId(xGrpUser.getUserId()); + + if (!CollectionUtils.isEmpty(userSessions)) { + for (UserSessionBase userSession : userSessions) { + logger.info("deleting permission of the group whose one of the user found logged in into system, so updating permission in session of that user"); + + sessionMgr.resetUserModulePermission(userSession); + } + } + } + } + + public void modifyUserActiveStatus(HashMap statusMap) { + checkAdminAccess(); + + UserSessionBase session = ContextUtil.getCurrentUserSession(); + String currentUser = null; + + if (session != null) { + currentUser = session.getLoginId(); + + if (currentUser == null || currentUser.trim().isEmpty()) { + currentUser = null; + } + } + + if (currentUser == null) { + return; + } + + Set> entries = statusMap.entrySet(); + + for (Map.Entry entry : entries) { + if (entry != null && entry.getKey() != null && entry.getValue() != null) { + XXUser xUser = daoManager.getXXUser().getById(entry.getKey()); + + if (xUser != null) { + VXPortalUser vXPortalUser = userMgr.getUserProfileByLoginId(xUser.getName()); + + if (vXPortalUser != null) { + if (vXPortalUser.getLoginId() != null && !vXPortalUser.getLoginId().equalsIgnoreCase(currentUser)) { + vXPortalUser.setStatus(entry.getValue()); + + userMgr.updateUser(vXPortalUser); + } + } + } + } + } + } + + public void checkAdminAccess() { + UserSessionBase session = ContextUtil.getCurrentUserSession(); + + if (session != null) { + if (!session.isUserAdmin()) { + VXResponse vXResponse = new VXResponse(); + + vXResponse.setStatusCode(HttpServletResponse.SC_FORBIDDEN); + vXResponse.setMsgDesc("Operation" + " denied. LoggedInUser=" + session.getXXPortalUser().getId() + " ,isn't permitted to perform the action."); + + throw restErrorUtil.generateRESTException(vXResponse); + } + } else { + VXResponse vXResponse = new VXResponse(); + + vXResponse.setStatusCode(HttpServletResponse.SC_UNAUTHORIZED); // user is null + vXResponse.setMsgDesc("Bad Credentials"); + + throw restErrorUtil.generateRESTException(vXResponse); + } + } + + public void checkAccess(VXUser vxUser) { + UserSessionBase session = ContextUtil.getCurrentUserSession(); + + if (session != null) { + if (!hasAccessToGetUserInfo(vxUser)) { + throw restErrorUtil.create403RESTException("Operation" + " denied. LoggedInUser=" + session.getXXPortalUser().getId() + " ,isn't permitted to perform the action."); + } + } else { + VXResponse vXResponse = new VXResponse(); + + vXResponse.setStatusCode(HttpServletResponse.SC_UNAUTHORIZED); // user is null + vXResponse.setMsgDesc("Bad Credentials"); + + throw restErrorUtil.generateRESTException(vXResponse); + } + } + + public void checkAccessRoles(List stringRolesList) { + UserSessionBase session = ContextUtil.getCurrentUserSession(); + + if (session != null && stringRolesList != null) { + if (!session.isUserAdmin() && !session.isKeyAdmin()) { + throw restErrorUtil.create403RESTException("Permission denied. LoggedInUser=" + session.getXXPortalUser().getId() + " ,isn't permitted to perform the action."); + } else { + if (!"rangerusersync".equals(session.getXXPortalUser().getLoginId())) { // new logic for rangerusersync user + if (session.isUserAdmin() && (stringRolesList.contains(RangerConstants.ROLE_KEY_ADMIN) || stringRolesList.contains(RangerConstants.ROLE_KEY_ADMIN_AUDITOR))) { + throw restErrorUtil.create403RESTException("Permission denied. LoggedInUser=" + session.getXXPortalUser().getId() + " isn't permitted to perform the action."); + } else if (session.isKeyAdmin() && (stringRolesList.contains(RangerConstants.ROLE_SYS_ADMIN) || stringRolesList.contains(RangerConstants.ROLE_ADMIN_AUDITOR))) { + throw restErrorUtil.create403RESTException("Permission denied. LoggedInUser=" + session.getXXPortalUser().getId() + " isn't permitted to perform the action."); + } + } + } + } else { + VXResponse vXResponse = new VXResponse(); + + vXResponse.setStatusCode(HttpServletResponse.SC_UNAUTHORIZED); // user is null or role is null + vXResponse.setMsgDesc("Bad Credentials"); + + throw restErrorUtil.generateRESTException(vXResponse); + } + } + + public VXStringList setUserRolesByExternalID(Long userId, List vStringRolesList) { + xaBizUtil.blockAuditorRoleUser(); + + List roleListNewProfile = new ArrayList<>(); + + if (vStringRolesList != null) { + for (VXString vXString : vStringRolesList) { + roleListNewProfile.add(vXString.getValue()); + } + } + + VXUser vXUser = getXUser(userId); + + checkAccessRoles(roleListNewProfile); + + if (vXUser != null && !roleListNewProfile.isEmpty()) { + VXPortalUser oldUserProfile = userMgr.getUserProfileByLoginId(vXUser.getName()); + + if (oldUserProfile != null) { + denySelfRoleChange(oldUserProfile.getLoginId()); + updateUserRolesPermissions(oldUserProfile, roleListNewProfile); + + List portalUserRoleList = daoManager.getXXPortalUserRole().findByUserId(oldUserProfile.getId()); + + return getStringListFromUserRoleList(portalUserRoleList); + } else { + throw restErrorUtil.createRESTException("User ID doesn't exist.", MessageEnums.INVALID_INPUT_DATA); + } + } else { + throw restErrorUtil.createRESTException("User ID doesn't exist.", MessageEnums.INVALID_INPUT_DATA); + } + } + + public VXStringList setUserRolesByName(String userName, List vStringRolesList) { + xaBizUtil.blockAuditorRoleUser(); + + List roleListNewProfile = new ArrayList<>(); + + if (vStringRolesList != null) { + for (VXString vXString : vStringRolesList) { + roleListNewProfile.add(vXString.getValue()); + } + } + + VXUser vXUser = getXUserByUserName(userName); + + checkAccessRoles(roleListNewProfile); + + if (vXUser != null && !roleListNewProfile.isEmpty()) { + VXPortalUser oldUserProfile = userMgr.getUserProfileByLoginId(vXUser.getName()); + + if (oldUserProfile != null) { + denySelfRoleChange(oldUserProfile.getLoginId()); + updateUserRolesPermissions(oldUserProfile, roleListNewProfile); + + List portalUserRoleList = daoManager.getXXPortalUserRole().findByUserId(oldUserProfile.getId()); + + return getStringListFromUserRoleList(portalUserRoleList); + } else { + throw restErrorUtil.createRESTException("Login ID doesn't exist.", MessageEnums.INVALID_INPUT_DATA); + } + } else { + throw restErrorUtil.createRESTException("Login ID doesn't exist.", MessageEnums.INVALID_INPUT_DATA); + } + } + + public VXStringList getUserRolesByExternalID(Long userId) { + VXUser vXUser = getXUser(userId); + + if (vXUser == null) { + throw restErrorUtil.createRESTException("Please provide a valid ID", MessageEnums.INVALID_INPUT_DATA); + } + + checkAccess(vXUser); + + VXPortalUser oldUserProfile = userMgr.getUserProfileByLoginId(vXUser.getName()); + + if (oldUserProfile != null) { + List portalUserRoleList = daoManager.getXXPortalUserRole().findByUserId(oldUserProfile.getId()); + + return getStringListFromUserRoleList(portalUserRoleList); + } else { + throw restErrorUtil.createRESTException("User ID doesn't exist.", MessageEnums.INVALID_INPUT_DATA); + } + } + + public VXStringList getUserRolesByName(String userName) { + if (userName != null && !userName.trim().isEmpty()) { + VXUser vXUser = xUserService.getXUserByUserName(userName); + + checkAccess(vXUser); + + VXPortalUser vXPortalUser = userMgr.getUserProfileByLoginId(userName); + + if (vXPortalUser != null && vXPortalUser.getUserRoleList() != null) { + List portalUserRoleList = daoManager.getXXPortalUserRole().findByUserId(vXPortalUser.getId()); + + return getStringListFromUserRoleList(portalUserRoleList); + } else { + throw restErrorUtil.createRESTException("Please provide a valid userName", MessageEnums.INVALID_INPUT_DATA); + } + } else { + throw restErrorUtil.createRESTException("Please provide a valid userName", MessageEnums.INVALID_INPUT_DATA); + } + } + + public void updateUserRolesPermissions(VXPortalUser oldUserProfile, List roleListNewProfile) { + //update permissions start + Collection roleListUpdatedProfile = new ArrayList<>(); + + if (oldUserProfile != null && oldUserProfile.getId() != null) { + Collection roleListOldProfile = oldUserProfile.getUserRoleList(); + + if (roleListNewProfile != null && roleListOldProfile != null) { + for (String role : roleListNewProfile) { + if (role != null && !roleListOldProfile.contains(role)) { + roleListUpdatedProfile.add(role); + } + } + } + } + + if (!roleListUpdatedProfile.isEmpty()) { + oldUserProfile.setUserRoleList(roleListUpdatedProfile); + + List xuserPermissionList = daoManager.getXXUserPermission().findByUserPermissionId(oldUserProfile.getId()); + + if (xuserPermissionList != null && !xuserPermissionList.isEmpty()) { + for (XXUserPermission xXUserPermission : xuserPermissionList) { + if (xXUserPermission != null) { + xUserPermissionService.deleteResource(xXUserPermission.getId()); + } + } + } + + assignPermissionToUser(oldUserProfile, true); + + if (!roleListUpdatedProfile.isEmpty()) { + userMgr.updateRoles(oldUserProfile.getId(), oldUserProfile.getUserRoleList()); + } + } + //update permissions end + } + + public VXStringList getStringListFromUserRoleList(List listXXPortalUserRole) { + if (listXXPortalUserRole == null) { + return null; + } + + List xStrList = new ArrayList<>(); + + for (XXPortalUserRole userRole : listXXPortalUserRole) { + if (userRole != null) { + VXString vXStr = new VXString(); + + vXStr.setValue(userRole.getUserRole()); + xStrList.add(vXStr); + } + } + + return new VXStringList(xStrList); + } + + public boolean hasAccess(String loginID) { + UserSessionBase session = ContextUtil.getCurrentUserSession(); + + if (session != null) { + return session.isUserAdmin() || session.getLoginId().equalsIgnoreCase(loginID); + } + + return false; + } + + public VXUser getMaskedVXUser(VXUser vXUser) { + if (vXUser != null) { + if (vXUser.getGroupIdList() != null && !vXUser.getGroupIdList().isEmpty()) { + vXUser.setGroupIdList(new ArrayList<>()); + } + + if (vXUser.getGroupNameList() != null && !vXUser.getGroupNameList().isEmpty()) { + vXUser.setGroupNameList(getMaskedCollection(vXUser.getGroupNameList())); + } + + if (vXUser.getUserRoleList() != null && !vXUser.getUserRoleList().isEmpty()) { + vXUser.setUserRoleList(getMaskedCollection(vXUser.getUserRoleList())); + } + + vXUser.setUpdatedBy(AppConstants.Masked_String); + } + + return vXUser; + } + + public VXGroup getMaskedVXGroup(VXGroup vXGroup) { + if (vXGroup != null) { + vXGroup.setUpdatedBy(AppConstants.Masked_String); + } + + return vXGroup; + } + + public VXGroupList lookupXGroups(SearchCriteria searchCriteria) { + VXGroupList ret = null; + + try { + HashMap searchParams = searchCriteria.getParamList(); + String nameToLookFor = searchParams != null ? (String) searchParams.get("name") : null; + VXGroup exactMatch = null; + + if (StringUtils.isEmpty(searchCriteria.getSortBy())) { + searchCriteria.setSortBy(nameToLookFor != null ? "name" : "id"); + } + + if (nameToLookFor != null) { + exactMatch = getGroupByGroupName(nameToLookFor); + + for (Map.Entry entry : searchParams.entrySet()) { + if (exactMatch == null) { + break; + } + + String paramName = entry.getKey(); + Object paramValue = entry.getValue(); + + switch (paramName.toLowerCase()) { + case "isvisible": + if (!Objects.equals(exactMatch.getIsVisible(), paramValue)) { + exactMatch = null; + } + break; + + case "groupsource": + if (!Objects.equals(exactMatch.getGroupSource(), paramValue)) { + exactMatch = null; + } + break; + + default: + // ignore + break; + } + } + } + + VXGroupList searchResult = xGroupService.searchXGroups(searchCriteria); + + if (exactMatch != null && exactMatch.getId() != null) { + List groups = searchResult.getList(); + + if (!groups.isEmpty()) { // remove exactMatch from groups if it is present + boolean removed = false; + + for (Iterator iter = groups.iterator(); iter.hasNext(); ) { + VXGroup group = iter.next(); + + if (group != null && exactMatch.getId().equals(group.getId())) { + iter.remove(); + removed = true; + + break; + } + } + + if (!removed) { // remove the last entry, if exactMatch was not removed above - to accomodate for add() below + groups.remove(groups.size() - 1); + } + } + + groups.add(0, exactMatch); + + ret = new VXGroupList(groups); + + ret.setStartIndex(searchCriteria.getStartIndex()); + ret.setTotalCount(searchResult.getTotalCount()); + ret.setPageSize(searchCriteria.getMaxRows()); + ret.setSortBy(searchCriteria.getSortBy()); + ret.setSortType(searchCriteria.getSortType()); + } else { + ret = searchResult; + } + } catch (Exception e) { + logger.error("Error getting the exact match of group => {}", String.valueOf(e)); + } + + if (ret == null || ret.getList().isEmpty()) { + searchCriteria.setSortBy("id"); + + ret = xGroupService.searchXGroups(searchCriteria); + } + + if (ret != null && ret.getListSize() > 0 && !hasAccessToModule(RangerConstants.MODULE_USER_GROUPS)) { + for (VXGroup vXGroup : ret.getList()) { + getMaskedVXGroup(vXGroup); + } + } + + return ret; + } + + public Collection getMaskedCollection(Collection listunMasked) { + List listMasked = new ArrayList<>(); + + if (listunMasked != null) { + for (int i = 0; i < listunMasked.size(); i++) { + listMasked.add(AppConstants.Masked_String); + } + } + + return listMasked; + } + + public List getRangerPrincipals(SearchCriteria searchCriteria) { + String searchString = (String) searchCriteria.getParamValue("name"); + int startIdx = searchCriteria.getStartIndex(); + int maxRows = searchCriteria.getMaxRows(); + + return daoManager.getXXUser().lookupPrincipalByName(searchString, startIdx, maxRows); + } + + public boolean hasAccessToModule(String moduleName) { + UserSessionBase userSession = ContextUtil.getCurrentUserSession(); + + if (userSession != null && userSession.getLoginId() != null) { + VXUser vxUser = xUserService.getXUserByUserName(userSession.getLoginId()); + + if (vxUser != null) { + List permissionList = daoManager.getXXModuleDef().findAccessibleModulesByUserId(userSession.getUserId(), vxUser.getId()); + + return permissionList != null && permissionList.contains(moduleName); + } + } + + return false; + } + + public long forceDeleteExternalGroups(List groupIds) { + long groupsDeleted = 0; + long failedDeletes = 0; + long startTime = Time.now(); + + for (Long groupId : groupIds) { + TransactionTemplate txTemplate = new TransactionTemplate(txManager); + + txTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + try { + txTemplate.execute(status -> { + deleteXGroup(groupId, true); + return null; + }); + + groupsDeleted += 1; + } catch (Throwable ex) { + logger.error("forceDeleteExternalGroups(): Failed to delete group id: {}", groupId, ex); + + failedDeletes += 1; + } + } + + if (failedDeletes == 1) { + logger.error("Failed to delete 1 group"); + } else if (failedDeletes > 1) { + logger.error("Failed to delete {} groups", failedDeletes); + } + + if (groupIds.size() == 1) { + logger.info("Force Deletion of 1 group took {} milliseconds", (Time.now() - startTime)); + } else if (groupIds.size() > 1) { + logger.info("Force Deletion of {} groups took {} milliseconds", groupIds.size(), (Time.now() - startTime)); + } + + return groupsDeleted; + } + + public long forceDeleteExternalUsers(List userIds) { + long usersDeleted = 0; + long failedDeletes = 0; + long startTime = Time.now(); + + for (Long userId : userIds) { + TransactionTemplate txTemplate = new TransactionTemplate(txManager); + + txTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + + try { + txTemplate.execute(status -> { + deleteXUser(userId, true); + + return null; + }); + + usersDeleted += 1; + } catch (Throwable ex) { + logger.error("forceDeleteExternalUsers(): Failed to delete user id: {}", userId, ex); + + failedDeletes += 1; + } + } + + if (failedDeletes == 1) { + logger.error("Failed to delete 1 user"); + } else if (failedDeletes > 1) { + logger.error("Failed to delete {} users", failedDeletes); + } + + if (userIds.size() == 1) { + logger.info("Force Deletion of 1 user took {} milliseconds", (Time.now() - startTime)); + } else if (userIds.size() > 1) { + logger.info("Force Deletion of {} users took {} milliseconds", userIds.size(), (Time.now() - startTime)); + } + + return usersDeleted; + } + + public void restrictSelfAccountDeletion(String loginID) { + UserSessionBase session = ContextUtil.getCurrentUserSession(); + + if (session != null) { + if (!session.isUserAdmin()) { + VXResponse vXRes = new VXResponse(); + + vXRes.setStatusCode(HttpServletResponse.SC_FORBIDDEN); + vXRes.setMsgDesc("Operation denied. LoggedInUser= " + session.getXXPortalUser().getLoginId() + " isn't permitted to perform the action."); + + throw restErrorUtil.generateRESTException(vXRes); + } else { + if (StringUtils.isNotEmpty(loginID) && loginID.equals(session.getLoginId())) { + VXResponse vXResponse = new VXResponse(); + + vXResponse.setStatusCode(HttpServletResponse.SC_FORBIDDEN); + vXResponse.setMsgDesc("Operation denied. LoggedInUser= " + session.getXXPortalUser().getLoginId() + " isn't permitted to delete his own profile."); + + throw restErrorUtil.generateRESTException(vXResponse); + } + } + } else { + VXResponse vXResponse = new VXResponse(); + + vXResponse.setStatusCode(HttpServletResponse.SC_UNAUTHORIZED); // user is null + vXResponse.setMsgDesc("Bad Credentials"); + + throw restErrorUtil.generateRESTException(vXResponse); + } + } + + public VXUser createServiceConfigUser(String userName) { + if (userName == null || "null".equalsIgnoreCase(userName) || userName.trim().isEmpty()) { + logger.error("User Name: {}", userName); + + throw restErrorUtil.createRESTException("Please provide a valid username.", MessageEnums.INVALID_INPUT_DATA); + } + + XXUser xxUser = daoManager.getXXUser().findByUserName(userName); + + if (xxUser == null) { + transactionSynchronizationAdapter.executeOnTransactionCommit(new ExternalUserCreator(userName)); + } + + xxUser = daoManager.getXXUser().findByUserName(userName); + + VXUser vXUser = null; + + if (xxUser != null) { + vXUser = xUserService.populateViewBean(xxUser); + } + + return vXUser; + } + + public VXUser createServiceConfigUserSynchronously(String userName) { + if (userName == null || "null".equalsIgnoreCase(userName) || userName.trim().isEmpty()) { + logger.error("User Name: {}", userName); + + throw restErrorUtil.createRESTException("Please provide a valid username.", MessageEnums.INVALID_INPUT_DATA); + } + + VXUser vXUser = null; + XXUser xxUser = daoManager.getXXUser().findByUserName(userName); + + if (xxUser == null) { + ExternalUserCreator externalUserCreator = new ExternalUserCreator(userName); + + externalUserCreator.run(); + + xxUser = daoManager.getXXUser().findByUserName(userName); + } + + if (xxUser != null) { + vXUser = xUserService.populateViewBean(xxUser); + } + + return vXUser; + } + + public void denySelfRoleChange(String userName) { + UserSessionBase session = ContextUtil.getCurrentUserSession(); + + if (session != null && session.getXXPortalUser() != null) { + if (userName.equals(session.getXXPortalUser().getLoginId())) { + throw restErrorUtil.create403RESTException("Permission denied. LoggedInUser=" + session.getXXPortalUser().getId() + " ,isn't permitted to change its own role."); + } + } + } + + @Transactional(readOnly = false, propagation = Propagation.REQUIRED) + public synchronized VXUgsyncAuditInfo postUserGroupAuditInfo(VXUgsyncAuditInfo vxUgsyncAuditInfo) { + checkAdminAccess(); + + //logger.info("post usersync audit info"); + vxUgsyncAuditInfo = xUgsyncAuditInfoService.createUgsyncAuditInfo(vxUgsyncAuditInfo); + + return vxUgsyncAuditInfo; + } + + public Long getUserStoreVersion() { + return daoManager.getXXGlobalState().getAppDataVersion(RANGER_GLOBAL_STATE_NAME_USER_GROUP); + } + + public Set getUsers() { + return new HashSet<>(xUserService.getUsers()); + } + + public Set getGroups() { + return new HashSet<>(xGroupService.getGroups()); + } + + public Map> getUserGroups() { + return daoManager.getXXUser().findGroupsByUserIds(); + } + + public RangerUserStore getRangerUserStoreIfUpdated(Long lastKnownUserStoreVersion) { + logger.debug("==> XUserMgr.getRangerUserStoreIfUpdated(lastKnownUserStoreVersion={})", lastKnownUserStoreVersion); + + RangerUserStore ret = RangerUserStoreCache.getInstance().getLatestRangerUserStoreOrCached(this); + + if (ret != null && Objects.equals(ret.getUserStoreVersion(), lastKnownUserStoreVersion)) { + ret = null; + } + + logger.debug("<== XUserMgr.getRangerUserStoreIfUpdated(lastKnownUserStoreVersion={}): ret={}", lastKnownUserStoreVersion, ret); + + return ret; + } + + public int createOrUpdateXUsers(VXUserList users) { + logger.debug("==> createOrUpdateXUsers(): Started"); + + xaBizUtil.blockAuditorRoleUser(); + + int ret = 0; + + for (VXUser vXUser : users.getList()) { + final String userName = vXUser == null ? null : vXUser.getName(); + final String firstName = vXUser == null ? null : vXUser.getFirstName(); + + if (userName == null || "null".equalsIgnoreCase(userName) || userName.trim().isEmpty()) { + logger.warn("Ignoring user {}: invalid username", userName); + + continue; + } + + if (firstName == null || "null".equalsIgnoreCase(firstName) || firstName.trim().isEmpty()) { + logger.warn("Ignoring user {}: invalid firstName {}", userName, firstName); + + continue; + } + + checkAccess(vXUser); + + TransactionTemplate txTemplate = new TransactionTemplate(txManager); + + txTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + try { + txTemplate.execute(status -> { + VXPortalUser vXPortalUser = userMgr.getUserProfileByLoginId(userName); + + if (vXPortalUser == null) { + logger.debug("create user {}", userName); + + createXUser(vXUser, userName); + } else { + logger.debug("Update user {}", userName); + + updateXUser(vXUser, vXPortalUser); + } + + return null; + }); + } catch (Throwable ex) { + logger.error("XUserMgr.createOrUpdateXUsers(): Failed to update DB for users: ", ex); + + throw restErrorUtil.createRESTException("Failed to create or update users ", MessageEnums.ERROR_CREATING_OBJECT); + } + + ret++; + } + + if (ret == 0) { + logger.debug("<== createOrUpdateXUsers(): No users created or updated"); + + return ret; + } + + TransactionTemplate txTemplate = new TransactionTemplate(txManager); + + txTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + + try { + txTemplate.execute((TransactionCallback) status -> { + int noOfRetries = 0; + Exception failureException; + + do { + noOfRetries++; + + try { + daoManager.getXXGlobalState().onGlobalAppDataChange(RANGER_GLOBAL_STATE_NAME_USER_GROUP); + + logger.debug("createOrUpdateXGroups(): Successfully updated x_ranger_global_state table"); + + return null; + } catch (Exception excp) { + logger.warn("createOrUpdateXGroups(): Failed to update x_ranger_global_state table and retry count = {}", noOfRetries); + + failureException = excp; + } + } + while (noOfRetries <= MAX_DB_TRANSACTION_RETRIES); + + logger.error("createOrUpdateXGroups(): Failed to update x_ranger_global_state table after max retries", failureException); + + throw new RuntimeException(failureException); + }); + } catch (Throwable ex) { + logger.error("XUserMgr.createOrUpdateXUsers(): Failed to update DB for GlobalState table ", ex); + + throw restErrorUtil.createRESTException("Failed to create or update users ", MessageEnums.ERROR_CREATING_OBJECT); + } + + logger.debug("<== createOrUpdateXUsers(): Done"); + + return ret; + } + + @Transactional(readOnly = false, propagation = Propagation.REQUIRED) + public int createOrUpdateXGroups(VXGroupList groups) { + for (VXGroup vXGroup : groups.getList()) { + if (vXGroup == null || vXGroup.getName() == null || "null".equalsIgnoreCase(vXGroup.getName()) || vXGroup.getName().trim().isEmpty()) { + logger.warn("Ignoring invalid groupname {}", vXGroup == null ? null : vXGroup.getName()); + + continue; + } + + createXGroupWithoutLogin(vXGroup); + } + + updateUserStoreVersion("createOrUpdateXGroups(groupsCount=" + groups.getListSize() + ")"); + + return groups.getListSize(); + } + + public int createOrDeleteXGroupUserList(List groupUserInfoList) { + int updatedGroups = 0; + long mb = 1024L * 1024L; + + if (logger.isDebugEnabled()) { + logger.debug("==>> createOrDeleteXGroupUserList"); + logger.debug("Max memory = {} Free memory = {} Total memory = {}", Runtime.getRuntime().maxMemory() / mb, Runtime.getRuntime().freeMemory() / mb, Runtime.getRuntime().totalMemory() / mb); + } + + checkAdminAccess(); + + xaBizUtil.blockAuditorRoleUser(); + + if (CollectionUtils.isNotEmpty(groupUserInfoList)) { + logger.debug("No. of groups to be updated = {}", groupUserInfoList.size()); + + Map usersFromDB = daoManager.getXXUser().getAllUserIds(); + + if (MapUtils.isNotEmpty(usersFromDB)) { + if (logger.isDebugEnabled()) { + logger.debug("No. of users in DB = {}", usersFromDB.size()); + logger.debug("After users from DB - Max memory = {} Free memory = {} Total memory = {}", Runtime.getRuntime().maxMemory() / mb, Runtime.getRuntime().freeMemory() / mb, Runtime.getRuntime().totalMemory() / mb); + } + + for (GroupUserInfo groupUserInfo : groupUserInfoList) { + xGroupUserService.createOrDeleteXGroupUsers(groupUserInfo, usersFromDB); + } + + updatedGroups = groupUserInfoList.size(); + } + } + + if (logger.isDebugEnabled()) { + logger.debug("<<== createOrDeleteXGroupUserList"); + logger.debug("Max memory = {} Free memory = {} Total memory = {}", Runtime.getRuntime().maxMemory() / mb, Runtime.getRuntime().freeMemory() / mb, Runtime.getRuntime().totalMemory() / mb); + } + + return updatedGroups; + } + + @Transactional(readOnly = false, propagation = Propagation.REQUIRED) + public List updateUserRoleAssignments(UsersGroupRoleAssignments ugRoleAssignments) { + List updatedUsers = new ArrayList<>(); + List requestedUsers = ugRoleAssignments.getUsers(); + Map userMap = ugRoleAssignments.getUserRoleAssignments(); + Map groupMap = ugRoleAssignments.getGroupRoleAssignments(); + Map whiteListUserMap = ugRoleAssignments.getWhiteListUserRoleAssignments(); + Map whiteListGroupMap = ugRoleAssignments.getWhiteListGroupRoleAssignments(); + + logger.debug("Request users for role updates = {}", requestedUsers); + + // For each user get groups and compute roles based on group role assignments + for (String userName : requestedUsers) { + VXPortalUser vXPortalUser = userMgr.getUserProfileByLoginId(userName); + + if (vXPortalUser == null) { + logger.info("{} doesn't exist and hence ignoring role assignments", userName); + + continue; + } + + if (vXPortalUser.getUserSource() != RangerCommonEnums.USER_EXTERNAL) { + logger.info("{} is internal to ranger admin and hence ignoring role assignments", userName); + + continue; + } + + logger.debug("Computing role for {}", userName); + + Set groupUsers = getGroupsForUser(userName); + String userRole = RangerConstants.ROLE_USER; + + if (MapUtils.isNotEmpty(userMap) && userMap.containsKey(userName)) { + // Add the user role that is defined in user role assignments + userRole = userMap.get(userName); + } else if (MapUtils.isNotEmpty(groupMap) && CollectionUtils.isNotEmpty(groupUsers)) { + for (String group : groupMap.keySet()) { + if (groupUsers.contains(group)) { + String value = groupMap.get(group); + + if (value != null) { + userRole = value; + break; + } + } + } + } + + if (MapUtils.isNotEmpty(whiteListUserMap) && whiteListUserMap.containsKey(userName)) { + userRole = whiteListUserMap.get(userName); + } else if (MapUtils.isNotEmpty(whiteListGroupMap) && CollectionUtils.isNotEmpty(groupUsers)) { + for (String group : whiteListGroupMap.keySet()) { + if (groupUsers.contains(group)) { + String value = whiteListGroupMap.get(group); + + if (value != null) { + userRole = value; + break; + } + } + } + } + + if (!vXPortalUser.getUserRoleList().contains(userRole)) { + logger.debug("Updating role for {} to {}", userName, userRole); + + //Update the role of the user only if newly computed role is different from the existing role. + String updatedUser = setRolesByUserName(userName, Collections.singletonList(userRole)); + + if (updatedUser != null) { + updatedUsers.add(updatedUser); + } + } else { + logger.debug("Role for {} unchanged: {}", userName, userRole); + } + + if (ugRoleAssignments.isReset()) { // use below data structure only when reset is true + roleAssignmentUpdatedUsers.add(userName); + } + } + + // Reset the role of any other users that are not part of the updated role assignments rules + if (ugRoleAssignments.isReset() && ugRoleAssignments.isLastPage()) { + List externalUsersWithNonUserRole = daoManager.getXXPortalUser().getNonUserRoleExternalUsers(); + + logger.debug("Existing external users with roles excluding ROLE_USER role: {}", externalUsersWithNonUserRole); + + for (String userName : externalUsersWithNonUserRole) { + if (!roleAssignmentUpdatedUsers.contains(userName)) { + logger.debug("Resetting to ROLE_USER for {}", userName); + + String updatedUser = setRolesByUserName(userName, Collections.singletonList(RangerConstants.ROLE_USER)); + + if (updatedUser != null) { + updatedUsers.add(updatedUser); + } + } + } + + roleAssignmentUpdatedUsers.clear(); + } + + return updatedUsers; + } + + public int updateDeletedUsers(Set deletedUsers) { + for (String deletedUser : deletedUsers) { + XXUser xUser = daoManager.getXXUser().findByUserName(deletedUser); + + if (xUser != null) { + VXUser vObj = xUserService.populateViewBean(xUser); + + vObj.setIsVisible(RangerCommonEnums.IS_HIDDEN); + + xUserService.updateResource(vObj); + } + } + + return deletedUsers.size(); + } + + public int updateDeletedGroups(Set deletedGroups) { + for (String deletedGroup : deletedGroups) { + XXGroup xGroup = daoManager.getXXGroup().findByGroupName(deletedGroup); + + if (xGroup != null) { + VXGroup vObj = xGroupService.populateViewBean(xGroup); + + vObj.setIsVisible(RangerCommonEnums.IS_HIDDEN); + + xGroupService.updateResource(vObj); + } + } + + return deletedGroups.size(); + } + + public VXUserList lookupXUsers(SearchCriteria searchCriteria) { + VXUserList vXUserList = new VXUserList(); + + if (StringUtils.isBlank(searchCriteria.getSortBy())) { + searchCriteria.setSortBy("id"); + } + + vXUserList = xUserService.lookupXUsers(searchCriteria, vXUserList); + + return vXUserList; + } + + public Map getUserCountByRole() { + return daoManager.getXXPortalUser().getCountByUserRole(); + } + + protected 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; + } + + protected void updateXgroupUserForGroupUpdate(VXGroup vXGroup) { + List grpUsers = daoManager.getXXGroupUser().findByGroupId(vXGroup.getId()); + + if (CollectionUtils.isNotEmpty(grpUsers)) { + for (XXGroupUser grpUser : grpUsers) { + VXGroupUser vXGroupUser = xGroupUserService.populateViewBean(grpUser); + + vXGroupUser.setName(vXGroup.getName()); + + updateXGroupUser(vXGroupUser); + } + } + } + + protected void validatePassword(VXUser vXUser) { + if (vXUser.getPassword() != null && !vXUser.getPassword().isEmpty()) { + boolean checkPassword = vXUser.getPassword().trim().matches(StringUtil.VALIDATION_CRED); + + if (!checkPassword) { + logger.warn("validatePassword(). Password should be minimum 8 characters, at least one uppercase letter, one lowercase letter and one numeric."); + + throw restErrorUtil.createRESTException("serverMsg.xuserMgrValidatePassword", MessageEnums.INVALID_PASSWORD, null, "Password should be minimum 8 characters, at least one uppercase letter, one lowercase letter and one numeric.", null); + } + } else { + logger.warn("validatePassword(). Password cannot be blank/null."); + + throw restErrorUtil.createRESTException("serverMsg.xuserMgrValidatePassword", MessageEnums.INVALID_PASSWORD, null, "Password cannot be blank/null", null); + } + } + + private List createOrDelGrpUserWithUpdatedGrpId(VXUser vXUser, Collection groupIdList, Long userId, List groupUsersToRemove) { + Collection groupNamesSet = new HashSet<>(); + List trxLogList = new ArrayList<>(); + + if (groupIdList != null) { + SearchCriteria searchCriteria = new SearchCriteria(); + + searchCriteria.addParam("xUserId", userId); + + VXGroupUserList vXGroupUserList = xGroupUserService.searchXGroupUsers(searchCriteria); + List vXGroupUsers = vXGroupUserList.getList(); + + if (vXGroupUsers != null) { + for (VXGroupUser eachVXGrpUser : vXGroupUsers) { + groupNamesSet.add(eachVXGrpUser.getName()); + } + + // 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); + List groupUserTrxLogs = xGroupUserService.getTransactionLog(vXGroupUser, null, OPERATION_CREATE_CONTEXT); + + if (CollectionUtils.isNotEmpty(groupUserTrxLogs)) { + trxLogList.addAll(groupUserTrxLogs); + } + + groupNamesSet.add(vXGroupUser.getName()); + } + } + + // Delete + for (VXGroupUser vXGroupUser : vXGroupUsers) { + boolean found = false; + + for (Long groupId : groupIdList) { + if (groupId.equals(vXGroupUser.getParentGroupId())) { + List groupUserTrxLogs = xGroupUserService.getTransactionLog(vXGroupUser, null, OPERATION_UPDATE_CONTEXT); + + if (CollectionUtils.isNotEmpty(groupUserTrxLogs)) { + trxLogList.addAll(groupUserTrxLogs); + } + + found = true; + break; + } + } + + if (!found) { + // TODO I've to get the transaction log from here. + List groupUserTrxLogs = xGroupUserService.getTransactionLog(vXGroupUser, null, OPERATION_DELETE_CONTEXT); + + if (CollectionUtils.isNotEmpty(groupUserTrxLogs)) { + trxLogList.addAll(groupUserTrxLogs); + } + + groupUsersToRemove.add(vXGroupUser.getId()); + // xGroupUserService.deleteResource(vXGroupUser.getId()); + groupNamesSet.remove(vXGroupUser.getName()); + } + } + } else { + for (Long groupId : groupIdList) { + VXGroupUser vXGroupUser = createXGroupUser(userId, groupId); + List groupUserTrxLogs = xGroupUserService.getTransactionLog(vXGroupUser, null, OPERATION_CREATE_CONTEXT); + + if (CollectionUtils.isNotEmpty(groupUserTrxLogs)) { + trxLogList.addAll(groupUserTrxLogs); + } + + groupNamesSet.add(vXGroupUser.getName()); + } + } + + vXUser.setGroupIdList(groupIdList); + vXUser.setGroupNameList(new ArrayList<>(groupNamesSet)); + } else { + logger.debug("Group id list can't be null for user. Group user mapping not updated for user : {}", userId); + } + + for (Long groupUserId : groupUsersToRemove) { + xGroupUserService.deleteResource(groupUserId); + } + + return trxLogList; + } + + private boolean hasAccessToGetUserInfo(VXUser requestedVXUser) { + UserSessionBase userSession = ContextUtil.getCurrentUserSession(); + + if (userSession != null && userSession.getLoginId() != null) { + VXUser loggedInVXUser = xUserService.getXUserByUserName(userSession.getLoginId()); + + if (requestedVXUser != null && CollectionUtils.isNotEmpty(requestedVXUser.getUserRoleList()) && loggedInVXUser != null && loggedInVXUser.getUserRoleList().size() == 1) { + if (loggedInVXUser.getUserRoleList().contains(RangerConstants.ROLE_USER)) { + return requestedVXUser.getId().equals(loggedInVXUser.getId()); + } else if (loggedInVXUser.getUserRoleList().contains(RangerConstants.ROLE_KEY_ADMIN) || loggedInVXUser.getUserRoleList().contains(RangerConstants.ROLE_KEY_ADMIN_AUDITOR)) { + return requestedVXUser.getUserRoleList().contains(RangerConstants.ROLE_KEY_ADMIN) || requestedVXUser.getUserRoleList().contains(RangerConstants.ROLE_KEY_ADMIN_AUDITOR) || requestedVXUser.getUserRoleList().contains(RangerConstants.ROLE_USER); + } else if (loggedInVXUser.getUserRoleList().contains(RangerConstants.ROLE_SYS_ADMIN) || loggedInVXUser.getUserRoleList().contains(RangerConstants.ROLE_ADMIN_AUDITOR)) { + if (loggedInVXUser.getUserRoleList().contains(RangerConstants.ROLE_SYS_ADMIN) && "rangerusersync".equalsIgnoreCase(userSession.getLoginId())) { + return true; + } else { + return requestedVXUser.getUserRoleList().contains(RangerConstants.ROLE_SYS_ADMIN) || requestedVXUser.getUserRoleList().contains(RangerConstants.ROLE_ADMIN_AUDITOR) || requestedVXUser.getUserRoleList().contains(RangerConstants.ROLE_USER); + } + } + } + } + + return false; + } + + private void populatePageList(List permMapList, int startIndex, int pageSize, VXPermMapList vxPermMapList) { + List onePageList = new ArrayList<>(); + + for (int i = startIndex; i < pageSize + startIndex && i < permMapList.size(); i++) { + VXPermMap vXPermMap = permMapList.get(i); + + onePageList.add(vXPermMap); + } + + vxPermMapList.setVXPermMaps(onePageList); + vxPermMapList.setStartIndex(startIndex); + vxPermMapList.setPageSize(pageSize); + vxPermMapList.setResultSize(onePageList.size()); + vxPermMapList.setTotalCount(permMapList.size()); + } + + private void populatePageList(List auditMapList, int startIndex, int pageSize, VXAuditMapList vxAuditMapList) { + List onePageList = new ArrayList<>(); + + for (int i = startIndex; i < pageSize + startIndex && i < auditMapList.size(); i++) { + VXAuditMap vXAuditMap = auditMapList.get(i); + + onePageList.add(vXAuditMap); + } + + vxAuditMapList.setVXAuditMaps(onePageList); + vxAuditMapList.setStartIndex(startIndex); + vxAuditMapList.setPageSize(pageSize); + vxAuditMapList.setResultSize(onePageList.size()); + vxAuditMapList.setTotalCount(auditMapList.size()); + } + + private void blockIfZoneGroup(Long grpId) { + List zoneRefGrpList = daoManager.getXXSecurityZoneRefGroup().findByGroupId(grpId); + + if (CollectionUtils.isNotEmpty(zoneRefGrpList)) { + StringBuilder zones = new StringBuilder(); + + for (XXSecurityZoneRefGroup zoneRefGrp : zoneRefGrpList) { + XXSecurityZone xSecZone = daoManager.getXXSecurityZoneDao().getById(zoneRefGrp.getZoneId()); + + if (zones.indexOf(xSecZone.getName()) < 0) { + zones.append(xSecZone.getName()).append(","); + } + } + + this.prepareAndThrow(zoneRefGrpList.get(0).getGroupName(), RangerConstants.MODULE_SECURITY_ZONE, zones, GROUP); + } + } + + private void blockIfZoneUser(Long id) { + List zoneRefUserList = daoManager.getXXSecurityZoneRefUser().findByUserId(id); + + if (CollectionUtils.isNotEmpty(zoneRefUserList)) { + StringBuilder zones = new StringBuilder(); + + for (XXSecurityZoneRefUser zoneRefUser : zoneRefUserList) { + XXSecurityZone xSecZone = daoManager.getXXSecurityZoneDao().getById(zoneRefUser.getZoneId()); + + if (zones.indexOf(xSecZone.getName()) < 0) { + zones.append(xSecZone.getName()).append(","); + } + } + + this.prepareAndThrow(zoneRefUserList.get(0).getUserName(), RangerConstants.MODULE_SECURITY_ZONE, zones, USER); + } + } + + private void blockIfRoleUser(Long id) { + List roleRefUsers = this.daoManager.getXXRoleRefUser().findByUserId(id); + + if (CollectionUtils.isNotEmpty(roleRefUsers)) { + StringBuilder roles = new StringBuilder(); + + for (XXRoleRefUser roleRefUser : roleRefUsers) { + XXRole xxRole = this.daoManager.getXXRole().getById(roleRefUser.getRoleId()); + final String roleName = xxRole.getName(); + + if (roles.indexOf(roleName) < 0) { + roles.append(roleName).append(","); + } + } + + final String roleRefUserName = roleRefUsers.get(0).getUserName(); + + this.prepareAndThrow(roleRefUserName, RangerConstants.ROLE_FIELD, roles, USER); + } + } + + private void blockIfRoleGroup(Long id) { + List roleRefGroups = this.daoManager.getXXRoleRefGroup().findByGroupId(id); + + if (CollectionUtils.isNotEmpty(roleRefGroups)) { + StringBuilder roles = new StringBuilder(); + + for (XXRoleRefGroup roleRefGroup : roleRefGroups) { + XXRole xxRole = this.daoManager.getXXRole().getById(roleRefGroup.getRoleId()); + final String roleName = xxRole.getName(); + + if (roles.indexOf(roleName) < 0) { + roles.append(roleName).append(","); + } + } + + final String roleRefGroupName = roleRefGroups.get(0).getGroupName(); + + this.prepareAndThrow(roleRefGroupName, RangerConstants.ROLE_FIELD, roles, GROUP); + } + } + + private void prepareAndThrow(String userGrpName, String moduleName, StringBuilder rolesOrZones, String userOrGrp) { + logger.error("Can Not Delete {}:{}", userOrGrp, userGrpName); + + VXResponse vXResponse = new VXResponse(); + + vXResponse.setStatusCode(HttpServletResponse.SC_BAD_REQUEST); + vXResponse.setMsgDesc("Can Not Delete " + userOrGrp + ": '" + userGrpName + "' as its present in " + moduleName + " : " + rolesOrZones.deleteCharAt(rolesOrZones.length() - 1)); + + throw restErrorUtil.generateRESTException(vXResponse); + } + + private void removeUserGroupReferences(List policyItems, String user, String group) { + List itemsToRemove = null; + + for (T policyItem : policyItems) { + if (StringUtils.isNotEmpty(user)) { + policyItem.removeUser(user); + } + + if (StringUtils.isNotEmpty(group)) { + policyItem.removeGroup(group); + } + + if (policyItem.getUsers().isEmpty() && policyItem.getGroups().isEmpty() && policyItem.getRoles().isEmpty()) { + if (itemsToRemove == null) { + itemsToRemove = new ArrayList<>(); + } + + itemsToRemove.add(policyItem); + } + } + + if (CollectionUtils.isNotEmpty(itemsToRemove)) { + policyItems.removeAll(itemsToRemove); + } + } + + private void createXUser(VXUser vXUser, String username) { + logger.debug("Creating user: {}", username); + + VXPortalUser vXPortalUser = new VXPortalUser(); + + vXPortalUser.setLoginId(username); + vXPortalUser.setFirstName(vXUser.getFirstName()); + + if ("null".equalsIgnoreCase(vXPortalUser.getFirstName())) { + vXPortalUser.setFirstName(""); + } + + vXPortalUser.setLastName(vXUser.getLastName()); + + if ("null".equalsIgnoreCase(vXPortalUser.getLastName())) { + vXPortalUser.setLastName(""); + } + + String emailAddress = vXUser.getEmailAddress(); + + if (StringUtils.isNotEmpty(emailAddress) && !stringUtil.validateEmail(emailAddress)) { + logger.warn("Invalid email address:{}", emailAddress); + + throw restErrorUtil.createRESTException("Please provide valid email address.", MessageEnums.INVALID_INPUT_DATA); + } + + vXPortalUser.setEmailAddress(emailAddress); + + if (vXPortalUser.getFirstName() != null && vXPortalUser.getLastName() != null && !vXPortalUser.getFirstName().trim().isEmpty() && !vXPortalUser.getLastName().trim().isEmpty()) { + vXPortalUser.setPublicScreenName(vXPortalUser.getFirstName() + " " + vXPortalUser.getLastName()); + } else { + vXPortalUser.setPublicScreenName(vXUser.getName()); + } + + vXPortalUser.setStatus(RangerCommonEnums.STATUS_ENABLED); + vXPortalUser.setUserSource(RangerCommonEnums.USER_EXTERNAL); + + String saltEncodedpasswd = userMgr.encrypt(username, vXUser.getPassword()); + + vXPortalUser.setPassword(saltEncodedpasswd); + vXPortalUser.setUserRoleList(vXUser.getUserRoleList()); + + XXPortalUser user = userMgr.mapVXPortalUserToXXPortalUser(vXPortalUser); + + user = daoManager.getXXPortalUser().create(user); + + // Create the UserRole for this user + Collection userRoleList = vXUser.getUserRoleList(); + + if (userRoleList != null) { + for (String userRole : userRoleList) { + userMgr.addUserRole(user.getId(), userRole); + } + } + + XXUser xUser = daoManager.getXXUser().findByUserName(vXUser.getName()); + + if (xUser == null) { + vXUser = xUserService.createResource(vXUser); + } else { + vXUser = xUserService.populateViewBean(xUser); + } + + xUserService.createTransactionLog(vXUser, null, OPERATION_CREATE_CONTEXT); + + assignPermissionToUser(vXPortalUser.getUserRoleList(), vXPortalUser.getId(), vXUser.getId(), true); + + logger.debug("Done creating user: {}", username); + } + + private String setRolesByUserName(String userName, List roleListNewProfile) { + logger.debug("==> XUserMgr.setRolesByUserName({}, {})", userName, roleListNewProfile); + + String ret = null; + + xaBizUtil.blockAuditorRoleUser(); + + if (roleListNewProfile == null) { + roleListNewProfile = new ArrayList<>(); + } + + if (userName != null && !roleListNewProfile.isEmpty()) { + checkAccessRoles(roleListNewProfile); + + VXPortalUser oldUserProfile = userMgr.getUserProfileByLoginId(userName); + + if (oldUserProfile != null) { + denySelfRoleChange(oldUserProfile.getLoginId()); + updateUserRolesPermissions(oldUserProfile, roleListNewProfile); + + logger.info("<== XUserMgr.setRolesByUserName returned roles for {} are: {}", userName, roleListNewProfile); + + ret = userName; + } else { + logger.error("{}doesn't exist.", userName); + } + } else { + logger.error("{}doesn't exist or new role assignments are empty", userName); + } + + logger.debug("<== XUserMgr.setRolesByUserName({}, {}) ret = {}", userName, roleListNewProfile, ret); + + return ret; + } + + private void assignPermissionToUser(Collection vXPortalUserList, Long vXPortalUserId, Long xUserId, boolean isCreate) { + HashMap moduleNameId = getAllModuleNameAndIdMap(); + + if (moduleNameId != null && CollectionUtils.isNotEmpty(vXPortalUserList)) { + for (String role : vXPortalUserList) { + if (RangerConstants.VALID_USER_ROLE_LIST.contains(role)) { + createOrUpdateUserPermisson(vXPortalUserId, xUserId, moduleNameId.get(RangerConstants.MODULE_RESOURCE_BASED_POLICIES), isCreate); + createOrUpdateUserPermisson(vXPortalUserId, xUserId, moduleNameId.get(RangerConstants.MODULE_REPORTS), isCreate); + + if (role.equals(RangerConstants.ROLE_USER)) { + createOrUpdateUserPermisson(vXPortalUserId, xUserId, moduleNameId.get(RangerConstants.MODULE_SECURITY_ZONE), isCreate); + } else { + createOrUpdateUserPermisson(vXPortalUserId, xUserId, moduleNameId.get(RangerConstants.MODULE_AUDIT), isCreate); + createOrUpdateUserPermisson(vXPortalUserId, xUserId, moduleNameId.get(RangerConstants.MODULE_USER_GROUPS), isCreate); + + if (role.equals(RangerConstants.ROLE_SYS_ADMIN) || role.equals(RangerConstants.ROLE_ADMIN_AUDITOR)) { + createOrUpdateUserPermisson(vXPortalUserId, xUserId, moduleNameId.get(RangerConstants.MODULE_TAG_BASED_POLICIES), isCreate); + createOrUpdateUserPermisson(vXPortalUserId, xUserId, moduleNameId.get(RangerConstants.MODULE_SECURITY_ZONE), isCreate); + } else { + createOrUpdateUserPermisson(vXPortalUserId, xUserId, moduleNameId.get(RangerConstants.MODULE_KEY_MANAGER), isCreate); + } + } + } + } + } + } + + private void createOrUpdateUserPermisson(Long portalUserId, Long xUserId, Long moduleId, boolean isCreate) { + VXUserPermission vXUserPermission; + XXUserPermission xUserPermission = daoManager.getXXUserPermission().findByModuleIdAndPortalUserId(portalUserId, moduleId); + + if (xUserPermission == null) { + vXUserPermission = new VXUserPermission(); + + // When Creating XXUserPermission UI sends xUserId, to keep it consistent here xUserId should be used + vXUserPermission.setUserId(xUserId); + vXUserPermission.setIsAllowed(RangerCommonEnums.IS_ALLOWED); + vXUserPermission.setModuleId(moduleId); + + try { + vXUserPermission = this.createXUserPermission(vXUserPermission); + + logger.info("Permission assigned to user: [{}] For Module: [{}]", vXUserPermission.getUserName(), vXUserPermission.getModuleName()); + } catch (Exception e) { + logger.error("Error while assigning permission to user: [{}] for module: [{}]", portalUserId, moduleId, e); + } + } else if (isCreate) { + vXUserPermission = xUserPermissionService.populateViewBean(xUserPermission); + + vXUserPermission.setIsAllowed(RangerCommonEnums.IS_ALLOWED); + + vXUserPermission = this.updateXUserPermission(vXUserPermission); + + logger.info("Permission Updated for user: [{}] For Module: [{}]", vXUserPermission.getUserName(), vXUserPermission.getModuleName()); + } + } + + private VXUser updateXUser(VXUser vXUser, VXPortalUser oldUserProfile) { + logger.debug("Updating user: {}", vXUser.getName()); + + VXPortalUser vXPortalUser = new VXPortalUser(); + + if (oldUserProfile != null && oldUserProfile.getId() != null) { + vXPortalUser.setId(oldUserProfile.getId()); + } + + vXPortalUser.setFirstName(vXUser.getFirstName()); + + if ("null".equalsIgnoreCase(vXPortalUser.getFirstName())) { + vXPortalUser.setFirstName(""); + } + + vXPortalUser.setLastName(vXUser.getLastName()); + + if ("null".equalsIgnoreCase(vXPortalUser.getLastName())) { + vXPortalUser.setLastName(""); + } + + vXPortalUser.setEmailAddress(vXUser.getEmailAddress()); + vXPortalUser.setLoginId(vXUser.getName()); + vXPortalUser.setStatus(vXUser.getStatus()); + vXPortalUser.setUserRoleList(vXUser.getUserRoleList()); + + if (vXPortalUser.getFirstName() != null && vXPortalUser.getLastName() != null && !vXPortalUser.getFirstName().trim().isEmpty() && !vXPortalUser.getLastName().trim().isEmpty()) { + vXPortalUser.setPublicScreenName(vXPortalUser.getFirstName() + " " + vXPortalUser.getLastName()); + } else { + vXPortalUser.setPublicScreenName(vXUser.getName()); + } + + vXPortalUser.setUserSource(vXUser.getUserSource()); + vXPortalUser.setSyncSource(vXUser.getSyncSource()); + + String hiddenPasswordString = PropertiesUtil.getProperty("ranger.password.hidden", "*****"); + String password = vXUser.getPassword(); + + if (oldUserProfile != null && password != null && password.equals(hiddenPasswordString)) { + vXPortalUser.setPassword(oldUserProfile.getPassword()); + } else if (oldUserProfile != null && oldUserProfile.getUserSource() == RangerCommonEnums.USER_EXTERNAL && password != null) { + vXPortalUser.setPassword(oldUserProfile.getPassword()); + + logger.debug("User is trying to change external user password which we are not allowing it to change"); + } else if (password != null) { + validatePassword(vXUser); + vXPortalUser.setPassword(password); + } + + XXPortalUser xXPortalUser = userMgr.updateUserWithPass(vXPortalUser); + + //update permissions start + Collection roleListUpdatedProfile = new ArrayList<>(); + + if (oldUserProfile != null && oldUserProfile.getId() != null) { + if (vXUser.getUserRoleList() != null) { + Collection roleListOldProfile = oldUserProfile.getUserRoleList(); + Collection roleListNewProfile = vXUser.getUserRoleList(); + + if (roleListNewProfile != null && roleListOldProfile != null) { + for (String role : roleListNewProfile) { + if (role != null && !roleListOldProfile.contains(role)) { + roleListUpdatedProfile.add(role); + } + } + } + } + } + + if (!roleListUpdatedProfile.isEmpty()) { + vXPortalUser.setUserRoleList(roleListUpdatedProfile); + + List xuserPermissionList = daoManager.getXXUserPermission().findByUserPermissionId(vXPortalUser.getId()); + + if (xuserPermissionList != null && !xuserPermissionList.isEmpty()) { + for (XXUserPermission xXUserPermission : xuserPermissionList) { + if (xXUserPermission != null) { + try { + xUserPermissionService.deleteResource(xXUserPermission.getId()); + } catch (Exception e) { + logger.error(e.getMessage()); + } + } + } + } + } + + //update permissions end + Collection roleList = new ArrayList<>(); + + if (xXPortalUser != null) { + roleList = userMgr.getRolesForUser(xXPortalUser); + } + + if (roleList == null || roleList.isEmpty()) { + roleList = new ArrayList<>(); + + roleList.add(RangerConstants.ROLE_USER); + } + + // TODO I've to get the transaction log from here. + // There is nothing to log anything in XXUser so far. + XXUser xUser = daoManager.getXXUser().findByUserName(vXUser.getName()); + + if (xUser == null) { + logger.warn("Could not find corresponding xUser for username: [{}], So not updating this user", vXPortalUser.getLoginId()); + + return vXUser; + } + + VXUser existing = xUserService.populateViewBean(xUser); + + logger.info("xUser.getName() = {} vXUser.getName() = {}", xUser.getName(), vXUser.getName()); + + vXUser.setId(xUser.getId()); + + try { + vXUser = xUserService.updateResource(vXUser); + } catch (Exception ex) { + logger.warn("Failed to update username {}", vXUser.getName()); + logger.debug("Failed to update username {}", vXUser.getName(), ex); + } + + vXUser.setUserRoleList(roleList); + + if (oldUserProfile != null) { + if (oldUserProfile.getUserSource() == RangerCommonEnums.USER_APP) { + vXUser.setPassword(password); + } else if (oldUserProfile.getUserSource() == RangerCommonEnums.USER_EXTERNAL) { + vXUser.setPassword(oldUserProfile.getPassword()); + } + } + + List trxLogList = xUserService.getTransactionLog(vXUser, existing, OPERATION_UPDATE_CONTEXT); + + vXUser.setPassword(hiddenPasswordString); + + Long userId = vXUser.getId(); + + assignPermissionToUser(vXPortalUser.getUserRoleList(), vXPortalUser.getId(), userId, true); + + xaBizUtil.createTrxLog(trxLogList); + + logger.debug("Done updating user: {}", vXUser.getName()); + + return vXUser; + } + + private void updateUserStoreVersion(String label) { + try { + daoManager.getXXGlobalState().onGlobalAppDataChange(RANGER_GLOBAL_STATE_NAME_USER_GROUP); + } catch (Exception excp) { + logger.error("{}: userStore version update failed", label, excp); + } + } + + private class ExternalUserCreator implements Runnable { + private final String userName; + + ExternalUserCreator(String user) { + this.userName = user; + } + + @Override + public void run() { + createExternalUser(); + } + + private void createExternalUser() { + logger.debug("==> ExternalUserCreator.createExternalUser(username={}", userName); + + XXPortalUser xXPortalUser = daoManager.getXXPortalUser().findByLoginId(userName); + + if (xXPortalUser == null) { + logger.debug("createExternalUser(): Couldn't find {} and hence creating user in x_portal_user table", userName); + + VXPortalUser vXPortalUser = new VXPortalUser(); + + vXPortalUser.setLoginId(userName); + vXPortalUser.setUserSource(RangerCommonEnums.USER_EXTERNAL); + + ArrayList roleList = new ArrayList<>(); + + roleList.add(RangerConstants.ROLE_USER); + + vXPortalUser.setUserRoleList(roleList); + + xXPortalUser = userMgr.mapVXPortalUserToXXPortalUser(vXPortalUser); + + try { + xXPortalUser = userMgr.createUser(xXPortalUser, RangerCommonEnums.STATUS_ENABLED, roleList); + + logger.debug("createExternalUser(): Successfully created user in x_portal_user table {}", xXPortalUser.getLoginId()); + } catch (Exception ex) { + throw new RuntimeException("Failed to create user " + userName + " in x_portal_user table. retrying", ex); + } + } + + VXUser createdXUser = null; + String actualPassword = ""; + XXUser xXUser = daoManager.getXXUser().findByUserName(userName); + + if (xXUser == null) { + VXUser vXUser = new VXUser(); + + vXUser.setName(userName); + vXUser.setUserSource(RangerCommonEnums.USER_EXTERNAL); + vXUser.setDescription(vXUser.getName()); + + actualPassword = vXUser.getPassword(); + + try { + createdXUser = xUserService.createResource(vXUser); + + logger.debug("createExternalUser(): Successfully created user in x_user table {}", vXUser.getName()); + } catch (Exception ex) { + throw new RuntimeException("Failed to create user " + userName + " in x_user table. retrying", ex); + } + } + + if (createdXUser != null) { + logger.info("User created: {}", createdXUser.getName()); + + try { + createdXUser.setPassword(actualPassword); + + xUserService.createTransactionLog(createdXUser, null, OPERATION_CREATE_CONTEXT); + + String hiddenPassword = PropertiesUtil.getProperty("ranger.password.hidden", "*****"); + + createdXUser.setPassword(hiddenPassword); + } catch (Exception ex) { + throw new RuntimeException("Error while creating trx logs for user: " + createdXUser.getName(), ex); + } + + try { + VXPortalUser createdXPortalUser = userMgr.mapXXPortalUserToVXPortalUserForDefaultAccount(xXPortalUser); + + assignPermissionToUser(createdXPortalUser, true); + } catch (Exception ex) { + throw new RuntimeException("Error while assigning permissions to user: " + createdXUser.getName(), ex); + } + } + + logger.debug("<== ExternalUserCreator.createExternalUser(username={}", userName); + } + } } 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 index 5f95ef733d..d3bb1f6c99 100644 --- a/security-admin/src/main/java/org/apache/ranger/biz/XUserMgrBase.java +++ b/security-admin/src/main/java/org/apache/ranger/biz/XUserMgrBase.java @@ -17,7 +17,7 @@ * under the License. */ - package org.apache.ranger.biz; +package org.apache.ranger.biz; import org.apache.ranger.common.MessageEnums; import org.apache.ranger.common.RESTErrorUtil; @@ -39,233 +39,227 @@ import org.apache.ranger.view.VXGroupUserList; import org.apache.ranger.view.VXLong; import org.apache.ranger.view.VXModuleDefList; +import org.apache.ranger.view.VXModulePermissionList; import org.apache.ranger.view.VXPermMap; import org.apache.ranger.view.VXPermMapList; import org.apache.ranger.view.VXUser; -import org.apache.ranger.view.VXModulePermissionList; import org.apache.ranger.view.VXUserList; import org.apache.ranger.view.VXUserPermissionList; import org.springframework.beans.factory.annotation.Autowired; + public class XUserMgrBase { + @Autowired + RESTErrorUtil restErrorUtil; + + @Autowired + XGroupService xGroupService; + + @Autowired + XUserService xUserService; + + @Autowired + XGroupUserService xGroupUserService; + + @Autowired + XPermMapService xPermMapService; + + @Autowired + XModuleDefService xModuleDefService; + + @Autowired + XUserPermissionService xUserPermissionService; + + @Autowired + XGroupPermissionService xGroupPermissionService; + + @Autowired + XAuditMapService xAuditMapService; + + public VXGroup getXGroup(Long id) { + return xGroupService.readResource(id); + } + + public VXGroup createXGroup(VXGroup vXGroup) { + vXGroup = xGroupService.createResource(vXGroup); + + return vXGroup; + } + + public VXGroup updateXGroup(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 xUserService.readResource(id); + } + + public VXUser createXUser(VXUser vXUser) { + vXUser = xUserService.createResource(vXUser); + + return vXUser; + } + + public VXUser updateXUser(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 xGroupUserService.readResource(id); + } + + public VXGroupUser createXGroupUser(VXGroupUser vXGroupUser) { + vXGroupUser = xGroupUserService.createResource(vXGroupUser); + + return vXGroupUser; + } + + public VXGroupUser updateXGroupUser(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 VXPermMap getXPermMap(Long id) { + return xPermMapService.readResource(id); + } + + public VXPermMap createXPermMap(VXPermMap vXPermMap) { + vXPermMap = xPermMapService.createResource(vXPermMap); + + return vXPermMap; + } + + public VXPermMap updateXPermMap(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 xAuditMapService.readResource(id); + } + + public VXAuditMap createXAuditMap(VXAuditMap vXAuditMap) { + vXAuditMap = xAuditMapService.createResource(vXAuditMap); + + return vXAuditMap; + } + + public VXAuditMap updateXAuditMap(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); + } + + public VXModuleDefList searchXModuleDef(SearchCriteria searchCriteria) { + return xModuleDefService.searchModuleDef(searchCriteria); + } + + public VXModulePermissionList searchXModuleDefList(SearchCriteria searchCriteria) { + return xModuleDefService.searchModuleDefList(searchCriteria); + } - @Autowired - RESTErrorUtil restErrorUtil; - - @Autowired - XGroupService xGroupService; - - @Autowired - XUserService xUserService; - - @Autowired - XGroupUserService xGroupUserService; - - @Autowired - XPermMapService xPermMapService; - - @ Autowired - XModuleDefService xModuleDefService; - - @ Autowired - XUserPermissionService xUserPermissionService; - - @ Autowired - XGroupPermissionService xGroupPermissionService; - - @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 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); - } - - public VXModuleDefList searchXModuleDef(SearchCriteria searchCriteria) { - return xModuleDefService.searchModuleDef(searchCriteria); - } - public VXModulePermissionList searchXModuleDefList(SearchCriteria searchCriteria) { - return xModuleDefService.searchModuleDefList(searchCriteria); - } - - public VXUserPermissionList searchXUserPermission(SearchCriteria searchCriteria) { - return xUserPermissionService.searchXUserPermission(searchCriteria); - } - - public VXGroupPermissionList searchXGroupPermission(SearchCriteria searchCriteria) { - return xGroupPermissionService.searchXGroupPermission(searchCriteria); - } - - public VXLong getXModuleDefSearchCount(SearchCriteria searchCriteria) { - return xModuleDefService.getSearchCount(searchCriteria, - xModuleDefService.searchFields); - } - - public VXLong getXUserPermissionSearchCount(SearchCriteria searchCriteria) { - return xUserPermissionService.getSearchCount(searchCriteria, - xUserPermissionService.searchFields); - } - - public VXLong getXGroupPermissionSearchCount(SearchCriteria searchCriteria){ - return xGroupPermissionService.getSearchCount(searchCriteria, - xGroupPermissionService.searchFields); - } + public VXUserPermissionList searchXUserPermission(SearchCriteria searchCriteria) { + return xUserPermissionService.searchXUserPermission(searchCriteria); + } + + public VXGroupPermissionList searchXGroupPermission(SearchCriteria searchCriteria) { + return xGroupPermissionService.searchXGroupPermission(searchCriteria); + } + + public VXLong getXModuleDefSearchCount(SearchCriteria searchCriteria) { + return xModuleDefService.getSearchCount(searchCriteria, xModuleDefService.searchFields); + } + + public VXLong getXUserPermissionSearchCount(SearchCriteria searchCriteria) { + return xUserPermissionService.getSearchCount(searchCriteria, xUserPermissionService.searchFields); + } + + public VXLong getXGroupPermissionSearchCount(SearchCriteria searchCriteria) { + return xGroupPermissionService.getSearchCount(searchCriteria, xGroupPermissionService.searchFields); + } } diff --git a/security-admin/src/main/java/org/apache/ranger/service/RangerRoleService.java b/security-admin/src/main/java/org/apache/ranger/service/RangerRoleService.java index bc91560850..e9388e2b06 100644 --- a/security-admin/src/main/java/org/apache/ranger/service/RangerRoleService.java +++ b/security-admin/src/main/java/org/apache/ranger/service/RangerRoleService.java @@ -175,7 +175,6 @@ private void updateRoleVersions(Set roleIds) { if (CollectionUtils.isNotEmpty(allAffectedServiceIds)) { for (final Long serviceId : allAffectedServiceIds) { Runnable serviceVersionUpdater = new ServiceDBStore.ServiceVersionUpdater(daoMgr, serviceId, ServiceDBStore.VERSION_TYPE.ROLE_VERSION, null, RangerPolicyDelta.CHANGE_TYPE_ROLE_UPDATE, null); - daoMgr.getRangerTransactionSynchronizationAdapter().executeOnTransactionCommit(serviceVersionUpdater); XXService serviceDbObj = serviceDao.getById(serviceId); @@ -198,7 +197,6 @@ private void updateRoleVersionOfAllServicesRefferingTag(RangerDaoManager daoMana for (XXService referringService : referringServices) { final Long referringServiceId = referringService.getId(); Runnable roleVersionUpdater = new ServiceDBStore.ServiceVersionUpdater(daoManager, referringServiceId, ServiceDBStore.VERSION_TYPE.ROLE_VERSION, null, RangerPolicyDelta.CHANGE_TYPE_ROLE_UPDATE, null); - daoMgr.getRangerTransactionSynchronizationAdapter().executeOnTransactionCommit(roleVersionUpdater); } } diff --git a/security-admin/src/main/java/org/apache/ranger/util/CLIUtil.java b/security-admin/src/main/java/org/apache/ranger/util/CLIUtil.java index 0fd584761b..410079f611 100644 --- a/security-admin/src/main/java/org/apache/ranger/util/CLIUtil.java +++ b/security-admin/src/main/java/org/apache/ranger/util/CLIUtil.java @@ -17,6 +17,9 @@ * under the License. */ +/** + * + */ package org.apache.ranger.util; import org.apache.commons.lang.StringUtils; @@ -38,65 +41,59 @@ import java.util.Locale; +/** + * + */ @Component public class CLIUtil { - private static final Logger logger = LoggerFactory.getLogger(CLIUtil.class); - - private static final String JAVA_PATCHES_CLASS_NAME_PREFIX = "Patch"; - - @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(); - checkIfJavaPatchesExecuting(beanClass); - 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); - } - - public static String getMessage(String messagekey, HttpServletRequest request) { - ServletContext servletContext = request.getSession().getServletContext(); - ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(servletContext); - Object[] args = new Object[] {}; - - return ctx.getMessage(messagekey, args, Locale.getDefault()); - } - - private static void checkIfJavaPatchesExecuting(Class beanClass) { - if (beanClass != null) { - final String className = beanClass.getSimpleName(); - - if (StringUtils.isNotEmpty(className)) { - if (className.startsWith(JAVA_PATCHES_CLASS_NAME_PREFIX)) { - UserSessionBase userSessBase = new UserSessionBase(); - - userSessBase.setUserAdmin(true); - userSessBase.setAuditUserAdmin(true); - userSessBase.setKeyAdmin(true); - userSessBase.setAuditKeyAdmin(true); - - RangerSecurityContext rangerSecCtx = new RangerSecurityContext(); - - rangerSecCtx.setUserSession(userSessBase); - RangerContextHolder.setSecurityContext(rangerSecCtx); - } - } - } - } + private static final Logger logger = LoggerFactory.getLogger(CLIUtil.class); + private static final String JAVA_PATCHES_CLASS_NAME_PREFIX = "Patch"; + static ApplicationContext context; + @Autowired + StandaloneSecurityHandler securityHandler; + + 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(); + checkIfJavaPatchesExecuting(beanClass); + return context.getBean(beanClass); + } + + public static String getMessage(String messagekey, HttpServletRequest request) { + ServletContext servletContext = request.getSession().getServletContext(); + ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(servletContext); + Object[] args = new Object[] {}; + String messageValue = ctx.getMessage(messagekey, args, Locale.getDefault()); + return messageValue; + } + + 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); + } + + private static void checkIfJavaPatchesExecuting(Class beanClass) { + if (beanClass != null) { + final String className = beanClass.getSimpleName(); + if (StringUtils.isNotEmpty(className)) { + if (className.startsWith(JAVA_PATCHES_CLASS_NAME_PREFIX)) { + UserSessionBase userSessBase = new UserSessionBase(); + userSessBase.setUserAdmin(true); + userSessBase.setAuditUserAdmin(true); + userSessBase.setKeyAdmin(true); + userSessBase.setAuditKeyAdmin(true); + RangerSecurityContext rangerSecCtx = new RangerSecurityContext(); + rangerSecCtx.setUserSession(userSessBase); + RangerContextHolder.setSecurityContext(rangerSecCtx); + } + } + } + } } diff --git a/security-admin/src/main/java/org/apache/ranger/util/Pbkdf2PasswordEncoderCust.java b/security-admin/src/main/java/org/apache/ranger/util/Pbkdf2PasswordEncoderCust.java index 813ae87179..d50a541b89 100644 --- a/security-admin/src/main/java/org/apache/ranger/util/Pbkdf2PasswordEncoderCust.java +++ b/security-admin/src/main/java/org/apache/ranger/util/Pbkdf2PasswordEncoderCust.java @@ -36,15 +36,14 @@ import java.util.Arrays; public class Pbkdf2PasswordEncoderCust implements PasswordEncoder { - private static final int DEFAULT_HASH_WIDTH = 256; - private static final int DEFAULT_ITERATIONS = 185000; - - private final BytesKeyGenerator saltGenerator; - private String algorithm; - private final byte[] secret; - private final int hashWidth; - private final int iterations; - private boolean encodeHashAsBase64; + private static final int DEFAULT_HASH_WIDTH = 256; + private static final int DEFAULT_ITERATIONS = 185000; + private final BytesKeyGenerator saltGenerator; + private final byte[] secret; + private final int hashWidth; + private final int iterations; + private String algorithm; + private boolean encodeHashAsBase64; public Pbkdf2PasswordEncoderCust(CharSequence secret) { this(secret, DEFAULT_ITERATIONS, DEFAULT_HASH_WIDTH); @@ -78,10 +77,16 @@ public void setAlgorithm(Pbkdf2PasswordEncoder.SecretKeyFactoryAlgorithm secretK public String encode(CharSequence rawPassword) { byte[] salt = this.saltGenerator.generateKey(); byte[] encoded = this.encode(rawPassword, salt); - return this.encode(encoded); } + @Override + public boolean matches(CharSequence rawPassword, String encodedPassword) { + byte[] digested = this.decode(encodedPassword); + byte[] salt = EncodingUtils.subArray(digested, 0, this.saltGenerator.getKeyLength()); + return matches(digested, this.encode(rawPassword, salt)); + } + public void setEncodeHashAsBase64(boolean encodeHashAsBase64) { this.encodeHashAsBase64 = encodeHashAsBase64; } @@ -90,14 +95,6 @@ private String encode(byte[] bytes) { return this.encodeHashAsBase64 ? Utf8.decode(Base64.encode(bytes)) : String.valueOf(Hex.encode(bytes)); } - @Override - public boolean matches(CharSequence rawPassword, String encodedPassword) { - byte[] digested = this.decode(encodedPassword); - byte[] salt = EncodingUtils.subArray(digested, 0, this.saltGenerator.getKeyLength()); - - return matches(digested, this.encode(rawPassword, salt)); - } - private static boolean matches(byte[] expected, byte[] actual) { return Arrays.equals(expected, actual); } @@ -108,10 +105,9 @@ private byte[] decode(String encodedBytes) { private byte[] encode(CharSequence rawPassword, byte[] salt) { try { - PBEKeySpec spec = new PBEKeySpec(rawPassword.toString().toCharArray(), EncodingUtils.concatenate(new byte[][] {salt, this.secret}), this.iterations, this.hashWidth); + PBEKeySpec spec = new PBEKeySpec(rawPassword.toString().toCharArray(), EncodingUtils.concatenate(salt, this.secret), this.iterations, this.hashWidth); SecretKeyFactory skf = SecretKeyFactory.getInstance(this.algorithm); - - return EncodingUtils.concatenate(new byte[][] {salt, skf.generateSecret(spec).getEncoded()}); + return EncodingUtils.concatenate(salt, skf.generateSecret(spec).getEncoded()); } catch (GeneralSecurityException var5) { throw new IllegalStateException("Could not create hash", var5); } diff --git a/security-admin/src/main/java/org/apache/ranger/util/RangerAdminCache.java b/security-admin/src/main/java/org/apache/ranger/util/RangerAdminCache.java index ea98957796..0f7c3d5fc1 100644 --- a/security-admin/src/main/java/org/apache/ranger/util/RangerAdminCache.java +++ b/security-admin/src/main/java/org/apache/ranger/util/RangerAdminCache.java @@ -29,18 +29,18 @@ import org.springframework.transaction.support.TransactionTemplate; public class RangerAdminCache extends RangerCache { - private static final Logger LOG = LoggerFactory.getLogger(RangerDBValueLoader.class); + private static final Logger LOG = LoggerFactory.getLogger(RangerDBValueLoader.class); - public static final int DEFAULT_ADMIN_CACHE_LOADER_THREADS_COUNT = 1; - public static final RefreshMode DEFAULT_ADMIN_CACHE_REFRESH_MODE = RefreshMode.ON_ACCESS; - public static final long DEFAULT_ADMIN_CACHE_VALUE_VALIDITY_PERIOD_MS = 0; // every access should look to refresh - public static final long DEFAULT_ADMIN_CACHE_VALUE_INIT_TIMEOUT_MS = -1L; // infinite timeout - public static final long DEFAULT_ADMIN_CACHE_VALUE_REFRESH_TIMEOUT_MS = 10 * 1000L; // 10 seconds + public static final int DEFAULT_ADMIN_CACHE_LOADER_THREADS_COUNT = 1; + public static final RefreshMode DEFAULT_ADMIN_CACHE_REFRESH_MODE = RefreshMode.ON_ACCESS; + public static final long DEFAULT_ADMIN_CACHE_VALUE_VALIDITY_PERIOD_MS = 0; // every access should look to refresh + public static final long DEFAULT_ADMIN_CACHE_VALUE_INIT_TIMEOUT_MS = -1L; // infinite timeout + public static final long DEFAULT_ADMIN_CACHE_VALUE_REFRESH_TIMEOUT_MS = 10 * 1000L; // 10 seconds - private static final String PROP_PREFIX = "ranger.admin.cache."; - private static final String PROP_LOADER_THREAD_POOL_SIZE = ".loader.threadpool.size"; - private static final String PROP_VALUE_INIT_TIMEOUT_MS = ".value.init.timeout.ms"; - private static final String PROP_VALUE_REFRESH_TIMEOUT_MS = ".value.refresh.timeout.ms"; + private static final String PROP_PREFIX = "ranger.admin.cache."; + private static final String PROP_LOADER_THREAD_POOL_SIZE = ".loader.threadpool.size"; + private static final String PROP_VALUE_INIT_TIMEOUT_MS = ".value.init.timeout.ms"; + private static final String PROP_VALUE_REFRESH_TIMEOUT_MS = ".value.refresh.timeout.ms"; protected RangerAdminCache(String name, RangerDBValueLoader loader) { this(name, loader, getLoaderThreadPoolSize(name), DEFAULT_ADMIN_CACHE_REFRESH_MODE, DEFAULT_ADMIN_CACHE_VALUE_VALIDITY_PERIOD_MS, getValueInitLoadTimeout(name), getValueRefreshLoadTimeout(name)); @@ -55,6 +55,18 @@ public V get(K key) { return super.get(key, RangerContextHolder.getSecurityContext()); } + private static int getLoaderThreadPoolSize(String cacheName) { + return RangerAdminConfig.getInstance().getInt(PROP_PREFIX + cacheName + PROP_LOADER_THREAD_POOL_SIZE, DEFAULT_ADMIN_CACHE_LOADER_THREADS_COUNT); + } + + private static long getValueInitLoadTimeout(String cacheName) { + return RangerAdminConfig.getInstance().getLong(PROP_PREFIX + cacheName + PROP_VALUE_INIT_TIMEOUT_MS, DEFAULT_ADMIN_CACHE_VALUE_INIT_TIMEOUT_MS); + } + + private static long getValueRefreshLoadTimeout(String cacheName) { + return RangerAdminConfig.getInstance().getLong(PROP_PREFIX + cacheName + PROP_VALUE_REFRESH_TIMEOUT_MS, DEFAULT_ADMIN_CACHE_VALUE_REFRESH_TIMEOUT_MS); + } + public abstract static class RangerDBValueLoader extends ValueLoader { private final TransactionTemplate txTemplate; @@ -101,16 +113,4 @@ public final RefreshableValue load(K key, RefreshableValue currentValue, O protected abstract RefreshableValue dbLoad(K key, RefreshableValue currentValue) throws Exception; } - - private static int getLoaderThreadPoolSize(String cacheName) { - return RangerAdminConfig.getInstance().getInt(PROP_PREFIX + cacheName + PROP_LOADER_THREAD_POOL_SIZE, DEFAULT_ADMIN_CACHE_LOADER_THREADS_COUNT); - } - - private static long getValueInitLoadTimeout(String cacheName) { - return RangerAdminConfig.getInstance().getLong(PROP_PREFIX + cacheName + PROP_VALUE_INIT_TIMEOUT_MS, DEFAULT_ADMIN_CACHE_VALUE_INIT_TIMEOUT_MS); - } - - private static long getValueRefreshLoadTimeout(String cacheName) { - return RangerAdminConfig.getInstance().getLong(PROP_PREFIX + cacheName + PROP_VALUE_REFRESH_TIMEOUT_MS, DEFAULT_ADMIN_CACHE_VALUE_REFRESH_TIMEOUT_MS); - } } diff --git a/security-admin/src/main/java/org/apache/ranger/util/RangerEnumUtil.java b/security-admin/src/main/java/org/apache/ranger/util/RangerEnumUtil.java index 0ca1f769b7..ee09e0bc70 100644 --- a/security-admin/src/main/java/org/apache/ranger/util/RangerEnumUtil.java +++ b/security-admin/src/main/java/org/apache/ranger/util/RangerEnumUtil.java @@ -19,6 +19,10 @@ package org.apache.ranger.util; +/** + * + */ + import org.apache.ranger.common.view.VEnum; import org.apache.ranger.common.view.VEnumElement; import org.slf4j.Logger; @@ -32,1994 +36,1990 @@ @Component public class RangerEnumUtil { - private static final Logger logger = LoggerFactory.getLogger(RangerEnumUtil.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 Map enumMap = new HashMap(); - protected List enumList = new ArrayList(); + public static final String ENUM_CommonEnums_ActiveStatus = "CommonEnums.ActiveStatus"; + public static final String ENUM_CommonEnums_ActivationStatus = "CommonEnums.ActivationStatus"; + public static final String ENUM_CommonEnums_BooleanValue = "CommonEnums.BooleanValue"; + public static final String ENUM_CommonEnums_DataType = "CommonEnums.DataType"; + public static final String ENUM_CommonEnums_DeviceType = "CommonEnums.DeviceType"; + public static final String ENUM_CommonEnums_DiffLevel = "CommonEnums.DiffLevel"; + public static final String ENUM_CommonEnums_FileType = "CommonEnums.FileType"; + public static final String ENUM_CommonEnums_FreqType = "CommonEnums.FreqType"; + public static final String ENUM_CommonEnums_MimeType = "CommonEnums.MimeType"; + public static final String ENUM_CommonEnums_NumberFormat = "CommonEnums.NumberFormat"; + public static final String ENUM_CommonEnums_ObjectStatus = "CommonEnums.ObjectStatus"; + public static final String ENUM_CommonEnums_PasswordResetStatus = "CommonEnums.PasswordResetStatus"; + public static final String ENUM_CommonEnums_PriorityType = "CommonEnums.PriorityType"; + public static final String ENUM_CommonEnums_ProgressStatus = "CommonEnums.ProgressStatus"; + public static final String ENUM_CommonEnums_RelationType = "CommonEnums.RelationType"; + public static final String ENUM_CommonEnums_UserSource = "CommonEnums.UserSource"; + public static final String ENUM_CommonEnums_AssetType = "CommonEnums.AssetType"; + public static final String ENUM_CommonEnums_AccessResult = "CommonEnums.AccessResult"; + public static final String ENUM_CommonEnums_PolicyType = "CommonEnums.PolicyType"; + public static final String ENUM_CommonEnums_XAAuditType = "CommonEnums.XAAuditType"; + public static final String ENUM_CommonEnums_ResourceType = "CommonEnums.ResourceType"; + public static final String ENUM_CommonEnums_XAGroupType = "CommonEnums.XAGroupType"; + public static final String ENUM_CommonEnums_XAPermForType = "CommonEnums.XAPermForType"; + public static final String ENUM_CommonEnums_XAPermType = "CommonEnums.XAPermType"; + public static final String ENUM_CommonEnums_ClassTypes = "CommonEnums.ClassTypes"; + public static final String ENUM_XXAuthSession_AuthStatus = "XXAuthSession.AuthStatus"; + public static final String ENUM_XXAuthSession_AuthType = "XXAuthSession.AuthType"; + public static final String ENUM_XResponse_ResponseStatus = "XResponse.ResponseStatus"; + private static final Logger logger = LoggerFactory.getLogger(RangerEnumUtil.class); + protected Map enumMap = new HashMap(); + protected List enumList = new ArrayList(); public List getEnums() { - if (enumList.isEmpty()) { - init(); - } - return enumList; + if (enumList.isEmpty()) { + init(); + } + return enumList; } public VEnum getEnum(String enumName) { - if (enumList.isEmpty()) { - init(); - } - return enumMap.get(enumName); + if (enumList.isEmpty()) { + init(); + } + return enumMap.get(enumName); } public String getLabel(String enumName, int enumValue) { - VEnum vEnum = getEnum(enumName); - if (vEnum == null) { - logger.error("Enum not found. enum={}", enumName, new Throwable()); - return ""; - } - for (VEnumElement vEnumElement : vEnum.getElementList()) { - if (vEnumElement.getElementValue() == enumValue) { - return vEnumElement.getElementLabel(); - } - } - logger.error("Enum value not found. enum={}, value={}", enumName, enumValue, new Throwable()); - return ""; + VEnum vEnum = getEnum(enumName); + if (vEnum == null) { + logger.error("Enum {} not found.", enumName, new Throwable()); + return ""; + } + for (VEnumElement vEnumElement : vEnum.getElementList()) { + if (vEnumElement.getElementValue() == enumValue) { + return vEnumElement.getElementLabel(); + } + } + logger.error("Enum value not found. enum={}, value={}", enumName, enumValue, new Throwable()); + return ""; } - public int getValue(String enumName, String elementName) { - VEnum vEnum = getEnum(enumName); - if (vEnum == null) { - logger.error("Enum not found. enum={}", enumName, new Throwable()); - return -1; - } - for (VEnumElement vEnumElement : vEnum.getElementList()) { - if (vEnumElement.getElementName().equalsIgnoreCase(elementName)) { - return vEnumElement.getElementValue(); - } - } - logger.error("Enum value not found. enum={}, elementName={}", enumName, elementName, new Throwable()); - return -1; - } + public int getValue(String enumName, String elementName) { + VEnum vEnum = getEnum(enumName); + if (vEnum == null) { + logger.error("Enum {} not found.", enumName, new Throwable()); + return -1; + } + for (VEnumElement vEnumElement : vEnum.getElementList()) { + if (vEnumElement.getElementName().equalsIgnoreCase(elementName)) { + return vEnumElement.getElementValue(); + } + } + logger.error("Enum value not found. enum={}, elementName={}", enumName, 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()); - 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()); - 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()); - 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()); - 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()); - 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()); - 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()); - 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()); - 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()); - 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()); - 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()); - 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()); - 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()); - 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()); - 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()); - 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()); - 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()); - 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()); - 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()); - 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()); - 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()); - 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); - - vElement = new VEnumElement(); - vElement.setElementName("RESOURCE_GLOBAL"); - vElement.setElementValue(11); - vElement.setElementLabel("Global"); - vElement.setRbKey("xa.enum.ResourceType.RESOURCE_GLOBAL"); - vElement.setEnumName(vEnum.getEnumName()); - - vEnum.getElementList().add(vElement); - - /////////////////////////////////// - // CommonEnums::XAGroupType - /////////////////////////////////// - vEnum = new VEnum(); - vEnum.setEnumName(ENUM_CommonEnums_XAGroupType); - vEnum.setElementList(new ArrayList()); - 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()); - 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()); - 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()); - 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()); - 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()); - 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); - - vElement = new VEnumElement(); - vElement.setElementName("AUTH_TYPE_KERBEROS"); - vElement.setElementValue(2); - vElement.setElementLabel("Kerberos"); - vElement.setRbKey("xa.enum.AuthType.AUTH_TYPE_KERBEROS"); - vElement.setEnumName(vEnum.getEnumName()); - - vEnum.getElementList().add(vElement); - - vElement = new VEnumElement(); - vElement.setElementName("AUTH_TYPE_SSO"); - vElement.setElementValue(3); - vElement.setElementLabel("SingleSignOn"); - vElement.setRbKey("xa.enum.AuthType.AUTH_TYPE_SSO"); - vElement.setEnumName(vEnum.getEnumName()); - - vEnum.getElementList().add(vElement); - - vElement = new VEnumElement(); - vElement.setElementName("AUTH_TYPE_TRUSTED_PROXY"); - vElement.setElementValue(4); - vElement.setElementLabel("Trusted Proxy"); - vElement.setRbKey("xa.enum.AuthType.AUTH_TYPE_TRUSTED_PROXY"); - vElement.setEnumName(vEnum.getEnumName()); - - vEnum.getElementList().add(vElement); - - /////////////////////////////////// - // XResponse::ResponseStatus - /////////////////////////////////// - vEnum = new VEnum(); - vEnum.setEnumName(ENUM_XResponse_ResponseStatus); - vEnum.setElementList(new ArrayList()); - 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); + VEnum vEnum; + VEnumElement vElement; + + /////////////////////////////////// + // CommonEnums::ActiveStatus + /////////////////////////////////// + vEnum = new VEnum(); + vEnum.setEnumName(ENUM_CommonEnums_ActiveStatus); + vEnum.setElementList(new ArrayList()); + 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()); + 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()); + 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()); + 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()); + 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()); + 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()); + 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()); + 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()); + 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()); + 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()); + 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()); + 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()); + 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()); + 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()); + 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()); + 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()); + 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()); + 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()); + 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()); + 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()); + 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); + + vElement = new VEnumElement(); + vElement.setElementName("RESOURCE_GLOBAL"); + vElement.setElementValue(11); + vElement.setElementLabel("Global"); + vElement.setRbKey("xa.enum.ResourceType.RESOURCE_GLOBAL"); + vElement.setEnumName(vEnum.getEnumName()); + + vEnum.getElementList().add(vElement); + /////////////////////////////////// + // CommonEnums::XAGroupType + /////////////////////////////////// + vEnum = new VEnum(); + vEnum.setEnumName(ENUM_CommonEnums_XAGroupType); + vEnum.setElementList(new ArrayList()); + 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()); + 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()); + 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()); + 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()); + 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()); + 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); + + vElement = new VEnumElement(); + vElement.setElementName("AUTH_TYPE_KERBEROS"); + vElement.setElementValue(2); + vElement.setElementLabel("Kerberos"); + vElement.setRbKey("xa.enum.AuthType.AUTH_TYPE_KERBEROS"); + vElement.setEnumName(vEnum.getEnumName()); + + vEnum.getElementList().add(vElement); + + vElement = new VEnumElement(); + vElement.setElementName("AUTH_TYPE_SSO"); + vElement.setElementValue(3); + vElement.setElementLabel("SingleSignOn"); + vElement.setRbKey("xa.enum.AuthType.AUTH_TYPE_SSO"); + vElement.setEnumName(vEnum.getEnumName()); + + vEnum.getElementList().add(vElement); + + vElement = new VEnumElement(); + vElement.setElementName("AUTH_TYPE_TRUSTED_PROXY"); + vElement.setElementValue(4); + vElement.setElementLabel("Trusted Proxy"); + vElement.setRbKey("xa.enum.AuthType.AUTH_TYPE_TRUSTED_PROXY"); + vElement.setEnumName(vEnum.getEnumName()); + + vEnum.getElementList().add(vElement); + + /////////////////////////////////// + // XResponse::ResponseStatus + /////////////////////////////////// + vEnum = new VEnum(); + vEnum.setEnumName(ENUM_XResponse_ResponseStatus); + vEnum.setElementList(new ArrayList()); + 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); } } diff --git a/security-admin/src/main/java/org/apache/ranger/util/RangerMetricsUtil.java b/security-admin/src/main/java/org/apache/ranger/util/RangerMetricsUtil.java index 56cb35c247..a6788bf094 100644 --- a/security-admin/src/main/java/org/apache/ranger/util/RangerMetricsUtil.java +++ b/security-admin/src/main/java/org/apache/ranger/util/RangerMetricsUtil.java @@ -39,26 +39,19 @@ */ @Component public class RangerMetricsUtil { - private static final Logger LOG = LoggerFactory.getLogger(RangerMetricsUtil.class); - + private static final Logger LOG = LoggerFactory.getLogger(RangerMetricsUtil.class); private static final OperatingSystemMXBean OS; private static final MemoryMXBean MEM_BEAN; - static { - OS = ManagementFactory.getOperatingSystemMXBean(); - MEM_BEAN = ManagementFactory.getMemoryMXBean(); - } - public Map getValues() { LOG.debug("==> RangerMetricsUtil.getValues()"); Map values = new LinkedHashMap<>(); - values.put("os.spec", StringUtils.join(Arrays.asList(addSystemInfo()), ", ")); values.put("os.vcpus", String.valueOf(OS.getAvailableProcessors())); values.put("memory", addMemoryDetails()); - LOG.debug("<== RangerMetricsUtil.getValues() {}", values); + LOG.debug("<== RangerMetricsUtil.getValues():{}", values); return values; } @@ -70,14 +63,13 @@ protected Map getPoolDivision() { LOG.debug("==> RangerMetricsUtil.getPoolDivision()"); Map poolDivisionValues = new LinkedHashMap<>(); - for (MemoryPoolMXBean mpBean : ManagementFactory.getMemoryPoolMXBeans()) { if (mpBean.getType() == MemoryType.HEAP) { poolDivisionValues.put(mpBean.getName(), mpBean.getUsage()); } } - LOG.debug("<== RangerMetricsUtil.getPoolDivision() {}", poolDivisionValues); + LOG.debug("<== RangerMetricsUtil.getPoolDivision(){}", poolDivisionValues); return poolDivisionValues; } @@ -91,7 +83,6 @@ protected Map addMemoryDetails() { Map memory = new LinkedHashMap<>(); MemoryUsage memHeapUsage = MEM_BEAN.getHeapMemoryUsage(); MemoryUsage nonHeapUsage = MEM_BEAN.getNonHeapMemoryUsage(); - memory.put("heapInit", String.valueOf(memHeapUsage.getInit())); memory.put("heapMax", String.valueOf(memHeapUsage.getMax())); memory.put("heapCommitted", String.valueOf(memHeapUsage.getCommitted())); @@ -102,7 +93,7 @@ protected Map addMemoryDetails() { memory.put("nonHeapUsed", String.valueOf(nonHeapUsage.getUsed())); memory.put("memory_pool_usages", getPoolDivision()); - LOG.debug("<== RangerMetricsUtil.addMemoryDetails() {}", memory); + LOG.debug("<== RangerMetricsUtil.addMemoryDetails(){}", memory); return memory; } @@ -114,9 +105,13 @@ protected String[] addSystemInfo() { LOG.debug("==> RangerMetricsUtil.addSystemInfo()"); String[] osInfo = {OS.getName(), OS.getArch(), OS.getVersion()}; - - LOG.debug("<== RangerMetricsUtil.addSystemInfo() {}", osInfo); + LOG.debug("<== RangerMetricsUtil.addSystemInfo(){}", osInfo); return osInfo; } + + static { + OS = ManagementFactory.getOperatingSystemMXBean(); + MEM_BEAN = ManagementFactory.getMemoryMXBean(); + } } diff --git a/security-admin/src/main/java/org/apache/ranger/util/RangerRestUtil.java b/security-admin/src/main/java/org/apache/ranger/util/RangerRestUtil.java index 7316f2177b..6e4389a2e0 100644 --- a/security-admin/src/main/java/org/apache/ranger/util/RangerRestUtil.java +++ b/security-admin/src/main/java/org/apache/ranger/util/RangerRestUtil.java @@ -39,81 +39,70 @@ @Component public class RangerRestUtil { - private static final Logger logger = LoggerFactory.getLogger(RangerRestUtil.class); - - @Autowired - StringUtil stringUtil; - - @Autowired - RESTErrorUtil restErrorUtil; - - @Autowired - RangerConfigUtil configUtil; - - void splitUserRoleList(Collection collection) { - Collection newCollection = new ArrayList(); - for (String role : collection) { - String[] roles = role.split(","); - newCollection.addAll(Arrays.asList(roles)); - } - 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 messageList = new ArrayList(); - // 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")); - - // firstName - if (!stringUtil.isValidName(userProfile.getFirstName())) { - logger.info("Invalid first name. {}", userProfile); - messageList.add(MessageEnums.INVALID_INPUT_DATA.getMessage(null, "firstName")); - } - - // 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.isEmpty()) { - VXResponse gjResponse = new VXResponse(); - gjResponse.setStatusCode(VXResponse.STATUS_ERROR); - gjResponse.setMsgDesc("Validation failure"); - gjResponse.setMessageList(messageList); - logger.info("Validation Error in updateUser() userProfile={}, error={}", userProfile, gjResponse); - throw restErrorUtil.createRESTException(gjResponse); - } - } + private static final Logger logger = LoggerFactory.getLogger(RangerRestUtil.class); + + @Autowired + StringUtil stringUtil; + + @Autowired + RESTErrorUtil restErrorUtil; + + @Autowired + RangerConfigUtil configUtil; + + /** + * This method cleans up the data provided by the user for update + * + * @param userProfile + * @return + */ + public void validateVUserProfileForUpdate(XXPortalUser gjUser, VXPortalUser userProfile) { + List messageList = new ArrayList(); + + // 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")); + + // firstName + if (!stringUtil.isValidName(userProfile.getFirstName())) { + logger.info("Invalid first name.{}", userProfile); + messageList.add(MessageEnums.INVALID_INPUT_DATA.getMessage(null, "firstName")); + } + + // 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.isEmpty()) { + VXResponse gjResponse = new VXResponse(); + gjResponse.setStatusCode(VXResponse.STATUS_ERROR); + gjResponse.setMsgDesc("Validation failure"); + gjResponse.setMessageList(messageList); + logger.info("Validation Error in updateUser() userProfile= {}, error= {}", userProfile, gjResponse); + throw restErrorUtil.createRESTException(gjResponse); + } + } + + void splitUserRoleList(Collection collection) { + Collection newCollection = new ArrayList(); + for (String role : collection) { + String[] roles = role.split(","); + newCollection.addAll(Arrays.asList(roles)); + } + collection.clear(); + collection.addAll(newCollection); + } } diff --git a/security-admin/src/main/java/org/apache/ranger/util/RangerServerHealthUtil.java b/security-admin/src/main/java/org/apache/ranger/util/RangerServerHealthUtil.java index ba2a23fc7c..4f3cb9a65d 100644 --- a/security-admin/src/main/java/org/apache/ranger/util/RangerServerHealthUtil.java +++ b/security-admin/src/main/java/org/apache/ranger/util/RangerServerHealthUtil.java @@ -60,7 +60,7 @@ In the future this health check API can be extended for other components like au "audit-Elasticsearch": { "status": "UP", "details": { "provider": "Elastic Search", "providerHealthCheckEndpoint": "http://localhost:9200/_cluster/health?pretty" } } } } - */ + */ public RangerServerHealth getRangerServerHealth(String dbVersion) { Map components = new HashMap<>(); @@ -81,8 +81,8 @@ public RangerServerHealth getRangerServerHealth(String dbVersion) { private Map getDbStatus(String dbVersion) { Map ret = new LinkedHashMap<>(); - Map details = new LinkedHashMap<>(); int dbFlavor = RangerBizUtil.getDBFlavor(); + Map details = new LinkedHashMap<>(); details.put(DB_FLAVOR, RangerBizUtil.getDBFlavorType(dbFlavor)); details.put(DB_VERSION, dbVersion); diff --git a/security-admin/src/main/java/org/apache/ranger/util/RestUtil.java b/security-admin/src/main/java/org/apache/ranger/util/RestUtil.java index cf91a09784..d73a2f10b6 100644 --- a/security-admin/src/main/java/org/apache/ranger/util/RestUtil.java +++ b/security-admin/src/main/java/org/apache/ranger/util/RestUtil.java @@ -16,7 +16,6 @@ * specific language governing permissions and limitations * under the License. */ - package org.apache.ranger.util; import org.apache.commons.lang.StringUtils; @@ -37,166 +36,146 @@ @Component public class RestUtil { - private static final Logger LOG = LoggerFactory.getLogger(RestUtil.class); - - private static final String PROXY_RANGER_URL_PATH = "/ranger"; - - public static final String timeOffsetCookieName = "clientTimeOffset"; - public static final String TIMEOUT_ACTION = "timeout"; - public static final String LOCAL_LOGIN_URL = "locallogin"; - public static final String ZONED_EVENT_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss z"; - - 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 (timeOffsetCookieName.equals(cookie.getName())) { - timeOffset = cookie.getValue(); - - if (timeOffset != null) { - cookieVal = Integer.parseInt(timeOffset); - } - break; - } - } catch (Exception ex) { - cookieVal = 0; - } - } - } - } catch (Exception ex) { - // ignored - } - - return cookieVal; - } - - public static int getClientTimeOffset() { - int clientTimeOffsetInMinute = 0; - - try { - clientTimeOffsetInMinute = RangerContextHolder.getSecurityContext().getRequestContext().getClientTimeOffsetInMinute(); - } catch (Exception ex) { - // ignored - } - - if (clientTimeOffsetInMinute == 0) { - try { - clientTimeOffsetInMinute = RangerContextHolder.getSecurityContext().getUserSession().getClientTimeOffsetInMinute(); - } catch (Exception ex) { - // ignored - } - } - - return clientTimeOffsetInMinute; - } - - public static String constructForwardableURL(HttpServletRequest httpRequest) { - String xForwardedProto = ""; - String xForwardedHost = ""; - String xForwardedContext = ""; - Enumeration names = httpRequest.getHeaderNames(); - - while (names.hasMoreElements()) { - String name = (String) names.nextElement(); - Enumeration values = httpRequest.getHeaders(name); - String value = ""; - - if (values != null) { - while (values.hasMoreElements()) { - value = (String) values.nextElement(); - } - } - - if (StringUtils.trimToNull(name) != null && StringUtils.trimToNull(value) != null) { - if (name.equalsIgnoreCase("x-forwarded-proto")) { - xForwardedProto = value; - } else if (name.equalsIgnoreCase("x-forwarded-host")) { - xForwardedHost = value; - } else if (name.equalsIgnoreCase("x-forwarded-context")) { - xForwardedContext = value; - } - } - } - - if (xForwardedHost.contains(",")) { - LOG.debug("xForwardedHost value is {}, it contains multiple hosts, selecting the first host.", xForwardedHost); - - xForwardedHost = xForwardedHost.split(",")[0].trim(); - } - - String xForwardedURL = ""; - - if (StringUtils.trimToNull(xForwardedProto) != null) { - //if header contains x-forwarded-host and x-forwarded-context - if (StringUtils.trimToNull(xForwardedHost) != null && StringUtils.trimToNull(xForwardedContext) != null) { - xForwardedURL = xForwardedProto + "://" + xForwardedHost + xForwardedContext + PROXY_RANGER_URL_PATH + httpRequest.getRequestURI(); - } else if (StringUtils.trimToNull(xForwardedHost) != null) { - //if header contains x-forwarded-host and does not contains x-forwarded-context - xForwardedURL = xForwardedProto + "://" + xForwardedHost + httpRequest.getRequestURI(); - } else { - //if header does not contains x-forwarded-host and x-forwarded-context - //preserve the x-forwarded-proto value coming from the request. - String requestURL = httpRequest.getRequestURL().toString(); - - if (StringUtils.trimToNull(requestURL) != null && requestURL.startsWith("http:")) { - requestURL = requestURL.replaceFirst("http", xForwardedProto); - } - - xForwardedURL = requestURL; - } - } - - return xForwardedURL; - } - - public static String constructRedirectURL(HttpServletRequest request, String redirectUrl, String xForwardedURL, String originalUrlQueryParam) { - String delimiter = "?"; - - if (redirectUrl.contains("?")) { - delimiter = "&"; - } - - String loginURL = redirectUrl + delimiter + originalUrlQueryParam + "="; - - if (StringUtils.trimToNull(xForwardedURL) != null) { - loginURL += xForwardedURL + getOriginalQueryString(request); - } else { - loginURL += request.getRequestURL().append(getOriginalQueryString(request)); - } - - return loginURL; - } - - public static String convertToTimeZone(Date date, String timeZone) { - try { - Instant utcInstant = date.toInstant(); - // Get the ZoneId from the request parameter - ZoneId zoneId = ZoneId.of(timeZone); - // Convert the UTC date to the specified timezone - ZonedDateTime zonedDateTime = utcInstant.atZone(zoneId); - - return zonedDateTime.format(DateTimeFormatter.ofPattern(ZONED_EVENT_TIME_FORMAT)); - } catch (Exception e) { - LOG.info("Exception occurred while converting to timeZone", e); - return null; - } - } - - private static String getOriginalQueryString(HttpServletRequest request) { - String originalQueryString = request.getQueryString(); - - LOG.debug("originalQueryString = {} ", originalQueryString); - - if (originalQueryString == null || originalQueryString.contains("action")) { - return ""; - } else { - return "?" + originalQueryString; - } - } + private static final Logger LOG = LoggerFactory.getLogger(RestUtil.class); + + public static final String timeOffsetCookieName = "clientTimeOffset"; + public static final String TIMEOUT_ACTION = "timeout"; + public static final String LOCAL_LOGIN_URL = "locallogin"; + public static final String ZONED_EVENT_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss z"; + + private static final String PROXY_RANGER_URL_PATH = "/ranger"; + + private RestUtil() { + //To block instantiation + } + + 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 (timeOffsetCookieName.equals(cookie.getName())) { + 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 = RangerContextHolder.getSecurityContext().getRequestContext().getClientTimeOffsetInMinute(); + } catch (Exception ex) { + } + if (clientTimeOffsetInMinute == 0) { + try { + clientTimeOffsetInMinute = RangerContextHolder.getSecurityContext().getUserSession().getClientTimeOffsetInMinute(); + } catch (Exception ex) { + } + } + return clientTimeOffsetInMinute; + } + + public static String constructForwardableURL(HttpServletRequest httpRequest) { + String xForwardedProto = ""; + String xForwardedHost = ""; + String xForwardedContext = ""; + Enumeration names = httpRequest.getHeaderNames(); + while (names.hasMoreElements()) { + String name = (String) names.nextElement(); + Enumeration values = httpRequest.getHeaders(name); + String value = ""; + if (values != null) { + while (values.hasMoreElements()) { + value = (String) values.nextElement(); + } + } + if (StringUtils.trimToNull(name) != null && StringUtils.trimToNull(value) != null) { + if (name.equalsIgnoreCase("x-forwarded-proto")) { + xForwardedProto = value; + } else if (name.equalsIgnoreCase("x-forwarded-host")) { + xForwardedHost = value; + } else if (name.equalsIgnoreCase("x-forwarded-context")) { + xForwardedContext = value; + } + } + } + if (xForwardedHost.contains(",")) { + LOG.debug("xForwardedHost value is {} it contains multiple hosts, selecting the first host.", xForwardedHost); + xForwardedHost = xForwardedHost.split(",")[0].trim(); + } + String xForwardedURL = ""; + if (StringUtils.trimToNull(xForwardedProto) != null) { + //if header contains x-forwarded-host and x-forwarded-context + if (StringUtils.trimToNull(xForwardedHost) != null && StringUtils.trimToNull(xForwardedContext) != null) { + xForwardedURL = xForwardedProto + "://" + xForwardedHost + xForwardedContext + PROXY_RANGER_URL_PATH + httpRequest.getRequestURI(); + } else if (StringUtils.trimToNull(xForwardedHost) != null) { + //if header contains x-forwarded-host and does not contains x-forwarded-context + xForwardedURL = xForwardedProto + "://" + xForwardedHost + httpRequest.getRequestURI(); + } else { + //if header does not contains x-forwarded-host and x-forwarded-context + //preserve the x-forwarded-proto value coming from the request. + String requestURL = httpRequest.getRequestURL().toString(); + if (StringUtils.trimToNull(requestURL) != null && requestURL.startsWith("http:")) { + requestURL = requestURL.replaceFirst("http", xForwardedProto); + } + xForwardedURL = requestURL; + } + } + return xForwardedURL; + } + + public static String constructRedirectURL(HttpServletRequest request, String redirectUrl, String xForwardedURL, String originalUrlQueryParam) { + String delimiter = "?"; + if (redirectUrl.contains("?")) { + delimiter = "&"; + } + String loginURL = redirectUrl + delimiter + originalUrlQueryParam + "="; + if (StringUtils.trimToNull(xForwardedURL) != null) { + loginURL += xForwardedURL + getOriginalQueryString(request); + } else { + loginURL += request.getRequestURL().append(getOriginalQueryString(request)); + } + return loginURL; + } + + public static String convertToTimeZone(Date date, String timeZone) { + try { + Instant utcInstant = date.toInstant(); + + // Get the ZoneId from the request parameter + ZoneId zoneId = ZoneId.of(timeZone); + // Convert the UTC date to the specified timezone + ZonedDateTime zonedDateTime = utcInstant.atZone(zoneId); + + return zonedDateTime.format(DateTimeFormatter.ofPattern(ZONED_EVENT_TIME_FORMAT)); + } catch (Exception e) { + LOG.info("Exception occurred while converting to timeZone", e); + return null; + } + } + + private static String getOriginalQueryString(HttpServletRequest request) { + String originalQueryString = request.getQueryString(); + LOG.debug("originalQueryString = {}", originalQueryString); + if (originalQueryString == null || originalQueryString.contains("action")) { + return ""; + } else { + return "?" + originalQueryString; + } + } } diff --git a/security-admin/src/main/resources/hadoop-metrics2.properties b/security-admin/src/main/resources/hadoop-metrics2.properties index 8e8eb9ae88..7379328e37 100644 --- a/security-admin/src/main/resources/hadoop-metrics2.properties +++ b/security-admin/src/main/resources/hadoop-metrics2.properties @@ -51,4 +51,3 @@ #raz.sink.graphite_razcntx.metrics_prefix=ranger #raz.sink.graphite_razcntx.context=admin ####### Graphite Sink <<<<<< CONF - diff --git a/security-admin/src/main/resources/internationalization/messages.properties b/security-admin/src/main/resources/internationalization/messages.properties index 9bba05a021..4391227393 100644 --- a/security-admin/src/main/resources/internationalization/messages.properties +++ b/security-admin/src/main/resources/internationalization/messages.properties @@ -23,4 +23,4 @@ AbstractUserDetailsAuthenticationProvider.onlySupports=Only UsernamePasswordAuth AccountStatusUserDetailsChecker.credentialsExpired=User credentials have expired AccountStatusUserDetailsChecker.disabled=User is disabled AccountStatusUserDetailsChecker.expired=User account has expired -AccountStatusUserDetailsChecker.locked=User account is locked \ No newline at end of file +AccountStatusUserDetailsChecker.locked=User account is locked diff --git a/security-admin/src/main/resources/internationalization/messages_cs_CZ.properties b/security-admin/src/main/resources/internationalization/messages_cs_CZ.properties index bbfc0b0d46..ae12f6bb1d 100644 --- a/security-admin/src/main/resources/internationalization/messages_cs_CZ.properties +++ b/security-admin/src/main/resources/internationalization/messages_cs_CZ.properties @@ -23,4 +23,4 @@ AbstractUserDetailsAuthenticationProvider.onlySupports=Je podporov\u00E1n pouze AccountStatusUserDetailsChecker.credentialsExpired=Platnost u\u017Eivatelsk\u00E9ho hesla vypr\u0161ela AccountStatusUserDetailsChecker.disabled=U\u017Eivatelsk\u00FD \u00FA\u010Det nen\u00ED aktivn\u00ED AccountStatusUserDetailsChecker.expired=Platnost u\u017Eivatelsk\u00E9ho \u00FA\u010Dtu vypr\u0161ela -AccountStatusUserDetailsChecker.locked=U\u017Eivatelsk\u00FD \u00FA\u010Det je uzam\u010Den \ No newline at end of file +AccountStatusUserDetailsChecker.locked=U\u017Eivatelsk\u00FD \u00FA\u010Det je uzam\u010Den diff --git a/security-admin/src/main/resources/internationalization/messages_de.properties b/security-admin/src/main/resources/internationalization/messages_de.properties index 7ea7067d09..320d688959 100644 --- a/security-admin/src/main/resources/internationalization/messages_de.properties +++ b/security-admin/src/main/resources/internationalization/messages_de.properties @@ -23,4 +23,4 @@ AbstractUserDetailsAuthenticationProvider.onlySupports=Nur UsernamePasswordAuthe AccountStatusUserDetailsChecker.credentialsExpired=Die G\u00FCltigkeit der Benutzerberechtigungen ist abgelaufen AccountStatusUserDetailsChecker.disabled=Der Benutzer ist deaktiviert AccountStatusUserDetailsChecker.expired=Die G\u00FCltigkeit des Benutzerkontos ist abgelaufen -AccountStatusUserDetailsChecker.locked=Das Benutzerkonto ist gesperrt \ No newline at end of file +AccountStatusUserDetailsChecker.locked=Das Benutzerkonto ist gesperrt diff --git a/security-admin/src/main/resources/internationalization/messages_es_ES.properties b/security-admin/src/main/resources/internationalization/messages_es_ES.properties index 6e11f41a76..936adba7b0 100644 --- a/security-admin/src/main/resources/internationalization/messages_es_ES.properties +++ b/security-admin/src/main/resources/internationalization/messages_es_ES.properties @@ -23,4 +23,4 @@ AbstractUserDetailsAuthenticationProvider.onlySupports=S\u00F3lo UsernamePasswor AccountStatusUserDetailsChecker.credentialsExpired=Las credenciales del usuario han expirado AccountStatusUserDetailsChecker.disabled=El usuario est\u00E1 deshabilitado AccountStatusUserDetailsChecker.expired=La cuenta del usuario ha expirado -AccountStatusUserDetailsChecker.locked=La cuenta del usuario est\u00E1 bloqueada \ No newline at end of file +AccountStatusUserDetailsChecker.locked=La cuenta del usuario est\u00E1 bloqueada diff --git a/security-admin/src/main/resources/internationalization/messages_fr.properties b/security-admin/src/main/resources/internationalization/messages_fr.properties index 014d79b7c7..dc50bc14a8 100644 --- a/security-admin/src/main/resources/internationalization/messages_fr.properties +++ b/security-admin/src/main/resources/internationalization/messages_fr.properties @@ -23,4 +23,4 @@ AbstractUserDetailsAuthenticationProvider.onlySupports=Seul UsernamePasswordAuth AccountStatusUserDetailsChecker.credentialsExpired=Les cr\u00E9ances de l'utilisateur ont expir\u00E9 AccountStatusUserDetailsChecker.disabled=Le compte utilisateur est d\u00E9sactiv\u00E9 AccountStatusUserDetailsChecker.expired=Le compte utilisateur a expir\u00E9 -AccountStatusUserDetailsChecker.locked=Le compte utilisateur est bloqu\u00E9 \ No newline at end of file +AccountStatusUserDetailsChecker.locked=Le compte utilisateur est bloqu\u00E9 diff --git a/security-admin/src/main/resources/internationalization/messages_it.properties b/security-admin/src/main/resources/internationalization/messages_it.properties index 14520470ee..30c725ae2f 100644 --- a/security-admin/src/main/resources/internationalization/messages_it.properties +++ b/security-admin/src/main/resources/internationalization/messages_it.properties @@ -23,4 +23,4 @@ AbstractUserDetailsAuthenticationProvider.onlySupports=Solo UsernamePasswordAuth AccountStatusUserDetailsChecker.credentialsExpired=Credenziali dell'utente scadute AccountStatusUserDetailsChecker.disabled=Utente disabilitato AccountStatusUserDetailsChecker.expired=Account dell'utente scaduto -AccountStatusUserDetailsChecker.locked=Account dell'utente bloccato \ No newline at end of file +AccountStatusUserDetailsChecker.locked=Account dell'utente bloccato diff --git a/security-admin/src/main/resources/internationalization/messages_ko_KR.properties b/security-admin/src/main/resources/internationalization/messages_ko_KR.properties index 30de2cf42a..e8d92a548d 100644 --- a/security-admin/src/main/resources/internationalization/messages_ko_KR.properties +++ b/security-admin/src/main/resources/internationalization/messages_ko_KR.properties @@ -23,4 +23,4 @@ AccountStatusUserDetailsChecker.credentialsExpired=\uBE44\uBC00\uBC88\uD638\uC75 AccountStatusUserDetailsChecker.disabled=\uC0AC\uC6A9\uC790 \uACC4\uC815\uC744 \uC0AC\uC6A9\uD560 \uC218 \uC5C6\uC2B5\uB2C8\uB2E4. AccountStatusUserDetailsChecker.expired=\uC0AC\uC6A9\uC790 \uACC4\uC815\uC758 \uC720\uD6A8 \uAE30\uAC04\uC774 \uB9CC\uB8CC \uB418\uC5C8\uC2B5\uB2C8\uB2E4. AccountStatusUserDetailsChecker.locked=\uC0AC\uC6A9\uC790 \uACC4\uC815\uC774 \uC7A0\uACA8 \uC788\uC2B5\uB2C8\uB2E4. -AclEntryAfterInvocationProvider.noPermission=Authentication {0}\uC740/\uB294 domain object {1}\uC5D0 \uB300\uD55C \uAD8C\uD55C\uC774 \uC5C6\uC2B5\uB2C8\uB2E4. \ No newline at end of file +AclEntryAfterInvocationProvider.noPermission=Authentication {0}\uC740/\uB294 domain object {1}\uC5D0 \uB300\uD55C \uAD8C\uD55C\uC774 \uC5C6\uC2B5\uB2C8\uB2E4. diff --git a/security-admin/src/main/resources/internationalization/messages_lt.properties b/security-admin/src/main/resources/internationalization/messages_lt.properties index ef874672a3..2d37c57970 100644 --- a/security-admin/src/main/resources/internationalization/messages_lt.properties +++ b/security-admin/src/main/resources/internationalization/messages_lt.properties @@ -23,4 +23,4 @@ AbstractUserDetailsAuthenticationProvider.onlySupports=Priimamas tik UsernamePas AccountStatusUserDetailsChecker.credentialsExpired=Pasibaig\u0117 vartotojo kredencial\u0173 galiojimas AccountStatusUserDetailsChecker.disabled=Vartotojas neveiksnus AccountStatusUserDetailsChecker.expired=Pasibaig\u0117 vartotojo paskyros galiojimas -AccountStatusUserDetailsChecker.locked=Vartotojo paskyra u\u017erakinta \ No newline at end of file +AccountStatusUserDetailsChecker.locked=Vartotojo paskyra u\u017erakinta diff --git a/security-admin/src/main/resources/internationalization/messages_pl.properties b/security-admin/src/main/resources/internationalization/messages_pl.properties index 911f28c52c..b589d0d98c 100644 --- a/security-admin/src/main/resources/internationalization/messages_pl.properties +++ b/security-admin/src/main/resources/internationalization/messages_pl.properties @@ -23,4 +23,4 @@ AbstractUserDetailsAuthenticationProvider.onlySupports=Tylko UsernamePasswordAut AccountStatusUserDetailsChecker.credentialsExpired=Wa\u017Cno\u015B\u0107 danych uwierzytelniaj\u0105cych wygas\u0142a AccountStatusUserDetailsChecker.disabled=Konto u\u017Cytkownika jest wy\u0142\u0105czone AccountStatusUserDetailsChecker.expired=Wa\u017Cno\u015B\u0107 konta u\u017Cytkownika wygas\u0142a -AccountStatusUserDetailsChecker.locked=Konto u\u017Cytkownika jest zablokowane \ No newline at end of file +AccountStatusUserDetailsChecker.locked=Konto u\u017Cytkownika jest zablokowane diff --git a/security-admin/src/main/resources/internationalization/messages_pt_BR.properties b/security-admin/src/main/resources/internationalization/messages_pt_BR.properties index bee41df593..56d1051d6a 100644 --- a/security-admin/src/main/resources/internationalization/messages_pt_BR.properties +++ b/security-admin/src/main/resources/internationalization/messages_pt_BR.properties @@ -23,4 +23,4 @@ AbstractUserDetailsAuthenticationProvider.onlySupports=Somente UsernamePasswordA AccountStatusUserDetailsChecker.credentialsExpired=Credenciais expiradas AccountStatusUserDetailsChecker.disabled=Usu\u00E1rio desabilitado AccountStatusUserDetailsChecker.expired=Conta expirada -AccountStatusUserDetailsChecker.locked=Conta bloqueada \ No newline at end of file +AccountStatusUserDetailsChecker.locked=Conta bloqueada diff --git a/security-admin/src/main/resources/internationalization/messages_pt_PT.properties b/security-admin/src/main/resources/internationalization/messages_pt_PT.properties index 7650ba72b3..8e984586af 100644 --- a/security-admin/src/main/resources/internationalization/messages_pt_PT.properties +++ b/security-admin/src/main/resources/internationalization/messages_pt_PT.properties @@ -23,4 +23,4 @@ AbstractUserDetailsAuthenticationProvider.onlySupports=Apenas UsernamePasswordAu AccountStatusUserDetailsChecker.credentialsExpired=As credenciais do utilizador expiraram AccountStatusUserDetailsChecker.disabled=O utilizador est\u00E1 desactivado AccountStatusUserDetailsChecker.expired=A conta de utilizador expirou -AccountStatusUserDetailsChecker.locked=A conta de utilizador est\u00E1 bloqueada \ No newline at end of file +AccountStatusUserDetailsChecker.locked=A conta de utilizador est\u00E1 bloqueada diff --git a/security-admin/src/main/resources/internationalization/messages_uk_UA.properties b/security-admin/src/main/resources/internationalization/messages_uk_UA.properties index d4a08612fd..7b07d3ef76 100644 --- a/security-admin/src/main/resources/internationalization/messages_uk_UA.properties +++ b/security-admin/src/main/resources/internationalization/messages_uk_UA.properties @@ -23,4 +23,4 @@ AbstractUserDetailsAuthenticationProvider.onlySupports=\u0422\u0456\u043B\u044C\ AccountStatusUserDetailsChecker.credentialsExpired=\u041F\u043E\u0432\u043D\u043E\u0432\u0430\u0436\u0435\u043D\u043D\u044F \u043A\u043E\u0440\u0438\u0441\u0442\u0443\u0432\u0430\u0447\u0430 \u0432\u0438\u0447\u0435\u0440\u043F\u0430\u043B\u0438 \u0442\u0435\u0440\u043C\u0456\u043D \u0434\u0456\u0457 AccountStatusUserDetailsChecker.disabled=\u041E\u0431\u043B\u0456\u043A\u043E\u0432\u0438\u0439 \u0437\u0430\u043F\u0438\u0441 \u043A\u043E\u0440\u0443\u0441\u0442\u0443\u0432\u0430\u0447\u0430 \u0437\u0430\u0431\u043E\u0440\u043E\u043D\u0435\u043D\u0438\u0439 AccountStatusUserDetailsChecker.expired=\u041E\u0431\u043B\u0456\u043A\u043E\u0432\u0438\u0439 \u0437\u0430\u043F\u0438\u0441 \u043A\u043E\u0440\u0443\u0441\u0442\u0443\u0432\u0430\u0447\u0430 \u0432\u0438\u0447\u0435\u0440\u043F\u0430\u0432 \u0442\u0435\u0440\u043C\u0456\u043D \u0434\u0456\u0457 -AccountStatusUserDetailsChecker.locked=\u041E\u0431\u043B\u0456\u043A\u043E\u0432\u0438\u0439 \u0437\u0430\u043F\u0438\u0441 \u043A\u043E\u0440\u0443\u0441\u0442\u0443\u0432\u0430\u0447\u0430 \u0437\u0430\u0431\u043B\u043E\u043A\u043E\u0432\u0430\u043D\u0438\u0439 \ No newline at end of file +AccountStatusUserDetailsChecker.locked=\u041E\u0431\u043B\u0456\u043A\u043E\u0432\u0438\u0439 \u0437\u0430\u043F\u0438\u0441 \u043A\u043E\u0440\u0443\u0441\u0442\u0443\u0432\u0430\u0447\u0430 \u0437\u0430\u0431\u043B\u043E\u043A\u043E\u0432\u0430\u043D\u0438\u0439 diff --git a/security-admin/src/main/resources/internationalization/messages_zh_CN.properties b/security-admin/src/main/resources/internationalization/messages_zh_CN.properties index b8c3e01a27..f035469b9d 100644 --- a/security-admin/src/main/resources/internationalization/messages_zh_CN.properties +++ b/security-admin/src/main/resources/internationalization/messages_zh_CN.properties @@ -23,4 +23,4 @@ AbstractUserDetailsAuthenticationProvider.onlySupports=\u4EC5\u4EC5\u652F\u6301U AccountStatusUserDetailsChecker.credentialsExpired=\u7528\u6237\u51ED\u8BC1\u5DF2\u8FC7\u671F AccountStatusUserDetailsChecker.disabled=\u7528\u6237\u5DF2\u5931\u6548 AccountStatusUserDetailsChecker.expired=\u7528\u6237\u5E10\u53F7\u5DF2\u8FC7\u671F -AccountStatusUserDetailsChecker.locked=\u7528\u6237\u5E10\u53F7\u5DF2\u88AB\u9501\u5B9A \ No newline at end of file +AccountStatusUserDetailsChecker.locked=\u7528\u6237\u5E10\u53F7\u5DF2\u88AB\u9501\u5B9A diff --git a/security-admin/src/main/resources/resourcenamemap.properties b/security-admin/src/main/resources/resourcenamemap.properties index a5497fc211..7cf4ae2ea8 100644 --- a/security-admin/src/main/resources/resourcenamemap.properties +++ b/security-admin/src/main/resources/resourcenamemap.properties @@ -21,4 +21,4 @@ lookupkeytab=xalogin.xml namerules=xalogin.xml authtype=xalogin.xml rangerprincipal=xalogin.xml -rangerkeytab=xalogin.xml \ No newline at end of file +rangerkeytab=xalogin.xml